BREP_gizmos 0.1.0

BREP in-scene gizmos and overlay widgets (transform gizmo, ViewCube, datum/axis visuals, dimension leaders). Pure geometry + hit-testing, no kernel or GPU dependency — the render engine consumes the emitted overlay geometry. A CPU rasterizer is provided for headless demo/verification.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
//! Transform gizmo — the move + rotate widget for the Rust rendering
//! engine. This is the pure-geometry + hit-testing reimplementation of the
//! app's `CombinedTransformControls`:
//! 3 axis translate arrows, 3 planar translate quads, 3 rotation rings, and an
//! optional center free-move handle. It holds NO interaction state and touches
//! neither the kernel nor the GPU — it consumes a [`GizmoCamera`] and emits an
//! [`Overlay`], answers [`Gizmo::hit`], and computes frame-space drag deltas.
//!
//! ## Integration contract (engine / wasm / host)
//!
//! Everything below is what the surrounding engine must feed the gizmo and what
//! it gets back. The serial wiring into `brep-render`'s overlay pass + the wasm
//! API is mechanical — no gizmo logic changes.
//!
//! FEED, every frame:
//!   * `GizmoCamera` — build from the live engine camera (view_proj, eye,
//!     forward, viewport, orthographic). Same struct the engine already mirrors.
//!   * The FEATURE FRAME — call [`TransformGizmo::set_frame`] with the selected
//!     feature's origin + 3 orthonormal axes (R28: drags happen in the feature's
//!     frame, +Z-up world convention). Defaults to world XYZ at the origin.
//!
//! FEED, on hover / pick (pointer move & down):
//!   * The screen point (CSS px, top-left origin, y down). Call
//!     [`Gizmo::hit`] → `Option<HandleId>`. The host keeps this as the "hovered"
//!     handle; on pointer-down it becomes the "active" (dragged) handle.
//!
//! FEED, each drag move:
//!   * The active `HandleId` (echoed back from the host), the START ray and the
//!     CURRENT ray. Build rays with `camera.ray_from_screen(x, y)` at the
//!     pointer-down point and the current pointer point. Call
//!     [`TransformGizmo::drag_delta`].
//!
//! GET BACK:
//!   * From [`Gizmo::geometry`] — an [`Overlay`] (world-space colored line
//!     segments + triangles) to convert into the engine's overlay vertex
//!     buffers. Pass the hovered/active handle so the highlighted handle draws
//!     gold.
//!   * From [`Gizmo::hit`] — the `HandleId` under the pointer (or `None`).
//!   * From [`TransformGizmo::drag_delta`] — a [`DragDelta`] in the gizmo's
//!     FRAME: `Translate(v)` where `v`'s components are distances along
//!     `ex/ey/ez` (world delta = `ex*v.x + ey*v.y + ez*v.z`), or
//!     `Rotate { axis_index, radians }` (signed rotation about that frame axis).
//!     The host turns this into the feature-edit commit callback (translate the datum,
//!     rotate the sketch plane, etc.). For a continuous drag either feed the
//!     original pointer-down ray as `start` (absolute delta from grab) or the
//!     previous-frame ray (incremental) — both are supported; rotation uses a
//!     signed-angle so incremental feeding avoids the ±180° wrap.

use crate::{Gizmo, GizmoCamera, HandleId, Overlay};
use crate::math::{Ray, Vec3};

// --- stable handle ids -----------------------------------------------------

/// Body / no specific handle (contract convention).
pub const HANDLE_NONE: HandleId = 0;
/// Axis translate arrows.
pub const HANDLE_AXIS_X: HandleId = 1;
pub const HANDLE_AXIS_Y: HandleId = 2;
pub const HANDLE_AXIS_Z: HandleId = 3;
/// Planar translate quads (named by the two in-plane axes).
pub const HANDLE_PLANE_XY: HandleId = 4;
pub const HANDLE_PLANE_YZ: HandleId = 5;
pub const HANDLE_PLANE_ZX: HandleId = 6;
/// Rotation rings (named by the axis they turn about).
pub const HANDLE_RING_X: HandleId = 7;
pub const HANDLE_RING_Y: HandleId = 8;
pub const HANDLE_RING_Z: HandleId = 9;
/// Center free-move / uniform handle (screen-plane translate).
pub const HANDLE_CENTER: HandleId = 10;

// --- colors (linear RGBA) --------------------------------------------------

