Colours in exports from materials and appearances; Appearance command
- Bodies export (STEP, 3MF) in the colour they are shown in: an appearance,
else the physical material's look, else the colour the body was imported
with (Document::body_color / painted). Physical materials used to export
no colour at all.
- AppearanceCommand (Modify): a colour per body ("#rrggbb" or [r, g, b];
null follows the material again), kept in the design and across renames.
- Material looks move to solvecraft-doc (material_color); the viewport draws
appearance, material or imported colour, as exported.
- Engine test: brass and red ABS bodies export, re-import with their RGB, and
keep it through open and export again.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AS5Tn3xieewUSg3uxrMVdL
This commit is contained in:
1 parent
578b35e88a
commit
ae4570ed39
8 files changed
+200
-86
No files matched your search
@@ -1040,6 +1040,9 @@ pub struct Document {
|
||||
/// Physical material per body (by body name); others use the default.
|
||||
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
|
||||
pub materials: std::collections::BTreeMap<String, String>,
|
||||
/// Appearance colour per body (by body name, sRGB); it overrides the material's look.
|
||||
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
|
||||
pub appearances: std::collections::BTreeMap<String, [u8; 3]>,
|
||||
/// Bodies moved into another component than their feature's (by body name).
|
||||
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
|
||||
pub body_components: std::collections::BTreeMap<String, u64>,
|
||||
@@ -1094,6 +1097,7 @@ impl Document {
|
||||
plastic: Default::default(),
|
||||
body_components: Default::default(),
|
||||
materials: Default::default(),
|
||||
appearances: Default::default(),
|
||||
favorites: Default::default(),
|
||||
canvases: Vec::new(),
|
||||
param_comments: Default::default(),
|
||||
@@ -1102,6 +1106,25 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour a body is shown and exported in (sRGB as 0–1 fractions): its
|
||||
/// appearance, else its material's look, else the colour it was imported with.
|
||||
pub fn body_color(&self, name: &str, body: &solvecraft_kernel::Body) -> Option<[f32; 3]> {
|
||||
let rgb = |c: [u8; 3]| c.map(|x| x as f32 / 255.0);
|
||||
self.appearances.get(name).copied().or_else(|| self.materials.get(name).and_then(|m| material_color(m))).map(rgb).or_else(|| body.color())
|
||||
}
|
||||
|
||||
/// The model with each body carrying the colour it is shown in (for export).
|
||||
pub fn painted(&self, state: &crate::ModelState) -> crate::ModelState {
|
||||
let mut st = state.clone();
|
||||
for b in &mut st.bodies {
|
||||
let c = self.body_color(&b.name, &b.body);
|
||||
if c != b.body.color() {
|
||||
b.body = b.body.clone().with_color(c);
|
||||
}
|
||||
}
|
||||
st
|
||||
}
|
||||
|
||||
/// Density of a body's material (g/cm³).
|
||||
pub fn density(&self, body: &str) -> f64 {
|
||||
self.materials.get(body).and_then(|m| material_density(m)).unwrap_or(DEFAULT_DENSITY)
|
||||
@@ -1445,6 +1468,26 @@ pub const MATERIALS: [(&str, f64); 14] = [
|
||||
("Glass", 2.50),
|
||||
];
|
||||
|
||||
/// How a physical material looks (sRGB); the default material has no colour of its own.
|
||||
pub fn material_color(name: &str) -> Option<[u8; 3]> {
|
||||
Some(match name {
|
||||
"Steel" => [158, 164, 172],
|
||||
"Stainless Steel" => [186, 191, 198],
|
||||
"Aluminum" => [204, 208, 214],
|
||||
"Brass" => [208, 172, 88],
|
||||
"Copper" => [204, 122, 80],
|
||||
"Titanium" => [150, 148, 158],
|
||||
"Cast Iron" => [104, 104, 110],
|
||||
"ABS Plastic" => [222, 222, 216],
|
||||
"PLA" => [110, 160, 222],
|
||||
"Nylon" => [236, 230, 214],
|
||||
"Polycarbonate" => [196, 216, 232],
|
||||
"Oak" => [190, 146, 92],
|
||||
"Glass" => [170, 208, 218],
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn material_density(name: &str) -> Option<f64> {
|
||||
MATERIALS.iter().find(|(n, _)| n.eq_ignore_ascii_case(name.trim())).map(|(_, d)| *d)
|
||||
}
|
||||
@@ -219,6 +219,9 @@ fn rename_body(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(m) = d.materials.remove(&old) {
|
||||
d.materials.insert(name.to_string(), m);
|
||||
}
|
||||
if let Some(c) = d.appearances.remove(&old) {
|
||||
d.appearances.insert(name.to_string(), c);
|
||||
}
|
||||
if let Some(c) = d.body_components.remove(&old) {
|
||||
d.body_components.insert(name.to_string(), c);
|
||||
}
|
||||
|
||||
@@ -162,9 +162,10 @@ fn export_to(s: &Session, path: &str, format: Format, bodies: &[String]) -> Resu
|
||||
let name = std::path::Path::new(path).file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| s.doc.name.clone());
|
||||
// A design with components exports as a STEP assembly; otherwise bodies as placed.
|
||||
let bytes = if format == Format::Step && bodies.is_empty() && !s.doc.occurrences.is_empty() {
|
||||
solvecraft_io::step_assembly(&s.doc, &s.model.state(), &name)?
|
||||
solvecraft_io::step_assembly(&s.doc, &s.doc.painted(&s.model.state()), &name)?
|
||||
} else {
|
||||
solvecraft_io::export(&s.world_state(), bodies, format, &name)?
|
||||
// Bodies carry the colour they are shown in (appearance, material or imported).
|
||||
solvecraft_io::export(&s.doc.painted(&s.world_state()), bodies, format, &name)?
|
||||
};
|
||||
std::fs::write(path, &bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
Ok(json!({"path": path, "bytes": bytes.len(), "format": format!("{format:?}")}))
|
||||
|
||||
@@ -23,6 +23,10 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.at("SOLID", "MODIFY")
|
||||
.icon("material")
|
||||
.params("bodies: [names]; material: name (Steel, Aluminum, ABS Plastic, …; `material.list`)"),
|
||||
CommandSpec::new("AppearanceCommand", "Appearance", appearance)
|
||||
.at("SOLID", "MODIFY")
|
||||
.icon("appearance")
|
||||
.params("bodies: [names]; color: \"#rrggbb\" or [r, g, b] (0–255), or null to follow the material"),
|
||||
CommandSpec::new("material.list", "List Materials", material_list).noundo(),
|
||||
CommandSpec::new("engine.commands", "List Commands", commands).noundo(),
|
||||
];
|
||||
@@ -271,6 +275,41 @@ fn physical_material(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"bodies": bodies, "material": canonical}))
|
||||
}
|
||||
|
||||
/// A colour parameter: `"#rrggbb"` or `[r, g, b]` (0–255).
|
||||
fn color_param(v: &Value) -> Option<[u8; 3]> {
|
||||
if let Some(t) = v.as_str() {
|
||||
let h = t.trim().trim_start_matches('#');
|
||||
if h.len() != 6 || !h.is_ascii() {
|
||||
return None;
|
||||
}
|
||||
let byte = |i: usize| h.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok());
|
||||
return Some([byte(0)?, byte(2)?, byte(4)?]);
|
||||
}
|
||||
let a = v.as_array().filter(|a| a.len() == 3)?;
|
||||
let c = |i: usize| a.get(i).and_then(Value::as_f64).filter(|x| x.is_finite() && (0.0..=255.0).contains(x)).map(|x| x.round() as u8);
|
||||
Some([c(0)?, c(1)?, c(2)?])
|
||||
}
|
||||
|
||||
fn appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "AppearanceCommand";
|
||||
let bodies = string_list(p, "bodies");
|
||||
let st = s.model.state();
|
||||
if bodies.is_empty() || bodies.iter().any(|b| st.body(b).is_none()) {
|
||||
return Err(bad(cmd, "`bodies` must list existing bodies"));
|
||||
}
|
||||
let color = match p.get("color") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(color_param(v).ok_or_else(|| bad(cmd, "`color` must be \"#rrggbb\" or [r, g, b] with values 0–255"))?),
|
||||
};
|
||||
for b in &bodies {
|
||||
match color {
|
||||
Some(c) => s.doc_mut().appearances.insert(b.clone(), c),
|
||||
None => s.doc_mut().appearances.remove(b),
|
||||
};
|
||||
}
|
||||
Ok(json!({"bodies": bodies, "color": color.map(|c| format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]))}))
|
||||
}
|
||||
|
||||
fn material_list(_s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
Ok(json!({"materials": solvecraft_doc::MATERIALS.iter().map(|(n, d)| json!({"name": n, "density_g_cm3": d})).collect::<Vec<_>>()}))
|
||||
}
|
||||
@@ -951,6 +951,42 @@ fn sample_plate_step_round_trip() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bodies export in the colour they are shown in: a material's look, an appearance over it,
|
||||
/// none for the default; and colours read from a STEP file survive the next export.
|
||||
#[test]
|
||||
fn material_and_appearance_colours_export_to_step() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "PrimitiveBox", json!({"length": 10, "width": 10, "height": 10, "body_name": "BrassBox"}));
|
||||
run(&mut s, "PrimitiveBox", json!({"corner": [20, 0, 0], "length": 10, "width": 10, "height": 10, "body_name": "RedAbs"}));
|
||||
run(&mut s, "PrimitiveBox", json!({"corner": [40, 0, 0], "length": 10, "width": 10, "height": 10, "body_name": "Plain"}));
|
||||
run(&mut s, "PhysicalMaterialCommand", json!({"bodies": ["BrassBox"], "material": "Brass"}));
|
||||
run(&mut s, "PhysicalMaterialCommand", json!({"bodies": ["RedAbs"], "material": "ABS Plastic"}));
|
||||
run(&mut s, "AppearanceCommand", json!({"bodies": ["RedAbs"], "color": "#d01c1c"}));
|
||||
assert!(s.execute("AppearanceCommand", &json!({"bodies": ["RedAbs"], "color": "#12"})).is_err());
|
||||
let rgb = |c: [u8; 3]| c.map(|x| x as f32 / 255.0);
|
||||
let want =
|
||||
[("BrassBox", Some(rgb(solvecraft_doc::material_color("Brass").unwrap()))), ("RedAbs", Some(rgb([0xd0, 0x1c, 0x1c]))), ("Plain", None)];
|
||||
let same = |a: Option<[f32; 3]>, b: Option<[f32; 3]>| match (a, b) {
|
||||
(Some(a), Some(b)) => a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3),
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
};
|
||||
let check = |imp: &solvecraft_kernel::StepImport| {
|
||||
for (name, c) in want {
|
||||
let b = imp.bodies.iter().find(|b| b.name == name).unwrap_or_else(|| panic!("no body {name}"));
|
||||
assert!(same(b.body.color(), c), "{name}: {:?} vs {c:?}", b.body.color());
|
||||
}
|
||||
};
|
||||
check(&step_round_trip(&mut s, "colours"));
|
||||
// Open the export and export again: the file's colours are kept.
|
||||
let p = std::env::temp_dir().join(format!("solvecraft-colours-{}.step", std::process::id()));
|
||||
run(&mut s, "ExportCommand", json!({"path": p.to_string_lossy()}));
|
||||
let mut s2 = Session::default();
|
||||
run(&mut s2, "doc.open", json!({"path": p.to_string_lossy()}));
|
||||
let _ = std::fs::remove_file(&p);
|
||||
check(&step_round_trip(&mut s2, "colours2"));
|
||||
}
|
||||
|
||||
/// Components export as a STEP assembly: products, occurrences, placements.
|
||||
#[test]
|
||||
fn components_export_as_step_assembly() {
|
||||
|
||||
@@ -262,22 +262,7 @@ impl Tokens {
|
||||
|
||||
/// How a physical material looks (the default appearance follows the material).
|
||||
pub fn material_color(name: &str) -> Option<Color32> {
|
||||
Some(match name {
|
||||
"Steel" => Color32::from_rgb(158, 164, 172),
|
||||
"Stainless Steel" => Color32::from_rgb(186, 191, 198),
|
||||
"Aluminum" => Color32::from_rgb(204, 208, 214),
|
||||
"Brass" => Color32::from_rgb(208, 172, 88),
|
||||
"Copper" => Color32::from_rgb(204, 122, 80),
|
||||
"Titanium" => Color32::from_rgb(150, 148, 158),
|
||||
"Cast Iron" => Color32::from_rgb(104, 104, 110),
|
||||
"ABS Plastic" => Color32::from_rgb(222, 222, 216),
|
||||
"PLA" => Color32::from_rgb(110, 160, 222),
|
||||
"Nylon" => Color32::from_rgb(236, 230, 214),
|
||||
"Polycarbonate" => Color32::from_rgb(196, 216, 232),
|
||||
"Oak" => Color32::from_rgb(190, 146, 92),
|
||||
"Glass" => Color32::from_rgb(170, 208, 218),
|
||||
_ => return None,
|
||||
})
|
||||
solvecraft_engine::doc::material_color(name).map(|[r, g, b]| Color32::from_rgb(r, g, b))
|
||||
}
|
||||
|
||||
/// Switch themes (the visuals follow on the next [`apply`]).
|
||||
|
||||
@@ -215,7 +215,7 @@ fn build_scene(app: &SolveApp) -> GpuScene {
|
||||
}
|
||||
// With a component active, bodies outside it are drawn faded.
|
||||
let faded = s.active_component != 0 && !s.doc.component_within(s.doc.body_component(&b.name, b.feature), s.active_component);
|
||||
let base = s.doc.materials.get(&b.name).and_then(|m| crate::theme::material_color(m)).unwrap_or(tk.body);
|
||||
let base = body_color(&s.doc, &b.name, &b.body).unwrap_or(tk.body);
|
||||
let col = if faded { c4(base.gamma_multiply(0.35)) } else { c4(base) };
|
||||
let m = b.mesh();
|
||||
let (shaded, edges) = match app.ui.visual_style {
|
||||
@@ -930,9 +930,16 @@ fn build_highlight(app: &SolveApp) -> GpuScene {
|
||||
sc
|
||||
}
|
||||
|
||||
/// A body's display colour (its material's, else the theme's) as RGB.
|
||||
/// A body's display colour (appearance, material or imported colour), if it has one.
|
||||
fn body_color(doc: &solvecraft_engine::doc::Document, name: &str, body: &solvecraft_engine::kernel::Body) -> Option<Color32> {
|
||||
let to8 = |x: f32| (x.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
doc.body_color(name, body).map(|[r, g, b]| Color32::from_rgb(to8(r), to8(g), to8(b)))
|
||||
}
|
||||
|
||||
/// A body's display colour (else the theme's) as RGB.
|
||||
fn body_rgb(app: &SolveApp, name: &str) -> (u8, u8, u8) {
|
||||
let c = app.session.doc.materials.get(name).and_then(|m| crate::theme::material_color(m)).unwrap_or(Tokens::get().body);
|
||||
let st = app.session.model.state();
|
||||
let c = st.body(name).and_then(|b| body_color(&app.session.doc, name, &b.body)).unwrap_or(Tokens::get().body);
|
||||
(c.r(), c.g(), c.b())
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user