BREP_gizmos 0.2.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
//! Datum / plane / axis / coordinate-frame display builders — the engine
//! overlay geometry that replaces the retired `editorDisplay` bodies for
//! datum features (`PlaneFeature`,
//! `DatiumFeature`) and the world-axis helper
//! (`axisHelpers`).
//!
//! Each builder emits an [`Overlay`] (world-space colored triangles + lines)
//! that the render engine's overlay pass draws over the shaded solids. No
//! kernel/GPU dependency — pure geometry + a `Gizmo` hit-test impl.
//!
//! # What SceneMap data feeds each builder (integration note)
//!
//! The engine's datum/plane/axis display path is a mechanical map from the
//! resident Rust `SceneMap` (`rust-kernel .../feature_pipeline/mod.rs`) to these
//! functions — no legacy overlay bodies:
//!
//! - **PLANE / DATUM plane** — `SceneMap.frames: HashMap<String, Frame>` where
//!   `Frame { origin, x_axis, y_axis, z_axis }`. Call
//!   [`datum_plane`]`(frame.origin, frame.x_axis, frame.y_axis, extent, color)`.
//!   `extent` is the plane's display size in world units (the previous app
//!   rendered planes at a fixed 5×5 → extent `5.0`; a future
//!   sized plane passes its own extent). When the feature has no meaningful
//!   world extent, use [`datum_plane_screen`] for a screen-constant card.
//!
//! - **DATUM coordinate frame (triad)** — the same `Frame`. Call
//!   [`datum_frame`]`(frame.origin, frame.x_axis, frame.y_axis, frame.z_axis,
//!   screen_px, camera)`. This is the reusable X/Y/Z triad (red/green/blue,
//!   screen-constant) for a `DATUM` coordinate system and for the
//!   transform-gizmo center.
//!
//! - **Revolve / sweep axis, construction line** — `SceneMap.axes:
//!   HashMap<String, Axis>` where `Axis { point, direction }`. Call
//!   [`datum_axis`]`(axis.point, axis.direction, length, color)`. `length` is
//!   the world span to draw (e.g. the operand's bounding extent along the axis).
//!
//! - **World axes helper** (`__WORLD_AXES__`) — no scene data; call
//!   [`world_axes`]`(camera, length_px)` for the origin triad.
//!
//! For selection/highlight the engine wraps a datum in [`DatumPlane`] /
//! [`DatumAxis`] (each carries one body [`HandleId`]) and calls [`Gizmo::hit`]
//! to know when the pointer is over the datum.
//!
//! # Screen-constant sizing
//!
//! A "screen-constant" widget stays a fixed pixel size regardless of zoom.
//! We size it in world units as `camera.world_per_pixel(anchor) * pixels`,
//! where [`GizmoCamera::world_per_pixel`] returns the world distance that
//! projects to one CSS pixel at the anchor point. Because it scales inversely
//! with zoom, the projected geometry keeps a constant on-screen size. The
//! triad ([`datum_frame`] / [`world_axes`]) is always screen-constant; the
//! plane card is world-sized ([`datum_plane`]) or screen-constant
//! ([`datum_plane_screen`]) — the two ways the plane extent can be sourced.

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

/// Datum X axis color (red), matching `DEFAULT_AXIS_COLORS.x` (`#ff4d4d`).
pub const AXIS_X_COLOR: [f32; 4] = [1.0, 0.302, 0.302, 1.0];
/// Datum Y axis color (green), matching `DEFAULT_AXIS_COLORS.y` (`#4dff4d`).
pub const AXIS_Y_COLOR: [f32; 4] = [0.302, 1.0, 0.302, 1.0];
/// Datum Z axis color (blue), matching `DEFAULT_AXIS_COLORS.z` (`#4d7dff`).
pub const AXIS_Z_COLOR: [f32; 4] = [0.302, 0.490, 1.0, 1.0];
/// Default datum-plane green, matching `CADmaterials.PLANE.BASE` (`#2eff2e`).
pub const PLANE_COLOR: [f32; 4] = [0.180, 1.0, 0.180, 1.0];

