From 2624f00c4e2d8b87aa1828233fb2f60899eb9533 Mon Sep 17 00:00:00 2001 From: Logan Date: Mon, 23 Nov 2026 22:59:54 -0500 Subject: [PATCH] D3D12.X: execute two-pass mesh shaders on DispatchMesh and ExecuteIndirect Console mesh shaders translated to a two-pass pair (compute + mesh/PS, TwoPassPso) were built by CreatePipelineState but had no execution path: DispatchMesh was not hooked on the console command list vtable, and ExecuteIndirect did not dispatch the compute pass or bind the record buffer (u1) before invoking the mesh pass. Hook DispatchMesh (slot 127, newer layout slot 129) and handle TwoPassPso in ExecuteIndirect: - Track console mesh root-argument layout (s[8:9] spill table, inline arguments from s16 across 16 SGPRs) in console_list::user_data_ms. - Create a companion DISPATCH command signature alongside non-root-changing DISPATCH_MESH command signatures in device_x::create_command_signature_x. - Allocate/recycle a DEFAULT-heap UAV record buffer per command list (recycled on allocator reset), bind u0 (io), u1 (res), u2..u5 (UMA), run the compute pass -> UAV barrier -> mesh pass -> UAV barrier, and scale indirect DispatchMesh group counts on the GPU when mesh_groups_per_record > 1. Assisted-by: Antigravity (Gemini 4 Neon) --- crates/xcl/src/hle/d3d12x/bind.rs | 387 +++++++++++++++++++++- crates/xcl/src/hle/d3d12x/console_list.rs | 38 ++- crates/xcl/src/hle/d3d12x/device_x.rs | 31 +- crates/xcl/src/hle/d3d12x/real.rs | 15 +- 4 files changed, 462 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index d68197e4aa..e23246c0dc 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -34,6 +34,28 @@ struct State { uma: Vec, /// where the next draw's io and argument table go (blocks in `uma`) arena: crate::gpu::uma::Arena, + res_buf: Option<(ID3D12Resource, u64, usize)>, + res_retired: Vec<(ID3D12Resource, u64, usize)>, +} + +static ALLOC_RES: Mutex>>> = Mutex::new(None); +static FREE_RES: Mutex> = Mutex::new(Vec::new()); + +fn hold_res_until_reset(allocator: usize, mut bufs: Vec<(ID3D12Resource, u64, usize)>) { + if bufs.is_empty() || allocator == 0 { + return; + } + ALLOC_RES.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().append(&mut bufs); +} + +pub(super) fn release_allocator_res(allocator: usize) { + let Some(bufs) = ALLOC_RES.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)) else { return }; + let mut free = FREE_RES.lock().unwrap(); + for b in bufs { + if free.len() < 16 { + free.push(b); + } + } } static STATES: Mutex>> = Mutex::new(None); @@ -73,7 +95,7 @@ fn with(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R { /// recording's memory is the previous allocator's until that one is reset, and pipeline /// and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics. pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { - let (old, blocks) = with(list, |s| { + let (old, blocks, res_bufs) = with(list, |s| { let old = std::mem::replace(&mut s.allocator, allocator); s.arena = Default::default(); s.pso = initial_pso; @@ -82,9 +104,14 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; - (old, std::mem::take(&mut s.uma)) + let mut res_bufs = std::mem::take(&mut s.res_retired); + if let Some(b) = s.res_buf.take() { + res_bufs.push(b); + } + (old, std::mem::take(&mut s.uma), res_bufs) }); console_list::hold_until_reset(old, blocks); + hold_res_until_reset(old, res_bufs); } /// `ClearState(pso)`: resets pipeline and root-argument state back to creation defaults @@ -102,8 +129,12 @@ pub(super) fn clear_state(list: *mut c_void, pso: usize) { /// The list is gone. pub(super) fn forget(list: *mut c_void) { - if let Some(s) = STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))) { + if let Some(mut s) = STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))) { console_list::hold_until_reset(s.allocator, s.uma); + if let Some(b) = s.res_buf.take() { + s.res_retired.push(b); + } + hold_res_until_reset(s.allocator, s.res_retired); } } @@ -204,19 +235,351 @@ fn note_address(va: u64) { /// command signatures that change root arguments (they need the title's root signature) static ROOT_SIGNATURES: Mutex>> = Mutex::new(None); +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct DispatchMeshSig { + companion_dispatch: usize, + byte_stride: u32, + mesh_offset: u32, +} + +static DISPATCH_MESH_SIGS: Mutex>> = Mutex::new(None); + pub(super) fn note_root_changing_signature(sig: usize) { ROOT_SIGNATURES.lock().unwrap().get_or_insert_with(Default::default).insert(sig); } +pub(super) fn note_dispatch_mesh_signature(sig: usize, companion_dispatch: usize, byte_stride: u32, mesh_offset: u32) { + DISPATCH_MESH_SIGS + .lock() + .unwrap() + .get_or_insert_with(HashMap::new) + .insert(sig, DispatchMeshSig { companion_dispatch, byte_stride, mesh_offset }); +} + +fn dispatch_mesh_sig_of(sig: usize) -> Option { + DISPATCH_MESH_SIGS.lock().unwrap().as_ref()?.get(&sig).copied() +} + +unsafe fn emit_uav_barrier(list: &ID3D12GraphicsCommandList, res: Option<&ID3D12Resource>) { + let mut b = 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(res.cloned()), + }), + }, + }; + list.ResourceBarrier(&[std::ptr::read(&b)]); + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.UAV).pResource); +} + +unsafe fn emit_transition(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { + let mut b = 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::ManuallyDrop::new(Some(res.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + }; + list.ResourceBarrier(&[std::ptr::read(&b)]); + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.Transition).pResource); +} + +unsafe fn default_uav_buffer(dev: &ID3D12Device, bytes: u64, what: &str) -> Result { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + }; + let mut res: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut res, + ) + .map_err(|e| format!("{what} ({bytes:#x} B): {e}"))?; + res.ok_or_else(|| format!("null {what}")) +} + +unsafe fn ensure_res_buffer(this: *mut c_void, need_bytes: u64) -> Result<(ID3D12Resource, u64), String> { + let need = need_bytes.max(4 << 20).next_multiple_of(1 << 20).min(128 << 20); + if let Some((buf, _cap, _dev)) = with(this, |s| s.res_buf.as_ref().filter(|(_, cap, _)| *cap >= need).cloned()) { + let va = buf.GetGPUVirtualAddress(); + return Ok((buf, va)); + } + let dev = super::real::list_device(this).ok_or("no device for two-pass buffer")?; + let dev_key = dev.as_raw() as usize; + let picked = { + let mut free = FREE_RES.lock().unwrap(); + free.iter().position(|(_, cap, d)| *d == dev_key && *cap >= need).map(|i| free.swap_remove(i)) + }; + let entry = match picked { + Some(e) => e, + None => (default_uav_buffer(&dev, need, "two-pass res buffer")?, need, dev_key), + }; + let buf = entry.0.clone(); + let va = buf.GetGPUVirtualAddress(); + with(this, |s| { + if let Some(old) = s.res_buf.replace(entry) { + s.res_retired.push(old); + } + }); + Ok((buf, va)) +} + +unsafe fn bind_two_pass_stage( + this: *mut c_void, + list: &ID3D12GraphicsCommandList, + real_mesh_pso: usize, + tp: &super::real::TwoPassPso, + res_va: u64, + compute_pass: bool, +) -> 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")?; + let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); + let copy = |bytes: &[u8]| -> Result { + let p = with(this, |s| s.arena.take(u, bytes.len().max(16), 256, &mut s.uma)).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); + Ok(p as usize) + }; + let inline = layout + .as_ref() + .map_or(0, |l| if compute_pass { l.inline_ms } else { l.inline_gfx } as usize) + .min(args.len()); + let table_at = copy(&args[inline..])?; + let mut io = match layout.as_ref() { + Some(l) if compute_pass => console_list::user_data_ms(l, &args, table_at as u64), + Some(l) => console_list::user_data_gfx(l, &args, table_at as u64), + None if compute_pass => { + let mut v = vec![0u32; 16]; + v[8] = table_at as u32; + v[9] = (table_at >> 32) as u32; + v + } + None => vec![table_at as u32, (table_at >> 32) as u32], + }; + io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); + 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_raw = if compute_pass { tp.compute_rs } else { tp.mesh_rs } as *mut c_void; + let rs = ID3D12RootSignature::from_raw_borrowed(&rs_raw).ok_or("two-pass root signature")?; + let views = [va(io_at), res_va].into_iter().chain((0..4).map(|k| windows.get(k).copied().unwrap_or(first))); + if compute_pass { + list.SetComputeRootSignature(rs); + for (k, v) in views.enumerate() { + list.SetComputeRootUnorderedAccessView(k as u32, v); + } + let pso_raw = tp.compute as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&pso_raw).ok_or("two-pass compute pipeline")?; + list.SetPipelineState(pc); + } else { + list.SetGraphicsRootSignature(rs); + for (k, v) in views.enumerate() { + list.SetGraphicsRootUnorderedAccessView(k as u32, v); + } + let pso_raw = real_mesh_pso as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&pso_raw).ok_or("two-pass mesh pipeline")?; + list.SetPipelineState(pc); + } + Ok(()) +} + +unsafe fn scale_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: Mutex>> = Mutex::new(None); + let key = dev.as_raw() as usize; + if let Some(pair) = CACHE.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { + return Ok(pair); + } + let hlsl = "cbuffer C : register(b0) { uint count; uint stride; uint offset; uint mult; };\nByteAddressBuffer src : register(t0);\nRWByteAddressBuffer dst : register(u0);\n[numthreads(64, 1, 1)]\nvoid main(uint tid : SV_DispatchThreadID) {\n if (tid >= count) return;\n uint base = tid * stride;\n uint dwords = stride / 4u;\n for (uint i = 0u; i < dwords; ++i) {\n uint w = src.Load(base + i * 4u);\n if (i * 4u == offset) w = w * mult;\n dst.Store(base + i * 4u, w);\n }\n}\n"; + let dxil = crate::gpu::recomp::dxc::compile_cached(hlsl, "main", "cs_6_6")?.0; + let params = [ + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 4 }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: 0, RegisterSpace: 0 }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }, + 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() + }; + let mut blob = None; + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None).map_err(|e| format!("scale rs serialize: {e}"))?; + let blob = blob.ok_or("scale rs blob")?; + let rs: ID3D12RootSignature = dev + .CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())) + .map_err(|e| format!("scale rs create: {e}"))?; + let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as *const c_void, BytecodeLength: dxil.len() }, + ..Default::default() + }; + let res_pso: Result = dev.CreateComputePipelineState(&cdesc); + std::mem::ManuallyDrop::drop(&mut cdesc.pRootSignature); + let pso = res_pso.map_err(|e| format!("scale pso create: {e}"))?; + CACHE.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, (rs.clone(), pso.clone())); + Ok((rs, pso)) +} + +unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsCommandList, src_raw: usize, src_off: u64, max: u32, stride: u32, mesh_offset: u32, mult: u32) -> Result { + let dev = super::real::list_device(this).ok_or("no device")?; + let (rs, pso) = scale_indirect_pipeline(&dev)?; + let src_ptr = src_raw as *mut c_void; + let src = ID3D12Resource::from_raw_borrowed(&src_ptr).ok_or("indirect args buffer")?; + let bytes = (max as u64).saturating_mul(stride as u64).max(256).next_multiple_of(256); + let dst = default_uav_buffer(&dev, bytes, "scaled args buffer")?; + emit_transition(list, src, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + let consts = [max, stride, mesh_offset, mult]; + list.SetComputeRoot32BitConstants(0, 4, consts.as_ptr() as *const c_void, 0); + list.SetComputeRootShaderResourceView(1, src.GetGPUVirtualAddress() + src_off); + list.SetComputeRootUnorderedAccessView(2, dst.GetGPUVirtualAddress()); + list.Dispatch(max.div_ceil(64), 1, 1); + emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + emit_transition(list, src, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + let dev_key = dev.as_raw() as usize; + with(this, |s| s.res_retired.push((dst.clone(), bytes, dev_key))); + Ok(dst) +} + +pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: u32, z: u32) { + type PcDm = unsafe extern "system" fn(*mut c_void, u32, u32, u32); + let pc_dm: PcDm = std::mem::transmute(super::real::orig_fn(this, 79)); + let raw_pso = with(this, |s| s.pso); + let pso = super::pso_async::resolve_wait(raw_pso); + if let Some(tp) = super::real::two_pass_of(pso) { + let groups = x.saturating_mul(y.max(1)).saturating_mul(z.max(1)); + if groups == 0 { + return; + } + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + let need = (groups as u64).saturating_mul(tp.record.record_dwords() as u64).saturating_mul(4); + let run = (|| -> Result<(), String> { + let (res_buf, res_va) = ensure_res_buffer(this, need)?; + bind_two_pass_stage(this, list, pso, &tp, res_va, true)?; + list.Dispatch(groups, 1, 1); + emit_uav_barrier(list, Some(&res_buf)); + bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; + pc_dm(this, groups.saturating_mul(tp.mesh_groups_per_record), 1, 1); + emit_uav_barrier(list, Some(&res_buf)); + Ok(()) + })(); + match run { + Ok(()) => { + count(DRAWS); + static LOGGED: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: two-pass DispatchMesh #{n} ({groups} groups, split {}, kind {})", tp.mesh_groups_per_record, tp.kind); + } + } + Err(e) => { + count(DRAWS_SKIPPED); + 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: two-pass DispatchMesh skipped: {e}"); + } + } + } + return; + } + if super::pso_async::is_pending(raw_pso) { + count(DRAWS_SKIPPED); + return; + } + let rs = with(this, |s| s.rs_gfx) as *mut c_void; + if let (Some(list), Some(r)) = (ID3D12GraphicsCommandList::from_raw_borrowed(&this), ID3D12RootSignature::from_raw_borrowed(&rs)) { + list.SetGraphicsRootSignature(r); + } + count(DRAWS_PC); + pc_dm(this, x, y, z); +} + /// #59 ExecuteIndirect(signature, max count, arguments, offset, count buffer, offset): with a /// translated pipeline, on XCL's ABI with the kept root arguments (signatures that change root /// arguments themselves cannot be – skipped, logged) pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) { type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); - 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 raw_pso = with(this, |s| s.pso); + let pso = super::pso_async::resolve_wait(raw_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) { + if let Some(msig) = dispatch_mesh_sig_of(sig) { + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + let run = (|| -> Result<(), String> { + let (res_buf, res_va) = ensure_res_buffer(this, 32 << 20)?; + bind_two_pass_stage(this, list, pso, &tp, res_va, true)?; + pc(this, msig.companion_dispatch, max, args, args_off, count_buf, count_off); + emit_uav_barrier(list, Some(&res_buf)); + if tp.mesh_groups_per_record > 1 && max > 0 && args != 0 { + let scaled = make_scaled_args_buffer(this, list, args, args_off, max, msig.byte_stride, msig.mesh_offset, tp.mesh_groups_per_record)?; + bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; + pc(this, sig, max, scaled.as_raw() as usize, 0, count_buf, count_off); + } else { + bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; + pc(this, sig, max, args, args_off, count_buf, count_off); + } + emit_uav_barrier(list, Some(&res_buf)); + Ok(()) + })(); + match run { + Ok(()) => { + count(DRAWS); + static LOGGED: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: two-pass ExecuteIndirect(DispatchMesh) #{n} (max {max}, split {}, kind {})", tp.mesh_groups_per_record, tp.kind); + } + } + Err(e) => { + count(DRAWS_SKIPPED); + 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: two-pass ExecuteIndirect skipped: {e}"); + } + } + } + return; + } + } + let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); if !gfx && !compute { // A pipeline still being built (or whose build failed): its stand-in draws nothing, and // the list may hold XCL's ABI root signature from a translated draw before it – the PC @@ -1258,4 +1621,18 @@ mod tests { let _ = pso_async::released(standin); } } + + #[test] + fn dispatch_mesh_signature_tracking_returns_companion_and_layout() { + let sig = 0x7400_0001usize; + let companion = 0x7400_0002usize; + assert_eq!(dispatch_mesh_sig_of(sig), None); + note_dispatch_mesh_signature(sig, companion, 28, 16); + assert_eq!( + dispatch_mesh_sig_of(sig), + Some(DispatchMeshSig { companion_dispatch: companion, byte_stride: 28, mesh_offset: 16 }) + ); + DISPATCH_MESH_SIGS.lock().unwrap().as_mut().unwrap().remove(&sig); + assert_eq!(dispatch_mesh_sig_of(sig), None); + } } diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 95568747fb..997f0c3e33 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -74,6 +74,7 @@ pub struct Layout { pub size: u32, pub inline: u32, pub inline_gfx: u32, + pub inline_ms: u32, } /// User SGPRs the console's compiler gives root arguments: compute s4…s15 (s0…s3 are the @@ -81,8 +82,10 @@ pub struct Layout { /// fetch shader) – both measured on its output (`tests/console_shaders.rs`). const INLINE_SGPRS: u32 = 12; const INLINE_SGPRS_GFX: u32 = 24; +const INLINE_SGPRS_MS: u32 = 16; const FIRST_SGPR: usize = 4; const FIRST_SGPR_GFX: usize = 8; +const FIRST_SGPR_MS: usize = 16; /// Layout from a serialized root signature: a DXBC container with RTS0 or a bare RTS0. pub fn layout_from_blob(blob: &[u8]) -> Option { @@ -99,7 +102,7 @@ pub fn layout_from_blob(blob: &[u8]) -> Option { // the parameters go into user SGPRs in order while each fits whole; from the first one // that does not, the rest go to the table (packed from its start) – as the console's // compiler expects them (HANDOFF: root argument binding) - let (mut spilled, mut spilled_gfx) = (false, false); + let (mut spilled, mut spilled_gfx, mut spilled_ms) = (false, false, false); for k in 0..n { let (ty, pay) = (r(poff + 12 * k)?, r(poff + 12 * k + 8)? as usize); let p = match ty { @@ -120,6 +123,10 @@ pub fn layout_from_blob(blob: &[u8]) -> Option { if !spilled_gfx { l.inline_gfx += bytes; } + spilled_ms |= l.inline_ms + bytes > 4 * INLINE_SGPRS_MS; + if !spilled_ms { + l.inline_ms += bytes; + } l.size += bytes; l.params.push(p); } @@ -163,6 +170,19 @@ pub fn user_data_gfx(l: &Layout, args: &[u8], table_at: u64) -> Vec { sgprs(FIRST_SGPR_GFX, l.inline_gfx, args, table_at) } +pub fn user_data_ms(l: &Layout, args: &[u8], table_at: u64) -> Vec { + let mut s = vec![0u32; FIRST_SGPR_MS]; + s[8] = table_at as u32; + s[9] = (table_at >> 32) as u32; + let inline = &args[..(l.inline_ms as usize).min(args.len())]; + s.extend(inline.chunks(4).map(|c| { + let mut w = [0u8; 4]; + w[..c.len()].copy_from_slice(c); + u32::from_le_bytes(w) + })); + s +} + fn sgprs(first: usize, inline: u32, args: &[u8], table_at: u64) -> Vec { let mut s = vec![0u32; first]; s[0] = table_at as u32; @@ -324,6 +344,7 @@ pub fn allocator_reset(allocator: *mut c_void) { if let Some(b) = blocks { unsafe { free_uma(&b) }; } + super::bind::release_allocator_res(allocator as usize); } fn with_list(obj: usize, f: impl FnOnce(&mut ListState) -> R) -> Option { @@ -987,4 +1008,19 @@ mod tests { let args: Vec = [1u32, 2, 0x5000, 4, 0x80].iter().flat_map(|w| w.to_le_bytes()).collect(); assert_eq!(user_data_gfx(&l, &args, 0x200), vec![0x200, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0x5000, 4, 0x80]); } + + #[test] + fn mesh_arguments_go_in_user_sgprs_from_s16() { + let inline = |p: &[(u32, u32)]| layout_from_blob(&rts0(p)).unwrap().inline_ms; + assert_eq!(inline(&[(1, 2), (2, 0), (0, 0)]), 20); + assert_eq!(inline(&[(1, 14), (2, 0)]), 64); + assert_eq!(inline(&[(1, 15), (2, 0)]), 60); + assert_eq!(inline(&[(1, 17), (2, 0)]), 0); + let l = layout_from_blob(&rts0(&[(1, 2), (2, 0), (0, 0)])).unwrap(); + let args: Vec = [1u32, 2, 0x5000, 4, 0x80].iter().flat_map(|w| w.to_le_bytes()).collect(); + let got = user_data_ms(&l, &args, 0x7_0000_0200); + assert_eq!(got[8], 0x200); + assert_eq!(got[9], 7); + assert_eq!(&got[16..], &[1, 2, 0x5000, 4, 0x80]); + } } diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 2af03a02d5..5814218d24 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -998,6 +998,19 @@ pub(super) unsafe extern "system" fn get_copyable_footprints_x( /// device #41 CreateCommandSignature(desc, root signature, riid, signature): the console's /// DispatchX argument (105) is a PC Dispatch; the root signature only goes with arguments /// that need one (constants, CBV / SRV / UAV) +fn indirect_arg_bytes(arg: &[u32; 4]) -> u32 { + match arg[0] { + 0 => 16, + 1 => 20, + 2 | 10 => 12, + 3 | 4 => 16, + 5 => arg[3].saturating_mul(4), + 6..=8 => 8, + 9 => 108, + _ => 0, + } +} + pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_void, desc: *const u8, root: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { if desc.is_null() || ppv.is_null() { return E_INVALIDARG; @@ -1015,8 +1028,22 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi let needs_root = list.iter().any(|a| (5..=8).contains(&a[0])); pc[8..16].copy_from_slice(&(if list.is_empty() { 0 } else { list.as_ptr() as u64 }).to_le_bytes()); let hr = real::dev_create_command_signature(this, pc.as_ptr() as usize, if needs_root { root } else { 0 }, riid, ppv); - if hr >= 0 && !ppv.is_null() && needs_root { - super::bind::note_root_changing_signature(*ppv as usize); + if hr >= 0 && !ppv.is_null() { + if needs_root { + super::bind::note_root_changing_signature(*ppv as usize); + } else if let Some(idx) = list.iter().position(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH.0 as u32) { + let offset: u32 = list[..idx].iter().map(indirect_arg_bytes).sum(); + let byte_stride = u32::from_le_bytes(pc[0..4].try_into().unwrap()); + let mut dispatch_list = list.clone(); + dispatch_list[idx][0] = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32; + let mut dpc = pc; + dpc[8..16].copy_from_slice(&(dispatch_list.as_ptr() as u64).to_le_bytes()); + let mut companion: *mut c_void = std::ptr::null_mut(); + let hr2 = real::dev_create_command_signature(this, dpc.as_ptr() as usize, 0, riid, &mut companion); + if hr2 >= 0 && !companion.is_null() { + super::bind::note_dispatch_mesh_signature(*ppv as usize, companion as usize, byte_stride, offset); + } + } } hr } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index aed907586c..d4fd049c6a 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1021,6 +1021,7 @@ 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), + (127, 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), @@ -4867,7 +4868,19 @@ 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)]; +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), (129, 127), (139, 10)]; + +pub(super) unsafe fn list_device(list: *mut c_void) -> Option { + type F = unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(list, 7)); + let iid = pc_iid(Kind::Device); + let mut raw: *mut c_void = std::ptr::null_mut(); + if f(list, &iid, &mut raw) >= 0 && !raw.is_null() { + Some(ID3D12Device::from_raw(raw)) + } else { + None + } +} /// 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).