diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 3f31c48b43..a2747462ce 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -259,6 +259,25 @@ pub(super) fn note_signature_dispatches(sig: usize, dispatches: bool) { } } +/// command signatures whose arguments only draw (Draw, DrawIndexed, DispatchMesh): an +/// ExecuteIndirect of one leaves no state behind, so it can be recorded at the submit (noted at +/// every creation, as `DISPATCH_SIGNATURES`) +static DRAW_ONLY_SIGNATURES: Mutex>> = Mutex::new(None); + +pub(super) fn note_signature_draws_only(sig: usize, draws_only: bool) { + let mut s = DRAW_ONLY_SIGNATURES.lock().unwrap(); + let s = s.get_or_insert_with(Default::default); + if draws_only { + s.insert(sig); + } else { + s.remove(&sig); + } +} + +fn signature_draws_only(sig: usize) -> bool { + DRAW_ONLY_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) +} + fn signature_dispatches(sig: usize) -> bool { DISPATCH_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) } @@ -270,8 +289,13 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us 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 raw_pso = with(this, |s| s.pso); - let unbuilt_compute = signature_dispatches(sig) && super::pso_async::is_pending(raw_pso) && super::real::is_console_compute(raw_pso); - if unbuilt_compute && super::list_x::defer(this, super::list_x::Deferred::Indirect(sig, max, args, args_off, count_buf, count_off)) { + let pending = super::pso_async::is_pending(raw_pso); + let unbuilt_compute = signature_dispatches(sig) && pending && super::real::is_console_compute(raw_pso); + // a graphics one too: the title's thread goes on to its next binds, whose builds then run on + // the workers at once instead of one after another here (only a signature that just draws: + // vertex / index buffer views and root arguments it sets would stay on the list after it) + let unbuilt_graphics = signature_draws_only(sig) && pending && !super::real::is_console_compute(raw_pso); + if (unbuilt_compute || unbuilt_graphics) && super::list_x::defer(this, super::list_x::Deferred::Indirect(sig, max, args, args_off, count_buf, count_off)) { return super::pso_async::need_by_submit(raw_pso); } let pso = super::pso_async::resolve_wait(raw_pso); @@ -1073,7 +1097,7 @@ pub(super) fn counts_snapshot() -> [u64; 5] { std::array::from_fn(|k| COUNTS[k].load(Ordering::Relaxed)) } -#[cfg(test)] +/// The pipeline `list` has bound (as the title made it; 0: none). pub(super) fn tracked_pso(list: *mut c_void) -> usize { STATES .lock() diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 57c30e0ffe..77c9874efd 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1259,6 +1259,8 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi } if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { super::bind::note_signature_dispatches(*ppv as usize, list.iter().any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32)); + let draws = [D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED, D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH].map(|t| t.0 as u32); + super::bind::note_signature_draws_only(*ppv as usize, !list.is_empty() && list.iter().all(|a| draws.contains(&a[0]))); } hr } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..5a98fb864b 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -31,6 +31,10 @@ use windows::Win32::Graphics::Dxgi::Common::*; use super::device_x::{self, DepthBias}; use super::real; +#[cfg(test)] +#[path = "list_x_render_targets_tests.rs"] +mod render_target_tests; + const PC_GET_TYPE: usize = 8; const PC_CLOSE: usize = 9; const PC_RESET: usize = 10; @@ -336,6 +340,7 @@ struct Bindings { stencil: Option, vertex_buffers: std::collections::BTreeMap, render_targets: Option, + render_target_copies: Vec, /// slot → the title's (address, bytes, stride) of the vertex buffer (`XCL_TRACE_FRAME`) vertex_titles: std::collections::BTreeMap, /// the title's (address, bytes, format) of the index buffer (`XCL_TRACE_FRAME`) @@ -607,6 +612,45 @@ unsafe fn restore_bindings(this: *mut c_void, b: &Bindings, ty: D3D12_COMMAND_LI } } +/// The rest of a direct list's state a PC Reset clears, on `list` (a segment going on from +/// another): depth bias for `bound_pso`, index buffer, depth bounds. +unsafe fn restore_direct(list: *mut c_void, dev_raw: usize, bound_pso: usize, depth_bias: Option, index_buffer: Option, depth_bounds: Option<(f32, f32)>) { + let info = if bound_pso != 0 { device_x::base_depth_bias_info(bound_pso) } else { None }; + let mut applied_native = false; + if let Some((true, static_bias)) = info { + let target = depth_bias.unwrap_or(static_bias); + if target.is_zero() { + applied_native = true; + } else if try_native_depth_bias(list, target) { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.native_bias = target; + } + applied_native = true; + } + } else if bound_pso == 0 { + if let Some(b) = depth_bias { + if device_x::dynamic_depth_bias_supported(dev_raw as *mut c_void) && try_native_depth_bias(list, b) { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.native_bias = b; + } + applied_native = true; + } + } + } + if depth_bias.is_some() && !applied_native { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.pso_dirty = true; + } + DEPTH_BIAS_USED.store(true, Ordering::Release); + } + if let Some(ref view) = index_buffer { + set_index_buffer(list, Some(view)); + } + if let Some((min, max)) = depth_bounds { + pc::(list, PC_OM_SET_DEPTH_BOUNDS)(list, min, max); + } +} + #[derive(Default)] struct ListState { allocator: usize, @@ -649,13 +693,16 @@ struct ListState { predication: Option, /// state a PC Reset clears (restored after KickoffX) bindings: Bindings, + /// queries begun on this recording and not ended yet (all types but timestamps): a call is + /// not put off to a segment of its own meanwhile (Begin and End must be in one PC list) + queries_open: u32, /// what this segment records at the submit (`defer`) deferred: Option, /// on a title list's first segment: the allocator its deferred segments record on (the title's may be recording another list by the submit) own_alloc: Option, } -/// A `Dispatch` or a dispatching `ExecuteIndirect` put off to the submit, with its arguments. +/// A `Dispatch` or an `ExecuteIndirect` (dispatching or drawing) put off to the submit, with its arguments. pub(super) enum Deferred { Dispatch(u32, u32, u32), Indirect(usize, u32, usize, u64, usize, u64), @@ -2648,7 +2695,7 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { Some(next_pc) } -/// Gives a dispatch whose pipeline is still being built a segment of its own, recorded at the submit. +/// Gives a call whose pipeline is still being built a segment of its own, recorded at the submit. pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { if split(list, Some(what)).is_none() { return false; @@ -2656,7 +2703,7 @@ pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { static N: AtomicU64 = AtomicU64::new(0); let n = N.fetch_add(1, Ordering::Relaxed) + 1; if n <= 4 || n.is_power_of_two() { - crate::xlog_info!("D3D12.X: dispatch with a pipeline still being built put off to the submit (#{n})"); + crate::xlog_info!("D3D12.X: a call with a pipeline still being built put off to the submit (#{n})"); } true } @@ -2664,7 +2711,7 @@ pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { /// Builds of a submit's put-off calls that go on without the commit headroom, as a title thread's own do: about what the title's threads had in the driver at once before. const WANTED_AT_ONCE: usize = 4; -/// Records the deferred dispatches of `wrapper`'s recording, waiting for their pipelines as a bind did. +/// Records the put-off calls of `wrapper`'s recording, waiting for their pipelines as a bind did. pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { let mut segs = Vec::new(); super::title_list::push_segments(wrapper, &mut segs); @@ -2675,7 +2722,7 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { for &ahead in segs[i..].iter().take(WANTED_AT_ONCE) { super::bind::want_bound(ahead); } - let Some((what, ty, heaps)) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(seg as usize))).and_then(|s| Some((s.deferred.take()?, s.list_type?, s.bindings.heaps.clone()))) else { + let Some((what, ty, bindings, depth_bias, index_buffer, depth_bounds)) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(seg as usize))).and_then(|s| Some((s.deferred.take()?, s.list_type?, s.bindings.clone(), s.depth_bias, s.index_buffer, s.depth_bounds))) else { continue; }; let Some(own) = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(first as usize))?.own_alloc.clone()) else { @@ -2688,8 +2735,14 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { Some(_) => 0, None => super::alloc_pool::title_reset(own).unwrap_or_else(|| real::reset_pc_allocator(own)), }; + // a drawing ExecuteIndirect starts with the pipeline it was recorded with, waited for as a + // bind did: one whose build failed goes to the PC with the stand-in bound, as in its + // list (a dispatch binds its own pipeline or is skipped) + let bound_pso = super::bind::tracked_pso(seg); + let draws = matches!(what, Deferred::Indirect(..)) && !super::real::is_console_compute(bound_pso); + let init_pso = if draws { super::pso_async::resolve_wait(bound_pso) } else { 0 }; if hr >= 0 { - hr = super::alloc_pool::reset_list(seg as usize, own as usize, ty.0, |pc_alloc| pc:: i32>(seg, PC_RESET)(seg, pc_alloc, 0)); + hr = super::alloc_pool::reset_list(seg as usize, own as usize, ty.0, |pc_alloc| pc:: i32>(seg, PC_RESET)(seg, pc_alloc, init_pso)); } real::preserve_vtable(seg, ext); if hr < 0 { @@ -2699,8 +2752,9 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { continue; } reset_copy_scratch(seg); - if !heaps.is_empty() { - pc::(seg, 28)(seg, heaps.len() as u32, heaps.as_ptr()); + restore_bindings(seg, &bindings, ty); + if ty == D3D12_COMMAND_LIST_TYPE_DIRECT { + restore_direct(seg, device_of(seg).map_or(0, |d| d.as_raw() as usize), bound_pso, depth_bias, index_buffer, depth_bounds); } if let Some(last) = last { super::bind::pass_arena(last, seg); @@ -2729,6 +2783,37 @@ unsafe fn reset_own_alloc(list: *mut c_void) { } } +// A rewrite between OMSetRenderTargets and the draw is still read here; native copies at OMSet. +unsafe fn snapshot_render_targets(list: *mut c_void, b: &mut Bindings) -> Option<()> { + let Some(rt) = b.render_targets.as_mut() else { return Some(()) }; + let dev = device_of(list)?; + let mut copies = Vec::new(); + for (ty, count) in [(D3D12_DESCRIPTOR_HEAP_TYPE_RTV, rt.num_targets), (D3D12_DESCRIPTOR_HEAP_TYPE_DSV, rt.dsv.is_some() as u32)] { + if count == 0 { + continue; + } + let heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: ty, NumDescriptors: count, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, NodeMask: 0, + }).ok()?; + let base = heap.GetCPUDescriptorHandleForHeapStart(); + let step = dev.GetDescriptorHandleIncrementSize(ty) as usize; + for i in 0..count as usize { + let src = if ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV { rt.dsv? } + else if rt.single != 0 { rt.handles[0] + i * step } else { rt.handles[i] }; + dev.CopyDescriptorsSimple(1, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: base.ptr + i * step }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src }, ty); + } + if ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV { + rt.dsv = Some(base.ptr); + } else { + rt.handles = vec![base.ptr]; + rt.single = 1; + } + copies.push(heap); + } + b.render_target_copies = copies; + Some(()) +} + /// Ends `list`'s segment and opens the next; with `dispatch`, a closed segment for it comes between. unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_void> { let wrapper = super::title_list::wrapper_of(list)?; @@ -2739,10 +2824,16 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ if ty == D3D12_COMMAND_LIST_TYPE_BUNDLE { return None; } + let mut captured = if matches!(dispatch, Some(Deferred::Indirect(..))) && !super::real::is_console_compute(super::bind::tracked_pso(list)) { + let mut b = LISTS.lock().unwrap().as_ref()?.get(&(list as usize))?.bindings.clone(); + snapshot_render_targets(list, &mut b)?; + Some(b) + } else { None }; let deferred = match dispatch { Some(what) => { - // (a predicated call stays in its list) - let plain = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).is_some_and(|s| s.allocator != 0 && s.predication.is_none()); + // (a predicated call stays in its list, and one inside a query: put off, the query would + // not count it, and its Begin and End would be in different PC lists) + let plain = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).is_some_and(|s| s.allocator != 0 && s.predication.is_none() && s.queries_open == 0); if !plain { return None; } @@ -2750,7 +2841,7 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ } None => None, }; - let (alloc, last_queue, bound_pso, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query, ended_early, written_ranges, bindings) = { + let (alloc, last_queue, bound_pso, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query, ended_early, written_ranges, bindings, queries_open) = { let mut g = LISTS.lock().unwrap(); let s = g.as_mut()?.get_mut(&(list as usize))?; if s.allocator == 0 { @@ -2773,6 +2864,7 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ ended_early, s.written_ranges.clone(), s.bindings.clone(), + s.queries_open, ) }; @@ -2866,6 +2958,8 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ pred_in_state: false, predication, bindings: bindings.clone(), + // (a query a Wait split ended up spanning still holds put-off calls back) + queries_open, ..Default::default() }, ); @@ -2877,40 +2971,7 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ restore_bindings(next_pc, &bindings, ty); if ty == D3D12_COMMAND_LIST_TYPE_DIRECT { - let info = if bound_pso != 0 { device_x::base_depth_bias_info(bound_pso) } else { None }; - let mut applied_native = false; - if let Some((true, static_bias)) = info { - let target = depth_bias.unwrap_or(static_bias); - if target.is_zero() { - applied_native = true; - } else if try_native_depth_bias(next_pc, target) { - if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(next_pc as usize))) { - s.native_bias = target; - } - applied_native = true; - } - } else if bound_pso == 0 { - if let Some(b) = depth_bias { - if device_x::dynamic_depth_bias_supported(dev_raw as *mut c_void) && try_native_depth_bias(next_pc, b) { - if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(next_pc as usize))) { - s.native_bias = b; - } - applied_native = true; - } - } - } - if depth_bias.is_some() && !applied_native { - if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(next_pc as usize))) { - s.pso_dirty = true; - } - DEPTH_BIAS_USED.store(true, Ordering::Release); - } - if let Some(ref view) = index_buffer { - set_index_buffer(next_pc, Some(view)); - } - if let Some((min, max)) = depth_bounds { - pc::(next_pc, PC_OM_SET_DEPTH_BOUNDS)(next_pc, min, max); - } + restore_direct(next_pc, dev_raw, bound_pso, depth_bias, index_buffer, depth_bounds); } if ty != D3D12_COMMAND_LIST_TYPE_COPY { if let (Some(op), Some(ref pb)) = (predication, pred_buf) { @@ -2928,7 +2989,13 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(seg as usize).or_default(); s.list_type = Some(ty); - s.bindings.heaps = bindings.heaps.clone(); + // (what a draw put off to the submit needs again there: `record_deferred`; the title's + // pipeline stays the key when the real one is bound there, as on its list) + s.bindings = captured.take().unwrap_or_else(|| bindings.clone()); + s.bound_pso = bound_pso; + s.depth_bias = depth_bias; + s.index_buffer = index_buffer; + s.depth_bounds = depth_bounds; s.deferred = Some(what); } super::bind::inherit_for_split(list, seg, alloc); @@ -4498,6 +4565,9 @@ pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usi /// command list #28 BeginQuery(heap, type, index) (PC #52) pub(super) unsafe extern "system" fn begin_query_x(this: *mut c_void, heap: usize, ty: D3D12_QUERY_TYPE, index: u32) { static N: AtomicU64 = AtomicU64::new(0); + if ty != D3D12_QUERY_TYPE_TIMESTAMP { + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(this as usize).or_default().queries_open += 1; + } if is_occlusion(ty) { let outer = LISTS .lock() @@ -4522,6 +4592,11 @@ pub(super) unsafe extern "system" fn begin_query_x(this: *mut c_void, heap: usiz /// command list #29 EndQuery(heap, type, index) (PC #53) pub(super) unsafe extern "system" fn end_query_x(this: *mut c_void, heap: usize, ty: D3D12_QUERY_TYPE, index: u32) { + if ty != D3D12_QUERY_TYPE_TIMESTAMP { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { + s.queries_open = s.queries_open.saturating_sub(1); + } + } if is_occlusion(ty) { let (forward, force_visible) = LISTS .lock() @@ -7079,6 +7154,188 @@ mod tests { } } + /// A graphics `ExecuteIndirect` whose pipeline is still being built is put off to the submit + /// like a dispatch: the title's thread goes on to its next bind, so the pipelines one list + /// binds are built on the workers at once, not one after another on that thread. + #[test] + fn a_graphics_execute_indirect_with_a_pipeline_still_building_waits_at_the_submit() { + use super::super::{bind, pso_async, title_list}; + use crate::gpu::recomp::dxc; + use std::sync::atomic::AtomicUsize; + use std::time::{Duration, Instant}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + use windows::Win32::Graphics::Dxgi::*; + + if dxc::location().is_err() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp = CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()); + if warp.and_then(|w| D3D12CreateDevice(&w, D3D_FEATURE_LEVEL_11_0, &mut dev)).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + } + let dev = dev.unwrap(); + // the real pipelines the builds give (the stand-ins' addresses are never bound) + let vs = dxc::compile(r#"[RootSignature("RootFlags(0)")] float4 main() : SV_Position { return float4(0, 0, 0, 1); }"#, "main", "vs_6_0", &[]).unwrap(); + let ps = dxc::compile("float4 main() : SV_Target { return 1; }", "main", "ps_6_0", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &vs).unwrap(); + let mut pd = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&rs), + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as _, BytecodeLength: vs.len() }, + PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as _, BytecodeLength: ps.len() }, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: true.into(), ..Default::default() }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + pd.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + pd.BlendState.RenderTarget[0].RenderTargetWriteMask = 0xF; + let real = [0; 5].map(|_| dev.CreateGraphicsPipelineState::(&pd).unwrap().into_raw() as usize); + + let arg = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, ..Default::default() }; + let mut sig: Option = None; + dev.CreateCommandSignature(&D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 16, NumArgumentDescs: 1, pArgumentDescs: &arg, NodeMask: 0 }, None, &mut sig).unwrap(); + let sig = sig.unwrap(); + // (as `create_command_signature_x` notes it: a signature that only draws) + bind::note_signature_draws_only(sig.as_raw() as usize, true); + let mut args: Option = None; + let buffer = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COMMON, None, &mut args).unwrap(); + let args = args.unwrap(); + + // two builds that last until the test lets them end, counting how many run at once + static RUNNING: AtomicUsize = AtomicUsize::new(0); + static MOST: AtomicUsize = AtomicUsize::new(0); + static BUILD: AtomicBool = AtomicBool::new(false); + BUILD.store(false, Ordering::Release); + let standins = [0x7E57_E001usize, 0x7E57_E002usize]; + let driver = real[4]; + for (&standin, &real) in standins.iter().zip(&real) { + pso_async::submit_lazy( + standin, + false, + Box::new(move || { + MOST.fetch_max(RUNNING.fetch_add(1, Ordering::AcqRel) + 1, Ordering::AcqRel); + let t = Instant::now(); + while !BUILD.load(Ordering::Acquire) && t.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(5)); + } + RUNNING.fetch_sub(1, Ordering::AcqRel); + real + }), + 0, + ); + // binds get a driver pipeline while it builds, as a shared stand-in's (`standin::shell`) + pso_async::shared(standin, driver); + } + + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let raw: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + let pc0 = raw.into_raw(); + real::adopt(pc0, real::Kind::CommandList); + on_create(pc0, alloc.as_raw() as usize, 0, ty); + bind::reset(pc0, alloc.as_raw() as usize, 0); + let wrap = title_list::wrap(pc0); + + let mut segs = vec![pc0]; + for (n, &standin) in standins.iter().enumerate() { + let list = *segs.last().unwrap(); + // SetPipelineState: the lazy build goes to the workers, both trackers note the pipeline (`cl_set_pipeline_state`) + pso_async::resolve(standin); + bind::clear_state(list, standin); + on_set_pipeline_state(list, standin); + let t = Instant::now(); + bind::execute_indirect(list, sig.as_raw() as usize, 1, args.as_raw() as usize, 0, 0, 0); + assert!(t.elapsed() < Duration::from_millis(700), "ExecuteIndirect {n} waited for the build ({:?})", t.elapsed()); + segs.clear(); + assert!(title_list::push_segments(wrap, &mut segs)); + } + assert_eq!(segs.len(), 1 + 2 * standins.len(), "the list before each ExecuteIndirect, the ExecuteIndirect, the list after it"); + // the put-off segment keeps the title's pipeline as its key (depth bias, `on_set_pipeline_state`) + let seg_pso = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(segs[1] as usize))).map(|s| s.bound_pso); + assert_eq!(seg_pso, Some(standins[0])); + if dxc::compile_threads() >= 2 { + let t = Instant::now(); + while MOST.load(Ordering::Acquire) < 2 && t.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(MOST.load(Ordering::Acquire), 2, "the two builds ran at once on the workers"); + } + + // inside an occlusion query the call stays in its list (put off, the query would not count it) + let mut queries: Option = None; + dev.CreateQueryHeap(&D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_OCCLUSION, Count: 1, NodeMask: 0 }, &mut queries).unwrap(); + let query_heap = queries.unwrap(); + let queries = query_heap.as_raw() as usize; + let counted = 0x7E57_E003usize; + let built = real[2]; + pso_async::submit_lazy(counted, false, Box::new(move || built), 0); + pso_async::shared(counted, driver); + let list = *segs.last().unwrap(); + begin_query_x(list, queries, D3D12_QUERY_TYPE_OCCLUSION, 0); + pso_async::resolve(counted); + bind::clear_state(list, counted); + bind::execute_indirect(list, sig.as_raw() as usize, 1, args.as_raw() as usize, 0, 0, 0); + end_query_x(list, queries, D3D12_QUERY_TYPE_OCCLUSION, 0); + segs.clear(); + assert!(title_list::push_segments(wrap, &mut segs)); + assert_eq!(segs.len(), 1 + 2 * standins.len(), "an ExecuteIndirect inside an occlusion query was put off"); + assert!(!pso_async::is_pending(counted)); + + // nor inside another query: its Begin and End must stay in one PC list + let mut stats_heap: Option = None; + dev.CreateQueryHeap(&D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, Count: 1, NodeMask: 0 }, &mut stats_heap).unwrap(); + let stats_heap = stats_heap.unwrap(); + let stats = 0x7E57_E004usize; + let built = real[3]; + pso_async::submit_lazy(stats, false, Box::new(move || built), 0); + pso_async::shared(stats, driver); + let list = *segs.last().unwrap(); + begin_query_x(list, stats_heap.as_raw() as usize, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0); + pso_async::resolve(stats); + bind::clear_state(list, stats); + bind::execute_indirect(list, sig.as_raw() as usize, 1, args.as_raw() as usize, 0, 0, 0); + end_query_x(list, stats_heap.as_raw() as usize, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0); + segs.clear(); + assert!(title_list::push_segments(wrap, &mut segs)); + assert_eq!(segs.len(), 1 + 2 * standins.len(), "an ExecuteIndirect inside a pipeline-statistics query was put off"); + assert!(!pso_async::is_pending(stats)); + + let close_fn: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(9)); + assert_eq!(close_fn(wrap), 0); + assert!(standins.iter().all(|&s| pso_async::is_pending(s)), "Close waited for a build"); + + BUILD.store(true, Ordering::Release); + record_deferred(wrap); + assert!(standins.iter().all(|&s| !pso_async::is_pending(s)), "the submit waits for the builds"); + + let rel_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(2)); + assert_eq!(rel_fn(wrap), 0); + for s in standins.into_iter().chain([counted, stats]) { + pso_async::release(pso_async::released(s)); + } + pso_async::release(driver); + } + } + /// Reproduces the exact intra-list fork-join pattern seen on retail compute queues: /// q_compute list O_c: Write64(cell_A, frame) -> Wait64(cell_B >= frame) -> Write64(cell_C, frame) /// q_direct list O_d: Wait64(cell_A >= frame) -> Write64(cell_B, frame) diff --git a/crates/xcl/src/hle/d3d12x/list_x_render_targets_tests.rs b/crates/xcl/src/hle/d3d12x/list_x_render_targets_tests.rs new file mode 100644 index 0000000000..0eca903d58 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/list_x_render_targets_tests.rs @@ -0,0 +1,134 @@ +use super::*; +use super::super::{bind, title_list}; +use crate::gpu::recomp::{dxc, runner}; +use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_11_0, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST}; +use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter1, IDXGIFactory6}; + +#[test] +fn deferred_graphics_keeps_render_targets_after_descriptor_overwrite() { + deferred_render_target(false); +} + +#[test] +fn deferred_graphics_keeps_render_targets_after_descriptor_heap_release() { + deferred_render_target(true); +} + +fn deferred_render_target(release_heap: bool) { + if dxc::location().is_err() { runner::skip_test("no DXC"); return; } + unsafe { + let factory: IDXGIFactory6 = CreateDXGIFactory1().unwrap(); + let selector = crate::gpu::adapter::Selector::from_env_or("auto"); + let adapter: IDXGIAdapter1 = if selector == crate::gpu::adapter::Selector::Warp { + factory.EnumWarpAdapter().unwrap() + } else { + let Some((adapter, _)) = crate::gpu::adapter::candidates(&factory, &selector).into_iter().next() else { + runner::skip_test(&crate::gpu::adapter::no_match(&factory, &selector)); return; + }; + adapter + }; + let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_11_0).unwrap(); + println!("deferred RTV adapter: {}", crate::gpu::adapter::name(&adapter.GetDesc1().unwrap())); + let vs = dxc::compile(r#"[RootSignature("RootFlags(0)")] float4 main(uint i : SV_VertexID) : SV_Position { + return float4(i == 2 ? 3 : -1, i == 1 ? 3 : -1, 0, 1); }"#, "main", "vs_6_0", &[]).unwrap(); + let ps = dxc::compile("float4 main() : SV_Target { return float4(1,0,0,1); }", "main", "ps_6_0", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &vs).unwrap(); + let mut pd = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&rs), + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as _, BytecodeLength: vs.len() }, + PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as _, BytecodeLength: ps.len() }, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: true.into(), ..Default::default() }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() + }; + pd.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + pd.BlendState.RenderTarget[0].RenderTargetWriteMask = 15; + let pso: ID3D12PipelineState = dev.CreateGraphicsPipelineState(&pd).unwrap(); + let make = |desc: &D3D12_RESOURCE_DESC, heap, state| { + let mut out: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, desc, state, None, &mut out).unwrap(); + out.unwrap() + }; + let texture = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 1, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, ..Default::default() + }; + let targets = [0; 2].map(|_| make(&texture, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_RENDER_TARGET)); + let buffer = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: 512, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() + }; + let readback = make(&buffer, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + let args = make(&buffer, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + let mut mapped = std::ptr::null_mut(); + args.Map(0, None, Some(&mut mapped)).unwrap(); + std::ptr::copy_nonoverlapping([3u32, 1, 0, 0].as_ptr(), mapped as *mut u32, 4); + args.Unmap(0, None); + let hd = D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: 1, ..Default::default() }; + let heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&hd).unwrap(); + let handle = heap.GetCPUDescriptorHandleForHeapStart(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let raw: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).unwrap(); + // Clear both through the source slot before recording the binding we must preserve. + for target in &targets { + dev.CreateRenderTargetView(target, None, handle); + raw.ClearRenderTargetView(handle, &[0., 0., 0., 0.], None); + } + dev.CreateRenderTargetView(&targets[0], None, handle); + let list = raw.into_raw(); + real::adopt(list, real::Kind::CommandList); + on_create(list, alloc.as_raw() as usize, pso.as_raw() as usize, D3D12_COMMAND_LIST_TYPE_DIRECT); + bind::reset(list, alloc.as_raw() as usize, pso.as_raw() as usize); + let wrapper = title_list::wrap(list); + bind::set_graphics_root_signature(list, rs.as_raw()); + ia_set_topology_x(list, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32); + rs_set_viewports_x(list, 1, &D3D12_VIEWPORT { Width: 1., Height: 1., MaxDepth: 1., ..Default::default() }); + rs_set_scissors_x(list, 1, &windows::Win32::Foundation::RECT { right: 1, bottom: 1, ..Default::default() }); + pc::(list, PC_OM_SET_RENDER_TARGETS)(list, 1, &handle.ptr, 1, std::ptr::null()); + note_render_targets(list, 1, &handle.ptr, 1, std::ptr::null()); + let arg = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, ..Default::default() }; + let mut signature: Option = None; + dev.CreateCommandSignature(&D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 16, NumArgumentDescs: 1, pArgumentDescs: &arg, NodeMask: 0 }, None, &mut signature).unwrap(); + let signature = signature.unwrap(); + // Enter the exact deferred path directly; no build timing is needed to force it. + assert!(defer(list, Deferred::Indirect(signature.as_raw() as usize, 1, args.as_raw() as usize, 0, 0, 0))); + dev.CreateRenderTargetView(&targets[1], None, handle); + if release_heap { drop(heap); } + let mut segments = Vec::new(); + assert!(title_list::push_segments(wrapper, &mut segments)); + let next = *segments.last().unwrap(); + let tail = ID3D12GraphicsCommandList::from_raw_borrowed(&next).unwrap(); + for (i, target) in targets.iter().enumerate() { + tail.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: transmute_copy(target), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_RENDER_TARGET, StateAfter: D3D12_RESOURCE_STATE_COPY_SOURCE, + }) }, ..Default::default() + }]); + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(target), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, ..Default::default() }; + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&readback), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: i as u64 * 256, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: texture.Format, Width: 1, Height: 1, Depth: 1, RowPitch: 256 } } } }; + tail.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + } + let close: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(*(*(wrapper as *const *const usize)).add(9)); + assert_eq!(close(wrapper), 0); + record_deferred(wrapper); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let execute: unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void) = std::mem::transmute(*(*(queue.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); + execute(queue.as_raw(), segments.len() as u32, segments.as_ptr()); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 5000).expect("deferred draw completes"); + readback.Map(0, None, Some(&mut mapped)).unwrap(); + let a = std::slice::from_raw_parts(mapped as *const u8, 4).to_vec(); + let b = std::slice::from_raw_parts((mapped as *const u8).add(256), 4).to_vec(); + readback.Unmap(0, None); + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(wrapper as *const *const usize)).add(2)); + assert_eq!(release(wrapper), 0); + assert_eq!((a, b), (vec![255, 0, 0, 255], vec![0, 0, 0, 0]), "the recorded draw must target A and leave B untouched"); + } +}