SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Hole: place a Single hole by distances from reference edges (#37) (#2931)
Jacques807e367bdb03
diff --git a/ROADMAP.md b/ROADMAP.mdindex fb2ec29fcb..01168c25b2 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -51,7 +51,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings.|---|---|---|---|| M0 | Vertical slice | done | — || M1 | Sketch depth: command coverage implemented — projection/intersect/include as linked geometry (auto-project on faces, lost-reference warnings, break link), full SKETCH create/modify set (slots, polygons, tangent arcs/circles, ellipse, fit/control splines, conic, text, trim/extend/break, fillet/chamfer, offset, mirror, patterns, move/scale, blend curve, centerline), constraints incl. curvature and polygon with over-constraint refusal, Shift-picked line midpoints in Horizontal/Vertical using persisted points and ordinary constraints (#2087), driven/arc-length/linear-diameter dimensions, AutoConstrain, DXF/SVG insert, 3D sketch curves (Project To Surface, Intersection Curve, Isoparametric Curve, Spun Profile), exact free-form profiles (B-spline/NURBS edges, any spline degree, curves cut by crossings), sweeps and pipes along 3D sketch curves, canvases and decals, curvature combs. Exact free-form Extend and certified associative offsets now preserve geometry and IDs through edits, deletion and reopen. Occurrence-frame 3D wires now store explicit coordinate spaces and retain points and analytic fits through moves, refresh, undo and reopen. Constructive sketch solving (Owen 1991, Fudos & Hoffmann 1997) ahead of the numerical solver: points and rigid clusters are placed on the branch the sketch had, so dimension edits and drags keep their solution; edits that would turn a sketch over are refused; drags re-solve only the sketch per frame. Remaining workflow repairs: mixed offset junctions, legacy natural-spline seams, and damaged legacy wire links lacking frame provenance | in progress | 4 |-| M2 | Robust modelling: coplanar booleans in the kernel, holes (placed on faces and on sketch points), threads (cosmetic, then modelled), patterns, mirror, shell, draft, split, construction geometry | in progress | 16 |+| M2 | Robust modelling: coplanar booleans in the kernel, holes (placed on faces, at distances from reference edges, and on sketch points), threads (cosmetic, then modelled), patterns, mirror, shell, draft, split, construction geometry | in progress | 16 || M3 | General fillets and chamfers (curved edges, chains, vertex blends); saddle rolling-ball surfaces now use continuous seam sections and arc-length fitting with shared contact boundaries and bounded accuracy checks; tiny rim edges remain selected instead of nearby wall seams when filleting (#2498) | in progress | 30 || M4 | Files: STEP import (done — [docs/step-import.md](docs/step-import.md)), FreeCAD/Rhino solids through cadmpeg (done, desktop, browser and CLI), 3MF export and 3MF/STL import as mesh bodies (done), 3MF with B-rep face tags ([docs/formats/3mf-face-tags.md](docs/formats/3mf-face-tags.md), done), constant-section parametric mesh reconstruction, DXF sketches, OBJ import | in progress | 6 || M5 | Persistent naming of faces and edges (docs/book/src/dev/naming.md): faces named from their exact kernel-reported history (sketch curve sides, caps, revolve sections, primitive sides, blends, shell inner walls, pattern/mirror copies; split pieces told apart by the faces around them, lumps of a cut body named after their faces), edges by their faces; fillets/chamfers, sketches on faces, shell/draft/offset/replace faces, hole placements, joint origins and face appearances resolve by name first and warn when the entity split or vanished: done. sheet metal edges by base sketch line and flange side, shell inner faces, sweep and loft roles: done. kernel-reported face history: done (merged faces answer to every name; operations without history yet fall back to geometric names, flagged unverified; format 14 keeps older designs' geometric names). Left: history through sheet metal, plastic, surface and emboss features; FaceSource certificates through history | in progress | 20 |diff --git a/assets/locales/en.json b/assets/locales/en.jsonindex ce1d7ded51..01d97b986c 100644--- a/assets/locales/en.json+++ b/assets/locales/en.json@@ -2189,6 +2189,9 @@"ui.rectangle": "Rectangle","ui.rectangular_pattern": "Rectangular Pattern","ui.redo": "Redo",+ "ui.reference_1": "Reference 1",+ "ui.reference_2": "Reference 2",+ "ui.reference_distance": "Reference distance","ui.relink_design_changed": "The assembly changed while choosing a source. Start Relink Source again.","ui.relink_done": "Source relinked for all instances.","ui.relink_not_linked": "This component is not linked to a source design.",diff --git a/assets/locales/ja.json b/assets/locales/ja.jsonindex 0e9e8fdfa4..9e77c1425e 100644--- a/assets/locales/ja.json+++ b/assets/locales/ja.json@@ -2189,6 +2189,9 @@"ui.rectangle": "長方形","ui.rectangular_pattern": "矩形パターン","ui.redo": "やり直す",+ "ui.reference_1": "参照 1",+ "ui.reference_2": "参照 2",+ "ui.reference_distance": "参照からの距離","ui.relink_design_changed": "参照元の選択中にアセンブリが変更されました。再リンクをやり直してください。","ui.relink_done": "すべてのインスタンスの参照元を再リンクしました。","ui.relink_not_linked": "このコンポーネントは参照元の設計にリンクされていません。",diff --git a/assets/locales/zh.json b/assets/locales/zh.jsonindex c653ed5af6..8807322cb6 100644--- a/assets/locales/zh.json+++ b/assets/locales/zh.json@@ -2189,6 +2189,9 @@"ui.rectangle": "矩形","ui.rectangular_pattern": "矩形阵列","ui.redo": "重做",+ "ui.reference_1": "参考 1",+ "ui.reference_2": "参考 2",+ "ui.reference_distance": "参考距离","ui.relink_design_changed": "选择源文件时装配已更改。请重新开始链接。","ui.relink_done": "已为所有实例重新链接源文件。","ui.relink_not_linked": "此组件未链接到源设计。",diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rsindex 836ef63229..32327ddd26 100644--- a/crates/doc/src/document.rs+++ b/crates/doc/src/document.rs@@ -724,6 +724,11 @@ pub enum FeatureKind {/// To Object: drill down to the face (or point) here instead of `depth`.#[serde(default, skip_serializing_if = "Option::is_none")]to: Option<FacePick>,+ /// Up to two straight edges of the face (#37): the hole's centre sits at each one's+ /// distance from its edge, measured in the face's plane, and follows the edges when the+ /// part changes. `position` keeps where it was placed.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ references: Vec<HoleReference>,},/// A thread on a cylindrical face. Cosmetic by default (no geometry change; drawn and/// exported as an annotation); `modeled` cuts the real helical ISO profile into the face.@@ -2019,6 +2024,15 @@ pub enum HoleKind {},}+/// A Single hole's reference edge (#37): a point on a straight edge of the hole's face, and the+/// distance of the hole's centre from that edge's line, in the face's plane.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)]+pub struct HoleReference {+ pub edge: Position,+ #[walk(length = "Reference distance")]+ pub distance: Expr,+}+/// Pattern layouts.#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)]#[serde(tag = "type", rename_all = "snake_case")]diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rsindex 3694e234bf..40dbac3ce7 100644--- a/crates/doc/src/eval.rs+++ b/crates/doc/src/eval.rs@@ -3651,6 +3651,7 @@ fn hole_spots(vals: &BTreeMap<String, Value>, st: &ModelState, f: &Feature) -> R_ => {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 = with_references(vals, st, f, at, dir)?;let dir = hole_dir_into_face(st, at, dir);return Ok((vec![hole_on_surface(st, at, dir, &[])], dir));}@@ -3698,6 +3699,7 @@ fn hole_spots_raw(vals: &BTreeMap<String, Value>, st: &ModelState, f: &Feature)_ => {let dir = direction.normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?;let p = single_hole_position(vals, st, position, at, points)?;+ let p = if hole_references(f).is_empty() { p } else { with_references(vals, st, f, hole_on_surface(st, p, dir, &[]), dir)? };Ok((vec![p], hole_dir_into_face(st, hole_on_surface(st, p, dir, &[]), dir)))}}@@ -3719,6 +3721,35 @@ fn single_hole_position(Ok(ss.plane.to_world(p.pos))}+/// A hole's reference edges (#37); none for any other feature.+fn hole_references(f: &Feature) -> &[crate::HoleReference] {+ match &f.kind {+ FeatureKind::Hole { references, .. } => references,+ _ => &[],+ }+}++/// Where a Single hole with reference edges (#37) is drilled: at its distances from the edges'+/// lines, in the plane of the face at `at` (on the surface), the edges found by their names, else+/// their points. A hole without reference edges stays at `at`.+fn with_references(vals: &BTreeMap<String, Value>, st: &ModelState, f: &Feature, at: Vec3, dir: Vec3) -> Result<Vec3> {+ let references = hole_references(f);+ if references.is_empty() {+ return Ok(at);+ }+ let mut distances = Vec::with_capacity(references.len());+ for r in references {+ distances.push(Document::eval_in(vals, &r.distance, Kind::Length)?);+ }+ let edges: Vec<(Vec3, Option<&str>)> = references.iter().enumerate().map(|(i, r)| (r.edge.0, f.edge_names.get(i).map(String::as_str))).collect();+ let frame = crate::hole_reference::reference_frame(st, at, dir, &edges, false)?;+ let centre = frame.place(at, &distances)?;+ if !crate::hole_reference::on_reference_face(st, &frame, centre) {+ return Err(DocError::Invalid("the reference distances put the hole's centre off its face".into()));+ }+ Ok(centre)+}+/// Where a hole placed by position is drilled: its `at` expressions evaluated, so it follows the/// parameters (#1678), else the point it was given.fn hole_position(vals: &BTreeMap<String, Value>, position: &crate::FacePick, at: &Option<crate::PointExpr>) -> Result<Vec3> {diff --git a/crates/doc/src/feature_walk_tests/fixtures.rs b/crates/doc/src/feature_walk_tests/fixtures.rsindex 60812e46c5..651576f648 100644--- a/crates/doc/src/feature_walk_tests/fixtures.rs+++ b/crates/doc/src/feature_walk_tests/fixtures.rs@@ -72,6 +72,11 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> {("hole_drilled", hole(json!({"type": "drilled", "tip_angle": "hole.tip_angle"}))),("hole_counterbore", hole(json!({"type": "counterbore", "cb_diameter": "hole.cb_diameter", "cb_depth": "hole.cb_depth"}))),("hole_countersink", hole(json!({"type": "countersink", "cs_diameter": "hole.cs_diameter", "cs_angle": "hole.cs_angle"}))),+ ("hole_references", {+ let mut h = hole(json!({"type": "simple"}));+ h["references"] = json!([{"edge": o, "distance": "hole.reference1"}, {"edge": o, "distance": "hole.reference2"}]);+ h+ }),("thread", json!({"type": "thread", "face": o, "length": "thread.length"})),("loft", json!({"type": "loft", "sections": []})),("sweep", json!({"type": "sweep", "sketch": 1, "profiles": {"type": "all"}, "path_sketch": 2, "path": ["l1"]})),@@ -272,6 +277,9 @@ pub(super) fn with_points(name: &str, mut v: Value) -> Value {"surface_revolve" => json!({"axis": line}),"hole_simple" => json!({"points": null, "to": p(4.0)}),"hole_drilled" | "hole_counterbore" | "hole_countersink" => json!({"to": p(4.0)}),+ "hole_references" => {+ json!({"references": [{"edge": p(11.0), "distance": "hole.reference1"}, {"edge": p(12.0), "distance": "hole.reference2"}]})+ }"emboss" => json!({"face": {"body": "B", "at": p(5.0)}}),"sheet_convert" => json!({"bends": [p(6.0)]}),"sheet_fold" => json!({"fixed": p(7.0)}),diff --git a/crates/doc/src/feature_walk_tests/golden_exprs.txt b/crates/doc/src/feature_walk_tests/golden_exprs.txtindex cd30f9340d..ff4ba3a820 100644--- a/crates/doc/src/feature_walk_tests/golden_exprs.txt+++ b/crates/doc/src/feature_walk_tests/golden_exprs.txt@@ -130,6 +130,13 @@ hole_countersinkCountersink diameter = hole.cs_diameter (Length)Countersink angle = hole.cs_angle (Angle)expressions: hole.diameter, hole.depth, hole.cs_diameter, hole.cs_angle+hole_references+ inputs:+ Diameter = hole.diameter (Length)+ Depth = hole.depth (Length)+ Reference distance = hole.reference1 (Length)+ Reference distance = hole.reference2 (Length)+ expressions: hole.diameter, hole.depth, hole.reference1, hole.reference2threadinputs:Length = thread.length (Length)diff --git a/crates/doc/src/feature_walk_tests/golden_geometry.txt b/crates/doc/src/feature_walk_tests/golden_geometry.txtindex 61c14aa7f0..f33a46bfa0 100644--- a/crates/doc/src/feature_walk_tests/golden_geometry.txt+++ b/crates/doc/src/feature_walk_tests/golden_geometry.txt@@ -56,6 +56,9 @@ hole_counterborehole_countersinkmoves: direction[0], direction[2], position[0], position[1], position[2], to[0], to[1], to[2]face points: [4, 4.5, 4.25]+hole_references+ moves: direction[0], direction[2], position[0], position[1], position[2], references[0].edge[0], references[0].edge[1], references[0].edge[2], references[1].edge[0], references[1].edge[1], references[1].edge[2]+ face points: [0, 0, 0]threadmoves: face[0], face[1], face[2]face points: [0, 0, 0]diff --git a/crates/doc/src/feature_walk_tests/golden_refs.txt b/crates/doc/src/feature_walk_tests/golden_refs.txtindex 6871a9968d..8f30912bf3 100644--- a/crates/doc/src/feature_walk_tests/golden_refs.txt+++ b/crates/doc/src/feature_walk_tests/golden_refs.txt@@ -58,6 +58,7 @@ hole_counterborehole_countersinksketches: [3]remap_refs: points.sketch+hole_referencesthreadloftsketches: [4, 5, 6]diff --git a/crates/doc/src/format/pending/hole-reference-edges.rs b/crates/doc/src/format/pending/hole-reference-edges.rsnew file mode 100644index 0000000000..9a51c1e450--- /dev/null+++ b/crates/doc/src/format/pending/hole-reference-edges.rs@@ -0,0 +1,6 @@+//! A Single hole can be placed by distances from up to two straight edges of its face+//! (`references`: each `{"edge": [x, y, z], "distance": "…"}`, the edges' persistent names in the+//! feature's `edge_names`, #37): it is drilled where those distances hold, measured in the face's+//! plane, and follows the edges when the part changes. Older designs need no transformation: a+//! hole without `references` stays at its position, as before; 0.21.x asks for an update instead+//! of drilling a referenced hole where it was first placed.diff --git a/crates/doc/src/hole_reference.rs b/crates/doc/src/hole_reference.rsnew file mode 100644index 0000000000..187a1971f7--- /dev/null+++ b/crates/doc/src/hole_reference.rs@@ -0,0 +1,251 @@+//! A Single hole placed by distances from reference edges (#37): up to two straight edges of the+//! face it is drilled into, each with the distance of the hole's centre from that edge's line,+//! measured in the face's plane. The edges are found again by their persistent names, else by+//! their stored points, so the hole follows them when the part changes.++use solidcraft_geom::{Mesh, Vec3};++use crate::{DocError, ModelBody, ModelState, Result};++/// The most reference edges a hole takes.+pub const MAX_HOLE_REFERENCES: usize = 2;++/// A reference edge's line in the face's plane.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct ReferenceLine {+ /// A point on the line: the edge's middle, moved into the face's plane.+ pub point: Vec3,+ /// Along the edge (unit).+ pub along: Vec3,+ /// In the plane, square to the edge, toward the side the face is on (unit): the way the+ /// distance grows.+ pub toward: Vec3,+}++impl ReferenceLine {+ /// How far `p` is from the line, toward the face's side (negative on the other side).+ pub fn distance(&self, p: Vec3) -> f64 {+ (p - self.point).dot(self.toward)+ }++ /// The point of the line nearest `p`.+ pub fn foot(&self, p: Vec3) -> Vec3 {+ self.point + self.along * (p - self.point).dot(self.along)+ }+}++/// The face a referenced hole is drilled into (its plane) and its reference edges' lines.+#[derive(Clone, Debug, PartialEq)]+pub struct ReferenceFrame {+ /// The body and the face (its index).+ pub body: String,+ pub face: usize,+ /// A point on the face's plane.+ pub origin: Vec3,+ /// The face's outward unit normal.+ pub normal: Vec3,+ pub lines: Vec<ReferenceLine>,+ /// The reference edges found (their indices in the body's mesh), one per line.+ pub edges: Vec<usize>,+}++impl ReferenceFrame {+ /// `p` moved square onto the face's plane.+ pub fn onto_plane(&self, p: Vec3) -> Vec3 {+ p - self.normal * (p - self.origin).dot(self.normal)+ }++ /// How far `p` is from each line (see [`ReferenceLine::distance`]).+ pub fn distances(&self, p: Vec3) -> Vec<f64> {+ let p = self.onto_plane(p);+ self.lines.iter().map(|l| l.distance(p)).collect()+ }++ /// The hole's centre at `distances` (one per line) from the lines, in the face's plane. With+ /// one line, `near` moves square to it (it keeps its place along the edge); with two, the+ /// centre is where both distances hold.+ pub fn place(&self, near: Vec3, distances: &[f64]) -> Result<Vec3> {+ if let Some((i, _)) = distances.iter().enumerate().find(|(_, d)| !(d.is_finite() && **d >= 0.0 && **d < 1e9)) {+ return Err(DocError::Invalid(format!("reference distance {} must be a length of 0 or more", i + 1)));+ }+ let p = self.onto_plane(near);+ match (self.lines.as_slice(), distances) {+ ([], []) => Ok(p),+ ([a], [d]) => Ok(p + a.toward * (d - a.distance(p))),+ ([a, b], [d1, d2]) => {+ // p + r1 * a.toward + s * e2, with e2 square to a in the plane: a's distance is+ // then d1, and s gives b's.+ let (r1, r2) = (d1 - a.distance(p), d2 - b.distance(p));+ let e2 = self.normal.cross(a.toward);+ let across = b.toward.dot(e2);+ if across.abs() < 1e-6 {+ return Err(DocError::Invalid("the reference edges are parallel: pick edges that cross".into()));+ }+ Ok(p + a.toward * r1 + e2 * ((r2 - r1 * a.toward.dot(b.toward)) / across))+ }+ _ => Err(DocError::Invalid("a hole takes one distance for each reference edge".into())),+ }+ }+}++/// The reference frame of a hole placed at `at` (on the surface), drilled along `dir` (into the+/// material), from its reference edges: a point on each edge and, when it has one, the edge's+/// persistent name. A fresh pick (`exact`) must lie on its edge; a stored one is found by its+/// name, else the edge nearest its point. The face is the flat face under `at` that faces the+/// drill, else the one the edges border.+pub fn reference_frame(st: &ModelState, at: Vec3, dir: Vec3, edges: &[(Vec3, Option<&str>)], exact: bool) -> Result<ReferenceFrame> {+ if edges.len() > MAX_HOLE_REFERENCES {+ return Err(DocError::Invalid(format!("a hole takes at most {MAX_HOLE_REFERENCES} reference edges")));+ }+ let dir = dir.normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?;+ if !at.is_finite() || edges.iter().any(|(p, _)| !p.is_finite()) {+ return Err(DocError::Invalid("reference edges need finite points".into()));+ }+ let b = body_at(st, at).ok_or_else(|| DocError::Invalid("no body at the hole for its reference edges".into()))?;+ let m = b.mesh();+ let size = b.body.size().max(1e-9);+ let mut found = Vec::with_capacity(edges.len());+ for (k, (p, name)) in edges.iter().enumerate() {+ found.push(find_edge(b, &m, k, *p, *name, exact)?);+ }+ let (face, origin, normal) = flat_face(b, &m, at, dir, &found).ok_or_else(|| {+ DocError::Invalid("reference edges need the hole on a flat face: no flat face facing the drill at the hole or along its edges".into())+ })?;+ let mut lines = Vec::with_capacity(found.len());+ for (k, (a, z, _)) in found.iter().enumerate() {+ let flat = |q: Vec3| q - normal * (q - origin).dot(normal);+ let (a, z) = (flat(*a), flat(*z));+ let along = (z - a).normalized().ok_or_else(|| DocError::Invalid(format!("reference edge {} is square to the face", k + 1)))?;+ let across = normal.cross(along).normalized().ok_or_else(|| DocError::Invalid(format!("reference edge {} is square to the face", k + 1)))?;+ let mid = (a + z) * 0.5;+ // The side the face is on next to the edge; an edge the face doesn't border (or borders+ // on both sides) takes the side the hole is on.+ let side = face_side(&m, face, mid, across, normal, size).unwrap_or_else(|| if (at - mid).dot(across) < 0.0 { -1.0 } else { 1.0 });+ lines.push(ReferenceLine { point: mid, along, toward: across * side });+ }+ if let [a, b] = lines.as_slice()+ && a.along.cross(b.along).len() < 1e-6+ {+ return Err(DocError::Invalid("the reference edges are parallel: pick edges that cross".into()));+ }+ Ok(ReferenceFrame { body: b.name.clone(), face, origin, normal, lines, edges: found.iter().map(|(_, _, i)| *i).collect() })+}++/// Whether `p` lies on the flat face a reference frame was made for.+pub fn on_reference_face(st: &ModelState, frame: &ReferenceFrame, p: Vec3) -> bool {+ let Some(b) = st.bodies.iter().find(|b| b.name == frame.body) else { return false };+ let m = b.mesh();+ let tol = (b.body.size() * 1e-4).max(1e-6);+ m.triangles+ .iter()+ .zip(&m.tri_face)+ .filter(|(_, f)| **f as usize == frame.face)+ .any(|(t, _)| m.tri(t).is_some_and(|[a, bb, c]| crate::appearance::closest_on_triangle(p, a, bb, c).dist(p) <= tol))+}++/// The persistent names of the edges at `edges`, on the body the hole at `at` is drilled into+/// (empty where an edge has none).+pub fn reference_edge_names(st: &ModelState, at: Vec3, edges: &[Vec3]) -> Vec<String> {+ match body_at(st, at) {+ Some(b) => crate::naming::edge_names_at(b, edges),+ None => Vec::new(),+ }+}++/// The (non-mesh) body whose surface is nearest `p`.+fn body_at(st: &ModelState, p: Vec3) -> Option<&ModelBody> {+ st.bodies+ .iter()+ .filter(|b| !b.body.is_mesh())+ .filter_map(|b| crate::appearance::nearest_face(b, p).map(|(d, _)| (d, b)))+ .min_by(|a, b| a.0.total_cmp(&b.0))+ .map(|(_, b)| b)+}++/// How far `p` is from an edge's polyline.+fn to_polyline(p: Vec3, e: &[Vec3]) -> f64 {+ e.windows(2).map(|w| p.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min)+}++/// Reference edge `k` (its ends, and its index in the mesh), found by `name`, else by the edge+/// nearest `p`: one that runs through `p` for a fresh pick, within a quarter of the body for a+/// stored one. It must be straight.+fn find_edge(b: &ModelBody, m: &Mesh, k: usize, p: Vec3, name: Option<&str>, exact: bool) -> Result<(Vec3, Vec3, usize)> {+ let size = b.body.size().max(1e-9);+ let by_name = name.filter(|n| !n.is_empty()).and_then(|n| crate::naming::locate_edge(b, n, p).ok()).map(|hit| hit.edge);+ let i = match by_name {+ Some(i) => i,+ None => {+ let reach = if exact { (size * 1e-2).max(1e-3) } else { size * 0.25 };+ m.edges+ .iter()+ .enumerate()+ .map(|(i, e)| (to_polyline(p, e), i))+ .filter(|(d, _)| d.is_finite())+ .min_by(|a, b| a.0.total_cmp(&b.0))+ .filter(|(d, _)| *d <= reach)+ .map(|(_, i)| i)+ .ok_or_else(|| {+ DocError::Invalid(if exact {+ format!("reference edge {}: no edge at [{}, {}, {}]", k + 1, p.x, p.y, p.z)+ } else {+ format!("reference edge {} no longer exists", k + 1)+ })+ })?+ }+ };+ let e = m.edges.get(i).ok_or_else(|| DocError::Invalid(format!("reference edge {} no longer exists", k + 1)))?;+ let (Some(a), Some(z)) = (e.first().copied(), e.last().copied()) else {+ return Err(DocError::Invalid(format!("reference edge {} no longer exists", k + 1)));+ };+ let len = a.dist(z);+ let straight = len > size * 1e-9 && e.iter().all(|q| q.dist_to_segment(a, z) <= 1e-5 * (1.0 + len));+ if !straight {+ return Err(DocError::Invalid(format!("reference edge {} is not straight: pick a straight edge", k + 1)));+ }+ Ok((a, z, i))+}++/// The flat face a referenced hole goes into (its index, a point on it and its outward normal):+/// the one under `at` when it faces the drill, else the one the edges border that faces it most.+fn flat_face(b: &ModelBody, m: &Mesh, at: Vec3, dir: Vec3, edges: &[(Vec3, Vec3, usize)]) -> Option<(usize, Vec3, Vec3)> {+ let size = b.body.size().max(1e-9);+ let plane = |f: usize| match crate::kernel::face_surface(&b.body, f) {+ // Outward, so against the drill.+ Some(crate::kernel::FaceSurface::Plane { normal, point }) => {+ let normal: Vec3 = normal.into();+ let n = if normal.dot(dir) > 0.0 { -normal } else { normal };+ (n.dot(dir) < -1e-3).then_some((f, point, n))+ }+ _ => None,+ };+ if let Some((d, f)) = crate::appearance::nearest_face(b, at)+ && d <= (size * 1e-4).max(1e-6)+ && let Some(hit) = plane(f)+ {+ return Some(hit);+ }+ // The faces every edge borders.+ let mut faces: Vec<usize> =+ edges.first().and_then(|(_, _, i)| m.edge_faces.get(*i)).map(|fs| fs.iter().map(|f| *f as usize).collect()).unwrap_or_default();+ for (_, _, i) in edges.iter().skip(1) {+ let theirs = m.edge_faces.get(*i).map(Vec::as_slice).unwrap_or(&[]);+ faces.retain(|f| theirs.iter().any(|g| *g as usize == *f));+ }+ faces.into_iter().filter_map(plane).min_by(|x, y| x.2.dot(dir).total_cmp(&y.2.dot(dir)))+}++/// Which side of an edge (through `mid`, square to it in the plane along `across`) face `face`+/// lies on: +1 or −1, or `None` when both sides or neither are that face.+fn face_side(m: &Mesh, face: usize, mid: Vec3, across: Vec3, normal: Vec3, size: f64) -> Option<f64> {+ let step = (size * 1e-3).max(1e-6);+ let lands = |s: f64| {+ let from = mid + across * (s * step) + normal * step;+ m.raycast(from, -normal).is_some_and(|(t, tri)| t <= 2.0 * step && m.tri_face.get(tri).is_some_and(|f| *f as usize == face))+ };+ match (lands(1.0), lands(-1.0)) {+ (true, false) => Some(1.0),+ (false, true) => Some(-1.0),+ _ => None,+ }+}diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rsindex b2e57d3bea..8c35170918 100644--- a/crates/doc/src/lib.rs+++ b/crates/doc/src/lib.rs@@ -31,6 +31,7 @@ pub mod format;mod format_offsets;pub mod frame;mod history_names;+pub mod hole_reference;pub use format_offsets::whole_profile_selection_from_value;pub mod joints;mod lineage;diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rsindex ee475be191..fc60ed31e9 100644--- a/crates/engine/src/cmd/edit.rs+++ b/crates/engine/src/cmd/edit.rs@@ -1037,6 +1037,13 @@ fn edit_feature(s: &mut Session, p: &Value) -> Result<Value> {nf.edge_names = solidcraft_doc::sheet::sheet_edge_names(&s.model.state_before(id), &solidcraft_doc::plain(&points(a)));}}+ // New reference edges for a hole (#37): the names of the edges there now.+ if let (FeatureKind::Hole { references: a, position, .. }, FeatureKind::Hole { references: b, .. }) = (&nf.kind, &f.kind) {+ let edges = |r: &[solidcraft_doc::HoleReference]| r.iter().map(|x| x.edge.0).collect::<Vec<_>>();+ if edges(a) != edges(b) {+ nf.edge_names = solidcraft_doc::hole_reference::reference_edge_names(&s.model.state_before(id), position.0, &edges(a));+ }+ }// New bend edges for a conversion: the names of the body's edges there now.if let (FeatureKind::SheetConvert { bends: a, body, .. }, FeatureKind::SheetConvert { bends: b, body: was, .. }) = (&nf.kind, &f.kind)&& (a != b || body != was)diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rsindex 216b126683..3391c1ecfc 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); 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)"),+ .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); references?: [{edge: [x,y,z] on a straight edge of the face, distance: expr}] (at most two; the centre goes that far from each edge's line, in the face's plane, and follows the edges; with a numeric position only); 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")@@ -520,6 +520,11 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) ->(Vec::new(), solidcraft_doc::sheet::sheet_edge_names(&s.model.state(), &solidcraft_doc::plain(&points)))}FeatureKind::SheetHem { edges, .. } => (Vec::new(), solidcraft_doc::sheet::sheet_edge_names(&s.model.state(), &solidcraft_doc::plain(edges))),+ // A hole's reference edges (#37) are edges of the body it is drilled into.+ FeatureKind::Hole { position, references, .. } if !references.is_empty() => {+ let edges: Vec<Vec3> = references.iter().map(|r| r.edge.0).collect();+ (Vec::new(), solidcraft_doc::hole_reference::reference_edge_names(&s.model.state(), position.0, &edges))+ }// A conversion's bend edges are edges of the body it converts.FeatureKind::SheetConvert { body, bends, .. } if !bends.is_empty() => {(Vec::new(), solidcraft_doc::sheet::bend_edge_names(&s.model.state(), body, &solidcraft_doc::plain(bends)))@@ -1931,6 +1936,11 @@ fn hole(s: &mut Session, p: &Value) -> Result<Value> {}None => None,};+ // Reference edges (#37): the centre sits at these distances from straight edges of its face.+ let references = hole_reference_params(s, p, cmd)?;+ if !references.is_empty() && (points.is_some() || at.is_some()) {+ return Err(bad(cmd, "`references` place a hole by its `position` given as numbers, not at sketch points or length expressions"));+ }let position = match (&points, at_value.or_else(|| p.get("position").and_then(vec3))) {(Some((_, first, _)), None) => *first,(_, Some(x)) => x,@@ -1948,6 +1958,24 @@ fn hole(s: &mut Session, p: &Value) -> Result<Value> {}},};+ // Placed by its reference edges: drilled where their distances put it, which `position`+ // then keeps. The edges must be straight edges at the given points, and cross.+ let position = if references.is_empty() {+ position+ } else {+ let st = s.model.state();+ let mut distances = Vec::with_capacity(references.len());+ for r in &references {+ distances.push(s.doc.eval(&r.distance, Kind::Length).map_err(|e| bad(cmd, format!("`references`: {e}")))?);+ }+ let edges: Vec<(Vec3, Option<&str>)> = references.iter().map(|r| (r.edge.0, None)).collect();+ let frame = solidcraft_doc::hole_reference::reference_frame(&st, position, direction, &edges, true).map_err(|e| bad(cmd, e.to_string()))?;+ let centre = frame.place(position, &distances).map_err(|e| bad(cmd, e.to_string()))?;+ if !solidcraft_doc::hole_reference::on_reference_face(&st, &frame, centre) {+ return Err(bad(cmd, "the reference distances put the hole's centre off its face"));+ }+ centre+ };// The diameter: given, or the tap drill of the thread (major − pitch), or an ISO 273// clearance hole for a bolt size (close, normal or loose fit).let diameter = match (expr(p, "diameter"), &thread, str_(p, "clearance")) {@@ -2022,10 +2050,33 @@ fn hole(s: &mut Session, p: &Value) -> Result<Value> {points: points.map(|x| x.0),thread,to: to.map(FacePick),+ references,},)}+/// A hole's reference edges (#37): `references: [{edge: [x, y, z], distance: expr}]`, at most+/// two, each distance a length.+fn hole_reference_params(s: &Session, p: &Value, cmd: &str) -> Result<Vec<solidcraft_doc::HoleReference>> {+ let Some(v) = p.get("references") else { return Ok(Vec::new()) };+ let list = v.as_array().ok_or_else(|| bad(cmd, "`references` must be a list of {edge: [x, y, z], distance}"))?;+ let most = solidcraft_doc::hole_reference::MAX_HOLE_REFERENCES;+ if list.len() > most {+ return Err(bad(cmd, format!("a hole takes at most {most} `references`")));+ }+ let mut out = Vec::with_capacity(list.len());+ for (i, r) in list.iter().enumerate() {+ let edge = r+ .get("edge")+ .and_then(vec3)+ .ok_or_else(|| bad(cmd, format!("`references[{i}].edge` must be a point [x, y, z] on a straight edge of the face")))?;+ let distance = expr(r, "distance").ok_or_else(|| bad(cmd, format!("`references[{i}].distance` must be a number or an expression")))?;+ check_expr(s, &distance, Kind::Length, cmd, "references")?;+ out.push(solidcraft_doc::HoleReference { edge: Position(edge), distance });+ }+ Ok(out)+}+/// The body whose face is nearest `p` (within its pick tolerance), when it belongs to another/// component than the active one.fn body_of_other_component_at(s: &Session, p: Vec3) -> Option<String> {diff --git a/crates/engine/src/hole_reference_tests.rs b/crates/engine/src/hole_reference_tests.rsnew file mode 100644index 0000000000..da8ac53a67--- /dev/null+++ b/crates/engine/src/hole_reference_tests.rs@@ -0,0 +1,167 @@+//! A Single hole placed by distances from reference edges (#37): the centre sits at the typed+//! distances from straight edges of its face, measured in the face's plane, follows the edges+//! when the part changes (also after the design is saved and reopened), and a bad reference is+//! refused with an error.++use std::f64::consts::PI;++use serde_json::{Value, json};+use solidcraft_doc::FeatureKind;+use solidcraft_geom::Vec3;++use crate::{EngineError, Session};++fn run(s: &mut Session, id: &str, p: Value) -> Value {+ match s.execute(id, &p) {+ Ok(v) => v,+ Err(e) => panic!("{id} {p}: {e}"),+ }+}++fn solid_at(s: &Session, p: Vec3) -> bool {+ s.model.state().bodies.iter().any(|b| b.body.contains(p))+}++/// The bore (5 mm across, 4 mm deep, down from the top face at z = `top`) is about (x, y):+/// empty on its axis and up to 2 mm from it, solid 3 mm from it in every direction (the margins+/// leave room for the facets of a larger body's coarser mesh).+fn bore_at(s: &Session, x: f64, y: f64, top: f64) {+ let at = Vec3::new(x, y, top - 2.0);+ for k in 0..8 {+ let a = PI / 4.0 * f64::from(k);+ let p = |r: f64| at + Vec3::new(a.cos(), a.sin(), 0.0) * r;+ assert!(!solid_at(s, p(0.0)) && !solid_at(s, p(2.0)), "the bore about ({x}, {y}) is empty {a} rad from +x");+ assert!(solid_at(s, p(3.0)), "the wall about ({x}, {y}) is solid {a} rad from +x");+ }+}++/// The last feature's position and reference edges.+fn hole(s: &Session) -> (Vec3, Vec<solidcraft_doc::HoleReference>) {+ match &s.doc.features.last().map(|f| &f.kind) {+ Some(FeatureKind::Hole { position, references, .. }) => (position.0, references.clone()),+ other => panic!("the last feature is not a hole: {other:?}"),+ }+}++/// A 50 × 40 × 10 box from the origin whose length and width are parameters.+fn plate() -> Session {+ let mut s = Session::default();+ run(&mut s, "parameters.add", json!({"name": "len", "expression": "50 mm"}));+ run(&mut s, "parameters.add", json!({"name": "wid", "expression": "40 mm"}));+ run(&mut s, "solid.box", json!({"length": "len", "width": "wid", "height": 10, "corner": [0, 0, 0]}));+ s+}++/// A Ø5 × 4 hole picked at (30, 25) on the top, with these references.+fn referenced(references: Value) -> Value {+ json!({"position": [30, 25, 10], "diameter": 5, "depth": 4, "name": "H", "references": references})+}++#[test]+fn a_hole_sits_at_its_distances_from_two_edges() {+ let mut s = plate();+ // 10 mm from the left edge (x = 0) and 12 mm from the front edge (y = 0) of the top.+ run(&mut s, "solid.hole", referenced(json!([{"edge": [0, 20, 10], "distance": 10}, {"edge": [25, 0, 10], "distance": "12 mm"}])));+ let (position, refs) = hole(&s);+ assert!(position.dist(Vec3::new(10.0, 12.0, 10.0)) < 1e-6, "the hole is placed at (10, 12), not {position:?}");+ assert_eq!(refs.len(), 2);+ bore_at(&s, 10.0, 12.0, 10.0);+ assert!(solid_at(&s, Vec3::new(30.0, 25.0, 8.0)), "nothing is drilled where the face was picked");+ // The distances are the hole's parameters, named like its other inputs.+ let f = s.doc.find_feature("H").unwrap();+ let labels: Vec<&str> = f.kind.inputs().iter().map(|(label, _, _)| *label).collect();+ assert_eq!(labels.iter().filter(|l| **l == "Reference distance").count(), 2, "{labels:?}");+ assert_eq!(f.param_names.len(), labels.len());+ assert_eq!(f.edge_names.len(), 2, "each reference edge keeps its persistent name");+ // One reference: the hole moves square to that edge and keeps its place along it.+ run(&mut s, "edit.undo", json!({}));+ run(&mut s, "solid.hole", referenced(json!([{"edge": [0, 20, 10], "distance": 10}])));+ bore_at(&s, 10.0, 25.0, 10.0);+}++#[test]+fn a_hole_follows_its_edges_when_the_box_grows() {+ let mut s = plate();+ // From the far edges: 10 mm from x = len, 12 mm from y = wid.+ run(&mut s, "solid.hole", referenced(json!([{"edge": [50, 20, 10], "distance": 10}, {"edge": [25, 40, 10], "distance": 12}])));+ bore_at(&s, 40.0, 28.0, 10.0);+ let id = s.doc.find_feature("H").unwrap().id;+ run(&mut s, "parameters.change", json!({"name": "len", "expression": "80 mm"}));+ run(&mut s, "parameters.change", json!({"name": "wid", "expression": "65 mm"}));+ assert!(s.model.result(id).is_some_and(|r| r.error.is_none()), "{:?}", s.model.result(id).map(|r| &r.error));+ bore_at(&s, 70.0, 53.0, 10.0);+ assert!(solid_at(&s, Vec3::new(40.0, 28.0, 8.0)), "the old spot is solid again");+ // A distance is a parameter too: changing it moves the hole.+ let d = s.doc.find_feature("H").unwrap().param_names.last().cloned().unwrap();+ run(&mut s, "parameters.change", json!({"name": d, "expression": "20 mm"}));+ bore_at(&s, 70.0, 45.0, 10.0);+ // Smaller than where the hole was placed: it still follows its edges.+ run(&mut s, "parameters.change", json!({"name": "len", "expression": "30 mm"}));+ bore_at(&s, 20.0, 45.0, 10.0);+ // Saved and reopened, the hole keeps its references and its place.+ let mut t = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());+ t.refresh();+ bore_at(&t, 20.0, 45.0, 10.0);+ assert_eq!(hole(&t).1, hole(&s).1);+}++#[test]+fn a_bad_reference_is_refused() {+ let mut s = plate();+ run(&mut s, "solid.hole", json!({"position": [25, 20, 10], "diameter": 10, "name": "Bore"}));+ let before = s.doc.features.len();+ let edge = |p: [f64; 3], d: Value| json!({"edge": p, "distance": d});+ for (refs, why) in [+ (json!([edge([25.0, 30.0, 10.0], json!(5))]), "no edge"),+ (json!([edge([30.0, 20.0, 10.0], json!(5))]), "not straight"),+ (json!([edge([0.0, 0.0, 5.0], json!(5))]), "square to the face"),+ (json!([edge([0.0, 20.0, 10.0], json!(5)), edge([50.0, 20.0, 10.0], json!(5))]), "parallel"),+ (json!([edge([0.0, 20.0, 10.0], json!(5)), edge([25.0, 0.0, 10.0], json!(5)), edge([50.0, 20.0, 10.0], json!(5))]), "at most 2"),+ (json!([edge([0.0, 20.0, 10.0], json!("-5 mm"))]), "0 or more"),+ (json!([edge([0.0, 20.0, 10.0], json!(500))]), "off its face"),+ (json!([edge([0.0, 20.0, 10.0], json!("5 deg"))]), "references"),+ (json!([edge([0.0, 20.0, 10.0], json!("nope"))]), "references"),+ (json!([{"edge": [0, 20], "distance": 5}]), "edge"),+ (json!([{"edge": [0, 20, 10]}]), "distance"),+ (json!({"edge": [0, 20, 10], "distance": 5}), "list"),+ ] {+ let p = referenced(refs.clone());+ match s.execute("solid.hole", &p) {+ Err(EngineError::Internal(..)) | Ok(_) => panic!("{refs} is refused"),+ Err(e) => assert!(e.to_string().contains(why), "{refs}: {e}"),+ }+ assert_eq!(s.doc.features.len(), before, "{refs} adds nothing");+ }+ // Not with sketch points or a position given as expressions.+ for p in [+ json!({"position": ["30 mm", "25 mm", "10 mm"], "diameter": 5, "references": [edge([0.0, 20.0, 10.0], json!(5))]}),+ json!({"sketch": 1, "points": ["p1"], "diameter": 5, "references": [edge([0.0, 20.0, 10.0], json!(5))]}),+ ] {+ assert!(s.execute("solid.hole", &p).is_err(), "{p}");+ }+}++#[test]+fn hostile_references_never_panic() {+ let mut s = plate();+ let values = crate::tests::hostile_values();+ let mut panicked = Vec::new();+ for v in &values {+ for refs in [+ v.clone(),+ json!([v]),+ json!([v, v]),+ json!([{"edge": v, "distance": 5}]),+ json!([{"edge": [0, 20, 10], "distance": v}]),+ json!([{"edge": [0, 20, 10], "distance": 5}, {"edge": v, "distance": v}]),+ ] {+ for at in [json!([30, 25, 10]), json!([0, 0, 10]), json!([1e300, 0, 10]), v.clone()] {+ let p = json!({"position": at, "diameter": 5, "references": refs});+ if let Err(EngineError::Internal(id, msg)) = s.execute("solid.hole", &p) {+ panicked.push(format!("{id} {p}: {msg}"));+ }+ }+ }+ }+ assert!(panicked.is_empty(), "solid.hole panicked:\n{}", panicked.join("\n"));+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex b69f500914..7084bc65a7 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -1250,6 +1250,8 @@ mod hole_face_tests;#[cfg(test)]mod hole_matrix_tests;#[cfg(test)]+mod hole_reference_tests;+#[cfg(test)]mod large_assembly_tests;#[cfg(test)]mod measure_centre_tests;diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex 0e2d53fa43..5e1f23df9f 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -826,6 +826,7 @@ fn hostile_params_never_panic() {"anchor","density","names",+ "references",];// Commands are independent; worker threads take them one at a time (their costs vary a lot).let ids: Vec<&str> = command_specs()diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex a4d8a01d7e..8bb0481d66 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -375,7 +375,7 @@ fn along(proj: &Proj, pos: Pos2, base: Vec3, dir: Vec3) -> Option<f64> {Some((b * e - d) / den)}-fn format_len(v: f64) -> String {+pub(crate) fn format_len(v: f64) -> String {let s = format!("{v:.3}");let s = s.trim_end_matches('0').trim_end_matches('.');format!("{} mm", if s == "-0" { "0" } else { s })@@ -445,7 +445,7 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj,| Kind::OffsetFaces { .. }| Kind::SketchModify(crate::sketch_modify_ui::Mod::Move { .. }));- let focus = std::mem::take(&mut d.focus);+ let mut focus = std::mem::take(&mut d.focus);let half_height = app.cam.half_height();let axis = revolve_axis(app, d);if matches!(d.kind, Kind::Revolve { .. }) {@@ -531,6 +531,11 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj,opts.all = false;}dir = None;+ // A Single hole's distances from its reference edges (#37); a newly picked edge's box+ // takes the keyboard.+ if crate::hole_refs::canvas(app, ui, painter, proj, d) {+ focus = false;+ }}// A fillet with a radius spline is shaped by its handles along the edge; the arrow would sit// on one of them.@@ -586,28 +591,42 @@ fn value_box(ui: &mut egui::Ui, label: &str, value: &mut String, at: Pos2, selec/// [`value_box`]; with `keep_tab` Tab stays in the box for the caller (the Move box steps/// through its values with it).fn value_box_with(ui: &mut egui::Ui, label: &str, value: &mut String, at: Pos2, select_all: bool, keep_tab: bool) {+ let ids = (egui::Id::new("sc_canvas_area"), egui::Id::new("sc_canvas_value"));+ value_box_in(ui, ids, label, value, (at, egui::Align2::LEFT_TOP), select_all, keep_tab);+}++/// [`value_box_with`] under its own ids (its area's and its field's), for a value beside the main+/// one (a hole's reference distances), with the point of the box that sits at `at`. Returns where+/// the field is.+pub(crate) fn value_box_in(+ ui: &mut egui::Ui,+ (area, id): (egui::Id, egui::Id),+ label: &str,+ value: &mut String,+ (at, pivot): (Pos2, egui::Align2),+ select_all: bool,+ keep_tab: bool,+) -> Option<egui::Rect> {let t = Tokens::get();- let id = egui::Id::new("sc_canvas_value");- Container::new(ui.ctx(), Surface::Canvas).area(egui::Id::new("sc_canvas_area")).fixed_pos(at).order(egui::Order::Foreground).show(- ui.ctx(),- |ui| {- Container::popup_frame(ui.style()).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| {- ui.horizontal(|ui| {- ui.label(egui::RichText::new(crate::i18n::tr_label(label)).color(t.text_dim).size(crate::theme::Tokens::get().font_caption));- let r = crate::ui_kit::canvas_value_field(ui, id, value, keep_tab);- crate::params_dialog::complete(ui, &r, value);- if select_all {- r.request_focus();- let n = value.chars().count();- let mut st = egui::text_edit::TextEditState::load(ui.ctx(), id).unwrap_or_default();- st.cursor- .set_char_range(Some(egui::text_selection::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(n))));- st.store(ui.ctx(), id);- }- });+ let mut field = None;+ Container::new(ui.ctx(), Surface::Canvas).area(area).fixed_pos(at).pivot(pivot).order(egui::Order::Foreground).show(ui.ctx(), |ui| {+ Container::popup_frame(ui.style()).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| {+ ui.horizontal(|ui| {+ ui.label(egui::RichText::new(crate::i18n::tr_label(label)).color(t.text_dim).size(crate::theme::Tokens::get().font_caption));+ let r = crate::ui_kit::canvas_value_field(ui, id, value, keep_tab);+ crate::params_dialog::complete(ui, &r, value);+ if select_all {+ r.request_focus();+ let n = value.chars().count();+ let mut st = egui::text_edit::TextEditState::load(ui.ctx(), id).unwrap_or_default();+ st.cursor.set_char_range(Some(egui::text_selection::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(n))));+ st.store(ui.ctx(), id);+ }+ field = Some(r.rect);});- },- );+ });+ });+ field}/// How far (logical points) from an arrow's stem a press still takes the arrow.diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 8a1b57c7d3..afda0175f7 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -377,6 +377,13 @@ crate::dialog_descriptor::dialog_descriptors! {/// Holes go on any face (flat or curved; the engine drills against the face's normal there).const HOLE_FACES: Accept = PLANAR_FACES | FACES | selection::POINTS;+/// The Single hole placement's inputs: the face, then up to two reference edges (#37).+fn single_hole_inputs() -> Vec<SelInput> {+ let mut v = vec![SelInput::new("Face", HOLE_FACES, true)];+ v.extend(crate::hole_refs::inputs());+ v+}+/// The rest of the Hole dialog: placement, extents, tap type and drill point.#[derive(Clone, Debug, PartialEq)]pub struct HoleOpts {@@ -392,11 +399,22 @@ pub struct HoleOpts {pub thread: String,/// Custom nominal diameter and pitch being edited, separate from the saved designation.pub custom_thread: Option<crate::dialogs_thread::HoleThreadDraft>,+ /// The Single hole's reference edge distances (`hole_refs`, #37).+ pub refs: Box<crate::hole_refs::Refs>,}impl Default for HoleOpts {fn default() -> Self {- HoleOpts { multiple: false, all: false, angled: true, tip_angle: "118 deg".into(), tapped: false, thread: "M5".into(), custom_thread: None }+ HoleOpts {+ multiple: false,+ all: false,+ angled: true,+ tip_angle: "118 deg".into(),+ tapped: false,+ thread: "M5".into(),+ custom_thread: None,+ refs: Default::default(),+ }}}@@ -738,7 +756,7 @@ impl Dialog {]}),"solid.move" => Dialog::new(crate::dialogs_move::kind(0), crate::dialogs_move::inputs(0)),- "solid.hole" => Dialog::new(hole_defaults(), vec![SelInput::new("Face", HOLE_FACES, true)]),+ "solid.hole" => Dialog::new(hole_defaults(), single_hole_inputs()),"solid.box" => Dialog::new(Kind::Primitive {cmd: "solid.box",@@ -1955,7 +1973,7 @@ fn placement_row(d: &mut Dialog, ui: &mut egui::Ui) {choice_row(ui, "Placement", "hole_place", &mut m, &["Single", "Multiple"]);if (m == 1) != opts.multiple {opts.multiple = m == 1;- d.inputs = vec![if opts.multiple { SelInput::new("Points", selection::POINTS, true) } else { SelInput::new("Face", HOLE_FACES, true) }];+ d.inputs = if opts.multiple { vec![SelInput::new("Points", selection::POINTS, true)] } else { single_hole_inputs() };d.active = 0;d.extra.remove("direction");}@@ -2004,7 +2022,7 @@ fn stored_revolve_axis(kind: &Kind) -> Option<&Value> {}}-fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, range: std::ops::Range<usize>) {+pub(crate) fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, range: std::ops::Range<usize>) {// Edit Text shows its Path input among its own rows.if matches!(d.kind, Kind::Text(_)) {return;@@ -3810,6 +3828,16 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result<Vec<(String, Value)>, SNone => json!({ "position": kept.unwrap_or(p) }),}));}+ // Reference edges (#37) place the one hole by its distances from them, from where+ // it was picked.+ let references = crate::hole_refs::params(d);+ if !references.is_empty() {+ let at = sels(d, 0).iter().find_map(face_point);+ match (places.as_mut_slice(), at) {+ ([place], Some(at)) => *place = json!({"position": at, "references": references}),+ _ => return Err("reference edges place one hole: pick one place on the face".into()),+ }+ }}let mut out = Vec::new();for place in places {@@ -4575,7 +4603,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option<usize>) -> Option<Diad.extra.insert("pull".into(), pt3(pull.0));d}- FeatureKind::Hole { position, at, direction, diameter, depth, hole, points, thread, to } => {+ FeatureKind::Hole { position, at, direction, diameter, depth, hole, points, thread, to, references } => {let mut d = start("solid.hole")?;let mut k = hole_defaults();if let Kind::Hole { diameter: dia, depth: dep, kind, cb_diameter, cb_depth, cs_diameter, cs_angle, opts } = &mut k {@@ -4643,6 +4671,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option<usize>) -> Option<Dialet exprs: Vec<&str> = at.iter().map(|e| e.as_str()).collect();d.extra.insert("position_exprs".into(), json!({"at": exprs, "point": pt3(position.0)}));}+ crate::hole_refs::restore(s, &mut d, references, &f.edge_names);}}if to.is_some() {diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rsindex 524e693c01..39b5c901c8 100644--- a/crates/ui-egui/src/dialogs_dense.rs+++ b/crates/ui-egui/src/dialogs_dense.rs@@ -183,7 +183,12 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui:ui_kit::text(ui, tr(key), ui_kit::Text::Hint("manage"));}placement_row(d, ui);- input_rows(d, ui, &app.session);+ if matches!(&d.kind, Kind::Hole { opts, .. } if !opts.multiple) {+ // Each reference edge with its distance (#37).+ enter |= crate::hole_refs::input_rows(d, ui, &app.session);+ } else {+ input_rows(d, ui, &app.session);+ }match &mut d.kind {Kind::Material { index } => {let names = app.session.doc.material_names();diff --git a/crates/ui-egui/src/hole_refs.rs b/crates/ui-egui/src/hole_refs.rsnew file mode 100644index 0000000000..876a3f419e--- /dev/null+++ b/crates/ui-egui/src/hole_refs.rs@@ -0,0 +1,352 @@+//! A Single hole placed by distances from reference edges (#37). After the face pick the Hole+//! dialog takes up to two straight edges of that face (Reference 1 and 2), each with the hole+//! centre's distance from it (Distance 1 and 2). Picking an edge measures its distance from where+//! the hole is; typing a distance (in the dialog or in its box on the canvas) moves the hole+//! there; moving the hole (another pick, or dragging its handle) measures the distances again.+//! The canvas shows each distance as a dimension from its edge to the hole's centre. OK sends the+//! edges and distances as `solid.hole`'s `references`, so the hole follows its edges when the+//! part changes; Edit Feature picks the edges again where they are now.++use egui::{Color32, Pos2, Stroke, vec2};+use serde_json::{Value, json};+use solidcraft_engine::doc::HoleReference;+use solidcraft_engine::doc::expr::Kind as ValueKind;+use solidcraft_engine::doc::hole_reference::{ReferenceFrame, on_reference_face, reference_frame};+use solidcraft_engine::geom::Vec3;+use solidcraft_engine::{Sel, Session};++use crate::SolveApp;+use crate::dialogs::{Dialog, Kind};+use crate::selection::{EDGES, SelInput};+use crate::theme::Tokens;+use crate::viewport::Proj;++/// The reference edge inputs, after the face input.+pub(crate) const REFERENCES: [&str; 2] = ["Reference 1", "Reference 2"];+/// Each reference edge's distance row (and its box on the canvas).+pub(crate) const DISTANCES: [&str; 2] = ["Distance 1", "Distance 2"];++/// The distances typed for the reference edges, what they were last worked out for, the face's+/// frame for the picked edges, and the distance whose canvas box takes the keyboard next (a+/// newly picked edge's, so a number typed straight after the pick sets it).+#[derive(Clone, Debug, Default, PartialEq)]+pub struct Refs {+ pub distance: [String; 2],+ seen: Option<Seen>,+ frame: Option<Framed>,+ focus: Option<usize>,+}++/// The place, edges and distances the dialog last had in step.+#[derive(Clone, Debug, PartialEq)]+struct Seen {+ place: Vec3,+ edges: [Option<Vec3>; 2],+ distance: [String; 2],+}++/// The face's frame (with the reference inputs its lines are for) and what it was found for: the+/// design's revision, the place and the edges.+#[derive(Clone, Debug, PartialEq)]+struct Framed {+ revision: u64,+ place: Vec3,+ edges: [Option<Vec3>; 2],+ frame: Option<(ReferenceFrame, Vec<usize>)>,+}++/// The reference edge inputs a Single hole's dialog has after its face input.+pub(crate) fn inputs() -> [SelInput; 2] {+ REFERENCES.map(|label| SelInput::new(label, EDGES, false))+}++/// Is `d` a Single hole's dialog?+fn single(d: &Dialog) -> bool {+ matches!(&d.kind, Kind::Hole { opts, .. } if !opts.multiple)+}++/// The hole's place: the first face pick (its index in the face input, and the point).+fn place(d: &Dialog) -> Option<(usize, Vec3)> {+ d.inputs.first()?.items.iter().enumerate().find_map(|(i, x)| match x {+ Sel::Face { point, .. } => Some((i, *point)),+ _ => None,+ })+}++/// A point on each reference edge picked, by input.+fn edges(d: &Dialog) -> [Option<Vec3>; 2] {+ REFERENCES.map(|label| {+ d.inputs.iter().find(|i| i.label == label).and_then(|i| i.items.first()).and_then(|x| match x {+ Sel::Edge { point, .. } => Some(*point),+ _ => None,+ })+ })+}++/// A point `[x, y, z]` of a dialog's stored parameters.+fn vec3(v: &Value) -> Option<Vec3> {+ let a = v.as_array()?;+ let c = |i: usize| a.get(i).and_then(Value::as_f64).filter(|x| x.is_finite());+ (a.len() == 3).then(|| Some(Vec3::new(c(0)?, c(1)?, c(2)?))).flatten()+}++/// The way the hole drills at `at`: as it was made (editing), else into the face there.+fn direction(s: &Session, d: &Dialog, at: Vec3) -> Option<Vec3> {+ d.extra.get("direction").and_then(vec3).or_else(|| solidcraft_engine::doc::hole_direction_at(&s.world_state(), at))+}++/// The face's frame at the place for the picked edges (and which reference inputs they are), found+/// again only when the design, the place or the edges change.+fn frame(s: &Session, d: &mut Dialog) -> Option<(ReferenceFrame, Vec<usize>)> {+ let (_, at) = place(d)?;+ let edges = edges(d);+ if edges.iter().all(Option::is_none) {+ return None;+ }+ let Kind::Hole { opts, .. } = &d.kind else { return None };+ if let Some(f) = &opts.refs.frame+ && f.revision == s.revision+ && f.place == at+ && f.edges == edges+ {+ return f.frame.clone();+ }+ let picked: Vec<(usize, Vec3)> = edges.iter().enumerate().filter_map(|(k, e)| e.map(|p| (k, p))).collect();+ let found = direction(s, d, at).and_then(|dir| {+ let pts: Vec<(Vec3, Option<&str>)> = picked.iter().map(|(_, p)| (*p, None)).collect();+ reference_frame(&s.world_state(), at, dir, &pts, true).ok().map(|f| (f, picked.iter().map(|(k, _)| *k).collect()))+ });+ if let Kind::Hole { opts, .. } = &mut d.kind {+ opts.refs.frame = Some(Framed { revision: s.revision, place: at, edges, frame: found.clone() });+ }+ found+}++/// Keep the distances and the hole's place in step: a new place or a new edge is measured, a+/// typed distance moves the place there (when it stays on the face). Run before the dialog's+/// commands are made.+pub(crate) fn sync(s: &Session, d: &mut Dialog) {+ if !single(d) {+ return;+ }+ let edges = edges(d);+ let Some((i, at)) = place(d) else {+ if let Kind::Hole { opts, .. } = &mut d.kind {+ opts.refs.seen = None;+ }+ return;+ };+ let framed = frame(s, d);+ let Kind::Hole { opts, .. } = &mut d.kind else { return };+ let refs = &mut opts.refs;+ let mut to = at;+ if let Some((f, picked)) = &framed {+ let same = refs.seen.as_ref().filter(|sn| sn.place == at && sn.edges == edges);+ match same {+ // Typed: the hole goes to the distances.+ Some(sn) if sn.distance != refs.distance => {+ let values: Option<Vec<f64>> =+ picked.iter().map(|k| refs.distance.get(*k).and_then(|e| s.doc.eval(e, ValueKind::Length).ok())).collect();+ if let Some(c) = values.and_then(|v| f.place(at, &v).ok()).filter(|c| on_reference_face(&s.world_state(), f, *c)) {+ to = c;+ }+ }+ Some(_) => {}+ // A new place, or a new edge: measured from where the hole is.+ None => {+ let moved = refs.seen.as_ref().is_none_or(|sn| sn.place != at);+ for (k, v) in picked.iter().zip(f.distances(at)) {+ let new_edge = refs.seen.as_ref().is_none_or(|sn| sn.edges.get(*k) != edges.get(*k));+ if let Some(slot) = refs.distance.get_mut(*k)+ && (moved || new_edge || slot.trim().is_empty())+ {+ *slot = crate::canvas::format_len(v.max(0.0));+ }+ if new_edge && edges.get(*k).is_some_and(Option::is_some) {+ refs.focus = Some(*k);+ }+ }+ }+ }+ }+ refs.seen = Some(Seen { place: to, edges, distance: refs.distance.clone() });+ if to != at+ && let Some(Sel::Face { point, .. }) = d.inputs.first_mut().and_then(|inp| inp.items.get_mut(i))+ {+ *point = to;+ }+}++/// The Single hole's selection rows, each reference edge with its distance on the row below it+/// once it is picked. Whether Enter was pressed in a distance.+pub(crate) fn input_rows(d: &mut Dialog, ui: &mut egui::Ui, s: &Session) -> bool {+ let mut enter = false;+ for i in 0..d.inputs.len() {+ crate::dialogs::input_rows_range(d, ui, s, i..i + 1);+ let Some(k) = d.inputs.get(i).filter(|inp| !inp.items.is_empty()).and_then(|inp| REFERENCES.iter().position(|l| *l == inp.label)) else {+ continue;+ };+ if let Kind::Hole { opts, .. } = &mut d.kind+ && let (Some(label), Some(value)) = (DISTANCES.get(k), opts.refs.distance.get_mut(k))+ {+ enter |= crate::ui_kit::expr_row(ui, label, value);+ }+ }+ sync(s, d);+ enter+}++/// The `references` OK sends: each picked edge (a point on it) with its distance.+pub(crate) fn params(d: &Dialog) -> Vec<Value> {+ let Kind::Hole { opts, .. } = &d.kind else { return Vec::new() };+ if opts.multiple {+ return Vec::new();+ }+ edges(d)+ .iter()+ .zip(&opts.refs.distance)+ .filter_map(|(e, distance)| e.map(|p| json!({"edge": [p.x, p.y, p.z], "distance": distance.trim()})))+ .collect()+}++/// Editing a hole with reference edges: the edges picked again where they are now, their+/// distances, and the place where those distances put the hole now.+pub(crate) fn restore(s: &Session, d: &mut Dialog, references: &[HoleReference], names: &[String]) {+ if references.is_empty() {+ return;+ }+ let Some((i, at)) = place(d) else { return };+ let st = s.world_state();+ let edges: Vec<(Vec3, Option<&str>)> = references.iter().enumerate().map(|(k, r)| (r.edge.0, names.get(k).map(String::as_str))).collect();+ let found = direction(s, d, at).and_then(|dir| reference_frame(&st, at, dir, &edges, false).ok());+ let mesh = found.as_ref().and_then(|f| st.body(&f.body)).map(|b| b.mesh());+ for (k, r) in references.iter().enumerate().take(REFERENCES.len()) {+ // Where the edge is now, else where it was picked.+ let sel = found.as_ref().zip(mesh.as_ref()).and_then(|(f, m)| {+ let index = *f.edges.get(k)?;+ let point = crate::selection::polyline_mid(m.edges.get(index)?);+ Some(Sel::Edge { body: f.body.clone(), index, point })+ });+ let sel = sel.or_else(|| nearest_edge(s, at, r.edge.0));+ if let (Some(label), Some(sel)) = (REFERENCES.get(k), sel)+ && let Some(inp) = d.inputs.iter_mut().find(|inp| inp.label == *label)+ {+ inp.items = vec![sel];+ }+ if let Kind::Hole { opts, .. } = &mut d.kind+ && let Some(slot) = opts.refs.distance.get_mut(k)+ {+ *slot = r.distance.to_string();+ }+ }+ // The hole where its distances put it now (the part may have changed since it was placed).+ let mut to = at;+ if let Some(f) = &found+ && let Kind::Hole { opts, .. } = &d.kind+ {+ let values: Option<Vec<f64>> = opts.refs.distance.iter().take(f.lines.len()).map(|e| s.doc.eval(e, ValueKind::Length).ok()).collect();+ if let Some(c) = values.and_then(|v| f.place(at, &v).ok()).filter(|c| on_reference_face(&st, f, *c)) {+ to = c;+ }+ }+ if let Some(Sel::Face { point, .. }) = d.inputs.first_mut().and_then(|inp| inp.items.get_mut(i)) {+ *point = to;+ }+ let edges = self::edges(d);+ if let Kind::Hole { opts, .. } = &mut d.kind {+ opts.refs.seen = Some(Seen { place: to, edges, distance: opts.refs.distance.clone() });+ }+}++/// The edge of the body under `at` nearest `p`, picked at `p` (a reference edge that is not+/// found as it was made: OK then reports why).+fn nearest_edge(s: &Session, at: Vec3, p: Vec3) -> Option<Sel> {+ let Some(Sel::Face { body, .. }) = crate::dialogs::face_sel(s, at) else { return None };+ let st = s.world_state();+ let m = st.body(&body)?.mesh();+ let to = |e: &Vec<Vec3>| e.windows(2).map(|w| p.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min);+ let index = m.edges.iter().enumerate().map(|(i, e)| (to(e), i)).filter(|(d, _)| d.is_finite()).min_by(|a, b| a.0.total_cmp(&b.0))?.1;+ Some(Sel::Edge { body, index, point: p })+}++/// The reference distances on the canvas: a dimension from each edge to the hole's centre, and a+/// box beside it to type the distance in. Whether a box took the keyboard (a newly picked edge's),+/// which the dialog's main value then leaves to it.+pub(crate) fn canvas(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, d: &mut Dialog) -> bool {+ if !single(d) {+ return false;+ }+ let Some((_, at)) = place(d) else { return false };+ let Some((f, picked)) = frame(&app.session, d) else { return false };+ let mut took = false;+ let t = Tokens::get();+ let px = 2.0 * app.cam.half_height() / f64::from(proj.rect.height().max(1.0));+ let centre = f.onto_plane(at);+ for (line, k) in f.lines.iter().zip(&picked) {+ let foot = line.foot(centre);+ let (Some(a), Some(b)) = (proj.to_screen(foot), proj.to_screen(centre)) else { continue };+ // The reference edge's line on either side of where the dimension leaves it.+ let reach = line.along * (14.0 * px);+ if let (Some(e0), Some(e1)) = (proj.to_screen(foot - reach), proj.to_screen(foot + reach)) {+ painter.line_segment([e0, e1], Stroke::new(1.2, t.dimension));+ }+ dimension(painter, a, b, t.dimension);+ let (Some(label), Kind::Hole { opts, .. }) = (DISTANCES.get(*k), &mut d.kind) else { continue };+ let focus = opts.refs.focus == Some(*k);+ if focus {+ opts.refs.focus = None;+ took = true;+ }+ let Some(value) = opts.refs.distance.get_mut(*k) else { continue };+ let at = box_beyond(a, b);+ let r = crate::canvas::value_box_in(+ ui,+ (egui::Id::new(("sc_hole_ref_area", *k)), egui::Id::new(("sc_hole_ref", *k))),+ label,+ value,+ at,+ focus,+ false,+ );+ if let Some(r) = r {+ crate::scenario::publish_handle(&format!("canvas:{label}"), r.center());+ }+ }+ took+}++/// Where a distance's box goes: just past its edge (at `a`, the hole's centre at `b`), on the side+/// away from the hole, so it stays clear of the hole's own value box at its centre. The box's side+/// toward the edge sits there.+fn box_beyond(a: Pos2, b: Pos2) -> (Pos2, egui::Align2) {+ const GAP: f32 = 10.0;+ let v = a - b;+ let out = if v.length() < 1.0 { vec2(1.0, 0.0) } else { v / v.length() };+ if out.x.abs() >= out.y.abs() {+ if out.x > 0.0 { (a + vec2(GAP, 0.0), egui::Align2::LEFT_CENTER) } else { (a - vec2(GAP, 0.0), egui::Align2::RIGHT_CENTER) }+ } else if out.y > 0.0 {+ (a + vec2(0.0, GAP), egui::Align2::CENTER_TOP)+ } else {+ (a - vec2(0.0, GAP), egui::Align2::CENTER_BOTTOM)+ }+}++/// A dimension line from `a` to `b`, an arrowhead at each end.+fn dimension(painter: &egui::Painter, a: Pos2, b: Pos2, col: Color32) {+ let v = b - a;+ let l = v.length();+ if l < 1.0 {+ return;+ }+ let u = v / l;+ let n = vec2(-u.y, u.x);+ painter.line_segment([a, b], Stroke::new(1.2, col));+ let head = 8.0f32.min(l * 0.4);+ for (tip, out) in [(a, -u), (b, u)] {+ painter.add(egui::Shape::convex_polygon(+ vec![tip, tip - out * head + n * head * 0.35, tip - out * head - n * head * 0.35],+ col,+ Stroke::NONE,+ ));+ }+}diff --git a/crates/ui-egui/src/hole_refs_ui_tests.rs b/crates/ui-egui/src/hole_refs_ui_tests.rsnew file mode 100644index 0000000000..ab170e1b27--- /dev/null+++ b/crates/ui-egui/src/hole_refs_ui_tests.rs@@ -0,0 +1,162 @@+//! A Single hole placed by distances from reference edges, through the window (#37): pick the+//! face, pick two edges (each distance is measured from the pick), type the distances (one in+//! the dialog, one in its box on the canvas), OK. The hole sits at those distances; Edit Feature+//! picks the edges again with their distances, and moving the hole's place measures them again.++use serde_json::json;+use solidcraft_engine::Sel;+use solidcraft_engine::doc::FeatureKind;+use solidcraft_engine::geom::Vec3;++use crate::dialogs::Kind;+use crate::scenario::Harness;++/// Where a world point is on screen.+fn screen(h: &mut Harness, p: Vec3) -> [f64; 2] {+ h.at(&json!({"world": [p.x, p.y, p.z]})).unwrap()+}++/// A 50 × 40 × 10 plate from the origin, seen from the top.+fn plate() -> Harness {+ let mut h = Harness::new();+ h.app.ui.show_origin = false;+ h.app.run("solid.box", json!({"length": 50, "width": 40, "height": 10, "corner": [0, 0, 0]})).unwrap();+ h.step(&json!({"call": "ui.view", "params": {"view": "top"}})).unwrap();+ h.settle();+ h+}++/// The open Hole dialog's reference distances.+fn distances(h: &Harness) -> [String; 2] {+ match h.app.dialog.as_ref().map(|d| &d.kind) {+ Some(Kind::Hole { opts, .. }) => opts.refs.distance.clone(),+ _ => panic!("the hole dialog is open"),+ }+}++/// Where the open dialog places the hole (its face pick).+fn place(h: &Harness) -> Vec3 {+ match h.app.dialog.as_ref().and_then(|d| d.inputs.first()).and_then(|i| i.items.first()) {+ Some(Sel::Face { point, .. }) => *point,+ other => panic!("a face place, not {other:?}"),+ }+}++/// The edge picked into the open dialog's input `label`.+fn picked_edge(h: &Harness, label: &str) -> Option<Vec3> {+ let d = h.app.dialog.as_ref()?;+ match d.inputs.iter().find(|i| i.label == label)?.items.first()? {+ Sel::Edge { point, .. } => Some(*point),+ _ => None,+ }+}++/// Replace the text of the field at `handle` with `text`.+fn type_into(h: &mut Harness, handle: &str, text: &str) {+ h.step(&json!({"click": {"handle": handle}})).unwrap();+ h.step(&json!({"key": "A", "cmd": true})).unwrap();+ h.step(&json!({"text": text})).unwrap();+ h.frames(2);+}++/// Whether the model holds material at `p`.+fn solid_at(h: &Harness, p: Vec3) -> bool {+ h.app.session.model.state().bodies.iter().any(|b| b.body.contains(p))+}++#[test]+fn a_hole_is_placed_by_its_distances_from_two_edges() {+ let mut h = plate();+ h.step(&json!({"start": "solid.hole"})).unwrap();+ let at = screen(&mut h, Vec3::new(30.0, 25.0, 10.0));+ h.step(&json!({"click": at})).unwrap();+ assert!(place(&h).dist(Vec3::new(30.0, 25.0, 10.0)) < 0.5, "the face is picked where clicked: {:?}", place(&h));+ let picked = place(&h);+ // The reference inputs come after the face; picking an edge measures its distance from the+ // pick, and the second input takes the next edge.+ h.step(&json!({"click": {"handle": "dialog:Reference 1"}})).unwrap();+ let left = screen(&mut h, Vec3::new(0.0, 20.0, 10.0));+ h.step(&json!({"click": left})).unwrap();+ let front = screen(&mut h, Vec3::new(25.0, 0.0, 10.0));+ h.step(&json!({"click": front})).unwrap();+ h.frames(2);+ assert!(picked_edge(&h, "Reference 1").is_some_and(|p| p.x.abs() < 1e-6), "the left edge is Reference 1: {:?}", picked_edge(&h, "Reference 1"));+ assert!(picked_edge(&h, "Reference 2").is_some_and(|p| p.y.abs() < 1e-6), "the front edge is Reference 2: {:?}", picked_edge(&h, "Reference 2"));+ let measured = distances(&h);+ let value = |s: &str| h.app.session.doc.eval(s, solidcraft_engine::doc::expr::Kind::Length).unwrap();+ assert!((value(&measured[0]) - picked.x).abs() < 1e-3 && (value(&measured[1]) - picked.y).abs() < 1e-3, "{measured:?} from {picked:?}");+ // The distances show on the canvas, each with a box to type in.+ assert!(h.at(&json!({"handle": "canvas:Distance 1"})).is_ok() && h.at(&json!({"handle": "canvas:Distance 2"})).is_ok());+ // Typed in the dialog and on the canvas: the hole goes there.+ type_into(&mut h, "dialog:Distance 1", "10 mm");+ type_into(&mut h, "canvas:Distance 2", "12 mm");+ assert_eq!(distances(&h), ["10 mm", "12 mm"]);+ assert!(place(&h).dist(Vec3::new(10.0, 12.0, 10.0)) < 1e-6, "the hole moved to its distances: {:?}", place(&h));+ h.step(&json!({"widget": "OK"})).unwrap();+ assert!(h.app.dialog.is_none(), "OK closed the dialog: {:?}", h.app.dialog.as_ref().map(|d| &d.error));+ let f = h.app.session.doc.features.last().unwrap().clone();+ let FeatureKind::Hole { position, references, .. } = &f.kind else { panic!("the last feature is a hole: {}", f.kind.type_name()) };+ assert!(position.0.dist(Vec3::new(10.0, 12.0, 10.0)) < 1e-6, "{position:?}");+ assert_eq!(references.iter().map(|r| r.distance.to_string()).collect::<Vec<_>>(), ["10 mm", "12 mm"]);+ assert!(h.app.session.model.result(f.id).is_some_and(|r| r.error.is_none()));+ assert!(+ !solid_at(&h, Vec3::new(10.0, 12.0, 8.0)) && solid_at(&h, Vec3::new(30.0, 25.0, 8.0)),+ "drilled at (10, 12), not where the face was picked"+ );++ // Edit Feature: the edges picked again with their distances, the hole where they put it.+ h.step(&json!({"call": "ui.editFeature", "params": {"feature": f.id}})).unwrap();+ h.frames(4);+ assert!(picked_edge(&h, "Reference 1").is_some_and(|p| p.x.abs() < 1e-6), "{:?}", picked_edge(&h, "Reference 1"));+ assert!(picked_edge(&h, "Reference 2").is_some_and(|p| p.y.abs() < 1e-6), "{:?}", picked_edge(&h, "Reference 2"));+ assert_eq!(distances(&h), ["10 mm", "12 mm"]);+ assert!(place(&h).dist(Vec3::new(10.0, 12.0, 10.0)) < 1e-6, "{:?}", place(&h));+ // The hole moved on its face (a new pick, or its handle dragged): the distances follow.+ if let Some(Sel::Face { point, .. }) = h.app.dialog.as_mut().and_then(|d| d.inputs.first_mut()).and_then(|i| i.items.first_mut()) {+ *point = Vec3::new(20.0, 30.0, 10.0);+ }+ h.frames(2);+ assert_eq!(distances(&h), ["20 mm", "30 mm"]);+ h.step(&json!({"widget": "OK"})).unwrap();+ assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().map(|d| &d.error));+ assert!(!solid_at(&h, Vec3::new(20.0, 30.0, 8.0)) && solid_at(&h, Vec3::new(10.0, 12.0, 8.0)), "the edit moved the hole to (20, 30)");+}++/// Reference edges place one hole: with places on two faces, OK says to pick one.+#[test]+fn reference_edges_place_one_hole() {+ let mut h = plate();+ h.step(&json!({"start": "solid.hole"})).unwrap();+ let at = screen(&mut h, Vec3::new(30.0, 25.0, 10.0));+ h.step(&json!({"click": at})).unwrap();+ // A second hole on another face (the bottom), as a pick there would place it.+ let d = h.app.dialog.as_mut().unwrap();+ let Some(Sel::Face { body, index, .. }) = d.inputs[0].items.first().cloned() else { panic!("a face place") };+ d.inputs[0].items.push(Sel::Face { body, index: index + 1, point: Vec3::new(40.0, 10.0, 0.0) });+ h.step(&json!({"click": {"handle": "dialog:Reference 1"}})).unwrap();+ let left = screen(&mut h, Vec3::new(0.0, 20.0, 10.0));+ h.step(&json!({"click": left})).unwrap();+ h.frames(2);+ let d = h.app.dialog.as_ref().unwrap();+ let err = crate::dialogs::apply_commands(&h.app, d).unwrap_err();+ assert!(err.contains("one hole"), "{err}");+}++/// A number typed straight after an edge pick is that edge's distance, not the diameter.+#[test]+fn a_number_typed_after_an_edge_pick_sets_its_distance() {+ let mut h = plate();+ h.step(&json!({"start": "solid.hole"})).unwrap();+ let at = screen(&mut h, Vec3::new(30.0, 25.0, 10.0));+ h.step(&json!({"click": at})).unwrap();+ h.step(&json!({"click": {"handle": "dialog:Reference 1"}})).unwrap();+ let left = screen(&mut h, Vec3::new(0.0, 20.0, 10.0));+ h.step(&json!({"click": left})).unwrap();+ h.frames(2);+ h.step(&json!({"text": "7 mm"})).unwrap();+ h.frames(2);+ assert_eq!(distances(&h)[0], "7 mm");+ assert!((place(&h).x - 7.0).abs() < 1e-6, "the hole is 7 mm from the left edge: {:?}", place(&h));+ let Some(Kind::Hole { diameter, .. }) = h.app.dialog.as_ref().map(|d| &d.kind) else { panic!("the hole dialog") };+ assert_eq!(diameter, "5 mm", "the diameter is left as it was");+}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex c8eec9b3fb..0ceb1b21b2 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -69,6 +69,9 @@ pub(crate) mod hole_place;mod hole_place_ui_tests;#[cfg(test)]mod hole_placement_ui_tests;+pub(crate) mod hole_refs;+#[cfg(test)]+mod hole_refs_ui_tests;pub mod home;pub mod i18n;#[cfg(test)]diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rsindex 878ff1fcba..e40d1046f7 100644--- a/crates/ui-egui/src/preselect_tests.rs+++ b/crates/ui-egui/src/preselect_tests.rs@@ -1481,8 +1481,9 @@ fn newer_options_reach_their_commands() {app.dialog = None;let top = face(&app, Vec3::new(20.0, 15.0, 20.0));let mut d = start(&mut app, vec![top], "solid.hole");- d.inputs.push(crate::selection::SelInput::new("To Object", crate::selection::FACES | crate::selection::VERTICES, false));- d.inputs[1].items = vec![face(&app, Vec3::new(20.0, 15.0, 0.0))];+ let mut to = crate::selection::SelInput::new("To Object", crate::selection::FACES | crate::selection::VERTICES, false);+ to.items = vec![face(&app, Vec3::new(20.0, 15.0, 0.0))];+ d.inputs.push(to);let p = apply_commands(&app, &d).unwrap().remove(0).1;assert!(p["to"].is_array() && p.get("depth").is_none(), "{p}");}diff --git a/docs/book/src/guide/features.md b/docs/book/src/guide/features.mdindex fe2cc43aa3..1521f9f358 100644--- a/docs/book/src/guide/features.md+++ b/docs/book/src/guide/features.md@@ -7,7 +7,7 @@ it.| Panel | Features ||---|---|-| Create | extrude (one side, two sides, symmetric, taper, start offset, to a distance or through all; new body, join, cut, intersect; thin walls along curves), revolve, sweep, loft, box, cylinder, sphere, torus, coil, pipe, rib, web, emboss, hole (simple, counterbore, countersink, tapped; on faces or at sketch points), thread, rectangular/circular/path patterns, mirror |+| Create | extrude (one side, two sides, symmetric, taper, start offset, to a distance or through all; new body, join, cut, intersect; thin walls along curves), revolve, sweep, loft, box, cylinder, sphere, torus, coil, pipe, rib, web, emboss, hole (simple, counterbore, countersink, tapped; on faces, at distances from edges, or at sketch points), thread, rectangular/circular/path patterns, mirror || Modify | press pull, fillet, chamfer, shell, draft, scale, combine, split body, offset face, replace face, move/copy, align, remove || Construct | offset plane, plane at angle, plane along path || Inspect | measure, section analysis, interference, compare bodies, curvature comb and map, zebra, draft, minimum radius, isocurves, centre of mass |@@ -96,6 +96,15 @@ unsupported. A new Emboss without an explicit face infers a unique eligible suppselect the face when the target is ambiguous. Older saved features without a face retain theirplanar placement.+A **Hole** with **Single** placement can also sit at distances from up to two straight edges of+its face. After picking the face, click **Reference 1** and pick an edge, then pick a second one+into **Reference 2**. Each edge gets a **Distance** row, measured from where you picked; the+canvas shows each one as a dimension from the edge to the hole's centre, with a box beside it.+Type a distance in either place and the hole moves so its centre is that far from the edge,+measured in the face's plane. Moving the hole measures the distances again. The hole keeps its+distances when the part changes: it follows its edges, and the distances are parameters like its+diameter.+A **Hole** with **Single** placement drills where you pick a planar face. A pick on or near apoint of a shown sketch that lies on that face, such as a circle's centre, places the holeexactly at that point, as **Multiple** placement picks it; **Select Other** (press and hold) also@@ -224,7 +233,7 @@ still be added through `set`. The fields of the common features:| Chamfer | `distance`, `distance2` or `angle`, `flip`, `edges`, `body` || Box | `length`, `width`, `height`, `corner`, `operation` || Cylinder | `radius`, `height`, `base`, `axis`, `operation` |-| Hole | `diameter`, `depth`, `position`, `direction`, `hole` (simple, drilled, counterbore, countersink), `thread`, `to` |+| Hole | `diameter`, `depth`, `position`, `direction`, `hole` (simple, drilled, counterbore, countersink), `thread`, `to`, `references` (an `edge` point and a `distance` each) || Shell | `thickness`, `faces`, `direction`, `body`, `tangent_chain` || Draft | `angle`, `faces`, `neutral`, `pull`, `body` || Offset face | `distance`, `faces`, `body` |diff --git a/skills/solidcraft-modeling/reference.md b/skills/solidcraft-modeling/reference.mdindex 22972dabb8..c9435e0b1f 100644--- a/skills/solidcraft-modeling/reference.md+++ b/skills/solidcraft-modeling/reference.md@@ -79,7 +79,7 @@ Distances are unsigned. Draw the geometry on the correct side first, and the dim| `sketch.slot.overall` / `sketch.slot.center_to_center` | `p0`, `p1` (overall ends / arc centres), `width` | Ids and dof are in the "Ids" section above. || `solid.fillet` / `solid.chamfer` | `edges:[[x,y,z]]`, `radius` / `distance` | The pick snaps to the **nearest** edge, with no distance limit and no error, so check that the face count changed. One pick takes the whole tangent chain: a rounded rim needs 1 point, not 8. || `solid.shell` | `faces:[[x,y,z]]`, `thickness` | A point on each face to remove, or its name from `body_topology`. Fillet first, except an edge of a removed face (see Order in `SKILL.md`). |-| `solid.hole` | `position:[x,y,z]` on a face (numbers or length expressions such as `["40", "width/2", "t"]`, which the hole then follows) + `diameter`, or `sketch` (+ `points`) | `clearance:"M3"`. `depth` defaults to through all. `type` is one of simple/drilled/counterbore/countersink. A `countersink` needs `cs_diameter` and `cs_angle`; a `counterbore` needs `cb_diameter` and `cb_depth`. `position` is a fixed point. |+| `solid.hole` | `position:[x,y,z]` on a face (numbers or length expressions such as `["40", "width/2", "t"]`, which the hole then follows) + `diameter`, or `sketch` (+ `points`) | `clearance:"M3"`. `depth` defaults to through all. `type` is one of simple/drilled/counterbore/countersink. A `countersink` needs `cs_diameter` and `cs_angle`; a `counterbore` needs `cb_diameter` and `cb_depth`. `position` is a fixed point; to tie it to the part, add `references: [{edge:[x,y,z], distance}]` (up to two straight edges of the face): the centre then sits at those distances from the edges and follows them. || `solid.pattern.rectangular` | `features`, `dir1`, `count1`, `spacing1` (+ `dir2`, `count2`, `spacing2`) | Spacing takes expressions and follows parameters. || `solid.pattern.circular` | `features`, `axis` (`"Z"` or `{origin, dir}`), `count` | `angle` defaults to 360 deg. A full pattern keeps the COM on the axis, so check its radius with a top-view screenshot. || `solid.mirror` | `features:[names]` or `bodies:[names]`, `plane` (`XY`/`XZ`/`YZ`, a construction plane, or `{origin, normal}` whose origin may use length expressions) | Follows parameters. A mirror or pattern feature cannot be listed in `features` of another mirror or pattern, but `bodies` can mirror the body it made. The mirror is a new body with the first free default name: `Body1`, `Body2` from `features`, and `Side (2)`, `Side (3)` from `bodies:["Side"]`. Read the name from `created_bodies`. With `combine:true`, a mirror that overlaps the original joins it and makes no new body. `features` copies only the features listed, so a later cut is left out unless you list it too. `bodies` copies the finished body. To name the mirror, use `body.rename {"body":"Side (2)","name":"Side_L"}`. The new name stays when parameters change. |