use super::*; #[cfg(not(target_arch = "wasm32"))] fn encoded_png( width: u32, height: u32, color: png::ColorType, depth: png::BitDepth, pixels: &[u8], palette: Option<&[u8]>, transparency: Option<&[u8]>, ) -> Vec { let mut bytes = Vec::new(); let mut encoder = png::Encoder::new(std::io::Cursor::new(&mut bytes), width, height); encoder.set_color(color); encoder.set_depth(depth); if let Some(palette) = palette { encoder.set_palette(palette); } if let Some(transparency) = transparency { encoder.set_trns(transparency); } let mut writer = encoder.write_header().unwrap(); writer.write_image_data(pixels).unwrap(); drop(writer); bytes } #[cfg(not(target_arch = "wasm32"))] #[test] fn glossmap_decode_uses_alpha_not_rgb() { let bytes = try_native_png_bytes(2, 1, &[255, 0, 0, 0, 0, 255, 0, 255]).unwrap(); let pixels = decode_glossmap_png(&bytes).unwrap(); assert_eq!(pixels.alpha, vec![0, 255]); assert_eq!(pixels.packed_rgb, vec![[0, 255, 0], [0, 0, 0]]); } #[test] fn texture_resource_selection_uses_canonical_root_and_path() { let path = polymodel_ldraw_core::NormalizedPath::new("textures/decal.png").unwrap(); let resource = |key: &str, resource_path: &str, root: &str, marker: u8| ModelResource { key: key.into(), path: resource_path.into(), root: root.into(), byte_length: 1, sha256: [marker; 32], mime_type: "image/png".into(), target_cids: Box::default(), bytes: Box::new([marker]), }; let resources = [ resource("other-mpd-texture", "textures/other.png", "mpd", 0), resource("official-texture", path.as_str(), "official-parts", 1), resource("mpd-texture", path.as_str(), "mpd", 2), ]; assert_eq!( texture_resource_for(&resources, polymodel_ldraw_core::RootId::CurrentMpd, &path) .unwrap() .key, "mpd-texture" ); assert_eq!( texture_resource_for( &resources, polymodel_ldraw_core::RootId::OfficialLibrary, &path, ) .unwrap() .key, "official-texture" ); let bare_path = polymodel_ldraw_core::NormalizedPath::new("decal.png").unwrap(); assert_eq!( texture_resource_for( &resources, polymodel_ldraw_core::RootId::CurrentMpd, &bare_path, ) .unwrap() .key, "mpd-texture" ); assert!( texture_resource_for( &resources, polymodel_ldraw_core::RootId::UploadedManifest, &path, ) .is_none() ); } #[test] fn texmap_planar_uvs_follow_basis_and_clip_to_texture() { let uvs = texmap_uvs( SceneTexmapProjectionMode::Planar, &[0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 4.0, 0.0], &[[0.0, 0.0, 0.0], [1.0, 2.0, 0.0], [3.0, -1.0, 0.0]], ) .unwrap(); assert_eq!(uvs, [[0.0, 0.0], [0.5, 0.5], [1.0, 0.0]]); } #[test] fn texmap_planar_solves_non_orthogonal_basis() { let uvs = texmap_uvs( SceneTexmapProjectionMode::Planar, &[0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 1.0, 2.0, 0.0], &[[0.0, 0.0, 0.0], [1.5, 1.0, 0.0]], ) .unwrap(); assert_eq!(uvs, [[0.0, 0.0], [0.5, 0.5]]); } #[test] fn texmap_planar_rejects_collinear_basis() { assert!( texmap_uvs( SceneTexmapProjectionMode::Planar, &[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 2.0, 0.0, 0.0], &[[0.5, 0.0, 0.0]], ) .is_err() ); } #[test] fn texmap_cylindrical_and_spherical_use_degree_extents() { let cylindrical = texmap_uvs( SceneTexmapProjectionMode::Cylindrical, &[0.0, 0.0, 0.0, 0.0, 0.0, 2.0, 1.0, 0.0, 0.0, 360.0], &[[1.0, 0.0, 0.0], [0.0, 1.0, 1.0]], ) .unwrap(); assert!((cylindrical[0][0] - 0.5).abs() < 1e-6); assert!((cylindrical[1][0] - 0.75).abs() < 1e-6); let spherical = texmap_uvs( SceneTexmapProjectionMode::Spherical, &[0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 360.0, 180.0], &[[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]], ) .unwrap(); assert!((spherical[0][0] - 0.75).abs() < 1e-6); assert!((spherical[1][1] - 0.5).abs() < 1e-6); } #[test] fn texmap_spherical_clamps_rounding_outside_unit_interval() { let parameters = [ 0.0, 0.0, 0.0, 1.0, 9.208261502450901e-9, -9.221431951215706e-9, 0.0, 1.0, 0.0, 360.0, 180.0, ]; let uvs = texmap_uvs( SceneTexmapProjectionMode::Spherical, ¶meters, &[[1.0, 5.4417490399506624e-9, -6.839130689711565e-9]], ) .expect("rounding at asin boundary should remain valid"); assert!(uvs.iter().flatten().all(|value| value.is_finite())); } #[cfg(not(target_arch = "wasm32"))] #[test] fn albedo_decode_expands_rgb_and_preserves_alpha() { let bytes = try_native_png_bytes(2, 1, &[255, 0, 0, 0, 255, 0, 128, 0]).unwrap(); let (width, height, pixels, translucent) = decode_albedo_png(&bytes).unwrap(); assert_eq!((width, height), (2, 1)); assert_eq!(pixels, vec![[255, 0, 0, 0], [255, 0, 128, 0]]); assert!(translucent); } #[cfg(not(target_arch = "wasm32"))] #[test] fn glossmap_decode_matrix_covers_png_channel_forms() { let rgb = encoded_png( 1, 1, png::ColorType::Rgb, png::BitDepth::Eight, &[1, 2, 3], None, None, ); let rgba8 = decode_glossmap_png(&rgb).unwrap(); assert_eq!(rgba8.alpha, vec![255]); assert_eq!(rgba8.packed_rgb, vec![[0, 0, 0]]); assert_eq!((rgba8.width, rgba8.height), (1, 1)); assert_eq!(rgba8.packed_rgb.len(), 1); let gray = encoded_png( 1, 1, png::ColorType::Grayscale, png::BitDepth::Eight, &[9], None, None, ); assert_eq!(decode_glossmap_png(&gray).unwrap().alpha, vec![255]); let indexed = encoded_png( 1, 1, png::ColorType::Indexed, png::BitDepth::Eight, &[0], Some(&[1, 2, 3]), None, ); assert_eq!(decode_glossmap_png(&indexed).unwrap().alpha, vec![255]); let indexed_trns = encoded_png( 1, 1, png::ColorType::Indexed, png::BitDepth::Eight, &[0], Some(&[1, 2, 3]), Some(&[77]), ); assert_eq!(decode_glossmap_png(&indexed_trns).unwrap().alpha, vec![77]); let ga = encoded_png( 1, 1, png::ColorType::GrayscaleAlpha, png::BitDepth::Eight, &[9, 64], None, None, ); assert_eq!(decode_glossmap_png(&ga).unwrap().alpha, vec![64]); let rgba16 = encoded_png( 1, 1, png::ColorType::Rgba, png::BitDepth::Sixteen, &[0, 1, 0, 2, 0, 3, 0, 4], None, None, ); let glossmap = decode_glossmap_png(&rgba16).unwrap(); assert_eq!(glossmap.alpha, vec![4]); assert_eq!(glossmap.packed_rgb, vec![[0, 255, 0]]); assert_eq!((glossmap.width, glossmap.height), (1, 1)); assert_eq!(glossmap.packed_rgb.len(), 1); let ga16 = encoded_png( 1, 1, png::ColorType::GrayscaleAlpha, png::BitDepth::Sixteen, &[0, 9, 0, 10], None, None, ); assert_eq!(decode_glossmap_png(&ga16).unwrap().alpha, vec![10]); assert!(decode_glossmap_png(b"not a png").is_err()); } #[test] fn gloss_roughness_packing_uses_alpha_only_and_checked_half_up() { assert_eq!(packed_roughness_from_alpha(0, 255).unwrap(), [0, 255, 0]); assert_eq!(packed_roughness_from_alpha(128, 255).unwrap(), [0, 127, 0]); assert_eq!(packed_roughness_from_alpha(255, 255).unwrap(), [0, 0, 0]); assert_eq!(packed_roughness_from_alpha(0, 65535).unwrap(), [0, 255, 0]); assert_eq!( packed_roughness_from_alpha(32768, 65535).unwrap(), [0, 127, 0] ); assert_eq!( packed_roughness_from_alpha(65535, 65535).unwrap(), [0, 0, 0] ); assert!(packed_roughness_from_alpha(256, 255).is_err()); } fn clip_homogeneous_segment(mut a: [f32; 4], mut b: [f32; 4]) -> Option<([f32; 4], [f32; 4])> { for plane in [[0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]] { let a_distance = a[0] * plane[0] + a[1] * plane[1] + a[2] * plane[2] + a[3] * plane[3]; let b_distance = b[0] * plane[0] + b[1] * plane[1] + b[2] * plane[2] + b[3] * plane[3]; if !a_distance.is_finite() || !b_distance.is_finite() || (a_distance < 0.0 && b_distance < 0.0) { return None; } if a_distance < 0.0 { let t = a_distance / (a_distance - b_distance); a = std::array::from_fn(|index| a[index] + (b[index] - a[index]) * t); } else if b_distance < 0.0 { let t = b_distance / (b_distance - a_distance); b = std::array::from_fn(|index| b[index] + (a[index] - b[index]) * t); } } (a[3] > 0.0 && b[3] > 0.0).then_some((a, b)) } fn expand_segment_in_pixels( a: [f32; 4], b: [f32; 4], side: f32, width: f32, viewport: [f32; 2], ) -> Option<([f32; 4], [f32; 4])> { let (a, b) = clip_homogeneous_segment(a, b)?; if !(viewport[0] > 0.0 && viewport[1] > 0.0) || !width.is_finite() { return None; } let a_ndc = [a[0] / a[3], a[1] / a[3]]; let b_ndc = [b[0] / b[3], b[1] / b[3]]; let tangent = [ (b_ndc[0] - a_ndc[0]) * 0.5 * viewport[0], (b_ndc[1] - a_ndc[1]) * 0.5 * viewport[1], ]; let length = tangent[0].hypot(tangent[1]); if length <= 0.0 || !length.is_finite() { return None; } let normal = [-tangent[1] / length, tangent[0] / length]; let offset = [ normal[0] * 2.0 / viewport[0] * 0.5 * width * side, normal[1] * 2.0 / viewport[1] * 0.5 * width * side, ]; Some(( [a[0] + offset[0] * a[3], a[1] + offset[1] * a[3], a[2], a[3]], [b[0] + offset[0] * b[3], b[1] + offset[1] * b[3], b[2], b[3]], )) } fn screen_xy(point: [f32; 4], viewport: [f32; 2]) -> [f32; 2] { [ (point[0] / point[3] + 1.0) * 0.5 * viewport[0], (point[1] / point[3] + 1.0) * 0.5 * viewport[1], ] } fn normalize3(vector: [f32; 3]) -> [f32; 3] { let length = vector[0].hypot(vector[1]).hypot(vector[2]); [vector[0] / length, vector[1] / length, vector[2] / length] } fn dot3(a: [f32; 3], b: [f32; 3]) -> f32 { a[0] * b[0] + a[1] * b[1] + a[2] * b[2] } fn cross3(a: [f32; 3], b: [f32; 3]) -> [f32; 3] { [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0], ] } fn camera_clip(point: [f32; 3], camera: [f32; 3], direction: [f32; 3], aspect: f32) -> [f32; 4] { let forward = normalize3(direction); let up_seed = if forward[2].abs() > 0.94 { [0.0, 1.0, 0.0] } else { [0.0, 0.0, 1.0] }; let right = normalize3(cross3(forward, up_seed)); let up = cross3(right, forward); let relative = [ point[0] - camera[0], point[1] - camera[1], point[2] - camera[2], ]; let camera_point = [ dot3(relative, right), dot3(relative, up), dot3(relative, forward), ]; let focal = 1.7; [ camera_point[0] * focal / aspect, camera_point[1] * focal, camera_point[2] - 1.0, camera_point[2], ] } fn transformed_point(point: [f32; 3], translation: [f32; 3], scale: f32, angle: f32) -> [f32; 3] { let (sin, cos) = angle.sin_cos(); [ translation[0] + scale * (point[0] * cos - point[1] * sin), translation[1] + scale * (point[0] * sin + point[1] * cos), translation[2] + scale * point[2], ] } fn assert_projected_ribbon_case( source: [[f32; 3]; 2], camera: [f32; 3], direction: [f32; 3], viewport: [f32; 2], ) { let aspect = viewport[0] / viewport[1]; let clips = [ camera_clip(source[0], camera, direction, aspect), camera_clip(source[1], camera, direction, aspect), ]; let positive = expand_segment_in_pixels(clips[0], clips[1], 1.0, BASE_RIBBON_WIDTH_PIXELS, viewport) .expect("orientation should produce a visible projected segment"); let negative = expand_segment_in_pixels(clips[0], clips[1], -1.0, BASE_RIBBON_WIDTH_PIXELS, viewport) .expect("both ribbon sides should expand"); let source_screen = [screen_xy(clips[0], viewport), screen_xy(clips[1], viewport)]; let positive_screen = [ screen_xy(positive.0, viewport), screen_xy(positive.1, viewport), ]; let negative_screen = [ screen_xy(negative.0, viewport), screen_xy(negative.1, viewport), ]; let tangent = [ source_screen[1][0] - source_screen[0][0], source_screen[1][1] - source_screen[0][1], ]; let tangent_length = tangent[0].hypot(tangent[1]); assert!( tangent_length > 0.0, "projected segment must remain non-degenerate" ); let normal = [-tangent[1] / tangent_length, tangent[0] / tangent_length]; for index in 0..2 { let plus = positive_screen[index]; let minus = negative_screen[index]; assert!( plus.iter() .chain(minus.iter()) .all(|value| value.is_finite()) ); let width = [plus[0] - minus[0], plus[1] - minus[1]]; assert!( (width[0] * normal[0] + width[1] * normal[1] - BASE_RIBBON_WIDTH_PIXELS).abs() < 1.0e-3 ); assert!((width[0] * tangent[0] + width[1] * tangent[1]).abs() / tangent_length < 1.0e-2); let centre = [(plus[0] + minus[0]) * 0.5, (plus[1] + minus[1]) * 0.5]; assert!((centre[0] - source_screen[index][0]).abs() < 1.0e-3); assert!((centre[1] - source_screen[index][1]).abs() < 1.0e-3); } let triangle_area = |a: [f32; 2], b: [f32; 2], c: [f32; 2]| { (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) }; assert!(triangle_area(positive_screen[0], negative_screen[0], positive_screen[1]).abs() > 0.0); assert!(triangle_area(positive_screen[1], negative_screen[0], negative_screen[1]).abs() > 0.0); } #[test] fn compact_segment_expansion_is_stable_across_camera_angles_and_aspects() { let segments = [ [[-0.8, 0.0, 0.0], [0.8, 0.0, 0.0]], [[0.0, -0.8, 0.0], [0.0, 0.8, 0.0]], [[-0.65, -0.45, 0.0], [0.7, 0.5, 0.0]], [[-0.04, 0.0, -0.8], [0.04, 0.0, 0.8]], [[-0.8, 0.0, -0.02], [0.8, 0.0, 0.02]], ]; let camera_poses = [ ([0.0, 0.0, 5.0], [0.0, 0.0, -1.0]), ([3.5, 2.0, 4.0], [-3.5, -2.0, -4.0]), ([-4.0, 1.5, 3.0], [4.0, -1.5, -3.0]), ([1.0, 4.5, 2.0], [-1.0, -4.5, -2.0]), ([0.2, -0.3, 5.0], [-0.02, 0.03, -1.0]), ]; let viewports = [[800.0, 800.0], [1600.0, 900.0], [900.0, 1600.0]]; for (camera, direction) in camera_poses { for viewport in viewports { for segment in segments { assert_projected_ribbon_case(segment, camera, direction, viewport); let transformed = [ transformed_point(segment[0], [0.7, -0.4, 0.2], 1.3, 0.6), transformed_point(segment[1], [0.7, -0.4, 0.2], 1.3, 0.6), ]; assert_projected_ribbon_case(transformed, camera, direction, viewport); let repeated = [ transformed_point(segment[0], [-0.8, 0.6, -0.3], 0.75, -0.9), transformed_point(segment[1], [-0.8, 0.6, -0.3], 0.75, -0.9), ]; assert_projected_ribbon_case(repeated, camera, direction, viewport); } } } } #[test] fn compact_segment_shader_uses_pixel_width_uniform_and_no_fake_tangent() { let shader = compact_segment_vertex_shader(BASE_RIBBON_WIDTH_PIXELS); assert!(shader.contains("uniform vec2 viewport")); assert!(shader.contains("window_tangent")); assert!(shader.contains("2.0 / viewport")); assert!(shader.contains("0.5 * 1.5000000")); assert!(shader.contains("clip_segment_to_plane")); assert!(!shader.contains("clip_epsilon")); assert!(!shader.contains("vec2(1.0, 0.0)")); } #[test] fn compact_segment_aabb_rejects_empty_or_nonfinite_production_inputs() { let identity = Mat4::from_scale(1.0); assert!(matches!( compact_segment_aabb(&[], &[identity]), Err(RendererError::InvalidRange { context: "compact segment endpoints", index: 0, len: 0, }) )); assert!(matches!( compact_segment_aabb( &[three_d::vec3(0.0, 0.0, 0.0), three_d::vec3(1.0, 0.0, 0.0)], &[], ), Err(RendererError::InvalidRange { context: "compact segment transforms", index: 0, len: 0, }) )); assert!(matches!( compact_segment_aabb(&[three_d::vec3(f32::NAN, 0.0, 0.0)], &[identity]), Err(RendererError::NonFiniteTransform) )); let overflow = Mat4::from_nonuniform_scale(f32::MAX, 1.0, 1.0); assert!(matches!( compact_segment_aabb( &[three_d::vec3(-2.0, 0.0, 0.0), three_d::vec3(2.0, 0.0, 0.0)], &[overflow], ), Err(RendererError::NonFiniteTransform) )); } #[test] fn compact_segment_cardinality_rejects_every_gpu_boundary_mismatch() { assert_eq!( validate_compact_segment_cardinality(2, Some(2), 3, Some(3)), Ok((12, 3)) ); assert_eq!( validate_compact_segment_cardinality(u64::MAX / 6 + 1, None, 1, None).unwrap_err(), RendererError::IndexOverflow { context: "compact segment vertex count", } ); assert_eq!( validate_compact_segment_cardinality(2, Some(1), 1, None).unwrap_err(), RendererError::InvalidRange { context: "compact segment controls", index: 1, len: 2, } ); assert_eq!( validate_compact_segment_cardinality(1, None, 2, Some(1)).unwrap_err(), RendererError::InvalidRange { context: "compact segment local views", index: 1, len: 2, } ); assert_eq!( validate_compact_segment_cardinality(1, None, u64::from(u32::MAX) + 1, None).unwrap_err(), RendererError::IndexOverflow { context: "compact segment instance count", } ); } #[test] fn compact_segment_aabb_contains_every_transformed_instance_endpoint() { let endpoints = [ three_d::vec3(-1.0, -0.5, 0.25), three_d::vec3(1.0, 0.5, 0.75), ]; let transforms = [ Mat4::from_translation(three_d::vec3(12.0, 0.0, 0.0)), Mat4::from_translation(three_d::vec3(-12.0, 0.0, 0.0)) * Mat4::from_angle_z(three_d::Rad(0.5)), ]; let aabb = compact_segment_aabb(&endpoints, &transforms).expect("finite transformed bounds"); for transform in transforms { for endpoint in endpoints { assert!(aabb.is_inside((transform * endpoint.extend(1.0)).truncate())); } } assert!(aabb.min().x <= -12.0); assert!(aabb.max().x >= 12.0); } #[test] fn compact_segment_expansion_preserves_endpoints_and_pixel_width_across_depths_and_aspects() { for viewport in [[800.0, 800.0], [1600.0, 900.0], [900.0, 1600.0]] { for depth in [1.0, 3.0, 20.0] { let a = [-0.3 * depth, -0.2 * depth, 0.0, depth]; let b = [0.4 * depth, 0.25 * depth, 0.0, depth]; let expanded = expand_segment_in_pixels(a, b, 1.0, BASE_RIBBON_WIDTH_PIXELS, viewport) .expect("valid segment expands"); let source_a = screen_xy(a, viewport); let source_b = screen_xy(b, viewport); let expanded_a = screen_xy(expanded.0, viewport); let expanded_b = screen_xy(expanded.1, viewport); let tangent = [source_b[0] - source_a[0], source_b[1] - source_a[1]]; let length = tangent[0].hypot(tangent[1]); let normal = [-tangent[1] / length, tangent[0] / length]; for (source, actual) in [(source_a, expanded_a), (source_b, expanded_b)] { let delta = [actual[0] - source[0], actual[1] - source[1]]; assert!( (delta[0] * normal[0] + delta[1] * normal[1] - BASE_RIBBON_WIDTH_PIXELS * 0.5) .abs() < 1.0e-4 ); assert!((delta[0] * tangent[0] + delta[1] * tangent[1]).abs() / length < 1.0e-2); } } } } #[test] fn compact_segment_expansion_handles_orientations_transforms_and_invalid_segments() { let viewport = [1280.0, 720.0]; for (a, b) in [ ([-0.5, 0.0, 0.0, 1.0], [0.5, 0.0, 0.0, 1.0]), ([0.0, -0.5, 0.0, 1.0], [0.0, 0.5, 0.0, 1.0]), ([-0.4, -0.3, 0.0, 1.0], [0.5, 0.4, 0.0, 1.0]), ([-0.2, 0.1, 0.0, 2.0], [0.4, -0.3, 0.0, 5.0]), ] { let expanded = expand_segment_in_pixels(a, b, -1.0, SELECTED_RIBBON_WIDTH_PIXELS, viewport) .expect("valid orientation expands"); assert!(expanded.0.iter().all(|value| value.is_finite())); assert!(expanded.1.iter().all(|value| value.is_finite())); assert_eq!(expanded.0[2], a[2]); assert_eq!(expanded.0[3], a[3]); assert_eq!(expanded.1[2], b[2]); assert_eq!(expanded.1[3], b[3]); } assert!( expand_segment_in_pixels( [0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 1.0], 1.0, BASE_RIBBON_WIDTH_PIXELS, viewport, ) .is_none() ); assert!(clip_homogeneous_segment([0.0, 0.0, -3.0, 1.0], [0.5, 0.0, -2.0, 1.0]).is_none()); assert!(clip_homogeneous_segment([0.0, 0.0, 0.0, -1.0], [0.25, 0.0, 0.25, 1.0]).is_none()); } fn topology_geometry( points: Vec<[f64; 3]>, triangles: Vec<[u32; 3]>, quads: Vec<[u32; 4]>, ) -> SceneGeometry { SceneGeometry { id: GeometryId(1), provenance: ProvenanceId(1), points: points.into_boxed_slice(), uvs: Box::default(), triangles: triangles.into_boxed_slice(), quads: quads.into_boxed_slice(), lines: Box::default(), conditional_lines: Box::default(), primitives: Box::default(), } } fn picker_scene() -> Scene { let geometry = topology_geometry( vec![[-1.0, -1.0, 0.0], [1.0, -1.0, 0.0], [0.0, 1.0, 0.0]], vec![[0, 1, 2]], Vec::new(), ); let occurrence = |id, z| SceneOccurrence { id: OccurrenceId(id), canonical_occurrence_id: smol_str::format_smolstr!("root/{id}"), parent_occurrence_id: Some("root".into()), logical_part_occurrence_id: Some(smol_str::format_smolstr!("root/{id}")), logical_part_path: Some("parts/triangle.dat".into()), node: NodeId(1), uvs: None, definition_id: "triangle.dat".into(), canonical_path: "parts/triangle.dat".into(), source_class: "part".into(), source: "root.ldr".into(), target: "triangle.dat".into(), source_span: Some([id as u32, 0, 1, 1]), direct_colour: 4, effective_colour: 4, primitive_colour: 4, material: Some(MaterialId(1)), bfc_state: "Certified".into(), bfc_cull: true, bfc_ccw: true, bfc_inverted: false, transform: [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, z, 1.0], ], }; Scene { id: SceneId(1), units: Units::declared(LengthUnit::LdrawUnit), source: "root.ldr".into(), provenance: Box::default(), diagnostics: Box::default(), root: NodeId(1), geometries: Box::new([geometry]), materials: Box::new([SceneMaterial { id: MaterialId(1), colour: 4, colour_rgb: Some([201, 26, 9]), alpha: 255, edge_colour: None, finish: None, local_mapping: None, albedo_texture: None, metallic_roughness_texture: None, }]), textures: Box::default(), occurrences: Box::new([occurrence(1, 5.0), occurrence(2, 2.0)]), bounds: SceneBounds::from_points([[-1.0, -1.0, 2.0], [1.0, 1.0, 5.0]]), stats: SceneStats::default(), } } #[test] fn textured_occurrences_share_geometry_and_split_uv_batches() { let mut scene = picker_scene(); let uv_a = vec![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]; let uv_b = vec![[0.25, 0.25], [0.75, 0.25], [0.25, 0.75]]; scene.occurrences[0].uvs = Some(Arc::from(uv_a.clone().into_boxed_slice())); scene.occurrences[1].uvs = Some(Arc::from(uv_b.clone().into_boxed_slice())); let plan = scene_render_plan(&scene).expect("render plan"); assert_eq!(scene.geometries.len(), 1); assert_eq!(scene.occurrences[0].node, scene.occurrences[1].node); assert_eq!(plan.batches.len(), 2); assert_eq!(plan.batches[0].uvs.as_deref(), Some(uv_a.as_slice())); assert_eq!(plan.batches[1].uvs.as_deref(), Some(uv_b.as_slice())); let picker = ScenePicker::new(&scene, plan).expect("picker with UV-split batches"); let hit = picker .pick(PickRay { origin: [0.0, 0.0, 10.0], direction: [0.0, 0.0, -1.0], }) .expect("UV-split picker ray") .expect("UV-split picker hit"); assert_eq!(hit.occurrence_index, 0); assert!(picker.selection(hit.occurrence_index).is_ok()); } #[test] fn scene_render_plan_rejects_misaligned_occurrence_uvs() { let mut scene = picker_scene(); scene.occurrences[0].uvs = Some(Arc::from(vec![[0.0, 0.0]].into_boxed_slice())); let error = scene_render_plan(&scene).expect_err("misaligned occurrence UVs"); assert!(matches!( error, RendererError::InvalidRange { context: "occurrence UV alignment", index: 1, len: 3, } )); } #[test] fn scene_render_plan_rejects_non_finite_occurrence_uvs() { let mut scene = picker_scene(); scene.occurrences[0].uvs = Some(Arc::from(vec![[f32::NAN, 0.0]; 3].into_boxed_slice())); let error = scene_render_plan(&scene).expect_err("non-finite occurrence UVs"); assert!(matches!( error, RendererError::InvalidRange { context: "occurrence UV alignment", index: 3, len: 3, } )); } #[test] fn selection_interaction_requires_shift_and_pointer_up() { let mut interaction = SelectionInteraction::default(); assert_eq!( interaction.pointer_down(10.0, 20.0), SelectionPointerAction::ForwardToOrbit ); assert_eq!( interaction.pointer_up(10.0, 20.0), SelectionPointerAction::ForwardToOrbit ); interaction.set_modifiers(true); assert_eq!( interaction.pointer_down(10.0, 20.0), SelectionPointerAction::WithholdFromOrbit ); assert_eq!( interaction.pointer_up(10.0, 20.0), SelectionPointerAction::Select { x: 10.0, y: 20.0 } ); } #[test] fn scene_material_alpha_selects_transparent_color_only_material_state() { let material = SceneMaterial { id: MaterialId(1), colour: 4, colour_rgb: Some([201, 26, 9]), alpha: 128, edge_colour: None, finish: None, local_mapping: None, albedo_texture: None, metallic_roughness_texture: None, }; let translucent = scene_material_translucent(&material, false); assert!(translucent); assert_eq!(scene_material_type(translucent), MaterialType::Transparent); let states = scene_material_render_states(translucent, true); assert_eq!(states.cull, Cull::Back); assert_eq!(states.depth_test, three_d::DepthTest::Less); assert!(!states.write_mask.depth); assert_eq!( states.blend, Blend::Enabled { source_rgb_multiplier: BlendMultiplierType::SrcAlpha, source_alpha_multiplier: BlendMultiplierType::One, destination_rgb_multiplier: BlendMultiplierType::OneMinusSrcAlpha, destination_alpha_multiplier: BlendMultiplierType::OneMinusSrcAlpha, rgb_equation: BlendEquationType::Add, alpha_equation: BlendEquationType::Add, } ); } #[test] fn compact_segment_material_uses_one_production_depth_policy() { let material = compact_segment_material(4, true); assert_eq!(material.color, Srgba::new(116, 180, 255, 200)); assert_eq!(material.material_type(), MaterialType::Transparent); assert_eq!(material.render_states.depth_test, three_d::DepthTest::Less); assert!(material.render_states.write_mask.depth); assert_eq!( material.render_states.blend, Blend::Enabled { source_rgb_multiplier: BlendMultiplierType::SrcAlpha, source_alpha_multiplier: BlendMultiplierType::One, destination_rgb_multiplier: BlendMultiplierType::OneMinusSrcAlpha, destination_alpha_multiplier: BlendMultiplierType::OneMinusSrcAlpha, rgb_equation: BlendEquationType::Add, alpha_equation: BlendEquationType::Add, } ); } #[test] fn base_edge_material_remains_opaque_with_blending_disabled() { let material = compact_segment_material(4, false); assert_eq!(material.material_type(), MaterialType::Opaque); assert_eq!(material.render_states.blend, Blend::Disabled); assert_eq!(material.render_states.depth_test, three_d::DepthTest::Less); assert!(material.render_states.write_mask.depth); } #[test] fn selection_interaction_latches_shift_at_pointer_down() { let mut interaction = SelectionInteraction::default(); interaction.set_modifiers(true); interaction.pointer_down(10.0, 20.0); interaction.set_modifiers(false); assert_eq!( interaction.pointer_up(10.0, 20.0), SelectionPointerAction::Select { x: 10.0, y: 20.0 } ); interaction.set_modifiers(false); interaction.pointer_down(30.0, 40.0); interaction.set_modifiers(true); assert_eq!( interaction.pointer_up(30.0, 40.0), SelectionPointerAction::ForwardToOrbit ); } #[test] fn selection_interaction_forwards_drag_and_cleans_pending_state() { let mut interaction = SelectionInteraction::default(); interaction.set_modifiers(true); interaction.pointer_down(0.0, 0.0); assert_eq!( interaction.pointer_move(3.0, 0.0), SelectionPointerAction::WithholdFromOrbit ); assert_eq!( interaction.pointer_move(4.0, 0.0), SelectionPointerAction::ForwardToOrbit ); assert_eq!( interaction.pointer_up(20.0, 0.0), SelectionPointerAction::ForwardToOrbit ); interaction.pointer_down(1.0, 1.0); interaction.cancel(); assert!(!interaction.has_pending_click()); interaction.pointer_down(1.0, 1.0); interaction.dispose(); assert!(!interaction.has_pending_click()); } #[cfg(not(target_arch = "wasm32"))] #[test] fn conditional_only_selection_keeps_a_tagged_fallback() { let bounds = SceneBounds::from_points([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]); assert_eq!( selection_fallback(true, bounds), bounds.map(SelectionFallback::BoundingBox) ); assert_eq!(selection_fallback(false, bounds), None); } #[cfg(not(target_arch = "wasm32"))] #[test] fn logical_part_selection_promotes_through_non_rendered_ancestors_and_selects_subtree() { let mut scene = picker_scene(); scene.occurrences[0].canonical_occurrence_id = "leaf-disc".into(); scene.occurrences[0].canonical_path = "p/4-4disc.dat".into(); scene.occurrences[0].parent_occurrence_id = Some("primitive-stud-with-no-geometry".into()); scene.occurrences[0].logical_part_occurrence_id = Some("logical-part-with-no-geometry".into()); scene.occurrences[0].logical_part_path = Some("parts/3021.dat".into()); scene.occurrences[1].canonical_occurrence_id = "sibling-leaf".into(); scene.occurrences[1].canonical_path = "parts/s/3021s01.dat".into(); scene.occurrences[1].parent_occurrence_id = Some("logical-part-with-no-geometry".into()); scene.occurrences[1].logical_part_occurrence_id = Some("logical-part-with-no-geometry".into()); scene.occurrences[1].logical_part_path = Some("parts/3021.dat".into()); let mut unrelated = scene.occurrences[1].clone(); unrelated.canonical_occurrence_id = "other-part".into(); unrelated.parent_occurrence_id = Some("root".into()); unrelated.logical_part_occurrence_id = Some("other-part".into()); unrelated.logical_part_path = Some("parts/3001.dat".into()); scene.occurrences = scene .occurrences .into_vec() .into_iter() .chain([unrelated]) .collect::>() .into_boxed_slice(); let plan = scene_render_plan(&scene).expect("render plan"); let picker = ScenePicker::new(&scene, plan).expect("picker"); let selection = picker.selection(0).expect("logical selection"); assert_eq!( selection.logical_part_occurrence_id, "logical-part-with-no-geometry" ); assert_eq!(selection.logical_part_path, "parts/3021.dat"); assert_eq!(selection.occurrence_indices, vec![0, 1]); assert!( scene.occurrences.iter().all(|occurrence| { occurrence.canonical_occurrence_id != selection.logical_part_occurrence_id }), "the promoted logical ancestor must deliberately have no rendered occurrence" ); } #[cfg(not(target_arch = "wasm32"))] #[test] fn empty_face_batch_does_not_shift_later_gpu_ranges() { let mut scene = picker_scene(); scene.geometries = scene .geometries .into_vec() .into_iter() .enumerate() .flat_map(|(index, geometry)| { (index == 0) .then_some(SceneGeometry { id: GeometryId(99), provenance: ProvenanceId(1), points: Box::new([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]), uvs: Box::default(), triangles: Box::default(), quads: Box::default(), lines: Box::new([[0, 1]]), conditional_lines: Box::default(), primitives: Box::default(), }) .into_iter() .chain((index == 0).then_some(geometry)) }) .collect::>() .into_boxed_slice(); let edge_occurrence = SceneOccurrence { id: OccurrenceId(99), canonical_occurrence_id: "edge-only".into(), parent_occurrence_id: None, logical_part_occurrence_id: None, logical_part_path: None, node: NodeId(99), uvs: None, definition_id: "edge-only".into(), canonical_path: "edge-only.ldr".into(), source_class: "CurrentMpd".into(), source: "edge-only.ldr".into(), target: "edge-only.ldr".into(), source_span: None, direct_colour: 16, effective_colour: 16, primitive_colour: 16, material: Some(MaterialId(1)), bfc_state: "Uncertified".into(), bfc_cull: false, bfc_ccw: true, bfc_inverted: false, transform: [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], ], }; scene.occurrences = scene .occurrences .into_vec() .into_iter() .enumerate() .flat_map(|(index, occurrence)| { (index == 0) .then_some(edge_occurrence.clone()) .into_iter() .chain((index != 0).then_some(occurrence)) }) .collect::>() .into_boxed_slice(); let plan = scene_render_plan(&scene).expect("render plan"); assert_eq!(plan.planned_to_upload[0], None); assert_eq!(plan.planned_to_upload[1], Some(0)); assert_eq!(plan.occurrence_ranges[0], None); assert_eq!(plan.occurrence_ranges[1].unwrap().batch, 0); } #[test] fn render_batches_preserve_identity_and_reflected_normal_provenance() { let mut scene = picker_scene(); scene.occurrences[1].transform[0][0] = -1.0; scene.occurrences[1].bfc_inverted = true; let plan = scene_render_plan(&scene).expect("render plan"); assert_eq!(plan.batches.len(), 2); let expected_material = MaterialId(1); assert_eq!(plan.batches[0].material, expected_material); assert_eq!(plan.batches[1].material, expected_material); let resolved_material = scene .materials .iter() .find(|material| material.id == expected_material) .expect("fixture material"); assert_eq!(resolved_material.colour, 4); assert!(!plan.batches[0].reflection); assert!(plan.batches[1].reflection); assert!(plan.batches[0].bfc_cull); assert!(plan.batches[1].bfc_cull); assert!(plan.batches[0].bfc_ccw); assert!(plan.batches[1].bfc_ccw); assert!(!plan.batches[0].bfc_inverted); assert!(plan.batches[1].bfc_inverted); assert_ne!( plan.batches[0].instances[0].transform, plan.batches[1].instances[0].transform ); let topology = &plan.topologies[0]; let [a, b, c] = topology.indices[..3] else { unreachable!() }; let p = |index: u32| topology.positions[index as usize]; let cross = |a: [f32; 3], b: [f32; 3], c: [f32; 3]| { let ab = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; let ac = [c[0] - a[0], c[1] - a[1], c[2] - a[2]]; [ ab[1] * ac[2] - ab[2] * ac[1], ab[2] * ac[0] - ab[0] * ac[2], ab[0] * ac[1] - ab[1] * ac[0], ] }; let authored = cross(p(a), p(b), p(c)); let reversed_upload = [-authored[0], -authored[1], -authored[2]]; let corrected_upload = [ -reversed_upload[0], -reversed_upload[1], -reversed_upload[2], ]; let reflection = plan.batches[1].reflection; let world = if reflection { [ -corrected_upload[0], corrected_upload[1], corrected_upload[2], ] } else { corrected_upload }; assert_eq!( world, authored, "the produced batch reflection value restores the world-facing normal" ); } #[cfg(not(target_arch = "wasm32"))] #[test] fn occurrence_gpu_ranges_follow_production_batch_instances_and_topology() { let ranges = occurrence_gpu_ranges(&picker_scene()).expect("ranges"); assert_eq!(ranges.len(), 2); assert_eq!( (ranges[0].unwrap().batch, ranges[0].unwrap().instance), (0, 0) ); assert_eq!( (ranges[1].unwrap().batch, ranges[1].unwrap().instance), (0, 1) ); assert_eq!(ranges[0].unwrap().geometry, GeometryId(1)); assert_eq!( ( ranges[0].unwrap().vertex_start, ranges[0].unwrap().vertex_count ), (0, 3) ); assert_eq!( ( ranges[0].unwrap().index_start, ranges[0].unwrap().index_count ), (0, 3) ); } #[cfg(not(target_arch = "wasm32"))] #[test] fn scene_consumers_resolve_sparse_opaque_ids_and_reject_invalid_references() { let mut scene = picker_scene(); scene.geometries[0].id = GeometryId(41); scene.root = NodeId(41); for occurrence in &mut scene.occurrences { occurrence.node = NodeId(41); occurrence.material = Some(MaterialId(73)); } scene.materials[0].id = MaterialId(73); let ranges = occurrence_gpu_ranges(&scene).expect("sparse ids"); assert_eq!(ranges[0].unwrap().geometry, GeometryId(41)); let plan = scene_render_plan(&scene).expect("sparse-id render plan"); let picker = ScenePicker::new(&scene, plan).expect("sparse-id picker"); assert!( picker .pick(PickRay { origin: [0.0, 0.0, 0.0], direction: [0.0, 0.0, 1.0], }) .expect("sparse-id pick") .is_some() ); let mut duplicate = scene.clone(); let duplicate_geometry = duplicate.geometries[0].clone(); duplicate.geometries = duplicate .geometries .into_vec() .into_iter() .chain([duplicate_geometry]) .collect::>() .into_boxed_slice(); assert_eq!( occurrence_gpu_ranges(&duplicate).unwrap_err(), RendererError::DuplicateGeometry(GeometryId(41)) ); let mut dangling_geometry = scene.clone(); dangling_geometry.occurrences[0].node = NodeId(99); assert_eq!( occurrence_gpu_ranges(&dangling_geometry).unwrap_err(), RendererError::MissingGeometry(GeometryId(99)) ); let mut dangling_material = scene; dangling_material.occurrences[0].material = Some(MaterialId(99)); assert_eq!( occurrence_gpu_ranges(&dangling_material).unwrap_err(), RendererError::MissingMaterial(MaterialId(99)) ); } #[cfg(not(target_arch = "wasm32"))] #[test] fn affine_bounds_match_transformed_corners() { let local = PickBounds { min: [-2.0, -3.0, -5.0], max: [7.0, 11.0, 13.0], }; let transform = [ [0.0, -2.0, 0.5, 0.0], [-3.0, 0.0, 0.25, 0.0], [0.75, 0.5, -4.0, 0.0], [17.0, -19.0, 23.0, 1.0], ]; let corners = (0..8) .map(|corner| { apply_scene_transform( transform, [ if corner & 1 == 0 { local.min[0] } else { local.max[0] }, if corner & 2 == 0 { local.min[1] } else { local.max[1] }, if corner & 4 == 0 { local.min[2] } else { local.max[2] }, ], ) .expect("finite corner") }) .collect::>(); let expected = PickBounds::from_points(corners).expect("corner bounds"); let actual = local.transformed(transform).expect("affine bounds"); for axis in 0..3 { assert!((actual.min[axis] - expected.min[axis]).abs() < 1.0e-12); assert!((actual.max[axis] - expected.max[axis]).abs() < 1.0e-12); } } #[cfg(not(target_arch = "wasm32"))] #[test] fn picker_returns_nearest_visible_occurrence_and_gpu_range() { let scene = picker_scene(); let plan = scene_render_plan(&scene).expect("render plan"); let picker = ScenePicker::new(&scene, plan).expect("picker"); let hit = picker .pick(PickRay { origin: [0.0, 0.0, 0.0], direction: [0.0, 0.0, 1.0], }) .expect("pick") .expect("hit"); assert_eq!(hit.occurrence_index, 1); assert_eq!(hit.triangle_index, 0); assert!((hit.distance - 2.0).abs() < 1.0e-12); let gpu = hit.gpu.expect("face occurrence has a GPU range"); assert_eq!((gpu.batch, gpu.instance), (0, 1)); } #[cfg(not(target_arch = "wasm32"))] #[test] fn picker_intersects_occurrence_transformed_triangles() { let mut scene = picker_scene(); let mut occurrences = scene.occurrences.into_vec(); occurrences.truncate(1); scene.occurrences = occurrences.into_boxed_slice(); scene.occurrences[0].transform = [ [2.0, 0.0, 0.0, 0.0], [0.0, 2.0, 0.0, 0.0], [0.0, 0.0, 3.0, 0.0], [4.0, -3.0, 7.0, 1.0], ]; let plan = scene_render_plan(&scene).expect("render plan"); let picker = ScenePicker::new(&scene, plan).expect("picker"); let hit = picker .pick(PickRay { origin: [4.0, -3.0, 0.0], direction: [0.0, 0.0, 1.0], }) .expect("pick") .expect("transformed hit"); assert_eq!(hit.occurrence_index, 0); assert_eq!(hit.triangle_index, 0); assert!((hit.distance - 7.0).abs() < 1.0e-12); } #[cfg(not(target_arch = "wasm32"))] #[test] fn picker_returns_none_when_ray_misses_scene_geometry() { let scene = picker_scene(); let plan = scene_render_plan(&scene).expect("render plan"); let picker = ScenePicker::new(&scene, plan).expect("picker"); let hit = picker .pick(PickRay { origin: [4.0, 4.0, 0.0], direction: [0.0, 0.0, 1.0], }) .expect("pick"); assert_eq!(hit, None); } #[cfg(not(target_arch = "wasm32"))] #[test] fn scene_topology_preserves_single_triangle_vertices() { let topology = scene_mesh_topology(&topology_geometry( vec![[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 3.0, 0.0]], vec![[0, 1, 2]], Vec::new(), )) .unwrap(); assert_eq!( topology.positions.as_ref(), &[[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 3.0, 0.0]][..] ); assert_eq!(topology.indices, [0, 1, 2]); assert_eq!(topology.triangle_count(), 1); assert_eq!(topology.max_index(), Some(2)); } #[cfg(not(target_arch = "wasm32"))] #[test] fn scene_topology_keeps_shared_vertices_and_reverse_winding_local() { let points = vec![ [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], ]; let forward = scene_mesh_topology(&topology_geometry( points.clone(), vec![[0, 1, 2], [0, 2, 3]], Vec::new(), )) .unwrap(); let reflected = scene_mesh_topology(&topology_geometry( points, vec![[2, 1, 0], [3, 2, 0]], Vec::new(), )) .unwrap(); assert_eq!(forward.positions.len(), 4); assert_eq!(forward.indices, [0, 1, 2, 0, 2, 3]); assert_eq!(reflected.indices, [2, 1, 0, 3, 2, 0]); assert_eq!(forward.triangle_count(), 2); assert_eq!(forward.max_index(), Some(3)); } #[cfg(not(target_arch = "wasm32"))] #[test] fn native_topology_triangulates_quads_and_preserves_rebased_records() { let topology = scene_mesh_topology(&topology_geometry( vec![ [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [10.0, 0.0, 0.0], [11.0, 0.0, 0.0], [10.0, 1.0, 0.0], ], vec![[4, 5, 6]], vec![[0, 1, 2, 3]], )) .unwrap(); assert_eq!(topology.indices, [4, 5, 6, 0, 1, 2, 0, 2, 3]); assert_eq!(topology.triangle_count(), 3); assert_eq!(topology.max_index(), Some(6)); for triangle in topology.indices.chunks_exact(3) { let vertices = triangle .iter() .map(|index| topology.positions[*index as usize]) .collect::>(); assert_eq!(vertices.len(), 3); } } #[cfg(not(target_arch = "wasm32"))] #[test] fn native_topology_rejects_foreign_index_domains() { let error = scene_mesh_topology(&topology_geometry( vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], vec![[0, 1, 3]], Vec::new(), )) .unwrap_err(); assert_eq!( error, RendererError::InvalidRange { context: "geometry index", index: 3, len: 3, } ); } #[cfg(not(target_arch = "wasm32"))] #[test] fn native_topology_expands_lines_and_filters_conditional_lines_by_view() { let mut geometry = topology_geometry( vec![ [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0], [0.0, -1.0, 0.0], [1.0, -1.0, 0.0], ], Vec::new(), Vec::new(), ); geometry.lines = vec![[0, 1]].into(); geometry.conditional_lines = vec![[4, 5, 0, 1]].into(); let visible = scene_mesh_topology_for_view(&geometry, [0.0, 0.0, 1.0]).unwrap(); let hidden = scene_mesh_topology_for_view(&geometry, [0.0, 0.0, -1.0]).unwrap(); assert_eq!( visible.triangle_count(), 4, "line plus visible conditional line" ); assert_eq!( hidden.triangle_count(), 4, "reversing the view preserves the two-control projected-side result" ); assert!(visible.positions.len() > geometry.points.len()); } #[cfg(not(target_arch = "wasm32"))] #[test] fn edge_topology_excludes_source_faces() { let mut geometry = topology_geometry( vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], vec![[0, 1, 2]], Vec::new(), ); geometry.lines = vec![[0, 1]].into(); let edges = scene_mesh_topology_for_view_kind(&geometry, [0.0, 0.0, 1.0], SceneTopologyKind::Edges) .unwrap(); assert_eq!( edges.triangle_count(), 2, "authored line becomes an edge ribbon" ); assert_eq!(edges.positions.len(), 4); assert!( edges .positions .iter() .all(|position| position[2].abs() < f32::EPSILON), "edge topology contains authored line positions, not source face vertices" ); } #[cfg(not(target_arch = "wasm32"))] #[test] fn render_plan_uses_faces_without_edge_ribbons() { let mut scene = picker_scene(); scene.geometries[0].lines = vec![[0, 1]].into(); scene.geometries[0].conditional_lines = vec![[0, 1, 2, 1]].into(); let complete = scene_mesh_topology(&scene.geometries[0]).expect("complete topology"); let plan = scene_render_plan(&scene).expect("render plan"); assert!(complete.triangle_count() > plan.topologies[0].triangle_count()); assert_eq!(plan.topologies[0].triangle_count(), 1); assert_eq!(plan.topologies[0].indices, [0, 1, 2]); } #[cfg(not(target_arch = "wasm32"))] #[test] fn native_topology_rejects_malformed_conditional_line_indices() { let mut geometry = topology_geometry( vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]], Vec::new(), Vec::new(), ); geometry.conditional_lines = vec![[0, 1, 2, 3]].into(); let error = scene_mesh_topology(&geometry).unwrap_err(); assert_eq!( error, RendererError::InvalidRange { context: "geometry conditional-line index", index: 2, len: 2, } ); } #[cfg(not(target_arch = "wasm32"))] #[test] fn render_plan_retains_canonical_edge_sources_in_one_pass() { let mut scene = picker_scene(); scene.geometries[0].lines = vec![[0, 1]].into(); scene.geometries[0].conditional_lines = vec![[0, 1, 2, 1]].into(); let plan = scene_render_plan(&scene).expect("render plan"); assert_eq!(plan.planned_occurrences.len(), 2); assert!( plan.edge_sources .iter() .all(|source| source.explicit.len() == 1) ); assert!( plan.edge_sources .iter() .all(|source| source.conditional.len() == 1) ); let conditional = build_conditional_edge_topology_for_scene(&scene, &plan, [0.0, 0.0, 1.0]) .expect("conditional topology"); assert_eq!(conditional.len(), 1); } #[cfg(not(target_arch = "wasm32"))] #[test] fn conditional_cache_filtering_is_view_only_and_does_not_change_plan() { let mut scene = picker_scene(); scene.geometries[0].conditional_lines = vec![[0, 1, 2, 1]].into(); let plan = scene_render_plan(&scene).expect("render plan"); let before = plan.clone(); let first = build_conditional_edge_topology_for_scene(&scene, &plan, [0.0, 0.0, 1.0]) .expect("first conditional topology"); let second = build_conditional_edge_topology_for_scene(&scene, &plan, [0.0, 0.0, -1.0]) .expect("second conditional topology"); assert_eq!(plan, before); assert_eq!(first.len(), 1); assert_eq!(second.len(), 1); } #[cfg(not(target_arch = "wasm32"))] #[test] fn edge_build_reports_exact_counts_and_reuses_occurrence_sources() { let mut scene = picker_scene(); scene.geometries[0].lines = vec![[0, 1]].into(); scene.geometries[0].conditional_lines = vec![[0, 1, 2, 1]].into(); let plan = scene_render_plan(&scene).expect("render plan"); let stats = edge_build_stats(&scene, &plan, [0.0, 0.0, 1.0]).expect("edge stats"); assert_eq!(stats.source_geometry_count, 1); assert_eq!(stats.planned_occurrences, 2); assert_eq!(stats.explicit_segments, 2); assert_eq!(stats.visible_conditional_segments, 2); assert_eq!(stats.generated_vertices, 12); assert_eq!(stats.generated_indices, 0); assert_eq!(stats.source_segment_vertices, 12); assert_eq!(stats.instance_count, 4); assert_eq!(stats.material_groups, 2); } #[cfg(not(target_arch = "wasm32"))] #[test] fn selected_edge_refilter_uses_cached_membership_without_changing_base_counts() { let mut scene = picker_scene(); scene.geometries[0].lines = vec![[0, 1]].into(); let plan = scene_render_plan(&scene).expect("render plan"); let selection = SelectionIdentity { canonical_occurrence_id: "root/1".into(), canonical_path: "parts/triangle.dat".into(), logical_part_occurrence_id: "root/1".into(), logical_part_path: "parts/triangle.dat".into(), occurrence_indices: vec![1], transforms: vec![scene.occurrences[1].transform], bounds: None, }; let (base_explicit, _) = compact_edge_inputs_for_membership(&scene, &plan, [0.0, 0.0, 1.0], None) .expect("base edge inputs"); let (selected_explicit, _) = compact_edge_inputs_for_membership( &scene, &plan, [0.0, 0.0, 1.0], Some(&selection.occurrence_indices), ) .expect("selected edge inputs"); assert_eq!(base_explicit.stats.planned_occurrences, 2); assert_eq!(base_explicit.stats.instance_count, 2); assert_eq!(selected_explicit.stats.planned_occurrences, 2); assert_eq!(selected_explicit.stats.instance_count, 1); assert_eq!( selected_explicit.batches[0].transforms, vec![scene_transform_to_mat4(selection.transforms[0]).expect("selected transform")] ); } #[cfg(not(target_arch = "wasm32"))] #[test] fn conditional_only_refresh_has_no_explicit_batches_and_preserves_shader_inputs() { let mut scene = picker_scene(); scene.geometries[0].conditional_lines = vec![[0, 1, 2, 1]].into(); let plan = scene_render_plan(&scene).expect("render plan"); let selection = [1usize]; let inputs = compact_conditional_edge_inputs_for_membership( &scene, &plan, [0.0, 0.0, 1.0], Some(&selection), ) .expect("conditional-only inputs"); assert!(inputs.batches.iter().all(|batch| batch.segments.len() == 1)); assert!(inputs.batches.iter().all(|batch| { batch .controls .as_ref() .is_some_and(|controls| controls.len() == 1) })); assert!(inputs.batches.iter().all(|batch| { batch .local_views .as_ref() .is_some_and(|views| views.len() == 1) })); assert_eq!(inputs.stats.visible_conditional_segments, 1); assert_eq!(inputs.stats.instance_count, 1); assert_eq!(inputs.stats.material_groups, 1); } #[cfg(not(target_arch = "wasm32"))] #[test] fn selected_production_inputs_preserve_type_two_and_type_five_controls_and_local_views() { let mut scene = picker_scene(); scene.geometries[0].lines = vec![[0, 1]].into(); scene.geometries[0].conditional_lines = vec![[0, 1, 2, 1]].into(); let plan = scene_render_plan(&scene).expect("render plan"); let picker = ScenePicker::new(&scene, plan.clone()).expect("picker"); let selection = picker.selection(1).expect("selected occurrence"); let (explicit, conditional) = compact_edge_inputs_for_membership( &scene, &plan, [0.0, 0.0, 1.0], Some(&selection.occurrence_indices), ) .expect("selected production inputs"); assert_eq!(explicit.batches.len(), 1, "selected type-2 batch"); assert_eq!(explicit.batches[0].segments.len(), 1); assert_eq!(explicit.batches[0].transforms.len(), 1); assert!(explicit.batches[0].controls.is_none()); assert!(explicit.batches[0].local_views.is_none()); assert_eq!(conditional.batches.len(), 1, "selected type-5 batch"); let batch = &conditional.batches[0]; assert_eq!(batch.segments.len(), 1); assert_eq!(batch.controls.as_ref().expect("type-5 controls").len(), 1); assert_eq!( batch .local_views .as_ref() .expect("per-instance local view") .len(), 1 ); assert_eq!(batch.transforms.len(), 1); assert_eq!(batch.ribbon_width, BASE_RIBBON_WIDTH_PIXELS); assert_eq!(conditional.stats.instance_count, 1); assert_eq!(conditional.stats.material_groups, 1); } #[cfg(not(target_arch = "wasm32"))] #[test] fn selected_production_inputs_isolate_repeated_logical_occurrences_and_rc_cache_identity() { let mut scene = picker_scene(); scene.geometries[0].lines = vec![[0, 1]].into(); scene.occurrences[0].logical_part_occurrence_id = Some("instance-a".into()); scene.occurrences[1].logical_part_occurrence_id = Some("instance-b".into()); scene.occurrences[0].canonical_occurrence_id = "root/instance-a".into(); scene.occurrences[1].canonical_occurrence_id = "root/instance-b".into(); scene.occurrences[0].transform[3][0] = 12.0; scene.occurrences[1].transform[3][0] = -12.0; let plan = scene_render_plan(&scene).expect("render plan"); let picker = ScenePicker::new(&scene, plan.clone()).expect("picker"); let first = picker.selection(0).expect("first logical selection"); let second = picker.selection(1).expect("second logical selection"); assert_eq!(first.occurrence_indices, vec![0]); assert_eq!(second.occurrence_indices, vec![1]); assert_eq!(first.canonical_occurrence_id, "root/instance-a"); assert_eq!(second.canonical_occurrence_id, "root/instance-b"); assert_eq!(first.transforms[0][3][0], 12.0); assert_eq!(second.transforms[0][3][0], -12.0); assert_eq!( picker.planned_occurrences().as_ptr(), plan.planned_occurrences.as_ptr() ); assert_eq!(picker.edge_sources().as_ptr(), plan.edge_sources.as_ptr()); assert_eq!(picker.topologies.as_ptr(), plan.topologies.as_ptr()); let (first_edges, _) = compact_edge_inputs_for_membership( &scene, &plan, [0.0, 0.0, 1.0], Some(&first.occurrence_indices), ) .expect("first selected subtree"); let (second_edges, _) = compact_edge_inputs_for_membership( &scene, &plan, [0.0, 0.0, 1.0], Some(&second.occurrence_indices), ) .expect("second selected subtree"); assert_eq!(first_edges.batches[0].transforms.len(), 1); assert_eq!(second_edges.batches[0].transforms.len(), 1); assert_eq!(first_edges.batches[0].transforms[0].w.x, 12.0); assert_eq!(second_edges.batches[0].transforms[0].w.x, -12.0); } #[cfg(not(target_arch = "wasm32"))] #[test] fn native_selection_slots_clear_every_lifecycle_and_reject_stale_conditional_refresh() { let mut scene = picker_scene(); scene.geometries[0].lines = vec![[0, 1]].into(); let plan = scene_render_plan(&scene).expect("render plan"); let identity = ScenePicker::new(&scene, plan) .expect("picker") .selection(0) .expect("selection"); let mut slots = NativeSelectionSlots::default(); slots.install( identity.clone(), ( Some(Vec::new()), Some(Vec::new()), Some(SelectionFallback::BoundingBox( SceneBounds::from_points([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]).unwrap(), )), ), ); assert_eq!(slots.live_renderable_count(), 1); let generation = slots.generation; assert!(slots.refilter_conditional(generation, None)); assert_eq!(slots.conditional_generation, 2); assert!(!slots.refilter_conditional(generation.wrapping_sub(1), Some(Vec::new()))); slots.clear(); assert!(slots.identity.is_none()); assert!(slots.explicit.is_none()); assert!(slots.conditional.is_none()); assert!(slots.fallback.is_none()); assert_eq!(slots.live_renderable_count(), 0); assert!(!slots.refilter_conditional(generation, Some(Vec::new()))); slots.install(identity, (None, None, None)); assert_eq!(slots.live_renderable_count(), 0); } #[cfg(not(target_arch = "wasm32"))] #[test] fn selected_edge_less_build_reports_only_tagged_fallback_without_edge_success() { let scene = picker_scene(); let plan = scene_render_plan(&scene).expect("render plan"); let picker = ScenePicker::new(&scene, plan.clone()).expect("picker"); let selection = picker.selection(0).expect("selection"); let (explicit, conditional) = compact_edge_inputs_for_membership( &scene, &plan, [0.0, 0.0, 1.0], Some(&selection.occurrence_indices), ) .expect("selected edge inputs"); assert!(explicit.batches.is_empty()); assert!(conditional.batches.is_empty()); assert!(selection_fallback(true, selection.bounds).is_some()); assert!(selection_fallback(false, selection.bounds).is_none()); } #[cfg(not(target_arch = "wasm32"))] #[test] fn selected_material_and_ribbon_width_are_separate_from_base_material() { let base = compact_segment_material(4, false); let selected = compact_segment_material(4, true); assert_ne!(base.color, selected.color); assert_ne!(base.material_type(), selected.material_type()); assert!(compact_segment_vertex_shader(BASE_RIBBON_WIDTH_PIXELS).contains("1.5000000")); assert!(compact_segment_vertex_shader(SELECTED_RIBBON_WIDTH_PIXELS).contains("3.0000000")); } #[cfg(not(target_arch = "wasm32"))] #[test] fn explicit_segment_cardinality_is_stable_across_orbit_views() { let mut scene = picker_scene(); scene.geometries[0].lines = vec![[0, 1]].into(); let plan = scene_render_plan(&scene).expect("render plan"); let before = plan.clone(); let first = edge_build_stats(&scene, &plan, [0.0, 0.0, 1.0]).expect("front edge stats"); let second = edge_build_stats(&scene, &plan, [0.0, 1.0, 0.0]).expect("side edge stats"); assert_eq!(plan, before); assert_eq!(first.generated_vertices, second.generated_vertices); assert_eq!(first.generated_indices, 0); assert_eq!(first.source_segment_vertices, 6); assert_eq!(first.instance_count, 2); } #[cfg(not(target_arch = "wasm32"))] #[test] fn edge_build_filters_conditional_segments_but_keeps_explicit_segments() { let mut scene = picker_scene(); scene.geometries[0].lines = vec![[0, 1]].into(); scene.geometries[0].conditional_lines = vec![[0, 1, 2, 1]].into(); let plan = scene_render_plan(&scene).expect("render plan"); let front = edge_build_stats(&scene, &plan, [0.0, 0.0, 1.0]).expect("front stats"); let back = edge_build_stats(&scene, &plan, [0.0, 0.0, -1.0]).expect("back stats"); assert_eq!(front.explicit_segments, 2); assert_eq!(back.explicit_segments, 2); assert_eq!(front.visible_conditional_segments, 2); assert_eq!(back.visible_conditional_segments, 2); } #[cfg(not(target_arch = "wasm32"))] #[test] fn render_plan_owns_authoritative_edge_sources_without_changing_face_batches() { assert_eq!(RenderStyle::default(), RenderStyle::Faces); let mut scene = picker_scene(); scene.geometries[0].lines = vec![[0, 1]].into(); scene.geometries[0].conditional_lines = vec![[0, 1, 2, 1]].into(); let plan = scene_render_plan(&scene).expect("render plan"); assert_eq!(plan.planned_occurrences.len(), scene.occurrences.len()); assert!( plan.edge_sources .iter() .all(|source| source.explicit.len() == 1) ); assert!( plan.edge_sources .iter() .all(|source| source.conditional.len() == 1) ); assert_eq!(plan.batches.len(), 1); assert_eq!( plan.upload_batch_indices, [0].into_iter().collect::>() ); assert_eq!( plan.planned_to_upload, [Some(0)].into_iter().collect::]>>() ); assert_eq!(plan.occurrence_ranges.len(), scene.occurrences.len()); assert!(plan.occurrence_ranges.iter().all(Option::is_some)); assert_eq!(plan.topologies.len(), scene.geometries.len()); assert_eq!(plan.topologies[0].triangle_count(), 1); } #[test] fn ldraw_basis_preserves_winding_and_has_positive_determinant() { assert_eq!(ldraw_to_world([1.0, 2.0, 3.0]), [1.0, 3.0, -2.0]); assert_eq!(basis_determinant(), 1.0); } #[test] fn conditional_line_rule_is_deterministic() { let edge = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]; let same_side_controls = [[0.0, 1.0, 0.0], [1.0, 1.0, 0.0]]; assert!(conditional_line_visible( edge, same_side_controls, [0.0, 0.0, 1.0] )); assert!(conditional_line_visible( edge, same_side_controls, [0.0, 0.0, -1.0] )); let opposite_side_controls = [[0.0, 1.0, 0.0], [1.0, -1.0, 0.0]]; assert!(!conditional_line_visible( edge, opposite_side_controls, [0.0, 0.0, 1.0] )); } #[cfg(not(target_arch = "wasm32"))] #[test] fn nested_affine_scene_and_gpu_layout_transform_origin_and_basis_once() { use polymodel_ldraw_core::{Matrix3, Point3, Transform}; use three_d::Transform as _; let parent = Transform { translation: Point3::new(10.0, 20.0, 30.0), matrix: Matrix3 { row_x: Point3::new(0.0, -1.0, 0.0), row_y: Point3::new(1.0, 0.0, 0.0), row_z: Point3::new(0.0, 0.0, 1.0), }, }; let child = Transform { translation: Point3::new(2.0, 3.0, 4.0), matrix: Matrix3 { row_x: Point3::new(-1.0, 0.0, 0.0), row_y: Point3::new(0.0, 1.0, 0.0), row_z: Point3::new(0.0, 0.0, 1.0), }, }; let composed = parent .compose(&child) .expect("finite parent-child composition"); assert_eq!(composed.translation, Point3::new(7.0, 22.0, 34.0)); assert!(composed.reflection()); let scene = world_transform(composed).expect("finite world transform"); let source_points = [ Point3::new(0.0, 0.0, 0.0), Point3::new(1.0, 0.0, 0.0), Point3::new(0.0, 1.0, 0.0), Point3::new(0.0, 0.0, 1.0), Point3::new(2.0, -3.0, 5.0), ]; let world_points = source_points.map(|source| { let expected_source = composed.apply(source).expect("source transform"); ldraw_to_world([expected_source.x, expected_source.y, expected_source.z]) }); assert_eq!(world_points[0], [7.0, 34.0, -22.0]); assert_eq!(world_points[1], [7.0, 34.0, -21.0]); assert_eq!(world_points[2], [6.0, 34.0, -22.0]); assert_eq!(world_points[3], [7.0, 35.0, -22.0]); let gpu = scene_transform_to_mat4(scene).expect("representable GPU transform"); for (source, expected) in source_points.into_iter().zip(world_points) { let world_source = ldraw_to_world([source.x, source.y, source.z]); let cpu = apply_scene_transform(scene, world_source).expect("scene CPU transform"); assert_eq!(cpu, expected); let gpu_point = gpu.transform_point(three_d::Point3::new( world_source[0] as f32, world_source[1] as f32, world_source[2] as f32, )); for axis in 0..3 { assert!((gpu_point[axis] - expected[axis] as f32).abs() < 1.0e-5); } } } #[test] fn gpu_transform_rejects_finite_f64_outside_f32_range() { let mut transform = [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], ]; transform[0][3] = f32::MAX as f64 * 2.0; assert!(matches!( scene_transform_to_mat4(transform), Err(RendererError::NonFiniteTransform) )); } #[test] fn camera_case_contract_validates_and_serializes_stably() { let case = named_camera_case("identity_front").expect("named case"); assert_eq!(case.schema_version, CAMERA_CASE_SCHEMA); assert_eq!( case.encoded_json().unwrap(), serde_json::to_string(&case).unwrap() ); assert_eq!(case.width, 2560); assert_eq!(case.height, 1440); let mut invalid = case.clone(); invalid.width = 0; assert_eq!(invalid.validate(), Err(CameraCaseError::ZeroViewport)); invalid.width = 2560; invalid.schema_version = "pm-camera-case-v0".into(); assert!(matches!( invalid.validate(), Err(CameraCaseError::UnknownSchema(_)) )); invalid.schema_version = CAMERA_CASE_SCHEMA.into(); invalid.fov_degrees = 180.0; assert_eq!(invalid.validate(), Err(CameraCaseError::InvalidFov)); } #[test] fn named_cases_and_variants_are_explicit_and_distinct() { let front = named_camera_case("identity_front").unwrap(); let back = named_camera_case("identity_back").unwrap(); assert_ne!(front.yaw_degrees, back.yaw_degrees); let identity = SceneVariantBinding::for_case("identity_front").unwrap(); let reflected = SceneVariantBinding::for_case("reflected_front").unwrap(); assert_eq!(identity.determinant, 1); assert_eq!(reflected.determinant, -1); assert_ne!(identity.occurrence_id, reflected.occurrence_id); assert_ne!(identity.occurrence_index, reflected.occurrence_index); } #[test] fn fixture_hash_and_required_metadata_are_stable() { assert!(PM90_FIXTURE.windows(2).any(|bytes| bytes == b"4 ")); assert!(PM90_FIXTURE.windows(3).any(|bytes| bytes == b"14 ")); assert!( PM90_FIXTURE .windows(b"BFC INVERTNEXT".len()) .any(|bytes| bytes == b"BFC INVERTNEXT") ); assert_eq!( pm90_fixture_hash(), "ab11c535b8676694e166ace527a1602d6c25897e7b06aac28717aeb3321d1a55" ); } #[test] fn ldraw_black_material_is_readable_but_remains_black() { let policy = LdrawLightingMaterialPolicy::ldraw(); let black = policy.black_albedo; let dark_grey = [109_u8, 110, 108]; let black_luminance = u16::from(black[0]) + u16::from(black[1]) + u16::from(black[2]); let dark_grey_luminance = u16::from(dark_grey[0]) + u16::from(dark_grey[1]) + u16::from(dark_grey[2]); assert!(black.iter().all(|channel| *channel > 0)); assert!(black_luminance < dark_grey_luminance); assert_eq!(policy.metallic, 0.0); assert!(policy.black_roughness > policy.roughness); assert_eq!( ldraw_colour_with_policy([0, 0, 0], policy, u8::MAX), three_d::Srgba::new_opaque(28, 38, 40) ); assert_eq!( ldraw_colour([0, 0, 0]), ldraw_colour_with_policy([0, 0, 0], policy, u8::MAX) ); assert_eq!( ldraw_colour_with_policy([12, 34, 56], policy, 128), three_d::Srgba::new(12, 34, 56, 128) ); } #[test] fn ldraw_policy_matches_three_d_direction_and_material_contract() { let policy = LdrawLightingMaterialPolicy::ldraw(); assert_eq!(policy.version, LdrawLightingMaterialPolicy::VERSION); assert_eq!(policy.ambient_energy, 0.45); assert_eq!(policy.ambient_colour, [255, 255, 255]); assert_eq!(policy.key_energy, 2.6); assert_eq!(policy.key_colour, [255, 255, 255]); assert_eq!(policy.key_direction, [-0.45, -0.55, -0.70]); assert_eq!(policy.fill_energy, 0.8); assert_eq!(policy.fill_colour, [210, 225, 255]); assert_eq!(policy.fill_direction, [0.55, 0.35, -0.30]); assert!(policy.albedo_is_direct_colour); assert_eq!(policy.roughness, 0.72); assert_eq!(policy.metallic, 0.0); assert!(policy.cull_back_faces); assert!(policy.depth_test); assert!(policy.depth_write); assert!(!policy.alpha_blend); } // This is a white-box policy assertion, not a visual regression test. #[test] fn seeded_ldconfig_red_is_not_the_grey_material_fallback() { let bytes = b"0 !COLOUR Red CODE 4 VALUE #C91A09 EDGE #212121\n3 4 0 0 0 10 0 0 0 10 0\n"; let mut sink = AdapterSink::new(None); let parsed = polymodel_ldraw_core::InProcessRustAdapter::parse_with_limits_and_sink( polymodel_ldraw_core::AdapterRequest { bytes, profile: polymodel_ldraw_core::ParserProfile::Strict, provenance_id: "seeded-ldconfig-red", root_name: "seeded-ldconfig-red", root: polymodel_ldraw_core::RootId::CurrentMpd, materializations: &[], target_selections: &[], cancellation: polymodel_ldraw_core::CancellationPolicy::default(), }, polymodel_ldraw_core::LdrawLimits::default(), &mut sink, ) .expect("seeded LDConfig colour should parse"); sink.take_error().expect("seeded geometry should adapt"); let scene = adapt_ldraw_parse_result(&parsed, None, sink).expect("seeded colour should adapt"); assert_eq!(parsed.result.scene.triangles, 1); assert_eq!(parsed.result.scene.quads, 0); assert_eq!(parsed.result.scene.lines, 0); assert_eq!(parsed.result.scene.conditional_lines, 0); assert_eq!(scene.stats.triangles, 1); assert_eq!(scene.stats.lines, 0); assert_eq!(scene.stats.points, 3); assert_eq!(scene.stats.occurrences, 1); assert_eq!(scene.provenance.len(), 1); assert_eq!(scene.provenance[0].id, ProvenanceId(1)); assert_eq!(scene.provenance[0].source, "seeded-ldconfig-red"); assert_eq!(scene.occurrences.len(), 1); assert_eq!(scene.geometries[0].provenance, ProvenanceId(1)); assert_eq!(scene.occurrences[0].source, "seeded-ldconfig-red"); assert_eq!(scene.occurrences[0].target, "seeded-ldconfig-red"); let material = scene.materials.first().expect("seeded code-4 material"); assert_eq!(material.colour, 4); assert_eq!(material.colour_rgb, Some([201, 26, 9])); let resolved = material .colour_rgb .or_else(|| fallback_colour_rgb(material.colour)) .unwrap_or([160, 165, 169]); assert_eq!(resolved, [201, 26, 9]); assert_ne!(resolved, [160, 165, 169]); } #[cfg(target_arch = "wasm32")] mod worker_policy_tests { use super::LdrawLightingMaterialPolicy; #[test] fn worker_target_uses_shared_ldraw_policy() { let policy = LdrawLightingMaterialPolicy::ldraw(); assert_eq!(policy.version, "pm-ldraw-lighting-material-v1"); assert_eq!(policy.ambient_energy, 0.45); assert_eq!(policy.key_energy, 2.6); assert_eq!(policy.fill_energy, 0.8); assert_eq!(policy.key_direction, [-0.45, -0.55, -0.70]); assert_eq!(policy.fill_direction, [0.55, 0.35, -0.30]); assert_eq!(policy.fill_colour, [210, 225, 255]); assert_eq!(policy.roughness, 0.72); assert_eq!(policy.metallic, 0.0); assert!(policy.albedo_is_direct_colour); assert!(policy.cull_back_faces && policy.depth_test && policy.depth_write); assert!(!policy.alpha_blend); } } #[cfg(not(target_arch = "wasm32"))] #[test] fn native_case_pose_changes_front_back_and_preserves_fit_defaults() { let bounds = SceneBounds { min: [-1.0, -1.0, -1.0], max: [1.0, 1.0, 1.0], }; let fit = scene_camera_fit(bounds, 2560, 1440).expect("valid fit"); let front = named_camera_case("identity_front") .unwrap() .native_pose(fit) .unwrap(); let back = named_camera_case("identity_back") .unwrap() .native_pose(fit) .unwrap(); assert_ne!(front.position, back.position); let default = NativeRenderOptions::default(); assert_eq!( (default.width, default.height, default.yaw_degrees), (1280, 720, 0.0) ); assert!(default.camera_case.is_none()); } #[cfg(not(target_arch = "wasm32"))] #[test] fn camera_fit_changes_aspect_sensitive_distance() { use three_d::InnerSpace as _; let bounds = SceneBounds { min: [-4.0, -1.0, -1.0], max: [4.0, 1.0, 1.0], }; let wide = scene_camera_fit(bounds, 1600, 400).expect("wide fit"); let tall = scene_camera_fit(bounds, 400, 1600).expect("tall fit"); assert_ne!(wide.position, tall.position); assert!((tall.position - tall.center).magnitude() > (wide.position - wide.center).magnitude()); } #[cfg(not(target_arch = "wasm32"))] #[test] fn native_camera_fit_contains_projected_corners_after_f32_conversion() { let bounds = SceneBounds { min: [-2_654.399_419_125, -742.736, -456.829_925], max: [-187.804_052_188, 742.725, 686.390_413], }; let fit = scene_camera_fit(bounds, 1280, 720).expect("valid fit"); assert!((fit.center.x + 1_421.101_7).abs() < 1.0e-3); assert!(fit.near > 0.0 && fit.far > fit.near && fit.control_min > 0.0); assert!(fit.control_min < (fit.position - fit.center).magnitude() * 0.02); assert_eq!(fit.control_max, fit.far); let projection = camera_space_clip_planes(bounds, fit.position, fit.center).expect("valid planes"); assert!(projection.near <= projection.min_depth || projection.min_depth <= 0.0); assert!(projection.far >= projection.max_depth); } #[test] fn clipping_raises_near_plane_for_close_positive_scene_without_precision_failure() { let bounds = SceneBounds { min: [-1.0, -1.0, -1.0], max: [1.0, 1.0, 1.0], }; let position = three_d::vec3(0.0, -1.0001, 0.0); let target = three_d::vec3(0.0, 0.0, 0.0); let projection = camera_space_clip_planes(bounds, position, target) .expect("close-up clipping should remain renderable"); assert!(projection.near > projection.min_depth); assert!( f64::from(projection.far) / f64::from(projection.near) <= CAMERA_DEPTH_RATIO_LIMIT * 1.001 ); } #[test] fn supplied_inside_pose_has_ordered_finite_planes_and_precision() { let bounds = SceneBounds { min: [-2654.399419125, -742.736, -456.829925], max: [-187.804052188, 742.725, 686.390413], }; let position = three_d::vec3(-1450.446, -512.09894, 419.3693); let target = three_d::vec3(-1421.1017, -0.0055232644, 73.33134); let projection = camera_space_clip_planes(bounds, position, target).expect("inside pose policy"); let oracle = camera_space_depth_interval(bounds, position, target).expect("inside oracle"); assert!(oracle.min_depth < 0.0 && oracle.max_depth > 0.0); assert!((f64::from(projection.min_depth) - oracle.min_depth).abs() < 0.01); assert!((f64::from(projection.max_depth) - oracle.max_depth).abs() < 0.01); assert!( projection.near.is_finite() && projection.far.is_finite() && projection.near > 0.0 && projection.far > projection.near ); assert!( f64::from(projection.far) / f64::from(projection.near) <= CAMERA_DEPTH_RATIO_LIMIT * 1.001 ); } #[test] fn clipping_rejects_invalid_inputs_and_equal_camera_pose() { let bounds = SceneBounds { min: [-10.0, -4.0, -2.0], max: [10.0, 4.0, 2.0], }; assert_eq!( camera_space_depth_interval( bounds, three_d::vec3(0.0, 0.0, 0.0), three_d::vec3(0.0, 0.0, 0.0) ), Err(CameraDepthError::InvalidCamera) ); assert_eq!( camera_space_depth_interval( SceneBounds { min: [f64::NAN, 0.0, 0.0], max: [1.0, 1.0, 1.0] }, three_d::vec3(0.0, -20.0, 0.0), three_d::vec3(0.0, 0.0, 0.0) ), Err(CameraDepthError::InvalidBounds) ); assert_eq!( camera_space_depth_interval( SceneBounds { min: [1.0, 1.0, 1.0], max: [-1.0, 1.0, 1.0] }, three_d::vec3(0.0, -20.0, 0.0), three_d::vec3(0.0, 0.0, 0.0) ), Err(CameraDepthError::InvalidBounds) ); assert_eq!( scene_camera_fit(bounds, 0, 720), Err(CameraDepthError::InvalidBounds) ); assert_eq!( camera_clip_planes(10.0, f32::NAN), Err(CameraDepthError::InvalidCamera) ); } #[test] fn finite_zero_volume_bounds_have_explicit_policy() { let bounds = SceneBounds { min: [0.0, 0.0, 0.0], max: [0.0, 0.0, 0.0], }; let interval = camera_space_depth_interval( bounds, three_d::vec3(0.0, -10.0, 0.0), three_d::vec3(0.0, 0.0, 0.0), ) .expect("finite degenerate interval"); assert_eq!(interval.min_depth, interval.max_depth); let planes = camera_space_clip_planes( bounds, three_d::vec3(0.0, -10.0, 0.0), three_d::vec3(0.0, 0.0, 0.0), ) .expect("degenerate scene policy"); assert!(planes.near > 0.0 && planes.far > planes.near); } #[test] fn ldraw_occurrence_transform_is_conjugated_and_bounds_use_instances() { use polymodel_ldraw_core::{CacheKey, LineType, ModelSummary, NormalizedPath}; let root_path = NormalizedPath::new("root.ldr").unwrap(); let child_path = NormalizedPath::new("parts/child.dat").unwrap(); let root_key = CacheKey::new(root_path, polymodel_ldraw_core::RootId::CurrentMpd, b"root"); let child_key = CacheKey::new( child_path.clone(), polymodel_ldraw_core::RootId::OfficialLibrary, b"child-a", ); let child_geometry = polymodel_ldraw_core::GeometryRecord { primitive_id: 1, source: child_key.clone(), span: polymodel_ldraw_core::Span { start: 0, end: 0, line: 1, column: 1, }, line_type: LineType::Three, colour: polymodel_ldraw_core::ColourCode(4), vertices: vec![ polymodel_ldraw_core::Point3::new(0.0, 0.0, 0.0), polymodel_ldraw_core::Point3::new(1.0, 0.0, 0.0), polymodel_ldraw_core::Point3::new(0.0, 1.0, 0.0), ], texmap: None, inverted: false, bfc: polymodel_ldraw_core::BfcFrame { state: polymodel_ldraw_core::BfcState::Certified, clipping: true, winding: polymodel_ldraw_core::Winding::Ccw, invert_next: false, }, }; let mut child = ModelSummary { model: polymodel_ldraw_core::ModelId(579), id: "child".into(), path: child_path.as_str().into(), cache_key: child_key.clone(), depth: 1, include_spans: Vec::new(), includes: Vec::new(), triangles: 1, quads: 0, lines: 0, conditional_lines: 0, step_ends: Vec::new(), bfc: polymodel_ldraw_core::BfcState::Certified, }; let root = ModelSummary { model: polymodel_ldraw_core::ModelId(1), id: "root".into(), path: "root.ldr".into(), cache_key: root_key, depth: 0, include_spans: Vec::new(), includes: vec![child_path.as_str().into()], triangles: 0, quads: 0, lines: 0, conditional_lines: 0, step_ends: Vec::new(), bfc: polymodel_ldraw_core::BfcState::Unknown, }; let mut clockwise = child_geometry.clone(); clockwise.bfc.clipping = false; clockwise.bfc.winding = polymodel_ldraw_core::Winding::Cw; clockwise.inverted = true; let mut edge = child_geometry.clone(); edge.line_type = LineType::Two; edge.colour = polymodel_ldraw_core::ColourCode(24); edge.vertices.truncate(2); child.triangles = 2; child.lines = 1; let mut fixture_events = std::collections::HashMap::new(); fixture_events.insert(child_key.clone(), vec![child_geometry, clockwise, edge]); let transform = polymodel_ldraw_core::Transform { translation: polymodel_ldraw_core::Point3::new(10.0, 20.0, 30.0), matrix: polymodel_ldraw_core::Matrix3 { row_x: polymodel_ldraw_core::Point3::new(0.0, -1.0, 0.0), row_y: polymodel_ldraw_core::Point3::new(1.0, 0.0, 0.0), row_z: polymodel_ldraw_core::Point3::new(0.0, 0.0, 1.0), }, }; let parsed_scene = polymodel_ldraw_core::SceneRecord { model_id: "root".into(), instance_ids: vec!["instance-00000001".into()], instances: vec![polymodel_ldraw_core::InstanceRecord { model: polymodel_ldraw_core::ModelId(579), instance_id: "instance-00000001".into(), parent: None, source_model: "root.ldr".into(), target_model: child.path.clone(), source_span: None, target_key: Some(child_key), transform, inverted: false, bfc: None, direct_colour: Some(polymodel_ldraw_core::ColourCode(4)), colour: Some(polymodel_ldraw_core::ColourCode(4)), texmap_state: None, texmap_reference: None, texmap: None, }], triangles: 1, quads: 0, lines: 0, conditional_lines: 0, bounds: None, reflection: false, }; let mut sink = AdapterSink::new(None); sink.current_model = Some(child.cache_key.clone()); sink.current_provenance = Some(ProvenanceId(1)); sink.provenance .push(polymodel_renderer_protocol::scene::SceneProvenance { id: ProvenanceId(1), source: child.path.clone(), span: None, }); for primitive in fixture_events.get(&child.cache_key).unwrap() { let _ = sink.emit_geometry( primitive.colour, primitive.vertices.as_slice(), primitive.line_type, primitive.bfc, primitive.texmap.as_ref(), primitive.inverted, ); } sink.take_error().unwrap(); let scene = adapt_ldraw_assembly_with_sink(&[root, child], Some(&parsed_scene), None, None, Some(sink)) .unwrap(); let child_geometry = scene .geometries .iter() .find(|geometry| geometry.triangles.len() == 1) .expect("child triangle geometry"); assert_eq!(scene.occurrences[0].node.0, child_geometry.id.0); assert_eq!(scene.occurrences[0].transform[3], [10.0, 30.0, -20.0, 1.0]); assert_eq!(scene.bounds.unwrap().min, [9.0, 30.0, -21.0]); assert_eq!(scene.bounds.unwrap().max, [10.0, 30.0, -20.0]); assert_eq!(scene.occurrences.len(), 3); assert!(scene.geometries.iter().any(|geometry| { geometry .primitives .iter() .any(|primitive| primitive.bfc_cull && primitive.bfc_ccw && !primitive.bfc_inverted) })); assert!(scene.geometries.iter().any(|geometry| { geometry .primitives .iter() .any(|primitive| !primitive.bfc_cull && !primitive.bfc_ccw && primitive.bfc_inverted) })); assert!( scene .occurrences .iter() .any(|occurrence| occurrence.bfc_ccw) ); assert!( scene .occurrences .iter() .any(|occurrence| !occurrence.bfc_ccw) ); let edge_occurrence = scene .occurrences .iter() .find(|occurrence| occurrence.primitive_colour == 24) .expect("colour-24 edge occurrence"); let edge_geometry = scene .geometries .iter() .find(|geometry| geometry.id.0 == edge_occurrence.node.0) .expect("edge geometry"); assert_eq!(edge_geometry.lines.len(), 1); assert_eq!(scene.stats.triangles, 2); assert_eq!(scene.stats.lines, 1); } #[test] fn ldraw_repeated_same_path_instances_keep_exact_definition_keys() { use polymodel_ldraw_core::{CacheKey, LineType, ModelSummary, NormalizedPath}; let root_key = CacheKey::new( NormalizedPath::new("root.ldr").unwrap(), polymodel_ldraw_core::RootId::CurrentMpd, b"root", ); let shared_path = NormalizedPath::new("parts/shared.dat").unwrap(); let child_a_key = CacheKey::new( shared_path.clone(), polymodel_ldraw_core::RootId::OfficialLibrary, b"a", ); let child_b_key = CacheKey::new( shared_path.clone(), polymodel_ldraw_core::RootId::OfficialLibrary, b"b", ); let child = |model: polymodel_ldraw_core::ModelId, id: &str, key: polymodel_ldraw_core::CacheKey| ModelSummary { model, id: id.into(), path: shared_path.as_str().into(), cache_key: key.clone(), depth: 1, include_spans: Vec::new(), includes: Vec::new(), triangles: 1, quads: 0, lines: 0, conditional_lines: 0, step_ends: Vec::new(), bfc: polymodel_ldraw_core::BfcState::Certified, }; let root = ModelSummary { model: polymodel_ldraw_core::ModelId(1), id: "root".into(), path: "root.ldr".into(), cache_key: root_key, depth: 0, include_spans: Vec::new(), includes: Vec::new(), triangles: 0, quads: 0, lines: 0, conditional_lines: 0, step_ends: Vec::new(), bfc: polymodel_ldraw_core::BfcState::Unknown, }; let transform = polymodel_ldraw_core::Transform::default(); let instance = |model: polymodel_ldraw_core::ModelId, id: &str, key: polymodel_ldraw_core::CacheKey| { polymodel_ldraw_core::InstanceRecord { model, instance_id: id.into(), parent: None, source_model: "root.ldr".into(), target_model: shared_path.as_str().into(), source_span: None, target_key: Some(key), transform, inverted: false, bfc: None, direct_colour: Some(polymodel_ldraw_core::ColourCode(4)), colour: Some(polymodel_ldraw_core::ColourCode(4)), texmap_state: None, texmap_reference: None, texmap: None, } }; let fixture_primitive = || polymodel_ldraw_core::GeometryRecord { primitive_id: 1, source: child_a_key.clone(), span: polymodel_ldraw_core::Span { start: 0, end: 0, line: 1, column: 1, }, line_type: LineType::Three, colour: polymodel_ldraw_core::ColourCode(4), vertices: vec![ polymodel_ldraw_core::Point3::new(0.0, 0.0, 0.0), polymodel_ldraw_core::Point3::new(1.0, 0.0, 0.0), polymodel_ldraw_core::Point3::new(0.0, 1.0, 0.0), ], texmap: None, inverted: false, bfc: polymodel_ldraw_core::BfcFrame { state: polymodel_ldraw_core::BfcState::Certified, clipping: true, winding: polymodel_ldraw_core::Winding::Ccw, invert_next: false, }, }; let parsed_scene = polymodel_ldraw_core::SceneRecord { model_id: "root".into(), instance_ids: vec!["a".into(), "b".into()], instances: vec![ instance(polymodel_ldraw_core::ModelId(2), "a", child_a_key.clone()), instance(polymodel_ldraw_core::ModelId(3), "b", child_b_key.clone()), ], triangles: 2, quads: 0, lines: 0, conditional_lines: 0, bounds: None, reflection: false, }; let child_a = child(polymodel_ldraw_core::ModelId(2), "a", child_a_key.clone()); let child_b = child(polymodel_ldraw_core::ModelId(3), "b", child_b_key.clone()); let mut sink = AdapterSink::new(None); for child in [&child_a, &child_b] { sink.current_model = Some(child.cache_key.clone()); sink.current_provenance = Some(ProvenanceId((sink.provenance.len() + 1) as u64)); sink.provenance .push(polymodel_renderer_protocol::scene::SceneProvenance { id: sink.current_provenance.unwrap(), source: child.path.clone(), span: None, }); let primitive = fixture_primitive(); let _ = sink.emit_geometry( primitive.colour, primitive.vertices.as_slice(), primitive.line_type, primitive.bfc, primitive.texmap.as_ref(), primitive.inverted, ); } sink.take_error().unwrap(); let scene = adapt_ldraw_assembly_with_sink( &[root, child_a, child_b], Some(&parsed_scene), None, None, Some(sink), ) .unwrap(); assert_eq!(scene.occurrences.len(), 2); assert_ne!(scene.occurrences[0].node, scene.occurrences[1].node); assert_eq!(scene.stats.triangles, 2); assert!(scene.bounds.is_some()); } #[cfg(not(target_arch = "wasm32"))] #[test] fn native_trace_preserves_stage_order() { let trace = NativeTrace::default(); let expected = [ NativeStage::Started, NativeStage::LibraryResolved, NativeStage::OmrParsed, NativeStage::SceneAdapted, NativeStage::WindowCreated, NativeStage::ContextCreated, NativeStage::GpuResourcesCreated, NativeStage::FrameCallbackEntered, NativeStage::DrawCompleted, NativeStage::ReadbackCompleted, NativeStage::OutputWritten, ]; for stage in expected { trace.record(stage); } assert_eq!(trace.snapshot().stages, expected); } #[cfg(not(target_arch = "wasm32"))] #[test] fn native_trace_records_window_before_preparation_and_monotonic_time() { let trace = NativeTrace::default(); for stage in [ NativeStage::ProcessStarted, NativeStage::WindowCreated, NativeStage::PreparationStarted, NativeStage::PreparationComplete, NativeStage::SceneInstalled, NativeStage::Rendered, ] { trace.record(stage); } let snapshot = trace.snapshot(); let window_index = snapshot .stages .iter() .position(|stage| *stage == NativeStage::WindowCreated) .unwrap(); let complete_index = snapshot .stages .iter() .position(|stage| *stage == NativeStage::PreparationComplete) .unwrap(); assert!(window_index < complete_index); assert!( snapshot .records .windows(2) .all(|records| records[0].elapsed_ms <= records[1].elapsed_ms) ); } #[cfg(not(target_arch = "wasm32"))] #[test] fn native_trace_propagates_terminal_failure() { let trace = NativeTrace::default(); trace.record(NativeStage::ContextCreated); trace.finish(NativeTerminal::Failure("shader upload failed".into())); assert_eq!( trace.snapshot().terminal, Some(NativeTerminal::Failure("shader upload failed".into())) ); } #[cfg(not(target_arch = "wasm32"))] #[test] fn native_trace_timeout_contains_last_stage_and_gl_context() { let trace = NativeTrace::default(); trace.record(NativeStage::ContextCreated); trace.timeout("deadline exceeded"); let Some(NativeTerminal::Timeout(message)) = trace.snapshot().terminal else { panic!("expected timeout terminal"); }; assert!(message.contains("last_stage=ContextCreated")); assert!(message.contains("gl_vendor=")); assert!(message.contains("gl_renderer=")); assert!(message.contains("gl_version=")); }