From 05c37573059f8fa682b63f7d8625fc0016d3f8e7 Mon Sep 17 00:00:00 2001 From: asc Date: Mon, 23 Nov 2026 23:55:11 -0500 Subject: [PATCH 1/7] GPU: reuse immutable descriptor tables across command lists --- crates/victory-gpu/src/descriptor.rs | 98 +++- crates/victory-gpu/src/descriptor/host.rs | 329 ++++++++--- .../src/descriptor/host/reuse_tests.rs | 523 ++++++++++++++++++ crates/victory-gpu/src/draw.rs | 41 +- 4 files changed, 873 insertions(+), 118 deletions(-) create mode 100644 crates/victory-gpu/src/descriptor/host/reuse_tests.rs diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 20b33fbe0ac..3117877a536 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -99,6 +99,55 @@ impl Heap { .as_ref() } + /// Resolve all slots in an eligible table before publishing a native + /// snapshot. Keep the view generations stable while recording the + /// list's normal texture preparation. + #[cfg(windows)] + pub(crate) fn with_texture_table( + &self, + table: u64, + count: u32, + f: impl FnOnce(&[TextureView<'_>]) -> R, + ) -> Option { + if self.desc.kind != VIEWS_KIND || count == 0 || count > host::DYNAMIC { + return None; + } + let offset = table.checked_sub(self.start)?; + if !offset.is_multiple_of(32) { + return None; + } + let last = table.checked_add(u64::from(count - 1) * 32)?; + self.index(last)?; + + let registry = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + let mut entries = Vec::new(); + for k in 0..count { + let at = table + u64::from(k) * 32; + // SAFETY: the entire immutable snapshot span is in the title heap. + let [tag, id, generation] = unsafe { (at as *const [u32; 3]).read_unaligned() }; + if [tag, id, generation] == [0, 0, 0] { + continue; + } + let (view, current) = registry.list.get(id as usize)?; + if tag != VIEW_TAG || *current != generation { + return None; + } + let resource = match view { + View::Shader(resource, _) | View::Unordered(resource, 0, _) => *resource, + _ => return None, + }; + let resource = crate::resource::host_resource(resource as This)?; + let record = u64::from(generation) << 32 | u64::from(id); + entries.push(TextureView { + slot: k, + record, + view, + resource, + }); + } + (!entries.is_empty()).then(|| f(&entries)) + } + /// The descriptor index of `handle` in this heap, if it lies in it. pub(crate) fn index(&self, handle: u64) -> Option { let step = u64::from(increment(self.desc.kind)?); @@ -148,19 +197,6 @@ fn mirror(handle: u64) { } } -/// Gives back dynamic slots of the host heap behind the title heap at -/// `heap`, if that heap still exists. -#[cfg(windows)] -pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) { - let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); - if heaps.iter().any(|&(_, _, h)| h == heap) - // SAFETY: registered heaps are live (removed when dropped). - && let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get() - { - host.release(first, n); - } -} - #[cfg(windows)] impl Drop for Heap { fn drop(&mut self) { @@ -295,6 +331,15 @@ pub(crate) enum View { Placed(bool, [u32; 14], [u32; 16]), } +/// A texture view resolved while its title view generation is live. +#[cfg(windows)] +pub(crate) struct TextureView<'a> { + pub(crate) slot: u32, + record: u64, + pub(crate) view: &'a View, + resource: &'a windows::Win32::Graphics::Direct3D12::ID3D12Resource, +} + impl View { /// Whether the view reads buffer memory (constant buffers, buffer views /// of resources or of memory) or memory the title placed a texture in: @@ -707,6 +752,33 @@ mod tests { assert_eq!(create(bad, none, &mut h), E_INVALIDARG); } + #[cfg(windows)] + #[test] + fn texture_table_eligibility_excludes_constant_buffers() { + let mut h = std::ptr::null(); + let desc = HeapDesc { + kind: VIEWS_KIND, + count: 4, + flags: SHADER_VISIBLE, + nodes: 0, + }; + let placement = Placement { + address: 0, + size: 0, + }; + assert_eq!(create(desc, placement, &mut h), S_OK); + let s = heap(h).start; + create_cbv(std::ptr::null(), &[0x1000, 1, 256, 0], s + 32); + fn reject(_: &[TextureView<'_>]) { + panic!("ineligible table was passed to the cache"); + } + assert_eq!(heap(h).with_texture_table(s, 4, reject), None::<()>); + assert_eq!(heap(h).with_texture_table(s + 1, 1, reject), None); + assert_eq!(heap(h).with_texture_table(s + 96, 2, reject), None); + assert_eq!(heap(h).with_texture_table(s + 64, 2, reject), None); + assert_eq!(release(h), 0); + } + #[test] fn views_survive_copies() { let null = std::ptr::null(); diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 582f2347adf..463dca4c584 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -5,23 +5,26 @@ //! writes it (view creation and descriptor copies) and again when a draw //! reads it through a table and finds the slot changed. -use std::sync::Mutex; +use std::collections::HashMap; +use std::sync::{Arc, Mutex, Weak}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; +use windows::core::Interface; -use super::{VIEW_TAG, View, view_at}; +use super::{TextureView, VIEW_TAG, View, view_at}; use crate::host::host; pub(crate) struct HostHeap { pub(crate) heap: ID3D12DescriptorHeap, + device: ID3D12Device, cpu: usize, step: u32, /// Slots mirroring the title's; view heaps have `dynamic` more. count: u32, /// Dynamic slots past `count` (none in sampler heaps): [`DYNAMIC`] /// where the host takes them, else [`MIN_DYNAMIC`]. - dynamic: u32, + dynamic_count: u32, sampler: bool, /// The record (view index and generation) each slot was last made from. made: Mutex>, @@ -30,9 +33,67 @@ pub(crate) struct HostHeap { /// released the resource may still be read, and a freed host resource /// read there is a GPU page fault (the console reads stale memory). kept: Mutex>>, - /// Where the search for free dynamic slots starts, and which are taken - /// (by lists not yet reset). + dynamic: Arc, +} + +/// View records and the resolved resources they name must both match. The +/// native identity is held alive by the table while its key is live. +#[derive(Clone, Eq, Hash, PartialEq)] +struct TableKey { + count: u32, + /// Sorted occupied offsets. Missing offsets are all the same null view. + views: Arc<[(u32, u64, usize)]>, +} + +struct DynamicSlots { + first: u32, next: Mutex<(u32, Vec)>, + shared: Mutex>>, +} + +/// An allocation tied to a particular host heap, even if a later title +/// heap reuses the same guest address. +pub(crate) struct DynamicRange { + pub(crate) first: u32, + count: u32, + dynamic: Arc, +} + +impl Drop for DynamicRange { + fn drop(&mut self) { + self.dynamic.release(self.first, self.count); + } +} + +/// One occupied range owned by the lists that may execute it. The cache has +/// only a weak reference, so it cannot pin otherwise unused ranges. +pub(crate) struct SharedTable { + key: TableKey, + range: DynamicRange, + _heap: ID3D12DescriptorHeap, + _resources: Vec, +} + +impl SharedTable { + pub(crate) fn first(&self) -> u32 { + self.range.first + } +} + +impl Drop for SharedTable { + fn drop(&mut self) { + let mut tables = self + .range + .dynamic + .shared + .lock() + .unwrap_or_else(|e| e.into_inner()); + // A newer snapshot with this key may have been published after + // our reference count hit zero but before this destructor ran. + if tables.get(&self.key).is_some_and(|entry| std::ptr::eq(entry.as_ptr(), self)) { + tables.remove(&self.key); + } + } } /// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for @@ -67,7 +128,7 @@ const PORTABLE_VIEWS: u32 = 1_000_000; /// took until it is reset (its submissions have run) or released. /// 2^16 ran out seconds into the world (every world run on an RX 9070 XT, /// each a device removal shortly after; #59). -const DYNAMIC: u32 = 1 << 18; +pub(super) const DYNAMIC: u32 = 1 << 18; /// The dynamic slots of a heap whose host would not take [`DYNAMIC`] more /// (a capped heap, NVIDIA): the title's slots keep their room first. @@ -75,7 +136,19 @@ const MIN_DYNAMIC: u32 = 1 << 16; impl HostHeap { pub(crate) fn new(sampler: bool, count: u32) -> Option { - let host = host()?; + Self::new_on(&host()?.device, sampler, count) + } + + fn new_on(device: &ID3D12Device, sampler: bool, count: u32) -> Option { + Self::new_on_with_dynamic(device, sampler, count, DYNAMIC) + } + + fn new_on_with_dynamic( + device: &ID3D12Device, + sampler: bool, + count: u32, + requested_dynamic: u32, + ) -> Option { let kind = if sampler { D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER } else { @@ -84,13 +157,12 @@ impl HostHeap { let make = |count: u32| -> windows::core::Result { // SAFETY: plain heap creation. unsafe { - host.device - .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { - Type: kind, - NumDescriptors: count, - Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, - NodeMask: 0, - }) + device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: count, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) } }; // The larger dynamic range only where the host takes it on top of @@ -103,8 +175,8 @@ impl HostHeap { return None; } } - } else if let Ok(heap) = make(count + DYNAMIC) { - (heap, count, DYNAMIC) + } else if let Ok(heap) = make(count + requested_dynamic) { + (heap, count, requested_dynamic) } else { match make(count + MIN_DYNAMIC) { Ok(heap) => (heap, count, MIN_DYNAMIC), @@ -124,7 +196,7 @@ impl HostHeap { let (cpu, step) = unsafe { ( heap.GetCPUDescriptorHandleForHeapStart().ptr, - host.device.GetDescriptorHandleIncrementSize(kind), + device.GetDescriptorHandleIncrementSize(kind), ) }; tracing::debug!(count, sampler, "host descriptor heap"); @@ -138,14 +210,19 @@ impl HostHeap { )); let h = HostHeap { heap, + device: device.clone(), cpu, step, count, - dynamic: extra, + dynamic_count: extra, sampler, made: Mutex::new(vec![0; count as usize]), kept: Mutex::new(vec![None; (count + extra) as usize]), - next: Mutex::new((0, vec![false; extra as usize])), + dynamic: Arc::new(DynamicSlots { + first: count, + next: Mutex::new((0, vec![false; extra as usize])), + shared: Mutex::new(HashMap::new()), + }), }; // A slot never written is undefined: shaders reading one (a slot // the title wrote in a way we do not know, or a table entry no @@ -163,34 +240,36 @@ impl HostHeap { /// doubled by copies to a block, the block copied over the heap. fn fill_null(&self, kind: D3D12_DESCRIPTOR_HEAP_TYPE, total: u32) -> windows::core::Result<()> { const BLOCK: u32 = 1 << 16; - let Some(host) = host() else { return Ok(()) }; // SAFETY: plain heap creation and copies inside live heaps. unsafe { let block: ID3D12DescriptorHeap = - host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { - Type: kind, - NumDescriptors: BLOCK, - ..Default::default() - })?; + self.device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: BLOCK, + ..Default::default() + })?; let start = block.GetCPUDescriptorHandleForHeapStart(); let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + (i * self.step) as usize, }; if self.sampler { - null_sampler(start); + null_sampler(&self.device, start); } else { - null_view(start); + null_view(&self.device, start); } let mut filled = 1; while filled < BLOCK { let n = filled.min(BLOCK - filled); - host.device.CopyDescriptorsSimple(n, at(filled), start, kind); + self.device + .CopyDescriptorsSimple(n, at(filled), start, kind); filled += n; } let mut done = 0; while done < total { let n = BLOCK.min(total - done); - host.device.CopyDescriptorsSimple(n, self.cpu(done), start, kind); + self.device + .CopyDescriptorsSimple(n, self.cpu(done), start, kind); done += n; } } @@ -200,13 +279,12 @@ impl HostHeap { /// A plain point sampler at slot `index`, for sampler slots without a /// view. fn null_sampler(&self, index: u32) { - null_sampler(self.cpu(index)); + null_sampler(&self.device, self.cpu(index)); } } /// A plain point sampler at `at`. -fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) { - let Some(host) = host() else { return }; +fn null_sampler(device: &ID3D12Device, at: D3D12_CPU_DESCRIPTOR_HANDLE) { let desc = D3D12_SAMPLER_DESC { Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, @@ -217,21 +295,21 @@ fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) { ..Default::default() }; // SAFETY: a slot of a sampler heap of ours. - unsafe { host.device.CreateSampler(&desc, at) }; + unsafe { device.CreateSampler(&desc, at) }; } impl HostHeap { /// `n` consecutive free dynamic slots (view heaps only), taken until - /// [`HostHeap::release`]: the first's index. - pub(crate) fn dynamic(&self, n: u32) -> Option { - if self.sampler || n == 0 || n > self.dynamic { + /// [`DynamicSlots::release`]: the first's index. + fn dynamic(&self, n: u32) -> Option { + if self.sampler || n == 0 || n > self.dynamic_count { return None; } - let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); + let mut guard = self.dynamic.next.lock().unwrap_or_else(|e| e.into_inner()); let (next, taken) = &mut *guard; let n = n as usize; // Search from `next` on, then from the start. - let starts = (*next as usize..self.dynamic as usize).chain(0..*next as usize); + let starts = (*next as usize..self.dynamic_count as usize).chain(0..*next as usize); let mut run = 0; let mut found = None; let mut last = usize::MAX; @@ -253,7 +331,7 @@ impl HostHeap { return None; }; taken[first..first + n].fill(true); - *next = ((first + n) % self.dynamic as usize) as u32; + *next = ((first + n) % self.dynamic_count as usize) as u32; Some(self.count + first as u32) } @@ -263,19 +341,62 @@ impl HostHeap { self.count } - /// Gives back `n` dynamic slots from `first` (an index [`dynamic`] - /// returned). - /// - /// [`dynamic`]: HostHeap::dynamic - pub(crate) fn release(&self, first: u32, n: u32) { - let Some(at) = first.checked_sub(self.count) else { - return; + /// The returned allocation releases its own host range on drop. + pub(crate) fn reserve_dynamic(&self, count: u32) -> Option { + Some(DynamicRange { + first: self.dynamic(count)?, + count, + dynamic: self.dynamic.clone(), + }) + } + + /// Share a fully resolved texture table while at least one list owns it. + /// Buffer, CBV and placed views require list-local storage or preparation. + pub(crate) fn shared_textures( + &self, + count: u32, + views: &[TextureView<'_>], + ) -> Option> { + let key = TableKey { + count, + views: views + .iter() + .map(|e| (e.slot, e.record, e.resource.as_raw() as usize)) + .collect(), }; - let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); - let end = (at + n).min(self.dynamic) as usize; - if let Some(slots) = guard.1.get_mut(at as usize..end) { - slots.fill(false); + let mut tables = self + .dynamic + .shared + .lock() + .unwrap_or_else(|e| e.into_inner()); + if let Some(table) = tables.get(&key).and_then(Weak::upgrade) { + return Some(table); + } + let range = self.reserve_dynamic(count)?; + let first = range.first; + let mut resources = Vec::with_capacity(views.len()); + let mut populated = views.iter().peekable(); + for slot in 0..count { + let index = first + slot; + if populated.peek().is_some_and(|e| e.slot == slot) { + let entry = populated.next().unwrap(); + if !make_texture(&self.device, entry.resource, entry.view, self.cpu(index)) { + return None; + } + self.keep(index, None); + resources.push(entry.resource.clone()); + } else { + self.make_null(index); + } } + let table = Arc::new(SharedTable { + key: key.clone(), + range, + _heap: self.heap.clone(), + _resources: resources, + }); + tables.insert(key, Arc::downgrade(&table)); + Some(table) } /// Makes slot `index` (a dynamic one) from `view`; a null view if the @@ -293,7 +414,7 @@ impl HostHeap { if self.sampler { self.null_sampler(index); } else { - null_view(self.cpu(index)); + null_view(&self.device, self.cpu(index)); } self.keep(index, None); } @@ -621,6 +742,58 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere true } +impl DynamicSlots { + fn release(&self, first: u32, n: u32) { + let Some(at) = first.checked_sub(self.first) else { + return; + }; + let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); + let end = (at + n).min(guard.1.len() as u32) as usize; + if let Some(slots) = guard.1.get_mut(at as usize..end) { + slots.fill(false); + } + } +} + +/// Writes a view of a native texture with the same validation as the +/// mirrored and list-local paths. +fn make_texture( + device: &ID3D12Device, + texture: &ID3D12Resource, + view: &View, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) -> bool { + match view { + View::Shader(_, desc) => { + let mut desc = desc.as_ref().map(srv_desc); + if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) { + return false; + } + // SAFETY: a live texture and a slot of our heap. + unsafe { + device.CreateShaderResourceView(texture, desc.as_ref().map(std::ptr::from_ref), at) + }; + } + View::Unordered(_, _, desc) => { + let mut desc = desc.as_ref().map(uav_desc); + if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) { + return false; + } + // SAFETY: a live texture and a slot of our heap. + unsafe { + device.CreateUnorderedAccessView( + texture, + None::<&ID3D12Resource>, + desc.as_ref().map(std::ptr::from_ref), + at, + ) + }; + } + _ => return false, + } + true +} + /// Makes the host descriptor for `view` at `at`: the host resource it /// views, or `None` if it cannot. fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { @@ -648,19 +821,7 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { View::Shader(resource, desc) => { let resource = *resource as crate::object::This; if let Some(texture) = crate::resource::host_resource(resource) { - let mut desc = desc.as_ref().map(srv_desc); - if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) { - return None; - } - // SAFETY: a live texture and a slot of our heap. - unsafe { - device.CreateShaderResourceView( - texture, - desc.as_ref().map(std::ptr::from_ref), - at, - ) - }; - Some(Some(texture.clone())) + make_texture(device, texture, view, at).then(|| Some(texture.clone())) } else if let (Some((data, len)), Some(desc)) = (crate::resource::buffer_bytes(resource), desc) { @@ -679,20 +840,7 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { _ => None, }; }; - let mut desc = desc.as_ref().map(uav_desc); - if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) { - return None; - } - // SAFETY: a live texture and a slot of our heap. - unsafe { - device.CreateUnorderedAccessView( - texture, - None::<&ID3D12Resource>, - desc.as_ref().map(std::ptr::from_ref), - at, - ) - }; - Some(Some(texture.clone())) + make_texture(device, texture, view, at).then(|| Some(texture.clone())) } View::Sampler(words) => { // SAFETY: 13 words in the host's layout. @@ -783,7 +931,7 @@ fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { // SAFETY: a slot of our heap; a zero location makes a null view. return unsafe { host.device.CreateConstantBufferView(Some(&desc), at) }; } - _ => return null_view(at), + _ => return null_view(&host.device, at), }; let desc = if buffer { D3D12_UNORDERED_ACCESS_VIEW_DESC { @@ -871,11 +1019,11 @@ fn null_buffer_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { /// A texture view that reads zeros with the dimension (and mip and array /// counts) of the title's description `words`; 2D if it names none. fn null_like(words: &[u32; 10], at: D3D12_CPU_DESCRIPTOR_HANDLE) { + let Some(host) = host() else { return }; const TEXTURES: std::ops::RangeInclusive = 2..=10; if !TEXTURES.contains(&words[1]) { - return null_view(at); + return null_view(&host.device, at); } - let Some(host) = host() else { return }; // One mip, one slice or cube, plane 0: fields a null view still checks. let mut w = [0u32; 10]; w[1] = words[1]; @@ -899,8 +1047,7 @@ fn null_like(words: &[u32; 10], at: D3D12_CPU_DESCRIPTOR_HANDLE) { /// shortcut: slots with no view at all (kind unknown) get this null 2D /// view; null buffer views there did not stop the world's low-address /// page faults (2026-11-24, run w10), so they are not the cause. -fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { - let Some(host) = host() else { return }; +fn null_view(device: &ID3D12Device, at: D3D12_CPU_DESCRIPTOR_HANDLE) { let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT_R8G8B8A8_UNORM, ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, @@ -913,10 +1060,7 @@ fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { }, }; // SAFETY: a slot of our heap; a null resource is allowed with a desc. - unsafe { - host.device - .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at) - }; + unsafe { device.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at) }; } #[cfg(test)] @@ -964,13 +1108,16 @@ mod tests { let Some(heap) = HostHeap::new(false, 4) else { return; // no host GPU }; - let a = heap.dynamic(heap.dynamic - 100).unwrap(); + let a = heap.dynamic(heap.dynamic_count - 100).unwrap(); let b = heap.dynamic(60).unwrap(); - assert_eq!((a, b), (4, 4 + heap.dynamic - 100)); + assert_eq!((a, b), (4, 4 + heap.dynamic_count - 100)); // 40 left at the end: 50 do not fit until something is given back. assert_eq!(heap.dynamic(50), None); - heap.release(a, 50); + heap.dynamic.release(a, 50); assert_eq!(heap.dynamic(50), Some(4)); - assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); + assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic_count - 40)); } } + +#[cfg(test)] +mod reuse_tests; diff --git a/crates/victory-gpu/src/descriptor/host/reuse_tests.rs b/crates/victory-gpu/src/descriptor/host/reuse_tests.rs new file mode 100644 index 00000000000..4b2d2ef6924 --- /dev/null +++ b/crates/victory-gpu/src/descriptor/host/reuse_tests.rs @@ -0,0 +1,523 @@ +//! Original 65,536-slot D3D12 allocator and descriptor readback fixture. +//! Set VICTORY_TABLE_TEST_ADAPTER (amd, nvidia or warp), +//! VICTORY_TABLE_TEST_AGILITY (Agility SDK 1.620.x x64 DLL directory) and +//! VICTORY_TABLE_TEST_DXC (dxc.exe path), then run: +//! cargo test --release -p victory-gpu --features diagnostics capped_pool_texture_table_reuse -- --ignored --nocapture +//! The default run uses GPU-based validation. Set VICTORY_TABLE_TEST_TIMING=1 +//! to measure CPU descriptor preparation with validation disabled. + +use super::*; +use std::mem::ManuallyDrop; +use std::time::Instant; +use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; +use windows::Win32::Graphics::Dxgi::*; +use windows::core::PCSTR; + +const HLSL: &str = r#" +#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), RootConstants(num32BitConstants=2, b0), UAV(u0)" +cbuffer Constants : register(b0) { uint slot, index; }; +RWByteAddressBuffer output : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + Texture2D image = ResourceDescriptorHeap[slot]; + output.Store(index * 4, image.Load(int3(0, 0, 0))); +} +"#; +const FIRST: u32 = 0x1458_acef; +const SECOND: u32 = 0xfec1_4921; +const SPAN: u32 = 2048; + +fn device(validate: bool) -> (ID3D12Device, String) { + let sdk = std::env::var("VICTORY_TABLE_TEST_AGILITY").expect("Agility SDK 1.620.x x64 path"); + let sdk = std::ffi::CString::new(format!("{}\\", sdk.trim_end_matches(['/', '\\']))).unwrap(); + let vendor = std::env::var("VICTORY_TABLE_TEST_ADAPTER").expect("amd, nvidia or warp"); + // SAFETY: the configuration, adapter enumeration and output pointers are ours. + unsafe { + let mut configuration: Option = None; + D3D12GetInterface(&CLSID_D3D12SDKConfiguration, &mut configuration).unwrap(); + let factory: ID3D12DeviceFactory = configuration + .unwrap() + .CreateDeviceFactory(620, PCSTR(sdk.as_ptr().cast())) + .unwrap(); + if validate { + let debug: ID3D12Debug = factory + .GetConfigurationInterface(&CLSID_D3D12Debug) + .unwrap(); + debug.EnableDebugLayer(); + debug + .cast::() + .unwrap() + .SetEnableGPUBasedValidation(true); + } + let dxgi: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap(); + let adapter: IDXGIAdapter1 = if vendor == "warp" { + dxgi.EnumWarpAdapter().unwrap() + } else { + let vendor = match vendor.as_str() { + "amd" => 0x1002, + "nvidia" => 0x10de, + _ => panic!("unknown adapter {vendor}"), + }; + (0..) + .map_while(|i| dxgi.EnumAdapters1(i).ok()) + .find(|a| a.GetDesc1().unwrap().VendorId == vendor) + .expect("requested hardware adapter") + }; + let desc = adapter.GetDesc1().unwrap(); + let end = desc + .Description + .iter() + .position(|&c| c == 0) + .unwrap_or(desc.Description.len()); + let name = String::from_utf16_lossy(&desc.Description[..end]); + assert_eq!( + vendor == "warp", + desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 + ); + let mut device = None; + factory + .CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device) + .unwrap(); + (device.unwrap(), name) + } +} + +fn shader() -> Vec { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("table.hlsl"); + let binary = dir.path().join("table.dxil"); + std::fs::write(&source, HLSL).unwrap(); + let result = std::process::Command::new(std::env::var_os("VICTORY_TABLE_TEST_DXC").unwrap()) + .args(["-E", "main", "-T", "cs_6_6", "-Fo"]) + .arg(&binary) + .arg(&source) + .output() + .unwrap(); + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stderr) + ); + std::fs::read(binary).unwrap() +} + +fn resource( + device: &ID3D12Device, + heap: D3D12_HEAP_TYPE, + state: D3D12_RESOURCE_STATES, + desc: &D3D12_RESOURCE_DESC, +) -> ID3D12Resource { + let mut resource = None; + // SAFETY: caller supplies a valid resource description and initial state. + unsafe { + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: heap, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + desc, + state, + None, + &mut resource, + ) + .unwrap(); + } + resource.unwrap() +} + +fn buf(width: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: width, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + } +} + +fn list(device: &ID3D12Device) -> (ID3D12CommandAllocator, ID3D12GraphicsCommandList) { + // SAFETY: creates a direct list and its matching allocator. + unsafe { + let allocator: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .unwrap(); + let list = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .unwrap(); + (allocator, list) + } +} + +struct Fixture { + device: ID3D12Device, + queue: ID3D12CommandQueue, + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + textures: [ID3D12Resource; 2], + upload: ID3D12Resource, +} + +impl Fixture { + fn new(device: ID3D12Device) -> Self { + let code = shader(); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Format: DXGI_FORMAT_R32_UINT, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + ..buf(1, D3D12_RESOURCE_FLAG_NONE) + }; + let textures = [(); 2].map(|()| { + resource( + &device, + D3D12_HEAP_TYPE_DEFAULT, + D3D12_RESOURCE_STATE_COPY_DEST, + &desc, + ) + }); + let upload = resource( + &device, + D3D12_HEAP_TYPE_UPLOAD, + D3D12_RESOURCE_STATE_GENERIC_READ, + &buf(1024, D3D12_RESOURCE_FLAG_NONE), + ); + // SAFETY: valid pipeline inputs and live resources. The upload is + // initialized before the command list is submitted, then kept alive. + unsafe { + let queue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()) + .unwrap(); + let root = device.CreateRootSignature(0, &code).unwrap(); + let pso_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(ID3D12RootSignature::clone(&root))), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: code.as_ptr().cast(), + BytecodeLength: code.len(), + }, + ..Default::default() + }; + let pso = device.CreateComputePipelineState(&pso_desc).unwrap(); + drop(ManuallyDrop::into_inner(pso_desc.pRootSignature)); + let mut data = std::ptr::null_mut(); + upload + .Map(0, Some(&D3D12_RANGE::default()), Some(&mut data)) + .unwrap(); + data.cast::().write_bytes(0, 1024); + data.cast::().write(FIRST); + data.cast::().add(128).write(SECOND); + upload.Unmap(0, None); + let (_allocator, setup) = list(&device); + for (i, texture) in textures.iter().enumerate() { + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(upload.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: (i * 512) as u64, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R32_UINT, + Width: 1, + Height: 1, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(texture.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + setup.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + drop(ManuallyDrop::into_inner(src.pResource)); + drop(ManuallyDrop::into_inner(dst.pResource)); + setup.ResourceBarrier(&[crate::host::transition( + texture, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + } + setup.Close().unwrap(); + let fixture = Self { + device, + queue, + root, + pso, + textures, + upload, + }; + fixture.submit(&[setup]); + fixture + } + } + + fn submit(&self, lists: &[ID3D12GraphicsCommandList]) { + let lists: Vec<_> = lists + .iter() + .map(|list| Some(list.cast::().unwrap())) + .collect(); + // SAFETY: closed lists and their live allocators, fence owned by this test. + unsafe { + self.queue.ExecuteCommandLists(&lists); + let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + self.queue.Signal(&fence, 1).unwrap(); + fence.SetEventOnCompletion(1, Default::default()).unwrap(); + self.device.GetDeviceRemovedReason().unwrap(); + } + } +} + +fn occupancy(heap: &HostHeap) -> usize { + heap.dynamic + .next + .lock() + .unwrap() + .1 + .iter() + .filter(|&&used| used) + .count() +} + +fn heap_replacement(fixture: &Fixture) { + let view = View::Shader(0, None); + let views = [TextureView { + slot: 0, + record: 1 << 32, + view: &view, + resource: &fixture.textures[0], + }]; + let original = HostHeap::new_on(&fixture.device, false, 1).unwrap(); + let original_pool = Arc::downgrade(&original.dynamic); + let original_table = original.shared_textures(SPAN, &views).unwrap(); + let list_local = original.reserve_dynamic(SPAN).unwrap(); + drop(original); + + let replacement = HostHeap::new_on(&fixture.device, false, 1).unwrap(); + let replacement_table = replacement.shared_textures(SPAN, &views).unwrap(); + assert_eq!(original_table.first(), replacement_table.first()); + assert!(!Arc::ptr_eq(&original_table, &replacement_table)); + assert_ne!( + original_table._heap.as_raw(), + replacement_table._heap.as_raw() + ); + drop(original_table); + assert!(original_pool.upgrade().is_some()); + drop(list_local); + assert!(original_pool.upgrade().is_none()); + assert_eq!(occupancy(&replacement), SPAN as usize); +} + +struct ResultRow { + failed: usize, + occupied: usize, + preparing: std::time::Duration, +} + +fn run(fixture: &Fixture, shared: bool, lists: usize, distinct: bool) -> ResultRow { + let device = &fixture.device; + let heap = HostHeap::new_on_with_dynamic(device, false, 1, MIN_DYNAMIC).unwrap(); + let width = (lists * 4) as u64; + let output = resource( + device, + D3D12_HEAP_TYPE_DEFAULT, + D3D12_RESOURCE_STATE_COMMON, + &buf(width, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + ); + let back = resource( + device, + D3D12_HEAP_TYPE_READBACK, + D3D12_RESOURCE_STATE_COPY_DEST, + &buf(width, D3D12_RESOURCE_FLAG_NONE), + ); + let (init_allocator, init) = list(device); + let (end_allocator, end) = list(device); + let recorded: Vec<_> = (0..lists).map(|_| list(device)).collect(); + let mut failures = 0; + let mut preparing = std::time::Duration::ZERO; + let mut work = vec![init.clone()]; + let mut leases = Vec::with_capacity(lists); + let mut expected = vec![0; lists]; + + // SAFETY: all lists are open and all resources remain live through the fence. + unsafe { + init.ResourceBarrier(&[crate::host::transition( + &output, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_DEST, + )]); + init.CopyBufferRegion(&output, 0, &fixture.upload, 768, width); + init.ResourceBarrier(&[crate::host::transition( + &output, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + init.Close().unwrap(); + for (index, (_, list)) in recorded.iter().enumerate() { + let rewritten = index + 1 == lists; + let texture = &fixture.textures[usize::from(rewritten)]; + let view = View::Shader(0, None); + // New generations can coexist at the same title view index. + let generation = u64::from(rewritten) + 1; + let position = if distinct { index as u32 } else { 0 }; + let views = [TextureView { + slot: position, + record: generation << 32, + view: &view, + resource: texture, + }]; + let started = Instant::now(); + let slot = if shared { + heap.shared_textures(SPAN, &views).map(|lease| { + let first = lease.first(); + leases.push(lease); + first + }) + } else if let Some(first) = heap.dynamic(SPAN) { + for slot in first..first + SPAN { + if slot == first + position { + assert!(make_texture(device, texture, &view, heap.cpu(slot))); + heap.keep(slot, Some(texture.clone())); + } else { + heap.make_null(slot); + } + } + Some(first) + } else { + None + }; + preparing += started.elapsed(); + if let Some(slot) = slot { + list.SetDescriptorHeaps(&[Some(heap.heap.clone())]); + list.SetComputeRootSignature(&fixture.root); + list.SetPipelineState(&fixture.pso); + let values = [slot + position, index as u32]; + list.SetComputeRoot32BitConstants(0, 2, values.as_ptr().cast(), 0); + list.SetComputeRootUnorderedAccessView(1, output.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + expected[index] = if rewritten { SECOND } else { FIRST }; + work.push(list.clone()); + } else { + failures += 1; + } + list.Close().unwrap(); + } + end.ResourceBarrier(&[crate::host::transition( + &output, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + end.CopyBufferRegion(&back, 0, &output, 0, width); + end.Close().unwrap(); + work.push(end); + fixture.submit(&work); + + let mut data = std::ptr::null_mut(); + back.Map(0, None, Some(&mut data)).unwrap(); + assert_eq!( + std::slice::from_raw_parts(data.cast::(), lists), + expected + ); + back.Unmap(0, Some(&D3D12_RANGE::default())); + drop((init_allocator, end_allocator, recorded)); + } + let occupied = occupancy(&heap); + if shared { + let keep = leases.pop().unwrap(); + drop(leases); + assert_eq!(occupancy(&heap), SPAN as usize); + drop(keep); + assert_eq!(occupancy(&heap), 0); + assert!(heap.dynamic.shared.lock().unwrap().is_empty()); + } + ResultRow { + failed: failures, + occupied, + preparing, + } +} + +#[test] +#[ignore = "requires a named D3D12 adapter, DXC and Agility SDK 1.620.x"] +fn capped_pool_texture_table_reuse() { + let timing = std::env::var_os("VICTORY_TABLE_TEST_TIMING").is_some(); + let (device, name) = device(!timing); + let info = (!timing).then(|| device.cast::().unwrap()); + let fixture = Fixture::new(device); + for (label, count, distinct) in [ + ("over-cap", 41, false), + ("equal-work", 24, false), + ("unique", 24, true), + ] { + if timing { + run(&fixture, false, count, distinct); + run(&fixture, true, count, distinct); + } + let mut samples = [Vec::new(), Vec::new()]; + for sample in 0..if timing { 5 } else { 1 } { + for shared in [sample % 2 != 0, sample % 2 == 0] { + let row = run(&fixture, shared, count, distinct); + let expected_failures = if shared { + 0 + } else { + count.saturating_sub((MIN_DYNAMIC / SPAN) as usize) + }; + let ranges = if shared && !distinct { + 2 + } else { + count - expected_failures + }; + assert_eq!(row.failed, expected_failures); + assert_eq!(row.occupied, ranges * SPAN as usize); + eprintln!( + "{name} {label} shared={shared} failed={} peak={} prepare_ms={:.3}", + row.failed, + row.occupied, + row.preparing.as_secs_f64() * 1000.0 + ); + samples[usize::from(shared)].push(row.preparing); + } + } + for (shared, samples) in samples.iter_mut().enumerate() { + samples.sort_unstable(); + eprintln!( + "{name} {label} shared={} median_ms={:.3}", + shared != 0, + samples[samples.len() / 2].as_secs_f64() * 1000.0 + ); + } + } + if let Some(info) = info { + heap_replacement(&fixture); + // SAFETY: fetch each validation message into its aligned buffer. + unsafe { + for i in 0..info.GetNumStoredMessages() { + let mut bytes = 0; + info.GetMessage(i, None, &mut bytes).unwrap(); + let mut storage = vec![0u64; bytes.div_ceil(8)]; + let message = storage.as_mut_ptr().cast::(); + info.GetMessage(i, Some(message), &mut bytes).unwrap(); + let message = &*message; + assert!( + message.Severity.0 > D3D12_MESSAGE_SEVERITY_ERROR.0, + "{}", + String::from_utf8_lossy(std::slice::from_raw_parts( + message.pDescription, + message.DescriptionByteLength, + )) + ); + } + } + } +} diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index d2537cc4ad9..a76b881ab80 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -74,21 +74,15 @@ pub(crate) struct State { /// Tables made afresh in this list: (table, what it holds) → first /// dynamic slot. fresh_tables: std::collections::HashMap<(u64, u64), u32>, - /// The dynamic slots the list holds: title heap, first, count; given - /// back when the list is reset or released. - dynamic: Vec<(usize, u32, u32)>, + /// Keep each shared range until this list can no longer be submitted. + shared_tables: + std::collections::HashMap>, + /// Dynamic list-local tables (including their CBV descriptors). + dynamic: Vec, /// A fresh table of the stage being bound could not be made. table_failed: bool, } -impl Drop for State { - fn drop(&mut self) { - for &(heap, first, n) in &self.dynamic { - crate::descriptor::release_dynamic(heap, first, n); - } - } -} - /// Draws recorded on the host GPU since the last frame line. static DRAWN: AtomicU64 = AtomicU64::new(0); @@ -702,6 +696,25 @@ impl State { .map(|u| u.table_offset_dwords / 8 + 1) .max() .unwrap_or(1); + if !entries.iter().any(|u| u.kind == ResourceType::Cbv) + && let Some(shared) = heap + .with_texture_table(table, n, |views| { + let shared = host.shared_textures(n, views)?; + for u in &entries { + let offset = u.table_offset_dwords / 8; + if let Ok(i) = views.binary_search_by_key(&offset, |view| view.slot) { + readable(list, u, views[i].view); + } + } + Some(shared) + }) + .flatten() + { + made.push((slot, shared.first() * 32)); + let identity = std::sync::Arc::as_ptr(&shared) as usize; + self.shared_tables.entry(identity).or_insert(shared); + continue; + } // The table and what its entries hold (record words). let key = { use std::hash::{Hash, Hasher}; @@ -723,7 +736,7 @@ impl State { made.push((slot, first * 32)); continue; } - let Some(first) = host.dynamic(n) else { + let Some(range) = host.reserve_dynamic(n) else { // Without its fresh table the shader would read the title's // slots, which for constant buffer tables hold no constant // view: a texture or null descriptor read as a buffer gives @@ -732,9 +745,9 @@ impl State { self.table_failed = true; continue; }; + let first = range.first; self.fresh_tables.insert(key, first); - self.dynamic - .push((std::ptr::from_ref(heap) as usize, first, n)); + self.dynamic.push(range); // The whole range: a shader may index past the entries its // used-resource list names (descriptor arrays). for k in 0..n { From a0afa2bdec1aa9c91694c9690f9e65f040c1fbed Mon Sep 17 00:00:00 2001 From: asc Date: Tue, 24 Nov 2026 02:16:14 -0500 Subject: [PATCH 2/7] Tests: verify rebuilt CBV submit-time snapshots --- .../src/descriptor/host/reuse_tests.rs | 81 ++++--- .../host/reuse_tests/cbv_snapshots.rs | 201 ++++++++++++++++++ crates/victory-gpu/src/draw.rs | 9 + crates/victory-gpu/src/host.rs | 22 +- docs/cbv-table-snapshots.md | 80 +++++++ 5 files changed, 359 insertions(+), 34 deletions(-) create mode 100644 crates/victory-gpu/src/descriptor/host/reuse_tests/cbv_snapshots.rs create mode 100644 docs/cbv-table-snapshots.md diff --git a/crates/victory-gpu/src/descriptor/host/reuse_tests.rs b/crates/victory-gpu/src/descriptor/host/reuse_tests.rs index 4b2d2ef6924..804f2d854f6 100644 --- a/crates/victory-gpu/src/descriptor/host/reuse_tests.rs +++ b/crates/victory-gpu/src/descriptor/host/reuse_tests.rs @@ -13,6 +13,8 @@ use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; use windows::Win32::Graphics::Dxgi::*; use windows::core::PCSTR; +mod cbv_snapshots; + const HLSL: &str = r#" #define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), RootConstants(num32BitConstants=2, b0), UAV(u0)" cbuffer Constants : register(b0) { uint slot, index; }; @@ -83,11 +85,11 @@ fn device(validate: bool) -> (ID3D12Device, String) { } } -fn shader() -> Vec { +fn shader(hlsl: &str) -> Vec { let dir = tempfile::tempdir().unwrap(); let source = dir.path().join("table.hlsl"); let binary = dir.path().join("table.dxil"); - std::fs::write(&source, HLSL).unwrap(); + std::fs::write(&source, hlsl).unwrap(); let result = std::process::Command::new(std::env::var_os("VICTORY_TABLE_TEST_DXC").unwrap()) .args(["-E", "main", "-T", "cs_6_6", "-Fo"]) .arg(&binary) @@ -102,6 +104,27 @@ fn shader() -> Vec { std::fs::read(binary).unwrap() } +fn compute_pipeline( + device: &ID3D12Device, + code: &[u8], +) -> (ID3D12RootSignature, ID3D12PipelineState) { + // SAFETY: live device and compiled compute shader with an embedded root signature. + unsafe { + let root = device.CreateRootSignature(0, code).unwrap(); + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(ID3D12RootSignature::clone(&root))), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: code.as_ptr().cast(), + BytecodeLength: code.len(), + }, + ..Default::default() + }; + let pipeline = device.CreateComputePipelineState(&desc); + drop(ManuallyDrop::into_inner(desc.pRootSignature)); + (root, pipeline.unwrap()) + } +} + fn resource( device: &ID3D12Device, heap: D3D12_HEAP_TYPE, @@ -169,7 +192,8 @@ struct Fixture { impl Fixture { fn new(device: ID3D12Device) -> Self { - let code = shader(); + let code = shader(HLSL); + let (root, pso) = compute_pipeline(&device, &code); let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Format: DXGI_FORMAT_R32_UINT, @@ -196,17 +220,6 @@ impl Fixture { let queue = device .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()) .unwrap(); - let root = device.CreateRootSignature(0, &code).unwrap(); - let pso_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: ManuallyDrop::new(Some(ID3D12RootSignature::clone(&root))), - CS: D3D12_SHADER_BYTECODE { - pShaderBytecode: code.as_ptr().cast(), - BytecodeLength: code.len(), - }, - ..Default::default() - }; - let pso = device.CreateComputePipelineState(&pso_desc).unwrap(); - drop(ManuallyDrop::into_inner(pso_desc.pRootSignature)); let mut data = std::ptr::null_mut(); upload .Map(0, Some(&D3D12_RANGE::default()), Some(&mut data)) @@ -500,24 +513,28 @@ fn capped_pool_texture_table_reuse() { } if let Some(info) = info { heap_replacement(&fixture); - // SAFETY: fetch each validation message into its aligned buffer. - unsafe { - for i in 0..info.GetNumStoredMessages() { - let mut bytes = 0; - info.GetMessage(i, None, &mut bytes).unwrap(); - let mut storage = vec![0u64; bytes.div_ceil(8)]; - let message = storage.as_mut_ptr().cast::(); - info.GetMessage(i, Some(message), &mut bytes).unwrap(); - let message = &*message; - assert!( - message.Severity.0 > D3D12_MESSAGE_SEVERITY_ERROR.0, - "{}", - String::from_utf8_lossy(std::slice::from_raw_parts( - message.pDescription, - message.DescriptionByteLength, - )) - ); - } + check_debug_messages(&info); + } +} + +fn check_debug_messages(info: &ID3D12InfoQueue) { + // SAFETY: fetch each validation message into its aligned buffer. + unsafe { + for i in 0..info.GetNumStoredMessages() { + let mut bytes = 0; + info.GetMessage(i, None, &mut bytes).unwrap(); + let mut storage = vec![0u64; bytes.div_ceil(8)]; + let message = storage.as_mut_ptr().cast::(); + info.GetMessage(i, Some(message), &mut bytes).unwrap(); + let message = &*message; + assert!( + message.Severity.0 > D3D12_MESSAGE_SEVERITY_ERROR.0, + "{}", + String::from_utf8_lossy(std::slice::from_raw_parts( + message.pDescription, + message.DescriptionByteLength, + )) + ); } } } diff --git a/crates/victory-gpu/src/descriptor/host/reuse_tests/cbv_snapshots.rs b/crates/victory-gpu/src/descriptor/host/reuse_tests/cbv_snapshots.rs new file mode 100644 index 00000000000..d46aae52a29 --- /dev/null +++ b/crates/victory-gpu/src/descriptor/host/reuse_tests/cbv_snapshots.rs @@ -0,0 +1,201 @@ +//! An original shader reading two words of a rebuilt CBV. The production +//! table builder and submission loop supply each list's snapshot. + +use super::*; +use crate::descriptor::{HEAP_IIDS, HeapDesc, Placement, create_cbv, create_heap, heap, release}; +use crate::draw::State; +use crate::host::{HostList, PREPARING, install_test_device}; +use crate::object::{S_OK, This}; +use victory_shader::{ResourceType, RootType, UsedResource}; + +const HLSL: &str = r#" +#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), RootConstants(num32BitConstants=2, b0), UAV(u0)" +cbuffer Bindings : register(b0) { uint slot, index; }; +RWByteAddressBuffer output : register(u0); +struct Values { uint4 rows[16]; }; +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + ConstantBuffer values = ResourceDescriptorHeap[slot]; + output.Store2(index * 8, uint2(values.rows[0].x, values.rows[15].w)); +} +"#; + +#[repr(align(16))] +struct Payload([u32; 64]); + +impl Payload { + fn from_pair(pair: [u32; 2]) -> Self { + let mut words = [0; 64]; + words[0] = pair[0]; + words[63] = pair[1]; + Self(words) + } +} + +struct TitleHeap(This); + +impl TitleHeap { + fn new() -> Self { + #[repr(C)] + struct Extended(HeapDesc, Placement); + let desc = Extended( + HeapDesc { + kind: 0, + count: 8, + flags: 1, + nodes: 0, + }, + Placement { + address: 0, + size: 0, + }, + ); + let mut object = std::ptr::null(); + assert_eq!( + create_heap(std::ptr::null(), &desc.0, &HEAP_IIDS[0], &mut object), + S_OK + ); + Self(object) + } + + fn cbv_slot(&self, state: &mut State, list: &HostList) -> u32 { + state.set_heaps(&[self.0]); + state.set_table(true, 0, heap(self.0).start); + let used = [UsedResource { + kind: ResourceType::Cbv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }]; + let slots = state.test_compute_tables(list, &used); + let [(0, offset)] = slots.as_slice() else { + panic!("no rebuilt CBV table") + }; + offset / 32 + } +} + +impl Drop for TitleHeap { + fn drop(&mut self) { + assert_eq!(release(self.0), 0); + } +} + +#[test] +#[ignore = "requires a named D3D12 adapter, DXC and Agility SDK 1.620.x; run alone"] +fn repeated_cbv_records_require_separate_submit_time_snapshots() { + let (device, name) = device(true); + let info: ID3D12InfoQueue = device.cast().unwrap(); + let host = install_test_device(device.clone()); + let code = shader(HLSL); + let (root, pipeline) = compute_pipeline(&device, &code); + let size = size_of::(); + assert_eq!(size, 256); + let mut title = Box::new(Payload::from_pair([11, 12])); + let mut replacement = Box::new(Payload::from_pair([13, 14])); + let title_ptr = (&raw mut title.0).cast::(); + let replacement_ptr = (&raw mut replacement.0).cast::(); + let descriptors = TitleHeap::new(); + let source = title_ptr as u64; + create_cbv( + std::ptr::null(), + &[source as u32, (source >> 32) as u32, size as u32, 0], + heap(descriptors.0).start, + ); + let heap = heap(descriptors.0).host().unwrap(); + + let first = host.new_list().unwrap(); + let second = host.new_list().unwrap(); + let readback = host.new_list().unwrap(); + let mut first_state = State::default(); + let mut second_state = State::default(); + let first_slot = descriptors.cbv_slot(&mut first_state, &first); + second.defer_copy(title_ptr, replacement_ptr, size); + let second_slot = descriptors.cbv_slot(&mut second_state, &second); + assert_ne!(first_slot, second_slot, "separate native table slots"); + + const RESULT_BYTES: u64 = 3 * 8; + let output = resource( + &device, + D3D12_HEAP_TYPE_DEFAULT, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + &buf(RESULT_BYTES, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + ); + let back = resource( + &device, + D3D12_HEAP_TYPE_READBACK, + D3D12_RESOURCE_STATE_COPY_DEST, + &buf(RESULT_BYTES, D3D12_RESOURCE_FLAG_NONE), + ); + + // SAFETY: the pipeline, open lists, output and descriptor ranges all + // remain live across recording and every fenced submission below. + unsafe { + let record = |list: &HostList, table_slot: u32, index: u32| { + list.list.SetDescriptorHeaps(&[Some(heap.heap.clone())]); + list.list.SetComputeRootSignature(&root); + list.list.SetPipelineState(&pipeline); + let data = [table_slot, index]; + list.list + .SetComputeRoot32BitConstants(0, 2, data.as_ptr().cast(), 0); + list.list + .SetComputeRootUnorderedAccessView(1, output.GetGPUVirtualAddress()); + list.list.Dispatch(1, 1, 1); + }; + record(&first, first_slot, 0); + record(&second, second_slot, 1); + // Model sharing by descriptor-record identity while preserving both + // real fills. This control reads list one's snapshot in list two. + record(&second, first_slot, 2); + first.close(); + second.close(); + readback.list.ResourceBarrier(&[crate::host::transition( + &output, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + readback + .list + .CopyBufferRegion(&back, 0, &output, 0, RESULT_BYTES); + readback.list.ResourceBarrier(&[crate::host::transition( + &output, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + readback.close(); + + for (round, a, b) in [ + ("distinct", [101, 102], [201, 202]), + ("equal", [301, 302], [301, 302]), + ("replayed distinct", [401, 402], [501, 502]), + ] { + // Rewrite both sources after recording, including when the very + // same closed lists are submitted again. + title_ptr.cast::().write(Payload::from_pair(a)); + replacement_ptr + .cast::() + .write(Payload::from_pair(b)); + let before = PREPARING[1].load(std::sync::atomic::Ordering::Relaxed); + host.execute(&[&first, &second, &readback]); + let copied = PREPARING[1].load(std::sync::atomic::Ordering::Relaxed) - before; + assert_eq!(copied, (3 * size) as u64); + let mut data = std::ptr::null_mut(); + back.Map(0, None, Some(&mut data)).unwrap(); + let results = std::slice::from_raw_parts(data.cast::<[u32; 2]>(), 3); + assert_eq!(results, &[a, b, a]); + assert_eq!(results[2] == results[1], a == b); + eprintln!( + "{name} {round}: identical CBV records=2 slots=2 fills={} bytes; ordered copy={size} bytes; native={results:?}", + 2 * size + ); + back.Unmap(0, Some(&D3D12_RANGE::default())); + } + device.GetDeviceRemovedReason().unwrap(); + } + check_debug_messages(&info); +} diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index a76b881ab80..09d046e5319 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -781,6 +781,15 @@ impl State { made } + #[cfg(test)] + pub(crate) fn test_compute_tables( + &mut self, + list: &HostList, + used: &[UsedResource], + ) -> Vec<(u8, u32)> { + self.tables(list, used, true) + } + /// The first draws, at debug level: what they bind and read /// (diagnostics builds). #[cfg(feature = "diagnostics")] diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 6672c1ed11a..39f6506ae65 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -117,10 +117,11 @@ pub(crate) fn fail(what: std::fmt::Arguments) -> ! { } } +static HOST: OnceLock> = OnceLock::new(); + /// The host GPU, created on first use; `None` without one (a run then /// behaves as before: nothing executes). pub(crate) fn host() -> Option<&'static Host> { - static HOST: OnceLock> = OnceLock::new(); HOST.get_or_init(|| match create() { Ok(host) => Some(host), Err(e) => { @@ -131,6 +132,17 @@ pub(crate) fn host() -> Option<&'static Host> { .as_ref() } +/// Install a specific adapter before invoking the normal binding path. +/// The fixture runs alone in its test process. +#[cfg(test)] +pub(crate) fn install_test_device(device: ID3D12Device) -> &'static Host { + assert!( + HOST.set(Some(create_host(device, false).unwrap())).is_ok(), + "test device must be installed before the host initializes" + ); + host().unwrap() +} + fn create() -> windows::core::Result { // SAFETY: plain D3D12 object creation with valid descriptions. unsafe { @@ -183,7 +195,13 @@ fn create() -> windows::core::Result { } else { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; } - let device = device.ok_or_else(windows::core::Error::empty)?; + create_host(device.ok_or_else(windows::core::Error::empty)?, debug) + } +} + +fn create_host(device: ID3D12Device, debug: bool) -> windows::core::Result { + // SAFETY: plain D3D12 object creation with valid descriptions. + unsafe { let messages = debug .then(|| device.cast::().ok()) .flatten(); diff --git a/docs/cbv-table-snapshots.md b/docs/cbv-table-snapshots.md new file mode 100644 index 00000000000..151b0b60ed8 --- /dev/null +++ b/docs/cbv-table-snapshots.md @@ -0,0 +1,80 @@ +# Rebuilt constant-buffer table snapshots + +A rebuilt CBV table in #562 binds a native heap offset during recording. +The CBV points to that list's upload scratch. Each submission copies the +title bytes into the scratch when its ordered `Step::Fill` runs. A deferred +title copy can run between the fills for two lists using the same +descriptor record. Resubmitting a closed list also fills its scratch +again. +[PR #562](https://github.com/Marvisak/VIctory/pull/562) + +The descriptor-demand collector can count the repeated record and the +new slots it reserves. It cannot establish that the upload bytes match. +Record-time source contents, equal bytes on a previous submission, and +matching guest address and size also fail to establish that invariant. +The existing table allocation and list-owned uploads are retained. + +## Synthetic validation + +Use the Agility SDK 1.620.x x64 DLL directory and a DXC with Shader Model +6.6 support. Run the ignored test alone because it installs its named +adapter before the normal host initializes. + +```powershell +$env:VICTORY_TABLE_TEST_AGILITY = 'C:\path\to\Agility\build\native\bin\x64' +$env:VICTORY_TABLE_TEST_DXC = 'C:\path\to\dxc.exe' +foreach ($adapter in 'amd', 'nvidia', 'warp') { + $env:VICTORY_TABLE_TEST_ADAPTER = $adapter + cargo test --locked -p victory-gpu --features diagnostics repeated_cbv_records_require_separate_submit_time_snapshots -- --ignored --nocapture + if ($LASTEXITCODE -ne 0) { throw "CBV test failed on $adapter" } +} +``` + +The fixture records two lists using the same title CBV through +`State::tables`. The second list's ordinary deferred copy replaces the +title data before its own fill. An original compute shader reads the +first and last dword of each 256-byte upload. A third dispatch deliberately +uses the first list's native slot in the second list to model sharing by +record identity. The fixture runs three batches using the same closed +recordings. + +| Submission | List one | List two | Forced slot reuse in list two | +| --- | --- | --- | --- | +| Different bytes | 101, 102 | 201, 202 | 101, 102 | +| Equal bytes | 301, 302 | 301, 302 | 301, 302 | +| Different bytes on replay | 401, 402 | 501, 502 | 401, 402 | + +These results matched on AMD Radeon Graphics, NVIDIA GeForce RTX 5070 +Laptop GPU, and WARP with the D3D12 debug layer and GPU-based validation. +Each batch used two dynamic slots and processed 512 bytes of CBV fills +plus the separate 256-byte deferred title copy. These are synthetic +allocation and copy counts. In-game demand and performance remain +unmeasured. + +## Requirements for reuse + +- An immutable snapshot needs an exact byte key or a version issued by + an owner that guarantees immutability, including the native view's + extent and any readable alignment padding. +- Choosing a snapshot using submit-time contents needs a way to resolve + the native slot after the ordered fill. Today the translated stage + receives its heap offset as a recorded root constant. A deferred + binding would need to choose the slot before GPU access while keeping + each native descriptor immutable through the end of its recording + and GPU use. +- #501's scratch probe changes where disjoint list uploads live. Ordered + title fills still need their own versions. #644's generated stage-root + data has a separate producer and binding path. #413's directly indexed + views also use a separate preparation path. + [PR #501](https://github.com/Marvisak/VIctory/pull/501), + [PR #644](https://github.com/Marvisak/VIctory/pull/644), + [PR #413](https://github.com/Marvisak/VIctory/pull/413) +- Both the upload and the descriptor range need suitable ownership for + every referencing recording and submission. A mixed table also needs + the resolved buffer shadow, native descriptor layout and applicable + counter identity. Refresh and writeback registration still belong to + the lists that use those buffers. Placed views need backing and mapping + generation tracking. + +The current rebuilt title CBV path exposes neither a sealed upload +version nor deferred native slot binding. From 9ca05334ededb7ec149609c564e78c712c9d3580 Mon Sep 17 00:00:00 2001 From: asc Date: Tue, 24 Nov 2026 11:39:46 -0500 Subject: [PATCH 3/7] Keep rebuilt CBV tables distinct across ordered title writes --- .../host/reuse_tests/cbv_snapshots.rs | 107 ++++++++++++++---- crates/victory-gpu/src/draw.rs | 22 +++- crates/victory-gpu/src/host.rs | 13 ++- docs/cbv-table-snapshots.md | 9 ++ 4 files changed, 125 insertions(+), 26 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host/reuse_tests/cbv_snapshots.rs b/crates/victory-gpu/src/descriptor/host/reuse_tests/cbv_snapshots.rs index d46aae52a29..930758d4ae7 100644 --- a/crates/victory-gpu/src/descriptor/host/reuse_tests/cbv_snapshots.rs +++ b/crates/victory-gpu/src/descriptor/host/reuse_tests/cbv_snapshots.rs @@ -2,22 +2,29 @@ //! table builder and submission loop supply each list's snapshot. use super::*; -use crate::descriptor::{HEAP_IIDS, HeapDesc, Placement, create_cbv, create_heap, heap, release}; +use crate::descriptor::{ + HEAP_IIDS, HeapDesc, Placement, create_cbv, create_heap, create_placed_srv, heap, release, +}; use crate::draw::State; use crate::host::{HostList, PREPARING, install_test_device}; use crate::object::{S_OK, This}; use victory_shader::{ResourceType, RootType, UsedResource}; const HLSL: &str = r#" -#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), RootConstants(num32BitConstants=2, b0), UAV(u0)" -cbuffer Bindings : register(b0) { uint slot, index; }; +#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), RootConstants(num32BitConstants=3, b0), UAV(u0)" +cbuffer Bindings : register(b0) { uint slot, index, tail; }; RWByteAddressBuffer output : register(u0); struct Values { uint4 rows[16]; }; [RootSignature(RS)] [numthreads(1, 1, 1)] void main() { ConstantBuffer values = ResourceDescriptorHeap[slot]; - output.Store2(index * 8, uint2(values.rows[0].x, values.rows[15].w)); + uint word = 0; + if (tail != 0) { + ByteAddressBuffer input = ResourceDescriptorHeap[slot + tail]; + word = input.Load(0); + } + output.Store3(index * 12, uint3(values.rows[0].x, values.rows[15].w, word)); } "#; @@ -33,16 +40,46 @@ impl Payload { } } -struct TitleHeap(This); +struct PlacedInput(Box); + +impl PlacedInput { + fn new(tail_slot: u64) -> Self { + let input = Self(Box::new(Payload::from_pair([881, 0]))); + let address = input.0.0.as_ptr() as u64; + crate::shadow::register(address as usize, address, 256); + let mut resource = [0; 14]; + resource[0] = 1; + resource[4] = 256; + let mut view = [0; 16]; + view[0] = DXGI_FORMAT_R32_TYPELESS.0 as u32; + view[1] = D3D12_SRV_DIMENSION_BUFFER.0 as u32; + view[2] = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view[6] = 64; + view[8] = D3D12_BUFFER_SRV_FLAG_RAW.0 as u32; + view[10] = address as u32; + view[11] = (address >> 32) as u32; + create_placed_srv(std::ptr::null(), &resource, &view, tail_slot); + input + } +} + +impl Drop for PlacedInput { + fn drop(&mut self) { + let address = self.0.0.as_ptr() as u64; + crate::shadow::unregister(address as usize, address); + } +} + +struct TitleHeap(This, u32); impl TitleHeap { - fn new() -> Self { + fn new(width: u32) -> Self { #[repr(C)] struct Extended(HeapDesc, Placement); let desc = Extended( HeapDesc { kind: 0, - count: 8, + count: width, flags: 1, nodes: 0, }, @@ -56,13 +93,13 @@ impl TitleHeap { create_heap(std::ptr::null(), &desc.0, &HEAP_IIDS[0], &mut object), S_OK ); - Self(object) + Self(object, width) } fn cbv_slot(&self, state: &mut State, list: &HostList) -> u32 { state.set_heaps(&[self.0]); state.set_table(true, 0, heap(self.0).start); - let used = [UsedResource { + let cbv = UsedResource { kind: ResourceType::Cbv, root: RootType::Table, table_offset_dwords: 0, @@ -71,8 +108,15 @@ impl TitleHeap { dwords: 4, user_data: 0, slot: 0, - }]; - let slots = state.test_compute_tables(list, &used); + }; + let srv = UsedResource { + kind: ResourceType::Srv, + table_offset_dwords: (self.1 - 1) * 8, + dwords: 8, + ..cbv + }; + let used = [cbv, srv]; + let slots = state.test_compute_tables(list, &used[..if self.1 == 1 { 1 } else { 2 }]); let [(0, offset)] = slots.as_slice() else { panic!("no rebuilt CBV table") }; @@ -100,7 +144,13 @@ fn repeated_cbv_records_require_separate_submit_time_snapshots() { let mut replacement = Box::new(Payload::from_pair([13, 14])); let title_ptr = (&raw mut title.0).cast::(); let replacement_ptr = (&raw mut replacement.0).cast::(); - let descriptors = TitleHeap::new(); + let width = + std::env::var("VICTORY_CBV_SNAPSHOT_WIDTH").map_or(1, |width| width.parse().unwrap()); + assert!([1, 16, 178, 256].contains(&width)); + let descriptors = TitleHeap::new(width); + let tail = width - 1; + let _input = + (tail != 0).then(|| PlacedInput::new(heap(descriptors.0).start + u64::from(tail) * 32)); let source = title_ptr as u64; create_cbv( std::ptr::null(), @@ -112,6 +162,7 @@ fn repeated_cbv_records_require_separate_submit_time_snapshots() { let first = host.new_list().unwrap(); let second = host.new_list().unwrap(); let readback = host.new_list().unwrap(); + let single = host.new_list().unwrap(); let mut first_state = State::default(); let mut second_state = State::default(); let first_slot = descriptors.cbv_slot(&mut first_state, &first); @@ -119,7 +170,14 @@ fn repeated_cbv_records_require_separate_submit_time_snapshots() { let second_slot = descriptors.cbv_slot(&mut second_state, &second); assert_ne!(first_slot, second_slot, "separate native table slots"); - const RESULT_BYTES: u64 = 3 * 8; + let mut single_state = State::default(); + let early_slot = descriptors.cbv_slot(&mut single_state, &single); + single.defer_copy(title_ptr, replacement_ptr, size); + // Also exercise the ordered callback path without changing title bytes. + single.defer(|| {}); + let late_slot = descriptors.cbv_slot(&mut single_state, &single); + + const RESULT_BYTES: u64 = 5 * 12; let output = resource( &device, D3D12_HEAP_TYPE_DEFAULT, @@ -140,9 +198,9 @@ fn repeated_cbv_records_require_separate_submit_time_snapshots() { list.list.SetDescriptorHeaps(&[Some(heap.heap.clone())]); list.list.SetComputeRootSignature(&root); list.list.SetPipelineState(&pipeline); - let data = [table_slot, index]; + let data = [table_slot, index, tail]; list.list - .SetComputeRoot32BitConstants(0, 2, data.as_ptr().cast(), 0); + .SetComputeRoot32BitConstants(0, 3, data.as_ptr().cast(), 0); list.list .SetComputeRootUnorderedAccessView(1, output.GetGPUVirtualAddress()); list.list.Dispatch(1, 1, 1); @@ -168,6 +226,9 @@ fn repeated_cbv_records_require_separate_submit_time_snapshots() { D3D12_RESOURCE_STATE_UNORDERED_ACCESS, )]); readback.close(); + record(&single, early_slot, 3); + record(&single, late_slot, 4); + single.close(); for (round, a, b) in [ ("distinct", [101, 102], [201, 202]), @@ -183,14 +244,22 @@ fn repeated_cbv_records_require_separate_submit_time_snapshots() { let before = PREPARING[1].load(std::sync::atomic::Ordering::Relaxed); host.execute(&[&first, &second, &readback]); let copied = PREPARING[1].load(std::sync::atomic::Ordering::Relaxed) - before; - assert_eq!(copied, (3 * size) as u64); + if tail == 0 { + assert_eq!(copied, (3 * size) as u64); + } + // Same CBV record, same list, and two different submit-time contents. + title_ptr.cast::().write(Payload::from_pair(a)); + host.execute(&[&single, &readback]); let mut data = std::ptr::null_mut(); back.Map(0, None, Some(&mut data)).unwrap(); - let results = std::slice::from_raw_parts(data.cast::<[u32; 2]>(), 3); - assert_eq!(results, &[a, b, a]); + let results = std::slice::from_raw_parts(data.cast::<[u32; 3]>(), 5); + let raw = if tail == 0 { 0 } else { 881 }; + let expected = [a, b, a, a, b].map(|[lo, hi]| [lo, hi, raw]); + assert_eq!(results, &expected); assert_eq!(results[2] == results[1], a == b); eprintln!( - "{name} {round}: identical CBV records=2 slots=2 fills={} bytes; ordered copy={size} bytes; native={results:?}", + "{name} {round}: width={width} separate same-list versions=2 total reserved slots={} fills={} bytes; ordered copy={size} bytes; native={results:?}", + 4 * width, 2 * size ); back.Unmap(0, Some(&D3D12_RANGE::default())); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 09d046e5319..f39a461b740 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -71,9 +71,8 @@ pub(crate) struct State { /// Graphics, compute. host_roots: [usize; 2], host_heaps: [usize; 2], - /// Tables made afresh in this list: (table, what it holds) → first - /// dynamic slot. - fresh_tables: std::collections::HashMap<(u64, u64), u32>, + /// Rebuilt tables by title address and record hash. + fresh_tables: std::collections::HashMap<(u64, u64), FreshTable>, /// Keep each shared range until this list can no longer be submitted. shared_tables: std::collections::HashMap>, @@ -83,6 +82,12 @@ pub(crate) struct State { table_failed: bool, } +struct FreshTable { + first: u32, + /// None for tables without a CBV. Their descriptors do not depend on a staged upload. + upload_version: Option, +} + /// Draws recorded on the host GPU since the last frame line. static DRAWN: AtomicU64 = AtomicU64::new(0); @@ -726,7 +731,10 @@ impl State { } (table, h.finish()) }; - if let Some(&first) = self.fresh_tables.get(&key) { + if let Some(cached) = self.fresh_tables.get(&key) + && cached.upload_version.is_none_or(|version| version == list.title_write_version()) + { + let first = cached.first; for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) { let handle = table + u64::from(u.table_offset_dwords) * 4; if let Some(view) = crate::descriptor::view(handle) { @@ -746,7 +754,7 @@ impl State { continue; }; let first = range.first; - self.fresh_tables.insert(key, first); + let mut upload_version = None; self.dynamic.push(range); // The whole range: a shader may index past the entries its // used-resource list names (descriptor arrays). @@ -755,6 +763,7 @@ impl State { let used = entries.iter().find(|u| u.table_offset_dwords / 8 == k); match crate::descriptor::view(table + u64::from(k) * 32) { Some(View::Constant(address, size)) => { + upload_version.get_or_insert_with(|| list.title_write_version()); let Some((gpu, to)) = list.scratch(u64::from(size)) else { host.make_null(index); continue; @@ -776,6 +785,9 @@ impl State { } } } + // Older ranges remain owned by the list, whose previous commands + // still refer to those descriptors and upload addresses. + self.fresh_tables.insert(key, FreshTable { first, upload_version }); made.push((slot, first * 32)); } made diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 39f6506ae65..bcd21ce881b 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -414,6 +414,8 @@ enum Step { struct Deferred { /// Destination, source, bytes. copies: Vec, + /// Changes whenever recorded CPU work can write title bytes. + title_write_version: usize, uploads: Vec, /// Host objects the list's commands name (pipelines, root signatures, /// descriptor heaps): the title may release its objects before it @@ -1036,9 +1038,14 @@ impl HostList { deferred .copies .push(Step::Copy(dst as usize, src as usize, len)); + deferred.title_write_version += 1; deferred.refreshed.clear(); } + pub(crate) fn title_write_version(&self) -> usize { + self.deferred().title_write_version + } + /// Copies `len` bytes of title memory at `src` into the list's upload /// memory at `dst` when the list is submitted. pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) { @@ -1164,8 +1171,10 @@ impl HostList { /// Runs `work` when the list is submitted, in order with its copies. /// `work` may write title memory (refreshes after it copy again). pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) { - self.deferred().copies.push(Step::Run(Box::new(work))); - self.deferred().refreshed.clear(); + let mut deferred = self.deferred(); + deferred.copies.push(Step::Run(Box::new(work))); + deferred.title_write_version += 1; + deferred.refreshed.clear(); } /// As [`HostList::defer`], for work that writes only host memory. diff --git a/docs/cbv-table-snapshots.md b/docs/cbv-table-snapshots.md index 151b0b60ed8..5ea3a97f3ee 100644 --- a/docs/cbv-table-snapshots.md +++ b/docs/cbv-table-snapshots.md @@ -78,3 +78,12 @@ unmeasured. The current rebuilt title CBV path exposes neither a sealed upload version nor deferred native slot binding. + + +## Same-list upload versions + +The production table builder also has to distinguish the same CBV record before and after ordered title-memory writes in one recording. The cache now records the title-write version for rebuilt tables that contain a CBV. A new version receives a new descriptor range and staged upload. The list still owns its previous range because already-recorded draws reference it. Tables without CBVs keep their existing cache behavior. + +Set `VICTORY_CBV_SNAPSHOT_WIDTH` to 1, 16, 178, or 256 and run the exact test in a fresh process per width and adapter. Width 1 is CBV-only. The other cases use an original mixed table with the CBV in the first slot and an actual raw placed SRV in the last. The shader checks both CBV words and reads the SRV value (881). The fixture replays the same recordings with different title bytes. The first two lists and the two versions in the single-list case hold four ranges, which occupy 4, 64, 712, or 1,024 slots across the respective widths. + +All 12 adapter and width combinations passed on AMD Radeon Graphics, RTX 5070 Laptop, and WARP with full D3D12 GPU-based validation. The WARP width-178 mutation bypassing the version check reproduced a late result of [101, 102, 881] instead of [201, 202, 881]. This test exercises version correctness. Cross-list mixed-table sharing and the cost at title-scale pressure remain open. From 5adc54b38c2ac16c8b2f972a03c0b22519a73f1e Mon Sep 17 00:00:00 2001 From: asc Date: Wed, 25 Nov 2026 12:29:35 -0500 Subject: [PATCH 4/7] Test descriptor reuse with the system shader compiler --- .../src/descriptor/host/reuse_tests.rs | 56 ++++++++++--------- 1 file changed, 30 insertions(+), 26 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host/reuse_tests.rs b/crates/victory-gpu/src/descriptor/host/reuse_tests.rs index bc6053caf8b..9c94c5a6c94 100644 --- a/crates/victory-gpu/src/descriptor/host/reuse_tests.rs +++ b/crates/victory-gpu/src/descriptor/host/reuse_tests.rs @@ -1,7 +1,6 @@ //! Original 65,536-slot D3D12 allocator and descriptor readback fixture. -//! Set VICTORY_TABLE_TEST_ADAPTER (amd, nvidia or warp), -//! VICTORY_TABLE_TEST_AGILITY (Agility SDK 1.620.x x64 DLL directory) and -//! VICTORY_TABLE_TEST_DXC (dxc.exe path), then run: +//! Set VICTORY_TABLE_TEST_ADAPTER (amd, nvidia or warp) and +//! VICTORY_TABLE_TEST_AGILITY (Agility SDK 1.620.x x64 DLL directory), then run: //! cargo test --release -p victory-gpu --features diagnostics capped_pool_texture_table_reuse -- --ignored --nocapture //! The default run uses GPU-based validation. Set VICTORY_TABLE_TEST_TIMING=1 //! to measure CPU descriptor preparation with validation disabled. @@ -10,17 +9,18 @@ use super::*; use std::mem::ManuallyDrop; use std::time::Instant; use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; use windows::Win32::Graphics::Dxgi::*; -use windows::core::{Interface, PCSTR}; +use windows::core::{Interface, PCSTR, s}; const HLSL: &str = r#" -#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), RootConstants(num32BitConstants=2, b0), UAV(u0)" -cbuffer Constants : register(b0) { uint slot, index; }; +#define RS "RootConstants(num32BitConstants=1, b0), UAV(u0), DescriptorTable(SRV(t0))" +cbuffer Constants : register(b0) { uint index; }; RWByteAddressBuffer output : register(u0); +Texture2D image : register(t0); [RootSignature(RS)] [numthreads(1, 1, 1)] void main() { - Texture2D image = ResourceDescriptorHeap[slot]; output.Store(index * 4, image.Load(int3(0, 0, 0))); } "#; @@ -84,22 +84,26 @@ fn device(validate: bool) -> (ID3D12Device, String) { } fn shader(hlsl: &str) -> Vec { - let dir = tempfile::tempdir().unwrap(); - let source = dir.path().join("table.hlsl"); - let binary = dir.path().join("table.dxil"); - std::fs::write(&source, hlsl).unwrap(); - let result = std::process::Command::new(std::env::var_os("VICTORY_TABLE_TEST_DXC").unwrap()) - .args(["-E", "main", "-T", "cs_6_6", "-Fo"]) - .arg(&binary) - .arg(&source) - .output() - .unwrap(); - assert!( - result.status.success(), - "{}", - String::from_utf8_lossy(&result.stderr) - ); - std::fs::read(binary).unwrap() + let mut code = None; + // SAFETY: the source and names live for the call, and the output blob is ours. + unsafe { + D3DCompile( + hlsl.as_ptr().cast(), + hlsl.len(), + s!("descriptor reuse fixture"), + None, + None, + s!("main"), + s!("cs_5_1"), + 0, + 0, + &mut code, + None, + ) + .expect("compile descriptor reuse fixture"); + let code = code.unwrap(); + std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()).to_vec() + } } fn compute_pipeline( @@ -475,9 +479,9 @@ fn run(fixture: &Fixture, shared: bool, lists: usize, distinct: bool) -> ResultR list.SetDescriptorHeaps(&[Some(heap.heap.clone())]); list.SetComputeRootSignature(&fixture.root); list.SetPipelineState(&fixture.pso); - let values = [slot + position, index as u32]; - list.SetComputeRoot32BitConstants(0, 2, values.as_ptr().cast(), 0); + list.SetComputeRoot32BitConstant(0, index as u32, 0); list.SetComputeRootUnorderedAccessView(1, output.GetGPUVirtualAddress()); + list.SetComputeRootDescriptorTable(2, heap.gpu(slot + position)); list.Dispatch(1, 1, 1); expected[index] = if rewritten { SECOND } else { FIRST }; work.push(list.clone()); @@ -528,7 +532,7 @@ fn run(fixture: &Fixture, shared: bool, lists: usize, distinct: bool) -> ResultR } #[test] -#[ignore = "requires a named D3D12 adapter, DXC and Agility SDK 1.620.x"] +#[ignore = "requires a named D3D12 adapter, Windows Graphics Tools and Agility SDK 1.620.x"] fn capped_pool_texture_table_reuse() { let timing = std::env::var_os("VICTORY_TABLE_TEST_TIMING").is_some(); let (device, name) = device(!timing); From 689dc4529cef67ae5a17b7f11bd381f59147f79a Mon Sep 17 00:00:00 2001 From: asc Date: Wed, 25 Nov 2026 14:39:36 -0500 Subject: [PATCH 5/7] GPU: resolve shared texture tables outside the view registry lock Snapshot descriptor generations and take non-resurrecting title resource references. Release the registry before descriptor creation, state changes or uploads. Keep the references live through preparation, and drop them after releasing the registry even on a rejected table. --- crates/victory-gpu/src/descriptor.rs | 100 ++++++++++++++++++++++++--- crates/victory-gpu/src/object.rs | 11 +++ crates/victory-gpu/src/resource.rs | 2 +- 3 files changed, 102 insertions(+), 11 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index b04f852f6d0..d75a74eb7f7 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -103,8 +103,8 @@ impl Heap { .as_ref() } - /// Resolve a capped table's populated texture SRVs while their title - /// descriptor generations are live. Other tables use normal allocation. + /// Resolve a capped table from an owned snapshot of its title views. + /// No driver calls or recording work run under the view registry lock. #[cfg(windows)] pub(crate) fn with_texture_table( &self, @@ -112,6 +112,24 @@ impl Heap { count: u32, f: impl FnOnce(&[TextureView<'_>]) -> R, ) -> Option { + let records = self.texture_table_records(table, count)?; + let mut entries = Vec::with_capacity(records.len()); + for record in &records { + let View::Shader(resource, Some(desc)) = &record.view else { unreachable!() }; + let (resource, desc) = host::texture_srv(*resource as This, desc)?; + entries.push(TextureView { + slot: record.slot, + record: record.generation, + view: &record.view, + resource, + desc, + }); + } + Some(f(&entries)) + } + + #[cfg(windows)] + fn texture_table_records(&self, table: u64, count: u32) -> Option> { if self.desc.kind != VIEWS_KIND || count == 0 || count > host::DYNAMIC { return None; } @@ -120,8 +138,10 @@ impl Heap { } self.index(table.checked_add(u64::from(count - 1) * 32)?)?; + // Resource release can invalidate registry entries, so the pins + // must always be dropped after the lock, including on failure. + let mut records = Vec::new(); let registry = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); - let mut entries = Vec::new(); for slot in 0..count { let at = table + u64::from(slot) * 32; // SAFETY: the checked span lies in the title descriptor heap. @@ -133,17 +153,22 @@ impl Heap { if tag != VIEW_TAG || *current != generation { return None; } - let View::Shader(resource, Some(desc)) = view else { return None }; - let (resource, desc) = host::texture_srv(*resource as This, desc)?; - entries.push(TextureView { + let View::Shader(resource, Some(_)) = view else { return None }; + let resource = *resource as This; + // SAFETY: destruction invalidates the descriptor under VIEWS + // before freeing the resource. Do not retain a zero count. + if resource.is_null() || !unsafe { object::try_add_ref(resource) } { + return None; + } + records.push(TextureRecord { slot, - record: u64::from(generation) << 32 | u64::from(id), - view, + generation: u64::from(generation) << 32 | u64::from(id), + view: view.clone(), resource, - desc, }); } - (!entries.is_empty()).then(|| f(&entries)) + drop(registry); + (!records.is_empty()).then_some(records) } /// The descriptor index of `handle` in this heap, if it lies in it. @@ -491,6 +516,22 @@ static VIEWS: std::sync::Mutex = std::sync::Mutex::new(Views { }); const VIEW_TAG: u32 = u32::from_le_bytes(*b"vVIE"); +/// One descriptor generation and a temporary reference to its resource. +#[cfg(windows)] +struct TextureRecord { + slot: u32, + generation: u64, + view: View, + resource: This, +} + +#[cfg(windows)] +impl Drop for TextureRecord { + fn drop(&mut self) { + crate::resource::resource_release(self.resource); + } +} + /// A texture SRV resolved from a live title view generation. #[cfg(windows)] pub(crate) struct TextureView<'a> { @@ -928,6 +969,45 @@ pub(crate) mod tests { assert_eq!(release(title_heap), 0); } + #[cfg(windows)] + #[test] + fn texture_table_snapshot_holds_the_resource_after_replacement() { + let null = std::ptr::null(); + let mut title_heap = null; + let desc = HeapDesc { kind: VIEWS_KIND, count: 2, flags: SHADER_VISIBLE, nodes: 0 }; + let placed = Placement { address: 0, size: 0 }; + assert_eq!(create(desc, placed, &mut title_heap), S_OK); + let heap = heap(title_heap); + let start = heap.start; + + let buffer_desc = [1u32, 0, 0, 0, 64, 0, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0]; + let properties = [1u32, 0, 0, 0, 0]; + let iid = guid(0x696442be, 0xa72e, 0x4059, [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad]); + let mut resource = null; + assert_eq!(crate::resource::create_committed( + null, properties.as_ptr().cast(), 0, buffer_desc.as_ptr().cast(), + 0, null.cast(), &iid, &mut resource, + ), S_OK); + let original = View::Shader(resource as usize, Some([0; 10])); + record(start, original.clone()); + create_cbv(null, &[0x1000, 1, 256, 0], start + 32); + assert!(heap.texture_table_records(start, 2).is_none()); + assert_eq!(object::refs(resource), 1); + record(start + 32, original.clone()); + let snapshot = heap.texture_table_records(start, 1).unwrap(); + let release_resource = slot:: u32>(resource, 0x10); + assert_eq!(release_resource(resource), 1); + // Replacing a title slot while resolving the snapshot takes the + // registry lock again and leaves the captured generation intact. + create_cbv(null, &[0x1000, 1, 256, 0], start); + assert_eq!(snapshot[0].view, original); + assert_eq!(view(start + 32), Some(original)); + assert!(crate::resource::buffer_bytes(resource).is_some()); + drop(snapshot); + assert_eq!(view(start + 32), None); + assert_eq!(release(title_heap), 0); + } + #[test] fn views_survive_copies() { let null = std::ptr::null(); diff --git a/crates/victory-gpu/src/object.rs b/crates/victory-gpu/src/object.rs index 2df92a7413b..8a4a073c456 100644 --- a/crates/victory-gpu/src/object.rs +++ b/crates/victory-gpu/src/object.rs @@ -71,6 +71,17 @@ pub(crate) extern "system" fn add_ref(this: This) -> u32 { unsafe { &*this }.refs.fetch_add(1, Ordering::Relaxed) + 1 } +/// Takes a reference without resurrecting an object already being destroyed. +/// The caller keeps its allocation alive while attempting the increment. +#[cfg(windows)] +pub(crate) unsafe fn try_add_ref(this: This) -> bool { + // SAFETY: the caller keeps the object header allocated for this call. + let refs = &unsafe { &*this }.refs; + refs.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| { + if n == 0 { None } else { n.checked_add(1) } + }).is_ok() +} + /// An object's reference count. pub(crate) fn refs(this: This) -> u32 { // SAFETY: `this` is one of our objects. diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 25b3444a7bf..5d0715645b8 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -2138,7 +2138,7 @@ extern "system" fn resource_query(this: This, iid: *const Iid, out: *mut This) - out, ) } -extern "system" fn resource_release(this: This) -> u32 { +pub(crate) extern "system" fn resource_release(this: This) -> u32 { object::release_boxed::(this) } /// Memory is always mapped (subresources are not told apart yet); a null From 134dde05d592c73e2ce83e792ae62a9a8441d68f Mon Sep 17 00:00:00 2001 From: asc Date: Wed, 25 Nov 2026 14:39:36 -0500 Subject: [PATCH 6/7] Test capped descriptor reuse on the system D3D12 runtime --- .../src/descriptor/host/reuse_tests.rs | 58 +++++++++---------- 1 file changed, 27 insertions(+), 31 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host/reuse_tests.rs b/crates/victory-gpu/src/descriptor/host/reuse_tests.rs index 9c94c5a6c94..1848fd541dc 100644 --- a/crates/victory-gpu/src/descriptor/host/reuse_tests.rs +++ b/crates/victory-gpu/src/descriptor/host/reuse_tests.rs @@ -1,17 +1,17 @@ //! Original 65,536-slot D3D12 allocator and descriptor readback fixture. -//! Set VICTORY_TABLE_TEST_ADAPTER (amd, nvidia or warp) and -//! VICTORY_TABLE_TEST_AGILITY (Agility SDK 1.620.x x64 DLL directory), then run: +//! Set VICTORY_TABLE_TEST_ADAPTER (amd, nvidia or warp), then run: //! cargo test --release -p victory-gpu --features diagnostics capped_pool_texture_table_reuse -- --ignored --nocapture -//! The default run uses GPU-based validation. Set VICTORY_TABLE_TEST_TIMING=1 -//! to measure CPU descriptor preparation with validation disabled. +//! Set VICTORY_TABLE_TEST_DEBUG=1 for the system D3D12 debug layer or +//! VICTORY_TABLE_TEST_GBV=1 for GPU-based validation, where supported. +//! VICTORY_TABLE_TEST_TIMING=1 runs five alternating timing samples. use super::*; use std::mem::ManuallyDrop; use std::time::Instant; -use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; +use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; use windows::Win32::Graphics::Dxgi::*; -use windows::core::{Interface, PCSTR, s}; +use windows::core::{Interface, s}; const HLSL: &str = r#" #define RS "RootConstants(num32BitConstants=1, b0), UAV(u0), DescriptorTable(SRV(t0))" @@ -28,27 +28,21 @@ const FIRST: u32 = 0x1458_acef; const SECOND: u32 = 0xfec1_4921; const SPAN: u32 = 2048; -fn device(validate: bool) -> (ID3D12Device, String) { - let sdk = std::env::var("VICTORY_TABLE_TEST_AGILITY").expect("Agility SDK 1.620.x x64 path"); - let sdk = std::ffi::CString::new(format!("{}\\", sdk.trim_end_matches(['/', '\\']))).unwrap(); +fn device(debug: bool, gbv: bool) -> (ID3D12Device, String) { let vendor = std::env::var("VICTORY_TABLE_TEST_ADAPTER").expect("amd, nvidia or warp"); - // SAFETY: the configuration, adapter enumeration and output pointers are ours. + // SAFETY: the debug interface, adapter enumeration and output pointers are ours. unsafe { - let mut configuration: Option = None; - D3D12GetInterface(&CLSID_D3D12SDKConfiguration, &mut configuration).unwrap(); - let factory: ID3D12DeviceFactory = configuration - .unwrap() - .CreateDeviceFactory(620, PCSTR(sdk.as_ptr().cast())) - .unwrap(); - if validate { - let debug: ID3D12Debug = factory - .GetConfigurationInterface(&CLSID_D3D12Debug) - .unwrap(); + if debug { + let mut debug: Option = None; + D3D12GetDebugInterface(&mut debug).expect("install Windows Graphics Tools for the D3D12 debug layer"); + let debug = debug.unwrap(); debug.EnableDebugLayer(); - debug - .cast::() - .unwrap() - .SetEnableGPUBasedValidation(true); + if gbv { + debug + .cast::() + .unwrap() + .SetEnableGPUBasedValidation(true); + } } let dxgi: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap(); let adapter: IDXGIAdapter1 = if vendor == "warp" { @@ -76,9 +70,7 @@ fn device(validate: bool) -> (ID3D12Device, String) { desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 ); let mut device = None; - factory - .CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device) - .unwrap(); + D3D12CreateDevice(&adapter.cast::().unwrap(), D3D_FEATURE_LEVEL_11_0, &mut device).unwrap(); (device.unwrap(), name) } } @@ -532,11 +524,13 @@ fn run(fixture: &Fixture, shared: bool, lists: usize, distinct: bool) -> ResultR } #[test] -#[ignore = "requires a named D3D12 adapter, Windows Graphics Tools and Agility SDK 1.620.x"] +#[ignore = "requires a named D3D12 adapter"] fn capped_pool_texture_table_reuse() { let timing = std::env::var_os("VICTORY_TABLE_TEST_TIMING").is_some(); - let (device, name) = device(!timing); - let info = (!timing).then(|| device.cast::().unwrap()); + let gbv = !timing && std::env::var_os("VICTORY_TABLE_TEST_GBV").is_some(); + let debug = gbv || !timing && std::env::var_os("VICTORY_TABLE_TEST_DEBUG").is_some(); + let (device, name) = device(debug, gbv); + let info = debug.then(|| device.cast::().unwrap()); let fixture = Fixture::new(device); for (label, count, distinct) in [ ("over-cap", 41, false), @@ -581,8 +575,10 @@ fn capped_pool_texture_table_reuse() { ); } } - if let Some(info) = info { + if !timing { heap_replacement(&fixture); + } + if let Some(info) = info { check_debug_messages(&info); } } From db0c7e5bbaf0086f659a2828f576c62234115f34 Mon Sep 17 00:00:00 2001 From: asc Date: Wed, 25 Nov 2026 17:05:31 -0500 Subject: [PATCH 7/7] GPU: preserve view metadata in shared texture tables --- crates/victory-gpu/src/descriptor/host.rs | 17 ++++++-- .../src/descriptor/host/reuse_tests.rs | 41 +++++++++++++++++++ 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index f1cb7807bbf..ada6381ec43 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -64,6 +64,8 @@ pub(crate) struct HostHeap { #[derive(Clone, Hash, PartialEq, Eq)] struct TextureTableKey { count: u32, + /// A table made before the optional address buffer existed has no entries there. + addresses: bool, /// Occupied offsets, title view generations and native resource identities. views: Vec<(u32, u64, usize)>, } @@ -503,6 +505,7 @@ impl HostHeap { let key = TextureTableKey { count, + addresses: self.addresses.get().is_some_and(Option::is_some), views: views.iter().map(|v| (v.slot, v.record, v.resource.as_raw() as usize)).collect(), }; let mut tables = self.slots.shared.lock().unwrap_or_else(|e| e.into_inner()); @@ -514,19 +517,25 @@ impl HostHeap { let mut populated = views.iter().peekable(); for slot in 0..count { let index = first + slot; - if populated.peek().is_some_and(|v| v.slot == slot) { + let view = if populated.peek().is_some_and(|v| v.slot == slot) { let view = populated.next().unwrap(); // SAFETY: the resolved resource is live and this slot belongs to the new allocation. unsafe { device.CreateShaderResourceView(&view.resource, Some(&view.desc), self.cpu(index)); } + Some(view.view) } else { null_view_on(device, self.cpu(index)); - } - // Previous occupants can include buffer views. Clear their old - // owners and shader-visible stride, even for holes in this table. + None + }; + // Earlier occupants' buffer metadata must not outlive the + // descriptors, including in the holes of a fresh table. self.keep(index, None); self.set_stride(index, None); + self.set_mark(index, None); + if key.addresses { + self.note_address(index, view); + } } let table = Arc::new(SharedTextureTable { key: key.clone(), diff --git a/crates/victory-gpu/src/descriptor/host/reuse_tests.rs b/crates/victory-gpu/src/descriptor/host/reuse_tests.rs index 1848fd541dc..7dbbccf3e0f 100644 --- a/crates/victory-gpu/src/descriptor/host/reuse_tests.rs +++ b/crates/victory-gpu/src/descriptor/host/reuse_tests.rs @@ -347,6 +347,46 @@ fn occupancy(heap: &HostHeap) -> usize { .count() } +fn shared_table_metadata(fixture: &Fixture) { + let device = &fixture.device; + let heap = capped_heap(device); + let mut title_texture = [0; 14]; + (title_texture[0], title_texture[4], title_texture[6], title_texture[7], title_texture[9]) = + (3, 128, 64, 1 | 1 << 16, 1); + let mut title_view = [0; 16]; + title_view[1] = D3D12_SRV_DIMENSION_TEXTURE2D.0 as u32; + title_view[5] = 1; + let view = View::Placed(false, title_texture, title_view); + let views = [TextureView { + slot: 0, + record: 1 << 32, + view: &view, + resource: fixture.textures[0].clone(), + desc: descriptor(), + }]; + let old = heap.shared_textures_on(device, 2, &views).unwrap(); + let bytes = u64::from(heap.address_slots()) * 16; + let addresses = resource( + device, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, + &buf(bytes, D3D12_RESOURCE_FLAG_NONE), + ); + let mut mapped = std::ptr::null_mut(); + // SAFETY: a live upload buffer with one four-dword entry per slot. + let (data, gpu) = unsafe { + addresses.Map(0, None, Some(&mut mapped)).unwrap(); + std::ptr::write_bytes(mapped.cast::(), 0xab, bytes as usize); + (mapped as *const [u32; 4], addresses.GetGPUVirtualAddress()) + }; + assert!(heap.addresses.set(Some((addresses, data as usize, gpu))).is_ok()); + let new = heap.shared_textures_on(device, 2, &views).unwrap(); + assert_ne!(new.first(), old.first()); + // SAFETY: both slots are inside the retained address buffer. + let words = unsafe { [data.add(new.first() as usize).read(), data.add(new.first() as usize + 1).read()] }; + assert_eq!(words, [texture_words(&view).unwrap(), [0; 4]]); + let replay = heap.shared_textures_on(device, 2, &views).unwrap(); + assert!(Arc::ptr_eq(&new, &replay)); +} + fn heap_replacement(fixture: &Fixture) { let view = View::Shader(0, None); let views = [TextureView { @@ -577,6 +617,7 @@ fn capped_pool_texture_table_reuse() { } if !timing { heap_replacement(&fixture); + shared_table_metadata(&fixture); } if let Some(info) = info { check_debug_messages(&info);