BREP_render 0.1.0

BREP Rust rendering engine: kernel-fed scene store + wgpu renderer (headless artifact, desktop window, and wasm canvas shells).
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
//! Engine-native sketch mode — S0 (data model + solver plumbing + read-only
//! display). See `docs/developer/sketch-mode-rust-plan.md`.
//!
//! This module is the foundation the interactive slices (S1 enter/exit, S2
//! picking, S3 tools, S4 constraints, S5 dimensions) build on. S0 provides:
//!
//! - [`doc`] — [`SketchDoc`], the typed serde mirror of the solver's
//!   `{points, geometries, constraints}` (+ [`SketchDiagnostics`]).
//! - [`solve`] — a direct in-process call to the kernel's 2D constraint solver
//!   (`brep_kernel::solve_sketch`) for solved coordinates + DOF/mobility.
//! - [`tessellate`] — a port of the previous sketcher's overlay-refresh pass:
//!   solved geometry → world-space overlay lines/points colored by mobility.
//! - [`session`] — [`SketchSession`], the `{doc, plane, diagnostics}` holder (with
//!   stubs for the interaction state later slices own).
//!
//! The engine displays a session read-only via
//! [`crate::engine_state::EngineState::set_sketch_overlay`].

pub mod constraint_glyphs;
pub mod dimensions;
pub mod doc;
pub mod external_ref;
pub mod handdraw;
pub mod infer;
pub mod session;
pub mod solve;
pub mod tessellate;
pub mod trim;

pub use doc::{SketchConstraint, SketchDiagnostics, SketchDoc, SketchGeometry, SketchPoint};
pub use external_ref::{classify_uv, EdgeLink, ExternalRef};
pub use session::{
    constraint_ref, entity_ref_eq, geometry_ref, point_ref, refs_equal, SketchSession,
};
pub use solve::SketchSolverSettings;
pub use tessellate::SketchTessellation;

// The CONSTRAINT annotation color (the green for dimension leaders/labels + the
// geometric-constraint glyphs) now lives in the display settings alongside every
// other sketch color: see [`crate::style::SketchColors::constraint`], fed to the
// overlay builders via [`crate::style::RenderSettings::sketch_colors`]. Constraints
// read in green so they stand apart from the blue/white sketch GEOMETRY (user
// directive, 2026-08-22); the egui host (brep-app) tints the dimension VALUE labels
// with the SAME setting — one editable source of truth for the whole app.

/// An orthonormal placement frame for a sketch plane — origin + in-plane `x`/`y`
/// axes + the `z` normal, all in world space (`f64`). A plane `(u, v)` coordinate
/// maps to world `origin + u·x + v·y` (via [`to_world`](Self::to_world)).
///
/// Mirrors the kernel's `feature_pipeline::Frame` shape; kept local (and `f64`) so
/// the sketch module stays self-contained and matches the solver's double-precision
/// coordinates. Later slices resolve this from the sketch's plane reference (a
/// DATUM/PLANE frame or a face frame); S0 uses the XY plane.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PlaneFrame {
    pub origin: [f64; 3],
    pub x_axis: [f64; 3],
    pub y_axis: [f64; 3],
    pub z_axis: [f64; 3],
}

impl PlaneFrame {
    /// The world XY plane (identity frame): `u → +x`, `v → +y`, normal `+z`.
    pub fn xy() -> Self {
        Self {
            origin: [0.0, 0.0, 0.0],
            x_axis: [1.0, 0.0, 0.0],
            y_axis: [0.0, 1.0, 0.0],
            z_axis: [0.0, 0.0, 1.0],
        }
    }

    /// The world XZ base plane (`datum.rs` normal `(0, -1, 0)`), resolved through
    /// the same worldUp convention the kernel uses (see [`from_normal`](Self::from_normal)).
    pub fn xz() -> Self {
        Self::from_normal([0.0, 0.0, 0.0], [0.0, -1.0, 0.0])
    }

