BREP_render 0.1.0

BREP Rust rendering engine: kernel-fed scene store + wgpu renderer (headless artifact, desktop window, and wasm canvas shells).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
//! Render settings (R14 — the `CADmaterials` semantics: per-kind material
//! variants, hover color, flat-shading toggle, user-persisted overrides) and
//! the selection/hover emphasis state (R17/R24 — name-keyed, fed by the host's
//! `SelectionFilter`). Plain data, shared by the engine core and the wgpu
//! renderer; JSON in/out at the R3 boundary.

use std::collections::HashSet;

/// sRGB color in 0..1 + alpha.
pub type Rgba = [f32; 4];

fn hex(hex: u32, alpha: f32) -> Rgba {
    [
        ((hex >> 16) & 0xff) as f32 / 255.0,
        ((hex >> 8) & 0xff) as f32 / 255.0,
        (hex & 0xff) as f32 / 255.0,
        alpha,
    ]
}

/// Parse `#rrggbb` / `#rgb` / `0xrrggbb` (returns None on anything else).
pub fn parse_css_hex(value: &str) -> Option<[f32; 3]> {
    let v = value.trim();
    let digits = v
        .strip_prefix('#')
        .or_else(|| v.strip_prefix("0x"))
        .or_else(|| v.strip_prefix("0X"))?;
    let expand = |c: char| c.to_digit(16).map(|d| (d * 17) as f32 / 255.0);
    match digits.len() {
        3 => {
            let mut chars = digits.chars();
            Some([
                expand(chars.next()?)?,
                expand(chars.next()?)?,
                expand(chars.next()?)?,
            ])
        }
        6 => {
            let n = u32::from_str_radix(digits, 16).ok()?;
            Some([
                ((n >> 16) & 0xff) as f32 / 255.0,
                ((n >> 8) & 0xff) as f32 / 255.0,
                (n & 0xff) as f32 / 255.0,
            ])
        }
        _ => None,
    }
}

/// The sketcher's overlay palette as plain `0xRRGGBB` hex — the ONE place the
/// default color literals live. [`RenderSettings`] stores each of these as an
/// editable [`Rgba`] field (defaults derived from here via [`hex`]) and hands the
/// sketch tessellation/overlay builders a live `SketchColors` view via
/// [`RenderSettings::sketch_colors`], so the sketch renderer reads its colors from
/// the display settings just like faces/edges/vertices do — no scattered constants.
///
/// The `constraint` green is a deliberate user directive (2026-08-22): CONSTRAINT
/// annotations (geometric-constraint glyphs + dimension leaders/labels) read in
/// green so they stand apart from the blue/white sketch GEOMETRY.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SketchColors {
    /// Movable geometry / point (blue).
    pub movable: u32,
    /// Locked geometry / point (near-white).
    pub locked: u32,
    /// No-mobility geometry fallback (yellow).
    pub geometry: u32,
    /// No-mobility point fallback.
    pub point: u32,
    /// Construction point (orange).
    pub construction_point: u32,
    /// Heuristic under-constrained point.
    pub under_constrained_point: u32,
    /// Selected entity — amber (the transform-gizmo accent); beats hover.
    pub selected: u32,
    /// Hovered entity — light blue (brighter than movable).
    pub hovered: u32,
    /// Draw-tool rubber-band preview (dim, so it reads as tentative).
    pub preview: u32,
    /// Constraint annotations — glyphs + dimension leaders/labels (green).
    pub constraint: u32,
}

impl Default for SketchColors {
    fn default() -> Self {
        // The previous sketcher's theme defaults — the single source of these literals.
        Self {
            movable: 0x4aa3ff,
            locked: 0xe6ebf2,
            geometry: 0xffff88,
            point: 0x9ec9ff,
            construction_point: 0xffa86a,
            under_constrained_point: 0xffb347,
            selected: 0xffa500,
            hovered: 0x7fd0ff,
            preview: 0x8fa0b8,
            constraint: 0x4ade80,
        }
    }
}

/// How base face color is chosen per solid.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FaceColorMode {
    /// The app look: every face gets `face_color` (unless the solid carries a
    /// metadata override).
    Uniform,
    /// The artifact look: stable name-hashed color per solid.
    HashedBySolid,
}

