Skip to content

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

Insert Mesh: optional move to origin on import (#12543) (#12698)

PaddleStroke3900dc742ce5
diff --git a/assets/locales/pending/mesh-import-origin.json b/assets/locales/pending/mesh-import-origin.json
new file mode 100644
index 0000000000..81fa8d69cc
--- /dev/null
+++ b/assets/locales/pending/mesh-import-origin.json
@@ -0,0 +1,53 @@
+{
+ "en": {
+ "ui.mesh_import_origin": "Move to origin",
+ "ui.mesh_import_origin_tip": "Center the mesh on X and Y with its base on Z = 0. When off, the mesh keeps the coordinates stored in the file."
+ },
+ "en-GB": {
+ "ui.mesh_import_origin_tip": "Centre the mesh on X and Y with its base on Z = 0. When off, the mesh keeps the coordinates stored in the file."
+ },
+ "ar": {
+ "ui.mesh_import_origin": "النقل إلى نقطة الأصل",
+ "ui.mesh_import_origin_tip": "توسيط الشبكة على المحورين X وY ووضع قاعدتها على Z = 0. عند إيقافه تحتفظ الشبكة بالإحداثيات المخزنة في الملف."
+ },
+ "de": {
+ "ui.mesh_import_origin": "In den Ursprung verschieben",
+ "ui.mesh_import_origin_tip": "Das Netz in X und Y zentrieren und seine Unterseite auf Z = 0 legen. Wenn aus, behält das Netz die Koordinaten aus der Datei."
+ },
+ "es": {
+ "ui.mesh_import_origin": "Mover al origen",
+ "ui.mesh_import_origin_tip": "Centra la malla en X e Y con su base en Z = 0. Si está desactivado, la malla conserva las coordenadas guardadas en el archivo."
+ },
+ "fr": {
+ "ui.mesh_import_origin": "Déplacer à l'origine",
+ "ui.mesh_import_origin_tip": "Centre le maillage en X et Y et pose sa base sur Z = 0. Désactivé, le maillage garde les coordonnées enregistrées dans le fichier."
+ },
+ "he": {
+ "ui.mesh_import_origin": "הזזה לראשית",
+ "ui.mesh_import_origin_tip": "מרכוז הרשת ב-X וב-Y והנחת הבסיס שלה על Z = 0. כשהאפשרות כבויה, הרשת שומרת על הקואורדינטות שבקובץ."
+ },
+ "it": {
+ "ui.mesh_import_origin": "Sposta all'origine",
+ "ui.mesh_import_origin_tip": "Centra la mesh in X e Y con la base su Z = 0. Se disattivato, la mesh mantiene le coordinate salvate nel file."
+ },
+ "ja": {
+ "ui.mesh_import_origin": "原点へ移動",
+ "ui.mesh_import_origin_tip": "メッシュを X と Y の中心に置き、底面を Z = 0 に合わせます。オフの場合、ファイルに保存された座標のままになります。"
+ },
+ "ko": {
+ "ui.mesh_import_origin": "원점으로 이동",
+ "ui.mesh_import_origin_tip": "메시를 X와 Y의 중앙에 놓고 바닥을 Z = 0에 맞춥니다. 끄면 파일에 저장된 좌표를 그대로 유지합니다."
+ },
+ "pt-BR": {
+ "ui.mesh_import_origin": "Mover para a origem",
+ "ui.mesh_import_origin_tip": "Centraliza a malha em X e Y com a base em Z = 0. Desligado, a malha mantém as coordenadas salvas no arquivo."
+ },
+ "vi": {
+ "ui.mesh_import_origin": "Di chuyển về gốc tọa độ",
+ "ui.mesh_import_origin_tip": "Căn giữa lưới theo X và Y, đặt đáy của nó tại Z = 0. Khi tắt, lưới giữ nguyên tọa độ lưu trong tệp."
+ },
+ "zh": {
+ "ui.mesh_import_origin": "移动到原点",
+ "ui.mesh_import_origin_tip": "将网格在 X 和 Y 方向居中,并将底面置于 Z = 0。关闭时,网格保留文件中存储的坐标。"
+ }
+}
diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs
index ca79625463..c2bc14a1ad 100644
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@ -31,7 +31,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.icon("open")
.key("Ctrl+O")
.noundo()
- .params("path: .sc design (or a .solidcraft design from an earlier release), .dxf/.svg drawing (opens as a new, unsaved design with an XY sketch, using sketch.insert_dxf/sketch.insert_svg units and defaults), or a .step/.stp/.igs/.fcstd/.3dm/.3mf/.stl/.obj/.glb/.gltf file (STEP, IGES, FreeCAD, Rhino, 3MF, STL, OBJ or glTF; opens as a new design holding the file as a component named after it, as file.insert_step and file.insert_mesh make), or a .ply/.xyz/.pts point cloud (opens as a new design holding it, as pointcloud.insert makes; its `units` and `max_points` as there); up?: z|y for a STEP, IGES, FreeCAD, Rhino or glTF file (see file.insert_step and file.insert_mesh); names?: auto|solid|product|instance for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step); units?: for an STL or OBJ file (see file.insert_mesh); folder?: bool for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step); read_only?: bool (a design: saving to its own file is refused, file.save_as keeps the changes elsewhere) → open_elsewhere: {host, user, app, opened} when another SolidCraft has the design open (its lock file is fresh); newer_file: {format, reads_up_to, unknown_changes, not_understood, notice} and warnings when a newer SolidCraft saved it: it opens all the same, and what this version can't read is named there and kept by saving"),
+ .params("path: .sc design (or a .solidcraft design from an earlier release), .dxf/.svg drawing (opens as a new, unsaved design with an XY sketch, using sketch.insert_dxf/sketch.insert_svg units and defaults), or a .step/.stp/.igs/.fcstd/.3dm/.3mf/.stl/.obj/.glb/.gltf file (STEP, IGES, FreeCAD, Rhino, 3MF, STL, OBJ or glTF; opens as a new design holding the file as a component named after it, as file.insert_step and file.insert_mesh make), or a .ply/.xyz/.pts point cloud (opens as a new design holding it, as pointcloud.insert makes; its `units` and `max_points` as there); up?: z|y for a STEP, IGES, FreeCAD, Rhino or glTF file (see file.insert_step and file.insert_mesh); names?: auto|solid|product|instance for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step); units?: for an STL or OBJ file (see file.insert_mesh); origin?: bool for a mesh file (see file.insert_mesh); folder?: bool for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step); read_only?: bool (a design: saving to its own file is refused, file.save_as keeps the changes elsewhere) → open_elsewhere: {host, user, app, opened} when another SolidCraft has the design open (its lock file is fresh); newer_file: {format, reads_up_to, unknown_changes, not_understood, notice} and warnings when a newer SolidCraft saved it: it opens all the same, and what this version can't read is named there and kept by saving"),
CommandSpec::new("file.insert_step", "Insert STEP", insert_step)
.at("SOLID", "INSERT")
.icon("import")
@@ -39,7 +39,7 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("file.insert_mesh", "Insert Mesh", insert_mesh)
.at("SOLID", "INSERT")
.icon("import")
- .params("path: .3mf, .stl, .obj, .ply (with faces), .glb or .gltf file (its meshes join the design as mesh bodies in a new component named after the file → component, component_name, occurrence; a glTF file's node tree becomes nested components held as one rigid group until component.unlock, a mesh placed again another occurrence, its materials the bodies' appearances, and its metres millimetres); name?; up?: z|y for a glTF file (default y: glTF has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence; z: the file's axes are kept); units?: mm|cm|m|in|ft for an STL or OBJ file, or a PLY file with faces (default mm): the unit its coordinates are in, scaled to millimetres as the file is read (a 3MF or glTF file states its own). The design keeps the millimetre mesh and not the unit, so insert the file again to try another"),
+ .params("path: .3mf, .stl, .obj, .ply (with faces), .glb or .gltf file (its meshes join the design as mesh bodies in a new component named after the file → component, component_name, occurrence; a glTF file's node tree becomes nested components held as one rigid group until component.unlock, a mesh placed again another occurrence, its materials the bodies' appearances, and its metres millimetres); name?; up?: z|y for a glTF file (default y: glTF has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence; z: the file's axes are kept); units?: mm|cm|m|in|ft for an STL or OBJ file, or a PLY file with faces (default mm): the unit its coordinates are in, scaled to millimetres as the file is read (a 3MF or glTF file states its own). The design keeps the millimetre mesh and not the unit, so insert the file again to try another; origin?: bool (default false: the mesh keeps its file's coordinates; true: once read, scaled and stood up, the import's occurrence is moved so the box around its bodies is centred on X and Y of the active component with its lowest point on Z = 0 → moved_to_origin: [x, y, z], the shift made)"),
CommandSpec::new("file.save", "Save", save)
.icon("save")
.key("Ctrl+S")
@@ -262,7 +262,7 @@ fn created_bodies(s: &Session, feature: u64) -> Vec<String> {
/// Add a MeshImport feature for a 3MF, STL, OBJ or glTF file, in a new component named after the
/// file. A glTF file's nodes become components in it, and its materials the bodies' looks; it is
/// in metres with Y up, so unless `y_up` is false its component is turned to Z up (#1505).
-fn add_mesh(s: &mut Session, path: &str, name: Option<&str>, y_up: Option<bool>, unit: Option<(&'static str, f64)>) -> Result<Value> {
+fn add_mesh(s: &mut Session, path: &str, name: Option<&str>, y_up: Option<bool>, unit: Option<(&'static str, f64)>, origin: bool) -> Result<Value> {
let err = |e: solidcraft_io::IoError| EngineError::Other(format!("{path}: {e}"));
let bytes = solidcraft_io::vfs::read(path, solidcraft_io::MAX_3MF_BYTES).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
let gltf = solidcraft_io::is_gltf_path(path);
@@ -296,9 +296,14 @@ fn add_mesh(s: &mut Session, path: &str, name: Option<&str>, y_up: Option<bool>,
s.refresh();
}
let turned = if gltf && y_up.unwrap_or(true) { turn_up(s, &placed)? } else { None };
+ // After the turn, so it is the stood-up mesh that sits on Z = 0.
+ let moved = if origin { import::move_to_origin(s, &placed)? } else { None };
let fname = s.doc.feature(id).map(|f| f.name.clone()).unwrap_or_default();
let mut out = json!({"path": path, "feature": id, "name": fname, "bodies": bodies, "created_bodies": bodies, "warnings": mf.warnings});
placed.report(&mut out);
+ if let Some(shift) = moved {
+ out["moved_to_origin"] = json!([shift.x, shift.y, shift.z]);
+ }
if let Some((name, _)) = unit {
out["units"] = json!(name);
}
@@ -360,7 +365,20 @@ fn insert_mesh(s: &mut Session, p: &Value) -> Result<Value> {
}
let up = mesh_up(p, path, cmd)?;
let unit = mesh_units(p, path, cmd)?;
- add_mesh(s, path, str_(p, "name"), up, unit)
+ add_mesh(s, path, str_(p, "name"), up, unit, mesh_origin(p, cmd)?)
+}
+
+/// `origin`: whether a mesh import is moved to the origin (#12543). Off unless asked, so a mesh
+/// keeps the coordinates its file gives it.
+fn mesh_origin(p: &Value, cmd: &str) -> Result<bool> {
+ match p.get("origin") {
+ None | Some(Value::Null) => Ok(false),
+ Some(Value::Bool(origin)) => Ok(*origin),
+ Some(_) => Err(bad(
+ cmd,
+ "`origin` must be true (the mesh is moved so its box is centred on X and Y with its base on Z = 0) or false (the file's coordinates are kept)",
+ )),
+ }
}
fn insert_step(s: &mut Session, p: &Value) -> Result<Value> {
@@ -398,6 +416,9 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
if !solidcraft_io::is_step_path(path) && !solidcraft_io::is_gltf_path(path) && p.get("up").is_some_and(|v| !v.is_null()) {
return Err(bad("doc.open", "`up` applies to STEP, IGES and glTF files only"));
}
+ if !solidcraft_io::is_mesh_path(path) && p.get("origin").is_some_and(|v| !v.is_null()) {
+ return Err(bad("doc.open", "`origin` applies to 3MF, STL, OBJ and glTF files only"));
+ }
if let Some(command) = super::drawing_import_command(path) {
let stem = std::path::Path::new(path).file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| "Untitled".into());
let mut fresh = Session::new(Document::new(&stem));
@@ -437,7 +458,7 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
let r = if solidcraft_io::is_step_path(path) {
add_step(&mut fresh, path, None, &step_options(p, "doc.open")?)?
} else {
- add_mesh(&mut fresh, path, None, mesh_up(p, path, "doc.open")?, mesh_units(p, path, "doc.open")?)?
+ add_mesh(&mut fresh, path, None, mesh_up(p, path, "doc.open")?, mesh_units(p, path, "doc.open")?, mesh_origin(p, "doc.open")?)?
};
// The design is the file: its component is the one being worked in.
if let Some(c) = r["component"].as_u64() {
@@ -448,7 +469,18 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
s.replace_design(fresh);
let errors = s.model.results.iter().filter(|r| r.error.is_some()).count();
let mut out = json!({"path": path, "features": s.doc.features.len(), "errors": errors, "bodies": r["bodies"], "warnings": r["warnings"]});
- for k in ["component", "component_name", "occurrence", "subcomponents", "rigid_joints", "stand_up", "system", "exporter", "exporter_up"] {
+ for k in [
+ "component",
+ "component_name",
+ "occurrence",
+ "subcomponents",
+ "rigid_joints",
+ "stand_up",
+ "moved_to_origin",
+ "system",
+ "exporter",
+ "exporter_up",
+ ] {
if let Some(v) = r.get(k) {
out[k] = v.clone();
}
diff --git a/crates/engine/src/cmd/file_import.rs b/crates/engine/src/cmd/file_import.rs
index 4577435d83..c40ae432ba 100644
--- a/crates/engine/src/cmd/file_import.rs
+++ b/crates/engine/src/cmd/file_import.rs
@@ -320,6 +320,63 @@ pub(crate) fn add_in_component(
Ok((id, Placed { component: top, occurrence: top_occ, name, components: comps.len(), joints: joint_ids }))
}
+/// Move an import to the origin of the component it was inserted into (#12543): the box around
+/// its bodies, where they are placed, comes to sit centred on X and Y with its lowest point on
+/// Z = 0. The import's occurrence moves; the file's coordinates in the feature are kept, so the
+/// move is its placement and Move Occurrence takes it on from there. Returns the shift, in that
+/// component's frame; `None` when the import has no bodies to place.
+pub(crate) fn move_to_origin(s: &mut Session, placed: &Placed) -> Result<Option<Vec3>> {
+ let occ = placed.occurrence.ok_or_else(|| EngineError::Other("the import has no placement to move".into()))?;
+ // A component activated without a path is shown at its first placement, as elsewhere.
+ let active = s.active_occurrence_path.clone().unwrap_or_else(|| s.doc.first_path(s.active_component));
+ // The frame the import was placed in: the origin it goes to.
+ let parent = s.doc.path_transform(s.active_component, &active).unwrap_or(IDENTITY);
+ let to_parent =
+ solidcraft_doc::mat_inverse(&parent).ok_or_else(|| EngineError::Other("the active component's placement can't be inverted".into()))?;
+ // This placement of the import only: the bodies whose path runs through its occurrence
+ // where it sits in the active component.
+ let ours: Vec<String> = s
+ .doc
+ .body_frames(&s.model.state())
+ .into_iter()
+ .filter(|(_, _, path, _)| path.starts_with(&active) && path.get(active.len()) == Some(&occ))
+ .map(|(name, ..)| name)
+ .collect();
+ let world = s.world_state()?;
+ let mut bounds = solidcraft_geom::Aabb3::EMPTY;
+ for body in world.bodies.iter().filter(|b| ours.contains(&b.name)) {
+ // Each body's own box in the active component's frame: a turned component's frame would
+ // only take a larger box around the world box's corners, leaving the mesh off Z = 0.
+ let b = if solidcraft_doc::is_identity(&to_parent) {
+ body.body.exact_bounds()?
+ } else {
+ solidcraft_doc::kernel::place_matrix(&body.body, to_parent)?.exact_bounds()?
+ };
+ if b.is_empty() {
+ continue;
+ }
+ bounds = bounds.union(&b);
+ }
+ if bounds.is_empty() {
+ return Ok(None);
+ }
+ let shift = Vec3::new(-(bounds.min.x + bounds.max.x) / 2.0, -(bounds.min.y + bounds.max.y) / 2.0, -bounds.min.z);
+ if ![shift.x, shift.y, shift.z].iter().all(|v| v.is_finite()) {
+ return Err(EngineError::Other("the import's bounds can't be placed at the origin".into()));
+ }
+ let mut by = IDENTITY;
+ by[3] = [shift.x, shift.y, shift.z, 1.0];
+ if let Some(o) = s.doc_mut().occurrences.iter_mut().find(|o| o.id == occ) {
+ let moved = solidcraft_doc::mat_mul(&by, &o.transform);
+ if !solidcraft_doc::is_placement(&moved) {
+ return Err(EngineError::Other("moving the import to the origin takes it out of a placement within 1e9 mm".into()));
+ }
+ o.transform = moved;
+ }
+ s.refresh();
+ Ok(Some(shift))
+}
+
/// Record that body `names[b]` lives in component `c`, placed by `offset`.
fn put_bodies(s: &mut Session, names: &[Option<String>], moves: &[(usize, u64, Mat)]) {
if moves.is_empty() {
diff --git a/crates/engine/src/tests/import_component.rs b/crates/engine/src/tests/import_component.rs
index 257b233c7b..fbf47915f5 100644
--- a/crates/engine/src/tests/import_component.rs
+++ b/crates/engine/src/tests/import_component.rs
@@ -278,6 +278,109 @@ fn a_mesh_file_comes_in_as_one_component() {
let _ = std::fs::remove_dir_all(&dir);
}
+/// A 10 x 20 x 30 box with its low corner at (100, 50, 7), saved as `block.stl` in `dir`.
+fn off_origin_stl(dir: &std::path::Path) -> String {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "corner": [100, 50, 7]}));
+ let stl = dir.join("block.stl").to_string_lossy().to_string();
+ run(&mut s, "file.save_mesh", json!({"path": stl}));
+ stl
+}
+
+/// The one box the design shows.
+fn only_box(s: &Session) -> [i64; 6] {
+ let boxes = shown_boxes(s);
+ assert_eq!(boxes.len(), 1, "{boxes:?}");
+ boxes[0]
+}
+
+/// Insert Mesh's `origin` (#12543): off, the mesh stays where its file puts it; on, its box is
+/// centred on X and Y with its base on Z = 0, by moving the import's occurrence, and the reply
+/// says by how much. A unit scales the mesh first, so the scaled box is the one centred.
+#[test]
+fn a_mesh_import_moves_to_the_origin_only_when_asked() {
+ let dir = temp_dir("origin");
+ let stl = off_origin_stl(&dir);
+ let mut s = Session::default();
+ let r = run(&mut s, "file.insert_mesh", json!({"path": stl}));
+ assert!(r.get("moved_to_origin").is_none(), "{r}");
+ assert_eq!(only_box(&s), [100_000, 50_000, 7_000, 110_000, 70_000, 37_000], "the file's coordinates by default");
+
+ let mut s = Session::default();
+ let r = run(&mut s, "file.insert_mesh", json!({"path": stl, "origin": true}));
+ assert_eq!(only_box(&s), [-5_000, -10_000, 0, 5_000, 10_000, 30_000], "centred on X and Y, base on Z = 0");
+ assert_eq!(r["moved_to_origin"], json!([-105.0, -60.0, -7.0]), "{r}");
+ let occ = r["occurrence"].as_u64().unwrap();
+ let placed = s.doc.occurrences.iter().find(|o| o.id == occ).unwrap().transform;
+ assert_eq!(placed[3], [-105.0, -60.0, -7.0, 1.0], "the occurrence carries the move");
+ // One undo step takes the whole import, move and all, away.
+ run(&mut s, "edit.undo", json!({}));
+ assert!(s.world_state().unwrap().bodies.is_empty());
+
+ let mut s = Session::default();
+ run(&mut s, "file.insert_mesh", json!({"path": stl, "origin": true, "units": "cm"}));
+ assert_eq!(only_box(&s), [-50_000, -100_000, 0, 50_000, 100_000, 300_000], "scaled to millimetres, then centred");
+
+ let mut s = Session::default();
+ let e = s.execute("file.insert_mesh", &json!({"path": stl, "origin": "yes"})).unwrap_err().to_string();
+ assert!(e.contains("`origin` must be true"), "{e}");
+ assert!(s.doc.features.is_empty(), "a refused import adds nothing");
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+/// `origin` is the origin of the component the mesh is inserted into, wherever that component
+/// is placed; and opening a mesh file as a design takes it too.
+#[test]
+fn a_mesh_moved_to_the_origin_sits_on_the_active_components_origin() {
+ let dir = temp_dir("origin-active");
+ let stl = off_origin_stl(&dir);
+ let mut s = Session::default();
+ let holder = run(&mut s, "component.create", json!({"name": "Holder", "grounded": false}));
+ // Made active as it is made.
+ run(&mut s, "occurrence.move", json!({"occurrence": holder["occurrence"], "translate": [0, 0, 40]}));
+ assert_ne!(s.active_component, 0);
+ run(&mut s, "file.insert_mesh", json!({"path": stl, "origin": true}));
+ assert_eq!(only_box(&s), [-5_000, -10_000, 40_000, 5_000, 10_000, 70_000], "on Holder's origin, 40 mm up");
+
+ let mut s = Session::default();
+ let r = run(&mut s, "doc.open", json!({"path": stl, "origin": true}));
+ assert_eq!(r["moved_to_origin"], json!([-105.0, -60.0, -7.0]), "{r}");
+ assert_eq!(only_box(&s), [-5_000, -10_000, 0, 5_000, 10_000, 30_000]);
+ let e = s.execute("doc.open", &json!({"path": dir.join("x.sc").to_string_lossy(), "origin": true})).unwrap_err().to_string();
+ assert!(e.contains("`origin` applies to"), "{e}");
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+/// Moving to the origin measures the mesh in the active component's own frame, so a component
+/// turned 45 degrees takes exactly the file box's shift (not a larger box around the turned
+/// one's corners); and a component made active without an occurrence path is taken at its first
+/// placement, as everywhere else.
+#[test]
+fn a_mesh_moves_to_the_origin_of_a_turned_or_pathless_active_component() {
+ let dir = temp_dir("origin-turned");
+ let stl = off_origin_stl(&dir);
+ let shift = |r: &Value| -> Vec3 {
+ let v = r["moved_to_origin"].as_array().unwrap_or_else(|| panic!("not moved: {r}"));
+ Vec3::new(v[0].as_f64().unwrap(), v[1].as_f64().unwrap(), v[2].as_f64().unwrap())
+ };
+
+ let mut s = Session::default();
+ let holder = run(&mut s, "component.create", json!({"name": "Holder", "grounded": false}));
+ run(&mut s, "occurrence.move", json!({"occurrence": holder["occurrence"], "axis": [1, 0, 0], "angle": "45 deg", "translate": [0, 0, 40]}));
+ assert_ne!(s.active_component, 0);
+ let r = run(&mut s, "file.insert_mesh", json!({"path": stl, "origin": true}));
+ assert!(close(shift(&r), Vec3::new(-105.0, -60.0, -7.0)), "in Holder's frame: {r}");
+
+ let mut s = Session::default();
+ run(&mut s, "component.create", json!({"name": "Holder", "grounded": false}));
+ assert_ne!(s.active_component, 0);
+ s.active_occurrence_path = None;
+ let r = run(&mut s, "file.insert_mesh", json!({"path": stl, "origin": true}));
+ assert!(close(shift(&r), Vec3::new(-105.0, -60.0, -7.0)), "at Holder's first placement: {r}");
+ assert_eq!(only_box(&s), [-5_000, -10_000, 0, 5_000, 10_000, 30_000]);
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
#[test]
fn undo_takes_the_whole_import_away() {
let dir = temp_dir("undo");
diff --git a/crates/ui-egui/src/mesh_units.rs b/crates/ui-egui/src/mesh_units.rs
index 5a8c3a5335..1391900efd 100644
--- a/crates/ui-egui/src/mesh_units.rs
+++ b/crates/ui-egui/src/mesh_units.rs
@@ -3,7 +3,9 @@
//! dialog asks for the unit first: OK imports with it (`units` of `file.insert_mesh` and
//! `doc.open`, which scale the coordinates to millimetres as the file is read), Cancel imports
//! nothing. The design keeps the millimetre mesh and not the unit, so a different unit is tried by
-//! importing the file again.
+//! importing the file again. The same dialog offers Move to origin (`origin` of the same
+//! commands, off unless ticked, #12543): the import is moved so its box is centred on X and Y
+//! with its base on Z = 0.
//!
//! Only interactive entry points ask ([`file_load::begin`]): a script, the control channel or MCP
//! calls the commands with their own `units`, or none for millimetres, and never meets a dialog.
@@ -24,6 +26,8 @@ pub struct Ask {
pub choice: usize,
/// Insert it as a mesh whatever its extension says (a PLY chosen with Insert Mesh).
pub mesh: bool,
+ /// Move it to the origin as it comes in (`origin`); off until ticked.
+ pub origin: bool,
}
/// Files that state no unit of their own and take one when imported.
@@ -39,7 +43,7 @@ pub fn ask(app: &mut SolveApp, path: &str, insert: bool) -> bool {
if !needs_unit(path) {
return false;
}
- app.mesh_units = Some(Ask { path: path.into(), insert, choice: default_choice(), mesh: false });
+ app.mesh_units = Some(Ask { path: path.into(), insert, choice: default_choice(), mesh: false, origin: false });
true
}
@@ -50,7 +54,7 @@ pub fn ask_ply_as_mesh(app: &mut SolveApp, path: &str) -> bool {
if !solidcraft_engine::io::is_ply_path(path) {
return false;
}
- app.mesh_units = Some(Ask { path: path.into(), insert: true, choice: default_choice(), mesh: true });
+ app.mesh_units = Some(Ask { path: path.into(), insert: true, choice: default_choice(), mesh: true, origin: false });
true
}
@@ -74,6 +78,11 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
ui_kit::Window::new(egui::Id::unique("sc_mesh_units"), "import", crate::i18n::tr("ui.point_cloud_units")).show(ctx, true, |ui| {
ui_kit::text(ui, &file, ui_kit::Text::Report("file", false));
ui_kit::choice_row(ui, crate::i18n::tr("ui.units"), "mesh_units", &mut ask.choice, &names);
+ let origin = ui_kit::checkbox(ui, crate::i18n::tr("ui.mesh_import_origin"), &mut ask.origin)
+ .on_hover_text(crate::i18n::tr("ui.mesh_import_origin_tip"));
+ // Named like the dialog's buttons: outside a labelled row the checkbox's own handle
+ // is a bare `dialog:`, which scripts can't tell apart.
+ crate::scenario::publish_handle("mesh_units:origin", origin.rect.center());
});
for (handle, key) in [("mesh_units:ok", "dialog:ok"), ("mesh_units:cancel", "dialog:cancel")] {
if let Some(at) = crate::scenario::handle_at(key) {
@@ -83,11 +92,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
match action {
ui_kit::Action::Ok => {
app.mesh_units = None;
- let kind = if ask.insert { file_load::Kind::Insert } else { file_load::Kind::Open };
- let mut request = file_load::Request::new(&ask.path, kind);
- request.mesh = ask.mesh;
- request.options.insert("units".into(), json!(unit_at(ask.choice)));
- let _ = file_load::begin_request(app, request);
+ let _ = file_load::begin_request(app, request(&ask));
}
ui_kit::Action::Cancel => app.mesh_units = None,
ui_kit::Action::None if closed => app.mesh_units = None,
@@ -95,6 +100,19 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
}
}
+/// The import the dialog's answer starts: the file with its unit, and `origin` when ticked (left
+/// out otherwise, so the command's default stands).
+fn request(ask: &Ask) -> file_load::Request {
+ let kind = if ask.insert { file_load::Kind::Insert } else { file_load::Kind::Open };
+ let mut request = file_load::Request::new(&ask.path, kind);
+ request.mesh = ask.mesh;
+ request.options.insert("units".into(), json!(unit_at(ask.choice)));
+ if ask.origin {
+ request.options.insert("origin".into(), json!(true));
+ }
+ request
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -137,4 +155,27 @@ mod tests {
assert_eq!((ask.path.as_str(), ask.insert, unit_at(ask.choice)), ("part.stl", true, "mm"));
assert!(app.file_load.idle(), "nothing is imported until OK");
}
+
+ #[test]
+ fn move_to_origin_is_off_until_ticked_and_then_sent() {
+ let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default());
+ assert!(ask(&mut app, "part.stl", true));
+ let mut held = app.mesh_units.clone().expect("asked");
+ assert!(!held.origin, "off by default");
+ assert!(!request(&held).options.contains_key("origin"), "unticked: the command's default");
+ held.origin = true;
+ held.choice = 3;
+ let sent = request(&held);
+ assert_eq!((sent.options.get("origin"), sent.options.get("units")), (Some(&json!(true)), Some(&json!("in"))));
+ }
+
+ #[test]
+ fn the_move_to_origin_checkbox_is_found_by_its_name() {
+ let mut h = crate::scenario::Harness::new();
+ assert!(ask(&mut h.app, "part.stl", true));
+ h.frames(3);
+ for handle in ["mesh_units:origin", "mesh_units:ok", "mesh_units:cancel"] {
+ assert!(crate::scenario::handle_at(handle).is_some(), "missing {handle}");
+ }
+ }
}