/// Default full screen extent (CSS px) for a screen-constant plane card.
pub const DEFAULT_PLANE_SCREEN_PX: f32 = 140.0;
/// Default triad axis screen length (CSS px), matching `DEFAULT_AXIS_HELPER_PX`.
pub const DEFAULT_FRAME_PX: f32 = 70.0;
/// Pointer pick tolerance (CSS px) for datum hit-testing.
pub const PICK_PX: f32 = 6.0;

// --- plane -----------------------------------------------------------------

/// A bounded datum plane sized in **world units**. `size` is the full edge
/// length (a `size × size` square centered on `origin`, spanning the plane's
/// `x_axis`/`y_axis`). Emits, in order: the two fill triangles (semi-transparent
/// — the fill color's alpha is reduced), the four border segments (the loop),
/// and a small right-angle corner marker that fixes the +x/+y orientation.
///
/// `x_axis`/`y_axis` are expected orthonormal in-plane axes (a `Frame`'s
/// `x_axis`/`y_axis`); they are used as-is (no re-orthonormalization).
pub fn datum_plane(
    origin: Vec3,
    x_axis: Vec3,
    y_axis: Vec3,
    size: f32,
    color: [f32; 4],
) -> Overlay {
    datum_plane_half(origin, x_axis, y_axis, size * 0.5, color)
}

/// A bounded datum plane whose on-screen size is **constant** (`screen_px` full
/// edge length in CSS pixels) regardless of zoom, anchored at `origin`. Use
/// when the datum feature has no intrinsic world extent. Same geometry layout
/// as [`datum_plane`].
pub fn datum_plane_screen(
    origin: Vec3,
    x_axis: Vec3,
    y_axis: Vec3,
    screen_px: f32,
    color: [f32; 4],
    camera: &GizmoCamera,
) -> Overlay {
    let half = camera.world_per_pixel(origin) * screen_px * 0.5;
    datum_plane_half(origin, x_axis, y_axis, half, color)
}

/// Shared plane builder: `half` is the half-edge length in world units.
fn datum_plane_half(
    origin: Vec3,
    x_axis: Vec3,
    y_axis: Vec3,
    half: f32,
    color: [f32; 4],
) -> Overlay {
    let mut ov = Overlay::new();
    let hx = x_axis.scale(half);
    let hy = y_axis.scale(half);
    // Corners, CCW in (x,y): 00 = (-x,-y), 10 = (+x,-y), 11 = (+x,+y), 01 = (-x,+y).
    let c00 = origin.sub(hx).sub(hy);
    let c10 = origin.add(hx).sub(hy);
    let c11 = origin.add(hx).add(hy);
    let c01 = origin.sub(hx).add(hy);

    // Semi-transparent fill (two triangles). Dim + low-alpha so the card reads
    // as a translucent overlay rather than an opaque face.
    let fill = with_alpha(scale_rgb(color, 0.55), (color[3] * 0.28).min(0.28));
    ov.tri(c00, c10, c11, fill);
    ov.tri(c00, c11, c01, fill);

    // Border loop (4 segments), pushed FIRST among the lines.
    let border = [color[0], color[1], color[2], 1.0];
    ov.line(c00, c10, border);
    ov.line(c10, c11, border);
    ov.line(c11, c01, border);
    ov.line(c01, c00, border);

    // Corner orientation marker: a small right-angle at the (-x,-y) corner,
    // ticking toward +x and +y so the plane's local frame is legible.
    let m = half * 0.28;
    ov.line(c00, c00.add(x_axis.scale(m)), border);
    ov.line(c00, c00.add(y_axis.scale(m)), border);

    ov
}

// --- axis ------------------------------------------------------------------

