From 7afecf845184279013bac99796d4d5b0417d6e4e Mon Sep 17 00:00:00 2001 From: nathan Date: Sun, 29 Nov 2026 18:01:40 +0100 Subject: [PATCH 1/2] D3D12.X: look for superseded targets in every declared table range MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A superseded target bound through a descriptor table is remapped when a draw or dispatch binds the table (#3179), but only the first 256 slots of each table were read. A view further in – a bindless SRV range, or a range at an explicit offset past slot 256 – was never seen: the target kept no tiles, its writes were dropped and its reads returned zeros. The root signature's SRV and UAV ranges of each descriptor table (RTS0 1.0 and 1.1, appended and unbounded ones included) are now kept in the layout, and the scan reads those ranges and nothing else. An unbounded range ends with the view heap the table lies in (console_heap::view_heap_remaining_slots); outside any view heap it has no known extent and is not read. CBV and sampler ranges cannot name a placed target and are skipped. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/bind.rs | 130 ++++++++++++++++++---- crates/xcl/src/hle/d3d12x/console_heap.rs | 9 ++ crates/xcl/src/hle/d3d12x/console_list.rs | 76 ++++++++++++- 3 files changed, 192 insertions(+), 23 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 7938495b9f..baa5a11c49 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -1302,35 +1302,75 @@ pub(super) fn bound_pso(this: *mut c_void) -> usize { with(this, |s| s.pso) } -/// Remap any superseded targets named in the first 256 slots of each descriptor table in `layout` -/// / `args`. Only called when `placements::any_superseded()` is true. +/// Remap any superseded targets named in the declared SRV/UAV descriptor ranges of `layout` / +/// `args`. Only called when `placements::any_superseded()` is true. unsafe fn note_superseded_in_tables(u: &crate::gpu::uma::Uma, layout: Option<&Layout>, args: &[u8]) { let Some(layout) = layout else { return }; - const TABLE_SLOTS: usize = 256; - let mut table = [0u8; TABLE_SLOTS * 32]; - for p in &layout.params { - let Param::Table { at } = *p else { continue }; - let at = at as usize; + scan_superseded_in_tables_with( + layout, + args, + u.base(), + super::console_heap::view_heap_remaining_slots, + |addr, len| u.in_committed_window(addr, len), + |addr, buf| super::title_textures::read_committed_into(addr, buf), + super::console_heap::named_by_index, + super::placements::note_use, + ); +} + +unsafe fn scan_superseded_in_tables_with( + layout: &Layout, + args: &[u8], + uma_base: usize, + mut heap_remaining: impl FnMut(usize) -> Option, + mut in_committed: impl FnMut(usize, usize) -> bool, + mut read_committed: impl FnMut(usize, &mut [u8]), + mut named_by_index: impl FnMut(u32) -> usize, + mut on_use: impl FnMut(usize), +) { + const CHUNK_SLOTS: usize = 256; + let mut chunk = [0u8; CHUNK_SLOTS * 32]; + for (at, ranges) in &layout.table_ranges { + 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; - if u.in_committed_window(addr, table.len()) { - std::ptr::copy_nonoverlapping(addr as *const u8, table.as_mut_ptr(), table.len()); - } else { - table.fill(0); - super::title_textures::read_committed_into(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 { - super::placements::note_use(res); + let Some(table_base) = uma_base.checked_add(offset) else { continue }; + let rem = heap_remaining(table_base); + for range in ranges { + let start = range.start as usize; + let total = match (rem, range.count) { + (Some(heap_rem), Some(c)) => (c as usize).min(heap_rem.saturating_sub(start)), + (Some(heap_rem), None) => heap_rem.saturating_sub(start), + (None, Some(c)) => c as usize, + // Unbounded range outside any registered view heap: no safe extent to scan. + (None, None) => 0, + }; + let mut done = 0usize; + while done < total { + let n = (total - done).min(CHUNK_SLOTS); + let bytes = n * 32; + let Some(addr) = start.checked_add(done).and_then(|s| s.checked_mul(32)).and_then(|b| table_base.checked_add(b)) else { break }; + let buf = &mut chunk[..bytes]; + if in_committed(addr, bytes) { + std::ptr::copy_nonoverlapping(addr as *const u8, buf.as_mut_ptr(), bytes); + } else { + buf.fill(0); + read_committed(addr, buf); + } + for slot in buf.chunks_exact(32) { + let index = u32::from_le_bytes(slot[..4].try_into().unwrap()); + if slot[15] >> 4 < 8 || index == 0 { + continue; + } + let res = named_by_index(index); + if res != 0 && res != super::console_heap::GONE { + on_use(res); + } + } + done += n; } } } @@ -5327,6 +5367,52 @@ mod tests { use std::sync::mpsc; use std::time::Duration; + /// A superseded target is looked for in the SRV / UAV ranges a table declares, however far + /// from the table's start (the first 256 slots only, before: a view at slot 300 was never + /// seen), and not in the slots between them. An unbounded range ends with the view heap the + /// table lies in; outside any view heap it is not read (no extent known). + #[test] + fn superseded_targets_are_found_in_every_declared_table_range() { + use console_list::TableRange; + const SLOTS: usize = 512; + let (uma_base, offset) = (0x1_0000_0000usize, 0x4000u32); + let table = uma_base + offset as usize; + // T#s (type nibble 8 in byte 15) naming shared-heap indexes 10 + k, at slots 10, 300 and 400 + let mut mem = vec![0u8; SLOTS * 32]; + for k in [10usize, 300, 400] { + mem[32 * k..32 * k + 4].copy_from_slice(&(10 + k as u32).to_le_bytes()); + mem[32 * k + 15] = 0x80; + } + let args = offset.to_le_bytes().to_vec(); + let found = |ranges: Vec, heap_slots: Option| { + let layout = Layout { table_ranges: vec![(0, ranges)], ..Default::default() }; + let mut used = Vec::new(); + unsafe { + scan_superseded_in_tables_with( + &layout, + &args, + uma_base, + |at| heap_slots.map(|n| n - (at - table) / 32), + |_, _| false, + |at, buf| buf.copy_from_slice(&mem[at - table..at - table + buf.len()]), + |index| 0x7000 + index as usize, + |res| used.push(res), + ); + } + used + }; + // an SRV range of 8 at slot 300: the target there, not the one at slot 10 + assert_eq!(found(vec![TableRange { start: 300, count: Some(8) }], Some(SLOTS)), vec![0x7000 + 310]); + // two ranges: both of their targets + assert_eq!(found(vec![TableRange { start: 0, count: Some(16) }, TableRange { start: 390, count: Some(16) }], Some(SLOTS)), vec![0x7000 + 20, 0x7000 + 410]); + // unbounded from 300: up to the view heap's end + assert_eq!(found(vec![TableRange { start: 300, count: None }], Some(SLOTS)), vec![0x7000 + 310, 0x7000 + 410]); + // unbounded outside any view heap: nothing read + assert!(found(vec![TableRange { start: 0, count: None }], None).is_empty()); + // a bounded range is cut at the view heap's end + assert_eq!(found(vec![TableRange { start: 300, count: Some(1000) }], Some(350)), vec![0x7000 + 310]); + } + #[test] fn aligned_list_addresses_reach_many_bind_shards() { let shards = (0..256).map(|index| state_shard_index(0x7100_0000 + index * 16)).collect::>(); diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 3c9dd506b8..3e44809a43 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -1083,6 +1083,15 @@ fn finish_view_slot(h: &Heap, k: u32, page: Option<(u32, u32)>) -> Slot { Slot { generation: h.generation, at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv, k, remaining: h.n - k } } +/// Remaining 32-byte view slots from `addr` to the end of the containing registered view heap, +/// without allocating shared-heap pages. Returns `None` if `addr` is not inside a view heap. +pub fn view_heap_remaining_slots(addr: usize) -> Option { + let heaps = HEAPS.lock().unwrap(); + let h = heaps.iter().find(|h| !h.sampler && addr >= h.shadow && addr < h.shadow + (h.n as usize) * (SLOT as usize))?; + let k = (addr - h.shadow) / (SLOT as usize); + Some((h.n as usize).saturating_sub(k)) +} + /// The slot behind a console CPU handle (None: not one of XCL's console heaps). A view slot /// of a heap in the shared heap gets its page's place there now if the page has none yet; one /// whose page finds no room there gets index 0, the null SRV / UAV pair. diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index ea46fa0e61..2c074034db 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -65,12 +65,22 @@ pub enum Param { Table { at: u32 }, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TableRange { + /// Descriptor slot offset from the start of the descriptor table. + pub start: u32, + /// Number of descriptors (`None` = unbounded, `u32::MAX` in RTS0). + pub count: Option, +} + /// Where a root signature's arguments go: all of them packed in order (`at`, `size` bytes); /// the first `inline` bytes of that are passed in user SGPRs (compute from s4, graphics /// stages from s8: `inline_gfx` bytes), the rest is the table. #[derive(Debug, Default)] pub struct Layout { pub params: Vec, + /// Declared SRV/UAV descriptor intervals per descriptor-table parameter (`(at, ranges)`). + pub table_ranges: Vec<(u32, Vec)>, pub size: u32, pub inline: u32, pub inline_gfx: u32, @@ -149,6 +159,7 @@ pub fn layout_from_blob(blob: &[u8]) -> Option { None => blob.to_vec(), }; let r = |o: usize| rts0.get(o..o + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); + let version = r(0)?; let (n, poff) = (r(4)? as usize, r(8)? as usize); let flags = r(20).unwrap_or(0); let mut l = Layout { heaps: [CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED, SAMPLER_HEAP_DIRECTLY_INDEXED].map(|f| flags & f != 0), ..Default::default() }; @@ -163,7 +174,34 @@ pub fn layout_from_blob(blob: &[u8]) -> Option { let p = match ty { 1 => Param::Constants { at: l.size, count: r(pay + 8)? }, 2..=4 => Param::Descriptor { at: l.size }, - _ => Param::Table { at: l.size }, + _ => { + if ty == 0 { + let mut ranges = Vec::new(); + if let (Some(nr), Some(roff)) = (r(pay), r(pay + 4)) { + let stride = if version >= 2 { 24usize } else { 20usize }; + let off_field = if version >= 2 { 20usize } else { 16usize }; + let mut next_offset = 0u32; + for j in 0..nr as usize { + let Some(base) = (roff as usize).checked_add(j.checked_mul(stride).unwrap_or(usize::MAX)) else { break }; + let (Some(rty), Some(num), Some(raw_off)) = (r(base), r(base + 4), r(base + off_field)) else { break }; + let start = if raw_off == u32::MAX { next_offset } else { raw_off }; + let count = if num == u32::MAX { None } else { Some(num) }; + next_offset = match count { + Some(c) => start.saturating_add(c), + None => u32::MAX, + }; + // 0 = SRV, 1 = UAV (only views that can reference a placed target) + if (rty == 0 || rty == 1) && num != 0 { + ranges.push(TableRange { start, count }); + } + } + } + if !ranges.is_empty() { + l.table_ranges.push((l.size, ranges)); + } + } + Param::Table { at: l.size } + } }; let bytes = match p { Param::Constants { count, .. } => count.checked_mul(4)?, @@ -1306,6 +1344,42 @@ mod tests { assert_eq!(&got[16..], &[1, 2, 0x5000, 4, 0x80]); } + /// A root signature whose only parameter is a descriptor table, in RTS0 `version` (1: 1.0, + /// 2: 1.1), with `ranges` of (range type, descriptors, offset from the table start). + fn rts0_table(version: u32, ranges: &[(u32, u32, u32)]) -> Vec { + // header (24 B), one parameter (12 B), its table payload (8 B), then the ranges + let (param, pay, roff) = (24u32, 36u32, 44u32); + let mut r = vec![version, 1, param, 0, 0, 0, 0, 0, pay, ranges.len() as u32, roff]; + for &(ty, num, off) in ranges { + if version >= 2 { + r.extend([ty, num, 0, 0, 0, off]); + } else { + r.extend([ty, num, 0, 0, off]); + } + } + r.iter().flat_map(|w| w.to_le_bytes()).collect() + } + + /// A table's SRV and UAV ranges are kept with their offsets from the table start (appended + /// ones after the range before them, unbounded ones without a count); CBV and sampler ranges + /// cannot name a placed target and are left out. Both range layouts (1.0: 20 bytes, 1.1: 24). + #[test] + fn descriptor_tables_keep_their_srv_and_uav_ranges() { + const APPEND: u32 = u32::MAX; + for version in [1, 2] { + // SRV 4 at 0, CBV 2 appended (4..6), UAV unbounded appended (6..), sampler 1 at 0 + let blob = rts0_table(version, &[(0, 4, 0), (2, 2, APPEND), (1, u32::MAX, APPEND), (3, 1, 0)]); + let l = layout_from_blob(&blob).expect("layout"); + assert_eq!(l.table_ranges, vec![(0, vec![TableRange { start: 0, count: Some(4) }, TableRange { start: 6, count: None }])], "version {version}"); + // an SRV range past the first 256 slots, at an explicit offset + let blob = rts0_table(version, &[(1, 8, 300)]); + assert_eq!(layout_from_blob(&blob).expect("layout").table_ranges, vec![(0, vec![TableRange { start: 300, count: Some(8) }])], "version {version}"); + // a table of constant buffers only: nothing to look at + let blob = rts0_table(version, &[(2, 16, 0)]); + assert!(layout_from_blob(&blob).expect("layout").table_ranges.is_empty(), "version {version}"); + } + } + #[test] fn force_memory_based_abi_spills_all_parameters_and_strips_xbox_flags() { let mut blob = rts0(&[(1, 2), (2, 0), (0, 0)]); From bdf38bf4361a4d7a7af678cce7d9a5e4e356e1ef Mon Sep 17 00:00:00 2001 From: lnqigr Date: Sun, 29 Nov 2026 02:24:06 +0100 Subject: [PATCH 2/2] D3D12.X: defer GPU-owned target pages until first use Keep XCL_LAZY_TARGETS opt-in. Defer shared video-memory tiles for GPU-owned placed targets and map them before command-list or upload use. Track copied RTV and DSV handles while mapping is pending. Reject a command list if first use cannot allocate its tiles. Unmapped targets remain eligible for a retry after reset. Cover deferred allocation, first use, and submission refusal. Views bound through descriptor tables are looked for in every SRV/UAV range the root signature declares, with the range walk of #3443 (now for_each_declared_table_slot), not only in the first 64 slots of each table: a target bound further in would otherwise keep no tiles. Related to #3211 and #1773. Assisted-by: Antigravity (Gemini 4 Neon) Assisted-by: Codex (GPT-6) Co-Authored-By: Claude Opus 5.5 --- README.md | 3 + crates/xcl/src/hle/d3d12x/bind.rs | 123 ++++- crates/xcl/src/hle/d3d12x/console_list.rs | 23 + crates/xcl/src/hle/d3d12x/list_x.rs | 67 ++- crates/xcl/src/hle/d3d12x/real.rs | 36 +- crates/xcl/src/hle/d3d12x/sharded.rs | 6 + crates/xcl/src/hle/d3d12x/title_textures.rs | 3 + crates/xcl/src/hle/d3d12x/vram.rs | 503 +++++++++++++++++++- 8 files changed, 749 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 3f76544f6a..61b1563d25 100644 --- a/README.md +++ b/README.md @@ -402,6 +402,9 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. console shaders' hashes (`cs`, `vs` / `ps`, `ms` / `ps`, `vs` / `gs` / `ps`). - `XCL_TEXTURE_LEVEL_PAGES=1` gives sampled title textures backing as their mip levels stream in. Zero-filled mip uploads in a batch share one staging span and still clear any mapped tiles. +- `XCL_LAZY_TARGETS=1` defers binding 64 KiB video-memory tiles for GPU-owned placed targets until + their first command-list or upload use, avoiding VRAM allocation for targets created upfront but + never touched. - `XCL_DSTORAGE_PARALLEL_DECOMPRESS=1` enables parallel CPU decompression for file-backed zlib requests with virtual destinations. Defaults: four workers and a shared 32 MiB staging budget (`XCL_DSTORAGE_WORKERS`, `XCL_DSTORAGE_MEMORY_BUDGET_MIB`). Requests retire in queue order. diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index baa5a11c49..e36110d36f 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -1328,6 +1328,29 @@ unsafe fn scan_superseded_in_tables_with( mut named_by_index: impl FnMut(u32) -> usize, mut on_use: impl FnMut(usize), ) { + for_each_declared_table_slot(layout, args, uma_base, heap_remaining, in_committed, read_committed, |slot| { + let index = u32::from_le_bytes(slot[..4].try_into().unwrap()); + if slot[15] >> 4 >= 8 && index != 0 { + let res = named_by_index(index); + if res != 0 && res != super::console_heap::GONE { + on_use(res); + } + } + true + }); +} + +/// Calls `on_slot` with each 32-byte slot of the SRV/UAV ranges the tables of `layout` declare, +/// read in chunks of 256 slots. False: `on_slot` returned false and the walk stopped there. +unsafe fn for_each_declared_table_slot( + layout: &Layout, + args: &[u8], + uma_base: usize, + mut heap_remaining: impl FnMut(usize) -> Option, + mut in_committed: impl FnMut(usize, usize) -> bool, + mut read_committed: impl FnMut(usize, &mut [u8]), + mut on_slot: impl FnMut(&[u8]) -> bool, +) -> bool { const CHUNK_SLOTS: usize = 256; let mut chunk = [0u8; CHUNK_SLOTS * 32]; for (at, ranges) in &layout.table_ranges { @@ -1361,19 +1384,15 @@ unsafe fn scan_superseded_in_tables_with( read_committed(addr, buf); } for slot in buf.chunks_exact(32) { - let index = u32::from_le_bytes(slot[..4].try_into().unwrap()); - if slot[15] >> 4 < 8 || index == 0 { - continue; - } - let res = named_by_index(index); - if res != 0 && res != super::console_heap::GONE { - on_use(res); + if !on_slot(slot) { + return false; } } done += n; } } } + true } /// `XCL_DUMP_TARGETS`: the resources the first 16 slots of each descriptor table of `this`'s @@ -1639,6 +1658,49 @@ pub(super) fn want_root_views(layout: Option<&Layout>, args: &[u8], path: super: } } +/// Bind tiles for any unmapped lazy GPU-owned targets referenced through root descriptor tables +/// before recording a translated draw or dispatch (`XCL_LAZY_TARGETS=1`). +#[must_use] +pub(super) unsafe fn ensure_table_lazy_targets(layout: Option<&Layout>, args: &[u8]) -> bool { + if !super::vram::has_unmapped_lazy_targets() { + return true; + } + let Some(l) = layout else { return true }; + let Some(u) = crate::gpu::uma::get() else { return true }; + ensure_table_lazy_targets_with( + l, + args, + u.base(), + super::console_heap::view_heap_remaining_slots, + |addr, len| u.in_committed_window(addr, len), + |addr, buf| super::title_textures::read_committed_into(addr, buf), + super::console_heap::named_by_index, + |res| super::vram::ensure_target_mapped(res), + ) +} + +unsafe fn ensure_table_lazy_targets_with( + layout: &Layout, + args: &[u8], + uma_base: usize, + heap_remaining: impl FnMut(usize) -> Option, + in_committed: impl FnMut(usize, usize) -> bool, + read_committed: impl FnMut(usize, &mut [u8]), + mut named_by_index: impl FnMut(u32) -> usize, + mut ensure_mapped: impl FnMut(usize) -> bool, +) -> bool { + for_each_declared_table_slot(layout, args, uma_base, heap_remaining, in_committed, read_committed, |slot| { + let w0 = u32::from_le_bytes(slot[..4].try_into().unwrap()); + if slot[15] >> 4 < 8 || w0 >= super::console_heap::GLOBAL_MAX || (w0 & 1) != 0 { + return true; + } + [w0, w0 + 1].into_iter().all(|idx| { + let res = named_by_index(idx); + res == 0 || res == super::console_heap::GONE || ensure_mapped(res) + }) + }) +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct DispatchMeshSig { companion_dispatch: usize, @@ -5297,6 +5359,9 @@ unsafe fn bind_abi_with_root_resolved( if super::placements::any_superseded() { note_superseded_in_tables(u, layout.as_deref(), &args); } + if !super::list_x::require_target_pages(this, ensure_table_lazy_targets(layout.as_deref(), &args)) { + return Err("could not bind lazy target pages for a root descriptor table".into()); + } std::ptr::copy_nonoverlapping(args[inline..].as_ptr(), table_at as *mut u8, args.len() - inline); let io = prepared_abi_io(layout.as_deref(), &args, table_at, gfx, user_sgprs, u.base(), heaps, limits, groups, group_limit); let io_bytes = io.iter().flat_map(|word| word.to_le_bytes()).collect::>(); @@ -5413,6 +5478,50 @@ mod tests { assert_eq!(found(vec![TableRange { start: 300, count: Some(1000) }], Some(350)), vec![0x7000 + 310]); } + /// A lazy target bound through a descriptor table gets its tiles wherever its view lies in a + /// declared SRV / UAV range (the first 64 slots only, before: a view at slot 100 kept no + /// tiles), not in the slots between ranges; a failed mapping refuses the table. + #[test] + fn lazy_targets_are_mapped_in_every_declared_table_range() { + use console_list::TableRange; + const SLOTS: usize = 256; + let (uma_base, offset) = (0x1_0000_0000usize, 0x4000u32); + let table = uma_base + offset as usize; + // T#s (type nibble 8 in byte 15) naming even shared-heap indexes 2 * k, at slots 10, 100 and 200 + let mut mem = vec![0u8; SLOTS * 32]; + for k in [10usize, 100, 200] { + mem[32 * k..32 * k + 4].copy_from_slice(&(2 * k as u32).to_le_bytes()); + mem[32 * k + 15] = 0x80; + } + let args = offset.to_le_bytes().to_vec(); + let mapped = |ranges: Vec, ok: bool| { + let layout = Layout { table_ranges: vec![(0, ranges)], ..Default::default() }; + let mut asked = Vec::new(); + let done = unsafe { + ensure_table_lazy_targets_with( + &layout, + &args, + uma_base, + |at| Some(SLOTS - (at - table) / 32), + |_, _| false, + |at, buf| buf.copy_from_slice(&mem[at - table..at - table + buf.len()]), + |index| 0x7000 + index as usize, + |res| { + asked.push(res); + ok + }, + ) + }; + (done, asked) + }; + // a range of 8 at slot 96: the view at slot 100 (and its pair), not the one at slot 10 + assert_eq!(mapped(vec![TableRange { start: 96, count: Some(8) }], true), (true, vec![0x7000 + 200, 0x7000 + 201])); + // unbounded from 0: every view up to the view heap's end + assert_eq!(mapped(vec![TableRange { start: 0, count: None }], true).1, vec![0x7000 + 20, 0x7000 + 21, 0x7000 + 200, 0x7000 + 201, 0x7000 + 400, 0x7000 + 401]); + // a mapping that fails stops the walk and refuses the table + assert_eq!(mapped(vec![TableRange { start: 96, count: Some(8) }], false), (false, vec![0x7000 + 200])); + } + #[test] fn aligned_list_addresses_reach_many_bind_shards() { let shards = (0..256).map(|index| state_shard_index(0x7100_0000 + index * 16)).collect::>(); diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 2c074034db..5a1077bfbf 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -995,6 +995,19 @@ pub unsafe fn close(obj: *mut c_void) -> Result { for c in b.chunks_exact(4).filter(|c| c[0] as u32 == 0) { super::placements::note_use(c[1] as usize); } + if super::vram::has_unmapped_lazy_targets() { + for c in b.chunks_exact(4) { + let mapped = match c[0] as u32 { + 0 | 2 => super::vram::ensure_target_mapped(c[1] as usize), + 1 => super::vram::ensure_target_mapped(c[1] as usize) + && super::vram::ensure_target_mapped(c[2] as usize), + _ => true, + }; + if !super::list_x::require_target_pages(list.as_raw(), mapped) { + break 'chunks; + } + } + } list.ResourceBarrier(std::slice::from_raw_parts(b.as_ptr() as *const D3D12_RESOURCE_BARRIER, m)); } out.barriers += n as u32; @@ -1020,6 +1033,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { // list's clear: `list_x::clear_uav`); None: not done let target = super::list_x::uav_clear_resource(res as usize, Some(g)).map(|t| t as *mut c_void); if let Some(r) = target.as_ref().and_then(|t| ID3D12Resource::from_raw_borrowed(t)) { + if !super::list_x::require_target_pages(list.as_raw(), super::vram::ensure_target_mapped(r.as_raw() as usize)) { + break 'chunks; + } let (gh, ch) = (D3D12_GPU_DESCRIPTOR_HANDLE { ptr: g.pc_gpu_uav }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: c.pc_uav as usize }); if get(1) != 0 { let f = values.map(f32::from_bits); @@ -1047,6 +1063,10 @@ pub unsafe fn close(obj: *mut c_void) -> Result { let bx: [u32; 6] = [get(29), get(30), get(31), get(32), get(33), get(34)]; let (pd, ps) = (dst[0] as *mut c_void, src[0] as *mut c_void); if ID3D12Resource::from_raw_borrowed(&pd).is_some() && ID3D12Resource::from_raw_borrowed(&ps).is_some() { + let mapped = super::vram::ensure_target_mapped(pd as usize) && super::vram::ensure_target_mapped(ps as usize); + if !super::list_x::require_target_pages(list.as_raw(), mapped) { + break 'chunks; + } list.CopyTextureRegion( dst.as_ptr() as *const D3D12_TEXTURE_COPY_LOCATION, get(13), @@ -1084,6 +1104,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { let user_sgprs = super::real::pso_user_sgprs_exact(real); // (the list is submitted after this: its root views in a GPU view get their tiles there) super::bind::want_root_views(layout.as_deref(), &table, super::view_want::Path::RootView); + if !super::list_x::require_target_pages(list.as_raw(), super::bind::ensure_table_lazy_targets(layout.as_deref(), &table)) { + break 'chunks; + } let inline = layout.as_ref().map_or(0, |l| inline_for(l, user_sgprs) as usize).min(table.len()); let table_at = uma_copy(st, &table[inline..]).ok_or("UMA: argument table")?; let mut io = match layout.as_ref() { diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 3a324390bc..985df46b74 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1208,6 +1208,14 @@ pub(super) fn poison_recording(list: usize) { POISONED_EVER.store(true, Ordering::Release); } +/// An unmapped first-use target makes the entire recording unsafe to submit. +pub(super) fn require_target_pages(list: *mut c_void, mapped: bool) -> bool { + if !mapped { + poison_recording(list as usize); + } + mapped +} + pub(super) fn recording_poisoned(list: usize) -> bool { if !POISONED_EVER.load(Ordering::Acquire) { return false; @@ -5248,7 +5256,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { physical.push(this); } if any_recording_poisoned(&physical) { - return warn(&ERR, "KickoffX", format_args!("recording is poisoned by an unavailable pipeline bind")); + return warn(&ERR, "KickoffX", format_args!("recording is poisoned")); } let ty = list_type(this); if ty == D3D12_COMMAND_LIST_TYPE_BUNDLE { @@ -6443,6 +6451,20 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 if uav_transition && !any_uav { out.push([2, 0, 0, 0, 0, 0, 0, 0]); } + if super::vram::has_unmapped_lazy_targets() { + for b in &out { + let r0 = (b[2] as u64 | (b[3] as u64) << 32) as usize; + let r1 = (b[4] as u64 | (b[5] as u64) << 32) as usize; + let mapped = match b[0] { + 0 | 2 => super::vram::ensure_target_mapped(r0), + 1 => super::vram::ensure_target_mapped(r0) && super::vram::ensure_target_mapped(r1), + _ => true, + }; + if !require_target_pages(this, mapped) { + return; + } + } + } // depth buffers whose depth plane can have a twin: in PARK where the title has them in // UNORDERED_ACCESS, the twin copied around the transitions (`depth_uav`) let plane_copies = super::depth_uav::any_kept().then(|| { @@ -6939,8 +6961,15 @@ pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, ds }; note_texture_write(this as usize, r, sub); super::placements::note_use(r); + let mut mapped = super::vram::ensure_target_mapped(r); if let Some(s) = src.as_ref() { - super::placements::note_use(transmute_copy(&s.pResource)); + let sr: usize = transmute_copy(&s.pResource); + super::placements::note_use(sr); + mapped = mapped && super::vram::ensure_target_mapped(sr); + } + if !require_target_pages(this, mapped) { + _c.amend(|op| if let super::capture::Op::Copy { refused, .. } = op { *refused = true }); + return; } super::lut3d::wrote(r, true, || { let from = src.as_ref().map_or("nothing".to_string(), |sl| { @@ -7060,6 +7089,10 @@ pub(super) unsafe extern "system" fn clear_depth_stencil_x(this: *mut c_void, ds ); } } + if !require_target_pages(this, super::vram::ensure_target_view_mapped(dsv)) { + _c.amend(|op| if let super::capture::Op::Clear { refused, .. } = op { *refused = true }); + return; + } pc::(this, PC_CLEAR_DEPTH_STENCIL_VIEW)(this, dsv, flags, depth, stencil, n, rects) } @@ -7126,6 +7159,9 @@ unsafe fn clear_uav(this: *mut c_void, slot: usize, gpu: u64, cpu: u64, res: usi } }; let Some(res) = uav_clear_resource(res, gpu_slot) else { return refused() }; + if !require_target_pages(this, super::vram::ensure_target_mapped(res)) { + return refused(); + } pc::(this, slot)(this, gpu, cpu, res, values, n, rects) } @@ -7175,6 +7211,10 @@ pub(super) unsafe extern "system" fn resolve_subresource_x(this: *mut c_void, ds }); super::present::note_use(dst, super::present::USE_COPY); note_texture_write(this as usize, dst, dst_sub); + let mapped = super::vram::ensure_target_mapped(dst) && super::vram::ensure_target_mapped(src); + if !require_target_pages(this, mapped) { + return; + } trace_resolve("ResolveSubresource", dst, src, format, ""); pc::(this, PC_RESOLVE_SUBRESOURCE)(this, dst, dst_sub, src, src_sub, format) } @@ -7192,6 +7232,10 @@ pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_v }); super::present::note_use(dst, super::present::USE_COPY); note_texture_write(this as usize, dst, dst_sub); + let mapped = super::vram::ensure_target_mapped(dst) && super::vram::ensure_target_mapped(src); + if !require_target_pages(this, mapped) { + return; + } if super::present::trace_frame() { trace_resolve("ResolveSubresourceRegion", dst, src, format, &format!(" mode {mode} at ({x}, {y}) rect {:?}", rect.as_ref().map(|r| (r.left, r.top, r.right, r.bottom)))); } @@ -7211,6 +7255,10 @@ pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usi note_texture_write(this as usize, dst, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES); super::placements::note_use(dst); super::placements::note_use(src); + let mapped = super::vram::ensure_target_mapped(dst) && super::vram::ensure_target_mapped(src); + if !require_target_pages(this, mapped) { + return; + } super::lut3d::wrote(dst, true, || format!("CopyResource from {src:#x}")); if super::present::trace_frame() { trace_watched_copy("CopyResource", dst, src); @@ -7322,6 +7370,21 @@ pub(super) unsafe extern "system" fn resolve_query_data_x(this: *mut c_void, hea mod tests { use super::*; + #[test] + fn failed_lazy_target_binding_rejects_submission_until_reset() { + let mut list_identity = 0u8; + let list = std::ptr::from_mut(&mut list_identity).cast::(); + assert!(super::require_target_pages(list, true)); + assert!(!super::any_recording_poisoned(&[list])); + assert!(!super::require_target_pages(list, false)); + assert!(super::any_recording_poisoned(&[list])); + assert!(super::require_target_pages(list, true)); + assert!(super::any_recording_poisoned(&[list])); + super::on_pc_reset(list); + assert!(!super::any_recording_poisoned(&[list])); + super::on_release(list as usize); + } + #[repr(C)] struct ReentrantGenerationPso { vtable: *const usize, diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 6fcaf053c6..db63eaccbb 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2914,6 +2914,9 @@ unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u3 if ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32 { super::depth_uav::dsvs_copied(this, n, dst, src); } + if ty == D3D12_DESCRIPTOR_HEAP_TYPE_RTV.0 as u32 || ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32 { + super::vram::copy_target_views_simple(this, n, dst, src, ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32); + } let f: unsafe extern "system" fn(*mut c_void, u32, u64, u64, u32) = std::mem::transmute(orig_fn(this, 24)); f(this, n, dst, src, ty); } @@ -2935,6 +2938,9 @@ unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dst if ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32 { super::depth_uav::dsv_ranges_copied(this, nd, dsts, dsizes, ns, srcs, ssizes); } + if ty == D3D12_DESCRIPTOR_HEAP_TYPE_RTV.0 as u32 || ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32 { + super::vram::copy_target_views_ranges(this, nd, dsts, dsizes, ns, srcs, ssizes, ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32); + } type F = unsafe extern "system" fn(*mut c_void, u32, *const u64, *const u32, u32, *const u64, *const u32, u32); let f: F = std::mem::transmute(orig_fn(this, 23)); return f(this, nd, dsts, dsizes, ns, srcs, ssizes, ty); @@ -3144,6 +3150,7 @@ unsafe extern "system" fn dev_create_dsv_x(this: *mut c_void, res: *mut c_void, let flags = copy.as_ref().map_or(0, |c| c.Flags.0 as u32); f(this, res, copy.as_ref().map_or(desc, |c| c as *const _), cpu); super::depth_uav::note_dsv(cpu as usize, res as usize, flags); + super::vram::note_target_view(this, cpu as usize, res as usize, true); } /// The view a DSV without a description has, for a depth buffer `pc_resource_desc` made @@ -4108,7 +4115,6 @@ macro_rules! as_usize { /// subsequent Reset and console calls dispatch through the current native table. unsafe extern "system" fn cl_close(this: *mut c_void) -> HRESULT { let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailListLifecycle); - let poisoned = super::list_x::recording_poisoned(this as usize); let _t = crate::hle::api_cost::time_if( super::look_stats::deep() && !super::title_textures::is_own_work() && !super::present::presenting(), crate::hle::api_cost::Call::ListLifecycle, @@ -4116,11 +4122,13 @@ unsafe extern "system" fn cl_close(this: *mut c_void) -> HRESULT { super::bind::flush_two_pass(this, super::bind::RunEnd::Close); super::list_x::before_close(this); super::gpu_times::before_close(this); + let poisoned = super::list_x::recording_poisoned(this as usize); let ext = *(this as *const usize); let f: RefFn = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12GraphicsCommandList", "Close"))); let hr = f(this) as HRESULT; preserve_vtable(this, ext); if hr >= 0 + && !poisoned && !super::title_textures::is_own_work() && !super::present::presenting() && super::title_list::wrapper_of(this).is_none() @@ -4133,7 +4141,7 @@ unsafe extern "system" fn cl_close(this: *mut c_void) -> HRESULT { crate::xlog_warn!("D3D12.X: command list {this:p} (type {}) Close → {:#x}", ty(this), hr as u32); } if poisoned { - crate::xlog_warn!("D3D12.X: command list {this:p} poisoned by an unavailable pipeline bind"); + crate::xlog_warn!("D3D12.X: command list {this:p} has a poisoned recording"); crate::util::E_FAIL } else { hr @@ -11177,6 +11185,7 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de let desc = copy.as_ref().map_or(desc, |c| c as *const _ as *const c_void); f(this, res, desc, handle); super::present::note_rtv(handle, res); + super::vram::note_target_view(this, handle, res as usize, false); if super::capture::enabled() { super::capture::note_view(handle, res as usize, false, (!desc.is_null()).then(|| (desc as *const [u32; 6]).read_unaligned())); } @@ -11217,6 +11226,9 @@ unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *co super::lut3d::wrote(r, false, || format!("ClearRenderTargetView {rtv:#x} to {:?}, {n} rects", color.as_ref())); } } + if !super::list_x::require_target_pages(this, super::vram::ensure_target_view_mapped(rtv)) { + return; + } f(this, rtv, color, n, rects) } @@ -11228,6 +11240,26 @@ unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rt ); type F = unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize); let f: F = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12GraphicsCommandList", "OMSetRenderTargets"))); + if super::vram::has_unmapped_lazy_targets() { + let count = if rtvs.is_null() { 0 } else { n.min(D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) as usize }; + if count > 0 { + let inc = if single != 0 { super::vram::rtv_increment_for_list(this) } else { 0 }; + if single != 0 && count > 1 && inc == 0 { + crate::xlog_warn!("D3D12.X: cannot resolve contiguous RTV handles for lazy target binding"); + super::list_x::poison_recording(this as usize); + return; + } + for k in 0..count { + let h = if single != 0 { (*rtvs).wrapping_add(k.wrapping_mul(inc)) } else { *rtvs.add(k) }; + if !super::list_x::require_target_pages(this, super::vram::ensure_target_view_mapped(h)) { + return; + } + } + } + if !dsv.is_null() && !super::list_x::require_target_pages(this, super::vram::ensure_target_view_mapped(*dsv)) { + return; + } + } f(this, n, rtvs, single, dsv); super::list_x::note_render_targets(this, n, rtvs, single, dsv); let _ = super::capture::op(this, || Some(super::capture::targets_op(this))); diff --git a/crates/xcl/src/hle/d3d12x/sharded.rs b/crates/xcl/src/hle/d3d12x/sharded.rs index 3d2a97e81e..fdbb4453d7 100644 --- a/crates/xcl/src/hle/d3d12x/sharded.rs +++ b/crates/xcl/src/hle/d3d12x/sharded.rs @@ -63,6 +63,12 @@ impl Sharded { self.shard(key).as_mut()?.remove(&key) } + pub fn remove_if(&self, key: usize, pred: impl FnOnce(&V) -> bool) -> Option { + let mut g = self.shard(key); + let m = g.as_mut()?; + m.get(&key).is_some_and(pred).then(|| m.remove(&key)).flatten() + } + pub fn contains(&self, key: usize) -> bool { self.shard(key).as_ref().is_some_and(|m| m.contains_key(&key)) } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d809b1c2a2..970a278e30 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -2842,6 +2842,9 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option device = d.device; bytes += n; let mut unmapped = false; + if super::vram::has_unmapped_lazy_targets() && !super::vram::ensure_target_mapped(d.res.as_raw() as usize) { + unmapped = true; + } if super::vram::level_pages() && super::vram::has_lazy_levels(d.res.as_raw() as usize) { // (the queue waits for these mappings before the copies: `vram::before_execute` // below; what a level's fresh pages held is another texture's, so all of it goes up) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 38c7f70c7a..985b997360 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1054,6 +1054,8 @@ struct Target { console_bytes: Option, total: u32, mapped: bool, + /// waiting for first GPU/upload use to bind tiles (`XCL_LAZY_TARGETS=1`) + lazy_target: bool, used: Vec, used_extra: Vec<(usize, usize)>, /// its levels get their pages one by one (`map_levels`); None: all of it has pages @@ -1139,6 +1141,236 @@ pub(super) fn level_pages() -> bool { #[cfg(test)] pub(super) static LEVEL_PAGES_FOR_TEST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +/// `XCL_LAZY_TARGETS=1` (off by default): a GPU-owned placed target on the shared pages defers +/// binding its 64 KiB video-memory tiles until its first command-list or upload use. Titles often +/// pre-create hundreds of render/depth/UAV targets and views upfront that are unused on the +/// current screen or menu; deferring their tiles avoids allocating gigabytes of idle VRAM. +pub(super) fn lazy_targets() -> bool { + #[cfg(test)] + if LAZY_TARGETS_FOR_TEST.load(std::sync::atomic::Ordering::Relaxed) { + return true; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var("XCL_LAZY_TARGETS").is_ok_and(|v| v.trim() == "1"); + if on { + crate::xlog_info!("D3D12.X: XCL_LAZY_TARGETS=1 - GPU-owned placed targets defer video memory pages until first use"); + } + on + }) +} + +/// `lazy_targets` for a test (under `VRAM_TEST_LOCK`) +#[cfg(test)] +pub(super) static LAZY_TARGETS_FOR_TEST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Unmapped lazy GPU-owned targets awaiting first use (`PAGES -> LAZY_UNMAPPED` lock order; +/// `.contains()` is leaf-only so hot paths avoid `PAGES`). +static LAZY_UNMAPPED: super::sharded::Sharded<()> = super::sharded::Sharded::new(); +static LAZY_UNMAPPED_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +/// [live unmapped targets, live unmapped tiles, targets mapped on use, tiles mapped on use] +static LAZY_TARGET_STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// RTV/DSV CPU descriptor handle -> unmapped lazy target resource (`TARGET_VIEWS` is leaf-only). +static TARGET_VIEWS: super::sharded::Sharded = super::sharded::Sharded::new(); +static TARGET_VIEW_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static RTV_INC: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); +static DSV_INC: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// Fast-path check (one relaxed atomic load): whether any GPU-owned lazy target still lacks tiles. +#[inline] +pub(super) fn has_unmapped_lazy_targets() -> bool { + LAZY_UNMAPPED_COUNT.load(std::sync::atomic::Ordering::Relaxed) != 0 +} + +unsafe fn view_increment(dev: *mut c_void, dsv: bool) -> u64 { + let slot = if dsv { &DSV_INC } else { &RTV_INC }; + let mut inc = slot.load(std::sync::atomic::Ordering::Relaxed); + if inc == 0 { + let Some(d) = ID3D12Device::from_raw_borrowed(&dev) else { return 0 }; + let ty = if dsv { D3D12_DESCRIPTOR_HEAP_TYPE_DSV } else { D3D12_DESCRIPTOR_HEAP_TYPE_RTV }; + inc = d.GetDescriptorHandleIncrementSize(ty); + slot.store(inc, std::sync::atomic::Ordering::Relaxed); + } + inc as u64 +} + +/// Cached RTV descriptor handle increment for `OMSetRenderTargets(..., single != 0, ...)`. +pub(super) unsafe fn rtv_increment_for_list(list: *mut c_void) -> usize { + let inc = RTV_INC.load(std::sync::atomic::Ordering::Relaxed); + if inc != 0 { + return inc as usize; + } + if let Some(l) = ID3D12GraphicsCommandList::from_raw_borrowed(&list) { + let mut dev: Option = None; + if l.GetDevice(&mut dev).is_ok() { + if let Some(d) = dev { + let size = d.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + RTV_INC.store(size, std::sync::atomic::Ordering::Relaxed); + return size as usize; + } + } + } + 0 +} + +fn forget_target_view(handle: usize) { + if TARGET_VIEW_COUNT.load(std::sync::atomic::Ordering::Relaxed) != 0 && TARGET_VIEWS.remove(handle).is_some() { + TARGET_VIEW_COUNT.fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + } +} + +/// Track an RTV or DSV handle when it points to a currently unmapped lazy target, or clear any +/// prior lazy-target entry when the handle is overwritten with another resource. +pub(super) unsafe fn note_target_view(dev: *mut c_void, handle: usize, res: usize, dsv: bool) { + if !has_unmapped_lazy_targets() && TARGET_VIEW_COUNT.load(std::sync::atomic::Ordering::Relaxed) == 0 { + return; + } + if res != 0 && LAZY_UNMAPPED.contains(res) { + if !dsv && RTV_INC.load(std::sync::atomic::Ordering::Relaxed) == 0 { + let _ = view_increment(dev, false); + } + if TARGET_VIEWS.insert(handle, res).is_none() { + TARGET_VIEW_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } else { + forget_target_view(handle); + } +} + +fn view_copy_pieces(dsts: &[(u64, u32)], srcs: &[(u64, u32)], inc: u64) -> Vec<(u64, u64, u32)> { + let (mut out, mut d, mut s, mut dk, mut sk) = (Vec::new(), 0, 0, 0u32, 0u32); + while d < dsts.len() && s < srcs.len() { + let n = (dsts[d].1 - dk).min(srcs[s].1 - sk); + if n > 0 { + out.push((dsts[d].0 + dk as u64 * inc, srcs[s].0 + sk as u64 * inc, n)); + } + dk += n; + sk += n; + if dk == dsts[d].1 { + (d, dk) = (d + 1, 0); + } + if sk == srcs[s].1 { + (s, sk) = (s + 1, 0); + } + } + out +} + +fn copy_target_views_with_inc(n: u32, dst: u64, src: u64, inc: u64) { + if inc == 0 { + return; + } + let span = (n as u64).saturating_mul(inc); + let reverse = dst > src && dst < src.saturating_add(span); + for idx in 0..n as u64 { + let k = if reverse { (n as u64 - 1) - idx } else { idx }; + let (to, from) = (dst.wrapping_add(k.wrapping_mul(inc)) as usize, src.wrapping_add(k.wrapping_mul(inc)) as usize); + match TARGET_VIEWS.get(from) { + Some(res) if LAZY_UNMAPPED.contains(res) => { + if TARGET_VIEWS.insert(to, res).is_none() { + TARGET_VIEW_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } + _ => forget_target_view(to), + } + } +} + +pub(super) unsafe fn copy_target_views_simple(dev: *mut c_void, n: u32, dst: u64, src: u64, dsv: bool) { + if TARGET_VIEW_COUNT.load(std::sync::atomic::Ordering::Relaxed) == 0 || n == 0 { + return; + } + copy_target_views_with_inc(n, dst, src, view_increment(dev, dsv)); +} + +#[allow(clippy::too_many_arguments)] +pub(super) unsafe fn copy_target_views_ranges( + dev: *mut c_void, + nd: u32, + dsts: *const u64, + dsizes: *const u32, + ns: u32, + srcs: *const u64, + ssizes: *const u32, + dsv: bool, +) { + if TARGET_VIEW_COUNT.load(std::sync::atomic::Ordering::Relaxed) == 0 || dsts.is_null() || srcs.is_null() { + return; + } + let ranges = |starts: *const u64, sizes: *const u32, n: u32| -> Vec<(u64, u32)> { + (0..n as usize).map(|r| (*starts.add(r), if sizes.is_null() { 1 } else { *sizes.add(r) })).collect() + }; + let inc = view_increment(dev, dsv); + for (dst, src, n) in view_copy_pieces(&ranges(dsts, dsizes, nd), &ranges(srcs, ssizes, ns), inc) { + copy_target_views_with_inc(n, dst, src, inc); + } +} + +/// Bind tiles for a lazy GPU-owned target on its first command-list or upload use. +/// Returns `true` if `res` is mapped (or not a lazy target), `false` if binding failed (OOM). +#[must_use] +pub(super) unsafe fn ensure_target_mapped(res: usize) -> bool { + if !has_unmapped_lazy_targets() || res == 0 || !LAZY_UNMAPPED.contains(res) { + return true; + } + // Clear any superseded mark in `placements` before taking `PAGES` (preserves `REGISTRY -> PAGES` order). + super::placements::note_use(res); + let mut g = PAGES.lock().unwrap(); + for (&dev_key, slot) in g.iter_mut() { + let Some(pages) = slot.as_mut() else { continue }; + let Some((va, console_bytes, total)) = pages.targets.get(&res).filter(|t| t.lazy_target && !t.mapped).map(|t| (t.va, t.console_bytes, t.total)) else { + if pages.targets.contains_key(&res) { + return true; + } + continue; + }; + let d = dev_key as *mut c_void; + let r = res as *mut c_void; + let (Some(dev), Some(res_ref)) = (ID3D12Device::from_raw_borrowed(&d), ID3D12Resource::from_raw_borrowed(&r)) else { + return false; + }; + let Some((used, used_extra)) = pages.bind(dev, res_ref, va, console_bytes, total) else { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: lazy target {res:#x} ({total} tiles) could not bind pages on first use; leaving unmapped"); + } + return false; + }; + if let Some(t) = pages.targets.get_mut(&res) { + t.used = used; + t.used_extra = used_extra; + t.mapped = true; + t.lazy_target = false; + } + if LAZY_UNMAPPED.remove(res).is_some() { + LAZY_UNMAPPED_COUNT.fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + } + LAZY_TARGET_STATS[0].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + LAZY_TARGET_STATS[1].fetch_sub(total as u64, std::sync::atomic::Ordering::Relaxed); + LAZY_TARGET_STATS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + LAZY_TARGET_STATS[3].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed); + return true; + } + true +} + +/// Bind tiles for any unmapped lazy target named by RTV/DSV CPU descriptor `handle`. +#[must_use] +pub(super) unsafe fn ensure_target_view_mapped(handle: usize) -> bool { + if !has_unmapped_lazy_targets() || handle == 0 { + return true; + } + let Some(res) = TARGET_VIEWS.get(handle) else { return true }; + if !ensure_target_mapped(res) { + return false; + } + if TARGET_VIEWS.remove_if(handle, |&cur| cur == res).is_some() { + TARGET_VIEW_COUNT.fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + } + true +} + /// Of the textures with lazy levels there are now: how many, the tiles they stand for, and the /// tiles of them that have pages; and the level groups given pages so far. static LEVEL_STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; @@ -2367,6 +2599,7 @@ unsafe fn place_on_pages( None }; let texels = (!require_aligned && super::memory_report::enabled()).then(|| TexelMeta::from_desc(desc, levels.is_none())); + let defer_target = require_aligned && lazy_targets() && total > 0 && owned_pages(va, console_bytes, total as usize).is_some(); let bound = { let mut g = PAGES.lock().unwrap(); if let Some(Some(pages)) = g.get_mut(&dev_key) { @@ -2375,11 +2608,20 @@ unsafe fn place_on_pages( LEVEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[1].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed); record_texel_insert(&texels); - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels, texels, recycle: recycle_key }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, lazy_target: false, used: Vec::new(), used_extra: Vec::new(), levels, texels, recycle: recycle_key }); + true + } else if defer_target { + // nothing mapped yet: a GPU-owned lazy target gets its pages on first use (`ensure_target_mapped`) + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: false, lazy_target: true, used: Vec::new(), used_extra: Vec::new(), levels: None, texels, recycle: recycle_key }); + if LAZY_UNMAPPED.insert(raw as usize, ()).is_none() { + LAZY_UNMAPPED_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + LAZY_TARGET_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + LAZY_TARGET_STATS[1].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed); true } else if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) { record_texel_insert(&texels); - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None, texels, recycle: recycle_key }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, lazy_target: false, used, used_extra, levels: None, texels, recycle: recycle_key }); true } else { false @@ -2504,6 +2746,10 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { t.mapped = true; return true; } + // (lazy GPU-owned targets: wait for first GPU/upload use rather than binding on placement release) + if pages.targets.get(&key).is_some_and(|t| t.lazy_target) { + return true; + } let Some((used, used_extra)) = pages.bind(&dev, res, va, console_bytes, total) else { return false; }; @@ -2546,6 +2792,13 @@ fn forget_pages(resource: usize, held: bool) -> Option { TEXEL_STATS[3].fetch_sub(tm.resident_texels, std::sync::atomic::Ordering::Relaxed); } } + if t.lazy_target { + if LAZY_UNMAPPED.remove(resource).is_some() { + LAZY_UNMAPPED_COUNT.fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + } + LAZY_TARGET_STATS[0].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + LAZY_TARGET_STATS[1].fetch_sub(t.total as u64, std::sync::atomic::Ordering::Relaxed); + } if t.mapped { pages.release_tiles(t.used, t.used_extra, now, false); for (used, used_extra) in take_level_tiles(t.levels.as_mut()) { @@ -2930,16 +3183,27 @@ pub fn page_owners() -> String { pages += p.pages.len() + p.extra_pages.len(); idle += p.idle.len(); for t in p.targets.values() { + if t.lazy_target { + continue; + } let k = if t.levels.is_none() { 0 } else { 1 }; kinds[k].0 += 1; kinds[k].1 += t.used.len() + t.used_extra.len(); } } let mb = |n: usize| n * PAGE >> 20; - format!( + let mut s = format!( "target pages by owner: {} textures with all their pages hold {} MB, {} sampled textures with pages by level hold {} MB (a shared page counts for each); {} MB of pages in all, {} MB of them idle", kinds[0].0, mb(kinds[0].1), kinds[1].0, mb(kinds[1].1), mb(pages), mb(idle) - ) + ); + let lazy_unmapped = LAZY_TARGET_STATS[0].load(std::sync::atomic::Ordering::Relaxed); + let lazy_mapped = LAZY_TARGET_STATS[2].load(std::sync::atomic::Ordering::Relaxed); + if lazy_targets() || lazy_unmapped != 0 || lazy_mapped != 0 { + let unmapped_mb = (LAZY_TARGET_STATS[1].load(std::sync::atomic::Ordering::Relaxed) * PAGE as u64) >> 20; + let mapped_mb = (LAZY_TARGET_STATS[3].load(std::sync::atomic::Ordering::Relaxed) * PAGE as u64) >> 20; + s.push_str(&format!("; lazy targets: {lazy_unmapped} unmapped ({unmapped_mb} MB deferred), {lazy_mapped} mapped on use ({mapped_mb} MB)")); + } + s } pub fn page_bytes() -> (usize, usize) { @@ -4125,6 +4389,7 @@ mod tests { console_bytes: None, total: 2, mapped: true, + lazy_target: false, used: Vec::new(), used_extra: Vec::new(), levels: Some(levels), @@ -5616,4 +5881,234 @@ mod tests { late_release::drain_known(true); } } + + #[test] + fn target_view_copy_pieces_and_table_follow_handles() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let pieces = view_copy_pieces(&[(0x1000, 2), (0x2000, 3)], &[(0x3000, 1), (0x4000, 4)], 32); + assert_eq!(pieces, vec![(0x1000, 0x3000, 1), (0x1020, 0x4000, 1), (0x2000, 0x4020, 3)]); + + let (lazy_res, other_res) = (0x7fff_a000usize, 0x7fff_b000usize); + let (h0, h1, h2) = (0x7fff_1000usize, 0x7fff_1020usize, 0x7fff_1040usize); + if LAZY_UNMAPPED.insert(lazy_res, ()).is_none() { + LAZY_UNMAPPED_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + unsafe { + note_target_view(std::ptr::null_mut(), h0, lazy_res, true); + note_target_view(std::ptr::null_mut(), h1, other_res, true); + } + assert_eq!(TARGET_VIEWS.get(h0), Some(lazy_res)); + assert_eq!(TARGET_VIEWS.get(h1), None); + + copy_target_views_with_inc(2, h1 as u64, h0 as u64, 32); + assert_eq!(TARGET_VIEWS.get(h1), Some(lazy_res)); + assert_eq!(TARGET_VIEWS.get(h2), None); + + // Copying from an untracked handle clears the destination entry. + copy_target_views_with_inc(1, h1 as u64, h2 as u64, 32); + assert_eq!(TARGET_VIEWS.get(h1), None); + + // Overwriting a tracked handle with a non-lazy resource clears it. + unsafe { note_target_view(std::ptr::null_mut(), h0, other_res, true); } + assert_eq!(TARGET_VIEWS.get(h0), None); + + if LAZY_UNMAPPED.remove(lazy_res).is_some() { + LAZY_UNMAPPED_COUNT.fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + } + } + + #[test] + fn gpu_lazy_target_defers_vram_until_first_use_and_renders_correctly() { + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + struct LazyGuard; + impl Drop for LazyGuard { + fn drop(&mut self) { + LAZY_TARGETS_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); + } + } + LAZY_TARGETS_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + let _lazy = LazyGuard; + + use windows::core::Interface; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + if !tier2(&dev) { + return crate::gpu::recomp::runner::skip_test("device lacks tiled resource tier 2"); + } + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let bytes_before = page_bytes_for(dev_key).0; + let unmapped_before = LAZY_TARGET_STATS[0].load(std::sync::atomic::Ordering::Relaxed); + let mapped_on_use_before = LAZY_TARGET_STATS[2].load(std::sync::atomic::Ordering::Relaxed); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 512, + Height: 512, + 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 riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let mut raw = std::ptr::null_mut(); + let hr = place( + dev.as_raw(), + 0x7_5000_0000, + &desc, + D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32, + std::ptr::null(), + Some(512 * 512 * 4), + riid, + &mut raw, + ); + if hr.is_none_or(|hr| hr < 0) || raw.is_null() { + return crate::gpu::recomp::runner::skip_test("reserved render target unavailable"); + } + let rt = ID3D12Resource::from_raw(raw); + let rt_key = rt.as_raw() as usize; + assert!( + page_bytes_for(dev_key).0 <= bytes_before, + "lazy target must not allocate VRAM at creation" + ); + assert!(mapped_tiles_for(dev_key, rt_key).is_none()); + assert!(LAZY_UNMAPPED.contains(rt_key)); + assert_eq!(LAZY_TARGET_STATS[0].load(std::sync::atomic::Ordering::Relaxed), unmapped_before + 1); + + // Creating and copying an RTV must not allocate VRAM either. + let rtv_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: 2, + ..Default::default() + }) + .unwrap(); + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize; + let h0 = rtv_heap.GetCPUDescriptorHandleForHeapStart(); + let h1 = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: h0.ptr + inc }; + dev.CreateRenderTargetView(&rt, None, h0); + note_target_view(dev.as_raw(), h0.ptr, rt_key, false); + dev.CopyDescriptorsSimple(1, h1, h0, D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + copy_target_views_simple(dev.as_raw(), 1, h1.ptr as u64, h0.ptr as u64, false); + assert!(mapped_tiles_for(dev_key, rt_key).is_none(), "creating and copying RTVs must not bind lazy tiles"); + assert!(remap_if_unmapped(&rt), "remap_if_unmapped should leave unused lazy target deferred"); + assert!(mapped_tiles_for(dev_key, rt_key).is_none(), "remap_if_unmapped must not prematurely bind lazy tiles"); + assert!(page_bytes_for(dev_key).0 <= bytes_before); + + // First command-list use via copied RTV binds the tiles and allows real rendering. + assert!(ensure_target_view_mapped(h1.ptr)); + let (own_tiles, extra_tiles) = mapped_tiles_for(dev_key, rt_key).expect("first use must bind target pages"); + assert!(own_tiles.len() + extra_tiles.len() >= 16, "expected >=16 mapped tiles for 512x512 RGBA8"); + assert!(!LAZY_UNMAPPED.contains(rt_key)); + assert_eq!(LAZY_TARGET_STATS[2].load(std::sync::atomic::Ordering::Relaxed), mapped_on_use_before + 1); + let mapped_bytes = page_bytes_for(dev_key).0; + + // A second unused lazy target allocates 0 extra bytes and cleans up on release. + let mut raw2 = std::ptr::null_mut(); + let hr2 = place( + dev.as_raw(), + 0x7_6000_0000, + &desc, + D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32, + std::ptr::null(), + Some(512 * 512 * 4), + riid, + &mut raw2, + ); + assert!(hr2.is_some_and(|hr| hr >= 0) && !raw2.is_null()); + let rt2 = ID3D12Resource::from_raw(raw2); + let rt2_key = rt2.as_raw() as usize; + assert!(page_bytes_for(dev_key).0 <= mapped_bytes, "unused second lazy target must allocate 0 VRAM"); + assert!(mapped_tiles_for(dev_key, rt2_key).is_none()); + assert!(LAZY_UNMAPPED.contains(rt2_key)); + forget(rt2_key); + drop(rt2); + assert!(!LAZY_UNMAPPED.contains(rt2_key)); + + // Clear via the copied RTV and read back pixel (0, 0) to verify GPU tile mapping & sync. + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let rb_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let rb_heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let mut readback: Option = None; + dev.CreateCommittedResource(&rb_heap, D3D12_HEAP_FLAG_NONE, &rb_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback).unwrap(); + let readback = readback.unwrap(); + + list.ClearRenderTargetView(h1, &[0.25, 0.5, 0.75, 1.0], None); + let barrier = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::ManuallyDrop::new(Some(rt.clone())), + Subresource: 0, + StateBefore: D3D12_RESOURCE_STATE_RENDER_TARGET, + StateAfter: D3D12_RESOURCE_STATE_COPY_SOURCE, + }), + }, + }; + list.ResourceBarrier(&[barrier]); + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::ManuallyDrop::new(Some(readback.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + Width: 1, + Height: 1, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::ManuallyDrop::new(Some(rt.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + let bx = D3D12_BOX { left: 0, top: 0, front: 0, right: 1, bottom: 1, back: 1 }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, Some(&bx)); + let _ = std::mem::ManuallyDrop::into_inner(dst.pResource); + let _ = std::mem::ManuallyDrop::into_inner(src.pResource); + list.Close().unwrap(); + + before_execute(&queue); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + fence.SetEventOnCompletion(1, windows::Win32::Foundation::HANDLE::default()).unwrap(); + + let mut mapped_ptr = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut mapped_ptr)).unwrap(); + let px = *(mapped_ptr as *const [u8; 4]); + readback.Unmap(0, None); + assert!( + (px[0] as i16 - 64).abs() <= 1 + && (px[1] as i16 - 128).abs() <= 1 + && (px[2] as i16 - 191).abs() <= 1 + && px[3] == 255, + "lazy render target pixel mismatch after first-use bind: {px:?}" + ); + + forget(rt_key); + drop((list, alloc, readback, rtv_heap, rt, fence, queue)); + } + } }