SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Physical material: one rule for a body's material and its density (#4783) (#4785)
CamWight9559ad398a1e
diff --git a/assets/materials/library.rs b/assets/materials/library.rsindex 83497e9700..4416cc1df6 100644--- a/assets/materials/library.rs+++ b/assets/materials/library.rs@@ -1,9 +1,14 @@//! Built-in physical materials: densities in g/cm³ and sRGB colours.++/// The default material's name: what a body without a usable material of its own is made of.+/// Assigning it clears a body's assignment.+pub const DEFAULT_MATERIAL: &str = "Default";+/// Density of the default material (g/cm³).pub const DEFAULT_DENSITY: f64 = 1.29;/// Physical materials: name and density (g/cm³).pub const MATERIALS: [(&str, f64); 14] = [- ("Default", DEFAULT_DENSITY),+ (DEFAULT_MATERIAL, DEFAULT_DENSITY),("Steel", 7.85),("Stainless Steel", 8.0),("Aluminum", 2.70),diff --git a/crates/doc/src/config.rs b/crates/doc/src/config.rsindex 36684b1d67..369db695ca 100644--- a/crates/doc/src/config.rs+++ b/crates/doc/src/config.rs@@ -4,7 +4,7 @@use serde::{Deserialize, Serialize};-use crate::{DocError, Document, Result};+use crate::{DEFAULT_MATERIAL, DocError, Document, Result};#[path = "config_rules.rs"]mod rules;@@ -96,7 +96,7 @@ impl Document {/// returning None for the default material.pub fn material_cell(&self, value: &str) -> Result<Option<String>> {let name = self.material_name(value).ok_or_else(|| DocError::Invalid(format!("unknown configuration material `{value}`")))?;- Ok((name != "Default").then_some(name))+ Ok((name != DEFAULT_MATERIAL).then_some(name))}/// Freeze design-unit-sensitive configuration literals when changing display units.@@ -140,7 +140,7 @@ impl Document {}}),Column::Suppress(id) => self.feature(*id).map(|f| f.suppressed.to_string()),- Column::Material(body) => Some(self.materials.get(body).cloned().unwrap_or_else(|| "Default".into())),+ Column::Material(body) => Some(self.materials.get(body).cloned().unwrap_or_else(|| DEFAULT_MATERIAL.into())),Column::Appearance(body) => Some(self.appearances.bodies.get(body).and_then(|look| serde_json::to_string(look).ok()).unwrap_or_default()),Column::ComponentAppearance(id) => {Some(self.appearances.components.get(id).and_then(|look| serde_json::to_string(look).ok()).unwrap_or_default())diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rsindex 5519439a1d..803c619765 100644--- a/crates/doc/src/document.rs+++ b/crates/doc/src/document.rs@@ -2856,9 +2856,21 @@ impl Document {st}- /// Density of a body's material (g/cm³).+ /// The material a body's mass is computed with, as the library or this design spells it:+ /// its assigned material when that is known and has a usable density, else+ /// [`DEFAULT_MATERIAL`]. The assignment as stored (`materials`) is left as it is.+ pub fn body_material(&self, body: &str) -> String {+ self.materials+ .get(body)+ .and_then(|m| self.material_name(m))+ .filter(|m| self.material_density(m).is_some())+ .unwrap_or_else(|| DEFAULT_MATERIAL.into())+ }++ /// Density of a body's material (g/cm³): its [`Document::body_material`]'s, so the name a+ /// body reads and the mass it has never disagree.pub fn density(&self, body: &str) -> f64 {- self.materials.get(body).and_then(|m| self.material_density(m)).unwrap_or(DEFAULT_DENSITY)+ self.material_density(&self.body_material(body)).unwrap_or(DEFAULT_DENSITY)}/// A material defined in this design, by name (case-insensitive).@@ -3572,10 +3584,10 @@ impl Document {}}-/// Density of the default material (g/cm³), as the default.+/// The built-in material library: (name, density), and each material's colour.#[path = "../../../assets/materials/library.rs"]mod materials;-pub use materials::{DEFAULT_DENSITY, MATERIALS, material_color};+pub use materials::{DEFAULT_DENSITY, DEFAULT_MATERIAL, MATERIALS, material_color};/// A physical material defined in a design (`material.create`): its name, its density and,/// optionally, the look it gives bodies without an appearance of their own.diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rsindex d2f5f47a62..87f0199a94 100644--- a/crates/doc/src/tests.rs+++ b/crates/doc/src/tests.rs@@ -251,6 +251,45 @@ fn params_and_serialization() {assert!(doc.param("d1").is_none(), "unused model parameters are pruned");}+/// #4783: a body reads the material its mass is computed with, as the library or the design+/// spells it. An unknown name, or a design material with an unusable density, reads as the+/// default material it weighs. `density` agrees in every case, and a configuration keeps the+/// assignment as stored.+#[test]+fn a_body_reads_the_material_its_mass_is_computed_with() {+ let mut doc = Document::new("materials");+ let usable = [("Walnut", 0.65), ("Mote", f64::MIN_POSITIVE), ("Limit", MAX_DENSITY)];+ let unusable = [("Broken", -3.0), ("Weightless", 0.0), ("Beyond", MAX_DENSITY.next_up())];+ for (name, density) in usable.into_iter().chain(unusable) {+ doc.user_materials.push(UserMaterial { name: name.into(), density, appearance: None });+ }+ // (body, its assignment as stored, the material it reads and weighs, that material's density)+ let cases = [+ ("Known", Some("Steel"), "Steel", 7.85),+ ("Miscased", Some("steel"), "Steel", 7.85),+ ("Own", Some(" walnut "), "Walnut", 0.65),+ ("Lightest", Some("Mote"), "Mote", f64::MIN_POSITIVE),+ ("At the limit", Some("Limit"), "Limit", MAX_DENSITY),+ ("Unknown", Some("Unobtainium"), DEFAULT_MATERIAL, DEFAULT_DENSITY),+ ("Unusable", Some("Broken"), DEFAULT_MATERIAL, DEFAULT_DENSITY),+ ("Zero density", Some("Weightless"), DEFAULT_MATERIAL, DEFAULT_DENSITY),+ ("Over the limit", Some("Beyond"), DEFAULT_MATERIAL, DEFAULT_DENSITY),+ ("Unassigned", None, DEFAULT_MATERIAL, DEFAULT_DENSITY),+ ];+ for (body, stored, ..) in cases {+ if let Some(material) = stored {+ doc.materials.insert(body.into(), material.into());+ }+ }+ for (body, stored, material, density) in cases {+ assert_eq!(doc.body_material(body), material, "{body}");+ assert_eq!(doc.density(body), density, "{body}");+ assert_eq!(doc.material_density(material), Some(density), "{body}: the density is its material's");+ let cell = doc.config_current(&crate::config::Column::Material(body.into()));+ assert_eq!(cell.as_deref(), Some(stored.unwrap_or(DEFAULT_MATERIAL)), "{body}: a configuration keeps the assignment as stored");+ }+}+#[test]fn primitives_and_combine() {let mut doc = Document::new("p");diff --git a/crates/engine/src/cmd/component_properties.rs b/crates/engine/src/cmd/component_properties.rsindex 764afed3c6..226f5d03f3 100644--- a/crates/engine/src/cmd/component_properties.rs+++ b/crates/engine/src/cmd/component_properties.rs@@ -130,7 +130,7 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool,edges += measured.merged.edges;vertices += measured.merged.vertices;bodies.push(json!({"name": body.name, "component": component, "path": path,- "material": doc.materials.get(&body.name).map(String::as_str).unwrap_or("Default"),+ "material": doc.body_material(&body.name),"density_g_cm3": density, "mass_g": body_mass, "volume_mm3": measured.volume,"area_mm2": measured.area, "center_of_mass": measured.centroid,"bbox": {"min": measured.bbox.min, "max": measured.bbox.max}}));diff --git a/crates/engine/src/cmd/component_properties_tests.rs b/crates/engine/src/cmd/component_properties_tests.rsindex 611b885d02..8a969551c9 100644--- a/crates/engine/src/cmd/component_properties_tests.rs+++ b/crates/engine/src/cmd/component_properties_tests.rs@@ -256,7 +256,8 @@ fn user_defined_material_survives_save_and_reopen() {/// #532: designs from before user materials open unchanged: built-in assignments keep their/// densities and a design without its own materials saves no `user_materials`. A damaged-/// file's unusable density falls back to the default instead of producing nonsense masses.+/// file's unusable density falls back to the default instead of producing nonsense masses, and+/// the body reads as the default material.#[test]fn designs_without_user_materials_open_unchanged() {let (dir, path) = temp_design("legacy");@@ -278,7 +279,17 @@ fn designs_without_user_materials_open_unchanged() {std::fs::write(&path, serde_json::to_vec(&legacy).unwrap()).unwrap();run(&mut s, "doc.open", json!({"path": path}));close(&mass(&mut s), solidcraft_doc::DEFAULT_DENSITY);+ // #4783: it reads as the material it weighs; the file's assignment is kept as it is.+ let props = run(&mut s, "component.properties", json!({"component": "root"}));+ assert_eq!(props["bodies"][0]["material"], "Default", "{props}");+ let measured = run(&mut s, "inspect.measure", json!({}));+ assert_eq!(measured["bodies"][0]["material"], "Default", "{measured}");+ close(&measured["bodies"][0]["density_g_cm3"], solidcraft_doc::DEFAULT_DENSITY);+ assert_eq!(s.doc.materials.get("Plate").map(String::as_str), Some("Broken"));assert_eq!(s.doc.material_look("Broken").map(|l| l.opacity), Some(1.0));+ // Assigning the default material, in any case, clears the damaged assignment.+ run(&mut s, "material.assign", json!({"bodies": ["Plate"], "material": "default"}));+ assert!(!s.doc.materials.contains_key("Plate"));let _ = std::fs::remove_dir_all(&dir);}@@ -292,6 +303,10 @@ fn configurations_switch_to_a_user_defined_material() {run(&mut s, "config.row", json!({"name": "Walnut", "values": {"material:Slat": "walnut"}}));run(&mut s, "config.activate", json!({"row": "Walnut"}));close(&mass(&mut s), 0.65);+ // A row of the default material, in any case, clears the assignment.+ run(&mut s, "config.row", json!({"name": "Plain", "values": {"material:Slat": "default"}}));+ run(&mut s, "config.activate", json!({"row": "Plain"}));+ assert!(!s.doc.materials.contains_key("Slat"));run(&mut s, "material.edit", json!({"material": "Walnut", "name": "Black Walnut"}));run(&mut s, "config.activate", json!({"row": "Default"}));run(&mut s, "config.activate", json!({"row": "Walnut"}));diff --git a/crates/engine/src/cmd/config.rs b/crates/engine/src/cmd/config.rsindex ca170e5a9a..08e548f52d 100644--- a/crates/engine/src/cmd/config.rs+++ b/crates/engine/src/cmd/config.rs@@ -2,6 +2,7 @@//! suppressions) and switching between its rows.use serde_json::{Value, json};+use solidcraft_doc::DEFAULT_MATERIAL;use solidcraft_doc::config::{Column, ConfigRow, MAX_COLUMNS, MAX_ROWS};use super::CommandSpec;@@ -265,7 +266,7 @@ fn row(s: &mut Session, p: &Value) -> Result<Value> {.ok_or_else(|| bad(cmd, format!("`{k}` is not a column (config.column adds one)")))?;match s.doc.configs.columns.get(col) {Some(Column::Material(_)) => {- text = s.doc.material_cell(&text).map_err(|e| bad(cmd, e.to_string()))?.unwrap_or_else(|| "Default".into());+ text = s.doc.material_cell(&text).map_err(|e| bad(cmd, e.to_string()))?.unwrap_or_else(|| DEFAULT_MATERIAL.into());}Some(Column::Appearance(_) | Column::ComponentAppearance(_) | Column::FaceAppearance(_)) => {text = match solidcraft_doc::config::appearance_cell(&text).map_err(|e| bad(cmd, e.to_string()))? {diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rsindex 76394f1134..5e271a87b1 100644--- a/crates/engine/src/cmd/inspect.rs+++ b/crates/engine/src/cmd/inspect.rs@@ -86,10 +86,11 @@ fn measure(s: &mut Session, p: &Value) -> Result<Value> {.collect();// Mass from each body's material.for (b, body) in bodies.iter_mut().zip(selected) {+ let source = body.definition_name();+ // Every body's material, measured or not: naming it takes no measuring.+ b["material"] = json!(s.doc.body_material(source));if let Some(v) = b["volume_mm3"].as_f64() {- let source = body.definition_name();let rho = s.doc.density(source);- b["material"] = json!(s.doc.materials.get(source).cloned().unwrap_or_else(|| "Default".into()));b["density_g_cm3"] = json!(rho);b["mass_g"] = json!(v * rho / 1000.0);}@@ -362,7 +363,7 @@ fn physical_material(s: &mut Session, p: &Value) -> Result<Value> {return Err(bad(cmd, "`bodies` must list existing bodies"));}for b in &bodies {- if canonical == "Default" {+ if canonical == solidcraft_doc::DEFAULT_MATERIAL {s.doc_mut().materials.remove(b);} else {s.doc_mut().materials.insert(b.clone(), canonical.clone());diff --git a/crates/engine/src/cmd/materials.rs b/crates/engine/src/cmd/materials.rsindex 0c27d46bef..233748a237 100644--- a/crates/engine/src/cmd/materials.rs+++ b/crates/engine/src/cmd/materials.rs@@ -7,7 +7,7 @@use serde_json::{Value, json};use solidcraft_doc::appearance::{Look, library};use solidcraft_doc::config::Column;-use solidcraft_doc::{MATERIALS, UserMaterial, valid_density};+use solidcraft_doc::{DEFAULT_MATERIAL, MATERIALS, UserMaterial, valid_density};use super::CommandSpec;use super::inspect::{color_param, look_json};@@ -133,13 +133,13 @@ fn uses(s: &Session, name: &str) -> (Vec<String>, Vec<String>) {}/// Point every use of material `from` (body assignments, configuration cells) at `to`-/// ("Default" removes the body assignments).+/// ([`DEFAULT_MATERIAL`] removes the body assignments).fn move_uses(s: &mut Session, from: &str, to: &str) {let columns = material_columns(s);let d = s.doc_mut();let bodies: Vec<String> = d.materials.iter().filter(|(_, m)| m.eq_ignore_ascii_case(from)).map(|(b, _)| b.clone()).collect();for b in bodies {- if to == "Default" {+ if to == DEFAULT_MATERIAL {d.materials.remove(&b);} else {d.materials.insert(b, to.to_string());diff --git a/crates/ui-egui/src/configurations_ui.rs b/crates/ui-egui/src/configurations_ui.rsindex 28e315f097..c5a5f0e3eb 100644--- a/crates/ui-egui/src/configurations_ui.rs+++ b/crates/ui-egui/src/configurations_ui.rs@@ -2,6 +2,7 @@use super::{cell_value, column_parts, configuration_rules_ui, table, unit_of};use crate::{SolveApp, ui_kit};use serde_json::{Value, json};+use solidcraft_engine::doc::DEFAULT_MATERIAL;/// The Configurations table, its rules and errors.pub(super) fn configurations_rows(app: &mut SolveApp,@@ -399,10 +400,12 @@ fn column_menu(app: &mut SolveApp, ui: &mut egui::Ui, error: &mut Option<String>}fn display_cell(kind: &str, value: &str) -> String {- if (kind == "material" || matches!(kind, "appearance" | "component_appearance" | "face_appearance")) && value.eq_ignore_ascii_case("Default") {+ let appearance = matches!(kind, "appearance" | "component_appearance" | "face_appearance");+ // Empty cells: the default material, and an appearance's own "Default" keyword (it follows).+ if (kind == "material" && value.eq_ignore_ascii_case(DEFAULT_MATERIAL)) || (appearance && value.eq_ignore_ascii_case("Default")) {return String::new();}- if matches!(kind, "appearance" | "component_appearance" | "face_appearance") {+ if appearance {solidcraft_engine::doc::config::appearance_cell(value).ok().flatten()@@ -427,11 +430,13 @@ fn value_control(ui: &mut egui::Ui, id: egui::Id, text: &mut String, kind: &str,};ui_kit::library_cell(ui, id, text, follow, |ui| {if ui_kit::button(ui, crate::i18n::tr_label(follow), ui_kit::Button::Normal).clicked() {- choice = Some("Default".to_owned());+ // An appearance's "Default" keyword follows; a material's is the default material.+ let follow_value = if appearance { "Default" } else { DEFAULT_MATERIAL };+ choice = Some(follow_value.to_owned());ui.close();}let choices: Vec<_> = if kind == "material" {- material_names.iter().filter(|n| *n != "Default").map(String::as_str).collect()+ material_names.iter().filter(|n| *n != DEFAULT_MATERIAL).map(String::as_str).collect()} else {solidcraft_engine::doc::appearance::LIBRARY.iter().map(|(name, _, _)| *name).collect()};diff --git a/crates/ui-egui/src/design_properties.rs b/crates/ui-egui/src/design_properties.rsindex 696e0c4d2e..a1ff144c41 100644--- a/crates/ui-egui/src/design_properties.rs+++ b/crates/ui-egui/src/design_properties.rs@@ -136,7 +136,8 @@ pub fn show_object(app: &mut SolveApp, ctx: &egui::Context) {let total = &v["total"];let bodies = v["bodies"].as_array().cloned().unwrap_or_default();if let [b] = bodies.as_slice() {- rows.push(("Material", b["material"].as_str().unwrap_or("Default").to_string()));+ // The engine names every body's material, measured or not: nothing to guess here.+ rows.push(("Material", b["material"].as_str().unwrap_or_default().to_string()));rows.push(("Density", format!("{:.3} g/cm³", number(b, "density_g_cm3"))));}rows.push(("Mass", format!("{:.3} g", number(total, "mass_g"))));diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 6e3f44e491..a296c36752 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -3580,7 +3580,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result<Vec<(String, Value)>, S}Kind::Material { index } => {need(0, "bodies")?;- let name = s.doc.material_names().get(*index).cloned().unwrap_or_else(|| "Default".into());+ let name = s.doc.material_names().get(*index).cloned().unwrap_or_else(|| solidcraft_engine::doc::DEFAULT_MATERIAL.into());("material.assign", json!({"bodies": sels(d, 0).body_names(), "material": name}))}Kind::Section { offset, flip } => {