/// A datum axis: a line segment from `point` extending `length` world units
/// along `direction`, with a small cone arrowhead at the `+` end (the `direction`
/// end). For revolve/sweep axes and construction lines. The shaft is the first
/// (only) line segment; the arrowhead is emitted as triangles.
pub fn datum_axis(point: Vec3, direction: Vec3, length: f32, color: [f32; 4]) -> Overlay {
    let mut ov = Overlay::new();
    let d = direction.normalized();
    let end = point.add(d.scale(length));
    ov.line(point, end, color); // shaft (first line segment)
    let head = length * 0.14;
    push_cone(&mut ov, end, d, head, head * 0.45, color, 12);
    ov
}

// --- coordinate frame (triad) ----------------------------------------------

/// A coordinate-frame triad: three **screen-constant** colored axes from
/// `origin` (X red, Y green, Z blue), each `screen_len_px` CSS pixels long, plus
/// a small origin marker (an octahedron "diamond"). The reusable triad for a
/// DATUM coordinate system and the transform-gizmo center.
///
/// The three axis shafts are the first three line segments (in X, Y, Z order);
/// arrowheads and the origin marker follow as triangles.
pub fn datum_frame(
    origin: Vec3,
    x: Vec3,
    y: Vec3,
    z: Vec3,
    screen_len_px: f32,
    camera: &GizmoCamera,
) -> Overlay {
    let mut ov = Overlay::new();
    let len = camera.world_per_pixel(origin) * screen_len_px;
    let axes = [
        (x.normalized(), AXIS_X_COLOR),
        (y.normalized(), AXIS_Y_COLOR),
        (z.normalized(), AXIS_Z_COLOR),
    ];
    // Shafts first (tests read these three segments).
    for (dir, col) in axes {
        ov.line(origin, origin.add(dir.scale(len)), col);
    }
    // Arrowheads.
    let head = len * 0.16;
    for (dir, col) in axes {
        push_cone(&mut ov, origin.add(dir.scale(len)), dir, head, head * 0.5, col, 10);
    }
    // Origin marker (small diamond).
    let marker = (len * 0.08).max(camera.world_per_pixel(origin) * 3.0);
    push_octahedron(&mut ov, origin, marker, [0.88, 0.88, 0.92, 1.0]);
    ov
}

/// The world-axis helper (`__WORLD_AXES__`): a screen-constant X/Y/Z triad at
/// the world origin. `length_px` is the axis length in CSS pixels.
pub fn world_axes(camera: &GizmoCamera, length_px: f32) -> Overlay {
    datum_frame(Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z, length_px, camera)
}

// --- selectable wrappers (Gizmo impls) -------------------------------------

/// A selectable datum plane for hit-testing/highlight. `size` is the full world
/// edge length, or `None` for a screen-constant card. `handle` is the body
/// [`HandleId`] returned from [`Gizmo::hit`].
#[derive(Debug, Clone, Copy)]
pub struct DatumPlane {
    pub origin: Vec3,
    pub x_axis: Vec3,
    pub y_axis: Vec3,
    pub size: Option<f32>,
    pub color: [f32; 4],
    pub handle: HandleId,
}

impl DatumPlane {
    /// The plane normal (`x_axis × y_axis`, normalized).
    pub fn normal(&self) -> Vec3 {
        self.x_axis.cross(self.y_axis).normalized()
    }

    /// World half-edge length for the current camera (world- or screen-sized).
    /// The SAME expression [`datum_plane`] / [`datum_plane_screen`] draw with, read
    /// off the LIVE camera on every call — so the pickable card can never drift
    /// from the drawn one across a zoom (no bake).
    fn half(&self, camera: &GizmoCamera) -> f32 {
        match self.size {
            Some(s) => s * 0.5,
            None => camera.world_per_pixel(self.origin) * DEFAULT_PLANE_SCREEN_PX * 0.5,
        }
    }

