SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Sketch Dimension: value box in the document's units (#3812) (#3878)
leValdemar1982cd5cc52ec5
diff --git a/crates/doc/src/params.rs b/crates/doc/src/params.rsindex ab4f0a2492..bad1ab7df1 100644--- a/crates/doc/src/params.rs+++ b/crates/doc/src/params.rs@@ -234,6 +234,22 @@ impl Document {}}+ /// A measured length (mm) written as a value in the design's units, with its unit: `1 in`+ /// for 25.4 mm in an inch design. Kept to the micrometre, as a millimetre value would be, so+ /// a dimension that restates the geometry moves nothing. Returns (unit, expression).+ pub fn design_length(&self, mm: f64) -> (String, String) {+ let u = self.units.trim();+ let per_unit = match expr::unit_info(u) {+ Some((Kind::Length, s)) if u != "mm" && s.is_finite() && s > 0.0 => s,+ _ => return ("mm".into(), format!("{} mm", (mm * 1e6).round() / 1e6)),+ };+ let decimals = (-(1e-6 / per_unit).log10()).ceil().clamp(0.0, 12.0) as usize;+ let text = format!("{:.*}", decimals, mm / per_unit);+ let text = if text.contains('.') { text.trim_end_matches('0').trim_end_matches('.') } else { &text };+ let text = if text == "-0" { "0" } else { text };+ (u.into(), format!("{text} {u}"))+ }+/// Every length input of every feature as the geometry reads it (mm; a unit-less result is/// in the design's units), for checking that an edit moves nothing.pub fn length_inputs(&self) -> Vec<Option<f64>> {@@ -1088,3 +1104,43 @@ pub(crate) fn numbers_after<'a>(base: &str, names: impl Iterator<Item = &'a str>.filter_map(|digits| digits.parse().ok()).collect()}++#[cfg(test)]+mod design_length_tests {+ use crate::Document;++ fn written(units: &str, mm: f64) -> (String, String) {+ let mut doc = Document::new("Units");+ doc.units = units.into();+ doc.design_length(mm)+ }++ #[test]+ fn a_measured_length_is_written_in_the_design_units() {+ let w = |u: &str, e: &str| (u.to_string(), e.to_string());+ assert_eq!(written("in", 25.4), w("in", "1 in"));+ assert_eq!(written("in", 12.7), w("in", "0.5 in"));+ assert_eq!(written("in", 10.0), w("in", "0.39370079 in"));+ assert_eq!(written("cm", 12.34), w("cm", "1.234 cm"));+ assert_eq!(written("mm", 12.3456789), w("mm", "12.345679 mm"));+ assert_eq!(written("in", -25.4), w("in", "-1 in"));+ assert_eq!(written("in", -1e-12), w("in", "0 in"));+ // Unknown or non-length units keep millimetres.+ assert_eq!(written("parsec", 5.0), w("mm", "5 mm"));+ assert_eq!(written("deg", 5.0), w("mm", "5 mm"));+ assert_eq!(written("", 5.0), w("mm", "5 mm"));+ }++ #[test]+ fn the_written_value_reads_back_within_a_micrometre() {+ for units in ["mm", "cm", "m", "in", "ft"] {+ let mut doc = Document::new("Units");+ doc.units = units.into();+ for mm in [0.001, 1.0, 12.345_678_9, 25.4, 999.999, 12_345.678] {+ let (_, e) = doc.design_length(mm);+ let back = doc.eval(&e, crate::expr::Kind::Length).unwrap();+ assert!((back - mm).abs() <= 1e-6, "{units} {mm}: {e} reads {back}");+ }+ }+ }+}diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rsindex f3a3b4ba1b..8b624d5431 100644--- a/crates/engine/src/cmd/sketch.rs+++ b/crates/engine/src/cmd/sketch.rs@@ -2574,8 +2574,8 @@ fn dimension(s: &mut Session, p: &Value) -> Result<Value> {before = None;return Ok((String::new(), name, measured(is_angle, cur)));}- let (unit, default_expr) =- if is_angle { ("deg", format!("{} deg", round6(cur.to_degrees()))) } else { ("mm", format!("{} mm", round6(cur))) };+ // With no value, the dimension restates what it measures, in the design's units (#3812).+ let (unit, default_expr) = if is_angle { ("deg".into(), format!("{} deg", round6(cur.to_degrees()))) } else { doc.design_length(cur) };let kind = if is_angle { Kind::Angle } else { Kind::Length };if let Some((name, rhs)) = &defines {// The new user parameter reads a bare number as the dimension would (the design's@@ -2591,7 +2591,7 @@ fn dimension(s: &mut Session, p: &Value) -> Result<Value> {doc.add_user_param(name, &rhs, Some(&unit), None).map_err(|e| bad(cmd, format!("value: {e}")))?;}let e = value.as_ref().map(|e| doc.with_design_unit(e, kind)).unwrap_or(default_expr);- let pname = doc.new_model_param(&e, unit);+ let pname = doc.new_model_param(&e, &unit);// The value must evaluate.let (vals, errs) = doc.param_values();if let Some(err) = errs.get(&pname) {diff --git a/crates/engine/src/cmd/sketch_constraints.rs b/crates/engine/src/cmd/sketch_constraints.rsindex efddb171e8..f12a394d25 100644--- a/crates/engine/src/cmd/sketch_constraints.rs+++ b/crates/engine/src/cmd/sketch_constraints.rs@@ -126,8 +126,8 @@ fn try_add(sk: &mut Sketch, doc: &mut solidcraft_doc::Document, k: ConstraintKinlet saved = sk.clone();let param = if dim {let v = k.value()?;- let e = if k.is_angle() { format!("{} deg", (v.to_degrees() * 1e6).round() / 1e6) } else { format!("{} mm", (v * 1e6).round() / 1e6) };- Some(doc.new_model_param(&e, if k.is_angle() { "deg" } else { "mm" }))+ let (unit, e) = if k.is_angle() { ("deg".into(), format!("{} deg", (v.to_degrees() * 1e6).round() / 1e6)) } else { doc.design_length(v) };+ Some(doc.new_model_param(&e, &unit))} else {None};@@ -383,13 +383,10 @@ fn toggle_driven(s: &mut Session, p: &Value) -> Result<Value> {slot.driven = true;slot.param = None;} else {- let (unit, e) = if c.kind.is_angle() {- ("deg", format!("{} deg", (v.to_degrees() * 1e6).round() / 1e6))- } else {- ("mm", format!("{} mm", (v * 1e6).round() / 1e6))- };+ let (unit, e) =+ if c.kind.is_angle() { ("deg".into(), format!("{} deg", (v.to_degrees() * 1e6).round() / 1e6)) } else { doc.design_length(v) };slot.driven = false;- slot.param = Some(doc.new_model_param(&e, unit));+ slot.param = Some(doc.new_model_param(&e, &unit));before = None;}Ok(driven)diff --git a/crates/engine/src/cmd/sketch_ux_tests.rs b/crates/engine/src/cmd/sketch_ux_tests.rsindex acd4cb6820..8e073759d9 100644--- a/crates/engine/src/cmd/sketch_ux_tests.rs+++ b/crates/engine/src/cmd/sketch_ux_tests.rs@@ -1790,3 +1790,63 @@ fn dragging_an_end_of_a_tangent_line_leaves_its_other_end_still() {let si = run(&mut s, "sketch.inspect", json!({}));assert!(si["failing"].as_array().is_some_and(Vec::is_empty), "still tangent: {si}");}++// ---------------------------------------------------------------------------------------------+// A dimension without a value restates its measurement in the design's units (#3812): `1 in`+// for a 25.4 mm line in an inch design, so the value box opens in the units the text shows.++/// A sketch with a 25.4 mm line `l1` in a design in `units`.+fn units_line(units: &str) -> Session {+ let mut s = Session::default();+ run(&mut s, "sketch.create", json!({"plane": "XY"}));+ run(&mut s, "sketch.line", json!({"points": [[0, 0], [25.4, 0]], "ids": ["l1"]}));+ run(&mut s, "document.units", json!({"units": units}));+ s+}++fn units_param(s: &Session, name: &str) -> (String, String) {+ let p = s.doc.param(name).unwrap();+ (p.expr.clone(), p.unit.clone())+}++fn units_line_end(s: &Session) -> f64 {+ let state = s.model.state();+ let sk = &state.sketch(s.active_sketch.unwrap()).unwrap().sketch;+ sk.point(sk.resolve_point("l1.end").unwrap()).unwrap().x+}++#[test]+fn a_dimension_without_a_value_is_written_in_the_design_units() {+ for (units, expr) in [("in", "1 in"), ("mm", "25.4 mm"), ("cm", "2.54 cm"), ("ft", "0.083333333 ft"), ("m", "0.0254 m")] {+ let mut s = units_line(units);+ let r = run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "scale_sketch": true}));+ let name = r["param"].as_str().unwrap();+ assert_eq!(units_param(&s, name), (expr.to_string(), units.to_string()), "{units}");+ assert!((units_line_end(&s) - 25.4).abs() < 1e-5, "{units}: the restated dimension moves nothing ({})", units_line_end(&s));+ }+}++#[test]+fn a_typed_bare_number_still_means_the_design_units() {+ let mut s = units_line("in");+ let r = run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": "2"}));+ assert_eq!(units_param(&s, r["param"].as_str().unwrap()).0, "2 in");+ assert!((units_line_end(&s) - 50.8).abs() < 1e-6);+}++#[test]+fn a_driven_dimension_made_driving_and_autoconstrain_dimensions_use_the_design_units() {+ let mut s = units_line("in");+ run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "driven": true}));+ let state = s.model.state();+ let id = state.sketch(s.active_sketch.unwrap()).unwrap().sketch.constraints.iter().find(|c| c.driven).unwrap().id.clone();+ run(&mut s, "sketch.toggle_driven", json!({"constraint": id, "driven": false}));+ let made = s.doc.params.iter().find(|p| p.model).unwrap();+ assert_eq!((made.expr.as_str(), made.unit.as_str()), ("1 in", "in"));++ let mut s = units_line("in");+ run(&mut s, "sketch.auto_constrain", json!({}));+ let lengths: Vec<_> = s.doc.params.iter().filter(|p| p.model && p.unit != "deg").collect();+ assert!(!lengths.is_empty(), "AutoConstrain dimensioned the line");+ assert!(lengths.iter().all(|p| p.unit == "in" && p.expr.ends_with(" in")), "{lengths:?}");+}diff --git a/crates/ui-egui/tests/scenarios/sketch_dimension_design_units.json b/crates/ui-egui/tests/scenarios/sketch_dimension_design_units.jsonnew file mode 100644index 0000000000..bccaff35e4--- /dev/null+++ b/crates/ui-egui/tests/scenarios/sketch_dimension_design_units.json@@ -0,0 +1,18 @@+[+ {"note": "#3812: in an inch design, the Dimension tool's value box opens in inches (`1 in` for a 25.4 mm line), as the dimension's text shows, not in millimetres (`25.4 mm`). Enter accepts the value as offered."},+ {"call": "engine.execute", "params": {"command": "sketch.create", "params": {"plane": "XY"}}},+ {"call": "engine.execute", "params": {"command": "sketch.line", "params": {"points": [[0, 0], [25.4, 0]], "ids": ["la"]}}},+ {"call": "engine.execute", "params": {"command": "document.units", "params": {"units": "in"}}},+ {"call": "ui.view", "params": {"view": "top"}},+ {"call": "ui.view", "params": {"view": "fit"}},+ {"start": "sketch.dimension"},+ {"click": {"sketch": [12.7, 0]}},+ {"click": {"sketch": [12.7, 6]}},+ {"shot": "value-box"},+ {"key": "Enter"},+ {"expect": {"errors": 0}},+ {"expect": {"query": {"command": "document.inspect", "path": ["params", 0, "expression"], "value": "1 in"}}},+ {"expect": {"query": {"command": "document.inspect", "path": ["params", 0, "unit"], "value": "in"}}},+ {"key": "Escape"},+ {"expect": {"query": {"command": "sketch.inspect", "path": ["curves", 0, "end_at", 0], "value": 25.4}}}+]