Publish the pareto-residency Windows build and portable launcher

This commit is contained in:
codec_d committed 2026-11-25 22:33:14 -08:00
1 parent efeef1d65b
commit 545f89019e
20 files changed
+1671 -217

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
@echo off
setlocal EnableExtensions DisableDelayedExpansion
if not "%~1"=="" if /i not "%~1"=="pareto-residency" (
echo Usage: Play-VIctory.cmd pareto-residency 1>&2
exit /b 2
)
if not defined VICTORY_GAME_DIR set "VICTORY_GAME_DIR=%~dp0..\GTA6.Xbox.v1.0.2.1"
if not exist "%VICTORY_GAME_DIR%\game_scarlett_master.exe" (
echo Set VICTORY_GAME_DIR to your own dump folder containing game_scarlett_master.exe. 1>&2
exit /b 2
)
set "runner=%~dp0victory-3d-rtx-pareto-residency.exe"
if not exist "%runner%" set "runner=%~dp0target\release\victory.exe"
if not exist "%runner%" (
echo Extract the Windows release or run cargo build --release --locked -p victory. 1>&2
exit /b 2
)
if not defined VICTORY_AMBIENT_AIR set "VICTORY_AMBIENT_AIR=1.5"
if not defined VICTORY_CACHE_DIR set "VICTORY_CACHE_DIR=%LOCALAPPDATA%\VIctory\cache-pareto"
if not defined VICTORY_TEXTURE_NO_WAIT set "VICTORY_TEXTURE_NO_WAIT=1"
if not defined VICTORY_RELAY set "VICTORY_RELAY=2"
if not defined VICTORY_WIDE_BACK set "VICTORY_WIDE_BACK=1"
if not defined VICTORY_CARD_REHASH_RUNS set "VICTORY_CARD_REHASH_RUNS=1"
if not defined VICTORY_JOIN_COPIES set "VICTORY_JOIN_COPIES=1"
if not defined VICTORY_INDIRECT_WINDOW set "VICTORY_INDIRECT_WINDOW=1"
if not defined VICTORY_RELAY_COPY set "VICTORY_RELAY_COPY=1"
if not defined VICTORY_CARD_STEPS set "VICTORY_CARD_STEPS=2"
if not defined VICTORY_INDIRECT_BATCH set "VICTORY_INDIRECT_BATCH=2"
if not defined VICTORY_MAP_THREADS set "VICTORY_MAP_THREADS=1"
if not defined VICTORY_CARD_AWAKE set "VICTORY_CARD_AWAKE=1"
if not defined VICTORY_SHOW_AFTER set "VICTORY_SHOW_AFTER=1"
if not defined VICTORY_AMBIENT set "VICTORY_AMBIENT=0.8"
if not defined VICTORY_THIN set "VICTORY_THIN=1"
if not defined VICTORY_JOIN_PARTS set "VICTORY_JOIN_PARTS=8"
if not defined VICTORY_UPLOAD_AHEAD set "VICTORY_UPLOAD_AHEAD=1"
if not defined VICTORY_LEVELS_ON_DEMAND set "VICTORY_LEVELS_ON_DEMAND=1"
if not defined VICTORY_CARD_BUFFERS_MIN_KB set "VICTORY_CARD_BUFFERS_MIN_KB=64"
if not defined VICTORY_LOG if not defined RUST_LOG set "VICTORY_LOG=warn"
"%runner%" run "%VICTORY_GAME_DIR%\game_scarlett_master.exe" --console series-s --execute
exit /b %errorlevel%
+13
View File
@@ -1,5 +1,18 @@
# VIctory on an RX 7900 XTX # VIctory on an RX 7900 XTX
## Run the codec_d Windows build
Download and extract the Windows x64 ZIP from the [private releases](https://github.com/codec-d/cool_fox/releases/latest). Open PowerShell in the extracted folder and point the launcher at your own complete Xbox dump.
```powershell
$env:VICTORY_GAME_DIR = 'D:\Games\MyDump'
.\Play-VIctory.cmd pareto-residency
```
The launcher selects Series S and the RTX-tested residency settings. It builds its shader cache locally under `%LOCALAPPDATA%\VIctory\cache-pareto`. Set `VICTORY_CACHE_DIR` to reuse an existing cache outside the checkout. Windows x64, an AVX2 CPU, and a Direct3D 12 GPU with shader model 6.6 and mesh shader support are required.
To build from this checkout, install the pinned Rust toolchain and the MSVC C++ build tools with a Windows SDK, then run `cargo build --release --locked -p victory`. The same launcher finds `target\release\victory.exe`. The sections below describe the upstream AMD fork and its separate launcher.
A fork of [VIctory](https://github.com/Marvisak/VIctory), a compatibility layer A fork of [VIctory](https://github.com/Marvisak/VIctory), a compatibility layer
that runs an Xbox Series title natively on Windows from files the user supplies. that runs an Xbox Series title natively on Windows from files the user supplies.
This one is about **speed on AMD RDNA 3**: the world at 30 frames a second on This one is about **speed on AMD RDNA 3**: the world at 30 frames a second on
+442 -47
View File
@@ -426,6 +426,48 @@ fn neutral_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<ID3D12Res
static FLIPS: Mutex<Vec<Flip>> = Mutex::new(Vec::new()); static FLIPS: Mutex<Vec<Flip>> = Mutex::new(Vec::new());
/// Deferred slot flips recorded into an open or not-yet-submitted command
/// list (`HostHeap::flip`), tracked so a one-shot decoration bake draw can
/// promote them out of the `neutral()` gray stand-in before sampling them.
pub(crate) struct PendingListFlip {
id: u64,
pub(crate) origin: (usize, u64),
flip: Flip,
}
impl PendingListFlip {
pub(crate) fn index(&self) -> u32 {
self.flip.index
}
pub(crate) fn handle(&self) -> u64 {
self.flip.handle
}
pub(crate) fn key(&self) -> u64 {
self.flip.key
}
}
static NEXT_PENDING_FLIP: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
static PENDING_LIST_FLIPS: Mutex<Vec<PendingListFlip>> = Mutex::new(Vec::new());
static PENDING_LIST_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
fn take_pending_list_flip(id: u64) -> Option<Flip> {
if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) == 0 {
return None;
}
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
let pos = pending.iter().position(|p| p.id == id)?;
let entry = pending.swap_remove(pos);
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
Some(entry.flip)
}
fn remove_pending_list_flip(id: u64) {
let _ = take_pending_list_flip(id);
}
/// Makes the slots whose new texture's upload has run /// Makes the slots whose new texture's upload has run
/// ([`HostHeap::texture_slots_flip`]); on any thread. Not if the heap is at /// ([`HostHeap::texture_slots_flip`]); on any thread. Not if the heap is at
/// something else: the next texture pass does. /// something else: the next texture pass does.
@@ -714,6 +756,12 @@ impl Spans {
/// pass last took the ranges ([`page_written`]). Kept apart from /// pass last took the ranges ([`page_written`]). Kept apart from
/// [`REMAPPED`] so that what such writes do is counted by itself. /// [`REMAPPED`] so that what such writes do is counted by itself.
static PAGE_WRITTEN: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new()); static PAGE_WRITTEN: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
/// Physical-page writes retained specifically for one-shot decoration/ped
/// texture bakes when `VICTORY_PAGE_WRITES` bit 2 is off (the default): normal
/// frames stay free of queue flooding while every bake still sees freshly
/// DirectStorage-streamed texture bytes immediately instead of waiting on
/// `RECHECK_FRAMES`.
static BAKE_PAGE_WRITTEN: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
/// Since the start: such ranges kept for a pass; ranges dropped because no /// Since the start: such ranges kept for a pass; ranges dropped because no
/// pass took them; slots of placed textures that held bytes of them when a /// pass took them; slots of placed textures that held bytes of them when a
@@ -1105,29 +1153,46 @@ pub(crate) fn device_removed() -> Option<String> {
pub(crate) static PLACED_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); 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); 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 /// Bytes per element and typed integer format bits of a buffer view, decoded
/// them for indexed reads (structured: the stride; raw: 1, the index is the /// in a single pass over the view descriptor; `(None, 0)` if not a buffer view.
/// byte; typed: the format's); `None` if `view` is not a buffer view. fn view_stride_and_kind(view: &View) -> (Option<u32>, u32) {
fn view_stride(view: &View) -> Option<u32> { use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED};
let (stride, raw, format) = view_elements(view)?; let Some((stride, raw, format)) = view_elements(view) else {
Some(if stride > 0 { return (None, 0);
};
let bytes = if stride > 0 {
stride stride
} else if raw { } else if raw {
1 1
} else { } else {
crate::resource::element(format).map_or(0, |(bytes, _)| bytes as u32) crate::resource::element(format).map_or(0, |(bytes, _)| bytes as u32)
}) };
let kind = if stride == 0 && !raw {
match format {
3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62 => VIEW_INTEGER,
4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64 => VIEW_INTEGER | VIEW_SIGNED,
_ => 0,
}
} else {
0
};
(Some(bytes), kind)
} }
/// What else the table of strides says of a typed buffer view of an integer /// Packed [`victory_shader::emit::SLOT_STRIDES`] word for `view`.
/// format (`victory_shader::emit::VIEW_INTEGER`); 0 for any other view. fn view_stride_word(view: &View) -> u32 {
let (stride, kind) = view_stride_and_kind(view);
stride.unwrap_or(0) | kind
}
#[cfg(test)]
fn view_stride(view: &View) -> Option<u32> {
view_stride_and_kind(view).0
}
#[cfg(test)]
fn view_kind(view: &View) -> u32 { fn view_kind(view: &View) -> u32 {
use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED}; view_stride_and_kind(view).1
match view_elements(view) {
Some((0, false, 3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62)) => VIEW_INTEGER,
Some((0, false, 4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64)) => VIEW_INTEGER | VIEW_SIGNED,
_ => 0,
}
} }
/// A buffer view's structure stride, whether it is raw, and its format; /// A buffer view's structure stride, whether it is raw, and its format;
@@ -1740,7 +1805,7 @@ impl HostHeap {
pub(crate) fn texture_news(&self) -> (u64, bool) { pub(crate) fn texture_news(&self) -> (u64, bool) {
let writes = self.textures.lock().unwrap_or_else(|e| e.into_inner()).writes; let writes = self.textures.lock().unwrap_or_else(|e| e.into_inner()).writes;
let noted = |ranges: &Mutex<Vec<(u64, u64)>>| !ranges.lock().unwrap_or_else(|e| e.into_inner()).is_empty(); let noted = |ranges: &Mutex<Vec<(u64, u64)>>| !ranges.lock().unwrap_or_else(|e| e.into_inner()).is_empty();
(writes, noted(&REMAPPED) || noted(&PAGE_WRITTEN)) (writes, noted(&REMAPPED) || noted(&PAGE_WRITTEN) || noted(&BAKE_PAGE_WRITTEN))
} }
/// Every title slot of the queue that is due at `frame`, and whether /// Every title slot of the queue that is due at `frame`, and whether
@@ -1888,7 +1953,48 @@ impl HostHeap {
if ranges.is_empty() { if ranges.is_empty() {
return 0; return 0;
} }
self.slots_written_under(&ranges, frame, crate::watch::page_writes() & 2 != 0)[2] let due = crate::watch::page_writes() & 2 != 0;
let made_due = self.slots_written_under(&ranges, frame, due)[2];
if !due {
let mut kept = BAKE_PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
kept.extend(ranges);
if kept.len() > 256 {
join(&mut kept);
const MOST: usize = 1 << 14;
if kept.len() > MOST {
let drop_n = kept.len() - MOST;
kept.drain(..drop_n);
}
}
}
made_due
}
/// Wakes uploaded placed-texture slots touched by recent physical-page
/// writes (DirectStorage completions) immediately (`due = frame`) right
/// before a one-shot ped/decoration bake draw.
pub(crate) fn texture_slots_bake_written(&self, frame: u64) -> usize {
let mut ranges = std::mem::take(&mut *BAKE_PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()));
if ranges.is_empty() {
return 0;
}
join(&mut ranges);
let mut slots: Vec<u32> = {
let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
ranges.iter().flat_map(|&(start, end)| placed.slots_holding(start, end)).collect()
};
if slots.is_empty() {
return 0;
}
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());
slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0));
for &slot in &slots {
textures.changed(slot, frame, frame);
}
slots.len()
} }
/// [`HostHeap::texture_slots_page_written`] for `ranges` (start, end): /// [`HostHeap::texture_slots_page_written`] for `ranges` (start, end):
@@ -2183,6 +2289,7 @@ impl HostHeap {
/// reads the table's dynamic slots). /// reads the table's dynamic slots).
pub(crate) fn mirror_after(&self, list: &crate::host::HostList, index: u32, handle: u64) { pub(crate) fn mirror_after(&self, list: &crate::host::HostList, index: u32, handle: u64) {
if show_after() if show_after()
&& !crate::texture::BAKING.get()
&& index < self.count && index < self.count
&& !self.texture_slot_made_from(index, handle) && !self.texture_slot_made_from(index, handle)
&& let Some(view) = super::view(handle) && let Some(view) = super::view(handle)
@@ -2197,14 +2304,143 @@ impl HostHeap {
} }
fn flip(&self, list: &crate::host::HostList, index: u32, handle: u64, late: Option<u64>) { fn flip(&self, list: &crate::host::HostList, index: u32, handle: u64, late: Option<u64>) {
use std::sync::atomic::Ordering::{Relaxed, Release};
let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle)); let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle));
let id = NEXT_PENDING_FLIP.fetch_add(1, Relaxed);
let origin = (std::ptr::from_ref(list) as usize, list.epoch());
{
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
pending.push(PendingListFlip {
id,
origin,
flip: Flip { after: 0, heap, index, handle, key, late },
});
PENDING_LIST_COUNT.store(pending.len(), Release);
}
struct PendingGuard(u64);
impl PendingGuard {
fn id(&self) -> u64 {
self.0
}
}
impl Drop for PendingGuard {
fn drop(&mut self) {
remove_pending_list_flip(self.0);
}
}
let guard = PendingGuard(id);
list.defer_host(move || { list.defer_host(move || {
let after = crate::host::submissions().0; // Call a `&self` method so Rust 2021+ moves the whole `guard`
let flip = Flip { after, heap, index, handle, key, late }; // into this closure rather than copying `guard.0` and dropping
// `guard` immediately at the end of `flip()`.
let Some(mut flip) = take_pending_list_flip(guard.id()) else {
return;
};
flip.after = crate::host::submissions().0;
FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip); FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip);
}); });
} }
/// Whether any deferred slot flip or view remake for this heap requires
/// settling in-flight GPU submissions before exposing real textures to a
/// one-shot decoration bake draw.
pub(crate) fn needs_gpu_settle_for_bake(&self) -> bool {
let own = std::ptr::from_ref(self) as usize;
let finished = crate::host::submissions().1;
if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) > 0 {
let pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
if pending.iter().any(|p| p.flip.heap == own) {
return true;
}
}
{
let flips = FLIPS.lock().unwrap_or_else(|e| e.into_inner());
if flips.iter().any(|f| f.heap == own && f.after > finished) {
return true;
}
}
let after = RESHOWN_AFTER.lock().unwrap_or_else(|e| e.into_inner());
after.iter().any(|&(at, _)| at > finished)
}
/// Drains deferred flips still sitting in unsubmitted command lists for
/// this heap so a decoration bake can mirror them out of `neutral()`.
/// Entries that cannot be promoted yet (unmapped memory or deferred
/// staging) must be returned via [`HostHeap::restore_pending_list_flip`].
pub(crate) fn take_pending_list_flips(&self) -> Vec<PendingListFlip> {
if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) == 0 {
return Vec::new();
}
let own = std::ptr::from_ref(self) as usize;
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
let (mine, rest): (Vec<PendingListFlip>, Vec<PendingListFlip>) =
pending.drain(..).partition(|p| p.flip.heap == own);
*pending = rest;
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
mine
}
/// Re-queues an unpromoted deferred flip drained by
/// [`HostHeap::take_pending_list_flips`] so its originating command list
/// still flips it out of `neutral()` once submitted.
pub(crate) fn restore_pending_list_flip(&self, item: PendingListFlip) {
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
pending.push(item);
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
}
/// Whether title descriptor slot `handle` still holds record `key`.
pub(crate) fn slot_still_at(&self, handle: u64, key: u64) -> bool {
key != 0 && record_key(handle) == key
}
/// Looks up `(view, key)` for slot `index` prior to a synchronous bake
/// upload without replacing its current host descriptor with `neutral()`;
/// [`HostHeap::publish_uploaded_slot`] exposes the real descriptor and
/// updates `Spans`/stride tracking once the GPU copy finishes.
pub(crate) fn prepare_bake_slot(&self, index: u32, handle: u64) -> Option<(View, u64)> {
if index >= self.count {
return None;
}
let key = record_key(handle);
let view = (key != 0).then(|| view_at(key as u32, (key >> 32) as u32)).flatten()?;
Some((view, key))
}
/// Exposes the real host descriptor for slot `index` after its synchronous
/// bake upload has completed on the GPU, updating `Spans`/stride tracking
/// without re-queuing the slot in `TextureQueue`.
pub(crate) fn publish_uploaded_slot(&self, index: u32, handle: u64, key: u64) -> bool {
if index >= self.count || key == 0 {
return false;
}
let (published, stale) = {
let _made = self.made.lock(index);
if self.made.get(index) == Some(key) {
return false;
}
if record_key(handle) != key {
return false;
}
let Some(view) = view_at(key as u32, (key >> 32) as u32) else {
return false;
};
let stale = self.note_buffer(index, Some(&view), true);
if let Some(kept) = make(&view, self.at(index)) {
self.put(index);
self.quick_is(index, 0);
self.clear_twin(index);
self.made.set(index, key);
self.keep(index, kept);
(true, stale)
} else {
(false, stale)
}
};
self.unmake_stale(index, stale);
published
}
/// Makes the slots whose new view's upload has run /// Makes the slots whose new view's upload has run
/// ([`HostHeap::texture_slot_flip`]); returns how many. /// ([`HostHeap::texture_slot_flip`]); returns how many.
pub(crate) fn texture_slots_flip(&self) -> usize { pub(crate) fn texture_slots_flip(&self) -> usize {
@@ -2222,6 +2458,7 @@ impl HostHeap {
ready ready
}; };
let mut flipped = 0; let mut flipped = 0;
let mut late_flipped = 0;
for f in ready { for f in ready {
let _made = self.made.lock(f.index); let _made = self.made.lock(f.index);
let Some(shown) = self.made.get(f.index) else { let Some(shown) = self.made.get(f.index) else {
@@ -2264,6 +2501,7 @@ impl HostHeap {
same_bytes(was, f.key); same_bytes(was, f.key);
} }
if let Some(since) = f.late { if let Some(since) = f.late {
late_flipped += 1;
let frames = crate::frame::current().saturating_sub(since); let frames = crate::frame::current().saturating_sub(since);
let n = LATE[0].fetch_add(1, Relaxed) + 1; let n = LATE[0].fetch_add(1, Relaxed) + 1;
let all = LATE[1].fetch_add(frames, Relaxed) + frames; let all = LATE[1].fetch_add(frames, Relaxed) + frames;
@@ -2282,7 +2520,7 @@ impl HostHeap {
} }
} }
FLIPPED[0].fetch_add(flipped as u64, Relaxed); FLIPPED[0].fetch_add(flipped as u64, Relaxed);
flipped flipped + late_flipped
} }
/// The memory of the texture title slot `index` views is there (again): /// The memory of the texture title slot `index` views is there (again):
@@ -2311,6 +2549,7 @@ impl HostHeap {
} }
self.put(index); self.put(index);
self.clear_twin(index); self.clear_twin(index);
self.write_stride(index, 0);
self.keep(index, None); self.keep(index, None);
} }
@@ -2506,15 +2745,8 @@ impl HostHeap {
textures.remove(slot); textures.remove(slot);
} }
} }
let stride = view.and_then(view_stride); let (stride, kind) = view.map_or((None, 0), view_stride_and_kind);
let kind = view.map_or(0, view_kind); self.write_stride(index, stride.unwrap_or(0) | kind);
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) | kind) };
}
let was = if stride.is_some() { let was = if stride.is_some() {
self.buffers.put(index); self.buffers.put(index);
true true
@@ -2527,6 +2759,20 @@ impl HostHeap {
stale stale
} }
/// Writes `word` (stride | format kind) for view-heap slot `index` into
/// the host's [`victory_shader::emit::SLOT_STRIDES`] table.
#[inline]
fn write_stride(&self, index: u32, word: u32) {
if let Some((_, _, data)) = &self.strides
&& index < victory_shader::emit::SLOT_STRIDES_COUNT
{
// SAFETY: inside the mapping; shaders read it while we write (a
// single aligned dword: either value is one the slot had, and
// dynamic slots are exclusively owned until submission finishes).
unsafe { (*data as *mut u32).add(index as usize).write_volatile(word) };
}
}
/// Gives back `n` dynamic slots from `first` (an index [`dynamic`] /// Gives back `n` dynamic slots from `first` (an index [`dynamic`]
/// returned). /// returned).
/// ///
@@ -2554,6 +2800,7 @@ impl HostHeap {
} }
self.put(index); self.put(index);
self.twin_made(index, kept.is_some() && twinned(view)); self.twin_made(index, kept.is_some() && twinned(view));
self.write_stride(index, if kept.is_some() { view_stride_word(view) } else { 0 });
self.keep(index, kept.flatten()); self.keep(index, kept.flatten());
} }
@@ -2586,13 +2833,14 @@ impl HostHeap {
} }
let twin = twinned(&view); let twin = twinned(&view);
let kept = make_twinned(&view, views.slot(at), Some(views.slot(at + 1)))?; let kept = make_twinned(&view, views.slot(at), Some(views.slot(at + 1)))?;
let stride_word = view_stride_word(&view);
let listed = Listed { let listed = Listed {
kind: crate::draw::view_kind(&view), kind: crate::draw::view_kind(&view),
texture: is_texture_view(&view), texture: is_texture_view(&view),
ready: (0, 0, false), ready: (0, 0, false),
tabled: None, tabled: None,
}; };
views.made.insert(words, ListView { view, at, twin, kept, listed }); views.made.insert(words, ListView { view, at, twin, stride_word, kept, listed });
} }
let made = &views.made[&words]; let made = &views.made[&words];
self.copy_from(index, views.slot(made.at)); self.copy_from(index, views.slot(made.at));
@@ -2602,6 +2850,7 @@ impl HostHeap {
} else { } else {
self.clear_twin(index); self.clear_twin(index);
} }
self.write_stride(index, made.stride_word);
self.keep(index, made.kept.clone()); self.keep(index, made.kept.clone());
Some(made.listed) Some(made.listed)
}) })
@@ -2626,6 +2875,7 @@ impl HostHeap {
} else { } else {
null_view(self.at(index)); null_view(self.at(index));
self.put(index); self.put(index);
self.write_stride(index, 0);
} }
self.clear_twin(index); self.clear_twin(index);
self.keep(index, None); self.keep(index, None);
@@ -2712,6 +2962,7 @@ impl HostHeap {
self.put(index); self.put(index);
// (Bound by its handle, not read by index.) // (Bound by its handle, not read by index.)
self.clear_twin(index); self.clear_twin(index);
self.write_stride(index, 1);
self.keep(index, Some(buffer.clone())); self.keep(index, Some(buffer.clone()));
} }
@@ -2721,6 +2972,7 @@ impl HostHeap {
null_buffer_view(self.at(index)); null_buffer_view(self.at(index));
self.put(index); self.put(index);
self.clear_twin(index); self.clear_twin(index);
self.write_stride(index, 0);
self.keep(index, None); self.keep(index, None);
} }
@@ -2755,6 +3007,7 @@ impl HostHeap {
}; };
self.put(index); self.put(index);
self.clear_twin(index); self.clear_twin(index);
self.write_stride(index, 1);
self.keep(index, Some(buffer.clone())); self.keep(index, Some(buffer.clone()));
} }
@@ -2784,6 +3037,7 @@ impl HostHeap {
}; };
self.put(index); self.put(index);
self.clear_twin(index); self.clear_twin(index);
self.write_stride(index, 0);
self.keep(index, None); self.keep(index, None);
} }
@@ -2841,6 +3095,7 @@ impl HostHeap {
unsafe { host.device.CreateShaderResourceView(buffer, Some(&raw), twin) }; unsafe { host.device.CreateShaderResourceView(buffer, Some(&raw), twin) };
} }
self.twin_made(index, twin.is_some()); self.twin_made(index, twin.is_some());
self.write_stride(index, 0);
// After the descriptor: what it showed is let go when nothing shows // After the descriptor: what it showed is let go when nothing shows
// it any more. // it any more.
self.keep(index, holds.then(|| buffer.clone())); self.keep(index, holds.then(|| buffer.clone()));
@@ -4084,24 +4339,27 @@ fn make_twinned(
} }
const BUFFER: u32 = 1; const BUFFER: u32 = 1;
if resource[0] != BUFFER { 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.
// Each texture is said once (the first 64), with how many times
// such a view was asked for so far: what shaders write through
// them is lost.
static SAID: Mutex<std::collections::BTreeSet<u64>> = Mutex::new(std::collections::BTreeSet::new());
static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let times = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
let at = u64::from(desc[10]) | u64::from(desc[11]) << 32; let at = u64::from(desc[10]) | u64::from(desc[11]) << 32;
let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); if *unordered || at != 0 {
if (said.len() < 64 && said.insert(at)) || times.is_power_of_two() { // shortcut: unordered access to a texture the title placed
tracing::warn!( // itself is not mirrored; give it a resource as shader
address = format_args!("{at:#x}"), // views of such textures get when a dispatch writes one.
times, // Each texture is said once (the first 64), with how many times
"placed unordered texture view not mirrored (null: writes through it are lost): resource {resource:?}, view {:?}", // such a view was asked for so far: what shaders write through
&desc[..10] // them is lost.
); static SAID: Mutex<std::collections::BTreeSet<u64>> = Mutex::new(std::collections::BTreeSet::new());
static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let times = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
if (said.len() < 64 && said.insert(at)) || times.is_power_of_two() {
tracing::warn!(
address = format_args!("{at:#x}"),
unordered = *unordered,
times,
"placed texture view not mirrored (null): resource {resource:?}, view {:?}",
&desc[..10]
);
}
} }
return None; return None;
} }
@@ -5446,6 +5704,71 @@ mod tests {
heap.release(last, 1); heap.release(last, 1);
assert_eq!(heap.dynamic(2), None); assert_eq!(heap.dynamic(2), None);
} }
#[test]
fn dynamic_slots_populate_and_clear_stride_table() {
use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED};
let Some(heap) = HostHeap::new(false, 4) else {
return; // no host GPU
};
let Some((_, _, data)) = heap.strides else {
panic!("view heap should allocate strides table");
};
let read_stride = |slot: u32| -> u32 {
// SAFETY: inside `SLOT_STRIDES_COUNT` mapping of `heap.strides`.
unsafe { *(data as *const u32).add(slot as usize) }
};
let memory = vec![0u64; 1 << 11];
let addr = (memory.as_ptr() as u64).next_multiple_of(4096);
let placed_typed = |uav: bool, dxgi_fmt: u32, elems: u32| {
let resource: [u32; 14] = [1, 0, 0, 0, 4096, 0, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0];
let mut desc = [0u32; 16];
// [format, dim=1 (buffer), mapping/pad, ..., num_elements @6, stride @7, flags @8]
let words = if uav {
[dxgi_fmt, 1, 0, 0, elems, 0, 0, 0, 0, 0]
} else {
[dxgi_fmt, 1, 5768, 0, 0, 0, elems, 0, 0, 0]
};
desc[..10].copy_from_slice(&words);
(desc[10], desc[11]) = (addr as u32, (addr >> 32) as u32);
View::Placed(uav, resource, desc)
};
let s0 = heap.dynamic(4).unwrap();
// R16G16B16A16_UINT (12): 8 bytes + VIEW_INTEGER
let u16x4 = placed_typed(true, 12, 64);
heap.make_at(s0, &u16x4);
assert_eq!(read_stride(s0), 8 | VIEW_INTEGER);
// R16_SINT (59): 2 bytes + VIEW_INTEGER | VIEW_SIGNED
let s16 = placed_typed(false, 59, 64);
heap.make_at(s0 + 1, &s16);
assert_eq!(read_stride(s0 + 1), 2 | VIEW_INTEGER | VIEW_SIGNED);
// R16G16B16A16_FLOAT (10): 8 bytes, no integer bits
let f16x4 = placed_typed(true, 10, 64);
heap.make_at(s0 + 2, &f16x4);
assert_eq!(read_stride(s0 + 2), 8);
// Clearing / nulling / raw views overwrite stale bits cleanly.
heap.make_null(s0);
assert_eq!(read_stride(s0), 0);
heap.null_raw_at(s0 + 1);
assert_eq!(read_stride(s0 + 1), 0);
heap.null_raw_uav_at(s0 + 2);
assert_eq!(read_stride(s0 + 2), 0);
// `make_listed` (both cold creation and cached copy hit) must populate strides.
let mut slot_mem = [0u32; 8];
crate::descriptor::record(slot_mem.as_mut_ptr() as u64, u16x4);
let rec = [slot_mem[0], slot_mem[1], slot_mem[2]];
assert!(heap.make_listed(0x1234, rec, s0).is_some());
assert_eq!(read_stride(s0), 8 | VIEW_INTEGER);
heap.make_null(s0 + 3);
assert_eq!(read_stride(s0 + 3), 0);
assert!(heap.make_listed(0x1234, rec, s0 + 3).is_some());
assert_eq!(read_stride(s0 + 3), 8 | VIEW_INTEGER);
}
} }
/// What is known of a record a list's tables hold, in that recording of the /// What is known of a record a list's tables hold, in that recording of the
@@ -5466,6 +5789,7 @@ struct ListView {
/// Its descriptor's slot in [`ListViews`]; its raw twin's is the next. /// Its descriptor's slot in [`ListViews`]; its raw twin's is the next.
at: u32, at: u32,
twin: bool, twin: bool,
stride_word: u32,
kept: Kept, kept: Kept,
listed: Listed, listed: Listed,
} }
@@ -5544,3 +5868,74 @@ pub(crate) fn note_listed(recording: u64, words: [u32; 3], listed: Listed) {
pub(crate) fn list_views() -> bool { pub(crate) fn list_views() -> bool {
crate::toggled!("VICTORY_LIST_VIEWS") crate::toggled!("VICTORY_LIST_VIEWS")
} }
#[cfg(test)]
mod bake_flip_tests {
use super::*;
#[test]
fn pending_list_flips_promote_once_and_clean_up() {
let heap = 0xdead_beefusize;
let id1 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let id2 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
{
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
pending.push(PendingListFlip {
id: id1,
origin: (1, 1),
flip: Flip { after: 0, heap, index: 7, handle: 0, key: 11, late: Some(1) },
});
pending.push(PendingListFlip {
id: id2,
origin: (2, 1),
flip: Flip { after: 0, heap, index: 8, handle: 0, key: 12, late: Some(1) },
});
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
}
let taken = take_pending_list_flip(id1).expect("id1 should be present");
assert_eq!(taken.index, 7);
assert!(take_pending_list_flip(id1).is_none(), "second take must be a no-op");
remove_pending_list_flip(id2);
assert!(take_pending_list_flip(id2).is_none(), "removed entry must be gone");
}
#[test]
fn deferred_flip_closure_keeps_pending_entry_alive_until_called_or_dropped() {
let heap = 0xcafe_babeusize;
let id1 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let id2 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
{
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
for (id, idx) in [(id1, 10), (id2, 11)] {
pending.push(PendingListFlip {
id,
origin: (3, 1),
flip: Flip { after: 0, heap, index: idx, handle: 0, key: 20, late: Some(1) },
});
}
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
}
struct TestGuard(u64);
impl TestGuard {
fn id(&self) -> u64 {
self.0
}
}
impl Drop for TestGuard {
fn drop(&mut self) {
remove_pending_list_flip(self.0);
}
}
let make_cb = |id: u64| -> Box<dyn Fn() -> Option<u32> + Send + 'static> {
let guard = TestGuard(id);
Box::new(move || take_pending_list_flip(guard.id()).map(|f| f.index))
};
let cb1 = make_cb(id1);
let cb2 = make_cb(id2);
// Must still be present after make_cb returns (guard moved, not dropped).
assert_eq!(cb1(), Some(10));
assert_eq!(cb1(), None);
drop(cb2);
assert!(take_pending_list_flip(id2).is_none(), "dropping uncalled closure cleans up entry");
}
}
+396 -73
View File
@@ -217,12 +217,45 @@ const BAKE_AHEAD: [u64; 2] = [12, 2];
/// until something is new, the next bakes of the frame need no pass. /// until something is new, the next bakes of the frame need no pass.
static BAKE_SERVED: AtomicU64 = AtomicU64::new(0); static BAKE_SERVED: AtomicU64 = AtomicU64::new(0);
/// Free-threaded wrapper around a reusable upload-only [`HostList`] protected
/// by [`BAKE_UPLOAD`]. D3D12 command allocators, lists, and retained COM
/// resources are free-threaded when externally synchronized.
struct BakeList(HostList);
// SAFETY: accessed exclusively under `BAKE_UPLOAD`'s mutex.
unsafe impl Send for BakeList {}
/// Serializes synchronous one-shot ped/decoration bake uploads across
/// concurrent `VICTORY_THIN=1` recording threads and owns the reusable
/// upload-only host command list.
static BAKE_UPLOAD: std::sync::Mutex<Option<BakeList>> = std::sync::Mutex::new(None);
/// Pending descriptor publications for a synchronous bake upload pass: slots
/// stay on `neutral()` (or their previous compatible view) until the dedicated
/// upload list has finished executing on the host GPU.
struct BakeSync {
publish: Vec<(u32, u64, u64)>,
keep: Vec<std::sync::Arc<crate::resource::HostTexture>>,
}
/// The pixel shaders of the title's decoration bake (the title: /// The pixel shaders of the title's decoration bake (the title:
/// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the /// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the
/// frame listings print it. They draw into a 256x256 corner of 2048x2048 /// frame listings print it. They draw into a 256x256 corner of 2048x2048
/// targets and name no texture in a table. /// targets and name no texture in a table.
pub(crate) const BAKE_PIXEL_SHADERS: [&str; 4] = pub(crate) const BAKE_PIXEL_SHADERS: [&str; 7] = [
["c0a7fe77b1862e10", "0d1575a396dfe513", "b7cfd8dda91ebb6b", "280967ad158cee0b"]; "c0a7fe77b1862e10",
"0d1575a396dfe513",
"b7cfd8dda91ebb6b",
"280967ad158cee0b",
"fa455c8a3c32577b",
"d126bcae5d5d8d26",
"fcee612943c008e0",
];
/// Geometry stages shared by every ped texture compositor / decoration bake
/// permutation (`vertex 089d6271be6650ef` fullscreen-triangle ped baker and
/// `mesh d4111a6e6ea49d91` decoration projection mesh), catching pixel-shader
/// permutations beyond `BAKE_PIXEL_SHADERS`.
const BAKE_GEOMETRY_SHADERS: [&str; 2] = ["089d6271be6650ef", "d4111a6e6ea49d91"];
/// Since the start: early runs of the texture pass, and those of them /// Since the start: early runs of the texture pass, and those of them
/// made for a bake draw. /// made for a bake draw.
@@ -1714,6 +1747,24 @@ impl State {
} }
continue; continue;
} }
if srv && slot == victory_shader::emit::SLOT_TABLE_STRIDES {
// Ours: the shader inspects typed view kinds for its
// descriptor tables only (already mirrored by `tables`),
// so bind the strides buffer without sweeping the heap.
match self.heap_strides(list) {
// SAFETY: an open list; the table lives as long
// as the heap the list holds.
Some(gpu) => unsafe {
if compute {
l.SetComputeRootShaderResourceView(param, gpu);
} else {
l.SetGraphicsRootShaderResourceView(param, gpu);
}
},
None => once!("a shader inspects table view kinds without a view heap set"),
}
continue;
}
let tabled = srv && crate::pipeline::host::bounded_root_srvs(); let tabled = srv && crate::pipeline::host::bounded_root_srvs();
let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot))
else { else {
@@ -1872,7 +1923,10 @@ impl State {
Some((index, shadow)) => (*index, address.zip(shadow.clone())), Some((index, shadow)) => (*index, address.zip(shadow.clone())),
None => { None => {
let shadow = address.and_then(|a| find(a).map(|s| (a, s))); let shadow = address.and_then(|a| find(a).map(|s| (a, s)));
let Some(index) = host.dynamic(1) else { let Some(index) = host.dynamic(1).or_else(|| {
crate::host::settle_for_fence();
host.dynamic(1)
}) else {
return false; return false;
}; };
self.dynamic.push((key.0, index, 1)); self.dynamic.push((key.0, index, 1));
@@ -1943,7 +1997,10 @@ impl State {
Some((index, shadow)) => (*index, address.zip(shadow.clone())), Some((index, shadow)) => (*index, address.zip(shadow.clone())),
None => { None => {
let shadow = address.and_then(|a| crate::shadow::find(a, 1).map(|s| (a, s))); let shadow = address.and_then(|a| crate::shadow::find(a, 1).map(|s| (a, s)));
let Some(index) = host.dynamic(1) else { let Some(index) = host.dynamic(1).or_else(|| {
crate::host::settle_for_fence();
host.dynamic(1)
}) else {
return false; return false;
}; };
self.dynamic.push((key.0, index, 1)); self.dynamic.push((key.0, index, 1));
@@ -2053,7 +2110,7 @@ impl State {
#[cfg(feature = "diagnostics")] #[cfg(feature = "diagnostics")]
let refreshed = std::time::Instant::now(); let refreshed = std::time::Instant::now();
stage.next("the heap pass: textures"); stage.next("the heap pass: textures");
self.heap_textures(list, heap, host); let _ = self.heap_textures(list, heap, host, None);
stage.end(); stage.end();
#[cfg(feature = "diagnostics")] #[cfg(feature = "diagnostics")]
HEAP_SPLIT[2].fetch_add(refreshed.elapsed().as_nanos() as u64, Ordering::Relaxed); HEAP_SPLIT[2].fetch_add(refreshed.elapsed().as_nanos() as u64, Ordering::Relaxed);
@@ -2062,20 +2119,179 @@ impl State {
Some(gpu) Some(gpu)
} }
/// The GPU address of the bound view heap's stride/kind table without
/// running the bindless heap buffer/texture sweep (for shaders that only
/// inspect descriptors already mirrored via their descriptor tables).
fn heap_strides(&self, list: &HostList) -> Option<u64> {
let heap = self
.heaps
.iter()
.filter(|&&h| h != 0)
.map(|&h| crate::descriptor::heap(h as This))
.find(|h| !h.samplers())?;
let host = heap.host()?;
let gpu = host.strides_gpu()?;
// Tag bit 1 (distinct from `heap_buffers`'s `| 1` and aligned guest pointers).
if list.first_use(gpu as usize | 2)
&& let Some(buffer) = host.strides_buffer()
{
list.keep(buffer);
}
Some(gpu)
}
/// Ensures textures claimed by background copy-queue uploads
/// (`VICTORY_UPLOAD_AHEAD=1`) or deferred behind the `neutral()` gray
/// stand-in (`VICTORY_SHOW_AFTER=1` / `shows_other`) have finished
/// uploading and flipped to their real descriptors before a one-shot
/// decoration bake draw samples them.
fn flush_for_bake(
&self,
list: &HostList,
host: &crate::descriptor::host::HostHeap,
mut sync: Option<&mut BakeSync>,
) {
static RESCUED: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4];
let drained = crate::texture::ahead::drain();
let mut settled = false;
let mut flipped = 0usize;
for _ in 0..4 {
let need_settle = host.needs_gpu_settle_for_bake();
if need_settle {
settled = true;
crate::host::settle_for_fence();
}
flipped += host.texture_views_remade();
flipped += host.texture_slots_flip();
if !need_settle || !host.needs_gpu_settle_for_bake() {
break;
}
}
let pending = host.take_pending_list_flips();
let mut promoted = 0usize;
if !pending.is_empty() {
let this_list = (std::ptr::from_ref(list) as usize, list.epoch());
let sampled = UsedResource {
kind: ResourceType::Srv,
root: RootType::Table,
table_offset_dwords: 0,
lower_bound: 0,
stride: 0,
dwords: 8,
user_data: 0,
slot: 0,
};
for item in pending {
let (origin, index, handle, key) = (item.origin, item.index(), item.handle(), item.key());
if !host.slot_still_at(handle, key) {
continue;
}
let Some(view) = crate::descriptor::view(handle) else {
continue;
};
if let View::Placed(_, resource, desc) = &view {
let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
let len = crate::resource::placed_bytes(resource).unwrap_or(1);
if crate::texture::mapped_bytes(address as *const u8, len as usize) == 0 {
host.restore_pending_list_flip(item);
continue;
}
}
if sync.is_some() || origin != this_list {
let placed = crate::descriptor::host::placed_texture(&view);
if let Some(&View::Shader(resource, _)) = placed.as_ref().or(Some(&view)) {
let resource = resource as This;
let texture = crate::resource::host_resource(resource);
let title_fills = texture.is_some_and(crate::texture::title_written);
let first = match (&placed, &view) {
(Some(_), View::Placed(_, _, desc)) => crate::resource::first_mip(desc),
_ => 0,
};
if let (Some(sync), Some(copy)) = (sync.as_deref_mut(), crate::resource::host_copy(resource)) {
sync.keep.push(copy);
}
if title_fills
&& !crate::texture::ahead::there(resource)
&& (sync.is_some() || !crate::texture::unchanged(resource, first))
{
let was_staged = crate::texture::is_staged(resource);
let _ = crate::residency::take_staging_deferred();
readable(list, sampled.kind, &view);
let failed = crate::residency::take_staging_deferred() || crate::residency::upload_refused();
if !was_staged {
crate::texture::unstage(resource);
}
if failed {
host.restore_pending_list_flip(item);
continue;
}
}
}
}
if let Some(sync) = sync.as_deref_mut() {
sync.publish.push((index, handle, key));
} else {
let _ = host.mirror(index, handle, true);
}
promoted += 1;
}
}
if drained > 0 || settled || flipped > 0 || promoted > 0 {
let n = RESCUED[0].fetch_add(1, Ordering::Relaxed) + 1;
let all_drained = RESCUED[1].fetch_add(drained as u64, Ordering::Relaxed) + drained as u64;
let all_flipped = RESCUED[2].fetch_add(flipped as u64, Ordering::Relaxed) + flipped as u64;
let all_promoted = RESCUED[3].fetch_add(promoted as u64, Ordering::Relaxed) + promoted as u64;
if n.is_power_of_two() {
tracing::info!(
frame = crate::frame::current(),
flushes = n,
drained_ahead = all_drained,
flipped = all_flipped,
promoted_from_lists = all_promoted,
settled,
"flushed deferred texture stand-ins before decoration bake"
);
}
}
}
/// Whether a graphics draw is a one-shot texture compositor / decoration
/// bake whose bindless texture inputs must be flushed and up to date
/// before recording the draw. Matches known bake pixel/geometry shaders
/// and structurally detects depth-less 4+ MRT square atlas bakes
/// (`>= 512x512`) so unseen NPC/head/clothing shader permutations never
/// bake `neutral()` or `null` stand-ins into permanent ped textures.
fn is_bake_draw(&self, p: &HostPipeline) -> bool {
if p.stages.iter().any(|s| {
let h = s.shader.hash.as_str();
BAKE_PIXEL_SHADERS.contains(&h) || BAKE_GEOMETRY_SHADERS.contains(&h)
}) {
return true;
}
self.depth == 0
&& self.targets.len() >= 4
&& self
.targets
.first()
.and_then(|&t| crate::resource::texture_kind(t as This))
.is_some_and(|(w, h, _)| w >= 512 && w == u64::from(h))
}
/// Runs the pass that uploads textures picked by index /// Runs the pass that uploads textures picked by index
/// ([`State::heap_textures`]) where nothing has asked for it yet /// ([`State::heap_textures`]) where nothing has asked for it yet
/// ([`early_budgets`]): once a frame for a few milliseconds, at the /// ([`early_budgets`]): once a frame for a few milliseconds, at the
/// frame's first draw with a view heap set, and with a larger budget /// frame's first draw with a view heap set, and with a larger budget
/// of its own before every draw whose pixel shader is one of the /// of its own before every draw whose pixel shader is one of the
/// title's bake programs. The uploads are recorded into `list` ahead /// title's bake programs. For decoration bakes, uploads run synchronously
/// of the draw being bound, as the world's pass records them. /// on a dedicated internal command list and descriptors are published only
/// after the GPU copy finishes so concurrent `VICTORY_THIN=1` lists can
/// never submit a bake draw ahead of its texture uploads.
fn early_textures(&self, list: &HostList, p: &HostPipeline, compute: bool) { fn early_textures(&self, list: &HostList, p: &HostPipeline, compute: bool) {
let (early_ms, bake_ms) = early_budgets(); let (early_ms, bake_ms) = early_budgets();
if compute || (early_ms == 0 && bake_ms == 0) { if compute || (early_ms == 0 && bake_ms == 0) {
return; return;
} }
let bake = bake_ms > 0 let is_bake = bake_ms > 0 && self.is_bake_draw(p);
&& p.stages.iter().any(|s| BAKE_PIXEL_SHADERS.contains(&s.shader.hash.as_str()));
static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
// The milliseconds this frame's bake draws have taken so far: a // The milliseconds this frame's bake draws have taken so far: a
// frame has several, and together they get `bake_ms`. // frame has several, and together they get `bake_ms`.
@@ -2085,15 +2301,9 @@ impl State {
if first { if first {
BAKED_MS.store(0, Ordering::Relaxed); BAKED_MS.store(0, Ordering::Relaxed);
} }
let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed)); if !is_bake && !(first && early_ms > 0) {
let budget = if bake && left > 0 {
// What a bake may read must be there now: up to 2 GiB.
(left, 2 << 30)
} else if first && early_ms > 0 {
(early_ms, 64 << 20)
} else {
return; return;
}; }
let Some(heap) = self let Some(heap) = self
.heaps .heaps
.iter() .iter()
@@ -2106,34 +2316,102 @@ impl State {
let Some(host) = heap.host() else { let Some(host) = heap.host() else {
return; return;
}; };
let bake = bake && left > 0; if is_bake {
if bake && !first && bake_exact() { let began = std::time::Instant::now();
let (writes, noted) = host.texture_news(); let mut bake_slot = BAKE_UPLOAD.lock().unwrap_or_else(|e| e.into_inner());
if !noted && BAKE_SERVED.load(Ordering::Relaxed) == writes + 1 { let gpu = crate::host::host();
if bake_slot.is_none()
&& let Some(gpu) = gpu
{
match gpu.new_list() {
Ok(upload_list) => *bake_slot = Some(BakeList(upload_list)),
Err(e) => tracing::warn!(error = %e, "no host list for synchronous bake uploads"),
}
}
let exact = bake_exact();
if let (Some(gpu), Some(BakeList(bake_list))) = (gpu, bake_slot.as_ref()) {
let mut sync = BakeSync { publish: Vec::new(), keep: Vec::new() };
crate::texture::BAKING.set(exact);
self.flush_for_bake(bake_list, host, Some(&mut sync));
let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed));
let run_pass = left > 0
&& (first
|| !exact
|| {
let (writes, noted) = host.texture_news();
noted || BAKE_SERVED.load(Ordering::Relaxed) != writes + 1
});
let mut served = false;
if run_pass {
let n = EARLY_TEXTURE_PASSES[1].fetch_add(1, Ordering::Relaxed) + 1;
if n.is_power_of_two() {
let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed));
tracing::info!(
frame,
bakes = n,
queued_at_the_last_pass = slots,
due_at_the_last_pass = due,
uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed),
"a draw of the title's decoration bake: textures picked by index are uploaded synchronously first (VICTORY_BAKE_TEXTURES_MS=0: not)"
);
}
BAKE_SERVED.store(0, Ordering::Relaxed);
PASS_BUDGET.set(Some((left, 2 << 30, true)));
served = self.heap_textures(bake_list, heap, host, Some(&mut sync));
PASS_BUDGET.set(None);
}
crate::texture::BAKING.set(false);
if bake_list.has_recorded_work() {
bake_list.close();
gpu.execute_sync_internal(bake_list);
bake_list.reset();
} else if !sync.publish.is_empty() {
crate::host::settle_for_fence();
}
for (index, handle, key) in sync.publish {
let _ = host.publish_uploaded_slot(index, handle, key);
}
host.texture_views_remade();
host.texture_slots_flip();
drop(sync.keep);
if run_pass && served && exact {
BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed);
}
BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed);
return; return;
} }
} // Fallback when no host GPU list can be created (e.g. headless tests).
let n = EARLY_TEXTURE_PASSES[usize::from(bake)].fetch_add(1, Ordering::Relaxed) + 1; crate::texture::BAKING.set(exact);
if bake && n.is_power_of_two() { self.flush_for_bake(list, host, None);
let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed)); crate::texture::BAKING.set(false);
tracing::info!( let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed));
frame, if left == 0 {
bakes = n, return;
queued_at_the_last_pass = slots, }
due_at_the_last_pass = due, if !first && exact {
uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed), let (writes, noted) = host.texture_news();
"a draw of the title's decoration bake: textures picked by index are uploaded first (VICTORY_BAKE_TEXTURES_MS=0: not)" if !noted && BAKE_SERVED.load(Ordering::Relaxed) == writes + 1 {
); return;
} }
let began = std::time::Instant::now(); }
PASS_BUDGET.set(Some((budget.0, budget.1, bake))); EARLY_TEXTURE_PASSES[1].fetch_add(1, Ordering::Relaxed);
crate::texture::BAKING.set(bake && bake_exact()); PASS_BUDGET.set(Some((left, 2 << 30, true)));
self.heap_textures(list, heap, host); crate::texture::BAKING.set(exact);
crate::texture::BAKING.set(false); let _ = self.heap_textures(list, heap, host, None);
PASS_BUDGET.set(None); crate::texture::BAKING.set(false);
if bake { PASS_BUDGET.set(None);
BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed);
return;
} }
let budget = if first && early_ms > 0 {
(early_ms, 64 << 20)
} else {
return;
};
EARLY_TEXTURE_PASSES[0].fetch_add(1, Ordering::Relaxed);
PASS_BUDGET.set(Some((budget.0, budget.1, false)));
let _ = self.heap_textures(list, heap, host, None);
PASS_BUDGET.set(None);
} }
/// The queue's side of the card accounting line /// The queue's side of the card accounting line
@@ -2230,10 +2508,11 @@ impl State {
list: &HostList, list: &HostList,
heap: &crate::descriptor::Heap, heap: &crate::descriptor::Heap,
host: &crate::descriptor::host::HostHeap, host: &crate::descriptor::host::HostHeap,
) { mut sync: Option<&mut BakeSync>,
) -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_TEXTURES").is_none_or(|v| v != "0")) { if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_TEXTURES").is_none_or(|v| v != "0")) {
return; return true;
} }
let memory = crate::host::host().and_then(|h| h.video_memory()); let memory = crate::host::host().and_then(|h| h.video_memory());
// `VICTORY_TEXTURE_STAGE_MB` sets it: a backlog of tens of thousands of // `VICTORY_TEXTURE_STAGE_MB` sets it: a backlog of tens of thousands of
@@ -2285,6 +2564,10 @@ impl State {
// Slots whose texture's memory the runtime mapped, unmapped or // Slots whose texture's memory the runtime mapped, unmapped or
// wrote since the last pass are due again. // wrote since the last pass are due again.
host.texture_slots_remapped(frame); host.texture_slots_remapped(frame);
let baking = crate::texture::BAKING.get();
if baking {
host.texture_slots_bake_written(frame);
}
host.texture_slots_short(frame); host.texture_slots_short(frame);
// The slots of textures whose first level with memory (levels on // The slots of textures whose first level with memory (levels on
// demand), or whose host copy for one with more levels, changed since // demand), or whose host copy for one with more levels, changed since
@@ -2298,11 +2581,6 @@ impl State {
host.texture_slots_waiting(frame); host.texture_slots_waiting(frame);
} }
let required = PASS_BUDGET.get().is_some_and(|(_, _, bake)| bake); let required = PASS_BUDGET.get().is_some_and(|(_, _, bake)| bake);
if !crate::residency::admit_texture_pass(required) {
BAKE_SERVED.store(0, Ordering::Relaxed);
return;
}
let baking = crate::texture::BAKING.get();
let (mut due, census) = host.texture_slots_due(frame, if baking { 1 << 16 } else { 4096 }); let (mut due, census) = host.texture_slots_due(frame, if baking { 1 << 16 } else { 4096 });
// (Those that are due later after all that are due.) // (Those that are due later after all that are due.)
let on_time = due.len(); let on_time = due.len();
@@ -2370,17 +2648,22 @@ impl State {
let bytes_at_most = if required || asked.is_some() { let bytes_at_most = if required || asked.is_some() {
bytes_at_most bytes_at_most
} else { } else {
crate::residency::prefetch_limit(bytes_at_most, crate::residency::pressured(), crate::residency::prefetch_limit(
crate::residency::limited_host_ram(), crate::texture::live_staging_bytes()) bytes_at_most,
crate::residency::pressured(),
crate::residency::critical_commit(),
crate::residency::limited_host_ram(),
crate::texture::live_staging_bytes(),
)
}; };
let began = std::time::Instant::now(); let began = std::time::Instant::now();
BAKE_SERVED.store(0, Ordering::Relaxed); if sync.is_none() {
BAKE_SERVED.store(0, Ordering::Relaxed);
}
let mut served = true; let mut served = true;
for (index, write) in due { for (index, write) in due {
if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span {
|| !crate::residency::admit_texture_pass(required)
{
served = false; served = false;
break; break;
} }
@@ -2524,23 +2807,41 @@ impl State {
); );
} }
} }
// Gate new host texture creation / staging on commit reserve after
// `mapped == 0` reclamation (`texture_slot_gone`) has run, and
// before mirroring a slot to an unuploaded texture.
if !crate::residency::admit_texture_pass(required) {
served = false;
break;
}
// A slot that shows the texture by an earlier view of it (one // A slot that shows the texture by an earlier view of it (one
// from another level) goes on doing so until the upload of what // from another level) goes on doing so until the upload of what
// the new one shows has run. // the new one shows has run.
let sync_bake = sync.is_some();
let shows_other = !baking let shows_other = !baking
&& !sync_bake
&& crate::resource::held_only() && crate::resource::held_only()
&& heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle)); && heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle));
// A slot that shows nothing of it yet, or something else, shows it // A slot that shows nothing of it yet, or something else, shows it
// when the upload has run too. // when the upload has run too.
let late = !shows_other let late = !shows_other
&& !baking && !baking
&& !sync_bake
&& crate::descriptor::host::show_after() && crate::descriptor::host::show_after()
&& heap.handle(index).is_some_and(|handle| !host.texture_slot_made_from(index, handle)); && heap.handle(index).is_some_and(|handle| !host.texture_slot_made_from(index, handle));
let view = heap.handle(index).and_then(|handle| { let (view, bake_key) = if sync_bake {
if shows_other || late { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) } match heap.handle(index).and_then(|handle| host.prepare_bake_slot(index, handle)) {
}); Some((view, key)) => (Some(view), Some(key)),
None => (None, None),
}
} else {
let view = heap.handle(index).and_then(|handle| {
if shows_other || late { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) }
});
(view, None)
};
let at_once = || { let at_once = || {
if late && let Some(handle) = heap.handle(index) { if (late || bake_key.is_some()) && let Some(handle) = heap.handle(index) {
let _ = host.mirror(index, handle, true); let _ = host.mirror(index, handle, true);
} }
}; };
@@ -2581,16 +2882,23 @@ impl State {
let same = !tabled && crate::texture::unchanged(resource, first); let same = !tabled && crate::texture::unchanged(resource, first);
if same { if same {
HEAP_TEXTURES_SAME.fetch_add(1, Ordering::Relaxed); HEAP_TEXTURES_SAME.fetch_add(1, Ordering::Relaxed);
if shows_other && let Some(handle) = heap.handle(index) { if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, heap.handle(index)) {
let _ = host.mirror(index, handle, true); if let Some(copy) = crate::resource::host_copy(resource) {
} sync.keep.push(copy);
// Its bytes are in, or on the way there in a list before.
if late && texture.is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource) {
if let Some(handle) = heap.handle(index) {
host.texture_slot_show_after(list, index, handle);
} }
sync.publish.push((index, handle, key));
} else { } else {
at_once(); if shows_other && let Some(handle) = heap.handle(index) {
let _ = host.mirror(index, handle, true);
}
// Its bytes are in, or on the way there in a list before.
if late && texture.is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource) {
if let Some(handle) = heap.handle(index) {
host.texture_slot_show_after(list, index, handle);
}
} else {
at_once();
}
} }
let again = partly.map(|mapped| (frame + 1, mapped)); let again = partly.map(|mapped| (frame + 1, mapped));
let memory = if again.is_none() && heap_recheck() { crate::texture::title_span(resource, first) } else { None }; let memory = if again.is_none() && heap_recheck() { crate::texture::title_span(resource, first) } else { None };
@@ -2625,6 +2933,7 @@ impl State {
break; break;
} }
let late = late && ahead.is_none(); let late = late && ahead.is_none();
let _ = crate::residency::take_staging_deferred();
if let Some(view) = &view if let Some(view) = &view
&& ahead.is_none() && ahead.is_none()
{ {
@@ -2634,12 +2943,21 @@ impl State {
readable(list, sampled.kind, view); readable(list, sampled.kind, view);
crate::texture::PICKING.set(None); crate::texture::PICKING.set(None);
} }
// A failed allocation leaves this slot due. Publishing it or // A failed or deferred staging allocation leaves this slot due.
// marking it served would lose the only retry for some materials. // Publishing it or marking it served would lose the only retry for
if ahead.is_none() && crate::residency::upload_refused() { // some materials.
if ahead.is_none()
&& (crate::residency::take_staging_deferred() || crate::residency::upload_refused())
{
served = false; served = false;
break; break;
} }
if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, heap.handle(index)) {
if let Some(copy) = crate::resource::host_copy(resource) {
sync.keep.push(copy);
}
sync.publish.push((index, handle, key));
}
if shows_other && let Some(handle) = heap.handle(index) { if shows_other && let Some(handle) = heap.handle(index) {
host.texture_slot_flip(list, index, handle); host.texture_slot_flip(list, index, handle);
} }
@@ -2672,7 +2990,7 @@ impl State {
let text: String = format!("{view:?}").chars().take(300).collect(); let text: String = format!("{view:?}").chars().take(300).collect();
tracing::error!(why, slot = index, "the host device went while textures picked by index were made ready; last: {text}"); tracing::error!(why, slot = index, "the host device went while textures picked by index were made ready; last: {text}");
crate::host::log_removal_context(); crate::host::log_removal_context();
return; return false;
} }
let (bytes, whole) = crate::texture::staged(resource, there.is_none()).unwrap_or((0, true)); let (bytes, whole) = crate::texture::staged(resource, there.is_none()).unwrap_or((0, true));
// Not all of it there: looked at again next frame, and from // Not all of it there: looked at again next frame, and from
@@ -2723,9 +3041,10 @@ impl State {
None => host.texture_slot_done(index, write, again), None => host.texture_slot_done(index, write, again),
} }
} }
if baking && served { if sync.is_none() && baking && served {
BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed); BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed);
} }
served
} }
/// For the frame listing, after a dropped dispatch's line: its group /// For the frame listing, after a dropped dispatch's line: its group
@@ -3440,7 +3759,10 @@ impl State {
made.push((slot, first * 32)); made.push((slot, first * 32));
continue; continue;
} }
let Some(first) = host.dynamic(n) else { let Some(first) = host.dynamic(n).or_else(|| {
crate::host::settle_for_fence();
host.dynamic(n)
}) else {
// No room: the draw must not run with the title's own // No room: the draw must not run with the title's own
// offsets (slots never made for it); `bind` drops it. // offsets (slots never made for it); `bind` drops it.
made.push((slot, u32::MAX)); made.push((slot, u32::MAX));
@@ -3488,11 +3810,12 @@ impl State {
TESTED_DEPTH.set((tested.0, true)); TESTED_DEPTH.set((tested.0, true));
} }
} else if let Some(view) = crate::descriptor::host::listed_view(recording, words) { } else if let Some(view) = crate::descriptor::host::listed_view(recording, words) {
let _ = crate::residency::take_staging_deferred();
TESTED_DEPTH.set((tested.0, false)); TESTED_DEPTH.set((tested.0, false));
readable(list, kind, &view); readable(list, kind, &view);
let depth = TESTED_DEPTH.get().1; let depth = TESTED_DEPTH.get().1;
TESTED_DEPTH.set((tested.0, tested.1 || depth)); TESTED_DEPTH.set((tested.0, tested.1 || depth));
if kind == ResourceType::Srv { if kind == ResourceType::Srv && !crate::residency::take_staging_deferred() {
listed.ready = (list.epoch(), tested.0, depth); listed.ready = (list.epoch(), tested.0, depth);
} }
} }
+23 -2
View File
@@ -4912,7 +4912,7 @@ impl Host {
let mut telling = std::time::Instant::now(); let mut telling = std::time::Instant::now();
for item in items { for item in items {
telling = match item { telling = match item {
Late::Run(flight) => { Late::Run(mut flight) => {
last = flight.number; last = flight.number;
for &i in &flight.order { for &i in &flight.order {
read_backs(flight.lists[i].host()); read_backs(flight.lists[i].host());
@@ -4923,6 +4923,9 @@ impl Host {
if let Some(own) = flight.own { if let Some(own) = flight.own {
own.landed(); own.landed();
} }
for detached in &mut flight.lists {
detached.release_tables();
}
landed.push((flight.lists, flight.order)); landed.push((flight.lists, flight.order));
crate::land::spent(crate::land::stat::READ_BACKS, telling) crate::land::spent(crate::land::stat::READ_BACKS, telling)
} }
@@ -5125,6 +5128,14 @@ impl Host {
let _ = self.submit(runs, &[], false); let _ = self.submit(runs, &[], false);
} }
/// Runs a closed internal upload-only host list synchronously without
/// draining title queues (`queue::before_sync`), so it is deadlock-safe
/// when invoked from `VICTORY_THIN=1` worker threads. Settles in-flight
/// GPU work and waits for the upload list's fence before returning.
pub(crate) fn execute_sync_internal(&self, list: &HostList) {
let _ = self.submit(&[list], &[], false);
}
/// A queue's submission with [`late`]: the host lists `lists`, taken /// A queue's submission with [`late`]: the host lists `lists`, taken
/// from the title's, go to the card in `order` and are not waited for. /// from the title's, go to the card in `order` and are not waited for.
/// They join the line of flights and are settled, with the others in /// They join the line of flights and are settled, with the others in
@@ -5382,7 +5393,7 @@ impl Host {
let mut landed = Vec::new(); let mut landed = Vec::new();
for item in items { for item in items {
match item { match item {
Late::Run(flight) => { Late::Run(mut flight) => {
last = flight.number; last = flight.number;
for &i in &flight.order { for &i in &flight.order {
read_backs(flight.lists[i].host()); read_backs(flight.lists[i].host());
@@ -5390,6 +5401,9 @@ impl Host {
if let Some(card) = flight.card { if let Some(card) = flight.card {
self.card_done(card); self.card_done(card);
} }
for detached in &mut flight.lists {
detached.release_tables();
}
landed.push((flight.lists, flight.order)); landed.push((flight.lists, flight.order));
} }
Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes), Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
@@ -6348,6 +6362,13 @@ impl HostList {
self.epoch.load(Ordering::Relaxed) self.epoch.load(Ordering::Relaxed)
} }
/// Whether any deferred steps or texture state transitions have been
/// recorded into this list since creation or its last [`HostList::reset`].
pub(crate) fn has_recorded_work(&self) -> bool {
!self.deferred().copies.is_empty()
|| !self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
}
/// Moves a title texture's host copy to `wanted` (a host state) in this /// Moves a title texture's host copy to `wanted` (a host state) in this
/// list: the host texture and the state it leaves, if that is a change. /// list: the host texture and the state it leaves, if that is a change.
/// The list's first use of a texture records nothing: its prelude brings /// The list's first use of a texture records nothing: its prelude brings
+4 -6
View File
@@ -295,12 +295,10 @@ pub(crate) fn amd(device: &ID3D12Device) -> bool {
/// Whether a record that does not fit in what is left of its list's budget /// Whether a record that does not fit in what is left of its list's budget
/// takes the rest, so that every record after it runs empty too /// takes the rest, so that every record after it runs empty too
/// (`VICTORY_INDIRECT_REST=0`: it takes nothing, and the next one that fits /// (`VICTORY_INDIRECT_REST=1`; off by default so one oversized record takes
/// runs). A list whose budget one garbage record empties loses all its later /// nothing and later valid draws still run).
/// draws, and which record that is may differ from frame to frame. The frame
/// line says how many records a frame are refused.
fn rest() -> u32 { fn rest() -> u32 {
u32::from(std::env::var("VICTORY_INDIRECT_REST").map_or(true, |v| v != "0")) u32::from(std::env::var("VICTORY_INDIRECT_REST").is_ok_and(|v| v == "1"))
} }
/// The clamp compiled from `source` (ours, or in the benchmark the one it /// The clamp compiled from `source` (ours, or in the benchmark the one it
@@ -2607,7 +2605,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
/// left then, and the records as clamped. /// left then, and the records as clamped.
fn four_records_of_a_group(rest: bool) -> Option<(u32, Vec<u32>)> { fn four_records_of_a_group(rest: bool) -> Option<(u32, Vec<u32>)> {
let mut warp = WarpHarness::new()?; let mut warp = WarpHarness::new()?;
let source = if rest { SOURCE.to_owned() } else { SOURCE.replace("REST ?", "false ?") }; let source = SOURCE.replace("REST ?", if rest { "true ?" } else { "false ?" });
let clamp = make_from(&warp.device, &source).expect("the clamp must compile on WARP"); let clamp = make_from(&warp.device, &source).expect("the clamp must compile on WARP");
const KIND_DRAW: u32 = 0; const KIND_DRAW: u32 = 0;
const STRIDE: u32 = 16; const STRIDE: u32 = 16;
+6
View File
@@ -203,6 +203,12 @@ impl Detached {
pub(crate) fn host(&self) -> &crate::host::HostList { pub(crate) fn host(&self) -> &crate::host::HostList {
&self.host &self.host
} }
/// Releases this list's dynamic descriptor slots once its GPU submission
/// has completed, without waiting for the full `bury_lag` allocator delay.
pub(crate) fn release_tables(&mut self) {
self._state.tables_done();
}
} }
/// A host list that has run and waits to be used again, and the bytes of /// A host list that has run and waits to be used again, and the bytes of
+1
View File
@@ -524,6 +524,7 @@ impl HostPipeline {
slot == victory_shader::emit::SLOT_FAULTS slot == victory_shader::emit::SLOT_FAULTS
} else { } else {
slot == victory_shader::emit::SLOT_STRIDES slot == victory_shader::emit::SLOT_STRIDES
|| slot == victory_shader::emit::SLOT_TABLE_STRIDES
|| slot == victory_shader::emit::SLOT_MEMORY || slot == victory_shader::emit::SLOT_MEMORY
}; };
if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() { if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() {
+15 -1
View File
@@ -52,7 +52,14 @@ pub(crate) fn room(memory: Option<[u64; 4]>) {
pool.reclaim(tick, limit, true); pool.reclaim(tick, limit, true);
} }
if let Ok(mut pool) = STAGING.try_lock() { if let Ok(mut pool) = STAGING.try_lock() {
pool.reclaim(tick, if pressure { 0 } else { limit }, true); let staging_limit = if crate::residency::critical_commit() {
0
} else if pressure {
1
} else {
limit
};
pool.reclaim(tick, staging_limit, true);
} }
} }
@@ -379,6 +386,13 @@ pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPi
// Copies from a buffer begin at multiples of 512. // Copies from a buffer begin at multiples of 512.
let bytes = bytes.next_multiple_of(512); let bytes = bytes.next_multiple_of(512);
let (piece, memory, again) = lock(&STAGING).take(bytes, 512, now(), || { let (piece, memory, again) = lock(&STAGING).take(bytes, 512, now(), || {
// Only gate speculative bindless prefetch on staging-pool growth
// headroom; table-bound textures and decoration bakes are sampled
// immediately and would otherwise read uninitialized/reused VRAM.
let speculative = crate::texture::PICKING.get().is_some() && !crate::texture::BAKING.get();
if speculative && !crate::residency::allow_staging_growth(false) {
return None;
}
let (buffer, data) = host.upload_buffer(BLOCK)?; let (buffer, data) = host.upload_buffer(BLOCK)?;
crate::host::name(&buffer, || "staging of textures (a block)".into()); crate::host::name(&buffer, || "staging of textures (a block)".into());
Some(Upload(buffer, data)) Some(Upload(buffer, data))
+85 -33
View File
@@ -3,6 +3,7 @@ use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
const MIB: u64 = 1 << 20;
const GIB: u64 = 1 << 30; const GIB: u64 = 1 << 30;
static PRESSURED: AtomicBool = AtomicBool::new(false); static PRESSURED: AtomicBool = AtomicBool::new(false);
static HEADROOM: AtomicU64 = AtomicU64::new(u64::MAX); static HEADROOM: AtomicU64 = AtomicU64::new(u64::MAX);
@@ -25,30 +26,68 @@ pub(crate) fn allocation_error(error: &windows::core::Error) {
} }
} }
thread_local! {
static STAGING_DEFERRED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub(crate) fn note_staging_deferred() {
STAGING_DEFERRED.set(true);
}
pub(crate) fn take_staging_deferred() -> bool {
STAGING_DEFERRED.replace(false)
}
pub(crate) fn upload_refused() -> bool { pub(crate) fn upload_refused() -> bool {
crate::host::coarse_ms() < RETRY_UPLOAD_AT.load(Ordering::Relaxed) crate::host::coarse_ms() < RETRY_UPLOAD_AT.load(Ordering::Relaxed)
} }
fn has_upload_reserve(commit: u64, bake: bool) -> bool { fn sample_commit(now: u64) -> u64 {
commit >= if bake { 2 * GIB } else { 4 * GIB } let next = NEXT_COMMIT_SAMPLE.load(Ordering::Relaxed);
if now >= next
&& NEXT_COMMIT_SAMPLE
.compare_exchange(next, now.saturating_add(32), Ordering::Relaxed, Ordering::Relaxed)
.is_ok()
&& let Some(status) = memory_status()
{
AVAILABLE_COMMIT.store(status.ullAvailPageFile, Ordering::Relaxed);
}
AVAILABLE_COMMIT.load(Ordering::Relaxed)
} }
/// Leave commit for game allocations and submissions already in flight. Direct fn has_upload_reserve(commit: u64, bake: bool) -> bool {
/// texture consumers bypass this gate. Bake prefetch gets priority over lookahead. // Keep a protective floor against Rust/game OOM aborts without starving
// bindless world textures or one-shot ped decoration bakes when steady-state
// commit headroom sits in the 1-4 GiB range on 32 GiB hosts.
commit >= if bake { 256 * MIB } else { 512 * MIB }
}
fn has_growth_reserve(commit: u64, bake: bool) -> bool {
// Growing a fresh 64 MiB upload block for speculative bindless prefetch
// requires more headroom than reusing slices already committed inside the
// staging pool.
commit >= if bake { 256 * MIB } else { 1024 * MIB }
}
/// Leave commit for game allocations and submissions already in flight while
/// still letting bindless textures and one-shot material bakes upload.
pub(crate) fn admit_texture_pass(bake: bool) -> bool { pub(crate) fn admit_texture_pass(bake: bool) -> bool {
let now = crate::host::coarse_ms(); let now = crate::host::coarse_ms();
if now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) { if now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) {
return false; return false;
} }
let next = NEXT_COMMIT_SAMPLE.load(Ordering::Relaxed); has_upload_reserve(sample_commit(now), bake)
if now >= next && NEXT_COMMIT_SAMPLE.compare_exchange( }
next, now.saturating_add(32), Ordering::Relaxed, Ordering::Relaxed,
).is_ok() { /// Whether the staging allocator may commit a brand-new OS upload buffer
if let Some(status) = memory_status() { /// (reusing existing free ranges in already-committed pool blocks stays open
AVAILABLE_COMMIT.store(status.ullAvailPageFile, Ordering::Relaxed); /// whenever `admit_texture_pass` is true).
} pub(crate) fn allow_staging_growth(bake: bool) -> bool {
let now = crate::host::coarse_ms();
if now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) {
return false;
} }
has_upload_reserve(AVAILABLE_COMMIT.load(Ordering::Relaxed), bake) has_growth_reserve(sample_commit(now), bake)
} }
pub(crate) fn limited_host_ram() -> bool { pub(crate) fn limited_host_ram() -> bool {
@@ -58,9 +97,9 @@ pub(crate) fn limited_host_ram() -> bool {
fn next_pressure(was: bool, physical: u64, commit: u64) -> bool { fn next_pressure(was: bool, physical: u64, commit: u64) -> bool {
if was { if was {
physical < 6 * GIB || commit < 8 * GIB physical < 5 * GIB || commit < 6 * GIB
} else { } else {
physical <= 4 * GIB || commit <= 6 * GIB physical <= 3 * GIB || commit <= 4 * GIB
} }
} }
@@ -100,13 +139,20 @@ pub(crate) fn pressured() -> bool {
PRESSURED.load(Ordering::Relaxed) PRESSURED.load(Ordering::Relaxed)
} }
/// True when OS commit headroom is critically low (< 1.5 GiB) or an allocation
/// just failed with `E_OUTOFMEMORY`, requiring emergency throttling.
pub(crate) fn critical_commit() -> bool {
let now = crate::host::coarse_ms();
now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) || sample_commit(now) < 1536 * MIB
}
/// A soft per-frame admission limit. A single texture can cross it. The /// A soft per-frame admission limit. A single texture can cross it. The
/// queue retains unserved slots so they can be retried on later frames. /// queue retains unserved slots so they can be retried on later frames.
pub(crate) fn prefetch_limit(bytes: u64, pressure: bool, limited: bool, staging: u64) -> u64 { pub(crate) fn prefetch_limit(bytes: u64, pressure: bool, critical: bool, limited: bool, staging: u64) -> u64 {
if pressure { if critical {
bytes.min(16 << 20) bytes.min(16 << 20)
} else if limited && staging >= GIB { } else if pressure || (limited && staging >= GIB) {
bytes.min(32 << 20) bytes.min(64 << 20)
} else { } else {
bytes bytes
} }
@@ -118,32 +164,38 @@ mod tests {
#[test] #[test]
fn bake_and_lookahead_leave_room_for_live_game_allocations() { fn bake_and_lookahead_leave_room_for_live_game_allocations() {
for (commit, bake, lookahead) in [ for (commit, bake, lookahead, growth) in [
(277 << 20, false, false), (2 * GIB, true, false), (4 * GIB, true, true), (128 * MIB, false, false, false),
(256 * MIB, true, false, false),
(512 * MIB, true, true, false),
(768 * MIB, true, true, false),
(1024 * MIB, true, true, true),
] { ] {
assert_eq!(has_upload_reserve(commit, true), bake); assert_eq!(has_upload_reserve(commit, true), bake);
assert_eq!(has_upload_reserve(commit, false), lookahead); assert_eq!(has_upload_reserve(commit, false), lookahead);
assert_eq!(has_growth_reserve(commit, false), growth);
} }
} }
#[test] #[test]
fn either_constraint_enters_pressure_and_both_must_recover() { fn either_constraint_enters_pressure_and_both_must_recover() {
assert!(next_pressure(false, 12 * GIB, 6 * GIB)); assert!(next_pressure(false, 12 * GIB, 4 * GIB));
assert!(next_pressure(false, 4 * GIB, 16 * GIB)); assert!(next_pressure(false, 3 * GIB, 16 * GIB));
assert!(next_pressure(true, 5 * GIB, 9 * GIB)); assert!(next_pressure(true, 4 * GIB, 7 * GIB));
assert!(next_pressure(true, 7 * GIB, 7 * GIB)); assert!(next_pressure(true, 6 * GIB, 5 * GIB));
assert!(!next_pressure(true, 6 * GIB, 8 * GIB)); assert!(!next_pressure(true, 5 * GIB, 6 * GIB));
assert!(!next_pressure(false, 5 * GIB, 7 * GIB)); assert!(!next_pressure(false, 4 * GIB, 5 * GIB));
} }
#[test] #[test]
fn prefetch_respects_existing_budgets_and_resumes_after_recovery() { fn prefetch_respects_existing_budgets_and_resumes_after_recovery() {
assert_eq!(prefetch_limit(512 << 20, false, true, GIB), 32 << 20); assert_eq!(prefetch_limit(512 << 20, false, false, true, GIB), 64 << 20);
assert_eq!(prefetch_limit(512 << 20, false, true, GIB - 1), 512 << 20); assert_eq!(prefetch_limit(512 << 20, false, false, true, GIB - 1), 512 << 20);
assert_eq!(prefetch_limit(512 << 20, false, false, 2 * GIB), 512 << 20); assert_eq!(prefetch_limit(512 << 20, false, false, false, 2 * GIB), 512 << 20);
assert_eq!(prefetch_limit(0, true, false, 0), 0); assert_eq!(prefetch_limit(0, true, true, false, 0), 0);
assert_eq!(prefetch_limit(8 << 20, true, false, 0), 8 << 20); assert_eq!(prefetch_limit(8 << 20, true, true, false, 0), 8 << 20);
assert_eq!(prefetch_limit(512 << 20, true, false, 0), 16 << 20); assert_eq!(prefetch_limit(512 << 20, true, false, false, 0), 64 << 20);
assert_eq!(prefetch_limit(192 << 20, false, false, 0), 192 << 20); assert_eq!(prefetch_limit(512 << 20, true, true, false, 0), 16 << 20);
assert_eq!(prefetch_limit(192 << 20, false, false, false, 0), 192 << 20);
} }
} }
+27 -7
View File
@@ -91,6 +91,11 @@ pub(crate) struct Staging {
/// recorded again about a second later if the card has room by then /// recorded again about a second later if the card has room by then
/// ([`upload`]). /// ([`upload`]).
waiting: std::sync::atomic::AtomicU64, waiting: std::sync::atomic::AtomicU64,
/// Recorded for a one-shot decoration bake (`BAKING`): submission-time
/// refresh must wait for title memory to stop remapping
/// (`title_memory_reading`) instead of taking `no_wait()` /
/// `refresh_unlocked()` or the 30-frame partial-read throttle.
exact: std::sync::atomic::AtomicBool,
} }
/// What a texture's staging buffer holds: the hash of the memory detiled /// What a texture's staging buffer holds: the hash of the memory detiled
@@ -756,6 +761,10 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
return; return;
}; };
use std::sync::atomic::Ordering::Relaxed; use std::sync::atomic::Ordering::Relaxed;
let baking = BAKING.get();
if baking {
staging.exact.store(true, Relaxed);
}
let picking = PICKING.get(); let picking = PICKING.get();
if picking.is_none() { if picking.is_none() {
// A draw samples it through a table: kept and checked from here on. // A draw samples it through a table: kept and checked from here on.
@@ -810,8 +819,10 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
// The host texture has the staging buffer's contents: only the check // The host texture has the staging buffer's contents: only the check
// at submission is left, and what it finds changed the next list that // at submission is left, and what it finds changed the next list that
// samples the texture uploads (a frame late where every list of the // samples the texture uploads (a frame late where every list of the
// frame was recorded before that check). // frame was recorded before that check). During a one-shot bake we
if staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) { // always record the copy so any change found at submission lands in
// VRAM before the bake draw executes.
if !baking && staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) {
#[cfg(feature = "diagnostics")] #[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexSkipped, 1); crate::copystat::add(crate::copystat::C::TexSkipped, 1);
list.defer_texture(staging); list.defer_texture(staging);
@@ -1254,12 +1265,13 @@ impl Staging {
let start = self.memory as usize; let start = self.memory as usize;
let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner()));
let last = &mut *last; let last = &mut *last;
let exact = self.exact.swap(false, std::sync::atomic::Ordering::Relaxed);
let alone = self.once.load(std::sync::atomic::Ordering::Relaxed); let alone = self.once.load(std::sync::atomic::Ordering::Relaxed);
if alone && last.hash.is_some() { if alone && !exact && last.hash.is_some() {
return 0; return 0;
} }
if !alone && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) { if !alone && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) {
if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) { if !exact && last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) {
return 0; return 0;
} }
last.asked = now; last.asked = now;
@@ -1303,7 +1315,7 @@ impl Staging {
last.hot_until = frame + HOT_FRAMES; last.hot_until = frame + HOT_FRAMES;
} }
let hot = hot_textures() && frame < last.hot_until; let hot = hot_textures() && frame < last.hot_until;
if unwritten && !turn && !hot { if !exact && unwritten && !turn && !hot {
return 0; return 0;
} }
blind = unwritten; blind = unwritten;
@@ -1322,7 +1334,7 @@ impl Staging {
// stays mapped (see `crate::watch::title_memory_reading`; without // stays mapped (see `crate::watch::title_memory_reading`; without
// it a page went between the asking and the read in runs 71 and // it a page went between the asking and the read in runs 71 and
// 74). // 74).
let _mapped = if no_wait() { let _mapped = if no_wait() && !exact {
// Not waited for: while the runtime remaps title memory the // Not waited for: while the runtime remaps title memory the
// texture is read through the kernel instead, whole or not at // texture is read through the kernel instead, whole or not at
// all (`no_wait`). // all (`no_wait`).
@@ -1342,7 +1354,7 @@ impl Staging {
// unmapped pages is slow, and nothing tells us when pages // unmapped pages is slow, and nothing tells us when pages
// arrive): a mip that streams in shows up to 30 frames late. // arrive): a mip that streams in shows up to 30 frames late.
let frame = crate::frame::current(); let frame = crate::frame::current();
if last.partial.is_some_and(|at| frame < at + 30) { if !exact && last.partial.is_some_and(|at| frame < at + 30) {
return 0; return 0;
} }
last.partial = Some(frame); last.partial = Some(frame);
@@ -1878,6 +1890,13 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O
let (piece, buffer, base, data) = match crate::pool::staging(host, total) { let (piece, buffer, base, data) = match crate::pool::staging(host, total) {
Some((piece, buffer, base, data)) => (Some(piece), buffer, base, data), Some((piece, buffer, base, data)) => (Some(piece), buffer, base, data),
None => { None => {
let speculative = PICKING.get().is_some() && !BAKING.get();
if crate::residency::upload_refused()
|| (speculative && !crate::residency::allow_staging_growth(false))
{
crate::residency::note_staging_deferred();
return None;
}
let (buffer, data) = host.upload_buffer(total)?; let (buffer, data) = host.upload_buffer(total)?;
crate::host::name(&buffer, || { crate::host::name(&buffer, || {
format!( format!(
@@ -1919,6 +1938,7 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O
detiled: std::sync::atomic::AtomicU32::new(0), detiled: std::sync::atomic::AtomicU32::new(0),
judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2], judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2],
waiting: std::sync::atomic::AtomicU64::new(0), waiting: std::sync::atomic::AtomicU64::new(0),
exact: std::sync::atomic::AtomicBool::new(BAKING.get()),
}); });
map.insert(resource as usize, s.clone()); map.insert(resource as usize, s.clone());
Some(s) Some(s)
+62 -8
View File
@@ -13,7 +13,7 @@
//! it as any texture. //! it as any texture.
use std::collections::VecDeque; use std::collections::VecDeque;
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering::Relaxed}; use std::sync::atomic::{AtomicU8, AtomicU64, AtomicUsize, Ordering::Relaxed};
use std::sync::{Arc, Condvar, Mutex, OnceLock}; use std::sync::{Arc, Condvar, Mutex, OnceLock};
use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Direct3D12::*;
@@ -80,6 +80,7 @@ pub(crate) enum Taken {
static QUEUE: (Mutex<VecDeque<Arc<Job>>>, Condvar) = (Mutex::new(VecDeque::new()), Condvar::new()); static QUEUE: (Mutex<VecDeque<Arc<Job>>>, Condvar) = (Mutex::new(VecDeque::new()), Condvar::new());
/// Those on their way, by host copy ([`HostTexture::serial`]). /// Those on their way, by host copy ([`HostTexture::serial`]).
static ON_THEIR_WAY: Mutex<Vec<(u64, Arc<Job>)>> = Mutex::new(Vec::new()); static ON_THEIR_WAY: Mutex<Vec<(u64, Arc<Job>)>> = Mutex::new(Vec::new());
static IN_FLIGHT: AtomicUsize = AtomicUsize::new(0);
static LANDED: Condvar = Condvar::new(); static LANDED: Condvar = Condvar::new();
static BYTES: AtomicU64 = AtomicU64::new(0); static BYTES: AtomicU64 = AtomicU64::new(0);
/// Since the start: uploads, bytes, microseconds from the asking until the /// Since the start: uploads, bytes, microseconds from the asking until the
@@ -104,7 +105,7 @@ fn claim(resource: This, first: u32, there: u64) -> Option<Taken> {
return way.iter().find(|(serial, _)| *serial == copy.serial).map(|(_, job)| Taken::Known(job.clone())); return way.iter().find(|(serial, _)| *serial == copy.serial).map(|(_, job)| Taken::Known(job.clone()));
} }
let most = if crate::residency::limited_host_ram() { 32 << 20 } else { MOST }; let most = if crate::residency::limited_host_ram() { 32 << 20 } else { MOST };
if crate::residency::pressured() if !crate::residency::allow_staging_growth(false)
|| BYTES.load(Relaxed) >= most || BYTES.load(Relaxed) >= most
|| copy.flags() & 0x7 != 0 || copy.flags() & 0x7 != 0
|| copy.state.load(Relaxed) != 0 || copy.state.load(Relaxed) != 0
@@ -134,7 +135,11 @@ fn claim(resource: This, first: u32, there: u64) -> Option<Taken> {
} }
let job = Arc::new(Job { staging, copy, asked: std::time::Instant::now(), then: Mutex::new(Some(Vec::new())) }); let job = Arc::new(Job { staging, copy, asked: std::time::Instant::now(), then: Mutex::new(Some(Vec::new())) });
BYTES.fetch_add(job.staging.read as u64, Relaxed); BYTES.fetch_add(job.staging.read as u64, Relaxed);
ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()).push((job.copy.serial, job.clone())); {
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
way.push((job.copy.serial, job.clone()));
IN_FLIGHT.store(way.len(), std::sync::atomic::Ordering::Release);
}
Some(Taken::New(job)) Some(Taken::New(job))
} }
@@ -144,6 +149,25 @@ pub(crate) fn send(job: &Arc<Job>) {
QUEUE.1.notify_one(); QUEUE.1.notify_one();
} }
/// Waits until every upload currently on its way here has finished copying
/// and run its completion callbacks (queuing slot flips into `FLIPS`).
/// Returns how many jobs were waited for.
pub(crate) fn drain() -> usize {
if IN_FLIGHT.load(std::sync::atomic::Ordering::Acquire) == 0 {
return 0;
}
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
let waiting = way.len();
let started = std::time::Instant::now();
while !way.is_empty() && started.elapsed().as_millis() < 2000 {
way = LANDED
.wait_timeout(way, std::time::Duration::from_millis(50))
.unwrap_or_else(|e| e.into_inner())
.0;
}
waiting
}
/// A list is about to record an upload into `copy`: one on its way here runs /// A list is about to record an upload into `copy`: one on its way here runs
/// first, and no other is taken after it. /// first, and no other is taken after it.
pub(crate) fn listed(copy: &HostTexture) { pub(crate) fn listed(copy: &HostTexture) {
@@ -293,11 +317,6 @@ fn finish(jobs: Vec<Arc<Job>>) {
job.copy.ahead.store(DONE, Relaxed); job.copy.ahead.store(DONE, Relaxed);
BYTES.fetch_sub(job.staging.read as u64, Relaxed); BYTES.fetch_sub(job.staging.read as u64, Relaxed);
} }
{
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
way.retain(|(serial, _)| !jobs.iter().any(|job| job.copy.serial == *serial));
LANDED.notify_all();
}
for job in &jobs { for job in &jobs {
let us = job.asked.elapsed().as_micros() as u64; let us = job.asked.elapsed().as_micros() as u64;
let n = STATS[0].fetch_add(1, Relaxed) + 1; let n = STATS[0].fetch_add(1, Relaxed) + 1;
@@ -319,6 +338,14 @@ fn finish(jobs: Vec<Arc<Job>>) {
f(); f();
} }
} }
// Remove from `ON_THEIR_WAY` only after `job.then` callbacks have queued
// their `FLIPS` entries so `drain()` observes every flip ready to apply.
{
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
way.retain(|(serial, _)| !jobs.iter().any(|job| job.copy.serial == *serial));
IN_FLIGHT.store(way.len(), std::sync::atomic::Ordering::Release);
LANDED.notify_all();
}
crate::descriptor::host::flip_now(); crate::descriptor::host::flip_now();
} }
@@ -416,4 +443,31 @@ mod tests {
back.Unmap(0, None); back.Unmap(0, None);
} }
} }
#[test]
fn drain_waits_until_then_callbacks_have_run() {
use std::sync::atomic::AtomicBool;
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc};
let Some(_host) = crate::host::host() else { return };
let desc = [3u32, 0, 0, 0, 128, 0, 128, 0x8_0001, 98, 1, 0, 0x105, 0, 0];
let whole = crate::resource::placed_bytes(&desc).unwrap() as usize;
// SAFETY: memory of our own that stays for the test.
let at = unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }.cast::<u8>();
// SAFETY: as above.
unsafe { std::ptr::write_bytes(at, 0x5a, whole) };
let texture = crate::resource::texture_at(at as u64, &desc).unwrap();
crate::resource::want_level(texture, 0);
let copy = crate::resource::host_copy(texture).unwrap();
if !crate::pool::fresh(&copy.texture) {
return;
}
let Some(Taken::New(job)) = claim(texture, 0, u64::MAX) else { panic!("not taken") };
let ran = Arc::new(AtomicBool::new(false));
let flag = ran.clone();
job.then(move || flag.store(true, std::sync::atomic::Ordering::Release));
send(&job);
assert!(drain() >= 1);
assert!(ran.load(std::sync::atomic::Ordering::Acquire), "job.then callback must run before drain() returns");
assert_eq!(drain(), 0);
}
} }
+35 -4
View File
@@ -1228,12 +1228,43 @@ fn translated_compute_matches_pc() {
let mut root_views: Vec<(u8, bool)> = cs_c.root_cbvs.iter().map(|&s| (s, false)).collect(); let mut root_views: Vec<(u8, bool)> = cs_c.root_cbvs.iter().map(|&s| (s, false)).collect();
root_views.extend(cs_c.root_srvs.iter().map(|&s| (s, true))); root_views.extend(cs_c.root_srvs.iter().map(|&s| (s, true)));
root_views.sort_unstable(); root_views.sort_unstable();
let view_strides: Vec<u32> = views
.iter()
.map(|v| match *v {
View::RawUav(_) => 1,
View::HalfUav(_) => 8,
View::Buffer { stride, .. } => match stride {
Stride::Raw => 1,
Stride::Typed => 16,
Stride::Structured(s) => s,
Stride::Format(f, bytes) => {
let kind = match f.0 as u32 {
3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62 => {
super::VIEW_INTEGER
}
4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64 => {
super::VIEW_INTEGER | super::VIEW_SIGNED
}
_ => 0,
};
bytes | kind
}
},
_ => 0,
})
.collect();
for (n, (slot, srv)) in root_views.into_iter().enumerate() { for (n, (slot, srv)) in root_views.into_iter().enumerate() {
assert_eq!(slot, 4 + u8::from(srv), "{name}: root view"); let data = if srv
let data = if srv { && (slot == super::SLOT_STRIDES || slot == super::SLOT_TABLE_STRIDES)
root_srv.clone() {
view_strides.clone()
} else { } else {
root_cbv.clone() assert_eq!(slot, 4 + u8::from(srv), "{name}: root view");
if srv {
root_srv.clone()
} else {
root_cbv.clone()
}
}; };
roots.push((1 + n as u32, Root::View { srv, data })); roots.push((1 + n as u32, Root::View { srv, data }));
} }
+46
View File
@@ -1004,6 +1004,12 @@ pub enum View<'a> {
UintTextureUav(u32, u32), UintTextureUav(u32, u32),
/// A typed RGBA16F buffer UAV of this many elements, zeroed. /// A typed RGBA16F buffer UAV of this many elements, zeroed.
HalfUav(u32), HalfUav(u32),
/// A typed buffer UAV pre-filled with `data` (`format`, bytes per element).
TypedUav {
data: &'a [u32],
format: DXGI_FORMAT,
elem_bytes: u32,
},
/// A constant buffer of these dwords. /// A constant buffer of these dwords.
Cbv(&'a [u32]), Cbv(&'a [u32]),
/// A buffer SRV over these dwords. /// A buffer SRV over these dwords.
@@ -1279,6 +1285,46 @@ impl Host {
)?; )?;
uavs.push((b, None, n, rb)); uavs.push((b, None, n, rb));
} }
View::TypedUav {
data,
format,
elem_bytes,
} => {
let n = data.len() as u32;
let bytes = u64::from(n) * 4;
let elements = (bytes / u64::from(elem_bytes)) as u32;
let b = make(
D3D12_HEAP_TYPE_DEFAULT,
&buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS),
D3D12_RESOURCE_STATE_COPY_DEST,
)?;
let up = upload(data)?;
list.CopyBufferRegion(&b, 0, &up, 0, bytes);
list.ResourceBarrier(&[transition(
&b,
D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
)]);
keep.push(up);
let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
Format: format,
ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 {
Buffer: D3D12_BUFFER_UAV {
NumElements: elements,
Flags: D3D12_BUFFER_UAV_FLAG_NONE,
..Default::default()
},
},
};
dev.CreateUnorderedAccessView(&b, None, Some(&desc), at);
let rb = make(
D3D12_HEAP_TYPE_READBACK,
&buffer(bytes, D3D12_RESOURCE_FLAG_NONE),
D3D12_RESOURCE_STATE_COPY_DEST,
)?;
uavs.push((b, None, n, rb));
}
View::TextureUav(w, h) => { View::TextureUav(w, h) => {
let t = make( let t = make(
D3D12_HEAP_TYPE_DEFAULT, D3D12_HEAP_TYPE_DEFAULT,
+19 -15
View File
@@ -7501,7 +7501,7 @@ impl<'a> Lower<'a> {
/// `ResourceHeap`): read from the host's table by heap slot in the /// `ResourceHeap`): read from the host's table by heap slot in the
/// current block. /// current block.
fn slot_stride(&mut self, src: &Source) -> Result<Option<V>, Why> { fn slot_stride(&mut self, src: &Source) -> Result<Option<V>, Why> {
let word = self.slot_word(src)?; let word = self.slot_word(src, false)?;
Ok(word.map(|word| { Ok(word.map(|word| {
let bits = self.s.m.i32(super::shader::VIEW_STRIDE_BITS); let bits = self.s.m.i32(super::shader::VIEW_STRIDE_BITS);
self.s.m.bin(self.cur, Bin::And, word, bits) self.s.m.bin(self.cur, Bin::And, word, bits)
@@ -7509,10 +7509,9 @@ impl<'a> Lower<'a> {
} }
/// Whether the typed buffer view `src` names is one of an integer format, /// Whether the typed buffer view `src` names is one of an integer format,
/// and whether a signed one, as [`Self::slot_stride`] (`None`: a view the /// and whether a signed one (`ResourceHeap` or `Table`).
/// program does not pick from the heap).
fn integer_view(&mut self, src: &Source) -> Result<Option<(V, V)>, Why> { fn integer_view(&mut self, src: &Source) -> Result<Option<(V, V)>, Why> {
let Some(word) = self.slot_word(src)? else { let Some(word) = self.slot_word(src, true)? else {
return Ok(None); return Ok(None);
}; };
let c = self.cur; let c = self.cur;
@@ -7526,19 +7525,22 @@ impl<'a> Lower<'a> {
} }
/// The host's word for the buffer view `src` names: its stride and /// The host's word for the buffer view `src` names: its stride and
/// format kind ([`super::shader::SLOT_STRIDES`]). /// format kind ([`super::shader::SLOT_STRIDES`] for `ResourceHeap`,
fn slot_word(&mut self, src: &Source) -> Result<Option<V>, Why> { /// [`super::shader::SLOT_TABLE_STRIDES`] for `Table` when `allow_table`).
fn slot_word(&mut self, src: &Source, allow_table: bool) -> Result<Option<V>, Why> {
let Source::Loaded { load, first } = src else { let Source::Loaded { load, first } = src else {
return Ok(None); return Ok(None);
}; };
let heap = self let srv_slot = match self
.scalar .scalar
.get(load) .get(load)
.and_then(|a| self.x.native.layout.get(a.param)) .and_then(|a| self.x.native.layout.get(a.param))
.is_some_and(|p| p.root == RootType::ResourceHeap); .map(|p| p.root)
if !heap { {
return Ok(None); Some(RootType::ResourceHeap) => super::shader::SLOT_STRIDES,
} Some(RootType::Table) if allow_table => super::shader::SLOT_TABLE_STRIDES,
_ => return Ok(None),
};
let key = (self.cur, *load, *first); let key = (self.cur, *load, *first);
if let Some(&v) = self.strides.get(&key) { if let Some(&v) = self.strides.get(&key) {
return Ok(Some(v)); return Ok(Some(v));
@@ -7553,7 +7555,7 @@ impl<'a> Lower<'a> {
self.s.m.tag(slot, Tag::Clamp); self.s.m.tag(slot, Tag::Clamp);
let two = self.s.m.i32(2); let two = self.s.m.i32(2);
let byte = self.s.m.bin(c, Bin::Shl, slot, two); let byte = self.s.m.bin(c, Bin::Shl, slot, two);
let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES); let h = self.s.root_srv_handle(srv_slot);
let iu = self.s.m.undef(self.s.t.i32); let iu = self.s.m.undef(self.s.t.i32);
let mask = self.s.m.i8(1); let mask = self.s.m.i8(1);
let align = self.s.m.i32(4); let align = self.s.m.i32(4);
@@ -11901,9 +11903,11 @@ impl<'a> Lower<'a> {
// store; through a view of an integer format it is a 16-bit // store; through a view of an integer format it is a 16-bit
// integer, zero- or sign-extended (VIctory 4243a96a: the face // integer, zero- or sign-extended (VIctory 4243a96a: the face
// network keeps its halves in UINT views; its output was // network keeps its halves in UINT views; its output was
// noise). shortcut: that is known of the views a program // noise). Both `ResourceHeap` (`SLOT_STRIDES`) and `Table`
// picks from the heap, not of those in its tables; and the // (`SLOT_TABLE_STRIDES`, dynamic table snapshots included)
// handle stays a float one, whose bits the drivers pass. // populate the view-kind bits, while the handle stays a float
// one (`0x409`), whose raw bits RTX and WARP pass bit-exact
// without extra CFG blocks or touching non-d16 shaders.
let integer = if typed { self.integer_view(src)? } else { None }; let integer = if typed { self.integer_view(src)? } else { None };
let mut wide = Vec::new(); let mut wide = Vec::new();
for k in 0..count { for k in 0..count {
+55 -12
View File
@@ -122,7 +122,7 @@ pub use lower::{host_settings, set_host_max_wave, set_host_rdna};
pub use rect::rect_list_gs; pub use rect::rect_list_gs;
pub use shader::{ pub use shader::{
MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES,
SLOT_STRIDES_COUNT, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS, SLOT_STRIDES_COUNT, SLOT_TABLE_STRIDES, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
raw_views, set_raw_views, set_view_heap_limit, view_heap_limit, raw_views, set_raw_views, set_view_heap_limit, view_heap_limit,
}; };
@@ -485,17 +485,45 @@ pub fn emit(
}; };
// The program in two other forms: without its early-outs, and // The program in two other forms: without its early-outs, and
// without any branch that only skips code no lane is left for. // without any branch that only skips code no lane is left for.
let form = |p: Option<ir::Program>| { let form = |label: &str, p: Option<ir::Program>| {
p.and_then(|p| { let Some(p) = p else {
let st = structure::structure(&p).ok()?; if why {
let io = io::raise(&p, native).ok()?; eprintln!("WAVE64-FORM {label}: ir returned None");
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).ok()?; }
Some((p, st, io, res)) return None;
}) };
let st = match structure::structure(&p) {
Ok(st) => st,
Err(e) => {
if why {
eprintln!("WAVE64-FORM {label}: structure failed: {e}");
}
return None;
}
};
let io = match io::raise(&p, native) {
Ok(io) => io,
Err(e) => {
if why {
eprintln!("WAVE64-FORM {label}: io::raise failed: {e}");
}
return None;
}
};
let res = match resource::track(&p, &native.layout, native.stage, Some(&st)) {
Ok(res) => res,
Err(e) => {
if why {
eprintln!("WAVE64-FORM {label}: resource::track failed: {e}");
}
return None;
}
};
Some((p, st, io, res))
}; };
let forms = [ let forms = [
("without early-outs", form(ir::without_early_outs(p))), ("without early-outs", form("without early-outs", ir::without_early_outs(p))),
("without skips", form(ir::without_skips(p, false))), ("without skips", form("without skips", ir::without_skips(p, false))),
]; ];
for (name, f) in &forms { for (name, f) in &forms {
if let Some((p, st, io, res)) = f { if let Some((p, st, io, res)) = f {
@@ -539,7 +567,7 @@ pub fn emit(
// lane runs, where the two host waves can exchange. // lane runs, where the two host waves can exchange.
// (`VICTORY_WAVE_DEEP_SKIPS=0` and `VICTORY_WAVE_WIDE=0` turn the two off.) // (`VICTORY_WAVE_DEEP_SKIPS=0` and `VICTORY_WAVE_WIDE=0` turn the two off.)
let deep_on = std::env::var_os("VICTORY_WAVE_DEEP_SKIPS").is_none_or(|v| v != "0"); let deep_on = std::env::var_os("VICTORY_WAVE_DEEP_SKIPS").is_none_or(|v| v != "0");
let deep = if deep_on { form(ir::without_skips(p, true)) } else { None }; let deep = if deep_on { form("without skips, scalars followed", ir::without_skips(p, true)) } else { None };
if let Some((p, st, io, res)) = &deep { if let Some((p, st, io, res)) = &deep {
let again = emit_program(c, native, p, st, io, res); let again = emit_program(c, native, p, st, io, res);
report("without skips, scalars followed", &again); report("without skips, scalars followed", &again);
@@ -700,7 +728,22 @@ fn widen(
|| matches!(&r, Ok((_, Some(64)))) && !needs.is_empty(); || matches!(&r, Ok((_, Some(64)))) && !needs.is_empty();
if !stuck { if !stuck {
if why { if why {
eprintln!("WAVE64-WIDE {} branches taken wave-wide", wide.len()); let order = ir::reverse_postorder(&p.blocks);
let mut rpo = vec![0usize; p.blocks.len()];
for (i, &b) in order.iter().enumerate() {
rpo[b] = i;
}
let mut sorted: Vec<usize> = wide.iter().copied().collect();
sorted.sort_unstable();
let desc: Vec<String> = sorted
.iter()
.map(|&b| {
let back = matches!(p.blocks[b].exit, ir::Exit::Branch { taken, not_taken } if rpo[taken] <= rpo[b] || rpo[not_taken] <= rpo[b]);
let nm = p.blocks[b].insts.last().map_or("?", |i| i.name());
format!("B{b}({nm}{})", if back { ",BACK" } else { "" })
})
.collect();
eprintln!("WAVE64-WIDE {} branches taken wave-wide: [{}]", wide.len(), desc.join(", "));
} }
return r; return r;
} }
+5
View File
@@ -24,6 +24,11 @@ pub const ROOT_CBV_SPACE: u32 = 1;
/// root SRV also tells the host that the buffer views of the whole heap /// root SRV also tells the host that the buffer views of the whole heap
/// must be ready when it runs, not only those its tables name. /// must be ready when it runs, not only those its tables name.
pub const SLOT_STRIDES: u8 = 255; pub const SLOT_STRIDES: u8 = 255;
/// The same table of strides and format kinds as [`SLOT_STRIDES`], bound for
/// shaders that only inspect views from descriptor tables (`RootType::Table`).
/// Kept distinct from [`SLOT_STRIDES`] so the host binds the table without
/// running the full bindless heap buffer sweep.
pub const SLOT_TABLE_STRIDES: u8 = 252;
/// The bits of a [`SLOT_STRIDES`] dword that hold the stride. /// The bits of a [`SLOT_STRIDES`] dword that hold the stride.
pub const VIEW_STRIDE_BITS: u32 = (1 << 30) - 1; pub const VIEW_STRIDE_BITS: u32 = (1 << 30) - 1;
/// In a [`SLOT_STRIDES`] dword: a typed buffer view of an integer format /// In a [`SLOT_STRIDES`] dword: a typed buffer view of an integer format
@@ -2057,3 +2057,337 @@ fn rdna_forms_give_what_the_spelled_out_ones_give() {
} }
} }
} }
/// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`.
const fn mubuf_idxen(op: u8, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] {
[
0x38 << 26 | (op as u32) << 18 | 1 << 13,
0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32,
]
}
/// SMEM `s_load_dwordx4 s[dst:dst+3], s[base:base+1], byte_offset` (soffset = null).
const fn s_load_dwordx4_off(dst: u8, base: u8, byte_offset: u32) -> [u32; 2] {
[
0x3D << 26 | 0x02 << 18 | (dst as u32) << 6 | (base as u32 >> 1),
(125 << 25) | (byte_offset & 0x1F_FFFF),
]
}
/// Builds a compute shader whose descriptors live in a `RootType::Table` at
/// `s4` (like `compute_graph_ops` and `ped_standard_head_cs`).
fn build_table_typed_cs(body: &[u32], used: Vec<UsedResource>) -> HostShader {
let mut words = Vec::new();
words.push(s_mov_b32(5, 0x80)); // s5 = 0
words.extend_from_slice(body);
words.push(S_ENDPGM);
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
let native = NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 8,
layout: vec![RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 4,
slot: 0,
}],
used,
io: StageIo::Cs(ComputeIo {
rsrc2: 5 << 1, // 5 user SGPRs: s0..s4
threads: [4, 1, 1],
}),
code,
};
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let st = structure::structure(&p).expect("structure");
let res =
resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track");
let io = io::raise(&p, &native).expect("io::raise");
let lowered = lower::lower(&lower::Parts {
native: &native,
p: &p,
st: &st,
io: &io,
res: &res,
inputs: Vec::new(),
outputs: Vec::new(),
prims: Vec::new(),
mesh_stride: 0,
})
.expect("lower");
let shader = HostShader {
stage: HwStage::Cs,
dxil: lowered.dxil,
user_data: lowered.user_data,
samplers: lowered.samplers,
static_samplers: Vec::new(),
root_cbvs: lowered.root_cbvs,
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: res.root_indexed_views,
};
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut copy = shader.dxil.clone();
v.validate(&mut copy).expect("DXIL validation failed");
}
shader
}
/// `compute_graph_ops` (facial lip-sync & wrapped submesh solver) binds
/// `R16G16B16A16_UINT` / `R16_UINT` UAVs via `RootType::Table` (which on NVIDIA
/// are snapshotted into dynamic descriptor slots) and reads/writes FP16 bit
/// patterns with `buffer_load_format_d16_xyzw` and `buffer_store_format_d16_xyzw`.
/// Verify bit-exact round-trips for UINT, SINT, and FLOAT views (including
/// non-zero table offsets matching dynamic descriptor snapshots) on hardware
/// GPU and WARP.
#[test]
fn typed_d16_table_uav_roundtrip_uint_sint_and_float() {
use windows::Win32::Graphics::Dxgi::Common::{
DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_SINT,
DXGI_FORMAT_R16G16B16A16_UINT,
};
let _serial = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let mut body = Vec::new();
// s[8:11] = table[0] (src typed UAV), s[12:15] = table[1] (dst typed UAV),
// s[16:19] = table[2] (raw UAV dump of loaded v[2:3]).
body.extend_from_slice(&s_load_dwordx4_off(8, 4, 0));
body.extend_from_slice(&s_load_dwordx4_off(12, 4, 32));
body.extend_from_slice(&s_load_dwordx4_off(16, 4, 64));
// buffer_load_format_d16_xyzw v[2:3], v0, s[8:11], 0 idxen (op 0x83)
body.extend_from_slice(&mubuf_idxen(0x83, 2, 0, 8));
// buffer_store_format_d16_xyzw v[2:3], v0, s[12:15], 0 idxen (op 0x87)
body.extend_from_slice(&mubuf_idxen(0x87, 2, 0, 12));
// Also dump thread 0's loaded v[2:3] into raw UAV (table[2]) to verify the load itself.
// v4 = v0 << 3 (byte offset = thread * 8)
body.push(0x3408_0083); // v_lshlrev_b32 v4, 3, v0
// buffer_store_dwordx2 v[2:3], v4, s[16:19], 0 offen (op 0x1D, offen bit 12)
body.extend_from_slice(&[
0x38 << 26 | 0x1D << 18 | 1 << 12,
0x80 << 24 | (16u32 >> 2) << 16 | (2u32 << 8) | 4u32,
]);
let used = (0..3u32)
.map(|k| UsedResource {
kind: ResourceType::Uav,
root: RootType::Table,
table_offset_dwords: k * 8,
lower_bound: k,
stride: 4,
dwords: 4,
user_data: 4,
slot: 0,
})
.collect();
let shader = build_table_typed_cs(&body, used);
assert!(
shader.root_srvs.contains(&super::SLOT_TABLE_STRIDES),
"table typed d16 shader should request SLOT_TABLE_STRIDES"
);
assert!(
!shader.root_srvs.contains(&super::SLOT_STRIDES),
"table-only shader must not trigger the bindless SLOT_STRIDES sweep"
);
// 4 elements x 4 u16 channels = 8 u32 dwords.
// Includes FP16 subnormal (0x0001), -0.0 (0x8000), 1.0 (0x3C00), -1.0 (0xBC00),
// NaN (0x7E00), max u16 (0xFFFF), and arbitrary patterns.
let uint_bits: [u32; 8] = [
0x3C00_0001, 0x7E00_BC00,
0xFFFF_8000, 0xABCD_1234,
0x0002_0000, 0x7BFF_FBFF,
0xDEAD_BEEF, 0xCAFE_BABE,
];
let sint_bits: [u32; 8] = [
0xFFFF_8000, 0x7FFF_0001,
0xC000_0000, 0x8001_7FFE,
0xFFFF_FFFF, 0x0000_0000,
0xFEDC_BA98, 0x7654_3210,
];
// Normal finite FP16 values that round-trip cleanly through f32.
let float_bits: [u32; 8] = [
0x4000_3C00, 0x3800_BC00, // 1.0, 2.0, -1.0, 0.5
0xC200_3400, 0x4500_0000, // 0.25, -3.0, 0.0, 5.0
0x3E00_BE00, 0x4400_C400, // -1.5, 1.5, -4.0, 4.0
0x3C00_0000, 0x4200_C000, // 0.0, 1.0, -2.0, 3.0
];
let zeros = [0u32; 8];
let cases = [
("R16G16B16A16_UINT @0", DXGI_FORMAT_R16G16B16A16_UINT, 8 | super::VIEW_INTEGER, &uint_bits, 0u32),
("R16G16B16A16_UINT @3 (dynamic offset)", DXGI_FORMAT_R16G16B16A16_UINT, 8 | super::VIEW_INTEGER, &uint_bits, 3u32),
("R16G16B16A16_SINT @0", DXGI_FORMAT_R16G16B16A16_SINT, 8 | super::VIEW_INTEGER | super::VIEW_SIGNED, &sint_bits, 0u32),
("R16G16B16A16_FLOAT @0", DXGI_FORMAT_R16G16B16A16_FLOAT, 8, &float_bits, 0u32),
];
for (backend, warp) in [("hardware", false), ("warp", true)] {
let Ok(host) = Host::new(warp) else { continue };
let (root, pso) = host
.compute_pipeline(&shader)
.unwrap_or_else(|e| panic!("{backend}: compute_pipeline failed: {e}"));
for &(label, format, stride_word, input, base_slot) in &cases {
let mut views = Vec::new();
let mut strides = Vec::new();
for _ in 0..base_slot {
views.push(View::RawUav(1));
strides.push(0u32);
}
let uav_base = base_slot as usize;
views.push(View::TypedUav { data: input, format, elem_bytes: 8 });
strides.push(stride_word);
views.push(View::TypedUav { data: &zeros, format, elem_bytes: 8 });
strides.push(stride_word);
views.push(View::RawUav(8));
strides.push(1);
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
if u.root == RootType::Table && u.slot == 0 {
ud[u.index as usize] = base_slot * 32;
}
}
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![
(0, Root::Constants(ud)),
(1, Root::View { srv: true, data: strides }),
],
views: &views,
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("{backend} {label}: dispatch failed: {e}"));
assert_eq!(
out[uav_base + 2],
input,
"{backend} {label}: buffer_load_format_d16_xyzw mismatch"
);
assert_eq!(
out[uav_base + 1],
input,
"{backend} {label}: buffer_store_format_d16_xyzw mismatch"
);
}
}
}
/// Non-`d16` typed loads (`buffer_load_format_x`) are used by
/// `CS_BlendshapeTranslationsHSSGraphOutputExtract` (reading `HSSGraphOut`
/// `R16_UINT`) and `CS_PedStandardSkinning_*` (reading bone indices). Verify
/// exact integer bits for `R16_UINT`, `R16_SINT`, and `R32_UINT`.
#[test]
fn typed_non_d16_table_load_preserves_integer_bits() {
use windows::Win32::Graphics::Dxgi::Common::{
DXGI_FORMAT_R16_SINT, DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R32_UINT,
};
let _serial = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let mut body = Vec::new();
// s[8:11] = table[0] (src typed SRV), s[12:15] = table[1] (raw UAV out)
body.extend_from_slice(&s_load_dwordx4_off(8, 4, 0));
body.extend_from_slice(&s_load_dwordx4_off(12, 4, 32));
// buffer_load_format_x v2, v0, s[8:11], 0 idxen (op 0x00)
body.extend_from_slice(&mubuf_idxen(0x00, 2, 0, 8));
// v4 = v0 << 2 (byte offset = thread * 4)
body.push(0x3408_0082); // v_lshlrev_b32 v4, 2, v0
// buffer_store_dword v2, v4, s[12:15], 0 offen (op 0x1C, offen bit 12)
body.extend_from_slice(&[
0x38 << 26 | 0x1C << 18 | 1 << 12,
0x80 << 24 | (12u32 >> 2) << 16 | (2u32 << 8) | 4u32,
]);
let used = vec![
UsedResource {
kind: ResourceType::Srv,
root: RootType::Table,
table_offset_dwords: 0,
lower_bound: 0,
stride: 4,
dwords: 4,
user_data: 4,
slot: 0,
},
UsedResource {
kind: ResourceType::Uav,
root: RootType::Table,
table_offset_dwords: 8,
lower_bound: 1,
stride: 4,
dwords: 4,
user_data: 4,
slot: 0,
},
];
let shader = build_table_typed_cs(&body, used);
// Non-d16 typed loads stay untouched (no SLOT_TABLE_STRIDES root SRV, no
// CFG branches) so non-d16 pixel/mesh/particle/skinning shaders keep
// identical DXIL and pipeline cache keys while still preserving raw bits.
assert!(
!shader.root_srvs.contains(&super::SLOT_TABLE_STRIDES),
"non-d16 typed load should not add SLOT_TABLE_STRIDES"
);
let r16_data = [0x3C00_0001u32, 0xFFFF_BC00u32];
let r32_data = [0xDEAD_BEEFu32, 0x0000_0001, 0x8000_0000, 0x7FFF_FFFF];
let cases: [(&str, _, u32, &[u32], [u32; 4]); 3] = [
(
"R16_UINT",
DXGI_FORMAT_R16_UINT,
2,
&r16_data,
[0x0001, 0x3C00, 0xBC00, 0xFFFF],
),
(
"R16_SINT",
DXGI_FORMAT_R16_SINT,
2,
&r16_data,
[0x0001, 0x3C00, 0xFFFF_BC00, 0xFFFF_FFFF],
),
(
"R32_UINT",
DXGI_FORMAT_R32_UINT,
4,
&r32_data,
r32_data,
),
];
for (backend, warp) in [("hardware", false), ("warp", true)] {
let Ok(host) = Host::new(warp) else { continue };
let (root, pso) = host
.compute_pipeline(&shader)
.unwrap_or_else(|e| panic!("{backend}: compute_pipeline failed: {e}"));
for &(label, format, elem_bytes, input, want) in &cases {
let views = [
View::Buffer {
data: input,
stride: super::host::Stride::Format(format, elem_bytes),
},
View::RawUav(4),
];
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
if u.root == RootType::Table && u.slot == 0 {
ud[u.index as usize] = 0;
}
}
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &views,
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("{backend} {label}: dispatch failed: {e}"));
assert_eq!(out[0], want, "{backend} {label}: buffer_load_format_x mismatch");
}
}
}
+59 -9
View File
@@ -227,9 +227,9 @@ pub fn track(
let mut offset_at = let mut offset_at =
std::collections::BTreeMap::<usize, (Vec<usize>, Vec<Value>, Vec<Site>)>::new(); std::collections::BTreeMap::<usize, (Vec<usize>, Vec<Value>, Vec<Site>)>::new();
for (b, block) in p.blocks.iter().enumerate() { for (b, block) in p.blocks.iter().enumerate() {
t.at.set(Some(b));
for (i, inst) in block.insts.iter().enumerate() { for (i, inst) in block.insts.iter().enumerate() {
let site = (b, i); let site = (b, i);
t.at.set(Some(site));
if let Some(value) = t.restored(inst, Some(b)) { if let Some(value) = t.restored(inst, Some(b)) {
out.restored_lanes.insert(site, value); out.restored_lanes.insert(site, value);
} }
@@ -240,7 +240,7 @@ pub fn track(
let mut first_lane = Vec::new(); let mut first_lane = Vec::new();
let mut offset = Vec::new(); let mut offset = Vec::new();
let mut descriptor = |op: &Operand, role| -> Result<(), ShaderError> { let mut descriptor = |op: &Operand, role| -> Result<(), ShaderError> {
let source = t.descriptor(inst, op, b).map_err(fail)?; let source = t.descriptor(inst, op, site).map_err(fail)?;
// A descriptor the code keeps per lane ([`Tracer::lane_copies`]) // A descriptor the code keeps per lane ([`Tracer::lane_copies`])
// is the same in every lane: its loop is lowered as it stands // is the same in every lane: its loop is lowered as it stands
// and needs no proof. // and needs no proof.
@@ -417,8 +417,8 @@ struct Tracer<'a> {
meets: std::cell::RefCell<Meets>, meets: std::cell::RefCell<Meets>,
/// Reverse-postorder index per block. /// Reverse-postorder index per block.
rpo: Vec<usize>, rpo: Vec<usize>,
/// The block of the access being traced ([`Self::live`]). /// The instruction site of the access being traced ([`Self::live`]).
at: std::cell::Cell<Option<usize>>, at: std::cell::Cell<Option<Site>>,
} }
/// What lanes are known to satisfy: each [`Bool`] where its flag is set, /// What lanes are known to satisfy: each [`Bool`] where its flag is set,
@@ -1119,8 +1119,8 @@ impl<'a> Tracer<'a> {
self.address(lo, hi, extra) self.address(lo, hi, extra)
} }
/// The source of the descriptor operand `op` of `inst`, in block `at`. /// The source of the descriptor operand `op` of `inst`, at `at`.
fn descriptor(&self, inst: &Inst, op: &Operand, at: usize) -> Result<Source, &'static str> { fn descriptor(&self, inst: &Inst, op: &Operand, at: Site) -> Result<Source, &'static str> {
let Operand::Scalar { code, dwords } = *op else { let Operand::Scalar { code, dwords } = *op else {
return Err("a descriptor not in SGPRs"); return Err("a descriptor not in SGPRs");
}; };
@@ -1135,8 +1135,14 @@ impl<'a> Tracer<'a> {
{ {
words = raw.to_vec(); words = raw.to_vec();
} }
// Only the lanes that reach the access read the descriptor. // Only the lanes that reach and run the access read the descriptor.
let mut known = Vec::from_iter(self.lanes.map(|l| (l.reach[at], true))); let mut known = Vec::new();
if let Some(l) = self.lanes {
known.push((l.reach[at.0], true));
if let Some(guard) = l.guards[at.0][at.1] {
known.push((guard, true));
}
}
self.classify(&words, &mut Vec::new(), &mut known) self.classify(&words, &mut Vec::new(), &mut known)
} }
@@ -1288,7 +1294,10 @@ impl<'a> Tracer<'a> {
let (Some(at), Some(lanes)) = (self.at.get(), self.lanes) else { let (Some(at), Some(lanes)) = (self.at.get(), self.lanes) else {
return t; return t;
}; };
let mut known = vec![(lanes.reach[at], true)]; let mut known = vec![(lanes.reach[at.0], true)];
if let Some(guard) = lanes.guards[at.0][at.1] {
known.push((guard, true));
}
for _ in 0..MAX_JOINS { for _ in 0..MAX_JOINS {
let Term::Value(v) = t else { break }; let Term::Value(v) = t else { break };
let Some((block, i)) = self.phis[v.0 as usize] else { let Some((block, i)) = self.phis[v.0 as usize] else {
@@ -4098,4 +4107,45 @@ pub(crate) mod tests {
assert_eq!(r.waterfall.compares.len(), 2); assert_eq!(r.waterfall.compares.len(), 2);
assert_eq!(r.waterfall.reads.len(), 4); assert_eq!(r.waterfall.reads.len(), 4);
} }
#[test]
fn a_guarded_access_excludes_dead_lane_edges_at_a_join() {
// Lanes failing `v_cmp_gt_u32` clear EXEC and take `s_cbranch_execz`
// directly to the join block without initializing the immediate
// sampler `s[8:11]`. The join's `image_sample_lz` is guarded by EXEC,
// so only the arm where `s[8:11]` was built can execute it.
let code: Vec<u8> = [
0xBE84_0300u32, // s_mov_b32 s4, s0
0xBE85_0380, // s_mov_b32 s5, 0
0xF40C_0302,
0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0
0x7E04_0D00, // v_cvt_f32_u32 v2, v0
0x7E06_0302, // v_mov_b32 v3, v2
0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0
0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
0x877E_6A7E, // s_and_b32 exec_lo, exec_lo, vcc_lo
0xBF88_0004, // s_cbranch_execz -> join (skips 4 dwords)
0xBE88_0380, // s_mov_b32 s8, 0
0xBE89_0380, // s_mov_b32 s9, 0
0xBE8A_0380, // s_mov_b32 s10, 0
0xBE8B_0380, // s_mov_b32 s11, 0
0xF09C_0F08,
0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11]
S_ENDPGM,
]
.iter()
.flat_map(|w| w.to_le_bytes())
.collect();
let p = crate::ir::build(&code, false, 256).unwrap();
let structured = lanes(&p).expect("structured form");
assert!(structured.guards[2][0].is_some(), "join access must carry an EXEC guard");
let r = track(&p, &[param(Table, 0, 1)], HwStage::Cs, Some(&structured)).unwrap();
assert!(
r.descriptors
.iter()
.any(|d| d.role == Role::Sampler && d.source == Source::Constant(vec![0; 4])),
"guarded join should resolve the immediate sampler from the live arm: {:?}",
r.descriptors
);
}
} }
+4
View File
@@ -13,3 +13,7 @@
- **15:56–15:59, reproducer and repair.** Replayed eight reported upload sizes through the release pool with a failing block allocator. The unpatched test made eight block creation attempts in one burst. Each pool now backs off growth for 500 ms after a failed creation while still reusing space in its existing blocks. An out-of-memory return from host upload or texture allocation interrupts the descriptor texture sweep, leaving interrupted work eligible for retry. The sweep checks available Windows commit at most once per 32 ms, including during a long pass. It defers ordinary prefetch below 4 GiB and bake prefetch below 2 GiB; explicitly bound textures can still request upload memory. GPU unit and device suite: 331 passed, 34 ignored. - **15:56–15:59, reproducer and repair.** Replayed eight reported upload sizes through the release pool with a failing block allocator. The unpatched test made eight block creation attempts in one burst. Each pool now backs off growth for 500 ms after a failed creation while still reusing space in its existing blocks. An out-of-memory return from host upload or texture allocation interrupts the descriptor texture sweep, leaving interrupted work eligible for retry. The sweep checks available Windows commit at most once per 32 ms, including during a long pass. It defers ordinary prefetch below 4 GiB and bake prefetch below 2 GiB; explicitly bound textures can still request upload memory. GPU unit and device suite: 331 passed, 34 ignored.
- **16:00–16:03, first opening-save retest.** Windows Graphics Capture showed a character, textured buildings and street lighting. The log contained no failed upload-buffer allocations or Rust allocation aborts. The harness timed out during shutdown and lost its timing receipt. The renderer logged a dropped draw due to exhausted dynamic descriptor slots. - **16:00–16:03, first opening-save retest.** Windows Graphics Capture showed a character, textured buildings and street lighting. The log contained no failed upload-buffer allocations or Rust allocation aborts. The harness timed out during shutdown and lost its timing receipt. The renderer logged a dropped draw due to exhausted dynamic descriptor slots.
- **16:04–16:07, confirmation and install.** From a fresh copy of the opening save, the release ran 135 seconds after the first interval above 1,000 draws/frame and remained live until the harness closed it. Peak process commit was 34.42 GiB; the lowest sampled Windows commit headroom was 1.30 GiB. Zero E_OUTOFMEMORY returns and zero Rust allocation aborts appeared in the log. Across 120 high-draw caption intervals the median was 54.3 ms/frame, with 39 at or below 50 ms. The descriptor-slot warning recurred. Installed and hash-verified the release behind the existing `pareto-residency` selector. SHA-256 `d580328bf90fe54e643dad60c04481d7e4b0d7134b9b6ce70c5e0f5c77ff3cf1`. Receipt and log: `../XCL-frame-timing/pareto-residency-comparison/oom-confirm/`. - **16:04–16:07, confirmation and install.** From a fresh copy of the opening save, the release ran 135 seconds after the first interval above 1,000 draws/frame and remained live until the harness closed it. Peak process commit was 34.42 GiB; the lowest sampled Windows commit headroom was 1.30 GiB. Zero E_OUTOFMEMORY returns and zero Rust allocation aborts appeared in the log. Across 120 high-draw caption intervals the median was 54.3 ms/frame, with 39 at or below 50 ms. The descriptor-slot warning recurred. Installed and hash-verified the release behind the existing `pareto-residency` selector. SHA-256 `d580328bf90fe54e643dad60c04481d7e4b0d7134b9b6ce70c5e0f5c77ff3cf1`. Receipt and log: `../XCL-frame-timing/pareto-residency-comparison/oom-confirm/`.
- **16:50–18:20, facial deformation & wrapped meshes (`d16` + table strides).** Added zero-sweep table view-kind lookup (`SLOT_TABLE_STRIDES = 252`, `heap_strides`) and dynamic descriptor slot stride population in `descriptor/host.rs`, plus NVIDIA-valid typed integer lowering (`bufferLoad.i32`/`bufferStore.i32` on `VIEW_INTEGER`/`VIEW_SIGNED`). Initially applying typed integer branching to non-`d16` typed loads caused shader regressions; restricting integer branching to `buffer_load_format_d16_*` and `buffer_store_format_d16_*` restored clean shading while keeping `VICTORY_TRANSLATOR` cache-compatible with `tools/cache-pareto` (`made=0`).
- **19:15–20:30, commit-gate starvation & synchronous bake uploads.** Lowered commit reserves (`has_upload_reserve`: 256 MiB bake / 512 MiB non-bake; `has_growth_reserve`: 256 MiB bake / 1024 MiB speculative bindless; pressure entry 3 GiB RAM / 4 GiB commit, recovery 5 GiB / 6 GiB), scoped 64 MiB staging-block growth gating in `pool.rs` (`REST = 2500 ms`) to speculative bindless only, expanded bake detection (`BAKE_GEOMETRY_SHADERS`, `ahead::drain`, `BAKE_PAGE_WRITTEN`), and routed one-shot ped/decoration bake uploads through a dedicated synchronous host list (`BAKE_UPLOAD` / `execute_sync_internal`) with post-upload descriptor publication (`prepare_bake_slot` / `publish_uploaded_slot`). GPU suite: 335 passed, 34 ignored.
- **20:50–21:10, alias-flood experiment reverted & clean release built.** Propagating aliased view maps/unmaps into `REMAPPED` and widening bake lookahead caused 2–4 GiB bake-pass truncations on frames 1368–1369 (`cap_alias_fix_rel`, median 70.5 ms in diagnostics capture, face-mask/shorts regression) and was reverted. Rebuilt clean release binary `target/release/victory.exe` without the alias flood (SHA-256 `38e99f1b1d6bafda2ff8de74d6566af06bc7e8cab70594d841af01752e501d73`); installation into `Downloads/leonida/victory-3d-rtx-pareto-residency.exe` deferred while user-launched PID 13544 holds the file open.
- **21:30–22:28, transmission prefilter Wave32 recovery, texture-starvation & scene-blinking fixes.** Diagnosed four linked regressions on RTX 5090 (32 GiB RAM): (1) `alphaResolve:CS_AlphTransmissionPrefilterMip_610a2fad` (`2da4beb386509b77`) was dropped under Wave32 `without_early_outs` because `resource::Tracer::descriptor()` and `live()` omitted per-instruction `lanes.guards[b][i]` when pruning dead join edges, leaving transmission buffer `0x17dff443d70` zeroed and causing `ptfx_PS_Transmission_aba1527f` (dual-source blend) and transmissive eye/alpha shaders to output black squares / corrupted blending; fixed in `crates/victory-shader/src/resource.rs` (`VICTORY_WAVE_WIDE` intentionally kept off due to known loop-widening TDR risk). (2) Completed submissions kept `Detached._state` dynamic descriptor slots pinned across `bury_lag()` (`16` submissions) in `host.rs` (`relay_land`, `settle`), exhausting NVIDIA's 262k dynamic slot pool and dropping draws; added `Detached::release_tables()` right on GPU completion plus a `settle_for_fence()` retry in `draw.rs`, and defaulted `VICTORY_INDIRECT_REST=0` in `indirect.rs` so one oversized indirect record does not zero out subsequent draws. (3) Split residency throttling into mild pressure vs. `critical_commit()` (`< 1536 MiB` commit or upload refusal) across `residency.rs`, `texture/ahead.rs`, and `pool.rs` so `VICTORY_UPLOAD_AHEAD`, `64 MiB/frame` prefetch, and one spare staging block stay active under mild 32 GiB pressure instead of stalling tens of thousands of textures on `neutral()`; fixed `descriptor/host.rs` (`prepare_bake_slot`, `publish_uploaded_slot`) and `draw.rs` (`flush_for_bake`) so pending bake slots are never prematurely overwritten with `neutral()` or silently dropped on defer/unmapped pages, and removed false `address=0x0` unordered-SRV warning spam. (4) Scoped `VICTORY_AMBIENT_AIR=1.5` to `pareto-residency` in `Downloads/leonida/Play-VIctory.cmd` to clear milky indoor ambient haze. Verification: `victory-shader` lib suite 281 passed, 0 failed, 4 ignored (including new `a_guarded_access_excludes_dead_lane_edges_at_a_join`); targeted `victory-gpu` suite 20 passed, 0 failed; RTX 5090 `translate --jobs 1 --validate --pipelines` on 154 VFX/particle/eye shaders emitted & validated 43/43 graphics + 96/111 compute pipelines (recovering `CS_AlphTransmissionPrefilterMip`, 0 regressions). Deployed release binary to `Downloads/leonida/victory-3d-rtx-pareto-residency.exe`, SHA-256 `37a410b13fcd5ef4cecfe2c27761b7132af64b00019a07c9256529b96892d7da`.