    /// The world-space point where the pointer ray crosses this plane, but ONLY
    /// inside the DRAWN card (`|u| <= half`, `|v| <= half`) — a construction plane
    /// is mathematically infinite, yet only the rectangle the user can see is
    /// pickable. `None` when the ray misses the card, runs parallel to the plane,
    /// or crosses it behind the eye.
    ///
    /// Either FACE of the card picks: the test is on the ray parameter, not on the
    /// normal's sign, so a plane viewed from its reverse side is still selectable.
    /// [`Gizmo::hit`] is exactly this test — one bounds implementation, shared.
    pub fn hit_point(&self, camera: &GizmoCamera, screen: [f32; 2]) -> Option<Vec3> {
        let ray = camera.ray_from_screen(screen[0], screen[1]);
        let t = ray.intersect_plane(self.origin, self.normal())?;
        if t < 0.0 {
            return None;
        }
        let p = ray.at(t);
        let rel = p.sub(self.origin);
        let u = rel.dot(self.x_axis.normalized());
        let v = rel.dot(self.y_axis.normalized());
        let half = self.half(camera);
        (u.abs() <= half && v.abs() <= half).then_some(p)
    }
}

impl Gizmo for DatumPlane {
    fn geometry(
        &self,
        camera: &GizmoCamera,
        hovered: Option<HandleId>,
        active: Option<HandleId>,
    ) -> Overlay {
        let hot = hovered == Some(self.handle) || active == Some(self.handle);
        let color = if hot { brighten(self.color) } else { self.color };
        match self.size {
            Some(s) => datum_plane(self.origin, self.x_axis, self.y_axis, s, color),
            None => datum_plane_screen(
                self.origin,
                self.x_axis,
                self.y_axis,
                DEFAULT_PLANE_SCREEN_PX,
                color,
                camera,
            ),
        }
    }

    fn hit(&self, camera: &GizmoCamera, screen: [f32; 2]) -> Option<HandleId> {
        self.hit_point(camera, screen).map(|_| self.handle)
    }
}

/// A selectable datum axis for hit-testing/highlight. `handle` is the body
/// [`HandleId`] returned from [`Gizmo::hit`].
#[derive(Debug, Clone, Copy)]
pub struct DatumAxis {
    pub point: Vec3,
    pub direction: Vec3,
    pub length: f32,
    pub color: [f32; 4],
    pub handle: HandleId,
}

impl DatumAxis {
    fn end(&self) -> Vec3 {
        self.point.add(self.direction.normalized().scale(self.length))
    }
}

impl Gizmo for DatumAxis {
    fn geometry(
        &self,
        _camera: &GizmoCamera,
        hovered: Option<HandleId>,
        active: Option<HandleId>,
    ) -> Overlay {
        let hot = hovered == Some(self.handle) || active == Some(self.handle);
        let color = if hot { brighten(self.color) } else { self.color };
        datum_axis(self.point, self.direction, self.length, color)
    }

    fn hit(&self, camera: &GizmoCamera, screen: [f32; 2]) -> Option<HandleId> {
        let ray = camera.ray_from_screen(screen[0], screen[1]);
        let end = self.end();
        let world_dist = ray.distance_to_segment(self.point, end);
        let mid = self.point.lerp(end, 0.5);
        let px = world_dist / camera.world_per_pixel(mid);
        if px <= PICK_PX {
            Some(self.handle)
        } else {
            None
        }
    }
}

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

/// Push a cone (arrowhead) as triangles: apex at `apex`, base ring of `radius`
/// centered `len` back along `-dir`. `dir` must be unit.
fn push_cone(
    ov: &mut Overlay,
    apex: Vec3,
    dir: Vec3,
    len: f32,
    radius: f32,
    color: [f32; 4],
    segments: usize,
) {
    let base = apex.sub(dir.scale(len));
    let p1 = dir.any_perp();
    let p2 = dir.cross(p1).normalized();
    let seg = segments.max(3);
    for i in 0..seg {
        let a0 = (i as f32) / (seg as f32) * std::f32::consts::TAU;
        let a1 = ((i + 1) as f32) / (seg as f32) * std::f32::consts::TAU;
        let r0 = base.add(p1.scale(a0.cos() * radius)).add(p2.scale(a0.sin() * radius));
        let r1 = base.add(p1.scale(a1.cos() * radius)).add(p2.scale(a1.sin() * radius));
        ov.tri(apex, r0, r1, color); // side
        ov.tri(base, r1, r0, color); // base cap
    }
}