/// The viewer's material palette + display toggles. Defaults are the
/// `CADmaterials` values.
#[derive(Debug, Clone, PartialEq)]
pub struct RenderSettings {
    pub background: [f32; 3],
    pub face_color_mode: FaceColorMode,
    pub face_color: Rgba,
    pub face_selected_color: Rgba,
    pub hover_color: Rgba,
    pub edge_color: Rgba,
    pub edge_selected_color: Rgba,
    pub edge_width_px: f32,
    /// Occluded edges render dimmed, not dropped (R17): alpha of the
    /// depth-failing edge pass. 0 disables the pass.
    pub hidden_edge_alpha: f32,
    pub vertex_color: Rgba,
    pub vertex_selected_color: Rgba,
    pub vertex_size_px: f32,
    pub flat_shading: bool,
    /// Wireframe display (R14): when true the shaded face-fill pass is skipped so
    /// only edges draw (the CAD wireframe look; back edges show through). Does
    /// NOT affect picking (CPU ray-based) or the overlay pass.
    pub wireframe: bool,
    /// World-axis helper (R20): screen length in CSS px; 0 disables.
    pub axis_length_px: f32,
    pub pick_double_sided: bool,
    /// Tessellation LOD factor (1.0 = the app's "Normal" preset).
    pub lod_factor: f64,
    // --- Sketcher overlay palette (managed here like every other display color) ---
    // Defaults come from `SketchColors::default()` (the single source of the
    // literals); `sketch_colors()` re-derives a `SketchColors` view for the
    // tessellation/overlay builders.
    pub sketch_movable_color: Rgba,
    pub sketch_locked_color: Rgba,
    pub sketch_geometry_color: Rgba,
    pub sketch_point_color: Rgba,
    pub sketch_construction_point_color: Rgba,
    pub sketch_under_constrained_point_color: Rgba,
    pub sketch_selected_color: Rgba,
    pub sketch_hovered_color: Rgba,
    pub sketch_preview_color: Rgba,
    pub sketch_constraint_color: Rgba,
}

impl Default for RenderSettings {
    fn default() -> Self {
        let sk = SketchColors::default();
        Self {
            background: [
                ((0x0b) as f32) / 255.0,
                ((0x0d) as f32) / 255.0,
                ((0x10) as f32) / 255.0,
            ],
            face_color_mode: FaceColorMode::Uniform,
            face_color: hex(0x00009e, 1.0),
            face_selected_color: hex(0xffc400, 1.0),
            hover_color: hex(0xfbff00, 1.0),
            edge_color: hex(0x009dff, 1.0),
            edge_selected_color: hex(0xff00ff, 1.0),
            edge_width_px: 2.0,
            hidden_edge_alpha: 0.22,
            vertex_color: hex(0x4aff03, 1.0),
            vertex_selected_color: hex(0x00ffff, 1.0),
            vertex_size_px: 6.0,
            flat_shading: false,
            wireframe: false,
            axis_length_px: 46.0,
            pick_double_sided: true,
            lod_factor: 1.0,
            // Sketch palette: derive each Rgba from the ONE source of the literals
            // (`SketchColors::default`) so nothing changes visually until edited.
            sketch_movable_color: hex(sk.movable, 1.0),
            sketch_locked_color: hex(sk.locked, 1.0),
            sketch_geometry_color: hex(sk.geometry, 1.0),
            sketch_point_color: hex(sk.point, 1.0),
            sketch_construction_point_color: hex(sk.construction_point, 1.0),
            sketch_under_constrained_point_color: hex(sk.under_constrained_point, 1.0),
            sketch_selected_color: hex(sk.selected, 1.0),
            sketch_hovered_color: hex(sk.hovered, 1.0),
            sketch_preview_color: hex(sk.preview, 1.0),
            sketch_constraint_color: hex(sk.constraint, 1.0),
        }
    }
}

impl RenderSettings {
    /// The artifact-corpus preset: byte-faithful to the slice-1 artifact look
    /// (per-solid hashed colors, 0x101418 background, 1.6px edges in
    /// 0x0d1030, no hidden-edge pass, no vertices, no axes).
    pub fn artifact() -> Self {
        Self {
            background: [
                ((0x10) as f32) / 255.0,
                ((0x14) as f32) / 255.0,
                ((0x18) as f32) / 255.0,
            ],
            face_color_mode: FaceColorMode::HashedBySolid,
            edge_color: hex(0x0d1030, 1.0),
            edge_width_px: 1.6,
            hidden_edge_alpha: 0.0,
            vertex_size_px: 0.0,
            axis_length_px: 0.0,
            ..Self::default()
        }
    }

