Skip to main content

brep_kernel/io/solidworks/
mod.rs

1//! SolidWorks parts (`.sldprt`) and assemblies (`.sldasm`): import.
2//!
3//! A SolidWorks part keeps each configuration's body as a Parasolid partition
4//! in neutral binary (`Contents/Config-N-Partition`): a section of zlib
5//! chunks, then the partition's rollback deltas. The file around it is an OLE
6//! compound document (SolidWorks before 2015) or SolidWorks' own container
7//! (2015 and later: a ZIP-like archive with rotated stream names and raw
8//! DEFLATE). Import finds the partition and reads it with the Parasolid
9//! reader; nothing else in the file is needed.
10//!
11//! An assembly keeps no bodies: `swXmlContents/COMPINSTANCETREE` lists the
12//! files it uses, their models (file and configuration) and each instance
13//! (`swReference`) with its placement. `swTransform` is a row-vector matrix in
14//! metres: p' = p R + t, the rotation's rows first and the translation last
15//! (PSAS's canard machining assembly, exported by SolidWorks both as an
16//! assembly and as a Parasolid assembly, agrees so to 1e-14; read as columns
17//! it misses by 67 mm).
18//!
19//! Container notes: blussyya/sldprt-format-research (CC-BY-SA-4.0) and the
20//! OLE compound file format ([MS-CFB]).
21
22use crate::parasolid::ParasolidImportReport;
23
24mod container;
25
26
27pub use container::solidworks_streams;
28
29/// The partition of each configuration of a SolidWorks part, `Config-0` first.
30pub fn solidworks_part_partitions(bytes: &[u8]) -> Result<Vec<(String, Vec<u8>)>, String> {
31    let streams = solidworks_streams(bytes, &|name: &str| name.starts_with("Contents/Config-") && name.ends_with("-Partition") && !name.ends_with("GhostPartition"))?;
32    let mut out = Vec::new();
33    for (name, data) in streams {
34        let config = name.trim_start_matches("Contents/").trim_end_matches("-Partition").to_string();
35        let partition = first_section(&data).map_err(|e| format!("{name}: {e}"))?;
36        out.push((config, partition));
37    }
38    out.sort_by_key(|(config, _)| config.trim_start_matches("Config-").parse::<u32>().unwrap_or(u32::MAX));
39    if out.is_empty() {
40        return Err("the part holds no body (no Config-N-Partition stream)".into());
41    }
42    Ok(out)
43}
44
45/// The first section of a partition stream: a four-byte size, a 16-byte
46/// identifier, zlib chunks (each a four-byte uncompressed and compressed
47/// length, then the zlib data) and eight zero bytes. The partition's data is
48/// the chunks' concatenation; the sections after it are its rollback deltas.
49fn first_section(data: &[u8]) -> Result<Vec<u8>, String> {
50    let u32_at = |at: usize| data.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize).ok_or("the partition stream is cut short");
51    let size = u32_at(0)?;
52    let end = 4 + size;
53    if end > data.len() {
54        return Err(format!("its first section claims {size} bytes of {}", data.len()));
55    }
56    let mut at = 20;
57    let mut out = Vec::new();
58    while at + 8 <= end.saturating_sub(8) {
59        let (full, packed) = (u32_at(at)?, u32_at(at + 4)?);
60        if out.len() + full > MAX_PARTITION {
61            return Err(format!("the partition would be larger than {MAX_PARTITION} bytes"));
62        }
63        let chunk = data.get(at + 8..at + 8 + packed).ok_or("a chunk runs past its section")?;
64        out.extend(zlib(chunk, full)?);
65        at += 8 + packed;
66    }
67    Ok(out)
68}
69
70/// The bound on a partition's size: far above any part's body, and what a
71/// chunk's stated length may never take the total past.
72const MAX_PARTITION: usize = 1 << 30;
73
74/// A zlib stream (RFC 1950): a two-byte header, raw DEFLATE, then the
75/// Adler-32 of the data, which is checked.
76pub(crate) fn zlib(chunk: &[u8], expected: usize) -> Result<Vec<u8>, String> {
77    if expected > MAX_PARTITION {
78        return Err(format!("a chunk states {expected} bytes"));
79    }
80    if chunk.len() < 2 || chunk[0] & 0x0f != 8 || (u16::from(chunk[0]) << 8 | u16::from(chunk[1])) % 31 != 0 {
81        return Err("a chunk is not zlib data".into());
82    }
83    let out = crate::three_mf::inflate::inflate(&chunk[2..], expected.max(1)).map_err(|e| format!("a zlib chunk: {e}"))?;
84    if out.len() != expected {
85        return Err(format!("a chunk inflates to {} bytes, not the {expected} it states", out.len()));
86    }
87    // The checksum follows the DEFLATE data at the stream's end.
88    if let Some(tail) = chunk.len().checked_sub(4).and_then(|at| chunk.get(at..)) {
89        let stated = u32::from_be_bytes([tail[0], tail[1], tail[2], tail[3]]);
90        if adler32(&out) != stated {
91            return Err("a zlib chunk's checksum does not match its data".into());
92        }
93    }
94    Ok(out)
95}
96
97fn adler32(data: &[u8]) -> u32 {
98    let (mut a, mut b) = (1u32, 0u32);
99    for chunk in data.chunks(5552) {
100        for &x in chunk {
101            a += u32::from(x);
102            b += a;
103        }
104        a %= 65521;
105        b %= 65521;
106    }
107    b << 16 | a
108}
109
110/// The configuration a sub-assembly's instance tree was recorded for (its
111/// most recent one), when it says.
112fn recorded_configuration(bytes: &[u8]) -> Result<Option<u32>, String> {
113    let xml = instance_tree_xml(bytes)?;
114    Ok(elements(&xml, "swConfiguration")
115        .into_iter()
116        .find(|c| c.get("swMostRecentConfiguration").as_deref() == Some("YES"))
117        .and_then(|c| c.get("swID"))
118        .and_then(|id| id.parse().ok()))
119}
120
121/// A SolidWorks part's body (its first configuration), as the Parasolid
122/// import reads it. The other configurations are named in the error when
123/// there is more than one, so a caller can say which was taken.
124pub fn import_solidworks_part_report(bytes: &[u8]) -> Result<ParasolidImportReport, String> {
125    let partitions = solidworks_part_partitions(bytes).map_err(|e| format!("solidworks_import: {e}"))?;
126    import_configuration(bytes, &partitions[0].0, &partitions[0].1).map_err(|e| format!("solidworks_import: {}: {e}", partitions[0].0))
127}
128
129/// A configuration's bodies: its partition's, or, when the partition holds
130/// none, the bodies its features keep for themselves
131/// (`Config-N-FeatureBodies/LocalBodies`). A part made only of imported
132/// bodies (an `Imported1` feature) is saved so: an empty partition beside
133/// them.
134fn import_configuration(bytes: &[u8], config: &str, partition: &[u8]) -> Result<ParasolidImportReport, String> {
135    let first = crate::parasolid::import_parasolid_bytes_report(partition);
136    match &first {
137        Err(e) if e.ends_with(NO_BODIES) => {}
138        _ => return first,
139    }
140    let stream = format!("{config}-FeatureBodies/LocalBodies");
141    let streams = solidworks_streams(bytes, &|name: &str| name == stream)?;
142    let Some((_, data)) = streams.first() else { return first };
143    import_local_bodies(data).map_err(|e| format!("{stream}: {e}"))
144}
145
146/// Each body of a `LocalBodies` stream imported, in order, as one report.
147pub(crate) fn import_local_bodies(data: &[u8]) -> Result<ParasolidImportReport, String> {
148    let mut report: Option<ParasolidImportReport> = None;
149    for (name, partition) in local_bodies(data)? {
150        // A body kept empty adds nothing; the others still import (cross
151        // review: one empty entry lost the bodies beside it).
152        let mut part = match crate::parasolid::import_parasolid_bytes_report(&partition) {
153            Err(e) if e.ends_with(NO_BODIES) => continue,
154            read => read.map_err(|e| format!("{name}: {e}"))?,
155        };
156        // A body its file leaves unnamed takes the name its feature keeps it
157        // by (cross review), numbered when the file holds more than one.
158        let count = part.solids.len();
159        part.names.resize(count, String::new());
160        for (k, given) in part.names.iter_mut().enumerate() {
161            if given.is_empty() {
162                *given = if count == 1 { name.clone() } else { format!("{name} ({})", k + 1) };
163            }
164        }
165        let Some(out) = report.as_mut() else {
166            report = Some(part);
167            continue;
168        };
169        out.solids.extend(part.solids);
170        out.names.extend(part.names);
171        out.appearances.extend(part.appearances);
172        out.fitted_curves += part.fitted_curves;
173        out.unverified_curves += part.unverified_curves;
174        out.diagnostics.events.extend(part.diagnostics.events);
175        for (code, n) in part.diagnostics.counters {
176            *out.diagnostics.counters.entry(code).or_insert(0) += n;
177        }
178        for (code, value) in part.diagnostics.measurements {
179            let at = out.diagnostics.measurements.entry(code).or_insert(value);
180            *at = at.max(value);
181        }
182    }
183    report.ok_or_else(|| NO_BODIES.into())
184}
185
186/// What the Parasolid import says of a partition with no body in it.
187const NO_BODIES: &str = "the file holds no bodies";
188
189/// The bodies a configuration's features keep (`LocalBodies`): a count,
190/// then for each body its name (an MFC string: `FF FE FF`, a length in
191/// UTF-16 units, the UTF-16 text), five bytes, the length of what follows
192/// (a zero byte and a partition section), and that, a section as
193/// [`first_section`] reads: a whole Parasolid transmit file.
194pub(crate) fn local_bodies(data: &[u8]) -> Result<Vec<(String, Vec<u8>)>, String> {
195    let u32_at = |at: usize| data.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize).ok_or("the stream is cut short");
196    let count = u32_at(0)?;
197    let mut at = 4;
198    let mut out = Vec::new();
199    for _ in 0..count {
200        if data.get(at..at + 3) != Some(&[0xFF, 0xFE, 0xFF][..]) {
201            return Err(format!("no body name at byte {at}"));
202        }
203        let mut units = usize::from(*data.get(at + 3).ok_or("the stream is cut short")?);
204        at += 4;
205        if units == 0xFF {
206            units = data.get(at..at + 2).map(|b| usize::from(u16::from_le_bytes([b[0], b[1]]))).ok_or("the stream is cut short")?;
207            at += 2;
208        }
209        let text: Vec<u16> = data
210            .get(at..at + 2 * units)
211            .ok_or("a body name runs past the stream")?
212            .chunks(2)
213            .map(|c| u16::from_le_bytes([c[0], c[1]]))
214            .collect();
215        let name = String::from_utf16_lossy(&text);
216        at += 2 * units;
217        let block = u32_at(at + 5)?;
218        let section = data.get(at + 10..).ok_or("the stream is cut short")?;
219        let size = section.get(..4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize).ok_or("the stream is cut short")?;
220        if block != size + 5 || 4 + size > section.len() {
221            return Err(format!("{name}: a block of {block} bytes around a section of {size}"));
222        }
223        out.push((name.clone(), first_section(&section[..4 + size]).map_err(|e| format!("{name}: {e}"))?));
224        at += 10 + 4 + size;
225    }
226    Ok(out)
227}
228
229/// One instance an assembly places.
230#[derive(Clone, Debug, PartialEq)]
231pub struct SwComponent {
232    /// The instance's name in the assembly.
233    pub name: String,
234    /// The file it uses, as the assembly stored it (often an absolute
235    /// Windows path), and that file's base name.
236    pub path: String,
237    pub file_name: String,
238    /// Whether the file is a sub-assembly.
239    pub assembly: bool,
240    /// The configuration the instance uses: its index (`Config-N`) and name.
241    pub configuration: u32,
242    pub configuration_name: String,
243    /// Where the instance goes: row-major 4×4, mm.
244    pub transform: crate::Mat4,
245    pub suppressed: bool,
246}
247
248/// The instances a SolidWorks assembly places, from its instance tree.
249pub fn solidworks_assembly_components(bytes: &[u8]) -> Result<Vec<SwComponent>, String> {
250    parse_instance_tree(&instance_tree_xml(bytes)?)
251}
252
253/// The instance tree's XML.
254fn instance_tree_xml(bytes: &[u8]) -> Result<String, String> {
255    let streams = solidworks_streams(bytes, &|name: &str| name.starts_with("swXmlContents/COMPINSTANCETREE"))?;
256    let (name, data) = streams.into_iter().next().ok_or("the assembly has no instance tree (swXmlContents/COMPINSTANCETREE)")?;
257    let xml = if data.starts_with(b"<?xml") || data.starts_with(b"<sw") {
258        data
259    } else {
260        // `__ZLB`: a 16-byte identifier, the uncompressed and compressed
261        // lengths, then zlib.
262        let u32_at = |at: usize| data.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize).ok_or("the instance tree is cut short");
263        let (full, packed) = (u32_at(16)?, u32_at(20)?);
264        zlib(data.get(24..24 + packed).ok_or("the instance tree is cut short")?, full).map_err(|e| format!("{name}: {e}"))?
265    };
266    Ok(String::from_utf8_lossy(&xml).into_owned())
267}
268
269/// The part of the tree that holds the assembly's own instances. Each
270/// model that places instances holds them inside its element, a
271/// sub-assembly's as well as the assembly's; the assembly's own model is
272/// the one no instance places. Read as the assembly's, a sub-assembly's
273/// instances were placed with its frame for the assembly's, and again
274/// through the sub-assembly. A tree whose instances stand outside every
275/// model is read whole.
276fn own_instances(xml: &str) -> &str {
277    let placed: Vec<String> = elements(xml, "swReference").iter().filter_map(|r| r.get("swModelRef")).collect();
278    let mut owners = Vec::new();
279    let mut rest = 0;
280    while let Some(at) = xml[rest..].find("<swModel ").map(|at| rest + at) {
281        let Some(tag_end) = xml[at..].find('>').map(|end| at + end) else { break };
282        rest = tag_end + 1;
283        if xml[..tag_end].ends_with('/') {
284            continue;
285        }
286        let Some(close) = xml[rest..].find("</swModel>").map(|end| rest + end) else { break };
287        let body = &xml[rest..close];
288        let id = elements(&xml[at..=tag_end], "swModel").into_iter().next().and_then(|m| m.get("id"));
289        if body.contains("<swReference ") && id.is_some_and(|id| !placed.contains(&id)) {
290            owners.push(body);
291        }
292        rest = close;
293    }
294    match owners.as_slice() {
295        [own] => own,
296        _ => xml,
297    }
298}
299
300fn parse_instance_tree(xml: &str) -> Result<Vec<SwComponent>, String> {
301    let files: Vec<Element> = elements(xml, "swFile");
302    let models: Vec<Element> = elements(xml, "swModel");
303    let mut out = Vec::new();
304    for reference in elements(own_instances(xml), "swReference") {
305        let model = models
306            .iter()
307            .find(|m| m.get("id") == reference.get("swModelRef"))
308            .ok_or_else(|| format!("instance {} names no model", reference.get("swName").unwrap_or_default()))?;
309        let file = files
310            .iter()
311            .find(|f| f.get("id") == model.get("swFileRef"))
312            .ok_or_else(|| format!("model {} names no file", model.get("swName").unwrap_or_default()))?;
313        let path = file.get("swPath").unwrap_or_default();
314        let numbers: Vec<f64> = reference
315            .get("swTransform")
316            .unwrap_or_default()
317            .split_whitespace()
318            .map(|t| t.parse::<f64>().map_err(|_| format!("a transform holds {t:?}")))
319            .collect::<Result<_, _>>()?;
320        if numbers.len() != 16 {
321            return Err(format!("instance {} has a transform of {} numbers", reference.get("swName").unwrap_or_default(), numbers.len()));
322        }
323        let s = &numbers;
324        if s[3] != 0.0 || s[7] != 0.0 || s[11] != 0.0 {
325            return Err("an instance's transform has a perspective part".into());
326        }
327        let scale = if s[15] != 0.0 { 1.0 / s[15] } else { return Err("an instance's transform has a zero weight".into()) };
328        let mm = 1000.0;
329        // p' = p R + t (rows): the column form takes R transposed.
330        let transform = [
331            s[0], s[4], s[8], s[12] * mm * scale,
332            s[1], s[5], s[9], s[13] * mm * scale,
333            s[2], s[6], s[10], s[14] * mm * scale,
334            0.0, 0.0, 0.0, 1.0,
335        ];
336        let file_name = path.rsplit(['\\', '/']).next().unwrap_or(&path).to_string();
337        out.push(SwComponent {
338            name: reference.get("swName").unwrap_or_default(),
339            assembly: file.get("swDocType").as_deref() == Some("ASSEMBLY"),
340            path,
341            file_name,
342            configuration: model.get("swConfigurationId").and_then(|c| c.parse().ok()).unwrap_or(0),
343            configuration_name: model.get("swConfigurationName").unwrap_or_default(),
344            transform,
345            suppressed: reference.get("swSuppressed").as_deref() == Some("YES"),
346        });
347    }
348    Ok(out)
349}
350
351/// An element's attributes, from its start tag.
352struct Element(Vec<(String, String)>);
353
354impl Element {
355    fn get(&self, key: &str) -> Option<String> {
356        self.0.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone())
357    }
358}
359
360/// The start tags `<tag ...>` of `xml`, attributes unescaped.
361fn elements(xml: &str, tag: &str) -> Vec<Element> {
362    let open = format!("<{tag} ");
363    let mut out = Vec::new();
364    let mut rest = xml;
365    while let Some(at) = rest.find(&open) {
366        let body = &rest[at + open.len()..];
367        let end = body.find('>').unwrap_or(body.len());
368        let attributes = &body[..end];
369        let mut pairs = Vec::new();
370        let mut a = attributes;
371        while let Some(eq) = a.find("=\"") {
372            let key = a[..eq].trim().to_string();
373            let after = &a[eq + 2..];
374            let close = after.find('"').unwrap_or(after.len());
375            pairs.push((key, unescape(&after[..close])));
376            a = &after[(close + 1).min(after.len())..];
377        }
378        out.push(Element(pairs));
379        rest = &body[end..];
380    }
381    out
382}
383
384fn unescape(value: &str) -> String {
385    value.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&apos;", "'").replace("&amp;", "&")
386}
387
388/// The event an import report carries for a virtual part with no body.
389pub const VIRTUAL_PART_WITHOUT_BODY: &str = "import.solidworks.virtual_part_without_body";
390
391/// A SolidWorks assembly's bodies, each instance's part read through
392/// `resolve` (given a file's base name, its bytes) and placed; sub-assemblies
393/// recursively. Suppressed instances are left out.
394///
395/// A virtual component (an instance of a part kept inside the assembly that
396/// made it, its file named `<part>^<assembly>`) is read from that assembly's
397/// `VirtualComp/<part>` stream, a whole part file, as any part is; a virtual
398/// part that holds no body contributes nothing, and the report names it
399/// ([`VIRTUAL_PART_WITHOUT_BODY`]).
400pub fn import_solidworks_assembly_report(
401    bytes: &[u8],
402    resolve: &mut dyn FnMut(&str) -> Option<Vec<u8>>,
403) -> Result<ParasolidImportReport, String> {
404    let mut report: Option<ParasolidImportReport> = None;
405    let mut parts: rustc_hash::FxHashMap<(String, u32), ParasolidImportReport> = rustc_hash::FxHashMap::default();
406    let mut empty = Vec::new();
407    place(bytes, crate::step_matrix::MAT4_IDENTITY, 0, resolve, &mut parts, &mut report, &mut empty)?;
408    let Some(mut report) = report else {
409        return Err(if empty.is_empty() {
410            "solidworks_import: the assembly places no part".to_string()
411        } else {
412            format!("solidworks_import: the assembly places no part with a body (virtual parts without one: {})", empty.join(", "))
413        });
414    };
415    for name in empty {
416        report.diagnostics.event(
417            crate::DiagnosticSeverity::Warning,
418            crate::KernelStage::Collect,
419            VIRTUAL_PART_WITHOUT_BODY,
420            format!("solidworks_import: virtual part {name} holds no body; it contributes nothing"),
421        );
422    }
423    Ok(report)
424}
425
426/// An assembly's own name, from its instance tree: the assembly model no
427/// instance places (the tree's root). `None` when the tree does not say.
428fn own_name(assembly: &[u8]) -> Result<Option<String>, String> {
429    let xml = instance_tree_xml(assembly)?;
430    let placed: Vec<String> = elements(&xml, "swReference").iter().filter_map(|r| r.get("swModelRef")).collect();
431    let files = elements(&xml, "swFile");
432    let roots: Vec<String> = elements(&xml, "swModel")
433        .into_iter()
434        .filter(|m| m.get("id").is_some_and(|id| !placed.contains(&id)))
435        .filter(|m| files.iter().any(|f| f.get("id") == m.get("swFileRef") && f.get("swDocType").as_deref() == Some("ASSEMBLY")))
436        .filter_map(|m| m.get("swName"))
437        .collect();
438    Ok(match roots.as_slice() {
439        [one] => Some(one.clone()),
440        _ => None,
441    })
442}
443
444/// The part file of a virtual component kept in `assembly` (its file named
445/// `<part>^<owner>`): the assembly's `VirtualComp/<part>` stream. `None` for
446/// a component that is not virtual, or whose part the assembly does not
447/// keep; an error when the assembly cannot be read for it (a damaged stream
448/// is not replaced by a file of the same name, cross review).
449fn virtual_part(assembly: &[u8], file_name: &str) -> Result<Option<Vec<u8>>, String> {
450    let Some((part, owner)) = file_name.split_once('^') else { return Ok(None) };
451    // Only the assembly that made it keeps it: another's part of the same
452    // name is not this one (cross review).
453    let owner = owner.rsplit_once('.').map_or(owner, |(stem, _)| stem);
454    if !own_name(assembly)?.is_some_and(|name| name.eq_ignore_ascii_case(owner)) {
455        return Ok(None);
456    }
457    let stream = format!("VirtualComp/{part}");
458    Ok(solidworks_streams(assembly, &|name: &str| name == stream)?.into_iter().next().map(|(_, data)| data))
459}
460
461fn place(
462    bytes: &[u8],
463    parent: crate::Mat4,
464    depth: usize,
465    resolve: &mut dyn FnMut(&str) -> Option<Vec<u8>>,
466    parts: &mut rustc_hash::FxHashMap<(String, u32), ParasolidImportReport>,
467    report: &mut Option<ParasolidImportReport>,
468    empty: &mut Vec<String>,
469) -> Result<(), String> {
470    if depth > 32 {
471        return Err("solidworks_import: assemblies nest more than 32 deep".into());
472    }
473    let components = solidworks_assembly_components(bytes).map_err(|e| format!("solidworks_import: {e}"))?;
474    for component in components.iter().filter(|c| !c.suppressed) {
475        let matrix = crate::step_matrix::mat4_mul(&parent, &component.transform);
476        let kept = virtual_part(bytes, &component.file_name).map_err(|e| format!("solidworks_import: {}: {e}", component.file_name))?;
477        let is_virtual = kept.is_some();
478        let file = kept
479            .or_else(|| resolve(&component.file_name))
480            .ok_or_else(|| format!("solidworks_import: {} uses {}, which is not beside the assembly", component.name, component.file_name))?;
481        if component.assembly {
482            // A sub-assembly's file records the tree of one configuration;
483            // an instance of another is not read.
484            let recorded = recorded_configuration(&file).map_err(|e| format!("solidworks_import: {}: {e}", component.file_name))?;
485            if recorded.is_some_and(|c| c != component.configuration) {
486                return Err(format!(
487                    "solidworks_import: {} uses configuration {:?} of sub-assembly {}, whose file records only configuration {}",
488                    component.name,
489                    component.configuration_name,
490                    component.file_name,
491                    recorded.unwrap_or(0)
492                ));
493            }
494            place(&file, matrix, depth + 1, resolve, parts, report, empty)?;
495            continue;
496        }
497        let key = (component.file_name.to_ascii_lowercase(), component.configuration);
498        if !parts.contains_key(&key) {
499            let partitions = solidworks_part_partitions(&file).map_err(|e| format!("solidworks_import: {}: {e}", component.file_name))?;
500            let wanted = format!("Config-{}", component.configuration);
501            let partition = partitions.iter().find(|(c, _)| *c == wanted).map(|(_, p)| p).ok_or_else(|| {
502                format!(
503                    "solidworks_import: {} uses configuration {:?} ({wanted}) of {}, which holds only {}",
504                    component.name,
505                    component.configuration_name,
506                    component.file_name,
507                    partitions.iter().map(|(c, _)| c.as_str()).collect::<Vec<_>>().join(", ")
508                )
509            })?;
510            // Empty when neither its partition nor any body its features
511            // keep holds one (any other error refuses it).
512            let part = match import_configuration(&file, &wanted, partition) {
513                Err(e) if is_virtual && e.ends_with(NO_BODIES) => {
514                    if !empty.contains(&component.file_name) {
515                        empty.push(component.file_name.clone());
516                    }
517                    continue;
518                }
519                read => read.map_err(|e| format!("solidworks_import: {}: {e}", component.file_name))?,
520            };
521            parts.insert(key.clone(), part);
522        }
523        let part = &parts[&key];
524        let transform = crate::AffineTransform::new(matrix).map_err(|e| format!("solidworks_import: {}: {e}", component.name))?;
525        let out = report.get_or_insert_with(|| ParasolidImportReport {
526            solids: Vec::new(),
527            names: Vec::new(),
528            appearances: Vec::new(),
529            application: Some("SolidWorks".into()),
530            modeller_version: part.modeller_version.clone(),
531            stated_resolution_mm: part.stated_resolution_mm,
532            fitted_curves: 0,
533            unverified_curves: 0,
534            diagnostics: Default::default(),
535        });
536        for (k, solid) in part.solids.iter().enumerate() {
537            let placed = crate::transform_brep(solid, transform, transform.determinant3() < 0.0).map_err(|e| format!("solidworks_import: {}: {e}", component.name))?;
538            out.solids.push(placed);
539            out.names.push(if part.solids.len() == 1 { component.name.clone() } else { format!("{} ({})", component.name, k + 1) });
540            out.appearances.push(part.appearances.get(k).cloned().unwrap_or_default());
541        }
542        out.fitted_curves += part.fitted_curves;
543        out.unverified_curves += part.unverified_curves;
544    }
545    Ok(())
546}