diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index b5021f5950..400001e161 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -34,6 +34,8 @@ const TRANSITIONS_MARKER: u32 = 0x8C0F_E007; const COPY_BUFFER_MARKER: u32 = 0x8C0F_E008; const CLEAR_UAV_MARKER: u32 = 0x8C0F_E009; const COPY_TEXTURE_MARKER: u32 = 0x8C0F_E00A; +/// a depth buffer and its twin, copied at an enhanced barrier (resource, into UNORDERED_ACCESS) +const TWIN_COPY_MARKER: u32 = 0x8C0F_E00B; /// root parameter header: 0xC0000000 | i << 10 (bits 31:30 set: the inline code leaves its /// dirty flag alone); the inline code adds the constant offset · 4 (bits 9:2) and /// (count − 1) << 16 @@ -529,8 +531,12 @@ unsafe extern "system" fn cl_copy_texture_region(this: *mut c_void, dst: *const w.extend_from_slice(&bx.as_ref().copied().unwrap_or([0; 6])); push(this as usize, &w); } -unsafe extern "system" fn cl_barrier(this: *mut c_void, _n: u32, _barriers: *const c_void) { +unsafe extern "system" fn cl_barrier(this: *mut c_void, n: u32, groups: *const c_void) { + let syncs = super::list_x::note_depth_uav_barrier_groups(n, groups); push(this as usize, &[BARRIER_MARKER]); + for (res, into) in syncs { + push(this as usize, &[TWIN_COPY_MARKER, res as u32, (res >> 32) as u32, into as u32]); + } } unsafe extern "system" fn cl_allocate_upload_memory(this: *mut c_void, size: usize, align: usize) -> *mut u8 { let Some(u) = crate::gpu::uma::get() else { return std::ptr::null_mut() }; @@ -741,6 +747,15 @@ pub unsafe fn close(obj: *mut c_void) -> Result { b.chunks_exact(4).filter(|c| c[0] as u32 == 0).map(|c| (c[1] as usize, c[2] as u32, D3D12_RESOURCE_STATES(c[3] as u32 as i32))).collect(); super::title_textures::note_transitions(st.pc, &t); } + for c in b.chunks_exact(4) { + let (ty, res) = (c[0] as u32, c[1] as usize); + let (before, after) = ((c[2] >> 32) as u32, c[3] as u32); + if ty == 0 && (before | after) & D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32 != 0 { + super::list_x::note_depth_uav_barrier(res, super::list_x::UavUse::Transition(before, after)); + } else if ty == 2 && res != 0 { + super::list_x::note_depth_uav_barrier(res, super::list_x::UavUse::UavBarrier); + } + } list.ResourceBarrier(std::slice::from_raw_parts(b.as_ptr() as *const D3D12_RESOURCE_BARRIER, n)); } out.barriers += n as u32; @@ -799,6 +814,12 @@ pub unsafe fn close(obj: *mut c_void) -> Result { out.skipped += 1; } at += 35; + } else if w0 == TWIN_COPY_MARKER { + let res = get(1) as usize | (get(2) as usize) << 32; + let barrier = |b: &[D3D12_RESOURCE_BARRIER]| list.ResourceBarrier(b); + let copy = |dst: &ID3D12Resource, src: &ID3D12Resource| list.CopyResource(dst, src); + super::depth_twin::sync(res, get(3) != 0, &barrier, ©); + at += 4; } else if w0 == BARRIER_MARKER { list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, diff --git a/crates/xcl/src/hle/d3d12x/depth_twin.rs b/crates/xcl/src/hle/d3d12x/depth_twin.rs new file mode 100644 index 0000000000..1dfa2f1322 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/depth_twin.rs @@ -0,0 +1,362 @@ +//! Twins of the console depth buffers that shaders write too (#970), with `XCL_DEPTH_UAV_TWINS=1`. +//! +//! The PC refuses a resource that is both a depth buffer and a UAV texture, so such a console +//! depth buffer loses ALLOW_UNORDERED_ACCESS (`device_x::pc_resource_desc`) and its UAVs were null +//! views – what the title's shaders wrote there was lost (a retail title clears or fills its D16 +//! shadow maps that way before it renders depth into them). A twin is a texture of the same +//! typeless format and size with unordered access and no depth: the depth buffer's UAVs are views +//! of the twin (`real::dev_create_uav_x`), and at the title's barriers into the UNORDERED_ACCESS +//! layout the depth buffer is copied to the twin, at those out of it the twin back to the depth +//! buffer (`sync`). The twin is the depth buffer's private data, so it goes when the depth +//! buffer does. +//! +//! XCL applies none of the title's enhanced barriers (#146): on the PC such a depth buffer stays +//! in the state it was made in, which `note_created` keeps for the copies' transitions (not +//! known: DEPTH_WRITE, what a depth buffer placed for unordered access is made in). Depth and +//! stencil formats (two planes) have no twin: the PC has no UAV format for them. + +use std::collections::HashMap; +use std::ffi::c_void; +use std::mem::ManuallyDrop; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows::core::{Interface, GUID}; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +/// The private data key under which a depth buffer holds its twin. +const TWIN: GUID = GUID::from_u128(0x5c1b_7a4e_9f02_4d36_b0a8_3e6d_1f29_c970); + +/// `XCL_DEPTH_UAV_TWINS=1`: depth buffers that shaders write get twins (off by default). +pub fn enabled() -> bool { + static E: OnceLock = OnceLock::new(); + *E.get_or_init(|| std::env::var("XCL_DEPTH_UAV_TWINS").is_ok_and(|v| v.trim() == "1")) +} + +/// The PC state each console depth buffer that is also a UAV was made in. +static MADE_IN: Mutex>> = Mutex::new(None); + +/// A console depth buffer that shaders write too was made (`device_x::create_placed_resource_x`) +/// in PC state `state`. +pub fn note_created(res: usize, state: u32) { + if enabled() { + MADE_IN.lock().unwrap().get_or_insert_with(HashMap::new).insert(res, state as i32); + } +} + +fn state_of(res: usize) -> D3D12_RESOURCE_STATES { + let s = MADE_IN.lock().unwrap().as_ref().and_then(|m| m.get(&res).copied()); + D3D12_RESOURCE_STATES(s.unwrap_or(D3D12_RESOURCE_STATE_DEPTH_WRITE.0)) +} + +/// `res` is gone (`real::res_release`, its last reference): a resource made later at the same +/// address does not take its state. +pub fn forget(res: usize) { + if let Some(m) = MADE_IN.lock().unwrap().as_mut() { + m.remove(&res); + } +} + +/// The view of the twin for a UAV the title made without a description: the twin's format is +/// typeless, and a UAV of a typeless resource needs a typed one (R16_UNORM, R32_FLOAT). +pub fn twin_uav_desc(twin: &D3D12_RESOURCE_DESC) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { + let format = if twin.Format == DXGI_FORMAT_R16_TYPELESS { DXGI_FORMAT_R16_UNORM } else { DXGI_FORMAT_R32_FLOAT }; + let mut v = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: format, ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, ..Default::default() }; + if twin.DepthOrArraySize > 1 { + v.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + v.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV { MipSlice: 0, FirstArraySlice: 0, ArraySize: twin.DepthOrArraySize as u32, PlaneSlice: 0 }; + } + v +} + +/// The depth buffer's transitions around a copy, from the state it was made in to the copy's +/// and back – none when it is in the copy's state already (a transition to the same state is +/// refused). +fn depth_transitions(made: D3D12_RESOURCE_STATES, copy: D3D12_RESOURCE_STATES) -> Option<[(D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES); 2]> { + (made != copy).then_some([(made, copy), (copy, made)]) +} + +/// The twin's description for a depth buffer's (None: no twin for it – a format of two planes, +/// several samples, or a resource that already has unordered access). +pub fn twin_desc(d: &D3D12_RESOURCE_DESC) -> Option { + let depth = d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0 && d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0; + if !depth || d.SampleDesc.Count != 1 || !matches!(d.Format, DXGI_FORMAT_R16_TYPELESS | DXGI_FORMAT_R32_TYPELESS) { + return None; + } + let mut t = *d; + t.Flags = D3D12_RESOURCE_FLAGS((d.Flags.0 & !(D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE.0)) | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0); + t.Alignment = 0; + Some(t) +} + +/// The twin `res` has (None: none made). +pub unsafe fn twin_of(res: &ID3D12Resource) -> Option { + let mut p: *mut c_void = std::ptr::null_mut(); + let mut size = std::mem::size_of::<*mut c_void>() as u32; + res.GetPrivateData(&TWIN, &mut size, Some(&mut p as *mut _ as *mut c_void)).ok()?; + // an interface kept with SetPrivateDataInterface comes back with a reference of its own + (!p.is_null()).then(|| ID3D12Resource::from_raw(p)) +} + +/// The twin a UAV of `res` is made on – made now if `res` has none yet (None: twins are off, or +/// `res` gets none: `twin_desc`, or it could not be made). +pub unsafe fn twin_for_uav(res: &ID3D12Resource) -> Option { + if !enabled() { + return None; + } + make_twin(res) +} + +/// `twin_for_uav` whether twins are on or not. +unsafe fn make_twin(res: &ID3D12Resource) -> Option { + if let Some(t) = twin_of(res) { + return Some(t); + } + let td = twin_desc(&res.GetDesc())?; + let mut dev: Option = None; + res.GetDevice(&mut dev).ok()?; + let props = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut twin: Option = None; + static N: AtomicU64 = AtomicU64::new(0); + if let Err(e) = dev?.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &td, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut twin) { + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: no twin for a depth buffer that shaders write ({}x{}x{}, format {}): {e} – its UAVs are null views", td.Width, td.Height, td.DepthOrArraySize, td.Format.0); + } + return None; + } + let twin = twin?; + res.SetPrivateDataInterface(&TWIN, &twin).ok()?; + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: a depth buffer that shaders write ({}x{}x{}, format {}) has a twin for its UAVs ({n} so far)", td.Width, td.Height, td.DepthOrArraySize, td.Format.0); + } + Some(twin) +} + +fn transition(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + // borrowed: the barrier holds no reference of its own + pResource: unsafe { std::mem::transmute_copy(res) }, + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + } +} + +/// At a barrier of the title that moves depth buffer `res` into (`into_uav`) or out of the +/// UNORDERED_ACCESS layout: the depth buffer is copied to its twin, or the twin back to it, with +/// the transitions the copy needs around it (`barrier`, `copy`: the list's ResourceBarrier and +/// CopyResource(destination, source)). Nothing when `res` has no twin. Returns whether it copied. +pub unsafe fn sync(res: usize, into_uav: bool, barrier: &dyn Fn(&[D3D12_RESOURCE_BARRIER]), copy: &dyn Fn(&ID3D12Resource, &ID3D12Resource)) -> bool { + let r = res as *mut c_void; + let Some(depth) = ID3D12Resource::from_raw_borrowed(&r) else { return false }; + let Some(twin) = twin_of(depth) else { return false }; + let made = state_of(res); + let uav = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + let (src, dst) = (D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST); + let (depth_copy, twin_copy) = if into_uav { (src, dst) } else { (dst, src) }; + let around = depth_transitions(made, depth_copy); + let mut before = vec![transition(&twin, uav, twin_copy)]; + let mut after = vec![transition(&twin, twin_copy, uav)]; + if let Some([(a, b), (c, d)]) = around { + before.push(transition(depth, a, b)); + after.push(transition(depth, c, d)); + } + barrier(&before); + if into_uav { + copy(&twin, depth); + } else { + copy(depth, &twin); + } + barrier(&after); + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + let d = depth.GetDesc(); + crate::xlog_info!("D3D12.X: a depth buffer and its twin ({}x{}x{}): {} ({n} copies so far)", d.Width, d.Height, d.DepthOrArraySize, if into_uav { "copied to the twin" } else { "the twin copied back" }); + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + fn depth_desc(format: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Alignment: 65536, + Width: 768, + Height: 768, + DepthOrArraySize: 6, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: flags, + } + } + + /// A single-plane depth buffer without unordered access gets a twin of its format and size + /// with unordered access and no depth; one of two planes, a UAV texture or MSAA does not. + #[test] + fn a_d16_or_d32_depth_buffer_gets_a_twin_with_unordered_access() { + let ds = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + for f in [DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R32_TYPELESS] { + let t = twin_desc(&depth_desc(f, ds | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)).unwrap(); + assert_eq!((t.Format, t.Width, t.Height, t.DepthOrArraySize, t.MipLevels, t.Alignment), (f, 768, 768, 6, 1, 0)); + assert_eq!(t.Flags, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + } + assert!(twin_desc(&depth_desc(DXGI_FORMAT_R24G8_TYPELESS, ds)).is_none(), "depth + stencil"); + assert!(twin_desc(&depth_desc(DXGI_FORMAT_R32G8X24_TYPELESS, ds)).is_none(), "depth + stencil"); + assert!(twin_desc(&depth_desc(DXGI_FORMAT_R16_TYPELESS, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)).is_none(), "not a depth buffer"); + let mut msaa = depth_desc(DXGI_FORMAT_R32_TYPELESS, ds); + msaa.SampleDesc.Count = 4; + assert!(twin_desc(&msaa).is_none()); + } + + /// A depth buffer made in the copy's state gets no transition to that same state (D3D12 + /// refuses StateBefore == StateAfter); one made in another state goes there and back. + #[test] + fn a_depth_buffer_in_the_copys_state_is_not_moved_to_it() { + let (dw, src, dst) = (D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST); + assert_eq!(depth_transitions(dw, src), Some([(dw, src), (src, dw)])); + assert_eq!(depth_transitions(src, src), None); + assert_eq!(depth_transitions(dst, dst), None); + } + + /// A UAV made without a description gets a typed view of the twin: R16_UNORM / R32_FLOAT, + /// an array view over every slice of a cube or cascade. + #[test] + fn a_uav_without_a_description_is_a_typed_view_of_the_twin() { + let t = twin_desc(&depth_desc(DXGI_FORMAT_R16_TYPELESS, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)).unwrap(); + let v = twin_uav_desc(&t); + assert_eq!((v.Format, v.ViewDimension), (DXGI_FORMAT_R16_UNORM, D3D12_UAV_DIMENSION_TEXTURE2DARRAY)); + assert_eq!(unsafe { v.Anonymous.Texture2DArray.ArraySize }, 6); + let mut one = depth_desc(DXGI_FORMAT_R32_TYPELESS, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); + one.DepthOrArraySize = 1; + let v = twin_uav_desc(&twin_desc(&one).unwrap()); + assert_eq!((v.Format, v.ViewDimension), (DXGI_FORMAT_R32_FLOAT, D3D12_UAV_DIMENSION_TEXTURE2D)); + } + + /// A depth buffer's state goes with it: a later one at the same address starts from + /// DEPTH_WRITE, not from the state the first was made in. + #[test] + fn a_released_depth_buffers_state_is_forgotten() { + let res = 0x7E57_9700usize; + MADE_IN.lock().unwrap().get_or_insert_with(HashMap::new).insert(res, D3D12_RESOURCE_STATE_COPY_SOURCE.0); + assert_eq!(state_of(res), D3D12_RESOURCE_STATE_COPY_SOURCE); + forget(res); + assert_eq!(state_of(res), D3D12_RESOURCE_STATE_DEPTH_WRITE); + } + + /// The round trip of a D16 depth buffer that shaders write: its clear reaches the twin at the + /// barrier into UNORDERED_ACCESS, a write through the twin's UAV reaches the depth buffer at + /// the barrier out of it, and the depth buffer is in the state it was made in afterwards. + #[test] + fn gpu_a_uav_write_to_a_depth_buffer_goes_through_its_twin() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let (w, h) = (64u32, 32u32); + let mut d = depth_desc(DXGI_FORMAT_R16_TYPELESS, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); + (d.Width, d.Height, d.DepthOrArraySize, d.Alignment) = (w as u64, h, 1, 0); + let default = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut depth: Option = None; + dev.CreateCommittedResource(&default, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_DEPTH_WRITE, None, &mut depth).unwrap(); + let depth = depth.unwrap(); + assert!(twin_of(&depth).is_none()); + let twin = make_twin(&depth).expect("a twin"); + assert_eq!(twin_of(&depth).map(|t| t.as_raw()), Some(twin.as_raw()), "kept with the depth buffer"); + assert_eq!(make_twin(&depth).map(|t| t.as_raw()), Some(twin.as_raw()), "made once"); + + // the depth buffer's DSV, and the twin's UAV in a shader-visible and a CPU heap (for the clear) + let heap = |ty, n, flags| -> ID3D12DescriptorHeap { dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: ty, NumDescriptors: n, Flags: flags, NodeMask: 0 }).unwrap() }; + let dsv_heap = heap(D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE); + let (gpu_heap, cpu_heap) = (heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE), heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE)); + let dsv = dsv_heap.GetCPUDescriptorHandleForHeapStart(); + dev.CreateDepthStencilView(&depth, Some(&D3D12_DEPTH_STENCIL_VIEW_DESC { Format: DXGI_FORMAT_D16_UNORM, ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, ..Default::default() }), dsv); + let uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R16_UNORM, ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, ..Default::default() }; + dev.CreateUnorderedAccessView(&twin, None, Some(&uav), gpu_heap.GetCPUDescriptorHandleForHeapStart()); + dev.CreateUnorderedAccessView(&twin, None, Some(&uav), cpu_heap.GetCPUDescriptorHandleForHeapStart()); + + // a readback buffer for one texture of R16 (rows of 256 bytes) + let pitch = 256u32; + let rb_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: (pitch * h) as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let readback_props = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut fence_value = 0u64; + // one list: `record`, then a copy of `src` (in `state`) to a readback buffer, run and read + let run = |record: &dyn Fn(&ID3D12GraphicsCommandList), src: &ID3D12Resource, state: D3D12_RESOURCE_STATES, fence_value: &mut u64| -> Vec { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + record(&list); + let mut rb: Option = None; + dev.CreateCommittedResource(&readback_props, D3D12_HEAP_FLAG_NONE, &rb_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb).unwrap(); + let rb = rb.unwrap(); + list.ResourceBarrier(&[transition(src, state, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: DXGI_FORMAT_R16_TYPELESS, Width: w, Height: h, Depth: 1, RowPitch: pitch }, + }; + let to = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint } }; + let from = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(src), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&to, 0, 0, 0, &from, None); + list.ResourceBarrier(&[transition(src, D3D12_RESOURCE_STATE_COPY_SOURCE, state)]); + list.Close().unwrap(); + q.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + *fence_value += 1; + q.Signal(&fence, *fence_value).unwrap(); + while fence.GetCompletedValue() < *fence_value { + std::thread::yield_now(); + } + let mut p: *mut c_void = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let rows = std::slice::from_raw_parts(p as *const u8, (pitch * h) as usize); + let px: Vec = (0..h as usize).flat_map(|y| (0..w as usize).map(move |x| u16::from_le_bytes([rows[y * pitch as usize + 2 * x], rows[y * pitch as usize + 2 * x + 1]]))).collect(); + rb.Unmap(0, None); + px + }; + + // the depth buffer cleared to 0.25, then the barrier into UNORDERED_ACCESS: the twin has it + let into = |l: &ID3D12GraphicsCommandList| { + l.ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH, 0.25, 0, None); + assert!(sync(depth.as_raw() as usize, true, &|b| l.ResourceBarrier(b), &|dst, src| l.CopyResource(dst, src))); + }; + let twin_px = run(&into, &twin, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, &mut fence_value); + assert!(twin_px.iter().all(|&v| v.abs_diff(16384) <= 1), "the twin has the depth buffer's 0.25: {:?}", &twin_px[..4]); + + // a write through the twin's UAV (0.75), then the barrier out of UNORDERED_ACCESS: the depth buffer has it + let out = |l: &ID3D12GraphicsCommandList| { + l.SetDescriptorHeaps(&[Some(gpu_heap.clone())]); + l.ClearUnorderedAccessViewFloat(gpu_heap.GetGPUDescriptorHandleForHeapStart(), cpu_heap.GetCPUDescriptorHandleForHeapStart(), &twin, &[0.75, 0.0, 0.0, 0.0], &[]); + assert!(sync(depth.as_raw() as usize, false, &|b| l.ResourceBarrier(b), &|dst, src| l.CopyResource(dst, src))); + }; + let depth_px = run(&out, &depth, D3D12_RESOURCE_STATE_DEPTH_WRITE, &mut fence_value); + assert!(depth_px.iter().all(|&v| v.abs_diff(49151) <= 1), "the depth buffer has the UAV's 0.75: {:?}", &depth_px[..4]); + assert_eq!(dev.GetDeviceRemovedReason(), Ok(()), "the device is still there"); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 4b6d32aa79..af4956cf5d 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -892,6 +892,8 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, // console-only state bits (Unicorn Overlord's 4K display target: 0x100000) are not the // PC's: the PC refused the resource (E_INVALIDARG) and the title threw let state = pc_initial_state(u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()), state); + // a depth buffer that shaders write too: the state its twin's copies start from (#970) + let depth_uav = u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()) & 6 == 6; let mut clear_buf = [0u8; 24]; let clear = pc_clear(clear, &mut clear_buf); if buffer { @@ -913,6 +915,9 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, super::title_textures::retire_overlapping(va as usize, bytes as usize); } real::note_title_address(*ppv as usize, va as usize); + if depth_uav { + super::depth_twin::note_created(*ppv as usize, state); + } } return hr; } @@ -927,6 +932,9 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, real::dev_create_committed_resource(this, &heap as *const _ as usize, 0, d.as_ptr() as usize, state as usize, clear as usize, riid, ppv) } }; + if hr >= 0 && depth_uav && !(*ppv).is_null() { + super::depth_twin::note_created(*ppv as usize, state); + } if hr >= 0 && !buffer && !(*ppv).is_null() { static M: AtomicU64 = AtomicU64::new(0); match super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)) { diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index cdf0c9e7ca..978cd7e073 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -2699,7 +2699,8 @@ pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u3 /// command list #146 console compute/UAV barrier (used by `XboxBvhBuilder.dll` between BVH /// build passes): emits a global UAV barrier so UMA writes become visible to the next pass -pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, _n: u32, _barriers: *const c_void) { +pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, n: u32, groups: *const c_void) { + let syncs = note_depth_uav_barrier_groups(n, groups); let b = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, @@ -2708,6 +2709,12 @@ pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, _n: u32, _ }, }; pc::(this, PC_RESOURCE_BARRIER)(this, 1, &b); + // depth buffers that shaders write: their twins follow the title's layout changes (#970) + for (res, into) in syncs { + let barrier = |b: &[D3D12_RESOURCE_BARRIER]| pc::(this, PC_RESOURCE_BARRIER)(this, b.len() as u32, b.as_ptr()); + let copy = |dst: &ID3D12Resource, src: &ID3D12Resource| pc::(this, PC_COPY_RESOURCE)(this, dst.as_raw(), src.as_raw()); + super::depth_twin::sync(res, into, &barrier, ©); + } } /// command list #84 CopyResourceX(destination, source, flags); in place (the console's @@ -3668,6 +3675,10 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 } } if ty == 2 { + let r = (b[2] as u64 | (b[3] as u64) << 32) as usize; + if r != 0 { + note_depth_uav_barrier(r, UavUse::UavBarrier); + } // UAV (resource +8): translated shaders reach title memory through XCL's memory // window buffers – other resources over the same memory – which a UAV barrier for // the title's resource alone does not order (AMD drivers wait and flush for any UAV @@ -3698,6 +3709,9 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 } // UAV writes before (or after) the transition: the same holds for the window buffers uav_transition |= (b[5] | b[6]) & UNORDERED_ACCESS != 0; + if (b[5] | b[6]) & UNORDERED_ACCESS != 0 { + note_depth_uav_barrier((b[2] as u64 | (b[3] as u64) << 32) as usize, UavUse::Transition(b[5], b[6])); + } } out.push(b); } @@ -3721,6 +3735,97 @@ const BUFFER_ONLY_STATES: u32 = 0x1 | 0x2; /// D3D12_RESOURCE_STATE_UNORDERED_ACCESS const UNORDERED_ACCESS: u32 = 0x8; +/// A console depth buffer that shaders write too, as the PC has it: ALLOW_DEPTH_STENCIL without +/// ALLOW_UNORDERED_ACCESS (`device_x::pc_resource_desc` drops it) – its UAVs are null views +/// (`real::dev_create_uav_x`), so what shaders write through them is lost (#970). +fn depth_without_uav(flags: i32) -> bool { + flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0 && flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 +} + +/// How a barrier of the title uses a resource as a UAV (`note_depth_uav_barrier`). +pub(super) enum UavUse { + /// a transition from or to UNORDERED_ACCESS (before, after) + Transition(u32, u32), + /// a UAV barrier naming the resource + UavBarrier, + /// an enhanced texture barrier (#146) with the UNORDERED_ACCESS layout or access: layouts + /// before, after + Layout(i32, i32), +} + +/// A barrier of the title that uses such a depth buffer as a UAV. Counted; the first 8 and +/// every power of two are logged. Returns whether `res` is such a depth buffer. +pub(super) unsafe fn note_depth_uav_barrier(res: usize, how: UavUse) -> bool { + let r = res as *mut c_void; + let Some(d) = ID3D12Resource::from_raw_borrowed(&r).map(|x| x.GetDesc()) else { return false }; + if !depth_without_uav(d.Flags.0) { + return false; + } + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + let what = match how { + UavUse::Transition(before, after) => format!("a transition {before:#x} → {after:#x}"), + UavUse::UavBarrier => "a UAV barrier".into(), + UavUse::Layout(before, after) => format!("a texture barrier, layout {before} → {after},"), + }; + let r = ID3D12Resource::from_raw_borrowed(&r).unwrap(); + let views = if super::depth_twin::twin_of(r).is_some() { "views of its twin (#970)" } else { "null views, what shaders write there is lost" }; + crate::xlog_warn!("D3D12.X: {what} uses a depth buffer as a UAV ({}x{}x{}, format {}); its UAVs are {views} ({n} so far)", d.Width, d.Height, d.DepthOrArraySize, d.Format.0); + } + true +} + +/// Whether an enhanced texture barrier moves its texture into or out of unordered access +/// (layout UNORDERED_ACCESS before or after, or the UNORDERED_ACCESS access bit). +fn barrier_uses_uav(layouts: (i32, i32), access: (i32, i32)) -> bool { + let layout = D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS.0; + layouts.0 == layout || layouts.1 == layout || (access.0 | access.1) & D3D12_BARRIER_ACCESS_UNORDERED_ACCESS.0 != 0 +} + +/// #146 Barrier(n, groups): the title's enhanced barriers (D3D12_BARRIER_GROUP) – XCL turns them +/// into one global UAV barrier and their description is not read (`uav_barrier_x`). Its texture +/// barriers that use a depth buffer without UAVs as one are counted (`note_depth_uav_barrier`). +/// Returns those that move such a depth buffer into (true) or out of (false) the +/// UNORDERED_ACCESS layout, for its twin (`depth_twin::sync`; empty when twins are off). +pub(super) unsafe fn note_depth_uav_barrier_groups(n: u32, groups: *const c_void) -> Vec<(usize, bool)> { + let mut syncs = Vec::new(); + let group_bytes = std::mem::size_of::(); + if n == 0 || n > 1024 || groups.is_null() || !crate::gpu::shader::readable(groups as usize, n as usize * group_bytes) { + return syncs; + } + let groups = std::slice::from_raw_parts(groups as *const D3D12_BARRIER_GROUP, n as usize); + for g in groups.iter().filter(|g| g.Type == D3D12_BARRIER_TYPE_TEXTURE) { + let (t, k) = (g.Anonymous.pTextureBarriers, g.NumBarriers as usize); + if k == 0 || t.is_null() || !crate::gpu::shader::readable(t as usize, k * std::mem::size_of::()) { + continue; + } + for b in std::slice::from_raw_parts(t, k) { + if barrier_uses_uav((b.LayoutBefore.0, b.LayoutAfter.0), (b.AccessBefore.0, b.AccessAfter.0)) { + let Some(r) = b.pResource.as_ref() else { continue }; + let res = r.as_raw() as usize; + if note_depth_uav_barrier(res, UavUse::Layout(b.LayoutBefore.0, b.LayoutAfter.0)) && super::depth_twin::enabled() { + if let Some(into) = twin_copy((b.LayoutBefore.0, b.LayoutAfter.0)) { + syncs.push((res, into)); + } + } + } + } + } + syncs +} + +/// The copy between a depth buffer and its twin a texture barrier needs (layouts before, after): +/// into UNORDERED_ACCESS: to the twin (true); out of it: back (false); None otherwise. +fn twin_copy(layouts: (i32, i32)) -> Option { + let uav = D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS.0; + match (layouts.0 == uav, layouts.1 == uav) { + (false, true) => Some(true), + (true, false) => Some(false), + _ => None, + } +} + /// Whether `res` is a buffer (null / unknown: taken as one – its states are left alone). unsafe fn is_buffer(res: usize) -> bool { let r = res as *mut c_void; @@ -4126,6 +4231,42 @@ mod tests { } } + /// Only a depth buffer without unordered access (what `pc_resource_desc` makes of a console + /// one shaders write too) counts as one whose UAVs are null. + #[test] + fn a_depth_buffer_without_unordered_access_is_one_with_null_uavs() { + let (ds, ua, rt) = (D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET.0); + assert!(depth_without_uav(ds)); + assert!(depth_without_uav(ds | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE.0)); + assert!(!depth_without_uav(ds | ua), "a depth buffer the PC lets have UAVs"); + assert!(!depth_without_uav(ua), "a plain UAV texture"); + assert!(!depth_without_uav(rt | ua)); + assert!(!depth_without_uav(0)); + // the console desc's flags as `pc_resource_desc` leaves them (depth + UAV: 0x6 → 0x2) + let mut x = [0u8; 0x38]; + x[0..4].copy_from_slice(&(D3D12_RESOURCE_DIMENSION_TEXTURE2D.0 as u32).to_le_bytes()); + x[0x20..0x24].copy_from_slice(&40u32.to_le_bytes()); + x[0x30..0x34].copy_from_slice(&((ds | ua) as u32).to_le_bytes()); + let d = device_x::pc_resource_desc(&x); + assert!(depth_without_uav(u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()) as i32)); + } + + /// The enhanced barriers a retail title gives its shadow maps: into and out of the + /// UNORDERED_ACCESS layout counts, depth write ↔ shader resource does not. + #[test] + fn an_enhanced_barrier_into_or_out_of_unordered_access_is_a_uav_use() { + let l = |x: D3D12_BARRIER_LAYOUT| x.0; + let a = |x: D3D12_BARRIER_ACCESS| x.0; + let (uav, dsw, srv) = (l(D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS), l(D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE), l(D3D12_BARRIER_LAYOUT_SHADER_RESOURCE)); + let (a_uav, a_dsw, a_srv) = (a(D3D12_BARRIER_ACCESS_UNORDERED_ACCESS), a(D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE), a(D3D12_BARRIER_ACCESS_SHADER_RESOURCE)); + assert!(barrier_uses_uav((srv, uav), (a_srv, a_uav)), "shader resource → unordered access"); + assert!(barrier_uses_uav((uav, dsw), (a_uav, a_dsw)), "unordered access → depth write"); + assert!(barrier_uses_uav((l(D3D12_BARRIER_LAYOUT_COMMON), l(D3D12_BARRIER_LAYOUT_COMMON)), (0, a_uav)), "the access alone"); + assert!(!barrier_uses_uav((dsw, srv), (a_dsw, a_srv))); + assert!(!barrier_uses_uav((l(D3D12_BARRIER_LAYOUT_UNDEFINED), dsw), (a(D3D12_BARRIER_ACCESS_NO_ACCESS), a_dsw))); + assert!(!barrier_uses_uav((dsw, dsw), (a_dsw, a(D3D12_BARRIER_ACCESS_RENDER_TARGET))), "RENDER_TARGET (0x8) is not UNORDERED_ACCESS (0x10)"); + } + static RESET_TEST_HR: AtomicU32 = AtomicU32::new(0); static RESET_TEST_REPLACEMENT_VT: AtomicU64 = AtomicU64::new(0); diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index f3f0357981..b5c4b3a352 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -13,6 +13,7 @@ mod alloc_pool; pub mod bind; pub mod console_heap; pub mod console_list; +pub mod depth_twin; pub mod device_x; pub mod dxgi_device; mod cpu_writes; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 3ff2a9793b..d03795ed4d 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1592,6 +1592,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { f(this) }; if n == 0 { + super::depth_twin::forget(this as usize); if let Some(s) = UNMAPPABLE.lock().unwrap().as_mut() { s.remove(&(this as usize)); } @@ -2227,10 +2228,17 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, let no_uav = ID3D12Resource::from_raw_borrowed(&res).is_some_and(|r| r.GetDesc().Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0); let null_desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT, ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, ..Default::default() }; let pc_uav = |at: u64| { + // with `XCL_DEPTH_UAV_TWINS=1` a depth buffer's UAV is a view of its twin (#970) + if let Some(twin) = no_uav.then(|| ID3D12Resource::from_raw_borrowed(&res).and_then(|r| super::depth_twin::twin_for_uav(r))).flatten() { + // (without a description: a typed view – the twin is typeless) + let typed = super::depth_twin::twin_uav_desc(&twin.GetDesc()); + return f(this, twin.as_raw(), std::ptr::null_mut(), if desc.is_null() { &typed } else { desc }, at); + } if no_uav { static N: AtomicU64 = AtomicU64::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: a UAV of a resource that cannot have one on the PC (a depth buffer) – a null view"); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_warn!("D3D12.X: a UAV of a resource that cannot have one on the PC (a depth buffer) – a null view ({n} so far)"); } f(this, std::ptr::null_mut(), std::ptr::null_mut(), &null_desc, at) } else {