SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Sketch Intersect: crossings on curved faces lie on the surface; a plane on a top face cuts it (#6272)
NOWN-DEV74321f8bbd87
diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rsindex dd662d1ac1..d01f219a41 100644--- a/crates/doc/src/project.rs+++ b/crates/doc/src/project.rs@@ -1046,12 +1046,29 @@ fn silhouette(plane: &Plane, m: &Mesh) -> Vec<LinkGeom> {/// Section of a mesh (or one of its faces) with the sketch plane.pub(crate) fn section(plane: &Plane, m: &Mesh, face: Option<u32>) -> Vec<LinkGeom> {+ let size = m.bounds().diagonal().max(1e-9);+ let (segs, exact) = section_segments(plane, m, face);+ let segs: Vec<(Vec2, Vec2)> = segs.into_iter().map(|(a, b, _)| (a, b)).collect();+ let loose = size * 2e-3;+ fit_segments(&segs, size).into_iter().map(|g| refine_round(g, &exact, loose)).collect()+}++/// The segments where the plane crosses the mesh's triangles (in plane coordinates, each with+/// its B-rep face), and the crossings that lie exactly on the surface (on a ruling).+fn section_segments(plane: &Plane, m: &Mesh, face: Option<u32>) -> (Vec<(Vec2, Vec2, u32)>, Vec<Vec2>) {let size = m.bounds().diagonal().max(1e-9);let q = size * 1e-7;let key = |p: Vec3| ((p.x / q).round() as i64, (p.y / q).round() as i64, (p.z / q).round() as i64);// Surface normal at each mesh vertex where the surface is smooth (None at creases), over// all faces and per face.type Key = (i64, i64, i64);+ // A vertex this close to the plane is on it, and lies on the same side for every edge it+ // ends (so a plane through a vertex, or on a face, cuts every edge there alike): below when+ // the mesh lies on or above the plane (the cut at its bottom face), else above (at its top+ // face, through an apex). An edge with an end on the plane crosses it at that end.+ let snap = size * 1e-9;+ let zero_above = m.positions.iter().any(|p| plane.height(*p) < -snap);+ let above = |h: f64| if h.abs() <= snap { zero_above } else { h > 0.0 };let mut normals: BTreeMap<Key, Option<Vec3>> = BTreeMap::new();let mut face_normals: BTreeMap<(u32, Key), Option<Vec3>> = BTreeMap::new();// Faces on either side of each mesh edge.@@ -1084,14 +1101,25 @@ pub(crate) fn section(plane: &Plane, m: &Mesh, face: Option<u32>) -> Vec<LinkGeolet crossing = |a: Vec3, b: Vec3| -> Option<Vec3> {let (a, b) = if key(a) <= key(b) { (a, b) } else { (b, a) };let (ha, hb) = (plane.height(a), plane.height(b));- if (ha > 0.0) == (hb > 0.0) {+ if above(ha) == above(hb) {return None;}+ if let Some(p) = [(a, ha), (b, hb)].into_iter().find(|(_, h)| h.abs() <= snap).map(|(p, _)| p) {+ exact.borrow_mut().push(plane.to_local(p));+ return Some(p);+ }let d = b - a;// An edge inside one face takes that face's normals (its ends may lie on the face's// boundary, a crease for the whole mesh); an edge between faces, the merged ones, so// both faces agree on the crossing.- let inside = edge_faces.get(&(key(a), key(b))).and_then(|fs| fs.first().filter(|f| fs.len() == 2 && fs.iter().all(|x| x == *f)).copied());+ let faces = edge_faces.get(&(key(a), key(b)));+ let inside = faces.and_then(|fs| fs.first().filter(|f| fs.len() == 2 && fs.iter().all(|x| x == *f)).copied());+ // An edge where a curved face meets another (a cylinder's rim on its cap) lies on the+ // curved face: its normals there put the crossing on the curve, not on the chord.+ let face_normal = |f: u32, p: Vec3| face_normals.get(&(f, key(p))).copied().flatten();+ let curved =+ || faces?.iter().copied().find(|f| matches!((face_normal(*f, a), face_normal(*f, b)), (Some(x), Some(y)) if x.dot(y) < 1.0 - 1e-12));+ let inside = inside.or_else(curved);let normal = |p: Vec3| match inside {Some(f) => face_normals.get(&(f, key(p))).copied().flatten(),None => normals.get(&key(p)).copied().flatten(),@@ -1136,7 +1164,7 @@ pub(crate) fn section(plane: &Plane, m: &Mesh, face: Option<u32>) -> Vec<LinkGeo}Some(h(0.5 * (lo + hi)))};- let mut segs: Vec<(Vec2, Vec2)> = Vec::new();+ let mut segs: Vec<(Vec2, Vec2, u32)> = Vec::new();for (t, f) in m.triangles.iter().zip(&m.tri_face) {if face.is_some_and(|x| x != *f) {continue;@@ -1152,13 +1180,11 @@ pub(crate) fn section(plane: &Plane, m: &Mesh, face: Option<u32>) -> Vec<LinkGeoif let [a, b] = pts[..] {let (a, b) = (plane.to_local(a), plane.to_local(b));if a.dist(b) > size * 1e-9 {- segs.push((a, b));+ segs.push((a, b, *f));}}}- let exact = exact.into_inner();- let loose = size * 2e-3;- fit_segments(&segs, size).into_iter().map(|g| refine_round(g, &exact, loose)).collect()+ (segs, exact.into_inner())}/// Re-fit a circle or arc through the exact section points near it, when there are enough.diff --git a/crates/engine/src/cmd/sketch_project_tests.rs b/crates/engine/src/cmd/sketch_project_tests.rsindex d136c4c9d1..0d42b14a5a 100644--- a/crates/engine/src/cmd/sketch_project_tests.rs+++ b/crates/engine/src/cmd/sketch_project_tests.rs@@ -737,3 +737,80 @@ fn projecting_what_the_face_sketch_already_shows_adds_no_second_copy() {assert_eq!(r["already_projected"].as_array().unwrap().len(), 1, "{r}");assert_eq!(shown(&mut s).0, border.0 + 1);}++/// The curves sketch Intersect makes, on `plane`, of the first body `steps` build: each line's ends,+/// each circle's centre and radius.+fn intersect_curves(steps: &[(&str, Value)], plane: Value) -> std::result::Result<Vec<Value>, String> {+ let mut s = Session::default();+ for (cmd, p) in steps {+ run(&mut s, cmd, p.clone());+ }+ run(&mut s, "sketch.create", plane);+ let body = s.model.state().bodies[0].name.clone();+ s.execute("sketch.intersect", &json!({"refs": [{"body": body}]})).map_err(|e| e.to_string())?;+ Ok(linked_curves(&inspect(&mut s)))+}++fn line_ends(curves: &[Value]) -> Vec<[f64; 4]> {+ let at = |c: &Value, k: &str, i: usize| c[k][i].as_f64().unwrap_or(f64::NAN);+ curves+ .iter()+ .filter(|c| c["type"] == "line")+ .map(|c| [at(c, "start_at", 0), at(c, "start_at", 1), at(c, "end_at", 0), at(c, "end_at", 1)])+ .collect()+}++/// Where Intersect's cut is already exact it stays as it is: a box's outline (through it and on+/// its bottom face), a cylinder's and a sphere's circle, a tilted cylinder's 21 segments.+#[test]+fn intersect_keeps_its_exact_cuts() {+ let block = [("solid.box", json!({"length": 40, "width": 30, "height": 20}))];+ for offset in [10, 0] {+ let mut ends = line_ends(&intersect_curves(&block, json!({"plane": "XY", "offset": offset})).unwrap());+ ends.iter_mut().for_each(|e| *e = e.map(|v| v.round()));+ ends.sort_by(|a, b| a.partial_cmp(b).unwrap());+ assert_eq!(ends, vec![[0.0, 0.0, 40.0, 0.0], [0.0, 30.0, 0.0, 0.0], [40.0, 0.0, 40.0, 30.0], [40.0, 30.0, 0.0, 30.0]], "offset {offset}");+ }+ for (steps, plane, radius) in [+ (vec![("solid.cylinder", json!({"base": [0, 0, 0], "radius": 7, "height": 30}))], json!({"plane": "XY", "offset": 12}), 7.0),+ (vec![("solid.sphere", json!({"center": [0, 0, 0], "radius": 10}))], json!({"plane": "XY", "offset": 4}), 84f64.sqrt()),+ ] {+ let c = intersect_curves(&steps, plane).unwrap();+ assert!(c.len() == 1 && c[0]["type"] == "circle" && (c[0]["radius"].as_f64().unwrap() - radius).abs() < 1e-4, "{c:?}");+ }+ let tilted = [("solid.cylinder", json!({"base": [0, 0, 0], "radius": 5, "height": 40, "axis": [1, 0, 1]}))];+ let ends = line_ends(&intersect_curves(&tilted, json!({"plane": "XY", "offset": 10})).unwrap());+ assert_eq!(ends.len(), 21);+ let first = [2.941, -0.2891, 3.3932, -1.7819];+ assert!(ends[0].iter().zip(first).all(|(a, b)| (a - b).abs() < 1e-4), "{:?}", ends[0]);+}++/// A plane crossing a curved face's rim cuts it on the surface, not on the mesh's chord: a+/// cylinder's sides lie √40 from its axis, a hole's walls its radius from its centre (they were+/// 6.3159 and 6.3085, 25.0122 and 34.9878).+#[test]+fn intersect_crosses_a_curved_face_on_the_surface() {+ let side = (40f64).sqrt();+ let rod = [("solid.cylinder", json!({"base": [0, 0, 0], "radius": 7, "height": 30}))];+ let xs: Vec<f64> = line_ends(&intersect_curves(&rod, json!({"plane": "XZ", "offset": 3})).unwrap()).iter().flat_map(|e| [e[0], e[2]]).collect();+ assert!(xs.iter().all(|x| (x.abs() - side).abs() < 1e-4 || x.abs() < 1e-9), "{xs:?}");+ assert!(xs.iter().any(|x| (x + side).abs() < 1e-4) && xs.iter().any(|x| (x - side).abs() < 1e-4), "{xs:?}");+ let plate = [("solid.box", json!({"length": 60, "width": 40, "height": 5})), ("solid.hole", json!({"position": [30, 20, 5], "diameter": 10}))];+ let xs: Vec<f64> =+ line_ends(&intersect_curves(&plate, json!({"plane": "XZ", "offset": 20})).unwrap()).iter().flat_map(|e| [e[0], e[2]]).collect();+ for wall in [25.0, 35.0] {+ assert!(xs.iter().any(|x| (x - wall).abs() < 1e-4), "{wall}: {xs:?}");+ }+ assert!(xs.iter().all(|x| [0.0, 25.0, 35.0, 60.0].iter().any(|w| (x - w).abs() < 1e-4)), "{xs:?}");+}++/// A plane on a body's top face cuts it there, as one on its bottom face does (it found nothing:+/// "projects to nothing on this sketch plane").+#[test]+fn intersect_on_a_top_face_gives_its_outline() {+ let block = [("solid.box", json!({"length": 40, "width": 30, "height": 20}))];+ let mut ends = line_ends(&intersect_curves(&block, json!({"plane": "XY", "offset": 20})).unwrap());+ ends.iter_mut().for_each(|e| *e = e.map(|v| v.round()));+ ends.sort_by(|a, b| a.partial_cmp(b).unwrap());+ assert_eq!(ends, vec![[0.0, 0.0, 40.0, 0.0], [0.0, 30.0, 0.0, 0.0], [40.0, 0.0, 40.0, 30.0], [40.0, 30.0, 0.0, 30.0]]);+}