diff --git a/crates/doc/src/assembly.rs b/crates/doc/src/assembly.rs index d2d2c80fb..0ca382f85 100644 --- a/crates/doc/src/assembly.rs +++ b/crates/doc/src/assembly.rs @@ -313,9 +313,10 @@ impl Document { pub fn body_frames_with_source(&self, st: &crate::ModelState) -> Vec<(String, String, u64, Vec, Mat)> { let mut out = Vec::new(); let owners = self.model_body_components(st); + let names = WorldNames::new(self, st); for (comp, path, m) in self.placements() { for (b, _) in st.bodies.iter().zip(&owners).filter(|(_, owner)| **owner == comp) { - let name = self.world_body_name(st, &b.name, comp, &path); + let name = names.name(&b.name, comp, &path); let w = match self.model_body_offset(b) { Some(o) => mat_mul(&m, o), None => m, @@ -328,38 +329,10 @@ impl Document { /// Computed placement name. Source names retain priority; ambiguous labels use full IDs. /// Resolves label ambiguity with bounded dynamic counts instead of expanding all placements. + /// To name many placed bodies, make one [`WorldNames`] and ask it for each. pub fn world_body_name(&self, st: &crate::ModelState, source: &str, component: u64, path: &[u64]) -> String { - if path == self.first_path(component) { - return source.to_string(); - } - let names: Vec<&str> = path.iter().filter_map(|id| self.occurrences.iter().find(|o| o.id == *id)).map(|o| o.name.as_str()).collect(); - let label = names.join("/"); - let candidate = format!("{source} ({label})"); - let mut counts = std::collections::BTreeMap::from([(0, 1usize)]); - for name in &names { - let mut next = std::collections::BTreeMap::::new(); - for o in self.occurrences.iter().filter(|o| o.name == *name) { - if let Some(count) = counts.get(&o.parent) { - let n = next.entry(o.component).or_default(); - *n = (*n + count).min(2); - } - } - counts = next; - } - let ambiguous = counts.get(&component).copied().unwrap_or(0) > 1; - // Slash and reserved-marker names could alias concatenated labels or fallback keys. - let reserved = - self.occurrences.iter().any(|o| o.name.contains('/') || o.name.contains("@occ[")) || st.bodies.iter().any(|b| b.name.contains("@occ[")); - if !ambiguous && !reserved && st.body(&candidate).is_none() { - return candidate; - } - let ids = path.iter().map(u64::to_string).collect::>().join("/"); - let encoded = serde_json::to_string(source).unwrap_or_else(|_| source.to_string()); - let mut key = format!("{encoded}@occ[{ids}]"); - while st.body(&key).is_some() { - key.push('#'); - } - key + // One name: scanning the design once is cheaper than indexing it first. + placed_name(&Scan { doc: self, st }, source, component, path) } /// The occurrence path of a component's first placement. @@ -438,3 +411,140 @@ impl Document { Ok(id) } } + +/// The names of a design's placed bodies ([`Document::world_body_name`]), with what naming one +/// needs from the whole design worked out once: the occurrences by id, by name and by +/// component, the model's body names, and whether any name could alias a label or fallback key. +/// Naming each body of an assembly is then as cheap as its occurrence path, not a scan of the +/// whole design. +pub struct WorldNames<'a> { + /// The first occurrence with each id. + by_id: std::collections::HashMap, + /// The occurrences with each name, in document order. + by_name: std::collections::HashMap<&'a str, Vec<&'a crate::Occurrence>>, + /// Each component's first occurrence ([`Document::occurrence_of`]). + first_of: std::collections::HashMap, + bodies: std::collections::HashSet<&'a str>, + /// Some occurrence or body name has a slash or the fallback key's marker. + reserved: bool, +} + +impl<'a> WorldNames<'a> { + pub fn new(doc: &'a Document, st: &'a crate::ModelState) -> WorldNames<'a> { + let mut by_id = std::collections::HashMap::with_capacity(doc.occurrences.len()); + let mut by_name: std::collections::HashMap<&str, Vec<&crate::Occurrence>> = std::collections::HashMap::new(); + let mut first_of = std::collections::HashMap::new(); + for o in &doc.occurrences { + by_id.entry(o.id).or_insert(o); + by_name.entry(o.name.as_str()).or_default().push(o); + first_of.entry(o.component).or_insert(o); + } + let reserved = + doc.occurrences.iter().any(|o| o.name.contains('/') || o.name.contains("@occ[")) || st.bodies.iter().any(|b| b.name.contains("@occ[")); + let bodies = st.bodies.iter().map(|b| b.name.as_str()).collect(); + WorldNames { by_id, by_name, first_of, bodies, reserved } + } + + /// The world name of the body `source` of `component` placed through `path`. + pub fn name(&self, source: &str, component: u64, path: &[u64]) -> String { + placed_name(self, source, component, path) + } +} + +/// What naming a placed body looks up in the design: by scanning it ([`Scan`], for one name) +/// or through its indexes ([`WorldNames`], for many). +trait NameLookup { + fn occurrence(&self, id: u64) -> Option<&crate::Occurrence>; + fn each_named(&self, name: &str, f: &mut dyn FnMut(&crate::Occurrence)); + fn first_of(&self, component: u64) -> Option<&crate::Occurrence>; + fn reserved(&self) -> bool; + fn has_body(&self, name: &str) -> bool; +} + +/// Lookups by scanning the design. +struct Scan<'a> { + doc: &'a Document, + st: &'a crate::ModelState, +} + +impl NameLookup for Scan<'_> { + fn occurrence(&self, id: u64) -> Option<&crate::Occurrence> { + self.doc.occurrences.iter().find(|o| o.id == id) + } + fn each_named(&self, name: &str, f: &mut dyn FnMut(&crate::Occurrence)) { + self.doc.occurrences.iter().filter(|o| o.name == name).for_each(f); + } + fn first_of(&self, component: u64) -> Option<&crate::Occurrence> { + self.doc.occurrence_of(component) + } + fn reserved(&self) -> bool { + self.doc.occurrences.iter().any(|o| o.name.contains('/') || o.name.contains("@occ[")) + || self.st.bodies.iter().any(|b| b.name.contains("@occ[")) + } + fn has_body(&self, name: &str) -> bool { + self.st.body(name).is_some() + } +} + +impl NameLookup for WorldNames<'_> { + fn occurrence(&self, id: u64) -> Option<&crate::Occurrence> { + self.by_id.get(&id).copied() + } + fn each_named(&self, name: &str, f: &mut dyn FnMut(&crate::Occurrence)) { + self.by_name.get(name).into_iter().flatten().copied().for_each(f); + } + fn first_of(&self, component: u64) -> Option<&crate::Occurrence> { + self.first_of.get(&component).copied() + } + fn reserved(&self) -> bool { + self.reserved + } + fn has_body(&self, name: &str) -> bool { + self.bodies.contains(name) + } +} + +/// The world name of the body `source` of `component` placed through `path` (see +/// [`Document::world_body_name`]). +fn placed_name(l: &impl NameLookup, source: &str, component: u64, path: &[u64]) -> String { + // The occurrence path of the component's first placement ([`Document::first_path`]). + let mut first = Vec::new(); + let mut c = component; + for _ in 0..1000 { + if c == 0 { + break; + } + let Some(o) = l.first_of(c) else { break }; + first.insert(0, o.id); + c = o.parent; + } + if path == first { + return source.to_string(); + } + let names: Vec<&str> = path.iter().filter_map(|id| l.occurrence(*id)).map(|o| o.name.as_str()).collect(); + let label = names.join("/"); + let candidate = format!("{source} ({label})"); + let mut counts = std::collections::BTreeMap::from([(0, 1usize)]); + for name in &names { + let mut next = std::collections::BTreeMap::::new(); + l.each_named(name, &mut |o| { + if let Some(count) = counts.get(&o.parent) { + let n = next.entry(o.component).or_default(); + *n = (*n + count).min(2); + } + }); + counts = next; + } + let ambiguous = counts.get(&component).copied().unwrap_or(0) > 1; + // Slash and reserved-marker names could alias concatenated labels or fallback keys. + if !ambiguous && !l.reserved() && !l.has_body(&candidate) { + return candidate; + } + let ids = path.iter().map(u64::to_string).collect::>().join("/"); + let encoded = serde_json::to_string(source).unwrap_or_else(|_| source.to_string()); + let mut key = format!("{encoded}@occ[{ids}]"); + while l.has_body(&key) { + key.push('#'); + } + key +} diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index dcea015aa..27a2022a7 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -8342,12 +8342,13 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut // places hundreds of parts, each a B-rep transform. let mut jobs = Vec::new(); let owners = doc.model_body_components(st); + let names = crate::WorldNames::new(doc, st); let bodies_of = |comp: u64| st.bodies.iter().zip(&owners).filter(move |(_, owner)| **owner == comp).map(|(b, _)| b); for (comp, path, m) in &placements { for b in bodies_of(*comp) { let bm = body_matrix(b, m); if !crate::is_identity(&bm) { - jobs.push((b, bm, doc.world_body_name(st, &b.name, *comp, path))); + jobs.push((b, bm, names.name(&b.name, *comp, path))); } } } @@ -8366,14 +8367,14 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut // A changed placement keeps a distinct mesh, at that placement's coordinates. let mut placed = if crate::is_identity(&bm) { let mut placed = b.clone(); - placed.name = doc.world_body_name(st, &b.name, comp, &path); + placed.name = names.name(&b.name, comp, &path); placed } else { // The same order as the jobs: this body's, made above (again here if it failed). let placed = match moved.next() { Some((Some(placed), _)) => placed, Some((None, (_, _, name))) => placed_before.placed(b, &bm, name.clone()), - None => placed_before.placed(b, &bm, doc.world_body_name(st, &b.name, comp, &path)), + None => placed_before.placed(b, &bm, names.name(&b.name, comp, &path)), }; placed_now.by_source.insert(placed_key(b, &bm), (b.clone(), placed.clone())); placed @@ -8428,7 +8429,7 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut .filter(|t| st.body(&t.body).map(|body| doc.model_body_component(body)).unwrap_or_else(|| comp_of_feature(t.feature)) == comp) { let mut t2 = t.clone(); - t2.body = doc.world_body_name(st, &t.body, comp, &path); + t2.body = names.name(&t.body, comp, &path); let frame = st.body(&t.body).and_then(|body| doc.model_body_offset(body)).map(|offset| crate::mat_mul(&m, offset)).unwrap_or(m); t2.axis_point = crate::apply_point(&frame, t.axis_point); t2.axis = crate::apply_vector(&frame, *t.axis).unit().unwrap_or(t.axis); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 9f95713f3..ac4fefdc0 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -69,8 +69,8 @@ pub mod sheet; pub mod text_params; pub use assembly::{ - IDENTITY, MAX_PLACEMENT_DEPTH, MAX_PLACEMENTS, Mat, Occurrence, apply_point, apply_vector, is_identity, map_point_expr, mat_inverse, mat_mul, - rigid, + IDENTITY, MAX_PLACEMENT_DEPTH, MAX_PLACEMENTS, Mat, Occurrence, WorldNames, apply_point, apply_vector, is_identity, map_point_expr, mat_inverse, + mat_mul, rigid, }; pub use document::*; pub use eval::KeptResults; diff --git a/crates/engine/src/cmd/occurrence_tests.rs b/crates/engine/src/cmd/occurrence_tests.rs index 796112926..5b3c2df45 100644 --- a/crates/engine/src/cmd/occurrence_tests.rs +++ b/crates/engine/src/cmd/occurrence_tests.rs @@ -101,6 +101,73 @@ fn renaming_a_parent_preserves_hidden_nested_copies_with_ambiguous_labels() { } } +/// The world name of a placed body as `Document::world_body_name` worked it out before +/// `WorldNames` (each name scanning the whole design), kept to prove the two agree. +fn world_name_by_scanning(doc: &crate::doc::Document, st: &crate::doc::ModelState, source: &str, component: u64, path: &[u64]) -> String { + if path == doc.first_path(component) { + return source.to_string(); + } + let names: Vec<&str> = path.iter().filter_map(|id| doc.occurrences.iter().find(|o| o.id == *id)).map(|o| o.name.as_str()).collect(); + let candidate = format!("{source} ({})", names.join("/")); + let mut counts = std::collections::BTreeMap::from([(0, 1usize)]); + for name in &names { + let mut next = std::collections::BTreeMap::::new(); + for o in doc.occurrences.iter().filter(|o| o.name == *name) { + if let Some(count) = counts.get(&o.parent) { + let n = next.entry(o.component).or_default(); + *n = (*n + count).min(2); + } + } + counts = next; + } + let ambiguous = counts.get(&component).copied().unwrap_or(0) > 1; + let reserved = + doc.occurrences.iter().any(|o| o.name.contains('/') || o.name.contains("@occ[")) || st.bodies.iter().any(|b| b.name.contains("@occ[")); + if !ambiguous && !reserved && st.body(&candidate).is_none() { + return candidate; + } + let ids = path.iter().map(u64::to_string).collect::>().join("/"); + let mut key = format!("{}@occ[{ids}]", serde_json::to_string(source).unwrap()); + while st.body(&key).is_some() { + key.push('#'); + } + key +} + +/// Naming every placed body at once (`WorldNames`) gives each the name naming it alone did: +/// nested copies, copies whose labels collide, a body named like a label, and names with a +/// slash or the fallback key's marker. +#[test] +fn placed_body_names_match_naming_each_body_alone() { + let mut s = Session::default(); + let (parent, _) = created(&mut s, "Assembly"); + let (knob, _) = created(&mut s, "Knob"); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Knob"})); + run(&mut s, "occurrence.copy", json!({"component": parent, "translate": [20, 0, 0]})); + run(&mut s, "occurrence.copy", json!({"component": knob, "translate": [0, 20, 0]})); + run(&mut s, "component.activate", json!({"component": 0})); + run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "body_name": "Knob (Assembly/Knob)"})); + let check = |s: &Session, step: &str| { + let st = s.model.state(); + let names = crate::doc::WorldNames::new(&s.doc, &st); + let mut seen = 0; + for (component, path, _) in s.doc.placements() { + for b in st.bodies.iter().filter(|b| s.doc.model_body_component(b) == component) { + assert_eq!(names.name(&b.name, component, &path), world_name_by_scanning(&s.doc, &st, &b.name, component, &path), "{step}: {path:?}"); + seen += 1; + } + } + assert!(seen >= 5, "{step}: every placement is named ({seen})"); + }; + check(&s, "copies"); + run(&mut s, "component.rename", json!({"component": parent, "name": "Knob"})); + check(&s, "a parent named like its child"); + run(&mut s, "component.rename", json!({"component": parent, "name": "Assembly/Other"})); + check(&s, "a slash"); + run(&mut s, "body.rename", json!({"body": "Knob", "name": "Grip (@occ[custom])"})); + check(&s, "the fallback marker"); +} + #[test] fn instance_copy_uses_selected_source_transform() { let mut s = Session::default(); diff --git a/crates/engine/src/occurrences.rs b/crates/engine/src/occurrences.rs index 29c0ba830..a07b4a305 100644 --- a/crates/engine/src/occurrences.rs +++ b/crates/engine/src/occurrences.rs @@ -89,12 +89,13 @@ impl Session { } let hidden: std::collections::BTreeSet<_> = self.visibility.hidden_bodies.iter().map(String::as_str).collect(); let mut names = std::collections::BTreeMap::new(); + let (before, after) = (solidcraft_doc::WorldNames::new(previous, state), solidcraft_doc::WorldNames::new(&self.doc, &renamed)); for (component, path, _) in previous.placements() { for body in state.bodies.iter().filter(|body| previous.model_body_component(body) == component) { - let old = previous.world_body_name(state, &body.name, component, &path); + let old = before.name(&body.name, component, &path); if hidden.contains(old.as_str()) { let source = rename.filter(|(old, _)| *old == body.name).map_or(body.name.as_str(), |(_, new)| new); - names.insert(old, self.doc.world_body_name(&renamed, source, component, &path)); + names.insert(old, after.name(source, component, &path)); } } } @@ -169,11 +170,12 @@ impl Session { } let leaf = self.doc.occurrences.iter().find(|o| Some(&o.id) == path.last()).ok_or_else(|| invalid("occurrence path has no leaf"))?; let state = self.model.state(); + let names = solidcraft_doc::WorldNames::new(&self.doc, &state); let bodies = state .bodies .iter() .filter(|b| self.doc.model_body_component(b) == component) - .map(|b| OccurrenceBody { source: b.name.clone(), world: self.doc.world_body_name(&state, &b.name, component, path) }) + .map(|b| OccurrenceBody { source: b.name.clone(), world: names.name(&b.name, component, path) }) .collect(); Ok(OccurrencePlacement { occurrence: leaf.id, @@ -417,12 +419,13 @@ impl Session { fn bodies_hidden_by_parents(&self) -> std::collections::BTreeSet { let st = self.model.state(); let mut out = std::collections::BTreeSet::new(); + let names = solidcraft_doc::WorldNames::new(&self.doc, &st); for (component, path, _) in self.doc.placements() { let placement_hidden = !path.is_empty() && !self.occurrence_visible(&path); let scope = Self::folder_scope(&path); for b in st.bodies.iter().filter(|b| self.doc.model_body_component(b) == component) { if placement_hidden || self.item_folder_hidden(&scope, component, "bodies", &b.name) { - out.insert(self.doc.world_body_name(&st, &b.name, component, &path)); + out.insert(names.name(&b.name, component, &path)); } } }