Wave 450/509: STEP import: a solid the kernel refuses, its faces too, is refused with the reason, never a mesh (and 3 more)

4 commits, squashed; the originals stay reachable from tag archive/merge-main-develop.

- 709765fca jyviko: Model cache: a saved model records its body check mode and is adopted under it
- 393c83c2a jyviko: STEP import: a solid the kernel refuses, its faces too, is refused with the reason, never a mesh
- 6700e6ef1 jyviko: kernel: a body SMLib keeps in the record's order is mapped, whatever order its export lists
- 222211de4 jyviko: Model cache: a thinned model keeps the check mode only as the model records it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ
This commit is contained in:
jyviko
2026-10-30 15:53:21 -04:00
parent 33fdadcc40
commit bc93a653f6
13 changed files with 199 additions and 93 deletions
+58 -1
View File
@@ -156,9 +156,22 @@ pub(crate) fn smlib_record_ordered(
/// Where SMLib's faces and edges of `brep` (imported from `record`) are in the record's order:
/// `None` where SMLib's export does not number them as the record does.
///
/// SMLib's export is in canonical order, and `order` says where SMLib's own face and edge `i`
/// went in it. Where the canonical record numbers them as `record` does, `order` maps SMLib's
/// to the record's. Otherwise SMLib may still keep the record's own order (an import lists
/// SMLib's faces and edges in the record's order, and canonical order can list them otherwise,
/// a tube's seam edges among them): the export put back in SMLib's order then numbers them as
/// `record` does, and SMLib's face and edge `i` are the record's `i`.
fn numbering(record: &solidcraft_geom::brep::Brep, brep: &solidcraft_smlib::Brep) -> Option<solidcraft_smlib::history::Order> {
match brep.to_native_ordered() {
Ok((back, order)) => same_numbering(record, &back).then_some(order),
Ok((back, order)) => {
if same_numbering(record, &back) {
return Some(order);
}
let in_smlib_order = in_smlib_order(&back, &order)?;
same_numbering(record, &in_smlib_order).then(solidcraft_smlib::history::Order::default)
}
Err(e) => {
log::debug!(target: "smlib", "no order for an operand: {e}");
None
@@ -166,6 +179,50 @@ fn numbering(record: &solidcraft_geom::brep::Brep, brep: &solidcraft_smlib::Brep
}
}
/// The canonical record `back` with its faces and edges in SMLib's own order (`order`: where
/// SMLib's face and edge `i` are in `back`), each loop naming its edges by SMLib's numbers.
/// `None` where `order` is not a renumbering of `back`'s faces and edges (an edge split into
/// pieces where solids touch along it is more than one record edge).
fn in_smlib_order(back: &solidcraft_geom::brep::Brep, order: &solidcraft_smlib::history::Order) -> Option<solidcraft_geom::brep::Brep> {
use solidcraft_geom::brep::Loop;
let permutation = |to: &[usize], n: usize| -> Option<Vec<usize>> {
if to.is_empty() {
return Some((0..n).collect());
}
let mut from = vec![usize::MAX; n];
for (i, &k) in to.iter().enumerate() {
let slot = from.get_mut(k)?;
if *slot != usize::MAX {
return None;
}
*slot = i;
}
(to.len() == n).then_some(from)
};
if !order.pieces.is_empty() {
return None;
}
// `faces_from[k]`: SMLib's number of `back`'s face k; likewise for edges.
let faces_from = permutation(&order.faces, back.faces.len())?;
let edges_from = permutation(&order.edges, back.edges.len())?;
let mut out = back.clone();
for (k, face) in back.faces.iter().enumerate() {
let mut face = face.clone();
for l in &mut face.loops {
if let Loop::Edges { edges } = l {
for e in edges.iter_mut() {
e.edge = u32::try_from(*edges_from.get(usize::try_from(e.edge).ok()?)?).ok()?;
}
}
}
*out.faces.get_mut(*faces_from.get(k)?)? = face;
}
for (k, edge) in back.edges.iter().enumerate() {
*out.edges.get_mut(*edges_from.get(k)?)? = edge.clone();
}
Some(out)
}
/// Whether two records of one body number its faces, edges and vertices alike: the same loops of
/// the same edges, the same edge ends, and each vertex where the other's is.
fn same_numbering(a: &solidcraft_geom::brep::Brep, b: &solidcraft_geom::brep::Brep) -> bool {
+20 -13
View File
@@ -57,7 +57,7 @@ pub struct ImportedBody {
pub file_faces: usize,
/// No B-rep could be made of the whole solid, and this is why (the import's warnings say so
/// too, naming each face left out): `body` is an open surface body of the solid's exact faces
/// but those, or a mesh body of them where no surface body could be made of them.
/// but those.
pub refused: Option<String>,
}
@@ -99,10 +99,11 @@ pub struct StepImport {
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IssueKind {
/// No body could be made of the part: it is not in the design.
/// The part could not be read from the file: it is not in the design.
NotImported,
/// No solid could be made of the part: it is shown as a mesh of its faces.
ShownAsMesh,
/// The kernel refuses the part's B-rep, its faces' too: it is not in the design, and the
/// warning gives the kernel's reason.
Refused,
/// No solid could be made of the part: it came in as surfaces of its faces.
ImportedAsSurfaces,
/// A face of the part could not be read or made, and is left out.
@@ -365,6 +366,12 @@ impl Reader {
false
}
/// `item`'s part is not in the design: the kernel refuses its B-rep, for `why`.
fn refused(&mut self, item: u64, why: &str) {
let label = self.label(item);
self.note(IssueKind::Refused, Some(item), 0, format!("{label}: not imported: {why}"));
}
/// A warning about the file as a whole.
fn warn(&mut self, msg: impl Into<String>) {
self.note(IssueKind::File, None, 0, msg);
@@ -788,8 +795,7 @@ impl Reader {
}
if let Some(again) = self.unreadable.get(&item) {
if let Some(msg) = again.clone() {
let label = self.label(item);
self.note(IssueKind::NotImported, Some(item), 0, format!("{label}: not imported: {msg}"));
self.refused(item, &msg);
}
continue;
}
@@ -816,8 +822,7 @@ impl Reader {
None => {
if let Some(again) = self.unreadable.get(&item) {
if let Some(msg) = again.clone() {
let label = self.label(item);
self.warn(format!("{label}: not imported: {msg}"));
self.refused(item, &msg);
}
continue;
}
@@ -840,9 +845,7 @@ impl Reader {
if let Some(failed) = read {
let label = self.label(item);
if let Some(why) = &part.refused {
let kind = if part.body.is_mesh() { IssueKind::ShownAsMesh } else { IssueKind::ImportedAsSurfaces };
let words = if part.body.is_mesh() { "shown as a mesh" } else { "imported as surfaces" };
self.note(kind, Some(item), 0, format!("{label}: {words}: {why}"));
self.note(IssueKind::ImportedAsSurfaces, Some(item), 0, format!("{label}: imported as surfaces: {why}"));
}
for f in &failed {
let (kind, faces, f) = match f {
@@ -924,8 +927,12 @@ impl Reader {
});
}
Err(parallel::Failure { read, msg }) => {
let label = self.label(item);
self.note(IssueKind::NotImported, Some(item), 0, format!("{label}: not imported: {msg}"));
if read {
let label = self.label(item);
self.note(IssueKind::NotImported, Some(item), 0, format!("{label}: not imported: {msg}"));
} else {
self.refused(item, &msg);
}
// Later instances don't read the item again.
if !self.oriented.contains_key(&item) {
self.unreadable.insert(item, (!read).then_some(msg));
+9 -42
View File
@@ -27,8 +27,7 @@ pub(super) struct Part {
/// The file face of each kernel face.
pub face_origin: Vec<u64>,
/// No B-rep could be made of the whole solid, and this is why: the body is a surface body of
/// the faces that read ([`surface_part`]), or, where none could be made of them, a mesh of
/// them ([`mesh_part`]).
/// the faces that read ([`surface_part`]).
pub refused: Option<String>,
}
@@ -204,9 +203,9 @@ const MAX_LEFT_OUT_ROUNDS: usize = 8;
/// [`MAX_LEFT_OUT_ROUNDS`] reads). A face is only ever left out where a refusal names it.
/// 2. Where a refusal names no face of the solid: the faces that read alone, stitched by SMLib
/// into one surface body (their edges sewn at ten times their tolerance).
/// 3. Where SMLib cannot stitch them either: a mesh of them ([`mesh_part`]).
///
/// With no face to import, the solid stays refused.
/// Where SMLib cannot stitch them either, or there is no face to import, the solid stays refused
/// with the reason it was: a B-rep SMLib refuses is never kept as a mesh of its faces.
fn surface_part(ex: &Exchange, item: u64, units: Units, refused: Failure) -> std::result::Result<(Part, Vec<Note>), Failure> {
let _span = solidcraft_profile::span("import", "step.refused_surfaces");
let trims = &solidcraft_smlib::pcurves::SmlibTrims;
@@ -256,13 +255,12 @@ fn surface_part(ex: &Exchange, item: u64, units: Units, refused: Failure) -> std
Err(e) => notes.push(Note::LeftOut(format!("left out: {}", e.to_string().trim_start_matches("the operation failed: ")))),
}
}
match stitched_part(&pieces, faces.len(), &refused.msg) {
Ok(part) => Ok((part, notes)),
Err(e) => {
log::debug!(target: "step", "item #{item}: its faces not stitched ({e}); meshed instead");
mesh_part(&pieces, faces.len(), notes, refused)
}
}
// Where SMLib cannot stitch them either, the solid is refused with the reason it was.
let part = stitched_part(&pieces, faces.len(), &refused.msg).map_err(|e| {
log::debug!(target: "step", "item #{item}: its faces not stitched ({e})");
refused
})?;
Ok((part, notes))
}
/// The one-face surface bodies `pieces` (each with its file face) stitched by SMLib into one
@@ -290,37 +288,6 @@ fn stitched_part(pieces: &[(u64, Body)], file_faces: usize, refused: &str) -> cr
Ok(Part { body, closed, file_faces, face_origin, refused: Some(refused.to_string()) })
}
/// The one-face surface bodies `pieces` meshed by the planner, their triangles together a mesh
/// body: no B-rep (modelling operations refuse it), for a solid whose faces SMLib could not
/// stitch either. Faces that cannot be meshed are left out, each named in the notes; with no
/// face to show, the solid stays refused.
fn mesh_part(pieces: &[(u64, Body)], file_faces: usize, mut notes: Vec<Note>, refused: Failure) -> std::result::Result<(Part, Vec<Note>), Failure> {
let _span = solidcraft_profile::span("import", "step.refused_mesh");
// Every face at the display tolerance of the whole solid.
let bounds: solidcraft_geom::Aabb3 = pieces.iter().flat_map(|(_, b)| b.record().vertices.iter().map(|v| crate::body::v3(v.point))).collect();
let size = if bounds.is_empty() { 0.0 } else { bounds.diagonal() };
let tol = crate::MeshTolerance::display_of(if size.is_finite() { size } else { 0.0 });
let (mut positions, mut triangles) = (Vec::new(), Vec::new());
for (face, b) in pieces {
match b.mesh(&tol) {
Ok(m) if !m.triangles.is_empty() => {
let Ok(base) = u32::try_from(positions.len()) else { break };
positions.extend_from_slice(&m.positions);
triangles.extend(m.triangles.iter().map(|t| t.map(|i| i.saturating_add(base))));
}
Ok(_) => notes.push(Note::LeftOut(format!("left out: face #{face}: no triangles"))),
Err(e) => notes.push(Note::LeftOut(format!("left out: face #{face}: {}", e.to_string().trim_start_matches("the operation failed: ")))),
}
}
if triangles.is_empty() {
return Err(Failure { msg: format!("{} (no face could be shown as a mesh either)", refused.msg), ..refused });
}
let body = crate::meshbody::mesh_body(&positions, &triangles)
.map_err(|e| Failure { msg: format!("{} (its mesh: {e})", refused.msg), read: refused.read })?;
let closed = body.is_closed_mesh();
Ok((Part { body, closed, file_faces, face_origin: Vec::new(), refused: Some(refused.msg) }, notes))
}
/// Prepare `jobs`, the results in the jobs' order. Solids still to read and orient (the slow
/// part) are shared out between up to `workers` threads, each taking the next job when it is
/// done with one, so one large part does not hold up the rest.
+23 -3
View File
@@ -490,6 +490,17 @@ fn offset_surface_cube_import_is_closed_and_editable() {
assert!(rel(measure(&result).unwrap().volume, 1000.0 - 40.0 * std::f64::consts::PI) < 1e-3);
}
/// A solid whose B-rep SMLib refuses, its faces too (here every SMLib call: the build has no
/// SMLib), is refused with the kernel's reason, naming the solid. It once came in as a mesh of
/// its faces, which the planner could still triangulate.
#[cfg(not(feature = "smlib"))]
#[test]
fn a_solid_smlib_refuses_with_its_faces_is_refused_not_meshed() {
let text = format!("{HEAD}{}#60=SHAPE_REPRESENTATION('',(#101),$);\n{TAIL}", cube_entities());
let why = step_import(&text).map(|imp| imp.warnings).unwrap_err().to_string();
assert!(why.contains("solid 'Cube': not imported: ") && why.contains("SMLib"), "{why}");
}
/// A hand-written unit cube brep (`#100`…) in a representation with the given unit and items.
fn cube_entities() -> String {
let mut s = String::new();
@@ -1748,7 +1759,9 @@ fn periodic_knot_tube(first: u64, x: f64, r: f64, h: f64) -> (String, u64) {
/// Two such tubes far apart in one body: the body's size sets a chord tolerance coarse beside
/// the tubes, and meshing a face at it divided the surface's whole parameter box, whose
/// corners lay outside the domain. The division never converged there (#1374's recursion),
/// and the import grew by gigabytes without end.
/// and the import grew by gigabytes without end. The sheet comes in as SMLib's B-rep of its two
/// faces, each the file's face (SMLib lists the seam edges in another canonical order than the
/// file, and keeps the file's own order), each a cylinder's side.
#[test]
fn periodic_knot_tube_faces_import_and_mesh() {
let t0 = std::time::Instant::now();
@@ -1760,9 +1773,16 @@ fn periodic_knot_tube_faces_import_and_mesh() {
);
let imp = step_import(&text).unwrap();
assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings);
let m = measure(&imp.bodies[0].body).unwrap();
let tubes = &imp.bodies[0];
assert!(tubes.refused.is_none() && !tubes.body.is_mesh() && tubes.body.is_surface(), "{:?} {:?}", tubes.refused, imp.warnings);
assert_eq!(tubes.face_origin, vec![fa, fb], "{:?}", imp.warnings);
// Each face is the file's quadratic circle of radius r (corner weights √2/2 to 12 digits,
// a radius off by under 1e-12 of r) moved straight along its axis by h: a cylinder's side,
// 2π r h. SMLib integrates to 1e-8.
let m = measure(&tubes.body).unwrap();
let area = 2.0 * std::f64::consts::TAU * r * h;
assert!(rel(m.area, area) < 0.02, "area {} (expected {area})", m.area);
assert!(rel(m.area, area) < 1e-6, "area {} (expected {area})", m.area);
assert_eq!(tubes.body.unmeshed_faces(), 0);
assert!(t0.elapsed().as_secs_f64() < 60.0, "took {:?}", t0.elapsed());
}