// Restyled gizmo look (matches the reference transform-controls image): an
// ORANGE center sphere, silver-grey axis shafts drawn as solid 3D rods (tubes)
// with orange CONE tips, three light-grey ROTATION ARCS joining adjacent axis
// tips (the rounded-triangle silhouette), and orange grab SPHERES for rotation.
// Colors are display sRGB values written ~directly by the overlay shader (with a
// per-face shade for depth), so use hex/255 — no linear conversion.
const C_ROD: [f32; 4] = [0.80, 0.81, 0.82, 1.0]; // silver-grey rod shafts (~0xccced1)
const C_ARROW: [f32; 4] = [0.961, 0.651, 0.137, 1.0]; // orange cone tips (#F5A623)
const C_RING: [f32; 4] = [0.91, 0.91, 0.91, 1.0]; // light-grey rotation arcs (~0xe8e8e8)
const C_DOT: [f32; 4] = [0.961, 0.651, 0.137, 1.0]; // orange rotation grab spheres (#F5A623)
const C_GOLD: [f32; 4] = [1.00, 0.85, 0.35, 1.0]; // hover/active highlight (amber)
const C_CENTER: [f32; 4] = [0.961, 0.651, 0.137, 1.0]; // orange center sphere (#F5A623)

// --- pixel sizing (screen-constant; multiplied by world_per_pixel) ---------

/// Arrow tip distance from the origin (CSS px). Public so the app can place the
/// egui axis labels (`XC`/`YC`/`ZC`) just past each cone tip. Chosen so the cone
/// BASE (`PX_AXIS_LEN - PX_HEAD_LEN` = 72) sits a few px OUTSIDE the rotation arc
/// (`PX_ARC_RAD` = 64): the arcs join the shafts and the cones poke past them, so
/// the white arcs never cut through the orange arrowheads.
pub const PX_AXIS_LEN: f32 = 90.0;
const PX_SHAFT_START: f32 = 8.0; // shaft begins this far out (emerges from the center sphere)
const PX_HEAD_LEN: f32 = 18.0; // arrowhead cone length
const PX_HEAD_RAD: f32 = 7.0; // arrowhead cone base radius
const PX_SHAFT_RAD: f32 = 2.2; // silver-rod shaft radius (thick, reads as a 3D rod)
const PX_ARC_RAD: f32 = 64.0; // rotation-arc radius (arcs join the SHAFTS, inside the cone bases)
const PX_CENTER_RAD: f32 = 7.0; // center free-move sphere radius
const PX_RING_GRAB_RAD: f32 = 5.0; // orange rotation grab-sphere radius

const RING_SEGMENTS: usize = 24; // samples per quarter rotation arc
const CONE_SEGMENTS: usize = 16; // radial facets of an arrowhead cone
const TUBE_SEGMENTS: usize = 8; // radial facets of a shaft rod
const SPHERE_RINGS: usize = 6; // latitude bands of a handle sphere
const SPHERE_SECTORS: usize = 10; // longitude sectors of a handle sphere

/// The three rotation arcs as `(rotation-axis index, in-plane axis i, in-plane
/// axis j)`. Each arc sweeps from tip `i` to tip `j` in the plane whose normal
/// is the rotation axis, so grabbing it rotates about that axis.
const ARCS: [(usize, usize, usize); 3] = [(2, 0, 1), (0, 1, 2), (1, 2, 0)];

/// Screen-constant handle sizes in world units at the gizmo origin.
#[derive(Debug, Clone, Copy)]
struct Sizes {
    px: f32,
    axis_len: f32,
    shaft_start: f32,
    head_len: f32,
    head_rad: f32,
    shaft_rad: f32,
    arc_rad: f32,
    center_rad: f32,
    grab_rad: f32,
}

/// The result of a drag, expressed in the gizmo's FRAME (see module docs).
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DragDelta {
    /// Translation whose components are distances along `ex`, `ey`, `ez`.
    /// World delta = `ex*v.x + ey*v.y + ez*v.z`.
    Translate(Vec3),
    /// Signed rotation about frame axis `axis_index` (0=ex, 1=ey, 2=ez).
    Rotate { axis_index: usize, radians: f32 },
    /// No usable delta (unknown handle or a degenerate ray/plane).
    None,
}

/// A move + rotate gizmo positioned at an origin with an orientation frame.
#[derive(Debug, Clone, Copy)]
pub struct TransformGizmo {
    /// Gizmo origin in world space.
    pub origin: Vec3,
    /// Frame X axis (unit, world space).
    pub ex: Vec3,
    /// Frame Y axis (unit, world space).
    pub ey: Vec3,
    /// Frame Z axis (unit, world space).
    pub ez: Vec3,
    /// Whether to draw + hit-test the center free-move handle.
    pub show_center: bool,
}

impl Default for TransformGizmo {
    fn default() -> Self {
        Self {
            origin: Vec3::ZERO,
            ex: Vec3::X,
            ey: Vec3::Y,
            ez: Vec3::Z,
            show_center: true,
        }
    }
}

impl TransformGizmo {
    /// A gizmo at `origin` with the world XYZ frame.
    pub fn at(origin: Vec3) -> Self {
        Self { origin, ..Self::default() }
    }