    /// Apply a partial JSON override (R3 settings entrypoint). Unknown keys
    /// are ignored; colors are CSS hex strings.
    pub fn apply_json(&mut self, json: &str) -> Result<(), String> {
        let value: serde_json::Value =
            serde_json::from_str(json).map_err(|error| format!("settings parse: {error}"))?;
        let color = |key: &str, target: &mut Rgba| {
            if let Some(v) = value.get(key).and_then(|v| v.as_str()) {
                if let Some(rgb) = parse_css_hex(v) {
                    target[0] = rgb[0];
                    target[1] = rgb[1];
                    target[2] = rgb[2];
                }
            }
        };
        color("faceColor", &mut self.face_color);
        color("faceSelectedColor", &mut self.face_selected_color);
        color("hoverColor", &mut self.hover_color);
        color("edgeColor", &mut self.edge_color);
        color("edgeSelectedColor", &mut self.edge_selected_color);
        color("vertexColor", &mut self.vertex_color);
        color("vertexSelectedColor", &mut self.vertex_selected_color);
        // Sketcher overlay palette (same CSS-hex shape as the face/edge/vertex colors).
        color("sketchMovableColor", &mut self.sketch_movable_color);
        color("sketchLockedColor", &mut self.sketch_locked_color);
        color("sketchGeometryColor", &mut self.sketch_geometry_color);
        color("sketchPointColor", &mut self.sketch_point_color);
        color("sketchConstructionPointColor", &mut self.sketch_construction_point_color);
        color("sketchUnderConstrainedPointColor", &mut self.sketch_under_constrained_point_color);
        color("sketchSelectedColor", &mut self.sketch_selected_color);
        color("sketchHoveredColor", &mut self.sketch_hovered_color);
        color("sketchPreviewColor", &mut self.sketch_preview_color);
        color("sketchConstraintColor", &mut self.sketch_constraint_color);
        if let Some(v) = value.get("background").and_then(|v| v.as_str()) {
            if let Some(rgb) = parse_css_hex(v) {
                self.background = rgb;
            }
        }
        if let Some(v) = value.get("edgeWidthPx").and_then(|v| v.as_f64()) {
            self.edge_width_px = (v as f32).clamp(0.0, 32.0);
        }
        if let Some(v) = value.get("vertexSizePx").and_then(|v| v.as_f64()) {
            self.vertex_size_px = (v as f32).clamp(0.0, 64.0);
        }
        if let Some(v) = value.get("hiddenEdgeAlpha").and_then(|v| v.as_f64()) {
            self.hidden_edge_alpha = (v as f32).clamp(0.0, 1.0);
        }
        if let Some(v) = value.get("faceColorMode").and_then(|v| v.as_str()) {
            match v.trim().to_ascii_lowercase().as_str() {
                "hashedbysolid" | "hashed" => self.face_color_mode = FaceColorMode::HashedBySolid,
                "uniform" => self.face_color_mode = FaceColorMode::Uniform,
                _ => {}
            }
        }
        if let Some(v) = value.get("flatShading").and_then(|v| v.as_bool()) {
            self.flat_shading = v;
        }
        if let Some(v) = value.get("wireframe").and_then(|v| v.as_bool()) {
            self.wireframe = v;
        }
        if let Some(v) = value.get("axisLengthPx").and_then(|v| v.as_f64()) {
            self.axis_length_px = (v as f32).clamp(0.0, 512.0);
        }
        if let Some(v) = value.get("pickDoubleSided").and_then(|v| v.as_bool()) {
            self.pick_double_sided = v;
        }
        // "Render Quality" is a named dropdown (Draft…Ultra) mapping to the display
        // LOD factor (higher quality = finer mesh = smaller factor). We store the
        // resolved f64 so the tessellation path is unchanged.
        if let Some(label) = value.get("renderQuality").and_then(|v| v.as_str()) {
            if let Some(lod) = lod_from_quality(label) {
                self.lod_factor = lod;
            }
        }
        Ok(())
    }

    /// Serialize EVERY setting to the SAME camelCase / CSS-hex shape
    /// [`apply_json`] reads, so `s.apply_json(&s.to_json())` is the identity.
    /// This is the counterpart the settings schema serializes/persists through
    /// (there was previously no serializer, only the partial-override reader).
    pub fn to_json(&self) -> String {
        serde_json::json!({
            "background": rgb_to_css_hex(self.background),
            "faceColorMode": match self.face_color_mode {
                FaceColorMode::Uniform => "uniform",
                FaceColorMode::HashedBySolid => "hashedBySolid",
            },
            "faceColor": rgba_to_css_hex(self.face_color),
            "faceSelectedColor": rgba_to_css_hex(self.face_selected_color),
            "hoverColor": rgba_to_css_hex(self.hover_color),
            "edgeColor": rgba_to_css_hex(self.edge_color),
            "edgeSelectedColor": rgba_to_css_hex(self.edge_selected_color),
            "edgeWidthPx": self.edge_width_px as f64,
            "hiddenEdgeAlpha": self.hidden_edge_alpha as f64,
            "vertexColor": rgba_to_css_hex(self.vertex_color),
            "vertexSelectedColor": rgba_to_css_hex(self.vertex_selected_color),
            "vertexSizePx": self.vertex_size_px as f64,
            "flatShading": self.flat_shading,
            "wireframe": self.wireframe,
            "axisLengthPx": self.axis_length_px as f64,
            "pickDoubleSided": self.pick_double_sided,
            "renderQuality": quality_from_lod(self.lod_factor),
            "sketchMovableColor": rgba_to_css_hex(self.sketch_movable_color),
            "sketchLockedColor": rgba_to_css_hex(self.sketch_locked_color),
            "sketchGeometryColor": rgba_to_css_hex(self.sketch_geometry_color),
            "sketchPointColor": rgba_to_css_hex(self.sketch_point_color),
            "sketchConstructionPointColor": rgba_to_css_hex(self.sketch_construction_point_color),
            "sketchUnderConstrainedPointColor": rgba_to_css_hex(self.sketch_under_constrained_point_color),
            "sketchSelectedColor": rgba_to_css_hex(self.sketch_selected_color),
            "sketchHoveredColor": rgba_to_css_hex(self.sketch_hovered_color),
            "sketchPreviewColor": rgba_to_css_hex(self.sketch_preview_color),
            "sketchConstraintColor": rgba_to_css_hex(self.sketch_constraint_color),
        })
        .to_string()
    }

