Wave 21/509: solidcraft-smlib: SMLib bodies into SolidCraft through schema 4

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

- 144b56924 jyviko: solidcraft-smlib: SMLib bodies into SolidCraft through schema 4

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-21 01:12:36 -04:00
parent e0fb4ef757
commit 4c4dbe4121
12 changed files with 1384 additions and 14 deletions
+8 -8
View File
@@ -1278,14 +1278,14 @@ impl Body {
if let Some(m) = &self.mesh {
return Ok(m.to_mesh());
}
// Two kinds of face truck cannot mesh in its surface's parameters: one trimmed by a
// helix, which turns more than once around its cylinder and comes out with triangles
// across the solid (#1289), and one that runs across the join of a B-spline surface that
// closes on itself, which comes out folded over itself or with a hole in it.
// Such a body is meshed from its display plan, which cuts and unwraps those faces.
let planned =
guard("tessellate", || Ok(crate::tess::seam::turns_more_than_once(&self.solid) || crate::tess::seam::closes_on_itself(&self.solid)));
if planned.unwrap_or(false) {
// A face trimmed by a helix (a modelled thread from another CAD system) turns more than
// once around its cylinder; truck meshes it with triangles across the solid (#1289).
// Such a body is meshed from its display plan, which cuts the face along a seam.
// So is one bounded by a single seam from pole to pole (a sphere from SMLib), which truck
// meshes as nothing.
if guard("tessellate", || Ok(crate::tess::seam::turns_more_than_once(&self.solid) || crate::tess::has_pole_to_pole_seam(&self.solid)))
.unwrap_or(false)
{
let turn = (angle.is_finite() && angle > 0.0)
.then(|| crate::tess::size::Turn { angle: angle.max(MIN_DISPLAY_ANGLE), floor: tol * DISPLAY_ANGLE_FLOOR });
match guard("tessellate", || crate::tess::plan(&self.solid, tol, turn, self.boundary_tol)) {
+1 -1
View File
@@ -191,7 +191,7 @@ pub use measure::{BodyMeasure, MassMeasure, measure, measure_mass};
pub use mesh_convert::convert_prismatic_mesh;
pub use meshbody::{MAX_TRIANGLES, mesh_body};
#[cfg(feature = "smlib")]
pub use native::smlib_body;
pub use native::{body_from_smlib, smlib_body};
pub use native::{brep_record, decode_native_body, encode_native_body, native_preview_mesh};
pub use offset::with_same_surface;
pub use ops::{
+10
View File
@@ -144,6 +144,16 @@ pub fn decode_native_body(bytes: &[u8]) -> Result<Body> {
})
}
/// An SMLib body as a kernel body, through its schema 4 record: SMLib's export mapped by
/// `solidcraft_smlib` (canonical order, radians, pcurves), then this adapter's decode of a
/// foreign record (analytic surfaces as truck's revolutions). The body is oriented as the record
/// says; `Body::new` only measures it.
#[cfg(feature = "smlib")]
pub fn body_from_smlib(brep: &solidcraft_smlib::Brep) -> Result<Body> {
let record = brep.to_native().map_err(|e| KernelError::Failed(e.to_string()))?;
guard("decode SMLib B-rep", || Body::new(adapter::decode_from(record, adapter::Producer::Foreign)?))
}
fn validate_topology(saved: &SavedBody) -> Result<()> {
saved.solid.validate().map_err(invalid)?;
let (faces, edges) = (saved.solid.faces.len(), saved.solid.edges.len());
+23 -4
View File
@@ -162,7 +162,7 @@ pub(super) fn encode(body: &Body) -> Result<b::Brep> {
}
let result = b::Brep { version: b::VERSION, tolerance, regions, shells: shell_records, faces, edges: edge_records, vertices };
result.validate().map_err(invalid)?;
compatible(&result)?;
compatible(&result, Producer::Own)?;
Ok(result)
}
@@ -303,17 +303,36 @@ fn regions(body: &Body) -> Result<Vec<b::Region>> {
Ok(regions)
}
fn compatible(body: &b::Brep) -> Result<()> {
fn compatible(body: &b::Brep, producer: Producer) -> Result<()> {
body.edges.iter().try_for_each(|e| compatible_curve(&e.curve))?;
body.faces.iter().try_for_each(|f| compatible_surface(&f.surface))
body.faces.iter().try_for_each(|f| match (&f.surface, producer) {
// Truck holds a plane by three points: another kernel's axes load rounded once.
(b::Surface::Plane { .. }, Producer::Foreign) => Ok(()),
(s, _) => compatible_surface(s),
})
}
/// Who wrote a record, which sets how exactly it must load.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Producer {
/// This adapter: the record loads back number for number, or is refused.
Own,
/// Another kernel (SMLib): its records load as truck holds them, analytic surfaces as
/// revolutions (as for our own) and planes through three points rounded once.
#[cfg_attr(not(feature = "smlib"), allow(dead_code))]
Foreign,
}
/// The solid of a record: validated, its geometry checked against its topology (truck builds
/// edges and faces from it unchecked), then built as the kernel built it.
pub(super) fn decode(body: b::Brep) -> Result<mt::Solid> {
decode_from(body, Producer::Own)
}
pub(super) fn decode_from(body: b::Brep, producer: Producer) -> Result<mt::Solid> {
body.validate().map_err(invalid)?;
body.check_geometry().map_err(invalid)?;
compatible(&body)?;
compatible(&body, producer)?;
let b::Brep { shells, faces, edges, vertices, .. } = body;
let vertices: Vec<mt::Vertex> = vertices.into_iter().map(|v| mt::Vertex::new(p(v.point))).collect();
let vertex = |i: u32| vertices.get(i as usize).ok_or_else(|| invalid("edge vertices"));
+39
View File
@@ -212,3 +212,42 @@ fn every_pcurve_lifts_onto_its_own_edge() {
}
}
}
/// SMLib's primitives load through their schema 4 records as bodies of SMLib's volume, oriented
/// as the records say (outward without `Body::new` turning them).
#[cfg(feature = "smlib")]
#[test]
fn smlib_primitives_decode_with_their_volume_and_orientation() {
use solidcraft_smlib::Brep as S;
let cases = [
("box", S::make_box([1., 2., 3.], [10., 20., 30.]).unwrap()),
("cylinder", S::make_cylinder([1., 2., 3.], 5., 10.).unwrap()),
("sphere", S::make_sphere([1., 2., 3.], 5.).unwrap()),
("frustum", S::make_cone([0.; 3], 5., 2., 10.).unwrap()),
("widening frustum", S::make_cone([0.; 3], 2., 5., 10.).unwrap()),
("cone", S::make_cone([0.; 3], 5., 0., 10.).unwrap()),
("torus", S::make_torus([0.; 3], 10., 3.).unwrap()),
];
for (name, s) in cases {
let record = s.to_native().unwrap();
let body = crate::native::body_from_smlib(&s).unwrap_or_else(|e| panic!("{name}: {e}"));
let forward: Vec<bool> = record
.shells
.iter()
.flat_map(|sh| match sh {
b::Shell::Faces { faces, .. } => faces.iter().map(|f| f.forward).collect(),
_ => Vec::new(),
})
.collect();
let loaded: Vec<bool> = body.solid.boundaries().iter().flat_map(|sh| sh.face_iter().map(|f| f.orientation()).collect::<Vec<_>>()).collect();
assert_eq!(loaded, forward, "{name}: the body was turned inside out");
let smlib = s.mass_properties(solidcraft_smlib::MEASURE_ACCURACY).unwrap().volume;
let ours = crate::measure(&body).unwrap().volume;
assert!((ours - smlib).abs() < 2e-3 * smlib, "{name}: decoded volume {ours}, SMLib's {smlib}");
assert_eq!(
(body.face_count(), body.edge_count(), body.vertex_count()),
(record.faces.len(), record.edges.len(), record.vertices.len()),
"{name}"
);
}
}
+61
View File
@@ -468,6 +468,60 @@ fn off_surface(rules: &size::Rules) -> f64 {
/// One face: boundary loops in 3D (shared edge nodes) to parameters and triangles.
/// `size`: the face's target side length (mm) and the surface's mean speed along u and v.
/// Whether a face of `solid` is bounded by one seam edge alone, used both ways between two
/// distinct vertices (poles): a whole sphere as one face, as SMLib writes it. Truck's mesher
/// projects both uses onto one parameter line and meshes nothing; the display plan opens the
/// loop across the period ([`open_pole_to_pole`]).
pub(crate) fn has_pole_to_pole_seam(solid: &Solid) -> bool {
solid.face_iter().any(|f| {
f.boundaries().iter().any(|w| {
let edges: Vec<&mt::Edge> = w.edge_iter().collect();
matches!(edges.as_slice(), [a, b] if a.id() == b.id() && a.front() != a.back())
})
})
}
/// Twice the signed area of a parameter polygon.
fn area2(uv: &[[f64; 2]]) -> f64 {
let n = uv.len();
(0..n).map(|k| uv.get(k).zip(uv.get((k + 1) % n)).map_or(0.0, |(a, b)| a[0] * b[1] - b[0] * a[1])).sum()
}
/// A loop that runs from one pole to the other and back along the same parameter line (both
/// uses of a seam joined only at the poles) encloses nothing once projected: the run after the
/// second pole is moved one period along the periodic direction, which way gives the loop a
/// positive area, so the face spans the period between its two seam copies.
fn open_pole_to_pole(s: &EvalSurface, dom: &uv::Domain, l: &mut seam::Loop) {
let n = l.uv.len();
let poles: Vec<usize> = (0..n).filter(|&k| l.uv.get(k).is_some_and(|q| (0..2).any(|d| uv::degenerate(s, *q, d)))).collect();
let [p0, p1] = poles.as_slice() else { return };
let (lo, hi) = l.uv.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), q| (a.min(q[0].min(q[1])), b.max(q[0].max(q[1]))));
let extent = (hi - lo).abs().max(1e-12);
if area2(&l.uv).abs() > 1e-9 * extent * extent {
return;
}
for d in 0..2 {
let Some(per) = dom.period[d] else { continue };
// Along the seam the periodic parameter is constant between the poles.
let second: Vec<usize> = (0..n).filter(|k| (k > p1 || k < p0) && *k != *p0 && *k != *p1).collect();
if second.is_empty() {
continue;
}
for sign in [1.0, -1.0] {
let mut moved = l.uv.clone();
for &k in &second {
if let Some(q) = moved.get_mut(k) {
q[d] += sign * per;
}
}
if area2(&moved) > 1e-9 * extent * extent {
l.uv = moved;
return;
}
}
}
}
fn plan_face(
fi: usize,
s: &EvalSurface,
@@ -533,6 +587,13 @@ fn plan_face(
}
_ => return Err(fail("boundary winds around the surface both ways")),
}
// A loop from pole to pole and back along one seam (a whole sphere as one face, as another
// kernel writes it) projects onto one parameter line: its second run is a period along.
if !seamed {
for l in projected.iter_mut() {
open_pole_to_pole(s, &dom, l);
}
}
// Split poles.
let mut fixed: Vec<Vec3> = Vec::new();
let mut uvs: Vec<[f64; 2]> = Vec::new();