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/// The diagnostic code for a component whose file was not found: its
392/// instances are left out and the rest of the assembly is placed.
393pub const MISSING_COMPONENT_FILE: &str = "import.solidworks.missing_component_file";
394
395/// A SolidWorks assembly's bodies, each instance's part read through
396/// `resolve` (given a file's base name, its bytes) and placed; sub-assemblies
397/// recursively. Suppressed instances are left out.
398///
399/// A component whose file `resolve` does not find (a part or a
400/// sub-assembly) is left out, as SolidWorks opens an assembly whose
401/// references are missing; the report names each such file once
402/// ([`MISSING_COMPONENT_FILE`]). An assembly none of whose components is
403/// found is refused, naming every missing file.
404///
405/// A virtual component (an instance of a part kept inside the assembly that
406/// made it, its file named `<part>^<assembly>`) is read from that assembly's
407/// `VirtualComp/<part>` stream, a whole part file, as any part is; a virtual
408/// part that holds no body contributes nothing, and the report names it
409/// ([`VIRTUAL_PART_WITHOUT_BODY`]).
410pub fn import_solidworks_assembly_report(
411    bytes: &[u8],
412    resolve: &mut dyn FnMut(&str) -> Option<Vec<u8>>,
413) -> Result<ParasolidImportReport, String> {
414    let mut report: Option<ParasolidImportReport> = None;
415    let mut parts: rustc_hash::FxHashMap<(String, u32), ParasolidImportReport> = rustc_hash::FxHashMap::default();
416    let mut empty = Vec::new();
417    let mut missing = Missing::default();
418    place(bytes, crate::step_matrix::MAT4_IDENTITY, 0, resolve, &mut parts, &mut report, &mut empty, &mut missing)?;
419    let Some(mut report) = report else {
420        return Err(if !missing.files.is_empty() {
421            format!(
422                "solidworks_import: none of the assembly's component files is beside it (missing: {}); put the parts and sub-assemblies it uses in its folder",
423                missing.describe()
424            )
425        } else if empty.is_empty() {
426            "solidworks_import: the assembly places no part".to_string()
427        } else {
428            format!("solidworks_import: the assembly places no part with a body (virtual parts without one: {})", empty.join(", "))
429        });
430    };
431    if !missing.files.is_empty() {
432        report.diagnostics.event(
433            crate::DiagnosticSeverity::Warning,
434            crate::KernelStage::Collect,
435            MISSING_COMPONENT_FILE,
436            format!(
437                "solidworks_import: {} component file(s) not beside the assembly, their instances left out: {}",
438                missing.files.len(),
439                missing.describe()
440            ),
441        );
442    }
443    for name in empty {
444        report.diagnostics.event(
445            crate::DiagnosticSeverity::Warning,
446            crate::KernelStage::Collect,
447            VIRTUAL_PART_WITHOUT_BODY,
448            format!("solidworks_import: virtual part {name} holds no body; it contributes nothing"),
449        );
450    }
451    Ok(report)
452}
453
454/// The component files an assembly uses that were not found, each with the
455/// number of instances (at any depth) left out for it, in the order met.
456#[derive(Default)]
457struct Missing {
458    files: Vec<(String, usize)>,
459}
460
461impl Missing {
462    fn add(&mut self, file_name: &str) {
463        match self.files.iter_mut().find(|(f, _)| f.eq_ignore_ascii_case(file_name)) {
464            Some((_, n)) => *n += 1,
465            None => self.files.push((file_name.to_string(), 1)),
466        }
467    }
468
469    fn describe(&self) -> String {
470        self.files
471            .iter()
472            .map(|(f, n)| if *n == 1 { f.clone() } else { format!("{f} (x{n})") })
473            .collect::<Vec<_>>()
474            .join(", ")
475    }
476}
477
478/// An assembly's own name, from its instance tree: the assembly model no
479/// instance places (the tree's root). `None` when the tree does not say.
480fn own_name(assembly: &[u8]) -> Result<Option<String>, String> {
481    let xml = instance_tree_xml(assembly)?;
482    let placed: Vec<String> = elements(&xml, "swReference").iter().filter_map(|r| r.get("swModelRef")).collect();
483    let files = elements(&xml, "swFile");
484    let roots: Vec<String> = elements(&xml, "swModel")
485        .into_iter()
486        .filter(|m| m.get("id").is_some_and(|id| !placed.contains(&id)))
487        .filter(|m| files.iter().any(|f| f.get("id") == m.get("swFileRef") && f.get("swDocType").as_deref() == Some("ASSEMBLY")))
488        .filter_map(|m| m.get("swName"))
489        .collect();
490    Ok(match roots.as_slice() {
491        [one] => Some(one.clone()),
492        _ => None,
493    })
494}
495
496/// The part file of a virtual component kept in `assembly` (its file named
497/// `<part>^<owner>`): the assembly's `VirtualComp/<part>` stream. `None` for
498/// a component that is not virtual, or whose part the assembly does not
499/// keep; an error when the assembly cannot be read for it (a damaged stream
500/// is not replaced by a file of the same name, cross review).
501fn virtual_part(assembly: &[u8], file_name: &str) -> Result<Option<Vec<u8>>, String> {
502    let Some((part, owner)) = file_name.split_once('^') else { return Ok(None) };
503    // Only the assembly that made it keeps it: another's part of the same
504    // name is not this one (cross review).
505    let (owner, extension) = owner.rsplit_once('.').unwrap_or((owner, ""));
506    // A virtual component nested in a virtual sub-assembly names its owner
507    // with the owner's own `^` written as `_`.
508    let same = |a: &str, b: &str| a.replace('^', "_").eq_ignore_ascii_case(&b.replace('^', "_"));
509    if !own_name(assembly)?.is_some_and(|name| same(&name, owner)) {
510        return Ok(None);
511    }
512    // The OLE container keeps it as `VirtualComp/<part>`, the 2015+ archive
513    // as `VirtualComp/<part>-<extension>` (`-sldprt`, `-sldasm`).
514    let plain = format!("VirtualComp/{part}");
515    let suffixed = format!("VirtualComp/{part}-{}", extension.to_ascii_lowercase());
516    let mut found = solidworks_streams(assembly, &|name: &str| name == plain || name.eq_ignore_ascii_case(&suffixed))?;
517    found.sort_by_key(|(name, _)| name != &plain);
518    Ok(found.into_iter().next().map(|(_, data)| data))
519}
520
521#[allow(clippy::too_many_arguments)]
522fn place(
523    bytes: &[u8],
524    parent: crate::Mat4,
525    depth: usize,
526    resolve: &mut dyn FnMut(&str) -> Option<Vec<u8>>,
527    parts: &mut rustc_hash::FxHashMap<(String, u32), ParasolidImportReport>,
528    report: &mut Option<ParasolidImportReport>,
529    empty: &mut Vec<String>,
530    missing: &mut Missing,
531) -> Result<(), String> {
532    if depth > 32 {
533        return Err("solidworks_import: assemblies nest more than 32 deep".into());
534    }
535    let components = solidworks_assembly_components(bytes).map_err(|e| format!("solidworks_import: {e}"))?;
536    for component in components.iter().filter(|c| !c.suppressed) {
537        let matrix = crate::step_matrix::mat4_mul(&parent, &component.transform);
538        let kept = virtual_part(bytes, &component.file_name).map_err(|e| format!("solidworks_import: {}: {e}", component.file_name))?;
539        let is_virtual = kept.is_some();
540        let Some(file) = kept.or_else(|| resolve(&component.file_name)) else {
541            missing.add(&component.file_name);
542            continue;
543        };
544        if component.assembly {
545            // A sub-assembly's file records the tree of one configuration;
546            // an instance of another is not read.
547            let recorded = recorded_configuration(&file).map_err(|e| format!("solidworks_import: {}: {e}", component.file_name))?;
548            if recorded.is_some_and(|c| c != component.configuration) {
549                return Err(format!(
550                    "solidworks_import: {} uses configuration {:?} of sub-assembly {}, whose file records only configuration {}",
551                    component.name,
552                    component.configuration_name,
553                    component.file_name,
554                    recorded.unwrap_or(0)
555                ));
556            }
557            place(&file, matrix, depth + 1, resolve, parts, report, empty, missing)?;
558            continue;
559        }
560        let key = (component.file_name.to_ascii_lowercase(), component.configuration);
561        if !parts.contains_key(&key) {
562            let partitions = solidworks_part_partitions(&file).map_err(|e| format!("solidworks_import: {}: {e}", component.file_name))?;
563            let wanted = format!("Config-{}", component.configuration);
564            let partition = partitions.iter().find(|(c, _)| *c == wanted).map(|(_, p)| p).ok_or_else(|| {
565                format!(
566                    "solidworks_import: {} uses configuration {:?} ({wanted}) of {}, which holds only {}",
567                    component.name,
568                    component.configuration_name,
569                    component.file_name,
570                    partitions.iter().map(|(c, _)| c.as_str()).collect::<Vec<_>>().join(", ")
571                )
572            })?;
573            // Empty when neither its partition nor any body its features
574            // keep holds one (any other error refuses it).
575            let part = match import_configuration(&file, &wanted, partition) {
576                Err(e) if is_virtual && e.ends_with(NO_BODIES) => {
577                    if !empty.contains(&component.file_name) {
578                        empty.push(component.file_name.clone());
579                    }
580                    continue;
581                }
582                read => read.map_err(|e| format!("solidworks_import: {}: {e}", component.file_name))?,
583            };
584            parts.insert(key.clone(), part);
585        }
586        let part = &parts[&key];
587        let transform = crate::AffineTransform::new(matrix).map_err(|e| format!("solidworks_import: {}: {e}", component.name))?;
588        let out = report.get_or_insert_with(|| ParasolidImportReport {
589            solids: Vec::new(),
590            names: Vec::new(),
591            appearances: Vec::new(),
592            application: Some("SolidWorks".into()),
593            modeller_version: part.modeller_version.clone(),
594            stated_resolution_mm: part.stated_resolution_mm,
595            fitted_curves: 0,
596            unverified_curves: 0,
597            diagnostics: Default::default(),
598        });
599        for (k, solid) in part.solids.iter().enumerate() {
600            let placed = crate::transform_brep(solid, transform, transform.determinant3() < 0.0).map_err(|e| format!("solidworks_import: {}: {e}", component.name))?;
601            out.solids.push(placed);
602            out.names.push(if part.solids.len() == 1 { component.name.clone() } else { format!("{} ({})", component.name, k + 1) });
603            out.appearances.push(part.appearances.get(k).cloned().unwrap_or_default());
604        }
605        out.fitted_curves += part.fitted_curves;
606        out.unverified_curves += part.unverified_curves;
607    }
608    Ok(())
609}