    /// The live [`SketchColors`] view of the sketcher palette — the tessellation /
    /// overlay builders read their colors from THIS (via
    /// [`crate::sketch::SketchSession::colors`]) so the display settings are the one
    /// source of truth. Each `Rgba` is quantized back to `0xRRGGBB` the SAME way
    /// [`rgb_to_css_hex`] serializes it, so a default settings value round-trips to
    /// the default `SketchColors` byte-exact.
    pub fn sketch_colors(&self) -> SketchColors {
        SketchColors {
            movable: rgba_to_u32(self.sketch_movable_color),
            locked: rgba_to_u32(self.sketch_locked_color),
            geometry: rgba_to_u32(self.sketch_geometry_color),
            point: rgba_to_u32(self.sketch_point_color),
            construction_point: rgba_to_u32(self.sketch_construction_point_color),
            under_constrained_point: rgba_to_u32(self.sketch_under_constrained_point_color),
            selected: rgba_to_u32(self.sketch_selected_color),
            hovered: rgba_to_u32(self.sketch_hovered_color),
            preview: rgba_to_u32(self.sketch_preview_color),
            constraint: rgba_to_u32(self.sketch_constraint_color),
        }
    }

    /// The settings schema WITH the current value baked into each field, as JSON
    /// — mirrors the kernel's `feature_schemas_json` export so a UI shell (egui
    /// here, a later `brep-ui` crate) can generate the whole form from data. The
    /// `value` of each field is pulled live from [`to_json`], so the export
    /// always reflects the current settings.
    pub fn settings_schema_json(&self) -> String {
        let current: serde_json::Value =
            serde_json::from_str(&self.to_json()).unwrap_or(serde_json::Value::Null);
        let fields: Vec<serde_json::Value> = settings_schema()
            .iter()
            .map(|field| {
                let kind = match &field.kind {
                    FieldKind::Color => serde_json::json!({ "type": "color" }),
                    FieldKind::Bool => serde_json::json!({ "type": "bool" }),
                    FieldKind::Enum { variants } => {
                        serde_json::json!({ "type": "enum", "variants": variants })
                    }
                    FieldKind::Number { min, max, step } => serde_json::json!({
                        "type": "number", "min": min, "max": max, "step": step
                    }),
                    FieldKind::Range { min, max, step } => serde_json::json!({
                        "type": "range", "min": min, "max": max, "step": step
                    }),
                    // The feature-dialog kinds never appear in the settings
                    // schema, but the match must stay exhaustive.
                    FieldKind::Scalar { step } => {
                        serde_json::json!({ "type": "scalar", "step": step })
                    }
                    FieldKind::Text { read_only } => {
                        serde_json::json!({ "type": "text", "readOnly": read_only })
                    }
                    FieldKind::Vec3 { step } => serde_json::json!({ "type": "vec3", "step": step }),
                    FieldKind::Reference { filter, multiple } => serde_json::json!({
                        "type": "reference", "filter": filter, "multiple": multiple
                    }),
                    FieldKind::Button { label } => {
                        serde_json::json!({ "type": "button", "label": label })
                    }
                };
                serde_json::json!({
                    "key": field.key,
                    "label": field.label,
                    "group": field.group,
                    "kind": kind,
                    "value": current.get(field.key),
                })
            })
            .collect();
        serde_json::json!({ "fields": fields }).to_string()
    }
}

/// Quantize an sRGB channel triple to a `#rrggbb` CSS hex string (the shape
/// [`RenderSettings::apply_json`] parses back).
fn rgb_to_css_hex(rgb: [f32; 3]) -> String {
    let q = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u32;
    format!("#{:02x}{:02x}{:02x}", q(rgb[0]), q(rgb[1]), q(rgb[2]))
}

/// Like [`rgb_to_css_hex`] but for an `Rgba` (the alpha is intentionally dropped
/// — `apply_json` only overrides the rgb channels, preserving existing alpha).
fn rgba_to_css_hex(rgba: Rgba) -> String {
    rgb_to_css_hex([rgba[0], rgba[1], rgba[2]])
}

/// Quantize an `Rgba` to a packed `0xRRGGBB` (alpha dropped), using the SAME
/// per-channel rounding as [`rgb_to_css_hex`] so the sketcher's `u32` palette
/// (`SketchColors`) is byte-identical to what the CSS-hex serialization would
/// produce — a default settings value maps back to the default `SketchColors`.
fn rgba_to_u32(rgba: Rgba) -> u32 {
    let q = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u32;
    (q(rgba[0]) << 16) | (q(rgba[1]) << 8) | q(rgba[2])
}

