SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Assemblies: dragging a part with mirrored copies no longer meshes them on every frame (#10101)
Sebastian Höpfl6f73bd95c435
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rsindex f16456499c..438f732df5 100644--- a/crates/doc/src/eval.rs+++ b/crates/doc/src/eval.rs@@ -40,6 +40,11 @@ pub struct ModelBody {joint_faces: Arc<OnceLock<JointFaces>>,/// Lazy canonical reference triangles for a proper rigid occurrence placement.mesh_placement: Option<Arc<placed_mesh::PlacedMesh>>,+ /// For a mirrored copy: its faces as a world state shows them, a rigid move of the source's+ /// [`placed_mesh::OppositeHand`]. Display only: the model reads the copy's own triangles.+ mirrored_mesh: Option<Arc<placed_mesh::PlacedMesh>>,+ /// The first mirrored copy made of this body, shared by its clones.+ opposite_hand: Arc<OnceLock<placed_mesh::OppositeHand>>,/// The display plan (none when the body has no plan: a mesh body, or one the planner/// refuses), shared like the mesh. A GPU viewport draws it.plan: Arc<[OnceLock<Option<Arc<TessPlan>>>; 4]>,@@ -86,6 +91,8 @@ impl ModelBody {mesh: Arc::new(OnceLock::new()),joint_faces: Arc::new(OnceLock::new()),mesh_placement: None,+ mirrored_mesh: None,+ opposite_hand: Arc::new(OnceLock::new()),plan: Arc::new(Default::default()),plan_mesh: Arc::new(Default::default()),key: 0,@@ -993,6 +1000,7 @@ impl ModelState {&& let Some(lines) = olds.first().and_then(|x| x.body.split_lines()){b.body = b.body.clone().with_split_lines(Some(lines.clone()));+ b.mirrored_mesh = None;}// An imported look outlives the operations on the body.if b.body.paint().is_none()@@ -1810,6 +1818,8 @@ fn hash_placement(m: &Mat, h: &mut impl Hasher) {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));+ // A feature added after the mirror that builds on its copies needs them made for that.+ placement_reuse::copies_only_shown(doc, f).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 {@@ -2413,6 +2423,16 @@ impl Model {_ => mats,};next.stamp(&state, f, key, mats);+ // Evaluated again only for what came before it (a mirror moved by a drag).+ if let Some(old) = self.results.get(i).filter(|old| old.id == f.id) {+ let made = old.state.bodies.iter().filter(|b| b.feature == f.id).map(|b| (b.name.as_str(), b));+ let made: std::collections::HashMap<&str, &ModelBody> = made.collect();+ for b in next.bodies.iter_mut().filter(|b| b.feature == f.id) {+ if let Some(old) = made.get(b.name.as_str()) {+ b.keep_meshes_of(old);+ }+ }+ }for b in &mut next.bodies {if !b.transferred {b.component = match doc.body_components.get(&b.name) {@@ -7809,6 +7829,9 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:}let m = mirror_matrix(&pl);let mut output = 0;+ // Copies evaluated on each frame a placement is dragged, which nothing cuts or joins:+ // searching their revolved faces again was nearly all that took.+ let shown_only = !*combine && !placements.is_empty() && placement_reuse::copies_only_shown(doc, f);for (k, n) in bodies.iter().enumerate() {let i = st.bodies.iter().position(|b| &b.name == n).ok_or_else(|| DocError::Unknown(format!("body `{n}`")))?;let Some(mb) = st.bodies.get(i).cloned() else { continue };@@ -7825,7 +7848,12 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:}None => (None, m, m),};- let mirrored = moved_copy(&mb, kernel::transform_matrix(&mb.body, if *combine { own } else { copy })?, 1);+ let copied = if shown_only {+ kernel::place_matrix(&mb.body, copy)+ } else {+ kernel::transform_matrix(&mb.body, if *combine { own } else { copy })+ };+ let mirrored = moved_copy(&mb, copied?, 1);if *combine {let joined = kernel::boolean(&mb.body, &mirrored.body, BoolOp::Union)?.ok_or_else(|| DocError::Invalid("the mirror join produced nothing".into()))?;@@ -7847,6 +7875,9 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:let name = copy_body_name(st, f, output, &mb.name);copy_sheet(st, &mb.name, &name, ©);let mut body = ModelBody::traced_new(name, mirrored, f.id);+ if !placements.is_empty() {+ body.mirrored_mesh = placed_mesh::PlacedMesh::mirrored(&mb, &body.body, ©).map(Arc::new);+ }if let Some(c) = component.filter(|c| *c != f.component) {// Kept in that component as a moved body is (and through later features).body.component = c;@@ -8525,7 +8556,8 @@ impl PlacedBodies {if let Some(placed) = self.taken(b, m, &name) {return placed;}- match kernel::place_matrix(&b.body, *m) {+ let body = if crate::is_identity(m) { Ok(b.body.clone()) } else { kernel::place_matrix(&b.body, *m) };+ match body {Ok(body) => {let mut fresh = ModelBody::new(name, body, b.feature);fresh.mesh_placement = placed_mesh::PlacedMesh::new(b, m).map(Arc::new);@@ -8631,6 +8663,12 @@ fn placed_key(b: &ModelBody, m: &crate::Mat) -> (usize, [u64; 16]) {(Arc::as_ptr(&b.mesh) as usize, bits)}+/// Whether a world state shows `b`, placed by `m`, apart from the model's body. A mirrored copy+/// always is: it is drawn from its source's opposite hand, and the model keeps its own triangles.+fn placed_apart(b: &ModelBody, m: &crate::Mat) -> bool {+ !crate::is_identity(m) || b.mirrored_mesh.is_some()+}+/// [`world_state`], reusing the bodies `placed` holds from an earlier call and leaving it holding/// this call's.pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut PlacedBodies) -> ModelState {@@ -8685,7 +8723,7 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mutfor (comp, path, m) in &placements {for b in bodies_of(*comp) {let bm = body_matrix(b, m);- if !crate::is_identity(&bm) {+ if placed_apart(b, &bm) {jobs.push((b, bm, names.name(&b.name, *comp, path)));}}@@ -8703,7 +8741,7 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mutlet bm = body_matrix(b, &m);// Identical geometry also shares its display mesh cell with the definition.// A changed placement keeps a distinct mesh, at that placement's coordinates.- let mut placed = if crate::is_identity(&bm) {+ let mut placed = if !placed_apart(b, &bm) {let mut placed = b.clone();placed.name = names.name(&b.name, comp, &path);placeddiff --git a/crates/doc/src/placed_mesh.rs b/crates/doc/src/placed_mesh.rsindex 4a945b38a2..11d61e61a7 100644--- a/crates/doc/src/placed_mesh.rs+++ b/crates/doc/src/placed_mesh.rs@@ -16,23 +16,57 @@ pub(super) struct PlacedMesh {/// each placement draws them moved, so a part is planned once however often it is placed.plans: Arc<[OnceLock<Option<Arc<TessPlan>>>; 4]>,plan_meshes: Arc<[OnceLock<Option<Arc<Mesh>>>; 4]>,+ /// The definition's own opposite hand: a copy of a copy is a rigid move of that.+ opposite_hand: Arc<OnceLock<OppositeHand>>,transform: crate::Mat,pub(super) tolerance: f64,}+/// A body's opposite hand: the first mirrored copy made of it, and the matrix that made it. A+/// reflection reverses each face's edge walk, so a copy can't be drawn from its source's triangles.+/// Two reflections do cancel, though: every later mirrored copy of the body, wherever dragging a+/// placement puts it, is a proper rigid move of this one, whose triangles are made once.+#[derive(Debug)]+pub(super) struct OppositeHand {+ /// The body it mirrors, to tell a holder whose body was replaced.+ source: Body,+ definition: ModelBody,+ matrix: crate::Mat,+}+impl PlacedMesh {+ /// Where `copy` (`source` transformed by `matrix`) stands relative to `source`'s opposite+ /// hand. `None` shows it from its own mesh: a matrix that isn't a reflection of the first.+ /// A copy of a copy goes by what its source is drawn from, which outlives that source.+ pub(super) fn mirrored(source: &ModelBody, copy: &Body, matrix: &crate::Mat) -> Option<Self> {+ let (cell, body, matrix) = match source.mirrored_mesh.as_deref() {+ Some(drawn) => (&drawn.opposite_hand, &drawn.body, crate::mat_mul(matrix, &drawn.transform)),+ None => (&source.opposite_hand, &source.body, *matrix),+ };+ let hand = cell.get_or_init(|| OppositeHand {+ source: body.clone(),+ definition: ModelBody::new(String::new(), copy.clone(), source.feature),+ matrix,+ });+ if !same_triangles(&hand.source, body) {+ return None;+ }+ Self::new(&hand.definition, &crate::mat_mul(&matrix, &crate::mat_inverse(&hand.matrix)?))+ }+/// Share the original definition, never a chain of previously placed meshes. A source's/// OnceLock lives with its immutable geometry, so edits get a new source automatically.pub(super) fn new(source: &ModelBody, transform: &crate::Mat) -> Option<Self> {if !proper_rigid(transform) {return None;}- Some(match source.mesh_placement.as_deref() {+ Some(match source.mesh_placement.as_deref().or(source.mirrored_mesh.as_deref()) {Some(original) => Self {body: original.body.clone(),mesh: original.mesh.clone(),plans: original.plans.clone(),plan_meshes: original.plan_meshes.clone(),+ opposite_hand: original.opposite_hand.clone(),transform: crate::mat_mul(transform, &original.transform),tolerance: original.tolerance,},@@ -41,6 +75,7 @@ impl PlacedMesh {mesh: source.mesh.clone(),plans: source.plan.clone(),plan_meshes: source.plan_mesh.clone(),+ opposite_hand: source.opposite_hand.clone(),transform: *transform,tolerance: source.display_tol(),},@@ -98,6 +133,29 @@ impl PlacedMesh {}}+/// Whether two bodies mesh to the same triangles: the same shape, split along the same lines.+fn same_triangles(a: &Body, b: &Body) -> bool {+ a.same_shape(b)+ && match (a.split_lines(), b.split_lines()) {+ (Some(x), Some(y)) => Arc::ptr_eq(x, y),+ (None, None) => true,+ _ => false,+ }+}++impl ModelBody {+ /// Keep the meshes `old` holds when this body is the same shape: a feature evaluated again+ /// that gives the same solids (an import, from its shared file) doesn't mesh them again.+ pub(super) fn keep_meshes_of(&mut self, old: &ModelBody) {+ if same_triangles(&self.body, &old.body) {+ self.mesh = old.mesh.clone();+ self.plan = old.plan.clone();+ self.plan_mesh = old.plan_mesh.clone();+ self.opposite_hand = old.opposite_hand.clone();+ }+ }+}+/// The display plan of a definition `body` at quality `q`, made once in `cell`.pub(super) fn definition_plan(body: &Body,diff --git a/crates/doc/src/placement_reuse.rs b/crates/doc/src/placement_reuse.rsindex efa71dc232..511efb503c 100644--- a/crates/doc/src/placement_reuse.rs+++ b/crates/doc/src/placement_reuse.rs@@ -68,6 +68,21 @@ fn local_plane(plane: &PlaneRef, depth: usize) -> bool {}}+/// Whether no feature after the mirror `f` can cut, join or otherwise build on bodies: only+/// features that read none, and further mirrors, which copy them. A boolean depends on how a+/// copy's revolved faces are turned, so a copy it may reach is made with+/// [`solidcraft_kernel::transform_matrix`]; one that is only shown needs no search for that. It+/// depends on the design alone, so a design evaluates the same however it was reached.+pub(super) fn copies_only_shown(doc: &Document, f: &Feature) -> bool {+ let mut later = doc.features.iter().skip_while(|g| g.id != f.id).skip(1);+ let mut components = std::collections::HashMap::with_capacity(doc.features.len());+ for g in &doc.features {+ components.entry(g.id).or_insert(g.component);+ }+ let copies = |g: &Feature| matches!(&g.kind, FeatureKind::Mirror { features, combine: false, .. } if features.is_empty());+ later.all(|g| copies(g) || local_geometry(g, &components))+}+pub(super) fn local_geometry(f: &Feature, components: &std::collections::HashMap<u64, u64>) -> bool {// Persistent picked-face/edge attachments can move an otherwise literal input.if !f.face_names.is_empty() || !f.edge_names.is_empty() || !f.edge_refs.is_empty() {diff --git a/crates/engine/src/tests/mirror_placed.rs b/crates/engine/src/tests/mirror_placed.rsindex 68ee1a398c..d8f2d2b18a 100644--- a/crates/engine/src/tests/mirror_placed.rs+++ b/crates/engine/src/tests/mirror_placed.rs@@ -232,3 +232,171 @@ fn a_placement_leading_to_another_component_is_reported_lost() {assert!(e.contains("no longer exists"), "{e}");assert!(s.world_state().body(©).is_none());}++/// A carriage-like part (a bored block and a ring) placed once, free to move: its occurrence and+/// body names.+fn curved_part(s: &mut Session) -> (u64, Vec<String>) {+ let c = run(s, "component.create", json!({"name": "Carriage", "grounded": false}));+ run(s, "solid.box", json!({"length": 20, "width": 10, "height": 10, "corner": [10, 5, 0], "body_name": "Block"}));+ run(s, "solid.cylinder", json!({"base": [20, 10, -1], "radius": 3, "height": 12, "operation": "cut", "targets": ["Block"]}));+ run(s, "solid.torus", json!({"center": [20, 10, 20], "major": 6, "minor": 2, "operation": "new", "body_name": "Ring"}));+ run(s, "component.activate", json!({"component": 0}));+ run(s, "occurrence.move", json!({"occurrence": c["occurrence"], "translate": [0, 7, 3]}));+ (c["occurrence"].as_u64().unwrap(), vec!["Block".into(), "Ring".into()])+}++/// The shown bodies drawn, as a viewport does, and the tessellation that took.+fn drawn(s: &Session) -> f64 {+ let world = s.world_state();+ let (_, work) = solidcraft_kernel::profile::capture(|| {+ for b in &world.bodies {+ b.mesh_in_place();+ b.display_plan();+ b.mesh();+ }+ });+ work.tessellate_ms+}++/// What the viewport shows is what a fresh evaluation of the design shows: where the triangles+/// are, which way they face and which faces and edges they belong to.+fn assert_as_evaluated_afresh(s: &Session) {+ let mut fresh = solidcraft_doc::Model::new();+ fresh.no_cache = true;+ fresh.evaluate(&s.doc);+ assert!(fresh.results.iter().all(|r| r.error.is_none()));+ let (shown, want) = (s.world_state(), solidcraft_doc::world_state(&s.doc, &fresh.state()));+ assert_eq!(shown.bodies.len(), want.bodies.len());+ for (a, b) in shown.bodies.iter().zip(&want.bodies) {+ assert_eq!(a.name, b.name);+ let (x, y) = (a.mesh(), b.mesh());+ assert_eq!(x.triangles, y.triangles, "{}", a.name);+ assert_eq!(x.tri_face, y.tri_face, "{}", a.name);+ assert_eq!(x.edge_faces, y.edge_faces, "{}", a.name);+ assert_eq!(x.seams, y.seams, "{}", a.name);+ assert_eq!(x.positions.len(), y.positions.len(), "{}", a.name);+ assert!(x.edges.iter().flatten().zip(y.edges.iter().flatten()).all(|(p, q)| p.dist(*q) < 1e-7), "{}: edges", a.name);+ assert_same_surface(&x, &y, &a.name);+ // A plan's ties fall by the pose it was made at.+ let (x, y) = (a.display_plan().unwrap().evaluate(), b.display_plan().unwrap().evaluate());+ assert_eq!(x.triangles.len(), y.triangles.len(), "{}: plan", a.name);+ assert_same_surface(&x, &y, &a.name);+ }+}++/// Two meshes of one surface, facing the same way. Their points can differ: a revolved face is+/// turned by where it stands when it is made, which only moves where the surface is sampled.+fn assert_same_surface(x: &solidcraft_geom::Mesh, y: &solidcraft_geom::Mesh, name: &str) {+ let enclosed = |m: &solidcraft_geom::Mesh| {+ m.triangles.iter().fold((0.0, 0.0), |(v, s), t| {+ let [a, b, c] = t.map(|i| m.positions[i as usize]);+ (v + a.dot(b.cross(c)) / 6.0, s + (b - a).cross(c - a).len() / 2.0)+ })+ };+ let ((v, s), (w, t)) = (enclosed(x), enclosed(y));+ assert!(v > 0.0 && (v - w).abs() < 1e-4 * w && (s - t).abs() < 1e-4 * t, "{name}: encloses {v}, {s} against {w}, {t}");+ let (a, b) = (x.bounds(), y.bounds());+ assert!(a.min.dist(b.min) < 0.05 && a.max.dist(b.max) < 0.05, "{name}: {a:?} against {b:?}");+}++/// Dragging a part with a mirrored copy moved the copy too, and every frame meshed the copy from+/// nothing: a design with a few dozen curved mirrored bodies dragged at a frame or two a second.+#[test]+fn dragging_a_mirrored_part_meshes_its_copies_once() {+ let mut s = Session::default();+ let (occurrence, bodies) = curved_part(&mut s);+ let first = run(&mut s, "solid.mirror", json!({"bodies": bodies, "plane": "XZ"}));+ // Mirrored again, as four carriages from one are: the source of these copies moves as well.+ run(&mut s, "solid.mirror", json!({"bodies": first["created_bodies"], "plane": "YZ"}));+ drawn(&s);+ for k in 1..=4 {+ let at = f64::from(k) * 3.5;+ run(&mut s, "occurrence.drag", json!({"occurrence": occurrence, "at": [0, 0, 0], "point": [1, at, 2], "continuous": true}));+ assert!(s.model.last_recomputed > 0, "the copies follow the part");+ assert_eq!(drawn(&s), 0.0, "frame {k}: the copies are drawn from triangles already made");+ }+ assert_as_evaluated_afresh(&s);+ run(&mut s, "edit.undo", json!({}));+ assert_as_evaluated_afresh(&s);+}++/// What the viewport draws of a copy doesn't reach what the model reads: a later feature finds+/// the copy's own triangles, as it does in a design opened afresh.+#[test]+fn a_mirrored_copys_shared_triangles_are_display_only() {+ let mut s = Session::default();+ let (occurrence, bodies) = curved_part(&mut s);+ let r = run(&mut s, "solid.mirror", json!({"bodies": bodies, "plane": "XZ"}));+ run(&mut s, "occurrence.drag", json!({"occurrence": occurrence, "at": [0, 0, 0], "point": [0, 3, 0], "continuous": true}));+ drawn(&s);+ let (state, world) = (s.model.state(), s.world_state());+ for copy in r["created_bodies"].as_array().unwrap().iter().map(|n| n.as_str().unwrap()) {+ assert!(world.body(copy).is_some_and(|b| b.cached_mesh().is_some()), "{copy} was drawn");+ assert!(state.body(copy).unwrap().cached_mesh().is_none(), "{copy}: the model's own mesh is its own");+ }+}++/// A source changed is mirrored from what it is now, not from the triangles of what it was.+#[test]+fn a_changed_source_gives_its_copy_new_triangles() {+ let mut s = Session::default();+ run(&mut s, "parameters.add", json!({"name": "side", "expression": "10 mm"}));+ let c = run(&mut s, "component.create", json!({"name": "Part", "grounded": false}));+ run(&mut s, "solid.box", json!({"length": "side", "width": 10, "height": 10, "corner": [10, 0, 0], "body_name": "Block"}));+ run(&mut s, "component.activate", json!({"component": 0}));+ run(&mut s, "occurrence.move", json!({"occurrence": c["occurrence"], "translate": [0, 20, 0]}));+ let copy = created(&run(&mut s, "solid.mirror", json!({"bodies": ["Block"], "plane": "XZ"})));+ assert_box(world_box(&s, ©), (Vec3::new(10.0, -30.0, 0.0), Vec3::new(20.0, -20.0, 10.0)));+ run(&mut s, "parameters.change", json!({"name": "side", "expression": "15 mm"}));+ assert_box(world_box(&s, ©), (Vec3::new(10.0, -30.0, 0.0), Vec3::new(25.0, -20.0, 10.0)));+ assert_as_evaluated_afresh(&s);+}++/// Copies nothing builds on skip the search that readies their revolved faces for a boolean.+/// A feature added later that does build on them gets them readied, as a design opened with that+/// feature has them, whether or not they were mirrored first.+#[test]+fn a_cut_added_after_a_mirror_finds_its_copies_readied() {+ let cut = |s: &mut Session, copy: &str| {+ run(s, "solid.cylinder", json!({"base": [20, -17, 15], "radius": 3, "height": 12, "operation": "cut", "targets": [copy]}));+ };+ let mut s = Session::default();+ let (_, bodies) = curved_part(&mut s);+ let copies = run(&mut s, "solid.mirror", json!({"bodies": bodies, "plane": "XZ"}));+ let ring = copies["created_bodies"][1].as_str().unwrap().to_string();+ let evaluated = s.model.recomputed;+ cut(&mut s, &ring);+ assert!(s.model.results.iter().all(|r| r.error.is_none()));+ assert!(s.model.recomputed - evaluated >= 2, "the mirror is evaluated again with the cut");+ let measured = |s: &Session| {+ let v = run(&mut s.scratch(), "inspect.measure", json!({"bodies": [ring]}));+ v["total"]["volume_mm3"].as_f64().unwrap()+ };+ let volume = measured(&s);+ let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());+ assert_eq!(measured(&reopened), volume, "what evaluates here is what opens");+}++/// A part inserted after the mirror keeps its meshes while the mirror moves: evaluating the+/// insert again gives the same solids, and meshing them was as slow as meshing the copies.+#[test]+fn an_insert_after_a_mirror_keeps_its_meshes_through_a_drag() {+ let dir = std::env::temp_dir().join(format!("solidcraft-mirror-insert-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let file = dir.join("insert.step").to_string_lossy().replace('\\', "/");+ let mut part = Session::default();+ run(&mut part, "solid.sphere", json!({"radius": 5}));+ run(&mut part, "file.export", json!({"path": file}));+ let mut s = Session::default();+ let (occurrence, bodies) = curved_part(&mut s);+ run(&mut s, "solid.mirror", json!({"bodies": bodies, "plane": "XZ"}));+ run(&mut s, "file.insert_step", json!({"path": file, "name": "After"}));+ let _ = std::fs::remove_dir_all(&dir);+ run(&mut s, "component.activate", json!({"component": 0}));+ drawn(&s);+ for k in 1..=3 {+ run(&mut s, "occurrence.drag", json!({"occurrence": occurrence, "at": [0, 0, 0], "point": [0, f64::from(k), 0], "continuous": true}));+ assert_eq!(drawn(&s), 0.0, "frame {k}");+ }+ assert_as_evaluated_afresh(&s);+}