Wave 279/509: STEP import: an edge off its face's surface carries its gap as its tolerance (and 3 more)

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

- 07cb8c7cc jyviko: STEP import: an edge off its face's surface carries its gap as its tolerance
- 21c64fb24 jyviko: tess: an edge loop of fewer than three segments is split until it encloses an area
- 9da3174bb jyviko: solidcraft-smlib: a revolution goes to SMLib as its NURBS form alone
- 31b9410f5 jyviko: solidcraft-smlib: a horn torus to rounding is no ring torus

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ
This commit is contained in:
jyvikoandClaude Opus 5.5 committed 2026-10-27 16:45:52 -04:00
1 parent 01be42ef41
commit 40f16c36bb
7 files changed
+246 -6

No files matched your search

+68
View File
@@ -1738,3 +1738,71 @@ fn step_conformance_parts_read_into_smlib() {
assert_eq!(n, faces, "{name}: faces");
}
}
/// A domed cubic patch 30 mm across whose four edges, cubic B-splines on its boundary rows,
/// are written `dz` mm above it, in a file that states 1e-6 mm: an intersection curve written
/// looser than its context. The patch has no closed-form pcurves for them, so SMLib makes them,
/// on the surface, and they lie `dz` from their edges.
fn dome_with_edges_raised(dz: f64) -> String {
let z = |i: usize, j: usize| if (1..=2).contains(&i) && (1..=2).contains(&j) { 6.0 } else { 0.0 };
let mut t = String::from(HEAD);
let mut rows = Vec::new();
for i in 0..4 {
let row: Vec<String> = (0..4).map(|j| format!("#{}", 100 + i * 4 + j)).collect();
for j in 0..4 {
t += &format!("#{}=CARTESIAN_POINT('',({}.,{}.,{}));\n", 100 + i * 4 + j, i * 10, j * 10, z(i, j));
}
rows.push(format!("({})", row.join(",")));
}
t += &format!(
"#10=B_SPLINE_SURFACE_WITH_KNOTS('',3,3,({}),.UNSPECIFIED.,.F.,.F.,.F.,(4,4),(4,4),(0.,1.),(0.,1.),.UNSPECIFIED.);\n",
rows.join(",")
);
// The boundary, counter-clockwise from above: (i, j) runs i = 0 → 3 at j = 0, j = 0 → 3 at
// i = 3, then back; each side's control points are the patch's, raised.
let sides: [[(usize, usize); 4]; 4] =
[[(0, 0), (1, 0), (2, 0), (3, 0)], [(3, 0), (3, 1), (3, 2), (3, 3)], [(3, 3), (2, 3), (1, 3), (0, 3)], [(0, 3), (0, 2), (0, 1), (0, 0)]];
let p = |(i, j): (usize, usize)| format!("({}.,{}.,{})", i * 10, j * 10, z(i, j) + dz);
for (k, side) in sides.iter().enumerate() {
t += &format!("#{}=CARTESIAN_POINT('',{});\n#{}=VERTEX_POINT('',#{});\n", 200 + k, p(side[0]), 210 + k, 200 + k);
let pts: Vec<String> = (0..4).map(|m| format!("#{}", 300 + k * 4 + m)).collect();
for (m, &q) in side.iter().enumerate() {
t += &format!("#{}=CARTESIAN_POINT('',{});\n", 300 + k * 4 + m, p(q));
}
t += &format!("#{}=B_SPLINE_CURVE_WITH_KNOTS('',3,({}),.UNSPECIFIED.,.F.,.F.,(4,4),(0.,1.),.UNSPECIFIED.);\n", 400 + k, pts.join(","));
}
for k in 0..4 {
t += &format!(
"#{}=EDGE_CURVE('',#{},#{},#{},.T.);\n#{}=ORIENTED_EDGE('',*,*,#{},.T.);\n",
500 + k,
210 + k,
210 + (k + 1) % 4,
400 + k,
510 + k,
500 + k
);
}
t += "#520=EDGE_LOOP('',(#510,#511,#512,#513));\n#521=FACE_OUTER_BOUND('',#520,.T.);\n#522=ADVANCED_FACE('',(#521),#10,.T.);\n";
t += "#530=OPEN_SHELL('',(#522));\n#531=SHELL_BASED_SURFACE_MODEL('Dome',(#530));\n#532=MANIFOLD_SURFACE_SHAPE_REPRESENTATION('',(#531),#540);\n";
t += &context(540, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))");
t += TAIL;
t
}
#[test]
fn edges_written_off_their_spline_face_carry_their_gap_as_their_tolerance() {
// 0.2 µm off, 200 times the file's stated uncertainty: each edge's tolerance covers its
// gap and the face imports, its notes saying how many edges and how far.
let imp = step_import(&dome_with_edges_raised(2e-4)).unwrap();
assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings);
assert!(imp.warnings.iter().any(|w| w.contains("4 edges lie off their faces' surfaces")), "{:?}", imp.warnings);
let r = imp.bodies[0].body.record();
assert!(r.edges.iter().all(|e| e.tolerance >= 2e-4 && e.tolerance < 1e-3), "{:?}", r.edges.iter().map(|e| e.tolerance).collect::<Vec<_>>());
// Far off (1.5 mm) is refused, naming the gap.
let far = step_import(&dome_with_edges_raised(1.5));
let refused = match &far {
Ok(i) => i.bodies.is_empty() && i.warnings.iter().any(|w| w.contains("off the face's surface")),
Err(e) => e.to_string().contains("off the face's surface"),
};
assert!(refused, "{far:?}");
}
+34
View File
@@ -182,6 +182,7 @@ pub(crate) fn plan(b: &brep::Brep, tol: f64, turn: Option<size::Turn>) -> Result
.into_iter()
.collect::<Result<_>>()?;
relax_crowded_faces(b, &jobs, &rules, &mut nodes)?;
split_thin_loops(b, &mut nodes)?;
let indexed: Vec<usize> = (0..faces.len()).collect();
let face_boundary = |fi: usize, nodes: &[edges::Nodes]| {
let (Some(face), Some(eval), Some(map)) = (faces.get(fi), evals.get(fi), params.get(fi)) else {
@@ -412,6 +413,39 @@ fn untangle(
/// as often as it takes, down to the tolerance alone (a plate with a thousand small holes is
/// not worth a hundred times the work to draw each hole round). An edge keeps one set of nodes
/// for both its faces, at the coarser of their levels, so every rim of a crowded face gets the
/// Segments an edge loop needs to enclose an area in its face's (u, v).
const MIN_LOOP_SEGMENTS: usize = 3;
/// Every edge loop with fewer than [`MIN_LOOP_SEGMENTS`] segments has its edges' segments halved
/// until it has them: two short arcs (a lens), each within the chord tolerance and so one
/// segment, would otherwise be two chords on one line, a boundary of no area. The new nodes are
/// on the edges' curves and shared by every face that runs them, as all edge nodes are.
fn split_thin_loops(b: &brep::Brep, nodes: &mut [edges::Nodes]) -> Result<()> {
for f in &b.faces {
for l in &f.loops {
let brep::Loop::Edges { edges: uses } = l else { continue };
let mut es: Vec<usize> = uses.iter().map(|u| u.edge as usize).collect();
es.sort_unstable();
es.dedup();
let count = |nodes: &[edges::Nodes]| -> usize {
uses.iter().map(|u| nodes.get(u.edge as usize).map_or(0, |n| n.points.len().saturating_sub(1))).sum()
};
// Each round at least doubles every edge's segments: a few rounds always do.
for _ in 0..MIN_LOOP_SEGMENTS {
if count(nodes) >= MIN_LOOP_SEGMENTS {
break;
}
for &e in &es {
let Some(slot) = nodes.get_mut(e) else { continue };
let segs: Vec<u32> = (0..slot.points.len().saturating_sub(1)).filter_map(|k| u32::try_from(k).ok()).collect();
edges::split_segments(b, e, slot, &segs)?;
}
}
}
}
Ok(())
}
/// same share whatever the order of the faces.
fn relax_crowded_faces(b: &brep::Brep, jobs: &[(usize, f64)], rules: &size::Rules, nodes: &mut [edges::Nodes]) -> Result<()> {
let Some(turn) = rules.turn else { return Ok(()) };
+41
View File
@@ -750,3 +750,44 @@ fn a_face_filled_leniently_is_named_in_the_stats() {
assert_eq!(lenient.face, 7);
assert!(lenient.reason.contains("face 7 (spline)"), "{}", lenient.reason);
}
#[test]
fn a_face_bounded_by_two_short_arcs_keeps_an_area_to_mesh() {
// A lens on z = 0 between two radius-1000 circles crossing at (±10, 0), in a record whose
// other face, a 2 m square, sets the segment length: each arc sags 0.05 mm off its chord,
// inside a 0.5 mm tolerance, so each samples as one segment and the two chords lie on one
// line, a boundary of no area. Its loop's segments are split until it encloses one.
use crate::sew::{PartEdge, PartFace, PartUse, Parts, assemble};
use solidcraft_geom::brep::{Curve, Frame, Surface};
use std::f64::consts::{PI, TAU};
let (r, half) = (1000.0f64, 10.0f64);
let c = (r * r - half * half).sqrt();
let circle = |cy: f64| Curve::Circle { frame: Frame { origin: [0.0, cy, 0.0], x_axis: [1.0, 0.0, 0.0], y_axis: [0.0, 1.0, 0.0] }, radius: r };
let top = c.atan2(half);
let line = |a: [f64; 3], z: [f64; 3]| Curve::Line { start: a, end: z };
let sq = [[3000.0, 0.0, 0.0], [5000.0, 0.0, 0.0], [5000.0, 2000.0, 0.0], [3000.0, 2000.0, 0.0]];
let plane = Surface::Plane { origin: [0.0; 3], u_axis: [1.0, 0.0, 0.0], v_axis: [0.0, 1.0, 0.0] };
let mut edges = vec![
PartEdge { curve: circle(-c), interval: [top, PI - top], vertices: [0, 1] },
PartEdge { curve: circle(c), interval: [PI + top, TAU - top], vertices: [1, 0] },
];
for k in 0..4 {
edges.push(PartEdge { curve: line(sq[k], sq[(k + 1) % 4]), interval: [0.0, 1.0], vertices: [2 + k as u32, 2 + ((k + 1) % 4) as u32] });
}
let uses = |es: &[u32]| es.iter().map(|&edge| PartUse { edge, forward: true, given: None }).collect::<Vec<_>>();
let mut vertices = vec![[half, 0.0, 0.0], [-half, 0.0, 0.0]];
vertices.extend(sq);
let parts = Parts {
vertices,
edges,
faces: vec![
PartFace { surface: plane.clone(), forward: true, loops: vec![uses(&[0, 1])] },
PartFace { surface: plane, forward: true, loops: vec![uses(&[2, 3, 4, 5])] },
],
tolerance: 1e-6,
};
let made = ok(assemble(parts, false));
let (plan, _) = ok(plan(&made.brep, 0.5, None));
let lens = made.faces.first().and_then(|&f| plan.faces.get(f)).expect("the lens's plan");
assert!(!lens.triangles.is_empty(), "the lens has triangles");
}
+5 -2
View File
@@ -185,8 +185,11 @@ fn laid_out(brep: &b::Brep, trusted: bool, analytic: bool, bare: &HashSet<(u32,
a.i(flat::FACE_LOOP_COUNT).push(int(f.loops.len())?);
a.i(flat::FACE_TRIM_TYPE).push(0);
// A face with a NURBS form: what it is (its analytic entry), then the NURBS it is
// parameterised on, whose range and trims these are (FACE_NURBS_FORM).
// parameterised on, whose range and trims these are (FACE_NURBS_FORM). A revolution
// (SMLib has no class for one) is that form alone, a NURBS face.
let form_is_face = f.nurbs.is_some() && matches!(f.surface, b::Surface::PlacedRevolution { .. });
let spline = match &f.nurbs {
Some(n) if form_is_face => surface(&mut a, n, f.domain, analytic)?,
Some(n) => {
surface(&mut a, &f.surface, f.domain, analytic)?;
nurbs_block(&mut a, n)?;
@@ -195,7 +198,7 @@ fn laid_out(brep: &b::Brep, trusted: bool, analytic: bool, bare: &HashSet<(u32,
None => surface(&mut a, &f.surface, f.domain, analytic)?,
};
if any_form {
a.i(flat::FACE_NURBS_FORM).push(i64::from(f.nurbs.is_some()));
a.i(flat::FACE_NURBS_FORM).push(i64::from(f.nurbs.is_some() && !form_is_face));
}
for (li, l) in f.loops.iter().enumerate() {
match l {
+3 -1
View File
@@ -331,8 +331,10 @@ impl Revolution {
let v = [v[0].max(-FRAC_PI_2), v[1].min(FRAC_PI_2)];
return Ok((b::Surface::Sphere { frame: frame(foot), radius }, [angle, v]));
}
// A ring torus only (SMLib has no other): a tube that reaches the axis to rounding (a
// horn torus, major = minor) is none.
let major = off.dot(x);
if !(major > radius) {
if !(major > radius + slack) {
return Err(NOT_ANALYTIC);
}
let torus = b::Surface::Torus { frame: frame(foot), major_radius: major, minor_radius: radius };
+30
View File
@@ -237,3 +237,33 @@ fn arcs_past_a_turn_come_a_turn_back() {
let line = Curve::Line { start: [0.0; 3], end: [1.0, 0.0, 0.0] };
assert_eq!(turned(&line, [7.0, 9.0]), ([7.0, 9.0], 0.0));
}
/// A revolved circle is SMLib's ring torus only where its tube stays off the axis: a tube that
/// reaches it to rounding (a horn torus, its centre as far from the axis as its radius, give or
/// take an ulp) and one across it (a spindle) go as their rational B-splines.
#[test]
fn only_a_tube_clear_of_its_axis_is_a_ring_torus() {
let ring = |major: f64| {
let frame = solidcraft_geom::brep::Frame { origin: [major, 0.0, 0.0], x_axis: [1.0, 0.0, 0.0], y_axis: [0.0, 0.0, 1.0] };
let (profile, _) = solidcraft_geom::brep::form::curve(&Curve::Circle { frame, radius: 1.0 }, [-1.0, 1.0]).unwrap();
let identity = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
let surface =
Surface::PlacedRevolution { profile: Box::new(profile), origin: [0.0; 3], axis: [0.0, 0.0, 1.0], matrix: identity, forward: false };
let face = Face { surface, nurbs: None, domain: [[0.0, 1.0], [-0.5, 0.5]], loops: Vec::new() };
let record = Record {
version: b::VERSION,
tolerance: 1e-6,
regions: Vec::new(),
shells: Vec::new(),
faces: vec![face],
edges: Vec::new(),
vertices: Vec::new(),
};
let made = analytic::analytic(&record).unwrap();
made.faces[0].surface.clone()
};
assert!(matches!(ring(1.5), Surface::Torus { .. }));
for major in [1.0, 1.0 + 4.0 * f64::EPSILON, 0.5] {
assert!(matches!(ring(major), Surface::PlacedRevolution { .. }), "major {major}");
}
}
+65 -3
View File
@@ -23,9 +23,9 @@
//!
//! Tolerances: the representation context's distance uncertainty (default [`DEFAULT_TOLERANCE`]
//! when the file has none, never below [`MIN_TOLERANCE`]) is the brep's tolerance and every
//! vertex's and edge's to start with. A vertex measurably off its curve or surface gets that
//! distance (with margin) as its tolerance; a face whose edges lie off its surface gets its
//! pcurves fitted at a looser tolerance, which its edges then carry.
//! vertex's and edge's to start with. A vertex measurably off its curve or surface, or an edge
//! whose curve lies measurably off a face's surface, gets that distance (with margin) as its
//! tolerance, and the solid's notes say how many and how far.
//!
//! Pcurves are the closed forms the 3D edges have on our surfaces ([`pcurve::exact_pcurves`]); a
//! use with none gets its pcurve from the kernel ([`read_solids_with`], SMLib's own trims). The
@@ -79,6 +79,12 @@ const MAX_SPLINE_DEGREE: usize = 16;
const MAX_SAMPLES: usize = 4096;
/// How far (mm) a vertex may lie from its curve before the edge is refused.
const MAX_VERTEX_GAP: f64 = 1.0;
/// How far (mm) an edge's curve may lie from a face's surface before the face is refused.
const MAX_EDGE_GAP: f64 = 1.0;
/// Intervals an edge's curve is measured over against each face's surface it bounds.
const EDGE_GAP_SAMPLES: usize = 16;
/// An edge's tolerance over the largest gap measured on its samples, as a vertex's is.
const EDGE_GAP_MARGIN: f64 = 1.5;
/// A solid (or sheet) read from the file.
#[derive(Clone, Debug)]
@@ -385,6 +391,8 @@ struct Builder<'b, 'a> {
face_ids: HashSet<u64>,
faces: Vec<FaceB>,
sense_mismatches: usize,
/// Edges whose tolerance was raised to the gap their curve has to a face's surface.
raised_edges: HashSet<u32>,
}
impl<'b, 'a> Builder<'b, 'a> {
@@ -402,6 +410,7 @@ impl<'b, 'a> Builder<'b, 'a> {
face_ids: HashSet::new(),
faces: Vec::new(),
sense_mismatches: 0,
raised_edges: HashSet::new(),
}
}
@@ -436,6 +445,50 @@ impl<'b, 'a> Builder<'b, 'a> {
Ok(())
}
/// Edge `e`'s tolerance covers `gap` (with margin): refused if far off.
fn cover_edge(&mut self, e: u32, gap: f64) -> R<()> {
let Some(x) = self.edges.get_mut(e as usize) else { return Err("edge reference".into()) };
if gap <= x.tolerance {
return Ok(());
}
if !(gap <= MAX_EDGE_GAP) {
return Err(format!("an edge lies {gap} mm off the face's surface"));
}
x.tolerance = EDGE_GAP_MARGIN * gap;
self.raised_edges.insert(e);
Ok(())
}
/// An edge's curve as the file has it may lie off a face's surface by more than the file's
/// uncertainty states (an intersection curve written looser than its context). Each use's
/// gap, between its pcurve on the surface and its edge's curve, is measured along the edge as
/// the record check measures it, and the edge's tolerance covers it, as a vertex's covers its
/// gap: the pcurves are as made and the record says how far its geometry agrees.
fn raise_edges(&mut self, surface: &BSurface, edge_loops: &[Vec<(u32, bool)>], pcs: &[Vec<Curve2>]) -> R<()> {
let on = SurfaceEval::new(surface).map_err(|m| m.to_string())?;
for (l, pc) in edge_loops.iter().zip(pcs) {
for (&(e, _), c) in l.iter().zip(pc) {
let edge = self.edges.get(e as usize).ok_or("edge reference")?;
let (curve, [t0, t1]) = match &edge.form {
Some((c, i)) => (c, *i),
None => (&edge.curve, edge.interval),
};
let eval = CurveEval::new(curve).map_err(|m| m.to_string())?;
let mut gap = 0.0f64;
for k in 0..=EDGE_GAP_SAMPLES {
let t = t0 + (t1 - t0) * (k as f64 / EDGE_GAP_SAMPLES as f64);
// A point a pcurve or surface lacks is the record check's to name.
let (Some(q), Some(p)) = (c.eval(t), eval.point(t)) else { continue };
if let Some(s) = on.point(q) {
gap = gap.max(s.dist(p));
}
}
self.cover_edge(e, gap)?;
}
}
Ok(())
}
/// The schema edge of an EDGE_CURVE, and whether it runs with the STEP edge.
fn edge(&mut self, id: u64) -> R<(u32, bool)> {
if let Some(e) = self.edge_ids.get(&id) {
@@ -749,6 +802,14 @@ impl<'b, 'a> Builder<'b, 'a> {
if let Some(first) = first_failure {
return Err(format!("pcurves failed on {failed} of {} faces; first: {first}", self.faces.len()));
}
if !self.raised_edges.is_empty() {
let most = self.raised_edges.iter().filter_map(|&e| self.edges.get(e as usize)).map(|e| e.tolerance).fold(0.0, f64::max);
notes.push(format!(
"{} edges lie off their faces' surfaces by more than {} mm: their tolerances are the gaps they have (up to {most:.3e} mm)",
self.raised_edges.len(),
self.tol
));
}
let flipped = turned.iter().filter(|t| **t).count();
if flipped > 0 {
notes.push(format!("{flipped} faces turned over: their loops disagree with their same_sense"));
@@ -1036,6 +1097,7 @@ impl<'b, 'a> Builder<'b, 'a> {
};
let pcs =
pcurve::pcurves_within(&surface, &uses_of(&self.edges, &edge_loops, made.as_ref())?, tol, box_on_form).map_err(|e| e.to_string())?;
self.raise_edges(&surface, &edge_loops, &pcs)?;
// Signed areas of the loops that close in (u, v).
let periods = natural_periods(&surface);
// Each use starts near where the one before it ends, along a bounded direction that