From e98e065584c6639b68f3c1d7321667a34d51ee62 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Tue, 20 Oct 2026 14:24:34 +0000 Subject: [PATCH] Open saved designs from the model they were saved with (#3053) (#3102) * WIP: adopt the saved model on open (#3053) Co-Authored-By: Claude Opus 5.5 * WIP: tests * WIP: bench-open opens as Open does * docs: opening from the saved model * Tests: an edit after opening evaluates from the feature it changes * clippy * Read SOLIDCRAFT_NO_MODEL_CACHE through the env helper * Open: no picture from the model when the model itself opens; cancel test evaluates * Saved model: bodies passed through found without writing their record; states list runs of bodies * Adopted results go into the evaluation cache: an undone edit, or the marker rolled forward, takes them again * Model cache size guard: the saved model's writer --------- Co-authored-by: Claude Opus 5.5 --- apps/solidcraft-cli/src/main.rs | 15 +- apps/solidcraft-cli/tests/model_cache.rs | 209 +++++++++++ crates/doc/src/construct.rs | 4 +- crates/doc/src/eval.rs | 9 +- crates/doc/src/lib.rs | 8 +- crates/doc/src/model_cache.rs | 424 +++++++++++++++++++++++ crates/doc/src/naming.rs | 16 + crates/doc/src/sheet.rs | 20 +- crates/engine/src/cmd/file.rs | 52 +-- crates/engine/src/lib.rs | 19 +- crates/io/src/design.rs | 93 ++--- crates/io/src/design/native_cache.rs | 158 +++------ crates/kernel/src/blend_variable.rs | 4 +- crates/kernel/src/boolean_diagnostics.rs | 8 +- docs/design-container.md | 60 +++- 15 files changed, 880 insertions(+), 219 deletions(-) create mode 100644 apps/solidcraft-cli/tests/model_cache.rs create mode 100644 crates/doc/src/model_cache.rs diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rs index dec00af12..9030066b9 100644 --- a/apps/solidcraft-cli/src/main.rs +++ b/apps/solidcraft-cli/src/main.rs @@ -654,24 +654,27 @@ pub(crate) fn cmd_bench_open(args: &[String]) -> Result<(), String> { let t = std::time::Instant::now(); // The file as read, held until the timeline has evaluated it (as the import command does). let mut read = None; - let doc = if step { + let (doc, saved) = if step { let imported = solidcraft_engine::io::step_import_feature(&bytes, path).map_err(|e| e.to_string())?; let mut doc = solidcraft_engine::doc::Document::new(&imported.name); doc.add_feature(imported.kind, Some(&imported.name)).map_err(|e| e.to_string())?; read = Some(imported.import); - doc + (doc, None) } else { - solidcraft_engine::io::read_design(&bytes).map_err(|e| e.to_string())? + // As Open reads it: with the model the file keeps. + solidcraft_engine::io::read_design_file(path, None::).map_err(|e| e.to_string())? }; let parse_ms = t.elapsed().as_secs_f64() * 1000.0; - println!("{}", json!({"step": "parse", "ms": parse_ms, "features": doc.features.len()})); + println!("{}", json!({"step": "parse", "ms": parse_ms, "features": doc.features.len(), "saved_model": saved.is_some()})); if args.iter().any(|a| a == "--parse-only") { return Ok(()); } let t = std::time::Instant::now(); - let s = Session::new(doc); + let s = Session::opened(doc, saved.as_ref()); drop(read); - println!("{}", json!({"step": "evaluate", "ms": t.elapsed().as_secs_f64() * 1000.0})); + // Taken from the file: nothing evaluated (SOLIDCRAFT_NO_MODEL_CACHE evaluates anyway). + let adopted = saved.is_some() && s.model.last_recomputed == 0; + println!("{}", json!({"step": "evaluate", "ms": t.elapsed().as_secs_f64() * 1000.0, "adopted": adopted})); for r in &s.model.results { println!("{}", json!({"step": "feature", "id": r.id, "name": r.name, "ms": r.ms, "error": r.error})); } diff --git a/apps/solidcraft-cli/tests/model_cache.rs b/apps/solidcraft-cli/tests/model_cache.rs new file mode 100644 index 000000000..6d4bab4eb --- /dev/null +++ b/apps/solidcraft-cli/tests/model_cache.rs @@ -0,0 +1,209 @@ +//! A design opened from the model its file keeps is the design evaluated again: the same +//! results, the same bodies (to the bit), the same face names and volumes after every feature, +//! and the same after an edit made to both. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use serde_json::{Value, json}; +use solidcraft_engine::Session; +use solidcraft_engine::doc::{ModelBody, ModelState}; + +fn corpus() -> Vec { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus"); + let mut v: Vec = + std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "solidcraft")).collect(); + v.sort(); + v +} + +fn temp(name: &str) -> PathBuf { + std::env::temp_dir().join(format!("solidcraft-model-cache-{}-{name}.solidcraft", std::process::id())) +} + +fn open(path: &Path) -> Session { + let mut s = Session::default(); + s.execute("doc.open", &json!({"path": path.to_string_lossy()})).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + s +} + +fn body(name: &str, b: &ModelBody) -> Value { + let measured = solidcraft_engine::kernel::measure(&b.body).ok(); + json!({ + "name": b.name, "feature": b.feature, "component": b.component, "source": b.source_name, "transferred": b.transferred, + "brep": solidcraft_engine::kernel::encode_native_body(&b.body).map(|bytes| format!("{:x}", sha(&bytes))).unwrap_or_else(|e| format!("{name}: {e}")), + "faces": *solidcraft_engine::doc::naming::face_names(b), + "volume": measured.as_ref().map(|m| m.volume.to_bits()), "area": measured.as_ref().map(|m| m.area.to_bits()), + "look": b.imported.as_ref().map(|l| format!("{l:?}")), + }) +} + +fn sha(bytes: &[u8]) -> u128 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + bytes.hash(&mut h); + let a = h.finish(); + bytes.len().hash(&mut h); + (u128::from(a) << 64) | u128::from(h.finish()) +} + +fn state(name: &str, st: &Arc) -> Value { + json!({ + "bodies": st.bodies.iter().map(|b| body(name, b)).collect::>(), + "sketches": st.sketches.iter().map(|s| json!([s.feature, s.name, s.plane, s.sketch, s.report, s.profiles.len()])).collect::>(), + "counter": st.body_counter, "sheets": st.sheets, "threads": st.threads, "construct": format!("{:?}", st.construct), + }) +} + +/// Everything a model holds that the rest of the app reads. +fn model(name: &str, s: &Session) -> Value { + let results: Vec = s + .model + .results + .iter() + .map(|r| json!({"id": r.id, "name": r.name, "error": r.error, "warning": r.warning, "skipped": r.skipped, "state": state(name, &r.state)})) + .collect(); + json!({"results": results, "world": state(name, &s.world_state())}) +} + +/// The same edit on both: a parameter's value when the design has one, else a new body. +fn edit(s: &mut Session) { + let param = s.doc.params.first().map(|p| (p.name.clone(), p.expr.clone())); + match param { + Some((name, expr)) => { + s.execute("parameters.change", &json!({"name": name, "expression": format!("({expr}) * 1.05")})).unwrap(); + } + None => { + s.execute("solid.box", &json!({"length": 7, "width": 8, "height": 9, "operation": "new"})).unwrap(); + } + } +} + +fn check(name: &str, mut built: Session) { + let path = temp(name); + built.execute("file.save_as", &json!({"path": path.to_string_lossy()})).unwrap(); + let bytes = std::fs::read(&path).unwrap(); + assert!(solidcraft_engine::io::read_design_geometry(&bytes).is_some(), "{name}: the save keeps the model"); + let mut cached = open(&path); + assert_eq!(cached.model.last_recomputed, 0, "{name}: opened without evaluating"); + let mut rebuilt = Session::new(solidcraft_engine::io::read_design(&bytes).unwrap()); + assert!(rebuilt.model.last_recomputed > 0); + assert_eq!(model(name, &cached), model(name, &rebuilt), "{name}: opened from the file's model"); + edit(&mut cached); + edit(&mut rebuilt); + assert_eq!(model(name, &cached), model(name, &rebuilt), "{name}: after the same edit"); + cached.execute("edit.undo", &json!({})).unwrap(); + rebuilt.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(model(name, &cached), model(name, &rebuilt), "{name}: after undoing it"); + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(format!("{}.bak", path.display())); +} + +#[test] +fn corpus_designs_open_from_their_model_as_evaluated() { + for p in corpus() { + let name = p.file_stem().unwrap_or_default().to_string_lossy().to_string(); + let s = open(&p); + // Names saved before format 14 are found again through names worked out from geometry on + // demand, which a saved model does not keep. + let legacy = s.doc.to_json().contains(&format!("\"{}", solidcraft_engine::doc::naming::LEGACY_MARK)); + if s.model.results.iter().any(|r| r.error.is_some()) || legacy { + // Not kept: a model with errors, or names saved before format 14. + let path = temp(&name); + let mut s = s; + s.execute("file.save_as", &json!({"path": path.to_string_lossy()})).unwrap(); + assert!(solidcraft_engine::io::read_design_geometry(&std::fs::read(&path).unwrap()).is_none(), "{name}"); + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(format!("{}.bak", path.display())); + continue; + } + check(&name, s); + } +} + +#[test] +fn sample_designs_open_from_their_model_as_evaluated() { + for sample in solidcraft_engine::sample::samples() { + let mut s = Session::default(); + for c in (sample.script)()["commands"].as_array().unwrap() { + s.execute(c["command"].as_str().unwrap(), &c["params"]).unwrap_or_else(|e| panic!("{}: {e}", sample.name)); + } + check(sample.name, s); + } +} + +#[test] +fn imported_assemblies_open_from_their_model_as_evaluated() { + // A STEP assembly of the hinge sample: parts placed several times. + let mut source = Session::default(); + let hinge = solidcraft_engine::sample::samples().into_iter().find(|s| s.name == "Hinge Assembly").unwrap(); + for c in (hinge.script)()["commands"].as_array().unwrap() { + source.execute(c["command"].as_str().unwrap(), &c["params"]).unwrap(); + } + let step = std::env::temp_dir().join(format!("solidcraft-model-cache-{}-hinge.step", std::process::id())); + source.execute("file.export", &json!({"path": step.to_string_lossy()})).unwrap(); + let mut s = Session::default(); + s.execute("file.insert_step", &json!({"path": step.to_string_lossy()})).unwrap(); + s.execute("file.insert_step", &json!({"path": step.to_string_lossy(), "matrix": [1, 0, 0, 200, 0, 1, 0, 0, 0, 0, 1, 0]})).unwrap(); + let _ = std::fs::remove_file(&step); + check("imported hinge", s); +} + +/// Opened from its model, a design evaluates only from the first feature an edit changes: the +/// saved states before it are kept as they were read (the same states, not evaluated again). +#[test] +fn an_edit_after_opening_evaluates_from_the_feature_it_changes() { + let plate = solidcraft_engine::sample::samples().into_iter().find(|s| s.name == "Sample Plate").unwrap(); + let mut built = Session::default(); + for c in (plate.script)()["commands"].as_array().unwrap() { + built.execute(c["command"].as_str().unwrap(), &c["params"]).unwrap(); + } + let path = temp("incremental"); + built.execute("file.save_as", &json!({"path": path.to_string_lossy()})).unwrap(); + let n = built.doc.features.len(); + assert!(n >= 4); + let mut s = open(&path); + assert_eq!(s.model.last_recomputed, 0); + let read: Vec> = s.model.results.iter().map(|r| r.state.clone()).collect(); + // How many of the first features still have the states read from the file. + let kept = |s: &Session| s.model.results.iter().zip(&read).take_while(|(r, st)| Arc::ptr_eq(&r.state, st)).count(); + // The marker moved back and forth: the features before it are as read. + s.execute("timeline.rollback", &json!({"position": n - 2})).unwrap(); + assert_eq!(kept(&s), n - 2, "rolled back"); + s.execute("timeline.rollback", &json!({})).unwrap(); + assert_eq!(kept(&s), n, "rolled forward: the features after the marker take their saved results again"); + // Suppressing the second-to-last feature keeps every state before it. + let k = s.doc.features[n - 2].id; + s.execute("timeline.suppress", &json!({"feature": k, "suppressed": true})).unwrap(); + assert_eq!(kept(&s), n - 2, "evaluated from the suppressed feature on"); + s.execute("edit.undo", &json!({})).unwrap(); + // A new feature at the end starts from the final state read from the file. + let mut s = open(&path); + let read: Vec> = s.model.results.iter().map(|r| r.state.clone()).collect(); + s.execute("solid.box", &json!({"length": 3, "width": 3, "height": 3, "operation": "new"})).unwrap(); + assert_eq!(s.model.results.len(), n + 1); + assert!(s.model.results.iter().zip(&read).all(|(r, st)| Arc::ptr_eq(&r.state, st)), "only the new feature evaluated"); + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(format!("{}.bak", path.display())); +} + +/// An edit made after opening and undone finds the saved results again: undo evaluates nothing. +#[test] +fn undoing_an_edit_after_opening_reuses_the_saved_results() { + let plate = solidcraft_engine::sample::samples().into_iter().find(|s| s.name == "Sample Plate").unwrap(); + let mut built = Session::default(); + for c in (plate.script)()["commands"].as_array().unwrap() { + built.execute(c["command"].as_str().unwrap(), &c["params"]).unwrap(); + } + let path = temp("undo"); + built.execute("file.save_as", &json!({"path": path.to_string_lossy()})).unwrap(); + let mut s = open(&path); + let read: Vec> = s.model.results.iter().map(|r| r.state.clone()).collect(); + let first = s.doc.features[1].id; + s.execute("timeline.suppress", &json!({"feature": first, "suppressed": true})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.model.last_recomputed, 0, "taken from the saved results"); + assert!(s.model.results.iter().zip(&read).all(|(r, st)| Arc::ptr_eq(&r.state, st)), "the very states read from the file"); + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(format!("{}.bak", path.display())); +} diff --git a/crates/doc/src/construct.rs b/crates/doc/src/construct.rs index 6c441bf3e..e5f589bb2 100644 --- a/crates/doc/src/construct.rs +++ b/crates/doc/src/construct.rs @@ -92,14 +92,14 @@ pub enum PointDef { } /// Resolved construction geometry, kept in the model state by feature. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ConstructGeom { Plane(Plane), Axis { origin: Vec3, dir: Vec3 }, Point(Vec3), } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Construct { pub feature: u64, pub name: String, diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 8fa1512ee..82dd4c7db 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -7,7 +7,7 @@ use std::collections::BTreeMap; use std::hash::{Hash, Hasher}; use std::sync::{Arc, OnceLock}; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use solidcraft_geom::tess::TessPlan; use solidcraft_geom::{Mesh, Plane, Region2, UnitVec3, Vec2, Vec3, regions_apart}; use solidcraft_kernel::{self as kernel, Body, BoolOp}; @@ -208,7 +208,7 @@ pub struct SolvedSketch { } /// A cosmetic thread: on which cylinder, its size, and the threaded part of the axis. -#[derive(Clone, Debug, PartialEq, Serialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreadInfo { pub feature: u64, pub body: String, @@ -615,7 +615,7 @@ impl ModelState { /// [`quantize`]); the rest keep theirs. fn stamp(&mut self, before: &Arc, f: &Feature, key: u64, mats: Vec) { let feature = f.id; - let depth = before.bodies.iter().filter_map(|b| b.names.origin.as_ref().map(|o| o.depth)).max().unwrap_or(0) + 1; + let depth = before.bodies.iter().filter_map(|b| b.names.depth()).max().unwrap_or(0) + 1; let sheets = if f.kind.is_sheet() { self.sheets.clone() } else { Vec::new() }; let origin = Arc::new(crate::naming::NamingOrigin { feature: f.clone(), before: before.clone(), depth, mats, sheets }); // Pieces a cut left are named after their faces, not the kernel's shell order (unless @@ -4596,8 +4596,11 @@ fn replay( Ok(()) } +#[path = "model_cache.rs"] +mod model_cache; #[path = "eval_more.rs"] mod more; +pub use model_cache::SavedModel; #[path = "eval_surface.rs"] mod surface; diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 163a53433..38bbb4505 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -58,10 +58,10 @@ pub use assembly::{ }; pub use document::*; pub use eval::{ - EdgeRef, FeatureResult, Model, ModelBody, ModelState, PlacedBodies, RevolveExtent, SolvedSketch, ThreadInfo, curve_pick_error, edge_names_for, - edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names, metric_thread_sizes, object_height, parse_metric_thread, - pattern_matrices, revolve_extent, revolve_extent_with_convention, select_profiles, sketch_hole_direction, sketch_line_plane, state_in_frame, - state_in_frame_at, suggested_thread, through_all_distance, world_state, world_state_reusing, + EdgeRef, FeatureResult, Model, ModelBody, ModelState, PlacedBodies, RevolveExtent, SavedModel, SolvedSketch, ThreadInfo, curve_pick_error, + edge_names_for, edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names, metric_thread_sizes, object_height, + parse_metric_thread, pattern_matrices, revolve_extent, revolve_extent_with_convention, select_profiles, sketch_hole_direction, sketch_line_plane, + state_in_frame, state_in_frame_at, suggested_thread, through_all_distance, world_state, world_state_reusing, }; pub use expr::Expr; pub use names::{BodyName, FeatureName, SketchId}; diff --git a/crates/doc/src/model_cache.rs b/crates/doc/src/model_cache.rs new file mode 100644 index 000000000..fbd49f87b --- /dev/null +++ b/crates/doc/src/model_cache.rs @@ -0,0 +1,424 @@ +//! A model as a design file keeps it: every feature's result and the state after it, so a design +//! opens without evaluating its timeline again (docs/design-container.md, "Model cache"). +//! +//! The records are JSON; the kernel bodies they hold are a separate list ([`SavedModel::bodies`]), +//! which the file stores in SolidCraft's exact native B-rep encoding. A body that several states +//! hold (one that later features pass through unchanged) is recorded once, as are its face names +//! and the solved sketches the states share. Face names are kept as worked out, not as the +//! history they were worked out from: a model taken from a file names every face as the model +//! that was saved did. + +use super::*; +use crate::history_names::{FaceInfo, Names}; +use serde_json::{Value as Json, json}; +use std::collections::HashMap; + +/// A model's results and states as records, and the kernel bodies they refer to by index. +pub struct SavedModel { + pub records: Json, + pub bodies: Vec, +} + +/// Records refer to these at most. +const MAX_ITEMS: usize = 1_000_000; +/// Bodies and sketches all the states hold together, at most (a state is a list of clones). +const MAX_HELD: usize = 50_000_000; + +fn hex(v: u64) -> String { + format!("{v:016x}") +} + +fn unhex(v: &Json) -> Result { + v.as_str().and_then(|s| u64::from_str_radix(s, 16).ok()).ok_or_else(|| bad("saved model: key")) +} + +fn bad(what: &str) -> DocError { + DocError::Invalid(what.into()) +} + +/// A design whose stored face or edge names were saved before format 14 (marked +/// [`crate::naming::LEGACY_MARK`]) finds them through names worked out from geometry on demand, +/// which a saved model does not keep. +fn has_legacy_names(doc: &Document) -> bool { + let mark = format!("\"{}", crate::naming::LEGACY_MARK); + doc.features.iter().any(|f| match &f.kind { + FeatureKind::Import { .. } => f.face_names.iter().any(|n| n.starts_with(crate::naming::LEGACY_MARK)), + _ => serde_json::to_string(f).is_ok_and(|j| j.contains(&mark)), + }) +} + +/// What tells two model bodies apart in a record: a body a feature passes through unchanged is a +/// clone sharing its mesh cell and names, so this finds it without writing its record again. +#[derive(PartialEq, Eq, Hash)] +struct BodyKey { + mesh: usize, + names: usize, + imported: usize, + key: u64, + feature: u64, + component: u64, + transferred: bool, + name: String, + source_name: Option, + source_transform: [u64; 16], +} + +impl BodyKey { + fn of(b: &ModelBody) -> Self { + let mut source_transform = [0; 16]; + for (bits, v) in source_transform.iter_mut().zip(b.source_transform.iter().flatten()) { + *bits = v.to_bits(); + } + BodyKey { + mesh: Arc::as_ptr(&b.mesh) as usize, + names: b.names.id(), + imported: b.imported.as_ref().map_or(0, |l| Arc::as_ptr(l) as usize), + key: b.key, + feature: b.feature, + component: b.component, + transferred: b.transferred, + name: b.name.clone(), + source_name: b.source_name.clone(), + source_transform, + } + } +} + +/// Indices as runs of consecutive ones (`[first, count]`): a state lists mostly the bodies of the +/// state before it, in order. +fn runs(indices: &[usize]) -> Vec<[usize; 2]> { + let mut out: Vec<[usize; 2]> = Vec::new(); + for &i in indices { + match out.last_mut() { + Some([first, count]) if *first + *count == i => *count += 1, + _ => out.push([i, 1]), + } + } + out +} + +#[derive(Default)] +struct Writer { + bodies: Vec, + model_bodies: Vec, + model_body_index: HashMap, + names: Vec, + names_index: HashMap, + sketches: Vec, + sketch_index: HashMap, + states: Vec, + state_index: HashMap, +} + +impl Writer { + fn names(&mut self, b: &ModelBody) -> usize { + let id = b.names.id(); + if let Some(i) = self.names_index.get(&id) { + return *i; + } + let names = crate::naming::names(b); + let info: Vec = names.info.iter().map(|i| json!([i.aliases, i.bounds, i.verified])).collect(); + self.names.push(json!({"faces": *names.faces, "info": info})); + self.names_index.insert(id, self.names.len() - 1); + self.names.len() - 1 + } + + fn model_body(&mut self, b: &ModelBody) -> Option { + if b.body.is_mesh() { + return None; + } + let key = BodyKey::of(b); + if let Some(i) = self.model_body_index.get(&key) { + return Some(*i); + } + let names = self.names(b); + let mut r = json!({ + "name": b.name, "feature": b.feature, "component": b.component, "key": hex(b.key), "names": names, + }); + if let Some(depth) = b.names.depth() { + r["depth"] = json!(depth); + } + if let Some(source) = &b.source_name { + r["source_name"] = json!(source); + } + if b.source_transform != crate::IDENTITY { + r["source_transform"] = json!(b.source_transform); + } + if b.transferred { + r["transferred"] = json!(true); + } + if let Some(look) = &b.imported { + let faces: Vec = look.faces.iter().map(|(name, (color, opacity))| json!([name, color, opacity])).collect(); + r["imported"] = json!({"color": look.color, "opacity": look.opacity, "faces": faces}); + } + r["body"] = json!(self.bodies.len()); + self.bodies.push(b.body.clone()); + self.model_bodies.push(r); + self.model_body_index.insert(key, self.model_bodies.len() - 1); + Some(self.model_bodies.len() - 1) + } + + fn sketch(&mut self, s: &Arc) -> Option { + let id = Arc::as_ptr(s) as usize; + if let Some(i) = self.sketch_index.get(&id) { + return Some(*i); + } + let r = json!({ + "feature": s.feature, "name": s.name, "plane": serde_json::to_value(s.plane).ok()?, + "sketch": serde_json::to_value(&s.sketch).ok()?, "report": serde_json::to_value(&s.report).ok()?, + }); + self.sketches.push(r); + self.sketch_index.insert(id, self.sketches.len() - 1); + Some(self.sketches.len() - 1) + } + + fn state(&mut self, st: &Arc) -> Option { + let id = Arc::as_ptr(st) as usize; + if let Some(i) = self.state_index.get(&id) { + return Some(*i); + } + let bodies = st.bodies.iter().map(|b| self.model_body(b)).collect::>>()?; + let sketches = st.sketches.iter().map(|s| self.sketch(s)).collect::>>()?; + let r = json!({ + "bodies": runs(&bodies), "sketches": runs(&sketches), "body_counter": st.body_counter, + "sheets": serde_json::to_value(&st.sheets).ok()?, "construct": serde_json::to_value(&st.construct).ok()?, + "threads": serde_json::to_value(&st.threads).ok()?, + "sketch_keys": st.sketch_keys.iter().map(|(f, k)| json!([f, hex(*k)])).collect::>(), + "blend_edges": serde_json::to_value(&st.blend_edges).ok()?, "fitted": serde_json::to_value(&st.fitted).ok()?, + "tapered": serde_json::to_value(&st.tapered).ok()?, + }); + self.states.push(r); + self.state_index.insert(id, self.states.len() - 1); + Some(self.states.len() - 1) + } +} + +impl Model { + /// The model as a design file keeps it: `None` unless it is `doc`'s evaluation without an + /// error, holds no mesh bodies, and `doc` keeps no names saved before format 14. Works out + /// the face names not asked for yet (a saved model keeps them as worked out). + pub fn saved(&self, doc: &Document) -> Option { + if self.results.is_empty() || self.results.iter().any(|r| r.error.is_some()) || !self.is_current(doc) || has_legacy_names(doc) { + return None; + } + kernel::guard("save the model", || { + let mut w = Writer::default(); + let mut features = Vec::with_capacity(self.results.len()); + for r in &self.results { + let state = w.state(&r.state).ok_or_else(|| kernel::KernelError::Invalid("not kept".into()))?; + let mut f = json!({"id": r.id, "fingerprint": hex(r.fingerprint), "ms": r.ms, "skipped": r.skipped, "state": state}); + if let Some(w) = &r.warning { + f["warning"] = json!(w); + } + if r.boolean_diagnostics != kernel::BooleanDiagnostics::default() { + f["diagnostics"] = serde_json::to_value(&r.boolean_diagnostics).map_err(|e| kernel::KernelError::Invalid(e.to_string()))?; + } + features.push(f); + } + let records = json!({ + "features": features, "states": w.states, "model_bodies": w.model_bodies, "names": w.names, "sketches": w.sketches, + }); + Ok(SavedModel { records, bodies: w.bodies }) + }) + .ok() + } +} + +impl SavedModel { + /// The states the records hold, every record checked. + fn states(&self) -> Result>> { + let (records, bodies) = (&self.records, &self.bodies); + let list = |key: &str| records.get(key).and_then(Json::as_array).filter(|l| l.len() <= MAX_ITEMS).ok_or_else(|| bad("saved model: list")); + let index = |v: Option<&Json>, len: usize| { + v.and_then(Json::as_u64).and_then(|i| usize::try_from(i).ok()).filter(|i| *i < len).ok_or_else(|| bad("saved model: index")) + }; + let text = + |v: Option<&Json>| v.and_then(Json::as_str).filter(|s| s.len() <= 1 << 16).map(str::to_owned).ok_or_else(|| bad("saved model: text")); + let parse = |v: Option<&Json>| v.cloned().ok_or_else(|| bad("saved model: missing")); + let mut names = Vec::new(); + for n in list("names")? { + let faces: Vec = serde_json::from_value(parse(n.get("faces"))?).map_err(|_| bad("saved model: names"))?; + let info: Vec<(Vec, std::collections::BTreeSet, bool)> = + serde_json::from_value(parse(n.get("info"))?).map_err(|_| bad("saved model: names"))?; + if info.len() != faces.len() { + return Err(bad("saved model: names")); + } + let info = info.into_iter().map(|(aliases, bounds, verified)| FaceInfo { aliases, bounds, verified }).collect(); + names.push(Arc::new(Names { faces: Arc::new(faces), info })); + } + let mut sketches = Vec::new(); + for s in list("sketches")? { + let sketch: solidcraft_sketch::Sketch = serde_json::from_value(parse(s.get("sketch"))?).map_err(|_| bad("saved model: sketch"))?; + sketches.push(Arc::new(SolvedSketch { + feature: s.get("feature").and_then(Json::as_u64).ok_or_else(|| bad("saved model: sketch"))?, + name: text(s.get("name"))?, + plane: serde_json::from_value(parse(s.get("plane"))?).map_err(|_| bad("saved model: sketch"))?, + report: serde_json::from_value(parse(s.get("report"))?).map_err(|_| bad("saved model: sketch"))?, + profiles: find_profiles(&sketch), + ends: solidcraft_sketch::loose_ends(&sketch), + sketch, + })); + } + let mut model_bodies = Vec::new(); + for r in list("model_bodies")? { + let body = bodies.get(index(r.get("body"), bodies.len())?).cloned().ok_or_else(|| bad("saved model: body"))?; + let mut b = + ModelBody::new(text(r.get("name"))?, body, r.get("feature").and_then(Json::as_u64).ok_or_else(|| bad("saved model: feature"))?); + b.component = r.get("component").and_then(Json::as_u64).ok_or_else(|| bad("saved model: component"))?; + b.key = unhex(r.get("key").unwrap_or(&Json::Null))?; + let depth = + r.get("depth").map(|d| d.as_u64().and_then(|d| usize::try_from(d).ok()).ok_or_else(|| bad("saved model: depth"))).transpose()?; + b.names = crate::naming::NameCell::saved( + names.get(index(r.get("names"), names.len())?).cloned().ok_or_else(|| bad("saved model: names"))?, + depth, + ); + b.source_name = r.get("source_name").map(|s| text(Some(s))).transpose()?; + if let Some(m) = r.get("source_transform") { + let m: crate::Mat = serde_json::from_value(m.clone()).map_err(|_| bad("saved model: transform"))?; + if m.iter().flatten().any(|x| !x.is_finite()) { + return Err(bad("saved model: transform")); + } + b.source_transform = m; + } + b.transferred = r.get("transferred").and_then(Json::as_bool).unwrap_or(false); + // Measured once here, so every state holding it adds it up for the cache's budget. + b.bytes = b.body.retained_bytes(); + if let Some(look) = r.get("imported") { + let faces: Vec<(String, [f32; 3], f32)> = serde_json::from_value(parse(look.get("faces"))?).map_err(|_| bad("saved model: look"))?; + b.imported = Some(Arc::new(crate::appearance::ImportedLook { + color: serde_json::from_value(parse(look.get("color"))?).map_err(|_| bad("saved model: look"))?, + opacity: serde_json::from_value(parse(look.get("opacity"))?).map_err(|_| bad("saved model: look"))?, + faces: faces.into_iter().map(|(name, color, opacity)| (name, (color, opacity))).collect(), + })); + } + model_bodies.push(b); + } + let mut states = Vec::new(); + let mut held = 0usize; + for s in list("states")? { + // Runs of consecutive indices, each within the list it indexes. + let ids = |key: &str, len: usize| -> Result> { + let mut out = Vec::new(); + for run in s.get(key).and_then(Json::as_array).ok_or_else(|| bad("saved model: state"))? { + let first = index(run.get(0), len)?; + let count = run.get(1).and_then(Json::as_u64).and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad("saved model: run"))?; + if first.checked_add(count).is_none_or(|end| end > len) || out.len().saturating_add(count) > MAX_ITEMS { + return Err(bad("saved model: run")); + } + out.extend(first..first + count); + } + Ok(out) + }; + let field = |key: &str| parse(s.get(key)); + let invalid = |_| bad("saved model: state"); + let mut sketch_keys = BTreeMap::new(); + for k in s.get("sketch_keys").and_then(Json::as_array).ok_or_else(|| bad("saved model: state"))? { + sketch_keys + .insert(k.get(0).and_then(Json::as_u64).ok_or_else(|| bad("saved model: state"))?, unhex(k.get(1).unwrap_or(&Json::Null))?); + } + let st = ModelState { + bodies: ids("bodies", model_bodies.len())?.into_iter().filter_map(|i| model_bodies.get(i).cloned()).collect(), + sketches: ids("sketches", sketches.len())?.into_iter().filter_map(|i| sketches.get(i).cloned()).collect(), + body_counter: index(s.get("body_counter"), usize::MAX)?, + sheets: serde_json::from_value(field("sheets")?).map_err(invalid)?, + construct: serde_json::from_value(field("construct")?).map_err(invalid)?, + threads: serde_json::from_value(field("threads")?).map_err(invalid)?, + sketch_keys, + blend_edges: serde_json::from_value(field("blend_edges")?).map_err(invalid)?, + fitted: serde_json::from_value(field("fitted")?).map_err(invalid)?, + tapered: serde_json::from_value(field("tapered")?).map_err(invalid)?, + }; + held = held.saturating_add(st.bodies.len()).saturating_add(st.sketches.len()); + if held > MAX_HELD { + return Err(bad("saved model: states")); + } + states.push(Arc::new(st)); + } + Ok(states) + } + + /// The model's final state (what a picture of it shows), without checking that it is a + /// document's evaluation. + pub fn final_state(&self) -> Result> { + let states = self.states()?; + let features = self.records.get("features").and_then(Json::as_array).ok_or_else(|| bad("saved model: features"))?; + let last = features.iter().rev().find(|f| f.get("skipped").and_then(Json::as_bool) == Some(false)); + match last { + Some(f) => f + .get("state") + .and_then(Json::as_u64) + .and_then(|i| states.get(usize::try_from(i).ok()?)) + .cloned() + .ok_or_else(|| bad("saved model: state")), + None => Ok(Arc::new(ModelState::default())), + } + } +} + +impl Model { + /// The model a design file kept for `doc` ([`Model::saved`]), taken as `doc`'s evaluation: + /// every feature's result as saved, nothing evaluated. Refused (an error) unless every + /// feature's fingerprint is the one `doc` gives it now, and every record is well formed. + pub fn adopt(doc: &Document, saved: &SavedModel) -> Result { + let states = saved.states()?; + let records = &saved.records; + let index = |v: Option<&Json>, len: usize| { + v.and_then(Json::as_u64).and_then(|i| usize::try_from(i).ok()).filter(|i| *i < len).ok_or_else(|| bad("saved model: index")) + }; + let text = + |v: Option<&Json>| v.and_then(Json::as_str).filter(|s| s.len() <= 1 << 16).map(str::to_owned).ok_or_else(|| bad("saved model: text")); + let features = records.get("features").and_then(Json::as_array).ok_or_else(|| bad("saved model: features"))?; + if features.len() != doc.features.len() { + return Err(bad("saved model: features")); + } + let (vals, param_errors) = evaluation_values(doc); + let step_digests = StepDigests::of(doc, &StepDigests::default()); + let marker = doc.marker.unwrap_or(usize::MAX); + let ctx = context_digest(doc, &vals); + let mut cache = EvalCache::default(); + let mut before = Arc::new(ModelState::default()); + let mut prev = 0; + let mut results = Vec::with_capacity(features.len()); + for (i, (f, r)) in doc.features.iter().zip(features).enumerate() { + prev = chain_fingerprint(doc, &vals, f, prev, i >= marker, &step_digests); + if r.get("id").and_then(Json::as_u64) != Some(f.id) || unhex(r.get("fingerprint").unwrap_or(&Json::Null))? != prev { + return Err(bad("saved model: the document changed")); + } + let ms = r.get("ms").and_then(Json::as_f64).filter(|ms| ms.is_finite()).ok_or_else(|| bad("saved model: time"))?; + let result = FeatureResult { + id: f.id, + name: f.name.clone(), + error: None, + warning: r.get("warning").map(|w| text(Some(w))).transpose()?, + boolean_diagnostics: match r.get("diagnostics") { + Some(d) => serde_json::from_value(d.clone()).map_err(|_| bad("saved model: diagnostics"))?, + None => Default::default(), + }, + ms, + skipped: r.get("skipped").and_then(Json::as_bool).ok_or_else(|| bad("saved model: skipped"))?, + stale: false, + fingerprint: prev, + state: states.get(index(r.get("state"), states.len())?).cloned().ok_or_else(|| bad("saved model: state"))?, + }; + // Each result where an evaluation would have put it, so an edit undone (or set back) + // finds it again rather than evaluating the feature anew. + if !result.skipped { + let local = fingerprint(0, f, &vals, false, &step_digests) ^ placement_digest(doc, f); + cache.put( + cache_key(f, prev, local, ctx, &before), + CachedEval { + error: None, + warning: result.warning.clone(), + boolean_diagnostics: result.boolean_diagnostics.clone(), + ms, + bytes: result.state.retained_bytes(), + state: result.state.clone(), + }, + ); + before = result.state.clone(); + } + results.push(result); + } + Ok(Model { results, param_errors, step_digests, cache: Arc::new(std::sync::Mutex::new(cache)), ..Model::default() }) + } +} diff --git a/crates/doc/src/naming.rs b/crates/doc/src/naming.rs index 263b4bb6b..71d32e6ee 100644 --- a/crates/doc/src/naming.rs +++ b/crates/doc/src/naming.rs @@ -46,6 +46,9 @@ pub struct NameCell { legacy: Arc>>>, /// The body this one is a moved copy of (its legacy names are that body's). copy_of: Option>, + /// How deep the chain of features that named it is, for names taken from a saved model + /// (which has no origin): see [`NameCell::depth`]. + saved_depth: Option, } impl NameCell { @@ -69,6 +72,19 @@ impl NameCell { pub fn same(body: &ModelBody) -> Self { NameCell { copy_of: Some(Arc::new(body.clone())), ..NameCell::default() } } + /// Names a saved model kept (worked out when it was saved), at `depth` in the chain of + /// features that named them. + pub(crate) fn saved(names: Arc, depth: Option) -> Self { + NameCell { saved_depth: depth, ..Self::shared(names) } + } + /// How deep the chain of features that named the body is (`None`: not made by a feature). + pub(crate) fn depth(&self) -> Option { + self.origin.as_ref().map(|o| o.depth).or(self.saved_depth) + } + /// Identity of the names: clones of a cell share them. + pub(crate) fn id(&self) -> usize { + Arc::as_ptr(&self.names) as usize + } fn shared(names: Arc) -> Self { let cell = OnceLock::new(); let _ = cell.set(names); diff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rs index b4bfd40af..130e26547 100644 --- a/crates/doc/src/sheet.rs +++ b/crates/doc/src/sheet.rs @@ -316,7 +316,7 @@ impl SheetSettings { /// The shape of the relief cut where two bends meet at a corner of the base (a rule's /// `corner_relief_shape`). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ReliefShape { /// Nothing is cut: the bends end square at the corner. @@ -418,7 +418,7 @@ impl Document { } /// A flange: a bend along a panel edge and the flat panel past it (flat coordinates). -#[derive(Clone, Debug, PartialEq, Serialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SheetFlange { /// The flange it hangs off (None = the base panel). pub parent: Option, @@ -469,7 +469,7 @@ pub struct EdgeFlange { } /// A sheet metal body (see the module docs). -#[derive(Clone, Debug, PartialEq, Serialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SheetBody { pub body: String, pub rule: String, @@ -483,21 +483,21 @@ pub struct SheetBody { pub holes: Vec, /// Planar machining in flat coordinates, with depths measured from the flat bottom. /// Derived from feature history; these records are not a document schema change. - #[serde(skip_serializing_if = "Vec::is_empty")] + #[serde(default, skip_serializing_if = "Vec::is_empty")] pub pockets: Vec, /// Straight bores drilled into a panel along its plane (a hole into a rim), in flat /// coordinates, each kept inside its own panel's material so the folded part and its flat /// pattern both carry it (#560). Derived from feature history, like `pockets`. - #[serde(skip_serializing_if = "Vec::is_empty")] + #[serde(default, skip_serializing_if = "Vec::is_empty")] pub bores: Vec, /// Perforation fields (#732), flat coordinates; their holes are computed on demand and never cut into the B-rep. - #[serde(skip_serializing_if = "Vec::is_empty")] + #[serde(default, skip_serializing_if = "Vec::is_empty")] pub perforations: Vec, /// Regions (flat coordinates) that text cut or machined, letters with their counters as /// holes: a record of where the sheet's text went, so that its DXF can write the letters on /// layers of their own (see [`SheetBody::letters`]). The cut-outs and pockets themselves are /// in `holes` and `pockets`. Derived from feature history, like `pockets`. - #[serde(skip_serializing_if = "Vec::is_empty")] + #[serde(default, skip_serializing_if = "Vec::is_empty")] pub labels: Vec, /// Unfolded. pub flat: bool, @@ -524,7 +524,7 @@ pub struct SheetBody { /// A straight round bore of one panel (None = the base), in flat coordinates: a cylinder from /// `base` along the unit `axis` for `height`, cut only from that panel's material. -#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] pub struct SheetBore { pub panel: Option, pub base: Vec3, @@ -534,7 +534,7 @@ pub struct SheetBore { } /// A perforation field from a `sheet.perforate` feature (#732). -#[derive(Clone, Debug, PartialEq, Serialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SheetPerforation { pub feature: u64, pub diameter: f64, @@ -543,7 +543,7 @@ pub struct SheetPerforation { pub square: bool, } -#[derive(Clone, Debug, PartialEq, Serialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SheetPocket { pub region: Region2, pub z0: f64, diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 100c6435b..73d3daa66 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -267,11 +267,11 @@ fn open(s: &mut Session, p: &Value) -> Result { } return Ok(out); } - let mut doc = solidcraft_io::read_design_file(path, s.open_preview.take()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + let (mut doc, saved) = solidcraft_io::read_design_file(path, s.open_preview.take()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; if let Some(stem) = default_name_for(&doc.name, path) { doc.name = stem; } - s.replace_design(Session::new(doc)); + s.replace_design(Session::opened(doc, saved.as_ref())); s.path = Some(path.to_string()); let errors = s.model.results.iter().filter(|r| r.error.is_some()).count(); Ok(json!({"path": path, "features": s.doc.features.len(), "errors": errors, "name": s.doc.name})) @@ -405,17 +405,17 @@ impl Session { let geometry = cache.then(|| saved_geometry(self, &design)).flatten(); let preview = preview.then(|| saved_preview(self)).flatten(); let thumbnail = cache.then(|| thumbnail::saved(self)).flatten(); - solidcraft_io::write_design_container_with_thumbnail(&design, compression, preview.as_ref(), geometry.as_deref(), thumbnail.as_deref()) + solidcraft_io::write_design_container_with_thumbnail(&design, compression, preview.as_ref(), geometry.as_ref(), thumbnail.as_deref()) } } /// The evaluated model a save keeps, so opening need not rebuild it: only the finished evaluation /// of `design`, the document saved (no sketch being edited, no uncaptured moves, no feature errors). -fn saved_geometry(s: &Session, design: &Document) -> Option> { - if s.active_sketch.is_some() || !s.pending_moves.is_empty() || s.model.results.iter().any(|r| r.error.is_some()) || !s.model.is_current(design) { +fn saved_geometry(s: &Session, design: &Document) -> Option { + if s.active_sketch.is_some() || !s.pending_moves.is_empty() || s.model.state().bodies.is_empty() { return None; } - Some(s.model.state()).filter(|st| !st.bodies.is_empty()) + s.model.saved(design) } /// Cache only warm display geometry. A save never waits for an unevaluated mesh. @@ -849,36 +849,37 @@ mod tests { } #[test] - fn native_cache_does_not_force_meshes_or_supply_editing_state() { - let mut session = Session::new(Document::new("Native cache authority")); + fn saved_model_needs_no_meshes_and_is_adopted_only_for_its_document() { + let mut session = Session::new(Document::new("Saved model")); session.execute("solid.box", &json!({"length":10,"width":20,"height":30})).unwrap(); let world = session.world_state(); assert!(world.bodies.iter().all(|b| b.cached_mesh().is_none())); - let mut cached = (*saved_geometry(&session, &session.doc).unwrap()).clone(); let bytes = session.design_container(solidcraft_io::DesignCompression::Fast, false, true).unwrap(); - assert!(world.bodies.iter().all(|b| b.cached_mesh().is_none()), "saving native geometry must not triangulate"); + assert!(world.bodies.iter().all(|b| b.cached_mesh().is_none()), "saving the model must not triangulate"); assert!(solidcraft_io::read_design_geometry(&bytes).is_some()); assert!( solidcraft_io::read_design_geometry(&session.design_container(solidcraft_io::DesignCompression::Fast, false, false).unwrap()).is_none() ); - cached.bodies[0].body = solidcraft_kernel::box_solid(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::new(100., 100., 100.)).unwrap(); - let bytes = - solidcraft_io::write_design_container_with_cache(&session.doc, solidcraft_io::DesignCompression::Fast, None, Some(&cached)).unwrap(); - let path = std::env::temp_dir().join(format!("solidcraft-native-forged-{}.solidcraft", std::process::id())); - std::fs::write(&path, bytes).unwrap(); - let seen = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let callback_seen = seen.clone(); - let mut reopened = Session { - open_preview: Some(Box::new(move |p| { - callback_seen.store(!p.meshes.is_empty(), std::sync::atomic::Ordering::Relaxed); - })), - ..Session::default() - }; + let path = std::env::temp_dir().join(format!("solidcraft-saved-model-{}.solidcraft", std::process::id())); + std::fs::write(&path, &bytes).unwrap(); + let mut reopened = Session::default(); reopened.execute("doc.open", &json!({"path":path})).unwrap(); - assert!(seen.load(std::sync::atomic::Ordering::Relaxed)); assert_eq!(reopened.doc, session.doc); + assert!(reopened.model.results.iter().all(|r| r.ms == session.model.results[0].ms), "taken from the file, not evaluated"); let measured = reopened.execute("inspect.measure", &json!({})).unwrap(); assert!((measured["bodies"][0]["volume_mm3"].as_f64().unwrap() - 6000.).abs() < 1e-6); + // The model of another document (a value edited in the file) is not taken: the design is + // evaluated. + let mut changed = (*session.doc).clone(); + if let Some(solidcraft_doc::FeatureKind::Box { length, .. }) = changed.features.last_mut().map(|f| &mut f.kind) { + *length = "20".into(); + } + let saved = saved_geometry(&session, &session.doc).unwrap(); + let other = solidcraft_io::write_design_container_with_cache(&changed, solidcraft_io::DesignCompression::Fast, None, Some(&saved)).unwrap(); + std::fs::write(&path, other).unwrap(); + reopened.execute("doc.open", &json!({"path":path})).unwrap(); + let measured = reopened.execute("inspect.measure", &json!({})).unwrap(); + assert!((measured["bodies"][0]["volume_mm3"].as_f64().unwrap() - 12000.).abs() < 1e-6); std::fs::remove_file(path).unwrap(); } @@ -1061,7 +1062,8 @@ mod tests { for x in [0, 20, 40] { s.execute("solid.box", &json!({"length":10,"width":10,"height":10,"corner":[x,0,0]})).unwrap(); } - s.execute("file.save", &json!({"path":path})).unwrap(); + // Without its model: the timeline is evaluated (and watched) as it opens. + s.execute("file.save", &json!({"path":path, "cache": false})).unwrap(); let progress = Arc::new(Progress::default()); let mut opened = Session::default(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a11fba4af..e34aeb615 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -359,12 +359,25 @@ impl Default for Session { } impl Session { - pub fn new(mut doc: Document) -> Self { + pub fn new(doc: Document) -> Self { + Self::opened(doc, None) + } + + /// A session on `doc` whose evaluation is the model its file kept (`saved`), when that is + /// `doc`'s evaluation ([`Model::adopt`]); otherwise the timeline is evaluated. + /// `SOLIDCRAFT_NO_MODEL_CACHE` set always evaluates. + pub fn opened(mut doc: Document, saved: Option<&solidcraft_doc::SavedModel>) -> Self { // The session keeps what is hidden (not an undo step); the design file carries it. let visibility = std::mem::take(&mut doc.visibility); let doc = Arc::new(doc); - let mut model = Model::new(); - model.evaluate(&doc); + let adopted = saved + .filter(|_| solidcraft_geom::env::var_os("NO_MODEL_CACHE").is_none()) + .and_then(|saved| Model::adopt(&doc, saved).map_err(|e| log::info!("the saved model is not used: {e}")).ok()); + let model = adopted.unwrap_or_else(|| { + let mut model = Model::new(); + model.evaluate(&doc); + model + }); Session { saved: doc.clone(), doc, diff --git a/crates/io/src/design.rs b/crates/io/src/design.rs index 50a457fe2..510d800d7 100644 --- a/crates/io/src/design.rs +++ b/crates/io/src/design.rs @@ -113,7 +113,7 @@ pub fn write_design_container_with_cache( doc: &Document, compression: DesignCompression, preview: Option<&DesignPreview>, - geometry: Option<&solidcraft_doc::ModelState>, + geometry: Option<&solidcraft_doc::SavedModel>, ) -> Result> { write_design_container_with_thumbnail(doc, compression, preview, geometry, None) } @@ -124,7 +124,7 @@ pub fn write_design_container_with_thumbnail( doc: &Document, compression: DesignCompression, preview: Option<&DesignPreview>, - geometry: Option<&solidcraft_doc::ModelState>, + geometry: Option<&solidcraft_doc::SavedModel>, thumbnail: Option<&[u8]>, ) -> Result> { write_container(doc, compression, preview, geometry, thumbnail, MAX_DESIGN_BYTES) @@ -136,7 +136,7 @@ fn write_container( doc: &Document, compression: DesignCompression, preview: Option<&DesignPreview>, - geometry: Option<&solidcraft_doc::ModelState>, + geometry: Option<&solidcraft_doc::SavedModel>, thumbnail: Option<&[u8]>, budget: usize, ) -> Result> { @@ -510,7 +510,7 @@ impl DesignContainerReader { // fallback, generating a bounded provisional mesh without source imports. read_preview(&mut self.reader).ok().or_else(|| { let document = self.reader.document(16 << 20).ok()?; - native_cache::geometry_preview(&document, self.geometry()?).ok() + native_cache::geometry_preview(&document, &self.geometry()?).ok() }) } @@ -519,8 +519,8 @@ impl DesignContainerReader { thumbnail::read(&mut self.reader).ok() } - /// The cached model state, when this build wrote it for exactly this document. - pub fn geometry(&mut self) -> Option { + /// The saved model, when this build wrote it for exactly this document. + pub fn geometry(&mut self) -> Option { let document = self.reader.document(16 << 20).ok()?; native_cache::read_geometry_with(&mut self.reader, &document).ok() } @@ -536,9 +536,11 @@ pub(super) fn read(bytes: &[u8]) -> Result { } /// Open from disk (or browser VFS), publishing only provisional display before -/// authoritative blob hydration. Desktop keeps one seekable file handle instead -/// of buffering the complete archive. JSON continues through the normal migrations. -pub fn read_design_file(path: &str, notify: Option) -> Result { +/// authoritative blob hydration, with the model the file keeps when this build saved it for +/// exactly this document ([`solidcraft_doc::Model::adopt`] takes it as the evaluation). Desktop +/// keeps one seekable file handle instead of buffering the complete archive. JSON continues +/// through the normal migrations. +pub fn read_design_file(path: &str, notify: Option) -> Result<(Document, Option)> { #[cfg(not(target_arch = "wasm32"))] let mut source = { crate::vfs::check(path).map_err(invalid)?; @@ -569,16 +571,19 @@ pub fn read_design_file(path: &str, notify: Option) source.seek(SeekFrom::Start(0)).map_err(invalid)?; if is_design_container(&prefix) { let mut reader = DesignContainerReader::new(source)?; + // A design with its model opens without a picture first: the model is the session. + let model = reader.geometry(); if let Some(notify) = notify - && let Some(preview) = reader.preview() + && model.is_none() + && let Ok(preview) = read_preview(&mut reader.reader) { notify(preview); } - reader.read_document() + Ok((reader.read_document()?, model)) } else { let mut bytes = Vec::new(); source.take(MAX_DESIGN_BYTES as u64 + 1).read_to_end(&mut bytes).map_err(invalid)?; - crate::read_design(&bytes) + Ok((crate::read_design(&bytes)?, None)) } } @@ -717,15 +722,31 @@ mod tests { #[test] fn file_reader_refuses_nonfiles_before_notifying_preview() { let directory = std::env::temp_dir(); - let result = read_design_file(directory.to_str().unwrap(), Some(|_| panic!("non-file supplied a preview"))); + let result = read_design_file(directory.to_str().unwrap(), Some(|_| panic!("non-file supplied a preview"))).map(|(doc, _)| doc); assert!(result.is_err_and(|e| e.to_string().contains("not a regular file"))); } - fn native_geometry() -> solidcraft_doc::ModelState { - let cube = solidcraft_kernel::box_solid(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::new(10., 20., 30.)).unwrap(); - let mut state = solidcraft_doc::ModelState::default(); - state.bodies.push(solidcraft_doc::ModelBody::new("Cube".into(), cube, 1)); - state + /// A saved model of one state holding `bodies` (no document evaluated it: enough for the + /// container, which stores whatever model it is given). + fn saved_model(bodies: Vec) -> solidcraft_doc::SavedModel { + let records: Vec = (0..bodies.len()) + .map(|i| json!({"name": format!("Body{i}"), "feature": 1, "component": 0, "key": "0000000000000001", "names": 0, "body": i})) + .collect(); + let state = json!({ + "bodies": [[0, bodies.len()]], "sketches": [], "body_counter": 7, "sheets": [], "construct": [], "threads": [], + "sketch_keys": [], "blend_edges": {}, "fitted": {}, "tapered": {}, + }); + solidcraft_doc::SavedModel { + records: json!({ + "features": [{"id": 1, "fingerprint": "0000000000000000", "ms": 0.0, "skipped": false, "state": 0}], + "states": [state], "model_bodies": records, "names": [{"faces": [], "info": []}], "sketches": [], + }), + bodies, + } + } + + fn native_geometry() -> solidcraft_doc::SavedModel { + saved_model(vec![solidcraft_kernel::box_solid(solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::new(10., 20., 30.)).unwrap()]) } #[test] @@ -739,7 +760,7 @@ mod tests { let entries = parts(&bytes); assert!(entries.contains_key("cache/bodies.bin")); assert!(!entries.contains_key("cache/preview.bin")); - assert_eq!(read_design_geometry(&bytes).unwrap().bodies[0].body.face_count(), bodies.bodies[0].body.face_count()); + assert_eq!(read_design_geometry(&bytes).unwrap().bodies[0].body.face_count(), bodies.bodies[0].face_count()); assert_eq!(bytes, write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&bodies)).unwrap()); let count = std::rc::Rc::new(std::cell::Cell::new(0)); let mut reader = DesignContainerReader::new(CountingReader { source: Cursor::new(bytes), count: count.clone() }).unwrap(); @@ -754,34 +775,26 @@ mod tests { use solidcraft_geom::Vec3; let part = solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(10., 20., 30.)).unwrap(); let share = solidcraft_kernel::DisplayShare::new(part.clone()); - let t = [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [50., 0., 0., 1.]]; - let mut state = solidcraft_doc::ModelState::default(); - state.body_counter = 7; - for (i, body) in [part.clone(), part.clone()].into_iter().enumerate() { - state.bodies.push(solidcraft_doc::ModelBody::new(format!("Part {i}"), body, 1)); - } + let mut bodies = vec![part.clone(), part.clone()]; for x in [50., 90.] { let moved = solidcraft_kernel::transform(&part, Vec3::new(x, 0., 0.), Vec3::ZERO, Vec3::Z, 0.).unwrap(); - let mut t = t; - t[3][0] = x; - let mut b = solidcraft_doc::ModelBody::new(format!("Copy {x}"), moved.with_display_share(&share, t), 2); - b.component = 3; - b.source_name = Some("Part".into()); - state.bodies.push(b); + let t = [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [x, 0., 0., 1.]]; + bodies.push(moved.with_display_share(&share, t)); } + let model = saved_model(bodies); let doc = document(); - let bytes = write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&state)).unwrap(); + let bytes = write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&model)).unwrap(); let manifest: Value = serde_json::from_slice(&parts(&bytes)["cache/model.json"]).unwrap(); - assert_eq!(manifest["bodies"].as_array().unwrap().len(), 3, "the part and each placed copy, once each"); - let read = read_design_geometry(&bytes).unwrap(); - assert_eq!(read.body_counter, 7); - assert_eq!(read.bodies.iter().map(|b| b.name.as_str()).collect::>(), ["Part 0", "Part 1", "Copy 50", "Copy 90"]); - let copies: Vec<_> = read.bodies[2..].iter().map(|b| b.body.display_share().unwrap()).collect(); + assert_eq!(manifest["slices"].as_array().unwrap().len(), 3, "the part and each placed copy, once each"); + let read = DesignContainerReader::new(Cursor::new(&bytes)).unwrap().geometry().unwrap(); + assert_eq!(read.records, model.records); + assert_eq!(read_design_geometry(&bytes).unwrap().body_counter, 7); + let copies: Vec<_> = read.bodies[2..].iter().map(|b| b.display_share().unwrap()).collect(); assert_eq!(copies[0].0.id(), copies[1].0.id(), "copies show one display again"); assert_eq!(copies[1].1[3][0], 90.); - assert_eq!((read.bodies[3].component, read.bodies[3].source_name.as_deref(), read.bodies[3].feature), (3, Some("Part"), 2)); - for (a, b) in state.bodies.iter().zip(&read.bodies) { - assert_eq!(solidcraft_kernel::encode_native_body(&a.body).unwrap(), solidcraft_kernel::encode_native_body(&b.body).unwrap()); + assert!(read.bodies[0].display_share().is_none()); + for (a, b) in model.bodies.iter().zip(&read.bodies) { + assert_eq!(solidcraft_kernel::encode_native_body(a).unwrap(), solidcraft_kernel::encode_native_body(b).unwrap()); } } diff --git a/crates/io/src/design/native_cache.rs b/crates/io/src/design/native_cache.rs index 3450e7c1a..7005349f0 100644 --- a/crates/io/src/design/native_cache.rs +++ b/crates/io/src/design/native_cache.rs @@ -1,10 +1,11 @@ -//! The model cache: the evaluated bodies of a design's timeline, saved with it so opening need -//! not rebuild them. Its SolidCraft schema is independent of the producing kernel; its key ties it -//! to the exact document, build and platform that computed it (docs/design-container.md). +//! The model cache: a design's evaluated timeline (every feature's result and the state after +//! it, [`SavedModel`]), saved with it so opening need not evaluate it again. Bodies use +//! SolidCraft's exact native B-rep encoding; the key ties the cache to the exact document, build +//! and platform that computed it (docs/design-container.md). use super::*; -use solidcraft_doc::{ModelBody, ModelState}; +use solidcraft_doc::{ModelState, SavedModel}; -const FORMAT: &str = "solidcraft-model-cache/1"; +const FORMAT: &str = "solidcraft-model-cache/2"; const PRODUCER: &str = "solidcraft-truck-adapter/3"; const MANIFEST: &str = "cache/model.json"; const PAYLOAD: &str = "cache/bodies.bin"; @@ -25,53 +26,25 @@ fn matrix(t: &[[f64; 4]; 4]) -> Vec { t.iter().flatten().copied().collect() } -fn look(look: &solidcraft_doc::appearance::ImportedLook) -> Value { - let faces: Vec = look.faces.iter().map(|(name, (color, opacity))| json!([name, color, opacity])).collect(); - json!({"color": look.color, "opacity": look.opacity, "faces": faces}) -} - -fn load_look(v: &Value) -> Result { - let unit = |x: f32| x.is_finite() && (0.0..=1.0).contains(&x); - let color = |v: &Value| -> Result> { - let c: Option<[f32; 3]> = serde_json::from_value(v.clone()).map_err(invalid)?; - if c.is_some_and(|c| !c.iter().copied().all(unit)) { - return Err(invalid("cached colour")); - } - Ok(c) - }; - let opacity: Option = serde_json::from_value(v.get("opacity").cloned().unwrap_or(Value::Null)).map_err(invalid)?; - if opacity.is_some_and(|o| !unit(o)) { - return Err(invalid("cached opacity")); - } - let mut faces = BTreeMap::new(); - for f in v.get("faces").and_then(Value::as_array).ok_or_else(|| invalid("cached face looks"))? { - let name = f.get(0).and_then(Value::as_str).filter(|n| n.len() <= 1024).ok_or_else(|| invalid("cached face name"))?; - let c = color(f.get(1).unwrap_or(&Value::Null))?.ok_or_else(|| invalid("cached face colour"))?; - let o = f.get(2).and_then(Value::as_f64).map(|o| o as f32).filter(|o| unit(*o)).ok_or_else(|| invalid("cached face opacity"))?; - faces.insert(name.to_owned(), (c, o)); - } - Ok(solidcraft_doc::appearance::ImportedLook { color: color(v.get("color").unwrap_or(&Value::Null))?, opacity, faces }) -} - -/// Encode a model state's bodies. Identical bodies (the same part placed many times, a body a -/// feature passed through) are stored once; a placed copy of a part records the part and its -/// matrix, so it shows that part's display as it did before saving. -pub(super) fn encode_model(state: &ModelState, document: &[u8]) -> Result<(Vec, Vec)> { - if state.bodies.is_empty() || state.bodies.len() > MAX_RECORDS { +/// Encode a saved model. Identical bodies (the same part placed many times) are stored once; a +/// placed copy of a part records the part and its matrix, so it shows that part's display as it +/// did before saving. +pub(super) fn encode_model(model: &SavedModel, document: &[u8]) -> Result<(Vec, Vec)> { + if model.bodies.is_empty() || model.bodies.len() > MAX_RECORDS { return Err(invalid("cached body count")); } // What to encode: every body, and the part every placed copy shows. let mut shares: Vec = Vec::new(); let mut share_index = std::collections::HashMap::new(); - for b in &state.bodies { - if let Some((share, _)) = b.body.display_share() { + for b in &model.bodies { + if let Some((share, _)) = b.display_share() { share_index.entry(share.id()).or_insert_with(|| { shares.push(share.clone()); shares.len() - 1 }); } } - let bodies: Vec<&solidcraft_kernel::Body> = state.bodies.iter().map(|b| &b.body).chain(shares.iter().map(|s| s.original())).collect(); + let bodies: Vec<&solidcraft_kernel::Body> = model.bodies.iter().chain(shares.iter().map(|s| s.original())).collect(); let encoded = solidcraft_kernel::map_on_threads(&bodies, 16, |b| solidcraft_kernel::encode_native_body(b).ok()); let mut data = Vec::new(); let mut slices = Vec::new(); @@ -90,35 +63,18 @@ pub(super) fn encode_model(state: &ModelState, document: &[u8]) -> Result<(Vec 1024 { - return Err(invalid("cached body name")); - } - let mut r = json!({"name": b.name, "body": i, "feature": b.feature, "component": b.component}); - if let Some(source) = &b.source_name { - r["source_name"] = json!(source); - } - if b.source_transform != solidcraft_doc::IDENTITY { - r["source_transform"] = json!(matrix(&b.source_transform)); - } - if b.transferred { - r["transferred"] = json!(true); - } - if let Some(l) = &b.imported { - r["imported"] = look(l); - } - if let Some((share, t)) = b.body.display_share() { - let s = share_index.get(&share.id()).ok_or_else(|| invalid("display share"))?; - r["share"] = json!([s, matrix(&t)]); - } - records.push(r); + let (body_index, share_body) = index.split_at(model.bodies.len()); + let mut table = Vec::with_capacity(model.bodies.len()); + for (b, i) in model.bodies.iter().zip(body_index) { + table.push(match b.display_share() { + Some((share, t)) => json!([i, share_index.get(&share.id()).ok_or_else(|| invalid("display share"))?, matrix(&t)]), + None => json!([i]), + }); } let manifest = serde_json::to_vec(&json!({ "format": FORMAT, "producer": PRODUCER, "app": env!("CARGO_PKG_VERSION"), "build": build(), "document": digest(document), "payload": digest(&data), - "bodies": slices, "shares": share_body, "body_counter": state.body_counter, "state": records, + "slices": slices, "shares": share_body, "bodies": table, "model": model.records, })) .map_err(invalid)?; if manifest.len() > MAX_MANIFEST { @@ -127,13 +83,13 @@ pub(super) fn encode_model(state: &ModelState, document: &[u8]) -> Result<(Vec Option { +pub fn read_design_geometry(bytes: &[u8]) -> Option> { if bytes.len() > MAX_DESIGN_BYTES || !is_design_container(bytes) { return None; } - DesignContainerReader::new(Cursor::new(bytes)).ok()?.geometry() + DesignContainerReader::new(Cursor::new(bytes)).ok()?.geometry()?.final_state().ok() } /// Whether `manifest` is a model cache this build wrote for `document`. @@ -148,12 +104,12 @@ fn current(manifest: &Value, document: &[u8]) -> bool { && env!("SOLIDCRAFT_SOURCE_COMMIT") != "unknown" } -pub(super) fn read_geometry_with(reader: &mut PackageReader, document: &[u8]) -> Result { +pub(super) fn read_geometry_with(reader: &mut PackageReader, document: &[u8]) -> Result { let container: Value = serde_json::from_slice(&reader.limited_part("container.json", 4096)?).map_err(invalid)?; if container.get("format").and_then(Value::as_str) != Some(VERSION) { return Err(invalid("container version")); } - let manifest: Value = serde_json::from_slice(&reader.limited_part(MANIFEST, MAX_MANIFEST)?).map_err(invalid)?; + let mut manifest: Value = serde_json::from_slice(&reader.limited_part(MANIFEST, MAX_MANIFEST)?).map_err(invalid)?; if !current(&manifest, document) { return Err(invalid("model cache key")); } @@ -163,16 +119,16 @@ pub(super) fn read_geometry_with(reader: &mut PackageReader, if manifest.get("payload").and_then(Value::as_str) != Some(digest(&data).as_str()) { return Err(invalid("model cache payload key")); } - let count = |v: &Value| v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| invalid("model cache number")); + let count = |v: Option<&Value>| v.and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()).ok_or_else(|| invalid("model cache number")); let slices = manifest - .get("bodies") + .get("slices") .and_then(Value::as_array) .filter(|b| !b.is_empty() && b.len() <= MAX_UNIQUE) .ok_or_else(|| invalid("cached bodies"))?; let mut end = 0usize; let mut parts = Vec::with_capacity(slices.len()); for s in slices { - let (offset, length) = (count(s.get(0).unwrap_or(&Value::Null))?, count(s.get(1).unwrap_or(&Value::Null))?); + let (offset, length) = (count(s.get(0))?, count(s.get(1))?); if offset != end { return Err(invalid("overlapping cached bodies")); } @@ -183,47 +139,33 @@ pub(super) fn read_geometry_with(reader: &mut PackageReader, return Err(invalid("trailing cached data")); } let decoded = solidcraft_kernel::map_on_threads(&parts, 16, |bytes| solidcraft_kernel::decode_native_body(bytes).ok()); - let bodies = decoded.into_iter().map(Option::flatten).collect::>>().ok_or_else(|| invalid("cached body"))?; - let body = |v: &Value| bodies.get(count(v)?).ok_or_else(|| invalid("cached body index")); + let unique = decoded.into_iter().map(Option::flatten).collect::>>().ok_or_else(|| invalid("cached body"))?; + let body = |v: Option<&Value>| unique.get(count(v)?).ok_or_else(|| invalid("cached body index")); let shares = manifest .get("shares") .and_then(Value::as_array) .filter(|s| s.len() <= MAX_UNIQUE) .ok_or_else(|| invalid("cached shares"))? .iter() - .map(|i| Ok(solidcraft_kernel::DisplayShare::new(body(i)?.clone()))) + .map(|i| Ok(solidcraft_kernel::DisplayShare::new(body(Some(i))?.clone()))) .collect::>>()?; - let records = - manifest.get("state").and_then(Value::as_array).filter(|s| !s.is_empty() && s.len() <= MAX_RECORDS).ok_or_else(|| invalid("cached state"))?; - let mut state = ModelState::default(); - state.body_counter = count(manifest.get("body_counter").unwrap_or(&Value::Null))?; - for r in records { - let name = r.get("name").and_then(Value::as_str).filter(|n| n.len() <= 1024).ok_or_else(|| invalid("cached body name"))?; - let mut kernel_body = body(r.get("body").unwrap_or(&Value::Null))?.clone(); - if let Some(share) = r.get("share") { - let s = shares.get(count(share.get(0).unwrap_or(&Value::Null))?).ok_or_else(|| invalid("cached share index"))?; - let numbers: Vec = serde_json::from_value(share.get(1).cloned().unwrap_or(Value::Null)).map_err(invalid)?; - let t = matrix_of(&numbers)?; - kernel_body = kernel_body.with_display_share(s, t); + let table = manifest + .get("bodies") + .and_then(Value::as_array) + .filter(|s| !s.is_empty() && s.len() <= MAX_RECORDS) + .ok_or_else(|| invalid("cached body table"))?; + let mut bodies = Vec::with_capacity(table.len()); + for entry in table { + let mut b = body(entry.get(0))?.clone(); + if let Some(share) = entry.get(1) { + let s = shares.get(count(Some(share))?).ok_or_else(|| invalid("cached share index"))?; + let numbers: Vec = serde_json::from_value(entry.get(2).cloned().unwrap_or(Value::Null)).map_err(invalid)?; + b = b.with_display_share(s, matrix_of(&numbers)?); } - let feature = r.get("feature").and_then(Value::as_u64).ok_or_else(|| invalid("cached body feature"))?; - let mut b = ModelBody::new(name.to_owned(), kernel_body, feature); - b.component = r.get("component").and_then(Value::as_u64).ok_or_else(|| invalid("cached body component"))?; - b.source_name = match r.get("source_name") { - None => None, - Some(v) => Some(v.as_str().filter(|n| n.len() <= 1024).ok_or_else(|| invalid("cached source name"))?.to_owned()), - }; - if let Some(v) = r.get("source_transform") { - let numbers: Vec = serde_json::from_value(v.clone()).map_err(invalid)?; - b.source_transform = matrix_of(&numbers)?; - } - b.transferred = r.get("transferred").and_then(Value::as_bool).unwrap_or(false); - if let Some(l) = r.get("imported") { - b.imported = Some(Arc::new(load_look(l)?)); - } - state.bodies.push(b); + bodies.push(b); } - Ok(state) + let records = manifest.get_mut("model").map(Value::take).ok_or_else(|| invalid("cached model"))?; + Ok(SavedModel { records, bodies }) } /// A 4 x 4 matrix from its 16 numbers in storage order, finite. @@ -238,9 +180,9 @@ fn matrix_of(numbers: &[f64]) -> Result<[[f64; 4]; 4]> { Ok(t) } -pub(super) fn geometry_preview(document: &[u8], state: ModelState) -> Result { +pub(super) fn geometry_preview(document: &[u8], model: &SavedModel) -> Result { let doc = Document::from_json(std::str::from_utf8(document).map_err(invalid)?)?; - let world = solidcraft_doc::world_state(&doc, &state); + let world = solidcraft_doc::world_state(&doc, &*model.final_state()?); let mut preview = DesignPreview::default(); let mut triangles = 0usize; let mut display_bytes = 0usize; diff --git a/crates/kernel/src/blend_variable.rs b/crates/kernel/src/blend_variable.rs index 8aafc19da..337408aa5 100644 --- a/crates/kernel/src/blend_variable.rs +++ b/crates/kernel/src/blend_variable.rs @@ -63,7 +63,7 @@ pub fn fillet_variable(body: &Body, edge_at: Vec3, start: Vec3, r0: f64, r1: f64 /// A fillet radius along an edge: a clamped B-spline of the position along it (0 at one end, 1 /// at the other), given by its degree, knots and control radii. The radius is a smooth curve /// shaped by its control radii, each pulling it toward itself near its Greville position. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct RadiusSpline { pub degree: usize, pub knots: Vec, @@ -503,7 +503,7 @@ const TAPER_SHARE: f64 = 0.9; const TAPER_SPANS: usize = 8; /// The radius a taper gives one edge: its positions from `start`. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct Taper { pub start: Vec3, pub spline: RadiusSpline, diff --git a/crates/kernel/src/boolean_diagnostics.rs b/crates/kernel/src/boolean_diagnostics.rs index b160980fb..e2a4b79cc 100644 --- a/crates/kernel/src/boolean_diagnostics.rs +++ b/crates/kernel/src/boolean_diagnostics.rs @@ -3,11 +3,11 @@ use std::cell::RefCell; -use serde::Serialize; +use serde::{Deserialize, Serialize}; const MAX_EVENTS: usize = 1024; -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum BooleanStrategy { RefinedTolerance, @@ -29,7 +29,7 @@ pub enum BooleanStrategy { /// Numerical adjustments used by a successful retry, in millimetres/radians. /// Operand shifts are reversed on the result; face shifts are temporary working /// offsets. A tool nudge, in contrast, changes the relative operand placement. -#[derive(Clone, Debug, PartialEq, Serialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BooleanFallback { pub strategy: BooleanStrategy, pub translation_mm: f64, @@ -73,7 +73,7 @@ impl BooleanFallback { } } -#[derive(Clone, Debug, Default, PartialEq, Serialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct BooleanDiagnostics { pub events: Vec, pub truncated: bool, diff --git a/docs/design-container.md b/docs/design-container.md index 29cddc747..c435fdc58 100644 --- a/docs/design-container.md +++ b/docs/design-container.md @@ -86,9 +86,10 @@ geometry, used for measurements, or used to seed evaluated model state. The orig design remains intact until the complete rebuilt session is ready. Cancellation or any change of active document/revision discards both preview and completion. -Normal design reading, CLI and browser opening still rebuild authoritatively. -The model cache can supply provisional display as described below. The saved -picture is not an interactive viewport. +Desktop Open takes the evaluation from the model cache when the file keeps one for +this document and build (see below); otherwise it evaluates the timeline, as +design reading in the CLI and browser does. The saved picture is not an +interactive viewport. ## Seekable reader (phase 2, first increment) @@ -121,6 +122,17 @@ being saved (`Model::is_current`). An active sketch, uncaptured moves, feature errors, mesh bodies or exceeded budgets leave the cache out; the design saves as before. +The model is the whole evaluation: every feature's result (warning, boolean +diagnostics, whether it was skipped, its fingerprint) and the state after it +(bodies, solved sketches, construction geometry, sheet metal bodies, threads and +the blend records later features read). States share what they share: a body that +later features pass through unchanged, its face names and a solved sketch are each +recorded once. Face names are kept as worked out (saving works out any not asked +for yet), so a body taken from the file is named exactly as when it was saved. +A design whose stored names predate format 14 (marked `?`) finds them through +names worked out from geometry on demand, which the cache does not keep: it saves +without a model. + Both entries are Deflate-compressed (level one) under either compression policy: the encoded bodies shrink about fourfold (an imported assembly) to tenfold (modelled parts), for a few tens of milliseconds. @@ -134,15 +146,14 @@ SHA-256 of their encoding), and a placed copy of a repeated part (an instance fr a STEP assembly) records the part and its matrix, so it shows that part's display again instead of being meshed on its own. -`cache/model.json` records `solidcraft-model-cache/1`, the producer revision +`cache/model.json` records `solidcraft-model-cache/2`, the producer revision `solidcraft-truck-adapter/3`, the application version, the build (source commit, CPU architecture and OS), the SHA-256 of the exact `document.json` (whose blob references pin every STEP, mesh and image payload) and of `cache/bodies.bin`, the -slices, and the bodies' records: name, feature, component, placement source, -imported look and display share. A cache is read back only when every one of these -matches: the same source compiled for the same platform computes the same numbers, -so another build's cache is a miss. A build of unknown source (a tarball without -git) never reads a cache. +slices, each kernel body's slice and display share, and the model's records. A +cache is read back only when every one of these matches: the same source compiled +for the same platform computes the same numbers, so another build's cache is a +miss. A build of unknown source (a tarball without git) never reads a cache. The fixed budgets of earlier caches (4,096 bodies, 100,000 faces, 64 MiB) scale with the design now: up to 200,000 body records, 100,000 distinct bodies, a 32 MiB @@ -152,9 +163,34 @@ budgets (256 MiB per part, 512 MiB expanded, 10,000 entries) are unchanged, and cache is left out when it would push the container near them. Decoding runs under `kernel::guard` and is linear in the payload's bytes. -Opening still rebuilds the design from its timeline; the cache supplies the -provisional picture (a bounded mesh of the placed bodies) before that finishes. -Any failure in it is a miss, never a failed open. Earlier `cache/key.json` and +### Opening from the model + +Open takes the model as the design's evaluation (`Model::adopt`) when the key +matches and every feature's fingerprint (its definition, the parameters and +imported files it reads, the features before it, the timeline marker) is the one +the opened document gives it now. Nothing is evaluated: the imported STEP text is +resolved and hashed, never parsed. Every feature is up to date, so an edit +evaluates from the first feature it changes, as after any evaluation: a feature +appended or edited at the end evaluates from the saved final state, an edit to +feature k from the saved state before k. Moving the timeline marker, undo and redo +reuse the saved results whose fingerprints come back. `SOLIDCRAFT_NO_MODEL_CACHE` +set evaluates anyway. Any failure (a key or fingerprint mismatch, a malformed +record, a body that does not decode) is a miss: the design is evaluated from its +timeline as before, and only that. + +This replaces the earlier rule that a cache never supplies evaluated session +state. It is safe because the cache is the result of evaluating exactly this +document with exactly this build: the hashes tie it to the document (and through +it to every source blob) and to its own payload, the build key to the code that +computed it, the fingerprints to every feature's inputs, and the exact encoding +gives back the bodies number for number. Hashes are not trust: a crafted file can +carry a cache whose geometry disagrees with its timeline, as a crafted STEP file +can carry any geometry. Every decoded body passes the same structural and resource +checks, under `kernel::guard`, and Compute All (`timeline.compute_all`) evaluates +the whole timeline again. + +Before the session is ready the cache still supplies the picture (a bounded mesh +of the placed bodies) shown while opening. Earlier `cache/key.json` and `cache/brep.bin` entries are ignored. ## Review increments and kernel independence