Skip to main content

brep_kernel/io/iges/
import.rs

1//! IGES to kernel `BrepSolid`, by way of the STEP importer.
2//!
3//! Solids (186) and trimmed-surface sets (144, 143) are translated to Part 21
4//! ([`super::to_step`]) so they get the STEP builder, closure gate and refusals.
5//! Anything that cannot be read correctly is refused by name; a file never
6//! imports short.
7
8use crate::topology::BrepSolid;
9use crate::{BodyAppearance, StepAssembly, StepOccurrence, StepProduct};
10use rustc_hash::FxHashMap as HashMap;
11
12use super::reader::{parse_iges, IgesFile};
13use super::structure::{self, Matrix, Placed};
14use super::to_step::{analyse_face_sets, free_shell_to_step, manifold_solid_to_step, trimmed_surfaces, FaceSets};
15
16/// Parse an IGES document and reconstruct one or more `BrepSolid`s.
17pub fn import_iges(text: &str) -> Result<Vec<BrepSolid>, String> {
18    Ok(import_iges_report(text)?.solids)
19}
20
21/// What [`import_iges_report`] returns: the solids, and the diagnostics the
22/// STEP lane measured while building them, merged over every body.
23#[derive(Clone, Debug)]
24pub struct IgesImportReport {
25    /// The solids, in file order: solids standing on their own, then each
26    /// subfigure instance's (408), placed.
27    pub solids: Vec<BrepSolid>,
28    /// Each solid's name (its 406 name property, else its directory label, else
29    /// the name of the instance that placed it), parallel to `solids`; empty
30    /// when the file gives none.
31    pub names: Vec<String>,
32    /// Each solid's colour (314, or the directory colour number), parallel to
33    /// `solids`, in the shape the STEP lane returns colours in.
34    pub appearances: Vec<BodyAppearance>,
35    /// Each solid's level (layer) number from its directory entry, parallel to
36    /// `solids`; 0 when unset, negative for a 406 list of levels.
37    pub levels: Vec<i64>,
38    /// The file's stated minimum resolution in mm (Global field 19), when it
39    /// states one.
40    pub stated_resolution_mm: Option<f64>,
41    /// Measurements and warnings, as `import_step_report` gives for STEP:
42    /// stated-precision consistency, bounded trims, closure readings.
43    pub diagnostics: crate::KernelDiagnostics,
44}
45
46/// [`import_iges`] with the import's diagnostics, the IGES counterpart of
47/// [`crate::import_step_report`].
48pub fn import_iges_report(text: &str) -> Result<IgesImportReport, String> {
49    let file = parse_iges(text)?;
50    let scale = file.global.length_scale_mm()?;
51    let stated = file.global.min_resolution * scale;
52    let mut diagnostics = crate::KernelDiagnostics::default();
53    let bodies = solids_with_diagnostics(&file, scale, &mut diagnostics)?;
54    let mut report = IgesImportReport {
55        solids: Vec::with_capacity(bodies.len()),
56        names: Vec::with_capacity(bodies.len()),
57        appearances: Vec::with_capacity(bodies.len()),
58        levels: Vec::with_capacity(bodies.len()),
59        stated_resolution_mm: (stated > 0.0 && stated.is_finite()).then_some(stated),
60        diagnostics,
61    };
62    for body in bodies {
63        report.solids.push(body.solid);
64        report.names.push(body.name.unwrap_or_default());
65        report.appearances.push(BodyAppearance { body: body.color, faces: body.faces });
66        report.levels.push(body.level);
67    }
68    Ok(report)
69}
70
71/// One imported solid and what the file said about it.
72struct Body {
73    solid: BrepSolid,
74    name: Option<String>,
75    color: Option<crate::ImportedColor>,
76    /// Each face's own colour in shell/face order, or empty when no face of
77    /// the body has one.
78    faces: FaceColors,
79    level: i64,
80}
81
82impl Body {
83    fn bare(solid: BrepSolid) -> Self {
84        Self { solid, name: None, color: None, faces: Vec::new(), level: 0 }
85    }
86}
87
88/// A body's per-face colours, as [`BodyAppearance::faces`] holds them.
89type FaceColors = Vec<Option<crate::ImportedColor>>;
90
91/// Each 186 built once, through the STEP lane, in its definition frame, with
92/// the colours its faces carry.
93type SolidCache = HashMap<i64, Vec<(BrepSolid, FaceColors)>>;
94
95/// Each subfigure's (308) trimmed-surface sets, sewn once in its own frame,
96/// keyed by the 308.
97type SetCache = HashMap<i64, Vec<BrepSolid>>;
98
99fn built_solid<'c>(
100    cache: &'c mut SolidCache,
101    file: &IgesFile,
102    pointer: i64,
103    scale: f64,
104    diagnostics: &mut crate::KernelDiagnostics,
105) -> Result<&'c [(BrepSolid, FaceColors)], String> {
106    if !cache.contains_key(&pointer) {
107        let (built, measured) = manifold_solid(file, pointer, scale)?;
108        merge_diagnostics(diagnostics, measured);
109        cache.insert(pointer, built);
110    }
111    Ok(&cache[&pointer])
112}
113
114/// A built solid moved by a placement; a mirroring placement turns it inside
115/// out unless the orientation is reversed with it.
116pub(super) fn place(solid: &BrepSolid, placement: &Matrix) -> Result<BrepSolid, String> {
117    if structure::is_identity(placement) {
118        return Ok(solid.clone());
119    }
120    let transform = crate::AffineTransform::new(*placement)?;
121    let mirrored = transform.determinant3() < 0.0;
122    crate::transform_brep(solid, transform, mirrored)
123}
124
125fn solids_with_diagnostics(
126    file: &IgesFile,
127    scale: f64,
128    diagnostics: &mut crate::KernelDiagnostics,
129) -> Result<Vec<Body>, String> {
130    // A file with explicit solids or shells goes down the STEP lane whole: same
131    // builder, same closure gate, same refusals. A solid a subfigure defines
132    // comes in once per instance, where the instance puts it; a shell no solid
133    // uses comes in as the STEP lane reads a surface model.
134    if file.entities_of_type(186).next().is_some() || file.entities_of_type(514).next().is_some() {
135        refuse_uncovered_geometry(file)?;
136        let mut cache = SolidCache::default();
137        let mut bodies = Vec::new();
138        for Placed { solid, placement, name, color, level } in structure::placed_solids(file, scale)? {
139            for (built, faces) in built_solid(&mut cache, file, solid, scale, diagnostics)? {
140                bodies.push(Body { solid: place(built, &placement)?, name: name.clone(), color, faces: faces.clone(), level });
141            }
142        }
143        bodies.extend(free_shell_bodies(file, scale, diagnostics)?);
144        if bodies.is_empty() {
145            let sheets = diagnostics.counters.get(crate::step_import::SHEETS_SKIPPED).copied().unwrap_or(0);
146            return Err(format!(
147                "iges_import: the file has no solids: its {sheets} shell(s) are sheets (open, or a single untrimmed face), not solids"
148            ));
149        }
150        return Ok(bodies);
151    }
152    // A file of trimmed surfaces whose subfigures are placed: the file's own
153    // sets, then each instance's sets where it puts them.
154    if file.entities_of_type(408).next().is_some() {
155        let bodies = placed_face_set_bodies(file, scale, diagnostics)?;
156        if bodies.is_empty() {
157            return Err(nothing_to_import(file));
158        }
159        return Ok(bodies);
160    }
161
162    if file.entities_of_type(144).next().is_none() && file.entities_of_type(143).next().is_none() {
163        return Err(nothing_to_import(file));
164    }
165    let (solids, measured) = face_set_solids(file, scale, &trimmed_surfaces(file))?;
166    for each in measured {
167        merge_diagnostics(diagnostics, each);
168    }
169    Ok(solids.into_iter().map(Body::bare).collect())
170}
171
172/// Why a file without solids or sewable surfaces imports nothing.
173fn nothing_to_import(file: &IgesFile) -> String {
174    if file.entities_of_type(144).next().is_none()
175        && file.entities_of_type(143).next().is_none()
176        && file.entities_of_type(128).next().is_some()
177    {
178        return "iges_import: file has untrimmed B-spline surfaces (entity 128) but no trimmed surfaces (entity 144) to form faces"
179            .into();
180    }
181    "iges_import: the file has no solids (186) or trimmed surfaces (144, 143) to import".into()
182}
183
184/// The trimmed surfaces no subfigure (308) lists: the file's own, in
185/// directory order.
186fn loose_surfaces(file: &IgesFile) -> Result<Vec<i64>, String> {
187    let members = structure::subfigure_member_set(file)?;
188    Ok(trimmed_surfaces(file).into_iter().filter(|pointer| !members.contains(pointer)).collect())
189}
190
191/// The file's own surface sets sewn into solids, refused as the flat import
192/// of a file without subfigures refuses them.
193fn loose_set_solids(
194    file: &IgesFile,
195    scale: f64,
196    diagnostics: &mut crate::KernelDiagnostics,
197) -> Result<Vec<BrepSolid>, String> {
198    let loose = loose_surfaces(file)?;
199    if loose.is_empty() {
200        return Ok(Vec::new());
201    }
202    let (solids, measured) = face_set_solids(file, scale, &loose)?;
203    for each in measured {
204        merge_diagnostics(diagnostics, each);
205    }
206    Ok(solids)
207}
208
209/// The solids a subfigure's (308) own trimmed surfaces sew into, in its own
210/// frame, built once however many instances place it. A set that does not
211/// sew refuses the file, naming the subfigure.
212fn subfigure_set_solids<'c>(
213    cache: &'c mut SetCache,
214    file: &IgesFile,
215    pointer: i64,
216    scale: f64,
217    diagnostics: &mut crate::KernelDiagnostics,
218) -> Result<&'c [BrepSolid], String> {
219    if !cache.contains_key(&pointer) {
220        let mut surfaces = Vec::new();
221        for member in structure::subfigure_members(file.entity(pointer)?)? {
222            if matches!(file.entity(member)?.de.entity_type, 144 | 143) {
223                surfaces.push(member);
224            }
225        }
226        surfaces.sort_unstable();
227        surfaces.dedup();
228        let mut solids = Vec::new();
229        if !surfaces.is_empty() {
230            let (built, measured) =
231                face_set_solids(file, scale, &surfaces).map_err(|error| format!("subfigure DE {pointer}: {error}"))?;
232            for each in measured {
233                merge_diagnostics(diagnostics, each);
234            }
235            solids = built;
236        }
237        cache.insert(pointer, solids);
238    }
239    Ok(&cache[&pointer])
240}
241
242/// A file of trimmed surfaces with subfigure instances, flattened: the
243/// file's own sets, then each instance's sets placed, in file order.
244fn placed_face_set_bodies(
245    file: &IgesFile,
246    scale: f64,
247    diagnostics: &mut crate::KernelDiagnostics,
248) -> Result<Vec<Body>, String> {
249    // The structure's refusals come before any sewing.
250    let placed = structure::placed_face_sets(file, scale)?;
251    let mut bodies: Vec<Body> = loose_set_solids(file, scale, diagnostics)?.into_iter().map(Body::bare).collect();
252    let mut cache = SetCache::default();
253    for Placed { solid: definition, placement, name, color, level } in placed {
254        for built in subfigure_set_solids(&mut cache, file, definition, scale, diagnostics)? {
255            bodies.push(Body { solid: place(built, &placement)?, name: name.clone(), color, faces: Vec::new(), level });
256        }
257    }
258    Ok(bodies)
259}
260
261/// The file's subfigure structure, the IGES counterpart of
262/// [`crate::read_step_assembly`]: one product for the file itself holding the
263/// solids that stand on their own, one per instanced subfigure (308) holding
264/// its own solids in its own frame, and one occurrence per instance (408) with
265/// its placement in millimetres. `Ok(None)` when the file places no
266/// subfigures, so the caller takes the flat import as for STEP.
267///
268/// A file of trimmed surfaces (144, 143) without solids reads the same way:
269/// each instanced subfigure's product holds the solids its own surfaces sew
270/// into, and the root product the file's own sets.
271///
272/// Every solid is built once, as in the flat import, and a file the flat
273/// import refuses is refused here with the same words: an assembly never
274/// comes in short.
275pub fn read_iges_assembly(text: &str) -> Result<Option<StepAssembly>, String> {
276    let file = parse_iges(text)?;
277    let members = structure::subfigure_member_set(&file)?;
278    let top_instances: Vec<i64> = file
279        .pointers_of_type(408)
280        .into_iter()
281        .map(|(pointer, _)| pointer)
282        .filter(|pointer| !members.contains(pointer))
283        .collect();
284    if top_instances.is_empty() {
285        return Ok(None);
286    }
287    // The flat import's checks and refusals, once, before any structure.
288    let scale = file.global.length_scale_mm()?;
289    if file.entities_of_type(186).next().is_none() && file.entities_of_type(514).next().is_none() {
290        return face_set_assembly(&file, scale, top_instances).map(Some);
291    }
292    if file.entities_of_type(186).next().is_none() {
293        return Err(
294            "iges_import: the file places subfigures (408) of trimmed surfaces, which this import cannot build yet"
295                .into(),
296        );
297    }
298    refuse_uncovered_geometry(&file)?;
299    structure::placed_solids(&file, scale)?;
300
301    let mut cache = SolidCache::default();
302    let mut sets = SetCache::default();
303    let mut diagnostics = crate::KernelDiagnostics::default();
304    let mut assembly = root_only_assembly(&file);
305    for (pointer, solid) in file.pointers_of_type(186) {
306        if !members.contains(&pointer) {
307            let color = structure::entity_color(&file, solid);
308            for (built, faces) in built_solid(&mut cache, &file, pointer, scale, &mut diagnostics)? {
309                assembly.products[0].bodies.push(built.clone());
310                assembly.products[0].appearances.push(BodyAppearance { body: color, faces: faces.clone() });
311            }
312        }
313    }
314    for body in free_shell_bodies(&file, scale, &mut diagnostics)? {
315        assembly.products[0].bodies.push(body.solid);
316        assembly.products[0].appearances.push(BodyAppearance { body: body.color, faces: body.faces });
317    }
318    assembly.sheets_skipped = diagnostics.counters.get(crate::step_import::SHEETS_SKIPPED).copied().unwrap_or(0) as usize;
319    let mut products: HashMap<i64, usize> = HashMap::default();
320    for pointer in top_instances {
321        add_instance(&file, scale, pointer, 0, &mut assembly, &mut products, (&mut cache, &mut sets), &mut diagnostics, 0)?;
322    }
323    Ok(Some(assembly))
324}
325
326/// The assembly with only its root product, the file itself, and nothing in it.
327fn root_only_assembly(file: &IgesFile) -> StepAssembly {
328    let root_name = {
329        let product = file.global.product_id.trim();
330        if product.is_empty() { "IGES".to_string() } else { product.to_string() }
331    };
332    StepAssembly {
333        products: vec![StepProduct {
334            pd_ref: 0,
335            name: root_name,
336            id: String::new(),
337            bodies: Vec::new(),
338            appearances: Vec::new(),
339            failed_bodies: 0,
340            pmi: None,
341        }],
342        occurrences: Vec::new(),
343        roots: vec![0],
344        first_error: None,
345        pmi: None,
346        pmi_diagnostics: Vec::new(),
347        sheets_skipped: 0,
348    }
349}
350
351/// [`read_iges_assembly`] for a file of trimmed surfaces: every set the flat
352/// import would sew is sewn first, in the flat import's order, so a file it
353/// refuses is refused here with the same words before any structure.
354fn face_set_assembly(file: &IgesFile, scale: f64, top_instances: Vec<i64>) -> Result<StepAssembly, String> {
355    let mut diagnostics = crate::KernelDiagnostics::default();
356    let placed = structure::placed_face_sets(file, scale)?;
357    let loose = loose_set_solids(file, scale, &mut diagnostics)?;
358    let mut sets = SetCache::default();
359    let mut any = !loose.is_empty();
360    for each in &placed {
361        // Each instance placed as the flat import places it, so a placement it
362        // cannot apply (singular, or one taking the geometry out of range) is
363        // refused here with its words, not carried as an occurrence that
364        // cannot be built.
365        for solid in subfigure_set_solids(&mut sets, file, each.solid, scale, &mut diagnostics)? {
366            place(solid, &each.placement)?;
367            any = true;
368        }
369    }
370    if !any {
371        return Err(nothing_to_import(file));
372    }
373    let mut assembly = root_only_assembly(file);
374    for solid in loose {
375        assembly.products[0].bodies.push(solid);
376        assembly.products[0].appearances.push(BodyAppearance { body: None, faces: Vec::new() });
377    }
378    let mut cache = SolidCache::default();
379    let mut products: HashMap<i64, usize> = HashMap::default();
380    for pointer in top_instances {
381        add_instance(file, scale, pointer, 0, &mut assembly, &mut products, (&mut cache, &mut sets), &mut diagnostics, 0)?;
382    }
383    Ok(assembly)
384}
385
386/// One 408 as an occurrence under `parent`, its subfigure as a product (added
387/// once, however many instances place it), and the subfigure's own instances
388/// beneath it.
389#[allow(clippy::too_many_arguments)]
390fn add_instance(
391    file: &IgesFile,
392    scale: f64,
393    pointer: i64,
394    parent: usize,
395    assembly: &mut StepAssembly,
396    products: &mut HashMap<i64, usize>,
397    (cache, sets): (&mut SolidCache, &mut SetCache),
398    diagnostics: &mut crate::KernelDiagnostics,
399    depth: usize,
400) -> Result<(), String> {
401    if depth > 64 {
402        return Err(format!("iges_import: instance DE {pointer} nests deeper than 64 levels"));
403    }
404    let instance = file.entity(pointer)?;
405    let (definition_pointer, definition) = structure::instanced_subfigure(file, pointer)?;
406    let child = match products.get(&definition_pointer) {
407        Some(&index) => index,
408        None => {
409            let index = assembly.products.len();
410            products.insert(definition_pointer, index);
411            assembly.products.push(StepProduct {
412                pd_ref: definition_pointer as usize,
413                name: structure::entity_name(file, definition).unwrap_or_else(|| format!("subfigure#{definition_pointer}")),
414                id: String::new(),
415                bodies: Vec::new(),
416                appearances: Vec::new(),
417                failed_bodies: 0,
418                pmi: None,
419            });
420            // The subfigure's own trimmed surfaces, sewn in its frame.
421            let color = structure::entity_color(file, definition);
422            for solid in subfigure_set_solids(sets, file, definition_pointer, scale, diagnostics)?.to_vec() {
423                assembly.products[index].bodies.push(solid);
424                assembly.products[index].appearances.push(BodyAppearance { body: color, faces: Vec::new() });
425            }
426            for member in structure::subfigure_members(definition)? {
427                let entity = file.entity(member)?;
428                match entity.de.entity_type {
429                    186 => {
430                        let color = structure::entity_color(file, entity);
431                        let built = built_solid(cache, file, member, scale, diagnostics)?.to_vec();
432                        let product = &mut assembly.products[index];
433                        for (solid, faces) in built {
434                            product.bodies.push(solid);
435                            product.appearances.push(BodyAppearance { body: color, faces });
436                        }
437                    }
438                    408 => add_instance(
439                        file,
440                        scale,
441                        member,
442                        index,
443                        assembly,
444                        products,
445                        (&mut *cache, &mut *sets),
446                        diagnostics,
447                        depth + 1,
448                    )?,
449                    _ => {}
450                }
451            }
452            index
453        }
454    };
455    let placement = structure::instance_matrix(file, instance, scale)?;
456    let rigid = crate::AffineTransform::new(placement).is_ok_and(|transform| transform.is_rigid(1e-9));
457    // An instance's colour in IGES is INHERITED: a body's or an inner
458    // instance's own colour wins over it, as the flat import reads it. As a
459    // whole-instance colour (which colours everything the instance places) it
460    // is given only where nothing beneath is coloured on its own; otherwise it
461    // goes to the child's own uncoloured bodies alone.
462    let (color, body_colors) = match structure::entity_color(file, instance) {
463        None => (None, Vec::new()),
464        Some(own) if !coloured_below(file, definition_pointer, 0)? => (Some(own), Vec::new()),
465        Some(own) => {
466            let bodies: Vec<Option<crate::ImportedColor>> = assembly.products[child]
467                .appearances
468                .iter()
469                .map(|appearance| appearance.body.is_none().then_some(own))
470                .collect();
471            let any = bodies.iter().any(Option::is_some);
472            (None, if any { bodies } else { Vec::new() })
473        }
474    };
475    assembly.occurrences.push(StepOccurrence {
476        edge_ref: pointer as usize,
477        parent,
478        child,
479        designator: structure::entity_name(file, instance).unwrap_or_else(|| format!("instance#{pointer}")),
480        placement,
481        rigid,
482        color,
483        body_colors,
484    });
485    Ok(())
486}
487
488/// Whether anything a subfigure places carries a colour of its own: the
489/// subfigure itself (its surface sets take it), a member solid, or a member
490/// instance, at any depth.
491fn coloured_below(file: &IgesFile, definition_pointer: i64, depth: usize) -> Result<bool, String> {
492    if depth > 64 {
493        return Err(format!("iges_import: subfigure DE {definition_pointer} nests deeper than 64 levels"));
494    }
495    let definition = file.entity(definition_pointer)?;
496    if structure::entity_color(file, definition).is_some() {
497        return Ok(true);
498    }
499    for member in structure::subfigure_members(definition)? {
500        let entity = file.entity(member)?;
501        match entity.de.entity_type {
502            186 if structure::entity_color(file, entity).is_some() => return Ok(true),
503            408 => {
504                if structure::entity_color(file, entity).is_some() {
505                    return Ok(true);
506                }
507                let (inner, _) = structure::instanced_subfigure(file, member)?;
508                if coloured_below(file, inner, depth + 1)? {
509                    return Ok(true);
510                }
511            }
512            _ => {}
513        }
514    }
515    Ok(false)
516}
517
518/// Fold one body's diagnostics into the file's: events and counts add up, and
519/// each measurement keeps its worst reading, as `measure_max` does.
520fn merge_diagnostics(into: &mut crate::KernelDiagnostics, from: crate::KernelDiagnostics) {
521    into.events.extend(from.events);
522    for (key, count) in from.counters {
523        *into.counters.entry(key).or_insert(0) += count;
524    }
525    for (key, value) in from.measurements {
526        let slot = into.measurements.entry(key).or_insert(value);
527        if value > *slot {
528            *slot = value;
529        }
530    }
531}
532
533/// Build trimmed surfaces (`surfaces`, in directory order) into solids: one
534/// solid per connected, closed set of faces, and a set lying inside another
535/// becomes its cavity.
536fn face_set_solids(
537    file: &IgesFile,
538    scale: f64,
539    surfaces: &[i64],
540) -> Result<(Vec<BrepSolid>, Vec<crate::KernelDiagnostics>), String> {
541    let sets = analyse_face_sets(file, scale, surfaces)?;
542    for body in &sets.bodies {
543        if let Some(reason) = sets.open_reason(body) {
544            return Err(reason);
545        }
546    }
547    let mut built = Vec::with_capacity(sets.bodies.len());
548    for body in &sets.bodies {
549        built.push(face_set_body(&sets, file, scale, body, &[])?);
550    }
551    // Largest first, so a cavity is always tested against what can hold it.
552    let mut order: Vec<usize> = (0..built.len()).collect();
553    order.sort_by(|&a, &b| built[b].volume.total_cmp(&built[a].volume));
554    let mut cavities: Vec<Vec<usize>> = vec![Vec::new(); built.len()];
555    let mut is_cavity = vec![false; built.len()];
556    for (rank, &inner) in order.iter().enumerate() {
557        for &outer in &order[..rank] {
558            if !is_cavity[outer] && inside(&built[inner].solid, &built[outer].solid)? {
559                cavities[outer].push(inner);
560                is_cavity[inner] = true;
561                break;
562            }
563        }
564    }
565    let mut solids = Vec::with_capacity(built.len());
566    let mut measured = Vec::with_capacity(built.len());
567    for index in 0..built.len() {
568        if is_cavity[index] {
569            continue;
570        }
571        if cavities[index].is_empty() {
572            solids.push(built[index].solid.clone());
573            measured.push(built[index].diagnostics.clone());
574            continue;
575        }
576        let voids: Vec<(&[usize], bool)> = cavities[index]
577            .iter()
578            .map(|&cavity| (sets.bodies[cavity].as_slice(), !built[cavity].flip))
579            .collect();
580        let with_cavities = face_set_body(&sets, file, scale, &sets.bodies[index], &voids)?;
581        solids.push(with_cavities.solid);
582        measured.push(with_cavities.diagnostics);
583    }
584    Ok((solids, measured))
585}
586
587struct BuiltBody {
588    solid: BrepSolid,
589    volume: f64,
590    flip: bool,
591    diagnostics: crate::KernelDiagnostics,
592}
593
594/// One closed face set through the STEP lane, in whichever sense gives it a
595/// positive volume; a twice-walked edge is read as written first.
596fn face_set_body(
597    sets: &FaceSets,
598    file: &IgesFile,
599    scale: f64,
600    body: &[usize],
601    voids: &[(&[usize], bool)],
602) -> Result<BuiltBody, String> {
603    let mut first_failure = None;
604    for split in [false, true] {
605        for flip in [false, true] {
606            let text = sets.to_step(file, scale, body, voids, flip, split)?;
607            match solids_or_refusal(&text) {
608                Ok((mut solids, diagnostics)) if solids.len() == 1 => {
609                    // A set of trimmed surfaces carries no face colours here.
610                    let (solid, _) = solids.remove(0);
611                    let volume = crate::solid_signed_volume(&solid)?;
612                    if volume > 0.0 {
613                        return Ok(BuiltBody { solid, volume, flip, diagnostics });
614                    }
615                }
616                Ok(_) => {}
617                Err(error) => {
618                    first_failure.get_or_insert(error);
619                }
620            }
621        }
622    }
623    Err(first_failure.unwrap_or_else(|| {
624        format!("iges_import: a set of {} trimmed surfaces built no solid with positive volume", body.len())
625    }))
626}
627
628/// Whether `inner` lies inside `outer`, judged at one vertex.
629fn inside(inner: &BrepSolid, outer: &BrepSolid) -> Result<bool, String> {
630    let Some(vertex) = inner.vertices.first() else {
631        return Ok(false);
632    };
633    let reading = crate::classify_point(vertex.point, outer, 1e-6)?;
634    Ok(reading.class == crate::PointClass::In)
635}
636
637/// The 514 shells no 186 uses, in file order. An OCC-written file carries a
638/// STEP SHELL_BASED_SURFACE_MODEL this way.
639fn free_shells(file: &IgesFile) -> Result<Vec<i64>, String> {
640    let mut used_shells: rustc_hash::FxHashSet<i64> = Default::default();
641    for (_, solid) in file.pointers_of_type(186) {
642        used_shells.insert(solid.int(0)?);
643        for index in 0..solid.int(2)?.max(0) as usize {
644            used_shells.insert(solid.int(3 + index * 2)?);
645        }
646    }
647    Ok(file
648        .pointers_of_type(514)
649        .into_iter()
650        .map(|(pointer, _)| pointer)
651        .filter(|pointer| !used_shells.contains(pointer))
652        .collect())
653}
654
655/// Refuse a file holding trimmed surfaces beside its solids. Importing only
656/// the solids would drop them and look like a complete import.
657fn refuse_uncovered_geometry(file: &IgesFile) -> Result<(), String> {
658    let free_faces = [144, 143]
659        .iter()
660        .flat_map(|&kind| file.pointers_of_type(kind))
661        .filter(|(_, entity)| entity.de.subordinate == 0)
662        .count();
663    if free_faces > 0 {
664        return Err(format!(
665            "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"
666        ));
667    }
668    Ok(())
669}
670
671/// Each free shell through the STEP lane: a closed shell of several faces as
672/// the solid a 186 would make of it, refused by name if it fails as one; a
673/// sheet (open, or a single untrimmed face) is not a solid and is counted in
674/// `SHEETS_SKIPPED`, never dropped silently.
675fn free_shell_bodies(
676    file: &IgesFile,
677    scale: f64,
678    diagnostics: &mut crate::KernelDiagnostics,
679) -> Result<Vec<Body>, String> {
680    let mut bodies = Vec::new();
681    for pointer in free_shells(file)? {
682        let entity = file.entity(pointer)?;
683        let whole_text = free_shell_to_step(file, pointer, scale, false)?;
684        let report = match surface_model_report(&whole_text) {
685            Ok(report) => report,
686            Err(first_failure) => {
687                let split_text = free_shell_to_step(file, pointer, scale, true)?;
688                if split_text == whole_text {
689                    return Err(format!("shell DE {pointer}: {first_failure}"));
690                }
691                surface_model_report(&split_text).map_err(|_| format!("shell DE {pointer}: {first_failure}"))?
692            }
693        };
694        if report.solids.is_empty() && report.sheets_skipped == 0 {
695            // The STEP lane skips a single-face surface model as reference
696            // geometry without counting it; here it is counted with the sheets.
697            diagnostics.count_n(crate::step_import::SHEETS_SKIPPED, 1);
698        }
699        let faces = face_colors(&report);
700        merge_diagnostics(diagnostics, report.diagnostics);
701        for (solid, faces) in report.solids.into_iter().zip(faces) {
702            bodies.push(Body {
703                solid,
704                name: structure::entity_name(file, entity),
705                color: structure::entity_color(file, entity),
706                faces,
707                level: entity.de.level,
708            });
709        }
710    }
711    Ok(bodies)
712}
713
714/// A surface model through the STEP lane: what it built, refusing a shell that
715/// reached the solid builder and failed there.
716fn surface_model_report(step: &str) -> Result<crate::StepImportReport, String> {
717    let report = crate::import_step_report(step).map_err(|error| format!("iges_import: {error}"))?;
718    if report.failed > 0 {
719        return Err(format!(
720            "iges_import: {}",
721            report.first_error.as_deref().unwrap_or("the shell did not import")
722        ));
723    }
724    for solid in &report.solids {
725        collapsed_face_refusal(solid)?;
726    }
727    Ok(report)
728}
729
730/// One 186 through the STEP lane. A twice-walked edge on a quadric is told apart
731/// by its position; elsewhere it is read as written first, because it is usually
732/// a seam the builder handles, and as a bridge (`split_at_repeated_edges`) only
733/// when that reading is refused. The first refusal is the one reported.
734fn manifold_solid(file: &IgesFile, pointer: i64, scale: f64) -> Result<Built, String> {
735    let whole_text = manifold_solid_to_step(file, pointer, scale, false)?;
736    let first_failure = match solids_or_refusal(&whole_text) {
737        Ok(built) => return Ok(built),
738        Err(error) => error,
739    };
740    let split_text = manifold_solid_to_step(file, pointer, scale, true)?;
741    if split_text == whole_text {
742        return Err(format!("solid DE {pointer}: {first_failure}"));
743    }
744    solids_or_refusal(&split_text).map_err(|_| format!("solid DE {pointer}: {first_failure}"))
745}
746
747/// Import translated STEP, refusing when the body did not build. The STEP lane
748/// skips a body that fails with text and returns the rest, but a file that
749/// comes in short looks like a complete import.
750/// Solids that built, each with its faces' colours, and the diagnostics the
751/// STEP lane measured on them.
752type Built = (Vec<(BrepSolid, FaceColors)>, crate::KernelDiagnostics);
753
754/// Each built solid's per-face colours as the STEP lane paired them: one list
755/// per solid, as long as its faces where any face has a colour, else empty.
756/// A list of another length is not a pairing and is dropped.
757fn face_colors(report: &crate::StepImportReport) -> Vec<FaceColors> {
758    report
759        .solids
760        .iter()
761        .enumerate()
762        .map(|(index, solid)| {
763            let faces: usize = solid.shells.iter().map(|shell| shell.faces.len()).sum();
764            match report.appearances.get(index) {
765                Some(appearance) if appearance.faces.len() == faces && appearance.faces.iter().any(Option::is_some) => {
766                    appearance.faces.clone()
767                }
768                _ => Vec::new(),
769            }
770        })
771        .collect()
772}
773
774fn solids_or_refusal(step: &str) -> Result<Built, String> {
775    let report = crate::import_step_report(step).map_err(|error| format!("iges_import: {error}"))?;
776    if report.failed > 0 {
777        return Err(format!(
778            "iges_import: {}",
779            report.first_error.as_deref().unwrap_or("the body did not import")
780        ));
781    }
782    if report.solids.is_empty() {
783        return Err("iges_import: the solid produced no body".into());
784    }
785    for solid in &report.solids {
786        collapsed_face_refusal(solid)?;
787    }
788    let faces = face_colors(&report);
789    Ok((report.solids.into_iter().zip(faces).collect(), report.diagnostics))
790}
791
792/// Area over boundary length squared below which a face has collapsed. Measured
793/// on foreign files: collapsed faces read a few times 1e-6. A 1 mm by 100 mm
794/// sliver reads 2.4e-3 and a 0.01 by 100 one 2.5e-5, so real faces clear it.
795const COLLAPSED_FACE_RATIO: f64 = 1e-5;
796
797/// A face with a real boundary that encloses almost nothing is a loop the
798/// builder read the wrong way round the carrier. It validates, and the solid
799/// then quietly lacks that face, so it is refused here.
800fn collapsed_face_refusal(solid: &BrepSolid) -> Result<(), String> {
801    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
802        let (Ok(area), Ok(length)) = (crate::face_area(face), crate::face_boundary_length(solid, face)) else {
803            continue;
804        };
805        if length > 0.0 && area < COLLAPSED_FACE_RATIO * length * length {
806            return Err(format!(
807                "iges_import: a face collapsed on import, enclosing {area:.3e} mm2 inside a boundary {length:.3e} mm long"
808            ));
809        }
810    }
811    Ok(())
812}