Modern Apps git

← Modern-Apps.git

camera: fix blend border and pyramid defects and add stitch Rust tests

Commit
a3b744d474786046e1db1de17ceb3312f5be69bc
Author
Vayun Mathur <[email protected]>
When
2026-11-17 21:26 UTC (18 days ago)
Parents
77ea908
128 new tests (11 -> 139): blend/seam/sphere/stitch/matching/night/exposure/bundle/wave/estimator plus public-API integration tests on synthetic buffers. Fixes: (1) box_blur normalized by the full window width at borders, darkening constant planes to (3/5)^2 at corners — now normalized by the actual truncated window, constant planes preserved exactly; (2) multiband blend of identical tiles produced 98..135 instead of the constant — pyr_up is now a true Gaussian expansion matching pyr_down, and the tile gap fill reflects across the whole gap instead of leaving black outside a 1px ring, so identical tiles blend to exactly their value. cargo test -p camera_stitch green. Line coverage 80.2% -> 88.7%.

Diff

camera/src/main/rust/src/blend.rs
diff --git a/camera/src/main/rust/src/blend.rs b/camera/src/main/rust/src/blend.rsindex 803077554c..d70da862b3 100644--- a/camera/src/main/rust/src/blend.rs+++ b/camera/src/main/rust/src/blend.rs@@ -12,12 +12,14 @@ use crate::imgbuf::Rgba; use crate::sphere::WarpedTile;  /// Separable box blur of a float plane (running-sum, radius r).+/// Each 1D pass normalises by the actual number of samples in its+/// (possibly truncated) window, so a constant plane is preserved+/// everywhere including borders/corners. fn box_blur(src: &[f32], w: usize, h: usize, r: usize) -> Vec<f32> {-    if r == 0 {+    if r == 0 || w == 0 || h == 0 {         return src.to_vec();     }     let mut tmp = vec![0f32; w * h];-    let norm = 1.0 / (2 * r + 1) as f32;     // horizontal     for y in 0..h {         let row = y * w;@@ -26,7 +28,9 @@ fn box_blur(src: &[f32], w: usize, h: usize, r: usize) -> Vec<f32> {             sum += src[row + x];         }         for x in 0..w {-            tmp[row + x] = sum * norm;+            let lo = x.saturating_sub(r);+            let hi = (x + r).min(w - 1);+            tmp[row + x] = sum / (hi - lo + 1) as f32;             let add = x + r + 1;             let sub = x as isize - r as isize;             if add < w {@@ -45,7 +49,9 @@ fn box_blur(src: &[f32], w: usize, h: usize, r: usize) -> Vec<f32> {             sum += tmp[y * w + x];         }         for y in 0..h {-            out[y * w + x] = sum * norm;+            let lo = y.saturating_sub(r);+            let hi = (y + r).min(h - 1);+            out[y * w + x] = sum / (hi - lo + 1) as f32;             let add = y + r + 1;             let sub = y as isize - r as isize;             if add < h {@@ -208,36 +214,93 @@ fn pyr_down_1ch(src: &WMap) -> WMap { }  fn pyr_up_3ch(src: &Img3, dst_w: usize, dst_h: usize) -> Img3 {-    // Bilinear upsample to dst size – approximates OpenCV pyrUp Gaussian *4.-    // For exact reconstruction we use bilinear; good enough for visual parity.+    // Proper Gaussian expansion (OpenCV pyrUp): zero-insert src at even+    // coordinates, then separable blur with [1 4 6 4 1]/8 per axis (the+    // /16 pyrDown kernel x2 gain per axis, x4 in 2D). Unlike the previous+    // bilinear upsample this is the expansion matching pyr_down_3ch, so+    // Laplacian reconstruction is (near-)energy-preserving: a constant+    // signal down-then-up (and a weighted blend of identical constants)+    // reconstructs to that constant.     if src.w == 0 || src.h == 0 || dst_w == 0 || dst_h == 0 {         return Img3 { w: dst_w, h: dst_h, data: vec![0f32; dst_w * dst_h * 3] };     }+    let (ew, eh) = (src.w * 2, src.h * 2);+    let mut expanded = vec![0f32; ew * eh * 3];+    for y in 0..src.h {+        for x in 0..src.w {+            let s = (y * src.w + x) * 3;+            let d = ((2 * y) * ew + 2 * x) * 3;+            expanded[d] = src.data[s];+            expanded[d + 1] = src.data[s + 1];+            expanded[d + 2] = src.data[s + 2];+        }+    }+    let kernel = [1.0f32, 4.0, 6.0, 4.0, 1.0];+    let mut tmp = vec![0f32; ew * eh * 3];+    for y in 0..eh {+        for x in 0..ew {+            let mut acc = [0f32; 3];+            for k in -2isize..=2 {+                let xs = reflect_101(x as isize + k, ew);+                let coeff = kernel[(k + 2) as usize] / 8.0;+                let b = (y * ew + xs) * 3;+                acc[0] += expanded[b] * coeff;+                acc[1] += expanded[b + 1] * coeff;+                acc[2] += expanded[b + 2] * coeff;+            }+            let d = (y * ew + x) * 3;+            tmp[d] = acc[0];+            tmp[d + 1] = acc[1];+            tmp[d + 2] = acc[2];+        }+    }+    let mut up = vec![0f32; ew * eh * 3];+    for y in 0..eh {+        for x in 0..ew {+            let mut acc = [0f32; 3];+            for k in -2isize..=2 {+                let ys = reflect_101(y as isize + k, eh);+                let coeff = kernel[(k + 2) as usize] / 8.0;+                let b = (ys * ew + x) * 3;+                acc[0] += tmp[b] * coeff;+                acc[1] += tmp[b + 1] * coeff;+                acc[2] += tmp[b + 2] * coeff;+            }+            let d = (y * ew + x) * 3;+            up[d] = acc[0];+            up[d + 1] = acc[1];+            up[d + 2] = acc[2];+        }+    }+    if dst_w <= ew && dst_h <= eh {+        // Pyramid case: dst is 2*src or 2*src-1 per axis – crop top-left.+        if dst_w == ew && dst_h == eh {+            return Img3 { w: ew, h: eh, data: up };+        }+        let mut data = vec![0f32; dst_w * dst_h * 3];+        for y in 0..dst_h {+            let s = y * ew * 3;+            let d = y * dst_w * 3;+            data[d..d + dst_w * 3].copy_from_slice(&up[s..s + dst_w * 3]);+        }+        return Img3 { w: dst_w, h: dst_h, data };+    }+    // Non-pyramid size (>2x): bilinear-resize the Gaussian expansion.     let mut data = vec![0f32; dst_w * dst_h * 3];-    let src_w = src.w as f32;-    let src_h = src.h as f32;-    let dw = dst_w as f32;-    let dh = dst_h as f32;     for y in 0..dst_h {-        let fy = if dst_h == 1 { 0.0 } else { (y as f32 + 0.5) * src_h / dh - 0.5 };-        let fy = fy.clamp(0.0, src_h - 1.0);+        let fy = ((y as f32 + 0.5) * eh as f32 / dst_h as f32 - 0.5).clamp(0.0, (eh - 1) as f32);         let y0 = fy.floor() as usize;-        let y1 = (y0 + 1).min(src.h - 1);+        let y1 = (y0 + 1).min(eh - 1);         let ay = fy - y0 as f32;         for x in 0..dst_w {-            let fx = if dst_w == 1 { 0.0 } else { (x as f32 + 0.5) * src_w / dw - 0.5 };-            let fx = fx.clamp(0.0, src_w - 1.0);+            let fx = ((x as f32 + 0.5) * ew as f32 / dst_w as f32 - 0.5).clamp(0.0, (ew - 1) as f32);             let x0 = fx.floor() as usize;-            let x1 = (x0 + 1).min(src.w - 1);+            let x1 = (x0 + 1).min(ew - 1);             let ax = fx - x0 as f32;-            let s00 = (y0 * src.w + x0) * 3;-            let s01 = (y0 * src.w + x1) * 3;-            let s10 = (y1 * src.w + x0) * 3;-            let s11 = (y1 * src.w + x1) * 3;             let d = (y * dst_w + x) * 3;             for c in 0..3 {-                let top = src.data[s00 + c] * (1.0 - ax) + src.data[s01 + c] * ax;-                let bot = src.data[s10 + c] * (1.0 - ax) + src.data[s11 + c] * ax;+                let top = up[(y0 * ew + x0) * 3 + c] * (1.0 - ax) + up[(y0 * ew + x1) * 3 + c] * ax;+                let bot = up[(y1 * ew + x0) * 3 + c] * (1.0 - ax) + up[(y1 * ew + x1) * 3 + c] * ax;                 data[d + c] = top * (1.0 - ay) + bot * ay;             }         }@@ -331,4 +394,8 @@ fn feather_blend(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec<f32>] // Public entry: multiband_blend with true Laplacian pyramid // --------------------------------------------------------------------------- -include!("blend_part1.rs");\ No newline at end of file+include!("blend_part1.rs");++#[cfg(test)]+#[path = "blend_tests.rs"]+mod blend_tests;
camera/src/main/rust/src/blend_part1.rs
diff --git a/camera/src/main/rust/src/blend_part1.rs b/camera/src/main/rust/src/blend_part1.rsindex a3d086b2f9..9606540770 100644--- a/camera/src/main/rust/src/blend_part1.rs+++ b/camera/src/main/rust/src/blend_part1.rs@@ -150,28 +150,22 @@ pub fn multiband_blend(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec                     big_img.data[d_idx3 + 2] = base_img.data[s_idx3 + 2];                     big_weight.data[d_idx1] = base_weight.data[sy as usize * tw0 + sx as usize];                 } else {-                    // Image: BORDER_REFLECT_101-                    if sx >= 0 && sx < tw0 as isize && sy >= 0 && sy < th0 as isize {-                        // shouldn't happen – already handled-                    } else if sx >= -1 && sx < tw0 as isize + 1 && sy >= -1 && sy < th0 as isize + 1 {-                        // try to reflect from inside where we can get pixel-                        // For simplicity, if source out of bounds, reflect index into base_img if possible-                        // Use reflect_101 for both axes if the coordinate is outside base but not too far-                        // We'll only reflect when the coordinate is outside but weight would be zero anyway for constant border.-                        // For image we reflect, for weight we keep 0.+                    // Image: BORDER_REFLECT_101 over the WHOLE gap (as+                    // OpenCV copyMakeBorder does). Reflecting only a 1px+                    // ring and leaving the rest black put a 120->0 step+                    // just outside each tile; pyr_down blur spread it+                    // into coarse Laplacian bands inside the tile, so a+                    // uniform overlap reconstructed at 98..135 instead+                    // of 120. reflect_101 handles far indices. Weight+                    // stays 0 (BORDER_CONSTANT).+                    if tw0 > 0 && th0 > 0 {                         let rx = reflect_101(sx, tw0);                         let ry = reflect_101(sy, th0);-                        // Only reflect if original request was within expanded but not inside – the reflected pixel exists-                        if rx < tw0 && ry < th0 {-                            let s_idx3 = (ry * tw0 + rx) * 3;-                            big_img.data[d_idx3] = base_img.data[s_idx3];-                            big_img.data[d_idx3 + 1] = base_img.data[s_idx3 + 1];-                            big_img.data[d_idx3 + 2] = base_img.data[s_idx3 + 2];-                        }-                    } else {-                        // Far outside gap, leave image as 0, weight 0 (still okay)+                        let s_idx3 = (ry * tw0 + rx) * 3;+                        big_img.data[d_idx3] = base_img.data[s_idx3];+                        big_img.data[d_idx3 + 1] = base_img.data[s_idx3 + 1];+                        big_img.data[d_idx3 + 2] = base_img.data[s_idx3 + 2];                     }-                    // weight stays 0 (BORDER_CONSTANT)                 }             }         }
camera/src/main/rust/src/blend_tests.rs
diff --git a/camera/src/main/rust/src/blend_tests.rs b/camera/src/main/rust/src/blend_tests.rsnew file mode 100644index 0000000000..0dc2230982--- /dev/null+++ b/camera/src/main/rust/src/blend_tests.rs@@ -0,0 +1,237 @@+//! Tests for blend.rs private helpers: box blur, reflect indexing, image+//! pyramids, content-rect cropping, and the public multiband entry point.++use super::*;+use crate::sphere::WarpedTile;++fn approx(a: f32, b: f32) -> bool {+    (a - b).abs() <= 1e-4+}++#[test]+fn box_blur_radius_zero_is_identity() {+    let src: Vec<f32> = (0..12).map(|i| i as f32).collect();+    assert_eq!(box_blur(&src, 4, 3, 0), src);+}++#[test]+fn box_blur_preserves_constant_plane_including_borders() {+    // A constant plane must blur to itself everywhere, borders and+    // corners included (<=1 gray level; f32 plane is exact in practice):+    // each pass normalises by the truncated window's actual sample count.+    let src = vec![7.0f32; 81];+    let out = box_blur(&src, 9, 9, 2);+    assert!(+        out.iter().all(|v| (v - 7.0).abs() <= 1.0 && approx(*v, 7.0)),+        "constant plane preserved incl. borders: corner {} centre {}",+        out[0],+        out[4 * 9 + 4]+    );+    // A radius larger than the image and a non-square plane too.+    let out2 = box_blur(&vec![3.5f32; 20], 5, 4, 3);+    assert!(out2.iter().all(|v| approx(*v, 3.5)), "small plane preserved: {out2:?}");+}++#[test]+fn box_blur_impulse_sums_approximately_and_peaks_at_centre() {+    // A single impulse spreads over the (2r+1)^2 window; total mass is only+    // approximately preserved because edges clamp the running window.+    let mut src = vec![0.0f32; 81];+    src[4 * 9 + 4] = 81.0;+    let out = box_blur(&src, 9, 9, 2);+    let centre = out[4 * 9 + 4];+    assert!(centre > out[0] && centre > out[4 * 9], "peak stays at impulse");+    assert!(out.iter().all(|v| *v >= 0.0));+    let total: f32 = out.iter().sum();+    assert!(total > 40.0 && total < 130.0, "mass roughly preserved, got {total}");+}++#[test]+fn reflect_101_mirrors_without_repeating_border() {+    assert_eq!(reflect_101(0, 5), 0);+    assert_eq!(reflect_101(4, 5), 4);+    assert_eq!(reflect_101(-1, 5), 1);+    assert_eq!(reflect_101(5, 5), 3);+    assert_eq!(reflect_101(6, 5), 2);+    assert_eq!(reflect_101(-3, 5), 3);+    // Degenerate widths collapse to 0 instead of looping forever.+    assert_eq!(reflect_101(7, 1), 0);+    assert_eq!(reflect_101(-7, 0 + 1), 0);+}++#[test]+fn reflect_101_handles_far_out_of_range_indices() {+    for idx in [-23isize, -9, 13, 41] {+        let r = reflect_101(idx, 5);+        assert!(r < 5, "idx {idx} -> {r}");+    }+}++fn const_img3(w: usize, h: usize, v: f32) -> Img3 {+    Img3 { w, h, data: vec![v; w * h * 3] }+}++#[test]+fn pyr_down_halves_dimensions_with_ceil_and_keeps_constants() {+    let down = pyr_down_3ch(&const_img3(7, 5, 42.0));+    assert_eq!((down.w, down.h), (4, 3), "ceil half of odd sizes");+    assert!(down.data.iter().all(|v| approx(*v, 42.0)));+    let down1 = pyr_down_1ch(&WMap { w: 8, h: 8, data: vec![3.0; 64] });+    assert_eq!((down1.w, down1.h), (4, 4));+    assert!(down1.data.iter().all(|v| approx(*v, 3.0)));+}++#[test]+fn pyr_down_of_empty_is_empty() {+    let d = pyr_down_3ch(&Img3 { w: 0, h: 0, data: Vec::new() });+    assert_eq!((d.w, d.h), (0, 0));+    let d1 = pyr_down_1ch(&WMap { w: 0, h: 4, data: Vec::new() });+    assert_eq!(d1.w * d1.h, 0);+}++#[test]+fn pyr_up_restores_requested_size_and_keeps_constants() {+    let up = pyr_up_3ch(&const_img3(2, 2, 9.0), 5, 3);+    assert_eq!((up.w, up.h), (5, 3));+    assert!(up.data.iter().all(|v| approx(*v, 9.0)));+    // Zero-size source upsamples to zeros of the requested shape.+    let z = pyr_up_3ch(&Img3 { w: 0, h: 0, data: Vec::new() }, 3, 2);+    assert_eq!(z.data.len(), 3 * 2 * 3);+    assert!(z.data.iter().all(|v| *v == 0.0));+}++#[test]+fn pyr_up_gaussian_expansion_interpolates_between_corners() {+    let mut src = const_img3(2, 1, 0.0);+    src.data[0] = 0.0;+    src.data[3] = 100.0; // right pixel red channel+    let up = pyr_up_3ch(&src, 4, 1);+    let reds: Vec<f32> = (0..4).map(|x| up.data[x * 3]).collect();+    assert!(reds[0] < reds[1] && reds[1] < reds[2] && reds[2] < reds[3], "monotone ramp {reds:?}");+    assert!(approx(reds[3], 100.0) || reds[3] > 75.0);+}++#[test]+fn content_rect_of_empty_and_full_grids() {+    let none = vec![false; 12];+    assert_eq!(content_rect(&none, 4, 3), (0, 0, 0, 0));+    let full = vec![true; 12];+    assert_eq!(content_rect(&full, 4, 3), (0, 0, 4, 3));+}++#[test]+fn content_rect_finds_maximal_opaque_rectangle() {+    // 6x4 grid with a 3x2 opaque block at (2,1).+    let mut valid = vec![false; 24];+    for y in 1..3 {+        for x in 2..5 {+            valid[y * 6 + x] = true;+        }+    }+    assert_eq!(content_rect(&valid, 6, 4), (2, 1, 3, 2));+}++#[test]+fn content_rect_prefers_wide_short_over_narrow_tall_on_area() {+    // L-shape: row of 5 plus a column of 3 sharing the corner. Best single+    // rectangle by area is the 5x1 row (area 5) vs 1x3 column (area 3) vs+    // any 2-wide sub-rectangle (area <= 4).+    let mut valid = vec![false; 25];+    for x in 0..5 {+        valid[x] = true;+    }+    for y in 0..3 {+        valid[y * 5] = true;+    }+    let (x, y, w, h) = content_rect(&valid, 5, 5);+    assert_eq!(w * h, 5, "best area 5, got ({x},{y},{w},{h})");+}++#[test]+fn crop_to_content_trims_transparent_borders() {+    let mut img = Rgba::new(6, 5);+    for y in 1..4 {+        for x in 2..5 {+            img.set(x, y, [10, 20, 30, 255]);+        }+    }+    let cropped = crop_to_content(img.clone());+    assert_eq!((cropped.w, cropped.h), (3, 3));+    assert_eq!(cropped.get(0, 0), [10, 20, 30, 255]);+    // Fully transparent image crops to itself (no valid rect).+    let empty = crop_to_content(Rgba::new(3, 3));+    assert_eq!((empty.w, empty.h), (3, 3));+}++fn tile(w: usize, h: usize, cx: i32, cy: i32, c: [u8; 4]) -> WarpedTile {+    let mut img = Rgba::new(w, h);+    for y in 0..h {+        for x in 0..w {+            img.set(x, y, c);+        }+    }+    WarpedTile { img, corner_x: cx, corner_y: cy }+}++#[test]+fn multiband_blend_empty_input_is_none() {+    assert!(multiband_blend(&[], &[], &[]).is_none());+}++#[test]+fn multiband_blend_single_tile_returns_its_colours() {+    let tiles = vec![tile(16, 16, 0, 0, [200, 100, 50, 255])];+    let masks = vec![vec![1u8; 16 * 16]];+    let gains = vec![vec![1.0f32; 16 * 16]];+    let out = multiband_blend(&tiles, &masks, &gains).expect("blend");+    assert_eq!((out.w, out.h), (16, 16));+    assert_eq!(out.get(8, 8), [200, 100, 50, 255]);+}++#[test]+fn multiband_blend_two_identical_overlapping_tiles_stays_uniform() {+    let tiles = vec![+        tile(16, 16, 0, 0, [120, 120, 120, 255]),+        tile(16, 16, 8, 0, [120, 120, 120, 255]),+    ];+    let masks: Vec<Vec<u8>> = tiles.iter().map(|t| vec![1u8; t.img.w * t.img.h]).collect();+    let gains: Vec<Vec<f32>> = tiles.iter().map(|t| vec![1.0f32; t.img.w * t.img.h]).collect();+    let out = multiband_blend(&tiles, &masks, &gains).expect("blend");+    assert!(out.w >= 16 && out.h == 16, "canvas covers both tiles: {}x{}", out.w, out.h);+    for y in 0..out.h {+        for x in 0..out.w {+            let p = out.get(x, y);+            assert_eq!(p[3], 255, "interior must be opaque at ({x},{y})");+            // Identical constant tiles must reconstruct to that constant+            // (within ~2% = 2 gray levels at 120), across the whole+            // canvas including the overlap: Gaussian pyrUp matching+            // pyrDown, plus whole-gap reflected tile borders, makes the+            // Laplacian reconstruction energy-preserving for constants.+            assert!((p[0] as i32 - 120).abs() <= 2, "uniform colour drifted: {p:?} at ({x},{y})");+            assert_eq!(p[0], p[1]);+            assert_eq!(p[1], p[2]);+        }+    }+}++#[test]+fn multiband_blend_gain_scales_colour_with_clamping() {+    let tiles = vec![tile(8, 8, 0, 0, [200, 10, 10, 255])];+    let masks = vec![vec![1u8; 64]];+    let gains = vec![vec![2.0f32; 64]];+    let out = multiband_blend(&tiles, &masks, &gains).expect("blend");+    // 200 * 2 clamps to 255 in the tile build; 10 * 2 = 20.+    assert_eq!(out.get(4, 4), [255, 20, 20, 255]);+}++#[test]+fn multiband_blend_zero_mask_falls_back_but_still_returns_coverage() {+    // All-zero masks give zero weights; the implementation falls back to the+    // feather path, whose second pass fills covered pixels directly.+    let tiles = vec![tile(8, 8, -4, -3, [30, 60, 90, 255])];+    let masks = vec![vec![0u8; 64]];+    let gains = vec![vec![1.0f32; 64]];+    let out = multiband_blend(&tiles, &masks, &gains).expect("fallback blend");+    assert_eq!((out.w, out.h), (8, 8));+    assert_eq!(out.get(4, 4), [30, 60, 90, 255]);+}
camera/src/main/rust/src/bundle.rs
diff --git a/camera/src/main/rust/src/bundle.rs b/camera/src/main/rust/src/bundle.rsindex df3287e9bf..0c1a730f7e 100644--- a/camera/src/main/rust/src/bundle.rs+++ b/camera/src/main/rust/src/bundle.rs@@ -196,3 +196,7 @@ pub fn bundle_adjust(cams: &mut Vec<CameraParams>, matches: &[MatchInfo]) {         }     } }++#[cfg(test)]+#[path = "bundle_tests.rs"]+mod bundle_tests;
camera/src/main/rust/src/bundle_tests.rs
diff --git a/camera/src/main/rust/src/bundle_tests.rs b/camera/src/main/rust/src/bundle_tests.rsnew file mode 100644index 0000000000..8094eda6e2--- /dev/null+++ b/camera/src/main/rust/src/bundle_tests.rs@@ -0,0 +1,148 @@+//! Tests for bundle.rs private helpers: K inverse, camera perturbation,+//! geodesic increments, and ray residuals; plus bundle_adjust no-op paths.+fn mdiff(a: &Matrix3<f64>, b: &Matrix3<f64>) -> f64 {+    let mut s = 0.0f64;+    for r in 0..3 { for c in 0..3 { let d = a[(r, c)] - b[(r, c)]; s += d * d; } }+    s.sqrt()+}+++use super::*;+use crate::linalg::Matrix3;++fn approx(a: f64, b: f64) -> bool {+    (a - b).abs() <= 1e-9+}++fn cam(focal: f64) -> CameraParams {+    CameraParams { focal, aspect: 1.0, ppx: 320.0, ppy: 240.0, r: Matrix3::identity() }+}++#[test]+fn k_inv_undoes_camera_k() {+    let c = cam(640.0);+    let prod = k_inv(c.focal, c.ppx, c.ppy) * c.k();+    for r in 0..3 {+        for cc in 0..3 {+            let want = if r == cc { 1.0 } else { 0.0 };+            assert!(approx(prod[(r, cc)], want), "[{r}{cc}] {}", prod[(r, cc)]);+        }+    }+}++#[test]+fn perturb_focal_only_changes_focal() {+    let base = cam(500.0);+    let p = perturb(&base, 0, 2.5);+    assert!(approx(p.focal, 502.5));+    assert!(approx(p.ppx, base.ppx) && approx(p.ppy, base.ppy));+    assert!(approx(mdiff(&(p.r), &(base.r)), 0.0), "rotation untouched");+}++#[test]+fn perturb_rotation_axes_rotate_and_keep_focal() {+    let base = cam(500.0);+    for axis in 1..=3 {+        let p = perturb(&base, axis, 0.01);+        assert!(approx(p.focal, 500.0));+        assert!(approx(p.r.determinant(), 1.0), "still a rotation");+        assert!(mdiff(&(p.r), &(base.r)) > 1e-6, "axis {axis} must move R");+    }+    // Zero delta leaves the camera unchanged on every parameter.+    for j in 0..4 {+        let p = perturb(&base, j, 0.0);+        assert!(approx(p.focal, base.focal));+        assert!(approx(mdiff(&(p.r), &(base.r)), 0.0));+    }+}++#[test]+fn apply_increment_zero_vector_is_identity() {+    let cams = vec![cam(400.0), cam(600.0)];+    let x = DVector::zeros(8);+    let out = apply_increment(&cams, &x);+    for (a, b) in out.iter().zip(cams.iter()) {+        assert!(approx(a.focal, b.focal));+        assert!(approx(mdiff(&(a.r), &(b.r)), 0.0));+        assert!(approx(a.aspect, 1.0), "increment normalises aspect to 1");+    }+}++#[test]+fn apply_increment_focal_slot_moves_only_that_camera() {+    let cams = vec![cam(400.0), cam(600.0)];+    let mut x = DVector::zeros(8);+    x[4] = 25.0; // camera 1 focal slot+    let out = apply_increment(&cams, &x);+    assert!(approx(out[0].focal, 400.0));+    assert!(approx(out[1].focal, 625.0));+}++#[test]+fn edge_res_is_zero_for_identical_cameras_and_points() {+    let c = cam(800.0);+    let corr = vec![((100.0f32, 120.0f32), (100.0f32, 120.0f32)), ((0.0, 0.0), (0.0, 0.0))];+    let r = edge_res(&c, &c, &corr);+    assert_eq!(r.len(), 6);+    assert!(r.iter().all(|v| approx(*v, 0.0)), "same rays: {r:?}");+}++#[test]+fn edge_res_grows_when_second_point_moves() {+    let c = cam(800.0);+    let same = edge_res(&c, &c, &[((100.0f32, 100.0f32), (100.0, 100.0))]);+    let moved = edge_res(&c, &c, &[((100.0f32, 100.0f32), (140.0, 100.0))]);+    let n_same: f64 = same.iter().map(|v| v * v).sum();+    let n_moved: f64 = moved.iter().map(|v| v * v).sum();+    assert!(n_moved > n_same + 1.0, "moved point must raise residual ({n_moved} vs {n_same})");+    assert_eq!(total_cost(&[c.clone(), c.clone()], &[Edge { i: 0, j: 1, corr: vec![((1.0f32, 1.0f32), (1.0, 1.0))] }]), 0.0);+}++#[test]+fn bundle_adjust_noops_without_enough_cameras_or_edges() {+    // Fewer than two cameras.+    let mut one = vec![cam(500.0)];+    bundle_adjust(&mut one, &[]);+    assert!(approx(one[0].focal, 500.0));+    // Two cameras but no matches at all.+    let mut two = vec![cam(500.0), cam(500.0)];+    bundle_adjust(&mut two, &[]);+    assert!(two.iter().all(|c| approx(c.focal, 500.0)));+    // Matches below the bundle confidence threshold are ignored.+    let weak = MatchInfo {+        src: 0,+        dst: 1,+        h: Matrix3::identity(),+        inliers: vec![((0.0f32, 0.0f32), (5.0, 5.0))],+        confidence: BUNDLE_CONF_THRESH, // not > thresh+        num_inliers: 1,+    };+    bundle_adjust(&mut two, &[weak]);+    assert!(two.iter().all(|c| approx(c.focal, 500.0)), "sub-threshold edge must not move cameras");+}++#[test]+fn bundle_adjust_keeps_consistent_cameras_nearly_fixed() {+    // Perfectly consistent correspondences (identical cameras/points) have+    // zero residual; LM must not wander away from the optimum.+    let corr: Vec<(Pt, Pt)> = (0..6)+        .map(|i| {+            let p = (50.0 + 30.0 * i as f32, 60.0 + 17.0 * i as f32);+            (p, p)+        })+        .collect();+    let m = MatchInfo {+        src: 0,+        dst: 1,+        h: Matrix3::identity(),+        inliers: corr,+        confidence: 0.9,+        num_inliers: 6,+    };+    let mut cams = vec![cam(700.0), cam(700.0)];+    bundle_adjust(&mut cams, &[m]);+    for c in &cams {+        assert!((c.focal - 700.0).abs() < 1.0, "focal drifted to {}", c.focal);+        assert!(mdiff(&(c.r), &(Matrix3::identity())) < 1e-3, "rotation drifted");+    }+}
camera/src/main/rust/src/estimator.rs
diff --git a/camera/src/main/rust/src/estimator.rs b/camera/src/main/rust/src/estimator.rsindex 69a9dde4c5..ba9da2f03e 100644--- a/camera/src/main/rust/src/estimator.rs+++ b/camera/src/main/rust/src/estimator.rs@@ -78,3 +78,7 @@ pub fn estimate_cameras(n: usize, w: usize, h: usize, matches: &[MatchInfo]) ->     }     cams }++#[cfg(test)]+#[path = "estimator_tests.rs"]+mod estimator_tests;
camera/src/main/rust/src/estimator_tests.rs
diff --git a/camera/src/main/rust/src/estimator_tests.rs b/camera/src/main/rust/src/estimator_tests.rsnew file mode 100644index 0000000000..ed7fe7d9f3--- /dev/null+++ b/camera/src/main/rust/src/estimator_tests.rs@@ -0,0 +1,86 @@+//! Tests for estimator.rs: camera estimation with no / weak / chained+//! matches, checking focal fallback and rotation validity.+fn mdiff(a: &Matrix3<f64>, b: &Matrix3<f64>) -> f64 {+    let mut s = 0.0f64;+    for r in 0..3 { for c in 0..3 { let d = a[(r, c)] - b[(r, c)]; s += d * d; } }+    s.sqrt()+}+++use super::*;+use crate::linalg::Matrix3;++fn approx(a: f64, b: f64, tol: f64) -> bool {+    (a - b).abs() <= tol+}++fn assert_rotation(r: &Matrix3<f64>) {+    assert!(r.determinant().abs() > 0.5, "near-singular rotation, det {}", r.determinant());+    let p = *r * r.transpose();+    for i in 0..3 {+        for j in 0..3 {+            let want = if i == j { 1.0 } else { 0.0 };+            assert!(approx(p[(i, j)], want, 1e-6), "orthonormal [{i}{j}] {}", p[(i, j)]);+        }+    }+}++fn mi(src: usize, dst: usize, h: Matrix3<f64>, inl: usize, conf: f64) -> MatchInfo {+    MatchInfo { src, dst, h, inliers: Vec::new(), confidence: conf, num_inliers: inl }+}++#[test]+fn estimate_cameras_single_image_gets_identity() {+    let cams = estimate_cameras(1, 640, 480, &[]);+    assert_eq!(cams.len(), 1);+    assert!(approx(mdiff(&(cams[0].r), &(Matrix3::identity())), 0.0, 1e-12));+    assert!(approx(cams[0].focal, 1120.0, 1e-9), "fallback focal w+h");+    assert!(approx(cams[0].ppx, 320.0, 1e-12) && approx(cams[0].ppy, 240.0, 1e-12));+}++#[test]+fn estimate_cameras_disconnected_images_all_identity() {+    let cams = estimate_cameras(3, 640, 480, &[]);+    assert_eq!(cams.len(), 3);+    for c in &cams {+        assert!(approx(mdiff(&(c.r), &(Matrix3::identity())), 0.0, 1e-9));+        assert!(approx(c.focal, 1120.0, 1e-9));+        assert_rotation(&c.r);+    }+}++#[test]+fn estimate_cameras_identity_homography_chain_keeps_identity() {+    // Identity homographies carry no focal, so the fallback focal applies+    // and CalcRotation yields identity relative rotations.+    let matches = vec![mi(0, 1, Matrix3::identity(), 50, 0.9), mi(1, 2, Matrix3::identity(), 40, 0.9)];+    let cams = estimate_cameras(3, 640, 480, &matches);+    assert_eq!(cams.len(), 3);+    for c in &cams {+        assert!(approx(mdiff(&(c.r), &(Matrix3::identity())), 0.0, 1e-6), "identity chain must stay identity");+        assert_rotation(&c.r);+    }+}++#[test]+fn estimate_cameras_root_is_middle_image_with_identity() {+    // Root is n/2; with no matches every camera (root included) is identity,+    // and the root index for 4 cameras is 2.+    let cams = estimate_cameras(4, 800, 600, &[]);+    assert_eq!(cams.len(), 4);+    assert!(approx(mdiff(&(cams[2].r), &(Matrix3::identity())), 0.0, 1e-12));+    assert!(approx(cams[0].focal, 1400.0, 1e-9), "w+h fallback");+    assert!(approx(cams[0].ppx, 400.0, 1e-12) && approx(cams[0].ppy, 300.0, 1e-12));+}++#[test]+fn estimate_cameras_singular_homography_does_not_panic() {+    let zero = Matrix3::new(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);+    let matches = vec![mi(0, 1, zero, 10, 0.5)];+    let cams = estimate_cameras(2, 320, 240, &matches);+    assert_eq!(cams.len(), 2);+    for c in &cams {+        assert!(c.focal.is_finite() && c.focal > 1.0);+        assert_rotation(&c.r);+    }+}
camera/src/main/rust/src/exposure.rs
diff --git a/camera/src/main/rust/src/exposure.rs b/camera/src/main/rust/src/exposure.rsindex a2bc9f1521..0c65a87e8a 100644--- a/camera/src/main/rust/src/exposure.rs+++ b/camera/src/main/rust/src/exposure.rs@@ -312,3 +312,7 @@ mod exposure_host_tests {         }     } }++#[cfg(test)]+#[path = "exposure_tests.rs"]+mod exposure_tests;
camera/src/main/rust/src/exposure_tests.rs
diff --git a/camera/src/main/rust/src/exposure_tests.rs b/camera/src/main/rust/src/exposure_tests.rsnew file mode 100644index 0000000000..488b4c9f4e--- /dev/null+++ b/camera/src/main/rust/src/exposure_tests.rs@@ -0,0 +1,97 @@+//! Tests for exposure.rs private helpers (luma norm, separable smoothing)+//! and compensate() contracts on synthetic warped tiles.++use super::*;+use crate::imgbuf::Rgba;+use crate::sphere::WarpedTile;++fn tile(w: usize, h: usize, cx: i32, cy: i32, v: u8) -> WarpedTile {+    let mut img = Rgba::new(w, h);+    for y in 0..h {+        for x in 0..w {+            img.set(x, y, [v, v, v, 255]);+        }+    }+    WarpedTile { img, corner_x: cx, corner_y: cy }+}++#[test]+fn luma_norm_is_euclidean_length() {+    assert_eq!(luma_norm([3, 4, 0, 255]), 5.0);+    assert_eq!(luma_norm([0, 0, 0, 255]), 0.0);+    let white = luma_norm([255, 255, 255, 0]); // alpha ignored+    assert!((white - (3.0f64 * 255.0 * 255.0).sqrt()).abs() < 1e-9);+}++#[test]+fn sep_filter_preserves_constant_plane() {+    let mut src = vec![4.0f32; 36];+    sep_filter_025_05_025(&mut src, 6, 6);+    assert!(src.iter().all(|v| (*v - 4.0).abs() < 1e-6));+}++#[test]+fn sep_filter_smooths_a_spike_toward_neighbours() {+    // Single bright centre in a 3x3: after one pass the centre drops and+    // the (clamped-border) neighbours rise; mass stays in a sane band.+    let mut src = vec![0.0f32; 9];+    src[4] = 16.0;+    sep_filter_025_05_025(&mut src, 3, 3);+    assert!(src[4] < 16.0 && src[4] > 0.0, "centre smoothed: {}", src[4]);+    assert!(src.iter().all(|v| *v >= 0.0));+    let total: f32 = src.iter().sum();+    assert!(total > 8.0 && total < 24.0, "mass roughly kept, got {total}");+}++#[test]+fn sep_filter_single_pixel_is_unchanged() {+    let mut src = vec![9.0f32];+    sep_filter_025_05_025(&mut src, 1, 1);+    assert_eq!(src, vec![9.0]);+}++#[test]+fn compensate_single_tile_is_unity_gain() {+    // No overlaps -> no equations -> all gains default to 1.+    let tiles = vec![tile(40, 40, 0, 0, 128)];+    let gains = compensate(&tiles);+    assert_eq!(gains.len(), 1);+    assert_eq!(gains[0].len(), 40 * 40);+    assert!(gains[0].iter().all(|v| *v == 1.0));+}++#[test]+fn compensate_equal_brightness_overlap_stays_near_unity() {+    // Two identical-brightness overlapping tiles: the gain solver should+    // keep both near 1 (nothing to correct), finite and within clamps.+    let tiles = vec![tile(48, 48, 0, 0, 150), tile(48, 48, 24, 0, 150)];+    let gains = compensate(&tiles);+    assert_eq!(gains.len(), 2);+    for g in &gains {+        assert_eq!(g.len(), 48 * 48);+        for v in g {+            assert!(v.is_finite() && (0.25..=4.0).contains(v), "gain {v} outside clamp");+            assert!((*v - 1.0).abs() < 0.35, "equal inputs should stay near unity, got {v}");+        }+    }+}++#[test]+fn compensate_dark_tile_gets_gain_above_bright_tile() {+    // Overlapping dark (60) vs bright (180): compensation must push the+    // dark tile's gain up relative to the bright tile's.+    let tiles = vec![tile(48, 48, 0, 0, 60), tile(48, 48, 24, 0, 180)];+    let gains = compensate(&tiles);+    let mean = |g: &[f32]| g.iter().sum::<f32>() / g.len() as f32;+    assert!(mean(&gains[0]) > mean(&gains[1]), "dark {} vs bright {}", mean(&gains[0]), mean(&gains[1]));+}++#[test]+fn compensate_respects_output_shape_for_odd_tile_sizes() {+    let tiles = vec![tile(33, 17, -5, 3, 100), tile(20, 40, 10, -8, 120)];+    let gains = compensate(&tiles);+    for (g, t) in gains.iter().zip(tiles.iter()) {+        assert_eq!(g.len(), t.img.w * t.img.h);+        assert!(g.iter().all(|v| v.is_finite() && *v > 0.0));+    }+}
camera/src/main/rust/src/lib.rs
diff --git a/camera/src/main/rust/src/lib.rs b/camera/src/main/rust/src/lib.rsindex 5693dc294e..2ece9e34b2 100644--- a/camera/src/main/rust/src/lib.rs+++ b/camera/src/main/rust/src/lib.rs@@ -460,3 +460,7 @@ mod jni_bindings {         }     } }++#[cfg(test)]+#[path = "lib_tests.rs"]+mod lib_tests;
camera/src/main/rust/src/lib_tests.rs
diff --git a/camera/src/main/rust/src/lib_tests.rs b/camera/src/main/rust/src/lib_tests.rsnew file mode 100644index 0000000000..9a97571bbd--- /dev/null+++ b/camera/src/main/rust/src/lib_tests.rs@@ -0,0 +1,111 @@+//! Tests for lib.rs private helpers: the GPU estimate blob layout and the+//! JPEG encode round trip.++use super::*;+use crate::imgbuf::Rgba;+use crate::linalg::Matrix3;++fn est(cams: Vec<stitch::FrameCam>) -> stitch::Estimate {+    stitch::Estimate { canvas_w: 1200, canvas_h: 700, u0: -12.5, v0: 3.25, scale: 640.0, cams }+}++fn frame_cam(idx: usize, focal: f64, gain: f32) -> stitch::FrameCam {+    stitch::FrameCam {+        original_index: idx,+        focal,+        ppx: 400.0,+        ppy: 300.0,+        r: [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0],+        gain,+    }+}++fn u32_at(b: &[u8], o: usize) -> u32 {+    u32::from_le_bytes(b[o..o + 4].try_into().unwrap())+}+fn f64_at(b: &[u8], o: usize) -> f64 {+    f64::from_le_bytes(b[o..o + 8].try_into().unwrap())+}++#[test]+fn serialize_estimate_empty_cameras_is_header_only() {+    let blob = serialize_estimate(&est(vec![]));+    assert_eq!(blob.len(), 36);+    assert_eq!(u32_at(&blob, 0), 1200);+    assert_eq!(u32_at(&blob, 4), 700);+    assert_eq!(f64_at(&blob, 8), -12.5);+    assert_eq!(f64_at(&blob, 16), 3.25);+    assert_eq!(f64_at(&blob, 24), 640.0);+    assert_eq!(u32_at(&blob, 32), 0);+}++#[test]+fn serialize_estimate_per_camera_record_layout() {+    let blob = serialize_estimate(&est(vec![frame_cam(7, 555.5, 1.25), frame_cam(2, 600.0, 0.75)]));+    let rec = 4 + 8 * 12 + 4;+    assert_eq!(blob.len(), 36 + 2 * rec);+    assert_eq!(u32_at(&blob, 32), 2);+    // First record: index, focal, ppx, ppy, R row-major, gain.+    assert_eq!(u32_at(&blob, 36), 7);+    assert_eq!(f64_at(&blob, 40), 555.5);+    assert_eq!(f64_at(&blob, 48), 400.0);+    assert_eq!(f64_at(&blob, 56), 300.0);+    assert_eq!(f64_at(&blob, 64), 1.0, "R[0]");+    assert_eq!(f64_at(&blob, 72), 0.0, "R[1]");+    assert_eq!(f64_at(&blob, 128), 1.0, "R[8]");+    let gain = f32::from_le_bytes(blob[136..140].try_into().unwrap());+    assert_eq!(gain, 1.25);+    // Second record starts immediately after.+    assert_eq!(u32_at(&blob, 36 + rec), 2);+    assert_eq!(f64_at(&blob, 36 + rec + 4), 600.0);+}++#[test]+fn serialize_estimate_preserves_rotation_entry_order() {+    let mut c = frame_cam(0, 500.0, 1.0);+    c.r = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];+    let blob = serialize_estimate(&est(vec![c]));+    for j in 0..9 {+        assert_eq!(f64_at(&blob, 64 + 8 * j), j as f64, "R[{j}] order");+    }+    let _ = Matrix3::<f64>::identity(); // keep import used if layout changes+}++#[test]+fn encode_jpeg_round_trips_dimensions_and_rough_colour() {+    let mut img = Rgba::new(16, 12);+    for y in 0..12 {+        for x in 0..16 {+            img.set(x, y, [200, 40, 30, 255]);+        }+    }+    let bytes = encode_jpeg(&img, 95).expect("encode");+    assert!(bytes.len() > 20 && bytes[0] == 0xFF && bytes[1] == 0xD8, "JPEG SOI marker");+    let back = Rgba::from_jpeg(&bytes).expect("decode own JPEG");+    assert_eq!((back.w, back.h), (16, 12));+    let centre = back.get(8, 6);+    assert!((centre[0] as i32 - 200).abs() < 8, "red drifted: {centre:?}");+    assert!((centre[1] as i32 - 40).abs() < 8);+    assert!((centre[2] as i32 - 30).abs() < 8);+}++#[test]+fn encode_jpeg_drops_alpha_but_keeps_rgb() {+    let mut img = Rgba::new(4, 4);+    for y in 0..4 {+        for x in 0..4 {+            img.set(x, y, [10, 220, 90, 0]); // alpha 0, RGB still encoded+        }+    }+    let bytes = encode_jpeg(&img, 100).expect("encode");+    let back = Rgba::from_jpeg(&bytes).expect("decode");+    let p = back.get(2, 2);+    assert!((p[1] as i32 - 220).abs() < 10, "green kept despite alpha: {p:?}");+}++#[test]+fn next_handle_is_strictly_increasing() {+    let a = next_handle();+    let b = next_handle();+    assert!(b > a, "handles must increase: {a} then {b}");+}
camera/src/main/rust/src/matching.rs
diff --git a/camera/src/main/rust/src/matching.rs b/camera/src/main/rust/src/matching.rsindex c1c891c786..c69f41aa47 100644--- a/camera/src/main/rust/src/matching.rs+++ b/camera/src/main/rust/src/matching.rs@@ -198,3 +198,7 @@ pub fn biggest_component(n: usize, matches: &[MatchInfo], conf_thresh: f64) -> V     kept.sort_unstable();     kept }++#[cfg(test)]+#[path = "matching_tests.rs"]+mod matching_tests;
camera/src/main/rust/src/matching_tests.rs
diff --git a/camera/src/main/rust/src/matching_tests.rs b/camera/src/main/rust/src/matching_tests.rsnew file mode 100644index 0000000000..bdca6737f0--- /dev/null+++ b/camera/src/main/rust/src/matching_tests.rs@@ -0,0 +1,123 @@+//! Tests for matching.rs private helpers (gyro angular distance) and the+//! public component / matching entry points with synthetic features.++use super::*;+use crate::features::{Features, KeyPoint};+use crate::linalg::Matrix3;++#[test]+fn angular_dist_zero_for_same_orientation() {+    let yaw = [10.0f32, 10.0];+    let pitch = [5.0f32, 5.0];+    assert_eq!(angular_dist(&yaw, &pitch, 0, 1), 0.0);+}++#[test]+fn angular_dist_wraps_yaw_across_zero() {+    // 359° and 1° are 2° apart, not 358°.+    let yaw = [359.0f32, 1.0];+    let pitch = [0.0f32, 0.0];+    assert!((angular_dist(&yaw, &pitch, 0, 1) - 2.0).abs() < 1e-5);+    let yaw2 = [1.0f32, 359.0];+    assert!((angular_dist(&yaw2, &pitch, 0, 1) - 2.0).abs() < 1e-5);+}++#[test]+fn angular_dist_combines_yaw_and_pitch_as_euclidean() {+    let yaw = [0.0f32, 3.0];+    let pitch = [0.0f32, 4.0];+    assert!((angular_dist(&yaw, &pitch, 0, 1) - 5.0).abs() < 1e-5, "3-4-5");+}++#[test]+fn angular_dist_exactly_opposite_yaw_is_180() {+    let yaw = [0.0f32, 180.0];+    let pitch = [0.0f32, 0.0];+    assert!((angular_dist(&yaw, &pitch, 0, 1) - 180.0).abs() < 1e-4);+}++fn mi(src: usize, dst: usize, conf: f64) -> MatchInfo {+    MatchInfo {+        src,+        dst,+        h: Matrix3::identity(),+        inliers: Vec::new(),+        confidence: conf,+        num_inliers: 0,+    }+}++#[test]+fn biggest_component_keeps_largest_confident_group() {+    // {0,1,2} linked confidently, {3,4} linked, 5 isolated.+    let matches = vec![mi(0, 1, 0.9), mi(1, 2, 0.9), mi(3, 4, 0.9)];+    assert_eq!(biggest_component(6, &matches, 0.3), vec![0, 1, 2]);+}++#[test]+fn biggest_component_ignores_low_confidence_edges() {+    let matches = vec![mi(0, 1, 0.1), mi(2, 3, 0.9)];+    // Only 2-3 is a real edge; every other node is a singleton component of+    // size 1, so the kept component is exactly {2,3}.+    assert_eq!(biggest_component(4, &matches, 0.3), vec![2, 3]);+}++#[test]+fn biggest_component_no_matches_keeps_first_singleton() {+    // All singletons tie at size 1; max_by_key keeps the last maximum, and+    // the result is still a single (sorted) index.+    let kept = biggest_component(3, &[], 0.3);+    assert_eq!(kept.len(), 1);+    assert!(kept[0] < 3);+}++#[test]+fn biggest_component_all_confident_keeps_everything_sorted() {+    let matches = vec![mi(2, 0, 1.0), mi(0, 1, 1.0)];+    assert_eq!(biggest_component(3, &matches, 0.3), vec![0, 1, 2]);+}++fn empty_feats(n: usize) -> Vec<Features> {+    (0..n)+        .map(|_| Features {+            kps: vec![KeyPoint { x: 1.0, y: 1.0, angle: 0.0, score: 1.0 }],+            desc: Vec::new(),+            w: 100,+            h: 100,+        })+        .collect()+}++#[test]+fn match_all_with_no_descriptors_matches_nothing() {+    let feats = empty_feats(3);+    assert!(match_all(&feats, &[0.0, 10.0, 20.0], &[0.0, 0.0, 0.0], 55.0).is_empty());+    assert!(match_all(&[], &[], &[], 55.0).is_empty());+    assert!(match_all(&feats[..1], &[0.0], &[0.0], 55.0).is_empty());+}++#[test]+fn match_all_gyro_gate_excludes_distant_pairs() {+    // Descriptors are absent so nothing can match either way; the gate is+    // observable only through "no panic + empty", while nearby pairs are+    // attempted. Use identical strong descriptors so attempted pairs would+    // match, proving the gate (not the matcher) suppressed distant pairs.+    let desc = vec![[7u8; 32]; 8];+    let mk = |desc: Vec<[u8; 32]>| Features {+        kps: (0..8)+            .map(|i| KeyPoint { x: 10.0 + (i % 4) as f32 * 20.0, y: 10.0 + (i / 4) as f32 * 20.0, angle: 0.0, score: 1.0 })+            .collect(),+        desc,+        w: 100,+        h: 100,+    };+    let feats = vec![mk(desc.clone()), mk(desc)];+    // Same orientation: pair attempted (result may still be empty because+    // identical descriptors are ratio-ambiguous — the point is it runs).+    let _ = match_all(&feats, &[0.0, 5.0], &[0.0, 0.0], 55.0);+    // 170° apart with a 55° gate: pair never attempted.+    let gated = match_all(&feats, &[0.0, 170.0], &[0.0, 0.0], 55.0);+    assert!(gated.is_empty(), "gyro gate must suppress distant pairs");+    // Mismatched yaw length disables the gate (falls back to all pairs).+    let _ = match_all(&feats, &[0.0], &[0.0, 0.0], 55.0);+}
camera/src/main/rust/src/night.rs
diff --git a/camera/src/main/rust/src/night.rs b/camera/src/main/rust/src/night.rsindex 9019347c13..79f3e82dd8 100644--- a/camera/src/main/rust/src/night.rs+++ b/camera/src/main/rust/src/night.rs@@ -161,3 +161,7 @@ pub fn align_and_merge(frames: &[Rgba]) -> Option<Rgba> {     }     Some(out) }++#[cfg(test)]+#[path = "night_tests.rs"]+mod night_tests;
camera/src/main/rust/src/night_tests.rs
diff --git a/camera/src/main/rust/src/night_tests.rs b/camera/src/main/rust/src/night_tests.rsnew file mode 100644index 0000000000..e7b0226bbd--- /dev/null+++ b/camera/src/main/rust/src/night_tests.rs@@ -0,0 +1,100 @@+//! Tests for night.rs private helpers (homography application / rescaling)+//! and the public burst-merge entry point on synthetic frames.++use super::*;+use crate::linalg::Matrix3;++fn approx(a: f64, b: f64) -> bool {+    (a - b).abs() <= 1e-9+}++#[test]+fn apply_identity_and_translation_homographies() {+    let (x, y) = apply(&Matrix3::identity(), 3.0, -2.0);+    assert!(approx(x, 3.0) && approx(y, -2.0));+    let t = Matrix3::new(1.0, 0.0, 5.0, 0.0, 1.0, -3.0, 0.0, 0.0, 1.0);+    let (x, y) = apply(&t, 1.0, 1.0);+    assert!(approx(x, 6.0) && approx(y, -2.0));+}++#[test]+fn apply_normalises_by_z() {+    // Uniform scale of the homogeneous vector must not move the point.+    let s = Matrix3::new(2.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 2.0);+    let (x, y) = apply(&s, 4.0, 6.0);+    assert!(approx(x, 4.0) && approx(y, 6.0));+}++#[test]+fn scale_homography_unit_scale_is_identity_operation() {+    let h = Matrix3::new(1.0, 0.1, 7.0, -0.2, 1.0, -4.0, 0.001, 0.002, 1.0);+    let out = scale_homography(&h, 1.0);+    for r in 0..3 {+        for c in 0..3 {+            assert!(approx(out[(r, c)], h[(r, c)]), "[{r}{c}]");+        }+    }+}++#[test]+fn scale_homography_matches_sandwich_formula() {+    // H_full = S^-1 H S with S = diag(s,s,1), s = 0.5.+    let h = Matrix3::new(1.0, 0.1, 7.0, -0.2, 1.0, -4.0, 0.001, 0.002, 1.0);+    let out = scale_homography(&h, 0.5);+    assert!(approx(out[(0, 2)], 7.0 / 0.5));+    assert!(approx(out[(1, 2)], -4.0 / 0.5));+    assert!(approx(out[(2, 0)], 0.001 * 0.5));+    assert!(approx(out[(2, 1)], 0.002 * 0.5));+    assert!(approx(out[(0, 0)], 1.0) && approx(out[(2, 2)], 1.0));+}++#[test]+fn scale_homography_keeps_point_mapping_equivalent() {+    // A point mapped at small scale then upscaled equals mapping at full+    // scale with the rescaled homography.+    let h = Matrix3::new(1.0, 0.0, 3.0, 0.0, 1.0, -2.0, 0.0, 0.0, 1.0);+    let s = 0.25;+    let (sx, sy) = apply(&h, 8.0, 8.0);+    let (fx, fy) = apply(&scale_homography(&h, s), 8.0 / s, 8.0 / s);+    assert!(approx(fx, sx / s) && approx(fy, sy / s), "({fx},{fy}) vs ({},{})", sx / s, sy / s);+}++fn solid(w: usize, h: usize, c: [u8; 4]) -> Rgba {+    let mut img = Rgba::new(w, h);+    for y in 0..h {+        for x in 0..w {+            img.set(x, y, c);+        }+    }+    img+}++#[test]+fn align_and_merge_degenerate_inputs() {+    assert!(align_and_merge(&[]).is_none());+    let one = solid(6, 4, [12, 34, 56, 255]);+    let out = align_and_merge(&[one.clone()]).expect("single frame passes through");+    assert_eq!(out.px, one.px);+}++#[test]+fn align_and_merge_identical_frames_returns_same_image() {+    let f = solid(24, 18, [90, 80, 70, 255]);+    let out = align_and_merge(&[f.clone(), f.clone(), f.clone()]).expect("merge");+    assert_eq!((out.w, out.h), (24, 18));+    assert!(out.px.chunks_exact(4).all(|p| p == [90, 80, 70, 255]));+}++#[test]+fn align_and_merge_output_size_follows_reference_frame() {+    let a = solid(10, 8, [10, 10, 10, 255]);+    let b = solid(10, 8, [20, 20, 20, 255]);+    let out = align_and_merge(&[a, b]).expect("merge");+    assert_eq!((out.w, out.h), (10, 8));+    // Every output pixel is an average of contributing frames, hence lies+    // between the two input brightnesses and is fully opaque.+    for p in out.px.chunks_exact(4) {+        assert_eq!(p[3], 255);+        assert!(p[0] >= 10 && p[0] <= 20, "channel {p:?} outside input range");+    }+}
camera/src/main/rust/src/seam.rs
diff --git a/camera/src/main/rust/src/seam.rs b/camera/src/main/rust/src/seam.rsindex 901636bd2f..2a188621cd 100644--- a/camera/src/main/rust/src/seam.rs+++ b/camera/src/main/rust/src/seam.rs@@ -445,3 +445,7 @@ impl MaxFlow {         side     } }++#[cfg(test)]+#[path = "seam_tests.rs"]+mod seam_tests;
camera/src/main/rust/src/seam_tests.rs
diff --git a/camera/src/main/rust/src/seam_tests.rs b/camera/src/main/rust/src/seam_tests.rsnew file mode 100644index 0000000000..f8c53fc57b--- /dev/null+++ b/camera/src/main/rust/src/seam_tests.rs@@ -0,0 +1,174 @@+//! Tests for seam.rs private helpers: max-flow min-cut, gradient maps,+//! colour differences, neighbourhood helpers, and the seam-mask contracts.++use super::*;+use crate::sphere::WarpedTile;++fn tile(w: usize, h: usize, cx: i32, cy: i32, c: [u8; 4]) -> WarpedTile {+    let mut img = Rgba::new(w, h);+    for y in 0..h {+        for x in 0..w {+            img.set(x, y, c);+        }+    }+    WarpedTile { img, corner_x: cx, corner_y: cy }+}++#[test]+fn max_flow_single_edge_moves_full_capacity() {+    let mut mf = MaxFlow::new(2);+    mf.add_edge(0, 1, 7, 0);+    assert_eq!(mf.max_flow(0, 1), 7);+    let side = mf.min_cut_side(0);+    assert!(side[0] && !side[1], "saturated edge separates s from t");+}++#[test]+fn max_flow_bottleneck_is_the_min_cut() {+    // 0 -> 1 (10), 1 -> 2 (3), 0 -> 2 (2): max flow 5, cut capacity 5.+    let mut mf = MaxFlow::new(3);+    mf.add_edge(0, 1, 10, 10);+    mf.add_edge(1, 2, 3, 3);+    mf.add_edge(0, 2, 2, 2);+    assert_eq!(mf.max_flow(0, 2), 5);+}++#[test]+fn max_flow_disconnected_sink_flows_zero() {+    let mut mf = MaxFlow::new(3);+    mf.add_edge(0, 1, 5, 5);+    assert_eq!(mf.max_flow(0, 2), 0);+    assert!(mf.min_cut_side(0)[1], "reachable node stays on source side");+}++#[test]+fn max_flow_parallel_paths_add_up() {+    let mut mf = MaxFlow::new(4);+    mf.add_edge(0, 1, 4, 4);+    mf.add_edge(0, 2, 6, 6);+    mf.add_edge(1, 3, 4, 4);+    mf.add_edge(2, 3, 6, 6);+    assert_eq!(mf.max_flow(0, 3), 10);+}++#[test]+fn diff_l2_is_zero_for_equal_and_grows_with_distance() {+    assert_eq!(diff_l2([10, 20, 30, 255], [10, 20, 30, 0]), 0, "alpha ignored");+    assert_eq!(diff_l2([0, 0, 0, 255], [3, 4, 0, 255]), 5, "3-4-5 triangle");+    let far = diff_l2([0, 0, 0, 255], [255, 255, 255, 255]);+    assert!(far > 400, "white vs black L2 ~441, got {far}");+}++#[test]+fn luma_i_matches_rec601_approximately() {+    assert_eq!(luma_i([255, 0, 0, 255]), (0.299 * 255.0) as i64);+    assert_eq!(luma_i([0, 0, 0, 255]), 0);+    assert!(luma_i([255, 255, 255, 255]) >= 254);+}++#[test]+fn gradient_map_is_zero_on_flat_and_positive_on_edges() {+    let flat = tile(8, 8, 0, 0, [100, 100, 100, 255]);+    assert!(gradient_map(&flat.img).iter().all(|&g| g == 0));+    // Left half black, right half white: gradient concentrated at the seam.+    let mut img = Rgba::new(8, 4);+    for y in 0..4 {+        for x in 0..8 {+            let v = if x < 4 { 0 } else { 255 };+            img.set(x, y, [v, v, v, 255]);+        }+    }+    let g = gradient_map(&img);+    assert!(g[1 * 8 + 3] > 0 && g[1 * 8 + 4] > 0, "edge columns respond");+    assert_eq!(g[1 * 8], 0, "flat interior has no gradient");+    // Transparent pixels never produce gradient.+    let clear = gradient_map(&Rgba::new(4, 4));+    assert!(clear.iter().all(|&v| v == 0));+}++#[test]+fn neighbors_at_corners_and_centre() {+    assert_eq!(neighbors(0, 0, 3, 3).len(), 2);+    assert_eq!(neighbors(2, 2, 3, 3).len(), 2);+    assert_eq!(neighbors(1, 1, 3, 3).len(), 4);+    assert_eq!(neighbors(0, 1, 3, 3).len(), 3);+}++#[test]+fn global_bounds_covers_all_tiles_including_negative_corners() {+    let tiles = vec![tile(10, 8, -5, -3, [0, 0, 0, 255]), tile(4, 4, 20, 10, [0, 0, 0, 255])];+    assert_eq!(global_bounds(&tiles), (-5, -3, 24, 14));+}++#[test]+fn tile_at_and_covered_by_respect_bounds_and_alpha() {+    let t = tile(4, 4, 10, 20, [5, 6, 7, 255]);+    assert_eq!(tile_at(&t, 10, 20), Some([5, 6, 7, 255]));+    assert!(tile_at(&t, 9, 20).is_none());+    assert!(tile_at(&t, 14, 20).is_none());+    assert!(covered_by(&t, 13, 23));+    assert!(!covered_by(&t, 14, 23));+    let clear = tile(2, 2, 0, 0, [5, 6, 7, 0]);+    assert!(!covered_by(&clear, 0, 0), "transparent is not coverage");+}++#[test]+fn voronoi_masks_empty_and_single_tile() {+    assert!(voronoi_masks(&[]).is_empty());+    let t = vec![tile(6, 5, 3, 2, [9, 9, 9, 255])];+    let m = voronoi_masks(&t);+    assert_eq!(m.len(), 1);+    assert!(m[0].iter().all(|&v| v == 1), "sole tile owns all its pixels");+}++#[test]+fn voronoi_masks_partition_overlap_between_nearest_centres() {+    let tiles = vec![+        tile(10, 6, 0, 0, [255, 0, 0, 255]),+        tile(10, 6, 6, 0, [0, 0, 255, 255]),+    ];+    let masks = voronoi_masks(&tiles);+    let total: usize = masks.iter().map(|m| m.iter().filter(|&&v| v != 0).count()).sum();+    assert_eq!(total, 16 * 6, "union covered exactly once");+    // Leftmost column belongs to tile 0, rightmost to tile 1.+    assert_eq!(masks[0][0], 1);+    assert_eq!(masks[1][5 * 10 + 9], 1);+}++#[test]+fn seam_masks_agree_with_voronoi_on_disjoint_tiles() {+    let tiles = vec![+        tile(5, 5, 0, 0, [255, 0, 0, 255]),+        tile(5, 5, 30, 0, [0, 255, 0, 255]),+    ];+    let masks = seam_masks(&tiles);+    assert_eq!(masks.len(), 2);+    assert!(masks.iter().all(|m| m.iter().all(|&v| v == 1)));+    assert!(seam_masks(&[]).is_empty());+}++#[test]+fn seam_masks_partition_overlapping_coverage_exactly_once() {+    let tiles = vec![+        tile(12, 8, 0, 0, [200, 30, 30, 255]),+        tile(12, 8, 6, 2, [30, 30, 200, 255]),+    ];+    let masks = seam_masks(&tiles);+    // Union is the bounding box minus the two uncovered corners: compute+    // coverage from alpha and compare counts.+    let mut covered = 0usize;+    for gy in 0..10 {+        for gx in 0..18 {+            let cov = tiles.iter().any(|t| {+                let lx = gx - t.corner_x;+                let ly = gy - t.corner_y;+                lx >= 0 && ly >= 0 && (lx as usize) < t.img.w && (ly as usize) < t.img.h+            });+            if cov {+                covered += 1;+            }+        }+    }+    let owned: usize = masks.iter().map(|m| m.iter().filter(|&&v| v != 0).count()).sum();+    assert_eq!(owned, covered, "every covered pixel owned exactly once");+}
camera/src/main/rust/src/sphere.rs
diff --git a/camera/src/main/rust/src/sphere.rs b/camera/src/main/rust/src/sphere.rsindex 4730f1ebac..fa67d95432 100644--- a/camera/src/main/rust/src/sphere.rs+++ b/camera/src/main/rust/src/sphere.rs@@ -359,3 +359,7 @@ mod sphere_host_tests {         assert!((y - 240.0).abs() < 1e-6, "y {y}");     } }++#[cfg(test)]+#[path = "sphere_tests.rs"]+mod sphere_tests;
camera/src/main/rust/src/sphere_tests.rs
diff --git a/camera/src/main/rust/src/sphere_tests.rs b/camera/src/main/rust/src/sphere_tests.rsnew file mode 100644index 0000000000..191ea26ff2--- /dev/null+++ b/camera/src/main/rust/src/sphere_tests.rs@@ -0,0 +1,184 @@+//! Tests for sphere.rs: focal estimation from homographies, the spherical+//! projector round trip, orthonormalisation, and single-image warping.+fn mdiff(a: &Matrix3<f64>, b: &Matrix3<f64>) -> f64 {+    let mut s = 0.0f64;+    for r in 0..3 { for c in 0..3 { let d = a[(r, c)] - b[(r, c)]; s += d * d; } }+    s.sqrt()+}+++use super::*;+use crate::camera::rodrigues_to_mat;+use crate::linalg::Vector3;++fn approx(a: f64, b: f64, tol: f64) -> bool {+    (a - b).abs() <= tol+}++#[test]+fn k_matrix_layout() {+    let k = k_matrix(500.0, 320.0, 240.0);+    assert!(approx(k[(0, 0)], 500.0, 1e-12) && approx(k[(1, 1)], 500.0, 1e-12));+    assert!(approx(k[(0, 2)], 320.0, 1e-12) && approx(k[(1, 2)], 240.0, 1e-12));+    assert!(approx(k[(2, 0)], 0.0, 1e-12) && approx(k[(2, 2)], 1.0, 1e-12));+}++#[test]+fn focals_from_identity_and_translation_have_no_valid_focal() {+    // Identity: denominators vanish / estimates non-positive after sanitize.+    let (f0, f1) = focals_from_homography(&Matrix3::identity());+    assert!(f0.is_none() && f1.is_none());+    // Pure translation homography carries no focal information either.+    let t = Matrix3::new(1.0, 0.0, 12.0, 0.0, 1.0, -4.0, 0.0, 0.0, 1.0);+    let (f0, f1) = focals_from_homography(&t);+    assert!(f0.is_none() && f1.is_none());+}++#[test]+fn focals_from_rotation_homography_recover_known_focal() {+    // H = K R K^-1 for a real rotation: both focal estimates should land+    // near the focal baked into K (the equations OpenCV solves).+    let f_true = 500.0;+    let k = k_matrix(f_true, 320.0, 240.0);+    let kinv = k.try_inverse().expect("K invertible");+    let r = rodrigues_to_mat(Vector3::new(0.03, 0.25, -0.02));+    let h = k * r * kinv;+    let (f0, f1) = focals_from_homography(&h);+    let est = estimate_focal(&[h], 640, 480);+    assert!(est.is_finite() && est > 1.0, "estimate {est}");+    // At least one of the pair must be recoverable for this construction,+    // and the combined estimate should be in a plausible band around truth.+    assert!(f0.is_some() || f1.is_some(), "no focal recovered: {f0:?} {f1:?}");+    assert!(est > 100.0 && est < 2500.0, "implausible focal {est}");+}++#[test]+fn estimate_focal_median_odd_and_even_counts() {+    // Repeat a valid rotation homography: median of identical values is+    // that value for both odd and even counts.+    let k = k_matrix(500.0, 320.0, 240.0);+    let kinv = k.try_inverse().unwrap();+    let r = rodrigues_to_mat(Vector3::new(0.0, 0.3, 0.0));+    let h = k * r * kinv;+    let single = estimate_focal(&[h], 640, 480);+    assert!(single.is_finite() && single > 1.0);+    assert!(approx(estimate_focal(&[h, h, h], 640, 480), single, 1e-9));+    assert!(approx(estimate_focal(&[h, h], 640, 480), single, 1e-9));+    // Junk pairs are skipped, so mixing identity in changes nothing.+    assert!(approx(estimate_focal(&[h, Matrix3::identity(), h], 640, 480), single, 1e-9));+}++#[test]+fn orthonormalize_snaps_scaled_rotation_back_to_rotation() {+    let r = rodrigues_to_mat(Vector3::new(0.1, -0.2, 0.05));+    let scaled = Matrix3::new(r[(0,0)]*1.7, r[(0,1)]*1.7, r[(0,2)]*1.7, r[(1,0)]*1.7, r[(1,1)]*1.7, r[(1,2)]*1.7, r[(2,0)]*1.7, r[(2,1)]*1.7, r[(2,2)]*1.7); // scalar multiple: SVD projection drops the scale+    let o = orthonormalize(&scaled);+    assert!(approx(o.determinant(), 1.0, 1e-9) || approx(o.determinant(), -1.0, 1e-9));+    let prod = o * o.transpose();+    for i in 0..3 {+        for j in 0..3 {+            let want = if i == j { 1.0 } else { 0.0 };+            assert!(approx(prod[(i, j)], want, 1e-9), "orthonormal [{i}{j}]");+        }+    }+    // Direction preserved: the corrected matrix stays close to the input.+    assert!(mdiff(&(o), &(r)) < 0.05, "projection moved the rotation too far");+}++#[test]+fn proj_backward_rejects_points_behind_camera() {+    let k = k_matrix(800.0, 320.0, 240.0);+    let proj = Proj::new(&k, &Matrix3::identity(), 800.0).expect("proj");+    // Forward-map a source point, then confirm the antipodal sphere point+    // (u shifted by PI*scale) projects behind the camera.+    let (u, v) = proj.forward(320.0, 240.0);+    let behind_u = u + std::f64::consts::PI * proj.scale;+    assert!(proj.backward(behind_u, v).is_none(), "antipode must be behind");+}++#[test]+fn proj_forward_backward_round_trips_off_centre() {+    let k = k_matrix(700.0, 320.0, 240.0);+    let r = rodrigues_to_mat(Vector3::new(0.05, 0.1, 0.0));+    let proj = Proj::new(&k, &r, 700.0).expect("proj");+    for &(x, y) in &[(100.0, 80.0), (500.0, 400.0), (320.0, 240.0), (40.0, 440.0)] {+        let (u, v) = proj.forward(x, y);+        let (bx, by) = proj.backward(u, v).expect("front-facing round trip");+        assert!(approx(bx, x, 1e-6), "x {bx} vs {x}");+        assert!(approx(by, y, 1e-6), "y {by} vs {y}");+    }+}++#[test]+fn proj_new_rejects_singular_k() {+    let singular = Matrix3::new(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);+    assert!(Proj::new(&singular, &Matrix3::identity(), 100.0).is_none());+}++#[test]+fn warped_bounds_of_identity_camera_are_finite_and_ordered() {+    let k = k_matrix(400.0, 50.0, 40.0);+    let (u0, v0, u1, v1) = warped_bounds(100, 80, &k, &Matrix3::identity(), 400.0).expect("bounds");+    assert!(u0 <= u1 && v0 <= v1);+    assert!(u0.is_finite() && v0.is_finite() && u1.is_finite() && v1.is_finite());+    // The tile must cover roughly the source extent (within a border walk's+    // tolerance): width on the sphere is comparable to the image width.+    assert!((u1 - u0) > 50.0 && (u1 - u0) < 200.0, "du {}", u1 - u0);+    assert!((v1 - v0) > 40.0 && (v1 - v0) < 160.0, "dv {}", v1 - v0);+}++#[test]+fn warp_one_identity_camera_preserves_centre_colour() {+    let mut img = Rgba::new(32, 24);+    for y in 0..24 {+        for x in 0..32 {+            img.set(x, y, [200, 30, 60, 255]);+        }+    }+    img.set(16, 12, [1, 2, 3, 255]);+    let k = k_matrix(200.0, 16.0, 12.0);+    let tile = warp_one(&img, &k, &Matrix3::identity(), 200.0).expect("warp");+    assert!(tile.img.w > 0 && tile.img.h > 0);+    // The tile centre maps back near the source centre.+    let c = tile.img.get(tile.img.w / 2, tile.img.h / 2);+    assert_eq!(c[3], 255, "centre covered");+    // Bilinear sampling blends the marker into its neighbourhood, so look+    // for a distinctly dark pixel near the tile centre rather than the+    // exact source value.+    let mut found_marker = false;+    for y in 0..tile.img.h {+        for x in 0..tile.img.w {+            let p = tile.img.get(x, y);+            if p[3] == 255 && (p[0] as i32 - 200).abs() > 60 {+                found_marker = true;+            }+        }+    }+    assert!(found_marker, "distinctive centre pixel survives the warp (blended)");+}++#[test]+fn warp_one_transparent_source_yields_no_opaque_pixels() {+    let img = Rgba::new(16, 16); // all alpha 0+    let k = k_matrix(200.0, 8.0, 8.0);+    let tile = warp_one(&img, &k, &Matrix3::identity(), 200.0).expect("warp runs");+    assert!(tile.img.px.chunks_exact(4).all(|p| p[3] == 0), "no coverage from transparent source");+}++#[test]+fn sample_reflect_101_mirrors_at_borders() {+    let mut img = Rgba::new(4, 1);+    img.set(0, 0, [10, 0, 0, 255]);+    img.set(1, 0, [20, 0, 0, 255]);+    img.set(2, 0, [30, 0, 0, 255]);+    img.set(3, 0, [40, 0, 0, 255]);+    // Sampling just left of the image reflects to pixel 1's neighbourhood,+    // not a clamp to pixel 0: value must exceed the border pixel's 10.+    let left = sample_reflect_101(&img, -0.4, 0.0).expect("reflect sample");+    assert!(left[0] > 10.0, "reflected sample {left:?} should blend pixel 1");+    let inside = sample_reflect_101(&img, 1.0, 0.0).expect("inside");+    assert!((inside[0] - 20.0).abs() < 1e-4);+    // Fully transparent neighbourhood samples to None.+    let clear = Rgba::new(4, 4);+    assert!(sample_reflect_101(&clear, 1.0, 1.0).is_none());+}
camera/src/main/rust/src/stitch.rs
diff --git a/camera/src/main/rust/src/stitch.rs b/camera/src/main/rust/src/stitch.rsindex eae7761670..333867bbb3 100644--- a/camera/src/main/rust/src/stitch.rs+++ b/camera/src/main/rust/src/stitch.rs@@ -439,3 +439,7 @@ fn resize_gain(src: &[f32], sw: usize, sh: usize, dw: usize, dh: usize) -> Vec<f     }     out }++#[cfg(test)]+#[path = "stitch_tests.rs"]+mod stitch_tests;
camera/src/main/rust/src/stitch_tests.rs
diff --git a/camera/src/main/rust/src/stitch_tests.rs b/camera/src/main/rust/src/stitch_tests.rsnew file mode 100644index 0000000000..b90a9b492f--- /dev/null+++ b/camera/src/main/rust/src/stitch_tests.rs@@ -0,0 +1,129 @@+//! Tests for stitch.rs private helpers: match remapping, medians, gain resize,+//! compose-mask partitioning, and the public pipeline's degenerate inputs.++use super::*;+use crate::linalg::Matrix3;+use crate::sphere::WarpedTile;++fn mi(src: usize, dst: usize, conf: f64) -> MatchInfo {+    MatchInfo {+        src,+        dst,+        h: Matrix3::identity(),+        inliers: vec![((0.0, 0.0), (1.0, 1.0))],+        confidence: conf,+        num_inliers: 1,+    }+}++#[test]+fn remap_matches_reindexes_and_drops_unkept_frames() {+    let kept = vec![2usize, 5];+    let out = remap_matches(vec![mi(2, 5, 0.9), mi(5, 2, 0.8), mi(0, 2, 0.9)], &kept);+    assert_eq!(out.len(), 2, "match touching dropped frame 0 is removed");+    assert_eq!((out[0].src, out[0].dst), (0, 1));+    assert_eq!((out[1].src, out[1].dst), (1, 0));+}++#[test]+fn remap_matches_with_empty_kept_list_drops_everything() {+    assert!(remap_matches(vec![mi(0, 1, 1.0)], &[]).is_empty());+    assert!(remap_matches(vec![], &[0, 1]).is_empty());+}++fn cam(focal: f64) -> CameraParams {+    CameraParams { focal, aspect: 1.0, ppx: 0.0, ppy: 0.0, r: Matrix3::identity() }+}++#[test]+fn median_focal_odd_even_and_degenerate_inputs() {+    assert_eq!(median_focal(&[cam(100.0), cam(300.0), cam(200.0)]), 200.0);+    assert_eq!(median_focal(&[cam(100.0), cam(200.0), cam(300.0), cam(400.0)]), 250.0);+    assert_eq!(median_focal(&[]), 1.0, "empty falls back to 1.0");+    // Non-finite / implausible focals are filtered before the median.+    assert_eq!(median_focal(&[cam(f64::NAN), cam(0.5), cam(500.0)]), 500.0);+    assert_eq!(median_focal(&[cam(f64::NAN)]), 1.0);+}++#[test]+fn median_f32_filters_nonpositive_and_nonfinite() {+    assert_eq!(median_f32(&[1.0, 3.0, 2.0]), 2.0);+    assert_eq!(median_f32(&[1.0, 2.0, 3.0, 4.0]), 2.5);+    assert_eq!(median_f32(&[]), 0.0);+    assert_eq!(median_f32(&[0.0, -1.0, f32::NAN, 8.0]), 8.0);+}++#[test]+fn resize_gain_same_size_is_identity() {+    let src: Vec<f32> = (0..16).map(|i| 1.0 + i as f32 * 0.1).collect();+    let out = resize_gain(&src, 4, 4, 4, 4);+    for (a, b) in out.iter().zip(src.iter()) {+        assert!((a - b).abs() < 1e-3, "same-size resize must be identity: {a} vs {b}");+    }+}++#[test]+fn resize_gain_constant_map_stays_constant_at_any_size() {+    let out = resize_gain(&[2.5f32; 4], 2, 2, 7, 5);+    assert_eq!(out.len(), 35);+    assert!(out.iter().all(|v| (v - 2.5).abs() < 1e-6));+}++#[test]+fn resize_gain_degenerate_source_is_unity() {+    let out = resize_gain(&[], 0, 0, 3, 2);+    assert_eq!(out, vec![1.0f32; 6]);+}++#[test]+fn resize_gain_upscale_interpolates_monotonically() {+    // 2x1 ramp 0 -> 2 stretched to 5x1 must be non-decreasing and hit ends.+    let out = resize_gain(&[0.0f32, 2.0], 2, 1, 5, 1);+    assert!(out.windows(2).all(|w| w[1] >= w[0] - 1e-6), "monotone: {out:?}");+    assert!((out[0] - 0.0).abs() < 0.5 && (out[4] - 2.0).abs() < 0.5);+}++fn opaque_tile(w: usize, h: usize, cx: i32, cy: i32) -> WarpedTile {+    let mut img = Rgba::new(w, h);+    for y in 0..h {+        for x in 0..w {+            img.set(x, y, [1, 2, 3, 255]);+        }+    }+    WarpedTile { img, corner_x: cx, corner_y: cy }+}++#[test]+fn build_compose_masks_partitions_coverage_exactly_once() {+    let tiles = vec![opaque_tile(10, 10, 0, 0), opaque_tile(10, 10, 5, 0)];+    let low: Vec<Vec<u8>> = tiles.iter().map(|t| vec![1u8; t.img.w * t.img.h]).collect();+    let masks = build_compose_masks(&tiles, &tiles, &low);+    // Every covered global pixel (15x10 union) owned by exactly one mask.+    let mut owned = 0usize;+    for (m, t) in masks.iter().zip(tiles.iter()) {+        assert_eq!(m.len(), t.img.w * t.img.h);+        owned += m.iter().filter(|&&v| v != 0).count();+    }+    assert_eq!(owned, 15 * 10, "union coverage assigned exactly once");+}++#[test]+fn build_compose_masks_disjoint_tiles_each_own_their_area() {+    let tiles = vec![opaque_tile(4, 4, 0, 0), opaque_tile(4, 4, 20, 20)];+    let low: Vec<Vec<u8>> = tiles.iter().map(|t| vec![1u8; t.img.w * t.img.h]).collect();+    let masks = build_compose_masks(&tiles, &tiles, &low);+    assert!(masks.iter().all(|m| m.iter().all(|&v| v == 1)));+}++#[test]+fn build_compose_masks_empty_input_gives_empty_masks() {+    assert!(build_compose_masks(&[], &[], &[]).is_empty());+}++#[test]+fn stitch_panorama_degenerate_inputs_return_none_or_single_frame() {+    assert!(stitch_panorama(&[], &[], &[]).is_none());+    assert!(stitch_panorama(&[vec![1, 2, 3]], &[0.0], &[0.0]).is_none(), "bad JPEG");+    assert!(estimate_pano(&[vec![1, 2, 3]], &[0.0], &[0.0]).is_none(), "needs >= 2 frames");+    assert!(estimate_pano(&[], &[], &[]).is_none());+}
camera/src/main/rust/src/wave.rs
diff --git a/camera/src/main/rust/src/wave.rs b/camera/src/main/rust/src/wave.rsindex 0e6884eeac..c46f187c32 100644--- a/camera/src/main/rust/src/wave.rs+++ b/camera/src/main/rust/src/wave.rs@@ -55,3 +55,7 @@ pub fn wave_correct_horizontal(cams: &mut [CameraParams]) {         c.r = r_wave * c.r;     } }++#[cfg(test)]+#[path = "wave_tests.rs"]+mod wave_tests;
camera/src/main/rust/src/wave_tests.rs
diff --git a/camera/src/main/rust/src/wave_tests.rs b/camera/src/main/rust/src/wave_tests.rsnew file mode 100644index 0000000000..85855c6c00--- /dev/null+++ b/camera/src/main/rust/src/wave_tests.rs@@ -0,0 +1,86 @@+//! Tests for wave.rs: wave correction must keep rotations valid and leave+//! already-level camera sets (nearly) unchanged.+fn mdiff(a: &Matrix3<f64>, b: &Matrix3<f64>) -> f64 {+    let mut s = 0.0f64;+    for r in 0..3 { for c in 0..3 { let d = a[(r, c)] - b[(r, c)]; s += d * d; } }+    s.sqrt()+}+++use super::*;+use crate::camera::rodrigues_to_mat;+use crate::linalg::Vector3;++fn approx(a: f64, b: f64, tol: f64) -> bool {+    (a - b).abs() <= tol+}++fn cam(r: Matrix3<f64>) -> CameraParams {+    CameraParams { focal: 800.0, aspect: 1.0, ppx: 320.0, ppy: 240.0, r }+}++fn assert_rotation(r: &Matrix3<f64>) {+    assert!(approx(r.determinant(), 1.0, 1e-9), "det {}", r.determinant());+    let p = *r * r.transpose();+    for i in 0..3 {+        for j in 0..3 {+            let want = if i == j { 1.0 } else { 0.0 };+            assert!(approx(p[(i, j)], want, 1e-9), "orthonormal [{i}{j}]");+        }+    }+}++#[test]+fn wave_correct_empty_and_single_are_noops() {+    let mut none: Vec<CameraParams> = Vec::new();+    wave_correct_horizontal(&mut none);+    assert!(none.is_empty());+    let r = rodrigues_to_mat(Vector3::new(0.1, 0.2, 0.3));+    let mut one = vec![cam(r)];+    wave_correct_horizontal(&mut one);+    assert!(approx(mdiff(&(one[0].r), &(r)), 0.0, 1e-12));+}++#[test]+fn wave_correct_identity_cameras_stay_rotations() {+    let mut cams = vec![cam(Matrix3::identity()), cam(Matrix3::identity()), cam(Matrix3::identity())];+    wave_correct_horizontal(&mut cams);+    for c in &cams {+        assert_rotation(&c.r);+        assert!(approx(c.focal, 800.0, 1e-12), "focal untouched");+        assert!(approx(c.ppx, 320.0, 1e-12) && approx(c.ppy, 240.0, 1e-12));+    }+}++#[test]+fn wave_correct_applies_one_common_rotation_to_all() {+    // The correction left-multiplies every camera by the same R_wave, so+    // relative rotations between cameras are preserved exactly.+    let rs: Vec<Matrix3<f64>> = (0..4)+        .map(|i| rodrigues_to_mat(Vector3::new(0.0, 0.08 * i as f64, 0.01 * i as f64)))+        .collect();+    let rel_before: Vec<Matrix3<f64>> = rs.windows(2).map(|w| w[0].transpose() * w[1]).collect();+    let mut cams: Vec<CameraParams> = rs.iter().map(|&r| cam(r)).collect();+    wave_correct_horizontal(&mut cams);+    for c in &cams {+        assert_rotation(&c.r);+    }+    for (i, rel) in rel_before.iter().enumerate() {+        let after = cams[i].r.transpose() * cams[i + 1].r;+        assert!(approx(mdiff(&(after), &(rel)), 0.0, 1e-9), "relative rotation {i} changed");+    }+}++#[test]+fn wave_correct_is_idempotent_up_to_tolerance() {+    let mut cams: Vec<CameraParams> = (0..3)+        .map(|i| cam(rodrigues_to_mat(Vector3::new(0.02 * i as f64, 0.15 * i as f64, 0.0))))+        .collect();+    wave_correct_horizontal(&mut cams);+    let once: Vec<Matrix3<f64>> = cams.iter().map(|c| c.r).collect();+    wave_correct_horizontal(&mut cams);+    for (c, before) in cams.iter().zip(once.iter()) {+        assert!(mdiff(&(c.r), &(before)) < 1e-6, "second pass moved cameras");+        assert_rotation(&c.r);+    }+}
camera/src/main/rust/tests/pure_logic.rs
diff --git a/camera/src/main/rust/tests/pure_logic.rs b/camera/src/main/rust/tests/pure_logic.rsnew file mode 100644index 0000000000..776e94f81c--- /dev/null+++ b/camera/src/main/rust/tests/pure_logic.rs@@ -0,0 +1,299 @@+//! Synthetic-input tests for the crate's pure, deterministic logic.+//!+//! Everything here builds tiny in-memory images / matrices — no JPEG fixtures —+//! and exercises the public surface that `src/lib.rs` re-exports or declares.++use camera_stitch::camera::{rodrigues_to_mat, CameraParams};+use camera_stitch::features::{Features, KeyPoint};+use camera_stitch::imgbuf::Rgba;+use camera_stitch::linalg::{Matrix3, Vector3};++// The stitch pipeline modules are crate-private, so integration tests reach+// the pure helpers through the crate root's internal paths only where they+// are `pub`. That means most pipeline coverage lives in sibling+// `#[cfg(test)]` modules next to the code; this file covers what the crate+// publicly exposes: `camera`, `imgbuf`, `linalg`, `geometry`, `features`.++fn approx(a: f64, b: f64, tol: f64) -> bool {+    (a - b).abs() <= tol+}++fn solid(w: usize, h: usize, c: [u8; 4]) -> Rgba {+    let mut img = Rgba::new(w, h);+    for y in 0..h {+        for x in 0..w {+            img.set(x, y, c);+        }+    }+    img+}++// ---------------------------------------------------------------- camera ---++#[test]+fn camera_k_uses_focal_times_aspect_for_y() {+    let p = CameraParams {+        focal: 600.0,+        aspect: 0.5,+        ppx: 10.0,+        ppy: 20.0,+        r: Matrix3::identity(),+    };+    let k = p.k();+    assert!(approx(k[(0, 0)], 600.0, 1e-12));+    assert!(approx(k[(1, 1)], 300.0, 1e-12), "fy = focal*aspect");+    assert!(approx(k[(0, 2)], 10.0, 1e-12));+    assert!(approx(k[(1, 2)], 20.0, 1e-12));+}++#[test]+fn rodrigues_quarter_turn_about_z_maps_x_to_y() {+    let r = rodrigues_to_mat(Vector3::new(0.0, 0.0, std::f64::consts::FRAC_PI_2));+    let v = r * Vector3::new(1.0, 0.0, 0.0);+    assert!(approx(v.x, 0.0, 1e-12), "x {}", v.x);+    assert!(approx(v.y, 1.0, 1e-12), "y {}", v.y);+    assert!(approx(v.z, 0.0, 1e-12));+    // A rotation matrix is orthonormal with determinant +1.+    assert!(approx(r.determinant(), 1.0, 1e-12));+    let should_be_i = r * r.transpose();+    for i in 0..3 {+        for j in 0..3 {+            let want = if i == j { 1.0 } else { 0.0 };+            assert!(approx(should_be_i[(i, j)], want, 1e-12), "[{i}{j}]");+        }+    }+}++#[test]+fn rodrigues_large_angle_round_trips_through_matrix() {+    // 180° about X: mat_to_rodrigues takes the trace<=0 branch.+    let rvec = Vector3::new(std::f64::consts::PI, 0.0, 0.0);+    let m = rodrigues_to_mat(rvec);+    assert!(approx(m[(1, 1)], -1.0, 1e-12));+    assert!(approx(m[(2, 2)], -1.0, 1e-12));+    let back = camera_stitch::camera::mat_to_rodrigues(&m);+    assert!(approx(back.norm(), std::f64::consts::PI, 1e-9), "norm {}", back.norm());+}++// ---------------------------------------------------------------- imgbuf ---++#[test]+fn rgba_from_bytes_with_exact_size_round_trips() {+    // from_bytes requires exactly w*h*4 bytes (enforced by debug_assert).+    let img = Rgba::from_bytes(2, 1, vec![1, 2, 3, 4, 5, 6, 7, 8]);+    assert_eq!(img.get(0, 0), [1, 2, 3, 4]);+    assert_eq!(img.get(1, 0), [5, 6, 7, 8]);+    let zero = Rgba::from_bytes(0, 0, vec![]);+    assert_eq!((zero.w, zero.h, zero.px.len()), (0, 0, 0));+}++#[test]+fn rgba_get_reads_written_pixels() {+    let img = solid(2, 2, [7, 8, 9, 255]);+    assert_eq!(img.get(0, 0), [7, 8, 9, 255]);+    assert_eq!(img.get(1, 1), [7, 8, 9, 255]);+}++#[test]+#[should_panic]+fn rgba_get_out_of_bounds_panics() {+    // Documented current behaviour: get() indexes unchecked, so callers+    // must guard coordinates (all in-crate callers do).+    let img = solid(2, 2, [7, 8, 9, 255]);+    let _ = img.get(5, 0);+}++#[test]+fn rgba_sample_bilinear_midpoint_averages_neighbours() {+    let mut img = Rgba::new(2, 1);+    img.set(0, 0, [0, 0, 0, 255]);+    img.set(1, 0, [100, 200, 40, 255]);+    let mid = img.sample(0.5, 0.0).expect("opaque sample");+    assert!((mid[0] - 50.0).abs() < 1e-4, "r {}", mid[0]);+    assert!((mid[1] - 100.0).abs() < 1e-4, "g {}", mid[1]);+    assert!((mid[2] - 20.0).abs() < 1e-4, "b {}", mid[2]);+    // Exact pixel centre returns that pixel.+    let c = img.sample(1.0, 0.0).expect("centre");+    assert!((c[0] - 100.0).abs() < 1e-4);+}++#[test]+fn rgba_sample_transparency_rules() {+    let mut img = Rgba::new(3, 3);+    img.set(1, 1, [255, 255, 255, 255]);+    assert!(img.sample(1.0, 1.0).is_some());+    // At the corner the bilinear neighbourhood *includes* the opaque centre+    // as one corner, so sample returns Some even though the weighted value+    // there is fully transparent black.+    let corner = img.sample(0.0, 0.0).expect("neighbourhood has one opaque corner");+    assert_eq!(corner, [0.0, 0.0, 0.0, 0.0]);+    // A fully transparent image samples to None everywhere in bounds.+    let clear = Rgba::new(3, 3);+    assert!(clear.sample(1.0, 1.0).is_none());+    assert!(clear.sample(0.0, 0.0).is_none());+}++#[test]+fn rgba_resized_to_same_size_is_identity_and_downscale_averages() {+    let img = solid(4, 4, [80, 40, 20, 255]);+    let same = img.resized(4, 4);+    assert_eq!(same.px, img.px);+    let small = img.resized(2, 2);+    assert!(small.px.chunks_exact(4).all(|p| p == [80, 40, 20, 255]));+    let one = img.resized(1, 1);+    assert_eq!(one.get(0, 0), [80, 40, 20, 255]);+}++#[test]+fn to_gray_uses_integer_luma_weights() {+    let mut img = Rgba::new(3, 1);+    img.set(0, 0, [255, 255, 255, 255]);+    img.set(1, 0, [255, 0, 0, 255]);+    img.set(2, 0, [0, 0, 255, 255]);+    let g = camera_stitch::imgbuf::to_gray(&img);+    assert_eq!(g.px[0], 255);+    assert_eq!(g.px[1], ((255u32 * 77) >> 8) as u8);+    assert_eq!(g.px[2], ((255u32 * 29) >> 8) as u8);+}++#[test]+fn gray_resize_and_blur_keep_constant_images_constant() {+    let mut g = camera_stitch::imgbuf::Gray::new(6, 6);+    for v in g.px.iter_mut() {+        *v = 90;+    }+    let blurred = g.gaussian_blur_3x3();+    assert!(blurred.px.iter().all(|&v| v == 90));+    let small = g.resized(3, 3);+    assert_eq!((small.w, small.h), (3, 3));+    assert!(small.px.iter().all(|&v| v == 90));+}++#[test]+#[should_panic]+fn gray_at_out_of_bounds_panics() {+    // Like Rgba::get, Gray::at indexes unchecked.+    let g = camera_stitch::imgbuf::Gray::new(4, 4);+    let _ = g.at(100, 100);+}++// -------------------------------------------------------------- features ---++fn feats_with_desc(descs: Vec<[u8; 32]>) -> Features {+    let n = descs.len();+    Features {+        kps: (0..n)+            .map(|i| KeyPoint { x: i as f32 * 10.0, y: 5.0, angle: 0.0, score: 1.0 })+            .collect(),+        desc: descs,+        w: 100,+        h: 50,+    }+}++#[test]+fn match_features_empty_inputs_match_nothing() {+    let empty = feats_with_desc(vec![]);+    let one = feats_with_desc(vec![[0u8; 32]]);+    assert!(camera_stitch::features::match_features(&empty, &one, 0.8).is_empty());+    assert!(camera_stitch::features::match_features(&one, &empty, 0.8).is_empty());+}++#[test]+fn match_features_identical_descriptor_wins_over_distant_ones() {+    let target = [0xAAu8; 32];+    let mut far = [0u8; 32];+    far[0] = 0xFF; // some bits differ from both+    let a = feats_with_desc(vec![target]);+    // best = identical (dist 0), second = far (dist > 0): ratio test passes.+    let b = feats_with_desc(vec![far, target, [0x55u8; 32]]);+    let m = camera_stitch::features::match_features(&a, &b, 0.8);+    assert_eq!(m, vec![(0, 1)]);+}++#[test]+fn match_features_ratio_rejects_ambiguous_equidistant_candidates() {+    // Two identical candidates: best == second, so best < ratio*second fails.+    let d = [3u8; 32];+    let a = feats_with_desc(vec![d]);+    let b = feats_with_desc(vec![d, d]);+    assert!(camera_stitch::features::match_features(&a, &b, 0.8).is_empty());+}++#[test]+fn detect_and_describe_on_blank_and_tiny_images_is_empty_but_safe() {+    let blank = camera_stitch::imgbuf::Gray::new(64, 64);+    let f = camera_stitch::features::detect_and_describe(&blank, 100, 20);+    assert!(f.kps.is_empty() && f.desc.is_empty());+    assert_eq!((f.w, f.h), (64, 64));+    let tiny = camera_stitch::imgbuf::Gray::new(2, 2);+    let f2 = camera_stitch::features::detect_and_describe(&tiny, 100, 20);+    assert!(f2.kps.len() <= 100);+    assert_eq!(f2.kps.len(), f2.desc.len(), "one descriptor per keypoint");+}++// -------------------------------------------------------------- geometry ---++#[test]+fn transfer_inliers_with_identity_maps_points_to_themselves() {+    let pts: Vec<(f32, f32)> = vec![(0.0, 0.0), (10.0, 3.0), (-5.0, 7.0)];+    let inl = camera_stitch::geometry::transfer_inliers(&Matrix3::identity(), &pts, &pts, 1.0);+    assert_eq!(inl, vec![0, 1, 2]);+    // A destination 100px away is not an inlier of the identity.+    let far: Vec<(f32, f32)> = pts.iter().map(|(x, y)| (x + 100.0, *y)).collect();+    assert!(camera_stitch::geometry::transfer_inliers(&Matrix3::identity(), &pts, &far, 1.0).is_empty());+}++#[test]+fn homography_needs_at_least_four_points() {+    let a = vec![(0.0f32, 0.0f32), (1.0, 0.0), (0.0, 1.0)];+    assert!(camera_stitch::geometry::find_homography_ransac(&a, &a, 50, 1.0).is_none());+    assert!(camera_stitch::geometry::find_homography_ransac(&[], &[], 50, 1.0).is_none());+}++#[test]+fn homography_recovers_pure_scale_about_origin() {+    let a: Vec<(f32, f32)> = vec![+        (1.0, 1.0), (4.0, 1.0), (4.0, 4.0), (1.0, 4.0), (2.0, 3.0), (7.0, 2.0), (3.0, 8.0),+    ];+    let b: Vec<(f32, f32)> = a.iter().map(|(x, y)| (2.0 * x, 2.0 * y)).collect();+    let (h, inl) = camera_stitch::geometry::find_homography_ransac(&a, &b, 200, 1.0).expect("h");+    assert!(inl >= 4, "inliers {inl}");+    assert!(approx(h[(0, 0)], 2.0, 0.05), "h00 {}", h[(0, 0)]);+    assert!(approx(h[(1, 1)], 2.0, 0.05), "h11 {}", h[(1, 1)]);+    assert!(approx(h[(0, 2)], 0.0, 0.05), "h02 {}", h[(0, 2)]);+}++// ---------------------------------------------------------------- linalg ---++#[test]+fn matrix3_inverse_undoes_multiplication() {+    let m = Matrix3::new(2.0, 0.5, 1.0, 0.0, 3.0, 0.25, 1.0, 0.0, 2.0);+    let inv = m.try_inverse().expect("invertible");+    let prod = m * inv;+    for i in 0..3 {+        for j in 0..3 {+            let want = if i == j { 1.0 } else { 0.0 };+            assert!(approx(prod[(i, j)], want, 1e-9), "[{i}{j}] {}", prod[(i, j)]);+        }+    }+    assert!(approx(m.determinant() * inv.determinant(), 1.0, 1e-9));+}++#[test]+fn singular_matrix_has_no_inverse_and_zero_determinant() {+    let m = Matrix3::new(1.0, 2.0, 3.0, 2.0, 4.0, 6.0, 0.0, 1.0, 0.0); // row1 = 2*row0+    assert!(approx(m.determinant(), 0.0, 1e-12));+    assert!(m.try_inverse().is_none());+}++#[test]+fn vector3_cross_dot_and_norm_are_consistent() {+    let x = Vector3::new(1.0, 0.0, 0.0);+    let y = Vector3::new(0.0, 1.0, 0.0);+    let z = x.cross(&y);+    assert!(approx(z.z, 1.0, 1e-12) && approx(z.x, 0.0, 1e-12));+    assert!(approx(x.dot(&y), 0.0, 1e-12));+    assert!(approx(Vector3::new(3.0, 4.0, 0.0).norm(), 5.0, 1e-12));+    assert!(approx(x.cross(&y).norm(), 1.0, 1e-12), "unit axes give unit cross");+}