diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 88faa6f..9a2cbf1 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -15,9 +15,10 @@ use std::collections::HashMap; use std::ffi::{c_char, c_void, CStr, CString}; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicI8, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; +use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; use windows_sys::core::GUID; @@ -34,6 +35,7 @@ pub const XBOX_TYPE_DMA: u32 = 0x10; /// IID of the console's DMA command list (created as a PC graphics command list) const IID_XBOX_DMA_COMMAND_LIST: GUID = GUID::from_u128(0x30bc77b9_8379_4b25_95de_b8588c42275d); const IID_GRAPHICS_COMMAND_LIST: GUID = GUID::from_u128(0x5b160d0f_ac1b_4185_8ba8_b3ae42a5a455); +const IID_PIPELINE_STATE: GUID = GUID::from_u128(0x765a30f3_f624_4c6f_a828_ace948622445); /// D3D12_INDIRECT_ARGUMENT_TYPE of the console's DispatchX const XBOX_ARG_DISPATCH_X: u32 = 105; @@ -66,7 +68,11 @@ pub fn pc_queue_desc(d: [u32; 4]) -> [u32; 4] { /// device #8 CreateCommandQueue / #48 CreateCommandQueueX(desc, riid, queue) pub(super) unsafe extern "system" fn create_command_queue_x(this: *mut c_void, desc: *const [u32; 4], riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let d = if desc.is_null() { [0; 4] } else { pc_queue_desc(desc.read_unaligned()) }; - real::dev_create_command_queue(this, d.as_ptr() as usize, riid, ppv) + let hr = real::dev_create_command_queue(this, d.as_ptr() as usize, riid, ppv); + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + super::list_x::on_queue_create(*ppv as usize, this as usize, D3D12_COMMAND_LIST_TYPE(d[0] as i32)); + } + hr } /// device #9 CreateCommandAllocator(type, riid, allocator) @@ -81,7 +87,11 @@ unsafe fn create_list(this: *mut c_void, node: u32, ty: u32, alloc: usize, pso: let hr = if super::console_list::enabled() { real::dev_create_command_list_x(this, node, ty, alloc, pso, riid, ppv) } else { - real::dev_create_command_list(this, node, ty, alloc, pso, riid, ppv) + let hr = real::dev_create_command_list(this, node, ty, alloc, pso, riid, ppv); + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + super::list_x::on_create(*ppv, alloc, pso, D3D12_COMMAND_LIST_TYPE(ty as i32)); + } + hr }; if dma && hr >= 0 && !ppv.is_null() { real::readopt(*ppv, real::Kind::DmaList); @@ -123,11 +133,76 @@ pub(super) unsafe extern "system" fn create_graphics_pso_x(this: *mut c_void, de } /// device #10 CreateGraphicsPipelineState(desc, riid, pipeline): remembered as a base for -/// derived pipelines +/// derived pipelines and tagged with `D3D12_PIPELINE_STATE_FLAG_DYNAMIC_DEPTH_BIAS` when supported. pub(super) unsafe extern "system" fn create_graphics_pso_pc(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { - let hr = real::dev_create_graphics_pso(this, desc, riid, ppv); - if hr >= 0 && !ppv.is_null() { - note_base(*ppv, desc); + create_graphics_pso_tracked(this, desc, riid, ppv) +} + +/// Cached result of `CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS16).DynamicDepthBiasSupported`: +/// -1 = not yet probed, 0 = unsupported, 1 = supported. +static DYN_DEPTH_BIAS: AtomicI8 = AtomicI8::new(-1); + +/// Query `D3D12_FEATURE_D3D12_OPTIONS16` for native dynamic depth bias support and cache it. +pub(super) fn probe_dynamic_depth_bias(dev: &ID3D12Device) -> bool { + let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default(); + let supported = unsafe { + dev.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS16, + &mut opts as *mut _ as *mut c_void, + std::mem::size_of::() as u32, + ) + .is_ok() + && opts.DynamicDepthBiasSupported.as_bool() + }; + DYN_DEPTH_BIAS.store(if supported { 1 } else { 0 }, Ordering::Release); + crate::xlog_info!( + "D3D12.X: native dynamic depth bias (OPTIONS16): {}", + if supported { "supported (ID3D12GraphicsCommandList9::RSSetDepthBias)" } else { "unsupported (using patched-PSO fallback)" } + ); + supported +} + +/// Whether the D3D12 device supports `D3D12_PIPELINE_STATE_FLAG_DYNAMIC_DEPTH_BIAS` / +/// `ID3D12GraphicsCommandList9::RSSetDepthBias`. Lazily probes `dev` if not yet probed. +pub(super) unsafe fn dynamic_depth_bias_supported(dev: *mut c_void) -> bool { + match DYN_DEPTH_BIAS.load(Ordering::Acquire) { + 1 => return true, + 0 => return false, + _ => {} + } + if dev.is_null() { + return false; + } + ID3D12Device::from_raw_borrowed(&dev).is_some_and(probe_dynamic_depth_bias) +} + +/// Create a graphics PSO, enabling `D3D12_PIPELINE_STATE_FLAG_DYNAMIC_DEPTH_BIAS` when the +/// device supports it (retrying without the flag if creation fails), and record it as a base. +unsafe fn create_graphics_pso_tracked(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let mut used_dynamic = false; + let hr = if !desc.is_null() && crate::gpu::shader::readable(desc as usize, GFX_DESC) { + let orig = GfxDesc((desc as *const [u8; GFX_DESC]).read_unaligned()); + let already_dynamic = rd32(&orig.0, PSO_FLAGS) & FLAG_DYNAMIC_DEPTH_BIAS != 0; + let want_dynamic = !already_dynamic && rd32(&orig.0, SO_ENTRIES) == 0 && dynamic_depth_bias_supported(this); + if want_dynamic { + let mut dyn_desc = orig; + enable_dynamic_depth_bias(&mut dyn_desc.0); + let hr = real::dev_create_graphics_pso(this, dyn_desc.0.as_ptr() as *const c_void, riid, ppv); + if hr >= 0 { + used_dynamic = true; + hr + } else { + real::dev_create_graphics_pso(this, desc, riid, ppv) + } + } else { + used_dynamic = already_dynamic; + real::dev_create_graphics_pso(this, desc, riid, ppv) + } + } else { + real::dev_create_graphics_pso(this, desc, riid, ppv) + }; + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + note_base(*ppv, desc, used_dynamic); } hr } @@ -139,21 +214,98 @@ const STAGES: [usize; 5] = [0x08, 0x18, 0x28, 0x38, 0x48]; const SO_ENTRIES: usize = 0x60; const INPUT_LAYOUT: usize = 0x228; const CACHED_PSO: usize = 0x278; +/// Flags field in D3D12_GRAPHICS_PIPELINE_STATE_DESC +const PSO_FLAGS: usize = 0x288; +const FLAG_DYNAMIC_DEPTH_BIAS: u32 = D3D12_PIPELINE_STATE_FLAG_DYNAMIC_DEPTH_BIAS.0 as u32; +/// RasterizerState.{DepthBias, DepthBiasClamp, SlopeScaledDepthBias} in D3D12_GRAPHICS_PIPELINE_STATE_DESC +const RASTERIZER_DEPTH_BIAS: usize = 0x1D0; +const RASTERIZER_DEPTH_BIAS_CLAMP: usize = 0x1D4; +const RASTERIZER_SLOPE_SCALED_DEPTH_BIAS: usize = 0x1D8; +/// Maximum cached depth-bias PSO variants across all base pipelines +const MAX_DEPTH_BIAS_PSOS: usize = 1024; /// CreateDerivedPipelineStateX patch: { u32 part; payload } at this stride (the largest /// payload is the blend state) const PATCH: usize = 0x14C; +/// Dynamic depth-bias override from `RSSetDepthBiasX`, stored as canonical f32 bits for hashing. +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)] +pub(super) struct DepthBias { + pub bias: u32, + pub clamp: u32, + pub slope: u32, +} + +impl DepthBias { + pub(super) const ZERO: Self = Self { bias: 0, clamp: 0, slope: 0 }; + + fn canon(v: f32) -> u32 { + if v == 0.0 { + 0.0f32.to_bits() + } else { + v.to_bits() + } + } + + pub(super) fn new(bias: f32, clamp: f32, slope: f32) -> Self { + Self { bias: Self::canon(bias), clamp: Self::canon(clamp), slope: Self::canon(slope) } + } + + pub(super) fn is_zero(self) -> bool { + self == Self::ZERO + } + + pub(super) fn depth_bias(self) -> f32 { + f32::from_bits(self.bias) + } + + pub(super) fn depth_bias_clamp(self) -> f32 { + f32::from_bits(self.clamp) + } + + pub(super) fn slope_scaled_depth_bias(self) -> f32 { + f32::from_bits(self.slope) + } + + pub(super) fn from_desc(d: &[u8; GFX_DESC]) -> Self { + let bias = i32::from_le_bytes(d[RASTERIZER_DEPTH_BIAS..RASTERIZER_DEPTH_BIAS + 4].try_into().unwrap()) as f32; + let clamp = f32::from_le_bytes(d[RASTERIZER_DEPTH_BIAS_CLAMP..RASTERIZER_DEPTH_BIAS_CLAMP + 4].try_into().unwrap()); + let slope = f32::from_le_bytes(d[RASTERIZER_SLOPE_SCALED_DEPTH_BIAS..RASTERIZER_SLOPE_SCALED_DEPTH_BIAS + 4].try_into().unwrap()); + Self::new(bias, clamp, slope) + } + + pub(super) fn patch_desc(self, d: &mut [u8; GFX_DESC]) { + let bias_i32 = self.depth_bias().round() as i32; + d[RASTERIZER_DEPTH_BIAS..RASTERIZER_DEPTH_BIAS + 4].copy_from_slice(&bias_i32.to_le_bytes()); + d[RASTERIZER_DEPTH_BIAS_CLAMP..RASTERIZER_DEPTH_BIAS_CLAMP + 4].copy_from_slice(&self.clamp.to_le_bytes()); + d[RASTERIZER_SLOPE_SCALED_DEPTH_BIAS..RASTERIZER_SLOPE_SCALED_DEPTH_BIAS + 4].copy_from_slice(&self.slope.to_le_bytes()); + } +} + +fn enable_dynamic_depth_bias(d: &mut [u8; GFX_DESC]) { + let flags = rd32(d, PSO_FLAGS) | FLAG_DYNAMIC_DEPTH_BIAS; + d[PSO_FLAGS..PSO_FLAGS + 4].copy_from_slice(&flags.to_le_bytes()); +} + +fn clear_dynamic_depth_bias(d: &mut [u8; GFX_DESC]) { + let flags = rd32(d, PSO_FLAGS) & !FLAG_DYNAMIC_DEPTH_BIAS; + d[PSO_FLAGS..PSO_FLAGS + 4].copy_from_slice(&flags.to_le_bytes()); +} + /// A graphics pipeline desc as bytes, aligned like the struct for the runtime's reads. #[repr(C, align(8))] #[derive(Clone, Copy)] struct GfxDesc([u8; GFX_DESC]); -/// A title graphics pipeline's description, kept for CreateDerivedPipelineStateX. The input -/// layout is copied; the shaders stay the title's and are checked by hash when a pipeline is -/// derived from it. +/// A title graphics pipeline's description, kept for CreateDerivedPipelineStateX and the +/// patched-PSO fallback of RSSetDepthBiasX. The input layout is copied; the shaders stay the +/// title's and are checked by hash when a pipeline is derived from it. struct Base { desc: GfxDesc, shaders: [u64; 5], + /// Whether this PSO was created with `D3D12_PIPELINE_STATE_FLAG_DYNAMIC_DEPTH_BIAS`. + dynamic_depth_bias: bool, + /// Original static `RasterizerState.{DepthBias, DepthBiasClamp, SlopeScaledDepthBias}`. + static_bias: DepthBias, _elems: Vec<[u8; 32]>, _names: Vec, } @@ -163,6 +315,9 @@ unsafe impl Send for Base {} unsafe impl Sync for Base {} static BASES: Mutex>>> = Mutex::new(None); +/// Cached derived PSOs for `RSSetDepthBiasX`: (base PSO, override) → owned derived PSO. +/// Released when the base PSO is released in `forget_base`. +static DEPTH_BIAS_PSOS: Mutex>> = Mutex::new(None); fn rd32(d: &[u8], o: usize) -> u32 { u32::from_le_bytes(d[o..o + 4].try_into().unwrap()) @@ -188,7 +343,7 @@ unsafe fn stage_hashes(d: &[u8; GFX_DESC]) -> Option<[u64; 5]> { } /// Remember a title graphics pipeline's description (not with stream output). -unsafe fn note_base(pso: *mut c_void, desc: *const c_void) { +unsafe fn note_base(pso: *mut c_void, desc: *const c_void, dynamic_depth_bias: bool) { if pso.is_null() || desc.is_null() || !crate::gpu::shader::readable(desc as usize, GFX_DESC) { return; } @@ -197,6 +352,7 @@ unsafe fn note_base(pso: *mut c_void, desc: *const c_void) { return; } let Some(shaders) = stage_hashes(&d.0) else { return }; + let static_bias = DepthBias::from_desc(&d.0); let (p, n) = (rd64(&d.0, INPUT_LAYOUT) as usize, rd32(&d.0, INPUT_LAYOUT + 8) as usize); let (mut elems, mut names) = (Vec::new(), Vec::new()); if n > 0 { @@ -216,15 +372,122 @@ unsafe fn note_base(pso: *mut c_void, desc: *const c_void) { let at = if elems.is_empty() { 0 } else { elems.as_ptr() as u64 }; d.0[INPUT_LAYOUT..INPUT_LAYOUT + 8].copy_from_slice(&at.to_le_bytes()); d.0[CACHED_PSO..CACHED_PSO + 16].fill(0); - let base = Arc::new(Base { desc: d, shaders, _elems: elems, _names: names }); + let base = Arc::new(Base { desc: d, shaders, dynamic_depth_bias, static_bias, _elems: elems, _names: names }); BASES.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso as usize, base); } -/// A pipeline released for good is no longer a base. +/// Depth-bias metadata for a tracked graphics PSO: `(created_with_dynamic_depth_bias, static_bias)`. +pub(super) fn base_depth_bias_info(pso: usize) -> Option<(bool, DepthBias)> { + if pso == 0 { + return None; + } + BASES.lock().unwrap().as_ref()?.get(&pso).map(|b| (b.dynamic_depth_bias, b.static_bias)) +} + +#[cfg(test)] +pub(super) fn depth_bias_cache_len() -> usize { + DEPTH_BIAS_PSOS.lock().unwrap().as_ref().map_or(0, HashMap::len) +} + +#[cfg(test)] +pub(super) fn register_test_base(pso: usize, dynamic_depth_bias: bool, static_bias: DepthBias) { + let base = Arc::new(Base { + desc: GfxDesc([0u8; GFX_DESC]), + shaders: [0; 5], + dynamic_depth_bias, + static_bias, + _elems: Vec::new(), + _names: Vec::new(), + }); + BASES.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, base); +} + +/// A pipeline released for good is no longer a base; its cached depth-bias variants go with it. pub(super) fn forget_base(pso: usize) { if let Some(m) = BASES.lock().unwrap().as_mut() { m.remove(&pso); } + let gone: Vec = { + let mut g = DEPTH_BIAS_PSOS.lock().unwrap(); + match g.as_mut() { + Some(m) => { + let mut out = Vec::new(); + m.retain(|&(base, _), &mut derived| { + if base == pso { + out.push(derived); + false + } else { + true + } + }); + out + } + None => Vec::new(), + } + }; + // release outside the lock: pso_release calls forget_pso -> forget_base on each derived PSO + for derived in gone { + super::pso_async::release(derived); + } +} + +/// Derive (or reuse from cache) a graphics PSO from `base` with patched rasterizer depth-bias +/// fields for `RSSetDepthBiasX`. Returns `None` if `base` is unknown, its shaders are gone, +/// the cache cap is reached, or creation fails. +pub(super) unsafe fn depth_bias_pso(dev: *mut c_void, base: usize, bias: DepthBias) -> Option { + static N: AtomicU64 = AtomicU64::new(0); + if dev.is_null() || base == 0 { + return None; + } + if let Some(&cached) = DEPTH_BIAS_PSOS.lock().unwrap().as_ref().and_then(|m| m.get(&(base, bias))) { + return Some(cached); + } + let b = BASES.lock().unwrap().as_ref().and_then(|m| m.get(&base).cloned())?; + if stage_hashes(&b.desc.0) != Some(b.shaders) { + if once(&N, 4) { + crate::xlog_warn!("D3D12.X: RSSetDepthBiasX – shaders of base pipeline {base:#x} are gone"); + } + return None; + } + let mut d = b.desc; + clear_dynamic_depth_bias(&mut d.0); + bias.patch_desc(&mut d.0); + let mut out: *mut c_void = std::ptr::null_mut(); + let hr = real::dev_create_graphics_pso(dev, d.0.as_ptr() as *const c_void, &IID_PIPELINE_STATE, &mut out); + if hr < 0 || out.is_null() { + if once(&N, 4) { + crate::xlog_warn!("D3D12.X: RSSetDepthBiasX – deriving pipeline from {base:#x} failed ({hr:#x})"); + } + return None; + } + let derived = out as usize; + let mut release_extra = 0usize; + let result = { + // re-check base liveness so we never leak a derived PSO for a concurrently released base + let alive = BASES.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&base)); + let mut g = DEPTH_BIAS_PSOS.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + if !alive { + release_extra = derived; + None + } else if let Some(&existing) = map.get(&(base, bias)) { + release_extra = derived; + Some(existing) + } else if map.len() >= MAX_DEPTH_BIAS_PSOS { + if once(&N, 1) { + crate::xlog_warn!("D3D12.X: RSSetDepthBiasX – derived PSO cache full ({MAX_DEPTH_BIAS_PSOS})"); + } + release_extra = derived; + None + } else { + map.insert((base, bias), derived); + Some(derived) + } + }; + if release_extra != 0 { + super::pso_async::release(release_extra); + } + result } /// Apply one CreateDerivedPipelineStateX patch to a desc: part 0 = depth-stencil state, 1 = @@ -289,11 +552,7 @@ pub(super) unsafe extern "system" fn create_derived_pso_x(this: *mut c_void, bas } } let desc = d.0.as_ptr() as *const c_void; - let hr = real::dev_create_graphics_pso(this, desc, riid, ppv); - if hr >= 0 { - note_base(*ppv, desc); - } - hr + create_graphics_pso_tracked(this, desc, riid, ppv) } /// device #86 CreatePipelineState(stream desc, riid, pipeline) @@ -600,6 +859,47 @@ mod tests { assert_eq!(apply_patch(&mut d, &patch), Err(4)); } + #[test] + fn depth_bias_patches_rasterizer_fields() { + use std::mem::offset_of; + type G = D3D12_GRAPHICS_PIPELINE_STATE_DESC; + let rast = offset_of!(G, RasterizerState); + assert_eq!(RASTERIZER_DEPTH_BIAS, rast + offset_of!(D3D12_RASTERIZER_DESC, DepthBias)); + assert_eq!(RASTERIZER_DEPTH_BIAS_CLAMP, rast + offset_of!(D3D12_RASTERIZER_DESC, DepthBiasClamp)); + assert_eq!(RASTERIZER_SLOPE_SCALED_DEPTH_BIAS, rast + offset_of!(D3D12_RASTERIZER_DESC, SlopeScaledDepthBias)); + assert_eq!(PSO_FLAGS, offset_of!(G, Flags)); + assert_eq!(FLAG_DYNAMIC_DEPTH_BIAS, 4); + + // -0.0 canonicalizes to +0.0 so zero checks and cache keys agree + let z = DepthBias::new(-0.0, 0.0, -0.0); + assert!(z.is_zero()); + assert_eq!(z, DepthBias::new(0.0, 0.0, 0.0)); + + let b = DepthBias::new(-125.6, 0.05, 1.5); + assert!(!b.is_zero()); + assert_eq!(b.depth_bias(), -125.6); + assert_eq!(b.depth_bias_clamp(), 0.05); + assert_eq!(b.slope_scaled_depth_bias(), 1.5); + let mut d = [0x55u8; GFX_DESC]; + b.patch_desc(&mut d); + assert_eq!(i32::from_le_bytes(d[RASTERIZER_DEPTH_BIAS..RASTERIZER_DEPTH_BIAS + 4].try_into().unwrap()), -126); + assert_eq!(f32::from_le_bytes(d[RASTERIZER_DEPTH_BIAS_CLAMP..RASTERIZER_DEPTH_BIAS_CLAMP + 4].try_into().unwrap()), 0.05); + assert_eq!(f32::from_le_bytes(d[RASTERIZER_SLOPE_SCALED_DEPTH_BIAS..RASTERIZER_SLOPE_SCALED_DEPTH_BIAS + 4].try_into().unwrap()), 1.5); + // from_desc recovers the baked rasterizer fields + assert_eq!(DepthBias::from_desc(&d), DepthBias::new(-126.0, 0.05, 1.5)); + // untouched bytes before and after the 12-byte depth-bias slice + assert!(d[..RASTERIZER_DEPTH_BIAS].iter().all(|&x| x == 0x55)); + assert!(d[RASTERIZER_SLOPE_SCALED_DEPTH_BIAS + 4..].iter().all(|&x| x == 0x55)); + + // enable / clear D3D12_PIPELINE_STATE_FLAG_DYNAMIC_DEPTH_BIAS touches only bit 2 of Flags + let mut f = [0u8; GFX_DESC]; + f[PSO_FLAGS..PSO_FLAGS + 4].copy_from_slice(&1u32.to_le_bytes()); + enable_dynamic_depth_bias(&mut f); + assert_eq!(rd32(&f, PSO_FLAGS), 1 | FLAG_DYNAMIC_DEPTH_BIAS); + clear_dynamic_depth_bias(&mut f); + assert_eq!(rd32(&f, PSO_FLAGS), 1); + } + #[test] fn page_pools_register_once_and_unregister() { unsafe { diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 6565db9..1deae2d 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3,10 +3,11 @@ //! The console's ID3D12GraphicsCommandList keeps the PC methods (some moved: //! `real::console_remap`) and holds console extensions from #60 on (as observed on Fortnite): //! CopyMemoryToMemoryX #60, FillMemoryWith{32,64,128}BitValueX #61–#63, depth bounds #68, -//! Write{32,64}BitValueBottomOfPipeX #69 / #70, DispatchX #78, DrawIndexedX #81, -//! CopyResourceX #84, SetPredicationBufferX #85, Write{32,64}BitValueTopOfPipeX #88 / #89, -//! Write32BitValueBottomOfShaderX #90. A title call of any other extension (waits on memory, -//! GDS, KickoffX, depth bias, hints…) is logged and does nothing (`real::class_for`). +//! Write{32,64}BitValueBottomOfPipeX #69 / #70, Wait{32,64}BitValueX #71 / #72, +//! DispatchX #78, DrawIndexedX #81, CopyResourceX #84, SetPredicationBufferX #85, +//! Write{32,64}BitValueTopOfPipeX #88 / #89, Write32BitValueBottomOfShaderX #90, +//! KickoffX #93, RSSetDepthBiasX #94. A title call of any other extension (GDS, hints…) +//! is logged and does nothing (`real::class_for`). //! //! Occlusion queries may nest on the console; the PC allows one active per list. When one //! begins while another is active, the outer one ends there on the PC and resolves as visible; @@ -19,21 +20,25 @@ use std::collections::HashMap; use std::ffi::c_void; use std::mem::{transmute_copy, ManuallyDrop}; -use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; use std::sync::Mutex; +use std::time::{Duration, Instant}; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; +use super::device_x::{self, DepthBias}; use super::real; const PC_GET_TYPE: usize = 8; +const PC_CLOSE: usize = 9; const PC_RESET: usize = 10; const PC_DRAW_INDEXED: usize = 13; const PC_COPY_BUFFER_REGION: usize = 15; const PC_COPY_TEXTURE_REGION: usize = 16; const PC_COPY_RESOURCE: usize = 17; +const PC_SET_PIPELINE_STATE: usize = 25; const PC_RESOURCE_BARRIER: usize = 26; const PC_IA_SET_INDEX_BUFFER: usize = 43; const PC_BEGIN_QUERY: usize = 52; @@ -42,6 +47,7 @@ const PC_RESOLVE_QUERY_DATA: usize = 54; const PC_SET_PREDICATION: usize = 55; const PC_OM_SET_DEPTH_BOUNDS: usize = 62; const PC_WRITE_BUFFER_IMMEDIATE: usize = 66; +const PC_QUEUE_EXECUTE_COMMAND_LISTS: usize = 10; /// Write64BitValueBottomOfPipeX flags 1 / 2, Write64BitValueTopOfPipeX flags 4 / 8: the value /// written is a GPU / system timestamp @@ -49,6 +55,10 @@ const BOTTOM_TIMESTAMPS: u32 = 0x3; const TOP_TIMESTAMPS: u32 = 0xC; /// fills larger than this are not done (one pattern buffer per value, up to this size) const MAX_FILL: u64 = 256 << 20; +/// Bounded wait timeout for Wait32BitValueX / Wait64BitValueX so an unsatisfied wait never hangs. +const WAIT_TIMEOUT: Duration = Duration::from_secs(2); +/// Cap on tracked per-list written UMA ranges (for same-list write-then-wait detection). +const MAX_WRITTEN_RANGES: usize = 256; fn once(counter: &AtomicU64, n: u64) -> bool { counter.fetch_add(1, Ordering::Relaxed) < n @@ -96,6 +106,488 @@ fn warn(counter: &AtomicU64, what: &str, why: std::fmt::Arguments) { } } +// --------------------------------------------------------------------------------------- +// per-list state & live queue tracking (KickoffX, Wait32/64BitValueX, RSSetDepthBiasX, +// index buffer restoration, nested occlusion queries) +// --------------------------------------------------------------------------------------- + +/// a query: (heap, index) +type Query = (usize, u32); + +/// One list's occlusion queries: the one active on the PC (with its type) and the outer ones +/// it ended early. +#[derive(Default)] +struct Occlusion { + active: Option<(Query, D3D12_QUERY_TYPE)>, + ended_early: Vec, +} + +impl Occlusion { + /// Begin `q` on the PC; Some(outer): end that one on the PC first. + fn begin(&mut self, q: Query, ty: D3D12_QUERY_TYPE) -> Option<(Query, D3D12_QUERY_TYPE)> { + let outer = self.active.replace((q, ty)); + if let Some((o, _)) = outer { + self.ended_early.push(o); + } + outer + } + + /// End the currently active PC query early (e.g. before a `KickoffX` split), so `EndQuery` + /// later resolves it as visible. + fn end_active_early(&mut self) -> Option<(Query, D3D12_QUERY_TYPE)> { + let active = self.active.take()?; + self.ended_early.push(active.0); + Some(active) + } + + /// Whether the PC ends `q` (not: an outer one already ended – it resolves as visible). + fn end(&mut self, q: Query) -> bool { + if self.active.is_some_and(|(a, _)| a == q) { + self.active = None; + return true; + } + match self.ended_early.iter().position(|e| *e == q) { + Some(i) => { + self.ended_early.swap_remove(i); + false + } + None => true, + } + } +} + +/// Recorded GPU-side memory wait from `Wait32BitValueX` (#71) or `Wait64BitValueX` (#72). +/// Evaluates `(mem_value & mask) value` using `D3D12_COMPARISON_FUNC` (1..=8), +/// matching AMD PM4 `WAIT_REG_MEM` semantics. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct PendingWait { + va: u64, + width: u8, // 4 or 8 + comparison: u32, + value: u64, + mask: u64, +} + +fn compare_u64(op: u32, lhs: u64, rhs: u64) -> Option { + match op { + 1 => Some(false), // D3D12_COMPARISON_FUNC_NEVER + 2 => Some(lhs < rhs), // D3D12_COMPARISON_FUNC_LESS + 3 => Some(lhs == rhs), // D3D12_COMPARISON_FUNC_EQUAL + 4 => Some(lhs <= rhs), // D3D12_COMPARISON_FUNC_LESS_EQUAL + 5 => Some(lhs > rhs), // D3D12_COMPARISON_FUNC_GREATER + 6 => Some(lhs != rhs), // D3D12_COMPARISON_FUNC_NOT_EQUAL + 7 => Some(lhs >= rhs), // D3D12_COMPARISON_FUNC_GREATER_EQUAL + 8 => Some(true), // D3D12_COMPARISON_FUNC_ALWAYS + _ => None, + } +} + +impl PendingWait { + unsafe fn read_value(&self) -> Option { + let addr = self.va as usize; + if !crate::gpu::shader::readable(addr, self.width as usize) { + return None; + } + match self.width { + 4 => Some((*(addr as *const AtomicU32)).load(Ordering::Acquire) as u64), + 8 => Some((*(addr as *const AtomicU64)).load(Ordering::Acquire)), + _ => None, + } + } + + unsafe fn is_satisfied(&self) -> bool { + let Some(cur) = self.read_value() else { + return true; + }; + compare_u64(self.comparison, cur & self.mask, self.value).unwrap_or(true) + } + + unsafe fn wait_until_satisfied(&self, timeout: Duration) -> bool { + if self.is_satisfied() { + return true; + } + for _ in 0..512 { + std::hint::spin_loop(); + if self.is_satisfied() { + return true; + } + } + let start = Instant::now(); + while start.elapsed() < timeout { + let step = if start.elapsed() < Duration::from_millis(10) { + Duration::from_micros(100) + } else { + Duration::from_millis(1) + }; + std::thread::sleep(step); + if self.is_satisfied() { + return true; + } + } + self.is_satisfied() + } +} + +#[derive(Default)] +struct ListState { + allocator: usize, + list_type: Option, + last_queue: Option, + /// Title's currently bound PSO (before dynamic depth-bias override) + bound_pso: usize, + /// Active `RSSetDepthBiasX` override (None = zero / disabled) + depth_bias: Option, + /// Last depth bias sent to `ID3D12GraphicsCommandList9::RSSetDepthBias` on this PC list + /// since CreateCommandList / Reset / ClearState / KickoffX (resets to ZERO on each). + native_bias: DepthBias, + /// True when the PC list's bound PSO needs patching via the fallback cache before the next draw + pso_dirty: bool, + /// True when a fallback depth-bias derived PSO is currently bound on the PC list + using_fallback_pso: bool, + /// Bound index buffer (PC address), restored after `DrawIndexedX` and `KickoffX` + index_buffer: Option, + /// Last `OMSetDepthBounds` values, restored after `KickoffX` + depth_bounds: Option<(f32, f32)>, + occlusion: Occlusion, + /// UMA address ranges written by this list since last Reset/KickoffX + written_ranges: Vec<(u64, u64)>, + /// External memory waits recorded on this list + pending_waits: Vec, +} + +impl ListState { + fn note_write(&mut self, va: u64, size: u64) { + if size == 0 { + return; + } + let end = va.saturating_add(size); + if self.written_ranges.len() < MAX_WRITTEN_RANGES { + self.written_ranges.push((va, end)); + } else if let Some(last) = self.written_ranges.last_mut() { + last.0 = last.0.min(va); + last.1 = last.1.max(end); + } + } + + fn has_prior_write(&self, va: u64, size: u64) -> bool { + let end = va.saturating_add(size); + self.written_ranges.iter().any(|&(s, e)| va < e && s < end) + } + + fn clear_waits(&mut self) { + if !self.pending_waits.is_empty() { + self.pending_waits.clear(); + PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); + } + } + + fn push_wait(&mut self, w: PendingWait) { + if self.pending_waits.is_empty() { + PENDING_WAIT_LISTS.fetch_add(1, Ordering::AcqRel); + } + self.pending_waits.push(w); + } +} + +#[derive(Clone, Copy)] +struct QueueInfo { + queue: usize, + device: usize, + ty: D3D12_COMMAND_LIST_TYPE, +} + +static LISTS: Mutex>> = Mutex::new(None); +static LIVE_QUEUES: Mutex> = Mutex::new(Vec::new()); +/// Number of lists with at least one pending `Wait32/64BitValueX` (fast-path guard for ExecuteCommandLists). +static PENDING_WAIT_LISTS: AtomicUsize = AtomicUsize::new(0); +/// Set once any list uses `RSSetDepthBiasX` (fast-path guard for Draw* hooks). +static DEPTH_BIAS_USED: AtomicBool = AtomicBool::new(false); + +/// Record a newly created title command queue so `KickoffX` can find a compatible queue. +pub(super) fn on_queue_create(queue: usize, device: usize, ty: D3D12_COMMAND_LIST_TYPE) { + if queue == 0 { + return; + } + let mut g = LIVE_QUEUES.lock().unwrap(); + g.retain(|q| q.queue != queue); + g.push(QueueInfo { queue, device, ty }); +} + +/// Remove a released command queue so `KickoffX` never submits to a dead queue. +pub(super) fn on_queue_release(queue: usize) { + LIVE_QUEUES.lock().unwrap().retain(|q| q.queue != queue); + if let Some(m) = LISTS.lock().unwrap().as_mut() { + for s in m.values_mut() { + if s.last_queue == Some(queue) { + s.last_queue = None; + } + } + } +} + +#[cfg(test)] +thread_local! { + /// Optional test interceptor for `try_native_depth_bias` so unit tests deterministically + /// verify the native `ID3D12GraphicsCommandList9::RSSetDepthBias` path and its fallback + /// even on Windows builds whose inbox D3D12Core.dll stops at `ID3D12GraphicsCommandList7`. + static TEST_NATIVE_BIAS: std::cell::RefCell bool>>> = const { std::cell::RefCell::new(None) }; +} + +/// Apply depth bias natively via `ID3D12GraphicsCommandList9::RSSetDepthBias` (exact f32, +/// without rounding to i32 or deriving a patched PSO). Returns `false` if unavailable. +unsafe fn try_native_depth_bias(list: *mut c_void, bias: DepthBias) -> bool { + if list.is_null() { + return false; + } + #[cfg(test)] + if let Some(res) = TEST_NATIVE_BIAS.with(|h| h.borrow_mut().as_mut().map(|f| f(list as usize, bias))) { + return res; + } + let Some(cl) = ID3D12GraphicsCommandList::from_raw_borrowed(&list) else { + return false; + }; + let Ok(cl9) = cl.cast::() else { + return false; + }; + cl9.RSSetDepthBias(bias.depth_bias(), bias.depth_bias_clamp(), bias.slope_scaled_depth_bias()); + true +} + +/// Record a newly created command list's allocator, initial pipeline, and type. +pub(super) unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_COMMAND_LIST_TYPE) { + if list.is_null() { + return; + } + let key = list as usize; + { + let mut g = LISTS.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + if let Some(old) = m.remove(&key) { + if !old.pending_waits.is_empty() { + PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); + } + } + m.insert(key, ListState { allocator: alloc, list_type: Some(ty), bound_pso: pso, ..Default::default() }); + } + // Dynamic-depth-bias PSOs ignore baked RasterizerState depth bias; seed the list with the + // initial PSO's static bias if non-zero (CreateCommandList resets RSSetDepthBias to 0). + if ty != D3D12_COMMAND_LIST_TYPE_BUNDLE && pso != 0 { + if let Some((true, static_bias)) = device_x::base_depth_bias_info(pso) { + if !static_bias.is_zero() && try_native_depth_bias(list, static_bias) { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&key)) { + s.native_bias = static_bias; + } + } + } + } +} + +/// Clean up all tracked state when a command list is released for good. +pub(super) fn on_release(list: usize) { + if let Some(old) = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&list)) { + if !old.pending_waits.is_empty() { + PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); + } + } +} + +/// Forget a released command allocator so `KickoffX` will not reset a list with a dead allocator. +pub(super) fn on_allocator_release(alloc: usize) { + if let Some(m) = LISTS.lock().unwrap().as_mut() { + for s in m.values_mut() { + if s.allocator == alloc { + s.allocator = 0; + } + } + } +} + +/// Track `SetPipelineState` on a command list (for `RSSetDepthBiasX` and `KickoffX`), +/// syncing `ID3D12GraphicsCommandList9::RSSetDepthBias` when the bound PSO uses native dynamic +/// depth bias. +pub(super) unsafe fn on_set_pipeline_state(list: *mut c_void, pso: usize) { + let key = list as usize; + let sync_target = { + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(key).or_default(); + // Keep the title-visible base PSO key when `bind_abi` re-binds its resolved background PSO. + if s.bound_pso == 0 || pso == s.bound_pso || super::pso_async::resolve(s.bound_pso) != pso { + s.bound_pso = pso; + } + let effective = s.bound_pso; + s.using_fallback_pso = false; + let is_bundle = s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE); + let info = if effective != 0 { device_x::base_depth_bias_info(effective) } else { None }; + if !is_bundle { + if let Some((true, static_bias)) = info { + let target = s.depth_bias.unwrap_or(static_bias); + s.pso_dirty = false; + if target != s.native_bias { + Some((target, s.depth_bias.is_some())) + } else { + None + } + } else { + s.pso_dirty = s.depth_bias.is_some(); + if s.pso_dirty { + DEPTH_BIAS_USED.store(true, Ordering::Release); + } + None + } + } else { + s.pso_dirty = s.depth_bias.is_some(); + if s.pso_dirty { + DEPTH_BIAS_USED.store(true, Ordering::Release); + } + None + } + }; + if let Some((target, has_override)) = sync_target { + if try_native_depth_bias(list, target) { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&key)) { + s.native_bias = target; + } + } else if has_override { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&key)) { + s.pso_dirty = true; + } + DEPTH_BIAS_USED.store(true, Ordering::Release); + } + } +} + +/// Track `ClearState` on a command list: resets dynamic state and binds `pso`. +pub(super) unsafe fn on_clear_state(list: *mut c_void, pso: usize) { + let key = list as usize; + let is_bundle = { + let mut g = LISTS.lock().unwrap(); + if let Some(s) = g.get_or_insert_with(HashMap::new).get_mut(&key) { + s.bound_pso = pso; + s.depth_bias = None; + s.native_bias = DepthBias::ZERO; + s.pso_dirty = false; + s.using_fallback_pso = false; + s.index_buffer = None; + s.depth_bounds = None; + s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) + } else { + false + } + }; + if !is_bundle && pso != 0 { + if let Some((true, static_bias)) = device_x::base_depth_bias_info(pso) { + if !static_bias.is_zero() && try_native_depth_bias(list, static_bias) { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&key)) { + s.native_bias = static_bias; + } + } + } + } +} + +/// Associate executed lists with `queue` and keep `queue` at the head of `LIVE_QUEUES`. +pub(super) unsafe fn note_queue_for_lists(queue: usize, lists: &[*mut c_void]) { + if queue == 0 { + return; + } + { + let mut g = LIVE_QUEUES.lock().unwrap(); + if let Some(pos) = g.iter().position(|q| q.queue == queue) { + let info = g.remove(pos); + g.push(info); + } else { + let raw = queue as *mut c_void; + if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&raw) { + let ty = q.GetDesc().Type; + let mut dev: Option = None; + let dev_raw = if q.GetDevice(&mut dev).is_ok() { + dev.as_ref().map_or(0, |d| d.as_raw() as usize) + } else { + 0 + }; + g.push(QueueInfo { queue, device: dev_raw, ty }); + } + } + } + let mut g = LISTS.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + for &l in lists { + if !l.is_null() { + m.entry(l as usize).or_default().last_queue = Some(queue); + } + } +} + +fn pick_queue(last_queue: Option, device: usize, ty: D3D12_COMMAND_LIST_TYPE) -> Option { + let g = LIVE_QUEUES.lock().unwrap(); + if let Some(q) = last_queue { + if g.iter().any(|info| info.queue == q) { + return Some(q); + } + } + g.iter().rev().find(|info| info.ty == ty && (device == 0 || info.device == 0 || info.device == device)).map(|info| info.queue) +} + +fn note_write(list: usize, va: u64, size: u64) { + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().note_write(va, size); +} + +unsafe fn wait_all(waits: &[PendingWait]) { + static TIMEOUTS: AtomicU64 = AtomicU64::new(0); + for w in waits { + if !w.wait_until_satisfied(WAIT_TIMEOUT) && once(&TIMEOUTS, 4) { + crate::xlog_warn!( + "D3D12.X: Wait{}BitValueX timed out after {} ms at {:#x} (op {}, want {:#x}, mask {:#x})", + w.width * 8, + WAIT_TIMEOUT.as_millis(), + w.va, + w.comparison, + w.value, + w.mask + ); + } + } +} + +/// Submit `lists` through `submit`, splitting the batch before any list whose `Wait32/64BitValueX` +/// condition is not yet satisfied so earlier lists in the same batch can run on the GPU first. +pub(super) unsafe fn execute_with_waits(lists: &[*mut c_void], mut submit: impl FnMut(&[*mut c_void])) { + if lists.is_empty() || PENDING_WAIT_LISTS.load(Ordering::Acquire) == 0 { + submit(lists); + return; + } + let per_list: Vec> = { + let g = LISTS.lock().unwrap(); + lists + .iter() + .map(|&l| { + g.as_ref() + .and_then(|m| m.get(&(l as usize))) + .map(|s| s.pending_waits.clone()) + .unwrap_or_default() + }) + .collect() + }; + let mut start = 0usize; + for (i, waits) in per_list.iter().enumerate() { + if waits.is_empty() || waits.iter().all(|w| w.is_satisfied()) { + continue; + } + if i > start { + submit(&lists[start..i]); + } + wait_all(waits); + start = i; + } + if start < lists.len() { + submit(&lists[start..]); + } +} + +// --------------------------------------------------------------------------------------- +// memory copy / fill / immediate write / timestamp +// --------------------------------------------------------------------------------------- + /// command list #60 CopyMemoryToMemoryX(destination, source, size, flags) pub(super) unsafe extern "system" fn copy_memory_x(this: *mut c_void, dst: u64, src: u64, size: u64, _flags: u32) { static N: AtomicU64 = AtomicU64::new(0); @@ -109,6 +601,7 @@ pub(super) unsafe extern "system" fn copy_memory_x(this: *mut c_void, dst: u64, if d == s && dst < src + size && src < dst + size { return warn(&N, W, format_args!("{src:#x} → {dst:#x} ({size:#x} bytes) overlap")); } + note_write(this as usize, dst, size); if d == s { // one window: the buffer is the source and the destination (the ranges do not overlap) as_copy_dest(this, d, || copy_buffer_region(this, d, doff, s, soff, size)); @@ -183,6 +676,7 @@ unsafe fn fill(list: *mut c_void, va: u64, size: u64, pat: [u8; 16], unit: u64, let Some(src) = pattern_buffer(list, pat, size) else { return warn(&N, what, format_args!("no pattern buffer for {pat:x?}")); }; + note_write(list as usize, va, size); as_copy_dest(list, d, || copy_buffer_region(list, d, off, src, 0, size)); } @@ -222,6 +716,7 @@ unsafe fn write(list: *mut c_void, va: u64, words: &[u32], mode: D3D12_WRITEBUFF let (Some((d, _)), Some(at)) = (real::uma_window_buffer(va as usize, n as usize), real::uma_va_of(va as usize)) else { return warn(&N, what, format_args!("{va:#x} is not in unified memory")); }; + note_write(list as usize, va, n); let params: Vec = words.iter().enumerate().map(|(i, &w)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: at + 4 * i as u64, Value: w }).collect(); let modes = vec![mode; words.len()]; type F = unsafe extern "system" fn(*mut c_void, u32, *const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, *const D3D12_WRITEBUFFERIMMEDIATE_MODE); @@ -257,6 +752,7 @@ unsafe fn timestamp(list: *mut c_void, va: u64, what: &str) { } m[&(dev.as_raw() as usize)].as_raw() as usize }; + note_write(list as usize, va, 8); let i = NEXT_TIMESTAMP.fetch_add(1, Ordering::Relaxed) % TIMESTAMP_SLOTS; pc::(list, PC_END_QUERY)(list, heap, D3D12_QUERY_TYPE_TIMESTAMP, i); type Resolve = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32, u32, usize, u64); @@ -277,6 +773,49 @@ pub(super) unsafe extern "system" fn write64_bottom_x(this: *mut c_void, va: u64 write(this, va, &[value as u32, (value >> 32) as u32], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT, W); } +/// Record a `Wait32BitValueX` or `Wait64BitValueX` memory wait on `list`. +/// +/// If an earlier write in the same open list already targeted an overlapping UMA range, the +/// `COMMON -> COPY_DEST -> COMMON` barrier around that write already orders subsequent work +/// on the GPU, so we do not stall before submission (which would deadlock waiting on our own +/// unsubmitted list). Otherwise the wait is evaluated on the CPU before `ExecuteCommandLists` +/// (or `KickoffX`) submits the list. +unsafe fn wait_memory(list: *mut c_void, va: u64, width: u8, comparison: u32, value: u64, mask: u64, what: &str) { + static N: AtomicU64 = AtomicU64::new(0); + let n = width as u64; + if !va.is_multiple_of(n) { + return warn(&N, what, format_args!("{va:#x} is not {n}-byte aligned")); + } + if real::uma_window_buffer(va as usize, width as usize).is_none() { + return warn(&N, what, format_args!("{va:#x} is not in unified memory")); + } + if compare_u64(comparison, 0, 0).is_none() { + return warn(&N, what, format_args!("unknown comparison op {comparison}")); + } + if comparison == D3D12_COMPARISON_FUNC_ALWAYS.0 as u32 { + return; + } + if comparison == D3D12_COMPARISON_FUNC_NEVER.0 as u32 { + return warn(&N, what, format_args!("NEVER comparison at {va:#x} (skipped to avoid hang)")); + } + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); + if s.has_prior_write(va, n) { + return; + } + s.push_wait(PendingWait { va, width, comparison, value, mask }); +} + +/// command list #71 Wait32BitValueX(address, comparison, value, mask, flags) +pub(super) unsafe extern "system" fn wait32_x(this: *mut c_void, va: u64, comparison: u32, value: u32, mask: u32, _flags: u32) { + wait_memory(this, va, 4, comparison, value as u64, mask as u64, "Wait32BitValueX"); +} + +/// command list #72 Wait64BitValueX(address, comparison, value, mask, flags) +pub(super) unsafe extern "system" fn wait64_x(this: *mut c_void, va: u64, comparison: u32, value: u64, mask: u64, _flags: u32) { + wait_memory(this, va, 8, comparison, value, mask, "Wait64BitValueX"); +} + /// command list #88 Write32BitValueTopOfPipeX(address, value, flags) pub(super) unsafe extern "system" fn write32_top_x(this: *mut c_void, va: u64, value: u32, _flags: u32) { write(this, va, &[value], D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_IN, "Write32BitValueTopOfPipeX"); @@ -298,6 +837,7 @@ pub(super) unsafe extern "system" fn write32_bottom_of_shader_x(this: *mut c_voi /// command list #68 OMSetDepthBounds(min, max) (PC #62) pub(super) unsafe extern "system" fn set_depth_bounds_x(this: *mut c_void, min: f32, max: f32) { + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(this as usize).or_default().depth_bounds = Some((min, max)); pc::(this, PC_OM_SET_DEPTH_BOUNDS)(this, min, max); } @@ -331,8 +871,265 @@ pub(super) unsafe extern "system" fn set_predication_buffer_x(this: *mut c_void, transition(this, b, D3D12_RESOURCE_STATE_PREDICATION, D3D12_RESOURCE_STATE_COMMON); } -/// the index buffer each list has bound (PC addresses), for DrawIndexedX to restore -static INDEX_BUFFERS: Mutex>> = Mutex::new(None); +/// command list #93 KickoffX(): flush commands recorded so far by closing the list, submitting +/// it to a compatible live command queue, and resetting it on the same command allocator so +/// recording can continue seamlessly until the title's normal `Close` + `ExecuteCommandLists`. +/// +/// If no compatible queue or allocator is known yet (e.g. a bundle, or a list created before +/// any queue of its type exists), `KickoffX` is a safe logged no-op and the recorded work runs +/// at `Close` + `ExecuteCommandLists`. +pub(super) unsafe extern "system" fn kickoff_x(this: *mut c_void) { + static NO_QUEUE: AtomicU64 = AtomicU64::new(0); + static ERR: AtomicU64 = AtomicU64::new(0); + let ty = list_type(this); + if ty == D3D12_COMMAND_LIST_TYPE_BUNDLE { + return; + } + let dev_raw = device_of(this).map_or(0, |d| d.as_raw() as usize); + let (alloc, queue, bound_pso, depth_bias, index_buffer, depth_bounds, active_query, waits) = { + let mut g = LISTS.lock().unwrap(); + let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(this as usize))) else { + if once(&NO_QUEUE, 4) { + crate::xlog_info!("D3D12.X: KickoffX – list allocator unknown, deferring to Close + ExecuteCommandLists"); + } + return; + }; + if s.allocator == 0 { + if once(&NO_QUEUE, 4) { + crate::xlog_info!("D3D12.X: KickoffX – list allocator unknown, deferring to Close + ExecuteCommandLists"); + } + return; + } + let Some(q) = pick_queue(s.last_queue, dev_raw, s.list_type.unwrap_or(ty)) else { + if once(&NO_QUEUE, 4) { + crate::xlog_info!("D3D12.X: KickoffX – no live queue of type {} yet, deferring to Close + ExecuteCommandLists", ty.0); + } + return; + }; + let active_query = s.occlusion.end_active_early(); + let waits = if s.pending_waits.is_empty() { + Vec::new() + } else { + PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); + std::mem::take(&mut s.pending_waits) + }; + s.written_ranges.clear(); + (s.allocator, q, s.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, active_query, waits) + }; + + // End any active occlusion query before Close (PC forbids closing with an open query). + if let Some(((h, i), qty)) = active_query { + pc::(this, PC_END_QUERY)(this, h, qty, i); + } + + let close_hr = pc:: i32>(this, PC_CLOSE)(this); + if close_hr < 0 { + return warn(&ERR, "KickoffX", format_args!("Close failed ({close_hr:#x})")); + } + + super::title_textures::refresh(); + if !waits.is_empty() { + wait_all(&waits); + } + + let q_raw = queue as *mut c_void; + type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); + let exec: ExecFn = transmute_copy(&real::orig_fn(q_raw, PC_QUEUE_EXECUTE_COMMAND_LISTS)); + let one = [this]; + exec(q_raw, 1, one.as_ptr()); + + let init_pso = super::pso_async::resolve_for_bind(bound_pso); + let ext = *(this as *const usize); + let reset_hr = pc:: i32>(this, PC_RESET)(this, alloc, init_pso); + if *(this as *const usize) != ext { + *(this as *mut usize) = ext; + } + if reset_hr < 0 { + return warn(&ERR, "KickoffX", format_args!("Reset after kickoff failed ({reset_hr:#x})")); + } + + // Reset() cleared the PC list's native RSSetDepthBias state to (0, 0, 0) and bound init_pso. + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { + s.native_bias = DepthBias::ZERO; + s.using_fallback_pso = false; + s.pso_dirty = false; + } + 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(this, target) { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this 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(this, b) { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this 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(&(this as usize))) { + s.pso_dirty = true; + } + DEPTH_BIAS_USED.store(true, Ordering::Release); + } + if let Some(ref view) = index_buffer { + set_index_buffer(this, Some(view)); + } + if let Some((min, max)) = depth_bounds { + pc::(this, PC_OM_SET_DEPTH_BOUNDS)(this, min, max); + } +} + +/// command list #94 RSSetDepthBiasX(depthBias, depthBiasClamp, slopeScaledDepthBias): +/// dynamic depth bias override. Uses `ID3D12GraphicsCommandList9::RSSetDepthBias` natively +/// when `D3D12_FEATURE_D3D12_OPTIONS16::DynamicDepthBiasSupported` and the bound PSO support +/// it (preserving exact `f32` bias with zero PSO derivation), falling back to the patched-PSO +/// cache (`device_x::depth_bias_pso`) otherwise. +pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_bias: f32, depth_bias_clamp: f32, slope_scaled_depth_bias: f32) { + static NON_FINITE: AtomicU64 = AtomicU64::new(0); + let clean = |v: f32| { + if v.is_finite() { + v + } else { + if once(&NON_FINITE, 4) { + crate::xlog_warn!("D3D12.X: RSSetDepthBiasX – non-finite value {v} clamped to 0.0"); + } + 0.0 + } + }; + let bias = DepthBias::new(clean(depth_bias), clean(depth_bias_clamp), clean(slope_scaled_depth_bias)); + let key = this as usize; + + let (bound_pso, is_bundle) = { + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(key).or_default(); + (s.bound_pso, s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE)) + }; + + let can_native = if is_bundle { + false + } else if bound_pso != 0 { + matches!(device_x::base_depth_bias_info(bound_pso), Some((true, _))) + } else { + device_of(this).is_some_and(|dev| device_x::dynamic_depth_bias_supported(dev.as_raw())) + }; + + if can_native { + let target = if bias.is_zero() { DepthBias::ZERO } else { bias }; + let (need_restore_base, need_native_call) = { + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(key).or_default(); + s.depth_bias = if bias.is_zero() { None } else { Some(bias) }; + s.pso_dirty = false; + let restore = s.using_fallback_pso && s.bound_pso != 0; + s.using_fallback_pso = false; + (if restore { Some(s.bound_pso) } else { None }, target != s.native_bias) + }; + if let Some(base) = need_restore_base { + let resolved = super::pso_async::resolve_for_bind(base); + pc::(this, PC_SET_PIPELINE_STATE)(this, resolved); + } + if !need_native_call { + return; + } + if try_native_depth_bias(this, target) { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&key)) { + s.native_bias = target; + } + return; + } + // ID3D12GraphicsCommandList9 unavailable: fall through to patched-PSO fallback. + if !bias.is_zero() { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&key)) { + s.pso_dirty = true; + } + DEPTH_BIAS_USED.store(true, Ordering::Release); + } + return; + } + + let restore = { + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(key).or_default(); + if bias.is_zero() { + let was_active = s.depth_bias.take().is_some(); + let was_fallback = std::mem::take(&mut s.using_fallback_pso); + s.pso_dirty = false; + if (was_active || was_fallback) && s.bound_pso != 0 { + Some(s.bound_pso) + } else { + None + } + } else { + if s.depth_bias != Some(bias) || !s.using_fallback_pso { + s.depth_bias = Some(bias); + s.pso_dirty = true; + DEPTH_BIAS_USED.store(true, Ordering::Release); + } + None + } + }; + if let Some(base) = restore { + let resolved = super::pso_async::resolve_for_bind(base); + pc::(this, PC_SET_PIPELINE_STATE)(this, resolved); + } +} + +/// Apply a pending fallback `RSSetDepthBiasX` override before a draw call on `list`. +pub(super) unsafe fn prepare_draw(list: *mut c_void) { + if !DEPTH_BIAS_USED.load(Ordering::Acquire) { + return; + } + let (bound_pso, bias) = { + let mut g = LISTS.lock().unwrap(); + let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(list as usize))) else { + return; + }; + if !s.pso_dirty { + return; + } + s.pso_dirty = false; + (s.bound_pso, s.depth_bias) + }; + if bound_pso == 0 { + return; + } + let (target, is_fallback) = match bias { + Some(b) => { + static MISS: AtomicU64 = AtomicU64::new(0); + let Some(dev) = device_of(list) else { return }; + match device_x::depth_bias_pso(dev.as_raw(), bound_pso, b) { + Some(derived) => (derived, true), + None => { + if once(&MISS, 4) { + crate::xlog_warn!("D3D12.X: RSSetDepthBiasX – could not derive pipeline for {bound_pso:#x}, using base pipeline"); + } + return; + } + } + } + None => (bound_pso, false), + }; + let resolved = super::pso_async::resolve_for_bind(target); + pc::(list, PC_SET_PIPELINE_STATE)(list, resolved); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.using_fallback_pso = is_fallback; + } +} + +// --------------------------------------------------------------------------------------- +// index buffers & DrawIndexedX +// --------------------------------------------------------------------------------------- /// a console GPU address as the PC's (unified memory: the window buffer's) fn pc_va(va: u64) -> u64 { @@ -346,15 +1143,17 @@ unsafe fn set_index_buffer(list: *mut c_void, view: Option<&D3D12_INDEX_BUFFER_V /// command list #47 IASetIndexBuffer(view) (PC #43): the address is the title's pub(super) unsafe extern "system" fn ia_set_index_buffer_x(this: *mut c_void, view: *const D3D12_INDEX_BUFFER_VIEW) { - let mut m = INDEX_BUFFERS.lock().unwrap(); - let m = m.get_or_insert_with(HashMap::new); + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default(); if view.is_null() { - m.remove(&(this as usize)); + s.index_buffer = None; + drop(g); return set_index_buffer(this, None); } let mut v = view.read_unaligned(); v.BufferLocation = pc_va(v.BufferLocation); - m.insert(this as usize, v); + s.index_buffer = Some(v); + drop(g); set_index_buffer(this, Some(&v)); } @@ -370,50 +1169,18 @@ pub(super) unsafe extern "system" fn draw_indexed_x(this: *mut c_void, va: u64, if count == 0 { return; } + prepare_draw(this); let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: pc_va(va), SizeInBytes: count.saturating_mul(stride), Format: format }; set_index_buffer(this, Some(&view)); pc::(this, PC_DRAW_INDEXED)(this, count, 1, 0, 0, 0); - let bound = INDEX_BUFFERS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).copied()); + let bound = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).and_then(|s| s.index_buffer)); set_index_buffer(this, bound.as_ref()); } -/// a query: (heap, index) -type Query = (usize, u32); +// --------------------------------------------------------------------------------------- +// nested occlusion queries & Reset +// --------------------------------------------------------------------------------------- -/// One list's occlusion queries: the one active on the PC and the outer ones it ended early. -#[derive(Default)] -struct Occlusion { - active: Option, - ended_early: Vec, -} - -impl Occlusion { - /// Begin `q` on the PC; Some(outer): end that one on the PC first. - fn begin(&mut self, q: Query) -> Option { - let outer = self.active.replace(q); - if let Some(o) = outer { - self.ended_early.push(o); - } - outer - } - - /// Whether the PC ends `q` (not: an outer one already ended – it resolves as visible). - fn end(&mut self, q: Query) -> bool { - if self.active == Some(q) { - self.active = None; - return true; - } - match self.ended_early.iter().position(|e| *e == q) { - Some(i) => { - self.ended_early.swap_remove(i); - false - } - None => true, - } - } -} - -static OCCLUSION: Mutex>> = Mutex::new(None); /// outer queries ended early, and the result they resolve to static VISIBLE: Mutex>> = Mutex::new(None); /// what such an OCCLUSION query reports (BINARY_OCCLUSION: 1) @@ -425,18 +1192,42 @@ fn is_occlusion(ty: D3D12_QUERY_TYPE) -> bool { type QueryFn = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32); -/// command list #10 Reset(allocator, initial pipeline): no query is active after it +/// command list #10 Reset(allocator, initial pipeline): updates allocator/pipeline and clears +/// per-recording state (queries, index buffer, depth bias, pending waits, written ranges) pub(super) unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, pso: usize) -> i32 { - if let Some(m) = OCCLUSION.lock().unwrap().as_mut() { - m.remove(&(this as usize)); - } + let is_bundle = { + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default(); + s.allocator = alloc; + s.bound_pso = pso; + s.depth_bias = None; + s.native_bias = DepthBias::ZERO; + s.pso_dirty = false; + s.using_fallback_pso = false; + s.index_buffer = None; + s.depth_bounds = None; + s.occlusion = Occlusion::default(); + s.written_ranges.clear(); + s.clear_waits(); + s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) + }; super::bind::reset(this, alloc); // the PC runtime writes its own vtable into a copy list again on Reset: keep XCL's let ext = *(this as *const usize); - let hr = pc:: i32>(this, PC_RESET)(this, alloc, pso); + let resolved = super::pso_async::resolve_for_bind(pso); + let hr = pc:: i32>(this, PC_RESET)(this, alloc, resolved); if *(this as *const usize) != ext { *(this as *mut usize) = ext; } + if hr >= 0 && !is_bundle && pso != 0 { + if let Some((true, static_bias)) = device_x::base_depth_bias_info(pso) { + if !static_bias.is_zero() && try_native_depth_bias(this, static_bias) { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { + s.native_bias = static_bias; + } + } + } + } hr } @@ -532,12 +1323,19 @@ pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usi 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 is_occlusion(ty) { - let outer = OCCLUSION.lock().unwrap().get_or_insert_with(HashMap::new).entry(this as usize).or_default().begin((heap, index)); - if let Some((h, i)) = outer { + let outer = LISTS + .lock() + .unwrap() + .get_or_insert_with(HashMap::new) + .entry(this as usize) + .or_default() + .occlusion + .begin((heap, index), ty); + if let Some(((h, i), oty)) = outer { if once(&N, 1) { crate::xlog_info!("D3D12.X: nested occlusion query – the outer one ends there and reports visible, the inner one counts"); } - pc::(this, PC_END_QUERY)(this, h, ty, i); + pc::(this, PC_END_QUERY)(this, h, oty, i); } if let Some(m) = VISIBLE.lock().unwrap().as_mut() { m.remove(&(heap, index)); @@ -549,7 +1347,14 @@ 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 is_occlusion(ty) { - let forward = OCCLUSION.lock().unwrap().get_or_insert_with(HashMap::new).entry(this as usize).or_default().end((heap, index)); + let forward = LISTS + .lock() + .unwrap() + .get_or_insert_with(HashMap::new) + .entry(this as usize) + .or_default() + .occlusion + .end((heap, index)); if !forward { let v = if ty == D3D12_QUERY_TYPE_BINARY_OCCLUSION { 1 } else { VISIBLE_SAMPLES }; VISIBLE.lock().unwrap().get_or_insert_with(HashMap::new).insert((heap, index), v); @@ -589,27 +1394,414 @@ pub(super) unsafe extern "system" fn resolve_query_data_x(this: *mut c_void, hea #[cfg(test)] mod tests { + use super::*; + use std::sync::Arc; + #[test] fn nested_occlusion_queries_end_the_outer_one_early() { - let mut o = super::Occlusion::default(); - assert_eq!(o.begin((1, 0)), None); - assert_eq!(o.begin((1, 1)), Some((1, 0)), "the outer one ends on the PC"); + let ty = D3D12_QUERY_TYPE_OCCLUSION; + let mut o = Occlusion::default(); + assert_eq!(o.begin((1, 0), ty), None); + assert_eq!(o.begin((1, 1), ty), Some(((1, 0), ty)), "the outer one ends on the PC"); assert!(o.end((1, 1)), "inner: a real query"); // more per-object queries inside the same outer one - assert_eq!(o.begin((1, 2)), None); + assert_eq!(o.begin((1, 2), ty), None); assert!(o.end((1, 2))); assert!(!o.end((1, 0)), "outer: already ended"); // overlapping, not nested: A, B, end A, end B - assert_eq!(o.begin((1, 3)), None); - assert_eq!(o.begin((1, 4)), Some((1, 3))); + assert_eq!(o.begin((1, 3), ty), None); + assert_eq!(o.begin((1, 4), ty), Some(((1, 3), ty))); assert!(!o.end((1, 3)) && o.end((1, 4))); assert!(o.active.is_none() && o.ended_early.is_empty()); assert!(o.end((1, 9)), "a query not begun here: the PC's call"); + // kickoff ends active query early so EndQuery later resolves it as visible + assert_eq!(o.begin((1, 5), D3D12_QUERY_TYPE_BINARY_OCCLUSION), None); + assert_eq!(o.end_active_early(), Some(((1, 5), D3D12_QUERY_TYPE_BINARY_OCCLUSION))); + assert!(!o.end((1, 5))); } #[test] fn fill_patterns_repeat_the_value() { - assert_eq!(super::pattern(&0x1122_3344u32.to_le_bytes())[..8], [0x44, 0x33, 0x22, 0x11, 0x44, 0x33, 0x22, 0x11]); - assert_eq!(super::pattern(&[7u8; 16]), [7u8; 16]); + assert_eq!(pattern(&0x1122_3344u32.to_le_bytes())[..8], [0x44, 0x33, 0x22, 0x11, 0x44, 0x33, 0x22, 0x11]); + assert_eq!(pattern(&[7u8; 16]), [7u8; 16]); + } + + #[test] + fn wait_comparison_ops_cover_all_d3d12_funcs() { + assert_eq!(compare_u64(0, 1, 1), None); + assert_eq!(compare_u64(9, 1, 1), None); + assert_eq!(compare_u64(1, 5, 5), Some(false)); // NEVER + assert_eq!(compare_u64(2, 4, 5), Some(true)); // LESS + assert_eq!(compare_u64(2, 5, 5), Some(false)); + assert_eq!(compare_u64(3, 5, 5), Some(true)); // EQUAL + assert_eq!(compare_u64(3, 4, 5), Some(false)); + assert_eq!(compare_u64(4, 5, 5), Some(true)); // LESS_EQUAL + assert_eq!(compare_u64(4, 6, 5), Some(false)); + assert_eq!(compare_u64(5, 6, 5), Some(true)); // GREATER + assert_eq!(compare_u64(5, 5, 5), Some(false)); + assert_eq!(compare_u64(6, 4, 5), Some(true)); // NOT_EQUAL + assert_eq!(compare_u64(6, 5, 5), Some(false)); + assert_eq!(compare_u64(7, 5, 5), Some(true)); // GREATER_EQUAL + assert_eq!(compare_u64(7, 4, 5), Some(false)); + assert_eq!(compare_u64(8, 0, 1), Some(true)); // ALWAYS + } + + #[test] + fn pending_wait_32_and_64_bit_with_mask_and_cross_thread_signal() { + let cell32 = Arc::new(AtomicU32::new(0xDEAD_0000)); + let w32 = PendingWait { + va: Arc::as_ptr(&cell32) as u64, + width: 4, + comparison: D3D12_COMPARISON_FUNC_EQUAL.0 as u32, + value: 0x0000_005A, + mask: 0x0000_00FF, + }; + unsafe { + assert!(!w32.is_satisfied()); + let writer = cell32.clone(); + let t = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(5)); + writer.store(0xBEEF_005A, Ordering::Release); + }); + assert!(w32.wait_until_satisfied(Duration::from_secs(1))); + t.join().unwrap(); + } + + let cell64 = Arc::new(AtomicU64::new(0x0000_0001_0000_0000)); + let w64 = PendingWait { + va: Arc::as_ptr(&cell64) as u64, + width: 8, + comparison: D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, + value: 0x0000_0002_0000_0000, + mask: u64::MAX, + }; + unsafe { + assert!(!w64.is_satisfied()); + // bounded timeout returns false without hanging + assert!(!w64.wait_until_satisfied(Duration::from_millis(5))); + cell64.store(0x0000_0002_0000_0001, Ordering::Release); + assert!(w64.is_satisfied()); + } + } + + #[test] + fn written_ranges_detect_same_list_overlap() { + let mut s = ListState::default(); + s.note_write(0x1000, 8); + assert!(s.has_prior_write(0x1000, 4)); + assert!(s.has_prior_write(0x1004, 4)); + assert!(s.has_prior_write(0x0FFC, 8)); + assert!(!s.has_prior_write(0x1008, 4)); + assert!(!s.has_prior_write(0x0FF8, 8)); + } + + #[test] + fn execute_with_waits_splits_batches_before_unsatisfied_list() { + // Use synthetic non-zero list pointers distinct from real COM objects. + let l0 = 0x7000_0001usize as *mut c_void; + let l1 = 0x7000_0002usize as *mut c_void; + let l2 = 0x7000_0003usize as *mut c_void; + let cell = Box::new(AtomicU32::new(0)); + let va = &*cell as *const AtomicU32 as u64; + + unsafe { + on_create(l0, 0x100, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + on_create(l1, 0x100, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + on_create(l2, 0x100, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + } + { + let mut g = LISTS.lock().unwrap(); + let s = g.as_mut().unwrap().get_mut(&(l1 as usize)).unwrap(); + s.push_wait(PendingWait { + va, + width: 4, + comparison: D3D12_COMPARISON_FUNC_EQUAL.0 as u32, + value: 42, + mask: u32::MAX as u64, + }); + } + + let mut batches: Vec> = Vec::new(); + unsafe { + execute_with_waits(&[l0, l1, l2], |chunk| { + batches.push(chunk.iter().map(|&p| p as usize).collect()); + // Simulate l0's GPU execution satisfying l1's wait! + if chunk.contains(&l0) { + cell.store(42, Ordering::Release); + } + }); + } + assert_eq!(batches, vec![vec![l0 as usize], vec![l1 as usize, l2 as usize]]); + + // Now that cell == 42 is already satisfied, the whole batch submits in one call. + batches.clear(); + unsafe { + execute_with_waits(&[l0, l1, l2], |chunk| { + batches.push(chunk.iter().map(|&p| p as usize).collect()); + }); + } + assert_eq!(batches, vec![vec![l0 as usize, l1 as usize, l2 as usize]]); + + on_release(l0 as usize); + on_release(l1 as usize); + on_release(l2 as usize); + } + + #[test] + fn queue_picking_prefers_last_queue_and_respects_release() { + let dev = 0x8000_0001usize; + let q1 = 0x8000_0010usize; + let q2 = 0x8000_0020usize; + let q_copy = 0x8000_0030usize; + on_queue_create(q1, dev, D3D12_COMMAND_LIST_TYPE_DIRECT); + on_queue_create(q2, dev, D3D12_COMMAND_LIST_TYPE_DIRECT); + on_queue_create(q_copy, dev, D3D12_COMMAND_LIST_TYPE_COPY); + + // Most recently created matching queue wins when no last_queue + assert_eq!(pick_queue(None, dev, D3D12_COMMAND_LIST_TYPE_DIRECT), Some(q2)); + assert_eq!(pick_queue(None, dev, D3D12_COMMAND_LIST_TYPE_COPY), Some(q_copy)); + // Explicit last_queue wins when still live + assert_eq!(pick_queue(Some(q1), dev, D3D12_COMMAND_LIST_TYPE_DIRECT), Some(q1)); + // Releasing q1 falls back to q2 + on_queue_release(q1); + assert_eq!(pick_queue(Some(q1), dev, D3D12_COMMAND_LIST_TYPE_DIRECT), Some(q2)); + on_queue_release(q2); + on_queue_release(q_copy); + assert_eq!(pick_queue(None, dev, D3D12_COMMAND_LIST_TYPE_DIRECT), None); + } + + #[test] + fn depth_bias_state_tracks_fallback_and_clear() { + let l = 0x9000_0001usize as *mut c_void; + let key = l as usize; + unsafe { + on_create(l, 0x100, 0xAAA, D3D12_COMMAND_LIST_TYPE_DIRECT); + on_set_pipeline_state(l, 0xBBB); + } + { + let mut g = LISTS.lock().unwrap(); + let s = g.as_mut().unwrap().get_mut(&key).unwrap(); + assert_eq!(s.bound_pso, 0xBBB); + assert!(!s.pso_dirty); + s.depth_bias = Some(DepthBias::new(-10.0, 0.0, 1.0)); + s.pso_dirty = true; + } + // Switching to a non-dynamic PSO while depth bias is active keeps pso_dirty for fallback + unsafe { on_set_pipeline_state(l, 0xCCC) }; + { + let g = LISTS.lock().unwrap(); + let s = g.as_ref().unwrap().get(&key).unwrap(); + assert_eq!(s.bound_pso, 0xCCC); + assert!(s.pso_dirty); + } + // ClearState resets depth bias, native_bias, and dirty flag + unsafe { on_clear_state(l, 0xDDD) }; + { + let g = LISTS.lock().unwrap(); + let s = g.as_ref().unwrap().get(&key).unwrap(); + assert_eq!(s.bound_pso, 0xDDD); + assert!(s.depth_bias.is_none()); + assert_eq!(s.native_bias, DepthBias::ZERO); + assert!(!s.pso_dirty); + } + on_release(key); + } + + #[test] + fn depth_bias_native_list9_and_bundle_fallback() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + let dev = dev.expect("D3D12 device"); + let supported = device_x::probe_dynamic_depth_bias(&dev); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("list"); + let has_list9 = list.cast::().is_ok(); + let raw = list.as_raw(); + let key = raw as usize; + + let pso_dyn_zero = 0x9100_0001usize; + let pso_dyn_static = 0x9100_0002usize; + let pso_static_only = 0x9100_0003usize; + let static_bias = DepthBias::new(-500.0, 0.0, 0.0); + device_x::register_test_base(pso_dyn_zero, true, DepthBias::ZERO); + device_x::register_test_base(pso_dyn_static, true, static_bias); + device_x::register_test_base(pso_static_only, false, DepthBias::ZERO); + + let cache_before = device_x::depth_bias_cache_len(); + on_create(raw, alloc.as_raw() as usize, pso_dyn_zero, D3D12_COMMAND_LIST_TYPE_DIRECT); + + if supported && has_list9 { + // Fractional f32 depth bias takes the native ID3D12GraphicsCommandList9 path + // without rounding to i32 or dirtying the patched-PSO fallback cache. + set_depth_bias_x(raw, -125.75, 0.05, 1.25); + { + let g = LISTS.lock().unwrap(); + let s = g.as_ref().unwrap().get(&key).unwrap(); + assert_eq!(s.depth_bias, Some(DepthBias::new(-125.75, 0.05, 1.25))); + assert_eq!(s.native_bias, DepthBias::new(-125.75, 0.05, 1.25)); + assert_eq!(s.native_bias.depth_bias(), -125.75); + assert!(!s.pso_dirty); + } + assert_eq!(device_x::depth_bias_cache_len(), cache_before); + + // Resetting depth bias to 0 updates native_bias to ZERO without touching fallback cache. + set_depth_bias_x(raw, 0.0, 0.0, 0.0); + { + let g = LISTS.lock().unwrap(); + let s = g.as_ref().unwrap().get(&key).unwrap(); + assert!(s.depth_bias.is_none()); + assert_eq!(s.native_bias, DepthBias::ZERO); + assert!(!s.pso_dirty); + } + + // Binding a dynamic PSO with non-zero static bias syncs native_bias to its static bias. + on_set_pipeline_state(raw, pso_dyn_static); + { + let g = LISTS.lock().unwrap(); + let s = g.as_ref().unwrap().get(&key).unwrap(); + assert_eq!(s.native_bias, static_bias); + assert!(!s.pso_dirty); + } + + // Switching back to a zero-static-bias dynamic PSO restores native_bias to ZERO. + on_set_pipeline_state(raw, pso_dyn_zero); + { + let g = LISTS.lock().unwrap(); + let s = g.as_ref().unwrap().get(&key).unwrap(); + assert_eq!(s.native_bias, DepthBias::ZERO); + assert!(!s.pso_dirty); + } + } + + // Non-dynamic PSO must fall back to the patched-PSO cache (pso_dirty = true). + on_set_pipeline_state(raw, pso_static_only); + set_depth_bias_x(raw, -50.0, 0.0, 0.0); + { + let g = LISTS.lock().unwrap(); + let s = g.as_ref().unwrap().get(&key).unwrap(); + assert_eq!(s.depth_bias, Some(DepthBias::new(-50.0, 0.0, 0.0))); + assert!(s.pso_dirty); + } + on_release(key); + + // Bundle lists cannot call ID3D12GraphicsCommandList9::RSSetDepthBias and must fall back. + let b_raw = 0x9100_00F0usize as *mut c_void; + on_create(b_raw, 0x100, pso_dyn_zero, D3D12_COMMAND_LIST_TYPE_BUNDLE); + set_depth_bias_x(b_raw, -75.0, 0.0, 0.0); + { + let g = LISTS.lock().unwrap(); + let s = g.as_ref().unwrap().get(&(b_raw as usize)).unwrap(); + assert!(s.pso_dirty); + assert_eq!(s.native_bias, DepthBias::ZERO); + } + on_release(b_raw as usize); + + device_x::forget_base(pso_dyn_zero); + device_x::forget_base(pso_dyn_static); + device_x::forget_base(pso_static_only); + } + } + + #[test] + fn depth_bias_native_path_exact_f32_and_list9_fallback() { + use std::cell::RefCell; + use std::rc::Rc; + + // Verify PC vtable slot of ID3D12GraphicsCommandList9::RSSetDepthBias is in layout table. + let cl9 = super::super::layout::find("ID3D12GraphicsCommandList9").expect("ID3D12GraphicsCommandList9 in layout"); + assert_eq!(super::super::layout::slot(cl9, "RSSetDepthBias"), Some(82)); + + let calls: Rc>> = Rc::new(RefCell::new(Vec::new())); + let allow = Rc::new(std::cell::Cell::new(true)); + let calls_cb = calls.clone(); + let allow_cb = allow.clone(); + TEST_NATIVE_BIAS.with(|h| { + *h.borrow_mut() = Some(Box::new(move |list, bias| { + if !allow_cb.get() { + return false; + } + calls_cb.borrow_mut().push((list, bias.depth_bias(), bias.depth_bias_clamp(), bias.slope_scaled_depth_bias())); + true + })); + }); + + let l = 0x9200_0001usize as *mut c_void; + let key = l as usize; + let pso_dyn_zero = 0x9200_0010usize; + let pso_dyn_static = 0x9200_0011usize; + let pso_static_only = 0x9200_0012usize; + device_x::register_test_base(pso_dyn_zero, true, DepthBias::ZERO); + device_x::register_test_base(pso_dyn_static, true, DepthBias::new(-500.0, 0.25, 2.0)); + device_x::register_test_base(pso_static_only, false, DepthBias::ZERO); + + let cache_before = device_x::depth_bias_cache_len(); + unsafe { + // 1. Initial PSO with baked static bias seeds native RSSetDepthBias on CreateCommandList. + on_create(l, 0x100, pso_dyn_static, D3D12_COMMAND_LIST_TYPE_DIRECT); + assert_eq!(*calls.borrow(), vec![(key, -500.0, 0.25, 2.0)]); + + // 2. Switching to zero-static-bias dynamic PSO resets native RSSetDepthBias to (0, 0, 0). + on_set_pipeline_state(l, pso_dyn_zero); + assert_eq!(calls.borrow().last(), Some(&(key, 0.0, 0.0, 0.0))); + + // 3. Fractional f32 override is forwarded verbatim (no i32 rounding, no fallback PSO cache). + set_depth_bias_x(l, -1000.5, 0.05, 1.5); + assert_eq!(calls.borrow().last(), Some(&(key, -1000.5, 0.05, 1.5))); + assert_eq!(device_x::depth_bias_cache_len(), cache_before); + { + let g = LISTS.lock().unwrap(); + let s = g.as_ref().unwrap().get(&key).unwrap(); + assert!(!s.pso_dirty); + assert_eq!(s.native_bias, DepthBias::new(-1000.5, 0.05, 1.5)); + } + + // 4. Switching between dynamic PSOs while override is active keeps the override without redundant calls. + let n_before = calls.borrow().len(); + on_set_pipeline_state(l, pso_dyn_static); + assert_eq!(calls.borrow().len(), n_before); + + // 5. Resetting to (0, 0, 0) sets native bias to (0, 0, 0); ClearState with static-bias PSO re-seeds it. + set_depth_bias_x(l, 0.0, 0.0, 0.0); + assert_eq!(calls.borrow().last(), Some(&(key, 0.0, 0.0, 0.0))); + on_clear_state(l, pso_dyn_static); + assert_eq!(calls.borrow().last(), Some(&(key, -500.0, 0.25, 2.0))); + + // 6. If ID3D12GraphicsCommandList9 is unavailable, set_depth_bias_x falls back cleanly to pso_dirty. + on_set_pipeline_state(l, pso_dyn_zero); + allow.set(false); + set_depth_bias_x(l, -42.5, 0.0, 0.0); + { + let g = LISTS.lock().unwrap(); + let s = g.as_ref().unwrap().get(&key).unwrap(); + assert!(s.pso_dirty); + assert_eq!(s.depth_bias, Some(DepthBias::new(-42.5, 0.0, 0.0))); + } + + // 7. Non-dynamic PSO always uses the patched-PSO fallback and never invokes RSSetDepthBias. + allow.set(true); + let n_before = calls.borrow().len(); + on_set_pipeline_state(l, pso_static_only); + set_depth_bias_x(l, -10.0, 0.0, 0.0); + assert_eq!(calls.borrow().len(), n_before); + { + let g = LISTS.lock().unwrap(); + let s = g.as_ref().unwrap().get(&key).unwrap(); + assert!(s.pso_dirty); + } + } + + TEST_NATIVE_BIAS.with(|h| *h.borrow_mut() = None); + on_release(key); + device_x::forget_base(pso_dyn_zero); + device_x::forget_base(pso_dyn_static); + device_x::forget_base(pso_static_only); } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 96efdfb..7ab060d 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -354,6 +354,7 @@ pub fn init() -> Result { } } open_uma(&device); + super::device_x::probe_dynamic_depth_bias(&device); let raw = device.into_raw(); // one reference kept for the process lifetime adopt(raw, Kind::Device); DEVICE.store(raw as usize, Ordering::Release); @@ -717,6 +718,8 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (68, l::set_depth_bounds_x as usize), (69, l::write32_bottom_x as usize), (70, l::write64_bottom_x as usize), + (71, l::wait32_x as usize), + (72, l::wait64_x as usize), (78, l::dispatch_x as usize), (81, l::draw_indexed_x as usize), (84, l::copy_resource_flags_x as usize), @@ -724,6 +727,8 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (88, l::write32_top_x as usize), (89, l::write64_top_x as usize), (90, l::write32_bottom_of_shader_x as usize), + (93, l::kickoff_x as usize), + (94, l::set_depth_bias_x as usize), ] } _ => vec![], @@ -1418,9 +1423,18 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { ("CreatePlacedResource1", dev_create_placed_resource1 as usize), ("CreateCommandQueue1", dev_create_command_queue1 as usize), ]), - Kind::CommandList => v.extend_from_slice(&[("OMSetRenderTargets", cl_om_set_render_targets as usize), ("SetPipelineState", cl_set_pipeline_state as usize), ("Close", cl_close as usize)]), - Kind::CommandQueue => v.push(("ExecuteCommandLists", q_execute_command_lists as usize)), - Kind::CommandAllocator => v.push(("Reset", alloc_reset as usize)), + Kind::CommandList => v.extend_from_slice(&[ + ("Release", cl_release as usize), + ("Close", cl_close as usize), + ("ClearState", cl_clear_state as usize), + ("DrawInstanced", cl_draw_instanced as usize), + ("DrawIndexedInstanced", cl_draw_indexed_instanced as usize), + ("SetPipelineState", cl_set_pipeline_state as usize), + ("OMSetRenderTargets", cl_om_set_render_targets as usize), + ("ExecuteIndirect", cl_execute_indirect as usize), + ]), + Kind::CommandQueue => v.extend_from_slice(&[("Release", q_release as usize), ("ExecuteCommandLists", q_execute_command_lists as usize)]), + Kind::CommandAllocator => v.extend_from_slice(&[("Release", alloc_release as usize), ("Reset", alloc_reset as usize)]), Kind::Resource => v.extend_from_slice(&[("Release", res_release as usize), ("Map", res_map as usize), ("Unmap", res_unmap as usize)]), Kind::PipelineState => v.push(("Release", pso_release as usize)), Kind::DescriptorHeap => v.push(("Release", heap_release as usize)), @@ -2356,6 +2370,9 @@ unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, &d.DSVFormat); out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, &d.SampleDesc); out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK, &d.NodeMask); + if d.Flags.0 != 0 { + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, &d.Flags); + } finish_two_pass(this, &out, tp, rs, "GS", riid, ppv) } @@ -2493,6 +2510,71 @@ unsafe extern "system" fn cl_set_pipeline_state(this: *mut c_void, pso: *mut c_v type F = unsafe extern "system" fn(*mut c_void, *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "SetPipelineState"))); f(this, super::pso_async::resolve_for_bind(pso as usize) as *mut c_void); + super::list_x::on_set_pipeline_state(this, pso as usize); +} + +unsafe extern "system" fn cl_clear_state(this: *mut c_void, pso: *mut c_void) { + type F = unsafe extern "system" fn(*mut c_void, *mut c_void); + let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ClearState"))); + f(this, super::pso_async::resolve_for_bind(pso as usize) as *mut c_void); + super::list_x::on_clear_state(this, pso as usize); +} + +unsafe extern "system" fn cl_draw_instanced(this: *mut c_void, vcount: u32, icount: u32, sv: u32, si: u32) { + super::list_x::prepare_draw(this); + type F = unsafe extern "system" fn(*mut c_void, u32, u32, u32, u32); + let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "DrawInstanced"))); + f(this, vcount, icount, sv, si); +} + +unsafe extern "system" fn cl_draw_indexed_instanced(this: *mut c_void, icount: u32, inst: u32, si: u32, bv: i32, sinst: u32) { + super::list_x::prepare_draw(this); + type F = unsafe extern "system" fn(*mut c_void, u32, u32, u32, i32, u32); + let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "DrawIndexedInstanced"))); + f(this, icount, inst, si, bv, sinst); +} + +#[allow(clippy::too_many_arguments)] +unsafe extern "system" fn cl_execute_indirect( + this: *mut c_void, + sig: *mut c_void, + max_count: u32, + arg_buf: *mut c_void, + arg_off: u64, + cnt_buf: *mut c_void, + cnt_off: u64, +) { + super::list_x::prepare_draw(this); + type F = unsafe extern "system" fn(*mut c_void, *mut c_void, u32, *mut c_void, u64, *mut c_void, u64); + let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ExecuteIndirect"))); + f(this, sig, max_count, arg_buf, arg_off, cnt_buf, cnt_off); +} + +unsafe extern "system" fn cl_release(this: *mut c_void) -> u32 { + let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + let n = f(this); + if n == 0 { + super::list_x::on_release(this as usize); + } + n +} + +unsafe extern "system" fn q_release(this: *mut c_void) -> u32 { + let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + let n = f(this); + if n == 0 { + super::list_x::on_queue_release(this as usize); + } + n +} + +unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { + let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + let n = f(this); + if n == 0 { + super::list_x::on_allocator_release(this as usize); + } + n } unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT { @@ -2511,18 +2593,19 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ExecuteCommandLists"))); // textures in title memory the CPU wrote since: uploaded again first super::title_textures::refresh(); - // console-shaped lists run as the PC lists they were translated into - let mapped: Vec<*mut c_void>; - let lists = if n > 0 && !lists.is_null() { - mapped = std::slice::from_raw_parts(lists, n as usize).iter().map(|&l| super::console_list::pc_list(l).or_else(|| super::title_list::backing(l)).unwrap_or(l)).collect(); - mapped.as_ptr() - } else { - lists - }; - f(this, n, lists); - if n > 0 && !lists.is_null() { - super::present::note_execute(this, std::slice::from_raw_parts(lists, n as usize)); + if n == 0 || lists.is_null() { + f(this, n, lists); + stop_if_device_removed(); + return; } + // console-shaped lists run as the PC lists they were translated into + let mapped: Vec<*mut c_void> = std::slice::from_raw_parts(lists, n as usize) + .iter() + .map(|&l| super::console_list::pc_list(l).or_else(|| super::title_list::backing(l)).unwrap_or(l)) + .collect(); + super::list_x::note_queue_for_lists(this as usize, &mapped); + super::list_x::execute_with_waits(&mapped, |chunk| f(this, chunk.len() as u32, chunk.as_ptr())); + super::present::note_execute(this, &mapped); stop_if_device_removed(); } diff --git a/tests/testtitle/src/gpu.rs b/tests/testtitle/src/gpu.rs index 71922eb..0f18296 100644 --- a/tests/testtitle/src/gpu.rs +++ b/tests/testtitle/src/gpu.rs @@ -75,10 +75,12 @@ unsafe fn xslot(list: &ID3D12GraphicsCommandList, slot: usize) -> F { } type OmSetRenderTargets = unsafe extern "system" fn(*mut c_void, u32, *const D3D12_CPU_DESCRIPTOR_HANDLE, i32, *const D3D12_CPU_DESCRIPTOR_HANDLE); +type ClearDsv = unsafe extern "system" fn(*mut c_void, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_CLEAR_FLAGS, f32, u8, u32, *const RECT); type ClearRtv = unsafe extern "system" fn(*mut c_void, D3D12_CPU_DESCRIPTOR_HANDLE, *const [f32; 4], u32, *const RECT); type SetRootSignature = unsafe extern "system" fn(*mut c_void, *mut c_void); const X_SET_GRAPHICS_ROOT_SIGNATURE: usize = 34; const X_OM_SET_RENDER_TARGETS: usize = 50; +const X_CLEAR_DEPTH_STENCIL_VIEW: usize = 51; const X_CLEAR_RENDER_TARGET_VIEW: usize = 52; fn e(x: windows::core::Error) -> String { @@ -453,8 +455,8 @@ pub fn console_device_methods() -> Result<(), String> { /// The console command list's memory methods as a title calls them, on its own graphics /// memory: Write32BitValueBottomOfPipeX #69, Write64BitValueTopOfPipeX #89, a GPU timestamp -/// (#70), FillMemoryWith32BitValueX #61, CopyMemoryToMemoryX #60, and an extension XCL does not -/// model (Wait32BitValueX #71). +/// (#70), FillMemoryWith32BitValueX #61, CopyMemoryToMemoryX #60, Wait32BitValueX #71, +/// Wait64BitValueX #72, and KickoffX #93. pub fn console_list_methods() -> Result<(), String> { unsafe { let dev = device()?; @@ -476,6 +478,10 @@ pub fn console_list_methods() -> Result<(), String> { let fill32: unsafe extern "system" fn(*mut c_void, u64, u64, u32) = std::mem::transmute(slot(61)); let copy: unsafe extern "system" fn(*mut c_void, u64, u64, u64, u32) = std::mem::transmute(slot(60)); let wait32: unsafe extern "system" fn(*mut c_void, u64, u32, u32, u32, u32) = std::mem::transmute(slot(71)); + let wait64: unsafe extern "system" fn(*mut c_void, u64, u32, u64, u64, u32) = std::mem::transmute(slot(72)); + let kickoff: unsafe extern "system" fn(*mut c_void) = std::mem::transmute(slot(93)); + + // 1. Memory writes, timestamp, fill, copy, and same-list write-then-wait (must not deadlock) write32_bottom(l, at(0), 0x1234_5678, 0, 0); write64_top(l, at(8), 0x1122_3344_5566_7788, 0); write64_bottom(l, at(0x10), 0, 0, 1); // GPU timestamp @@ -493,6 +499,47 @@ pub fn console_list_methods() -> Result<(), String> { ensure!(r64(0x10) != 0, "no GPU timestamp"); ensure!((0..64).all(|i| r32(0x100 + 4 * i) == 0xABCD_EF01) && r32(0x200) == 0 && r32(0xFC) == 0, "FillMemoryWith32BitValueX"); ensure!((0..64).all(|i| *mem.add(0x2000 + i) == i as u8 ^ 0x5A) && *mem.add(0x2040) == 0, "CopyMemoryToMemoryX"); + + // 2. KickoffX (#93): flushes work to the GPU BEFORE Close() is called, then continues recording + alloc.Reset().map_err(e)?; + list.Reset(&alloc, None).map_err(e)?; + write32_bottom(l, at(0x400), 0x1111_2222, 0, 0); + kickoff(l); + // Wait for the kicked-off write on the GPU while the list is still open! + let t0 = std::time::Instant::now(); + while (mem.add(0x400) as *const std::sync::atomic::AtomicU32).as_ref().unwrap().load(std::sync::atomic::Ordering::Acquire) != 0x1111_2222 + && t0.elapsed() < std::time::Duration::from_secs(2) + { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + ensure!(r32(0x400) == 0x1111_2222, "KickoffX did not flush work before Close ({:#x})", r32(0x400)); + // Continue recording on the same list and submit normally via Close + ExecuteCommandLists + write32_bottom(l, at(0x404), 0x3333_4444, 0, 0); + list.Close().map_err(e)?; + queue.ExecuteCommandLists(&[Some(list.cast::().map_err(e)?)]); + wait(&queue, &fence, 2)?; + ensure!(r32(0x404) == 0x3333_4444, "post-KickoffX write failed ({:#x})", r32(0x404)); + + // 3. Cross-thread Wait32BitValueX (#71, masked EQUAL) + Wait64BitValueX (#72, GREATER_EQUAL) + alloc.Reset().map_err(e)?; + list.Reset(&alloc, None).map_err(e)?; + wait32(l, at(0x300), 3, 0x0000_00AA, 0x0000_00FF, 0); + wait64(l, at(0x308), 7, 0x0000_0002_0000_0000, u64::MAX, 0); + write32_bottom(l, at(0x310), 0x55AA_55AA, 0, 0); + list.Close().map_err(e)?; + let addr32 = at(0x300) as usize; + let addr64 = at(0x308) as usize; + let writer = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(15)); + (*(addr32 as *const std::sync::atomic::AtomicU32)).store(0xDEAD_00AA, std::sync::atomic::Ordering::Release); + (*(addr64 as *const std::sync::atomic::AtomicU64)).store(0x0000_0003_0000_0000, std::sync::atomic::Ordering::Release); + }); + queue.ExecuteCommandLists(&[Some(list.cast::().map_err(e)?)]); + wait(&queue, &fence, 3)?; + writer.join().map_err(|_| "wait writer thread panicked".to_string())?; + ensure!(r32(0x300) == 0xDEAD_00AA && r64(0x308) == 0x0000_0003_0000_0000, "wait cells not written"); + ensure!(r32(0x310) == 0x55AA_55AA, "post-Wait32/64 write failed ({:#x})", r32(0x310)); + crate::XMemFree(mem as *mut c_void, graphics); Ok(()) } @@ -1046,3 +1093,222 @@ pub fn mfplat_reset_dxgi_device_manager() -> Result<(), String> { res } } + +/// Dynamic depth bias via `RSSetDepthBiasX` (#94): draws a triangle at z = 0.5 against a depth +/// buffer cleared to 0.5 with `DepthFunc = LESS`, exercising native `ID3D12GraphicsCommandList9` +/// dynamic depth bias (when supported by the adapter) or the patched-PSO fallback: +/// 1. Top-left: no bias → rejected (blue). +/// 2. Top-right: fractional `RSSetDepthBiasX(-1000.5, 0, 0)` → passes (green). +/// 3. `KickoffX` (#93) while `-1000.5` is active, then bottom-right without re-calling +/// `RSSetDepthBiasX` → still passes (green). +/// 4. Bottom-left right half: `RSSetDepthBiasX(0, 0, 0)` resets bias to 0 → rejected (blue). +/// 5. Bottom-left left half: PSO with baked static `RasterizerState.DepthBias = -1000` (no +/// `RSSetDepthBiasX` override) → passes (green). +/// 6. Top-left corner: switch back to zero-bias PSO → previous PSO's static bias does not leak (blue). +pub fn dynamic_depth_bias() -> Result<(), String> { + unsafe { + let dev = device()?; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).map_err(e)?; + let rs = root_signature(&dev)?; + let vs = compile( + "float4 main(uint id : SV_VertexID) : SV_Position { float2 p[3] = { float2(-1,-1), float2(-1,3), float2(3,-1) }; return float4(p[id], 0.5, 1.0); }", + "vs_5_0", + )?; + let ps = compile("float4 main() : SV_Target { return float4(0, 1, 0, 1); }", "ps_5_0")?; + let mut desc = pso_desc(&rs, bc(&vs), bc(&ps)); + desc.DSVFormat = DXGI_FORMAT_D32_FLOAT; + desc.DepthStencilState.DepthEnable = true.into(); + desc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS; + let pso: ID3D12PipelineState = dev.CreateGraphicsPipelineState(&desc).map_err(e)?; + + let mut static_desc = desc; + static_desc.RasterizerState.DepthBias = -1000; + let pso_static_bias: ID3D12PipelineState = dev.CreateGraphicsPipelineState(&static_desc).map_err(e)?; + + let (w, h) = (64u32, 64u32); + let rt_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w as u64, + Height: h, + 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 rt_clear = D3D12_CLEAR_VALUE { Format: DXGI_FORMAT_R8G8B8A8_UNORM, Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.0, 0.0, 1.0, 1.0] } }; + let mut rt: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &rt_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + Some(&rt_clear), + &mut rt, + ) + .map_err(e)?; + let rt = rt.ok_or("no render target")?; + + let ds_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w as u64, + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_D32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + let ds_clear = D3D12_CLEAR_VALUE { + Format: DXGI_FORMAT_D32_FLOAT, + Anonymous: D3D12_CLEAR_VALUE_0 { DepthStencil: D3D12_DEPTH_STENCIL_VALUE { Depth: 0.5, Stencil: 0 } }, + }; + let mut ds: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &ds_desc, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + Some(&ds_clear), + &mut ds, + ) + .map_err(e)?; + let ds = ds.ok_or("no depth buffer")?; + + let rtv_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: 1, ..Default::default() }) + .map_err(e)?; + let dsv_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV, NumDescriptors: 1, ..Default::default() }) + .map_err(e)?; + let heap_start = |heap: &ID3D12DescriptorHeap| -> D3D12_CPU_DESCRIPTOR_HANDLE { + let f: unsafe extern "system" fn(*mut c_void) -> usize = transmute_copy(&(*(*(heap.as_raw() as *const *const usize)).add(9))); + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: f(heap.as_raw()) } + }; + let rtv = heap_start(&rtv_heap); + let dsv = heap_start(&dsv_heap); + dev.CreateRenderTargetView(&rt, None, rtv); + dev.CreateDepthStencilView(&ds, None, dsv); + + let mut layout = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0u64; + dev.GetCopyableFootprints(&rt_desc, 0, 1, 0, Some(&mut layout), None, None, Some(&mut total)); + let mut rb: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: total, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut rb, + ) + .map_err(e)?; + let rb = rb.ok_or("no readback buffer")?; + + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).map_err(e)?; + let bind_pass_state = || { + xslot::(&list, X_OM_SET_RENDER_TARGETS)(list.as_raw(), 1, &rtv, 0, &dsv); + list.RSSetScissorRects(&[RECT { left: 0, top: 0, right: w as i32, bottom: h as i32 }]); + xslot::(&list, X_SET_GRAPHICS_ROOT_SIGNATURE)(list.as_raw(), rs.as_raw()); + list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + }; + bind_pass_state(); + xslot::(&list, X_CLEAR_RENDER_TARGET_VIEW)(list.as_raw(), rtv, &[0.0, 0.0, 1.0, 1.0], 0, std::ptr::null()); + xslot::(&list, X_CLEAR_DEPTH_STENCIL_VIEW)(list.as_raw(), dsv, D3D12_CLEAR_FLAG_DEPTH, 0.5, 0, 0, std::ptr::null()); + + let vp = |x: u32, y: u32, vw: u32, vh: u32| D3D12_VIEWPORT { TopLeftX: x as f32, TopLeftY: y as f32, Width: vw as f32, Height: vh as f32, MinDepth: 0.0, MaxDepth: 1.0 }; + type KickoffX = unsafe extern "system" fn(*mut c_void); + type SetDepthBiasX = unsafe extern "system" fn(*mut c_void, f32, f32, f32); + let kickoff = xslot::(&list, 93); + let set_bias = xslot::(&list, 94); + + // 1. Top-left: no bias (0.5 < 0.5 is false -> rejected -> blue) + list.RSSetViewports(&[vp(0, 0, w / 2, h / 2)]); + list.DrawInstanced(3, 1, 0, 0); + + // 2. Top-right: fractional negative depth bias pushes z < 0.5 -> passes -> green + set_bias(list.as_raw(), -1000.5, 0.0, 0.0); + list.RSSetViewports(&[vp(w / 2, 0, w / 2, h / 2)]); + list.DrawInstanced(3, 1, 0, 0); + + // 3. KickoffX mid-list while depth-bias override is active: bias must persist after Reset() + kickoff(list.as_raw()); + bind_pass_state(); + list.RSSetViewports(&[vp(w / 2, h / 2, w / 2, h / 2)]); + list.DrawInstanced(3, 1, 0, 0); + + // 4. Bottom-left right half: reset depth bias to 0 -> rejected -> blue + set_bias(list.as_raw(), 0.0, 0.0, 0.0); + list.RSSetViewports(&[vp(w / 4, h / 2, w / 4, h / 2)]); + list.DrawInstanced(3, 1, 0, 0); + + // 5. Bottom-left left half: PSO with baked static DepthBias = -1000 (no override) -> passes -> green + list.SetPipelineState(&pso_static_bias); + list.RSSetViewports(&[vp(0, h / 2, w / 4, h / 2)]); + list.DrawInstanced(3, 1, 0, 0); + + // 6. Top-left corner: switch back to zero-bias PSO -> static bias must not leak -> blue + list.SetPipelineState(&pso); + list.RSSetViewports(&[vp(0, 0, w / 4, h / 4)]); + list.DrawInstanced(3, 1, 0, 0); + + list.ResourceBarrier(&[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 { + pResource: transmute_copy(&rt), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_RENDER_TARGET, + StateAfter: D3D12_RESOURCE_STATE_COPY_SOURCE, + }), + }, + }]); + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: transmute_copy(&rb), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: layout }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: transmute_copy(&rt), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().map_err(e)?; + queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?; + wait(&queue, &fence, 1)?; + + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).map_err(e)?; + let pitch = layout.Footprint.RowPitch as usize; + let px = |x: usize, y: usize| -> [u8; 4] { + let o = y * pitch + x * 4; + let s = std::slice::from_raw_parts((p as *const u8).add(o), 4); + [s[0], s[1], s[2], s[3]] + }; + let (tl, tr, br, bl_reset, bl_static, tl_after) = (px(20, 20), px(48, 16), px(48, 48), px(24, 48), px(8, 48), px(8, 8)); + rb.Unmap(0, None); + ensure!(tl == [0, 0, 255, 255], "top-left {tl:?} (expected blue: no depth bias, 0.5 < 0.5 fails)"); + ensure!(tr == [0, 255, 0, 255], "top-right {tr:?} (expected green: RSSetDepthBiasX(-1000.5) passes depth test)"); + ensure!(br == [0, 255, 0, 255], "bottom-right {br:?} (expected green: depth bias persists across KickoffX)"); + ensure!(bl_reset == [0, 0, 255, 255], "bottom-left reset {bl_reset:?} (expected blue: RSSetDepthBiasX(0) restores zero bias)"); + ensure!(bl_static == [0, 255, 0, 255], "bottom-left static {bl_static:?} (expected green: baked static DepthBias = -1000 preserved)"); + ensure!(tl_after == [0, 0, 255, 255], "top-left after static PSO {tl_after:?} (expected blue: static bias did not leak to zero-bias PSO)"); + Ok(()) + } +} diff --git a/tests/testtitle/src/main.rs b/tests/testtitle/src/main.rs index 3adb304..f809824 100644 --- a/tests/testtitle/src/main.rs +++ b/tests/testtitle/src/main.rs @@ -591,7 +591,8 @@ fn main() { check("D3D12.X: triangle rendered on the real GPU and read back (console + derived pipeline)", gpu::render_triangle); check("D3D12.X: frame clock + PresentX of the title's back buffer", gpu::present_x_frame); check("D3D12.X: console device methods (placed title memory, DMA queue + list, page pools)", gpu::console_device_methods); - check("D3D12.X: console command list memory methods (writes, timestamp, fill, copy)", gpu::console_list_methods); + check("D3D12.X: console command list memory methods (writes, timestamp, fill, copy, KickoffX, Wait32/64)", gpu::console_list_methods); + check("D3D12.X: dynamic depth bias via RSSetDepthBiasX (#94)", gpu::dynamic_depth_bias); check("DirectStorage (xcrdapi): a file read into memory, status + D3D12 fence", gpu::direct_storage); check("D3D12.X: a texture in title memory (XG layout, #44) follows CPU writes", gpu::title_texture); check("D3D12.X: a texture in a streaming pool gets its texels once pages are mapped in", gpu::streamed_texture);