    /// Set the origin + orientation frame (the feature's frame). The axes are
    /// re-orthonormalized defensively (ex kept, ez = ex×ey, ey = ez×ex).
    pub fn set_frame(&mut self, origin: Vec3, ex: Vec3, ey: Vec3, ez: Vec3) {
        self.origin = origin;
        let ex = ex.normalized();
        let mut ez = ez.normalized();
        if ez.length() < 1e-6 {
            ez = ex.cross(ey).normalized();
        }
        let ey = ez.cross(ex).normalized();
        let ez = ex.cross(ey).normalized();
        self.ex = ex;
        self.ey = ey;
        self.ez = ez;
    }

    /// World-space unit axis for `i` (0=ex, 1=ey, 2=ez).
    pub fn axis(&self, i: usize) -> Vec3 {
        match i {
            0 => self.ex,
            1 => self.ey,
            _ => self.ez,
        }
    }

    fn sizes(&self, camera: &GizmoCamera) -> Sizes {
        let px = camera.world_per_pixel(self.origin).max(1e-6);
        Sizes {
            px,
            axis_len: PX_AXIS_LEN * px,
            shaft_start: PX_SHAFT_START * px,
            head_len: PX_HEAD_LEN * px,
            head_rad: PX_HEAD_RAD * px,
            shaft_rad: PX_SHAFT_RAD * px,
            arc_rad: PX_ARC_RAD * px,
            center_rad: PX_CENTER_RAD * px,
            grab_rad: PX_RING_GRAB_RAD * px,
        }
    }

    /// The world-space (shaft-start, tip) endpoints of axis arrow `i`. Exposed
    /// so callers/tests can locate a handle without duplicating the sizing.
    pub fn axis_seg(&self, camera: &GizmoCamera, i: usize) -> (Vec3, Vec3) {
        let s = self.sizes(camera);
        let a = self.axis(i);
        (
            self.origin.add(a.scale(s.shaft_start)),
            self.origin.add(a.scale(s.axis_len)),
        )
    }

    // -- drag math (pure; no state) -----------------------------------------

    /// Frame-space delta for the active `handle` given the drag's start & current
    /// rays (build both with `camera.ray_from_screen`). See [`DragDelta`].
    pub fn drag_delta(
        &self,
        camera: &GizmoCamera,
        handle: HandleId,
        start: Ray,
        current: Ray,
    ) -> DragDelta {
        match handle {
            HANDLE_AXIS_X => DragDelta::Translate(self.axis_translate(camera, 0, start, current)),
            HANDLE_AXIS_Y => DragDelta::Translate(self.axis_translate(camera, 1, start, current)),
            HANDLE_AXIS_Z => DragDelta::Translate(self.axis_translate(camera, 2, start, current)),
            HANDLE_PLANE_XY => DragDelta::Translate(self.plane_translate(0, 1, start, current)),
            HANDLE_PLANE_YZ => DragDelta::Translate(self.plane_translate(1, 2, start, current)),
            HANDLE_PLANE_ZX => DragDelta::Translate(self.plane_translate(2, 0, start, current)),
            HANDLE_RING_X => DragDelta::Rotate { axis_index: 0, radians: self.ring_rotate(0, start, current) },
            HANDLE_RING_Y => DragDelta::Rotate { axis_index: 1, radians: self.ring_rotate(1, start, current) },
            HANDLE_RING_Z => DragDelta::Rotate { axis_index: 2, radians: self.ring_rotate(2, start, current) },
            HANDLE_CENTER => DragDelta::Translate(self.center_translate(camera, start, current)),
            _ => DragDelta::None,
        }
    }

    /// Axis translate: project the camera-facing-plane movement onto the axis.
    /// Returns a frame-local vector with only component `i` set.
    pub fn axis_translate(&self, camera: &GizmoCamera, i: usize, start: Ray, current: Ray) -> Vec3 {
        let n = camera.forward.normalized();
        let (p0, p1) = match (
            plane_point(&start, self.origin, n),
            plane_point(&current, self.origin, n),
        ) {
            (Some(a), Some(b)) => (a, b),
            _ => return Vec3::ZERO,
        };
        let d = p1.sub(p0).dot(self.axis(i));
        let mut out = Vec3::ZERO;
        match i {
            0 => out.x = d,
            1 => out.y = d,
            _ => out.z = d,
        }
        out
    }

    /// Planar translate: intersect both rays with the plane spanned by frame
    /// axes `i` and `j` (normal = the third axis) through the origin. Returns a
    /// frame-local vector with components `i` and `j` set.
    pub fn plane_translate(&self, i: usize, j: usize, start: Ray, current: Ray) -> Vec3 {
        let k = 3 - i - j; // the remaining index → plane normal
        let n = self.axis(k);
        let (p0, p1) = match (
            plane_point(&start, self.origin, n),
            plane_point(&current, self.origin, n),
        ) {
            (Some(a), Some(b)) => (a, b),
            _ => return Vec3::ZERO,
        };
        let delta = p1.sub(p0);
        let a = delta.dot(self.axis(i));
        let b = delta.dot(self.axis(j));
        let mut out = Vec3::ZERO;
        set_comp(&mut out, i, a);
        set_comp(&mut out, j, b);
        out
    }