/// The kind of one settings field — the closed set of widget shapes the generic
/// form renderer knows how to emit. Plain data, NO egui dependency: the schema
/// lives in the engine, the renderer (brep-app / a later brep-ui) walks it.
#[derive(Debug, Clone, PartialEq)]
pub enum FieldKind {
    /// An sRGB color (`#rrggbb`) → a color picker button.
    Color,
    /// A boolean toggle → a checkbox.
    Bool,
    /// A closed choice → a combo box. `variants` are the JSON string values
    /// (exactly what `apply_json` accepts / `to_json` emits).
    Enum { variants: Vec<&'static str> },
    /// A bounded number → a slider / drag-value honoring `min`/`max`/`step`.
    Number { min: f64, max: f64, step: f64 },
    /// A 0..1 (or otherwise fractional) number → a slider honoring the bounds.
    Range { min: f64, max: f64, step: f64 },
    // --- extra kinds the FEATURE dialogs need (settings never use these) -------
    /// An UNBOUNDED number (feature params carry no min/max) → a drag value.
    Scalar { step: f64 },
    /// A free-text string → a single-line text edit. `read_only` marks an
    /// identity field (a feature `id`) that is shown but not editable here (a
    /// rename must cascade to references — a later slice).
    Text { read_only: bool },
    /// A 3-vector (position / rotationEuler / scale) → three drag values.
    Vec3 { step: f64 },
    /// A reference-selection field (solid / face / edge / … picked in the 3D
    /// view). The schema-driven form renders a DISABLED placeholder here — the
    /// real engine-native picker is the NEXT slice (#42). `filter` is the
    /// selection filter (e.g. `["SOLID"]`), `multiple` whether it takes a list.
    Reference { filter: Vec<String>, multiple: bool },
    /// An ACTION button (schema `"type":"button"`) → a clickable button. It binds
    /// to no value; a click is surfaced to the caller by the field `key` (e.g.
    /// `editSketch`), which the host acts on. `label` is the button caption.
    Button { label: String },
}

/// One field of the settings form: the camelCase `apply_json`/`to_json` key, a
/// human label, a UI group, and the widget `kind`. The ordered list of these
/// (see [`settings_schema`]) fully describes the form — a UI shell generates a
/// widget per field with no per-field code.
#[derive(Debug, Clone)]
pub struct SettingsField {
    /// The camelCase key — the SAME one `apply_json`/`to_json` use.
    pub key: &'static str,
    pub label: &'static str,
    pub group: &'static str,
    pub kind: FieldKind,
}

/// The GENERAL form field — the schema element ONE form engine renders for BOTH
/// the display-settings dialog AND the schema-driven feature dialogs. Unlike
/// [`SettingsField`] (which uses `&'static str` because the settings schema is
/// compile-time), this owns its strings so it can carry a per-feature schema
/// pulled from the kernel catalogue at run time, and it carries a `path` (a
/// chain of JSON object keys) so a field can bind to a NESTED value —
/// `["transform","position"]`, `["boolean","operation"]` — not just a top-level
/// key. The settings form is `path == [key]`.
#[derive(Debug, Clone)]
pub struct FormField {
    /// JSON object-key chain into the document the form edits (≥ 1 segment).
    pub path: Vec<String>,
    pub label: String,
    pub group: String,
    pub kind: FieldKind,
}

impl FormField {
    /// The last path segment — a stable per-field id for egui salting / probing.
    pub fn key(&self) -> &str {
        self.path.last().map(String::as_str).unwrap_or("")
    }
}

/// The "Render Quality" dropdown levels shown in Settings, each mapped to a
/// display-tessellation LOD factor. Higher quality = finer mesh = SMALLER factor
/// (chord tolerance = extent · 1.5e-3 · factor). Order is coarse→fine, the order
/// the ComboBox lists them. `lod_factor` stays the internal representation the
/// tessellation path reads; only the SETTINGS UI/serialization speaks in levels.
pub const RENDER_QUALITY: &[(&str, f64)] = &[
    ("Draft", 4.0),
    ("Low", 2.0),
    ("Medium", 1.0),
    ("High", 0.5),
    ("Ultra", 0.25),
];

/// The LOD factor for a quality label (`None` if not a known level).
fn lod_from_quality(label: &str) -> Option<f64> {
    RENDER_QUALITY
        .iter()
        .find(|(name, _)| *name == label)
        .map(|(_, factor)| *factor)
}

/// The quality label NEAREST a LOD factor — the serialization inverse of
/// [`lod_from_quality`]. A stored factor is always one of the level values in
/// normal use; nearest-match keeps a hand-set/legacy value mapping to a sane label.
fn quality_from_lod(lod: f64) -> &'static str {
    RENDER_QUALITY
        .iter()
        .min_by(|(_, a), (_, b)| {
            (a - lod).abs().total_cmp(&(b - lod).abs())
        })
        .map(|(name, _)| *name)
        .unwrap_or("Medium")
}

/// Lift the compile-time display-settings schema into general [`FormField`]s so
/// the ONE `field_input` engine (which the feature dialogs also use) renders the
/// settings panel too — a single schema-driven dialog engine, not two.
pub fn settings_form_fields() -> Vec<FormField> {
    settings_schema()
        .into_iter()
        .map(|field| FormField {
            path: vec![field.key.to_string()],
            label: field.label.to_string(),
            group: field.group.to_string(),
            kind: field.kind,
        })
        .collect()
}

