Fix midpoint picks in sketch dimensions (#4872)

Retain MID snaps across both picks and materialize reusable midpoint
constraints for point-to-line and point-to-point dimensions. Let midpoint
pairs choose horizontal or vertical spans with pointer placement before
entering a value.

Cover projected model edges, overlapping geometry, helper reuse,
undo/cancel/reopen, and existing angular and line-circle workflows.
This commit is contained in:
cronos
2026-10-24 00:58:56 +00:00
committed by GitHub
parent 7dd5baac5c
commit 45edd5baf5
7 changed files with 510 additions and 25 deletions
+36 -3
View File
@@ -120,7 +120,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.params(concat!("p0, p1: overall ends, width", connect_doc!(), created_doc!())),
CommandSpec::new("sketch.point", "Point", draw_point).at("SKETCH", "CREATE").icon("point").enabled(in_sketch).params(concat!("point: [x,y] (each a number or an expression over the design's parameters: the point is then fixed where it comes to and follows them) or a snap: \"mid:<line>\" (held at the line's midpoint), \"on:<curve>:x,y\" (on the curve near x,y), {vertex: [x,y,z]} or {on_edge: [x,y,z]} of the model; id?", connect_doc!(), created_doc!())),
CommandSpec::new("sketch.dimension", "Sketch Dimension", dimension).at("SKETCH", "CREATE").icon("dimension").key("D").enabled(in_sketch).params(
"entities: [refs], type?: auto|distance|horizontal|vertical|length|radius|diameter|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override), or `name = expression` (e.g. \"width = 40\"), which adds the user parameter `name` with that expression and dimensions with `name` (refused when the name is taken or reserved; the reply's `defined` names it); text_at?: [x, y]. Two points or a line off the axes: with auto, text_at across from them is the distance between them, above or below them horizontal, beside them vertical. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends true): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled",
"entities: [refs] (a line midpoint is \"mid:line_id\"), type?: auto|distance|horizontal|vertical|length|radius|diameter|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override), or `name = expression` (e.g. \"width = 40\"), which adds the user parameter `name` with that expression and dimensions with `name` (refused when the name is taken or reserved; the reply's `defined` names it); text_at?: [x, y]. Two points or a line off the axes: with auto, text_at across from them is the distance between them, above or below them horizontal, beside them vertical. Two midpoints: placing text above or below their bounding box measures horizontally, beside it vertically. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends true): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled",
),
CommandSpec::new("sketch.constraint.horizontal_vertical", "Horizontal/Vertical", c_horizontal_vertical)
.at("SKETCH", "CONSTRAINTS")
@@ -2236,13 +2236,20 @@ fn dimension(s: &mut Session, p: &Value) -> Result<Value> {
let start = s.doc.clone();
let ((param, kind_name, current), info) = edit(s, p, cmd, true, |sk, doc| {
before = Some(dof_now(sk));
let ent = |r: &str| -> Result<(Option<usize>, Option<usize>)> {
let mut ent = |r: &str| -> Result<(Option<usize>, Option<usize>)> {
if let Some(c) = sk.curve_index(r) {
return Ok((None, Some(c)));
}
if let Some(q) = sk.resolve_point(r) {
return Ok((Some(q), None));
}
if let Some(line) = r.strip_prefix("mid:") {
let l = sk.curve_index(line).ok_or_else(|| bad(cmd, format!("unknown sketch line `{line}`")))?;
if line_pts(sk, l).is_none() {
return Err(bad(cmd, "a midpoint reference needs a line"));
}
return Ok((Some(AlignmentTarget::Midpoint(l).materialize(sk, cmd)?), None));
}
Err(bad(cmd, format!("unknown sketch entity `{r}`")))
};
let e0 = ent(ents.first().map(String::as_str).unwrap_or(""))?;
@@ -2300,7 +2307,12 @@ fn dimension(s: &mut Session, p: &Value) -> Result<Value> {
}
((Some(a), None), Some((Some(b), None))) => {
let (pa, pb) = (sk.point(a).unwrap_or_default(), sk.point(b).unwrap_or_default());
match auto_orientation(&ty, pa, pb, text_at) {
let orientation = if ents.iter().all(|id| id.starts_with("mid:")) {
midpoint_orientation(&ty, pa, pb, text_at)
} else {
auto_orientation(&ty, pa, pb, text_at)
};
match orientation {
"horizontal" => (ConstraintKind::DistanceX { p: a, q: b, value: (pb.x - pa.x).abs() }, (pb.x - pa.x).abs()),
"vertical" => (ConstraintKind::DistanceY { p: a, q: b, value: (pb.y - pa.y).abs() }, (pb.y - pa.y).abs()),
_ => (ConstraintKind::Distance { p: a, q: b, value: pa.dist(pb) }, pa.dist(pb)),
@@ -2514,6 +2526,27 @@ fn auto_orientation(ty: &str, a: Vec2, b: Vec2, text_at: Option<Vec2>) -> &str {
}
}
/// Midpoint pairs choose an axis as soon as the text passes their bounding box.
/// Keeping the aligned sector inside that box avoids requiring a long pointer move
/// for shallow diagonals; explicit types and already aligned points retain their behavior.
fn midpoint_orientation(ty: &str, a: Vec2, b: Vec2, text_at: Option<Vec2>) -> &str {
let d = b - a;
if ty == "auto"
&& d.x.abs() > 1e-9 * d.len()
&& d.y.abs() > 1e-9 * d.len()
&& let Some(t) = text_at
{
let between = |v: f64, p: f64, q: f64| p.min(q) <= v && v <= p.max(q);
if between(t.x, a.x, b.x) && !between(t.y, a.y, b.y) {
return "horizontal";
}
if between(t.y, a.y, b.y) && !between(t.x, a.x, b.x) {
return "vertical";
}
}
auto_orientation(ty, a, b, text_at)
}
/// Keep a dimension's text where it was placed (`at`, sketch coordinates), relative to the
/// dimension so it follows the geometry.
fn place_text(sk: &mut Sketch, id: &str, at: Option<Vec2>) {
@@ -966,3 +966,95 @@ fn coincident_circles_lie_on_each_other() {
assert!(sk.point(c).unwrap().dist(Vec2::new(0.0, 0.0)) < 1e-6);
assert!((sk.point(start).unwrap().dist(sk.point(c).unwrap()) - 10.0).abs() < 1e-6);
}
#[test]
fn midpoint_edge_dimensions_track_the_midpoint_and_reuse_it() {
for reverse in [false, true] {
let mut s = new_sketch();
run(&mut s, "sketch.line", json!({"points":[[0,10],[20,10]]}));
run(&mut s, "sketch.line", json!({"points":[[-10,-10],[-10,40]]}));
run(&mut s, "sketch.constraint.fix", json!({"entity":"l2"}));
let length = run(&mut s, "sketch.dimension", json!({"entities":["l1"],"value":20}))["param"].as_str().unwrap().to_string();
let baseline = s.doc.to_json();
let entities = if reverse { json!(["l2", "mid:l1"]) } else { json!(["mid:l1", "l2"]) };
let d = run(&mut s, "sketch.dimension", json!({"entities":entities,"value":25}));
assert_eq!(d["unit"], "mm");
assert!((d["measured"].as_f64().unwrap() - 25.).abs() < 1e-6);
let param = d["param"].as_str().unwrap().to_string();
let accepted = s.doc.to_json();
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc.to_json(), baseline, "the helper and dimension undo together");
run(&mut s, "edit.redo", json!({}));
assert_eq!(s.doc.to_json(), accepted);
run(&mut s, "parameters.change", json!({"name":length,"expression":"40 mm"}));
run(&mut s, "parameters.change", json!({"name":param,"expression":"30 mm"}));
run(&mut s, "sketch.dimension", json!({"entities":entities,"driven":true}));
let sk = sketch(&s);
let mids: Vec<_> = sk
.constraints
.iter()
.filter_map(|c| match c.kind {
solidcraft_sketch::ConstraintKind::Midpoint { p, l } if l == sk.curve_index("l1").unwrap() => Some(p),
_ => None,
})
.collect();
assert_eq!(mids.len(), 1, "another dimension reuses the constrained midpoint");
let mid = sk.point(mids[0]).unwrap();
let a = sk.point(sk.resolve_point("l1.start").unwrap()).unwrap();
let b = sk.point(sk.resolve_point("l1.end").unwrap()).unwrap();
assert!(mid.dist((a + b) * 0.5) < 1e-6);
assert!((mid.x - 20.).abs() < 1e-6, "distance from the fixed x=-10 edge is 30 mm");
assert!((a.dist(b) - 40.).abs() < 1e-6);
let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());
reopened.active_sketch = s.active_sketch;
assert_eq!(sketch(&reopened), sk);
}
}
#[test]
fn invalid_midpoint_dimension_references_leave_the_design_unchanged() {
let mut s = new_sketch();
run(&mut s, "sketch.line", json!({"points":[[0,10],[20,10]]}));
run(&mut s, "sketch.circle.center", json!({"center":[30,30],"radius":5}));
let baseline = s.doc.to_json();
for entities in [json!(["mid:missing", "l1"]), json!(["mid:c1", "l1"]), json!(["mid:l1", "missing"])] {
assert!(s.execute("sketch.dimension", &json!({"entities":entities,"value":10})).is_err());
assert_eq!(s.doc.to_json(), baseline);
}
}
#[test]
fn midpoint_pair_orientation_uses_the_text_box_and_respects_explicit_types() {
use solidcraft_sketch::ConstraintKind as K;
let mut s = new_sketch();
run(&mut s, "sketch.line", json!({"points":[[0,10],[20,10]],"infer":false}));
run(&mut s, "sketch.line", json!({"points":[[40,20],[40,40]],"infer":false}));
for (ty, at, axis) in [
("auto", [25., 33.], 'x'),
("auto", [43., 20.], 'y'),
("auto", [25., 20.], 'd'),
("distance", [25., 33.], 'd'),
("horizontal", [43., 20.], 'x'),
("vertical", [25., 33.], 'y'),
] {
let mut trial = s.scratch();
run(&mut trial, "sketch.dimension", json!({"entities":["mid:l1","mid:l2"],"type":ty,"text_at":at,"driven":true}));
let sk = sketch(&trial);
let c = sk.constraints.iter().rev().find(|c| c.kind.is_dimension()).unwrap();
assert!(
match axis {
'x' => matches!(c.kind, K::DistanceX { .. }),
'y' => matches!(c.kind, K::DistanceY { .. }),
_ => matches!(c.kind, K::Distance { .. }),
},
"{ty} at {at:?}: {:?}",
c.kind
);
let expected = match axis {
'x' => 30.,
'y' => 20.,
_ => 1300_f64.sqrt(),
};
assert!((solidcraft_sketch::measure_dimension(&sk, &c.kind).unwrap() - expected).abs() < 1e-6);
}
}