/// Push a small octahedron ("diamond") marker centered at `center`, with
/// vertices at `center ± axis*half` on each world axis (8 triangular faces).
fn push_octahedron(ov: &mut Overlay, center: Vec3, half: f32, color: [f32; 4]) {
    let px = center.add(Vec3::X.scale(half));
    let nx = center.sub(Vec3::X.scale(half));
    let py = center.add(Vec3::Y.scale(half));
    let ny = center.sub(Vec3::Y.scale(half));
    let pz = center.add(Vec3::Z.scale(half));
    let nz = center.sub(Vec3::Z.scale(half));
    let faces = [
        (px, py, pz),
        (py, nx, pz),
        (nx, ny, pz),
        (ny, px, pz),
        (py, px, nz),
        (nx, py, nz),
        (ny, nx, nz),
        (px, ny, nz),
    ];
    for (a, b, c) in faces {
        ov.tri(a, b, c, color);
    }
}

fn scale_rgb(c: [f32; 4], s: f32) -> [f32; 4] {
    [c[0] * s, c[1] * s, c[2] * s, c[3]]
}
fn with_alpha(c: [f32; 4], a: f32) -> [f32; 4] {
    [c[0], c[1], c[2], a]
}
fn brighten(c: [f32; 4]) -> [f32; 4] {
    [
        (c[0] * 1.35 + 0.1).min(1.0),
        (c[1] * 1.35 + 0.1).min(1.0),
        (c[2] * 1.35 + 0.1).min(1.0),
        c[3],
    ]
}

