SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Holes from a sketch on a body's face drill that body (#2882) (#3770)
raykholo9db39f3d7ded
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rsindex 59a5ffae72..e4bcd2f851 100644--- a/crates/doc/src/eval.rs+++ b/crates/doc/src/eval.rs@@ -2634,12 +2634,13 @@ fn body_at(st: &ModelState, body: &Option<crate::BodyName>, points: &[Vec3]) ->}/// A hole stays on its face when the model changes: a position now inside a body moves back-/// against the drilling direction to the surface, one now above it moves down onto it.-fn hole_on_surface(st: &ModelState, p: Vec3, dir: Vec3) -> Vec3 {+/// against the drilling direction to the surface, one now above it moves down onto it. Only the+/// bodies in `scope` count (every body when it is empty, see [`hole_scope`]).+fn hole_on_surface(st: &ModelState, p: Vec3, dir: Vec3, scope: &[String]) -> Vec3 {let size = st.bodies.iter().map(|b| b.body.size()).fold(1.0, f64::max);let eps = size * 1e-6;let mut best: Option<Vec3> = None;- for b in &st.bodies {+ for b in st.bodies.iter().filter(|b| in_hole_scope(scope, b)) {let m = b.mesh();// Already on the surface: the drill enters right here.if let Some((t, _)) = m.raycast(p - dir * eps, dir)@@ -2920,12 +2921,12 @@ pub(crate) fn revolve_axis(ss: &SolvedSketch, axis: &AxisRef) -> Result<(Vec2, V/// Whether a drill from `p` along `d` reaches material: it starts into a body (`touches`), or,/// when `ahead` is set, a body lies further along `d`. A spot exactly on a surface counts only-/// when the drill enters there, not when it leaves.-fn hole_reaches(st: &ModelState, p: Vec3, d: Vec3, ahead: bool) -> bool {+/// when the drill enters there, not when it leaves. Only the bodies in `scope` count.+fn hole_reaches(st: &ModelState, p: Vec3, d: Vec3, ahead: bool, scope: &[String]) -> bool {let size = st.bodies.iter().map(|b| b.body.size()).fold(1.0, f64::max);let eps = size * 1e-6;let q = p + d * eps;- st.bodies.iter().any(|b| {+ st.bodies.iter().filter(|b| in_hole_scope(scope, b)).any(|b| {let m = b.mesh();m.contains(q) || (ahead && m.raycast(q, d).is_some())})@@ -2943,13 +2944,13 @@ pub fn sketch_hole_direction(st: &ModelState, sketch: u64, ids: &[String], flip:let ss = st.sketch(sketch)?;let spots: Vec<Vec3> =ids.iter().map(|id| ss.sketch.points.iter().find(|p| &p.id == id).map(|p| ss.plane.to_world(p.pos))).collect::<Option<_>>()?;- let dir = sketch_hole_dir(st, &spots, ss.plane.normal());+ let dir = sketch_hole_dir(st, &spots, ss.plane.normal(), &[]);Some(if flip { -dir } else { dir })}-fn sketch_hole_dir(st: &ModelState, spots: &[Vec3], n: Vec3) -> Vec3 {+fn sketch_hole_dir(st: &ModelState, spots: &[Vec3], n: Vec3, scope: &[String]) -> Vec3 {let down = -n;- let any = |d: Vec3, ahead: bool| spots.iter().any(|p| hole_reaches(st, *p, d, ahead));+ let any = |d: Vec3, ahead: bool| spots.iter().any(|p| hole_reaches(st, *p, d, ahead, scope));if any(down, false) {down} else if any(n, false) {@@ -2961,6 +2962,20 @@ fn sketch_hole_dir(st: &ModelState, spots: &[Vec3], n: Vec3) -> Vec3 {}}+/// The bodies a hole at sketch points finds its side and its faces on: the bodies it cuts when it+/// names them (a hole from a sketch on a body's face cuts that body, #2882), so a body further+/// along can't take the holes meant for it. Empty (every body) otherwise.+fn hole_scope(f: &Feature) -> &[String] {+ match &f.kind {+ FeatureKind::Hole { points: Some(sp), .. } if !sp.single && !f.participants.iter().any(|b| b == "*") => &f.participants,+ _ => &[],+ }+}++fn in_hole_scope(scope: &[String], b: &ModelBody) -> bool {+ scope.is_empty() || scope.contains(&b.name)+}+/// Where a hole feature drills (each on the surface) and in which direction: at its sketch/// points perpendicular to the sketch (into the material), else at its position.fn hole_spots(vals: &BTreeMap<String, Value>, st: &ModelState, f: &Feature) -> Result<(Vec<Vec3>, Vec3)> {@@ -2974,21 +2989,21 @@ fn hole_spots(vals: &BTreeMap<String, Value>, st: &ModelState, f: &Feature) -> Rlet p = ss.sketch.points.iter().find(|p| &p.id == id).ok_or_else(|| DocError::Unknown(format!("sketch point `{id}`")))?;v.push(ss.plane.to_world(p.pos));}- let dir = sketch_hole_dir(st, &v, ss.plane.normal());+ let dir = sketch_hole_dir(st, &v, ss.plane.normal(), hole_scope(f));let dir = if sp.flip { -dir } else { dir };(v, dir)}_ => {let dir = direction.normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?;- let at = hole_on_surface(st, single_hole_position(vals, st, position, at, points)?, dir);+ let at = hole_on_surface(st, single_hole_position(vals, st, position, at, points)?, dir, &[]);let dir = hole_dir_into_face(st, at, dir);- return Ok((vec![hole_on_surface(st, at, dir)], dir));+ return Ok((vec![hole_on_surface(st, at, dir, &[])], dir));}};if spots.is_empty() || spots.len() > 10_000 {return Err(DocError::Invalid("a hole needs 1…10000 points".into()));}- Ok((spots.into_iter().map(|p| hole_on_surface(st, p, dir)).collect(), dir))+ Ok((spots.into_iter().map(|p| hole_on_surface(st, p, dir, hole_scope(f))).collect(), dir))}/// A hole's depth: down to the To Object (where the hole's axis meets the face there, else the@@ -3021,14 +3036,14 @@ fn hole_spots_raw(vals: &BTreeMap<String, Value>, st: &ModelState, f: &Feature)let ss = st.sketch(sp.sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {}", sp.sketch)))?;let v: Vec<Vec3> =sp.ids.iter().filter_map(|id| ss.sketch.points.iter().find(|p| &p.id == id)).map(|p| ss.plane.to_world(p.pos)).take(10_000).collect();- let dir = sketch_hole_dir(st, &v, ss.plane.normal());+ let dir = sketch_hole_dir(st, &v, ss.plane.normal(), hole_scope(f));let dir = if sp.flip { -dir } else { dir };Ok((v, dir))}_ => {let dir = direction.normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?;let p = single_hole_position(vals, st, position, at, points)?;- Ok((vec![p], hole_dir_into_face(st, hole_on_surface(st, p, dir), dir)))+ Ok((vec![p], hole_dir_into_face(st, hole_on_surface(st, p, dir, &[]), dir)))}}}@@ -4822,7 +4837,7 @@ fn replay(for (k, m) in mats.iter().enumerate() {let d = crate::apply_vector(m, dir).normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?;for p in &spots {- let at = hole_on_surface(st, crate::apply_point(m, *p), d);+ let at = hole_on_surface(st, crate::apply_point(m, *p), d, hole_scope(src));let to = to.map(|t| crate::apply_point(m, t.0));let depth = hole_depth_to(st, &at, d, &to, depth)?;// Each copy's faces are named as the hole's, with the instance.diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rsindex 51c5ad8fc6..9c26734ad9 100644--- a/crates/engine/src/cmd/features.rs+++ b/crates/engine/src/cmd/features.rs@@ -68,7 +68,7 @@ pub static COMMANDS: &[CommandSpec] = &[.at("SOLID", "CREATE").icon("hole").key("H")- .params("position: [x,y,z] on a face (numbers, or length expressions the hole follows) | sketch + points: [sketch point ids] (one hole each, perpendicular to the sketch, into the material on whichever side of the sketch plane it is) | sketch alone (every sketch point: standalone points and circle centres); flip?: bool (sketch points: drill to the other side); single?: bool (with one sketch point: a Single hole that follows the point, drilled into the face there); direction?: [x,y,z] (default: into the face, against its outward normal; one that leaves the face is mirrored into it; ignored with sketch points unless single); diameter | thread (a tapped hole: the tap drill, major − pitch) | clearance: \"M6\" with fit?: close|normal|loose (ISO 273); depth? (default through all) | to?: [x,y,z] (To Object: drill to that face or point); type?: simple|drilled|counterbore|countersink; tip_angle?; cb_diameter?, cb_depth?; cs_diameter?, cs_angle?; thread?: \"M6\" (cosmetic)"),+ .params("position: [x,y,z] on a face (numbers, or length expressions the hole follows) | sketch + points: [sketch point ids] (one hole each, perpendicular to the sketch, into the material on whichever side of the sketch plane it is) | sketch alone (every sketch point: standalone points and circle centres); flip?: bool (sketch points: drill to the other side); single?: bool (with one sketch point: a Single hole that follows the point, drilled into the face there); direction?: [x,y,z] (default: into the face, against its outward normal; one that leaves the face is mirrored into it; ignored with sketch points unless single); diameter | thread (a tapped hole: the tap drill, major − pitch) | clearance: \"M6\" with fit?: close|normal|loose (ISO 273); depth? (default through all) | to?: [x,y,z] (To Object: drill to that face or point); type?: simple|drilled|counterbore|countersink; tip_angle?; cb_diameter?, cb_depth?; cs_diameter?, cs_angle?; thread?: \"M6\" (cosmetic); targets?: [body] (the bodies to drill; holes at the points of a sketch on a body's face default to that body, found along the holes' direction on it alone; explicit targets or participants override, [\"*\"] every body)"),CommandSpec::new("solid.pipe", "Pipe", pipe).at("SOLID", "CREATE").icon("pipe")@@ -1853,15 +1853,25 @@ fn hole(s: &mut Session, p: &Value) -> Result<Value> {Some(v) => Some(vec3(v).ok_or_else(|| bad(cmd, "`to` must be a point [x, y, z] on the face to drill to"))?),None => None,};- // A hole picked on a body of another component (a moved one, shown where it is placed) cuts- // that body: the pick is already in that body's frame, and the component's own bodies alone- // would leave nothing to cut.let mut p = p.clone();- if points.is_none()- && p.get("participants").is_none()- && let Some(body) = body_of_other_component_at(s, position)- {- p["participants"] = json!([body]);+ let targets = string_list(&p, "targets");+ if p.get("participants").is_none() {+ // The bodies to drill, as `targets` (like an extrude's): its participants.+ if !targets.is_empty() {+ p["participants"] = json!(targets);+ } else if let Some(body) = points.as_ref().filter(|(sp, _, _)| !sp.single).and_then(|(sp, _, _)| sketch_face_body(s, sp.sketch.0)) {+ // Holes at the points of a sketch on a body's face drill that body (#2882): a body+ // further along, past the face, doesn't take them. Stored, so recomputes and+ // reopening keep the same scope.+ p["participants"] = json!([body]);+ } else if points.is_none()+ && let Some(body) = body_of_other_component_at(s, position)+ {+ // A hole picked on a body of another component (a moved one, shown where it is+ // placed) cuts that body: the pick is already in that body's frame, and the+ // component's own bodies alone would leave nothing to cut.+ p["participants"] = json!([body]);+ }}add_feature(s,diff --git a/crates/engine/src/hole_face_tests.rs b/crates/engine/src/hole_face_tests.rsindex ededdd4314..582a712538 100644--- a/crates/engine/src/hole_face_tests.rs+++ b/crates/engine/src/hole_face_tests.rs@@ -374,3 +374,44 @@ fn drilled_sketch_points_break_through_a_sloping_back_face() {assert!(reopened.model.result(id).unwrap().error.is_none());near(volume(&mut reopened), left);}++/// Back (z 0…6) under a smaller Front (z 14…20), and a sketch on Front's top face with points+/// over Front (`in`) and beyond its edges, over Back (`out1`, `out2`).+fn front_and_back(s: &mut Session) {+ run(s, "solid.box", json!({"length": 40, "width": 40, "height": 6, "body_name": "Back"}));+ run(s, "solid.box", json!({"corner": [10, 10, 14], "length": 20, "width": 20, "height": 6, "body_name": "Front"}));+ run(s, "sketch.create", json!({"plane": {"face": [20, 20, 20]}, "name": "Pts", "project_edges": false}));+ for (id, p) in [("in", [20, 20]), ("out1", [5, 5]), ("out2", [35, 35])] {+ run(s, "sketch.point", json!({"point": p, "id": id}));+ }+ run(s, "sketch.finish", json!({}));+}++/// #2882: holes at the points of a sketch on a body's face drill that body, never one behind it.+#[test]+fn holes_from_a_sketch_on_a_face_drill_that_body_only() {+ let mut s = Session::default();+ front_and_back(&mut s);+ let base = volume(&mut s);+ run(&mut s, "solid.hole", json!({"sketch": "Pts", "points": ["in", "out1", "out2"], "diameter": 5, "depth": 4, "name": "H"}));+ assert_eq!(s.doc.find_feature("H").unwrap().participants, vec!["Front".to_string()]);+ near(base - volume(&mut s), pi() * 6.25 * 4.0);+ assert!(!solid_at(&s, 20.0, 20.0, 18.0), "drilled into Front");+ for (x, y) in [(5.0, 5.0), (35.0, 35.0), (20.0, 20.0)] {+ assert!(solid_at(&s, x, y, 5.5) && solid_at(&s, x, y, 3.0), "Back is not drilled at ({x}, {y})");+ }+ let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());+ near(base - volume(&mut reopened), pi() * 6.25 * 4.0);+}++/// Through all from Front's face stops at Front; `targets` picks another body to drill instead.+#[test]+fn face_sketch_holes_through_all_stay_in_their_body_unless_targets_say_otherwise() {+ let mut s = Session::default();+ front_and_back(&mut s);+ run(&mut s, "solid.hole", json!({"sketch": "Pts", "points": ["in"], "diameter": 5, "name": "H"}));+ assert!(!solid_at(&s, 20.0, 20.0, 15.0) && solid_at(&s, 20.0, 20.0, 3.0));+ run(&mut s, "edit.undo", json!({}));+ run(&mut s, "solid.hole", json!({"sketch": "Pts", "points": ["in"], "diameter": 5, "targets": ["Back"], "name": "H"}));+ assert!(solid_at(&s, 20.0, 20.0, 15.0) && !solid_at(&s, 20.0, 20.0, 3.0));+}