diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 7b18b4586..8b48cb9fb 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1471,6 +1471,21 @@ impl HostHeap { return None; }; if made[index as usize] != key { + // A failed growth must not retire another working view of the + // same texture or record the refused generation as materialized. + if for_draw + && crate::sparse::enabled() + && let Some(refused) = sparse_refused(&view) + { + let same_resource = self.kept.lock().unwrap_or_else(|e| e.into_inner()) + [index as usize] + .as_ref() + == Some(&refused); + if !same_resource { + self.unmake(&mut made, index); + } + return None; + } // Views of other textures in the memory this one describes // are stale: their host slots read nothing from here on, and // let go of the host copies they held. @@ -2202,7 +2217,12 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { // shortcut: unordered access to a texture the title placed // itself is not mirrored; give it a resource as shader // views of such textures get when a dispatch writes one. - once!(dimension = resource[0], "placed unordered texture view not mirrored"); + if *unordered { + once!( + dimension = resource[0], + "placed unordered texture view not mirrored" + ); + } return None; } // The resource description's width, after the alignment. @@ -2254,9 +2274,34 @@ pub(crate) fn placed_texture(view: &View) -> Option { } let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; let texture = crate::resource::texture_at(address, resource)?; + crate::resource::sparse_view(texture, first_visible_mip(desc)).ok()?; Some(View::Shader(texture as usize, desc[..10].try_into().ok())) } +fn first_visible_mip(desc: &[u32; 16]) -> u32 { + if desc[1] == D3D12_SRV_DIMENSION_TEXTURE2D.0 as u32 + && desc[5] > 0 + && desc[6] == 0 + && desc[7] == 0 + { + desc[4] + } else { + 0 + } +} + +fn sparse_refused(view: &View) -> Option { + let View::Placed(false, resource, desc) = view else { + return None; + }; + if resource[0] != 3 || !matches!(resource[8], 70..=72) { + return None; + } + let address = u64::from(desc[10]) | (u64::from(desc[11]) << 32); + let texture = crate::resource::texture_at(address, resource)?; + crate::resource::sparse_view(texture, first_visible_mip(desc)).err() +} + /// A null view of the kind `view` is, for a slot whose view the host /// cannot make: unordered access (to a buffer or a 2D texture) or a shader /// view. Writes to it are dropped, reads give zeros. @@ -2429,6 +2474,85 @@ fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { mod tests { use super::*; + #[test] + #[ignore = "requires the opt-in D3D12 sparse backing in a dedicated test process"] + fn failed_sparse_promotion_keeps_the_last_usable_descriptor() { + use windows_sys::Win32::System::Memory::*; + assert!(crate::sparse::enabled()); + let base = + unsafe { VirtualAlloc(std::ptr::null_mut(), 8 << 20, MEM_RESERVE, PAGE_NOACCESS) } + as usize; + assert_ne!(base, 0); + assert_eq!( + unsafe { VirtualAlloc(base as _, 4096, MEM_COMMIT, PAGE_READWRITE) } as usize, + base + ); + let resource = [3, 0, 0, 0, 2048, 0, 2048, 0x3_0001, 71, 1, 0, 0, 0, 0]; + let at = |base: usize, first| { + let mut desc = [0; 16]; + ( + desc[0], desc[1], desc[2], desc[4], desc[5], desc[10], desc[11], + ) = ( + 71, + 4, + 5768, + first, + 3 - first, + base as u32, + (base as u64 >> 32) as u32, + ); + // ResourceDesc padding can differ between writes for this same allocation. + let mut resource = resource; + resource[1] = 0x1234 + first; + resource[13] = 0xabcd - first; + let view = View::Placed(false, resource, desc); + let [i, g] = super::super::words_for(view); + [VIEW_TAG, i, g, 0, 0, 0, 0, 0] + }; + let low_words = at(base, 2); + let wide_words = at(base, 0); + let low = low_words.as_ptr() as u64; + let wide = wide_words.as_ptr() as u64; + let heap = HostHeap::new(false, 8).expect("test device"); + assert!(heap.mirror(1, low, true).is_some()); + assert!(heap.texture_slot_made_from(1, low)); + crate::sparse::FAIL_PROMOTION.with(|f| f.set(true)); + assert!(heap.mirror(1, wide, true).is_none()); + assert!( + !heap.texture_slot_made_from(1, wide), + "the refused key was not stored as ready" + ); + assert!( + heap.texture_slot_made_from(1, low), + "the old slot still holds its resource" + ); + assert!(heap.mirror(1, low, true).is_some()); + let other = + unsafe { VirtualAlloc(std::ptr::null_mut(), 8 << 20, MEM_RESERVE, PAGE_NOACCESS) } + as usize; + assert_ne!(other, 0); + assert_eq!( + unsafe { VirtualAlloc(other as _, 4096, MEM_COMMIT, PAGE_READWRITE) } as usize, + other + ); + let other_words = at(other, 2); + let other_handle = other_words.as_ptr() as u64; + assert!(heap.mirror(2, other_handle, true).is_some()); + assert!(heap.texture_slot_made_from(2, other_handle)); + assert!(heap.mirror(2, wide, true).is_none()); + assert!( + !heap.texture_slot_made_from(2, other_handle), + "an unrelated resource cannot survive in the refused slot" + ); + assert!(heap.mirror(3, wide, true).is_none()); + assert!(!heap.texture_slot_made_from(3, wide)); + assert!( + !heap.texture_slot_made_from(2, wide), + "a new slot must not expose missing mip data" + ); + assert!(unsafe { crate::host::host().unwrap().device.GetDeviceRemovedReason() }.is_ok()); + } + /// A null texture UAV keeps the title's dimension (3D for the world's /// wind field), and is 2D when the title names none. #[test] diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 492ae72ac..a524c7155 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2813,6 +2813,39 @@ fn hand_back(back: &[Declared]) { } impl Host { + // Identity-preserving, monotonic additions to a reserved BC texture's + // tile map. Recording/refresh ordering requires the same direct queue; + // a refreshing submission already holds the submission mutex. + pub(crate) fn map_sparse( + &self, + texture: &ID3D12Resource, + first: u32, + heap: &ID3D12Heap, + count: u32, + ) { + let start = D3D12_TILED_RESOURCE_COORDINATE { + Subresource: first, + ..Default::default() + }; + let region = D3D12_TILE_REGION_SIZE { + NumTiles: count, + ..Default::default() + }; + unsafe { + self.queue.UpdateTileMappings( + texture, + 1, + Some(&start), + Some(®ion), + heap, + 1, + Some(&D3D12_TILE_RANGE_FLAG_NONE), + Some(&0), + Some(&count), + D3D12_TILE_MAPPING_FLAG_NONE, + ); + } + } /// Whether the host runs mesh shaders at shader model 6.6 (translated /// mesh shaders need both); logged once. pub(crate) fn mesh_shaders(&self) -> bool { diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index db53f110b..7597716fe 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -52,6 +52,8 @@ mod memory; mod shadow; pub mod signature; #[cfg(windows)] +mod sparse; +#[cfg(windows)] mod texture; #[cfg(windows)] mod watch; diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index e4fee24d2..bc8d4b232 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1118,6 +1118,7 @@ struct Resource { /// lists that name it). #[cfg(windows)] pub(crate) struct HostTexture { + pub(crate) sparse: Option, pub(crate) texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, pub(crate) state: std::sync::atomic::AtomicU32, /// The bytes the host gives it. @@ -1155,6 +1156,7 @@ struct Hosted { gone: std::sync::atomic::AtomicBool, /// A texture of [`PLACED_TEXTURES`]. placed: std::sync::atomic::AtomicBool, + first_view: std::sync::atomic::AtomicU32, } /// Counts for the memory line: host copies of textures the title fills @@ -1303,7 +1305,17 @@ fn hosted(this: This, make: bool) -> Option { .clear .as_ref() .map_or(std::ptr::null(), |c| std::ptr::from_ref(c).cast::()); - let Some(texture) = host_texture(&r.desc, r.host.state, clear) else { + let sparse = if sparse_candidate(r) { + sparse_host(r) + } else { + None + }; + let (texture, sparse) = if let Some((tex, sparse)) = sparse { + (Some(tex), Some(sparse)) + } else { + (host_texture(&r.desc, r.host.state, clear), None) + }; + let Some(texture) = texture else { r.host.refused.store(true, Relaxed); return None; }; @@ -1321,6 +1333,7 @@ fn hosted(this: This, make: bool) -> Option { } let state = crate::host::legal_state(&texture, crate::host::texture_state(r.host.state)); let mut host = HostTexture::new(texture, state); + host.sparse = sparse; host.filled = fills(&r.desc); if host.filled { KINDS[0].fetch_add(1, Relaxed); @@ -1340,6 +1353,161 @@ fn hosted(this: This, make: bool) -> Option { made.clone() } +#[cfg(windows)] +// Only a wholly uncommitted range is eligible. Guarded and no-access +// committed pages can still contain bytes. A failed query conservatively +// keeps the conventional allocation. +fn region_present(start: usize, len: usize) -> bool { + use windows_sys::Win32::System::Memory::*; + let Some(end) = start.checked_add(len) else { + return true; + }; + if len > 0 && crate::texture::committed(start as *const u8, 1) { + return true; + } + let mut at = start; + while at < end { + let mut mbi: MEMORY_BASIC_INFORMATION = unsafe { core::mem::zeroed() }; + if unsafe { VirtualQuery(at as _, &mut mbi, size_of_val(&mbi)) } == 0 { + return true; + } + if mbi.State == MEM_COMMIT { + return true; + } + let next = (mbi.BaseAddress as usize).saturating_add(mbi.RegionSize); + if next <= at { + return true; + } + at = next; + } + false +} + +#[cfg(windows)] +fn sparse_host( + r: &Resource, +) -> Option<( + windows::Win32::Graphics::Direct3D12::ID3D12Resource, + crate::sparse::Sparse, +)> { + use std::sync::atomic::Ordering::Relaxed; + use windows::Win32::Graphics::Direct3D12::*; + let first = r.host.first_view.load(Relaxed); + if first == 0 || first >= u32::from(r.desc.mip_levels) { + return None; + } + let layout = texture_layout(&r.desc)?.planes[0].layout.clone(); + if layout.slices != 1 || layout.desc.swizzle.xor() { + return None; + } + let base = r.data() as usize; + let mut absent = 0; + for (i, m) in layout + .mips + .iter() + .enumerate() + .take(first.min(layout.first_tail_mip) as usize) + { + let end = if i == 0 { + layout.slice_size + } else { + layout.mips[i - 1].offset + }; + // A guarded or no-access committed page can still hold data. Only + // wholly uncommitted spans qualify, regardless of permissions. + if end <= m.offset + || region_present( + base.checked_add(m.offset as usize)?, + (end - m.offset) as usize, + ) + { + break; + } + absent += 1; + } + if absent == 0 { + return None; + } + // The repr(C) resource description is also used by host_texture; normalize + // the title-specific fields exactly as the committed BC path does. + let mut d = r.desc; + d.alignment = 0; + d.layout = 0; + d.flags &= 0xf; + d.format = pc_format(d.format); + let desc = unsafe { + (&raw const d) + .cast::() + .read_unaligned() + }; + let state = D3D12_RESOURCE_STATES(crate::host::legal_for( + d.flags, + crate::host::texture_state(r.host.state), + ) as i32); + crate::sparse::Sparse::try_new(desc, state, absent) +} + +#[cfg(windows)] +fn sparse_candidate(r: &Resource) -> bool { + use std::sync::atomic::Ordering::Relaxed; + crate::sparse::enabled() + && r.host.placed.load(Relaxed) + && r.desc.dimension == 3 + && r.desc.depth_or_array_size == 1 + && r.desc.sample_count == 1 + && (r.desc.flags & 0xf) == 0 + && matches!(r.desc.format, 70..=72) + && r.desc.mip_levels >= 2 + && r.desc.width >= 512 + && r.desc.height >= 512 +} + +#[cfg(windows)] +pub(crate) fn sparse_view( + this: This, + first: u32, +) -> Result<(), windows::Win32::Graphics::Direct3D12::ID3D12Resource> { + use std::sync::atomic::Ordering::Relaxed; + if !crate::sparse::enabled() { + return Ok(()); + } + let r = resource(this); + if !sparse_candidate(r) { + return Ok(()); + } + r.host.first_view.fetch_min(first, Relaxed); + let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((h, _)) = made.as_ref() + && let Some(s) = &h.sparse + && !s.promote(&h.texture, first) + { + return Err(h.texture.clone()); + } + Ok(()) +} + +#[cfg(windows)] +pub(crate) fn sparse_staging( + this: This, + texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, +) -> std::sync::Weak { + if !crate::sparse::enabled() { + return std::sync::Weak::new(); + } + let made = resource(this) + .host + .made + .lock() + .unwrap_or_else(|e| e.into_inner()); + if let Some((h, _)) = made.as_ref() + && h.texture == *texture + && h.sparse.is_some() + { + return std::sync::Arc::downgrade(h); + } + std::sync::Weak::new() +} + /// The host copy of title texture `this` if it is made, without making it /// (for diagnostics, which must not count as a use). #[cfg(all(windows, feature = "diagnostics"))] @@ -1768,6 +1936,7 @@ impl HostTexture { HOST_TEXTURES[0].fetch_add(1, Relaxed); HOST_TEXTURES[1].fetch_add(bytes, Relaxed); HostTexture { + sparse: None, texture, state: std::sync::atomic::AtomicU32::new(state), bytes, @@ -1995,6 +2164,7 @@ fn hand_out_resource( refused: std::sync::atomic::AtomicBool::new(false), gone: std::sync::atomic::AtomicBool::new(false), placed: std::sync::atomic::AtomicBool::new(false), + first_view: std::sync::atomic::AtomicU32::new(u32::MAX), }, }); // The host copy waits for the texture's first use ([`Hosted`]). diff --git a/crates/victory-gpu/src/sparse.rs b/crates/victory-gpu/src/sparse.rs new file mode 100644 index 000000000..c28e03614 --- /dev/null +++ b/crates/victory-gpu/src/sparse.rs @@ -0,0 +1,204 @@ +//! Experimental private backing for sampled-only, single-slice BC1 textures. +//! Existing views keep the original resource and subresource numbering. +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering::Relaxed}; +use std::sync::{Mutex, OnceLock}; +use windows::Win32::Graphics::Direct3D12::*; + +/// Opt in to reserved backing for hidden, wholly uncommitted detailed mips. +pub(crate) fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SPARSE_BC1").is_some_and(|v| v == "1")) +} + +pub(crate) struct Sparse { + // Overall starting tile for each standard subresource, then the packed tail and/or end. + starts: Vec, + first: AtomicU32, + refused: AtomicBool, + change: Mutex<()>, +} +impl Sparse { + /// On an unpublished resource or the host's direct queue, add mappings. + /// Newly added tiles are never reused or removed while the resource lives. + fn map(texture: &ID3D12Resource, first: u32, count: u32) -> windows::core::Result<()> { + let host = crate::host::host().ok_or(windows::core::Error::empty())?; + let desc = D3D12_HEAP_DESC { + SizeInBytes: u64::from(count) * 65536, + Properties: D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + CreationNodeMask: 1, + VisibleNodeMask: 1, + ..Default::default() + }, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + ..Default::default() + }; + let mut heap: Option = None; + unsafe { + host.device.CreateHeap(&desc, &mut heap)?; + let heap = heap.ok_or(windows::core::Error::empty())?; + // The resource's COM reference count (including descriptor heaps) + // governs these backing heaps' lifetime, even beyond the title handle. + let key = windows::core::GUID::from_u128( + 0x0128e665_6b89_412d_a55e_12d744300000 + u128::from(first), + ); + texture.SetPrivateDataInterface(&key, &heap)?; + host.map_sparse(texture, first, &heap, count); + } + Ok(()) + } + + pub(crate) fn try_new( + mut desc: D3D12_RESOURCE_DESC, + state: D3D12_RESOURCE_STATES, + limit: u32, + ) -> Option<(ID3D12Resource, Sparse)> { + if limit == 0 { + return None; + } + let host = crate::host::host()?; + static SUPPORTED: OnceLock = OnceLock::new(); + if !*SUPPORTED.get_or_init(|| { + let mut opt = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + unsafe { + host.device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS, + (&raw mut opt).cast(), + size_of_val(&opt) as u32, + ) + .is_ok() + && opt.TiledResourcesTier.0 >= 2 + } + }) { + return None; + } + let full_committed_bytes = unsafe { + host.device + .GetResourceAllocationInfo(0, &[desc]) + .SizeInBytes + }; + if full_committed_bytes == 0 || full_committed_bytes == u64::MAX { + return None; + } + desc.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; + let mut texture = None; + unsafe { + host.device + .CreateReservedResource(&desc, state, None, &mut texture) + .ok()?; + } + let texture: ID3D12Resource = texture?; + let mut total = 0; + let mut packed = D3D12_PACKED_MIP_INFO::default(); + let mut num = u32::from(desc.MipLevels); + let mut locations = vec![D3D12_SUBRESOURCE_TILING::default(); num as usize]; + unsafe { + host.device.GetResourceTiling( + &texture, + Some(&mut total), + Some(&mut packed), + None, + Some(&mut num), + 0, + locations.as_mut_ptr(), + ); + } + let standard = usize::from(packed.NumStandardMips); + if standard > locations.len() + || standard > num as usize + || total == 0 + || standard + usize::from(packed.NumPackedMips) != usize::from(desc.MipLevels) + { + return None; + } + let mut starts: Vec<_> = locations[..standard] + .iter() + .map(|t| t.StartTileIndexInOverallResource) + .collect(); + if packed.NumPackedMips > 0 { + if packed + .StartTileIndexInOverallResource + .checked_add(packed.NumTilesForPackedMips) + != Some(total) + { + return None; + } + starts.push(packed.StartTileIndexInOverallResource); + } + starts.push(total); + if starts.first() != Some(&0) || starts.windows(2).any(|s| s[0] >= s[1]) { + return None; + } + let first = limit + .min(u32::from(packed.NumStandardMips)) + .min(u32::from(desc.MipLevels) - 1); + if first == 0 { + return None; + } + let skipped = starts[first as usize]; + // Never select a device/shape with larger capacity after full promotion, + // even when its initial tail would be cheap. + if u64::from(total) * 65536 > full_committed_bytes { + return None; + } + Self::map(&texture, first, total - skipped).ok()?; + Some(( + texture, + Self { + starts, + first: AtomicU32::new(first), + refused: AtomicBool::new(false), + change: Mutex::new(()), + }, + )) + } + + pub(crate) fn first(&self) -> u32 { + self.first.load(Relaxed) + } + + pub(crate) fn promote(&self, texture: &ID3D12Resource, first: u32) -> bool { + if first >= self.first() { + return true; + } + let _guard = self.change.lock().unwrap_or_else(|e| e.into_inner()); + let previous = self.first(); + if first >= previous { + return true; + } + if self.refused.load(Relaxed) { + return false; + } + let count = self.starts[previous as usize] - self.starts[first as usize]; + #[cfg(test)] + let result = if FAIL_PROMOTION.with(|fail| fail.replace(false)) { + Err(windows::core::Error::from_hresult( + windows::Win32::Foundation::E_OUTOFMEMORY, + )) + } else { + Self::map(texture, first, count) + }; + #[cfg(not(test))] + let result = Self::map(texture, first, count); + if let Err(e) = result { + if let Some(host) = crate::host::host() + && unsafe { host.device.GetDeviceRemovedReason() }.is_err() + { + crate::host::fail(format_args!( + "device lost during sparse texture promotion: {e}" + )); + } + // Like a refused committed texture, do not retry an allocation + // every draw. This generation can still serve all resident mips. + // A replacement after normal retirement uses its widest known view. + self.refused.store(true, Relaxed); + tracing::warn!(error=%e, "cannot grow sparse texture; keeping its resident mip range"); + return false; + } + self.first.store(first, Relaxed); + true + } +} +#[cfg(test)] +thread_local! { pub(crate) static FAIL_PROMOTION: std::cell::Cell = const { std::cell::Cell::new(false) }; } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 34e7d5156..a4d5b3800 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -33,6 +33,7 @@ macro_rules! once { /// A texture's upload state: the staging buffer laid out as the host /// texture's subresources, and what was last detiled. pub(crate) struct Staging { + sparse_host: std::sync::Weak, buffer: ID3D12Resource, /// Its bytes. #[cfg(feature = "diagnostics")] @@ -834,6 +835,31 @@ impl Staging { /// Detiles `tiled` (the texture's memory) into the staging buffer. fn detile(&self, tiled: &[u8]) { + // A stage may change during a refresh-only list. Mapping a newly + // nonzero level preserves the prior zero until an actual upload, + // as for a fresh committed texture. Promotion is monotonic. + let mut unavailable = 0; + if let Some(h) = self.sparse_host.upgrade() + && let Some(s) = &h.sparse + { + for i in 0..s.first() as usize { + let start = self.layout.mips[i].offset as usize; + let end = if i == 0 { + self.layout.slice_size + } else { + self.layout.mips[i - 1].offset + } as usize; + if tiled + .get(start..end) + .is_none_or(|part| part.iter().any(|&b| b != 0)) + { + if !s.promote(&h.texture, i as u32) { + unavailable = s.first(); + } + break; + } + } + } self.dirty.store(true, std::sync::atomic::Ordering::Relaxed); #[cfg(feature = "diagnostics")] if tiled.iter().all(|&b| b == 0) { @@ -852,6 +878,13 @@ impl Staging { let linear = unsafe { std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len) }; + if mip < unavailable { + // This generation refused the heap. Its live SRVs can only + // select resident levels. Never write nonzero bytes into a + // NULL tile through a copy in a previously recorded list. + linear.fill(0); + continue; + } if let Err(e) = self.layout .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize) @@ -1095,6 +1128,17 @@ pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 { /// The staging state of a title texture, made on first use. fn staging(resource: This, texture: &ID3D12Resource) -> Option> { + if crate::sparse::enabled() + && let Some(s) = STAGING + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .and_then(|m| m.get(&(resource as usize)).cloned()) + { + return Some(s); + } + // Before STAGING: eviction takes the resource's made lock, then STAGING. + let sparse_host = crate::resource::sparse_staging(resource, texture); let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); let map = map.get_or_insert_with(HashMap::new); if let Some(s) = map.get(&(resource as usize)) { @@ -1148,6 +1192,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { STAGED[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); STAGED[1].fetch_add(total, std::sync::atomic::Ordering::Relaxed); let s = Arc::new(Staging { + sparse_host, buffer, #[cfg(feature = "diagnostics")] size: total, @@ -1171,6 +1216,119 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { mod title_memory_tests { use super::with_title; + #[test] + #[ignore = "opt-in D3D12 sparse texture study, run in its own process"] + fn sparse_placed_bc_preserves_identity_and_promotes_for_views_and_bytes() { + use crate::descriptor::{View, host::placed_texture}; + use crate::object::This; + use windows_sys::Win32::System::Memory::*; + assert!(crate::sparse::enabled()); + let placed = |base: usize, first: u32, format: u32| { + let resource = [3, 0, 0, 0, 2048, 0, 2048, 0x3_0001, format, 1, 0, 0, 0, 0]; + let mut view = [0; 16]; + ( + view[0], view[1], view[2], view[4], view[5], view[10], view[11], + ) = ( + format, + 4, + 5768, + first, + 3 - first, + base as u32, + (base as u64 >> 32) as u32, + ); + let Some(View::Shader(object, _)) = + placed_texture(&View::Placed(false, resource, view)) + else { + panic!("missing placed view") + }; + object as This + }; + // The process owns independent synthetic reservations. The title + // resource lookup intentionally retains them for its lifetime. + let memory = || unsafe { + let base = VirtualAlloc(core::ptr::null_mut(), 8 << 20, MEM_RESERVE, PAGE_NOACCESS); + assert!(!base.is_null()); + assert_eq!(VirtualAlloc(base, 4096, MEM_COMMIT, PAGE_READWRITE), base); + base as usize + }; + let a = memory(); + let object = placed(a, 2, 71); + let h = crate::resource::host_copy(object).unwrap(); + let s = h + .sparse + .as_ref() + .expect("restricted BC1 SRV reserves its missing top mips"); + let first = s.first(); + assert!(first > 0 && first <= 2); + let stage = super::staging(object, &h.texture).unwrap(); + let mut tiled = vec![0u8; stage.layout.size as usize]; + stage.detile(&tiled); + assert_eq!(s.first(), first, "all zero content does not need new tiles"); + tiled[stage.layout.mips[0].offset as usize] = 7; + stage.detile(&tiled); + assert_eq!( + s.first(), + 0, + "new source content is retained even for a hidden level" + ); + assert_eq!( + h.texture, + crate::resource::host_copy(object).unwrap().texture + ); + let b = memory(); + let second = placed(b, 2, 71); + let original = crate::resource::host_copy(second).unwrap(); + assert!(original.sparse.as_ref().unwrap().first() > 0); + assert_eq!(second, placed(b, 0, 71)); + assert_eq!(original.sparse.as_ref().unwrap().first(), 0); + assert_eq!( + original.texture, + crate::resource::host_copy(second).unwrap().texture + ); + assert!( + crate::resource::host_copy(placed(memory(), 0, 71)) + .unwrap() + .sparse + .is_none() + ); + assert!( + crate::resource::host_copy(placed(memory(), 2, 98)) + .unwrap() + .sparse + .is_none() + ); + + let object = placed(memory(), 2, 71); + let h = crate::resource::host_copy(object).unwrap(); + let s = h.sparse.as_ref().unwrap(); + let first = s.first(); + let stage = super::staging(object, &h.texture).unwrap(); + let mut tiled = vec![0x7f; stage.layout.size as usize]; + crate::sparse::FAIL_PROMOTION.with(|f| f.set(true)); + stage.detile(&tiled); + assert_eq!( + s.first(), + first, + "failed allocation cannot change the mapped range" + ); + let byte = |i: usize| unsafe { *stage.data.add(stage.footprints[i].Offset as usize) }; + assert_eq!( + byte(0), + 0, + "an unavailable tile must not receive nonzero copy data" + ); + assert_eq!( + byte(first as usize), + 0x7f, + "a resident mip still receives new data" + ); + tiled.fill(0x42); + stage.detile(&tiled); + assert_eq!(byte(0), 0); + assert_eq!(byte(first as usize), 0x42); + } + /// Title memory whose tail is reserved and not committed reads through /// the copy as its bytes and then zeros, without a fault; so does /// memory a page of which is taken away between two reads, and the