Skip to content

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

Sketch on a turned occurrence: reuse moved bodies across edits (#4853) (#4863)

raykholo60105172b20b
diff --git a/crates/doc/src/anchor_frame.rs b/crates/doc/src/anchor_frame.rs
index e58fda5c22..9dd56cd1ec 100644
--- a/crates/doc/src/anchor_frame.rs
+++ b/crates/doc/src/anchor_frame.rs
@@ -1,5 +1,5 @@
//! Presentation/projection state for an exact selected planar source placement.
-use crate::{DocError, Document, FaceAnchor, ModelBody, ModelState, Result};
+use crate::{DocError, Document, FaceAnchor, ModelState, Result};
use std::borrow::Cow;
pub fn state_in_face_anchor_frame<'a>(doc: &Document, state: &'a ModelState, anchor: &FaceAnchor, author: u64) -> Result<Cow<'a, ModelState>> {
@@ -9,17 +9,7 @@ pub fn state_in_face_anchor_frame<'a>(doc: &Document, state: &'a ModelState, anc
let mut output = crate::state_in_frame_at(doc, state, author, frame).into_owned();
// In place, the body is the model's own, display mesh included: a sketch projecting the
// face's edges meshes it once for the features after it too, rather than a copy.
- let mut body = if crate::is_identity(&relative) {
- raw.clone()
- } else {
- ModelBody::new(raw.name.clone(), solidcraft_kernel::transform_matrix(&raw.body, relative)?, raw.feature)
- };
- body.component = raw.component;
- body.transferred = raw.transferred;
- body.source_name = raw.source_name.clone();
- body.source_transform = crate::mat_mul(&relative, &raw.source_transform);
- body.imported = raw.imported.clone();
- body.names = crate::naming::NameCell::same(raw);
+ let body = state.body_in_frame(raw, &relative)?;
let slot = output.bodies.iter_mut().find(|body| body.name == raw.name).ok_or_else(|| DocError::Unknown("anchored body frame".into()))?;
*slot = body;
Ok(Cow::Owned(output))
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index 39162c1415..3da658d836 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -736,6 +736,9 @@ impl ModelState {
/// Model after some prefix of the timeline.
#[derive(Clone, Debug, Default)]
pub struct ModelState {
+ /// Frame placements belong to the evaluator. A weak reference avoids a cycle through
+ /// cached bodies' naming origins, which retain earlier model states.
+ frame_bodies: std::sync::Weak<std::sync::Mutex<FrameBodies>>,
/// Cosmetic threads (from Thread features and threaded holes).
pub threads: Vec<ThreadInfo>,
pub bodies: Vec<ModelBody>,
@@ -767,6 +770,31 @@ pub struct ModelState {
}
impl ModelState {
+ /// `body` moved by `matrix` into a feature's frame. The evaluator that made this state keeps
+ /// the moved body, so an unchanged body under an unchanged placement is moved (and meshed)
+ /// once rather than on every evaluation.
+ pub(crate) fn body_in_frame(&self, body: &ModelBody, matrix: &Mat) -> Result<ModelBody> {
+ if crate::is_identity(matrix) {
+ return Ok(body.clone());
+ }
+ let cache = self.frame_bodies.upgrade();
+ // Not held while the body is moved: copies of the evaluator may share the cache.
+ let reused = cache.as_ref().and_then(|c| c.lock().unwrap_or_else(|e| e.into_inner()).reused(body, matrix));
+ let placed = match reused {
+ Some(placed) => placed,
+ None => {
+ let placed = ModelBody::new(body.name.clone(), kernel::transform_matrix(&body.body, *matrix)?, body.feature);
+ #[cfg(test)]
+ cost_tests::count(|c| c.moved += 1);
+ if let Some(c) = &cache {
+ c.lock().unwrap_or_else(|e| e.into_inner()).keep(body, matrix, &placed);
+ }
+ placed
+ }
+ };
+ Ok(in_frame(body, matrix, &placed))
+ }
+
/// A digest of everything later features can read: bodies (by content identity), sketches,
/// the body counter, threads and sheet bodies.
fn digest(&self) -> u64 {
@@ -1088,6 +1116,8 @@ pub struct Model {
/// Results another copy of this model evaluated (ahead, off the window thread) that
/// `evaluate` takes for features they match ([`Model::prime`]), with that copy's context.
primed: Option<(u64, Arc<std::collections::HashMap<u64, FeatureResult>>)>,
+ /// Shared with copies of this evaluator; states hold only a weak reference.
+ frame_bodies: Arc<std::sync::Mutex<FrameBodies>>,
}
/// Parameters a feature uses directly (inputs, sketch dimensions and the expressions of a
@@ -1798,6 +1828,7 @@ impl Model {
pub fn evaluate(&mut self, doc: &Document) {
let (vals, perr) = evaluation_values(doc);
self.param_errors = perr;
+ self.frame_bodies.lock().unwrap_or_else(|e| e.into_inner()).next_generation();
let mut prev_fp = 0u64;
// The names the design must not use again travel with the state (#4957).
let mut state = std::sync::Arc::new(ModelState { reserved_body_names: doc.reserved_body_names.clone(), ..(*self.empty).clone() });
@@ -1909,6 +1940,7 @@ impl Model {
let mut next = (*state).clone();
// The names the design must not use again travel with the state (#4957, #4302).
next.reserved_body_names.clone_from(&reserved);
+ next.frame_bodies = Arc::downgrade(&self.frame_bodies);
for b in &mut next.bodies {
b.made = crate::lineage::Made::Before;
}
@@ -7303,20 +7335,9 @@ pub fn state_in_frame_at<'a>(doc: &Document, st: &'a ModelState, comp: u64, fram
let mut out = st.clone();
for (b, m) in out.bodies.iter_mut().zip(&body_m) {
if !crate::is_identity(m)
- && let Ok(t) = kernel::transform_matrix(&b.body, *m)
+ && let Ok(moved) = st.body_in_frame(b, m)
{
- #[cfg(test)]
- cost_tests::count(|c| c.moved += 1);
- // Moving a body keeps its faces (and their order): it keeps their names.
- let names = crate::naming::NameCell::same(b);
- let mut nb = ModelBody::new(b.name.clone(), t, b.feature);
- nb.component = b.component;
- nb.transferred = b.transferred;
- nb.source_name = b.source_name.clone();
- nb.source_transform = crate::mat_mul(m, &b.source_transform);
- nb.imported = b.imported.clone();
- nb.names = names;
- *b = nb;
+ *b = moved;
}
}
for (s, m) in out.sketches.iter_mut().zip(&sketch_m) {
@@ -7351,27 +7372,33 @@ pub fn world_state(doc: &Document, st: &ModelState) -> ModelState {
/// definition and placement are unchanged instead of transforming it again, and so keeps its
/// display mesh. Without this every change anywhere in a design transformed and meshed every
/// body of every moved component again.
-#[derive(Default)]
+#[derive(Debug, Default)]
pub struct PlacedBodies {
by_source: std::collections::HashMap<(usize, [u64; 16]), (ModelBody, ModelBody)>,
}
impl PlacedBodies {
+ fn reused(&self, b: &ModelBody, m: &crate::Mat) -> Option<&ModelBody> {
+ self.by_source
+ .get(&placed_key(b, m))
+ .filter(|(source, _)| {
+ Arc::ptr_eq(&source.mesh, &b.mesh)
+ && source.body.same(&b.body)
+ && source.body.color() == b.body.color()
+ && source.body.paint() == b.body.paint()
+ && match (source.body.split_lines(), b.body.split_lines()) {
+ (Some(x), Some(y)) => Arc::ptr_eq(x, y),
+ (None, None) => true,
+ _ => false,
+ }
+ })
+ .map(|(_, placed)| placed)
+ }
+
/// The body `b` placed by `m`, from an earlier call when `b` is the same body as then.
fn placed(&self, b: &ModelBody, m: &crate::Mat, name: String) -> ModelBody {
- let reused = self.by_source.get(&placed_key(b, m)).filter(|(source, _)| {
- Arc::ptr_eq(&source.mesh, &b.mesh)
- && source.body.same(&b.body)
- && source.body.color() == b.body.color()
- && source.body.paint() == b.body.paint()
- && match (source.body.split_lines(), b.body.split_lines()) {
- (Some(x), Some(y)) => Arc::ptr_eq(x, y),
- (None, None) => true,
- _ => false,
- }
- });
- match reused {
- Some((_, placed)) => {
+ match self.reused(b, m) {
+ Some(placed) => {
let mut fresh = ModelBody::new(name, placed.body.clone(), b.feature);
fresh.mesh = placed.mesh.clone();
fresh.mesh_placement = placed.mesh_placement.clone();
@@ -7391,6 +7418,66 @@ impl PlacedBodies {
}
}
+/// Bodies [`state_in_frame_at`] moved into a feature's frame, by source body and matrix: a
+/// sketch on a face of a turned component is evaluated in that component's frame, and without
+/// this every edit of it moved (and so meshed again) every body placed differently from it.
+/// Held by the [`Model`] across evaluations; each `evaluate` starts a new generation, and an
+/// entry neither it nor the evaluation before it used is dropped, so the cache holds only the
+/// placements in use.
+#[derive(Debug, Default)]
+pub(crate) struct FrameBodies {
+ now: PlacedBodies,
+ before: PlacedBodies,
+}
+
+impl FrameBodies {
+ /// At most this many bodies are kept per generation.
+ const CAP: usize = 4096;
+
+ pub(crate) fn next_generation(&mut self) {
+ self.before = std::mem::take(&mut self.now);
+ }
+
+ /// The moved body for `b` under `m`, when a call in this or the previous generation moved
+ /// the same body by the same matrix.
+ fn reused(&mut self, b: &ModelBody, m: &crate::Mat) -> Option<ModelBody> {
+ if let Some(placed) = self.now.reused(b, m) {
+ return Some(placed.clone());
+ }
+ let placed = self.before.reused(b, m)?.clone();
+ let key = placed_key(b, m);
+ if let Some(entry) = self.before.by_source.remove(&key)
+ && self.now.by_source.len() < Self::CAP
+ {
+ self.now.by_source.insert(key, entry);
+ }
+ Some(placed)
+ }
+
+ fn keep(&mut self, b: &ModelBody, m: &crate::Mat, moved: &ModelBody) {
+ if self.now.by_source.len() < Self::CAP {
+ self.now.by_source.insert(placed_key(b, m), (b.clone(), moved.clone()));
+ }
+ }
+}
+
+/// `b` in a feature's frame: `placed` (its geometry moved by `m`, sharing the moved body's
+/// mesh and display plan), carrying `b`'s ownership and naming.
+fn in_frame(b: &ModelBody, m: &crate::Mat, placed: &ModelBody) -> ModelBody {
+ let mut moved = ModelBody::new(b.name.clone(), placed.body.clone(), b.feature);
+ moved.mesh = placed.mesh.clone();
+ moved.plan = placed.plan.clone();
+ moved.plan_mesh = placed.plan_mesh.clone();
+ moved.component = b.component;
+ moved.transferred = b.transferred;
+ moved.source_name = b.source_name.clone();
+ moved.source_transform = crate::mat_mul(m, &b.source_transform);
+ moved.imported = b.imported.clone();
+ // Moving a body keeps its faces (and their order): it keeps their names.
+ moved.names = crate::naming::NameCell::same(b);
+ moved
+}
+
fn placed_key(b: &ModelBody, m: &crate::Mat) -> (usize, [u64; 16]) {
let mut bits = [0u64; 16];
for (slot, v) in bits.iter_mut().zip(m.iter().flatten()) {
diff --git a/crates/doc/src/eval_cost_tests.rs b/crates/doc/src/eval_cost_tests.rs
index 07a0aa9628..3d7c4c21fa 100644
--- a/crates/doc/src/eval_cost_tests.rs
+++ b/crates/doc/src/eval_cost_tests.rs
@@ -5,6 +5,7 @@
//! fingerprint it, so each sketch command took longer the more parts were inserted.
use std::cell::Cell;
+use std::collections::BTreeMap;
use std::sync::Arc;
use solidcraft_geom::{Plane, Vec2, Vec3};
@@ -223,6 +224,72 @@ fn a_sketch_on_a_face_still_sees_the_placed_bodies() {
assert_eq!(work.digested, 0);
}
+#[test]
+fn editing_a_sketch_on_a_turned_occurrence_reuses_its_frame_bodies() {
+ use solidcraft_sketch::{LinkKind, LinkSource};
+
+ let mut doc = Document::new("turned face");
+ let comp = doc.add_component(Some("Plate"), 0).unwrap();
+ let occurrence = doc.occurrences.iter_mut().find(|o| o.component == comp).unwrap();
+ occurrence.transform = rigid(Vec3::ZERO, Vec3::ZERO, Vec3::X, std::f64::consts::FRAC_PI_2);
+ let path = vec![occurrence.id];
+ let kind = serde_json::from_value(serde_json::json!({
+ "type": "box", "corner": [0, 0, 0], "length": "90", "width": "120", "height": "8"
+ }))
+ .unwrap();
+ let plate = doc.add_feature(kind, Some("Plate")).unwrap();
+ doc.feature_mut(plate).unwrap().component = comp;
+ let mut model = Model::new();
+ model.evaluate(&doc);
+ let state = model.state();
+ let raw = state.bodies.first().unwrap();
+ let index = raw.body.face_sources().unwrap().iter().position(|s| matches!(s, Some(kernel::FaceSource::Box { axis: 2, high: true, .. }))).unwrap();
+ let world = world_state(&doc, &state);
+ let shown = world.bodies.first().unwrap();
+ let picked = shown.body.face_plane(index).unwrap();
+ let anchor = doc.capture_face_anchor(raw, index, &picked, &path, 0, &[]).unwrap();
+ let source = LinkSource::Face { body: raw.name.clone(), at: apply_point(&doc.component_transform(comp), Vec3::new(30., 60., 8.)) };
+ let resolved = crate::project::resolve(&doc, &BTreeMap::new(), &world, &picked, LinkKind::Project, &source).unwrap();
+ let plane = PlaneRef::Face { plane: picked, at: picked.origin, name: None, anchor: Some(Box::new(anchor.clone())) };
+ let mut sketch = Sketch::new();
+ let a = sketch.add_point(Vec2::ZERO, None).unwrap();
+ let b = sketch.add_point(Vec2::new(3., 3.), None).unwrap();
+ sketch.add_line_pts(a, b, None).unwrap();
+ sketch.add_link(LinkKind::Project, source, &resolved.geom).unwrap();
+ let id = doc.add_feature(FeatureKind::Sketch { plane, sketch }, None).unwrap();
+ doc.feature_mut(id).unwrap().component = 0;
+ let first = counted(|| model.evaluate(&doc));
+ assert!(first.moved > 0, "{first:?}");
+ assert!(model.result(id).unwrap().error.is_none(), "{:?}", model.result(id).unwrap().error);
+ let reopened = Model::adopt(&doc, &model.saved(&doc).unwrap()).unwrap();
+ for mut model in [model, reopened] {
+ let before = state_in_face_anchor_frame(&doc, &model.state_before(id), &anchor, 0).unwrap().bodies.first().unwrap().mesh();
+
+ for to in [Vec2::new(4., 5.), Vec2::new(6., 7.)] {
+ doc.sketch_mut(id).unwrap().points.get_mut(1).unwrap().pos = to;
+ let work = counted(|| model.evaluate(&doc));
+ assert_eq!(work.moved, 0, "sketch edit must reuse the unchanged placement: {work:?}");
+ assert_eq!(model.last_recomputed, 1);
+ let result = model.result(id).unwrap();
+ assert!(result.error.is_none(), "{:?}", result.error);
+ let solved = model.state();
+ let solved = solved.sketch(id).unwrap();
+ assert!(solved.sketch.links.iter().all(|link| !link.lost));
+ assert!((solved.plane.normal().dot(picked.normal()) - 1.).abs() < 1e-9);
+ let after = state_in_face_anchor_frame(&doc, &model.state_before(id), &anchor, 0).unwrap().bodies.first().unwrap().mesh();
+ assert!(Arc::ptr_eq(&before, &after), "the anchored body's mesh must survive sketch edits");
+ }
+ // A changed placement is a different frame: the body is moved again, not reused.
+ let turned = doc.occurrences.iter().find(|o| o.component == comp).unwrap().transform;
+ doc.occurrences.iter_mut().find(|o| o.component == comp).unwrap().transform =
+ rigid(Vec3::ZERO, Vec3::ZERO, Vec3::X, std::f64::consts::FRAC_PI_3);
+ let work = counted(|| model.evaluate(&doc));
+ assert!(work.moved > 0, "a changed placement must move the body again: {work:?}");
+ doc.occurrences.iter_mut().find(|o| o.component == comp).unwrap().transform = turned;
+ model.evaluate(&doc);
+ }
+}
+
#[test]
fn an_imported_file_is_fingerprinted_by_its_text() {
let doc = placed_imports(2);
diff --git a/crates/doc/src/model_cache.rs b/crates/doc/src/model_cache.rs
index 9e597a1e21..406d6dcbfa 100644
--- a/crates/doc/src/model_cache.rs
+++ b/crates/doc/src/model_cache.rs
@@ -330,6 +330,7 @@ impl SavedModel {
.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 {
+ frame_bodies: Default::default(),
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)?,
@@ -529,7 +530,11 @@ impl Model {
/// did not keep ([`SavedModel::thinned`]). 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<Model> {
- let states = saved.states()?;
+ let mut states = saved.states()?;
+ let frame_bodies = Arc::new(std::sync::Mutex::new(FrameBodies::default()));
+ for state in &mut states {
+ Arc::make_mut(state).frame_bodies = Arc::downgrade(&frame_bodies);
+ }
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"))
@@ -584,7 +589,7 @@ impl Model {
}
results.push(result);
}
- let mut model = Model { results, param_errors, step_digests, ..Model::default() };
+ let mut model = Model { results, param_errors, step_digests, frame_bodies, ..Model::default() };
let unkept = model.results.iter().filter(|r| r.unkept).count();
if unkept > 0 {
// The features whose state the file did not keep, each evaluated again from the state