diff --git a/crates/kernel/src/thin_face_tests.rs b/crates/kernel/src/thin_face_tests.rs index 105df4152..faef716b9 100644 --- a/crates/kernel/src/thin_face_tests.rs +++ b/crates/kernel/src/thin_face_tests.rs @@ -1,11 +1,17 @@ //! A face thinner than the tolerance still meshes: the lens of a sphere's patch that pokes out //! of a box's side has two edges that, sampled coarsely, run along one line in its parameters. //! The shell's mesh had a hole there. +//! +//! So does a face pinched to a point, where its boundary touches itself within the tolerance (a +//! sphere touching a box's edge leaves one on the box, #1648). use std::collections::HashMap; use solidcraft_geom::Vec3; +use truck_meshalgo::prelude::*; +use truck_modeling as mt; +use crate::body::p3; use crate::{BoolOp, build::box_solid, build::sphere, ops::boolean}; /// Triangle sides in the mesh with no triangle on the other side of them, with the points @@ -41,3 +47,56 @@ fn a_lens_thinner_than_the_tolerance_is_meshed() { assert_eq!(open_sides(&mesh), 0, "open sides at {tol}"); } } + +/// Twice the signed area of a closed polyline in the XY plane. +fn area2(points: &[mt::Point3]) -> f64 { + points.iter().zip(points.iter().cycle().skip(1)).map(|(p, q)| p.x * q.y - q.x * p.y).sum() +} + +/// A face in the XY plane between y = 0 and an arch from (5, h) to (0, h) whose middle dips +/// 2.8e-7 below y = 0, as the intersection curve does in the union of #1648. Its loop starts +/// along the bottom, so the bottom goes into the triangulation before the arch. +#[test] +fn a_face_touching_its_own_edge_meshes() { + let (h, dip) = (0.3175, 2.8e-7); + let v = |x: f64, y: f64| mt::builder::vertex(p3(Vec3::new(x, y, 0.0))); + let (lb, rb, rt, lt) = (v(0.0, 0.0), v(5.0, 0.0), v(5.0, h), v(0.0, h)); + let control = vec![p3(Vec3::new(5.0, h, 0.0)), p3(Vec3::new(2.5, -h - 2.0 * dip, 0.0)), p3(Vec3::new(0.0, h, 0.0))]; + let arch = mt::BSplineCurve::new(mt::KnotVec::bezier_knot(2), control); + let arch = mt::Edge::new(&rt, <, mt::Curve::BSplineCurve(arch)); + let wire: mt::Wire = vec![mt::builder::line(&lb, &rb), mt::builder::line(&rb, &rt), arch, mt::builder::line(<, &lb)].into(); + let plane = mt::Plane::new(p3(Vec3::ZERO), p3(Vec3::X), p3(Vec3::Y)); + let face = mt::Face::new(vec![wire], mt::Surface::Plane(plane)); + let shell: mt::Shell = vec![face].into(); + for tol in [0.3, 0.08, 0.02, 0.005] { + let meshed = shell.robust_triangulation_within(Deflection { rulings: true, ..Deflection::chord(tol) }); + let face = meshed.face_iter().next().unwrap(); + let boundary: Vec = face.boundaries()[0].edge_iter().flat_map(|e| e.oriented_curve().0.into_iter().skip(1)).collect(); + let mesh = face.surface().unwrap(); + let area: f64 = mesh + .faces() + .triangle_iter() + .map(|t| { + let [a, b, c] = [0, 1, 2].map(|i| mesh.positions()[t[i].pos]); + (b - a).cross(c - a).magnitude() / 2.0 + }) + .sum(); + // The triangles cover the face's boundary polygon, the parts on both sides of the pinch. + let polygon = area2(&boundary).abs() / 2.0; + assert!((area - polygon).abs() < 1e-5, "at {tol}: triangles cover {area}, the boundary {polygon}"); + } +} + +/// The union of #1648: the sphere touches the box's bottom edge at (2.5, 7.5, 17.5). +#[test] +fn sphere_touching_a_box_edge_unites_soundly() { + let a = sphere(Vec3::new(2.5, 15.0, 27.5), 12.5).unwrap(); + let b = box_solid(Vec3::new(0.0, 0.0, 17.5), Vec3::new(5.0, 7.5, 22.5)).unwrap(); + let union = boolean(&a, &b, BoolOp::Union).unwrap().unwrap(); + assert!(union.validity().is_empty(), "{:?}", union.validity()); + let size = union.size(); + for tol in [size * 1e-2, size * 2.5e-3, size * 6e-4] { + let faces: std::collections::HashSet = union.tessellate(tol).unwrap().tri_face.into_iter().collect(); + assert_eq!(faces.len(), union.face_count(), "at {tol}"); + } +} diff --git a/crates/kernel/tests/boolean_props.rs b/crates/kernel/tests/boolean_props.rs index 7fb11c31a..d6d67474a 100644 --- a/crates/kernel/tests/boolean_props.rs +++ b/crates/kernel/tests/boolean_props.rs @@ -312,9 +312,9 @@ fn generic_box_cylinder_intersect() { check(identity(&a, &b)); } -/// A sphere and a box on the grid: the union has a face that does not mesh. +/// A sphere and a box on the grid: the sphere touches the box's bottom edge, so the union has a +/// face pinched to a point there, which did not mesh (#1648). #[test] -#[ignore = "kernel bug, #1648"] fn grid_sphere_box_union_is_sound() { let a = Prim::Sph { at: [2.5, 15.0, 27.5], r: 12.5 }; let b = Prim::Box { at: [0.0, 0.0, 17.5], size: [5.0, 7.5, 5.0] }; diff --git a/tests/robustness/goldens.json b/tests/robustness/goldens.json index ac24656ea..c6c7c32e8 100644 --- a/tests/robustness/goldens.json +++ b/tests/robustness/goldens.json @@ -21,7 +21,7 @@ "17": {"area":6022.921702,"bodies":1,"edges":48,"error":null,"faces":19,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut box","shell","cut cylinder"],"unsupported":0,"volume":2981.269959}, "18": {"area":5969.14407,"bodies":1,"edges":131,"error":null,"faces":53,"outcome":"ok","rejected":0,"shells":4,"steps":["extruded profile","join cylinder","circular pattern","cut cylinder","hole","cut cylinder","hole","circular pattern"],"unsupported":0,"volume":20696.295391}, "19": {"area":3440.869757,"bodies":1,"edges":42,"error":null,"faces":16,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","chamfer","cut sphere"],"unsupported":0,"volume":5909.174021}, - "20": {"area":5726.92956,"bodies":1,"edges":116,"error":null,"faces":45,"outcome":"ok","rejected":1,"shells":1,"steps":["extruded profile","fillet","cut box","cut cylinder","hole","circular pattern","cut box"],"unsupported":0,"volume":17142.747554}, + "20": {"area":5727.102692,"bodies":1,"edges":116,"error":null,"faces":45,"outcome":"ok","rejected":1,"shells":1,"steps":["extruded profile","fillet","cut box","cut cylinder","hole","circular pattern","cut box"],"unsupported":0,"volume":17142.747554}, "21": {"area":5814.791707,"bodies":1,"edges":56,"error":null,"faces":22,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","join box","hole","fillet","hole","cut box"],"unsupported":1,"volume":19153.734422}, "22": {"area":4634.445571,"bodies":1,"edges":138,"error":null,"faces":54,"outcome":"ok","rejected":0,"shells":2,"steps":["revolved section","join box","join box","join box","rectangular pattern","cut cylinder"],"unsupported":0,"volume":7855.557174}, "23": {"area":1795.696192,"bodies":1,"edges":16,"error":null,"faces":7,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut sphere"],"unsupported":0,"volume":3198.694598}, @@ -56,7 +56,7 @@ "52": {"area":8628.608654,"bodies":1,"edges":45,"error":null,"faces":18,"outcome":"ok","rejected":0,"shells":1,"steps":["box","shell","cut cylinder","chamfer","join cylinder"],"unsupported":1,"volume":9001.505742}, "53": {"area":17463.451761,"bodies":1,"edges":116,"error":null,"faces":48,"outcome":"ok","rejected":0,"shells":4,"steps":["extruded profile","cut cylinder","shell","fillet","join cylinder","circular pattern"],"unsupported":0,"volume":16954.551768}, "54": {"area":7075.531663,"bodies":1,"edges":81,"error":"offset: a corner whose faces don't meet the same way after t","faces":35,"outcome":"failed","rejected":0,"shells":4,"steps":["extruded profile","join box","circular pattern","cut cylinder","cut box","join cylinder","shell"],"unsupported":2,"volume":16028.147251}, - "55": {"area":6796.974648,"bodies":1,"edges":60,"error":null,"faces":23,"outcome":"ok","rejected":0,"shells":1,"steps":["box","fillet","cut sphere","circular pattern","rectangular pattern","cut sphere"],"unsupported":0,"volume":24740.927218}, + "55": {"area":6796.504547,"bodies":1,"edges":60,"error":null,"faces":23,"outcome":"ok","rejected":0,"shells":1,"steps":["box","fillet","cut sphere","circular pattern","rectangular pattern","cut sphere"],"unsupported":0,"volume":24744.182468}, "56": {"area":4453.31728,"bodies":1,"edges":33,"error":null,"faces":13,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut box","chamfer"],"unsupported":0,"volume":11829.375}, "57": {"area":4671.095724,"bodies":1,"edges":66,"error":null,"faces":24,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut sphere","circular pattern","chamfer","cut sphere","cut sphere","cut cylinder"],"unsupported":2,"volume":16017.21038}, "58": {"area":4197.049258,"bodies":1,"edges":42,"error":null,"faces":16,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","fillet","cut sphere"],"unsupported":0,"volume":12543.173591}, @@ -143,6 +143,7 @@ {"reason":"#2247: a cut no longer splits the separate pieces of a body into bodies of their own, so these seeds keep one body (bodies N -> 1). The generator looks at the model, so after the first such cut some seeds build different steps: seed 33 joins and patterns a box instead of chamfering (volume 13858 -> 24911 mm3), seed 18 now builds (its hole pattern failed with no result), and seed 54 picks a shell that fails the same way on main before #2247 (offset corner). Every step passes the validity and volume-direction checks.","seeds":[7,9,12,16,18,22,27,31,33,45,50,54,67,72,81,93]}, {"reason":"Reseam rotationally symmetric drill cutters after failed cuts (#2387): seed 86 now drills its hole, so its following pattern, shell and sphere cut complete with the fuzz validity and material checks.","seeds":[86]}, {"reason":"Rebase #2387 onto #2247: patterned pieces stay in one body. Seed 86 drills its hole, then reaches the same offset-corner shell refusal as main instead of shelling separate bodies. Completed steps still pass validity and volume-direction checks.","seeds":[86]}, - {"reason":"A join whose coincident faces were pushed apart now trims the slab beyond the plane by editing faces when the boolean cut of it fails (a prism whose edge in the plane lies in the end face of a slab with rounded corners). Seed 70: the shell of a body in two lumps, refused before, now builds; its volume matches an independent offset of the profile (4120.90 vs 4120.67 mm3, the gap is the unshelled profile's own tessellation).","seeds":[70]} + {"reason":"A join whose coincident faces were pushed apart now trims the slab beyond the plane by editing faces when the boolean cut of it fails (a prism whose edge in the plane lies in the end face of a slab with rounded corners). Seed 70: the shell of a body in two lumps, refused before, now builds; its volume matches an independent offset of the profile (4120.90 vs 4120.67 mm3, the gap is the unshelled profile's own tessellation).","seeds":[70]}, + {"reason":"#1648: a face whose boundary touches itself within the tolerance is triangulated through the touching point instead of across the face, so faces that meshed with triangles missing or outside them now mesh whole. Seeds 20 and 55 build the same designs (same steps, faces, edges and shells); only the measured area, and for seed 55 the volume, of their final bodies move. Seed 55: replaying it with the old and the new triangulation gives the same final body; two curved faces measured 442.14 and 325.42 mm2 with the old triangulation at a fine tolerance, 436.29 and 305.83 mm2 with the new one, which agrees with their coarser meshes, and its volume moves from 24740.93 to 24744.18 mm3, against 24743.58 mm3 from a mesh at 1e-4 mm. Seed 20, as main now builds it, moves only in area, from 5726.92956 to 5727.102692 mm2 (3e-5 relative). Recorded from the fork CI output (Linux).","seeds":[20,55]} ] } diff --git a/vendor/README.md b/vendor/README.md index cc622f620..600e40be3 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -190,6 +190,14 @@ Changes: point of the face's edges now goes to that point, when it is within the chord tolerance (`onto_edges`). Points within `TOLERANCE` stay on the surface, so exact geometry meshes as before. The meshes Boolean operations intersect keep truck's points. +- `tessellation/triangulation.rs`: a face whose boundary touches itself or another of its loops + within `TOLERANCE` (pinched to a point where a body touches its edge, #1648) can cross there by + less than that. A segment that would cross one already added was left out of the triangulation, + and the fallback that joins the next point instead cut across the face: such a face came out + with no triangles, or without those at the pinch, depending on which segment went in first. + When a segment is left out, every boundary point within `TOLERANCE` of a segment, away from its + ends, is put into it (`pinched`: at most 8192 boundary points, and at most 8192 put in), and + the face is triangulated again. Faces whose segments all go in are triangulated as before. - `tessellation/triangulation.rs`: in display and export meshes (`Deflection::rulings`), a direction left undivided along the rulings of a face ruled one way also gets a grid line diff --git a/vendor/truck-meshalgo/src/tessellation/triangulation.rs b/vendor/truck-meshalgo/src/tessellation/triangulation.rs index 0d28b316b..1428376c9 100644 --- a/vendor/truck-meshalgo/src/tessellation/triangulation.rs +++ b/vendor/truck-meshalgo/src/tessellation/triangulation.rs @@ -881,8 +881,9 @@ impl PolyBoundary { .unwrap_or(false) } - /// Inserts points and adds constraint into triangulation. - fn insert_to(&self, triangulation: &mut Cdt) { + /// Inserts points and adds constraint into triangulation. SolidCraft: whether every segment + /// went in. + fn insert_to(&self, triangulation: &mut Cdt) -> bool { let poly2tri: Vec<_> = self .0 .iter() @@ -894,6 +895,7 @@ impl PolyBoundary { .collect(); let mut prev: Option = None; let mut counter = 0; + let mut complete = true; self.0 .iter() .map(Vec::len) @@ -915,13 +917,63 @@ impl PolyBoundary { if triangulation.can_add_constraint(vi, vj) { triangulation.add_constraint(vi, vj); } else { + complete = false; prev = Some(i); } } }); + complete } } +/// SolidCraft: most boundary points [`pinched`] compares with every segment, and most points it +/// puts into segments. +const MAX_PINCH_POINTS: usize = 8192; + +/// SolidCraft: `loops` with every point that lies within `TOLERANCE` of a segment, away from its +/// ends, put into that segment (in order along it): where a loop touches itself or another, +/// both pass through the same point. `None` when no point does, or the loops have more than +/// [`MAX_PINCH_POINTS`] points, or more than that would be put in. +fn pinched(loops: &[Vec]) -> Option>> { + if loops.iter().map(Vec::len).sum::() > MAX_PINCH_POINTS { + return None; + } + let mut extra: Vec>> = loops.iter().map(|l| vec![Vec::new(); l.len()]).collect(); + let mut found = 0; + for (l, extra) in loops.iter().zip(&mut extra) { + let n = l.len(); + for (i, extra) in extra.iter_mut().enumerate() { + let (q0, q1) = (l[i], l[(i + 1) % n]); + let d = q1 - q0; + let len2 = d.magnitude2(); + if len2 <= TOLERANCE2 { + continue; + } + for &p in loops.iter().flatten() { + if p.distance2(q0) <= TOLERANCE2 || p.distance2(q1) <= TOLERANCE2 { + continue; + } + let t = (p - q0).dot(d) / len2; + if t > 0.0 && t < 1.0 && p.distance2(q0 + d * t) <= TOLERANCE2 { + if found == MAX_PINCH_POINTS { + return None; + } + extra.push((t, p)); + found += 1; + } + } + extra.sort_by(|a, b| a.0.total_cmp(&b.0)); + } + } + (found > 0).then(|| { + loops + .iter() + .zip(extra) + .map(|(l, extra)| l.iter().zip(extra).flat_map(|(p, e)| std::iter::once(*p).chain(e.into_iter().map(|(_, q)| q))).collect()) + .collect() + }) +} + fn spade_round(x: f64) -> f64 { match f64::abs(x) < MIN_ALLOWED_VALUE { true => 0.0, @@ -963,7 +1015,17 @@ pub(super) fn preview_face(surface: &S, loops: &[Vec

(surface: &S, polyboundary: &PolyBoundary, tol: Deflection, cap: usize, steps: Option) -> PolygonMesh { let mut triangulation = Cdt::new(); - polyboundary.insert_to(&mut triangulation); + // SolidCraft: a loop that touches itself or another loop within `TOLERANCE` (a face pinched + // to a point where a body touches its edge, #1648) can cross there by less than that. A + // segment that would cross one already added is left out, the fallback in `insert_to` then + // joins the next point across the face, and the face came out with no triangles. Its + // segments are then taken through the points they pass, and it is triangulated again. + if !polyboundary.insert_to(&mut triangulation) { + if let Some(loops) = pinched(&polyboundary.0) { + triangulation = Cdt::new(); + PolyBoundary(loops, Vec::new(), Vec::new()).insert_to(&mut triangulation); + } + } insert_surface(&mut triangulation, surface, polyboundary, tol, cap, steps); let mut mesh = triangulation_into_polymesh( triangulation.vertices(),