diff --git a/crates/engine/src/eval/io.rs b/crates/engine/src/eval/io.rs index 214f092829163258862d831dee1ff90e11f28345..103b2bcea9c19518458770e9914f380c54b51936 100644 --- a/crates/engine/src/eval/io.rs +++ b/crates/engine/src/eval/io.rs @@ -93,12 +93,23 @@ impl Engine { data: &[u8], bytes_per_pixel: u32, size: [u32; 2], + ) { + self.upload_raw_texture(enc, &tex.texture, data, bytes_per_pixel, size); + } + + fn upload_raw_texture( + &self, + enc: &mut wgpu::CommandEncoder, + texture: &wgpu::Texture, + data: &[u8], + bytes_per_pixel: u32, + size: [u32; 2], ) { #[cfg(target_arch = "wasm32")] { let _ = enc; self.queue.write_texture( - tex.texture.as_image_copy(), + texture.as_image_copy(), data, wgpu::TexelCopyBufferLayout { offset: 0, @@ -168,7 +179,7 @@ impl Engine { rows_per_image: Some(h), }, }, - tex.texture.as_image_copy(), + texture.as_image_copy(), wgpu::Extent3d { width: w, height: h, @@ -181,7 +192,7 @@ impl Engine { } } self.queue.write_texture( - tex.texture.as_image_copy(), + texture.as_image_copy(), data, wgpu::TexelCopyBufferLayout { offset: 0, @@ -375,7 +386,7 @@ impl Engine { } else { base_tex }; - let tex = if need_depth_conv { + let mut tex = if need_depth_conv { let promoted = self.alloc_tex(target_size, dst_depth, key); let u = UniformParams::default(); self.dispatch_op(enc, ShaderOp::ChangeDepth, &masked_tex.view, &self.dummy.view, &self.dummy.view, &promoted, &u); @@ -383,6 +394,47 @@ impl Engine { } else { masked_tex }; + if let Some(z_vals) = img.z_f32.as_ref() { + let expected_len = (img.size[0] as usize).saturating_mul(img.size[1] as usize); + if z_vals.len() == expected_len && tex.size[0] > 0 && tex.size[1] > 0 { + let z_tex = crate::cache::AuxChannelTex::new( + &self.device, + tex.size, + wgpu::TextureFormat::R32Float, + "loader-aux-z", + ); + if z_tex.size == img.size { + self.upload_raw_texture( + enc, + &z_tex.texture, + bytemuck::cast_slice(z_vals), + 4, + img.size, + ); + } else { + let [sw, sh] = [img.size[0] as usize, img.size[1] as usize]; + let [dw, dh] = [z_tex.size[0] as usize, z_tex.size[1] as usize]; + let mut resampled = Vec::with_capacity(dw * dh); + for dy in 0..dh { + let sy = ((dy * sh) / dh).min(sh.saturating_sub(1)); + for dx in 0..dw { + let sx = ((dx * sw) / dw).min(sw.saturating_sub(1)); + resampled.push(z_vals[sy * sw + sx]); + } + } + self.upload_raw_texture( + enc, + &z_tex.texture, + bytemuck::cast_slice(&resampled), + 4, + z_tex.size, + ); + } + let mut aux = tex.aux_cloned(); + aux.z = Some(z_tex); + tex.set_aux(Some(std::sync::Arc::new(aux))); + } + } self.cache.insert(key, tex.clone(), node.id, frame_i); tex } @@ -1760,4 +1812,103 @@ Composition {{ assert_eq!(oob_loop.size, [32, 32]); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn loader_attaches_exr_z_channel_to_aux_with_row_padding() { + use ::exr::prelude::*; + + let w = 13usize; + let h = 7usize; + let z_expected: Vec = (0..(w * h)) + .map(|i| if i % 5 == 0 { crate::cache::EMPTY_Z_SENTINEL } else { -1.25 - (i as f32) * 0.125 }) + .collect(); + let mut channels = SmallVec::<[AnyChannel; 4]>::new(); + channels.push(AnyChannel::new("R", FlatSamples::F32(vec![0.8; w * h]))); + channels.push(AnyChannel::new("G", FlatSamples::F32(vec![0.4; w * h]))); + channels.push(AnyChannel::new("B", FlatSamples::F32(vec![0.2; w * h]))); + channels.push(AnyChannel::new("A", FlatSamples::F32(vec![1.0; w * h]))); + channels.push(AnyChannel::new("Z", FlatSamples::F32(z_expected.clone()))); + let image = Image::from_layer(Layer::new( + Vec2(w, h), + LayerAttributes::default(), + Encoding::UNCOMPRESSED, + AnyChannels::sort(channels), + )); + let dir = std::env::temp_dir().join(format!("fission_loader_exr_z_{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let exr_path = dir.join("z_plate.exr"); + image.write().to_file(&exr_path).expect("write synthetic Z EXR"); + + let comp_src = format!( + r#"Composition {{ + CurrentTime = 0, + RenderRange = {{ 0, 1 }}, + GlobalRange = {{ 0, 1 }}, + Tools = ordered() {{ + L = Loader {{ + Clips = {{ Clip {{ ID = "Clip1", Filename = "{}", Length = 1, GlobalStart = 0, GlobalEnd = 0, }} }}, + }}, + }}, + }}"#, + exr_path.display() + ); + let comp = Comp::from_fusion_str(&comp_src).expect("parse EXR Loader comp"); + let Ok(mut eng) = Engine::new_headless() else { + let _ = std::fs::remove_dir_all(&dir); + return; + }; + let (tex, _) = eng.evaluate(&comp, comp.find_node("L").unwrap(), 0.0); + let aux = tex.aux.as_ref().expect("Loader must attach aux for EXR with Z channel"); + let z_tex = aux.z.as_ref().expect("aux.z must be present"); + assert_eq!(z_tex.size, [w as u32, h as u32]); + assert_eq!(z_tex.format, wgpu::TextureFormat::R32Float); + + let unpadded_bpr = (w as u32) * 4; + let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let padded_bpr = unpadded_bpr.div_ceil(align) * align; + let buf = eng.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("readback-exr-z"), + size: u64::from(padded_bpr) * u64::from(h as u32), + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut enc = eng.device.create_command_encoder(&Default::default()); + enc.copy_texture_to_buffer( + z_tex.texture.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &buf, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(padded_bpr), + rows_per_image: Some(h as u32), + }, + }, + wgpu::Extent3d { width: w as u32, height: h as u32, depth_or_array_layers: 1 }, + ); + eng.queue.submit(Some(enc.finish())); + let slice = buf.slice(..); + let (tx, rx) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |res| { + let _ = tx.send(res); + }); + eng.device + .poll(wgpu::PollType::Wait { + submission_index: None, + timeout: Some(std::time::Duration::from_secs(10)), + }) + .unwrap(); + rx.recv().unwrap().unwrap(); + let data = slice.get_mapped_range().unwrap(); + let mut got = Vec::with_capacity(w * h); + for y in 0..h { + let start = y * padded_bpr as usize; + let row_bytes = &data[start..start + unpadded_bpr as usize]; + got.extend_from_slice(bytemuck::cast_slice::(row_bytes)); + } + drop(data); + buf.unmap(); + let _ = std::fs::remove_dir_all(&dir); + + assert_eq!(got, z_expected, "Loader aux.z must match exact EXR float32 depth values"); + } } diff --git a/crates/engine/src/eval/text_3d.rs b/crates/engine/src/eval/text_3d.rs index 150fc8b03cabfb181fe1960643df7d0697b02b44..8ad723a313eab508a921a15d620f047b60f07320 100644 --- a/crates/engine/src/eval/text_3d.rs +++ b/crates/engine/src/eval/text_3d.rs @@ -881,9 +881,15 @@ impl Engine { let (size, tex_scale) = crate::cache::clamp_dims_to_limit(raw_size[0], raw_size[1], max_dim); let aspect = (size[0] as f32 / size[1].max(1) as f32).max(1e-4); + let want_z = comp.eval_number(node, "RendererSoftware.Channels.Z", time, 0.0, &self.expr) >= 0.5 + || comp.eval_number(node, "RendererOpenGL.Channels.Z", time, 0.0, &self.expr) >= 0.5; + let want_normal = comp.eval_number(node, "RendererSoftware.Channels.Normal", time, 0.0, &self.expr) >= 0.5 + || comp.eval_number(node, "RendererOpenGL.Channels.Normal", time, 0.0, &self.expr) >= 0.5; + let Some(scene_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else { let mut empty = create_texture(&self.device, size, 0); empty.tex_scale = tex_scale; + crate::scene3d::Scene3DRenderer::attach_empty_aux(&self.device, &self.queue, &mut empty, want_z, want_normal); return empty; }; @@ -921,6 +927,7 @@ impl Engine { if bad_clip { let mut empty = create_texture(&self.device, size, 0); empty.tex_scale = tex_scale; + crate::scene3d::Scene3DRenderer::attach_empty_aux(&self.device, &self.queue, &mut empty, want_z, want_normal); return empty; } let v = crate::scene3d::mat4_inverse(cam.world); @@ -962,6 +969,8 @@ impl Engine { 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.push(if want_z { 1.0 } else { 0.0 }); + hash_floats.push(if want_normal { 1.0 } else { 0.0 }); hash_floats.extend_from_slice(&lights.ambient); hash_floats.push(lights.count as f32); for dl in &lights.dirs { @@ -1126,19 +1135,22 @@ impl Engine { let mut dst = create_texture(&self.device, size, key); dst.tex_scale = tex_scale; - self.scene3d.render_meshes( + self.scene3d.render_meshes_with_aux( &self.device, &self.queue, enc, - &dst, + &mut dst, &self.dummy, view_proj, view, + proj, cam_pos, cam_far, lights, lighting_enabled, shadows_enabled, + want_z, + want_normal, &draw_meshes, ); self.cache.insert(key, dst.clone(), node.id, frame_i); diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 5dc06c93abb5a4de47b03d5d548a5888a20573f2..c359ed7f47c95de21d8c1f4364b36d08ea2ff5ac 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -53,6 +53,9 @@ pub struct DecodedImage { /// Optional unclamped linear HDR RGBA32F pixels (`[r, g, b, a, ...]`, top-down), /// populated for OpenEXR images to preserve HDR highlights `> 1.0` and negative values. pub rgba_f32: Option>>, + /// Optional single-channel `f32` Z-depth buffer (`[w * h]`, top-down), populated when + /// an OpenEXR file contains a `Z` channel (`"Z"`, `"z"`, or `"*.Z"`). + pub z_f32: Option>>, } impl DecodedImage { @@ -66,7 +69,11 @@ impl DecodedImage { .rgba_f32 .as_ref() .map_or(0, |v| (v.len() * std::mem::size_of::()) as u64); - u8_bytes + f16_bytes + f32_bytes + let z_bytes = self + .z_f32 + .as_ref() + .map_or(0, |v| (v.len() * std::mem::size_of::()) as u64); + u8_bytes + f16_bytes + f32_bytes + z_bytes } } @@ -822,6 +829,7 @@ impl MediaCache { rgba: Arc::new(raw), rgba_f16: None, rgba_f32: None, + z_f32: None, }; let unthrottled = if let Ok(mut state) = self.shared.state.lock() { diff --git a/crates/engine/src/media/exr.rs b/crates/engine/src/media/exr.rs index 2ceb7f0e259bb7dd7c5461d57bae55da424d6d84..74ab48a299cee63533e105cdd38173787f4e4794 100644 --- a/crates/engine/src/media/exr.rs +++ b/crates/engine/src/media/exr.rs @@ -176,6 +176,47 @@ pub(super) fn find_exr_channel_loc( None } +/// Finds a `Z` depth channel (`"Z"`, `"z"`, or ending in `".Z"`/`".z"`, e.g. `"depth.Z"`) +/// in a layer matching `(w, h)`. Exact `"Z"`/`"z"` takes priority over suffixed channels. +fn find_exr_z_loc( + headers: &[::exr::meta::header::Header], + w: usize, + h: usize, +) -> Option<(usize, usize)> { + let valid_layer = |header: &::exr::meta::header::Header| { + !header.deep && header.layer_size.width() == w && header.layer_size.height() == h + }; + let is_suffixed_z = |full: &str| { + full.contains('.') + && full + .rsplit('.') + .next() + .is_some_and(|s| s.eq_ignore_ascii_case("z")) + }; + let matchers: [&dyn Fn(&str) -> bool; 2] = [ + &|full: &str| full.eq_ignore_ascii_case("z"), + &is_suffixed_z, + ]; + for pred in matchers { + for (li, header) in headers.iter().enumerate() { + if !valid_layer(header) { + continue; + } + let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string()); + for (ci, ch) in header.channels.list.iter().enumerate() { + if ch.sampling != ::exr::math::Vec2(1, 1) { + continue; + } + let full = full_exr_channel_name(lname.as_deref(), &ch.name.to_string()); + if pred(&full) { + return Some((li, ci)); + } + } + } + } + None +} + /// Decodes a single-layer or multi-layer (Blender `ViewLayer.Combined.R/G/B/A`) OpenEXR /// selectively for only the matched RGBA channels, producing clamped RGBA8 and linear HDR /// RGBA16F/RGBA32F buffers without decoding unrelated AOV/Cryptomatte layers. @@ -332,15 +373,29 @@ fn decode_exr_from( let g_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, green_name, "G", "g"); let b_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, blue_name, "B", "b"); let a_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, alpha_name, "A", "a"); + let z_loc = find_exr_z_loc(chunks_reader.headers(), w, h); let target_locs = [Some(r_loc), g_loc, b_loc, a_loc]; - let mut needed_layers: Vec = target_locs.iter().flatten().map(|(l, _)| *l).collect(); + let mut needed_layers: Vec = target_locs + .iter() + .chain(std::iter::once(&z_loc)) + .flatten() + .map(|(l, _)| *l) + .collect(); needed_layers.sort_unstable(); needed_layers.dedup(); let mut raw_f32 = Vec::new(); raw_f32.try_reserve_exact(elem_count).ok()?; raw_f32.resize(elem_count, 0.0_f32); + let mut z_raw_f32 = if z_loc.is_some() { + let mut v = Vec::new(); + v.try_reserve_exact(pixel_count).ok()?; + v.resize(pixel_count, crate::cache::EMPTY_Z_SENTINEL); + Some(v) + } else { + None + }; let mut line_f32 = Vec::::new(); let mut line_f16 = Vec::::new(); let mut line_u32 = Vec::::new(); @@ -360,7 +415,8 @@ fn decode_exr_from( comp_mask[c] = true; } } - if !comp_mask.iter().any(|&m| m) { + let write_z = z_loc == Some(loc); + if !comp_mask.iter().any(|&m| m) && !write_z { continue; } let y = line.location.position.y(); @@ -388,13 +444,27 @@ fn decode_exr_from( } } - let row_base = (y * w + x0) * 4; - for (dx, &sample) in line_f32.iter().enumerate() { - let val = if sample.is_nan() { 0.0 } else { sample }; - let px_off = row_base + dx * 4; - for (c, &enabled) in comp_mask.iter().enumerate() { - if enabled { - raw_f32[px_off + c] = val; + if comp_mask.iter().any(|&m| m) { + let row_base = (y * w + x0) * 4; + for (dx, &sample) in line_f32.iter().enumerate() { + let val = if sample.is_nan() { 0.0 } else { sample }; + let px_off = row_base + dx * 4; + for (c, &enabled) in comp_mask.iter().enumerate() { + if enabled { + raw_f32[px_off + c] = val; + } + } + } + } + if write_z { + if let Some(ref mut z_vec) = z_raw_f32 { + let z_row_base = y * w + x0; + for (dx, &sample) in line_f32.iter().enumerate() { + z_vec[z_row_base + dx] = if sample.is_nan() { + crate::cache::EMPTY_Z_SENTINEL + } else { + sample + }; } } } @@ -428,6 +498,7 @@ fn decode_exr_from( rgba: Arc::new(raw), rgba_f16: Some(Arc::new(raw_f16)), rgba_f32: Some(Arc::new(raw_f32)), + z_f32: z_raw_f32.map(Arc::new), }) } @@ -518,4 +589,56 @@ mod tests { assert_eq!(par_bits, seq_bits, "f32 bits mismatch for ({has_g},{has_b},{has_a},{post_multiply})"); } } + + #[test] + fn exr_decodes_z_channel_and_suffixed_z_with_nan_fallback() { + use ::exr::prelude::*; + + let write_exr = |z_chan_name: Option<&str>, z_vals: &[f32]| -> Vec { + let size = Vec2(3usize, 2usize); + let mut channels = SmallVec::<[AnyChannel; 4]>::new(); + let rgba = [1.0_f32, 0.5, 0.25, 1.0]; + for (name, val) in [("R", rgba[0]), ("G", rgba[1]), ("B", rgba[2]), ("A", rgba[3])] { + channels.push(AnyChannel::new(name, FlatSamples::F32(vec![val; 6]))); + } + if let Some(zn) = z_chan_name { + channels.push(AnyChannel::new(zn, FlatSamples::F32(z_vals.to_vec()))); + } + let image = Image::from_layer(Layer::new( + size, + LayerAttributes::default(), + Encoding::UNCOMPRESSED, + AnyChannels::sort(channels), + )); + let mut buf = std::io::Cursor::new(Vec::new()); + image.write().to_buffered(&mut buf).unwrap(); + buf.into_inner() + }; + + // 1. EXR without Z channel -> z_f32 is None. + let no_z = write_exr(None, &[]); + assert!(MediaCache::insert_virtual_bytes("vexr_z/no_z.exr", no_z)); + let dec_no_z = decode_exr_rgba(Path::new("vexr_z/no_z.exr"), None, None, None, None, false, true).unwrap(); + assert!(dec_no_z.z_f32.is_none()); + + // 2. EXR with bare "Z" channel including NaN -> NaN mapped to EMPTY_Z_SENTINEL. + let z_expected = [-2.5_f32, -3.0, -4.25, f32::NAN, -10.0, crate::cache::EMPTY_Z_SENTINEL]; + let with_z = write_exr(Some("Z"), &z_expected); + assert!(MediaCache::insert_virtual_bytes("vexr_z/with_z.exr", with_z)); + let dec_z = decode_exr_rgba(Path::new("vexr_z/with_z.exr"), None, None, None, None, false, true).unwrap(); + let got_z = dec_z.z_f32.expect("z_f32 populated"); + assert_eq!( + got_z.as_slice(), + &[-2.5_f32, -3.0, -4.25, crate::cache::EMPTY_Z_SENTINEL, -10.0, crate::cache::EMPTY_Z_SENTINEL] + ); + + // 3. EXR with suffixed "depth.Z" channel -> also decoded into z_f32. + let depth_z = write_exr(Some("depth.Z"), &[-1.5, -2.0, -2.5, -3.0, -3.5, -4.0]); + assert!(MediaCache::insert_virtual_bytes("vexr_z/depth_z.exr", depth_z)); + let dec_dz = decode_exr_rgba(Path::new("vexr_z/depth_z.exr"), None, None, None, None, false, false).unwrap(); + assert_eq!( + dec_dz.z_f32.expect("depth.Z populated").as_slice(), + &[-1.5, -2.0, -2.5, -3.0, -3.5, -4.0] + ); + } } diff --git a/crates/engine/src/media/png.rs b/crates/engine/src/media/png.rs index b61109f7ae23de067013d00d1847c5957e9bbfaf..bc0c59438f9c87e99df8bb66905a6bbf78eede67 100644 --- a/crates/engine/src/media/png.rs +++ b/crates/engine/src/media/png.rs @@ -246,5 +246,6 @@ pub(super) fn decode_raster_image( rgba: Arc::new(raw), rgba_f16: None, rgba_f32: None, + z_f32: None, }) } diff --git a/crates/engine/src/media/prefetch.rs b/crates/engine/src/media/prefetch.rs index 078a6b56e0bed815822d445e0eb85c8ae899ec78..de4cd225dbd4a4914e3fbf05b1585b1b3958be02 100644 --- a/crates/engine/src/media/prefetch.rs +++ b/crates/engine/src/media/prefetch.rs @@ -282,6 +282,7 @@ impl MediaCache { rgba: Arc::new(raw), rgba_f16: None, rgba_f32: None, + z_f32: None, }; let unthrottled = if let Ok(mut state) = self.shared.state.lock() { state.in_flight.remove(&key); @@ -719,6 +720,7 @@ impl MediaPrefetchHandle { rgba: Arc::new(raw), rgba_f16: None, rgba_f32: None, + z_f32: None, }; let unthrottled = if let Ok(mut state) = shared.state.lock() { state.in_flight.remove(&key); diff --git a/crates/engine/src/media/tests.rs b/crates/engine/src/media/tests.rs index 30ff9862dc8e375a60f7337c6adb896e37b0d77d..54ef68963467d6f598cbbedd67111bb98022f3dc 100644 --- a/crates/engine/src/media/tests.rs +++ b/crates/engine/src/media/tests.rs @@ -1180,6 +1180,7 @@ Tools = ordered() {{ rgba: Arc::clone(&four_mb), rgba_f16: None, rgba_f32: None, + z_f32: None, }; cache.shared.insert_cached_locked(&mut state, key, img); } diff --git a/crates/engine/src/scene3d/mod.rs b/crates/engine/src/scene3d/mod.rs index c38fae1f1d7b137313a36eb89ab4e60c4a907651..7458db5ec3ae5fcf3e9c3674d32f7069c3de354d 100644 --- a/crates/engine/src/scene3d/mod.rs +++ b/crates/engine/src/scene3d/mod.rs @@ -26,10 +26,13 @@ fn lock_or_recover(m: &Mutex) -> MutexGuard<'_, T> { m.lock().unwrap_or_else(|e| e.into_inner()) } -use crate::cache::CachedTexture; +use crate::cache::{AuxChannelTex, AuxChannels, CachedTexture, EMPTY_Z_SENTINEL}; 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, UV_XFORM_WGSL}; +use shader::{ + DepthToEyeZUniform, MeshUniform, ShadowUniform, DEPTH_TO_EYE_Z_SHADER, 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 @@ -38,6 +41,11 @@ pub struct Scene3DRenderer { /// `[triangles, lines][back-facing, front-facing]`; back faces draw first so translucent /// faces show the inside of closed meshes. pipelines: [[wgpu::RenderPipeline; 2]; 2], + /// Normal-channel pass `[triangles, lines][back-facing, front-facing]` writing `Rgba16Float`. + normal_pipelines: [[wgpu::RenderPipeline; 2]; 2], + /// Compute pass converting `Depth32Float` into eye-space `Z` (`R32Float`). + depth_z_bgl: wgpu::BindGroupLayout, + depth_z_pipeline: wgpu::ComputePipeline, sampler: wgpu::Sampler, meshes: Mutex>>, /// Memoized CPU `Text3D` extruded meshes keyed by deterministic geometry content hash. @@ -708,46 +716,130 @@ impl Scene3DRenderer { wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 24, shader_location: 2 }, ], }; - let make_pipeline = |topology: wgpu::PrimitiveTopology, back_pass: bool| device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("scene3d-mesh"), - layout: Some(&pl), - vertex: wgpu::VertexState { - module: &shader, - entry_point: Some("vs_mesh"), - compilation_options: Default::default(), - buffers: &[Some(vbuf_layout.clone())], - }, - fragment: Some(wgpu::FragmentState { - module: &shader, - entry_point: Some("fs_mesh"), - compilation_options: wgpu::PipelineCompilationOptions { - constants: &[("BACK_PASS", if back_pass { 1.0 } else { 0.0 })], + let make_pipeline = |topology: wgpu::PrimitiveTopology, + back_pass: bool, + fs_entry: &'static str, + target_format: wgpu::TextureFormat, + blend: Option| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("scene3d-mesh"), + layout: Some(&pl), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_mesh"), + compilation_options: Default::default(), + buffers: &[Some(vbuf_layout.clone())], + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some(fs_entry), + compilation_options: wgpu::PipelineCompilationOptions { + constants: &[("BACK_PASS", if back_pass { 1.0 } else { 0.0 })], + ..Default::default() + }, + targets: &[Some(wgpu::ColorTargetState { + format: target_format, + blend, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + primitive: wgpu::PrimitiveState { + topology, + cull_mode: None, ..Default::default() }, - targets: &[Some(wgpu::ColorTargetState { - format: wgpu::TextureFormat::Rgba8Unorm, - blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), - write_mask: wgpu::ColorWrites::ALL, - })], - }), - primitive: wgpu::PrimitiveState { - topology, - cull_mode: None, - ..Default::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, - }); + 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 pipelines = [wgpu::PrimitiveTopology::TriangleList, wgpu::PrimitiveTopology::LineList] - .map(|topology| [make_pipeline(topology, true), make_pipeline(topology, false)]); + .map(|topology| { + [ + make_pipeline( + topology, + true, + "fs_mesh", + wgpu::TextureFormat::Rgba8Unorm, + Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), + ), + make_pipeline( + topology, + false, + "fs_mesh", + wgpu::TextureFormat::Rgba8Unorm, + Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), + ), + ] + }); + let normal_pipelines = [wgpu::PrimitiveTopology::TriangleList, wgpu::PrimitiveTopology::LineList] + .map(|topology| { + [ + make_pipeline(topology, true, "fs_normal", wgpu::TextureFormat::Rgba16Float, None), + make_pipeline(topology, false, "fs_normal", wgpu::TextureFormat::Rgba16Float, None), + ] + }); + let depth_z_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("scene3d-depth-z-shader"), + source: wgpu::ShaderSource::Wgsl(DEPTH_TO_EYE_Z_SHADER.into()), + }); + let depth_z_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("scene3d-depth-z-bgl"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Depth, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::WriteOnly, + format: wgpu::TextureFormat::R32Float, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: std::num::NonZeroU64::new( + std::mem::size_of::() as u64, + ), + }, + count: None, + }, + ], + }); + let depth_z_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("scene3d-depth-z-pl"), + bind_group_layouts: &[Some(&depth_z_bgl)], + immediate_size: 0, + }); + let depth_z_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("scene3d-depth-to-eye-z"), + layout: Some(&depth_z_pl), + module: &depth_z_shader, + entry_point: Some("depth_to_eye_z"), + compilation_options: Default::default(), + cache: None, + }); let sampler = device.create_sampler(&wgpu::SamplerDescriptor { label: Some("scene3d-linear"), address_mode_u: wgpu::AddressMode::ClampToEdge, @@ -849,6 +941,9 @@ impl Scene3DRenderer { Self { bgl, pipelines, + normal_pipelines, + depth_z_bgl, + depth_z_pipeline, sampler, meshes: Mutex::new(Lru::with_byte_cap( MAX_CACHED_MESH_BUFFERS, @@ -937,6 +1032,61 @@ impl Scene3DRenderer { lock_or_recover(&self.meshes).entries.len() } + /// Attaches empty sky auxiliary channels (`EMPTY_Z_SENTINEL` for Z, `(0,0,0,0)` for Normal) + /// when a `Renderer3D` exits early (e.g. disconnected `SceneInput` or invalid clip planes). + pub fn attach_empty_aux( + device: &wgpu::Device, + queue: &wgpu::Queue, + dst: &mut CachedTexture, + want_z: bool, + want_normal: bool, + ) { + if !want_z && !want_normal { + return; + } + let size = [dst.size[0].max(1), dst.size[1].max(1)]; + let mut aux = dst.aux_cloned(); + if want_z { + let z_tex = AuxChannelTex::new(device, size, wgpu::TextureFormat::R32Float, "scene3d-aux-z"); + let data = vec![EMPTY_Z_SENTINEL; (z_tex.size[0] as usize) * (z_tex.size[1] as usize)]; + queue.write_texture( + z_tex.texture.as_image_copy(), + bytemuck::cast_slice(&data), + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(z_tex.size[0] * 4), + rows_per_image: Some(z_tex.size[1]), + }, + wgpu::Extent3d { + width: z_tex.size[0], + height: z_tex.size[1], + depth_or_array_layers: 1, + }, + ); + aux.z = Some(z_tex); + } + if want_normal { + let normal_tex = AuxChannelTex::new(device, size, wgpu::TextureFormat::Rgba16Float, "scene3d-aux-normal"); + let data = vec![0u16; (normal_tex.size[0] as usize) * (normal_tex.size[1] as usize) * 4]; + queue.write_texture( + normal_tex.texture.as_image_copy(), + bytemuck::cast_slice(&data), + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(normal_tex.size[0] * 8), + rows_per_image: Some(normal_tex.size[1]), + }, + wgpu::Extent3d { + width: normal_tex.size[0], + height: normal_tex.size[1], + depth_or_array_layers: 1, + }, + ); + aux.normal = Some(normal_tex); + } + dst.set_aux(Some(Arc::new(aux))); + } + #[allow(clippy::too_many_arguments)] pub fn render_meshes( &self, @@ -954,6 +1104,95 @@ impl Scene3DRenderer { shadows_enabled: bool, meshes: &[DrawMesh], ) { + let _ = self.render_meshes_inner( + device, + queue, + enc, + dst, + dummy, + view_proj, + view, + mat4_identity(), + cam_pos, + cam_far, + lights, + lighting_enabled, + shadows_enabled, + false, + false, + meshes, + ); + } + + #[allow(clippy::too_many_arguments)] + pub fn render_meshes_with_aux( + &self, + device: &wgpu::Device, + queue: &wgpu::Queue, + enc: &mut wgpu::CommandEncoder, + dst: &mut CachedTexture, + dummy: &CachedTexture, + view_proj: Mat4, + view: Mat4, + proj: Mat4, + cam_pos: [f32; 3], + cam_far: f32, + lights: SceneLights, + lighting_enabled: bool, + shadows_enabled: bool, + want_z: bool, + want_normal: bool, + meshes: &[DrawMesh], + ) { + if let Some(aux) = self.render_meshes_inner( + device, + queue, + enc, + dst, + dummy, + view_proj, + view, + proj, + cam_pos, + cam_far, + lights, + lighting_enabled, + shadows_enabled, + want_z, + want_normal, + meshes, + ) { + let mut merged = dst.aux_cloned(); + if aux.z.is_some() { + merged.z = aux.z; + } + if aux.normal.is_some() { + merged.normal = aux.normal; + } + dst.set_aux(Some(Arc::new(merged))); + } + } + + #[allow(clippy::too_many_arguments)] + fn render_meshes_inner( + &self, + device: &wgpu::Device, + queue: &wgpu::Queue, + enc: &mut wgpu::CommandEncoder, + dst: &CachedTexture, + dummy: &CachedTexture, + view_proj: Mat4, + view: Mat4, + proj: Mat4, + cam_pos: [f32; 3], + cam_far: f32, + lights: SceneLights, + lighting_enabled: bool, + shadows_enabled: bool, + want_z: bool, + want_normal: bool, + meshes: &[DrawMesh], + ) -> Option { let depth_size = [dst.size[0].max(1), dst.size[1].max(1)]; let depth_target = lock_or_recover(&self.depth_targets).get_or_insert_with(depth_size, || { let tex = device.create_texture(&wgpu::TextureDescriptor { @@ -967,7 +1206,7 @@ impl Scene3DRenderer { sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Depth32Float, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, view_formats: &[], }); let view = tex.create_view(&wgpu::TextureViewDescriptor::default()); @@ -1407,7 +1646,7 @@ impl Scene3DRenderer { view: depth_view, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), - store: wgpu::StoreOp::Discard, + store: if want_z { wgpu::StoreOp::Store } else { wgpu::StoreOp::Discard }, }), stencil_ops: None, }), @@ -1426,6 +1665,102 @@ impl Scene3DRenderer { } } } + drop(pass); + + if !want_z && !want_normal { + return None; + } + + let mut aux = AuxChannels::default(); + if want_z { + let z_tex = AuxChannelTex::new(device, depth_size, wgpu::TextureFormat::R32Float, "scene3d-aux-z"); + let depth_z_uni = DepthToEyeZUniform { + proj_zw: [proj[10], proj[11], proj[14], proj[15]], + params: [EMPTY_Z_SENTINEL, 0.0, 0.0, 0.0], + }; + let depth_z_ubuf = cached_uniform_buffer( + &self.uniform_cache, + device, + "scene3d-depth-z-u", + bytemuck::bytes_of(&depth_z_uni), + ); + let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("scene3d-depth-z-bg"), + layout: &self.depth_z_bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(depth_view) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&z_tex.view) }, + wgpu::BindGroupEntry { binding: 2, resource: depth_z_ubuf.as_entire_binding() }, + ], + }); + let mut cpass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("scene3d-depth-to-eye-z"), + timestamp_writes: None, + }); + cpass.set_pipeline(&self.depth_z_pipeline); + cpass.set_bind_group(0, &bg, &[]); + cpass.dispatch_workgroups(z_tex.size[0].div_ceil(8), z_tex.size[1].div_ceil(8), 1); + aux.z = Some(z_tex); + } + + if want_normal { + let normal_raw = device.create_texture(&wgpu::TextureDescriptor { + label: Some("scene3d-aux-normal"), + size: wgpu::Extent3d { + width: depth_size[0], + height: depth_size[1], + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba16Float, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::COPY_SRC + | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let normal_tex = AuxChannelTex::from_texture(normal_raw, depth_size); + let mut npass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("scene3d-normal-pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &normal_tex.view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: 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, + }); + for d in &draw_items { + npass.set_bind_group(0, &d.bg, &[d.uni_offset]); + npass.set_vertex_buffer(0, d.vbuf.slice(..)); + npass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32); + for (pipeline, culled) in self.normal_pipelines[d.wireframe as usize].iter().zip(d.cull) { + if !culled { + npass.set_pipeline(pipeline); + npass.draw_indexed(0..d.idx_count, 0, 0..1); + } + } + } + drop(npass); + aux.normal = Some(normal_tex); + } + + Some(aux) } } @@ -2145,4 +2480,141 @@ mod tests { assert_eq!(renderer.uniform_vram_bytes(), 0); assert_eq!(renderer.mesh_vram_bytes(), 0); } + + fn readback_aux_tex(eng: &Engine, aux: &AuxChannelTex, bpp: u32) -> Vec { + let [w, h] = aux.size; + let unpadded_bpr = w * bpp; + let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let padded_bpr = unpadded_bpr.div_ceil(align) * align; + let buf = eng.device().create_buffer(&wgpu::BufferDescriptor { + label: Some("readback-aux"), + size: u64::from(padded_bpr) * u64::from(h), + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut enc = eng.device().create_command_encoder(&Default::default()); + enc.copy_texture_to_buffer( + aux.texture.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &buf, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(padded_bpr), + rows_per_image: Some(h), + }, + }, + wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, + ); + eng.queue().submit(Some(enc.finish())); + let slice = buf.slice(..); + let (tx, rx) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |res| { + let _ = tx.send(res); + }); + eng.device() + .poll(wgpu::PollType::Wait { + submission_index: None, + timeout: Some(std::time::Duration::from_secs(10)), + }) + .unwrap(); + rx.recv().unwrap().unwrap(); + let data = slice.get_mapped_range().unwrap(); + let mut out = Vec::with_capacity((unpadded_bpr * h) as usize); + for y in 0..h as usize { + let start = y * padded_bpr as usize; + out.extend_from_slice(&data[start..start + unpadded_bpr as usize]); + } + drop(data); + buf.unmap(); + out + } + + #[test] + fn renderer3d_z_and_normal_aux_channels_match_fusion_convention() { + let make_comp = |proj_type: &str, ch_z: u8, ch_n: u8| -> Comp { + let src = format!( + r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ + Flat = MtlBlinn {{ Inputs = {{ ["Specular.Intensity"] = Input {{ Value = 0, }}, }}, }}, + P = Shape3D {{ Inputs = {{ + ["SurfacePlaneInputs.Width"] = Input {{ Value = 0.5, }}, + ["SurfacePlaneInputs.Height"] = Input {{ Value = 0.5, }}, + ["Transform3DOp.Translate.Z"] = Input {{ Value = -1.0, }}, + MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, + }}, }}, + Cam = Camera3D {{ Inputs = {{ + ProjectionType = Input {{ Value = FuID {{ "{proj_type}" }}, }}, + ["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, + ApertureW = Input {{ Value = 1.0, }}, + ApertureH = Input {{ Value = 1.0, }}, + }}, }}, + M = Merge3D {{ Inputs = {{ + SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, + SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }}, + }}, }}, + R = Renderer3D {{ Inputs = {{ + Width = Input {{ Value = 64, }}, + Height = Input {{ Value = 64, }}, + ["RendererSoftware.Channels.Z"] = Input {{ Value = {ch_z}, }}, + ["RendererSoftware.Channels.Normal"] = Input {{ Value = {ch_n}, }}, + SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, + }}, }}, + }} }}"# + ); + Comp::from_fusion_str(&src).expect("parse Z/Normal comp") + }; + + let Ok(mut eng) = Engine::new_headless() else { return }; + + // 1. Both channels disabled -> zero aux allocation (`aux == None`). + let comp_off = make_comp("Perspective", 0, 0); + let (tex_off, _) = eng.evaluate(&comp_off, comp_off.find_node("R").unwrap(), 0.0); + assert!(tex_off.aux.is_none(), "aux must stay None when Z and Normal are disabled"); + + // 2. Perspective & Orthographic cameras both yield Z = -3.0 at center and EMPTY_Z_SENTINEL at corner. + for proj_type in ["Perspective", "Orthographic"] { + let comp = make_comp(proj_type, 1, 1); + let r_id = comp.find_node("R").unwrap(); + let (tex, _) = eng.evaluate(&comp, r_id, 0.0); + let aux = tex.aux.as_ref().expect("aux channels must be attached"); + let z_tex = aux.z.as_ref().expect("aux.z must be present"); + let n_tex = aux.normal.as_ref().expect("aux.normal must be present"); + assert_eq!(z_tex.format, wgpu::TextureFormat::R32Float); + assert_eq!(n_tex.format, wgpu::TextureFormat::Rgba16Float); + + let z_bytes = readback_aux_tex(&eng, z_tex, 4); + let z_vals: &[f32] = bytemuck::cast_slice(&z_bytes); + let center_z = z_vals[32 * 64 + 32]; + let corner_z = z_vals[0]; + assert!( + (center_z - (-3.0)).abs() <= 1e-3, + "{proj_type} center Z should be -3.0, got {center_z}" + ); + assert_eq!( + corner_z, EMPTY_Z_SENTINEL, + "{proj_type} empty corner Z should be EMPTY_Z_SENTINEL, got {corner_z}" + ); + + let n_bytes = readback_aux_tex(&eng, n_tex, 8); + let read_n = |x: usize, y: usize| -> [f32; 4] { + let off = (y * 64 + x) * 8; + [ + ::exr::prelude::f16::from_bits(u16::from_le_bytes([n_bytes[off], n_bytes[off + 1]])).to_f32(), + ::exr::prelude::f16::from_bits(u16::from_le_bytes([n_bytes[off + 2], n_bytes[off + 3]])).to_f32(), + ::exr::prelude::f16::from_bits(u16::from_le_bytes([n_bytes[off + 4], n_bytes[off + 5]])).to_f32(), + ::exr::prelude::f16::from_bits(u16::from_le_bytes([n_bytes[off + 6], n_bytes[off + 7]])).to_f32(), + ] + }; + let cn = read_n(32, 32); + let kn = read_n(0, 0); + assert!( + cn[0].abs() <= 1e-3 && cn[1].abs() <= 1e-3 && (cn[2] - 1.0).abs() <= 1e-3 && cn[3].abs() <= 1e-3, + "{proj_type} center normal should be (0,0,1,0), got {cn:?}" + ); + assert_eq!(kn, [0.0, 0.0, 0.0, 0.0], "{proj_type} corner normal should be zero"); + } + + // 3. Toggling Channels.Z on an existing comp updates cache key cleanly. + let (tex_cached_off, _) = eng.evaluate(&make_comp("Perspective", 0, 0), comp_off.find_node("R").unwrap(), 0.0); + assert!(tex_cached_off.aux.is_none()); + } } diff --git a/crates/engine/src/scene3d/shader.rs b/crates/engine/src/scene3d/shader.rs index 9eb4bc1672eb402bc0bd29437c86efaac307b627..23f54575aa15f2ad94fc644d23d22049fae1a5a2 100644 --- a/crates/engine/src/scene3d/shader.rs +++ b/crates/engine/src/scene3d/shader.rs @@ -79,6 +79,49 @@ pub(super) struct ShadowUniform { pub(super) point: [[f32; 4]; MAX_LIGHTS], } +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +pub(super) struct DepthToEyeZUniform { + /// `[P[2][2], P[2][3], P[3][2], P[3][3]]` from the camera projection matrix. + pub(super) proj_zw: [f32; 4], + /// `[EMPTY_Z_SENTINEL, 0.0, 0.0, 0.0]`. + pub(super) params: [f32; 4], +} + +/// Compute shader converting `Depth32Float` NDC depth (`[0, 1]`) into exact eye-space `Z` +/// (`R32Float`, negative in front of camera, `EMPTY_Z_SENTINEL` on empty sky pixels). +pub(super) const DEPTH_TO_EYE_Z_SHADER: &str = r#" +struct DepthToEyeZParams { + proj_zw: vec4, + params: vec4, +}; + +@group(0) @binding(0) var depth_tex: texture_depth_2d; +@group(0) @binding(1) var out_z: texture_storage_2d; +@group(0) @binding(2) var u: DepthToEyeZParams; + +@compute @workgroup_size(8, 8, 1) +fn depth_to_eye_z(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(out_z); + if (gid.x >= dims.x || gid.y >= dims.y) { + return; + } + let d = textureLoad(depth_tex, vec2(gid.xy), 0); + var z_eye = u.params.x; + if (d < 1.0 - 1e-6) { + let p22 = u.proj_zw.x; + let p23 = u.proj_zw.y; + let p32 = u.proj_zw.z; + let p33 = u.proj_zw.w; + let denom = p22 - d * p23; + if (abs(denom) > 1e-12) { + z_eye = (d * p33 - p32) / denom; + } + } + textureStore(out_z, vec2(gid.xy), vec4(z_eye, 0.0, 0.0, 0.0)); +} +"#; + /// 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 wrap_uv_only(uv_in: vec2, wrap_f: f32) -> vec2 { @@ -517,4 +560,56 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4 { } return col; } + +@fragment +fn fs_normal(in: VsOut) -> @location(0) vec4 { + let uv_xformed = apply_uv_xform(in.uv, u.uv_xform, u.uv_off_wrap); + let uv_bump_xformed = apply_uv_xform(in.uv, u.bump_uv_xform, u.bump_off_wrap); + let dpdx_w = dpdx(in.world_pos); + let dpdy_w = dpdy(in.world_pos); + let duvdx = dpdx(uv_bump_xformed); + let duvdy = dpdy(uv_bump_xformed); + let facing_away = dot(in.world_n, u.cam_pos.xyz - in.world_pos) < 0.0; + if (facing_away != BACK_PASS) { + discard; + } + + var col = u.diffuse_col; + if (u.flags.x > 0.5) { + var uv_samp = uv_xformed; + if (u.dod.z > 0.5 && u.dod.w > 0.5) { + let tdims = vec2(textureDimensions(mat_tex)); + let canvas_px = vec2(uv_samp.x * u.dod.z, uv_samp.y * u.dod.w); + uv_samp = (canvas_px - u.dod.xy) / tdims; + if (uv_samp.x < 0.0 || uv_samp.x > 1.0 || uv_samp.y < 0.0 || uv_samp.y > 1.0) { + discard; + } + } + let tex_col = textureSampleLevel(mat_tex, mat_samp, uv_samp, 0.0); + col = select(tex_col, vec4(1.0), u.mat_fx.z > 0.5) * u.diffuse_col; + } + let out_alpha = col.a * u.mtl_params.x; + if (out_alpha <= 0.002) { + discard; + } + + let nlen = length(in.world_n); + var n = select(vec3(0.0, 0.0, 1.0), in.world_n / nlen, nlen > 1e-5); + if (u.bump_off_wrap.w > 0.5 && (u.mat_fx.y > 0.5 || abs(u.mat_fx.x) > 1e-5)) { + n = perturb_bump_normal( + n, + dpdx_w, + dpdy_w, + duvdx, + duvdy, + uv_bump_xformed, + u.mat_fx.x, + u.mat_fx.y, + u.bump_off_wrap.z, + u.bump_params.x, + i32(u.bump_params.y + 0.5), + ); + } + return vec4(n, 0.0); +} "#;