Skip to content

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

fix: keep expression move distances on world axes (#7234) (#8508)

Colin Faulkingham99664a4d3526
diff --git a/crates/doc/src/assembly.rs b/crates/doc/src/assembly.rs
index 7775f2afe9..a2473e03a5 100644
--- a/crates/doc/src/assembly.rs
+++ b/crates/doc/src/assembly.rs
@@ -255,6 +255,14 @@ pub fn map_point_expr(m: &Mat, p: &mut crate::PointExpr) {
}
}
+/// Map a displacement given as length expressions, retaining its parameter dependencies.
+/// Unlike a point, a displacement is unaffected by the frame's translation.
+pub fn map_vector_expr(m: &Mat, v: &mut crate::PointExpr) {
+ let mut rotation = *m;
+ rotation[3] = [0.0, 0.0, 0.0, 1.0];
+ map_point_expr(&rotation, v);
+}
+
impl FeatureKind {
/// Map the feature's world geometry (points, directions, explicit planes) by `m`.
pub fn transform_geometry(&mut self, m: &Mat) {
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index e294e9bc0c..09b9336151 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -75,7 +75,7 @@ pub mod text_params;
pub use assembly::{
BomType, IDENTITY, MAX_PLACEMENT_DEPTH, MAX_PLACEMENTS, Mat, Occurrence, WorldNames, apply_point, apply_vector, is_identity, map_point_expr,
- mat_inverse, mat_mul, rigid,
+ map_vector_expr, mat_inverse, mat_mul, rigid,
};
pub use document::*;
pub use eval::{
diff --git a/crates/engine/src/frames.rs b/crates/engine/src/frames.rs
index 64fb163bd3..48b5b269b9 100644
--- a/crates/engine/src/frames.rs
+++ b/crates/engine/src/frames.rs
@@ -10,7 +10,7 @@
//! without moved components).
use serde_json::{Map, Value};
-use solidcraft_doc::{Mat, apply_point, apply_vector, is_identity, map_point_expr, mat_inverse};
+use solidcraft_doc::{Mat, apply_point, apply_vector, is_identity, map_point_expr, map_vector_expr, mat_inverse};
use solidcraft_geom::Vec3;
use crate::Session;
@@ -26,6 +26,8 @@ enum K {
Make,
/// A direction: turned with the command's frame.
Dir,
+ /// A displacement with length expressions: turned without the frame's translation.
+ Delta,
/// A point the command's bodies move about: into the frame of those bodies (the command's
/// frame, as its directions are).
Moved,
@@ -90,7 +92,7 @@ fn table(id: &str) -> &'static [(&'static str, K)] {
"inspect.curvature_comb" | "inspect.minimum_radius" | "inspect.isocurve" => &[("edges", Picks), ("faces", Picks)],
"parts.insert" | "parts.fastener" => &[("at", Pick), ("point", Make), ("direction", Dir)],
"appearance.assign" => &[("faces", Picks), ("bodies", Body), ("body", Body)],
- "solid.move" => &[("bodies", Body), ("translate", Dir), ("axis", Dir), ("origin", Moved)],
+ "solid.move" => &[("bodies", Body), ("translate", Delta), ("axis", Dir), ("origin", Moved)],
"solid.combine" => &[("target", Body), ("tools", Body)],
"solid.remove" | "solid.bounding_solid" | "material.assign" => &[("bodies", Body)],
_ => &[],
@@ -233,12 +235,12 @@ impl Mapper<'_> {
fn make(&mut self, v: &Value) -> Option<Value> {
let m = self.f.active;
- let Some(p) = vec3(v) else { return self.make_expr(&m, v) };
+ let Some(p) = vec3(v) else { return self.map_expr(&m, v, map_point_expr) };
self.local_point(&m, p)
}
- /// A point with expression coordinates (`["w / 2", 0, 0]`): mapped as expressions.
- fn make_expr(&mut self, m: &Mat, v: &Value) -> Option<Value> {
+ /// Coordinates such as `["w / 2", 0, 0]`, mapped without evaluating their expressions.
+ fn map_expr(&mut self, m: &Mat, v: &Value, map: fn(&Mat, &mut solidcraft_doc::PointExpr)) -> Option<Value> {
let a = v.as_array().filter(|a| a.len() == 3)?;
let c = |i: usize| match a.get(i)? {
Value::Number(n) => n.as_f64().filter(|x| x.is_finite()).map(|x| solidcraft_doc::Expr::new(format!("{x}"))),
@@ -250,7 +252,7 @@ impl Mapper<'_> {
return None;
}
let inv = mat_inverse(m)?;
- map_point_expr(&inv, &mut p);
+ map(&inv, &mut p);
self.changed = true;
Some(serde_json::json!(p))
}
@@ -527,6 +529,10 @@ pub fn to_local(s: &Session, id: &str, params: &Value) -> Option<Value> {
Picks => m.picks(v, body.as_deref()),
Make => m.make(v),
Dir => m.dir(v),
+ Delta => m.dir(v).or_else(|| {
+ let frame = m.first.unwrap_or(m.f.active);
+ m.map_expr(&frame, v, map_vector_expr)
+ }),
Moved => {
let frame = m.first.unwrap_or(m.f.active);
vec3(v).and_then(|p| m.local_point(&frame, p))
diff --git a/crates/engine/src/frames_tests.rs b/crates/engine/src/frames_tests.rs
index fcd11c4575..b614f8e4a5 100644
--- a/crates/engine/src/frames_tests.rs
+++ b/crates/engine/src/frames_tests.rs
@@ -217,6 +217,52 @@ fn block_in_component() -> Session {
s
}
+#[test]
+fn move_expression_distances_follow_world_axes_in_a_turned_component() {
+ for translate in [json!([0, -4, 0]), json!(["0 mm", "-4 mm", "0 mm"]), json!([0, "-4", 0])] {
+ let mut s = block_in_component();
+ run(&mut s, "occurrence.move", json!({"occurrence": "C:1", "axis": [1, 0, 0], "angle": "90 deg", "translate": [50, 10, 20]}));
+ let before = world_bbox(&s, "Body1");
+ run(&mut s, "solid.move", json!({"bodies": ["Body1"], "translate": translate}));
+ let after = world_bbox(&s, "Body1");
+ let shift = Vec3::new(0.0, -4.0, 0.0);
+ assert!(near(after.0, before.0 + shift) && near(after.1, before.1 + shift), "{translate}: {before:?} -> {after:?}");
+ assert!((volume(&mut s) - 24_000.0).abs() < 1e-6);
+ }
+}
+
+#[test]
+fn move_expression_distances_keep_parameters_through_rebuild_and_reopen() {
+ for copy in [false, true] {
+ let mut s = block_in_component();
+ run(&mut s, "parameters.add", json!({"name": "travel", "expression": "4 mm"}));
+ // An oblique turn mixes all three coordinates; the placement's translation must
+ // never contribute to the displacement vector.
+ run(&mut s, "occurrence.move", json!({"occurrence": "C:1", "axis": [1, 2, 3], "angle": "37 deg", "translate": [50, 10, 20]}));
+ run(&mut s, "component.activate", json!({"component": "C"}));
+ let before = world_bbox(&s, "Body1");
+ run(&mut s, "solid.move", json!({"bodies": ["Body1"], "translate": [2, "-travel", "1 cm"], "copy": copy}));
+ let moved = s.model.state().bodies.last().unwrap().name.clone();
+ let assert_shift = |s: &Session, travel: f64| {
+ let after = world_bbox(s, &moved);
+ let shift = Vec3::new(2.0, -travel, 10.0);
+ assert!(near(after.0, before.0 + shift) && near(after.1, before.1 + shift), "copy={copy}, travel={travel}: {before:?} -> {after:?}");
+ if copy {
+ let original = world_bbox(s, "Body1");
+ assert!(near(original.0, before.0) && near(original.1, before.1));
+ }
+ };
+ assert_shift(&s, 4.0);
+ run(&mut s, "parameters.change", json!({"name": "travel", "expression": "8 mm"}));
+ assert_shift(&s, 8.0);
+ let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());
+ assert_shift(&reopened, 8.0);
+ run(&mut reopened, "parameters.change", json!({"name": "travel", "expression": "12 mm"}));
+ assert_shift(&reopened, 12.0);
+ assert!((volume(&mut reopened) - if copy { 48_000.0 } else { 24_000.0 }).abs() < 1e-6);
+ }
+}
+
/// Edit Feature passes a primitive's placement through as saved, so changing the radius of
/// Leaf B's rod in the Hinge Assembly leaves the leaf where it was (#2926).
#[test]
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 5eef89329e..a4fc8f7da8 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -6085,11 +6085,27 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option<usize>) -> Option<Dia
}
FeatureKind::Move { bodies, translate, rotate_axis, angle, copy } => {
let mut d = start("solid.move")?;
+ // Move stores distances in the first body's frame, which can differ from the
+ // feature's component. Refill the world distances that the command accepts.
+ let frame = bodies
+ .first()
+ .and_then(|body| {
+ s.placed_document()
+ .body_frames_with_source(&s.model.state())
+ .into_iter()
+ .find(|(world, own, ..)| world == &**body || own == &**body)
+ .map(|(.., frame)| frame)
+ })
+ .unwrap_or_else(|| feature_frame(s, f.component));
+ let mut world_translate = translate.clone();
+ if !solidcraft_engine::doc::is_identity(&frame) {
+ solidcraft_engine::doc::map_vector_expr(&frame, &mut world_translate);
+ }
crate::dialogs_move::for_feature(
&s.doc,
&mut d,
&solidcraft_engine::doc::plain(bodies),
- translate,
+ &world_translate,
rotate_axis.map(Vec3::from),
angle.as_ref(),
*copy,
diff --git a/crates/ui-egui/src/dialogs_move_tests.rs b/crates/ui-egui/src/dialogs_move_tests.rs
index 369952fd77..7aa2d14312 100644
--- a/crates/ui-egui/src/dialogs_move_tests.rs
+++ b/crates/ui-egui/src/dialogs_move_tests.rs
@@ -54,6 +54,37 @@ fn the_main_value_writes_through_to_the_command() {
assert_eq!((x.as_str(), y.as_str(), z.as_str()), ("30 mm", "0 mm", "0 mm"), "the box edits X alone");
}
+#[test]
+fn editing_a_move_in_a_turned_component_keeps_world_distances() {
+ let mut h = crate::scenario::Harness::new();
+ h.app.run("component.create", json!({"name": "Part", "grounded": false})).unwrap();
+ h.app.run("solid.box", json!({"length": 40, "width": 30, "height": 20})).unwrap();
+ h.app.run("parameters.add", json!({"name": "travel", "expression": "4 mm"})).unwrap();
+ h.app.run("occurrence.move", json!({"occurrence": "Part:1", "axis": [1, 0, 0], "angle": "90 deg", "translate": [50, 10, 20]})).unwrap();
+ h.app.run("component.activate", json!({"component": "root"})).unwrap();
+ let moved = h.app.run("solid.move", json!({"bodies": ["Body1"], "translate": ["0 mm", "-travel", "0 mm"]})).unwrap()["feature"].as_u64().unwrap();
+ let bounds = |h: &crate::scenario::Harness| h.app.session.world_state().body("Body1").unwrap().mesh().bounds();
+ let before = bounds(&h);
+ let mut d = crate::dialogs::for_feature(&h.app, moved, None).unwrap();
+ let Kind::Move { x, y, z, .. } = &d.kind else { panic!("not a move") };
+ let displayed = Vec3::new(len(&h.app, x).unwrap(), len(&h.app, y).unwrap(), len(&h.app, z).unwrap());
+ assert!((displayed - Vec3::new(0.0, -4.0, 0.0)).len() < 1e-6, "{displayed:?}");
+ for (command, params) in crate::dialogs::apply_commands(&h.app, &d).unwrap() {
+ h.app.run(&command, params).unwrap();
+ }
+ let after = bounds(&h);
+ assert!((after.min - before.min).len() < 1e-6 && (after.max - before.max).len() < 1e-6, "accepting the unchanged dialog must not move the body");
+ h.app.run("parameters.change", json!({"name": "travel", "expression": "8 mm"})).unwrap();
+ assert!((bounds(&h).min - before.min - Vec3::new(0.0, -4.0, 0.0)).len() < 1e-6);
+ if let Kind::Move { y, .. } = &mut d.kind {
+ *y = "-12 mm".into();
+ }
+ for (command, params) in crate::dialogs::apply_commands(&h.app, &d).unwrap() {
+ h.app.run(&command, params).unwrap();
+ }
+ assert!((bounds(&h).min - before.min - Vec3::new(0.0, -8.0, 0.0)).len() < 1e-6, "edited distances follow world axes too");
+}
+
/// #6822: Rotate must offer a draggable handle after the body and axis are picked.
#[test]
fn rotate_handle_updates_the_angle_without_moving_the_camera() {