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

Every edit clones the document for undo, and `MeshData`'s positions and
triangles (plain `Vec`s) were copied with it: ~165 MB a command for a 2 M-
triangle STL. They are now `Arc<[f64]>` and `Arc<[u32]>`, shared by clones;
the few places that rewrite them build new arrays. Saved designs are
unchanged (an `Arc<[T]>` serializes as the array).

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jackson Oursland
2026-10-22 12:06:44 +00:00
committed by GitHub
parent f843a3f83c
commit 4dc1828138
7 changed files with 52 additions and 21 deletions
+5 -3
View File
@@ -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]>,
}
+1 -3
View File
@@ -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()));
+25
View File
@@ -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();
+6 -6
View File
@@ -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);
+10 -4
View File
@@ -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();
+2 -2
View File
@@ -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] };
+3 -3
View File
@@ -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,
}],