    /// Ring rotate: signed angle about frame axis `i` between the start & current
    /// ray intersections with the plane through the origin perpendicular to `i`.
    pub fn ring_rotate(&self, i: usize, start: Ray, current: Ray) -> f32 {
        let n = self.axis(i);
        let (p0, p1) = match (
            plane_point(&start, self.origin, n),
            plane_point(&current, self.origin, n),
        ) {
            (Some(a), Some(b)) => (a, b),
            _ => return 0.0,
        };
        let v0 = p0.sub(self.origin);
        let v1 = p1.sub(self.origin);
        if v0.length() < 1e-9 || v1.length() < 1e-9 {
            return 0.0;
        }
        let v0 = v0.normalized();
        let v1 = v1.normalized();
        let cross = v0.cross(v1).dot(n);
        let dot = v0.dot(v1).clamp(-1.0, 1.0);
        cross.atan2(dot)
    }

    /// Center free-move: screen-plane translate, returned in full frame-local
    /// coordinates (all three components may be set).
    pub fn center_translate(&self, camera: &GizmoCamera, start: Ray, current: Ray) -> Vec3 {
        let n = camera.forward.normalized();
        let (p0, p1) = match (
            plane_point(&start, self.origin, n),
            plane_point(&current, self.origin, n),
        ) {
            (Some(a), Some(b)) => (a, b),
            _ => return Vec3::ZERO,
        };
        let delta = p1.sub(p0);
        Vec3::new(delta.dot(self.ex), delta.dot(self.ey), delta.dot(self.ez))
    }

    // -- geometry helpers ---------------------------------------------------

    /// A point on the rotation arc that sweeps from tip `i` to tip `j` (in the
    /// plane whose normal is the third frame axis), parameter `t` in `0..=1`.
    fn arc_point(&self, i: usize, j: usize, t: f32, radius: f32) -> Vec3 {
        let ang = t * std::f32::consts::FRAC_PI_2;
        self.origin
            .add(self.axis(i).scale(ang.cos() * radius))
            .add(self.axis(j).scale(ang.sin() * radius))
    }

    /// The orange grab sphere position for the arc `(i, j)`: the MIDPOINT of the
    /// quarter arc (`t = 0.5`, the 45° bisector angle) at the arc radius, so the
    /// handle sits ON the drawn arc curve.
    fn arc_grab_point(&self, i: usize, j: usize, s: &Sizes) -> Vec3 {
        self.arc_point(i, j, 0.5, s.arc_rad)
    }

    fn draw_axis_arrow(
        &self,
        ov: &mut Overlay,
        s: &Sizes,
        i: usize,
        shaft_color: [f32; 4],
        head_color: [f32; 4],
    ) {
        let a = self.axis(i);
        let shaft_a = self.origin.add(a.scale(s.shaft_start));
        let base = self.origin.add(a.scale(s.axis_len - s.head_len));
        let tip = self.origin.add(a.scale(s.axis_len));
        // Silver rod shaft as a solid 3D tube (thick; per-element geometry since
        // the overlay line width is a single per-pass value).
        push_tube(ov, shaft_a, base, s.shaft_rad, shaft_color);
        // Orange arrowhead cone (side + base cap).
        push_cone(ov, base, tip, s.head_rad, head_color);
    }

    fn draw_arc(&self, ov: &mut Overlay, i: usize, j: usize, s: &Sizes, color: [f32; 4]) {
        let mut prev = self.arc_point(i, j, 0.0, s.arc_rad);
        for k in 1..=RING_SEGMENTS {
            let t = k as f32 / RING_SEGMENTS as f32;
            let cur = self.arc_point(i, j, t, s.arc_rad);
            ov.line(prev, cur, color);
            prev = cur;
        }
    }

    fn draw_center(&self, ov: &mut Overlay, s: &Sizes, color: [f32; 4]) {
        push_sphere(ov, self.origin, s.center_rad, color);
    }

    fn highlight(id: HandleId, base: [f32; 4], hovered: Option<HandleId>, active: Option<HandleId>) -> [f32; 4] {
        if active == Some(id) || hovered == Some(id) {
            C_GOLD
        } else {
            base
        }
    }
}

