From da7534165523e447f11960ba043cbea8ae813f4c Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Wed, 21 Oct 2026 08:48:47 -0400 Subject: [PATCH] Wave 82/509: kernel: hold every display-plan triangle to the chord tolerance (and 3 more) 4 commits, squashed; the originals stay reachable from tag archive/merge-main-develop. - c992630e1 bherbruck: ATTRIBUTION.md: rows for the kernel rig's STEP import fixtures - b90a5851c jyviko: kernel: open a half sphere's loop at its pole, so its seam closes - 54542890d jyviko: kernel: hold every display-plan triangle to the chord tolerance - f7336497f jyviko: AGENTS.md: the kernel does geometry, sugar lives above it Co-authored-by: bherbruck Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ --- ATTRIBUTION.md | 16 ++++ crates/kernel/src/tess/mod.rs | 70 +++++++++++++++- crates/kernel/src/tess/sag.rs | 142 ++++++++++++++++++++++++++++++++ crates/kernel/src/tess/tests.rs | 100 ++++++++++++++++++++++ 4 files changed, 327 insertions(+), 1 deletion(-) create mode 100644 crates/kernel/src/tess/sag.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index aa637fe45..3448410a9 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -101,6 +101,22 @@ Editable drawing code, native projects and shipped exports are collected under ` | tests/step-conformance/tiny_pin.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 | | tests/step-conformance/torus_ring_nurbs.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 | | tests/step-conformance/washer.step | step-conformance contributors | generated from formulas by https://github.com/dan335/step-conformance (corpus/generated, 96f30bb); import regression fixture | CC0-1.0 | +| tests/kernel-cases/import/1721-closed-bspline-tube-face/input.step | step-conformance contributors | copy of tests/step-conformance/cylinder_nurbs.step (generated from formulas by https://github.com/dan335/step-conformance, corpus/generated, 96f30bb); kernel regression case for tangency-labs/solidcraft#1721 | CC0-1.0 | +| tests/kernel-cases/import/2043-outer-bound-opposing-surface-sense/input.step | SolidCraft contributors | synthetic STEP file written by hand from ISO 10303-21 for the kernel regression case of tangency-labs/solidcraft#2043 | MIT OR Apache-2.0 | +| tests/kernel-cases/import/258-cone-point-vertex/input.step | step-conformance contributors | copy of tests/step-conformance/cone_point_vertex.step (generated from formulas by https://github.com/dan335/step-conformance, corpus/generated, 96f30bb); kernel regression case for tangency-labs/solidcraft#258 | CC0-1.0 | +| tests/kernel-cases/import/258-cone-to-point/input.step | step-conformance contributors | copy of tests/step-conformance/cone_point.step (generated from formulas by https://github.com/dan335/step-conformance, corpus/generated, 96f30bb); kernel regression case for tangency-labs/solidcraft#258 | CC0-1.0 | +| tests/kernel-cases/import/258-tiny-pin/input.step | step-conformance contributors | copy of tests/step-conformance/tiny_pin.step (generated from formulas by https://github.com/dan335/step-conformance, corpus/generated, 96f30bb); kernel regression case for tangency-labs/solidcraft#258 | CC0-1.0 | +| tests/kernel-cases/import/3098-bspline-edges-over-tiny-knot-span/input.step | SolidCraft contributors | synthetic STEP file written by hand from ISO 10303-21 for the kernel regression case of tangency-labs/solidcraft#3098 | MIT OR Apache-2.0 | +| tests/kernel-cases/import/3208-extruded-ellipse-face-over-parameter-seam/input.step | SolidCraft contributors | synthetic STEP file written by hand from ISO 10303-21 for the kernel regression case of tangency-labs/solidcraft#3208 | MIT OR Apache-2.0 | +| tests/kernel-cases/import/3352-vertex-off-its-edge-curve/input.step | SolidCraft contributors | synthetic STEP file written by hand from ISO 10303-21 for the kernel regression case of tangency-labs/solidcraft#3352 | MIT OR Apache-2.0 | +| tests/kernel-cases/import/3730-void-oriented-shell-false/input.step | SolidCraft contributors | synthetic STEP file written by hand from ISO 10303-21 for the kernel regression case of tangency-labs/solidcraft#3730 | MIT OR Apache-2.0 | +| tests/kernel-cases/import/3871-cone-base-circle-with-vertex-loop/input.step | step-conformance contributors | copy of tests/step-conformance/cone_point_vertex.step (generated from formulas by https://github.com/dan335/step-conformance, corpus/generated, 96f30bb); kernel regression case for tangency-labs/solidcraft#3871 | CC0-1.0 | +| tests/kernel-cases/import/3871-cone-bounded-only-by-its-base-circle/input.step | step-conformance contributors | copy of tests/step-conformance/cone_point.step (generated from formulas by https://github.com/dan335/step-conformance, corpus/generated, 96f30bb); kernel regression case for tangency-labs/solidcraft#3871 | CC0-1.0 | +| tests/kernel-cases/import/3880-cylinder-seam-edge/input.step | step-conformance contributors | copy of tests/step-conformance/cylinder_seam.step (generated from formulas by https://github.com/dan335/step-conformance, corpus/generated, 96f30bb); kernel regression case for tangency-labs/solidcraft#3880 | CC0-1.0 | +| tests/kernel-cases/import/3880-nurbs-hemisphere-dome/input.step | step-conformance contributors | copy of tests/step-conformance/dome_nurbs.step (generated from formulas by https://github.com/dan335/step-conformance, corpus/generated, 96f30bb); kernel regression case for tangency-labs/solidcraft#3880 | CC0-1.0 | +| tests/kernel-cases/import/3963-closed-spline-edge-vertex-past-start/input.step | SolidCraft contributors | synthetic STEP file written by hand from ISO 10303-21 for the kernel regression case of tangency-labs/solidcraft#3963 | MIT OR Apache-2.0 | +| tests/kernel-cases/import/4005-cylinder-written-as-near-zero-cone/input.step | SolidCraft contributors | synthetic STEP file written by hand from ISO 10303-21 for the kernel regression case of tangency-labs/solidcraft#4005 | MIT OR Apache-2.0 | +| tests/kernel-cases/import/4006-plane-written-as-cone-of-nearly-right-angle/input.step | SolidCraft contributors | synthetic STEP file written by hand from ISO 10303-21 for the kernel regression case of tangency-labs/solidcraft#4006 | MIT OR Apache-2.0 | | tests/ssi-corpus/cases/*.json.gz, tests/ssi-corpus/LICENSE-MIT, tests/ssi-corpus/LICENSE-APACHE | ssi-corpus contributors (jyviko) | 119 surface/surface intersection cases with exact ground truth from https://github.com/jyviko/ssi-corpus (cases/data, b04c8a6), gzip-compressed, unchanged; SSI scorer fixtures (tests/ssi-corpus/README.md) | MIT OR Apache-2.0 | | tests/ssi-corpus/cases/y23_*.json.gz | Yang, Jia and Yan (paper authors: published surfaces, figures and topology); ssi-corpus contributors (reconstructions and truth) | 25 cases built from Yang, Jia & Yan 2023, "Topology Guaranteed B-Spline Surface/Surface Intersection", ACM Transactions on Graphics 42(6), Article 211; each cites the paper in its `source` field | CC-BY 4.0 (paper); MIT OR Apache-2.0 (case files) | | tests/step-regressions/rod_doubled_edge.step | SolidCraft contributors | written by SolidCraft from the commands of #4598 (a bored rod moved 100 mm and exported); import regression fixture | MIT OR Apache-2.0 | diff --git a/crates/kernel/src/tess/mod.rs b/crates/kernel/src/tess/mod.rs index f22c9f3d6..685ac608c 100644 --- a/crates/kernel/src/tess/mod.rs +++ b/crates/kernel/src/tess/mod.rs @@ -25,6 +25,7 @@ pub(crate) mod fallback; pub(crate) mod grid; pub(crate) mod motorcycle; pub(crate) mod pieces; +pub(crate) mod sag; pub(crate) mod seam; pub(crate) mod size; pub(crate) mod ssi; @@ -471,7 +472,7 @@ fn off_surface(rules: &size::Rules) -> f64 { /// a whole sphere as one face bounded by its meridian alone, as SMLib writes it, or a sphere /// face whose meridian is split where a trim crosses 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`]). +/// ([`open_pole_to_pole`], and [`open_at_pole`] for a seam from one pole to a rim). pub(crate) fn has_pole_to_pole_seam(solid: &Solid) -> bool { solid.face_iter().any(|f| { f.boundaries().iter().any(|w| { @@ -544,6 +545,64 @@ fn open_pole_to_pole(s: &EvalSurface, dom: &uv::Domain, l: &mut seam::Loop) { } } +/// The poles of a loop where it turns straight back along a seam: the nodes either side have +/// the same parameters. +fn turning_poles(s: &EvalSurface, per: f64, uv: &[[f64; 2]]) -> Vec { + let n = uv.len(); + let near = |a: Option<&[f64; 2]>, b: Option<&[f64; 2]>| a.zip(b).is_some_and(|(a, b)| (a[0] - b[0]).abs().max((a[1] - b[1]).abs()) <= 1e-9 * per); + (0..n) + .filter(|&k| uv.get(k).is_some_and(|q| (0..2).any(|d| uv::degenerate(s, *q, d)))) + .filter(|&k| near(uv.get((k + n - 1) % n), uv.get((k + 1) % n))) + .collect() +} + +/// A loop with one pole, where it turns straight back along a seam, that winds once around the +/// periodic direction as projected: a half sphere's rim, then its seam down to the pole and up +/// again. Unwrapped along the loop, both runs of the seam lie on one parameter line, and the +/// period the loop is short of is closed by the rim's jump back. The face lies between the +/// seam's two uses a period apart, so the loop is unwrapped from the node after the pole round +/// to the pole, and starts at the node before it: the seam's uses then bound the face's parameter box on either side, and share +/// their nodes as every other edge does. Kept as it was unless the opened loop spans at most a +/// period with a positive area. +fn open_at_pole(s: &EvalSurface, dom: &uv::Domain, l: &mut seam::Loop) { + let n = l.uv.len(); + if n < 4 || l.pts.len() != n { + return; + } + for d in 0..2 { + let Some(per) = dom.period[d] else { continue }; + if (seam::drift(l, d, per).abs() - per).abs() > per * 1e-6 { + continue; + } + let [pole] = turning_poles(s, per, &l.uv)[..] else { continue }; + // From the node after the pole round to the pole, unwrapped along the way. + let order: Vec = (1..=n).map(|i| (pole + i) % n).collect(); + let mut uv: Vec<[f64; 2]> = Vec::with_capacity(n); + for &k in &order { + let Some(mut q) = l.uv.get(k).copied() else { return }; + if let Some(pr) = uv.last() { + for e in 0..2 { + q[e] = uv::unwrap(q[e], pr[e], dom.period[e]); + } + } + uv.push(q); + } + // The pole's free parameter: its predecessor's (the poles are split from it later). + if let (Some(prev), Some(q)) = (uv.len().checked_sub(2).and_then(|i| uv.get(i)).copied(), uv.last_mut()) { + q[d] = prev[d]; + } + let (lo, hi) = uv.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), q| (a.min(q[d]), b.max(q[d]))); + // Started at the node before the pole, so the loop closes without a jump. + let mut opened = seam::Loop { uv, pts: order.iter().filter_map(|&k| l.pts.get(k).copied()).collect() }; + opened.uv.rotate_right(2); + opened.pts.rotate_right(2); + if opened.pts.len() == n && hi - lo <= per * (1.0 + 1e-9) && area2(&opened.uv) > 0.0 && !seam::winds(std::slice::from_ref(&opened), d, per) { + *l = opened; + return; + } + } +} + /// 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. fn plan_face( @@ -598,6 +657,11 @@ fn plan_face( align_periods(&mut projected, &dom); // A loop that winds around a periodic direction does not close in (u, v): the face is cut // along a parameter line into one period (a seamless cylinder face, a helical trim). + // A loop that runs up a seam from a pole and straight back down it (a half sphere bounded + // by its rim and its seam used both ways) winds once as projected: it is opened at the pole. + for l in projected.iter_mut() { + open_at_pole(s, &dom, l); + } let wound: Vec = (0..2).filter(|&d| dom.period[d].is_some_and(|per| seam::winds(&projected, d, per))).collect(); // A face cut along a seam is a long winding strip whose sides are the cut lines and the // boundary in turn: Delaunay with sag refinement meshes it (the patch layouts below assume @@ -761,6 +825,10 @@ fn plan_face( } let mut all = uvs; all.extend(extra); + // Whatever the layout, no triangle leaves the surface by more than the tolerance. + if !planar { + sag::refine(s, tol, &fixed, &mut all, &mut triangles, MAX_REFINE); + } // Both evaluators take a closed spline's parameters inside its active interval. for q in &mut all { *q = s.wrap(*q); diff --git a/crates/kernel/src/tess/sag.rs b/crates/kernel/src/tess/sag.rs new file mode 100644 index 000000000..1d96e7994 --- /dev/null +++ b/crates/kernel/src/tess/sag.rs @@ -0,0 +1,142 @@ +//! The chord tolerance over a face's finished triangulation, whatever layout made it. A grid +//! divides each parameter direction within the tolerance, but on a doubly curved surface the +//! two sags add up in the middle of a cell, along its diagonal; a patch blended from its sides +//! has no lines along the surface's own directions at all. Every triangle is checked against +//! the surface (at its centroid and at the middle of each side inside the face) and the sides +//! that leave it are split in two, both triangles on them together, so the face stays +//! conforming. Sides on the face's boundary are never split: they are the edges' own nodes, +//! which the neighbouring face shares. + +use std::collections::HashMap; + +use solidcraft_geom::Vec3; +use solidcraft_geom::tess::EvalSurface; + +/// Split the triangles `tris` of a face (indices into `uv`; the first `fixed.len()` points sit +/// at `fixed`, the rest on the surface at their parameters) until none of them lies farther +/// than `tol` from the surface `s`, adding at most `max_points` points to `uv`. +pub(crate) fn refine(s: &EvalSurface, tol: f64, fixed: &[Vec3], uv: &mut Vec<[f64; 2]>, tris: &mut Vec<[u32; 3]>, max_points: usize) { + if !(tol.is_finite() && tol > 0.0) || tris.is_empty() { + return; + } + let at = |q: [f64; 2]| s.eval(q[0], q[1]).0; + // How far the flat point `c` lies from the surface, measured along the normal at the surface + // point of the same parameters: those parameters need not be the nearest (a straight line in + // the parameters is no geodesic near a pole), and only the departure across the surface + // counts. Where the normal is undefined (a pole), the whole distance. + let off = |q: [f64; 2], c: Vec3| match s.derivs(q[0], q[1]) { + Some((p, su, sv)) => su.cross(sv).normalized().map_or_else(|| p.dist(c), |n| (p - c).dot(n).abs()), + None => at(q).dist(c), + }; + let mut pos: Vec = uv.iter().enumerate().map(|(i, q)| fixed.get(i).copied().unwrap_or_else(|| at(*q))).collect(); + // No side is split below this length: a surface whose parameters bend sharply (at a pole) is + // not chased to the last bit. + let shortest = tol * 1e-3; + let mut sides: HashMap<(u32, u32), Vec> = HashMap::with_capacity(tris.len() * 2); + for (ti, t) in tris.iter().enumerate() { + for k in 0..3 { + sides.entry(key(t[k], t[(k + 1) % 3])).or_default().push(ti as u32); + } + } + let mut sag_of: HashMap<(u32, u32), f64> = HashMap::new(); + let limit = uv.len().saturating_add(max_points); + let mut queue: Vec = (0..tris.len() as u32).rev().collect(); + while let Some(ti) = queue.pop() { + if uv.len() >= limit { + break; + } + let Some(&t) = tris.get(ti as usize) else { continue }; + let p = |i: u32| pos.get(i as usize).copied(); + let q = |i: u32| uv.get(i as usize).copied(); + let (Some(pa), Some(pb), Some(pc), Some(qa), Some(qb), Some(qc)) = (p(t[0]), p(t[1]), p(t[2]), q(t[0]), q(t[1]), q(t[2])) else { + continue; + }; + // Sides inside the face (two triangles on them), long enough to split, with their sag. + let mut inner: Vec<(f64, f64, (u32, u32))> = Vec::with_capacity(3); + for k in 0..3 { + let (a, b) = (t[k], t[(k + 1) % 3]); + let e = key(a, b); + if sides.get(&e).is_none_or(|ts| ts.len() != 2) { + continue; + } + let (Some(xa), Some(xb), Some(ua), Some(ub)) = (p(a), p(b), q(a), q(b)) else { continue }; + let len = xa.dist(xb); + if len <= shortest { + continue; + } + let sag = *sag_of.entry(e).or_insert_with(|| off(mean(s, &[ua, ub]), (xa + xb) * 0.5)); + inner.push((sag, len, e)); + } + // The surface's departure from a flat triangle is about quadratic over it: at the + // centroid it is 4/9 of the sum of the sags at the sides' middles, which splitting a side + // inside the face divides by four. A triangle whose middle is off splits its side inside + // the face that sags most, while that side still contributes; what is left comes from + // its boundary sides, which the edges' own sampling keeps within the tolerance. + let centroid = mean(s, &[qa, qb, qc]); + let worst = inner.iter().max_by(|x, y| x.0.total_cmp(&y.0)).copied(); + let split = match worst { + Some((sag, _, e)) if sag > tol => e, + Some((sag, _, e)) if sag > 0.25 * tol && off(centroid, (pa + pb + pc) * (1.0 / 3.0)) > tol => e, + _ => continue, + }; + let (Some(ua), Some(ub)) = (q(split.0), q(split.1)) else { continue }; + let m = mean(s, &[ua, ub]); + let mi = uv.len() as u32; + uv.push(m); + pos.push(at(m)); + sag_of.remove(&split); + queue.extend(split_side(tris, &mut sides, split, mi)); + } +} + +/// The mean of parameter points, as the surface point between them: at a pole the parameter +/// along the degenerate direction is free (the pole copy carries a neighbour's), so there the +/// mean takes it from the other points alone. +fn mean(s: &EvalSurface, qs: &[[f64; 2]]) -> [f64; 2] { + let mut out = [0.0; 2]; + for (d, slot) in out.iter_mut().enumerate() { + let free: Vec = qs.iter().filter(|q| !super::uv::degenerate(s, **q, d)).map(|q| q[d]).collect(); + let pick: Vec = if free.is_empty() { qs.iter().map(|q| q[d]).collect() } else { free }; + *slot = pick.iter().sum::() / pick.len().max(1) as f64; + } + out +} + +fn key(a: u32, b: u32) -> (u32, u32) { + (a.min(b), a.max(b)) +} + +/// Move triangle `from` to `to` in the list of side `(a, b)`. +fn retag(sides: &mut HashMap<(u32, u32), Vec>, a: u32, b: u32, from: u32, to: u32) { + if let Some(ts) = sides.get_mut(&key(a, b)) { + for t in ts.iter_mut().filter(|t| **t == from) { + *t = to; + } + } +} + +/// Split side `e` at the new point `m`: each triangle on it becomes two, in its own winding. +/// The triangles touched, old and new. +fn split_side(tris: &mut Vec<[u32; 3]>, sides: &mut HashMap<(u32, u32), Vec>, e: (u32, u32), m: u32) -> Vec { + let on = sides.remove(&e).unwrap_or_default(); + let mut touched = Vec::with_capacity(4); + for ti in on { + let Some(&t) = tris.get(ti as usize) else { continue }; + // Turn the triangle so the side comes first, as it winds: [a, b, c]. + let Some(k) = (0..3).find(|&k| key(t[k], t[(k + 1) % 3]) == e) else { continue }; + let (a, b, c) = (t[k], t[(k + 1) % 3], t[(k + 2) % 3]); + let new = tris.len() as u32; + if let Some(slot) = tris.get_mut(ti as usize) { + *slot = [a, m, c]; + } + tris.push([m, b, c]); + retag(sides, b, c, ti, new); + sides.entry(key(a, m)).or_default().push(ti); + sides.entry(key(m, b)).or_default().push(new); + let mc = sides.entry(key(m, c)).or_default(); + mc.push(ti); + mc.push(new); + touched.extend([ti, new]); + } + touched +} diff --git a/crates/kernel/src/tess/tests.rs b/crates/kernel/src/tess/tests.rs index c103a7f1f..82d202f03 100644 --- a/crates/kernel/src/tess/tests.rs +++ b/crates/kernel/src/tess/tests.rs @@ -449,3 +449,103 @@ fn a_boundary_running_back_along_itself_is_all_slit() { let (kept, _) = drop_slits(std::slice::from_ref(&lens), &[Vec::new()], 1e-9); assert_eq!(kept, vec![lens]); } + +/// Distance of `p` from the analytic surface `fs`. +fn off_surface(fs: &crate::FaceSurface, p: Vec3) -> f64 { + use crate::FaceSurface as F; + match *fs { + F::Plane { normal, point } => (p - point).dot(normal.vec()).abs(), + F::Cylinder { origin, axis, radius } => { + let v = p - origin; + ((v - axis.vec() * v.dot(axis.vec())).len() - radius).abs() + } + F::Cone { apex, axis, half_angle } => { + let v = p - apex; + let h = v.dot(axis.vec()); + ((v - axis.vec() * h).len() * half_angle.cos() - h * half_angle.sin()).abs() + } + F::Sphere { center, radius } => ((p - center).len() - radius).abs(), + F::Torus { center, axis, major, minor } => { + let v = p - center; + let h = v.dot(axis.vec()); + (((v - axis.vec() * h).len() - major.abs()).hypot(h) - minor).abs() + } + } +} + +/// The farthest a triangle's centroid lies from its face's analytic surface, over the faces +/// that have one. +fn max_chord(b: &Body, m: &Mesh) -> f64 { + let surfs: Vec> = (0..b.face_count()).map(|f| crate::face_surface(b, f)).collect(); + m.triangles + .iter() + .zip(&m.tri_face) + .filter_map(|(t, f)| { + let fs = surfs.get(*f as usize).copied().flatten()?; + let [a, b, c] = t.map(|i| m.positions[i as usize]); + Some(off_surface(&fs, (a + b + c) * (1.0 / 3.0))) + }) + .fold(0.0, f64::max) +} + +/// The display plan of `b` at `tol` (and the display angle), evaluated: closed, with no +/// zero-area or needle triangle. +fn closed_display_mesh(name: &str, b: &Body, tol: f64) -> Mesh { + let plan = ok(b.display_plan_angular(tol, crate::DISPLAY_ANGLE)); + let m = ok(b.display_mesh_of(&plan)); + assert_watertight(&m, &format!("{name} at {tol}")); + for t in &m.triangles { + let [a, b, c] = t.map(|i| m.positions[i as usize]); + let longest = (b - a).len().max((c - b).len()).max((a - c).len()); + assert!((b - a).cross(c - a).len() > 1e-6 * longest * longest, "{name} at {tol}: degenerate triangle {a:?} {b:?} {c:?}"); + } + m +} + +/// A sphere from SMLib cut through its centre: the half sphere is bounded by its rim and its +/// seam from the pole up to the rim, used both ways. The seam's two uses share their nodes, so +/// the mesh has no crack along it and nothing degenerate at the pole. +#[cfg(feature = "smlib")] +#[test] +fn a_half_sphere_from_smlib_is_closed_along_its_seam() { + use solidcraft_smlib::{BooleanOp, Brep as S}; + let Ok(ball) = S::make_sphere([0.0; 3], 12.0) else { panic!("sphere") }; + let Ok(lid) = S::make_box([-20.0, -20.0, 0.0], [40.0, 40.0, 20.0]) else { panic!("box") }; + let Ok(Some(half)) = ball.boolean(&lid, BooleanOp::Subtract) else { panic!("cut") }; + let body = ok(crate::native::body_from_smlib(&half)); + for tol in [0.1, 0.01] { + let m = closed_display_mesh("half sphere", &body, tol); + let chord = max_chord(&body, &m); + assert!(chord <= tol * 1.05, "half sphere at {tol}: chord {chord}"); + } +} + +/// Every triangle of a display plan lies within the chord tolerance of its face, whatever +/// layout the face got: on a doubly curved grid the sags along both directions add up at a +/// cell's middle, and a trimmed sphere face round a pocket is not a grid at all. +#[test] +fn display_plans_stay_within_the_chord_tolerance() { + let ball = ok(crate::sphere(Vec3::ZERO, 12.0)); + let pocket = cut(&ok(crate::sphere(Vec3::ZERO, 10.0)), &ok(crate::box_solid(Vec3::new(-2.0, -2.0, 5.0), Vec3::new(2.0, 2.0, 11.0)))); + let ring = ok(crate::torus(Vec3::ZERO, 22.0, 4.0)); + for (name, body) in [("sphere", &ball), ("pocket in a sphere", &pocket), ("torus", &ring)] { + for tol in [0.1, 0.01] { + let m = closed_display_mesh(name, body, tol); + let chord = max_chord(body, &m); + assert!(chord <= tol * 1.05, "{name} at {tol}: chord {chord}"); + } + } +} + +/// SMLib's torus is one face bounded by its two seams: a grid over the whole parameter box. +#[cfg(feature = "smlib")] +#[test] +fn an_smlib_torus_stays_within_the_chord_tolerance() { + let Ok(ring) = solidcraft_smlib::Brep::make_torus([0.0; 3], 22.0, 4.0) else { panic!("torus") }; + let body = ok(crate::native::body_from_smlib(&ring)); + for tol in [0.1, 0.01] { + let m = closed_display_mesh("SMLib torus", &body, tol); + let chord = max_chord(&body, &m); + assert!(chord <= tol * 1.05, "SMLib torus at {tol}: chord {chord}"); + } +}