From 7919eaf44cb5cc271eac37d188175f8de116811a Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Thu, 29 Oct 2026 01:02:38 -0400 Subject: [PATCH] Wave 332/509: Tessellation: a face's sides are flipped where the triangles lie closer along the surface the other way (and 3 more) 4 commits, squashed; the originals stay reachable from tag archive/merge-main-develop. - 666ccd85d jyviko: Tessellation: sag refinement splits a flat triangle's long side and never across an obtuse one's short side - 2b22b2cbe jyviko: Tessellation: a face's sides are flipped where the triangles lie closer along the surface the other way - e0d5ee496 jyviko: Tests: thicken and raised-band histories checked as SMLib reports them, Meet edges and seams included - 39e1dcea0 jyviko: Faceted boolean: a body's own mesh is closed once its faces' shared corners are one vertex Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ --- crates/kernel/src/polybool.rs | 22 ++++ crates/kernel/src/record_tests.rs | 15 ++- crates/kernel/src/tess/mod.rs | 1 + crates/kernel/src/tess/sag.rs | 180 ++++++++++++++++++++++++++++++ crates/kernel/src/tess/tests.rs | 93 +++++++++++++++ 5 files changed, 307 insertions(+), 4 deletions(-) diff --git a/crates/kernel/src/polybool.rs b/crates/kernel/src/polybool.rs index a722c1882..59deb9279 100644 --- a/crates/kernel/src/polybool.rs +++ b/crates/kernel/src/polybool.rs @@ -39,6 +39,8 @@ fn faceted_boolean_untimed(a: &Body, b: &Mesh, op: BoolOp, tol: f64) -> Result MAX_TRIANGLES { return Err(failed(&format!("the mesh is too detailed ({} triangles, at most {MAX_TRIANGLES})", b.triangles.len()))); } + let welded = welded(b); + let b = &welded; let groups = coplanar_groups(b, tol)?; let mut faces = Vec::new(); let mut face_group = Vec::new(); @@ -60,6 +62,26 @@ fn faceted_boolean_untimed(a: &Body, b: &Mesh, op: BoolOp, tol: f64) -> Result Mesh { + let mut at: BTreeMap<[u64; 3], u32> = BTreeMap::new(); + let mut positions = Vec::with_capacity(m.positions.len()); + let index: Vec = m + .positions + .iter() + .map(|p| { + *at.entry([p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]).or_insert_with(|| { + positions.push(*p); + (positions.len() - 1) as u32 + }) + }) + .collect(); + let triangles = m.triangles.iter().map(|t| t.map(|i| index.get(i as usize).copied().unwrap_or(i))).collect(); + Mesh { positions, triangles, ..Mesh::default() } +} + /// The mesh's triangles in runs that make one planar face each: triangles sharing an edge, on /// one plane within `tol`, are one run. fn coplanar_groups(m: &Mesh, tol: f64) -> Result>> { diff --git a/crates/kernel/src/record_tests.rs b/crates/kernel/src/record_tests.rs index 3590a7dca..31075a9a8 100644 --- a/crates/kernel/src/record_tests.rs +++ b/crates/kernel/src/record_tests.rs @@ -468,7 +468,8 @@ fn sweeps_along_paths() { check_sweep(&b, &side, &ring, Some(1)); } -/// Kept faces are their origins, unchanged; each edge an operand still owns is that edge. +/// Kept faces are their origins, unchanged; each edge an operand still owns is that edge (a new +/// edge, where two faces meet, has a Meet origin instead). fn check_kept(result: &Body, input: &Body) { let h = result.history().unwrap(); h.check(result, &[input]).unwrap(); @@ -482,7 +483,11 @@ fn check_kept(result: &Body, input: &Body) { let mut owned = 0; for (e, p) in re.iter().zip(&h.edges) { for o in &p.origins { - let crate::history::EdgeOrigin::Edge { operand: 0, edge } = o else { panic!("{o:?}") }; + let edge = match o { + crate::history::EdgeOrigin::Edge { operand: 0, edge } => edge, + crate::history::EdgeOrigin::Meet { .. } => continue, + _ => panic!("{o:?}"), + }; assert!(e.mid.dist(ie[*edge].mid) < 1e-6, "edge {}", e.index); owned += 1; } @@ -506,12 +511,14 @@ fn thicken_reports_copies_offsets_and_walls() { let h = t.history().unwrap(); assert_eq!(h.faces[0].origins, [FaceOrigin::Face { operand: 0, face: 0 }]); assert_eq!(h.faces[1].origins, [FaceOrigin::Offset { operand: 0, face: 0 }]); - let free: Vec = (0..half.edge_count()).collect(); + // A wall along each free edge of the sheet: the side's two rims, not its seam (an edge the + // one face meets itself along, no boundary). + let free: Vec = (0..half.edge_count()).filter(|e| half.record().edges[*e].uses.len() == 1).collect(); for (i, f) in h.faces.iter().enumerate().skip(2) { let [FaceOrigin::Edge { operand: 0, edge }] = f.origins.as_slice() else { panic!("{f:?}") }; assert_eq!(*edge, nearest_edge(&t, i, &half, &free)); } - assert_eq!(h.faces.len(), 2 + half.edge_count()); + assert_eq!(h.faces.len(), 2 + free.len()); } #[test] diff --git a/crates/kernel/src/tess/mod.rs b/crates/kernel/src/tess/mod.rs index 3695369c0..204a8b298 100644 --- a/crates/kernel/src/tess/mod.rs +++ b/crates/kernel/src/tess/mod.rs @@ -924,6 +924,7 @@ fn plan_face( // Whatever the layout, no triangle leaves the surface by more than the tolerance. if !planar { sag::refine(s, tol, reach, &fixed, &mut all, &mut triangles, MAX_REFINE); + sag::flip(s, tol, reach, &fixed, &all, &mut triangles); } // Both evaluators take a closed spline's parameters inside its active interval. for q in &mut all { diff --git a/crates/kernel/src/tess/sag.rs b/crates/kernel/src/tess/sag.rs index 02ebb35ef..4082c4aed 100644 --- a/crates/kernel/src/tess/sag.rs +++ b/crates/kernel/src/tess/sag.rs @@ -82,6 +82,25 @@ pub(crate) fn refine(s: &EvalSurface, tol: f64, reach: f64, fixed: &[Vec3], uv: Some((sag, _, e)) if sag > 0.25 * tol && off(centroid, (pa + pb + pc) * (1.0 / 3.0)) > tol => e, _ => continue, }; + // Splitting a triangle's shorter side leaves a child with its long side and a wider + // angle, and where the long side's middle lies on the surface (a section with an + // inflection) the children flatten toward it without end. So a triangle flattened onto its + // longest side (its widest angle past 150 degrees) splits that side, and a split never + // goes across an obtuse triangle's shorter side: that triangle's longest side is split + // first, and so on along the path (Rivara's longest-edge propagation, its lengths growing, + // so it ends). Only sides inside the face are split. + let mut split = flat_long_side(&t, &pos, &sides, shortest, 150.0).unwrap_or(split); + let mut from = ti; + while let Some(&across) = sides.get(&split).and_then(|ts| ts.iter().find(|&&o| o != from)) { + match tris.get(across as usize).and_then(|o| flat_long_side(o, &pos, &sides, shortest, 90.0)) { + Some(long) if long != split => (split, from) = (long, across), + _ => break, + } + } + // The triangle is looked at again when the split was another's, on its way. + if from != ti { + queue.push(ti); + } let (Some(ua), Some(ub)) = (q(split.0), q(split.1)) else { continue }; let m = mean(&[ua, ub]); let mi = uv.len() as u32; @@ -105,6 +124,20 @@ fn mean(s: &EvalSurface, dom: &super::uv::Domain, reach: f64, qs: &[[f64; 2]]) - out } +/// The longest side of triangle `t` when the angle opposite it is past `degrees` and the side lies +/// inside the face (two triangles on it) and is long enough to split. +fn flat_long_side(t: &[u32; 3], pos: &[Vec3], sides: &HashMap<(u32, u32), Vec>, shortest: f64, degrees: f64) -> Option<(u32, u32)> { + let p = |i: u32| pos.get(i as usize).copied(); + let len = |k: usize| p(t[k]).zip(p(t[(k + 1) % 3])).map(|(a, b)| a.dist(b)); + let lengths = [len(0)?, len(1)?, len(2)?]; + let k = (0..3).max_by(|&i, &j| lengths[i].total_cmp(&lengths[j]))?; + let (l, a, b) = (lengths[k], lengths[(k + 1) % 3], lengths[(k + 2) % 3]); + let side = key(t[k], t[(k + 1) % 3]); + let inside = sides.get(&side).is_some_and(|ts| ts.len() == 2) && l > shortest; + let flat = a > 0.0 && b > 0.0 && (a * a + b * b - l * l) / (2.0 * a * b) < degrees.to_radians().cos(); + (inside && flat).then_some(side) +} + fn key(a: u32, b: u32) -> (u32, u32) { (a.min(b), a.max(b)) } @@ -143,3 +176,150 @@ fn split_side(tris: &mut Vec<[u32; 3]>, sides: &mut HashMap<(u32, u32), Vec } touched } + +/// The sharpest corner (radians) a flip may make. +const MIN_FLIP_ANGLE: f64 = 1e-3; + +/// Flip the sides inside a face's triangulation (as [`refine`] takes it) where the two triangles +/// on a side lie closer along the surface the other way: their facets turn less from the surface +/// normal. A layout can leave +/// slivers standing on their long side across the surface (their corners on it, their plane across +/// it), which count several times the area under them and which no split repairs; the flip lays +/// them down. A side is flipped only when both new triangles keep the orientation of the old ones +/// in (u, v) and against the surface normal (nothing folds), and the new side and the new +/// triangles' middles stay within `tol` of the surface, or no farther than the old side's middle. +/// Sides with one triangle (the face's boundary) are never flipped. +pub(crate) fn flip(s: &EvalSurface, tol: f64, reach: f64, fixed: &[Vec3], uv: &[[f64; 2]], tris: &mut [[u32; 3]]) { + if !(tol.is_finite() && tol > 0.0) || tris.len() < 2 { + return; + } + let dom = super::uv::domain(s); + let mean = |qs: &[[f64; 2]]| mean(s, &dom, reach, qs); + let pos: Vec = uv.iter().enumerate().map(|(i, q)| fixed.get(i).copied().unwrap_or_else(|| s.eval(q[0], q[1]).0)).collect(); + let p = |i: u32| pos.get(i as usize).copied(); + let q = |i: u32| uv.get(i as usize).copied(); + let off = |m: [f64; 2], c: Vec3| match s.derivs(m[0], m[1]) { + Some((x, su, sv)) => su.cross(sv).normalized().map_or_else(|| x.dist(c), |n| (x - c).dot(n).abs()), + None => s.eval(m[0], m[1]).0.dist(c), + }; + // Twice the signed area in (u, v). + let area_uv = |t: [u32; 3]| match (q(t[0]), q(t[1]), q(t[2])) { + (Some(a), Some(b), Some(c)) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]), + _ => 0.0, + }; + // The triangle's smallest angle in 3D. + let min_angle = |t: [u32; 3]| -> f64 { + let (Some(a), Some(b), Some(c)) = (p(t[0]), p(t[1]), p(t[2])) else { return 0.0 }; + let angle = |o: Vec3, x: Vec3, y: Vec3| match ((x - o).normalized(), (y - o).normalized()) { + (Some(u), Some(v)) => u.dot(v).clamp(-1.0, 1.0).acos(), + _ => 0.0, + }; + angle(a, b, c).min(angle(b, c, a)).min(angle(c, a, b)) + }; + // How far a facet's normal turns from the surface normal at its middle (radians, 0 to pi/2). + let deviation = |t: [u32; 3]| -> f64 { + let (Some(a), Some(b), Some(c), 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 { return 0.0 }; + let m = mean(&[qa, qb, qc]); + let facet = (b - a).cross(c - a).normalized(); + match (facet, s.derivs(m[0], m[1]).and_then(|(_, su, sv)| su.cross(sv).normalized())) { + (Some(f), Some(n)) => f.dot(n).abs().clamp(0.0, 1.0).acos(), + _ => 0.0, + } + }; + // Whether the facet's normal lies on the side of the surface normal that its (u, v) + // orientation `sign` says. + let upright = |t: [u32; 3], sign: f64| -> bool { + let (Some(a), Some(b), Some(c), 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 { return false }; + let m = mean(&[qa, qb, qc]); + match s.derivs(m[0], m[1]) { + Some((_, su, sv)) => (b - a).cross(c - a).dot(su.cross(sv)) * sign > 0.0, + None => true, + } + }; + let centroid_off = |t: [u32; 3]| match (p(t[0]), p(t[1]), p(t[2]), q(t[0]), q(t[1]), q(t[2])) { + (Some(a), Some(b), Some(c), Some(qa), Some(qb), Some(qc)) => off(mean(&[qa, qb, qc]), (a + b + c) * (1.0 / 3.0)), + _ => f64::INFINITY, + }; + 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 queue: Vec<(u32, u32)> = sides.iter().filter(|(_, ts)| ts.len() == 2).map(|(e, _)| *e).collect(); + queue.sort_unstable(); + let mut budget = tris.len().saturating_mul(8); + // Each triangle's deviation, until it is flipped. + let mut dev_of: Vec> = vec![None; tris.len()]; + while let Some(e) = queue.pop() { + if budget == 0 { + break; + } + let Some(&[t1, t2]) = sides.get(&e).map(|v| v.as_slice()) else { continue }; + let (Some(&ta), Some(&tb)) = (tris.get(t1 as usize), tris.get(t2 as usize)) else { continue }; + // [a, b, c] on one side of a -> b, [b, a, d] on the other. + let Some(k) = (0..3).find(|&k| key(ta[k], ta[(k + 1) % 3]) == e) else { continue }; + let (a, b, c) = (ta[k], ta[(k + 1) % 3], ta[(k + 2) % 3]); + let Some(d) = tb.iter().copied().find(|&v| v != a && v != b) else { continue }; + if c == d || sides.contains_key(&key(c, d)) { + continue; + } + let (n1, n2) = ([a, d, c], [d, b, c]); + let sign = area_uv(ta).signum(); + if sign == 0.0 || area_uv(tb).signum() != sign || area_uv(n1) * sign <= 0.0 || area_uv(n2) * sign <= 0.0 { + continue; + } + // The pair the other way must lie closer along the surface (its facets turn less from + // the surface normal), by more than a degree: a pair within a degree of the surface is + // left as the layout made it. + let mut cached = |ti: u32, t: [u32; 3]| match dev_of.get(ti as usize).copied().flatten() { + Some(d) => d, + None => { + let d = deviation(t); + if let Some(slot) = dev_of.get_mut(ti as usize) { + *slot = Some(d); + } + d + } + }; + let worse = cached(t1, ta).max(cached(t2, tb)); + let degree = 1f64.to_radians(); + if worse < degree || deviation(n1).max(deviation(n2)) >= worse - degree { + continue; + } + // ... and have area in 3D (three corners on one line of a cone have none, however they + // lie in (u, v)). + if min_angle(n1).min(min_angle(n2)) < MIN_FLIP_ANGLE { + continue; + } + if !(upright(n1, sign) && upright(n2, sign)) { + continue; + } + let (Some(pa), Some(pb), Some(pc), Some(pd), Some(qa), Some(qb), Some(qc), Some(qd)) = (p(a), p(b), p(c), p(d), q(a), q(b), q(c), q(d)) + else { + continue; + }; + let allowed = tol.max(off(mean(&[qa, qb]), (pa + pb) * 0.5)).max(centroid_off(ta)).max(centroid_off(tb)); + if off(mean(&[qc, qd]), (pc + pd) * 0.5) > allowed || centroid_off(n1) > allowed || centroid_off(n2) > allowed { + continue; + } + budget -= 1; + for ti in [t1, t2] { + if let Some(slot) = dev_of.get_mut(ti as usize) { + *slot = None; + } + } + if let Some(slot) = tris.get_mut(t1 as usize) { + *slot = n1; + } + if let Some(slot) = tris.get_mut(t2 as usize) { + *slot = n2; + } + sides.remove(&e); + sides.insert(key(c, d), vec![t1, t2]); + // a-d moves from t2 to t1, b-c from t1 to t2. + retag(&mut sides, a, d, t2, t1); + retag(&mut sides, b, c, t1, t2); + queue.extend([key(a, d), key(d, b), key(b, c), key(c, a)].into_iter().filter(|s| sides.get(s).is_some_and(|ts| ts.len() == 2))); + } +} diff --git a/crates/kernel/src/tess/tests.rs b/crates/kernel/src/tess/tests.rs index 9d60e2bcf..a98fe87e0 100644 --- a/crates/kernel/src/tess/tests.rs +++ b/crates/kernel/src/tess/tests.rs @@ -908,3 +908,96 @@ fn a_small_sphere_void_in_a_large_block_meshes() { assert_watertight(&m, "block with a sphere void"); assert_eq!(hollow.unmeshed_faces(), 0); } + +/// A sheet whose section is an S (a cubic 30 long, 1.5 off its chord each way, its middle on the +/// chord), straight across, meshed as fans with one triangle flat on the chord across its middle +/// (A, B at the sides, C a hair above the chord a third along). The chord's middle lies on the +/// surface while the triangle's short sides sag: splitting those left a child with the chord and +/// its vertex nearer to it, without end (a loft side of a bike frame refined to slivers until the +/// point budget ran out, its area counted three times). The flat triangle now splits the chord, +/// and refinement ends within its budget with no sliver. +#[test] +fn sag_refinement_across_an_inflection_ends_without_slivers() { + let mut ctrl = Vec::new(); + for j in 0..2 { + for (i, z) in [0.0, 4.0, -4.0, 0.0].into_iter().enumerate() { + ctrl.push([10.0 * i as f64, 10.0 * f64::from(j), z, 1.0]); + } + } + let s = EvalSurface::Nurbs { + degree: [3, 1], + knots: [vec![0., 0., 0., 0., 1., 1., 1., 1.], vec![0., 0., 1., 1.]], + count: [4, 2], + ctrl, + closed: [false, false], + }; + // Boundary: bottom and top rows of n + 1 nodes (their sides within the tolerance, 0.5), A and + // B halfway up the ends. Inside: C. Bottom fan from A, the triangle A B C, top fan from C. + let n = 6u32; + let mut uv: Vec<[f64; 2]> = Vec::new(); + for i in 0..=n { + uv.push([f64::from(i) / f64::from(n), 0.0]); + } + for i in 0..=n { + uv.push([f64::from(i) / f64::from(n), 1.0]); + } + let (bottom, top) = (0u32, n + 1); + let (a, b, c) = (2 * n + 2, 2 * n + 3, 2 * n + 4); + uv.extend([[0.0, 0.5], [1.0, 0.5], [1.0 / 3.0, 0.5 + 1e-3]]); + let mut tris: Vec<[u32; 3]> = vec![[a, bottom, bottom + 1]]; + tris.extend((1..n).map(|i| [a, bottom + i, bottom + i + 1])); + tris.push([a, bottom + n, b]); + tris.push([a, b, c]); + tris.push([c, b, top + n]); + tris.extend((0..n).rev().map(|i| [c, top + i + 1, top + i])); + tris.push([c, top, a]); + // The sides along the ends are straight. + let fixed: Vec = Vec::new(); + let tol = 0.5; + let start = uv.len(); + super::sag::refine(&s, tol, 1e-9, &fixed, &mut uv, &mut tris, 20_000); + assert!(uv.len() - start < 1_000, "{} points added: refinement ran to its budget", uv.len() - start); + for t in &tris { + let [p, q, r] = t.map(|i| uv[i as usize]); + let area = (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]); + let longest = [(p, q), (q, r), (r, p)].iter().map(|(x, y)| (x[0] - y[0]).hypot(x[1] - y[1])).fold(0.0, f64::max); + assert!(area > 1e-6 * longest * longest, "a sliver {t:?}: {p:?} {q:?} {r:?}"); + } +} + +/// A sheet curved across (a parabola 20 wide, 3.2 high at a tenth in from either side) and two +/// triangles standing on a chord across the curve: their corners on the surface, their planes +/// across it, so they count far more than the area under them. The flip lays them along the +/// sheet, on the straight side along it. +#[test] +fn triangles_standing_across_a_curved_sheet_are_flipped_along_it() { + let mut ctrl = Vec::new(); + for j in 0..2 { + for (i, z) in [5.0, -5.0, 5.0].into_iter().enumerate() { + ctrl.push([10.0 * i as f64 - 10.0, 10.0 * f64::from(j), z, 1.0]); + } + } + let s = EvalSurface::Nurbs { + degree: [2, 1], + knots: [vec![0., 0., 0., 1., 1., 1.], vec![0., 0., 1., 1.]], + count: [3, 2], + ctrl, + closed: [false, false], + }; + let uv = vec![[0.1, 0.5], [0.9, 0.5], [0.5, 0.52], [0.5, 0.48]]; + let mut tris = vec![[0, 1, 2], [1, 0, 3]]; + let area = |tris: &[[u32; 3]]| -> f64 { + tris.iter() + .map(|t| { + let [a, b, c] = t.map(|i| s.eval(uv[i as usize][0], uv[i as usize][1]).0); + (b - a).cross(c - a).len() / 2.0 + }) + .sum() + }; + let before = area(&tris); + super::sag::flip(&s, 0.1, 1e-9, &[], &uv, &mut tris); + let after = area(&tris); + let sides: Vec<(u32, u32)> = tris.iter().flat_map(|t| (0..3).map(move |k| (t[k].min(t[(k + 1) % 3]), t[k].max(t[(k + 1) % 3])))).collect(); + assert!(sides.contains(&(2, 3)) && !sides.contains(&(0, 1)), "{tris:?}"); + assert!(after < 0.5 * before, "{before} -> {after}"); +}