impl Gizmo for TransformGizmo {
    fn geometry(
        &self,
        camera: &GizmoCamera,
        hovered: Option<HandleId>,
        active: Option<HandleId>,
    ) -> Overlay {
        let s = self.sizes(camera);
        let mut ov = Overlay::new();

        let hl = |id, base| Self::highlight(id, base, hovered, active);

        // Rotation arcs — light-grey quarter arcs joining adjacent axis shafts
        // (the rounded-triangle silhouette), each with an orange grab sphere ON
        // the arc midpoint. Arc `(k, i, j)` rotates about axis `k`.
        for (k, i, j) in ARCS {
            let id = ring_handle(k);
            self.draw_arc(&mut ov, i, j, &s, hl(id, C_RING));
            push_sphere(&mut ov, self.arc_grab_point(i, j, &s), s.grab_rad, hl(id, C_DOT));
        }

        // Axis translate arrows — silver rod shaft, orange cone head.
        for (i, id) in [(0, HANDLE_AXIS_X), (1, HANDLE_AXIS_Y), (2, HANDLE_AXIS_Z)] {
            self.draw_axis_arrow(&mut ov, &s, i, hl(id, C_ROD), hl(id, C_ARROW));
        }

        // Center free-move handle — orange sphere.
        if self.show_center {
            self.draw_center(&mut ov, &s, hl(HANDLE_CENTER, C_CENTER));
        }

        ov
    }

    fn hit(&self, camera: &GizmoCamera, screen: [f32; 2]) -> Option<HandleId> {
        let s = self.sizes(camera);
        let ray = camera.ray_from_screen(screen[0], screen[1]);
        let line_thresh_px = 7.0_f32;

        // Candidates as (priority rank, pixel distance, id). Lower rank wins;
        // within a rank the nearest pixel distance wins. Rank 0 = axis/ring
        // lines + center; rank 1 = plane quads (so lines win when ambiguous).
        let mut best: Option<(u8, f32, HandleId)> = None;
        let mut consider = |rank: u8, dist_px: f32, id: HandleId| {
            match best {
                Some((br, bd, _)) if (br, bd) <= (rank, dist_px) => {}
                _ => best = Some((rank, dist_px, id)),
            }
        };

        // Center handle (rank 0): screen distance from the origin's projection.
        if self.show_center {
            if let Some(os) = camera.world_to_screen(self.origin) {
                let d = ((screen[0] - os[0]).powi(2) + (screen[1] - os[1]).powi(2)).sqrt();
                if d <= PX_CENTER_RAD + 2.0 {
                    consider(0, d, HANDLE_CENTER);
                }
            }
        }

        // Axis arrows (rank 0): ray-to-segment over the whole arrow.
        for (i, id) in [(0, HANDLE_AXIS_X), (1, HANDLE_AXIS_Y), (2, HANDLE_AXIS_Z)] {
            let (a, b) = self.axis_seg(camera, i);
            let d_px = ray.distance_to_segment(a, b) / s.px;
            if d_px <= line_thresh_px {
                consider(0, d_px, id);
            }
        }

        // Rotation handles (rank 0): grabbable along the drawn quarter arc OR on
        // the orange grab sphere at the arc midpoint (matching what the user sees).
        for (k, i, j) in ARCS {
            let id = ring_handle(k);
            let mut prev = self.arc_point(i, j, 0.0, s.arc_rad);
            let mut min_w = f32::INFINITY;
            for step in 1..=RING_SEGMENTS {
                let t = step as f32 / RING_SEGMENTS as f32;
                let cur = self.arc_point(i, j, t, s.arc_rad);
                let d = ray.distance_to_segment(prev, cur);
                if d < min_w {
                    min_w = d;
                }
                prev = cur;
            }
            // Also consider the inner grab sphere (screen distance).
            let grab = self.arc_grab_point(i, j, &s);
            let grab_px = camera
                .world_to_screen(grab)
                .map(|g| ((screen[0] - g[0]).powi(2) + (screen[1] - g[1]).powi(2)).sqrt())
                .unwrap_or(f32::INFINITY);
            let d_px = (min_w / s.px).min(grab_px.max(0.0) - PX_RING_GRAB_RAD).max(0.0);
            if (min_w / s.px) <= line_thresh_px || grab_px <= PX_RING_GRAB_RAD + 3.0 {
                consider(0, d_px, id);
            }
        }

        best.map(|(_, _, id)| id)
    }
}

// --- free helpers ----------------------------------------------------------

fn plane_point(ray: &Ray, p0: Vec3, n: Vec3) -> Option<Vec3> {
    ray.intersect_plane(p0, n).map(|t| ray.at(t))
}

fn set_comp(v: &mut Vec3, i: usize, val: f32) {
    match i {
        0 => v.x = val,
        1 => v.y = val,
        _ => v.z = val,
    }
}

/// The rotation-ring handle id for rotation about frame axis `k`.
fn ring_handle(k: usize) -> HandleId {
    match k {
        0 => HANDLE_RING_X,
        1 => HANDLE_RING_Y,
        _ => HANDLE_RING_Z,
    }
}

/// A radially-symmetric perpendicular basis `(u, v)` for a unit `axis`.
fn axis_basis(axis: Vec3) -> (Vec3, Vec3) {
    let u = axis.any_perp();
    let v = axis.cross(u).normalized();
    (u, v)
}

