From 3bc7143a8dbc5a2326345d6e734604c56a9e3266 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:51:54 +0100 Subject: [PATCH] D3D12.X: keep vram::Pages tile mappings contiguous per heap --- crates/xcl/src/hle/d3d12x/vram.rs | 540 +++++++++++++++++++++++++----- 1 file changed, 464 insertions(+), 76 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 040d78a0c..740b69ef9 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -220,6 +220,165 @@ struct Target { used_extra: Vec<(usize, usize)>, } +/// Per-heap free-tile allocator for `Pages`. +/// +/// Keeping free tiles partitioned by pool heap (sorted descending so `.pop()` yields ascending +/// contiguous tile indices) prevents streaming churn across 100+ 64 MiB pools from scattering a +/// single texture across dozens of heaps — which otherwise explodes `Pages::map` into dozens of +/// `UpdateTileMappings` calls per texture. +struct TilePool { + /// Free tile indices for each pool heap (descending when `!dirty_sort[h]`). + free_by_heap: Vec>, + /// Whether `free_by_heap[h]` must be sorted descending before popping. + dirty_sort: Vec, + /// Total free tiles currently available across all heaps. + free_total: usize, + /// Tiles given back, reusable after `COOL`. + cooling: std::collections::VecDeque<(Tile, std::time::Instant)>, +} + +impl TilePool { + fn new() -> Self { + TilePool { + free_by_heap: Vec::new(), + dirty_sort: Vec::new(), + free_total: 0, + cooling: std::collections::VecDeque::new(), + } + } + + fn add_heap(&mut self, pool_pages: u32) -> u32 { + let h = self.free_by_heap.len() as u32; + self.free_by_heap.push((0..pool_pages).rev().collect()); + self.dirty_sort.push(false); + self.free_total += pool_pages as usize; + h + } + + fn push_cooling(&mut self, tile: Tile, now: std::time::Instant) { + self.cooling.push_back((tile, now)); + } + + /// Move every cooled tile (`>= COOL`) into its pool heap's free list so best-fit allocation + /// sees all ready tiles at once. + fn drain_cooling(&mut self, now: std::time::Instant) { + while self.cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL) { + let Some(((h, t), _)) = self.cooling.pop_front() else { break }; + let idx = h as usize; + if idx < self.free_by_heap.len() { + self.free_by_heap[idx].push(t); + self.dirty_sort[idx] = true; + self.free_total += 1; + } + } + } + + fn return_tiles(&mut self, tiles: &[Tile]) { + for &(h, t) in tiles { + let idx = h as usize; + if idx < self.free_by_heap.len() { + self.free_by_heap[idx].push(t); + self.dirty_sort[idx] = true; + self.free_total += 1; + } + } + } + + /// Pick the pool heap to take up to `rem` tiles from: + /// 1. `preferred` if it fits all `rem` tiles (keeps partial-overlap placements on 1 heap), + /// 2. otherwise best-fit heap with `len >= rem` (fits the whole texture in 1 heap without + /// splitting fuller pools), + /// 3. otherwise the heap with the most free tiles (minimizing distinct heaps touched). + fn pick_heap(&self, rem: usize, preferred: Option) -> Option { + if self.free_total == 0 { + return None; + } + if let Some(p) = preferred.map(|h| h as usize).filter(|&h| h < self.free_by_heap.len()) { + if self.free_by_heap[p].len() >= rem { + return Some(p); + } + } + let mut best_fit: Option<(usize, usize)> = None; + let mut largest: Option<(usize, usize)> = None; + for (h, tiles) in self.free_by_heap.iter().enumerate() { + let len = tiles.len(); + if len == 0 { + continue; + } + if len >= rem { + if best_fit.is_none_or(|(_, blen)| len < blen) { + best_fit = Some((h, len)); + } + } else if largest.is_none_or(|(lh, llen)| len > llen || (len == llen && preferred == Some(h as u32) && preferred != Some(lh as u32))) { + largest = Some((h, len)); + } + } + best_fit.or(largest).map(|(h, _)| h) + } + + /// Allocate `count` tiles, preferring a single heap and ascending contiguous offsets. + /// `make_heap` allocates a new backing pool heap of `pool_pages` tiles when `free_total == 0`. + /// On failure, any tiles already taken are returned untouched. + fn take_batch( + &mut self, + count: usize, + preferred: Option, + now: std::time::Instant, + pool_pages: u32, + mut make_heap: impl FnMut() -> Option, + ) -> Option> { + if count == 0 { + return Some(Vec::new()); + } + self.drain_cooling(now); + let mut out = Vec::with_capacity(count); + while out.len() < count { + let rem = count - out.len(); + let h = match self.pick_heap(rem, preferred) { + Some(h) => h, + None => { + let Some(new_h) = make_heap() else { + self.return_tiles(&out); + return None; + }; + let added = self.add_heap(pool_pages); + debug_assert_eq!(added, new_h); + added as usize + } + }; + if self.dirty_sort[h] { + self.free_by_heap[h].sort_unstable_by(|a, b| b.cmp(a)); + self.dirty_sort[h] = false; + } + let free = &mut self.free_by_heap[h]; + let take = rem.min(free.len()); + for _ in 0..take { + let t = free.pop().unwrap(); + out.push((h as u32, t)); + } + self.free_total -= take; + } + Some(out) + } +} + +/// Allocate one 64 MiB default heap for `Pages`. +unsafe fn alloc_pool_heap(dev: &ID3D12Device) -> Option { + let desc = D3D12_HEAP_DESC { + SizeInBytes: POOL_PAGES as u64 * PAGE as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + // every kind of texture (resource heap tier 2: the only flags for both) + Flags: D3D12_HEAP_FLAG_NONE, + }; + let mut heap: Option = None; + if let Err(e) = super::title_textures::own_work(|| dev.CreateHeap(&desc, &mut heap)) { + crate::xlog_warn!("D3D12.X: no video memory for more pages of title textures ({e})"); + return None; + } + heap +} + /// The title's pages of video memory for tiled textures (see the module's comment). struct Pages { queue: ID3D12CommandQueue, @@ -227,9 +386,7 @@ struct Pages { fence: ID3D12Fence, value: u64, pools: Vec, - free: Vec, - /// tiles given back, reusable after `COOL` - cooling: std::collections::VecDeque<(Tile, std::time::Instant)>, + pool: TilePool, /// title page address → its video memory pages: std::collections::HashMap, /// extra / sub-64 KiB tiles keyed by `(va, tile_index)` so repeated placements at the same @@ -241,6 +398,13 @@ struct Pages { targets: std::collections::HashMap, /// queue → the fence value it last waited for waited: std::collections::HashMap, + /// cached `reservable()` answers for `(DXGI_FORMAT, SampleCount)` on this device + reservable_cache: std::collections::HashMap<(i32, u32), bool>, + /// reusable scratch buffers for `map()` + scratch_heaps: Vec, + scratch_flags: Vec, + scratch_offsets: Vec, + scratch_counts: Vec, } // D3D12 objects are free-threaded @@ -259,6 +423,7 @@ impl Pages { return None; } let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).ok()?; + let _ = queue.SetName(windows::core::w!("xcl vram tile-mapping queue")); let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; crate::xlog_info!("D3D12.X: textures in title memory: tiled resources on 64 KiB pages of video memory, one per page of the title's"); Some(Pages { @@ -266,58 +431,52 @@ impl Pages { fence, value: 0, pools: Vec::new(), - free: Vec::new(), - cooling: std::collections::VecDeque::new(), + pool: TilePool::new(), pages: std::collections::HashMap::new(), extra_pages: std::collections::HashMap::new(), idle: std::collections::VecDeque::new(), targets: std::collections::HashMap::new(), waited: std::collections::HashMap::new(), + reservable_cache: std::collections::HashMap::new(), + scratch_heaps: Vec::new(), + scratch_flags: Vec::new(), + scratch_offsets: Vec::new(), + scratch_counts: Vec::new(), }) } /// Pages no resource used for `IDLE` go back to the pools. fn sweep(&mut self, now: std::time::Instant) { - sweep_idle(&mut self.idle, &mut self.pages, &mut self.extra_pages, &mut self.cooling, now); - } - - unsafe fn take_tile(&mut self, dev: &ID3D12Device) -> Option { - if let Some(t) = self.free.pop() { - return Some(t); - } - if self.cooling.front().is_some_and(|(_, at)| at.elapsed() >= COOL) { - return self.cooling.pop_front().map(|(t, _)| t); - } - let desc = D3D12_HEAP_DESC { - SizeInBytes: POOL_PAGES as u64 * PAGE as u64, - Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, - Alignment: 0, - // every kind of texture (resource heap tier 2: the only flags for both) - Flags: D3D12_HEAP_FLAG_NONE, - }; - let mut heap: Option = None; - if let Err(e) = super::title_textures::own_work(|| dev.CreateHeap(&desc, &mut heap)) { - crate::xlog_warn!("D3D12.X: no video memory for more pages of title textures ({e})"); - return None; - } - self.pools.push(heap?); - let h = self.pools.len() as u32 - 1; - self.free.extend((1..POOL_PAGES).rev().map(|t| (h, t))); - Some((h, 0)) + sweep_idle(&mut self.idle, &mut self.pages, &mut self.extra_pages, &mut self.pool.cooling, now); } /// Map every tile of `res` (`tiles[i]`: overall tile i) – one call per pool heap. unsafe fn map(&mut self, res: &ID3D12Resource, tiles: &[Tile]) { - let mut heaps: Vec = tiles.iter().map(|t| t.0).collect(); - heaps.sort_unstable(); - heaps.dedup(); - for h in heaps { - let ranges = heap_ranges(h, tiles); - let flags: Vec = ranges.iter().map(|r| if r.0 { D3D12_TILE_RANGE_FLAG_NONE } else { D3D12_TILE_RANGE_FLAG_SKIP }).collect(); - let offsets: Vec = ranges.iter().map(|r| r.1).collect(); - let counts: Vec = ranges.iter().map(|r| r.2).collect(); + if tiles.is_empty() { + return; + } + self.scratch_heaps.clear(); + self.scratch_heaps.extend(tiles.iter().map(|t| t.0)); + self.scratch_heaps.sort_unstable(); + self.scratch_heaps.dedup(); + for i in 0..self.scratch_heaps.len() { + let h = self.scratch_heaps[i]; + let ranges = heap_ranges_trimmed(h, tiles); + if ranges.is_empty() { + continue; + } + self.scratch_flags.clear(); + self.scratch_offsets.clear(); + self.scratch_counts.clear(); + let mut num_tiles = 0u32; + for &(mapped, off, count) in &ranges { + self.scratch_flags.push(if mapped { D3D12_TILE_RANGE_FLAG_NONE } else { D3D12_TILE_RANGE_FLAG_SKIP }); + self.scratch_offsets.push(off); + self.scratch_counts.push(count); + num_tiles += count; + } let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); - let region = D3D12_TILE_REGION_SIZE { NumTiles: tiles.len() as u32, UseBox: false.into(), ..Default::default() }; + let region = D3D12_TILE_REGION_SIZE { NumTiles: num_tiles, UseBox: false.into(), ..Default::default() }; self.queue.UpdateTileMappings( res, 1, @@ -325,9 +484,9 @@ impl Pages { Some(®ion), &self.pools[h as usize], ranges.len() as u32, - Some(flags.as_ptr()), - Some(offsets.as_ptr()), - Some(counts.as_ptr()), + Some(self.scratch_flags.as_ptr()), + Some(self.scratch_offsets.as_ptr()), + Some(self.scratch_counts.as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE, ); } @@ -338,6 +497,9 @@ impl Pages { /// Unmap every tile of `res` (`D3D12_TILE_RANGE_FLAG_NULL`) so its unshared tiles can return /// to the pool even while the title keeps the COM object alive. unsafe fn unmap(&mut self, res: &ID3D12Resource, total: u32) { + if total == 0 { + return; + } let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); let region = D3D12_TILE_REGION_SIZE { NumTiles: total, UseBox: false.into(), ..Default::default() }; let flag = D3D12_TILE_RANGE_FLAG_NULL; @@ -364,7 +526,7 @@ impl Pages { if p.users == 0 { if immediate_cool { if let Some(p) = self.pages.remove(&a) { - self.cooling.push_back((p.tile, now)); + self.pool.push_cooling(p.tile, now); } } else { p.idle_since = Some(now); @@ -379,7 +541,7 @@ impl Pages { if p.users == 0 { if immediate_cool { if let Some(p) = self.extra_pages.remove(&k) { - self.cooling.push_back((p.tile, now)); + self.pool.push_cooling(p.tile, now); } } else { p.idle_since = Some(now); @@ -395,49 +557,69 @@ impl Pages { let (first, own) = (total > 0).then(|| owned_pages(va, console_bytes, total as usize)).flatten()?; let now = std::time::Instant::now(); self.sweep(now); + + let mut missing = 0usize; + let mut preferred: Option = None; + for i in 0..total as usize { + let existing = if i < own { + self.pages.get(&(first + i * PAGE)).map(|p| p.tile.0) + } else { + self.extra_pages.get(&(va, i)).map(|p| p.tile.0) + }; + match existing { + Some(h) if preferred.is_none() => preferred = Some(h), + Some(_) => {} + None => missing += 1, + } + } + + let pools = &mut self.pools; + let pool = &mut self.pool; + let fresh = pool.take_batch(missing, preferred, now, POOL_PAGES, || { + let heap = alloc_pool_heap(dev)?; + pools.push(heap); + Some(pools.len() as u32 - 1) + })?; + let mut fresh_iter = fresh.into_iter(); + let mut tiles = Vec::with_capacity(total as usize); let mut used = Vec::with_capacity(own); let mut used_extra = Vec::new(); for i in 0..total as usize { let tile = if i < own { let a = first + i * PAGE; - let tile = match self.pages.get_mut(&a) { + let t = match self.pages.get_mut(&a) { Some(p) => { p.users += 1; p.idle_since = None; - Some(p.tile) + p.tile } - None => self.take_tile(dev).inspect(|&t| { + None => { + let t = fresh_iter.next().unwrap(); self.pages.insert(a, Page { tile: t, users: 1, idle_since: None }); - }), + t + } }; - if tile.is_some() { - used.push(a); - } - tile + used.push(a); + t } else { let k = (va, i); - let tile = match self.extra_pages.get_mut(&k) { + let t = match self.extra_pages.get_mut(&k) { Some(p) => { p.users += 1; p.idle_since = None; - Some(p.tile) + p.tile } - None => self.take_tile(dev).inspect(|&t| { + None => { + let t = fresh_iter.next().unwrap(); self.extra_pages.insert(k, Page { tile: t, users: 1, idle_since: None }); - }), + t + } }; - if tile.is_some() { - used_extra.push(k); - } - tile + used_extra.push(k); + t }; - let Some(t) = tile else { break }; - tiles.push(t); - } - if tiles.len() < total as usize { - self.release_tiles(used, used_extra, now, true); - return None; + tiles.push(tile); } self.map(res, &tiles); Some((used, used_extra)) @@ -460,6 +642,16 @@ fn heap_ranges(heap: u32, tiles: &[Tile]) -> Vec<(bool, u32, u32)> { out } +/// Like `heap_ranges`, with any trailing `SKIP` range trimmed so `UpdateTileMappings` only walks +/// up to the last tile belonging to `heap`. +fn heap_ranges_trimmed(heap: u32, tiles: &[Tile]) -> Vec<(bool, u32, u32)> { + let mut out = heap_ranges(heap, tiles); + while out.last().is_some_and(|r| !r.0) { + out.pop(); + } + out +} + /// 64 KiB page boundaries `P` with `va <= P < va + bytes`, capped at `total` tiles: /// `(first_page, count)`. Because every `P` lies strictly inside `[va, va + bytes)`, two /// non-overlapping ranges never share a page here even when `va` is only 4 KiB aligned. @@ -532,12 +724,18 @@ unsafe fn place_on_pages( crate::xlog_info!("D3D12.X: GPU-owned texture at {va:#x} ({}x{}, format {}, {} samples) not reserved ({why}): in an arena", desc.Width, desc.Height, desc.Format.0, desc.SampleDesc.Count); } }; - if !reservable(dev, &tiled) { + let dev_key = dev.as_raw() as usize; + let is_reservable = { + let mut g = PAGES.lock().unwrap(); + let pages = g.entry(dev_key).or_insert_with(|| Pages::new(dev)).as_mut()?; + *pages.reservable_cache.entry((tiled.Format.0, tiled.SampleDesc.Count)).or_insert_with(|| reservable(dev, &tiled)) + }; + if !is_reservable { log("no tiled support for its format or sample count"); return None; } - let mut g = PAGES.lock().unwrap(); - let pages = g.entry(dev.as_raw() as usize).or_insert_with(|| Pages::new(dev)).as_mut()?; + // CreateReservedResource and GetResourceTiling do not touch `PAGES`; keep them outside the + // lock so concurrent streaming threads, `before_execute`, and `page_bytes` do not serialize. let hr = super::real::dev_create_reserved_resource(this, &tiled as *const _ as usize, state as usize, clear as usize, riid, ppv); if hr < 0 || (*ppv).is_null() { log(&format!("{hr:#x}")); @@ -547,14 +745,24 @@ unsafe fn place_on_pages( let res = ID3D12Resource::from_raw_borrowed(&raw)?; let mut total = 0u32; dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); - let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) else { - drop(g); + let bound = { + let mut g = PAGES.lock().unwrap(); + if let Some(Some(pages)) = g.get_mut(&dev_key) { + if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) { + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra }); + true + } else { + false + } + } else { + false + } + }; + if !bound { drop(windows::core::IUnknown::from_raw(raw)); *ppv = std::ptr::null_mut(); return None; - }; - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra }); - drop(g); + } PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize); Some(hr) } @@ -620,7 +828,7 @@ fn forget_pages(resource: usize) { } } -/// Before GPU work on `queue`: it waits for the pages mapped since its last work on that device. +/// Before GPU work on `queue`: have it wait for every tile mapping made so far on its device. pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { let mut dev: Option = None; if queue.GetDevice(&mut dev).is_err() { @@ -725,10 +933,78 @@ mod tests { let tiles = [(0, 5), (0, 6), (1, 0), (1, 1), (0, 9), (0, 10), (0, 11)]; assert_eq!(heap_ranges(0, &tiles), [(true, 5, 2), (false, 0, 2), (true, 9, 3)]); assert_eq!(heap_ranges(1, &tiles), [(false, 0, 2), (true, 0, 2), (false, 0, 3)]); + assert_eq!(heap_ranges_trimmed(1, &tiles), [(false, 0, 2), (true, 0, 2)]); // shared pages out of order: runs break where the tiles do assert_eq!(heap_ranges(0, &[(0, 3), (0, 1), (0, 2)]), [(true, 3, 1), (true, 1, 2)]); } + /// Streaming churn across 100+ 64 MiB pool heaps: cooling tiles returned in interleaved + /// cross-heap order are regrouped per heap and sorted into contiguous ascending runs, so new + /// textures stay inside 1 pool heap (1 UpdateTileMappings call, 1 contiguous range) instead of + /// scattering across dozens of heaps. + #[test] + fn tile_pool_keeps_churned_allocations_in_single_heap_and_contiguous() { + let t0 = Instant::now(); + let mut pool = TilePool::new(); + let heaps_made = std::cell::Cell::new(0u32); + let mut make = || { + let h = heaps_made.get(); + heaps_made.set(h + 1); + Some(h) + }; + + // Fill 100 pools (64 tiles each for a fast unit test, same multi-heap topology as 1024). + const P: u32 = 64; + let mut live: Vec> = Vec::new(); + for _ in 0..100 { + live.push(pool.take_batch(P as usize, None, t0, P, &mut make).unwrap()); + } + assert_eq!(heaps_made.get(), 100); + assert_eq!(pool.free_total, 0); + + // Free 32 tiles from every pool in interleaved round-robin order (worst-case churn across + // all 100 pools in `cooling`). + for tile_idx in 0..32usize { + for h in 0..100usize { + pool.push_cooling(live[h][tile_idx], t0); + } + } + assert_eq!(pool.cooling.len(), 3200); + + // After COOL, allocating 100 textures of 32 tiles each must: + // - allocate ZERO new heaps, + // - place EVERY texture into exactly 1 single pool heap (1 UpdateTileMappings call), + // - yield 1 single contiguous tile range (0..32) per texture! + let t1 = t0 + COOL + Duration::from_millis(1); + for _ in 0..100 { + let alloc = pool.take_batch(32, None, t1, P, &mut make).unwrap(); + assert_eq!(alloc.len(), 32); + let h0 = alloc[0].0; + assert!(alloc.iter().all(|&(h, _)| h == h0), "texture scattered across multiple heaps"); + let ranges = heap_ranges_trimmed(h0, &alloc); + assert_eq!(ranges, [(true, 0, 32)], "expected 1 contiguous ascending range"); + } + assert_eq!(heaps_made.get(), 100, "must reuse cooled tiles without making new heaps"); + assert_eq!(pool.free_total, 0); + + // Partial overlap preference: if heap 7 has free tiles and preferred=Some(7), use heap 7. + for t in 10..18u32 { + pool.push_cooling((7, t), t1); + pool.push_cooling((3, t), t1); + } + let t2 = t1 + COOL + Duration::from_millis(1); + let pref = pool.take_batch(8, Some(7), t2, P, &mut make).unwrap(); + assert!(pref.iter().all(|&(h, _)| h == 7), "preferred heap should be chosen"); + assert_eq!(heap_ranges_trimmed(7, &pref), [(true, 10, 8)]); + + // Rollback on OOM: requesting more tiles than available when make_heap fails returns every + // popped tile cleanly so free_total is preserved. + assert_eq!(pool.free_total, 8); + let fail = pool.take_batch(16, None, t2, P, || None); + assert!(fail.is_none()); + assert_eq!(pool.free_total, 8, "OOM rollback must return all popped tiles"); + } + /// Idle pages go back after `IDLE`, and a sweep looks at the queue of idle pages alone: one /// used again stays, one idle again later goes when that is `IDLE` ago, and the sweeps of /// 20 000 placements beside 200 000 pages in use take no time to speak of (a look at every @@ -1032,4 +1308,116 @@ mod tests { drop(last); } } + + /// Reproduces the multi-pool streaming churn pattern on the active D3D12 driver (comparing + /// scattered cross-heap `UpdateTileMappings` against single-heap contiguous + /// `UpdateTileMappings`, both with `FLAG_NONE` and per-texture `Signal`): + /// `cargo test -p xcl --lib -- --ignored --exact hle::d3d12x::vram::tests::churn_update_tile_mappings_timing --nocapture` + #[test] + #[ignore] + fn churn_update_tile_mappings_timing() { + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::*; + unsafe { + let mut dev: Option = None; + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("D3D12 device"); + let dev = dev.unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + const HEAPS: usize = 64; + const TILES_PER_TEX: usize = 32; // 2 MiB tiled texture + const TEX_COUNT: usize = 256; + let heap_desc = D3D12_HEAP_DESC { + SizeInBytes: 64 * PAGE as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_NONE, + }; + let mut heaps = Vec::with_capacity(HEAPS); + for _ in 0..HEAPS { + let mut h: Option = None; + dev.CreateHeap(&heap_desc, &mut h).unwrap(); + heaps.push(h.unwrap()); + } + let tex_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 1024, + Height: 512, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + let make_textures = || -> Vec { + (0..TEX_COUNT) + .map(|_| { + let mut r: Option = None; + dev.CreateReservedResource(&tex_desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + r.unwrap() + }) + .collect() + }; + + // BEFORE pattern: flat-FIFO cooling scatters each 32-tile texture across 32 heaps, + // calling UpdateTileMappings(FLAG_NONE) per heap + Signal per texture. + let old_res = make_textures(); + let mut fval = 0u64; + let t0 = Instant::now(); + let mut old_calls = 0usize; + for (k, r) in old_res.iter().enumerate() { + let tiles: Vec = (0..TILES_PER_TEX).map(|i| (((k + i) % HEAPS) as u32, (i % 64) as u32)).collect(); + let mut hs: Vec = tiles.iter().map(|t| t.0).collect(); + hs.sort_unstable(); + hs.dedup(); + for h in hs { + let ranges = heap_ranges(h, &tiles); + let flags: Vec = ranges.iter().map(|x| if x.0 { D3D12_TILE_RANGE_FLAG_NONE } else { D3D12_TILE_RANGE_FLAG_SKIP }).collect(); + let offsets: Vec = ranges.iter().map(|x| x.1).collect(); + let counts: Vec = ranges.iter().map(|x| x.2).collect(); + let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); + let region = D3D12_TILE_REGION_SIZE { NumTiles: tiles.len() as u32, UseBox: false.into(), ..Default::default() }; + queue.UpdateTileMappings(r, 1, Some(&coord), Some(®ion), &heaps[h as usize], ranges.len() as u32, Some(flags.as_ptr()), Some(offsets.as_ptr()), Some(counts.as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE); + old_calls += 1; + } + fval += 1; + queue.Signal(&fence, fval).unwrap(); + } + let old_submit = t0.elapsed(); + fence.SetEventOnCompletion(fval, windows::Win32::Foundation::HANDLE::default()).unwrap(); + let old_total = t0.elapsed(); + + // AFTER pattern: per-heap contiguous TilePool -> 1 heap, 1 contiguous range, + // D3D12_TILE_MAPPING_FLAG_NONE, per-texture Signal. + let new_res = make_textures(); + let t1 = Instant::now(); + let mut new_calls = 0usize; + for (k, r) in new_res.iter().enumerate() { + let h = k % HEAPS; + let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); + let region = D3D12_TILE_REGION_SIZE { NumTiles: TILES_PER_TEX as u32, UseBox: false.into(), ..Default::default() }; + let flag = D3D12_TILE_RANGE_FLAG_NONE; + let off = 0u32; + let cnt = TILES_PER_TEX as u32; + queue.UpdateTileMappings(r, 1, Some(&coord), Some(®ion), &heaps[h], 1, Some(&flag), Some(&off), Some(&cnt), D3D12_TILE_MAPPING_FLAG_NONE); + new_calls += 1; + fval += 1; + queue.Signal(&fence, fval).unwrap(); + } + let new_submit = t1.elapsed(); + fence.SetEventOnCompletion(fval, windows::Win32::Foundation::HANDLE::default()).unwrap(); + let new_total = t1.elapsed(); + + println!( + "BEFORE ({TEX_COUNT} x 2MiB textures, {old_calls} UpdateTileMappings + {TEX_COUNT} Signals): submit={old_submit:?} gpu_done={old_total:?}" + ); + println!( + "AFTER ({TEX_COUNT} x 2MiB textures, {new_calls} UpdateTileMappings + {TEX_COUNT} Signals): submit={new_submit:?} gpu_done={new_total:?}" + ); + assert!(new_calls < old_calls); + } + } }