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 <[email protected]>
This commit is contained in:
1 parent
9a791323ba
commit
d246d10802
6 files changed
+694
No files matched your search
@@ -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<reg>, 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<f32> = 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]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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::<u8>(),
|
||||
p.cast::<u8>().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),
|
||||
|
||||
@@ -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<Option<bool>> = 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<Option<bool>> = 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<bool> = 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<V> = 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)?;
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user