/// Push a solid 3D rod (open-ended tube) from `a` to `b` with world `radius`.
/// Used for the silver axis shafts — thick per-element geometry, since the
/// overlay line width is a single per-pass value and can't be varied per shaft.
fn push_tube(ov: &mut Overlay, a: Vec3, b: Vec3, radius: f32, color: [f32; 4]) {
    let axis = b.sub(a);
    if axis.length() < 1e-9 || radius <= 0.0 {
        return;
    }
    let (u, v) = axis_basis(axis.normalized());
    let ring = |center: Vec3, k: usize| -> Vec3 {
        let ang = (k as f32 / TUBE_SEGMENTS as f32) * std::f32::consts::TAU;
        center
            .add(u.scale(ang.cos() * radius))
            .add(v.scale(ang.sin() * radius))
    };
    for k in 0..TUBE_SEGMENTS {
        let a0 = ring(a, k);
        let a1 = ring(a, k + 1);
        let b0 = ring(b, k);
        let b1 = ring(b, k + 1);
        ov.tri(a0, b0, b1, color);
        ov.tri(a0, b1, a1, color);
    }
}

/// Push a filled arrowhead cone: apex at `tip`, base circle of world `radius`
/// centered at `base`, radially symmetric about `tip - base` (side + base cap).
fn push_cone(ov: &mut Overlay, base: Vec3, tip: Vec3, radius: f32, color: [f32; 4]) {
    let axis = tip.sub(base);
    if axis.length() < 1e-9 || radius <= 0.0 {
        return;
    }
    let (u, v) = axis_basis(axis.normalized());
    let ring = |k: usize| -> Vec3 {
        let ang = (k as f32 / CONE_SEGMENTS as f32) * std::f32::consts::TAU;
        base.add(u.scale(ang.cos() * radius))
            .add(v.scale(ang.sin() * radius))
    };
    let mut prev = ring(0);
    for k in 1..=CONE_SEGMENTS {
        let cur = ring(k);
        ov.tri(tip, prev, cur, color); // side
        ov.tri(base, cur, prev, color); // base cap
        prev = cur;
    }
}

