diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rs index 9030066b9..04bc9766c 100644 --- a/apps/solidcraft-cli/src/main.rs +++ b/apps/solidcraft-cli/src/main.rs @@ -4,7 +4,7 @@ //! solidcraft-cli run [--in design|part.step|mesh.3mf] [--out FILE]... [--save FILE] [--quiet] [--results] [--timings] [--profile] [--json-out FILE] [--allow-errors] //! solidcraft-cli eval [--json-out FILE] (alias: inspect) measurements as JSON //! solidcraft-cli script [--out script.json] the design's history as a command script -//! solidcraft-cli bench-open [--parse-only] [--save OUT.solidcraft] [--display LEVEL [--edit NAME EXPR]] loading timings as JSON lines +//! solidcraft-cli bench-open [--parse-only] [--save OUT.solidcraft] [--display LEVEL [--edit NAME EXPR]] [--ops script.json] loading timings as JSON lines //! solidcraft-cli bench-agent [--scale F] [--save F] [--script-out F] a ~1,300-body design built command by command, timed //! solidcraft-cli snapshot [--in design|part.step] --out shot.png [--width W] [--height H] [--view iso|front|top|…|NAME | --camera JSON] [--no-grid] [--no-axes] //! [--body NAME:opacity=0.3,color=#rrggbb]... [--tool NAME]... [--section z=27] @@ -50,7 +50,9 @@ const USAGE: &str = "usage: as plain UTF-8: a shell's > can re-encode it, e.g. Windows PowerShell adds a byte-order mark) solidcraft-cli script [--out script.json] (the design's history as a command script that eval and run replay) - solidcraft-cli bench-open [--parse-only] [--save OUT.solidcraft] [--display LEVEL [--edit NAME EXPR]] + solidcraft-cli bench-open [--parse-only] [--save OUT.solidcraft] [--display LEVEL [--edit NAME EXPR]] [--ops script.json] + (--ops: after opening, run each command of the script and undo it, timing the command, the + evaluations it caused and the view it leaves: placing and meshing what changed) solidcraft-cli bench-agent [--scale F] [--save design.solidcraft] [--script-out script.json] solidcraft-cli snapshot [--in design.solidcraft|part.step] --out shot.png [--width W] [--height H] [--view NAME | --camera JSON] [--no-grid] [--no-axes] [--body NAME:opacity=0.3,color=#rrggbb]... [--tool NAME]... [--section z=27] @@ -642,6 +644,36 @@ fn cmd_bench_edit(args: &[String]) -> Result<(), String> { Ok(()) } +/// `bench-open --ops`: each command of `script` (a JSON array of `{command, params}`), then its +/// undo, each timed as the command and the view it leaves (the placed model, its meshes warmed +/// as the desktop does after a change). +fn bench_ops(mut s: Session, script: &str) -> Result { + let text = std::fs::read_to_string(script).map_err(|e| format!("{script}: {e}"))?; + let ops: Value = serde_json::from_str(&text).map_err(|e| format!("{script}: {e}"))?; + let ops = ops.as_array().ok_or("--ops: a JSON array of {command, params}")?; + let time = |s: &mut Session, id: &str, p: &Value| -> Result { + let t = std::time::Instant::now(); + let r = s.execute(id, p).map_err(|e| format!("{id}: {e}"))?; + let ms = t.elapsed().as_secs_f64() * 1000.0; + let t = std::time::Instant::now(); + s.world_state().warm_meshes(|| true); + let view_ms = t.elapsed().as_secs_f64() * 1000.0; + println!("{}", json!({"step": "op", "command": id, "ms": ms, "view_ms": view_ms})); + Ok(r) + }; + for op in ops { + let id = op.get("command").and_then(Value::as_str).ok_or("--ops: each step needs a `command`")?; + let p = op.get("params").cloned().unwrap_or(Value::Null); + let steps = s.undo.len(); + time(&mut s, id, &p)?; + // Commands that are no undo step (showing and hiding) have nothing to undo. + if op.get("undo").and_then(Value::as_bool) != Some(false) && s.undo.len() > steps { + time(&mut s, "edit.undo", &json!({}))?; + } + } + Ok(s) +} + /// Separate file reading, JSON decoding/repair, timeline evaluation and display meshing. pub(crate) fn cmd_bench_open(args: &[String]) -> Result<(), String> { let path = args.first().ok_or("usage: solidcraft-cli bench-open [--parse-only]")?; @@ -727,6 +759,10 @@ pub(crate) fn cmd_bench_open(args: &[String]) -> Result<(), String> { // `--display LEVEL`: the display plans the viewport draws at that display quality, made as // the GPU viewport makes them; `--edit NAME EXPR` then changes a parameter and times the // evaluation and the plans of the bodies it changed. + let s = match flag("--ops").and_then(|i| args.get(i + 1)) { + Some(ops) => bench_ops(s, ops)?, + None => s, + }; let Some(level) = flag("--display").and_then(|i| args.get(i + 1)) else { return Ok(()) }; let q = solidcraft_engine::doc::display_quality::DisplayQuality::parse(level).ok_or("--display: coarse, normal, fine or ultra")?; let plans = |st: &solidcraft_engine::doc::ModelState| { diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 02afec755..8b5ed6eed 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -2637,6 +2637,87 @@ impl Document { } } + /// Rename body `old` to `new` where the design keeps things by body name outside its + /// features: materials, appearances, configuration columns, offsets, components and the + /// browser's groups and order. (The features are the rename command's to change.) + pub fn rename_body_keys(&mut self, old: &str, new: &str) { + if let Some(m) = self.materials.remove(old) { + self.materials.insert(new.to_string(), m); + } + if let Some(c) = self.appearances.bodies.remove(old) { + self.appearances.bodies.insert(new.to_string(), c); + } + for f in self.appearances.faces.iter_mut().filter(|f| f.body == old) { + f.body = new.to_string(); + } + for column in &mut self.configs.columns { + match column { + crate::config::Column::Material(body) | crate::config::Column::Appearance(body) if *body == old => { + *body = new.to_string(); + } + crate::config::Column::FaceAppearance(target) if target.body == old => { + target.body = new.to_string(); + } + _ => {} + } + } + if let Some(o) = self.body_offsets.remove(old) { + self.body_offsets.insert(new.to_string(), o); + } + if let Some(c) = self.body_components.remove(old) { + self.body_components.insert(new.to_string(), c); + } + for g in self.browser_groups.iter_mut().filter(|g| g.folder == "bodies") { + for k in g.items.iter_mut().filter(|k| *k == old) { + *k = new.to_string(); + } + } + for (_, v) in self.browser_order.iter_mut().filter(|(k, _)| k.ends_with("/bodies")) { + for k in v.iter_mut().filter(|k| *k == old) { + *k = new.to_string(); + } + } + } + + /// The single body rename (old name, new name) that turns `previous` into this design, + /// when that is all that changed: the features' stored body names (`made` gives the names + /// each feature's bodies have now, by feature id) and what [`Document::rename_body_keys`] + /// renames. `None` for any other change. + pub fn body_rename_from(&self, previous: &Document, made: impl Fn(u64) -> Vec) -> Option<(String, String)> { + if self.features.len() != previous.features.len() { + return None; + } + let mut rename: Option<(String, String)> = None; + for (a, b) in previous.features.iter().zip(&self.features) { + if a.id != b.id { + return None; + } + if a.body_names == b.body_names { + continue; + } + let now = made(a.id); + for (k, name) in b.body_names.iter().enumerate() { + let current = now.get(k); + // Slots the rename left alone, and the ones it set to the names they have now. + if a.body_names.get(k) == Some(name) || name.trim().is_empty() || current == Some(name) { + continue; + } + let pair = (current?.clone(), name.clone()); + match &rename { + Some(r) if *r != pair => return None, + _ => rename = Some(pair), + } + } + } + let (old, new) = rename?; + let mut expected = previous.clone(); + for (f, g) in expected.features.iter_mut().zip(&self.features) { + f.body_names.clone_from(&g.body_names); + } + expected.rename_body_keys(&old, &new); + (expected == *self).then_some((old, new)) + } + /// 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 82dd4c7db..c4ced0c4b 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1494,6 +1494,58 @@ impl Model { } } +impl Model { + /// Follow a rename of body `old` to `new` without evaluating anything (#3044): `doc` is the + /// design after the rename, which changed nothing but names, so every result keeps its + /// geometry and meshes and only the body's name (and the names worked out from it) changes. + /// False, leaving the model as it was, when the rename can't be followed that way and the + /// design must be evaluated: the model isn't the design's, the body is changed by a later + /// feature, or is sheet metal, threaded, or named in a later feature's face references. + pub fn rename_body(&mut self, doc: &Document, old: &str, new: &str) -> 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(at) = self.results.iter().position(|r| r.state.body(old).is_some()) else { return false }; + let Some(made) = self.results.get(at).and_then(|r| r.state.body(old)).map(|b| Arc::as_ptr(&b.mesh)) else { return false }; + // Untouched from the feature that made it to the end, and nothing else holds its name. + let untouched = self.results.iter().skip(at).all(|r| r.state.body(old).is_some_and(|b| Arc::as_ptr(&b.mesh) == made)); + let named_elsewhere = self + .results + .iter() + .any(|r| r.state.body(new).is_some() || r.state.sheets.iter().any(|x| x.body == old) || r.state.threads.iter().any(|t| t.body == old)); + let faces_named = doc.features.iter().skip(at + 1).any(|f| f.face_names.iter().any(|n| n.contains(old))); + if !untouched || named_elsewhere || faces_named { + return false; + } + // States shared between results stay shared. + let mut renamed: std::collections::HashMap<*const ModelState, Arc> = std::collections::HashMap::new(); + for r in self.results.iter_mut().skip(at) { + let state = renamed + .entry(Arc::as_ptr(&r.state)) + .or_insert_with(|| { + let mut st = (*r.state).clone(); + for b in st.bodies.iter_mut().filter(|b| b.name == old) { + b.name = new.to_string(); + b.names = b.names.renamed(); + } + Arc::new(st) + }) + .clone(); + r.state = state; + } + // The fingerprints of the renamed design, so the next evaluation reuses every result. + let (vals, _) = evaluation_values(doc); + let marker = doc.marker.unwrap_or(usize::MAX); + self.step_digests = StepDigests::of(doc, &self.step_digests); + let mut prev = 0; + for (i, (r, f)) in self.results.iter_mut().zip(&doc.features).enumerate() { + prev = chain_fingerprint(doc, &vals, f, prev, i >= marker, &self.step_digests); + r.fingerprint = prev; + } + true + } +} + /// Key of the design's length unit (mm per unit) among the values (no parameter can be named /// so). pub(crate) const DESIGN_LEN: &str = "\u{1}design_len"; diff --git a/crates/doc/src/naming.rs b/crates/doc/src/naming.rs index 71d32e6ee..1801fca6f 100644 --- a/crates/doc/src/naming.rs +++ b/crates/doc/src/naming.rs @@ -85,6 +85,17 @@ impl NameCell { pub(crate) fn id(&self) -> usize { Arc::as_ptr(&self.names) as usize } + /// The same origin, lineage and depth with nothing worked out yet: for a body given a new + /// name, whose faces' names may be made from it. + pub(crate) fn renamed(&self) -> Self { + NameCell { + origin: self.origin.clone(), + lineage: self.lineage.clone(), + copy_of: self.copy_of.clone(), + saved_depth: self.saved_depth, + ..NameCell::default() + } + } fn shared(names: Arc) -> Self { let cell = OnceLock::new(); let _ = cell.set(names); diff --git a/crates/engine/src/cmd/browser.rs b/crates/engine/src/cmd/browser.rs index 1de6dd786..824808a98 100644 --- a/crates/engine/src/cmd/browser.rs +++ b/crates/engine/src/cmd/browser.rs @@ -508,20 +508,6 @@ fn view_list(s: &mut Session, _p: &Value) -> Result { Ok(json!({ "views": s.doc.named_views })) } -/// Rename an item key in the browser's groups and orders of a folder. -fn rename_key(d: &mut solidcraft_doc::Document, folder: &str, old: &str, new: &str) { - for g in d.browser_groups.iter_mut().filter(|g| g.folder == folder) { - for k in g.items.iter_mut().filter(|k| *k == old) { - *k = new.to_string(); - } - } - for (_, v) in d.browser_order.iter_mut().filter(|(k, _)| k.ends_with(&format!("/{folder}"))) { - for k in v.iter_mut().filter(|k| *k == old) { - *k = new.to_string(); - } - } -} - /// The keys whose strings name bodies, alone or in a list (`body`, `targets`…), at any depth of a /// feature: its own fields and the face, edge and link references inside it. const BODY_KEYS: [&str; 5] = ["body", "bodies", "target", "targets", "tools"]; @@ -638,33 +624,7 @@ fn rename_body(s: &mut Session, p: &Value) -> Result { if let Some(e) = failed { return Err(bad(cmd, e)); } - if let Some(m) = d.materials.remove(&old) { - d.materials.insert(name.to_string(), m); - } - if let Some(c) = d.appearances.bodies.remove(&old) { - d.appearances.bodies.insert(name.to_string(), c); - } - for f in d.appearances.faces.iter_mut().filter(|f| f.body == old) { - f.body = name.to_string(); - } - for column in &mut d.configs.columns { - match column { - solidcraft_doc::config::Column::Material(body) | solidcraft_doc::config::Column::Appearance(body) if *body == old => { - *body = name.to_string(); - } - solidcraft_doc::config::Column::FaceAppearance(target) if target.body == old => { - target.body = name.to_string(); - } - _ => {} - } - } - if let Some(o) = d.body_offsets.remove(&old) { - d.body_offsets.insert(name.to_string(), o); - } - if let Some(c) = d.body_components.remove(&old) { - d.body_components.insert(name.to_string(), c); - } - rename_key(d, "bodies", &old, name); + d.rename_body_keys(&old, name); for b in s.visibility.hidden_bodies.iter_mut().filter(|b| **b == old) { *b = name.to_string(); } @@ -864,6 +824,44 @@ mod tests { assert!(names(&s).contains(&"Body2".to_string()) && names(&s).contains(&"Body4".to_string()), "{:?}", names(&s)); } + /// #3044: a rename changes names only, so it, its undo and its redo evaluate nothing: every + /// body keeps its geometry and display mesh, and the model is the one evaluating the renamed + /// design gives. + #[test] + fn renaming_a_body_evaluates_nothing() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "A"})); + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "center": [20, 0, 2.5], "operation": "new", "body_name": "B"})); + run(&mut s, "appearance.assign", json!({"bodies": ["A"], "appearance": "Aluminum - Satin"})); + let meshes = |s: &Session| s.model.state().bodies.iter().map(|b| std::sync::Arc::as_ptr(&b.mesh())).collect::>(); + let shown = meshes(&s); + s.evaluations = 0; + run(&mut s, "body.rename", json!({"body": "A", "name": "Plate"})); + assert_eq!(s.evaluations, 0, "a rename evaluates nothing"); + assert_eq!(names(&s), vec!["Plate".to_string(), "B".to_string()]); + assert_eq!(meshes(&s), shown, "the bodies keep their meshes"); + assert!(s.doc.appearances.bodies.contains_key("Plate")); + // The same model as evaluating the renamed design. + let mut fresh = Session::new((*s.doc).clone()); + fresh.refresh(); + assert_eq!(names(&fresh), names(&s)); + s.refresh(); + assert_eq!(s.model.last_recomputed, 0, "the next evaluation reuses every result"); + s.evaluations = 0; + run(&mut s, "edit.undo", json!({})); + assert_eq!(names(&s), vec!["A".to_string(), "B".to_string()]); + run(&mut s, "edit.redo", json!({})); + assert_eq!(names(&s), vec!["Plate".to_string(), "B".to_string()]); + assert_eq!(s.evaluations, 0, "undo and redo of a rename evaluate nothing"); + assert_eq!(meshes(&s), shown); + // A body a later feature uses is renamed in that feature too: that is evaluated. + run(&mut s, "solid.combine", json!({"target": "Plate", "tools": ["B"], "operation": "join", "keep_tools": true})); + s.evaluations = 0; + run(&mut s, "body.rename", json!({"body": "B", "name": "Tool"})); + assert!(s.evaluations > 0); + assert!(names(&s).contains(&"Tool".to_string())); + } + #[test] fn renaming_a_body_leaves_other_text_with_its_name_alone() { let mut s = Session::default(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e34aeb615..29516295b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -149,6 +149,14 @@ pub enum Sel { }, } +/// A body rename between two designs (see `Session::body_renames`). +struct BodyRename { + before: std::sync::Weak, + after: std::sync::Weak, + old: String, + new: String, +} + /// One undo step. #[derive(Clone, Debug)] pub struct Snapshot { @@ -246,6 +254,9 @@ pub struct Session { /// Pairs `inspect.clearance` measured, by the bodies' geometry where they stood (shared with /// scratch copies): a body that did not change or move is not measured again. clearance_cache: std::sync::Arc>, + /// Recent body renames: the design before and after each, and the names, so undo and redo + /// follow them without evaluating either. + body_renames: Vec, /// Features copied with `timeline.copy` (pasted by `timeline.paste`). pub clipboard: Vec, /// Sketch geometry copied with `sketch.copy` (pasted by `sketch.paste`). @@ -399,6 +410,7 @@ impl Session { occurrence_visibility_cache: Default::default(), removed_later_cache: Default::default(), clearance_cache: Default::default(), + body_renames: Vec::new(), clipboard: Vec::new(), sketch_clipboard: None, section: None, @@ -620,6 +632,47 @@ 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). + fn refresh_from(&mut self, previous: &Arc) { + if let Some((old, new)) = self.body_rename(previous) + && self.model.rename_body(&self.doc, &old, &new) + { + self.revision += 1; + if !self.doc.assembly.joints.is_empty() { + cmd::joints::resolve(self); + } + return; + } + self.refresh(); + } + + /// The body rename that turned `previous` into the design (old name, new name), if that is + /// the whole change: one this session made (either way round), else one the designs show. + fn body_rename(&mut self, previous: &Arc) -> Option<(String, String)> { + let holds = |w: &std::sync::Weak, d: &Arc| w.upgrade().is_some_and(|x| Arc::ptr_eq(&x, d)); + self.body_renames.retain(|r| r.before.strong_count() > 0 && r.after.strong_count() > 0); + for r in &self.body_renames { + if holds(&r.before, previous) && holds(&r.after, &self.doc) { + return Some((r.old.clone(), r.new.clone())); + } + if holds(&r.after, previous) && holds(&r.before, &self.doc) { + return Some((r.new.clone(), r.old.clone())); + } + } + let model = &self.model; + let made = |id: u64| -> Vec { + model.result(id).map(|r| r.state.bodies.iter().filter(|b| b.feature == id).map(|b| b.name.clone()).collect()).unwrap_or_default() + }; + let (old, new) = self.doc.body_rename_from(previous, made)?; + self.body_renames.push(BodyRename { before: Arc::downgrade(previous), after: Arc::downgrade(&self.doc), old: old.clone(), new: new.clone() }); + if self.body_renames.len() > MAX_UNDO { + self.body_renames.remove(0); + } + Some((old, new)) + } + /// Only persistent render intent, or only part properties, changed. Never evaluate or clear /// a stale model here. fn render_only_change(&self, before: &Snapshot) -> bool { @@ -766,7 +819,7 @@ impl Session { match live_edit { Some(edit) => self.refresh_live(edit), None if render_only => self.refresh_render(&previous_doc), - None => self.refresh(), + None => self.refresh_from(&previous_doc), } } Ok(v) @@ -874,6 +927,7 @@ impl Session { occurrence_visibility_cache: Default::default(), removed_later_cache: Default::default(), clearance_cache: self.clearance_cache.clone(), + body_renames: Vec::new(), clipboard: self.clipboard.clone(), sketch_clipboard: self.sketch_clipboard.clone(), section: None, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d7aafdc3d..3ede07560 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3791,3 +3791,37 @@ fn a_tapered_side_drawn_in_two_collinear_pieces_is_one_face() { let m = run(&mut s, "inspect.measure", json!({})); assert_eq!(m["bodies"][0]["kernel"]["faces"], 6, "{m}"); } + +/// #3044: renaming a body of an imported assembly (a part placed twice, so the file has more +/// solids than the part has bodies) evaluates nothing, not even the file again, and leaves the +/// model evaluating the renamed design gives; undo does the same. +#[test] +fn renaming_an_imported_assembly_body_reads_nothing_again() { + let dir = std::env::temp_dir().join(format!("solidcraft-step-rename-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut a = Session::default(); + run(&mut a, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Cube"})); + run(&mut a, "solid.box", json!({"length": 4, "width": 4, "height": 4, "center": [30, 0, 2], "operation": "new", "body_name": "Pin"})); + run(&mut a, "component.from_bodies", json!({"bodies": ["Cube"]})); + run(&mut a, "occurrence.copy", json!({"component": "Cube", "translate": [0, 40, 0]})); + let p = dir.join("Assembly.step"); + run(&mut a, "file.export", json!({"path": p.to_string_lossy()})); + let mut s = Session::default(); + run(&mut s, "doc.open", json!({"path": p.to_string_lossy()})); + let names = |s: &Session| s.model.state().bodies.iter().map(|b| b.name.clone()).collect::>(); + let before = names(&s); + let body = before.first().cloned().unwrap(); + s.evaluations = 0; + run(&mut s, "body.rename", json!({"body": body, "name": "Renamed"})); + assert_eq!(s.evaluations, 0, "a rename evaluates nothing"); + let after = names(&s); + assert_eq!(after.first().map(String::as_str), Some("Renamed")); + assert_eq!(after.len(), before.len()); + let mut fresh = Session::new((*s.doc).clone()); + fresh.refresh(); + assert_eq!(names(&fresh), after, "the same names as evaluating the renamed design"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(names(&s), before); + assert_eq!(s.evaluations, 0, "nor does its undo"); + let _ = std::fs::remove_dir_all(&dir); +}