diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 1057d564238..0599ef25d99 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -106,6 +106,74 @@ impl Heap { .as_ref() } + /// 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, + table: u64, + 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; + } + if !(table.checked_sub(self.start)?).is_multiple_of(32) { + return None; + } + 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()); + for slot in 0..count { + let at = table + u64::from(slot) * 32; + // SAFETY: the checked span lies in the title descriptor 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 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, + generation: u64::from(generation) << 32 | u64::from(id), + view: view.clone(), + resource, + }); + } + drop(registry); + (!records.is_empty()).then_some(records) + } + /// 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)?); @@ -276,19 +344,6 @@ pub(crate) fn evict(textures: &std::collections::HashSet) { } } -/// 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); - } -} - /// Runs `f` on the host heap behind the title heap at `heap` while that /// heap cannot be released; None if it is gone or has no host heap. #[cfg(windows)] @@ -469,6 +524,32 @@ 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> { + pub(crate) slot: u32, + record: u64, + pub(crate) view: &'a View, + resource: windows::Win32::Graphics::Direct3D12::ID3D12Resource, + desc: windows::Win32::Graphics::Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC, +} + impl View { /// The resource objects the view names. fn resources(&self) -> [usize; 2] { @@ -913,6 +994,65 @@ pub(crate) mod tests { assert_eq!(create(bad, none, &mut h), E_INVALIDARG); } + #[cfg(windows)] + #[test] + fn texture_table_rejects_non_texture_records_and_invalid_spans() { + let mut title_heap = std::ptr::null(); + let desc = HeapDesc { kind: VIEWS_KIND, count: 4, 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; + create_cbv(std::ptr::null(), &[0x1000, 1, 256, 0], start + 32); + fn reject(_: &[TextureView<'_>]) { + panic!("ineligible table was passed to the cache"); + } + assert_eq!(heap.with_texture_table(start, 4, reject), None); + assert_eq!(heap.with_texture_table(start + 1, 1, reject), None); + assert_eq!(heap.with_texture_table(start + 96, 2, reject), None); + assert_eq!(heap.with_texture_table(start + 64, 2, reject), None); + 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/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 74e4bf550cc..ada6381ec43 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -5,12 +5,14 @@ //! 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::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, Weak}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; -use super::{VIEW_TAG, View, view_at, views_current}; +use super::{TextureView, VIEW_TAG, View, view_at, views_current}; use crate::host::host; pub(crate) struct HostHeap { @@ -31,9 +33,7 @@ pub(crate) struct HostHeap { /// read there is a GPU page fault (the console reads stale memory). /// With it the view's own copy of title memory, if it has one. kept: Mutex>, - /// Where the search for free dynamic slots starts, and which are taken - /// (by lists not yet reset). - next: Mutex<(u32, Vec)>, + slots: Arc, /// Slot pairs kept for host copies' views (`crate::memory`), past the /// dynamic slots and below the null buffer views: the next never /// taken, those given back, and where they end. @@ -61,6 +61,84 @@ pub(crate) struct HostHeap { pub(crate) viewed: std::sync::Arc, } +#[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)>, +} + +static NEXT_HEAP_ID: AtomicUsize = AtomicUsize::new(1); + +struct DynamicSlots { + id: usize, + first: u32, + /// Cursor and occupancy held by recorded lists. + next: Mutex<(u32, Vec)>, + shared: Mutex>>, +} + +impl DynamicSlots { + fn new(first: u32, count: u32) -> Self { + Self { + id: NEXT_HEAP_ID.fetch_add(1, Ordering::Relaxed), + first, + next: Mutex::new((0, vec![false; count as usize])), + shared: Mutex::default(), + } + } + + fn release(&self, first: u32, count: 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 + count).min(guard.1.len() as u32) as usize; + if let Some(slots) = guard.1.get_mut(at as usize..end) { + slots.fill(false); + } + } +} + +/// Slots reserved on a particular native heap generation. +pub(crate) struct DynamicRange { + pub(crate) first: u32, + count: u32, + slots: Arc, +} + +impl Drop for DynamicRange { + fn drop(&mut self) { + self.slots.release(self.first, self.count); + } +} + +/// A shared allocation tied to one native heap and retained by every +/// recording that may replay it. Cache entries cannot keep the slots alive. +pub(crate) struct SharedTextureTable { + key: TextureTableKey, + range: DynamicRange, + _heap: ID3D12DescriptorHeap, + _resources: Vec, +} + +impl SharedTextureTable { + pub(crate) fn first(&self) -> u32 { + self.range.first + } +} + +impl Drop for SharedTextureTable { + fn drop(&mut self) { + let mut tables = self.range.slots.shared.lock().unwrap_or_else(|e| e.into_inner()); + 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 /// device-removed reports: a shader indexing a heap past its end faults. static GPU_RANGES: Mutex> = Mutex::new(Vec::new()); @@ -93,7 +171,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. @@ -196,7 +274,7 @@ impl HostHeap { 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])), + slots: Arc::new(DynamicSlots::new(count, extra)), pairs: Mutex::new((count + extra, Vec::new())), pairs_end: match victory_shader::emit::NULL_BUFFER_VIEW { null if !sampler && null > count + extra && null < total => null - 1, @@ -316,7 +394,7 @@ impl HostHeap { if self.sampler || n == 0 || n > self.dynamic { return None; } - let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); + let mut guard = self.slots.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 (extending past cursor by @@ -350,6 +428,20 @@ impl HostHeap { Some(self.count + first as u32) } + /// The generation of this native heap, even if title heap addresses repeat. + pub(crate) fn identity(&self) -> usize { + self.slots.id + } + + /// An allocation given back only to the pool that owns it. + pub(crate) fn reserve_dynamic(&self, count: u32) -> Option { + Some(DynamicRange { + first: self.dynamic(count)?, + count, + slots: self.slots.clone(), + }) + } + /// Two consecutive slots (view heaps only) kept until /// [`HostHeap::free_pair`]: past the dynamic slots where the heap has /// room (a host copy's views, `crate::memory`, for as long as it @@ -391,14 +483,68 @@ impl HostHeap { /// /// [`dynamic`]: HostHeap::dynamic pub(crate) fn release(&self, first: u32, n: u32) { - let Some(at) = first.checked_sub(self.count) else { - return; + self.slots.release(first, n); + } + + /// Share a fully resolved range of texture SRVs on the native heap. + pub(crate) fn shared_textures( + &self, + count: u32, + views: &[TextureView<'_>], + ) -> Option> { + self.shared_textures_on(&host()?.device, count, views) + } + + fn shared_textures_on( + &self, + device: &ID3D12Device, + count: u32, + views: &[TextureView<'_>], + ) -> Option> { + use windows::core::Interface; + + 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 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.slots.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 populated = views.iter().peekable(); + for slot in 0..count { + let index = first + 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)); + 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(), + range, + _heap: self.heap.clone(), + _resources: views.iter().map(|v| v.resource.clone()).collect(), + }); + tables.insert(key, Arc::downgrade(&table)); + Some(table) } /// Makes slot `index` (a dynamic one) from `view`; a null view if the @@ -1462,6 +1608,22 @@ pub(crate) fn make_view(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option< make(view, at).flatten().map(|k| k.0) } +/// Resolve an explicit texture SRV using the same format rules as its +/// ordinary mirror. The capped-table cache excludes all other view kinds. +pub(super) fn texture_srv( + resource: crate::object::This, + words: &[u32; 10], +) -> Option<(ID3D12Resource, D3D12_SHADER_RESOURCE_VIEW_DESC)> { + let copy = crate::resource::fixed_table_texture(resource)?; + let mut desc = srv_desc(words); + if desc.ViewDimension == D3D12_SRV_DIMENSION_BUFFER + || !fits(©.texture, ©.castable, Some(&mut desc.Format), false) + { + return None; + } + Some((copy.texture.clone(), desc)) +} + /// 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 { @@ -1802,7 +1964,12 @@ fn null_like(words: &[u32; 10], at: D3D12_CPU_DESCRIPTOR_HANDLE) { /// 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 }; + if let Some(host) = host() { + null_view_on(&host.device, at); + } +} + +fn null_view_on(device: &ID3D12Device, at: D3D12_CPU_DESCRIPTOR_HANDLE) { let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT_R8G8B8A8_UNORM, ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, @@ -1816,11 +1983,13 @@ 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) + device.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at) }; } +#[cfg(test)] +mod reuse_tests; + #[cfg(test)] mod tests { use super::*; 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..7dbbccf3e0f --- /dev/null +++ b/crates/victory-gpu/src/descriptor/host/reuse_tests.rs @@ -0,0 +1,647 @@ +//! Original 65,536-slot D3D12 allocator and descriptor readback fixture. +//! 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 +//! 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_11_0; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Dxgi::*; +use windows::core::{Interface, s}; + +const HLSL: &str = r#" +#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() { + 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(debug: bool, gbv: bool) -> (ID3D12Device, String) { + let vendor = std::env::var("VICTORY_TABLE_TEST_ADAPTER").expect("amd, nvidia or warp"); + // SAFETY: the debug interface, adapter enumeration and output pointers are ours. + unsafe { + 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(); + if gbv { + 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; + D3D12CreateDevice(&adapter.cast::().unwrap(), D3D_FEATURE_LEVEL_11_0, &mut device).unwrap(); + (device.unwrap(), name) + } +} + +fn shader(hlsl: &str) -> Vec { + 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( + 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, + 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(HLSL); + let (root, pso) = compute_pipeline(&device, &code); + 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 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 capped_heap(device: &ID3D12Device) -> HostHeap { + let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + let total = 1 + MIN_DYNAMIC; + // SAFETY: a plain shader-visible heap on the fixture's own device. + let (heap, cpu, step) = unsafe { + let heap: ID3D12DescriptorHeap = device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: total, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .unwrap(); + let cpu = heap.GetCPUDescriptorHandleForHeapStart().ptr; + let step = device.GetDescriptorHandleIncrementSize(kind); + (heap, cpu, step) + }; + HostHeap { + heap, + cpu, + step, + count: 1, + dynamic: MIN_DYNAMIC, + sampler: false, + marks: None, + made: Mutex::new(vec![0]), + kept: Mutex::new(vec![None; total as usize]), + slots: Arc::new(DynamicSlots::new(1, MIN_DYNAMIC)), + pairs: Mutex::new((total, Vec::new())), + pairs_end: total, + strides: None, + addresses: Default::default(), + viewed: Default::default(), + } +} + +fn descriptor() -> D3D12_SHADER_RESOURCE_VIEW_DESC { + D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MipLevels: 1, + ..Default::default() + }, + }, + } +} + +fn occupancy(heap: &HostHeap) -> usize { + heap.slots + .next + .lock() + .unwrap() + .1 + .iter() + .filter(|&&used| used) + .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 { + slot: 0, + record: 1 << 32, + view: &view, + resource: fixture.textures[0].clone(), + desc: descriptor(), + }]; + let original = capped_heap(&fixture.device); + let original_pool = Arc::downgrade(&original.slots); + let original_table = original + .shared_textures_on(&fixture.device, SPAN, &views) + .unwrap(); + let list_local = original.reserve_dynamic(SPAN).unwrap(); + let original_id = original.identity(); + drop(original); + + let replacement = capped_heap(&fixture.device); + let replacement_table = replacement + .shared_textures_on(&fixture.device, SPAN, &views) + .unwrap(); + assert_ne!(original_id, replacement.identity()); + 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 = capped_heap(device); + 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.clone(), + desc: descriptor(), + }]; + let started = Instant::now(); + let slot = if shared { + heap.shared_textures_on(device, 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 { + device.CreateShaderResourceView( + texture, + Some(&views[0].desc), + heap.cpu(slot), + ); + heap.keep(slot, Some((texture.clone(), None))); + } else { + null_view_on(device, heap.cpu(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); + 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()); + } 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.ResourceBarrier(&[crate::host::transition( + &output, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COMMON, + )]); + end.Close().unwrap(); + work.push(end); + for _ in 0..2 { + 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.slots.shared.lock().unwrap().is_empty()); + } + ResultRow { + failed: failures, + occupied, + preparing, + } +} + +#[test] +#[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 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), + ("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 !timing { + heap_replacement(&fixture); + shared_table_metadata(&fixture); + } + if let Some(info) = info { + 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/draw.rs b/crates/victory-gpu/src/draw.rs index 9c1216cc571..c64fe6adb51 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -71,12 +71,14 @@ 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>, - /// The dynamic slots the list holds: title heap, first, count; given - /// back when the list is reset or released. - dynamic: Vec<(usize, u32, u32)>, + /// (native heap generation, title table, record hash) to dynamic slot. + fresh_tables: std::collections::HashMap<(usize, u64, u64), u32>, + /// Keep shared ranges while this recording can execute or replay. + /// Submissions finish before the title can reset the recording. + shared_tables: + std::collections::HashMap>, + /// List-local reservations released on reset or release. + dynamic: Vec, /// A fresh table of the stage being bound could not be made. table_failed: bool, /// The title-memory page table made for this list (`crate::memory`) @@ -106,17 +108,6 @@ struct Fixed { topology: bool, } -impl Drop for State { - fn drop(&mut self) { - for &(heap, first, n) in &self.dynamic { - match (heap, crate::memory::heap()) { - (MEMORY_HEAP, Some(ours)) => ours.release(first, n), - _ => crate::descriptor::release_dynamic(heap, first, n), - } - } - } -} - /// The key of our own view heap (`crate::memory::heap`) among the title's. const MEMORY_HEAP: usize = crate::memory::OURS; @@ -924,29 +915,28 @@ impl State { let len = if shadow.marked() { shadow.left(address) } else { shadow.left(address).min(1 << 20) }; shadow.gpu_writes(list, address, len, true); } - let (key, host) = match self.heaps[0] { - 0 => (MEMORY_HEAP, crate::memory::heap()), - h => ( - std::ptr::from_ref(crate::descriptor::heap(h as This)) as usize, - crate::descriptor::heap(h as This).host(), - ), + let host = match self.heaps[0] { + 0 => crate::memory::heap(), + h => crate::descriptor::heap(h as This).host(), }; let Some(host) = host else { not_run("a root view without a host view heap"); return None; }; + let key = host.identity(); let copy = std::sync::Arc::as_ptr(&shadow) as usize; if let Some(&index) = self.root_slots.get(&(key, copy, uav)) { return Some((index, offset)); } let (run_heap, next, end) = self.root_run; if run_heap != key || next >= end { - let Some(first) = host.dynamic(ROOT_VIEW_RUN) else { + let Some(range) = host.reserve_dynamic(ROOT_VIEW_RUN) else { once!("no dynamic slots for root views: dropped"); not_run("no dynamic slots for root views"); return None; }; - self.dynamic.push((key, first, ROOT_VIEW_RUN)); + let first = range.first; + self.dynamic.push(range); self.root_run = (key, first, first + ROOT_VIEW_RUN); } let index = self.root_run.1; @@ -1033,11 +1023,11 @@ impl State { return; }; let Some(visible) = heap.host() else { return }; - let Some(slot) = visible.dynamic(1) else { + let Some(range) = visible.reserve_dynamic(1) else { return; }; - self.dynamic - .push((std::ptr::from_ref(heap) as usize, slot, 1)); + let slot = range.first; + self.dynamic.push(range); visible.make_at(slot, &view); let at = host.cpu_view(); let Some(resource) = crate::descriptor::host::make_view(&view, at) else { @@ -1284,6 +1274,25 @@ impl State { .map(|u| u.table_offset_dwords / 8 + 1) .max() .unwrap_or(1); + if entries.iter().all(|u| u.kind == ResourceType::Srv) + && 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, true); + } + } + 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}; @@ -1293,7 +1302,7 @@ impl State { // SAFETY: a descriptor slot in title memory. unsafe { (at as *const [u32; 3]).read_unaligned() }.hash(&mut h); } - (table, h.finish()) + (host.identity(), table, h.finish()) }; if let Some(&first) = self.fresh_tables.get(&key) { for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) { @@ -1305,7 +1314,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 @@ -1314,9 +1323,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 { diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 7e09ba7b433..80caca29b0c 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -488,7 +488,7 @@ impl Shared { // SAFETY: a live buffer. let gpu = unsafe { table.GetGPUVirtualAddress() }; Some(Shared { - host: std::ptr::from_ref(heap) as usize, + host: heap.identity(), table, data: data as usize, gpu, @@ -567,7 +567,7 @@ fn layout(key: usize) -> Arc { pub(crate) fn prepare(key: usize, mut add: impl FnMut(&Arc, usize, usize)) { let layout = with_heap(key, |heap| { let mut shared = shared(); - let host = std::ptr::from_ref(heap) as usize; + let host = heap.identity(); let (_, s) = shared.iter_mut().find(|(k, s)| *k == key && s.host == host)?; let now = crate::shadow::generation(); if s.generation != now { @@ -614,7 +614,7 @@ fn has_missed(marks: &[u32], l: &Layout) -> bool { pub(crate) fn bind(list: &HostList, key: usize) -> Option { let table = with_heap(key, |heap| { let mut shared = shared(); - let host = std::ptr::from_ref(heap) as usize; + let host = heap.identity(); if let Some((_, s)) = shared.iter().find(|(k, s)| *k == key && s.host == host) { list.keep(&s.table); return Some(s.gpu); diff --git a/crates/victory-gpu/src/object.rs b/crates/victory-gpu/src/object.rs index 1fda39392eb..cf1908d65fa 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 1cf952e4f9d..68507480ea8 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1100,6 +1100,15 @@ pub(crate) fn host_copy(this: This) -> Option> { resource(this).host() } +/// A materialized texture whose backing cannot be evicted or reused. +#[cfg(windows)] +pub(crate) fn fixed_table_texture(this: This) -> Option> { + if this.is_null() { + return None; + } + made(resource(this)).filter(|copy| copy.key.is_none() && copy.placement.is_none()) +} + /// The host description of a title texture: the same, without the /// console's layout and flags, in a format the host takes for its use. #[cfg(windows)] @@ -2132,7 +2141,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