Skip to content

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

Imported meshes: share their triangles between document copies (#4673) (#4675)

Jackson Oursland4dc1828138a1
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs
index 9a52d36a1a..d396f24e73 100644
--- a/crates/doc/src/document.rs
+++ b/crates/doc/src/document.rs
@@ -1854,14 +1854,16 @@ fn fair_keep_edges() -> bool {
true
}
-/// Triangles of one imported mesh body (millimetres).
+/// Triangles of one imported mesh body (millimetres). The arrays are shared by clones: every
+/// edit keeps the design as it was for undo, and a scanned part's triangles (hundreds of
+/// megabytes) are not copied for that.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MeshData {
pub name: String,
/// x, y, z per vertex.
- pub positions: Vec<f64>,
+ pub positions: std::sync::Arc<[f64]>,
/// Three vertex indices per triangle.
- pub triangles: Vec<u32>,
+ pub triangles: std::sync::Arc<[u32]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub color: Option<[f32; 3]>,
}
diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs
index dc538983e8..c39e5a0973 100644
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@ -752,9 +752,7 @@ mod tests {
let mut preview = saved_preview(&s).unwrap();
// A checksum-valid but forged cached shape must not become editable geometry.
for mesh in &mut preview.meshes {
- for coordinate in &mut mesh.positions {
- *coordinate *= 10.0;
- }
+ mesh.positions = mesh.positions.iter().map(|c| c * 10.0).collect();
}
let bytes = solidcraft_io::write_design_container_with_preview(&s.doc, solidcraft_io::DesignCompression::Fast, Some(&preview)).unwrap();
let path = std::env::temp_dir().join(format!("solidcraft-preview-{}.solidcraft", std::process::id()));
diff --git a/crates/engine/src/tests/mesh_convert.rs b/crates/engine/src/tests/mesh_convert.rs
index c7c3e91fe7..315683b8fe 100644
--- a/crates/engine/src/tests/mesh_convert.rs
+++ b/crates/engine/src/tests/mesh_convert.rs
@@ -22,6 +22,31 @@ fn imported_box() -> Session {
Session::new(doc)
}
+/// An edit keeps the design as it was for undo, and an imported mesh's triangles are shared
+/// with that copy, not copied (a scan's are hundreds of megabytes): after an edit and its undo
+/// the document holds the same arrays. They still save as plain arrays.
+#[test]
+fn edits_share_an_imported_meshs_triangles_with_undo() {
+ let mut s = imported_box();
+ let arrays = |s: &Session| match &s.doc.features[0].kind {
+ FeatureKind::MeshImport { meshes, .. } => (meshes[0].positions.clone(), meshes[0].triangles.clone()),
+ other => panic!("{other:?}"),
+ };
+ let (positions, triangles) = arrays(&s);
+ run(&mut s, "parameters.add", json!({"name":"size","expression":"2","unit":""}));
+ let (p, t) = arrays(&s);
+ assert!(std::sync::Arc::ptr_eq(&p, &positions) && std::sync::Arc::ptr_eq(&t, &triangles), "shared after an edit");
+ run(&mut s, "edit.undo", json!({}));
+ let (p, t) = arrays(&s);
+ assert!(std::sync::Arc::ptr_eq(&p, &positions) && std::sync::Arc::ptr_eq(&t, &triangles), "shared after undo");
+ let saved =
+ serde_json::to_value(MeshData { name: "M".into(), positions: vec![1.5, 2.0, 3.0].into(), triangles: vec![0, 0, 0].into(), color: None })
+ .unwrap();
+ assert_eq!(saved, json!({"name":"M","positions":[1.5,2.0,3.0],"triangles":[0,0,0]}));
+ let back: MeshData = serde_json::from_value(saved).unwrap();
+ assert_eq!(&back.positions[..], &[1.5, 2.0, 3.0]);
+}
+
#[test]
fn mesh_conversion_is_parametric_undoable_and_editable_after_cold_reopen() {
let mut s = imported_box();
diff --git a/crates/io/src/design.rs b/crates/io/src/design.rs
index 42f4fc9277..3dfc0d212c 100644
--- a/crates/io/src/design.rs
+++ b/crates/io/src/design.rs
@@ -326,10 +326,10 @@ fn encode_mesh(mesh: &MeshData) -> Result<Vec<u8>> {
bytes.extend_from_slice(MESH_MAGIC);
bytes.extend_from_slice(&(mesh.positions.len() as u64).to_le_bytes());
bytes.extend_from_slice(&(mesh.triangles.len() as u64).to_le_bytes());
- for value in &mesh.positions {
+ for value in mesh.positions.iter() {
bytes.extend_from_slice(&value.to_le_bytes());
}
- for value in &mesh.triangles {
+ for value in mesh.triangles.iter() {
bytes.extend_from_slice(&value.to_le_bytes());
}
Ok(bytes)
@@ -536,7 +536,7 @@ fn read_preview<R: Read + Seek>(reader: &mut PackageReader<R>) -> Result<DesignP
return Err(invalid("overlapping preview bodies"));
}
end = end.checked_add(length).ok_or_else(|| invalid("preview overflow"))?;
- let mut mesh = MeshData { name: String::new(), positions: Vec::new(), triangles: Vec::new(), color: None };
+ let mut mesh = MeshData { name: String::new(), positions: Vec::new().into(), triangles: Vec::new().into(), color: None };
decode_mesh(data.get(offset..end).ok_or_else(|| invalid("truncated preview"))?, &mut mesh)?;
triangles = triangles.saturating_add(mesh.triangles.len() / 3);
if triangles > MAX_PREVIEW_TRIANGLES {
@@ -971,8 +971,8 @@ mod tests {
fn mesh() -> MeshData {
MeshData {
name: "Precise mesh".into(),
- positions: vec![0.123456789012345, -0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0],
- triangles: vec![0, 1, 2],
+ positions: vec![0.123456789012345, -0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0].into(),
+ triangles: vec![0, 1, 2].into(),
color: Some([0.25, 0.5, 0.75]),
}
}
@@ -1128,7 +1128,7 @@ mod tests {
assert!(read_design_preview(&package(&entries)).is_none());
}
let mut too_large = mesh();
- too_large.triangles = vec![0; (MAX_PREVIEW_TRIANGLES + 1) * 3];
+ too_large.triangles = vec![0; (MAX_PREVIEW_TRIANGLES + 1) * 3].into();
let bytes = write_design_container_with_preview(&doc, DesignCompression::Fast, Some(&DesignPreview { meshes: vec![too_large] })).unwrap();
assert!(read_design_preview(&bytes).is_none());
assert_eq!(crate::read_design(&bytes).unwrap(), doc);
diff --git a/crates/io/src/gltf_in.rs b/crates/io/src/gltf_in.rs
index 3ea1281627..e5a05a248a 100644
--- a/crates/io/src/gltf_in.rs
+++ b/crates/io/src/gltf_in.rs
@@ -101,10 +101,16 @@ impl GltfImport {
if let solidcraft_doc::FeatureKind::MeshImport { meshes, .. } = &mut self.feature.kind {
for (m, slot) in meshes.iter_mut().zip(&self.plan.bodies) {
let Some(frame) = slot.and_then(|s| world.get(s).copied().flatten()) else { continue };
- for p in m.positions.as_chunks_mut::<3>().0 {
- let q = solidcraft_doc::apply_point(&frame, Vec3::new(p[0], p[1], p[2]));
- *p = [q.x, q.y, q.z];
- }
+ m.positions = m
+ .positions
+ .as_chunks::<3>()
+ .0
+ .iter()
+ .flat_map(|p| {
+ let q = solidcraft_doc::apply_point(&frame, Vec3::new(p[0], p[1], p[2]));
+ [q.x, q.y, q.z]
+ })
+ .collect();
}
}
self.plan = MeshPlan::default();
diff --git a/crates/io/src/mutate.rs b/crates/io/src/mutate.rs
index 6d2a6e66a2..5fe98b6e05 100644
--- a/crates/io/src/mutate.rs
+++ b/crates/io/src/mutate.rs
@@ -508,8 +508,8 @@ outer
doc.set_param("width", "40", Some("mm"), None).unwrap();
let mesh = solidcraft_doc::MeshData {
name: "Preview".into(),
- positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0],
- triangles: vec![0, 1, 2],
+ positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0].into(),
+ triangles: vec![0, 1, 2].into(),
color: None,
};
let preview = crate::DesignPreview { meshes: vec![mesh] };
diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs
index 6b20a1c3ff..dcf9418964 100644
--- a/crates/ui-egui/src/file_load.rs
+++ b/crates/ui-egui/src/file_load.rs
@@ -1120,8 +1120,8 @@ mod tests {
let preview = solidcraft_engine::io::DesignPreview {
meshes: vec![solidcraft_engine::doc::MeshData {
name: "Saved triangle".into(),
- positions: vec![0.0, 0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 10.0, 0.0],
- triangles: vec![0, 1, 2],
+ positions: vec![0.0, 0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 10.0, 0.0].into(),
+ triangles: vec![0, 1, 2].into(),
color: Some([0.8, 0.2, 0.1]),
}],
};
@@ -1136,7 +1136,7 @@ mod tests {
let preview = solidcraft_engine::io::DesignPreview {
meshes: vec![solidcraft_engine::doc::MeshData {
name: "Hostile overdraw".into(),
- positions: vec![0.0, 0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 10.0, 0.0],
+ positions: vec![0.0, 0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 10.0, 0.0].into(),
triangles: (0..10_000).flat_map(|_| [0, 1, 2]).collect(),
color: None,
}],