diff --git a/crates/doc/src/config_styles.rs b/crates/doc/src/config_styles.rs index 30ef3d7e8..fac9ec97a 100644 --- a/crates/doc/src/config_styles.rs +++ b/crates/doc/src/config_styles.rs @@ -149,7 +149,10 @@ impl Document { sketch == producer_sketch && extent.taper.is_none() && role == format!("side:{curve}") && self.feature(*sketch).is_some_and(|feature| matches!(&feature.kind, FeatureKind::Sketch { sketch, .. } if sketch.curves.iter().any(|candidate| candidate.id == *curve && !candidate.construction && matches!(candidate.kind, solidcraft_sketch::CurveKind::Line { .. } | solidcraft_sketch::CurveKind::Circle { .. } | solidcraft_sketch::CurveKind::Arc { .. })))) } - (super::FaceCertificate::Imported { .. }, FeatureKind::Import { .. }) => role.strip_prefix("face:").is_some_and(|index| index.parse::().is_ok()), + // A linked design's face is named after its name there (`link:…`, see lineage::link_role). + (super::FaceCertificate::Imported { .. }, FeatureKind::Import { .. }) => { + role.strip_prefix("face:").is_some_and(|index| index.parse::().is_ok()) || role.starts_with("link:") + } (super::FaceCertificate::Lineage, _) => !role.is_empty(), (super::FaceCertificate::ShellPlanar { source_producer, source, inner }, FeatureKind::Shell { .. }) => { *source_producer != target.origin_feature diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 32327ddd2..cd2ec9198 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -2395,6 +2395,11 @@ pub struct Feature { /// independent base of a copied component. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub inserted: bool, + /// The Import feature of a linked design (Insert Design): the names that design gave the + /// faces of its bodies (by body, then face, in the file's order; empty where not known), so + /// its faces are named after them and references follow them through Update Links (#3330). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub link_faces: Vec>, #[serde(flatten)] pub kind: FeatureKind, } @@ -3160,6 +3165,7 @@ impl Document { shell_piece_order: false, kernel_piece_order: false, inserted: false, + link_faces: Vec::new(), kind, }; self.place_feature(f); diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 021557912..d37ba42aa 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -6898,9 +6898,10 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: let imp = kernel::step_import_shared(step)?; let digest = crate::config::payload_digest(step); let names = import_body_names(st, &f.body_names, &imp, skip); - for (b, name) in imp.bodies.iter().zip(names) { + for (k, (b, name)) in imp.bodies.iter().zip(names).enumerate() { let Some(name) = name else { continue }; - let b = crate::lineage::numbered_tool(b.body.clone().with_import_certificate(&digest, f.id)?); + let carried = f.link_faces.get(k).map_or(&[][..], Vec::as_slice); + let b = crate::lineage::linked_tool(b.body.clone().with_import_certificate(&digest, f.id)?, f.id, carried); st.bodies.push(ModelBody::traced_new(name, b, f.id)); } if !imp.warnings.is_empty() { diff --git a/crates/doc/src/format/pending/linked-face-names.rs b/crates/doc/src/format/pending/linked-face-names.rs new file mode 100644 index 000000000..112aa0f1d --- /dev/null +++ b/crates/doc/src/format/pending/linked-face-names.rs @@ -0,0 +1,6 @@ +//! The Import feature of a linked design (Insert Design) saves `link_faces`: the names that +//! design gives the faces of its bodies (by body, then face), so the linked faces are named after +//! them and joints on them follow them through Update Links (#3330). An older design has none +//! until its links are next updated; its linked faces keep their numbered names (`face:`), +//! which they still answer to afterwards. The last release refuses a design that has them (it +//! refuses the newer format number). diff --git a/crates/doc/src/history_names_tests.rs b/crates/doc/src/history_names_tests.rs index adee0b05d..d938c1a48 100644 --- a/crates/doc/src/history_names_tests.rs +++ b/crates/doc/src/history_names_tests.rs @@ -66,3 +66,28 @@ fn a_merged_face_takes_the_shared_stem_or_the_first_name_and_answers_to_the_othe let names = qualify(vec![m], &[]); assert_eq!(matches(&names, 0, "F9:top"), Some(Match::Alias)); } + +/// #3330: a linked design's faces are named after the names that design gave them, so what the +/// name holds must mean nothing else in the assembly, while its pieces stay pieces. +#[test] +fn a_linked_designs_face_names_keep_their_pieces_and_nothing_else() { + use crate::lineage::link_role; + let role = |n: &str| link_role(7, n, 0); + // A whole face is a digest of its name, the same on every build. + assert_eq!(role("F2:top"), "link:eb25d870dc3c9480"); + assert_ne!(role("F2:side:c0"), role("F3:side:c0")); + // No feature number, `@`, `|` or `#` of that design is left to be read as one of this design. + let blend = role("F3:blend:F2:top|F2:side:l4@F5.1"); + assert!(blend.starts_with("link:") && !blend.contains(['@', '|', '#', 'F']), "{blend}"); + // A piece keeps its qualifier, the faces around it named as they are here. + assert_eq!(role("F2:top#[F2:side:l4,F4:side:l4]#2"), format!("{}#[F7:{},F7:{}]#2", role("F2:top"), role("F2:side:l4"), role("F4:side:l4"))); + assert_eq!(role("F2:top#3"), format!("{}#3", role("F2:top"))); + let nested = format!("F7:{}", role("F2:top#[a]#[b]")); + assert_eq!(crate::naming::strip_piece(&nested), format!("F7:{}", role("F2:top"))); + assert_eq!(crate::naming::parent_piece(&nested), Some(format!("F7:{}", role("F2:top#[a]")).as_str())); + // Hostile names never panic, and qualifiers are read only so deep. + assert!(role(&format!("F1:top{}", "#[a]".repeat(10_000))).len() < 2_000); + for n in ["", "#", "#[", "]", "a#[", "#[]", "x#[[]]]", "#1", "a#[b]#", "é#[ü]"] { + let _ = role(n); + } +} diff --git a/crates/doc/src/lineage.rs b/crates/doc/src/lineage.rs index ce548df89..3ae653095 100644 --- a/crates/doc/src/lineage.rs +++ b/crates/doc/src/lineage.rs @@ -412,10 +412,50 @@ pub(crate) fn part_tool(body: Body, part: &str) -> Traced { /// Faces named by their place in a body built as a whole (an imported part's faces in the /// file's order): `face:`. pub(crate) fn numbered_tool(body: Body) -> Traced { - let roles = (0..body.face_count()).map(|k| vec![format!("face:{k}")]).collect(); + linked_tool(body, 0, &[]) +} + +/// [`numbered_tool`] for a body of feature `fid` imported from a linked design, whose faces that +/// design named `carried` (by face, empty where not known): such a face is named after its name +/// there ([`link_role`]), so a reference to it follows that name, not the face's place in the +/// file, when the design changes; it still answers to `face:`. +pub(crate) fn linked_tool(body: Body, fid: u64, carried: &[String]) -> Traced { + let roles = (0..body.face_count()) + .map(|k| { + let numbered = format!("face:{k}"); + match carried.get(k).filter(|n| !n.is_empty()) { + Some(name) => vec![link_role(fid, name, 0), numbered], + None => vec![numbered], + } + }) + .collect(); Traced::made(body, Some(roles)) } +/// Nesting of piece qualifiers a carried name is read through (deeper ones are digested whole). +const MAX_LINK_DEPTH: usize = 32; + +/// The role of a face a linked design named `name`: `link:`, a digest of the name (which +/// may hold anything: `@`, `|` and feature numbers of that design mean something else here). A +/// piece keeps its qualifier, with the faces around it named the same way (`F:link:…`), so +/// its pieces are told apart and found as they are in that design. +pub(crate) fn link_role(fid: u64, name: &str, depth: usize) -> String { + let Some((stem, around)) = crate::piece_names::piece_parts(name).filter(|_| depth < MAX_LINK_DEPTH) else { + // FNV-1a: the same digest on every build and platform. + let digest = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)); + return format!("link:{digest:016x}"); + }; + let mut role = link_role(fid, stem, depth + 1); + if name.get(stem.len()..).is_some_and(|rest| rest.starts_with("#[")) { + let around: Vec = around.iter().map(|a| format!("F{fid}:{}", link_role(fid, a, depth + 1))).collect(); + role.push_str(&format!("#[{}]", around.join(","))); + } + if let Some((_, k)) = name.rsplit_once('#').filter(|(_, k)| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit())) { + role.push_str(&format!("#{k}")); + } + role +} + /// The role of an extrude's cap at `height` along the sketch normal: on the sketch plane, above /// it or below it. pub(crate) fn extrude_cap_role(height: f64) -> String { diff --git a/crates/doc/src/naming.rs b/crates/doc/src/naming.rs index f898030e9..f4024e0f7 100644 --- a/crates/doc/src/naming.rs +++ b/crates/doc/src/naming.rs @@ -805,6 +805,48 @@ pub fn face_name_at_body(body: &ModelBody, point: Vec3) -> Option { face_names(body).get(index).filter(|name| !name.is_empty()).cloned() } +/// The names the faces of `imported` have in `part`, by body, then face (empty where not known): +/// `imported` are the bodies read back from the STEP text `part`'s solid bodies were written to +/// (a linked design), where they stand in it. Each takes the names of the solid of `part` that +/// most of its faces lie on, face by face: the same geometry, so a point well inside a face lies +/// on the face it was written from (and on a face of another solid only where two touch). Of +/// solids that hold as many (two alike in one place), the one the file names it after. +pub fn carried_face_names(part: &ModelState, imported: &[solidcraft_kernel::ImportedBody]) -> Vec> { + let solids: Vec<&ModelBody> = part.bodies.iter().filter(|b| !b.body.is_mesh()).collect(); + let indices: Vec>> = solids.iter().map(|_| OnceLock::new()).collect(); + imported + .iter() + .map(|read| { + let probe = ModelBody::new(String::new(), read.body.clone(), 0); + let points: Vec> = face_spots(&probe).into_iter().map(|s| s.map(|s| s.point)).collect(); + let best = solids + .iter() + .zip(&indices) + .filter_map(|(b, index)| { + let tol = (b.body.size() * 2e-3).max(1e-3); + let near = b.outline_bounds().inflated(tol); + if !points.iter().flatten().any(|p| near.contains(*p)) { + return None; + } + // Like face_name_at_body, a body too large to index is left unnamed. + let index = index + .get_or_init(|| { + let mesh = b.mesh(); + (mesh.triangles.len() <= 2_000_000 && face_count(b) <= 50_000).then(|| FaceIndex::new(&mesh, face_count(b))) + }) + .as_ref()?; + let hits: Vec> = points.iter().map(|p| p.and_then(|p| index.face_at(p, tol))).collect(); + Some((hits.iter().flatten().count(), *b, hits)) + }) + .filter(|(n, ..)| *n > 0) + .max_by_key(|(n, b, _)| (*n, b.name == read.name)); + let Some((_, b, hits)) = best else { return Vec::new() }; + let names = face_names(b); + hits.into_iter().map(|h| h.and_then(|i| names.get(i).cloned()).unwrap_or_default()).collect() + }) + .collect() +} + /// Where a face is, for a script: a point that lies on it and picks it, and the plane, cylinder, /// cone, sphere or torus it is part of (when it is one). #[derive(Clone, Copy, Debug)] diff --git a/crates/engine/src/cmd/component_extract.rs b/crates/engine/src/cmd/component_extract.rs index 8f9944aa4..e20e38ed3 100644 --- a/crates/engine/src/cmd/component_extract.rs +++ b/crates/engine/src/cmd/component_extract.rs @@ -566,7 +566,7 @@ pub(super) fn extract(s: &mut Session, p: &Value) -> Result { // This design: the component's history becomes an Import feature of the new design's bodies let shown = file.display().to_string(); - let (_, sf) = session_bodies(&part, &shown)?; + let (_, sf, faces) = session_bodies(&part, &shown)?; // The link has a body per piece: a body in pieces keeps its name on the first let mut solids: Vec = Vec::new(); for b in part.world_state().bodies.iter().filter(|b| !b.body.is_mesh()) { @@ -589,6 +589,7 @@ pub(super) fn extract(s: &mut Session, p: &Value) -> Result { if let Some(f) = d.feature_mut(id) { f.component = comp; f.body_names = if solids.len() == sf.body_names.len() { solids } else { sf.body_names }; + f.link_faces = faces; } let path = stored(s.path.as_deref(), &file); s.doc_mut().links.insert(comp, DesignLink { path: path.clone(), feature: id }); diff --git a/crates/engine/src/cmd/component_link.rs b/crates/engine/src/cmd/component_link.rs index 2cfe57dab..205ab7b4e 100644 --- a/crates/engine/src/cmd/component_link.rs +++ b/crates/engine/src/cmd/component_link.rs @@ -4,7 +4,9 @@ //! join a new component through an Import feature (exact B-rep, kept in this design so it opens //! without the part file). The link remembers the file, relative to this design's folder once it //! is saved; Update Links reads the file again and replaces the Import feature's bodies, and -//! Break Link keeps the bodies and forgets the file. +//! Break Link keeps the bodies and forgets the file. The bodies' faces are named after the names +//! the design gives them (`Feature::link_faces`), so a joint on a linked face stays on that face +//! when the design changes, as it would inside the design, and reports it when the face is gone. use std::path::{Component as PathPart, Path, PathBuf}; @@ -30,7 +32,8 @@ pub static COMMANDS: &[CommandSpec] = &[ reuse?: bool (default false): insert a free occurrence, reusing an existing link to the same file when available", ), CommandSpec::new("component.update_links", "Update Links", update_links).icon("update").params( - "component?: id or name (default: every linked component) — reads the linked designs again and replaces their bodies where they changed", + "component?: id or name (default: every linked component) — reads the linked designs again and replaces their bodies where they changed; \ + → updated, unchanged, warnings (also joints whose faces are gone or that no longer solve)", ), CommandSpec::new("component.relink", "Relink Source", relink).icon("update").params( "component: id or name of a linked component; path: a saved .solidcraft design — replaces the source and linked bodies for all its occurrences, preserving identities and placements; returns path, previous_path, warnings, joint_errors and joint_conflicts", @@ -120,8 +123,12 @@ pub(super) fn rebased(doc: &Document, from: Option<&str>, to: &str) -> std::coll doc.links.iter().map(|(c, l)| (*c, DesignLink { path: stored(Some(to), &resolve(from, &l.path)), feature: l.feature })).collect() } +/// The bodies of a linked design: its name, the Import feature that holds them and the names +/// the design gives their faces (`Feature::link_faces`). +type Linked = (String, solidcraft_io::StepFeature, Vec>); + /// The solid bodies of the design at `file`, evaluated, as an Import feature. -fn linked_bodies(file: &Path, own: Option<&str>) -> Result<(String, solidcraft_io::StepFeature)> { +fn linked_bodies(file: &Path, own: Option<&str>) -> Result { let shown = file.display().to_string(); if own.is_some_and(|o| absolute(Path::new(o)) == absolute(file)) { return Err(EngineError::Other(format!("{shown}: a design can't be linked into itself"))); @@ -132,7 +139,7 @@ fn linked_bodies(file: &Path, own: Option<&str>) -> Result<(String, solidcraft_i } /// The solid bodies of `part`, the design saved as `shown`, as an Import feature. -fn session_bodies(part: &Session, shown: &str) -> Result<(String, solidcraft_io::StepFeature)> { +fn session_bodies(part: &Session, shown: &str) -> Result { let name = part.doc.name.clone(); if let Some(e) = part.model.results.iter().find_map(|r| r.error.clone()) { return Err(EngineError::Other(format!("{shown}: the design has a feature that fails ({e}); fix it before linking it"))); @@ -148,7 +155,10 @@ fn session_bodies(part: &Session, shown: &str) -> Result<(String, solidcraft_io: if world.bodies.len() > solids.len() { feature.warnings.push(format!("{} mesh bodies of {shown} are not linked", world.bodies.len() - solids.len())); } - Ok((name, feature)) + // The STEP text keeps no face names: carry the design's own, so references into the linked + // bodies follow them as they do inside the design (#3330). + let faces = solidcraft_doc::naming::carried_face_names(&world, &feature.import.bodies); + Ok((name, feature, faces)) } fn component_key(s: &Session, p: &Value, key: &str, cmd: &str) -> Result { @@ -178,7 +188,7 @@ fn insert_design(s: &mut Session, p: &Value) -> Result { return super::component::copy_occurrence(s, &json!({"component": component, "parent": parent, "translate": translate})); } } - let (design_name, sf) = linked_bodies(&file, s.path.as_deref())?; + let (design_name, sf, faces) = linked_bodies(&file, s.path.as_deref())?; let name = str_(p, "name").filter(|n| !n.trim().is_empty()).map(str::to_string).unwrap_or(design_name); let mut create = json!({"name": name, "activate": false}); // Clipboard insertion uses reuse even for the first paste, which must stay movable. @@ -195,6 +205,7 @@ fn insert_design(s: &mut Session, p: &Value) -> Result { if let Some(f) = s.doc_mut().feature_mut(id) { f.component = comp; f.body_names = sf.body_names; + f.link_faces = faces; } if let Some(o) = s.doc_mut().occurrences.iter_mut().find(|o| Some(o.id) == occ) { o.transform[3] = [translate.x, translate.y, translate.z, 1.0]; @@ -237,28 +248,63 @@ fn update_links(s: &mut Session, p: &Value) -> Result { }; let old = old.clone(); let file = resolve(s.path.as_deref(), &link.path); - let (_, sf) = linked_bodies(&file, s.path.as_deref()).map_err(|e| bad(cmd, format!("{cname}: {e}")))?; + let (_, sf, faces) = linked_bodies(&file, s.path.as_deref()).map_err(|e| bad(cmd, format!("{cname}: {e}")))?; warnings.extend(sf.warnings.iter().cloned()); - if matches!(&sf.kind, FeatureKind::Import { step, .. } if *step == old) { + let same = matches!(&sf.kind, FeatureKind::Import { step, .. } if *step == old); + let kept = s.doc.feature(link.feature).map(|f| &f.link_faces); + if same && kept == Some(&faces) { unchanged.push(cname); continue; } - if let Some(f) = s.doc_mut().feature_mut(link.feature) { - // Bodies keep their names where the design still has as many. - if f.body_names.len() != sf.body_names.len() { - f.body_names = sf.body_names; + // The same bodies, their faces named for the first time (a link made before names were + // kept): nothing a reference finds changes. Names the design gave other faces since do. + let changed = !same || kept.is_some_and(|k| !k.is_empty()); + if !same { + for name in numbered_references(s, comp, link.feature) { + warnings.push(format!( + "{name} refers to faces of {cname} by their place in the linked file, which this update can change: check it, and pick its faces again so it follows them by name" + )); } - f.kind = sf.kind; } - updated.push(cname); + if let Some(f) = s.doc_mut().feature_mut(link.feature) { + if !same { + // Bodies keep their names where the design still has as many. + if f.body_names.len() != sf.body_names.len() { + f.body_names = sf.body_names; + } + f.kind = sf.kind; + } + // A link made before the design's face names were kept gets them here. + f.link_faces = faces; + } + if changed { updated.push(cname) } else { unchanged.push(cname) } } s.refresh(); if let Some(e) = s.doc.links.values().find_map(|l| s.model.result(l.feature).and_then(|r| r.error.clone())) { return Err(EngineError::Other(e)); } + // A reference whose face the design no longer has says so here, not only in the joint list. + if !updated.is_empty() { + let sol = solidcraft_doc::joints::solve(&s.doc, &s.model.state()); + warnings.extend(sol.errors.iter().chain(&sol.conflicts).map(|(_, name, why)| format!("joint {name}: {why}"))); + } Ok(json!({"updated": updated, "unchanged": unchanged, "warnings": warnings})) } +/// The joints and joint origins on occurrences of `comp` that name its linked faces by their +/// place in the file (`F:face:`, made before the design's own names were kept), which +/// an update can give to another face. +fn numbered_references(s: &Session, comp: u64, feature: u64) -> Vec { + let numbered = format!("F{feature}:face:"); + let on = |o: &solidcraft_doc::joints::JointOrigin| { + s.doc.occurrences.iter().any(|x| x.id == o.occurrence && x.component == comp) + && o.snap.face_names().iter().any(|n| n.trim_start_matches(solidcraft_doc::naming::LEGACY_MARK).starts_with(&numbered)) + }; + let joints = s.doc.assembly.joints.iter().filter(|j| on(&j.a) || on(&j.b)).map(|j| format!("joint {}", j.name)); + let origins = s.doc.assembly.origins.iter().filter(|o| on(&o.origin)).map(|o| format!("joint origin {}", o.name)); + joints.chain(origins).collect() +} + fn relink(s: &mut Session, p: &Value) -> Result { let cmd = "component.relink"; let comp = component_key(s, p, "component", cmd)?; @@ -280,7 +326,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { } // Read/evaluate the candidate before changing anything. Session::execute owns the single // undo step and restores both the document and evaluated state on any later failure. - let (_, sf) = linked_bodies(&file, s.path.as_deref()).map_err(|e| bad(cmd, e.to_string()))?; + let (_, sf, faces) = linked_bodies(&file, s.path.as_deref()).map_err(|e| bad(cmd, e.to_string()))?; let geometry_changed = match (s.doc.feature(link.feature).map(|f| &f.kind), &sf.kind) { (Some(FeatureKind::Import { step: old, .. }), FeatureKind::Import { step, .. }) => old != step, _ => true, @@ -301,6 +347,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { f.body_names = sf.body_names; } f.kind = sf.kind; + f.link_faces = faces; } s.doc_mut().links.insert(comp, DesignLink { path: path.clone(), feature: link.feature }); s.refresh(); @@ -431,4 +478,136 @@ mod tests { assert!(s.execute("component.insert_design", &json!({"path": "x.solidcraft", "translate": [1, "a", 2]})).is_err()); assert!(s.doc.components.is_empty() && s.doc.links.is_empty() && s.doc.features.is_empty()); } + + /// #3330's part: a plate 60 × 40 × 5 with a Ø 6 hole at x = `hx` (10 mm), saved at `path`. The + /// session stays open to edit the part as a user would. + fn plate(path: &Path) -> Session { + let mut part = Session::default(); + run(&mut part, "parameters.add", json!({"name": "hx", "expression": "10 mm"})); + run(&mut part, "solid.box", json!({"length": 60, "width": 40, "height": 5, "corner": [-30, -20, 0], "body_name": "Plate"})); + run(&mut part, "solid.cylinder", json!({"diameter": 6, "height": 7, "base": ["hx", 0, -1], "operation": "cut", "name": "Hole"})); + run(&mut part, "file.save", json!({"path": path})); + part + } + + /// Another Ø 6 hole through the plate at `x`. + fn hole(part: &mut Session, x: f64, name: &str) { + run(part, "solid.cylinder", json!({"diameter": 6, "height": 7, "base": [x, 0, -1], "operation": "cut", "name": name})); + } + + /// #3330's assembly: the plate linked in and grounded, and a pin rigidly jointed to the top edge + /// of its hole. `older`: the link keeps no face names, as one made before them. + fn pinned(path: &Path, older: bool) -> Session { + let mut s = Session::default(); + let feature = run(&mut s, "component.insert_design", json!({"path": path, "name": "Plate"}))["feature"].as_u64().unwrap(); + if older { + s.doc_mut().feature_mut(feature).unwrap().link_faces.clear(); + s.refresh(); + } + run(&mut s, "occurrence.ground", json!({"occurrence": "Plate:1", "grounded": true})); + run(&mut s, "solid.cylinder", json!({"diameter": 6, "height": 20, "base": [0, 50, 0], "operation": "new", "body_name": "PinBody"})); + run(&mut s, "component.create", json!({"name": "Pin", "parent": "root", "activate": false})); + run(&mut s, "component.move_bodies", json!({"bodies": ["PinBody"], "component": "Pin"})); + let joint = json!({"type": "rigid", "name": "PinInHole", "flip": true, + "a": {"occurrence": "Plate:1", "circle": [13, 0, 5]}, "b": {"occurrence": "Pin:1", "circle": [3, 50, 0]}}); + run(&mut s, "joint.create", joint); + s + } + + /// Asserts the pin's joint sits on the plate's top at x (world) and solves without errors. + fn assert_joint_at(s: &mut Session, x: f64, case: &str) { + let list = run(s, "joint.list", json!({})); + assert_eq!(list["errors"], json!([]), "{case}: {list}"); + let o = &list["joints"][0]["frame_a"]["origin"]; + let at = [0, 1, 2].map(|i| o[i].as_f64().unwrap_or(f64::NAN)); + assert!((at[0] - x).abs() < 1e-6 && at[1].abs() < 1e-6 && (at[2] - 5.0).abs() < 1e-6, "{case}: the joint is at {at:?}, not x = {x}"); + } + + /// #3330: a joint on a linked part's hole stays on that hole when Update Links brings in an + /// edit of the part, as it does inside one design, also when the edit adds a hole of the same + /// size that takes the first one's place in the file. + #[test] + fn joints_on_a_linked_part_follow_its_faces_through_update_links() { + let dir = std::env::temp_dir().join(format!("solidcraft-link-names-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("plate.solidcraft"); + let hx = |part: &mut Session, x: &str| { + run(part, "parameters.change", json!({"name": "hx", "expression": x})); + }; + let edits: [(&str, &dyn Fn(&mut Session), f64); 3] = [ + ("the hole moved to x = 20", &|p: &mut Session| hx(p, "20 mm"), 20.0), + ( + "a hole at x = -10 added before it in the timeline, and the hole moved to x = 20", + &|p: &mut Session| { + run(p, "timeline.rollback", json!({"position": 1})); + hole(p, -10.0, "Hole0"); + run(p, "timeline.rollback", json!({})); + hx(p, "20 mm"); + }, + 20.0, + ), + ( + "the hole moved to x = 5, and a hole added at x = 15", + &|p: &mut Session| { + hx(p, "5 mm"); + hole(p, 15.0, "Hole2"); + }, + 5.0, + ), + ]; + for (case, edit, x) in edits { + let mut part = plate(&path); + let mut s = pinned(&path, false); + assert_joint_at(&mut s, 10.0, case); + edit(&mut part); + run(&mut part, "file.save", json!({})); + let update = run(&mut s, "component.update_links", json!({})); + assert_eq!(update["updated"], json!(["Plate"]), "{case}: {update}"); + assert_eq!(update["warnings"], json!([]), "{case}: {update}"); + assert_joint_at(&mut s, x, case); + } + let _ = std::fs::remove_dir_all(&dir); + } + + /// #3330: when the part no longer has the face a joint is on, Update Links and the joint list + /// say so instead of moving the joint to another hole of the same size. + #[test] + fn a_joint_whose_linked_face_is_gone_is_reported_not_moved() { + let dir = std::env::temp_dir().join(format!("solidcraft-link-gone-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("plate.solidcraft"); + let mut part = plate(&path); + let mut s = pinned(&path, false); + hole(&mut part, -10.0, "Hole0"); + run(&mut part, "timeline.delete", json!({"feature": "Hole"})); + run(&mut part, "file.save", json!({})); + let update = run(&mut s, "component.update_links", json!({})); + let warnings = update["warnings"].to_string(); + assert!(warnings.contains("joint PinInHole") && warnings.contains("no longer exists"), "{update}"); + let list = run(&mut s, "joint.list", json!({})); + assert_eq!(list["errors"][0]["name"], "PinInHole", "{list}"); + assert!(list["joints"][0]["frame_a"].is_null(), "{list}"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A joint made on a link that kept no face names (an older design) names the faces by their + /// place in the file: Update Links says it can't vouch for it, and keeps the names from then on. + #[test] + fn update_links_warns_about_joints_on_faces_named_by_their_place() { + let dir = std::env::temp_dir().join(format!("solidcraft-link-numbered-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("plate.solidcraft"); + let mut part = plate(&path); + let mut s = pinned(&path, true); + let feature = s.doc.links.values().next().unwrap().feature; + assert!(s.doc.feature(feature).unwrap().link_faces.is_empty()); + // An unchanged part keeps the bodies; the names come in quietly. + assert_eq!(run(&mut s, "component.update_links", json!({}))["unchanged"], json!(["Plate"])); + assert!(!s.doc.feature(feature).unwrap().link_faces.is_empty()); + run(&mut part, "parameters.change", json!({"name": "hx", "expression": "20 mm"})); + run(&mut part, "file.save", json!({})); + let update = run(&mut s, "component.update_links", json!({})); + assert!(update["warnings"].to_string().contains("joint PinInHole refers to faces of Plate by their place"), "{update}"); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/docs/book/src/dev/naming.md b/docs/book/src/dev/naming.md index 2ba80c42b..a99c5cae0 100644 --- a/docs/book/src/dev/naming.md +++ b/docs/book/src/dev/naming.md @@ -30,7 +30,7 @@ tool built from a sketch, cut from each target, the cut body split into lumps) i | a body of the model before the feature | as they were | | a moved copy of one (pattern, mirror) | `@F.` | | the cavity side of a shell grown outward | `F:inner:` | -| a body the feature built | by role: `F:side:`, `start`/`top`/`bottom`/`end` caps, `+x`… box sides, `face:` imported faces | +| a body the feature built | by role: `F:side:`, `start`/`top`/`bottom`/`end` caps, `+x`… box sides, `face:` imported faces, `link:` faces of a linked design (see below) | | a copied tool of a patterned feature | `F:@F.` | `crates/doc/src/history_names.rs` names each face of the result from its origins: a kept or @@ -56,6 +56,20 @@ curve the profile segment lies on exactly; nothing is sampled. Names are worked out lazily, on first request, and shared by a body's clones. +### Linked designs + +A linked design (Insert Design) comes in as STEP text, which keeps no names: its faces would be +named by their place in the file (`face:`), and adding a hole to the part can give that place to +another face. So when the link is made or updated, each face is matched to the face of the part it +was written from (the same geometry, so a point well inside one lies on the other) and the Import +feature keeps that face's name in the part (`Feature::link_faces`). The face is named +`F:link:`, a digest of that name (which may hold anything: the part's feature +numbers and `@`, `|` mean something else in the assembly), and a piece keeps its qualifier with the +faces around it named the same way. A joint or other reference on a linked face therefore stays on +it across Update Links exactly as it would inside the part, and says so when the part no longer has +the face. Every linked face still answers to `face:`, so references made before keep finding +their face by place; Update Links warns about joints that do. + ### Where there is no history A body made by an operation that does not report history yet (some kernel paths return none; see