Skip to main content

brep_render/
pipeline.rs

1//! History → scene: run a whole feature history through the kernel's native
2//! `execute_history` (same process, same thread — the solid registry is
3//! thread-local) and populate a [`RenderScene`] from the resident handles via
4//! the kernel's native display payload accessor. No JSON, no typed-array
5//! boundary — the R1 promise.
6
7use crate::scene::{solid_display_from_payload, RenderScene, SolidDisplay};
8use brep_kernel::{display_payload_handle_native, execute_history, HistoryRequest};
9use std::collections::HashMap;
10
11/// Non-fatal diagnostics from a scene build (mirrors the previous app's run-history
12/// reporting: a failed feature halts the remaining features but the solids
13/// built so far still display — seeing what a failing history DID build is the
14/// point of the artifact).
15#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
16pub struct SceneBuildReport {
17    /// Successful plugin callback state, committed with the accepted scene only.
18    #[serde(default)]
19    pub plugin_persistent_data: Vec<(String, serde_json::Value)>,
20    /// Per-feature hard errors, as `"<feature id>: <message>"`.
21    pub feature_errors: Vec<String>,
22    /// Unresolved reference-selection names, as `"<feature id>: <name>"`.
23    pub unresolved: Vec<String>,
24    /// What the kernel REPAIRED while building a feature, as
25    /// `"<feature id>: <what>"` — today, a self-crossing the soundness
26    /// acceptance split and re-trimmed rather than refused. Not an error: the
27    /// feature SUCCEEDED, with a result the kernel changed on its way out, and
28    /// a change the user cannot see is the one thing a repair must never be.
29    /// `#[serde(default)]` keeps reports serialized before this field crossing
30    /// the worker boundary.
31    #[serde(default)]
32    pub feature_notes: Vec<String>,
33    /// What a SUCCESSFUL feature did with what it was asked, when not everything
34    /// (`brep_kernel::FeatureResult::fulfilment`): `(feature id, fulfilment)` in
35    /// run order, only for the features that report one. A partial is a
36    /// different answer from the one asked for, so the history tree shows it on
37    /// the feature's row and the run report carries it typed. `#[serde(default)]`
38    /// for reports serialized before this field.
39    #[serde(default)]
40    pub feature_fulfilment: Vec<(String, brep_kernel::Fulfilment)>,
41    /// The kernel's typed refusal for each feature that failed with one
42    /// (`brep_kernel::FeatureResult::refusal`): `(feature id, refusal, refused
43    /// step)` in run order — the class, stage and text `feature_errors` flattens
44    /// to a line, and the motion step that refused when the feature records one
45    /// (`FeatureResult::refused_step`). Features whose refusal is text only do
46    /// not appear. Additive: `#[serde(default)]` for reports serialized before
47    /// it, and omitted when empty.
48    #[serde(default, skip_serializing_if = "Vec::is_empty")]
49    pub feature_refusals: Vec<(String, brep_kernel::KernelRefusal, Option<String>)>,
50    /// The MEASURED approximations each SUCCESSFUL feature carries
51    /// (`brep_kernel::FeatureResult::approximations`): `(feature id,
52    /// approximations)` in run order, only for the features that carry any.
53    /// The result stands and this says by how much, and why, it is not exact —
54    /// the third kind of report beside a refusal (the result does not stand)
55    /// and a fulfilment (what was done of what was asked); today the STEP
56    /// import's shell-closure gate (`import.shell_closure`) is the producer.
57    /// Additive: `#[serde(default)]` for reports serialized before it, and
58    /// omitted when empty.
59    #[serde(default, skip_serializing_if = "Vec::is_empty")]
60    pub feature_approximations: Vec<(String, Vec<brep_kernel::Approximation>)>,
61    /// Solids whose display payload (tessellation) failed, as
62    /// `"<solid name>: <message>"` — the solid is skipped, not fatal.
63    pub display_errors: Vec<String>,
64    /// Per-feature wall-clock execution time `(feature id, milliseconds)` in run
65    /// order, carried through from the kernel's [`brep_kernel::HistoryResult`]
66    /// timings — the history tree's "N ms" readout.
67    pub feature_timings: Vec<(String, f64)>,
68    /// Per-feature output solid names `(feature id, [solid names])` in run order —
69    /// the history tree's read-only "Outputs" node.
70    pub feature_outputs: Vec<(String, Vec<String>)>,
71    /// Named plane FRAMES this run resolved `(frame name, frame)`, in run order —
72    /// every DATUM registers three (`{id}:XY|XZ|YZ`), every PLANE one (`{id}`), and
73    /// a SKETCH its own plane (`{id}`). Surfaced here so the engine can DISPLAY the
74    /// construction datum/plane frames (filtered to the D/P producing features) as
75    /// first-class scene citizens — the resolved frames ride
76    /// [`brep_kernel::FeatureResult::frames`] straight through, no kernel change.
77    pub frames: Vec<(String, brep_kernel::Frame)>,
78    /// Solved sketch PROFILES this run produced `(sketch id, profile)`, in run
79    /// order — every SKETCH feature publishes one under its own id. Surfaced here
80    /// (exactly like [`Self::frames`]) so the engine can display each committed
81    /// sketch as a SHEET SOLID (planar face + named boundary edges + corner
82    /// vertices) via `sketch_display_payload`, no kernel-contract change.
83    pub profiles: Vec<(String, brep_kernel::SketchProfile)>,
84    /// Named axis LINES this run produced `(axis name, line)`, in run order — a
85    /// SKETCH publishes one per line geometry (construction included). Surfaced
86    /// here (exactly like [`Self::frames`]/[`Self::profiles`]) so the engine can
87    /// resolve a revolve/sweep `axis` reference to a world line at annotation-build
88    /// time, fully headless. `#[serde(default)]` keeps older serialized reports
89    /// (pre-`axes`) deserializing cleanly across the worker boundary.
90    #[serde(default)]
91    pub axes: Vec<(String, brep_kernel::Axis)>,
92    /// Named PATH chains this run produced `(path name, curves)`, in run order — a
93    /// SKETCH publishes its whole ordered chain under `{id}` and EACH model segment
94    /// under `{id}:G{gid}`. Surfaced here (exactly like [`Self::profiles`]) so the
95    /// engine can draw a committed sketch's OPEN geometry: an open chain closes no
96    /// region, so it publishes no profile, and before this the sheet builder had
97    /// nothing to draw it from — an open sketch was invisible in 3D. `#[serde(default)]`
98    /// keeps older serialized reports (pre-`paths`) deserializing cleanly across the
99    /// worker boundary.
100    #[serde(default)]
101    pub paths: Vec<(String, Vec<brep_kernel::NurbsCurve>)>,
102    /// Named world POINTS this run produced `(point name, point)`, in run order —
103    /// a SKETCH publishes every solved point under `{id}:P{pid}` with its
104    /// construction flag. Surfaced here (exactly like [`Self::paths`]) so the
105    /// engine can draw a committed sketch's STANDALONE points: a points-only
106    /// sketch (a hole-placement sketch) has no segment and no profile, so before
107    /// this the sheet builder had nothing to draw it from — it was invisible and
108    /// unpickable in 3D. `#[serde(default)]` keeps older serialized reports
109    /// (pre-`points`) deserializing cleanly across the worker boundary.
110    #[serde(default)]
111    pub points: Vec<(String, brep_kernel::ScenePoint)>,
112    /// The wire-harness tail's routing report (endpoints, segments, one route
113    /// per connection, bundles). Read RUNNER-SIDE like everything else here —
114    /// the tail ran on the runner's thread — and shipped so the harness panel
115    /// reads it off the applied run. `#[serde(default)]` keeps older serialized
116    /// reports deserializing across the worker boundary.
117    #[serde(default)]
118    pub wire_harness: Option<brep_kernel::WireHarnessReport>,
119    /// The PMI tail's resolution of every view's annotations (`None` when the
120    /// document carries no `pmi` block).
121    #[serde(default)]
122    pub pmi: Option<brep_kernel::PmiReport>,
123    /// The PORTS tail's resolution of the declared-ports block (`None` when the
124    /// document declares none). Shipped for the same reason the two above are:
125    /// the tail is not a feature, so its refused names and unresolved
126    /// references reach no feature row — the Qualify panel reads them here.
127    #[serde(default)]
128    pub ports: Option<brep_kernel::PortsReport>,
129}
130
131/// Execute a serialized `HistoryRequest` (the `execute_history_json` request
132/// shape — a saved part file parses as one) and build the display scene from
133/// the final resident solids.
134pub fn scene_from_history_json(
135    request_json: &str,
136) -> Result<(RenderScene, SceneBuildReport), String> {
137    let request: HistoryRequest = serde_json::from_str(request_json)
138        .map_err(|error| format!("history request parse: {error}"))?;
139    scene_from_history(&request)
140}
141
142/// Typed-request variant of [`scene_from_history_json`].
143pub fn scene_from_history(
144    request: &HistoryRequest,
145) -> Result<(RenderScene, SceneBuildReport), String> {
146    let mut scene = RenderScene::new();
147    let report = update_scene_from_history(&mut scene, request)?;
148    Ok((scene, report))
149}
150
151/// Explicitly provision trusted packages for a one-shot headless scene build.
152/// The document itself provides only exact pins; loading it never installs code.
153pub fn scene_from_history_with_plugins(
154    request: &HistoryRequest,
155    runtime: &brep_plugins::Runtime,
156) -> Result<(RenderScene, SceneBuildReport), String> {
157    runtime.with_provider(|| scene_from_history(request))
158}
159
160/// The fold of a history run into an ordered scene layout: each entry is the
161/// solid's final name, its resident handle, and whether the feature that
162/// produced it REPLAYED from the incremental cache (R10 — a reused solid is the
163/// same resident geometry, so its display can be kept verbatim and its GPU
164/// buffers reused).
165struct SceneLayout {
166    order: Vec<String>,
167    handles: std::collections::HashMap<String, u32>,
168    reused: std::collections::HashSet<String>,
169    /// `name -> creating-feature id` of the FINAL resident SOLIDS (last writer
170    /// wins; a `removed` name drops its entry) — the eager provenance the runner
171    /// ships so the main thread never has to re-run the history to answer
172    /// "what feature produced this SOLID?". Matches the resident semantics of the
173    /// old `resident_handles_and_creators`.
174    creators: std::collections::HashMap<String, String>,
175    /// `face/edge NAME -> ORIGINATING feature id` — the FIRST feature (timeline
176    /// order) to emit each face/edge name, i.e. the entity's TRUE origin (the
177    /// feature that gave it its name). Unlike `creators` this is FIRST-writer-wins
178    /// and is NEVER pruned on `removed`: a boolean removes its target solid and
179    /// re-adds the same solid name carrying mostly the same face names, so pruning
180    /// then re-adding would reset those origins to the boolean feature — the same
181    /// last-writer bug one level down. Accepted edge case: a fully-deleted solid
182    /// whose name later recurs on unrelated geometry keeps its old origin — but
183    /// under this app's DETERMINISTIC naming a recurring name is the same
184    /// conceptual entity, and the whole map is rebuilt every run, so it can never
185    /// point at a feature that was deleted from the history.
186    entity_origin: std::collections::HashMap<String, String>,
187}
188
189/// Whether `request` is an ASSEMBLY document: any ACOMP-typed feature, or a
190/// present `assembly` constraint block. Mirrors
191/// `EngineState::history_has_assembly` — a componentless document ships no
192/// [`AssemblySync`] and the main side clears its projection, exactly as the
193/// main-side sync used to.
194fn request_has_assembly(request: &HistoryRequest) -> bool {
195    request.assembly.is_some()
196        || request.features.iter().any(|feature| {
197            feature.feature_type.eq_ignore_ascii_case("ACOMP")
198                || feature.feature_type.eq_ignore_ascii_case("ASSEMBLY COMPONENT")
199        })
200}
201
202fn fold_history(result: &brep_kernel::HistoryResult, report: &mut SceneBuildReport) -> SceneLayout {
203    // Removals first (a boolean result reuses a removed target's name), then
204    // additions, insertion-ordered — mirrors SceneMap::apply.
205    let mut order: Vec<String> = Vec::new();
206    let mut handles: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
207    let mut reused: std::collections::HashSet<String> = std::collections::HashSet::new();
208    let mut creators: std::collections::HashMap<String, String> = std::collections::HashMap::new();
209    let mut entity_origin: std::collections::HashMap<String, String> =
210        std::collections::HashMap::new();
211    for (index, feature) in result.results.iter().enumerate() {
212        if let Some(data) = &feature.persistent_data {
213            if feature.error.is_none() { report.plugin_persistent_data.push((feature.id.clone(), data.clone())); }
214        }
215        // A feature whose `inputParams` carry no `id` still has to be nameable in
216        // the report, or its errors read as `": <message>"` and point at nothing.
217        // Its POSITION is the only handle it has, and the one `feature_delete`
218        // takes to remove it again.
219        let label = if feature.id.is_empty() { format!("feature[{index}]") } else { feature.id.clone() };
220        for removed in &feature.removed {
221            if handles.remove(removed).is_some() {
222                order.retain(|name| name != removed);
223            }
224            reused.remove(removed);
225            creators.remove(removed);
226            // NOTE: `entity_origin` is deliberately NOT pruned here — see its doc on
227            // `SceneLayout`. First-writer-with-no-pruning is the whole point.
228        }
229        for added in &feature.added {
230            if handles.insert(added.name.clone(), added.handle).is_none() {
231                order.push(added.name.clone());
232            }
233            creators.insert(added.name.clone(), feature.id.clone());
234            // The FIRST feature to emit a given face/edge name IS its origin (this
235            // loop is in timeline order). `entry(..).or_insert_with` keeps that
236            // first writer — using `insert` here would be last-writer and silently
237            // reproduce the exact bug this map exists to fix.
238            for (_, name) in &added.face_names {
239                entity_origin
240                    .entry(name.clone())
241                    .or_insert_with(|| feature.id.clone());
242            }
243            for (_, name) in &added.edge_names {
244                entity_origin
245                    .entry(name.clone())
246                    .or_insert_with(|| feature.id.clone());
247            }
248            // A solid displays as reused only when its whole producing feature
249            // replayed unchanged; a re-run feature re-tessellates.
250            if feature.reused {
251                reused.insert(added.name.clone());
252            } else {
253                reused.remove(&added.name);
254            }
255        }
256        if let Some(error) = &feature.error {
257            report.feature_errors.push(format!("{label}: {error}"));
258        }
259        for name in &feature.unresolved {
260            report.unresolved.push(format!("{label}: {name}"));
261        }
262        for note in &feature.notes {
263            report.feature_notes.push(format!("{label}: {note}"));
264        }
265        if let Some(fulfilment) = &feature.fulfilment {
266            report
267                .feature_fulfilment
268                .push((feature.id.clone(), fulfilment.clone()));
269        }
270        if let Some(refusal) = &feature.refusal {
271            report
272                .feature_refusals
273                .push((feature.id.clone(), refusal.clone(), feature.refused_step.clone()));
274        }
275        if !feature.approximations.is_empty() {
276            report
277                .feature_approximations
278                .push((feature.id.clone(), feature.approximations.clone()));
279        }
280        // The feature's output solid name(s) — the history tree's Outputs node.
281        report.feature_outputs.push((
282            feature.id.clone(),
283            feature.added.iter().map(|a| a.name.clone()).collect(),
284        ));
285        // The named plane frames this feature resolved (DATUM three / PLANE one /
286        // SKETCH its own). Carried straight through so the engine can display the
287        // construction datum/plane frames (it filters to the D/P producers).
288        for (name, frame) in &feature.frames {
289            report.frames.push((name.clone(), *frame));
290        }
291        // The solved sketch profile (SKETCH features publish one under `{id}`) —
292        // carried straight through so the engine can synthesize its sheet solid.
293        for (name, profile) in &feature.profiles {
294            report.profiles.push((name.clone(), profile.clone()));
295        }
296        // The named axis lines this feature published (a SKETCH emits one per line
297        // geometry) — carried through so the engine can resolve a revolve `axis`
298        // reference to a world line for the angle gizmo.
299        for (name, axis) in &feature.axes {
300            report.axes.push((name.clone(), *axis));
301        }
302        // The named path chains this feature published (a SKETCH emits its whole
303        // chain under `{id}` and every model segment under `{id}:G{gid}`) — carried
304        // through so the engine can draw the segments no closed profile covers.
305        for (name, curves) in &feature.paths {
306            report.paths.push((name.clone(), curves.clone()));
307        }
308        // The named world points this feature published (a SKETCH emits every
309        // solved point under `{id}:P{pid}`) — carried through so the engine can
310        // draw a sketch's standalone points, which no segment covers.
311        for (name, point) in &feature.points {
312            report.points.push((name.clone(), *point));
313        }
314    }
315    // Per-feature timing rides the kernel result straight through.
316    report.feature_timings = result.timings.clone();
317    // The wire-harness routing report rides through the same way; its bundle
318    // solids arrived above as the appended `WireHarness` result's `added`.
319    report.wire_harness = result.wire_harness.clone();
320    report.pmi = result.pmi.clone();
321    report.ports = result.ports.clone();
322    SceneLayout { order, handles, reused, creators, entity_origin }
323}
324
325/// Executes history without accessing the render scene and emits display deltas.
326/// Tracks resident handles so unchanged solids retain their meshes and GPU
327/// buffers when the main thread applies the resulting [`RunOutput`].
328pub struct SceneRunner {
329    pub(crate) plugin_revision: Option<u64>,
330    plugins: Option<brep_plugins::Runtime>,
331    plugin_error: Option<String>,
332    /// Last emitted handle per solid name. Handles are never recycled, so a
333    /// matching handle identifies a cache replay whose display can be reused.
334    last_sent: HashMap<String, u32>,
335    /// Baseline tessellation LOD. A change clears `last_sent` so even unchanged
336    /// handles receive meshes built with the new chord tolerance.
337    last_lod: f64,
338    /// Revision installed via `Command::SetPartsLibrary`. Runs with a different
339    /// revision are refused; `reset` clears this alongside the kernel store.
340    pub(crate) parts_library_revision: Option<u64>,
341    /// Names in the last library install. A missing installed part triggers a
342    /// library reload; a name never installed proceeds to the feature's normal
343    /// unresolved-reference error, avoiding an endless reload loop.
344    pub(crate) parts_library_names: std::collections::BTreeSet<String>,
345    /// The run whose tail installed this thread's assembly session: its
346    /// generation and the kernel's session serial right after it. A session
347    /// anything else has replaced since (serial moved) is not that run's.
348    pub(crate) session_of: Option<(u64, u64)>,
349}
350
351/// One placed component as the run left it — the engine's own projection of the
352/// kernel's `ComponentRecord`, which is a `#[serde(skip)]` side-channel and
353/// carries no serde derives of its own. Shipped in the reply so the main thread
354/// has the post-solve component set without re-running the history.
355#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
356pub struct ComponentSnapshot {
357    /// The owning ACOMP feature id — also the namespace prefix segment.
358    pub id: String,
359    /// The display / parts-library part name.
360    pub part_name: String,
361    /// The rigid instance pose (part-local snapshot space -> assembly space)
362    /// as the kernel's row-major 4x4; [`Self::affine`] wraps it back up.
363    pub transform: [f64; 16],
364    /// Evaluated pose before the constraint solver adjusts it.
365    #[serde(default)]
366    pub requested_transform: Option<[f64; 16]>,
367    /// Authored expressions captured at the run boundary.
368    #[serde(default)]
369    pub authored_transform: serde_json::Value,
370    /// Grounded flag (the feature's `isFixed`).
371    pub fixed: bool,
372    /// Opaque source metadata (`sourceKey` / `sourceSignature` / …).
373    pub source: serde_json::Value,
374    /// Member solid scene names, already namespaced (`{id}:{part solid name}`).
375    pub solids: Vec<String>,
376    /// The part's harness PORT ids, namespaced (`{id}:{part port id}`).
377    pub ports: Vec<String>,
378    /// A sub-assembly's SOLVED occurrence poses: path below this component
379    /// (`ACOMP2`, `ACOMP2:ACOMP1`) → pose in this component's part-local
380    /// frame, row-major 4x4. A nested occurrence sits at `transform` composed
381    /// with this, NOT at the transform its document authors: the
382    /// sub-assembly's own mates may have moved it. Empty for a part.
383    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
384    pub nested_poses: std::collections::BTreeMap<String, [f64; 16]>,
385}
386
387impl ComponentSnapshot {
388    /// The pose as the kernel's transform type (for `transform_brep` and the
389    /// structured STEP writer).
390    pub fn affine(&self) -> brep_kernel::AffineTransform {
391        brep_kernel::AffineTransform { elements: self.transform }
392    }
393}
394
395/// Bake an ACOMP `transform` param (`{translate, rotateEulerDeg}`, degrees,
396/// intrinsic `XYZ` — `R = Rx·Ry·Rz`) into the kernel's row-major 4x4. The
397/// inverse of [`brep_kernel::transform_to_pose_params`], which is the encoder
398/// the solver's write-back uses; a component's record pose and its
399/// `inputParams.transform` are the same rigid placement in the two spellings,
400/// and `component_snapshot_pose_matches_the_kernel_bake` pins this against the
401/// kernel's own bake of the same params.
402///
403/// Needed because the per-feature `components` side-channel is captured when the
404/// ACOMP EXECUTES, which is before the constraint tail solves; the solved pose
405/// arrives separately as the write-back. Missing/garbage values fall back to the
406/// identity placement, exactly like the feature's own reader.
407pub(crate) fn pose_params_to_transform(pose: &serde_json::Value) -> [f64; 16] {
408    let vec3 = |key: &str| -> [f64; 3] {
409        let value = &pose[key];
410        std::array::from_fn(|axis| value[axis].as_f64().unwrap_or(0.0))
411    };
412    let translate = vec3("translate");
413    let [rx, ry, rz] = vec3("rotateEulerDeg").map(f64::to_radians);
414    let (sx, cx) = rx.sin_cos();
415    let (sy, cy) = ry.sin_cos();
416    let (sz, cz) = rz.sin_cos();
417    let x = [[1.0, 0.0, 0.0], [0.0, cx, -sx], [0.0, sx, cx]];
418    let y = [[cy, 0.0, sy], [0.0, 1.0, 0.0], [-sy, 0.0, cy]];
419    let z = [[cz, -sz, 0.0], [sz, cz, 0.0], [0.0, 0.0, 1.0]];
420    let mul = |a: [[f64; 3]; 3], b: [[f64; 3]; 3]| -> [[f64; 3]; 3] {
421        std::array::from_fn(|i| {
422            std::array::from_fn(|j| (0..3).map(|k| a[i][k] * b[k][j]).sum())
423        })
424    };
425    let r = mul(x, mul(y, z));
426    [
427        r[0][0], r[0][1], r[0][2], translate[0],
428        r[1][0], r[1][1], r[1][2], translate[1],
429        r[2][0], r[2][1], r[2][2], translate[2],
430        0.0, 0.0, 0.0, 1.0,
431    ]
432}
433
434impl From<&brep_kernel::ComponentRecord> for ComponentSnapshot {
435    fn from(record: &brep_kernel::ComponentRecord) -> Self {
436        Self {
437            id: record.id.clone(),
438            part_name: record.part_name.clone(),
439            transform: record.transform.elements,
440            requested_transform: Some(record.transform.elements),
441            authored_transform: serde_json::Value::Null,
442            fixed: record.fixed,
443            source: record.source.clone(),
444            solids: record.solids.clone(),
445            ports: record.ports.clone(),
446            nested_poses: record
447                .nested_poses
448                .iter()
449                .map(|(path, pose)| (path.clone(), pose.elements))
450                .collect(),
451        }
452    }
453}
454
455/// Everything the main thread needs from the run's ASSEMBLY tail, read on the
456/// runner right after the run and shipped in the reply.
457///
458/// The kernel's assembly session — the post-solve constraint state, its
459/// per-constraint statuses, the DOF summary and the overlay geometry — is
460/// thread-local to whoever ran `execute_history`. Before this the main thread
461/// obtained them by executing the whole history a SECOND time
462/// (`sync_assembly`), which on a document with a wire harness swept every
463/// bundle twice per edit. It reads them from here instead; the only main-side
464/// replay left is the one a constraint MUTATION needs, because that solve runs
465/// against resident geometry on the thread that asks (see
466/// `EngineState::ensure_assembly_session`).
467///
468/// `None` for a componentless document: nothing here is read and the reads cost
469/// nothing.
470#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
471pub struct AssemblySync {
472    /// The scene's component set in deterministic id order — the same fold
473    /// (`removed` unmaps, `components` inserts) the scene build honours.
474    pub components: Vec<ComponentSnapshot>,
475    /// The post-solve `assembly` block (`{constraints, idCounter}`), which the
476    /// applier folds back into the document — the pose-authority write-back's
477    /// state half (the pose/`isFixed` half rides
478    /// [`RunOutput::assembly_poses`]/[`RunOutput::assembly_fixed`]).
479    pub state: serde_json::Value,
480    /// Per-constraint status rows for the constraints panel.
481    pub statuses: serde_json::Value,
482    /// The solve's DOF / diagnostics summary.
483    pub dof: serde_json::Value,
484    /// Per-constraint overlay rows (world anchors/directions/status/value).
485    pub overlay: serde_json::Value,
486    /// The runner's parts-library store, shipped ONLY when the run itself moved
487    /// it — the ACOMP self-heal and the orphan GC are library mutations and the
488    /// main side has no other way to see them. Omitted (`None`) otherwise: it
489    /// carries every embedded part payload, which for an imported STEP assembly
490    /// is megabytes.
491    #[serde(default, skip_serializing_if = "Option::is_none")]
492    pub parts_library: Option<brep_kernel::PartsLibraryMap>,
493}
494
495/// The delta a [`SceneRunner::run`] produces: the displayed KERNEL solids IN
496/// ORDER plus the run's [`SceneBuildReport`]. The applier walks `snapshot` in
497/// order, reusing or replacing each entry (see the field docs).
498#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
499pub struct RunOutput {
500    /// The displayed KERNEL solids IN ORDER. `display: Some` = freshly tessellated
501    /// (new, or the handle changed since last emit); `None` = UNCHANGED — the
502    /// applier keeps its existing [`SolidDisplay`] for this name, whose
503    /// `source_handle` equals `handle`.
504    pub snapshot: Vec<(String /* name */, u32 /* handle */, Option<SolidDisplay>)>,
505    pub report: SceneBuildReport,
506    /// Eager PROVENANCE: `name -> creating-feature id` for the run's FINAL resident
507    /// SOLIDS (same last-writer-wins fold as the display snapshot). Shipped WITH the
508    /// run so the main thread can answer SOLID provenance without a cold
509    /// `execute_history` — critical once the run lives on a background thread and the
510    /// main-side registry is cold.
511    pub provenance: Vec<(String, String)>,
512    /// Eager ENTITY ORIGIN: `face/edge NAME -> ORIGINATING feature id` (FIRST writer
513    /// in timeline order, never pruned — see `SceneLayout::entity_origin`). Shipped
514    /// beside `provenance` so `creating_feature` can answer "which feature gave this
515    /// face/edge its name?" (the "Edit owning feature" context action + the Info
516    /// tab's `creatingFeature`) with no cold re-run. Crosses the background-worker
517    /// seam, so the serde round-trip test asserts it survives.
518    pub entity_origin: Vec<(String, String)>,
519    /// Assembly-solver POSE write-backs from this run's constraint tail:
520    /// `(component feature id, {translate, rotateEulerDeg})` — read RUNNER-SIDE
521    /// (the kernel assembly session is thread-local to the thread/worker that ran
522    /// `execute_history`, so only the runner can see it) and shipped here so the
523    /// engine folds them into the owning ACOMP features' `inputParams` (the
524    /// pose-authority contract). Empty on a no-motion solve — a satisfied
525    /// assembly must not churn feature fingerprints. `#[serde(default)]` keeps
526    /// pre-assembly serialized replies deserializing.
527    #[serde(default)]
528    pub assembly_poses: Vec<(String, serde_json::Value)>,
529    /// `isFixed` write-backs riding the same fold (the Fixed-constraint lane
530    /// grounds a component); shape mirrors [`Self::assembly_poses`].
531    #[serde(default)]
532    pub assembly_fixed: Vec<(String, bool)>,
533    /// Names of solids the solve re-posed IN PLACE this run (the display seam:
534    /// their producing feature may have replayed `reused`, yet their geometry
535    /// moved). The runner already defeated the handle-unchanged reuse fast path
536    /// for these (their snapshot entries arrive `Some`, freshly tessellated);
537    /// shipped for observability/tests. Empty on zero-mate/no-motion runs.
538    #[serde(default)]
539    pub moved_solids: Vec<String>,
540    /// IMPORTED COLOURS: `entity name -> "#RRGGBB"` for every solid/face this run
541    /// left a `color` scene-metadata record on (STEP presentation entities, read
542    /// by `brep_kernel::io/appearance.rs` and stamped by IMPORT3D).
543    ///
544    /// Read RUNNER-SIDE for the same reason as `assembly_poses`: the kernel's
545    /// scene-metadata store is thread-local to whoever ran `execute_history`, so
546    /// a main-thread read under a background runner sees nothing. The applier
547    /// folds these into the engine's own [`crate::metadata::MetadataStore`]
548    /// WITHOUT overwriting, so the Info window shows an imported colour and a
549    /// user's edit of it still wins.
550    ///
551    /// Filtered to the names this run actually produced, so a colour left in the
552    /// (never-cleared) kernel store by a previous document cannot bleed into
553    /// this one.
554    #[serde(default)]
555    pub imported_colors: Vec<(String, String)>,
556    /// Every output name some feature of this run CONSUMED — the union of the
557    /// per-feature `removed` lists, sorted. The committed-sketch refresh hides a
558    /// sketch a downstream extrude/revolve/sheet-metal consumer absorbed, and it
559    /// used to learn that by executing the history again on the UI thread; it
560    /// reads this instead. NOT pruned the way the display fold prunes: a name
561    /// removed and later re-added is still a name this run consumed.
562    #[serde(default)]
563    pub consumed: Vec<String>,
564    /// The run's assembly tail, for a document that has one (see
565    /// [`AssemblySync`]).
566    #[serde(default)]
567    pub assembly: Option<AssemblySync>,
568}
569
570impl SceneRunner {
571    /// Provision explicitly trusted packages on this runner's execution thread.
572    pub fn set_plugins(&mut self, revision: u64, packages: serde_json::Value) {
573        let runtime = serde_json::from_value(packages)
574            .map_err(|e| format!("plugin packages: {e}"))
575            .and_then(brep_plugins::Runtime::new);
576        match runtime {
577            Ok(runtime) => { self.plugins = Some(runtime); self.plugin_error = None; }
578            Err(error) => { self.plugins = None; self.plugin_error = Some(error); }
579        }
580        self.plugin_revision = Some(revision);
581        self.last_sent.clear();
582    }
583
584    pub(crate) fn plugin_action(&self, request: crate::runner::PluginActionRequest) -> crate::runner::PluginActionReply {
585        let result = if let Some(source) = &request.script {
586            brep_plugins::execute_script(source, &request.input)
587        } else { match &self.plugins {
588            Some(runtime) => runtime.execute_action(&request.pins, &request.action, &request.input),
589            None => Err(self.plugin_error.clone().unwrap_or_else(|| "no plugin packages installed".into())),
590        }};
591        crate::runner::PluginActionReply { id: request.id, result }
592    }
593
594    pub fn new() -> Self {
595        Self {
596            plugin_revision: None,
597            plugins: None,
598            plugin_error: None,
599            last_sent: HashMap::new(),
600            last_lod: 1.0,
601            parts_library_revision: None,
602            parts_library_names: std::collections::BTreeSet::new(),
603            session_of: None,
604        }
605    }
606
607    /// Reset the delta baseline (call on a wholesale document switch so the next
608    /// run is a full rebuild — no stale reuse across unrelated models).
609    pub fn reset(&mut self) {
610        self.last_sent.clear();
611        // A reset always accompanies the `clear_history_cache` that empties
612        // this side's parts library, so forget what was installed — the next
613        // run's stamp will not match and the library is re-sent.
614        self.parts_library_revision = None;
615        self.parts_library_names.clear();
616        self.session_of = None;
617    }
618
619    /// An owned copy of the assembly session the run of `generation` left on
620    /// this thread, or `None` when this thread's session is not that run's.
621    pub(crate) fn export_session(&self, generation: u64) -> Option<brep_kernel::SessionTransfer> {
622        match self.session_of {
623            Some((ran, serial)) if ran == generation && serial == brep_kernel::assembly_session_serial() => {
624                brep_kernel::assembly_session_export()
625            }
626            _ => None,
627        }
628    }
629
630    /// Execute `request` and fold it into an ordered delta snapshot (does NOT
631    /// touch any scene). For each displayed kernel solid in order: if the handle
632    /// is unchanged since the last emit, emit `(name, handle, None)` (the applier
633    /// keeps its existing display); otherwise (re-)tessellate the resident handle
634    /// and emit `(name, handle, Some(display))`. A display-payload error is
635    /// recorded in `report.display_errors` and the entry is SKIPPED — and NOT
636    /// recorded in the new baseline, so a later successful run re-tessellates it.
637    ///
638    ///
639    /// Colours are NOT applied here. A display arrives colourless and the main
640    /// side paints it from the metadata store
641    /// ([`EngineState::sync_colors_from_metadata`](crate::engine_state::EngineState::sync_colors_from_metadata)),
642    /// which is the only colour authority — a runner may be a background thread
643    /// or worker with no view of that store.
644    pub fn run(&mut self, request: &HistoryRequest) -> RunOutput {
645        self.run_observed(request, &mut |_| true)
646    }
647
648    /// [`Self::run`] with a progress observer: `observe` is called before every
649    /// feature the kernel actually executes (see
650    /// [`brep_kernel::execute_history_observed`]); returning `false` stops the
651    /// run at that boundary, and the partial result is folded like any other.
652    pub fn run_observed(
653        &mut self,
654        request: &HistoryRequest,
655        observe: &mut dyn FnMut(brep_kernel::HistoryProgress<'_>) -> bool,
656    ) -> RunOutput {
657        // The parts-library revision ACROSS the run: a run heals a dirty entry
658        // and GCs orphans, and those are the only library mutations the main
659        // side cannot see for itself. Compared below to decide whether the
660        // (potentially megabyte) store has to ride the reply.
661        let library_revision_before = brep_kernel::parts_library_revision();
662        let result = {
663            let mut trace = crate::run_trace::span("runner");
664            let result = match &self.plugins {
665                Some(runtime) => runtime.with_provider(|| brep_kernel::execute_history_observed(request, observe)),
666                None => brep_kernel::execute_history_observed(request, observe),
667            };
668            if let Some(trace) = trace.as_mut() {
669                trace.result(&result);
670            }
671            result
672        };
673        let mut report = SceneBuildReport::default();
674        let layout = fold_history(&result, &mut report);
675
676        // --- assembly pose-authority read (RUNNER-SIDE) ---- The kernel assembly
677        // session (constraint solve tail) is THREAD-LOCAL to whoever ran
678        // `execute_history` — i.e. this thread/worker — so the pose and isFixed
679        // write-backs must be read HERE and shipped in the RunOutput; a
680        // main-thread read under a background runner would see a cold session.
681        let pose_updates: serde_json::Value =
682            serde_json::from_str(&brep_kernel::assembly_pose_updates_json())
683                .unwrap_or(serde_json::Value::Null);
684        let assembly_poses: Vec<(String, serde_json::Value)> = pose_updates["poses"]
685            .as_object()
686            .map(|map| map.iter().map(|(id, pose)| (id.clone(), pose.clone())).collect())
687            .unwrap_or_default();
688        let assembly_fixed: Vec<(String, bool)> = pose_updates["isFixed"]
689            .as_object()
690            .map(|map| {
691                map.iter()
692                    .filter_map(|(id, flag)| flag.as_bool().map(|b| (id.clone(), b)))
693                    .collect()
694            })
695            .unwrap_or_default();
696        // The display seam: solids the solve re-posed IN PLACE keep their resident
697        // handle, so the handle-unchanged reuse fast path below would wrongly skip
698        // re-tessellating them even though their geometry moved. Drop them from
699        // the baseline so they re-emit fresh displays. The `movedSolids` key is
700        // ABSENT on zero-mate reports — tolerated (empty).
701        let dof: serde_json::Value = serde_json::from_str(&brep_kernel::assembly_dof_json())
702            .unwrap_or(serde_json::Value::Null);
703        let moved_solids: Vec<String> = dof["movedSolids"]
704            .as_array()
705            .map(|items| {
706                items
707                    .iter()
708                    .filter_map(|item| item["name"].as_str().map(String::from))
709                    .collect()
710            })
711            .unwrap_or_default();
712        for name in &moved_solids {
713            self.last_sent.remove(name);
714        }
715
716        // --- the assembly session + consumed names (RUNNER-SIDE) -------------
717        // Same thread-local reason as the poses above, and the whole point of
718        // `AssemblySync`: read here, applied there, never re-executed.
719        let assembly = request_has_assembly(request).then(|| {
720            let authored: HashMap<&str, &serde_json::Value> = request.features.iter()
721                .filter_map(|f| f.input_params["id"].as_str().map(|id| (id, &f.input_params["transform"])))
722                .collect();
723            let mut components: std::collections::BTreeMap<String, ComponentSnapshot> =
724                std::collections::BTreeMap::new();
725            for feature in &result.results {
726                for removed in &feature.removed {
727                    components.remove(removed);
728                }
729                for record in &feature.components {
730                    let mut snapshot = ComponentSnapshot::from(record);
731                    snapshot.authored_transform = authored.get(record.id.as_str())
732                        .map(|value| (*value).clone()).unwrap_or_default();
733                    components.insert(record.id.clone(), snapshot);
734                }
735            }
736            // A record's pose is captured when its ACOMP EXECUTES, which is
737            // before the constraint tail solves — so a solved component's record
738            // still carries its authored placement. Re-pose from the same solver
739            // write-back the document adopts, or the projection (the structure
740            // tree, the BOM, the structured STEP writer, the component vertex
741            // ref) would lag the solve by a run.
742            for (id, pose) in &assembly_poses {
743                if let Some(component) = components.get_mut(id) {
744                    component.transform = pose_params_to_transform(pose);
745                }
746            }
747            // Same for a grounded flag the tail wrote (a legacy Fixed row the
748            // lifecycle migrated into the instance setting): the record was
749            // captured before it, and the projection must not show the part
750            // free until some later run.
751            for (id, fixed) in &assembly_fixed {
752                if let Some(component) = components.get_mut(id) {
753                    component.fixed = *fixed;
754                }
755            }
756            let parse = |json: String| {
757                serde_json::from_str::<serde_json::Value>(&json).unwrap_or(serde_json::Value::Null)
758            };
759            AssemblySync {
760                components: components.into_values().collect(),
761                state: parse(brep_kernel::assembly_state_json()),
762                statuses: parse(brep_kernel::assembly_statuses_json()),
763                dof: dof.clone(),
764                overlay: parse(brep_kernel::assembly_overlay_json()),
765                parts_library: (brep_kernel::parts_library_revision() != library_revision_before)
766                    .then(brep_kernel::parts_library_map),
767            }
768        });
769        // The consumed-name union the committed-sketch refresh needs. Sorted, so
770        // the reply is byte-stable for a given run (the worker seam serializes it).
771        let consumed: Vec<String> = result
772            .results
773            .iter()
774            .flat_map(|feature| feature.removed.iter().cloned())
775            .collect::<std::collections::BTreeSet<String>>()
776            .into_iter()
777            .collect();
778
779        // Display LOD: a finite, positive factor (garbage from a hand-edited saved
780        // file → the "Normal" 1.0, since chord = extent·1.5e-3·lod and a 0/NaN lod
781        // would zero the tolerance → runaway refinement). A change since the last
782        // run means every resident mesh must re-tessellate at the new chord even
783        // though its handle is unchanged, so drop the reuse baseline.
784        let lod = if request.display_lod.is_finite() && request.display_lod > 0.0 {
785            request.display_lod
786        } else {
787            1.0
788        };
789        if lod != self.last_lod {
790            self.last_sent.clear();
791            self.last_lod = lod;
792        }
793
794        let mut snapshot: Vec<(String, u32, Option<SolidDisplay>)> =
795            Vec::with_capacity(layout.order.len());
796        let mut next_sent: HashMap<String, u32> = HashMap::with_capacity(layout.order.len());
797
798        for name in &layout.order {
799            let handle = layout.handles[name];
800            if self.last_sent.get(name) == Some(&handle) {
801                // Handle unchanged since last emit ⇒ same resident geometry ⇒ the
802                // applier keeps its existing display. This is EXACTLY the old
803                // `reused && source_handle == handle` fast path (monotonic handles):
804                // the canary below verifies the implication holds.
805                debug_assert!(
806                    layout.reused.contains(name),
807                    "handle unchanged must imply reused (monotonic handles): {name}"
808                );
809                snapshot.push((name.clone(), handle, None));
810                next_sent.insert(name.clone(), handle);
811                continue;
812            }
813            match display_payload_handle_native(handle, lod) {
814                Ok(payload) => {
815                    let mut solid = solid_display_from_payload(name, payload);
816                    solid.source_handle = handle;
817                    // Runner thread → the SheetTree thread-local is warm here; stamp
818                    // the sheet-metal marker so the UI thread reads it off the scene
819                    // (never calling the thread-local from a cold UI thread).
820                    solid.is_sheet_metal = brep_kernel::is_sheet_metal_handle(handle);
821                    snapshot.push((name.clone(), handle, Some(solid)));
822                    next_sent.insert(name.clone(), handle);
823                }
824                // A tessellation failure skips the solid (non-fatal) and does NOT
825                // poison the baseline — dropping it lets a later successful run
826                // re-tessellate from scratch.
827                Err(error) => report.display_errors.push(format!("{name}: {error}")),
828            }
829        }
830
831        self.last_sent = next_sent;
832        // Eager provenance for the run's final resident solids (the applier stores
833        // this map main-side so per-frame provenance queries never re-run history).
834        let provenance: Vec<(String, String)> = layout
835            .creators
836            .iter()
837            .map(|(name, id)| (name.clone(), id.clone()))
838            .collect();
839        // Eager entity origin (face/edge NAME -> originating feature id) rides
840        // alongside, so face/edge provenance survives the off-thread seam too.
841        let entity_origin: Vec<(String, String)> = layout
842            .entity_origin
843            .iter()
844            .map(|(name, id)| (name.clone(), id.clone()))
845            .collect();
846        // Imported colours, read HERE for the thread-local reason above and
847        // filtered to this run's own entities: the solids it displays plus the
848        // faces/edges it named. The kernel store is never cleared between
849        // documents, so an unfiltered ship could hand the applier a colour that
850        // belongs to a model the user closed.
851        let imported_colors: Vec<(String, String)> = serde_json::from_str::<serde_json::Value>(
852            &brep_kernel::scene_metadata_colors_json(),
853        )
854        .ok()
855        .and_then(|value| value.as_object().cloned())
856        .map(|map| {
857            map.into_iter()
858                .filter(|(name, _)| {
859                    layout.handles.contains_key(name) || layout.entity_origin.contains_key(name)
860                })
861                .filter_map(|(name, hex)| hex.as_str().map(|hex| (name, hex.to_string())))
862                .collect()
863        })
864        .unwrap_or_default();
865
866        RunOutput {
867            snapshot,
868            report,
869            provenance,
870            entity_origin,
871            assembly_poses,
872            assembly_fixed,
873            moved_solids,
874            imported_colors,
875            consumed,
876            assembly,
877        }
878    }
879
880    /// The resident handle last EMITTED for `name` (the delta baseline), or `None`
881    /// if the runner has not emitted a solid of that name. The measurement-query
882    /// path resolves an object's owning-solid handle through this so the query runs
883    /// against the SAME resident geometry the last run displayed (on the runner's
884    /// own thread, whose registry is warm from that run).
885    pub fn handle_of(&self, name: &str) -> Option<u32> {
886        self.last_sent.get(name).copied()
887    }
888}
889
890impl Default for SceneRunner {
891    fn default() -> Self {
892        Self::new()
893    }
894}
895
896/// Execute the history and reconcile `scene` in place (R10 incremental update):
897/// reused solids already present keep their [`SolidDisplay`] verbatim (stable
898/// `revision` ⇒ the renderer reuses their GPU buffers); everything else is
899/// (re-)tessellated from the resident handle; departed solids are dropped.
900///
901/// Implemented on the M1 seam: a throwaway [`SceneRunner`] primed from the
902/// CURRENT scene (`name → source_handle` of what is displayed) reproduces the
903/// pre-seam reuse in a single synchronous call, and its [`RunOutput`] delta is
904/// applied back to `scene` by MOVING existing displays out (via
905/// [`RenderScene::drain`]) so a reused solid's mesh is never cloned.
906pub fn update_scene_from_history(
907    scene: &mut RenderScene,
908    request: &HistoryRequest,
909) -> Result<SceneBuildReport, String> {
910    let mut runner = SceneRunner::new();
911    runner.last_sent = scene
912        .solids()
913        .iter()
914        .map(|solid| (solid.name.clone(), solid.source_handle))
915        .collect();
916    let output = runner.run(request);
917
918    // Move the current displays out, then reinsert in snapshot ORDER: a fresh
919    // entry replaces, an UNCHANGED entry reuses the moved-out display (whose
920    // `source_handle` equals the run's handle — guaranteed by the reuse
921    // invariant). Leftovers (departed names) are dropped.
922    let mut kept: HashMap<String, SolidDisplay> = scene
923        .drain()
924        .into_iter()
925        .map(|solid| (solid.name.clone(), solid))
926        .collect();
927    for (name, _handle, maybe) in output.snapshot {
928        match maybe {
929            Some(display) => scene.insert_solid(display),
930            None => scene.insert_solid(
931                kept.remove(&name).expect("keep target present"),
932            ),
933        }
934    }
935    Ok(output.report)
936}
937
938/// Execute `request` and return the FINAL resident solids as `(name, handle)` in
939/// display order — the export lane (STEP/STL) needs the current solids' resident
940/// handles, which the scene build does not itself retain. Run right after a scene
941/// build (warm incremental cache) this replays the cached features, so the
942/// handles it returns are the very ones the displayed scene was built from; run
943/// cold it re-executes and registers fresh (still-valid) handles. Either way the
944/// handles are live in the thread-local registry when this returns, ready to
945/// hand to `brep_kernel::export_step_handles`.
946pub fn resident_solid_handles(request: &HistoryRequest) -> Vec<(String, u32)> {
947    let _trace = crate::run_trace::span("export_resident_handles");
948    let result = execute_history(request);
949    let mut report = SceneBuildReport::default();
950    let layout = fold_history(&result, &mut report);
951    layout
952        .order
953        .iter()
954        .map(|name| (name.clone(), layout.handles[name]))
955        .collect()
956}
957