Preserve imported part names and IGES assembly structure (#1609)

Build on #1426's import components and nested STEP assembly instances.
Replace placeholder solid labels with meaningful part or instance names.
Translate IGES groups and subfigure instances through the existing STEP
component path, preserving nesting and placements and sewing surfaces
within each group. Bound assembly walks and reuse work buffers.

Related to:
- tangency-labs/solidcraft#1386
- tangency-labs/solidcraft#1426

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Luke Jones
2026-10-21 00:39:08 +00:00
committed by GitHub
parent 2f43ad5c5b
commit 26c0c19ef7
10 changed files with 571 additions and 90 deletions
+54 -57
View File
@@ -9,6 +9,8 @@
use std::collections::HashMap;
use std::fmt::Write as _;
mod assembly;
/// Largest IGES file we read.
pub const MAX_IGES_BYTES: usize = 512 << 20;
const MAX_ENTITIES: usize = 2_000_000;
@@ -1240,77 +1242,42 @@ fn translate(text: &str) -> std::result::Result<(String, Vec<String>), String> {
// Entities used by others (a B-rep's faces, a trimmed surface's curves) are not roots;
// physically dependent entities have status digits 01 in columns 3–4, but files are lax:
// collect references instead.
let mut solids: Vec<(u64, String)> = Vec::new();
let assembly = assembly::Assembly::read(&t, &seqs)?;
let mut solids = HashMap::new();
let mut styles: Vec<(u64, [f32; 3])> = Vec::new();
let mut n = 0usize;
let mut fallback = String::new();
let watch = crate::watch::current();
for &s in &seqs {
if watch.as_ref().is_some_and(|w| w.cancelled()) {
return Err("IGES import cancelled".into());
}
let Some(de) = f.des.get(&s) else { continue };
if de.typ != 186 {
continue;
}
n += 1;
// A name property (406 form 15) among the solid's trailing pointers, else the label.
let named = f.params.get(&s).and_then(|p| {
p.iter().skip(4).filter_map(|x| int(x)).filter(|x| *x > 0).find_map(|ptr| {
let d = f.des.get(&usize::try_from(ptr).ok()?)?;
(d.typ == 406 && d.form == 15).then(|| f.params.get(&usize::try_from(ptr).ok()?)?.get(2).cloned()).flatten()
})
});
let name = match named.filter(|x| !x.trim().is_empty()) {
Some(x) => x.trim().to_string(),
None if de.label.is_empty() => format!("Body{n}"),
None => de.label.clone(),
let name = if let Some(name) = assembly::entity_name(&f, s) {
name
} else {
fallback.clear();
let _ = write!(fallback, "Body{n}");
fallback.as_str()
};
match brep(&mut t, s as i64, &mut styles) {
Ok((id, color)) => {
let named = {
// Re-label the solid with its name.
let line = t.o.lines.get(id as usize - 1).cloned().unwrap_or_default();
line.replacen("('',", &format!("('{}',", name.replace('\'', "''")), 1)
};
if let Some(l) = t.o.lines.get_mut(id as usize - 1) {
*l = named;
*l = l.replacen("('',", &format!("('{}',", name.replace('\'', "''")), 1);
}
if let Some(c) = color {
styles.push((id, c));
}
solids.push((id, name));
solids.insert(s, id);
}
Err(e) => t.warn(format!("solid {name}: not read: {e}")),
}
}
// Trimmed and bounded surfaces not used by anything else: sewn into shells.
let mut faces = Vec::new();
let mut sw = Sewer { tol, verts: Vec::new(), grid: HashMap::new(), edges: Vec::new(), by_ends: HashMap::new() };
if solids.is_empty() {
for &s in &seqs {
let Some(de) = f.des.get(&s) else { continue };
if de.typ != 144 && de.typ != 143 && !(de.typ == 128 && is_root(&f, s)) {
continue;
}
match trimmed(&mut t, &mut sw, s as i64) {
Ok(fb) => faces.push(fb),
Err(e) => t.warn(format!("surface {s}: not read: {e}")),
}
}
if !faces.is_empty() {
orient(&mut faces);
let (shell, closed) = write_shell(&mut t.o, &sw, &faces, &mut styles);
let item = if closed {
t.o.add(format!("MANIFOLD_SOLID_BREP('Body1',#{shell})"))
} else {
t.warn("the surfaces do not close into a solid: imported as an open body");
t.o.add(format!("SHELL_BASED_SURFACE_MODEL('Body1',(#{shell}))"))
};
solids.push((item, "Body1".into()));
}
}
if solids.is_empty() {
let why = t.warnings.first().cloned().unwrap_or_else(|| "no solids or trimmed surfaces".into());
return Err(format!("IGES import: nothing to read ({why})"));
}
let items = solids.iter().map(|(i, _)| format!("#{i}")).collect::<Vec<_>>().join(",");
t.o.add(format!("ADVANCED_BREP_SHAPE_REPRESENTATION('',({items}),#{ctx})"));
assembly.write(&mut t, &seqs, &solids, &mut styles, ctx)?;
for (item, c) in styles {
let rgb = t.o.add(format!("COLOUR_RGB('',{},{},{})", r(c[0] as f64), r(c[1] as f64), r(c[2] as f64)));
let fasc = t.o.add(format!("FILL_AREA_STYLE_COLOUR('',#{rgb})"));
@@ -1331,12 +1298,42 @@ fn translate(text: &str) -> std::result::Result<(String, Vec<String>), String> {
Ok((s, t.warnings))
}
/// A surface entity nobody refers to (a bare B-spline patch is a face of its own).
fn is_root(f: &Iges, seq: usize) -> bool {
let target = seq.to_string();
!f.params
.iter()
.any(|(s, p)| *s != seq && f.des.get(s).is_some_and(|d| d.typ != 406 && d.typ != 402) && p.iter().skip(1).any(|x| x.trim() == target))
/// Sew surfaces within their owning group, keeping different parts separate.
fn sew_surfaces(
t: &mut Tr,
seqs: impl Iterator<Item = usize>,
name: &str,
styles: &mut Vec<(u64, [f32; 3])>,
faces: &mut Vec<FaceB>,
sw: &mut Sewer,
) -> R<Option<u64>> {
faces.clear();
sw.verts.clear();
sw.grid.clear();
sw.edges.clear();
sw.by_ends.clear();
let watch = crate::watch::current();
for seq in seqs {
if watch.as_ref().is_some_and(|w| w.cancelled()) {
return Err("IGES import cancelled".into());
}
match trimmed(t, sw, seq as i64) {
Ok(face) => faces.push(face),
Err(e) => t.warn(format!("surface {seq}: not read: {e}")),
}
}
if faces.is_empty() {
return Ok(None);
}
orient(faces);
let (shell, closed) = write_shell(&mut t.o, sw, faces, styles);
let name = name.replace('\'', "''");
Ok(Some(if closed {
t.o.add(format!("MANIFOLD_SOLID_BREP('{name}',#{shell})"))
} else {
t.warn("the surfaces do not close into a solid: imported as an open body");
t.o.add(format!("SHELL_BASED_SURFACE_MODEL('{name}',(#{shell}))"))
}))
}
/// A trimmed (144) or bounded (143) surface, or a bare B-spline surface, as a face.
+280
View File
@@ -0,0 +1,280 @@
//! IGES groups (402) and subfigures (308/408), from the published IGES specification.
//! Definitions become STEP products; instances refer to them without copying geometry.
//! Reference: https://nvlpubs.nist.gov/nistpubs/Legacy/IR/nbsir88-3813.pdf
use super::*;
use std::collections::HashSet;
const MAX_GROUPS: usize = 10_000;
const MAX_INSTANCES: usize = 100_000;
const MAX_REFERENCES: usize = 4 * MAX_ENTITIES;
struct Group {
seq: usize,
members: Vec<usize>,
}
struct Instance {
definition: usize,
transform: Xf,
}
pub(super) struct Assembly {
groups: Vec<Group>,
indices: HashMap<usize, usize>,
instances: HashMap<usize, Instance>,
referenced: HashSet<usize>,
surface_references: HashSet<usize>,
}
impl Assembly {
pub(super) fn read(t: &Tr, seqs: &[usize]) -> R<Self> {
let mut out = Self {
groups: Vec::new(),
indices: HashMap::new(),
instances: HashMap::new(),
referenced: HashSet::new(),
surface_references: HashSet::new(),
};
let mut references = 0usize;
let watch = crate::watch::current();
for &seq in seqs {
if watch.as_ref().is_some_and(|w| w.cancelled()) {
return Err("IGES import cancelled".into());
}
let de = t.de(seq as i64)?;
if de.typ == 308 || (de.typ == 402 && matches!(de.form, 1 | 7 | 14 | 15)) {
if out.groups.len() >= MAX_GROUPS {
return Err("too many IGES assembly definitions".into());
}
let field = if de.typ == 308 { 3 } else { 1 };
let count = usize::try_from(t.i(seq as i64, field)?).map_err(|_| "negative IGES group size")?;
references = references.saturating_add(count);
if count > MAX_LIST || references > MAX_REFERENCES {
return Err("IGES assembly references exceed the work limit".into());
}
let p = t.p(seq as i64)?;
let entries = p.get(field + 1..field + 1 + count).ok_or("truncated IGES group")?;
let mut members = Vec::with_capacity(count);
for entry in entries {
let child = int(entry).and_then(|x| usize::try_from(x).ok()).filter(|x| *x > 0).ok_or("invalid IGES group reference")?;
t.de(child as i64)?;
members.push(child);
out.referenced.insert(child);
}
out.indices.insert(seq, out.groups.len());
out.groups.push(Group { seq, members });
} else if de.typ == 408 {
if out.instances.len() >= MAX_INSTANCES {
return Err("too many IGES assembly instances".into());
}
let definition = usize::try_from(t.i(seq as i64, 1)?).map_err(|_| "invalid IGES subfigure reference")?;
if t.de(definition as i64)?.typ != 308 {
return Err("IGES instance does not refer to a subfigure definition".into());
}
let p = t.p(seq as i64)?;
let scale = match p.get(5).map(|s| s.trim()) {
None | Some("") => 1.0,
Some(s) => num(s).filter(|x| *x != 0.0).ok_or("invalid IGES instance scale")?,
};
let [x, y, z] = t.pt(seq as i64, 2)?;
let local = Xf([[scale, 0.0, 0.0, x], [0.0, scale, 0.0, y], [0.0, 0.0, scale, z]]);
let transform = t.own_xf(seq as i64, 0)?.then(&local).then(&t.own_xf(definition as i64, 0)?);
if !transform.0.iter().flatten().all(|v| v.is_finite()) {
return Err("non-finite IGES instance placement".into());
}
out.instances.insert(seq, Instance { definition, transform });
out.referenced.insert(definition);
}
}
// Index geometry references once instead of rescanning all parameters for each patch.
for (&seq, params) in &t.f.params {
if watch.as_ref().is_some_and(|w| w.cancelled()) {
return Err("IGES import cancelled".into());
}
if t.f.des.get(&seq).is_some_and(|d| matches!(d.typ, 308 | 402 | 406 | 408)) {
continue;
}
for p in params.iter().skip(1) {
let p = p.trim();
if p.starts_with('0') {
continue;
}
if let Ok(id) = p.parse::<usize>()
&& id != seq
&& t.f.des.get(&id).is_some_and(|d| d.typ == 128)
{
out.surface_references.insert(id);
}
}
}
let mut depths = HashMap::with_capacity(out.groups.len());
let mut placements = out.groups.iter().filter(|g| !out.referenced.contains(&g.seq)).count()
+ out.instances.keys().filter(|s| !out.referenced.contains(*s)).count();
for group in &out.groups {
placements += group.members.iter().filter(|s| out.indices.contains_key(*s) || out.instances.contains_key(*s)).count();
if placements > MAX_INSTANCES {
return Err("too many IGES assembly placements".into());
}
out.depth(group.seq, 0, &mut depths)?;
}
Ok(out)
}
fn depth(&self, seq: usize, depth: usize, seen: &mut HashMap<usize, Option<usize>>) -> R<usize> {
if depth >= MAX_DEPTH {
return Err("IGES assembly nesting is too deep".into());
}
if let Some(height) = seen.get(&seq) {
return height.ok_or_else(|| "cyclic IGES assembly".into());
}
seen.insert(seq, None);
let group = self.indices.get(&seq).and_then(|i| self.groups.get(*i)).ok_or("missing IGES assembly definition")?;
let mut height = 1;
for child in &group.members {
let definition = self.instances.get(child).map(|i| i.definition).unwrap_or(*child);
if self.indices.contains_key(&definition) {
height = height.max(1 + self.depth(definition, depth + 1, seen)?);
}
}
if height > MAX_DEPTH {
return Err("IGES assembly nesting is too deep".into());
}
seen.insert(seq, Some(height));
Ok(height)
}
pub(super) fn write(&self, t: &mut Tr, seqs: &[usize], solids: &HashMap<usize, u64>, styles: &mut Vec<(u64, [f32; 3])>, ctx: u64) -> R<()> {
let app = t.o.add("APPLICATION_CONTEXT('mechanical design')");
let pc = t.o.add(format!("PRODUCT_CONTEXT('',#{app},'mechanical')"));
let dc = t.o.add(format!("PRODUCT_DEFINITION_CONTEXT('part definition',#{app},'design')"));
let origin = t.o.placement([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]);
let mut products = HashMap::with_capacity(self.groups.len() + 1);
let mut items = Vec::new();
let mut list = String::new();
let mut fallback = String::new();
let mut made = 0usize;
let f = t.f;
let mut faces = Vec::new();
let mut sewer = Sewer { tol: t.tol, verts: Vec::new(), grid: HashMap::new(), edges: Vec::new(), by_ends: HashMap::new() };
let watch = crate::watch::current();
// A synthetic root holds loose geometry and top-level groups/instances.
for group in std::iter::once(None).chain(self.groups.iter().map(Some)) {
if watch.as_ref().is_some_and(|w| w.cancelled()) {
return Err("IGES import cancelled".into());
}
let seq = group.map(|g| g.seq).unwrap_or(0);
let name = if seq == 0 {
"Import"
} else if let Some(name) = entity_name(f, seq) {
name
} else {
fallback.clear();
let _ = write!(fallback, "Group {seq}");
fallback.as_str()
};
items.clear();
let members = group.map(|g| g.members.as_slice()).unwrap_or(seqs);
items.extend(members.iter().filter(|s| seq != 0 || !self.referenced.contains(*s)).filter_map(|s| solids.get(s).copied()));
let surfaces = members
.iter()
.copied()
.filter(|s| seq != 0 || !self.referenced.contains(s))
.filter(|s| f.des.get(s).is_some_and(|d| matches!(d.typ, 143 | 144) || (d.typ == 128 && !self.surface_references.contains(s))));
if let Some(item) = sew_surfaces(t, surfaces, if seq == 0 { "Body1" } else { name }, styles, &mut faces, &mut sewer)? {
items.push(item);
}
made += items.len();
list.clear();
let _ = write!(list, "#{origin}");
for item in &items {
let _ = write!(list, ",#{item}");
}
let rep = t.o.add(format!("ADVANCED_BREP_SHAPE_REPRESENTATION('',({list}),#{ctx})"));
let name = name.replace('\'', "''");
let product = t.o.add(format!("PRODUCT('{name}','{name}','',(#{pc}))"));
let formation = t.o.add(format!("PRODUCT_DEFINITION_FORMATION('','',#{product})"));
let pd = t.o.add(format!("PRODUCT_DEFINITION('design','',#{formation},#{dc})"));
let shape = t.o.add(format!("PRODUCT_DEFINITION_SHAPE('','',#{pd})"));
t.o.add(format!("SHAPE_DEFINITION_REPRESENTATION(#{shape},#{rep})"));
products.insert(seq, (pd, rep));
}
if made == 0 {
let why = t.warnings.first().map(String::as_str).unwrap_or("no solids or trimmed surfaces");
return Err(format!("IGES import: nothing to read ({why})"));
}
for group in std::iter::once(None).chain(self.groups.iter().map(Some)) {
let parent = group.map(|g| g.seq).unwrap_or(0);
let members = group.map(|g| g.members.as_slice()).unwrap_or(seqs);
for &child in members {
if watch.as_ref().is_some_and(|w| w.cancelled()) {
return Err("IGES import cancelled".into());
}
if parent == 0 && self.referenced.contains(&child) {
continue;
}
let (definition, transform) = match self.instances.get(&child) {
Some(i) => (i.definition, i.transform),
None if self.indices.contains_key(&child) => (child, t.own_xf(child as i64, 0)?),
_ => continue,
};
let (parent_pd, parent_rep) = products.get(&parent).copied().ok_or("missing IGES assembly parent")?;
let (child_pd, child_rep) = products.get(&definition).copied().ok_or("missing IGES assembly child")?;
let label = entity_name(f, child).unwrap_or("").replace('\'', "''");
let nauo = t.o.add(format!("NEXT_ASSEMBLY_USAGE_OCCURRENCE('{child}','{label}','',#{parent_pd},#{child_pd},$)"));
let shape = t.o.add(format!("PRODUCT_DEFINITION_SHAPE('','',#{nauo})"));
let op = transformation(&mut t.o, transform)?;
let rr = t.o.add(format!("(REPRESENTATION_RELATIONSHIP('','',#{child_rep},#{parent_rep})REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION(#{op})SHAPE_REPRESENTATION_RELATIONSHIP())"));
t.o.add(format!("CONTEXT_DEPENDENT_SHAPE_REPRESENTATION(#{rr},#{shape})"));
}
}
Ok(())
}
}
fn transformation(out: &mut Out, xf: Xf) -> R<u64> {
if !xf.0.iter().flatten().all(|v| v.is_finite()) {
return Err("non-finite IGES assembly placement".into());
}
let [x, y, z] = [xf.dir([1.0, 0.0, 0.0]), xf.dir([0.0, 1.0, 0.0]), xf.dir([0.0, 0.0, 1.0])];
let [sx, sy, sz] = [norm(x), norm(y), norm(z)];
let scale = xf.scale();
if [sx, sy, sz, scale].iter().any(|s| !s.is_finite() || *s <= 1e-300) {
return Err("singular IGES assembly placement".into());
}
let (x, y, z, o) = (out.dir(mul(x, 1.0 / sx)), out.dir(mul(y, 1.0 / sy)), out.dir(mul(z, 1.0 / sz)), out.point(xf.point([0.0; 3])));
Ok(out.add(format!("CARTESIAN_TRANSFORMATION_OPERATOR_3D_NON_UNIFORM('','',#{x},#{y},#{o},{},#{z},{},{})", r(sx), r(sy), r(sz))))
}
/// Name properties follow the associativity pointers; member pointers are not properties.
pub(super) fn entity_name(f: &Iges, seq: usize) -> Option<&str> {
let de = f.des.get(&seq)?;
let p = f.params.get(&seq)?;
let count = |i: usize| p.get(i).and_then(|s| int(s)).and_then(|x| usize::try_from(x).ok()).filter(|n| *n <= MAX_LIST);
let end = match de.typ {
186 => count(3)?.checked_mul(2)?.checked_add(4)?,
308 => count(3)?.checked_add(4)?,
402 => count(1)?.checked_add(2)?,
408 => 6,
_ => p.len(),
};
let property = (|| {
let after = end.checked_add(count(end)?)?.checked_add(1)?;
let n = count(after)?;
p.get(after + 1..after + 1 + n)?.iter().find_map(|s| {
let id = int(s).and_then(|x| usize::try_from(x).ok())?;
let d = f.des.get(&id)?;
if d.typ != 406 || d.form != 15 {
return None;
}
f.params.get(&id)?.get(2).and_then(|s| name_text(s))
})
})();
property.or_else(|| if de.typ == 308 { p.get(2).and_then(|s| name_text(s)) } else { None }).or_else(|| name_text(&de.label))
}
/// Match the component-name limit before copying or repeating a shared name property.
fn name_text(s: &str) -> Option<&str> {
let end = s.char_indices().nth(128).map(|(i, _)| i).unwrap_or(s.len());
let name = s.get(..end)?.trim();
(!name.is_empty()).then_some(name)
}
+134 -6
View File
@@ -156,15 +156,116 @@ fn an_arc_revolved_about_its_centre_is_a_cap_not_a_ball() {
assert!(rel(area, cap) < 1e-3, "area {area} vs {cap}");
}
/// A unit-cube-like box (10 × 20 × 30) made of six trimmed bilinear B-spline patches whose
/// boundaries are lines: sewn into a closed solid.
/// An exported box inside a named group and nested subfigures, placed twice. The second
/// placement composes its translation and scale with a directory transformation.
fn assembly_file(form: i64, scale: f64) -> String {
let body = box_solid(Vec3::ZERO, Vec3::new(2.0, 3.0, 4.0)).unwrap();
let text = iges_export_bodies(&[ExportBody { name: "Body1".into(), body: &body, color: None }], &StepHeader::default()).unwrap();
let f = parse(&text).unwrap();
let mut ids: Vec<_> = f.des.keys().copied().collect();
ids.sort_unstable();
let solid = *ids.iter().find(|&&s| f.des[&s].typ == 186).unwrap();
let mut transforms: HashMap<_, _> = f.des.iter().map(|(seq, d)| (*seq, d.xform)).collect();
let mut ents: Vec<_> = ids
.iter()
.enumerate()
.map(|(k, seq)| {
assert_eq!(*seq, 2 * k + 1);
let d = &f.des[seq];
let p = f.params[seq]
.iter()
.skip(1)
.map(|s| if s.is_empty() || num(s).is_some() { s.clone() } else { format!("{}H{s}", s.chars().count()) })
.collect::<Vec<_>>()
.join(",");
(d.typ, d.form, p)
})
.collect();
let definition = 2 * ents.len() + 1;
ents.push((308, 0, format!("0,8HLead rod,1,{solid}")));
let first = 2 * ents.len() + 1;
ents.push((408, 0, format!("{definition},10.,0.,0.,1.")));
let rotation = 2 * ents.len() + 1;
ents.push((124, 0, "0.,-1.,0.,100.,1.,0.,0.,0.,0.,0.,1.,0.".into()));
let second = 2 * ents.len() + 1;
ents.push((408, 0, format!("{definition},0.,20.,0.,{scale}")));
transforms.insert(second, rotation as i64);
let frame = 2 * ents.len() + 1;
ents.push((308, 0, format!("1,5HFrame,2,{first},{second}")));
let property = 2 * ents.len() + 1;
ents.push((406, 15, "1,6HMotion".into()));
ents.push((402, form, format!("1,{frame},0,1,{property}")));
iges_file(&ents)
.lines()
.map(|line| {
if line.as_bytes()[72] != b'D' {
return line.to_string();
}
let seq: usize = line[73..80].trim().parse().unwrap();
match transforms.get(&seq) {
Some(xf) => format!("{}{:>8}{}", &line[..48], xf, &line[56..]),
None => line.to_string(),
}
})
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn trimmed_surfaces_sew_into_a_solid() {
let c =
|i: usize| -> [f64; 3] { [if i & 1 != 0 { 10.0 } else { 0.0 }, if i & 2 != 0 { 20.0 } else { 0.0 }, if i & 4 != 0 { 30.0 } else { 0.0 }] };
fn groups_and_subfigure_instances_keep_names_structure_and_placements() {
for (form, scale) in [(1, 1.0), (7, 2.0), (14, 1.0), (15, 2.0)] {
let imp = iges_import(&assembly_file(form, scale)).unwrap();
assert!(imp.warnings.is_empty(), "{:?}", imp.warnings);
assert_eq!(imp.bodies.len(), 2);
assert_eq!(imp.tree.len(), 1);
let motion = &imp.tree[0].children[0];
assert_eq!(motion.name, "Motion");
let frame = &motion.children[0];
assert_eq!(frame.name, "Frame");
assert_eq!(frame.children.len(), 2);
assert!(frame.children.iter().all(|n| n.name == "Lead rod"));
assert!(imp.bodies.iter().all(|b| b.path == ["Import", "Motion", "Frame", "Lead rod"]));
assert_eq!(imp.bodies[0].source_item, imp.bodies[1].source_item);
let a = measure(&imp.bodies[0].body).unwrap();
let b = measure(&imp.bodies[1].body).unwrap();
assert!(rel(a.volume, 24.0) < 1e-6 && rel(b.volume, 24.0 * scale.powi(3)) < 1e-6);
assert!(a.bbox.min.dist(Vec3::new(10.0, 0.0, 0.0)) < 1e-6 && a.bbox.max.dist(Vec3::new(12.0, 3.0, 4.0)) < 1e-6);
assert!(b.bbox.min.dist(Vec3::new(80.0 - 3.0 * scale, 0.0, 0.0)) < 1e-6);
assert!(b.bbox.max.dist(Vec3::new(80.0, 2.0 * scale, 4.0 * scale)) < 1e-6);
}
}
#[test]
fn invalid_assembly_references_and_counts_fail_before_geometry() {
for (params, message) in [
("0,4HLoop,1,1".into(), "cyclic"),
("0,4HPart,1,999".into(), "missing entity"),
("0,4HPart,-1".into(), "negative IGES group size"),
(format!("0,4HPart,{}", MAX_LIST + 1), "work limit"),
] {
let error = iges_import(&iges_file(&[(308, 0, params)])).unwrap_err();
assert!(matches!(&error, crate::KernelError::Invalid(text) if text.contains(message)), "{error}");
}
let mut chain = Vec::new();
for k in 0..=MAX_DEPTH {
chain.push((308, 0, if k == MAX_DEPTH { "0,4HPart,0".into() } else { format!("0,4HPart,1,{}", 2 * k + 3) }));
}
let error = iges_import(&iges_file(&chain)).unwrap_err();
assert!(matches!(&error, crate::KernelError::Invalid(text) if text.contains("nesting is too deep")), "{error}");
let members = "1,".repeat(100_000);
let many = [(308, 0, "0,4HPart,0".into()), (308, 0, format!("1,5HFrame,100001,{members}1"))];
let error = iges_import(&iges_file(&many)).unwrap_err();
assert!(matches!(&error, crate::KernelError::Invalid(text) if text.contains("too many IGES assembly placements")), "{error}");
}
/// Six trimmed bilinear patches with line boundaries, forming a 10 × 20 × 30 box.
fn trimmed_box(ents: &mut Vec<(i64, i64, String)>, x: f64) -> Vec<usize> {
let c = |i: usize| -> [f64; 3] {
[x + if i & 1 != 0 { 10.0 } else { 0.0 }, if i & 2 != 0 { 20.0 } else { 0.0 }, if i & 4 != 0 { 30.0 } else { 0.0 }]
};
// Faces as corner quads (counter-clockwise seen from outside).
let quads = [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]];
let mut ents: Vec<(i64, i64, String)> = Vec::new();
let mut faces = Vec::new();
let fmt = |p: [f64; 3]| format!("{:?},{:?},{:?}", p[0], p[1], p[2]);
for q in quads {
let (a, b, cc, d) = (c(q[0]), c(q[1]), c(q[2]), c(q[3]));
@@ -182,7 +283,15 @@ fn trimmed_surfaces_sew_into_a_solid() {
ents.push((142, 0, format!("0,{s_de},0,{comp},2")));
let cos = 2 * ents.len() - 1;
ents.push((144, 0, format!("{s_de},1,0,{cos}")));
faces.push(2 * ents.len() - 1);
}
faces
}
#[test]
fn trimmed_surfaces_sew_into_a_solid() {
let mut ents = Vec::new();
trimmed_box(&mut ents, 0.0);
let imp = iges_import(&iges_file(&ents)).unwrap();
assert!(imp.warnings.is_empty(), "{:?}", imp.warnings);
assert!(imp.bodies[0].closed);
@@ -190,6 +299,25 @@ fn trimmed_surfaces_sew_into_a_solid() {
assert!(rel(m.volume, 6000.0) < 1e-6 && rel(m.area, 2200.0) < 1e-6, "{} {}", m.volume, m.area);
}
#[test]
fn surfaces_in_separate_groups_remain_separate_parts() {
let mut ents = Vec::new();
for (name, x) in [("Left", 0.0), ("Right", 100.0)] {
let faces = trimmed_box(&mut ents, x);
let members = faces.iter().map(|s| s.to_string()).collect::<Vec<_>>().join(",");
ents.push((308, 0, format!("0,{}H{name},{},{members}", name.len(), faces.len())));
}
let imp = iges_import(&iges_file(&ents)).unwrap();
assert!(imp.warnings.is_empty(), "{:?}", imp.warnings);
assert_eq!(imp.bodies.len(), 2);
assert_eq!(imp.tree[0].children.iter().map(|n| n.name.as_str()).collect::<Vec<_>>(), ["Left", "Right"]);
for (body, x) in imp.bodies.iter().zip([0.0, 100.0]) {
let m = measure(&body.body).unwrap();
assert!(body.closed && rel(m.volume, 6000.0) < 1e-6 && rel(m.area, 2200.0) < 1e-6);
assert!(m.bbox.min.dist(Vec3::new(x, 0.0, 0.0)) < 1e-6 && m.bbox.max.dist(Vec3::new(x + 10.0, 20.0, 30.0)) < 1e-6);
}
}
#[test]
fn a_drill_point_round_trips_through_iges() {
// A blind hole with a cone tip: the tip's face closes at its apex (its seam runs out to the
+1 -1
View File
@@ -101,7 +101,7 @@ pub(crate) fn point(cx: &Ctx, id: u64) -> R<mt::Point3> {
Ok(mt::Point3::new(g(0)?, g(1)?, g(2)?) * cx.len)
}
fn direction(cx: &Ctx, id: u64) -> R<mt::Vector3> {
pub(super) fn direction(cx: &Ctx, id: u64) -> R<mt::Vector3> {
let e = entity(cx, id)?;
if e.name() != "DIRECTION" {
return Err(format!("#{id}: expected DIRECTION, found {}", e.name()));
+31 -2
View File
@@ -562,10 +562,39 @@ impl Reader {
fn placement_matrix(&mut self, item: u64, u: Units) -> R<mt::Matrix4> {
let cx = Ctx { ex: &self.ex, len: u.len, ang: u.ang, tol: u.tol };
let e = geom::entity(&cx, item)?;
if e.name() == "CARTESIAN_TRANSFORMATION_OPERATOR_3D" {
if matches!(e.name(), "CARTESIAN_TRANSFORMATION_OPERATOR_3D" | "CARTESIAN_TRANSFORMATION_OPERATOR_3D_NON_UNIFORM") {
let p = e.params();
let o = geom::point(&cx, p.get(4).and_then(Param::as_ref_id).ok_or("transformation without origin")?)?;
return Ok(mt::Matrix4::from_translation(o.to_homogeneous().truncate()));
let direction = |i: usize, fallback: mt::Vector3| -> R<mt::Vector3> {
match p.get(i) {
None | Some(Param::Null) => Ok(fallback),
Some(Param::Ref(id)) => geom::direction(&cx, *id),
_ => Err("invalid transformation direction".into()),
}
};
let scale = |i: usize, fallback: f64| -> R<f64> {
match p.get(i) {
None | Some(Param::Null) => Ok(fallback),
Some(v) => v.as_f64().filter(|x| x.is_finite() && *x != 0.0).ok_or_else(|| "invalid transformation scale".into()),
}
};
let sx = scale(5, 1.0)?;
let (sy, sz) = (scale(7, sx)?, scale(8, sx)?);
let m = mt::Matrix4::from_cols(
(direction(2, mt::Vector3::unit_x())? * sx).extend(0.0),
(direction(3, mt::Vector3::unit_y())? * sy).extend(0.0),
(direction(6, mt::Vector3::unit_z())? * sz).extend(0.0),
o.to_homogeneous(),
);
if !to_array(&m).iter().flatten().all(|x| x.is_finite()) {
return Err("invalid transformation scale".into());
}
use mt::SquareMatrix as _;
let det = m.determinant();
if !det.is_finite() || det == 0.0 {
return Err("singular transformation".into());
}
return Ok(m);
}
Ok(geom::frame(&cx, item)?.matrix())
}