Skip to content

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

Renaming a feature no longer rebuilds the design (#3044) (#3097)

bherbruck5d9ebe991112
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs
index 8b5ed6eedc..2a3ea293b6 100644
--- a/crates/doc/src/document.rs
+++ b/crates/doc/src/document.rs
@@ -2718,6 +2718,22 @@ impl Document {
(expected == *self).then_some((old, new))
}
+ /// The feature whose name alone turns `previous` into this design, when that is all that
+ /// changed.
+ pub fn feature_rename_from(&self, previous: &Document) -> Option<u64> {
+ if self.features.len() != previous.features.len() {
+ return None;
+ }
+ let mut renamed = previous.features.iter().zip(&self.features).filter(|(a, b)| a.id == b.id && a.name != b.name);
+ let (_, b) = renamed.next()?;
+ if renamed.next().is_some() {
+ return None;
+ }
+ let mut expected = previous.clone();
+ expected.feature_mut(b.id)?.name.clone_from(&b.name);
+ (expected == *self).then_some(b.id)
+ }
+
/// A complete structural proof: no non-render field is allowed to differ. Keeping this
/// comparison based on the whole Document also includes fields added in future versions.
/// The clone/comparison is only needed when render intent actually differs.
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index c4ced0c4bd..fecbe34d75 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -1533,7 +1533,57 @@ impl Model {
.clone();
r.state = state;
}
- // The fingerprints of the renamed design, so the next evaluation reuses every result.
+ self.refingerprint(doc);
+ true
+ }
+
+ /// Follow a rename of feature `id` to `doc`'s name for it without evaluating anything: a
+ /// feature's name labels it (its result, its sketch, its construction geometry) but builds
+ /// nothing. False, leaving the model as it was, when the model isn't the design's, the
+ /// feature failed, or a later failed feature's error quotes its old name: evaluate then.
+ pub fn rename_feature(&mut self, doc: &Document, id: u64) -> bool {
+ if self.results.len() != doc.features.len() || self.results.iter().zip(&doc.features).any(|(r, f)| r.id != f.id || r.stale) {
+ return false;
+ }
+ let Some(name) = doc.feature(id).map(|f| f.name.clone()) else { return false };
+ let Some(at) = self.results.iter().position(|r| r.id == id) else { return false };
+ // An error may quote the old name: the feature's own, or a later one's that refers to it
+ // by id (a pattern of it: "{name} cannot be patterned or mirrored yet").
+ let old = self.results.get(at).map(|r| r.name.clone()).unwrap_or_default();
+ if self.results.iter().skip(at).any(|r| r.error.as_deref().is_some_and(|e| r.id == id || e.contains(&old))) {
+ return false;
+ }
+ if let Some(r) = self.results.get_mut(at) {
+ r.name.clone_from(&name);
+ }
+ let mut renamed: std::collections::HashMap<*const ModelState, Arc<ModelState>> = std::collections::HashMap::new();
+ for r in self.results.iter_mut().skip(at) {
+ let labels = r.state.sketches.iter().any(|k| k.feature == id) || r.state.construct.iter().any(|c| c.feature == id);
+ if !labels {
+ continue;
+ }
+ let state = renamed
+ .entry(Arc::as_ptr(&r.state))
+ .or_insert_with(|| {
+ let mut st = (*r.state).clone();
+ for k in st.sketches.iter_mut().filter(|k| k.feature == id) {
+ Arc::make_mut(k).name.clone_from(&name);
+ }
+ for c in st.construct.iter_mut().filter(|c| c.feature == id) {
+ c.name.clone_from(&name);
+ }
+ Arc::new(st)
+ })
+ .clone();
+ r.state = state;
+ }
+ self.refingerprint(doc);
+ true
+ }
+
+ /// Set every result's fingerprint to `doc`'s, so the next evaluation reuses every result
+ /// (after a change that builds nothing differently).
+ fn refingerprint(&mut self, doc: &Document) {
let (vals, _) = evaluation_values(doc);
let marker = doc.marker.unwrap_or(usize::MAX);
self.step_digests = StepDigests::of(doc, &self.step_digests);
@@ -1542,7 +1592,6 @@ impl Model {
prev = chain_fingerprint(doc, &vals, f, prev, i >= marker, &self.step_digests);
r.fingerprint = prev;
}
- true
}
}
diff --git a/crates/engine/src/cmd/edit_tests.rs b/crates/engine/src/cmd/edit_tests.rs
index e29aede83d..bdc464f7b0 100644
--- a/crates/engine/src/cmd/edit_tests.rs
+++ b/crates/engine/src/cmd/edit_tests.rs
@@ -746,3 +746,64 @@ fn edit_takes_dotted_keys_and_numbers_for_expressions() {
}
assert_eq!(*s.doc, before);
}
+
+/// #3044: renaming a feature labels it and builds nothing, so it, its undo and its redo evaluate
+/// nothing, and leave the model evaluating the renamed design gives (the result's, the sketch's
+/// and the construction plane's names). A rename other features follow is evaluated.
+#[test]
+fn renaming_a_feature_evaluates_nothing() {
+ let mut s = Session::default();
+ run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": 5, "name": "Shelf"}));
+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Outline"}));
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 6]}));
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "solid.extrude", json!({"distance": 4, "name": "Plate"}));
+ let labels = |s: &Session| {
+ let st = s.model.state();
+ let results: Vec<String> = s.model.results.iter().map(|r| r.name.clone()).collect();
+ let sketches: Vec<String> = st.sketches.iter().map(|k| k.name.clone()).collect();
+ let planes: Vec<String> = st.construct.iter().map(|c| c.name.clone()).collect();
+ (results, sketches, planes)
+ };
+ for (feature, name) in [("Outline", "Profile"), ("Plate", "Base plate")] {
+ s.evaluations = 0;
+ run(&mut s, "timeline.rename", json!({"feature": feature, "name": name}));
+ assert_eq!(s.evaluations, 0, "renaming {feature} evaluates nothing");
+ let mut fresh = Session::new((*s.doc).clone());
+ fresh.refresh();
+ assert_eq!(labels(&s), labels(&fresh));
+ s.refresh();
+ assert_eq!(s.model.last_recomputed, 0, "the next evaluation reuses every result");
+ }
+ let renamed = labels(&s);
+ s.evaluations = 0;
+ run(&mut s, "edit.undo", json!({}));
+ assert!(labels(&s).0.contains(&"Profile".to_string()) && labels(&s).0.contains(&"Plate".to_string()));
+ run(&mut s, "edit.redo", json!({}));
+ assert_eq!(labels(&s), renamed);
+ assert_eq!(s.evaluations, 0, "undo and redo of a rename evaluate nothing");
+ // A sketch on the plane names it: renaming the plane renames it there too, which is evaluated.
+ run(&mut s, "sketch.create", json!({"plane": "Shelf", "name": "Top"}));
+ run(&mut s, "sketch.finish", json!({}));
+ s.evaluations = 0;
+ run(&mut s, "timeline.rename", json!({"feature": "Shelf", "name": "Ledge"}));
+ assert!(s.evaluations > 0);
+ assert!(labels(&s).2.contains(&"Ledge".to_string()));
+ // A failed pattern's error quotes its source's name: renaming the source is evaluated, so
+ // the error names it as an evaluation does.
+ run(&mut s, "solid.pattern.rectangular", json!({"features": ["Base plate"], "dir1": [0, 0, 1], "count1": 2, "spacing1": 10, "name": "Copies"}));
+ let copies = s.doc.find_feature("Copies").unwrap().id;
+ if let Some(solidcraft_doc::FeatureKind::Pattern { features, .. }) = s.doc_mut().feature_mut(copies).map(|f| &mut f.kind) {
+ *features = vec!["Top".into()];
+ }
+ s.refresh();
+ let failed = |s: &Session| s.model.results.iter().filter_map(|r| r.error.clone()).collect::<Vec<_>>();
+ assert!(failed(&s).iter().any(|e| e.contains("Top")), "{:?}", failed(&s));
+ s.evaluations = 0;
+ run(&mut s, "timeline.rename", json!({"feature": "Top", "name": "Lid sketch"}));
+ assert!(s.evaluations > 0, "a later error quotes the old name");
+ assert!(failed(&s).iter().any(|e| e.contains("Lid sketch")), "{:?}", failed(&s));
+ let mut fresh = Session::new((*s.doc).clone());
+ fresh.refresh();
+ assert_eq!(failed(&s), failed(&fresh));
+}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 29516295b1..3eae93671d 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -633,8 +633,8 @@ impl Session {
}
/// [`Session::refresh`] after the design changed from `previous`; a change that only renamed
- /// a body (or undid or redid such a rename) renames it in the model instead, which keeps
- /// every result and mesh (#3044).
+ /// a body or a feature (or undid or redid such a rename) renames it in the model instead,
+ /// which keeps every result and mesh (#3044).
fn refresh_from(&mut self, previous: &Arc<Document>) {
if let Some((old, new)) = self.body_rename(previous)
&& self.model.rename_body(&self.doc, &old, &new)
@@ -645,6 +645,13 @@ impl Session {
}
return;
}
+ // A feature's name labels it and builds nothing.
+ if let Some(id) = self.doc.feature_rename_from(previous)
+ && self.model.rename_feature(&self.doc, id)
+ {
+ self.revision += 1;
+ return;
+ }
self.refresh();
}
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 7c5e24363b..42d9f57fe8 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -3850,3 +3850,50 @@ fn renaming_an_imported_assembly_body_reads_nothing_again() {
assert_eq!(s.evaluations, 0, "nor does its undo");
let _ = std::fs::remove_dir_all(&dir);
}
+
+/// #3044: on a design with thousands of bodies the cheap commands stay cheap: showing, hiding,
+/// selecting, colouring and renaming a body or a feature, and undoing them, recompute no feature
+/// (renames don't even look over the timeline) and leave every body's display mesh as it was, so
+/// nothing is meshed or uploaded again.
+#[test]
+fn cheap_commands_on_thousands_of_bodies_evaluate_nothing() {
+ let mut s = Session::default();
+ for k in 0..2 {
+ run(
+ &mut s,
+ "solid.box",
+ json!({"length": 4, "width": 4, "height": 4, "center": [0, 6 * k, 2], "operation": "new", "name": format!("Seed{k}")}),
+ );
+ run(
+ &mut s,
+ "solid.pattern.rectangular",
+ json!({"features": [format!("Seed{k}")], "dir1": [1, 0, 0], "count1": 1000, "spacing1": 6, "name": format!("Row{k}")}),
+ );
+ }
+ let st = s.model.state();
+ assert_eq!(st.bodies.len(), 2000);
+ let meshes = |s: &Session| s.model.state().bodies.iter().map(|b| std::sync::Arc::as_ptr(&b.mesh())).collect::<Vec<_>>();
+ let shown = meshes(&s);
+ s.refresh();
+ for (command, params) in [
+ ("select.set", json!({"items": [{"type": "body", "name": "Body7"}]})),
+ ("browser.visibility", json!({"visible": false, "items": ["Body7"]})),
+ ("browser.visibility", json!({"visible": true, "items": ["Body7"]})),
+ ("appearance.assign", json!({"bodies": ["Body7"], "appearance": "Aluminum - Satin"})),
+ ("body.rename", json!({"body": "Body7", "name": "Renamed"})),
+ ("timeline.rename", json!({"feature": "Row1", "name": "Second row"})),
+ ("edit.undo", json!({})),
+ ("edit.undo", json!({})),
+ ("edit.redo", json!({})),
+ ] {
+ s.evaluations = 0;
+ run(&mut s, command, params);
+ // Renames are followed in the model; the rest may look over the timeline, which then
+ // finds every result as it was.
+ assert_eq!(s.model.last_recomputed, 0, "{command} recomputed a feature");
+ if command.ends_with("rename") {
+ assert_eq!(s.evaluations, 0, "{command} evaluated the design");
+ }
+ }
+ assert_eq!(meshes(&s), shown, "every body keeps its mesh");
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 5d3be9ce3b..44adfee3d6 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -86,6 +86,8 @@ pub mod messages;
#[cfg(test)]
mod pattern_arrow_tests;
#[cfg(test)]
+mod scale_tests;
+#[cfg(test)]
mod surface_clamp_tests;
#[cfg(test)]
mod surface_errors_tests;
diff --git a/crates/ui-egui/src/scale_tests.rs b/crates/ui-egui/src/scale_tests.rs
new file mode 100644
index 0000000000..fcd56ba467
--- /dev/null
+++ b/crates/ui-egui/src/scale_tests.rs
@@ -0,0 +1,107 @@
+//! How the cost of a frame and of cheap commands grows with the number of bodies (#3044): a
+//! design with many bodies must not make every frame or every click slower per body squared.
+
+use serde_json::json;
+
+use crate::scenario::Harness;
+
+/// A design of `n` boxes (ten patterns of a box each), in a headless app, settled.
+fn grid(n: usize) -> Harness {
+ let mut h = Harness::new();
+ let per = n.div_ceil(10).max(1);
+ for k in 0..n.div_ceil(per) {
+ let count = per.min(n - k * per);
+ h.app
+ .run("solid.box", json!({"length": 4, "width": 4, "height": 4, "center": [0, 6 * k, 2], "operation": "new", "name": format!("Seed{k}")}))
+ .unwrap();
+ if count > 1 {
+ h.app
+ .run(
+ "solid.pattern.rectangular",
+ json!({"features": [format!("Seed{k}")], "dir1": [1, 0, 0], "count1": count, "spacing1": 6, "name": format!("Row{k}")}),
+ )
+ .unwrap();
+ }
+ }
+ assert_eq!(h.app.session.model.state().bodies.len(), n);
+ h.frames(3);
+ h
+}
+
+fn ms(f: impl FnOnce()) -> f64 {
+ let t = std::time::Instant::now();
+ f();
+ t.elapsed().as_secs_f64() * 1000.0
+}
+
+/// Times per body count; run with `--ignored --nocapture` (not a pass/fail check).
+#[test]
+#[ignore = "manual scaling measurement"]
+fn frame_and_cheap_command_cost_by_body_count() {
+ for n in [50, 500, 5000] {
+ let mut h = grid(n);
+ h.app.session.world_state().warm_meshes(|| true);
+ let scene_cold = ms(|| drop(crate::viewport::build_scene(&h.app)));
+ let scene_again = ms(|| drop(crate::viewport::build_scene(&h.app)));
+ let idle = ms(|| h.frames(10)) / 10.0;
+ h.app.tree.expanded.insert("c0/bodies".into());
+ h.frames(2);
+ let expanded = ms(|| h.frames(10)) / 10.0;
+ let rename = ms(|| {
+ h.app.run("body.rename", json!({"body": "Body7", "name": "Renamed"})).unwrap();
+ h.frame();
+ });
+ let scene_renamed = ms(|| drop(crate::viewport::build_scene(&h.app)));
+ let select = ms(|| {
+ h.app.run("select.set", json!({"items": [{"type": "body", "name": "Renamed"}]})).unwrap();
+ h.frame();
+ });
+ let highlight = ms(|| drop(crate::viewport::build_highlight(&h.app)));
+ let hide = ms(|| {
+ h.app.run("browser.visibility", json!({"visible": false, "items": ["Renamed"]})).unwrap();
+ h.frame();
+ });
+ let undo = ms(|| {
+ h.app.run("edit.undo", json!({})).unwrap();
+ h.frame();
+ });
+ println!(
+ "SCALE n={n} scene_cold_ms={scene_cold:.2} scene_again_ms={scene_again:.2} scene_renamed_ms={scene_renamed:.2} highlight_ms={highlight:.2} idle_frame_ms={idle:.2} expanded_frame_ms={expanded:.2} rename_ms={rename:.2} select_ms={select:.2} hide_ms={hide:.2} undo_ms={undo:.2}"
+ );
+ }
+}
+
+/// A design from a file (`SOLIDCRAFT_SCALE_DESIGN`), every browser folder open: the time of an
+/// idle frame and of the cheap commands, as [`frame_and_cheap_command_cost_by_body_count`].
+#[test]
+#[ignore = "manual measurement on a design file"]
+fn frame_cost_of_a_design_file() {
+ let Some(path) = std::env::var_os("SOLIDCRAFT_SCALE_DESIGN") else { return };
+ let bytes = std::fs::read(&path).unwrap();
+ let doc = solidcraft_engine::io::read_design(&bytes).unwrap();
+ let mut h = Harness::new();
+ h.app.session = solidcraft_engine::Session::new(doc);
+ h.app.session.world_state().warm_meshes(|| true);
+ h.frames(3);
+ let idle = ms(|| h.frames(5)) / 5.0;
+ let keys: Vec<String> =
+ h.app.session.doc.components.iter().flat_map(|c| ["bodies", "components", "occurrences"].map(|f| format!("c{}/{f}", c.id))).collect();
+ h.app.tree.expanded.extend(keys);
+ h.frames(2);
+ let expanded = ms(|| h.frames(5)) / 5.0;
+ let scene = ms(|| drop(crate::viewport::build_scene(&h.app)));
+ let scene_again = ms(|| drop(crate::viewport::build_scene(&h.app)));
+ let bodies = h.app.session.world_state().bodies.len();
+ let rename = ms(|| {
+ h.app.run("body.rename", json!({"body": "Body1", "name": "Renamed"})).unwrap();
+ h.frame();
+ });
+ let scene_renamed = ms(|| drop(crate::viewport::build_scene(&h.app)));
+ println!(
+ "DESIGN bodies={bodies} idle_frame_ms={idle:.2} expanded_frame_ms={expanded:.2} scene_ms={scene:.2} scene_again_ms={scene_again:.2} rename_ms={rename:.2} scene_renamed_ms={scene_renamed:.2}"
+ );
+ let t = std::time::Instant::now();
+ while t.elapsed().as_secs() < std::env::var("SOLIDCRAFT_SCALE_LOOP").ok().and_then(|v| v.parse().ok()).unwrap_or(0) {
+ h.frame();
+ }
+}
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index aaae8c4a2a..64d36b7109 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -646,7 +646,7 @@ fn push_block(
made.insert(key, block);
}
-fn build_scene(app: &SolveApp) -> GpuScene {
+pub(crate) fn build_scene(app: &SolveApp) -> GpuScene {
let tk = Tokens::get();
let mut sc = GpuScene::default();
let s = &app.session;
@@ -1977,7 +1977,7 @@ struct HoverBlock {
}
/// The highlight scene: origin widget, construction planes, selection and hover.
-fn build_highlight(app: &SolveApp) -> GpuScene {
+pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene {
let t = Tokens::get();
let mut sc = GpuScene::default();
let st = crate::open_meshing::shown_world(app);