diff --git a/crates/xcl/src/gpu/desc.rs b/crates/xcl/src/gpu/desc.rs index 0097c70e9..fa6166061 100644 --- a/crates/xcl/src/gpu/desc.rs +++ b/crates/xcl/src/gpu/desc.rs @@ -277,6 +277,18 @@ pub fn image_d3d12(t: &Image) -> Option<(D3D12_RESOURCE_DESC, D3D12_SHADER_RESOU Some((res, v)) } +/// S# word 2 fields that make [`sampler_d3d12`]'s filter blend: XY_MAG_FILTER [21:20] and +/// XY_MIN_FILTER [23:22] other than point (linear or anisotropic), MIP_FILTER [27:26] linear. +pub const SAMPLER_XY_FILTER: u32 = 0x00F0_0000; +pub const SAMPLER_MIP_FILTER: u32 = 0x0C00_0000; +pub const SAMPLER_MIP_LINEAR: u32 = 0x0800_0000; + +/// Whether a sample through the S# with word 2 `w2` can return a blend of texels or mips +/// rather than one texel (the host filter [`sampler_d3d12`] makes is not MIN_MAG_MIP_POINT). +pub fn sampler_filters(w2: u32) -> bool { + w2 & SAMPLER_XY_FILTER != 0 || w2 & SAMPLER_MIP_FILTER == SAMPLER_MIP_LINEAR +} + /// D3D12 sampler from an S#. Border colours from the console's table (type 3) become /// transparent black. `comparison` selects the comparison variant (image_*_c). pub fn sampler_d3d12(w: &[u32; 4], comparison: bool) -> D3D12_SAMPLER_DESC { diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs index 14b175fd3..54a4905f0 100644 --- a/crates/xcl/src/gpu/dxil/lower_image.rs +++ b/crates/xcl/src/gpu/dxil/lower_image.rs @@ -9,6 +9,7 @@ use super::lower::{err, LResult, Lw, VAR_VGPR}; use super::module::{BinOp, Pred, Value}; use super::ops::{AtomicOp, CompType, Sampler, TexKind, Texture}; use super::ops_core::op; +use crate::gpu::desc; use crate::gpu::rdna2::{self, Decoded}; /// Upper bound on valid SRV indices in the shared shader-visible view heap @@ -1047,6 +1048,12 @@ impl Lw { let act = self.act(); let valid = self.valid_tsharp(tw0, tw1, tw3); let run = self.land(act, valid); + // the T#'s format, for D16 reads of UNORM / SNORM texels (`d16_fmt`) + let ifmt = self.lshrc(tw1, 20); + let ifmt = self.andc(ifmt, 0x1FF); + let c77 = self.c(77); + let ifmt = self.umin(ifmt, c77); + let finfo = self.fmt_info(ifmt); let z0 = self.c(0); let safe_tw0 = self.sel(valid, tw0, z0); let comps: Vec = (0..4).filter(|c| dmask >> c & 1 == 1).collect(); @@ -1303,12 +1310,45 @@ impl Lw { }; let n = if gather { 4 } else { comps.len() }; let sel: Vec = (0..n).map(|k| if gather { k } else { comps[k] as usize }).collect(); + // D16: a gather or a sample whose sampler cannot filter returns texels, codes of the + // format (`d16_fmt`); a filtered sample is a blend of them, not a code, and keeps the + // host's value (truncated, as d16_fmt's float channels). + enum Filters { + No, + Yes, + /// whether the S# filters, read when the shader runs + Dynamic(Value), + } + let filters = match self.static_samplers.get(&d.pc).copied() { + _ if gather || !d16 => Filters::No, + Some(w) if desc::sampler_filters(w[2]) => Filters::Yes, + Some(_) => Filters::No, + None => { + let s2 = self.sreg(ssamp + 2); + let xy = self.andc(s2, desc::SAMPLER_XY_FILTER); + let xy = self.cmpc(Pred::Ne, xy, 0); + let mip = self.andc(s2, desc::SAMPLER_MIP_FILTER); + let mip = self.cmpc(Pred::Eq, mip, desc::SAMPLER_MIP_LINEAR); + Filters::Dynamic(self.lor(xy, mip)) + } + }; let vals: Vec = sel .iter() .map(|&c| { if d16 { - // f32tof16(asfloat(e)) - self.s.f32_to_f16(r[c]) + // f32tof16(asfloat(e)); UNORM / SNORM rounded once (`d16_fmt`). A + // gather's four values are of the one component DMASK names. + let comp = if gather { comps.first().copied().unwrap_or(0) as u32 } else { c as u32 }; + let sel = self.c(4 + comp); + match filters { + Filters::No => self.d16_fmt(rb[c], sel, finfo), + Filters::Yes => self.f16_rtz(r[c]), + Filters::Dynamic(fl) => { + let texel = self.d16_fmt(rb[c], sel, finfo); + let host = self.f16_rtz(r[c]); + self.sel(fl, host, texel) + } + } } else { rb[c] } @@ -1456,7 +1496,7 @@ impl Lw { } } if ms { - return self.mimg_msaa(base, &ic, tw0, lkind, cls, &comps, vdata, d16, act, run); + return self.mimg_msaa(base, &ic, tw0, lkind, cls, &comps, vdata, d16, act, run, finfo); } match base { "load" | "load_mip" => { @@ -1519,8 +1559,8 @@ impl Lw { .iter() .map(|&c| { let x = r[c as usize]; - let fx = self.f(x); - let h = self.s.f32_to_f16(fx); + let sel = self.c(4 + c as u32); + let h = self.d16_fmt(x, sel, finfo); let lo = self.andc(x, 0xFFFF); let fl = self.cmpc(Pred::Eq, cls, 0); self.sel(fl, h, lo) @@ -1616,7 +1656,7 @@ impl Lw { /// DMASK component of the four samples fragment .. fragment + 3 (a gather of samples). /// Samples past the resource's count read 0 (made explicit: D3D leaves them undefined). #[allow(clippy::too_many_arguments)] - fn mimg_msaa(&mut self, base: &str, ic: &[Value], tw0: Value, kind: TexKind, cls: Value, comps: &[u64], vdata: u64, d16: bool, act: Value, run: Value) -> LResult<()> { + fn mimg_msaa(&mut self, base: &str, ic: &[Value], tw0: Value, kind: TexKind, cls: Value, comps: &[u64], vdata: u64, d16: bool, act: Value, run: Value, finfo: Value) -> LResult<()> { let nc = kind.coords(); let frag = ic[nc]; let coords = ic[..nc].to_vec(); @@ -1662,11 +1702,18 @@ impl Lw { } else { comps.iter().map(|&c| self.rd(tmps[0][c as usize])).collect() }; + // the component of each value: msaa_load's are all of one + let comp_of: Vec = if base == "msaa_load" { + vec![comps.first().copied().unwrap_or(0) as u32; raw.len()] + } else { + comps.iter().map(|&c| c as u32).collect() + }; let vals: Vec = if d16 { raw.iter() - .map(|&x| { - let fx = self.f(x); - let h = self.s.f32_to_f16(fx); + .zip(comp_of) + .map(|(&x, comp)| { + let sel = self.c(4 + comp); + let h = self.d16_fmt(x, sel, finfo); let lo = self.andc(x, 0xFFFF); let fl = self.cmpc(Pred::Eq, cls, 0); self.sel(fl, h, lo) diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index fe04b4ac6..57396a27d 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -523,6 +523,89 @@ impl Lw { self.s.m.set_insert_before_term(prev_ins); r } + /// A D16 format load's non-integer channel `s` (decoded f32 bits) of DST_SEL `sel` as f16. + /// UNORM / SNORM data is `code / (2^w - 1)`, rounded once to nearest as RDNA2 does: its + /// binary expansion repeats the w-bit code, so its first 32 bits decide the rounding (a tie + /// cannot happen). Other channels truncate (`f16_rtz`), as RDNA2 does, whatever the host's + /// `legacyF32ToF16` rounds to. + pub(crate) fn d16_fmt(&mut self, s: Value, sel: Value, info: Value) -> Value { + let f = self.f(s); + let plain = self.f16_rtz(f); + let ty = self.lshrc(info, 3); + let ty = self.andc(ty, 7); + let four = self.c(4); + let k = self.sub(sel, four); + let k = self.andc(k, 3); + let six = self.c(6); + let k6 = self.mul(k, six); + let eight = self.c(8); + let shift = self.add(k6, eight); + let w = self.bin(BinOp::LShr, info, shift); + let w = self.andc(w, 63); + let snorm = self.cmpc(Pred::Eq, ty, 1); + let one = self.c(1); + let wm1 = self.sub(w, one); + let we = self.sel(snorm, wm1, w); + let dmax = self.bin(BinOp::Shl, one, we); + let dmax = self.sub(dmax, one); + // the code, back from the decoded value (within 2 ULP of exact) + let zf = self.fc(0.0); + let onef = self.fc(1.0); + let a = self.fabs(f); + let u = self.fmax(f, zf); + let a = self.sel(snorm, a, u); + let a = self.fmin(a, onef); + let df = self.uitof(dmax); + let y = self.fmul(a, df); + let y = self.un(crate::gpu::dxil::ops_core::op::ROUND_NE, y); + let y = self.ftoui(y); + // first 32 bits of y / dmax + let y64 = self.zext64(y); + let k32 = self.c64(32); + let y64 = self.bin(BinOp::Shl, y64, k32); + let d64 = self.zext64(dmax); + let p = self.bin(BinOp::UDiv, y64, d64); + let p = self.trunc32(p); + let lz = self.lzcnt(p); + let fourteen = self.c(14); + let e = self.sub(fourteen, lz); + // normal: 11 bits after the leading one and the round bit + let pn = self.bin(BinOp::Shl, p, lz); + let b = self.lshrc(pn, 20); + let half_ = self.lshrc(b, 1); + let rb = self.andc(b, 1); + let m = self.add(half_, rb); + let em1 = self.sub(e, one); + let eh = self.shlc(em1, 10); + let normal = self.add(eh, m); + // subnormal + let s8 = self.lshrc(p, 8); + let r7 = self.lshrc(p, 7); + let r7 = self.andc(r7, 1); + let sub = self.add(s8, r7); + let is_normal = self.cmp(Pred::SGe, e, one); + let h = self.sel(is_normal, normal, sub); + let zero = self.c(0); + let y0 = self.cmpc(Pred::Eq, y, 0); + let h = self.sel(y0, zero, h); + let full = self.cmp(Pred::UGe, y, dmax); + let h = self.selc(full, 0x3C00, h); + let neg = self.fcmp(Pred::FOLt, f, zf); + let sbit = self.c(0x8000); + let sgn = self.land(snorm, neg); + let sgn = self.sel(sgn, sbit, zero); + let h = self.or(h, sgn); + // which channels: UNORM / SNORM (ty 0 / 1) of 2..16 bits, a component (sel >= 4) + let is_norm = self.cmpc(Pred::ULe, ty, 1); + let comp = self.cmpc(Pred::UGe, sel, 4); + let w_lo = self.cmpc(Pred::UGe, w, 2); + let w_hi = self.cmpc(Pred::ULe, w, 16); + let use_n = self.land(is_norm, comp); + let use_n = self.land(use_n, w_lo); + let use_n = self.land(use_n, w_hi); + self.sel(use_n, h, plain) + } + fn fmt_desc(&mut self, d3: Value, mtbuf_fmt: Option) -> FmtDesc { let key = (d3, mtbuf_fmt); if let Some(&cached) = self.fmt_desc_cache.get(&key) { @@ -1312,8 +1395,8 @@ impl Lw { if let Some((_, _, high)) = d16_format { let cur0 = self.vreg(vdata); let lo16 = self.andc(s_val, 0xFFFF); - let sf = self.f(s_val); - let h16 = self.s.f32_to_f16(sf); + let sel0 = self.andc(d3, 7); + let h16 = self.d16_fmt(s_val, sel0, c1.desc.info); let h = self.sel(c1.desc.isint, lo16, h16); if high { let h = self.shlc(h, 16); @@ -1357,8 +1440,9 @@ impl Lw { let half = |lw: &mut Lw, comp: u64| -> Value { let s = decode_sel(lw, comp); let lo = lw.andc(s, 0xFFFF); - let sf = lw.f(s); - let h = lw.s.f32_to_f16(sf); + let sel = lw.lshrc(d3, 3 * comp as u32); + let sel = lw.andc(sel, 7); + let h = lw.d16_fmt(s, sel, desc.info); lw.sel(desc.isint, lo, h) }; for i in 0..count { @@ -1385,8 +1469,7 @@ impl Lw { let sel = lw.andc(sel, 7); let s = lw.dst_sel(&c, sel, desc.isint); let lo = lw.andc(s, 0xFFFF); - let sf = lw.f(s); - let h = lw.s.f32_to_f16(sf); + let h = lw.d16_fmt(s, sel, desc.info); lw.sel(desc.isint, lo, h) }; for i in 0..count { diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 7851791c9..87e81871a 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -5,6 +5,7 @@ use std::fmt::Write as _; use super::{elements_at, param_registers, ps_attribute_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, Mode, MsInterface, Options, KERNEL_EXPORTS, KERNEL_LANES, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_SPLIT_MAGIC, KERNEL_SPLIT_SGPRS, KERNEL_VGPRS, MESH_HEADER}; use super::upper_lanes::Read; +use crate::gpu::desc; use crate::gpu::dxbc::SigElement; use crate::gpu::rdna2::{self, Decoded, Encoding, Operand, Variant}; @@ -2194,7 +2195,8 @@ impl Em { if let Some((_, components, high)) = d16_format { let half = |component: u64| { let selected = format!("dst_sel({t}_c, ({d3} >> {}u) & 7u, {t}_int)", 3 * component); - format!("select({t}_int, {selected} & 0xFFFFu, f32tof16(asfloat({selected})))") + let sel = format!("(({d3} >> {}u) & 7u)", 3 * component); + format!("select({t}_int, {selected} & 0xFFFFu, d16_fmt({selected}, {sel}, {t}_info))") }; let mut assigns = Vec::new(); if high { @@ -2634,6 +2636,7 @@ impl Em { // indexing `ResourceDescriptorHeap` (valid XCL T#: type >= 8, BASE_ADDRESS_HI cleared, // SRV index < (1 << 21) - 1 so `tw0 + 1` stays in bounds without wrapping). self.line(&format!("bool {t}_ok = (({tw3} >> 28) >= 8u) && ((({tw1}) & 0xFFu) == 0u) && (({tw0}) < {}u);", crate::gpu::dxil::lower_image::VIEW_HEAP_MAX_SRV)); + self.line(&format!("uint {t}_finfo = FMT_INFO[min(({tw1} >> 20) & 0x1FFu, 77u)];")); let comps: Vec = (0..4).filter(|c| dmask >> c & 1 == 1).collect(); // write the selected result components (`r` is a uint4 of raw bits); D16 packs halves let write_result = |s: &mut Self, r: &str, n: usize, sel: &dyn Fn(usize) -> u64, half: &dyn Fn(&str) -> String| { @@ -2655,7 +2658,18 @@ impl Em { } } }; - let f16 = |e: &str| format!("f32tof16(asfloat({e}))"); + // UNORM / SNORM rounded once (`d16_fmt`); the component is the swizzle letter of `e` + let finfo = format!("{t}_finfo"); + let comp_of = |e: &str| match e.chars().last() { + Some('x') => 0, + Some('y') => 1, + Some('z') => 2, + _ => 3, + }; + let f16 = { + let finfo = finfo.clone(); + move |e: &str| format!("d16_fmt({e}, {}u, {finfo})", 4 + comp_of(e)) + }; if sampling { if matches!(dim, 6 | 7) { @@ -2815,7 +2829,29 @@ impl Em { let n = if gather { 4 } else { comps.len() }; let comps2 = comps.clone(); let sel = move |k: usize| if gather { k as u64 } else { comps2[k] }; - write_result(self, &format!("{t}_r"), n, &sel, &f16); + // D16: a gather or a sample whose sampler cannot filter returns texels, codes of the + // format (`d16_fmt`); a filtered sample is a blend of them, not a code, and keeps the + // host's value (truncated, as d16_fmt's float channels). + let point = match self.static_ss.get(&d.pc) { + _ if gather || !d16 => "true".to_string(), + Some(w) => (!desc::sampler_filters(w[2])).to_string(), + None => { + let s2 = self.sreg(ssamp + 2); + self.line(&format!( + "bool {t}_pt = (({s2}) & {:#X}u) == 0u && (({s2}) & {:#X}u) != {:#X}u;", + desc::SAMPLER_XY_FILTER, + desc::SAMPLER_MIP_FILTER, + desc::SAMPLER_MIP_LINEAR + )); + format!("{t}_pt") + } + }; + let half = move |e: &str| match point.as_str() { + "true" => f16(e), + "false" => format!("f16_rtz(asfloat({e}))"), + p => format!("select({p}, {}, f16_rtz(asfloat({e})))", f16(e)), + }; + write_result(self, &format!("{t}_r"), n, &sel, &half); return Ok(()); } @@ -2843,7 +2879,7 @@ impl Em { "uint4 {t}_r = ({t}_ok ? asuint(float4({t}_T.CalculateLevelOfDetail({t}_S, {coord}), {t}_T.CalculateLevelOfDetailUnclamped({t}_S, {coord}), 0.0f, 0.0f)) : uint4(0u, 0u, 0u, 0u));" )); let comps2 = comps.clone(); - write_result(self, &format!("{t}_r"), comps.len(), &move |k| comps2[k], &f16); + write_result(self, &format!("{t}_r"), comps.len(), &move |k| comps2[k], &|e: &str| format!("f32tof16(asfloat({e}))")); return Ok(()); } @@ -2931,7 +2967,7 @@ impl Em { )); } let cls = format!("{t}_cls"); - let half = move |e: &str| format!("(({cls} == 0u) ? f32tof16(asfloat({e})) : ({e} & 0xFFFFu))"); + let half = move |e: &str| format!("(({cls} == 0u) ? d16_fmt({e}, {}u, {finfo}) : ({e} & 0xFFFFu))", 4 + comp_of(e)); let comps2 = comps.clone(); write_result(self, &format!("{t}_r"), comps.len(), &move |k| comps2[k], &half); } @@ -5944,6 +5980,29 @@ void st_bytes(uint a, uint4 r, uint n) { st_part(b, m << s, r.x << s); if (s != 0u && s + 8u * n > 32u) st_part(b + 4u, m >> (32u - s), r.x >> (32u - s)); } +// code / (2^w - 1) as f16, rounded once to nearest (RDNA2's D16 of UNORM / SNORM data): the +// binary expansion repeats the w-bit code, so p (its first 32 bits) decides the rounding, and a +// tie cannot happen. f32tof16 of the decoded f32 rounds twice, the second time toward zero. +uint norm16_rep(uint y, uint w) { + uint d = (1u << w) - 1u; + if (y == 0u) return 0u; + if (y >= d) return 0x3C00u; + uint p = (uint)(((uint64_t)y << 32) / (uint64_t)d); + uint lz = 31u - firstbithigh(p); + int e = 14 - (int)lz; + if (e >= 1) { uint b = (p << lz) >> 20; return ((uint)(e - 1) << 10) + (b >> 1) + (b & 1u); } + return (p >> 8) + ((p >> 7) & 1u); +} +// a D16 format load's non-integer channel x (decoded f32 bits) of DST_SEL sel +uint d16_fmt(uint x, uint sel, uint info) { + uint ty = (info >> 3) & 7u; + uint w = (info >> (8u + 6u * ((sel - 4u) & 3u))) & 63u; + if (ty > 1u || sel < 4u || w < 2u || w > 16u) return f16_rtz(asfloat(x)); + float f = asfloat(x); + if (ty == 0u) return norm16_rep((uint)round(saturate(f) * (float)((1u << w) - 1u)), w); + uint h = norm16_rep((uint)round(min(abs(f), 1.0f) * (float)((1u << (w - 1u)) - 1u)), w - 1u); + return h | select(f < 0.0f, 0x8000u, 0u); +} uint dst_sel(uint4 c, uint sel, bool isint) { return select(sel == 0u, 0u, select(sel == 1u, select(isint, 1u, 0x3F800000u), pick4(c, (sel - 4u) & 3u))); } "#; diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 8965a41ca..a58ba9b7e 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1766,6 +1766,85 @@ fn gpu_typed_buffer_loads_and_stores() { assert_eq!(r.sgpr[50], 1 | 1 << 5, "s_bitset1"); } +#[test] +fn gpu_buffer_d16_loads_of_32_bit_floats_truncate() { + // RDNA2 packs a D16 load of a 32-bit float toward zero (boykopovar/AnyPS5#22750). The host's + // legacyF32ToF16 truncates on some drivers and rounds to nearest on others (vkd3d-proton), so + // these values tell the two apart: 1 + 1.5 / 1.75 ulp, overflow, a denormal half-way. + if !gpu_ready() { + return; + } + const IN: [u32; 8] = [0x3F80_3000, 0x3F80_3800, 0x4788_B800, 0xC788_B800, 0x477F_FF00, 0x33C0_0000, 0xBFC0_0000, 0x7F80_0000]; + const WANT: [u16; 8] = [0x3C01, 0x3C01, 0x7BFF, 0xFBFF, 0x7BFF, 0x0001, 0xBE00, 0x7C00]; + let ident = 4 | 5 << 3 | 6 << 6 | 7 << 9; + let code = prog(&[("BUFFER_LOAD_FORMAT_D16_X", "ENC_MUBUF", &[("VDATA", 10), ("VADDR", 1), ("SRSRC", 3), ("SOFFSET", 128), ("OFFEN", 1)], None)]); + let mut mem = vec![0u32; 512]; + mem[0x40..0x48].copy_from_slice(&IN); + let mut st = KernelState::default(); + st.sgpr[12..16].copy_from_slice(&[0x100, 0, 0x100, ident | 22 << 12]); // 32_FLOAT + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[1] = 4 * (l % 8) as u32; + } + let r = runner::run_code(&code, &st, &mem).unwrap(); + let mut bad = Vec::new(); + for l in 0..64 { + let got = (r.vgpr[l][10] & 0xFFFF) as u16; + if got != WANT[l % 8] { + bad.push(format!("lane {l}: {:#010x} -> {got:#06x}, want {:#06x}", IN[l % 8], WANT[l % 8])); + } + } + assert!(bad.is_empty(), "{} of 64 differ: +{}", bad.len(), bad.join(" +")); +} + +/// D16 format loads of 16_UNORM / 16_SNORM: RDNA2 rounds the normalised value to f16 once, to +/// nearest even (XCL-BT-020, gfx1031; AnyPS5#22750 over 256 16-bit codes, gfx1036). 64 lanes each +/// load their own code; the expected halves are the exact value rounded once. +#[test] +fn gpu_buffer_d16_loads_of_16_bit_norms_round_once() { + if !gpu_ready() { + return; + } + const UNORM: [u16; 64] = [0x0000, 0xFFFF, 0xFFAF, 0xFFEF, 0x0801, 0x0803, 0x0805, 0x0807, 0x8000, 0x7FFF, 0x1234, 0x4321, 0xEBBE, 0x78FA, 0xE20F, 0xF2BF, 0x4275, 0x8398, 0xBD51, 0x1BC1, 0xB57A, 0x7378, 0x64F0, 0x9631, 0xA93D, 0x1078, 0xE750, 0x620A, 0x03BF, 0x5971, 0x9EFA, 0xA070, 0xC8CB, 0x2DF2, 0xF2DD, 0xEEA9, 0x028F, 0xD55A, 0x6C19, 0x23A3, 0xE272, 0x61DF, 0x186A, 0xB09A, 0x0F62, 0xAD5F, 0x89C7, 0xDB80, 0x92C3, 0x507A, 0x6FF9, 0x5CFD, 0xF790, 0xCFC4, 0xB827, 0xE334, 0x70BB, 0xF609, 0x5ADA, 0x4EDA, 0xDEC6, 0xCA73, 0xAAE7, 0x0E6C]; + const UNORM_F16: [u16; 64] = [0x0000, 0x3C00, 0x3BFD, 0x3BFF, 0x2801, 0x2802, 0x2803, 0x2804, 0x3800, 0x3800, 0x2C8D, 0x3432, 0x3B5E, 0x3790, 0x3B10, 0x3B96, 0x3427, 0x381D, 0x39EB, 0x2EF0, 0x39AC, 0x3738, 0x364F, 0x38B2, 0x394A, 0x2C1E, 0x3B3B, 0x3621, 0x237E, 0x3597, 0x38F8, 0x3904, 0x3A46, 0x31BE, 0x3B97, 0x3B75, 0x211E, 0x3AAB, 0x36C2, 0x3074, 0x3B14, 0x361E, 0x2E1B, 0x3985, 0x2BB1, 0x396B, 0x384E, 0x3ADC, 0x3896, 0x3508, 0x3700, 0x35D0, 0x3BBD, 0x3A7E, 0x39C1, 0x3B1A, 0x370C, 0x3BB0, 0x35AE, 0x34EE, 0x3AF6, 0x3A54, 0x3957, 0x2B36]; + const SNORM: [u16; 64] = [0x0000, 0x7FFF, 0x8000, 0x8001, 0x7FF7, 0x8009, 0x0401, 0x0403, 0xFBFF, 0xC000, 0x4000, 0x0001, 0x0669, 0x5B5B, 0x93FA, 0x9DB5, 0xAA7E, 0x4B72, 0x6920, 0xC24D, 0x6F99, 0x4FDA, 0x507E, 0xE531, 0x1C88, 0x0D1A, 0x3151, 0xDB97, 0xDA66, 0xADB0, 0xF832, 0xE808, 0xFE62, 0xD349, 0xEFCC, 0xFC89, 0xFF9D, 0xAEB5, 0x3CAB, 0xA475, 0x1B07, 0xFCAC, 0x2B11, 0x067A, 0xA023, 0x872F, 0xAC57, 0x775A, 0x3629, 0x315A, 0xA1B8, 0x6C88, 0xA7C3, 0xD5E3, 0xECDC, 0x4E5C, 0x6CEB, 0xFB6D, 0x0ED9, 0x00B7, 0x0A51, 0x205A, 0x490A, 0x246B]; + const SNORM_F16: [u16; 64] = [0x0000, 0x3C00, 0xBC00, 0xBC00, 0x3BFF, 0xBBFF, 0x2801, 0x2803, 0xA801, 0xB800, 0x3800, 0x0200, 0x2A69, 0x39B6, 0xBAC0, 0xBA25, 0xB958, 0x38B7, 0x3A92, 0xB7B6, 0x3AFA, 0x38FE, 0x3908, 0xB2B4, 0x3322, 0x2E8D, 0x362A, 0xB48D, 0xB4B3, 0xB925, 0xABCE, 0xB1FE, 0xA278, 0xB597, 0xB00D, 0xA6EE, 0x9A30, 0xB915, 0x3795, 0xB9B9, 0x32C2, 0xA6A8, 0x3562, 0x2A7A, 0xB9FE, 0xBB8D, 0xB93B, 0x3B76, 0x36C5, 0x362B, 0xB9E5, 0x3AC9, 0xB984, 0xB544, 0xB0C9, 0x38E6, 0x3ACF, 0xA893, 0x2F6D, 0x1DB8, 0x2D29, 0x340B, 0x3891, 0x348D]; + let ident = 4 | 5 << 3 | 6 << 6 | 7 << 9; + let vs = |base: u32, fmt: u32| [base, 0, 0x100, ident | fmt << 12]; + let code = prog(&[ + ("BUFFER_LOAD_FORMAT_D16_X", "ENC_MUBUF", &[("VDATA", 10), ("VADDR", 1), ("SRSRC", 3), ("SOFFSET", 128), ("OFFEN", 1)], None), + ("BUFFER_LOAD_FORMAT_D16_X", "ENC_MUBUF", &[("VDATA", 11), ("VADDR", 1), ("SRSRC", 4), ("SOFFSET", 128), ("OFFEN", 1)], None), + ]); + let mut mem = vec![0u32; 512]; + for l in 0..64 { + let put = |mem: &mut Vec, base: usize, v: u16| { + let (w, sh) = ((base + 2 * l) / 4, 16 * (l % 2)); + mem[w] |= (v as u32) << sh; + }; + put(&mut mem, 0x100, UNORM[l]); + put(&mut mem, 0x200, SNORM[l]); + } + let mut st = KernelState::default(); + st.sgpr[12..16].copy_from_slice(&vs(0x100, 7)); // 16_UNORM + st.sgpr[16..20].copy_from_slice(&vs(0x200, 8)); // 16_SNORM + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[1] = 2 * l as u32; + } + let r = runner::run_code(&code, &st, &mem).unwrap(); + let mut bad = Vec::new(); + for l in 0..64 { + let (u, s) = ((r.vgpr[l][10] & 0xFFFF) as u16, (r.vgpr[l][11] & 0xFFFF) as u16); + if u != UNORM_F16[l] { + bad.push(format!("16_UNORM {:#06x}: {u:#06x}, want {:#06x}", UNORM[l], UNORM_F16[l])); + } + if s != SNORM_F16[l] { + bad.push(format!("16_SNORM {:#06x}: {s:#06x}, want {:#06x}", SNORM[l], SNORM_F16[l])); + } + } + assert!(bad.is_empty(), "{} of 128 differ:\n{}", bad.len(), bad.join("\n")); +} + fn el(name: &str, index: u32, sv: u32, ct: u32, reg: u32, mask: u8) -> crate::gpu::dxbc::SigElement { crate::gpu::dxbc::SigElement { name: name.into(), index, system_value: sv, component_type: ct, register: reg, mask, rw_mask: mask, stream: 0 } } @@ -3083,6 +3162,129 @@ fn gpu_images_a16_d16() { } } +/// D16 reads of an 8_8_8_8_UNORM texture: RDNA2 rounds code / 255 to f16 once, to nearest even +/// (AnyPS5#22750, all 256 codes, gfx1036). One texel per lane, codes 4·lane .. 4·lane + 3. +#[test] +fn gpu_image_d16_loads_of_unorm8_round_once() { + if !gpu_ready() { + return; + } + use runner::{TestTexture, TexDim}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM; + const UNORM8_F16: [u16; 256] = [0x0000, 0x1C04, 0x2004, 0x2206, 0x2404, 0x2505, 0x2606, 0x2707, 0x2804, 0x2885, 0x2905, 0x2986, 0x2A06, 0x2A87, 0x2B07, 0x2B88, 0x2C04, 0x2C44, 0x2C85, 0x2CC5, 0x2D05, 0x2D45, 0x2D86, 0x2DC6, 0x2E06, 0x2E46, 0x2E87, 0x2EC7, 0x2F07, 0x2F47, 0x2F88, 0x2FC8, 0x3004, 0x3024, 0x3044, 0x3064, 0x3085, 0x30A5, 0x30C5, 0x30E5, 0x3105, 0x3125, 0x3145, 0x3165, 0x3186, 0x31A6, 0x31C6, 0x31E6, 0x3206, 0x3226, 0x3246, 0x3266, 0x3287, 0x32A7, 0x32C7, 0x32E7, 0x3307, 0x3327, 0x3347, 0x3367, 0x3388, 0x33A8, 0x33C8, 0x33E8, 0x3404, 0x3414, 0x3424, 0x3434, 0x3444, 0x3454, 0x3464, 0x3474, 0x3485, 0x3495, 0x34A5, 0x34B5, 0x34C5, 0x34D5, 0x34E5, 0x34F5, 0x3505, 0x3515, 0x3525, 0x3535, 0x3545, 0x3555, 0x3565, 0x3575, 0x3586, 0x3596, 0x35A6, 0x35B6, 0x35C6, 0x35D6, 0x35E6, 0x35F6, 0x3606, 0x3616, 0x3626, 0x3636, 0x3646, 0x3656, 0x3666, 0x3676, 0x3687, 0x3697, 0x36A7, 0x36B7, 0x36C7, 0x36D7, 0x36E7, 0x36F7, 0x3707, 0x3717, 0x3727, 0x3737, 0x3747, 0x3757, 0x3767, 0x3777, 0x3788, 0x3798, 0x37A8, 0x37B8, 0x37C8, 0x37D8, 0x37E8, 0x37F8, 0x3804, 0x380C, 0x3814, 0x381C, 0x3824, 0x382C, 0x3834, 0x383C, 0x3844, 0x384C, 0x3854, 0x385C, 0x3864, 0x386C, 0x3874, 0x387C, 0x3885, 0x388D, 0x3895, 0x389D, 0x38A5, 0x38AD, 0x38B5, 0x38BD, 0x38C5, 0x38CD, 0x38D5, 0x38DD, 0x38E5, 0x38ED, 0x38F5, 0x38FD, 0x3905, 0x390D, 0x3915, 0x391D, 0x3925, 0x392D, 0x3935, 0x393D, 0x3945, 0x394D, 0x3955, 0x395D, 0x3965, 0x396D, 0x3975, 0x397D, 0x3986, 0x398E, 0x3996, 0x399E, 0x39A6, 0x39AE, 0x39B6, 0x39BE, 0x39C6, 0x39CE, 0x39D6, 0x39DE, 0x39E6, 0x39EE, 0x39F6, 0x39FE, 0x3A06, 0x3A0E, 0x3A16, 0x3A1E, 0x3A26, 0x3A2E, 0x3A36, 0x3A3E, 0x3A46, 0x3A4E, 0x3A56, 0x3A5E, 0x3A66, 0x3A6E, 0x3A76, 0x3A7E, 0x3A87, 0x3A8F, 0x3A97, 0x3A9F, 0x3AA7, 0x3AAF, 0x3AB7, 0x3ABF, 0x3AC7, 0x3ACF, 0x3AD7, 0x3ADF, 0x3AE7, 0x3AEF, 0x3AF7, 0x3AFF, 0x3B07, 0x3B0F, 0x3B17, 0x3B1F, 0x3B27, 0x3B2F, 0x3B37, 0x3B3F, 0x3B47, 0x3B4F, 0x3B57, 0x3B5F, 0x3B67, 0x3B6F, 0x3B77, 0x3B7F, 0x3B88, 0x3B90, 0x3B98, 0x3BA0, 0x3BA8, 0x3BB0, 0x3BB8, 0x3BC0, 0x3BC8, 0x3BD0, 0x3BD8, 0x3BE0, 0x3BE8, 0x3BF0, 0x3BF8, 0x3C00]; + let mimg = |name: &'static str, f: &[(&str, u64)]| -> Vec { encode(name, "ENC_MIMG", f, None).unwrap() }; + let mut code = mimg("IMAGE_LOAD", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("DMASK", 0xF), ("DIM", 1), ("UNORM", 1), ("D16", 1)]); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let mut st = KernelState::default(); + st.sgpr[16..24].copy_from_slice(&tsharp(0, 56, 9)); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = l as u32; + r[1] = 0; + } + let data: Vec = (0..=255u8).collect(); + let tex = [TestTexture { dim: TexDim::D2, format: DXGI_FORMAT_R8G8B8A8_UNORM, width: 64, height: 1, depth: 1, texel_bytes: 4, data, uav: false }]; + let r = runner::run_code_with(&code, &st, &[], &tex, &[]).unwrap(); + let mut bad = Vec::new(); + for l in 0..64 { + let got = [r.vgpr[l][10] & 0xFFFF, r.vgpr[l][10] >> 16, r.vgpr[l][11] & 0xFFFF, r.vgpr[l][11] >> 16]; + for c in 0..4 { + let code = 4 * l + c; + if got[c] != u32::from(UNORM8_F16[code]) { + bad.push(format!("{code}: {:#06x}, want {:#06x}", got[c], UNORM8_F16[code])); + } + } + } + assert!(bad.is_empty(), "{} of 256 differ:\n{}", bad.len(), bad.join("\n")); +} + +/// D16 samples of an 8_8_8_8_UNORM texture: a filtered sample is a blend of texels, not a code +/// of the format, so it keeps the host's value (truncated, as other float D16 reads) – half way +/// between codes 0 and 255 is 0.5 (0x3800), not code 128's 0x3804. A sampler that cannot +/// filter returns texels, rounded once (`d16_fmt`): codes 9 and 128 give 0x2885 and 0x3804. +/// Each sampler both from the sampler heap (S# in registers) and static (S# from constants). +#[test] +fn gpu_image_d16_filtered_samples_keep_the_blend() { + if !gpu_ready() { + return; + } + use runner::{TestSampler, TestTexture, TexDim}; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM; + let clamp = 2 | 2 << 3 | 2 << 6; + let point = [clamp, 0x00FF_F000u32, 0, 0]; + let linear = [clamp, 0x00FF_F000, 1 << 20 | 1 << 22, 0]; + let mov = |r: u64, v: u32| -> (&'static str, &'static str, Vec<(&'static str, u64)>, Option) { + if v == 0 { + ("S_MOV_B32", "ENC_SOP1", vec![("SDST", r), ("SSRC0", 128)], None) + } else { + ("S_MOV_B32", "ENC_SOP1", vec![("SDST", r), ("SSRC0", 255)], Some(v)) + } + }; + let mut list = Vec::new(); + for k in 0..4 { + list.push(mov(28 + k as u64, linear[k])); + list.push(mov(32 + k as u64, point[k])); + } + let sample = |vdata: u64, ssamp: u64, dmask: u64, d16: u64| { + ("IMAGE_SAMPLE_LZ", "ENC_MIMG", vec![("VDATA", vdata), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", ssamp), ("DMASK", dmask), ("DIM", 1), ("D16", d16)], None) + }; + // T# in s[16:23]; S# heap trilinear s[24:27] (6) and point s[36:39] (9), static bilinear + // s[28:31] (7) and point s[32:35] (8). Filtered: R, G; point: B, A (the same in both texels). + list.push(sample(10, 6, 0x3, 1)); + list.push(sample(12, 6, 0x3, 0)); + list.push(sample(14, 7, 0x3, 1)); + list.push(sample(15, 7, 0x3, 0)); + list.push(sample(17, 9, 0xC, 1)); + list.push(sample(18, 8, 0xC, 1)); + let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); + let code = prog(&refs); + + let mut st = KernelState::default(); + st.sgpr[16..24].copy_from_slice(&tsharp(0, 56, 9)); + st.sgpr[24..28].copy_from_slice(&[clamp, 0x00FF_F000, 1 << 20 | 1 << 22 | 2 << 26, 1]); + st.sgpr[36..40].copy_from_slice(&point); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = f(0.25 + l as f32 / 128.0); // texel 0's centre .. near texel 1's; lane 32 half way + r[1] = f(0.5); + } + let tex = [TestTexture { dim: TexDim::D2, format: DXGI_FORMAT_R8G8B8A8_UNORM, width: 2, height: 1, depth: 1, texel_bytes: 4, data: vec![0, 255, 9, 128, 255, 0, 9, 128], uav: false }]; + let samp = [ + TestSampler { filter: D3D12_FILTER_MIN_MAG_MIP_POINT, address: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, comparison: None }, + TestSampler { filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR, address: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, comparison: None }, + ]; + let r = runner::run_code_with(&code, &st, &[], &tex, &samp).unwrap(); + // binary16 toward zero of a value in [2^-14, 1] or 0: rebias the exponent, drop 13 bits + let rtz = |x: u32| -> u32 { + let v = f32::from_bits(x); + assert!(v == 0.0 || (1.0 / 16384.0..=1.0).contains(&v), "sample {v} outside the checked range"); + if v == 0.0 { 0 } else { ((x >> 23) - 112) << 10 | (x >> 13) & 0x3FF } + }; + let mut bad = Vec::new(); + for l in 0..64 { + let v = &r.vgpr[l]; + let w = l as f32 / 64.0; // texel 1's weight + for (k, ideal) in [w, 1.0 - w].into_iter().enumerate() { + let got = f32::from_bits(v[12 + k]); + assert!((got - ideal).abs() < 1.0 / 256.0, "lane {l} c{k}: f32 sample {got}, about {ideal}"); + assert_eq!(v[15 + k], v[12 + k], "lane {l} c{k}: static and heap linear samples differ"); + } + let want = [rtz(v[12]), rtz(v[13])]; + for (name, reg) in [("heap trilinear", 10), ("static bilinear", 14)] { + let got = [v[reg] & 0xFFFF, v[reg] >> 16]; + if got != want { + bad.push(format!("lane {l} {name}: {:#06x} {:#06x}, want {:#06x} {:#06x}", got[0], got[1], want[0], want[1])); + } + } + if l == 32 { + assert_eq!(want, [0x3800, 0x3800], "half way between codes 0 and 255"); + } + for (name, reg) in [("heap point", 17), ("static point", 18)] { + assert_eq!([v[reg] & 0xFFFF, v[reg] >> 16], [0x2885, 0x3804], "lane {l} {name}: codes 9 and 128 round once"); + } + } + assert!(bad.is_empty(), "{} filtered samples differ:\n{}", bad.len(), bad.join("\n")); +} + /// f32 → IEEE half bits (exact for the small values used in tests). fn half_bits(x: f32) -> u32 { if x == 0.0 {