From d246d10802d875c2c6a809fbd83fbf87ba030267 Mon Sep 17 00:00:00 2001 From: readmet3xt-lab <238408149+readmet3xt-lab@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:23:04 +0530 Subject: [PATCH] VICTORY_FILTER_3D: colour-grading tables filtered in the shader (experiment) PS_CompositeNMB (6318f669e4f17d65) posterizes light in some runs: every pixel of its output is exactly one entry of its first 33^3 table (CS_LUT3DBlend4- WithTonalAdjustments) run through the 64^3 ACES table, i.e. the first table is read unfiltered (steps of 0.44 stops, green/magenta where the channels step apart; ops2 frames 1513/1587/1657). Everything static is right: the translated and the recorded root signature's sampler s1 is linear (filter 0x14), the view is a Texture3D of the 33^3 RGBA16F texture, the table's contents are smooth, and the card filters such a texture (bound by table, by heap index, with a point-sampler heap bound, left in UAV state). With VICTORY_FILTER_3D=1 a level-0 sample of a 3D texture with a linear, clamping immediate sampler is eight textureLoads weighted in the shader, so the card's sampler is out of the path: a run with it on says whether the sampling is what fails, and is the fix if so. Off by default; part of the shader cache key. Test: both forms agree on WARP and the card. examples/capture_probe: what a recorded frame bound for one pipeline (root signatures, heap slots, constant words, 3D table contents), read from the capture's files without a device. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/examples/capture_probe.rs | 359 ++++++++++++++++++ crates/victory-gpu/src/shader_cache.rs | 1 + .../victory-shader/src/emit/filter3d_tests.rs | 182 +++++++++ crates/victory-shader/src/emit/host.rs | 44 +++ crates/victory-shader/src/emit/lower.rs | 106 ++++++ crates/victory-shader/src/emit/mod.rs | 2 + 6 files changed, 694 insertions(+) create mode 100644 crates/victory-gpu/examples/capture_probe.rs create mode 100644 crates/victory-shader/src/emit/filter3d_tests.rs diff --git a/crates/victory-gpu/examples/capture_probe.rs b/crates/victory-gpu/examples/capture_probe.rs new file mode 100644 index 0000000..73ed669 --- /dev/null +++ b/crates/victory-gpu/examples/capture_probe.rs @@ -0,0 +1,359 @@ +//! What a recorded frame (`VICTORY_RECORD`, `docs/replay.md`) bound for one +//! pipeline, read from the capture's files alone: no device is made and +//! nothing is run (`victory replay` hangs some cards). +//! +//! cargo run --release -p victory-gpu --example capture_probe -- [ids] +//! +//! For the first draw of a pipeline whose name holds `text` (the runtime names +//! host pipelines by their shaders' hashes): the root signature's static +//! samplers (of the pipeline and of the list), its root constants, the heap +//! slots constants that are heap places lead to (view descriptions and the +//! resources' descriptions), some words of the constant buffers among them as +//! the CPU last wrote them, and the start-of-frame contents of the 3D RGBA16F +//! textures shown (along x and z through the middle). Resource ids after the +//! text: their contents too (R32_FLOAT rows, RGBA32F texels; `STEP=`). +//! Written to find why PS_CompositeNMB's colour tables posterized. +#![allow(dead_code)] +#[path = "../src/replay/wire.rs"] +mod wire; + +use std::collections::HashMap; +use std::io::{Read, Seek, SeekFrom}; +use windows::Win32::Graphics::Direct3D12::*; +use wire::*; + +fn half(h: u16) -> f32 { + let (sign, exp, man) = ( + (h >> 15) as u32, + ((h >> 10) & 0x1f) as i32, + (h & 0x3ff) as f32, + ); + let v = match exp { + 0 => man * 2f32.powi(-24), + 31 => f32::INFINITY, + e => (1.0 + man / 1024.0) * 2f32.powi(e - 15), + }; + if sign == 1 { -v } else { v } +} + +fn samplers(blob: &[u8]) { + unsafe { + let mut d: Option = None; + let r = D3D12CreateVersionedRootSignatureDeserializer( + blob.as_ptr().cast(), + blob.len(), + &::IID, + std::ptr::from_mut(&mut d).cast(), + ); + if r.is_err() { + println!(" root signature: no deserializer {r:?}"); + return; + } + let d = d.unwrap(); + let Ok(desc) = d.GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1) else { + return; + }; + let desc = &(*desc).Anonymous.Desc_1_1; + let s = std::slice::from_raw_parts(desc.pStaticSamplers, desc.NumStaticSamplers as usize); + for x in s { + println!( + " static sampler s{} space {} vis {} filter {:#x} addr {} {} {} lod {}..{} bias {} aniso {} cmp {}", + x.ShaderRegister, + x.RegisterSpace, + x.ShaderVisibility.0, + x.Filter.0, + x.AddressU.0, + x.AddressV.0, + x.AddressW.0, + x.MinLOD, + x.MaxLOD, + x.MipLODBias, + x.MaxAnisotropy, + x.ComparisonFunc.0 + ); + } + } +} + +fn main() -> anyhow::Result<()> { + let args: Vec = std::env::args().collect(); + let folder = std::path::PathBuf::from(&args[1]); + let text = &args[2]; + let frame = Frame::read(&folder.join("frame.bin"))?; + let resources: HashMap = frame.resources.iter().map(|r| (r.id, r)).collect(); + let roots: HashMap = frame.roots.iter().map(|(i, b)| (*i, b)).collect(); + let heaps: HashMap = + frame.descriptor_heaps.iter().map(|h| (h.id, h)).collect(); + let pipes: HashMap = frame.pipelines.iter().map(|p| (p.id, p)).collect(); + for h in &frame.descriptor_heaps { + println!( + "descriptor heap {} kind {} count {} flags {}", + h.id, h.kind, h.count, h.flags + ); + } + let wanted: Vec = frame + .pipelines + .iter() + .filter(|p| p.name.contains(text.as_str())) + .map(|p| p.id) + .collect(); + for p in &wanted { + let pipe = pipes[p]; + println!("pipeline {p} '{}'", pipe.name); + for part in &pipe.parts { + if let Part::Root { root } = part { + println!(" root {root}"); + if let Some(b) = roots.get(root) { + samplers(&b.0); + } + } + } + } + let called = |id: u32| match resources.get(&id) { + None => format!("#{id} (none)"), + Some(r) => format!( + "#{id} '{}' dim {} {}x{}x{} m{} f{} flags {:#x} layout {}", + r.name, + r.desc.dimension, + r.desc.width, + r.desc.height, + r.desc.depth, + r.desc.mips, + r.desc.format, + r.desc.flags, + r.desc.layout + ), + }; + let mut late: HashMap<(u32, u32), Slot> = HashMap::new(); + let mut all_deltas: Vec = Vec::new(); + let mut deltas_file = std::fs::File::open(folder.join("deltas.bin"))?; + // The bytes of buffer `res` at `at`, as the CPU last wrote them by now. + let mut word_at = |deltas: &[Delta], res: u32, at: u64| -> Option { + let d = deltas + .iter() + .rev() + .find(|d| d.res == res && d.at <= at && at + 4 <= d.at + d.len)?; + let mut b = [0u8; 4]; + deltas_file + .seek(SeekFrom::Start(d.file + (at - d.at))) + .ok()?; + deltas_file.read_exact(&mut b).ok()?; + Some(u32::from_le_bytes(b)) + }; + let mut shown = 0; + let mut lut_ids: Vec = Vec::new(); + for s in &frame.submits { + for (heap, at, slot) in &s.views { + late.insert((*heap, *at), *slot); + } + let slot_at = |heap: u32, at: u32| -> Slot { + if let Some(s) = late.get(&(heap, at)) { + return *s; + } + let Some(h) = heaps.get(&heap) else { + return Slot::EMPTY; + }; + let after = h.runs.partition_point(|r| r.0 <= at); + match after.checked_sub(1).map(|n| &h.runs[n]) { + Some((first, count, slot)) if at - first < *count => *slot, + _ => Slot::EMPTY, + } + }; + all_deltas.extend(s.deltas.iter().cloned()); + for &l in s.lists.iter().filter(|&&l| l != MISSING) { + let mut pso = 0; + let mut heap = 0; + let mut list_root = 0u32; + let mut consts: HashMap> = HashMap::new(); + for c in Cmd::all(&frame.lists[l as usize].commands.0)? { + match c { + Cmd::Pipeline { pso: p } => pso = p, + Cmd::Heaps { heaps } => heap = heaps.first().copied().unwrap_or(0), + Cmd::RootSignature { + graphics: true, + root, + } => { + consts.clear(); + list_root = root; + } + Cmd::Constants { + graphics: true, + param, + offset, + values, + } => { + let all = consts.entry(param).or_default(); + let end = offset as usize + values.len(); + if all.len() < end { + all.resize(end, 0); + } + all[offset as usize..end].copy_from_slice(&values); + } + c if c.runs_shaders() && wanted.contains(&pso) && shown < 1 => { + shown += 1; + println!("draw {c:?} heap {heap} list root {list_root}"); + if let Some(b) = roots.get(&list_root) { + samplers(&b.0); + } + let mut params: Vec<_> = consts.iter().collect(); + params.sort(); + for (param, values) in params { + println!(" param {param}: {values:x?}"); + for &v in values { + if v & 31 != 0 || v >> 5 < 64 { + continue; + } + for k in 0..48u32 { + let at = (v >> 5) + k; + let sl = slot_at(heap, at); + if sl.kind == 0 { + continue; + } + let w = |i: usize| { + u32::from_le_bytes( + sl.desc[4 * i..4 * i + 4].try_into().unwrap(), + ) + }; + if sl.kind == 1 { + let base = u64::from(w(0)) | u64::from(w(1)) << 32; + let mut text = String::new(); + for off in [ + 0x50u64, 0x26c, 0x310, 0x318, 0x3c0, 0x400, 0x408, + 0x40c, 0x410, 0x500, 0x514, 0x51c, 0x520, 0x524, 0x528, + ] { + if let Some(v) = + word_at(&all_deltas, sl.res, base + off) + { + text += &format!( + " [{off:#x}]={v:#x}/{}", + f32::from_bits(v) + ); + } + } + println!(" cbv slot {at} words:{text}"); + } + println!( + " slot {at} (+{} bytes) kind {} described {} desc [{:x} {:x} {:x} {:x} {:x} {:x} {:x} {:x}] {}", + k * 32, + sl.kind, + sl.described, + w(0), + w(1), + w(2), + w(3), + w(4), + w(5), + w(6), + w(7), + called(sl.res) + ); + if let Some(r) = resources.get(&sl.res) + && r.desc.dimension == 4 + && !lut_ids.contains(&sl.res) + { + lut_ids.push(sl.res); + } + } + } + } + } + _ => {} + } + } + } + } + // Start-of-frame contents of the 3D textures shown. + let mut file = std::fs::File::open(folder.join("contents.bin"))?; + // Small float textures named on the command line: every texel. + for id in args[3..].iter().filter_map(|a| a.parse::().ok()) { + let r = resources[&id]; + let Some(c) = frame.contents.iter().find(|c| c.res == id) else { + println!("{}: no contents", called(id)); + continue; + }; + println!("{}: contents len {} file {:#x}", called(id), c.len, c.file); + if c.file == ZERO { + println!(" all zero"); + continue; + } + let mut bytes = vec![0u8; c.len as usize]; + file.seek(SeekFrom::Start(c.file))?; + file.read_exact(&mut bytes)?; + let f = |i: usize| f32::from_le_bytes(bytes[4 * i..4 * i + 4].try_into().unwrap()); + match r.desc.format { + 41 => { + let n = (r.desc.width as usize).min(bytes.len() / 4); + let step = std::env::var("STEP") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(64usize); + for i in (0..n).step_by(step) { + println!(" [{i:4}] {}", f(i)); + } + // Distinct values and the largest jump between neighbours. + let mut distinct: Vec = (0..n).map(|i| f(i).to_bits()).collect(); + distinct.dedup(); + let jump = (1..n).map(|i| (f(i) - f(i - 1)).abs()).fold(0f32, f32::max); + println!( + " runs of equal values: {} of {n}; largest step {jump}", + distinct.len() + ); + } + 2 => { + for i in 0..(bytes.len() / 16).min(16) { + println!( + " texel {i}: {:?}", + [f(4 * i), f(4 * i + 1), f(4 * i + 2), f(4 * i + 3)] + ); + } + } + _ => {} + } + } + for id in lut_ids { + let r = resources[&id]; + let Some(c) = frame.contents.iter().find(|c| c.res == id) else { + println!("{}: no contents", called(id)); + continue; + }; + println!( + "{}: contents first {} count {} len {} file {:#x}", + called(id), + c.first, + c.count, + c.len, + c.file + ); + if c.file == ZERO || r.desc.format != 10 { + continue; + } + let (w, h, d) = ( + r.desc.width as usize, + r.desc.height as usize, + r.desc.depth as usize, + ); + let pitch = (w * 8).div_ceil(256) * 256; + let mut bytes = vec![0u8; (pitch * h * d).min(c.len as usize)]; + file.seek(SeekFrom::Start(c.file))?; + file.read_exact(&mut bytes)?; + let texel = |x: usize, y: usize, z: usize| -> [f32; 4] { + let at = z * pitch * h + y * pitch + x * 8; + [0, 1, 2, 3].map(|i| { + half(u16::from_le_bytes([ + bytes[at + 2 * i], + bytes[at + 2 * i + 1], + ])) + }) + }; + let (my, mz) = (h / 2, d / 2); + println!(" along x (y={my}, z={mz}):"); + for x in 0..w { + println!(" x {x:2} {:?}", texel(x, my, mz)); + } + println!(" along z (x={}, y={my}):", w / 2); + for z in 0..d { + println!(" z {z:2} {:?}", texel(w / 2, my, z)); + } + } + Ok(()) +} diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index b291e11..4dd39b0 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -68,6 +68,7 @@ fn build() -> [u8; 32] { "VICTORY_WAVE_OWN_BITS", "VICTORY_WAVE_LOCAL", "VICTORY_F16_NEAREST", + "VICTORY_FILTER_3D", "VICTORY_HELPER_OWN", "VICTORY_FIRSTLANE_OWN", "VICTORY_FIRST_HALF", diff --git a/crates/victory-shader/src/emit/filter3d_tests.rs b/crates/victory-shader/src/emit/filter3d_tests.rs new file mode 100644 index 0000000..9964a73 --- /dev/null +++ b/crates/victory-shader/src/emit/filter3d_tests.rs @@ -0,0 +1,182 @@ +//! A level-0 sample of a 3D texture with a linear, clamping immediate +//! sampler, by the card and by hand (`VICTORY_FILTER_3D`): the same +//! trilinear values. + +use super::host::{Dispatch, Host, Root, View}; +use super::intersect_tests::build_compute_shader; +use super::lower::TEST_FILTER_3D; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; + +/// Texture size per axis. +const N: u32 = 4; + +/// Points (normalized) and the value a trilinear filter gives there of a +/// texture whose texel (x, y, z) holds (x, 10 y, 100 z, 1). +fn cases() -> Vec<([f32; 3], [f32; 4])> { + let at = |p: f32| ((p * N as f32 - 0.5).clamp(0.0, (N - 1) as f32), p); + [ + [0.3f32, 0.55, 0.8], + [0.125, 0.125, 0.125], + [0.01, 0.99, 0.5], + [0.7, 0.2, 0.33], + ] + .into_iter() + .map(|p| { + let [x, y, z] = p.map(|v| at(v).0); + (p, [x, 10.0 * y, 100.0 * z, 1.0]) + }) + .collect() +} + +/// The program: the immediate sampler of the colour-grading tables +/// (PS_CompositeNMB: clamp, linear, point mip), then for each case +/// `image_sample_lz` 3D of four channels at the case's point, stored. +fn program() -> NativeProgram { + let mut words = vec![ + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xF40C_0400, + 0xFA00_0000, // s_load_dwordx8 s[16:23], s[0:1], 0: the 3D SRV + 0xF408_0300, + 0xFA00_0020, // s_load_dwordx4 s[12:15], s[0:1], 32: the output UAV + 0x7E1E_0280, // v_mov_b32 v15, 0: output byte offsets + ]; + // s_mov_b32 s24..s27: the sampler words. + for (k, w) in [0x92u32, 0x00C0_0000, 0x1450_0000, 0] + .into_iter() + .enumerate() + { + words.extend([0xBE98_03FF + ((k as u32) << 16), w]); + } + for (i, (p, _)) in cases().iter().enumerate() { + for (reg, v) in p.iter().enumerate() { + // v_mov_b32 v, literal + words.extend([0x7E00_02FF | ((reg as u32) << 17), v.to_bits()]); + } + // image_sample_lz (0x27) 3D (dim 2), dmask xyzw, v[0:2] -> v[10:13], + // resource s[16:23], sampler s[24:27]. + words.extend([0xF000_0F10 | (0x27 << 18), 0x00C4_0A00]); + for ch in 0..4u32 { + // buffer_store_dword v<10+ch>, v15, s[12:15], 0 offen offset:... + words.extend([ + 0xE070_1000 | ((i as u32 * 4 + ch) * 4), + 0x8003_000F | ((10 + ch) << 8), + ]); + } + } + words.push(0xBF81_0000); // s_endpgm + NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 16, + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: [(ResourceType::Srv, 0, 8), (ResourceType::Uav, 8, 4)] + .map(|(kind, at, dwords)| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: at, + lower_bound: 0, + stride: 0, + dwords, + user_data: 0, + slot: 0, + }) + .to_vec(), + io: StageIo::Cs(ComputeIo { + rsrc2: 2 << 1, + threads: [1, 1, 1], + }), + code: words.into_iter().flat_map(u32::to_le_bytes).collect(), + } +} + +fn translate(by_hand: bool) -> super::HostShader { + let was = TEST_FILTER_3D.replace(Some(by_hand)); + let built = build_compute_shader(&program()); + TEST_FILTER_3D.set(was); + let mut shader = built.expect("translates").0; + // (The tests' builder leaves the root signature's samplers out.) + shader.static_samplers = shader + .samplers + .iter() + .map(|&w| super::StaticSampler::from_words(w)) + .collect(); + shader +} + +/// The switch changes the program (eight reads and their weights for each +/// sample), and only with it on; the sampler stays bound either way. +#[test] +fn the_switch_takes_the_other_form() { + let card = translate(false); + let hand = translate(true); + assert_ne!(card.dxil, hand.dxil); + assert!(hand.dxil.len() > card.dxil.len()); + assert_eq!(card.static_samplers, hand.static_samplers); + assert_eq!(card.static_samplers[0].filter, 0x14, "linear, point mip"); +} + +/// Both forms give the trilinear values, on WARP and on the card. +#[test] +fn by_hand_and_by_the_card_agree() { + let texels: Vec<[f32; 4]> = (0..N * N * N) + .map(|i| { + [ + (i % N) as f32, + 10.0 * (i / N % N) as f32, + 100.0 * (i / (N * N)) as f32, + 1.0, + ] + }) + .collect(); + let cases = cases(); + for (name, warp) in [("WARP", true), ("hardware", false)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {name} device; skipped"); + continue; + }; + for by_hand in [false, true] { + let shader = translate(by_hand); + let (root, pso) = host.compute_pipeline(&shader).unwrap(); + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![( + 0, + Root::Constants(vec![0; shader.user_data_dwords() as usize]), + )], + views: &[ + View::Texture3D(N, N, N, &texels), + View::RawUav(4 * cases.len() as u32), + ], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap(); + let got: Vec = out[0].iter().copied().map(f32::from_bits).collect(); + for (i, (p, want)) in cases.iter().enumerate() { + for ch in 0..4 { + let g = got[4 * i + ch]; + // The card's weights have 8 fractional bits. + let tolerance = 0.01 * (1.0 + want[ch].abs()); + assert!( + (g - want[ch]).abs() <= tolerance, + "{name} by_hand={by_hand} at {p:?} channel {ch}: {g} not {}", + want[ch] + ); + } + } + } + } +} diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 8bfb9d7..c24e348 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -996,6 +996,8 @@ pub enum View<'a> { Texture(u32, u32, &'a [[f32; 4]]), /// An RGBA32F cube SRV (face size, mip count, texels in D3D subresource order). Cube(u32, u16, &'a [[f32; 4]]), + /// An RGBA32F 3D texture SRV (width, height, depth, texels x fastest). + Texture3D(u32, u32, u32, &'a [[f32; 4]]), /// A raw buffer UAV of this many dwords, zeroed. RawUav(u32), /// An RGBA32F texture UAV (width, height), zeroed. @@ -1175,6 +1177,48 @@ impl Host { let mut at = views.GetCPUDescriptorHandleForHeapStart(); at.ptr += i * view_size; match *v { + View::Texture3D(w, h, depth, texels) => { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE3D, + DepthOrArraySize: depth as u16, + ..texture(w, h, D3D12_RESOURCE_FLAG_NONE) + }; + let tex = make( + D3D12_HEAP_TYPE_DEFAULT, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + let pitch = (w as usize * 16).next_multiple_of(256); + let upload = make( + D3D12_HEAP_TYPE_UPLOAD, + &buffer( + (pitch * (h * depth) as usize) as u64, + D3D12_RESOURCE_FLAG_NONE, + ), + D3D12_RESOURCE_STATE_GENERIC_READ, + )?; + let mut p = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut p)).map_err(err)?; + for (row, line) in texels.chunks(w as usize).enumerate() { + std::ptr::copy_nonoverlapping( + line.as_ptr().cast::(), + p.cast::().add(row * pitch), + line.len() * 16, + ); + } + upload.Unmap(0, None); + let mut from = footprint(&upload, w, h); + from.Anonymous.PlacedFootprint.Footprint.Depth = depth; + list.CopyTextureRegion(&subresource(&tex), 0, 0, 0, &from, None); + keep.push(upload); + list.ResourceBarrier(&[transition( + &tex, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + dev.CreateShaderResourceView(&tex, None, at); + keep.push(tex); + } View::Texture(..) | View::Cube(..) => { let (w, h, mut texels, faces, mips) = match *v { View::Texture(w, h, t) => (w, h, t, 1, 1), diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 72af2be..0093bac 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1112,6 +1112,40 @@ fn f16_nearest_on() -> bool { thread_local! { /// A test's choice for [`f16_nearest_on`], for its thread only. pub(super) static TEST_F16_NEAREST: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// A test's choice for [`filter_3d_on`], for its thread only. + pub(super) static TEST_FILTER_3D: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// `VICTORY_FILTER_3D=1`: a level-0 sample of a 3D texture with an immediate +/// sampler that filters linearly and clamps (`image_sample_lz`: the colour +/// grading's 33^3 and 64^3 tables in PS_CompositeNMB) is done in the shader: +/// the eight texels around the point are read as they are (`textureLoad`) +/// and weighted by distance, instead of the card's filtered sample. +/// Off by default: an experiment. In some runs the composite's first table +/// came out unfiltered (each pixel exactly one table entry: posterized light +/// in steps of 0.44 stops, green and magenta fringes where the channels step +/// apart), with every static part right: the root signature's sampler +/// linear, the view a Texture3D of the 33^3 RGBA16F texture, its contents +/// smooth, and the card filtering such a texture in a test program. Reads +/// that bypass the sampler say whether the sampling is what fails. +fn filter_3d_on() -> bool { + #[cfg(test)] + if let Some(on) = TEST_FILTER_3D.get() { + return on; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_FILTER_3D").is_some_and(|v| v == "1")) +} + +/// Whether immediate sampler words filter linearly in both directions +/// (any mip filter) without anisotropy, comparison or min/max reduction, +/// and clamp on all three axes: what [`filter_3d_on`] does by hand. +fn linear_clamp_sampler(words: &[u32]) -> bool { + let Some(&[w0, w1, w2, w3]) = words.get(..4) else { + return false; + }; + let s = super::sampler::StaticSampler::from_words([w0, w1, w2, w3]); + s.filter & !1 == 0x14 && s.address == [3, 3, 3] } /// `VICTORY_WAVE_OWN_BITS=0`: a wave OR where not every lane runs is refused as before @@ -11363,6 +11397,78 @@ impl<'a> Lower<'a> { }; call_sample(self, name, op, &args, &mut gathered) } + 62 if kind == 4 + && name == "image_sample_lz" + && filter_3d_on() + && sampler_choice.is_none() + && matches!(ss, Source::Constant(words) if linear_clamp_sampler(words)) => + { + // Trilinear by hand at level 0 ([`filter_3d_on`]): the + // texel centres around the point, their indices clamped + // to the texture (the sampler clamps), weighted by the + // point's place between them. + let (i32t, f32t) = (self.s.t.i32, self.s.t.f32); + let level = self.s.m.i32(0); + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, level]); + let half = self.s.m.f32(0.5f32.to_bits()); + let one = self.s.m.f32(1.0f32.to_bits()); + let zero = self.s.m.f32(0); + let (mut lo, mut hi, mut part) = ([iu; 3], [iu; 3], [fu; 3]); + for k in 0..3 { + let n = self.s.m.extract(c, d, k as u32); + let n = self.s.m.cast(c, Cast::UiToFp, n, f32t); + let last = self.s.m.bin(c, Bin::Sub, n, one); + let t = self.s.m.bin(c, Bin::Mul, cs[k], n); + let t = self.s.m.bin(c, Bin::Sub, t, half); + let first = self.unary(27, t); // round down + part[k] = self.s.m.bin(c, Bin::Sub, t, first); + let next = self.s.m.bin(c, Bin::Add, first, one); + for (slot, x) in [(&mut lo[k], first), (&mut hi[k], next)] { + let x = self.binary(35, x, zero); // maximum + let x = self.binary(36, x, last); // minimum + *slot = self.s.m.cast(c, Cast::FpToSi, x, i32t); + } + } + // The eight texels, x fastest. + let mut texels = Vec::with_capacity(8); + for n in 0..8 { + let pick = |k: usize| if n >> k & 1 == 0 { lo[k] } else { hi[k] }; + let r = self.s.op( + c, + "textureLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 66, + &[h, level, pick(0), pick(1), pick(2), iu, iu, iu], + ); + texels.push(r); + } + let lerp = |l: &mut Self, a: V, b: V, t: V| { + let d = l.s.m.bin(c, Bin::Sub, b, a); + let d = l.s.m.bin(c, Bin::Mul, d, t); + l.s.m.bin(c, Bin::Add, a, d) + }; + let mut g = [fu; 4]; + for (ch, slot) in g.iter_mut().enumerate() { + let mut v: Vec = texels + .iter() + .map(|&r| self.s.m.extract(c, r, ch as u32)) + .collect(); + // Along x, then y, then z. + for (k, &t) in part.iter().enumerate() { + let step = 1 << k; + for i in (0..8).step_by(2 * step) { + v[i] = lerp(self, v[i], v[i + step], t); + } + } + *slot = v[0]; + } + gathered = Some(g); + texels[0] + } 62 => { let lod = if name == "image_sample_l" { let x = addr_packed(self, coord_base, coords)?; diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 5c191a7..1e916a5 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -87,6 +87,8 @@ mod cube_lod_tests; #[cfg(all(test, windows))] mod diff_tests; #[cfg(all(test, windows))] +mod filter3d_tests; +#[cfg(all(test, windows))] mod intersect_tests; #[cfg(all(windows, any(test, feature = "host")))] pub mod host;