1use crate::parasolid::ParasolidImportReport;
23
24mod container;
25
26
27pub use container::solidworks_streams;
28
29pub 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
45fn 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
70const MAX_PARTITION: usize = 1 << 30;
73
74pub(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 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
110fn 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
121pub 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
129fn 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
146pub(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 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 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
186const NO_BODIES: &str = "the file holds no bodies";
188
189pub(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(§ion[..4 + size]).map_err(|e| format!("{name}: {e}"))?));
224 at += 10 + 4 + size;
225 }
226 Ok(out)
227}
228
229#[derive(Clone, Debug, PartialEq)]
231pub struct SwComponent {
232 pub name: String,
234 pub path: String,
237 pub file_name: String,
238 pub assembly: bool,
240 pub configuration: u32,
242 pub configuration_name: String,
243 pub transform: crate::Mat4,
245 pub suppressed: bool,
246}
247
248pub fn solidworks_assembly_components(bytes: &[u8]) -> Result<Vec<SwComponent>, String> {
250 parse_instance_tree(&instance_tree_xml(bytes)?)
251}
252
253fn 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 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
269fn 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 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
351struct 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
360fn 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("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'").replace("&", "&")
386}
387
388pub const VIRTUAL_PART_WITHOUT_BODY: &str = "import.solidworks.virtual_part_without_body";
390
391pub const MISSING_COMPONENT_FILE: &str = "import.solidworks.missing_component_file";
394
395pub 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#[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
478fn 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
496fn 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 let (owner, extension) = owner.rsplit_once('.').unwrap_or((owner, ""));
506 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 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 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 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}