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:
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,11 +155,14 @@ pub fn begin_dimension(app: &mut SolveApp, entities: Vec<String>, at: Vec2) -> R
|
||||
|
||||
/// Type-first creation: the picks determine a dimension, so its value takes the keyboard at
|
||||
/// once (D, click a line, type). The text follows the pointer; a click pins it, Enter places
|
||||
/// it. False when the dimension would only be a driven one: that keeps the place-first flow,
|
||||
/// where placing it adds it.
|
||||
/// it. Midpoint pairs and dimensions that would only be driven keep the place-first flow:
|
||||
/// the pointer chooses the orientation, and a click places the text before entering a value.
|
||||
pub fn begin_live(app: &mut SolveApp, entities: Vec<String>, pointer: Option<Pos2>) -> Result<bool, String> {
|
||||
// A midpoint pair chooses its orientation and text position before entering a value.
|
||||
// This also permits switching freely between driving and reference spans.
|
||||
let midpoint_pair = entities.len() == 2 && entities.iter().all(|id| id.starts_with("mid:"));
|
||||
let (param, expr, draft) = dimension_draft(app, entities, None)?;
|
||||
if draft.driven {
|
||||
if draft.driven || midpoint_pair {
|
||||
return Ok(false);
|
||||
}
|
||||
let live = Some(Live { origin: pointer, moved: false, typed: false });
|
||||
@@ -814,6 +817,7 @@ fn edit_box(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
fn clear_picks(app: &mut SolveApp) {
|
||||
if let Some(tool) = app.tool.as_mut().filter(|t| t.kind == crate::tools::Kind::Dimension) {
|
||||
tool.picks.clear();
|
||||
tool.point_picks.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -835,6 +839,20 @@ pub fn draft_preview() -> Option<(String, solidcraft_engine::sketch::Constraint,
|
||||
})
|
||||
}
|
||||
|
||||
/// A place-first draft, including a driven dimension, for creation tests.
|
||||
#[cfg(test)]
|
||||
pub fn placement_dimension_preview(app: &SolveApp) -> Option<solidcraft_engine::sketch::Constraint> {
|
||||
let (id, draft) = placement_preview(app)?;
|
||||
draft
|
||||
.preview
|
||||
.sketch(draft.sketch)?
|
||||
.sketch
|
||||
.constraints
|
||||
.iter()
|
||||
.find(|c| c.param.as_deref() == Some(id.as_str()) || (c.driven && c.id == id))
|
||||
.cloned()
|
||||
}
|
||||
|
||||
/// Dimensions drawn last frame: (id, text centre on screen), for tests and the control channel.
|
||||
pub fn drawn() -> Vec<(String, Pos2)> {
|
||||
DRAWN.with(|d| d.borrow().iter().map(|x| (x.id.clone(), x.text.center())).collect())
|
||||
@@ -863,7 +881,7 @@ mod tests {
|
||||
h.app.run("sketch.line", json!({"points":[[10,10],[20,10]],"infer":false,"connect":false})).unwrap();
|
||||
h.app.run("sketch.line", json!({"points":[[10,10],[10,20]],"infer":false,"connect":false})).unwrap();
|
||||
h.call("ui.view", json!({"view":"top"}));
|
||||
for (picks, at, angular) in [(vec![[35, 30]], [40, 40], false), (vec![[15, 10], [10, 15]], [18, 18], true)] {
|
||||
for (picks, at, angular) in [(vec![[35, 30]], [40, 40], false), (vec![[13, 10], [10, 13]], [18, 18], true)] {
|
||||
h.step(&json!({"start":"sketch.dimension"})).unwrap();
|
||||
for pick in picks {
|
||||
h.step(&json!({"click":{"sketch":pick}})).unwrap();
|
||||
|
||||
@@ -815,3 +815,280 @@ fn type_first_switching_between_aligned_horizontal_and_vertical_keeps_the_picked
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn midpoint_then_edge_creates_a_distance_in_one_undo_step() {
|
||||
use solidcraft_engine::sketch::ConstraintKind;
|
||||
let mut h = line([20., 0.]);
|
||||
h.app.run("sketch.line", json!({"points":[[-10,-10],[-10,20]]})).unwrap();
|
||||
h.app.run("sketch.constraint.fix", json!({"entity":"l2"})).unwrap();
|
||||
h.settle();
|
||||
let baseline = h.app.session.doc.to_json();
|
||||
let undo = h.app.session.undo.len();
|
||||
for accept in [false, true] {
|
||||
place(&mut h, &[[10., 0.], [-10., -5.]], [0., -8.]);
|
||||
let (_, c, sk) = crate::dim_view::draft_preview().unwrap();
|
||||
let ConstraintKind::PointLineDistance { p, l, .. } = c.kind else { panic!("MID to edge must be a distance: {:?}", c.kind) };
|
||||
assert_eq!(sk.curves[l].id, "l2");
|
||||
assert!(sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Midpoint { p: q, l: 0 } if q == p)));
|
||||
assert_eq!(h.app.session.doc.to_json(), baseline, "preview creates no persistent helper");
|
||||
if !accept {
|
||||
h.step(&json!({"key":"Escape"})).unwrap();
|
||||
assert!(h.app.tool.as_ref().unwrap().point_picks.is_empty());
|
||||
continue;
|
||||
}
|
||||
type_value(&mut h, "25 mm");
|
||||
h.step(&json!({"key":"Enter"})).unwrap();
|
||||
assert!(!crate::dim_view::editing());
|
||||
assert_eq!(h.app.session.undo.len(), undo + 1);
|
||||
let state = h.app.session.world_state();
|
||||
let solved = state.sketch(h.app.session.active_sketch.unwrap()).unwrap();
|
||||
assert!(solved.report.ok());
|
||||
let sk = &solved.sketch;
|
||||
let c = sk.constraints.iter().find(|c| c.param.is_some()).unwrap();
|
||||
assert!(matches!(c.kind, ConstraintKind::PointLineDistance { .. }));
|
||||
assert!((solidcraft_engine::sketch::measure_dimension(sk, &c.kind).unwrap() - 25.).abs() < 1e-6);
|
||||
let accepted = h.app.session.doc.to_json();
|
||||
h.app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(h.app.session.doc.to_json(), baseline);
|
||||
h.app.run("edit.redo", json!({})).unwrap();
|
||||
assert_eq!(h.app.session.doc.to_json(), accepted);
|
||||
}
|
||||
crate::dim_view::cancel();
|
||||
}
|
||||
|
||||
/// The short sketch edge overlaps a face's automatically projected boundary.
|
||||
fn midpoint_face_sketch() -> Harness {
|
||||
use solidcraft_engine::geom::Vec3;
|
||||
crate::dim_view::cancel();
|
||||
let mut h = Harness::new();
|
||||
h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();
|
||||
h.app.run("sketch.rectangle.two_point", json!({"p0":[-10,-5],"p1":[10,15]})).unwrap();
|
||||
h.app.finish_sketch();
|
||||
h.app.run("solid.extrude", json!({"distance":10})).unwrap();
|
||||
h.app.run("sketch.create", json!({"plane":{"face":[0,5,10]}})).unwrap();
|
||||
let state = h.app.session.world_state();
|
||||
let ss = state.sketch(h.app.session.active_sketch.unwrap()).unwrap();
|
||||
let plane = ss.plane;
|
||||
assert!(ss.sketch.curves.iter().any(|c| c.link.is_some()));
|
||||
for ends in [[[-8., -5.], [2., -5.]], [[3., 2.], [7., 6.]]] {
|
||||
let points: Vec<_> = ends
|
||||
.into_iter()
|
||||
.map(|p| {
|
||||
let q = plane.to_local(Vec3::new(p[0], p[1], 10.));
|
||||
[q.x, q.y]
|
||||
})
|
||||
.collect();
|
||||
h.app.run("sketch.line", json!({"points":points,"infer":false})).unwrap();
|
||||
}
|
||||
h.call("ui.view", json!({"view":"top"}));
|
||||
h.app.cam.distance = 90.;
|
||||
h.app.cam.target = Vec3::new(0., 5., 10.);
|
||||
h.settle();
|
||||
h
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_sketch_midpoint_to_model_edge_dimensions_the_snapped_point() {
|
||||
use solidcraft_engine::sketch::{ConstraintKind, Shape};
|
||||
let mut h = midpoint_face_sketch();
|
||||
let baseline = h.app.session.doc.to_json();
|
||||
let undo = h.app.session.undo.len();
|
||||
h.step(&json!({"start":"sketch.dimension"})).unwrap();
|
||||
for p in [[-3., -5.], [10., 2.], [4., -10.]] {
|
||||
h.step(&json!({"click":{"world":[p[0],p[1],10.]}})).unwrap();
|
||||
}
|
||||
let (_, c, sk) = crate::dim_view::draft_preview().expect("MID to projected model edge has a draft");
|
||||
let ConstraintKind::PointLineDistance { p, l, .. } = c.kind else { panic!("expected point/edge distance: {:?}", c.kind) };
|
||||
assert!(sk.curves[l].link.is_some());
|
||||
let source = sk
|
||||
.constraints
|
||||
.iter()
|
||||
.find_map(|c| match c.kind {
|
||||
ConstraintKind::Midpoint { p: q, l } if p == q => Some(l),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(sk.curves[source].link.is_none(), "the short sketch edge won the overlapping pick");
|
||||
let Shape::Line { a, b } = sk.shape(source).unwrap() else { panic!() };
|
||||
assert!((a.dist(b) - 10.).abs() < 1e-6);
|
||||
assert!((solidcraft_engine::sketch::measure_dimension(&sk, &c.kind).unwrap() - 13.).abs() < 1e-6);
|
||||
assert_eq!(h.app.session.doc.to_json(), baseline);
|
||||
type_value(&mut h, "12 mm");
|
||||
h.step(&json!({"key":"Enter"})).unwrap();
|
||||
assert!(!crate::dim_view::editing());
|
||||
assert_eq!(h.app.session.undo.len(), undo + 1);
|
||||
h.app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(h.app.session.doc.to_json(), baseline);
|
||||
crate::dim_view::cancel();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn midpoint_pairs_dimension_sketch_and_projected_model_edges() {
|
||||
use solidcraft_engine::sketch::ConstraintKind;
|
||||
for (first, second, projected) in [
|
||||
([-3_f64, -5.], [5., 4.], [false, false]),
|
||||
([-3., -5.], [10., 5.], [false, true]),
|
||||
([10., 5.], [-3., -5.], [true, false]),
|
||||
([0., -5.], [10., 5.], [true, true]),
|
||||
] {
|
||||
let mut h = midpoint_face_sketch();
|
||||
let baseline = h.app.session.doc.to_json();
|
||||
let undo = h.app.session.undo.len();
|
||||
h.step(&json!({"start":"sketch.dimension"})).unwrap();
|
||||
for p in [first, second] {
|
||||
h.step(&json!({"click":{"world":[p[0],p[1],10.]}})).unwrap();
|
||||
}
|
||||
let at = [(first[0] + second[0]) * 0.5, (first[1] + second[1]) * 0.5];
|
||||
assert_eq!(h.app.session.doc.to_json(), baseline);
|
||||
h.step(&json!({"click":{"world":[at[0],at[1],10.]}})).unwrap();
|
||||
if crate::dim_view::editing() {
|
||||
h.step(&json!({"key":"Enter"})).unwrap();
|
||||
}
|
||||
let state = h.app.session.world_state();
|
||||
let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch;
|
||||
let c = sk.constraints.iter().rev().find(|c| c.kind.is_dimension()).expect("two MID picks commit a distance");
|
||||
let ConstraintKind::Distance { p, q, .. } = c.kind else { panic!("expected midpoint distance for {projected:?}: {:?}", c.kind) };
|
||||
for (point, expected) in [(p, projected[0]), (q, projected[1])] {
|
||||
let l = sk
|
||||
.constraints
|
||||
.iter()
|
||||
.find_map(|c| match c.kind {
|
||||
ConstraintKind::Midpoint { p, l } if p == point => Some(l),
|
||||
_ => None,
|
||||
})
|
||||
.expect("each pick remains a midpoint");
|
||||
assert_eq!(sk.curves[l].link.is_some(), expected);
|
||||
}
|
||||
let measured = ((first[0] - second[0]).powi(2) + (first[1] - second[1]).powi(2)).sqrt();
|
||||
assert!((solidcraft_engine::sketch::measure_dimension(sk, &c.kind).unwrap() - measured).abs() < 1e-6);
|
||||
assert_eq!(h.app.session.undo.len(), undo + 1);
|
||||
h.app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(h.app.session.doc.to_json(), baseline);
|
||||
crate::dim_view::cancel();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn midpoint_selection_keeps_line_circle_gap_dimensions_in_both_orders() {
|
||||
use solidcraft_engine::sketch::ConstraintKind;
|
||||
for reverse in [false, true] {
|
||||
let mut h = line([20., 0.]);
|
||||
h.app.run("sketch.circle.center", json!({"center":[10,10],"radius":3})).unwrap();
|
||||
h.settle();
|
||||
let baseline = h.app.session.doc.to_json();
|
||||
let picks = if reverse { [[13., 10.], [10., 0.]] } else { [[10., 0.], [13., 10.]] };
|
||||
place(&mut h, &picks, [25., 5.]);
|
||||
let (_, c, sk) = crate::dim_view::draft_preview().expect("the edge-to-edge gap remains available");
|
||||
assert!(matches!(c.kind, ConstraintKind::LineCircleDistance { value, .. } if (value - 7.).abs() < 1e-6));
|
||||
assert!(!sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })));
|
||||
h.step(&json!({"key":"Escape"})).unwrap();
|
||||
assert_eq!(h.app.session.doc.to_json(), baseline);
|
||||
crate::dim_view::cancel();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn midpoint_dimension_orientation_follows_the_pointer_before_placement() {
|
||||
use solidcraft_engine::sketch::ConstraintKind;
|
||||
for (first, second) in [([-3_f64, -5.], [5., 4.]), ([-3., -5.], [10., 5.]), ([10., 5.], [-3., -5.]), ([0., -5.], [10., 5.])] {
|
||||
for (horizontal, held_y, reused) in
|
||||
[(true, false, false), (false, false, false), (true, true, false), (false, true, false), (true, false, true), (false, false, true)]
|
||||
{
|
||||
if held_y && (first != [-3., -5.] || second != [10., 5.]) {
|
||||
continue;
|
||||
}
|
||||
let mut h = midpoint_face_sketch();
|
||||
if held_y {
|
||||
let state = h.app.session.world_state();
|
||||
let ss = state.sketch(h.app.session.active_sketch.unwrap()).unwrap();
|
||||
let short = ss.sketch.curves.iter().find(|c| c.link.is_none()).unwrap().id.clone();
|
||||
let bottom = ss
|
||||
.sketch
|
||||
.curves
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find_map(|(i, c)| {
|
||||
c.link.as_ref()?;
|
||||
let solidcraft_engine::sketch::Shape::Line { a, b } = ss.sketch.shape(i)? else {
|
||||
return None;
|
||||
};
|
||||
((ss.plane.to_world(a).y + 5.).abs() < 1e-6 && (ss.plane.to_world(b).y + 5.).abs() < 1e-6).then(|| c.id.clone())
|
||||
})
|
||||
.unwrap();
|
||||
for end in ["start", "end"] {
|
||||
h.app.run("sketch.constraint.coincident", json!({"a":format!("{short}.{end}"),"b":bottom})).unwrap();
|
||||
}
|
||||
h.settle();
|
||||
}
|
||||
if reused {
|
||||
let state = h.app.session.world_state();
|
||||
let ss = state.sketch(h.app.session.active_sketch.unwrap()).unwrap();
|
||||
let mid_ref = |point: [f64; 2]| {
|
||||
ss.sketch
|
||||
.curves
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find_map(|(i, c)| {
|
||||
let solidcraft_engine::sketch::Shape::Line { a, b } = ss.sketch.shape(i)? else {
|
||||
return None;
|
||||
};
|
||||
let at = ss.plane.to_world((a + b) * 0.5);
|
||||
((at.x - point[0]).abs() < 1e-6 && (at.y - point[1]).abs() < 1e-6).then(|| format!("mid:{}", c.id))
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
h.app.run("sketch.dimension", json!({"entities":[mid_ref(first),mid_ref(second)],"driven":true})).unwrap();
|
||||
h.settle();
|
||||
}
|
||||
let baseline = h.app.session.doc.to_json();
|
||||
let undo = h.app.session.undo.len();
|
||||
h.step(&json!({"start":"sketch.dimension"})).unwrap();
|
||||
for p in [first, second] {
|
||||
h.step(&json!({"click":{"world":[p[0],p[1],10.]}})).unwrap();
|
||||
}
|
||||
assert!(!crate::dim_view::editing(), "choose the midpoint span's orientation before entering a value");
|
||||
let above = [(first[0] + second[0]) * 0.5, first[1].max(second[1]) + 3.];
|
||||
let beside = [first[0].max(second[0]) + 3., (first[1] + second[1]) * 0.5];
|
||||
// Switch back and forth without accepting or changing the picked midpoints.
|
||||
for is_x in [true, false, true, horizontal] {
|
||||
let at = if is_x { above } else { beside };
|
||||
h.step(&json!({"move":{"world":[at[0],at[1],10.]}})).unwrap();
|
||||
h.settle();
|
||||
let c = crate::dim_view::draft_preview()
|
||||
.map(|(_, c, _)| c)
|
||||
.or_else(|| crate::dim_view::placement_dimension_preview(&h.app))
|
||||
.expect("a midpoint dimension previews before placement");
|
||||
assert!(
|
||||
if is_x { matches!(c.kind, ConstraintKind::DistanceX { .. }) } else { matches!(c.kind, ConstraintKind::DistanceY { .. }) },
|
||||
"{first:?} to {second:?}, horizontal={is_x}: {:?}",
|
||||
c.kind
|
||||
);
|
||||
let expected = if is_x { (first[0] - second[0]).abs() } else { (first[1] - second[1]).abs() };
|
||||
assert!((c.kind.value().unwrap() - expected).abs() < 1e-6);
|
||||
assert_eq!(h.app.session.doc.to_json(), baseline);
|
||||
}
|
||||
let at = if horizontal { above } else { beside };
|
||||
h.step(&json!({"click":{"world":[at[0],at[1],10.]}})).unwrap();
|
||||
if crate::dim_view::editing() {
|
||||
h.step(&json!({"key":"Enter"})).unwrap();
|
||||
}
|
||||
let state = h.app.session.world_state();
|
||||
let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch;
|
||||
let c = sk.constraints.iter().rev().find(|c| c.kind.is_dimension()).unwrap();
|
||||
assert!(if horizontal { matches!(c.kind, ConstraintKind::DistanceX { .. }) } else { matches!(c.kind, ConstraintKind::DistanceY { .. }) });
|
||||
if held_y {
|
||||
assert_eq!(c.driven, !horizontal, "the vertical span is fixed by the model edge");
|
||||
}
|
||||
assert_eq!(
|
||||
sk.constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })).count(),
|
||||
2,
|
||||
"reuse the picked midpoint points"
|
||||
);
|
||||
assert_eq!(h.app.session.undo.len(), undo + 1);
|
||||
h.app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(h.app.session.doc.to_json(), baseline);
|
||||
crate::dim_view::cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+73
-16
@@ -78,7 +78,7 @@ pub struct Tool {
|
||||
pub hover: Option<(Vec2, Option<String>)>,
|
||||
/// Picked entity ids.
|
||||
pub picks: Vec<String>,
|
||||
/// Horizontal/Vertical point references: point ids or `{midpoint: line_id}`.
|
||||
/// Horizontal/Vertical point references, or the Dimension tool's midpoint snaps.
|
||||
pub point_picks: Vec<Value>,
|
||||
/// Inline dimension boxes for the shape being drawn, the point count they were made for,
|
||||
/// and whether the first box should take the keyboard.
|
||||
@@ -277,24 +277,60 @@ pub fn on_click(app: &mut SolveApp, proj: &Proj, pos: Pos2, shift: bool) {
|
||||
Kind::Ext => crate::sketch_tools::on_click(app, &mut tool, proj, pos),
|
||||
Kind::Dimension => {
|
||||
let hits = pick(app, proj, pos);
|
||||
let hit = hits.iter().find_map(|h| match h {
|
||||
Hit::SketchPoint { id, .. } => Some((id.clone(), false)),
|
||||
Hit::SketchCurve { id, .. } => Some((id.clone(), true)),
|
||||
_ => None,
|
||||
// The snap identifies the intended line even when another (projected) edge
|
||||
// overlaps it and wins the ordinary curve hit. Both picks can be midpoints.
|
||||
let midpoint = sketch_point_at(app, proj, pos).and_then(|(_, snap)| snap).and_then(|id| {
|
||||
if id.starts_with("mid:") { return Some(id); }
|
||||
// An earlier dimension may already have materialized this midpoint.
|
||||
// Picking that point retains the same midpoint intent on subsequent dimensions.
|
||||
let state = app.session.world_state();
|
||||
let ss = app.session.active_sketch.and_then(|sid| state.sketch(sid))?;
|
||||
let point = ss.sketch.resolve_point(&id)?;
|
||||
ss.sketch.constraints.iter().find_map(|c| match c.kind {
|
||||
solidcraft_engine::sketch::ConstraintKind::Midpoint { p, l } if !c.driven && p == point => {
|
||||
ss.sketch.curves.get(l).map(|c| format!("mid:{}", c.id))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}).filter(|id| {
|
||||
let Some(line) = id.strip_prefix("mid:") else { return false };
|
||||
let state = app.session.world_state();
|
||||
app.session
|
||||
.active_sketch
|
||||
.and_then(|sid| state.sketch(sid))
|
||||
.is_some_and(|ss| {
|
||||
ss.sketch.curve_index(line).is_some_and(|l| solidcraft_engine::view::sketch_curve_visible(&ss.sketch, l))
|
||||
// A circle/arc and a line still measure their edge-to-edge gap.
|
||||
&& tool.picks.first().is_none_or(|first| {
|
||||
ss.sketch.curve_index(first).is_none_or(|l| matches!(ss.sketch.shape(l), Some(solidcraft_engine::sketch::Shape::Line { .. })))
|
||||
})
|
||||
})
|
||||
});
|
||||
let hit = midpoint.as_deref().and_then(|id| id.strip_prefix("mid:")).map(|id| (id.to_string(), true, true)).or_else(|| {
|
||||
hits.iter().find_map(|h| match h {
|
||||
Hit::SketchPoint { sketch, id, .. } if Some(*sketch) == app.session.active_sketch => Some((id.clone(), false, true)),
|
||||
Hit::SketchCurve { sketch, id, straight, .. } if Some(*sketch) == app.session.active_sketch => {
|
||||
Some((id.clone(), true, *straight))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
});
|
||||
let fresh = |tool: &Tool, id: &String| !tool.picks.contains(id) && tool.picks.len() < 2;
|
||||
if let Some(typed) = crate::dim_view::live() {
|
||||
match hit {
|
||||
// Before anything is typed, another entity joins the dimension, as in the
|
||||
// place-first flow (a distance, an angle between lines).
|
||||
Some((id, _)) if !typed && fresh(&tool, &id) => {
|
||||
let mut picks = tool.picks.clone();
|
||||
picks.push(id);
|
||||
Some((id, _, midpoint_target)) if !typed && fresh(&tool, &id) => {
|
||||
let picks = dimension_picks(&tool, id, midpoint.as_deref(), midpoint_target);
|
||||
match crate::dim_view::begin_live(app, picks.clone(), Some(pos)) {
|
||||
Ok(true) => tool.picks = picks,
|
||||
Ok(false) => {
|
||||
crate::dim_view::cancel();
|
||||
Ok(live) => {
|
||||
if !live {
|
||||
crate::dim_view::cancel();
|
||||
}
|
||||
tool.picks = picks;
|
||||
if let Some(midpoint) = midpoint {
|
||||
tool.point_picks.push(json!(midpoint));
|
||||
}
|
||||
}
|
||||
Err(error) => app.set_status(error, true),
|
||||
}
|
||||
@@ -306,9 +342,12 @@ pub fn on_click(app: &mut SolveApp, proj: &Proj, pos: Pos2, shift: bool) {
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if let Some((id, curve)) = hit {
|
||||
} else if let Some((id, curve, midpoint_target)) = hit {
|
||||
if fresh(&tool, &id) {
|
||||
tool.picks.push(id);
|
||||
tool.picks = dimension_picks(&tool, id, midpoint.as_deref(), midpoint_target);
|
||||
if let Some(midpoint) = midpoint {
|
||||
tool.point_picks.push(json!(midpoint));
|
||||
}
|
||||
// As soon as the picks determine a dimension (one line, circle or arc, or a
|
||||
// second entity), its value takes the keyboard: D, click, type. A pick that
|
||||
// doesn't keeps the place-first flow; placing reports why.
|
||||
@@ -320,7 +359,10 @@ pub fn on_click(app: &mut SolveApp, proj: &Proj, pos: Pos2, shift: bool) {
|
||||
&& let Some((at, _)) = sketch_point_at(app, proj, pos)
|
||||
{
|
||||
match crate::dim_view::begin_dimension(app, tool.picks.clone(), at) {
|
||||
Ok(()) => tool.picks.clear(),
|
||||
Ok(()) => {
|
||||
tool.picks.clear();
|
||||
tool.point_picks.clear();
|
||||
}
|
||||
Err(error) => app.set_status(error, true),
|
||||
}
|
||||
}
|
||||
@@ -331,6 +373,20 @@ pub fn on_click(app: &mut SolveApp, proj: &Proj, pos: Pos2, shift: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A single edge still measures its length; a second pick uses the snapped midpoints.
|
||||
fn dimension_picks(tool: &Tool, id: String, midpoint: Option<&str>, midpoint_target: bool) -> Vec<String> {
|
||||
let mut picks = tool.picks.clone();
|
||||
if midpoint_target
|
||||
&& picks.len() == 1
|
||||
&& let Some(midpoint) = tool.point_picks.first().and_then(Value::as_str)
|
||||
&& let Some(first) = picks.first_mut()
|
||||
{
|
||||
*first = midpoint.to_string();
|
||||
}
|
||||
picks.push(if picks.len() == 1 { midpoint.map(str::to_string).unwrap_or(id) } else { id });
|
||||
picks
|
||||
}
|
||||
|
||||
/// Put down the next point of the shape being drawn; the last point runs the command (with
|
||||
/// the typed values as dimension constraints).
|
||||
pub fn place(app: &mut SolveApp, p: (Vec2, Option<String>)) {
|
||||
@@ -881,9 +937,10 @@ pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) {
|
||||
tk.text_dim,
|
||||
);
|
||||
}
|
||||
if t.kind == Kind::HorizontalVertical {
|
||||
if matches!(t.kind, Kind::HorizontalVertical | Kind::Dimension) {
|
||||
for target in &t.point_picks {
|
||||
let point = if let Some(id) = target.get("midpoint").and_then(Value::as_str) {
|
||||
let midpoint = target.get("midpoint").and_then(Value::as_str).or_else(|| target.as_str().and_then(|id| id.strip_prefix("mid:")));
|
||||
let point = if let Some(id) = midpoint {
|
||||
ss.sketch.curve_index(id).and_then(|l| match ss.sketch.shape(l)? {
|
||||
solidcraft_engine::sketch::Shape::Line { a, b } => Some((a + b) * 0.5),
|
||||
_ => None,
|
||||
|
||||
@@ -3100,7 +3100,14 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
// (#2448): its release clicks.
|
||||
app.viewport.tool_click = true;
|
||||
}
|
||||
// While acquiring a midpoint dimension's second entity, geometry takes precedence
|
||||
// over existing dimension lines ending on it. Dimension text can still supply a value.
|
||||
let midpoint_geometry = crate::dim_view::live() == Some(false)
|
||||
&& app.tool.as_ref().is_some_and(|t| t.kind == crate::tools::Kind::Dimension && t.picks.len() == 1 && !t.point_picks.is_empty())
|
||||
&& matches!(cand.as_ref().map(|c| &c.0), Some(Hit::SketchPoint { .. } | Hit::SketchCurve { .. }))
|
||||
&& crate::dim_view::hit_text(p).is_none();
|
||||
let reference_pick = (resp.clicked() || resp.double_clicked())
|
||||
&& !midpoint_geometry
|
||||
&& !held
|
||||
&& app.dialog.is_none()
|
||||
&& crate::dim_view::pick_reference(ui.ctx(), p, resp.double_clicked());
|
||||
|
||||
@@ -44,9 +44,10 @@ fn angle_dimension_both_interactive_workflows() {
|
||||
{"call":"ui.view","params":{"view":"top"}}
|
||||
]))
|
||||
.unwrap();
|
||||
// Pick the lines away from MID snaps so this remains an angular workflow.
|
||||
let picks = json!([
|
||||
{"click":{"sketch":[20,0]}},
|
||||
{"click":{"sketch":[15,15]},"shift":true}
|
||||
{"click":{"sketch":[10,0]}},
|
||||
{"click":{"sketch":[10,10]},"shift":true}
|
||||
]);
|
||||
if preselect {
|
||||
h.run(&picks).unwrap();
|
||||
|
||||
Reference in New Issue
Block a user