diff --git a/crates/xcl/src/gpu/recomp/fetch.rs b/crates/xcl/src/gpu/recomp/fetch.rs new file mode 100644 index 000000000..30b95d56d --- /dev/null +++ b/crates/xcl/src/gpu/recomp/fetch.rs @@ -0,0 +1,289 @@ +//! The vertex fetch of a legacy GS pipeline drawn in two passes. +//! +//! The geometry-mode compute pass (`Mode::Geometry`) reads its ES vertex inputs pre-fetched +//! from `mem`: one float4 (raw bits) per ES input register for each vertex of each triangle, +//! at io[`IO_GS_VERTICES`] (`super::IO_GS_VERTICES`). The console's fetch shader would have +//! made them from the title's vertex buffers; here a small compute shader does, from the +//! pipeline's input layout and the list's vertex and index buffers, before the draw's two +//! passes. +//! +//! Its root signature ([`root_signature`]): b0 = [`CONSTANTS`] root constants (see +//! [`Constants`]), t0 = index buffer, t1..t8 = the vertex buffer slots the layout uses +//! ([`MAX_SLOTS`]), u0 = the fetched vertices. Buffers are bound at a 4-byte aligned address +//! with the byte delta to the view's start and the view's size in the constants: nothing is +//! read past a view (the root descriptors have no bounds). + +use std::fmt::Write; + +/// vertex buffer slots one fetch can read +pub const MAX_SLOTS: usize = 8; +/// root constants of the fetch shader (dwords) +pub const CONSTANTS: u32 = 8 + 4 * MAX_SLOTS as u32; +/// threads per group of the fetch shader (one vertex each) +pub const THREADS: u32 = 64; + +/// One ES input register the fetch fills: from vertex buffer `slot` (index into the fetch's +/// slot list) at byte `offset` of each vertex (or instance), in DXGI format `format`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Element { + pub register: u32, + pub slot: u32, + pub offset: u32, + pub format: u32, + pub per_instance: bool, +} + +/// The fetch shader's root constants. +#[derive(Debug, Clone, Copy, Default)] +#[repr(C)] +pub struct Constants { + /// vertices to fetch (3 per triangle) + pub count: u32, + /// first index (indexed) or first vertex + pub first: u32, + pub base_vertex: i32, + /// bit 0: indexed, bit 1: 16-bit indices + pub flags: u32, + /// index buffer: bytes from the bound address to the view, bytes readable from the bound address + pub ib_delta: u32, + pub ib_bytes: u32, + pub first_instance: u32, + pub pad: u32, + /// per slot: delta, stride, bytes readable, 0 + pub slots: [[u32; 4]; MAX_SLOTS], +} + +impl Constants { + pub fn words(&self) -> Vec { + let mut w = vec![self.count, self.first, self.base_vertex as u32, self.flags, self.ib_delta, self.ib_bytes, self.first_instance, self.pad]; + for s in &self.slots { + w.extend_from_slice(s); + } + w + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Num { + Float, + Unorm, + Snorm, + Uint, + Sint, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Pack { + /// n components of 32 / 16 / 8 bits + Bits(u32), + /// R10G10B10A2 + Rgb10a2, +} + +/// (components, packing, number kind, BGRA order) of a DXGI vertex format. +fn format_info(f: u32) -> Option<(u32, Pack, Num, bool)> { + use Num::*; + use Pack::*; + Some(match f { + 2 => (4, Bits(32), Float, false), + 3 => (4, Bits(32), Uint, false), + 4 => (4, Bits(32), Sint, false), + 6 => (3, Bits(32), Float, false), + 7 => (3, Bits(32), Uint, false), + 8 => (3, Bits(32), Sint, false), + 10 => (4, Bits(16), Float, false), + 11 => (4, Bits(16), Unorm, false), + 12 => (4, Bits(16), Uint, false), + 13 => (4, Bits(16), Snorm, false), + 14 => (4, Bits(16), Sint, false), + 16 => (2, Bits(32), Float, false), + 17 => (2, Bits(32), Uint, false), + 18 => (2, Bits(32), Sint, false), + 24 => (4, Rgb10a2, Unorm, false), + 25 => (4, Rgb10a2, Uint, false), + 28 => (4, Bits(8), Unorm, false), + 30 => (4, Bits(8), Uint, false), + 31 => (4, Bits(8), Snorm, false), + 32 => (4, Bits(8), Sint, false), + 34 => (2, Bits(16), Float, false), + 35 => (2, Bits(16), Unorm, false), + 36 => (2, Bits(16), Uint, false), + 37 => (2, Bits(16), Snorm, false), + 38 => (2, Bits(16), Sint, false), + 41 => (1, Bits(32), Float, false), + 42 => (1, Bits(32), Uint, false), + 43 => (1, Bits(32), Sint, false), + 49 => (2, Bits(8), Unorm, false), + 50 => (2, Bits(8), Uint, false), + 51 => (2, Bits(8), Snorm, false), + 52 => (2, Bits(8), Sint, false), + 54 => (1, Bits(16), Float, false), + 56 => (1, Bits(16), Unorm, false), + 57 => (1, Bits(16), Uint, false), + 58 => (1, Bits(16), Snorm, false), + 59 => (1, Bits(16), Sint, false), + 61 => (1, Bits(8), Unorm, false), + 62 => (1, Bits(8), Uint, false), + 63 => (1, Bits(8), Snorm, false), + 64 => (1, Bits(8), Sint, false), + 87 => (4, Bits(8), Unorm, true), + _ => return None, + }) +} + +/// Whether the fetch can read DXGI format `f`. +pub fn supported(f: u32) -> bool { + format_info(f).is_some() +} + +/// Bytes of one element in DXGI format `f` (for D3D12_APPEND_ALIGNED_ELEMENT). +pub fn bytes(f: u32) -> Option { + format_info(f).map(|(n, pack, _, _)| match pack { + Pack::Bits(b) => n * b / 8, + Pack::Rgb10a2 => 4, + }) +} + +/// HLSL that makes component `i` (raw bits, uint) of the element whose words are w0..w3. +fn component(i: u32, pack: Pack, num: Num) -> String { + let (raw, bits) = match pack { + Pack::Bits(32) => (format!("w{i}"), 32), + Pack::Bits(b) => { + let per_word = 32 / b; + let (w, sh) = (i / per_word, (i % per_word) * b); + (format!("((w{w} >> {sh}u) & {:#x}u)", (1u64 << b) - 1), b) + } + Pack::Rgb10a2 => { + let (sh, b) = [(0, 10), (10, 10), (20, 10), (30, 2)][i as usize]; + (format!("((w0 >> {sh}u) & {:#x}u)", (1u32 << b) - 1), b) + } + }; + let max = ((1u64 << bits) - 1) as f64; + let smax = ((1u64 << (bits - 1)) - 1) as f64; + let sext = |r: &str| if bits == 32 { format!("int({r})") } else { format!("(int({r} << {}u) >> {})", 32 - bits, 32 - bits) }; + match (num, bits) { + (Num::Float, 32) | (Num::Uint, _) => raw, + (Num::Sint, _) => format!("uint({})", sext(&raw)), + (Num::Float, 16) => format!("asuint(f16tof32({raw}))"), + (Num::Float, _) => raw, + (Num::Unorm, _) => format!("asuint(float({raw}) / {max:.1})"), + (Num::Snorm, _) => format!("asuint(max(float({}) / {smax:.1}, -1.0))", sext(&raw)), + } +} + +/// The fetch compute shader for ES input registers `0..registers` (each vertex: `registers` +/// float4s, registers without an element zero). +pub fn hlsl(registers: u32, elements: &[Element]) -> Result { + let mut h = String::new(); + h.push_str("ByteAddressBuffer ib : register(t0);\n"); + for s in 0..MAX_SLOTS { + let _ = writeln!(h, "ByteAddressBuffer vb{s} : register(t{});", s + 1); + } + h.push_str("RWByteAddressBuffer outb : register(u0);\n"); + let _ = writeln!( + h, + "cbuffer C : register(b0) {{ uint count; uint first; int base_vertex; uint flags; uint ib_delta; uint ib_bytes; uint first_instance; uint pad0; uint4 slot[{MAX_SLOTS}]; }};" + ); + // a dword at any byte address, 0 past the readable bytes + h.push_str( + "uint ld(ByteAddressBuffer b, uint a, uint size)\n{\n if (a + 4u > size) return 0u;\n uint s = (a & 3u) * 8u;\n uint lo = b.Load(a & ~3u);\n if (s == 0u) return lo;\n uint hi = (a & ~3u) + 8u <= size ? b.Load((a & ~3u) + 4u) : 0u;\n return (lo >> s) | (hi << (32u - s));\n}\n", + ); + let _ = writeln!(h, "[numthreads({THREADS}, 1, 1)]\nvoid main(uint id : SV_DispatchThreadID)\n{{"); + h.push_str(" if (id >= count) return;\n uint vtx;\n"); + h.push_str(" if ((flags & 1u) != 0u) {\n uint a = ib_delta + (first + id) * ((flags & 2u) != 0u ? 2u : 4u);\n uint w = a + ((flags & 2u) != 0u ? 2u : 4u) <= ib_bytes ? ib.Load(a & ~3u) : 0u;\n uint i = (flags & 2u) != 0u ? ((a & 2u) != 0u ? (w >> 16) : (w & 0xFFFFu)) : w;\n vtx = uint(int(i) + base_vertex);\n } else {\n vtx = first + id;\n }\n"); + let _ = writeln!(h, " uint o = id * {}u;", registers * 16); + for r in 0..registers { + let Some(e) = elements.iter().find(|e| e.register == r) else { + let _ = writeln!(h, " outb.Store4(o + {}u, uint4(0u, 0u, 0u, 0u));", r * 16); + continue; + }; + if e.slot as usize >= MAX_SLOTS { + return Err(format!("register {r}: vertex buffer slot {} of more than {MAX_SLOTS}", e.slot)); + } + let (n, pack, num, bgra) = format_info(e.format).ok_or_else(|| format!("register {r}: vertex format {} not fetched yet", e.format))?; + let words = match pack { + Pack::Bits(b) => (n * b).div_ceil(32), + Pack::Rgb10a2 => 1, + }; + let index = if e.per_instance { "first_instance" } else { "vtx" }; + let s = e.slot; + let _ = writeln!(h, " {{\n uint a = slot[{s}].x + {index} * slot[{s}].y + {}u;", e.offset); + for w in 0..words { + let _ = writeln!(h, " uint w{w} = ld(vb{s}, a + {}u, slot[{s}].z);", 4 * w); + } + let one = if matches!(num, Num::Uint | Num::Sint) { "1u" } else { "0x3F800000u" }; + let mut c: Vec = (0..4).map(|i| if i < n { component(i, pack, num) } else if i == 3 { one.into() } else { "0u".into() }).collect(); + if bgra { + c.swap(0, 2); + } + let _ = writeln!(h, " outb.Store4(o + {}u, uint4({}, {}, {}, {}));\n }}", r * 16, c[0], c[1], c[2], c[3]); + } + h.push_str("}\n"); + Ok(h) +} + +/// The fetch shader's root signature (see the module docs). +pub fn root_signature(dev: &windows::Win32::Graphics::Direct3D12::ID3D12Device) -> Result { + use windows::Win32::Graphics::Direct3D12::*; + let mut params = vec![D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: CONSTANTS } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }]; + for t in 0..=MAX_SLOTS as u32 { + params.push(D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: t, RegisterSpace: 0 } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + } + params.push(D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: 0, RegisterSpace: 0 } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + let desc = D3D12_ROOT_SIGNATURE_DESC { NumParameters: params.len() as u32, pParameters: params.as_ptr(), ..Default::default() }; + unsafe { + let mut blob = None; + let mut err = None; + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, Some(&mut err)).map_err(|e| format!("serialize the fetch root signature: {e}"))?; + let blob = blob.ok_or("no root signature blob")?; + dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())).map_err(|e| format!("fetch root signature: {e}")) + } +} + +/// root parameter of the index buffer, of vertex buffer slot 0, of the output +pub const PARAM_IB: u32 = 1; +pub const PARAM_VB0: u32 = 2; +pub const PARAM_OUT: u32 = 2 + MAX_SLOTS as u32; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fetch_shader_reads_each_register_once_and_zeroes_the_rest() { + let e = [ + Element { register: 0, slot: 0, offset: 0, format: 6, per_instance: false }, + Element { register: 2, slot: 1, offset: 4, format: 28, per_instance: true }, + ]; + let h = hlsl(3, &e).unwrap(); + assert!(h.contains("uint o = id * 48u;")); + assert!(h.contains("outb.Store4(o + 16u, uint4(0u, 0u, 0u, 0u));"), "{h}"); + // R32G32B32_FLOAT: three words, w = 1.0 + assert!(h.contains("outb.Store4(o + 0u, uint4(w0, w1, w2, 0x3F800000u));"), "{h}"); + // R8G8B8A8_UNORM per instance, one word + assert!(h.contains("slot[1].x + first_instance * slot[1].y + 4u"), "{h}"); + assert!(h.contains("asuint(float(((w0 >> 8u) & 0xffu)) / 255.0)"), "{h}"); + assert!(hlsl(1, &[Element { register: 0, slot: 0, offset: 0, format: 26, per_instance: false }]).is_err(), "R11G11B10 not fetched yet"); + assert!(hlsl(1, &[Element { register: 0, slot: 9, offset: 0, format: 2, per_instance: false }]).is_err()); + assert_eq!(Constants::default().words().len(), CONSTANTS as usize); + } + + #[test] + fn signed_and_bgra_components() { + assert_eq!(component(1, Pack::Bits(16), Num::Sint), "uint((int(((w0 >> 16u) & 0xffffu) << 16u) >> 16))"); + let h = hlsl(1, &[Element { register: 0, slot: 0, offset: 0, format: 87, per_instance: false }]).unwrap(); + assert!(h.contains("uint4(asuint(float(((w0 >> 16u) & 0xffu)) / 255.0), asuint(float(((w0 >> 8u) & 0xffu)) / 255.0), asuint(float(((w0 >> 0u) & 0xffu)) / 255.0)"), "{h}"); + } +} diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index bd2c568ba..0401761b2 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -53,6 +53,7 @@ pub mod dxc; pub(crate) mod emit; +pub mod fetch; pub mod mesh_dispatch; pub mod mesh_wave; pub mod x64_masks; diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 22fc6ab6d..ea705e6a9 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -211,6 +211,12 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us let pso = super::pso_async::resolve_wait(with(this, |s| s.pso)); let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); + if let Some(tp) = super::real::two_pass_of(pso) { + // the group / vertex counts are in GPU memory: the record buffer cannot be sized here + count(DRAWS_SKIPPED); + note_skipped(format_args!("ExecuteIndirect with a console {} pipeline (two passes) skipped – not done yet", tp.kind)); + return; + } if !gfx && !compute { return pc(this, sig, max, args, args_off, count_buf, count_off); } @@ -299,6 +305,9 @@ unsafe fn draw_rects(this: *mut c_void, list: &ID3D12GraphicsCommandList, vertic /// #12 DrawInstanced pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) { DRAW_ARGS.with(|d| d.set((false, vertices, instances, first_vertex, 0))); + if gs_draw(this, vertices, instances, first_vertex, None, first_instance).is_some() { + return; + } if let Some(list) = graphics_bound(this) { if draw_rects(this, &list, vertices, instances, first_vertex, first_instance) { return; @@ -315,6 +324,10 @@ thread_local! { /// #13 DrawIndexedInstanced pub(super) unsafe extern "system" fn draw_indexed_instanced(this: *mut c_void, indices: u32, instances: u32, first_index: u32, base_vertex: i32, first_instance: u32) { + DRAW_ARGS.with(|d| d.set((true, indices, instances, first_index, base_vertex))); + if gs_draw(this, indices, instances, first_index, Some(base_vertex), first_instance).is_some() { + return; + } if let Some(list) = prepare_indexed_draw(this, indices, instances, first_index, base_vertex) { super::list_x::sync_title_buffers(this, Some((first_index, indices, base_vertex)), 0, 0, instances); emit_prepared_indexed_draw(&list, indices, instances, first_index, base_vertex, first_instance); @@ -352,6 +365,13 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone(); let pso = with(this, |s| s.pso); // a pipeline still being built in the background is waited for (its stand-in draws nothing) + if super::real::two_pass_of(super::pso_async::resolve_wait(pso)).is_some() { + // a draw XCL does not run in two passes (DrawIndexedX): a mesh pipeline draws no + // vertices on the PC + count(DRAWS_SKIPPED); + note_skipped(format_args!("a draw with a pipeline in two passes that is not run that way (DrawIndexedX) skipped")); + return None; + } if !super::real::is_translated_graphics(super::pso_async::resolve_wait(pso)) { count(DRAWS_PC); if super::present::trace_frame() { @@ -792,6 +812,38 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis /// arguments the console's way – compute or graphics) and the argument table in unified /// memory, u1 res, u2… the memory windows; then the pipeline. unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool) -> Result<(), String> { + let views = abi_views(this, gfx, None, &[])?; + // a pipeline still being built in the background is waited for + let real = super::pso_async::resolve_wait(pso); + let rs = super::real::pso_root_signature(real).or_else(|| super::real::abi_rs_cached().map(|p| p as usize)).ok_or("no XCL ABI root signature")?; + let rs = rs as *mut c_void; + let rs = ID3D12RootSignature::from_raw_borrowed(&rs).ok_or("root signature")?; + set_abi(list, rs, &views, gfx); + let real = real as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?; + list.SetPipelineState(pc); + Ok(()) +} + +/// The ABI root signature `rs` and its six root UAVs `views` on the compute or graphics side. +unsafe fn set_abi(list: &ID3D12GraphicsCommandList, rs: &ID3D12RootSignature, views: &[u64], gfx: bool) { + if gfx { + list.SetGraphicsRootSignature(rs); + for (k, v) in views.iter().enumerate() { + list.SetGraphicsRootUnorderedAccessView(k as u32, *v); + } + } else { + list.SetComputeRootSignature(rs); + for (k, v) in views.iter().enumerate() { + list.SetComputeRootUnorderedAccessView(k as u32, *v); + } + } +} + +/// The GPU addresses of the ABI's root UAVs for the kept arguments (compute or graphics): +/// u0 io (the user SGPRs, `io_patch` written over them), u1 res (`res`, or 256 bytes of its +/// own), u2… the memory windows. +unsafe fn abi_views(this: *mut c_void, gfx: bool, res: Option, io_patch: &[(usize, u32)]) -> Result, String> { let u = crate::gpu::uma::get().ok_or("no unified memory")?; let windows = super::real::uma_window_vas(); let first = *windows.first().ok_or("unified memory is not open on the GPU")?; @@ -810,30 +862,262 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi None => vec![table_at as u32, (table_at >> 32) as u32], }; io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); + for &(k, v) in io_patch { + if let Some(w) = io.get_mut(k) { + *w = v; + } + } let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::>())?; - let res_at = copy(&[0u8; 256])?; let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); - // a pipeline still being built in the background is waited for - let real = super::pso_async::resolve_wait(pso); - let rs = super::real::pso_root_signature(real).or_else(|| super::real::abi_rs_cached().map(|p| p as usize)).ok_or("no XCL ABI root signature")?; - let rs = rs as *mut c_void; - let rs = ID3D12RootSignature::from_raw_borrowed(&rs).ok_or("root signature")?; - let views = [va(io_at), va(res_at)].into_iter().chain((0..4).map(|k| windows.get(k).copied().unwrap_or(first))); - if gfx { - list.SetGraphicsRootSignature(rs); - for (k, v) in views.enumerate() { - list.SetGraphicsRootUnorderedAccessView(k as u32, v); + let res = match res { + Some(r) => r, + None => va(copy(&[0u8; 256])?), + }; + Ok([va(io_at), res].into_iter().chain((0..4).map(|k| windows.get(k).copied().unwrap_or(first))).collect()) +} + +// --------------------------------------------------------------------------------------- +// pipelines in two passes (console MS / NGG and legacy GS: `real::TwoPassPso`) +// --------------------------------------------------------------------------------------- + +/// D3D12's limit on thread groups in one dimension of a dispatch +const MAX_GROUPS: u32 = 65535; + +/// ID3D12GraphicsCommandList6::DispatchMesh on the PC +const PC_DISPATCH_MESH: usize = 79; + +/// Unified memory for this recording in window 0 – what `mem` (u2) holds, the memory a +/// 32-bit console address names – freed when the list's allocator is reset. GPU data only: in +/// the runtime layout window 0 is a sparse window (video memory). +unsafe fn window0_scratch(this: *mut c_void, size: usize) -> Result<*mut u8, String> { + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + let size = size.max(16); + let p = if u.is_sparse_window(0) { super::sparse::alloc_in(0, size, 1 << 16).map(|(p, _)| p as *mut u8) } else { u.alloc_in(0, size, 1 << 16) }; + let p = p.ok_or_else(|| format!("window 0 of unified memory is full ({} KB for a two-pass draw)", size >> 10))?; + with(this, |s| s.uma.push(p as usize)); + Ok(p) +} + +/// A UAV barrier on all UAV accesses. +fn uav_barrier_all() -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }) }, + } +} + +/// A draw with a pipeline in two passes: the console program as a compute shader over +/// `groups` thread groups (one record each, in memory of this recording), a UAV barrier, then +/// the title's mesh pipeline (pass-through MS + PS) over the records. Both passes get the kept +/// graphics root arguments (`io_patch` written over the user SGPRs). Afterwards the list has +/// the mesh pipeline and its ABI root signature bound, as after any translated draw; the +/// compute side is set again by the next translated dispatch (`bind_abi`), and the title's +/// own root signatures and arguments never reach the PC list. +unsafe fn two_pass(this: *mut c_void, list: &ID3D12GraphicsCommandList, real: usize, tp: &super::real::TwoPassPso, groups: u32, io_patch: &[(usize, u32)]) -> Result<(), String> { + if groups == 0 { + return Ok(()); + } + let mesh_groups = groups.saturating_mul(tp.mesh_groups_per_record.max(1)); + if groups > MAX_GROUPS || mesh_groups > MAX_GROUPS { + return Err(format!("{groups} groups ({mesh_groups} mesh groups) – over D3D12's {MAX_GROUPS} in one dispatch")); + } + let rec = tp.record.record_dwords() * 4; + let res = allocate_upload_memory(this, groups as usize * rec, 256); + if res.is_null() { + return Err(format!("unified memory is full ({} KB of records)", (groups as usize * rec) >> 10)); + } + // a group that allocates no output leaves its counts at 0 (the memory is reused) + for g in 0..groups as usize { + std::ptr::write_bytes(res.add(g * rec), 0, 16); + } + let res_va = super::real::uma_va_of(res as usize).ok_or("record buffer not on the GPU")?; + let views = abi_views(this, true, Some(res_va), io_patch)?; + let rs = |p: usize| { + let p = p as *mut c_void; + ID3D12RootSignature::from_raw_borrowed(&p).cloned() + }; + let ps = |p: usize| { + let p = p as *mut c_void; + ID3D12PipelineState::from_raw_borrowed(&p).cloned() + }; + let (crs, cpso) = (rs(tp.compute_rs).ok_or("compute root signature")?, ps(tp.compute).ok_or("compute pipeline")?); + let (mrs, mpso) = (rs(tp.mesh_rs).ok_or("mesh root signature")?, ps(real).ok_or("mesh pipeline")?); + // pass 1: the console program, one record per group + set_abi(list, &crs, &views, false); + list.SetPipelineState(&cpso); + list.Dispatch(groups, 1, 1); + list.ResourceBarrier(&[uav_barrier_all()]); + // pass 2: the records rasterised + set_abi(list, &mrs, &views, true); + list.SetPipelineState(&mpso); + let dispatch_mesh: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(super::real::orig_fn(this, PC_DISPATCH_MESH)); + dispatch_mesh(this, mesh_groups, 1, 1); + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 4 || ((n + 1).is_power_of_two() && n >= 63) { + crate::xlog_info!("D3D12.X: {} draws in two passes so far (latest: console {} over {groups} groups, {mesh_groups} mesh groups)", n + 1, tp.kind); + } + Ok(()) +} + +/// The pipeline bound on `this` (waited for if still being built) and its two-pass parts +/// (None: not such a pipeline). +fn bound_two_pass(this: *mut c_void) -> Option<(usize, std::sync::Arc)> { + let real = super::pso_async::resolve_wait(with(this, |s| s.pso)); + super::real::two_pass_of(real).map(|tp| (real, tp)) +} + +fn note_skipped(what: std::fmt::Arguments) { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: {what}"); + } +} + +/// #126 (#128 on the newer console layout: `real::NEWER_LIST_SLOTS`) DispatchMesh(x, y, z): +/// with a console mesh pipeline bound, its two passes. The slot is inferred, not seen in a +/// title yet: the console list keeps the PC's ID3D12GraphicsCommandList1 at #104–#109 and +/// RSSetShadingRate / RSSetShadingRateImage at #124 / #125, and on the PC DispatchMesh follows +/// them. With any other pipeline bound the call is logged with its arguments (they tell what +/// the method is) and dropped, as by the stub that was there. +pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: u32, z: u32) { + let Some((real, tp)) = bound_two_pass(this).filter(|(_, tp)| tp.kind == "MS") else { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: command list DispatchMesh slot called ({x:#x}, {y:#x}, {z:#x}) without a console mesh pipeline bound (pipeline {:#x}) – dropped", with(this, |s| s.pso)); } - } else { - list.SetComputeRootSignature(rs); - for (k, v) in views.enumerate() { - list.SetComputeRootUnorderedAccessView(k as u32, v); + return; + }; + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this).cloned() else { return }; + // the translated program numbers its group by SV_GroupID.x: a grid is flattened + let groups = (x as u64) * (y as u64) * (z as u64); + if y > 1 || z > 1 { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: DispatchMesh({x}, {y}, {z}) with a console mesh pipeline – drawn as {groups} groups in a row"); } } - let real = real as *mut c_void; - let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?; - list.SetPipelineState(pc); - Ok(()) + let r = u32::try_from(groups).map_err(|_| "too many groups".to_string()).and_then(|g| two_pass(this, &list, real, &tp, g, &[])); + match r { + Ok(()) => count(DRAWS), + Err(e) => { + count(DRAWS_SKIPPED); + note_skipped(format_args!("DispatchMesh({x}, {y}, {z}) with a console mesh pipeline skipped: {e}")); + } + } +} + +/// A Draw* with a pipeline in two passes bound (Some: it was – drawn or skipped). A GS +/// pipeline: XCL fetches the triangles' vertices (`recomp::fetch`), then the two passes run +/// over them. `indexed`: the base vertex of an indexed draw. +unsafe fn gs_draw(this: *mut c_void, count_: u32, instances: u32, first: u32, indexed: Option, first_instance: u32) -> Option<()> { + let (real, tp) = bound_two_pass(this)?; + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this).cloned() else { return Some(()) }; + if tp.kind != "GS" { + // a mesh pipeline draws no vertices (on the PC the call is invalid) + count(DRAWS_SKIPPED); + note_skipped(format_args!("Draw* with a console mesh pipeline bound (DispatchMesh draws it) skipped")); + return Some(()); + } + match gs_fetch_and_draw(this, &list, real, &tp, count_, instances, first, indexed, first_instance) { + Ok(()) => count(DRAWS), + Err(e) => { + count(DRAWS_SKIPPED); + note_skipped(format_args!("draw with a console GS pipeline skipped: {e}")); + } + } + Some(()) +} + +#[allow(clippy::too_many_arguments)] +unsafe fn gs_fetch_and_draw( + this: *mut c_void, + list: &ID3D12GraphicsCommandList, + real: usize, + tp: &super::real::TwoPassPso, + count_: u32, + instances: u32, + first: u32, + indexed: Option, + first_instance: u32, +) -> Result<(), String> { + use crate::gpu::recomp::fetch; + let f = match &tp.fetch { + Some(Ok(f)) => f, + Some(Err(e)) => return Err(format!("no vertex fetch ({e})")), + None => return Err("no vertex fetch".into()), + }; + let (vbs, ib, topology) = super::list_x::ia_state(this); + if topology.is_some_and(|t| t != windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32) { + return Err(format!("topology {topology:?} (triangle lists only)")); + } + if instances > 1 { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: a draw of {instances} instances with a console GS pipeline – the first only"); + } + } + if !f.missing.is_empty() { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: GS pipeline inputs without an input layout element (zero): {:?}", f.missing); + } + } + let prims = count_ / 3; + if prims == 0 || instances == 0 { + return Ok(()); + } + let groups = prims.div_ceil(crate::gpu::recomp::GS_PRIMS_PER_GROUP); + if groups > MAX_GROUPS { + return Err(format!("{prims} triangles in one draw")); + } + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + let vertices = prims * 3; + let vin = window0_scratch(this, vertices as usize * f.registers.max(1) as usize * 16)?; + // io[IO_GS_VERTICES] is an offset in `mem` (u2, window 0) + let vin_offset = vin as usize - u.window(0).0; + let vin_va = super::real::uma_va_of(vin as usize).ok_or("fetched vertices not on the GPU")?; + // the fetch: buffers bound at 4-byte aligned addresses, the rest in the constants + let mut c = fetch::Constants { count: vertices, first, base_vertex: indexed.unwrap_or(0), first_instance, ..Default::default() }; + let aligned = |va: u64| va & !3; + let ib_va = match (indexed, ib) { + (Some(_), Some(v)) => { + let sixteen = v.Format == windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16_UINT; + c.flags = 1 | if sixteen { 2 } else { 0 }; + c.ib_delta = (v.BufferLocation & 3) as u32; + c.ib_bytes = v.SizeInBytes + c.ib_delta; + aligned(v.BufferLocation) + } + (Some(_), None) => return Err("indexed draw without an index buffer".into()), + (None, _) => vin_va, + }; + let mut slot_vas = [vin_va; fetch::MAX_SLOTS]; + for (k, slot) in f.slots.iter().enumerate() { + let v = vbs.get(slot).ok_or_else(|| format!("no vertex buffer at slot {slot}"))?; + if v.BufferLocation == 0 { + return Err(format!("vertex buffer at slot {slot} not on the GPU")); + } + let delta = (v.BufferLocation & 3) as u32; + c.slots[k] = [delta, v.StrideInBytes, v.SizeInBytes + delta, 0]; + slot_vas[k] = aligned(v.BufferLocation); + } + let rs = super::real::fetch_rs().ok_or("no vertex fetch root signature")? as *mut c_void; + let rs = ID3D12RootSignature::from_raw_borrowed(&rs).ok_or("fetch root signature")?; + let pso = f.pso as *mut c_void; + let pso = ID3D12PipelineState::from_raw_borrowed(&pso).ok_or("fetch pipeline")?; + list.SetComputeRootSignature(rs); + let words = c.words(); + list.SetComputeRoot32BitConstants(0, words.len() as u32, words.as_ptr() as *const c_void, 0); + list.SetComputeRootShaderResourceView(fetch::PARAM_IB, ib_va); + for (k, va) in slot_vas.iter().enumerate() { + list.SetComputeRootShaderResourceView(fetch::PARAM_VB0 + k as u32, *va); + } + list.SetComputeRootUnorderedAccessView(fetch::PARAM_OUT, vin_va); + list.SetPipelineState(pso); + list.Dispatch(vertices.div_ceil(fetch::THREADS), 1, 1); + list.ResourceBarrier(&[uav_barrier_all()]); + two_pass(this, list, real, tp, groups, &[(crate::gpu::recomp::IO_GS_PRIMS, prims), (crate::gpu::recomp::IO_GS_VERTICES, vin_offset as u32)]) } #[cfg(test)] diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index e6400ef09..6a82c627e 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -268,6 +268,17 @@ pub(super) fn rect_list_state(list: *mut c_void) -> Option (std::collections::BTreeMap, Option, Option) { + let g = LISTS.lock().unwrap(); + match g.as_ref().and_then(|m| m.get(&(list as usize))) { + Some(s) => (s.bindings.vertex_buffers.clone(), s.index_buffer, s.bindings.topology), + None => Default::default(), + } +} + /// `pc_va` for other modules. pub(super) fn pc_va_of(va: u64) -> u64 { pc_va(va) diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 3d0619897..9c8b2fec3 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -28,6 +28,8 @@ pub mod sparse; pub mod title_list; pub mod title_textures; pub mod vram; +#[cfg(test)] +mod two_pass_tests; use std::ffi::c_void; use std::sync::OnceLock; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index dda9388b2..09028a7b4 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -888,6 +888,9 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (90, l::write32_bottom_of_shader_x as usize), (93, l::kickoff_x as usize), (94, l::set_depth_bias_x as usize), + // DispatchMesh after RSSetShadingRate / RSSetShadingRateImage (#124 / #125) as on + // the PC – inferred, see `bind::dispatch_mesh` + (126, b::dispatch_mesh as usize), // console compute/BVH builder extensions (`XboxBvhBuilder.dll`) (146, l::uav_barrier_x as usize), (148, b::allocate_upload_memory as usize), @@ -3562,6 +3565,19 @@ pub struct TwoPassPso { pub mesh_groups_per_record: u32, /// "MS" or "GS" pub kind: &'static str, + /// GS: the vertex fetch in front of the compute pass (Err: why the draws cannot have one) + pub fetch: Option>, +} + +/// The vertex fetch of a GS pipeline (`recomp::fetch`): its compute pipeline state (XCL's, +/// root signature `fetch_rs`), the title's vertex buffer slot of each fetch slot, and the ES +/// input registers each vertex has. +pub struct GsFetch { + pub pso: usize, + pub slots: Vec, + pub registers: u32, + /// some ES input has no element in the input layout (zero) + pub missing: Vec, } impl Drop for TwoPassPso { @@ -3571,6 +3587,86 @@ impl Drop for TwoPassPso { } } +impl Drop for GsFetch { + fn drop(&mut self) { + super::pso_async::release(self.pso); + } +} + +/// The vertex fetch's root signature (`recomp::fetch::root_signature`), made once. +static FETCH_RS: AtomicUsize = AtomicUsize::new(0); + +pub fn fetch_rs() -> Option { + Some(FETCH_RS.load(Ordering::Acquire)).filter(|&p| p != 0) +} + +unsafe fn fetch_rs_for(this: *mut c_void) -> Result { + if let Some(p) = fetch_rs() { + return Ok(p); + } + let dev = ID3D12Device::from_raw_borrowed(&this).ok_or("device")?; + let raw = crate::gpu::recomp::fetch::root_signature(dev)?.into_raw() as usize; + match FETCH_RS.compare_exchange(0, raw, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => Ok(raw), + Err(other) => { + drop(ID3D12RootSignature::from_raw(raw as *mut c_void)); + Ok(other) + } + } +} + +/// The vertex fetch of a GS pipeline from its description's input layout and the ES inputs +/// (ISG1 of the console VS): elements matched by semantic. +unsafe fn gs_fetch(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, vs: &[u8]) -> Result { + use crate::gpu::recomp::fetch; + let inputs: Vec = crate::gpu::dxbc::signatures(vs).0.into_iter().filter(|e| e.system_value == 0).collect(); + let registers = inputs.iter().map(|e| e.register + 1).max().unwrap_or(0); + let layout: &[D3D12_INPUT_ELEMENT_DESC] = if d.InputLayout.pInputElementDescs.is_null() || d.InputLayout.NumElements == 0 || d.InputLayout.NumElements > 64 { + &[] + } else { + std::slice::from_raw_parts(d.InputLayout.pInputElementDescs, d.InputLayout.NumElements as usize) + }; + // offsets of D3D12_APPEND_ALIGNED_ELEMENT: after the previous element of the slot + let mut ends: HashMap = HashMap::new(); + let mut placed = Vec::new(); + for el in layout { + let name = if el.SemanticName.is_null() { String::new() } else { el.SemanticName.to_string().unwrap_or_default() }; + let f = el.Format.0 as u32; + let at = if el.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT { *ends.get(&el.InputSlot).unwrap_or(&0) } else { el.AlignedByteOffset }; + ends.insert(el.InputSlot, at + fetch::bytes(f).unwrap_or(4)); + placed.push((name, el.SemanticIndex, el.InputSlot, at, f, el.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA)); + } + let (mut slots, mut elements, mut missing) = (Vec::::new(), Vec::new(), Vec::new()); + for e in &inputs { + let Some((_, _, slot, at, f, inst)) = placed.iter().find(|p| p.0.eq_ignore_ascii_case(&e.name) && p.1 == e.index) else { + missing.push(e.semantic()); + continue; + }; + let k = match slots.iter().position(|s| s == slot) { + Some(k) => k, + None => { + slots.push(*slot); + slots.len() - 1 + } + }; + elements.push(fetch::Element { register: e.register, slot: k as u32, offset: *at, format: *f, per_instance: *inst }); + } + let hlsl = fetch::hlsl(registers, &elements)?; + let cs = crate::gpu::recomp::dxc::compile_cached(&hlsl, "main", "cs_6_6")?.0; + let rs = fetch_rs_for(this)?; + let fc: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); + let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + cdesc.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs as *mut c_void); + cdesc.CS = bytecode(&cs); + let iid = pc_iid(Kind::PipelineState); + let mut pso: *mut c_void = std::ptr::null_mut(); + let hr = fc(this, &cdesc as *const _ as *const c_void, &iid, &mut pso); + if hr < 0 || pso.is_null() { + return Err(format!("the driver rejected the vertex fetch ({hr:#x})")); + } + Ok(GsFetch { pso: pso as usize, slots, registers, missing }) +} + static TWO_PASS: Mutex>>> = Mutex::new(None); /// The compute pass of a pipeline state XCL built from console MS / GS code. @@ -3661,7 +3757,7 @@ fn two_pass_ps(ps: Option<&[u8]>, split_wave64: bool) -> Result<(Option> /// Create the mesh pipeline (`stream`, RS and shaders already in it) and the compute pass; /// the title gets the mesh pipeline state. #[allow(clippy::too_many_arguments)] -unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu::recomp::pso::TwoPass, mesh_rs: *mut c_void, kind: &'static str, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { +unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu::recomp::pso::TwoPass, mesh_rs: *mut c_void, kind: &'static str, fetch: Option>, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let Some(rs) = abi_rs_for(this, &tp.samplers) else { return E_INVALIDARG }; let fs: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); let desc: [usize; 2] = [stream.0.len(), stream.0.as_ptr() as usize]; @@ -3685,7 +3781,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: return E_INVALIDARG; } note_pso_rs(*ppv, mesh_rs); - TWO_PASS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); + TWO_PASS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind, fetch })); let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); if n < 5 || n % 1000 == 0 { crate::xlog_info!("D3D12.X: pipeline from the console {kind} in two passes (compute {} B + mesh {} B DXIL)", tp.cs.len(), tp.ms.len()); @@ -3767,7 +3863,7 @@ unsafe fn translated_mesh_stream(this: *mut c_void, desc: *const c_void, riid: * out.raw(*ty, payload, palign == 8); } } - Some(finish_two_pass(this, &out, tp, rs, "MS", riid, ppv)) + Some(finish_two_pass(this, &out, tp, rs, "MS", None, riid, ppv)) } /// A graphics PSO with a console VS + GS: the GS pipeline in two passes, as a mesh pipeline @@ -3838,7 +3934,12 @@ unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE if d.Flags.0 != 0 { out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, &d.Flags); } - finish_two_pass(this, &out, tp, rs, "GS", riid, ppv) + // the vertex fetch: a failure only keeps this pipeline's draws from running (logged there) + let fetch = gs_fetch(this, d, vs); + if let Err(e) = &fetch { + note_translation_error(format!("VS+GS vertex fetch: {e}")); + } + finish_two_pass(this, &out, tp, rs, "GS", Some(fetch), riid, ppv) } /// Rewrite a pipeline state stream with stand-in shaders. None if not possible. @@ -4296,7 +4397,9 @@ pub(super) static QUEUE_SHIFTED: AtomicBool = AtomicBool::new(false); static QUEUE_OLDER: AtomicBool = AtomicBool::new(false); /// command list slots of the newer layout → the older layout's slot of the same method -const NEWER_LIST_SLOTS: [(usize, usize); 21] = [(61, 59), (62, 60), (63, 61), (64, 62), (65, 63), (70, 68), (71, 69), (72, 70), (73, 71), (74, 72), (80, 78), (83, 81), (85, 83), (86, 84), (87, 85), (90, 88), (91, 89), (92, 90), (95, 93), (96, 94), (139, 10)]; +/// (128, 126): DispatchMesh, if the shift reaches it – not seen yet; `bind::dispatch_mesh` drops +/// a call without a console mesh pipeline bound. +const NEWER_LIST_SLOTS: [(usize, usize); 22] = [(61, 59), (62, 60), (63, 61), (64, 62), (65, 63), (70, 68), (71, 69), (72, 70), (73, 71), (74, 72), (80, 78), (83, 81), (85, 83), (86, 84), (87, 85), (90, 88), (91, 89), (92, 90), (95, 93), (96, 94), (128, 126), (139, 10)]; /// The title called device method `slot`, which only runtimes with the newer layouts have (a retail game /// records its first lists before any queue call could tell). diff --git a/crates/xcl/src/hle/d3d12x/two_pass_tests.rs b/crates/xcl/src/hle/d3d12x/two_pass_tests.rs new file mode 100644 index 000000000..941f21a1f --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/two_pass_tests.rs @@ -0,0 +1,536 @@ +//! Pipelines in two passes drawn end to end without a game: synthetic console containers (an +//! NGG mesh program; the ES variant of a VS + a GS) go through the backend device's pipeline +//! hooks, the draws are recorded through the console command list's methods (`bind`, +//! `list_x`) on a list made as for a title, and the render target is read back. +//! +//! Skipped (passing) without a D3D12 device with mesh shaders, unified memory on the GPU or DXC. + +use std::ffi::c_void; +use std::sync::Mutex; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +use super::{bind, device_x, list_x, real, title_list}; +use crate::gpu::rdna2::encode; +use crate::gpu::recomp::dxc; +use crate::gpu::xbox::tests::{container, dxil_part, fssm}; + +/// The tests share the backend device and its counters. +static SERIAL: Mutex<()> = Mutex::new(()); + +const SIZE: u32 = 32; +const CLEAR: [f32; 4] = [-1.0, -1.0, -1.0, -1.0]; +/// VALU source code of v0 +const V: u64 = 256; + +fn f(x: f32) -> u32 { + x.to_bits() +} + +/// The backend device, when it can run these tests. +fn ready() -> Option { + if dxc::location().is_err() { + println!("no DXC – skipping"); + return None; + } + if super::backend() != super::Backend::Real { + println!("no real D3D12 device – skipping"); + return None; + } + if real::uma_window_vas().is_empty() { + println!("unified memory is not open on the GPU – skipping"); + return None; + } + let raw = real::device_raw(); + let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw) }?.clone(); + let mut o7 = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + let mesh = unsafe { dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &mut o7 as *mut _ as _, std::mem::size_of_val(&o7) as u32) }.is_ok() + && o7.MeshShaderTier.0 >= D3D12_MESH_SHADER_TIER_1.0; + if !mesh { + println!("GPU without mesh shaders – skipping"); + return None; + } + Some(dev) +} + +/// A v1 signature part (ISG1 / OSG1): (name, index, system value, component type, register). +fn signature(elements: &[(&str, u32, u32, u32, u32)]) -> Vec { + let mut d = Vec::new(); + d.extend_from_slice(&(elements.len() as u32).to_le_bytes()); + d.extend_from_slice(&8u32.to_le_bytes()); + let names_at = 8 + 32 * elements.len() as u32; + let mut names = Vec::new(); + for &(name, index, sv, ct, reg) in elements { + d.extend_from_slice(&0u32.to_le_bytes()); // stream + d.extend_from_slice(&(names_at + names.len() as u32).to_le_bytes()); + d.extend_from_slice(&index.to_le_bytes()); + d.extend_from_slice(&sv.to_le_bytes()); + d.extend_from_slice(&ct.to_le_bytes()); + d.extend_from_slice(®.to_le_bytes()); + d.extend_from_slice(&[0xF, 0xF, 0, 0]); + d.extend_from_slice(&0u32.to_le_bytes()); // min precision + names.extend_from_slice(name.as_bytes()); + names.push(0); + } + d.extend_from_slice(&names); + d +} + +/// A PSV0 part: `r` = the runtime info (48 bytes). +fn psv0(r: &[u8; 48]) -> Vec { + let mut part = 48u32.to_le_bytes().to_vec(); + part.extend_from_slice(r); + part.extend_from_slice(&0u32.to_le_bytes()); // resources + part +} + +/// A console shader container of DXIL kind `kind` with one FSSM (hardware stage `hw`). +fn console(kind: u32, hw: u8, code: &[u8], isg1: &[u8], osg1: &[u8], psv: Option>) -> Vec { + let dxil = dxil_part(kind, &[fssm(code, &[(hw, kind as u8)])]); + let mut parts: Vec<(&[u8; 4], &[u8])> = vec![(b"SFI0", &[0; 8]), (b"ISG1", isg1), (b"OSG1", osg1)]; + if let Some(p) = &psv { + parts.push((b"PSV0", p)); + } + parts.push((b"HASH", &[0; 20])); + parts.push((b"DXIL", &dxil)); + container(&parts) +} + +fn prog(list: &[(&str, &str, Vec<(&str, u64)>, Option)], end: bool) -> Vec { + let mut v = Vec::new(); + for (n, e, fl, l) in list { + v.extend(encode(n, e, fl, *l).unwrap_or_else(|x| panic!("{n}: {x}"))); + } + if end { + v.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + } + v +} + +/// RTS0 v2 with one parameter of `n` root constants (inline: the user SGPRs from s8). +fn rts0_constants(n: u32) -> Vec { + let words: [u32; 12] = [2, 1, 24, 0, 0, 0, 1, 0, 36, 0, 0, n]; + words.iter().flat_map(|w| w.to_le_bytes()).collect() +} + +/// A list made as for a title (wrapped, adopted by `bind` / `list_x`), with a render target, +/// viewport and scissor set on the PC list; `record` records the draw through the console +/// methods; then the target is read back. +struct Target { + dev: ID3D12Device, + alloc: ID3D12CommandAllocator, + raw_list: *mut c_void, + backing: *mut c_void, + rt: ID3D12Resource, + _heap: ID3D12DescriptorHeap, +} + +impl Target { + unsafe fn new(dev: &ID3D12Device) -> Target { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let mut raw_list: *mut c_void = std::ptr::null_mut(); + let iid = windows_sys::core::GUID::from_u128(0x5b160d0f_ac1b_4185_8ba8_b3ae42a5a455); + let hr = device_x::create_command_list_pc(dev.as_raw(), 0, D3D12_COMMAND_LIST_TYPE_DIRECT.0 as u32, alloc.as_raw() as usize, 0, &iid, &mut raw_list); + assert!(hr >= 0 && !raw_list.is_null(), "CreateCommandList: {hr:#x}"); + let backing = title_list::backing(raw_list).expect("a title's list"); + let tex = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: SIZE as u64, + Height: SIZE, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let cv = D3D12_CLEAR_VALUE { Format: DXGI_FORMAT_R32G32B32A32_FLOAT, Anonymous: D3D12_CLEAR_VALUE_0 { Color: CLEAR } }; + let mut rt: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &tex, D3D12_RESOURCE_STATE_RENDER_TARGET, Some(&cv), &mut rt).unwrap(); + let rt = rt.unwrap(); + let heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: 1, ..Default::default() }).unwrap(); + let rtv = heap.GetCPUDescriptorHandleForHeapStart(); + dev.CreateRenderTargetView(&rt, None, rtv); + let list = ID3D12GraphicsCommandList::from_raw_borrowed(&backing).unwrap(); + list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.ClearRenderTargetView(rtv, &CLEAR, None); + list.RSSetViewports(&[D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: SIZE as f32, Height: SIZE as f32, MinDepth: 0.0, MaxDepth: 1.0 }]); + list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { left: 0, top: 0, right: SIZE as i32, bottom: SIZE as i32 }]); + Target { dev: dev.clone(), alloc, raw_list, backing, rt, _heap: heap } + } + + /// Close, run and read back the target (one RGBA32F texel per pixel, row by row). + unsafe fn finish(self) -> Vec<[f32; 4]> { + let dev = &self.dev; + let list = ID3D12GraphicsCommandList::from_raw_borrowed(&self.backing).unwrap().clone(); + let tex = self.rt.GetDesc(); + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0u64; + dev.GetCopyableFootprints(&tex, 0, 1, 0, Some(&mut fp), None, None, Some(&mut total)); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: total, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut rb: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb).unwrap(); + let rb = rb.unwrap(); + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(&self.rt), + Subresource: 0, + StateBefore: D3D12_RESOURCE_STATE_RENDER_TARGET, + StateAfter: D3D12_RESOURCE_STATE_COPY_SOURCE, + }), + }, + }]); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&self.rt), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + let t0 = std::time::Instant::now(); + while fence.GetCompletedValue() < 1 { + assert!(t0.elapsed().as_secs() < 20, "the GPU did not finish (device removed: {:?})", dev.GetDeviceRemovedReason()); + std::thread::yield_now(); + } + assert!(dev.GetDeviceRemovedReason().is_ok(), "device removed: {:?}", dev.GetDeviceRemovedReason()); + let mut q = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut q)).unwrap(); + let pitch = fp.Footprint.RowPitch as usize; + let mut px = Vec::with_capacity((SIZE * SIZE) as usize); + for y in 0..SIZE as usize { + for x in 0..SIZE as usize { + let c = (q as *const u8).add(y * pitch + x * 16) as *const f32; + px.push([*c, *c.add(1), *c.add(2), *c.add(3)]); + } + } + rb.Unmap(0, None); + // the list goes as a title's does (its unified memory with its allocator) + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(self.raw_list as *const *const usize)).add(2)); + release(self.raw_list); + drop(self.alloc); + px + } +} + +/// Is pixel centre (x, y) (pixels, y down) inside triangle `t` given in clip space (y up)? +fn inside(t: [[f32; 2]; 3], x: usize, y: usize, margin: f32) -> bool { + let p = |v: [f32; 2]| ((v[0] + 1.0) * 0.5 * SIZE as f32, (1.0 - v[1]) * 0.5 * SIZE as f32); + let (a, b, c) = (p(t[0]), p(t[1]), p(t[2])); + let (qx, qy) = (x as f32 + 0.5, y as f32 + 0.5); + let area = (b.0 - a.0) * (c.1 - a.1) - (c.0 - a.0) * (b.1 - a.1); + let l1 = ((b.0 - qx) * (c.1 - qy) - (c.0 - qx) * (b.1 - qy)) / area; + let l2 = ((c.0 - qx) * (a.1 - qy) - (a.0 - qx) * (c.1 - qy)) / area; + let l3 = 1.0 - l1 - l2; + l1.min(l2).min(l3) > margin +} + +/// Console NGG program (the console's style: wave index from s3, group from v5 >> 7, +/// GS_ALLOC_REQ for 3 vertices and 1 triangle, exp pos0 / param0 / prim) in an MS container + +/// a PC PS, through `CreatePipelineState`; drawn by the console list's DispatchMesh with two +/// groups: each group's triangle (shifted right by its group) with param0.x = the group. +#[test] +fn gpu_console_mesh_pipeline_draws_through_dispatch_mesh() { + let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let Some(dev) = ready() else { return }; + let exp = |tgt: u64, en: u64, v: [u64; 4], done: u64| ("EXP", "ENC_EXP", vec![("TGT", tgt), ("EN", en), ("VSRC0", v[0]), ("VSRC1", v[1]), ("VSRC2", v[2]), ("VSRC3", v[3]), ("DONE", done)], None); + let mut list: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = vec![ + ("S_BFE_U32", "ENC_SOP2", vec![("SDST", 0), ("SSRC0", 3), ("SSRC1", 255)], Some(0x40018)), // wave index + ("V_MBCNT_LO_U32_B32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 193), ("SRC1", 128)], None), + ("V_MBCNT_HI_U32_B32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 193), ("SRC1", V)], None), + ("V_LSHL_ADD_U32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 0), ("SRC1", 134), ("SRC2", V)], None), // thread in group + ("V_READFIRSTLANE_B32", "ENC_VOP1", vec![("VDST", 1), ("SRC0", V + 5)], None), + ("S_LSHR_B32", "ENC_SOP2", vec![("SDST", 1), ("SSRC0", 1), ("SSRC1", 135)], None), // group = v5 >> 7 + ("S_MOV_B32", "ENC_SOP1", vec![("SDST", 124), ("SSRC0", 255)], Some(1 << 12 | 3)), // 1 primitive, 3 vertices + ("S_SENDMSG", "ENC_SOPP", vec![("SIMM16", 9)], None), + ("S_BARRIER", "ENC_SOPP", vec![], None), + ("V_CMPX_GT_U32", "ENC_VOPC", vec![("SRC0", 131), ("VSRC1", 0)], None), // threads 0..2 + ("BUFFER_LOAD_DWORDX4", "ENC_MUBUF", vec![("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("V_CVT_F32_U32", "ENC_VOP1", vec![("VDST", 20), ("SRC0", 1)], None), + ("V_ADD_F32", "ENC_VOP2", vec![("VDST", 10), ("SRC0", V + 20), ("VSRC1", 10)], None), // x += group + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 14), ("SRC0", V + 20)], None), + ("V_CVT_F32_U32", "ENC_VOP1", vec![("VDST", 15), ("SRC0", V)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 16), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 17), ("SRC0", 242)], None), + ]; + list.push(exp(12, 0xF, [10, 11, 12, 13], 1)); + list.push(exp(32, 0xF, [14, 15, 16, 17], 0)); + list.push(("S_MOV_B64", "ENC_SOP1", vec![("SDST", 126), ("SSRC0", 193)], None)); + list.push(("V_CMPX_EQ_U32", "ENC_VOPC", vec![("SRC0", 128), ("VSRC1", 0)], None)); // thread 0 + list.push(("V_MOV_B32", "ENC_VOP1", vec![("VDST", 21), ("SRC0", 255)], Some(1 << 10 | 2 << 20))); + list.push(exp(20, 1, [21, 0, 0, 0], 1)); + let code = prog(&list, true); + let mut r = [0u8; 48]; + r[12..14].copy_from_slice(&128u16.to_le_bytes()); // max vertices + r[14..16].copy_from_slice(&128u16.to_le_bytes()); // max primitives + r[24] = 13; // mesh + r[27] = 2; // triangles + r[36..40].copy_from_slice(&128u32.to_le_bytes()); // numthreads + r[40..44].copy_from_slice(&1u32.to_le_bytes()); + r[44..48].copy_from_slice(&1u32.to_le_bytes()); + let ms = console(13, 7, &code, &signature(&[]), &signature(&[("SV_Position", 0, 1, 3, 0), ("TEXCOORD", 0, 0, 3, 1)]), Some(psv0(&r))); + assert!(crate::gpu::recomp::pso::console_mesh(&ms, None, true).is_ok(), "{:?}", crate::gpu::recomp::pso::console_mesh(&ms, None, true).err()); + let ps = dxc::compile("struct V { float4 pos : SV_Position; float4 p0 : TEXCOORD0; };\nfloat4 main(V v) : SV_Target0 { return v.p0; }\n", "main", "ps_6_6", &[]).unwrap(); + + unsafe { + // the title's mesh pipeline: its root signature, MS (console), PS, state + let game_rs: ID3D12RootSignature = { + let mut ser = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).unwrap(); + let ser = ser.unwrap(); + dev.CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())).unwrap() + }; + #[repr(C, align(8))] + struct Sub { + ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, + v: T, + } + #[repr(C)] + struct Stream { + rs: Sub<*mut c_void>, + ms: Sub, + ps: Sub, + rast: Sub, + depth: Sub, + rt: Sub, + } + let code = |b: &[u8]| D3D12_SHADER_BYTECODE { pShaderBytecode: b.as_ptr() as _, BytecodeLength: b.len() }; + let mut rt = D3D12_RT_FORMAT_ARRAY { NumRenderTargets: 1, ..Default::default() }; + rt.RTFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + let st = Stream { + rs: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, v: game_rs.as_raw() }, + ms: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, v: code(&ms) }, + ps: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, v: code(&ps) }, + rast: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, v: D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: true.into(), ..Default::default() } }, + depth: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, v: D3D12_DEPTH_STENCIL_DESC::default() }, + rt: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, v: rt }, + }; + let d2: ID3D12Device2 = dev.cast().unwrap(); + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: std::mem::size_of::(), pPipelineStateSubobjectStream: &st as *const _ as *mut _ }; + let pso: ID3D12PipelineState = d2.CreatePipelineState(&desc).unwrap_or_else(|e| panic!("{e}: {:?}", real::stats().translation_errors)); + let real_pso = super::pso_async::resolve_wait(pso.as_raw() as usize); + let tp = real::two_pass_of(real_pso).unwrap_or_else(|| panic!("no two-pass parts: {:?}", real::stats().translation_errors)); + assert_eq!(tp.kind, "MS"); + + // the vertex table (3 float4) in title memory, its V# in s[16:19] (root constants 8..11) + let u = crate::gpu::uma::get().unwrap(); + let table = u.alloc(1 << 16, 1 << 16).unwrap() as usize; + for (i, (x, y)) in [(-1.0f32, -1.0f32), (-1.0, 1.0), (0.0, -1.0)].iter().enumerate() { + std::ptr::copy_nonoverlapping([f(*x), f(*y), f(0.0), f(1.0)].as_ptr(), (table as *mut u32).add(4 * i), 4); + } + let mut constants = [0u32; 12]; + constants[8..12].copy_from_slice(&[table as u32, ((table >> 32) as u32 & 0xFFFF) | 16 << 16, 3, 0]); + let rs_key = 0x7400_0010usize; + super::console_list::note_root_signature(rs_key, &rts0_constants(12)); + + let t = Target::new(&dev); + let before = bind::counts_snapshot(); + bind::set_pipeline_state(t.backing, pso.as_raw()); + bind::set_graphics_root_signature(t.backing, rs_key as *mut c_void); + bind::set_graphics_root_constants(t.backing, 0, 12, constants.as_ptr(), 0); + bind::dispatch_mesh(t.backing, 2, 1, 1); + let after = bind::counts_snapshot(); + // (other tests count too: the pixels below are what tells) + assert!(after[0] > before[0], "the DispatchMesh ran as a translated draw"); + let px = t.finish(); + u.free(table); + + // group g: (-1 + g, -1), (-1 + g, 1), (g, -1); param0 = (g, vertex, 0, 1) + let (mut hit, mut clear) = ([0usize; 2], 0usize); + for y in 0..SIZE as usize { + for x in 0..SIZE as usize { + let p = px[y * SIZE as usize + x]; + let mut covered = false; + for g in 0..2 { + let gf = g as f32; + if inside([[-1.0 + gf, -1.0], [-1.0 + gf, 1.0], [gf, -1.0]], x, y, 0.02) { + assert_eq!((p[0], p[2], p[3]), (gf, 0.0, 1.0), "pixel ({x},{y}) in group {g}'s triangle: {p:?}"); + hit[g] += 1; + covered = true; + } + } + let near = (0..2).any(|g| inside([[-1.0 + g as f32, -1.0], [-1.0 + g as f32, 1.0], [g as f32, -1.0]], x, y, -0.05)); + if !covered && !near { + assert_eq!(p, CLEAR, "pixel ({x},{y}) outside both triangles"); + clear += 1; + } + } + } + println!("two-pass MS draw: {hit:?} pixels in the two triangles, {clear} clear"); + assert!(hit[0] > 80 && hit[1] > 80 && clear > 300, "{hit:?} / {clear}"); + } +} + +/// A legacy GS pipeline: the ES variant of a console VS (POSITION → LDS, s_setpc into the GS) +/// + a GS (each triangle → a 4-vertex strip, the parallelogram a, b, c, b + c − a; TEXCOORD0 = +/// (primitive, vertex)) + a PC PS, through `CreateGraphicsPipelineState`; drawn by the console +/// list's DrawInstanced from a vertex buffer in title memory (two triangles) and by its +/// DrawIndexedInstanced (the second triangle through 16-bit indices). +#[test] +fn gpu_console_gs_pipeline_draws_through_draw_instanced() { + let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let Some(dev) = ready() else { return }; + let e = |n: &'static str, enc: &'static str, f: Vec<(&'static str, u64)>| (n, enc, f, None::); + // ES: vertex (v9..v12) → LDS at lane·32, then into the GS + let es = prog( + &[ + e("V_MBCNT_LO_U32_B32", "ENC_VOP3", vec![("VDST", 20), ("SRC0", 193), ("SRC1", 128)]), + e("V_MBCNT_HI_U32_B32", "ENC_VOP3", vec![("VDST", 20), ("SRC0", 193), ("SRC1", V + 20)]), + e("V_LSHLREV_B32", "ENC_VOP2", vec![("VDST", 21), ("SRC0", 133), ("VSRC1", 20)]), + e("DS_WRITE2_B32", "ENC_DS", vec![("ADDR", 21), ("DATA0", 9), ("DATA1", 10), ("OFFSET0", 0), ("OFFSET1", 1)]), + e("DS_WRITE2_B32", "ENC_DS", vec![("ADDR", 21), ("DATA0", 11), ("DATA1", 12), ("OFFSET0", 2), ("OFFSET1", 3)]), + e("S_BARRIER", "ENC_SOPP", vec![]), + e("S_SETPC_B64", "ENC_SOP1", vec![("SSRC0", 6)]), + ], + false, + ); + // GS: EXEC = primitives of this wave (s3[15:8]), vertices from LDS, parallelogram strip + let mut gs: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = vec![ + ("S_BFE_U32", "ENC_SOP2", vec![("SDST", 0), ("SSRC0", 3), ("SSRC1", 255)], Some(0x80008)), + ("S_BFM_B64", "ENC_SOP2", vec![("SDST", 126), ("SSRC0", 0), ("SSRC1", 128)], None), + ("V_MBCNT_LO_U32_B32", "ENC_VOP3", vec![("VDST", 20), ("SRC0", 193), ("SRC1", 128)], None), + ("V_MBCNT_HI_U32_B32", "ENC_VOP3", vec![("VDST", 20), ("SRC0", 193), ("SRC1", V + 20)], None), + ("V_LSHLREV_B32", "ENC_VOP2", vec![("VDST", 30), ("SRC0", 130), ("VSRC1", 0)], None), + ("V_AND_B32", "ENC_VOP2", vec![("VDST", 30), ("SRC0", 255), ("VSRC1", 30)], Some(0x3FFFC)), + ("V_LSHRREV_B32", "ENC_VOP2", vec![("VDST", 31), ("SRC0", 144), ("VSRC1", 0)], None), + ("V_LSHLREV_B32", "ENC_VOP2", vec![("VDST", 31), ("SRC0", 130), ("VSRC1", 31)], None), + ("V_LSHLREV_B32", "ENC_VOP2", vec![("VDST", 32), ("SRC0", 130), ("VSRC1", 1)], None), + ("DS_READ2_B32", "ENC_DS", vec![("VDST", 40), ("ADDR", 30), ("OFFSET0", 0), ("OFFSET1", 1)], None), + ("DS_READ2_B32", "ENC_DS", vec![("VDST", 42), ("ADDR", 31), ("OFFSET0", 0), ("OFFSET1", 1)], None), + ("DS_READ2_B32", "ENC_DS", vec![("VDST", 44), ("ADDR", 32), ("OFFSET0", 0), ("OFFSET1", 1)], None), + ]; + for (d, a, b) in [(46u64, 42u64, 44u64), (47, 43, 45)] { + gs.push(("V_ADD_F32", "ENC_VOP2", vec![("VDST", d), ("SRC0", V + a), ("VSRC1", b)], None)); + gs.push(("V_SUB_F32", "ENC_VOP2", vec![("VDST", d), ("SRC0", V + d), ("VSRC1", d - 6)], None)); // − x0 / − y0 + } + // output base: s2 + lane · (4 vertices · 32 bytes) + gs.push(("V_MAD_U32_U24", "ENC_VOP3", vec![("VDST", 50), ("SRC0", V + 20), ("SRC1", 255), ("SRC2", 2)], Some(128))); + gs.push(("V_MOV_B32", "ENC_VOP1", vec![("VDST", 51), ("SRC0", 240)], None)); // 0.5 + gs.push(("V_MOV_B32", "ENC_VOP1", vec![("VDST", 52), ("SRC0", 242)], None)); // 1.0 + for (k, (x, y)) in [(40u64, 41u64), (42, 43), (44, 45), (46, 47)].into_iter().enumerate() { + let o = 8 * k as u64; + gs.push(("DS_WRITE2_B32", "ENC_DS", vec![("ADDR", 50), ("DATA0", x), ("DATA1", y), ("OFFSET0", o), ("OFFSET1", o + 1)], None)); + gs.push(("DS_WRITE2_B32", "ENC_DS", vec![("ADDR", 50), ("DATA0", 51), ("DATA1", 52), ("OFFSET0", o + 2), ("OFFSET1", o + 3)], None)); + gs.push(("V_MOV_B32", "ENC_VOP1", vec![("VDST", 53), ("SRC0", 128 + k as u64)], None)); + gs.push(("DS_WRITE2_B32", "ENC_DS", vec![("ADDR", 50), ("DATA0", 2), ("DATA1", 53), ("OFFSET0", o + 4), ("OFFSET1", o + 5)], None)); + gs.push(("S_SENDMSG", "ENC_SOPP", vec![("SIMM16", 0x22)], None)); // emit + } + gs.push(("S_SENDMSG", "ENC_SOPP", vec![("SIMM16", 0x12)], None)); // cut + gs.push(("S_SENDMSG", "ENC_SOPP", vec![("SIMM16", 0x3)], None)); // GS done + let gs = prog(&gs, true); + let vs_blob = console(1, 2, &es, &signature(&[("POSITION", 0, 0, 3, 0)]), &signature(&[("SV_Position", 0, 1, 3, 0), ("TEXCOORD", 0, 0, 3, 1)]), None); + let mut r = [0u8; 48]; + r[0..4].copy_from_slice(&3u32.to_le_bytes()); // triangles in + r[4..8].copy_from_slice(&5u32.to_le_bytes()); // triangle strip out + r[24] = 2; // geometry + r[26..28].copy_from_slice(&4u16.to_le_bytes()); // max vertex count + let gs_blob = console(2, 3, &gs, &signature(&[]), &signature(&[("SV_Position", 0, 1, 3, 0), ("TEXCOORD", 0, 0, 1, 1)]), Some(psv0(&r))); + let ps = dxc::compile("struct V { float4 pos : SV_Position; nointerpolation uint4 p0 : TEXCOORD0; };\nfloat4 main(V v) : SV_Target0 { return float4(1.0, (float)v.p0.x, (float)v.p0.y, 1.0); }\n", "main", "ps_6_6", &[]).unwrap(); + + unsafe { + let code = |b: &[u8]| D3D12_SHADER_BYTECODE { pShaderBytecode: b.as_ptr() as _, BytecodeLength: b.len() }; + let elems = [D3D12_INPUT_ELEMENT_DESC { + SemanticName: windows::core::s!("POSITION"), + Format: DXGI_FORMAT_R32G32B32_FLOAT, + AlignedByteOffset: 0, + InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + ..Default::default() + }]; + let mut d = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + VS: code(&vs_blob), + GS: code(&gs_blob), + PS: code(&ps), + SampleMask: u32::MAX, + InputLayout: D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: elems.as_ptr(), NumElements: 1 }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + d.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + d.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + d.RasterizerState.DepthClipEnable = true.into(); + d.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + d.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + let pso: ID3D12PipelineState = dev.CreateGraphicsPipelineState(&d).unwrap_or_else(|e| panic!("{e}: {:?}", real::stats().translation_errors)); + let real_pso = super::pso_async::resolve_wait(pso.as_raw() as usize); + let tp = real::two_pass_of(real_pso).unwrap_or_else(|| panic!("no two-pass parts: {:?}", real::stats().translation_errors)); + assert_eq!(tp.kind, "GS"); + assert!(matches!(&tp.fetch, Some(Ok(f)) if f.registers == 1 && f.slots == [0] && f.missing.is_empty()), "vertex fetch: {:?}", tp.fetch.as_ref().map(|r| r.as_ref().map(|f| (f.registers, f.slots.clone())).map_err(|e| e.clone()))); + + // two triangles (xyz, 12-byte stride) in title memory, then 16-bit indices 3, 4, 5 + let tris: [[[f32; 2]; 3]; 2] = [[[-0.9, -0.9], [-0.5, -0.9], [-0.9, -0.5]], [[0.1, 0.1], [0.5, 0.1], [0.1, 0.5]]]; + let u = crate::gpu::uma::get().unwrap(); + let vb = u.alloc(1 << 16, 1 << 16).unwrap() as usize; + for (k, v) in tris.iter().flatten().enumerate() { + std::ptr::copy_nonoverlapping([v[0], v[1], 0.5f32].as_ptr(), (vb as *mut f32).add(3 * k), 3); + } + let ib = vb + 0x1000; + std::ptr::copy_nonoverlapping([3u16, 4, 5].as_ptr(), (ib + 2) as *mut u16, 3); // at an odd 2-byte offset + + let draw = |indexed: bool| -> Vec<[f32; 4]> { + let t = Target::new(&dev); + bind::set_pipeline_state(t.backing, pso.as_raw()); + list_x::ia_set_topology_x(t.backing, windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32); + let view = D3D12_VERTEX_BUFFER_VIEW { BufferLocation: vb as u64, SizeInBytes: 6 * 12, StrideInBytes: 12 }; + list_x::ia_set_vertex_buffers_x(t.backing, 0, 1, &view); + let before = bind::counts_snapshot(); + if indexed { + let iv = D3D12_INDEX_BUFFER_VIEW { BufferLocation: (ib + 2) as u64, SizeInBytes: 6, Format: DXGI_FORMAT_R16_UINT }; + list_x::ia_set_index_buffer_x(t.backing, &iv); + bind::draw_indexed_instanced(t.backing, 3, 1, 0, 0, 0); + } else { + bind::draw_instanced(t.backing, 6, 1, 0, 0); + } + let after = bind::counts_snapshot(); + assert!(after[0] > before[0], "a translated draw"); + t.finish() + }; + // the parallelogram of triangle (a, b, c): a, b, c, b + c − a + let quad = |t: [[f32; 2]; 3]| -> [[[f32; 2]; 3]; 2] { + let d = [t[1][0] + t[2][0] - t[0][0], t[1][1] + t[2][1] - t[0][1]]; + [[t[0], t[1], t[2]], [t[2], t[1], d]] + }; + let check = |px: &[[f32; 4]], drawn: &[(usize, [[f32; 2]; 3])]| { + let (mut hit, mut clear) = (vec![0usize; drawn.len()], 0usize); + for y in 0..SIZE as usize { + for x in 0..SIZE as usize { + let p = px[y * SIZE as usize + x]; + let mut near = false; + for (k, (prim, t)) in drawn.iter().enumerate() { + let q = quad(*t); + if q.iter().any(|h| inside(*h, x, y, 0.02)) { + assert_eq!((p[0], p[1], p[3]), (1.0, *prim as f32, 1.0), "pixel ({x},{y}) in primitive {prim}'s parallelogram: {p:?}"); + hit[k] += 1; + } + near |= q.iter().any(|h| inside(*h, x, y, -0.05)); + } + if !near { + assert_eq!(p, CLEAR, "pixel ({x},{y}) outside every parallelogram"); + clear += 1; + } + } + } + println!("two-pass GS draw: {hit:?} pixels in the parallelograms, {clear} clear"); + assert!(hit.iter().all(|&h| h > 10) && clear > 400, "{hit:?} / {clear}"); + }; + check(&draw(false), &[(0, tris[0]), (1, tris[1])]); + // indexed: one triangle, primitive 0 of the draw, from vertices 3..5 + check(&draw(true), &[(0, tris[1])]); + u.free(vb); + } +}