    /// The world YZ base plane (`datum.rs` normal `(1, 0, 0)`), resolved through
    /// the same worldUp convention the kernel uses (see [`from_normal`](Self::from_normal)).
    pub fn yz() -> Self {
        Self::from_normal([0.0, 0.0, 0.0], [1.0, 0.0, 0.0])
    }

    /// Derive an orthonormal frame from an `origin` + plane `normal`, a faithful
    /// port of `feature_pipeline::Frame::from_origin_normal` — the kernel's SINGLE
    /// source of truth for how a plane reference becomes in-plane axes:
    ///
    /// ```text
    /// refUp = |n·(0,1,0)| > 0.9 ? (1,0,0) : (0,1,0)
    /// x = norm(refUp × n);  y = norm(n × x);  z = n
    /// ```
    ///
    /// A degenerate (zero / non-finite) normal — or a normal collinear with the
    /// picked `refUp` — returns the XY identity axes (at `origin`) rather than
    /// erroring, so callers always get a usable frame.
    pub fn from_normal(origin: [f64; 3], normal: [f64; 3]) -> Self {
        let identity = Self {
            origin,
            ..Self::xy()
        };
        let Some(z) = normalize(normal) else {
            return identity;
        };
        let world_up = [0.0, 1.0, 0.0];
        let ref_up = if dot(z, world_up).abs() > 0.9 {
            [1.0, 0.0, 0.0]
        } else {
            world_up
        };
        let Some(x) = normalize(cross(ref_up, z)) else {
            return identity;
        };
        let Some(y) = normalize(cross(z, x)) else {
            return identity;
        };
        Self {
            origin,
            x_axis: x,
            y_axis: y,
            z_axis: z,
        }
    }

    /// Read a persisted `persistentData.basis` object (`{origin, x, y, z}`, each a
    /// `[x, y, z]` array) into a frame, mirroring the kernel's `persisted_basis_frame`
    /// (`features/sketch.rs`). Missing keys default to the identity components, so a
    /// partial / absent basis still yields a usable XY-ish frame.
    pub fn from_basis_json(basis: &serde_json::Value) -> Self {
        Self {
            origin: read_vec3(basis.get("origin"), [0.0, 0.0, 0.0]),
            x_axis: read_vec3(basis.get("x"), [1.0, 0.0, 0.0]),
            y_axis: read_vec3(basis.get("y"), [0.0, 1.0, 0.0]),
            z_axis: read_vec3(basis.get("z"), [0.0, 0.0, 1.0]),
        }
    }

    /// Map a plane `(u, v)` coordinate to world `[x, y, z]`.
    pub fn to_world(&self, u: f64, v: f64) -> [f64; 3] {
        [
            self.origin[0] + self.x_axis[0] * u + self.y_axis[0] * v,
            self.origin[1] + self.x_axis[1] * u + self.y_axis[1] * v,
            self.origin[2] + self.x_axis[2] * u + self.y_axis[2] * v,
        ]
    }

    /// Project a world point onto the plane's `(u, v)` frame — the inverse of
    /// [`to_world`](Self::to_world). With orthonormal axes this is plain dot
    /// products against the offset from the origin (`d = world − origin`;
    /// `u = d·x_axis`, `v = d·y_axis`); a point off the plane projects orthogonally
    /// (its normal component is dropped). Mirrors the previous sketcher's
    /// world→UV projection.
    pub fn to_uv(&self, world: [f64; 3]) -> (f64, f64) {
        let d = [
            world[0] - self.origin[0],
            world[1] - self.origin[1],
            world[2] - self.origin[2],
        ];
        (dot(d, self.x_axis), dot(d, self.y_axis))
    }
}

impl Default for PlaneFrame {
    fn default() -> Self {
        Self::xy()
    }
}

