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
use super::*;

impl EngineState {
    /// Clear the current SELECTION (Esc): drop all selected solids/faces/edges/
    /// vertices (hover is left untouched). Bumps the emphasis generation + marks
    /// dirty only when something was actually cleared. Returns whether it changed.
    pub fn clear_selection(&mut self) -> bool {
        let had_datums = !self.emphasis.selected_datums.is_empty();
        let had = !self.emphasis.selected_solids.is_empty()
            || !self.emphasis.selected_faces.is_empty()
            || !self.emphasis.selected_edges.is_empty()
            || !self.emphasis.selected_vertices.is_empty()
            || had_datums;
        if had {
            self.emphasis.selected_solids.clear();
            self.emphasis.selected_faces.clear();
            self.emphasis.selected_edges.clear();
            self.emphasis.selected_vertices.clear();
            self.emphasis.selected_datums.clear();
            self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
            self.dirty = true;
        }
        // A cleared datum drops its selection accent — re-feed the datum planes so
        // the highlight disappears immediately (no re-run needed).
        if had_datums {
            self.refresh_construction_datums();
        }
        had
    }

    /// Select the top-priority pick under CSS-pixel `(x, y)` that the SELECTION
    /// FILTER admits — replacing the current selection (a plain viewport click).
    /// A miss (or a click when the filter admits nothing) clears the selection.
    /// Marks dirty when the selection changed; returns whether something was
    /// selected. The by-kind honoring lives in [`select_filtered_at`] in the
    /// appended selection-filter impl block (kept separate so concurrent edits to
    /// this primary block don't conflict).
    pub fn select_top_at(&mut self, x: f64, y: f64) -> bool {
        self.select_filtered_at(x, y)
    }

    /// The current SELECTION (not hover) as JSON
    /// `{ solids:[..], faces:[..], edges:[..], vertices: n }` — lets a UI / the
    /// headed verifier read selection state (e.g. assert Esc cleared it).
    pub fn selection_json(&self) -> String {
        let solids: Vec<&String> = self.emphasis.selected_solids.iter().collect();
        let faces: Vec<&String> = self.emphasis.selected_faces.iter().collect();
        let edges: Vec<&String> = self.emphasis.selected_edges.iter().collect();
        let datums: Vec<&String> = self.emphasis.selected_datums.iter().collect();
        serde_json::json!({
            "solids": solids,
            "faces": faces,
            "edges": edges,
            "datums": datums,
            "vertices": self.emphasis.selected_vertices.len(),
        })
        .to_string()
    }

    // --- Reference-selection widget (the engine-native picker, #42) --------
    //
    // A feature-dialog reference field activates this MODAL: the UI hides the
    // rest of itself and shows only the widget's list + Finish/Cancel; the engine
    // rolls to the pre-feature "before" state, highlights the running selection
    // (via `emphasis`), and each click in the viewport type-constrained-picks a
    // name into the list. Finish writes the names into the feature params (via
    // the same `update_feature_params` path) and restores; Cancel discards. The
    // list of names is the whole state — no event-on-object wiring.

    /// True while the reference-selection modal is active (the shell hides the
    /// rest of the UI and the viewport routes clicks to picking).
    pub fn ref_select_active(&self) -> bool {
        self.ref_select.is_some()
    }

    /// Enter reference-selection mode for feature `feature_id`'s param at `path`.
    /// Seeds the running list from `seed_names` (the field's current value), rolls
    /// the model to the pre-feature "before" state (the step just before the
    /// edited feature ran), and highlights the seeded names. `filter` constrains
    /// the pick kind (`["SOLID"]`, `["FACE"]`, …); `multiple` allows a list.
    pub fn begin_ref_select(
        &mut self,
        feature_id: &str,
        path: Vec<String>,
        label: String,
        filter: Vec<String>,
        multiple: bool,
        seed_names: Vec<String>,
    ) {
        let restore_index = self.history.rollback();
        // "Before" = the step just before the edited feature ran, so the user
        // picks against the correct geometry. Clamp at 0 for the first feature.
        let before = self
            .history
            .index_of(feature_id)
            .map(|i| i.saturating_sub(1))
            .unwrap_or(restore_index);
        // Constrain the GLOBAL selection filter to exactly the kinds this field
        // permits: this drives BOTH click-picking (`ref_select_click`) AND
        // hover-highlighting (`hover_at`, which reads `selection_filter`), so only
        // the allowed kinds highlight/select while the picker is active. An
        // absent/construction-only field filter maps to all-enabled (see
        // `from_ref_filter`). Restored to the all-enabled default on finish/cancel
        // (`end_ref_select`).
        self.selection_filter = SelectionFilter::from_ref_filter(&filter);
        self.ref_select = Some(RefSelectState {
            feature_id: feature_id.to_string(),
            path,
            label,
            filter,
            multiple,
            names: seed_names,
            restore_index,
        });
        // Roll to the before-state (re-runs + marks dirty), then light up the seed.
        self.history.set_rollback(before);
        self.rerun_history();
        self.sync_ref_select_emphasis();
    }

