//! Host descriptor heaps behind the title's shader-visible heaps (decision //! 0007, step 3). Translated shaders index the heaps directly at the //! title's descriptor positions, so each host heap keeps the title heap's //! order: slot `i` is made from what the title wrote at slot `i`, when it //! writes it (view creation and descriptor copies) and again when a draw //! reads it through a table and finds the slot changed. use std::collections::HashMap; use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; use victory_shader::emit::{RawWindow, StrideEntry}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; use super::{VIEW_TAG, View, view_at}; use crate::host::{HostList, host}; /// An aligned upload copy backing a buffer SRV whose offset inside its shadow /// buffer is not a multiple of its element stride. Kept mapped so each draw /// or dispatch using the slot can schedule a submission-time refresh. #[derive(Clone)] struct UnalignedCopy { resource: ID3D12Resource, dst: usize, src: usize, len: usize, } struct LiveSlots { seen: Vec, slots: Vec, } pub(crate) struct HostHeap { pub(crate) heap: ID3D12DescriptorHeap, 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, sampler: bool, /// The record (view index and generation) each slot was last made from. made: Mutex>, /// Title slots in this view heap that have held a view, for bindless /// refresh before draws/dispatches. live: Mutex, /// Incremented whenever the title writes or updates a view in this heap. generation: AtomicU64, /// The host resource each slot views, held while the slot does: shaders /// index heaps directly, so a slot the title has not rewritten since it /// 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>>, /// Slots backed by an [`UnalignedCopy`] that must be refreshed from title /// memory when a command list referencing the slot is submitted. unaligned: Mutex>, /// Where the search for free dynamic slots starts, and which are taken /// (by lists not yet reset). next: Mutex<(u32, Vec)>, /// Per slot, what shaders need to read a buffer whose stride shader /// analysis could not recover statically ([`StrideEntry`]). strides: Option, /// The first of the [`ALIASES`] slots after the dynamic ones (view /// heaps), and which slots have a raw view there. alias_base: u32, aliases: Mutex, } /// The raw views of the bytes structured and typed buffer views read, for /// shaders that read such a buffer without knowing its stride: they take a /// raw handle, which reads a raw view only (over the title's own view the /// host GPUs disagree: an RTX 5070 reads other dwords than a Radeon). The /// runtime stride table names the slot. struct Aliases { /// The pool slot of each heap slot that has a raw view. of: HashMap, /// Pool slots given back. free: Vec, /// Pool slots from here on were never taken. next: u32, } /// Slots past the dynamic ones in a view heap for [`Aliases`]: one per /// structured or typed buffer view in the heap at a time. /// shortcut: a heap holding more such views at once leaves the rest without /// a raw view (they read zeros through the unknown-stride path, with a /// warning); the count is a guess, not a measured need. const ALIASES: u32 = 1 << 16; /// The pool's first slots: null raw views (a shader view, an unordered /// access one) for views that cannot have a raw view of their own. const NULL_ALIASES: u32 = 2; struct StrideTable { _resource: ID3D12Resource, ptr: usize, gpu: u64, len: u32, } impl StrideTable { fn new(device: &ID3D12Device, len: u32) -> Option { let bytes = (u64::from(len) * u64::from(StrideEntry::BYTES)).max(8); let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0, }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }; let mut resource: Option = None; let mut p = std::ptr::null_mut(); // SAFETY: plain committed upload buffer creation and persistent CPU map. let gpu = unsafe { device .CreateCommittedResource( &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut resource, ) .ok()?; let res = resource.as_ref()?; res.Map(0, None, Some(&mut p)).ok()?; std::ptr::write_bytes(p.cast::(), 0, bytes as usize); res.GetGPUVirtualAddress() }; Some(Self { _resource: resource?, ptr: p as usize, gpu, len, }) } } /// 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()); /// For device-removed reports: where host GPU address `va` lies against /// the host descriptor heaps. pub(crate) fn near_heaps(va: u64) -> String { let ranges = GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()); let mut text = String::new(); for &(start, bytes, step, sampler) in ranges.iter() { let kind = if sampler { "sampler" } else { "view" }; let place = if va < start { format!("{:#x} below", start - va) } else if va < start + bytes { format!("inside, slot {}", (va - start) / step) } else { format!( "{:#x} past its end (slot {})", va - start - bytes, (va - start) / step ) }; text.push_str(&format!("; {kind} heap {start:#x}+{bytes:#x}: {place}")); } text } /// The host's limit for shader-visible view heaps on resource binding /// tiers 1 and 2; tier 3 hardware may take more. const PORTABLE_VIEWS: u32 = 1_000_000; /// Slots past the title's in a view heap, for tables a draw needs made /// afresh (constant buffers copied per draw). A list holds the slots it /// 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; /// 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. const MIN_DYNAMIC: u32 = 1 << 16; impl HostHeap { pub(crate) fn new(sampler: bool, count: u32) -> Option { let host = host()?; let kind = if sampler { D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER } else { D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV }; 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, }) } }; let aliases = if sampler { 0 } else { ALIASES }; // The larger dynamic range only where the host takes it on top of // every title slot; else the smaller one, and the cap after that. let (heap, count, extra) = if sampler { match make(count) { Ok(heap) => (heap, count, 0), Err(e) => { tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); return None; } } } else if let Ok(heap) = make(count + DYNAMIC + aliases) { (heap, count, DYNAMIC) } else { match make(count + MIN_DYNAMIC + aliases) { Ok(heap) => (heap, count, MIN_DYNAMIC), Err(e) if count + MIN_DYNAMIC + aliases > PORTABLE_VIEWS => { // shortcut: descriptors past the host's limit are left // out; a title that reaches them needs remapping. tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}"); ( make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - MIN_DYNAMIC - aliases, MIN_DYNAMIC, ) } Err(e) => { tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); return None; } } }; // SAFETY: a live heap. let (cpu, step) = unsafe { ( heap.GetCPUDescriptorHandleForHeapStart().ptr, host.device.GetDescriptorHandleIncrementSize(kind), ) }; tracing::debug!(count, sampler, "host descriptor heap"); // SAFETY: a live shader-visible heap. let gpu = unsafe { heap.GetGPUDescriptorHandleForHeapStart().ptr }; GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push(( gpu, u64::from(count + extra + aliases) * u64::from(step), u64::from(step), sampler, )); let strides = if sampler { None } else { StrideTable::new(&host.device, count + extra) }; let h = HostHeap { heap, cpu, step, count, dynamic: extra, sampler, made: Mutex::new(vec![0; count as usize]), live: Mutex::new(LiveSlots { seen: vec![false; if sampler { 0 } else { count as usize }], slots: Vec::new(), }), generation: AtomicU64::new(0), kept: Mutex::new(vec![None; (count + extra) as usize]), unaligned: Mutex::new(HashMap::new()), next: Mutex::new((0, vec![false; extra as usize])), strides, alias_base: count + extra, aliases: Mutex::new(Aliases { of: HashMap::new(), free: Vec::new(), next: NULL_ALIASES, }), }; // 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 // used-resource entry names) read a wild address. Every slot starts // null instead. let started = std::time::Instant::now(); if let Err(e) = h.fill_null(kind, count + extra + aliases) { tracing::warn!(error = %e, "host descriptor heap not made null"); } if !sampler { null_buffer_view(h.cpu(h.alias_base)); null_raw_uav(h.cpu(h.alias_base + 1)); } tracing::debug!( ms = started.elapsed().as_millis(), "host descriptor heap made null" ); Some(h) } /// Makes the first `total` slots null: one null slot in a CPU-side heap, /// 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() })?; 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); } else { null_view(start); } let mut filled = 1; while filled < BLOCK { let n = filled.min(BLOCK - filled); host.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); done += n; } } Ok(()) } /// A plain point sampler at slot `index`, for sampler slots without a /// view. fn null_sampler(&self, index: u32) { null_sampler(self.cpu(index)); } } /// A plain point sampler at `at`. fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) { let Some(host) = host() else { return }; let desc = D3D12_SAMPLER_DESC { Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, MaxAnisotropy: 1, ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER, ..Default::default() }; // SAFETY: a slot of a sampler heap of ours. unsafe { host.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 { return None; } let mut guard = self.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 mut run = 0; let mut found = None; let mut last = usize::MAX; for at in starts { // A run cannot wrap past the end. if at != last.wrapping_add(1) { run = 0; } last = at; run = if taken[at] { 0 } else { run + 1 }; if run == n { found = Some(at + 1 - n); break; } } let Some(first) = found else { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { tracing::warn!(n, "no free dynamic descriptor slots: a table is not made") }); return None; }; taken[first..first + n].fill(true); *next = ((first + n) % self.dynamic as usize) as u32; Some(self.count + first as u32) } /// The title slots this heap has host slots for; fewer than the title's /// when the host caps its size. pub(crate) fn count(&self) -> u32 { 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) { self.release_with(first, n, Self::forget_view); } pub(super) fn release_with(&self, first: u32, n: u32, mut clear: impl FnMut(&Self, u32)) { let Some(at) = first.checked_sub(self.count) else { return; }; // Clear the retiring list's aliases before another list can lease // these slots and publish its own stride entries. for index in first..first.saturating_add(n).min(self.alias_base) { clear(self, index); } 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); } } /// Makes slot `index` (a dynamic one) from `view`; a null view if the /// host cannot. pub(crate) fn make_at(&self, index: u32, view: &View) { let kept = make(view, self.cpu(index)); if kept.is_none() { null_for(view, self.cpu(index)); } self.note_view(index, view, kept.as_ref()); self.keep(index, kept.unwrap_or(Kept::Empty)); } /// Makes slot `index` read nothing: a null view, or a plain sampler. pub(crate) fn make_null(&self, index: u32) { if self.sampler { self.null_sampler(index); } else { null_view(self.cpu(index)); } self.keep(index, Kept::Empty); self.forget_view(index); } /// Slot `index` now views `kept` (or nothing of the host's). fn keep(&self, index: u32, kept: Kept) { let (resource, unaligned) = match kept { Kept::Empty => (None, None), Kept::Resource(r) => (Some(r), None), Kept::Unaligned(copy) => (Some(copy.resource.clone()), Some(copy)), }; let mut slots = self.kept.lock().unwrap_or_else(|e| e.into_inner()); if let Some(slot) = slots.get_mut(index as usize) { *slot = resource; } drop(slots); let mut map = self.unaligned.lock().unwrap_or_else(|e| e.into_inner()); match unaligned { Some(copy) => { map.insert(index, copy); } None if !map.is_empty() => { map.remove(&index); } None => {} } } /// If slot `index` is backed by an unaligned upload copy, schedules a /// submission-time refresh from title memory on `list`. pub(crate) fn refresh_slot(&self, index: u32, list: &HostList) { let copy = { let map = self.unaligned.lock().unwrap_or_else(|e| e.into_inner()); if map.is_empty() { return; } map.get(&index).cloned() }; if let Some(copy) = copy { list.defer_fill_upload( copy.resource, copy.dst as *mut u8, copy.src as *const u8, copy.len, ); } } fn set_entry(&self, index: u32, entry: StrideEntry) { if let Some(t) = &self.strides && index < t.len { // SAFETY: `t.ptr` points to a live mapped UPLOAD buffer of // `t.len` entries of two dwords. unsafe { (t.ptr as *mut [u32; 2]) .add(index as usize) .write(entry.words()); } } } /// GPU virtual address of the runtime stride table: a [`StrideEntry`] /// per slot. pub(crate) fn stride_table_gpu(&self) -> Option { self.strides.as_ref().map(|t| t.gpu) } /// Makes slot `index` (a dynamic one) a constant buffer view of host /// memory (the list's own, which it holds). pub(crate) fn constant_at(&self, index: u32, gpu: u64, size: u32) { self.keep(index, Kept::Empty); self.forget_view(index); let Some(host) = host() else { return }; let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { BufferLocation: gpu, SizeInBytes: size.next_multiple_of(256), }; // SAFETY: a slot of our heap; the memory is the caller's. unsafe { host.device .CreateConstantBufferView(Some(&desc), self.cpu(index)) }; } /// Makes slot `index` (a dynamic one) a raw buffer view of `len` bytes /// of `buffer` from byte `offset` (a multiple of 16): a root SRV with a /// size, whose reads past it return zeros instead of reaching whatever /// the host placed after the buffer. pub(crate) fn raw_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) { let Some(host) = host() else { return }; let elements = (len / 4).clamp(1, u64::from(u32::MAX)) as u32; let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT_R32_TYPELESS, ViewDimension: D3D12_SRV_DIMENSION_BUFFER, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Buffer: D3D12_BUFFER_SRV { FirstElement: offset / 4, NumElements: elements, StructureByteStride: 0, Flags: D3D12_BUFFER_SRV_FLAG_RAW, }, }, }; // SAFETY: a slot of our heap and a live buffer covering the range. unsafe { host.device .CreateShaderResourceView(buffer, Some(&desc), self.cpu(index)) }; self.keep(index, Kept::Resource(buffer.clone())); } /// Makes slot `index` (a dynamic one) a raw buffer view with unordered /// access of `len` bytes of `buffer` from byte `offset` (a multiple of /// 16): a root UAV with a size, whose writes past it are dropped /// instead of reaching whatever the host placed after the buffer. pub(crate) fn raw_uav_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) { let Some(host) = host() else { return }; let elements = (len / 4).clamp(1, u64::from(u32::MAX)) as u32; let desc = raw_uav_desc(offset / 4, elements); // SAFETY: a slot of our heap and a live buffer covering the range. unsafe { host.device.CreateUnorderedAccessView( buffer, None::<&ID3D12Resource>, Some(&desc), self.cpu(index), ) }; self.keep(index, Kept::Resource(buffer.clone())); } /// Makes slot `index` a raw buffer view that reads zeros. pub(crate) fn null_raw_at(&self, index: u32) { null_buffer_view(self.cpu(index)); self.keep(index, Kept::Empty); } /// Makes slot `index` a raw buffer view with unordered access of no /// buffer: reads return zeros and writes are dropped. pub(crate) fn null_raw_uav_at(&self, index: u32) { let Some(host) = host() else { return }; let desc = raw_uav_desc(0, 1); // SAFETY: a slot of our heap; a null resource is allowed with a desc. unsafe { host.device.CreateUnorderedAccessView( None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&desc), self.cpu(index), ) }; self.keep(index, Kept::Empty); } /// Whether this is a sampler heap. pub(crate) fn is_sampler(&self) -> bool { self.sampler } /// The shader-visible handle of slot `index`. pub(crate) fn gpu_handle(&self, index: u32) -> D3D12_GPU_DESCRIPTOR_HANDLE { // SAFETY: a live shader-visible heap. let start = unsafe { self.heap.GetGPUDescriptorHandleForHeapStart().ptr }; D3D12_GPU_DESCRIPTOR_HANDLE { ptr: start + u64::from(index) * u64::from(self.step), } } fn cpu(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE { D3D12_CPU_DESCRIPTOR_HANDLE { ptr: self.cpu + index as usize * self.step as usize, } } /// Makes host slot `index` from the record the title has at `handle` /// if it changed since, and returns the view recorded there. Buffer /// views are made only for draws (`for_draw`), which also copy their /// data: a host copy of a buffer is made on first use. pub(crate) fn mirror(&self, index: u32, handle: u64, for_draw: bool) -> Option { if index >= self.count { // Diagnostic (NVIDIA heap cap): the highest title slot past the // host heap seen so far. static HIGHEST: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if HIGHEST.fetch_max(index, std::sync::atomic::Ordering::Relaxed) < index { tracing::warn!( index, count = self.count, for_draw, "title slot past the host heap" ); } return None; } // SAFETY: the handle is a descriptor slot in title memory. let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; // Generations start at 1, so a made slot's key is never 0. let key = u64::from(generation) << 32 | u64::from(i); let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); let view = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten(); let Some(view) = view else { // Not a view of ours (never written, or of a resource the // title released): nothing to read. if made[index as usize] != 0 { made[index as usize] = 0; self.make_null(index); if !self.sampler { self.generation.fetch_add(1, Ordering::Release); } } else if !for_draw && !self.sampler { self.generation.fetch_add(1, Ordering::Release); } return None; }; let changed = made[index as usize] != key; if changed { let later = !for_draw && view.is_buffer(); made[index as usize] = if later { 0 } else { key }; let kept = if later { None } else { make(&view, self.cpu(index)) }; if kept.is_none() && !self.sampler { null_for(&view, self.cpu(index)); } self.note_view(index, &view, kept.as_ref()); self.keep(index, kept.unwrap_or(Kept::Empty)); } if !self.sampler && (!for_draw || changed) { let mut live = self.live.lock().unwrap_or_else(|e| e.into_inner()); if let Some(seen) = live.seen.get_mut(index as usize) && !*seen { *seen = true; live.slots.push(index); } drop(live); self.generation.fetch_add(1, Ordering::Release); } Some(view) } pub(crate) fn generation(&self) -> u64 { self.generation.load(Ordering::Acquire) } pub(crate) fn live_slots(&self) -> Vec { self.live .lock() .unwrap_or_else(|e| e.into_inner()) .slots .clone() } /// The view host slot `index` was made from, in a few words, with the /// title and host addresses of a buffer view (diagnostics). "null" for /// a slot never made or left null. #[cfg(feature = "diagnostics")] pub(crate) fn describe_slot(&self, index: u32) -> Option { let key = *self .made .lock() .unwrap_or_else(|e| e.into_inner()) .get(index as usize)?; if key == 0 { return Some("null".into()); } let view = view_at(key as u32, (key >> 32) as u32)?; let mut text: String = format!("{view:?}").chars().take(120).collect(); if let Some((address, len)) = buffer_range(&view) { let host = crate::shadow::find(address, len.max(1)).map(|s| s.gpu(address)); text.push_str(&format!(" title {address:#x}+{len:#x} host {host:#x?}")); } Some(text) } } /// Logs `what` the first time it happens. macro_rules! once { ($($arg:tt)*) => {{ static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| tracing::warn!($($arg)*)); }}; } /// A view description from its words, with the format as the host has it. fn srv_desc(words: &[u32; 10]) -> D3D12_SHADER_RESOURCE_VIEW_DESC { let mut words = *words; words[0] = crate::resource::pc_format(words[0]); // SAFETY: 40 bytes in the host's layout. unsafe { std::ptr::from_ref(&words) .cast::() .read_unaligned() } } fn uav_desc(words: &[u32; 10]) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { let mut words = *words; words[0] = crate::resource::pc_format(words[0]); // SAFETY: 40 bytes in the host's layout. unsafe { std::ptr::from_ref(&words) .cast::() .read_unaligned() } } /// A buffer view of title memory at `address` on its host copy: the first /// element moves by the copy's offset. /// Bytes per element of a buffer view. fn element_size(desc: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> u64 { // SAFETY: a buffer view's union member. let buffer = unsafe { desc.Anonymous.Buffer }; if buffer.StructureByteStride > 0 { u64::from(buffer.StructureByteStride) } else if buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0 { 4 } else { crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes) } } /// The title memory a buffer shader or unordered access view reads: its /// address and length. pub(crate) fn buffer_range(view: &View) -> Option<(u64, u64)> { let (base, words): (u64, &[u32; 10]) = match view { View::Shader(r, Some(desc)) => ( crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64, desc, ), View::Placed(false, resource, desc) if resource[0] == 1 => ( u64::from(desc[10]) | u64::from(desc[11]) << 32, desc[..10].try_into().ok()?, ), View::Unordered(r, _, Some(desc)) => { let base = crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64; return unordered_range(base, desc); } View::Placed(true, resource, desc) if resource[0] == 1 => { let base = u64::from(desc[10]) | u64::from(desc[11]) << 32; return unordered_range(base, desc[..10].try_into().ok()?); } _ => return None, }; let desc = srv_desc(words); let element = element_size(&desc); // SAFETY: a buffer view's union member. let buffer = unsafe { desc.Anonymous.Buffer }; Some(( base + buffer.FirstElement * element, u64::from(buffer.NumElements) * element, )) } fn uav_element_size(desc: &D3D12_UNORDERED_ACCESS_VIEW_DESC) -> Option { // SAFETY: a buffer view's union member. let buffer = unsafe { desc.Anonymous.Buffer }; if buffer.StructureByteStride > 0 { Some(u64::from(buffer.StructureByteStride)) } else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { Some(4) } else { crate::resource::element(desc.Format.0 as u32).map(|(bytes, _)| bytes) } } impl HostHeap { /// Slot `index` was just made from `view` (`made`: what [`make`] gave): /// writes its runtime stride table entry, and for a structured or typed /// buffer view makes the raw view of the same bytes the entry names. fn note_view(&self, index: u32, view: &View, made: Option<&Kept>) { if self.strides.is_none() { return; } let Some(kept) = made else { // A null view: nothing to read through any handle. return self.forget_view(index); }; let stride = view_stride(view); // An aligned copy of the viewed bytes is a buffer of its own: the // slot's own view reads the right element from element 0, so the // entry names no raw view of the host copy. let viewed = match kept { Kept::Unaligned(_) => Viewed::Own, Kept::Resource(resource) => viewed_bytes(view, Some(resource)), Kept::Empty => Viewed::Own, }; let entry = match viewed { // Not a buffer view, or a raw one: the slot's own view. Viewed::Own => { self.unalias(index); StrideEntry { stride, ..StrideEntry::default() } } Viewed::Bytes { buffer, start, len, unordered, } => { let (raw_slot, bias) = self.alias(index, &buffer, start, len, unordered); StrideEntry { stride, raw_slot: Some(raw_slot), bias, } } Viewed::Unknown => { once!("a buffer view whose bytes in its host copy are not found has no raw view"); self.unalias(index); StrideEntry { stride, raw_slot: Some(self.null_alias(view_is_unordered(view))), bias: 0, } } }; self.set_entry(index, entry); } /// Slot `index`'s runtime stride table entry, as shaders read it. #[cfg(test)] pub(crate) fn entry_words(&self, index: u32) -> [u32; 2] { let t = self.strides.as_ref().expect("a view heap's table"); assert!(index < t.len); // SAFETY: as in `set_entry`. unsafe { (t.ptr as *const [u32; 2]).add(index as usize).read() } } /// The first slot of the raw view pool. #[cfg(test)] pub(crate) fn alias_base(&self) -> u32 { self.alias_base } /// Slot `index` holds no view shaders read through the runtime stride /// table: its entry is cleared and its raw view given back. pub(super) fn forget_view(&self, index: u32) { if self.strides.is_none() { return; } self.unalias(index); self.set_entry(index, StrideEntry::default()); } /// The slot of the null raw view standing in for a raw view the host /// cannot make: reads give zeros, writes are dropped. fn null_alias(&self, unordered: bool) -> u32 { self.alias_base + u32::from(unordered) } /// Gives back the raw view slot of `index`, if it has one. fn unalias(&self, index: u32) { let mut a = self.aliases.lock().unwrap_or_else(|e| e.into_inner()); if let Some(slot) = a.of.remove(&index) { a.free.push(slot); } } /// Makes the raw view of bytes `[start, start + len)` of `buffer` for /// slot `index` (in the slot it already has for one, or a free one): the /// heap slot it is in, and the bytes from its start to `start`. /// /// The raw view ends with the view's last element, so reads past it /// give zeros and writes are dropped, as through the view itself. /// shortcut: it ends on the dword holding the last byte and starts up /// to 12 bytes before the first (raw views start on 16 bytes); only an /// offset wrapping below the view's start reaches those bytes. fn alias( &self, index: u32, buffer: &ID3D12Resource, start: u64, len: u64, unordered: bool, ) -> (u32, u32) { let Some(window) = RawWindow::covering(start, len) else { // shortcut: a view starting off a dword of its host copy (an // element size that is not a multiple of 4) has no raw view; a // raw load could not address its bytes either. once!(start, len, "a buffer view off the dwords of its host copy has no raw view"); self.unalias(index); return (self.null_alias(unordered), 0); }; let slot = { let mut a = self.aliases.lock().unwrap_or_else(|e| e.into_inner()); let slot = match a.of.get(&index) { Some(&slot) => Some(slot), None => a.free.pop().or_else(|| { (a.next < ALIASES).then(|| { a.next += 1; a.next - 1 }) }), }; let Some(slot) = slot else { once!( "no free raw view slots: a buffer read without a known stride reads zeros" ); return (self.null_alias(unordered), 0); }; a.of.insert(index, slot); self.alias_base + slot }; let Some(host) = host() else { return (self.null_alias(unordered), 0); }; // SAFETY: a live buffer holding the range (the slot's own view was // just made on it) and a slot of our heap. unsafe { if unordered { let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R32_TYPELESS, ViewDimension: D3D12_UAV_DIMENSION_BUFFER, Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Buffer: D3D12_BUFFER_UAV { FirstElement: window.first, NumElements: window.dwords, Flags: D3D12_BUFFER_UAV_FLAG_RAW, ..Default::default() }, }, }; host.device.CreateUnorderedAccessView( buffer, None::<&ID3D12Resource>, Some(&desc), self.cpu(slot), ); } else { let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT_R32_TYPELESS, ViewDimension: D3D12_SRV_DIMENSION_BUFFER, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Buffer: D3D12_BUFFER_SRV { FirstElement: window.first, NumElements: window.dwords, StructureByteStride: 0, Flags: D3D12_BUFFER_SRV_FLAG_RAW, }, }, }; host.device .CreateShaderResourceView(buffer, Some(&desc), self.cpu(slot)); } } (slot, window.bias) } } /// What a view the host made reads, for its raw view. enum Viewed { /// Not a buffer, or through a raw view already. Own, /// These bytes of this host buffer (the view's own), read or also /// written. Bytes { buffer: ID3D12Resource, start: u64, len: u64, unordered: bool, }, /// A structured or typed buffer view whose host buffer is not the one /// the bytes are found in now. Unknown, } /// Whether `view` is for unordered access. fn view_is_unordered(view: &View) -> bool { matches!(view, View::Unordered(..) | View::Placed(true, ..)) } /// The bytes of its host copy the structured or typed buffer view `view` /// reads: as [`make`] places it (`kept`: the resource it made the view on), /// from the first element's byte in the copy for the view's length. fn viewed_bytes(view: &View, kept: Option<&ID3D12Resource>) -> Viewed { use windows::core::Interface; const BUFFER: u32 = 1; // The title buffer's address and length, and the view's description. let (base, len, words, unordered): (u64, u64, &[u32; 10], bool) = match view { View::Shader(r, Some(desc)) | View::Unordered(r, _, Some(desc)) => { let r = *r as crate::object::This; if crate::resource::host_resource(r).is_some() { return Viewed::Own; } let Some((data, len)) = crate::resource::buffer_bytes(r) else { return Viewed::Own; }; (data as u64, len, desc, view_is_unordered(view)) } View::Placed(unordered, resource, desc) if resource[0] == BUFFER => { let Ok(words) = desc[..10].try_into() else { return Viewed::Own; }; ( u64::from(desc[10]) | u64::from(desc[11]) << 32, u64::from(resource[4]) | u64::from(resource[5]) << 32, words, *unordered, ) } _ => return Viewed::Own, }; // (first element, elements, bytes per element), none for a raw view. let elements = if unordered { let desc = uav_desc(words); // SAFETY: a buffer view's union member. let b = unsafe { desc.Anonymous.Buffer }; (b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 == 0) .then(|| (b.FirstElement, b.NumElements, uav_element_size(&desc).unwrap_or(0))) } else { let desc = srv_desc(words); // SAFETY: a buffer view's union member. let b = unsafe { desc.Anonymous.Buffer }; (b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 == 0) .then(|| (b.FirstElement, b.NumElements, element_size(&desc))) }; let Some((first, count, element)) = elements else { return Viewed::Own; }; let (Some(kept), Some(shadow)) = (kept, crate::shadow::find(base, len)) else { return Viewed::Unknown; }; if element == 0 || shadow.buffer.as_raw() != kept.as_raw() { return Viewed::Unknown; } Viewed::Bytes { buffer: shadow.buffer.clone(), start: shadow.offset(base) + first * element, len: u64::from(count) * element, unordered, } } /// Element byte stride of `view` for the runtime stride table (`0` for /// non-buffer views or descriptors without a known element size). fn view_stride(view: &View) -> u32 { let bytes = match view { View::Shader(_, Some(desc)) => element_size(&srv_desc(desc)), View::Placed(false, resource, desc) if resource[0] == 1 => desc[..10] .try_into() .ok() .map_or(0, |w: &[u32; 10]| element_size(&srv_desc(w))), View::Unordered(_, _, Some(desc)) => uav_element_size(&uav_desc(desc)).unwrap_or(0), View::Placed(true, resource, desc) if resource[0] == 1 => desc[..10] .try_into() .ok() .and_then(|w: &[u32; 10]| uav_element_size(&uav_desc(w))) .unwrap_or(0), _ => 0, }; u32::try_from(bytes).unwrap_or(0) } /// [`buffer_range`] of an unordered access view of memory at `base`. fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> { let desc = uav_desc(words); // SAFETY: a buffer view's union member. let buffer = unsafe { desc.Anonymous.Buffer }; let element = uav_element_size(&desc)?; Some(( base + buffer.FirstElement * element, u64::from(buffer.NumElements) * element, )) } /// What a slot made by [`make`] views: nothing of the host's, the resource it /// made the view on, or an aligned copy of the bytes a structured view reads. enum Kept { Empty, Resource(ID3D12Resource), Unaligned(UnalignedCopy), } fn buffer_srv( address: u64, len: u64, mut desc: D3D12_SHADER_RESOURCE_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE, ) -> Option { let shadow = crate::shadow::find(address, len)?; let element = element_size(&desc); // SAFETY: a buffer view's union member. let buffer = unsafe { &mut desc.Anonymous.Buffer }; let offset = shadow.offset(address); let host = host()?; if element == 0 { once!( offset, element, "buffer view not on an element of its host copy" ); return None; } if offset % element != 0 { // The title's placed buffer starts at an address that is not a // multiple of `element` inside our larger host shadow buffer (e.g. a // non-power-of-two structured element stride inside a ring buffer). // Copy the viewed bytes into a persistently mapped aligned upload // buffer starting at element 0, and track it so draws refresh it from // title memory at submission time. let view_offset = buffer.FirstElement.checked_mul(element)?; let room = shadow.left(address).checked_sub(view_offset)? / element; let elements = if buffer.NumElements == 0 { u32::try_from(room.min(u64::from(u32::MAX))).ok()? } else { buffer.NumElements.min(u32::try_from(room).unwrap_or(u32::MAX)) }; if elements == 0 { return None; } buffer.NumElements = elements; let bytes = u64::from(elements).checked_mul(element)?; const MAX_UNALIGNED_COPY: u64 = 1 << 20; if bytes == 0 || bytes > MAX_UNALIGNED_COPY { once!( offset, element, "buffer view not on an element of its host copy" ); return None; } let start = address.checked_add(view_offset)?; let (upload, dst) = host.upload_buffer(bytes)?; crate::host::copy_mapped(dst, start as *const u8, bytes as usize, false); buffer.FirstElement = 0; // SAFETY: a live upload buffer and a slot of our heap. unsafe { host.device .CreateShaderResourceView(&upload, Some(&desc), at) }; return Some(Kept::Unaligned(UnalignedCopy { resource: upload, dst: dst as usize, src: start as usize, len: bytes as usize, })); } buffer.FirstElement += offset / element; let remaining = shadow.left(address) / element; buffer.NumElements = if buffer.NumElements == 0 { remaining as u32 } else { buffer.NumElements.min(remaining as u32) }; if buffer.NumElements == 0 { return None; } // SAFETY: a live buffer and a slot of our heap. unsafe { host.device .CreateShaderResourceView(&shadow.buffer, Some(&desc), at) }; Some(Kept::Resource(shadow.buffer.clone())) } /// An unordered access view of title buffer memory at `address` (`len` /// bytes) on its host copy, as [`buffer_srv`]; false if the copy cannot be /// written by shaders (upload memory). /// shortcut: what shaders write stays in the host copy; title memory (and /// so the CPU, and copies run on the CPU) does not see it. fn buffer_uav( address: u64, len: u64, mut desc: D3D12_UNORDERED_ACCESS_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE, ) -> Option { let shadow = crate::shadow::find(address, len)?; // SAFETY: a live buffer. let flags = unsafe { shadow.buffer.GetDesc() }.Flags; if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { once!("unordered access to a buffer whose host copy shaders cannot write"); return None; } // SAFETY: a buffer view's union member. let buffer = unsafe { &mut desc.Anonymous.Buffer }; let element = if buffer.StructureByteStride > 0 { u64::from(buffer.StructureByteStride) } else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { 4 } else { crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes) }; let offset = shadow.offset(address); if element == 0 || offset % element != 0 { once!( offset, element, "unordered buffer view not on an element of its host copy" ); return None; } buffer.FirstElement += offset / element; buffer.CounterOffsetInBytes = 0; let remaining = shadow.left(address) / element; buffer.NumElements = if buffer.NumElements == 0 { remaining as u32 } else { buffer.NumElements.min(remaining as u32) }; if buffer.NumElements == 0 { return None; } let host = host()?; // SAFETY: a live buffer and a slot of our heap. unsafe { host.device.CreateUnorderedAccessView( &shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at, ) }; Some(Kept::Resource(shadow.buffer.clone())) } /// Whether the host can make a shader (or unordered access) view of /// `texture` in `format` (none: the texture's own). The console allows any /// view; the host refuses (and removes the device for) views without the /// resource's permission, of typed depth, and in another format than a /// typed resource's. A view of a typed texture in another format of its /// family takes the texture's format. /// shortcut: such a view (sRGB of UNORM, say) reads without its /// conversion; cast with castable formats if colors come out wrong. fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordered: bool) -> bool { use crate::resource::{DEPTH_FORMATS, family}; // SAFETY: a live resource. let d = unsafe { texture.GetDesc() }; let allowed = if unordered { d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0 } else { d.Flags.0 & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE.0 == 0 }; let own = d.Format.0 as u32; if !allowed || DEPTH_FORMATS.iter().any(|&(typed, _)| typed == own) { once!( unordered, format = own, flags = d.Flags.0, "view the host does not allow" ); return false; } // Every family has more than one format, its typeless one first. let typeless = family(own) == own && family(own + 1) == own; if let Some(format) = format.as_deref_mut() && unordered && let Some(&(_, linear)) = crate::resource::SRGB .iter() .find(|&&(s, _)| s == format.0 as u32) { format.0 = linear as i32; } let view = format.as_ref().map_or(0, |f| f.0 as u32); if view == 0 { return !typeless; } if family(view) != family(own) { once!(view, own, "view format of another family"); return false; } if let Some(format) = format && !typeless { *format = d.Format; } 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 { let host = host()?; let device = &host.device; match view { &View::Constant(address, size) => { let shadow = crate::shadow::find(address, u64::from(size))?; let gpu = shadow.gpu(address); if gpu % 256 != 0 { once!( address = format_args!("{address:#x}"), "constant buffer not 256-byte aligned on the host" ); return None; } let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { BufferLocation: gpu, SizeInBytes: size.next_multiple_of(256), }; // SAFETY: a slot of our heap; the range lies in the host copy. unsafe { device.CreateConstantBufferView(Some(&desc), at) }; Some(Kept::Resource(shadow.buffer.clone())) } 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(Kept::Resource(texture.clone())) } else if let (Some((data, len)), Some(desc)) = (crate::resource::buffer_bytes(resource), desc) { buffer_srv(data as u64, len, srv_desc(desc), at) } else { None } } View::Unordered(resource, _counter, desc) => { let resource = *resource as crate::object::This; let Some(texture) = crate::resource::host_resource(resource) else { return match (crate::resource::buffer_bytes(resource), desc) { (Some((data, len)), Some(desc)) => { buffer_uav(data as u64, len, uav_desc(desc), at) } _ => 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(Kept::Resource(texture.clone())) } View::Sampler(words) => { // SAFETY: 13 words in the host's layout. let desc = unsafe { std::ptr::from_ref(words) .cast::() .read_unaligned() }; // SAFETY: a slot of our sampler heap. unsafe { device.CreateSampler(&desc, at) }; Some(Kept::Empty) } View::ConsoleSampler(words) => { let desc = crate::sampler::console(words); // SAFETY: a slot of our sampler heap. unsafe { device.CreateSampler(&desc, at) }; Some(Kept::Empty) } View::Placed(unordered, resource, desc) => { if let Some(view) = placed_texture(view) { return make(&view, at); } const BUFFER: u32 = 1; if resource[0] != BUFFER { // 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" ); return None; } // The resource description's width, after the alignment. let len = u64::from(resource[4]) | u64::from(resource[5]) << 32; let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; let words: &[u32; 10] = desc[..10].try_into().unwrap_or(&[0; 10]); if *unordered { buffer_uav(address, len, uav_desc(words), at) } else { buffer_srv(address, len, srv_desc(words), at) } } } } /// A shader view of a texture the title placed in memory itself, as a view /// of the resource made for that memory (on first use). pub(crate) fn placed_texture(view: &View) -> Option { const BUFFER: u32 = 1; let View::Placed(false, resource, desc) = view else { return None; }; if resource[0] == BUFFER { return None; } let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; let texture = crate::resource::texture_at(address, resource)?; Some(View::Shader(texture as usize, desc[..10].try_into().ok())) } /// 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. fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { let Some(host) = host() else { return }; let is_buffer = |r: &usize| crate::resource::buffer_bytes(*r as crate::object::This).is_some(); // Unordered views: whether a buffer, and the title's view dimension. let (buffer, dimension) = match view { View::Unordered(r, _, desc) => ( is_buffer(r) || desc.is_some_and(|d| d[1] == 1), desc.map(|d| d[1]), ), View::Placed(true, resource, desc) => (resource[0] == 1, Some(desc[1])), // Shader views of buffers read nothing through a null buffer view: // a null 2D view where the shader expects a buffer is a mismatch // the hardware does not survive in general (GPU-based validation // reports it). View::Shader(r, desc) if is_buffer(r) || desc.is_some_and(|d| d[1] == 1) => { return null_buffer_view(at); } View::Placed(false, resource, _) if resource[0] == 1 => return null_buffer_view(at), // Textures: a null view of the title's dimension (1D, arrays, 3D, // cubes), not always 2D. View::Shader(_, Some(desc)) => return null_like(desc, at), View::Placed(false, _, desc) => { return null_like(desc[..10].try_into().unwrap_or(&[0; 10]), at); } View::Constant(..) => { let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC::default(); // 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), }; let desc = if buffer { D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R32_UINT, ViewDimension: D3D12_UAV_DIMENSION_BUFFER, ..Default::default() } } else { null_uav_desc(dimension) }; // SAFETY: a slot of our heap; a null resource is allowed with a desc. unsafe { host.device.CreateUnorderedAccessView( None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&desc), at, ) }; } /// A null texture UAV of the title's view dimension (1D, 1D or 2D arrays, /// 3D), 2D if it names none: a 2D null view where the shader writes a 3D /// texture is a mismatch GPU-based validation reports (the world's wind /// field, CS_CopyWindFieldBeforeUpdateWithSmooth, 2026-11-24). fn null_uav_desc(dimension: Option) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { let mut desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R32_UINT, ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, ..Default::default() }; match dimension.map(|d| D3D12_UAV_DIMENSION(d as i32)) { Some(D3D12_UAV_DIMENSION_TEXTURE1D) => { desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; } Some(D3D12_UAV_DIMENSION_TEXTURE1DARRAY) => { desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY; desc.Anonymous.Texture1DArray = D3D12_TEX1D_ARRAY_UAV { ArraySize: 1, ..Default::default() }; } Some(D3D12_UAV_DIMENSION_TEXTURE2DARRAY) => { desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; desc.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV { ArraySize: 1, ..Default::default() }; } Some(D3D12_UAV_DIMENSION_TEXTURE3D) => { desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; desc.Anonymous.Texture3D = D3D12_TEX3D_UAV { WSize: u32::MAX, ..Default::default() }; } _ => {} } desc } /// A buffer view that reads zeros (raw, as translated shaders mostly read /// buffers). /// A raw buffer view with unordered access of `elements` dwords from dword /// `first`. fn raw_uav_desc(first: u64, elements: u32) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R32_TYPELESS, ViewDimension: D3D12_UAV_DIMENSION_BUFFER, Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Buffer: D3D12_BUFFER_UAV { FirstElement: first, NumElements: elements, StructureByteStride: 0, CounterOffsetInBytes: 0, Flags: D3D12_BUFFER_UAV_FLAG_RAW, }, }, } } fn null_buffer_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { let Some(host) = host() else { return }; let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT_R32_TYPELESS, ViewDimension: D3D12_SRV_DIMENSION_BUFFER, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Buffer: D3D12_BUFFER_SRV { NumElements: 1, Flags: D3D12_BUFFER_SRV_FLAG_RAW, ..Default::default() }, }, }; // SAFETY: a slot of our heap; a null resource is allowed with a desc. unsafe { host.device .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at) }; } /// A raw unordered access view of a buffer that drops writes and reads /// zeros. fn null_raw_uav(at: D3D12_CPU_DESCRIPTOR_HANDLE) { let Some(host) = host() else { return }; let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R32_TYPELESS, ViewDimension: D3D12_UAV_DIMENSION_BUFFER, Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Buffer: D3D12_BUFFER_UAV { NumElements: 1, Flags: D3D12_BUFFER_UAV_FLAG_RAW, ..Default::default() }, }, }; // SAFETY: a slot of our heap; a null resource is allowed with a desc. unsafe { host.device.CreateUnorderedAccessView( None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&desc), at, ) }; } /// 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) { const TEXTURES: std::ops::RangeInclusive = 2..=10; if !TEXTURES.contains(&words[1]) { return null_view(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]; match words[1] { 6 => {} 7 => w[5] = 1, 3 | 5 | 10 => (w[5], w[7]) = (1, 1), _ => w[5] = 1, } let mut desc = srv_desc(&w); desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; // SAFETY: a slot of our heap; a null resource is allowed with a desc. unsafe { host.device .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at) }; } /// A view that reads zeros, for slots whose view the host cannot make. /// 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 }; let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT_R8G8B8A8_UNORM, 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() }, }, }; // SAFETY: a slot of our heap; a null resource is allowed with a desc. unsafe { host.device .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at) }; } #[cfg(test)] mod tests { use super::*; /// 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] fn null_uavs_keep_the_titles_dimension() { let d = null_uav_desc(Some(8)); assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE3D); // SAFETY: the member the dimension names. assert_eq!(unsafe { d.Anonymous.Texture3D.WSize }, u32::MAX); let d = null_uav_desc(Some(5)); assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE2DARRAY); // SAFETY: the member the dimension names. assert_eq!(unsafe { d.Anonymous.Texture2DArray.ArraySize }, 1); let dimension = |d| null_uav_desc(d).ViewDimension; assert_eq!(dimension(Some(2)), D3D12_UAV_DIMENSION_TEXTURE1D); assert_eq!(dimension(Some(4)), D3D12_UAV_DIMENSION_TEXTURE2D); assert_eq!(dimension(None), D3D12_UAV_DIMENSION_TEXTURE2D); // Multisampled UAVs need a cap; they stay 2D. assert_eq!(dimension(Some(6)), D3D12_UAV_DIMENSION_TEXTURE2D); } /// A null 3D UAV made on the real device leaves it alive. #[test] fn null_3d_uav_is_accepted_by_the_device() { let Some(host) = host() else { return; // no host GPU }; let Some(heap) = HostHeap::new(false, 4) else { return; }; let view = View::Unordered(0, 0, Some([28, 8, 0, 0, 0, 0, 0, 0, 0, 0])); null_for(&view, heap.cpu(0)); // SAFETY: a plain device query. assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); } /// Dynamic slots stay taken until given back, and runs do not wrap. #[test] fn dynamic_slots_are_held_until_released() { let Some(heap) = HostHeap::new(false, 4) else { return; // no host GPU }; let a = heap.dynamic(heap.dynamic - 100).unwrap(); let b = heap.dynamic(60).unwrap(); assert_eq!((a, b), (4, 4 + heap.dynamic - 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); assert_eq!(heap.dynamic(50), Some(4)); assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); } /// A structured buffer SRV whose offset inside its shadow buffer is not a /// multiple of its element stride is copied into an aligned upload buffer /// and refreshed from title memory when a command list referencing the slot /// is submitted. #[test] fn unaligned_structured_buffer_srv_refreshes_on_submission() { let Some(host) = host() else { return; // no host GPU }; let Some(heap) = HostHeap::new(false, 4) else { return; }; let mut backing: Vec = (0..4096usize).map(|i| (i % 251) as u8).collect(); let base = backing.as_ptr() as u64; crate::shadow::register(base as usize, base, backing.len() as u64); // Offset 32 is not a multiple of stride 24 (32 % 24 == 8). let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT_UNKNOWN, ViewDimension: D3D12_SRV_DIMENSION_BUFFER, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Buffer: D3D12_BUFFER_SRV { FirstElement: 0, NumElements: 1, StructureByteStride: 24, Flags: D3D12_BUFFER_SRV_FLAG_NONE, }, }, }; let kept = buffer_srv(base + 32, 24, desc, heap.cpu(0)) .expect("unaligned structured SRV should succeed"); let (upload, dst) = match &kept { Kept::Unaligned(copy) => (copy.resource.clone(), copy.dst as *const u8), _ => panic!("expected an unaligned upload copy"), }; heap.keep(0, kept); // Mutate the title slice *after* creating the view (as a ring buffer does). let updated: [u8; 24] = std::array::from_fn(|i| 0xA0u8.wrapping_add(i as u8)); backing[32..56].copy_from_slice(&updated); let list = host.new_list().expect("host command list"); heap.refresh_slot(0, &list); list.close(); host.execute(&[&list]); crate::shadow::unregister(base as usize, base); // SAFETY: `upload` is persistently mapped for its lifetime (`24` bytes) // and `host.execute` has completed. unsafe { assert_eq!(upload.GetDesc().Width, 24); let got = std::slice::from_raw_parts(dst, 24); assert_eq!(got, &updated); assert!(host.device.GetDeviceRemovedReason().is_ok()); } } }