//! 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::sync::Mutex; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; use super::{VIEW_TAG, View, view_at}; use crate::host::host; /// How the "title slot past the host heap" line reads (`VICTORY_SLOT_DIAG`, /// read once at start-up). #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(crate) enum SlotDiag { /// The first slot past the heap says it, and no other. The title walks /// its slots in increasing order, so a line per new high-water mark is a /// line per slot: 199 846 of the first 200 000 lines of a run, ~8 000 a /// second, on the thread recording the frame - the whole of the first /// frame's 21 s stall (Marvisak/VIctory#2634). Once, /// One line per slot, as before: for a run that has to count them. All, /// Silent. Off, } impl SlotDiag { /// `VICTORY_SLOT_DIAG`: unset or `once` reads once, `all` reads every /// slot (the old way), `0` or `off` reads none. fn parse(value: Option<&str>) -> Self { match value { None | Some("once") => Self::Once, Some("all") => Self::All, Some("0" | "off") => Self::Off, Some(_) => Self::Once, } } /// The mode this process runs with. fn now() -> Self { static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); *MODE.get_or_init(|| Self::parse(std::env::var("VICTORY_SLOT_DIAG").ok().as_deref())) } } /// Says the "slot past the host heap" line for `index` in `mode`, reusing /// `once` to say it once per process (a `static` at the call site; a value of /// its own in the tests). fn say_slot_past( once: &std::sync::Once, mode: SlotDiag, index: u32, count: u32, for_draw: bool, ) { let says = match mode { SlotDiag::Off => false, SlotDiag::All => true, SlotDiag::Once => { let mut says = false; once.call_once(|| says = true); says } }; if says { tracing::warn!( index, count, for_draw, "title slot past the host heap: slots above the host heap's count are not mirrored" ); } } 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`: [`DYNAMIC`] in view heaps, none in /// sampler heaps. (Upstream falls back to 2^16 on a capped host heap; /// ours keeps 2^18 there: 2^16 and 2^17 both ran out in this title.) dynamic: u32, sampler: bool, /// The record (view index and generation) each slot was last made from. made: Mutex>, /// [`HostHeap::made`] again in atomics, for the hit path of /// [`HostHeap::mirror`]: the same key stored under the lock with Release, /// so a slot already made from the record a draw names is recognised /// without taking it. A slot is made once and then read by every draw and /// every pass in between, so the lock was being taken for a lookup that /// almost always found the slot up to date. made_fast: Vec, /// The slots made from a view narrowed to a part-resident texture's mips /// ([`narrow_to_resident`]): the texture, the mips the title asked for /// and those the host view names. More levels arriving (or a host copy /// filling the chain) wants a wider window than the slot shows, and the /// title's descriptor does not change, so `mirror` remakes these itself /// (JMAN730/victory#672). `narrowed_count` says whether any is (read /// without the lock on the mirror of every slot). narrowed: Mutex>, narrowed_count: std::sync::atomic::AtomicUsize, /// 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>>, /// Where the search for free dynamic slots starts, and which are taken /// (by lists not yet reset). next: Mutex<(u32, Vec)>, /// How many dynamic slots are free (changed under `next`'s lock): with /// fewer than a table needs, the search is not made. Once the world /// had taken them all, every later table of the frame searched every /// slot before it was refused. free: std::sync::atomic::AtomicU32, /// The shortest table that found no run of free slots since slots were /// last given back (changed under `next`'s lock; `u32::MAX`: none). /// Until something is given back the free runs only shrink, so a table /// of that length or longer is refused without the search. Enough /// slots were free, but in pieces, and every such table walked the /// whole ring before it was refused: 0.33 ms each with 131,072 slots, /// 1.0 s of the recording threads in a frame that refused 3,143 (run /// 45), under the lock all of them need. (A free run that lies across /// the place the search starts from is seen by neither.) too_long: std::sync::atomic::AtomicU32, /// View heaps: the bytes per element of the buffer view at each title /// slot, for shaders that pick a buffer by an index they compute /// (`victory_shader::emit::SLOT_STRIDES`): an upload buffer of /// `SLOT_STRIDES_COUNT` dwords, its GPU address and its mapping. strides: Option<(ID3D12Resource, u64, usize)>, /// Title slots holding buffer views. Such a view gets its host slot /// (and its memory a host copy) only when something reads it: a draw /// through a table, or [`HostHeap::buffer_slots`] for shaders that pick /// buffers from the whole heap. buffers: Mutex>, /// Of those and of the slots that left the set: the ones written since /// [`HostHeap::buffer_changes`] last took them. changed: Mutex>, /// Title slots holding a view of a texture the title may fill itself (a /// placed texture, a texture object), with the frame from which they /// are due: such a texture is uploaded when a draw reads it through a /// table; one a shader picks by a computed index is brought up to date /// from here ([`HostHeap::texture_slots_due`]). textures: Mutex, /// Per title slot, the frame (plus one; 0: never) in which a draw last /// read it through a table, or made a table it lies in (with /// [`TABLED_READ`] set if the draw read it). The draw that /// reads such a slot brings its texture up to date itself and the slot /// then leaves `textures`; a write of a slot that was a table's within /// the last [`TABLED_FRAMES`] frames is due only [`TABLED_GRACE`] /// frames later, by when its draw has read it. A title that builds a /// table per draw writes thousands of texture views a frame into slots /// only tables read (the title: some 2,500 a frame in its /// opening cutscene, a few hundred textures over and over), and every /// one of them stood in the queue of textures picked by index, ahead /// of or behind the ones shaders do pick by index. tabled: Vec, /// The title memory each placed texture view of this heap describes, /// by slot and by address ([`Spans`]): which slots a newer view of /// other memory there makes stale, and which to look at again when the /// runtime maps, unmaps or writes memory ([`remapped`]). placed: Mutex, } /// Title memory by the placed texture views that describe it: per span of /// memory (its start, its end) the title slots holding a view of a /// texture that takes exactly that span. Spans never overlap: a console /// title need not clear a descriptor when it streams a texture out, so a /// view written over memory that older views describe otherwise (another /// start or another length: another texture) is all that says the older /// ones are stale. Views of one span with different descriptions (the /// formats of one family, say) are one texture's. /// No host heap is needed, so it is tested without one. #[derive(Default)] pub(crate) struct Spans { by_start: std::collections::BTreeMap)>, by_slot: std::collections::HashMap, /// The bytes a placed texture takes, by resource description: worked /// out once for each (a title writes the views of a few thousand /// descriptions, thousands of times a frame). sizes: std::collections::HashMap<[u32; 14], Option>, } impl Spans { /// The bytes of title memory a placed texture with the resource /// description `desc` takes (`crate::resource::placed_bytes`). fn bytes(&mut self, desc: &[u32; 14]) -> Option { if let Some(&known) = self.sizes.get(desc) { return known; } let bytes = crate::resource::placed_bytes(desc); self.sizes.insert(*desc, bytes); bytes } /// The starts of the spans that overlap `[start, end)`. fn overlapping(&self, start: u64, end: u64) -> Vec { let before = self .by_start .range(..start) .next_back() .filter(|(_, span)| span.0 > start) .map(|(at, _)| *at); before.into_iter().chain(self.by_start.range(start..end).map(|(at, _)| *at)).collect() } /// Slot `index` holds a view of a texture in `[start, end)`. `newer`: /// the title wrote it now, so the slots whose views describe that /// memory otherwise are stale: they are returned, and forgotten. /// Otherwise (a draw made the slot from what it held) a view that /// overlaps other spans is left out. fn note(&mut self, index: u32, start: u64, end: u64, newer: bool) -> Vec { let same = |span: Option<&(u64, std::collections::BTreeSet)>| span.is_some_and(|s| s.0 == end); if self.by_slot.get(&index) == Some(&start) && same(self.by_start.get(&start)) { return Vec::new(); } self.forget(index); if end <= start { return Vec::new(); } let mut stale = Vec::new(); for at in self.overlapping(start, end) { if at == start && same(self.by_start.get(&at)) { continue; } if !newer { return stale; } if let Some((_, slots)) = self.by_start.remove(&at) { for slot in slots { self.by_slot.remove(&slot); stale.push(slot); } } } self.by_start.entry(start).or_insert_with(|| (end, Default::default())).1.insert(index); self.by_slot.insert(index, start); stale } /// Slot `index` holds no placed texture view any more. fn forget(&mut self, index: u32) { let Some(start) = self.by_slot.remove(&index) else { return; }; if let Some(span) = self.by_start.get_mut(&start) { span.1.remove(&index); if span.1.is_empty() { self.by_start.remove(&start); } } } /// The slots whose texture's memory overlaps `[start, end)`. fn slots_in(&self, start: u64, end: u64) -> Vec { self.overlapping(start, end) .iter() .filter_map(|at| self.by_start.get(at)) .flat_map(|span| span.1.iter().copied()) .collect() } } /// Title memory the runtime mapped, unmapped or is about to write since a /// texture pass last took the ranges ([`remapped`]). static REMAPPED: Mutex> = Mutex::new(Vec::new()); /// The lowest start and the highest end of any span of [`Spans`] so far /// (the start is `u64::MAX` until there is one): what the runtime does to /// memory outside is none of the texture pass's business. static SPANNED: [std::sync::atomic::AtomicU64; 2] = [ std::sync::atomic::AtomicU64::new(u64::MAX), std::sync::atomic::AtomicU64::new(0), ]; /// Since the start: slots whose view a newer view of other memory there /// made stale; ranges of memory noted as mapped, unmapped or written; /// ranges dropped because no pass took them; slots made due by such /// ranges; and made slots whose memory was found unmapped (made null). pub(crate) static STALE: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; /// Whether a view written over memory that older views describe otherwise /// makes those stale; `VICTORY_STALE_TEXTURES=0` leaves them as they are. fn stale_out() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("VICTORY_STALE_TEXTURES").is_none_or(|v| v != "0")) } /// The runtime mapped or unmapped title memory `[at, at + len)`, or is /// about to write it through the kernel (`crate::watch`): the placed /// textures there may have arrived, gone, or changed with no descriptor /// written. The range is kept for the next texture pass /// ([`HostHeap::texture_slots_remapped`]). Called with the runtime's own /// locks held: this locks one mutex of its own and calls nothing. pub(crate) fn remapped(at: usize, len: usize) { use std::sync::atomic::Ordering::Relaxed; /// Ranges kept until a pass takes them. const MOST: usize = 1 << 15; let (start, end) = (at as u64, at.saturating_add(len) as u64); if end <= SPANNED[0].load(Relaxed) || start >= SPANNED[1].load(Relaxed) { return; } let mut ranges = REMAPPED.lock().unwrap_or_else(|e| e.into_inner()); STALE[1].fetch_add(1, Relaxed); // Pages are mapped one after the other. if let Some(last) = ranges.last_mut() && last.1 == start { last.1 = end; return; } if ranges.len() >= MOST { // No pass runs (no shader that picks textures by index is bound): // the slots there are looked at when they are due, as before. STALE[2].fetch_add(ranges.len() as u64, Relaxed); ranges.clear(); } ranges.push((start, end)); } /// Frames for which a slot a draw read through a table counts as a table's /// slot ([`HostHeap::tabled`]). const TABLED_FRAMES: u64 = 240; /// Frames a write of a table's slot waits in the queue for the draw that /// reads it, before the slot is taken for one shaders pick by index. /// Frames as `crate::frame::current` counts them: in its opening cutscene /// The title begins two or three of them per frame it presents /// (435 begun in the 353 s of run 52's, for some 140 presented). const TABLED_GRACE: u64 = 8; /// In [`HostHeap::tabled`]: a draw read the slot in that frame. const TABLED_READ: u32 = 1 << 31; /// Since the start: writes of texture views into slots that count as a /// table's (due later), and slots that left the queue because a draw read /// them through a table. pub(crate) static TABLED_WRITES: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; /// Whether slots draws read through tables leave the queue of textures /// picked by index; `VICTORY_TABLED_TEXTURES=1` keeps them in it as /// before. fn tabled_out() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("VICTORY_TABLED_TEXTURES").is_none_or(|v| v != "1")) } /// What the queue of textures picked by index knows of a title slot. #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct Waiting { /// The frame from which the slot is due. due: u64, /// The frame it was written in. written: u64, /// Which write of the queue put it here: the pass hands it back with /// what it did, so a slot written again meanwhile stays as written. write: u64, /// Looks in a row that found nothing to upload (its memory not mapped, /// or no more of it than at the last upload). looks: u8, /// Bytes of its memory that were mapped when it was last uploaded /// without all of it there; 0: not uploaded yet. mapped: u64, /// For a slot uploaded whole and looked at again /// ([`TextureQueue::recheck`]): where its memory is (address, bytes), /// the fingerprint it had at the upload, how many looks found it /// unchanged, and the frame of the upload. A fingerprint of 0: none. checked: (u64, u64, u64, u8, u64), } /// The queue of title slots whose texture view waits to be brought up to /// date for shaders that pick textures by index: which are due, and in /// which order (no host heap needed, so it is tested without one). #[derive(Default)] pub(crate) struct TextureQueue { slots: std::collections::BTreeMap, writes: u64, } impl TextureQueue { /// A texture view was written into slot `index` in `frame`, due from /// frame `due`. `seen`: it was not written, a draw or the pass made /// the host slot from a view the queue may hold already, which then /// stays as it is. fn written(&mut self, index: u32, frame: u64, due: u64, seen: bool) { if seen && self.slots.contains_key(&index) { return; } self.writes += 1; let write = self.writes; self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) }); } fn remove(&mut self, index: u32) { self.slots.remove(&index); } /// Up to `max` slots due at `frame`, each with its write number, in /// the order to serve them: /// - first the ones looked at before (their memory was not mapped, or /// only part of it): the look is a query, and memory that has /// arrived since is what the title streamed in last; /// - then the others, the newest write first and the oldest next, in /// turns: slot order served the low slots of a backlog of /// 25,000-40,000 while the textures of the shot on screen waited /// (run 52: 98% of the drawn pixels had no colour texture in the /// first 3D frames). fn due(&self, frame: u64, max: usize) -> Vec<(u32, u64)> { let mut again: Vec<(u64, u32, u64)> = Vec::new(); let mut fresh: Vec<(u64, u32, u64)> = Vec::new(); for (&index, w) in self.slots.iter().filter(|(_, w)| w.due <= frame) { let class = if w.looks > 0 || w.mapped > 0 { &mut again } else { &mut fresh }; class.push((w.written, index, w.write)); } // By the number of the write, counted over the run. let newest_first = |a: &(u64, u32, u64), b: &(u64, u32, u64)| b.2.cmp(&a.2); again.sort_unstable_by(newest_first); fresh.sort_unstable_by(newest_first); let mut order: Vec<(u32, u64)> = again.iter().map(|&(_, index, write)| (index, write)).collect(); let (mut new, mut old) = (0, fresh.len()); while new < old && order.len() < max { order.push((fresh[new].1, fresh[new].2)); new += 1; if new < old && order.len() < max { old -= 1; order.push((fresh[old].1, fresh[old].2)); } } order.truncate(max); order } /// The entry of `index` if it is still the write the pass was handed. fn same(&mut self, index: u32, write: u64) -> Option<&mut Waiting> { self.slots.get_mut(&index).filter(|w| w.write == write) } /// Slot `index` is up to date: out of the queue until written again. fn done(&mut self, index: u32, write: u64) { if self.same(index, write).is_some() { self.slots.remove(&index); } } /// Nothing to upload at slot `index` now: looked at again after 1, 2, /// 4, ... frames, at most `most`. fn later(&mut self, index: u32, write: u64, frame: u64, most: u64) { if let Some(w) = self.same(index, write) { w.due = frame + (1u64 << w.looks.min(16)).min(most.max(1)); w.looks = w.looks.saturating_add(1); } } /// Slot `index` was uploaded with `mapped` bytes of its memory there, /// not all of it: looked at again from frame `due`. fn partly(&mut self, index: u32, write: u64, due: u64, mapped: u64) { if let Some(w) = self.same(index, write) { (w.due, w.looks, w.mapped) = (due, 0, mapped.max(1)); } } /// Slot `index` was uploaded whole from memory `at` (address, bytes) /// with fingerprint `print`: looked at again from frame `due`, for a /// title that fills a texture's memory after it wrote the view (the /// `looks`-th such look; `uploaded` is the upload's frame). #[allow(clippy::too_many_arguments)] fn recheck(&mut self, index: u32, write: u64, due: u64, at: (u64, u64), print: u64, looks: u8, uploaded: u64) { if let Some(w) = self.same(index, write) { (w.due, w.looks, w.mapped) = (due, 1, 0); w.checked = (at.0, at.1, print, looks, uploaded); } } /// What [`TextureQueue::recheck`] noted of slot `index`, if it is /// waiting for such a look. fn checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> { self.slots.get(&index).map(|w| w.checked).filter(|c| c.2 != 0) } /// The memory slot `index`'s texture lies in was mapped, unmapped or /// written in `frame`: the slot is looked at from frame `due` as one /// written now, whatever was known of it (a pass at work on it does /// not take it out). fn changed(&mut self, index: u32, frame: u64, due: u64) { self.writes += 1; let write = self.writes; let due = self.slots.get(&index).map_or(due, |w| w.due.min(due)); self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) }); } /// Bytes of slot `index`'s memory that were mapped at its last upload /// (0: not uploaded, or all of it was). fn mapped(&self, index: u32) -> u64 { self.slots.get(&index).map_or(0, |w| w.mapped) } /// For the frame line: slots in the queue; of them due at `frame`; /// waiting for their memory (looked at, never uploaded); uploaded in /// part; and the frames the oldest due one has waited since its write. fn census(&self, frame: u64) -> [u64; 5] { let mut c = [self.slots.len() as u64, 0, 0, 0, 0]; for w in self.slots.values() { if w.mapped > 0 { c[3] += 1; } else if w.looks > 0 { c[2] += 1; } if w.due <= frame { c[1] += 1; c[4] = c[4].max(frame.saturating_sub(w.written)); } } c } } /// Whether `view` is of a texture the title may fill itself: a texture it /// placed in memory, or a texture object. pub(crate) fn is_texture_view(view: &View) -> bool { match view { View::Placed(false, resource, _) => resource[0] != 1, View::Shader(r, _) => crate::resource::buffer_bytes(*r as crate::object::This).is_none(), _ => false, } } /// Buffer views left null because the host would refuse them /// ([`buffer_view_ok`]), since the start. pub(crate) static REFUSED_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); /// Whether the host device is gone, and why (the first time it is asked /// after that): for passes that make many views, to name the one that did /// it. pub(crate) fn device_removed() -> Option { let host = host()?; // SAFETY: a plain query. let reason = unsafe { host.device.GetDeviceRemovedReason() }; reason.err().map(|e| e.to_string()) } /// Writes of title view-heap slots with a placed texture view and with a /// view of a texture object, since the start (diagnostic counts). pub(crate) static PLACED_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); pub(crate) static OBJECT_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); /// Bytes per element of a buffer view, as the console's descriptor holds /// them for indexed reads (structured: the stride; raw: 1, the index is the /// byte; typed: the format's); `None` if `view` is not a buffer view. fn view_stride(view: &View) -> Option { const BUFFER: u32 = 1; let (words, unordered): (&[u32; 10], bool) = match view { View::Shader(_, Some(d)) if d[1] == BUFFER => (d, false), View::Unordered(_, _, Some(d)) if d[1] == BUFFER => (d, true), View::Placed(unordered, resource, d) if resource[0] == BUFFER => { (d[..10].try_into().ok()?, *unordered) } _ => return None, }; // SAFETY: buffer views' union members. let (stride, raw, format) = unsafe { if unordered { let d = uav_desc(words); let b = d.Anonymous.Buffer; (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0, d.Format) } else { let d = srv_desc(words); let b = d.Anonymous.Buffer; (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0, d.Format) } }; Some(if stride > 0 { stride } else if raw { 1 } else { crate::resource::element(format.0 as u32).map_or(0, |(bytes, _)| bytes as u32) }) } /// 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; /// The size of every host view heap on a host that takes more than /// [`PORTABLE_VIEWS`] (AMD): the title's heap (a little over 1,000,000 /// views in the retail game) plus [`DYNAMIC`] fits with room to spare, and /// the last slot is the null slot every view index at or past it reads. const UNCAPPED_VIEWS: u32 = 1 << 21; /// Picks, once, the null slot at the end of every host view heap and tells /// the translator now (`set_view_heap_limit`) instead of when the title's /// heap is made: a shader keeps the limit it was translated with, and the /// title makes 25 pipelines (their shaders translated at once) before it /// makes its view heap. Called before a shader is translated and before a /// view heap is made. /// /// Every host clamps. A host that caps view heaps at [`PORTABLE_VIEWS`] /// (NVIDIA) hung on a view index past the heap; one that does not (AMD /// RDNA3, RX 7900 XT) took a page fault and removed the device on entering /// the world: a compute program read view slot 16,777,088 (0xffff80) of a /// heap of 1,507,328, past its end. Unclamped, that index is undefined on /// any host. pub(crate) fn probe_view_limit() { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { let Some(host) = host() else { return }; let fits = |count: u32| { // SAFETY: plain heap creation; the heap is released at once. let made: windows::core::Result = unsafe { host.device .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: count, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0, }) }; made.is_ok() }; let views = if fits(UNCAPPED_VIEWS) { UNCAPPED_VIEWS } else { PORTABLE_VIEWS }; tracing::info!( views, "host view heaps hold {views} views; view indices are clamped to the null slot at the end from the first shader on" ); victory_shader::emit::set_view_heap_limit(views - 1); }); } /// 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 in the world ("no free dynamic descriptor slots", run 11; /// upstream PR #336 takes 2^18). On a host heap capped at 1,000,000 views /// (NVIDIA) these come out of the title's slots, whose highest seen is /// about 720,000: 2^17 left 868,000 of them, and ran out in the opening /// cutscene (a frame asks for up to 16,000 tables while the frame before /// still holds its own; a draw refused its table read slots never made /// for it, and the card stopped within frames). 2^18 leaves 737,000; a /// table past them is made afresh in these slots like any other. pub(crate) const DYNAMIC: u32 = 1 << 18; /// A slot the host made from a view narrowed to a part-resident texture's /// mips ([`narrow_to_resident`]): the texture, the window the title asked /// for and the one the host view names. #[derive(Clone, Copy)] struct Narrowed { resource: crate::object::This, asked: (u32, u32), } thread_local! { /// What the last [`make`] on this thread narrowed, if anything: taken by /// the slot that made it ([`HostHeap::note_narrowed`]). static LAST_NARROW: std::cell::Cell> = const { std::cell::Cell::new(None) }; } 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 extra = if sampler { 0 } else { DYNAMIC }; // A view heap ends at the null slot shaders clamp view indices to // (`probe_view_limit`), whatever the title's own count: the title's // slots, then the dynamic ones, then null up to and with that slot. if !sampler { probe_view_limit(); } let null = if sampler { 0 } else { victory_shader::emit::view_heap_limit() }; let (heap, count, size) = if null == 0 { match make(count + extra) { Ok(heap) => (heap, count, count + extra), Err(e) => { tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); return None; } } } else { let size = null + 1; let fitted = if count + extra <= null { count } else { // shortcut: descriptors past the host's limit are left out; a title that reaches // them needs remapping. They read the null slot instead. tracing::warn!(count, "host view heap capped at {size}; views past it read a null slot"); null - extra }; match make(size) { Ok(heap) => (heap, fitted, size), Err(e) => { tracing::warn!(error = %e, count, size, "no host view 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(size) * u64::from(step), u64::from(step), sampler, )); let strides = (!sampler) .then(|| { let bytes = u64::from(victory_shader::emit::SLOT_STRIDES_COUNT) * 4; let (buffer, data) = host.upload_buffer(bytes)?; // SAFETY: the buffer's whole mapping; a live buffer. let gpu = unsafe { std::ptr::write_bytes(data, 0, bytes as usize); buffer.GetGPUVirtualAddress() }; crate::host::name(&buffer, || "element strides by view heap slot".to_owned()); Some((buffer, gpu, data as usize)) }) .flatten(); let h = HostHeap { heap, cpu, step, count, dynamic: extra, sampler, made: Mutex::new(vec![0; count as usize]), made_fast: (0..count).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(), narrowed: Mutex::default(), narrowed_count: std::sync::atomic::AtomicUsize::new(0), kept: Mutex::new(vec![None; (count + extra) as usize]), next: Mutex::new((0, vec![false; DYNAMIC as usize])), free: std::sync::atomic::AtomicU32::new(DYNAMIC), too_long: std::sync::atomic::AtomicU32::new(u32::MAX), strides, buffers: Mutex::default(), changed: Mutex::default(), textures: Mutex::default(), tabled: (0..if sampler { 0 } else { count }) .map(|_| std::sync::atomic::AtomicU32::new(0)) .collect(), placed: Mutex::default(), }; // 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, size) { tracing::warn!(error = %e, "host descriptor heap not made null"); } 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; } #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::DynamicAsked, 1); let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); let (next, taken) = &mut *guard; let enough = self.free.load(std::sync::atomic::Ordering::Relaxed) >= n && n < self.too_long.load(std::sync::atomic::Ordering::Relaxed); 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.take(if enough { DYNAMIC as usize } else { 0 }) { // 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 { if enough { self.too_long.fetch_min(n as u32, std::sync::atomic::Ordering::Relaxed); } 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")); #[cfg(feature = "diagnostics")] { use crate::copystat::{C, add}; add(C::DynamicRefused, 1); add(C::DynamicNs, started.elapsed().as_nanos() as u64); } return None; }; #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::DynamicNs, started.elapsed().as_nanos() as u64); taken[first..first + n].fill(true); self.free.fetch_sub(n as u32, std::sync::atomic::Ordering::Relaxed); *next = ((first + n) % 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 } /// The GPU address of the table of element strides by title slot (view /// heaps). pub(crate) fn strides_gpu(&self) -> Option { self.strides.as_ref().map(|s| s.1) } /// The table's buffer, for a list to hold. pub(crate) fn strides_buffer(&self) -> Option<&ID3D12Resource> { self.strides.as_ref().map(|s| &s.0) } /// Up to `max` title slots whose texture view is due at `frame`, each /// with its write number, in the order to serve them /// ([`TextureQueue::due`]), and the queue's counts /// ([`TextureQueue::census`]). pub(crate) fn texture_slots_due(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, [u64; 5]) { let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); (if max == 0 { Vec::new() } else { textures.due(frame, max) }, textures.census(frame)) } /// The texture view of title slot `index` (as handed out with `write`) /// was brought up to date: due again from frame `again` (uploaded with /// that many bytes of its memory there, not all), or not until the /// slot is written again. pub(crate) fn texture_slot_done(&self, index: u32, write: u64, again: Option<(u64, u64)>) { let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); match again { Some((frame, mapped)) => textures.partly(index, write, frame, mapped), None => textures.done(index, write), } } /// Title slot `index` was uploaded whole: see [`TextureQueue::recheck`]. #[allow(clippy::too_many_arguments)] pub(crate) fn texture_slot_recheck( &self, index: u32, write: u64, due: u64, at: (u64, u64), print: u64, looks: u8, uploaded: u64, ) { let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); textures.recheck(index, write, due, at, print, looks, uploaded); } /// See [`TextureQueue::checked`]. pub(crate) fn texture_slot_checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> { self.textures.lock().unwrap_or_else(|e| e.into_inner()).checked(index) } /// Nothing to upload at title slot `index` now (its memory is not /// mapped, or no more of it than before): looked at again after 1, 2, /// 4, ... frames, at most `most`. pub(crate) fn texture_slot_later(&self, index: u32, write: u64, frame: u64, most: u64) { let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); textures.later(index, write, frame, most); } /// Bytes of title slot `index`'s memory that were mapped when it was /// last uploaded in part (0: not uploaded, or whole). pub(crate) fn texture_slot_mapped(&self, index: u32) -> u64 { self.textures.lock().unwrap_or_else(|e| e.into_inner()).mapped(index) } /// Takes the ranges of title memory the runtime mapped, unmapped or /// wrote since the last call ([`remapped`]) and makes the slots whose /// placed texture lies there due from the next frame (by when a write /// under way has landed): memory that arrived is uploaded, memory that /// went makes the slot null ([`HostHeap::texture_slot_gone`]), and a /// texture streamed into the place of another of the same description /// is uploaded although no descriptor says so. Slots tables read are /// left to their draws. Returns how many slots it made due. /// shortcut: the ranges are kept in one place for all heaps; the heap /// whose pass runs first takes them (a title has one view heap). pub(crate) fn texture_slots_remapped(&self, frame: u64) -> usize { use std::sync::atomic::Ordering::Relaxed; let ranges = std::mem::take(&mut *REMAPPED.lock().unwrap_or_else(|e| e.into_inner())); if ranges.is_empty() { return 0; } let mut slots: Vec = { let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); ranges.iter().flat_map(|&(start, end)| placed.slots_in(start, end)).collect() }; slots.sort_unstable(); slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); for &slot in &slots { textures.changed(slot, frame, frame + 1); } STALE[3].fetch_add(slots.len() as u64, Relaxed); slots.len() } /// The memory of the texture title slot `index` views is not mapped /// (any more): a host slot made from it becomes null again, so that /// the host copy can be let go (`crate::resource::let_go_idle`; a slot /// keeps what it views). True if the slot was made. pub(crate) fn texture_slot_gone(&self, index: u32) -> bool { let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); if made.get(index as usize).is_none_or(|&key| key == 0) { return false; } self.unmake(&mut made, index); STALE[4].fetch_add(1, std::sync::atomic::Ordering::Relaxed); true } /// Whether host slot `index` shows a host texture now (a texture was /// made for it, and its memory was there then). pub(crate) fn texture_slot_has_contents(&self, index: u32) -> bool { let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); made.get(index as usize).is_some_and(|&key| key != 0) } /// Makes host slot `index` null again, as it is before its view is /// made: a null view of the kind it held. fn unmake(&self, made: &mut [u64], index: u32) { let Some(key) = made.get_mut(index as usize).map(std::mem::take) else { return; }; if key == 0 { return; } // Null from here on: the hit path must not read the slot as made. self.made_fast[index as usize].store(0, std::sync::atomic::Ordering::Release); match view_at(key as u32, (key >> 32) as u32) { Some(view) => null_for(&view, self.cpu(index)), None => null_view(self.cpu(index)), } self.forget_narrowed(index); self.keep(index, None); } /// Title slot `index` is a table's ([`HostHeap::tabled`]). `read`: a /// draw read it through the table and brought what it views up to /// date, so the slot leaves the queue of textures picked by index; the /// caller makes the host slot in place ([`HostHeap::mirror`]), as the /// pass would have, for a shader that picks it by index all the same. pub(crate) fn texture_slot_tabled(&self, index: u32, read: bool) { self.tabled_in(index, read, crate::frame::current()); } /// [`HostHeap::texture_slot_tabled`] in frame `frame`. fn tabled_in(&self, index: u32, read: bool, frame: u64) { use std::sync::atomic::Ordering::Relaxed; let Some(stamp) = self.tabled.get(index as usize) else { return; }; let now = (frame as u32).wrapping_add(1) & !TABLED_READ; let old = stamp.load(Relaxed); if !read { if old & !TABLED_READ != now { stamp.store(now, Relaxed); } return; } // Once per slot and frame: tables are read by every draw. if old != now | TABLED_READ { stamp.store(now | TABLED_READ, Relaxed); if tabled_out() { let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); if textures.slots.remove(&index).is_some() { TABLED_WRITES[1].fetch_add(1, Relaxed); } } } } /// Whether title slot `index` was a table's within the last /// [`TABLED_FRAMES`] frames before `frame` (never, if such slots are /// to be queued as any other). fn tabled_lately(&self, index: u32, frame: u64) -> bool { let stamp = self.tabled_stamp(index) & !TABLED_READ; let now = (frame as u32).wrapping_add(1) & !TABLED_READ; tabled_out() && stamp != 0 && u64::from(now.wrapping_sub(stamp)) <= TABLED_FRAMES } /// What `tabled` holds for title slot `index`; 0: never a table's. fn tabled_stamp(&self, index: u32) -> u32 { self.tabled .get(index as usize) .map_or(0, |s| s.load(std::sync::atomic::Ordering::Relaxed)) } /// The queue's part of a write of title slot `index` in `frame`: /// `texture`, whether it now holds a view of a texture the title may /// fill; `seen` as for [`HostHeap::note_buffer`]. fn queue_texture(&self, index: u32, texture: bool, seen: bool, frame: u64) { let stamp = if tabled_out() { self.tabled_stamp(index) } else { 0 }; let now = (frame as u32).wrapping_add(1) & !TABLED_READ; // A table's slot lately: the draw that reads it uploads its // texture, so its write waits for that draw. let lately = stamp != 0 && u64::from(now.wrapping_sub(stamp & !TABLED_READ)) <= TABLED_FRAMES; // Made now by a draw of this frame that read it through a table: // up to date. let read_now = seen && stamp == now | TABLED_READ; let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); if texture && !read_now { let due = if lately && !seen { TABLED_WRITES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); frame + TABLED_GRACE } else { 0 }; textures.written(index, frame, due, seen); } else { textures.remove(index); } } /// The title slots that hold buffer views. pub(crate) fn buffer_slots(&self) -> Vec { let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner()); buffers.iter().copied().collect() } /// The title slots whose buffer view was written, or went, since the /// last call. pub(crate) fn buffer_changes(&self) -> Vec { let mut changed = self.changed.lock().unwrap_or_else(|e| e.into_inner()); std::mem::take(&mut *changed).into_iter().collect() } /// Records what title slot `index` now holds for shaders that pick /// buffers from the heap: its element stride in the table, and whether /// it is a buffer view at all. /// `seen`: the slot was not written now, a draw or a pass made its /// host slot from what it held. /// Returns the title slots whose placed texture view the write made /// stale ([`Spans`]): out of the queue of textures already, their host /// slots are the caller's to make null (it holds `made`). fn note_buffer(&self, index: u32, view: Option<&View>, seen: bool) -> Vec { if self.sampler { return Vec::new(); } // Measured for the texture side of the same gap (textures a shader // picks by a computed index are neither made, if placed, nor // uploaded): slots written with a placed texture view, and with a // view of a texture object. let texture = match view { Some(View::Placed(false, resource, _)) if resource[0] != 1 => { PLACED_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); true } Some(View::Shader(r, _)) if crate::resource::buffer_bytes(*r as crate::object::This).is_none() => { OBJECT_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); true } _ => false, }; self.queue_texture(index, texture, seen, crate::frame::current()); // The memory a placed texture view describes. Not for a slot // tables read (thousands of writes a frame, each read by its // draw): no pass looks at it, and the same texture's view in a // slot shaders pick by index says what it says. let placed_view = match view { Some(View::Placed(false, resource, desc)) if resource[0] != 1 && !self.tabled_lately(index, crate::frame::current()) => { Some((resource, u64::from(desc[10]) | u64::from(desc[11]) << 32)) } _ => None, }; let stale = { use std::sync::atomic::Ordering::Relaxed; let mut placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); let span = placed_view .and_then(|(resource, start)| Some((start, start.saturating_add(placed.bytes(resource)?)))); match span { Some((start, end)) => { SPANNED[0].fetch_min(start, Relaxed); SPANNED[1].fetch_max(end, Relaxed); placed.note(index, start, end, !seen && stale_out()) } None => { placed.forget(index); Vec::new() } } }; if !stale.is_empty() { STALE[0].fetch_add(stale.len() as u64, std::sync::atomic::Ordering::Relaxed); let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); for &slot in &stale { textures.remove(slot); } } let stride = view.and_then(view_stride); if let Some((_, _, data)) = &self.strides && index < victory_shader::emit::SLOT_STRIDES_COUNT { // SAFETY: inside the mapping; shaders read it while we write (a // dword, either value is one the slot had). unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0)) }; } let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner()); let was = if stride.is_some() { buffers.insert(index); true } else { buffers.remove(&index) }; if was { self.changed .lock() .unwrap_or_else(|e| e.into_inner()) .insert(index); } stale } /// Gives back `n` dynamic slots from `first` (an index [`dynamic`] /// returned). /// /// [`dynamic`]: HostHeap::dynamic pub(crate) fn release(&self, first: u32, n: u32) { let Some(at) = first.checked_sub(self.count) else { return; }; 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) { let given = slots.iter().filter(|taken| **taken).count() as u32; self.free.fetch_add(given, std::sync::atomic::Ordering::Relaxed); self.too_long.store(u32::MAX, std::sync::atomic::Ordering::Relaxed); 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.keep(index, kept.flatten()); } /// Makes slot `index` (a dynamic one) a structured buffer alias with /// element width `stride`, for a shader that declares a structured SRV /// where the title binds a raw buffer SRV (`draw::fullscreen_structured_alias` /// names the verified passes). The title's own slot keeps its raw view. pub(crate) fn make_structured_at(&self, index: u32, view: &View, stride: u32) -> bool { let Some((address, len, desc)) = buffer_srv_parts(view) else { return false; }; let Some(alias) = structured_alias(desc, stride) else { return false; }; let Some(kept) = buffer_srv_alias(address, len, alias, self.cpu(index)) else { return false; }; self.keep(index, kept); true } /// 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, None); } /// Slot `index` now views `resource` (or nothing of the host's). fn keep(&self, index: u32, resource: Option) { let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); if let Some(slot) = kept.get_mut(index as usize) { // A running submission may still read the old resource through // this slot. if let Some(old) = std::mem::replace(slot, resource) { crate::host::retire(old); } } } /// 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, Some(buffer.clone())); } /// Makes slot `index` (a dynamic one) 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, None); } /// Makes slot `index` (a dynamic one) a raw unordered access view of /// `len` bytes of `buffer` from byte `offset` (a multiple of 16): a /// root UAV with a size, whose accesses past it do nothing 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 = 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: offset / 4, NumElements: elements, StructureByteStride: 0, CounterOffsetInBytes: 0, Flags: D3D12_BUFFER_UAV_FLAG_RAW, }, }, }; // 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, Some(buffer.clone())); } /// Makes slot `index` (a dynamic one) a raw unordered access view of /// nothing: reads give zeros, writes are dropped. pub(crate) fn null_raw_uav_at(&self, index: u32) { self.keep(index, None); 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), self.cpu(index), ) }; } /// 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), } } /// 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, None); 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)) }; } 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. /// Whether host slot `index` shows a view narrowed to mips that more of /// have arrived since (or whose chain a host copy has filled): the slot /// has to be made again though the title's descriptor is unchanged. fn widen_due(&self, index: u32) -> bool { if self.narrowed_count.load(std::sync::atomic::Ordering::Relaxed) == 0 { return false; } let entry = { let map = self.narrowed.lock().unwrap_or_else(|e| e.into_inner()); map.get(&index).copied() }; let Some((n, host_mips)) = entry else { return false; }; let Some(texture) = crate::resource::host_resource(n.resource) else { return false; }; // SAFETY: a live resource while a slot still shows it. let mips = u32::from(unsafe { texture.GetDesc() }.MipLevels); let want = crate::texture::wanted( n.asked, crate::texture::resident(n.resource), mips, crate::texture::is_host_written(n.resource), ); want != host_mips } /// Records what the last [`make`] on this thread narrowed slot `index` /// to: nothing when it is not a narrowed view any more. fn note_narrowed(&self, index: u32) { let n = LAST_NARROW.with(|c| c.take()); let mut map = self.narrowed.lock().unwrap_or_else(|e| e.into_inner()); match n { Some(entry) => map.insert(index, entry), None => map.remove(&index), }; self.narrowed_count .store(map.len(), std::sync::atomic::Ordering::Relaxed); } /// Drops the narrowing of slot `index`: it shows something else now. fn forget_narrowed(&self, index: u32) { let mut map = self.narrowed.lock().unwrap_or_else(|e| e.into_inner()); if map.remove(&index).is_some() { self.narrowed_count .store(map.len(), std::sync::atomic::Ordering::Relaxed); } } pub(crate) fn mirror(&self, index: u32, handle: u64, for_draw: bool) -> Option { if index >= self.count { // Diagnostic (heap cap): slots above the host heap's count are not // mirrored. The title walks them in increasing order, so a line per // new high-water mark is one line per slot; `VICTORY_SLOT_DIAG` // takes once (the default), every slot (the old way) or none. static SAID: std::sync::Once = std::sync::Once::new(); say_slot_past(&SAID, SlotDiag::now(), index, self.count, for_draw); 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); // The hit path: the slot was made from this very record and nothing // has narrowed it since. `widen_due` is asked all the same: a host // copy that brought more mips of a narrowed texture in wants a wider // slot without the title's descriptor changing (#672). if mirror_fast_on() && tag == VIEW_TAG && key != 0 && self.made_fast[index as usize].load(std::sync::atomic::Ordering::Acquire) == key && !self.widen_due(index) && let Some(view) = view_at(i, generation) { return Some(view); } 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.made_fast[index as usize].store(0, std::sync::atomic::Ordering::Release); self.make_null(index); let _ = self.note_buffer(index, None, false); } else if for_draw { // Left for later and stale since: out of the sets and the stride table. let _ = self.note_buffer(index, None, false); } return None; }; // A narrowed slot whose texture has more mips now is made again // though its descriptor did not change: bindless draws never write // the slot again, so nothing else would widen it (#672). if made[index as usize] != key || self.widen_due(index) { // 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. for stale in self.note_buffer(index, Some(&view), for_draw) { if stale != index { self.unmake(&mut made, stale); } } // A view of a texture object that has no host copy yet waits // for it, as buffer views wait for a draw: the slot is made // when the texture is first used (`super::make_waiting`), or // here when a draw reads the slot through a table. let waiting = if for_draw { None } else { view.waiting_texture() }; if let Some(texture) = waiting { super::wait_for(texture, handle); } let later = !for_draw && (view.is_buffer() || waiting.is_some()); // Another view of the placed texture the slot shows already (a // title that streams a texture in writes its view again with // more mips each time some arrive): the slot goes on showing // the old view until a draw or the texture pass makes the new // one and uploads what it shows. Made null here, the texture // read as nothing for as long as it waited in the queue, every // time it got sharper. if later && keep_views() && view_at(made[index as usize] as u32, (made[index as usize] >> 32) as u32) .is_some_and(|old| same_placed_texture(&old, &view)) { KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); return Some(view); } made[index as usize] = if later { 0 } else { key }; self.made_fast[index as usize].store(if later { 0 } else { key }, std::sync::atomic::Ordering::Release); let kept = if later { self.forget_narrowed(index); None } else { let kept = make(&view, self.cpu(index)); self.note_narrowed(index); kept }; if kept.is_none() && !self.sampler { null_for(&view, self.cpu(index)); } self.keep(index, kept.flatten()); } Some(view) } /// Whether host slot `index` shows `buffer`; `None` if it shows no /// resource (diagnostics: a buffer view's slot must show the host copy /// that is brought up to date for it). #[cfg(feature = "diagnostics")] pub(crate) fn shows(&self, index: u32, buffer: &ID3D12Resource) -> Option { let kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); let shown = kept.get(index as usize)?.as_ref()?; Some(windows::core::Interface::as_raw(shown) == windows::core::Interface::as_raw(buffer)) } /// 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) } } /// Whether [`HostHeap::mirror`] may take its hit path without the lock /// (`VICTORY_MIRROR_FAST=0` off, the slow way: every slot through the mutex). fn mirror_fast_on() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| mirror_fast_from(std::env::var("VICTORY_MIRROR_FAST").ok().as_deref())) } /// [`mirror_fast_on`] from the variable's text: unset or anything but `0` is /// on, `0` is the slow way. fn mirror_fast_from(text: Option<&str>) -> bool { text.map(str::trim) != Some("0") } /// 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)*)); }}; } /// Narrows a shader resource view of `texture` to the mips of `resource` /// whose memory is there ([`crate::texture::resident`]): `MostDetailedMip` /// up to the most detailed resident one, `MipLevels` to what is left. /// Returns the mips it names, `None` if the view is not narrowed (the /// texture is all there, or is not a 2D view, or none of it is known). fn narrow_to_resident( resource: crate::object::This, texture: &ID3D12Resource, desc: &mut D3D12_SHADER_RESOURCE_VIEW_DESC, ) -> Option<(u32, u32)> { if !crate::texture::resident_mips_on() { return None; } // A copy or resolve filled the host chain: title-memory residency is // stale and must not clamp the view (#616). if crate::texture::is_host_written(resource) { return None; } let resident = crate::texture::resident(resource)?; if resident.1 == 0 { return None; } // SAFETY: a live resource. let mips = u32::from(unsafe { texture.GetDesc() }.MipLevels); let asked = match desc.ViewDimension { D3D12_SRV_DIMENSION_TEXTURE2D => { // SAFETY: the union member of a 2D view. let t = unsafe { desc.Anonymous.Texture2D }; (t.MostDetailedMip, t.MipLevels) } D3D12_SRV_DIMENSION_TEXTURE2DARRAY => { // SAFETY: the union member of a 2D array view. let t = unsafe { desc.Anonymous.Texture2DArray }; (t.MostDetailedMip, t.MipLevels) } _ => return None, }; let (first, count) = crate::texture::narrowed(asked, resident, mips); if (first, count) == (asked.0, if asked.1 == 0 { mips } else { asked.1 }) { return None; } match desc.ViewDimension { D3D12_SRV_DIMENSION_TEXTURE2D => { // SAFETY: as above. let t = unsafe { &mut desc.Anonymous.Texture2D }; *t = D3D12_TEX2D_SRV { MostDetailedMip: first, MipLevels: count, PlaneSlice: t.PlaneSlice, ResourceMinLODClamp: t.ResourceMinLODClamp, }; } _ => { // SAFETY: as above. let t = unsafe { &mut desc.Anonymous.Texture2DArray }; *t = D3D12_TEX2D_ARRAY_SRV { MostDetailedMip: first, MipLevels: count, FirstArraySlice: t.FirstArraySlice, ArraySize: t.ArraySize, PlaneSlice: t.PlaneSlice, ResourceMinLODClamp: t.ResourceMinLODClamp, }; } } // Remembered for the slot that shows it: more levels arriving want a // wider window than this one, and its descriptor will not change. LAST_NARROW.set(Some((Narrowed { resource, asked }, (first, count)))); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::ViewNarrowed, 1); Some((first, count)) } /// 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) } } /// Checked `(start, bytes)` of `count` elements of `element` bytes starting /// at `base + first * element`: `None` on any `u64` overflow. A title's /// `FirstElement` is whatever its descriptor words held, so a view of other /// memory read as a buffer (or a bogus `FirstElement`) would otherwise wrap /// to a plausible address in release and panic in a debug build. fn checked_buffer_range(base: u64, first: u64, count: u32, element: u64) -> Option<(u64, u64)> { let start = base.checked_add(first.checked_mul(element)?)?; let bytes = u64::from(count).checked_mul(element)?; start.checked_add(bytes)?; Some((start, 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); if desc.ViewDimension != D3D12_SRV_DIMENSION_BUFFER { // A texture view of a buffer: its words are no buffer's. return None; } let element = element_size(&desc); // SAFETY: `ViewDimension` is `D3D12_SRV_DIMENSION_BUFFER`. let buffer = unsafe { desc.Anonymous.Buffer }; checked_buffer_range(base, buffer.FirstElement, buffer.NumElements, element) } /// The title memory the host slot of buffer view `view` is made on /// (address, bytes): the whole buffer the view is of, which is what /// [`make`] finds the host copy by. [`buffer_range`] is the part of it the /// view reads. pub(crate) fn buffer_extent(view: &View) -> Option<(u64, u64)> { match view { View::Shader(r, Some(_)) | View::Unordered(r, _, Some(_)) => { let (data, len) = crate::resource::buffer_bytes(*r as crate::object::This)?; Some((data as u64, len)) } View::Placed(_, resource, desc) if resource[0] == 1 => Some(( u64::from(desc[10]) | u64::from(desc[11]) << 32, u64::from(resource[4]) | u64::from(resource[5]) << 32, )), _ => None, } } /// Whether a buffer view is brought up to date in the host copy its slot /// shows ([`buffer_copy`]). On by default; `VICTORY_VIEW_EXTENT=0` looks the /// copy up by the view's range alone, as before. fn view_extent() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_EXTENT").is_none_or(|v| v != "0")) } /// The host copy buffer view `view` reads, and the title range (address, /// bytes) it reads there; `None` for other views and empty ranges. /// /// The copy is the one the view's slot shows: [`make`] finds it by the /// whole buffer the view is of ([`buffer_extent`]). Looked up by the range /// the view reads, as it was, the copy is another one wherever the two /// lookups differ: for memory outside buffer objects, a view of a part of a /// buffer that crosses a window line (the buffer's window is two cells, the /// part's one), and for buffer objects, a part that also lies in a smaller /// buffer object. The slot then showed a copy nothing brought up to date, /// and what shaders wrote through it was looked for in the other copy. pub(crate) fn buffer_copy(view: &View) -> Option<(std::sync::Arc, u64, u64)> { let (address, len) = buffer_range(view)?; if len == 0 { return None; } if view_extent() && let Some((base, width)) = buffer_extent(view) // (The console is lax: a view may begin past its buffer's end.) && address >= base && address - base < width.max(1) && let Some(shadow) = crate::shadow::find(base, width) { return Some((shadow, address, len)); } crate::shadow::find(address, len).map(|shadow| (shadow, address, len)) } /// [`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); if desc.ViewDimension != D3D12_UAV_DIMENSION_BUFFER { // A texture view of a buffer: its words are no buffer's. return None; } // SAFETY: `ViewDimension` is `D3D12_UAV_DIMENSION_BUFFER`. let buffer = unsafe { 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)?.0 }; checked_buffer_range(base, buffer.FirstElement, buffer.NumElements, element) } /// The host resource a slot made by [`make`] views, if any. type Kept = Option; /// A structured buffer view (`first`, `count` elements of `stride` bytes, /// `offset` bytes into its host copy) as a raw view of the same bytes: /// its first dword and its dwords. Translated shaders read untyped buffers /// as raw bytes at `element * stride + offset` (the stride from the /// used-resource entry, or from the table by heap slot for a buffer picked /// by index), and a raw read through a structured view gives zeros on /// NVIDIA (reported upstream with PR #193; structured reads through raw /// views were right there). So the host's view is raw whenever it can be: /// the bytes must start on 16 (the host's raw view alignment) and be whole /// dwords. A view that cannot stays structured. fn raw_window(offset: u64, first: u64, count: u32, stride: u32) -> Option<(u64, u32)> { if stride == 0 { return None; } let start = first.checked_mul(u64::from(stride))?.checked_add(offset)?; let bytes = u64::from(count) * u64::from(stride); (start % 16 == 0 && bytes % 4 == 0) .then(|| u32::try_from(bytes / 4).ok().map(|dwords| (start / 4, dwords))) .flatten() } /// Whether the host accepts a buffer view with these fields of a buffer of /// `width` bytes. It removes the device for one it does not (view creation /// returns nothing), and the console is laxer: the title's heap holds /// views past their memory's end, of no elements, of typeless formats /// without the raw flag, with strides the host has no structured buffers /// for. Since every buffer view of the heap is made for shaders that pick /// them by index, one such view ended the run (2026-11-24, run 10). fn buffer_view_ok(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bool, width: u64) -> bool { use crate::resource::family; let f = format.0 as u32; let element = if raw { // raw: R32 typeless, counted in dwords, starting on 16 bytes if format != DXGI_FORMAT_R32_TYPELESS || stride != 0 || !first.is_multiple_of(4) { return false; } 4 } else if stride > 0 { // structured: no format, a stride the host takes if format != DXGI_FORMAT_UNKNOWN || stride > 2048 || !stride.is_multiple_of(4) { return false; } u64::from(stride) } else { // typed: a format with a size that is not typeless let typeless = family(f) == f && family(f + 1) == f; match crate::resource::element(f) { Some((bytes, 1)) if f != 0 && !typeless && bytes > 0 => bytes, _ => return false, } }; count > 0 && first .checked_add(u64::from(count)) .and_then(|end| end.checked_mul(element)) .is_some_and(|end| end <= width) } 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 offset = shadow.offset(address); // A structured view as a raw view of the same bytes (see `raw_window`). // SAFETY: a buffer view's union member. let structured = unsafe { desc.Anonymous.Buffer }; let window = (desc.Format == DXGI_FORMAT_UNKNOWN) .then(|| raw_window(offset, structured.FirstElement, structured.NumElements, structured.StructureByteStride)) .flatten(); if let Some((first, count)) = window { desc.Format = DXGI_FORMAT_R32_TYPELESS; desc.Anonymous.Buffer = D3D12_BUFFER_SRV { FirstElement: first, NumElements: count, StructureByteStride: 0, Flags: D3D12_BUFFER_SRV_FLAG_RAW, }; } let element = element_size(&desc); // SAFETY: a buffer view's union member. let buffer = unsafe { &mut desc.Anonymous.Buffer }; if window.is_none() { if element == 0 || offset % element != 0 { once!( offset, element, "buffer view not on an element of its host copy" ); return None; } // A `FirstElement` the title wrote past `u64` is no view of the copy. buffer.FirstElement = buffer.FirstElement.checked_add(offset / element)?; } let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride); let raw = buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; // SAFETY: a live buffer. let width = unsafe { shadow.buffer.GetDesc() }.Width; if !buffer_view_ok(desc.Format, first, count, stride, raw, width) { REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); once!( format = desc.Format.0, first, count, stride, raw, width, "buffer view the host would refuse left null" ); return None; } // The console has no component mapping; one the host does not know is the default's. if desc.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING { desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; } let host = host()?; // SAFETY: a live buffer and a slot of our heap. unsafe { host.device .CreateShaderResourceView(&shadow.buffer, Some(&desc), at) }; Some(Some(shadow.buffer.clone())) } /// The buffer a view is of: its memory address, its length in bytes, and /// the view's description (`None` for views that are not buffer views). fn buffer_srv_parts(view: &View) -> Option<(u64, u64, D3D12_SHADER_RESOURCE_VIEW_DESC)> { const BUFFER: u32 = 1; match view { View::Shader(resource, Some(desc)) => { let (data, len) = crate::resource::buffer_bytes(*resource as crate::object::This)?; Some((data as u64, len, srv_desc(desc))) } View::Placed(false, resource, desc) if resource[0] == BUFFER => { let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; let len = u64::from(resource[4]) | u64::from(resource[5]) << 32; Some((address, len, srv_desc(desc[..10].try_into().ok()?))) } _ => None, } } /// Re-expresses the exact byte start and length of a raw buffer SRV as /// structured elements of width `stride`, rejecting typed or already /// structured views and fractional bounds. fn structured_alias( mut desc: D3D12_SHADER_RESOURCE_VIEW_DESC, stride: u32, ) -> Option { if desc.ViewDimension != D3D12_SRV_DIMENSION_BUFFER || !(4..=2048).contains(&stride) || !stride.is_multiple_of(4) { return None; } let old_bytes = element_size(&desc); // SAFETY: `ViewDimension == D3D12_SRV_DIMENSION_BUFFER` verified above. let old = unsafe { desc.Anonymous.Buffer }; if old.StructureByteStride != 0 || old.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 == 0 || old_bytes == 0 || old.NumElements == 0 { return None; } let width = u64::from(stride); let start = old.FirstElement.checked_mul(old_bytes)?; let size = u64::from(old.NumElements).checked_mul(old_bytes)?; if start % width != 0 || size % width != 0 { return None; } desc.Format = DXGI_FORMAT_UNKNOWN; desc.Anonymous.Buffer = D3D12_BUFFER_SRV { FirstElement: start / width, NumElements: u32::try_from(size / width).ok()?, StructureByteStride: stride, Flags: D3D12_BUFFER_SRV_FLAG_NONE, }; Some(desc) } /// [`buffer_srv`] that keeps the structured shape it is given instead of /// turning it into a raw window ([`raw_window`]): for a shader whose /// translated reads are structured while the title binds a raw view. fn buffer_srv_alias( 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 offset = shadow.offset(address); let element = element_size(&desc); // SAFETY: a buffer view's union member. let buffer = unsafe { &mut desc.Anonymous.Buffer }; if element == 0 || buffer.StructureByteStride == 0 || buffer.NumElements == 0 { return None; } if offset % element != 0 { once!( offset, element, "structured alias not on an element of its host copy" ); return None; } // A `FirstElement` the title wrote past `u64` is no view of the copy. buffer.FirstElement = buffer.FirstElement.checked_add(offset / element)?; let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride); // SAFETY: a live buffer. let width = unsafe { shadow.buffer.GetDesc() }.Width; if !buffer_view_ok(desc.Format, first, count, stride, false, width) { REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); once!( first, count, stride, width, "structured alias the host would refuse left raw" ); return None; } // The console has no component mapping; one the host does not know is the default's. if desc.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING { desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; } let host = host()?; // SAFETY: a live buffer and a slot of our heap. unsafe { host.device .CreateShaderResourceView(&shadow.buffer, Some(&desc), at) }; Some(Some(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); // A structured view as a raw view of the same bytes (see `raw_window`). let window = (desc.Format == DXGI_FORMAT_UNKNOWN) .then(|| raw_window(offset, buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride)) .flatten(); if let Some((first, count)) = window { buffer.FirstElement = first; buffer.NumElements = count; buffer.StructureByteStride = 0; buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; } else { if element == 0 || offset % element != 0 { once!(offset, element, "unordered buffer view not on an element of its host copy"); return None; } // A `FirstElement` the title wrote past `u64` is no view of the copy. buffer.FirstElement = buffer.FirstElement.checked_add(offset / element)?; } buffer.CounterOffsetInBytes = 0; let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride); let raw = buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; if window.is_some() { // (Left out at first: every structured unordered access view was then // refused by `buffer_view_ok` and left null, runs 15 and 16.) desc.Format = DXGI_FORMAT_R32_TYPELESS; } // SAFETY: a live buffer. let width = unsafe { shadow.buffer.GetDesc() }.Width; if !buffer_view_ok(desc.Format, first, count, stride, raw, width) { REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); once!( format = desc.Format.0, first, count, stride, raw, width, "unordered buffer view the host would refuse left null" ); 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(Some(shadow.buffer.clone())) } /// Whether the host lets views of a typed resource name another format of /// its family (`CastingFullyTypedFormatSupported`; never SNORM for UNORM, /// nor FLOAT for another type), which [`fits`] uses for sRGB and linear /// twins only. fn casts_typed() -> bool { static CASTS: std::sync::OnceLock = std::sync::OnceLock::new(); *CASTS.get_or_init(|| { let Some(host) = host() else { return false }; let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS3::default(); // SAFETY: the query writes its own structure of the given size. let asked = unsafe { host.device.CheckFeatureSupport( D3D12_FEATURE_D3D12_OPTIONS3, (&raw mut options).cast(), size_of_val(&options) as u32, ) }; let casts = asked.is_ok() && options.CastingFullyTypedFormatSupported.as_bool(); if !casts { tracing::warn!( "the host does not cast typed formats: sRGB views of linear textures (and the reverse) read in the texture's own format" ); } casts }) } /// Whether [`fits`] refuses unordered access views in formats the host /// cannot store to. On by default; `VICTORY_TYPED_UAV=0` lets such a view /// reach the host (as before), which then removes the device. fn typed_uav_check() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("VICTORY_TYPED_UAV").is_none_or(|v| v != "0")) } /// Whether the host creates a typed unordered access view in `format`, /// asked once per format. Hosts refuse some (B8G8R8X8_UNORM and the block /// formats on NVIDIA: no typed store there) by removing the device rather /// than failing the call, so [`fits`] leaves such a view's slot null. A /// host that stores to `format` (RADV through vkd3d-proton does, B8G8R8X8 /// as B8G8R8A8 with the alpha ignored) keeps every view it had. fn typed_store(format: DXGI_FORMAT) -> bool { use std::sync::atomic::{AtomicU8, Ordering::Relaxed}; // 0: not asked, 1: refused, 2: stored to. static SUPPORT: [AtomicU8; 256] = [const { AtomicU8::new(0) }; 256]; let Some(state) = usize::try_from(format.0).ok().and_then(|f| SUPPORT.get(f)) else { return false; }; match state.load(Relaxed) { 0 => {} known => return known == 2, } let asked = host().is_some_and(|host| { let mut support = D3D12_FEATURE_DATA_FORMAT_SUPPORT { Format: format, ..Default::default() }; // SAFETY: a plain query into our own structure. let asked = unsafe { host.device.CheckFeatureSupport( D3D12_FEATURE_FORMAT_SUPPORT, (&raw mut support).cast(), size_of_val(&support) as u32, ) }; asked.is_ok() && support.Support1.0 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0 != 0 }); state.store(if asked { 2 } else { 1 }, Relaxed); asked } /// 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, but for casts it allows (see [`casts_typed`]). A view /// of a typed texture in another format of its family takes the texture's /// format, unless it is the texture's sRGB or linear twin and the host /// casts: then the hardware converts (or not) as the console does. /// shortcut: other casts within a family (UINT of UNORM, say) read as the /// texture's own format. 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) { if unordered { crate::resource::DEPTH_UNORDERED[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed); } 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 { if typeless { return false; } // A default view of a texture in a format the host cannot store to // removes the device: leave the slot null instead. if unordered && typed_uav_check() && !typed_store(d.Format) { once!(own, "an unordered view in a format the host cannot store"); return false; } return true; } // A view of a target whose format the host refuses, in the title's // format: in the stand-in the host copy has. if view != own && crate::resource::target_format(view) == own { if let Some(format) = format { *format = d.Format; } return true; } if family(view) != family(own) { once!(view, own, "view format of another family"); return false; } let twin = crate::resource::SRGB .iter() .any(|&(s, l)| (s, l) == (view, own) || (l, s) == (view, own)); let casts = twin && casts_typed(); // The format the host makes the view in: the texture's (the title's the // host takes as it is), or the view's for a typeless texture and for the // twins the host casts. A host that cannot store to it removes the // device for a write there, so the slot stays null instead. let created = if !typeless && !casts { own } else { view }; if unordered && typed_uav_check() && !typed_store(DXGI_FORMAT(created as i32)) { once!(view = created, own, "an unordered view in a format the host cannot store"); return false; } if let Some(format) = format && !casts && !typeless { *format = d.Format; } true } /// The title's unordered access view of a depth texture, as a view of the /// texture's colour twin `twin` ([`crate::resource::Twin`]): the same mip /// and slices, in the colour format of the twin's family for a depth or /// typeless format (R16_UNORM for 16-bit depth, R32_FLOAT for 32-bit; the /// bits are the same). Without a description: mip 0 of every slice. /// The twin of a stencil plane (R8) stands for the views of that plane /// only, which become R8_UINT views of its one plane; `None` for a view of /// the depth plane, which the twin does not stand for. The depth plane has /// a twin of its own, viewed as a depth texture's without stencil: a view /// in the format of the depth plane of a depth-stencil format (21, 46) /// takes the twin's colour format too. fn twin_uav( twin: &ID3D12Resource, desc: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>, ) -> Option { // SAFETY: a live resource. let d = unsafe { twin.GetDesc() }; let mut desc = desc.cloned().unwrap_or_else(|| { let mut all = D3D12_UNORDERED_ACCESS_VIEW_DESC { ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, ..Default::default() }; if d.DepthOrArraySize > 1 { all.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; all.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV { ArraySize: u32::from(d.DepthOrArraySize), ..Default::default() }; } all }); // A stencil plane's twin (R8 typeless, 60): the title's view is of the // stencil plane if it names plane 1 or a stencil view format (22, 47). if d.Format.0 == 60 { let mut plane = 0; match desc.ViewDimension { D3D12_UAV_DIMENSION_TEXTURE2D => { // SAFETY: the member the dimension names. let mut view = unsafe { desc.Anonymous.Texture2D }; plane = std::mem::take(&mut view.PlaneSlice); desc.Anonymous.Texture2D = view; } D3D12_UAV_DIMENSION_TEXTURE2DARRAY => { // SAFETY: the member the dimension names. let mut view = unsafe { desc.Anonymous.Texture2DArray }; plane = std::mem::take(&mut view.PlaneSlice); desc.Anonymous.Texture2DArray = view; } _ => {} } if plane != 1 && !matches!(desc.Format.0, 22 | 47) { return None; } desc.Format.0 = 62; return Some(desc); } // None, typeless and depth formats (R16: 0, 53, 55; R32: 0, 39, 40), // and those of a depth-stencil format's depth plane (19 to 21, 44 to // 46), for the twin of such a plane. desc.Format.0 = match (desc.Format.0, d.Format.0) { (0 | 53 | 55 | 19..=21 | 44..=46, 53) => 56, (0 | 39 | 40 | 19..=21 | 44..=46, 39) => 41, (other, _) => other, }; Some(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 { LAST_NARROW.set(None); 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(Some(shadow.buffer.clone())) } View::Shader(resource, desc) => { let resource = *resource as crate::object::This; if let Some(texture) = crate::resource::host_resource(resource) { // The title's views of textures with a stencil plane, as it // describes them (format, dimension, component mapping, a // pad, then first level, levels, plane): each distinct one // once. They say how its shaders read the stencil plane // (the lighting takes each pixel's material class and its // "inside a room" bit from it). #[cfg(feature = "diagnostics")] { // SAFETY: a live resource. let own = unsafe { texture.GetDesc() }.Format.0; if matches!(own, 19..=22 | 44..=47) { static SEEN: Mutex)>> = Mutex::new(Vec::new()); let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); if seen.len() < 64 && !seen.contains(&(own, *desc)) { seen.push((own, *desc)); tracing::info!( ?resource, texture_format = own, view = ?desc, "shader view of a depth-stencil texture" ); } } } let mut desc = desc.as_ref().map(srv_desc); if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) { return None; } // A texture only part of which is mapped (streaming in): // sample the mips that are there, not the zeros of the ones // that are not. The console streams a texture's mips into // place and clamps the level of detail to what arrived; the // host has no clamp but the view's window. if let Some(d) = desc.as_mut() && let Some(mips) = narrow_to_resident(resource, texture, d) { let _ = mips; } // SAFETY: a live texture and a slot of our heap. unsafe { device.CreateShaderResourceView( texture, desc.as_ref().map(std::ptr::from_ref), at, ) }; Some(Some(texture.clone())) } 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, }; }; // The first such views of depth textures are logged as the // title describes them (format, dimension, then mip, slices and // plane): they say which planes shaders write, and as what. if crate::resource::depth_and_unordered(resource) { static LOGGED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if LOGGED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 512 { tracing::info!( ?resource, view = ?desc, "unordered access view of a depth texture" ); } } let mut desc = desc.as_ref().map(uav_desc); // A depth texture's unordered access is its colour twin's: the // host gives a depth texture none. let twin = crate::resource::twin_resource(resource) .and_then(|twin| Some((twin, twin_uav(twin, desc.as_ref())?))) // A view of the depth plane of a texture with a stencil // plane: of that plane's own twin. .or_else(|| { let twin = crate::resource::twin_plane_resource(resource)?; Some((twin, twin_uav(twin, desc.as_ref())?)) }); let texture = match twin { Some((twin, view)) => { desc = Some(view); twin } None => texture, }; if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) { return None; } // SAFETY: a live texture and a slot of our heap. unsafe { device.CreateUnorderedAccessView( texture, None::<&ID3D12Resource>, desc.as_ref().map(std::ptr::from_ref), at, ) }; Some(Some(texture.clone())) } 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(None) } View::ConsoleSampler(words) => { let desc = crate::sampler::console(words); // SAFETY: a slot of our sampler heap. unsafe { device.CreateSampler(&desc, at) }; Some(None) } 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) } } } } /// Writes of a slot with another view of the placed texture it showed, /// since the start: the slot kept showing the old view. pub(crate) static KEPT_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); /// Whether a slot written with another view of the placed texture it /// shows keeps showing the old one until the new is made; /// `VICTORY_KEEP_VIEWS=0` makes it null at once, as before. fn keep_views() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_VIEWS").is_none_or(|v| v != "0")) } /// Whether both are shader views of one texture the title placed in /// memory: the same address and the same resource description, whatever /// part of it each shows. fn same_placed_texture(a: &View, b: &View) -> bool { match (a, b) { (View::Placed(false, resource, desc), View::Placed(false, other, other_desc)) => { resource[0] != 1 && resource == other && desc[10..12] == other_desc[10..12] } _ => false, } } /// 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). 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 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 subscriber that only counts the lines said: what a diagnostic's cost /// comes to offline. #[derive(Clone, Default)] struct Lines(std::sync::Arc); impl Lines { fn said(&self) -> usize { self.0.load(std::sync::atomic::Ordering::Relaxed) } } impl tracing::Subscriber for Lines { fn enabled(&self, _: &tracing::Metadata<'_>) -> bool { true } fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id { tracing::span::Id::from_u64(1) } fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {} fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {} fn event(&self, _: &tracing::Event<'_>) { self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } fn enter(&self, _: &tracing::span::Id) {} fn exit(&self, _: &tracing::span::Id) {} } /// The title asks for 1 245 184 slots, more than the 1 000 000 a host heap /// holds, and walks them in increasing order. "Line when the high-water /// mark moves" was therefore a line per slot: 199 846 of the first 200 000 /// lines of a run, ~8 000 a second, on the thread recording the frame, /// which was the whole of the first frame's 21 s stall. A quarter of a /// million slots past the heap now cost one line. #[test] fn the_mirror_hit_path_is_on_by_default_and_has_an_off_switch() { assert!(mirror_fast_from(None)); assert!(mirror_fast_from(Some(""))); assert!(mirror_fast_from(Some("1"))); assert!(!mirror_fast_from(Some("0"))); assert!(!mirror_fast_from(Some(" 0 "))); } #[test] fn a_slot_past_the_host_heap_is_said_once_not_per_slot() { let lines = Lines::default(); tracing::subscriber::with_default(lines.clone(), || { let once = std::sync::Once::new(); for index in 0..250_000u32 { say_slot_past(&once, SlotDiag::Once, index, 1_000_000, true); } }); assert_eq!(lines.said(), 1); } /// The line can still be had per slot (the way it was, for a run that has /// to count them) or not at all, and either way once it has been said in /// the "once" mode it is not said again. #[test] fn the_slot_past_the_host_heap_follows_its_switch() { let lines = Lines::default(); { let lines = lines.clone(); tracing::subscriber::with_default(lines.clone(), move || { let once = std::sync::Once::new(); for index in 0..3 { say_slot_past(&once, SlotDiag::All, index, 2, false); } assert_eq!(lines.said(), 3); for index in 0..3 { say_slot_past(&once, SlotDiag::Off, index, 2, false); } assert_eq!(lines.said(), 3, "off says nothing"); say_slot_past(&once, SlotDiag::Once, 0, 2, false); say_slot_past(&once, SlotDiag::Once, 1, 2, false); assert_eq!(lines.said(), 4, "once, whatever the mode before it"); }); } assert_eq!(SlotDiag::parse(None), SlotDiag::Once, "on by default"); assert_eq!(SlotDiag::parse(Some("once")), SlotDiag::Once); assert_eq!(SlotDiag::parse(Some("all")), SlotDiag::All); assert_eq!(SlotDiag::parse(Some("0")), SlotDiag::Off); assert_eq!(SlotDiag::parse(Some("off")), SlotDiag::Off); assert_eq!(SlotDiag::parse(Some("1")), SlotDiag::Once); } /// 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); } /// Views of one placed texture are told from views of others by the /// address and the resource description, not by what they show. #[test] fn views_of_one_placed_texture_are_told_by_address_and_description() { let texture = [3, 0, 0, 0, 512, 0, 512, 0x8_0001, 98, 1, 0, 0x105, 0, 0]; let view = |resource: [u32; 14], first_mip: u32, address: u32| { let mut desc = [0u32; 16]; (desc[0], desc[1], desc[4], desc[5], desc[10], desc[11]) = (98, 4, first_mip, 8 - first_mip, address, 0xb); View::Placed(false, resource, desc) }; let low = view(texture, 3, 0x1000_0000); // more mips of the same texture assert!(same_placed_texture(&low, &view(texture, 0, 0x1000_0000))); // another address, another description, a buffer, an unordered view assert!(!same_placed_texture(&low, &view(texture, 3, 0x2000_0000))); let mut wider = texture; wider[4] = 1024; assert!(!same_placed_texture(&low, &view(wider, 3, 0x1000_0000))); let mut buffer = texture; buffer[0] = 1; assert!(!same_placed_texture(&view(buffer, 3, 0x1000_0000), &view(buffer, 3, 0x1000_0000))); let View::Placed(_, resource, desc) = low.clone() else { unreachable!() }; assert!(!same_placed_texture(&low, &View::Placed(true, resource, desc))); assert!(!same_placed_texture(&low, &View::Shader(0, None))); } /// Unordered views in formats the host cannot store to stay null /// instead of removing the device, for shared sRGB render targets and /// their linear twins as for default views: `fits` gives the host's own /// answer for the format the view is made in. #[test] fn unordered_views_follow_the_hosts_typed_store_support() { let Some(host) = host() else { return; // no host GPU }; let stores = |format: u32| { let mut support = D3D12_FEATURE_DATA_FORMAT_SUPPORT { Format: DXGI_FORMAT(format as i32), ..Default::default() }; // SAFETY: a plain query into our own structure. let asked = unsafe { host.device.CheckFeatureSupport( D3D12_FEATURE_FORMAT_SUPPORT, (&raw mut support).cast(), size_of_val(&support) as u32, ) }; asked.is_ok() && support.Support1.0 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0 != 0 }; let texture = |format: DXGI_FORMAT| -> Option { let mut tex: Option = None; let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, Height: 64, DepthOrArraySize: 1, MipLevels: 1, Format: format, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, ..Default::default() }; // SAFETY: plain committed texture creation. unsafe { host.device.CreateCommittedResource( &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut tex, ) } .ok()?; tex }; // The title's shared pair: an sRGB render target the host makes // typeless and a linear unordered access texture over it. let Some(bgra) = texture(DXGI_FORMAT_B8G8R8A8_TYPELESS) else { return; // no such texture on this host }; let pair = |own: DXGI_FORMAT, view: Option| { let tex = texture(own)?; let mut format = view.map(|v| DXGI_FORMAT(v as i32)); let fits = fits(&tex, format.as_mut(), true); let made = match format { Some(f) => f, // A default view names the texture's own format. None => own, }; Some((fits, stores(made.0 as u32))) }; // RGBA8 and BGRA8 sRGB views are rewritten to their linear twins, // whose typed store every host has. for (own, view) in [ (DXGI_FORMAT_B8G8R8A8_TYPELESS, Some(91)), (DXGI_FORMAT_B8G8R8A8_TYPELESS, Some(87)), (DXGI_FORMAT_B8G8R8X8_TYPELESS, Some(93)), (DXGI_FORMAT_B8G8R8X8_TYPELESS, Some(88)), (DXGI_FORMAT_R8G8B8A8_TYPELESS, Some(29)), (DXGI_FORMAT_R8G8B8A8_TYPELESS, Some(28)), ] { let Some((fits, stores)) = pair(own, view) else { continue; // a texture this host cannot create }; assert_eq!(fits, stores, "texture {own:?}, view {view:?}"); } // A typed texture's default unordered view follows its own format. for own in [ DXGI_FORMAT_B8G8R8X8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, ] { let Some((fits, stores)) = pair(own, None) else { continue; }; assert_eq!(fits, stores, "texture {own:?}, default view"); } // A view of a texture without the unordered access flag is refused // whatever the format, and a typeless one with no view format too. assert!(!fits(&bgra, None, true)); // SAFETY: a plain device query. assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); } /// 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 a_structured_view_made_raw_passes_the_host_check() { // 100 elements of 20 bytes from element 8, in a copy that starts 32 // bytes before the view's memory: bytes 192..2192. let (first, count) = raw_window(32, 8, 100, 20).unwrap(); assert_eq!((first, count), (48, 500)); assert!(buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 4096)); // the format a raw view must name; the structured one's is refused assert!(!buffer_view_ok(DXGI_FORMAT_UNKNOWN, first, count, 0, true, 4096)); // past the buffer, not on 16 bytes, no elements assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 2000)); assert!(raw_window(4, 0, 100, 20).is_none()); assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, 0, 0, 0, true, 4096)); // a structured view the host takes as it is assert!(buffer_view_ok(DXGI_FORMAT_UNKNOWN, 1, 10, 12, false, 4096)); } /// The queue of textures picked by index serves the slots looked at /// before first, then the newest write and the oldest in turns; a /// slot whose memory is not there is looked at again after /// 1, 2, 4 frames up to the limit; and what the pass reports about a /// slot written again meanwhile is dropped. #[test] fn the_texture_queue_serves_the_newest_writes_first() { let mut q = TextureQueue::default(); // Slots 10..18 written in frames 1..9, slot 5 last. for i in 0..8u32 { q.written(10 + i, u64::from(i) + 1, 0, false); } q.written(5, 9, 0, false); let order: Vec = q.due(9, 100).into_iter().map(|d| d.0).collect(); // newest, oldest, newest, oldest, and so on assert_eq!(order, [5, 10, 17, 11, 16, 12, 15, 13, 14]); assert_eq!(q.due(9, 2).len(), 2); assert_eq!(q.census(9), [9, 9, 0, 0, 8]); // Slot 17's memory is not mapped: again next frame, then in 2, 4, 4. let write = |q: &TextureQueue, index: u32| q.due(u64::MAX, 100).iter().find(|d| d.0 == index).unwrap().1; let w17 = write(&q, 17); let mut frame = 9; for wait in [1, 2, 4, 4] { q.later(17, w17, frame, 4); assert!(!q.due(frame + wait - 1, 100).iter().any(|d| d.0 == 17)); frame += wait; // Due again, and ahead of every slot never looked at. assert_eq!(q.due(frame, 100)[0].0, 17); } assert_eq!(q.census(9)[2], 1); q.done(17, w17); assert!(!q.due(u64::MAX, 100).iter().any(|d| d.0 == 17)); // Uploaded with part of its memory there: kept, with what was there. let w16 = write(&q, 16); q.partly(16, w16, 12, 4096); assert_eq!(q.mapped(16), 4096); assert_eq!(q.due(12, 100)[0].0, 16); // The title writes slot 16 again while the pass works on it: what // the pass then says about the old write changes nothing. q.written(16, 13, 0, false); q.done(16, w16); q.later(16, w16, 13, 4); assert_eq!(q.mapped(16), 0); assert_eq!(q.due(13, 100)[0].0, 16); // A draw that makes the host slot (`seen`) keeps what the queue knows, let w15 = write(&q, 15); q.partly(15, w15, 20, 8192); q.written(15, 14, 0, true); assert_eq!(q.mapped(15), 8192); // and queues a slot the queue did not hold. q.written(99, 14, 0, true); assert!(q.due(14, 100).iter().any(|d| d.0 == 99)); // A write due later (a table's slot) is not handed out before. q.written(98, 14, 16, false); assert!(!q.due(15, 100).iter().any(|d| d.0 == 98)); assert!(q.due(16, 100).iter().any(|d| d.0 == 98)); } /// A buffer view's `FirstElement` and `NumElements` are the title's: one /// that would overflow `u64` (a bogus address, or a texture's words read /// as a buffer's) is refused instead of wrapping to a plausible address. #[test] fn overflowing_buffer_ranges_are_refused() { assert_eq!(checked_buffer_range(0x1000, 2, 4, 16), Some((0x1020, 64))); assert_eq!(checked_buffer_range(0x1000, 0, 0, 16), Some((0x1000, 0))); // `FirstElement * element` beyond `u64`: wraps to 0 when unchecked. assert_eq!(checked_buffer_range(0x1000, 1u64 << 60, 1, 16), None); assert_eq!(checked_buffer_range(0x1000, u64::MAX, 1, 1), None); // The start fits, the whole view does not (release: wraps to a small one). assert_eq!(checked_buffer_range(u64::MAX - 8, 0, u32::MAX, u64::from(u32::MAX)), None); assert_eq!(checked_buffer_range(u64::MAX - 8, 0, 1, 16), None); let mut resource = [0u32; 14]; resource[0] = 1; // D3D12_RESOURCE_DIMENSION_BUFFER let view = |desc: [u32; 16]| View::Placed(false, resource, desc); // The host's 40-byte descriptor words: format, dimension, component // mapping, then the union at word 4 (a `u64` `FirstElement` there, // `NumElements`, stride and flags after it). let words = |format: u32, dimension: u32, first: u64, count: u32, stride: u32, flags: u32| { let mut words = [0u32; 10]; words[0] = format; words[1] = dimension; words[2] = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; (words[4], words[5]) = (first as u32, (first >> 32) as u32); (words[6], words[7], words[8]) = (count, stride, flags); words }; let placed = |words: [u32; 10]| { let mut desc = [0u32; 16]; desc[..10].copy_from_slice(&words); desc[10] = 0x1000; // the view's address view(desc) }; let buffer = |first: u64| { words( DXGI_FORMAT_UNKNOWN.0 as u32, D3D12_SRV_DIMENSION_BUFFER.0 as u32, first, 4, 16, D3D12_BUFFER_SRV_FLAG_NONE.0 as u32, ) }; // A structured buffer view at a bogus first element: refused. assert_eq!(buffer_range(&placed(buffer(1u64 << 60))), None); assert_eq!(buffer_range(&placed(buffer(u64::MAX))), None); // The same view with a first element that fits is a view of it. assert_eq!(buffer_range(&placed(buffer(2))), Some((0x1020, 64))); // A texture view of buffer memory is no buffer view at all: its words // are a texture's, and reading them as a buffer's is a bogus address. let texture = words( DXGI_FORMAT_R8G8B8A8_UNORM.0 as u32, D3D12_SRV_DIMENSION_TEXTURE2D.0 as u32, 0, 0, 0, 0, ); assert_eq!(buffer_range(&placed(texture)), None); // Through a table's unordered slot too (its dimension word is its own). let unordered_texture = words( DXGI_FORMAT_R8G8B8A8_UNORM.0 as u32, D3D12_UAV_DIMENSION_TEXTURE2D.0 as u32, 0, 0, 0, 0, ); assert_eq!(buffer_range(&View::Placed(true, resource, { let mut desc = [0u32; 16]; desc[..10].copy_from_slice(&unordered_texture); desc[10] = 0x1000; desc })), None); } /// A view written over memory that older views describe otherwise /// makes those stale; views of the same span are one texture's. #[test] fn a_newer_view_of_other_memory_makes_the_older_stale() { let mut spans = Spans::default(); // Three textures side by side, the first in two slots. assert!(spans.note(1, 0x1000, 0x3000, true).is_empty()); assert!(spans.note(2, 0x1000, 0x3000, true).is_empty()); assert!(spans.note(3, 0x3000, 0x4000, true).is_empty()); assert!(spans.note(4, 0x8000, 0x9000, true).is_empty()); // The same slot written with the same span again: nothing changes. assert!(spans.note(2, 0x1000, 0x3000, true).is_empty()); assert_eq!(spans.slots_in(0x2000, 0x3800), [1, 2, 3]); assert_eq!(spans.slots_in(0x4000, 0x8000), [] as [u32; 0]); // A draw makes a slot whose view overlaps them: left out, nothing stale. assert!(spans.note(9, 0x2000, 0x3800, false).is_empty()); assert_eq!(spans.slots_in(0x2000, 0x3800), [1, 2, 3]); // The title writes a texture over the end of the first and all of // the second: their three slots are stale. let mut stale = spans.note(5, 0x2000, 0x4000, true); stale.sort_unstable(); assert_eq!(stale, [1, 2, 3]); assert_eq!(spans.slots_in(0, u64::MAX), [5, 4]); // Another start in the same memory: stale in turn. Another length // from the same start too. assert_eq!(spans.note(6, 0x2800, 0x3000, true), [5]); assert_eq!(spans.note(7, 0x2800, 0x2c00, true), [6]); // A slot that moves to another texture leaves its span behind. assert!(spans.note(7, 0x8000, 0x9000, true).is_empty()); assert_eq!(spans.slots_in(0x2800, 0x2c00), [] as [u32; 0]); assert_eq!(spans.slots_in(0x8000, 0x8001), [4, 7]); spans.forget(4); spans.forget(7); assert!(spans.by_start.is_empty() && spans.by_slot.is_empty()); } /// Memory the runtime maps under a slot's texture makes the slot due /// again from the next frame; a stale slot leaves the queue. #[test] fn remapped_memory_makes_its_texture_slots_due() { let Some(heap) = HostHeap::new(false, 8) else { return; // no host GPU }; let slots = |at: u64| -> Vec { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; // 64x64 BC7, one mip, at an address no test and no title uses. let at = 0x7fee_0000_0000u64; let view = |address: u64, width: u32| { let mut desc = [0u32; 16]; (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); View::Placed(false, [3, 0, 0, 0, width, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc) }; let len = crate::resource::placed_bytes(&[3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0]).unwrap(); assert!(heap.note_buffer(1, Some(&view(at, 64)), false).is_empty()); let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0]; assert_eq!(queued, 1); heap.texture_slot_done(1, write, None); assert_eq!(slots(u64::MAX), []); // Memory elsewhere: nothing. Under the texture: due from the next frame. remapped((at + 2 * len) as usize, 0x1000); remapped(at as usize, 0x1000); assert_eq!(heap.texture_slots_remapped(50), 1); assert_eq!(slots(50), []); assert_eq!(slots(51), [1]); // A wider texture written at the same address: slot 1 is stale. assert_eq!(heap.note_buffer(2, Some(&view(at, 128)), false), [1]); assert_eq!(slots(u64::MAX), [2]); } /// A slot a draw read through a table leaves the queue; the title's /// next write of it waits for its draw, and is due after the grace /// frames if none reads it. #[test] fn slots_read_through_tables_leave_the_texture_queue() { let Some(heap) = HostHeap::new(false, 8) else { return; // no host GPU }; let frame = 100; let slots = |at: u64| -> Vec { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; let texture = View::Placed(false, [3, 0, 0, 0, 4, 0, 4, 0x1_0001, 28, 1, 0, 0x105, 0, 0], [0; 16]); assert!(is_texture_view(&texture)); heap.queue_texture(2, true, false, frame); heap.queue_texture(3, true, false, frame); assert_eq!(slots(frame), [3, 2]); heap.tabled_in(3, true, frame); assert_eq!(slots(frame), [2]); // Made in place by the draw that read it: still out. heap.queue_texture(3, true, true, frame); assert_eq!(slots(frame), [2]); // Written again in the next frame: due once the grace frames have // passed without a draw that reads it. heap.queue_texture(3, true, false, frame + 1); assert_eq!(slots(frame + TABLED_GRACE), [2]); assert_eq!(slots(frame + 1 + TABLED_GRACE), [3, 2]); // The draw comes after all: out again. heap.tabled_in(3, true, frame + 1); assert_eq!(slots(u64::MAX), [2]); // A slot of a table no draw read stays queued; its next write waits. heap.tabled_in(2, false, frame + 1); assert_eq!(slots(frame + 1), [2]); heap.queue_texture(2, true, false, frame + 2); assert_eq!(slots(frame + 2), []); // Long after the last table, a write is due at once. heap.queue_texture(2, true, false, frame + 3 + TABLED_FRAMES); assert_eq!(slots(frame + 3 + TABLED_FRAMES), [2]); } #[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)); } }