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
//! History → scene: run a whole feature history through the kernel's native
//! `execute_history` (same process, same thread — the solid registry is
//! thread-local) and populate a [`RenderScene`] from the resident handles via
//! the kernel's native display payload accessor. No JSON, no typed-array
//! boundary — the R1 promise.

use crate::scene::{solid_display_from_payload, RenderScene, SolidDisplay};
use brep_kernel::{display_payload_handle_native, execute_history, HistoryRequest};
use std::collections::HashMap;

/// Non-fatal diagnostics from a scene build (mirrors the previous app's run-history
/// reporting: a failed feature halts the remaining features but the solids
/// built so far still display — seeing what a failing history DID build is the
/// point of the artifact).
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct SceneBuildReport {
    /// Per-feature hard errors, as `"<feature id>: <message>"`.
    pub feature_errors: Vec<String>,
    /// Unresolved reference-selection names, as `"<feature id>: <name>"`.
    pub unresolved: Vec<String>,
    /// Solids whose display payload (tessellation) failed, as
    /// `"<solid name>: <message>"` — the solid is skipped, not fatal.
    pub display_errors: Vec<String>,
    /// Per-feature wall-clock execution time `(feature id, milliseconds)` in run
    /// order, carried through from the kernel's [`brep_kernel::HistoryResult`]
    /// timings — the history tree's "N ms" readout.
    pub feature_timings: Vec<(String, f64)>,
    /// Per-feature output solid names `(feature id, [solid names])` in run order —
    /// the history tree's read-only "Outputs" node.
    pub feature_outputs: Vec<(String, Vec<String>)>,
    /// Named plane FRAMES this run resolved `(frame name, frame)`, in run order —
    /// every DATUM registers three (`{id}:XY|XZ|YZ`), every PLANE one (`{id}`), and
    /// a SKETCH its own plane (`{id}`). Surfaced here so the engine can DISPLAY the
    /// construction datum/plane frames (filtered to the D/P producing features) as
    /// first-class scene citizens — the resolved frames ride
    /// [`brep_kernel::FeatureResult::frames`] straight through, no kernel change.
    pub frames: Vec<(String, brep_kernel::Frame)>,
    /// Solved sketch PROFILES this run produced `(sketch id, profile)`, in run
    /// order — every SKETCH feature publishes one under its own id. Surfaced here
    /// (exactly like [`Self::frames`]) so the engine can display each committed
    /// sketch as a SHEET SOLID (planar face + named boundary edges + corner
    /// vertices) via `sketch_profile_display_payload`, no kernel-contract change.
    pub profiles: Vec<(String, brep_kernel::SketchProfile)>,
    /// Named axis LINES this run produced `(axis name, line)`, in run order — a
    /// SKETCH publishes one per line geometry (construction included). Surfaced
    /// here (exactly like [`Self::frames`]/[`Self::profiles`]) so the engine can
    /// resolve a revolve/sweep `axis` reference to a world line at annotation-build
    /// time, fully headless. `#[serde(default)]` keeps older serialized reports
    /// (pre-`axes`) deserializing cleanly across the worker boundary.
    #[serde(default)]
    pub axes: Vec<(String, brep_kernel::Axis)>,
}

/// Execute a serialized `HistoryRequest` (the `execute_history_json` request
/// shape — a saved part file parses as one) and build the display scene from
/// the final resident solids.
pub fn scene_from_history_json(
    request_json: &str,
) -> Result<(RenderScene, SceneBuildReport), String> {
    let request: HistoryRequest = serde_json::from_str(request_json)
        .map_err(|error| format!("history request parse: {error}"))?;
    scene_from_history(&request)
}

/// Typed-request variant of [`scene_from_history_json`].
pub fn scene_from_history(
    request: &HistoryRequest,
) -> Result<(RenderScene, SceneBuildReport), String> {
    let mut scene = RenderScene::new();
    let report = update_scene_from_history(&mut scene, request, None)?;
    Ok((scene, report))
}

