Skip to content

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

Move / Copy with Copy on a component copies the component (#9914) (#9930)

momysnowc1612e923472
diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs
index 5a65389ff6..b1c34042ba 100644
--- a/crates/engine/src/cmd/features.rs
+++ b/crates/engine/src/cmd/features.rs
@@ -167,7 +167,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.icon("presspull")
.key("Q")
.params("face: [x,y,z] and distance: expr (positive adds material, negative cuts), or edges: [[x,y,z]…] and distance (a fillet)"),
- CommandSpec::new("solid.move", "Move/Copy", move_bodies).at("SOLID", "MODIFY").icon("move").key("M").enabled(not_in_sketch).params("bodies: [names]; translate?: [x,y,z] (exprs or numbers); axis?: [x,y,z]; angle?: expr; copy?: bool (default false: keeps the original bodies and transforms a new copy instead of moving them in place)"),
+ CommandSpec::new("solid.move", "Move/Copy", move_bodies).at("SOLID", "MODIFY").icon("move").key("M").enabled(not_in_sketch).params("bodies: [names]; translate?: [x,y,z] (exprs or numbers); axis?: [x,y,z]; angle?: expr; copy?: bool (default false: keeps the original bodies and transforms a new copy instead of moving them in place); occurrences?: [occurrence paths, root first] (only with copy: each component is copied as an independent component, as Paste New copies it, and the copy moves by the same translate, axis and angle in the world; the reply lists the copies in occurrences)"),
];
/// Where an extrude starts and which way is positive: a point inside the (first) profile or
@@ -1804,6 +1804,9 @@ fn combine(s: &mut Session, p: &Value) -> Result<Value> {
}
fn move_bodies(s: &mut Session, p: &Value) -> Result<Value> {
+ if let Some(paths) = copied_components(p)? {
+ return copy_components(s, p, paths);
+ }
if let Some(plan) = crate::frames::placements_moved(s, p) {
return move_placements(s, p, plan);
}
@@ -1845,10 +1848,29 @@ fn move_split(s: &mut Session, moves: &[Value]) -> Result<Value> {
Ok(last)
}
-/// A move of several placements of one part (`frames::placements_moved`, #4768): each placement
-/// moved in the world by the move's translation and turn (about the world origin, as the Move
-/// feature turns bodies), and the root component's bodies listed moved as bodies, in one step.
-fn move_placements(s: &mut Session, p: &Value, plan: crate::frames::PlacementMove) -> Result<Value> {
+/// The occurrence paths a copying move copies (`occurrences`, root first), `None` when it names
+/// none. A component is only ever copied, so the move must set `copy`.
+fn copied_components(p: &Value) -> Result<Option<Vec<Vec<u64>>>> {
+ let cmd = "solid.move";
+ let Some(list) = p.get("occurrences") else { return Ok(None) };
+ let paths: Vec<Vec<u64>> = list
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|path| path.as_array().and_then(|ids| ids.iter().map(Value::as_u64).collect::<Option<Vec<u64>>>()).filter(|ids| !ids.is_empty()))
+ .collect::<Option<_>>()
+ .ok_or_else(|| bad(cmd, "`occurrences` must list occurrence paths, each a list of occurrence ids"))?;
+ if paths.is_empty() || paths.len() > 1000 {
+ return Err(bad(cmd, "`occurrences` must list 1…1000 occurrence paths"));
+ }
+ if p.get("copy").and_then(Value::as_bool) != Some(true) {
+ return Err(bad(cmd, "`occurrences` are copied: set `copy` to true"));
+ }
+ Ok(Some(paths))
+}
+
+/// The translation (mm) and turn (radians, if any) of a move in the world.
+fn world_move(s: &Session, p: &Value) -> Result<(Vec<f64>, Option<f64>)> {
let cmd = "solid.move";
let length = |v: &Value| -> Result<f64> {
match v {
@@ -1866,6 +1888,79 @@ fn move_placements(s: &mut Session, p: &Value, plan: crate::frames::PlacementMov
Some(a) => Some(s.doc.eval(&a, Kind::Angle).map_err(|e| bad(cmd, format!("angle: {e}")))?),
None => None,
};
+ Ok((translate, angle))
+}
+
+/// A copying move of components (`occurrences`, with `copy`): each picked placement's component is
+/// copied as an independent component, as Paste New copies it (`component.paste_new`), placed where
+/// the placement is; the copy then moves by the move's translation and turn in the world, as
+/// `occurrence.move` moves a placement. The bodies listed are copied as bodies (see
+/// `move_body_feature`) in the same command, so the whole move is one undo step.
+fn copy_components(s: &mut Session, p: &Value, paths: Vec<Vec<u64>>) -> Result<Value> {
+ let cmd = "solid.move";
+ let (translate, angle) = world_move(s, p)?;
+ let paste = super::find_command("component.paste_new").ok_or_else(|| EngineError::UnknownCommand("component.paste_new".into()))?;
+ let mover = super::find_command("occurrence.move").ok_or_else(|| EngineError::UnknownCommand("occurrence.move".into()))?;
+ // A component inside another one copied here comes with its parent's copy.
+ let mut paths: Vec<Vec<u64>> = paths.into_iter().fold(Vec::new(), |mut out, path| {
+ if !out.contains(&path) {
+ out.push(path);
+ }
+ out
+ });
+ let all = paths.clone();
+ paths.retain(|p| !all.iter().any(|q| q.len() < p.len() && p.starts_with(q)));
+ // The bodies are given in the world; their own component's frame turns them, as a move of bodies
+ // alone is turned, so they are mapped the same way, before any copy is made.
+ let has_bodies = match p.get("bodies") {
+ None => false,
+ Some(Value::Array(bodies)) => !bodies.is_empty(),
+ Some(_) => return Err(bad(cmd, "`bodies` must list bodies")),
+ };
+ let mut rest = p.clone();
+ if let Some(object) = rest.as_object_mut() {
+ object.remove("occurrences");
+ }
+ // Bodies in differently placed frames split by frame (`frames::split_move`, #9660), as a move of them alone does.
+ let split = crate::frames::split_move(s, &rest);
+ let bodies = (has_bodies && split.is_none()).then(|| crate::frames::to_local(s, cmd, &rest).unwrap_or_else(|| rest.clone()));
+ let mut copies = Vec::new();
+ for path in &paths {
+ let Some(&source) = path.last() else { continue };
+ let component =
+ s.doc.occurrences.iter().find(|o| o.id == source).map(|o| o.component).ok_or_else(|| bad(cmd, "`occurrences` names no occurrence"))?;
+ let made = paste.run_nested(s, &json!({"component": component, "occurrence": source, "path": path}))?;
+ let copy = made.get("occurrence").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "the copy has no occurrence"))?;
+ // The copy is placed by the same parent placement as its source.
+ let mut at = path[..path.len() - 1].to_vec();
+ at.push(copy);
+ let mut q = json!({"occurrence": copy, "path": at, "space": "world", "translate": translate});
+ if let Some(axis) = p.get("axis") {
+ q["axis"] = axis.clone();
+ }
+ if let Some(angle) = angle {
+ q["angle"] = json!(angle);
+ }
+ mover.run_nested(s, &q)?;
+ copies.push(copy);
+ }
+ // The reply is a solid.move reply: the bodies' feature reply, with the copies made alongside.
+ let mut out = match (split, bodies) {
+ (Some(moves), _) => move_split(s, &moves)?,
+ (None, Some(local)) => move_body_feature(s, &local)?,
+ (None, None) => json!({}),
+ };
+ if let Some(object) = out.as_object_mut() {
+ object.insert("occurrences".into(), json!(copies));
+ }
+ Ok(out)
+}
+
+/// A move of several placements of one part (`frames::placements_moved`, #4768): each placement
+/// moved in the world by the move's translation and turn (about the world origin, as the Move
+/// feature turns bodies), and the root component's bodies listed moved as bodies, in one step.
+fn move_placements(s: &mut Session, p: &Value, plan: crate::frames::PlacementMove) -> Result<Value> {
+ let (translate, angle) = world_move(s, p)?;
let spec = super::find_command("occurrence.move").ok_or_else(|| EngineError::UnknownCommand("occurrence.move".into()))?;
let mut moved = Vec::new();
for path in &plan.paths {
diff --git a/crates/engine/src/cmd/solid_move_copy_tests.rs b/crates/engine/src/cmd/solid_move_copy_tests.rs
index 7938175409..94590e9ddd 100644
--- a/crates/engine/src/cmd/solid_move_copy_tests.rs
+++ b/crates/engine/src/cmd/solid_move_copy_tests.rs
@@ -181,3 +181,160 @@ fn an_older_design_with_no_copy_key_at_all_still_loads_and_moves_in_place() {
let moved = state.body("Cube").unwrap();
assert!(moved.mesh().bounds().min.dist(Vec3::new(5.0, 0.0, 0.0)) < 1e-6);
}
+
+/// A component `Part` holding a 20 mm cube at the origin, placed once at the root.
+fn part_with_cube(s: &mut Session) -> (u64, u64) {
+ let made = run(s, "component.create", json!({"name": "Part", "grounded": false}));
+ cube20(s, "Peg");
+ run(s, "component.activate", json!({"component": "root"}));
+ (made["component"].as_u64().unwrap(), made["occurrence"].as_u64().unwrap())
+}
+
+/// The component an occurrence is an instance of.
+fn component_of(s: &Session, occurrence: u64) -> u64 {
+ s.doc.occurrences.iter().find(|o| o.id == occurrence).expect("the occurrence exists").component
+}
+
+/// The lowest corner of the first body a placement shows, in the world.
+fn world_min(s: &Session, path: &[u64]) -> Vec3 {
+ let names = s.occurrence_bodies(path, true).unwrap();
+ s.world_state().body(&names[0]).unwrap().mesh().bounds().min
+}
+
+#[test]
+fn copying_a_picked_component_makes_an_independent_component_at_the_moved_place() {
+ let mut s = Session::default();
+ let (part, occurrence) = part_with_cube(&mut s);
+ let before = s.doc.clone();
+ let source = world_min(&s, &[occurrence]);
+ let reply = run(&mut s, "solid.move", json!({"bodies": [], "occurrences": [[occurrence]], "copy": true, "translate": [50, 0, 0]}));
+ let copy = reply["occurrences"][0].as_u64().expect("the move reports the copy it made");
+ let copied = component_of(&s, copy);
+ assert_ne!(copied, part, "an independent copy of the component, not another instance of it");
+ let name = &s.doc.components.iter().find(|c| c.id == copied).expect("the copy is a component").name;
+ assert_eq!(name, "Part (2)", "named the way Paste New names its copies");
+ assert!(world_min(&s, &[copy]).dist(Vec3::new(source.x + 50.0, source.y, source.z)) < 1e-6, "the copy lands at the moved place");
+ assert!(world_min(&s, &[occurrence]).dist(source) < 1e-6, "the original component stays where it was");
+ assert_eq!(s.occurrence_bodies(&[occurrence], true).unwrap().len(), 1, "the original keeps its body");
+ run(&mut s, "edit.undo", json!({}));
+ assert_eq!(s.doc, before, "one undo removes the copy");
+}
+
+#[test]
+fn a_copied_component_turns_with_the_move() {
+ let mut s = Session::default();
+ let (_, occurrence) = part_with_cube(&mut s);
+ let reply = run(
+ &mut s,
+ "solid.move",
+ json!({"bodies": [], "occurrences": [[occurrence]], "copy": true, "translate": [0, 0, 0], "axis": [0, 0, 1], "angle": "90 deg"}),
+ );
+ let copy = reply["occurrences"][0].as_u64().unwrap();
+ // A quarter turn about the origin takes the cube's x from 0..20 to -20..0 and y to 0..20.
+ assert!(world_min(&s, &[copy]).dist(Vec3::new(-20.0, 0.0, 0.0)) < 1e-6, "the copy turns with the move");
+ assert!(world_min(&s, &[occurrence]).dist(Vec3::ZERO) < 1e-6, "the original does not turn");
+}
+
+#[test]
+fn bodies_and_a_component_copied_together_are_one_undo_step() {
+ let mut s = Session::default();
+ let (_, occurrence) = part_with_cube(&mut s);
+ cube20_at(&mut s, "Top", [0, 0, 50]);
+ let before = s.doc.clone();
+ let count = s.model.state().bodies.len();
+ let reply = run(&mut s, "solid.move", json!({"bodies": ["Top"], "occurrences": [[occurrence]], "copy": true, "translate": [50, 0, 0]}));
+ assert_eq!(reply["occurrences"].as_array().map(Vec::len), Some(1));
+ assert!(reply.get("feature").is_some(), "the reply is a solid.move reply: the body feature's, with the copies alongside");
+ assert_eq!(s.model.state().bodies.len(), count + 2, "a copy of the body and of the component");
+ run(&mut s, "edit.undo", json!({}));
+ assert_eq!(s.doc, before, "one undo removes both copies");
+}
+
+/// A copying move of a component and of bodies in differently turned frames (a block in the root
+/// and a screw inserted lying down) is one move: the component's copy turns with it, the bodies
+/// split into one feature per frame as a move of them alone does (#9660), in one undo step.
+#[test]
+fn a_copied_component_and_bodies_in_differently_turned_frames_are_one_undo_step() {
+ let mut s = Session::default();
+ let (_, occurrence) = part_with_cube(&mut s);
+ run(&mut s, "solid.box", json!({"length": 30, "width": 30, "height": 10, "center": [0, 0, 5], "body_name": "Block"}));
+ run(
+ &mut s,
+ "parts.insert",
+ json!({"family": "socket_head_cap_screw", "size": "M3", "length": 12, "point": [0, 0, 10], "direction": [1, 0, 0], "name": "screw"}),
+ );
+ let before = s.doc.clone();
+ let reply = run(
+ &mut s,
+ "solid.move",
+ json!({"bodies": ["Block", "Body1"], "occurrences": [[occurrence]], "copy": true, "axis": [0, 0, 1], "angle": "90 deg"}),
+ );
+ assert_eq!(reply["features"].as_array().map(Vec::len), Some(2), "one Move feature per frame");
+ let copy = reply["occurrences"][0].as_u64().expect("the move reports the copy it made");
+ assert!(world_min(&s, &[copy]).dist(Vec3::new(-20.0, 0.0, 0.0)) < 1e-6, "the copy turns with the move");
+ assert!(world_min(&s, &[occurrence]).dist(Vec3::ZERO) < 1e-6, "the original does not turn");
+ run(&mut s, "edit.undo", json!({}));
+ assert_eq!(s.doc, before, "one undo removes the copies of the component and of the bodies");
+}
+
+#[test]
+fn a_component_picked_with_its_parent_is_copied_once_inside_the_parents_copy() {
+ let mut s = Session::default();
+ // `Outer` at the root holds `Inner`, which holds a 20 mm cube.
+ let outer = run(&mut s, "component.create", json!({"name": "Outer", "grounded": false}))["occurrence"].as_u64().unwrap();
+ let inner = run(&mut s, "component.create", json!({"name": "Inner", "parent": "Outer"}))["occurrence"].as_u64().unwrap();
+ cube20(&mut s, "Peg");
+ run(&mut s, "component.activate", json!({"component": "root"}));
+ let counts = |s: &Session| (s.doc.components.len(), s.doc.occurrences.len(), s.model.state().bodies.len());
+ assert_eq!(counts(&s), (2, 2, 1), "components, occurrences and bodies before the move");
+ let before = s.doc.clone();
+ let source = world_min(&s, &[outer, inner]);
+
+ // Both are picked, Inner inside Outer: Inner comes with its parent's copy, so one copy is made.
+ let reply = run(&mut s, "solid.move", json!({"bodies": [], "occurrences": [[outer], [outer, inner]], "copy": true, "translate": [50, 0, 0]}));
+ assert_eq!(reply["occurrences"].as_array().map(Vec::len), Some(1), "one copy: Inner is copied inside Outer's copy");
+ let copy = reply["occurrences"][0].as_u64().unwrap();
+ assert_eq!(counts(&s), (4, 4, 2), "the copy of Outer and its own Inner, with the cube copied once");
+ assert!(
+ world_min(&s, &[copy]).dist(Vec3::new(source.x + 50.0, source.y, source.z)) < 1e-6,
+ "the copied cube sits 50 mm along X from the original"
+ );
+ assert!(world_min(&s, &[outer, inner]).dist(source) < 1e-6, "the original cube stays where it was");
+
+ run(&mut s, "edit.undo", json!({}));
+ assert_eq!(counts(&s), (2, 2, 1), "one undo puts back the two components, two occurrences and one body");
+ assert_eq!(s.doc, before, "one undo removes the whole copy");
+}
+
+#[test]
+fn a_copy_that_fails_part_way_changes_nothing() {
+ let mut s = Session::default();
+ let (_, occurrence) = part_with_cube(&mut s);
+ let before = s.doc.clone();
+ let undo = s.undo.len();
+ // The first component copies; the second names no occurrence, so the whole move is refused.
+ let error = s.execute("solid.move", &json!({"bodies": [], "occurrences": [[occurrence], [999_999]], "copy": true, "translate": [50, 0, 0]}));
+ assert!(error.is_err());
+ assert_eq!(s.doc, before, "the first copy is rolled back with the rest");
+ assert_eq!(s.undo.len(), undo, "a refused move leaves no undo step");
+}
+
+#[test]
+fn components_move_only_as_copies() {
+ let mut s = Session::default();
+ let (_, occurrence) = part_with_cube(&mut s);
+ let before = s.doc.clone();
+ let error = s.execute("solid.move", &json!({"bodies": [], "occurrences": [[occurrence]], "translate": [50, 0, 0]})).unwrap_err();
+ assert!(error.to_string().contains("copy"), "{error}");
+ assert_eq!(s.doc, before, "a refused move changes nothing");
+}
+
+#[test]
+fn bodies_that_are_not_a_list_are_refused_with_components() {
+ let mut s = Session::default();
+ let (_, occurrence) = part_with_cube(&mut s);
+ let before = s.doc.clone();
+ let error = s.execute("solid.move", &json!({"bodies": "Peg", "occurrences": [[occurrence]], "copy": true, "translate": [50, 0, 0]})).unwrap_err();
+ assert!(error.to_string().contains("bodies"), "{error}");
+ assert_eq!(s.doc, before, "a refused move changes nothing");
+}
diff --git a/crates/engine/src/frames.rs b/crates/engine/src/frames.rs
index 313f13e1d5..5c60938917 100644
--- a/crates/engine/src/frames.rs
+++ b/crates/engine/src/frames.rs
@@ -495,8 +495,9 @@ fn map_params(s: &Session, id: &str, params: &Value) -> Option<Value> {
return Some(out);
}
// Several placements of one part moved together are moved as placements, in the world
- // (`placements_moved`): their names and vectors stay as given.
- if id == "solid.move" && placements_moved(s, params).is_some() {
+ // (`placements_moved`), and components copied (`occurrences`) likewise: their names and vectors
+ // stay as given. Bodies listed with them are mapped by `copy_components`.
+ if id == "solid.move" && (params.get("occurrences").is_some() || placements_moved(s, params).is_some()) {
return None;
}
if id == "timeline.redefine" {
diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs
index a4b198e9b0..3703d7ce09 100644
--- a/crates/ui-egui/src/browser.rs
+++ b/crates/ui-egui/src/browser.rs
@@ -1701,7 +1701,7 @@ fn occurrence_rows_inner(
if r.double && !takes_components && app.session.doc.parts.contains_key(&placement.component) {
crate::dialogs_part_size::open(app, placement.component);
}
- if r.clicked && takes_components {
+ if r.clicked && (takes_components || crate::dialogs_move::picks_components(app)) {
if let Some(mut d) = app.dialog.take() {
d.pick(&app.session, Sel::Occurrence { path: path.to_vec() });
app.dialog = Some(d);
diff --git a/crates/ui-egui/src/browser_model_tests.rs b/crates/ui-egui/src/browser_model_tests.rs
index 9ebf21d6fa..167255ba5c 100644
--- a/crates/ui-egui/src/browser_model_tests.rs
+++ b/crates/ui-egui/src/browser_model_tests.rs
@@ -237,6 +237,15 @@ fn body_names(app: &crate::SolveApp) -> Vec<String> {
.unwrap_or_default()
}
+/// The bodies the open Move/Copy would move, a picked component's bodies included.
+fn move_bodies(app: &crate::SolveApp) -> Vec<String> {
+ let Some(d) = app.dialog.as_ref() else { return Vec::new() };
+ crate::dialogs_move::params(app, d)
+ .ok()
+ .and_then(|p| p["bodies"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect()))
+ .unwrap_or_default()
+}
+
fn two_bodies(h: &mut crate::scenario::Harness) {
h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Left"})).unwrap();
h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [30, 0, 0], "body_name": "Right"})).unwrap();
@@ -309,7 +318,7 @@ fn browser_move_copy_takes_a_component_clicked_in_the_tree() {
open_move(&mut h);
h.frames(2);
click(&mut h, &format!("row:occurrence:{occurrence}"));
- assert_eq!(body_names(&h.app), owned, "the component's bodies are the Move/Copy selection");
+ assert_eq!(move_bodies(&h.app), owned, "the component's bodies are the Move/Copy selection");
assert!(h.app.tree.occurrence_move.is_none(), "the open body dialog stays; this click does not switch to component Move");
h.app.dialog = None;
@@ -318,7 +327,7 @@ fn browser_move_copy_takes_a_component_clicked_in_the_tree() {
click(&mut h, "row:Untitled");
assert_eq!(h.app.tree.picked_components, vec![0]);
h.app.start("solid.move");
- let names = body_names(&h.app);
+ let names = move_bodies(&h.app);
assert!(names.iter().any(|n| owned.contains(n)), "Move/Copy starts from the component picked in the tree: {names:?}");
}
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index df2e2ae34b..81b275d359 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -1125,6 +1125,19 @@ impl Dialog {
continue;
}
}
+ // Move/Copy keeps a selected component as the component, so Create Copy can still be
+ // ticked after it (the bodies are what a move without a copy moves).
+ if matches!(d.kind, Kind::Move { .. })
+ && let Sel::Occurrence { path } = sel
+ && !path.is_empty()
+ && let Some(inp) = d.inputs.first_mut()
+ && inp.accept == BODIES
+ {
+ if !inp.items.contains(sel) {
+ inp.items.push(sel.clone());
+ }
+ continue;
+ }
let as_body = match sel {
Sel::Face { body, .. } | Sel::Edge { body, .. } | Sel::Vertex { body, .. } => Some(Sel::Body { name: body.to_string() }),
_ => None,
diff --git a/crates/ui-egui/src/dialogs_move.rs b/crates/ui-egui/src/dialogs_move.rs
index 87a3904e2f..5dabbab22e 100644
--- a/crates/ui-egui/src/dialogs_move.rs
+++ b/crates/ui-egui/src/dialogs_move.rs
@@ -98,7 +98,7 @@ pub(crate) fn chained(app: &SolveApp) -> Option<(Vec<String>, Mat)> {
(Some(s), None) => s,
(None, c) => c?,
};
- (!is_identity(&m)).then(|| (items(d, 0).body_names(), m))
+ (!is_identity(&m)).then(|| (bodies_of(app, d), m))
}
/// Whether the triad is being dragged in a Move dialog (`drag` keeps the values it began from).
@@ -117,7 +117,7 @@ fn made(app: &SolveApp, d: &Dialog) -> Option<Mat> {
/// Where a point a pick keeps on moved body `body` (see [`from_shown`]) shows: moved on by the
/// current type's own move.
pub(crate) fn shown_point(app: &SolveApp, body: &str, p: Vec3) -> Vec3 {
- let Some(d) = app.dialog.as_ref().filter(|d| matches!(d.kind, Kind::Move { .. }) && items(d, 0).body_names().iter().any(|n| n == body)) else {
+ let Some(d) = app.dialog.as_ref().filter(|d| matches!(d.kind, Kind::Move { .. }) && bodies_of(app, d).iter().any(|n| n == body)) else {
return p;
};
made(app, d).map_or(p, |m| apply_point(&m, p))
@@ -128,7 +128,7 @@ pub(crate) fn shown_point(app: &SolveApp, body: &str, p: Vec3) -> Vec3 {
/// own move. Kept there, a pivot or From point picked mid-move doesn't move with the move it
/// sets.
pub(crate) fn from_shown(app: &SolveApp, sel: Sel) -> Sel {
- let Some(d) = app.dialog.as_ref().filter(|d| matches!(d.kind, Kind::Move { .. }) && on_moved(d, &sel)) else { return sel };
+ let Some(d) = app.dialog.as_ref().filter(|d| matches!(d.kind, Kind::Move { .. }) && on_moved(&bodies_of(app, d), &sel)) else { return sel };
let Some(back) = made(app, d).and_then(|m| mat_inverse(&m)) else { return sel };
match sel {
Sel::Edge { body, index, point } => Sel::Edge { body, index, point: apply_point(&back, point) },
@@ -138,14 +138,86 @@ pub(crate) fn from_shown(app: &SolveApp, sel: Sel) -> Sel {
}
}
-/// Whether a pick is on one of the bodies being moved.
-fn on_moved(d: &Dialog, s: &Sel) -> bool {
+/// Whether a pick is on one of the bodies being moved (`moved`, see [`bodies_of`]).
+fn on_moved(moved: &[String], s: &Sel) -> bool {
match s {
- Sel::Edge { body, .. } | Sel::Face { body, .. } | Sel::Vertex { body, .. } => items(d, 0).body_names().contains(body),
+ Sel::Edge { body, .. } | Sel::Face { body, .. } | Sel::Vertex { body, .. } => moved.contains(body),
_ => false,
}
}
+/// The bodies the picks stand for: the bodies picked, and the bodies of each picked component
+/// (the bodies its placement shows, as a Browser row lists them).
+fn bodies_of(app: &SolveApp, d: &Dialog) -> Vec<String> {
+ let mut out: Vec<String> = Vec::new();
+ for sel in items(d, 0) {
+ let names = match sel {
+ Sel::Body { name } => vec![name.clone()],
+ Sel::Occurrence { path } => app.session.occurrence_bodies(path, true).unwrap_or_default(),
+ _ => Vec::new(),
+ };
+ for name in names {
+ if !out.contains(&name) {
+ out.push(name);
+ }
+ }
+ }
+ out
+}
+
+/// Whether Create Copy is ticked.
+fn copies(d: &Dialog) -> bool {
+ d.extra.get("copy").and_then(Value::as_bool).unwrap_or(false)
+}
+
+/// Whether a Move dialog takes the components picked (not their bodies) into its bodies input: a
+/// click on a component in the component pick mode, or a Browser row. Not when it edits a move
+/// that is already a feature (its picks stay bodies). Without Create Copy the components still
+/// move their bodies (`targets`).
+pub(crate) fn picks_components(app: &SolveApp) -> bool {
+ app.dialog.as_ref().is_some_and(|d| matches!(d.kind, Kind::Move { .. }) && d.active == 0 && d.editing.is_none())
+}
+
+/// What a click picks in a Move dialog: with the component pick mode on, the component a body
+/// belongs to (copied as a component with Create Copy, see `targets`), otherwise the pick as it was.
+pub(crate) fn component_pick(app: &SolveApp, hit: &crate::viewport::Hit, sel: Sel) -> Sel {
+ let (crate::viewport::Hit::Face { body, .. }, Sel::Body { .. }) = (hit, &sel) else { return sel };
+ if app.ui.pick_components && picks_components(app) {
+ let occurrence = crate::viewport::component_selection(app, body);
+ if matches!(occurrence, Sel::Occurrence { .. }) {
+ return occurrence;
+ }
+ }
+ sel
+}
+
+/// What the move moves and copies, as solid.move takes them: the bodies, and with Create Copy the
+/// components picked (copied as components, see `occurrences`).
+fn targets(app: &SolveApp, d: &Dialog) -> (Vec<String>, Vec<Vec<u64>>) {
+ if !copies(d) {
+ return (bodies_of(app, d), Vec::new());
+ }
+ let components = items(d, 0)
+ .iter()
+ .filter_map(|s| match s {
+ Sel::Occurrence { path } => Some(path.clone()),
+ _ => None,
+ })
+ .collect();
+ (items(d, 0).body_names(), components)
+}
+
+/// The solid.move parameters that name what the move moves (`bodies`, and `occurrences` when
+/// there are components to copy).
+fn targets_json(app: &SolveApp, d: &Dialog) -> Value {
+ let (bodies, components) = targets(app, d);
+ let mut p = json!({ "bodies": bodies });
+ if !components.is_empty() {
+ p["occurrences"] = json!(components);
+ }
+ p
+}
+
/// A point of the model before this move where the earlier types' move puts it: on a moved body
/// (`moved`) or, for the bodies' centre, always.
fn carried(d: &Dialog, moved: bool, p: Vec3) -> Vec3 {
@@ -193,7 +265,7 @@ fn sel_point(app: &SolveApp, d: &Dialog, s: Option<&Sel>) -> Option<Vec3> {
None => app.session.world_state(),
};
// The centre is found where the body was modelled; the picked point is where it stands.
- Some(crate::dialogs::edge_circle_in(&st, body, *index).map_or(*point, |(c, ..)| carried(d, on_moved(d, s), c)))
+ Some(crate::dialogs::edge_circle_in(&st, body, *index).map_or(*point, |(c, ..)| carried(d, on_moved(&bodies_of(app, d), s), c)))
}
Sel::Vertex { point, .. } | Sel::Face { point, .. } => Some(*point),
_ => None,
@@ -211,7 +283,7 @@ fn bodies_center(app: &SolveApp, d: &Dialog) -> Option<Vec3> {
None => app.session.model.state(),
};
let mut bb: Option<(Vec3, Vec3)> = None;
- for n in items(d, 0).body_names() {
+ for n in bodies_of(app, d) {
let Some(b) = st.body(&n) else { continue };
let x = b.mesh().bounds();
bb = Some(match bb {
@@ -271,7 +343,7 @@ pub fn params(app: &SolveApp, d: &Dialog) -> Result<Value, String> {
let made = transform(app, &p)?;
with_transform(p, &mat_mul(&made, &c))
}
- (Step::Needs(_), Some(c)) => with_transform(json!({ "bodies": items(d, 0).body_names() }), &c),
+ (Step::Needs(_), Some(c)) => with_transform(targets_json(app, d), &c),
};
if d.extra.get("copy").and_then(Value::as_bool).unwrap_or(false) {
p["copy"] = json!(true);
@@ -323,13 +395,13 @@ fn with_transform(mut p: Value, m: &Mat) -> Value {
/// The current type's own move, from where the earlier types leave the bodies.
fn step(app: &SolveApp, d: &Dialog) -> Result<Step, String> {
let Kind::Move { mode, x, y, z, rx, ry, rz, angle } = &d.kind else { return Err("not a move".into()) };
- let bodies = items(d, 0).body_names();
- if bodies.is_empty() {
+ let (bodies, components) = targets(app, d);
+ if bodies.is_empty() && components.is_empty() {
return Err("select bodies first".into());
}
let need_point = |i: usize, what: &str| sel_point(app, d, items(d, i).first()).ok_or(format!("select {what} first"));
let num = |t: Vec3| json!([mm(t.x), mm(t.y), mm(t.z)]);
- let mut p = json!({ "bodies": bodies });
+ let mut p = targets_json(app, d);
match *mode {
TRANSLATE => p["translate"] = json!([x, y, z]),
FREE => {
@@ -398,7 +470,7 @@ fn step(app: &SolveApp, d: &Dialog) -> Result<Step, String> {
fn axis_line(app: &SolveApp, d: &Dialog, s: &Sel) -> Option<(Vec3, Vec3)> {
let (o, a) = modelled_axis(app, s)?;
match chain(d) {
- Some(c) if on_moved(d, s) => Some((apply_point(&c, o), apply_vector(&c, a))),
+ Some(c) if on_moved(&bodies_of(app, d), s) => Some((apply_point(&c, o), apply_vector(&c, a))),
_ => Some((o, a)),
}
}
diff --git a/crates/ui-egui/src/dialogs_move_tests.rs b/crates/ui-egui/src/dialogs_move_tests.rs
index 1657d64c25..eecd6b944f 100644
--- a/crates/ui-egui/src/dialogs_move_tests.rs
+++ b/crates/ui-egui/src/dialogs_move_tests.rs
@@ -643,3 +643,109 @@ fn editing_a_move_about_a_world_axis_keeps_the_angle_expression() {
let Kind::Move { rx, ry, rz, .. } = &d.kind else { panic!("not a move") };
assert_eq!((rx.as_str(), ry.as_str(), rz.as_str()), ("0 deg", "0 deg", "45 deg"));
}
+
+/// A design with a component `Part` holding a 20 mm cube at the origin, seen from above, with no
+/// dialog open. Returns the harness and the part's placement.
+fn part_harness() -> (crate::scenario::Harness, u64) {
+ let mut h = crate::scenario::Harness::new();
+ let made = h.app.run("component.create", json!({"name": "Part", "grounded": false})).unwrap();
+ h.app.run("solid.box", json!({"length": 20, "width": 20, "height": 20, "body_name": "Peg"})).unwrap();
+ h.app.run("component.activate", json!({"component": "root"})).unwrap();
+ h.app.ui.show_browser = false;
+ h.app.ui.show_timeline = false;
+ h.app.set_origin_shown(false);
+ h.step(&json!({"call": "ui.view", "params": {"view": "top"}})).unwrap();
+ (h, made["occurrence"].as_u64().unwrap())
+}
+
+/// Opens Move/Copy with the viewport in component (`components`) or body pick mode, Create Copy
+/// ticked or not, then clicks the top of the cube.
+fn click_cube_in_move(components: bool, copy: bool) -> (crate::scenario::Harness, u64) {
+ let (mut h, occurrence) = part_harness();
+ h.app.start("solid.move");
+ h.settle();
+ h.app.ui.pick_components = components;
+ h.app.ui.pick_bodies = !components;
+ if copy {
+ h.app.dialog.as_mut().unwrap().extra.insert("copy".into(), json!(true));
+ }
+ h.step(&json!({"click": {"world": [10, 10, 20]}})).unwrap();
+ (h, occurrence)
+}
+
+#[test]
+fn a_component_picked_with_create_copy_is_moved_as_a_component_copy() {
+ let (h, occurrence) = click_cube_in_move(true, true);
+ let d = h.app.dialog.as_ref().unwrap();
+ assert_eq!(d.inputs[0].items, vec![Sel::Occurrence { path: vec![occurrence] }]);
+ let p = crate::dialogs_move::params(&h.app, d).unwrap();
+ assert_eq!(p["occurrences"], json!([[occurrence]]));
+ assert_eq!(p["bodies"], json!([]));
+ assert_eq!(p["copy"], json!(true));
+}
+
+#[test]
+fn a_body_picked_with_create_copy_is_still_a_body_copy() {
+ let (h, _) = click_cube_in_move(false, true);
+ let d = h.app.dialog.as_ref().unwrap();
+ assert!(matches!(d.inputs[0].items.as_slice(), [Sel::Body { .. }]), "{:?}", d.inputs[0].items);
+ let p = crate::dialogs_move::params(&h.app, d).unwrap();
+ assert_eq!(p["bodies"].as_array().map(Vec::len), Some(1));
+ assert!(p.get("occurrences").is_none());
+ assert_eq!(p["copy"], json!(true));
+}
+
+#[test]
+fn a_component_picked_without_create_copy_moves_its_bodies_as_before() {
+ let (h, occurrence) = click_cube_in_move(true, false);
+ let d = h.app.dialog.as_ref().unwrap();
+ assert_eq!(d.inputs[0].items, vec![Sel::Occurrence { path: vec![occurrence] }]);
+ let p = crate::dialogs_move::params(&h.app, d).unwrap();
+ assert_eq!(p["bodies"].as_array().map(Vec::len), Some(1), "the component's body moves");
+ assert!(p.get("occurrences").is_none());
+ assert!(p.get("copy").is_none());
+}
+
+#[test]
+fn a_component_picked_before_create_copy_is_ticked_is_copied_as_a_component() {
+ let (mut h, occurrence) = click_cube_in_move(true, false);
+ h.app.dialog.as_mut().unwrap().extra.insert("copy".into(), json!(true));
+ let p = crate::dialogs_move::params(&h.app, h.app.dialog.as_ref().unwrap()).unwrap();
+ assert_eq!(p["occurrences"], json!([[occurrence]]));
+ let placements = h.app.session.doc.occurrences.len();
+ h.app.session.execute("solid.move", &p).unwrap();
+ assert_eq!(h.app.session.doc.occurrences.len(), placements + 1, "OK copies the component");
+}
+
+#[test]
+fn editing_a_move_never_takes_a_component_pick() {
+ // An existing move of another body is edited, and the component is clicked in component mode.
+ let (mut h, _) = part_harness();
+ h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [100, 0, 0], "body_name": "Plate"})).unwrap();
+ let moved = h.app.run("solid.move", json!({"bodies": ["Plate"], "translate": [0, 0, 5]})).unwrap()["feature"].as_u64().unwrap();
+ h.app.dialog = Some(crate::dialogs::for_feature(&h.app, moved, None).unwrap());
+ h.settle();
+ h.app.ui.pick_components = true;
+ h.app.ui.pick_bodies = false;
+ h.step(&json!({"click": {"world": [10, 10, 20]}})).unwrap();
+ let items = h.app.dialog.as_ref().unwrap().inputs[0].items.clone();
+ assert!(items.iter().any(|s| matches!(s, Sel::Body { name } if name == "Peg")), "the click picks the body: {items:?}");
+ assert!(!items.iter().any(|s| matches!(s, Sel::Occurrence { .. })), "an edited move's picks stay bodies: {items:?}");
+}
+
+#[test]
+fn selected_components_are_copied_when_create_copy_is_ticked_after_them() {
+ // One selected placement starts the Browser's own component move, so two are selected here.
+ let (mut h, first) = part_harness();
+ let second = h.app.run("occurrence.copy", json!({"occurrence": first, "translate": [50, 0, 0]})).unwrap()["occurrence"].as_u64().unwrap();
+ h.app.session.selection = vec![Sel::Occurrence { path: vec![first] }, Sel::Occurrence { path: vec![second] }];
+ h.app.start("solid.move");
+ let picked = vec![Sel::Occurrence { path: vec![first] }, Sel::Occurrence { path: vec![second] }];
+ assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].items, picked);
+ let p = crate::dialogs_move::params(&h.app, h.app.dialog.as_ref().unwrap()).unwrap();
+ assert_eq!(p["bodies"].as_array().map(Vec::len), Some(2), "without a copy the components' bodies move");
+ assert!(p.get("occurrences").is_none());
+ h.app.dialog.as_mut().unwrap().extra.insert("copy".into(), json!(true));
+ let p = crate::dialogs_move::params(&h.app, h.app.dialog.as_ref().unwrap()).unwrap();
+ assert_eq!(p["occurrences"], json!([[first], [second]]));
+}
diff --git a/crates/ui-egui/src/move_preview.rs b/crates/ui-egui/src/move_preview.rs
index 76a8ac2a64..bd0a65f105 100644
--- a/crates/ui-egui/src/move_preview.rs
+++ b/crates/ui-egui/src/move_preview.rs
@@ -23,11 +23,12 @@ pub(crate) struct MovePreview {
cached: Option<Cached>,
}
-/// The listed bodies' world meshes, for the design and revision they were taken from.
+/// The world meshes of the bodies drawn (the listed bodies, and the bodies of the components
+/// copied), for the design and revision they were taken from.
struct Cached {
document: Arc<Document>,
revision: u64,
- bodies: Vec<String>,
+ names: Vec<String>,
meshes: Vec<Arc<Mesh>>,
}
@@ -71,25 +72,38 @@ impl MovePreview {
return None;
}
let bodies: Vec<String> = params.get("bodies")?.as_array()?.iter().map(|b| b.as_str().map(str::to_string)).collect::<Option<_>>()?;
- if bodies.is_empty() {
+ // The components copied (`occurrences`): their bodies are drawn moved, as copies of them.
+ let components: Vec<Vec<u64>> = match params.get("occurrences") {
+ None => Vec::new(),
+ Some(Value::Array(list)) => {
+ list.iter().map(|path| path.as_array()?.iter().map(Value::as_u64).collect::<Option<Vec<u64>>>()).collect::<Option<_>>()?
+ }
+ Some(_) => return None,
+ };
+ if bodies.is_empty() && components.is_empty() {
return None;
}
- if self
- .cached
- .as_ref()
- .is_none_or(|c| c.revision != app.session.revision || !Arc::ptr_eq(&c.document, &app.session.doc) || c.bodies != bodies)
+ let copy = params.get("copy").and_then(Value::as_bool) == Some(true);
+ // Only a copy takes components (the engine refuses them otherwise).
+ if !components.is_empty() && !copy {
+ return None;
+ }
+ let mut names = bodies.clone();
+ for path in &components {
+ names.extend(app.session.occurrence_bodies(path, true).ok()?);
+ }
+ if self.cached.as_ref().is_none_or(|c| c.revision != app.session.revision || !Arc::ptr_eq(&c.document, &app.session.doc) || c.names != names)
{
let state = app.session.world_state();
- let meshes: Vec<Arc<Mesh>> = bodies.iter().map(|n| state.body(n).map(|b| b.mesh())).collect::<Option<_>>()?;
+ let meshes: Vec<Arc<Mesh>> = names.iter().map(|n| state.body(n).map(|b| b.mesh())).collect::<Option<_>>()?;
if meshes.iter().map(|m| m.triangles.len()).sum::<usize>() > MAX_TRIANGLES {
return None;
}
- self.cached = Some(Cached { document: app.session.doc.clone(), revision: app.session.revision, bodies: bodies.clone(), meshes });
+ self.cached = Some(Cached { document: app.session.doc.clone(), revision: app.session.revision, names: names.clone(), meshes });
}
let cache = self.cached.as_ref()?;
// About the world origin, as the Move feature turns bodies (`kernel::transform`).
let m = rigid(translate, Vec3::ZERO, axis, angle);
- let copy = params.get("copy").and_then(Value::as_bool) == Some(true);
let mut scene = GpuScene::default();
let removed = scene.color(colors.removed);
let mut bounds = Aabb3::EMPTY;
@@ -205,4 +219,31 @@ mod tests {
}
assert!(pv.compute(&app, &[("solid.extrude".to_string(), json!({}))], c).is_none());
}
+
+ /// A copy of a component is drawn where the copy lands: the component's bodies moved, the
+ /// component itself left where it was, so the preview is not the scratch design's.
+ #[test]
+ fn a_component_copy_is_previewed_where_the_copy_lands() {
+ let mut s = Session::default();
+ s.execute("solid.box", &json!({"length": 20, "width": 10, "height": 5, "body_name": "Plate"})).unwrap();
+ let made = s.execute("component.create", &json!({"name": "Part", "grounded": false})).unwrap();
+ s.execute("solid.box", &json!({"length": 20, "width": 10, "height": 15, "body_name": "Peg"})).unwrap();
+ s.execute("component.activate", &json!({"component": "root"})).unwrap();
+ let occurrence = made["occurrence"].as_u64().unwrap();
+ let app = SolveApp::new(s, Services::default());
+ let c = colors(&app);
+ let mut pv = MovePreview::default();
+ // The component's box is 0..20 along X; the copy lands 50 mm along.
+ let copy = [("solid.move".to_string(), json!({"bodies": [], "occurrences": [[occurrence]], "copy": true, "translate": [50, 0, 0]}))];
+ let built = pv.compute(&app, &copy, c).expect("taken here").expect("built");
+ assert!(built.replaced.is_empty(), "a copy keeps the original shown");
+ assert!(near(Vec3::new(built.bounds.min.x, 0.0, 0.0), Vec3::new(50.0, 0.0, 0.0)), "{:?}", built.bounds);
+ assert!(near(Vec3::new(built.bounds.max.x, 0.0, 0.0), Vec3::new(70.0, 0.0, 0.0)), "{:?}", built.bounds);
+ // With bodies listed too, the component's copy is drawn alongside the body's: the
+ // component's box is 15 mm tall, the Plate 5 mm, so the height shows it is there.
+ let mixed = [("solid.move".to_string(), json!({"bodies": ["Plate"], "occurrences": [[occurrence]], "copy": true, "translate": [50, 0, 0]}))];
+ let built = pv.compute(&app, &mixed, c).expect("taken here").expect("built");
+ assert!(near(Vec3::new(built.bounds.min.x, 0.0, 0.0), Vec3::new(50.0, 0.0, 0.0)), "{:?}", built.bounds);
+ assert!(near(Vec3::new(0.0, 0.0, built.bounds.max.z), Vec3::new(0.0, 0.0, 15.0)), "{:?}", built.bounds);
+ }
}
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index 12db428bd7..12fd046c54 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -3159,7 +3159,9 @@ pub(crate) fn sketch_constraint_at(app: &SolveApp, pos: Pos2, hit: Option<&Hit>)
pub fn candidate(app: &SolveApp, hits: &[Hit]) -> Option<(Hit, Sel)> {
if let Some(d) = app.dialog.as_ref().filter(|d| d.wants_picks()) {
let snap = d.face_snap(&app.session, hits);
- return hits.iter().find_map(|h| d.candidate_on(&app.session, h, snap.as_ref()).map(|s| (h.clone(), s)));
+ return hits
+ .iter()
+ .find_map(|h| d.candidate_on(&app.session, h, snap.as_ref()).map(|s| (h.clone(), crate::dialogs_move::component_pick(app, h, s))));
}
hits.iter().filter(|h| pick_allowed(app, h)).find_map(|h| hit_candidate(app, h))
}
@@ -3170,7 +3172,10 @@ pub fn candidates(app: &SolveApp, hits: &[Hit]) -> Vec<(Hit, Sel)> {
// The face under the cursor is looked up once for every sketch point a face place may
// snap to, before Select Other caps its rows.
let snap = d.face_snap(&app.session, hits);
- return hits.iter().filter_map(|h| d.candidate_on(&app.session, h, snap.as_ref()).map(|s| (h.clone(), s))).collect();
+ return hits
+ .iter()
+ .filter_map(|h| d.candidate_on(&app.session, h, snap.as_ref()).map(|s| (h.clone(), crate::dialogs_move::component_pick(app, h, s))))
+ .collect();
}
hits.iter().filter(|h| pick_allowed(app, h)).filter_map(|h| hit_candidate(app, h)).collect()
}