/// Intersect a world-space ray (`origin` + `dir`) with a sketch `plane` and return
/// the hit's in-plane `(u, v)` coordinate, or `None` when the ray is parallel to
/// the plane (`|dir·n| < 1e-9`) or the hit is behind the ray origin (`t <= 0`).
///
/// This is the pure pixel→plane math behind
/// [`EngineState::sketch_uv_at`](crate::engine_state::EngineState::sketch_uv_at):
/// the caller supplies the camera ray (`camera.pick_ray(x, y)`); the plane's axes
/// are assumed orthonormal, so the world→uv projection is plain dot products.
pub fn ray_plane_uv(plane: &PlaneFrame, origin: [f64; 3], dir: [f64; 3]) -> Option<(f64, f64)> {
    let n = plane.z_axis;
    let denom = dot(dir, n);
    if denom.abs() < 1e-9 {
        return None; // ray parallel to the plane
    }
    let t = dot(sub(plane.origin, origin), n) / denom;
    if t <= 0.0 {
        return None; // plane is behind the ray origin
    }
    let hit = [
        origin[0] + t * dir[0],
        origin[1] + t * dir[1],
        origin[2] + t * dir[2],
    ];
    let w = sub(hit, plane.origin);
    Some((dot(w, plane.x_axis), dot(w, plane.y_axis)))
}

/// Dot product of two 3-vectors.
fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}

/// `a - b` for two 3-vectors.
fn sub(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}

/// Cross product `a × b`.
fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
    [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ]
}

/// Normalize `v`, or `None` when it is (near) zero / non-finite.
fn normalize(v: [f64; 3]) -> Option<[f64; 3]> {
    let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
    if len.is_finite() && len > 1e-12 {
        Some([v[0] / len, v[1] / len, v[2] / len])
    } else {
        None
    }
}

/// Read a `[x, y, z]` JSON array as an `[f64; 3]`, falling back per-component to
/// `default` (mirrors the kernel's `read_vec3` in `features/sketch.rs`).
fn read_vec3(value: Option<&serde_json::Value>, default: [f64; 3]) -> [f64; 3] {
    let Some(array) = value.and_then(|v| v.as_array()) else {
        return default;
    };
    let component = |index: usize| {
        array
            .get(index)
            .and_then(serde_json::Value::as_f64)
            .unwrap_or(default[index])
    };
    [component(0), component(1), component(2)]
}

#[cfg(test)]
mod tests {
    use super::doc::{id_key, SketchDiagnostics, SketchDoc};
    use super::*;
    use serde_json::{json, Value};

    /// Solve a sketch `Value` directly and return the full solved sketch object
    /// (`{points, geometries, constraints, diagnostics}`).
    fn solve_value(sketch: Value) -> Value {
        let request = brep_kernel::SolveSketchRequest {
            sketch,
            iterations: Some(1000),
            remove_implied_duplicates: false,
            tolerance: None,
            distance_slide_threshold_ratio: None,
            distance_slide_step_ratio: None,
            distance_slide_min_step: None,
            polish: None,
        };
        brep_kernel::solve_sketch(&request).expect("solve_sketch")["sketch"].clone()
    }

    #[test]
    fn sketchdoc_round_trips_solver_json() {
        // A solved rectangle produces `{points, geometries, constraints,
        // diagnostics}`. `SketchDoc` mirrors the three editable arrays; splitting
        // diagnostics off, the doc must re-serialize BYTE-EQUAL to the input.
        let session = SketchSession::seed_rectangle_circle().expect("seed session");
        let solved = solve_value(serde_json::to_value(&session.doc).unwrap());

        let mut doc_value = solved.clone();
        doc_value
            .as_object_mut()
            .unwrap()
            .remove("diagnostics")
            .expect("solved sketch carries diagnostics");

        let doc: SketchDoc = serde_json::from_value(doc_value.clone()).expect("doc from value");
        let back = serde_json::to_value(&doc).expect("doc to value");
        assert_eq!(back, doc_value, "SketchDoc did not round-trip the solver JSON");

        // Diagnostics round-trips independently.
        let diag: SketchDiagnostics =
            serde_json::from_value(solved["diagnostics"].clone()).expect("diag from value");
        let diag_back = serde_json::to_value(&diag).expect("diag to value");
        assert_eq!(diag_back, solved["diagnostics"], "diagnostics did not round-trip");
    }