/// The fold of a history run into an ordered scene layout: each entry is the
/// solid's final name, its resident handle, and whether the feature that
/// produced it REPLAYED from the incremental cache (R10 — a reused solid is the
/// same resident geometry, so its display can be kept verbatim and its GPU
/// buffers reused).
struct SceneLayout {
    order: Vec<String>,
    handles: std::collections::HashMap<String, u32>,
    reused: std::collections::HashSet<String>,
    /// `name -> creating-feature id` of the FINAL resident solids (last writer
    /// wins; a `removed` name drops its entry) — the eager provenance the runner
    /// ships so the main thread never has to re-run the history to answer
    /// "what feature produced this object?". Matches the resident semantics of the
    /// old `resident_handles_and_creators`.
    creators: std::collections::HashMap<String, String>,
}

fn fold_history(result: &brep_kernel::HistoryResult, report: &mut SceneBuildReport) -> SceneLayout {
    // Removals first (a boolean result reuses a removed target's name), then
    // additions, insertion-ordered — mirrors SceneMap::apply.
    let mut order: Vec<String> = Vec::new();
    let mut handles: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
    let mut reused: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut creators: std::collections::HashMap<String, String> = std::collections::HashMap::new();
    for feature in &result.results {
        for removed in &feature.removed {
            if handles.remove(removed).is_some() {
                order.retain(|name| name != removed);
            }
            reused.remove(removed);
            creators.remove(removed);
        }
        for added in &feature.added {
            if handles.insert(added.name.clone(), added.handle).is_none() {
                order.push(added.name.clone());
            }
            creators.insert(added.name.clone(), feature.id.clone());
            // A solid displays as reused only when its whole producing feature
            // replayed unchanged; a re-run feature re-tessellates.
            if feature.reused {
                reused.insert(added.name.clone());
            } else {
                reused.remove(&added.name);
            }
        }
        if let Some(error) = &feature.error {
            report.feature_errors.push(format!("{}: {error}", feature.id));
        }
        for name in &feature.unresolved {
            report.unresolved.push(format!("{}: {name}", feature.id));
        }
        // The feature's output solid name(s) — the history tree's Outputs node.
        report.feature_outputs.push((
            feature.id.clone(),
            feature.added.iter().map(|a| a.name.clone()).collect(),
        ));
        // The named plane frames this feature resolved (DATUM three / PLANE one /
        // SKETCH its own). Carried straight through so the engine can display the
        // construction datum/plane frames (it filters to the D/P producers).
        for (name, frame) in &feature.frames {
            report.frames.push((name.clone(), *frame));
        }
        // The solved sketch profile (SKETCH features publish one under `{id}`) —
        // carried straight through so the engine can synthesize its sheet solid.
        for (name, profile) in &feature.profiles {
            report.profiles.push((name.clone(), profile.clone()));
        }
        // The named axis lines this feature published (a SKETCH emits one per line
        // geometry) — carried through so the engine can resolve a revolve `axis`
        // reference to a world line for the angle gizmo.
        for (name, axis) in &feature.axes {
            report.axes.push((name.clone(), *axis));
        }
    }
    // Per-feature timing rides the kernel result straight through.
    report.feature_timings = result.timings.clone();
    SceneLayout { order, handles, reused, creators }
}

/// A stateful, SCENE-FREE history run that emits a DELTA snapshot instead of
/// mutating a scene — the M1 seam of the off-thread history runner. It remembers,
/// in [`Self::last_sent`], the resident handle it last EMITTED per solid name, so
/// a rerun can tell the applier which displays are UNCHANGED (skip re-tessellating
/// + keep their GPU buffers) vs. which are new/rebound (freshly tessellated).
///
/// Being scene-free is the point: a later milestone runs this on a background
/// thread / worker with no access to the render scene, then ships the
/// [`RunOutput`] delta back to the main thread to apply. In M1 the run is
/// immediately applied on the same thread (see `EngineState::apply_run_output`),
/// so behavior is byte-identical to the pre-seam in-place reconcile.
pub struct SceneRunner {
    /// `name -> handle` of what was last EMITTED (the delta baseline). Handles are
    /// monotonic and never recycled (the resident registry's counter only
    /// increments, and `clear_history_cache` frees solids without resetting it),
    /// so "handle unchanged since last emit" is EXACTLY the old
    /// `reused && source_handle matches` reuse condition — a re-executed feature
    /// always registers a NEW handle, so a matching handle proves a cache replay.
    last_sent: HashMap<String, u32>,
    /// The display LOD factor the current baseline was tessellated at. When a run
    /// arrives at a DIFFERENT lod (the user moved the "LOD factor" slider) every
    /// resident mesh must be rebuilt at the new chord tolerance even though its
    /// handle is unchanged — so a lod change drops `last_sent` to defeat the
    /// handle-unchanged reuse fast path. Init `1.0` (the "Normal" default) so a
    /// first run at the default lod does NOT spuriously invalidate an empty
    /// baseline's peers.
    last_lod: f64,
}

