Skip to content

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

Joint: a pick's snap is measured once, not every frame (#12864)

Kai Evanseaf014eb54a9
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index cb2531f325..5de3e43319 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -143,7 +143,7 @@ impl ModelBody {
/// Face measurements for joint origins, at their original chord tolerance. Pose changes
/// and scratch copies share them; a geometry edit makes a new body and cache.
- pub(crate) fn joint_faces(&self) -> Result<Arc<[kernel::FaceInfo]>> {
+ pub fn joint_faces(&self) -> Result<Arc<[kernel::FaceInfo]>> {
let measure = || {
#[cfg(test)]
cost_tests::count(|c| c.joint_faces += 1);
@@ -8765,6 +8765,7 @@ impl PlacedBodies {
let mut fresh = ModelBody::new(name.to_string(), placed.body.clone(), b.feature);
fresh.mesh = placed.mesh.clone();
fresh.measured = placed.measured.clone();
+ fresh.joint_faces = placed.joint_faces.clone();
fresh.mesh_placement = placed.mesh_placement.clone();
fresh.plan = placed.plan.clone();
fresh.plan_mesh = placed.plan_mesh.clone();
diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs
index 2a2bb88e15..19de666d60 100644
--- a/crates/ui-egui/src/dialogs_assembly.rs
+++ b/crates/ui-egui/src/dialogs_assembly.rs
@@ -675,8 +675,8 @@ pub fn snap_of(s: &Session, sel: &Sel) -> Option<SnapPt> {
let (body, mut snap) = match sel {
Sel::Face { body, index, point } => {
let b = st.body(body)?;
- let tol = (b.body.size() * 2e-3).max(1e-3);
- let f = b.body.faces(tol).ok()?.into_iter().find(|f| f.index == *index)?;
+ let faces = b.joint_faces().ok()?;
+ let f = faces.iter().find(|f| f.index == *index)?;
match f.plane_normal {
Some(n) => (body.as_str(), SnapPt { at: f.centroid, z: n, kind: SnapKind::FaceCenter, param: json!({"face": pt(*point)}) }),
None => {
@@ -750,6 +750,45 @@ pub fn snap_of(s: &Session, sel: &Sel) -> Option<SnapPt> {
Some(snap)
}
+/// Each pick's snap, measured once for the world state, design and open sketch it was measured in.
+#[derive(Default)]
+pub(crate) struct SnapMemo(std::sync::Mutex<Snaps>);
+
+#[derive(Default)]
+struct Snaps {
+ world: std::sync::Weak<solidcraft_engine::doc::ModelState>,
+ doc: std::sync::Weak<solidcraft_engine::doc::Document>,
+ active_sketch: Option<u64>,
+ /// Least recently used first.
+ snaps: Vec<(Sel, Option<SnapPt>)>,
+}
+
+/// Snaps kept: the picks, and the hovered items since the last one picked.
+const SNAPS_KEPT: usize = 16;
+
+/// [`snap_of`] from the app's memo while the world it was measured in stands.
+pub(crate) fn picked_snap(app: &SolveApp, sel: &Sel) -> Option<SnapPt> {
+ let s = &app.session;
+ let Ok(mut memo) = app.snaps.0.lock() else { return snap_of(s, sel) };
+ let world = std::sync::Arc::downgrade(&crate::open_meshing::session_world(s));
+ let doc = std::sync::Arc::downgrade(&s.doc);
+ if !(memo.world.ptr_eq(&world) && memo.doc.ptr_eq(&doc) && memo.active_sketch == s.active_sketch) {
+ *memo = Snaps { world, doc, active_sketch: s.active_sketch, snaps: Vec::new() };
+ }
+ if let Some(i) = memo.snaps.iter().position(|(x, _)| x == sel) {
+ let hit = memo.snaps.remove(i);
+ let snap = hit.1.clone();
+ memo.snaps.push(hit);
+ return snap;
+ }
+ let snap = snap_of(s, sel);
+ if memo.snaps.len() >= SNAPS_KEPT {
+ memo.snaps.remove(0);
+ }
+ memo.snaps.push((sel.clone(), snap.clone()));
+ snap
+}
+
/// A snap moved across its own plane by (x, y) (the joint's offset), as an explicit frame.
fn shifted(s: &SnapPt, x: f64, y: f64) -> Value {
let ax = s.z.any_perp();
@@ -1460,7 +1499,7 @@ fn occurrences(s: &Session, items: &[Sel]) -> Vec<u64> {
pub fn commands(app: &SolveApp, k: &Asm, inputs: &[SelInput]) -> Result<Vec<(String, Value)>, String> {
let s = &app.session;
let snap = |i: usize, what: &str| -> Result<SnapPt, String> {
- sel_items(inputs, i).first().and_then(|x| snap_of(s, x)).ok_or_else(|| format!("select {what} first"))
+ sel_items(inputs, i).first().and_then(|x| picked_snap(app, x)).ok_or_else(|| format!("select {what} first"))
};
let eval = |e: &str, kind: ValueKind| -> Result<f64, String> {
if e.trim().is_empty() { Ok(0.0) } else { crate::length_input::eval(&s.doc, e, kind).map_err(|e| e.to_string()) }
@@ -1528,7 +1567,7 @@ pub fn commands(app: &SolveApp, k: &Asm, inputs: &[SelInput]) -> Result<Vec<(Str
if !custom_name.is_empty() {
p["name"] = json!(custom_name);
}
- if let Some(x) = sel_items(inputs, 1).first().and_then(|x| snap_of(s, x)) {
+ if let Some(x) = sel_items(inputs, 1).first().and_then(|x| picked_snap(app, x)) {
p["at"] = x.param;
}
return Ok(cmd("joint.as_built", p));
@@ -1759,7 +1798,7 @@ pub fn overlay(app: &SolveApp, painter: &egui::Painter, proj: &Proj, d: &mut Dia
.iter()
.enumerate()
.filter(|(_, i)| i.accept == SNAPS)
- .filter_map(|(n, i)| i.items.first().and_then(|x| snap_of(&app.session, x)).map(|s| (s, if n == 0 { t.accent } else { t.warning })))
+ .filter_map(|(n, i)| i.items.first().and_then(|x| picked_snap(app, x)).map(|s| (s, if n == 0 { t.accent } else { t.warning })))
.collect();
for (n, (s, c)) in picked.iter().enumerate() {
let tag = format!("Component {}", n + 1);
@@ -1772,7 +1811,7 @@ pub fn overlay(app: &SolveApp, painter: &egui::Painter, proj: &Proj, d: &mut Dia
Some(sel) => {
let fresh = !matches!(hover, Some((s, _)) if *s == sel);
if fresh {
- *hover = Some((sel.clone(), snap_of(&app.session, &sel)));
+ *hover = Some((sel.clone(), picked_snap(app, &sel)));
}
if let Some((_, Some(s))) = hover.as_ref() {
glyph(painter, proj, s, t.hover_profile_edge, app.cam.half_height(), Some(snap_name(s.kind)));
diff --git a/crates/ui-egui/src/dialogs_assembly_tests.rs b/crates/ui-egui/src/dialogs_assembly_tests.rs
index 064179139e..d7cbbfdfe5 100644
--- a/crates/ui-egui/src/dialogs_assembly_tests.rs
+++ b/crates/ui-egui/src/dialogs_assembly_tests.rs
@@ -466,6 +466,67 @@ fn a_hole_side_shows_its_wall_not_the_plate_beside_it() {
assert_eq!(snap.kind, SnapKind::CircleCenter, "the pre-fill is the plate's face, not the hole's wall: {item:?}");
}
+/// The Joint dialog's frames (glyphs, OK's check, preview, rows) reuse each pick's snap: once
+/// measured, they mesh nothing until the world changes, and then the snap follows it.
+#[test]
+fn a_picked_snap_is_measured_once_not_every_frame() {
+ let mut s = Session::default();
+ s.execute("component.create", &json!({"name": "Plate"})).unwrap();
+ s.execute("solid.box", &json!({"length": 40, "width": 40, "height": 10, "corner": [0, 0, 0]})).unwrap();
+ s.execute("solid.cylinder", &json!({"diameter": 10, "height": 20, "base": [20, 20, -5], "operation": "cut"})).unwrap();
+ s.execute("component.create", &json!({"name": "Peg"})).unwrap();
+ s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "corner": [60, 0, 0]})).unwrap();
+ s.execute("component.activate", &json!({"component": "root"})).unwrap();
+ let mut h = crate::scenario::Harness::new();
+ h.app = SolveApp::new(s, Services::default());
+ let (plate, peg) = (occ(&h.app, "Plate"), occ(&h.app, "Peg"));
+ h.app.run("occurrence.ground", json!({"occurrence": plate, "grounded": true})).unwrap();
+ h.app.start("joint.create");
+ let mut d = h.app.dialog.clone().unwrap();
+ let wall = face_sel(&h.app.session, Vec3::new(25.0, 20.0, 5.0)).unwrap();
+ let bottom = face_sel(&h.app.session, Vec3::new(65.0, 5.0, 0.0)).unwrap();
+ d.pick(&h.app.session, wall.clone());
+ d.pick(&h.app.session, bottom.clone());
+ h.app.dialog = Some(d);
+ let settle = |h: &mut crate::scenario::Harness| {
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
+ h.frames(2);
+ while h.app.preview.busy {
+ assert!(std::time::Instant::now() < deadline, "the joint preview did not finish");
+ std::thread::sleep(std::time::Duration::from_millis(1));
+ h.frame();
+ }
+ h.frames(2);
+ };
+ settle(&mut h);
+ assert!(h.app.preview.active && h.app.preview.error.is_none(), "{:?}", h.app.preview.error);
+ let hole = snap_of(&h.app.session, &wall).unwrap();
+ assert_eq!(hole.kind, SnapKind::CircleCenter);
+ assert!(Vec3::new(hole.at.x, hole.at.y, 0.0).dist(Vec3::new(20.0, 20.0, 0.0)) < 1e-6, "{hole:?}");
+ let face = snap_of(&h.app.session, &bottom).unwrap();
+ assert!(face.at.dist(Vec3::new(65.0, 5.0, 0.0)) < 1e-9 && face.z.dist(-Vec3::Z) < 1e-9, "{face:?}");
+ let cmds = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap();
+ let ((), work) = solidcraft_engine::kernel::profile::capture(|| {
+ for _ in 0..3 {
+ h.frame();
+ apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap();
+ preview_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap();
+ }
+ });
+ assert_eq!(work.tessellate_ms, 0.0, "the frames after the picks measured them again: {work:?}");
+ assert_eq!(apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(), cmds);
+ for (sel, fresh) in [(&wall, &hole), (&bottom, &face)] {
+ let kept = picked_snap(&h.app, sel).unwrap();
+ assert!(kept.at.dist(fresh.at) < 1e-9 && kept.z.dist(fresh.z) < 1e-9 && kept.param == fresh.param, "{kept:?} {fresh:?}");
+ }
+ // A moved Peg is a new world: its face is measured again where it went.
+ h.app.run("occurrence.move", json!({"occurrence": peg, "translate": [0, 30, 0], "capture": false})).unwrap();
+ settle(&mut h);
+ let moved = picked_snap(&h.app, &bottom).unwrap();
+ assert!(moved.at.dist(Vec3::new(65.0, 35.0, 0.0)) < 1e-9, "{moved:?}");
+ assert!(picked_snap(&h.app, &wall).unwrap().at.dist(hole.at) < 1e-9, "the grounded Plate stays");
+}
+
#[test]
fn as_built_animation_drives_the_new_shared_id_and_handles_exhaustion() {
let mut app = two_boxes();
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index e5b19940f5..be1e20a8e4 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -575,6 +575,8 @@ pub struct SolveApp {
pub render_workspace: render_workspace::State,
pub tool: Option<tools::Tool>,
pub dialog: Option<dialogs::Dialog>,
+ /// The joint dialogs' picked and hovered snaps ([`dialogs_assembly::picked_snap`]).
+ pub(crate) snaps: dialogs_assembly::SnapMemo,
/// Each command dialog's options and values as last applied (this session only).
pub(crate) remembered_commands: Vec<dialogs::RememberedCommand>,
/// The Change Parameters window, when open.
@@ -861,6 +863,7 @@ impl SolveApp {
render_workspace,
tool: None,
dialog: None,
+ snaps: Default::default(),
remembered_commands: Vec::new(),
params: None,
design_properties: None,