    /// The running list of picked names (empty when not active) — the modal UI
    /// reads this back to draw its one-per-line list.
    pub fn ref_select_names(&self) -> Vec<String> {
        self.ref_select
            .as_ref()
            .map(|r| r.names.clone())
            .unwrap_or_default()
    }

    /// The active field's label (for the modal heading), or empty.
    pub fn ref_select_label(&self) -> String {
        self.ref_select
            .as_ref()
            .map(|r| r.label.clone())
            .unwrap_or_default()
    }

    /// A one-line summary of the active field for the modal heading:
    /// `"Tool solids (SOLID, multiple)"`.
    pub fn ref_select_prompt(&self) -> String {
        match &self.ref_select {
            Some(r) => format!(
                "{} ({}{})",
                r.label,
                r.filter.join("/"),
                if r.multiple { ", multiple" } else { "" }
            ),
            None => String::new(),
        }
    }

    /// A viewport click while active: type-constrained-pick the nearest allowed
    /// hit under CSS-pixel `(x, y)` and add its name to the running list (single
    /// fields replace; multiple fields append, de-duplicated). Re-lights the
    /// highlight. No-op on a miss / an empty (unnamed) hit.
    pub fn ref_select_click(&mut self, x: f64, y: f64) {
        let Some(state) = self.ref_select.as_ref() else {
            return;
        };
        let filter = state.filter.clone();
        let multiple = state.multiple;
        let options = self.pick_options();
        let Some(hit) = pick::pick_filtered(&self.scene, &self.camera, x, y, &options, &filter)
        else {
            return;
        };
        if hit.name.trim().is_empty() {
            return; // e.g. a vertex (no kernel name) — nothing to record by name.
        }
        let state = self.ref_select.as_mut().expect("active by guard above");
        if multiple {
            if !state.names.iter().any(|n| n == &hit.name) {
                state.names.push(hit.name);
            }
        } else {
            state.names = vec![hit.name];
        }
        self.sync_ref_select_emphasis();
    }

    /// Remove the name at `index` from the running list (the modal's per-line X).
    pub fn ref_select_remove(&mut self, index: usize) {
        if let Some(state) = self.ref_select.as_mut() {
            if index < state.names.len() {
                state.names.remove(index);
            }
        }
        self.sync_ref_select_emphasis();
    }

    /// Finish: write the running names into the edited feature's params at the
    /// field path, restore the rolled-to step, clear the highlight, and re-run so
    /// the feature rebuilds with the chosen references.
    pub fn finish_ref_select(&mut self) {
        let Some(state) = self.ref_select.take() else {
            return;
        };
        if let Some(index) = self.history.index_of(&state.feature_id) {
            let mut params = self
                .history
                .feature_params(index)
                .unwrap_or_else(|| serde_json::json!({}));
            let value = if state.multiple {
                serde_json::Value::Array(
                    state
                        .names
                        .iter()
                        .cloned()
                        .map(serde_json::Value::String)
                        .collect(),
                )
            } else {
                serde_json::Value::String(state.names.first().cloned().unwrap_or_default())
            };
            set_json_at(&mut params, &state.path, value);
            self.history.set_feature_params(index, params);
        }
        self.end_ref_select(state.restore_index);
    }

    /// Cancel: discard the running selection, clear the highlight, restore the
    /// rolled-to step, and re-run (no param change).
    pub fn cancel_ref_select(&mut self) {
        if let Some(state) = self.ref_select.take() {
            self.end_ref_select(state.restore_index);
        }
    }

