diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index c1ea4a5a7..2b00a1a4d 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -1481,6 +1481,57 @@ fn combine(s: &mut Session, p: &Value) -> Result { } fn move_bodies(s: &mut Session, p: &Value) -> Result { + if let Some(plan) = crate::frames::placements_moved(s, p) { + return move_placements(s, p, plan); + } + move_body_feature(s, p) +} + +/// 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 { + let cmd = "solid.move"; + let length = |v: &Value| -> Result { + match v { + Value::Number(n) => n.as_f64().ok_or_else(|| bad(cmd, "translate entries must be numbers or expressions")), + Value::String(e) => s.doc.eval(e, Kind::Length).map_err(|e| bad(cmd, format!("translate: {e}"))), + _ => Err(bad(cmd, "translate entries must be numbers or expressions")), + } + }; + let translate = match p.get("translate") { + Some(Value::Array(a)) if a.len() == 3 => a.iter().map(length).collect::>>()?, + None => vec![0.0; 3], + _ => return Err(bad(cmd, "`translate` must be [x, y, z]")), + }; + let angle = match expr(p, "angle") { + Some(a) => Some(s.doc.eval(&a, Kind::Angle).map_err(|e| bad(cmd, format!("angle: {e}")))?), + None => None, + }; + 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 { + let Some(&occurrence) = path.last() else { continue }; + let mut q = json!({"occurrence": occurrence, "path": path, "space": "world", "translate": translate}); + if let Some(axis) = p.get("axis") { + q["axis"] = axis.clone(); + } + if let Some(angle) = angle { + q["angle"] = json!(angle); + } + spec.run_nested(s, &q)?; + moved.push(occurrence); + } + let mut out = json!({"placements": moved}); + if !plan.bodies.is_empty() { + let mut rest = p.clone(); + rest["bodies"] = json!(plan.bodies); + out["bodies"] = move_body_feature(s, &rest)?; + } + Ok(out) +} + +fn move_body_feature(s: &mut Session, p: &Value) -> Result { let cmd = "solid.move"; let bodies = string_list(p, "bodies"); if bodies.is_empty() { diff --git a/crates/engine/src/cmd/features_more_tests.rs b/crates/engine/src/cmd/features_more_tests.rs index 5620ff88e..a4120c9bf 100644 --- a/crates/engine/src/cmd/features_more_tests.rs +++ b/crates/engine/src/cmd/features_more_tests.rs @@ -1953,3 +1953,96 @@ fn a_sketch_coil_never_panics_on_hostile_parameters() { assert!(!matches!(result, Err(crate::EngineError::Internal(..))), "profiles {profiles} panicked: {result:?}"); } } + +fn placed_bounds(s: &Session, name: &str) -> solidcraft_geom::Aabb3 { + s.world_state().body(name).unwrap_or_else(|| panic!("no {name}")).mesh().bounds() +} + +fn about(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +/// Frees every grounded placement (a design's first part starts grounded), so a move can take it. +fn unground_all(s: &mut Session) { + let grounded: Vec = s.doc.occurrences.iter().filter(|o| o.grounded).map(|o| o.id).collect(); + for occurrence in grounded { + run(s, "occurrence.ground", json!({"occurrence": occurrence, "grounded": false})); + } +} + +/// A part placed twice, the copy turned a quarter about X and set at x = 100: `Blade` at +/// x 0…20, y 0…8, z 0…30 and its copy at x 100…120, y −30…0, z 0…8. +fn twice_placed_blade(s: &mut Session) -> (String, String) { + let made = run(s, "component.create", json!({"name": "Blade"})); + run(s, "solid.box", json!({"length": 20, "width": 8, "height": 30, "body_name": "Blade"})); + run(s, "component.activate", json!({"component": 0})); + let copy = run(s, "occurrence.copy", json!({"occurrence": made["occurrence"]})); + run(s, "occurrence.move", json!({"occurrence": copy["occurrence"], "axis": [1, 0, 0], "angle": "90 deg"})); + run(s, "occurrence.move", json!({"occurrence": copy["occurrence"], "translate": [100, 0, 0], "space": "world"})); + let names: Vec = s.world_state().bodies.iter().map(|b| b.name.clone()).collect(); + assert_eq!(names.len(), 2, "{names:?}"); + unground_all(s); + (names[0].clone(), names[1].clone()) +} + +fn shifted(a: solidcraft_geom::Aabb3, b: solidcraft_geom::Aabb3, by: [f64; 3]) -> bool { + [ + (a.min.x, b.min.x, by[0]), + (a.max.x, b.max.x, by[0]), + (a.min.y, b.min.y, by[1]), + (a.max.y, b.max.y, by[1]), + (a.min.z, b.min.z, by[2]), + (a.max.z, b.max.z, by[2]), + ] + .iter() + .all(|(was, now, d)| about(was + d, *now)) +} + +/// #4768: every placement of a part placed twice, moved together, goes exactly the way asked, +/// however each placement is turned: the shared part was moved once per placement listed, each +/// turning the move its own way, so the turned copy went down Z instead of along Y. One undo +/// step puts both back. +#[test] +fn placements_of_one_part_moved_together_each_go_the_way_asked() { + let mut s = Session::default(); + let (a, b) = twice_placed_blade(&mut s); + let (a0, b0) = (placed_bounds(&s, &a), placed_bounds(&s, &b)); + let undo = s.undo.len(); + let r = run(&mut s, "solid.move", json!({"bodies": [a.clone(), b.clone()], "translate": ["240 mm", "-100 mm", "0 mm"]})); + assert_eq!(r["placements"].as_array().map(Vec::len), Some(2), "{r}"); + assert!(shifted(a0, placed_bounds(&s, &a), [240.0, -100.0, 0.0]), "{a}: {:?}", placed_bounds(&s, &a)); + assert!(shifted(b0, placed_bounds(&s, &b), [240.0, -100.0, 0.0]), "{b}: {:?}", placed_bounds(&s, &b)); + assert_eq!(s.undo.len(), undo + 1, "one undo step"); + run(&mut s, "edit.undo", json!({})); + assert!(shifted(a0, placed_bounds(&s, &a), [0.0; 3]) && shifted(b0, placed_bounds(&s, &b), [0.0; 3]), "undone"); + // A quarter turn about Z moves each placement about the world origin, as Move turns a body. + run(&mut s, "solid.move", json!({"bodies": [a.clone(), b.clone()], "axis": [0, 0, 1], "angle": 90})); + let turned = placed_bounds(&s, &a); + assert!(about(turned.min.x, -8.0) && about(turned.max.x, 0.0) && about(turned.min.y, 0.0) && about(turned.max.y, 20.0), "{turned:?}"); + let turned = placed_bounds(&s, &b); + assert!(about(turned.min.x, 0.0) && about(turned.max.x, 30.0) && about(turned.min.y, 100.0) && about(turned.max.y, 120.0), "{turned:?}"); +} + +/// The same part inserted from a STEP assembly, where a rigid group holds the placements in the +/// imported component: the move goes to the placement of the whole import, once. +#[test] +fn an_imported_assembly_with_a_repeated_part_moves_as_one() { + let dir = std::env::temp_dir().join(format!("solidcraft-4768-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("rep.step").to_string_lossy().to_string(); + let mut src = Session::default(); + twice_placed_blade(&mut src); + run(&mut src, "file.export", json!({"path": path})); + let mut s = Session::default(); + run(&mut s, "file.insert_step", json!({"path": path})); + unground_all(&mut s); + let names: Vec = s.world_state().bodies.iter().map(|b| b.name.clone()).collect(); + assert_eq!(names.len(), 2, "{names:?}"); + let before: Vec<_> = names.iter().map(|n| placed_bounds(&s, n)).collect(); + let r = run(&mut s, "solid.move", json!({"bodies": names, "translate": [240, -100, 0]})); + assert_eq!(r["placements"].as_array().map(Vec::len), Some(1), "the import's placement, once: {r}"); + for (n, b) in names.iter().zip(before) { + assert!(shifted(b, placed_bounds(&s, n), [240.0, -100.0, 0.0]), "{n}: {:?}", placed_bounds(&s, n)); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/frames.rs b/crates/engine/src/frames.rs index ee7eef0cf..0536c724d 100644 --- a/crates/engine/src/frames.rs +++ b/crates/engine/src/frames.rs @@ -370,6 +370,11 @@ pub fn to_local(s: &Session, id: &str, params: &Value) -> Option { out["targets"] = targets; 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() { + return None; + } if id == "timeline.redefine" { let cmd = params.get("command")?.as_str()?; let key = params.get("feature").and_then(|v| v.as_str().map(str::to_string).or_else(|| v.as_u64().map(|id| id.to_string())))?; @@ -536,3 +541,56 @@ fn same_coordinates(a: &Value, b: &Value) -> bool { #[cfg(test)] #[path = "frames_tests.rs"] mod tests; + +/// What a `solid.move` of the placed model moves as placements (#4768). A part placed more than +/// once (an imported assembly's screws or fan corners) is one body: moving it once per placement +/// listed moved it that many times, each placement turning the move its own way, so the copies +/// flew apart. When `bodies` name one part through two or more placements, each listed body's +/// placement is moved instead, in the world, as `occurrence.move` moves it. A placement held by +/// a rigid group (an imported assembly) moves with the outermost placement that holds it, and one +/// inside another placement being moved is not moved again. Bodies of the root component, which +/// have no placement, are moved as bodies (`bodies`). `None`: an ordinary move of bodies (no part +/// named through two placements, or a copy). +pub(crate) struct PlacementMove { + /// Occurrence paths (root first) to move. + pub paths: Vec>, + /// Root-component bodies listed, moved as bodies. + pub bodies: Vec, +} + +pub(crate) fn placements_moved(s: &Session, params: &Value) -> Option { + if params.get("copy").and_then(Value::as_bool) == Some(true) || !placed(s) { + return None; + } + let names: Vec<&str> = params.get("bodies")?.as_array()?.iter().filter_map(Value::as_str).collect(); + let st = s.model.state(); + let doc = s.placed_document(); + let frames = doc.body_frames_with_source(&st); + let listed: Vec<&(String, String, u64, Vec, Mat)> = names.iter().filter_map(|n| frames.iter().find(|f| f.0 == *n)).collect(); + // One part (a component's body) named through two different placements. + let repeated = listed.iter().enumerate().any(|(i, a)| listed[..i].iter().any(|b| b.1 == a.1 && b.2 == a.2 && b.3 != a.3)); + if !repeated { + return None; + } + let mut paths: Vec> = Vec::new(); + let mut bodies = Vec::new(); + for (world, _, _, path, _) in listed { + if path.is_empty() { + bodies.push(world.clone()); + continue; + } + // Up through the rigid groups that hold it (as `occurrence.move` asks for). + let mut k = path.len(); + while k > 1 && path.get(k - 1).is_some_and(|o| s.held_by_rigid_group(*o).is_some()) { + k -= 1; + } + let target = path[..k].to_vec(); + if !paths.contains(&target) { + paths.push(target); + } + } + // A placement inside another one being moved goes with it. + let all = paths.clone(); + paths.retain(|p| !all.iter().any(|q| q.len() < p.len() && p.starts_with(q))); + Some(PlacementMove { paths, bodies }) +}