/// The delta a [`SceneRunner::run`] produces: the displayed KERNEL solids IN
/// ORDER plus the run's [`SceneBuildReport`]. The applier walks `snapshot` in
/// order, reusing or replacing each entry (see the field docs).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RunOutput {
    /// The displayed KERNEL solids IN ORDER. `display: Some` = freshly tessellated
    /// (new, or the handle changed since last emit); `None` = UNCHANGED — the
    /// applier keeps its existing [`SolidDisplay`] for this name, whose
    /// `source_handle` equals `handle`.
    pub snapshot: Vec<(String /* name */, u32 /* handle */, Option<SolidDisplay>)>,
    pub report: SceneBuildReport,
    /// Eager PROVENANCE: `name -> creating-feature id` for the run's FINAL resident
    /// solids (same last-writer-wins fold as the display snapshot). Shipped WITH the
    /// run so the main thread can answer object provenance (`creating_feature`, the
    /// Info tab's `creatingFeature`) without a cold `execute_history` — critical once
    /// the run lives on a background thread and the main-side registry is cold.
    pub provenance: Vec<(String, String)>,
}

impl SceneRunner {
    pub fn new() -> Self {
        Self { last_sent: HashMap::new(), last_lod: 1.0 }
    }

    /// Reset the delta baseline (call on a wholesale document switch so the next
    /// run is a full rebuild — no stale reuse across unrelated models).
    pub fn reset(&mut self) {
        self.last_sent.clear();
    }

    /// Execute `request` and fold it into an ordered delta snapshot (does NOT
    /// touch any scene). For each displayed kernel solid in order: if the handle
    /// is unchanged since the last emit, emit `(name, handle, None)` (the applier
    /// keeps its existing display); otherwise (re-)tessellate the resident handle
    /// and emit `(name, handle, Some(display))`. A display-payload error is
    /// recorded in `report.display_errors` and the entry is SKIPPED — and NOT
    /// recorded in the new baseline, so a later successful run re-tessellates it.
    ///
    /// `color_overrides` is an optional `name → sRGB [0..1;3]` map (the metadata
    /// color layer); applied to freshly built solids only (reused ones keep it).
    pub fn run(
        &mut self,
        request: &HistoryRequest,
        color_overrides: Option<&HashMap<String, [f32; 3]>>,
    ) -> RunOutput {
        let result = execute_history(request);
        let mut report = SceneBuildReport::default();
        let layout = fold_history(&result, &mut report);

        // Display LOD: a finite, positive factor (garbage from a hand-edited saved
        // file → the "Normal" 1.0, since chord = extent·1.5e-3·lod and a 0/NaN lod
        // would zero the tolerance → runaway refinement). A change since the last
        // run means every resident mesh must re-tessellate at the new chord even
        // though its handle is unchanged, so drop the reuse baseline.
        let lod = if request.display_lod.is_finite() && request.display_lod > 0.0 {
            request.display_lod
        } else {
            1.0
        };
        if lod != self.last_lod {
            self.last_sent.clear();
            self.last_lod = lod;
        }

        let mut snapshot: Vec<(String, u32, Option<SolidDisplay>)> =
            Vec::with_capacity(layout.order.len());
        let mut next_sent: HashMap<String, u32> = HashMap::with_capacity(layout.order.len());

        for name in &layout.order {
            let handle = layout.handles[name];
            if self.last_sent.get(name) == Some(&handle) {
                // Handle unchanged since last emit ⇒ same resident geometry ⇒ the
                // applier keeps its existing display. This is EXACTLY the old
                // `reused && source_handle == handle` fast path (monotonic handles):
                // the canary below verifies the implication holds.
                debug_assert!(
                    layout.reused.contains(name),
                    "handle unchanged must imply reused (monotonic handles): {name}"
                );
                snapshot.push((name.clone(), handle, None));
                next_sent.insert(name.clone(), handle);
                continue;
            }
            match display_payload_handle_native(handle, lod) {
                Ok(payload) => {
                    let mut solid = solid_display_from_payload(name, payload);
                    solid.source_handle = handle;
                    if let Some(overrides) = color_overrides {
                        solid.color_override = overrides.get(name).copied();
                    }
                    snapshot.push((name.clone(), handle, Some(solid)));
                    next_sent.insert(name.clone(), handle);
                }
                // A tessellation failure skips the solid (non-fatal) and does NOT
                // poison the baseline — dropping it lets a later successful run
                // re-tessellate from scratch.
                Err(error) => report.display_errors.push(format!("{name}: {error}")),
            }
        }

        self.last_sent = next_sent;
        // Eager provenance for the run's final resident solids (the applier stores
        // this map main-side so per-frame provenance queries never re-run history).
        let provenance: Vec<(String, String)> = layout
            .creators
            .iter()
            .map(|(name, id)| (name.clone(), id.clone()))
            .collect();
        RunOutput { snapshot, report, provenance }
    }