    /// Restore the rolled-to step + clear emphasis + re-run + reset the selection
    /// filter to the all-enabled default (shared Finish/Cancel tail).
    ///
    /// Resetting to the DEFAULT (not a saved "prior" filter) is deliberate: the
    /// spec baseline out of ref-select is "all kinds enabled", and `begin_ref_select`
    /// overwrites `ref_select` without routing through here, so a stashed prior
    /// could be a stale already-constrained filter. Living in this shared tail also
    /// means a stray `finish_ref_select()` while inactive (early return on `take`)
    /// never clobbers the filter.
    fn end_ref_select(&mut self, restore_index: usize) {
        let _ = self.emphasis.apply_json("{}");
        self.selection_filter = SelectionFilter::default();
        self.history.set_rollback(restore_index);
        self.rerun_history();
    }

    /// Drive the selection highlight (`emphasis`) from the running name list so
    /// picks light up in the viewport. A field may allow SEVERAL kinds at once
    /// (e.g. `FACE`/`EDGE`), and a pick can be any of them, so every picked name is
    /// fed to EVERY name-based bucket the filter permits — a name only ever matches
    /// its own kind's entities (edge names carry the `|…[n]` topology form, faces do
    /// not), so the cross-listing is harmless and each pick highlights correctly.
    /// (The old code bucketed ALL names by `filter.first()` only, so an EDGE pick
    /// under a `FACE`-first filter landed in `faces`, matched nothing, and never
    /// showed.) VERTEX picks are position-keyed, not name-keyed, so they can't be
    /// emphasized from a name list here.
    fn sync_ref_select_emphasis(&mut self) {
        let json = match &self.ref_select {
            Some(state) => {
                let names = serde_json::json!(state.names);
                let mut selected = serde_json::Map::new();
                for kind in &state.filter {
                    let bucket = match kind.as_str() {
                        "FACE" => "faces",
                        "EDGE" => "edges",
                        "SOLID" => "solids",
                        "PLANE" | "DATUM" => "datums",
                        _ => continue, // VERTEX / unknown: no name-based highlight
                    };
                    selected.entry(bucket.to_string()).or_insert_with(|| names.clone());
                }
                // No highlightable kind in the filter → fall back to solids (the
                // prior default) so at least solid-name picks still light up.
                if selected.is_empty() {
                    selected.insert("solids".to_string(), names);
                }
                serde_json::json!({ "selected": selected }).to_string()
            }
            None => "{}".to_string(),
        };
        let _ = self.emphasis.apply_json(&json);
        self.dirty = true;
    }
}

/// Write `value` into `root` at `path` (object-key chain), auto-vivifying
/// intermediate objects — the engine-side twin of the form's nested setter, used
/// to commit a reference field's picked names back into the feature params.
fn set_json_at(root: &mut serde_json::Value, path: &[String], value: serde_json::Value) {
    if path.is_empty() {
        *root = value;
        return;
    }
    if !root.is_object() {
        *root = serde_json::Value::Object(serde_json::Map::new());
    }
    let mut cur = root;
    for seg in &path[..path.len() - 1] {
        let obj = cur.as_object_mut().expect("object by construction");
        cur = obj
            .entry(seg.clone())
            .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
        if !cur.is_object() {
            *cur = serde_json::Value::Object(serde_json::Map::new());
        }
    }
    cur.as_object_mut()
        .expect("object by construction")
        .insert(path[path.len() - 1].clone(), value);
}

impl EngineState {
    /// Hover-highlight the TOP-priority pick under CSS-pixel `(x, y)` whose kind
    /// the selection filter admits, setting it HOVERED in `emphasis` (the
    /// renderer tints it). A miss — or a filter admitting nothing — clears the
    /// hover. No-ops (returns `false`, no dirty) when the hovered entity is
    /// unchanged, so a stationary pointer over the same face doesn't re-render
    /// every frame (the `k === prevK` early-out). Returns
    /// whether the hover state changed.
    pub fn hover_at(&mut self, x: f64, y: f64) -> bool {
        let kinds = self.selection_filter.enabled_kinds();
        if kinds.is_empty() {
            return self.clear_hover();
        }
        let options = self.pick_options();
        match pick::pick_filtered(&self.scene, &self.camera, x, y, &options, &kinds) {
            Some(hit) => {
                if self.hover_is(&hit) {
                    return false; // unchanged — keep the frame clean.
                }
                self.set_hover_to_candidate(&hit);
                true
            }
            None => self.clear_hover(),
        }
    }

