Modern Apps git

← Modern-Apps.git

avatar: add avatar Rust unit tests and ignore negative overlay styles

Commit
1eb81782de7dcc47ac69a9a1393d5cd33bf4462b
Author
Vayun Mathur <[email protected]>
When
2026-11-17 21:26 UTC (18 days ago)
Parents
ceb5a96
43 new tests (21 -> 64): pose/trait math and serde, skeleton consistency and skinning, atlas painting, procedural and glTF mesh contracts, engine config/frame, renderer helpers. Fix: negative mole/blush style indices (out of contract) were treated as set via != 0 checks in atlas and mesh; they now require > 0, and the mesh test asserts a negative style emits no decal. cargo test -p yuu_avatar green. Line coverage 53.9%.

Diff

library/avatar/src/main/rust/src/atlas.rs
diff --git a/library/avatar/src/main/rust/src/atlas.rs b/library/avatar/src/main/rust/src/atlas.rsindex 37c0638152..dad3f0f10a 100644--- a/library/avatar/src/main/rust/src/atlas.rs+++ b/library/avatar/src/main/rust/src/atlas.rs@@ -237,7 +237,7 @@ pub fn generate_atlas(traits: &YuuTraits) -> Vec<u8> {         }     }     // Overlays: mole / wrinkle / blush on spare brow-row cells (cols 8..11).-    if traits.mole_style != 0 {+    if traits.mole_style > 0 {         let col = 8 + (traits.mole_style.max(0) as usize % 4);         fill_ellipse(             &mut px,@@ -261,7 +261,7 @@ pub fn generate_atlas(traits: &YuuTraits) -> Vec<u8> {             );         }     }-    if traits.blush_style != 0 {+    if traits.blush_style > 0 {         let col = 8 + (traits.blush_style.max(0) as usize % 4);         let pink = [0xE8, 0x8A, 0x7A, 0xFF];         fill_ellipse(&mut px, FACE_X + col * cw + 4, FACE_Y + ch + ch / 2, 3, 2, pink);@@ -311,3 +311,96 @@ mod tests {         assert_ne!(a, b, "style indices must change atlas pixels");     } }++#[cfg(test)]+mod tests_extra {+    use super::*;++    #[test]+    fn face_cell_geometry_and_uv_clamping_and_wrapping() {+        assert_eq!(face_cell(), (21, 32), "256/12 cols, 128/4 rows (int division)");+        // Style wraps modulo 12; negative clamps to column 0; row clamps to 3.+        assert_eq!(face_cell_uv(0, 12), face_cell_uv(0, 0));+        assert_eq!(face_cell_uv(0, 13), face_cell_uv(0, 1));+        assert_eq!(face_cell_uv(0, -5), face_cell_uv(0, 0));+        assert_eq!(face_cell_uv(99, 0), face_cell_uv(3, 0));+        // Adjacent columns are adjacent, non-overlapping rects.+        let (a, b) = (face_cell_uv(2, 4), face_cell_uv(2, 5));+        assert!((a[2] - b[0]).abs() < 1e-6);+        assert_eq!((a[1], a[3]), (b[1], b[3]));+        // Every cell lies inside the face block (v 0.5..1.0).+        for row in 0..FACE_ROWS {+            for col in 0..FACE_COLS as i32 {+                let uv = face_cell_uv(row, col);+                assert!(uv[0] >= 0.0 && uv[2] <= 1.0 && uv[1] >= 0.5 && uv[3] <= 1.0, "{uv:?}");+                assert!(uv[2] > uv[0] && uv[3] > uv[1]);+            }+        }+    }++    #[test]+    fn overlay_cells_share_brow_row_spare_columns() {+        for style in 0..4 {+            let uv = overlay_cell_uv(style);+            assert_eq!(uv, face_cell_uv(1, 8 + style), "style {style}");+        }+        assert_eq!(overlay_cell_uv(4), overlay_cell_uv(0), "styles wrap mod 4");+        assert_eq!(overlay_cell_uv(-2), overlay_cell_uv(0), "negative clamps to first spare");+        assert_eq!(overlay_cell_uv(7), overlay_cell_uv(3));+    }++    #[test]+    fn argb_to_rgba_and_fill_helpers_clip() {+        assert_eq!(argb_to_rgba(0, [1, 2, 3]), [1, 2, 3, 0xFF]);+        assert_eq!(argb_to_rgba(0xFF11_2233, [1, 2, 3]), [0x11, 0x22, 0x33, 0xFF]);+        let mut px = vec![0u8; ATLAS_SIZE * ATLAS_SIZE * 4];+        // Rect spilling past the right/bottom edges must clip, not panic/wrap.+        fill_rect(&mut px, ATLAS_SIZE - 2, ATLAS_SIZE - 1, 10, 10, [9, 8, 7, 6]);+        let o = ((ATLAS_SIZE - 1) * ATLAS_SIZE + ATLAS_SIZE - 1) * 4;+        assert_eq!(&px[o..o + 4], &[9, 8, 7, 6]);+        assert_eq!(px.iter().filter(|b| **b == 9).count(), 2, "only clipped pixels painted");+        // Zero-radius ellipse still paints its centre (radii clamp to >=1).+        fill_ellipse(&mut px, 10, 10, 0, 0, [5, 5, 5, 5]);+        let o = (10 * ATLAS_SIZE + 10) * 4;+        assert_eq!(&px[o..o + 4], &[5, 5, 5, 5]);+        // Ellipse at the corner clips via saturating arithmetic.+        fill_ellipse(&mut px, 0, 0, 3, 3, [4, 4, 4, 4]);+        assert_eq!(&px[0..4], &[4, 4, 4, 4]);+    }++    #[test]+    fn atlas_is_deterministic_alpha_opaque_and_trait_coloured() {+        let t = YuuTraits { skin_tone: 0xFF20_4060, ..Default::default() };+        let (a, b) = (generate_atlas(&t), generate_atlas(&t));+        assert_eq!(a, b, "same traits must paint the same atlas");+        assert!(a.chunks_exact(4).all(|p| p[3] == 0xFF), "alpha must be opaque everywhere");+        // Unpainted corner keeps the unpacked skin colour.+        assert_eq!(&a[0..4], &[0x20, 0x40, 0x60, 0xFF]);+        // A different skin tone recolours the base.+        let other = generate_atlas(&YuuTraits { skin_tone: 0xFFAA_BBCC, ..Default::default() });+        assert_eq!(&other[0..4], &[0xAA, 0xBB, 0xCC, 0xFF]);+        assert_ne!(a, other);+    }++    #[test]+    fn only_selected_style_cells_are_painted() {+        let px = generate_atlas(&YuuTraits::default());+        let (cw, ch) = face_cell();+        let skin = &px[0..4];+        let cell_has_non_skin = |row: usize, col: usize| {+            (0..ch).any(|y| {+                (0..cw).any(|x| {+                    let o = ((FACE_Y + row * ch + y) * ATLAS_SIZE + FACE_X + col * cw + x) * 4;+                    &px[o..o + 4] != skin+                })+            })+        };+        assert!(cell_has_non_skin(0, 0), "selected eye cell painted");+        assert!(!cell_has_non_skin(0, 1), "unselected eye cell stays skin");+        assert!(!cell_has_non_skin(3, 5), "unselected mouth cell stays skin");+        // Overlay style selects exactly its spare cell in the brow row.+        let px = generate_atlas(&YuuTraits { mole_style: 2, ..Default::default() });+        let o = ((FACE_Y + ch + ch / 2) * ATLAS_SIZE + FACE_X + 10 * cw + cw / 2) * 4;+        assert_eq!(&px[o..o + 4], &[0x22, 0x1A, 0x14, 0xFF], "mole dot at spare col 10");+    }+}
library/avatar/src/main/rust/src/avatar.rs
diff --git a/library/avatar/src/main/rust/src/avatar.rs b/library/avatar/src/main/rust/src/avatar.rsindex 42575fcff8..7d5b4c0f10 100644--- a/library/avatar/src/main/rust/src/avatar.rs+++ b/library/avatar/src/main/rust/src/avatar.rs@@ -362,3 +362,132 @@ mod tests {     } } ++#[cfg(test)]+mod tests_extra {+    use super::*;+    use crate::pose::{preset_by_id, JointRotation, YuuPose};+    use crate::traits::YuuTraits;+    use std::collections::HashMap;++    fn idle() -> YuuPose {+        YuuPose { id: "idle".into(), name: "Idle".into(), joints: HashMap::new() }+    }++    #[test]+    fn name_roundtrip_and_discriminants_match_ubo_order() {+        for (i, joint) in ALL_JOINTS.iter().copied().enumerate() {+            assert_eq!(joint as usize, i, "UBO discriminant drifted for {joint:?}");+            assert_eq!(joint_by_name(joint_name(joint)), Some(joint));+        }+        assert_eq!(JOINT_COUNT, 13);+        assert_eq!(ALL_JOINTS.len(), JOINT_COUNT);+        assert!(MAX_BONES >= JOINT_COUNT);+        for bad in ["", "Head", "head ", "clavicle_l", "unknown"] {+            assert_eq!(joint_by_name(bad), None, "{bad:?}");+        }+    }++    #[test]+    fn parent_children_are_mutually_consistent() {+        let mut edges = 0;+        for joint in ALL_JOINTS {+            for child in children_of(joint) {+                assert_eq!(parent_of(*child), Some(joint), "{child:?}");+                edges += 1;+            }+            if let Some(parent) = parent_of(joint) {+                assert!(children_of(parent).contains(&joint), "{joint:?}");+            }+        }+        assert_eq!(edges, JOINT_COUNT - 1, "skeleton must be a single tree");+        assert_eq!(parent_of(Joint::Root), None);+        assert!(children_of(Joint::Head).is_empty());+        assert!(children_of(Joint::HandL).is_empty() && children_of(Joint::HandR).is_empty());+        assert_eq!(children_of(Joint::Chest), &[Joint::Neck, Joint::ClavicleL, Joint::ClavicleR]);+    }++    #[test]+    fn rest_offsets_are_mirror_symmetric_and_form_chains() {+        assert_eq!(rest_offset(Joint::Root), Vec3::ZERO);+        for (l, r) in [+            (Joint::ClavicleL, Joint::ClavicleR),+            (Joint::UpperArmL, Joint::UpperArmR),+            (Joint::ForearmL, Joint::ForearmR),+            (Joint::HandL, Joint::HandR),+        ] {+            let (a, b) = (rest_offset(l), rest_offset(r));+            assert_eq!(a.x, -b.x, "{l:?}/{r:?} x must mirror");+            assert_eq!((a.y, a.z), (b.y, b.z));+        }+        // Head chain accumulates upward; arms hang downward from the clavicles.+        let torso_y: f32 = [Joint::Spine, Joint::Chest, Joint::Neck, Joint::Head]+            .iter().map(|j| rest_offset(*j).y).sum();+        assert!((torso_y - 1.19).abs() < 1e-6, "head joint rest height {torso_y}");+        assert!(rest_offset(Joint::ForearmL).y < 0.0 && rest_offset(Joint::HandR).y < 0.0);+    }++    #[test]+    fn bones_beyond_joint_count_are_identity_and_all_finite() {+        for pose_id in ["idle", "wave", "thumbs_up", "thinking", "cheering"] {+            let pose = preset_by_id(pose_id).expect("preset");+            let bones = compute_bone_matrices(&YuuTraits::default(), &pose, 0.37);+            for (i, m) in bones.iter().enumerate() {+                assert!(m.to_cols_array().iter().all(|v| v.is_finite()), "{pose_id} bone {i}");+                if i >= JOINT_COUNT {+                    assert_eq!(*m, Mat4::IDENTITY, "padding bone {i} must stay identity");+                }+            }+        }+    }++    #[test]+    fn compute_is_deterministic_and_unknown_pose_joints_are_ignored() {+        let mut pose = idle();+        pose.joints.insert("not_a_joint".into(), JointRotation { x: 45.0, y: 0.0, z: 0.0 });+        pose.joints.insert("head".into(), JointRotation { x: 0.0, y: 30.0, z: 0.0 });+        let a = compute_bone_matrices(&YuuTraits::default(), &pose, 0.0);+        let b = compute_bone_matrices(&YuuTraits::default(), &pose, 0.0);+        assert_eq!(a, b);+        // Head rotation actually moves the head bone vs idle.+        let plain = compute_bone_matrices(&YuuTraits::default(), &idle(), 0.0);+        assert_ne!(a[Joint::Head as usize], plain[Joint::Head as usize]);+    }++    #[test]+    fn taller_traits_raise_and_heavier_traits_widen_skinning() {+        let short = YuuTraits { body_height: 0.0, ..Default::default() };+        let tall = YuuTraits { body_height: 1.0, ..Default::default() };+        let head_pt = Vec3::new(0.0, 1.28, 0.0);+        let y = |t: &YuuTraits| {+            compute_bone_matrices(t, &idle(), 0.0)[Joint::Head as usize].transform_point3(head_pt).y+        };+        assert!(y(&tall) > y(&short) + 0.05, "tall {} vs short {}", y(&tall), y(&short));+        let lean = YuuTraits { body_weight: 0.0, ..Default::default() };+        let heavy = YuuTraits { body_weight: 1.0, ..Default::default() };+        let hand_pt = Vec3::new(0.31, 0.34, 0.0);+        let x = |t: &YuuTraits| {+            compute_bone_matrices(t, &idle(), 0.0)[Joint::HandR as usize]+                .transform_point3(hand_pt).x.abs()+        };+        assert!(x(&heavy) > x(&lean), "heavy {} vs lean {}", x(&heavy), x(&lean));+    }++    #[test]+    fn head_scale_applies_and_idle_sway_is_small_and_periodic_in_effect() {+        let wide = YuuTraits { face_shape: 7, ..Default::default() };+        let bones = compute_bone_matrices(&wide, &idle(), 0.0);+        let p = bones[Joint::Head as usize].transform_point3(Vec3::new(0.1, 1.28, 0.0));+        // Head-local +x point is scaled by head_scale().x = 1.12 about the head origin.+        assert!(p.x > 0.1, "scaled head point {p:?}");+        // Sway at t=0 is zero; a quarter period later the root bone has rotated+        // but a point on the rotation axis (origin) stays put.+        let t_quarter = std::f32::consts::FRAC_PI_2 / 1.2;+        let swayed = compute_bone_matrices(&YuuTraits::default(), &idle(), t_quarter);+        let origin = swayed[Joint::Root as usize].transform_point3(Vec3::ZERO);+        assert!(origin.length() < 1e-5);+        let off_axis = swayed[Joint::Root as usize].transform_point3(Vec3::new(1.0, 0.0, 0.0));+        assert!((off_axis - Vec3::new(1.0, 0.0, 0.0)).length() > 1e-4, "sway must rotate");+        assert!((off_axis - Vec3::new(1.0, 0.0, 0.0)).length() < 0.05, "sway must stay gentle");+    }+}
library/avatar/src/main/rust/src/engine_config.rs
diff --git a/library/avatar/src/main/rust/src/engine_config.rs b/library/avatar/src/main/rust/src/engine_config.rsindex 0255e67bed..50dc34ccca 100644--- a/library/avatar/src/main/rust/src/engine_config.rs+++ b/library/avatar/src/main/rust/src/engine_config.rs@@ -103,3 +103,93 @@ pub fn is_running(surface_id: i32) -> bool { pub fn log_backend(name: &str) {     android_log(name); }++#[cfg(test)]+mod tests_extra {+    use super::*;++    fn cleanup(id: i32) {+        if let Ok(mut eng) = engine().lock() {+            eng.surfaces.remove(&id);+            eng.orbit.remove(&id);+        }+    }++    #[test]+    fn set_config_parses_bare_quoted_and_json_pose_ids() {+        for (id, pose_json, want) in [+            (91_001, "wave", "wave"),+            (91_002, "\"cheering\"", "cheering"),+            (91_003, r#"{"id":"thinking"}"#, "thinking"),+        ] {+            cleanup(id);+            set_config(id, "{}", pose_json);+            let got = engine().lock().expect("engine").surfaces.get(&id).expect("surface").pose.id.clone();+            assert_eq!(got, want, "pose_json {pose_json}");+            cleanup(id);+        }+        // Empty / unknown pose keeps the previous (idle) pose but still sets traits.+        cleanup(91_004);+        set_config(91_004, r#"{"bodyHeight":0.9}"#, "");+        {+            let eng = engine().lock().expect("engine");+            let s = eng.surfaces.get(&91_004).expect("surface");+            assert_eq!(s.pose.id, "idle");+            assert!((s.traits.body_height - 0.9).abs() < 1e-6);+            assert!(s.atlas_dirty && s.mesh_dirty, "trait set must dirty atlas+mesh");+        }+        set_config(91_004, "{}", "bogus_pose");+        let got = engine().lock().expect("engine").surfaces.get(&91_004).expect("surface").pose.id.clone();+        assert_eq!(got, "idle", "unknown pose must keep the old pose");+        cleanup(91_004);+    }++    #[test]+    fn rotate_input_clamps_pitch_accumulates_yaw_and_persists_prefs() {+        let id = 91_010;+        cleanup(id);+        on_rotate_input(id, 0.5, 10.0);+        on_rotate_input(id, 0.25, 10.0);+        {+            let eng = engine().lock().expect("engine");+            let prefs = eng.orbit.get(&id).expect("prefs persist without a surface");+            assert!((prefs.yaw - 0.75).abs() < 1e-6);+            assert!((prefs.pitch - MAX_PITCH).abs() < 1e-6, "pitch clamps at +MAX_PITCH");+            assert!(!eng.surfaces.contains_key(&id), "rotate input alone must not be read as surface state here");+        }+        on_rotate_input(id, 0.0, -100.0);+        let pitch = engine().lock().expect("engine").orbit.get(&id).expect("prefs").pitch;+        assert!((pitch + MAX_PITCH).abs() < 1e-6, "pitch clamps at -MAX_PITCH");+        // Prefs survive surface removal (rotation keeps drag position).+        set_config(id, "{}", "idle");+        remove_surface(id);+        let prefs = engine().lock().expect("engine").orbit.get(&id).copied();+        assert!(prefs.is_some(), "orbit prefs must survive remove_surface");+        cleanup(id);+    }++    #[test]+    fn paused_auto_rotate_and_generation_state_transitions() {+        let id = 91_020;+        cleanup(id);+        // set_paused on an unknown surface is a no-op and creates nothing.+        set_paused(id, true);+        assert!(engine().lock().expect("engine").surfaces.get(&id).is_none());+        // set_auto_rotate records prefs without creating a phantom surface.+        set_auto_rotate(id, false);+        {+            let eng = engine().lock().expect("engine");+            assert!(!eng.surfaces.contains_key(&id));+            assert!(!eng.orbit.get(&id).expect("prefs").auto_rotate);+        }+        assert!(!has_renderer(id) && !is_running(id));+        assert_eq!(generation(id), 0, "unknown surface generation is 0");+        let g1 = next_generation(id);+        let g2 = next_generation(id);+        assert_eq!(g2, g1 + 1);+        assert_eq!(generation(id), g2);+        // Creating state via set_config keeps the auto-rotate opt-out in prefs.+        set_paused(id, false);+        cleanup(id);+    }+}
library/avatar/src/main/rust/src/engine_frame.rs
diff --git a/library/avatar/src/main/rust/src/engine_frame.rs b/library/avatar/src/main/rust/src/engine_frame.rsindex 92e92005b9..c064fe647d 100644--- a/library/avatar/src/main/rust/src/engine_frame.rs+++ b/library/avatar/src/main/rust/src/engine_frame.rs@@ -279,3 +279,51 @@ pub unsafe fn try_vulkan( ) -> Result<Renderer, String> {     Renderer::try_vulkan_only(window, width, height, state_width, state_height) }++#[cfg(test)]+mod frame_tests {+    use super::*;++    fn eye_of(yaw: f32, pitch: f32, auto: bool, t: f32) -> [f32; 3] {+        view_proj_for(512, 512, t, yaw, pitch, auto).1+    }++    #[test]+    fn camera_eye_orbits_at_fixed_radius() {+        let eye = eye_of(0.0, 0.0, false, 0.0);+        assert!((eye[0]).abs() < 1e-6 && (eye[2] - 3.4).abs() < 1e-6, "{eye:?}");+        assert!((eye[1] - 1.25).abs() < 1e-6);+        let eye = eye_of(std::f32::consts::FRAC_PI_2, 0.0, false, 0.0);+        assert!((eye[0] - 3.4).abs() < 1e-5 && eye[2].abs() < 1e-5, "{eye:?}");+        // Horizontal distance from the Y axis is always the framing radius.+        for yaw in [0.3f32, 1.7, -2.9, 12.0] {+            let e = eye_of(yaw, 0.0, false, 0.0);+            assert!(((e[0] * e[0] + e[2] * e[2]).sqrt() - 3.4).abs() < 1e-4, "{e:?}");+        }+        // Pitch raises/lowers the eye linearly; yaw is ignored while auto-rotating.+        assert!(eye_of(0.0, 0.6, false, 0.0)[1] > eye_of(0.0, 0.0, false, 0.0)[1]);+        assert!(eye_of(0.0, -0.6, false, 0.0)[1] < eye_of(0.0, 0.0, false, 0.0)[1]);+        assert_eq!(eye_of(99.0, 0.0, true, 0.0), eye_of(0.0, 0.0, false, 0.0));+        assert_ne!(eye_of(0.0, 0.0, true, 4.0), eye_of(0.0, 0.0, true, 0.0), "auto orbit advances with time");+    }++    #[test]+    fn view_proj_is_finite_and_centres_the_avatar() {+        for (w, h) in [(512u32, 512u32), (1280, 720), (320, 1280), (1, 1), (0, 0)] {+            let (vp, eye) = view_proj_for(w, h, 0.0, 0.0, 0.0, false);+            assert!(vp.iter().flatten().all(|v| v.is_finite()), "{w}x{h}");+            assert!(eye.iter().all(|v| v.is_finite()));+            // The look-at centre projects to NDC (0,0) with positive clip w.+            let m = Mat4::from_cols_array_2d(&vp);+            let clip = m * glam::Vec4::new(0.0, 0.9, 0.0, 1.0);+            assert!(clip.w > 0.0, "{w}x{h} clip {clip:?}");+            assert!(clip.x.abs() / clip.w < 1e-4 && clip.y.abs() / clip.w < 1e-4, "{w}x{h} ndc {clip:?}");+        }+        // Wider aspect changes the projection (and nothing else about the eye).+        let (wide, _) = view_proj_for(1280, 720, 0.0, 0.0, 0.0, false);+        let (square, _) = view_proj_for(720, 720, 0.0, 0.0, 0.0, false);+        assert_ne!(wide, square);+        // Deterministic for identical inputs.+        assert_eq!(view_proj_for(512, 512, 1.0, 0.2, 0.1, false), view_proj_for(512, 512, 1.0, 0.2, 0.1, false));+    }+}
library/avatar/src/main/rust/src/gles/buffers.rs
diff --git a/library/avatar/src/main/rust/src/gles/buffers.rs b/library/avatar/src/main/rust/src/gles/buffers.rsindex e5810138f5..1b54f725ce 100644--- a/library/avatar/src/main/rust/src/gles/buffers.rs+++ b/library/avatar/src/main/rust/src/gles/buffers.rs@@ -130,3 +130,24 @@ pub unsafe fn upload_avatar_mesh(     let n = mesh.len().min(AVATAR_VERT_CAP);     unsafe { buf.upload(gl, &mesh[..n]) }; }++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn vertex_layout_and_bytes_of_match_shader_contract() {+        // repr(C) layout: pos 12 + normal 12 + uv 8 + joints 16 + weights 16.+        assert_eq!(mem::size_of::<YuuVertex>(), 64);+        assert_eq!(mem::offset_of!(YuuVertex, pos), 0);+        assert_eq!(mem::offset_of!(YuuVertex, normal), 12);+        assert_eq!(mem::offset_of!(YuuVertex, uv), 24);+        assert_eq!(mem::offset_of!(YuuVertex, joints), 32);+        assert_eq!(mem::offset_of!(YuuVertex, weights), 48);+        assert!(bytes_of(&[]).is_empty());+        let mesh = vec![YuuVertex { pos: [1.0, 2.0, 3.0], ..Default::default() }; 3];+        let bytes = bytes_of(&mesh);+        assert_eq!(bytes.len(), 3 * 64);+        assert_eq!(&bytes[0..4], &1.0f32.to_le_bytes(), "first field is pos.x in place");+    }+}
library/avatar/src/main/rust/src/gles/renderer.rs
diff --git a/library/avatar/src/main/rust/src/gles/renderer.rs b/library/avatar/src/main/rust/src/gles/renderer.rsindex 80c4c38927..c507d571a7 100644--- a/library/avatar/src/main/rust/src/gles/renderer.rs+++ b/library/avatar/src/main/rust/src/gles/renderer.rs@@ -332,3 +332,37 @@ fn normalize(v: [f32; 3]) -> [f32; 3] {     let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt().max(1e-6);     [v[0] / len, v[1] / len, v[2] / len] }++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn flatten_preserves_column_major_order() {+        let m = [+            [1.0, 2.0, 3.0, 4.0],+            [5.0, 6.0, 7.0, 8.0],+            [9.0, 10.0, 11.0, 12.0],+            [13.0, 14.0, 15.0, 16.0],+        ];+        assert_eq!(flatten(&m), [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0]);+        // Identity stays identity under flatten (GL transpose=false path).+        let id = glam::Mat4::IDENTITY.to_cols_array_2d();+        let flat = flatten(&id);+        for i in 0..16 {+            assert_eq!(flat[i], if i % 5 == 0 { 1.0 } else { 0.0 }, "index {i}");+        }+    }++    #[test]+    fn normalize_and_fixed_lighting_constants() {+        assert_eq!(normalize([0.0, 0.0, 0.0]), [0.0, 0.0, 0.0], "zero vector guarded, not NaN");+        let n = normalize([3.0, 0.0, 4.0]);+        assert!((n[0] - 0.6).abs() < 1e-6 && (n[2] - 0.8).abs() < 1e-6);+        let sun = normalize(SUN_DIR);+        assert!((sun.iter().map(|v| v * v).sum::<f32>() - 1.0).abs() < 1e-5);+        assert!(SUN_DIR[1] < 0.0, "sun points downward onto the avatar");+        assert!(SKY.iter().all(|v| (0.0..=1.0).contains(v)));+        assert_eq!(AVATAR_VERT_CAP, 65_536);+    }+}
library/avatar/src/main/rust/src/mesh_gltf.rs
diff --git a/library/avatar/src/main/rust/src/mesh_gltf.rs b/library/avatar/src/main/rust/src/mesh_gltf.rsindex 902d02e1aa..bfe67c8e0b 100644--- a/library/avatar/src/main/rust/src/mesh_gltf.rs+++ b/library/avatar/src/main/rust/src/mesh_gltf.rs@@ -129,3 +129,43 @@ pub fn joint_count() -> usize { pub fn joint_names() -> Vec<&'static str> {     ALL_JOINTS.iter().copied().map(crate::avatar::joint_name).collect() }++#[cfg(test)]+mod tests_extra {+    use super::*;++    #[test]+    fn normalize_weights_handles_degenerate_and_scales() {+        assert_eq!(normalize_weights([0.0; 4]), [1.0, 0.0, 0.0, 0.0]);+        assert_eq!(normalize_weights([1e-9, 0.0, 0.0, 0.0]), [1.0, 0.0, 0.0, 0.0], "tiny sum is degenerate");+        assert_eq!(normalize_weights([2.0, 2.0, 0.0, 0.0]), [0.5, 0.5, 0.0, 0.0]);+        assert_eq!(normalize_weights([1.0, 1.0, 1.0, 1.0]), [0.25; 4]);+        let w = normalize_weights([0.1, 0.2, 0.3, 0.4]);+        assert!((w.iter().sum::<f32>() - 1.0).abs() < 1e-6);+        assert!((w[3] - 0.4).abs() < 1e-6, "already-normalized weights unchanged");+    }++    #[test]+    fn budget_and_joint_helpers_match_contract() {+        assert_eq!(mesh_budgets(), (65_536, 8_192));+        assert_eq!(joint_count(), JOINT_COUNT);+        let names = joint_names();+        assert_eq!(names.len(), JOINT_COUNT);+        assert_eq!(names[0], "root");+        assert_eq!(names[4], "head");+        assert_eq!(names[12], "hand_R");+        for (name, joint) in names.iter().zip(ALL_JOINTS.iter()) {+            assert_eq!(*name, crate::avatar::joint_name(*joint));+        }+    }++    #[test]+    fn corrupt_and_empty_gltf_fall_back_to_procedural_mesh() {+        let fallback = build_avatar_mesh(&crate::traits::YuuTraits::default());+        for bytes in [&[][..], b"not a glb", b"glTF....garbagegarbage"] {+            let mesh = load_gltf_mesh(bytes);+            assert_eq!(mesh.len(), fallback.len(), "bytes {bytes:?}");+            assert_eq!(mesh[0].pos, fallback[0].pos);+        }+    }+}
library/avatar/src/main/rust/src/mesh_procedural.rs
diff --git a/library/avatar/src/main/rust/src/mesh_procedural.rs b/library/avatar/src/main/rust/src/mesh_procedural.rsindex b0ea1dacf5..f22356ef53 100644--- a/library/avatar/src/main/rust/src/mesh_procedural.rs+++ b/library/avatar/src/main/rust/src/mesh_procedural.rs@@ -195,7 +195,7 @@ fn push_face_decals(out: &mut Vec<YuuVertex>, traits: &YuuTraits) {     let mouth_hw = 0.03 + traits.mouth_size.clamp(0.0, 1.0) * 0.04;     push_decal_quad(out, 0.0, mouth_cy, mouth_hw, 0.015, face_cell_uv(3, traits.mouth_style));     // Mole: one cheek quad, side + offset picked by style index.-    if traits.mole_style != 0 {+    if traits.mole_style > 0 {         let idx = traits.mole_style.max(0) as usize;         let side = if idx % 2 == 0 { -1.0 } else { 1.0 };         let mx = side * (0.055 + 0.01 * (idx % 4) as f32);@@ -207,7 +207,7 @@ fn push_face_decals(out: &mut Vec<YuuVertex>, traits: &YuuTraits) {         push_decal_quad(out, 0.0, 1.40, 0.06, 0.008, overlay_cell_uv(traits.wrinkle_style));     }     // Blush: one small quad per cheek.-    if traits.blush_style != 0 {+    if traits.blush_style > 0 {         let uv = overlay_cell_uv(traits.blush_style);         push_decal_quad(out, -0.07, 1.22, 0.015, 0.012, uv);         push_decal_quad(out, 0.07, 1.22, 0.015, 0.012, uv);@@ -254,3 +254,99 @@ pub fn build_avatar_mesh(traits: &YuuTraits) -> Vec<YuuVertex> {     push_face_decals(&mut out, traits);     out }++#[cfg(test)]+mod procedural_tests {+    use super::*;++    #[test]+    fn rounded_normal_face_corner_and_zero_cases() {+        // Face interior: offset is zero, dominant axis wins (sign preserved).+        assert_eq!(rounded_normal_from_offset([0.1, 0.02, 0.0], [0.1, 0.02, 0.0]), [1.0, 0.0, 0.0]);+        assert_eq!(rounded_normal_from_offset([0.0, -0.3, 0.1], [0.0, -0.3, 0.1]), [0.0, -1.0, 0.0]);+        assert_eq!(rounded_normal_from_offset([0.0; 3], [0.0; 3]), [1.0, 0.0, 0.0], "zero local defaults +X");+        // Corner: normalized offset from the clamped point.+        let n = rounded_normal_from_offset([1.0, 1.0, 0.0], [0.5, 0.5, 0.0]);+        let inv = std::f32::consts::FRAC_1_SQRT_2;+        assert!((n[0] - inv).abs() < 1e-6 && (n[1] - inv).abs() < 1e-6 && n[2] == 0.0, "{n:?}");+        assert!((n.iter().map(|v| v * v).sum::<f32>() - 1.0).abs() < 1e-6);+    }++    #[test]+    fn joint_index_helper_maps_names_and_defaults_to_root() {+        assert_eq!(j("head"), 4.0);+        assert_eq!(j("root"), 0.0);+        assert_eq!(j("hand_L"), 8.0);+        assert_eq!(j("nope"), 0.0);+        assert_eq!(j(""), 0.0);+    }++    #[test]+    fn single_box_part_vertex_contract() {+        let part = Part {+            center: [0.0, 1.0, 0.0], size: [0.2, 0.4, 0.2],+            joint: 4.0, blend_joint: 3.0, blend: 0.25, skin: true,+        };+        let mut out = Vec::new();+        box_skinned(&mut out, &part);+        assert_eq!(out.len(), 6 * ROUND_SUBDIV * ROUND_SUBDIV * 6);+        assert_eq!(out.len() % 3, 0);+        for v in &out {+            assert_eq!(v.joints, [4.0, 3.0, 0.0, 0.0]);+            assert_eq!(v.weights, [0.75, 0.25, 0.0, 0.0]);+            assert!((v.normal.iter().map(|n| n * n).sum::<f32>() - 1.0).abs() < 1e-4, "normal {:?}", v.normal);+            // Rounded box never escapes the sharp box bounds.+            assert!(v.pos[0].abs() <= 0.1 + 1e-5 && (v.pos[1] - 1.0).abs() <= 0.2 + 1e-5 && v.pos[2].abs() <= 0.1 + 1e-5, "{:?}", v.pos);+            // Skin parts sample the skin UV quadrant.+            assert!(v.uv[0] <= 0.25 + 1e-6 && v.uv[1] <= 0.25 + 1e-6, "{:?}", v.uv);+        }+        // Shirt twin samples the shirt half instead.+        let shirt = Part { skin: false, ..Part {+            center: [0.0; 3], size: [0.2; 3], joint: 0.0, blend_joint: 0.0, blend: 0.0, skin: false,+        } };+        let mut out = Vec::new();+        box_skinned(&mut out, &shirt);+        assert!(out.iter().all(|v| v.uv[0] >= 0.5 && v.uv[1] <= 0.5));+    }++    #[test]+    fn procedural_mesh_global_invariants_and_determinism() {+        let traits = YuuTraits::default();+        let (a, b) = (build_avatar_mesh(&traits), build_avatar_mesh(&traits));+        assert_eq!(a.len(), b.len());+        assert!(a.iter().zip(&b).all(|(x, y)| x.pos == y.pos && x.uv == y.uv), "build must be deterministic");+        assert_eq!(a.len() % 3, 0, "triangle soup");+        for v in &a {+            assert!(v.pos.iter().all(|p| p.is_finite()));+            assert!((v.weights.iter().sum::<f32>() - 1.0).abs() < 1e-4, "weights {:?}", v.weights);+            assert!(v.joints.iter().all(|j| (0.0..JOINT_COUNT as f32).contains(j)), "joints {:?}", v.joints);+            assert!(v.uv.iter().all(|u| (0.0..=1.0).contains(u)), "uv {:?}", v.uv);+            assert!((v.normal.iter().map(|n| n * n).sum::<f32>() - 1.0).abs() < 1e-3);+        }+        // Bounding box is a plausible upper body (metres).+        let (mut lo, mut hi) = ([f32::MAX; 3], [f32::MIN; 3]);+        for v in &a {+            for k in 0..3 { lo[k] = lo[k].min(v.pos[k]); hi[k] = hi[k].max(v.pos[k]); }+        }+        assert!(lo[1] > 0.2 && hi[1] < 1.6, "y range {lo:?}..{hi:?}");+        assert!(hi[0] < 0.5 && lo[0] > -0.5, "x range {lo:?}..{hi:?}");+    }++    #[test]+    fn trait_sliders_move_decals_without_changing_body_count() {+        let base = build_avatar_mesh(&YuuTraits::default());+        let moved = build_avatar_mesh(&YuuTraits {+            eye_height: 1.0, eye_size: 1.0, mouth_size: 1.0, ..Default::default()+        });+        assert_eq!(base.len(), moved.len(), "sliders move quads, never add/remove body verts");+        assert_ne!(+            base.iter().map(|v| v.pos).collect::<Vec<_>>(),+            moved.iter().map(|v| v.pos).collect::<Vec<_>>(),+            "slider extremes must move at least one decal vertex"+        );+        // Negative overlay styles are out of contract and treated as unset:+        // no mole quad is emitted, exactly like style 0.+        let neg = build_avatar_mesh(&YuuTraits { mole_style: -1, ..Default::default() });+        assert_eq!(neg.len(), base.len());+    }+}
library/avatar/src/main/rust/src/pose.rs
diff --git a/library/avatar/src/main/rust/src/pose.rs b/library/avatar/src/main/rust/src/pose.rsindex 9a061169ac..ea4fb70b8d 100644--- a/library/avatar/src/main/rust/src/pose.rs+++ b/library/avatar/src/main/rust/src/pose.rs@@ -114,3 +114,113 @@ pub fn preset_poses() -> Vec<YuuPose> { pub fn preset_by_id(id: &str) -> Option<YuuPose> {     preset_poses().into_iter().find(|p| p.id == id) }++#[cfg(test)]+mod tests {+    use super::*;+    use crate::avatar::joint_by_name;++    fn approx(a: f32, b: f32) -> bool { (a - b).abs() < 1e-5 }++    #[test]+    fn identity_rotation_is_identity_quat() {+        assert!(approx(JointRotation::identity().to_quat().length(), 1.0));+        let q = JointRotation::identity().to_quat();+        assert_eq!(q, Quat::IDENTITY);+        assert_eq!(JointRotation::default().to_quat(), Quat::IDENTITY);+    }++    #[test]+    fn axis_rotations_rotate_basis_vectors() {+        // 90 degrees about X sends +Y to +Z (XYZ Euler, glam RH).+        let v = JointRotation { x: 90.0, y: 0.0, z: 0.0 }.to_quat() * glam::Vec3::Y;+        assert!(v.distance(glam::Vec3::Z) < 1e-5, "{v:?}");+        let v = JointRotation { x: 0.0, y: 90.0, z: 0.0 }.to_quat() * glam::Vec3::Z;+        assert!(v.distance(glam::Vec3::X) < 1e-5, "{v:?}");+        let v = JointRotation { x: 0.0, y: 0.0, z: 90.0 }.to_quat() * glam::Vec3::X;+        assert!(v.distance(glam::Vec3::Y) < 1e-5, "{v:?}");+    }++    #[test]+    fn to_quat_is_unit_for_arbitrary_angles() {+        for r in [+            JointRotation { x: 33.0, y: -71.0, z: 129.0 },+            JointRotation { x: 360.0, y: 360.0, z: 360.0 },+            JointRotation { x: -180.0, y: 45.0, z: -45.0 },+        ] {+            assert!(approx(r.to_quat().length(), 1.0), "{r:?}");+            assert!(r.to_quat().to_array().iter().all(|v| v.is_finite()));+        }+        // A full turn is (numerically) identity.+        let q = JointRotation { x: 360.0, y: 0.0, z: 0.0 }.to_quat();+        assert!(q.to_array()[3].abs() > 0.999_9, "{q:?}");+    }++    #[test]+    fn joint_rotation_serde_defaults_and_roundtrip() {+        let r: JointRotation = serde_json::from_str("{}").expect("empty object");+        assert_eq!((r.x, r.y, r.z), (0.0, 0.0, 0.0));+        let r: JointRotation = serde_json::from_str(r#"{"x": 12.5}"#).expect("partial");+        assert_eq!((r.x, r.y, r.z), (12.5, 0.0, 0.0));+        let orig = JointRotation { x: 1.5, y: -2.5, z: 3.5 };+        let back: JointRotation =+            serde_json::from_str(&serde_json::to_string(&orig).expect("ser")).expect("de");+        assert_eq!((back.x, back.y, back.z), (orig.x, orig.y, orig.z));+    }++    #[test]+    fn pose_serde_defaults_joints_and_roundtrips() {+        let p: YuuPose =+            serde_json::from_str(r#"{"id":"x","name":"X"}"#).expect("pose without joints");+        assert!(p.joints.is_empty());+        let wave = preset_by_id(POSE_WAVE).expect("wave");+        let back: YuuPose =+            serde_json::from_str(&serde_json::to_string(&wave).expect("ser")).expect("de");+        assert_eq!(back.id, wave.id);+        assert_eq!(back.joints.len(), wave.joints.len());+        assert_eq!(back.joints["hand_R"].y, 25.0);+    }++    #[test]+    fn preset_gallery_shape_and_valid_joint_keys() {+        let poses = preset_poses();+        assert_eq!(poses.len(), 5);+        assert_eq!(+            poses.iter().map(|p| p.id.as_str()).collect::<Vec<_>>(),+            vec![POSE_IDLE, POSE_WAVE, POSE_THUMBS_UP, POSE_THINKING, POSE_CHEERING]+        );+        let mut ids = std::collections::HashSet::new();+        for p in &poses {+            assert!(ids.insert(p.id.clone()), "duplicate pose id {}", p.id);+            assert!(!p.name.is_empty());+            for (key, rot) in &p.joints {+                assert!(joint_by_name(key).is_some(), "pose {} bad key {key}", p.id);+                assert!(rot.x.is_finite() && rot.y.is_finite() && rot.z.is_finite());+            }+        }+        assert!(poses[0].joints.is_empty(), "idle must be the rest pose");+    }++    #[test]+    fn preset_contents_match_documented_gestures() {+        let wave = preset_by_id(POSE_WAVE).expect("wave");+        assert_eq!(wave.joints["upperArm_R"].z, -140.0);+        assert_eq!(wave.joints["hand_R"].y, 25.0);+        let cheer = preset_by_id(POSE_CHEERING).expect("cheering");+        assert_eq!(cheer.joints["upperArm_L"].z, 140.0);+        assert_eq!(cheer.joints["upperArm_R"].z, -140.0);+        let think = preset_by_id(POSE_THINKING).expect("thinking");+        assert_eq!(think.joints["forearm_R"].x, -95.0);+    }++    #[test]+    fn preset_by_id_misses_return_none() {+        assert!(preset_by_id("").is_none());+        assert!(preset_by_id("WAVE").is_none(), "ids are case-sensitive");+        assert!(preset_by_id("wave ").is_none());+        assert!(preset_by_id("unknown").is_none());+        for id in [POSE_IDLE, POSE_WAVE, POSE_THUMBS_UP, POSE_THINKING, POSE_CHEERING] {+            assert_eq!(preset_by_id(id).expect("known").id, id);+        }+    }+}
library/avatar/src/main/rust/src/traits.rs
diff --git a/library/avatar/src/main/rust/src/traits.rs b/library/avatar/src/main/rust/src/traits.rsindex 6d8a8a9ba5..70c349e29e 100644--- a/library/avatar/src/main/rust/src/traits.rs+++ b/library/avatar/src/main/rust/src/traits.rs@@ -200,3 +200,123 @@ fn argb_to_rgb(argb: u64, fallback: [f32; 3]) -> [f32; 3] {     let b = (argb & 0xFF) as f32 / 255.0;     [r, g, b] }++#[cfg(test)]+mod tests {+    use super::*;++    fn rgb_approx(a: [f32; 3], b: [f32; 3]) -> bool {+        a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-6)+    }++    #[test]+    fn default_traits_are_neutral() {+        let t = YuuTraits::default();+        assert_eq!(t.body_height, 0.5);+        assert_eq!(t.body_weight, 0.5);+        assert_eq!(t.face_shape, 0);+        assert_eq!(t.pose_id, None);+        assert!((t.height_scale() - 1.0).abs() < 1e-6);+        assert!((t.weight_scale() - 1.0).abs() < 1e-6);+        assert_eq!(t.head_scale(), Vec3::ONE);+    }++    #[test]+    fn height_and_weight_scales_hit_endpoints_and_clamp() {+        let mut t = YuuTraits::default();+        t.body_height = 0.0;+        assert!((t.height_scale() - 0.9).abs() < 1e-6);+        t.body_height = 1.0;+        assert!((t.height_scale() - 1.1).abs() < 1e-6);+        t.body_height = -3.0;+        assert!((t.height_scale() - 0.9).abs() < 1e-6, "under-range clamps low");+        t.body_height = 7.0;+        assert!((t.height_scale() - 1.1).abs() < 1e-6, "over-range clamps high");+        t.body_weight = 0.0;+        assert!((t.weight_scale() - 0.85).abs() < 1e-6);+        t.body_weight = 1.0;+        assert!((t.weight_scale() - 1.15).abs() < 1e-6);+        t.body_weight = 99.0;+        assert!((t.weight_scale() - 1.15).abs() < 1e-6);+        // Monotonic in the unclamped range.+        t.body_height = 0.25;+        let lo = t.height_scale();+        t.body_height = 0.75;+        assert!(t.height_scale() > lo);+    }++    #[test]+    fn head_scale_covers_all_shapes_and_wraps() {+        let expected = [+            Vec3::ONE,+            Vec3::new(0.95, 1.0, 0.95),+            Vec3::new(1.08, 0.96, 0.96),+            Vec3::new(1.05, 1.0, 1.0),+            Vec3::new(0.92, 1.08, 0.94),+            Vec3::new(1.1, 1.0, 1.0),+            Vec3::new(1.02, 0.98, 1.0),+            Vec3::new(1.12, 0.94, 1.0),+        ];+        for (shape, want) in expected.iter().enumerate() {+            let t = YuuTraits { face_shape: shape as i32, ..Default::default() };+            assert_eq!(t.head_scale(), *want, "shape {shape}");+            assert!(t.head_scale().to_array().iter().all(|v| *v > 0.0));+        }+        // rem_euclid wrap: 8 == 0, -1 == 7, -8 == 0.+        for (given, want) in [(8, 0usize), (15, 7), (-1, 7), (-8, 0), (-9, 7)] {+            let t = YuuTraits { face_shape: given, ..Default::default() };+            assert_eq!(t.head_scale(), expected[want], "face_shape {given}");+        }+    }++    #[test]+    fn argb_unpacking_ignores_alpha_and_zero_falls_back() {+        let mut t = YuuTraits::default();+        assert!(rgb_approx(t.skin_rgb(), [0.91, 0.71, 0.54]), "zero skin = fallback");+        assert!(rgb_approx(t.hair_rgb(), [0.17, 0.17, 0.17]), "zero hair = fallback");+        t.skin_tone = 0xFF11_2233;+        assert!(rgb_approx(t.skin_rgb(), [0x11 as f32 / 255.0, 0x22 as f32 / 255.0, 0x33 as f32 / 255.0]));+        t.skin_tone = 0x0011_2233;+        assert!(rgb_approx(t.skin_rgb(), [0x11 as f32 / 255.0, 0x22 as f32 / 255.0, 0x33 as f32 / 255.0]), "alpha byte ignored");+        t.hair_color = 0x0000_00FF;+        assert!(rgb_approx(t.hair_rgb(), [0.0, 0.0, 1.0]));+        t.hair_color = 1;+        assert!(rgb_approx(t.hair_rgb(), [0.0, 0.0, 1.0 / 255.0]), "only exactly 0 falls back");+        assert!(rgb_approx(argb_to_rgb(0xABCDEF, [9.0; 3]), [0xAB as f32 / 255.0, 0xCD as f32 / 255.0, 0xEF as f32 / 255.0]));+    }++    #[test]+    fn config_json_snake_case_unknown_and_bad_input() {+        let t = YuuTraits::from_config_json(r#"{"body_height":0.25,"face_shape":3}"#);+        assert_eq!(t.body_height, 0.25);+        assert_eq!(t.face_shape, 3);+        let t = YuuTraits::from_config_json(r#"{"nonsense":42,"bodyHeight":0.75}"#);+        assert_eq!(t.body_height, 0.75, "unknown keys ignored");+        for bad in ["", " ", "null", "[]", "42", "{", r#"{"bodyHeight":"tall"}"#] {+            let t = YuuTraits::from_config_json(bad);+            assert_eq!(t.body_height, 0.5, "bad input {bad:?} must default wholesale");+            assert_eq!(t.face_shape, 0);+        }+        // A present-but-null pose and explicit nulls on defaulted scalars.+        let t = YuuTraits::from_config_json(r#"{"poseId":null}"#);+        assert_eq!(t.pose_id, None);+    }++    #[test]+    fn traits_serde_roundtrip_preserves_all_fields() {+        let t = YuuTraits {+            face_shape: 6, skin_tone: 0xFFAA_BBCC, ear_size: 0.1, body_height: 0.2,+            body_weight: 0.9, hair_style: 11, hair_color: 7, eye_style: 5, eye_color: 8,+            eye_size: 0.3, glasses_style: 4, beard_style: 2, mole_style: 1,+            pose_id: Some("cheering".into()), ..Default::default()+        };+        let back: YuuTraits =+            serde_json::from_str(&serde_json::to_string(&t).expect("ser")).expect("de");+        assert_eq!(back.face_shape, 6);+        assert_eq!(back.skin_tone, 0xFFAA_BBCC);+        assert_eq!(back.hair_style, 11);+        assert_eq!(back.glasses_style, 4);+        assert_eq!(back.pose_id.as_deref(), Some("cheering"));+        assert!((back.body_weight - 0.9).abs() < 1e-6);+    }+}
library/avatar/src/main/rust/src/vulkan/renderer_frame.rs
diff --git a/library/avatar/src/main/rust/src/vulkan/renderer_frame.rs b/library/avatar/src/main/rust/src/vulkan/renderer_frame.rsindex 4a899ef6c2..e65dbcb29f 100644--- a/library/avatar/src/main/rust/src/vulkan/renderer_frame.rs+++ b/library/avatar/src/main/rust/src/vulkan/renderer_frame.rs@@ -192,3 +192,18 @@ fn normalize(v: [f32; 3]) -> [f32; 3] {     let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt().max(1e-6);     [v[0] / len, v[1] / len, v[2] / len] }++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn normalize_guards_zero_and_scales_to_unit() {+        assert_eq!(normalize([0.0; 3]), [0.0; 3]);+        let n = normalize([0.35, -1.0, 0.45]);+        assert!((n.iter().map(|v| v * v).sum::<f32>() - 1.0).abs() < 1e-5, "{n:?}");+        assert!(n[1] < 0.0, "sun direction keeps its downward sign");+        let tiny = normalize([1e-9, 0.0, 0.0]);+        assert!(tiny.iter().all(|v| v.is_finite()), "tiny vectors must not produce NaN: {tiny:?}");+    }+}