Skip to content

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

Preserve linked component materials and appearances (#7609) (#7616)

amolinari-autotex54f613e4dda3
diff --git a/crates/doc/src/appearance.rs b/crates/doc/src/appearance.rs
index 03cab9ef1d..064a9fa8dc 100644
--- a/crates/doc/src/appearance.rs
+++ b/crates/doc/src/appearance.rs
@@ -201,9 +201,19 @@ impl Document {
/// The faces of a body with appearances of their own: (B-rep face index, look). A later
/// assignment to the same face wins.
pub fn face_colors(&self, b: &crate::ModelBody) -> Vec<(usize, Look)> {
+ let mut out = self.imported_face_colors(b);
+ for (index, look) in self.authored_face_colors(b) {
+ out.retain(|(old, _)| *old != index);
+ out.push((index, look));
+ }
+ out
+ }
+
+ /// Imported paint alone, after applying body-appearance precedence.
+ pub(crate) fn imported_face_colors(&self, b: &crate::ModelBody) -> Vec<(usize, Look)> {
// An assigned body appearance replaces imported paint; design face appearances still win.
let to8 = |x: f32| (x.clamp(0.0, 1.0) * 255.0).round() as u8;
- let mut out: Vec<(usize, Look)> = if self.appearances.bodies.contains_key(b.definition_name()) {
+ if self.appearances.bodies.contains_key(b.definition_name()) {
Vec::new()
} else {
match b.body.paint() {
@@ -219,7 +229,13 @@ impl Document {
None => Vec::new(),
},
}
- };
+ }
+ }
+
+ /// Design-authored face overrides, without imported STEP paint. Linked designs carry
+ /// these independently so an inherited body look does not hide their face overrides.
+ pub fn authored_face_colors(&self, b: &crate::ModelBody) -> Vec<(usize, Look)> {
+ let mut out = Vec::new();
for f in self.appearances.faces.iter().filter(|f| f.body == b.definition_name()) {
let (p, look) = (crate::apply_point(&b.source_transform, f.point), f.look.clone());
if f.strict_name {
@@ -385,6 +401,28 @@ mod tests {
assert!(restored.iter().all(|(face, look)| *look == if *face == 0 { face_look.clone() } else { Look::custom([255, 0, 0], 0.5) }));
}
+ #[test]
+ fn linked_paint_retains_imported_faces_without_baking_authored_overrides() {
+ let mut state = crate::ModelState::default();
+ state.bodies.push(imported_box());
+ let body = &state.bodies[0];
+ let mut doc = Document::default();
+ doc.appearances.faces.push(FaceLook {
+ body: body.name.clone(),
+ point: Vec3::ZERO,
+ look: Look::custom([0, 255, 0], 1.0),
+ name: Some(crate::naming::face_names(body)[0].clone()),
+ strict_name: false,
+ certificate: None,
+ });
+ let exported = doc.painted(&state);
+ assert!(exported.bodies[0].body.paint().unwrap().faces.iter().any(|face| face.color == [0., 1., 0.]));
+ let linked = doc.painted_for_link(&state);
+ let faces = &linked.bodies[0].body.paint().unwrap().faces;
+ assert_eq!(faces.len(), body.body.faces(0.01).unwrap().len());
+ assert!(faces.iter().all(|face| face.color == [1., 0., 0.] && face.opacity == 0.5));
+ }
+
#[test]
fn body_appearance_overrides_imported_face_paint() {
check_imported_appearance_precedence(&imported_box());
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs
index 1406057a68..20bf5226e8 100644
--- a/crates/doc/src/document.rs
+++ b/crates/doc/src/document.rs
@@ -2617,13 +2617,42 @@ pub struct StandardPart {
/// A component whose contents come from another design file (Insert Design): where that file
/// is, and the Import feature in the component that holds its bodies (Update Links replaces
/// them; Break Link keeps them and forgets the file).
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct DesignLink {
/// The design file: relative to this design's folder once this design is saved, else as
/// given (`/` separates folders).
pub path: String,
/// The Import feature holding the linked design's bodies.
pub feature: u64,
+ /// Last inherited values, by Import body slot. Differing assembly assignments are
+ /// local overrides and survive a source update. Older links start with no baseline.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub inherited: Vec<LinkedBodyProperties>,
+}
+
+/// The values last inherited by a linked body, not another editable material library.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct LinkedBodyProperties {
+ pub material: String,
+ /// SHA-256 of the inherited custom definition, for equality only. The complete
+ /// engineering card stays in user_materials, not duplicated once per linked body.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub material_fingerprint: Option<String>,
+ /// Explicit body/component look only: material fallback must remain a fallback.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub appearance: Option<crate::appearance::Look>,
+ /// Last inherited authored face overrides. None marks links saved before face
+ /// inheritance; Some(empty) records that the source has no authored face overrides.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub faces: Option<Vec<crate::appearance::FaceLook>>,
+}
+
+impl LinkedBodyProperties {
+ pub fn fingerprint(material: &UserMaterial) -> Result<String> {
+ use sha2::{Digest, Sha256};
+ let bytes = serde_json::to_vec(material).map_err(|e| DocError::Invalid(e.to_string()))?;
+ Ok(format!("{:x}", Sha256::digest(bytes)))
+ }
}
/// A name the design's counter hands out (`Body1`).
@@ -3131,14 +3160,22 @@ impl Document {
/// The model with each body carrying the colour, opacity and face colours it is shown with
/// (for export).
pub fn painted(&self, state: &crate::ModelState) -> crate::ModelState {
+ self.painted_with_faces(state, true)
+ }
+
+ /// Linked designs carry authored face overrides as editable properties. Their STEP
+ /// geometry keeps imported paint, without baking a second copy of those overrides.
+ pub fn painted_for_link(&self, state: &crate::ModelState) -> crate::ModelState {
+ self.painted_with_faces(state, false)
+ }
+
+ fn painted_with_faces(&self, state: &crate::ModelState, authored_faces: bool) -> crate::ModelState {
let mut st = state.clone();
for b in &mut st.bodies {
let c = self.body_color(b);
- let faces: Vec<solidcraft_kernel::FacePaint> = self
- .face_colors(b)
- .into_iter()
- .map(|(face, l)| solidcraft_kernel::FacePaint { face, color: l.rgb(), opacity: l.opacity as f32 })
- .collect();
+ let face_colors = if authored_faces { self.face_colors(b) } else { self.imported_face_colors(b) };
+ let faces: Vec<solidcraft_kernel::FacePaint> =
+ face_colors.into_iter().map(|(face, l)| solidcraft_kernel::FacePaint { face, color: l.rgb(), opacity: l.opacity as f32 }).collect();
let opacity = self.model_body_opacity(b) as f32;
let paint = solidcraft_kernel::Paint { opacity, faces };
if c != b.body.color() || b.body.paint() != Some(&paint) {
diff --git a/crates/doc/src/format/pending/linked-body-properties.rs b/crates/doc/src/format/pending/linked-body-properties.rs
new file mode 100644
index 0000000000..c8d0de5a70
--- /dev/null
+++ b/crates/doc/src/format/pending/linked-body-properties.rs
@@ -0,0 +1,8 @@
+//! Linked components retain the last inherited physical material, explicit body look and
+//! authored face overrides by imported body slot. Face baselines are optional: an older
+//! link is read again on Update Links while preserving local assignments. Authored face
+//! overrides stay separate from imported STEP paint, including under a body appearance.
+//! Source-only property edits can then update the link while
+//! differing local assignments survive. Older links have no baseline: existing assignments
+//! are preserved and missing ones can be recovered on Update Links. The last release
+//! refuses the newer design format instead of silently discarding these baselines.
diff --git a/crates/engine/src/cmd/component_extract.rs b/crates/engine/src/cmd/component_extract.rs
index da2161ca84..4933b4b226 100644
--- a/crates/engine/src/cmd/component_extract.rs
+++ b/crates/engine/src/cmd/component_extract.rs
@@ -17,7 +17,7 @@ use serde_json::{Value, json};
use solidcraft_doc::{DesignLink, Document, FeatureKind, ModelBody, ModelState};
use solidcraft_geom::Vec3;
-use super::{absolute, component_key, resolve, session_bodies, stored};
+use super::{absolute, component_key, inherit_properties, resolve, session_bodies, stored};
use crate::params::{bad, str_};
use crate::{EngineError, Result, Session};
@@ -566,7 +566,7 @@ pub(super) fn extract(s: &mut Session, p: &Value) -> Result<Value> {
// This design: the component's history becomes an Import feature of the new design's bodies
let shown = file.display().to_string();
- let (_, sf, faces, _) = session_bodies(&part, &shown)?;
+ let (_, sf, faces, _, properties) = 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<String> = Vec::new();
for b in part.world_state().bodies.iter().filter(|b| !b.body.is_mesh()) {
@@ -592,12 +592,14 @@ pub(super) fn extract(s: &mut Session, p: &Value) -> Result<Value> {
f.link_faces = faces;
}
let path = stored(s.path.as_deref(), &file);
- s.doc_mut().links.insert(comp, DesignLink { path: file.to_string_lossy().into_owned(), feature: id });
+ s.doc_mut().links.insert(comp, DesignLink { path: file.to_string_lossy().into_owned(), feature: id, inherited: Vec::new() });
s.refresh();
rename_joint_faces(s, &state, id, &sc.own);
if let Some(e) = s.model.result(id).and_then(|r| r.error.clone()) {
return Err(EngineError::Other(e));
}
+ inherit_properties(s, comp, &properties)?;
+ s.refresh();
let mut warnings = sf.warnings;
warnings.extend(before.check(s, CMD, &sc.name)?);
let copies = copies_of(s, comp)?;
diff --git a/crates/engine/src/cmd/component_link.rs b/crates/engine/src/cmd/component_link.rs
index 1273507dd2..ee05bd0bbe 100644
--- a/crates/engine/src/cmd/component_link.rs
+++ b/crates/engine/src/cmd/component_link.rs
@@ -13,7 +13,7 @@ use std::path::{Path, PathBuf};
use std::sync::Mutex;
use serde_json::{Value, json};
-use solidcraft_doc::{DesignLink, Document, FeatureKind};
+use solidcraft_doc::{DesignLink, Document, FeatureKind, LinkedBodyProperties, UserMaterial};
use super::CommandSpec;
use super::design_link::{absolute, resolve, stored};
@@ -88,11 +88,20 @@ pub fn resolve_design_links(doc: &mut Document, from: Option<&str>) {
/// 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`), with the source's design properties.
-type Linked = (String, solidcraft_io::StepFeature, Vec<Vec<String>>, solidcraft_doc::Metadata);
+type Linked = (String, solidcraft_io::StepFeature, Vec<Vec<String>>, solidcraft_doc::Metadata, Vec<SourceProperties>);
+
+#[derive(Clone)]
+struct SourceProperties {
+ material: String,
+ definition: Option<UserMaterial>,
+ appearance: Option<solidcraft_doc::appearance::Look>,
+ /// Resolved authored overrides, by the face index in this imported body.
+ faces: Vec<(usize, solidcraft_doc::appearance::Look)>,
+}
/// What a linked file last gave, by the file: digests of its bytes, of the STEP text it gave and
-/// of its face names, and that read's warnings. Update Links evaluates a file again only when its
-/// bytes or the linked bodies changed since (#5606). Bounded, oldest first out.
+/// of its face names, and that read's warnings and source properties. Update Links evaluates
+/// a file again only when its bytes or the linked bodies changed since (#5606). Bounded, oldest first out.
static READS: Mutex<Vec<LinkRead>> = Mutex::new(Vec::new());
const READS_SIZE: usize = 256;
@@ -102,6 +111,7 @@ struct LinkRead {
step: u64,
faces: u64,
warnings: Vec<String>,
+ properties: Vec<SourceProperties>,
}
#[cfg(test)]
@@ -116,15 +126,18 @@ fn digest<T: Hash + ?Sized>(value: &T) -> u64 {
h.finish()
}
-/// The warnings of the last read of `file`, when it had these bytes and gave the STEP text
+/// Warnings and source properties of the last read of `file`, when it had these bytes and gave the STEP text
/// `step` and the face names `faces`: the bodies it gives are the ones the link holds.
-fn unchanged_read(file: &Path, bytes: u64, step: u64, faces: u64) -> Option<Vec<String>> {
+fn unchanged_read(file: &Path, bytes: u64, step: u64, faces: u64) -> Option<(Vec<String>, Vec<SourceProperties>)> {
let file = absolute(file);
let reads = READS.lock().ok()?;
- reads.iter().find(|r| r.file == file && r.bytes == bytes && r.step == step && r.faces == faces).map(|r| r.warnings.clone())
+ reads
+ .iter()
+ .find(|r| r.file == file && r.bytes == bytes && r.step == step && r.faces == faces)
+ .map(|r| (r.warnings.clone(), r.properties.clone()))
}
-fn remember_read(file: &Path, bytes: u64, feature: &solidcraft_io::StepFeature, faces: &[Vec<String>]) {
+fn remember_read(file: &Path, bytes: u64, feature: &solidcraft_io::StepFeature, faces: &[Vec<String>], properties: &[SourceProperties]) {
let FeatureKind::Import { step, .. } = &feature.kind else { return };
let file = absolute(file);
let Ok(mut reads) = READS.lock() else { return };
@@ -132,7 +145,14 @@ fn remember_read(file: &Path, bytes: u64, feature: &solidcraft_io::StepFeature,
if reads.len() >= READS_SIZE {
reads.remove(0);
}
- reads.push(LinkRead { file, bytes, step: digest(step.as_bytes()), faces: digest(faces), warnings: feature.warnings.clone() });
+ reads.push(LinkRead {
+ file,
+ bytes,
+ step: digest(step.as_bytes()),
+ faces: digest(faces),
+ warnings: feature.warnings.clone(),
+ properties: properties.to_vec(),
+ });
}
/// The bytes of the design at `file`, which must not be the design saved at `own`.
@@ -168,9 +188,9 @@ fn design_bodies(file: &Path, bytes: &[u8]) -> Result<Linked> {
} else {
(solidcraft_io::read_design(bytes).map_err(fail)?, None)
};
- let (name, feature, faces, metadata) = session_bodies(&Session::opened_at(doc, saved.as_ref(), Some(&shown)), &shown)?;
- remember_read(file, digest(bytes), &feature, &faces);
- Ok((name, feature, faces, metadata))
+ let (name, feature, faces, metadata, properties) = session_bodies(&Session::opened_at(doc, saved.as_ref(), Some(&shown)), &shown)?;
+ remember_read(file, digest(bytes), &feature, &faces, &properties);
+ Ok((name, feature, faces, metadata, properties))
}
/// The solid bodies of `part`, the design saved as `shown`, as an Import feature.
@@ -184,7 +204,7 @@ fn session_bodies(part: &Session, shown: &str) -> Result<Linked> {
if solids.is_empty() {
return Err(EngineError::Other(format!("{shown}: the design has no solid bodies to link")));
}
- let step = solidcraft_io::export(&part.doc.painted(&world), &solids, solidcraft_io::Format::Step, &name)
+ let step = solidcraft_io::export(&part.doc.painted_for_link(&world), &solids, solidcraft_io::Format::Step, &name)
.map_err(|e| EngineError::Other(format!("{shown}: {e}")))?;
let mut feature = solidcraft_io::step_import_feature(&step, shown).map_err(|e| EngineError::Other(format!("{shown}: {e}")))?;
if world.bodies.len() > solids.len() {
@@ -193,7 +213,239 @@ fn session_bodies(part: &Session, shown: &str) -> Result<Linked> {
// 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, part.doc.metadata.clone()))
+ let properties = feature
+ .import
+ .bodies
+ .iter()
+ .zip(&faces)
+ .map(|(read, carried)| {
+ // STEP can split a source body into several lumps. Match its carried source
+ // face names rather than assuming source and imported body orders agree.
+ let source = world
+ .bodies
+ .iter()
+ .find(|b| b.name == read.name)
+ .or_else(|| {
+ world
+ .bodies
+ .iter()
+ .filter(|b| !b.body.is_mesh())
+ .filter_map(|b| {
+ let names = solidcraft_doc::naming::face_names(b);
+ let count = carried.iter().filter(|n| !n.is_empty() && names.contains(n)).count();
+ (count > 0).then_some((count, b))
+ })
+ .max_by_key(|(count, _)| *count)
+ .map(|(_, b)| b)
+ })
+ .ok_or_else(|| EngineError::Other(format!("{shown}: cannot match linked body {} to its source properties", read.name)))?;
+ let key = source.definition_name();
+ let material = part.doc.body_material(key);
+ let definition = if solidcraft_doc::material_density(&material).is_none() { part.doc.user_material(&material).cloned() } else { None };
+ let appearance = part
+ .doc
+ .appearances
+ .bodies
+ .get(key)
+ .cloned()
+ .or_else(|| part.doc.appearances.components.get(&part.doc.model_body_component(source)).cloned());
+ let names = solidcraft_doc::naming::face_names(source);
+ let authored: std::collections::BTreeMap<_, _> = part
+ .doc
+ .authored_face_colors(source)
+ .into_iter()
+ .filter_map(|(index, look)| names.get(index).map(|name| (name.clone(), look)))
+ .collect();
+ let faces = carried.iter().enumerate().filter_map(|(index, name)| authored.get(name).map(|look| (index, look.clone()))).collect();
+ Ok(SourceProperties { material, definition, appearance, faces })
+ })
+ .collect::<Result<Vec<_>>>()?;
+ Ok((name, feature, faces, part.doc.metadata.clone(), properties))
+}
+
+fn material_fingerprint(doc: &Document, material: &str) -> Result<Option<String>> {
+ if solidcraft_doc::material_density(material).is_some() {
+ return Ok(None);
+ }
+ doc.user_material(material).map(LinkedBodyProperties::fingerprint).transpose().map_err(|e| EngineError::Other(e.to_string()))
+}
+
+/// Copy a design-owned definition without changing a same-named assembly material.
+fn inherit_material(doc: &mut Document, source: &SourceProperties, previous: Option<&str>) -> Result<String> {
+ let Some(definition) = &source.definition else { return Ok(source.material.clone()) };
+ for existing in &doc.user_materials {
+ // Equal density/optics do not make differently named materials interchangeable.
+ // A previous disambiguated copy can be reused on subsequent source updates.
+ if !existing.name.eq_ignore_ascii_case(&definition.name) && previous != Some(existing.name.as_str()) {
+ continue;
+ }
+ let mut candidate = definition.clone();
+ candidate.name.clone_from(&existing.name);
+ if &candidate == existing {
+ return Ok(existing.name.clone());
+ }
+ }
+ if doc.user_materials.len() >= solidcraft_doc::MAX_USER_MATERIALS {
+ return Err(EngineError::Other("cannot inherit linked material: this design already has 1000 custom materials".into()));
+ }
+ let mut copy = definition.clone();
+ if doc.material_name(&copy.name).is_some() {
+ let base: String = copy.name.chars().take(64).collect();
+ let name = (1..=solidcraft_doc::MAX_USER_MATERIALS + 1)
+ .map(|i| format!("{base} (linked {i})"))
+ .find(|name| doc.material_name(name).is_none())
+ .ok_or_else(|| EngineError::Other("cannot name the linked material".into()))?;
+ copy.name = name;
+ }
+ let name = copy.name.clone();
+ doc.user_materials.push(copy);
+ Ok(name)
+}
+
+/// Replace only unchanged inherited face assignments. A locally edited, added or removed
+/// override remains local, independently for each face. Resolve names on the evaluated Import,
+/// not source feature IDs or face order from the source's model.
+fn inherit_faces(
+ s: &mut Session,
+ name: &str,
+ source: &SourceProperties,
+ previous: Option<&LinkedBodyProperties>,
+) -> (Vec<solidcraft_doc::appearance::FaceLook>, bool) {
+ use solidcraft_doc::appearance::FaceLook;
+ let previous = previous.and_then(|p| p.faces.as_deref()).unwrap_or_default();
+ if source.faces.is_empty() && previous.is_empty() {
+ return (Vec::new(), false);
+ }
+ let state = s.model.state();
+ let Some(body) = state.body(name) else { return (Vec::new(), false) };
+ let names = solidcraft_doc::naming::face_names(body);
+ // A stable named assignment needs no new geometric point. Keep its position in
+ // the appearance list and avoid tessellating on unchanged cached reads.
+ if previous.len() == source.faces.len()
+ && previous.iter().all(|old| old.body == name && s.doc.appearances.faces.contains(old))
+ && source.faces.iter().all(|(index, look)| {
+ names.get(*index).is_some_and(|name| previous.iter().any(|old| old.name.as_ref() == Some(name) && old.look == *look))
+ })
+ {
+ return (previous.to_vec(), false);
+ }
+ let before = s.doc.appearances.faces.clone();
+ let mut local = before.clone();
+ let mut inherited = Vec::new();
+ let mut replaced = Vec::new();
+ let mut blocked = std::collections::BTreeSet::new();
+ for old in previous {
+ let mut old = old.clone();
+ old.body = name.into();
+ if let Some(index) = local.iter().position(|face| *face == old) {
+ local.remove(index);
+ replaced.push(old);
+ } else {
+ if let Some(name) = &old.name {
+ blocked.extend(solidcraft_doc::naming::faces_with_stem(body, name));
+ }
+ // Remember an explicit local removal too, including after save/reopen.
+ inherited.push(old);
+ }
+ }
+ s.doc_mut().appearances.faces = local;
+ blocked.extend(s.doc.authored_face_colors(body).into_iter().map(|(index, _)| index));
+ let spots = if source.faces.is_empty() { Vec::new() } else { solidcraft_doc::naming::face_spots(body) };
+ let mut assignments = Vec::new();
+ for (index, look) in &source.faces {
+ if blocked.contains(index) {
+ // An appended local override can coexist with the old inherited entry.
+ // Keep that baseline as a tombstone if the local override is later removed.
+ if let Some(old) = names.get(*index).and_then(|name| previous.iter().find(|old| old.name.as_ref() == Some(name))) {
+ let mut old = old.clone();
+ old.body = name.into();
+ if !inherited.contains(&old) {
+ inherited.push(old);
+ }
+ }
+ continue;
+ }
+ let Some(face_name) = names.get(*index).filter(|name| !name.is_empty()) else { continue };
+ let Some(spot) = spots.get(*index).and_then(|spot| *spot) else { continue };
+ let face = FaceLook {
+ body: name.into(),
+ point: spot.point,
+ look: look.clone(),
+ name: Some(face_name.clone()),
+ strict_name: false,
+ certificate: None,
+ };
+ assignments.push(face.clone());
+ inherited.push(face);
+ }
+ // Replace inherited entries in place; leave all local and other bodies' entries
+ // in their original order, including multiple overrides on the same face.
+ let mut after = Vec::new();
+ for old in &before {
+ if replaced.contains(old) {
+ if let Some(index) = assignments.iter().position(|face| face.body == old.body && face.name == old.name) {
+ after.push(assignments.remove(index));
+ }
+ } else {
+ after.push(old.clone());
+ }
+ }
+ after.extend(assignments);
+ let changed = after != before;
+ s.doc_mut().appearances.faces = after;
+ (inherited, changed)
+}
+
+/// Apply properties after evaluation has resolved body-name collisions. Last inherited
+/// values are kept independently for material and appearance, so overriding one does not
+/// stop updates of the other. Session::execute makes this part of the command's undo step.
+fn inherit_properties(s: &mut Session, component: u64, sources: &[SourceProperties]) -> Result<bool> {
+ let Some(link) = s.doc.links.get(&component).cloned() else { return Ok(false) };
+ let state = s.model.state();
+ let names: Vec<String> = state.bodies.iter().filter(|b| b.feature == link.feature).map(|b| b.name.clone()).collect();
+ let slots = s.doc.feature(link.feature).map(|f| f.body_name_slots(names.len())).unwrap_or_default();
+ let mut inherited = link.inherited.clone();
+ inherited.resize(sources.len(), LinkedBodyProperties::default());
+ let mut changed = false;
+ for (name, slot) in names.iter().zip(slots) {
+ let Some(source) = sources.get(slot) else { continue };
+ let old = link.inherited.get(slot);
+ let current_definition = material_fingerprint(&s.doc, &s.doc.body_material(name))?;
+ let may_change_material = match old {
+ Some(old) => s.doc.materials.get(name) == Some(&old.material) && current_definition == old.material_fingerprint,
+ None => !s.doc.materials.contains_key(name),
+ };
+ let mut next = old.cloned().unwrap_or_default();
+ if may_change_material {
+ let material = inherit_material(s.doc_mut(), source, old.map(|old| old.material.as_str()))?;
+ changed |= s.doc.materials.get(name) != Some(&material);
+ s.doc_mut().materials.insert(name.clone(), material.clone());
+ next.material_fingerprint = material_fingerprint(&s.doc, &material)?;
+ next.material = material;
+ }
+ if s.doc.appearances.bodies.get(name) == old.and_then(|old| old.appearance.as_ref()) {
+ changed |= s.doc.appearances.bodies.get(name) != source.appearance.as_ref();
+ match &source.appearance {
+ Some(look) => {
+ s.doc_mut().appearances.bodies.insert(name.clone(), look.clone());
+ }
+ None => {
+ s.doc_mut().appearances.bodies.remove(name);
+ }
+ }
+ next.appearance.clone_from(&source.appearance);
+ }
+ let (faces, face_changed) = inherit_faces(s, name, source, old);
+ next.faces = Some(faces);
+ changed |= face_changed;
+ if let Some(snapshot) = inherited.get_mut(slot) {
+ *snapshot = next;
+ }
+ }
+ if let Some(link) = s.doc_mut().links.get_mut(&component) {
+ link.inherited = inherited;
+ }
+ Ok(changed)
}
fn component_key(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<u64> {
@@ -225,7 +477,7 @@ fn insert_design(s: &mut Session, p: &Value) -> Result<Value> {
return super::component::copy_occurrence(s, &json!({"component": component, "parent": parent, "translate": translate}));
}
}
- let (design_name, sf, faces, metadata) = linked_bodies(&file, s.path.as_deref())?;
+ let (design_name, sf, faces, metadata, properties) = 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.
@@ -252,11 +504,13 @@ fn insert_design(s: &mut Session, p: &Value) -> Result<Value> {
o.transform[3] = [translate.x, translate.y, translate.z, 1.0];
}
let path = stored(s.path.as_deref(), &file);
- s.doc_mut().links.insert(comp, DesignLink { path: file.to_string_lossy().into_owned(), feature: id });
+ s.doc_mut().links.insert(comp, DesignLink { path: file.to_string_lossy().into_owned(), feature: id, inherited: Vec::new() });
s.refresh();
if let Some(e) = s.model.result(id).and_then(|r| r.error.clone()) {
return Err(EngineError::Other(e));
}
+ inherit_properties(s, comp, &properties)?;
+ s.refresh();
let st = s.model.state();
let bodies: Vec<&str> = st.bodies.iter().filter(|b| b.feature == id).map(|b| b.name.as_str()).collect();
Ok(
@@ -294,18 +548,34 @@ fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
link_refused(s.path.as_deref(), &link.path).map_err(|e| bad(cmd, format!("{cname}: {e}")))?;
let file = resolve(s.path.as_deref(), &link.path);
let bytes = read_link(&file, s.path.as_deref()).map_err(|e| bad(cmd, format!("{cname}: {e}")))?;
- let kept_faces = s.doc.feature(link.feature).map(|f| digest(f.link_faces.as_slice()));
- if let Some(known) = kept_faces.and_then(|faces| unchanged_read(&file, digest(bytes.as_slice()), digest(old.as_bytes()), faces)) {
+ // A link that has not recorded the properties it inherited (made before they were) is read again.
+ let kept_faces = s
+ .doc
+ .feature(link.feature)
+ .filter(|_| !link.inherited.is_empty() && link.inherited.iter().all(|p| p.faces.is_some()))
+ .map(|f| digest(f.link_faces.as_slice()));
+ if let Some((known, properties)) = kept_faces.and_then(|faces| unchanged_read(&file, digest(bytes.as_slice()), digest(old.as_bytes()), faces))
+ {
warnings.extend(known);
- unchanged.push(cname);
+ // Another component or session may have evaluated this source first. Its
+ // cached geometry says nothing about this link's inherited properties.
+ if inherit_properties(s, comp, &properties)? {
+ updated.push(cname)
+ } else {
+ unchanged.push(cname)
+ }
continue;
}
- let (_, sf, faces, _) = design_bodies(&file, &bytes).map_err(|e| bad(cmd, format!("{cname}: {e}")))?;
+ let (_, sf, faces, _, properties) = design_bodies(&file, &bytes).map_err(|e| bad(cmd, format!("{cname}: {e}")))?;
warnings.extend(sf.warnings.iter().cloned());
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);
+ if inherit_properties(s, comp, &properties)? {
+ updated.push(cname)
+ } else {
+ unchanged.push(cname)
+ }
continue;
}
// The same bodies, their faces named for the first time (a link made before names were
@@ -329,6 +599,8 @@ fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
// A link made before the design's face names were kept gets them here.
f.link_faces = faces;
}
+ s.refresh();
+ let changed = inherit_properties(s, comp, &properties)? || changed;
if changed { updated.push(cname) } else { unchanged.push(cname) }
}
solidcraft_doc::progress::item(None);
@@ -381,7 +653,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
}
// 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, faces, _) = linked_bodies(&file, s.path.as_deref()).map_err(|e| bad(cmd, e.to_string()))?;
+ let (_, sf, faces, _, properties) = 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,
@@ -404,11 +676,13 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
f.kind = sf.kind;
f.link_faces = faces;
}
- s.doc_mut().links.insert(comp, DesignLink { path: file.to_string_lossy().into_owned(), feature: link.feature });
+ s.doc_mut().links.insert(comp, DesignLink { path: file.to_string_lossy().into_owned(), ..link.clone() });
s.refresh();
if let Some(error) = s.model.result(link.feature).and_then(|r| r.error.clone()) {
return Err(bad(cmd, error));
}
+ inherit_properties(s, comp, &properties)?;
+ s.refresh();
// Report the solver's diagnostics. A resolved joint can still describe the wrong
// connection after a source edit; the reminder above does not depend on solve errors.
let sol = solidcraft_doc::joints::solve(&s.doc, &s.model.state());
@@ -840,7 +1114,7 @@ mod tests {
std::fs::copy(&part, dir.join("parts").join("NUL.solidcraft")).unwrap();
let before = volume(&mut a);
for link in crafted.iter().chain(&devices) {
- a.doc_mut().links.insert(comp, DesignLink { path: link.to_string(), feature });
+ a.doc_mut().links.insert(comp, DesignLink { path: link.to_string(), feature, ..Default::default() });
let calls = solidcraft_io::vfs::file_calls();
let listed = run(&mut a, "component.links", json!({}));
let entry = &listed["links"][0];
@@ -858,7 +1132,7 @@ mod tests {
// Allowed (Allow once, a preference, …), the same link is read as any other.
#[cfg(unix)]
{
- a.doc_mut().links.insert(comp, DesignLink { path: crafted[0].to_string(), feature });
+ a.doc_mut().links.insert(comp, DesignLink { path: crafted[0].to_string(), feature, ..Default::default() });
solidcraft_io::vfs::allowing_hosts(&["EVIL.example".to_string()], || {
let listed = run(&mut a, "component.links", json!({}));
assert_eq!(listed["links"][0]["found"], true, "{listed}");
@@ -868,7 +1142,7 @@ mod tests {
}
// A local link, relative or absolute, is found and read as before.
for local in ["parts/plate.solidcraft".to_string(), part.to_string_lossy().to_string()] {
- a.doc_mut().links.insert(comp, DesignLink { path: local.clone(), feature });
+ a.doc_mut().links.insert(comp, DesignLink { path: local.clone(), feature, ..Default::default() });
assert_eq!(run(&mut a, "component.links", json!({}))["links"][0]["found"], true, "{local}");
assert_eq!(run(&mut a, "component.update_links", json!({}))["unchanged"], json!(["plate"]), "{local}");
}
@@ -888,7 +1162,9 @@ mod tests {
fn every_link_path_goes_through_the_design_path_rule() {
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
let code = |file: &str| {
- let text = std::fs::read_to_string(root.join(file)).unwrap();
+ // Windows Git checkouts can use CRLF. Locate the test module in either
+ // representation, rather than mistaking its fixture file calls for product code.
+ let text = std::fs::read_to_string(root.join(file)).unwrap().replace("\r\n", "\n");
// The code before its test module.
text.split("\n#[cfg(test)]\n#[allow(clippy::unwrap_used").next().unwrap_or("").to_string()
};
diff --git a/crates/engine/src/cmd/component_relink_tests.rs b/crates/engine/src/cmd/component_relink_tests.rs
index d457ac51d5..16c9b049a5 100644
--- a/crates/engine/src/cmd/component_relink_tests.rs
+++ b/crates/engine/src/cmd/component_relink_tests.rs
@@ -24,6 +24,121 @@ fn volume(s: &mut Session) -> f64 {
run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap()
}
+fn properties_part(path: &Path, material: &str, density: Option<f64>, color: [u8; 3]) -> Session {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Cube"}));
+ if let Some(density) = density {
+ s.doc_mut().user_materials.push(solidcraft_doc::UserMaterial { name: material.into(), density, appearance: None, physical_card: None });
+ }
+ run(&mut s, "material.assign", json!({"bodies": ["Cube"], "material": material}));
+ s.doc_mut().appearances.bodies.insert("Cube".into(), solidcraft_doc::appearance::Look::custom(color, 0.4));
+ run(&mut s, "file.save", json!({"path": path}));
+ s
+}
+
+fn assert_link_properties(s: &mut Session, component: u64, material: &str, mass: f64, color: [u8; 3]) {
+ let p = run(s, "component.properties", json!({"component": component}));
+ assert_eq!(p["bodies"][0]["material"], material, "{p}");
+ assert!((p["total"]["mass_g"].as_f64().unwrap() - mass).abs() < 1e-6, "{p}");
+ let state = s.model.state();
+ let b = state.bodies.iter().find(|b| b.component == component).unwrap();
+ let look = s.doc.model_body_look(b).unwrap();
+ assert_eq!(look.color, color);
+ assert!((s.doc.model_body_opacity(b) - 0.4).abs() < 1e-9);
+}
+
+#[test]
+fn linked_design_properties_keep_material_and_appearance_after_insert_and_reload() {
+ let dir = folder("properties-insert");
+ let file = dir.join("source.solidcraft");
+ properties_part(&file, "Steel", None, [12, 34, 56]);
+ let mut s = Session::default();
+ // The assembly already owns this body name; properties must follow the new name.
+ run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "body_name": "Cube"}));
+ let c = run(&mut s, "component.insert_design", json!({"path": file}))["component"].as_u64().unwrap();
+ assert_link_properties(&mut s, c, "Steel", 7.85, [12, 34, 56]);
+ assert_eq!(s.doc.body_material("Cube"), "Default");
+ let assembly = dir.join("assembly.solidcraft");
+ run(&mut s, "file.save", json!({"path": assembly}));
+ let mut cold = Session::default();
+ run(&mut cold, "doc.open", json!({"path": assembly}));
+ assert_link_properties(&mut cold, c, "Steel", 7.85, [12, 34, 56]);
+ run(&mut cold, "component.insert_design", json!({"path": file, "reuse": true}));
+ assert_eq!(cold.doc.links.len(), 1);
+ assert_link_properties(&mut cold, c, "Steel", 7.85, [12, 34, 56]);
+ let _ = std::fs::remove_dir_all(dir);
+}
+
+#[test]
+fn linked_design_properties_follow_source_only_edits_and_keep_local_overrides() {
+ let dir = folder("properties-update");
+ let file = dir.join("source.solidcraft");
+ let mut part = properties_part(&file, "Steel", None, [12, 34, 56]);
+ let mut s = Session::default();
+ let c = run(&mut s, "component.insert_design", json!({"path": file}))["component"].as_u64().unwrap();
+ run(&mut part, "material.assign", json!({"bodies": ["Cube"], "material": "Aluminum"}));
+ part.doc_mut().appearances.bodies.insert("Cube".into(), solidcraft_doc::appearance::Look::custom([80, 90, 100], 0.4));
+ run(&mut part, "file.save", json!({}));
+ assert_eq!(run(&mut s, "component.update_links", json!({}))["updated"].as_array().unwrap().len(), 1);
+ assert_link_properties(&mut s, c, "Aluminum", 2.7, [80, 90, 100]);
+ run(&mut s, "edit.undo", json!({}));
+ assert_link_properties(&mut s, c, "Steel", 7.85, [12, 34, 56]);
+ run(&mut s, "edit.redo", json!({}));
+ assert_link_properties(&mut s, c, "Aluminum", 2.7, [80, 90, 100]);
+ run(&mut s, "material.assign", json!({"bodies": ["Cube"], "material": "Brass"}));
+ s.doc_mut().appearances.bodies.insert("Cube".into(), solidcraft_doc::appearance::Look::custom([1, 2, 3], 0.4));
+ run(&mut part, "material.assign", json!({"bodies": ["Cube"], "material": "Steel"}));
+ run(&mut part, "file.save", json!({}));
+ run(&mut s, "component.update_links", json!({}));
+ assert_link_properties(&mut s, c, "Brass", solidcraft_doc::material_density("Brass").unwrap(), [1, 2, 3]);
+ let _ = std::fs::remove_dir_all(dir);
+}
+
+#[test]
+fn linked_design_properties_do_not_replace_conflicting_custom_materials() {
+ let dir = folder("properties-custom");
+ let file = dir.join("source.solidcraft");
+ properties_part(&file, "Custom alloy", Some(4.2), [12, 34, 56]);
+ let mut s = Session::default();
+ s.doc_mut().user_materials.push(solidcraft_doc::UserMaterial {
+ name: "Custom alloy".into(),
+ density: 9.0,
+ appearance: None,
+ physical_card: None,
+ });
+ let c = run(&mut s, "component.insert_design", json!({"path": file}))["component"].as_u64().unwrap();
+ let p = run(&mut s, "component.properties", json!({"component": c}));
+ let assigned = p["bodies"][0]["material"].as_str().unwrap();
+ assert_ne!(assigned, "Custom alloy");
+ assert!((p["total"]["mass_g"].as_f64().unwrap() - 4.2).abs() < 1e-6, "{p}");
+ assert_eq!(s.doc.material_density("Custom alloy"), Some(9.0));
+ assert_eq!(s.doc.user_materials.len(), 2);
+ let _ = std::fs::remove_dir_all(dir);
+}
+
+#[test]
+fn linked_design_properties_keep_distinct_names_for_equal_material_properties() {
+ let dir = folder("properties-equal-density");
+ let file = dir.join("source.solidcraft");
+ properties_part(&file, "Source alloy", Some(4.2), [12, 34, 56]);
+ let mut s = Session::default();
+ s.doc_mut().user_materials.push(solidcraft_doc::UserMaterial {
+ name: "Different alloy".into(),
+ density: 4.2,
+ appearance: None,
+ physical_card: None,
+ });
+ let c = run(&mut s, "component.insert_design", json!({"path": file}))["component"].as_u64().unwrap();
+ assert_link_properties(&mut s, c, "Source alloy", 4.2, [12, 34, 56]);
+ let count = s.doc.user_materials.len();
+ for _ in 0..2 {
+ assert_eq!(run(&mut s, "component.update_links", json!({}))["unchanged"].as_array().unwrap().len(), 1);
+ assert_eq!(s.doc.user_materials.len(), count);
+ }
+ assert_eq!(s.doc.user_material("Different alloy").unwrap().density, 4.2);
+ let _ = std::fs::remove_dir_all(dir);
+}
+
#[test]
fn reused_design_insertion_is_free_even_before_a_link_exists() {
let dir = folder("reuse-grounding");
@@ -46,6 +161,272 @@ fn reused_design_insertion_is_free_even_before_a_link_exists() {
let _ = std::fs::remove_dir_all(dir);
}
+#[test]
+fn linked_design_properties_update_density_without_geometry_and_keep_edited_cards() {
+ let dir = folder("properties-density");
+ let file = dir.join("source.solidcraft");
+ let mut part = properties_part(&file, "Custom alloy", Some(4.2), [12, 34, 56]);
+ let mut s = Session::default();
+ let c = run(&mut s, "component.insert_design", json!({"path": file}))["component"].as_u64().unwrap();
+ part.doc_mut().user_materials[0].density = 4.8;
+ run(&mut part, "file.save", json!({}));
+ assert_eq!(run(&mut s, "component.update_links", json!({}))["updated"].as_array().unwrap().len(), 1);
+ let p = run(&mut s, "component.properties", json!({"component": c}));
+ assert!((p["total"]["mass_g"].as_f64().unwrap() - 4.8).abs() < 1e-6, "{p}");
+ let name = p["bodies"][0]["material"].as_str().unwrap().to_string();
+ let count = s.doc.user_materials.len();
+ for _ in 0..2 {
+ assert_eq!(run(&mut s, "component.update_links", json!({}))["unchanged"].as_array().unwrap().len(), 1);
+ assert_eq!(s.doc.user_materials.len(), count, "unchanged source does not duplicate a disambiguated material");
+ }
+ s.doc_mut().user_materials.iter_mut().find(|m| m.name == name).unwrap().density = 6.0;
+ part.doc_mut().user_materials[0].density = 5.0;
+ run(&mut part, "file.save", json!({}));
+ run(&mut s, "component.update_links", json!({}));
+ assert_link_properties(&mut s, c, &name, 6.0, [12, 34, 56]);
+ let assembly = dir.join("assembly.solidcraft");
+ run(&mut s, "file.save", json!({"path": assembly}));
+ let mut cold = Session::default();
+ run(&mut cold, "doc.open", json!({"path": assembly}));
+ assert_link_properties(&mut cold, c, &name, 6.0, [12, 34, 56]);
+ let _ = std::fs::remove_dir_all(dir);
+}
+
+#[test]
+fn linked_design_properties_keep_opaque_pbr_and_face_color_after_reload() {
+ use solidcraft_doc::appearance::{FaceLook, Look};
+ use solidcraft_geom::Vec3;
+ let dir = folder("properties-optics");
+ let file = dir.join("source.solidcraft");
+ let mut part = properties_part(&file, "Steel", None, [12, 34, 56]);
+ let mut look = Look::custom([12, 34, 56], 1.0);
+ look.pbr = Some(solidcraft_doc::pbr_appearance::PbrParameters::new(0.8, 0.23, 1.5).unwrap());
+ part.doc_mut().appearances.bodies.insert("Cube".into(), look.clone());
+ let top = Vec3::new(5.0, 5.0, 10.0);
+ part.doc_mut().appearances.faces.push(FaceLook {
+ body: "Cube".into(),
+ point: top,
+ look: Look::custom([190, 20, 30], 0.65),
+ name: None,
+ strict_name: false,
+ certificate: None,
+ });
+ run(&mut part, "file.save", json!({}));
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "body_name": "Cube"}));
+ let c = run(&mut s, "component.insert_design", json!({"path": file}))["component"].as_u64().unwrap();
+ assert!(!s.doc.appearances.faces.iter().any(|face| face.body == "Cube"), "the assembly's existing body keeps its appearance");
+ let check = |s: &Session| {
+ let state = s.model.state();
+ let body = state.bodies.iter().find(|b| b.component == c).unwrap();
+ assert_eq!(s.doc.model_body_look(body), Some(look.clone()));
+ let face = solidcraft_doc::appearance::face_index_at(body, top).unwrap();
+ let face_looks = s.doc.face_colors(body);
+ let face_look = &face_looks.iter().find(|(f, _)| *f == face).unwrap().1;
+ assert_eq!(face_look.color, [190, 20, 30]);
+ assert!((face_look.opacity - 0.65).abs() < 1e-6);
+ };
+ check(&s);
+ let assembly = dir.join("assembly.solidcraft");
+ run(&mut s, "file.save", json!({"path": assembly}));
+ let mut cold = Session::default();
+ run(&mut cold, "doc.open", json!({"path": assembly}));
+ check(&cold);
+ let _ = std::fs::remove_dir_all(dir);
+}
+
+#[test]
+fn linked_face_overrides_update_independently_and_preserve_local_edits_and_removals() {
+ use solidcraft_doc::appearance::{FaceLook, Look};
+ use solidcraft_geom::Vec3;
+ let dir = folder("properties-faces");
+ let file = dir.join("source.solidcraft");
+ let mut part = properties_part(&file, "Steel", None, [12, 34, 56]);
+ let top = Vec3::new(5.0, 5.0, 10.0);
+ let side = Vec3::new(10.0, 5.0, 5.0);
+ for (point, color) in [(top, [190, 20, 30]), (side, [20, 190, 30])] {
+ part.doc_mut().appearances.faces.push(FaceLook {
+ body: "Cube".into(),
+ point,
+ look: Look::custom(color, 1.0),
+ name: None,
+ strict_name: false,
+ certificate: None,
+ });
+ }
+ run(&mut part, "file.save", json!({}));
+ let mut s = Session::default();
+ let c = run(&mut s, "component.insert_design", json!({"path": file}))["component"].as_u64().unwrap();
+ let color = |s: &Session, point| {
+ let state = s.model.state();
+ let body = state.bodies.iter().find(|b| b.component == c).unwrap();
+ let index = solidcraft_doc::appearance::face_index_at(body, point).unwrap();
+ s.doc.face_colors(body).into_iter().find(|(face, _)| *face == index).map(|(_, look)| look.color)
+ };
+ assert_eq!(color(&s, top), Some([190, 20, 30]));
+ assert_eq!(color(&s, side), Some([20, 190, 30]));
+ part.doc_mut().appearances.faces[0].look = Look::custom([30, 40, 200], 1.0);
+ part.doc_mut().appearances.faces.pop();
+ run(&mut part, "file.save", json!({}));
+ run(&mut s, "component.update_links", json!({}));
+ assert_eq!(color(&s, top), Some([30, 40, 200]));
+ assert_eq!(color(&s, side), None, "a removed source override reveals the body's look");
+ run(&mut s, "edit.undo", json!({}));
+ assert_eq!(color(&s, side), Some([20, 190, 30]));
+ run(&mut s, "edit.redo", json!({}));
+ assert_eq!(color(&s, side), None);
+ let mut local = s.doc.appearances.faces[0].clone();
+ local.look = Look::custom([200, 180, 30], 1.0);
+ s.doc_mut().appearances.faces.push(local);
+ let assembly = dir.join("assembly.solidcraft");
+ run(&mut s, "file.save", json!({"path": assembly}));
+ let mut cold = Session::default();
+ run(&mut cold, "doc.open", json!({"path": assembly}));
+ part.doc_mut().appearances.faces[0].look = Look::custom([40, 50, 60], 1.0);
+ run(&mut part, "file.save", json!({}));
+ run(&mut cold, "component.update_links", json!({}));
+ assert_eq!(color(&cold, top), Some([200, 180, 30]), "a local face edit survives a source edit after reopening");
+ cold.doc_mut().appearances.faces.clear();
+ part.doc_mut().appearances.faces[0].look = Look::custom([60, 70, 80], 1.0);
+ run(&mut part, "file.save", json!({}));
+ run(&mut cold, "component.update_links", json!({}));
+ assert_eq!(color(&cold, top), None, "an explicit local removal is not restored by a source update");
+ // A link saved by the earlier material-only implementation must be read again,
+ // even when the file read cache already knows the current source bytes.
+ cold.doc_mut().links.get_mut(&c).unwrap().inherited[0].faces = None;
+ run(&mut cold, "component.update_links", json!({}));
+ assert_eq!(color(&cold, top), Some([60, 70, 80]));
+ let _ = std::fs::remove_dir_all(dir);
+}
+
+#[test]
+fn linked_properties_update_every_component_and_session_sharing_a_cached_source() {
+ let dir = folder("properties-shared-read");
+ let file = dir.join("source.solidcraft");
+ let mut part = properties_part(&file, "Source alloy", Some(4.2), [12, 34, 56]);
+ let mut s = Session::default();
+ let a = run(&mut s, "component.insert_design", json!({"path": file}))["component"].as_u64().unwrap();
+ let b = run(&mut s, "component.insert_design", json!({"path": file}))["component"].as_u64().unwrap();
+ let mut other = Session::default();
+ let c = run(&mut other, "component.insert_design", json!({"path": file}))["component"].as_u64().unwrap();
+ part.doc_mut().user_materials[0].density = 4.8;
+ run(&mut part, "file.save", json!({}));
+ let updated = run(&mut s, "component.update_links", json!({}));
+ assert_eq!(updated["updated"].as_array().unwrap().len(), 2, "{updated}");
+ for component in [a, b] {
+ let p = run(&mut s, "component.properties", json!({"component": component}));
+ assert!((p["total"]["mass_g"].as_f64().unwrap() - 4.8).abs() < 1e-6, "{p}");
+ }
+ run(&mut other, "component.update_links", json!({}));
+ let p = run(&mut other, "component.properties", json!({"component": c}));
+ assert!((p["total"]["mass_g"].as_f64().unwrap() - 4.8).abs() < 1e-6, "{p}");
+ let _ = std::fs::remove_dir_all(dir);
+}
+
+#[test]
+fn linked_face_removal_without_a_body_look_does_not_reveal_baked_source_paint() {
+ use solidcraft_doc::appearance::{FaceLook, Look};
+ let dir = folder("properties-unpainted-body");
+ let file = dir.join("source.solidcraft");
+ let mut part = properties_part(&file, "Steel", None, [12, 34, 56]);
+ part.doc_mut().appearances.bodies.clear();
+ part.doc_mut().appearances.faces.push(FaceLook {
+ body: "Cube".into(),
+ point: solidcraft_geom::Vec3::new(5.0, 5.0, 10.0),
+ look: Look::custom([190, 20, 30], 0.65),
+ name: None,
+ strict_name: false,
+ certificate: None,
+ });
+ run(&mut part, "file.save", json!({}));
+ let mut s = Session::default();
+ run(&mut s, "component.insert_design", json!({"path": file}));
+ assert_eq!(s.doc.face_colors(&s.model.state().bodies[0]).len(), 1);
+ assert!(s.doc.appearances.bodies.is_empty());
+ s.doc_mut().appearances.faces.clear();
+ assert!(s.doc.face_colors(&s.model.state().bodies[0]).is_empty(), "local removal must reveal the body's material, not duplicate STEP paint");
+ part.doc_mut().appearances.faces[0].look = Look::custom([20, 190, 30], 0.8);
+ run(&mut part, "file.save", json!({}));
+ run(&mut s, "component.update_links", json!({}));
+ assert!(s.doc.face_colors(&s.model.state().bodies[0]).is_empty(), "source edits must preserve the local removal");
+ let _ = std::fs::remove_dir_all(dir);
+}
+
+#[test]
+fn unchanged_linked_face_overrides_do_not_reorder_assignments_or_report_updates() {
+ use solidcraft_doc::appearance::{FaceLook, Look};
+ let dir = folder("properties-face-cache");
+ let file = dir.join("source.solidcraft");
+ let mut part = properties_part(&file, "Steel", None, [12, 34, 56]);
+ part.doc_mut().appearances.faces.push(FaceLook {
+ body: "Cube".into(),
+ point: solidcraft_geom::Vec3::new(5.0, 5.0, 10.0),
+ look: Look::custom([190, 20, 30], 0.65),
+ name: None,
+ strict_name: false,
+ certificate: None,
+ });
+ run(&mut part, "file.save", json!({}));
+ let mut s = Session::default();
+ for _ in 0..2 {
+ run(&mut s, "component.insert_design", json!({"path": file}));
+ }
+ let before = s.doc.clone();
+ for _ in 0..2 {
+ let result = run(&mut s, "component.update_links", json!({}));
+ assert!(result["updated"].as_array().unwrap().is_empty(), "{result}");
+ assert_eq!(result["unchanged"].as_array().unwrap().len(), 2, "{result}");
+ assert_eq!(s.doc, before, "unchanged links preserve assignment order and inherited baselines");
+ }
+ let _ = std::fs::remove_dir_all(dir);
+}
+
+#[test]
+fn linked_design_properties_survive_save_as_and_relink_with_undo() {
+ let dir = folder("properties-relink");
+ let first = dir.join("first.solidcraft");
+ let second = dir.join("second.solidcraft");
+ properties_part(&first, "Steel", None, [12, 34, 56]);
+ properties_part(&second, "Aluminum", None, [80, 90, 100]);
+ let mut s = Session::default();
+ let c = run(&mut s, "component.insert_design", json!({"path": first}))["component"].as_u64().unwrap();
+ let baseline = s.doc.links[&c].inherited.clone();
+ let assembly = dir.join("assembly.solidcraft");
+ run(&mut s, "file.save", json!({"path": assembly}));
+ let saved_as = dir.join("saved-as.solidcraft");
+ run(&mut s, "file.save", json!({"path": saved_as}));
+ let mut cold = Session::default();
+ run(&mut cold, "doc.open", json!({"path": saved_as}));
+ assert_eq!(cold.doc.links[&c].inherited, baseline);
+ run(&mut cold, "component.relink", json!({"component": c, "path": second}));
+ assert_link_properties(&mut cold, c, "Aluminum", 2.7, [80, 90, 100]);
+ run(&mut cold, "edit.undo", json!({}));
+ assert_link_properties(&mut cold, c, "Steel", 7.85, [12, 34, 56]);
+ run(&mut cold, "edit.redo", json!({}));
+ assert_link_properties(&mut cold, c, "Aluminum", 2.7, [80, 90, 100]);
+ let _ = std::fs::remove_dir_all(dir);
+}
+
+#[test]
+fn linked_design_properties_repair_old_links_without_overwriting_assignments() {
+ let dir = folder("properties-legacy");
+ let file = dir.join("source.solidcraft");
+ properties_part(&file, "Steel", None, [12, 34, 56]);
+ let mut s = Session::default();
+ let c = run(&mut s, "component.insert_design", json!({"path": file}))["component"].as_u64().unwrap();
+ s.doc_mut().links.get_mut(&c).unwrap().inherited.clear();
+ s.doc_mut().materials.remove("Cube");
+ s.doc_mut().appearances.bodies.remove("Cube");
+ run(&mut s, "component.update_links", json!({}));
+ assert_link_properties(&mut s, c, "Steel", 7.85, [12, 34, 56]);
+ s.doc_mut().links.get_mut(&c).unwrap().inherited.clear();
+ run(&mut s, "material.assign", json!({"bodies": ["Cube"], "material": "Brass"}));
+ s.doc_mut().appearances.bodies.insert("Cube".into(), solidcraft_doc::appearance::Look::custom([1, 2, 3], 0.4));
+ run(&mut s, "component.update_links", json!({}));
+ assert_link_properties(&mut s, c, "Brass", solidcraft_doc::material_density("Brass").unwrap(), [1, 2, 3]);
+ let _ = std::fs::remove_dir_all(dir);
+}
+
#[test]
fn relink_repairs_a_moved_source_for_every_instance_in_one_undo_step() {
let dir = folder("moved");
diff --git a/crates/engine/src/cmd/design_link.rs b/crates/engine/src/cmd/design_link.rs
index 8844a37a04..9e33c2e93f 100644
--- a/crates/engine/src/cmd/design_link.rs
+++ b/crates/engine/src/cmd/design_link.rs
@@ -68,7 +68,7 @@ pub(super) fn resolve(design: Option<&str>, link: &str) -> PathBuf {
/// The links of `doc` stored for a design saved at `to` instead of at `from`.
pub(super) fn rebased(doc: &Document, from: Option<&str>, to: &str) -> std::collections::BTreeMap<u64, DesignLink> {
- doc.links.iter().map(|(c, l)| (*c, DesignLink { path: stored(Some(to), &resolve(from, &l.path)), feature: l.feature })).collect()
+ doc.links.iter().map(|(c, l)| (*c, DesignLink { path: stored(Some(to), &resolve(from, &l.path)), ..l.clone() })).collect()
}
#[cfg(test)]
@@ -90,7 +90,7 @@ mod tests {
let unsaved = stored(None, &part);
assert!(Path::new(&unsaved).is_absolute(), "{unsaved}");
let mut doc = Document::default();
- doc.links.insert(7, DesignLink { path: unsaved, feature: 3 });
+ doc.links.insert(7, DesignLink { path: unsaved, feature: 3, ..Default::default() });
let moved = rebased(&doc, None, &design);
assert_eq!(moved.get(&7).map(|l| l.path.as_str()), Some("../parts/plate.solidcraft"));
let beside = root.join("parts").join("asm.solidcraft").to_string_lossy().into_owned();
diff --git a/crates/ui-egui/src/file_load_ui_tests.rs b/crates/ui-egui/src/file_load_ui_tests.rs
index 08c3b7d000..3d18de8443 100644
--- a/crates/ui-egui/src/file_load_ui_tests.rs
+++ b/crates/ui-egui/src/file_load_ui_tests.rs
@@ -279,7 +279,7 @@ fn update_links_and_open_linked_design_ask_before_a_network_location() {
let comp = h.app.run("component.insert_design", json!({"path": part})).unwrap()["component"].as_u64().unwrap();
h.app.run("file.save", json!({"path": case})).unwrap();
let feature = h.app.session.doc.links[&comp].feature;
- h.app.session.doc_mut().links.insert(comp, solidcraft_engine::doc::DesignLink { path: crafted.into(), feature });
+ h.app.session.doc_mut().links.insert(comp, solidcraft_engine::doc::DesignLink { path: crafted.into(), feature, ..Default::default() });
save_part(8.0);
let until_idle = |h: &mut crate::scenario::Harness| {
let began = std::time::Instant::now();
diff --git a/crates/ui-egui/src/i18n_menu_tests.rs b/crates/ui-egui/src/i18n_menu_tests.rs
index 95b5f8d7c8..9d3fa277d3 100644
--- a/crates/ui-egui/src/i18n_menu_tests.rs
+++ b/crates/ui-egui/src/i18n_menu_tests.rs
@@ -95,7 +95,10 @@ fn every_menu_label_is_in_the_english_catalog() {
// Linked components offer source-file actions absent from the sample design.
let linked = app.session.execute("component.create", &json!({"name": "Linked part"})).expect("linked component");
let component = linked["component"].as_u64().expect("component id");
- app.session.doc_mut().links.insert(component, solidcraft_engine::doc::DesignLink { path: "part.solidcraft".into(), feature: 0 });
+ app.session
+ .doc_mut()
+ .links
+ .insert(component, solidcraft_engine::doc::DesignLink { path: "part.solidcraft".into(), feature: 0, ..Default::default() });
take(&app, &mut seen);
assert!(seen.contains("Open Linked Design"));