    /// Clear the hover highlight (pointer moved to empty space / off the
    /// viewport). Bumps the emphasis generation + marks dirty only when a hover
    /// was actually lit. Returns whether it changed. (Distinct from
    /// [`clear_selection`](Self::clear_selection), which leaves hover alone.)
    pub fn clear_hover(&mut self) -> bool {
        let had = !self.emphasis.hovered_solids.is_empty()
            || !self.emphasis.hovered_faces.is_empty()
            || !self.emphasis.hovered_edges.is_empty()
            || !self.emphasis.hovered_vertices.is_empty();
        if had {
            self.emphasis.hovered_solids.clear();
            self.emphasis.hovered_faces.clear();
            self.emphasis.hovered_edges.clear();
            self.emphasis.hovered_vertices.clear();
            self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
            self.dirty = true;
        }
        had
    }

    /// The current HOVER (not selection) as JSON
    /// `{ solids:[..], faces:[..], edges:[..], vertices: n }` — the hover twin of
    /// [`selection_json`](Self::selection_json) so a UI / the headed verifier can
    /// assert that moving the pointer over a face lit the hover emphasis.
    pub fn hovered_json(&self) -> String {
        let solids: Vec<&String> = self.emphasis.hovered_solids.iter().collect();
        let faces: Vec<&String> = self.emphasis.hovered_faces.iter().collect();
        let edges: Vec<&String> = self.emphasis.hovered_edges.iter().collect();
        serde_json::json!({
            "solids": solids,
            "faces": faces,
            "edges": edges,
            "vertices": self.emphasis.hovered_vertices.len(),
        })
        .to_string()
    }

    /// TOGGLE the top admitted pick under CSS-pixel `(x, y)` in the current
    /// selection (a **Ctrl/Cmd+click**): add it if absent, remove it if present,
    /// leaving the rest of the selection intact (unlike [`select_top_at`], which
    /// REPLACES). A miss — or a filter admitting nothing — leaves the selection
    /// untouched (additive mode never clears). Returns whether a hit was toggled.
    pub fn select_toggle_at(&mut self, x: f64, y: f64) -> bool {
        let kinds = self.selection_filter.enabled_kinds();
        if kinds.is_empty() {
            return false;
        }
        let options = self.pick_options();
        match pick::pick_filtered(&self.scene, &self.camera, x, y, &options, &kinds) {
            Some(hit) => {
                self.toggle_candidate(&hit);
                true
            }
            None => false,
        }
    }

    /// The RANKED, filter-respecting candidates under CSS-pixel `(x, y)` as JSON
    /// `[{kind, name, solid, depth}]` — the "candidates under the cursor" list
    /// (feeds the disambiguation popup + the headed verifier).
    ///
    /// Sorted EXACTLY as the previous app sorted its pick list
    /// (kind PRIORITY first, then depth) — `pick::pick`
    /// already ranks by `(kind, depth, screen_dist)` and appends the owning SOLID
    /// entries at the very end, so filtering by the enabled kinds preserves that
    /// order.
    pub fn candidates_at(&self, x: f64, y: f64) -> String {
        let list = self.candidates_filtered_at(x, y);
        let out: Vec<serde_json::Value> = list
            .iter()
            .map(|c| {
                serde_json::json!({
                    "kind": c.kind.as_str(),
                    "name": c.name,
                    "solid": c.solid,
                    "depth": c.depth,
                })
            })
            .collect();
        serde_json::Value::Array(out).to_string()
    }

    /// The same ranked, filter-respecting candidate list as typed values (the
    /// in-process egui popup consumes these directly, then re-hovers / selects a
    /// chosen one via [`hover_candidate`](Self::hover_candidate) /
    /// [`select_candidate`](Self::select_candidate) /
    /// [`toggle_candidate`](Self::toggle_candidate)). EMPTY when the filter admits
    /// nothing (not the `pick_filtered` "empty filter = any" case).
    pub fn candidates_filtered_at(&self, x: f64, y: f64) -> Vec<pick::PickCandidate> {
        let kinds = self.selection_filter.enabled_kinds();
        if kinds.is_empty() {
            return Vec::new();
        }
        pick::pick(&self.scene, &self.camera, x, y, &self.pick_options())
            .into_iter()
            .filter(|c| kinds.iter().any(|k| k.eq_ignore_ascii_case(c.kind.as_str())))
            .collect()
    }