/// The Rust-owned settings schema: the ordered list of display-settings fields,
/// grouped, analogous to the kernel feature schemas. Adding a field here (plus
/// its `apply_json`/`to_json` handling) makes the whole UI grow a widget for it
/// with ZERO renderer changes.
pub fn settings_schema() -> Vec<SettingsField> {
    let f = |key, label, group, kind| SettingsField { key, label, group, kind };
    vec![
        // --- Scene ---------------------------------------------------------
        f("background", "Background", "Scene", FieldKind::Color),
        f(
            "axisLengthPx",
            "Axis length (px)",
            "Scene",
            FieldKind::Number { min: 0.0, max: 512.0, step: 1.0 },
        ),
        f(
            "renderQuality",
            "Render Quality",
            "Scene",
            FieldKind::Enum { variants: RENDER_QUALITY.iter().map(|(label, _)| *label).collect() },
        ),
        // --- Faces ---------------------------------------------------------
        f(
            "faceColorMode",
            "Face color mode",
            "Faces",
            FieldKind::Enum { variants: vec!["uniform", "hashedBySolid"] },
        ),
        f("faceColor", "Face color", "Faces", FieldKind::Color),
        f("faceSelectedColor", "Selected face", "Faces", FieldKind::Color),
        f("hoverColor", "Hover", "Faces", FieldKind::Color),
        f("flatShading", "Flat shading", "Faces", FieldKind::Bool),
        f("wireframe", "Wireframe", "Faces", FieldKind::Bool),
        // --- Edges ---------------------------------------------------------
        f("edgeColor", "Edge color", "Edges", FieldKind::Color),
        f("edgeSelectedColor", "Selected edge", "Edges", FieldKind::Color),
        f(
            "edgeWidthPx",
            "Edge width (px)",
            "Edges",
            FieldKind::Number { min: 0.0, max: 32.0, step: 0.1 },
        ),
        f(
            "hiddenEdgeAlpha",
            "Hidden-edge alpha",
            "Edges",
            FieldKind::Range { min: 0.0, max: 1.0, step: 0.01 },
        ),
        // --- Vertices ------------------------------------------------------
        f("vertexColor", "Vertex color", "Vertices", FieldKind::Color),
        f("vertexSelectedColor", "Selected vertex", "Vertices", FieldKind::Color),
        f(
            "vertexSizePx",
            "Vertex size (px)",
            "Vertices",
            FieldKind::Number { min: 0.0, max: 64.0, step: 0.5 },
        ),
        // --- Picking -------------------------------------------------------
        f("pickDoubleSided", "Pick double-sided", "Picking", FieldKind::Bool),
        // --- Sketch --------------------------------------------------------
        // The sketcher overlay palette, editable live like every other display
        // color. `sketch_colors()` feeds these to the tessellation/overlay builders.
        f("sketchMovableColor", "Movable geometry", "Sketch", FieldKind::Color),
        f("sketchLockedColor", "Locked geometry", "Sketch", FieldKind::Color),
        f("sketchGeometryColor", "Geometry (no mobility)", "Sketch", FieldKind::Color),
        f("sketchPointColor", "Point", "Sketch", FieldKind::Color),
        f("sketchConstructionPointColor", "Construction point", "Sketch", FieldKind::Color),
        f("sketchUnderConstrainedPointColor", "Under-constrained point", "Sketch", FieldKind::Color),
        f("sketchSelectedColor", "Selected", "Sketch", FieldKind::Color),
        f("sketchHoveredColor", "Hovered", "Sketch", FieldKind::Color),
        f("sketchPreviewColor", "Draw preview", "Sketch", FieldKind::Color),
        f("sketchConstraintColor", "Constraint / dimension", "Sketch", FieldKind::Color),
    ]
}

/// A selected/hovered vertex reference: vertices have no kernel names, so they
/// resolve by owning solid + position.
#[derive(Debug, Clone)]
pub struct VertexRef {
    pub solid: String,
    pub position: [f64; 3],
}

/// The emphasis state (selection + hover), name-keyed like `SelectionFilter`.
/// Solid-level emphasis cascades to that solid's faces/edges (the
/// `SelectionState._applyToSolid` behavior).
#[derive(Debug, Default)]
pub struct Emphasis {
    pub selected_solids: HashSet<String>,
    pub selected_faces: HashSet<String>,
    pub selected_edges: HashSet<String>,
    pub selected_vertices: Vec<VertexRef>,
    /// Selected construction datum/plane FRAMES, keyed by frame NAME (`{id}:XY`
    /// for a DATUM base plane, `{id}` for a PLANE feature). Datums carry no
    /// resident geometry, so — like the render-color feed — they emphasize purely
    /// by name; a selected datum is re-colored with the selection accent when the
    /// engine re-feeds the datum planes.
    pub selected_datums: HashSet<String>,
    pub hovered_solids: HashSet<String>,
    pub hovered_faces: HashSet<String>,
    pub hovered_edges: HashSet<String>,
    pub hovered_vertices: Vec<VertexRef>,
    /// Bumped on every change — cache key for derived GPU state.
    pub generation: u64,
}

impl Emphasis {
    pub fn is_empty(&self) -> bool {
        self.selected_solids.is_empty()
            && self.selected_faces.is_empty()
            && self.selected_edges.is_empty()
            && self.selected_vertices.is_empty()
            && self.selected_datums.is_empty()
            && self.hovered_solids.is_empty()
            && self.hovered_faces.is_empty()
            && self.hovered_edges.is_empty()
            && self.hovered_vertices.is_empty()
    }

