From 61df188f76cf842d6ba070bf6acd7db50a2baa8e Mon Sep 17 00:00:00 2001 From: xstraok Date: Mon, 23 Nov 2026 21:27:13 -0500 Subject: [PATCH] Recompiler: send image heap indices that are no view to null views (#575) A T# that is still in the console encoding (word 0 = BASE_ADDRESS >> 8, not an XCL heap index) made ResourceDescriptorHeap[tw0] read gigabytes past the shader-visible view heap. On RADV that is an SQC page fault and the device is removed during a retail game's world loading: the faulting VAs were never covered by a BO (RADV_DEBUG=bo_history) and lie past the 1 000 000 x 32 B heap; as T# word 0 they are addresses in the title's own mappings. The shared view heap is now 1 000 000 descriptors on every device (the least a resource binding tier 3 GPU has, which SM 6.6 dynamic resources need), and its last 12 slots are null views that no console heap gets: a null SRV of each texture type recompiled shaders declare (1D, 2D, 3D, CubeArray, 1DArray, 2DArray, 2DMS) and a null UAV of each (1D, 2D, 3D, 1DArray, 2DArray), since D3D12 needs a null view's dimension to match the declaration. Image instructions use word 0 as the view index only below them and when word 3's TYPE is an image type (>= 8); otherwise the null view of the type they declare: such a T# reads 0 and its stores and atomics are dropped. The TYPE check covers the all-zero T# XCL writes for a null-resource CreateShaderResourceViewX / CreateUnorderedAccessViewX, whose word 0 would otherwise be the view at index 0. A 2DMS store or atomic is refused at translation (SM 6.6 has no RWTexture2DMS; DXC refused it before). The bound is a constant (gpu::desc::NULL_VIEWS), so a translation does not depend on the device or on whether the heap existed when it was made, and cached translations stay valid. Test runs with textures get the same heap. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SobdMAZZmGnBr71QeZQsUz --- crates/xcl/src/gpu/desc.rs | 24 ++++++ crates/xcl/src/gpu/recomp/emit.rs | 33 ++++++-- crates/xcl/src/gpu/recomp/runner.rs | 6 +- crates/xcl/src/gpu/recomp/tests.rs | 97 +++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/console_heap.rs | 74 +++++++++++++---- 5 files changed, 212 insertions(+), 22 deletions(-) diff --git a/crates/xcl/src/gpu/desc.rs b/crates/xcl/src/gpu/desc.rs index 157bb1e18..d44accd1e 100644 --- a/crates/xcl/src/gpu/desc.rs +++ b/crates/xcl/src/gpu/desc.rs @@ -323,6 +323,30 @@ pub fn sampler_d3d12(w: &[u32; 4], comparison: bool) -> D3D12_SAMPLER_DESC { } } +/// Views in the shader-visible heap recompiled shaders index (`ResourceDescriptorHeap` with T# +/// word 0), on every device: the least a resource binding tier 3 GPU has, which SM 6.6 +/// dynamic resources need. A constant, so translated shaders do not depend on the device. +pub const VIEW_HEAP_SIZE: u32 = 1_000_000; +/// The texture types recompiled shaders declare (`Texture` / `RWTexture`), in the +/// order of their null views. +pub const NULL_SRV_TYPES: [&str; 7] = ["1D", "2D", "3D", "CubeArray", "1DArray", "2DArray", "2DMS"]; +pub const NULL_UAV_TYPES: [&str; 5] = ["1D", "2D", "3D", "1DArray", "2DArray"]; +/// The heap's last 12 slots, which no view heap gets: a null SRV of each type in +/// `NULL_SRV_TYPES`, then a null UAV of each in `NULL_UAV_TYPES`. A T# whose word 0 is no heap +/// index reads 0 through the one of the type the shader declares and its writes are dropped +/// (D3D12 needs a null view's dimension to match the declaration). +pub const NULL_VIEWS: u32 = VIEW_HEAP_SIZE - (NULL_SRV_TYPES.len() + NULL_UAV_TYPES.len()) as u32; + +/// The null SRV for a texture type of `NULL_SRV_TYPES` ("2D", "CubeArray", …). +pub fn null_srv(ty: &str) -> u32 { + NULL_VIEWS + NULL_SRV_TYPES.iter().position(|&t| t == ty).expect("a texture type with a null SRV") as u32 +} + +/// The null UAV for a texture type of `NULL_UAV_TYPES`. +pub fn null_uav(ty: &str) -> u32 { + NULL_VIEWS + (NULL_SRV_TYPES.len() + NULL_UAV_TYPES.iter().position(|&t| t == ty).expect("a texture type with a null UAV")) as u32 +} + /// The T# as recompiled shaders read it (XCL shader ABI): BASE_ADDRESS – word 0 and the /// high byte of word 1 – replaced by the descriptor heap index of the SRV (UAV at index + 1); /// every other field (format, size, swizzle …) stays as the console wrote it. diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 1d5ef0139..67ed466c6 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -2085,6 +2085,18 @@ impl Em { }; let t = self.t(); let tw0 = self.sreg(srsrc); + // a T# whose word 0 is no heap index (a console address the title wrote without a view) + // must not read past the heap: RADV faults on the GPU (SQC page fault, device removed). + // Views sit below the null ones in pairs (SRV, UAV at + 1): anything else gets the null + // view of the texture type the declaration names ("2D", "CubeArray", …). So does a T# + // with no image TYPE (word 3 [31:28] < 8): a null view's T# is all zero, and its word 0 + // would be the view at index 0. + use crate::gpu::desc::{null_srv, null_uav, NULL_VIEWS}; + let views = NULL_VIEWS - 1; + let tw3 = self.sreg(srsrc + 3); + let view = format!("({tw0} < {views}u && {tw3} >= 0x80000000u)"); + let srv_i = |ty: &str| format!("({view} ? {tw0} : {}u)", null_srv(ty)); + let uav_i = |ty: &str| format!("({view} ? {tw0} + 1u : {}u)", null_uav(ty)); let tw1 = self.sreg(srsrc + 1); let act = self.act(); let ps = matches!(self.opt.mode, Mode::Pixel(_)); @@ -2171,7 +2183,7 @@ impl Em { return Err("MIMG unorm"); } let samp = if has_c { "SamplerComparisonState" } else { "SamplerState" }; - self.line(&format!("{ty} {t}_T = ResourceDescriptorHeap[NonUniformResourceIndex({tw0})];")); + self.line(&format!("{ty} {t}_T = ResourceDescriptorHeap[NonUniformResourceIndex({})];", srv_i(ty.trim_start_matches("Texture").trim_end_matches("")))); let sampler = self.sampler_ref(d.pc, has_c, &s3); self.line(&format!("{samp} {t}_S = {sampler};")); if let Some(o) = &offset { @@ -2275,7 +2287,7 @@ impl Em { _ => return Err("MIMG dim"), }; let s3 = self.sreg(ssamp + 3); - self.line(&format!("{ty} {t}_T = ResourceDescriptorHeap[NonUniformResourceIndex({tw0})];")); + self.line(&format!("{ty} {t}_T = ResourceDescriptorHeap[NonUniformResourceIndex({})];", srv_i(ty.trim_start_matches("Texture").trim_end_matches("")))); let sampler = self.sampler_ref(d.pc, false, &s3); self.line(&format!("SamplerState {t}_S = {sampler};")); self.line(&format!( @@ -2298,7 +2310,7 @@ impl Em { 5 => ("Texture2DArray", format!("{t}_T.GetDimensions({mipv}, {t}_w, {t}_h, {t}_d, {t}_n);")), _ => return Err("get_resinfo dim"), }; - self.line(&format!("{ty} {t}_T = ResourceDescriptorHeap[NonUniformResourceIndex({tw0})];")); + self.line(&format!("{ty} {t}_T = ResourceDescriptorHeap[NonUniformResourceIndex({})];", srv_i(ty.trim_start_matches("Texture")))); self.line(&format!("uint {t}_w, {t}_h, {t}_d, {t}_n; {call}")); self.line(&format!("uint4 {t}_r = uint4({t}_w, {t}_h, {t}_d, {t}_n);")); let comps2 = comps.clone(); @@ -2321,12 +2333,19 @@ impl Em { if dim == 3 && base.starts_with("load") { return Err("image_load cube"); } + // (SM 6.6 has no RWTexture2DMS) + if dim == 6 && !base.starts_with("load") { + return Err("MIMG 2DMS store"); + } + // (a 2DMS T# is only loaded from) + let uav_i = if dim == 6 { String::new() } else { uav_i(rty) }; self.line(&format!("uint {t}_cls = img_cls(({tw1} >> 20) & 0x1FFu);")); match base { "load" | "load_mip" => { self.line(&format!("uint4 {t}_r;")); let ld = if dim == 6 { format!("{t}_T.Load({icoord}, {})", ic.get(2).cloned().unwrap_or("0u".into())) } else { format!("{t}_T.Load({load_arg})") }; - let tex = |vt: &str| format!("Texture{rty}<{vt}4> {t}_T = ResourceDescriptorHeap[NonUniformResourceIndex({tw0})];"); + let srv_i = srv_i(rty); + let tex = |vt: &str| format!("Texture{rty}<{vt}4> {t}_T = ResourceDescriptorHeap[NonUniformResourceIndex({srv_i})];"); self.line(&format!( "if ({t}_cls == 1u) {{ {} {t}_r = {ld}; }} else if ({t}_cls == 2u) {{ {} {t}_r = asuint({ld}); }} else {{ {} {t}_r = asuint({ld}); }}", tex("uint"), @@ -2355,7 +2374,7 @@ impl Em { }); } let v4 = format!("uint4({})", vals.join(", ")); - let uav = |vt: &str| format!("RWTexture{rty}<{vt}4> {t}_U = ResourceDescriptorHeap[NonUniformResourceIndex({tw0} + 1u)];"); + let uav = |vt: &str| format!("RWTexture{rty}<{vt}4> {t}_U = ResourceDescriptorHeap[NonUniformResourceIndex({uav_i})];"); self.line(&format!( "if ({act}) {{ if ({t}_cls == 1u) {{ {} {t}_U[{icoord}] = {v4}; }} else if ({t}_cls == 2u) {{ {} {t}_U[{icoord}] = (int4){v4}; }} else {{ {} {t}_U[{icoord}] = asfloat({v4}); }} }}", uav("uint"), @@ -2366,7 +2385,7 @@ impl Em { _ if base.starts_with("atomic_") && matches!(&base[7..], "cmpswap" | "sub" | "inc" | "dec" | "fcmpswap" | "fmin" | "fmax") => { // the operations without an int view: on the uint texel (CAS loops where needed) let (v, cmp) = (self.vreg(vdata), self.vreg(vdata + 1)); - self.line(&format!("RWTexture{rty} {t}_U = ResourceDescriptorHeap[NonUniformResourceIndex({tw0} + 1u)];")); + self.line(&format!("RWTexture{rty} {t}_U = ResourceDescriptorHeap[NonUniformResourceIndex({uav_i})];")); self.line(&format!("uint {t}_old = 0u;")); let body = rmw32(&base[7..], &At::Ref(format!("{t}_U[{icoord}]")), &v, &cmp, &format!("{t}_old"), &t).ok_or("image_atomic")?; self.line(&format!("if ({act}) {{ {body} }}")); @@ -2389,7 +2408,7 @@ impl Em { let v = self.vreg(vdata); let vt = if signed { "int" } else { "uint" }; let val = if signed { format!("(int){v}") } else { v.clone() }; - self.line(&format!("RWTexture{rty}<{vt}> {t}_U = ResourceDescriptorHeap[NonUniformResourceIndex({tw0} + 1u)];")); + self.line(&format!("RWTexture{rty}<{vt}> {t}_U = ResourceDescriptorHeap[NonUniformResourceIndex({uav_i})];")); self.line(&format!("{vt} {t}_old = 0;")); self.line(&format!("if ({act}) {{ {op}({t}_U[{icoord}], {val}, {t}_old); }}")); if f("GLC") == 1 { diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index c7f9cc42f..7f0d42f60 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -166,7 +166,8 @@ struct Bound { /// Create the descriptor heaps (always, so the directly indexed root signature is valid), /// the test textures and samplers; record the uploads into `list`. unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, textures: &[TestTexture], samplers: &[TestSampler]) -> Result { - let n = (2 * textures.len()).max(2) as u32; + // with textures: the heap translated shaders get in a title, with its null views at the end + let n = if textures.is_empty() { 2 } else { crate::gpu::desc::VIEW_HEAP_SIZE }; let heap: ID3D12DescriptorHeap = dev .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, @@ -186,6 +187,9 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; let sinc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) as usize; let at = |h: &ID3D12DescriptorHeap, k: usize, step: usize| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: h.GetCPUDescriptorHandleForHeapStart().ptr + k * step }; + if !textures.is_empty() { + crate::hle::d3d12x::console_heap::write_null_views(dev, heap.GetCPUDescriptorHandleForHeapStart().ptr, inc); + } for (j, sm) in samplers.iter().enumerate() { let mut sd = D3D12_SAMPLER_DESC { Filter: sm.filter, diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 596a74198..198f2ee66 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -7187,3 +7187,100 @@ fn fspx_containers_translate_and_compile() { println!("FSPX: {ok} / {n} translated and compiled"); assert_eq!(ok, n); } + +/// A T# whose word 0 is no heap index (a console address the title wrote without a view) must +/// not index past the shader-visible heap: RADV faulted on the GPU (SQC page fault at heap start +/// + word 0 · 32, device removed) while a retail game streamed its world. Such a T# reads the +/// null SRV at the heap's end (0) and its stores and atomics go to the null UAV (dropped), while +/// a real view next to it still works. +#[test] +fn gpu_image_with_no_heap_index_reads_zero_and_drops_writes() { + if !gpu_ready() { + return; + } + use runner::{TestSampler, TestTexture, TexDim}; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32_UINT}; + let mimg = |name: &'static str, f: &[(&str, u64)]| -> Vec { encode(name, "ENC_MIMG", f, None).unwrap() }; + let mut code = Vec::new(); + // garbage T# in s[16:23] (SRSRC = 4), S# in s[24:27] (SSAMP = 6); real UAV T# in s[32:39] (8) + code.extend(mimg("IMAGE_SAMPLE_LZ", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0xF), ("DIM", 1)])); + code.extend(mimg("IMAGE_LOAD", &[("VDATA", 14), ("VADDR", 3), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)])); + code.extend(mimg("IMAGE_STORE", &[("VDATA", 6), ("VADDR", 3), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)])); + code.extend(mimg("IMAGE_ATOMIC_UMAX", &[("VDATA", 7), ("VADDR", 3), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)])); + // the other texture types, each through its own null view + code.extend(mimg("IMAGE_SAMPLE_LZ", &[("VDATA", 16), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0xF), ("DIM", 2)])); + code.extend(mimg("IMAGE_SAMPLE_LZ", &[("VDATA", 20), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0xF), ("DIM", 3)])); + code.extend(mimg("IMAGE_LOAD", &[("VDATA", 24), ("VADDR", 3), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 5), ("UNORM", 1)])); + code.extend(mimg("IMAGE_STORE", &[("VDATA", 6), ("VADDR", 3), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 2), ("UNORM", 1)])); + code.extend(mimg("IMAGE_STORE", &[("VDATA", 6), ("VADDR", 3), ("SRSRC", 8), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)])); + // a null view's T# (all zero, s[40:47]) does not read the view at index 0; a real T# of it does + code.extend(mimg("IMAGE_LOAD", &[("VDATA", 25), ("VADDR", 3), ("SRSRC", 10), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)])); + code.extend(mimg("IMAGE_LOAD", &[("VDATA", 26), ("VADDR", 3), ("SRSRC", 12), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)])); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + + let mut st = KernelState::default(); + let mut garbage = tsharp(0, 77, 9); + garbage[0] = 0x9e55_ff68; // a console address, far past the heap + st.sgpr[16..24].copy_from_slice(&garbage); + st.sgpr[24..28].copy_from_slice(&[0, 0, 0, 0]); + st.sgpr[32..40].copy_from_slice(&tsharp(2, 20, 9)); + st.sgpr[40..48].copy_from_slice(&[0; 8]); + st.sgpr[48..56].copy_from_slice(&tsharp(0, 77, 9)); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = f(0.5); + r[1] = f(0.5); + r[3] = (l % 4) as u32; + r[4] = l as u32 / 4; // lanes 16.. land outside the 4x4 texture: their stores are dropped + r[5] = 0; + r[6] = 10 * l as u32 + 1; + r[7] = 0xFFFF_FFFF; + for v in 10..27 { + r[v] = 0xDEAD_BEEF; + } + } + let tex = vec![ + TestTexture { dim: TexDim::D2, format: DXGI_FORMAT_R32G32B32A32_FLOAT, width: 4, height: 4, depth: 1, texel_bytes: 16, data: vec![0x3F; 256], uav: false }, + TestTexture { dim: TexDim::D2, format: DXGI_FORMAT_R32_UINT, width: 4, height: 4, depth: 1, texel_bytes: 4, data: vec![0xEE; 64], uav: true }, + ]; + let samp = vec![TestSampler { filter: D3D12_FILTER_MIN_MAG_MIP_POINT, address: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, comparison: None }]; + let r = runner::run_code_with(&code, &st, &[], &tex, &samp).unwrap(); + for l in 0..64 { + assert_eq!(&r.vgpr[l][10..14], &[0, 0, 0, 0], "lane {l}: sample through the null SRV"); + assert_eq!(r.vgpr[l][14], 0, "lane {l}: load through the null SRV"); + assert_eq!(&r.vgpr[l][16..24], &[0; 8], "lane {l}: 3D and cube samples through their null SRVs"); + assert_eq!(r.vgpr[l][24], 0, "lane {l}: 2D array load through its null SRV"); + assert_eq!(r.vgpr[l][25], 0, "lane {l}: load through an all-zero T#"); + // (lanes 16.. load outside the texture: 0) + assert_eq!(r.vgpr[l][26], if l < 16 { 0x3F3F_3F3F } else { 0 }, "lane {l}: load through a real T# of view 0"); + } + // the real UAV got only its own stores: none of the garbage T#'s writes landed in it + let t1: Vec = r.textures[0].chunks(4).map(|c| u32::from_le_bytes(c.try_into().unwrap())).collect(); + for (i, &v) in t1.iter().enumerate() { + assert_eq!(v, 10 * i as u32 + 1, "real UAV texel {i}"); + } +} + +/// Each image declaration falls back to the null view of its own texture type, in 12 slots past +/// every view: D3D12 needs a null view's dimension to match the declaration (a Texture2D null +/// view for a Texture3D read is undefined on Windows drivers; RADV does not mind). +#[test] +fn image_declarations_fall_back_to_the_null_view_of_their_type() { + use crate::gpu::desc::{null_srv, null_uav, NULL_SRV_TYPES, NULL_UAV_TYPES, NULL_VIEWS, VIEW_HEAP_SIZE}; + let mut slots: Vec = NULL_SRV_TYPES.iter().map(|t| null_srv(t)).chain(NULL_UAV_TYPES.iter().map(|t| null_uav(t))).collect(); + slots.sort(); + slots.dedup(); + assert_eq!(slots, (NULL_VIEWS..VIEW_HEAP_SIZE).collect::>()); + let code = prog(&[ + ("IMAGE_SAMPLE_LZ", "ENC_MIMG", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0xF), ("DIM", 2)], None), + ("IMAGE_SAMPLE_LZ", "ENC_MIMG", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0xF), ("DIM", 3)], None), + ("IMAGE_LOAD", "ENC_MIMG", &[("VDATA", 14), ("VADDR", 3), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 5), ("UNORM", 1)], None), + ("IMAGE_STORE", "ENC_MIMG", &[("VDATA", 6), ("VADDR", 3), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 2), ("UNORM", 1)], None), + ]); + let t = translate(&code, &Options::default()).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported); + for (decl, null) in [(" Texture3D<", null_srv("3D")), (" TextureCubeArray<", null_srv("CubeArray")), (" Texture2DArray<", null_srv("2DArray")), (" RWTexture3D<", null_uav("3D"))] { + let line = t.hlsl.lines().find(|l| l.contains(decl) && l.contains("ResourceDescriptorHeap")).unwrap_or_else(|| panic!("no{decl}: {}", t.hlsl)); + assert!(line.contains(&format!(" : {null}u)")), "{line}"); + } +} diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 176973ea2..ae5dc5cb9 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -92,8 +92,6 @@ unsafe impl Send for Global {} static GLOBAL: Mutex> = Mutex::new(None); static GLOBAL_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); -/// descriptors of the shared heap at most (the GPU may take more: OPTIONS19) -const GLOBAL_MAX: u32 = 1 << 21; /// view slots per page of a heap's place in the shared heap (2 PC descriptors each) pub const PAGE_SLOTS: u32 = 256; @@ -133,30 +131,27 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { if GLOBAL_FAILED.load(Relaxed) { return false; } - let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS19::default(); - let max = if dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS19, &mut o as *mut _ as *mut std::ffi::c_void, std::mem::size_of_val(&o) as u32).is_ok() && o.MaxViewDescriptorHeapSize > 0 { - o.MaxViewDescriptorHeapSize - } else { - 1_000_000 - }; - let cap = max.min(GLOBAL_MAX); - let d = D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: cap, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }; + let size = crate::gpu::desc::VIEW_HEAP_SIZE; + let d = D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: size, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }; let heap: ID3D12DescriptorHeap = match dev.CreateDescriptorHeap(&d) { Ok(h) => h, Err(e) => { GLOBAL_FAILED.store(true, Relaxed); - crate::xlog_warn!("console descriptor heaps: no shared shader-visible heap of {cap} ({e}) – each keeps its own"); + crate::xlog_warn!("console descriptor heaps: no shared shader-visible heap of {size} ({e}) – each keeps its own"); return false; } }; - crate::xlog_info!("console descriptor heaps: one shader-visible PC heap of {cap} view descriptors for all of them"); + crate::xlog_info!("console descriptor heaps: one shader-visible PC heap of {size} view descriptors for all of them"); + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + write_null_views(dev, heap.GetCPUDescriptorHandleForHeapStart().ptr, inc as usize); *g = Some(Global { dev: dev.clone(), cpu: heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, gpu: heap.GetGPUDescriptorHandleForHeapStart().ptr, - inc: dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), + inc, heap, - cap, + // the null views at the end are no one's + cap: crate::gpu::desc::NULL_VIEWS, next: 0, free: Vec::new(), }); @@ -164,6 +159,57 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { true } +/// The null SRVs and UAVs (`desc::null_srv` / `null_uav`, one of each texture type) of the +/// shader-visible heap whose first descriptor is at `cpu`: recompiled shaders read and write +/// there through a T# whose word 0 is no heap index. +pub(crate) unsafe fn write_null_views(dev: &ID3D12Device, cpu: usize, inc: usize) { + use crate::gpu::desc::{null_srv, null_uav, NULL_SRV_TYPES, NULL_UAV_TYPES}; + use std::mem::{offset_of, size_of, transmute}; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R8G8B8A8_UNORM}; + let srv = |ty: &str| { + let (dim, view) = match ty { + "1D" => (D3D12_SRV_DIMENSION_TEXTURE1D, D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture1D: D3D12_TEX1D_SRV { MipLevels: 1, ..Default::default() } }), + "2D" => (D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() } }), + "3D" => (D3D12_SRV_DIMENSION_TEXTURE3D, D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture3D: D3D12_TEX3D_SRV { MipLevels: 1, ..Default::default() } }), + "CubeArray" => (D3D12_SRV_DIMENSION_TEXTURECUBEARRAY, D3D12_SHADER_RESOURCE_VIEW_DESC_0 { TextureCubeArray: D3D12_TEXCUBE_ARRAY_SRV { MipLevels: 1, NumCubes: 1, ..Default::default() } }), + "1DArray" => (D3D12_SRV_DIMENSION_TEXTURE1DARRAY, D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture1DArray: D3D12_TEX1D_ARRAY_SRV { MipLevels: 1, ArraySize: 1, ..Default::default() } }), + "2DArray" => (D3D12_SRV_DIMENSION_TEXTURE2DARRAY, D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2DArray: D3D12_TEX2D_ARRAY_SRV { MipLevels: 1, ArraySize: 1, ..Default::default() } }), + _ => (D3D12_SRV_DIMENSION_TEXTURE2DMS, D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2DMS: D3D12_TEX2DMS_SRV::default() }), + }; + D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT_R8G8B8A8_UNORM, ViewDimension: dim, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, Anonymous: view } + }; + let uav = |ty: &str| { + let (dim, view) = match ty { + "1D" => (D3D12_UAV_DIMENSION_TEXTURE1D, D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Texture1D: D3D12_TEX1D_UAV::default() }), + "2D" => (D3D12_UAV_DIMENSION_TEXTURE2D, D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_UAV::default() }), + "3D" => (D3D12_UAV_DIMENSION_TEXTURE3D, D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Texture3D: D3D12_TEX3D_UAV { WSize: 1, ..Default::default() } }), + "1DArray" => (D3D12_UAV_DIMENSION_TEXTURE1DARRAY, D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Texture1DArray: D3D12_TEX1D_ARRAY_UAV { ArraySize: 1, ..Default::default() } }), + _ => (D3D12_UAV_DIMENSION_TEXTURE2DARRAY, D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Texture2DArray: D3D12_TEX2D_ARRAY_UAV { ArraySize: 1, ..Default::default() } }), + }; + D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R32_UINT, ViewDimension: dim, Anonymous: view } + }; + let at = |k: u32| cpu + k as usize * inc; + // an adopted device's own methods: XCL's take handles into console heaps + use std::ffi::c_void; + use windows::core::Interface; + type Srv = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, usize); + type Uav = unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, usize); + let raw = dev.as_raw(); + let (create_srv, create_uav): (Srv, Uav) = if super::real::is_adopted(raw) { + const SRV: usize = offset_of!(ID3D12Device_Vtbl, CreateShaderResourceView) / size_of::(); + const UAV: usize = offset_of!(ID3D12Device_Vtbl, CreateUnorderedAccessView) / size_of::(); + (transmute(super::real::orig_fn(raw, SRV)), transmute(super::real::orig_fn(raw, UAV))) + } else { + (transmute(dev.vtable().CreateShaderResourceView), transmute(dev.vtable().CreateUnorderedAccessView)) + }; + for ty in NULL_SRV_TYPES { + create_srv(raw, std::ptr::null_mut(), &srv(ty), at(null_srv(ty))); + } + for ty in NULL_UAV_TYPES { + create_uav(raw, std::ptr::null_mut(), std::ptr::null_mut(), &uav(ty), at(null_uav(ty))); + } +} + /// `count` descriptors of the shared heap: the index of the first. None: no shared heap, or /// no room left in it. fn reserve_global(count: u32) -> Option {