brep_render/style.rs
1//! Render settings (R14 — the `CADmaterials` semantics: per-kind material
2//! variants, hover color, flat-shading toggle, user-persisted overrides) and
3//! the selection/hover emphasis state (R17/R24 — name-keyed, fed by the host's
4//! `SelectionFilter`). Plain data, shared by the engine core and the wgpu
5//! renderer; JSON in/out at the R3 boundary.
6
7use std::collections::HashSet;
8
9/// sRGB color in 0..1 + alpha.
10pub type Rgba = [f32; 4];
11
12fn hex(hex: u32, alpha: f32) -> Rgba {
13 let [r, g, b] = crate::color::hex_to_srgb_f32(hex);
14 [r, g, b, alpha]
15}
16
17/// Parse `#rrggbb` / `#rgb` / `0xrrggbb` (returns None on anything else).
18pub fn parse_css_hex(value: &str) -> Option<[f32; 3]> {
19 let v = value.trim();
20 let digits = v
21 .strip_prefix('#')
22 .or_else(|| v.strip_prefix("0x"))
23 .or_else(|| v.strip_prefix("0X"))?;
24 let expand = |c: char| c.to_digit(16).map(|d| (d * 17) as f32 / 255.0);
25 match digits.len() {
26 3 => {
27 let mut chars = digits.chars();
28 Some([
29 expand(chars.next()?)?,
30 expand(chars.next()?)?,
31 expand(chars.next()?)?,
32 ])
33 }
34 6 => {
35 let n = u32::from_str_radix(digits, 16).ok()?;
36 Some(crate::color::hex_to_srgb_f32(n))
37 }
38 _ => None,
39 }
40}
41
42/// The sketcher's overlay palette as plain `0xRRGGBB` hex — the ONE place the
43/// default color literals live. [`RenderSettings`] stores each of these as an
44/// editable [`Rgba`] field (defaults derived from here via `hex`) and hands the
45/// sketch tessellation/overlay builders a live `SketchColors` view via
46/// [`RenderSettings::sketch_colors`], so the sketch renderer reads its colors from
47/// the display settings just like faces/edges/vertices do — no scattered constants.
48///
49/// The `constraint` green is a deliberate user directive (2026-08-22): CONSTRAINT
50/// annotations (geometric-constraint glyphs + dimension leaders/labels) read in
51/// green so they stand apart from the blue/white sketch GEOMETRY.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub struct SketchColors {
54 /// Movable geometry / point (blue).
55 pub movable: u32,
56 /// Locked geometry / point (near-white).
57 pub locked: u32,
58 /// No-mobility geometry fallback (yellow).
59 pub geometry: u32,
60 /// No-mobility point fallback.
61 pub point: u32,
62 /// Construction point (orange) while it can move; a locked one takes `locked`.
63 pub construction_point: u32,
64 /// Heuristic under-constrained point.
65 pub under_constrained_point: u32,
66 /// Selected entity — amber (the transform-gizmo accent); beats hover.
67 pub selected: u32,
68 /// Hovered entity — light blue (brighter than movable).
69 pub hovered: u32,
70 /// Draw-tool rubber-band preview (dim, so it reads as tentative).
71 pub preview: u32,
72 /// Constraint annotations — glyphs + dimension leaders/labels (green).
73 pub constraint: u32,
74 /// A constraint the solver named as part of a CONFLICT — the red of the
75 /// status bar's conflict dot, so the two readouts agree at a glance.
76 pub conflict: u32,
77}
78
79impl Default for SketchColors {
80 fn default() -> Self {
81 // The previous sketcher's theme defaults — the single source of these literals.
82 Self {
83 movable: 0x4aa3ff,
84 locked: 0xe6ebf2,
85 geometry: 0xffff88,
86 point: 0x9ec9ff,
87 construction_point: 0xffa86a,
88 under_constrained_point: 0xffb347,
89 selected: 0xffa500,
90 hovered: 0x7fd0ff,
91 preview: 0x8fa0b8,
92 constraint: 0x4ade80,
93 conflict: 0xff5c5c,
94 }
95 }
96}
97
98/// The GUI chrome theme (panels, windows, toolbar, text) — controls the egui
99/// look, NOT the 3D viewport background (that is the separate `background`
100/// setting). `Auto` follows the OS/system theme (`prefers-color-scheme` on web).
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub enum ThemeMode {
103 /// Follow the system's theme preference (falls back to dark when no OS signal).
104 Auto,
105 Light,
106 Dark,
107}
108
109/// How a plain viewport click builds a MULTI-selection (the Settings "Multi-select"
110/// dropdown). Read by the app's viewport click routing — the engine's selection
111/// primitives (`select_candidate` replace / `toggle_candidate` toggle) are
112/// mode-agnostic; this only chooses which one a plain click drives.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum MultiSelectMode {
115 /// A plain click REPLACES the selection; Ctrl/Cmd+click adds/toggles (the
116 /// classic CAD behavior).
117 CtrlClick,
118 /// A plain click TOGGLES the item in the selection (click again to unselect)
119 /// so a multi-selection needs no modifier key; a click on empty space clears.
120 ClickToggles,
121}
122
123impl MultiSelectMode {
124 /// Every mode, in the order the Settings dropdown lists them.
125 pub const ALL: [MultiSelectMode; 2] = [MultiSelectMode::CtrlClick, MultiSelectMode::ClickToggles];
126
127 /// The human label — ALSO the serialized `multiSelect` value (the
128 /// renderQuality pattern: the dropdown and the stored JSON speak the label;
129 /// `apply_json` parses it back tolerantly).
130 pub fn label(&self) -> &'static str {
131 match self {
132 MultiSelectMode::CtrlClick => "Ctrl+Click",
133 MultiSelectMode::ClickToggles => "Click toggles",
134 }
135 }
136}
137
138/// How base face color is chosen per solid.
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub enum FaceColorMode {
141 /// The app look: every face gets `face_color` (unless the solid carries a
142 /// metadata override).
143 Uniform,
144 /// The artifact look: stable name-hashed color per solid.
145 HashedBySolid,
146}
147
148/// The viewer's material palette + display toggles. Defaults are the
149/// `CADmaterials` values.
150/// Global toolbar appearance. Missing saved values migrate to Ribbon.
151#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
152pub enum ToolbarStyle {
153 #[default]
154 Ribbon,
155 Classic,
156}
157
158impl ToolbarStyle {
159 pub fn as_str(self) -> &'static str {
160 match self {
161 Self::Ribbon => "Ribbon",
162 Self::Classic => "Classic",
163 }
164 }
165}
166
167/// Workbench ids that no longer exist, each with the id that took its place.
168/// The app's registry owns the live ids; this is only the rename table a
169/// stored value passes through on read.
170pub const RETIRED_WORKBENCHES: &[(&str, &str)] = &[("pmi", "modeling")];
171
172/// `id`, or its successor when it names a retired workbench.
173pub fn successor_workbench(id: &str) -> &str {
174 RETIRED_WORKBENCHES
175 .iter()
176 .find(|(retired, _)| *retired == id)
177 .map_or(id, |(_, successor)| successor)
178}
179
180#[derive(Debug, Clone, PartialEq)]
181pub struct RenderSettings {
182 /// GUI chrome theme (egui panels/windows/toolbar/text). Defaults to `Auto`,
183 /// following the OS light/dark preference.
184 pub theme: ThemeMode,
185 /// Global UI size scale applied to the whole egui chrome via
186 /// `egui::Context::set_zoom_factor`. 1.0 = native size; composes with the
187 /// device pixel ratio. Clamped to `[0.5, 3.0]`.
188 pub ui_scale: f32,
189 /// Skip the startup recovery offer without restoring documents automatically.
190 /// Autosaving remains enabled for the current session.
191 pub disable_recovery_prompt: bool,
192 /// Open on an empty document instead of the example model (the Box / Pin /
193 /// Cut seed) when the application starts.
194 pub disable_startup_model: bool,
195 /// Size multiplier for the floating TEXT LABELS the app overlays on the 3D
196 /// model — the dimension-gizmo value chips (sketch + feature dimensions), the
197 /// assembly-constraint chips, and the transform gizmo's axis letters. 1.0 = the
198 /// base monospace size; the label's glyphs, its measured edit-box width, and its
199 /// chip padding all scale together (see `brep-app`'s `viewport::labels`). A
200 /// MULTIPLIER, not a point size, so labels stay consistent with each other and
201 /// the setting survives a restyle. Clamped to `[0.25, 3.0]`: 0.25 is the
202 /// smallest label that is still a LABEL rather than a smudge — a quarter of the
203 /// 12pt base monospace is a ~3.8pt glyph row inside a ~4.5pt-tall chip, which is
204 /// the point at which the double-click/drag target stops being something a
205 /// pointer can reliably land on (and it composes with `uiScale` + the device
206 /// pixel ratio, so it is not an absolute 3pt on screen). The 3.0 ceiling keeps a
207 /// user from filling the viewport with one label. Independent of
208 /// [`RenderSettings::ui_scale`], which sizes the egui CHROME (panels/toolbar)
209 /// and not the model overlay.
210 pub label_scale: f32,
211 /// Debug overlay: draw the 1px red outline of each gizmo grab handle's hit
212 /// region (arrows/leaders as capsules, balls as circles). Off by default;
213 /// toggled from Settings to inspect exactly where a drag will grab.
214 pub debug_grab_handles: bool,
215 pub background: [f32; 3],
216 pub face_color_mode: FaceColorMode,
217 /// IGNORE the model's own colours when shading (RENDER-ONLY).
218 ///
219 /// Bodies and faces carry a durable `color` metadata attribute — stamped by
220 /// a STEP import, editable in the Info window — and by default it IS the
221 /// shaded colour. Ticking this box makes the viewport fall back to
222 /// [`Self::face_color_mode`] (the uniform or name-hashed colour) as though
223 /// the model carried no colours at all.
224 ///
225 /// It is a DISPLAY switch, not an edit: the metadata store is never touched,
226 /// so unticking it brings every model colour straight back, and a document
227 /// saved with the box ticked still carries all of its colours. Defaults to
228 /// false — a coloured model shows its colours.
229 pub override_model_colors: bool,
230 /// Show the WORKBENCH ACTIONS toolbar — a second strip under the primary
231 /// toolbar with one button per feature the active workbench offers (and, where
232 /// the Constraints panel is shown, one per assembly-constraint type). Chrome
233 /// only: it never changes what the palette or context bar offer. The app
234 /// hides the strip while a sketch is being edited regardless of this flag.
235 pub show_workbench_toolbar: bool,
236 pub toolbar_style: ToolbarStyle,
237 pub face_color: Rgba,
238 pub face_selected_color: Rgba,
239 pub hover_color: Rgba,
240 pub edge_color: Rgba,
241 pub edge_selected_color: Rgba,
242 pub edge_width_px: f32,
243 /// Draw the OCCLUDED portions of edges at all — the second, depth-failing
244 /// edge pass that [`Self::hidden_edge_alpha`] dims.
245 ///
246 /// It is a whole extra pass over every edge buffer in the scene, so turning
247 /// it off is the single largest display saving the viewer has: measured
248 /// 2026-09-11 on a heavy model, frame `draw` fell 33.61 ms -> 24.76 ms
249 /// (-26%). The viewport looks materially different with it off — edges
250 /// behind a face simply are not there — which is why this is a user's
251 /// choice rather than something a performance heuristic flips. Defaults to
252 /// FALSE since the 2026-10-14 display defaults directive (the user's chosen
253 /// look: no occluded-edge pass, see [`RenderSettings::default`]); before that
254 /// it defaulted to true.
255 ///
256 /// Distinct from setting [`Self::hidden_edge_alpha`] to 0, which also skips
257 /// the pass: the alpha is how DIM the occluded edges are, this is WHETHER
258 /// they are drawn, so a user can A/B the cost without losing their dimness.
259 pub show_occluded_edges: bool,
260 /// Occluded edges render dimmed, not dropped (R17): alpha of the
261 /// depth-failing edge pass. 0 disables the pass, as does
262 /// [`Self::show_occluded_edges`] being false.
263 pub hidden_edge_alpha: f32,
264 pub vertex_color: Rgba,
265 pub vertex_selected_color: Rgba,
266 pub vertex_size_px: f32,
267 pub flat_shading: bool,
268 /// Wireframe display (R14): when true the shaded face-fill pass is skipped so
269 /// only edges draw (the CAD wireframe look; back edges show through). Does
270 /// NOT affect picking (CPU ray-based) or the overlay pass.
271 pub wireframe: bool,
272 /// Draw the shaded FACES (R14 companion): false leaves the model as its
273 /// edges and vertices alone. Independent of [`Self::wireframe`], which
274 /// swaps the shaded fill for the triangle wireframe — with faces off there
275 /// is nothing to swap, so both face passes are skipped.
276 ///
277 /// A DISPLAY switch only: picking is CPU ray-based and unaffected, so a
278 /// hidden face still selects. This exists so a presentation capture (and
279 /// the toolbar's three visibility toggles) can drop a whole class of
280 /// geometry without editing the size settings that describe how the class
281 /// is DRAWN — a zeroed `edgeWidthPx` is not "no edges", it is a
282 /// zero-width edge the user has to restore by remembering the old number.
283 pub show_faces: bool,
284 /// Draw the EDGES (both the visible pass and the dimmed occluded one).
285 /// See [`Self::show_faces`] for why this is not `edgeWidthPx = 0`.
286 pub show_edges: bool,
287 /// Draw the VERTEX points. See [`Self::show_faces`].
288 pub show_vertices: bool,
289 /// World-axis helper (R20): screen length in CSS px; 0 disables.
290 pub axis_length_px: f32,
291 /// On-screen edge length of the always-on corner ViewCube, in CSS px. Drives
292 /// BOTH the rendered mini-camera viewport AND the hit-test corner rect (they
293 /// read the same value), so the cube and its clickable region scale together.
294 /// Defaults to [`ViewCube::DEFAULT_SIZE_PX`](brep_gizmos::view_cube::ViewCube::DEFAULT_SIZE_PX), so the cube is unchanged until edited.
295 pub viewcube_size_px: f32,
296 pub pick_double_sided: bool,
297 /// How a plain viewport click builds a multi-selection (see [`MultiSelectMode`]).
298 pub multi_select: MultiSelectMode,
299 /// A connected SpaceMouse / Spaceball moves the 3D view (`brep-app`'s
300 /// `spacemouse` module). On by default: with no device it does nothing.
301 pub spacemouse_enabled: bool,
302 /// Speed multiplier over the device's base rates, clamped to
303 /// `[0.1, 5.0]` (the slider's domain).
304 pub spacemouse_sensitivity: f32,
305 /// Per-axis direction flips, indexed in the device's HID axis order
306 /// (`SPACEMOUSE_AXES`): pan x, zoom, pan y, tilt, roll, spin.
307 pub spacemouse_invert: [bool; 6],
308 /// Tessellation LOD factor — the chord-tolerance multiplier behind the
309 /// "Render Quality" dropdown (see [`RENDER_QUALITY`]: 1.0 = "Medium", 0.5 =
310 /// "High"). Defaults to 0.5, the "High" level, per the 2026-10-14 display
311 /// defaults directive.
312 pub lod_factor: f64,
313 // --- Sketcher overlay palette (managed here like every other display color) ---
314 // Defaults come from `SketchColors::default()` (the single source of the
315 // literals); `sketch_colors()` re-derives a `SketchColors` view for the
316 // tessellation/overlay builders.
317 pub sketch_movable_color: Rgba,
318 pub sketch_locked_color: Rgba,
319 pub sketch_geometry_color: Rgba,
320 pub sketch_point_color: Rgba,
321 pub sketch_construction_point_color: Rgba,
322 pub sketch_under_constrained_point_color: Rgba,
323 pub sketch_selected_color: Rgba,
324 pub sketch_hovered_color: Rgba,
325 pub sketch_preview_color: Rgba,
326 pub sketch_constraint_color: Rgba,
327 pub sketch_conflict_color: Rgba,
328 /// The active UI WORKBENCH id (`"all"` / `"modeling"` / `"sheetMetal"`), a
329 /// plain string (NOT an enum) so the app-side per-file workbench registry
330 /// stays the sole owner of the valid-id set — adding a workbench never touches
331 /// this crate. This is purely a UI FILTER over feature-CREATION: it does not
332 /// affect what the history executes or renders. Default `"modeling"`. An
333 /// unknown stored id is tolerated here and validated app-side (the registry's
334 /// resolver falls back to the default).
335 pub workbench: String,
336 /// Assembly AUTO-SOLVE: when true (the default) every constraint mutation
337 /// re-solves + re-runs immediately; when false the mutation paths only
338 /// update state and the user drives the manual Solve button. Consulted by
339 /// the app's constraint-mutation path.
340 pub assembly_auto_solve: bool,
341 /// Show Constraint Graphics: the render toggle the
342 /// viewport overlay lane consumes — per-constraint leader/label graphics
343 /// draw only while this is on. Owned here so the panel toggle, persistence,
344 /// and the overlay renderer all read ONE flag.
345 pub show_constraint_graphics: bool,
346 /// The BOM's COLUMN CONFIGURATION — the raw text of the Settings panel's
347 /// Assemblies textarea (one `[*]prefix.Field` per line). Stored VERBATIM,
348 /// exactly as the user typed it: parsing, the known-field catalogue and the
349 /// `part.` / `occurrence.` vocabulary all live app-side
350 /// (`panels::bom_columns`), so adding a BOM field never touches this crate
351 /// — the same division of labour that keeps `workbench` a plain string here.
352 ///
353 /// Default EMPTY, which means "the app's shipped default configuration".
354 /// A document that was never configured therefore persists byte-for-byte as
355 /// before, and a later change to the shipped default still reaches every
356 /// user who never overrode it.
357 pub bom_columns: String,
358}
359
360impl Default for RenderSettings {
361 fn default() -> Self {
362 let sk = SketchColors::default();
363 Self {
364 // Default to Auto so the chrome follows the OS light/dark preference
365 // (egui's `ThemePreference::System`; falls back to dark when there is
366 // no OS signal).
367 theme: ThemeMode::Auto,
368 // 1.0 = native UI size (no zoom); scales the whole egui chrome.
369 ui_scale: 1.0,
370 disable_recovery_prompt: false,
371 disable_startup_model: false,
372 // 1.0 = the labels' native monospace size (no scaling).
373 label_scale: 1.0,
374 // Debug grab-handle outlines are off by default (a diagnostic aid).
375 debug_grab_handles: false,
376 // The viewport look is the user's 2026-10-14 display defaults
377 // directive (a screenshot of their Settings window, every value
378 // below read from it): a slate background, a light grey-blue face
379 // colour, dark slate 1px edges with no occluded-edge pass. The
380 // selection/hover colours, the vertex colours and the whole sketch
381 // palette were already these values; vertex dots stay shown (the
382 // user's explicit follow-up to the directive).
383 background: [
384 ((0x13) as f32) / 255.0,
385 ((0x1b) as f32) / 255.0,
386 ((0x24) as f32) / 255.0,
387 ],
388 face_color_mode: FaceColorMode::Uniform,
389 face_color: hex(0xa9bdcc, 1.0),
390 face_selected_color: hex(0xffc400, 1.0),
391 hover_color: hex(0xfbff00, 1.0),
392 edge_color: hex(0x324452, 1.0),
393 edge_selected_color: hex(0xff00ff, 1.0),
394 edge_width_px: 1.0,
395 // No occluded-edge pass by default: the toggle is off AND its alpha
396 // is 0, so switching the pass back on starts from "invisible" until
397 // the user also raises the alpha (the two are independent on purpose,
398 // see `show_occluded_edges`).
399 show_occluded_edges: false,
400 hidden_edge_alpha: 0.0,
401 vertex_color: hex(0x4aff03, 1.0),
402 vertex_selected_color: hex(0x00ffff, 1.0),
403 vertex_size_px: 6.0,
404 flat_shading: false,
405 wireframe: false,
406 // Everything visible: the three toggles are a subtractive control.
407 show_faces: true,
408 show_edges: true,
409 show_vertices: true,
410 override_model_colors: false,
411 show_workbench_toolbar: true,
412 toolbar_style: ToolbarStyle::Ribbon,
413 axis_length_px: 46.0,
414 // The corner ViewCube's current on-screen size — the single source of
415 // the literal is `ViewCube::DEFAULT_SIZE_PX`, so the settings default and
416 // the widget default can never drift.
417 viewcube_size_px: brep_gizmos::view_cube::ViewCube::DEFAULT_SIZE_PX,
418 pick_double_sided: true,
419 multi_select: MultiSelectMode::ClickToggles,
420 spacemouse_enabled: true,
421 spacemouse_sensitivity: 1.0,
422 spacemouse_invert: [false; 6],
423 // "High" render quality (RENDER_QUALITY: 0.5 = half the "Medium"
424 // chord tolerance) — the directive's dropdown value.
425 lod_factor: 0.5,
426 // Sketch palette: derive each Rgba from the ONE source of the literals
427 // (`SketchColors::default`) so nothing changes visually until edited.
428 sketch_movable_color: hex(sk.movable, 1.0),
429 sketch_locked_color: hex(sk.locked, 1.0),
430 sketch_geometry_color: hex(sk.geometry, 1.0),
431 sketch_point_color: hex(sk.point, 1.0),
432 sketch_construction_point_color: hex(sk.construction_point, 1.0),
433 sketch_under_constrained_point_color: hex(sk.under_constrained_point, 1.0),
434 sketch_selected_color: hex(sk.selected, 1.0),
435 sketch_hovered_color: hex(sk.hovered, 1.0),
436 sketch_preview_color: hex(sk.preview, 1.0),
437 sketch_constraint_color: hex(sk.constraint, 1.0),
438 sketch_conflict_color: hex(sk.conflict, 1.0),
439 // Default workbench: general Modeling.
440 workbench: "modeling".to_string(),
441 // Assembly: auto-solve every constraint mutation; constraint
442 // graphics shown while a document has constraints.
443 assembly_auto_solve: true,
444 show_constraint_graphics: true,
445 // Empty = the app's shipped BOM column configuration.
446 bom_columns: String::new(),
447 }
448 }
449}
450
451impl RenderSettings {
452 /// The artifact-corpus preset: byte-faithful to the slice-1 artifact look
453 /// (per-solid hashed colors, 0x101418 background, 1.6px edges in
454 /// 0x0d1030, no hidden-edge pass, no vertices, no axes, "Medium" LOD).
455 /// Every field the corpus look depends on is pinned HERE, so a change to the
456 /// app's own defaults (2026-10-14 moved the viewport colours, the edge pass
457 /// and the LOD) never shifts the corpus.
458 pub fn artifact() -> Self {
459 Self {
460 background: [
461 ((0x10) as f32) / 255.0,
462 ((0x14) as f32) / 255.0,
463 ((0x18) as f32) / 255.0,
464 ],
465 face_color_mode: FaceColorMode::HashedBySolid,
466 edge_color: hex(0x0d1030, 1.0),
467 edge_width_px: 1.6,
468 show_occluded_edges: false,
469 hidden_edge_alpha: 0.0,
470 show_vertices: false,
471 vertex_size_px: 0.0,
472 axis_length_px: 0.0,
473 lod_factor: 1.0,
474 ..Self::default()
475 }
476 }
477
478 /// Apply a partial JSON override (R3 settings entrypoint). Unknown keys
479 /// are ignored; colors are CSS hex strings.
480 pub fn apply_json(&mut self, json: &str) -> Result<(), String> {
481 let value: serde_json::Value =
482 serde_json::from_str(json).map_err(|error| format!("settings parse: {error}"))?;
483 let color = |key: &str, target: &mut Rgba| {
484 if let Some(v) = value.get(key).and_then(|v| v.as_str()) {
485 if let Some(rgb) = parse_css_hex(v) {
486 target[0] = rgb[0];
487 target[1] = rgb[1];
488 target[2] = rgb[2];
489 }
490 }
491 };
492 color("faceColor", &mut self.face_color);
493 color("faceSelectedColor", &mut self.face_selected_color);
494 color("hoverColor", &mut self.hover_color);
495 color("edgeColor", &mut self.edge_color);
496 color("edgeSelectedColor", &mut self.edge_selected_color);
497 color("vertexColor", &mut self.vertex_color);
498 color("vertexSelectedColor", &mut self.vertex_selected_color);
499 // Sketcher overlay palette (same CSS-hex shape as the face/edge/vertex colors).
500 color("sketchMovableColor", &mut self.sketch_movable_color);
501 color("sketchLockedColor", &mut self.sketch_locked_color);
502 color("sketchGeometryColor", &mut self.sketch_geometry_color);
503 color("sketchPointColor", &mut self.sketch_point_color);
504 color("sketchConstructionPointColor", &mut self.sketch_construction_point_color);
505 color("sketchUnderConstrainedPointColor", &mut self.sketch_under_constrained_point_color);
506 color("sketchSelectedColor", &mut self.sketch_selected_color);
507 color("sketchHoveredColor", &mut self.sketch_hovered_color);
508 color("sketchPreviewColor", &mut self.sketch_preview_color);
509 color("sketchConstraintColor", &mut self.sketch_constraint_color);
510 color("sketchConflictColor", &mut self.sketch_conflict_color);
511 if let Some(v) = value.get("background").and_then(|v| v.as_str()) {
512 if let Some(rgb) = parse_css_hex(v) {
513 self.background = rgb;
514 }
515 }
516 if let Some(v) = value.get("edgeWidthPx").and_then(|v| v.as_f64()) {
517 self.edge_width_px = (v as f32).clamp(0.0, 32.0);
518 }
519 if let Some(v) = value.get("vertexSizePx").and_then(|v| v.as_f64()) {
520 self.vertex_size_px = (v as f32).clamp(0.0, 64.0);
521 }
522 if let Some(v) = value.get("showOccludedEdges").and_then(|v| v.as_bool()) {
523 self.show_occluded_edges = v;
524 }
525 if let Some(v) = value.get("hiddenEdgeAlpha").and_then(|v| v.as_f64()) {
526 self.hidden_edge_alpha = (v as f32).clamp(0.0, 1.0);
527 }
528 if let Some(v) = value.get("faceColorMode").and_then(|v| v.as_str()) {
529 match v.trim().to_ascii_lowercase().as_str() {
530 "hashedbysolid" | "hashed" => self.face_color_mode = FaceColorMode::HashedBySolid,
531 "uniform" => self.face_color_mode = FaceColorMode::Uniform,
532 _ => {}
533 }
534 }
535 if let Some(v) = value.get("theme").and_then(|v| v.as_str()) {
536 match v.trim().to_ascii_lowercase().as_str() {
537 "auto" => self.theme = ThemeMode::Auto,
538 "light" => self.theme = ThemeMode::Light,
539 "dark" => self.theme = ThemeMode::Dark,
540 _ => {}
541 }
542 }
543 if let Some(v) = value.get("uiScale").and_then(|v| v.as_f64()) {
544 self.ui_scale = (v as f32).clamp(0.5, 3.0);
545 }
546 if let Some(v) = value.get("disableRecoveryPrompt").and_then(|v| v.as_bool()) {
547 self.disable_recovery_prompt = v;
548 }
549 if let Some(v) = value.get("disableStartupModel").and_then(|v| v.as_bool()) {
550 self.disable_startup_model = v;
551 }
552 // Model-overlay label size. Clamped to the SAME [0.25, 3.0] domain the
553 // settings slider offers, so a persisted value never silently re-clamps on
554 // reload (the `viewcubeSizePx` rule).
555 if let Some(v) = value.get("labelScale").and_then(|v| v.as_f64()) {
556 self.label_scale = (v as f32).clamp(0.25, 3.0);
557 }
558 if let Some(v) = value.get("debugGrabHandles").and_then(|v| v.as_bool()) {
559 self.debug_grab_handles = v;
560 }
561 if let Some(v) = value.get("flatShading").and_then(|v| v.as_bool()) {
562 self.flat_shading = v;
563 }
564 if let Some(v) = value.get("wireframe").and_then(|v| v.as_bool()) {
565 self.wireframe = v;
566 }
567 if let Some(v) = value.get("showFaces").and_then(|v| v.as_bool()) {
568 self.show_faces = v;
569 }
570 if let Some(v) = value.get("showEdges").and_then(|v| v.as_bool()) {
571 self.show_edges = v;
572 }
573 if let Some(v) = value.get("showVertices").and_then(|v| v.as_bool()) {
574 self.show_vertices = v;
575 }
576 if let Some(v) = value.get("overrideModelColors").and_then(|v| v.as_bool()) {
577 self.override_model_colors = v;
578 }
579 if let Some(v) = value.get("toolbarStyle").and_then(|v| v.as_str()) {
580 self.toolbar_style = match v {
581 "Ribbon" => ToolbarStyle::Ribbon,
582 "Classic" => ToolbarStyle::Classic,
583 _ => return Err(format!("unknown toolbar style: {v}")),
584 };
585 }
586 if let Some(v) = value.get("showWorkbenchToolbar").and_then(|v| v.as_bool()) {
587 self.show_workbench_toolbar = v;
588 }
589 if let Some(v) = value.get("axisLengthPx").and_then(|v| v.as_f64()) {
590 self.axis_length_px = (v as f32).clamp(0.0, 512.0);
591 }
592 // ViewCube corner size — clamp to the SAME [40, 230] domain the settings
593 // slider offers, so a persisted value never silently re-clamps on reload.
594 if let Some(v) = value.get("viewcubeSizePx").and_then(|v| v.as_f64()) {
595 self.viewcube_size_px = (v as f32).clamp(40.0, 230.0);
596 }
597 if let Some(v) = value.get("pickDoubleSided").and_then(|v| v.as_bool()) {
598 self.pick_double_sided = v;
599 }
600 // The multi-select mode dropdown serializes its human label (the
601 // renderQuality pattern); match on the alphanumeric skeleton so
602 // "Ctrl+Click" / "ctrlClick" / "CTRL CLICK" all parse.
603 if let Some(v) = value.get("multiSelect").and_then(|v| v.as_str()) {
604 let skeleton: String = v
605 .chars()
606 .filter(|c| c.is_ascii_alphanumeric())
607 .collect::<String>()
608 .to_ascii_lowercase();
609 match skeleton.as_str() {
610 "ctrlclick" => self.multi_select = MultiSelectMode::CtrlClick,
611 "clicktoggles" => self.multi_select = MultiSelectMode::ClickToggles,
612 _ => {}
613 }
614 }
615 if let Some(v) = value.get("spacemouseEnabled").and_then(|v| v.as_bool()) {
616 self.spacemouse_enabled = v;
617 }
618 if let Some(v) = value.get("spacemouseSensitivity").and_then(|v| v.as_f64()) {
619 self.spacemouse_sensitivity = (v as f32).clamp(0.1, 5.0);
620 }
621 for (slot, (key, _)) in self.spacemouse_invert.iter_mut().zip(SPACEMOUSE_AXES) {
622 if let Some(v) = value.get(key).and_then(|v| v.as_bool()) {
623 *slot = v;
624 }
625 }
626 // The active UI workbench id (a plain string; the app validates it against
627 // its registry). Stored verbatim — an unknown id is tolerated here —
628 // except a RETIRED id, which is rewritten to its successor on read so
629 // a document or settings file saved before the retirement opens there.
630 if let Some(v) = value.get("workbench").and_then(|v| v.as_str()) {
631 self.workbench = successor_workbench(v).to_string();
632 }
633 if let Some(v) = value.get("assemblyAutoSolve").and_then(|v| v.as_bool()) {
634 self.assembly_auto_solve = v;
635 }
636 // The BOM column configuration, verbatim (see the field docs) — never
637 // normalized here, so a malformed line survives a save/reload and the
638 // panel can still point at the line the user has to fix.
639 if let Some(v) = value.get("bomColumns").and_then(|v| v.as_str()) {
640 self.bom_columns = v.to_string();
641 }
642 if let Some(v) = value.get("showConstraintGraphics").and_then(|v| v.as_bool()) {
643 self.show_constraint_graphics = v;
644 }
645 // "Render Quality" is a named dropdown (Draft…Ultra) mapping to the display
646 // LOD factor (higher quality = finer mesh = smaller factor). We store the
647 // resolved f64 so the tessellation path is unchanged.
648 if let Some(label) = value.get("renderQuality").and_then(|v| v.as_str()) {
649 if let Some(lod) = lod_from_quality(label) {
650 self.lod_factor = lod;
651 }
652 }
653 Ok(())
654 }
655
656 /// Serialize EVERY setting to the SAME camelCase / CSS-hex shape
657 /// [`apply_json`](Self::apply_json) reads, so `s.apply_json(&s.to_json())` is the identity.
658 /// This is the counterpart the settings schema serializes/persists through
659 /// (there was previously no serializer, only the partial-override reader).
660 pub fn to_json(&self) -> String {
661 let mut json = serde_json::json!({
662 "theme": match self.theme {
663 ThemeMode::Auto => "auto",
664 ThemeMode::Light => "light",
665 ThemeMode::Dark => "dark",
666 },
667 "uiScale": self.ui_scale as f64,
668 "disableRecoveryPrompt": self.disable_recovery_prompt,
669 "disableStartupModel": self.disable_startup_model,
670 "labelScale": self.label_scale as f64,
671 "debugGrabHandles": self.debug_grab_handles,
672 "background": rgb_to_css_hex(self.background),
673 "faceColorMode": match self.face_color_mode {
674 FaceColorMode::Uniform => "uniform",
675 FaceColorMode::HashedBySolid => "hashedBySolid",
676 },
677 "faceColor": rgba_to_css_hex(self.face_color),
678 "faceSelectedColor": rgba_to_css_hex(self.face_selected_color),
679 "hoverColor": rgba_to_css_hex(self.hover_color),
680 "edgeColor": rgba_to_css_hex(self.edge_color),
681 "edgeSelectedColor": rgba_to_css_hex(self.edge_selected_color),
682 "edgeWidthPx": self.edge_width_px as f64,
683 "showOccludedEdges": self.show_occluded_edges,
684 "hiddenEdgeAlpha": self.hidden_edge_alpha as f64,
685 "vertexColor": rgba_to_css_hex(self.vertex_color),
686 "vertexSelectedColor": rgba_to_css_hex(self.vertex_selected_color),
687 "vertexSizePx": self.vertex_size_px as f64,
688 "flatShading": self.flat_shading,
689 "wireframe": self.wireframe,
690 "showFaces": self.show_faces,
691 "showEdges": self.show_edges,
692 "showVertices": self.show_vertices,
693 "overrideModelColors": self.override_model_colors,
694 "showWorkbenchToolbar": self.show_workbench_toolbar,
695 "toolbarStyle": self.toolbar_style.as_str(),
696 "axisLengthPx": self.axis_length_px as f64,
697 "viewcubeSizePx": self.viewcube_size_px as f64,
698 "pickDoubleSided": self.pick_double_sided,
699 "multiSelect": self.multi_select.label(),
700 "spacemouseEnabled": self.spacemouse_enabled,
701 "spacemouseSensitivity": self.spacemouse_sensitivity as f64,
702 "renderQuality": quality_from_lod(self.lod_factor),
703 "sketchMovableColor": rgba_to_css_hex(self.sketch_movable_color),
704 "sketchLockedColor": rgba_to_css_hex(self.sketch_locked_color),
705 "sketchGeometryColor": rgba_to_css_hex(self.sketch_geometry_color),
706 "sketchPointColor": rgba_to_css_hex(self.sketch_point_color),
707 "sketchConstructionPointColor": rgba_to_css_hex(self.sketch_construction_point_color),
708 "sketchUnderConstrainedPointColor": rgba_to_css_hex(self.sketch_under_constrained_point_color),
709 "sketchSelectedColor": rgba_to_css_hex(self.sketch_selected_color),
710 "sketchHoveredColor": rgba_to_css_hex(self.sketch_hovered_color),
711 "sketchPreviewColor": rgba_to_css_hex(self.sketch_preview_color),
712 "sketchConstraintColor": rgba_to_css_hex(self.sketch_constraint_color),
713 "sketchConflictColor": rgba_to_css_hex(self.sketch_conflict_color),
714 "workbench": self.workbench,
715 "assemblyAutoSolve": self.assembly_auto_solve,
716 "showConstraintGraphics": self.show_constraint_graphics,
717 "bomColumns": self.bom_columns,
718 });
719 for ((key, _), invert) in SPACEMOUSE_AXES.iter().zip(self.spacemouse_invert) {
720 json[*key] = serde_json::Value::Bool(invert);
721 }
722 json.to_string()
723 }
724
725 /// The live [`SketchColors`] view of the sketcher palette — the tessellation /
726 /// overlay builders read their colors from THIS (via
727 /// [`crate::sketch::SketchSession::colors`]) so the display settings are the one
728 /// source of truth. Each `Rgba` is quantized back to `0xRRGGBB` the SAME way
729 /// `rgb_to_css_hex` serializes it, so a default settings value round-trips to
730 /// the default `SketchColors` byte-exact.
731 pub fn sketch_colors(&self) -> SketchColors {
732 SketchColors {
733 movable: rgba_to_u32(self.sketch_movable_color),
734 locked: rgba_to_u32(self.sketch_locked_color),
735 geometry: rgba_to_u32(self.sketch_geometry_color),
736 point: rgba_to_u32(self.sketch_point_color),
737 construction_point: rgba_to_u32(self.sketch_construction_point_color),
738 under_constrained_point: rgba_to_u32(self.sketch_under_constrained_point_color),
739 selected: rgba_to_u32(self.sketch_selected_color),
740 hovered: rgba_to_u32(self.sketch_hovered_color),
741 preview: rgba_to_u32(self.sketch_preview_color),
742 constraint: rgba_to_u32(self.sketch_constraint_color),
743 conflict: rgba_to_u32(self.sketch_conflict_color),
744 }
745 }
746
747 /// The settings schema WITH the current value baked into each field, as JSON
748 /// — mirrors the kernel's `feature_schemas_json` export so a UI shell (egui
749 /// here, a later `brep-ui` crate) can generate the whole form from data. The
750 /// `value` of each field is pulled live from [`to_json`](Self::to_json), so the export
751 /// always reflects the current settings.
752 pub fn settings_schema_json(&self) -> String {
753 let current: serde_json::Value =
754 serde_json::from_str(&self.to_json()).unwrap_or(serde_json::Value::Null);
755 let fields: Vec<serde_json::Value> = settings_schema()
756 .iter()
757 .map(|field| {
758 let kind = match &field.kind {
759 FieldKind::Color => serde_json::json!({ "type": "color" }),
760 FieldKind::Bool => serde_json::json!({ "type": "bool" }),
761 FieldKind::Enum { variants, .. } => {
762 serde_json::json!({ "type": "enum", "variants": variants })
763 }
764 FieldKind::Number { min, max, step } => serde_json::json!({
765 "type": "number", "min": min, "max": max, "step": step
766 }),
767 FieldKind::Range { min, max, step } => serde_json::json!({
768 "type": "range", "min": min, "max": max, "step": step
769 }),
770 // The feature-dialog kinds never appear in the settings
771 // schema, but the match must stay exhaustive.
772 FieldKind::Scalar { step } => {
773 serde_json::json!({ "type": "scalar", "step": step })
774 }
775 FieldKind::BoundedScalar { min, max, step } => serde_json::json!({
776 "type": "scalar", "min": min, "max": max, "step": step
777 }),
778 FieldKind::Text { read_only } => {
779 serde_json::json!({ "type": "text", "readOnly": read_only })
780 }
781 FieldKind::Vec3 { step } => serde_json::json!({ "type": "vec3", "step": step }),
782 FieldKind::Reference { filter, multiple } => serde_json::json!({
783 "type": "reference", "filter": filter, "multiple": multiple
784 }),
785 FieldKind::Button { label } => {
786 serde_json::json!({ "type": "button", "label": label })
787 }
788 };
789 serde_json::json!({
790 "key": field.key,
791 "label": field.label,
792 "group": field.group,
793 "kind": kind,
794 "value": current.get(field.key),
795 })
796 })
797 .collect();
798 serde_json::json!({ "fields": fields }).to_string()
799 }
800}
801
802/// Quantize an sRGB channel triple to a `#rrggbb` CSS hex string (the shape
803/// [`RenderSettings::apply_json`] parses back).
804fn rgb_to_css_hex(rgb: [f32; 3]) -> String {
805 format!("#{:06x}", rgba_to_u32([rgb[0], rgb[1], rgb[2], 1.0]))
806}
807
808/// Like [`rgb_to_css_hex`] but for an `Rgba` (the alpha is intentionally dropped
809/// — `apply_json` only overrides the rgb channels, preserving existing alpha).
810fn rgba_to_css_hex(rgba: Rgba) -> String {
811 rgb_to_css_hex([rgba[0], rgba[1], rgba[2]])
812}
813
814/// Clamp and round sRGB channels to packed `0xRRGGBB`, dropping alpha.
815/// Shared by CSS serialization and the sketch palette.
816fn rgba_to_u32(rgba: Rgba) -> u32 {
817 let q = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u32;
818 (q(rgba[0]) << 16) | (q(rgba[1]) << 8) | q(rgba[2])
819}
820
821/// The kind of one settings field — the closed set of widget shapes the generic
822/// form renderer knows how to emit. Plain data, NO egui dependency: the schema
823/// lives in the engine, the renderer (brep-app / a later brep-ui) walks it.
824#[derive(Debug, Clone, PartialEq)]
825pub enum FieldKind {
826 /// An sRGB color (`#rrggbb`) → a color picker button.
827 Color,
828 /// A boolean toggle → a checkbox.
829 Bool,
830 /// A closed choice → a combo box. `variants` are the JSON string values
831 /// (exactly what `apply_json` accepts / `to_json` emits). `labels` are what
832 /// the box shows for them, parallel to `variants`; empty (or a missing
833 /// entry) shows the value itself. A feature schema sets them with
834 /// `optionLabels` (`{value: label}`), so a stored key can read as words.
835 Enum { variants: Vec<String>, labels: Vec<String> },
836 /// A bounded number → a slider / drag-value honoring `min`/`max`/`step`.
837 Number { min: f64, max: f64, step: f64 },
838 /// A 0..1 (or otherwise fractional) number → a slider honoring the bounds.
839 Range { min: f64, max: f64, step: f64 },
840 // --- extra kinds the FEATURE dialogs need (settings never use these) -------
841 /// An UNBOUNDED number (feature params carry no min/max) → a drag value.
842 Scalar { step: f64 },
843 /// A scalar text field whose numeric edits are bounded on commit. Drawing
844 /// the field never clamps or quantizes its existing value.
845 BoundedScalar { min: f64, max: f64, step: f64 },
846 /// A single-line text edit. `read_only` protects identity fields whose
847 /// renaming must also update references.
848 Text { read_only: bool },
849 /// A 3-vector (position / rotationEuler / scale) → three drag values.
850 Vec3 { step: f64 },
851 /// A reference-selection field for viewport picking. `filter` limits entity
852 /// kinds (e.g. `["SOLID"]`); `multiple` allows a list of selections.
853 Reference { filter: Vec<String>, multiple: bool },
854 /// An ACTION button (schema `"type":"button"`) → a clickable button. It binds
855 /// to no value; a click is surfaced to the caller by the field `key` (e.g.
856 /// `editSketch`), which the host acts on. `label` is the button caption.
857 Button { label: String },
858}
859
860/// One field of the settings form: the camelCase `apply_json`/`to_json` key, a
861/// human label, a UI group, and the widget `kind`. The ordered list of these
862/// (see [`settings_schema`]) fully describes the form — a UI shell generates a
863/// widget per field with no per-field code.
864#[derive(Debug, Clone)]
865pub struct SettingsField {
866 /// The camelCase key — the SAME one `apply_json`/`to_json` use.
867 pub key: &'static str,
868 pub label: &'static str,
869 pub group: &'static str,
870 pub kind: FieldKind,
871}
872
873/// The GENERAL form field — the schema element ONE form engine renders for BOTH
874/// the display-settings dialog AND the schema-driven feature dialogs. Unlike
875/// [`SettingsField`] (which uses `&'static str` because the settings schema is
876/// compile-time), this owns its strings so it can carry a per-feature schema
877/// pulled from the kernel catalogue at run time, and it carries a `path` (a
878/// chain of JSON object keys) so a field can bind to a NESTED value —
879/// `["transform","position"]`, `["boolean","operation"]` — not just a top-level
880/// key. The settings form is `path == [key]`.
881#[derive(Debug, Clone)]
882pub struct FormField {
883 /// JSON object-key chain into the document the form edits (≥ 1 segment).
884 pub path: Vec<String>,
885 pub label: String,
886 pub group: String,
887 pub kind: FieldKind,
888}
889
890impl FormField {
891 /// The last path segment — a stable per-field id for egui salting / probing.
892 pub fn key(&self) -> &str {
893 self.path.last().map(String::as_str).unwrap_or("")
894 }
895}
896
897/// The "Render Quality" dropdown levels shown in Settings, each mapped to a
898/// display-tessellation LOD factor. Higher quality = finer mesh = SMALLER factor
899/// (chord tolerance = extent · 1.5e-3 · factor). Order is coarse→fine, the order
900/// the ComboBox lists them. `lod_factor` stays the internal representation the
901/// tessellation path reads; only the SETTINGS UI/serialization speaks in levels.
902pub const RENDER_QUALITY: &[(&str, f64)] = &[
903 ("Draft", 4.0),
904 ("Low", 2.0),
905 ("Medium", 1.0),
906 ("High", 0.5),
907 ("Ultra", 0.25),
908];
909
910/// The LOD factor for a quality label (`None` if not a known level).
911fn lod_from_quality(label: &str) -> Option<f64> {
912 RENDER_QUALITY
913 .iter()
914 .find(|(name, _)| *name == label)
915 .map(|(_, factor)| *factor)
916}
917
918/// The quality label NEAREST a LOD factor — the serialization inverse of
919/// [`lod_from_quality`]. A stored factor is always one of the level values in
920/// normal use; nearest-match keeps a hand-set/legacy value mapping to a sane label.
921fn quality_from_lod(lod: f64) -> &'static str {
922 RENDER_QUALITY
923 .iter()
924 .min_by(|(_, a), (_, b)| {
925 (a - lod).abs().total_cmp(&(b - lod).abs())
926 })
927 .map(|(name, _)| *name)
928 .unwrap_or("Medium")
929}
930
931/// Lift the compile-time display-settings schema into general [`FormField`]s so
932/// the ONE `field_input` engine (which the feature dialogs also use) renders the
933/// settings panel too — a single schema-driven dialog engine, not two.
934pub fn settings_form_fields() -> Vec<FormField> {
935 settings_schema()
936 .into_iter()
937 .map(|field| FormField {
938 path: vec![field.key.to_string()],
939 label: field.label.to_string(),
940 group: field.group.to_string(),
941 kind: field.kind,
942 })
943 .collect()
944}
945
946/// The SpaceMouse invert settings, `(json key, label)`, in the device's HID
947/// axis order: translation x, y, z then rotation x, y, z. HID's frame is x to
948/// the right, y toward the user, z down, so its y is push / pull (zoom) and
949/// its z is lift / press (pan up / down); rotation about x tilts the cap
950/// forward / back, about y rolls it sideways, about z spins it.
951pub const SPACEMOUSE_AXES: [(&str, &str); 6] = [
952 ("spacemouseInvertPanX", "Invert pan left / right"),
953 ("spacemouseInvertZoom", "Invert zoom (push / pull)"),
954 ("spacemouseInvertPanY", "Invert pan up / down"),
955 ("spacemouseInvertTilt", "Invert tilt"),
956 ("spacemouseInvertRoll", "Invert roll"),
957 ("spacemouseInvertSpin", "Invert spin"),
958];
959
960/// The Rust-owned settings schema: the ordered list of display-settings fields,
961/// grouped, analogous to the kernel feature schemas. Adding a field here (plus
962/// its `apply_json`/`to_json` handling) makes the whole UI grow a widget for it
963/// with ZERO renderer changes.
964pub fn settings_schema() -> Vec<SettingsField> {
965 let f = |key, label, group, kind| SettingsField { key, label, group, kind };
966 vec![
967 // --- Appearance ----------------------------------------------------
968 // FIRST so the "Appearance" group renders at the TOP of the settings tree
969 // (groups are ordered by first field appearance). The GUI-chrome theme —
970 // NOT the 3D viewport background (that lives under Scene).
971 f(
972 "theme",
973 "Theme",
974 "Appearance",
975 FieldKind::Enum { variants: ["auto", "light", "dark"].iter().map(|s| s.to_string()).collect(), labels: Vec::new() },
976 ),
977 // A SLIDER (both `Range` and `Number` render an `egui::Slider` over the
978 // given domain) scaling the whole egui UI via `Context::set_zoom_factor`.
979 f(
980 "uiScale",
981 "UI scale",
982 "Appearance",
983 FieldKind::Range { min: 0.5, max: 3.0, step: 0.05 },
984 ),
985 // The size of the floating text labels overlaid on the MODEL (dimension
986 // value chips, constraint chips, gizmo axis letters) — a multiplier over
987 // their base monospace size, NOT a point size. Bounds MATCH the
988 // `apply_json` clamp so the slider can't set a value that re-clamps on
989 // reload. The 0.25 floor (a quarter of the base, on the 0.05 step) is the
990 // smallest chip whose click/drag target a pointer can still land on — see
991 // `RenderSettings::label_scale`. Separate from `uiScale`, which sizes the
992 // egui chrome.
993 f(
994 "labelScale",
995 "Label scale",
996 "Appearance",
997 FieldKind::Range { min: 0.25, max: 3.0, step: 0.05 },
998 ),
999 // The workbench actions toolbar (the feature-button strip under the
1000 // primary toolbar). Chrome, so it sits with the other chrome settings.
1001 f(
1002 "showWorkbenchToolbar",
1003 "Show workbench actions toolbar",
1004 "Appearance",
1005 FieldKind::Bool,
1006 ),
1007 f("toolbarStyle", "Toolbar style", "Appearance",
1008 FieldKind::Enum { variants: ["Ribbon", "Classic"].iter().map(|s| s.to_string()).collect(), labels: Vec::new() }),
1009 // --- Startup -------------------------------------------------------
1010 f(
1011 "disableRecoveryPrompt",
1012 "Disable recovery dialog on startup",
1013 "Startup",
1014 FieldKind::Bool,
1015 ),
1016 f(
1017 "disableStartupModel",
1018 "Start with an empty document",
1019 "Startup",
1020 FieldKind::Bool,
1021 ),
1022 // --- Scene ---------------------------------------------------------
1023 f("background", "Background", "Scene", FieldKind::Color),
1024 f(
1025 "axisLengthPx",
1026 "Axis length (px)",
1027 "Scene",
1028 FieldKind::Number { min: 0.0, max: 512.0, step: 1.0 },
1029 ),
1030 // The corner ViewCube's on-screen size. Bounds MATCH the `apply_json` clamp
1031 // ([40, 230], centered on the 135px default) so the slider can't set a value
1032 // that re-clamps on reload. Renders as an `egui::Slider`.
1033 f(
1034 "viewcubeSizePx",
1035 "ViewCube size (px)",
1036 "Scene",
1037 FieldKind::Number { min: 40.0, max: 230.0, step: 1.0 },
1038 ),
1039 f(
1040 "renderQuality",
1041 "Render Quality",
1042 "Scene",
1043 FieldKind::Enum { variants: RENDER_QUALITY.iter().map(|(label, _)| label.to_string()).collect(), labels: Vec::new() },
1044 ),
1045 // --- Faces ---------------------------------------------------------
1046 f(
1047 "faceColorMode",
1048 "Face color mode",
1049 "Faces",
1050 FieldKind::Enum { variants: ["uniform", "hashedBySolid"].iter().map(|s| s.to_string()).collect(), labels: Vec::new() },
1051 ),
1052 f("faceColor", "Face color", "Faces", FieldKind::Color),
1053 f("faceSelectedColor", "Selected face", "Faces", FieldKind::Color),
1054 f("hoverColor", "Hover", "Faces", FieldKind::Color),
1055 f("flatShading", "Flat shading", "Faces", FieldKind::Bool),
1056 f("wireframe", "Wireframe", "Faces", FieldKind::Bool),
1057 f("showFaces", "Show faces", "Faces", FieldKind::Bool),
1058 f(
1059 "overrideModelColors",
1060 "Override model colors",
1061 "Faces",
1062 FieldKind::Bool,
1063 ),
1064 // --- Edges ---------------------------------------------------------
1065 f("showEdges", "Show edges", "Edges", FieldKind::Bool),
1066 f("edgeColor", "Edge color", "Edges", FieldKind::Color),
1067 f("edgeSelectedColor", "Selected edge", "Edges", FieldKind::Color),
1068 f(
1069 "edgeWidthPx",
1070 "Edge width (px)",
1071 "Edges",
1072 FieldKind::Number { min: 0.0, max: 32.0, step: 0.1 },
1073 ),
1074 f("showOccludedEdges", "Show occluded edges", "Edges", FieldKind::Bool),
1075 f(
1076 "hiddenEdgeAlpha",
1077 "Hidden-edge alpha",
1078 "Edges",
1079 FieldKind::Range { min: 0.0, max: 1.0, step: 0.01 },
1080 ),
1081 // --- Vertices ------------------------------------------------------
1082 f("showVertices", "Show vertices", "Vertices", FieldKind::Bool),
1083 f("vertexColor", "Vertex color", "Vertices", FieldKind::Color),
1084 f("vertexSelectedColor", "Selected vertex", "Vertices", FieldKind::Color),
1085 f(
1086 "vertexSizePx",
1087 "Vertex size (px)",
1088 "Vertices",
1089 FieldKind::Number { min: 0.0, max: 64.0, step: 0.5 },
1090 ),
1091 // --- Picking -------------------------------------------------------
1092 f("pickDoubleSided", "Pick double-sided", "Picking", FieldKind::Bool),
1093 // How a plain viewport click builds a multi-selection: the classic
1094 // Ctrl+Click add, or modifier-free click-toggles (click an item to add
1095 // it, click it again to remove it).
1096 f(
1097 "multiSelect",
1098 "Multi-select",
1099 "Picking",
1100 FieldKind::Enum {
1101 variants: MultiSelectMode::ALL.iter().map(|m| m.label().to_string()).collect(),
1102 labels: Vec::new(),
1103 },
1104 ),
1105 // --- Sketch --------------------------------------------------------
1106 // The sketcher overlay palette, editable live like every other display
1107 // color. `sketch_colors()` feeds these to the tessellation/overlay builders.
1108 f("sketchMovableColor", "Movable geometry", "Sketch", FieldKind::Color),
1109 f("sketchLockedColor", "Locked geometry", "Sketch", FieldKind::Color),
1110 f("sketchGeometryColor", "Geometry (no mobility)", "Sketch", FieldKind::Color),
1111 f("sketchPointColor", "Point", "Sketch", FieldKind::Color),
1112 f("sketchConstructionPointColor", "Construction point", "Sketch", FieldKind::Color),
1113 f("sketchUnderConstrainedPointColor", "Under-constrained point", "Sketch", FieldKind::Color),
1114 f("sketchSelectedColor", "Selected", "Sketch", FieldKind::Color),
1115 f("sketchHoveredColor", "Hovered", "Sketch", FieldKind::Color),
1116 f("sketchPreviewColor", "Draw preview", "Sketch", FieldKind::Color),
1117 f("sketchConstraintColor", "Constraint / dimension", "Sketch", FieldKind::Color),
1118 f("sketchConflictColor", "Conflicting constraint", "Sketch", FieldKind::Color),
1119 // --- SpaceMouse ----------------------------------------------------
1120 // A 6-DoF navigation device (SpaceMouse / Spaceball). The slider's
1121 // domain MATCHES the `apply_json` clamp. One flip per device axis.
1122 f("spacemouseEnabled", "Use SpaceMouse / Spaceball", "SpaceMouse", FieldKind::Bool),
1123 f(
1124 "spacemouseSensitivity",
1125 "Speed",
1126 "SpaceMouse",
1127 FieldKind::Range { min: 0.1, max: 5.0, step: 0.05 },
1128 ),
1129 f(SPACEMOUSE_AXES[0].0, SPACEMOUSE_AXES[0].1, "SpaceMouse", FieldKind::Bool),
1130 f(SPACEMOUSE_AXES[2].0, SPACEMOUSE_AXES[2].1, "SpaceMouse", FieldKind::Bool),
1131 f(SPACEMOUSE_AXES[1].0, SPACEMOUSE_AXES[1].1, "SpaceMouse", FieldKind::Bool),
1132 f(SPACEMOUSE_AXES[3].0, SPACEMOUSE_AXES[3].1, "SpaceMouse", FieldKind::Bool),
1133 f(SPACEMOUSE_AXES[5].0, SPACEMOUSE_AXES[5].1, "SpaceMouse", FieldKind::Bool),
1134 f(SPACEMOUSE_AXES[4].0, SPACEMOUSE_AXES[4].1, "SpaceMouse", FieldKind::Bool),
1135 // --- Debug ---------------------------------------------------------
1136 // LAST so the "Debug" group renders at the BOTTOM of the settings tree.
1137 f("debugGrabHandles", "Debug grab handles", "Debug", FieldKind::Bool),
1138 ]
1139}
1140
1141/// A selected/hovered vertex reference: vertices have no kernel names, so they
1142/// resolve by owning solid + position.
1143#[derive(Debug, Clone)]
1144pub struct VertexRef {
1145 pub solid: String,
1146 pub position: [f64; 3],
1147}
1148
1149/// A set of entity NAMES that remembers the order they were ADDED in — the
1150/// selection's pick order.
1151///
1152/// The selection used to be a plain `HashSet`, so which of two picked faces
1153/// came out first was the hash seed's choice and differed between processes.
1154/// That is not cosmetic: an assembly Distance takes element 0 as its BASE face,
1155/// whose outward normal gives the value its sign and the arrow its direction,
1156/// so the same two picks could seed opposite constraints in two runs. Every
1157/// reader of the selection — [`EngineState::selection_json`](crate::engine_state::EngineState::selection_json), the context bar's
1158/// feature offers, the constraint seeder — now sees the picks in the order they
1159/// were made.
1160///
1161/// [`insert`](Self::insert) appends, and a name already in the set keeps its
1162/// place; [`remove`](Self::remove) keeps the rest in order. Toggling a name off
1163/// and on therefore moves it to the END, which is where a re-pick belongs.
1164/// Membership rides in a `HashSet` beside the order, because `contains` is
1165/// called for every face and every edge of every solid, every frame, by the
1166/// emphasis colour feed.
1167#[derive(Debug, Clone, Default, PartialEq, Eq)]
1168pub struct OrderedNames {
1169 order: Vec<String>,
1170 index: HashSet<String>,
1171}
1172
1173impl OrderedNames {
1174 /// Add `name` at the END. Returns whether it was not already there (the
1175 /// `HashSet::insert` contract), and an already-present name does NOT move.
1176 pub fn insert(&mut self, name: String) -> bool {
1177 if !self.index.insert(name.clone()) {
1178 return false;
1179 }
1180 self.order.push(name);
1181 true
1182 }
1183
1184 /// Drop `name`, keeping the order of everything else. Returns whether it
1185 /// was there (the `HashSet::remove` contract).
1186 pub fn remove(&mut self, name: &str) -> bool {
1187 if !self.index.remove(name) {
1188 return false;
1189 }
1190 self.order.retain(|n| n != name);
1191 true
1192 }
1193
1194 pub fn contains(&self, name: &str) -> bool {
1195 self.index.contains(name)
1196 }
1197
1198 pub fn clear(&mut self) {
1199 self.order.clear();
1200 self.index.clear();
1201 }
1202
1203 pub fn len(&self) -> usize {
1204 self.order.len()
1205 }
1206
1207 pub fn is_empty(&self) -> bool {
1208 self.order.is_empty()
1209 }
1210
1211 /// The names in PICK ORDER, oldest first.
1212 pub fn iter(&self) -> std::slice::Iter<'_, String> {
1213 self.order.iter()
1214 }
1215}
1216
1217impl FromIterator<String> for OrderedNames {
1218 fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> Self {
1219 let mut out = Self::default();
1220 for name in iter {
1221 out.insert(name);
1222 }
1223 out
1224 }
1225}
1226
1227impl Extend<String> for OrderedNames {
1228 fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1229 for name in iter {
1230 self.insert(name);
1231 }
1232 }
1233}
1234
1235impl<'a> IntoIterator for &'a OrderedNames {
1236 type Item = &'a String;
1237 type IntoIter = std::slice::Iter<'a, String>;
1238 fn into_iter(self) -> Self::IntoIter {
1239 self.order.iter()
1240 }
1241}
1242
1243/// The emphasis state (selection + hover), name-keyed like `SelectionFilter`.
1244/// Solid-level emphasis cascades to that solid's faces/edges (the
1245/// `SelectionState._applyToSolid` behavior).
1246#[derive(Debug, Default, Clone)]
1247pub struct Emphasis {
1248 pub selected_solids: OrderedNames,
1249 pub selected_faces: OrderedNames,
1250 pub selected_edges: OrderedNames,
1251 pub selected_vertices: Vec<VertexRef>,
1252 /// Selected construction datum/plane FRAMES, keyed by frame NAME (`{id}:XY`
1253 /// for a DATUM base plane, `{id}` for a PLANE feature). Datums carry no
1254 /// resident geometry, so — like the render-color feed — they emphasize purely
1255 /// by name; a selected datum is re-colored with the selection accent when the
1256 /// engine re-feeds the datum planes.
1257 pub selected_datums: OrderedNames,
1258 pub hovered_solids: HashSet<String>,
1259 pub hovered_faces: HashSet<String>,
1260 pub hovered_edges: HashSet<String>,
1261 pub hovered_vertices: Vec<VertexRef>,
1262 /// HOVERED construction datum/plane FRAMES — the hover twin of
1263 /// [`selected_datums`](Self::selected_datums), keyed the same way. Construction
1264 /// planes are ordinary pick candidates, so the pointer (and a pick-list row)
1265 /// pre-highlights one exactly like a face; the accent is applied when the engine
1266 /// re-feeds the datum planes.
1267 pub hovered_datums: HashSet<String>,
1268 /// Bumped on every change — cache key for derived GPU state.
1269 pub generation: u64,
1270}
1271
1272impl Emphasis {
1273 pub fn is_empty(&self) -> bool {
1274 self.selected_solids.is_empty()
1275 && self.selected_faces.is_empty()
1276 && self.selected_edges.is_empty()
1277 && self.selected_vertices.is_empty()
1278 && self.selected_datums.is_empty()
1279 && self.hovered_solids.is_empty()
1280 && self.hovered_faces.is_empty()
1281 && self.hovered_edges.is_empty()
1282 && self.hovered_vertices.is_empty()
1283 && self.hovered_datums.is_empty()
1284 }
1285
1286 /// Replace the whole emphasis state from the R3 JSON shape:
1287 /// `{selected: {solids, faces, edges, vertices:[{solid,position}]}, hovered: {...}}`.
1288 pub fn apply_json(&mut self, json: &str) -> Result<(), String> {
1289 let value: serde_json::Value =
1290 serde_json::from_str(json).map_err(|error| format!("emphasis parse: {error}"))?;
1291 let names = |group: &serde_json::Value, key: &str| -> HashSet<String> {
1292 crate::json_support::string_values(group.get(key))
1293 .map(str::to_string)
1294 .collect()
1295 };
1296 // The SELECTED buckets keep the order they are given: a saved selection
1297 // comes back in the order it was picked in.
1298 let ordered = |group: &serde_json::Value, key: &str| -> OrderedNames {
1299 crate::json_support::string_values(group.get(key))
1300 .map(str::to_string)
1301 .collect()
1302 };
1303 let vertices = |group: &serde_json::Value| -> Vec<VertexRef> {
1304 group
1305 .get("vertices")
1306 .and_then(|v| v.as_array())
1307 .map(|list| {
1308 list.iter()
1309 .filter_map(|v| {
1310 let solid = v.get("solid")?.as_str()?.to_string();
1311 let p = v.get("position")?.as_array()?;
1312 Some(VertexRef {
1313 solid,
1314 position: [
1315 p.first()?.as_f64()?,
1316 p.get(1)?.as_f64()?,
1317 p.get(2)?.as_f64()?,
1318 ],
1319 })
1320 })
1321 .collect()
1322 })
1323 .unwrap_or_default()
1324 };
1325 let empty = serde_json::json!({});
1326 let selected = value.get("selected").unwrap_or(&empty);
1327 let hovered = value.get("hovered").unwrap_or(&empty);
1328 self.selected_solids = ordered(selected, "solids");
1329 self.selected_faces = ordered(selected, "faces");
1330 self.selected_edges = ordered(selected, "edges");
1331 self.selected_datums = ordered(selected, "datums");
1332 self.selected_vertices = vertices(selected);
1333 self.hovered_solids = names(hovered, "solids");
1334 self.hovered_faces = names(hovered, "faces");
1335 self.hovered_edges = names(hovered, "edges");
1336 self.hovered_datums = names(hovered, "datums");
1337 self.hovered_vertices = vertices(hovered);
1338 self.generation = self.generation.wrapping_add(1);
1339 Ok(())
1340 }
1341}
1342
1343/// The visual state of one displayed face/edge (hover wins over selected, the
1344/// `SelectionState` order).
1345#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1346pub enum EmphasisState {
1347 Base,
1348 Selected,
1349 Hovered,
1350}
1351
1352impl Emphasis {
1353 pub fn face_state(&self, solid: &str, face: &str) -> EmphasisState {
1354 if self.hovered_solids.contains(solid) || (!face.is_empty() && self.hovered_faces.contains(face)) {
1355 EmphasisState::Hovered
1356 } else if self.selected_solids.contains(solid)
1357 || (!face.is_empty() && self.selected_faces.contains(face))
1358 {
1359 EmphasisState::Selected
1360 } else {
1361 EmphasisState::Base
1362 }
1363 }
1364
1365 pub fn edge_state(&self, solid: &str, edge: &str) -> EmphasisState {
1366 if self.hovered_solids.contains(solid) || (!edge.is_empty() && self.hovered_edges.contains(edge)) {
1367 EmphasisState::Hovered
1368 } else if self.selected_solids.contains(solid)
1369 || (!edge.is_empty() && self.selected_edges.contains(edge))
1370 {
1371 EmphasisState::Selected
1372 } else {
1373 EmphasisState::Base
1374 }
1375 }
1376
1377 pub fn vertex_state(&self, solid: &str, position: [f64; 3], tol: f64) -> EmphasisState {
1378 let matches = |refs: &[VertexRef]| {
1379 refs.iter().any(|r| {
1380 r.solid == solid
1381 && (r.position[0] - position[0]).abs() <= tol
1382 && (r.position[1] - position[1]).abs() <= tol
1383 && (r.position[2] - position[2]).abs() <= tol
1384 })
1385 };
1386 if matches(&self.hovered_vertices) {
1387 EmphasisState::Hovered
1388 } else if matches(&self.selected_vertices) {
1389 EmphasisState::Selected
1390 } else {
1391 EmphasisState::Base
1392 }
1393 }
1394}
1395
1396