SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Snap points: the centre, middle and ends an edge or face offers, in the engine (#5881) (#5882)
Franka402c5e50278
diff --git a/crates/engine/src/cmd/measure_sel.rs b/crates/engine/src/cmd/measure_sel.rsindex a20ebe161d..7ab108d8e3 100644--- a/crates/engine/src/cmd/measure_sel.rs+++ b/crates/engine/src/cmd/measure_sel.rs@@ -367,6 +367,16 @@ fn describe(s: &Session, sel: &Sel) -> Option<Item> {}}+/// A picked item's exact shape with its points (an edge's polyline) and triangles (a face's),+/// as Measure sees it: what [`crate::snap`] takes an item's centres, middle and ends from.+pub(crate) fn shape_of(s: &Session, sel: &Sel) -> Option<(Shape, Vec<Vec3>, Vec<[Vec3; 3]>)> {+ let item = describe(s, sel)?;+ Some(match item.geo {+ Geo::Points(p) => (item.shape, p, Vec::new()),+ Geo::Tris(t) => (item.shape, Vec::new(), t),+ })+}+fn sample<T: Copy>(v: &[T], max: usize) -> Vec<T> {let step = v.len().div_ceil(max).max(1);v.iter().step_by(step).copied().collect()diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rsindex 414cd774c6..63f45ed101 100644--- a/crates/engine/src/cmd/mod.rs+++ b/crates/engine/src/cmd/mod.rs@@ -60,7 +60,8 @@ pub(crate) mod motion;mod parts;mod script;mod section;-pub(crate) use measure_sel::measure_items;+pub(crate) use measure_sel::{measure_items, shape_of};+pub(crate) use measure_shape::Shape;#[cfg(test)]mod kernel_heal_tests;mod parameter_sweep;diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 2639e5f468..56ec782c86 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -24,6 +24,7 @@ pub mod sample;pub mod schema;mod slicer_icon;pub mod slicers;+pub mod snap;pub mod timing;pub mod view;@@ -1338,6 +1339,8 @@ mod profile_refs_tests;#[cfg(test)]mod sketch_edit_removed_tests;#[cfg(test)]+mod snap_tests;+#[cfg(test)]mod split_face_tests;#[cfg(test)]mod tests;diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rsnew file mode 100644index 0000000000..04e806016b--- /dev/null+++ b/crates/engine/src/snap.rs@@ -0,0 +1,197 @@+//! Snap points (#5881): the points a hovered edge or face offers as picks, so a point input+//! (Move's From and To, Measure, …) can take a hole's centre or an edge's middle where no vertex+//! sits. A round edge offers its centre (an arc also its ends and middle), a straight or other+//! edge its ends and middle, a flat face its centre, a cylinder or cone the centres of its ends,+//! a sphere or torus its centre, a vertex itself. The shapes are Measure's: exact from the+//! kernel where it knows the curve or surface, fitted to the mesh otherwise. World coordinates,+//! as the viewport shows the model.++use serde::Serialize;+use solidcraft_geom::{UnitVec3, Vec3};++use crate::cmd::Shape;+use crate::{Sel, Session};++/// What a snap point is on its item.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum SnapKind {+ /// The centre of a circle, an arc, a sphere or a torus, or of one end of a cylinder or cone.+ Centre,+ /// The middle of an edge (along its length).+ Middle,+ /// One end of an edge.+ End,+ /// The centre of a flat face (of its area).+ FaceCentre,+ /// A vertex.+ Vertex,+}++/// A point an item offers as a pick.+#[derive(Clone, Debug, PartialEq, Serialize)]+pub struct SnapPoint {+ pub at: Vec3,+ pub kind: SnapKind,+ /// The body the item belongs to (empty for the origin and sketch geometry).+ pub body: String,+}++/// Points closer than this (relative to the item's size) are one snap point.+const SAME: f64 = 1e-6;++/// The snap points `sel` offers: none for things with no points to offer (a body, a plane).+pub fn snap_points(s: &Session, sel: &Sel) -> Vec<SnapPoint> {+ let body = match sel {+ Sel::Edge { body, .. } | Sel::Face { body, .. } | Sel::Vertex { body, .. } => body.clone(),+ _ => String::new(),+ };+ let found = match sel {+ Sel::Vertex { point, .. } => vec![(*point, SnapKind::Vertex)],+ Sel::Edge { .. } | Sel::SketchCurve { .. } | Sel::ExternalSketchCurve { .. } => edge_points(s, sel),+ Sel::Face { .. } => face_points(s, sel),+ _ => Vec::new(),+ };+ let mut out: Vec<SnapPoint> = Vec::new();+ for (at, kind) in found {+ let tol = SAME * (1.0 + at.len());+ if at.is_finite() && !out.iter().any(|p| p.at.dist(at) <= tol) {+ out.push(SnapPoint { at, kind, body: body.clone() });+ }+ }+ out+}++/// An edge's or sketch curve's points: a whole circle its centre; an arc its centre, ends and+/// middle; anything else its ends and middle.+fn edge_points(s: &Session, sel: &Sel) -> Vec<(Vec3, SnapKind)> {+ let Some((shape, pts, _)) = crate::cmd::shape_of(s, sel) else { return Vec::new() };+ let ends = |v: &mut Vec<(Vec3, SnapKind)>| {+ v.extend(pts.first().map(|p| (*p, SnapKind::End)));+ v.extend(pts.last().map(|p| (*p, SnapKind::End)));+ };+ let mut v = Vec::new();+ match shape {+ Shape::Round { center, axis, radius, .. } => {+ v.push((center, SnapKind::Centre));+ if !shape.full() {+ // The kernel may split one arc into pieces (at a cylinder's seam): the whole arc.+ let arc = whole_arc(s, sel, center, axis, radius).unwrap_or(pts.clone());+ v.extend(arc.first().map(|p| (*p, SnapKind::End)));+ v.extend(arc.last().map(|p| (*p, SnapKind::End)));+ v.extend(arc_middle(center, axis, &arc).map(|p| (p, SnapKind::Middle)));+ }+ }+ Shape::Line { a, b } => v.extend([(a, SnapKind::End), (b, SnapKind::End), (a.lerp(b, 0.5), SnapKind::Middle)]),+ _ => {+ ends(&mut v);+ v.extend(along(&pts, 0.5).map(|p| (p, SnapKind::Middle)));+ }+ }+ v+}++/// The polyline of a picked edge joined with the neighbouring edges that continue it on the+/// same circle, in order: the whole arc when the kernel split it.+fn whole_arc(s: &Session, sel: &Sel, center: Vec3, axis: UnitVec3, radius: f64) -> Option<Vec<Vec3>> {+ let Sel::Edge { body, index, .. } = sel else { return None };+ let st = s.world_state();+ let m = st.body(body)?.mesh();+ let tol = (radius * 1e-6).max(1e-9);+ let on = |e: &Vec<Vec3>| e.iter().all(|p| (p.dist(center) - radius).abs() <= tol * 10.0 && (*p - center).dot(axis).abs() <= tol * 10.0);+ let mut left: Vec<usize> =+ m.tangent_chain(*index, 2f64.to_radians()).into_iter().filter(|&i| i != *index && m.edges.get(i).is_some_and(on)).collect();+ let mut arc = m.edges.get(*index).filter(|e| on(e))?.clone();+ // Add pieces at either end while one starts or ends there (capped by the pieces there are).+ while let Some((k, at_end, rev)) = left.iter().enumerate().find_map(|(k, &i)| {+ let e = m.edges.get(i)?;+ let (first, last, a, z) = (*e.first()?, *e.last()?, *arc.first()?, *arc.last()?);+ [(z, first, true, false), (z, last, true, true), (a, last, false, false), (a, first, false, true)]+ .into_iter()+ .find(|(p, q, _, _)| p.dist(*q) <= tol * 10.0)+ .map(|(_, _, at_end, rev)| (k, at_end, rev))+ }) {+ let i = left.swap_remove(k);+ let mut piece = m.edges.get(i)?.clone();+ if rev {+ piece.reverse();+ }+ if at_end {+ arc.extend(piece.into_iter().skip(1));+ } else {+ piece.pop();+ piece.extend(arc);+ arc = piece;+ }+ }+ Some(arc)+}++/// The exact middle of an arc through `pts` (first to last): on the circle, halfway round+/// from one end to the other on the side the polyline runs.+fn arc_middle(center: Vec3, axis: UnitVec3, pts: &[Vec3]) -> Option<Vec3> {+ let (a, z) = (*pts.first()? - center, *pts.last()? - center);+ let near = along(pts, 0.5)? - center;+ let radius = a.len();+ // Along the bisector of the ends, or square to them across a half circle.+ let dir = (a + z).normalized().or_else(|| axis.cross(a).normalized())?;+ let dir = if dir.dot(near) < 0.0 { -dir } else { dir };+ Some(center + dir * radius)+}++/// The point a fraction `f` of the way along a polyline (by length).+fn along(pts: &[Vec3], f: f64) -> Option<Vec3> {+ let total: f64 = pts.windows(2).map(|w| w[0].dist(w[1])).sum();+ let mut left = total * f;+ for w in pts.windows(2) {+ let d = w[0].dist(w[1]);+ if left <= d && d > 0.0 {+ return Some(w[0].lerp(w[1], left / d));+ }+ left -= d;+ }+ pts.last().copied()+}++/// A face's points: a flat face its area's centre; a cylinder or cone the centres of its two+/// ends on the axis; a sphere or torus its centre.+fn face_points(s: &Session, sel: &Sel) -> Vec<(Vec3, SnapKind)> {+ let Sel::Face { body, index, .. } = sel else { return Vec::new() };+ let st = s.world_state();+ let Some(b) = st.body(body) else { return Vec::new() };+ let Some((shape, _, tris)) = crate::cmd::shape_of(s, sel) else { return Vec::new() };+ let verts: Vec<Vec3> = tris.iter().flat_map(|t| t.iter().copied()).collect();+ match solidcraft_kernel::face_surface(&b.body, *index) {+ Some(solidcraft_kernel::FaceSurface::Sphere { center, .. } | solidcraft_kernel::FaceSurface::Torus { center, .. }) => {+ return vec![(center, SnapKind::Centre)];+ }+ Some(solidcraft_kernel::FaceSurface::Cone { apex, axis, .. }) => return axis_ends(apex, axis, &verts),+ _ => {}+ }+ match shape {+ Shape::Round { center, axis, .. } => axis_ends(center, axis, &verts),+ Shape::Plane { .. } => area_centre(&tris).map(|p| vec![(p, SnapKind::FaceCentre)]).unwrap_or_default(),+ _ => Vec::new(),+ }+}++/// The points of the axis through `origin` along `axis` level with the face's two ends.+fn axis_ends(origin: Vec3, axis: UnitVec3, verts: &[Vec3]) -> Vec<(Vec3, SnapKind)> {+ let along = || verts.iter().map(|p| (*p - origin).dot(axis));+ let (lo, hi) = (along().fold(f64::INFINITY, f64::min), along().fold(f64::NEG_INFINITY, f64::max));+ if !(lo.is_finite() && hi.is_finite()) {+ return Vec::new();+ }+ vec![(origin + axis * lo, SnapKind::Centre), (origin + axis * hi, SnapKind::Centre)]+}++/// The centre of the area of some triangles.+fn area_centre(tris: &[[Vec3; 3]]) -> Option<Vec3> {+ let (mut sum, mut area) = (Vec3::ZERO, 0.0);+ for [a, b, c] in tris {+ let w = (*b - *a).cross(*c - *a).len() * 0.5;+ sum += (*a + *b + *c) * (w / 3.0);+ area += w;+ }+ (area > 0.0).then(|| sum * (1.0 / area))+}diff --git a/crates/engine/src/snap_tests.rs b/crates/engine/src/snap_tests.rsnew file mode 100644index 0000000000..50e31a42d0--- /dev/null+++ b/crates/engine/src/snap_tests.rs@@ -0,0 +1,139 @@+//! Snap points (#5881): the centres, middles and ends edges and faces offer. Every expected+//! point is worked out by hand from the part's dimensions.++use std::f64::consts::{FRAC_1_SQRT_2, PI};++use serde_json::{Value, json};+use solidcraft_geom::Vec3;++use crate::snap::{SnapKind, SnapPoint, snap_points};+use crate::{Sel, Session};++fn run(s: &mut Session, id: &str, p: Value) {+ if let Err(e) = s.execute(id, &p) {+ panic!("{id} {p}: {e}");+ }+}++/// A 60 × 40 × 10 plate with a Ø6 hole at (15, 20) and a Ø8 hole at (45, 20).+fn plate() -> Session {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 60, "width": 40, "height": 10}));+ run(&mut s, "solid.cylinder", json!({"radius": 3, "height": 12, "base": [15, 20, -1], "operation": "cut"}));+ run(&mut s, "solid.cylinder", json!({"radius": 4, "height": 12, "base": [45, 20, -1], "operation": "cut"}));+ s+}++fn sel(v: Value) -> Sel {+ serde_json::from_value(v).unwrap()+}++/// The first mesh edge all of whose points satisfy `on`, as a pick.+fn edge(s: &Session, on: impl Fn(Vec3) -> bool) -> Sel {+ let st = s.model.state();+ let b = st.bodies.first().unwrap();+ let m = b.mesh();+ let (i, e) = m.edges.iter().enumerate().find(|(_, e)| e.iter().all(|p| on(*p))).unwrap();+ sel(json!({"type": "edge", "body": b.name, "index": i, "point": e[e.len() / 2]}))+}++/// The face all of whose triangle corners satisfy `on`, as a pick.+fn face(s: &Session, on: impl Fn(Vec3) -> bool) -> Sel {+ let st = s.model.state();+ let b = st.bodies.first().unwrap();+ let m = b.mesh();+ let n = m.tri_face.iter().map(|f| *f as usize + 1).max().unwrap();+ let tris = |f: usize| -> Vec<[Vec3; 3]> {+ m.triangles.iter().zip(&m.tri_face).filter(|(_, tf)| **tf as usize == f).filter_map(|(t, _)| m.tri(t)).collect()+ };+ let f = (0..n).find(|&f| !tris(f).is_empty() && tris(f).iter().all(|t| t.iter().all(|p| on(*p)))).unwrap();+ sel(json!({"type": "face", "body": b.name, "index": f, "point": tris(f)[0][0]}))+}++/// The points of one kind, in the order given.+fn of(points: &[SnapPoint], kind: SnapKind) -> Vec<Vec3> {+ points.iter().filter(|p| p.kind == kind).map(|p| p.at).collect()+}++/// Whether `got` holds exactly the `want` points (any order), each within `tol`.+fn same(got: &[Vec3], want: &[Vec3], tol: f64) -> bool {+ got.len() == want.len() && want.iter().all(|w| got.iter().any(|g| g.dist(*w) <= tol))+}++#[test]+fn a_hole_offers_the_centres_of_its_ends_and_its_rim_its_centre() {+ let s = plate();+ let wall = face(&s, |p| ((p - Vec3::new(15.0, 20.0, p.z)).len() - 3.0).abs() < 1e-3);+ let got = snap_points(&s, &wall);+ assert!(same(&of(&got, SnapKind::Centre), &[Vec3::new(15.0, 20.0, 0.0), Vec3::new(15.0, 20.0, 10.0)], 1e-6), "{got:?}");+ assert_eq!(got.len(), 2, "only the two centres: {got:?}");++ let rim = edge(&s, |p| (p.z - 10.0).abs() < 1e-9 && ((p - Vec3::new(45.0, 20.0, 10.0)).len() - 4.0).abs() < 1e-3);+ let got = snap_points(&s, &rim);+ assert!(same(&of(&got, SnapKind::Centre), &[Vec3::new(45.0, 20.0, 10.0)], 1e-6), "{got:?}");+ assert_eq!(got.len(), 1, "a whole circle offers only its centre: {got:?}");+ assert!(got.iter().all(|p| p.body == "Body1"), "{got:?}");+}++#[test]+fn a_straight_edge_offers_its_ends_and_middle() {+ let s = plate();+ let front = edge(&s, |p| p.y.abs() < 1e-9 && (p.z - 10.0).abs() < 1e-9);+ let got = snap_points(&s, &front);+ assert!(same(&of(&got, SnapKind::End), &[Vec3::new(0.0, 0.0, 10.0), Vec3::new(60.0, 0.0, 10.0)], 1e-9), "{got:?}");+ assert!(same(&of(&got, SnapKind::Middle), &[Vec3::new(30.0, 0.0, 10.0)], 1e-9), "{got:?}");+}++#[test]+fn a_flat_face_offers_the_centre_of_its_area() {+ let s = plate();+ let top = face(&s, |p| (p.z - 10.0).abs() < 1e-9);+ // The plate's area less the two holes, each holding its area at its centre.+ let (a, h6, h8) = (60.0 * 40.0, PI * 9.0, PI * 16.0);+ let x = (a * 30.0 - h6 * 15.0 - h8 * 45.0) / (a - h6 - h8);+ let got = snap_points(&s, &top);+ // The holes' circles are tessellated, so their areas are a little off.+ assert!(same(&of(&got, SnapKind::FaceCentre), &[Vec3::new(x, 20.0, 10.0)], 0.02), "want x = {x}: {got:?}");+ assert_eq!(got.len(), 1, "{got:?}");+}++#[test]+fn an_arc_offers_its_centre_ends_and_middle() {+ // A Ø20 cylinder cut at the corner (60, 40) leaves a quarter circle about it on the top.+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 60, "width": 40, "height": 10}));+ run(&mut s, "solid.cylinder", json!({"radius": 10, "height": 12, "base": [60, 40, -1], "operation": "cut"}));+ let c = Vec3::new(60.0, 40.0, 10.0);+ let arc = edge(&s, |p| (p.z - 10.0).abs() < 1e-9 && ((p - c).len() - 10.0).abs() < 1e-3);+ let got = snap_points(&s, &arc);+ assert!(same(&of(&got, SnapKind::Centre), &[c], 1e-6), "{got:?}");+ assert!(same(&of(&got, SnapKind::End), &[Vec3::new(50.0, 40.0, 10.0), Vec3::new(60.0, 30.0, 10.0)], 1e-6), "{got:?}");+ let mid = Vec3::new(60.0 - 10.0 * FRAC_1_SQRT_2, 40.0 - 10.0 * FRAC_1_SQRT_2, 10.0);+ assert!(same(&of(&got, SnapKind::Middle), &[mid], 1e-6), "the exact middle of the arc, not of its chord: {got:?}");+}++#[test]+fn a_sphere_offers_its_centre_and_a_vertex_itself() {+ let mut s = Session::default();+ run(&mut s, "solid.sphere", json!({"radius": 7, "center": [5, -3, 12]}));+ let ball = face(&s, |_| true);+ let got = snap_points(&s, &ball);+ assert_eq!(got.iter().map(|p| p.kind).collect::<Vec<_>>(), [SnapKind::Centre], "{got:?}");+ assert!(got[0].at.dist(Vec3::new(5.0, -3.0, 12.0)) < 1e-6, "{got:?}");++ let v = sel(json!({"type": "vertex", "body": "Body1", "point": [1, 2, 3]}));+ let got = snap_points(&s, &v);+ assert_eq!(got, [SnapPoint { at: Vec3::new(1.0, 2.0, 3.0), kind: SnapKind::Vertex, body: "Body1".into() }]);+}++#[test]+fn things_without_points_offer_none() {+ let s = plate();+ for v in [+ json!({"type": "body", "name": "Body1"}),+ json!({"type": "plane", "name": "XY"}),+ json!({"type": "edge", "body": "Nope", "index": 0, "point": [0, 0, 0]}),+ ] {+ assert!(snap_points(&s, &sel(v.clone())).is_empty(), "{v}");+ }+}