diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 0f16a9726..bc0b3616c 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -284,6 +284,8 @@ Editable drawing code, native projects and shipped exports are collected under ` | assets/icons/ui/design/svg/model/circle_tt.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/circle_ttt.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/coil.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/model/colored_components.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/model/colored_components_off.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/combine.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/component.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/compute.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | diff --git a/assets/icons/ui/design/palette.toml b/assets/icons/ui/design/palette.toml index aaed95b24..a8f95ce1a 100644 --- a/assets/icons/ui/design/palette.toml +++ b/assets/icons/ui/design/palette.toml @@ -48,6 +48,38 @@ source = "#236ead" light = "#236ead" dark = "#2976b8" +# Simultaneous component colours for inspection icons; existing workspace ramps stay unchanged. + +[roles.component-orange-1] +source = "#f1d2af" +light = "#f1d2af" +dark = "#ba8f6a" + +[roles.component-orange-2] +source = "#c06f00" +light = "#c06f00" +dark = "#b86f04" + +[roles.component-orange-3] +source = "#a45000" +light = "#a45000" +dark = "#95682d" + +[roles.component-yellow-1] +source = "#e5d99b" +light = "#e5d99b" +dark = "#a9985f" + +[roles.component-yellow-2] +source = "#a28200" +light = "#a28200" +dark = "#9a8100" + +[roles.component-yellow-3] +source = "#826700" +light = "#826700" +dark = "#857100" + [strokes] # on the 64 grid geometry = 2.55 action = 4.25 diff --git a/assets/icons/ui/design/requested_icons.txt b/assets/icons/ui/design/requested_icons.txt index 9cafce11d..60cbb03ef 100644 --- a/assets/icons/ui/design/requested_icons.txt +++ b/assets/icons/ui/design/requested_icons.txt @@ -57,6 +57,8 @@ circle_tt false circle_ttt false close false coil false +colored_components false +colored_components_off false combine false compare false component false diff --git a/assets/icons/ui/design/svg/model/colored_components.svg b/assets/icons/ui/design/svg/model/colored_components.svg new file mode 100644 index 000000000..8de0b38dc --- /dev/null +++ b/assets/icons/ui/design/svg/model/colored_components.svg @@ -0,0 +1,21 @@ + + Colored components + + + + + + + + + + + + + + + + + + + diff --git a/assets/icons/ui/design/svg/model/colored_components_off.svg b/assets/icons/ui/design/svg/model/colored_components_off.svg new file mode 100644 index 000000000..01565a01b --- /dev/null +++ b/assets/icons/ui/design/svg/model/colored_components_off.svg @@ -0,0 +1,21 @@ + + Disable component colors + + + + + + + + + + + + + + + + + + + diff --git a/assets/locales/en.json b/assets/locales/en.json index 3a1c035d9..9a589460e 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -692,6 +692,7 @@ "cmd.component_capture_position": "Capture Position", "cmd.component_copies": "Find Identical Copies", "cmd.component_create": "New Component", + "cmd.component_cycle_color": "Cycle Component Color", "cmd.component_delete": "Delete Component", "cmd.component_extract": "Extract to File", "cmd.component_from_bodies": "Create Components from Bodies", @@ -776,6 +777,8 @@ "cmd.inspect_accessibility": "Accessibility Analysis", "cmd.inspect_center_of_mass": "Center of Mass", "cmd.inspect_clearance": "Clearance", + "cmd.inspect_colored_components": "Enable Component Colors", + "cmd.inspect_colored_components_disable": "Disable Component Colors", "cmd.inspect_compare": "Compare Bodies", "cmd.inspect_continuity": "Continuity Analysis", "cmd.inspect_curvature_comb": "Curvature Comb Analysis", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 09541fc16..9c305556e 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -692,6 +692,7 @@ "cmd.component_capture_position": "位置をキャプチャ", "cmd.component_copies": "同一のコピーを検索", "cmd.component_create": "新規コンポーネント", + "cmd.component_cycle_color": "コンポーネントの色を順に変更", "cmd.component_delete": "コンポーネントを削除", "cmd.component_extract": "ファイルに抽出", "cmd.component_from_bodies": "ボディからコンポーネントを作成", @@ -776,6 +777,8 @@ "cmd.inspect_accessibility": "アクセシビリティ解析", "cmd.inspect_center_of_mass": "重心", "cmd.inspect_clearance": "クリアランス", + "cmd.inspect_colored_components": "コンポーネントの色分けを有効化", + "cmd.inspect_colored_components_disable": "コンポーネントの色分けを無効化", "cmd.inspect_compare": "ボディを比較", "cmd.inspect_continuity": "連続性解析", "cmd.inspect_curvature_comb": "曲率コーム解析", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index b25e1957c..72aaa9115 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -692,6 +692,7 @@ "cmd.component_capture_position": "捕获位置", "cmd.component_copies": "查找相同副本", "cmd.component_create": "新建组件", + "cmd.component_cycle_color": "循环切换组件颜色", "cmd.component_delete": "删除组件", "cmd.component_extract": "提取到文件", "cmd.component_from_bodies": "由实体创建组件", @@ -776,6 +777,8 @@ "cmd.inspect_accessibility": "可达性分析", "cmd.inspect_center_of_mass": "质心", "cmd.inspect_clearance": "间隙", + "cmd.inspect_colored_components": "启用组件颜色", + "cmd.inspect_colored_components_disable": "禁用组件颜色", "cmd.inspect_compare": "比较实体", "cmd.inspect_continuity": "连续性分析", "cmd.inspect_curvature_comb": "曲率梳分析", diff --git a/crates/doc/src/component_color.rs b/crates/doc/src/component_color.rs new file mode 100644 index 000000000..9cd7685f2 --- /dev/null +++ b/crates/doc/src/component_color.rs @@ -0,0 +1,162 @@ +//! Identification colours, independent of materials and appearances. + +use crate::Document; + +/// Automatic colours select this palette in creation order; cycling uses the same order. +/// Colors are generated by picking colors on a color wheel, with 0.9 brightness and 0.8 saturation. +/// First pass is 3 colors, 120 huedegrees from each other. Second pass starts with 60 degrees from +/// the first one. Then third and fourth pass fill 60 and 30 degrees gaps between already generated +/// colors of the palette. +pub const PALETTE: [[u8; 3]; 24] = [ + [230, 161, 92], + [92, 230, 161], + [161, 92, 230], + [161, 230, 92], + [92, 161, 230], + [230, 92, 161], + [230, 230, 92], + [92, 230, 92], + [92, 230, 230], + [92, 92, 230], + [230, 92, 230], + [230, 92, 92], + [230, 195, 92], + [195, 230, 92], + [126, 230, 92], + [92, 230, 126], + [92, 230, 195], + [92, 195, 230], + [92, 126, 230], + [126, 92, 230], + [195, 92, 230], + [230, 92, 195], + [230, 92, 126], + [230, 126, 92], +]; + +/// Select a colour in creation order, wrapping at the end of the palette. +pub fn automatic_color(index: u64) -> [u8; 3] { + PALETTE.get((index % PALETTE.len() as u64) as usize).copied().unwrap_or([230, 161, 92]) +} + +pub fn next_color(color: [u8; 3]) -> [u8; 3] { + let index = PALETTE.iter().position(|c| *c == color).map_or(0, |i| (i + 1) % PALETTE.len()); + PALETTE.get(index).copied().unwrap_or([230, 161, 92]) +} + +impl Document { + pub fn component_identification_color(&self, id: u64) -> [u8; 3] { + self.components.iter().enumerate().find(|(_, c)| c.id == id).map_or_else( + || automatic_color(0), + |(position, c)| c.identification_color.unwrap_or_else(|| automatic_color(c.identification_color_index.unwrap_or(position as u64))), + ) + } + + /// Fill older records in stored order and repair stale counters without changing saved indices. + pub(crate) fn normalise_component_color_indices(&mut self) -> crate::Result<()> { + let mut next = self.next_component_color_index; + for component in &self.components { + if let Some(index) = component.identification_color_index { + next = next.max(index.checked_add(1).ok_or_else(|| crate::DocError::Invalid("component colour sequence exhausted".into()))?); + } + } + for component in &mut self.components { + if component.identification_color_index.is_none() { + let following = next.checked_add(1).ok_or_else(|| crate::DocError::Invalid("component colour sequence exhausted".into()))?; + component.identification_color_index = Some(next); + next = following; + } + } + self.next_component_color_index = next; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn old_components_default_to_stable_colors_and_overrides_round_trip() { + let mut doc = Document::default(); + let id = doc.add_component(Some("Part"), 0).unwrap(); + let automatic = doc.component_identification_color(id); + let mut legacy: serde_json::Value = serde_json::from_str(&doc.to_json()).unwrap(); + legacy["components"][0].as_object_mut().unwrap().remove("identification_color"); + legacy["format_pending"].as_array_mut().unwrap().retain(|name| name != "component-identification-colors"); + let restored = Document::from_json(&legacy.to_string()).unwrap(); + assert_eq!(restored.component_identification_color(id), automatic); + assert_eq!(restored.components[0].identification_color, None); + let override_color = next_color(automatic); + assert_ne!(override_color, automatic); + doc.components[0].identification_color = Some(override_color); + doc.components[0].name = "Renamed".into(); + let saved = Document::from_json(&doc.to_json()).unwrap(); + assert_eq!(saved.component_identification_color(id), override_color); + assert_eq!(saved.components[0].identification_color, Some(override_color)); + } + + #[test] + fn creation_order_wraps_and_survives_deletion_reordering_and_reopening() { + let mut doc = Document::default(); + let mut ids = Vec::new(); + for index in 0..25 { + // IDs also belong to occurrences, so their numeric values are not colour indices. + let id = doc.add_component(None, 0).unwrap(); + assert_eq!(doc.component_identification_color(id), PALETTE[index % PALETTE.len()]); + ids.push(id); + } + let retained = ids[1]; + doc.components.retain(|c| c.id != ids[0]); + doc.occurrences.retain(|o| o.component != ids[0]); + doc.components.reverse(); + let mut restored = Document::from_json(&doc.to_json()).unwrap(); + assert_eq!(restored.component_identification_color(retained), PALETTE[1]); + let next = restored.add_component(None, 0).unwrap(); + assert_eq!(restored.component_identification_color(next), PALETTE[1]); + assert_eq!(restored.next_component_color_index, 26); + } + + #[test] + fn legacy_order_and_overrides_are_preserved_and_stale_counters_repaired() { + let mut doc = Document::default(); + let first = doc.add_component(None, 0).unwrap(); + let second = doc.add_component(None, first).unwrap(); + doc.components[1].identification_color = Some([1, 2, 3]); + let mut json: serde_json::Value = serde_json::from_str(&doc.to_json()).unwrap(); + json.as_object_mut().unwrap().remove("next_component_color_index"); + for component in json["components"].as_array_mut().unwrap() { + component.as_object_mut().unwrap().remove("identification_color_index"); + } + json["format_pending"].as_array_mut().unwrap().retain(|name| name != "sequential-component-colors"); + let mut restored = Document::from_json(&json.to_string()).unwrap(); + assert_eq!(restored.components[0].identification_color_index, Some(0)); + assert_eq!(restored.components[1].identification_color_index, Some(1)); + assert_eq!(restored.component_identification_color(first), PALETTE[0]); + assert_eq!(restored.component_identification_color(second), [1, 2, 3]); + let third = restored.add_component(None, 0).unwrap(); + assert_eq!(restored.component_identification_color(third), PALETTE[2]); + restored.next_component_color_index = 0; + let mut repaired = Document::from_json(&restored.to_json()).unwrap(); + let fourth = repaired.add_component(None, 0).unwrap(); + assert_eq!(repaired.component_identification_color(fourth), PALETTE[3]); + let mut hostile: serde_json::Value = serde_json::from_str(&repaired.to_json()).unwrap(); + hostile["components"][0]["identification_color_index"] = u64::MAX.into(); + assert!(Document::from_json(&hostile.to_string()).is_err()); + } + + #[test] + fn cycling_visits_every_palette_color_and_wraps() { + let original = automatic_color(123); + let mut seen = std::collections::BTreeSet::new(); + let mut color = original; + for _ in 0..PALETTE.len() { + assert!(seen.insert(color)); + color = next_color(color); + } + assert_eq!(color, original); + assert_eq!(automatic_color(0), PALETTE[0]); + assert_eq!(automatic_color(1), PALETTE[1]); + assert_eq!(automatic_color(24), PALETTE[0]); + } +} diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 17f44b0d2..c4ee4039b 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -1957,6 +1957,12 @@ pub struct SketchPoints { #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Component { pub id: u64, + /// Optional identification colour, separate from normal appearances. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub identification_color: Option<[u8; 3]>, + /// Creation sequence used to select an automatic identification colour. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub identification_color_index: Option, pub name: String, /// Parent component (0 = the root). #[serde(default)] @@ -2536,6 +2542,9 @@ pub struct Document { /// Components below the root, as a tree (by parent). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub components: Vec, + /// Next automatic colour sequence number; deletions never rewind it. + #[serde(default)] + pub next_component_color_index: u64, /// Placements of components in their parents (each non-root component has at least one). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub occurrences: Vec, @@ -2800,6 +2809,7 @@ impl Document { next_id: 1, reserved_body_names: Default::default(), components: Vec::new(), + next_component_color_index: 0, occurrences: Vec::new(), assembly: Default::default(), sheet: Default::default(), @@ -3114,6 +3124,9 @@ impl Document { if self.components.len() >= 10_000 { return Err(DocError::Invalid("too many components".into())); } + self.normalise_component_color_indices()?; + let color_index = self.next_component_color_index; + let next_color_index = color_index.checked_add(1).ok_or_else(|| DocError::Invalid("component colour sequence exhausted".into()))?; let id = self.next_id.max(1); self.next_id = id.checked_add(1).ok_or_else(|| DocError::Invalid("too many items in the design".into()))?; let name = match name.map(str::trim) { @@ -3126,7 +3139,8 @@ impl Document { format!("Component{k}") } }; - self.components.push(Component { id, name, parent, ..Default::default() }); + self.components.push(Component { id, name, parent, identification_color_index: Some(color_index), ..Default::default() }); + self.next_component_color_index = next_color_index; let occurrence = self.add_occurrence(id, parent, crate::IDENTITY)?; // The design's first part is grounded, so joints and drags have something fixed to work // from (#2804); later parts and copies start free. Only creation decides this: opening a diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs index fce88e078..ff4005e1d 100644 --- a/crates/doc/src/format.rs +++ b/crates/doc/src/format.rs @@ -1144,6 +1144,7 @@ fn rigid(m: &crate::Mat) -> bool { /// Feature input names and component occurrences, which format 1 files may predate. fn normalise(d: &mut Document) -> Result<()> { + d.normalise_component_color_indices()?; d.name_all_feature_inputs(); let missing: Vec<(u64, u64)> = d.components.iter().filter(|c| !d.occurrences.iter().any(|o| o.component == c.id)).map(|c| (c.id, c.parent)).collect(); diff --git a/crates/doc/src/format/pending/component-identification-colors.rs b/crates/doc/src/format/pending/component-identification-colors.rs new file mode 100644 index 000000000..aab156984 --- /dev/null +++ b/crates/doc/src/format/pending/component-identification-colors.rs @@ -0,0 +1,4 @@ +//! Components save an optional `identification_color_index` and the document saves +//! `next_component_color_index`. Automatic colours follow creation order and wrap through the +//! palette; deletions do not rewind the sequence. Older records receive indices in stored order +//! during normalization (not the order they were originally created), preserving explicit RGB overrides. diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 95ad72841..586e05d6d 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -15,6 +15,7 @@ pub use body_transfer::{valid_transfer_matrix, validate_body_transfer}; pub mod canvas; mod clipboard; pub use clipboard::{clone_expression, remap_topology}; +pub mod component_color; mod component_removal; pub use component_removal::RemovedTree; pub mod config; diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index e14ec5c49..0b3f2d1a9 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -28,6 +28,9 @@ mod transfer; mod occurrence_tests; pub static COMMANDS: &[CommandSpec] = &[ + CommandSpec::new("component.cycle_color", "Cycle Component Color", cycle_color) + .icon("colored_components").doc_only() + .params("component: id or name; saves the next identification colour and enables Component Colors; shared by every instance, separate from appearances"), CommandSpec::new("component.create", "New Component", new_component) .at("SOLID", "ASSEMBLE") .icon("component") @@ -565,3 +568,13 @@ pub fn to_active_frame(s: &Session, kind: &mut FeatureKind) { kind.transform_geometry(&inv); } } + +fn cycle_color(s: &mut Session, p: &Value) -> Result { + let cmd = "component.cycle_color"; + let id = component(s, p, "component", cmd)?; + let next = solidcraft_doc::component_color::next_color(s.doc.component_identification_color(id)); + let c = s.doc_mut().components.iter_mut().find(|c| c.id == id).ok_or_else(|| bad(cmd, "choose a component below the design root"))?; + c.identification_color = Some(next); + s.colored_components = Some(()); + Ok(json!({"component": id, "color": next})) +} diff --git a/crates/engine/src/cmd/component_clone.rs b/crates/engine/src/cmd/component_clone.rs index cd0eb0c8f..f69c6deb7 100644 --- a/crates/engine/src/cmd/component_clone.rs +++ b/crates/engine/src/cmd/component_clone.rs @@ -257,6 +257,7 @@ pub(super) fn paste( if let Some(added) = scratch.doc_mut().components.iter_mut().find(|x| x.id == new) { added.metadata = c.metadata.clone(); added.properties = c.properties.clone(); + added.identification_color = c.identification_color; } components.insert(*old, new); if *old != component { diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs index 60b404a5b..bf9da3bd7 100644 --- a/crates/engine/src/cmd/inspect.rs +++ b/crates/engine/src/cmd/inspect.rs @@ -8,6 +8,9 @@ use crate::params::{bad, bool_, str_, string_list}; use crate::{EngineError, Result, Session}; pub static COMMANDS: &[CommandSpec] = &[ + CommandSpec::new("inspect.colored_components", "Enable Component Colors", colored_components) + .at("SOLID", "INSPECT").icon("colored_components").noundo() + .params("enabled?: bool (omitted: toggle); temporary component colours, without changing appearances"), CommandSpec::new("inspect.measure", "Measure", measure) .at("SOLID", "INSPECT") .icon("measure") @@ -724,3 +727,16 @@ fn material_list(s: &mut Session, _p: &Value) -> Result { .collect::>>()?; Ok(json!({"materials": built_in.chain(user).collect::>()})) } + +fn colored_components(s: &mut Session, p: &Value) -> Result { + if p.get("enabled").is_some_and(|v| !v.is_boolean()) { + return Err(bad("inspect.colored_components", "enabled must be a boolean")); + } + let enabled = bool_(p, "enabled").unwrap_or(s.colored_components.is_none()); + if enabled && s.colored_components.is_none() { + s.colored_components = Some(()); + } else if !enabled { + s.colored_components = None; + } + Ok(json!({"enabled": enabled})) +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 316aa219f..aefd20d6e 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -215,12 +215,16 @@ impl CommandSpec { } pub fn info(&self, s: &Session) -> CommandInfo { let e = (self.enabled)(s); + let (label, icon) = match self.id { + "inspect.colored_components" if s.colored_components.is_some() => ("Disable Component Colors", "colored_components_off"), + _ => (self.label, self.icon), + }; CommandInfo { id: self.id, - label: self.label, + label, tab: self.tab, panel: self.panel, - icon: self.icon, + icon, shortcut: self.shortcut, params: self.params, enabled: e.is_ok(), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 10a60850d..2b40b3d1c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -327,6 +327,8 @@ pub struct Session { pub section: Option<(Vec3, Vec3)>, /// Whether the section's cut faces are hatched (`inspect.section`'s `hatch`; on by default). pub section_hatch: bool, + /// Component identification colours are enabled when present; view state only. + pub colored_components: Option<()>, /// Surface analysis shading the model (zebra, draft, curvature map). pub analysis: Option, /// The seams `inspect.continuity` last measured, for the viewport to shade. View state: not @@ -491,6 +493,7 @@ impl Session { sketch_clipboard: None, section: None, section_hatch: true, + colored_components: None, analysis: None, continuity: Vec::new(), checkpoints: Vec::new(), @@ -1152,6 +1155,7 @@ impl Session { sketch_clipboard: self.sketch_clipboard.clone(), section: None, section_hatch: true, + colored_components: None, analysis: None, continuity: Vec::new(), checkpoints: Vec::new(), @@ -1458,6 +1462,7 @@ fn same_but_features(a: &Document, b: &Document) -> bool { browser_order, named_views, visibility, + next_component_color_index, } = a; *render == b.render && *format == b.format @@ -1491,4 +1496,5 @@ fn same_but_features(a: &Document, b: &Document) -> bool { && *browser_order == b.browser_order && *named_views == b.named_views && *visibility == b.visibility + && *next_component_color_index == b.next_component_color_index } diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index e4baa83c5..529e2e48f 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -348,6 +348,12 @@ pub fn sketch_point_visible(sk: &Sketch, i: usize) -> bool { sk.points.get(i).is_some_and(|p| SketchPointVisibility::new(sk).takes(p)) } +/// Stable identification colour shared by every body of a component. +pub fn component_color(s: &Session, component: u64) -> Option<[u8; 3]> { + s.colored_components?; + Some(s.doc.component_identification_color(component)) +} + /// The scene for a headless render, cut by the session's section. pub fn scene(s: &Session, cam: &Camera) -> Scene { scene_with_section(s, cam, s.section) @@ -520,8 +526,14 @@ fn build_scene( // The body's appearance (or imported colour) and faces with looks of their own, as in // the viewport. let to8 = |x: f32| (x.clamp(0.0, 1.0) * 255.0).round() as u8; - let color = if selected { p.body_selected } else { s.doc.body_color(body).map_or(p.body, |[r, g, b]| Rgb(to8(r), to8(g), to8(b))) }; - let face_colors = if selected { + let color = if selected { + p.body_selected + } else if let Some([r, g, b]) = component_color(s, body.component) { + Rgb(r, g, b) + } else { + s.doc.body_color(body).map_or(p.body, |[r, g, b]| Rgb(to8(r), to8(g), to8(b))) + }; + let face_colors = if selected || s.colored_components.is_some() { Vec::new() } else { s.doc.face_colors(body).into_iter().map(|(f, l)| (f as u32, Rgb(l.color[0], l.color[1], l.color[2]))).collect() diff --git a/crates/engine/src/view_display_tests.rs b/crates/engine/src/view_display_tests.rs index 06f9faf7d..118386b05 100644 --- a/crates/engine/src/view_display_tests.rs +++ b/crates/engine/src/view_display_tests.rs @@ -189,3 +189,84 @@ fn scene_sampler_uses_exact_active_occurrence_plane_and_preserves_other_scene_co let hidden = scene_with_sketch_sampler(&s, &cam, |_, _, _| panic!("hidden sketch sampled")); assert!(hidden.lines.iter().all(|line| !line.on_top)); } + +#[test] +fn colored_components_toggle_is_stable_and_does_not_change_the_design() { + let mut s = Session::default(); + let first_id = s.doc_mut().add_component(Some("First"), 0).unwrap(); + let second_id = s.doc_mut().add_component(Some("Second"), 0).unwrap(); + let before = serde_json::to_value(&s.doc).unwrap(); + assert_eq!(component_color(&s, first_id), None); + assert_eq!(s.execute("inspect.colored_components", &json!({})).unwrap()["enabled"], true); + s.colored_components = Some(()); + let first = component_color(&s, first_id); + assert!(first.is_some()); + assert_ne!(first, component_color(&s, second_id)); + s.execute("inspect.colored_components", &json!({"enabled": true})).unwrap(); + assert_eq!(component_color(&s, first_id), first); + assert!(s.execute("inspect.colored_components", &json!({"enabled": "yes"})).is_err()); + assert_eq!(component_color(&s, first_id), first); + assert_eq!(s.execute("inspect.colored_components", &json!({})).unwrap()["enabled"], false); + assert_eq!(component_color(&s, first_id), None); + assert_eq!(serde_json::to_value(&s.doc).unwrap(), before); +} + +#[test] +fn colored_components_override_appearances_and_restore_them() { + let mut s = Session::default(); + for (name, x) in [("Left", 0), ("Right", 20)] { + s.execute("component.activate", &json!({"component": 0})).unwrap(); + s.execute("component.create", &json!({"name": name})).unwrap(); + s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0]})).unwrap(); + } + s.selection.clear(); + let cam = Camera::default(); + let original = scene(&s, &cam); + s.execute("inspect.colored_components", &json!({"enabled": true})).unwrap(); + s.colored_components = Some(()); + let colored = scene(&s, &cam); + assert_eq!(colored.meshes.len(), 2); + assert_ne!(colored.meshes[0].color, colored.meshes[1].color); + for (body, mesh) in s.world_state().bodies.iter().zip(&colored.meshes) { + let [r, g, b] = component_color(&s, body.component).unwrap(); + assert_eq!(mesh.color, Rgb(r, g, b)); + assert!(mesh.face_colors.is_empty()); + } + s.execute("inspect.colored_components", &json!({"enabled": false})).unwrap(); + let restored = scene(&s, &cam); + for (a, b) in original.meshes.iter().zip(restored.meshes) { + assert_eq!(a.color, b.color); + assert_eq!(a.face_colors, b.face_colors); + } +} + +#[test] +fn cycling_component_color_is_saved_undoable_and_shared_by_instances() { + let mut s = Session::default(); + let component = s.execute("component.create", &json!({"name":"Part"})).unwrap()["component"].as_u64().unwrap(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":10})).unwrap(); + s.execute("occurrence.copy", &json!({"component":component,"translate":[20,0,0]})).unwrap(); + let appearances = s.doc.appearances.clone(); + s.execute("inspect.colored_components", &json!({"enabled":true})).unwrap(); + let automatic = component_color(&s, component).unwrap(); + s.execute("inspect.colored_components", &json!({"enabled":false})).unwrap(); + s.execute("inspect.colored_components", &json!({"enabled":true})).unwrap(); + assert_eq!(component_color(&s, component), Some(automatic)); + let result = s.execute("component.cycle_color", &json!({"component":component})).unwrap(); + let custom = component_color(&s, component).unwrap(); + assert_ne!(custom, automatic); + assert_eq!(result["color"], json!(custom)); + assert_eq!(s.doc.appearances, appearances); + let loaded = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + assert_eq!(loaded.doc.component_identification_color(component), custom); + let copies: Vec<_> = s.world_state().bodies.iter().map(|b| b.component).collect(); + assert_eq!(copies, [component, component]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(component_color(&s, component), Some(automatic)); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(component_color(&s, component), Some(custom)); + s.execute("component.paste_new", &json!({"component":component,"translate":[40,0,0]})).unwrap(); + assert!(s.doc.components.iter().filter(|c| c.identification_color == Some(custom)).count() >= 2); + assert!(s.execute("component.cycle_color", &json!({"component":"missing"})).is_err()); + assert!(s.execute("component.cycle_color", &json!({"component":0})).is_err()); +} diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 96948454b..161e9e677 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -838,6 +838,9 @@ fn component_items(app: &SolveApp, id: u64) -> Vec { .with(if id == 0 { json!({ "bodies": names }) } else { json!({"component": id}) }) .on(id != 0 || !bodies.is_empty()), ); + if id != 0 { + v.push(cmd(app, "component.cycle_color", "Cycle Component Color").with(json!({"component": id}))); + } v.push(act("ui.properties", "Properties", "measure").with(json!({ "component": id }))); if doc.links.contains_key(&id) { v.push(act("ui.relinkSource", "Relink Source (All Instances)…", "update").with(json!({"component": id}))); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6c94e78c9..f15cb4918 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1047,6 +1047,10 @@ impl SolveApp { } return; } + if id == "inspect.colored_components" { + drop(self.run(id, serde_json::json!({}))); + return; + } if id == "material.properties.validate" { self.material_card_review = Some(material_card_review::ReviewWindow::default()); self.home.open = false; diff --git a/crates/ui-egui/src/menu_tests.rs b/crates/ui-egui/src/menu_tests.rs index f7bc90905..943294b1b 100644 --- a/crates/ui-egui/src/menu_tests.rs +++ b/crates/ui-egui/src/menu_tests.rs @@ -369,6 +369,24 @@ fn move_shortcut_respects_grounding_and_keeps_body_selection_as_a_body_move() { assert_eq!(dialog.inputs[0].items, vec![solidcraft_engine::Sel::Body { name: "Body1".into() }]); } +#[test] +fn component_and_occurrence_menus_cycle_shared_identification_color() { + let mut app = SolveApp::new(Session::default(), Services::default()); + let id = app.run("component.create", json!({"name":"Part"})).unwrap()["component"].as_u64().unwrap(); + let original = app.session.doc.component_identification_color(id); + assert!(app.session.colored_components.is_none()); + act(&mut app, &Target::Component { id }, "Cycle Component Color"); + let next = app.session.doc.component_identification_color(id); + assert_ne!(original, next); + assert!(app.session.colored_components.is_some()); + assert!(app.dialog.is_none()); + let occurrence = app.session.doc.occurrence_of(id).unwrap().id; + act(&mut app, &Target::Occurrence { path: vec![occurrence] }, "Cycle Component Color"); + assert_ne!(app.session.doc.component_identification_color(id), next); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc.component_identification_color(id), next); +} + #[test] fn pick_runs_an_item_of_the_open_menu() { let mut app = sample_app(); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 61de64a4d..0e627844a 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -1246,10 +1246,11 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { painter.rect_filled(br, t.radius_sm, t.hover); } if let Some(c) = shown.first().or(cmds.first()) { + let info = c.info(&app.session); icons::paint_icon( &painter, Rect::from_center_size(br.center() - vec2(0.0, 3.0), vec2(26.0, 26.0)), - c.icon, + info.icon, f32::from(t.icon.a()) / 255.0, ); } @@ -1309,12 +1310,12 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { } else if resp.hovered() && info.enabled { painter.rect_filled(whole, t.radius_sm, t.hover); } - let icon = if selected.id == "sketch.finish" { "finish" } else { selected.icon }; + let icon = if selected.id == "sketch.finish" { "finish" } else { info.icon }; let side = if finish { 30.0 } else { 26.0 }; let icon_rect = Rect::from_center_size(pos2(br.center().x, whole.top() + if labels { 16.0 } else { button_height / 2.0 }), vec2(side, side)); icons::paint_icon(&painter, icon_rect, icon, if info.enabled { 1.0 } else { 0.35 }); - let tr_label = app.tr_label(selected.label).to_string(); + let tr_label = app.tr_label(info.label).to_string(); resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled() && info.enabled, &tr_label)); if ribbon_tooltip(app, resp, selected, info.disabled_reason.as_deref()).clicked() && info.enabled { let id = selected.id; @@ -1347,7 +1348,8 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { sketch_menu_rows(app, ui, &variants, &mut menu, &mut toggle); }); } else if labels { - let label = app.tr_label(crate::workspace::ribbon_button_label(selected)); + let button_label = crate::workspace::ribbon_button_label(selected); + let label = app.tr_label(if button_label == selected.label { info.label } else { button_label }); let color = if info.enabled { t.text } else { t.text_dim }; let galley = ribbon_button_galley(&painter, label, whole.width() - BUTTON_LABEL_PADDING, color); painter.galley(pos2(whole.center().x, whole.top() + 32.0), galley, t.text); @@ -1572,8 +1574,8 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { let response = crate::ui_kit::command_menu_button( ui, c.id, - c.label, - c.icon, + info.label, + info.icon, &crate::keymap::display_for(app, c.id).unwrap_or_default(), info.enabled, ); @@ -1598,7 +1600,7 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { let leaves = |p: egui::Pos2| !r.contains(p) || over_popup(p); if let (Some(d), Some(p)) = (egui::DragAndDrop::payload::(ui.ctx()), pointer) { let removing = !d.from_menu && leaves(p); - drag_ghost(ui.ctx(), d.id, p, removing); + drag_ghost(app, ui.ctx(), d.id, p, removing); if ui.input(|i| i.pointer.any_released()) && drop.is_none() { egui::DragAndDrop::clear_payload(ui.ctx()); if removing { @@ -1676,7 +1678,7 @@ const CONSTRAINT_GRID_WIDTH: f32 = 82.0; fn ribbon_tooltip(app: &SolveApp, response: egui::Response, command: &solidcraft_engine::CommandSpec, disabled: Option<&str>) -> egui::Response { response.on_hover_ui(|ui| { let t = Tokens::get(); - let name = app.tr_label(command.label); + let name = app.tr_label(command.info(&app.session).label); let name_width = ui.painter().layout_no_wrap(name.to_string(), crate::fonts::semibold(crate::theme::Tokens::get().font_heading), t.text).size().x; let key_width = crate::keymap::display_for(app, command.id) @@ -1760,7 +1762,7 @@ fn dropdown_width(app: &SolveApp, ui: &egui::Ui, cmds: &[&'static solidcraft_eng let font = FontId::proportional(t.font_button); cmds.iter() .map(|c| { - let label = ui.painter().layout_no_wrap(app.tr_label(c.label).to_string(), font.clone(), t.text).size().x; + let label = ui.painter().layout_no_wrap(app.tr_label(c.info(&app.session).label).to_string(), font.clone(), t.text).size().x; let key = crate::keymap::display_for(app, c.id) .map(|k| ui.painter().layout_no_wrap(k.to_string(), FontId::monospace(t.font_button), t.text).size().x + 24.0) .unwrap_or(0.0); @@ -1790,12 +1792,12 @@ fn dropdown_row(app: &SolveApp, ui: &mut egui::Ui, c: &'static solidcraft_engine let pr = Rect::from_center_size(pos2(rect.right() - 13.0, rect.center().y), vec2(20.0, 20.0)); let pin = ui.interact(pr, ui.id().with(("dropdown_pin", c.id)), Sense::click()); let pointer_on = (resp.hovered() || pin.hovered()) && !egui::DragAndDrop::has_any_payload(ui.ctx()); - let label = app.tr_label(c.label).to_string(); + let label = app.tr_label(info.label).to_string(); resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled() && info.enabled, &label)); crate::scenario::publish_handle(&format!("toolbar:{}", c.id), rect.center()); crate::scenario::publish_handle(&format!("dropdown:{}", c.id), rect.center()); let hot = info.enabled && (pointer_on || resp.has_focus()); - let mut row = crate::ui_kit::MenuItem::new(c.id, &label, c.icon); + let mut row = crate::ui_kit::MenuItem::new(c.id, &label, info.icon); row.enabled = info.enabled; row.highlighted = hot; let shortcut = crate::keymap::display_for(app, c.id).unwrap_or_default(); @@ -1927,13 +1929,14 @@ struct ToolbarDrag { } /// The dragged command's icon under the pointer, crossed out when releasing removes it. -fn drag_ghost(ctx: &egui::Context, id: &str, at: egui::Pos2, removing: bool) { +fn drag_ghost(app: &SolveApp, ctx: &egui::Context, id: &str, at: egui::Pos2, removing: bool) { let t = Tokens::get(); let Some(c) = solidcraft_engine::find_command(id) else { return }; let p = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("sc_toolbar_drag"))); let r = Rect::from_center_size(at + vec2(14.0, 16.0), vec2(30.0, 30.0)); p.rect(r, t.radius_sm, t.toolbar.gamma_multiply(0.92), Stroke::new(1.0, if removing { t.error } else { t.accent }), egui::StrokeKind::Inside); - icons::paint_icon(&p, r.shrink(5.0), c.icon, f32::from(t.icon.a()) / 255.0); + let info = c.info(&app.session); + icons::paint_icon(&p, r.shrink(5.0), info.icon, f32::from(t.icon.a()) / 255.0); if removing { let s = Stroke::new(2.0, t.error); let x = Rect::from_center_size(r.right_top(), vec2(9.0, 9.0)); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 4e614fa19..2acfbdb77 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -381,6 +381,7 @@ fn in_view(proj: &Proj, b: &solidcraft_engine::geom::Aabb3) -> bool { fn scene_key(app: &SolveApp) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); app.session.revision.hash(&mut h); + app.session.colored_components.hash(&mut h); (std::sync::Arc::as_ptr(&crate::open_meshing::shown_world(app)) as usize).hash(&mut h); app.ui.show_grid.hash(&mut h); app.ui.visual_style.hash(&mut h); @@ -964,12 +965,15 @@ pub(crate) fn build_scene(app: &SolveApp) -> GpuScene { sc.line(a.to_f32(), c.to_f32(), c4(tk.body_edge), 0.85, false); } } - let base = body_color(&s.doc, b).unwrap_or(tk.body); + let base = solidcraft_engine::view::component_color(s, b.component) + .map(|[r, g, b]| Color32::from_rgb(r, g, b)) + .or_else(|| body_color(&s.doc, b)) + .unwrap_or(tk.body); let col = if faded { c4(base.gamma_multiply(0.35)) } else { c4(base) }; // Appearances: the body's opacity, and faces with looks of their own. let opacity = s.doc.model_body_opacity(b); let face_looks: std::collections::HashMap = - if shaded { s.doc.face_colors(b).into_iter().collect() } else { Default::default() }; + if shaded && s.colored_components.is_none() { s.doc.face_colors(b).into_iter().collect() } else { Default::default() }; let opaque = !faded && opacity >= 0.999 && face_looks.values().all(|l| l.opacity >= 0.999); let planned = drawn_plan(app, b, opaque); let on_gpu = planned.is_some(); diff --git a/crates/ui-egui/src/viewport_appearance_tests.rs b/crates/ui-egui/src/viewport_appearance_tests.rs index f1a6a8e11..50867e41f 100644 --- a/crates/ui-egui/src/viewport_appearance_tests.rs +++ b/crates/ui-egui/src/viewport_appearance_tests.rs @@ -196,3 +196,31 @@ fn cancelling_theme_preview_restores_viewport_palette_keys() { h.frame(); assert_ne!(keys(&h.app), first); } + +#[test] +fn inspect_menu_toggles_component_colors_without_a_dialog_and_refreshes_scene() { + let mut h = crate::scenario::Harness::new(); + h.frames(3); + let command = solidcraft_engine::find_command("inspect.colored_components").unwrap(); + let info = command.info(&h.app.session); + assert_eq!((info.label, info.icon), ("Enable Component Colors", "colored_components")); + h.step(&json!({"click": {"handle": "tab:INSPECT"}})).unwrap(); + h.frames(2); + let original_key = super::scene_key(&h.app); + h.step(&json!({"click": {"handle": "panel:INSPECT:CHECK"}})).unwrap(); + h.frames(2); + assert!(h.widget("Enable Component Colors").is_some()); + h.step(&json!({"click": {"handle": "dropdown:inspect.colored_components"}})).unwrap(); + assert!(h.app.session.colored_components.is_some()); + assert!(h.app.dialog.is_none()); + assert_ne!(super::scene_key(&h.app), original_key); + let info = command.info(&h.app.session); + assert_eq!((info.label, info.icon), ("Disable Component Colors", "colored_components_off")); + h.step(&json!({"click": {"handle": "panel:INSPECT:CHECK"}})).unwrap(); + h.frames(2); + assert!(h.widget("Disable Component Colors").is_some()); + h.step(&json!({"click": {"handle": "dropdown:inspect.colored_components"}})).unwrap(); + assert!(h.app.session.colored_components.is_none()); + let info = command.info(&h.app.session); + assert_eq!((info.label, info.icon), ("Enable Component Colors", "colored_components")); +} diff --git a/crates/ui-egui/tests/icon_audit.rs b/crates/ui-egui/tests/icon_audit.rs index af57592f9..70333d23b 100644 --- a/crates/ui-egui/tests/icon_audit.rs +++ b/crates/ui-egui/tests/icon_audit.rs @@ -171,6 +171,12 @@ fn requested_menu_icons_have_artwork_and_match_manifest() { assistant(&mut h, &mut requested); ribbon(&mut h, &mut requested); + h.app.start("inspect.colored_components"); + h.frames(2); + click(&mut h, "panel:INSPECT:CHECK"); + collect(&mut h, "component colors enabled", &mut requested); + escape(&mut h); + h.app.start("inspect.colored_components"); click(&mut h, "appbar:file"); assert!(h.widget("Export Current View as DXF…").is_some(), "painted File rows retain accessible action labels"); collect(&mut h, "File", &mut requested);