authoravatarclover caruso<git@paperclover.net>2026-12-01 13:12:51-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 13:31:51-08:00
logbdc13296e484339dfda2fee378da66be86175a75
treee91e1ad7e51f9ec435210cd41dced361d370a86b
parente5f36c175bc0257886e466e69dca1e6be2849baa
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

engine: dynamic uniform ring buffer, LUT texture cache, and bilinear Gaussian blur


5 files changed, 812 insertions(+), 132 deletions(-)

crates/engine/src/eval/blur_glow.rs+335-45
......@@ -130,6 +130,20 @@ impl Engine {
130130 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
131131 self.dispatch_op(enc, ShaderOp::Merge, &work_src.view, &small_blur.view, mv, &dst, &um);
132132 }
133 } else if rx < 0.25 {
134 let mut uv = UniformParams::default();
135 uv.p[0] = [0.0, 1.0, ry, mode];
136 uv.p[1] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, clamp_edges];
137 uv.p[2] = [1.0, 0.0, 0.0, 0.0];
138 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
139 self.dispatch_op(enc, ShaderOp::Blur, &work_src.view, &work_src.view, mv, &dst, &uv);
140 } else if ry < 0.25 {
141 let mut uh = UniformParams::default();
142 uh.p[0] = [1.0, 0.0, rx, mode];
143 uh.p[1] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, clamp_edges];
144 uh.p[2] = [1.0, 0.0, 0.0, 0.0];
145 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
146 self.dispatch_op(enc, ShaderOp::Blur, &work_src.view, &work_src.view, mv, &dst, &uh);
133147 } else {
134148 let tmp = self.alloc_tex(work_src.size, src.depth, 0);
135149 let mut uh = UniformParams::default();
......@@ -407,24 +421,34 @@ impl Engine {
407421 }
408422 }
409423
410 let tmp1 = self.alloc_tex(cur.size, src_tex.depth, 0);
411 let tmp2 = self.alloc_tex(cur.size, src_tex.depth, 0);
412 let mut uh = UniformParams::default();
413 uh.p[0] = [1.0, 0.0, rx_s, blur_mode];
414 uh.p[1] = [1.0, 0.0, 0.0, clamp_edges];
415 self.dispatch_op(enc, ShaderOp::Blur, &cur.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh);
424 let after_h = if rx_s >= 0.25 {
425 let tmp1 = self.alloc_tex(cur.size, src_tex.depth, 0);
426 let mut uh = UniformParams::default();
427 uh.p[0] = [1.0, 0.0, rx_s, blur_mode];
428 uh.p[1] = [1.0, 0.0, 0.0, clamp_edges];
429 self.dispatch_op(enc, ShaderOp::Blur, &cur.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh);
430 tmp1
431 } else {
432 cur
433 };
416434
417 let mut uv = UniformParams::default();
418 uv.p[0] = [0.0, 1.0, ry_s, blur_mode];
419 uv.p[1] = [1.0, 0.0, 0.0, clamp_edges];
420 self.dispatch_op(enc, ShaderOp::Blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv);
435 let blurred_cur = if ry_s >= 0.25 {
436 let tmp2 = self.alloc_tex(after_h.size, src_tex.depth, 0);
437 let mut uv = UniformParams::default();
438 uv.p[0] = [0.0, 1.0, ry_s, blur_mode];
439 uv.p[1] = [1.0, 0.0, 0.0, clamp_edges];
440 self.dispatch_op(enc, ShaderOp::Blur, &after_h.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv);
441 tmp2
442 } else {
443 after_h
444 };
421445
422446 if levels > 0 {
423447 let upscaled = self.alloc_tex(src_tex.size, src_tex.depth, 0);
424 self.dispatch_op(enc, ShaderOp::DisplayBlit, &tmp2.view, &self.dummy.view, &self.dummy.view, &upscaled, &u_blit);
448 self.dispatch_op(enc, ShaderOp::DisplayBlit, &blurred_cur.view, &self.dummy.view, &self.dummy.view, &upscaled, &u_blit);
425449 upscaled
426450 } else {
427 tmp2
451 blurred_cur
428452 }
429453 }
430454
......@@ -687,12 +711,22 @@ impl Engine {
687711 stats.nodes_evaluated += 1;
688712
689713 // 1. Preprocess glow source: Threshold -> Gain -> SrcSat -> GlowMask RGB multiply (verbatim MT_XGlow.fuse!)
690 let prep = self.alloc_tex(src.size, src.depth, 0);
691 let mut up = UniformParams::default();
692 up.p[0] = [t_lo, t_hi, src_sat, if glow_mask.is_some() { 1.0 } else { 0.0 }];
693 up.p[1] = [gain, 0.0, 0.0, 0.0];
694 let gmv = glow_mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
695 self.dispatch_op(enc, ShaderOp::XGlowPrep, &src.view, &self.dummy.view, gmv, &prep, &up);
714 let identity_prep = t_lo <= 1e-5
715 && t_hi <= 1e-5
716 && glow_mask.is_none()
717 && (gain - 1.0).abs() <= 1e-5
718 && (src_sat - 1.0).abs() <= 1e-5;
719 let prep = if identity_prep {
720 src.clone()
721 } else {
722 let prep = self.alloc_tex(src.size, src.depth, 0);
723 let mut up = UniformParams::default();
724 up.p[0] = [t_lo, t_hi, src_sat, if glow_mask.is_some() { 1.0 } else { 0.0 }];
725 up.p[1] = [gain, 0.0, 0.0, 0.0];
726 let gmv = glow_mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
727 self.dispatch_op(enc, ShaderOp::XGlowPrep, &src.view, &self.dummy.view, gmv, &prep, &up);
728 prep
729 };
696730
697731 // 2. Build mip pyramid matching MT_XGlow.fuse (1x, 1/2, 1/4, 1/8, 1/16)
698732 let mut ub = UniformParams::default();
......@@ -716,36 +750,51 @@ impl Engine {
716750 let base_rx = (x_glow / 720.0) * src.size[0] as f32;
717751 let base_ry = (y_glow / 720.0) * src.size[0] as f32;
718752
753 // Reuse per-mip blur scratch buffers and ping-pong accumulator buffers across octaves.
754 let mut mip_h: [Option<CachedTexture>; 5] = Default::default();
755 let mut mip_v: [Option<CachedTexture>; 5] = Default::default();
756 let mut acc_ping: [Option<CachedTexture>; 2] = Default::default();
757
719758 let mut running: Option<CachedTexture> = if glow_only { None } else { Some(src.clone()) };
720759 for i in 1..=iters {
721760 let var = i as f32 / iters as f32;
722761 let mult = if mode == 1 { FIB[i - 1] } else { EXPO[i - 1] };
723 let (mip_tex, div) = if i <= 2 && self.hiq {
724 (&prep, 1.0_f32)
762 let (mip_tex, div, level_idx) = if i <= 2 && self.hiq {
763 (&prep, 1.0_f32, 0usize)
725764 } else if i <= 4 {
726 (half.as_ref().unwrap_or(&prep), 2.0_f32)
765 (half.as_ref().unwrap_or(&prep), 2.0_f32, 1usize)
727766 } else if i <= 8 {
728 (quarter.as_ref().unwrap_or(&prep), 4.0_f32)
767 (quarter.as_ref().unwrap_or(&prep), 4.0_f32, 2usize)
729768 } else if i <= 12 {
730 (eighth.as_ref().unwrap_or(&prep), 8.0_f32)
769 (eighth.as_ref().unwrap_or(&prep), 8.0_f32, 3usize)
731770 } else {
732 (sixteenth.as_ref().unwrap_or(&prep), 16.0_f32)
771 (sixteenth.as_ref().unwrap_or(&prep), 16.0_f32, 4usize)
733772 };
734773
735774 // MT_XGlow passes BLUR_XSize = blur_x * mult to the mip image (which is `div` times smaller,
736775 // so in mip pixels the radius is base_rx * mult / div!).
737776 let rx_mip = (base_rx * mult / div).max(0.0);
738777 let ry_mip = (base_ry * mult / div).max(0.0);
739 let tmp1 = self.alloc_tex(mip_tex.size, src.depth, 0);
740 let tmp2 = self.alloc_tex(mip_tex.size, src.depth, 0);
741 let mut uh = UniformParams::default();
742 uh.p[0] = [1.0, 0.0, rx_mip, 0.0];
743 uh.p[1] = [1.0, 0.0, 0.0, 0.0];
744 self.dispatch_op(enc, ShaderOp::Blur, &mip_tex.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh);
745 let mut uv = UniformParams::default();
746 uv.p[0] = [0.0, 1.0, ry_mip, 0.0];
747 uv.p[1] = [1.0, 0.0, 0.0, 0.0];
748 self.dispatch_op(enc, ShaderOp::Blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv);
778 let after_h = if rx_mip >= 0.25 {
779 let t1 = mip_h[level_idx].get_or_insert_with(|| self.alloc_tex(mip_tex.size, src.depth, 0));
780 let mut uh = UniformParams::default();
781 uh.p[0] = [1.0, 0.0, rx_mip, 0.0];
782 uh.p[1] = [1.0, 0.0, 0.0, 0.0];
783 self.dispatch_op(enc, ShaderOp::Blur, &mip_tex.view, &self.dummy.view, &self.dummy.view, t1, &uh);
784 t1 as &CachedTexture
785 } else {
786 mip_tex
787 };
788 let oct_tex = if ry_mip >= 0.25 {
789 let t2 = mip_v[level_idx].get_or_insert_with(|| self.alloc_tex(mip_tex.size, src.depth, 0));
790 let mut uv = UniformParams::default();
791 uv.p[0] = [0.0, 1.0, ry_mip, 0.0];
792 uv.p[1] = [1.0, 0.0, 0.0, 0.0];
793 self.dispatch_op(enc, ShaderOp::Blur, &after_h.view, &self.dummy.view, &self.dummy.view, t2, &uv);
794 t2 as &CachedTexture
795 } else {
796 after_h
797 };
749798
750799 let gc = grad.as_ref().map_or([1.0, 1.0, 1.0, 1.0], |g| g.sample(var as f64));
751800 let falloff_scale = 1.0 / falloff.powi(i as i32);
......@@ -754,16 +803,19 @@ impl Engine {
754803 let uv_scale = glow_sat * var;
755804
756805 let is_last = i == iters && mask.is_none() && (blend - 1.0).abs() <= 1e-4;
757 let next = self.alloc_tex_like(
758 &src,
759 src.depth,
760 if is_last { key } else { 0 },
761 );
806 let next = if is_last {
807 self.alloc_tex_like(&src, src.depth, key)
808 } else {
809 let slot = (i - 1) & 1;
810 acc_ping[slot]
811 .get_or_insert_with(|| self.alloc_tex_like(&src, src.depth, 0))
812 .clone()
813 };
762814 let mut ua = UniformParams::default();
763815 ua.p[0] = [gc[0], gc[1], gc[2], y_scale];
764816 ua.p[1] = [uv_scale, if running.is_some() { 1.0 } else { 0.0 }, falloff_scale * 0.5, 0.0];
765817 let base_v = running.as_ref().map_or(&self.dummy.view, |r| &r.view);
766 self.dispatch_op(enc, ShaderOp::XGlowAccum, base_v, &tmp2.view, &self.dummy.view, &next, &ua);
818 self.dispatch_op(enc, ShaderOp::XGlowAccum, base_v, &oct_tex.view, &self.dummy.view, &next, &ua);
767819 running = Some(next);
768820 }
769821
......@@ -1071,12 +1123,14 @@ impl Engine {
10711123 stats.cache_misses += 1;
10721124 stats.nodes_evaluated += 1;
10731125
1074 let grad_tex = create_texture(&self.device, [256, 1], 0);
1075 self.queue.write_texture(
1076 grad_tex.texture.as_image_copy(),
1126 let grad_tex = self.pipelines.borrow_mut().get_or_upload_lut_tex(
1127 &self.device,
1128 &self.queue,
1129 [256, 1],
1130 BitDepth::Int8,
1131 wgpu::TextureFormat::Rgba8Unorm,
1132 256 * 4,
10771133 &grad_bytes,
1078 wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 4), rows_per_image: Some(1) },
1079 wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 },
10801134 );
10811135 let mut dst = self.alloc_tex(src.canvas_size, src.depth, key);
10821136 dst.tex_scale *= src.tex_scale;
......@@ -2192,4 +2246,240 @@ mod tests {
21922246 let (_, huge) = Engine::dir_blur_expanded_dod(&src, 1, f32::INFINITY, f32::NAN, [f32::MAX, f32::NEG_INFINITY], [64, 64]);
21932247 assert!(huge[0] <= 4096 && huge[1] <= 4096, "non-finite inputs stay bounded: {huge:?}");
21942248 }
2249
2250 fn f16_to_f32(bits: u16) -> f32 {
2251 let sign = ((bits & 0x8000) as u32) << 16;
2252 let exp = (bits >> 10) & 0x1F;
2253 let frac = (bits & 0x03FF) as u32;
2254 if exp == 0 {
2255 if frac == 0 {
2256 f32::from_bits(sign)
2257 } else {
2258 let mut f = frac;
2259 let mut e = -14i32;
2260 while (f & 0x0400) == 0 {
2261 f <<= 1;
2262 e -= 1;
2263 }
2264 let f_norm = f & 0x03FF;
2265 let e_f32 = ((e + 127) as u32) << 23;
2266 f32::from_bits(sign | e_f32 | (f_norm << 13))
2267 }
2268 } else if exp == 0x1F {
2269 f32::from_bits(sign | 0x7F80_0000 | (frac << 13))
2270 } else {
2271 let e_f32 = ((exp as u32) + 112) << 23;
2272 f32::from_bits(sign | e_f32 | (frac << 13))
2273 }
2274 }
2275
2276 fn readback_rgba16f(eng: &Engine, tex: &CachedTexture) -> Vec<[f32; 4]> {
2277 let [w, h] = tex.size;
2278 let unpadded_bpr = w * 8;
2279 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
2280 let padded_bpr = unpadded_bpr.div_ceil(align) * align;
2281 let buf = eng.device.create_buffer(&wgpu::BufferDescriptor {
2282 label: Some("readback-f16"),
2283 size: u64::from(padded_bpr) * u64::from(h),
2284 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
2285 mapped_at_creation: false,
2286 });
2287 let mut enc = eng.device.create_command_encoder(&Default::default());
2288 enc.copy_texture_to_buffer(
2289 tex.texture.as_image_copy(),
2290 wgpu::TexelCopyBufferInfo {
2291 buffer: &buf,
2292 layout: wgpu::TexelCopyBufferLayout {
2293 offset: 0,
2294 bytes_per_row: Some(padded_bpr),
2295 rows_per_image: Some(h),
2296 },
2297 },
2298 wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
2299 );
2300 eng.queue.submit(Some(enc.finish()));
2301 let slice = buf.slice(..);
2302 let (tx, rx) = std::sync::mpsc::channel();
2303 slice.map_async(wgpu::MapMode::Read, move |res| {
2304 let _ = tx.send(res);
2305 });
2306 eng.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(std::time::Duration::from_secs(10)) }).unwrap();
2307 rx.recv().unwrap().unwrap();
2308 let data = slice.get_mapped_range().unwrap();
2309 let mut out = Vec::with_capacity((w * h) as usize);
2310 for y in 0..h as usize {
2311 let row = &data[y * padded_bpr as usize..y * padded_bpr as usize + unpadded_bpr as usize];
2312 for px in row.chunks_exact(8) {
2313 out.push([
2314 f16_to_f32(u16::from_le_bytes([px[0], px[1]])),
2315 f16_to_f32(u16::from_le_bytes([px[2], px[3]])),
2316 f16_to_f32(u16::from_le_bytes([px[4], px[5]])),
2317 f16_to_f32(u16::from_le_bytes([px[6], px[7]])),
2318 ]);
2319 }
2320 }
2321 drop(data);
2322 buf.unmap();
2323 out
2324 }
2325
2326 fn cpu_discrete_gauss_1d(src: &[[f32; 4]], w: usize, h: usize, horizontal: bool, radius: f32, clamp_edges: bool) -> Vec<[f32; 4]> {
2327 let sigma = (radius * 0.45).max(0.25) as f64;
2328 let span = (radius as f64).max(sigma * 3.0);
2329 let taps = (span.ceil() as i32).clamp(1, 64);
2330 let inv2s2 = 0.5 / (sigma * sigma);
2331 let mut out = vec![[0.0f32; 4]; w * h];
2332 for y in 0..h {
2333 for x in 0..w {
2334 let mut acc = [0.0f64; 4];
2335 let mut wsum = 0.0f64;
2336 for k in -taps..=taps {
2337 let wt = (-(k as f64) * (k as f64) * inv2s2).exp();
2338 wsum += wt;
2339 let (sx, sy) = if horizontal {
2340 (x as i32 + k, y as i32)
2341 } else {
2342 (x as i32, y as i32 + k)
2343 };
2344 let sample = if clamp_edges {
2345 let cx = sx.clamp(0, w as i32 - 1) as usize;
2346 let cy = sy.clamp(0, h as i32 - 1) as usize;
2347 src[cy * w + cx]
2348 } else if sx >= 0 && sx < w as i32 && sy >= 0 && sy < h as i32 {
2349 src[sy as usize * w + sx as usize]
2350 } else {
2351 [0.0; 4]
2352 };
2353 for c in 0..4 {
2354 acc[c] += sample[c] as f64 * wt;
2355 }
2356 }
2357 for c in 0..4 {
2358 out[y * w + x][c] = (acc[c] / wsum) as f32;
2359 }
2360 }
2361 }
2362 out
2363 }
2364
2365 #[test]
2366 fn bilinear_gaussian_blur_matches_discrete_reference_u8_and_f16() {
2367 let Ok(eng) = Engine::new_headless() else {
2368 return;
2369 };
2370 let (w, h) = (48u32, 32u32);
2371 let mut pixels_f32 = Vec::with_capacity((w * h) as usize);
2372 let mut pixels_u8 = Vec::with_capacity((w * h * 4) as usize);
2373 for y in 0..h {
2374 for x in 0..w {
2375 // Top half: smooth gradient; bottom half: sharp step edge + corner impulse.
2376 let (r, g, b, a): (f32, f32, f32, f32) = if y < h / 2 {
2377 (x as f32 / (w - 1) as f32, y as f32 / (h / 2 - 1) as f32, 0.35, 1.0)
2378 } else if x < w / 2 {
2379 (1.0, 0.0, 0.2, 1.0)
2380 } else {
2381 (0.0, 1.0, 0.8, 0.5)
2382 };
2383 let ur = (r * 255.0).round() as u8;
2384 let ug = (g * 255.0).round() as u8;
2385 let ub = (b * 255.0).round() as u8;
2386 let ua = (a * 255.0).round() as u8;
2387 pixels_u8.extend_from_slice(&[ur, ug, ub, ua]);
2388 pixels_f32.push([ur as f32 / 255.0, ug as f32 / 255.0, ub as f32 / 255.0, ua as f32 / 255.0]);
2389 }
2390 }
2391 let pixels_f16: Vec<u16> = pixels_f32
2392 .iter()
2393 .flat_map(|p| p.iter().map(|&v| crate::media::f32_to_f16_bits(v)))
2394 .collect();
2395
2396 for &radius in &[1.5f32, 6.0, 14.0] {
2397 for &clamp_edges in &[false, true] {
2398 let ce = if clamp_edges { 1.0 } else { 0.0 };
2399
2400 // 1) Rgba16Float 1D H + 1D V separable passes
2401 let src_f16 = eng.alloc_tex([w, h], BitDepth::Float16, 0);
2402 eng.queue.write_texture(
2403 src_f16.texture.as_image_copy(),
2404 bytemuck::cast_slice(&pixels_f16),
2405 wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 8), rows_per_image: Some(h) },
2406 wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
2407 );
2408 let tmp_f16 = eng.alloc_tex([w, h], BitDepth::Float16, 0);
2409 let dst_f16 = eng.alloc_tex([w, h], BitDepth::Float16, 0);
2410 let mut enc = eng.device.create_command_encoder(&Default::default());
2411 let mut uh = UniformParams::default();
2412 uh.p[0] = [1.0, 0.0, radius, 0.0];
2413 uh.p[1] = [1.0, 0.0, 0.0, ce];
2414 eng.dispatch_op(&mut enc, ShaderOp::Blur, &src_f16.view, &eng.dummy.view, &eng.dummy.view, &tmp_f16, &uh);
2415 let mut uv = UniformParams::default();
2416 uv.p[0] = [0.0, 1.0, radius, 0.0];
2417 uv.p[1] = [1.0, 0.0, 0.0, ce];
2418 eng.dispatch_op(&mut enc, ShaderOp::Blur, &tmp_f16.view, &eng.dummy.view, &eng.dummy.view, &dst_f16, &uv);
2419 eng.queue.submit(Some(enc.finish()));
2420
2421 let got_f16 = readback_rgba16f(&eng, &dst_f16);
2422 let ref_src_f16: Vec<[f32; 4]> = pixels_f16
2423 .chunks_exact(4)
2424 .map(|c| [f16_to_f32(c[0]), f16_to_f32(c[1]), f16_to_f32(c[2]), f16_to_f32(c[3])])
2425 .collect();
2426 let mut ref_h = cpu_discrete_gauss_1d(&ref_src_f16, w as usize, h as usize, true, radius, clamp_edges);
2427 for px in &mut ref_h {
2428 for c in px.iter_mut() {
2429 *c = f16_to_f32(crate::media::f32_to_f16_bits(*c));
2430 }
2431 }
2432 let mut ref_hv = cpu_discrete_gauss_1d(&ref_h, w as usize, h as usize, false, radius, clamp_edges);
2433 for px in &mut ref_hv {
2434 for c in px.iter_mut() {
2435 *c = f16_to_f32(crate::media::f32_to_f16_bits(*c));
2436 }
2437 }
2438 let mut max_err_f16 = 0.0f32;
2439 let mut worst = (0usize, 0usize, 0usize, 0.0f32, 0.0f32);
2440 for y in 0..h as usize {
2441 for x in 0..w as usize {
2442 let idx = y * w as usize + x;
2443 for c in 0..4 {
2444 let err = (got_f16[idx][c] - ref_hv[idx][c]).abs();
2445 if err > max_err_f16 {
2446 max_err_f16 = err;
2447 worst = (x, y, c, got_f16[idx][c], ref_hv[idx][c]);
2448 }
2449 }
2450 }
2451 }
2452 assert!(
2453 max_err_f16 < 1e-3,
2454 "Rgba16Float r={radius} clamp={clamp_edges}: max_err={max_err_f16} at {:?}",
2455 worst
2456 );
2457
2458 // 2) Rgba8Unorm 1D H pass (comparing direct bilinear pass to discrete float reference)
2459 let src_u8 = eng.alloc_tex([w, h], BitDepth::Int8, 0);
2460 eng.queue.write_texture(
2461 src_u8.texture.as_image_copy(),
2462 &pixels_u8,
2463 wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 4), rows_per_image: Some(h) },
2464 wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
2465 );
2466 let dst_u8 = eng.alloc_tex([w, h], BitDepth::Int8, 0);
2467 let mut enc = eng.device.create_command_encoder(&Default::default());
2468 eng.dispatch_op(&mut enc, ShaderOp::Blur, &src_u8.view, &eng.dummy.view, &eng.dummy.view, &dst_u8, &uh);
2469 eng.queue.submit(Some(enc.finish()));
2470
2471 let got_u8 = eng.readback_rgba(&dst_u8).unwrap();
2472 let max_lsb_u8 = got_u8
2473 .chunks_exact(4)
2474 .zip(&ref_h)
2475 .flat_map(|(g, r)| (0..4).map(move |c| (g[c] as i32 - (r[c] * 255.0).round() as i32).abs()))
2476 .max()
2477 .unwrap_or(0);
2478 assert!(
2479 max_lsb_u8 <= 1,
2480 "Rgba8Unorm r={radius} clamp={clamp_edges}: max_lsb_err={max_lsb_u8}"
2481 );
2482 }
2483 }
2484 }
21952485}
crates/engine/src/eval/color.rs+97-21
......@@ -431,12 +431,14 @@ impl Engine {
431431 }
432432 stats.cache_misses += 1;
433433 stats.nodes_evaluated += 1;
434 let curve_tex = create_texture_dod_fmt(&self.device, [12, 3], [0, 0], [12, 3], BitDepth::Float16, wgpu::TextureFormat::Rgba16Float, 0);
435 self.queue.write_texture(
436 curve_tex.texture.as_image_copy(),
434 let curve_tex = self.pipelines.borrow_mut().get_or_upload_lut_tex(
435 &self.device,
436 &self.queue,
437 [12, 3],
438 BitDepth::Float16,
439 wgpu::TextureFormat::Rgba16Float,
440 12 * 8,
437441 bytemuck::cast_slice(&table),
438 wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(12 * 8), rows_per_image: Some(3) },
439 wgpu::Extent3d { width: 12, height: 3, depth_or_array_layers: 1 },
440442 );
441443 let dst = self.alloc_tex_like(&src, src.depth, key);
442444 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
......@@ -860,22 +862,15 @@ impl Engine {
860862 }
861863
862864 pub(super) fn upload_lut_f16(&self, lut_f16: &[u16; 256 * 4]) -> CachedTexture {
863 let lut_tex = create_texture_dod_fmt(
865 self.pipelines.borrow_mut().get_or_upload_lut_tex(
864866 &self.device,
865 [256, 1],
866 [0, 0],
867 &self.queue,
867868 [256, 1],
868869 BitDepth::Float16,
869870 wgpu::TextureFormat::Rgba16Float,
870 0,
871 );
872 self.queue.write_texture(
873 lut_tex.texture.as_image_copy(),
871 256 * 8,
874872 bytemuck::cast_slice(lut_f16),
875 wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 8), rows_per_image: Some(1) },
876 wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 },
877 );
878 lut_tex
873 )
879874 }
880875
881876 /// Returns `(y0, y1, slope0, slope1)` for RGBA `ColorCurves` linear tangent extrapolation
......@@ -1140,12 +1135,14 @@ impl Engine {
11401135 stats.cache_misses += 1;
11411136 stats.nodes_evaluated += 1;
11421137
1143 let lut_tex = create_texture(&self.device, [256, 3], 0);
1144 self.queue.write_texture(
1145 lut_tex.texture.as_image_copy(),
1138 let lut_tex = self.pipelines.borrow_mut().get_or_upload_lut_tex(
1139 &self.device,
1140 &self.queue,
1141 [256, 3],
1142 BitDepth::Int8,
1143 wgpu::TextureFormat::Rgba8Unorm,
1144 256 * 4,
11461145 &lut,
1147 wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 4), rows_per_image: Some(3) },
1148 wgpu::Extent3d { width: 256, height: 3, depth_or_array_layers: 1 },
11491146 );
11501147 let dst = self.alloc_tex_like(&src, src.depth, key);
11511148 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
......@@ -2028,5 +2025,84 @@ mod tests {
20282025 .sum();
20292026 assert!(dy > dx * 2, "LockSizeXY=0 with MasterXSize=5, MasterYSize=1 must vary faster in Y ({dy}) than X ({dx})");
20302027 }
2028
2029 #[test]
2030 fn lut_and_curve_texture_cache_hits_on_repeat_evals() {
2031 let comp_src = r#"Composition {
2032 CurrentTime = 0,
2033 RenderRange = { 0, 1 },
2034 GlobalRange = { 0, 1 },
2035 Tools = ordered() {
2036 Src = Background {
2037 Inputs = {
2038 Width = Input { Value = 16, },
2039 Height = Input { Value = 16, },
2040 TopLeftRed = Input { Value = 0.5, },
2041 TopLeftGreen = Input { Value = 0.25, },
2042 TopLeftBlue = Input { Value = 0.75, },
2043 TopLeftAlpha = Input { Value = 1.0, },
2044 },
2045 },
2046 CC = ColorCorrector {
2047 Inputs = {
2048 Input = Input { SourceOp = "Src", Source = "Output", },
2049 MasterRGBGamma = Input { Value = 1.4, },
2050 },
2051 },
2052 LutR = LUTBezier {
2053 KeyColorSplines = { [0] = { 0, RH = { 0.33, 0.5 } }, [1] = { 1, LH = { 0.66, 0.9 } } },
2054 },
2055 Curves = ColorCurves {
2056 Inputs = {
2057 Input = Input { SourceOp = "CC", Source = "Output", },
2058 Red = Input { SourceOp = "LutR", Source = "Value", },
2059 },
2060 },
2061 HueC = HueCurves {
2062 Inputs = {
2063 Input = Input { SourceOp = "Curves", Source = "Output", },
2064 },
2065 },
2066 }
2067 }"#;
2068 let comp = Comp::from_fusion_str(comp_src).expect("parse LUT cache comp");
2069 let Ok(mut eng) = Engine::new_headless() else {
2070 return;
2071 };
2072 let target = comp.find_node("HueC").unwrap();
2073
2074 eng.evaluate(&comp, target, 0.0);
2075 let (hits_1, misses_1) = {
2076 let reg = eng.pipelines.borrow();
2077 (reg.lut_hits, reg.lut_misses)
2078 };
2079 assert_eq!(misses_1, 3, "CC + ColorCurves + HueCurves should upload 3 LUTs on cold eval");
2080 assert_eq!(hits_1, 0);
2081
2082 // Bust node/output cache and re-evaluate: LUT textures should all hit in ShaderRegistry cache.
2083 eng.bust_gpu_cache();
2084 eng.evaluate(&comp, target, 0.0);
2085 let (hits_2, misses_2) = {
2086 let reg = eng.pipelines.borrow();
2087 (reg.lut_hits, reg.lut_misses)
2088 };
2089 assert_eq!(misses_2, misses_1, "repeat eval must not allocate new LUT textures");
2090 assert_eq!(hits_2, 3, "CC + ColorCurves + HueCurves should all hit LUT cache on repeat eval");
2091
2092 // Verify bounded 64-entry LRU eviction.
2093 for i in 0..80u8 {
2094 let bytes = [i; 12 * 3 * 8];
2095 let _ = eng.pipelines.borrow_mut().get_or_upload_lut_tex(
2096 &eng.device,
2097 &eng.queue,
2098 [12, 3],
2099 model::BitDepth::Float16,
2100 wgpu::TextureFormat::Rgba16Float,
2101 12 * 8,
2102 &bytes,
2103 );
2104 }
2105 assert!(eng.pipelines.borrow().lut_misses <= 83);
2106 }
20312107}
20322108
crates/engine/src/eval/dispatch.rs+128-46
......@@ -265,27 +265,24 @@ impl Engine {
265265 }
266266
267267 #[allow(clippy::too_many_arguments)]
268 pub(super) fn dispatch_op(
268 fn dispatch_with_registry(
269269 &self,
270 reg_cell: &RefCell<ShaderRegistry>,
270271 enc: &mut wgpu::CommandEncoder,
271272 op: ShaderOp,
272273 src_a: &wgpu::TextureView,
273274 src_b: &wgpu::TextureView,
274275 mask: &wgpu::TextureView,
275 dst: &CachedTexture,
276 dst_view: &wgpu::TextureView,
277 dst_size: [u32; 2],
276278 params: &UniformParams,
277279 ) {
278 let reg_cell = self.pipelines_for(dst.depth);
279 reg_cell.borrow_mut().ensure_pipeline(&self.device, op);
280 let (chunk_idx, dynamic_offset) = {
281 let mut reg = reg_cell.borrow_mut();
282 reg.ensure_pipeline(&self.device, op);
283 reg.alloc_uniform_slot(&self.device, &self.queue, params)
284 };
280285 let reg = reg_cell.borrow();
281 let ubuf = self.device.create_buffer(&wgpu::BufferDescriptor {
282 label: Some("op-params"),
283 size: std::mem::size_of::<UniformParams>() as u64,
284 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
285 mapped_at_creation: false,
286 });
287 self.queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(params));
288
289286 let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
290287 label: Some("op-bg"),
291288 layout: &reg.bgl,
......@@ -294,8 +291,15 @@ impl Engine {
294291 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) },
295292 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) },
296293 wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&reg.sampler) },
297 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(&dst.view) },
298 wgpu::BindGroupEntry { binding: 5, resource: ubuf.as_entire_binding() },
294 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(dst_view) },
295 wgpu::BindGroupEntry {
296 binding: 5,
297 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
298 buffer: &reg.uniform_chunks[chunk_idx],
299 offset: 0,
300 size: std::num::NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64),
301 }),
302 },
299303 ],
300304 });
301305
......@@ -304,8 +308,32 @@ impl Engine {
304308 timestamp_writes: None,
305309 });
306310 pass.set_pipeline(&reg.pipelines[&op]);
307 pass.set_bind_group(0, &bg, &[]);
308 pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1);
311 pass.set_bind_group(0, &bg, &[dynamic_offset]);
312 pass.dispatch_workgroups(dst_size[0].div_ceil(8), dst_size[1].div_ceil(8), 1);
313 }
314
315 #[allow(clippy::too_many_arguments)]
316 pub(super) fn dispatch_op(
317 &self,
318 enc: &mut wgpu::CommandEncoder,
319 op: ShaderOp,
320 src_a: &wgpu::TextureView,
321 src_b: &wgpu::TextureView,
322 mask: &wgpu::TextureView,
323 dst: &CachedTexture,
324 params: &UniformParams,
325 ) {
326 self.dispatch_with_registry(
327 self.pipelines_for(dst.depth),
328 enc,
329 op,
330 src_a,
331 src_b,
332 mask,
333 &dst.view,
334 dst.size,
335 params,
336 );
309337 }
310338
311339 #[allow(clippy::too_many_arguments)]
......@@ -320,36 +348,17 @@ impl Engine {
320348 dst_size: [u32; 2],
321349 params: &UniformParams,
322350 ) {
323 self.pipelines.borrow_mut().ensure_pipeline(&self.device, op);
324 let reg = self.pipelines.borrow();
325 let ubuf = self.device.create_buffer(&wgpu::BufferDescriptor {
326 label: Some("op-params"),
327 size: std::mem::size_of::<UniformParams>() as u64,
328 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
329 mapped_at_creation: false,
330 });
331 self.queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(params));
332
333 let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
334 label: Some("op-bg"),
335 layout: &reg.bgl,
336 entries: &[
337 wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) },
338 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) },
339 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) },
340 wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&reg.sampler) },
341 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(dst_view) },
342 wgpu::BindGroupEntry { binding: 5, resource: ubuf.as_entire_binding() },
343 ],
344 });
345
346 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
347 label: Some("comp-op"),
348 timestamp_writes: None,
349 });
350 pass.set_pipeline(&reg.pipelines[&op]);
351 pass.set_bind_group(0, &bg, &[]);
352 pass.dispatch_workgroups(dst_size[0].div_ceil(8), dst_size[1].div_ceil(8), 1);
351 self.dispatch_with_registry(
352 &self.pipelines,
353 enc,
354 op,
355 src_a,
356 src_b,
357 mask,
358 dst_view,
359 dst_size,
360 params,
361 );
353362 }
354363}
355364
......@@ -433,3 +442,76 @@ pub fn create_texture_dod_fmt(
433442 cached.tex_scale = tex_scale;
434443 cached
435444}
445
446#[cfg(test)]
447mod tests {
448 use super::*;
449 use crate::Engine;
450
451 #[test]
452 fn dynamic_uniform_ring_handles_over_1024_dispatches_in_single_encoder() {
453 let Ok(eng) = Engine::new_headless() else {
454 return;
455 };
456 let min_align = eng.device.limits().min_uniform_buffer_offset_alignment.max(1);
457 let stride = eng.pipelines.borrow().uniform_stride;
458 assert!(stride >= std::mem::size_of::<UniformParams>() as u32);
459 assert_eq!(stride % min_align, 0);
460
461 let out_first = eng.alloc_tex([4, 4], BitDepth::Int8, 0);
462 let out_1023 = eng.alloc_tex([4, 4], BitDepth::Int8, 0);
463 let out_1024 = eng.alloc_tex([4, 4], BitDepth::Int8, 0);
464 let out_last = eng.alloc_tex([4, 4], BitDepth::Int8, 0);
465 let scratch = eng.alloc_tex([4, 4], BitDepth::Int8, 0);
466
467 let bg_params = |rgba: [f32; 4]| {
468 let mut u = UniformParams::default();
469 u.p[0] = rgba;
470 u.p[1] = rgba;
471 u.p[2] = rgba;
472 u.p[3] = rgba;
473 u
474 };
475
476 let mut enc = eng.device.create_command_encoder(&Default::default());
477 let total = 1100usize;
478 for i in 0..total {
479 let (target, rgba) = match i {
480 0 => (&out_first, [0.2, 0.4, 0.6, 1.0]),
481 1023 => (&out_1023, [0.3, 0.7, 0.2, 1.0]),
482 1024 => (&out_1024, [0.8, 0.5, 0.1, 1.0]),
483 1099 => (&out_last, [0.1, 0.2, 0.9, 1.0]),
484 _ => (&scratch, [0.9, 0.1, 0.1, 1.0]),
485 };
486 eng.dispatch_op(
487 &mut enc,
488 ShaderOp::Bg,
489 &eng.dummy.view,
490 &eng.dummy.view,
491 &eng.dummy.view,
492 target,
493 &bg_params(rgba),
494 );
495 }
496 eng.queue.submit(Some(enc.finish()));
497 assert!(
498 eng.pipelines.borrow().uniform_chunks.len() >= 2,
499 "1,100 dispatches should allocate at least 2 uniform chunks"
500 );
501
502 let check = |tex: &CachedTexture, expected: [u8; 4], label: &str| {
503 let px = eng.readback_rgba(tex).expect("readback");
504 for (c, &want) in expected.iter().enumerate() {
505 assert!(
506 (px[c] as i32 - want as i32).abs() <= 1,
507 "{label} channel {c}: got {} expected {want}",
508 px[c]
509 );
510 }
511 };
512 check(&out_first, [51, 102, 153, 255], "dispatch 0");
513 check(&out_1023, [77, 179, 51, 255], "dispatch 1023");
514 check(&out_1024, [204, 128, 26, 255], "dispatch 1024");
515 check(&out_last, [26, 51, 230, 255], "dispatch 1099");
516 }
517}
crates/engine/src/eval/registry.rs+149-3
......@@ -1,6 +1,10 @@
1//! Shader domains, GPU op enum, and lazy WGSL pipeline compilation cache.
1//! Shader domains, GPU op enum, lazy WGSL pipeline cache, dynamic uniform ring,
2//! and tiny LUT/curve texture LRU cache.
23
34use std::collections::HashMap;
5use std::num::NonZeroU64;
6
7use crate::cache::CachedTexture;
48
59#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
610pub(super) enum ShaderDomain {
......@@ -219,6 +223,18 @@ impl ShaderOp {
219223}
220224
221225const COMMON_WGSL: &str = include_str!("../shaders/common.wgsl");
226const UNIFORM_SLOTS_PER_CHUNK: u32 = 1024;
227const MAX_UNIFORM_CHUNKS: usize = 16;
228const LUT_CACHE_CAPACITY: usize = 64;
229
230struct LutCacheEntry {
231 size: [u32; 2],
232 format: wgpu::TextureFormat,
233 hash: u64,
234 bytes: Vec<u8>,
235 tex: CachedTexture,
236 last_used: u64,
237}
222238
223239pub(super) struct ShaderRegistry {
224240 format: wgpu::TextureFormat,
......@@ -228,10 +244,21 @@ pub(super) struct ShaderRegistry {
228244 pub(super) sampler: wgpu::Sampler,
229245 pub(super) modules: HashMap<ShaderDomain, wgpu::ShaderModule>,
230246 pub(super) pipelines: HashMap<ShaderOp, wgpu::ComputePipeline>,
247 pub(super) uniform_stride: u32,
248 pub(super) uniform_chunks: Vec<wgpu::Buffer>,
249 uniform_cursor: u32,
250 lut_cache: Vec<LutCacheEntry>,
251 lut_tick: u64,
252 pub(super) lut_hits: u64,
253 pub(super) lut_misses: u64,
231254}
232255
233256impl ShaderRegistry {
234257 pub(super) fn new(device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) -> Self {
258 let uniform_size = std::mem::size_of::<super::dispatch::UniformParams>() as u32;
259 let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1);
260 let uniform_stride = uniform_size.div_ceil(min_align) * min_align;
261
235262 let tex_entry = |binding| wgpu::BindGroupLayoutEntry {
236263 binding,
237264 visibility: wgpu::ShaderStages::COMPUTE,
......@@ -269,8 +296,8 @@ impl ShaderRegistry {
269296 visibility: wgpu::ShaderStages::COMPUTE,
270297 ty: wgpu::BindingType::Buffer {
271298 ty: wgpu::BufferBindingType::Uniform,
272 has_dynamic_offset: false,
273 min_binding_size: None,
299 has_dynamic_offset: true,
300 min_binding_size: NonZeroU64::new(u64::from(uniform_size)),
274301 },
275302 count: None,
276303 },
......@@ -301,7 +328,126 @@ impl ShaderRegistry {
301328 sampler,
302329 modules: HashMap::new(),
303330 pipelines: HashMap::new(),
331 uniform_stride,
332 uniform_chunks: Vec::new(),
333 uniform_cursor: 0,
334 lut_cache: Vec::new(),
335 lut_tick: 0,
336 lut_hits: 0,
337 lut_misses: 0,
338 }
339 }
340
341 /// Writes `params` into the next aligned slot in the chunked dynamic uniform ring
342 /// and returns `(chunk_index, dynamic_byte_offset)`.
343 ///
344 /// Lazily allocates 1,024-slot chunks up to `MAX_UNIFORM_CHUNKS` (16,384 slots) so a
345 /// single unsubmitted `CommandEncoder` never overwrites earlier slots while long
346 /// multi-frame playback stays memory-bounded.
347 pub(super) fn alloc_uniform_slot(
348 &mut self,
349 device: &wgpu::Device,
350 queue: &wgpu::Queue,
351 params: &super::dispatch::UniformParams,
352 ) -> (usize, u32) {
353 let slot_global = self.uniform_cursor;
354 let chunk_idx = (slot_global / UNIFORM_SLOTS_PER_CHUNK) as usize;
355 let slot_in_chunk = slot_global % UNIFORM_SLOTS_PER_CHUNK;
356 if chunk_idx >= self.uniform_chunks.len() {
357 let size = u64::from(UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride);
358 let buf = device.create_buffer(&wgpu::BufferDescriptor {
359 label: Some("op-params-ring"),
360 size,
361 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
362 mapped_at_creation: false,
363 });
364 self.uniform_chunks.push(buf);
365 }
366 let offset = slot_in_chunk * self.uniform_stride;
367 queue.write_buffer(
368 &self.uniform_chunks[chunk_idx],
369 u64::from(offset),
370 bytemuck::bytes_of(params),
371 );
372 let next = slot_global + 1;
373 let max_slots = (MAX_UNIFORM_CHUNKS as u32) * UNIFORM_SLOTS_PER_CHUNK;
374 self.uniform_cursor = if next >= max_slots { 0 } else { next };
375 (chunk_idx, offset)
376 }
377
378 /// Returns a cached tiny LUT/curve texture for `(size, format, bytes)` or uploads and
379 /// inserts one into the bounded 64-entry LRU cache.
380 #[allow(clippy::too_many_arguments)]
381 pub(super) fn get_or_upload_lut_tex(
382 &mut self,
383 device: &wgpu::Device,
384 queue: &wgpu::Queue,
385 size: [u32; 2],
386 depth: model::BitDepth,
387 format: wgpu::TextureFormat,
388 bytes_per_row: u32,
389 bytes: &[u8],
390 ) -> CachedTexture {
391 use std::hash::{Hash, Hasher};
392 let mut hasher = std::collections::hash_map::DefaultHasher::new();
393 size.hash(&mut hasher);
394 format.hash(&mut hasher);
395 bytes.hash(&mut hasher);
396 let hash = hasher.finish();
397 self.lut_tick = self.lut_tick.wrapping_add(1);
398 let tick = self.lut_tick;
399
400 if let Some(entry) = self.lut_cache.iter_mut().find(|e| {
401 e.hash == hash && e.size == size && e.format == format && e.bytes.as_slice() == bytes
402 }) {
403 entry.last_used = tick;
404 self.lut_hits += 1;
405 return entry.tex.clone();
406 }
407
408 self.lut_misses += 1;
409 let tex = super::dispatch::create_texture_dod_fmt(
410 device,
411 size,
412 [0, 0],
413 size,
414 depth,
415 format,
416 hash,
417 );
418 queue.write_texture(
419 tex.texture.as_image_copy(),
420 bytes,
421 wgpu::TexelCopyBufferLayout {
422 offset: 0,
423 bytes_per_row: Some(bytes_per_row),
424 rows_per_image: Some(size[1]),
425 },
426 wgpu::Extent3d {
427 width: size[0],
428 height: size[1],
429 depth_or_array_layers: 1,
430 },
431 );
432 if self.lut_cache.len() >= LUT_CACHE_CAPACITY {
433 if let Some((evict_idx, _)) = self
434 .lut_cache
435 .iter()
436 .enumerate()
437 .min_by_key(|(_, e)| e.last_used)
438 {
439 self.lut_cache.swap_remove(evict_idx);
440 }
304441 }
442 self.lut_cache.push(LutCacheEntry {
443 size,
444 format,
445 hash,
446 bytes: bytes.to_vec(),
447 tex: tex.clone(),
448 last_used: tick,
449 });
450 tex
305451 }
306452
307453 pub(super) fn ensure_pipeline(&mut self, device: &wgpu::Device, op: ShaderOp) {
crates/engine/src/shaders/blur_glow.wgsl+103-17
......@@ -79,7 +79,8 @@ fn blur_op(@builtin(global_invocation_id) gid: vec3<u32>) {
7979 let radius = u.p[0].z;
8080 let mode = i32(u.p[0].w + 0.5);
8181
82 var acc = textureLoad(src_a, vec2<i32>(gid.xy), 0);
82 let center = textureLoad(src_a, vec2<i32>(gid.xy), 0);
83 var acc = center;
8384 let clamp_edges = u.p[1].w > 0.5;
8485 if (radius >= 0.25) {
8586 var wsum = 0.0;
......@@ -102,30 +103,115 @@ fn blur_op(@builtin(global_invocation_id) gid: vec3<u32>) {
102103 acc = acc / max(wsum, 1.0);
103104 } else {
104105 // Gaussian blur: extend sample span to 3*sigma so tails aren't truncated at 2.2*sigma.
105 acc = vec4<f32>(0.0);
106106 let sigma = max(radius * 0.45, 0.25);
107107 let span = max(radius, sigma * 3.0);
108 let taps = clamp(i32(ceil(span)), 1, 64);
109 let step_scale = span / f32(taps);
110108 let inv2s2 = 0.5 / (sigma * sigma);
111 for (var i = -taps; i <= taps; i = i + 1) {
112 let d = f32(i) * step_scale;
113 let w = exp(-d * d * inv2s2);
114 let off = uv + dir * d;
115 let s = select(
116 select(vec4<f32>(0.0), textureSampleLevel(src_a, samp_lin, off, 0.0), off.x >= 0.0 && off.x <= 1.0 && off.y >= 0.0 && off.y <= 1.0),
117 textureSampleLevel(src_a, samp_lin, clamp(off, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0),
118 clamp_edges,
119 );
120 acc = acc + s * w;
121 wsum = wsum + w;
109 if (span <= 64.0) {
110 // Hardware bilinear-filtered pairing: adjacent positive taps (i, i+1) collapse to a
111 // single textureSampleLevel at offset = i + w_{i+1} / (w_i + w_{i+1}) with weight w_i + w_{i+1}.
112 let taps = clamp(i32(ceil(span)), 1, 64);
113 acc = center;
114 wsum = 1.0;
115 if (clamp_edges) {
116 for (var i = 1; i <= taps; i = i + 2) {
117 let fi = f32(i);
118 let w0 = exp(-fi * fi * inv2s2);
119 if (i + 1 <= taps) {
120 let fi1 = f32(i + 1);
121 let w1 = exp(-fi1 * fi1 * inv2s2);
122 let wp = w0 + w1;
123 let off = fi + w1 / max(wp, 1e-12);
124 let sp = textureSampleLevel(src_a, samp_lin, clamp(uv + dir * off, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
125 let sn = textureSampleLevel(src_a, samp_lin, clamp(uv - dir * off, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
126 acc = acc + (sp + sn) * wp;
127 wsum = wsum + 2.0 * wp;
128 } else {
129 let sp = textureSampleLevel(src_a, samp_lin, clamp(uv + dir * fi, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
130 let sn = textureSampleLevel(src_a, samp_lin, clamp(uv - dir * fi, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
131 acc = acc + (sp + sn) * w0;
132 wsum = wsum + 2.0 * w0;
133 }
134 }
135 } else {
136 for (var i = 1; i <= taps; i = i + 2) {
137 let fi = f32(i);
138 let w0 = exp(-fi * fi * inv2s2);
139 if (i + 1 <= taps) {
140 let fi1 = f32(i + 1);
141 let w1 = exp(-fi1 * fi1 * inv2s2);
142 let wp = w0 + w1;
143 let off = fi + w1 / max(wp, 1e-12);
144
145 let p0 = uv + dir * fi;
146 let p1 = uv + dir * fi1;
147 let p0_in = p0.x >= 0.0 && p0.x <= 1.0 && p0.y >= 0.0 && p0.y <= 1.0;
148 let p1_in = p1.x >= 0.0 && p1.x <= 1.0 && p1.y >= 0.0 && p1.y <= 1.0;
149 if (p0_in && p1_in) {
150 acc = acc + textureSampleLevel(src_a, samp_lin, uv + dir * off, 0.0) * wp;
151 } else if (p0_in) {
152 acc = acc + textureSampleLevel(src_a, samp_lin, p0, 0.0) * w0;
153 }
154
155 let n0 = uv - dir * fi;
156 let n1 = uv - dir * fi1;
157 let n0_in = n0.x >= 0.0 && n0.x <= 1.0 && n0.y >= 0.0 && n0.y <= 1.0;
158 let n1_in = n1.x >= 0.0 && n1.x <= 1.0 && n1.y >= 0.0 && n1.y <= 1.0;
159 if (n0_in && n1_in) {
160 acc = acc + textureSampleLevel(src_a, samp_lin, uv - dir * off, 0.0) * wp;
161 } else if (n0_in) {
162 acc = acc + textureSampleLevel(src_a, samp_lin, n0, 0.0) * w0;
163 }
164
165 wsum = wsum + 2.0 * wp;
166 } else {
167 let p0 = uv + dir * fi;
168 if (p0.x >= 0.0 && p0.x <= 1.0 && p0.y >= 0.0 && p0.y <= 1.0) {
169 acc = acc + textureSampleLevel(src_a, samp_lin, p0, 0.0) * w0;
170 }
171 let n0 = uv - dir * fi;
172 if (n0.x >= 0.0 && n0.x <= 1.0 && n0.y >= 0.0 && n0.y <= 1.0) {
173 acc = acc + textureSampleLevel(src_a, samp_lin, n0, 0.0) * w0;
174 }
175 wsum = wsum + 2.0 * w0;
176 }
177 }
178 }
179 acc = acc / max(wsum, 1e-6);
180 } else {
181 // Span > 64px: strided taps (>1px spacing cannot be paired into 1 bilinear fetch).
182 let step_scale = span / 64.0;
183 acc = center;
184 wsum = 1.0;
185 for (var i = 1; i <= 64; i = i + 1) {
186 let d = f32(i) * step_scale;
187 let w = exp(-d * d * inv2s2);
188 let p0 = uv + dir * d;
189 let n0 = uv - dir * d;
190 if (clamp_edges) {
191 let sp = textureSampleLevel(src_a, samp_lin, clamp(p0, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
192 let sn = textureSampleLevel(src_a, samp_lin, clamp(n0, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
193 acc = acc + (sp + sn) * w;
194 } else {
195 if (p0.x >= 0.0 && p0.x <= 1.0 && p0.y >= 0.0 && p0.y <= 1.0) {
196 acc = acc + textureSampleLevel(src_a, samp_lin, p0, 0.0) * w;
197 }
198 if (n0.x >= 0.0 && n0.x <= 1.0 && n0.y >= 0.0 && n0.y <= 1.0) {
199 acc = acc + textureSampleLevel(src_a, samp_lin, n0, 0.0) * w;
200 }
201 }
202 wsum = wsum + 2.0 * w;
203 }
204 acc = acc / max(wsum, 1e-6);
122205 }
123 acc = acc / max(wsum, 1e-6);
124206 }
125207 }
126208
209 if (u.p[1].y < 0.5 && u.p[1].x >= 0.9999) {
210 store_dst(vec2<i32>(gid.xy), acc);
211 return;
212 }
127213 let orig = select(
128 textureLoad(src_a, vec2<i32>(gid.xy), 0),
214 center,
129215 textureLoad(src_b, vec2<i32>(gid.xy), 0),
130216 u.p[2].x > 0.5,
131217 );