    /// Replace the whole emphasis state from the R3 JSON shape:
    /// `{selected: {solids, faces, edges, vertices:[{solid,position}]}, hovered: {...}}`.
    pub fn apply_json(&mut self, json: &str) -> Result<(), String> {
        let value: serde_json::Value =
            serde_json::from_str(json).map_err(|error| format!("emphasis parse: {error}"))?;
        let names = |group: &serde_json::Value, key: &str| -> HashSet<String> {
            group
                .get(key)
                .and_then(|v| v.as_array())
                .map(|list| {
                    list.iter()
                        .filter_map(|v| v.as_str().map(str::to_string))
                        .collect()
                })
                .unwrap_or_default()
        };
        let vertices = |group: &serde_json::Value| -> Vec<VertexRef> {
            group
                .get("vertices")
                .and_then(|v| v.as_array())
                .map(|list| {
                    list.iter()
                        .filter_map(|v| {
                            let solid = v.get("solid")?.as_str()?.to_string();
                            let p = v.get("position")?.as_array()?;
                            Some(VertexRef {
                                solid,
                                position: [
                                    p.first()?.as_f64()?,
                                    p.get(1)?.as_f64()?,
                                    p.get(2)?.as_f64()?,
                                ],
                            })
                        })
                        .collect()
                })
                .unwrap_or_default()
        };
        let empty = serde_json::json!({});
        let selected = value.get("selected").unwrap_or(&empty);
        let hovered = value.get("hovered").unwrap_or(&empty);
        self.selected_solids = names(selected, "solids");
        self.selected_faces = names(selected, "faces");
        self.selected_edges = names(selected, "edges");
        self.selected_datums = names(selected, "datums");
        self.selected_vertices = vertices(selected);
        self.hovered_solids = names(hovered, "solids");
        self.hovered_faces = names(hovered, "faces");
        self.hovered_edges = names(hovered, "edges");
        self.hovered_vertices = vertices(hovered);
        self.generation = self.generation.wrapping_add(1);
        Ok(())
    }
}

/// The visual state of one displayed face/edge (hover wins over selected, the
/// `SelectionState` order).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EmphasisState {
    Base,
    Selected,
    Hovered,
}

impl Emphasis {
    pub fn face_state(&self, solid: &str, face: &str) -> EmphasisState {
        if self.hovered_solids.contains(solid) || (!face.is_empty() && self.hovered_faces.contains(face)) {
            EmphasisState::Hovered
        } else if self.selected_solids.contains(solid)
            || (!face.is_empty() && self.selected_faces.contains(face))
        {
            EmphasisState::Selected
        } else {
            EmphasisState::Base
        }
    }

    pub fn edge_state(&self, solid: &str, edge: &str) -> EmphasisState {
        if self.hovered_solids.contains(solid) || (!edge.is_empty() && self.hovered_edges.contains(edge)) {
            EmphasisState::Hovered
        } else if self.selected_solids.contains(solid)
            || (!edge.is_empty() && self.selected_edges.contains(edge))
        {
            EmphasisState::Selected
        } else {
            EmphasisState::Base
        }
    }

