Wave 94/509: kernel: with SOLIDCRAFT_KERNEL=smlib, STEP solids are SMLib's bodies (and 3 more)

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

- 8fde178fe Brennen Herbruck: kernel: any schema 4 record into SMLib with its order, healed where refused
- 5014c4f17 Brennen Herbruck: kernel: with SOLIDCRAFT_KERNEL=smlib, STEP solids are SMLib's bodies
- 8ad09ec64 bherbruck: smlib export: a face's loop crosses its poles where the face's parameter box says
- f4da25243 bherbruck: solidcraft-smlib: the fork at bf7c272, whose operation results hold their own gaps

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ
This commit is contained in:
Brennen HerbruckandClaude Opus 5.5 authored and jyviko committed 2026-10-21 11:44:05 -04:00
1 parent 532027f7a6
commit 84aa2c5b1b
8 files changed
+189 -19

No files matched your search

+44 -6
View File
@@ -67,6 +67,20 @@ const CHECKS: usize = 16;
/// the surface. Loops are as the record keeps them (relative to the surface's natural normal: outer counter-clockwise, inner clockwise); each
/// pcurve runs on its use's interval in its curve's direction, whatever `forward` says.
pub fn pcurves(surface_record: &Surface, loops: &[Vec<EdgeUse<'_>>], tolerance: f64) -> Result<Vec<Vec<Curve2>>> {
pcurves_within(surface_record, loops, tolerance, None)
}
/// [`pcurves`] for a face whose parameter box is known (`domain`, u then v, as its kernel
/// gives it): where two uses meet at a pole, the periodic parameter's jump there is free, and
/// the loop takes the jumps whose extent in that parameter is nearest the box's. Two meridians
/// a three-quarter turn apart bound a quarter of a sphere or three quarters of it; the loop alone
/// can't tell which, the box can.
pub fn pcurves_within(
surface_record: &Surface,
loops: &[Vec<EdgeUse<'_>>],
tolerance: f64,
domain: Option<[[f64; 2]; 2]>,
) -> Result<Vec<Vec<Curve2>>> {
if !(tolerance.is_finite() && tolerance > 0.0 && tolerance <= 1e3) {
return Err(Error::Invalid(format!("pcurve tolerance {tolerance}")));
}
@@ -76,7 +90,7 @@ pub fn pcurves(surface_record: &Surface, loops: &[Vec<EdgeUse<'_>>], tolerance:
}
let mut budget = Budget(0);
surface(surface_record, 0, &mut budget).map_err(|e| Error::Invalid(e.to_string()))?;
let on = On::new(surface_record)?;
let on = On::new(surface_record)?.within(domain);
// A seam edge used twice is fitted once.
let mut done: Vec<(u32, Curve2)> = Vec::new();
let mut out = Vec::with_capacity(loops.len());
@@ -117,6 +131,8 @@ pub fn pcurves(surface_record: &Surface, loops: &[Vec<EdgeUse<'_>>], tolerance:
struct On {
surface: SurfaceEval,
dom: Domain,
/// The face's own parameter box, where its kernel gives one.
face: Option<[[f64; 2]; 2]>,
}
/// A curve sample: its parameter, point, surface parameters (periodic ones unwrapped along the
@@ -135,7 +151,12 @@ impl On {
fn new(s: &Surface) -> Result<Self> {
let surface = SurfaceEval::new(s)?;
let dom = surface.domain();
Ok(On { surface, dom })
Ok(On { surface, dom, face: None })
}
fn within(self, face: Option<[[f64; 2]; 2]>) -> Self {
let face = face.filter(|f| f.iter().flatten().all(|x| x.is_finite()));
On { face, ..self }
}
fn pcurve(&self, record: &Curve, curve: &CurveEval, range: [f64; 2], tol: f64) -> Result<Curve2> {
@@ -418,7 +439,23 @@ impl On {
let other = uses.iter().flat_map(|(c, _)| points(c).into_iter().filter_map(|q| q.get(1 - d).copied()));
let (lo, hi) = other.fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), x| (a.min(x), b.max(x)));
let flat = if hi >= lo { 1e-9 * period * (hi - lo) } else { 0.0 };
let mut best: Option<(bool, usize, Vec<f64>)> = None;
// With the face's box: how far the loop's extent along `d` is from the box's
// (in steps of a millionth of a period, so rounding doesn't decide).
let width = self.face.and_then(|f| f.get(d).copied()).map(|[a, b]| (b - a).abs());
let misfit = |extra: &[f64]| -> u64 {
let Some(width) = width else { return 0 };
let (mut a, mut b) = (f64::INFINITY, f64::NEG_INFINITY);
for ((c, _), s) in uses.iter().zip(extra) {
for q in points(c) {
if let Some(x) = q.get(d) {
a = a.min(x + s);
b = b.max(x + s);
}
}
}
if b < a { 0 } else { ((b - a - width).abs() / period * 1e6).round() as u64 }
};
let mut best: Option<(u64, bool, usize, Vec<f64>)> = None;
for combo in 0..3usize.pow(free.len() as u32) {
let (mut code, mut moved, mut add) = (combo, 0, 0.0);
let mut extra = shift.clone();
@@ -434,11 +471,12 @@ impl On {
}
}
let right = area(uses, &extra, d) > flat;
if best.as_ref().is_none_or(|(r, m, _)| (right && !r) || (right == *r && moved < *m)) {
best = Some((right, moved, extra));
let fit = misfit(&extra);
if best.as_ref().is_none_or(|(f, r, m, _)| fit < *f || (fit == *f && ((right && !r) || (right == *r && moved < *m)))) {
best = Some((fit, right, moved, extra));
}
}
if let Some((_, _, extra)) = best {
if let Some((_, _, _, extra)) = best {
shift = extra;
}
}
+22
View File
@@ -234,6 +234,28 @@ fn meridians_run_straight_into_the_poles() {
}
}
/// Two meridians a three-quarter turn apart bound a quarter of a sphere or three quarters of
/// it; the loop alone can't tell which. Given the face's box, the loop spans it: three quarters
/// of a turn in u (a ball revolved 270°), or a quarter where the box says so.
#[test]
fn meridians_at_a_pole_span_the_face_box() {
let sphere = Surface::Sphere { frame: about_z([0.; 3], false), radius: 6. };
let at = |a: f64| Curve::Circle { frame: frame([0.; 3], [a.cos(), a.sin(), 0.], [0., 0., 1.]), radius: 6. };
let (first, last) = (at(0.), at(1.5 * PI));
let half = [-FRAC_PI_2, FRAC_PI_2];
for (box_u, span) in [([0., 1.5 * PI], 1.5 * PI), ([-FRAC_PI_2, 0.], FRAC_PI_2)] {
for flip in [false, true] {
let l = vec![
EdgeUse { edge: 0, curve: &first, interval: half, forward: !flip, tolerance: 0.0 },
EdgeUse { edge: 1, curve: &last, interval: half, forward: flip, tolerance: 0.0 },
];
let pcs = &pcurves_within(&sphere, std::slice::from_ref(&l), 1e-7, Some([box_u, [-FRAC_PI_2, FRAC_PI_2]])).unwrap()[0];
let (a, b) = (pcs[0].eval(0.).unwrap()[0], pcs[1].eval(0.).unwrap()[0]);
assert!(((a - b).abs() - span).abs() < 1e-9, "box {box_u:?}, flip {flip}: u {a} and {b}");
}
}
}
/// A whole sphere bounded only by its seam (one meridian from pole to pole, used twice), in
/// frames where rounding leaves the loop with the uses on one line a tiny positive area: the
/// two uses come out a period apart and the loop turns counter-clockwise around the whole
+18 -9
View File
@@ -210,24 +210,33 @@ pub(crate) fn body_from_smlib_ordered(brep: &solidcraft_smlib::Brep) -> Result<(
/// `None` where it does not.
#[cfg(feature = "smlib")]
pub(crate) fn smlib_body_ordered(body: &Body) -> Result<(solidcraft_smlib::Brep, Option<solidcraft_smlib::history::Order>)> {
smlib_record_ordered(&tolerant_record(body)?)
}
/// `record` in SMLib, healed where SMLib's check refuses it as given, with where each of SMLib's
/// faces and edges is in the record's order: `None` where SMLib's export of it does not number
/// every face, edge and vertex as the record does.
#[cfg(feature = "smlib")]
pub(crate) fn smlib_record_ordered(
record: &solidcraft_geom::brep::Brep,
) -> Result<(solidcraft_smlib::Brep, Option<solidcraft_smlib::history::Order>)> {
use solidcraft_smlib::{Brep, CheckLevel};
let record = tolerant_record(body)?;
let import = |trusted: bool| Brep::from_record(&record, trusted).map_err(|e| KernelError::Failed(format!("SMLib: {e}")));
let import = |trusted: bool| Brep::from_record(record, trusted).map_err(|e| KernelError::Failed(format!("SMLib: {e}")));
let valid = |b: &Brep| b.check(CheckLevel::All).is_ok_and(|c| c.is_valid());
// A record SMLib's check refuses as given (a gap a little over the record's tolerance, a
// hole listed before its face's outer loop) goes through SMLib's healer; healed, it is kept
// only where SMLib then finds it valid.
let trusted = import(true)?;
let brep = if valid(&trusted) {
trusted
} else {
match import(false) {
// One SMLib refuses as given altogether goes through the healer too.
let brep = match import(true) {
Ok(trusted) if valid(&trusted) => trusted,
Ok(trusted) => match import(false) {
Ok(healed) if valid(&healed) => healed,
_ => trusted,
}
},
Err(e) => import(false).map_err(|_| e)?,
};
let order = match brep.to_native_ordered() {
Ok((back, order)) => same_numbering(&record, &back).then_some(order),
Ok((back, order)) => same_numbering(record, &back).then_some(order),
Err(e) => {
log::debug!(target: "smlib", "no order for an operand: {e}");
None
+5 -2
View File
@@ -121,9 +121,12 @@ struct Units {
len: f64,
ang: f64,
tol: f64,
/// The context's own distance uncertainty (mm), as the file states it (SMLib's reads take it).
#[cfg_attr(not(feature = "smlib"), allow(dead_code))]
uncertainty: Option<f64>,
}
const DEFAULT_UNITS: Units = Units { len: 1.0, ang: 1.0, tol: 0.01 };
const DEFAULT_UNITS: Units = Units { len: 1.0, ang: 1.0, tol: 0.01, uncertainty: None };
/// Units of a representation context (GLOBAL_UNIT_ASSIGNED_CONTEXT, uncertainty), read by
/// [`solidcraft_step::units::context`]; the vertex-on-curve tolerance is ten times the
@@ -135,7 +138,7 @@ fn context_units(ex: &Exchange, ctx: Option<u64>, cache: &mut HashMap<u64, Units
}
let c = solidcraft_step::units::context(ex, id);
let tol = c.uncertainty.map(|t| (t * 10.0).max(1e-3)).unwrap_or(c.units.len * 1e-2).clamp(1e-4, 1.0);
let u = Units { len: c.units.len, ang: c.units.ang, tol };
let u = Units { len: c.units.len, ang: c.units.ang, tol, uncertainty: c.uncertainty };
cache.insert(id, u);
u
}
+47
View File
@@ -66,6 +66,10 @@ pub(super) fn workers() -> usize {
fn prepare(ex: &Exchange, job: &Job) -> Prepared {
let (part, read) = match &job.source {
Source::Oriented(part) => (part.clone(), None),
Source::Item { item, units } if smlib_backend() => {
let (part, read) = smlib_part(ex, *item, *units)?;
(Arc::new(part), Some(read))
}
Source::Item { item, units } => {
let cx = Ctx { ex, len: units.len, ang: units.ang, tol: units.tol, snap: units.snap };
let out = guard("step brep", || brep::read_item(&cx, *item).map_err(KernelError::Failed))
@@ -91,6 +95,49 @@ fn prepare(ex: &Exchange, job: &Job) -> Prepared {
.map_err(|e| Failure { read: false, msg: e.to_string() })
}
/// Whether solids are read into SMLib ([`crate::backend`]). A setting this build can't honour
/// reads them on neither kernel: [`smlib_part`] then says why.
fn smlib_backend() -> bool {
!matches!(crate::backend(), Ok(crate::Backend::Truck))
}
/// A solid item read with the STEP reader into its schema 4 record, then into SMLib (healed
/// where SMLib's check refuses it as given), and brought back as a body: the part SMLib made of
/// the file. A solid the reader or SMLib refuses is not imported, with the reason; there is no
/// other kernel to fall back on.
#[cfg(feature = "smlib")]
pub(super) fn smlib_part(ex: &Exchange, item: u64, units: Units) -> std::result::Result<(Part, Vec<String>), Failure> {
crate::backend().map_err(|e| Failure { read: true, msg: e.to_string() })?;
let context =
solidcraft_step::units::Context { units: solidcraft_step::read::Units { len: units.len, ang: units.ang }, uncertainty: units.uncertainty };
let solid = solidcraft_step::topology::read_solid(ex, item, context).map_err(|msg| Failure { read: true, msg })?;
let failed = |e: KernelError| Failure { read: false, msg: e.to_string().trim_start_matches("the operation failed: ").to_string() };
let (brep, smlib_order) = crate::native::smlib_record_ordered(&solid.brep).map_err(failed)?;
let (body, body_order) = crate::native::body_from_smlib_ordered(&brep).map_err(failed)?;
// The file face of each body face: SMLib's face i is the record's `smlib_order` face and the
// body's `body_order` face (an empty order is the same one).
let (Some(smlib_order), Some(body_order)) = (smlib_order, body_order) else {
return Err(Failure { read: false, msg: "not supported yet: SMLib renumbered the solid's faces".into() });
};
let at = |order: &[usize], i: usize| if order.is_empty() { Some(i) } else { order.get(i).copied() };
let faces = brep.counts().map_err(|e| failed(KernelError::Failed(format!("SMLib: {e}"))))?[0];
let mut face_origin = vec![0u64; body.face_count()];
for i in 0..faces {
let file_face = at(&smlib_order.faces, i).and_then(|r| solid.face_origin.get(r)).copied();
match (at(&body_order.faces, i).and_then(|b| face_origin.get_mut(b)), file_face) {
(Some(slot), Some(f)) => *slot = f,
_ => return Err(Failure { read: false, msg: "not supported yet: SMLib renumbered the solid's faces".into() }),
}
}
let part = Part { body, closed: !solid.sheet, file_faces: solid.face_origin.len(), face_origin };
Ok((part, solid.notes))
}
#[cfg(not(feature = "smlib"))]
pub(super) fn smlib_part(_: &Exchange, _: u64, _: Units) -> std::result::Result<(Part, Vec<String>), Failure> {
Err(Failure { read: true, msg: crate::backend().err().map_or_else(|| "this build has no SMLib".into(), |e| e.to_string()) })
}
/// 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.
+51
View File
@@ -1899,3 +1899,54 @@ fn corpus_truck_and_schema_4_counts() {
);
}
}
/// The step-conformance parts read into SMLib (`SOLIDCRAFT_KERNEL=smlib`): the STEP reader's
/// schema 4 record, SMLib's body of it, back as a kernel body. Each has its exact volume and
/// face count, and every face is traced to a face of the file. The NURBS cylinder, dome and
/// torus wind around a closed spline surface without a seam edge, which the reader refuses for
/// now, and stay refused on this path with that reason.
#[cfg(feature = "smlib")]
#[test]
fn step_conformance_parts_read_into_smlib() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/step-conformance");
// (file, exact volume (mm³) and faces of its solid items: cylinder_twice places its one
// cylinder twice)
#[rustfmt::skip]
let parts: [(&str, f64, usize); 17] = [
("cone_point", 1000.0 * std::f64::consts::PI, 2), ("cone_point_vertex", 1000.0 * std::f64::consts::PI, 2),
("cylinder", 9424.778, 3), ("cylinder_inch", 9424.778, 3), ("cylinder_nurbs", 9424.778, 3),
("cylinder_placed", 9424.778, 3), ("cylinder_seam", 9424.778, 3), ("cylinder_twice", 9424.778, 3),
("dome", 16755.161, 2), ("dome_nurbs", 16755.161, 2), ("far_cylinder", 9424.778, 3),
("grooved_shaft", 153532.251, 753), ("plate_100_holes", 71588.321, 110), ("sheet_disc", 193396443.755, 3),
("tiny_pin", std::f64::consts::FRAC_PI_8, 3), ("torus_ring_nurbs", 4934.802, 2), ("washer", 3534.292, 4),
];
for (name, volume, faces) in parts {
let text = std::fs::read_to_string(dir.join(format!("{name}.step"))).unwrap();
let ex = solidcraft_step::p21::parse(&text).unwrap();
// The file's one representation context, as the import reads it.
let ctx = ex.entities.iter().find(|(_, e)| e.record("GLOBAL_UNIT_ASSIGNED_CONTEXT").is_some()).map(|(id, _)| *id);
let units = context_units(&ex, ctx, &mut HashMap::new());
let mut items: Vec<u64> = ex.entities.iter().filter(|(_, e)| e.name() == "MANIFOLD_SOLID_BREP").map(|(id, _)| *id).collect();
items.sort_unstable();
let (mut v, mut n) = (0.0, 0);
for item in items {
let made = parallel::smlib_part(&ex, item, units);
if name.ends_with("_nurbs") {
let msg = made.err().map(|f| f.msg).unwrap_or_default();
assert!(msg.contains("closed spline surface's seam"), "{name}: {msg}");
continue;
}
let (part, _) = made.unwrap_or_else(|f| panic!("{name}: {}", f.msg));
assert_eq!(part.face_origin.len(), part.body.face_count(), "{name}");
assert!(part.face_origin.iter().all(|f| ex.get(*f).is_some_and(|e| e.name() == "ADVANCED_FACE")), "{name}: {:?}", part.face_origin);
let m = measure(&part.body).unwrap_or_else(|e| panic!("{name}: {e}"));
v += m.volume;
n += m.faces;
}
if name.ends_with("_nurbs") {
continue;
}
assert!(rel(v, volume) < 1e-3, "{name}: volume {v} vs {volume}");
assert_eq!(n, faces, "{name}: faces");
}
}
+1 -1
View File
@@ -1 +1 @@
ca2559f785a662c9ec589aa2cdcfaf3217597db8
bf7c272dd60ec079bdc99f29005d993bd61a042b
+1 -1
View File
@@ -1125,7 +1125,7 @@ fn pcurves(surface: &b::Surface, domain: [[f64; 2]; 2], loops: &[Loop], edges: &
}
uses.push(loop_uses);
}
let mut curves = b::pcurve::pcurves(surface, &uses, tolerance).map_err(|e| invalid(format!("pcurve: {e}")))?;
let mut curves = b::pcurve::pcurves_within(surface, &uses, tolerance, Some(domain)).map_err(|e| invalid(format!("pcurve: {e}")))?;
into_domain(surface, domain, &mut curves);
Ok(curves)
}