    /// The resident handle last EMITTED for `name` (the delta baseline), or `None`
    /// if the runner has not emitted a solid of that name. The measurement-query
    /// path resolves an object's owning-solid handle through this so the query runs
    /// against the SAME resident geometry the last run displayed (on the runner's
    /// own thread, whose registry is warm from that run).
    pub fn handle_of(&self, name: &str) -> Option<u32> {
        self.last_sent.get(name).copied()
    }
}

impl Default for SceneRunner {
    fn default() -> Self {
        Self::new()
    }
}

/// Execute the history and reconcile `scene` in place (R10 incremental update):
/// reused solids already present keep their [`SolidDisplay`] verbatim (stable
/// `revision` ⇒ the renderer reuses their GPU buffers); everything else is
/// (re-)tessellated from the resident handle; departed solids are dropped.
///
/// `color_overrides` is an optional `name → sRGB [0..1;3]` map (the metadata
/// color layer); applied to freshly built solids so the renderer picks it up.
///
/// Implemented on the M1 seam: a throwaway [`SceneRunner`] primed from the
/// CURRENT scene (`name → source_handle` of what is displayed) reproduces the
/// pre-seam reuse in a single synchronous call, and its [`RunOutput`] delta is
/// applied back to `scene` by MOVING existing displays out (via
/// [`RenderScene::drain`]) so a reused solid's mesh is never cloned.
pub fn update_scene_from_history(
    scene: &mut RenderScene,
    request: &HistoryRequest,
    color_overrides: Option<&HashMap<String, [f32; 3]>>,
) -> Result<SceneBuildReport, String> {
    let mut runner = SceneRunner::new();
    runner.last_sent = scene
        .solids()
        .iter()
        .map(|solid| (solid.name.clone(), solid.source_handle))
        .collect();
    let output = runner.run(request, color_overrides);

    // Move the current displays out, then reinsert in snapshot ORDER: a fresh
    // entry replaces, an UNCHANGED entry reuses the moved-out display (whose
    // `source_handle` equals the run's handle — guaranteed by the reuse
    // invariant). Leftovers (departed names) are dropped.
    let mut kept: HashMap<String, SolidDisplay> = scene
        .drain()
        .into_iter()
        .map(|solid| (solid.name.clone(), solid))
        .collect();
    for (name, _handle, maybe) in output.snapshot {
        match maybe {
            Some(display) => scene.insert_solid(display),
            None => scene.insert_solid(
                kept.remove(&name).expect("keep target present"),
            ),
        }
    }
    Ok(output.report)
}

