Skip to main content

brep_render/
engine_state.rs

1//! [`EngineState`] — the windowing-agnostic viewer state machine the host UI
2//! programs against (R3): scene + camera + controls + settings + emphasis, plus
3//! the whole event/command/query surface (run-history feed, pointer/wheel
4//! ingestion, camera commands, picking, world→screen, visibility). No GPU, no
5//! canvas — the wasm `Engine` and the winit desktop shell both wrap this; it is
6//! fully unit-testable on native.
7//!
8//! Everything crosses the R3 boundary as plain JSON/scalars: the host never holds a
9//! renderer object, only names, ids, and JSON.
10
11use crate::controls::ArcballControls;
12use crate::history::History;
13use crate::pick::{self, PickOptions};
14use crate::scene::RenderScene;
15use crate::style::{Emphasis, RenderSettings};
16use crate::view::ViewCamera;
17use crate::widgets::{gizmo_camera, WidgetOverlay, WidgetRegistry};
18use brep_kernel::HistoryRequest;
19use std::collections::HashMap;
20
21/// One DIALOG row's hover state — which panel lit it, the row's own TEXT, and
22/// what that text resolved to in the scene.
23///
24/// The row text is the memo key rather than the candidate's name because the two
25/// differ whenever the derived-face fallback fires (a fillet's `Edges` row reads
26/// `A|B[0]` while the face it lights is `F1:BLEND:A|B[0]` — see
27/// [`EngineState::hover_entity_by_name`]). An unresolvable row memoizes as
28/// `candidate: None`, so a held hover over a name the scene does not carry scans
29/// the scene ONCE, not once per frame.
30#[derive(Clone)]
31pub(crate) struct DialogHover {
32    /// Which panel set it (`"history"`, `"constraints"`, `"pmi"`, `"refsel"`) —
33    /// [`EngineState::dialog_hover_end`] acts only for the owner that set it, so a
34    /// pane that never hovered a row cannot end another pane's hover.
35    pub(crate) owner: &'static str,
36    /// The row's TEXT, exactly as the dialog listed it.
37    pub(crate) row: String,
38    /// What it resolved to, or `None` for a row the scene does not carry.
39    pub(crate) candidate: Option<pick::PickCandidate>,
40}
41
42pub struct EngineState {
43    pub scene: RenderScene,
44    /// Display-only assembly surroundings in the active work part frame. Never picked or saved.
45    pub context_scene: RenderScene,
46    /// The Work part CONTEXT face clicked / hovered ([`Self::context_hit_at`]):
47    /// kept apart from [`Self::emphasis`], so no selection consumer (feature
48    /// prefill, references, plugins, metadata) ever sees a name the part's own
49    /// kernel cannot resolve.
50    pub(crate) context_selected: Option<crate::pick::PickCandidate>,
51    pub(crate) context_hovered: Option<crate::pick::PickCandidate>,
52    /// Ghosts (context solids) lit WHOLE by a running instructions occurrence
53    /// pick whose names they are (`sync_ref_select_emphasis`): every face of
54    /// each goes into the context highlight. Cleared when the pick ends.
55    pub(crate) context_pick_lit: Vec<String>,
56    /// How the context is shown: kept across context rebuilds and Work parts.
57    pub(crate) context_display: crate::engine_state::context_pick::ContextDisplay,
58    pub camera: ViewCamera,
59    pub controls: ArcballControls,
60    pub settings: RenderSettings,
61    pub emphasis: Emphasis,
62    /// In-scene overlay widgets: datums/dimensions/curves, transform
63    /// gizmo, ViewCube — fed as JSON, drawn by the render core's overlay pass.
64    pub widgets: WidgetRegistry,
65    /// The engine-owned editable model recipe (ordered features + rollback
66    /// index) — the SINGLE source of truth for the model. The UI never keeps its
67    /// own copy; it mutates/reads this through the `history_*` / feature methods.
68    pub history: History,
69    interference_sessions: std::collections::BTreeMap<String, interference::InterferenceCursor>,
70    interference_sequence: u64,
71    illustration_snapshot: Option<illustration::IllustrationSnapshot>,
72    geometry_diagnostics: std::collections::BTreeMap<String, serde_json::Value>,
73    /// A single feature staged by [`EngineState::stage_feature_begin`] whose
74    /// run has not landed yet (an agent's write; `batch.rs`).
75    staged_feature: Option<batch::StagedFeature>,
76    /// A structured batch started by [`EngineState::author_batch_begin`]
77    /// that has not finished yet; the app steps it once per frame.
78    batch_job: Option<Box<batch::BatchJob>>,
79    /// `History::busy_refused` already reported to the user.
80    busy_refused_seen: u64,
81    /// The build report (`{featureErrors, unresolved, displayErrors}`) of the
82    /// last history run, so the UI can show it without re-running.
83    history_report: String,
84    /// The Properties-panel metadata store: user attributes keyed by OBJECT NAME
85    /// (solid / face / edge kernel name), NOT feature id — so a record survives
86    /// feature edits as long as the object's name persists. Persisted with the
87    /// model (a top-level `metadata` field in the history document); see the
88    /// [`crate::metadata`] module for the store + the object-info/measurement API.
89    pub metadata: crate::metadata::MetadataStore,
90    /// The document's component namespace, built once per history revision
91    /// ([`EngineState::component_namespace`]).
92    component_namespace: std::cell::RefCell<Option<(u64, std::rc::Rc<brep_kernel::ComponentNamespace>)>>,
93    /// Derived preview data stays outside the recipe and undo history: the
94    /// document's own picture at a history edit serial (opened with it, or the
95    /// last one a save rendered), and the last picture a save produced by key.
96    document_thumbnail: std::cell::RefCell<Option<(u64, serde_json::Value)>>,
97    thumbnail_cache: std::cell::RefCell<Option<(Vec<u64>, serde_json::Value)>>,
98    /// Bumped whenever settings change so the renderer re-derives per-solid
99    /// base styles (a cheap key, not a per-frame diff).
100    pub settings_generation: u64,
101    /// The engine sets this whenever the camera/scene/emphasis changed; the
102    /// presentation shell renders only when it is set (R22 on-demand render —
103    /// the OrthoCameraIdle matrix-compare analogue, made explicit).
104    pub dirty: bool,
105    /// The modal reference-selection state (the ref-select widget). `Some` while
106    /// the user is picking references for a feature-dialog field; `None`
107    /// otherwise. The picked-name list here is the SINGLE source of truth while
108    /// active (the UI reads it back; the viewport appends to it on a pick).
109    pub ref_select: Option<RefSelectState>,
110    /// A finished REPLACE REPAIR pick `(mate, old ref, picked name)` waiting
111    /// for the replace dialog, which owns the remap (nested components
112    /// included) — see [`RefSelectTarget::ReplaceRepair`].
113    pub(crate) replace_repair_pick: Option<(String, String, String)>,
114    /// Which entity KINDS a plain viewport click may select (the selection
115    /// filter, mirroring the earlier `SelectionFilter.allowedSelectionTypes`). `select_top_at`
116    /// consults it via `pick_filtered`; see the appended `SelectionFilter` impl
117    /// block near the end of this file for the state + honoring logic.
118    pub selection_filter: SelectionFilter,
119    /// The HELD-LETTER filter override: the
120    /// kind a held key (S/F/E/V/C/P) admits and the bottom filter it
121    /// replaced, restored when the key is released.
122    pub(crate) filter_override: Option<(&'static str, SelectionFilter)>,
123    /// The transform-controls gizmo controller: which feature (if any) has the
124    /// move/rotate gizmo armed (via the in-viewport center-sphere toggle), plus the
125    /// in-flight handle drag. All the arm/drag/apply logic lives in the appended
126    /// transform-gizmo impl block near the end of this file.
127    pub transform_gizmo: TransformArm,
128    /// The COMPONENT Move gizmo controller (assemblies §8.5): which ACOMP
129    /// instance has the bbox-center move/rotate gizmo armed, the translate/
130    /// rotate cycle mode, and the commit-on-release drag. Exclusive with
131    /// `transform_gizmo` (shared widget slot). See `component_move.rs`.
132    pub component_move: ComponentMoveArm,
133    /// The active engine-native sketch edit (`Some` while in sketch mode). Holds
134    /// the live [`crate::sketch::SketchSession`] plus the pre-entry camera + roll
135    /// to restore on exit. All the enter/exit/new logic lives in the appended
136    /// sketch-mode impl block at the END of this file.
137    sketch_edit: Option<SketchEdit>,
138    /// The active engine-native 3D SKETCH edit (`Some` while in 3D sketch
139    /// mode): the live [`crate::sketch3d::Sketch3dSession`] plus the pre-entry
140    /// camera + roll. See `sketch3d_mode.rs`.
141    sketch3d_edit: Option<Sketch3dEdit>,
142    /// The `world_per_pixel` the 3D sketch overlay was last baked at (its
143    /// working-plane and reference-plane squares are pixel-sized); `0.0` =
144    /// not in 3D sketch mode.
145    pub(crate) sketch3d_overlay_wpp: f64,
146    /// Sketch-mode camera lock. When true (the default on every sketch entry), the
147    /// camera is held flat-on to the sketch plane and an empty drag only PANS —
148    /// no orbit. Toggling it back on re-faces the camera to the plane. Meaningful
149    /// only while `sketch_edit` is `Some`. See the sketch-mode impl block.
150    sketch_camera_locked: bool,
151    /// Set for ONE frame when the sketch entity-LIST panel hovers a row (it calls
152    /// [`sketch_hover_entity`](Self::sketch_hover_entity)). The viewport, which
153    /// draws AFTER the panel and would otherwise `sketch_clear_hover` because the
154    /// pointer is off the viewport, consumes this flag via
155    /// [`take_sketch_list_hover`](Self::take_sketch_list_hover) and keeps the
156    /// panel-set hover so list→canvas highlight survives the frame.
157    sketch_list_hover_active: bool,
158    /// Transient user-facing notices (e.g. a sketch solve that failed after an
159    /// edit). The shell drains them each frame via [`take_notices`](Self::take_notices)
160    /// into a toast overlay; the engine only queues. Replaces the swallowed
161    /// `eprintln!` on the interactive re-solve paths.
162    notices: Vec<String>,
163    /// Notices that are NOT errors — a warning, or a success such as "Updated 2
164    /// part(s)" — with their severity, queued by
165    /// [`push_notice_as`](Self::push_notice_as). Beside [`Self::notices`] rather
166    /// than in it, so every existing `push_notice` stays an error unchanged.
167    graded_notices: Vec<(NoticeSeverity, String)>,
168    /// Committed-sketch visibility: the feature ids whose persistent committed-sketch
169    /// overlay is HIDDEN (its Scene-tree checkbox off). Absent = visible. See the
170    /// committed-sketch impl block appended at the END of this file.
171    hidden_sketches: std::collections::HashSet<String>,
172    /// The committed-sketch feature ids whose overlay groups were fed on the LAST
173    /// [`refresh_committed_sketches`](Self::refresh_committed_sketches), so an id that
174    /// is no longer shown (rolled back, deleted, hidden, or became the active edit)
175    /// can have its now-stale groups cleared.
176    shown_sketch_ids: Vec<String>,
177    /// The board bodies fed on the LAST
178    /// [`refresh_board_geometry`](Self::refresh_board_geometry), in stack order,
179    /// so a body this build did not produce can be swept out of the scene.
180    /// Parallels [`shown_sketch_ids`].
181    shown_board_ids: Vec<String>,
182    /// The eCAD board those bodies were built from — the rebuild test. A
183    /// SCHEMATIC edit rewrites the whole `pcb` block with the same board inside
184    /// it, and this is what makes that edit free.
185    board_built_from: Option<brep_ecad_core::board::Board>,
186    /// The pin-to-net map those bodies' NET COLOURS were built from. The board
187    /// alone does not decide them — a copper island carries the net of the pads
188    /// it touches, and which net a pad carries is the SCHEMATIC's answer — so
189    /// this is the second half of the rebuild test. Empty for a board with no
190    /// placements, which can carry no net at all.
191    board_pin_nets: std::collections::BTreeMap<(brep_ecad_core::Uuid, String), String>,
192    /// What that build cost, for the Scene tree and the tests.
193    board_build: board_geometry::BoardBuild,
194    /// The built bodies themselves, KEPT across runs. The scene reconcile drops
195    /// every derived body, so without this a dense board would be re-meshed on
196    /// every history run; a clone of these is what goes back in instead.
197    board_displays: Vec<crate::scene::SolidDisplay>,
198    /// The named plane FRAMES the last history run resolved `(frame name, frame)`.
199    /// Stored so [`refresh_construction_datums`](Self::refresh_construction_datums)
200    /// (and datum selection) can display/pick the construction datum/plane frames
201    /// without re-running. Filled from the run's
202    /// [`crate::pipeline::SceneBuildReport::frames`]; the D/P filter is applied at
203    /// display time (a frame name maps to its producing feature TYPE via the
204    /// history). See the appended construction-datum impl block at the END.
205    construction_frames: Vec<(String, brep_kernel::Frame)>,
206    /// The DRAFT ANALYSIS view while it is on (`draft_analysis_ops`): display
207    /// only, never saved and never an undo step.
208    draft_analysis: Option<draft_analysis_ops::DraftAnalysisState>,
209    /// The solved sketch PROFILES the last history run produced `(sketch id,
210    /// profile)`. Stored so [`refresh_committed_sketches`](Self::refresh_committed_sketches)
211    /// can synthesize each committed sketch's SHEET SOLID (planar face + named
212    /// boundary edges + corner vertices) without re-running. Filled from the run's
213    /// [`crate::pipeline::SceneBuildReport::profiles`]; rollback / active-edit /
214    /// visibility gating is applied at display time.
215    sketch_profiles: Vec<(String, brep_kernel::SketchProfile)>,
216    /// The named PATH chains the last history run produced `(path name, curves)`.
217    /// Stored alongside [`sketch_profiles`](Self::sketch_profiles) so
218    /// [`refresh_committed_sketches`](Self::refresh_committed_sketches) can draw the
219    /// sketch geometry no closed profile covers: a sketch's OPEN chain publishes no
220    /// profile, so the sheet builder had nothing to draw it from and an open sketch
221    /// was invisible in 3D. Filled from the run's
222    /// [`crate::pipeline::SceneBuildReport::paths`]; the per-segment `{id}:G{gid}`
223    /// entries are the display input (the whole-chain `{id}` entry duplicates them
224    /// and `{id}:REF:{source}` is projected reference geometry).
225    sketch_paths: Vec<(String, Vec<brep_kernel::NurbsCurve>)>,
226    /// The named world POINTS the last history run produced `(point name, point)`.
227    /// Stored alongside [`sketch_paths`](Self::sketch_paths) so
228    /// [`refresh_committed_sketches`](Self::refresh_committed_sketches) can draw the
229    /// sketch points no segment covers: a points-only sketch (a hole-placement
230    /// sketch) publishes no profile and no path, so it had nothing to draw from
231    /// and was invisible in 3D. Filled from the run's
232    /// [`crate::pipeline::SceneBuildReport::points`]; the per-point `{id}:P{pid}`
233    /// entries are the display input (construction points are skipped at draw
234    /// time, like construction geometry).
235    sketch_points: Vec<(String, brep_kernel::ScenePoint)>,
236    /// The named axis LINES the last history run produced `(axis name, line)`.
237    /// Stored so the feature-dimension angle gizmo can resolve a revolve `axis`
238    /// reference to a world line without re-running. Filled from the run's
239    /// [`crate::pipeline::SceneBuildReport::axes`].
240    sketch_axes: Vec<(String, brep_kernel::Axis)>,
241    /// The wire-harness routing report of the last APPLIED run (`None` before
242    /// the first run). Filled from [`crate::pipeline::SceneBuildReport::wire_harness`];
243    /// the harness panel reads it, the committed-curve display reads the port
244    /// kinds off it. See the appended wire-harness impl block.
245    wire_harness_report: Option<brep_kernel::WireHarnessReport>,
246    /// The PORTS tail's report of the last APPLIED run (`None` before the first
247    /// run, and for a document that declares no `ports` block). Filled from
248    /// [`crate::pipeline::SceneBuildReport::ports`]; the Qualify panel reads it,
249    /// and it is the only place the tail's refused names and unresolved
250    /// references surface, the tail not being a feature.
251    ports_report: Option<brep_kernel::PortsReport>,
252    /// The PMI tail's report of the last APPLIED run (`pmi_ops.rs`).
253    pub(crate) pmi_report: Option<brep_kernel::PmiReport>,
254    /// The ACTIVE PMI view (engine memory, never persisted): its camera,
255    /// display state and explode poses are applied; its annotations drawn.
256    pub(crate) pmi_active_view: Option<String>,
257    /// The annotation whose form the PMI panel shows (engine memory). Never
258    /// assign `Some` here: go through [`EngineState::open_pmi_annotation`], the
259    /// one place that counts the open.
260    pub(crate) pmi_open_annotation: Option<String>,
261    /// The VIEW whose form the PMI panel shows (engine memory) — exclusive
262    /// with [`Self::pmi_open_annotation`], since the pane shows one dialog.
263    /// Never assign `Some` here: go through [`EngineState::open_pmi_view`].
264    pub(crate) pmi_open_view: Option<String>,
265    /// The annotation SELECTED in the PMI tree or by its viewport label: the
266    /// tree row's highlight and the label's accent. Cleared with the selection
267    /// (Esc / Clear / a click on empty space); read through
268    /// [`EngineState::pmi_selected_annotation`], which prunes a stale id.
269    pub(crate) pmi_selected_annotation: Option<String>,
270    /// The VIEW selected in the PMI tree — its row's highlight. Selecting a
271    /// view never ACTIVATES it (a double click does); exclusive with
272    /// [`Self::pmi_selected_annotation`], since the tree selects one row.
273    /// Read through [`EngineState::pmi_selected_view`], which prunes a stale id.
274    pub(crate) pmi_selected_view: Option<String>,
275    /// How many times a PMI dialog — an annotation's or a view's — has been
276    /// OPENED: monotonic, never reset, closes do not count. The app's dialog
277    /// door keys on it beside the subject so a re-open of the dialog that is
278    /// ALREADY open is still one open event (a viewport label double click on the
279    /// annotation whose form is up, which a user makes precisely because they
280    /// are on another tab).
281    pub(crate) pmi_dialog_opens: u64,
282    /// The modeling camera / visibility / wireframe remembered on entering
283    /// the PMI workbench, restored when a view deactivates or the workbench
284    /// is left.
285    pub(crate) pmi_modeling: Option<pmi_ops::PmiModelingSnapshot>,
286    /// The un-exploded displays of the solids the active view's explode
287    /// annotations posed, for an exact restore.
288    pub(crate) pmi_explode_originals: std::collections::HashMap<String, crate::scene::SolidDisplay>,
289    /// How far the active view's explode steps are shown, and any Explode /
290    /// Collapse animation (`exploded_ops`). Display state, never saved.
291    pub(crate) explode_playback: exploded_ops::ExplodePlayback,
292    /// The motion study being played or scrubbed and its bake
293    /// (`simulation_play`). Display state, never saved.
294    pub(crate) simulation_play: Option<simulation_play::SimulationPlayback>,
295    /// Solids the active view's section removes whole: hidden (no copy, no
296    /// re-upload) rather than clipped, and shown again on restore.
297    pub(crate) pmi_section_hidden: Vec<String>,
298    /// Bumped when an un-posed original's `visible` changes (a user or view
299    /// hide while the active view poses or sections that solid): sheets
300    /// draw from the originals, so their cache key carries it.
301    pub(crate) pmi_unposed_visibility: u64,
302    /// The `pmi` block parsed, keyed by the history revision it was parsed
303    /// at ([`Self::pmi_state_shared`]): every write to the saved document,
304    /// undo and redo included, moves that revision.
305    pub(crate) pmi_state_cache: std::cell::RefCell<Option<(u64, std::rc::Rc<brep_kernel::PmiState>)>>,
306    /// A balloon whose dragged bubble could not be re-projected yet because
307    /// the scene did not hold its occurrence's exact solids: re-derived when
308    /// the topology reply lands (`pmi_refresh_stale_balloon`).
309    pub(crate) pmi_balloon_stale: Option<String>,
310    /// `(world_per_pixel, view direction)` the PMI overlay was last baked at.
311    pub(crate) pmi_overlay_key: Option<(f64, [f64; 3])>,
312    /// The center marks the last PMI overlay bake drew, for automation
313    /// ([`Self::pmi_center_marks_json`]): `(annotation id, per mark its two
314    /// cross arms as unit world directions)`, read in f64 before the
315    /// overlay's f32 buffers, with the bake's view direction.
316    pub(crate) pmi_center_marks_drawn: (Vec<(String, Vec<[[f64; 3]; 2]>)>, [f64; 3]),
317    pub(crate) pmi_hovered: Option<String>,
318    pub(crate) pmi_label_hover_active: bool,
319    /// The sheet the sheet viewport shows (engine memory, never persisted).
320    /// `None` = the 3D view (`sheet_ops.rs`).
321    pub(crate) sheet_open: Option<String>,
322    /// The sheet or placed view whose form the Sheets pane shows. Never assign
323    /// `Some` here: go through [`EngineState::open_sheet_object`], the one
324    /// place that counts the open.
325    pub(crate) sheet_open_object: Option<String>,
326    /// How many times a sheet object's form has been OPENED — the sheet half
327    /// of the same counter as [`Self::pmi_dialog_opens`], read by the
328    /// app's dialog door so a re-open of the object already open still counts.
329    pub(crate) sheet_object_opens: u64,
330    /// The placed view, sheet dimension or ordinate set SELECTED in the Sheets
331    /// tree or on the paper: the tree row's highlight and the object's accent
332    /// on the sheet. Cleared with the selection; read through
333    /// [`EngineState::sheet_selected_object`], which prunes a stale id.
334    pub(crate) sheet_selected_object: Option<String>,
335    /// The last projected sheet, kept until the model or the block moves: a
336    /// sheet is a hidden-line pass over the whole model and must never run
337    /// per frame.
338    pub(crate) sheet_cache: Option<sheet_ops::SheetCache>,
339    /// The sheet's exact passes on the runner and waiting for it.
340    pub(crate) sheet_lines: sheet_ops::SheetLinesWork,
341    /// The open document's name, as the shell means it (the tab, the file, the
342    /// root PRODUCT of a STEP export). Engine memory, never persisted: the
343    /// document does not carry its own name, the SHELL owns it, and it is here
344    /// because a drawing sheet's TITLE BLOCK prints it. Set every frame by the
345    /// app from the active tab (a no-op when unchanged).
346    pub(crate) document_name: String,
347    /// What the spline-anchor cage overlay was last fed for — `(spline id,
348    /// selected anchor, applied run generation)` — so the per-frame refresh
349    /// the history panel makes while an SP form is open is a no-op until one
350    /// of those moves. See `spline_edit.rs`.
351    spline_overlay_key: Option<(String, Option<usize>, u64)>,
352    /// The CAM workbench's generation queue and results (`cam_ops.rs`).
353    pub cam: cam_ops::CamGeneration,
354    /// Whether the ports placed components carry (`ACOMP1:PORT1`) draw their
355    /// sheets. The app sets it from the active workbench — one that shows the
356    /// Wire Harness panel; a document's own PORT features always draw.
357    component_ports_visible: bool,
358    /// The spline whose anchor editor is open (fed by the history panel with
359    /// the cage overlay), so a viewport click on one of its anchor dots selects
360    /// that anchor; the index of the last such pick, until the panel takes it.
361    spline_edit_feature: Option<String>,
362    spline_anchor_picked: Option<usize>,
363    /// The NURBS solid whose control-cage editor is open (fed by the history
364    /// panel with the cage overlay) and what that overlay was last fed for —
365    /// `(feature id, selected points, applied run generation)`. The selection
366    /// itself is the transform gizmo's (`TransformArm::cage`). See
367    /// `cage_edit.rs`.
368    cage_edit_feature: Option<String>,
369    cage_overlay_key: Option<(String, Vec<usize>, u64)>,
370    /// The Deform Face whose pick handles are shown (fed by the history panel)
371    /// and what that overlay was last fed for — `(feature id, armed pick,
372    /// applied run generation)`. See `deform_edit.rs`.
373    deform_edit_feature: Option<String>,
374    deform_overlay_key: Option<(String, Option<usize>, u64)>,
375    /// Construction datum/plane visibility: the frame NAMES whose datum plane is
376    /// HIDDEN (its Scene-tree checkbox off). Absent = visible. Mirrors
377    /// [`hidden_sketches`].
378    hidden_datums: std::collections::HashSet<String>,
379    /// The datum frame NAMES fed to the widget on the LAST
380    /// [`refresh_construction_datums`](Self::refresh_construction_datums). The datum
381    /// feed REPLACES its set wholesale each call, so this is a bookkeeping mirror of
382    /// what is currently shown (parallels [`shown_sketch_ids`]).
383    shown_datum_names: Vec<String>,
384    /// The history-run seam (M2a of the off-thread runner). Owns the scene-free
385    /// runner + its delta baseline (`name → last-emitted handle`) ACROSS reruns:
386    /// [`rerun_history`](Self::rerun_history) SUBMITS a run tagged with
387    /// [`run_generation`](Self::run_generation), and [`pump`](Self::pump) drains
388    /// the completed reply and [`apply_run_output`](Self::apply_run_output)s its
389    /// delta to [`Self::scene`]. The [`InlineRunner`](crate::runner::InlineRunner)
390    /// default runs synchronously (submit → immediate poll, byte-identical to the
391    /// old in-place reconcile); a background thread/worker impl slots in behind the
392    /// same trait in M2b/M3. Reset on a document switch
393    /// ([`set_history_json`](Self::set_history_json)) so a new model rebuilds fully.
394    pub(crate) runner: Box<dyn crate::runner::HistoryRunner>,
395    plugins: plugins::Plugins,
396    /// Monotonic run counter: bumped each time [`rerun_history`](Self::rerun_history)
397    /// SUBMITS a run, and stamped onto the reply so a stale reply (a newer run that
398    /// finished first) can be dropped. `run_generation != applied_generation` means
399    /// a run is in flight (always equal for the synchronous Inline runner).
400    run_generation: u64,
401    /// The generation of the last reply [`pump`](Self::pump) APPLIED — the high-water
402    /// mark that gates stale replies.
403    applied_generation: u64,
404    /// The latest [`crate::runner::RunProgress`] of the run in flight (a
405    /// background runner posts one before each feature it executes), or
406    /// `None` when nothing is running. Names what the spinner is waiting on.
407    run_progress: Option<crate::runner::RunProgress>,
408    /// The feature the last CANCELLED run was executing (`Some("")` when the
409    /// run was cancelled before any progress arrived), cleared by the next
410    /// submit. The history header shows it until the model is rebuilt.
411    cancelled_run: Option<String>,
412    /// Background-runner deaths in a row (see `recover_from_runner_failure`):
413    /// the first is restarted and rebuilt, the next is reported instead. Back
414    /// to 0 when a run lands or the failure has been reported.
415    runner_failures: u32,
416    /// The runner's agent died again after its one restart and was LEFT
417    /// DOWN: no replacement is spawned until the next run is submitted
418    /// (`revive_runner_if_down`), and a failure heard meanwhile is ignored.
419    /// A browser worker that can never start
420    /// (the page's wasm no longer matched the redeployed glue) was respawned by
421    /// the give-up itself, died, was restarted and given up on again, forever.
422    runner_down: bool,
423    /// A TRANSIENT expressions source the runs evaluate instead of the
424    /// document's own (the family table's row preview). Never written into
425    /// the history: not saved, not undone, not dirty. See
426    /// [`Self::set_expression_preview`].
427    expression_preview: Option<ExpressionPreview>,
428    /// How many run replies came back from the runner (applied or dropped as
429    /// stale). A run the runner coalesced away never replies, so this counts
430    /// the runs actually EXECUTED.
431    runs_replied: u64,
432    /// Displays shipped by replies [`pump`](Self::pump) DROPPED as superseded,
433    /// by solid name, latest wins. A background runner executes every run it
434    /// is handed and its delta baseline (`name → last-emitted handle`) advances
435    /// on each, so a later reply can say "unchanged, keep yours" about a
436    /// display that only ever travelled in a dropped reply (the reporter's
437    /// arrow-head drag: the frame that built the new radius was superseded by
438    /// the still-pointer frames that replayed its handle). The keep is served
439    /// from here when the scene's display is not the handle it names. Cleared
440    /// with the runner's baseline (document switch, cancel) and whenever a
441    /// fresh display for the name is applied.
442    superseded_displays: HashMap<String, crate::scene::SolidDisplay>,
443    /// A pending one-shot "frame the scene once the in-flight run lands" request.
444    /// Import / Open SUBMIT an async run (native [`ThreadRunner`], wasm worker) and
445    /// want to `zoom_to_fit` the RESULT — but the scene is still empty when they
446    /// return, so an immediate fit frames nothing (bbox empty → no-op). Instead they
447    /// set this flag and [`pump`](Self::pump) performs the fit on the first apply that
448    /// leaves the run no longer pending. Under the synchronous Inline runner the run
449    /// applies inside the submitting call's own `pump`, so the fit is still immediate.
450    pending_fit: bool,
451    /// The instructions wizard waits for the run that places the wrapper:
452    /// its step views read the solids that run makes. [`pump`](Self::pump)
453    /// runs it once no run is pending.
454    instructions_wizard_pending: bool,
455    /// A re-target folded new steps in: their views wait for the run that
456    /// builds the new revision's solids, like the wizard's.
457    instructions_views_pending: bool,
458    /// The in-app player's insertion motion: the shown step's arrowed parts
459    /// moving home ([`instructions_ops::Insertion`]).
460    pub(crate) instructions_insertion: Option<instructions_ops::Insertion>,
461    /// EAGER provenance `name → creating-feature id` for the current resident
462    /// solids, shipped with each run ([`crate::pipeline::RunOutput::provenance`]) and
463    /// replaced wholesale in [`apply_run_output`](Self::apply_run_output). Answers
464    /// `creating_feature` + the Info tab's `creatingFeature` WITHOUT a cold
465    /// `execute_history` — the freeze side-door once the run lives off-thread.
466    pub(crate) provenance: std::collections::HashMap<String, String>,
467    /// EAGER ENTITY ORIGIN `face/edge NAME → ORIGINATING feature id` (FIRST writer in
468    /// timeline order), shipped with each run
469    /// ([`crate::pipeline::RunOutput::entity_origin`]) and replaced wholesale in
470    /// [`apply_run_output`](Self::apply_run_output). Unlike `provenance` (the SOLID's
471    /// LAST writer) this is the feature that gave the face/edge its NAME — the answer
472    /// `creating_feature` returns for a face/edge (the "Edit owning feature" action +
473    /// the Info tab's `creatingFeature`), so it rolls to the entity's origin, not the
474    /// owning solid's last producer.
475    pub(crate) entity_origin: std::collections::HashMap<String, String>,
476    /// Object-info MEASUREMENT cache `name → merged object-info JSON`, filled by
477    /// [`pump_queries`](crate::metadata) from the runner's replies and served every
478    /// frame a selection persists (so `object_info_json` fires ONE query per
479    /// selection, not one per frame). Invalidated on any geometry change
480    /// (`apply_run_output`) or metadata edit (`set_metadata_attribute`).
481    pub(crate) info_cache: std::collections::HashMap<String, String>,
482    /// In-flight measurement queries `id → object NAME` — the key needed to MERGE a
483    /// reply back into the info cache (inject `name` + `creatingFeature`, the latter
484    /// now resolved by the entity name itself). Cleared alongside `info_cache` on a
485    /// geometry change so a stale reply is dropped rather than caching a superseded
486    /// measurement.
487    pub(crate) pending_query: std::collections::HashMap<u64, String>,
488    /// Monotonic measurement-query id (pairs a [`crate::runner::MeasureReply`] back
489    /// with its `pending_query` entry).
490    pub(crate) next_query_id: u64,
491    /// Off-thread mesh reconstructions awaiting a runner reply.
492    pub(crate) pending_mesh_imports: std::collections::HashMap<u64, MeshImportDestination>,
493    pub(crate) mesh_preview_results: std::collections::VecDeque<crate::runner::MeshImportReply>,
494    /// Phases of preview imports (interactive import), oldest first.
495    pub(crate) mesh_preview_phases: std::collections::VecDeque<crate::runner::MeshImportPhaseReply>,
496    /// Completed region refits, oldest first.
497    pub(crate) region_fit_results: std::collections::VecDeque<crate::runner::RegionFitReply>,
498    pub(crate) apply_choices_results: std::collections::VecDeque<crate::runner::ApplyRegionChoicesReply>,
499    /// Monotonic id for pairing mesh import replies with submissions.
500    pub(crate) next_mesh_import_id: u64,
501    /// Topology requests in flight (see [`crate::runner::TopologyRequest`]).
502    pub(crate) pending_topology: std::collections::HashSet<u64>,
503    /// Every resident handle asked for since the last applied run, answered or
504    /// not: a handle the runner could not clone is not asked for again until a
505    /// run brings new handles.
506    pub(crate) topology_asked: std::collections::HashSet<u32>,
507    /// Monotonic id for pairing topology replies with requests.
508    pub(crate) next_topology_id: u64,
509    /// The run's ASSEMBLY tail as the runner read it
510    /// ([`crate::pipeline::AssemblySync`]) — the constraint state, statuses, DOF
511    /// and overlay rows every assembly panel reads, adopted from the reply of the
512    /// last applied run. `None` for a componentless document. This is what
513    /// replaced the second, main-side `execute_history`: see `assembly_ops`.
514    pub(crate) assembly_sync: Option<crate::pipeline::AssemblySync>,
515    /// The scene's assembly COMPONENT records (deterministic id order), adopted
516    /// from [`Self::assembly_sync`] — the Assembly Structure tree's source.
517    /// Empty for componentless documents.
518    pub(crate) assembly_components: Vec<crate::pipeline::ComponentSnapshot>,
519    /// The [`Self::applied_generation`] the main-side kernel assembly SESSION was
520    /// last installed for (`None` = never). Only a constraint MUTATION needs one
521    /// — its solve runs against the resident geometry of the thread that asks —
522    /// so only `ensure_assembly_session` sets this. See `assembly_ops`.
523    pub(crate) assembly_session_generation: Option<u64>,
524    /// The kernel's session serial when this document's session was put in
525    /// place: the kernel session is one per thread, shared by every open
526    /// document, so a moved serial means another one replaced it.
527    pub(crate) assembly_session_serial: u64,
528    /// Take the runner's session copy instead of replaying (tests switch it
529    /// off to compare the two lanes), and how often each lane served.
530    pub(crate) session_transfer: bool,
531    pub(crate) session_imports: u64,
532    pub(crate) session_replays: u64,
533    /// This document has needed its main-side session: from then on every
534    /// applied run asks a background runner for a copy of the new session up
535    /// front, so the next mate action finds it in place. Sticky — a document
536    /// only viewed never pays for the copy (the watch's is ~21 MB of JSON).
537    pub(crate) session_wanted: bool,
538    /// The generation a session copy was last asked for (not answered yet).
539    pub(crate) session_requested: Option<u64>,
540    /// The generation the pump last asked for a copy up front: once per run
541    /// that lands, never again for the same one (two open assemblies share
542    /// this thread's one session; re-asking whenever it is not ours would make
543    /// them take it from each other on every pump).
544    pub(crate) session_prefetched: Option<u64>,
545    /// Reruns made because the runner no longer held the applied run's
546    /// session (it answered `None`); reset by an import. One is enough: the
547    /// rerun installs a session there (a cache hit), whose copy is asked for.
548    pub(crate) session_recoveries: u32,
549    /// The next run is a document's first on a background runner: it shows
550    /// parts made by another kernel build from their stored snapshots, and a
551    /// second run rebuilds them (`HistoryRequest::defer_stale_parts`).
552    pub(crate) defer_stale_next: bool,
553    /// The parts the last applied run showed from a stale snapshot, being
554    /// rebuilt by the run in flight (empty when none).
555    pub(crate) stale_parts: Vec<String>,
556    /// Set by the run that just applied when it showed stale parts; the pump
557    /// takes it and submits the run that rebuilds them.
558    pub(crate) stale_parts_shown: Option<Vec<String>>,
559    /// A component replace whose run has not landed yet (see
560    /// `replace_component`), and the last finished replace's report.
561    pub(crate) replace_pending: Option<replace_component::PendingReplace>,
562    pub(crate) last_replace_report: Option<serde_json::Value>,
563    /// Every output name the last applied run CONSUMED
564    /// ([`crate::pipeline::RunOutput::consumed`]) — what the committed-sketch
565    /// refresh hides a consumed sketch by, and what it used to re-execute the
566    /// whole history on the UI thread to learn.
567    pub(crate) consumed_names: std::collections::HashSet<String>,
568    /// Re-entrancy guard for the parts-library resync in [`Self::pump`] (a
569    /// refused run re-runs, and `rerun_history` pumps).
570    pub(crate) library_resync: bool,
571    /// A run just RELEASED a sketch's edge links whose edges it could not
572    /// resolve (see [`Self::release_unresolved_sketch_links`]): the history
573    /// changed under the applied report, so [`Self::pump`] re-runs it once and
574    /// the report stops naming edges the sketch no longer lists.
575    pub(crate) sketch_links_released: bool,
576    /// The assembly-constraint viewport overlays — the cached
577    /// [`crate::constraint_overlays::ConstraintOverlay`] records the engine last
578    /// built from the kernel session (`assembly_overlay_json` + state), the source
579    /// of the drawn leader/arrow group, the label feed, and the grabbable-handle
580    /// hit regions. Refreshed after every history apply and every constraint
581    /// mutation; see the appended assembly-overlay impl block.
582    pub(crate) constraint_overlays: Vec<crate::constraint_overlays::ConstraintOverlay>,
583    /// A live GRAB on a constraint's distance-arrow / angle-arc handle (`Some`
584    /// between `constraint_drag_begin` and `constraint_drag_release`): the drag
585    /// previews the value locally and COMMITS on release via
586    /// `assembly_update_constraint_json` (which auto-solves).
587    pub(crate) constraint_drag: Option<ConstraintDrag>,
588    /// The `world_per_pixel` the constraint overlay buffers were last baked at
589    /// (screen-constant arc/rod sizing): `ensure_constraint_overlay_current`
590    /// re-bakes when the camera zoom moves it materially. `0.0` = never baked.
591    constraint_overlay_wpp: f64,
592    /// What the free-motion glyph group was last baked from (component,
593    /// its freedom row, centre), and at which `world_per_pixel`.
594    freedom_glyph_key: Option<String>,
595    freedom_glyph_wpp: f64,
596    /// The `world_per_pixel` the FEATURE-DIMENSION gizmo group
597    /// (`feature-dim-leaders`) was last baked at. The leaders' rod/cone/origin
598    /// sphere — and the angular arc's whole world RADIUS — are
599    /// `pixels × world_per_pixel`, so a zoom makes the drawn gizmo stale;
600    /// `ensure_feature_dimension_overlay_current` re-bakes on a material move.
601    /// `0.0` = nothing baked (gizmo disarmed / not in dimension mode).
602    /// See `feature_dims`.
603    pub(crate) feature_dim_overlay_wpp: f64,
604    /// The `world_per_pixel` the live SKETCH overlay groups (geometry, points,
605    /// preview, `sketch-dim-leaders`, `sketch-constraint-glyphs`) were last baked
606    /// at — construction dashes, dimension arrowheads and constraint glyphs are
607    /// all screen-constant. `ensure_sketch_overlay_current` re-bakes on a material
608    /// zoom. `0.0` = nothing baked (not in sketch mode). See `sketch_input`.
609    pub(crate) sketch_overlay_wpp: f64,
610    /// The constraint id whose referenced ELEMENTS the panel/label hover is
611    /// currently highlighting (dedupe key so a held hover doesn't re-bump the
612    /// emphasis generation every frame).
613    constraint_hovered: Option<String>,
614    /// Set for ONE frame when a constraint LABEL hover applied the element
615    /// highlight; the viewport's modeling hover branch consumes it (mirrors
616    /// [`Self::take_sketch_list_hover`]) so the scene hover doesn't clobber it.
617    constraint_label_hover_active: bool,
618    /// The SCENE-TREE row the pointer is over, as the pick candidate its hover
619    /// lit (the row→viewport highlight). Kept so
620    /// [`scene_tree_hover_end`](Self::scene_tree_hover_end) clears ONLY a hover
621    /// the tree itself set — never one the viewport lit in the meantime — and as
622    /// the dedupe key that keeps a held row hover from re-bumping the emphasis
623    /// generation every frame. See `scene_query.rs`.
624    scene_tree_hovered: Option<pick::PickCandidate>,
625    /// Set for ONE frame while a Scene-tree row is hovered; the viewport's
626    /// modeling hover branch consumes it via
627    /// [`take_scene_tree_hover`](Self::take_scene_tree_hover) and skips the
628    /// pointer-off-viewport `clear_hover` (mirrors
629    /// [`Self::take_sketch_list_hover`]) so the row-set highlight survives.
630    scene_tree_hover_active: bool,
631    /// The DIALOG row the pointer is over — a feature form's reference line, its
632    /// read-only `Outputs` line, or the reference picker card's picked-name line
633    /// (the row→viewport highlight, the twin of the Scene tree's above). Its OWN
634    /// slot, not the tree's: History, Constraints, PMI and the Scene tree can all
635    /// be on screen at once in a split dock, and a shared slot would let the pane
636    /// that draws second end the hover the pane that drew first had just set. See
637    /// [`DialogHover`] for what it memoizes and `scene_query.rs` for the API.
638    dialog_hovered: Option<DialogHover>,
639    /// Set for ONE frame while a dialog row is hovered; the viewport's modeling
640    /// hover branch consumes it via [`take_dialog_hover`](Self::take_dialog_hover)
641    /// and skips the pointer-off-viewport `clear_hover` (mirrors
642    /// [`Self::take_scene_tree_hover`]) so the row-set highlight survives.
643    dialog_hover_active: bool,
644    /// The constraint SELECTED via its viewport label chip (`Some` = selected):
645    /// drives the chip's selected accent, the context bar's Delete-constraint
646    /// action, and clears with the selection (Esc / Clear / delete). Read
647    /// through [`Self::selected_constraint`], which prunes a stale id.
648    selected_constraint: Option<String>,
649    /// The feature SELECTED in the history tree, beside the geometry selection
650    /// that selecting it made. It stays selected only while that geometry
651    /// selection is unchanged — a viewport pick, Esc or Clear replaces the
652    /// geometry and so deselects the feature. Read through
653    /// [`Self::selected_feature`].
654    selected_feature: Option<(String, selection_ux::FeatureSelection)>,
655    /// How many times a constraint's dialog has been OPENED through
656    /// [`Self::assembly_set_constraint_open`] — the constraint half of the same
657    /// counter as [`Self::pmi_dialog_opens`], read by the app's dialog door
658    /// so a re-open of the constraint already open still counts. The flag
659    /// itself lives in the kernel (it is part of the saved document), so this
660    /// counts the OPENS this engine performed, not the flag's history.
661    pub(crate) constraint_opens: u64,
662    /// The STEP product structure a [`Self::probe_step_assembly`] parsed, held
663    /// until the import dialog's button decides its fate: consumed by
664    /// [`Self::import_probed_step_assembly`], dropped by
665    /// [`Self::discard_probed_step_assembly`] (Cancel), by the next probe, or by
666    /// a document switch. The ONE parse of a structured STEP import lives here —
667    /// the dialog needs the counts BEFORE the user chooses, and re-parsing
668    /// multi-MB Part-21 text on the way back would double the most expensive step
669    /// of the import. See `model_io`'s import block.
670    pub(crate) pending_step_assembly: Option<brep_kernel::StepAssembly>,
671    /// STEP probes submitted to the runner and not yet answered (their ids).
672    pub(crate) pending_step_probes: std::collections::HashSet<u64>,
673    /// Answered probes awaiting [`Self::take_step_probe`], oldest first.
674    pub(crate) step_probe_results: std::collections::VecDeque<(u64, StepProbeOutcome)>,
675    /// Monotonic id pairing a probe reply with its submission.
676    pub(crate) next_step_probe_id: u64,
677}
678
679/// What a STEP probe found, as the file panel consumes it (see
680/// [`EngineState::submit_step_probe`]).
681#[derive(Debug, Clone, PartialEq)]
682pub enum StepProbeOutcome {
683    /// Product structure: the parsed assembly is stashed for
684    /// [`EngineState::import_probed_step_assembly`]; these are its counts.
685    Structure(model_io::StepAssemblyProbe),
686    /// Product structure DECLARED, from an outline read
687    /// ([`EngineState::submit_step_outline`]): the counts the file promises,
688    /// with nothing built and nothing stashed. Importing it as an assembly
689    /// still takes the full read ([`EngineState::submit_step_probe`]).
690    Outline(model_io::StepAssemblyProbe),
691    /// No structure worth keeping — take the flat lane.
692    Flat,
693    /// The text did not parse as Part 21; the flat lane refuses it with its
694    /// own wording.
695    Failed(String),
696}
697
698/// A live constraint-handle drag: which constraint + which `inputParams` field
699/// (`distance` / `angle`), the params snapshot the commit mutates, and the live
700/// preview value the overlay/label show while dragging.
701#[derive(Debug, Clone)]
702pub struct ConstraintDrag {
703    pub id: String,
704    pub field: &'static str,
705    pub params: serde_json::Value,
706    pub preview: f64,
707}
708
709/// WHO a finished reference-selection commits to: a history FEATURE's params
710/// (the original widget) or an ASSEMBLY CONSTRAINT's `inputParams` (same modal,
711/// different commit lane — see `assembly_ops::begin_ref_select_for_constraint`).
712#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
713pub enum RefSelectTarget {
714    #[default]
715    Feature,
716    AssemblyConstraint,
717    /// ONE SPLINE ANCHOR's port attachment: `path` is unused, the picked name
718    /// must be a PORT feature id (a click on a port's drawn sheet), and Finish
719    /// writes `persistentData.spline.points[index].attachment` (see
720    /// `spline_edit.rs`).
721    SplineAnchor { index: usize },
722    /// A PMI annotation's reference field: `feature_id` is the annotation id;
723    /// Finish writes the picked names into its params through the PMI block
724    /// (`pmi_ops.rs`). Vertex picks are `{solid}@x,y,z` in WORLD coordinates.
725    Pmi,
726    /// ONE CONNECTION POINT's reference field: `feature_id` is the point's
727    /// part-local ADDRESS (`J1.VCC`) — a connection point is data, not a
728    /// feature, so there is no id to carry — and `path` is the block key the
729    /// pick writes (`pointRef` / `directionRef`). Finish writes it through
730    /// `ports_ops::ports_commit_ref`, and NOTHING ROLLS: a point resolves at
731    /// the tail of the run, so the geometry it may name is what is on screen.
732    PortPoint { field: ports_ops::PortRefField },
733    /// A MOUNT FRAME helper's one pick (`mount_ops`): `feature_id` and `path`
734    /// are the block key. Finish resolves the pick against the scene on
735    /// screen and writes the mount it asks for, composed onto the current
736    /// one, as one undo step; nothing rolls.
737    Mount { pick: mount_ops::MountPick },
738    /// A drawing-sheet object's reference field — a dimension's anchors, an
739    /// ordinate set's datum or members, a section's cutting line, a detail's
740    /// centre or rim: `feature_id` is the object id, the picks are ANCHORS
741    /// clicked on the open sheet's paper (`sheet_ops.rs`), and nothing rolls.
742    Sheet,
743    /// A CAM record's reference field (a setup's orientation picks and
744    /// bodies, an operation's targets): `feature_id` is the record id and
745    /// `path` addresses the field from the `cam` block's ROOT, a `#<id>`
746    /// segment selecting the array element with that id
747    /// (`["setups", "#SETUP1", "targets"]`). Finish writes it through
748    /// `cam_ops::cam_commit_refs`, and nothing rolls: CAM references name the
749    /// finished model, which is what is on screen.
750    Cam,
751    /// A manufacturing-instructions step's OCCURRENCE field — an insertion
752    /// arrow's part or a callout's: `feature_id` is the step id and `field`
753    /// says which row. The pick is a SOLID of the placed assembly; Finish
754    /// derives the occurrence (the solid's name without its member) and writes
755    /// it through `instructions_ops::instructions_commit_ref`, one undo step,
756    /// and nothing rolls.
757    Instructions { field: InstructionsRefField },
758    /// A motion-study CLIP's parts field: `feature_id` is the clip id and
759    /// `path` its list field (`["occurrences"]`). Finish writes the picked
760    /// names, as the components that hold them, through
761    /// `simulation_refs::simulation_commit_refs`; nothing rolls.
762    Simulation,
763    /// A REPLACE COMPONENT repair: a held mate's broken reference, re-aimed
764    /// at ONE face or edge picked in the view. `feature_id` is the mate id
765    /// and `path` is `[old reference]`. Finish commits nothing itself: it
766    /// hands `(mate, old ref, pick)` to the replace dialog
767    /// ([`EngineState::take_replace_repair_pick`]), whose repair also
768    /// reaches mates inside nested assemblies; nothing rolls.
769    ReplaceRepair,
770    /// A feature's VEC3 field filled from ONE picked vertex, edge or face
771    /// (Transform Face's `pivot`): `path` is the pick BUTTON's own path, the
772    /// field's key with [`POINT_PICK_SUFFIX`] appended (`["pivot#pick"]`), so
773    /// the form draws that button as the focused one. Finish resolves the pick
774    /// to a point against the scene the feature runs against
775    /// (`brep_kernel::face_transform_reference_point`) and writes it at the
776    /// field's own path as three numbers; nothing is written when nothing was
777    /// picked or the pick does not resolve.
778    PointPick,
779    /// The DRAFT ANALYSIS window's pull field: Finish hands the one pick to
780    /// [`EngineState::draft_analysis_set`]. Display state only: nothing is
781    /// written to the document and nothing rolls.
782    DraftAnalysis,
783}
784
785/// The suffix a vec3 field's PICK button carries on its key (`pivot#pick`),
786/// the `key#id` form every published hit key with a sub-control uses.
787pub const POINT_PICK_SUFFIX: &str = "#pick";
788
789/// Which occurrence field of a step a pick fills ([`RefSelectTarget::Instructions`]).
790#[derive(Debug, Clone, Copy, PartialEq, Eq)]
791pub enum InstructionsRefField {
792    /// The part insertion arrow `index` animates (one of the step's own adds).
793    Arrow(usize),
794    /// The part callout `index` points at (any part of the assembly).
795    Callout(usize),
796}
797
798/// The modal state of the reference-selection widget while it is ACTIVE: which
799/// feature-dialog field is being filled, what it accepts, and the running list
800/// of picked kernel names (the source of truth — added by picking in the view,
801/// removed via the per-line X). See the ref-select methods below.
802#[derive(Debug, Clone, Default)]
803pub struct RefSelectState {
804    /// The id of the feature whose param is being edited.
805    pub feature_id: String,
806    /// The JSON path into that feature's `inputParams` the names write to
807    /// (`["targetSolid"]`, `["boolean","targets"]`, `["faceRef"]`, …).
808    pub path: Vec<String>,
809    /// A human label for the modal heading (the field's label).
810    pub label: String,
811    /// The allowed pick kinds (`["SOLID"]`, `["FACE"]`, …) — the type constraint.
812    pub filter: Vec<String>,
813    /// Whether the field takes a LIST of references (else a single one).
814    pub multiple: bool,
815    /// The picked kernel names — the running selection (source of truth).
816    pub names: Vec<String>,
817    /// The rollback step to restore on Finish/Cancel (the edited feature's own
818    /// step): entering the mode rolls to the pre-feature "before" state, so we
819    /// remember where to return.
820    pub restore_index: usize,
821    /// Which surface Finish commits the names to (feature params vs an
822    /// assembly constraint's `inputParams`). Defaults to [`RefSelectTarget::Feature`].
823    pub target: RefSelectTarget,
824    /// How many picks landed since the field was activated (a viewport click,
825    /// a fed name, a sheet anchor). A SINGLE-valued field drawn IN ITS FORM
826    /// finishes on its first pick — the form's consumer has nothing to wait
827    /// for once the one reference is in — and this is what says one landed,
828    /// as opposed to the seed the field opened with.
829    pub picks: usize,
830    /// Whether the field's own form drew the pick this frame. An in-form pick
831    /// has no card of its own, so a form that stops being drawn (its pane
832    /// tabbed away or closed, its subject gone) would strand the pick with
833    /// nothing on screen to end it; the shell finishes a pick nobody claimed.
834    pub claimed: bool,
835    /// The form asked for the pick to finish at the END of this frame rather
836    /// than now: an edit elsewhere on a feature's form while its pick runs.
837    /// Deferred because the viewport pane may draw AFTER the form in the same
838    /// frame and the click that caused the edit (a text field losing focus)
839    /// may itself be the pick — finishing at once would hand that click to
840    /// the ordinary selection instead.
841    pub finish_requested: bool,
842}
843
844impl Default for EngineState {
845    fn default() -> Self {
846        Self {
847            scene: RenderScene::new(),
848            context_scene: RenderScene::new(),
849            context_selected: None,
850            context_hovered: None,
851            context_pick_lit: Vec::new(),
852            context_display: Default::default(),
853            camera: ViewCamera::default(),
854            controls: ArcballControls::new(),
855            settings: RenderSettings::default(),
856            emphasis: Emphasis::default(),
857            widgets: WidgetRegistry::new(),
858            history: History::default(),
859            history_report: String::new(),
860            metadata: crate::metadata::MetadataStore::new(),
861            component_namespace: std::cell::RefCell::new(None),
862            document_thumbnail: std::cell::RefCell::new(None),
863            thumbnail_cache: std::cell::RefCell::new(None),
864            settings_generation: 1,
865            dirty: true,
866            ref_select: None,
867            replace_repair_pick: None,
868            selection_filter: SelectionFilter::default(),
869            filter_override: None,
870            transform_gizmo: TransformArm::default(),
871            component_move: ComponentMoveArm::default(),
872            sketch_edit: None,
873            sketch3d_edit: None,
874            sketch3d_overlay_wpp: 0.0,
875            sketch_camera_locked: true,
876            sketch_list_hover_active: false,
877            notices: Vec::new(),
878            graded_notices: Vec::new(),
879            hidden_sketches: std::collections::HashSet::new(),
880            shown_sketch_ids: Vec::new(),
881            shown_board_ids: Vec::new(),
882            board_built_from: None,
883            board_pin_nets: Default::default(),
884            board_build: board_geometry::BoardBuild::default(),
885            board_displays: Vec::new(),
886            construction_frames: Vec::new(),
887            draft_analysis: None,
888            sketch_profiles: Vec::new(),
889            sketch_paths: Vec::new(),
890            sketch_points: Vec::new(),
891            sketch_axes: Vec::new(),
892            wire_harness_report: None,
893            ports_report: None,
894            sheet_open: None,
895            sheet_open_object: None,
896            sheet_object_opens: 0,
897            sheet_selected_object: None,
898            sheet_cache: None,
899            sheet_lines: Default::default(),
900            document_name: String::new(),
901            pmi_report: None,
902            pmi_active_view: None,
903            pmi_open_annotation: None,
904            pmi_open_view: None,
905            pmi_selected_annotation: None,
906            pmi_selected_view: None,
907            pmi_dialog_opens: 0,
908            pmi_modeling: None,
909            pmi_explode_originals: std::collections::HashMap::new(),
910            explode_playback: Default::default(),
911            simulation_play: None,
912            pmi_section_hidden: Vec::new(),
913            pmi_unposed_visibility: 0,
914            pmi_state_cache: Default::default(),
915            pmi_balloon_stale: None,
916            pmi_overlay_key: None,
917            pmi_center_marks_drawn: Default::default(),
918            pmi_hovered: None,
919            pmi_label_hover_active: false,
920            spline_overlay_key: None,
921            cam: cam_ops::CamGeneration::default(),
922            component_ports_visible: false,
923            spline_edit_feature: None,
924            spline_anchor_picked: None,
925            cage_edit_feature: None,
926            cage_overlay_key: None,
927            deform_edit_feature: None,
928            deform_overlay_key: None,
929            hidden_datums: std::collections::HashSet::new(),
930            shown_datum_names: Vec::new(),
931            runner: Box::new(crate::runner::InlineRunner::new()),
932            plugins: plugins::Plugins::default(),
933            interference_sessions: Default::default(),
934            interference_sequence: 0,
935            illustration_snapshot: None,
936            geometry_diagnostics: Default::default(),
937            staged_feature: None,
938            batch_job: None,
939            busy_refused_seen: 0,
940            run_generation: 0,
941            applied_generation: 0,
942            run_progress: None,
943            cancelled_run: None,
944            runner_failures: 0,
945            runner_down: false,
946            expression_preview: None,
947            runs_replied: 0,
948            superseded_displays: HashMap::new(),
949            pending_fit: false,
950            instructions_wizard_pending: false,
951            instructions_views_pending: false,
952            instructions_insertion: None,
953            provenance: std::collections::HashMap::new(),
954            entity_origin: std::collections::HashMap::new(),
955            info_cache: std::collections::HashMap::new(),
956            pending_query: std::collections::HashMap::new(),
957            next_query_id: 0,
958            pending_mesh_imports: std::collections::HashMap::new(),
959            mesh_preview_results: std::collections::VecDeque::new(),
960            mesh_preview_phases: std::collections::VecDeque::new(),
961            region_fit_results: std::collections::VecDeque::new(),
962            apply_choices_results: std::collections::VecDeque::new(),
963            next_mesh_import_id: 0,
964            pending_topology: std::collections::HashSet::new(),
965            topology_asked: std::collections::HashSet::new(),
966            next_topology_id: 0,
967            assembly_components: Vec::new(),
968            assembly_sync: None,
969            assembly_session_generation: None,
970            assembly_session_serial: 0,
971            session_transfer: true,
972            session_imports: 0,
973            session_replays: 0,
974            session_wanted: false,
975            session_requested: None,
976            session_prefetched: None,
977            session_recoveries: 0,
978            defer_stale_next: false,
979            stale_parts: Vec::new(),
980            stale_parts_shown: None,
981            replace_pending: None,
982            last_replace_report: None,
983            consumed_names: std::collections::HashSet::new(),
984            library_resync: false,
985            sketch_links_released: false,
986            constraint_overlays: Vec::new(),
987            constraint_drag: None,
988            constraint_overlay_wpp: 0.0,
989            freedom_glyph_key: None,
990            freedom_glyph_wpp: 0.0,
991            feature_dim_overlay_wpp: 0.0,
992            sketch_overlay_wpp: 0.0,
993            constraint_hovered: None,
994            constraint_label_hover_active: false,
995            scene_tree_hovered: None,
996            scene_tree_hover_active: false,
997            dialog_hovered: None,
998            dialog_hover_active: false,
999            selected_constraint: None,
1000            selected_feature: None,
1001            constraint_opens: 0,
1002            pending_step_assembly: None,
1003            pending_step_probes: std::collections::HashSet::new(),
1004            step_probe_results: std::collections::VecDeque::new(),
1005            next_step_probe_id: 1,
1006        }
1007    }
1008}
1009
1010impl EngineState {
1011    pub fn new() -> Self {
1012        Self::default()
1013    }
1014
1015    fn pick_options(&self) -> PickOptions {
1016        PickOptions {
1017            double_sided: self.settings.pick_double_sided,
1018            ..PickOptions::default()
1019        }
1020    }
1021}
1022
1023/// Has the camera's `world_per_pixel` moved MATERIALLY (>0.5%) away from the
1024/// value an overlay group's screen-constant sizing was baked at?
1025///
1026/// The ONE judgement every camera-keyed overlay re-bake shares
1027/// (`ensure_overlays_current` and the per-group ensures it drives), so
1028/// "what counts as a zoom" cannot drift between them. `baked == 0.0` means
1029/// "never baked" — a state each caller handles itself, so it reads as NOT
1030/// stale here. The band is what keeps a quiet frame quiet: float jitter in the
1031/// camera never trips it, so there is no per-frame re-bake loop.
1032pub(crate) fn overlay_wpp_stale(baked: f64, now: f64) -> bool {
1033    baked > 0.0 && (now - baked).abs() > baked * 0.005
1034}
1035
1036// ============================================================================
1037// MODULE MAP — engine_state is split into topic children. THIS file is the
1038// module root: it keeps the EngineState/RefSelectState structs, Default, the
1039// constructor + shared pick_options, the child `mod` declarations, and the
1040// re-exports that preserve the original `engine_state::*` public paths.
1041// Append new work to the matching child (or add a new child + re-export here).
1042// ============================================================================
1043
1044/// The assembly surface (Wave-3): main-side session sync + component
1045/// projection, constraint CRUD with the document fold (pose-authority
1046/// contract), the insert-component flow, component fix/select actions, the
1047/// constraint flavor of the reference picker, and `document_signature` — the
1048/// ONE parts-library `sourceSignature` hash every writer shares.
1049mod assembly_ops;
1050pub use assembly_ops::ASSEMBLY_SESSION_PENDING;
1051mod context_pick;
1052/// Assembly-constraint viewport overlays: overlay refresh from
1053/// the kernel session, the grabbable distance/angle handle pick + drag preview +
1054/// `assembly_update_constraint_json` commit, movedSolids re-tessellation, the
1055/// drag-path document fold, label feed + element hover, and tests.
1056mod assembly_overlay;
1057/// Replace component (swap an occurrence's part, keep its mates by name when
1058/// the parts share lineage; mark the rest unresolved) — `replace_components`,
1059/// the report, repair, and the Save As lineage stamp.
1060pub mod replace_component;
1061/// BOM export: the `{partName, sourceKey,
1062/// quantity}` parts list off the main-side parts library + live component
1063/// projection, serialized as CSV / JSON for the file dialog's Export modal.
1064mod bom;
1065/// Mass properties of a part: computed from its geometry and the density the
1066/// PART carries (never per occurrence), and the load-time migration of old
1067/// occurrence-stored Mass/Material onto the part.
1068pub mod part_mass;
1069/// Camera & view commands (zoom-to-fit, resize, pointer/wheel ingestion,
1070/// projection, standard views, camera state/matrices, world→screen) plus the
1071/// widget-overlay feeds (datums/overlay/dimensions/transform JSON), the
1072/// ViewCube (incl. `apply_look_direction`), `datum_pick`, the widget
1073/// transform-handle hover/pick/drag path, and `dimension_anchors_json`.
1074mod camera_widgets;
1075/// Committed-sketch persistent overlays: sheet-solid synthesis from stored
1076/// profiles (`refresh_committed_sketches`), per-sketch visibility, the
1077/// Scene-tree rows + `sketch_entities_json`, and the committed-sketch tests.
1078/// The board's 3D bodies (substrate + copper + via barrels), derived from the
1079/// document's `pcb` block after every run — see the module notes.
1080mod board_geometry;
1081mod committed_sketches;
1082/// The COMPONENT Move gizmo (assemblies §8.5): translate→rotate→off cycle at
1083/// the member-bbox center, fixed-refusal, free-move drag with the pose commit
1084/// (and re-solve) on release. See `ComponentMoveArm`.
1085mod component_move;
1086/// Flip a constraint to its other solution (one undo step, a seeded pose).
1087mod assembly_flip;
1088/// Assembly COMPONENT read surface: the app-side component projection derived
1089/// from the history's ACOMP features + the scene's namespaced solid names
1090/// (`component_of_solid` / `component_info` / `component_bbox_center`), and its
1091/// tests + shared assembly fixtures.
1092mod components;
1093/// Construction datum/plane display: frame→feature mapping,
1094/// `refresh_construction_datums`, datum visibility + selection + entity rows,
1095/// and the construction-datum tests.
1096mod construction_datums;
1097/// Expressions & configurator surface (`expressions_json`, `set_expressions`,
1098/// `configurator_json`, `expression_variables_json`) + parsing helpers + tests.
1099mod expressions;
1100pub use expressions::ExpressionPreview;
1101/// The feature-dimension gizmo (dimension arrows / angle arc / center-sphere
1102/// toggle): arm state, `__brep`-style annotation JSON, overlay publishing,
1103/// drag + set-value writeback, `FEATURE_DIM_OVERLAY`, fd_* math helpers, tests.
1104mod feature_dims;
1105/// The Draft Analysis view: faces tinted by their draft against a pull.
1106mod draft_analysis_ops;
1107/// The assembly interference check: the bbox-prefiltered
1108/// pairwise non-destructive INTERSECT sweep over component instances
1109/// (`interference_check`), its report types, and the pure pair planner.
1110mod interference;
1111mod batch;
1112mod plugins;
1113mod illustration;
1114/// History runs & the feature CRUD surface: `run_history_json`, the
1115/// runner/pump/apply seam, history JSON accessors, roll/update/add/delete/
1116/// reorder, engine undo/redo, `load_model_and_fit`,
1117/// and the history-cache rollback tests.
1118mod history_ops;
1119// Rename a feature/solid/sketch/datum and every name built from it.
1120pub mod rename_ops;
1121/// Model I/O: `import_step_feature`, `export_step_text`, `export_stl_text`,
1122/// `triangle_normal`, and the io tests.
1123mod model_io;
1124/// Construction PLANES as ordinary pick candidates: the combined
1125/// scene+plane-card candidate list (`pick_candidates_at`), the planes-aware
1126/// single-hit pick (`pick_top_at`), the shared candidate ordering, and the
1127/// plane-pick tests. Read its header for how a plane competes for a pick.
1128mod plane_pick;
1129mod box_select;
1130pub use box_select::BoxSelectMode;
1131/// Scene & object queries: `pick_json`/`hover_json`, settings + emphasis +
1132/// visibility + color overrides, `scene_listing_json`, `depth_range_bbox`,
1133/// `scene_entities_json`/select-by-name, mass properties + object info, tests.
1134mod scene_query;
1135/// The selection-filter state + kind gating (`SelectionFilter`,
1136/// `select_filtered_at`, hide-selected) and its tests.
1137mod selection_filter;
1138/// Selection & hover UX: clear/select-top/selection JSON, the modal
1139/// ref-select widget (incl. `set_json_at`), hover/candidate cycling, and the
1140/// live sketch overlay feed (`set_sketch_overlay`/`clear_sketch_overlay`) +
1141/// selection UX tests.
1142mod selection_ux;
1143/// Sketch editing ops appended after dimensions: dimension labels/value/drag,
1144/// sketch undo/redo + diagnostics dump, trim, external edge refs
1145/// (pick/link/reproject), and hand-draw strokes.
1146mod sketch_edit_ops;
1147/// Sketch-mode viewport input: overlay refresh, uv picking, hover/click/drag,
1148/// the draw tools + pending-geometry helpers, and delete-selection.
1149mod sketch_input;
1150/// Sketch mode session: `SketchDrag`/`SketchEdit` state, plane-frame helpers,
1151/// enter/exit/new sketch, and the camera lock.
1152mod sketch_mode;
1153/// 3D sketch mode: `Sketch3dEdit`, enter/exit/new, the cursor-to-3D mapping,
1154/// the draw tools, reference linking, constraint edits and undo.
1155mod sketch3d_mode;
1156pub use sketch3d_mode::{Sketch3dCursorHit, Sketch3dEdit};
1157/// Sketch entity-list panel rows + notices + solver settings
1158/// (`SketchEntityRow`), and the constraint palette/actions
1159/// (`SketchConstraintAction`, add-constraint builders, ground/construction
1160/// toggles, cleanup).
1161mod sketch_panel;
1162/// The transform-controls gizmo: `GizmoMode`/`TransformArm`, arm/drag/apply,
1163/// pose ⇄ params JSON, quaternion helpers (`rotate_euler_xyz_f64`), tests.
1164mod transform_gizmo;
1165/// The wire-harness surface: the document's `wireHarness` block (connection
1166/// add / edit / remove / bundles toggle — checkpointed document edits that
1167/// re-run the history, whose tail routes them), the applied run's routing
1168/// report, the endpoint list, and the panel's hover highlight.
1169mod wire_harness_ops;
1170/// The PORTS surface: the ports tail's report of the last applied run — the
1171/// one place the tail's resolved points, refused names and unresolved
1172/// references reach a caller, the tail not being a feature.
1173mod ports_ops;
1174pub use ports_ops::PortRefField;
1175/// A part's mount frame set from a pick: origin to a point, seat on a face.
1176mod mount_ops;
1177pub use mount_ops::MountPick;
1178pub use selection_ux::RefSelectField;
1179// Every harness wire as a BOM line with its cut length (MF QTY), or the reason
1180// the last applied run cannot give one.
1181mod wire_bom;
1182mod pmi_ops;
1183mod pmi_section;
1184// Assembly exploded views: PMI views whose explode rows are ordered steps.
1185mod exploded_ops;
1186pub use exploded_ops::{ExplodePlayback, ExplodeStep, ExplodedView};
1187// Manufacturing instructions: the wrapper assembly, the wizard, step views and the player.
1188mod instructions_ops;
1189pub use instructions_ops::{Insertion, PlayTo};
1190// Motion studies: the simulation block, motors and clips.
1191mod simulation_ops;
1192pub use simulation_ops::MotorMate;
1193// Motion-study playback: bake the frames through the kernel, pose the displays.
1194mod simulation_play;
1195pub use simulation_play::{BakedFrame, SimulationPlayback};
1196// Motion-study player data: the study's frames for the instructions player
1197// template (the offline .html, and what the PLM serves).
1198mod simulation_player;
1199pub use simulation_player::assembly_signature;
1200// A clip's parts picked in the viewport: the reference-selection lane of
1201// the Simulation pane's forms.
1202mod simulation_refs;
1203// A study's published motion on a manufacturing-instructions step.
1204mod instructions_motion;
1205pub use instructions_motion::PublishedMotion;
1206// Their printed PDF, per-step PNG and SVG, and the print settings.
1207mod instructions_export;
1208pub use instructions_export::IMAGE_PX as INSTRUCTIONS_IMAGE_PX;
1209pub use instructions_export::{TOPOLOGY_WAIT, InstructionsPdfExport};
1210pub mod cam_ops;
1211pub use pmi_ops::{pmi_view_params, pmi_view_schema, world_vertex_ref, PmiModelingSnapshot, PmiViewPatch};
1212// Drawing sheets: the `sheets` block, the open sheet and the projection cache.
1213mod sheet_ops;
1214pub(crate) mod pmi_overlay;
1215pub use pmi_overlay::PmiLabel;
1216/// The 3D spline-anchor editor: the resolved anchor list, the value edits
1217/// (position / distances / flip / side / add / remove / reorder / detach),
1218/// the anchor flavour of the transform gizmo, the port-attach flavour of the
1219/// reference picker, and the direction-cage overlay.
1220mod spline_edit;
1221/// The NURBS Solid CONTROL-CAGE editor: the cage's points through the
1222/// kernel's resolver, the multi-point selection that arms the transform
1223/// gizmo at its centroid, the drag write-back, loop insertion, reset and the
1224/// cage overlay.
1225mod cage_edit;
1226/// The Deform Face PICK HANDLES: the kernel's resolved picks drawn as dots,
1227/// one armed by a click, dragged along its normal through the transform gizmo.
1228mod deform_edit;
1229
1230// Re-exports preserving the original `engine_state::*` public surface.
1231pub use assembly_ops::{document_signature, nested_fixed_state, ComponentInsert};
1232pub use board_geometry::{
1233    default_color as board_default_color, BoardBuild, BOARD_SOLID_PREFIX, SUBSTRATE_SOLID,
1234    VIAS_SOLID,
1235};
1236pub use bom::{OCCURRENCE_ATTRIBUTES, PART_ATTRIBUTES};
1237pub use component_move::{ComponentMoveArm, TypedMove};
1238pub use components::ComponentInfo;
1239pub use draft_analysis_ops::{DraftAnalysisState, DRAFT_ANALYSIS_DEFAULT_MIN_DEG};
1240pub use interference::{ClearancePair, InterferencePair, InterferenceReport, INTERFERENCE_OVERLAY_GROUP};
1241pub use model_io::{
1242    EmbeddedOnly, PartSink, StepAssemblyImport, StepAssemblyProbe, StepAssemblyReport,
1243};
1244pub(crate) use model_io::is_iges_text;
1245pub use selection_filter::SelectionFilter;
1246pub use sketch_mode::{SketchDrag, SketchEdit};
1247pub use sketch_panel::{NoticeSeverity, SketchConstraintAction, SketchEntityRow};
1248pub use wire_harness_ops::ConnectionPatch;
1249pub use wire_bom::{WireBomLine, WireLengthState};
1250pub use spline_edit::SplineAnchorRow;
1251pub use cage_edit::{CageArm, CageSelect, CageSummary, CAGE_PICK_RADIUS_PX};
1252pub use deform_edit::{DeformArm, DeformPickRow, DEFORM_PICK_RADIUS_PX};
1253pub use transform_gizmo::{is_face_transform_type, GizmoMode, TransformArm};
1254pub(crate) use transform_gizmo::rotate_euler_xyz_f64;
1255
1256
1257
1258
1259
1260
1261
1262/// Reconstruction results either append to a document or remain uncommitted.
1263#[derive(Clone, Copy, PartialEq, Eq)]
1264pub(crate) enum MeshImportDestination {
1265    Document,
1266    Preview,
1267}