    /// Hover a SPECIFIC candidate (the popup entry the pointer is over) — sets it
    /// HOVERED in `emphasis`, replacing any prior hover.
    pub fn hover_candidate(&mut self, candidate: &pick::PickCandidate) {
        self.set_hover_to_candidate(candidate);
    }

    /// REPLACE the selection with a specific candidate (a plain click on a popup
    /// entry) — reuses the same bucketing as a plain viewport click.
    pub fn select_candidate(&mut self, candidate: &pick::PickCandidate) {
        self.set_selection_to_candidate(candidate);
    }

    /// TOGGLE a specific candidate in the selection (a Ctrl/Cmd+click on a popup
    /// entry, or the [`select_toggle_at`](Self::select_toggle_at) hit): add if
    /// absent, remove if present. Returns whether it is NOW selected (`true` =
    /// added, `false` = removed). Bumps the emphasis generation + marks dirty.
    pub fn toggle_candidate(&mut self, candidate: &pick::PickCandidate) -> bool {
        use crate::pick::PickKind;
        let now_selected = match candidate.kind {
            PickKind::Solid => {
                let name = self.candidate_solid_name(candidate);
                if self.emphasis.selected_solids.remove(&name) {
                    false
                } else {
                    self.emphasis.selected_solids.insert(name);
                    true
                }
            }
            PickKind::Face => {
                if self.emphasis.selected_faces.remove(&candidate.name) {
                    false
                } else {
                    self.emphasis.selected_faces.insert(candidate.name.clone());
                    true
                }
            }
            PickKind::Edge => {
                if self.emphasis.selected_edges.remove(&candidate.name) {
                    false
                } else {
                    self.emphasis.selected_edges.insert(candidate.name.clone());
                    true
                }
            }
            PickKind::Vertex => {
                if let Some(index) = self
                    .emphasis
                    .selected_vertices
                    .iter()
                    .position(|v| Self::vertex_ref_matches(v, candidate))
                {
                    self.emphasis.selected_vertices.remove(index);
                    false
                } else {
                    self.emphasis.selected_vertices.push(crate::style::VertexRef {
                        solid: candidate.solid.clone(),
                        position: candidate.position,
                    });
                    true
                }
            }
        };
        self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
        self.dirty = true;
        now_selected
    }

    /// Set the hover emphasis to exactly one candidate (bucketed by kind), the
    /// hover twin of `set_selection_to_candidate`.
    fn set_hover_to_candidate(&mut self, candidate: &pick::PickCandidate) {
        use crate::pick::PickKind;
        self.emphasis.hovered_solids.clear();
        self.emphasis.hovered_faces.clear();
        self.emphasis.hovered_edges.clear();
        self.emphasis.hovered_vertices.clear();
        match candidate.kind {
            PickKind::Solid => {
                self.emphasis
                    .hovered_solids
                    .insert(self.candidate_solid_name(candidate));
            }
            PickKind::Face => {
                self.emphasis.hovered_faces.insert(candidate.name.clone());
            }
            PickKind::Edge => {
                self.emphasis.hovered_edges.insert(candidate.name.clone());
            }
            PickKind::Vertex => {
                self.emphasis.hovered_vertices.push(crate::style::VertexRef {
                    solid: candidate.solid.clone(),
                    position: candidate.position,
                });
            }
        }
        self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
        self.dirty = true;
    }

    /// Whether the CURRENT hover is exactly this one candidate (the `hover_at`
    /// early-out) — a single hovered entity that matches `candidate`.
    fn hover_is(&self, candidate: &pick::PickCandidate) -> bool {
        use crate::pick::PickKind;
        let total = self.emphasis.hovered_solids.len()
            + self.emphasis.hovered_faces.len()
            + self.emphasis.hovered_edges.len()
            + self.emphasis.hovered_vertices.len();
        if total != 1 {
            return false;
        }
        match candidate.kind {
            PickKind::Solid => self
                .emphasis
                .hovered_solids
                .contains(&self.candidate_solid_name(candidate)),
            PickKind::Face => self.emphasis.hovered_faces.contains(&candidate.name),
            PickKind::Edge => self.emphasis.hovered_edges.contains(&candidate.name),
            PickKind::Vertex => self
                .emphasis
                .hovered_vertices
                .iter()
                .any(|v| Self::vertex_ref_matches(v, candidate)),
        }
    }

