mirror of
https://github.com/ivall/xcl.git
synced 2026-11-24 05:14:57 +01:00
d3d12x: implement KickoffX, Wait32/64BitValueX, and RSSetDepthBiasX
This commit is contained in:
@@ -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::<D3D12_FEATURE_DATA_D3D12_OPTIONS16>() 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<CString>,
|
||||
}
|
||||
@@ -163,6 +315,9 @@ unsafe impl Send for Base {}
|
||||
unsafe impl Sync for Base {}
|
||||
|
||||
static BASES: Mutex<Option<HashMap<usize, Arc<Base>>>> = 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<Option<HashMap<(usize, DepthBias), usize>>> = 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<usize> = {
|
||||
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<usize> {
|
||||
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 {
|
||||
|
||||
+1257
-65
File diff suppressed because it is too large
Load Diff
@@ -354,6 +354,7 @@ pub fn init() -> Result<String, String> {
|
||||
}
|
||||
}
|
||||
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();
|
||||
}
|
||||
|
||||
|
||||
+268
-2
@@ -75,10 +75,12 @@ unsafe fn xslot<F: Copy>(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::<ID3D12CommandList>().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::<ID3D12CommandList>().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<ID3D12Resource> = 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<ID3D12Resource> = 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<ID3D12Resource> = 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::<OmSetRenderTargets>(&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::<SetRootSignature>(&list, X_SET_GRAPHICS_ROOT_SIGNATURE)(list.as_raw(), rs.as_raw());
|
||||
list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
|
||||
};
|
||||
bind_pass_state();
|
||||
xslot::<ClearRtv>(&list, X_CLEAR_RENDER_TARGET_VIEW)(list.as_raw(), rtv, &[0.0, 0.0, 1.0, 1.0], 0, std::ptr::null());
|
||||
xslot::<ClearDsv>(&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::<KickoffX>(&list, 93);
|
||||
let set_bias = xslot::<SetDepthBiasX>(&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(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user