    #[test]
    fn seed_rectangle_solves_with_plausible_dof_and_mobility() {
        let session = SketchSession::seed_rectangle_circle().expect("seed session");
        let diag = &session.diagnostics;

        // The rectangle is fully constrained; the free circle adds exactly its
        // four coordinate DOF.
        assert_eq!(diag.dof, 4, "diag = {diag:?}");
        assert_eq!(diag.status, "under");
        assert_eq!(diag.redundant, 0);
        assert!(!diag.conflicting);

        // Rectangle corners (grounded/dimensioned) are locked; circle points free.
        for id in [0, 1, 2, 3] {
            assert_eq!(
                diag.point_movable(&json!(id)),
                Some(false),
                "rectangle point {id} should be locked"
            );
        }
        for id in [4, 5] {
            assert_eq!(
                diag.point_movable(&json!(id)),
                Some(true),
                "circle point {id} should be movable"
            );
        }

        // Rectangle sides locked (white); circle movable (blue).
        for gid in [10, 11, 12, 13] {
            assert_eq!(diag.geometry_movable(&json!(gid)), Some(false));
        }
        assert_eq!(diag.geometry_movable(&json!(20)), Some(true));

        // Solved coordinates: the grounded corner stays at the origin and the
        // dimensioned corner sits at (20, 12).
        let p2 = session.doc.point(&json!(2)).expect("point 2");
        assert!((p2.x - 20.0).abs() < 1e-6 && (p2.y - 12.0).abs() < 1e-6, "p2 = {p2:?}");
    }

    #[test]
    fn tessellation_yields_expected_segment_and_point_counts() {
        let session = SketchSession::seed_rectangle_circle().expect("seed session");
        let tess = session.tessellation(0.05);

        // 4 rectangle lines (1 segment each) + a 64-gon circle = 68 segments.
        assert_eq!(tess.line_segment_count(), 4 + 64);
        // 6 points (4 rectangle corners + circle center/radius), none dropped.
        assert_eq!(tess.point_count(), 6);

        // Every emitted vertex carries an rgb triple.
        assert_eq!(tess.line_positions.len(), tess.line_colors.len());
        assert_eq!(tess.point_positions.len(), tess.point_colors.len());

        // XY plane: solved z is flat zero on every line vertex.
        assert!(tess.line_positions.chunks(3).all(|c| c[2].abs() < 1e-6));

        // The circle center point (id 4, movable) is colored blue (0x4aa3ff).
        let center = session.doc.point(&json!(4)).unwrap();
        let cx = center.x as f32;
        let idx = tess
            .point_positions
            .chunks(3)
            .position(|c| (c[0] - cx).abs() < 1e-4)
            .expect("circle center among overlay points");
        let col = &tess.point_colors[idx * 3..idx * 3 + 3];
        assert!((col[0] - 0x4a as f32 / 255.0).abs() < 1e-3, "movable point not blue: {col:?}");
    }

    #[test]
    fn construction_geometry_is_dashed_into_multiple_segments() {
        // A single long construction line dashes into many short segments; a
        // solid line of the same span stays one segment.
        let doc: SketchDoc = serde_json::from_value(json!({
            "points": [
                { "id": 0, "x": 0.0,  "y": 0.0 },
                { "id": 1, "x": 100.0, "y": 0.0 }
            ],
            "geometries": [
                { "id": 10, "type": "line", "points": [0, 1], "construction": true }
            ],
            "constraints": []
        }))
        .unwrap();
        let session = SketchSession::new(doc, PlaneFrame::xy()).expect("session");
        let tess = session.tessellation(0.05); // dash ~0.4, gap ~0.3 over a 100-long span
        assert!(
            tess.line_segment_count() > 10,
            "construction line should dash into many segments, got {}",
            tess.line_segment_count()
        );
    }

