BREP_render 0.1.0

BREP Rust rendering engine: kernel-fed scene store + wgpu renderer (headless artifact, desktop window, and wasm canvas shells).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
    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 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]"));
    }

    #[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.
        let f = engine.selection_filter();
        assert!(f.solid && !f.face && !f.edge && !f.vertex, "solid-only: {f:?}");
        assert_eq!(
            engine.selection_filter_json(),
            r#"{"SOLID":true,"FACE":false,"EDGE":false,"VERTEX":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. spline's datum ref) maps to NO
    /// pickable kind, so it falls back to the all-enabled default rather than an
    /// empty, unusable filter.
    #[test]
    fn ref_select_datum_only_field_falls_back_to_all_enabled() {
        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![],
        );
        assert_eq!(
            engine.selection_filter(),
            SelectionFilter::default(),
            "construction-only field → all-enabled fallback"
        );
        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; PLANE/DATUM are dropped; zero-mapped-kinds → 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, face: false, edge: false, vertex: false }
        );
        assert_eq!(
            m(&["FACE", "EDGE"]),
            SelectionFilter { solid: false, face: true, edge: true, vertex: false }
        );
        // Construction kinds are dropped; the surviving pickable kind wins.
        assert_eq!(
            m(&["PLANE", "FACE"]),
            SelectionFilter { solid: false, face: true, edge: false, vertex: false }
        );
        // Zero mapped kinds → all-enabled fallback (never empty-and-unusable).
        assert_eq!(m(&["DATUM"]), SelectionFilter::default());
        assert_eq!(m(&["PLANE"]), SelectionFilter::default());
        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), None)
            .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), None)
            .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), None)
            .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");
    }

    #[test]
    fn settings_and_visibility_toggles() {
        let mut engine = EngineState::new();
        engine
            .run_history_json(&cube_request("V", 4.0), None)
            .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");
    }

    #[test]
    fn color_overrides_apply_from_history_feed() {
        let mut engine = EngineState::new();
        engine
            .run_history_json(&cube_request("Tint", 4.0), Some(r##"{"Tint": "#00ff00"}"##))
            .unwrap();
        assert_eq!(
            engine.scene.solid("Tint").unwrap().color_override,
            Some([0.0, 1.0, 0.0])
        );
    }

    #[test]
    fn live_color_override_sets_and_clears() {
        let mut engine = EngineState::new();
        engine
            .run_history_json(&cube_request("Live", 4.0), None)
            .unwrap();
        assert_eq!(engine.scene.solid("Live").unwrap().color_override, None);

        engine.dirty = false;
        assert!(engine.set_color_override("Live", Some("#123456")));
        assert!(engine.dirty);
        assert_eq!(
            engine.scene.solid("Live").unwrap().color_override,
            crate::style::parse_css_hex("#123456")
        );

        // None clears back to the base color.
        assert!(engine.set_color_override("Live", None));
        assert_eq!(engine.scene.solid("Live").unwrap().color_override, None);
        // An empty string also clears.
        engine.set_color_override("Live", Some("#abcdef"));
        assert!(engine.set_color_override("Live", Some("")));
        assert_eq!(engine.scene.solid("Live").unwrap().color_override, None);
        // An unknown solid is a no-op miss.
        assert!(!engine.set_color_override("Nope", Some("#ffffff")));
    }

    #[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()
    }