    /// The scene name a SOLID candidate resolves to (its owning `solid`, falling
    /// back to `name` when the pick didn't carry one) — the same rule
    /// `set_selection_to_candidate` uses.
    fn candidate_solid_name(&self, candidate: &pick::PickCandidate) -> String {
        if candidate.solid.is_empty() {
            candidate.name.clone()
        } else {
            candidate.solid.clone()
        }
    }

    /// Vertex identity: same owning solid + position within the emphasis match
    /// tolerance (vertices carry no kernel name, so they resolve by solid+pos).
    fn vertex_ref_matches(v: &crate::style::VertexRef, candidate: &pick::PickCandidate) -> bool {
        const TOL: f64 = 1e-4;
        v.solid == candidate.solid
            && (v.position[0] - candidate.position[0]).abs() <= TOL
            && (v.position[1] - candidate.position[1]).abs() <= TOL
            && (v.position[2] - candidate.position[2]).abs() <= TOL
    }
}

// ---------------------------------------------------------------------------
// Sketch display (S0) — read-only overlay of a solved SketchSession.
//
// Additive, self-contained: a solved sketch is fed to the general `set_overlay`
// channel as the named groups `sketch-geometry` (lines) and `sketch-points`
// (billboarded points), colored by solver mobility. No interaction (the tools /
// picking / dimensions of later slices live elsewhere); this block only pushes /
// clears the display geometry.
// ---------------------------------------------------------------------------
impl EngineState {
    /// Display a solved [`crate::sketch::SketchSession`] as a read-only overlay.
    /// The plane geometry is tessellated to world space and pushed via
    /// [`set_overlay_json`](Self::set_overlay_json); construction dashes are sized
    /// against the LIVE camera so they stay screen-constant.
    pub fn set_sketch_overlay(&mut self, session: &crate::sketch::SketchSession) {
        let world_per_pixel = self.camera.world_per_pixel();
        let json = session.overlay_json(world_per_pixel);
        // The overlay channel accepts our exact `{groups:[…]}` shape; a parse
        // failure would be a programming error in the tessellator, so drop it.
        let _ = self.set_overlay_json(&json);
        // The dimension leaders ride in their own `sketch-dim-leaders` group (S5).
        let _ = self.set_overlay_json(&session.dim_leaders_overlay_json(world_per_pixel));
        // The geometric-constraint glyphs ride in `sketch-constraint-glyphs` (S6c).
        let _ = self.set_overlay_json(&session.constraint_glyphs_overlay_json(world_per_pixel));
    }

