SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Wave 313/509: Mesh: a ray through an edge two triangles share crosses one of them (and 3 more)
jyviko0fa9c52b30a4
diff --git a/crates/doc/src/config_shell_tests.rs b/crates/doc/src/config_shell_tests.rsindex ad33c690ad..af8adaad59 100644--- a/crates/doc/src/config_shell_tests.rs+++ b/crates/doc/src/config_shell_tests.rs@@ -231,7 +231,7 @@ fn regularized_shell_keeps_legacy_and_explicit_single_face_projections_closed()#[test]fn saved_former_strip_projection_reports_lost_without_expanding_healthy_material() {- let (mut doc, _, shell) = shell_document();+ let (mut doc, _, _) = shell_document();let mut model = Model::new();model.evaluate(&doc);let state = model.state();@@ -240,27 +240,10 @@ fn saved_former_strip_projection_reports_lost_without_expanding_healthy_materiallet plane = body.body.face_plane(index).unwrap();let stem = crate::naming::face_names(body)[index].clone();assert_eq!(crate::naming::strip_piece(&stem), stem);- // Reconstruct the original raw shell before certificate stamping/regularization,- // and run the unchanged historical naming/capture path on its actual strip.- let before = model.state_before(shell);- // Legacy Shell did not propagate construction certificates. Omit transient- // metadata here; operand paint also disables new wall-run coalescence so- // this control retains the actual historical raw pieces.- let raw_source = solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(20., 12., 10.)).unwrap().with_paint(Some(solidcraft_kernel::Paint {- opacity: 1.,- faces: vec![solidcraft_kernel::FacePaint { face: 0, color: [1., 0., 0.], opacity: 1. }],- }));- let raw = solidcraft_kernel::shell(&raw_source, &[Vec3::new(5., 6., 10.)], 2.).unwrap();- let mut old_body = ModelBody::new("Case".into(), raw, shell);- old_body.names = crate::naming::NameCell::new(Some(std::sync::Arc::new(crate::naming::NamingOrigin {- feature: doc.feature(shell).unwrap().clone(),- before,- depth: 1,- mats: vec![],- sheets: vec![],- })));- let captured = crate::naming::face_name_at_body(&old_body, Vec3::new(20., 6., 1.)).unwrap();- assert_eq!(crate::naming::parent_piece(&captured), Some(stem.as_str()), "actual strip capture records a piece name");+ // The builds before format 14 split this wall into strips along the opening and saved a+ // projection of one of them by its number. The kernel's shell leaves the wall one face now,+ // so the strip exists only as that saved name and geometry.+ assert_eq!(crate::naming::face_name_at_body(body, Vec3::new(20., 6., 1.)).as_deref(), Some(stem.as_str()), "the shelled wall is one face");// What the builds before format 14 saved for that piece: its number by centroid order.let former = format!("{stem}#1");let mut sketch = solidcraft_sketch::Sketch::new();@@ -471,7 +454,6 @@ fn saved_curved_strip_projection_is_lost_after_exact_wall_coalescence() {#[test]fn saved_stepped_tab_cut_piece_projection_is_lost_without_expanding_material() {- use solidcraft_kernel::{BoolOp, FacePaint, Paint};use solidcraft_sketch::{LinkKind, LinkSource, Sketch};let mut doc = Document::new("public stepped tab case");doc.set_param("length", "40", Some("mm"), None).unwrap();@@ -498,46 +480,26 @@ fn saved_stepped_tab_cut_piece_projection_is_lost_without_expanding_material() {).unwrap();doc.feature_mut(tool).unwrap().body_names = vec!["Pocket tool".into()];- let cut = doc- .add_feature(- FeatureKind::Combine { target: "Case".into(), tools: vec!["Pocket tool".into()], operation: crate::Operation::Cut, keep_tools: false },- Some("Pocket"),- )- .unwrap();+ doc.add_feature(+ FeatureKind::Combine { target: "Case".into(), tools: vec!["Pocket tool".into()], operation: crate::Operation::Cut, keep_tools: false },+ Some("Pocket"),+ )+ .unwrap();let mut model = Model::new();model.evaluate(&doc);assert!(model.results.iter().all(|r| r.error.is_none()), "{:?}", model.results);- let before = model.state_before(cut);- // A real per-face paint control preserves the former slab construction;- // no historical names or geometry are fabricated.- let old_stock = before- .body("Case")- .unwrap()- .body- .clone()- .with_paint(Some(Paint { opacity: 1., faces: vec![FacePaint { face: 0, color: [1., 0., 0.], opacity: 1. }] }));- let old_cut = solidcraft_kernel::boolean(&old_stock, &before.body("Pocket tool").unwrap().body, BoolOp::Cut).unwrap().unwrap();- let mut old_body = ModelBody::new("Case".into(), old_cut, cut);- old_body.names = crate::naming::NameCell::new(Some(std::sync::Arc::new(crate::naming::NamingOrigin {- feature: doc.feature(cut).unwrap().clone(),- before,- depth: 1,- mats: vec![],- sheets: vec![],- })));+ // Older builds left Case's -x wall split by the Join and the Cut and saved a projection of+ // the patch y 10..20, z 0..20 by its piece name. The kernel leaves the wall one face now: the+ // patch is only that saved name and its rectangle on YZ.let at = Vec3::new(0., 15., 1.);- let former = crate::naming::face_name_at_body(&old_body, at).unwrap();- assert_ne!(former, crate::naming::strip_piece(&former), "actual former bounded wall patch has a full piece name");- let index = crate::naming::face_on_body(&old_body, &former, at).unwrap().0;- let mut old_state = crate::ModelState::default();- old_state.bodies.push(old_body);let plane = solidcraft_geom::Plane::YZ;- let resolved = crate::project::resolve_face_indices(&old_state, &plane, LinkKind::Project, "Case", &[index]).unwrap();let current_state = model.state();let current = current_state.body("Case").unwrap();- let stem = crate::naming::strip_piece(&former);+ let stem = crate::naming::face_name_at_body(current, at).unwrap();+ assert_eq!(crate::naming::strip_piece(&stem), stem, "the -x wall is one face");+ let former = format!("{stem}#1");let current_names = crate::naming::face_names(current);- let merged = current_names.iter().position(|name| name == stem).unwrap();+ let merged = current_names.iter().position(|name| name == &stem).unwrap();// The Join leaves Case's -x wall on its own support, so the wall keeps its exact box// identity through the Join and the Cut: one face again, no longer the saved piece.assert!(@@ -548,8 +510,10 @@ fn saved_stepped_tab_cut_piece_projection_is_lost_without_expanding_material() {"the merged wall carries its exact construction identity");assert!(!current_names.contains(&former));+ let corners = [Vec2::new(10., 0.), Vec2::new(20., 0.), Vec2::new(20., 20.), Vec2::new(10., 20.)];+ let geometry: Vec<_> = (0..4).map(|i| solidcraft_sketch::LinkGeom::Line(corners[i], corners[(i + 1) % 4])).collect();let mut sketch = Sketch::new();- sketch.add_link(LinkKind::Project, LinkSource::Face { body: "Case".into(), at }, &resolved.geom).unwrap();+ sketch.add_link(LinkKind::Project, LinkSource::Face { body: "Case".into(), at }, &geometry).unwrap();sketch.links[0].face_name = Some(former);let original = sketch.clone();let captured = original.points.iter().filter(|p| p.link.is_some()).map(|p| p.pos).collect::<Vec<_>>();diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rsindex 3a0bd95095..73c2b42ff8 100644--- a/crates/geom/src/mesh.rs+++ b/crates/geom/src/mesh.rs@@ -600,33 +600,10 @@ impl Mesh {self.edges.extend(o.edges.iter().cloned());}- /// Number of triangles a ray crosses (for inside/outside tests on closed meshes).+ /// Number of triangles a ray crosses (for inside/outside tests on closed meshes), each+ /// crossing counted once ([`ray_crosses`]).pub fn ray_crossings(&self, o: Vec3, dir: Vec3) -> usize {- let mut n = 0;- for t in &self.triangles {- let Some([a, b, c]) = self.tri(t) else { continue };- let (e1, e2) = (b - a, c - a);- let p = dir.cross(e2);- let det = e1.dot(p);- if det.abs() < 1e-14 {- continue;- }- let inv = 1.0 / det;- let s = o - a;- let u = s.dot(p) * inv;- if !(0.0..1.0).contains(&u) {- continue;- }- let q = s.cross(e1);- let v = dir.dot(q) * inv;- if v < 0.0 || u + v >= 1.0 {- continue;- }- if e2.dot(q) * inv > 0.0 {- n += 1;- }- }- n+ self.triangles.iter().filter_map(|t| self.tri(t)).filter(|&[a, b, c]| ray_crosses(a, b, c, o, dir)).count()}/// Point inside a closed mesh (majority vote of three skewed rays).@@ -854,33 +831,11 @@ impl InsideIndex<'_> {return 0;}let Some(list) = g.cells.get(gx * g.n.1 + gy) else { return 0 };- let dir = g.dir;- let mut n = 0;- for &i in list {- let Some(t) = self.mesh.triangles.get(i as usize) else { continue };- let Some([a, b, c]) = self.mesh.tri(t) else { continue };- let (e1, e2) = (b - a, c - a);- let p = dir.cross(e2);- let det = e1.dot(p);- if det.abs() < 1e-14 {- continue;- }- let inv = 1.0 / det;- let s = o - a;- let u = s.dot(p) * inv;- if !(0.0..1.0).contains(&u) {- continue;- }- let q = s.cross(e1);- let v = dir.dot(q) * inv;- if v < 0.0 || u + v >= 1.0 {- continue;- }- if e2.dot(q) * inv > 0.0 {- n += 1;- }- }- n+ list.iter()+ .filter_map(|&i| self.mesh.triangles.get(i as usize))+ .filter_map(|t| self.mesh.tri(t))+ .filter(|&[a, b, c]| ray_crosses(a, b, c, o, g.dir))+ .count()}/// Same answer as `Mesh::contains`.@@ -888,3 +843,23 @@ impl InsideIndex<'_> {self.rays.iter().filter(|g| self.crossings(g, p) % 2 == 1).count() >= 2}}++/// Whether the ray from `o` along `dir` crosses the triangle `a b c` in front of `o`. Watertight:+/// a ray through an edge two triangles share crosses exactly one of them. Each edge's side of the+/// ray is the signed volume `dir · ((p - o) × (q - o))`, exactly antisymmetric in floating point+/// (swapping `p` and `q` negates every rounded term), so both triangles see one value with+/// opposite signs; a ray exactly on the edge's line is put on one side by the edge's endpoints+/// in lexicographic order, the same for both. A triangle the ray runs along is not crossed.+fn ray_crosses(a: Vec3, b: Vec3, c: Vec3, o: Vec3, dir: Vec3) -> bool {+ let side = |p: Vec3, q: Vec3| {+ let v = dir.dot((p - o).cross(q - o));+ if v != 0.0 { v > 0.0 } else { (p.x, p.y, p.z) < (q.x, q.y, q.z) }+ };+ let normal = (b - a).cross(c - a);+ let along = dir.dot(normal);+ if along == 0.0 || !along.is_finite() {+ return false;+ }+ let s = side(a, b);+ side(b, c) == s && side(c, a) == s && (a - o).dot(normal) / along > 0.0+}diff --git a/crates/geom/src/tests.rs b/crates/geom/src/tests.rsindex ab614f0e4e..4317155031 100644--- a/crates/geom/src/tests.rs+++ b/crates/geom/src/tests.rs@@ -97,6 +97,44 @@ fn raycast_never_slips_between_triangles() {}}+/// A ray through an edge that two triangles share crosses exactly one of them: the same grid,+/// crossed at every inner edge's midpoint (and the middle of each cell, on its diagonal), straight+/// down and obliquely. The bracket example's hole centre fell on such an edge of the base's top+/// and was counted once for two faces.+#[test]+fn ray_crossings_count_a_shared_edge_once() {+ let n = 6;+ let positions: Vec<Vec3> =+ (0..=n).flat_map(|j| (0..=n).map(move |i| Vec3::new(f64::from(i) * 40.0 / 6.0 + 100.0, f64::from(j) * 5.0, 20.0))).collect();+ let id = |i: u32, j: u32| j * (n + 1) + i;+ let mut triangles = Vec::new();+ for j in 0..n {+ for i in 0..n {+ triangles.push([id(i, j), id(i + 1, j), id(i + 1, j + 1)]);+ triangles.push([id(i, j), id(i + 1, j + 1), id(i, j + 1)]);+ }+ }+ let tri_face = vec![0; triangles.len()];+ let m = Mesh { positions, triangles, tri_face, ..Default::default() };+ let dirs = [Vec3::new(-0.57735, 0.57735, -0.57735), Vec3::new(0.3, -0.7, -0.648), Vec3::new(-0.123456789, -0.2, -1.0), Vec3::new(0.0, 0.0, -1.0)];+ for d in dirs {+ for j in 1..2 * n {+ for i in 1..2 * n {+ if i % 2 == 0 && j % 2 == 0 {+ continue;+ }+ let p = Vec3::new(f64::from(i) * 20.0 / 6.0 + 100.0, f64::from(j) * 2.5, 20.0);+ assert_eq!(m.ray_crossings(p - d * 50.0, d), 1, "{p:?} along {d:?}");+ assert_eq!(m.ray_crossings(p + d * 50.0, d), 0, "{p:?} along {d:?}, from beyond");+ }+ }+ }+ // A closed cube: a ray through its top's diagonal crosses the top and the bottom.+ let cube = cube_mesh(2.0);+ assert_eq!(cube.ray_crossings(Vec3::new(0.5, 0.5, 5.0), Vec3::new(0.0, 0.0, -1.0)), 2);+ assert_eq!(cube.ray_crossings(Vec3::new(0.5, 0.5, 1.0), Vec3::new(0.0, 0.0, -1.0)), 1);+}+#[test]fn planes() {assert_eq!(Plane::XY.normal(), Vec3::Z);diff --git a/crates/kernel/src/planar_sources.rs b/crates/kernel/src/planar_sources.rsindex af081a1f58..ad0ee3249c 100644--- a/crates/kernel/src/planar_sources.rs+++ b/crates/kernel/src/planar_sources.rs@@ -141,6 +141,12 @@ impl Body {self.map_planar_sources(&[input], None, None, &[], false)}+ /// Generate distinct outer/inner roles from the exact original supports of+ /// an inside shell. Generated rims and curved walls are intentionally absent.+ pub(crate) fn with_shell_planar_sources(self, input: &Body, thickness: f64, open: &[Vec3]) -> Result<Self> {+ self.map_planar_sources(&[input], Some(thickness), None, open, false)+ }+/// Retain exact shell roles, and construction roles for Cut, only on unchanged/// supports without a competing coplanar tool. No imported or fitted role is inferred.pub(crate) fn with_preserved_boolean_planar_sources(self, input: &Body, tool: &Body, constructed: bool) -> Result<Self> {diff --git a/crates/kernel/src/polyhedron.rs b/crates/kernel/src/polyhedron.rsindex 5b966f9cd4..4b895bce97 100644--- a/crates/kernel/src/polyhedron.rs+++ b/crates/kernel/src/polyhedron.rs@@ -185,10 +185,12 @@ fn polyhedron_record(hs: &[HalfSpace], verts: &[Vec3], faces: &[(usize, Vec<usiz}/// Hollow a body: walls of `thickness` inside, open at the faces under `open` (SMLib's shell).-/// The result's history is over `[b]`: the inner walls are offsets of the faces they line.+/// The result's history is over `[b]`: the inner walls are offsets of the faces they line. Each+/// kept planar wall and its inner lining carry the outer and inner shell roles of the face they+/// came from (face certificates: sketches and press-pulls attach to them).pub fn shell(b: &Body, open: &[Vec3], thickness: f64) -> Result<Body> {let _span = solidcraft_profile::span("kernel", "shell");- crate::offset_backend::shell(b, open, thickness)+ crate::offset_backend::shell(b, open, thickness)?.with_shell_planar_sources(b, thickness, open)}/// Tilt the faces near `faces` by `angle` about their line on the neutral plane, so that theydiff --git a/crates/kernel/src/prism.rs b/crates/kernel/src/prism.rsindex 6e49fe704e..7f7d97dada 100644--- a/crates/kernel/src/prism.rs+++ b/crates/kernel/src/prism.rs@@ -128,23 +128,27 @@ mod sheets {/// SmBrep.cpp: "spine points"), as where pieces of material touch at a corner or an outline/// passes a point twice. So each loop, oriented (outer counter-clockwise, holes clockwise), is/// split where it passes a point twice into simple loops, and each simple loop is a face of its- /// own; those running counter-clockwise are material, the others holes. The sheet is the- /// material united less the holes united (SMLib's 2D boolean, which takes touching faces).- /// `tol` (mm): how close a loop's passes through one point are.+ /// own; those running counter-clockwise are material, the others holes. Each region is its+ /// material united less its holes united (SMLib's 2D boolean, which takes touching faces), and+ /// the sheet is the regions united: a region may lie in another's hole (the island inside a+ /// ring), where the other's hole must not take it. `tol` (mm): how close a loop's passes+ /// through one point are.pub(super) fn sheet(regions: &[Region2], tol: f64) -> Result<Brep> {- let (mut material, mut holes) = (Vec::new(), Vec::new());+ let mut sheets = Vec::with_capacity(regions.len());for r in regions {+ let (mut material, mut holes) = (Vec::new(), Vec::new());let loops = std::iter::once(r.outer.ccw()).chain(r.holes.iter().map(|h| h.ccw().reversed()));for piece in loops.flat_map(|lp| simple_loops(lp, tol * 10.0)) {let face = face(&piece)?;if piece.signed_area() > 0.0 { material.push(face) } else { holes.push(face) }}+ let Some(material) = united(material)? else { continue };+ sheets.push(match united(holes)? {+ Some(holes) => combine(&material, &holes, BoolOp::Cut)?.ok_or_else(|| failed("sheet", "the holes take all the material"))?,+ None => material,+ });}- let material = united(material)?.ok_or_else(|| failed("sheet", "the regions hold no material"))?;- match united(holes)? {- Some(holes) => combine(&material, &holes, BoolOp::Cut)?.ok_or_else(|| failed("sheet", "the holes take all the material")),- None => Ok(material),- }+ united(sheets)?.ok_or_else(|| failed("sheet", "the regions hold no material"))}/// A simple closed loop as one planar face.