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
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
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 {
// The viewport-selected CONSTRAINT (label click) clears with the rest.
let had_constraint = self.selected_constraint.is_some();
self.constraint_deselect();
let had_datums = !self.emphasis.selected_datums.is_empty();
let had = had_constraint
|| !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,
target: RefSelectTarget::Feature,
});
// 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 target = state.target;
// The field's RAW kind strings drive the pick (`pick_top_at` reads
// `DATUM` as an alias of `PLANE`), so a `["PLANE","FACE"]` sketchPlane
// field now picks a construction plane through the ORDINARY candidate
// list — including one sitting under a face, which the geometry-miss
// fallback below could never reach.
let picked = match self.pick_top_at(x, y, &filter) {
Some(hit) if hit.kind == pick::PickKind::Plane => {
// Accept ONLY a resolved D/P frame name, the same guard the
// fallback applies — a stray widget-fed plane never lands in a
// reference field.
if self.datum_feature_for_name(&hit.name).is_none() {
return;
}
hit.name
}
Some(hit) if !hit.name.trim().is_empty() => hit.name,
Some(hit) => {
// A vertex pick carries no kernel name. For an ASSEMBLY CONSTRAINT
// field that accepts VERTEX, build the `{solidName}@x,y,z` ref with
// COMPONENT-LOCAL coordinates (world pick · owning-component
// pose⁻¹ — the lane-E selection contract; the kernel resolver snaps
// to the nearest topology vertex). Everything else stays a no-op.
if target != RefSelectTarget::AssemblyConstraint
|| !matches!(hit.kind, pick::PickKind::Vertex)
{
return;
}
match self.component_vertex_ref(&hit.solid, hit.position) {
Some(vertex_ref) => vertex_ref,
None => return, // not component geometry — constraints reject it anyway
}
}
None => {
// TOTAL MISS. The plane CARDS are candidates above and they are
// the same set `datum_pick` tests, so in the app this arm is
// unreachable for a plane field; it is kept as a second line of
// defense for the tested `["PLANE","FACE"]` sketchPlane flow (and
// it is the ONLY path that would reach a datum AXIS, were one ever
// fed). Accept ONLY a resolved D/P frame name
// (`datum_feature_for_name`, mirroring `select_datum`'s guard) so an
// AXIS name — which `datum_pick` may also return — never lands in a
// plane field.
let admits_plane = filter
.iter()
.any(|k| k.eq_ignore_ascii_case("PLANE") || k.eq_ignore_ascii_case("DATUM"));
if !admits_plane {
return;
}
let name = self.datum_pick(x, y);
if name.is_empty() || self.datum_feature_for_name(&name).is_none() {
return;
}
name
}
};
let state = self.ref_select.as_mut().expect("active by guard above");
if multiple {
if !state.names.iter().any(|n| n == &picked) {
state.names.push(picked);
}
} else {
state.names = vec![picked];
}
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;
};
// An ASSEMBLY CONSTRAINT field commits through the constraint update
// lane (kernel session + document fold), not feature params; the shared
// end tail below still restores the roll + re-runs (which re-solves).
if state.target == RefSelectTarget::AssemblyConstraint {
self.assembly_commit_constraint_refs(
&state.feature_id,
&state.path,
&state.names,
state.multiple,
);
self.end_ref_select(state.restore_index);
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.
pub(crate) 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 {
// Case-INSENSITIVE match, mirroring `SelectionFilter::set` (which
// pick-filtering uses via `from_ref_filter`). Without this, a
// schema that spelled a kind non-canonically (e.g. `"Edge"`) would
// let the user PICK that kind but silently skip its seed HIGHLIGHT
// here — a lenient-pick / strict-highlight split. VERTEX is inert:
// vertex picks carry no kernel name, so `ref_select_click` never
// records one in `names` (empty-name early-return), so there is
// nothing to highlight by name.
let bucket = match kind.to_ascii_uppercase().as_str() {
"FACE" => "faces",
"EDGE" => "edges",
"SOLID" => "solids",
"PLANE" | "DATUM" => "datums",
_ => continue, // VERTEX (never name-seeded) / unknown
};
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);
// A picked construction PLANE/DATUM highlights through the datum-plane
// WIDGET, whose accent is baked at feed time (`refresh_construction_datums`
// reads `emphasis.selected_datums`) — so a plain `apply_json` does not
// re-color it. Re-feed here so a datum pick lights up (and un-lights on
// remove) in the modal. Harmless for non-datum fields (no datum selected →
// an ordinary calm-color re-feed).
self.refresh_construction_datums();
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.
pub(crate) 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();
}
match self.pick_top_at(x, y, &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_datums = !self.emphasis.hovered_datums.is_empty();
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()
|| had_datums;
if had {
self.emphasis.hovered_solids.clear();
self.emphasis.hovered_faces.clear();
self.emphasis.hovered_edges.clear();
self.emphasis.hovered_vertices.clear();
self.emphasis.hovered_datums.clear();
self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
self.dirty = true;
}
// A hovered plane's accent is baked into the datum feed, so dropping the
// hover needs a re-feed to un-light it (the datum twin of the selection
// re-feed in `clear_selection`).
if had_datums {
self.refresh_construction_datums();
}
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();
let datums: Vec<&String> = self.emphasis.hovered_datums.iter().collect();
serde_json::json!({
"solids": solids,
"faces": faces,
"edges": edges,
"datums": datums,
"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). With the COMPONENT filter on, a hit on component geometry
/// toggles the whole component (all member solids as one unit). 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();
let component_on = self.selection_filter.component;
if kinds.is_empty() && !component_on {
return false;
}
let pick_kinds = if kinds.is_empty() {
SelectionFilter::default().enabled_kinds()
} else {
kinds.clone()
};
match self.pick_top_at(x, y, &pick_kinds) {
Some(hit) => {
// COMPONENT promotion (the select_filtered_at rule, additively):
// toggle the WHOLE component's member solids as one unit, so a
// Ctrl/Cmd+click gathers the multi-component selections the
// pair-constraint offers key on.
if component_on {
if let Some(owner) = self.hit_owning_component(&hit) {
self.toggle_component_selection(&owner);
return true;
}
}
if kinds.is_empty() {
return false; // COMPONENT-only, non-component 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 pick-list popup + the headed verifier).
///
/// Sorted category-major in the pick-list order (VERTEX > EDGE > FACE >
/// PLANE > SOLID > COMPONENT), nearest (smallest depth) first within each
/// category — see [`candidates_filtered_at`](Self::candidates_filtered_at).
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": self.candidate_kind_label(c),
"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 pick-list 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).
///
/// The raw list is [`pick_candidates_at`](Self::pick_candidates_at), so
/// construction PLANE cards are ordinary entries here — a plane under other
/// geometry is listed (right after the faces) instead of being reachable only
/// on a geometry miss.
///
/// With the filter's COMPONENT lane on, one COMPONENT entry per owning
/// assembly component of ANY raw hit is appended (name = component id, depth
/// = the component's nearest hit) — a raw hit of a filtered-OFF kind still
/// reaches its owning component, mirroring `select_filtered_at`'s
/// component-only promotion (a PLANE hit owns no component). The final list is
/// sorted category-major in the pick-list order
/// (VERTEX > EDGE > FACE > PLANE > SOLID > COMPONENT), nearest first within
/// each category.
pub fn candidates_filtered_at(&self, x: f64, y: f64) -> Vec<pick::PickCandidate> {
let kinds = self.selection_filter.enabled_kinds();
let component_on = self.selection_filter.component;
if kinds.is_empty() && !component_on {
return Vec::new();
}
let raw = self.pick_candidates_at(x, y);
let mut out: Vec<pick::PickCandidate> = raw
.iter()
.filter(|c| self.candidate_admitted(&kinds, c))
.cloned()
.collect();
if component_on {
// One entry per owning component, carrying its NEAREST member hit's
// depth/position (raw hits are kind-major, so scan them all).
let mut components: Vec<pick::PickCandidate> = Vec::new();
for hit in &raw {
let Some(owner) = self.hit_owning_component(hit) else {
continue;
};
match components.iter_mut().find(|c| c.name == owner) {
Some(entry) => {
if hit.depth < entry.depth {
entry.depth = hit.depth;
entry.position = hit.position;
}
}
None => components.push(pick::PickCandidate {
kind: pick::PickKind::Component,
name: owner,
solid: String::new(),
depth: hit.depth,
screen_dist: hit.screen_dist,
position: hit.position,
}),
}
}
out.extend(components);
}
// Category-major (PickKind's discriminant order IS the pick-list order),
// nearest first within a category — the shared ordering every pick path
// uses, so the appended COMPONENT rows land in the same sort.
super::plane_pick::sort_pick_candidates(&mut out);
out
}
/// Whether a candidate is CURRENTLY selected (drives the pick-list popup's
/// per-row selected state so click-toggling reads back visually).
pub fn candidate_is_selected(&self, candidate: &pick::PickCandidate) -> bool {
use crate::pick::PickKind;
match candidate.kind {
PickKind::Solid => self
.emphasis
.selected_solids
.contains(&self.candidate_solid_name(candidate)),
PickKind::Face => self.emphasis.selected_faces.contains(&candidate.name),
PickKind::Edge => self.emphasis.selected_edges.contains(&candidate.name),
PickKind::Vertex => self
.emphasis
.selected_vertices
.iter()
.any(|v| Self::vertex_ref_matches(v, candidate)),
PickKind::Plane => self.emphasis.selected_datums.contains(&candidate.name),
PickKind::Component => {
let members = self.component_member_solids(&candidate.name);
!members.is_empty()
&& members
.iter()
.all(|m| self.emphasis.selected_solids.contains(m))
}
}
}
/// 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
}
}
PickKind::Plane => {
// A construction PLANE toggles by FRAME NAME, the datum bucket the
// Scene-tree row / `select_datum` fill.
if self.emphasis.selected_datums.remove(&candidate.name) {
false
} else {
self.emphasis.selected_datums.insert(candidate.name.clone());
true
}
}
PickKind::Component => {
// The whole component toggles as ONE unit (member solids), the
// same rule as the Ctrl/Cmd+click COMPONENT promotion.
let was_selected = self.candidate_is_selected(candidate);
self.toggle_component_selection(&candidate.name);
!was_selected
}
};
self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
self.dirty = true;
// A plane's accent is baked into the datum feed, so a toggled plane only
// lights / un-lights after a re-feed.
if candidate.kind == PickKind::Plane {
self.refresh_construction_datums();
}
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;
// A hovered PLANE's accent lives in the datum FEED, so the re-feed below
// is needed both when a plane becomes hovered and when one stops being.
let touches_datums =
!self.emphasis.hovered_datums.is_empty() || candidate.kind == PickKind::Plane;
self.emphasis.hovered_solids.clear();
self.emphasis.hovered_faces.clear();
self.emphasis.hovered_edges.clear();
self.emphasis.hovered_vertices.clear();
self.emphasis.hovered_datums.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,
});
}
PickKind::Plane => {
self.emphasis.hovered_datums.insert(candidate.name.clone());
}
PickKind::Component => {
// Hovering a COMPONENT entry lights every member solid.
for member in self.component_member_solids(&candidate.name) {
self.emphasis.hovered_solids.insert(member);
}
}
}
self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
self.dirty = true;
if touches_datums {
self.refresh_construction_datums();
}
}
/// Whether the CURRENT hover is exactly this one candidate (the `hover_at`
/// early-out) — a single hovered entity that matches `candidate` (for a
/// COMPONENT candidate: exactly its member-solid set).
fn hover_is(&self, candidate: &pick::PickCandidate) -> bool {
use crate::pick::PickKind;
if candidate.kind == PickKind::Component {
let members = self.component_member_solids(&candidate.name);
return !members.is_empty()
&& self.emphasis.hovered_faces.is_empty()
&& self.emphasis.hovered_edges.is_empty()
&& self.emphasis.hovered_vertices.is_empty()
&& self.emphasis.hovered_datums.is_empty()
&& self.emphasis.hovered_solids.len() == members.len()
&& members.iter().all(|m| self.emphasis.hovered_solids.contains(m));
}
let total = self.emphasis.hovered_solids.len()
+ self.emphasis.hovered_faces.len()
+ self.emphasis.hovered_edges.len()
+ self.emphasis.hovered_vertices.len()
+ self.emphasis.hovered_datums.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)),
PickKind::Plane => self.emphasis.hovered_datums.contains(&candidate.name),
PickKind::Component => false, // handled by the early return above
}
}
/// 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));
// The zoom this screen-constant sizing was baked at, so the per-frame
// `ensure_sketch_overlay_current` re-bakes it when the camera zooms.
self.sketch_overlay_wpp = if world_per_pixel > 0.0 {
world_per_pixel
} else {
f64::MIN_POSITIVE
};
}
/// 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\"}]}",
);
self.sketch_overlay_wpp = 0.0;
}
}
#[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,
sketch: false,
face: true,
edge: false,
vertex: false,
plane: false,
component: 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,
sketch: true,
face: false,
edge: false,
vertex: false,
plane: false,
component: 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,
sketch: false,
face: false,
edge: false,
vertex: false,
plane: false,
component: 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,
sketch: true,
face: false,
edge: false,
vertex: false,
plane: false,
component: 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));
}
/// COMPONENT entries in the pick list: with the filter's COMPONENT lane on,
/// the candidate list appends one COMPONENT entry per owning component AFTER
/// the solids (the category order points > edges > faces > solids >
/// components), and toggling that entry selects/deselects the whole
/// component's member solids as one unit.
#[test]
fn candidates_include_component_entries_and_toggle_whole_components() {
use crate::engine_state::component_fixtures::two_instance_assembly_json;
let mut engine = EngineState::new();
engine.set_history_json(&two_instance_assembly_json()).unwrap();
engine.resize(800.0, 600.0);
engine.camera.eye = [25.0, 5.0, 45.0];
engine.camera.target = [25.0, 5.0, 5.0];
engine.camera.up = [0.0, 1.0, 0.0];
engine.camera.projection = crate::view::Projection::Orthographic { half_height: 20.0 };
// Default filter (COMPONENT on): the ACOMP2 click spot lists its faces,
// the owning solid, and ONE trailing COMPONENT entry — category-major
// (kind ranks never decrease down the list).
let cands = engine.candidates_filtered_at(400.0, 300.0);
assert!(cands.len() >= 3, "faces + solid + component: {cands:?}");
let ranks: Vec<u8> = cands.iter().map(|c| c.kind as u8).collect();
assert!(
ranks.windows(2).all(|w| w[0] <= w[1]),
"category-major order: {ranks:?}"
);
let components: Vec<_> = cands
.iter()
.filter(|c| c.kind == pick::PickKind::Component)
.collect();
assert_eq!(components.len(), 1, "one owning component: {cands:?}");
assert_eq!(components[0].name, "ACOMP2");
assert_eq!(
cands.last().unwrap().kind,
pick::PickKind::Component,
"components list last"
);
assert!(
cands.iter().any(|c| c.kind == pick::PickKind::Solid && c.name == "ACOMP2:Part"),
"the member solid still lists under its own category: {cands:?}"
);
// Toggling the COMPONENT entry selects the member solids as one unit…
let comp = components[0].clone();
assert!(!engine.candidate_is_selected(&comp));
assert!(engine.toggle_candidate(&comp), "component added");
assert!(engine.candidate_is_selected(&comp));
let sel: serde_json::Value = serde_json::from_str(&engine.selection_json()).unwrap();
assert_eq!(sel["solids"], serde_json::json!(["ACOMP2:Part"]), "{sel}");
// …and toggling again removes the whole unit.
assert!(!engine.toggle_candidate(&comp), "component removed");
assert!(!engine.has_selection());
// Hovering the COMPONENT entry lights every member solid.
engine.hover_candidate(&comp);
let hov: serde_json::Value = serde_json::from_str(&engine.hovered_json()).unwrap();
assert_eq!(hov["solids"], serde_json::json!(["ACOMP2:Part"]), "{hov}");
// COMPONENT lane off → no COMPONENT entries.
let mut f = engine.selection_filter();
f.component = false;
engine.set_selection_filter(f);
let cands = engine.candidates_filtered_at(400.0, 300.0);
assert!(
cands.iter().all(|c| c.kind != pick::PickKind::Component),
"no component entries with the lane off: {cands:?}"
);
// COMPONENT-only: the list is exactly the component entries (sub-entity
// kinds are filtered out, but their raw hits still reach the owner).
engine.set_selection_filter(SelectionFilter {
solid: false,
sketch: false,
face: false,
edge: false,
vertex: false,
plane: false,
component: true,
});
let cands = engine.candidates_filtered_at(400.0, 300.0);
assert!(!cands.is_empty(), "component-only still lists the owner");
assert!(
cands.iter().all(|c| c.kind == pick::PickKind::Component),
"component-only lists only components: {cands:?}"
);
}
/// 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.
// ===========================================================================