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

    fn cube_request(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 runner that accepts everything, replies to nothing, and CAN be
    /// abandoned — the shape of a background runner stuck inside a feature.
    struct Abandonable;

    impl crate::runner::HistoryRunner for Abandonable {
        fn submit_run(&mut self, _request: brep_kernel::HistoryRequest, _generation: u64) {}
        fn poll_run(&mut self) -> Option<crate::runner::RunReply> {
            None
        }
        fn submit_query(&mut self, _query: crate::runner::MeasureQuery) {}
        fn poll_query(&mut self) -> Option<crate::runner::MeasureReply> {
            None
        }
        fn submit_mesh_import(&mut self, _request: crate::runner::MeshImportRequest) {}
        fn poll_mesh_import(&mut self) -> Option<crate::runner::MeshImportReply> {
            None
        }
        fn submit_step_probe(&mut self, _request: crate::runner::StepProbeRequest) {}
        fn poll_step_probe(&mut self) -> Option<crate::runner::StepProbeReply> {
            None
        }
        fn reset(&mut self) {}
        fn cancel(&mut self) -> bool {
            true
        }
    }

    /// Cancelling an in-flight run: the engine stops waiting (no spinner, no
    /// stale reply can ever apply), keeps the LAST COMPLETED scene, records
    /// what it was cancelled on, and says so; the next edit submits a fresh
    /// run and clears the note. With nothing in flight — or under the
    /// synchronous Inline runner — there is nothing to cancel.
    #[test]
    fn cancel_run_abandons_the_run_and_keeps_the_last_result() {
        let mut state = EngineState::new();
        assert!(!state.cancel_run(), "Inline: nothing is ever pending");
        state.set_history_json(&cube_request("Box", 10.0)).unwrap();
        assert_eq!(state.scene.solids().len(), 1);
        let params = |size: f64| {
            format!(
                r#"{{"id":"Box","sizeX":{size},"sizeY":{size},"sizeZ":{size},"transform":{{"position":[0,0,0],"rotationEuler":[0,0,0],"scale":[1,1,1]}},"boolean":{{"targets":[],"operation":"NONE"}}}}"#
            )
        };

        state.set_runner(Box::new(Abandonable));
        state.update_feature_params("Box", &params(12.0)).unwrap();
        assert!(state.run_pending(), "the stuck runner never replies");
        assert!(state.run_progress().is_none(), "no progress was ever posted");
        let _ = state.take_notices();

        assert!(state.cancel_run());
        assert!(!state.run_pending(), "nothing is waited on any more");
        assert_eq!(state.cancelled_run(), Some(""), "cancelled before any progress");
        assert_eq!(state.scene.solids().len(), 1, "the last completed result stays on screen");
        let notices = state.take_notices();
        assert!(
            notices.iter().any(|n| n.starts_with("Run cancelled.")),
            "the user is told: {notices:?}"
        );
        assert!(!state.cancel_run(), "nothing pending now");

        // The document is AHEAD of the scene (the 12 edit is in the history);
        // the next edit re-runs it all and the cancelled note is gone.
        state.update_feature_params("Box", &params(14.0)).unwrap();
        assert!(state.run_pending());
        assert!(state.cancelled_run().is_none());
        assert!(state.history_request_json().contains("\"sizeX\":14"));
    }

    /// A 3-feature history mirroring the app seed: a cube `Box`, a cylinder
    /// `Pin`, and a boolean `Cut` = SUBTRACT(targetSolid=Box, tools=[Pin]).
    fn boolean_history() -> String {
        serde_json::json!({
            "expressions": "",
            "configurator": {},
            "features": [
                {
                    "type": "P.CU",
                    "inputParams": {
                        "id": "Box",
                        "sizeX": 20.0, "sizeY": 20.0, "sizeZ": 20.0,
                        "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": {}
                },
                {
                    "type": "P.CY",
                    "inputParams": {
                        "id": "Pin",
                        "radius": 6.0, "height": 30.0,
                        "transform": {
                            "position": [10.0, -5.0, 10.0],
                            "rotationEuler": [0.0, 0.0, 0.0],
                            "scale": [1.0, 1.0, 1.0]
                        },
                        "boolean": { "targets": [], "operation": "NONE" }
                    },
                    "persistentData": {}
                },
                {
                    "type": "B",
                    "inputParams": {
                        "id": "Cut",
                        "targetSolid": "Box",
                        "boolean": { "operation": "SUBTRACT", "targets": ["Pin"] }
                    },
                    "persistentData": {}
                }
            ]
        })
        .to_string()
    }

    #[test]
    fn ref_select_rolls_to_before_and_highlights_seed() {
        let mut engine = EngineState::new();
        engine.set_history_json(&boolean_history()).unwrap();
        // At the last step the boolean has run → one subtracted solid.
        assert_eq!(engine.scene.solids().len(), 1);

        engine.begin_ref_select(
            "Cut",
            vec!["targetSolid".into()],
            "Target solid".into(),
            vec!["SOLID".into()],
            false,
            vec!["Box".into()],
        );
        assert!(engine.ref_select_active());
        // Rolled to the pre-feature "before" state: cube + cylinder, un-subtracted.
        assert_eq!(engine.scene.solids().len(), 2);
        // The seed name is highlighted.
        assert!(engine.emphasis.selected_solids.contains("Box"));
        assert_eq!(engine.ref_select_names(), vec!["Box".to_string()]);
    }

    /// Regression: a field that allows several kinds (e.g. `FACE`/`EDGE`, FACE
    /// listed first) must highlight an EDGE pick as an EDGE — not silently drop it
    /// into `selected_faces` (the old `filter.first()`-only bucketing) where it
    /// matched no face and never showed in the viewport.
    #[test]
    fn ref_select_edge_pick_under_a_face_edge_filter_highlights_the_edge() {
        let mut engine = EngineState::new();
        engine.set_history_json(&boolean_history()).unwrap();
        engine.begin_ref_select(
            "Cut",
            vec!["edgeRef".into()],
            "Edges".into(),
            vec!["FACE".into(), "EDGE".into()],
            true,
            vec!["Box_PY|Box_PZ[0]".into()],
        );
        // The picked edge lands in the EDGE bucket, so `edge_state` will emphasize it.
        assert!(
            engine.emphasis.selected_edges.contains("Box_PY|Box_PZ[0]"),
            "an edge pick under a FACE-first filter must highlight as an edge"
        );
        // Cross-listed into faces too — harmless, since no FACE carries that name.
        assert!(engine.emphasis.selected_faces.contains("Box_PY|Box_PZ[0]"));
    }

    /// HARDENING: the seed-highlight bucketing matches the filter kind CASE-
    /// INSENSITIVELY (aligned with `SelectionFilter::set`, which pick-filtering
    /// uses), so a non-canonically-spelled filter can no longer let you PICK a
    /// kind while silently skipping its seed HIGHLIGHT.
    #[test]
    fn ref_select_seed_highlights_under_a_noncanonical_case_filter() {
        let mut engine = EngineState::new();
        engine.set_history_json(&boolean_history()).unwrap();
        engine.begin_ref_select(
            "Cut",
            vec!["edgeRef".into()],
            "Edges".into(),
            vec!["edge".into()], // lower-case on purpose
            true,
            vec!["Box_PY|Box_PZ[0]".into()],
        );
        assert!(
            engine.emphasis.selected_edges.contains("Box_PY|Box_PZ[0]"),
            "a lower-case `edge` filter must still highlight the edge seed"
        );
    }

    #[test]
    fn ref_select_finish_writes_single_ref_and_restores() {
        let mut engine = EngineState::new();
        engine.set_history_json(&boolean_history()).unwrap();
        engine.begin_ref_select(
            "Cut",
            vec!["targetSolid".into()],
            "Target solid".into(),
            vec!["SOLID".into()],
            false,
            vec![],
        );
        // Simulate a pick (unit test has no camera set up for a real ray).
        engine.ref_select.as_mut().unwrap().names = vec!["Box".into()];
        engine.finish_ref_select();

        assert!(!engine.ref_select_active());
        assert!(engine.emphasis.is_empty(), "highlight cleared on finish");
        // Restored to the boolean step: back to a single subtracted solid.
        assert_eq!(engine.scene.solids().len(), 1);
        // The param was written.
        let idx = engine.history.index_of("Cut").unwrap();
        let params = engine.history.feature_params(idx).unwrap();
        assert_eq!(params["targetSolid"], "Box");
    }

    #[test]
    fn ref_select_finish_writes_multiple_nested_ref() {
        let mut engine = EngineState::new();
        engine.set_history_json(&boolean_history()).unwrap();
        engine.begin_ref_select(
            "Cut",
            vec!["boolean".into(), "targets".into()],
            "Tool solids".into(),
            vec!["SOLID".into()],
            true,
            vec![],
        );
        let state = engine.ref_select.as_mut().unwrap();
        state.names = vec!["Pin".into()];
        // De-dup: re-adding an existing name is a no-op (mirrors ref_select_click).
        if !state.names.iter().any(|n| n == "Pin") {
            state.names.push("Pin".into());
        }
        engine.finish_ref_select();

        let idx = engine.history.index_of("Cut").unwrap();
        let params = engine.history.feature_params(idx).unwrap();
        assert_eq!(params["boolean"]["targets"], serde_json::json!(["Pin"]));
    }

    #[test]
    fn ref_select_remove_and_cancel_leave_params_untouched() {
        let mut engine = EngineState::new();
        engine.set_history_json(&boolean_history()).unwrap();
        let idx = engine.history.index_of("Cut").unwrap();
        let before = engine.history.feature_params(idx).unwrap();

        engine.begin_ref_select(
            "Cut",
            vec!["boolean".into(), "targets".into()],
            "Tool solids".into(),
            vec!["SOLID".into()],
            true,
            vec!["Pin".into(), "Box".into()],
        );
        engine.ref_select_remove(0); // drop "Pin"
        assert_eq!(engine.ref_select_names(), vec!["Box".to_string()]);
        engine.cancel_ref_select();

        assert!(!engine.ref_select_active());
        assert!(engine.emphasis.is_empty());
        // Cancel discarded everything: params are exactly as before.
        assert_eq!(engine.history.feature_params(idx).unwrap(), before);
        assert_eq!(engine.scene.solids().len(), 1);
    }

    // --- ref-select follows the field's allowed kinds (selection filter) -------

    /// Entering ref-select for a `["SOLID"]` field constrains the GLOBAL selection
    /// filter to Solid-only; finishing restores the all-enabled default.
    #[test]
    fn ref_select_solid_field_constrains_filter_then_finish_restores() {
        let mut engine = EngineState::new();
        engine.set_history_json(&boolean_history()).unwrap();
        // Out of ref-select: everything is pickable (the new default).
        assert_eq!(engine.selection_filter(), SelectionFilter::default());

        engine.begin_ref_select(
            "Cut",
            vec!["targetSolid".into()],
            "Target solid".into(),
            vec!["SOLID".into()],
            false,
            vec![],
        );
        // Only Solid is pickable while the SOLID field's picker is active — and
        // NOT sketches: a committed sketch picks as a `PickKind::Solid` too, but
        // it registers no kernel solid, so admitting one here would offer a name
        // the feature could never resolve.
        let f = engine.selection_filter();
        assert!(f.solid && !f.face && !f.edge && !f.vertex, "solid-only: {f:?}");
        assert!(!f.sketch, "a SOLID field must not admit committed sketches: {f:?}");
        assert_eq!(
            engine.selection_filter_json(),
            r#"{"SOLID":true,"SKETCH":false,"FACE":false,"EDGE":false,"VERTEX":false,"PLANE":false,"COMPONENT":false}"#
        );

        engine.ref_select.as_mut().unwrap().names = vec!["Box".into()];
        engine.finish_ref_select();
        // Finish restored the all-enabled default.
        assert_eq!(engine.selection_filter(), SelectionFilter::default());
    }

    /// A multi-kind field (`["FACE","EDGE"]`) enables EXACTLY those kinds; cancel
    /// restores the all-enabled default.
    #[test]
    fn ref_select_face_edge_field_enables_exactly_those_then_cancel_restores() {
        let mut engine = EngineState::new();
        engine.set_history_json(&boolean_history()).unwrap();
        engine.begin_ref_select(
            "Cut",
            vec!["faceRef".into()],
            "Faces / edges".into(),
            vec!["FACE".into(), "EDGE".into()],
            true,
            vec![],
        );
        let f = engine.selection_filter();
        assert!(
            !f.solid && f.face && f.edge && !f.vertex,
            "face+edge only: {f:?}"
        );
        engine.cancel_ref_select();
        assert_eq!(engine.selection_filter(), SelectionFilter::default());
    }

    /// A sketch-plane field (`["PLANE","FACE"]`): the construction PLANE kind has
    /// no pickable-kind equivalent, so the filter maps to FACE-only (never empty).
    /// Plane/datum picking rides the independent `datum_pick` widget path, so this
    /// mapping does not affect sketch-plane selection.
    #[test]
    fn ref_select_plane_face_field_maps_to_face_only() {
        let mut engine = EngineState::new();
        engine.set_history_json(&boolean_history()).unwrap();
        engine.begin_ref_select(
            "Cut",
            vec!["plane".into()],
            "Sketch plane".into(),
            vec!["PLANE".into(), "FACE".into()],
            false,
            vec![],
        );
        let f = engine.selection_filter();
        assert!(!f.solid && f.face && !f.edge && !f.vertex, "face-only: {f:?}");
        engine.cancel_ref_select();
        assert_eq!(engine.selection_filter(), SelectionFilter::default());
    }

    /// A construction-ONLY field (`["DATUM"]`, e.g. a plane/datum ref) admits
    /// exactly ONE kind — the construction PLANE cards (`DATUM` is the schema's
    /// other spelling of `PLANE`) — and disables every GEOMETRY kind, rather than
    /// collapsing to the all-enabled default (which would highlight/pick solids,
    /// faces, and edges the field does not want). Cancel restores the default.
    #[test]
    fn ref_select_datum_only_field_disables_pickable_kinds() {
        let mut engine = EngineState::new();
        engine.set_history_json(&boolean_history()).unwrap();
        engine.begin_ref_select(
            "Cut",
            vec!["datum".into()],
            "Datum".into(),
            vec!["DATUM".into()],
            false,
            vec![],
        );
        let f = engine.selection_filter();
        assert!(
            !f.solid && !f.face && !f.edge && !f.vertex && !f.component,
            "construction-only field disables every GEOMETRY kind: {f:?}"
        );
        assert!(f.plane, "…and admits the construction planes it asked for: {f:?}");
        engine.cancel_ref_select();
        assert_eq!(engine.selection_filter(), SelectionFilter::default());
    }

    /// An ABSENT / empty field filter (a `reference_selection` with no
    /// `selectionFilter`) falls back to all-enabled, not no-selection.
    #[test]
    fn ref_select_empty_field_filter_falls_back_to_all_enabled() {
        let mut engine = EngineState::new();
        engine.set_history_json(&boolean_history()).unwrap();
        engine.begin_ref_select(
            "Cut",
            vec!["anything".into()],
            "Anything".into(),
            vec![],
            false,
            vec![],
        );
        assert_eq!(engine.selection_filter(), SelectionFilter::default());
    }

    /// The bare mapping (independent of a live history): SOLID/FACE/EDGE/VERTEX map
    /// one-to-one and the construction spellings PLANE/DATUM both map to the PLANE
    /// lane (construction planes are ordinary pick candidates now); only a
    /// genuinely empty/unknown filter falls back to all-enabled.
    #[test]
    fn from_ref_filter_maps_kinds_and_falls_back() {
        let m = |v: &[&str]| {
            SelectionFilter::from_ref_filter(&v.iter().map(|s| s.to_string()).collect::<Vec<_>>())
        };
        assert_eq!(
            m(&["SOLID"]),
            SelectionFilter { solid: true, sketch: false, face: false, edge: false, vertex: false, plane: false, component: false }
        );
        assert_eq!(
            m(&["FACE", "EDGE"]),
            SelectionFilter { solid: false, sketch: false, face: true, edge: true, vertex: false, plane: false, component: false }
        );
        // A `["PLANE","FACE"]` sketchPlane field admits planes AND faces — and
        // still NOTHING else: no solids, no edges (the no-regress rule).
        assert_eq!(
            m(&["PLANE", "FACE"]),
            SelectionFilter { solid: false, sketch: false, face: true, edge: false, vertex: false, plane: true, component: false }
        );
        // COMPONENT maps to promotion + member-SOLID hover preview.
        assert_eq!(
            m(&["COMPONENT"]),
            SelectionFilter { solid: true, sketch: false, face: false, edge: false, vertex: false, plane: false, component: true }
        );
        // A CONSTRUCTION-ONLY field (PLANE/DATUM — the same lane under both
        // spellings) admits the plane cards and nothing else; it never collapses
        // to all-enabled, so it cannot light up solids/faces/edges.
        let plane_only = SelectionFilter {
            solid: false,
            sketch: false,
            face: false,
            edge: false,
            vertex: false,
            plane: true,
            component: false,
        };
        assert_eq!(m(&["DATUM"]), plane_only);
        assert_eq!(m(&["PLANE"]), plane_only);
        // SKETCH is its OWN lane, split off `PickKind::Solid`: a `["SOLID"]` field
        // (a boolean target, a mirror body) does NOT light it up — a committed
        // sketch registers no kernel solid, so its name could never resolve there
        // — and a `["SKETCH"]` field lights up only it.
        assert!(!m(&["SOLID"]).sketch, "a SOLID field must not admit sketches");
        assert_eq!(
            m(&["SKETCH"]),
            SelectionFilter { solid: false, sketch: true, face: false, edge: false, vertex: false, plane: false, component: false }
        );
        // The sweep's own path field: whole sketches AND individual edges, nothing
        // else. `any_enabled` must count the sketch lane, or a SKETCH-only field
        // would fall through to the all-enabled fallback and admit everything.
        assert_eq!(
            m(&["SKETCH", "EDGE"]),
            SelectionFilter { solid: false, sketch: true, face: false, edge: true, vertex: false, plane: false, component: false }
        );
        assert!(m(&["SKETCH"]).any_enabled(), "a SKETCH-only filter is not empty");
        // Only a genuinely empty filter falls back to all-enabled.
        assert_eq!(m(&[]), SelectionFilter::default());
    }

    #[test]
    fn run_history_feeds_scene_and_lists_it() {
        let mut engine = EngineState::new();
        let report = engine
            .run_history_json(&cube_request("EngineCube", 10.0))
            .unwrap();
        assert!(report.contains("featureErrors"));
        assert_eq!(engine.scene.solids().len(), 1);
        let listing: serde_json::Value =
            serde_json::from_str(&engine.scene_listing_json()).unwrap();
        assert_eq!(listing[0]["name"], "EngineCube");
        assert_eq!(listing[0]["visible"], true);
        assert_eq!(listing[0]["faces"], 6);
    }

    #[test]
    fn pick_and_hover_return_kernel_names() {
        let mut engine = EngineState::new();
        engine
            .run_history_json(&cube_request("PickCube", 10.0))
            .unwrap();
        engine.resize(800.0, 600.0);
        engine.camera.eye = [5.0, 5.0, 60.0];
        engine.camera.target = [5.0, 5.0, 5.0];
        engine.camera.up = [0.0, 1.0, 0.0];
        engine.camera.projection = crate::view::Projection::Orthographic { half_height: 10.0 };

        let hits: serde_json::Value = serde_json::from_str(&engine.pick_json(400.0, 300.0)).unwrap();
        assert!(hits.as_array().unwrap().len() >= 2);
        assert_eq!(hits[0]["kind"], "FACE");
        assert!(hits[0]["name"].as_str().unwrap().len() > 0);
        assert_eq!(hits.as_array().unwrap().last().unwrap()["kind"], "SOLID");

        let hover: serde_json::Value = serde_json::from_str(&engine.hover_json(400.0, 300.0)).unwrap();
        assert_eq!(hover["kind"], "FACE");
        // A miss hovers nothing.
        assert_eq!(engine.hover_json(5.0, 5.0), "null");
    }

    #[test]
    fn world_to_screen_roundtrips_center() {
        let mut engine = EngineState::new();
        engine.resize(640.0, 480.0);
        engine.camera.eye = [0.0, 0.0, 20.0];
        engine.camera.target = [0.0, 0.0, 0.0];
        engine.camera.projection = crate::view::Projection::Orthographic { half_height: 10.0 };
        let out: Vec<[f64; 4]> =
            serde_json::from_str(&engine.world_to_screen_json("[[0,0,0]]").unwrap()).unwrap();
        assert!((out[0][0] - 320.0).abs() < 1e-9);
        assert!((out[0][1] - 240.0).abs() < 1e-9);
        assert_eq!(out[0][3], 1.0);
    }

    #[test]
    fn camera_commands_set_dirty_and_persist() {
        let mut engine = EngineState::new();
        engine
            .run_history_json(&cube_request("C", 4.0))
            .unwrap();
        engine.dirty = false;
        engine.zoom_to_fit();
        assert!(engine.dirty);
        let saved = engine.camera_state_json();
        assert_eq!(engine.toggle_projection(), "perspective");
        engine.apply_camera_state_json(&saved).unwrap();
        // Restoring the saved ortho state comes back orthographic.
        assert!(matches!(
            engine.camera.projection,
            crate::view::Projection::Orthographic { .. }
        ));
    }

    #[test]
    fn viewcube_arrows_apply_relative_rotation() {
        use brep_gizmos::view_cube::ViewCube;
        let size = ViewCube::new().size() as f64;
        // Fixed sub-rect local px for an arrow given its screen-axis anchor.
        let loc = |sx: f64, sy: f64| ((0.5 + 0.5 * sx) * size, (0.5 - 0.5 * sy) * size);
        let rc = (0.99 + 2.0 * 0.80) / 3.0; // pan centroid radius

        let base = |engine: &mut EngineState| {
            engine.resize(800.0, 600.0);
            engine.set_viewcube_enabled(true);
            engine.camera.eye = [0.0, 20.0, 0.0];
            engine.camera.target = [0.0, 0.0, 0.0];
            engine.camera.up = [0.0, 0.0, 1.0];
        };

        // ARROW_RIGHT: orbit about screen-up (world +Z) — eye leaves +Y for the
        // screen-right side (world -X), z-height unchanged, up unchanged.
        let mut e = EngineState::new();
        base(&mut e);
        let (lx, ly) = loc(rc, 0.0);
        assert!(e.viewcube_click(lx, ly), "right arrow hit");
        assert!(e.camera.eye[0].abs() > 5.0, "orbited into X: {:?}", e.camera.eye);
        assert!(e.camera.eye[1].abs() < 1e-6, "left +Y: {:?}", e.camera.eye);
        assert!(e.camera.eye[2].abs() < 1e-6, "kept height: {:?}", e.camera.eye);
        assert_eq!(e.camera.up, [0.0, 0.0, 1.0], "orbit keeps up");

        // ARROW_LEFT orbits the opposite way about +Z.
        let mut e2 = EngineState::new();
        base(&mut e2);
        let (lx, ly) = loc(-rc, 0.0);
        assert!(e2.viewcube_click(lx, ly), "left arrow hit");
        assert!(
            e.camera.eye[0].signum() != e2.camera.eye[0].signum(),
            "left/right orbit opposite azimuth: {:?} vs {:?}",
            e.camera.eye,
            e2.camera.eye
        );

        // ARROW_UP: orbit about screen-right — eye rises to +Z, up tilts.
        let mut eu = EngineState::new();
        base(&mut eu);
        let (lx, ly) = loc(0.0, rc);
        assert!(eu.viewcube_click(lx, ly), "up arrow hit");
        assert!(eu.camera.eye[2] > 5.0, "elevated to +Z: {:?}", eu.camera.eye);
        assert_ne!(eu.camera.up, [0.0, 0.0, 1.0], "up-arrow tilts the up vector");

        // ROLL_CCW: roll about the view dir — up vector changes, eye fixed.
        let mut er = EngineState::new();
        base(&mut er);
        let eye_before = er.camera.eye;
        let (lx, ly) = loc(-0.66, 0.66 + 0.19);
        assert!(er.viewcube_click(lx, ly), "roll-ccw arrow hit");
        assert_eq!(er.camera.eye, eye_before, "roll leaves the eye put");
        assert_ne!(er.camera.up, [0.0, 0.0, 1.0], "roll spins the up vector");
    }

    /// The ViewCube-size setting must reach BOTH the rendered cube (its
    /// mini-camera scissor rect) AND the hit-test corner rect through the ONE
    /// `apply_settings_json` choke point — the render and pick paths read the same
    /// `viewcube.size`, so if the plumbing call is dropped, both go stale together
    /// and this test fails. Also pins the [40, 230] clamp and the round-trip
    /// through `settings_json` (the persisted buffer).
    #[test]
    fn viewcube_size_setting_scales_render_and_hit_rect() {
        use brep_gizmos::view_cube::ViewCube;
        let rect_wh = |e: &EngineState| -> (f64, f64) {
            let v: serde_json::Value =
                serde_json::from_str(&e.viewcube_rect_json()).unwrap();
            (v["w"].as_f64().unwrap(), v["h"].as_f64().unwrap())
        };

        let mut e = EngineState::new();
        e.resize(800.0, 600.0);
        e.set_viewcube_enabled(true);
        // Default: the widget's built-in size (unchanged until edited).
        assert_eq!(rect_wh(&e), (ViewCube::DEFAULT_SIZE_PX as f64, ViewCube::DEFAULT_SIZE_PX as f64));

        // Grow it: BOTH the hit-test rect and the rendered frame's scissor rect
        // (which shares `viewcube.size` with the mini-camera viewport) follow.
        e.apply_settings_json(r#"{"viewcubeSizePx": 200}"#).unwrap();
        assert_eq!(e.settings.viewcube_size_px, 200.0);
        assert_eq!(rect_wh(&e), (200.0, 200.0), "hit-test rect scaled");
        let frame = e.build_widget_overlay().and_then(|o| o.viewcube).expect("cube built");
        assert!((frame.rect_css[2] - 200.0).abs() < 1e-3 && (frame.rect_css[3] - 200.0).abs() < 1e-3,
            "rendered cube scissor rect scaled: {:?}", frame.rect_css);

        // Out-of-range values clamp to [40, 230] (matching the slider bounds).
        e.apply_settings_json(r#"{"viewcubeSizePx": 9000}"#).unwrap();
        assert_eq!(e.settings.viewcube_size_px, 230.0);
        e.apply_settings_json(r#"{"viewcubeSizePx": 5}"#).unwrap();
        assert_eq!(e.settings.viewcube_size_px, 40.0);

        // The value round-trips through the persisted settings buffer.
        assert!(e.settings_json().contains("\"viewcubeSizePx\":40"), "persisted: {}", e.settings_json());
    }

    #[test]
    fn settings_and_visibility_toggles() {
        let mut engine = EngineState::new();
        engine
            .run_history_json(&cube_request("V", 4.0))
            .unwrap();
        let gen0 = engine.settings_generation;
        engine.apply_settings_json(r##"{"flatShading": true, "faceColor": "#ff0000"}"##).unwrap();
        assert!(engine.settings.flat_shading);
        assert_ne!(engine.settings_generation, gen0);
        assert!(engine.set_visible("V", false));
        assert!(!engine.scene.solid("V").unwrap().visible);
        assert!(!engine.set_visible("Nope", false));
    }

    // The "LOD factor" setting scales DISPLAY tessellation, so a change re-runs
    // history (to re-tessellate at the new chord); re-applying the SAME value — or
    // any non-lod setting — must not, and a lod change with no document loaded must
    // not run an empty history (the boot-restore guard).
    #[test]
    fn lod_factor_change_reruns_once_repeats_and_non_lod_do_not() {
        // Boot guard: an empty history must not re-run on a quality change. The
        // "Render Quality" dropdown maps Draft→lod 4.0 (see style::RENDER_QUALITY).
        let mut empty = EngineState::new();
        let boot_gen = empty.run_generation;
        empty.apply_settings_json(r##"{"renderQuality": "Draft"}"##).unwrap();
        assert_eq!(empty.settings.lod_factor, 4.0);
        assert_eq!(
            empty.run_generation, boot_gen,
            "a quality change with no document loaded must not re-run"
        );

        // With a document LOADED (set_history_json populates self.history — the
        // document rerun_history reads; run_history_json is a scene-only one-shot),
        // a quality CHANGE submits exactly one re-run. Low→lod 2.0 (≠ default 1.0).
        let mut engine = EngineState::new();
        engine.set_history_json(&cube_request("Ball", 6.0)).unwrap();
        let gen0 = engine.run_generation;
        engine.apply_settings_json(r##"{"renderQuality": "Low"}"##).unwrap();
        assert_eq!(engine.settings.lod_factor, 2.0);
        assert_eq!(engine.run_generation, gen0 + 1, "a quality change must submit one re-run");

        // Re-applying the SAME quality must not re-run.
        let gen1 = engine.run_generation;
        engine.apply_settings_json(r##"{"renderQuality": "Low"}"##).unwrap();
        assert_eq!(engine.run_generation, gen1, "an unchanged quality must not re-run");

        // A non-lod setting change must not re-run.
        engine.apply_settings_json(r##"{"flatShading": true}"##).unwrap();
        assert_eq!(engine.run_generation, gen1, "a non-lod setting change must not re-run");
    }

    #[test]
    fn full_buffer_apply_keeps_wireframe_and_still_changes_lod() {
        // The exact repro for "changing Render Quality resets my wireframe": the
        // TOOLBAR flips wireframe with a PARTIAL apply, then the settings panel
        // applies its WHOLE buffer to change Render Quality. The panel now re-seeds
        // that buffer from `settings_json()` every frame, so the buffer it sends
        // carries the live wireframe=true — the full-buffer apply must NOT reset it,
        // and the quality change must still take effect (one re-run).
        let mut engine = EngineState::new();
        engine.set_history_json(&cube_request("Ball", 6.0)).unwrap();
        engine.apply_settings_json(r##"{"wireframe": true}"##).unwrap(); // toolbar path
        assert!(engine.settings.wireframe);

        // `settings_json()` is EXACTLY what the panel re-seeds from, so this is the
        // buffer the panel would apply after the user picks a new quality.
        let mut buf: serde_json::Value =
            serde_json::from_str(&engine.settings_json()).unwrap();
        buf["renderQuality"] = serde_json::Value::String("Draft".into());
        let gen0 = engine.run_generation;
        engine.apply_settings_json(&buf.to_string()).unwrap();

        assert!(engine.settings.wireframe, "full-buffer apply must NOT reset wireframe");
        assert_eq!(engine.settings.lod_factor, 4.0, "Render Quality must still change the lod");
        assert_eq!(engine.run_generation, gen0 + 1, "the lod change must re-run exactly once");
    }

    #[test]
    fn projection_round_trips_through_the_settings_apply_path() {
        let ortho =
            |e: &EngineState| matches!(e.camera.projection, crate::view::Projection::Orthographic { .. });
        let reported = |e: &EngineState| {
            serde_json::from_str::<serde_json::Value>(&e.settings_json()).unwrap()["orthographic"]
                .as_bool()
                .unwrap()
        };
        let mut engine = EngineState::new();
        let start = ortho(&engine);
        assert_eq!(reported(&engine), start, "settings_json must report the LIVE projection");

        // Toolbar-toggle path: flip it via the settings-apply seam.
        engine
            .apply_settings_json(&format!("{{\"orthographic\": {}}}", !start))
            .unwrap();
        assert_eq!(ortho(&engine), !start, "apply must drive the camera");
        assert_eq!(reported(&engine), !start, "settings_json follows the camera");

        // Toggle back.
        engine
            .apply_settings_json(&format!("{{\"orthographic\": {start}}}"))
            .unwrap();
        assert_eq!(ortho(&engine), start, "toggling back restores the projection");

        // A PARTIAL apply that omits the key must leave the projection untouched
        // (this is what protects the wireframe/color toggles from moving the camera).
        engine.apply_settings_json(r##"{"wireframe": true}"##).unwrap();
        assert_eq!(ortho(&engine), start, "an apply without `orthographic` leaves projection alone");
    }

    #[test]
    fn saved_orthographic_setting_restores_camera_on_boot() {
        // Boot ordering: a persisted settings blob is applied to a FRESH engine before
        // any document loads. The projection must follow it, and the ortho half_height
        // resolved against the cold boot camera must be sane (not garbage/NaN).
        let ortho =
            |e: &EngineState| matches!(e.camera.projection, crate::view::Projection::Orthographic { .. });
        let mut a = EngineState::new();
        a.apply_settings_json(r##"{"orthographic": true}"##).unwrap();
        assert!(ortho(&a), "saved orthographic=true restores orthographic on boot");
        if let crate::view::Projection::Orthographic { half_height } = a.camera.projection {
            assert!(
                half_height.is_finite() && half_height > 0.0,
                "boot ortho half_height must be sane: {half_height}"
            );
        }
        let mut b = EngineState::new();
        b.apply_settings_json(r##"{"orthographic": false}"##).unwrap();
        assert!(!ortho(&b), "saved orthographic=false restores perspective on boot");
    }

    /// Build a cube through the ENGINE-OWNED history (not the scene-only
    /// one-shot), so `update_feature_params` can edit it afterwards.
    fn engine_cube(engine: &mut EngineState, name: &str, size: f64) {
        engine.set_history_json(&cube_request(name, size)).unwrap();
        assert!(
            engine.scene.solid(name).is_some(),
            "the cube must build before a colour test"
        );
    }

    /// A cube's `inputParams` at a given size — the edit payload that forces a
    /// re-tessellation (a NEW display, with no colour of its own).
    fn cube_params(name: &str, size: f64) -> String {
        serde_json::json!({
            "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" }
        })
        .to_string()
    }

    /// THE regression this whole colour path exists for. The old transient
    /// override was measured dying here: set a colour, edit the feature, and the
    /// re-tessellated display came back colourless. Metadata is the authority
    /// now, so the fresh display is re-coloured from the store.
    ///
    /// The hex is deliberately UPPERCASE — that is the case a STEP import stamps
    /// (`#RRGGBB`), and a case-sensitive parse would silently drop every
    /// imported colour while a lowercase test stayed green.
    #[test]
    fn model_color_survives_a_feature_edit() {
        let mut engine = EngineState::new();
        engine_cube(&mut engine, "Tint", 4.0);

        engine.set_metadata_attribute("Tint", "color", "#00FF00");
        assert_eq!(
            engine.scene.solid("Tint").unwrap().color_override,
            Some([0.0, 1.0, 0.0]),
            "a metadata colour must reach the display immediately (no rerun)"
        );

        engine
            .update_feature_params("Tint", &cube_params("Tint", 8.0))
            .unwrap();
        assert_eq!(
            engine.scene.solid("Tint").unwrap().color_override,
            Some([0.0, 1.0, 0.0]),
            "the colour must survive the re-tessellation an edit forces"
        );
        assert_eq!(
            engine.metadata.attribute("Tint", "color"),
            Some("#00FF00"),
            "and the stored attribute must be untouched by the rerun"
        );
    }

    /// The colour is DURABLE: it rides the document through save and reload,
    /// which the old transient override never did (the serialized document
    /// contained no colour at all).
    #[test]
    fn model_color_round_trips_through_save_and_reload() {
        let mut engine = EngineState::new();
        engine_cube(&mut engine, "Saved", 4.0);
        engine.set_metadata_attribute("Saved", "color", "#123456");

        let document = engine.history_request_json();
        assert!(
            document.contains("123456"),
            "the saved document must carry the colour; got {document}"
        );

        let mut reopened = EngineState::new();
        reopened.set_history_json(&document).unwrap();
        assert_eq!(
            reopened.scene.solid("Saved").unwrap().color_override,
            crate::style::parse_css_hex("#123456"),
            "a reopened document must render its stored colours"
        );
    }

    /// The "Override model colors" contract: it changes what is RENDERED and
    /// nothing else. The store is never written, so the toggle is reversible and
    /// a document saved with it on still carries every colour.
    #[test]
    fn override_model_colors_is_render_only() {
        let mut engine = EngineState::new();
        engine_cube(&mut engine, "Body", 4.0);
        engine.set_metadata_attribute("Body", "color", "#ff8800");
        let stored = engine.metadata.attribute("Body", "color").map(str::to_string);
        assert!(engine.scene.solid("Body").unwrap().color_override.is_some());

        engine
            .apply_settings_json(r##"{"overrideModelColors": true}"##)
            .unwrap();
        assert_eq!(
            engine.scene.solid("Body").unwrap().color_override,
            None,
            "ticking the box must drop the render override back to faceColorMode"
        );
        assert_eq!(
            engine.metadata.attribute("Body", "color").map(str::to_string),
            stored,
            "...while leaving the METADATA exactly as it was"
        );
        assert!(
            engine.history_request_json().contains("ff8800"),
            "a document saved with the box ticked still carries its colours"
        );

        engine
            .apply_settings_json(r##"{"overrideModelColors": false}"##)
            .unwrap();
        assert_eq!(
            engine.scene.solid("Body").unwrap().color_override,
            crate::style::parse_css_hex("#ff8800"),
            "unticking restores the colour from the untouched store"
        );
    }

    /// Sketch sheets colour themselves (`SKETCH_SHEET_COLOR`) and have no
    /// metadata record, so the sync must SKIP them rather than blank them.
    #[test]
    fn the_sync_leaves_sketch_sheets_alone() {
        let mut engine = EngineState::new();
        engine_cube(&mut engine, "Solid", 4.0);

        let mut sheet = engine.scene.solid("Solid").unwrap().clone();
        sheet.name = "SketchSheet".to_string();
        sheet.is_sketch = true;
        sheet.color_override = Some([0.25, 0.5, 0.75]);
        engine.scene.insert_solid(sheet);

        engine.sync_colors_from_metadata();
        assert_eq!(
            engine.scene.solid("SketchSheet").unwrap().color_override,
            Some([0.25, 0.5, 0.75]),
            "a sketch sheet keeps its synthesized colour through a sync"
        );
    }

    /// The R10 no-op guarantee. This sync runs after EVERY history apply, so a
    /// sloppy comparison here would bump revisions on a stable scene and defeat
    /// the renderer's GPU-buffer reuse.
    #[test]
    fn the_sync_is_a_no_op_on_a_stable_scene() {
        let mut engine = EngineState::new();
        engine_cube(&mut engine, "Stable", 4.0);
        engine.set_metadata_attribute("Stable", "color", "#abcdef");
        let revision = engine.scene.solid("Stable").unwrap().revision;

        engine.dirty = false;
        assert!(
            !engine.sync_colors_from_metadata(),
            "a second sync over unchanged metadata must report no change"
        );
        assert_eq!(
            engine.scene.solid("Stable").unwrap().revision,
            revision,
            "...and must not bump the revision the GPU cache keys off"
        );
        assert!(!engine.dirty, "...nor mark the engine dirty");
    }

    /// Removing the attribute puts the body back on the global colour scheme.
    #[test]
    fn removing_the_color_attribute_clears_the_render_override() {
        let mut engine = EngineState::new();
        engine_cube(&mut engine, "Gone", 4.0);
        engine.set_metadata_attribute("Gone", "color", "#00ff00");
        assert!(engine.scene.solid("Gone").unwrap().color_override.is_some());

        assert!(engine.remove_metadata_attribute("Gone", "color"));
        assert_eq!(engine.scene.solid("Gone").unwrap().color_override, None);
    }

    #[test]
    fn undo_redo_reverts_and_reapplies_geometry() {
        let mut engine = EngineState::new();
        engine.set_history_json(&cube_request("U", 10.0)).unwrap();
        // A freshly loaded model has nothing to undo.
        assert!(!engine.can_undo());
        let base_x = engine.scene.solid("U").unwrap().bbox.max[0];

        // Edit sizeX → the solid grows.
        let mut params: serde_json::Value =
            serde_json::from_str(&engine.feature_params_json(0)).unwrap();
        params["sizeX"] = serde_json::json!(40.0);
        engine
            .update_feature_params("U", &params.to_string())
            .unwrap();
        let grown_x = engine.scene.solid("U").unwrap().bbox.max[0];
        assert!(grown_x > base_x, "edit grew the cube: {grown_x} > {base_x}");
        assert!(engine.can_undo());

        // Undo → geometry returns to the original size.
        engine.undo();
        let reverted_x = engine.scene.solid("U").unwrap().bbox.max[0];
        assert!(
            (reverted_x - base_x).abs() < 1e-6,
            "undo reverted geometry: {reverted_x} == {base_x}"
        );
        assert!(engine.can_redo());

        // Redo → grown again.
        engine.redo();
        let regrown_x = engine.scene.solid("U").unwrap().bbox.max[0];
        assert!(
            (regrown_x - grown_x).abs() < 1e-6,
            "redo re-applied geometry: {regrown_x} == {grown_x}"
        );

        // Add a second solid, then undo removes it (solid count returns to 1).
        engine
            .add_feature(&cube_feature_json("V", 6.0))
            .unwrap();
        assert_eq!(engine.scene.solids().len(), 2);
        engine.undo();
        assert_eq!(engine.scene.solids().len(), 1);
    }

    /// A single-feature `{type, inputParams, …}` cube descriptor (for `add_feature`).
    fn cube_feature_json(name: &str, size: f64) -> String {
        serde_json::json!({
            "type": "P.CU",
            "inputParams": {
                "id": name,
                "sizeX": size, "sizeY": size, "sizeZ": size,
                "transform": {
                    "position": [30.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()
    }