From 7090cf87ebf69321576c2ab7da746e79d2b31799 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Tue, 1 Dec 2026 01:31:19 -0800 Subject: [PATCH] Shadow map pooling, alpha-tested casters, cube-seam fix; TextPlus font aliases and Inspector schema sync - Renderer3D shadows require lighting; cube maps/depth are reused across renders and caster/face uniforms share one dynamic-offset buffer. - Shadow pass skips transparent meshes and alpha-tests textured casters; face pick uses the normal-offset point, guards clip.w, far derives from camera range. - metric_alias is symmetric for Times New Roman / Courier New. - WandMask Channel, ChannelBoolean And/Or/Xor/Signed Add, Loader Loop/Reverse default from the clip. Assisted-by: claude-sonnet-5.5 --- crates/app/src/inspector/schemas.rs | 4 +- crates/app/src/inspector/widgets.rs | 8 + crates/engine/src/eval/text_3d.rs | 12 +- crates/engine/src/scene3d/mod.rs | 281 ++++++++++++++++++++-------- crates/engine/src/scene3d/shader.rs | 77 +++++--- crates/engine/src/text_engine.rs | 12 ++ 6 files changed, 288 insertions(+), 106 deletions(-) diff --git a/crates/app/src/inspector/schemas.rs b/crates/app/src/inspector/schemas.rs index 03ed481e10c70e118c830ad75ff4ecf2696b8e5b..99fe52a490c16df6198f0943287f363fe5d1a926 100644 --- a/crates/app/src/inspector/schemas.rs +++ b/crates/app/src/inspector/schemas.rs @@ -104,8 +104,9 @@ const MASK_CHANNELS: &[&str] = &[ const EDGES_INT: &[(i32, &str)] = &[(0, "Canvas"), (1, "Wrap"), (2, "Duplicate"), (3, "Mirror")]; const CB_OPS: &[(i32, &str)] = &[ - (0, "Copy"), (1, "Add"), (2, "Subtract"), (6, "Multiply"), (7, "Divide"), + (0, "Copy"), (1, "Add"), (2, "Subtract"), (3, "And"), (4, "Or"), (5, "Exclusive Or"), (6, "Multiply"), (7, "Divide"), (8, "Maximum"), (9, "Minimum"), (10, "Negative"), (11, "Solid"), (12, "Clear"), (13, "Difference"), + (14, "Signed Add"), ]; const CB_CHANNELS: &[(i32, &str)] = &[ (0, "Red FG"), (1, "Green FG"), (2, "Blue FG"), (3, "Alpha FG"), (4, "Do Nothing"), @@ -601,6 +602,7 @@ pub fn schema_for_kind(kind: &str) -> &'static [ParamSpec] { v2("SelectionPoint", "Seed Point", 0.0, 1.0, [0.5, 0.5]), flt("Range", "Range", 0.0, 1.0, 0.1), flt("RangeSoftEdge", "Range Soft", 0.0, 1.0, 0.0), + int_enum("Channel", "Channel", &[(0, "Color"), (1, "Red"), (2, "Green"), (3, "Blue"), (4, "Alpha")], 0), int_enum("ColorSpace", "Color Space", &[(0, "RGB"), (1, "YUV")], 0), fuid("Filter", "Filter", BLUR_FILTERS, "Fast Gaussian"), flt("SoftEdge", "Soft Edge", 0.0, 0.5, 0.0), diff --git a/crates/app/src/inspector/widgets.rs b/crates/app/src/inspector/widgets.rs index 3af3d009efe36f3d637045d3c21f6920c35677be..a5f063c5215be8405e30e54458a5734ced49f863 100644 --- a/crates/app/src/inspector/widgets.rs +++ b/crates/app/src/inspector/widgets.rs @@ -110,6 +110,14 @@ impl InspectorState { ); } ParamKind::Bool { default } => { + // A Loader without `Inputs.Loop`/`Reverse` plays whatever its clip says. + let node = comp.node(node_id); + let clip = node.clips.first().filter(|_| node.kind == "Loader"); + let default = match spec.name { + "Loop" => clip.map_or(default, |c| c.loop_clip), + "Reverse" => clip.map_or(default, |c| c.reverse), + _ => default, + }; self.render_bool_row(ui, comp, history, node_id, spec.name, spec.label, default, actions); } ParamKind::Enum { options, default } => { diff --git a/crates/engine/src/eval/text_3d.rs b/crates/engine/src/eval/text_3d.rs index 66c4067aed32d60405218a5d985bc5da86dd3f50..e92e8721ff2ae3adb9b68d1fd8bacb7180efe1ca 100644 --- a/crates/engine/src/eval/text_3d.rs +++ b/crates/engine/src/eval/text_3d.rs @@ -517,8 +517,9 @@ impl Engine { // 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" + // Only the OpenGL renderer shades shadows, and only when lighting is on. + let shadows_enabled = lighting_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(); @@ -538,14 +539,14 @@ impl Engine { 0, ); - let (view, proj, cam_pos) = if let Some(cam) = cameras.first() { + let (view, proj, cam_pos, cam_far) = if let Some(cam) = cameras.first() { let v = crate::scene3d::mat4_inverse(cam.world); let p = crate::scene3d::mat4_perspective_wgpu(cam.vfov_rad, aspect, cam.near, cam.far); - (v, p, [cam.world[12], cam.world[13], cam.world[14]]) + (v, p, [cam.world[12], cam.world[13], cam.world[14]], cam.far) } else { let v = crate::scene3d::mat4_translate(0.0, 0.0, -5.0); let p = crate::scene3d::mat4_perspective_wgpu(45.0_f32.to_radians(), aspect, 0.05, 5000.0); - (v, p, [0.0, 0.0, 5.0]) + (v, p, [0.0, 0.0, 5.0], 5000.0) }; let view_proj = crate::scene3d::mat4_mul(proj, view); @@ -670,6 +671,7 @@ impl Engine { view_proj, view, cam_pos, + cam_far, lights, lighting_enabled, shadows_enabled, diff --git a/crates/engine/src/scene3d/mod.rs b/crates/engine/src/scene3d/mod.rs index 13fe6a3c477b613dbd1a6679a07800823d8cc941..2da6eb18dd139fa15b544f98ba76974abb4006f1 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, ShadowUniform, MAX_DIR_LIGHTS, MAX_LIGHTS, MAX_SHADOW_LIGHTS, SHADER_3D, SHADOW_MAP_SIZE, SHADOW_SHADER}; +use shader::{MeshUniform, ShadowUniform, MAX_DIR_LIGHTS, MAX_LIGHTS, MAX_SHADOW_LIGHTS, SHADER_3D, SHADOW_MAP_SIZE, SHADOW_SHADER, UV_XFORM_WGSL}; pub type Mat4 = [f32; 16]; // Column-major 4x4 @@ -37,12 +37,28 @@ pub struct Scene3DRenderer { 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, + /// `Caster` uniform (dynamic offset), material texture and sampler: group 0 of the shadow pass. + shadow_caster_bgl: wgpu::BindGroupLayout, + /// `Face` uniform (dynamic offset): group 1 of the shadow pass. + shadow_face_bgl: wgpu::BindGroupLayout, /// 1x1 map bound when no light casts shadows. shadow_dummy: wgpu::TextureView, + /// Cube maps and depth buffer reused across renders; grown, never shrunk. + shadow_targets: Mutex>, } +#[derive(Clone)] +struct ShadowTargets { + maps: wgpu::Texture, + /// Array layers of `maps` (six per shadow light). + layers: u32, + depth: wgpu::TextureView, +} + +/// Bytes of the shadow pass's `Caster` and `Face` uniforms. +const CASTER_BYTES: usize = 128; +const FACE_BYTES: usize = 80; + /// Most meshes kept resident on the GPU across frames. const MESH_CACHE_CAP: usize = 64; @@ -378,8 +394,8 @@ fn mesh_key(base_shape: &ShapeKind, aspect: f32, wireframe: bool) -> MeshKey { } /// 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); +fn cube_face_view_projections(eye: [f32; 3], far: f32) -> [Mat4; 6] { + let proj = mat4_perspective_wgpu(std::f32::consts::FRAC_PI_2, 1.0, 0.01, far); [ ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]), ([-1.0, 0.0, 0.0], [0.0, 1.0, 0.0]), @@ -407,7 +423,7 @@ impl Scene3DRenderer { let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("scene3d-shader"), source: wgpu::ShaderSource::Wgsl( - SHADER_3D + format!("{UV_XFORM_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()) @@ -531,24 +547,47 @@ impl Scene3DRenderer { }); let shadow_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("scene3d-shadow-shader"), - source: wgpu::ShaderSource::Wgsl(SHADOW_SHADER.into()), + source: wgpu::ShaderSource::Wgsl(format!("{UV_XFORM_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, + let dynamic_uniform = |binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: true, + min_binding_size: None, + }, + count: None, + }; + let shadow_caster_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("scene3d-shadow-caster-bgl"), + entries: &[ + dynamic_uniform(0), + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, }, - count: None, - }], + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + let shadow_face_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("scene3d-shadow-face-bgl"), + entries: &[dynamic_uniform(0)], }); 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)], + bind_group_layouts: &[Some(&shadow_caster_bgl), Some(&shadow_face_bgl)], immediate_size: 0, }); let shadow_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { @@ -603,8 +642,10 @@ impl Scene3DRenderer { sampler, meshes: Mutex::new(Lru::new(MESH_CACHE_CAP)), shadow_pipeline, - shadow_uniform_bgl, + shadow_caster_bgl, + shadow_face_bgl, shadow_dummy, + shadow_targets: Mutex::new(None), } } @@ -619,6 +660,7 @@ impl Scene3DRenderer { view_proj: Mat4, view: Mat4, cam_pos: [f32; 3], + cam_far: f32, lights: SceneLights, lighting_enabled: bool, shadows_enabled: bool, @@ -653,9 +695,12 @@ impl Scene3DRenderer { face_vp: [mat4_identity(); 6 * MAX_SHADOW_LIGHTS], point: [[-1.0, 0.0, 0.0, 0.0]; MAX_LIGHTS], }; + // Receivers visible to the camera are at most `cam_far` from it, so that bounds the light's reach. + let distance_to_cam = |p: [f32; 3]| (0..3).map(|i| (p[i] - cam_pos[i]).powi(2)).sum::().sqrt(); 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)); + let far = cam_far + distance_to_cam(pl.pos); + shadow_uni.face_vp[slot * 6..slot * 6 + 6].copy_from_slice(&cube_face_view_projections(pl.pos, far)); 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 { @@ -665,42 +710,65 @@ impl Scene3DRenderer { 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_targets = (!shadow_lights.is_empty()).then(|| { + let layers = 6 * shadow_lights.len() as u32; + let mut cache = self.shadow_targets.lock().unwrap(); + match cache.as_ref() { + Some(t) if t.layers >= layers => t.clone(), + _ => { + let target = |label, format, usage, depth_or_array_layers| { + device.create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { width: SHADOW_MAP_SIZE, height: SHADOW_MAP_SIZE, depth_or_array_layers }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }) + }; + let fresh = ShadowTargets { + maps: target( + "scene3d-shadow-maps", + wgpu::TextureFormat::R32Float, + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, + layers, + ), + layers, + depth: target( + "scene3d-shadow-depth", + wgpu::TextureFormat::Depth32Float, + wgpu::TextureUsages::RENDER_ATTACHMENT, + 1, + ) + .create_view(&wgpu::TextureViewDescriptor::default()), + }; + *cache = Some(fresh.clone()); + fresh + } + } }); - let shadow_view = shadow_map.as_ref().map(|t| { - t.create_view(&wgpu::TextureViewDescriptor { + let shadow_view = shadow_targets.as_ref().map(|t| { + t.maps.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, + // One buffer holds every caster and face uniform of this render at dynamic offsets: casters + // first (at most one per mesh), then six faces per light. + let uniform_stride = (CASTER_BYTES as u32).next_multiple_of(device.limits().min_uniform_buffer_offset_alignment) as usize; + let face_base = meshes.len() * uniform_stride; + let mut shadow_uniform_bytes = vec![0u8; if shadow_lights.is_empty() { 0 } else { face_base + shadow_lights.len() * 6 * uniform_stride }]; + let shadow_dyn_buf = (!shadow_lights.is_empty()).then(|| { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some("scene3d-shadow-dyn"), + size: shadow_uniform_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() }], }) - }; + }); + let mut n_casters = 0; // Sort back-to-front in camera view space so semi-transparent planes blend cleanly. let mut order: Vec<(usize, f32)> = meshes @@ -721,8 +789,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, + /// Shadow-pass bind group and dynamic uniform offset; `None` for meshes that cast no shadow. + caster: Option<(wgpu::BindGroup, u32)>, vbuf: wgpu::Buffer, ibuf: wgpu::Buffer, idx_count: u32, @@ -862,42 +930,71 @@ impl Scene3DRenderer { }, ], }); + // A fully transparent mesh casts no shadow; textured ones are alpha-tested in the pass. + let caster = shadow_dyn_buf.as_ref().filter(|_| !fx.wireframe && m.diffuse_col[3] > 1e-3).map(|buf| { + let mut data = [0.0_f32; CASTER_BYTES / 4]; + data[..16].copy_from_slice(&m.world); + data[16..20].copy_from_slice(&fx.uv.m); + data[20..24].copy_from_slice(&uni.uv_off_wrap); + data[24..28].copy_from_slice(&dod); + data[28..30].copy_from_slice(&[if m.tex.is_some() && !fx.bump_only { 1.0 } else { 0.0 }, m.diffuse_col[3]]); + let offset = n_casters * uniform_stride; + shadow_uniform_bytes[offset..offset + CASTER_BYTES].copy_from_slice(bytemuck::cast_slice(&data)); + n_casters += 1; + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("scene3d-shadow-caster"), + layout: &self.shadow_caster_bgl, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: buf, + offset: 0, + size: std::num::NonZeroU64::new(CASTER_BYTES as u64), + }), + }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(tex_view) }, + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) }, + ], + }); + (bind_group, offset as u32) + }); 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))), + caster, 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()); + if let (Some(targets), Some(buf)) = (&shadow_targets, &shadow_dyn_buf) { + let face_bg = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("scene3d-shadow-face"), + layout: &self.shadow_face_bgl, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: buf, + offset: 0, + size: std::num::NonZeroU64::new(FACE_BYTES as u64), + }), + }], + }); 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]); + let layer = slot * 6 + face; + let mut uniform = [0.0_f32; FACE_BYTES / 4]; + uniform[..16].copy_from_slice(&shadow_uni.face_vp[layer]); 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 { + let face_offset = face_base + layer * uniform_stride; + shadow_uniform_bytes[face_offset..face_offset + FACE_BYTES].copy_from_slice(bytemuck::cast_slice(&uniform)); + let layer_view = targets.maps.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2), - base_array_layer: layer, + base_array_layer: layer as u32, array_layer_count: Some(1), ..Default::default() }); @@ -913,7 +1010,7 @@ impl Scene3DRenderer { }, })], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &shadow_depth_view, + view: &targets.depth, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard, @@ -925,16 +1022,17 @@ impl Scene3DRenderer { multiview_mask: None, }); pass.set_pipeline(&self.shadow_pipeline); - pass.set_bind_group(1, &face_bg, &[]); + pass.set_bind_group(1, &face_bg, &[face_offset as u32]); for d in &draw_items { - let Some(caster) = &d.caster else { continue }; - pass.set_bind_group(0, caster, &[]); + let Some((caster, caster_offset)) = &d.caster else { continue }; + pass.set_bind_group(0, caster, &[*caster_offset]); 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); } } } + queue.write_buffer(buf, 0, &shadow_uniform_bytes); } let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { @@ -1129,7 +1227,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, false, meshes); + renderer.render_meshes(&device, &queue, &mut enc, &dst, &dummy, vp, vp, cam, 1000.0, SceneLights::default(), false, false, meshes); queue.submit(Some(enc.finish())); renderer.meshes.lock().unwrap().entries.len() }; @@ -1193,4 +1291,33 @@ mod tests { 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)); } + + #[test] + fn transparent_textured_casters_leave_no_shadow() { + let dark_receiver_pixels = |card_alpha: 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, }}, }}, }}, + Bg = Background {{ Inputs = {{ Width = Input {{ Value = 8, }}, Height = Input {{ Value = 8, }}, TopLeftRed = Input {{ Value = 1, }}, TopLeftAlpha = Input {{ Value = {card_alpha}, }}, }}, }}, + Tex = Texture2DOperator {{ Inputs = {{ Input = Input {{ SourceOp = "Bg", Source = "Output", }}, }}, }}, + Recv = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 8, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = -2, }}, MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, }}, }}, + Card = ImagePlane3D {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 0.4, }}, MaterialInput = Input {{ SourceOp = "Tex", Source = "MaterialOutput", }}, }}, }}, + Pt = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 1.6, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, ["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 = "Card", 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 = 1, }}, ["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 (tex, _) = eng.evaluate(&comp, comp.find_node("R").expect("R"), 0.0); + let buf = eng.readback_rgba(&tex).ok()?; + Some((0..64 * 64).filter(|&i| buf[i * 4 + 3] > 200 && buf[i * 4] < 40).count()) + }; + let (Some(opaque), Some(clear), Some(off)) = (dark_receiver_pixels(255, 1), dark_receiver_pixels(0, 1), dark_receiver_pixels(0, 0)) else { + return; + }; + assert!(opaque > off + 15, "opaque card must shadow: {opaque} vs {off}"); + assert_eq!(clear, off, "a fully transparent card casts no shadow"); + } } diff --git a/crates/engine/src/scene3d/shader.rs b/crates/engine/src/scene3d/shader.rs index d2ddf9f7332bb81c79ae389d5a192ee61371f21d..81f11603c063f0a75405d6ec8d18063453bb4467 100644 --- a/crates/engine/src/scene3d/shader.rs +++ b/crates/engine/src/scene3d/shader.rs @@ -69,28 +69,66 @@ pub(super) struct ShadowUniform { 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. +/// UV affine plus wrap (`off_wrap.z`: 0 clamp, 1 wrap, 2 mirror), shared by both pipelines. +pub(super) const UV_XFORM_WGSL: &str = r#" +fn apply_uv_xform(raw_uv: vec2, m: vec4, off_wrap: vec4) -> vec2 { + var uv = vec2(m.x * raw_uv.x + m.z * raw_uv.y, m.y * raw_uv.x + m.w * raw_uv.y) + off_wrap.xy; + let wrap = i32(off_wrap.z + 0.5); + if (wrap == 1) { + uv = fract(uv); + } else if (wrap == 2) { + uv = vec2(1.0) - abs(fract(uv * 0.5) * 2.0 - vec2(1.0)); + } + return uv; +} +"#; + +/// Per-caster `model` and alpha-test inputs 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. Textured casters discard fragments whose coverage is below half. pub(super) const SHADOW_SHADER: &str = r#" -struct Caster { model: mat4x4 }; +// `alpha.x`: 1 when the bound texture alpha-tests the caster; `alpha.y`: diffuse alpha. +struct Caster { + model: mat4x4, + uv_xform: vec4, + uv_off_wrap: vec4, + dod: vec4, + alpha: vec4, +}; struct Face { vp: mat4x4, light_pos: vec4 }; @group(0) @binding(0) var caster: Caster; +@group(0) @binding(1) var mat_tex: texture_2d; +@group(0) @binding(2) var mat_samp: sampler; @group(1) @binding(0) var face: Face; struct VsOut { @builtin(position) clip: vec4, @location(0) world_pos: vec3, + @location(1) uv: vec2, }; @vertex -fn vs_shadow(@location(0) pos: vec3) -> VsOut { +fn vs_shadow(@location(0) pos: vec3, @location(2) uv: vec2) -> VsOut { let wp = caster.model * vec4(pos, 1.0); - return VsOut(face.vp * wp, wp.xyz); + return VsOut(face.vp * wp, wp.xyz, uv); } @fragment fn fs_shadow(in: VsOut) -> @location(0) f32 { + if (caster.alpha.x > 0.5) { + var uv = apply_uv_xform(in.uv, caster.uv_xform, caster.uv_off_wrap); + if (caster.dod.z > 0.5 && caster.dod.w > 0.5) { + let tdims = vec2(textureDimensions(mat_tex)); + uv = (vec2(uv.x * caster.dod.z, uv.y * caster.dod.w) - caster.dod.xy) / tdims; + if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { + discard; + } + } + if (textureSampleLevel(mat_tex, mat_samp, uv, 0.0).a * caster.alpha.y < 0.5) { + discard; + } + } return distance(in.world_pos, face.light_pos.xyz); } "#; @@ -192,8 +230,12 @@ fn point_shadow_occlusion(i: i32, world_pos: vec3, n: vec3, light_pos: return 0.0; } let slot = i32(params.x + 0.5); - let d = world_pos - light_pos; - let dist = length(d); + let dist = length(world_pos - light_pos); + // World size of one texel at this distance for a 90 degree face. + let texel = 2.0 * dist / f32(SHADOW_MAP_SIZE); + // The face is picked from the offset point so the lookup never straddles a cube seam. + let biased = world_pos + n * (texel * 1.5); + let d = biased - light_pos; let a = abs(d); var face = 4; if (a.x >= a.y && a.x >= a.z) { @@ -203,9 +245,10 @@ fn point_shadow_occlusion(i: i32, world_pos: vec3, n: vec3, light_pos: } 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 clip = shadow.face_vp[slot * 6 + face] * vec4(biased, 1.0); + if (clip.w <= 1e-5) { + return 0.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; @@ -256,18 +299,6 @@ fn eval_light_contrib( return out; } -fn apply_uv_xform(raw_uv: vec2) -> vec2 { - let m = u.uv_xform; - var uv = vec2(m.x * raw_uv.x + m.z * raw_uv.y, m.y * raw_uv.x + m.w * raw_uv.y) + u.uv_off_wrap.xy; - let wrap = i32(u.uv_off_wrap.z + 0.5); - if (wrap == 1) { - uv = fract(uv); - } else if (wrap == 2) { - uv = vec2(1.0) - abs(fract(uv * 0.5) * 2.0 - vec2(1.0)); - } - return uv; -} - fn perturb_bump_normal( base_n: vec3, dpdx_w: vec3, @@ -327,7 +358,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4 { if (facing_away != BACK_PASS) { discard; } - let uv_xformed = apply_uv_xform(in.uv); + let uv_xformed = apply_uv_xform(in.uv, u.uv_xform, u.uv_off_wrap); let dpdx_w = dpdx(in.world_pos); let dpdy_w = dpdy(in.world_pos); let duvdx = dpdx(uv_xformed); diff --git a/crates/engine/src/text_engine.rs b/crates/engine/src/text_engine.rs index 0ccd23a352670ab42ba4280ddbc71ffe879f3738..1a13fd66cf6e65503154aa961daafd1cd58b01c3 100644 --- a/crates/engine/src/text_engine.rs +++ b/crates/engine/src/text_engine.rs @@ -83,8 +83,12 @@ fn metric_alias(family: &str) -> Option<&'static str> { Some("Liberation Sans") } else if family.eq_ignore_ascii_case("Liberation Serif") { Some("Times New Roman") + } else if family.eq_ignore_ascii_case("Times New Roman") { + Some("Liberation Serif") } else if family.eq_ignore_ascii_case("Liberation Mono") { Some("Courier New") + } else if family.eq_ignore_ascii_case("Courier New") { + Some("Liberation Mono") } else { None } @@ -485,4 +489,12 @@ mod tests { 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})"); } + + #[test] + fn metric_aliases_map_both_ways() { + for (a, b) in [("Arial", "Liberation Sans"), ("Times New Roman", "Liberation Serif"), ("Courier New", "Liberation Mono")] { + assert_eq!(metric_alias(a), Some(b)); + assert_eq!(metric_alias(b), Some(a)); + } + } } -- 2.54.1