    #[test]
    fn id_key_matches_solver_formatting() {
        assert_eq!(id_key(&json!(10)), "10");
        assert_eq!(id_key(&json!(10.0)), "10");
        assert_eq!(id_key(&json!(0)), "0");
        assert_eq!(id_key(&json!(-0.0)), "0");
        assert_eq!(id_key(&json!("edge:3")), "edge:3");
    }

    #[test]
    fn plane_frame_embeds_uv_in_world() {
        let f = PlaneFrame::xy();
        assert_eq!(f.to_world(3.0, 4.0), [3.0, 4.0, 0.0]);
    }

    #[test]
    fn to_uv_inverts_to_world_on_a_tilted_frame() {
        // A round-trip uv → world → uv recovers the original coordinate on a
        // non-identity (tilted, offset) frame.
        let f = PlaneFrame::from_normal([5.0, -2.0, 3.0], [1.0, 2.0, 3.0]);
        for &(u, v) in &[(0.0, 0.0), (2.5, -1.5), (-4.0, 7.0)] {
            let world = f.to_world(u, v);
            let (ru, rv) = f.to_uv(world);
            assert!((ru - u).abs() < 1e-9 && (rv - v).abs() < 1e-9, "uv=({u},{v}) -> ({ru},{rv})");
        }
        // A point pushed off the plane along the normal projects to the same uv
        // (orthogonal projection drops the normal component).
        let base = f.to_world(1.0, 2.0);
        let off = [
            base[0] + f.z_axis[0] * 9.0,
            base[1] + f.z_axis[1] * 9.0,
            base[2] + f.z_axis[2] * 9.0,
        ];
        let (ou, ov) = f.to_uv(off);
        assert!((ou - 1.0).abs() < 1e-9 && (ov - 2.0).abs() < 1e-9, "off-plane uv=({ou},{ov})");
    }

    // --- S1: PlaneFrame::from_normal / xz / yz / from_basis_json --------------