/// Execute `request` and return the FINAL resident solids as `(name, handle)` in
/// display order — the export lane (STEP/STL) needs the current solids' resident
/// handles, which the scene build does not itself retain. Run right after a scene
/// build (warm incremental cache) this replays the cached features, so the
/// handles it returns are the very ones the displayed scene was built from; run
/// cold it re-executes and registers fresh (still-valid) handles. Either way the
/// handles are live in the thread-local registry when this returns, ready to
/// hand to `brep_kernel::export_step_handles`.
pub fn resident_solid_handles(request: &HistoryRequest) -> Vec<(String, u32)> {
    let result = execute_history(request);
    let mut report = SceneBuildReport::default();
    let layout = fold_history(&result, &mut report);
    layout
        .order
        .iter()
        .map(|name| (name.clone(), layout.handles[name]))
        .collect()
}

#[cfg(test)]
mod tests {
    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 DOTTED feature id (the new `{shortName}{N}` scheme yields ids like `P.CU1`)
    // must be safe as a downstream reference: the `.` is inert everywhere (scene-map
    // resolution is exact HashMap lookup — only `:` and `|` are name delimiters).
    // Prove it at RUNTIME: a boolean SUBTRACT that targets a dotted-id solid resolves
    // (nothing lands in `report.unresolved`) and builds a scene.
    #[test]
    fn dotted_feature_id_resolves_as_a_boolean_reference() {
        let request = serde_json::json!({
            "expressions": "",
            "configurator": {},
            "features": [
                {
                    "type": "P.CU",
                    "inputParams": {
                        "id": "P.CU1",
                        "sizeX": 10.0, "sizeY": 10.0, "sizeZ": 10.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.CU",
                    "inputParams": {
                        "id": "P.CU2",
                        "sizeX": 10.0, "sizeY": 10.0, "sizeZ": 10.0,
                        "transform": { "position": [5.0, 0.0, 0.0], "rotationEuler": [0.0, 0.0, 0.0], "scale": [1.0, 1.0, 1.0] },
                        // SUBTRACT referencing the DOTTED id of the first cube.
                        "boolean": { "targets": ["P.CU1"], "operation": "SUBTRACT" }
                    },
                    "persistentData": {}
                }
            ]
        })
        .to_string();
        let (scene, report) = scene_from_history_json(&request).unwrap();
        assert!(report.feature_errors.is_empty(), "{:?}", report.feature_errors);
        // The dotted reference `P.CU1` resolved — if `.` broke name matching it would
        // appear here instead.
        assert!(report.unresolved.is_empty(), "dotted ref unresolved: {:?}", report.unresolved);
        // The subtract folded the two cubes into one resident solid.
        assert_eq!(scene.solids().len(), 1);
    }

    #[test]
    fn cube_history_populates_scene() {
        let (scene, report) = scene_from_history_json(&cube_request("P.CU1", 10.0)).unwrap();
        assert!(report.feature_errors.is_empty(), "{:?}", report.feature_errors);
        assert!(report.display_errors.is_empty(), "{:?}", report.display_errors);
        assert_eq!(scene.solids().len(), 1);
        let solid = scene.solid("P.CU1").expect("solid keyed by kernel name");
        assert_eq!(solid.faces.len(), 6);
        // Cube tessellation: 2 triangles per face.
        assert_eq!(solid.mesh.indices.len(), 6 * 2 * 3);
        for face in &solid.faces {
            assert_eq!(face.tri_count, 2, "face {} range", face.name);
            assert!(!face.name.is_empty());
        }
        // 12 boundary edges, each a straight 2-point polyline, all named.
        assert_eq!(solid.edges.len(), 12);
        for edge in &solid.edges {
            assert!(edge.polyline.len() >= 2);
            assert!(!edge.name.is_empty());
        }
        assert_eq!(solid.vertices.len(), 8);
        let bbox = scene.bbox();
        assert!((bbox.size()[0] - 10.0).abs() < 1e-6);
    }

    fn sphere_request(name: &str, radius: f64, lod: f64) -> brep_kernel::HistoryRequest {
        let mut request: brep_kernel::HistoryRequest = serde_json::from_value(serde_json::json!({
            "expressions": "",
            "configurator": {},
            "features": [{
                "type": "P.S",
                "inputParams": {
                    "id": name,
                    "radius": radius,
                    "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": {}
            }]
        }))
        .unwrap();
        request.display_lod = lod;
        request
    }

    // A LOD-factor change must re-tessellate every resident mesh at the new chord
    // tolerance EVEN THOUGH the solid's handle is unchanged (same geometry, replayed
    // from the incremental cache) — otherwise the "LOD factor" slider does nothing.
    #[test]
    fn lod_change_retessellates_reused_solid_coarser() {
        let mut runner = SceneRunner::new();

        // Fine mesh at lod 0.5.
        let fine = runner.run(&sphere_request("LodBall", 10.0, 0.5), None);
        let (_, fine_handle, fine_display) = &fine.snapshot[0];
        let fine_tris = fine_display.as_ref().expect("first run tessellates").mesh.indices.len();

        // SAME sphere, coarser lod 4.0: the incremental cache replays the sphere so
        // the handle is unchanged (proven below) — the ONLY reason to re-emit is the
        // lod change, and the coarser chord must drop the triangle count.
        let coarse = runner.run(&sphere_request("LodBall", 10.0, 4.0), None);
        let (_, coarse_handle, coarse_display) = &coarse.snapshot[0];
        assert_eq!(
            coarse_handle, fine_handle,
            "same sphere must replay to the same handle (reuse path) — else the test proves nothing"
        );
        let coarse_tris = coarse_display
            .as_ref()
            .expect("a lod change re-emits Some(display) despite the unchanged handle")
            .mesh
            .indices
            .len();
        assert!(
            coarse_tris < fine_tris,
            "coarser lod must shrink the mesh: fine(lod 0.5)={fine_tris} coarse(lod 4.0)={coarse_tris}"
        );

        // Re-running at the SAME lod reuses the baseline (None) — no spurious full
        // re-tessellation on every run once the lod is stable.
        let again = runner.run(&sphere_request("LodBall", 10.0, 4.0), None);
        assert!(
            again.snapshot[0].2.is_none(),
            "an unchanged lod must reuse the display baseline (None), not re-tessellate"
        );
    }

    #[test]
    fn reused_history_keeps_stable_revision() {
        let request: brep_kernel::HistoryRequest =
            serde_json::from_str(&cube_request("Keep", 8.0)).unwrap();
        let mut scene = RenderScene::new();
        update_scene_from_history(&mut scene, &request, None).unwrap();
        let first_rev = scene.solid("Keep").unwrap().revision;

        // A second identical run replays from the incremental cache; the reused
        // solid must keep its revision (so the renderer reuses its GPU buffers).
        update_scene_from_history(&mut scene, &request, None).unwrap();
        assert_eq!(scene.solid("Keep").unwrap().revision, first_rev);
    }

    #[test]
    fn color_override_applies_to_fresh_solids() {
        let request: brep_kernel::HistoryRequest =
            serde_json::from_str(&cube_request("Tinted", 5.0)).unwrap();
        let mut overrides = std::collections::HashMap::new();
        overrides.insert("Tinted".to_string(), [1.0, 0.0, 0.0]);
        let mut scene = RenderScene::new();
        update_scene_from_history(&mut scene, &request, Some(&overrides)).unwrap();
        assert_eq!(scene.solid("Tinted").unwrap().color_override, Some([1.0, 0.0, 0.0]));
    }

    #[test]
    fn scene_insert_replace_and_remove() {
        let (mut scene, _) = scene_from_history_json(&cube_request("A", 4.0)).unwrap();
        let (other, _) = scene_from_history_json(&cube_request("B", 2.0)).unwrap();
        for solid in other.solids() {
            scene.insert_solid(solid.clone());
        }
        assert_eq!(scene.solids().len(), 2);
        assert!(scene.remove_solid("A"));
        assert!(!scene.remove_solid("A"));
        assert_eq!(scene.solids().len(), 1);
        assert!(scene.solid("B").is_some());
    }

    #[test]
    fn datum_history_surfaces_three_named_frames() {
        // A single DATUM feature resolves three base-plane frames; the build report
        // surfaces them so the engine can display them as datum planes.
        let request = serde_json::json!({
            "expressions": "",
            "configurator": {},
            "features": [{
                "type": "D",
                "inputParams": { "id": "Datum" },
                "persistentData": {}
            }]
        })
        .to_string();
        let (_scene, report) = scene_from_history_json(&request).unwrap();
        let names: Vec<&str> = report.frames.iter().map(|(n, _)| n.as_str()).collect();
        assert!(names.contains(&"Datum:XY"), "{names:?}");
        assert!(names.contains(&"Datum:XZ"), "{names:?}");
        assert!(names.contains(&"Datum:YZ"), "{names:?}");
    }

    /// A `RunOutput` — the whole delta (tessellated `SolidDisplay` snapshot + the
    /// report's frames/profiles/provenance) — survives a serde JSON round trip.
    /// This is the wasm WorkerRunner (M3) message payload: the worker serializes
    /// the run result and the main thread reconstructs it byte-for-byte.
    #[test]
    fn run_output_round_trips_through_serde() {
        // A cube (→ a tessellated SolidDisplay) + a DATUM (→ frames) + a committed
        // rectangle SKETCH (→ a profile) exercise every side-channel of the report.
        let request: HistoryRequest = serde_json::from_str(
            r#"{
                "expressions": "", "configurator": {},
                "features": [
                    { "type": "P.CU", "inputParams": { "id": "Box", "sizeX": 10, "sizeY": 10, "sizeZ": 10,
                        "transform": { "position": [0,0,0], "rotationEuler": [0,0,0], "scale": [1,1,1] },
                        "boolean": { "targets": [], "operation": "NONE" } }, "persistentData": {} },
                    { "type": "D", "inputParams": { "id": "Datum" }, "persistentData": {} },
                    { "type": "S", "inputParams": { "id": "Sk" }, "persistentData": {
                        "basis": { "origin": [0,0,0], "x": [1,0,0], "y": [0,1,0], "z": [0,0,1] },
                        "sketch": { "points": [
                            {"id":0,"x":0,"y":0},{"id":1,"x":10,"y":0},{"id":2,"x":10,"y":6},{"id":3,"x":0,"y":6}],
                          "geometries": [
                            {"id":10,"type":"line","points":[0,1]},{"id":11,"type":"line","points":[1,2]},
                            {"id":12,"type":"line","points":[2,3]},{"id":13,"type":"line","points":[3,0]}],
                          "constraints": [] } } }
                ]
            }"#,
        )
        .unwrap();

        let output = SceneRunner::new().run(&request, None);
        // Sanity: the run produced the box display + the datum frames + the profile.
        assert_eq!(output.snapshot.len(), 1, "one solid (the box)");
        assert!(output.snapshot[0].2.as_ref().unwrap().mesh.positions.len() > 0);
        assert!(output.report.frames.iter().any(|(n, _)| n == "Datum:XY"));
        assert!(output.report.profiles.iter().any(|(n, _)| n == "Sk"));
        assert!(output.provenance.iter().any(|(n, id)| n == "Box" && id == "Box"));

        let json = serde_json::to_string(&output).expect("RunOutput serializes");
        let back: RunOutput = serde_json::from_str(&json).expect("RunOutput deserializes");

        assert_eq!(back.snapshot.len(), output.snapshot.len());
        assert_eq!(back.snapshot[0].0, "Box");
        assert_eq!(
            back.snapshot[0].2.as_ref().unwrap().mesh.positions.len(),
            output.snapshot[0].2.as_ref().unwrap().mesh.positions.len()
        );
        assert!(back.report.frames.iter().any(|(n, _)| n == "Datum:XY"));
        let (name, profile) = back.report.profiles.iter().find(|(n, _)| n == "Sk").unwrap();
        assert_eq!(name, "Sk");
        assert_eq!(profile.regions.len(), 1, "the rectangle profile survived");
        assert_eq!(back.provenance, output.provenance);
    }
}