From 32dc8750df8dde5272d2a0d186eb1711769784e5 Mon Sep 17 00:00:00 2001 From: semmelrinde <124386289+semmelrinde@users.noreply.github.com> Date: Thu, 5 Nov 2026 01:05:40 +0000 Subject: [PATCH] Sketch Project: faces and edges of a part's second copy now project (#9957) (#10721) * Sketch Project: a face or edge of a part's second placement projects where that placement is (#9957) Projecting the face of `Block (Part:2)` failed with "face of Block: the face no longer exists". The pick's body name was turned into the definition's own name, and the model a sketch reads holds only each component's first placement, so the face was looked for on the first placement, somewhere else. Sketch picks now keep the name the browser shows, and the further placements a sketch's links name are placed into the model it reads (`with_placed_copies`), when the sketch is evaluated and when a link is added or refreshed. Only the named ones are placed. A link to a body the model lacks also makes the sketch follow every placement, so moving the copy moves what was projected from it. Co-Authored-By: Claude Opus 5.5 * Sketch Project: a projection from a second placement follows renames of its part and body (#9957) The link keeps the copy by the name the browser shows (`Block (Part:2)`), which a rename of the component or of the body changes. component.rename and body.rename now rename it in the sketches' links as well. The copies a sketch reads are found through their component's bodies, not by going through every body for every placement. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/doc/src/eval.rs | 68 +++++++++++++++- crates/doc/src/lib.rs | 4 +- crates/engine/src/cmd/browser.rs | 3 + crates/engine/src/cmd/component.rs | 4 + crates/engine/src/cmd/sketch_project.rs | 80 +++++++++++++++++-- crates/engine/src/cmd/sketch_project_tests.rs | 53 ++++++++++++ crates/engine/src/frames.rs | 3 + 7 files changed, 202 insertions(+), 13 deletions(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index c6fc6bdd7..6f85867da 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1570,6 +1570,9 @@ fn cache_key(f: &Feature, chain_fp: u64, local: u64, ctx: u64, state: &ModelStat #[derive(Default)] struct PlacementReads { all: bool, + /// A body named that `st` lacks: a further placement's (`Block (Part:2)`), found through + /// its occurrence (#9957), or gone. + unlisted: bool, components: std::collections::BTreeSet, paths: Vec>, bodies: std::collections::BTreeSet, @@ -1608,14 +1611,17 @@ impl PlacementReads { } } - /// 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). + /// The component of body `name` in `st`; every component and every placement when the body + /// is not there (a further placement's body, or 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, + None => { + self.all = true; + self.unlisted = true; + } } } @@ -1851,6 +1857,9 @@ fn placement_digest(doc: &Document, f: &Feature, st: Option<&ModelState>) -> u64 } } hash_placed_bodies(doc, st, &reads.bodies, &inverse, &mut h); + if reads.unlisted { + placements_hash(doc).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() { @@ -7243,6 +7252,14 @@ fn eval_feature( None if !plane_reads_geometry(plane) && sketch.links.is_empty() => std::borrow::Cow::Borrowed(st), None => state_in_frame(doc, st, f.component)?, }; + // A further placement a link reads is placed in its frame too (#9957). + let named: Vec<&str> = sketch.links.iter().flat_map(|l| l.source.bodies()).collect(); + let fst = match anchor.map(|anchor| anchor.author_frame(doc, f.component)) { + _ if named.is_empty() => fst, + Some(Ok(frame)) => with_placed_copies(doc, st, fst, &frame, &named), + Some(Err(_)) => fst, + None => with_placed_copies(doc, st, fst, &doc.component_transform(f.component), &named), + }; let (plane, face_warning) = match (anchor, plane) { (Some(_), plane) => doc.resolve_attached_plane_noted(vals, plane, f.component, st, &fst)?, // A flat face of a sheet: the panel's exact plane, from its flat region and fold. @@ -8480,6 +8497,51 @@ pub fn state_in_frame_at<'a>(doc: &Document, st: &'a ModelState, comp: u64, fram Ok(Cow::Owned(out)) } +/// `framed` (the model `st` in the frame that `frame` places in the world) with the further +/// placements `names` names (`Block (Part:2)`), where they are in the world. A component's model +/// holds its first placement only, so a sketch projecting a copy's face found no body of that +/// name and took the first placement's (#9957). Only the named ones are placed: placing every +/// body of an assembly for each sketch made sketch edits as slow as the design is big. +pub fn with_placed_copies<'a>( + doc: &Document, + st: &ModelState, + framed: std::borrow::Cow<'a, ModelState>, + frame: &Mat, + names: &[&str], +) -> std::borrow::Cow<'a, ModelState> { + let missing: Vec<&str> = names.iter().copied().filter(|n| !n.is_empty() && framed.body(n).is_none()).collect(); + if missing.is_empty() || doc.occurrences.is_empty() { + return framed; + } + let Some(inv) = crate::mat_inverse(frame) else { return framed }; + let mut by_component: std::collections::HashMap> = std::collections::HashMap::new(); + for (b, owner) in st.bodies.iter().zip(doc.model_body_components(st)) { + by_component.entry(owner).or_default().push(b); + } + let world = crate::WorldNames::new(doc, st); + let mut placed: Vec = Vec::new(); + for (comp, path, m) in doc.placements() { + for b in by_component.get(&comp).into_iter().flatten() { + let name = world.name(&b.name, comp, &path); + if !missing.contains(&name.as_str()) || placed.iter().any(|p| p.name == name) { + continue; + } + let bm = doc.model_body_offset(b).map(|o| crate::mat_mul(&m, o)).unwrap_or(m); + if let Ok(mut copy) = st.body_in_frame(b, &crate::mat_mul(&inv, &bm)) { + copy.name = name; + copy.source_name = Some(b.definition_name().to_string()); + placed.push(copy); + } + } + } + if placed.is_empty() { + return framed; + } + let mut out = framed.into_owned(); + out.bodies.extend(placed); + std::borrow::Cow::Owned(out) +} + /// The model placed in the world: each component's bodies, sketches, threads and construction /// geometry through every occurrence of it (bodies of the first placement keep their names; /// further instances get the occurrence path in brackets). Without components this is the model diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 87c1bcb3f..1815e4f7d 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -92,8 +92,8 @@ pub use eval::{ blend_target, curve_pick_error, draft_corner_options, edge_names_for, edge_refs, face_point_names, face_point_state, hole_direction_at, hole_on_surface, import_body_names, join_pieces_added, map_wire, metric_thread_sizes, object_height, parse_metric_thread, pattern_matrices, revolve_extent, revolve_extent_for_handle, revolve_extent_with_convention, select_profiles, sketch_hole_direction, sketch_line_plane, - state_in_frame, state_in_frame_at, suggested_thread, suggested_thread_in, tangent_face_chain, through_all_distance, world_state, - world_state_reusing, + state_in_frame, state_in_frame_at, suggested_thread, suggested_thread_in, tangent_face_chain, through_all_distance, with_placed_copies, + world_state, world_state_reusing, }; pub use eval::{EvalCache, KeptResults}; pub use expr::Expr; diff --git a/crates/engine/src/cmd/browser.rs b/crates/engine/src/cmd/browser.rs index c75286f6e..fec2ab08b 100644 --- a/crates/engine/src/cmd/browser.rs +++ b/crates/engine/src/cmd/browser.rs @@ -1202,6 +1202,7 @@ fn rename_body(s: &mut Session, p: &Value) -> Result { } let previous = s.doc.clone(); let st = s.model.state(); + let placed = s.doc.body_frames_with_source(&st); let b = st.body(&old).ok_or_else(|| bad(cmd, format!("no body `{old}`")))?; if st.body(name).is_some() { return Err(bad(cmd, format!("another body is called `{name}`"))); @@ -1319,6 +1320,8 @@ fn rename_body(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, e)); } d.rename_body_keys(&old, name); + // A sketch projecting the body in another placement of its component keeps it. + super::sketch_project::follow_placed_renames(d, &st, &placed, Some((&old, name))); s.remember_body_rename(&previous, &old, name); Ok(json!({"body": old, "name": name})) } diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index 97f6a47fb..3225f6a45 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -394,6 +394,8 @@ fn rename(s: &mut Session, p: &Value) -> Result { let id = component(s, p, "component", cmd)?; let name = str_(p, "name").map(str::trim).filter(|n| !n.is_empty() && n.len() <= 128).ok_or_else(|| bad(cmd, "`name` must be 1…128 characters"))?; + let st = s.model.state(); + let placed = s.doc.body_frames_with_source(&st); let d = s.doc_mut(); if id == 0 { d.name = name.to_string(); @@ -406,6 +408,8 @@ fn rename(s: &mut Session, p: &Value) -> Result { o.name = format!("{name}:{k}"); } } + // A sketch projecting a body of one of those placements keeps it. + super::sketch_project::follow_placed_renames(d, &st, &placed, None); } Ok(json!({"component": id, "name": name})) } diff --git a/crates/engine/src/cmd/sketch_project.rs b/crates/engine/src/cmd/sketch_project.rs index 25949c093..f00fb8681 100644 --- a/crates/engine/src/cmd/sketch_project.rs +++ b/crates/engine/src/cmd/sketch_project.rs @@ -145,21 +145,84 @@ fn sketch_plane(doc: &Document, id: u64, st: &solidcraft_doc::ModelState) -> Res } /// The model before sketch `id` in the frame its links and its plane are resolved in: the -/// attached face's frame for a sketch on a face, else its component's. +/// attached face's frame for a sketch on a face, else its component's. The further placements +/// `named` names (`Block (Part:2)`) are in it too, where they are (#9957). fn state_for_sketch<'a>( s: &Session, doc: &Document, id: u64, st: &'a solidcraft_doc::ModelState, + named: &[&str], ) -> std::result::Result, solidcraft_doc::DocError> { let comp = doc.feature(id).map(|f| f.component).unwrap_or(0); let attachment = doc.feature(id).and_then(|feature| match &feature.kind { solidcraft_doc::FeatureKind::Sketch { plane, .. } => super::sketch::face::anchor(plane), _ => None, }); - match attachment { - Some(anchor) => solidcraft_doc::state_in_face_anchor_frame(doc, st, anchor, comp), - None => solidcraft_doc::state_in_frame_at(doc, st, comp, owner_frame(s, doc, comp)), + let (framed, frame) = match attachment { + Some(anchor) => (solidcraft_doc::state_in_face_anchor_frame(doc, st, anchor, comp)?, anchor.author_frame(doc, comp)?), + None => { + let frame = owner_frame(s, doc, comp); + (solidcraft_doc::state_in_frame_at(doc, st, comp, frame)?, frame) + } + }; + Ok(solidcraft_doc::with_placed_copies(doc, st, framed, &frame, named)) +} + +/// The placed bodies of a design (`Document::body_frames_with_source`): world name, definition +/// name, component, occurrence path and frame. +pub(super) type PlacedBodies = Vec<(String, String, u64, Vec, solidcraft_doc::Mat)>; + +/// Sketch links keep a further placement's body by the name the world gives it (`Block (Part:2)`, +/// #9957), which a rename of the body or of its component changes: each link naming one of +/// `before` (the placed bodies before the rename) now names what that body is called in `doc`. +/// `renamed` is the body renamed (old name, new name), if one was. +pub(super) fn follow_placed_renames(doc: &mut Document, st: &solidcraft_doc::ModelState, before: &PlacedBodies, renamed: Option<(&str, &str)>) { + let renames: std::collections::HashMap = { + let names = solidcraft_doc::WorldNames::new(doc, st); + before + .iter() + .filter(|(world, own, ..)| world != own) + .filter_map(|(world, own, component, path, _)| { + let source = match renamed { + Some((old, new)) if own == old => new, + _ => own.as_str(), + }; + let now = names.name(source, *component, path); + (now != *world).then(|| (world.clone(), now)) + }) + .collect() + }; + if renames.is_empty() { + return; + } + for f in &mut doc.features { + if let FeatureKind::Sketch { sketch, .. } = &mut f.kind { + for link in &mut sketch.links { + rename_link_body(&mut link.source, &renames); + } + } + } +} + +fn rename_link_body(source: &mut LinkSource, renames: &std::collections::HashMap) { + match source { + LinkSource::Edge { body, .. } + | LinkSource::Face { body, .. } + | LinkSource::Body { body } + | LinkSource::Vertex { body, .. } + | LinkSource::OnSurface { body, .. } + | LinkSource::Iso { body, .. } + | LinkSource::Spun { body, .. } => { + if let Some(new) = renames.get(body.as_str()) { + body.clone_from(new); + } + } + LinkSource::Intersection { a, b } => { + rename_link_body(a, renames); + rename_link_body(b, renames); + } + _ => {} } } @@ -205,7 +268,8 @@ pub(super) fn refresh(s: &Session, doc: &Document, id: u64, sk: &mut Sketch) -> solidcraft_doc::FeatureKind::Sketch { plane, .. } => super::sketch::face::anchor(plane), _ => None, }); - let Ok(st) = state_for_sketch(s, &doc, id, &st) else { + let named: Vec<&str> = sk.links.iter().flat_map(|l| l.source.bodies()).collect(); + let Ok(st) = state_for_sketch(s, &doc, id, &st, &named) else { return vec!["lost face attachment; reattach explicitly".into()]; }; let Ok(plane) = sketch_plane(&doc, id, &st) else { return Vec::new() }; @@ -257,7 +321,7 @@ pub(super) fn origin_axis_line(s: &Session, p: &Value, line: &Value, cmd: &str) let id = sketch_store::target(s, p, cmd)?; let doc = placed_candidate(s, &s.doc); let st = s.model.state_before(id); - let st = state_for_sketch(s, &doc, id, &st)?; + let st = state_for_sketch(s, &doc, id, &st, &[])?; let plane = sketch_plane(&doc, id, &st)?; let src = source(s, line, cmd)?; let LinkSource::Axis { name } = &src else { return Err(bad(cmd, "the mirror line must be a straight sketch curve or an origin axis")) }; @@ -297,7 +361,7 @@ fn add_link_unless_present( let (vals, _) = doc.param_values(); let st = s.model.state_before(id); // The model as the sketch's component sees it. - let st = state_for_sketch(s, &doc, id, &st)?; + let st = state_for_sketch(s, &doc, id, &st, &src.bodies())?; let plane = sketch_plane(&doc, id, &st)?; let r = resolve(&doc, &vals, &st, &plane, kind, &src)?; if skip_present && r.wires.is_empty() && sk.link_geometry_present(&r.geom) { @@ -719,7 +783,7 @@ pub(super) fn snap_points(s: &mut Session, p: &Value, cmd: &str) -> Result = + sk.links.iter().flat_map(|l| sk.link_points(&l.id)).filter_map(|p| sk.points.get(p)).map(|p| ss.plane.to_world(p.pos)).collect(); + assert!(!points.is_empty()); + assert!(points.iter().all(|p| p.x > 49.9 && p.x < 70.1 && p.y > y - 0.1 && p.y < y + 20.1), "sketch {id}, y {y}: {points:?}"); + } + }; + check(&s, 0.0); + // A design opened again, so rebuilt from its features, finds the copy as well. + check(&Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()), 0.0); + // Moving the copy moves what was projected from it. + let first = s.doc.occurrences[0].id; + let copy = s.doc.occurrences.iter().map(|o| o.id).find(|id| *id != first).unwrap(); + run(&mut s, "occurrence.move", json!({"occurrence":copy,"translate":[0,15,0],"capture":true})); + check(&s, 15.0); + // Renaming the part or the body renames the copy ("Base (Housing:2)"): the links follow it. + run(&mut s, "component.rename", json!({"component":part["component"],"name":"Housing"})); + run(&mut s, "body.rename", json!({"body":"Block","name":"Base"})); + assert!(s.model.state().sketch(sketches[0]).unwrap().sketch.links.iter().all(|l| l.source.bodies() == ["Base (Housing:2)"])); + check(&s, 15.0); + check(&Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()), 15.0); +} diff --git a/crates/engine/src/frames.rs b/crates/engine/src/frames.rs index 150a5d64f..6bb8c4ee6 100644 --- a/crates/engine/src/frames.rs +++ b/crates/engine/src/frames.rs @@ -291,7 +291,10 @@ impl Mapper<'_> { m.insert(k.into(), y); } } + // A sketch's view of the model holds a further placement by the name the world + // gives it (`with_placed_copies`), so that name stays (#9957). if let Some(bn) = &b + && !self.here && let Some(own) = self.own_name(bn) { m.insert("body".into(), Value::String(own));