1use crate::topology::BrepSolid;
9use crate::Vec3;
10use crate::{BodyAppearance, StepAssembly, StepOccurrence, StepProduct};
11use rustc_hash::FxHashMap as HashMap;
12
13use super::reader::{parse_iges, IgesFile};
14use super::structure::{self, Matrix, Placed};
15use super::to_step::{analyse_face_sets, free_shell_to_step, manifold_solid_to_step, trimmed_surfaces, FaceSets};
16
17pub fn import_iges(text: &str) -> Result<Vec<BrepSolid>, String> {
19 Ok(import_iges_report(text)?.solids)
20}
21
22pub fn import_iges_bodies(text: &str) -> Result<IgesImportReport, String> {
27 let _lean = Lean::enter();
28 import_iges_report(text)
29}
30
31std::thread_local! {
32 static TRIM_READINGS: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
35}
36
37struct Lean(bool);
40
41impl Lean {
42 fn enter() -> Self {
43 let before = TRIM_READINGS.with(|readings| readings.get());
44 if crate::step_import::import_lean() {
45 TRIM_READINGS.with(|readings| readings.set(false));
46 }
47 Lean(before)
48 }
49}
50
51impl Drop for Lean {
52 fn drop(&mut self) {
53 TRIM_READINGS.with(|readings| readings.set(self.0));
54 }
55}
56
57fn step_report(step: &str, sheets: bool) -> Result<crate::StepImportReport, String> {
61 let readings = TRIM_READINGS.with(|readings| readings.get());
62 if readings {
63 if sheets {
64 crate::step_import::import_step_report_with_sheets(step)
65 } else {
66 crate::import_step_report(step)
67 }
68 } else {
69 crate::step_import::import_step_report_dropping_readings(step, sheets)
70 }
71 .map_err(|error| format!("iges_import: {error}"))
72}
73
74#[derive(Clone, Debug)]
77pub struct IgesImportReport {
78 pub solids: Vec<BrepSolid>,
81 pub names: Vec<String>,
85 pub appearances: Vec<BodyAppearance>,
88 pub levels: Vec<i64>,
91 pub stated_resolution_mm: Option<f64>,
94 pub diagnostics: crate::KernelDiagnostics,
97}
98
99pub fn import_iges_report(text: &str) -> Result<IgesImportReport, String> {
102 let file = parse_iges(text)?;
103 let scale = file.global.length_scale_mm()?;
104 let stated = file.global.min_resolution * scale;
105 let mut diagnostics = crate::KernelDiagnostics::default();
106 let bodies = solids_with_diagnostics(&file, scale, &mut diagnostics)?;
107 let mut report = IgesImportReport {
108 solids: Vec::with_capacity(bodies.len()),
109 names: Vec::with_capacity(bodies.len()),
110 appearances: Vec::with_capacity(bodies.len()),
111 levels: Vec::with_capacity(bodies.len()),
112 stated_resolution_mm: (stated > 0.0 && stated.is_finite()).then_some(stated),
113 diagnostics,
114 };
115 for body in bodies {
116 report.solids.push(body.solid);
117 report.names.push(body.name.unwrap_or_default());
118 report.appearances.push(BodyAppearance { body: body.color, faces: body.faces });
119 report.levels.push(body.level);
120 }
121 Ok(report)
122}
123
124struct Body {
126 solid: BrepSolid,
127 name: Option<String>,
128 color: Option<crate::ImportedColor>,
129 faces: FaceColors,
132 level: i64,
133}
134
135impl Body {
136 fn bare(solid: BrepSolid) -> Self {
137 Self { solid, name: None, color: None, faces: Vec::new(), level: 0 }
138 }
139}
140
141type FaceColors = Vec<Option<crate::ImportedColor>>;
143
144type SolidCache = HashMap<i64, Vec<(BrepSolid, FaceColors)>>;
147
148type SetCache = HashMap<i64, Vec<BrepSolid>>;
151
152fn built_solid<'c>(
153 cache: &'c mut SolidCache,
154 file: &IgesFile,
155 pointer: i64,
156 scale: f64,
157 diagnostics: &mut crate::KernelDiagnostics,
158) -> Result<&'c [(BrepSolid, FaceColors)], String> {
159 if !cache.contains_key(&pointer) {
160 let (built, measured) = manifold_solid(file, pointer, scale)?;
161 merge_diagnostics(diagnostics, measured);
162 cache.insert(pointer, built);
163 }
164 Ok(&cache[&pointer])
165}
166
167pub(super) fn place(solid: &BrepSolid, placement: &Matrix) -> Result<BrepSolid, String> {
170 if structure::is_identity(placement) {
171 return Ok(solid.clone());
172 }
173 let transform = crate::AffineTransform::new(*placement)?;
174 let mirrored = transform.determinant3() < 0.0;
175 crate::transform_brep(solid, transform, mirrored)
176}
177
178fn solids_with_diagnostics(
179 file: &IgesFile,
180 scale: f64,
181 diagnostics: &mut crate::KernelDiagnostics,
182) -> Result<Vec<Body>, String> {
183 if file.entities_of_type(186).next().is_some() || file.entities_of_type(514).next().is_some() {
188 refuse_uncovered_geometry(file)?;
189 let mut cache = SolidCache::default();
190 let mut bodies = Vec::new();
191 for Placed { solid, placement, name, color, level } in structure::placed_solids(file, scale)? {
192 for (built, faces) in built_solid(&mut cache, file, solid, scale, diagnostics)? {
193 bodies.push(Body { solid: place(built, &placement)?, name: name.clone(), color, faces: faces.clone(), level });
194 }
195 }
196 bodies.extend(free_shell_bodies(file, scale, diagnostics)?);
197 if bodies.is_empty() {
198 let sheets = diagnostics.counters.get(crate::step_import::SHEETS_SKIPPED).copied().unwrap_or(0);
199 return Err(format!(
200 "iges_import: the file has no solids: its {sheets} shell(s) are sheets (open, or a single untrimmed face), not solids"
201 ));
202 }
203 return Ok(bodies);
204 }
205 if file.entities_of_type(408).next().is_some() {
208 let bodies = placed_face_set_bodies(file, scale, diagnostics)?;
209 if bodies.is_empty() {
210 return Err(nothing_to_import(file));
211 }
212 return Ok(bodies);
213 }
214
215 if file.entities_of_type(144).next().is_none() && file.entities_of_type(143).next().is_none() {
216 return Err(nothing_to_import(file));
217 }
218 let (solids, measured) = face_set_solids(file, scale, &trimmed_surfaces(file))?;
219 for each in measured {
220 merge_diagnostics(diagnostics, each);
221 }
222 Ok(solids.into_iter().map(Body::bare).collect())
223}
224
225fn nothing_to_import(file: &IgesFile) -> String {
227 if file.entities_of_type(144).next().is_none()
228 && file.entities_of_type(143).next().is_none()
229 && file.entities_of_type(128).next().is_some()
230 {
231 return "iges_import: file has untrimmed B-spline surfaces (entity 128) but no trimmed surfaces (entity 144) to form faces"
232 .into();
233 }
234 "iges_import: the file has no solids (186) or trimmed surfaces (144, 143) to import".into()
235}
236
237fn loose_surfaces(file: &IgesFile) -> Result<Vec<i64>, String> {
240 let members = structure::subfigure_member_set(file)?;
241 Ok(trimmed_surfaces(file).into_iter().filter(|pointer| !members.contains(pointer)).collect())
242}
243
244fn loose_set_solids(
247 file: &IgesFile,
248 scale: f64,
249 diagnostics: &mut crate::KernelDiagnostics,
250) -> Result<Vec<BrepSolid>, String> {
251 let loose = loose_surfaces(file)?;
252 if loose.is_empty() {
253 return Ok(Vec::new());
254 }
255 let (solids, measured) = face_set_solids(file, scale, &loose)?;
256 for each in measured {
257 merge_diagnostics(diagnostics, each);
258 }
259 Ok(solids)
260}
261
262fn subfigure_set_solids<'c>(
266 cache: &'c mut SetCache,
267 file: &IgesFile,
268 pointer: i64,
269 scale: f64,
270 diagnostics: &mut crate::KernelDiagnostics,
271) -> Result<&'c [BrepSolid], String> {
272 if !cache.contains_key(&pointer) {
273 let mut surfaces = Vec::new();
274 for member in structure::subfigure_members(file.entity(pointer)?)? {
275 if matches!(file.entity(member)?.de.entity_type, 144 | 143) {
276 surfaces.push(member);
277 }
278 }
279 surfaces.sort_unstable();
280 surfaces.dedup();
281 let mut solids = Vec::new();
282 if !surfaces.is_empty() {
283 let (built, measured) =
284 face_set_solids(file, scale, &surfaces).map_err(|error| format!("subfigure DE {pointer}: {error}"))?;
285 for each in measured {
286 merge_diagnostics(diagnostics, each);
287 }
288 solids = built;
289 }
290 cache.insert(pointer, solids);
291 }
292 Ok(&cache[&pointer])
293}
294
295fn placed_face_set_bodies(
298 file: &IgesFile,
299 scale: f64,
300 diagnostics: &mut crate::KernelDiagnostics,
301) -> Result<Vec<Body>, String> {
302 let placed = structure::placed_face_sets(file, scale)?;
304 let mut bodies: Vec<Body> = loose_set_solids(file, scale, diagnostics)?.into_iter().map(Body::bare).collect();
305 let mut cache = SetCache::default();
306 for Placed { solid: definition, placement, name, color, level } in placed {
307 for built in subfigure_set_solids(&mut cache, file, definition, scale, diagnostics)? {
308 bodies.push(Body { solid: place(built, &placement)?, name: name.clone(), color, faces: Vec::new(), level });
309 }
310 }
311 Ok(bodies)
312}
313
314pub fn read_iges_assembly(text: &str) -> Result<Option<StepAssembly>, String> {
329 let _lean = Lean::enter();
332 let file = parse_iges(text)?;
333 let members = structure::subfigure_member_set(&file)?;
334 let top_instances: Vec<i64> = file
335 .pointers_of_type(408)
336 .into_iter()
337 .map(|(pointer, _)| pointer)
338 .filter(|pointer| !members.contains(pointer))
339 .collect();
340 if top_instances.is_empty() {
341 return Ok(None);
342 }
343 let scale = file.global.length_scale_mm()?;
345 if file.entities_of_type(186).next().is_none() && file.entities_of_type(514).next().is_none() {
346 return face_set_assembly(&file, scale, top_instances).map(Some);
347 }
348 if file.entities_of_type(186).next().is_none() {
349 return Err(
350 "iges_import: the file places subfigures (408) of trimmed surfaces, which this import cannot build yet"
351 .into(),
352 );
353 }
354 refuse_uncovered_geometry(&file)?;
355 structure::placed_solids(&file, scale)?;
356
357 let mut cache = SolidCache::default();
358 let mut sets = SetCache::default();
359 let mut diagnostics = crate::KernelDiagnostics::default();
360 let mut assembly = root_only_assembly(&file);
361 for (pointer, solid) in file.pointers_of_type(186) {
362 if !members.contains(&pointer) {
363 let color = structure::entity_color(&file, solid);
364 for (built, faces) in built_solid(&mut cache, &file, pointer, scale, &mut diagnostics)? {
365 assembly.products[0].bodies.push(built.clone());
366 assembly.products[0].appearances.push(BodyAppearance { body: color, faces: faces.clone() });
367 }
368 }
369 }
370 for body in free_shell_bodies(&file, scale, &mut diagnostics)? {
371 assembly.products[0].bodies.push(body.solid);
372 assembly.products[0].appearances.push(BodyAppearance { body: body.color, faces: body.faces });
373 }
374 assembly.sheets_skipped = diagnostics.counters.get(crate::step_import::SHEETS_SKIPPED).copied().unwrap_or(0) as usize;
375 let mut products: HashMap<i64, usize> = HashMap::default();
376 for pointer in top_instances {
377 add_instance(&file, scale, pointer, 0, &mut assembly, &mut products, (&mut cache, &mut sets), &mut diagnostics, 0)?;
378 }
379 Ok(Some(assembly))
380}
381
382fn root_only_assembly(file: &IgesFile) -> StepAssembly {
384 let root_name = {
385 let product = file.global.product_id.trim();
386 if product.is_empty() { "IGES".to_string() } else { product.to_string() }
387 };
388 StepAssembly {
389 products: vec![StepProduct {
390 pd_ref: 0,
391 name: root_name,
392 id: String::new(),
393 bodies: Vec::new(),
394 appearances: Vec::new(),
395 failed_bodies: 0,
396 pmi: None,
397 }],
398 occurrences: Vec::new(),
399 roots: vec![0],
400 first_error: None,
401 pmi: None,
402 pmi_diagnostics: Vec::new(),
403 sheets_skipped: 0,
404 }
405}
406
407fn face_set_assembly(file: &IgesFile, scale: f64, top_instances: Vec<i64>) -> Result<StepAssembly, String> {
411 let mut diagnostics = crate::KernelDiagnostics::default();
412 let placed = structure::placed_face_sets(file, scale)?;
413 let loose = loose_set_solids(file, scale, &mut diagnostics)?;
414 let mut sets = SetCache::default();
415 let mut any = !loose.is_empty();
416 for each in &placed {
417 for solid in subfigure_set_solids(&mut sets, file, each.solid, scale, &mut diagnostics)? {
422 place(solid, &each.placement)?;
423 any = true;
424 }
425 }
426 if !any {
427 return Err(nothing_to_import(file));
428 }
429 let mut assembly = root_only_assembly(file);
430 for solid in loose {
431 assembly.products[0].bodies.push(solid);
432 assembly.products[0].appearances.push(BodyAppearance { body: None, faces: Vec::new() });
433 }
434 let mut cache = SolidCache::default();
435 let mut products: HashMap<i64, usize> = HashMap::default();
436 for pointer in top_instances {
437 add_instance(file, scale, pointer, 0, &mut assembly, &mut products, (&mut cache, &mut sets), &mut diagnostics, 0)?;
438 }
439 Ok(assembly)
440}
441
442#[allow(clippy::too_many_arguments)]
446fn add_instance(
447 file: &IgesFile,
448 scale: f64,
449 pointer: i64,
450 parent: usize,
451 assembly: &mut StepAssembly,
452 products: &mut HashMap<i64, usize>,
453 (cache, sets): (&mut SolidCache, &mut SetCache),
454 diagnostics: &mut crate::KernelDiagnostics,
455 depth: usize,
456) -> Result<(), String> {
457 if depth > 64 {
458 return Err(format!("iges_import: instance DE {pointer} nests deeper than 64 levels"));
459 }
460 let instance = file.entity(pointer)?;
461 let (definition_pointer, definition) = structure::instanced_subfigure(file, pointer)?;
462 let child = match products.get(&definition_pointer) {
463 Some(&index) => index,
464 None => {
465 let index = assembly.products.len();
466 products.insert(definition_pointer, index);
467 assembly.products.push(StepProduct {
468 pd_ref: definition_pointer as usize,
469 name: structure::entity_name(file, definition).unwrap_or_else(|| format!("subfigure#{definition_pointer}")),
470 id: String::new(),
471 bodies: Vec::new(),
472 appearances: Vec::new(),
473 failed_bodies: 0,
474 pmi: None,
475 });
476 let color = structure::entity_color(file, definition);
478 for solid in subfigure_set_solids(sets, file, definition_pointer, scale, diagnostics)?.to_vec() {
479 assembly.products[index].bodies.push(solid);
480 assembly.products[index].appearances.push(BodyAppearance { body: color, faces: Vec::new() });
481 }
482 for member in structure::subfigure_members(definition)? {
483 let entity = file.entity(member)?;
484 match entity.de.entity_type {
485 186 => {
486 let color = structure::entity_color(file, entity);
487 let built = built_solid(cache, file, member, scale, diagnostics)?.to_vec();
488 let product = &mut assembly.products[index];
489 for (solid, faces) in built {
490 product.bodies.push(solid);
491 product.appearances.push(BodyAppearance { body: color, faces });
492 }
493 }
494 408 => add_instance(
495 file,
496 scale,
497 member,
498 index,
499 assembly,
500 products,
501 (&mut *cache, &mut *sets),
502 diagnostics,
503 depth + 1,
504 )?,
505 _ => {}
506 }
507 }
508 index
509 }
510 };
511 let placement = structure::instance_matrix(file, instance, scale)?;
512 let rigid = crate::AffineTransform::new(placement).is_ok_and(|transform| transform.is_rigid(1e-9));
513 let (color, body_colors) = match structure::entity_color(file, instance) {
519 None => (None, Vec::new()),
520 Some(own) if !coloured_below(file, definition_pointer, 0)? => (Some(own), Vec::new()),
521 Some(own) => {
522 let bodies: Vec<Option<crate::ImportedColor>> = assembly.products[child]
523 .appearances
524 .iter()
525 .map(|appearance| appearance.body.is_none().then_some(own))
526 .collect();
527 let any = bodies.iter().any(Option::is_some);
528 (None, if any { bodies } else { Vec::new() })
529 }
530 };
531 assembly.occurrences.push(StepOccurrence {
532 edge_ref: pointer as usize,
533 parent,
534 child,
535 designator: structure::entity_name(file, instance).unwrap_or_else(|| format!("instance#{pointer}")),
536 placement,
537 rigid,
538 color,
539 body_colors,
540 });
541 Ok(())
542}
543
544fn coloured_below(file: &IgesFile, definition_pointer: i64, depth: usize) -> Result<bool, String> {
548 if depth > 64 {
549 return Err(format!("iges_import: subfigure DE {definition_pointer} nests deeper than 64 levels"));
550 }
551 let definition = file.entity(definition_pointer)?;
552 if structure::entity_color(file, definition).is_some() {
553 return Ok(true);
554 }
555 for member in structure::subfigure_members(definition)? {
556 let entity = file.entity(member)?;
557 match entity.de.entity_type {
558 186 if structure::entity_color(file, entity).is_some() => return Ok(true),
559 408 => {
560 if structure::entity_color(file, entity).is_some() {
561 return Ok(true);
562 }
563 let (inner, _) = structure::instanced_subfigure(file, member)?;
564 if coloured_below(file, inner, depth + 1)? {
565 return Ok(true);
566 }
567 }
568 _ => {}
569 }
570 }
571 Ok(false)
572}
573
574fn merge_diagnostics(into: &mut crate::KernelDiagnostics, from: crate::KernelDiagnostics) {
577 into.events.extend(from.events);
578 for (key, count) in from.counters {
579 *into.counters.entry(key).or_insert(0) += count;
580 }
581 for (key, value) in from.measurements {
582 let slot = into.measurements.entry(key).or_insert(value);
583 if value > *slot {
584 *slot = value;
585 }
586 }
587}
588
589fn face_set_solids(
593 file: &IgesFile,
594 scale: f64,
595 surfaces: &[i64],
596) -> Result<(Vec<BrepSolid>, Vec<crate::KernelDiagnostics>), String> {
597 let sets = analyse_face_sets(file, scale, surfaces)?;
598 let as_sheets = crate::switch!("BREP_IGES_OPEN_SHEETS", true);
602 let mut sheets = Vec::new();
603 let mut sheet_readings = Vec::new();
604 let mut closed = Vec::with_capacity(sets.bodies.len());
605 for body in &sets.bodies {
606 match sets.open_reason(body) {
607 None => closed.push(body.as_slice()),
608 Some(reason) if !as_sheets => return Err(reason),
609 Some(reason) => {
610 let (sheet, readings) = face_set_sheet(&sets, file, scale, body).map_err(|error| format!("{reason}; as a sheet: {error}"))?;
611 sheets.push(sheet);
612 sheet_readings.push(readings);
613 }
614 }
615 }
616 let mut built = Vec::with_capacity(closed.len());
617 for body in &closed {
618 built.push(face_set_body(&sets, file, scale, body, &[])?);
619 }
620 let reach: Vec<_> = built.iter().map(|body| brep_topology::recentre::solid_bounds(&body.solid)).collect();
626 let corners: Vec<_> = built.iter().map(|body| vertex_box(&body.solid)).collect();
627 let mut containers: Vec<Vec<usize>> = vec![Vec::new(); built.len()];
628 for inner in 0..built.len() {
629 for outer in 0..built.len() {
630 let fits = |axis: fn(Vec3) -> f64| {
631 axis(corners[inner].0) >= axis(reach[outer].minimum) && axis(corners[inner].1) <= axis(reach[outer].maximum)
632 };
633 if inner != outer
634 && fits(|p| p.x)
635 && fits(|p| p.y)
636 && fits(|p| p.z)
637 && inside(&built[inner].solid, &built[outer].solid)?
638 {
639 containers[inner].push(outer);
640 }
641 }
642 }
643 let mut cavities: Vec<Vec<usize>> = vec![Vec::new(); built.len()];
644 let mut is_cavity = vec![false; built.len()];
645 for inner in 0..built.len() {
646 let depth = containers[inner].len();
647 if depth % 2 == 1 {
648 if let Some(&parent) = containers[inner].iter().find(|&&outer| containers[outer].len() == depth - 1) {
649 cavities[parent].push(inner);
650 is_cavity[inner] = true;
651 }
652 }
653 }
654 let mut solids = Vec::with_capacity(built.len());
655 let mut measured = Vec::with_capacity(built.len());
656 for index in 0..built.len() {
657 if is_cavity[index] {
658 continue;
659 }
660 if cavities[index].is_empty() {
661 solids.push(built[index].solid.clone());
662 measured.push(built[index].diagnostics.clone());
663 continue;
664 }
665 let voids: Vec<(&[usize], bool)> = cavities[index].iter().map(|&cavity| (closed[cavity], !built[cavity].flip)).collect();
666 let with_cavities = face_set_body(&sets, file, scale, closed[index], &voids)?;
667 solids.push(with_cavities.solid);
668 measured.push(with_cavities.diagnostics);
669 }
670 solids.extend(sheets);
671 measured.extend(sheet_readings);
672 Ok((solids, measured))
673}
674
675fn face_set_sheet(
679 sets: &FaceSets,
680 file: &IgesFile,
681 scale: f64,
682 body: &[usize],
683) -> Result<(BrepSolid, crate::KernelDiagnostics), String> {
684 let mut first_failure = None;
685 for split in [false, true] {
686 let text = sets.to_step_sheet(file, scale, body, split)?;
687 let built = step_report(&text, true).and_then(|report| {
688 if report.failed > 0 || report.solids.len() != 1 {
689 return Err(format!(
690 "iges_import: {}",
691 report.first_error.as_deref().unwrap_or("the sheet did not build as one body")
692 ));
693 }
694 Ok(report)
695 });
696 match built {
697 Ok(mut report) => {
698 let sheet = report.solids.remove(0);
699 collapsed_face_refusal(&sheet)?;
700 return Ok((sheet, report.diagnostics));
701 }
702 Err(error) => {
703 first_failure.get_or_insert(error);
704 }
705 }
706 }
707 Err(first_failure.unwrap_or_default())
708}
709
710struct BuiltBody {
711 solid: BrepSolid,
712 flip: bool,
713 diagnostics: crate::KernelDiagnostics,
714}
715
716fn face_set_body(
720 sets: &FaceSets,
721 file: &IgesFile,
722 scale: f64,
723 body: &[usize],
724 voids: &[(&[usize], bool)],
725) -> Result<BuiltBody, String> {
726 let mut first_failure = None;
727 for split in [false, true] {
728 for flip in [false, true] {
729 let text = sets.to_step(file, scale, body, voids, flip, split)?;
730 match solids_or_refusal(&text) {
731 Ok((mut solids, diagnostics)) if solids.len() == 1 => {
732 let (solid, _) = solids.remove(0);
738 let sign = crate::solid_signed_volume_for_sign(&solid, 0.0).or_else(|_| crate::solid_signed_volume(&solid))?;
739 if sign > 0.0 {
740 return Ok(BuiltBody { solid, flip, diagnostics });
741 }
742 }
743 Ok(_) => {}
744 Err(error) => {
745 first_failure.get_or_insert(error);
746 }
747 }
748 }
749 }
750 Err(first_failure.unwrap_or_else(|| {
751 format!("iges_import: a set of {} trimmed surfaces built no solid with positive volume", body.len())
752 }))
753}
754
755fn vertex_box(solid: &BrepSolid) -> (Vec3, Vec3) {
758 let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
759 let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
760 for vertex in &solid.vertices {
761 let p = vertex.point;
762 low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
763 high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
764 }
765 (low, high)
766}
767
768fn inside(inner: &BrepSolid, outer: &BrepSolid) -> Result<bool, String> {
773 const READINGS: usize = 16;
774 let count = inner.vertices.len();
775 if count == 0 {
776 return Ok(false);
777 }
778 let step = count.div_ceil(READINGS).max(1);
779 for vertex in inner.vertices.iter().step_by(step) {
780 if crate::classify_point(vertex.point, outer, 1e-6)?.class != crate::PointClass::In {
781 return Ok(false);
782 }
783 }
784 Ok(true)
785}
786
787fn free_shells(file: &IgesFile) -> Result<Vec<i64>, String> {
790 let mut used_shells: rustc_hash::FxHashSet<i64> = Default::default();
791 for (_, solid) in file.pointers_of_type(186) {
792 used_shells.insert(solid.int(0)?);
793 for index in 0..solid.int(2)?.max(0) as usize {
794 used_shells.insert(solid.int(3 + index * 2)?);
795 }
796 }
797 Ok(file
798 .pointers_of_type(514)
799 .into_iter()
800 .map(|(pointer, _)| pointer)
801 .filter(|pointer| !used_shells.contains(pointer))
802 .collect())
803}
804
805fn refuse_uncovered_geometry(file: &IgesFile) -> Result<(), String> {
808 let free_faces = [144, 143]
809 .iter()
810 .flat_map(|&kind| file.pointers_of_type(kind))
811 .filter(|(_, entity)| entity.de.subordinate == 0)
812 .count();
813 if free_faces > 0 {
814 return Err(format!(
815 "iges_import: the file holds {free_faces} trimmed surface(s) outside its solids, which this import cannot build yet; importing the solids alone would leave them out"
816 ));
817 }
818 Ok(())
819}
820
821fn free_shell_bodies(
826 file: &IgesFile,
827 scale: f64,
828 diagnostics: &mut crate::KernelDiagnostics,
829) -> Result<Vec<Body>, String> {
830 let mut bodies = Vec::new();
831 for pointer in free_shells(file)? {
832 let entity = file.entity(pointer)?;
833 let whole_text = free_shell_to_step(file, pointer, scale, false)?;
834 let report = match surface_model_report(&whole_text) {
835 Ok(report) => report,
836 Err(first_failure) => {
837 let split_text = free_shell_to_step(file, pointer, scale, true)?;
838 if split_text == whole_text {
839 return Err(format!("shell DE {pointer}: {first_failure}"));
840 }
841 surface_model_report(&split_text).map_err(|_| format!("shell DE {pointer}: {first_failure}"))?
842 }
843 };
844 if report.solids.is_empty() && report.sheets_skipped == 0 {
845 diagnostics.count_n(crate::step_import::SHEETS_SKIPPED, 1);
848 }
849 let faces = face_colors(&report);
850 merge_diagnostics(diagnostics, report.diagnostics);
851 for (solid, faces) in report.solids.into_iter().zip(faces) {
852 bodies.push(Body {
853 solid,
854 name: structure::entity_name(file, entity),
855 color: structure::entity_color(file, entity),
856 faces,
857 level: entity.de.level,
858 });
859 }
860 }
861 Ok(bodies)
862}
863
864fn surface_model_report(step: &str) -> Result<crate::StepImportReport, String> {
867 let report = step_report(step, false)?;
868 if report.failed > 0 {
869 return Err(format!(
870 "iges_import: {}",
871 report.first_error.as_deref().unwrap_or("the shell did not import")
872 ));
873 }
874 for solid in &report.solids {
875 collapsed_face_refusal(solid)?;
876 }
877 Ok(report)
878}
879
880fn manifold_solid(file: &IgesFile, pointer: i64, scale: f64) -> Result<Built, String> {
885 let whole_text = manifold_solid_to_step(file, pointer, scale, false)?;
886 let first_failure = match solids_or_refusal(&whole_text) {
887 Ok(built) => return Ok(built),
888 Err(error) => error,
889 };
890 let split_text = manifold_solid_to_step(file, pointer, scale, true)?;
891 if split_text == whole_text {
892 return Err(format!("solid DE {pointer}: {first_failure}"));
893 }
894 solids_or_refusal(&split_text).map_err(|_| format!("solid DE {pointer}: {first_failure}"))
895}
896
897type Built = (Vec<(BrepSolid, FaceColors)>, crate::KernelDiagnostics);
903
904fn face_colors(report: &crate::StepImportReport) -> Vec<FaceColors> {
908 report
909 .solids
910 .iter()
911 .enumerate()
912 .map(|(index, solid)| {
913 let faces: usize = solid.shells.iter().map(|shell| shell.faces.len()).sum();
914 match report.appearances.get(index) {
915 Some(appearance) if appearance.faces.len() == faces && appearance.faces.iter().any(Option::is_some) => {
916 appearance.faces.clone()
917 }
918 _ => Vec::new(),
919 }
920 })
921 .collect()
922}
923
924fn solids_or_refusal(step: &str) -> Result<Built, String> {
925 let report = step_report(step, false)?;
926 if report.failed > 0 {
927 return Err(format!(
928 "iges_import: {}",
929 report.first_error.as_deref().unwrap_or("the body did not import")
930 ));
931 }
932 if report.solids.is_empty() {
933 return Err("iges_import: the solid produced no body".into());
934 }
935 for solid in &report.solids {
936 collapsed_face_refusal(solid)?;
937 }
938 let faces = face_colors(&report);
939 Ok((report.solids.into_iter().zip(faces).collect(), report.diagnostics))
940}
941
942const COLLAPSED_FACE_RATIO: f64 = 1e-5;
946
947fn collapsed_face_refusal(solid: &BrepSolid) -> Result<(), String> {
956 let screen = crate::switch!("BREP_IGES_AREA_SCREEN", true);
957 let mut readings = [0usize; 3]; let outcome = collapsed_face_scan(solid, screen, &mut readings);
959 if crate::profile::profile_enabled() {
960 profile_line!("iges.area_screen screened={} unread={} short={}", readings[0], readings[1], readings[2]);
961 }
962 outcome
963}
964
965fn collapsed_face_scan(solid: &BrepSolid, screen: bool, readings: &mut [usize; 3]) -> Result<(), String> {
966 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
967 let Ok(length) = crate::face_boundary_length(solid, face) else {
968 continue;
969 };
970 if screen {
971 match boundary_vector_area(face) {
972 Some((vector_area, error)) if vector_area - error > AREA_SCREEN_MARGIN * COLLAPSED_FACE_RATIO * length * length => {
973 readings[0] += 1;
974 continue;
975 }
976 Some(_) => readings[2] += 1,
977 None => readings[1] += 1,
978 }
979 }
980 let Ok(area) = crate::face_area(face) else {
981 continue;
982 };
983 if length > 0.0 && area < COLLAPSED_FACE_RATIO * length * length {
984 return Err(format!(
985 "iges_import: a face collapsed on import, enclosing {area:.3e} mm2 inside a boundary {length:.3e} mm long"
986 ));
987 }
988 }
989 Ok(())
990}
991
992const AREA_SCREEN_MARGIN: f64 = 10.0;
996
997const AREA_SCREEN_CHORDS: usize = 16;
1000
1001fn pcurve_stations(pcurve: &crate::NurbsCurve) -> Option<Vec<f64>> {
1007 let [start, end] = pcurve.domain().ok()?;
1008 if !(start.is_finite() && end.is_finite() && end > start) {
1009 return None;
1010 }
1011 let mut breaks = vec![start];
1012 for &knot in &pcurve.knots {
1013 if knot > breaks[breaks.len() - 1] && knot < end {
1014 breaks.push(knot);
1015 }
1016 }
1017 breaks.push(end);
1018 let mut stations = vec![start];
1019 for span in breaks.windows(2) {
1020 let share = (AREA_SCREEN_CHORDS as f64 * (span[1] - span[0]) / (end - start)).ceil() as usize;
1021 let chords = share.max(2);
1022 for chord in 0..chords {
1023 let at = |fraction: f64| span[0] + (span[1] - span[0]) * fraction;
1024 stations.push(at((chord as f64 + 0.5) / chords as f64));
1025 stations.push(if chord + 1 == chords { span[1] } else { at((chord + 1) as f64 / chords as f64) });
1026 }
1027 }
1028 Some(stations)
1029}
1030
1031const AREA_SCREEN_AGREEMENT: f64 = 1e-2;
1035
1036const AREA_SCREEN_JOINT: f64 = 1e-3;
1040
1041pub(super) fn boundary_vector_area(face: &crate::topology::FaceRecord) -> Option<(f64, f64)> {
1060 let image = |uv: Vec3| -> Option<Vec3> {
1061 let point = face.surface.evaluate(uv.x, uv.y).ok()?;
1062 (point.x.is_finite() && point.y.is_finite() && point.z.is_finite()).then_some(point)
1063 };
1064 let polynomial = face.loops.iter().flat_map(|loop_record| &loop_record.coedges).all(|coedge| {
1067 let first = coedge.pcurve.control_points.first().map_or(1.0, |point| point.w);
1068 first.is_finite() && first != 0.0 && coedge.pcurve.control_points.iter().all(|point| (point.w - first).abs() <= 1e-12 * first.abs())
1069 });
1070 if !polynomial {
1071 return None;
1072 }
1073 let mut origin = None;
1074 let mut sum = Vec3::new(0.0, 0.0, 0.0);
1075 let mut error = 0.0;
1076 let mut winding = 0.0;
1077 let mut sampled = 0.0;
1081 for loop_record in &face.loops {
1082 let mut polygon: Vec<Vec<Vec3>> = Vec::with_capacity(loop_record.coedges.len());
1084 for coedge in &loop_record.coedges {
1085 let stations = pcurve_stations(&coedge.pcurve)?
1086 .into_iter()
1087 .map(|t| coedge.pcurve.evaluate(t).ok())
1088 .collect::<Option<Vec<_>>>()?;
1089 polygon.push(stations);
1090 }
1091 let (mut low, mut high) = (Vec3::new(f64::INFINITY, f64::INFINITY, 0.0), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, 0.0));
1092 for uv in polygon.iter().flatten() {
1093 low = Vec3::new(low.x.min(uv.x), low.y.min(uv.y), 0.0);
1094 high = Vec3::new(high.x.max(uv.x), high.y.max(uv.y), 0.0);
1095 }
1096 let joint = AREA_SCREEN_JOINT * high.sub(low).length();
1097 for (index, stations) in polygon.iter().enumerate() {
1098 let next = &polygon[(index + 1) % polygon.len()];
1099 let end = stations[stations.len() - 1];
1100 if !(end.sub(next[0]).length() <= joint) {
1101 return None;
1102 }
1103 for pair in stations.windows(2) {
1104 sampled += 0.5 * (pair[0].x * pair[1].y - pair[0].y * pair[1].x);
1105 }
1106 winding += 0.5 * (end.x * next[0].y - end.y * next[0].x);
1107 }
1108 let mut last: Option<Vec3> = None;
1111 let mut first = None;
1112 for stations in &polygon {
1113 let mut previous = image(stations[0])?;
1114 let origin = *origin.get_or_insert(previous);
1115 first.get_or_insert(previous);
1116 if let Some(end) = last {
1117 sum = sum.add(end.sub(origin).cross(previous.sub(origin)));
1118 }
1119 for chord in stations[1..].chunks(2) {
1120 let (arc, next) = (image(chord[0])?, image(chord[1])?);
1121 let sag = arc.sub(previous.add(next).scale(0.5)).length();
1122 error += 2.0 * next.sub(previous).length() * sag;
1123 sum = sum.add(previous.sub(origin).cross(next.sub(origin)));
1124 previous = next;
1125 }
1126 last = Some(previous);
1127 }
1128 if let (Some(start), Some(end), Some(origin)) = (first, last, origin) {
1129 sum = sum.add(end.sub(origin).cross(start.sub(origin)));
1130 }
1131 }
1132 let exact = crate::parameter_space_area(face).ok()?;
1133 if !((sampled - exact).abs() <= AREA_SCREEN_AGREEMENT * exact.abs()) {
1134 return None;
1135 }
1136 winding += sampled;
1137 let length = 0.5 * sum.length();
1138 (winding > 0.0 && length.is_finite() && error.is_finite()).then_some((length, error))
1139}