Skip to content

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

Sketch: dragging part of a selection moves the whole selection (#2621) (#2720)

HiroKenEz65e6d9dafd36
diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs
index e2ca211abf..38b96a4f76 100644
--- a/crates/engine/src/cmd/sketch.rs
+++ b/crates/engine/src/cmd/sketch.rs
@@ -179,7 +179,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.params("entities: [curve, point or constraint ids]"),
CommandSpec::new("sketch.move_point", "Drag Sketch Point", move_point).icon("sketch_move").enabled(in_sketch).params("point: ref, to: [x,y]"),
CommandSpec::new("sketch.drag", "Drag Sketch Geometry", drag).icon("sketch_move").enabled(in_sketch).live(drag_live).params(
- "entity: point or curve, from: [x,y] where it was grabbed, to: [x,y], live?: bool: a point moves toward `to` within the design constraints; when exact cursor placement is impossible, bounded feasible steps minimize cursor distance while keeping design constraints mandatory. A line (spline, conic) slides by to - from; a circle or arc grabbed on its edge takes the radius to `to`. Long moves use continuation to retain the solution branch, and a step that would sweep an arc through its start is rejected. Returns `reached`: progress along the requested move (0..1; feasible point motion projects its actual displacement onto that move), and `at`: where the grabbed spot went (`from` moved as the dragged points did), the `from` of the next move. `live: true` solves the sketch and leaves later features stale until `sketch.drag_end` or a command that reads the model; `dof` is then the one from before the drag",
+ "entity: point or curve, from: [x,y] where it was grabbed, to: [x,y], live?: bool: a point moves toward `to` within the design constraints; when exact cursor placement is impossible, bounded feasible steps minimize cursor distance while keeping design constraints mandatory. A line (spline, conic) slides by to - from; a circle or arc grabbed on its edge takes the radius to `to`. `with?`: [point or curve ids]: the rest of a selection dragged by `entity`, which all slides by to - from as one (circles keep their radii). Long moves use continuation to retain the solution branch, and a step that would sweep an arc through its start is rejected. Returns `reached`: progress along the requested move (0..1; feasible point motion projects its actual displacement onto that move), and `at`: where the grabbed spot went (`from` moved as the dragged points did), the `from` of the next move. `live: true` solves the sketch and leaves later features stale until `sketch.drag_end` or a command that reads the model; `dof` is then the one from before the drag",
),
CommandSpec::new("sketch.drag_end", "End Sketch Drag", drag_end).icon("sketch_move").enabled(in_sketch).doc_only().params(
"constraint?: {command: a sketch.constraint.* id, params}: ends a drag made of `sketch.drag` `live: true` frames: adds the constraint it let go on (not kept if it over-constrains the sketch), then evaluates the whole model once; returns the constraint's result and the sketch's solved state and degrees of freedom",
@@ -2397,7 +2397,7 @@ fn move_point(s: &mut Session, p: &Value) -> Result<Value> {
let id = target_sketch(s, p, cmd)?;
let (_, rep) = edit_solved(s, id, false, |sk, _| {
let q = point_ref(sk, p.get("point"), cmd, "point")?;
- Ok(((), drag_entity(sk, Ent::Point(q), to, to, false).1.solve_again()))
+ Ok(((), drag_entity(sk, Ent::Point(q), &[], to, to, false).1.solve_again()))
})?;
Ok(json!({"sketch": rep.as_ref().map(report_json)}))
}
@@ -2424,6 +2424,21 @@ fn drag_frame(s: &mut Session, p: &Value, live: bool) -> Result<(Value, Option<c
let (d, rep) = edit_solved(s, id, false, |sk, doc| {
let r = p.get("entity").and_then(Value::as_str).ok_or_else(|| bad(cmd, "`entity` must be a sketch point or curve"))?;
let e = ent(sk, r).ok_or_else(|| bad(cmd, format!("unknown sketch entity `{r}`")))?;
+ let with = match p.get("with") {
+ None | Some(Value::Null) => Vec::new(),
+ Some(v) => {
+ let ids = v.as_array().ok_or_else(|| bad(cmd, "`with` must be a list of sketch point or curve ids"))?;
+ if ids.len() > sk.points.len() + sk.curves.len() {
+ return Err(bad(cmd, "`with` lists more entities than the sketch has"));
+ }
+ ids.iter()
+ .map(|v| {
+ let r = v.as_str().ok_or_else(|| bad(cmd, "`with` must be a list of sketch point or curve ids"))?;
+ ent(sk, r).ok_or_else(|| bad(cmd, format!("unknown sketch entity `{r}`")))
+ })
+ .collect::<Result<Vec<_>>>()?
+ }
+ };
if let Some(link) = super::sketch_create::text_link(sk, r).map(str::to_owned) {
let moving = sk.link_points(&link).into_iter().filter_map(|i| sk.point(i).map(|p| (i, p))).collect();
super::sketch_create::move_text(sk, &link, to - from, 0.0, Vec2::ZERO, false)?;
@@ -2431,7 +2446,7 @@ fn drag_frame(s: &mut Session, p: &Value, live: bool) -> Result<(Value, Option<c
}
// The held solves work on the dimensions' current values (a solved step applies them).
doc.apply_dimension_values(&doc.param_values().0, sk)?;
- let (d, left) = drag_entity(sk, e, from, to, live);
+ let (d, left) = drag_entity(sk, e, &with, from, to, live);
// A live frame's held solve is its only one; otherwise the sketch's own solve reports
// its degrees of freedom.
Ok((d, if live && last.is_some() { left } else { left.solve_again() }))
diff --git a/crates/engine/src/cmd/sketch_drag.rs b/crates/engine/src/cmd/sketch_drag.rs
index 8899230325..3f5cb7f6e3 100644
--- a/crates/engine/src/cmd/sketch_drag.rs
+++ b/crates/engine/src/cmd/sketch_drag.rs
@@ -120,10 +120,13 @@ impl Path {
/// and the drag ends there. Returns how far it got and what it leaves for the edit's solve
/// ([`Left::Solved`]: the held solve of the last step it kept left the sketch solved).
///
+/// `with`: the rest of a selection dragged by one of its entities; all of it slides by the
+/// cursor's move as one (see [`plan_group`]).
+///
/// `live`: one frame of an interactive drag, whose held solves and cursor correction share
/// one frame's work budget ([`Budget::frame`]); otherwise each has a solve's own.
-pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, from: Vec2, to: Vec2, live: bool) -> (Dragged, Left) {
- let Some((path, hold, n, short)) = prepare(sk, e, from, to) else {
+pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, with: &[Ent], from: Vec2, to: Vec2, live: bool) -> (Dragged, Left) {
+ let Some((path, hold, n, short)) = prepare(sk, e, with, from, to) else {
return (Dragged { reached: 0.0, moving: Vec::new() }, Left::Unsolved);
};
#[cfg(test)]
@@ -383,16 +386,16 @@ impl Geometry {
/// `drag_entity` runs, for tests.
#[cfg(test)]
pub(super) fn drag_steps(sk: &Sketch, e: Ent, from: Vec2, to: Vec2) -> usize {
- prepare(sk, e, from, to).map_or(0, |(_, _, n, _)| n)
+ prepare(sk, e, &[], from, to).map_or(0, |(_, _, n, _)| n)
}
/// A drag's path, what its solves hold and its number of steps (and of short steps, see
/// `SHORT_STEP_FRACTION`), or `None` if it cannot move.
-fn prepare(sk: &Sketch, e: Ent, from: Vec2, to: Vec2) -> Option<(Path, Hold, usize, usize)> {
+fn prepare(sk: &Sketch, e: Ent, with: &[Ent], from: Vec2, to: Vec2) -> Option<(Path, Hold, usize, usize)> {
if !(from.is_finite() && to.is_finite()) {
return None;
}
- let (path, hold) = plan(sk, e, from, to)?;
+ let (path, hold) = if with.is_empty() { plan(sk, e, from, to)? } else { plan_group(sk, e, with, to - from)? };
let n = step_count(sk, &hold, path.length(), STEP_FRACTION);
let short = step_count(sk, &hold, path.length(), SHORT_STEP_FRACTION);
Some((path, hold, n, short))
@@ -503,6 +506,36 @@ fn plan(sk: &Sketch, e: Ent, from: Vec2, to: Vec2) -> Option<(Path, Hold)> {
Some((path, hold))
}
+/// A selection dragged by one of its entities (`e`, the rest `with`): every free point of all of
+/// them slides by `d` and the solves hold them all (circles and ellipses keep their radii), so
+/// the selection moves as one instead of its free ends trailing behind the grabbed entity.
+fn plan_group(sk: &Sketch, e: Ent, with: &[Ent], d: Vec2) -> Option<(Path, Hold)> {
+ let mut hold = Hold::default();
+ for e in std::iter::once(&e).chain(with) {
+ match *e {
+ Ent::Point(q) => hold.points.push(q),
+ Ent::Curve(c) => {
+ let Some(kind) = sk.curves.get(c).map(|x| &x.kind) else { continue };
+ hold.points.extend(kind.point_ids());
+ if matches!(kind, CurveKind::Circle { .. } | CurveKind::Ellipse { .. }) {
+ hold.radii.push(c);
+ }
+ }
+ }
+ }
+ hold.points.sort_unstable();
+ hold.points.dedup();
+ hold.radii.sort_unstable();
+ hold.radii.dedup();
+ let locked = sk.locked_points();
+ let pts: Vec<(usize, Vec2)> =
+ hold.points.iter().filter(|q| !locked.get(**q).copied().unwrap_or(true)).filter_map(|&q| Some((q, sk.point(q)?))).collect();
+ if pts.is_empty() {
+ return None;
+ }
+ Some((Path::Slide { pts, d }, hold))
+}
+
/// Steps for a move of `length`: enough that none is longer than `fraction` of the smallest
/// size of the geometry the solve moves with what it holds (at least `MIN_STEP`), at most
/// `MAX_STEPS`. A move short next to every size in the sketch (a normal mouse frame) is one
diff --git a/crates/engine/src/cmd/sketch_drag_live_tests.rs b/crates/engine/src/cmd/sketch_drag_live_tests.rs
index 268b7d6bab..8139899efa 100644
--- a/crates/engine/src/cmd/sketch_drag_live_tests.rs
+++ b/crates/engine/src/cmd/sketch_drag_live_tests.rs
@@ -288,3 +288,37 @@ fn letting_go_on_a_snap_or_undoing_evaluates_once() {
assert!(r["constraint"]["error"].is_string(), "{r}");
assert!(!s.model.is_stale());
}
+
+#[test]
+fn a_drag_with_the_rest_of_a_selection_moves_it_as_one() {
+ // A vertical line and a 5 mm tail hanging off its top that keeps only its length (#2621).
+ let start = || {
+ let mut s = Session::default();
+ run(&mut s, "sketch.create", json!({"plane": "XY"}));
+ run(&mut s, "sketch.line", json!({"points": [[10, 10], [10, 50], [14, 47]]}));
+ run(&mut s, "sketch.constraint.horizontal_vertical", json!({"line": "l1"}));
+ run(&mut s, "sketch.dimension", json!({"entities": ["l2"], "value": 5}));
+ run(&mut s, "sketch.circle.center", json!({"center": [40, 10], "radius": 3, "id": "c1"}));
+ s
+ };
+ let v = solidcraft_geom::Vec2::new;
+ for live in [false, true] {
+ // Dragged alone, the line leaves the tail's free end where it was as far as it can.
+ let mut s = start();
+ run(&mut s, "sketch.drag", json!({"entity": "l1", "from": [10, 30], "to": [20, 20], "live": live}));
+ assert!(pt(&s, "l2.end").dist(v(24.0, 37.0)) > 1.0, "{:?}", pt(&s, "l2.end"));
+ // Dragged with the tail and the circle, all of it slides by the cursor's move.
+ let mut s = start();
+ let r = run(&mut s, "sketch.drag", json!({"entity": "l1", "with": ["l2", "c1"], "from": [10, 30], "to": [20, 20], "live": live}));
+ assert_eq!((&r["reached"], &r["at"]), (&json!(1.0), &json!([20.0, 20.0])), "{r}");
+ for (p, at) in [("l1.start", v(20.0, 0.0)), ("l1.end", v(20.0, 40.0)), ("l2.end", v(24.0, 37.0)), ("c1.center", v(50.0, 0.0))] {
+ assert!(pt(&s, p).dist(at) < 1e-6, "{p}: {:?}", pt(&s, p));
+ }
+ let sk = s.doc.sketch(s.active_sketch.expect("sketch mode")).expect("the sketch");
+ assert_eq!(sk.radius(sk.curve_index("c1").expect("the circle")), Some(3.0));
+ }
+ let mut s = start();
+ for with in [json!("l2"), json!([7]), json!(["nope"])] {
+ assert!(s.execute("sketch.drag", &json!({"entity": "l1", "with": with, "from": [10, 30], "to": [20, 20]})).is_err(), "{with}");
+ }
+}
diff --git a/crates/ui-egui/src/sketch_drag_ui_tests.rs b/crates/ui-egui/src/sketch_drag_ui_tests.rs
index 96c57de764..281cafda04 100644
--- a/crates/ui-egui/src/sketch_drag_ui_tests.rs
+++ b/crates/ui-egui/src/sketch_drag_ui_tests.rs
@@ -2,6 +2,7 @@
//! brings the model up to date in the drag's one undo step, and the grab stays on the geometry.
use serde_json::{Value, json};
+use solidcraft_engine::Sel;
use solidcraft_engine::geom::Vec2;
use crate::scenario::Harness;
@@ -244,3 +245,66 @@ fn associated_spline_offset_hides_fit_nodes_and_follows_a_source_drag_live() {
let sk = &state.sketch(sid).unwrap().sketch;
assert!(sk.curves[derived].kind.point_ids().iter().all(|i| !solidcraft_engine::view::sketch_point_visible(sk, *i)));
}
+
+#[test]
+fn dragging_a_selected_line_moves_the_whole_selection() {
+ let mut h = Harness::new();
+ run(&mut h, "sketch.create", json!({"plane": "XY"}));
+ // An L with a chamfered corner and a short tail (#2621): the tail keeps only its length, so
+ // dragged on its own the L would leave the tail's free end behind like a string.
+ run(&mut h, "sketch.line", json!({"points": [[10, 10], [10, 50], [15, 55], [50, 55], [54, 52]]}));
+ run(&mut h, "sketch.constraint.horizontal_vertical", json!({"line": "l1"}));
+ run(&mut h, "sketch.constraint.horizontal_vertical", json!({"line": "l3"}));
+ run(&mut h, "sketch.dimension", json!({"entities": ["l4"], "value": 5}));
+ run(&mut h, "sketch.line", json!({"points": [[80, 10], [80, 30]], "connect": false}));
+ let sid = h.app.session.active_sketch.expect("sketch mode");
+ let before = h.app.session.world_state().sketch(sid).expect("the sketch").sketch.clone();
+ let lines = ["l1", "l2", "l3", "l4"];
+ let mut selected: Vec<usize> = lines.iter().flat_map(|l| before.curves[before.curve_index(l).unwrap()].kind.point_ids()).collect();
+ selected.sort_unstable();
+ selected.dedup();
+ h.app.session.selection = lines.iter().map(|l| Sel::SketchCurve { id: (*l).into() }).collect();
+ h.app.session.selection.extend(selected.iter().map(|&p| Sel::SketchPoint { id: before.points[p].id.clone() }));
+ h.call("ui.view", json!({"view": "top"}));
+ h.app.cam.distance = 150.0;
+ h.frames(3);
+ let a = screen(&mut h, 10.0, 30.0);
+ let b = screen(&mut h, 20.0, 20.0);
+ let mut path = vec![a];
+ path.extend(steps(a, b, 8));
+ press_and_move(&mut h, &path);
+ release(&mut h, b);
+ let after = &h.app.session.world_state().sketch(sid).expect("the sketch").sketch.clone();
+ for &p in &selected {
+ let moved = after.points[p].pos - before.points[p].pos;
+ assert!(moved.dist(Vec2::new(10.0, -10.0)) < 0.05, "{} moved by {moved:?}", before.points[p].id);
+ }
+ let other = before.curves[before.curve_index("l5").unwrap()].kind.point_ids();
+ for p in other {
+ assert!(after.points[p].pos.dist(before.points[p].pos) < 1e-9, "the unselected line stays");
+ }
+}
+
+#[test]
+fn a_window_selected_circle_still_takes_its_radius_from_a_drag_on_its_edge() {
+ let mut h = Harness::new();
+ run(&mut h, "sketch.create", json!({"plane": "XY"}));
+ run(&mut h, "sketch.circle.center", json!({"center": [20, 20], "radius": 10, "id": "c1"}));
+ // A window around the circle picks it and its centre: not a group to move.
+ h.app.session.selection = vec![Sel::SketchCurve { id: "c1".into() }, Sel::SketchPoint { id: "c1.center".into() }];
+ h.call("ui.view", json!({"view": "top"}));
+ h.app.cam.distance = 150.0;
+ h.frames(3);
+ let a = screen(&mut h, 30.0, 20.0);
+ let b = screen(&mut h, 35.0, 20.0);
+ let mut path = vec![a];
+ path.extend(steps(a, b, 6));
+ press_and_move(&mut h, &path);
+ release(&mut h, b);
+ assert!(point(&h, "c1.center").dist(Vec2::new(20.0, 20.0)) < 1e-9);
+ let sid = h.app.session.active_sketch.expect("sketch mode");
+ let st = h.app.session.world_state();
+ let sk = &st.sketch(sid).expect("the sketch").sketch;
+ let r = sk.radius(sk.curve_index("c1").expect("the circle")).expect("a radius");
+ assert!((r - 15.0).abs() < 0.05, "{r}");
+}
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index 22661bd6d4..0267a2d421 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -2662,7 +2662,10 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
let active = app.session.active_sketch;
match hit {
Some(Hit::SketchPoint { sketch, id, .. }) if Some(sketch) == active => {
- app.viewport.point_drag = Some((id, app.session.undo.len(), None))
+ // A point dragged with the rest of a selection slides with it, from where it
+ // was grabbed, rather than going to the cursor.
+ let grab = if dragged_with(app, &id).is_empty() { None } else { on_plane(app, a) };
+ app.viewport.point_drag = Some((id, app.session.undo.len(), grab))
}
Some(Hit::SketchCurve { sketch, id, .. }) if Some(sketch) == active => {
app.viewport.point_drag = on_plane(app, a).map(|q| (id, app.session.undo.len(), Some(q)));
@@ -2697,12 +2700,19 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
&& let Some(mut q) = hover.and_then(|p| on_plane(app, p))
{
let from = grab.unwrap_or(q);
+ let with = dragged_with(app, &id);
// Snap the dragged point (or the line's ends) to other geometry, like drawing.
let snap = {
let st = app.session.world_state();
app.session.active_sketch.and_then(|s| st.sketch(s)).and_then(|ss| {
let sk = &ss.sketch;
- let (own, exclude) = crate::drag_snap::moving_points(sk, &id);
+ let (mut own, mut exclude) = crate::drag_snap::moving_points(sk, &id);
+ for (o, x) in with.iter().map(|w| crate::drag_snap::moving_points(sk, w)) {
+ own.extend(o);
+ exclude.extend(x);
+ }
+ own.sort_unstable();
+ own.dedup();
if own.iter().any(|&p| sk.point_locked(p)) {
return crate::drag_snap::find(sk, &[], &[], 0.0);
}
@@ -2719,7 +2729,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
q += s.offset;
}
// Each frame re-solves the sketch only (`live`); the model follows when the drag ends.
- let at = match app.session.execute("sketch.drag", &json!({"entity": id, "from": [from.x, from.y], "to": [q.x, q.y], "live": true})) {
+ let params = json!({"entity": id, "with": with, "from": [from.x, from.y], "to": [q.x, q.y], "live": true});
+ let at = match app.session.execute("sketch.drag", &params) {
Ok(r) => {
app.session.undo.truncate(depth + 1);
r.get("at").and_then(solidcraft_engine::params::vec2).unwrap_or(q)
@@ -2908,6 +2919,39 @@ pub(crate) fn select(app: &mut SolveApp, sel: Option<Sel>, add: bool, toggle: bo
}
}
+/// The rest of the selected sketch geometry when the point or curve `id` is part of it (#2621):
+/// a drag that starts on a selected entity moves the whole selection with it.
+fn dragged_with(app: &SolveApp, id: &str) -> Vec<String> {
+ fn geometry(s: &Sel) -> Option<&str> {
+ match s {
+ Sel::SketchPoint { id } | Sel::SketchCurve { id } => Some(id.as_str()),
+ _ => None,
+ }
+ }
+ let selected = || app.session.selection.iter().filter_map(geometry);
+ if !selected().any(|s| s == id) {
+ return Vec::new();
+ }
+ let rest: Vec<String> = selected().filter(|s| *s != id).map(str::to_owned).collect();
+ // A curve's own points, selected with it by a window, are not a group: a circle grabbed on
+ // its edge still takes its radius from the drag.
+ let st = app.session.world_state();
+ let own: Vec<&str> = app
+ .session
+ .active_sketch
+ .and_then(|s| st.sketch(s))
+ .and_then(|ss| {
+ let sk = &ss.sketch;
+ let c = sk.curves.get(sk.curve_index(id)?)?;
+ Some(c.kind.point_ids().into_iter().filter_map(|p| sk.points.get(p).map(|p| p.id.as_str())).collect())
+ })
+ .unwrap_or_default();
+ if rest.iter().all(|r| own.contains(&r.as_str())) {
+ return Vec::new();
+ }
+ rest
+}
+
/// What a click on `sel` picks: its pieces ([`grouped_selection`]), and for a letter of a sketch
/// text the whole text, unless Shift is held (Shift picks the one letter).
pub(crate) fn picked_selection(s: &solidcraft_engine::Session, sel: &Sel) -> Vec<Sel> {