From 85bce11eb2a2a96f516541c3de49031e337dd4eb Mon Sep 17 00:00:00 2001 From: clover caruso Date: Mon, 30 Nov 2026 23:18:50 -0800 Subject: [PATCH] Fix TextPlus landscape aspect scaling and 3D shadows/archive parity (#46) --- crates/engine/src/eval/text_3d.rs | 10 +- crates/engine/src/scene3d/collect.rs | 209 +++++++++++------- crates/engine/src/scene3d/mod.rs | 302 ++++++++++++++++++++++++++- crates/engine/src/scene3d/shader.rs | 101 ++++++++- crates/engine/src/text_engine.rs | 40 ++++ 5 files changed, 573 insertions(+), 89 deletions(-) diff --git a/crates/engine/src/eval/text_3d.rs b/crates/engine/src/eval/text_3d.rs index a7a040ca8294d64ed6fe25ffd9d4670c6a68c976..66c4067aed32d60405218a5d985bc5da86dd3f50 100644 --- a/crates/engine/src/eval/text_3d.rs +++ b/crates/engine/src/eval/text_3d.rs @@ -514,7 +514,12 @@ impl Engine { return empty; }; - let lighting_enabled = comp.eval_number(node, "RendererSoftware.LightingEnabled", time, 0.0, &self.expr) > 0.5; + // Only the active renderer's lighting toggle counts; Fusion's default renderer is software. + let renderer = node.static_str("RendererType").unwrap_or("RendererSoftware"); + let lighting_enabled = comp.eval_number(node, &format!("{renderer}.LightingEnabled"), time, 0.0, &self.expr) > 0.5; + // Only the OpenGL renderer shades shadows. + let shadows_enabled = renderer == "RendererOpenGL" + && comp.eval_number(node, "RendererOpenGL.ShadowsEnabled", time, 0.0, &self.expr) > 0.5; let mut cameras = Vec::new(); let mut mesh_specs = Vec::new(); let mut lights = crate::scene3d::SceneLights::default(); @@ -549,6 +554,7 @@ impl Engine { let mut hash_floats = Vec::with_capacity(28 + mesh_specs.len() * 20); hash_floats.extend_from_slice(&view_proj); hash_floats.push(if lighting_enabled { 1.0 } else { 0.0 }); + hash_floats.push(if shadows_enabled { 1.0 } else { 0.0 }); hash_floats.extend_from_slice(&lights.ambient); for dl in &lights.dirs { hash_floats.extend_from_slice(&dl.to_light); @@ -559,6 +565,7 @@ impl Engine { hash_floats.extend_from_slice(&pl.color); hash_floats.push(pl.decay_type); hash_floats.push(pl.decay_rate); + hash_floats.push(pl.shadow_density.unwrap_or(-1.0)); } for sl in &lights.spots { hash_floats.extend_from_slice(&sl.pos); @@ -665,6 +672,7 @@ impl Engine { cam_pos, lights, lighting_enabled, + shadows_enabled, &draw_meshes, ); self.cache.insert(key, dst.clone(), node.id, frame_i); diff --git a/crates/engine/src/scene3d/collect.rs b/crates/engine/src/scene3d/collect.rs index 5e646de9d4ff0f93aa1c8addce6c6410c645f657..1c82ef2c53b8c5ffd019733025fcae56e9b44295 100644 --- a/crates/engine/src/scene3d/collect.rs +++ b/crates/engine/src/scene3d/collect.rs @@ -257,53 +257,74 @@ fn collect_scene_inner( let near = comp.eval_number(node, "PlaneOfFocus", time, 0.05, expr).min(0.05).max(0.005) as f32; let far = 5000.0_f32; cameras.push(CameraInstance { world, vfov_rad, near, far }); + if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { + collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); + } } "LightAmbient" => { - let Some(color) = light_color(comp, node, time, expr) else { return }; - for (acc, c) in lights.ambient.iter_mut().zip(color) { - *acc += c; + if let Some(color) = light_color(comp, node, time, expr) { + for (acc, c) in lights.ambient.iter_mut().zip(color) { + *acc += c; + } + } + if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { + collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); } } "LightDirectional" => { - let Some(color) = light_color(comp, node, time, expr) else { return }; - // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation! - let dx = world[8]; - let dy = world[9]; - let dz = world[10]; - let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5); - lights.dirs.push(DirLight { to_light: [dx / len, dy / len, dz / len], color }); + if let Some(color) = light_color(comp, node, time, expr) { + // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation! + let dx = world[8]; + let dy = world[9]; + let dz = world[10]; + let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5); + lights.dirs.push(DirLight { to_light: [dx / len, dy / len, dz / len], color }); + } + if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { + collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); + } } "LightPoint" => { - let Some(color) = light_color(comp, node, time, expr) else { return }; - let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; - lights.points.push(PointLight { - pos: [world[12], world[13], world[14]], - color, - decay_type, - decay_rate: 1.0, - }); + if let Some(color) = light_color(comp, node, time, expr) { + let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; + lights.points.push(PointLight { + pos: [world[12], world[13], world[14]], + color, + decay_type, + decay_rate: 1.0, + shadow_density: (comp.eval_number(node, "ShadowLightInputs3D.ShadowsEnabled", time, 0.0, expr) > 0.5) + .then(|| comp.eval_number(node, "ShadowLightInputs3D.ShadowDensity", time, 0.5, expr).clamp(0.0, 1.0) as f32), + }); + } + if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { + collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); + } } "LightSpot" => { - let Some(color) = light_color(comp, node, time, expr) else { return }; - let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32; - let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32; - let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; - // SpotLight shines along -Z in local space - let dx = -world[8]; - let dy = -world[9]; - let dz = -world[10]; - let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5); - let half_cone = (cone_deg * 0.5).max(0.5); - let outer_deg = (half_cone + penumbra_deg.max(0.0)).min(89.5); - let inner_deg = (half_cone + penumbra_deg.min(0.0)).max(0.1).min(outer_deg); - lights.spots.push(SpotLight { - pos: [world[12], world[13], world[14]], - dir: [dx / len, dy / len, dz / len], - color, - cos_inner: inner_deg.to_radians().cos(), - cos_outer: outer_deg.to_radians().cos(), - decay_type, - }); + if let Some(color) = light_color(comp, node, time, expr) { + let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32; + let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32; + let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; + // SpotLight shines along -Z in local space + let dx = -world[8]; + let dy = -world[9]; + let dz = -world[10]; + let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5); + let half_cone = (cone_deg * 0.5).max(0.5); + let outer_deg = (half_cone + penumbra_deg.max(0.0)).min(89.5); + let inner_deg = (half_cone + penumbra_deg.min(0.0)).max(0.1).min(outer_deg); + lights.spots.push(SpotLight { + pos: [world[12], world[13], world[14]], + dir: [dx / len, dy / len, dz / len], + color, + cos_inner: inner_deg.to_radians().cos(), + cos_outer: outer_deg.to_radians().cos(), + decay_type, + }); + } + if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { + collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); + } } "ImagePlane3D" => { let Some(own) = surface_scope(comp, node, "SurfacePlaneInputs", ovr, time, expr) else { return }; @@ -316,48 +337,52 @@ fn collect_scene_inner( meshes.push(make_mesh_instance(world, ShapeKind::ImagePlane, mat, None, &own)); } "Shape3D" => { - let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs"); - let Some(own) = surface_scope(comp, node, shape_name, ovr, time, expr) else { return }; - let shape = match shape_name { - "SurfaceSphereInputs" => ShapeKind::Sphere { - // Fusion 21.1 Shape3D Sphere default Radius is 1.0 (verified via probe_moon_3d f00) - radius: comp.eval_number(node, "SurfaceSphereInputs.Radius", time, 1.0, expr) as f32, - sub_base: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32, - sub_height: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelHeight", time, 20.0, expr).round() as u32, - }, - "SurfaceCylinderInputs" => { - let start_sw = comp.eval_number(node, "SurfaceCylinderInputs.StartSweep", time, 0.0, expr) as f32; - let end_sw = comp.eval_number(node, "SurfaceCylinderInputs.EndSweep", time, 360.0, expr) as f32; - ShapeKind::Cylinder { - radius: comp.eval_number(node, "SurfaceCylinderInputs.Radius", time, 1.0, expr) as f32, - height: comp.eval_number(node, "SurfaceCylinderInputs.Height", time, 2.0, expr) as f32, - start_sweep_deg: start_sw, - end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw }, - sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32, + if let Some(own) = surface_scope(comp, node, node.static_str("Shape").unwrap_or("SurfacePlaneInputs"), ovr, time, expr) { + let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs"); + let shape = match shape_name { + "SurfaceSphereInputs" => ShapeKind::Sphere { + // Fusion 21.1 Shape3D Sphere default Radius is 1.0 (verified via probe_moon_3d f00) + radius: comp.eval_number(node, "SurfaceSphereInputs.Radius", time, 1.0, expr) as f32, + sub_base: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32, + sub_height: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelHeight", time, 20.0, expr).round() as u32, + }, + "SurfaceCylinderInputs" => { + let start_sw = comp.eval_number(node, "SurfaceCylinderInputs.StartSweep", time, 0.0, expr) as f32; + let end_sw = comp.eval_number(node, "SurfaceCylinderInputs.EndSweep", time, 360.0, expr) as f32; + ShapeKind::Cylinder { + radius: comp.eval_number(node, "SurfaceCylinderInputs.Radius", time, 1.0, expr) as f32, + height: comp.eval_number(node, "SurfaceCylinderInputs.Height", time, 2.0, expr) as f32, + start_sweep_deg: start_sw, + end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw }, + sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32, + } } + "SurfaceCubeInputs" => ShapeKind::Cube { + width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32, + sub: cube_subdivisions(comp, node, time, expr), + faces: 0b11_1111, + }, + _ => { + // Fusion's plane is square: Height and SubdivisionHeight follow Width. + let sub = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionWidth", time, 10.0, expr).round() as u32; + let width = comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32; + ShapeKind::Plane { width, height: width, sub_w: sub, sub_h: sub } + } + }; + let mat_node = ovr.material_override.or_else(|| { + node.connected_node("MaterialInput") + .and_then(|s| comp.find_node(s)) + }); + let mut mat = resolve_material(comp, mat_node, time, expr, visited); + if !mat.has_material_shader { + apply_mtl_std(&mut mat, comp, node, "", time, expr); } - "SurfaceCubeInputs" => ShapeKind::Cube { - width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32, - sub: cube_subdivisions(comp, node, time, expr), - faces: 0b11_1111, - }, - _ => { - // Fusion's plane is square: Height and SubdivisionHeight follow Width. - let sub = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionWidth", time, 10.0, expr).round() as u32; - let width = comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32; - ShapeKind::Plane { width, height: width, sub_w: sub, sub_h: sub } - } - }; - let mat_node = ovr.material_override.or_else(|| { - node.connected_node("MaterialInput") - .and_then(|s| comp.find_node(s)) - }); - let mut mat = resolve_material(comp, mat_node, time, expr, visited); - if mat_node.is_none() { - apply_mtl_std(&mut mat, comp, node, "", time, expr); + mat.fx.wireframe = comp.eval_number(node, &format!("{shape_name}.Wireframe"), time, 0.0, expr) > 0.5; + meshes.push(make_mesh_instance(world, shape, mat, None, &own)); + } + if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { + collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); } - mat.fx.wireframe = comp.eval_number(node, &format!("{shape_name}.Wireframe"), time, 0.0, expr) > 0.5; - meshes.push(make_mesh_instance(world, shape, mat, None, &own)); } "Cube3D" => { if let Some(own) = surface_scope(comp, node, "SurfaceCubeInputs", ovr, time, expr) { @@ -372,7 +397,7 @@ fn collect_scene_inner( .and_then(|s| comp.find_node(s)) }); let mut mat = resolve_material(comp, mat_node, time, expr, visited); - if mat_node.is_none() { + if !mat.has_material_shader { apply_mtl_std(&mut mat, comp, node, &format!("{face}."), time, expr); } mat.fx.wireframe = wireframe; @@ -410,7 +435,7 @@ fn collect_scene_inner( .and_then(|s| comp.find_node(s)) }); let mut mat = resolve_material(comp, mat_node, time, expr, visited); - if mat_node.is_none() { + if !mat.has_material_shader { apply_mtl_std(&mut mat, comp, node, "", time, expr); } meshes.push(make_mesh_instance(world, shape, mat, None, &own)); @@ -437,6 +462,9 @@ fn collect_scene_inner( slices: if ext_depth.abs() > 1e-4 { 8 } else { 1 }, }; meshes.push(make_mesh_instance(world, shape, mat, Some(Text3DSpec { node_id }), ovr)); + if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { + collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); + } } "MacroOperator" | "GroupOperator" => { if let Some(out_id) = node.macro_output { @@ -457,6 +485,9 @@ struct ResolvedMaterial { fx: MaterialFx, /// A bare texture operator used as a surface's material renders flat, ignoring lights. unlit: bool, + /// True when resolved from a shader material node (`MtlBlinn` / `MtlPhong` / `MtlCookTorrance`), + /// which owns diffuse/specular rather than inheriting the geometry node's `MtlStdInputs`. + has_material_shader: bool, } impl Default for ResolvedMaterial { @@ -469,6 +500,7 @@ impl Default for ResolvedMaterial { specular_exponent: 50.0, fx: MaterialFx::default(), unlit: false, + has_material_shader: false, } } } @@ -705,6 +737,7 @@ fn resolve_material_inner( specular_exponent: spec_exp, fx, unlit: false, + has_material_shader: true, } } _ => ResolvedMaterial { @@ -1268,4 +1301,22 @@ mod tests { assert!(inv.iter().all(|v| v.is_finite())); assert_eq!(mat4_inverse(mat4_translate(1.0, 2.0, 3.0)), mat4_translate(-1.0, -2.0, -3.0)); } + + #[test] + fn camera3d_passes_scene_input_and_cube3d_tints_textured_faces() { + let src = comp_src( + r#"Bg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, }, }, + Cube = Cube3D { Inputs = { + FrontMaterialInput = Input { SourceOp = "Bg", Source = "Output", }, + ["Front.MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 0.5, }, + ["Front.MtlStdInputs.Diffuse.Color.Blue"] = Input { Value = 0.0, }, + }, }, + Cam = Camera3D { Inputs = { SceneInput = Input { SourceOp = "Cube", Source = "Output", }, }, },"#, + ); + let (cams, meshes, _) = collect(&src, "Cam"); + assert_eq!(cams.len(), 1); + assert!(meshes.len() >= 2, "Camera3D must pass SceneInput Cube3D through"); + let front = meshes.iter().find(|m| matches!(m.shape.base_shape(), ShapeKind::Cube { faces: 1, .. })).unwrap(); + assert_eq!(front.diffuse_col, [1.0, 0.5, 0.0, 1.0]); + } } diff --git a/crates/engine/src/scene3d/mod.rs b/crates/engine/src/scene3d/mod.rs index 70ac908ccd588ff1d854515d895f2ceca16af4f9..13fe6a3c477b613dbd1a6679a07800823d8cc941 100644 --- a/crates/engine/src/scene3d/mod.rs +++ b/crates/engine/src/scene3d/mod.rs @@ -25,7 +25,7 @@ use std::sync::{Arc, Mutex}; use crate::cache::CachedTexture; use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges}; use model::NodeId; -use shader::{MeshUniform, MAX_DIR_LIGHTS, MAX_LIGHTS, SHADER_3D}; +use shader::{MeshUniform, ShadowUniform, MAX_DIR_LIGHTS, MAX_LIGHTS, MAX_SHADOW_LIGHTS, SHADER_3D, SHADOW_MAP_SIZE, SHADOW_SHADER}; pub type Mat4 = [f32; 16]; // Column-major 4x4 @@ -36,6 +36,11 @@ pub struct Scene3DRenderer { pipelines: [[wgpu::RenderPipeline; 2]; 2], sampler: wgpu::Sampler, meshes: Mutex>>, + shadow_pipeline: wgpu::RenderPipeline, + /// Bound for `Caster` (group 0) and `Face` (group 1) uniforms of the shadow pass. + shadow_uniform_bgl: wgpu::BindGroupLayout, + /// 1x1 map bound when no light casts shadows. + shadow_dummy: wgpu::TextureView, } /// Most meshes kept resident on the GPU across frames. @@ -322,6 +327,8 @@ pub struct PointLight { pub decay_type: f32, /// Unused by the shader; `Renderer3D` still folds it into its cache key. pub decay_rate: f32, + /// Shadow density in `0..=1` when the light casts shadows. + pub shadow_density: Option, } #[derive(Clone, Copy, Debug)] @@ -370,14 +377,41 @@ fn mesh_key(base_shape: &ShapeKind, aspect: f32, wireframe: bool) -> MeshKey { (h.finish(), aspect_bits, wireframe) } +/// View-projections of the six 90 degree faces (`+X -X +Y -Y +Z -Z`) around `eye`. +fn cube_face_view_projections(eye: [f32; 3]) -> [Mat4; 6] { + let proj = mat4_perspective_wgpu(std::f32::consts::FRAC_PI_2, 1.0, 0.01, 1000.0); + [ + ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]), + ([-1.0, 0.0, 0.0], [0.0, 1.0, 0.0]), + ([0.0, 1.0, 0.0], [0.0, 0.0, 1.0]), + ([0.0, -1.0, 0.0], [0.0, 0.0, 1.0]), + ([0.0, 0.0, 1.0], [0.0, 1.0, 0.0]), + ([0.0, 0.0, -1.0], [0.0, 1.0, 0.0]), + ] + .map(|(f, up)| { + let right = [f[1] * up[2] - f[2] * up[1], f[2] * up[0] - f[0] * up[2], f[0] * up[1] - f[1] * up[0]]; + let up = [right[1] * f[2] - right[2] * f[1], right[2] * f[0] - right[0] * f[2], right[0] * f[1] - right[1] * f[0]]; + let dot = |a: [f32; 3]| a[0] * eye[0] + a[1] * eye[1] + a[2] * eye[2]; + let view = [ + right[0], up[0], -f[0], 0.0, + right[1], up[1], -f[1], 0.0, + right[2], up[2], -f[2], 0.0, + -dot(right), -dot(up), dot(f), 1.0, + ]; + mat4_mul(proj, view) + }) +} + impl Scene3DRenderer { pub fn new(device: &wgpu::Device) -> Self { let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("scene3d-shader"), source: wgpu::ShaderSource::Wgsl( SHADER_3D + .replace("MAX_SHADOW_LIGHTS", &MAX_SHADOW_LIGHTS.to_string()) .replace("MAX_DIR_LIGHTS", &MAX_DIR_LIGHTS.to_string()) .replace("MAX_LIGHTS", &MAX_LIGHTS.to_string()) + .replace("SHADOW_MAP_SIZE", &SHADOW_MAP_SIZE.to_string()) .into(), ), }); @@ -410,6 +444,26 @@ impl Scene3DRenderer { ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), count: None, }, + wgpu::BindGroupLayoutEntry { + binding: 3, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 4, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2Array, + multisampled: false, + }, + count: None, + }, ], }); let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { @@ -475,7 +529,83 @@ impl Scene3DRenderer { mipmap_filter: wgpu::MipmapFilterMode::Linear, ..Default::default() }); - Self { bgl, pipelines, sampler, meshes: Mutex::new(Lru::new(MESH_CACHE_CAP)) } + let shadow_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("scene3d-shadow-shader"), + source: wgpu::ShaderSource::Wgsl(SHADOW_SHADER.into()), + }); + let shadow_uniform_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("scene3d-shadow-bgl"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }], + }); + let shadow_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("scene3d-shadow-pl"), + bind_group_layouts: &[Some(&shadow_uniform_bgl), Some(&shadow_uniform_bgl)], + immediate_size: 0, + }); + let shadow_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("scene3d-shadow"), + layout: Some(&shadow_pl), + vertex: wgpu::VertexState { + module: &shadow_shader, + entry_point: Some("vs_shadow"), + compilation_options: Default::default(), + buffers: &[Some(vbuf_layout)], + }, + fragment: Some(wgpu::FragmentState { + module: &shadow_shader, + entry_point: Some("fs_shadow"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: wgpu::TextureFormat::R32Float, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + primitive: wgpu::PrimitiveState::default(), + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::Less), + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }), + multisample: wgpu::MultisampleState::default(), + multiview_mask: None, + cache: None, + }); + let shadow_dummy = device + .create_texture(&wgpu::TextureDescriptor { + label: Some("scene3d-shadow-dummy"), + size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::R32Float, + usage: wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }) + .create_view(&wgpu::TextureViewDescriptor { + dimension: Some(wgpu::TextureViewDimension::D2Array), + ..Default::default() + }); + Self { + bgl, + pipelines, + sampler, + meshes: Mutex::new(Lru::new(MESH_CACHE_CAP)), + shadow_pipeline, + shadow_uniform_bgl, + shadow_dummy, + } } #[allow(clippy::too_many_arguments)] @@ -491,6 +621,7 @@ impl Scene3DRenderer { cam_pos: [f32; 3], lights: SceneLights, lighting_enabled: bool, + shadows_enabled: bool, meshes: &[DrawMesh], ) { let depth_tex = device.create_texture(&wgpu::TextureDescriptor { @@ -509,6 +640,68 @@ impl Scene3DRenderer { }); let depth_view = depth_tex.create_view(&wgpu::TextureViewDescriptor::default()); + // Point-light indices that get a cube shadow map, in slot order. + let shadow_lights: Vec = if shadows_enabled { + (0..lights.points.len().min(MAX_LIGHTS)) + .filter(|&i| lights.points[i].shadow_density.is_some()) + .take(MAX_SHADOW_LIGHTS) + .collect() + } else { + Vec::new() + }; + let mut shadow_uni = ShadowUniform { + face_vp: [mat4_identity(); 6 * MAX_SHADOW_LIGHTS], + point: [[-1.0, 0.0, 0.0, 0.0]; MAX_LIGHTS], + }; + for (slot, &li) in shadow_lights.iter().enumerate() { + let pl = &lights.points[li]; + shadow_uni.face_vp[slot * 6..slot * 6 + 6].copy_from_slice(&cube_face_view_projections(pl.pos)); + shadow_uni.point[li] = [slot as f32, pl.shadow_density.unwrap_or(0.0), 0.0, 0.0]; + } + let shadow_ubuf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("scene3d-shadow-u"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer(&shadow_ubuf, 0, bytemuck::bytes_of(&shadow_uni)); + let shadow_map = (!shadow_lights.is_empty()).then(|| { + device.create_texture(&wgpu::TextureDescriptor { + label: Some("scene3d-shadow-maps"), + size: wgpu::Extent3d { + width: SHADOW_MAP_SIZE, + height: SHADOW_MAP_SIZE, + depth_or_array_layers: 6 * shadow_lights.len() as u32, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::R32Float, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }) + }); + let shadow_view = shadow_map.as_ref().map(|t| { + t.create_view(&wgpu::TextureViewDescriptor { + dimension: Some(wgpu::TextureViewDimension::D2Array), + ..Default::default() + }) + }); + let uniform_bind_group = |label: &str, bytes: &[u8]| { + let buf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size: bytes.len() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer(&buf, 0, bytes); + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some(label), + layout: &self.shadow_uniform_bgl, + entries: &[wgpu::BindGroupEntry { binding: 0, resource: buf.as_entire_binding() }], + }) + }; + // Sort back-to-front in camera view space so semi-transparent planes blend cleanly. let mut order: Vec<(usize, f32)> = meshes .iter() @@ -528,6 +721,8 @@ impl Scene3DRenderer { /// Skip the `[back-facing, front-facing]` pass. cull: [bool; 2], bg: wgpu::BindGroup, + /// `model` for the shadow pass; `None` for meshes that cast no shadow. + caster: Option, vbuf: wgpu::Buffer, ibuf: wgpu::Buffer, idx_count: u32, @@ -660,18 +855,88 @@ impl Scene3DRenderer { wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() }, wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(tex_view) }, wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) }, + wgpu::BindGroupEntry { binding: 3, resource: shadow_ubuf.as_entire_binding() }, + wgpu::BindGroupEntry { + binding: 4, + resource: wgpu::BindingResource::TextureView(shadow_view.as_ref().unwrap_or(&self.shadow_dummy)), + }, ], }); draw_items.push(GpuDraw { wireframe: fx.wireframe, cull: [fx.cull_back, fx.cull_front], bg, + caster: (!fx.wireframe && !shadow_lights.is_empty()) + .then(|| uniform_bind_group("scene3d-caster", bytemuck::cast_slice(&m.world))), vbuf, ibuf, idx_count, }); } + if let Some(map) = &shadow_map { + let shadow_depth_view = device + .create_texture(&wgpu::TextureDescriptor { + label: Some("scene3d-shadow-depth"), + size: wgpu::Extent3d { width: SHADOW_MAP_SIZE, height: SHADOW_MAP_SIZE, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Depth32Float, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }) + .create_view(&wgpu::TextureViewDescriptor::default()); + for (slot, &li) in shadow_lights.iter().enumerate() { + let pos = lights.points[li].pos; + for face in 0..6 { + let layer = (slot * 6 + face) as u32; + let mut uniform = [0.0_f32; 20]; + uniform[..16].copy_from_slice(&shadow_uni.face_vp[layer as usize]); + uniform[16..19].copy_from_slice(&pos); + let face_bg = uniform_bind_group("scene3d-shadow-face", bytemuck::cast_slice(&uniform)); + let layer_view = map.create_view(&wgpu::TextureViewDescriptor { + dimension: Some(wgpu::TextureViewDimension::D2), + base_array_layer: layer, + array_layer_count: Some(1), + ..Default::default() + }); + let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("scene3d-shadow-pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &layer_view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { r: 1e30, g: 0.0, b: 0.0, a: 0.0 }), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &shadow_depth_view, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(1.0), + store: wgpu::StoreOp::Discard, + }), + stencil_ops: None, + }), + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(&self.shadow_pipeline); + pass.set_bind_group(1, &face_bg, &[]); + for d in &draw_items { + let Some(caster) = &d.caster else { continue }; + pass.set_bind_group(0, caster, &[]); + pass.set_vertex_buffer(0, d.vbuf.slice(..)); + pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..d.idx_count, 0, 0..1); + } + } + } + } + let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("scene3d-pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { @@ -864,7 +1129,7 @@ mod tests { let frame = |meshes: &[DrawMesh]| { let mut enc = device.create_command_encoder(&Default::default()); let (vp, cam) = (mat4_identity(), [0.0, 0.0, 5.0]); - renderer.render_meshes(&device, &queue, &mut enc, &dst, &dummy, vp, vp, cam, SceneLights::default(), false, meshes); + renderer.render_meshes(&device, &queue, &mut enc, &dst, &dummy, vp, vp, cam, SceneLights::default(), false, false, meshes); queue.submit(Some(enc.finish())); renderer.meshes.lock().unwrap().entries.len() }; @@ -897,4 +1162,35 @@ mod tests { assert_eq!(shift.then(&double).apply([0.0, 0.0]), [1.0, 0.0]); assert_eq!(double.then(&shift).apply([0.0, 0.0]), [0.5, 0.0]); } + + #[test] + fn opengl_renderer_lighting_and_point_light_shadows() { + let render_gl = |lighting: u8, shadows: u8| -> Option> { + let src = format!( + r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ + Flat = MtlBlinn {{ Inputs = {{ ["Specular.Intensity"] = Input {{ Value = 0, }}, }}, }}, + Recv = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 8, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = -2, }}, MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, }}, }}, + Blocker = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 0.8, }}, ["Transform3DOp.Translate.X"] = Input {{ Value = 0.4, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 0, }}, MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, }}, }}, + Pt = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 1.6, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, Intensity = Input {{ Value = 1, }}, ["ShadowLightInputs3D.ShadowsEnabled"] = Input {{ Value = 1, }}, ["ShadowLightInputs3D.ShadowDensity"] = Input {{ Value = 1.0, }}, }}, }}, + Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 4.5, }}, ApertureW = Input {{ Value = 1.0, }}, ApertureH = Input {{ Value = 1.0, }}, }}, }}, + M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "Recv", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Blocker", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Pt", Source = "Output", }}, SceneInput4 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }}, + R = Renderer3D {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, RendererType = Input {{ Value = FuID {{ "RendererOpenGL" }}, }}, ["RendererOpenGL.LightingEnabled"] = Input {{ Value = {lighting}, }}, ["RendererOpenGL.ShadowsEnabled"] = Input {{ Value = {shadows}, }}, SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, }}, }}, + }} }}"# + ); + let comp = Comp::from_fusion_str(&src).expect("parse shadow comp"); + let mut eng = Engine::new_headless().ok()?; + let id = comp.find_node("R").expect("R"); + let (tex, _) = eng.evaluate(&comp, id, 0.0); + eng.readback_rgba(&tex).ok() + }; + let (Some(unlit), Some(no_shad), Some(with_shad)) = (render_gl(0, 0), render_gl(1, 0), render_gl(1, 1)) else { + return; + }; + // With LightingEnabled=0 under RendererOpenGL, receiver is pure flat white. + let px = |buf: &[u8], x: usize, y: usize| buf[(y * 64 + x) * 4]; + assert_eq!(px(&unlit, 8, 32), 255); + // Blocker at (0,0,0) casts a shadow onto Recv (Z=-2) to the left of center when viewed from X=1.8. + let dark_pixels = |buf: &[u8]| (0..64 * 64).filter(|&i| buf[i * 4 + 3] > 200 && buf[i * 4] < 40).count(); + assert!(dark_pixels(&with_shad) > dark_pixels(&no_shad) + 15, "shadows should darken receiver: with={} vs without={}", dark_pixels(&with_shad), dark_pixels(&no_shad)); + } } diff --git a/crates/engine/src/scene3d/shader.rs b/crates/engine/src/scene3d/shader.rs index ffbaa1839514afe4058f44a49fb19e60b51e5146..d2ddf9f7332bb81c79ae389d5a192ee61371f21d 100644 --- a/crates/engine/src/scene3d/shader.rs +++ b/crates/engine/src/scene3d/shader.rs @@ -6,6 +6,10 @@ use bytemuck::{Pod, Zeroable}; pub(super) const MAX_LIGHTS: usize = 8; /// Directional lights get this many shader slots. pub(super) const MAX_DIR_LIGHTS: usize = 4; +/// Point lights that can cast shadows in one render. +pub(super) const MAX_SHADOW_LIGHTS: usize = 4; +/// Edge length in texels of each cube-map face. +pub(super) const SHADOW_MAP_SIZE: u32 = 1024; #[repr(C)] #[derive(Clone, Copy, Debug, Pod, Zeroable)] @@ -56,7 +60,43 @@ pub(super) struct MeshUniform { pub(super) spot_col: [[f32; 4]; MAX_LIGHTS], } -/// WGSL source; `MAX_LIGHTS` and `MAX_DIR_LIGHTS` are substituted with the Rust constants at pipeline creation. +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +pub(super) struct ShadowUniform { + /// Cube-face view-projections, six per shadow slot (`+X -X +Y -Y +Z -Z`). + pub(super) face_vp: [[f32; 16]; 6 * MAX_SHADOW_LIGHTS], + /// Per point light `(shadow slot or -1, density, 0, 0)`. + pub(super) point: [[f32; 4]; MAX_LIGHTS], +} + +/// Per-caster `model` plus per-face view-projection and light position; writes the distance to +/// the light so the main pass can compare it against a fragment's own distance. +pub(super) const SHADOW_SHADER: &str = r#" +struct Caster { model: mat4x4 }; +struct Face { vp: mat4x4, light_pos: vec4 }; + +@group(0) @binding(0) var caster: Caster; +@group(1) @binding(0) var face: Face; + +struct VsOut { + @builtin(position) clip: vec4, + @location(0) world_pos: vec3, +}; + +@vertex +fn vs_shadow(@location(0) pos: vec3) -> VsOut { + let wp = caster.model * vec4(pos, 1.0); + return VsOut(face.vp * wp, wp.xyz); +} + +@fragment +fn fs_shadow(in: VsOut) -> @location(0) f32 { + return distance(in.world_pos, face.light_pos.xyz); +} +"#; + +/// WGSL source; `MAX_LIGHTS`, `MAX_DIR_LIGHTS`, `MAX_SHADOW_LIGHTS` and `SHADOW_MAP_SIZE` are +/// substituted with the Rust constants at pipeline creation. pub(super) const SHADER_3D: &str = r#" struct MeshUniform { mvp: mat4x4, @@ -80,11 +120,18 @@ struct MeshUniform { spot_col: array, MAX_LIGHTS>, }; +struct ShadowUniform { + face_vp: array, 6 * MAX_SHADOW_LIGHTS>, + point: array, MAX_LIGHTS>, +}; + override BACK_PASS: bool = false; @group(0) @binding(0) var u: MeshUniform; @group(0) @binding(1) var mat_tex: texture_2d; @group(0) @binding(2) var mat_samp: sampler; +@group(0) @binding(3) var shadow: ShadowUniform; +@group(0) @binding(4) var shadow_maps: texture_2d_array; struct VsIn { @location(0) pos: vec3, @@ -138,6 +185,41 @@ fn light_attenuation(dist: f32, decay_type: f32) -> f32 { return 1.0; } +/// Fraction of PCF taps where the cube map of point light `i` records a closer occluder. +fn point_shadow_occlusion(i: i32, world_pos: vec3, n: vec3, light_pos: vec3) -> f32 { + let params = shadow.point[i]; + if (params.x < -0.5) { + return 0.0; + } + let slot = i32(params.x + 0.5); + let d = world_pos - light_pos; + let dist = length(d); + let a = abs(d); + var face = 4; + if (a.x >= a.y && a.x >= a.z) { + face = select(1, 0, d.x > 0.0); + } else if (a.y >= a.z) { + face = select(3, 2, d.y > 0.0); + } else { + face = select(5, 4, d.z > 0.0); + } + // World size of one texel at this distance for a 90 degree face. + let texel = 2.0 * dist / f32(SHADOW_MAP_SIZE); + let clip = shadow.face_vp[slot * 6 + face] * vec4(world_pos + n * (texel * 1.5), 1.0); + let ndc = clip.xy / clip.w; + let base = vec2(floor(vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * f32(SHADOW_MAP_SIZE))); + let last = SHADOW_MAP_SIZE - 1; + var occluded = 0.0; + for (var dy: i32 = -1; dy <= 1; dy = dy + 1) { + for (var dx: i32 = -1; dx <= 1; dx = dx + 1) { + let t = clamp(base + vec2(dx, dy), vec2(0), vec2(last)); + let stored = textureLoad(shadow_maps, t, slot * 6 + face, 0).r; + occluded = occluded + select(0.0, 1.0, dist - texel * 3.0 > stored); + } + } + return occluded / 9.0; +} + fn eval_light_contrib( n: vec3, v: vec3, @@ -147,12 +229,14 @@ fn eval_light_contrib( spec_rgb: vec3, spec_int: f32, shininess: f32, + diffuse_vis: f32, + spec_vis: f32, ) -> vec3 { let ndotl = max(dot(n, l), 0.0); if (ndotl <= 0.0) { return vec3(0.0); } - var out = albedo * light_rgb * ndotl; + var out = albedo * light_rgb * (ndotl * diffuse_vis); if (spec_int > 1e-4) { let h = normalize(l + v); let model = i32(u.mat_fx.w + 0.5); @@ -167,7 +251,7 @@ fn eval_light_contrib( } else { lobe = pow(max(dot(n, h), 0.0), shininess); } - out = out + light_rgb * spec_rgb * (lobe * spec_int); + out = out + light_rgb * spec_rgb * (lobe * spec_int * spec_vis); } return out; } @@ -295,7 +379,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4 { for (var i: i32 = 0; i < MAX_DIR_LIGHTS; i = i + 1) { if (i >= n_dir) { break; } let l = normalize(u.dir_to_light[i].xyz); - lit = lit + eval_light_contrib(n, v, l, u.dir_color[i].rgb, albedo, spec_rgb, spec_int, shininess); + lit = lit + eval_light_contrib(n, v, l, u.dir_color[i].rgb, albedo, spec_rgb, spec_int, shininess, 1.0, 1.0); } let n_pt = i32(u.light_counts.x + 0.5); @@ -304,7 +388,12 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4 { let to_l = u.point_pos[i].xyz - in.world_pos; let dist = max(length(to_l), 1e-4); let att = light_attenuation(dist, u.point_pos[i].w); - lit = lit + eval_light_contrib(n, v, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess); + // Shadow density dims only the diffuse term; specular is cut outright. + let occ = point_shadow_occlusion(i, in.world_pos, n, u.point_pos[i].xyz); + lit = lit + eval_light_contrib( + n, v, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess, + 1.0 - shadow.point[i].y * occ, 1.0 - occ, + ); } let n_sp = i32(u.light_counts.y + 0.5); @@ -320,7 +409,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4 { let cone = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 1e-4), 0.0, 1.0); if (cone > 0.0) { let att = light_attenuation(dist, u.spot_col[i].w) * cone; - lit = lit + eval_light_contrib(n, v, l_dir, u.spot_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess); + lit = lit + eval_light_contrib(n, v, l_dir, u.spot_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess, 1.0, 1.0); } } diff --git a/crates/engine/src/text_engine.rs b/crates/engine/src/text_engine.rs index 2d2da3d000d560458024ba7c98187fa994ce7493..0ccd23a352670ab42ba4280ddbc71ffe879f3738 100644 --- a/crates/engine/src/text_engine.rs +++ b/crates/engine/src/text_engine.rs @@ -76,10 +76,25 @@ pub fn parse_style(style: &str) -> (u16, bool) { (weight, s.contains("italic") || s.contains("oblique")) } +fn metric_alias(family: &str) -> Option<&'static str> { + if family.eq_ignore_ascii_case("Liberation Sans") { + Some("Arial") + } else if family.eq_ignore_ascii_case("Arial") { + Some("Liberation Sans") + } else if family.eq_ignore_ascii_case("Liberation Serif") { + Some("Times New Roman") + } else if family.eq_ignore_ascii_case("Liberation Mono") { + Some("Courier New") + } else { + None + } +} + fn resolve(db: &fontdb::Database, family: &str, style: &str) -> Option { let (weight, italic) = parse_style(style); let wanted: String = style.chars().filter(|c| !c.is_whitespace()).collect::().to_ascii_lowercase(); let id = std::iter::once(family) + .chain(metric_alias(family)) .chain(FALLBACK_FAMILIES) .find_map(|name| pick(db, name, &wanted, weight, italic)) .or_else(|| db.query(&fontdb::Query { families: &[fontdb::Family::SansSerif], ..Default::default() })) @@ -445,4 +460,29 @@ mod tests { assert!((right[2] - 480).abs() <= 6, "{right:?}"); assert!(((centre[0] + centre[2]) / 2 - 480).abs() <= 3, "{centre:?}"); } + + #[test] + fn liberation_sans_uses_metric_equivalent_and_landscape_scales_with_width() { + let lib_font = Font::find("Liberation Sans", "Regular").expect("Liberation Sans or metric alias"); + let arial_font = Font::find("Arial", "Regular").expect("Arial"); + let (lib_face, arial_face) = (lib_font.face(), arial_font.face()); + let lib_w = shape_line(&lib_face, "Aspect 321", 50.0, 0.0).width; + let arial_w = shape_line(&arial_face, "Aspect 321", 50.0, 0.0).width; + assert!((lib_w - arial_w).abs() < 1.0, "expected Liberation Sans / Arial metric parity: {lib_w} vs {arial_w}"); + + let span = |dims: [u32; 2]| { + let mut p = params("Aspect 321"); + p.font_family = "Liberation Sans"; + p.size_norm = 0.18; + let (sz, orig, rgba) = rasterize_text_plus(dims, &p, 0); + let b = alpha_bounds(sz, orig, &rgba).unwrap(); + (b[2] - b[0] + 1, b[3] - b[1] + 1, (b[0] + b[2]) / 2, (b[1] + b[3]) / 2) + }; + let (lw, lh, lcx, lcy) = span([320, 180]); + let (pw, ph, pcx, pcy) = span([180, 320]); + assert!((lw as f32 / pw as f32 - 320.0 / 180.0).abs() < 0.08, "landscape/portrait width ratio {lw}/{pw}"); + assert!((lh as f32 / ph as f32 - 320.0 / 180.0).abs() < 0.12, "landscape/portrait height ratio {lh}/{ph}"); + assert!((lcx - 160).abs() <= 8 && (lcy - 90).abs() <= 8, "landscape centered ({lcx}, {lcy})"); + assert!((pcx - 90).abs() <= 6 && (pcy - 160).abs() <= 6, "portrait centered ({pcx}, {pcy})"); + } } -- 2.54.1