diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 11be1c0ce4..310f388da9 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -1568,3 +1568,36 @@ fn raw_buffer_oob_check_guards_32bit_wraparound() { assert!(uge >= 4, "expected wraparound icmp uge checks for load and atomic (got {uge}):\n{dis}"); } } + +/// The console's quad sample mask (#142, `IO_QUAD_KILL`): a PS starts with the mask's test – +/// on the HLSL path the prologue `emit::quad_mask_prologue` right after the output's zeroing +/// (before EXEC is taken), with the io dwords 119 / 120 and one uniform branch; on the direct +/// path one discard more than the program's own (its DONE export's). +#[test] +fn quad_sample_mask_starts_pixel_shaders_on_both_paths() { + use crate::gpu::recomp::{dxc, emit::quad_mask_prologue, runner, translate as translate_hlsl, Mode, Options, PsInterface, IO_QUAD_KILL}; + assert_eq!(IO_QUAD_KILL, [119, 120], "the io slots the host writes (`quad_mask::kill_words`)"); + let p = quad_mask_prologue(); + assert!(p.contains("io.Load(476u)") && p.contains("io.Load(480u)"), "{p}"); + assert!(p.contains("[branch] if ((xcl_qk0 | xcl_qk1) != 0u)"), "one uniform test when nothing is masked:\n{p}"); + assert!(p.contains("uint2(xi.xcl_pos.xy) & 1u") && p.contains("discard;"), "{p}"); + let color = ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 4), ("VSRC2", 4), ("VSRC3", 4), ("DONE", 1), ("VM", 1)][..], None); + let code = prog(&[("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 242)], None), color]); + let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x2, attrs: None }; + let t = translate_hlsl(&code, &Options { mode: Mode::Pixel(psi.clone()), wave64: true, ..Default::default() }).unwrap(); + let start = format!("XclOut main(XclIn xi)\n{{\n XclOut xo = (XclOut)0;\n{p}"); + assert!(t.hlsl.contains(&start), "HLSL\n{}", t.hlsl); + // the mask is tested before EXEC is taken + let main = &t.hlsl[t.hlsl.find("XclOut main(").unwrap()..]; + assert!(main.find("xcl_qk0").unwrap() < main.find("ballot(true)").unwrap(), "{}", t.hlsl); + if dxc::location().is_err() { + return runner::skip_test("no DXC (the HLSL text is checked)"); + } + let discards = |c: &[u8]| super::validate::disassemble(c).unwrap_or_else(|e| panic!("{e}")).matches("@dx.op.discard(i32 82").count(); + let compiled = dxc::compile(&t.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + let direct = super::kernel::translate_pixel(&code, ko, &psi).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); + // the program's own discard (lanes without a DONE export), and the mask's + assert_eq!(discards(&direct.dxil), 2, "direct path's discards"); + assert!(discards(&compiled) >= 1, "HLSL path's discards"); +} diff --git a/crates/xcl/src/gpu/dxil/lower_gfx.rs b/crates/xcl/src/gpu/dxil/lower_gfx.rs index a337d470bc..b57fc91675 100644 --- a/crates/xcl/src/gpu/dxil/lower_gfx.rs +++ b/crates/xcl/src/gpu/dxil/lower_gfx.rs @@ -236,6 +236,9 @@ impl Lw { if let Some(v) = sys(14) { vgpr.insert(v as u32, io.coverage(&mut self.s)); } + // the console's quad sample mask (#142), before EXEC is taken (a pixel shader given + // early depth must not get it: the depth of the pixels it discards would be written) + self.quad_mask_prologue(&mut io, pos); self.gfx_common_init(vgpr); for (o, _) in targets.values_mut() { o.vars = self.out_vars(4); @@ -251,6 +254,33 @@ impl Lw { self.gfx = Some(GfxCtx { io, vs: None, ps: Some(ps.clone()), pos: None, params: Vec::new(), ps_in, targets, depth, ps_done: false, ps_vm: false, live_var, live_vm_var }); } + /// The console's quad sample mask (`IO_QUAD_KILL`; the HLSL path's + /// `emit::quad_mask_prologue`): the pixel at (x & 1, y & 1) of its quad is discarded when + /// the mask takes all 16 of its samples away. Straight-line: two loads of the same io + /// dwords for every lane and a few integer operations; a discard whose condition is false + /// in every draw the title does not mask (io slots 0). + fn quad_mask_prologue(&mut self, io: &mut GraphicsIo, pos: Sig) { + let Some(buf) = self.init.io else { return }; + let [lo, hi] = crate::gpu::recomp::IO_QUAD_KILL; + let o = self.c(lo as u32 * 4); + let k0 = self.s.raw_load(buf, o, 1)[0]; + let o = self.c(hi as u32 * 4); + let k1 = self.s.raw_load(buf, o, 1)[0]; + let x = io.load_input(&mut self.s, pos, 0, 0); + let y = io.load_input(&mut self.s, pos, 0, 1); + let x = self.ftoui(x); + let y = self.ftoui(y); + let x = self.andc(x, 1); + let y = self.andc(y, 1); + let odd_row = self.nz(y); + let word = self.sel(odd_row, k1, k0); + let shift = self.shlc(x, 4); + let bits = self.lshr(word, shift); + let bits = self.andc(bits, 0xFFFF); + let dead = self.cmpc(Pred::Eq, bits, 0xFFFF); + io.discard(&mut self.s, dead); + } + /// SGPRs from `io`, SCC 0, EXEC = `ballot(true)`. fn gfx_common_init(&mut self, vgpr: HashMap) { let zero = self.c(0); diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 1c51cfd0e2..8f7dc82a21 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -5526,6 +5526,10 @@ static uint xcl_cap = 1u << 16; h.push_str(" float4 xcl_unused : SV_Target7;\n"); } h.push_str("};\nXclOut main(XclIn xi)\n{\n XclOut xo = (XclOut)0;\n"); + // the console's quad sample mask (#142). A pixel shader given early depth + // (`[earlydepthstencil]`) must not get it: the depth of the pixels it discards + // would still be written + h.push_str(&quad_mask_prologue()); if self.ps_writes_mask { h.push_str(" xo.xcl_mask = 0xFFFFFFFFu;\n"); } @@ -5578,6 +5582,21 @@ static uint xcl_cap = 1u << 16; } } +/// The start of every pixel shader: the console's quad sample mask +/// (`IO_QUAD_KILL`, command list #142). The pixel at (x & 1, y & 1) of its quad is discarded +/// when the mask takes all 16 of its samples away; nothing is done (one uniform branch) when it +/// takes none, which is every draw the title does not mask and every draw without +/// `XCL_SAMPLE_MASK=1`. Discarded before the program's EXEC is taken (`ballot(true)`), the +/// pixel is a helper lane for its quad's derivatives and out of EXEC, as a pixel the console's +/// mask leaves uncovered. (A mask that keeps some samples of a pixel keeps the whole pixel; the +/// retail title only sets 0 or 0xFFFF per pixel.) +pub fn quad_mask_prologue() -> String { + let [lo, hi] = super::IO_QUAD_KILL.map(|k| k * 4); + format!( + " uint xcl_qk0 = io.Load({lo}u);\n uint xcl_qk1 = io.Load({hi}u);\n [branch] if ((xcl_qk0 | xcl_qk1) != 0u) {{\n uint2 xcl_qp = uint2(xi.xcl_pos.xy) & 1u;\n if ((((xcl_qp.y != 0u ? xcl_qk1 : xcl_qk0) >> (xcl_qp.x << 4u)) & 0xFFFFu) == 0xFFFFu)\n discard;\n }}\n" + ) +} + /// Vertex output struct shared by the VS mode and the mesh pass-through: SV_Position, then /// the params in `exp param` order (non-system OSG1 elements, then clip/cull distances). fn out_struct(h: &mut String, name: &str, outputs: &[SigElement]) { diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 8452602e8a..c04928d8bf 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -425,6 +425,13 @@ const _: () = assert!(IO_THREAD_LIMIT[1] == IO_THREAD_LIMIT[0] + 1 && IO_THREAD_ /// First console mesh group in this dispatch slice. Record indices always start at zero. pub const IO_MESH_GROUP_BASE: usize = 118; +/// io slots (trap-temp range, after `IO_MESH_GROUP_BASE`) of the console's quad sample mask +/// (command list #142 `SetQuadSampleMaskX(u64)`, the two PA_SC_AA_MASK registers: 16 sample +/// bits for each pixel of a 2×2 quad), stored inverted – the samples the mask takes away – so an +/// io block that does not write them (0) takes nothing away: [119] = pixels (x, y) = (0, 0) in +/// bits 0..15, (1, 0) in 16..31; [120] = (0, 1), (1, 1). A pixel shader discards a pixel all of +/// whose 16 bits are set (`emit::quad_mask_prologue`, `Lw::quad_mask_prologue`). +pub const IO_QUAD_KILL: [usize; 2] = [119, 120]; impl GsInterface { /// bytes of one ES vertex in LDS (ESGS item: 16 per ES output register) diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index c0faf78b0c..c43a5a9351 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -2300,6 +2300,62 @@ fn gpu_ps_exp_vm_controls_pixel_survival() { } } +/// The console's quad sample mask (#142, `IO_QUAD_KILL`) on the GPU, through the HLSL and +/// the direct DXIL pixel shaders: each pixel (x, y) is drawn when the mask keeps the 16-bit +/// word of its quad position (x & 1) + 2 (y & 1), cleared otherwise – the retail title's +/// masks (all ones, both diagonals, 3 of 4, 1 of 4) and none. +#[test] +fn gpu_quad_sample_mask_discards_the_quad_pixels_it_takes_away() { + if !gpu_ready() { + return; + } + use super::{PsInterface, VsInterface, IO_QUAD_KILL, KERNEL_SGPRS}; + use crate::gpu::dxil::kernel::{translate_pixel, translate_vertex, KernelOptions}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT; + let vs_code = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", V + 4)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", V + 5)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 242)], None), + ("EXP", "ENC_EXP", &[("TGT", 12), ("EN", 0xF), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1)], None), + ]); + let ps_code = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 242)], None), + ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 4), ("VSRC2", 4), ("VSRC3", 4), ("DONE", 1), ("VM", 1)], None), + ]); + let vsi = VsInterface { inputs: vec![el("POSITION", 0, 0, 3, 0, 3)], outputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], attr_base: 4, params: None }; + let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + let vo = Options { mode: Mode::Vertex(vsi.clone()), wave64: true, ..Default::default() }; + let vs_hlsl = super::dxc::compile(&translate(&vs_code, &vo).unwrap().hlsl, "main", "vs_6_6", &[]).unwrap(); + let vs_dxil = translate_vertex(&vs_code, ko, &vsi).unwrap().dxil; + let verts = [-1.0f32, -1.0, -1.0, 3.0, 3.0, -1.0]; + let layout = [runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }]; + let clear = [0.0f32, 0.0, 1.0, 1.0]; + let masks = [u64::MAX, 0x0000_FFFF_FFFF_0000, 0xFFFF_0000_0000_FFFF, 0xFFFF_0000_FFFF_FFFF, 0x0000_FFFF_0000_0000, 0]; + let psi = PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None }; + let po = Options { mode: Mode::Pixel(psi.clone()), wave64: true, ..Default::default() }; + let pt = translate(&ps_code, &po).unwrap(); + let ps_hlsl = super::dxc::compile(&pt.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", pt.hlsl)); + let ps_dxil = translate_pixel(&ps_code, ko, &psi).unwrap().dxil; + for (backend, vs, ps) in [("hlsl", &vs_hlsl, &ps_hlsl), ("direct_dxil", &vs_dxil, &ps_dxil)] { + for mask in masks { + let kill = !mask; + let mut sgprs = vec![0u32; KERNEL_SGPRS]; + sgprs[IO_QUAD_KILL[0]] = kill as u32; + sgprs[IO_QUAD_KILL[1]] = (kill >> 32) as u32; + let px = runner::draw(vs, ps, &layout, &verts, 8, &sgprs, &[], 16, clear).unwrap(); + for y in 0..16usize { + for x in 0..16usize { + let word = (mask >> (16 * ((x & 1) + 2 * (y & 1)))) & 0xFFFF; + let want = if word != 0 { [1.0; 4] } else { clear }; + let got = px[y * 16 + x]; + assert!(got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-5), "{backend}, mask {mask:#018x}: pixel ({x},{y}) = {got:?}, expected {want:?}"); + } + } + } + } +} + /// `emit::rect_list_gs` declares the VS's output struct; the fourth vertex is v[0] with its /// float outputs continued from the other three, its integer (flat) ones left as v[0]'s. #[test] diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 7938495b9f..0a2025db18 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -41,6 +41,9 @@ struct State { uma: Vec, /// where the next draw's io and argument table go (blocks in `uma`) arena: crate::gpu::uma::Arena, + /// the console's quad sample mask (#142, `quad_mask`) as the io words of the next draws + /// (`recomp::IO_QUAD_KILL`: the samples it takes away; [0, 0] = all ones) + quad_kill: [u32; 2], /// a heap of views is bound (`list_x::ensure_view_heap`), and what that call said (the shared /// view heap is bound: `list_x::note_shared_view_heap_use`) heap_bound: bool, @@ -1081,6 +1084,7 @@ fn install_reset( s.args_gfx.clear(); s.rs_gfx = 0; s.heaps = [0; 2]; + s.quad_kill = [0; 2]; // (the scratch blocks are in `res_retired` already) (s.scratch, s.scratch_used, s.scratch_taken, s.scratch_in_args, s.record_open) = (None, 0, 0, false, None); let mut res_bufs = std::mem::take(&mut s.res_retired); @@ -1184,11 +1188,17 @@ fn install_clear_state( s.args_gfx.clear(); s.rs_gfx = 0; s.heaps = [0; 2]; + s.quad_kill = [0; 2]; old_resolution }); drop(old_resolution); } +/// #142 `SetQuadSampleMaskX`: the io words of the list's next draws (`quad_mask::kill_words`). +pub(super) fn set_quad_kill(list: *mut c_void, words: [u32; 2]) { + with(list, |s| s.quad_kill = words); +} + /// Allocation-bearing root state captured before a mid-list split commits. Preparation also /// transfers the reserved destination's old UMA ownership (and retires its previous recording's /// two-pass buffers and deferred run), so installation cannot allocate. @@ -1203,6 +1213,7 @@ pub(super) struct PreparedSplit { pso: usize, resolution: Option, heaps: [u32; 2], + quad_kill: [u32; 2], } impl PreparedSplit { @@ -1236,9 +1247,9 @@ pub(super) fn initial_pipeline(list: *mut c_void) -> (usize, Option PreparedSplit { let backing = native_backing(to, allocator); - let (layout, args, layout_gfx, args_gfx, rs_gfx, pso, resolution, heaps) = with(from, |s| { + let (layout, args, layout_gfx, args_gfx, rs_gfx, pso, resolution, heaps, quad_kill) = with(from, |s| { (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.pso, - s.resolution.clone(), s.heaps) + s.resolution.clone(), s.heaps, s.quad_kill) }); let (old, blocks, res_bufs, res_marks, res_untracked, had_fb) = with(to, |s| { let old = std::mem::replace(&mut s.allocator, 0); @@ -1264,12 +1275,12 @@ pub(super) fn prepare_split(from: *mut c_void, to: *mut c_void, allocator: usize unmark_deferring(to); console_list::hold_until_reset(old, blocks); retire_recording_res(old, res_bufs, res_marks, res_untracked); - PreparedSplit { to: to as usize, allocator: backing, layout, args, layout_gfx, args_gfx, rs_gfx, pso, resolution, heaps } + PreparedSplit { to: to as usize, allocator: backing, layout, args, layout_gfx, args_gfx, rs_gfx, pso, resolution, heaps, quad_kill } } /// Install a preflighted split state without cloning or growing the state map. pub(super) fn install_prepared_split(prepared: PreparedSplit) { - let PreparedSplit { to, allocator, layout, args, layout_gfx, args_gfx, rs_gfx, pso, resolution, heaps } = prepared; + let PreparedSplit { to, allocator, layout, args, layout_gfx, args_gfx, rs_gfx, pso, resolution, heaps, quad_kill } = prepared; let entry = STATES.get(to).expect("prepared split destination state"); let old_resolution = { let mut s = entry.state.lock().unwrap(); @@ -1283,6 +1294,7 @@ pub(super) fn install_prepared_split(prepared: PreparedSplit) { s.rs_gfx = rs_gfx; s.pso = pso; s.heaps = heaps; + s.quad_kill = quad_kill; std::mem::replace(&mut s.resolution, resolution) }; drop(old_resolution); @@ -3084,6 +3096,10 @@ unsafe fn prepare_two_pass_stage( let table_at = copy(&args[inline..])?; let mut io = two_pass_io(layout.as_deref(), &args, table_at as u64, compute_pass, u.base(), heaps); io[crate::gpu::recomp::IO_MESH_GROUP_BASE] = group_base; + // the quad sample mask for the mesh pass's pixel shader (as `bind_abi`; not the compute pass) + if !compute_pass { + quad_kill_io(&mut io, with(this, |s| s.quad_kill)); + } let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::>())?; let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); let rs = if compute_pass { tp.compute_rs } else { tp.mesh_rs }; @@ -5145,6 +5161,8 @@ struct PreparedAbiState { res_at: usize, allocator: usize, heaps: [u32; 2], + /// the quad sample mask's io words (graphics only) + quad_kill: [u32; 2], } fn prepare_abi_state( @@ -5174,7 +5192,8 @@ fn prepare_abi_state( let io_bytes = crate::gpu::recomp::KERNEL_SGPRS * std::mem::size_of::(); let io_at = state.arena.take(u, io_bytes, 256, &mut state.uma).ok_or_else(|| full(io_bytes))? as usize; let res_at = state.arena.take(u, 256, 256, &mut state.uma).ok_or_else(|| full(256))? as usize; - Ok(PreparedAbiState { layout, args, inline, table_at, io_at, res_at, allocator: state.allocator, heaps: state.heaps }) + let quad_kill = if gfx { state.quad_kill } else { [0; 2] }; + Ok(PreparedAbiState { layout, args, inline, table_at, io_at, res_at, allocator: state.allocator, heaps: state.heaps, quad_kill }) }) } @@ -5206,6 +5225,18 @@ fn prepared_abi_io( io } +/// A draw's quad sample mask into its pixel shader's io (`recomp::IO_QUAD_KILL`; nothing to +/// write when it takes nothing away: the slots are 0). +fn quad_kill_io(io: &mut [u32], words: [u32; 2]) { + if words == [0; 2] { + return; + } + for (k, w) in words.into_iter().enumerate() { + io[crate::gpu::recomp::IO_QUAD_KILL[k]] = w; + } + super::quad_mask::note_masked_draw(); +} + /// A draw's or an indirect command's bind on XCL's ABI (no groups known here) unsafe fn bind_abi_resolved( this: *mut c_void, list: &ID3D12GraphicsCommandList, original: usize, pso: usize, gfx: bool, @@ -5252,13 +5283,15 @@ unsafe fn bind_abi_with_root_resolved( // a compute shader takes no more arguments from registers than it has (`inline_for`) let user_sgprs = if gfx { None } else { super::real::pso_user_sgprs_exact(pso) }; let prepared = prepare_abi_state(this, u, gfx, user_sgprs)?; - let PreparedAbiState { layout, args, inline, table_at, io_at, res_at, allocator, heaps } = prepared; + let PreparedAbiState { layout, args, inline, table_at, io_at, res_at, allocator, heaps, quad_kill } = prepared; want_root_views(layout.as_deref(), &args, super::view_want::Path::RootView); if super::placements::any_superseded() { note_superseded_in_tables(u, layout.as_deref(), &args); } std::ptr::copy_nonoverlapping(args[inline..].as_ptr(), table_at as *mut u8, args.len() - inline); - let io = prepared_abi_io(layout.as_deref(), &args, table_at, gfx, user_sgprs, u.base(), heaps, limits, groups, group_limit); + let mut io = prepared_abi_io(layout.as_deref(), &args, table_at, gfx, user_sgprs, u.base(), heaps, limits, groups, group_limit); + // the quad sample mask for the pixel shader (graphics only; [0, 0] when all ones) + quad_kill_io(&mut io, quad_kill); let io_bytes = io.iter().flat_map(|word| word.to_le_bytes()).collect::>(); std::ptr::copy_nonoverlapping(io_bytes.as_ptr(), io_at as *mut u8, io_bytes.len()); std::ptr::write_bytes(res_at as *mut u8, 0, 256); @@ -7027,6 +7060,38 @@ void main(uint t : SV_GroupIndex) { } } + /// The quad sample mask (#142): a list's draws get its io words until the list's reset or + /// ClearState, and a mid-list split carries them; an all-ones mask writes nothing (the io + /// slots stay 0). + #[test] + fn quad_sample_mask_reaches_the_io_of_the_lists_draws() { + let (list, split) = (0x5151_0000usize as *mut c_void, 0x5151_1000usize as *mut c_void); + let words = super::super::quad_mask::kill_words(0x0000_FFFF_FFFF_0000); + assert_eq!(words, [0xFFFF, 0xFFFF_0000]); + set_quad_kill(list, words); + assert_eq!(with(list, |s| s.quad_kill), words); + let mut io = vec![0u32; crate::gpu::recomp::KERNEL_SGPRS]; + quad_kill_io(&mut io, words); + let [lo, hi] = crate::gpu::recomp::IO_QUAD_KILL; + assert_eq!((io[lo], io[hi]), (0xFFFF, 0xFFFF_0000)); + assert!(io.iter().enumerate().all(|(k, &w)| w == 0 || k == lo || k == hi)); + use crate::gpu::recomp::{IO_GROUP_LIMIT, IO_LOOP_BUDGET, IO_MESH_GROUP_BASE, IO_THREAD_LIMIT, IO_UMA_BASE_HI}; + let taken = [IO_UMA_BASE_HI, IO_LOOP_BUDGET, IO_GROUP_LIMIT, IO_THREAD_LIMIT[0], IO_THREAD_LIMIT[1], IO_THREAD_LIMIT[2], IO_MESH_GROUP_BASE]; + assert!(!crate::gpu::recomp::IO_QUAD_KILL.iter().any(|&k| taken.contains(&k) || k >= crate::gpu::recomp::KERNEL_SCC_SLOT)); + let mut io = vec![0u32; crate::gpu::recomp::KERNEL_SGPRS]; + quad_kill_io(&mut io, super::super::quad_mask::kill_words(u64::MAX)); + assert!(io.iter().all(|&w| w == 0)); + inherit_for_split(list, split, 0); + assert_eq!(with(split, |s| s.quad_kill), words); + clear_state(list, 0); + assert_eq!(with(list, |s| s.quad_kill), [0; 2]); + set_quad_kill(list, words); + reset(list, 0, 0); + assert_eq!(with(list, |s| s.quad_kill), [0; 2]); + forget(list); + forget(split); + } + #[test] fn dispatch_limits_are_explicit_and_graphics_ignores_them() { let slots = crate::gpu::recomp::IO_THREAD_LIMIT; diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 45856969ab..790f736af9 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -41,6 +41,7 @@ pub mod null; mod placements; pub mod present; pub mod pso_async; +mod quad_mask; mod queue_submit; mod pso_manifest; pub mod real; diff --git a/crates/xcl/src/hle/d3d12x/quad_mask.rs b/crates/xcl/src/hle/d3d12x/quad_mask.rs new file mode 100644 index 0000000000..46a93acf34 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/quad_mask.rs @@ -0,0 +1,131 @@ +//! The console's quad sample mask: command list #142 of the newer layout, `SetQuadSampleMaskX(u64)` +//! (the name as in xcl-dev/xcl PR #1274, which leaves it a no-op). The u64 is the two +//! PA_SC_AA_MASK registers of AMD's rasteriser: 16 sample bits for each pixel of a 2×2 quad, +//! X0Y0 in bits 0..15, X1Y0 in 16..31, X0Y1 in 32..47, X1Y1 in 48..63 (register names +//! PA_SC_AA_MASK_X0Y0_X1Y0 / _X0Y1_X1Y1). A retail title sets it per draw from fade tables +//! (0, 1, 2, 3 or 4 pixels of the quad, each 0 or 0xFFFF, and the complement for the other +//! side of a cross-fade): dithered LOD fades. As a stub every pixel is drawn: what should +//! fade in a dither pattern is drawn whole. +//! +//! The PC has no such mask: the translated pixel shaders test it (`recomp::IO_QUAD_KILL`, the +//! inverted words in the draw's io block, written by `bind`) and discard the pixels it takes +//! away. Off unless `XCL_SAMPLE_MASK=1`: off, the mask is taken as all ones (the io words stay +//! 0 and the shaders' test never discards). + +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::OnceLock; + +/// `XCL_SAMPLE_MASK=1` applies the mask (no translation changes: the test is in every pixel +/// shader). Off by default. +pub(super) fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_SAMPLE_MASK").is_ok_and(|v| v.trim() == "1")) +} + +/// The io words (`recomp::IO_QUAD_KILL`) of a mask: the samples it takes away, quad row by quad +/// row ([0] = pixels (0, 0) and (1, 0), [1] = (0, 1) and (1, 1)). All ones: [0, 0]. +pub(super) fn kill_words(mask: u64) -> [u32; 2] { + let k = !mask; + [k as u32, (k >> 32) as u32] +} + +/// Whether the translated pixel shaders keep the pixel at (x, y) of the screen under the io +/// `words` (`emit::quad_mask_prologue`): not when every sample bit of its quad position is set. +#[cfg(test)] +pub(super) fn pixel_kept(words: [u32; 2], x: u32, y: u32) -> bool { + let w = words[(y & 1) as usize]; + (w >> (16 * (x & 1))) & 0xFFFF != 0xFFFF +} + +/// calls of #142 by the title, of them with a mask that takes something away +static CALLS: AtomicU64 = AtomicU64::new(0); +static PARTIAL: AtomicU64 = AtomicU64::new(0); +/// draws bound with a partial mask +static MASKED_DRAWS: AtomicU64 = AtomicU64::new(0); + +/// Command list #142 `SetQuadSampleMaskX(mask)` (newer layout only: on the older one #142 is +/// another method, answered as the stub did). The mask holds for the list's next draws, until +/// the next call or the list's reset (the title assumes all ones after a reset: it resends only +/// a changed mask, and its cache starts at all ones). +pub(super) unsafe extern "system" fn set_quad_sample_mask_x(this: *mut c_void, mask: u64) -> u64 { + if !super::real::QUEUE_SHIFTED.load(Ordering::Acquire) { + return 0; + } + let n = CALLS.fetch_add(1, Ordering::Relaxed) + 1; + let partial = if mask != u64::MAX { PARTIAL.fetch_add(1, Ordering::Relaxed) + 1 } else { PARTIAL.load(Ordering::Relaxed) }; + if n == 1 { + crate::xlog_info!( + "D3D12.X: list #142 SetQuadSampleMaskX({mask:#x}) – the quad sample mask is {}", + if enabled() { "on (XCL_SAMPLE_MASK=1)" } else { "off: every pixel is drawn (XCL_SAMPLE_MASK=1 applies it)" } + ); + } + if n.is_power_of_two() && n >= 1024 { + crate::xlog_info!( + "D3D12.X: quad sample mask: {n} calls, {partial} with a partial mask, {} draws bound with one", + MASKED_DRAWS.load(Ordering::Relaxed) + ); + } + super::bind::set_quad_kill(this, if enabled() { kill_words(mask) } else { [0; 2] }); + 0 +} + +/// A draw's io block got a partial mask. +pub(super) fn note_masked_draw() { + MASKED_DRAWS.fetch_add(1, Ordering::Relaxed); +} + +#[cfg(test)] +mod tests { + use super::{kill_words, pixel_kept}; + + /// the pixels of the quad a mask keeps, as bits (x + 2y) + fn kept(mask: u64) -> u32 { + let w = kill_words(mask); + (0..4).filter(|&i| pixel_kept(w, i & 1, i >> 1)).map(|i| 1 << i).sum() + } + + #[test] + fn all_ones_takes_nothing_away_and_writes_zero_io_words() { + assert_eq!(kill_words(u64::MAX), [0, 0]); + assert_eq!(kept(u64::MAX), 0xF); + assert_eq!(kill_words(0), [u32::MAX, u32::MAX]); + assert_eq!(kept(0), 0); + } + + /// The masks a retail title sets (counted over a run: all ones, the two diagonals, "3 of 4" + /// and "1 of 4") and its fade tables' order of the 16-bit words: word i = pixel + /// (i & 1, i >> 1). + #[test] + fn the_titles_masks_keep_their_quad_pixels() { + let cases: [(u64, u32); 10] = [ + (0xFFFF_FFFF_FFFF_FFFF, 0xF), + (0x0000_FFFF_FFFF_0000, 0b0110), + (0xFFFF_0000_0000_FFFF, 0b1001), + (0x0000_FFFF_FFFF_FFFF, 0b0111), + (0xFFFF_0000_FFFF_FFFF, 0b1011), + (0xFFFF_FFFF_0000_FFFF, 0b1101), + (0xFFFF_FFFF_FFFF_0000, 0b1110), + (0x0000_0000_0000_FFFF, 0b0001), + (0x0000_FFFF_0000_0000, 0b0100), + (0xFFFF_0000_0000_0000, 0b1000), + ]; + for (mask, want) in cases { + assert_eq!(kept(mask), want, "{mask:#018x}"); + // the complement (the other side of a cross-fade) keeps the other pixels + assert_eq!(kept(!mask), !want & 0xF, "!{mask:#018x}"); + } + // the test reads the parity of the screen position only + let w = kill_words(0x0000_0000_0000_FFFF); + assert!(pixel_kept(w, 10, 4) && !pixel_kept(w, 11, 4) && !pixel_kept(w, 10, 5) && !pixel_kept(w, 11, 5)); + } + + /// A pixel with some of its samples kept is drawn whole (the title only sets 0 / 0xFFFF). + #[test] + fn a_pixel_keeps_its_samples_if_any_is_kept() { + let w = kill_words(0xFFFF_FFFF_FFFF_0001); + assert!(pixel_kept(w, 0, 0)); + let w = kill_words(0xFFFF_FFFF_FFFF_0000); + assert!(!pixel_kept(w, 0, 0) && pixel_kept(w, 1, 0) && pixel_kept(w, 0, 1) && pixel_kept(w, 1, 1)); + } +} diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 6fcaf053c6..1fe6140b63 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1694,6 +1694,8 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { // the newer layout's (called before anything tells the layouts apart) (131, l::flush_cache_range_x as usize), (132, l::flush_cache_range_x as usize), + // the quad sample mask (newer layout; `quad_mask`) + (142, super::quad_mask::set_quad_sample_mask_x as usize), // console compute/BVH builder extensions (`XboxBvhBuilder.dll`) (146, l::uav_barrier_x as usize), (148, b::allocate_upload_memory as usize), @@ -12956,6 +12958,15 @@ mod readback_routing_tests { assert!(slots.contains(&(54, l::clear_uav_float_x as usize))); } + /// Newer-layout #142 SetQuadSampleMaskX is the quad sample mask's handler, not the stub + /// (and not a pair of `NEWER_LIST_SLOTS`: the older layout's #142 is another method). + #[test] + fn list_142_sets_the_quad_sample_mask() { + let slots = console_slots(Kind::CommandList); + assert!(slots.contains(&(142, super::super::quad_mask::set_quad_sample_mask_x as usize))); + assert!(!NEWER_LIST_SLOTS.iter().any(|&(newer, older)| newer == 142 || older == 142)); + } + /// Bug #6: `Kind::DmaList` must install `cl_release` so releasing a DMA command list removes /// its entry from `list_x::LISTS`. #[test]