    /// Remove the sketch overlay groups (feeding empty same-named groups upserts
    /// them to empty, which the overlay channel treats as a removal — other
    /// overlay groups are left untouched).
    pub fn clear_sketch_overlay(&mut self) {
        let _ = self.set_overlay_json(
            "{\"groups\":[{\"name\":\"sketch-geometry\"},{\"name\":\"sketch-points\"},{\"name\":\"sketch-preview\"},{\"name\":\"sketch-dim-leaders\"},{\"name\":\"sketch-constraint-glyphs\"}]}",
        );
    }
}

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

    fn cube(name: &str, size: f64) -> String {
        serde_json::json!({
            "expressions": "",
            "configurator": {},
            "features": [{
                "type": "P.CU",
                "inputParams": {
                    "id": name,
                    "sizeX": size, "sizeY": size, "sizeZ": size,
                    "transform": {
                        "position": [0.0, 0.0, 0.0],
                        "rotationEuler": [0.0, 0.0, 0.0],
                        "scale": [1.0, 1.0, 1.0]
                    },
                    "boolean": { "targets": [], "operation": "NONE" }
                },
                "persistentData": {}
            }]
        })
        .to_string()
    }

    /// A cube filling `0..size` framed straight-on down -Z, so the viewport
    /// centre `(400, 300)` lands on a face centre — a ray that pierces BOTH the
    /// near (+Z) and far (-Z) faces, i.e. an overlapping spot with two FACE
    /// candidates under one pixel.
    fn front_cube(size: f64) -> EngineState {
        let mut engine = EngineState::new();
        engine.run_history_json(&cube("UxCube", size), None).unwrap();
        engine.resize(800.0, 600.0);
        engine.camera.eye = [size / 2.0, size / 2.0, size * 6.0];
        engine.camera.target = [size / 2.0, size / 2.0, size / 2.0];
        engine.camera.up = [0.0, 1.0, 0.0];
        engine.camera.projection = crate::view::Projection::Orthographic { half_height: size };
        engine
    }

    fn face_filter(engine: &mut EngineState) {
        engine.set_selection_filter(SelectionFilter {
            solid: false,
            face: true,
            edge: false,
            vertex: false,
        });
    }

    #[test]
    fn candidates_at_respect_filter_and_the_kind_then_depth_sort() {
        let mut engine = front_cube(10.0);

        // FACE-only: the overlapping centre pixel lists BOTH faces (near + far),
        // both FACE, sorted by ascending depth (the final sort: kind priority
        // then depth). No SOLID entry — the filter drops it.
        face_filter(&mut engine);
        let v: serde_json::Value =
            serde_json::from_str(&engine.candidates_at(400.0, 300.0)).unwrap();
        let arr = v.as_array().unwrap();
        assert!(arr.len() >= 2, "two faces under the pixel: {arr:?}");
        assert!(arr.iter().all(|c| c["kind"] == "FACE"), "faces only: {arr:?}");
        let depths: Vec<f64> = arr.iter().map(|c| c["depth"].as_f64().unwrap()).collect();
        assert!(
            depths.windows(2).all(|w| w[0] <= w[1]),
            "sorted by ascending depth (near face first): {depths:?}"
        );

        // SOLID-only: the SAME pixel lists exactly the owning solid.
        engine.set_selection_filter(SelectionFilter {
            solid: true,
            face: false,
            edge: false,
            vertex: false,
        });
        let v: serde_json::Value =
            serde_json::from_str(&engine.candidates_at(400.0, 300.0)).unwrap();
        let arr = v.as_array().unwrap();
        assert_eq!(arr.len(), 1, "one solid: {arr:?}");
        assert_eq!(arr[0]["kind"], "SOLID");
        assert_eq!(arr[0]["name"], "UxCube");

        // Nothing enabled → an empty candidate list.
        engine.set_selection_filter(SelectionFilter {
            solid: false,
            face: false,
            edge: false,
            vertex: false,
        });
        let v: serde_json::Value =
            serde_json::from_str(&engine.candidates_at(400.0, 300.0)).unwrap();
        assert!(v.as_array().unwrap().is_empty(), "no kind admitted → empty");
    }

    #[test]
    fn toggle_candidate_adds_then_removes_and_multi_selects() {
        let mut engine = front_cube(10.0);
        face_filter(&mut engine);
        let cands = engine.candidates_filtered_at(400.0, 300.0);
        assert!(cands.len() >= 2, "need two overlapping faces");
        let near = cands[0].clone();
        let far = cands[1].clone();
        assert_ne!(near.name, far.name, "distinct faces");

        // Toggling two distinct faces ADDS both → a selection of size 2.
        assert!(engine.toggle_candidate(&near), "near added");
        assert!(engine.toggle_candidate(&far), "far added");
        assert_eq!(engine.emphasis.selected_faces.len(), 2, "both faces selected");

        // Toggling the near face again REMOVES it → back to 1, the far face kept.
        assert!(!engine.toggle_candidate(&near), "near removed");
        assert_eq!(engine.emphasis.selected_faces.len(), 1);
        assert!(engine.emphasis.selected_faces.contains(&far.name));
    }

    #[test]
    fn select_toggle_at_adds_then_removes_the_top_hit() {
        let mut engine = front_cube(10.0);
        face_filter(&mut engine);
        // First Ctrl+click at the centre adds the near face.
        assert!(engine.select_toggle_at(400.0, 300.0));
        assert_eq!(engine.emphasis.selected_faces.len(), 1);
        // A second Ctrl+click at the SAME spot toggles that same top hit off.
        assert!(engine.select_toggle_at(400.0, 300.0));
        assert_eq!(engine.emphasis.selected_faces.len(), 0);
        // A Ctrl+click on empty space is a no-op (never clears the selection).
        engine.set_selection_filter(SelectionFilter {
            solid: true,
            face: false,
            edge: false,
            vertex: false,
        });
        assert!(engine.select_toggle_at(400.0, 300.0), "solid added");
        assert!(!engine.select_toggle_at(10.0, 10.0), "miss is a no-op");
        assert!(engine.has_selection(), "miss left the selection intact");
    }

    #[test]
    fn hover_at_lights_the_top_face_and_clears() {
        let mut engine = front_cube(10.0);
        face_filter(&mut engine);
        // Moving over the face lights exactly one hovered face.
        assert!(engine.hover_at(400.0, 300.0), "hover set");
        assert_eq!(engine.emphasis.hovered_faces.len(), 1);
        let lit: String = engine.emphasis.hovered_faces.iter().next().unwrap().clone();
        // Re-hovering the SAME entity does not churn the frame.
        assert!(!engine.hover_at(400.0, 300.0), "unchanged hover → no change");
        assert_eq!(engine.emphasis.hovered_faces.iter().next().unwrap(), &lit);
        // Moving onto empty space clears the hover.
        assert!(engine.hover_at(10.0, 10.0), "miss clears the prior hover");
        assert!(engine.emphasis.hovered_faces.is_empty());
        // Hover does NOT touch the selection set.
        assert!(!engine.has_selection());
    }

    #[test]
    fn candidate_hover_and_select_target_the_exact_entity() {
        let mut engine = front_cube(10.0);
        face_filter(&mut engine);
        let cands = engine.candidates_filtered_at(400.0, 300.0);
        let far = cands[1].clone();
        // Hovering the SECOND (far) candidate lights that exact face, not the near one.
        engine.hover_candidate(&far);
        assert!(engine.emphasis.hovered_faces.contains(&far.name));
        assert_eq!(engine.emphasis.hovered_faces.len(), 1);
        // Selecting it replaces the selection with exactly that face.
        engine.select_candidate(&far);
        assert_eq!(engine.emphasis.selected_faces.len(), 1);
        assert!(engine.emphasis.selected_faces.contains(&far.name));
    }

    /// NAME-based selection re-attaches across a feature re-run: after editing
    /// the feature (new geometry, same deterministic kernel names) the selected
    /// face name still exists in the rebuilt scene and the emphasis still
    /// resolves it — the selection isn't dropped by the rebuild.
    #[test]
    fn selection_reattaches_across_feature_reruns() {
        let mut engine = front_cube(10.0);
        face_filter(&mut engine);
        assert!(engine.select_top_at(400.0, 300.0), "selected the near face");
        let selected: String = engine.emphasis.selected_faces.iter().next().unwrap().clone();

        // "Edit the feature": re-run the history with a changed size (the same
        // feature id → the same deterministic entity names on new geometry).
        engine.run_history_json(&cube("UxCube", 12.0), None).unwrap();

        assert!(
            engine.emphasis.selected_faces.contains(&selected),
            "selection survives the re-run"
        );
        let names: Vec<String> = engine
            .scene
            .solids()
            .iter()
            .flat_map(|s| s.faces.iter().map(|f| f.name.clone()))
            .collect();
        assert!(
            names.contains(&selected),
            "the selected name re-attaches to the rebuilt scene: {selected} not in {names:?}"
        );
        // And the render-side emphasis lookup still lights it.
        assert_eq!(
            engine.emphasis.face_state("UxCube", &selected),
            crate::style::EmphasisState::Selected,
            "emphasis resolves the re-attached face"
        );
    }
}

// ===========================================================================
// Sketch mode (S1) — enter / exit / new an engine-native sketch edit.
//
// A SKETCH feature (`type "S"`) persists its editable state in
// `persistentData.sketch` (`{points, geometries, constraints}` — a `SketchDoc`)
// and its plane in `persistentData.basis` (a `PlaneFrame`). Entering sketch mode
// is fully HEADLESS: it reads that persisted state straight off the history JSON
// (no kernel SceneMap needed), rolls the model to the step BEFORE the sketch (the
// natural backdrop), orients the camera onto the plane, and holds a live solved
// [`crate::sketch::SketchSession`]. Exit writes the (possibly edited) doc back to
// `persistentData.sketch` (commit) or discards it — deleting the feature outright
// when it was a brand-new, never-committed sketch (cancel). The camera + rolled-to
// step are snapshotted on enter and restored on exit.
//
// This mirrors the reference-selection modal's enter/roll-before/finish/restore
// shape; kept in ONE appended block so concurrent edits to the primary impl land
// clean.
// ===========================================================================