Skip to content

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

Joint drive moves parts without evaluating them (#3391) (#3397)

SS-EN408d30ea5638
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index fad3082660..dec38fc683 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -1021,6 +1021,11 @@ pub struct Model {
kept: KeptSlot,
/// The imported texts' digests the last `evaluate` fingerprinted the features with.
step_digests: StepDigests,
+ /// The document context the last `evaluate` ran in ([`context_digest`]).
+ context: u64,
+ /// 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>>)>,
}
/// Parameters a feature uses directly (inputs, sketch dimensions and the expressions of a
@@ -1187,8 +1192,17 @@ fn evaluation_values(doc: &Document) -> (BTreeMap<String, Value>, BTreeMap<Strin
/// A feature's fingerprint in the chain after `prev`: its own inputs, where it is placed, and
/// the sheet metal or plastic rules it takes defaults from.
-fn chain_fingerprint(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, prev: u64, rolled_back: bool, steps: &StepDigests) -> u64 {
- let mut fp = fingerprint(prev, f, vals, rolled_back, steps) ^ placement_digest(doc, f);
+#[allow(clippy::too_many_arguments)]
+fn chain_fingerprint(
+ doc: &Document,
+ vals: &BTreeMap<String, Value>,
+ f: &Feature,
+ prev: u64,
+ rolled_back: bool,
+ steps: &StepDigests,
+ st: Option<&ModelState>,
+) -> u64 {
+ let mut fp = fingerprint(prev, f, vals, rolled_back, steps) ^ placement_digest(doc, f, st);
// Sheet metal features also depend on the rules (and the parameters they use).
if f.kind.is_sheet() {
let mut h = std::collections::hash_map::DefaultHasher::new();
@@ -1273,9 +1287,157 @@ fn cache_key(f: &Feature, chain_fp: u64, local: u64, ctx: u64, state: &ModelStat
h.finish()
}
-/// Where components are placed, for a sketch that sees other components' geometry (on a face,
-/// or with projections): it is resolved in its own component's view of them.
-fn placement_digest(doc: &Document, f: &Feature) -> u64 {
+/// What a feature reads of placements: components (their first placement), occurrence paths
+/// and bodies in its timeline input, whose geometry it finds in its evaluating frame, or all.
+#[derive(Default)]
+struct PlacementReads {
+ all: bool,
+ components: std::collections::BTreeSet<u64>,
+ paths: Vec<Vec<u64>>,
+ bodies: std::collections::BTreeSet<String>,
+}
+
+impl PlacementReads {
+ fn is_empty(&self) -> bool {
+ !self.all && self.components.is_empty() && self.paths.is_empty() && self.bodies.is_empty()
+ }
+
+ /// A body's complete placement in the feature's input state, including its offset. Later
+ /// transfers do not change where an earlier feature read it.
+ fn placed_body(&mut self, st: Option<&ModelState>, name: &str) {
+ if st.is_some_and(|st| st.body(name).is_some()) {
+ self.bodies.insert(name.to_owned());
+ } else {
+ self.all = true;
+ }
+ }
+
+ /// The same target selection as `apply_traced`, expanded only over the timeline input.
+ fn drawn_targets(&mut self, st: Option<&ModelState>, f: &Feature) {
+ let Some(st) = st else {
+ self.all = true;
+ return;
+ };
+ let (_, targets) = feature_op(f);
+ let names = if targets.is_empty() { &f.participants } else { &targets };
+ let all = names.len() == 1 && names.first().is_some_and(|n| n == "*");
+ if all || names.is_empty() {
+ self.bodies.extend(st.bodies.iter().filter(|b| all || b.component == f.component || b.feature == f.id).map(|b| b.name.clone()));
+ } else {
+ for name in names {
+ self.placed_body(Some(st), name);
+ }
+ }
+ }
+
+ /// The component of body `name` in `st`; every component when the body is not there (a
+ /// projection then takes the body nearest its point, wherever that is).
+ fn body(&mut self, doc: &Document, st: Option<&ModelState>, name: &str) {
+ match st.and_then(|st| st.body(name)) {
+ Some(b) => {
+ self.components.insert(doc.model_body_component(b));
+ }
+ None => self.all = true,
+ }
+ }
+
+ /// The component of sketch `id`, and the root when it holds wires fixed in the world (they
+ /// are read through the reader's whole placement).
+ fn sketch(&mut self, doc: &Document, id: u64) {
+ self.components.insert(doc.feature(id).map(|f| f.component).unwrap_or(0));
+ if doc.sketch(id).is_ok_and(|sk| sk.wires.iter().any(|w| w.space == solidcraft_sketch::WireSpace::World)) {
+ self.components.insert(0);
+ }
+ }
+
+ fn link(&mut self, doc: &Document, st: Option<&ModelState>, source: &solidcraft_sketch::LinkSource) {
+ use solidcraft_sketch::LinkSource as L;
+ match source {
+ L::Edge { body, .. } | L::Face { body, .. } | L::Body { body } | L::Vertex { body, .. } | L::Iso { body, .. } | L::Spun { body, .. } => {
+ self.body(doc, st, body)
+ }
+ L::SketchCurve { sketch, .. } | L::SketchPoint { sketch, .. } => self.sketch(doc, *sketch),
+ L::OnSurface { sketch, body, .. } => {
+ self.sketch(doc, *sketch);
+ self.body(doc, st, body);
+ }
+ L::Intersection { a, b } => {
+ self.link(doc, st, a);
+ self.link(doc, st, b);
+ }
+ // In the sketch's own frame: the component's origin, axes and planes, its own axes, text.
+ L::Origin | L::Axis { .. } | L::SketchAxis { .. } | L::Plane { .. } | L::Text { .. } => {}
+ }
+ }
+}
+
+/// The frame of an occurrence path from the root (its occurrences' transforms in turn); `None`
+/// when the path no longer leads anywhere.
+fn path_frame(doc: &Document, path: &[u64]) -> Option<Mat> {
+ if path.len() > crate::MAX_PLACEMENT_DEPTH + 1 {
+ return None;
+ }
+ let (mut m, mut c) = (crate::IDENTITY, 0);
+ for id in path {
+ let o = doc.occurrences.iter().find(|o| o.id == *id && o.parent == c)?;
+ m = crate::mat_mul(&m, &o.transform);
+ c = o.component;
+ }
+ Some(m)
+}
+
+/// Hash a placement on a grid far finer than anything a design shows ([`QUANTUM`] mm, a
+/// thousandth of that for the rotation), so the same relative placement reached through
+/// different whole-assembly motions (each rounding a little differently) reads the same.
+fn hash_placement(m: &Mat, h: &mut impl Hasher) {
+ for (col, column) in m.iter().enumerate() {
+ let q = if col == 3 { QUANTUM } else { QUANTUM * 1e-3 };
+ for v in column {
+ let r = (v / q).round();
+ // -0 and 0 are the same place.
+ (if r == 0.0 { 0.0f64 } else { r }).to_bits().hash(h);
+ }
+ }
+}
+
+/// Where the geometry a feature reads from other components is placed, as its own component
+/// sees it: the placement of each component (or occurrence path) it reads relative to its own
+/// frame. A feature that reads nothing outside its own frame gives 0, so moving parts around
+/// (a joint driven, an occurrence moved) leaves it as it was; one that reads a part moved
+/// relative to it (a sketch projecting a face of another part, To Object, a mirror of a placed
+/// body) is evaluated again. `st` is the model the feature starts from, which says what
+/// component a body it names belongs to (without it, every component is taken as read).
+/// [`placement_digest`] of a mirror of placed bodies: its own component's frame, each placement it
+/// was picked at (the copy's component, frame and the frame it was picked in) and the offsets of
+/// the bodies it mirrors (#1938).
+fn mirror_placements_digest(doc: &Document, f: &Feature, placements: &[Vec<u64>], bodies: &[crate::BodyName]) -> u64 {
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ doc.component_transform(f.component).iter().flatten().for_each(|x| x.to_bits().hash(&mut h));
+ for placed in placements.iter().map(|path| mirror_copy_frame(doc, path)) {
+ placed.is_some().hash(&mut h);
+ if let Some((component, frame, picked)) = placed {
+ component.hash(&mut h);
+ frame.iter().chain(&picked).flatten().for_each(|x| x.to_bits().hash(&mut h));
+ }
+ }
+ for b in bodies {
+ serde_json::to_string(&doc.body_offsets.get(&b.0)).unwrap_or_default().hash(&mut h);
+ }
+ h.finish()
+}
+
+fn placement_digest(doc: &Document, f: &Feature, st: Option<&ModelState>) -> u64 {
+ // No shortcut for a design without placements: its first component (placed where the
+ // design is) must not change what its features read, or creating it evaluates them all.
+ let mut reads = PlacementReads::default();
+ let mut frame = None;
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ // A sketch, profile or path of another component is moved through both placements.
+ for (sketch, _) in f.kind.profile_sels() {
+ if doc.feature(sketch).is_some_and(|s| s.component != f.component) {
+ reads.sketch(doc, sketch);
+ }
+ }
let path = match &f.kind {
FeatureKind::Sweep { path_sketch, .. }
| FeatureKind::SurfaceSweep { path_sketch, .. }
@@ -1292,10 +1454,8 @@ fn placement_digest(doc: &Document, f: &Feature) -> u64 {
_ => &[],
};
if path.as_ref().is_some_and(wired) || rails.iter().any(|r| wired(&r.sketch)) {
- let mut hash = std::collections::hash_map::DefaultHasher::new();
- let owner = path.and_then(|path| doc.feature(path.0)).map(|feature| feature.component).unwrap_or(0);
- for frame in [doc.component_transform(f.component), doc.component_transform(owner)] {
- frame.iter().flatten().for_each(|value| value.to_bits().hash(&mut hash));
+ if let Some(path) = path {
+ reads.sketch(doc, path.0);
}
// A sweep's profile and the rails' components place them too.
let profile = match &f.kind {
@@ -1303,69 +1463,113 @@ fn placement_digest(doc: &Document, f: &Feature) -> u64 {
_ => None,
};
for sketch in profile.into_iter().chain(rails.iter().map(|r| &r.sketch)) {
- let owner = doc.feature(sketch.0).map(|feature| feature.component).unwrap_or(0);
- doc.component_transform(owner).iter().flatten().for_each(|value| value.to_bits().hash(&mut hash));
+ reads.sketch(doc, sketch.0);
}
- return hash.finish();
}
// A network through 3D sketch curves reads their points through the components the
// feature and those sketches are placed in, as a sweep's wired path does.
if let FeatureKind::SurfaceNetwork { u, v, .. } = &f.kind {
let sketches: Vec<crate::SketchId> = u.iter().chain(v).filter_map(|c| c.sketch).collect();
if sketches.iter().any(wired) {
- let mut hash = std::collections::hash_map::DefaultHasher::new();
- doc.component_transform(f.component).iter().flatten().for_each(|value| value.to_bits().hash(&mut hash));
for sketch in &sketches {
- let owner = doc.feature(sketch.0).map(|feature| feature.component).unwrap_or(0);
- doc.component_transform(owner).iter().flatten().for_each(|value| value.to_bits().hash(&mut hash));
+ reads.sketch(doc, sketch.0);
}
- return hash.finish();
}
}
- // To / From Object finds its target where that target's component is placed (#928).
- let to_object = match &f.kind {
- FeatureKind::Extrude { extent, .. } => extent.to.is_some() || extent.from.is_some(),
- FeatureKind::Revolve { to, .. } => to.is_some(),
- _ => false,
- };
- // A mirror of placed bodies follows the placements it was picked at and its own component's
- // frame, not every occurrence: moving an unrelated one leaves it (and its cache) alone.
- if let FeatureKind::Mirror { placements, bodies, .. } = &f.kind
- && !placements.is_empty()
- {
- let mut h = std::collections::hash_map::DefaultHasher::new();
- doc.component_transform(f.component).iter().flatten().for_each(|x| x.to_bits().hash(&mut h));
- for placed in placements.iter().map(|path| mirror_copy_frame(doc, path)) {
- placed.is_some().hash(&mut h);
- if let Some((component, frame, picked)) = placed {
- component.hash(&mut h);
- frame.iter().chain(&picked).flatten().for_each(|x| x.to_bits().hash(&mut h));
+ match &f.kind {
+ // To / From Object finds its target where that target's component is placed (#928),
+ // over every body.
+ FeatureKind::Extrude { extent, .. } if extent.to.is_some() || extent.from.is_some() => reads.all = true,
+ FeatureKind::Revolve { to: Some(_), .. } => reads.all = true,
+ // A mirror of placed bodies follows the placements it was picked at and its own component's
+ // frame, not every occurrence: moving an unrelated one leaves it (and its cache) alone.
+ FeatureKind::Mirror { placements, bodies, .. } if !placements.is_empty() => return mirror_placements_digest(doc, f, placements, bodies),
+ // A combine moves tools placed differently from its target into the target's frame (#3383).
+ FeatureKind::Combine { target, tools, .. } => {
+ frame = st.and_then(|st| st.body(target)).map(|b| body_world(doc, b));
+ reads.placed_body(st, target);
+ for tool in tools {
+ reads.placed_body(st, tool);
+ }
+ }
+ // Joins, cuts and intersects meet their targets where those are placed (#3383).
+ kind if drawn_tools_change_bodies(kind) => reads.drawn_targets(st, f),
+ FeatureKind::Sketch { plane, sketch } => {
+ match crate::face_anchor::plane_face_anchor(plane) {
+ // Read in the frame of the placement it was drawn in, its face through the
+ // placement it was picked at.
+ Some(anchor) => {
+ match anchor.author_frame(doc, f.component) {
+ Ok(m) => frame = Some(m),
+ Err(e) => e.to_string().hash(&mut h),
+ }
+ if anchor.path.is_empty() {
+ reads.components.insert(anchor.component);
+ } else {
+ reads.paths.push(anchor.path.clone());
+ }
+ }
+ // A face or edges picked on whatever body lies there.
+ None if plane_reads_geometry(plane) => reads.all = true,
+ None => {}
+ }
+ for link in &sketch.links {
+ reads.link(doc, st, &link.source);
}
}
- for b in bodies {
- serde_json::to_string(&doc.body_offsets.get(&b.0)).unwrap_or_default().hash(&mut h);
+ _ => {}
+ }
+ if reads.is_empty() {
+ return 0;
+ }
+ let frame = frame.unwrap_or_else(|| doc.component_transform(f.component));
+ let Some(inverse) = crate::mat_inverse(&frame) else { return placements_hash(doc) };
+ if reads.all {
+ reads.components.insert(0);
+ match st {
+ // The components holding what the feature can reach: a component made later, or one
+ // that holds nothing yet (just created), changes nothing it reads.
+ Some(st) => {
+ reads.components.extend(doc.body_owners(st));
+ let owner = |id: u64| doc.feature(id).map(|g| g.component);
+ reads.components.extend(st.sketches.iter().filter_map(|s| owner(s.feature)));
+ reads.components.extend(st.construct.iter().filter_map(|c| owner(c.feature)));
+ }
+ None => reads.components.extend(doc.components.iter().map(|c| c.id)),
}
- return h.finish();
}
- // A combine moves tools placed differently from its target into the target's frame (#3383).
- let combine = matches!(&f.kind, FeatureKind::Combine { .. });
- if !to_object && !combine && drawn_tools_change_bodies(&f.kind) {
- return drawn_tools_digest(doc, f);
+ for c in &reads.components {
+ c.hash(&mut h);
+ // Its own component is read in its own frame.
+ if *c != f.component {
+ hash_placement(&crate::mat_mul(&inverse, &doc.component_transform(*c)), &mut h);
+ }
}
- if to_object || combine {
- return if doc.occurrences.is_empty() && doc.body_offsets.is_empty() { 0 } else { placements_hash(doc) };
+ for path in &reads.paths {
+ path.hash(&mut h);
+ match path_frame(doc, path) {
+ Some(m) => hash_placement(&crate::mat_mul(&inverse, &m), &mut h),
+ None => u8::MAX.hash(&mut h),
+ }
}
- let FeatureKind::Sketch { plane, sketch } = &f.kind else { return 0 };
- let anchor = crate::face_anchor::plane_face_anchor(plane);
- if (doc.occurrences.is_empty() && (anchor.is_none() || doc.body_offsets.is_empty()))
- || (!matches!(plane, PlaneRef::Face { .. }) && anchor.is_none() && sketch.links.is_empty())
- {
- return 0;
+ for name in &reads.bodies {
+ name.hash(&mut h);
+ match st.and_then(|st| st.body(name)) {
+ Some(b) => hash_placement(&crate::mat_mul(&inverse, &body_world(doc, b)), &mut h),
+ None => u8::MAX.hash(&mut h),
+ }
+ }
+ // Legacy and component-wide reads still need the conservative offset dependency. Body
+ // reads above already include just their own offsets, in the frame that evaluates them.
+ if reads.all || !reads.components.is_empty() || !reads.paths.is_empty() {
+ serde_json::to_string(&doc.body_offsets).unwrap_or_default().hash(&mut h);
}
- placements_hash(doc)
+ // Never 0: the feature reads placements.
+ h.finish() | 1
}
-/// Every occurrence's placement and every body offset.
+/// Every occurrence's placement and every body offset (a feature read from a frame that cannot
+/// be inverted).
fn placements_hash(doc: &Document) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
for o in &doc.occurrences {
@@ -1463,7 +1667,8 @@ impl Model {
let marker = doc.marker.unwrap_or(usize::MAX);
let mut prev_fp = first.checked_sub(1).and_then(|i| self.results.get(i)).map_or(0, |r| r.fingerprint);
for (i, f) in doc.features.iter().enumerate().skip(first) {
- prev_fp = chain_fingerprint(doc, &vals, f, prev_fp, i >= marker, &steps);
+ let before = self.state_before(f.id);
+ prev_fp = chain_fingerprint(doc, &vals, f, prev_fp, i >= marker, &steps, Some(&before));
if let Some(r) = self.results.get_mut(i).filter(|r| r.id == f.id) {
r.fingerprint = prev_fp;
}
@@ -1504,12 +1709,31 @@ impl Model {
let steps = StepDigests::of(doc, &self.step_digests);
let marker = doc.marker.unwrap_or(usize::MAX);
let mut prev = 0;
+ // The model each feature starts from (which components the bodies it names are in).
+ let mut state = self.empty.clone();
doc.features.iter().zip(&self.results).enumerate().all(|(i, (f, r))| {
- prev = chain_fingerprint(doc, &vals, f, prev, i >= marker, &steps);
+ prev = chain_fingerprint(doc, &vals, f, prev, i >= marker, &steps, Some(&state));
+ if !r.skipped {
+ state = r.state.clone();
+ }
r.id == f.id && r.fingerprint == prev
})
}
+ /// Take the results `ahead` (a copy of this model, evaluated off this thread for the same
+ /// commands) computed: until [`Model::unprime`], `evaluate` reuses each one whose feature
+ /// has the same inputs here, instead of evaluating it again. Results that don't match are
+ /// ignored, so a design changed meanwhile is evaluated as usual.
+ pub fn prime(&mut self, ahead: &Model) {
+ let results = ahead.results.iter().filter(|r| !r.skipped && !r.stale).map(|r| (r.id, r.clone())).collect();
+ self.primed = Some((ahead.context, Arc::new(results)));
+ }
+
+ /// Stop offering the results [`Model::prime`] took.
+ pub fn unprime(&mut self) {
+ self.primed = None;
+ }
+
/// Re-evaluate the document, reusing results up to the first changed feature.
pub fn evaluate(&mut self, doc: &Document) {
let (vals, perr) = evaluation_values(doc);
@@ -1522,7 +1746,9 @@ impl Model {
let mut restored = 0;
let marker = doc.marker.unwrap_or(usize::MAX);
let ctx = context_digest(doc, &vals);
+ self.context = ctx;
self.step_digests = StepDigests::of(doc, &self.step_digests);
+ let primed = self.primed.as_ref().filter(|(context, _)| !self.no_cache && *context == ctx).map(|(_, results)| results.clone());
// Each feature's component, for `Document::legacy_body_component` on every body after
// every feature without searching the timeline for each (the first feature with an id).
let mut feature_component: std::collections::HashMap<u64, u64> = std::collections::HashMap::with_capacity(doc.features.len());
@@ -1534,7 +1760,7 @@ impl Model {
let rolled_back = i >= marker;
// Opening was cancelled: the rest is skipped and the result discarded.
let cancelled = watched.step(i);
- let fp = chain_fingerprint(doc, &vals, f, prev_fp, rolled_back, &self.step_digests);
+ let fp = chain_fingerprint(doc, &vals, f, prev_fp, rolled_back, &self.step_digests, Some(&state));
prev_fp = fp;
if reuse
&& let Some(old) = self.results.get(i)
@@ -1565,7 +1791,7 @@ impl Model {
continue;
}
// The same feature on the same inputs: its earlier result.
- let key = cache_key(f, fp, fingerprint(0, f, &vals, false, &self.step_digests) ^ placement_digest(doc, f), ctx, &state);
+ let key = cache_key(f, fp, fingerprint(0, f, &vals, false, &self.step_digests) ^ placement_digest(doc, f, Some(&state)), ctx, &state);
let kept = self.kept.0.as_ref().filter(|_| !self.no_cache);
if !self.no_cache
&& let Some(c) = self.cache.lock().ok().and_then(|mut m| m.get(key)).or_else(|| kept.and_then(|k| k.get(key)))
@@ -1591,6 +1817,15 @@ impl Model {
});
continue;
}
+ // Evaluated ahead on these same inputs (the same chain of definitions from the start).
+ if let Some(r) = primed.as_ref().and_then(|p| p.get(&f.id)).filter(|r| r.fingerprint == fp && !r.stale && !r.skipped) {
+ restored += 1;
+ if r.error.is_none() {
+ state = r.state.clone();
+ }
+ out.push(FeatureResult { state: state.clone(), ..r.clone() });
+ continue;
+ }
recomputed += 1;
let t0 = now();
let mut next = (*state).clone();
@@ -1831,9 +2066,12 @@ impl Model {
let marker = doc.marker.unwrap_or(usize::MAX);
self.step_digests = StepDigests::of(doc, &self.step_digests);
let mut prev = 0;
+ // Each feature's fingerprint reads the model it starts from, as evaluating does.
+ let mut before = Arc::new(ModelState::default());
for (i, (r, f)) in self.results.iter_mut().zip(&doc.features).enumerate() {
- prev = chain_fingerprint(doc, &vals, f, prev, i >= marker, &self.step_digests);
+ prev = chain_fingerprint(doc, &vals, f, prev, i >= marker, &self.step_digests, Some(&before));
r.fingerprint = prev;
+ before = r.state.clone();
}
}
}
@@ -6463,25 +6701,6 @@ impl Drop for ToolFrames {
}
}
-/// [`placement_digest`] of a feature with drawn tools: the placements, when it names the bodies
-/// it changes (they may lie in another component, where its tools meet them, #3383); nothing
-/// otherwise, as it then changes only bodies of its own component.
-fn drawn_tools_digest(doc: &Document, f: &Feature) -> u64 {
- let targets = match &f.kind {
- FeatureKind::Extrude { targets, .. }
- | FeatureKind::Revolve { targets, .. }
- | FeatureKind::Loft { targets, .. }
- | FeatureKind::Sweep { targets, .. }
- | FeatureKind::Pipe { targets, .. }
- | FeatureKind::Coil { targets, .. } => !targets.is_empty(),
- _ => false,
- };
- if (!targets && f.participants.is_empty()) || (doc.occurrences.is_empty() && doc.body_offsets.is_empty()) {
- return 0;
- }
- placements_hash(doc)
-}
-
/// The matrix taking the evaluated feature's drawn tools into body `name`'s frame (`None`: the
/// same frame).
fn tool_frame(name: &str) -> Option<Mat> {
diff --git a/crates/doc/src/model_cache.rs b/crates/doc/src/model_cache.rs
index fbd49f87be..d2f0f732f2 100644
--- a/crates/doc/src/model_cache.rs
+++ b/crates/doc/src/model_cache.rs
@@ -380,7 +380,7 @@ impl Model {
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);
+ prev = chain_fingerprint(doc, &vals, f, prev, i >= marker, &step_digests, Some(&before));
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"));
}
@@ -403,7 +403,7 @@ impl Model {
// 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);
+ let local = fingerprint(0, f, &vals, false, &step_digests) ^ placement_digest(doc, f, Some(&before));
cache.put(
cache_key(f, prev, local, ctx, &before),
CachedEval {
diff --git a/crates/engine/src/cmd/contact_sweep.rs b/crates/engine/src/cmd/contact_sweep.rs
index e253aea34d..e9a3593a21 100644
--- a/crates/engine/src/cmd/contact_sweep.rs
+++ b/crates/engine/src/cmd/contact_sweep.rs
@@ -32,6 +32,65 @@ struct CachedBody {
chord: f64,
}
+/// Bodies [`ContactMeshes`] keeps; it starts over when full.
+const MAX_CACHED_MESHES: usize = 4 * MAX_BODIES;
+
+/// A body's contact mesh and what is measured on it, made once per body content.
+#[derive(Clone)]
+pub(crate) struct ContactMesh {
+ mesh: Arc<Mesh>,
+ chord: f64,
+ /// Its thinnest width across its facet directions (the sweep's step is a quarter of it).
+ thickness: f64,
+}
+
+/// Contact meshes by the body's geometry ([`solidcraft_doc::ModelBody::geometry_key`]), shared
+/// by a session and its scratch copies: driving a joint again meshes no body that did not change.
+#[derive(Default)]
+pub(crate) struct ContactMeshes(HashMap<u64, ContactMesh>);
+
+/// Tessellate `body` for contact checks and measure how thin it is.
+fn contact_mesh(body: &solidcraft_doc::ModelBody) -> Result<ContactMesh> {
+ let tolerance = (body.body.size() * 1e-3).max(1e-3);
+ let mesh = body.body.tessellate(tolerance)?;
+ if mesh.triangles.len() > MAX_TRIANGLES || mesh.positions.len().saturating_add(mesh.triangles.len().saturating_mul(4)) > 200_000 {
+ return Err(limit("body exceeds contact sweep tessellation budget"));
+ }
+ let extent = mesh.bounds().size();
+ // Whole-body widths along bounded distinct facet normals catch tilted
+ // plates without interpreting skinny mesh triangles as thin material.
+ // Local thin walls of a wider body remain a sampling limitation.
+ let mut thickness = extent.x.min(extent.y).min(extent.z);
+ let mut directions: Vec<Vec3> = Vec::new();
+ for triangle in &mesh.triangles {
+ let Some([a, b, c]) = mesh.tri(triangle) else {
+ return Err(limit("invalid contact tessellation"));
+ };
+ let Some(direction) = (b - a).cross(c - a).normalized() else { continue };
+ if directions.len() < 32 && !directions.iter().any(|d| d.dot(direction).abs() > 1.0 - 1e-6) {
+ directions.push(direction);
+ }
+ }
+ for direction in directions {
+ let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
+ for point in &mesh.positions {
+ let projected = point.dot(direction);
+ low = low.min(projected);
+ high = high.max(projected);
+ }
+ thickness = thickness.min(high - low);
+ }
+ if !thickness.is_finite() || thickness <= 1e-9 {
+ return Err(limit("body is too thin for a bounded contact sweep"));
+ }
+ // Flat faces tessellate exactly; only planes known from how the face was
+ // made count (an unknown face is taken as curved).
+ let faces = body.body.face_count();
+ let flat = faces <= 1024 && (0..faces).all(|i| body.body.face_plane(i).is_some());
+ let chord = if flat { 0.0 } else { tolerance };
+ Ok(ContactMesh { mesh: Arc::new(mesh), chord, thickness })
+}
+
/// A member of a contact set: (occurrence id, name).
pub(super) type Member = (u64, String);
@@ -90,47 +149,24 @@ impl ContactGeometry {
let (mesh, chord) = if let Some(cached) = meshes.get(&body.name) {
cached.clone()
} else {
- let tolerance = (body.body.size() * 1e-3).max(1e-3);
- let mesh = body.body.tessellate(tolerance)?;
- if mesh.triangles.len() > MAX_TRIANGLES || mesh.positions.len().saturating_add(mesh.triangles.len().saturating_mul(4)) > 200_000 {
- return Err(limit("body exceeds contact sweep tessellation budget"));
- }
- let extent = mesh.bounds().size();
- // Whole-body widths along bounded distinct facet normals catch tilted
- // plates without interpreting skinny mesh triangles as thin material.
- // Local thin walls of a wider body remain a sampling limitation.
- let mut thickness = extent.x.min(extent.y).min(extent.z);
- let mut directions: Vec<Vec3> = Vec::new();
- for triangle in &mesh.triangles {
- let Some([a, b, c]) = mesh.tri(triangle) else {
- return Err(limit("invalid contact tessellation"));
- };
- let Some(direction) = (b - a).cross(c - a).normalized() else { continue };
- if directions.len() < 32 && !directions.iter().any(|d| d.dot(direction).abs() > 1.0 - 1e-6) {
- directions.push(direction);
- }
- }
- for direction in directions {
- let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
- for point in &mesh.positions {
- let projected = point.dot(direction);
- low = low.min(projected);
- high = high.max(projected);
+ let key = body.geometry_key();
+ let known = key.and_then(|k| s.contact_meshes.lock().ok().and_then(|c| c.0.get(&k).cloned()));
+ let made = match known {
+ Some(made) => made,
+ None => {
+ let made = contact_mesh(body)?;
+ if let (Some(k), Ok(mut cache)) = (key, s.contact_meshes.lock()) {
+ if cache.0.len() >= MAX_CACHED_MESHES {
+ cache.0.clear();
+ }
+ cache.0.insert(k, made.clone());
+ }
+ made
}
- thickness = thickness.min(high - low);
- }
- if !thickness.is_finite() || thickness <= 1e-9 {
- return Err(limit("body is too thin for a bounded contact sweep"));
- }
- out.step = out.step.min(thickness * 0.25);
- let mesh = Arc::new(mesh);
- // Flat faces tessellate exactly; only planes known from how the face was
- // made count (an unknown face is taken as curved).
- let faces = body.body.face_count();
- let flat = faces <= 1024 && (0..faces).all(|i| body.body.face_plane(i).is_some());
- let chord = if flat { 0.0 } else { tolerance };
- meshes.insert(body.name.clone(), (mesh.clone(), chord));
- (mesh, chord)
+ };
+ out.step = out.step.min(made.thickness * 0.25);
+ meshes.insert(body.name.clone(), (made.mesh.clone(), made.chord));
+ (made.mesh, made.chord)
};
out.bodies.push(CachedBody {
path: path.clone(),
diff --git a/crates/engine/src/cmd/contact_sweep_tests.rs b/crates/engine/src/cmd/contact_sweep_tests.rs
index 096731b466..79e8bfd2a4 100644
--- a/crates/engine/src/cmd/contact_sweep_tests.rs
+++ b/crates/engine/src/cmd/contact_sweep_tests.rs
@@ -26,6 +26,24 @@ fn rail_value(s: &Session) -> f64 {
s.doc.assembly.joints.iter().find(|j| j.name == "Rail").unwrap().values[0]
}
+#[test]
+fn joint_pose_contact_reuses_reference_geometry_across_new_placements() {
+ let mut s = slider();
+ // Measure the swept-contact geometry factory, separately from other joint work.
+ super::ContactGeometry::new(&s).unwrap();
+ for value in [11., 12., 13., 14.] {
+ let result = run(&mut s, "joint.drive", json!({"joint":"Rail","value":value}));
+ let (_, work) = crate::kernel::profile::capture(|| super::ContactGeometry::new(&s).unwrap());
+ assert!(result["stopped_by_contact"].is_null(), "{result}");
+ assert!((rail_value(&s) - value).abs() < 1e-8);
+ assert_eq!(work.tessellate_ms, 0., "unchanged contact bodies were tessellated for slider value {value}");
+ }
+ // Reusing geometry must still stop a genuine collision, including an endpoint beyond it.
+ let result = run(&mut s, "joint.drive", json!({"joint":"Rail","value":-30}));
+ assert!(result["stopped_by_contact"].is_object(), "{result}");
+ assert!(rail_value(&s).abs() < 2e-3);
+}
+
#[test]
fn slider_cannot_tunnel_to_a_collision_free_endpoint() {
let mut s = slider();
@@ -39,6 +57,28 @@ fn slider_cannot_tunnel_to_a_collision_free_endpoint() {
assert!((rail_value(&s) + 100000.0).abs() < 1e-6, "disabled contact skips sweep budget");
}
+/// Each drive with contact on meshed every body in a contact set again: a body that did not
+/// change keeps its contact mesh across drives (and scratch copies), a changed one is meshed anew.
+#[test]
+fn contact_meshes_are_made_once_per_body() {
+ let mut s = slider();
+ let meshes = |s: &Session| super::ContactGeometry::new(s).unwrap().bodies.iter().map(|b| b.mesh.clone()).collect::<Vec<_>>();
+ let first = meshes(&s);
+ assert_eq!(first.len(), 2);
+ run(&mut s, "joint.drive", json!({"joint": "Rail", "value": 5}));
+ let scratch = s.scratch();
+ for again in [meshes(&s), meshes(&scratch)] {
+ assert!(first.iter().zip(&again).all(|(a, b)| std::sync::Arc::ptr_eq(a, b)), "the same meshes, not tessellated again");
+ }
+ // A body that changed is meshed for what it is now.
+ run(&mut s, "component.activate", json!({"component": "B"}));
+ run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [24, 4, 10], "operation": "join"}));
+ run(&mut s, "component.activate", json!({"component": 0}));
+ let changed = meshes(&s);
+ assert!(changed.iter().zip(&first).any(|(a, b)| !std::sync::Arc::ptr_eq(a, b)));
+ assert!(changed.iter().map(|m| m.bounds().max.z).fold(0.0, f64::max) > 11.0, "the joined box is in the contact mesh");
+}
+
#[test]
fn revolute_cannot_cross_a_blocker_between_clear_endpoints() {
let mut s = Session::default();
diff --git a/crates/engine/src/cmd/motion.rs b/crates/engine/src/cmd/motion.rs
index e49e973348..0f81069947 100644
--- a/crates/engine/src/cmd/motion.rs
+++ b/crates/engine/src/cmd/motion.rs
@@ -19,7 +19,7 @@ mod analysis;
#[path = "motion_animation.rs"]
mod animation;
#[path = "contact_sweep.rs"]
-mod contact_sweep;
+pub(crate) mod contact_sweep;
#[path = "motion_sweep.rs"]
mod sweep;
diff --git a/crates/engine/src/cmd/motion_tests.rs b/crates/engine/src/cmd/motion_tests.rs
index 5d7594f7ca..b860a044be 100644
--- a/crates/engine/src/cmd/motion_tests.rs
+++ b/crates/engine/src/cmd/motion_tests.rs
@@ -20,6 +20,416 @@ fn b_x(s: &Session) -> f64 {
super::world_point(s, occ(s, "B"), Vec3::new(20.0, 0.0, 0.0)).x
}
+#[derive(Clone, Copy)]
+enum PartAuthoring {
+ RootThenTransfer,
+ RootThenNestedTransfer,
+ InComponent,
+}
+
+#[derive(Clone, Copy)]
+enum JoinSelection {
+ Named,
+ Implicit,
+ All,
+}
+
+/// A boolean authored before a later transfer still reads the bodies in its timeline input,
+/// not their final owners. Explicit targets must not turn every occurrence into an input.
+fn joined_motion_part(authoring: PartAuthoring, selection: JoinSelection) -> Session {
+ let mut s = Session::default();
+ if matches!(authoring, PartAuthoring::InComponent) {
+ run(&mut s, "component.create", json!({"name":"Rotor"}));
+ }
+ run(&mut s, "solid.box", json!({"length":10,"width":8,"height":6,"body_name":"Part","name":"Base"}));
+ run(&mut s, "select.set", json!({"items":[]}));
+ let mut p = json!({"length":6,"width":4,"height":4,"corner":[8,2,1],"operation":"join","name":"Boss"});
+ match selection {
+ JoinSelection::Named => p["targets"] = json!(["Part"]),
+ JoinSelection::All => p["targets"] = json!(["*"]),
+ JoinSelection::Implicit => {}
+ }
+ run(&mut s, "solid.box", p);
+ if !matches!(authoring, PartAuthoring::InComponent) {
+ let parent = if matches!(authoring, PartAuthoring::RootThenNestedTransfer) {
+ run(&mut s, "component.create", json!({"name":"Group","activate":false}));
+ "Group"
+ } else {
+ "root"
+ };
+ run(&mut s, "component.create", json!({"name":"Rotor","parent":parent,"activate":false}));
+ run(&mut s, "component.move_bodies", json!({"bodies":["Part"],"component":"Rotor"}));
+ }
+ let driven = if matches!(authoring, PartAuthoring::RootThenNestedTransfer) { "Group" } else { "Rotor" };
+ attach_motion_rotor(&mut s, driven, "Turn");
+ s
+}
+
+fn attach_motion_rotor(s: &mut Session, component: &str, joint: &str) {
+ run(s, "component.activate", json!({"component":"root"}));
+ run(s, "joint.as_built", json!({"type":"revolute","name":joint,"a":0,"b":component,"at":{"occurrence":0,"point":[0,0,0],"z":[0,0,1]}}));
+}
+
+fn unrelated_motion_rotor(s: &mut Session) {
+ run(s, "component.activate", json!({"component":"root"}));
+ run(s, "component.create", json!({"name":"Unrelated"}));
+ run(s, "solid.box", json!({"length":2,"width":2,"height":2,"corner":[100,100,100],"body_name":"Remote"}));
+ attach_motion_rotor(s, "Unrelated", "Other turn");
+}
+
+/// Test work and identity, not elapsed time. Every first visit to an angle must preserve the
+/// definitions and their warm meshes, even across full turns; returning to a cached pose alone
+/// would miss the regression. The world mesh is still in the new physical position.
+fn assert_joint_only_moves(s: &mut Session, joint: &str) {
+ use std::sync::Arc;
+ let definitions = s.model.state();
+ let meshes: Vec<_> = definitions.bodies.iter().map(|b| b.mesh()).collect();
+ for body in &s.world_state().bodies {
+ std::hint::black_box(body.mesh());
+ std::hint::black_box(body.display_plan());
+ }
+ let joints = run(s, "joint.list", json!({"quiet":true}));
+ let base = joints["joints"].as_array().unwrap().iter().find(|j| j["name"] == joint).unwrap()["values"][0]["value"].as_f64().unwrap();
+ for offset in [5., 10., 15., 37., 91., 365., 721., 12418., 12423., 37., 0.] {
+ let angle = base + offset;
+ let r = run(s, "joint.drive", json!({"joint":joint,"value":angle,"quiet":true}));
+ assert_eq!(r["moved"], true, "{r}");
+ assert!(r["stopped_by_loop"].is_null() && r["stopped_by_contact"].is_null(), "{r}");
+ let joints = run(s, "joint.list", json!({"quiet":true}));
+ let actual = joints["joints"].as_array().unwrap().iter().find(|j| j["name"] == joint).unwrap()["values"][0]["value"].as_f64().unwrap();
+ assert!((actual - angle).abs() < 1e-8, "{joint} did not reach {angle}: {actual}");
+ assert_eq!(s.model.last_recomputed, 0, "{joint} at {angle}: unchanged geometry was evaluated again");
+ let current = s.model.state();
+ assert!(Arc::ptr_eq(&definitions, &current), "{joint} at {angle}: definition state replaced");
+ for (b, mesh) in current.bodies.iter().zip(&meshes) {
+ assert!(Arc::ptr_eq(&b.mesh(), mesh), "{}: canonical mesh replaced", b.name);
+ }
+ let world = s.world_state();
+ let (_, work) = crate::kernel::profile::capture(|| {
+ for b in &world.bodies {
+ let local = definitions.body(b.definition_name()).unwrap().mesh();
+ let placed = b.mesh();
+ assert_eq!(placed.triangles, local.triangles);
+ assert_eq!(placed.tri_face, local.tri_face);
+ assert_eq!(placed.positions.len(), local.positions.len());
+ assert_eq!(placed.normals.len(), local.normals.len());
+ for (p, q) in local.positions.iter().zip(&placed.positions) {
+ assert!(crate::doc::apply_point(&b.source_transform, *p).dist(*q) < 1e-8);
+ }
+ for (n, q) in local.normals.iter().zip(&placed.normals) {
+ assert!(crate::doc::apply_vector(&b.source_transform, *n).dist(*q) < 1e-8);
+ }
+ }
+ });
+ assert_eq!(work.tessellate_ms, 0., "{joint} at {angle}: reference tessellation ran");
+ }
+}
+
+fn assert_motion_matches_full_rebuild(s: &Session) {
+ let mut full = crate::doc::Model::default();
+ full.no_cache = true;
+ full.evaluate(&s.doc);
+ assert!(full.results.iter().all(|r| r.error.is_none()), "{:?}", full.results.iter().filter_map(|r| r.error.as_ref()).collect::<Vec<_>>());
+ let (cached, fresh) = (s.model.state(), full.state());
+ assert_eq!(cached.bodies.len(), fresh.bodies.len());
+ for (a, b) in cached.bodies.iter().zip(&fresh.bodies) {
+ assert_eq!(a.name, b.name);
+ assert_eq!(a.body.face_count(), b.body.face_count(), "{}", a.name);
+ let (a_bounds, b_bounds) = (a.mesh().bounds(), b.mesh().bounds());
+ assert!(a_bounds.min.dist(b_bounds.min) < 1e-8 && a_bounds.max.dist(b_bounds.max) < 1e-8, "{}", a.name);
+ let (a_mass, b_mass) = (crate::kernel::measure(&a.body).unwrap(), crate::kernel::measure(&b.body).unwrap());
+ assert!((a_mass.volume - b_mass.volume).abs() < 1e-6, "{}: {} vs {}", a.name, a_mass.volume, b_mass.volume);
+ }
+}
+
+#[test]
+fn joint_pose_named_union_before_transfer_retains_definitions() {
+ assert_joint_only_moves(&mut joined_motion_part(PartAuthoring::RootThenTransfer, JoinSelection::Named), "Turn");
+}
+
+#[test]
+fn joint_pose_joined_cylinders_keep_mesh_cells_at_unseen_angles() {
+ let mut s = Session::default();
+ run(&mut s, "solid.cylinder", json!({"radius":8.5,"height":8,"base":[0,32,0],"axis":[0,1,0],"operation":"new","body_name":"Crank"}));
+ run(
+ &mut s,
+ "solid.cylinder",
+ json!({"radius":2.8,"height":30,"base":[0,36,0],"axis":[0.981627183447664,0,0.1908089953765448],"operation":"join","targets":["Crank"]}),
+ );
+ run(&mut s, "component.create", json!({"name":"Crank","activate":false}));
+ run(&mut s, "component.move_bodies", json!({"bodies":["Crank"],"component":"Crank"}));
+ run(&mut s, "joint.as_built", json!({"type":"revolute","name":"Crank","a":0,"b":"Crank","at":{"occurrence":0,"point":[0,0,0],"z":[0,1,0]}}));
+ assert_joint_only_moves(&mut s, "Crank");
+}
+
+#[test]
+fn joint_pose_named_union_in_its_component_retains_definitions() {
+ assert_joint_only_moves(&mut joined_motion_part(PartAuthoring::InComponent, JoinSelection::Named), "Turn");
+}
+
+#[test]
+fn joint_pose_nested_body_transfer_ignores_ancestor_motion() {
+ assert_joint_only_moves(&mut joined_motion_part(PartAuthoring::RootThenNestedTransfer, JoinSelection::Named), "Turn");
+}
+
+#[test]
+fn joint_pose_second_occurrence_shares_the_definition() {
+ let mut s = joined_motion_part(PartAuthoring::InComponent, JoinSelection::Named);
+ let second = run(&mut s, "occurrence.copy", json!({"component":"Rotor","translate":[40,0,0]}))["occurrence"].as_u64().unwrap();
+ run(&mut s, "joint.as_built", json!({"type":"revolute","name":"Copy turn","a":0,"b":second,"at":{"occurrence":0,"point":[40,0,0],"z":[0,0,1]}}));
+ assert_eq!(s.world_state().bodies.len(), 2);
+ assert_joint_only_moves(&mut s, "Copy turn");
+ assert_motion_matches_full_rebuild(&s);
+}
+
+#[test]
+fn joint_pose_implicit_union_in_its_component_retains_definitions() {
+ assert_joint_only_moves(&mut joined_motion_part(PartAuthoring::InComponent, JoinSelection::Implicit), "Turn");
+}
+
+#[test]
+fn joint_pose_unrelated_part_does_not_invalidate_named_union() {
+ let mut s = joined_motion_part(PartAuthoring::RootThenTransfer, JoinSelection::Named);
+ unrelated_motion_rotor(&mut s);
+ assert_joint_only_moves(&mut s, "Other turn");
+}
+
+#[test]
+fn joint_pose_future_body_is_not_an_input_of_an_earlier_wildcard_union() {
+ let mut s = joined_motion_part(PartAuthoring::RootThenTransfer, JoinSelection::All);
+ unrelated_motion_rotor(&mut s);
+ assert_joint_only_moves(&mut s, "Other turn");
+}
+
+#[test]
+fn joint_pose_empty_cache_keeps_unchanged_definition_results() {
+ let mut s = joined_motion_part(PartAuthoring::RootThenTransfer, JoinSelection::Named);
+ *s.model.cache.lock().unwrap() = Default::default();
+ assert_joint_only_moves(&mut s, "Turn");
+}
+
+#[test]
+fn joint_pose_explicit_extrude_targets_ignore_unrelated_motion() {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Base"}));
+ run(&mut s, "sketch.create", json!({"plane":"XY","name":"BossOutline"}));
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0":[8,2],"p1":[14,6]}));
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "solid.extrude", json!({"sketch":"BossOutline","distance":3,"operation":"join","targets":["Base"],"name":"Boss"}));
+ unrelated_motion_rotor(&mut s);
+ assert_joint_only_moves(&mut s, "Other turn");
+}
+
+#[test]
+fn joint_pose_combine_ignores_unrelated_motion() {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Base"}));
+ run(&mut s, "solid.box", json!({"length":2,"width":2,"height":2,"corner":[4,4,9],"body_name":"Boss","operation":"new"}));
+ run(&mut s, "solid.combine", json!({"target":"Base","tools":["Boss"],"operation":"join"}));
+ unrelated_motion_rotor(&mut s);
+ assert_joint_only_moves(&mut s, "Other turn");
+}
+
+/// A fixed tool removes the top 5 mm of the target where x=8..12. Sliding the target
+/// relative to it changes the removed volume from 100 to 200 mm³. Moving the tool together
+/// with the target preserves that volume and must preserve the computed definition too.
+fn cross_component_motion_cut(move_tool_with_target: bool, kind: &str) -> Session {
+ let mut s = Session::default();
+ run(&mut s, "component.create", json!({"name":"MovingTarget"}));
+ run(&mut s, "solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Target"}));
+ run(&mut s, "component.activate", json!({"component":"root"}));
+ if move_tool_with_target {
+ run(&mut s, "component.create", json!({"name":"Tool"}));
+ }
+ run(&mut s, "solid.box", json!({"length":4,"width":12,"height":6,"corner":[8,-1,5],"operation":"cut","targets":["Target"],"name":"Notch"}));
+ run(&mut s, "component.activate", json!({"component":"root"}));
+ let axis = if kind == "slider" { json!([1, 0, 0]) } else { json!([0, 0, 1]) };
+ run(&mut s, "joint.as_built", json!({"type":kind,"name":"Motion","a":0,"b":"MovingTarget","at":{"occurrence":0,"point":[0,0,0],"z":axis}}));
+ if move_tool_with_target {
+ run(&mut s, "joint.rigid_group", json!({"occurrences":["MovingTarget","Tool"]}));
+ }
+ s
+}
+
+fn motion_target_volume(s: &Session) -> f64 {
+ crate::kernel::measure(&s.model.state().body("Target").unwrap().body).unwrap().volume
+}
+
+fn motion_combine_cut(kind: &str, together: bool) -> Session {
+ let mut s = Session::default();
+ run(&mut s, "component.create", json!({"name":"MovingTarget"}));
+ run(&mut s, "solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Target"}));
+ run(&mut s, "component.activate", json!({"component":"root"}));
+ run(&mut s, "component.create", json!({"name":"Tool"}));
+ run(&mut s, "solid.box", json!({"length":4,"width":12,"height":6,"corner":[8,-1,5],"body_name":"Cutter","operation":"new"}));
+ run(&mut s, "component.activate", json!({"component":"root"}));
+ run(&mut s, "solid.combine", json!({"target":"Target","tools":["Cutter"],"operation":"cut"}));
+ let axis = if kind == "slider" { json!([1, 0, 0]) } else { json!([0, 0, 1]) };
+ run(&mut s, "joint.as_built", json!({"type":kind,"name":"Motion","a":0,"b":"MovingTarget","at":{"occurrence":0,"point":[0,0,0],"z":axis}}));
+ if together {
+ run(&mut s, "joint.rigid_group", json!({"occurrences":["MovingTarget","Tool"]}));
+ }
+ s
+}
+
+#[test]
+fn joint_pose_combine_common_motion_keeps_the_target_frame() {
+ let mut s = motion_combine_cut("revolute", true);
+ assert_joint_only_moves(&mut s, "Motion");
+ assert!((motion_target_volume(&s) - 900.).abs() < 1e-6);
+ assert_motion_matches_full_rebuild(&s);
+}
+
+#[test]
+fn joint_pose_combine_relative_motion_rebuilds_the_cut() {
+ let mut s = motion_combine_cut("slider", false);
+ assert!((motion_target_volume(&s) - 900.).abs() < 1e-6);
+ run(&mut s, "joint.drive", json!({"joint":"Motion","value":5}));
+ let volume = motion_target_volume(&s);
+ assert!((volume - 800.).abs() < 1e-6, "Combine must follow relative motion: {volume}");
+ assert_motion_matches_full_rebuild(&s);
+}
+
+#[test]
+fn joint_pose_target_body_offset_rebuilds_the_cut() {
+ let mut s = cross_component_motion_cut(false, "slider");
+ assert!((motion_target_volume(&s) - 900.).abs() < 1e-6);
+ let mut offset = crate::doc::IDENTITY;
+ offset[3][0] = 5.;
+ s.doc_mut().body_offsets.insert("Target".into(), offset);
+ s.refresh();
+ let volume = motion_target_volume(&s);
+ assert!((volume - 800.).abs() < 1e-6, "the input body's offset changes the tool frame: {volume}");
+ assert_motion_matches_full_rebuild(&s);
+}
+
+#[test]
+fn joint_pose_unrelated_body_offset_keeps_named_union() {
+ let mut s = joined_motion_part(PartAuthoring::RootThenTransfer, JoinSelection::Named);
+ unrelated_motion_rotor(&mut s);
+ let before = s.model.state();
+ let mut offset = crate::doc::IDENTITY;
+ offset[3][0] = 5.;
+ s.doc_mut().body_offsets.insert("Remote".into(), offset);
+ s.refresh();
+ assert_eq!(s.model.last_recomputed, 0);
+ assert!(std::sync::Arc::ptr_eq(&before, &s.model.state()));
+ assert_motion_matches_full_rebuild(&s);
+}
+
+#[test]
+fn joint_pose_implicit_union_reads_its_target_body_offset() {
+ let mut s = joined_motion_part(PartAuthoring::InComponent, JoinSelection::Implicit);
+ let volume = |s: &Session| crate::kernel::measure(&s.model.state().body("Part").unwrap().body).unwrap().volume;
+ assert!((volume(&s) - 544.).abs() < 1e-6);
+ let mut offset = crate::doc::IDENTITY;
+ offset[3][0] = 5.;
+ s.doc_mut().body_offsets.insert("Part".into(), offset);
+ s.refresh();
+ assert!((volume(&s) - 480.).abs() < 1e-6, "the join's tool is now entirely inside its target: {}", volume(&s));
+ assert_motion_matches_full_rebuild(&s);
+}
+
+#[test]
+fn joint_pose_true_relative_target_motion_rebuilds_the_cut() {
+ let mut s = cross_component_motion_cut(false, "slider");
+ assert!((motion_target_volume(&s) - 900.).abs() < 1e-6);
+ run(&mut s, "joint.drive", json!({"joint":"Motion","value":5}));
+ let volume = motion_target_volume(&s);
+ assert!((volume - 800.).abs() < 1e-6, "relative motion should leave 800 mm³, got {volume}");
+ assert!(s.model.last_recomputed > 0, "a target moved relative to its tool");
+ assert_motion_matches_full_rebuild(&s);
+}
+
+#[test]
+fn joint_pose_shared_rigid_motion_keeps_the_cut_definition() {
+ let mut s = cross_component_motion_cut(true, "slider");
+ assert!((motion_target_volume(&s) - 900.).abs() < 1e-6);
+ let before = s.model.state();
+ run(&mut s, "joint.drive", json!({"joint":"Motion","value":5}));
+ assert_eq!(s.model.last_recomputed, 0, "relative target/tool placement did not change");
+ assert!(std::sync::Arc::ptr_eq(&before, &s.model.state()));
+ assert!((motion_target_volume(&s) - 900.).abs() < 1e-6);
+ assert_motion_matches_full_rebuild(&s);
+}
+
+#[test]
+fn joint_pose_shared_rotation_preserves_relative_cut_geometry() {
+ let mut s = cross_component_motion_cut(true, "revolute");
+ assert_joint_only_moves(&mut s, "Motion");
+ assert!((motion_target_volume(&s) - 900.).abs() < 1e-6);
+ assert_motion_matches_full_rebuild(&s);
+}
+
+#[test]
+fn joint_pose_primed_ahead_result_does_not_replace_unchanged_geometry() {
+ let mut s = joined_motion_part(PartAuthoring::RootThenTransfer, JoinSelection::Named);
+ let definitions = s.model.state();
+ let mesh = definitions.body("Part").unwrap().mesh();
+ let commands = [("joint.drive".into(), json!({"joint":"Turn","value":5,"quiet":true}))];
+ let evaluated = s.ahead().evaluate(&commands).unwrap();
+ *s.model.cache.lock().unwrap() = Default::default();
+ s.prime(&evaluated);
+ run(&mut s, &commands[0].0, commands[0].1.clone());
+ s.unprime();
+ assert!(std::sync::Arc::ptr_eq(&definitions, &s.model.state()), "computing ahead must not replace an unchanged definition");
+ assert!(std::sync::Arc::ptr_eq(&mesh, &s.model.state().body("Part").unwrap().mesh()));
+ assert_motion_matches_full_rebuild(&s);
+}
+
+#[test]
+fn joint_pose_save_and_reopen_keep_definitions_at_new_angles() {
+ let mut s = joined_motion_part(PartAuthoring::RootThenTransfer, JoinSelection::Named);
+ run(&mut s, "joint.drive", json!({"joint":"Turn","value":5}));
+ let directory = std::env::temp_dir().join(format!(
+ "solidcraft-joint-pose-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
+ ));
+ std::fs::create_dir(&directory).unwrap();
+ let path = directory.join("part.solidcraft");
+ run(&mut s, "file.save", json!({"path":path,"cache":true,"preview":true}));
+ let mut opened = Session::default();
+ run(&mut opened, "doc.open", json!({"path":path}));
+ std::fs::remove_file(&path).unwrap();
+ std::fs::remove_dir(&directory).unwrap();
+ assert_motion_matches_full_rebuild(&opened);
+ assert_joint_only_moves(&mut opened, "Turn");
+}
+
+#[test]
+fn joint_pose_undo_and_redo_match_fresh_geometry() {
+ let mut s = joined_motion_part(PartAuthoring::RootThenTransfer, JoinSelection::Named);
+ for angle in [5, 10] {
+ run(&mut s, "joint.drive", json!({"joint":"Turn","value":angle}));
+ }
+ run(&mut s, "edit.undo", json!({}));
+ let joints = run(&mut s, "joint.list", json!({"quiet":true}));
+ assert!((joints["joints"][0]["values"][0]["value"].as_f64().unwrap() - 5.).abs() < 1e-8);
+ assert_motion_matches_full_rebuild(&s);
+ run(&mut s, "edit.redo", json!({}));
+ let joints = run(&mut s, "joint.list", json!({"quiet":true}));
+ assert!((joints["joints"][0]["values"][0]["value"].as_f64().unwrap() - 10.).abs() < 1e-8);
+ assert_motion_matches_full_rebuild(&s);
+}
+
+#[test]
+fn joint_pose_geometry_edit_invalidates_the_warm_definition_mesh() {
+ let mut s = Session::default();
+ run(&mut s, "parameters.add", json!({"name":"span","expression":"10 mm"}));
+ run(&mut s, "component.create", json!({"name":"Rotor"}));
+ run(&mut s, "solid.box", json!({"length":"span","width":8,"height":6,"body_name":"Part"}));
+ attach_motion_rotor(&mut s, "Rotor", "Turn");
+ run(&mut s, "joint.drive", json!({"joint":"Turn","value":5}));
+ let before = s.model.state().body("Part").unwrap().mesh();
+ run(&mut s, "parameters.change", json!({"name":"span","expression":"12 mm"}));
+ let model = s.model.state();
+ let body = model.body("Part").unwrap();
+ assert!(!std::sync::Arc::ptr_eq(&before, &body.mesh()));
+ assert!((crate::kernel::measure(&body.body).unwrap().volume - 576.).abs() < 1e-6);
+ assert_motion_matches_full_rebuild(&s);
+}
+
/// Cubes A (grounded, x 0…10) and B (x 20…30) on a slider along x: B's −x face on A's +x face
/// at value 0, B 10 mm away to start.
fn rail() -> Session {
@@ -456,3 +866,112 @@ fn hostile_animation_params_are_refused() {
assert!(root.join("in.gif").exists() && !dir.join("out").exists());
let _ = std::fs::remove_dir_all(&dir);
}
+
+/// A grounded Base plate, an Arm turning on it about Z (joint `Pivot`) and a Head fixed to the
+/// arm. The Arm's slot sketch projects the arm's own edge and its axis, the Head's bore sketch
+/// an edge of the arm (they move together). With `in_context`, the slot sketch also projects an
+/// edge of the Base, across the joint.
+fn pivot(in_context: bool) -> Session {
+ let mut s = Session::default();
+ run(&mut s, "component.create", json!({"name": "Base"}));
+ run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 10, "corner": [-20, -20, 0], "body_name": "Plate"}));
+ run(&mut s, "solid.chamfer", json!({"edges": [[0, -20, 10]], "distance": 1}));
+ run(&mut s, "component.activate", json!({"component": "root"}));
+ run(&mut s, "component.create", json!({"name": "Arm"}));
+ run(&mut s, "solid.box", json!({"length": 50, "width": 8, "height": 5, "corner": [-4, -4, 10], "body_name": "Bar"}));
+ run(&mut s, "sketch.create", json!({"plane": {"origin": [0, 0, 15], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}, "name": "Slot"}));
+ run(&mut s, "sketch.project", json!({"refs": [{"edge": [20, 4, 15], "body": "Bar"}, "origin"]}));
+ if in_context {
+ run(&mut s, "sketch.project", json!({"refs": [{"edge": [0, 20, 10], "body": "Plate"}]}));
+ }
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [20, -2], "p1": [30, 2]}));
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "solid.extrude", json!({"sketch": "Slot", "distance": -2, "operation": "cut", "name": "SlotCut"}));
+ run(&mut s, "solid.chamfer", json!({"edges": [[10, -4, 15]], "distance": 0.5}));
+ run(&mut s, "component.activate", json!({"component": "root"}));
+ run(&mut s, "component.create", json!({"name": "Head"}));
+ run(&mut s, "solid.box", json!({"length": 10, "width": 12, "height": 6, "corner": [36, -6, 15], "body_name": "Cap"}));
+ run(&mut s, "sketch.create", json!({"plane": {"origin": [0, 0, 21], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}, "name": "Bore"}));
+ run(&mut s, "sketch.project", json!({"refs": [{"edge": [40, 4, 15], "body": "Bar"}]}));
+ run(&mut s, "sketch.circle.center", json!({"center": [41, 0], "radius": 2}));
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "solid.extrude", json!({"sketch": "Bore", "distance": -4, "operation": "cut", "name": "BoreCut"}));
+ run(&mut s, "component.activate", json!({"component": "root"}));
+ let (base, arm, head) = (occ(&s, "Base"), occ(&s, "Arm"), occ(&s, "Head"));
+ run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": true}));
+ run(
+ &mut s,
+ "joint.create",
+ json!({"type": "revolute", "a": {"occurrence": base, "point": [0, 0, 10]}, "b": {"occurrence": arm, "point": [0, 0, 10]}, "flip": true, "name": "Pivot"}),
+ );
+ run(&mut s, "joint.rigid_group", json!({"occurrences": [arm, head]}));
+ s
+}
+
+/// Every body of `model` and `full` the same: names, faces and where their meshes lie.
+fn same_bodies(model: &solidcraft_doc::ModelState, full: &solidcraft_doc::ModelState) {
+ assert_eq!(model.bodies.len(), full.bodies.len());
+ for (a, b) in model.bodies.iter().zip(&full.bodies) {
+ assert_eq!(a.name, b.name);
+ assert_eq!(a.body.face_count(), b.body.face_count(), "{}", a.name);
+ let (m, n) = (a.mesh().bounds(), b.mesh().bounds());
+ assert!(m.min.dist(n.min) < 1e-9 && m.max.dist(n.max) < 1e-9, "{}: {m:?} vs {n:?}", a.name);
+ }
+}
+
+/// The model `s` shows, evaluated again from nothing.
+fn rebuilt(s: &Session) -> std::sync::Arc<solidcraft_doc::ModelState> {
+ let mut full = solidcraft_doc::Model::default();
+ full.no_cache = true;
+ full.evaluate(&s.doc);
+ full.state()
+}
+
+/// Driving a joint only moves parts: a part that projects its own geometry, or that of a part
+/// moving with it, is not evaluated again (#1989's motion on a finished assembly evaluated the
+/// whole timeline on every drive, and every new pose missed the cache).
+#[test]
+fn driving_a_joint_moves_parts_without_evaluating_them() {
+ let mut s = pivot(false);
+ let model = s.model.state();
+ let head = occ(&s, "Head");
+ let tip = |s: &Session| super::world_point(s, head, Vec3::new(46.0, 0.0, 15.0));
+ let before = tip(&s);
+ for (step, angle) in ["30 deg", "75 deg", "-40 deg", "75 deg"].into_iter().enumerate() {
+ let r = run(&mut s, "joint.drive", json!({"joint": "Pivot", "value": angle}));
+ assert_eq!(r["moved"], true, "{r}");
+ assert_eq!((s.model.last_recomputed, s.model.last_restored), (0, 0), "step {step}: nothing evaluated, nothing taken from the cache");
+ assert!(std::sync::Arc::ptr_eq(&model, &s.model.state()), "the parts' bodies are the ones they were");
+ }
+ // The head went round with the arm: 75° about Z through the origin.
+ let (sin, cos) = 75f64.to_radians().sin_cos();
+ let want = Vec3::new(before.x * cos - before.y * sin, before.x * sin + before.y * cos, before.z);
+ assert!(tip(&s).dist(want) < 1e-6, "{:?} vs {want:?}", tip(&s));
+ same_bodies(&s.model.state(), &rebuilt(&s));
+}
+
+/// A sketch that projects another part's edge is in-context design: it is evaluated again when
+/// that part moves relative to it (and gives what a full rebuild gives), not when the two move
+/// together.
+#[test]
+fn an_in_context_sketch_follows_only_the_parts_it_reads() {
+ let mut s = pivot(true);
+ let slot = s.doc.find_feature("Slot").map(|f| f.id).unwrap();
+ let projected = |s: &Session| s.model.state().sketch(slot).map(|k| k.sketch.clone()).unwrap();
+ let first = projected(&s);
+ run(&mut s, "joint.drive", json!({"joint": "Pivot", "value": "30 deg"}));
+ assert!(s.model.last_recomputed > 0, "the slot sketch reads the base, which turned relative to it");
+ assert_ne!(projected(&s).links, first.links, "the base's edge is where the arm now sees it");
+ same_bodies(&s.model.state(), &rebuilt(&s));
+ // The whole assembly moved as one (both occurrences by the same turn and shift): nothing the
+ // sketch reads moved relative to it.
+ let model = s.model.state();
+ let turn = solidcraft_doc::rigid(Vec3::new(5.0, -3.0, 2.0), Vec3::new(1.0, 2.0, 0.0), Vec3::new(0.3, 0.2, 1.0), 0.7);
+ for o in &mut s.doc_mut().occurrences {
+ o.transform = solidcraft_doc::mat_mul(&turn, &o.transform);
+ }
+ s.refresh();
+ assert_eq!(s.model.last_recomputed, 0);
+ assert!(std::sync::Arc::ptr_eq(&model, &s.model.state()));
+ same_bodies(&s.model.state(), &rebuilt(&s));
+}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 6cde8bd05a..942e6b385f 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -177,12 +177,14 @@ impl Ahead {
}
/// Run `commands` (their results stay in the shared evaluation cache, and in [`Ahead::kept`]),
- /// then make the display meshes and plans of the bodies they end with: the bodies the run
- /// here finds share them, so the window draws, fits and picks without tessellating anything.
- pub fn evaluate(self, commands: &[(String, Value)]) -> Result<()> {
- let (s, _) = self.0.preview_in_place(commands)?;
- s.world_state().warm_display();
- Ok(())
+ /// then make the display meshes and plans of the bodies they end with, so the window draws,
+ /// fits and picks without tessellating anything. What they evaluated comes back for
+ /// [`Session::prime`], so running them for real evaluates nothing again: the shared cache
+ /// drops results past its budget, and a large design's states are past it.
+ pub fn evaluate(self, commands: &[(String, Value)]) -> Result<Evaluated> {
+ let (after, _) = self.0.preview_in_place(commands)?;
+ after.world_state().warm_display();
+ Ok(Evaluated(after.model))
}
/// Run `commands` one after another, each reply or error in turn (what they evaluate stays
@@ -193,6 +195,10 @@ impl Ahead {
}
}
+/// The model a session copy evaluated ahead ([`Ahead::evaluate`]).
+#[derive(Clone, Debug)]
+pub struct Evaluated(solidcraft_doc::Model);
+
/// What some commands would make, evaluated on a scratch copy of a session
/// ([`Session::preview`]). The session itself is not changed.
#[derive(Clone, Debug)]
@@ -267,6 +273,9 @@ pub struct Session {
/// Recent body renames: the design before and after each, and the names, so undo and redo
/// follow them without evaluating either.
body_renames: Vec<BodyRename>,
+ /// Bodies' contact meshes (shared with scratch copies): a joint driven again meshes no body
+ /// that did not change.
+ contact_meshes: std::sync::Arc<std::sync::Mutex<cmd::motion::contact_sweep::ContactMeshes>>,
/// Features copied with `timeline.copy` (pasted by `timeline.paste`).
pub clipboard: Vec<solidcraft_doc::Feature>,
/// Sketch geometry copied with `sketch.copy` (pasted by `sketch.paste`).
@@ -421,6 +430,7 @@ impl Session {
removed_later_cache: Default::default(),
clearance_cache: Default::default(),
body_renames: Vec::new(),
+ contact_meshes: Default::default(),
clipboard: Vec::new(),
sketch_clipboard: None,
section: None,
@@ -953,6 +963,7 @@ impl Session {
removed_later_cache: Default::default(),
clearance_cache: self.clearance_cache.clone(),
body_renames: Vec::new(),
+ contact_meshes: self.contact_meshes.clone(),
clipboard: self.clipboard.clone(),
sketch_clipboard: self.sketch_clipboard.clone(),
section: None,
@@ -978,6 +989,19 @@ impl Session {
self.revision = old.max(previous_revision) + 1;
}
+ /// Offer what a copy of this session evaluated ahead for the commands about to run
+ /// ([`Ahead::evaluate`]): until [`Session::unprime`], evaluating takes each feature result
+ /// whose inputs match instead of computing it again (a design changed meanwhile matches
+ /// less, or nothing, and is evaluated as usual).
+ pub fn prime(&mut self, evaluated: &Evaluated) {
+ self.model.prime(&evaluated.0);
+ }
+
+ /// Stop offering what [`Session::prime`] offered.
+ pub fn unprime(&mut self) {
+ self.model.unprime();
+ }
+
/// Commit commands evaluated on a scratch copy without losing this session's file,
/// saved state, view state, checkpoints or earlier undo steps.
pub fn accept_computed(&mut self, mut computed: Session) {
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index b92c4d83e4..f2d8cf46a3 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -3242,6 +3242,39 @@ fn computed_import_preserves_file_and_earlier_undo_history() {
assert!(s.model.state().bodies.is_empty());
}
+/// Commands evaluated ahead (off the window thread) and then run for real take what was
+/// evaluated: on a design whose states are past the shared cache's budget the second run
+/// evaluated everything again, so an off-thread command cost twice its time.
+#[test]
+fn commands_evaluated_ahead_are_not_evaluated_again() {
+ let mut s = Session::default();
+ run(&mut s, "parameters.add", json!({"name": "w", "expression": "40 mm"}));
+ run(&mut s, "solid.box", json!({"length": "w", "width": 30, "height": 10, "body_name": "Block"}));
+ run(&mut s, "solid.chamfer", json!({"edges": [[10, 0, 10]], "distance": 1}));
+ run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 20, "corner": [2, 2, 0], "operation": "cut"}));
+ let commands = vec![("parameters.change".to_string(), json!({"name": "w", "expression": "50 mm"}))];
+ let evaluated = s.ahead().evaluate(&commands).unwrap();
+ // The shared cache dropped those results (as it does past its budget).
+ s.model.cache = Default::default();
+ let mut unprimed = s.scratch();
+ s.prime(&evaluated);
+ let r = run(&mut s, "parameters.change", json!({"name": "w", "expression": "50 mm"}));
+ s.unprime();
+ assert_eq!((&r["recomputed"], &r["restored"]), (&json!(0), &json!(3)), "every feature taken from the evaluation ahead: {r}");
+ let r = run(&mut unprimed, "parameters.change", json!({"name": "w", "expression": "50 mm"}));
+ assert_eq!(r["recomputed"], 3, "without it, all evaluated again: {r}");
+ for (a, b) in s.model.state().bodies.iter().zip(&unprimed.model.state().bodies) {
+ assert_eq!(a.mesh().bounds(), b.mesh().bounds());
+ }
+ // Inputs that differ from those evaluated ahead are evaluated, as usual.
+ s.model.cache = Default::default();
+ s.prime(&evaluated);
+ let r = run(&mut s, "parameters.change", json!({"name": "w", "expression": "60 mm"}));
+ s.unprime();
+ assert_eq!(r["recomputed"], 3, "{r}");
+ assert!((s.model.state().body("Block").unwrap().mesh().bounds().max.x - 60.0).abs() < 1e-9);
+}
+
#[test]
fn adopting_a_computed_component_keeps_its_warm_world_geometry() {
let mut s = Session::default();
@@ -3954,3 +3987,50 @@ fn cheap_commands_on_thousands_of_bodies_evaluate_nothing() {
}
assert_eq!(meshes(&s), shown, "every body keeps its mesh");
}
+
+/// #3397: a new, empty component changes nothing a feature reads, so creating one recomputes
+/// nothing, the first component of a design included: not a targeted cut, a Combine, a To
+/// Object extrude or a sketch on a face without a construction certificate (a legacy face
+/// plane, which reads every placed body), all of which read placements.
+#[test]
+fn creating_a_component_recomputes_nothing() {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length": 30, "width": 30, "height": 10, "operation": "new", "body_name": "Block"}));
+ run(&mut s, "solid.cylinder", json!({"diameter": 8, "height": 12, "base": [15, 15, -1], "operation": "cut", "targets": ["Block"]}));
+ run(&mut s, "solid.box", json!({"length": 10, "width": 30, "height": 20, "corner": [0, 0, 10], "operation": "new", "body_name": "Tab"}));
+ run(&mut s, "solid.combine", json!({"target": "Block", "tools": ["Tab"], "operation": "join"}));
+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Post sketch"}));
+ run(&mut s, "sketch.circle.center", json!({"center": [25, 25], "radius": 2}));
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "solid.extrude", json!({"sketch": "Post sketch", "to": [25, 25, 10], "operation": "new", "body_name": "Post"}));
+ // A plate whose top face loses its certificate: a patterned cut, a pad joined flush with
+ // the top, then one more cut. Extruding that face makes a sketch on a legacy face plane.
+ run(&mut s, "solid.box", json!({"length": 100, "width": 100, "height": 10, "corner": [200, 0, 0], "operation": "new", "body_name": "Plate"}));
+ run(
+ &mut s,
+ "solid.cylinder",
+ json!({"diameter": 4, "height": 12, "base": [210, 10, -1], "operation": "cut", "targets": ["Plate"], "name": "Pilot"}),
+ );
+ run(
+ &mut s,
+ "solid.pattern.rectangular",
+ json!({"features": ["Pilot"], "dir1": [1, 0, 0], "count1": 4, "spacing1": 20, "dir2": [0, 1, 0], "count2": 4, "spacing2": 20}),
+ );
+ run(&mut s, "sketch.create", json!({"plane": "XY", "offset": "5 mm", "name": "Pad sketch"}));
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [260, 60], "p1": [295, 95]}));
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "solid.extrude", json!({"sketch": "Pad sketch", "distance": 5, "operation": "join", "targets": ["Plate"]}));
+ run(&mut s, "solid.box", json!({"length": 5, "width": 100, "height": 12, "corner": [199, 0, -1], "operation": "cut", "targets": ["Plate"]}));
+ run(&mut s, "solid.extrude", json!({"face": [240, 40, 10], "distance": 1, "operation": "join", "name": "Face layer"}));
+ let legacy_face = s
+ .doc
+ .features
+ .iter()
+ .any(|f| matches!(&f.kind, solidcraft_doc::FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { anchor: None, .. }, .. }));
+ assert!(legacy_face, "the face extrude's sketch is on a legacy face plane");
+ for name in ["First", "Second"] {
+ run(&mut s, "component.create", json!({"name": name}));
+ assert_eq!(s.model.last_recomputed, 0, "creating {name} recomputed a feature");
+ run(&mut s, "component.activate", json!({"component": "root"}));
+ }
+}
diff --git a/crates/ui-egui/src/apply_off_thread_tests.rs b/crates/ui-egui/src/apply_off_thread_tests.rs
index 0d574dea4f..b61e695237 100644
--- a/crates/ui-egui/src/apply_off_thread_tests.rs
+++ b/crates/ui-egui/src/apply_off_thread_tests.rs
@@ -108,12 +108,12 @@ fn the_dialog_holds_its_inputs_while_ok_computes() {
// OK computing, until the test lets it finish.
let (finish, done) = std::sync::mpsc::channel();
let cmds = h.app.dialog.as_ref().and_then(|d| crate::dialogs::apply_commands(&h.app, d).ok()).unwrap();
- h.app.applying = Some(crate::dialogs::Applying { done, started: crate::now_ms(), cmds, seen: true });
+ h.app.applying = Some(crate::dialogs::Applying::computing(done, cmds));
// A click on the square picked would take it out of the profiles.
h.step(&json!({"click": {"world": [10, 10, 10]}})).unwrap();
h.frames(2);
assert_eq!(h.app.dialog.as_ref().map(|d| d.inputs[0].items.clone()), Some(picked), "no pick while computing");
- finish.send(()).unwrap();
+ finish.send(None).unwrap();
until_applied(&mut h);
assert!(h.app.dialog.is_none());
h.step(&json!({"expect": {"bodies": 1, "volume": 13000}})).unwrap();
@@ -129,8 +129,8 @@ fn inputs_changed_while_ok_computes_are_computed_off_the_thread_too() {
let features = h.app.session.doc.features.len();
// OK computing other commands than the dialog's, until the test lets it finish.
let (finish, done) = std::sync::mpsc::channel();
- h.app.applying = Some(crate::dialogs::Applying { done, started: crate::now_ms(), cmds: Vec::new(), seen: true });
- finish.send(()).unwrap();
+ h.app.applying = Some(crate::dialogs::Applying::computing(done, Vec::new()));
+ finish.send(None).unwrap();
h.frames(1);
assert!(h.app.applying.is_some(), "the dialog's own commands are computing");
assert_eq!(h.app.session.doc.features.len(), features, "nothing applied on the window thread");
diff --git a/crates/ui-egui/src/deferred.rs b/crates/ui-egui/src/deferred.rs
index 4a91046310..644a8d96a8 100644
--- a/crates/ui-egui/src/deferred.rs
+++ b/crates/ui-egui/src/deferred.rs
@@ -7,8 +7,9 @@
//! The command is evaluated on a copy of the session ([`solidcraft_engine::Session::ahead`]),
//! which leaves what it computes in the evaluation cache the session shares. Done within the
//! app's wait ([`crate::dialogs::APPLY_AT_ONCE`]), the command just runs; otherwise the window
-//! goes on, saying it computes, and the command runs for real once the evaluation is in, finding
-//! its features in the cache. Commands asked for meanwhile wait their turn; a marker moved again
+//! goes on, saying it computes, and the command runs for real once the evaluation is in, taking
+//! the features it evaluated ([`solidcraft_engine::Session::prime`]) rather than computing them
+//! again. Commands asked for meanwhile wait their turn; a marker moved again
//! replaces the move still waiting, so a drag computes where it ends rather than every slot it
//! crossed.
//!
@@ -24,7 +25,9 @@ use crate::SolveApp;
/// A command computing off the window thread.
pub struct Deferred {
- done: std::sync::mpsc::Receiver<()>,
+ done: std::sync::mpsc::Receiver<Option<solidcraft_engine::Evaluated>>,
+ /// What it evaluated, once in (`Some(None)`: it failed, or its thread is gone).
+ evaluated: Option<Option<solidcraft_engine::Evaluated>>,
/// When it started (ms).
pub(crate) started: f64,
command: (String, Value),
@@ -33,11 +36,26 @@ pub struct Deferred {
}
impl Deferred {
- fn finished(&self) -> bool {
- !matches!(self.done.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty))
+ pub(crate) fn finished(&mut self) -> bool {
+ if self.evaluated.is_none() {
+ match self.done.try_recv() {
+ Ok(evaluated) => self.evaluated = Some(evaluated),
+ Err(std::sync::mpsc::TryRecvError::Disconnected) => self.evaluated = Some(None),
+ Err(std::sync::mpsc::TryRecvError::Empty) => {}
+ }
+ }
+ self.evaluated.is_some()
}
}
+/// How a command asked to run off the window thread goes.
+enum Start {
+ /// It computes off the window thread.
+ Later(Deferred),
+ /// It runs now, with what was evaluated for it ahead (if anything).
+ Now(Option<solidcraft_engine::Evaluated>),
+}
+
/// A delete's check computing off the window thread: each check command's reply, in order.
pub struct DeleteCheck {
done: std::sync::mpsc::Receiver<Vec<Result<Value, String>>>,
@@ -105,14 +123,24 @@ impl SolveApp {
return Ok(Value::Null);
}
match self.begin_deferred(id, &params) {
- Some(job) => {
+ Start::Later(job) => {
self.deferred = Some(job);
Ok(Value::Null)
}
- None => self.run(id, params),
+ Start::Now(evaluated) => self.run_evaluated(id, params, evaluated.as_ref()),
}
}
+ /// Run a command for real, taking the features `evaluated` computed for it ahead.
+ fn run_evaluated(&mut self, id: &str, params: Value, evaluated: Option<&solidcraft_engine::Evaluated>) -> Result<Value, String> {
+ if let Some(evaluated) = evaluated {
+ self.session.prime(evaluated);
+ }
+ let r = self.run(id, params);
+ self.session.unprime();
+ r
+ }
+
/// Since when a command, or a delete's check, has been computing off the window thread (ms),
/// if one is.
pub fn computing_since(&self) -> Option<f64> {
@@ -175,7 +203,7 @@ impl SolveApp {
/// Each frame: a command whose evaluation is in runs, then the next one waiting starts.
pub(crate) fn poll_deferred(&mut self, ctx: &egui::Context) {
- if let Some(job) = &self.deferred {
+ if let Some(job) = &mut self.deferred {
if !job.finished() {
ctx.request_repaint_after(std::time::Duration::from_millis(100));
return;
@@ -187,7 +215,7 @@ impl SolveApp {
// The design changed meanwhile: computed again for the design as it is now.
let _ = self.run_heavy(&id, params);
} else if !superseded {
- let _ = self.run(&id, params);
+ let _ = self.run_evaluated(&id, params, job.evaluated.flatten().as_ref());
}
}
}
@@ -201,33 +229,35 @@ impl SolveApp {
/// ([`SolveApp::apply_off_thread`]), a file operation in progress, no threads (the web), or
/// done within the wait.
#[cfg(not(target_arch = "wasm32"))]
- fn begin_deferred(&self, id: &str, params: &Value) -> Option<Deferred> {
- let wait = self.apply_off_thread?;
+ fn begin_deferred(&self, id: &str, params: &Value) -> Start {
+ let Some(wait) = self.apply_off_thread else { return Start::Now(None) };
if self.file_load.busy() || self.file_picker.is_some() {
- return None;
+ return Start::Now(None);
}
let ahead = self.session.ahead();
let command = (id.to_string(), params.clone());
let commands = vec![command.clone()];
let (tx, rx) = std::sync::mpsc::channel();
- std::thread::Builder::new()
- .name("history".into())
- .spawn(move || {
- let _ = ahead.evaluate(&commands);
- let _ = tx.send(());
- })
- .ok()?;
+ let spawned = std::thread::Builder::new().name("history".into()).spawn(move || {
+ let _ = tx.send(ahead.evaluate(&commands).ok());
+ });
+ if spawned.is_err() {
+ return Start::Now(None);
+ }
// Zero explicitly requests off-thread application, even if a fast worker
// finishes before this thread is scheduled again. Apply on the next frame.
- if wait.is_zero() || matches!(rx.recv_timeout(wait), Err(std::sync::mpsc::RecvTimeoutError::Timeout)) {
- Some(Deferred { done: rx, started: crate::now_ms(), command, revision: self.session.revision })
- } else {
- None
+ if !wait.is_zero() {
+ match rx.recv_timeout(wait) {
+ Ok(evaluated) => return Start::Now(evaluated),
+ Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => return Start::Now(None),
+ Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
+ }
}
+ Start::Later(Deferred { done: rx, evaluated: None, started: crate::now_ms(), command, revision: self.session.revision })
}
#[cfg(target_arch = "wasm32")]
- fn begin_deferred(&self, _id: &str, _params: &Value) -> Option<Deferred> {
- None
+ fn begin_deferred(&self, _id: &str, _params: &Value) -> Start {
+ Start::Now(None)
}
}
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 91f9f69f94..f20648b4a4 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -437,12 +437,14 @@ struct ShellChain {
faces: Vec<Sel>,
}
-/// OK computing off the window thread: the dialog's commands evaluated on a scratch copy of the
-/// session, which leaves the feature in the evaluation cache the session shares. Once that is
-/// in, OK runs them for real and finds the feature there; meanwhile the window stays live and
-/// the dialog says it is computing.
+/// OK computing off the window thread: the dialog's commands evaluated on a copy of the
+/// session. Once that is in, OK runs them for real, taking what the copy evaluated
+/// ([`solidcraft_engine::Session::prime`]) rather than computing it again; meanwhile the window
+/// stays live and the dialog says it is computing.
pub struct Applying {
- pub(crate) done: std::sync::mpsc::Receiver<()>,
+ pub(crate) done: std::sync::mpsc::Receiver<Option<solidcraft_engine::Evaluated>>,
+ /// What it evaluated, once in (`Some(None)`: it failed, or its worker is gone).
+ evaluated: Option<Option<solidcraft_engine::Evaluated>>,
/// When OK was pressed (ms).
pub(crate) started: f64,
/// The commands being computed.
@@ -453,17 +455,48 @@ pub struct Applying {
}
impl Applying {
- /// The evaluation is in (or its worker ended).
- fn finished(&self) -> bool {
- !matches!(self.done.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty))
+ /// OK computing `cmds`, in once `done` says what was evaluated (tests stand in for the worker).
+ #[cfg(test)]
+ pub(crate) fn computing(done: std::sync::mpsc::Receiver<Option<solidcraft_engine::Evaluated>>, cmds: Vec<(String, Value)>) -> Self {
+ Applying { done, evaluated: None, started: crate::now_ms(), cmds, seen: true }
}
/// The evaluation is in and the job has been in a frame. A job that has just started waits
/// one frame: the window thread may be held up between starting it and the check, and the
/// feature must not appear where the dialog says it is computing.
- fn ready(&self) -> bool {
+ fn ready(&mut self) -> bool {
self.seen && self.finished()
}
+
+ /// The evaluation is in (or its worker ended).
+ fn finished(&mut self) -> bool {
+ if self.evaluated.is_none() {
+ match self.done.try_recv() {
+ Ok(evaluated) => self.evaluated = Some(evaluated),
+ Err(std::sync::mpsc::TryRecvError::Disconnected) => self.evaluated = Some(None),
+ Err(std::sync::mpsc::TryRecvError::Empty) => {}
+ }
+ }
+ self.evaluated.is_some()
+ }
+}
+
+/// How OK goes.
+enum Begun {
+ /// It computes off the window thread.
+ Later(Applying),
+ /// It runs now, with what was evaluated for it (if anything).
+ Now(Option<solidcraft_engine::Evaluated>),
+}
+
+/// Run the dialog's commands, taking the features `evaluated` computed for them ahead.
+fn run_evaluated(app: &mut SolveApp, d: &Dialog, evaluated: Option<&solidcraft_engine::Evaluated>) -> Result<(), String> {
+ if let Some(evaluated) = evaluated {
+ app.session.prime(evaluated);
+ }
+ let r = run_dialog(app, d);
+ app.session.unprime();
+ r
}
/// How long the desktop app's OK waits for its evaluation before it lets the window go on and
@@ -471,41 +504,44 @@ impl Applying {
/// applies at once, as it always did.
pub const APPLY_AT_ONCE: std::time::Duration = std::time::Duration::from_millis(150);
-/// Start OK's evaluation off the window thread, for a feature dialog. `None` when OK should
+/// Start OK's evaluation off the window thread, for a feature dialog. `Now` when OK should
/// just run: not a feature, not asked for ([`SolveApp::apply_off_thread`]), no threads (the
/// web), or done within the wait.
#[cfg(not(target_arch = "wasm32"))]
-fn begin_applying(app: &SolveApp, d: &Dialog) -> Option<Applying> {
- let wait = app.apply_off_thread?;
+fn begin_applying(app: &SolveApp, d: &Dialog) -> Begun {
+ let Some(wait) = app.apply_off_thread else { return Begun::Now(None) };
if !d.previews() {
- return None;
+ return Begun::Now(None);
}
- let cmds = apply_commands(app, d).ok()?;
- let scratch = app.session.scratch();
+ let Ok(cmds) = apply_commands(app, d) else { return Begun::Now(None) };
+ let ahead = app.session.ahead();
let (tx, rx) = std::sync::mpsc::channel();
let computed = cmds.clone();
#[cfg(test)]
let gate = app.apply_gate.clone();
- std::thread::Builder::new()
- .name("apply".into())
- .spawn(move || {
- let _ = scratch.preview(&computed);
- #[cfg(test)]
- if let Some(gate) = gate {
- let _ = gate.lock().unwrap().recv();
- }
- let _ = tx.send(());
- })
- .ok()?;
+ let spawned = std::thread::Builder::new().name("apply".into()).spawn(move || {
+ let evaluated = ahead.evaluate(&computed).ok();
+ #[cfg(test)]
+ if let Some(gate) = gate {
+ let _ = gate.lock().unwrap().recv();
+ }
+ let _ = tx.send(evaluated);
+ });
+ if spawned.is_err() {
+ return Begun::Now(None);
+ }
match rx.recv_timeout(wait) {
- Err(std::sync::mpsc::RecvTimeoutError::Timeout) => Some(Applying { done: rx, started: crate::now_ms(), cmds, seen: false }),
- _ => None,
+ Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
+ Begun::Later(Applying { done: rx, evaluated: None, started: crate::now_ms(), cmds, seen: false })
+ }
+ Ok(evaluated) => Begun::Now(evaluated),
+ Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Begun::Now(None),
}
}
#[cfg(target_arch = "wasm32")]
-fn begin_applying(_app: &SolveApp, _d: &Dialog) -> Option<Applying> {
- None
+fn begin_applying(_app: &SolveApp, _d: &Dialog) -> Begun {
+ Begun::Now(None)
}
/// The commands a dialog's inputs make (or why they make none), its picks, and the design's
@@ -2470,11 +2506,11 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
Kind::Text(k) => Some(crate::sketch_text::apply(app, k)),
_ => match begin_applying(app, &d) {
// Computing: the dialog stays, saying so, until it is in.
- Some(job) => {
+ Begun::Later(job) => {
app.applying = Some(job);
None
}
- None => Some(run_dialog(app, &d)),
+ Begun::Now(evaluated) => Some(run_evaluated(app, &d, evaluated.as_ref())),
},
};
match run {
@@ -2486,22 +2522,22 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
None => {}
}
}
- // OK's evaluation is in: run it, the feature taken from the cache. Inputs changed meanwhile
+ // OK's evaluation is in: run it, taking what was evaluated. Inputs changed meanwhile
// (nothing should change them) are computed in turn, off the window thread too: run here,
// they would hold the window for the whole boolean.
// A job that has just started is not in yet: it waits a frame, so the dialog says it is
// computing before the feature appears.
- let ready = app.applying.as_ref().is_some_and(Applying::ready);
+ let ready = app.applying.as_mut().is_some_and(Applying::ready);
if let Some(job) = &mut app.applying {
job.seen = true;
}
if ready && !cancel {
- let computed = app.applying.take().map(|job| job.cmds);
+ let (computed, evaluated) = app.applying.take().map(|job| (Some(job.cmds), job.evaluated.flatten())).unwrap_or_default();
let current = apply_commands(app, &d).ok();
- let again = if current.is_some() && current != computed { begin_applying(app, &d) } else { None };
+ let again = if current.is_some() && current != computed { begin_applying(app, &d) } else { Begun::Now(evaluated) };
match again {
- Some(job) => app.applying = Some(job),
- None => match run_dialog(app, &d) {
+ Begun::Later(job) => app.applying = Some(job),
+ Begun::Now(evaluated) => match run_evaluated(app, &d, evaluated.as_ref()) {
Ok(()) => {
cancel = !apply_again;
applied = true;
diff --git a/crates/ui-egui/src/dialogs_sketch_tests.rs b/crates/ui-egui/src/dialogs_sketch_tests.rs
index 091d5775da..be9bf7cd2e 100644
--- a/crates/ui-egui/src/dialogs_sketch_tests.rs
+++ b/crates/ui-egui/src/dialogs_sketch_tests.rs
@@ -195,11 +195,11 @@ fn apply_keeps_the_panel_open_after_asynchronous_evaluation() {
d.repeat_after_apply = true;
h.app.dialog = Some(d);
let (finish, done) = std::sync::mpsc::channel();
- h.app.applying = Some(Applying { done, started: crate::now_ms(), cmds, seen: true });
+ h.app.applying = Some(Applying::computing(done, cmds));
let undo = h.app.session.undo.len();
h.frames(2);
assert_eq!(h.app.session.undo.len(), undo);
- finish.send(()).unwrap();
+ finish.send(None).unwrap();
h.frames(3);
assert!(h.app.applying.is_none());
let d = h.app.dialog.as_ref().unwrap();
diff --git a/crates/ui-egui/src/history_off_thread_tests.rs b/crates/ui-egui/src/history_off_thread_tests.rs
index d4ec4d6ab6..968d72158a 100644
--- a/crates/ui-egui/src/history_off_thread_tests.rs
+++ b/crates/ui-egui/src/history_off_thread_tests.rs
@@ -59,6 +59,32 @@ fn the_marker_moved_computes_off_the_window_thread_then_moves() {
assert!((v - (12500.0 - hole)).abs() < 1.0, "{v}");
}
+/// The command runs for real with what was evaluated off the window thread: nothing is
+/// evaluated twice, even once the evaluation cache no longer holds it (a large design's states
+/// are past its budget, and the window thread evaluated the whole command again).
+#[test]
+fn a_command_computed_off_the_thread_is_not_evaluated_again() {
+ let mut h = block_boss_hole();
+ h.app.run_heavy("timeline.roll_to", json!({"position": 1})).unwrap();
+ until_settled(&mut h);
+ h.app.session.model.cache = Default::default();
+ h.app.run_heavy("timeline.roll_to", json!({})).unwrap();
+ for _ in 0..500 {
+ if h.app.deferred.as_mut().is_some_and(crate::deferred::Deferred::finished) {
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ // What it evaluated is gone from the cache.
+ h.app.session.model.cache = Default::default();
+ until_settled(&mut h);
+ assert_eq!(marker(&h), None);
+ assert_eq!((h.app.session.model.last_recomputed, h.app.session.model.last_restored), (0, 2), "the boss and the hole as evaluated off the thread");
+ let hole = std::f64::consts::PI * 4.0 * 15.0;
+ let v = h.app.run("inspect.measure", json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap();
+ assert!((v - (12500.0 - hole)).abs() < 1.0, "{v}");
+}
+
#[test]
fn a_marker_moved_again_replaces_the_move_still_waiting() {
let mut h = block_boss_hole();