/// Push a filled UV sphere of world `radius` at `center`. Flat-shaded facets;
/// the overlay shader's per-face shade gives the 3D read.
fn push_sphere(ov: &mut Overlay, center: Vec3, radius: f32, color: [f32; 4]) {
    if radius <= 0.0 {
        return;
    }
    let point = |ring: usize, sector: usize| -> Vec3 {
        let lat = std::f32::consts::PI * (ring as f32 / SPHERE_RINGS as f32) - std::f32::consts::FRAC_PI_2;
        let lon = std::f32::consts::TAU * (sector as f32 / SPHERE_SECTORS as f32);
        center.add(Vec3::new(
            lat.cos() * lon.cos() * radius,
            lat.cos() * lon.sin() * radius,
            lat.sin() * radius,
        ))
    };
    for r in 0..SPHERE_RINGS {
        for sct in 0..SPHERE_SECTORS {
            let p00 = point(r, sct);
            let p01 = point(r, sct + 1);
            let p10 = point(r + 1, sct);
            let p11 = point(r + 1, sct + 1);
            ov.tri(p00, p10, p11, color);
            ov.tri(p00, p11, p01, color);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::raster;

    /// Oblique orthographic camera so axes/rings are visually separated (avoids
    /// the axis-aligned degeneracy where an axis and a ring project to the same
    /// screen line).
    fn oblique_cam(vp: f32) -> GizmoCamera {
        let eye = [8.0, -10.0, 7.0];
        let view_proj = raster::test_view_proj(eye, [0.0, 0.0, 0.0], vp, vp);
        let fwd = Vec3::new(-eye[0], -eye[1], -eye[2]).normalized();
        GizmoCamera {
            view_proj,
            eye: Vec3::from(eye),
            forward: fwd,
            // test_view_proj's up for this oblique pose (Z-up heuristic).
            up: Vec3::Z,
            viewport: [vp, vp],
            orthographic: true,
        }
    }

    /// Straight-down (-Z) orthographic camera: world +X → screen right, world
    /// +Y → screen up. Handy for deterministic drag-math tests.
    fn topdown_cam(vp: f32) -> GizmoCamera {
        let eye = [0.0, 0.0, 10.0];
        let view_proj = raster::test_view_proj(eye, [0.0, 0.0, 0.0], vp, vp);
        GizmoCamera {
            view_proj,
            eye: Vec3::from(eye),
            forward: Vec3::new(0.0, 0.0, -1.0),
            // test_view_proj's up for the near-vertical -Z pose (+Y fallback).
            up: Vec3::Y,
            viewport: [vp, vp],
            orthographic: true,
        }
    }

    #[test]
    fn hit_picks_the_axis_the_ray_passes_near() {
        let cam = oblique_cam(240.0);
        let gz = TransformGizmo::default();
        // Point on the +X arrow shaft out past the rings, projected to screen
        // (a mid-shaft sample can coincide with a ring crossing).
        let (a, b) = gz.axis_seg(&cam, 0);
        let p = a.lerp(b, 0.82);
        let s = cam.world_to_screen(p).unwrap();
        assert_eq!(gz.hit(&cam, s), Some(HANDLE_AXIS_X), "screen {s:?}");

        // And the +Y arrow.
        let (a, b) = gz.axis_seg(&cam, 1);
        let p = a.lerp(b, 0.82);
        let s = cam.world_to_screen(p).unwrap();
        assert_eq!(gz.hit(&cam, s), Some(HANDLE_AXIS_Y));
    }

    #[test]
    fn hit_is_none_in_empty_space() {
        let cam = oblique_cam(240.0);
        let gz = TransformGizmo::default();
        // Far corner — well outside the ~90px gizmo centered at the viewport.
        assert_eq!(gz.hit(&cam, [6.0, 6.0]), None);
        assert_eq!(gz.hit(&cam, [234.0, 234.0]), None);
    }

    #[test]
    fn hit_picks_a_ring() {
        let cam = oblique_cam(240.0);
        let gz = TransformGizmo::default();
        // The Z-rotation arc joins the X and Y tips (in the XY plane); sample a
        // point midway along it.
        let s = gz.sizes(&cam);
        let p = gz.arc_point(0, 1, 0.5, s.arc_rad);
        let sp = cam.world_to_screen(p).unwrap();
        assert_eq!(gz.hit(&cam, sp), Some(HANDLE_RING_Z));
    }

    #[test]
    fn axis_translate_moves_positive_x_for_a_positive_x_drag() {
        let cam = topdown_cam(200.0);
        let gz = TransformGizmo::default();
        let center = [100.0, 100.0];
        let start = cam.ray_from_screen(center[0], center[1]);
        // Move the pointer 40px to screen-right (world +X for this camera).
        let current = cam.ray_from_screen(center[0] + 40.0, center[1]);
        let d = gz.axis_translate(&cam, 0, start, current);
        assert!(d.x > 0.0, "expected +X translate, got {d:?}");
        assert!(d.y.abs() < 1e-3 && d.z.abs() < 1e-3, "off-axis leak {d:?}");
        // Magnitude should be ~ 40px * world_per_pixel.
        let expect = 40.0 * cam.world_per_pixel(gz.origin);
        assert!((d.x - expect).abs() < 0.05 * expect.max(1.0), "d.x={} expect={}", d.x, expect);
    }

    #[test]
    fn plane_translate_reports_both_in_plane_components() {
        let cam = topdown_cam(200.0);
        let gz = TransformGizmo::default();
        let center = [100.0, 100.0];
        let start = cam.ray_from_screen(center[0], center[1]);
        // +30px right (world +X), -20px screen-y (world +Y, since y is down).
        let current = cam.ray_from_screen(center[0] + 30.0, center[1] - 20.0);
        let d = gz.plane_translate(0, 1, start, current);
        assert!(d.x > 0.0 && d.y > 0.0, "expected +X,+Y in-plane move, got {d:?}");
        assert!(d.z.abs() < 1e-3, "no normal-axis component expected {d:?}");
    }

    #[test]
    fn ring_rotate_returns_expected_angle() {
        let cam = topdown_cam(200.0);
        let gz = TransformGizmo::default();
        let center = [100.0, 100.0];
        // Start ray hits +X, current ray hits +Y → +90° about +Z.
        let start = cam.ray_from_screen(center[0] + 40.0, center[1]);
        let current = cam.ray_from_screen(center[0], center[1] - 40.0);
        let ang = gz.ring_rotate(2, start, current);
        assert!(
            (ang - std::f32::consts::FRAC_PI_2).abs() < 1e-2,
            "expected +pi/2, got {ang}"
        );
        // Reverse pair → -90°.
        let ang2 = gz.ring_rotate(2, current, start);
        assert!((ang2 + std::f32::consts::FRAC_PI_2).abs() < 1e-2, "got {ang2}");
    }

    #[test]
    fn drag_delta_dispatches_by_handle() {
        let cam = topdown_cam(200.0);
        let gz = TransformGizmo::default();
        let c = [100.0, 100.0];
        let start = cam.ray_from_screen(c[0], c[1]);
        let cur = cam.ray_from_screen(c[0] + 20.0, c[1]);
        match gz.drag_delta(&cam, HANDLE_AXIS_X, start, cur) {
            DragDelta::Translate(v) => assert!(v.x > 0.0),
            other => panic!("expected translate, got {other:?}"),
        }
        let cur_rot = cam.ray_from_screen(c[0], c[1] - 20.0);
        let start_rot = cam.ray_from_screen(c[0] + 20.0, c[1]);
        match gz.drag_delta(&cam, HANDLE_RING_Z, start_rot, cur_rot) {
            DragDelta::Rotate { axis_index, radians } => {
                assert_eq!(axis_index, 2);
                assert!(radians > 0.0);
            }
            other => panic!("expected rotate, got {other:?}"),
        }
        assert_eq!(gz.drag_delta(&cam, HANDLE_NONE, start, cur), DragDelta::None);
    }

    #[test]
    fn geometry_emits_lines_and_tris() {
        let cam = oblique_cam(240.0);
        let gz = TransformGizmo::default();
        let ov = gz.geometry(&cam, Some(HANDLE_AXIS_X), None);
        assert!(!ov.lines.is_empty(), "expected line geometry (rotation arcs)");
        assert!(!ov.tris.is_empty(), "expected triangle geometry (shafts/cones/spheres)");
        // The hovered X axis shaft + cone are now solid geometry, so its gold
        // highlight lands on TRIS (the arcs are the only line geometry).
        let gold = ov
            .tris
            .iter()
            .any(|v| (v.color[0] - C_GOLD[0]).abs() < 1e-3 && (v.color[1] - C_GOLD[1]).abs() < 1e-3);
        assert!(gold, "hovered handle should be highlighted gold");
    }

    #[test]
    fn handles_are_screen_constant_across_zoom() {
        // Two "zoom" levels simulated via viewport size: with the same world
        // view volume, a larger viewport halves world_per_pixel, so the gizmo's
        // WORLD size shrinks to keep its SCREEN size fixed. Use a top-down
        // camera so the +X arrow lies in the screen plane (no foreshortening),
        // making the projected span equal the target arrow pixel length.
        let cam_a = topdown_cam(240.0);
        let cam_b = topdown_cam(480.0);
        let gz = TransformGizmo::default();

        let span = |cam: &GizmoCamera| {
            let (_a, tip) = gz.axis_seg(cam, 0);
            let o = cam.world_to_screen(gz.origin).unwrap();
            let t = cam.world_to_screen(tip).unwrap();
            ((t[0] - o[0]).powi(2) + (t[1] - o[1]).powi(2)).sqrt()
        };
        let sa = span(&cam_a);
        let sb = span(&cam_b);
        assert!((sa - sb).abs() < 1.0, "screen span not constant: {sa} vs {sb}");
        // And it should be near our target arrow pixel length.
        assert!((sa - PX_AXIS_LEN).abs() < 3.0, "arrow span {sa}px");
    }

    #[test]
    fn cone_base_sits_outside_the_rotation_arc() {
        // Fix 1: the arrowhead cone must start OUTSIDE the rotation arcs so the
        // white arcs never cut through the orange cones. The cone BASE is at
        // `axis_len - head_len`; the arc is at `arc_rad`. The base must clear the
        // arc with a few px of gap.
        let cam = topdown_cam(240.0);
        let gz = TransformGizmo::default();
        let s = gz.sizes(&cam);
        let cone_base_dist = s.axis_len - s.head_len; // where the cone begins
        assert!(
            cone_base_dist > s.arc_rad + 4.0 * s.px,
            "cone base ({cone_base_dist}) must clear the arc ({}) by >4px",
            s.arc_rad
        );
        // The cone TIP is past the base (the cone pokes outward beyond the arc).
        assert!(s.axis_len > cone_base_dist, "cone tip past its base");
    }

    #[test]
    fn rotation_grab_sphere_sits_on_the_arc() {
        // Fix 2: each rotation grab sphere sits at the MIDPOINT of its quarter arc
        // — on the drawn arc curve (radius = arc_rad), not floating on the inner
        // bisector.
        let cam = oblique_cam(240.0);
        let gz = TransformGizmo::default();
        let s = gz.sizes(&cam);
        for (_, i, j) in ARCS {
            let grab = gz.arc_grab_point(i, j, &s);
            // On the arc curve: identical to the arc's mid-sweep sample…
            let mid = gz.arc_point(i, j, 0.5, s.arc_rad);
            assert!(grab.sub(mid).length() < 1e-5, "grab off the arc mid: {grab:?}");
            // …and exactly `arc_rad` from the origin (a point on the circle).
            let r = grab.sub(gz.origin).length();
            assert!((r - s.arc_rad).abs() < 1e-4, "grab radius {r} != arc_rad {}", s.arc_rad);
        }
        // A click on a grab sphere's screen projection still resolves to its ring.
        let s = gz.sizes(&cam);
        let grab = gz.arc_grab_point(0, 1, &s); // the Z-rotation arc (about ez)
        let sp = cam.world_to_screen(grab).unwrap();
        assert_eq!(gz.hit(&cam, sp), Some(HANDLE_RING_Z), "grab-sphere click picks its ring");
    }
}