Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Hole: independent tapping depth and recessed drill points (#4486)

amolinari-autotexface5e2d3143
diff --git a/assets/locales/en.json b/assets/locales/en.json
index cb37d55347..13f95a5a59 100644
--- a/assets/locales/en.json
+++ b/assets/locales/en.json
@@ -227,6 +227,7 @@
"From Bodies": "From Bodies",
"From edges": "From edges",
"Full Length": "Full Length",
+ "Full thread depth": "Full thread depth",
"G2 corners require a constant radius and Exact fit. G2 corner construction is not supported yet.": "G2 corners require a constant radius and Exact fit. G2 corner construction is not supported yet.",
"Gap": "Gap",
"Grid": "Grid",
@@ -534,6 +535,7 @@
"This child is shared. Position changes apply to every copy of its parent.": "This child is shared. Position changes apply to every copy of its parent.",
"This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.",
"This image is not attached to GitHub yet. Copy or save it, then attach it on GitHub.": "This image is not attached to GitHub yet. Copy or save it, then attach it on GitHub.",
+ "Thread depth": "Thread depth",
"Thread diameter": "Thread diameter",
"To": "To",
"To Offset": "To Offset",
diff --git a/assets/locales/it.json b/assets/locales/it.json
index 3cdb28e950..96b6925f84 100644
--- a/assets/locales/it.json
+++ b/assets/locales/it.json
@@ -164,6 +164,7 @@
"From Bodies": "Dai corpi",
"From edges": "Spigoli di partenza",
"Full Length": "Lunghezza totale",
+ "Full thread depth": "Profondità filetto completa",
"Gap": "Gioco",
"Grid": "Griglia",
"HISTORY": "CRONOLOGIA",
@@ -382,6 +383,7 @@
"This child is shared. Deleting it removes it from every copy of its parent.": "Questo elemento figlio è condiviso. Eliminandolo verrà rimosso da ogni copia del padre.",
"This child is shared. Position changes apply to every copy of its parent.": "Questo elemento figlio è condiviso. Le modifiche alla posizione si applicano a ogni copia del padre.",
"This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Questa faccia non consente un collegamento persistente. Scegli un'altra faccia o usa esplicitamente un piano fisso.",
+ "Thread depth": "Profondità filetto",
"To Offset": "Fino a una distanza",
"To edges": "Spigoli di arrivo",
"Tolerance": "Tolleranza",
diff --git a/assets/locales/ja.json b/assets/locales/ja.json
index 143283a4d7..e7b07595ce 100644
--- a/assets/locales/ja.json
+++ b/assets/locales/ja.json
@@ -227,6 +227,7 @@
"From Bodies": "ボディから",
"From edges": "開始側エッジ",
"Full Length": "全長",
+ "Full thread depth": "ねじ深さ全体",
"G2 corners require a constant radius and Exact fit. G2 corner construction is not supported yet.": "G2 コーナーには一定半径と Exact fit が必要です。G2 コーナーの構築はまだサポートされていません。",
"Gap": "間隔",
"Grid": "グリッド",
@@ -534,6 +535,7 @@
"This child is shared. Position changes apply to every copy of its parent.": "この子要素は共有されています。位置の変更は親のすべてのコピーに適用されます。",
"This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "この面は安定したアタッチメントを提供できません。別の面を選択するか、固定平面を明示的に使用してください。",
"This image is not attached to GitHub yet. Copy or save it, then attach it on GitHub.": "この画像はまだGitHubに添付されていません。コピーまたは保存し、GitHubで添付してください。",
+ "Thread depth": "ねじ深さ",
"Thread diameter": "ねじ径",
"To": "終了",
"To Offset": "オフセットまで",
diff --git a/assets/locales/zh.json b/assets/locales/zh.json
index 9a188da96d..1d7ae67b1d 100644
--- a/assets/locales/zh.json
+++ b/assets/locales/zh.json
@@ -227,6 +227,7 @@
"From Bodies": "从实体创建",
"From edges": "起始边",
"Full Length": "全长",
+ "Full thread depth": "完整螺纹深度",
"G2 corners require a constant radius and Exact fit. G2 corner construction is not supported yet.": "G2 拐角需要恒定半径和 Exact fit。尚不支持构建 G2 拐角。",
"Gap": "间隙",
"Grid": "网格",
@@ -534,6 +535,7 @@
"This child is shared. Position changes apply to every copy of its parent.": "此子项是共享的。位置更改会应用到其父项的每个副本。",
"This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "此面无法提供持久附着。请选择其他面或显式使用固定平面。",
"This image is not attached to GitHub yet. Copy or save it, then attach it on GitHub.": "此图片尚未附加到GitHub。请复制或保存图片,然后在GitHub中附加。",
+ "Thread depth": "螺纹深度",
"Thread diameter": "螺纹直径",
"To": "终点",
"To Offset": "偏移",
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs
index 2204c19b49..25abbaa226 100644
--- a/crates/doc/src/document.rs
+++ b/crates/doc/src/document.rs
@@ -721,6 +721,11 @@ pub enum FeatureKind {
/// A cosmetic thread in the holes (e.g. "M6x1").
#[serde(default, skip_serializing_if = "Option::is_none")]
thread: Option<String>,
+ /// Threaded depth from the cylindrical wall's entry; `None` = its full useful length.
+ /// Independent of the drill depth and excluding the drill point and entry recess.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[walk(length = "Thread depth")]
+ thread_depth: Option<Expr>,
/// To Object: drill down to the face (or point) here instead of `depth`.
#[serde(default, skip_serializing_if = "Option::is_none")]
to: Option<FacePick>,
@@ -2024,12 +2029,20 @@ pub enum HoleKind {
cb_diameter: Expr,
#[walk(length = "Counterbore depth")]
cb_depth: Expr,
+ /// Optional drill point below the narrow cylindrical bore; absent stays flat.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[walk(angle = "Tip angle")]
+ tip_angle: Option<Expr>,
},
Countersink {
#[walk(length = "Countersink diameter")]
cs_diameter: Expr,
#[walk(angle = "Countersink angle")]
cs_angle: Expr,
+ /// Optional drill point, independent of the entry countersink.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[walk(angle = "Tip angle")]
+ tip_angle: Option<Expr>,
},
}
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index bcfdea4d24..a5b8f3ce84 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -4376,10 +4376,9 @@ fn hole_tools_and_prisms(
let prism = more::PrimitivePrism::Cylinder { base: *position + axis * lo, axis, radius: rad, height: hi - lo };
Ok((crate::lineage::part_tool(tool, part), Some(prism)))
};
- let mut tools = Vec::new();
- match hole {
- HoleKind::Simple => tools.push(cyl(r, bottom, top, "bore")?),
- HoleKind::Drilled { tip_angle } => {
+ // Reuse the existing drill-point tool for the narrow bore, independently of its entry.
+ let bore = |tip_angle: Option<&crate::Expr>| -> Result<Vec<(Traced, Option<more::PrimitivePrism>)>> {
+ if let Some(tip_angle) = tip_angle {
let half = val(vals, tip_angle, Kind::Angle)? / 2.0;
// A hole exactly as deep as the material: the point is in the air past the exit
// face, which would lie on the drill point's shoulder (a through hole, as drilled).
@@ -4395,25 +4394,28 @@ fn hole_tools_and_prisms(
let rp = Plane::new(*position, side, up).ok_or_else(|| DocError::Invalid("hole axis".into()))?;
let pts = [Vec2::new(0.0, top), Vec2::new(r, top), Vec2::new(r, bottom), Vec2::new(0.0, bottom - tip)];
let region = Region2 { outer: solidcraft_geom::Loop2::polygon(&pts), holes: vec![] };
- tools.extend(
- kernel::revolve(&rp, &[region], Vec2::ZERO, Vec2::Y, std::f64::consts::TAU)?
- .into_iter()
- .map(|tool| (crate::lineage::part_tool(tool, "bore"), None)),
- );
- } else {
- tools.push(cyl(r, bottom, top, "bore")?);
+ return Ok(kernel::revolve(&rp, &[region], Vec2::ZERO, Vec2::Y, std::f64::consts::TAU)?
+ .into_iter()
+ .map(|tool| (crate::lineage::part_tool(tool, "bore"), None))
+ .collect());
}
}
- HoleKind::Counterbore { cb_diameter, cb_depth } => {
+ Ok(vec![cyl(r, bottom, top, "bore")?])
+ };
+ let mut tools = Vec::new();
+ match hole {
+ HoleKind::Simple => tools.extend(bore(None)?),
+ HoleKind::Drilled { tip_angle } => tools.extend(bore(Some(tip_angle))?),
+ HoleKind::Counterbore { cb_diameter, cb_depth, tip_angle } => {
let (rc, dc) = (val(vals, cb_diameter, Kind::Length)? / 2.0, val(vals, cb_depth, Kind::Length)?);
if !(rc > r && dc > 0.0 && -dc > bottom) {
return Err(DocError::Invalid("the counterbore must be wider than the hole and shallower than it".into()));
}
// Wide and shallow first: the narrow hole then crosses the pocket floor.
tools.push(cyl(rc, -dc, top, "cbore")?);
- tools.push(cyl(r, bottom, top, "bore")?);
+ tools.extend(bore(tip_angle.as_ref())?);
}
- HoleKind::Countersink { cs_diameter, cs_angle } => {
+ HoleKind::Countersink { cs_diameter, cs_angle, tip_angle } => {
let (rc, half) = (val(vals, cs_diameter, Kind::Length)? / 2.0, val(vals, cs_angle, Kind::Angle)? / 2.0);
if !(rc > r && half > 1e-3 && half < std::f64::consts::FRAC_PI_2) {
return Err(DocError::Invalid("the countersink must be wider than the hole".into()));
@@ -4424,7 +4426,7 @@ fn hole_tools_and_prisms(
let len = (r_top - r_end) / half.tan();
let top_plane = plane.offset(top);
tools.push((crate::lineage::part_tool(kernel::extrude_tapered(&top_plane, &disc(r_top), len, -1.0, -half)?, "csink"), None));
- tools.push(cyl(r, bottom, top, "bore")?);
+ tools.extend(bore(tip_angle.as_ref())?);
}
}
Ok(tools)
@@ -6746,7 +6748,14 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:
}
apply_traced(st, f, tools, *operation, &crate::plain(targets))
}
- FeatureKind::Hole { thread, diameter, .. } => {
+ FeatureKind::Hole { thread, thread_depth, diameter, .. } => {
+ let thread_depth = thread_depth.as_ref().map(|d| val(vals, d, Kind::Length)).transpose()?;
+ if thread_depth.is_some() && thread.is_none() {
+ return Err(DocError::Invalid("thread depth requires a tapped hole".into()));
+ }
+ if thread_depth.is_some_and(|d| !d.is_finite() || d <= 0.0) {
+ return Err(DocError::Invalid("thread depth must be finite and positive".into()));
+ }
let (spots, dir) = hole_spots(vals, st, f)?;
let tools = hole_feature_tools(vals, st, f)?;
let handled = sheet_hole_cut(st, f, &tools, warning)?;
@@ -6757,16 +6766,33 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:
apply_beside_sheet_cut(st, f, tools, Operation::Cut, &[], &handled)?;
}
if let Some(d) = thread {
- // A point on each hole's wall, a little below the entry.
+ // Find the bore beyond any entry recess, including shallow and through holes.
let r = val(vals, diameter, Kind::Length)? / 2.0;
let parallel_pipe = crate::pipe_thread_catalog::parse_pipe_thread(d).is_some();
for p in spots {
let wall = if parallel_pipe {
parallel_tapped_wall(st, p, dir, r).ok_or_else(|| DocError::Invalid("no cylindrical pipe-thread wall remains".into()))?
} else {
- p + dir.any_perp() * r + dir * (r * 0.5)
+ parallel_tapped_wall(st, p, dir, r).unwrap_or(p + dir.any_perp() * r + dir * (r * 0.5))
};
- let t = thread_on_impl(st, f.id, wall, Some(d), None, true, false)?;
+ let mut t = thread_on_impl(st, f.id, wall, Some(d), None, true, false)?;
+ if let Some(depth) = thread_depth {
+ let available = t.end - t.start;
+ if depth > available {
+ return Err(DocError::Invalid(format!(
+ "thread depth {} mm exceeds the cylindrical wall's useful length of {} mm; reduce the thread depth or use full thread depth",
+ show_mm(depth),
+ show_mm(available)
+ )));
+ }
+ // Start at the entry in the drilling direction, independently of the
+ // wall probe's position and the cylinder surface's axis orientation.
+ if dir.dot(t.axis) > 0.0 {
+ t.end = t.start + depth;
+ } else {
+ t.start = t.end - depth;
+ }
+ }
st.threads.push(t);
}
}
diff --git a/crates/doc/src/format/pending/recessed-hole-drill-point.rs b/crates/doc/src/format/pending/recessed-hole-drill-point.rs
new file mode 100644
index 0000000000..9bb2ef7b2f
--- /dev/null
+++ b/crates/doc/src/format/pending/recessed-hole-drill-point.rs
@@ -0,0 +1,3 @@
+//! Counterbore and countersink holes may store an optional nested `tip_angle` for the
+//! narrow bore's drill point. Missing values retain the previous flat bottom. No rewrite
+//! is needed; the entry recess and depth-to-shoulder semantics remain unchanged.
diff --git a/crates/doc/src/format/pending/tapped-hole-thread-depth.rs b/crates/doc/src/format/pending/tapped-hole-thread-depth.rs
new file mode 100644
index 0000000000..8c7bf62888
--- /dev/null
+++ b/crates/doc/src/format/pending/tapped-hole-thread-depth.rs
@@ -0,0 +1,5 @@
+//! Tapped holes may store `thread_depth`, a length expression independent of the drill depth.
+//! An absent value retains the full useful cylindrical wall used by older designs. An explicit
+//! depth starts at that wall's entry, excludes the drill point and entry recess, and is refused
+//! when it is not positive and finite or exceeds the available cylindrical wall. Older readers
+//! would ignore the quota and describe a full-depth thread, so the design format must advance.
diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs
index 8b4da92014..6159c30322 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: metric major minus pitch or tabulated UNC/UNF, G or Rp cut-tap drill) | 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\" or \"1/4-20 UNC\" (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: metric major minus pitch or tabulated UNC/UNF, G or Rp cut-tap drill) | 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\" or \"1/4-20 UNC\" (cosmetic); thread_depth?: positive length independent of drill depth (default: full useful cylindrical wall; must fit that wall); 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")
@@ -2062,6 +2062,19 @@ fn hole(s: &mut Session, p: &Value) -> Result<Value> {
fine_only_hint(t).unwrap_or_else(|| format!("unknown tapped thread `{t}` (ISO metric or a catalogued UNC/UNF, G or Rp size)")),
));
}
+ let thread_depth = match p.get("thread_depth") {
+ None | Some(Value::Null) => None,
+ Some(_) => Some(req_expr(cmd, p, "thread_depth")?),
+ };
+ if let Some(d) = &thread_depth {
+ if thread.is_none() {
+ return Err(bad(cmd, "`thread_depth` requires `thread` (a tapped hole)"));
+ }
+ let depth = s.doc.eval(d, Kind::Length).map_err(|e| bad(cmd, format!("`thread_depth`: {e}")))?;
+ if !depth.is_finite() || depth <= 0.0 {
+ return Err(bad(cmd, "`thread_depth` must be finite and positive"));
+ }
+ }
// A position given as length expressions (#1678), say `["leg_h*0.4", "width/2", "t"]`: kept,
// so the hole follows the parameters; drilled where they evaluate now.
let at: Option<solidcraft_doc::PointExpr> = match p.get("position").and_then(Value::as_array) {
@@ -2158,10 +2171,13 @@ fn hole(s: &mut Session, p: &Value) -> Result<Value> {
_ => solidcraft_doc::HoleKind::Simple,
},
"drilled" => solidcraft_doc::HoleKind::Drilled { tip_angle: expr(p, "tip_angle").unwrap_or_else(|| "118 deg".into()) },
- "counterbore" => solidcraft_doc::HoleKind::Counterbore { cb_diameter: get("cb_diameter")?, cb_depth: get("cb_depth")? },
+ "counterbore" => {
+ solidcraft_doc::HoleKind::Counterbore { cb_diameter: get("cb_diameter")?, cb_depth: get("cb_depth")?, tip_angle: expr(p, "tip_angle") }
+ }
"countersink" => solidcraft_doc::HoleKind::Countersink {
cs_diameter: get("cs_diameter")?,
cs_angle: expr(p, "cs_angle").unwrap_or_else(|| "90 deg".into()),
+ tip_angle: expr(p, "tip_angle"),
},
other => return Err(bad(cmd, format!("unknown hole type `{other}`"))),
};
@@ -2201,6 +2217,7 @@ fn hole(s: &mut Session, p: &Value) -> Result<Value> {
hole: kind,
points: points.map(|x| x.0),
thread,
+ thread_depth,
to: to.map(FacePick),
references,
},
diff --git a/crates/engine/src/hole_matrix_tests.rs b/crates/engine/src/hole_matrix_tests.rs
index 610fbddca0..5898647ee4 100644
--- a/crates/engine/src/hole_matrix_tests.rs
+++ b/crates/engine/src/hole_matrix_tests.rs
@@ -801,3 +801,58 @@ fn hole_matrix() {
report.join(" | ")
);
}
+
+#[test]
+fn recessed_drill_point_geometry_roundtrip_preview_and_undo() {
+ for kind in ["counterbore", "countersink"] {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length":40,"width":30,"height":20})).unwrap();
+ let mut p = json!({"position":[20,15,20],"direction":[0,0,-1],"diameter":6,"depth":8,"type":kind,"cb_diameter":12,"cb_depth":3,"cs_diameter":12,"cs_angle":"90 deg"});
+ let hole = run(&mut s, "solid.hole", p.clone()).unwrap()["feature"].as_u64().unwrap();
+ let probe = Vec3::new(20.0, 15.0, 11.5);
+ assert!(solid_at(&s, probe), "legacy absent tip is flat");
+ let mut legacy: Value = serde_json::from_str(&s.doc.to_json()).unwrap();
+ legacy["format"] = json!("solidcraft/30");
+ legacy.as_object_mut().unwrap().remove("format_pending");
+ let old = Session::new(solidcraft_doc::Document::from_json(&legacy.to_string()).unwrap());
+ assert!(solid_at(&old, probe), "format-30 recessed holes keep their flat bottom");
+ p["tip_angle"] = json!("118 deg");
+ run(&mut s, "timeline.redefine", json!({"feature":hole,"command":"solid.hole","params":p})).unwrap();
+ assert!(!solid_at(&s, probe), "{kind}: drill point must remove the axis below the shoulder");
+ assert!(solid_at(&s, Vec3::new(23.1, 15.0, 11.5)), "point must not widen the cylindrical bore");
+ let saved = s.doc.to_json();
+ let loaded = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap());
+ assert!(!solid_at(&loaded, probe), "chosen bottom must survive reopen");
+ p.as_object_mut().unwrap().remove("tip_angle");
+ let redefine = json!({"feature":hole,"command":"solid.hole","params":p});
+ let preview = s.preview(&[("timeline.redefine".into(), redefine.clone())]).unwrap();
+ assert!(preview.after.bodies.iter().any(|b| b.body.contains(probe)));
+ assert_eq!(s.doc.to_json(), saved, "preview cannot accept the bottom change");
+ run(&mut s, "timeline.redefine", redefine).unwrap();
+ assert!(solid_at(&s, probe));
+ run(&mut s, "edit.undo", json!({})).unwrap();
+ assert!(!solid_at(&s, probe));
+ run(&mut s, "edit.redo", json!({})).unwrap();
+ assert!(solid_at(&s, probe));
+ }
+}
+
+#[test]
+fn recessed_drill_point_through_and_exact_shoulder_keep_the_existing_exit() {
+ for kind in ["counterbore", "countersink"] {
+ for exact in [false, true] {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length":40,"width":30,"height":20})).unwrap();
+ let mut p = json!({"position":[20,15,20],"direction":[0,0,-1],"diameter":6,"type":kind,"cb_diameter":12,"cb_depth":3,"cs_diameter":12,"cs_angle":"90 deg"});
+ if exact {
+ p["depth"] = json!(20);
+ }
+ let hole = run(&mut s, "solid.hole", p.clone()).unwrap()["feature"].as_u64().unwrap();
+ let flat = measure(&mut s).unwrap().0;
+ p["tip_angle"] = json!("118 deg");
+ run(&mut s, "timeline.redefine", json!({"feature":hole,"command":"solid.hole","params":p})).unwrap();
+ assert!((measure(&mut s).unwrap().0 - flat).abs() < 1e-6, "point beyond the exit must not change the part");
+ assert!(!solid_at(&s, Vec3::new(20.0, 15.0, 0.01)));
+ }
+ }
+}
diff --git a/crates/engine/src/thread_tests.rs b/crates/engine/src/thread_tests.rs
index 52b10e8bf7..3bc55c4e0d 100644
--- a/crates/engine/src/thread_tests.rs
+++ b/crates/engine/src/thread_tests.rs
@@ -24,6 +24,132 @@ fn volume(s: &mut Session, b: &str) -> f64 {
const SIZES: [(f64, f64); 9] = [(3.0, 0.5), (4.0, 0.7), (5.0, 0.8), (6.0, 1.0), (8.0, 1.25), (10.0, 1.5), (12.0, 1.75), (16.0, 2.0), (20.0, 2.5)];
+fn assert_tapped_depth(state: &solidcraft_doc::ModelState, entry: Vec3, inward: Vec3, offset: f64, depth: f64) {
+ assert_eq!(state.threads.len(), 1);
+ let thread = &state.threads[0];
+ assert!(thread.internal);
+ let a = (thread.axis_point + thread.axis * thread.start - entry).dot(inward);
+ let b = (thread.axis_point + thread.axis * thread.end - entry).dot(inward);
+ assert!((a.min(b) - offset).abs() < 1e-6, "thread entry {} mm, expected {offset} mm", a.min(b));
+ assert!((a.max(b) - offset - depth).abs() < 1e-6, "thread end {} mm, expected {} mm", a.max(b), offset + depth);
+}
+
+#[test]
+fn tapped_thread_depth_keeps_reference_edge_placement_after_reopen() {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length":60,"width":60,"height":12}));
+ run(
+ &mut s,
+ "solid.hole",
+ json!({"position":[30,30,12],"thread":"M6","depth":8,"thread_depth":3,
+ "references":[{"edge":[0,25,12],"distance":"10 mm"},{"edge":[25,0,12],"distance":"12 mm"}]}),
+ );
+ let inward = Vec3::new(0.0, 0.0, -1.0);
+ let entry = Vec3::new(10.0, 12.0, 12.0);
+ assert_tapped_depth(&s.model.state(), entry, inward, 0.0, 3.0);
+ let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());
+ assert_tapped_depth(&reopened.model.state(), entry, inward, 0.0, 3.0);
+ let solidcraft_doc::FeatureKind::Hole { references, thread_depth, .. } = &reopened.doc.features.last().unwrap().kind else {
+ panic!("expected a referenced tapped hole");
+ };
+ assert_eq!(references.len(), 2);
+ assert_eq!(thread_depth.as_ref().unwrap().to_string(), "3");
+ assert!(!reopened.model.state().bodies[0].body.contains(Vec3::new(10.0, 12.0, 10.0)));
+}
+
+#[test]
+fn tapped_thread_depth_is_independent_through_preview_redefine_undo_and_reload() {
+ for (height, mut params, full) in
+ [(12.0, json!({"depth":8,"type":"drilled"}), 8.0), (12.0, json!({}), 12.0), (12.0, json!({"to":[30,30,5]}), 7.0)]
+ {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length":60,"width":60,"height":height,"body_name":"Plate"}));
+ params["position"] = json!([30, 30, height]);
+ params["direction"] = json!([0, 0, -1]);
+ params["thread"] = json!("M6");
+ let hole = run(&mut s, "solid.hole", params.clone())["feature"].as_u64().unwrap();
+ let entry = Vec3::new(30.0, 30.0, height);
+ let inward = Vec3::new(0.0, 0.0, -1.0);
+ assert_tapped_depth(&s.model.state(), entry, inward, 0.0, full);
+ let before = s.doc.to_json();
+ let physical_volume = volume(&mut s, "Plate");
+
+ // Version 29 never saved this field: its default remains the full wall.
+ let mut legacy: Value = serde_json::from_str(&before).unwrap();
+ legacy["format"] = json!("solidcraft/29");
+ let reopened = Session::new(solidcraft_doc::Document::from_json(&legacy.to_string()).unwrap());
+ assert_tapped_depth(&reopened.model.state(), entry, inward, 0.0, full);
+
+ params["thread_depth"] = json!(4);
+ let redefine = json!({"feature":hole,"command":"solid.hole","params":params});
+ let preview = s.preview(&[("timeline.redefine".into(), redefine.clone())]).unwrap();
+ assert_tapped_depth(&preview.after, entry, inward, 0.0, 4.0);
+ assert_eq!(s.doc.to_json(), before, "preview must not change the design");
+ run(&mut s, "timeline.redefine", redefine);
+ assert_tapped_depth(&s.model.state(), entry, inward, 0.0, 4.0);
+ assert!((volume(&mut s, "Plate") - physical_volume).abs() < 1e-6, "thread depth must not change the drill geometry");
+ let saved = s.doc.to_json();
+ let reopened = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap());
+ assert_tapped_depth(&reopened.model.state(), entry, inward, 0.0, 4.0);
+ run(&mut s, "edit.undo", json!({}));
+ assert_eq!(s.doc.to_json(), before);
+ assert_tapped_depth(&s.model.state(), entry, inward, 0.0, full);
+ }
+}
+
+#[test]
+fn tapped_thread_depth_uses_the_cylinder_beyond_recesses_and_in_shallow_holes() {
+ for (height, mut params, offset, full) in [
+ (12.0, json!({"thread":"M6","type":"counterbore","cb_diameter":12,"cb_depth":5,"depth":9}), 5.0, 4.0),
+ (12.0, json!({"thread":"G 1/4","type":"counterbore","cb_diameter":20,"cb_depth":5,"depth":9}), 5.0, 4.0),
+ (12.0, json!({"thread":"1/4-20 UNC","type":"counterbore","cb_diameter":12,"cb_depth":5,"depth":9}), 5.0, 4.0),
+ (12.0, json!({"thread":"M6","type":"countersink","cs_diameter":11,"cs_angle":"90 deg","depth":9}), 3.0, 6.0),
+ (12.0, json!({"thread":"M36","type":"drilled","depth":3}), 0.0, 3.0),
+ (5.0, json!({"thread":"M36"}), 0.0, 5.0),
+ ] {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length":60,"width":60,"height":height,"body_name":"Plate"}));
+ params["position"] = json!([30, 30, height]);
+ params["direction"] = json!([0, 0, -1]);
+ let hole = run(&mut s, "solid.hole", params.clone())["feature"].as_u64().unwrap();
+ let entry = Vec3::new(30.0, 30.0, height);
+ let inward = Vec3::new(0.0, 0.0, -1.0);
+ assert_tapped_depth(&s.model.state(), entry, inward, offset, full);
+ params["thread_depth"] = json!(2);
+ run(&mut s, "timeline.redefine", json!({"feature":hole,"command":"solid.hole","params":params}));
+ assert_tapped_depth(&s.model.state(), entry, inward, offset, 2.0);
+ }
+}
+
+#[test]
+fn tapped_thread_depth_starts_at_the_entry_for_both_axis_directions() {
+ for (entry, inward) in [(Vec3::new(0.0, 10.0, 6.0), Vec3::new(1.0, 0.0, 0.0)), (Vec3::new(20.0, 10.0, 6.0), Vec3::new(-1.0, 0.0, 0.0))] {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length":20,"width":20,"height":12}));
+ run(
+ &mut s,
+ "solid.hole",
+ json!({"position":[entry.x,entry.y,entry.z],"direction":[inward.x,inward.y,inward.z],"thread":"M6","depth":8,"thread_depth":3}),
+ );
+ assert_tapped_depth(&s.model.state(), entry, inward, 0.0, 3.0);
+ }
+}
+
+#[test]
+fn tapped_thread_depth_rejects_invalid_or_excessive_values_atomically() {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length":20,"width":20,"height":10}));
+ let before = s.doc.to_json();
+ for depth in [json!(0), json!(-1), json!(20), json!(true), json!(""), json!("NaN mm"), json!("1e999 mm"), json!("3 deg")] {
+ let result = s.execute("solid.hole", &json!({"position":[10,10,10],"thread":"M6","depth":8,"thread_depth":depth}));
+ assert!(result.is_err(), "invalid thread depth {depth}: {result:?}");
+ assert_eq!(s.doc.to_json(), before);
+ assert!(s.model.state().threads.is_empty());
+ }
+ assert!(s.execute("solid.hole", &json!({"position":[10,10,10],"diameter":5,"thread_depth":3})).is_err());
+ assert_eq!(s.doc.to_json(), before);
+}
+
/// Keep the original 48-station reproduction of the shell error even though new fine
/// threads now use more stations. The same cut polygons must rebuild as a closed solid.
#[test]
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 8afc9c605c..3ae6349d26 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -405,6 +405,9 @@ pub struct HoleOpts {
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>,
+ /// Use the full useful cylindrical wall, independently of the drill extents.
+ pub thread_full_depth: bool,
+ pub thread_depth: String,
}
impl Default for HoleOpts {
@@ -418,6 +421,8 @@ impl Default for HoleOpts {
thread: "M5".into(),
custom_thread: None,
refs: Default::default(),
+ thread_full_depth: true,
+ thread_depth: "10 mm".into(),
}
}
}
@@ -3955,7 +3960,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result<Vec<(String, Value)>, S
} else if !opts.all {
params["depth"] = json!(depth);
}
- if ty == "drilled" {
+ if ty == "drilled" || (opts.angled && !opts.all) {
params["tip_angle"] = json!(opts.tip_angle);
}
if opts.tapped {
@@ -3965,6 +3970,9 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result<Vec<(String, Value)>, S
solidcraft_engine::doc::parse_tapped_thread(&opts.thread)
.ok_or("select a valid metric or catalogued UNC/UNF, G or Rp thread size")?;
params["thread"] = json!(opts.thread.trim());
+ if !opts.thread_full_depth {
+ params["thread_depth"] = json!(opts.thread_depth.trim());
+ }
}
match *kind {
1 => {
@@ -4724,7 +4732,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option<usize>) -> Option<Dia
d.extra.insert("pull".into(), pt3(pull.0));
d
}
- FeatureKind::Hole { position, at, direction, diameter, depth, hole, points, thread, to, references } => {
+ FeatureKind::Hole { position, at, direction, diameter, depth, hole, points, thread, thread_depth, 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 {
@@ -4736,19 +4744,31 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option<usize>) -> Option<Dia
opts.tapped = true;
opts.thread = th.clone();
}
+ opts.thread_full_depth = thread_depth.is_none();
+ if let Some(depth) = thread_depth {
+ opts.thread_depth = depth.to_string();
+ }
if let Some(dd) = depth {
*dep = dd.to_string();
}
match hole {
- HoleKind::Counterbore { cb_diameter: a, cb_depth: b } => {
+ HoleKind::Counterbore { cb_diameter: a, cb_depth: b, tip_angle } => {
*kind = 1;
*cb_diameter = a.to_string();
*cb_depth = b.to_string();
+ if let Some(angle) = tip_angle {
+ opts.angled = true;
+ opts.tip_angle = angle.to_string();
+ }
}
- HoleKind::Countersink { cs_diameter: a, cs_angle: b } => {
+ HoleKind::Countersink { cs_diameter: a, cs_angle: b, tip_angle } => {
*kind = 2;
*cs_diameter = a.to_string();
*cs_angle = b.to_string();
+ if let Some(angle) = tip_angle {
+ opts.angled = true;
+ opts.tip_angle = angle.to_string();
+ }
}
HoleKind::Drilled { tip_angle } => {
opts.tip_angle = tip_angle.to_string();
@@ -5355,6 +5375,34 @@ mod refused_ok_tests {
steps(h, &[json!({"click": {"handle": "dialog:Depth"}}), json!({"key": "A", "cmd": true}), json!({"text": depth})]);
}
+ #[test]
+ fn recessed_drill_point_controls_and_payload_follow_the_bottom_choice() {
+ for recessed in [1, 2] {
+ let mut h = hole_dialog();
+ if let Kind::Hole { kind, opts, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
+ *kind = recessed;
+ opts.angled = true;
+ opts.tip_angle = "118 deg".into();
+ }
+ h.frames(2);
+ assert!(crate::scenario::rect_of("dialog:widget:Drill Point").is_some());
+ assert!(crate::scenario::rect_of("dialog:widget:Tip Angle").is_some());
+ let commands = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap();
+ assert_eq!(commands[0].1["tip_angle"], "118 deg");
+ if let Kind::Hole { opts, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
+ opts.angled = false;
+ }
+ h.frames(2);
+ assert!(crate::scenario::rect_of("dialog:widget:Tip Angle").is_none());
+ assert!(apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap()[0].1.get("tip_angle").is_none());
+ if let Kind::Hole { opts, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
+ opts.all = true;
+ }
+ h.frames(2);
+ assert!(crate::scenario::rect_of("dialog:widget:Drill Point").is_none());
+ }
+ }
+
/// What the dialog shows in red once the live preview has finished: its own error, else the
/// preview's.
fn shown(h: &mut Harness) -> Option<String> {
diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs
index cdc5b01f5f..f22aefd8bf 100644
--- a/crates/ui-egui/src/dialogs_dense.rs
+++ b/crates/ui-egui/src/dialogs_dense.rs
@@ -524,9 +524,10 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui:
});
if opts.tapped {
enter |= crate::dialogs_thread::hole_rows(ui, &app.session.doc, &mut opts.thread, &mut opts.custom_thread);
+ ui_kit::checkbox_grid(ui, &mut [("Full thread depth", &mut opts.thread_full_depth)], 1);
}
// Through all, the tip lies past the part.
- if *kind == 0 && !opts.all {
+ if !opts.all {
form_row(ui, "Drill Point", |ui| {
let mut tip = usize::from(opts.angled);
combo(ui, "hole_tip", &["Flat", "Angle"], &mut tip);
diff --git a/crates/ui-egui/src/dialogs_hole.rs b/crates/ui-egui/src/dialogs_hole.rs
index 3326cdb33f..8180659975 100644
--- a/crates/ui-egui/src/dialogs_hole.rs
+++ b/crates/ui-egui/src/dialogs_hole.rs
@@ -19,6 +19,7 @@ pub(crate) enum Dim {
CbDepth,
CsAngle,
Depth,
+ ThreadDepth,
Diameter,
TipAngle,
}
@@ -32,6 +33,7 @@ impl Dim {
Dim::CbDepth => "Counterbore depth",
Dim::CsAngle => "Countersink angle",
Dim::Depth => "Depth",
+ Dim::ThreadDepth => "Thread depth",
Dim::Diameter => "Diameter",
Dim::TipAngle => "Tip Angle",
}
@@ -39,8 +41,8 @@ impl Dim {
}
/// The sizes a hole of type `kind` takes, top to bottom: a depth unless it goes through all or
-/// to an object, a diameter unless it is tapped (the thread sets it), a tip angle for an angled
-/// tip at the bottom of a blind simple hole.
+/// to an object, a diameter unless tapped, and a tip angle for an angled bottom
+/// independently of the entry recess.
pub(crate) fn dims(kind: usize, opts: &HoleOpts, to_object: bool) -> Vec<Dim> {
let mut v = match kind {
1 => vec![Dim::TopDiameter, Dim::CbDepth],
@@ -50,15 +52,31 @@ pub(crate) fn dims(kind: usize, opts: &HoleOpts, to_object: bool) -> Vec<Dim> {
if !opts.all && !to_object {
v.push(Dim::Depth);
}
+ if opts.tapped && !opts.thread_full_depth {
+ v.push(Dim::ThreadDepth);
+ }
if !opts.tapped {
v.push(Dim::Diameter);
}
- if kind == 0 && opts.angled && !opts.all {
+ if opts.angled && !opts.all {
v.push(Dim::TipAngle);
}
v
}
+/// Tapped bores use the engine's catalogued cut-tap drill, including Unified and parallel pipe sizes.
+/// A custom draft with an error must not illustrate its stale, last valid designation.
+fn bore_diameter(diameter: &str, opts: &HoleOpts, eval: &dyn Fn(&str, ValueKind) -> Option<f64>) -> Option<f64> {
+ if opts.tapped {
+ if opts.custom_thread.as_ref().is_some_and(|draft| draft.error.is_some()) {
+ return None;
+ }
+ solidcraft_engine::doc::parse_tapped_thread(&opts.thread).map(|size| size.tap_drill)
+ } else {
+ eval(diameter, ValueKind::Length).filter(|v| v.is_finite() && *v > 0.0)
+ }
+}
+
/// What the picture is drawn from.
struct Section {
kind: usize,
@@ -66,6 +84,9 @@ struct Section {
to_object: bool,
angled: bool,
tapped: bool,
+ /// A schematic fraction: known blind extents use the entered lengths. To Object and
+ /// Through All have no typed drill length, so partial tapping is shown as a shorter span.
+ thread_fraction: f32,
/// The bore's diameter over the counterbore's or countersink's (1 for a simple hole).
ratio: f32,
/// Half the countersink's and the tip's angles (radians).
@@ -82,7 +103,8 @@ pub(crate) fn rows(ui: &mut egui::Ui, k: &mut Kind, to_object: bool, eval: &dyn
let len = |e: &str| eval(e, ValueKind::Length).filter(|v| v.is_finite() && *v > 0.0);
let angle = |e: &str, lo: f64, hi: f64, or: f64| eval(e, ValueKind::Angle).filter(|v| v.is_finite()).map_or(or, |v| (v / 2.0).clamp(lo, hi));
let top = if kind == 2 { cs_diameter.as_str() } else { cb_diameter.as_str() };
- let ratio = match (len(diameter.as_str()), len(top)) {
+ let bore = bore_diameter(diameter, opts, eval);
+ let ratio = match (bore, len(top)) {
(Some(d), Some(t)) if kind != 0 => (d / t).clamp(0.3, 0.8) as f32,
_ if kind != 0 => 0.55,
_ => 1.0,
@@ -91,8 +113,26 @@ pub(crate) fn rows(ui: &mut egui::Ui, k: &mut Kind, to_object: bool, eval: &dyn
kind,
through: opts.all,
to_object,
- angled: kind == 0 && opts.angled,
+ angled: opts.angled,
tapped: opts.tapped,
+ thread_fraction: if opts.thread_full_depth {
+ 1.0
+ } else if !opts.all && !to_object {
+ let recess = match kind {
+ 1 => len(cb_depth.as_str()).unwrap_or(0.0),
+ 2 => match (bore, len(cs_diameter.as_str())) {
+ (Some(d), Some(top)) => (top - d).max(0.0) / (2.0 * angle(cs_angle.as_str(), 0.35, 1.3, std::f64::consts::FRAC_PI_4).tan()),
+ _ => 0.0,
+ },
+ _ => 0.0,
+ };
+ match (len(opts.thread_depth.as_str()), len(depth.as_str()).filter(|d| *d > recess)) {
+ (Some(thread), Some(drill)) => (thread / (drill - recess)).clamp(0.05, 1.0) as f32,
+ _ => 0.55,
+ }
+ } else {
+ 0.55
+ },
ratio,
cs_half: angle(cs_angle.as_str(), 0.35, 1.3, std::f64::consts::FRAC_PI_4) as f32,
tip_half: angle(opts.tip_angle.as_str(), 0.5, 1.3, 1.03) as f32,
@@ -113,6 +153,9 @@ pub(crate) fn rows(ui: &mut egui::Ui, k: &mut Kind, to_object: bool, eval: &dyn
if dims.contains(&Dim::Depth) {
fields.push((Dim::Depth.label(kind), depth));
}
+ if dims.contains(&Dim::ThreadDepth) {
+ fields.push((Dim::ThreadDepth.label(kind), &mut opts.thread_depth));
+ }
if dims.contains(&Dim::Diameter) {
fields.push((Dim::Diameter.label(kind), diameter));
}
@@ -135,8 +178,15 @@ fn head(p: &egui::Painter, tip: Pos2, from: Pos2, col: Color32) {
/// A dimension line from `a` to `b` with arrowheads at both ends.
fn dimension(p: &egui::Painter, a: Pos2, b: Pos2, stroke: Stroke) {
p.line_segment([a, b], stroke);
- head(p, a, b, stroke.color);
- head(p, b, a, stroke.color);
+ if a.distance(b) < 14.0 {
+ // Short partial depths need outward arrows rather than overlapping heads.
+ let d = (b - a).normalized();
+ head(p, a, a - d * 8.0, stroke.color);
+ head(p, b, b + d * 8.0, stroke.color);
+ } else {
+ head(p, a, b, stroke.color);
+ head(p, b, a, stroke.color);
+ }
}
/// An arc about `c` of radius `r` between the directions at `from` and `to` (radians, screen y
@@ -187,9 +237,10 @@ fn paint(p: &egui::Painter, pic: Rect, s: &Section, slots: &[(Dim, Rect, bool)])
};
// Across: the axis, the widest half width, the material's sides; the vertical dimensions sit
// right of the material, before the fields.
- let cx = pic.left() + 44.0;
- let wide = 24.0;
- let (left, right) = (pic.left() + 6.0, pic.left() + 76.0);
+ // Leave three separate depth lanes inside the picture even on a narrow form.
+ let cx = pic.left() + pic.width() * 0.40;
+ let wide = pic.width() * 0.20;
+ let (left, right) = (pic.left() + pic.width() * 0.04, pic.left() + pic.width() * 0.68);
let bottom = pic.bottom() - 3.0;
let top_r = wide;
let bore_r = if s.kind == 0 { wide * 0.55 } else { wide * s.ratio };
@@ -205,7 +256,7 @@ fn paint(p: &egui::Painter, pic: Rect, s: &Section, slots: &[(Dim, Rect, bool)])
bottom + 1.0
} else {
let mut y = step + 18.0;
- for d in [Dim::Depth, Dim::Diameter] {
+ for d in [Dim::Depth, Dim::ThreadDepth, Dim::Diameter] {
if let Some(v) = y_of(d) {
y = y.max(v + 10.0);
}
@@ -242,12 +293,15 @@ fn paint(p: &egui::Painter, pic: Rect, s: &Section, slots: &[(Dim, Rect, bool)])
p.add(Shape::convex_polygon(vec![pos2(cx - bore_r, shoulder), pos2(cx + bore_r, shoulder), apex], clear, Stroke::NONE));
}
// A tapped hole's thread: thin lines at the thread's major diameter, in the material.
+ let thread_start = step + 2.0;
+ let thread_end = thread_start + ((if s.through { bottom } else { shoulder - 3.0 }) - thread_start).max(0.0) * s.thread_fraction;
if s.tapped {
let r = bore_r * 1.22;
- let (y0, y1) = (half.iter().rev().nth(1).map_or(top, |x| x.1), if s.through { bottom } else { shoulder - 3.0 });
for x in [cx - r, cx + r] {
- p.line_segment([pos2(x, y0 + 2.0), pos2(x, y1)], Stroke::new(1.0, t.form_ink));
+ p.line_segment([pos2(x, thread_start), pos2(x, thread_end)], Stroke::new(1.0, t.form_ink));
}
+ p.line_segment([pos2(cx - r, thread_end), pos2(cx - bore_r, thread_end)], Stroke::new(1.0, t.form_ink));
+ p.line_segment([pos2(cx + bore_r, thread_end), pos2(cx + r, thread_end)], Stroke::new(1.0, t.form_ink));
}
// Outlines: the block's top and sides, the hole's walls and bottom.
let edge = Stroke::new(1.4, t.form_ink);
@@ -289,13 +343,20 @@ fn paint(p: &egui::Painter, pic: Rect, s: &Section, slots: &[(Dim, Rect, bool)])
leader(Dim::TopDiameter, b);
}
// Depths stand right of the material: the counterbore's nearer, the hole's farther out.
- let mut x = right + 8.0;
+ let mut x = right + pic.width() * 0.07;
if let Some(y) = y_of(Dim::CbDepth) {
p.line_segment([pos2(cx + top_r, step), pos2(x + 3.0, step)], thin(Dim::CbDepth));
p.line_segment([pos2(right, top), pos2(x + 3.0, top)], thin(Dim::CbDepth));
dimension(p, pos2(x, top), pos2(x, step), ink(Dim::CbDepth));
leader(Dim::CbDepth, pos2(x, y.clamp(top + 2.0, step - 2.0)));
- x += 10.0;
+ x += pic.width() * 0.10;
+ }
+ if let Some(y) = y_of(Dim::ThreadDepth) {
+ p.line_segment([pos2(cx + bore_r * 1.22, thread_start), pos2(x + 3.0, thread_start)], thin(Dim::ThreadDepth));
+ p.line_segment([pos2(cx + bore_r * 1.22, thread_end), pos2(x + 3.0, thread_end)], thin(Dim::ThreadDepth));
+ dimension(p, pos2(x, thread_start), pos2(x, thread_end), ink(Dim::ThreadDepth));
+ leader(Dim::ThreadDepth, pos2(x, y.clamp(thread_start, thread_end.max(thread_start))));
+ x += pic.width() * 0.10;
}
if let Some(y) = y_of(Dim::Depth) {
p.line_segment([pos2(cx + bore_r, shoulder), pos2(x + 3.0, shoulder)], thin(Dim::Depth));
@@ -334,6 +395,125 @@ fn paint(p: &egui::Painter, pic: Rect, s: &Section, slots: &[(Dim, Rect, bool)])
mod tests {
use super::*;
+ #[test]
+ fn recessed_drill_point_total_depth_dimension_is_outside_partial_tapping() {
+ for kind in [1, 2] {
+ for width in [80.0, 120.0] {
+ for fraction in [0.05, 0.5] {
+ let ctx = crate::fonts::test_context();
+ let pic = Rect::from_min_size(pos2(10.0, 10.0), vec2(width, 200.0));
+ let section = Section {
+ kind,
+ through: false,
+ to_object: false,
+ angled: false,
+ tapped: true,
+ thread_fraction: fraction,
+ ratio: 0.5,
+ cs_half: std::f32::consts::FRAC_PI_4,
+ tip_half: 1.03,
+ };
+ let slots = [
+ (Dim::TopDiameter, 25.0),
+ (if kind == 1 { Dim::CbDepth } else { Dim::CsAngle }, 60.0),
+ (Dim::Depth, 105.0),
+ (Dim::ThreadDepth, 145.0),
+ ]
+ .map(|(dim, y)| (dim, Rect::from_min_size(pos2(150.0, y), vec2(100.0, 20.0)), false));
+ let output = ctx.run_ui(egui::RawInput::default(), |ui| paint(ui.painter(), pic, &section, &slots));
+ let mut dimensions: Vec<_> = output
+ .shapes
+ .iter()
+ .filter_map(|clipped| match &clipped.shape {
+ Shape::LineSegment { points, stroke }
+ if (stroke.width - 1.0).abs() < 1e-4
+ && (points[0].x - points[1].x).abs() < 1e-4
+ && points[0].x > pic.left() + width * 0.68
+ && (points[0].y - points[1].y).abs() > 0.5 =>
+ {
+ Some((points[0].x, (points[0].y - points[1].y).abs()))
+ }
+ _ => None,
+ })
+ .collect();
+ assert!(dimensions.len() >= 2, "both total and partial depths must be drawn");
+ dimensions.sort_by(|a, b| b.1.total_cmp(&a.1));
+ let total = dimensions[0];
+ assert!(dimensions.iter().skip(1).all(|shorter| total.0 > shorter.0), "longest drill depth must be outside: {dimensions:?}");
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn tapped_section_uses_the_current_nominal_size_and_pitch() {
+ let mut opts = HoleOpts { tapped: true, thread: "M8".into(), ..HoleOpts::default() };
+ let stale_diameter = |_: &str, _: ValueKind| Some(4.0);
+ assert_eq!(bore_diameter("4 mm", &opts, &stale_diameter), Some(6.75));
+ opts.thread = "M8x1.2".into();
+ assert_eq!(bore_diameter("4 mm", &opts, &stale_diameter), Some(6.8));
+ for (designation, drill) in [("G 1/4", 11.75), ("Rp 1/4", 11.4), ("1/4-20 UNC", 5.1054)] {
+ opts.thread = designation.into();
+ assert_eq!(bore_diameter("4 mm", &opts, &stale_diameter), Some(drill), "{designation}");
+ }
+ opts.thread = "invalid".into();
+ assert_eq!(bore_diameter("4 mm", &opts, &stale_diameter), None);
+ opts.tapped = false;
+ assert_eq!(bore_diameter("4 mm", &opts, &stale_diameter), Some(4.0));
+ }
+
+ #[test]
+ fn partial_tapping_has_an_independent_dimension_for_every_extent() {
+ for kind in 0..=2 {
+ for through in [false, true] {
+ let mut opts = HoleOpts { tapped: true, thread_full_depth: false, all: through, ..HoleOpts::default() };
+ for to_object in [false, true] {
+ let labels: Vec<_> = dims(kind, &opts, to_object).into_iter().map(|d| d.label(kind)).collect();
+ assert!(labels.contains(&"Thread depth"), "partial tapping needs its own dimension: {labels:?}");
+ }
+ opts.thread_full_depth = true;
+ assert!(!dims(kind, &opts, false).into_iter().any(|d| d.label(kind) == "Thread depth"));
+ opts.thread_full_depth = false;
+ opts.tapped = false;
+ assert!(!dims(kind, &opts, false).into_iter().any(|d| d.label(kind) == "Thread depth"));
+ }
+ }
+ }
+
+ #[test]
+ fn partial_tapping_fields_do_not_overlap_on_narrow_forms() {
+ for width in [220.0, 280.0, 360.0] {
+ let ctx = crate::fonts::test_context();
+ let app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default());
+ let mut kind = crate::dialogs::Dialog::for_command(&app, "solid.hole").unwrap().kind;
+ if let Kind::Hole { kind, opts, .. } = &mut kind {
+ *kind = 1;
+ opts.tapped = true;
+ opts.thread_full_depth = false;
+ }
+ for _ in 0..3 {
+ let mut output = ctx.run_ui(
+ egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(width + 20.0, 700.0))), ..Default::default() },
+ |ui| {
+ ui.set_width(width);
+ crate::ui_kit::scope(ui, |ui| rows(ui, &mut kind, false, &|_, _| Some(10.0)));
+ },
+ );
+ output.textures_delta.clear();
+ }
+ let figure = crate::scenario::rect_of("dialog:figure:hole section").unwrap();
+ let picture = crate::scenario::rect_of("dialog:figure_picture:hole section").unwrap();
+ let mut previous_bottom = figure.top();
+ assert!(!dims(1, &HoleOpts { tapped: true, ..HoleOpts::default() }, false).contains(&Dim::Diameter));
+ for label in ["Counterbore Ø", "Counterbore depth", "Depth", "Thread depth"] {
+ let field = crate::scenario::rect_of(&format!("dialog:widget:{label}")).unwrap();
+ assert!(figure.contains_rect(field), "{label} is outside the {width} pt form: {field:?}");
+ assert!(field.left() > picture.right() && field.top() >= previous_bottom, "{label} overlaps another element: {field:?}");
+ previous_bottom = field.bottom();
+ }
+ }
+ }
+
fn opts(all: bool, angled: bool) -> HoleOpts {
HoleOpts { all, angled, ..HoleOpts::default() }
}
diff --git a/crates/ui-egui/src/hole_place_ui_tests.rs b/crates/ui-egui/src/hole_place_ui_tests.rs
index f2c7e244b3..bdeec1f299 100644
--- a/crates/ui-egui/src/hole_place_ui_tests.rs
+++ b/crates/ui-egui/src/hole_place_ui_tests.rs
@@ -274,7 +274,12 @@ fn the_dialog_shows_the_sizes_beside_a_section_of_the_hole() {
h.frames(3);
let (cb, cbd, depth, dia) = (at("Counterbore Ø"), at("Counterbore depth"), at("Depth"), at("Diameter"));
assert!(cb.y < cbd.y && cbd.y < depth.y && depth.y < dia.y, "{cb:?} {cbd:?} {depth:?} {dia:?}");
- assert!(handle_at("dialog:Tip Angle").is_none(), "no tip on a counterbore");
+ assert!(handle_at("dialog:Tip Angle").is_some(), "a counterbore retains the selected angled bottom");
+ if let Some(Kind::Hole { opts, .. }) = h.app.dialog.as_mut().map(|d| &mut d.kind) {
+ opts.angled = false;
+ }
+ h.frames(3);
+ assert!(handle_at("dialog:Tip Angle").is_none(), "a flat bottom needs no tip angle");
// Through all: no depth.
if let Some(Kind::Hole { opts, .. }) = h.app.dialog.as_mut().map(|d| &mut d.kind) {
opts.all = true;
@@ -293,3 +298,63 @@ fn the_dialog_shows_the_sizes_beside_a_section_of_the_hole() {
h.frames(2);
assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Hole { depth, .. } if depth == "7 mm"));
}
+
+#[test]
+fn tapped_thread_depth_field_keeps_focus_and_typing_separate_from_acceptance() {
+ let mut h = Harness::new();
+ h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap();
+ let hole = h.app.run("solid.hole", json!({"position":[20,15,20],"thread":"M6","depth":12})).unwrap()["feature"].as_u64().unwrap();
+ let original = h.app.session.doc.to_json();
+ h.step(&json!({"call":"ui.editFeature","params":{"feature":hole}})).unwrap();
+ h.frames(3);
+ // Opening Edit Feature intentionally rolls the marker back; focusing a field must
+ // preserve that editing state, and Cancel must restore the original marker too.
+ let editing = h.app.session.doc.to_json();
+ assert!(handle_at("dialog:Thread depth").is_none(), "full tapping needs no partial-depth field");
+ h.step(&json!({"click":{"handle":"dialog:Full thread depth"}})).unwrap();
+ h.frames(3);
+ assert!(handle_at("dialog:Thread depth").is_some(), "partial depth belongs beside the section");
+ h.step(&json!({"click":{"handle":"dialog:Thread depth"}})).unwrap();
+ h.step(&json!({"key":"A","cmd":true})).unwrap();
+ h.step(&json!({"text":"1 cm / 2"})).unwrap();
+ h.frames(3);
+ assert_eq!(h.app.session.doc.to_json(), editing, "selecting and typing a dimension must not apply the model");
+ assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Hole { opts, .. } if !opts.thread_full_depth && opts.thread_depth == "1 cm / 2"));
+ h.step(&json!({"key":"Escape"})).unwrap();
+ h.frames(3);
+ assert!(h.app.dialog.is_none());
+ assert_eq!(h.app.session.doc.to_json(), original, "Cancel preserves the accepted design");
+}
+
+/// The upstream Preferences split must retain both Hole controls on Design.
+#[test]
+fn hole_design_preferences_keep_both_controls_and_cancel_after_page_split() {
+ let mut h = Harness::new();
+ h.call("ui.prefs", json!({"language":"en", "open":"Design"}));
+ let page = rect_of("prefs:page_body").unwrap();
+ for label in ["Snap to face and edge centres", "Move holes by clicking or dragging"] {
+ let mut point = None;
+ for _ in 0..12 {
+ point = h.output.accesskit_update.as_ref().and_then(|tree| {
+ tree.nodes.iter().rev().find_map(|(_, node)| {
+ if node.label() != Some(label) {
+ return None;
+ }
+ let b = node.bounds()?;
+ let p = egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32);
+ page.contains(p).then_some(p)
+ })
+ });
+ if point.is_some() {
+ break;
+ }
+ h.call("ui.scroll", json!({"x":page.center().x,"y":page.center().y,"delta":-100}));
+ h.frames(12);
+ }
+ let p = point.unwrap_or_else(|| panic!("Hole preference missing from Design: {label}"));
+ h.call("ui.click", json!({"x":p.x,"y":p.y}));
+ }
+ assert!(h.app.preferences.hole_snaps && h.app.preferences.hole_moves);
+ h.call("ui.prefs", json!({"button":"cancel"}));
+ assert!(!h.app.preferences.hole_snaps && !h.app.preferences.hole_moves);
+}