Skip to content

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

Added mesh import units for STL and OBJ (#10406)

Steven Watersf1159a5d51e8
diff --git a/apps/solidcraft-web/src/main.rs b/apps/solidcraft-web/src/main.rs
index f55f0d447e..4f8818ba8e 100644
--- a/apps/solidcraft-web/src/main.rs
+++ b/apps/solidcraft-web/src/main.rs
@@ -828,7 +828,9 @@ mod web {
self.files.panel.set(false);
}
"insert" => {
- self.app.insert_path(&path);
+ if !solidcraft_ui_egui::mesh_units::ask(&mut self.app, &path, true) {
+ self.app.insert_path(&path);
+ }
self.files.panel.set(false);
}
"download" => match vfs::read(&path, solidcraft_engine::io::MAX_DESIGN_BYTES) {
diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs
index e458e0a63f..06a46dc9fe 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); 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); 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)"),
+ .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"),
CommandSpec::new("file.save", "Save", save)
.icon("save")
.key("Ctrl+S")
@@ -225,7 +225,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>) -> Result<Value> {
+fn add_mesh(s: &mut Session, path: &str, name: Option<&str>, y_up: Option<bool>, unit: Option<(&'static str, f64)>) -> 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);
@@ -239,7 +239,7 @@ fn add_mesh(s: &mut Session, path: &str, name: Option<&str>, y_up: Option<bool>)
}
(g.feature, Some(g.plan), g.looks)
} else {
- (solidcraft_io::mesh_import_feature(&bytes, path).map_err(err)?, None, Vec::new())
+ (solidcraft_io::mesh_import_feature_in(&bytes, path, unit.map_or(1.0, |(_, mm)| mm)).map_err(err)?, None, Vec::new())
};
let fname = name.filter(|n| !n.trim().is_empty()).unwrap_or(&mf.name).to_string();
let cname = import::component_name(path, name);
@@ -262,6 +262,9 @@ fn add_mesh(s: &mut Session, path: &str, name: Option<&str>, y_up: Option<bool>)
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((name, _)) = unit {
+ out["units"] = json!(name);
+ }
if let Some(turned) = turned {
out["stand_up"] = json!(turned);
}
@@ -291,6 +294,27 @@ fn mesh_up(p: &Value, path: &str, cmd: &str) -> Result<Option<bool>> {
Ok(Some(step_options(p, cmd)?.y_up))
}
+/// `units` for an STL, OBJ or PLY file: the unit its coordinates are in (one of
+/// `solidcraft_doc::point_cloud::UNITS`, the same as a point cloud's), which they are scaled from
+/// to millimetres as the file is read. The design keeps the millimetre mesh and not the unit, so
+/// importing again is how a different unit is tried. A 3MF or glTF file states its own.
+fn mesh_units(p: &Value, path: &str, cmd: &str) -> Result<Option<(&'static str, f64)>> {
+ let names = || solidcraft_doc::point_cloud::UNITS.iter().map(|(n, _)| *n).collect::<Vec<_>>().join(", ");
+ let unit = match p.get("units") {
+ None | Some(Value::Null) => return Ok(None),
+ Some(Value::String(u)) => solidcraft_doc::point_cloud::UNITS
+ .iter()
+ .find(|(name, _)| name.eq_ignore_ascii_case(u))
+ .map(|(name, mm)| (*name, *mm))
+ .ok_or_else(|| bad(cmd, format!("`units` must be one of {} (not `{u}`)", names())))?,
+ Some(_) => return Err(bad(cmd, format!("`units` must be one of {}", names()))),
+ };
+ if solidcraft_io::is_gltf_path(path) || path.to_ascii_lowercase().ends_with(".3mf") {
+ return Err(bad(cmd, "`units` applies to STL, OBJ and PLY files only: a 3MF or glTF file states its own"));
+ }
+ Ok(Some(unit))
+}
+
fn insert_mesh(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "file.insert_mesh";
let path = path_arg(p, cmd)?;
@@ -298,7 +322,8 @@ fn insert_mesh(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "only 3MF, STL, OBJ, PLY and glTF files (.3mf, .stl, .obj, .ply, .glb, .gltf) can be inserted as meshes"));
}
let up = mesh_up(p, path, cmd)?;
- add_mesh(s, path, str_(p, "name"), up)
+ let unit = mesh_units(p, path, cmd)?;
+ add_mesh(s, path, str_(p, "name"), up, unit)
}
fn insert_step(s: &mut Session, p: &Value) -> Result<Value> {
@@ -375,7 +400,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")?)?
+ add_mesh(&mut fresh, path, None, mesh_up(p, path, "doc.open")?, mesh_units(p, path, "doc.open")?)?
};
// The design is the file: its component is the one being worked in.
if let Some(c) = r["component"].as_u64() {
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 4280dc95f5..e068b923ff 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -2087,6 +2087,15 @@ fn threemf_export_open_insert() {
assert_eq!(s.model.state().bodies.len(), 3);
assert!(rel(volume(&mut s), 2.0 * want) < 2e-3);
assert!(s.execute("file.insert_mesh", &json!({"path": dir.join("x.step").to_string_lossy()})).is_err());
+ // An STL's unit scales it to millimetres as it is read: inches are 25.4 mm each. 3MF states its own.
+ let mut inch = Session::default();
+ let r = run(&mut inch, "file.insert_mesh", json!({"path": stl.to_string_lossy(), "units": "in"}));
+ assert_eq!(r["units"], "in", "{r}");
+ assert!(rel(volume(&mut inch), want * 25.4f64.powi(3)) < 2e-3);
+ for bad_units in [json!("furlong"), json!(7), json!("")] {
+ assert!(inch.execute("file.insert_mesh", &json!({"path": stl.to_string_lossy(), "units": bad_units})).is_err());
+ }
+ assert!(inch.execute("file.insert_mesh", &json!({"path": p.to_string_lossy(), "units": "in"})).is_err());
let junk = dir.join("junk.3mf");
std::fs::write(&junk, b"PK\x03\x04 not really").unwrap();
let before = s.doc.clone();
@@ -2096,6 +2105,90 @@ fn threemf_export_open_insert() {
let _ = std::fs::remove_dir_all(&dir);
}
+/// A cube one unit across comes in as that unit in millimetres, for every unit: the sizes are
+/// written out here, not read from the table that scales the file.
+#[test]
+fn stl_cube_of_one_unit_comes_in_as_that_many_millimetres() {
+ let dir = std::env::temp_dir().join(format!("solidcraft-stl-units-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let stl = dir.join("one.stl");
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1}));
+ run(&mut s, "file.save_mesh", json!({"path": stl.to_string_lossy()}));
+ for (units, edge) in [("mm", 1.0_f64), ("cm", 10.0), ("m", 1000.0), ("in", 25.4), ("ft", 304.8)] {
+ let mut t = Session::default();
+ let r = run(&mut t, "file.insert_mesh", json!({"path": stl.to_string_lossy(), "units": units}));
+ assert_eq!(r["units"], units, "{r}");
+ let solidcraft_doc::FeatureKind::MeshImport { meshes, .. } = &t.doc.features[0].kind else { panic!("{units}: not a mesh import") };
+ for axis in 0..3 {
+ let along: Vec<f64> = meshes[0].positions.chunks(3).map(|p| p[axis]).collect();
+ let (lo, hi) = (along.iter().cloned().fold(f64::MAX, f64::min), along.iter().cloned().fold(f64::MIN, f64::max));
+ assert!(((hi - lo) - edge).abs() <= edge * 1e-12, "{units}: edge {} along axis {axis}, want {edge}", hi - lo);
+ }
+ assert!(rel(volume(&mut t), edge.powi(3)) < 1e-9, "{units}: volume {}", volume(&mut t));
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+/// A unit given on import and a Scale feature after an import in millimetres make the same body,
+/// within floating-point precision, for each unitless mesh format: STL, OBJ and PLY (with faces).
+#[test]
+fn a_unit_on_import_matches_importing_in_millimetres_then_scaling() {
+ let dir = std::env::temp_dir().join(format!("solidcraft-unit-vs-scale-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ // A cube one unit across, as the three formats write it.
+ let corners = [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]];
+ let triangles =
+ [[0, 2, 1], [0, 3, 2], [4, 5, 6], [4, 6, 7], [0, 1, 5], [0, 5, 4], [3, 7, 6], [3, 6, 2], [0, 4, 7], [0, 7, 3], [1, 2, 6], [1, 6, 5]];
+ let vertex = |i: usize| format!("{} {} {}", corners[i][0], corners[i][1], corners[i][2]);
+ let mut stl = String::from("solid cube\n");
+ for t in triangles {
+ stl += "facet normal 0 0 0\nouter loop\n";
+ for i in t {
+ stl += &format!("vertex {}\n", vertex(i));
+ }
+ stl += "endloop\nendfacet\n";
+ }
+ stl += "endsolid cube\n";
+ let mut obj = String::from("o Cube\n");
+ for i in 0..8 {
+ obj += &format!("v {}\n", vertex(i));
+ }
+ for t in triangles {
+ obj += &format!("f {} {} {}\n", t[0] + 1, t[1] + 1, t[2] + 1);
+ }
+ let mut ply = String::from("ply\nformat ascii 1.0\nelement vertex 8\nproperty float x\nproperty float y\nproperty float z\n");
+ ply += "element face 12\nproperty list uchar int vertex_indices\nend_header\n";
+ for i in 0..8 {
+ ply += &format!("{}\n", vertex(i));
+ }
+ for t in triangles {
+ ply += &format!("3 {} {} {}\n", t[0], t[1], t[2]);
+ }
+ let close = |a: f64, b: f64| (a - b).abs() <= 1e-9 * b.abs().max(1.0);
+ for (extension, text) in [("stl", stl), ("obj", obj), ("ply", ply)] {
+ let path = dir.join(format!("cube.{extension}"));
+ std::fs::write(&path, text).unwrap();
+ for (units, mm) in [("mm", 1.0_f64), ("cm", 10.0), ("m", 1000.0), ("in", 25.4), ("ft", 304.8)] {
+ let mut with_unit = Session::default();
+ run(&mut with_unit, "file.insert_mesh", json!({"path": path.to_string_lossy(), "units": units}));
+ let mut scaled = Session::default();
+ let inserted = run(&mut scaled, "file.insert_mesh", json!({"path": path.to_string_lossy()}));
+ let body = inserted["bodies"][0].as_str().unwrap().to_string();
+ run(&mut scaled, "solid.scale", json!({"bodies": [body], "factor": mm.to_string()}));
+ let (a, b) = (with_unit.model.state().bodies[0].mesh().bounds(), scaled.model.state().bodies[0].mesh().bounds());
+ let (a, b) = ([a.min.x, a.min.y, a.min.z, a.max.x, a.max.y, a.max.z], [b.min.x, b.min.y, b.min.z, b.max.x, b.max.y, b.max.z]);
+ for (x, y) in a.into_iter().zip(b) {
+ assert!(close(x, y), "{extension} {units}: bounds {a:?} against {b:?}");
+ }
+ let (va, vb) = (volume(&mut with_unit), volume(&mut scaled));
+ assert!(rel(va, vb) < 1e-9, "{extension} {units}: volume {va} against {vb}");
+ assert!(rel(va, mm.powi(3)) < 1e-9, "{extension} {units}: volume {va}, want {}", mm.powi(3));
+ }
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
#[test]
fn holes_at_sketch_points_threads_and_components() {
let mut s = Session::default();
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index 2f1dde8bd6..74ede324ee 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -292,8 +292,27 @@ pub struct MeshFeature {
/// feature. A glTF file's bodies are all built where they are (see [`read_gltf`] for its node
/// tree), and it can't read buffers in other files.
pub fn mesh_import_feature(bytes: &[u8], file: &str) -> Result<MeshFeature> {
+ mesh_import_feature_in(bytes, file, 1.0)
+}
+
+/// [`mesh_import_feature`] for a file whose coordinates are in a unit of `mm_per_unit`
+/// millimetres (25.4 for inches). The scaling is made once, as the file is read: the feature
+/// keeps the millimetre mesh and nothing of the unit. Only STL, OBJ and PLY files take a unit
+/// other than millimetres; a 3MF or glTF file says its own.
+pub fn mesh_import_feature_in(bytes: &[u8], file: &str, mm_per_unit: f64) -> Result<MeshFeature> {
let _span = solidcraft_profile::span("import", "mesh_import_feature");
+ if !mm_per_unit.is_finite() || mm_per_unit <= 0.0 {
+ return Err(IoError::Invalid("the unit must be a positive number of millimetres".into()));
+ }
+ let own_units = |what: &str| {
+ if mm_per_unit == 1.0 {
+ Ok(())
+ } else {
+ Err(IoError::Invalid(format!("a {what} file states its own units; a unit applies to STL, OBJ and PLY files")))
+ }
+ };
if is_gltf_path(file) {
+ own_units("glTF")?;
let mut no_files = |name: &str| Err(format!("`{name}` can't be read here"));
let mut g = read_gltf(bytes, file, &mut no_files)?;
g.flatten();
@@ -305,7 +324,7 @@ pub fn mesh_import_feature(bytes: &[u8], file: &str) -> Result<MeshFeature> {
let path = std::path::Path::new(file);
let stem = path.file_stem().map(|s| s.to_string_lossy().to_string()).filter(|s| !s.trim().is_empty()).unwrap_or_else(|| "Mesh".into());
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
- let (objects, warnings) = if ext == "obj" {
+ let (mut objects, warnings) = if ext == "obj" {
obj::read_obj(bytes, &stem)?
} else if ext == "ply" {
ply::read_ply_mesh(bytes, &stem)?
@@ -319,8 +338,20 @@ pub fn mesh_import_feature(bytes: &[u8], file: &str) -> Result<MeshFeature> {
let triangles = (0..n).map(|i| [i * 3, i * 3 + 1, i * 3 + 2]).collect();
(vec![MeshObject { name: stem.clone(), positions, triangles, ..Default::default() }], Vec::new())
} else {
+ own_units("3MF")?;
read_3mf(bytes)?
};
+ if mm_per_unit != 1.0 {
+ let limit = solidcraft_doc::point_cloud::MAX_COORD;
+ for o in &mut objects {
+ for p in &mut o.positions {
+ *p = *p * mm_per_unit;
+ if ![p.x, p.y, p.z].iter().all(|v| v.is_finite() && v.abs() <= limit) {
+ return Err(IoError::Invalid(format!("mesh `{}` is out of range at this unit", o.name)));
+ }
+ }
+ }
+ }
// Check every mesh now, so the command fails rather than the timeline.
let mut meshes = Vec::with_capacity(objects.len());
for o in &objects {
@@ -1011,6 +1042,83 @@ mod tests {
solidcraft_kernel::measure(&solidcraft_kernel::mesh_body(&pos, &tris).unwrap()).unwrap().volume
}
+ /// A unit scales an STL's coordinates to millimetres once, as it is read (an inch cube of 10 is
+ /// 254 mm across); the feature keeps nothing of the unit. A bad unit, a unit on a file that
+ /// states its own, and a size beyond the limits are refused.
+ #[test]
+ fn stl_unit_scales_the_mesh_as_it_is_read() {
+ let stl = cube_stl(&[], b"solid exported by something", None, [0.0; 3]);
+ let volume = |mm: f64| {
+ let f = mesh_import_feature_in(&stl, "x.stl", mm).unwrap();
+ let solidcraft_doc::FeatureKind::MeshImport { meshes, .. } = f.kind else { panic!() };
+ let m = &meshes[0];
+ let pos: Vec<Vec3> = m.positions.chunks(3).map(|c| Vec3::new(c[0], c[1], c[2])).collect();
+ let tris: Vec<[u32; 3]> = m.triangles.chunks(3).map(|c| [c[0], c[1], c[2]]).collect();
+ solidcraft_kernel::measure(&solidcraft_kernel::mesh_body(&pos, &tris).unwrap()).unwrap().volume
+ };
+ assert!((volume(1.0) - 1000.0).abs() < 1e-6);
+ assert!((volume(25.4) - 1000.0 * 25.4f64.powi(3)).abs() < 1e-3 * 25.4f64.powi(3));
+ assert!(mesh_import_feature_in(&stl, "x.stl", 0.0).is_err());
+ assert!(mesh_import_feature_in(&stl, "x.stl", f64::NAN).is_err());
+ assert!(mesh_import_feature_in(&stl, "x.stl", 1e12).is_err());
+ assert!(mesh_import_feature_in(&stl, "x.3mf", 25.4).is_err());
+ assert!(mesh_import_feature_in(&stl, "x.glb", 25.4).is_err());
+ }
+
+ /// An STL holding `triangles` as a binary file.
+ fn stl_of(triangles: &[[[f32; 3]; 3]]) -> Vec<u8> {
+ let mut bytes = vec![0u8; 80];
+ bytes.extend((triangles.len() as u32).to_le_bytes());
+ for triangle in triangles {
+ bytes.extend([0u8; 12]);
+ for vertex in triangle {
+ for coordinate in vertex {
+ bytes.extend(coordinate.to_le_bytes());
+ }
+ }
+ bytes.extend([0u8; 2]);
+ }
+ bytes
+ }
+
+ /// Every stored coordinate is the file's `f32` value widened to `f64` and multiplied by the
+ /// unit's millimetres, exactly: no rounding through `f32`, and not scaled twice. The values
+ /// are exact in `f32`, so the expected numbers carry no rounding of their own.
+ #[test]
+ fn stl_coordinates_are_the_widened_value_times_the_unit_exactly() {
+ let (a, b, c, d) = ([0.5, -3.75, 1.25], [7.0, 0.25, -2.5], [-1.5, 4.0, 0.125], [2.0, 2.0, 9.5]);
+ let triangles = [[a, b, c], [a, c, d], [a, d, b], [b, d, c]];
+ let stl = stl_of(&triangles);
+ for (unit, mm) in solidcraft_doc::point_cloud::UNITS {
+ let feature = mesh_import_feature_in(&stl, "t.stl", mm).unwrap();
+ let solidcraft_doc::FeatureKind::MeshImport { meshes, .. } = feature.kind else { panic!() };
+ let want: Vec<f64> = triangles.iter().flatten().flatten().map(|v| f64::from(*v) * mm).collect();
+ assert_eq!(&*meshes[0].positions, want.as_slice(), "{unit}");
+ }
+ }
+
+ /// A PLY with faces, read as a mesh, takes a unit as an STL does: it states none either.
+ #[test]
+ fn ply_mesh_unit_scales_its_vertices_exactly() {
+ let corners = [[0.5f32, -3.75, 1.25], [7.0, 0.25, -2.5], [-1.5, 4.0, 0.125], [2.0, 2.0, 9.5]];
+ let mut ply = String::from("ply\nformat ascii 1.0\nelement vertex 4\nproperty float x\nproperty float y\nproperty float z\n");
+ ply.push_str("element face 4\nproperty list uchar int vertex_indices\nend_header\n");
+ for c in corners {
+ ply.push_str(&format!("{} {} {}\n", c[0], c[1], c[2]));
+ }
+ ply.push_str("3 0 1 2\n3 0 2 3\n3 0 3 1\n3 1 3 2\n");
+ let sorted = |mut v: Vec<f64>| {
+ v.sort_by(f64::total_cmp);
+ v
+ };
+ for (unit, mm) in solidcraft_doc::point_cloud::UNITS {
+ let feature = mesh_import_feature_in(ply.as_bytes(), "t.ply", mm).unwrap();
+ let solidcraft_doc::FeatureKind::MeshImport { meshes, .. } = feature.kind else { panic!() };
+ let want: Vec<f64> = corners.iter().flatten().map(|v| f64::from(*v) * mm).collect();
+ assert_eq!(sorted(meshes[0].positions.to_vec()), sorted(want), "{unit}");
+ }
+ }
+
/// STL quirks: a binary header starting with "solid", a zero triangle count, garbage
/// normals, stray inverted facets and non-finite vertices.
#[test]
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 87690cd590..c251bf0674 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -872,11 +872,15 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) ->
})),
"ui.file" => {
let Some(path) = s("path") else { return err("path is required") };
- if p.get("insert").and_then(Value::as_bool).unwrap_or(false) {
- app.insert_path_async(path);
- } else {
- app.open_path_async(path);
- }
+ // A control call never meets the unit dialog an STL or OBJ file asks a person: it names
+ // `units` itself, or the file is in millimetres.
+ let kind =
+ if p.get("insert").and_then(Value::as_bool).unwrap_or(false) { crate::file_load::Kind::Insert } else { crate::file_load::Kind::Open };
+ let mut request = crate::file_load::Request::new(path, kind);
+ if let Some(units) = p.get("units").filter(|u| !u.is_null()) {
+ request.options.insert("units".into(), units.clone());
+ }
+ let _ = crate::file_load::begin_request(app, request);
ok(json!({"busy": app.file_load.busy()}))
}
"ui.documents" => ok(crate::documents::control(app, p)),
diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs
index 216ee4dfdf..e4a9974c72 100644
--- a/crates/ui-egui/src/file_load.rs
+++ b/crates/ui-egui/src/file_load.rs
@@ -61,6 +61,9 @@ pub struct Request {
pub design: Option<String>,
/// The chat turn that requested the load. It must still be current when the file lands.
pub(crate) chat_turn: Option<Arc<std::sync::atomic::AtomicBool>>,
+ /// Insert the file as a mesh whatever its extension says: a PLY goes to `pointcloud.insert`
+ /// unless the person chose Insert Mesh for it (then it needs its faces).
+ pub mesh: bool,
}
impl Request {
@@ -74,6 +77,7 @@ impl Request {
allow_hosts: Vec::new(),
design: None,
chat_turn: None,
+ mesh: false,
}
}
fn insert(&self) -> bool {
@@ -88,7 +92,7 @@ impl Request {
fn command(&self) -> (&'static str, Value) {
match &self.kind {
Kind::Open => ("doc.open", self.params()),
- Kind::Insert if solidcraft_engine::io::is_mesh_path(&self.path) => ("file.insert_mesh", self.params()),
+ Kind::Insert if self.mesh || solidcraft_engine::io::is_mesh_path(&self.path) => ("file.insert_mesh", self.params()),
Kind::Insert if solidcraft_engine::io::is_point_cloud_path(&self.path) => ("pointcloud.insert", self.params()),
Kind::Insert => (insert_command(&self.path), self.params()),
Kind::Recover { id, dir } => ("doc.recover", json!({"id": id, "dir": dir})),
@@ -265,6 +269,10 @@ impl FileLoad {
}
pub fn begin(app: &mut SolveApp, path: &str, insert: bool) {
+ // An STL or OBJ file states no unit: ask which, then import (see `crate::mesh_units`).
+ if crate::mesh_units::ask(app, path, insert) {
+ return;
+ }
let _ = begin_request(app, Request::new(path, if insert { Kind::Insert } else { Kind::Open }));
}
@@ -286,11 +294,11 @@ pub fn begin_request(app: &mut SolveApp, request: Request) -> Result<(), String>
}
let r = match &request.kind {
Kind::Insert => {
- app.insert_path(&request.path);
+ app.insert_path_with(&request.path, &request.options, request.mesh);
Ok(Value::Null)
}
Kind::Open => {
- app.open_path(&request.path);
+ app.open_path_with(&request.path, &request.options);
// Opened in place of the blank tab it made, with no switch to it.
crate::edit_in_place::attach(app);
Ok(Value::Null)
@@ -413,6 +421,7 @@ pub fn control(app: &mut SolveApp, req: crate::control::ControlRequest) -> Optio
allow_hosts: Vec::new(),
design: None,
chat_turn: req.chat_turn,
+ mesh: false,
};
let _ = begin_request(app, request);
None
@@ -1458,6 +1467,15 @@ mod tests {
assert!(reply.try_recv().is_ok_and(|r| r["ok"] == json!(false)), "the caller hears it failed");
}
+ #[test]
+ fn a_ply_is_a_point_cloud_unless_inserted_as_a_mesh() {
+ let mut request = Request::new("scan.ply", Kind::Insert);
+ assert_eq!(request.command().0, "pointcloud.insert");
+ assert_eq!(Request::new("scan.ply", Kind::Open).command().0, "doc.open");
+ request.mesh = true;
+ assert_eq!(request.command().0, "file.insert_mesh");
+ }
+
#[test]
fn repeated_queued_opens_reply_once_and_keep_one_session() {
let mut app = SolveApp::new(Session::default(), Default::default());
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 3f60f5094f..e8e473c19e 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -117,6 +117,7 @@ mod measurement_ui_tests;
#[cfg(test)]
mod menu_tests;
pub(crate) mod mesh_lod;
+pub mod mesh_units;
pub mod messages;
pub(crate) mod motion;
pub mod occurrence_drag;
@@ -696,6 +697,8 @@ pub struct SolveApp {
pub recovery_discard_all: bool,
/// The selection's measurement in the view's corner (#7000).
pub(crate) quick_measure: quick_measure::QuickMeasure,
+ /// An STL or OBJ file waiting for the unit its coordinates are in (`mesh_units`).
+ pub mesh_units: Option<mesh_units::Ask>,
/// The bodies of a just-opened Y-up file, offered to be stood up (`stand_up`).
pub stand_up: Option<Vec<String>>,
/// The placement of the component that file came in as: the offer turns it.
@@ -910,6 +913,7 @@ impl SolveApp {
reopen_guard_dir: None,
recovery_discard_all: false,
quick_measure: Default::default(),
+ mesh_units: None,
stand_up: None,
stand_up_occurrence: None,
stand_up_reason: false,
@@ -1927,7 +1931,22 @@ impl SolveApp {
linked_source::start_selected(self);
return;
}
- if matches!(id, "file.insert_step" | "file.insert_mesh" | "pointcloud.insert") {
+ if id == "file.insert_mesh" {
+ // Insert Mesh is an explicit ask for a mesh: a PLY chosen here is read as one (its
+ // faces), after asking its unit, where any other way of inserting it is a point cloud.
+ // Like Insert SVG it asks the host for its own kind of file (on the web a file dialog,
+ // not the window that also opens and downloads designs), so the file comes straight
+ // back here and nothing has to remember which command asked.
+ self.pick_open_for(&["3mf", "stl", "obj", "ply", "glb", "gltf"], |app, path| {
+ if let Some(path) = path
+ && !mesh_units::ask_ply_as_mesh(app, &path)
+ {
+ app.insert_path_async(&path);
+ }
+ });
+ return;
+ }
+ if matches!(id, "file.insert_step" | "pointcloud.insert") {
self.pick_open(|app, path| {
if let Some(path) = path {
app.insert_path_async(&path);
@@ -2550,6 +2569,11 @@ impl SolveApp {
}
pub fn open_path(&mut self, path: &str) {
+ self.open_path_with(path, &Default::default());
+ }
+
+ /// [`Self::open_path`] with the import options of the request (`units` of an STL or OBJ file).
+ pub fn open_path_with(&mut self, path: &str, options: &serde_json::Map<String, Value>) {
match documents::reuse_path(self, path) {
Ok(true) => return,
Err(e) => {
@@ -2560,7 +2584,9 @@ impl SolveApp {
}
self.home.open = false;
documents::prepare_open(self);
- if let Ok(r) = self.run("doc.open", json!({ "path": path })) {
+ let mut params = options.clone();
+ params.insert("path".into(), json!(path));
+ if let Ok(r) = self.run("doc.open", Value::Object(params)) {
// An opened design comes up at the home view, not at the angle the design before it
// was left at: `prepare_open` keeps the camera when it reuses a blank design.
self.cam.set_view(StandardView::Iso);
@@ -2591,9 +2617,23 @@ impl SolveApp {
/// Insert CAD bodies, meshes or sketch drawing geometry into the current design.
pub fn insert_path(&mut self, path: &str) {
- let cmd = if solidcraft_engine::io::is_point_cloud_path(path) { "pointcloud.insert" } else { file_load::insert_command(path) };
+ self.insert_path_with(path, &Default::default(), false);
+ }
+
+ /// [`Self::insert_path`] with the import options of the request (`units` of an STL or OBJ file).
+ /// `mesh`: insert it as a mesh whatever its extension says (a PLY with faces).
+ pub fn insert_path_with(&mut self, path: &str, options: &serde_json::Map<String, Value>, mesh: bool) {
+ let cmd = if mesh {
+ "file.insert_mesh"
+ } else if solidcraft_engine::io::is_point_cloud_path(path) {
+ "pointcloud.insert"
+ } else {
+ file_load::insert_command(path)
+ };
let before: Vec<String> = crate::open_meshing::session_world(&self.session).bodies.iter().map(|b| b.name.clone()).collect();
- if let Ok(r) = self.run(cmd, json!({ "path": path })) {
+ let mut params = options.clone();
+ params.insert("path".into(), json!(path));
+ if let Ok(r) = self.run(cmd, Value::Object(params)) {
self.fit_view();
stand_up::offer(self, path, &before, Some(&r));
if let Some(summary) = timeline::import_status(self, &r) {
@@ -3348,6 +3388,7 @@ impl SolveApp {
bom_panel::show(self, ui.ctx());
material_card_review::show(self, ui.ctx());
recovery_ui::show(self, ui.ctx());
+ mesh_units::show(self, ui.ctx());
stand_up::show(self, ui.ctx());
prefs_notice::show(self, ui.ctx());
context_menu::show(self, ui.ctx());
diff --git a/crates/ui-egui/src/mesh_units.rs b/crates/ui-egui/src/mesh_units.rs
new file mode 100644
index 0000000000..5a8c3a5335
--- /dev/null
+++ b/crates/ui-egui/src/mesh_units.rs
@@ -0,0 +1,140 @@
+//! Asking which unit an STL or OBJ file is in. These formats carry no unit, so a file made in
+//! inches would come in 25.4 times too small. When a person opens, inserts or drops one, a small
+//! 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.
+//!
+//! 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.
+
+use serde_json::json;
+use solidcraft_engine::doc::point_cloud::UNITS;
+
+use crate::{SolveApp, file_load, ui_kit};
+
+/// A file waiting for its unit.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Ask {
+ /// The file.
+ pub path: String,
+ /// Insert it into the design (else open it as a new design).
+ pub insert: bool,
+ /// The chosen unit: an index into the unit list, millimetres first.
+ pub choice: usize,
+ /// Insert it as a mesh whatever its extension says (a PLY chosen with Insert Mesh).
+ pub mesh: bool,
+}
+
+/// Files that state no unit of their own and take one when imported.
+pub fn needs_unit(path: &str) -> bool {
+ let lower = path.to_ascii_lowercase();
+ lower.ends_with(".stl") || lower.ends_with(".obj")
+}
+
+/// Ask for the unit of `path` before it is imported. Returns whether the file was held for the
+/// answer (the caller then stops: the dialog starts the import itself). The web app asks too, for
+/// the file a person uploaded, before its mesh is made.
+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 });
+ true
+}
+
+/// Insert Mesh was chosen and `path` is a PLY: ask its unit, then insert it as a mesh (its faces)
+/// and not as the point cloud every other way of inserting a PLY makes. Returns whether it was
+/// held for the answer; another file goes on as the extension says.
+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 });
+ true
+}
+
+/// The unit chosen when the dialog opens: millimetres, the unit a file is read in without one.
+fn default_choice() -> usize {
+ UNITS.iter().position(|(name, _)| *name == "mm").unwrap_or(0)
+}
+
+/// The unit's id for `units` (`mm`, `in`, ...) at `choice`.
+fn unit_at(choice: usize) -> &'static str {
+ UNITS.get(choice).map_or("mm", |(name, _)| name)
+}
+
+/// The dialog, while a file waits for its unit.
+pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
+ let Some(mut ask) = app.mesh_units.clone() else { return };
+ let file = std::path::Path::new(&ask.path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| ask.path.clone());
+ // The symbols themselves (mm, cm, m, in, ft), as everywhere else units are chosen.
+ let names: Vec<&str> = UNITS.iter().map(|(name, _)| *name).collect();
+ let (closed, action) =
+ 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);
+ });
+ for (handle, key) in [("mesh_units:ok", "dialog:ok"), ("mesh_units:cancel", "dialog:cancel")] {
+ if let Some(at) = crate::scenario::handle_at(key) {
+ crate::scenario::publish_handle(handle, at);
+ }
+ }
+ 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);
+ }
+ ui_kit::Action::Cancel => app.mesh_units = None,
+ ui_kit::Action::None if closed => app.mesh_units = None,
+ _ => app.mesh_units = Some(ask),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn only_stl_and_obj_files_ask() {
+ for path in ["part.stl", "PART.STL", "a/b/c.Obj", "x.obj"] {
+ assert!(needs_unit(path), "{path}");
+ }
+ for path in ["part.3mf", "part.step", "part.glb", "part.ply", "stl", "part.stl.txt", ""] {
+ assert!(!needs_unit(path), "{path}");
+ }
+ }
+
+ #[test]
+ fn a_ply_asks_only_when_it_is_inserted_as_a_mesh() {
+ let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default());
+ // Open and Insert keep sending a PLY to the point cloud: no dialog.
+ assert!(!ask(&mut app, "scan.ply", true) && !ask(&mut app, "scan.PLY", false));
+ assert!(app.mesh_units.is_none());
+ // Insert Mesh is explicit: the dialog, then the mesh command.
+ assert!(!ask_ply_as_mesh(&mut app, "part.stl"), "only a PLY needs this route");
+ assert!(ask_ply_as_mesh(&mut app, "scan.ply"));
+ let held = app.mesh_units.clone().expect("held");
+ assert_eq!((held.path.as_str(), held.insert, held.mesh, unit_at(held.choice)), ("scan.ply", true, true, "mm"));
+ }
+
+ #[test]
+ fn millimetres_come_first_and_a_bad_choice_is_millimetres() {
+ assert_eq!(unit_at(0), "mm");
+ assert_eq!(unit_at(3), "in");
+ assert_eq!(unit_at(99), "mm");
+ }
+
+ #[test]
+ fn an_stl_waits_for_its_unit_and_the_control_channel_does_not() {
+ let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default());
+ file_load::begin(&mut app, "part.stl", true);
+ let ask = app.mesh_units.clone().expect("asked");
+ 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");
+ }
+}