    fn approx(a: [f64; 3], b: [f64; 3]) -> bool {
        a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9)
    }

    /// A frame is orthonormal + right-handed: unit axes, mutually perpendicular,
    /// and `x × y == z`.
    fn assert_orthonormal(f: &PlaneFrame) {
        for axis in [f.x_axis, f.y_axis, f.z_axis] {
            let len = (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt();
            assert!((len - 1.0).abs() < 1e-9, "axis not unit: {axis:?}");
        }
        assert!(super::dot(f.x_axis, f.y_axis).abs() < 1e-9, "x·y != 0");
        assert!(super::dot(f.y_axis, f.z_axis).abs() < 1e-9, "y·z != 0");
        assert!(super::dot(f.z_axis, f.x_axis).abs() < 1e-9, "z·x != 0");
        assert!(
            approx(super::cross(f.x_axis, f.y_axis), f.z_axis),
            "not right-handed: {f:?}"
        );
    }

    #[test]
    fn from_normal_xy_is_the_identity_frame() {
        let f = PlaneFrame::from_normal([0.0, 0.0, 0.0], [0.0, 0.0, 1.0]);
        assert_eq!(f, PlaneFrame::xy());
        assert_orthonormal(&f);
    }

    #[test]
    fn base_planes_match_the_datum_normals_and_are_orthonormal() {
        // datum.rs base-plane normals: XY (0,0,1), XZ (0,-1,0), YZ (1,0,0).
        let xz = PlaneFrame::xz();
        assert!(approx(xz.z_axis, [0.0, -1.0, 0.0]), "XZ normal: {:?}", xz.z_axis);
        assert!(approx(xz.origin, [0.0, 0.0, 0.0]));
        assert_orthonormal(&xz);

        let yz = PlaneFrame::yz();
        assert!(approx(yz.z_axis, [1.0, 0.0, 0.0]), "YZ normal: {:?}", yz.z_axis);
        assert!(approx(yz.origin, [0.0, 0.0, 0.0]));
        assert_orthonormal(&yz);
    }

    #[test]
    fn from_normal_carries_origin_and_normalizes() {
        let f = PlaneFrame::from_normal([5.0, 6.0, 7.0], [0.0, 0.0, 4.0]);
        assert_eq!(f.origin, [5.0, 6.0, 7.0]);
        assert!(approx(f.z_axis, [0.0, 0.0, 1.0]), "unnormalized normal: {:?}", f.z_axis);
        assert_orthonormal(&f);
    }

    #[test]
    fn from_normal_degenerate_returns_identity_axes_at_origin() {
        let f = PlaneFrame::from_normal([2.0, 3.0, 4.0], [0.0, 0.0, 0.0]);
        assert_eq!(
            f,
            PlaneFrame {
                origin: [2.0, 3.0, 4.0],
                ..PlaneFrame::xy()
            }
        );
    }

    #[test]
    fn from_basis_json_round_trips_a_basis_object() {
        // The exact shape the kernel persists (features/sketch.rs `persisted_basis_frame`).
        let f = PlaneFrame::yz();
        let basis = json!({
            "origin": f.origin,
            "x": f.x_axis,
            "y": f.y_axis,
            "z": f.z_axis,
        });
        let back = PlaneFrame::from_basis_json(&basis);
        assert_eq!(back, f);

        // Missing keys fall back to the identity components.
        let partial = json!({ "origin": [5.0, 0.0, 0.0] });
        let g = PlaneFrame::from_basis_json(&partial);
        assert_eq!(g.origin, [5.0, 0.0, 0.0]);
        assert_eq!(g.x_axis, [1.0, 0.0, 0.0]);
        assert_eq!(g.y_axis, [0.0, 1.0, 0.0]);
        assert_eq!(g.z_axis, [0.0, 0.0, 1.0]);
    }

    // --- S2: pixel → plane ray∩plane → uv (pure helper) -----------------------

    #[test]
    fn ray_plane_uv_hits_the_xy_plane_and_recovers_uv() {
        // A ray straight down onto the XY plane at world (3, 4, 0) recovers (3, 4).
        let plane = PlaneFrame::xy();
        let uv = super::ray_plane_uv(&plane, [3.0, 4.0, 10.0], [0.0, 0.0, -1.0]).unwrap();
        assert!((uv.0 - 3.0).abs() < 1e-9 && (uv.1 - 4.0).abs() < 1e-9, "uv = {uv:?}");
    }

    #[test]
    fn ray_plane_uv_rejects_parallel_and_behind_rays() {
        let plane = PlaneFrame::xy();
        // Parallel to the plane (dir in-plane) → None.
        assert!(super::ray_plane_uv(&plane, [0.0, 0.0, 5.0], [1.0, 0.0, 0.0]).is_none());
        // Plane behind the origin (looking away from it) → None (t <= 0).
        assert!(super::ray_plane_uv(&plane, [0.0, 0.0, 5.0], [0.0, 0.0, 1.0]).is_none());
    }

    #[test]
    fn ray_plane_uv_uses_the_plane_axes_on_a_tilted_plane() {
        // On the YZ plane (normal +x, x_axis/y_axis per the datum convention), a
        // ray from +x recovers the in-plane coordinates in that frame.
        let plane = PlaneFrame::yz();
        let target = plane.to_world(2.5, -1.5);
        let origin = [
            target[0] + plane.z_axis[0] * 8.0,
            target[1] + plane.z_axis[1] * 8.0,
            target[2] + plane.z_axis[2] * 8.0,
        ];
        let dir = [-plane.z_axis[0], -plane.z_axis[1], -plane.z_axis[2]];
        let uv = super::ray_plane_uv(&plane, origin, dir).unwrap();
        assert!((uv.0 - 2.5).abs() < 1e-9 && (uv.1 + 1.5).abs() < 1e-9, "uv = {uv:?}");
    }
}