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