From d52733518f8a980a8218ffd0a78d2c527f4b4bc5 Mon Sep 17 00:00:00 2001 From: BBareth <179921368+BBareth@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:28:27 +0100 Subject: [PATCH] D3D12.X: make shadowed textures active again when a draw samples them Table::insert shadows the active textures a newer one overlaps, and a placed texture over a different range is unmapped as well. Shadowed textures are never uploaded again, but a title can keep sampling them: GTA 6 samples the Bink planes of its credit-card scene after a newer placement lands over part of them, so the GPU read zeros and the cards rendered green with blocky streaks (over 131k draws sampled shadowed textures in one 355 s run). When a draw binds descriptor tables, the textures they name that are shadowed become active again: the active ones overlapping them are shadowed without being unmapped, the texture is marked pending (unless the GPU wrote it), remapped if it was unmapped, and its known content is forgotten so the next submit uploads it. When two overlapping textures are made active in turn before a submit (one draw sampling both, or two draws of one submission), the second shadows the first again. The first stays pending and the next submit uploads it all the same, since a draw already recorded samples it. Assisted-by: Codex CLI (gpt-6.2-sol) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/bind.rs | 40 ++++ crates/xcl/src/hle/d3d12x/title_textures.rs | 229 +++++++++++++++++++- 2 files changed, 266 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index b8206dea5c..2d8415ec2b 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -556,6 +556,41 @@ fn table_resources_of(this: *mut c_void, gfx: bool, slots: usize) -> Vec out } +/// Check the first 64 slots of each bound table. A texture descriptor copied as bytes still +/// samples the resource named by its heap index in word 0. +unsafe fn uncover_bound_tables(layout: Option<&Layout>, args: &[u8], u: &crate::gpu::uma::Uma) { + let Some(layout) = layout.filter(|_| super::title_textures::has_shadowed()) else { return }; + const TABLE_SLOTS: usize = 64; + let mut resources = Vec::new(); + for p in &layout.params { + let Param::Table { at } = *p else { continue }; + let at = at as usize; + let Some(word) = args.get(at..at + 4) else { continue }; + let offset = u32::from_le_bytes(word.try_into().unwrap()) as usize; + if offset == 0 { + continue; + } + let addr = u.base() + offset; + let mut table = [0u8; TABLE_SLOTS * 32]; + if u.in_committed_window(addr, table.len()) { + std::ptr::copy_nonoverlapping(addr as *const u8, table.as_mut_ptr(), table.len()); + } else { + super::title_textures::copy_readable(addr, &mut table); + } + for slot in table.chunks_exact(32) { + let index = u32::from_le_bytes(slot[..4].try_into().unwrap()); + if slot[15] >> 4 < 8 || index == 0 { + continue; + } + let res = super::console_heap::named_by_index(index); + if res != 0 && res != super::console_heap::GONE && !resources.contains(&res) { + resources.push(res); + } + } + } + super::title_textures::uncover_drawn(&resources); +} + /// `XCL_CAPTURE_FRAME`: a draw or dispatch of the title's on `this` (`gfx`: with the graphics /// root arguments), with the root arguments, heaps and pipeline it has, until the call returns. pub(super) unsafe fn capture_work(this: *mut c_void, kind: impl FnOnce() -> super::capture::WorkKind, gfx: bool) -> super::capture::Guard { @@ -1794,6 +1829,10 @@ unsafe fn prepare_two_pass_stage(this: *mut c_void, real_mesh_pso: usize, tp: &s if pso == 0 { return Err(if compute_pass { "two-pass compute pipeline" } else { "two-pass mesh pipeline" }.into()); } + if !compute_pass { + // Both passes use the same graphics root tables. + uncover_bound_tables(layout.as_deref(), &args, u); + } let w = |k: usize| super::real::uma_window_va(k).unwrap_or(first); Ok(StageBind { rs, pso, views: [va(io_at), res_va, w(0), w(1), w(2), w(3)] }) } @@ -3462,6 +3501,7 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi } let real = real as *mut c_void; let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?.clone(); + uncover_bound_tables(layout.as_deref(), &args, u); let b = Bound { rs, views, pso: pc, io: views[0] }; rebind(this, list, &b, gfx); Ok(b) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index fd04827aaf..5c139feab6 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -110,7 +110,7 @@ struct Table { by_res: BTreeMap, /// Active `(va, PC texture)` → end address (`va + size`); entries with different `(va, end)` are disjoint by_va: BTreeMap<(usize, usize), usize>, - /// Older overlapped textures kept dormant until released or uncovered when a newer one is released + /// Older overlapped textures kept dormant until sampled again or uncovered by a release shadowed: BTreeMap, /// Shadowed `(va, PC texture)` → end address (may overlap) shadowed_by_va: BTreeMap<(usize, usize), usize>, @@ -123,6 +123,9 @@ struct Table { src_pieces: BTreeMap>, /// textures whose first upload is still to come (`Entry::pending`; may name ones that went) pending_res: std::collections::BTreeSet, + /// pending textures `uncover` shadowed again: a draw of this submit may have made them active, + /// so the next submit still uploads them (they stay `Entry::pending`, uncounted in `PENDING`) + displaced: std::collections::BTreeSet, /// 16 MiB blocks of the textures' sources -> how many active ones cover it: the part of the /// watched ranges that textures make (cheap to rebuild from, unlike all textures) coarse: BTreeMap, @@ -154,6 +157,7 @@ impl Table { next_seq: 0, src_pieces: BTreeMap::new(), pending_res: std::collections::BTreeSet::new(), + displaced: std::collections::BTreeSet::new(), coarse: BTreeMap::new(), } } @@ -355,6 +359,52 @@ impl Table { (pending_delta, to_unmap) } + /// Reactivate a sampled texture and return its pending-count change and whether it needs + /// remapping. Keep displaced textures mapped for work that may still be using them. + fn uncover(&mut self, res: usize) -> Option<(isize, bool)> { + let mut e = self.shadowed.remove(&res)?; + self.shadowed_by_va.remove(&(e.va, res)); + let size = e.tex.size() as usize; + let (va, end) = (e.va, e.va.saturating_add(size)); + let mut pending_delta = 0; + for (ova, ores, oend) in self.active_overlaps(va, end) { + // Committed textures at the exact same range can coexist as format aliases. + if !e.placed && ova == va && oend == end && self.by_res.get(&ores).is_some_and(|o| !o.placed) { + continue; + } + self.by_va.remove(&(ova, ores)); + if let Some(old) = self.by_res.remove(&ores) { + self.unlink_src(ores, old.src, old.tex.size() as usize); + if old.pending { + self.pending_res.remove(&ores); + self.displaced.insert(ores); + pending_delta -= 1; + } + self.max_shadowed_size = self.max_shadowed_size.max(oend.saturating_sub(ova)); + self.shadowed_by_va.insert((ova, ores), oend); + self.shadowed.insert(ores, old); + } + } + if self.shadowed.is_empty() { + self.max_shadowed_size = 0; + } + let remap = std::mem::take(&mut e.unmapped); + texture_upload::forget(&e.known); + if !e.gpu_written { + e.pending = true; + } + if e.pending { + self.pending_res.insert(res); + pending_delta += 1; + } + self.next_seq += 1; + e.seq = self.next_seq; + self.by_va.insert((va, res), end); + self.link_src(res, e.src, size); + self.by_res.insert(res, e); + Some((pending_delta, remap)) + } + /// Remove `res` on COM release, reactivating any shadowed older textures it uncovered (newest /// first). Returns `(was_present, pending_delta, unmapped_res_to_remap)`. fn remove(&mut self, res: usize) -> (bool, isize, Vec) { @@ -445,6 +495,7 @@ static TEXTURES: Mutex = Mutex::new(Table::new()); static REFRESH: Mutex<()> = Mutex::new(()); static TEXTURES_GEN: AtomicU64 = AtomicU64::new(0); static TEXTURES_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static HAS_SHADOWED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// cached `watch_ranges` keyed by `watch_key` static WATCH_CACHE: Mutex>)>> = Mutex::new(None); /// the queue uploads go to, per device @@ -535,6 +586,7 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, let (delta, unmap_ptrs) = t.insert(res as usize, e); adjust_pending(delta); TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); + HAS_SHADOWED.store(!t.shadowed.is_empty(), Ordering::Relaxed); clone_resources(&unmap_ptrs) }; for r in &to_unmap { @@ -840,6 +892,7 @@ pub(super) unsafe fn retire_overlapping(va: usize, len: usize) { } adjust_pending(delta); TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); + HAS_SHADOWED.store(!t.shadowed.is_empty(), Ordering::Relaxed); (retired, clone_resources(&unmap_ptrs)) }; for r in &to_unmap { @@ -858,6 +911,7 @@ pub fn forget(res: usize) { let (removed, delta, remap_ptrs) = t.remove(res); adjust_pending(delta); TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); + HAS_SHADOWED.store(!t.shadowed.is_empty(), Ordering::Relaxed); (removed, unsafe { clone_resources(&remap_ptrs) }) }; for r in &to_remap { @@ -874,6 +928,54 @@ pub fn forget(res: usize) { } } +/// Whether a draw's descriptor tables might name a shadowed texture. +pub(super) fn has_shadowed() -> bool { + HAS_SHADOWED.load(Ordering::Relaxed) +} + +/// Restore sampled shadowed textures while recording so the next submit can upload them. +pub(super) fn uncover_drawn(res: &[usize]) { + if res.is_empty() { + return; + } + let (restored, remap) = { + let mut t = TEXTURES.lock().unwrap(); + let (mut restored, mut remap, mut delta) = (0, Vec::new(), 0); + for &r in res { + if let Some((d, unmapped)) = t.uncover(r) { + restored += 1; + delta += d; + if unmapped { + remap.push(r); + } + } + } + if restored == 0 { + return; + } + adjust_pending(delta); + TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); + HAS_SHADOWED.store(!t.shadowed.is_empty(), Ordering::Relaxed); + (restored, unsafe { clone_resources(&remap) }) + }; + for r in &remap { + unsafe { + super::vram::remap_if_unmapped(r); + // Lazy levels of a GPU-written texture cannot wait for a CPU upload to map them. + if super::vram::level_pages() && TEXTURES.lock().unwrap().get_mut(r.as_raw() as usize).is_some_and(|e| e.gpu_written) { + super::vram::map_levels(r, None); + } + } + } + TEXTURES_GEN.fetch_add(1, Ordering::Release); + static N: AtomicU64 = AtomicU64::new(0); + let before = N.fetch_add(restored, Ordering::Relaxed); + let n = before + restored; + if before == 0 || before.ilog2() != n.ilog2() { + crate::xlog_info!("D3D12.X: {n} shadowed textures sampled by draws so far were made active again ({} needed remapping in this batch)", remap.len()); + } +} + /// The title-memory address of a texture kept in step with it. pub fn address(res: usize) -> Option { let t = TEXTURES.lock().unwrap(); @@ -1762,13 +1864,22 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool) { let mut t = TEXTURES.lock().unwrap(); let mut names = t.touched_by(&dirty); names.extend(std::mem::take(&mut t.pending_res)); + let displaced = std::mem::take(&mut t.displaced); + names.extend(displaced.iter().copied()); let waiting = std::mem::take(&mut *AGAIN.lock().unwrap()); names.extend(waiting.iter().copied()); let mut later = std::collections::BTreeSet::new(); let todo = names .into_iter() .filter_map(|res| { - let e = t.by_res.get_mut(&res)?; + let active = t.by_res.contains_key(&res); + let e = if active { + t.by_res.get_mut(&res)? + } else if displaced.contains(&res) { + t.shadowed.get_mut(&res).filter(|e| e.pending && !e.unmapped)? + } else { + return None; + }; let mut again = texture_upload::Change::None; if waiting.contains(&res) && !e.gpu_written { let (queue, waited) = target.on(e.device); @@ -1786,7 +1897,8 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool) { return None; } let whole = e.pending; - if e.pending { + // (a displaced one stays pending: it goes up whole again if it is uncovered) + if e.pending && active { e.pending = false; PENDING.fetch_sub(1, Ordering::Relaxed); } @@ -3757,6 +3869,117 @@ pub(super) mod tests { assert!(!tbl.by_res.contains_key(&10) && !tbl.by_res.contains_key(&11) && tbl.by_res.contains_key(&12)); } + /// Sampling a shadowed texture makes it active, mapped and pending again. + #[test] + fn a_sampled_shadowed_texture_is_active_again() { + let tex_16k = Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 1, 1, 28, 0x105)).unwrap()); + let tex_64k = Arc::new(xg::Texture::new(&console_desc(3, 128, 128, 1, 1, 28, 0x105)).unwrap()); + let entry = |va: usize, tex: &Arc, pending: bool, placed: bool| Entry { + device: 0, + va, + src: va, + in_gpu_view: false, + paged: false, + tex: Arc::clone(tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending, + gpu_written: false, + written_call: 0, + placed, + unmapped: false, + seq: 0, + known: Default::default(), + target: false, + }; + let mut tbl = Table::new(); + assert_eq!(tbl.insert(1, entry(0x10_4000, &tex_16k, true, true)), (1, vec![])); + assert_eq!(tbl.insert(2, entry(0x10_0000, &tex_64k, true, true)), (0, vec![1])); + assert!(tbl.shadowed[&1].unmapped); + assert_eq!(tbl.uncover(2), None, "an active texture is not shadowed"); + + assert_eq!(tbl.uncover(1), Some((0, true))); + assert!(tbl.by_res[&1].pending && !tbl.by_res[&1].unmapped); + assert!(tbl.by_res[&1].seq > tbl.shadowed[&2].seq); + assert!(!tbl.by_res.contains_key(&2) && !tbl.shadowed[&2].unmapped); + assert_eq!(tbl.overlapping(0x10_0000, 0x1_0000), vec![(1, 0x10_4000)]); + assert_eq!(tbl.pending_res, [1].into_iter().collect()); + assert_eq!(tbl.touched_by(&[0x10_4000]), [1].into_iter().collect()); + + assert_eq!(tbl.uncover(2), Some((0, false))); + assert!(tbl.shadowed.contains_key(&1) && !tbl.shadowed[&1].unmapped); + assert!(tbl.displaced.contains(&1) && tbl.shadowed[&1].pending, "1 still goes up at the next submit"); + let (removed, _, remap) = tbl.remove(2); + assert_eq!((removed, remap), (true, vec![])); + assert!(tbl.by_res.contains_key(&1)); + + let mut gpu_alias = entry(0x20_0000, &tex_16k, false, false); + gpu_alias.gpu_written = true; + assert_eq!(tbl.insert(10, entry(0x20_0000, &tex_16k, false, false)), (0, vec![])); + assert_eq!(tbl.insert(11, gpu_alias), (0, vec![])); + assert_eq!(tbl.insert(12, entry(0x20_0000, &tex_64k, false, false)), (0, vec![])); + assert_eq!(tbl.uncover(10), Some((1, false))); + assert_eq!(tbl.uncover(11), Some((0, false))); + assert!(tbl.by_res.contains_key(&10) && !tbl.by_res[&11].pending && tbl.shadowed.contains_key(&12)); + } + + /// Real GPU: one draw samples two overlapping textures, A then B. B shadows A again before + /// the submit, and A is uploaded all the same (it read its old texels before). + #[test] + fn gpu_both_overlapping_textures_a_draw_samples_go_up() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + struct Registered(usize); + impl Drop for Registered { + fn drop(&mut self) { forget(self.0); } + } + unsafe { + let raw_device = super::super::real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let console = console_desc(3, 64, 64, 1, 1, DXGI_FORMAT_R8_UNORM.0 as u32, 1); + let size = xg::Texture::new(&console).unwrap().size() as usize; + let base = VirtualAlloc(std::ptr::null(), 2 * size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + let make = || { + let mut t = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, Height: 64, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }, + D3D12_RESOURCE_STATE_COMMON, None, &mut t, + ).unwrap(); + t.unwrap() + }; + let (a, b): (ID3D12Resource, ID3D12Resource) = (make(), make()); + let (ka, kb) = (a.as_raw() as usize, b.as_raw() as usize); + std::ptr::write_bytes(base as *mut u8, 0x11, 2 * size); + register(raw_device, a.as_raw(), base, &console, D3D12_RESOURCE_STATE_COMMON).unwrap(); + let _ra = Registered(ka); + refresh(queue.as_raw()); + // B lies over the second half of A and shadows it + register(raw_device, b.as_raw(), base + size / 2, &console, D3D12_RESOURCE_STATE_COMMON).unwrap(); + let _rb = Registered(kb); + refresh(queue.as_raw()); + assert!(TEXTURES.lock().unwrap().shadowed.contains_key(&ka)); + assert_eq!(read_r8(dev, &queue, &a), vec![0x11; 64 * 64]); + // the title writes the memory under both, then one draw samples A and B + std::ptr::write_bytes(base as *mut u8, 0x33, 2 * size); + uncover_drawn(&[ka, kb]); + assert!(TEXTURES.lock().unwrap().shadowed.contains_key(&ka), "B is the active one"); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &a), vec![0x33; 64 * 64], "A goes up although B shadowed it again"); + assert_eq!(read_r8(dev, &queue, &b), vec![0x33; 64 * 64]); + drop((_rb, _ra)); + VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } + /// Real GPU (#248): placed title textures share `vram::Pages` so streaming unreleased /// overlapping placements stays bounded in video memory, superseded textures never corrupt /// newer placements on shared tiles, 4 KiB-aligned neighbours never false-alias, and mip