SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Wave 296/509: Fillet setbacks not past where the rounds meet are refused naming the least; the rig grades a refusal by its reason (and 3 more)
jyviko7314e9440c59
diff --git a/apps/solidcraft-cli/src/kernel_cases.rs b/apps/solidcraft-cli/src/kernel_cases.rsindex 3d6a01bd1d..ced493a637 100644--- a/apps/solidcraft-cli/src/kernel_cases.rs+++ b/apps/solidcraft-cli/src/kernel_cases.rs@@ -246,9 +246,22 @@ fn check_case(dir: &str, dumps: Option<&std::path::Path>) -> Value {return out;}(Err(e), true) => {- // The right answer is a clean refusal.- out["status"] = json!("pass");- out["refused_with"] = json!(e.to_string());+ // The right answer is a clean refusal, for the reason the case gives: a `refused`+ // case names it (`refusal`, a part of the message), so a failure for another reason+ // (an SMLib status) is not taken for it.+ let e = e.to_string();+ out["refused_with"] = json!(e);+ match want["refusal"].as_str() {+ Some(why) if !e.contains(why) => {+ out["status"] = json!("fail");+ out["error"] = json!(format!("refused, but not because {why:?}: {e}"));+ }+ None if refused => {+ out["status"] = json!("fail");+ out["error"] = json!(format!("refused ({e}), but expected.json gives no `refusal`: the reason it must be refused for"));+ }+ _ => out["status"] = json!("pass"),+ }return out;}(Err(e), false) => {diff --git a/crates/geom/src/brep/form.rs b/crates/geom/src/brep/form.rsindex ea616c877e..05d6f98c1d 100644--- a/crates/geom/src/brep/form.rs+++ b/crates/geom/src/brep/form.rs@@ -50,11 +50,18 @@ pub fn angle(s: f64) -> f64 {q * FRAC_PI_2 + quarter_psi(s - q)}-/// The quarters an angle interval needs: the first one and how many.-fn quarters([a0, a1]: [f64; 2]) -> Option<(f64, usize)> {+/// The quarters an angle interval needs: the first one and how many. An end within `reach` (an+/// angle) of a quarter's end is on it: a face whose boundary lies within its tolerance of a+/// quarter's end needs no part of the quarter past it.+fn quarters([a0, a1]: [f64; 2], reach: f64) -> Option<(f64, usize)> {if !(a0.is_finite() && a1.is_finite() && a1 > a0 && a1 - a0 <= TAU * (1.0 + 1e-9)) {return None;}+ let on_end = |a: f64| {+ let end = (a / FRAC_PI_2).round() * FRAC_PI_2;+ if (a - end).abs() <= reach { end } else { a }+ };+ let (a0, a1) = (on_end(a0), on_end(a1));let q0 = quarter_of(a0);let q1 = (a1 / FRAC_PI_2 - SLACK).ceil();let n = (q1 - q0).max(1.0) as usize;@@ -63,13 +70,14 @@ fn quarters([a0, a1]: [f64; 2]) -> Option<(f64, usize)> {/// A face's quarters along an angle direction and its domain there: a whole turn is exactly/// four quarters from the one it starts in (the form closes on itself, so it is periodic and the-/// face's seam uses lie a period apart), anything less the quarters it needs.-fn face_quarters(a: [f64; 2]) -> Option<((f64, usize), [f64; 2])> {+/// face's seam uses lie a period apart), anything less the quarters it needs ([`quarters`], ends+/// within `reach` of a quarter's end on it).+fn face_quarters(a: [f64; 2], reach: f64) -> Option<((f64, usize), [f64; 2])> {if a[1] - a[0] >= TAU * (1.0 - 1e-9) {let q0 = quarter_of(a[0]);return Some(((q0, 4), [q0, q0 + 4.0]));}- let grid = quarters(a)?;+ let grid = quarters(a, reach)?;Some((grid, params(a, grid)))}@@ -130,7 +138,7 @@ pub fn curve(c: &Curve, [t0, t1]: [f64; 2]) -> Option<(Curve, [f64; 2])> {fn conic(frame: &Frame, [rx, ry]: [f64; 2], t: [f64; 2]) -> Option<(Curve, [f64; 2])> {let (o, x, y, _) = axes(frame)?;- let grid = quarters(t)?;+ let grid = quarters(t, 0.0)?;let (knots, pts) = arcs(grid.0, grid.1);let homogeneous = pts.iter().map(|([c, s], w)| hom(o + x * (rx * c) + y * (ry * s), *w)).collect();Some((Curve::RationalSpline { knots, homogeneous }, params(t, grid)))@@ -139,8 +147,30 @@ fn conic(frame: &Frame, [rx, ry]: [f64; 2], t: [f64; 2]) -> Option<(Curve, [f64;/// The NURBS form of a cylinder, cone, sphere or torus face over `domain` (in the label's/// parameters: angles, and the height along the axis of a cylinder or cone) and the domain in the/// form's parameters; `None` for another kind, or a domain of more than one turn.-pub fn surface(s: &Surface, [u, v]: [[f64; 2]; 2]) -> Option<(Surface, [[f64; 2]; 2])> {- let (grid, fu) = face_quarters(u)?;+pub fn surface(s: &Surface, domain: [[f64; 2]; 2]) -> Option<(Surface, [[f64; 2]; 2])> {+ surface_within(s, domain, 0.0)+}++/// [`surface`] for a face whose boundary lies within `tolerance` (mm) of its surface: where the+/// domain ends within `tolerance` of a quarter's end (the angle that far along the widest circle+/// of the face in that direction), the form ends there too. A face's box is the extent of its+/// boundary's points ([`extent`]), which may run past a quarter's end by as much as its edges lie+/// off the surface; the form then covers no quarter for that alone (a torus face of half a tube+/// would otherwise go round the whole tube).+pub fn surface_within(s: &Surface, [u, v]: [[f64; 2]; 2], tolerance: f64) -> Option<(Surface, [[f64; 2]; 2])> {+ // The angle `tolerance` makes on a circle of `radius`.+ let reach = |radius: f64| if tolerance > 0.0 && radius > 0.0 && radius.is_finite() { tolerance / radius } else { 0.0 };+ let (reach_u, reach_v) = match s {+ Surface::Cylinder { radius, .. } => (reach(radius.abs()), 0.0),+ Surface::Cone { radius_at_origin, half_angle, .. } => {+ let slope = half_angle.tan();+ (reach(v.iter().map(|h| (radius_at_origin + h * slope).abs()).fold(0.0, f64::max)), 0.0)+ }+ Surface::Sphere { radius, .. } => (reach(radius.abs()), reach(radius.abs())),+ Surface::Torus { major_radius, minor_radius, .. } => (reach(major_radius.abs() + minor_radius.abs()), reach(minor_radius.abs())),+ _ => (0.0, 0.0),+ };+ let (grid, fu) = face_quarters(u, reach_u)?;let (u_knots, ring) = arcs(grid.0, grid.1);// The ring of arcs times a profile `(control, weight)` mapped to (radial, axial) about the// frame: a rational tensor product, its weights the products.@@ -173,13 +203,13 @@ pub fn surface(s: &Surface, [u, v]: [[f64; 2]; 2]) -> Option<(Surface, [[f64; 2]Some((Surface::RationalSpline { u_knots, v_knots: vec![v[0], v[0], v[1], v[1]], homogeneous }, [fu, v]))}Surface::Sphere { frame, radius } => {- let vgrid = quarters(v)?;+ let vgrid = quarters(v, reach_v)?;let (v_knots, meridian) = arcs(vgrid.0, vgrid.1);let homogeneous = net(frame, &meridian, &|[c, s]| (radius * c, radius * s))?;Some((Surface::RationalSpline { u_knots, v_knots, homogeneous }, [fu, params(v, vgrid)]))}Surface::Torus { frame, major_radius, minor_radius } => {- let (vgrid, fv) = face_quarters(v)?;+ let (vgrid, fv) = face_quarters(v, reach_v)?;let (v_knots, tube) = arcs(vgrid.0, vgrid.1);let homogeneous = net(frame, &tube, &|[c, s]| (major_radius + minor_radius * c, minor_radius * s))?;Some((Surface::RationalSpline { u_knots, v_knots, homogeneous }, [fu, fv]))@@ -189,7 +219,7 @@ pub fn surface(s: &Surface, [u, v]: [[f64; 2]; 2]) -> Option<(Surface, [[f64; 2]// zero (the profile): (a + ib)(c + is) for each point's radial (a, b) in the frame and// each arc control point (c, s), weights multiplied; then the matrix.let (angles, along) = if *forward { (v, u) } else { (u, v) };- let (ring_grid, fa) = face_quarters(angles)?;+ let (ring_grid, fa) = face_quarters(angles, 0.0)?;let (a_knots, arcs_r) = arcs(ring_grid.0, ring_grid.1);let (p_knots, h) = profile_nurbs(profile, Some(along))?;let fp = match profile.as_ref() {diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rsindex bfbde93e94..4f006e0a54 100644--- a/crates/kernel/src/blend.rs+++ b/crates/kernel/src/blend.rs@@ -225,9 +225,92 @@ pub fn fillet(body: &Body, edges: &[Vec3], radius: f64) -> Result<Body> {pub fn fillet_setback(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)]) -> Result<Body> {let _span = solidcraft_profile::span("kernel", "fillet_setback");body.require_brep("fillet")?;+ setbacks_reach(body, edges, radius, setbacks)?;crate::blend_smlib::fillet_setback(body, edges, radius, setbacks).and_then(|b| closed(body, b))}+/// Refuses a setback that does not reach past where its corner's rounds meet without one+/// ([`setback_minimum`]), naming the least it must exceed, at a corner where every edge is one+/// of `edges` (the others are SMLib's to refuse). SMLib fails there with its own status+/// (smlib_blend_setback): its patch does not join contact lines that already cross.+fn setbacks_reach(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)]) -> Result<()> {+ let faces = Faces::of(body)?;+ let (picked, _) = crate::blend_smlib::picked_edges(body, edges)?;+ let picked: BTreeSet<usize> = picked.into_iter().collect();+ let reach = body.size() * 0.05 + 1e-3;+ for (at, distance) in setbacks {+ let nearest = (0..faces.rec.vertices.len())+ .filter_map(|v| u32::try_from(v).ok())+ .filter_map(|v| faces.point(v).map(|p| (p.dist(*at), v)))+ .filter(|(d, _)| *d <= reach)+ .min_by(|a, b| a.0.total_cmp(&b.0));+ let Some((_, v)) = nearest else { continue };+ let all_rounded = (0..faces.rec.edges.len())+ .filter(|e| faces.rec.edges.get(*e).is_some_and(|x| !x.uses.is_empty() && x.vertices.contains(&v)))+ .all(|e| picked.contains(&e));+ if !all_rounded {+ continue;+ }+ let Some(least) = setback_minimum(&faces, v, radius) else { continue };+ if *distance <= least * (1.0 + 1e-9) {+ let p = faces.point(v).unwrap_or(*at);+ let shown = format!("{:.4}", least).trim_end_matches('0').trim_end_matches('.').to_string();+ let why =+ if (least - radius).abs() <= radius * 1e-9 { format!("more than the radius ({shown} mm)") } else { format!("more than {shown} mm") };+ return Err(KernelError::Invalid(format!(+ "the setback must be {why} at the corner ({:.3}, {:.3}, {:.3}): the rounds' contact lines meet {shown} mm from it along its edges, \+ and the corner's patch starts past that",+ p.x, p.y, p.z+ )));+ }+ }+ Ok(())+}++/// The least setback a corner of rounds of `radius` at `vertex` takes: on each face at the+/// corner, the contact lines (rails) of the two rounded edges beside it cross, and a setback+/// must reach past that crossing along both edges (smlib_blend_setback). A rail lies+/// r tan(psi / 2) from its edge, psi the angle between the outward normals of the edge's two+/// faces (r on faces square to each other); the rails of edges at angle alpha on a face, d1 and+/// d2 from them, cross (d2 + d1 cos alpha) / sin alpha along the first edge from the vertex.+/// Exact for planar faces and straight edges; `None` for a corner with any other (left to SMLib)+/// or one it cannot read.+fn setback_minimum(faces: &Faces, vertex: u32, radius: f64) -> Option<f64> {+ let at: Vec<usize> =+ (0..faces.rec.edges.len()).filter(|e| faces.rec.edges.get(*e).is_some_and(|x| !x.uses.is_empty() && x.vertices.contains(&vertex))).collect();+ if at.len() < 3 {+ return None;+ }+ // Each edge's direction away from the vertex and its rail's distance from it.+ let mut away = Vec::with_capacity(at.len());+ let mut rail = Vec::with_capacity(at.len());+ for e in &at {+ let [a, b] = faces.rec.edges.get(*e)?.vertices;+ if a == b || !faces.straight(*e) {+ return None;+ }+ let (pa, pb) = faces.ends(*e)?;+ away.push(if a == vertex { (pb - pa).normalized()? } else { (pa - pb).normalized()? });+ let [f, g]: [u32; 2] = faces.faces_of(*e).into_iter().collect::<Vec<_>>().try_into().ok()?;+ let cos = faces.plane_normal(f as usize)?.dot(faces.plane_normal(g as usize)?).clamp(-1.0, 1.0);+ rail.push(radius * (cos.acos() / 2.0).tan());+ }+ let mut least: f64 = 0.0;+ let around: BTreeSet<u32> = at.iter().flat_map(|e| faces.faces_of(*e)).collect();+ for f in around {+ let beside: Vec<usize> = (0..at.len()).filter(|i| at.get(*i).is_some_and(|e| faces.faces_of(*e).contains(&f))).collect();+ let [i, j] = beside[..] else { return None };+ let cos = away.get(i)?.dot(*away.get(j)?).clamp(-1.0, 1.0);+ let sin = (1.0 - cos * cos).sqrt();+ if sin <= 1e-9 {+ return None;+ }+ let (di, dj) = (*rail.get(i)?, *rail.get(j)?);+ least = least.max((dj + di * cos) / sin).max((di + dj * cos) / sin);+ }+ (least.is_finite() && least > 0.0).then_some(least)+}+/// [`fillet`] whose corners where three or more rounded edges meet are G2 patches/// ([`crate::corner_g2`]): each such corner is set back, `setbacks` naming a corner by a point at/// its vertex and the distance its patch starts along each edge there (the others take@@ -298,6 +381,7 @@ pub fn fillet_g2_corners(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(}}let set_back: Vec<(Vec3, f64)> = corners.iter().copied().zip(distance).collect();+ setbacks_reach(body, edges, radius, &set_back)?;let open = crate::blend_smlib::fillet_setback_open(body, edges, radius, &set_back)?;let mut patches = Vec::with_capacity(open.holes.len());for hole in &open.holes {diff --git a/crates/kernel/src/fillet_setback_tests.rs b/crates/kernel/src/fillet_setback_tests.rsindex d1e0a886c4..69bf82c502 100644--- a/crates/kernel/src/fillet_setback_tests.rs+++ b/crates/kernel/src/fillet_setback_tests.rs@@ -42,3 +42,18 @@ fn a_setback_off_the_rounded_corner_is_refused() {assert!(fillet_setback(&b, &edges, 5.0, &[(Vec3::new(0.0, 0.0, 0.0), 8.0)]).is_err());assert!(matches!(corner_case(Some(20.0)), Err(KernelError::TooLarge(_))));}++/// A setback that does not reach past where the corner's rounds meet without one (on faces square+/// to each other, the radius) is refused before SMLib runs, naming that least setback; a setback+/// just past it builds.+#[test]+fn a_setback_not_past_the_radius_is_refused_naming_the_least() {+ for s in [2.0, 5.0] {+ match corner_case(Some(s)) {+ Err(KernelError::Invalid(why)) => assert!(why.contains("setback must be more than the radius (5 mm)"), "{why}"),+ other => panic!("setback {s}: {:?}", other.map(|b| b.face_count())),+ }+ }+ let out = corner_case(Some(5.5)).unwrap();+ assert!(out.validity().is_empty(), "{:?}", out.validity());+}diff --git a/crates/kernel/src/step_in/mod.rs b/crates/kernel/src/step_in/mod.rsindex 3485b6cab0..ebc8df0085 100644--- a/crates/kernel/src/step_in/mod.rs+++ b/crates/kernel/src/step_in/mod.rs@@ -624,10 +624,22 @@ impl Reader {self.warn(format!("more than {MAX_BODIES} bodies: the rest are left out"));return;}- // The node lists the planned solid; it becomes a body index once converted.- out.push(self.plan.len());- self.plan.push(Planned { item, units: u, batch: id });- *self.uses.entry(item).or_default() += 1;+ // The node lists the planned solids (a surface model's closed shells+ // beside its sheet are solids of their own, in the model's colour); each+ // becomes a body index once converted.+ for piece in solidcraft_step::topology::items(&self.ex, item) {+ if piece != item {+ if let Some(c) = self.colors.get(&item).copied() {+ self.colors.entry(piece).or_insert(c);+ }+ if let Some(o) = self.opacity.get(&item).copied() {+ self.opacity.entry(piece).or_insert(o);+ }+ }+ out.push(self.plan.len());+ self.plan.push(Planned { item: piece, units: u, batch: id });+ *self.uses.entry(piece).or_default() += 1;+ }}}"MAPPED_ITEM" => {diff --git a/crates/kernel/src/step_in/tests.rs b/crates/kernel/src/step_in/tests.rsindex 6deee12752..3481fa9ef0 100644--- a/crates/kernel/src/step_in/tests.rs+++ b/crates/kernel/src/step_in/tests.rs@@ -394,6 +394,38 @@ fn shelled_three_quarter_tube_round_trips() {round_trip(&b);}+/// A half tube (half a torus's tube, half way round, closed by a flat annulus and+/// two flat ends) whose torus the file places 5 nm off the rest, well within the file's+/// accuracy: the torus face's boundary then projects a hair past both ends of its half of the+/// tube, and its NURBS form once took the quarter past each end too, going round the whole tube,+/// which SMLib does not take for a torus: the part came in as a mesh of its faces.+#[test]+fn half_tube_a_hair_off_its_torus_imports_as_a_solid() {+ use solidcraft_geom::Seg2;+ use std::f64::consts::PI;+ let (major, minor) = (10.75, 1.25);+ let d = Loop2 {+ segs: vec![+ Seg2::Arc { center: Vec2::new(major, 0.0), radius: minor, start: 0.0, sweep: PI },+ Seg2::Line { a: Vec2::new(major - minor, 0.0), b: Vec2::new(major + minor, 0.0) },+ ],+ };+ let tube = revolve(&Plane::XZ, &[Region2 { outer: d, holes: vec![] }], Vec2::ZERO, Vec2::Y, PI).unwrap().pop().unwrap();+ let text = step_export(&[&tube], "test").unwrap();+ // The torus's placement moved to a point of its own, 5 nm along the axis, off the face's side.+ let torus = text.lines().find_map(|l| l.split_once("=TOROIDAL_SURFACE('',#")).unwrap().1.split(',').next().unwrap().to_string();+ let place = text.lines().find(|l| l.starts_with(&format!("#{torus}=AXIS2_PLACEMENT_3D('',#"))).unwrap();+ let (_, axes) = place.split_once("('',#").unwrap().1.split_once(',').unwrap();+ let mut low = text.replace(place, &format!("#{torus}=AXIS2_PLACEMENT_3D('',#900000,{axes}"));+ let data_end = low.rfind("ENDSEC;").unwrap();+ low.insert_str(data_end, "#900000=CARTESIAN_POINT('',(0.0,0.0,-5.E-6));\n");+ let imp = step_import(&low).unwrap();+ assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings);+ let b = &imp.bodies[0];+ assert!(b.refused.is_none() && b.closed && !b.body.is_mesh() && !b.body.is_surface(), "{:?} {:?}", b.refused, imp.warnings);+ assert!(rel(measure(&b.body).unwrap().volume, measure(&tube).unwrap().volume) < 1e-3);+}+#[test]fn several_bodies_and_names() {let a = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap();@@ -538,6 +570,46 @@ fn product(pd: u64, name: &str) -> String {)}+/// A surface model of a closed shell and an open one beside it (Poppy Humanoid's thighs: the+/// part, and a sheet of two faces on it) comes in as two bodies: the closed shell a solid of its+/// own, the open one a surface body, each in the model's colour. It once came in as one body,+/// open for its sheet's edges.+#[test]+fn a_surface_models_closed_shell_beside_a_sheet_is_a_solid_of_its_own() {+ let mut t = String::from(HEAD);+ t += &cube_entities();+ // A unit square sheet at z = 5.+ let corners = [(0, 0), (1, 0), (1, 1), (0, 1)];+ for (i, (x, y)) in corners.iter().enumerate() {+ t += &format!("#{}=CARTESIAN_POINT('',({x}.,{y}.,5.));\n#{}=VERTEX_POINT('',#{});\n", 800 + i, 810 + i, 800 + i);+ }+ let mut oes = Vec::new();+ for i in 0..4 {+ let (a, b) = (corners[i], corners[(i + 1) % 4]);+ t += &format!("#{}=DIRECTION('',({}.,{}.,0.));\n#{}=VECTOR('',#{},1.);\n", 820 + 2 * i, b.0 - a.0, b.1 - a.1, 821 + 2 * i, 820 + 2 * i);+ t += &format!("#{}=LINE('',#{},#{});\n", 830 + i, 800 + i, 821 + 2 * i);+ t += &format!("#{}=EDGE_CURVE('',#{},#{},#{},.T.);\n", 840 + i, 810 + i, 810 + (i + 1) % 4, 830 + i);+ t += &format!("#{}=ORIENTED_EDGE('',*,*,#{},.T.);\n", 850 + i, 840 + i);+ oes.push(format!("#{}", 850 + i));+ }+ t += &format!("#860=EDGE_LOOP('',({}));\n#861=FACE_OUTER_BOUND('',#860,.T.);\n", oes.join(","));+ t += "#862=CARTESIAN_POINT('',(0.,0.,5.));\n#863=DIRECTION('',(0.,0.,1.));\n#864=AXIS2_PLACEMENT_3D('',#862,#863,$);\n#865=PLANE('',#864);\n";+ t += "#866=ADVANCED_FACE('',(#861),#865,.T.);\n#130=OPEN_SHELL('',(#866));\n#110=SHELL_BASED_SURFACE_MODEL('Thigh',(#100,#130));\n";+ t += &context(20, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))");+ t += "#60=MANIFOLD_SURFACE_SHAPE_REPRESENTATION('',(#110),#20);\n";+ t += "#70=STYLED_ITEM('',(#71),#110);\n#71=PRESENTATION_STYLE_ASSIGNMENT((#72));\n#72=SURFACE_STYLE_USAGE(.BOTH.,#73);\n#73=SURFACE_SIDE_STYLE('',(#74));\n#74=SURFACE_STYLE_FILL_AREA(#75);\n#75=FILL_AREA_STYLE('',(#76));\n#76=FILL_AREA_STYLE_COLOUR('',#77);\n#77=COLOUR_RGB('',1.,0.5,0.);\n";+ t += TAIL;+ let imp = step_import(&t).unwrap();+ assert_eq!(imp.bodies.len(), 2, "{:?}", imp.warnings);+ let (solid, sheet) = (&imp.bodies[0], &imp.bodies[1]);+ assert!(solid.closed && solid.refused.is_none() && !solid.body.is_surface(), "{:?}", imp.warnings);+ assert_eq!((solid.source_item, solid.file_faces), (100, 6));+ assert!(rel(measure(&solid.body).unwrap().volume, 1.0) < 1e-9);+ assert!(!sheet.closed && sheet.body.is_surface() && sheet.body.face_count() == 1);+ assert_eq!((sheet.source_item, sheet.name.as_str()), (110, "Thigh"));+ assert!(imp.bodies.iter().all(|b| b.color == Some([1.0, 0.5, 0.0])));+}+#[test]fn hand_written_part_in_inches_with_colour() {let mut t = String::from(HEAD);diff --git a/crates/step/src/topology.rs b/crates/step/src/topology.rsindex 5ca4b5d35b..e89ef795bb 100644--- a/crates/step/src/topology.rs+++ b/crates/step/src/topology.rs@@ -248,9 +248,24 @@ pub fn read_solids_with(ex: &Exchange, trims: &dyn Trims) -> Solids {}fn read_solids_in(ex: &Exchange, trims: Option<&dyn Trims>) -> Solids {- let mut items: Vec<u64> = ex.entities.iter().filter(|(_, e)| SOLID_ITEMS.contains(&e.name())).map(|(id, _)| *id).collect();- items.sort_unstable();- let index = Index::new(ex);+ let mut solids: Vec<u64> = ex.entities.iter().filter(|(_, e)| SOLID_ITEMS.contains(&e.name())).map(|(id, _)| *id).collect();+ solids.sort_unstable();+ let mut index = Index::new(ex);+ // A surface model's closed shells read on their own sit where the model does.+ let mut items = Vec::with_capacity(solids.len());+ for solid in solids {+ for piece in self::items(ex, solid) {+ if piece != solid {+ if let Some(c) = index.context.get(&solid).copied() {+ index.context.insert(piece, c);+ }+ if let Some(p) = index.product.get(&solid).cloned() {+ index.product.insert(piece, p);+ }+ }+ items.push(piece);+ }+ }let mut out = Solids::default();let mut budget = MAX_FILE_FACES;let mut readers: HashMap<u64, (Reader<'_>, units::Context)> = HashMap::new();@@ -334,7 +349,7 @@ fn read_with<'a>(let mut b = Builder::new(ex, reader, tolerance(&context), budget, trims);// The file's faces, edges, vertices and their geometry read into the builder.let topology = solidcraft_profile::span("import", "step.topology");- let (ids, kind) = item_shells(e)?;+ let (ids, kind) = item_shells(ex, item)?;let mut shells = Vec::with_capacity(ids.len());let mut skipped = false;for s in ids {@@ -362,7 +377,7 @@ pub struct FaceRead {/// as [`read_solid_with`] reads it, with its own edges and vertices (so its tolerances cover its/// own gaps only); a face that cannot be read on its own says why and the others are still read.pub fn read_faces_with(ex: &Exchange, item: u64, context: units::Context, trims: &dyn Trims) -> R<Vec<FaceRead>> {- let (shells, _) = item_shells(entity(ex, item)?)?;+ let (shells, _) = item_shells(ex, item)?;let mut reader = Reader::new(ex, context.units);let mut budget = MAX_FILE_FACES;let mut out = Vec::new();@@ -384,8 +399,31 @@ pub fn read_faces_with(ex: &Exchange, item: u64, context: units::Context, trims:Ok(out)}+/// A surface model's shells the file calls closed and the others, in its order.+fn model_shells(ex: &Exchange, shells: &[u64]) -> (Vec<u64>, Vec<u64>) {+ shells.iter().partition(|s| ex.get(**s).is_some_and(|e| matches!(e.name(), "CLOSED_SHELL" | "ORIENTED_CLOSED_SHELL")))+}++/// The items a solid item is read as, each one body: the item itself, but for a surface model+/// with both closed and open shells (a part with a sheet beside it) each closed shell on its own+/// (a solid), then the model (its open shells, a sheet).+pub fn items(ex: &Exchange, item: u64) -> Vec<u64> {+ let shells = match ex.get(item) {+ Some(e) if e.name() == "SHELL_BASED_SURFACE_MODEL" => {+ e.params().get(1).and_then(Param::as_list).unwrap_or(&[]).iter().filter_map(Param::as_ref_id).collect()+ }+ _ => Vec::new(),+ };+ let (closed, open) = model_shells(ex, &shells);+ if closed.is_empty() || open.is_empty() {+ return vec![item];+ }+ closed.into_iter().chain([item]).collect()+}+/// The shells of a solid item (the outer shell first, then its voids), and what kind it is.-fn item_shells(e: &Entity) -> R<(Vec<u64>, Kind)> {+fn item_shells(ex: &Exchange, item: u64) -> R<(Vec<u64>, Kind)> {+ let e = entity(ex, item)?;let p = e.params();match e.name() {"MANIFOLD_SOLID_BREP" => Ok((vec![rid(p.get(1), "outer shell")?], Kind::Solid)),@@ -403,8 +441,12 @@ fn item_shells(e: &Entity) -> R<(Vec<u64>, Kind)> {if ids.is_empty() || ids.len() > brep::MAX_SHELLS {return Err(format!("a surface model with {} shells", ids.len()));}- Ok((ids, Kind::Model))+ // Its closed shells, where it has open ones too, are items of their own ([`items`]).+ let (closed, open) = model_shells(ex, &ids);+ Ok((if closed.is_empty() || open.is_empty() { ids } else { open }, Kind::Model))}+ // A closed shell of a surface model that has open shells too ([`items`]).+ "CLOSED_SHELL" | "ORIENTED_CLOSED_SHELL" => Ok((vec![item], Kind::Model)),n => Err(unsupported(n)),}}@@ -1226,7 +1268,7 @@ impl<'b, 'a> Builder<'b, 'a> {boundary.push(b);}let extent = brep::form::extent(&label, &boundary).ok_or_else(|| unsupported("a face whose boundary does not lie on its surface"))?;- Some(brep::form::surface(&label, extent).ok_or_else(|| unsupported("a face of more than one turn"))?)+ Some(brep::form::surface_within(&label, extent, tol).ok_or_else(|| unsupported("a face of more than one turn"))?)}None => None,};diff --git a/tests/kernel-cases/README.md b/tests/kernel-cases/README.mdindex 5de1011e42..4125c76dbe 100644--- a/tests/kernel-cases/README.md+++ b/tests/kernel-cases/README.md@@ -83,6 +83,7 @@ the frozen truck-geometry PRs, a `kernel-paused` PR), for the report's coverage| `source` | `analytic` (numbers worked out by hand; `method` gives the formulas) or `invariants` (no number is known: only the outcome, validity and counts are graded). || `method` | How the numbers were derived, or which invariants hold and why. || `outcome` | `solid` (default: the script succeeds), `refused` (the right answer is a clean error, never a panic or a hang), or `solid_or_refused` (either a clean error or a result graded as usual, where the geometry has no single manifold answer, such as two bodies touching along a curve only). |+| `refusal` | Required with `outcome: refused` (optional with `solid_or_refused`): a part of the refusal's message, the reason it must be refused for. A refusal for another reason (an SMLib status, a different check) fails. || `valid` | Default `true`: every body is one closed shell (or `shells` in all) that passes the record's structure and geometry checks and SMLib's `check(All)`. `false` only where the result is legitimately not a solid (a sheet). Where SMLib can't take the record yet (a surface kind its conversion lacks), its check gives no verdict and is not graded. || `shells` | The total number of shells, where it isn't one per body: a body with a sealed void (2), several lumps kept in one body. || `body_count`, `faces`, `edges`, `vertices` | Exact counts, where the geometry fixes them. Faces and edges count whole analytic surfaces and curves once (a full cylinder side is one face). |diff --git a/tests/kernel-cases/fillets/1207-fillet-bar-top-edge-after-boss-arc-round-no-tangent-chain/expected.json b/tests/kernel-cases/fillets/1207-fillet-bar-top-edge-after-boss-arc-round-no-tangent-chain/expected.jsonindex d1cb67164c..f0ed48f17c 100644--- a/tests/kernel-cases/fillets/1207-fillet-bar-top-edge-after-boss-arc-round-no-tangent-chain/expected.json+++ b/tests/kernel-cases/fillets/1207-fillet-bar-top-edge-after-boss-arc-round-no-tangent-chain/expected.json@@ -4,7 +4,8 @@],"what": "after the boss's partial base arc is rounded r2, the bar's top edge that runs into the round rounded r2 without its tangent chain","source": "invariants",- "method": "bar and boss as 1207-fillet-bar-top-edge-and-boss-arc-together; the base arc rounded r2 first (V0 + 28.9190), running out over the front face where its section is a curve on that face tangent to the bar's top edge; then that edge rounded r2 alone (tangent chain off): it ends where the section curve goes on tangentially, so a clean refusal or a valid body",+ "method": "bar and boss as 1207-fillet-bar-top-edge-and-boss-arc-together; the base arc rounded r2 first (V0 + 28.9190), running out over the front face where its section is a curve on that face tangent to the bar's top edge; then that edge rounded r2 alone (tangent chain off): it ends where the section curve goes on tangentially, so a valid body or a refusal saying so (the edge continues tangentially)","body_count": 1,- "outcome": "solid_or_refused"+ "outcome": "solid_or_refused",+ "refusal": "continues tangentially"}diff --git a/tests/kernel-cases/fillets/1390-chamfer-hole-rim-touching-bottom/expected.json b/tests/kernel-cases/fillets/1390-chamfer-hole-rim-touching-bottom/expected.jsonindex 12ae742f5c..f24e04bdc1 100644--- a/tests/kernel-cases/fillets/1390-chamfer-hole-rim-touching-bottom/expected.json+++ b/tests/kernel-cases/fillets/1390-chamfer-hole-rim-touching-bottom/expected.json@@ -7,5 +7,6 @@"what": "a 3 mm chamfer on the rim of a hole that is tangent to the bottom face runs off that face and must not add material below the part","source": "invariants","method": "cube 20 with a diameter 10 hole along -Y from the back face, its axis at z=5 so the hole wall touches the bottom face z=0 along one line. The hole rim on the back face has no face material between it and the bottom edge there, so a 3 mm setback cannot lie on the face: no chamfer of that size exists. The right answer is a clean refusal (a chamfer of a convex edge only ever removes material; building it grew the part by 1067 mm3 below the bottom face).",- "outcome": "refused"+ "outcome": "refused",+ "refusal": "larger than the faces beside its edges allow"}\ No newline at end of filediff --git a/tests/kernel-cases/fillets/3435-fillet-larger-than-top-ring/expected.json b/tests/kernel-cases/fillets/3435-fillet-larger-than-top-ring/expected.jsonindex bc6e1c9e01..b400385d55 100644--- a/tests/kernel-cases/fillets/3435-fillet-larger-than-top-ring/expected.json+++ b/tests/kernel-cases/fillets/3435-fillet-larger-than-top-ring/expected.json@@ -6,5 +6,6 @@"what": "a fillet of radius 6.9 on a cylinder rim whose flat top ring (round the joined boss) is only 4.3 mm wide must be refused, not grow the part","source": "invariants","method": "cylinder radius 7, boss radius 2.7 flush on its top face: the flat ring round the boss is 7 - 2.7 = 4.3 mm wide, and a rolling-ball round of radius 6.9 needs 6.9 mm of top face (for a convex rim the round consumes r of each neighbouring face). No such round exists, so the right answer is a clean refusal; accepting it produced a body larger than before the fillet (a round only removes material).",- "outcome": "refused"+ "outcome": "refused",+ "refusal": "larger than the faces beside its edges allow"}\ No newline at end of filediff --git a/tests/kernel-cases/fillets/4782-fillet-two-end-verticals-past-a-full-round/expected.json b/tests/kernel-cases/fillets/4782-fillet-two-end-verticals-past-a-full-round/expected.jsonindex c2e80c5d74..04e5adeb50 100644--- a/tests/kernel-cases/fillets/4782-fillet-two-end-verticals-past-a-full-round/expected.json+++ b/tests/kernel-cases/fillets/4782-fillet-two-end-verticals-past-a-full-round/expected.json@@ -4,6 +4,7 @@],"what": "both vertical edges of a 15 mm wide box end rounded r10, past the full round (7.5): refused","source": "invariants",- "method": "each round's rail on the end face lies 10 from its edge, past the other's (15 - 10 = 5): the rounds would cross on the face; the largest that fits is the full round, 7.5",- "outcome": "refused"+ "method": "each round's rail on the end face lies 10 from its edge, past the other's (15 - 10 = 5): the rounds would cross on the face; refused as too large (the largest that fits is the full round, 7.5, which fit reduce finds)",+ "outcome": "refused",+ "refusal": "larger than the faces beside its edges allow"}diff --git a/tests/kernel-cases/fillets/783-fillet-pick-far-from-any-edge-refused/expected.json b/tests/kernel-cases/fillets/783-fillet-pick-far-from-any-edge-refused/expected.jsonindex e9b1fbe7c8..b055f1b043 100644--- a/tests/kernel-cases/fillets/783-fillet-pick-far-from-any-edge-refused/expected.json+++ b/tests/kernel-cases/fillets/783-fillet-pick-far-from-any-edge-refused/expected.json@@ -6,5 +6,6 @@"what": "a fillet whose edge pick is 15 mm from the nearest edge must be refused, not applied to some other edge","source": "invariants","method": "box 20x20x10 and a pick at (10,-15,10): the nearest edge is the top front edge, 15 mm away, so the pick names no edge. The right answer is a clean refusal (never silently rounding the nearest edge).",- "outcome": "refused"+ "outcome": "refused",+ "refusal": "no edge at"}\ No newline at end of filediff --git a/tests/kernel-cases/fillets/896-fillet-smooth-seam-refused/expected.json b/tests/kernel-cases/fillets/896-fillet-smooth-seam-refused/expected.jsonindex 8bfa828bf4..e103b5c107 100644--- a/tests/kernel-cases/fillets/896-fillet-smooth-seam-refused/expected.json+++ b/tests/kernel-cases/fillets/896-fillet-smooth-seam-refused/expected.json@@ -6,5 +6,6 @@"what": "a fillet picked on the seam where a rounded edge runs tangent into the flat top has no corner to round and is refused as an invalid pick","source": "invariants","method": "box 40x30x20 with all 12 edges rounded R3 (faces: 6 planes, 12 quarter cylinders, 8 sphere octants). The line at y=3 along the top where the flat top meets the R3 round tangentially is a smooth edge (dihedral 180 degrees): there is no corner to fillet, so the pick is refused with a clean error, never a result.",- "outcome": "refused"+ "outcome": "refused",+ "refusal": "is smooth"}\ No newline at end of filediff --git a/tests/kernel-cases/fillets/9-fillet-corner-setback-1-5-not-past-r2-curvature/expected.json b/tests/kernel-cases/fillets/9-fillet-corner-setback-1-5-not-past-r2-curvature/expected.jsonindex eac02c13ab..d2c71fe052 100644--- a/tests/kernel-cases/fillets/9-fillet-corner-setback-1-5-not-past-r2-curvature/expected.json+++ b/tests/kernel-cases/fillets/9-fillet-corner-setback-1-5-not-past-r2-curvature/expected.json@@ -4,6 +4,7 @@],"what": "three r2 rounds at a box corner, curvature (g2) corner, set back 1.5: not past where the rounds meet (r): refused","source": "invariants",- "method": "a setback must reach past where the corner's rounds meet without one, past r = 2 on a corner of faces square to each other (smlib_blend_setback, solid.fillet `setbacks`); 1.5 is not, so the right answer is a clean refusal",- "outcome": "refused"+ "method": "a setback must reach past where the corner's rounds meet without one, past r = 2 on a corner of faces square to each other (smlib_blend_setback, solid.fillet `setbacks`); 1.5 is not, so the right answer is a refusal naming the least setback, before SMLib runs. A rolling-ball corner takes setbacks too (they replace the ball's corner by SMLib's set-back patch, ladder 07-fillets/013), so the rule holds for both corners",+ "outcome": "refused",+ "refusal": "the setback must be more than the radius (2 mm)"}diff --git a/tests/kernel-cases/fillets/9-fillet-corner-setback-1-5-not-past-r2-rolling/expected.json b/tests/kernel-cases/fillets/9-fillet-corner-setback-1-5-not-past-r2-rolling/expected.jsonindex 766c23180d..2b4d6fc53f 100644--- a/tests/kernel-cases/fillets/9-fillet-corner-setback-1-5-not-past-r2-rolling/expected.json+++ b/tests/kernel-cases/fillets/9-fillet-corner-setback-1-5-not-past-r2-rolling/expected.json@@ -4,6 +4,7 @@],"what": "three r2 rounds at a box corner, rolling-ball corner, set back 1.5: not past where the rounds meet (r): refused","source": "invariants",- "method": "a setback must reach past where the corner's rounds meet without one, past r = 2 on a corner of faces square to each other (smlib_blend_setback, solid.fillet `setbacks`); 1.5 is not, so the right answer is a clean refusal",- "outcome": "refused"+ "method": "a setback must reach past where the corner's rounds meet without one, past r = 2 on a corner of faces square to each other (smlib_blend_setback, solid.fillet `setbacks`); 1.5 is not, so the right answer is a refusal naming the least setback, before SMLib runs. A rolling-ball corner takes setbacks too (they replace the ball's corner by SMLib's set-back patch, ladder 07-fillets/013), so the rule holds for both corners",+ "outcome": "refused",+ "refusal": "the setback must be more than the radius (2 mm)"}diff --git a/tests/kernel-cases/fillets/9-fillet-corner-setback-2-not-past-r2-curvature/expected.json b/tests/kernel-cases/fillets/9-fillet-corner-setback-2-not-past-r2-curvature/expected.jsonindex d66518f420..8fada733f2 100644--- a/tests/kernel-cases/fillets/9-fillet-corner-setback-2-not-past-r2-curvature/expected.json+++ b/tests/kernel-cases/fillets/9-fillet-corner-setback-2-not-past-r2-curvature/expected.json@@ -4,6 +4,7 @@],"what": "three r2 rounds at a box corner, curvature (g2) corner, set back 2: not past where the rounds meet (r): refused","source": "invariants",- "method": "a setback must reach past where the corner's rounds meet without one, past r = 2 on a corner of faces square to each other (smlib_blend_setback, solid.fillet `setbacks`); 2 is not, so the right answer is a clean refusal",- "outcome": "refused"+ "method": "a setback must reach past where the corner's rounds meet without one, past r = 2 on a corner of faces square to each other (smlib_blend_setback, solid.fillet `setbacks`); 2 is not, so the right answer is a refusal naming the least setback, before SMLib runs. A rolling-ball corner takes setbacks too (they replace the ball's corner by SMLib's set-back patch, ladder 07-fillets/013), so the rule holds for both corners",+ "outcome": "refused",+ "refusal": "the setback must be more than the radius (2 mm)"}diff --git a/tests/kernel-cases/fillets/9-fillet-corner-setback-2-not-past-r2-rolling/expected.json b/tests/kernel-cases/fillets/9-fillet-corner-setback-2-not-past-r2-rolling/expected.jsonindex a75996f2ee..37de4f85aa 100644--- a/tests/kernel-cases/fillets/9-fillet-corner-setback-2-not-past-r2-rolling/expected.json+++ b/tests/kernel-cases/fillets/9-fillet-corner-setback-2-not-past-r2-rolling/expected.json@@ -4,6 +4,7 @@],"what": "three r2 rounds at a box corner, rolling-ball corner, set back 2: not past where the rounds meet (r): refused","source": "invariants",- "method": "a setback must reach past where the corner's rounds meet without one, past r = 2 on a corner of faces square to each other (smlib_blend_setback, solid.fillet `setbacks`); 2 is not, so the right answer is a clean refusal",- "outcome": "refused"+ "method": "a setback must reach past where the corner's rounds meet without one, past r = 2 on a corner of faces square to each other (smlib_blend_setback, solid.fillet `setbacks`); 2 is not, so the right answer is a refusal naming the least setback, before SMLib runs. A rolling-ball corner takes setbacks too (they replace the ball's corner by SMLib's set-back patch, ladder 07-fillets/013), so the rule holds for both corners",+ "outcome": "refused",+ "refusal": "the setback must be more than the radius (2 mm)"}