Colored components (feature request #2507) (#2877)

* feat: add colored components inspection toggle

* feat: persist component colors and add cycling controls

* feat: assign component colors in creation order

* fix: update component color menu integration and translations

* fix: proper description for pending format change.

* fix: deleted duplicated format change description from docs/pending.

* Compare the component colour counter in the features-only check

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Vadim Kalinsky <vadim@kalinsky.com>
Co-authored-by: bherbruck <brennen.herbruck@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-10-25 21:11:03 +00:00
1 parent 5fbe058051
commit 59cad5f0bb
27 files changed
+488 -20

No files matched your search

+2
View File
@@ -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 |
+32
View File
@@ -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
@@ -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
@@ -0,0 +1,21 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<title>Colored components</title>
<path d="M9.235 17.706L15.059 20.882L15.059 48.941L9.235 44.926Z" fill="#c06f00"/>
<path d="M35.176 9.235L15.059 20.882L15.059 48.941L36.765 35.139Z" fill="#a45000"/>
<path d="M29.046 5L35.176 8.176L15.196 19.718L9.066 16.541Z" fill="#f1d2af"/>
<path d="M29.046 5.529L35.176 8.706L35.176 36.235L15.059 49.471L9.235 45.765L9.066 17.071Z" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M9.066 17.6L15.059 20.882L34.647 9.235" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M15.059 20.882L15.059 47.067" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M32.222 18.595L44.949 25.944L44.949 51.122L32.222 43.774Z" fill="#328bd3"/>
<path d="M54.934 20.173L44.949 25.944L44.949 51.122L54.934 45.352Z" fill="#236ead"/>
<path d="M42.059 12.412L54.934 20.173L44.949 25.944L32 17.706Z" fill="#b9ddf8"/>
<path d="M41.159 11.766L54.934 20.173L54.934 45.352L44.949 51.122L31.164 42.715L31.164 17.536Z" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M32.222 18.595L44.949 25.944L54.934 20.173" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M44.949 25.944L44.949 51.122" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M18.299 39.062L31.015 46.411L31.015 59L18.299 51.652Z" fill="#a28200"/>
<path d="M41.921 40.121L31.015 46.411L31.015 59L41.921 52.711Z" fill="#826700"/>
<path d="M29.194 32.773L41.921 40.121L31.015 46.411L18.299 39.062Z" fill="#e5d99b"/>
<path d="M29.194 32.773L41.921 40.121L41.921 52.711L31.015 59L18.299 51.652L18.299 39.062Z" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M18.299 39.062L31.015 46.411L41.921 40.121" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M31.015 46.411L31.015 59" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 2.3 KiB

@@ -0,0 +1,21 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<title>Disable component colors</title>
<path d="M9.235 17.706L15.059 20.882L15.059 48.941L9.235 44.926Z" fill="#328bd3"/>
<path d="M35.176 9.235L15.059 20.882L15.059 48.941L36.765 35.139Z" fill="#236ead"/>
<path d="M29.046 5L35.176 8.176L15.196 19.718L9.066 16.541Z" fill="#b9ddf8"/>
<path d="M29.046 5.529L35.176 8.706L35.176 36.235L15.059 49.471L9.235 45.765L9.066 17.071Z" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M9.066 17.6L15.059 20.882L34.647 9.235" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M15.059 20.882L15.059 47.067" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M32.222 18.595L44.949 25.944L44.949 51.122L32.222 43.774Z" fill="#328bd3"/>
<path d="M54.934 20.173L44.949 25.944L44.949 51.122L54.934 45.352Z" fill="#236ead"/>
<path d="M42.059 12.412L54.934 20.173L44.949 25.944L32 17.706Z" fill="#b9ddf8"/>
<path d="M41.159 11.766L54.934 20.173L54.934 45.352L44.949 51.122L31.164 42.715L31.164 17.536Z" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M32.222 18.595L44.949 25.944L54.934 20.173" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M44.949 25.944L44.949 51.122" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M18.299 39.062L31.015 46.411L31.015 59L18.299 51.652Z" fill="#328bd3"/>
<path d="M41.921 40.121L31.015 46.411L31.015 59L41.921 52.711Z" fill="#236ead"/>
<path d="M29.194 32.773L41.921 40.121L31.015 46.411L18.299 39.062Z" fill="#b9ddf8"/>
<path d="M29.194 32.773L41.921 40.121L41.921 52.711L31.015 59L18.299 51.652L18.299 39.062Z" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M18.299 39.062L31.015 46.411L41.921 40.121" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M31.015 46.411L31.015 59" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 2.3 KiB

+3
View File
@@ -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",
+3
View File
@@ -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": "曲率コーム解析",
+3
View File
@@ -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": "曲率梳分析",
+162
View File
@@ -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]);
}
}
+15 -1
View File
@@ -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<u64>,
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<Component>,
/// 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<crate::Occurrence>,
@@ -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
+1
View File
@@ -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();
@@ -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.
+1
View File
@@ -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;
+13
View File
@@ -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<Value> {
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}))
}
+1
View File
@@ -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 {
+16
View File
@@ -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<Value> {
.collect::<Result<Vec<_>>>()?;
Ok(json!({"materials": built_in.chain(user).collect::<Vec<_>>()}))
}
fn colored_components(s: &mut Session, p: &Value) -> Result<Value> {
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}))
}
+6 -2
View File
@@ -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(),
+6
View File
@@ -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<SurfaceAnalysis>,
/// 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
}
+14 -2
View File
@@ -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()
+81
View File
@@ -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());
}
+3
View File
@@ -838,6 +838,9 @@ fn component_items(app: &SolveApp, id: u64) -> Vec<Item> {
.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})));
+4
View File
@@ -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;
+18
View File
@@ -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();
+16 -13
View File
@@ -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::<ToolbarDrag>(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));
+6 -2
View File
@@ -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<usize, solidcraft_engine::doc::appearance::Look> =
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();
@@ -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"));
}
+6
View File
@@ -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);