    pub fn vertex_state(&self, solid: &str, position: [f64; 3], tol: f64) -> EmphasisState {
        let matches = |refs: &[VertexRef]| {
            refs.iter().any(|r| {
                r.solid == solid
                    && (r.position[0] - position[0]).abs() <= tol
                    && (r.position[1] - position[1]).abs() <= tol
                    && (r.position[2] - position[2]).abs() <= tol
            })
        };
        if matches(&self.hovered_vertices) {
            EmphasisState::Hovered
        } else if matches(&self.selected_vertices) {
            EmphasisState::Selected
        } else {
            EmphasisState::Base
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn settings_json_overrides() {
        let mut settings = RenderSettings::default();
        settings
            .apply_json(
                r##"{"faceColor": "#ff0000", "edgeWidthPx": 4.5, "flatShading": true,
                     "hoverColor": "#0f0", "unknownKey": 1}"##,
            )
            .unwrap();
        assert_eq!(settings.face_color[0], 1.0);
        assert_eq!(settings.face_color[1], 0.0);
        assert_eq!(settings.edge_width_px, 4.5);
        assert!(settings.flat_shading);
        assert_eq!(settings.hover_color[1], 1.0);
    }

    #[test]
    fn settings_json_face_color_mode_and_wireframe() {
        let mut settings = RenderSettings::default();
        // Defaults: uniform faces, shaded (not wireframe).
        assert_eq!(settings.face_color_mode, FaceColorMode::Uniform);
        assert!(!settings.wireframe);
        settings
            .apply_json(r##"{"faceColorMode": "hashedBySolid", "wireframe": true}"##)
            .unwrap();
        assert_eq!(settings.face_color_mode, FaceColorMode::HashedBySolid);
        assert!(settings.wireframe);
        // Round-trip back to uniform + shaded.
        settings
            .apply_json(r##"{"faceColorMode": "uniform", "wireframe": false}"##)
            .unwrap();
        assert_eq!(settings.face_color_mode, FaceColorMode::Uniform);
        assert!(!settings.wireframe);
        // An unknown mode string is ignored (stays uniform).
        settings.apply_json(r##"{"faceColorMode": "bogus"}"##).unwrap();
        assert_eq!(settings.face_color_mode, FaceColorMode::Uniform);
    }

    #[test]
    fn emphasis_states_cascade_from_solid() {
        let mut emphasis = Emphasis::default();
        emphasis
            .apply_json(
                r#"{"selected": {"solids": ["A"], "faces": ["F1"]},
                    "hovered": {"edges": ["E1"], "vertices": [{"solid": "A", "position": [1, 2, 3]}]}}"#,
            )
            .unwrap();
        assert_eq!(emphasis.face_state("A", "anything"), EmphasisState::Selected);
        assert_eq!(emphasis.face_state("B", "F1"), EmphasisState::Selected);
        assert_eq!(emphasis.face_state("B", "F2"), EmphasisState::Base);
        assert_eq!(emphasis.edge_state("B", "E1"), EmphasisState::Hovered);
        assert_eq!(
            emphasis.vertex_state("A", [1.0, 2.0, 3.0], 1e-9),
            EmphasisState::Hovered
        );
        assert_eq!(
            emphasis.vertex_state("B", [1.0, 2.0, 3.0], 1e-9),
            EmphasisState::Base
        );
        let gen0 = emphasis.generation;
        emphasis.apply_json(r#"{}"#).unwrap();
        assert!(emphasis.is_empty());
        assert_ne!(emphasis.generation, gen0);
    }

    #[test]
    fn settings_to_json_roundtrip_is_identity() {
        // Start from defaults, then mutate a spread of fields with hex-exact
        // colors / representable numbers so the round-trip is exact.
        let mut s = RenderSettings::default();
        s.face_color = hex(0x123456, 1.0);
        s.edge_color = hex(0xabcdef, 1.0);
        s.background = [0.0, 0.0, 0.0];
        s.face_color_mode = FaceColorMode::HashedBySolid;
        s.edge_width_px = 3.5;
        s.hidden_edge_alpha = 0.5;
        s.vertex_size_px = 8.0;
        s.axis_length_px = 30.0;
        // Must be a "Render Quality" LEVEL value now (serialized as its label +
        // read back to the same factor) — Low = 2.0; a between-levels value would
        // snap to the nearest level and break the identity by design.
        s.lod_factor = 2.0;
        s.flat_shading = true;
        s.wireframe = true;
        s.pick_double_sided = false;
        // Sketch palette carried through the round-trip too (hex-exact values).
        s.sketch_movable_color = hex(0x112233, 1.0);
        s.sketch_constraint_color = hex(0x00ff00, 1.0);
        s.sketch_selected_color = hex(0xfedcba, 1.0);

        // The task's literal identity form: applying its own serialization is a
        // no-op.
        let mut identity = s.clone();
        identity.apply_json(&s.to_json()).unwrap();
        assert_eq!(identity, s);

        // And it reconstructs the same value from a fresh default (alphas match,
        // since apply_json preserves the target's existing alpha = 1.0).
        let mut rebuilt = RenderSettings::default();
        rebuilt.apply_json(&s.to_json()).unwrap();
        assert_eq!(rebuilt, s);
    }

    #[test]
    fn settings_schema_covers_every_json_key() {
        // Every schema key must be a key `to_json` emits (so the form can read a
        // live value for it) — the schema and the serializer stay in lockstep.
        let json: serde_json::Value =
            serde_json::from_str(&RenderSettings::default().to_json()).unwrap();
        for field in settings_schema() {
            assert!(
                json.get(field.key).is_some(),
                "schema field {} has no to_json value",
                field.key
            );
        }
        // The schema export reflects the current value (e.g. wireframe flips).
        let mut s = RenderSettings::default();
        s.wireframe = true;
        let export: serde_json::Value = serde_json::from_str(&s.settings_schema_json()).unwrap();
        let wf = export["fields"]
            .as_array()
            .unwrap()
            .iter()
            .find(|f| f["key"] == "wireframe")
            .unwrap();
        assert_eq!(wf["value"], serde_json::json!(true));
    }

    #[test]
    fn sketch_colors_default_matches_the_hex_constants() {
        // The default RenderSettings sketch palette round-trips BYTE-EXACT to the
        // single source of the literals (`SketchColors::default`), so nothing
        // changes visually until edited.
        assert_eq!(RenderSettings::default().sketch_colors(), SketchColors::default());
    }

    #[test]
    fn sketch_colors_follow_apply_json() {
        // Editing a sketch color in the settings (the dialog's apply path) reaches
        // the `SketchColors` view the tessellation reads.
        let mut s = RenderSettings::default();
        s.apply_json(r##"{"sketchConstraintColor": "#ff0000", "sketchMovableColor": "#00ff00"}"##)
            .unwrap();
        let c = s.sketch_colors();
        assert_eq!(c.constraint, 0xff0000);
        assert_eq!(c.movable, 0x00ff00);
        // Untouched entries keep their defaults.
        assert_eq!(c.locked, SketchColors::default().locked);
    }

    #[test]
    fn css_hex_parsing() {
        assert_eq!(parse_css_hex("#ffffff"), Some([1.0, 1.0, 1.0]));
        assert_eq!(parse_css_hex("#f00"), Some([1.0, 0.0, 0.0]));
        assert!(parse_css_hex("red").is_none());
        assert_eq!(parse_css_hex("0x00009e").map(|c| c[2]), Some(0x9e as f32 / 255.0));
    }
}