Skip to main content

brep_render/engine_state/
camera_widgets.rs

1use super::*;
2
3impl EngineState {
4    /// Per-frame overlay upkeep — the ONE call the app viewport makes each frame
5    /// (see `BREP_app/src/viewport/interaction.rs`).
6    ///
7    /// Everything fed through the general `set_overlay` channel is pre-expanded
8    /// into GPU vertices AT FEED TIME (see the "Why not one uniform feed" note in
9    /// [`crate::widgets`]), so — unlike the specialized widgets (transform gizmo,
10    /// datums, ViewCube), which are rebuilt against the LIVE camera every frame —
11    /// a baked overlay group keeps whatever screen-constant sizing it was baked
12    /// with. A ZOOM changes `world_per_pixel` and nothing else re-bakes them, so
13    /// the draggable gizmos keep their old pixel size — and where a handle's world
14    /// position is ITSELF `px × world_per_pixel` (the angular arc), their old
15    /// POSITION too, drifting away from the live-computed grab region.
16    ///
17    /// So: re-bake on a MATERIAL `world_per_pixel` change, keyed on that ONE
18    /// quantity rather than on any particular gesture. Every zoom path moves it —
19    /// the wheel, [`Self::zoom_to_fit`], [`Self::standard_view`] (which fits), a
20    /// viewport [`Self::resize`] — so they are all covered without a per-path
21    /// hook. What does NOT move it needs no re-bake, and correctly gets none:
22    /// pan and orbit hold the eye→target distance, the ViewCube (face, corner AND
23    /// navigation arrow) is a fixed-pivot reorient, and
24    /// [`Self::toggle_projection`] preserves apparent size by construction
25    /// (`ViewCamera::toggle_projection` solves for the distance/half-height that
26    /// keeps `world_per_pixel` — see `projection_toggle_preserves_apparent_size`).
27    /// The baked buffers are world-space, so the GPU re-projects them for free.
28    /// Re-bakes only on actual change, so a quiet frame stays quiet (no per-frame
29    /// dirty loop).
30    pub fn ensure_overlays_current(&mut self) {
31        // Assembly-constraint leaders + grabbable distance/angle handles (§8.4).
32        self.ensure_constraint_overlay_current();
33        // The ◎ feature-DIMENSION gizmo: draggable leaders/arrowheads + the
34        // angular sweep handle, whose arc radius is itself px × world_per_pixel.
35        self.ensure_feature_dimension_overlay_current();
36        // Live sketch mode: draggable dimension leaders, constraint glyphs and
37        // construction dashes, all sized in pixels at bake time.
38        self.ensure_sketch_overlay_current();
39        // The active PMI view's annotation graphics (screen-constant arrows
40        // that also face the camera).
41        self.ensure_pmi_overlay_current();
42    }
43
44    /// Frame the whole scene (used right after the first history feed).
45    pub fn zoom_to_fit(&mut self) {
46        self.camera.zoom_to_fit(&self.scene.bbox(), 1.15);
47        self.dirty = true;
48    }
49
50    // --- Sizing -----------------------------------------------------------
51
52    /// Update the CSS viewport size (used by all camera math). The physical
53    /// framebuffer size + DPR are the presentation shell's concern.
54    pub fn resize(&mut self, css_width: f64, css_height: f64) {
55        self.camera.width = css_width.max(1.0);
56        self.camera.height = css_height.max(1.0);
57        self.dirty = true;
58    }
59
60    // --- Pointer / wheel ingestion (R22) ----------------------------------
61
62    pub fn pointer_down(&mut self, x: f64, y: f64, button: i32) -> bool {
63        // Sketch camera lock: while locked, the view is held flat-on to the sketch
64        // plane, so a LEFT press must NOT drive the camera at all — neither orbit
65        // (which would tilt off the plane) NOR pan. Suppressing it keeps left-drag
66        // free for sketch interaction and leaves pan on right/middle. Modeling mode
67        // and the UNLOCKED sketch view (where left orbits) are unaffected.
68        if self.sketch_mode()
69            && self.sketch_camera_locked
70            && button == crate::controls::BUTTON_LEFT
71        {
72            return false;
73        }
74        self.controls.pointer_down(x, y, button)
75    }
76
77    pub fn pointer_move(&mut self, x: f64, y: f64) -> bool {
78        let changed = self.controls.pointer_move(&mut self.camera, x, y);
79        if changed {
80            self.dirty = true;
81        }
82        changed
83    }
84
85    pub fn pointer_up(&mut self) -> bool {
86        self.controls.pointer_up()
87    }
88
89    pub fn wheel(&mut self, delta_y: f64, cursor: Option<[f64; 2]>) -> bool {
90        let changed = self.controls.wheel(&mut self.camera, delta_y, cursor);
91        if changed {
92            self.dirty = true;
93        }
94        changed
95    }
96
97    pub fn set_controls_enabled(&mut self, enabled: bool) {
98        self.controls.enabled = enabled;
99    }
100
101    /// Two-finger pan/pinch, also available with the sketch camera locked:
102    /// neither operation changes its orientation relative to the sketch plane.
103    pub fn touch_navigation(&mut self, from: [f64; 2], to: [f64; 2], scale: f64) -> bool {
104        let changed = self
105            .controls
106            .touch_navigation(&mut self.camera, from, to, scale);
107        self.dirty |= changed;
108        changed
109    }
110
111    // --- Camera commands (R21) --------------------------------------------
112
113    pub fn toggle_projection(&mut self) -> &'static str {
114        let kind = self.camera.toggle_projection();
115        self.dirty = true;
116        kind
117    }
118
119    pub fn set_projection(&mut self, kind: &str) {
120        let is_persp = matches!(self.camera.projection, crate::view::Projection::Perspective { .. });
121        let want_persp = kind.to_ascii_lowercase().starts_with("pers");
122        if is_persp != want_persp {
123            self.camera.toggle_projection();
124            self.dirty = true;
125        }
126    }
127
128    /// Snap to a named view and fit, the name read in [`Self::view_frame`] —
129    /// so with a board shown TOP looks down on its component side.
130    pub fn standard_view(&mut self, name: &str) -> bool {
131        let ok = self.camera.standard_view_in(self.view_frame(), name);
132        if ok {
133            self.camera.zoom_to_fit(&self.scene.bbox(), 1.15);
134            self.dirty = true;
135        }
136        ok
137    }
138
139    /// The frame the named views and the ViewCube are read in: Z-up
140    /// ([`ViewFrame::Board`]) while the document shows a board, Y-up otherwise.
141    ///
142    /// Keyed on the DOCUMENT, not the workbench: the board is seen in 3D from
143    /// every workbench that draws the 3D view (Modeling, Assembly…) — the PCB
144    /// workbench itself draws its 2D editor there instead — so a frame the PCB
145    /// workbench switched on would never be in force where the board is looked
146    /// at. A document that has a board is one whose 3D view is about the board.
147    pub fn view_frame(&self) -> crate::view::ViewFrame {
148        if self.shown_board_ids.is_empty() {
149            crate::view::ViewFrame::World
150        } else {
151            crate::view::ViewFrame::Board
152        }
153    }
154
155    /// Put the ViewCube in the frame [`Self::view_frame`] reads now, after the
156    /// board bodies were fed or removed. The first time a board appears the
157    /// camera turns to the board's ISO view and frames it, so a board document
158    /// opens looking down on the component side from the front right, as a
159    /// board viewer does, rather than at the Y-up startup vantage that shows
160    /// the board as a standing wall. Losing the board leaves the camera alone.
161    pub(super) fn sync_view_frame(&mut self) {
162        let frame = self.view_frame();
163        if frame == self.widgets.view_frame() {
164            return;
165        }
166        self.widgets.set_view_frame(frame);
167        if frame == crate::view::ViewFrame::Board {
168            self.camera.standard_view_in(frame, "ISO");
169            self.camera.zoom_to_fit(&self.scene.bbox(), 1.15);
170        }
171        self.dirty = true;
172    }
173
174    pub fn camera_state_json(&self) -> String {
175        self.camera.state_json()
176    }
177
178    pub fn apply_camera_state_json(&mut self, json: &str) -> Result<(), String> {
179        self.camera.apply_state_json(json)?;
180        self.dirty = true;
181        Ok(())
182    }
183
184    pub fn world_per_pixel(&self) -> f64 {
185        self.camera.world_per_pixel()
186    }
187
188    // --- World → screen (R25) ---------------------------------------------
189
190    /// Project world points to CSS-pixel screen coords for host anchoring. Input
191    /// is `[[x,y,z], …]`; output `[[sx, sy, depth, inFront], …]` where inFront
192    /// is 1 when a LABEL anchored at the point should draw
193    /// ([`crate::view::ViewCamera::label_anchor_visible`], THE one label policy:
194    /// the point is projectable — ortho always, perspective unless at/behind the
195    /// eye plane, near/far NEVER cull — AND its projection lands inside the
196    /// viewport, so an off-screen anchor's chip vanishes instead of clamping to
197    /// the viewport edge). Every app label pass (sketch dims, feature dims,
198    /// constraint chips, gizmo axis text) keys its skip off THIS flag, so the
199    /// policy lives in exactly one place.
200    pub fn world_to_screen_json(&self, points_json: &str) -> Result<String, String> {
201        let points: Vec<[f64; 3]> = serde_json::from_str(points_json)
202            .map_err(|error| format!("world_to_screen points parse: {error}"))?;
203        let out: Vec<[f64; 4]> = points
204            .into_iter()
205            .map(|p| {
206                let (sx, sy, depth) = self.camera.project(p);
207                let visible = self.camera.label_anchor_visible(p);
208                [sx, sy, depth, if visible { 1.0 } else { 0.0 }]
209            })
210            .collect();
211        Ok(serde_json::to_string(&out).unwrap_or_else(|_| "[]".to_string()))
212    }
213
214    /// The camera matrices for the host overlays' per-frame world→screen /
215    /// screen→world hot path: `{ viewProj:[16], viewProjInverse:[16],
216    /// viewport:[w,h] }`. Both matrices are column-major (index =
217    /// `col*4 + row`); `viewProj` maps world → wgpu clip
218    /// (x,y in −1..1, z in 0..1) and `viewport` is the CSS-pixel size. This lets
219    /// dimensions + sketch drop the compat mirror camera and read the engine's
220    /// own view-projection directly (see `world_to_screen_json` for one-shots).
221    pub fn camera_matrices_json(&self) -> String {
222        let view_proj = self.camera.view_proj_flat();
223        let view_proj_inverse = self.camera.view_proj_inverse_flat();
224        serde_json::json!({
225            "viewProj": view_proj,
226            "viewProjInverse": view_proj_inverse,
227            "viewport": [self.camera.width, self.camera.height],
228        })
229        .to_string()
230    }
231
232    // --- Picking (R23/R24) ------------------------------------------------
233
234}
235
236impl EngineState {
237    /// Build this frame's overlay-widget geometry, or None when nothing is
238    /// enabled (skips the overlay passes entirely).
239    pub fn build_widget_overlay(&self) -> Option<WidgetOverlay> {
240        if !self.widgets.any_visible() {
241            return None;
242        }
243        Some(self.widgets.build_overlay(&gizmo_camera(&self.camera)))
244    }
245
246    /// Fit the per-frame depth window to EVERYTHING drawn, then resolve the GPU
247    /// camera — the ONE path both frame loops (wasm `Engine::render`, desktop
248    /// `redraw`) use so they can't drift. The overlay is built FIRST, then its
249    /// WORLD bounds are folded into the fit: near/far never affect the overlay
250    /// geometry (it depends only on view direction + `world_per_pixel`), so
251    /// building it before the fit lets construction geometry — datum planes,
252    /// world axes, frames, the transform gizmo — be bracketed by the depth
253    /// window instead of clipping against the solids-only bounds. The world
254    /// ORIGIN is always folded in too, so the origin triad stays bracketed even
255    /// when every geometry channel is momentarily empty (an all-empty frame then
256    /// yields a tiny origin-centred window — harmless, re-fit next frame). The
257    /// ViewCube is excluded (it draws with its own mini-camera; see
258    /// [`WidgetOverlay::world_bbox`]). Returns the resolved camera + the built
259    /// overlay for the frame to hand to the render core.
260    pub fn fit_camera_and_overlay(&mut self) -> (crate::camera::Camera, Option<WidgetOverlay>) {
261        let overlay = self.build_widget_overlay();
262        let mut depth_bbox = self.depth_range_bbox();
263        if let Some(overlay) = &overlay {
264            depth_bbox.union(&overlay.world_bbox());
265        }
266        depth_bbox.expand([0.0, 0.0, 0.0]);
267        self.camera.fit_depth_range(&depth_bbox);
268        (self.camera.resolve(), overlay)
269    }
270
271    pub fn set_datums_json(&mut self, json: &str) -> Result<(), String> {
272        self.widgets.set_datums_json(json)?;
273        self.dirty = true;
274        Ok(())
275    }
276
277    /// Feed the general overlay geometry channel (`set_overlay`): arbitrary named
278    /// tri/line/point groups (feature-dialog previews and other display-only
279    /// geometry), drawn in the widget overlay pass.
280    pub fn set_overlay_json(&mut self, json: &str) -> Result<(), String> {
281        self.widgets.set_overlay_json(json)?;
282        self.dirty = true;
283        Ok(())
284    }
285
286    pub fn set_dimensions_json(&mut self, json: &str) -> Result<(), String> {
287        self.widgets.set_dimensions_json(json)?;
288        self.dirty = true;
289        Ok(())
290    }
291
292    pub fn set_transform_json(&mut self, json: &str) -> Result<(), String> {
293        self.widgets.set_transform_json(json)?;
294        self.dirty = true;
295        Ok(())
296    }
297
298    pub fn set_viewcube_enabled(&mut self, enabled: bool) {
299        self.widgets.set_viewcube_enabled(enabled);
300        self.dirty = true;
301    }
302
303    /// The ViewCube corner rect `{x,y,w,h}` (CSS px) so the host can decide
304    /// whether to forward a pointer event.
305    pub fn viewcube_rect_json(&self) -> String {
306        let r = self.widgets.viewcube_rect(&gizmo_camera(&self.camera));
307        serde_json::json!({ "x": r[0], "y": r[1], "w": r[2], "h": r[3] }).to_string()
308    }
309
310    /// Update the ViewCube hover from cube-local pixels; returns whether it
311    /// changed (a hover-out is `(None)` with local coords outside).
312    pub fn viewcube_hover(&mut self, local_x: f64, local_y: f64) -> bool {
313        let cam = gizmo_camera(&self.camera);
314        let handle = self.widgets.viewcube_hit(&cam, local_x as f32, local_y as f32);
315        let changed = self.widgets.set_viewcube_hover(handle);
316        if changed {
317            self.dirty = true;
318        }
319        changed
320    }
321
322    pub fn viewcube_clear_hover(&mut self) -> bool {
323        let changed = self.widgets.set_viewcube_hover(None);
324        if changed {
325            self.dirty = true;
326        }
327        changed
328    }
329
330    /// Click the ViewCube at cube-local pixels: snap the shared camera to the
331    /// region's standard view (keeping the current pivot distance). Returns
332    /// true if a region was hit.
333    pub fn viewcube_click(&mut self, local_x: f64, local_y: f64) -> bool {
334        let cam = gizmo_camera(&self.camera);
335        let Some(handle) = self.widgets.viewcube_hit(&cam, local_x as f32, local_y as f32) else {
336            return false;
337        };
338        // Navigation arrows apply a RELATIVE camera rotation (orbit / roll) to
339        // the current view instead of snapping to an absolute standard view.
340        if brep_gizmos::view_cube::ViewCube::is_arrow(handle) {
341            self.apply_viewcube_arrow(handle);
342            self.dirty = true;
343            return true;
344        }
345        let (dir, fallback_up) = self.widgets.viewcube_target(handle);
346        // Minimal-rotation snap with a LEVELLED roll: the view direction snaps to
347        // the region, and the up is snapped to the nearest member of a discrete
348        // per-kind set (see [`snap_view_up`]) so a face lands flat-on with its
349        // bottom edge horizontal and a corner lands on a proper top-vertex-up
350        // isometric — always the orientation that rotates the camera the least.
351        let kind = brep_gizmos::view_cube::ViewCube::region_kind(handle);
352        let dirf = [dir[0] as f64, dir[1] as f64, dir[2] as f64];
353        let up = snap_view_up(kind, dirf, self.camera.up, fallback_up);
354        self.apply_look_direction(dir, up);
355        self.dirty = true;
356        true
357    }
358
359    /// Reorient the camera to look along `dir` (world eye→target) with `up`,
360    /// preserving the current pivot distance.
361    pub(super) fn apply_look_direction(&mut self, dir: [f32; 3], up: [f32; 3]) {
362        let dir = [dir[0] as f64, dir[1] as f64, dir[2] as f64];
363        let dist = self.camera.distance();
364        self.camera.eye = [
365            self.camera.target[0] - dir[0] * dist,
366            self.camera.target[1] - dir[1] * dist,
367            self.camera.target[2] - dir[2] * dist,
368        ];
369        self.camera.up = [up[0] as f64, up[1] as f64, up[2] as f64];
370    }
371
372    /// Apply a ViewCube navigation-arrow rotation to the CURRENT camera (a
373    /// relative 90° orbit / roll), keeping the pivot (`target`) fixed. The
374    /// rotation axes are the camera's own screen axes so the motion follows the
375    /// on-screen arrow direction: the eye moves toward the pan arrow it points
376    /// at, and the roll arcs spin the up vector about the view direction.
377    fn apply_viewcube_arrow(&mut self, handle: u32) {
378        use crate::view::{add3, rotate3, sub3};
379        use brep_gizmos::view_cube::ViewCube;
380        // World-space screen axes of the current view: right, up, forward(eye→target).
381        let (right, up_axis, fwd) = self.camera.basis();
382        let target = self.camera.target;
383        let rel = sub3(self.camera.eye, target); // eye relative to pivot
384        let q = std::f64::consts::FRAC_PI_2; // 90° per click
385        match handle {
386            // Orbit about the screen-up axis; eye moves toward the arrow side.
387            ViewCube::ARROW_RIGHT => {
388                self.camera.eye = add3(target, rotate3(rel, up_axis, q));
389            }
390            ViewCube::ARROW_LEFT => {
391                self.camera.eye = add3(target, rotate3(rel, up_axis, -q));
392            }
393            // Orbit about the screen-right axis; carry the up vector along so the
394            // view stays upright (eye moves toward the arrow side).
395            ViewCube::ARROW_UP => {
396                self.camera.eye = add3(target, rotate3(rel, right, -q));
397                self.camera.up = rotate3(self.camera.up, right, -q);
398            }
399            ViewCube::ARROW_DOWN => {
400                self.camera.eye = add3(target, rotate3(rel, right, q));
401                self.camera.up = rotate3(self.camera.up, right, q);
402            }
403            // Roll about the view direction; only the up vector changes.
404            ViewCube::ROLL_CCW => {
405                self.camera.up = rotate3(self.camera.up, fwd, q);
406            }
407            ViewCube::ROLL_CW => {
408                self.camera.up = rotate3(self.camera.up, fwd, -q);
409            }
410            _ => {}
411        }
412    }
413
414    /// Pick the datum plane/axis under a screen pixel; returns its name (empty
415    /// when none).
416    ///
417    /// NOT the selection path any more: construction planes are ordinary pick
418    /// candidates ([`Self::pick_candidates_at`] → the widget's `datum_plane_hits`,
419    /// which reports EVERY card the ray crosses rather than the first), so the
420    /// viewport click router no longer calls this. It survives as the AXIS-aware
421    /// second line of defense inside [`Self::ref_select_click`]'s total-miss arm.
422    pub fn datum_pick(&self, x: f64, y: f64) -> String {
423        self.widgets
424            .datum_pick(&gizmo_camera(&self.camera), x as f32, y as f32)
425            .unwrap_or_default()
426    }
427
428    /// Update the transform-gizmo hover from a screen pixel; returns the handle
429    /// under the pointer (0 = none). Marks dirty when the highlight changed.
430    pub fn transform_hover(&mut self, x: f64, y: f64) -> u32 {
431        let cam = gizmo_camera(&self.camera);
432        let handle = self.widgets.transform_hit(&cam, x as f32, y as f32);
433        if self.widgets.set_transform_hover(handle) {
434            self.dirty = true;
435        }
436        handle
437    }
438
439    /// The transform-gizmo handle under a screen pixel (0 = none) — the host
440    /// echoes it back to start a drag.
441    pub fn transform_pick(&self, x: f64, y: f64) -> u32 {
442        self.widgets.transform_hit(&gizmo_camera(&self.camera), x as f32, y as f32)
443    }
444
445    /// Compute a transform drag (frame-space + world delta) as JSON for the
446    /// feature-edit commit. Marks the handle active for the highlight.
447    pub fn transform_drag(
448        &mut self,
449        handle: u32,
450        sx: f64,
451        sy: f64,
452        cx: f64,
453        cy: f64,
454    ) -> String {
455        let cam = gizmo_camera(&self.camera);
456        self.widgets.set_transform_active(handle);
457        self.dirty = true;
458        self.widgets
459            .transform_drag_json(&cam, handle, sx as f32, sy as f32, cx as f32, cy as f32)
460    }
461
462    pub fn transform_drag_end(&mut self) {
463        self.widgets.set_transform_active(0);
464        self.dirty = true;
465    }
466
467    /// Per-dimension label placement: `[{id, anchor:[x,y,z],
468    /// screen:[sx,sy,inFront]}]` — the host pins each text label at `screen`.
469    pub fn dimension_anchors_json(&self) -> String {
470        let anchors = self.widgets.dimension_anchors(&gizmo_camera(&self.camera));
471        let out: Vec<serde_json::Value> = anchors
472            .into_iter()
473            .map(|(id, p)| {
474                let world = [p[0] as f64, p[1] as f64, p[2] as f64];
475                let (sx, sy, _) = self.camera.project(world);
476                // Same ONE label policy as `world_to_screen_json` — near/far
477                // never cull; off-viewport anchors hide their label.
478                let visible = if self.camera.label_anchor_visible(world) { 1.0 } else { 0.0 };
479                serde_json::json!({
480                    "id": id,
481                    "anchor": p,
482                    "screen": [sx, sy, visible],
483                })
484            })
485            .collect();
486        serde_json::to_string(&out).unwrap_or_else(|_| "[]".to_string())
487    }
488
489    // --- Undo / redo (engine-owned) ---------------------------------------
490    //
491    // The model is engine-owned, so its undo history lives in the engine core
492    // too: `History` holds the stacks and snapshots itself BEFORE each model
493    // mutation (edit / add / delete / reorder), while roll-to-step is view state
494    // and is NOT snapshotted. The UI only TRIGGERS these; it never holds a stack.
495
496}
497
498/// Choose the camera `up` when the ViewCube snaps to a face / edge / corner.
499///
500/// `dir` is the world eye→target direction the view snaps to
501/// ([`brep_gizmos::view_cube::ViewCube::target_view`]): axis-aligned for a face,
502/// a 45° blend for an edge, a body-diagonal for a corner. `current_up` is the
503/// live camera up; `fallback` the region's canonical up.
504///
505/// The roll is snapped to a DISCRETE set and the member closest to the current
506/// up wins (max dot ⇒ least roll), so the reorient rotates by the smallest angle
507/// while still landing "level":
508/// - **face** (`kind == 1`): the 4 signed world axes lying in the face plane
509///   (the two axes `dir` is perpendicular to) — the face ends flat-on with its
510///   bottom edge horizontal, choosing whichever of the 4 edges was already
511///   nearest the top.
512/// - **corner** (`kind == 3`): the 3 cube axes that point up for this corner
513///   (top-vertex-up isometric), 120° apart — the axis whose sign opposes each
514///   component of `dir` (so the near vertex reads upright, not inverted).
515/// - **edge / other**: no discrete set — the current up is projected onto the
516///   plane ⟂ `dir` (free roll preserved), falling back to `fallback` when that
517///   projection degenerates (up nearly parallel to `dir`).
518pub(super) fn snap_view_up(
519    kind: u8,
520    dir: [f64; 3],
521    current_up: [f64; 3],
522    fallback: [f32; 3],
523) -> [f32; 3] {
524    let mut candidates: Vec<[f64; 3]> = Vec::new();
525    match kind {
526        // Face: both signs of each axis the (axis-aligned) view dir is ⟂ to.
527        1 => {
528            for a in 0..3 {
529                if dir[a].abs() < 0.5 {
530                    let mut p = [0.0; 3];
531                    p[a] = 1.0;
532                    candidates.push(p);
533                    p[a] = -1.0;
534                    candidates.push(p);
535                }
536            }
537        }
538        // Corner: the axis direction opposite each component of the view dir
539        // (dir = -normalize(signs), so -sign(dir[a]) recovers the corner's sign).
540        3 => {
541            for a in 0..3 {
542                let mut p = [0.0; 3];
543                p[a] = -dir[a].signum();
544                candidates.push(p);
545            }
546        }
547        _ => {}
548    }
549
550    let dot = |v: &[f64; 3]| v[0] * current_up[0] + v[1] * current_up[1] + v[2] * current_up[2];
551    // An EXACT tie — the current up perpendicular to two candidates, as from
552    // an ISO onto its TOP face — goes to the candidate nearest the region's
553    // own up, not to whichever the loop listed last. The listing order only
554    // happened to give TOP's −Z in the Y-up frame; in the board frame it gave
555    // the TOP view upside down (the layout's +Y down the screen).
556    let score = |v: &[f64; 3]| {
557        dot(v) + 1e-6 * (v[0] * fallback[0] as f64 + v[1] * fallback[1] as f64 + v[2] * fallback[2] as f64)
558    };
559    if let Some(best) = candidates
560        .into_iter()
561        .max_by(|x, y| score(x).partial_cmp(&score(y)).unwrap_or(std::cmp::Ordering::Equal))
562    {
563        return [best[0] as f32, best[1] as f32, best[2] as f32];
564    }
565
566    // Edge / fallback: project the current up onto the plane ⟂ dir (keep roll).
567    let d = dot(&dir);
568    let proj = [
569        current_up[0] - dir[0] * d,
570        current_up[1] - dir[1] * d,
571        current_up[2] - dir[2] * d,
572    ];
573    let len = (proj[0] * proj[0] + proj[1] * proj[1] + proj[2] * proj[2]).sqrt();
574    if len > 1e-4 {
575        [
576            (proj[0] / len) as f32,
577            (proj[1] / len) as f32,
578            (proj[2] / len) as f32,
579        ]
580    } else {
581        fallback
582    }
583}
584
585/// Serialize a screen-space [`brep_gizmos::hit_region::HitShape`] to the gizmo
586/// hit-area JSON schema the app strokes: `{ kind:"capsule", a:[x,y], b:[x,y], r }`
587/// or `{ kind:"circle", c:[x,y], r }` — viewport-local px, so the app only offsets
588/// by `rect.min`. The engine hit-tests these SAME shapes, so the drawn outline can
589/// never drift from the pickable region. Shared by both gizmo exposers.
590pub(super) fn hit_shape_json(shape: &brep_gizmos::hit_region::HitShape) -> serde_json::Value {
591    use brep_gizmos::hit_region::HitShape;
592    match *shape {
593        HitShape::Capsule { a, b, r } => {
594            serde_json::json!({ "kind": "capsule", "a": a, "b": b, "r": r })
595        }
596        HitShape::Circle { c, r } => serde_json::json!({ "kind": "circle", "c": c, "r": r }),
597    }
598}
599
600/// Serialize an iterator of [`brep_gizmos::hit_region::HitShape`]s to the app's
601/// gizmo hit-area JSON array (see [`hit_shape_json`]); `"[]"` on failure.
602pub(super) fn hit_shapes_json<'a>(
603    shapes: impl Iterator<Item = &'a brep_gizmos::hit_region::HitShape>,
604) -> String {
605    let out: Vec<serde_json::Value> = shapes.map(hit_shape_json).collect();
606    serde_json::to_string(&out).unwrap_or_else(|_| "[]".to_string())
607}
608
609
610