// --- tests -----------------------------------------------------------------

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

    /// Local ortho world→clip builder with a tunable `half` span (two of these
    /// at different `half` = two zoom levels), mirroring `raster::test_view_proj`
    /// but parameterized so screen-constancy can be probed.
    fn ortho_vp(eye: Vec3, target: Vec3, w: f32, h: f32, half: f32) -> [[f32; 4]; 4] {
        let fwd = target.sub(eye).normalized();
        let up = if fwd.z.abs() > 0.9 { Vec3::Y } else { Vec3::Z };
        let right = fwd.cross(up).normalized();
        let u = right.cross(fwd).normalized();
        let view = [
            [right.x, u.x, -fwd.x, 0.0],
            [right.y, u.y, -fwd.y, 0.0],
            [right.z, u.z, -fwd.z, 0.0],
            [-right.dot(eye), -u.dot(eye), fwd.dot(eye), 1.0],
        ];
        let aspect = w / h;
        let (l, r, b, t) = (-half * aspect, half * aspect, -half, half);
        let (near, far) = (0.01f32, 100.0f32);
        let ortho = [
            [2.0 / (r - l), 0.0, 0.0, 0.0],
            [0.0, 2.0 / (t - b), 0.0, 0.0],
            [0.0, 0.0, -1.0 / (far - near), 0.0],
            [-(r + l) / (r - l), -(t + b) / (t - b), -near / (far - near), 1.0],
        ];
        mat_mul(&ortho, &view)
    }

    fn mat_mul(a: &[[f32; 4]; 4], b: &[[f32; 4]; 4]) -> [[f32; 4]; 4] {
        let mut out = [[0.0f32; 4]; 4];
        for col in 0..4 {
            for row in 0..4 {
                let mut s = 0.0;
                for k in 0..4 {
                    s += a[k][row] * b[col][k];
                }
                out[col][row] = s;
            }
        }
        out
    }

    /// Isometric camera at a given zoom (`half`), square 200x200 viewport.
    fn iso_cam(half: f32) -> GizmoCamera {
        let eye = Vec3::new(10.0, 10.0, 10.0);
        let target = Vec3::ZERO;
        let fwd = target.sub(eye).normalized();
        GizmoCamera {
            view_proj: ortho_vp(eye, target, 200.0, 200.0, half),
            eye,
            forward: fwd,
            // ortho_vp's up for this oblique pose (Z-up heuristic).
            up: Vec3::Z,
            viewport: [200.0, 200.0],
            orthographic: true,
        }
    }

    /// Straight-down (-Z) camera for plane hit-testing; world XY maps cleanly to
    /// screen.
    fn topdown_cam(half: f32) -> GizmoCamera {
        let eye = Vec3::new(0.0, 0.0, 10.0);
        let target = Vec3::ZERO;
        let fwd = target.sub(eye).normalized();
        GizmoCamera {
            view_proj: ortho_vp(eye, target, 200.0, 200.0, half),
            eye,
            forward: fwd,
            // ortho_vp's up for the near-vertical -Z pose (+Y fallback).
            up: Vec3::Y,
            viewport: [200.0, 200.0],
            orthographic: true,
        }
    }

    fn seg_screen_len(ov: &Overlay, seg: usize, cam: &GizmoCamera) -> f32 {
        let a = cam.world_to_screen(Vec3::from(ov.lines[seg * 2].pos)).unwrap();
        let b = cam.world_to_screen(Vec3::from(ov.lines[seg * 2 + 1].pos)).unwrap();
        ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)).sqrt()
    }

    #[test]
    fn plane_emits_two_tris_and_border_in_plane() {
        let origin = Vec3::new(1.0, 2.0, 3.0);
        let (x, y) = (Vec3::X, Vec3::Y);
        let ov = datum_plane(origin, x, y, 4.0, PLANE_COLOR);

        // Exactly two fill triangles (the quad).
        assert_eq!(ov.tris.len(), 6, "expected 2 tris (6 verts)");

        // At least the four border segments (border loop) are present.
        assert!(ov.lines.len() >= 8, "expected >= 4 border segments");

        // First four segments form a closed border loop over the four corners.
        let half = 2.0f32;
        let c00 = origin.sub(x.scale(half)).sub(y.scale(half));
        let c10 = origin.add(x.scale(half)).sub(y.scale(half));
        let c11 = origin.add(x.scale(half)).add(y.scale(half));
        let c01 = origin.sub(x.scale(half)).add(y.scale(half));
        let expect = [(c00, c10), (c10, c11), (c11, c01), (c01, c00)];
        for (i, (a, b)) in expect.iter().enumerate() {
            let pa = Vec3::from(ov.lines[i * 2].pos);
            let pb = Vec3::from(ov.lines[i * 2 + 1].pos);
            assert!(pa.sub(*a).length() < 1e-5, "border {i} start");
            assert!(pb.sub(*b).length() < 1e-5, "border {i} end");
        }

        // Every triangle vertex and every line vertex lies in the plane
        // (x,y): normal Z, so z == origin.z.
        let n = x.cross(y).normalized();
        for v in &ov.tris {
            let d = Vec3::from(v.pos).sub(origin).dot(n);
            assert!(d.abs() < 1e-5, "tri vert off-plane by {d}");
        }
        for v in &ov.lines {
            let d = Vec3::from(v.pos).sub(origin).dot(n);
            assert!(d.abs() < 1e-5, "line vert off-plane by {d}");
        }
    }

    #[test]
    fn axis_line_endpoints_correct() {
        let point = Vec3::new(0.0, 0.0, 1.0);
        let dir = Vec3::new(0.0, 0.0, 1.0);
        let ov = datum_axis(point, dir, 5.0, AXIS_Z_COLOR);
        // Shaft is the first (and only) line segment.
        assert_eq!(ov.lines.len(), 2, "one shaft segment");
        let a = Vec3::from(ov.lines[0].pos);
        let b = Vec3::from(ov.lines[1].pos);
        assert!(a.sub(point).length() < 1e-6, "start at point");
        assert!(b.sub(Vec3::new(0.0, 0.0, 6.0)).length() < 1e-6, "end at point+dir*len");
        // Arrowhead present (a cone of triangles).
        assert!(ov.tris.len() >= 9, "arrowhead cone tris");
    }

    #[test]
    fn frame_axes_equal_and_screen_constant() {
        let cam1 = iso_cam(6.0); // zoom level A
        let cam2 = iso_cam(3.0); // zoom level B (2x closer)
        let px = 40.0f32;
        let f1 = datum_frame(Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z, px, &cam1);
        let f2 = datum_frame(Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z, px, &cam2);

        let l1 = [
            seg_screen_len(&f1, 0, &cam1),
            seg_screen_len(&f1, 1, &cam1),
            seg_screen_len(&f1, 2, &cam1),
        ];
        let l2 = [
            seg_screen_len(&f2, 0, &cam2),
            seg_screen_len(&f2, 1, &cam2),
            seg_screen_len(&f2, 2, &cam2),
        ];

        // The three axes have ~equal screen length (isometric foreshortening is
        // identical for X/Y/Z).
        assert!((l1[0] - l1[1]).abs() < 1.0, "X vs Y len: {:?}", l1);
        assert!((l1[1] - l1[2]).abs() < 1.0, "Y vs Z len: {:?}", l1);

        // Same axis is screen-constant across the two zoom levels.
        for i in 0..3 {
            assert!(
                (l1[i] - l2[i]).abs() < 1.0,
                "axis {i} screen length not constant across zoom: {} vs {}",
                l1[i],
                l2[i]
            );
        }

        // Sanity: nonzero and within the expected foreshortened band of px.
        for i in 0..3 {
            assert!(l1[i] > 0.5 * px && l1[i] < px + 1.0, "axis {i} len {}", l1[i]);
        }
    }

    #[test]
    fn plane_hit_inside_and_outside() {
        let cam = topdown_cam(6.0);
        let plane = DatumPlane {
            origin: Vec3::ZERO,
            x_axis: Vec3::X,
            y_axis: Vec3::Y,
            size: Some(5.0),
            color: PLANE_COLOR,
            handle: 7,
        };
        // Ray through the viewport center pierces the quad center.
        assert_eq!(plane.hit(&cam, [100.0, 100.0]), Some(7));
        // A ray near the screen edge lands well outside the 5-unit quad.
        assert_eq!(plane.hit(&cam, [196.0, 100.0]), None);
    }

    #[test]
    fn axis_hit_near_and_far() {
        let cam = topdown_cam(6.0);
        // Axis along +X through origin, in the z=0 plane the camera looks down on.
        let axis = DatumAxis {
            point: Vec3::new(-2.0, 0.0, 0.0),
            direction: Vec3::X,
            length: 4.0,
            color: AXIS_X_COLOR,
            handle: 9,
        };
        // Center pixel projects onto the axis → hit.
        assert_eq!(axis.hit(&cam, [100.0, 100.0]), Some(9));
        // A pixel far off the axis in screen-y → miss.
        assert_eq!(axis.hit(&cam, [100.0, 40.0]), None);
    }

    #[test]
    fn world_axes_is_a_triad() {
        let cam = iso_cam(6.0);
        let ov = world_axes(&cam, DEFAULT_FRAME_PX);
        // Three axis shafts (first three line segments).
        assert!(ov.lines.len() >= 6, "three shaft segments");
        // Colored X/Y/Z (red/green/blue) on the three shafts.
        assert_eq!(ov.lines[0].color, AXIS_X_COLOR);
        assert_eq!(ov.lines[2].color, AXIS_Y_COLOR);
        assert_eq!(ov.lines[4].color, AXIS_Z_COLOR);
    }
}