Water light on, PS4 pads, F1 menu saves at once, long-session memory, memory switches
Rendering and memory (GPL-3.0 code ported in; credits in the source): - Water: 64-lane compute programs on 32-lane waves keep each wave together through loops and set up shared memory from the first thread, so the water's tiled light no longer leaves dark blocks. It runs by default now (VICTORY_WATER_LIGHT=0 leaves it out; an empty value, an earlier version's saved OFF, runs it). Also cloud tiles and the screen probes' ray activation. - Placed views: their padding cleared as before; folding a buffer view's first element into its address is VICTORY_PLACED_FOLD=1, off: with it on, clothing and caps swapped to other variants for single frames in the boat cutscene. - Texture sweep: textures whose copy was let go leave the looks until used again. Static samplers made first, in one order. Small buffers made ahead of the first 3D frame. - play mode: VICTORY_TEXSPK_PASS_MS=8, VICTORY_PASSES_HOT=1, VICTORY_HELPER_PRIORITY=1. - Memory switches, all off: VICTORY_SLOT_EVICT, VICTORY_ALLOCATOR_TRIM, VICTORY_BUDGET_PACK (and VICTORY_LIST_POOL_IDLE_S). Input: DualShock 4 (0x05C4, 0x09CC, 0x0BA0 adapter) read over HID, USB and Bluetooth, beside the DualSense; PlayStation pads rumble, and stop when the game ends (issue #352). F1 menu: every change is saved at once; it saves to victory-settings.txt in VICTORY_HOME or %LOCALAPPDATA%\victory however the game was started (no more "NO SETTINGS FILE"). Warm-up start: its 30 s count from the first frame of 100 draws or more, not from the start: waiting at the title screen restarted it too early and the next run still sat at 14 fps. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
df2daafeb1
commit
64d4931b3d
44 files changed
+4664
-952
No files matched your search
@@ -0,0 +1,165 @@
|
||||
//! Buffers of 64 KiB made ahead of the title's need for them.
|
||||
//!
|
||||
//! Every title buffer gets a copy of the host's, rounded up to 64 KiB, and with
|
||||
//! `VICTORY_CARD_BUFFERS` a second one in the card's memory. Making one pair takes about
|
||||
//! 0.8 ms (two committed resources, each waited for until its memory is there), and the title
|
||||
//! asks for thousands in the frame a scene starts in: the first frame with a 3D scene of a new
|
||||
//! game made 3,450 of them and stood for 2.8 s of its 4 s over them alone (run full1,
|
||||
//! 2026-11-27, RTX 4070 SUPER + Ryzen 7 7800X3D), and while a scene streams in about a
|
||||
//! thousand a second are made by the threads a frame waits for.
|
||||
//!
|
||||
//! A thread of low priority makes them while the title shows its logos and keeps some in
|
||||
//! store afterwards (`VICTORY_BUFFERS_AHEAD=<n>`: that many at first, at most 1024 kept
|
||||
//! afterwards; default 4096; `0`: none, every buffer is made when it is asked for, as before).
|
||||
//! A buffer taken from here is what [`crate::host::Host::shared_buffer`] or
|
||||
//! [`crate::host::Host::uav_buffer`] would have made then: new, zeroed, its memory there.
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::ID3D12Resource;
|
||||
|
||||
/// The size of the buffers made ahead: what a title buffer of up to 64 KiB is rounded to.
|
||||
pub(crate) const SIZE: u64 = 1 << 16;
|
||||
|
||||
/// Kept in store once the first lot is made.
|
||||
const KEPT: usize = 1024;
|
||||
|
||||
/// A buffer the CPU maps, and where.
|
||||
struct Shared(ID3D12Resource, usize);
|
||||
|
||||
// SAFETY: D3D12 objects are free-threaded; the address is of the buffer's own mapping, which
|
||||
// lives as long as it does.
|
||||
unsafe impl Send for Shared {}
|
||||
|
||||
struct Card(ID3D12Resource);
|
||||
|
||||
// SAFETY: D3D12 objects are free-threaded.
|
||||
unsafe impl Send for Card {}
|
||||
|
||||
static SHARED: Mutex<Vec<Shared>> = Mutex::new(Vec::new());
|
||||
static CARD: Mutex<Vec<Card>> = Mutex::new(Vec::new());
|
||||
/// Whether the title's buffers get a side in the card's memory (seen by `crate::shadow`).
|
||||
static CARD_WANTED: AtomicBool = AtomicBool::new(false);
|
||||
/// Taken from the store: buffers the CPU maps, buffers on the card.
|
||||
static TAKEN: [AtomicUsize; 2] = [AtomicUsize::new(0), AtomicUsize::new(0)];
|
||||
|
||||
fn first() -> usize {
|
||||
static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
|
||||
*N.get_or_init(|| {
|
||||
std::env::var("VICTORY_BUFFERS_AHEAD").ok().and_then(|v| v.trim().parse::<usize>().ok()).unwrap_or(4096).min(16384)
|
||||
})
|
||||
}
|
||||
|
||||
/// Starts the thread that makes the buffers, once. Called when the first title buffer of any
|
||||
/// size gets a copy in the card's memory ([`want_card`]), which is in a run's first second:
|
||||
/// the store is full long before the first frame with a scene (started at the first buffer of
|
||||
/// [`SIZE`], as until run v1q of 2026-11-27, it was 46 s into the run and 2 s before that
|
||||
/// frame: 1,806 of its 3,674 buffers were still made when asked for).
|
||||
///
|
||||
/// Not at the first buffer of ours of any kind: the tools make such buffers too, and `victory
|
||||
/// warm` starts a process for every 40 pipelines. With 4,096 buffers made in each of them it
|
||||
/// compiled 18 pipelines a second in place of 350 (2026-11-27, 88,604 pipelines).
|
||||
pub(crate) fn start() {
|
||||
if first() == 0 {
|
||||
return;
|
||||
}
|
||||
static STARTED: std::sync::Once = std::sync::Once::new();
|
||||
STARTED.call_once(|| {
|
||||
if std::thread::Builder::new().name("victory-ahead".into()).spawn(fill).is_err() {
|
||||
tracing::warn!("no thread for the buffers made ahead: each is made when it is asked for");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Says that the title's buffers get a side in the card's memory, so such buffers are made
|
||||
/// ahead from now on.
|
||||
pub(crate) fn want_card() {
|
||||
CARD_WANTED.store(true, Ordering::Relaxed);
|
||||
start();
|
||||
}
|
||||
|
||||
/// A buffer of [`SIZE`] the CPU maps, if one is in store.
|
||||
pub(crate) fn shared() -> Option<(ID3D12Resource, *mut u8)> {
|
||||
if first() == 0 {
|
||||
return None;
|
||||
}
|
||||
let made = SHARED.lock().unwrap_or_else(|e| e.into_inner()).pop()?;
|
||||
TAKEN[0].fetch_add(1, Ordering::Relaxed);
|
||||
Some((made.0, made.1 as *mut u8))
|
||||
}
|
||||
|
||||
/// A buffer of [`SIZE`] in the card's memory, if one is in store. Asking says that the
|
||||
/// title's buffers get such a side, so they are made ahead from now on.
|
||||
pub(crate) fn card() -> Option<ID3D12Resource> {
|
||||
if first() == 0 {
|
||||
return None;
|
||||
}
|
||||
CARD_WANTED.store(true, Ordering::Relaxed);
|
||||
let made = CARD.lock().unwrap_or_else(|e| e.into_inner()).pop()?;
|
||||
TAKEN[1].fetch_add(1, Ordering::Relaxed);
|
||||
Some(made.0)
|
||||
}
|
||||
|
||||
fn fill() {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_BELOW_NORMAL};
|
||||
// SAFETY: this thread's own priority.
|
||||
unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL) };
|
||||
}
|
||||
// (The first buffer may be asked for while the host is still being set up.)
|
||||
let mut waited = 0;
|
||||
let host = loop {
|
||||
if let Some(host) = crate::host::host() {
|
||||
break host;
|
||||
}
|
||||
waited += 1;
|
||||
if waited > 1200 {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
};
|
||||
let began = std::time::Instant::now();
|
||||
let mut want = first();
|
||||
let mut said = false;
|
||||
loop {
|
||||
let shared = SHARED.lock().unwrap_or_else(|e| e.into_inner()).len();
|
||||
let card = CARD.lock().unwrap_or_else(|e| e.into_inner()).len();
|
||||
let card_wanted = CARD_WANTED.load(Ordering::Relaxed);
|
||||
// On the card only while it has room to spare: a store there must not take what
|
||||
// textures need (seven tenths of the budget; the title's own copies stop at eight).
|
||||
let card_room = card_wanted
|
||||
&& host.video_memory().is_none_or(|[budget, used, ..]| used + SIZE <= budget / 100 * 70);
|
||||
let (more_shared, more_card) = (shared < want, card < want && card_room);
|
||||
if !more_shared && !more_card {
|
||||
if !said && shared >= want && (card >= want || !card_room) && card_wanted {
|
||||
said = true;
|
||||
tracing::info!(
|
||||
"buffers of 64 KiB made ahead (VICTORY_BUFFERS_AHEAD={}): {} the CPU maps, {} on the card, in store {:.1} s after \
|
||||
the first title buffer got its copy on the card; taken meanwhile {} and {}; from now on {} are kept",
|
||||
first(),
|
||||
shared,
|
||||
card,
|
||||
began.elapsed().as_secs_f64(),
|
||||
TAKEN[0].load(Ordering::Relaxed),
|
||||
TAKEN[1].load(Ordering::Relaxed),
|
||||
first().min(KEPT)
|
||||
);
|
||||
want = first().min(KEPT);
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(if said { 20 } else { 50 }));
|
||||
continue;
|
||||
}
|
||||
if more_shared
|
||||
&& let Some((buffer, data)) = host.shared_buffer_now(SIZE)
|
||||
{
|
||||
SHARED.lock().unwrap_or_else(|e| e.into_inner()).push(Shared(buffer, data as usize));
|
||||
}
|
||||
if more_card
|
||||
&& let Some(buffer) = host.uav_buffer(SIZE)
|
||||
{
|
||||
CARD.lock().unwrap_or_else(|e| e.into_inner()).push(Card(buffer));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Two presented planes as one image: the console's display puts the second
|
||||
//! (the interface) over the first (the scene), each scaled to the screen.
|
||||
//! Grand Theft Auto VI presents so on Series S.
|
||||
//! The game presents so on Series S.
|
||||
|
||||
use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
|
||||
use windows::Win32::Graphics::Direct3D::ID3DBlob;
|
||||
|
||||
@@ -357,6 +357,9 @@ fn big(at: *mut u8, size: usize, made: bool) {
|
||||
if size < BIG {
|
||||
return;
|
||||
}
|
||||
if made && size >= 64 << 20 {
|
||||
name_big(size);
|
||||
}
|
||||
for (place, bytes) in BIG_AT.iter().zip(&BIG_BYTES) {
|
||||
if made {
|
||||
if place.compare_exchange(0, at as usize, Relaxed, Relaxed).is_ok() {
|
||||
@@ -371,6 +374,26 @@ fn big(at: *mut u8, size: usize, made: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Set while [`name_big`] logs: what it allocates is not named again.
|
||||
static NAMING_BIG: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Logs where a block of ours of 64 MB or more is made, for the first 24:
|
||||
/// the memory census lists their sizes alone (one of 401 MB in run leak3).
|
||||
fn name_big(size: usize) {
|
||||
if NAMING_BIG.with(|n| n.replace(true)) {
|
||||
return;
|
||||
}
|
||||
static NAMED: AtomicU64 = AtomicU64::new(0);
|
||||
if NAMED.fetch_add(1, Relaxed) < 24 {
|
||||
let trace = std::backtrace::Backtrace::force_capture();
|
||||
tracing::info!(mb = size >> 20, "a block of ours of 64 MB or more made:
|
||||
{trace}");
|
||||
}
|
||||
NAMING_BIG.with(|n| n.set(false));
|
||||
}
|
||||
|
||||
/// The sizes of our own big blocks alive, largest first, in MB.
|
||||
fn big_blocks() -> String {
|
||||
let mut sizes: Vec<u64> = BIG_BYTES.iter().map(|b| b.load(Relaxed)).filter(|&b| b != 0).collect();
|
||||
@@ -900,7 +923,7 @@ fn log_memory() {
|
||||
"memory, more: views named whole in their records since the start: {} constant buffer \
|
||||
views, {} views of placed memory; of the view table's entries {} are constant buffer \
|
||||
views and {} views of placed memory; shapes of placed views kept: {}; host lists: {} \
|
||||
made by the host, {} preludes made for them, private bytes grew {:.0} MB while \
|
||||
made by the host, {} preludes made for them ({} alive), private bytes grew {:.0} MB while \
|
||||
lists were made; twins of depth textures: {:.0} MB; host copies of \
|
||||
placed textures whose title memory is not mapped any more (estimate): {:.0} MB, of \
|
||||
them still shown by a descriptor slot {:.0} MB; the pipeline library's mapped file \
|
||||
@@ -912,6 +935,7 @@ fn log_memory() {
|
||||
views[5],
|
||||
lists[0],
|
||||
lists[1],
|
||||
crate::host::PRELUDES_ALIVE.load(Relaxed),
|
||||
lists[2] as i64 as f64 / (1 << 20) as f64,
|
||||
mb(census[7]),
|
||||
mb(census[8]),
|
||||
|
||||
@@ -1210,6 +1210,39 @@ fn shape_of(unordered: bool, resource: &[u32; 14], desc: &[u32; 16]) -> (Shape,
|
||||
)
|
||||
}
|
||||
|
||||
/// Diagnostics: which words of placed views' shapes vary. Each new shape's
|
||||
/// 29 words (unordered, the resource's 14, the view's 14 without its
|
||||
/// address) go into a set per word, of at most 4,096 values; at 1,000 shapes
|
||||
/// and then every 50,000 the distinct values per word are logged, with the
|
||||
/// last shape's words. (Shapes were meant to be as many as the title has
|
||||
/// kinds of textures and buffers; run leak1 filled all 4,194,304.)
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
fn shape_census(shape: &Shape, count: usize) {
|
||||
use std::collections::HashSet;
|
||||
static SEEN: std::sync::Mutex<Vec<HashSet<u32>>> = std::sync::Mutex::new(Vec::new());
|
||||
let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if seen.is_empty() {
|
||||
seen.resize_with(29, HashSet::new);
|
||||
}
|
||||
let (unordered, resource, rest) = shape;
|
||||
let words: Vec<u32> = std::iter::once(u32::from(*unordered)).chain(resource.iter().copied()).chain(rest.iter().copied()).collect();
|
||||
for (set, &w) in seen.iter_mut().zip(&words) {
|
||||
if set.len() < 4096 {
|
||||
set.insert(w);
|
||||
}
|
||||
}
|
||||
if count == 1000 || (count > 0 && count % 50_000 == 0) {
|
||||
let distinct: Vec<String> = seen.iter().map(|s| s.len().to_string()).collect();
|
||||
let last: Vec<String> = words.iter().map(|w| format!("{w:x}")).collect();
|
||||
tracing::info!(
|
||||
shapes = count,
|
||||
"placed view shapes, distinct values per word (0 unordered, 1-14 the resource, 15-24 the view's words 0-9, 25-28 its words 12-15): {}; the last: {}",
|
||||
distinct.join(" "),
|
||||
last.join(" ")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The record words that name the view of placed memory at `address` with
|
||||
/// shape number `shape`.
|
||||
fn placed_words(shape: u32, address: u64) -> [u32; 2] {
|
||||
@@ -1226,6 +1259,8 @@ impl Views {
|
||||
if self.shapes.len() >= SHAPES {
|
||||
return None;
|
||||
}
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
shape_census(&shape, self.shapes.len());
|
||||
let at = self.shapes.len() as u32;
|
||||
self.shapes.push(shape);
|
||||
self.shape_index.insert(shape, at);
|
||||
@@ -1522,6 +1557,88 @@ pub(crate) fn make_waiting() {
|
||||
}
|
||||
}
|
||||
|
||||
// Slot eviction (`VICTORY_SLOT_EVICT=1`, `crate::resource::slot_evict`): memory stack by
|
||||
// skornuta (skornuta/victory-memory-stack 57fb136, GPL-3.0), patch 06 and its base.
|
||||
|
||||
/// For `crate::resource::slot_evict`: of the host textures `raws` (raw
|
||||
/// pointer to title texture), those shown only by title slots a draw makes
|
||||
/// again by itself (`HostHeap::slots_showing`), with those slots as (heap,
|
||||
/// index). A texture any other slot shows is left out (the third result
|
||||
/// counts them). So is one any of whose slots a draw's table showed after
|
||||
/// frame `cutoff` (the second result counts them): a texture drawn through
|
||||
/// a table every frame never asks for its host copy again, so its last use
|
||||
/// is old although it is on screen.
|
||||
#[cfg(windows)]
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub(crate) fn evictable_slots(
|
||||
raws: &std::collections::HashMap<usize, usize>,
|
||||
frame: u64,
|
||||
cutoff: u64,
|
||||
) -> (std::collections::HashMap<usize, Vec<(usize, u32)>>, u64, u64) {
|
||||
let set: std::collections::HashSet<usize> = raws.keys().copied().collect();
|
||||
let mut by_texture: std::collections::HashMap<usize, Vec<(usize, u32)>> = std::collections::HashMap::new();
|
||||
let mut blocked = std::collections::HashSet::new();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
{
|
||||
// (The heaps stay while the lock is held: `mirror`.)
|
||||
let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner());
|
||||
for &(_, _, at) in heaps.iter() {
|
||||
// SAFETY: a registered heap, live while the lock is held.
|
||||
let Some(Some(host)) = unsafe { &*(at as *const Heap) }.host.get() else {
|
||||
continue;
|
||||
};
|
||||
for (index, raw, ok, lately) in host.slots_showing(&set, frame, cutoff) {
|
||||
if lately {
|
||||
seen.insert(raw);
|
||||
}
|
||||
if ok {
|
||||
by_texture.entry(raw).or_default().push((at, index));
|
||||
} else {
|
||||
blocked.insert(raw);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let kept = seen.iter().filter(|raw| !blocked.contains(raw)).count() as u64;
|
||||
by_texture.retain(|raw, _| !blocked.contains(raw) && !seen.contains(raw));
|
||||
(
|
||||
by_texture.into_iter().filter_map(|(raw, slots)| Some((*raws.get(&raw)?, slots))).collect(),
|
||||
kept,
|
||||
blocked.len() as u64,
|
||||
)
|
||||
}
|
||||
|
||||
/// Puts the slots of title texture `resource` back to waiting for its host
|
||||
/// copy ([`evictable_slots`]): null now, made again when the texture is
|
||||
/// ([`make_waiting`]) or after the draw that reads them through a table.
|
||||
/// Returns how many were made. Called before the host copy is let go.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn evict_slots(resource: usize, slots: &[(usize, u32)]) -> u64 {
|
||||
let mut n = 0;
|
||||
for &(at, index) in slots {
|
||||
// (The heap stays while the lock is held: `mirror`.)
|
||||
let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner());
|
||||
if !heaps.iter().any(|&(_, _, h)| h == at) {
|
||||
continue;
|
||||
}
|
||||
// SAFETY: a registered heap, live while the lock is held.
|
||||
let heap = unsafe { &*(at as *const Heap) };
|
||||
let (Some(handle), Some(Some(host))) = (heap.handle(index), heap.host.get()) else {
|
||||
continue;
|
||||
};
|
||||
if host.texture_slot_evicted(index) {
|
||||
drop(heaps);
|
||||
let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let handles = waiting.entry(resource).or_default();
|
||||
if !handles.contains(&handle) {
|
||||
handles.push(handle);
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
fn record(handle: u64, view: View) {
|
||||
if handle == 0 {
|
||||
return;
|
||||
@@ -1634,56 +1751,6 @@ pub(crate) extern "system" fn create_uav(
|
||||
record(handle, view);
|
||||
}
|
||||
|
||||
/// Copy only the fields of a placed resource description. Padding can differ
|
||||
/// between two views of the same texture and the caller may leave it unwritten.
|
||||
fn placed_resource_words(desc: *const [u32; 14]) -> Option<[u32; 14]> {
|
||||
if desc.is_null() {
|
||||
return None;
|
||||
}
|
||||
let src = desc.cast::<u32>();
|
||||
let mut fields = [0; 14];
|
||||
// SAFETY: the caller supplies a 56-byte ResourceDesc, possibly unaligned.
|
||||
// Dimension occupies word 0. Alignment through Flags occupy words 2..13.
|
||||
unsafe {
|
||||
fields[0] = src.read_unaligned();
|
||||
fields[2..13].copy_from_slice(&src.add(2).cast::<[u32; 11]>().read_unaligned());
|
||||
}
|
||||
Some(fields)
|
||||
}
|
||||
|
||||
/// The words of a placed view's description with those its kind does not
|
||||
/// use set to zero. The first ten words are the PC's view description: for a
|
||||
/// shader resource view, the format, the dimension, the component mapping,
|
||||
/// a word of padding (the union that follows starts on 8 bytes) and the
|
||||
/// union's six words; for an unordered access view, the format, the
|
||||
/// dimension and the union's eight words. Each dimension uses only the head
|
||||
/// of the union, and the title leaves the rest unwritten: run vt-shapes saw
|
||||
/// 131,392 values in word 3 and 36,413 in word 9 of a million shapes, each
|
||||
/// a new shape for the same view. Words 10 and on (the address and the
|
||||
/// console's own fields) are kept; an unknown dimension keeps all.
|
||||
fn placed_view_words(desc: *const [u32; 16], unordered: bool) -> Option<[u32; 16]> {
|
||||
let mut d = words(desc)?;
|
||||
// Words of the union each dimension uses (D3D12_BUFFER_SRV and the like).
|
||||
let (start, used) = if unordered {
|
||||
// D3D12_UAV_DIMENSION: buffer, 1D, 1D array, 2D, 2D array, 2D MS,
|
||||
// 2D MS array, 3D.
|
||||
const USED: [usize; 9] = [0, 7, 1, 3, 2, 4, 0, 2, 3];
|
||||
(2, USED.get(d[1] as usize).copied())
|
||||
} else {
|
||||
// D3D12_SRV_DIMENSION: buffer, 1D, 1D array, 2D, 2D array, 2D MS,
|
||||
// 2D MS array, 3D, cube, cube array, acceleration structure.
|
||||
const USED: [usize; 12] = [0, 5, 3, 5, 4, 6, 0, 2, 3, 3, 5, 2];
|
||||
(4, USED.get(d[1] as usize).copied())
|
||||
};
|
||||
if let Some(used) = used.filter(|_| d[1] != 0) {
|
||||
if !unordered {
|
||||
d[3] = 0;
|
||||
}
|
||||
d[start + used..10].fill(0);
|
||||
}
|
||||
Some(d)
|
||||
}
|
||||
|
||||
/// Device methods 0x230 and 0x238: shader resource and unordered access
|
||||
/// views of memory the title placed itself, `(resource desc, view desc,
|
||||
/// handle)`.
|
||||
@@ -1693,7 +1760,8 @@ pub(crate) extern "system" fn create_placed_srv(
|
||||
desc: *const [u32; 16],
|
||||
handle: u64,
|
||||
) {
|
||||
if let (Some(resource), Some(desc)) = (placed_resource_words(resource), placed_view_words(desc, false)) {
|
||||
if let (Some(resource), Some(desc)) = (words(resource), words(desc)) {
|
||||
let (resource, desc) = normal_placed(false, resource, desc);
|
||||
record(handle, View::Placed(false, resource, desc));
|
||||
}
|
||||
}
|
||||
@@ -1704,11 +1772,103 @@ pub(crate) extern "system" fn create_placed_uav(
|
||||
desc: *const [u32; 16],
|
||||
handle: u64,
|
||||
) {
|
||||
if let (Some(resource), Some(desc)) = (placed_resource_words(resource), placed_view_words(desc, true)) {
|
||||
if let (Some(resource), Some(desc)) = (words(resource), words(desc)) {
|
||||
let (resource, desc) = normal_placed(true, resource, desc);
|
||||
record(handle, View::Placed(true, resource, desc));
|
||||
}
|
||||
}
|
||||
|
||||
/// A placed view as the title gives it carries bytes no view reads: the
|
||||
/// padding of the resource description (words 1 and 13), of a shader
|
||||
/// resource view's description (word 3), and the union's words past the
|
||||
/// member of the view's dimension. The title leaves them as its stack held
|
||||
/// them, so nearly every view of placed memory was a shape of its own: run
|
||||
/// leak1 filled the 4,194,304 shapes the records can name in 20 minutes on
|
||||
/// the water, then made 5.6 million table entries that nothing lets go
|
||||
/// (3.3 GB), and the frame time doubled; the reported slow-down, white
|
||||
/// picture and stuttering sound after long play. Those bytes are cleared.
|
||||
/// With `VICTORY_PLACED_FOLD=1`, a buffer view's first element is folded
|
||||
/// into its address and its buffer's width made the view's own length, so
|
||||
/// views of one ring of buffers at many offsets are one shape (off: it
|
||||
/// swapped clothing for single frames).
|
||||
/// `VICTORY_PLACED_NORMAL=0`: kept as the title gave them, as before.
|
||||
/// `VICTORY_PLACED_FOLD=1`: [`normal_placed`] also folds a buffer view's
|
||||
/// first element into its address.
|
||||
fn placed_fold() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_PLACED_FOLD").is_some_and(|v| v == "1"))
|
||||
}
|
||||
|
||||
fn normal_placed(unordered: bool, mut resource: [u32; 14], mut desc: [u32; 16]) -> ([u32; 14], [u32; 16]) {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
if !*ON.get_or_init(|| std::env::var_os("VICTORY_PLACED_NORMAL").is_none_or(|v| v != "0")) {
|
||||
return (resource, desc);
|
||||
}
|
||||
resource[1] = 0;
|
||||
resource[13] = 0;
|
||||
// The union's first word, and the words of the dimension's member
|
||||
// (unknown dimensions keep all of them).
|
||||
let (start, used) = if unordered {
|
||||
(2, match desc[1] {
|
||||
1 => 7,
|
||||
2 => 1,
|
||||
3 => 3,
|
||||
4 => 2,
|
||||
5 => 4,
|
||||
6 => 1,
|
||||
7 => 2,
|
||||
8 => 3,
|
||||
_ => 8,
|
||||
})
|
||||
} else {
|
||||
desc[3] = 0;
|
||||
(4, match desc[1] {
|
||||
1 => 5,
|
||||
2 => 3,
|
||||
3 => 5,
|
||||
4 => 4,
|
||||
5 => 6,
|
||||
6 => 1,
|
||||
7 => 2,
|
||||
8 => 3,
|
||||
9 => 3,
|
||||
10 => 5,
|
||||
11 => 2,
|
||||
_ => 6,
|
||||
})
|
||||
};
|
||||
for w in &mut desc[(start + used).min(10)..10] {
|
||||
*w = 0;
|
||||
}
|
||||
// A buffer view of a buffer: its first element into its address
|
||||
// (`VICTORY_PLACED_FOLD=1`; off by default). With it on, characters'
|
||||
// clothing and caps changed to other variants of theirs for single frames
|
||||
// in cutscenes (the boat ride, RTX 5070, 2026-11-27): views the title
|
||||
// keeps apart were taken for one. `VICTORY_PLACED_NORMAL=0` (no
|
||||
// clearing either) had it gone too; the clearing above alone was our
|
||||
// own before this merge, and keeps the shapes from leaking.
|
||||
if resource[0] == 1 && desc[1] == 1 && placed_fold() {
|
||||
let (count, stride, flags) = if unordered { (desc[4], desc[5], desc[8]) } else { (desc[6], desc[7], desc[8]) };
|
||||
// (Raw: a flag of 1 in both kinds of view.)
|
||||
let element = if stride > 0 {
|
||||
u64::from(stride)
|
||||
} else if flags & 1 != 0 {
|
||||
4
|
||||
} else {
|
||||
crate::resource::element(desc[0]).map_or(0, |(bytes, _)| bytes)
|
||||
};
|
||||
if element > 0 {
|
||||
let first = u64::from(desc[start]) | u64::from(desc[start + 1]) << 32;
|
||||
let address = (u64::from(desc[10]) | u64::from(desc[11]) << 32).wrapping_add(first.wrapping_mul(element));
|
||||
let len = u64::from(count) * element;
|
||||
(desc[start], desc[start + 1]) = (0, 0);
|
||||
(desc[10], desc[11]) = (address as u32, (address >> 32) as u32);
|
||||
(resource[4], resource[5]) = (len as u32, (len >> 32) as u32);
|
||||
}
|
||||
}
|
||||
(resource, desc)
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn create_sampler(_: This, desc: *const [u32; 13], handle: u64) {
|
||||
if let Some(desc) = words(desc) {
|
||||
@@ -2050,7 +2210,9 @@ mod tests {
|
||||
] {
|
||||
create(null, &resource, &desc, handle);
|
||||
let first = slot;
|
||||
assert_eq!(view(handle), Some(View::Placed(unordered, resource, desc)));
|
||||
// Kept as `normal_placed` makes it (a buffer view's first element folded into its address).
|
||||
let (r, d) = normal_placed(unordered, resource, desc);
|
||||
assert_eq!(view(handle), Some(View::Placed(unordered, r, d)));
|
||||
let mut noisy = desc;
|
||||
for w in unused {
|
||||
noisy[w] = 0xdead_beef;
|
||||
@@ -2202,6 +2364,45 @@ mod tests {
|
||||
/// The leak of run 65: a title that writes constant buffer views and
|
||||
/// views of placed memory at ever new addresses adds nothing to the
|
||||
/// table; one shape stands for all the placed views alike.
|
||||
#[test]
|
||||
fn buffer_views_differing_in_padding_are_one_shape_and_offsets_stay_apart() {
|
||||
if !inline() {
|
||||
return;
|
||||
}
|
||||
let null = std::ptr::null();
|
||||
let slots = [0u64; 4];
|
||||
let at = slots.as_ptr() as u64;
|
||||
// A raw buffer view of 17 dwords (format 0x27, raw flag), its
|
||||
// resource 0x1_0000 bytes wide; padding as a stack might leave it.
|
||||
let resource = |junk: u32, width: u32| -> [u32; 14] {
|
||||
[1, junk, 0, 0, width, 0, 1, 0x10001, 0, 1, 0, 1, 0, junk ^ 0x5a5a]
|
||||
};
|
||||
let view_desc = |junk: u32, first: u32, address: u64| -> [u32; 16] {
|
||||
let mut d = [0u32; 16];
|
||||
d[..10].copy_from_slice(&[0x27, 1, 0x1688, junk, first, 0, 17, 0, 1, junk.rotate_left(7)]);
|
||||
(d[10], d[11]) = (address as u32, (address >> 32) as u32);
|
||||
d[12] = 0x16;
|
||||
d
|
||||
};
|
||||
let base = 0xd_7771_0000u64;
|
||||
let kept: [u32; 14] = [1, 0, 0, 0, 0x1_0000, 0, 1, 0x10001, 0, 1, 0, 1, 0, 0];
|
||||
let mut seen = Vec::new();
|
||||
for n in 0..500u32 {
|
||||
// Other padding every time, seven offsets into one ring.
|
||||
create_placed_srv(null, &resource(n.wrapping_mul(0x9e37_79b9), 0x1_0000), &view_desc(n.wrapping_mul(0x85eb_ca6b), n % 7, base), at);
|
||||
let Some(View::Placed(false, r, d)) = view(at) else { panic!("a placed view") };
|
||||
// Padding cleared; the first element and the address kept as given
|
||||
// (folding them is VICTORY_PLACED_FOLD=1, off: it swapped clothing).
|
||||
assert_eq!(u64::from(d[10]) | u64::from(d[11]) << 32, base);
|
||||
assert_eq!((d[4], d[5], d[6], r), (n % 7, 0, 17, kept));
|
||||
assert_eq!((r[1], r[13], d[3], d[9]), (0, 0, 0, 0));
|
||||
seen.push((r, d[..10].to_vec()));
|
||||
}
|
||||
seen.sort();
|
||||
seen.dedup();
|
||||
assert_eq!(seen.len(), 7, "one shape for each offset, whatever the padding");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn views_at_new_addresses_add_no_entries() {
|
||||
if !inline() {
|
||||
@@ -2214,13 +2415,15 @@ mod tests {
|
||||
// 13 are the description's padding, which placed views keep as zero.
|
||||
let resource: [u32; 14] = std::array::from_fn(|k| if k == 1 || k == 13 { 0 } else { 0x5ee0_0000 + k as u32 });
|
||||
let mut desc: [u32; 16] = std::array::from_fn(|k| 0x7a70_0000 + k as u32);
|
||||
// (As views are kept: their padding cleared, `normal_placed`.)
|
||||
let kept = normal_placed(false, resource, desc).0;
|
||||
let mine = |v: &View| match v {
|
||||
View::Constant(address, _) => (0x6_0000_0000..0x6_1000_0000).contains(address),
|
||||
View::Placed(_, r, _) => *r == resource,
|
||||
View::Placed(_, r, _) => *r == kept,
|
||||
_ => false,
|
||||
};
|
||||
let entries = || VIEWS.read().unwrap().list.iter().filter(|(v, _)| mine(v)).count();
|
||||
let shapes = || VIEWS.read().unwrap().shapes.iter().filter(|s| s.1 == resource).count();
|
||||
let shapes = || VIEWS.read().unwrap().shapes.iter().filter(|s| s.1 == kept).count();
|
||||
for n in 0..20_000u64 {
|
||||
let address = 0x6_0000_0000 + n * 0x100;
|
||||
create_cbv(null, &[address as u32, (address >> 32) as u32, 512, 0], at);
|
||||
@@ -2228,18 +2431,21 @@ mod tests {
|
||||
let placed = 0xd_4940_0000 + n * 0x1_0000;
|
||||
(desc[10], desc[11]) = (placed as u32, (placed >> 32) as u32);
|
||||
create_placed_srv(null, &resource, &desc, at);
|
||||
assert_eq!(view(at), Some(View::Placed(false, resource, desc)));
|
||||
let (r, d) = normal_placed(false, resource, desc);
|
||||
assert_eq!(view(at), Some(View::Placed(false, r, d)));
|
||||
}
|
||||
assert_eq!(entries(), 0, "no table entries");
|
||||
assert_eq!(shapes(), 1, "one shape for 20,000 placed views");
|
||||
// The same shape, unordered: another shape.
|
||||
create_placed_uav(null, &resource, &desc, at);
|
||||
assert_eq!(view(at), Some(View::Placed(true, resource, desc)));
|
||||
let (r, d) = normal_placed(true, resource, desc);
|
||||
assert_eq!(view(at), Some(View::Placed(true, r, d)));
|
||||
assert_eq!(shapes(), 2);
|
||||
// Placed memory past 1 TiB (not title memory) is a table entry.
|
||||
(desc[10], desc[11]) = (0, 0x100);
|
||||
create_placed_srv(null, &resource, &desc, at);
|
||||
assert_eq!(view(at), Some(View::Placed(false, resource, desc)));
|
||||
let (r, d) = normal_placed(false, resource, desc);
|
||||
assert_eq!(view(at), Some(View::Placed(false, r, d)));
|
||||
assert_eq!(entries(), 1);
|
||||
// A record's words are the same for the same view (the host knows
|
||||
// a slot's view by them), and differ with the address.
|
||||
|
||||
@@ -1002,6 +1002,27 @@ const COPIED_GRACE: u64 = 4;
|
||||
/// In [`HostHeap::tabled`]: a draw read the slot in that frame.
|
||||
const TABLED_READ: u32 = 1 << 31;
|
||||
|
||||
/// Whether a slot's table stamp ([`HostHeap::tabled`]: the frame a draw's
|
||||
/// table last showed it, plus one, in 31 bits; 0 never) is later than frame
|
||||
/// `cutoff`, seen from frame `frame`. A stamp without [`TABLED_READ`] counts
|
||||
/// too (a table showed the slot; whether the shader read it then is not
|
||||
/// known): the answer errs toward "used". For slot eviction
|
||||
/// (`crate::resource::slot_evict`; memory stack by skornuta,
|
||||
/// skornuta/victory-memory-stack 57fb136, GPL-3.0).
|
||||
pub(crate) fn seen_since(stamp: u32, cutoff: u64, frame: u64) -> bool {
|
||||
let stamp = stamp & !TABLED_READ;
|
||||
if stamp == 0 {
|
||||
return false;
|
||||
}
|
||||
let mask = !TABLED_READ;
|
||||
let now = (frame as u32).wrapping_add(1) & mask;
|
||||
let cut = (cutoff as u32).wrapping_add(1) & mask;
|
||||
// Ages back from now, in the stamps' 31 bits.
|
||||
let age = now.wrapping_sub(stamp) & mask;
|
||||
let limit = now.wrapping_sub(cut) & mask;
|
||||
age < limit
|
||||
}
|
||||
|
||||
/// Since the start: writes of texture views into slots that count as a
|
||||
/// table's (due later), and slots that left the queue because a draw read
|
||||
/// them through a table; of the latter, those a draw read again in the
|
||||
@@ -3104,6 +3125,58 @@ impl HostHeap {
|
||||
flipped + late_flipped
|
||||
}
|
||||
|
||||
/// For `crate::resource::slot_evict` (`VICTORY_SLOT_EVICT=1`; memory
|
||||
/// stack by skornuta, skornuta/victory-memory-stack 57fb136, GPL-3.0):
|
||||
/// every slot (title or dynamic) showing one of the host textures `raws`
|
||||
/// (raw pointers), as (index, raw, whether letting it go is safe, whether
|
||||
/// a draw's table showed it after frame `cutoff`). Safe: a title slot a
|
||||
/// draw read through a table lately, which that draw makes again by
|
||||
/// itself (`HostHeap::mirror_after`). Slots only shaders pick by index
|
||||
/// (nothing would make them again) and dynamic ones (a list not yet
|
||||
/// reset) are not. The second answer is the slot's table stamp
|
||||
/// ([`seen_since`]): a texture a draw reads through a table every frame
|
||||
/// never asks for its host copy again, so its last use says nothing of
|
||||
/// that.
|
||||
pub(crate) fn slots_showing(
|
||||
&self,
|
||||
raws: &std::collections::HashSet<usize>,
|
||||
frame: u64,
|
||||
cutoff: u64,
|
||||
) -> Vec<(u32, usize, bool, bool)> {
|
||||
self.kept
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, slot)| {
|
||||
// (A lock to a slot: see `kept`.)
|
||||
let raw = {
|
||||
let r = slot.lock().unwrap_or_else(|e| e.into_inner());
|
||||
windows::core::Interface::as_raw(r.as_ref()?) as usize
|
||||
};
|
||||
raws.contains(&raw).then(|| {
|
||||
let i = i as u32;
|
||||
let ok = i < self.count && !self.sampler && self.tabled_lately(i, frame);
|
||||
(i, raw, ok, seen_since(self.tabled_stamp(i), cutoff, frame))
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Title slot `index` goes back to null at once, its host copy about to
|
||||
/// be let go by `crate::resource::slot_evict` (memory stack by skornuta,
|
||||
/// skornuta/victory-memory-stack 57fb136, GPL-3.0): as
|
||||
/// [`HostHeap::texture_slot_gone`] without its wait, for the copy is
|
||||
/// there and goes now. True if the slot was made.
|
||||
pub(crate) fn texture_slot_evicted(&self, index: u32) -> bool {
|
||||
let _made = self.made.lock(index);
|
||||
if self.made.get(index).is_none_or(|key| key == 0) {
|
||||
return false;
|
||||
}
|
||||
// (A wait of `texture_slot_gone` begun for this slot is over.)
|
||||
self.texture_slot_here(index);
|
||||
self.unmake(index);
|
||||
true
|
||||
}
|
||||
|
||||
/// The memory of the texture title slot `index` views is there (again):
|
||||
/// see [`HostHeap::texture_slot_gone`].
|
||||
pub(crate) fn texture_slot_here(&self, index: u32) {
|
||||
|
||||
@@ -3207,6 +3207,19 @@ impl State {
|
||||
)
|
||||
};
|
||||
|
||||
// A frame's runs of the pass (its own and the early ones, not those
|
||||
// before a bake) within `VICTORY_TEXSPK_PASS_MS` together
|
||||
// ([`texspk_pass_ms`]).
|
||||
let frame_pass = !required && !baking && sync.is_none();
|
||||
let span = match texspk_pass_ms() {
|
||||
Some(cap) if frame_pass => {
|
||||
if PASS_FRAME.swap(frame, Ordering::Relaxed) != frame {
|
||||
PASS_FRAME_NANOS.store(0, Ordering::Relaxed);
|
||||
}
|
||||
pass_span_left(span, cap, PASS_FRAME_NANOS.load(Ordering::Relaxed))
|
||||
}
|
||||
_ => span,
|
||||
};
|
||||
let began = std::time::Instant::now();
|
||||
HEAP_TEXTURE_REST[7].fetch_add(began.duration_since(entered).as_nanos() as u64, Ordering::Relaxed);
|
||||
// The frame's pass, the early one, or the one before a bake.
|
||||
@@ -3642,6 +3655,9 @@ impl State {
|
||||
let took = began.elapsed().as_nanos() as u64;
|
||||
HEAP_TEXTURE_NANOS[4].fetch_add(took, Ordering::Relaxed);
|
||||
HEAP_TEXTURE_PASSES[3 + kind].fetch_add(took, Ordering::Relaxed);
|
||||
if frame_pass && texspk_pass_ms().is_some() {
|
||||
PASS_FRAME_NANOS.fetch_add(took, Ordering::Relaxed);
|
||||
}
|
||||
served
|
||||
}
|
||||
|
||||
@@ -3791,7 +3807,10 @@ impl State {
|
||||
// depth read is the opaque one behind them; outdoors on water that is
|
||||
// the bottom, the reflected direction is wrong and the estimate dark
|
||||
// (play session 2026-11-27: dark patches on the water around a boat).
|
||||
let alpha_too = std::env::var("VICTORY_AMBIENT_SPECULAR_ALPHA").is_ok_and(|v| v.trim() == "1");
|
||||
// On again by default (2026-11-27): those dark patches were water tiles the tile
|
||||
// list had dropped (`VICTORY_LOOPS_WAVE`), not this; without it glass in a dark room
|
||||
// mirrors the bright sky (run fix2, spectacles 75 s into the opening). `=0`: off.
|
||||
let alpha_too = !std::env::var("VICTORY_AMBIENT_SPECULAR_ALPHA").is_ok_and(|v| v.trim() == "0");
|
||||
if role == Role::Miss
|
||||
&& !(layer == crate::ambient::MISS_OPAQUE || (alpha_too && layer == crate::ambient::MISS_ALPHA))
|
||||
{
|
||||
@@ -3938,6 +3957,56 @@ impl State {
|
||||
d.Width.abs_diff(w * 2) <= 1 && u64::from(d.Height).abs_diff(u64::from(h) * 2) <= 1
|
||||
})
|
||||
})
|
||||
})
|
||||
.or_else(|| {
|
||||
// In the opening's cutscenes the miss program's own places hold no depth of
|
||||
// the picture (its usual place a 1x1 texture; run loops1: no stand-in for 80 s,
|
||||
// reflections of the bright sky in dark rooms and on eyes). The picture's
|
||||
// depth is still in the frame's table, at a place this program does not read
|
||||
// (capture haze2: place 752 of table 0, the depth plane of the depth-stencil
|
||||
// target; place 448 its stencil plane). So: every place of that table, the
|
||||
// depth-stencil target's depth plane first, then any 32-bit depth of that size.
|
||||
use windows::Win32::Graphics::Dxgi::Common::{
|
||||
DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT_D32_FLOAT_S8X24_UINT, DXGI_FORMAT_R32_TYPELESS,
|
||||
DXGI_FORMAT_R32G8X24_TYPELESS,
|
||||
};
|
||||
let (w, h) = image.as_ref().map(|(d, _)| (d.Width, d.Height))?;
|
||||
let Some(Root::Table(table)) = self.roots_ref(true).first() else { return None };
|
||||
let start = match self.ambient_tables.iter().find(|m| m.0 == 0) {
|
||||
Some(m) => m.1,
|
||||
None => self.user_value(true, 0, RootType::Table, 0),
|
||||
};
|
||||
let mut plain = None;
|
||||
for offset in (0..1600u32).step_by(8) {
|
||||
let Some(view) = crate::descriptor::view(table + u64::from(offset) * 4) else { continue };
|
||||
if stencil_view(Some(view.clone())) {
|
||||
continue;
|
||||
}
|
||||
let view = crate::descriptor::host::placed_texture(&view).unwrap_or(view);
|
||||
let View::Shader(resource, _) = view else { continue };
|
||||
let Some(host) = crate::resource::host_resource(resource as This) else { continue };
|
||||
// SAFETY: a live resource.
|
||||
let d = unsafe { host.GetDesc() };
|
||||
let fits = d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D
|
||||
&& d.Width.abs_diff(w * 2) <= 1
|
||||
&& u64::from(d.Height).abs_diff(u64::from(h) * 2) <= 1;
|
||||
if !fits {
|
||||
continue;
|
||||
}
|
||||
let found = (d, heap.gpu_handle((start + offset * 4) / 32));
|
||||
match d.Format {
|
||||
DXGI_FORMAT_R32G8X24_TYPELESS | DXGI_FORMAT_D32_FLOAT_S8X24_UINT => {
|
||||
static WIDE: AtomicU64 = AtomicU64::new(0);
|
||||
if WIDE.fetch_add(1, Ordering::Relaxed) == 0 {
|
||||
tracing::info!(offset, "reflections stand-in: the picture's depth taken from the frame's table, a place the miss program does not read (counted once)");
|
||||
}
|
||||
return Some(found);
|
||||
}
|
||||
DXGI_FORMAT_R32_TYPELESS | DXGI_FORMAT_D32_FLOAT if plain.is_none() => plain = Some(found),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
plain
|
||||
}),
|
||||
Role::Radiance | Role::Air => image,
|
||||
};
|
||||
@@ -5848,6 +5917,45 @@ pub(crate) fn depth_bounds(list: &HostList, min: f32, max: f32) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame [`PASS_FRAME_NANOS`] counts for, and the nanoseconds its runs
|
||||
/// of the pass over textures picked by index took ([`texspk_pass_ms`]).
|
||||
static PASS_FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
|
||||
static PASS_FRAME_NANOS: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// The milliseconds a frame's runs of the pass over textures picked by index
|
||||
/// take together at most (`VICTORY_TEXSPK_PASS_MS=<n>`, 1 to 1000; unset or
|
||||
/// 0: each run within `VICTORY_TEXTURE_STAGE_MS` alone, as before). The
|
||||
/// slots left wait for the next frame's runs, as those past a run's time do
|
||||
/// now; runs before a bake keep their own budget.
|
||||
///
|
||||
/// The pass runs several times a frame (its own, the early one at the
|
||||
/// frame's first draw, 16 ms each in the launcher): walking through the
|
||||
/// world it took 2.2-2.7 s of each 5 seconds in the stretches with frames
|
||||
/// over 50 ms (3,000 uploads a second, every one through a staging buffer
|
||||
/// made for it and detiled whole), 0.6-0.9 s in calm ones. With 8 ms (RTX
|
||||
/// 4090, Ryzen 9 7950X3D, DLSS Quality, no frame cap, the walking route
|
||||
/// through the first boat mission) the mean went from 39.4 to 47.0 fps.
|
||||
/// What changes for the picture: a texture picked by index may show a frame
|
||||
/// or more later in such a burst (its slot shows what it showed until then,
|
||||
/// `VICTORY_SHOW_NEW_LATER`).
|
||||
fn texspk_pass_ms() -> Option<u64> {
|
||||
static MS: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
|
||||
*MS.get_or_init(|| {
|
||||
std::env::var("VICTORY_TEXSPK_PASS_MS")
|
||||
.ok()
|
||||
.and_then(|v| v.trim().parse::<u64>().ok())
|
||||
.filter(|&ms| ms > 0)
|
||||
.map(|ms| ms.min(1000))
|
||||
})
|
||||
}
|
||||
|
||||
/// A run's time within the frame's cap of `cap_ms` milliseconds when the
|
||||
/// frame's runs took `spent_ns` nanoseconds already: no more than `span`.
|
||||
fn pass_span_left(span: std::time::Duration, cap_ms: u64, spent_ns: u64) -> std::time::Duration {
|
||||
let cap = std::time::Duration::from_millis(cap_ms);
|
||||
span.min(cap.saturating_sub(std::time::Duration::from_nanos(spent_ns)))
|
||||
}
|
||||
|
||||
/// Per-frame texture staging byte budget scaled from the adapter's local VRAM
|
||||
/// budget (`None` keeps the 192 MiB 12 GiB baseline).
|
||||
fn staging_budget_per_frame(vram_budget: Option<u64>) -> u64 {
|
||||
@@ -5865,6 +5973,20 @@ fn staging_budget_per_frame(vram_budget: Option<u64>) -> u64 {
|
||||
mod tests {
|
||||
use super::staging_budget_per_frame;
|
||||
|
||||
#[test]
|
||||
fn a_frames_pass_runs_share_the_texspk_cap() {
|
||||
use super::pass_span_left;
|
||||
use std::time::Duration;
|
||||
let ms = Duration::from_millis;
|
||||
// The first run of a frame: the run's own time, or the cap if less.
|
||||
assert_eq!(pass_span_left(ms(16), 8, 0), ms(8));
|
||||
assert_eq!(pass_span_left(ms(4), 8, 0), ms(4));
|
||||
// Later runs: what the frame has left.
|
||||
assert_eq!(pass_span_left(ms(16), 8, 5_000_000), ms(3));
|
||||
// Spent: nothing (the run stops at its first slot).
|
||||
assert_eq!(pass_span_left(ms(16), 8, 9_000_000), Duration::ZERO);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staging_budget_scales_with_vram_budget() {
|
||||
const GIB: u64 = 1 << 30;
|
||||
|
||||
+456
-36
@@ -842,6 +842,27 @@ pub(crate) fn made_host() -> Option<&'static Host> {
|
||||
|
||||
/// The host GPU, created on first use; `None` without one (a run then
|
||||
/// behaves as before: nothing executes).
|
||||
/// The most of the card's memory taken as this process's budget, in bytes, whatever the system
|
||||
/// gives (`VICTORY_VRAM_BUDGET_MB=<n>`, 2048 at least; not given: the system's budget). The
|
||||
/// texture queue's line, the card copies of title buffers and what is kept for render targets
|
||||
/// are all sized from the budget, so a smaller one leaves the rest of the card to other
|
||||
/// programs, and keeps a card with little memory from being filled to the point where the
|
||||
/// system moves its memory into the PC's.
|
||||
fn vram_budget_cap() -> Option<u64> {
|
||||
static CAP: OnceLock<Option<u64>> = OnceLock::new();
|
||||
*CAP.get_or_init(|| {
|
||||
let mb = std::env::var("VICTORY_VRAM_BUDGET_MB").ok()?.trim().parse::<u64>().ok()?;
|
||||
let mb = mb.max(2048);
|
||||
tracing::info!(mb, "the card's memory: no more than this is taken as the budget (VICTORY_VRAM_BUDGET_MB)");
|
||||
Some(mb << 20)
|
||||
})
|
||||
}
|
||||
|
||||
/// The host if it has been made (never makes it).
|
||||
pub(crate) fn host_made() -> Option<&'static Host> {
|
||||
HOST.get().and_then(|h| h.as_ref())
|
||||
}
|
||||
|
||||
pub(crate) fn host() -> Option<&'static Host> {
|
||||
HOST.get_or_init(|| match create() {
|
||||
Ok(host) => Some(host),
|
||||
@@ -911,14 +932,31 @@ fn create() -> windows::core::Result<Host> {
|
||||
D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?;
|
||||
tracing::info!("host device on the software adapter (WARP)");
|
||||
} else {
|
||||
D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
|
||||
// The card with the most memory of its own (or the one
|
||||
// VICTORY_ADAPTER names), not Windows' first adapter, which is
|
||||
// often an integrated GPU.
|
||||
if let Some((adapter, name, own)) = victory_shader::emit::host::hardware_adapter()
|
||||
&& D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).is_ok()
|
||||
{
|
||||
tracing::info!(adapter = %name, own_memory_mb = own >> 20, "host device on the card with the most memory of its own (VICTORY_ADAPTER names another)");
|
||||
}
|
||||
if device.is_none() {
|
||||
D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
|
||||
}
|
||||
// Whether a GPU hang ends the run or freezes the PC (#1054).
|
||||
crate::tdr::log();
|
||||
}
|
||||
let device = device.ok_or_else(windows::core::Error::empty)?;
|
||||
require_direct_heaps(&device);
|
||||
// Before anything is made with it (`VICTORY_RECORD`).
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::replay::record::from_env(&device);
|
||||
// Before anything else has a static sampler (`pipeline::samplers`): the
|
||||
// first thing made with the device, in the run as in the tools. Made
|
||||
// after Streamline had the device (DLSS loaded, in the run only), the
|
||||
// run drew a white-painted material black with the pipelines `victory
|
||||
// warm` had compiled (launcher run rel4, 2026-11-27).
|
||||
crate::pipeline::samplers::prime(&device);
|
||||
// `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the
|
||||
// driver compiling shaders again on the "D3D Background Thread"s,
|
||||
// for minutes after pipelines were made or loaded) is switched off.
|
||||
@@ -1238,7 +1276,10 @@ const BATCHES: u32 = 8;
|
||||
|
||||
/// A host command list and its allocator, always used together.
|
||||
pub(crate) struct HostList {
|
||||
allocator: ID3D12CommandAllocator,
|
||||
/// Its command allocator and when it was made ([`now_ms`]): with
|
||||
/// [`allocator_trim`] a reset now and then takes a new one, and the old
|
||||
/// one, which keeps the most memory its list ever recorded into it, goes.
|
||||
allocator: Mutex<(ID3D12CommandAllocator, u64)>,
|
||||
pub(crate) list: ID3D12GraphicsCommandList,
|
||||
/// Work for submission time, in recorded order.
|
||||
deferred: Mutex<Deferred>,
|
||||
@@ -1255,9 +1296,11 @@ pub(crate) struct HostList {
|
||||
/// What the list does with depth textures that have a colour twin, by
|
||||
/// twin ([`TwinUse`]).
|
||||
twins: Mutex<std::collections::HashMap<usize, TwinUse>>,
|
||||
/// The list that runs those transitions just before this one, made
|
||||
/// when the list first has such transitions ([`lazy_prelude`]).
|
||||
prelude: OnceLock<Option<Prelude>>,
|
||||
/// The list that runs those transitions just before this one: taken
|
||||
/// from [`PRELUDES`] when a submission of the list first needs one, given
|
||||
/// back when the list is reset (every submission of it has run).
|
||||
/// With it, when its allocator was made ([`allocator_trim`]).
|
||||
prelude: Mutex<Option<(Prelude, u64)>>,
|
||||
/// The pipelines the list binds, for reports of slow submissions.
|
||||
pipelines: std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>,
|
||||
/// What its indirect executions ran, for the report of a removed device.
|
||||
@@ -1265,8 +1308,9 @@ pub(crate) struct HostList {
|
||||
indirects: indirects::Shared,
|
||||
/// The work its indirect executions may still do (`indirect`): a
|
||||
/// shader-writable word, zeroed when the list is submitted, and after
|
||||
/// it what the clamp notes about mesh records. In memory the CPU maps.
|
||||
budget: OnceLock<Option<(ID3D12Resource, usize)>>,
|
||||
/// it what the clamp notes about mesh records. In memory the CPU maps:
|
||||
/// a buffer of its own, or with [`budget_pack`] a slot of a shared one.
|
||||
budget: OnceLock<Option<Budget>>,
|
||||
/// The same words in the card's own memory ([`card_budget`]), which the
|
||||
/// clamp uses instead when there is one: zeroed in the list before its
|
||||
/// first clamp, its notes copied to `budget` when the list closes.
|
||||
@@ -1316,6 +1360,35 @@ pub(crate) struct HostList {
|
||||
/// A list's prelude: an allocator and a closed list.
|
||||
type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList);
|
||||
|
||||
/// Preludes no list holds. Each host list kept its own from its first
|
||||
/// submission that needed one until the list went: 1,140 alive in a
|
||||
/// 25-minute run (leak3), beside 1,526 lists, each pair of an allocator and
|
||||
/// a list costing the driver about 2.9 MB of the PC's memory at creation. A
|
||||
/// prelude is used only while its list's submission runs, so a list takes
|
||||
/// one then and gives it back at its reset; the lists in the air hold
|
||||
/// theirs. `VICTORY_PRELUDE_POOL=0`: each list keeps its own, as before.
|
||||
/// (Each with when its allocator was made, for [`allocator_trim`].)
|
||||
static PRELUDES: Mutex<Vec<(Prelude, u64)>> = Mutex::new(Vec::new());
|
||||
|
||||
impl Drop for HostList {
|
||||
fn drop(&mut self) {
|
||||
if self.prelude.get_mut().unwrap_or_else(|e| e.into_inner()).is_some() {
|
||||
PRELUDES_ALIVE.fetch_sub(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The most preludes [`PRELUDES`] keeps.
|
||||
const PRELUDES_KEPT: usize = 256;
|
||||
|
||||
fn prelude_pool() -> bool {
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_PRELUDE_POOL").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// Preludes alive (held by a list or kept), for the memory line.
|
||||
pub(crate) static PRELUDES_ALIVE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
/// Whether the new host list each of the title's lists gets when it is
|
||||
/// submitted is left open for the title's next reset ([`HostList::leave_open`];
|
||||
/// `VICTORY_FRESH_OPEN=0`: closed at once and reset again, as before). What
|
||||
@@ -1352,6 +1425,74 @@ fn lazy_prelude() -> bool {
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_PRELUDE").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
// Allocator trim: memory stack by skornuta (skornuta/victory-memory-stack 57fb136, GPL-3.0),
|
||||
// patches 13 and 17.
|
||||
|
||||
/// Whether host command allocators are taken anew now and then
|
||||
/// (`VICTORY_ALLOCATOR_TRIM=1`; off by default), and after how many
|
||||
/// seconds. A D3D12 command allocator never gives back the memory of the
|
||||
/// most its list ever recorded into it: a list that once took a loading
|
||||
/// frame's commands keeps that for the run, and upstream 1,600 of them
|
||||
/// (host lists and their preludes) held about 2.3 GB of private memory
|
||||
/// beside the card's own. With the switch a list's reset (and a prelude's,
|
||||
/// before it records again: the only moments its allocator holds nothing
|
||||
/// that runs) takes a new allocator when the one it has is
|
||||
/// `VICTORY_ALLOCATOR_TRIM_S` seconds old (30, 5 to 3600), and the old one
|
||||
/// goes behind the submissions still running ([`retire`]). Idle pooled
|
||||
/// lists not taken for that long go too (`crate::list`), and every ten
|
||||
/// seconds the spare scratch chunks nobody took all that while
|
||||
/// ([`Spare::trim`]). A title list executed again without a reset keeps
|
||||
/// its allocator: only resets swap.
|
||||
pub(crate) fn allocator_trim() -> Option<u64> {
|
||||
static S: OnceLock<Option<u64>> = OnceLock::new();
|
||||
*S.get_or_init(|| {
|
||||
std::env::var_os("VICTORY_ALLOCATOR_TRIM").is_some_and(|v| v == "1").then(|| {
|
||||
std::env::var("VICTORY_ALLOCATOR_TRIM_S")
|
||||
.ok()
|
||||
.and_then(|v| v.trim().parse().ok())
|
||||
.unwrap_or(30u64)
|
||||
.clamp(5, 3600)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Since the start: host list allocators and prelude allocators taken anew
|
||||
/// ([`allocator_trim`]).
|
||||
pub(crate) static ALLOCATOR_TRIMS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
|
||||
|
||||
/// With [`allocator_trim`]: `allocator`, made at `made`, is replaced by a
|
||||
/// new one if it is old enough, and the old one is retired. Whether it was
|
||||
/// (the new one needs no reset). To be called only where the allocator's
|
||||
/// last commands have run. Without the switch: nothing, false.
|
||||
fn allocator_refresh(allocator: &mut ID3D12CommandAllocator, made: &mut u64, count: &std::sync::atomic::AtomicU64) -> bool {
|
||||
let Some(secs) = allocator_trim() else {
|
||||
return false;
|
||||
};
|
||||
let now = now_ms();
|
||||
if now.saturating_sub(*made) < secs * 1000 {
|
||||
return false;
|
||||
}
|
||||
let Some(host) = host() else {
|
||||
return false;
|
||||
};
|
||||
// SAFETY: plain object creation.
|
||||
let fresh: windows::core::Result<ID3D12CommandAllocator> =
|
||||
unsafe { host.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) };
|
||||
match fresh {
|
||||
Ok(fresh) => {
|
||||
retire(std::mem::replace(allocator, fresh));
|
||||
*made = now;
|
||||
count.fetch_add(1, Ordering::Relaxed);
|
||||
true
|
||||
}
|
||||
Err(_) => {
|
||||
// No new one now: the old one serves on, and is asked again later.
|
||||
*made = now;
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Timestamps per list (diagnostics); commands past them are not timed.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
const STAMPS: u32 = 4096;
|
||||
@@ -1865,6 +2006,115 @@ fn card_budget() -> bool {
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_CARD_BUDGET").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
// Indirect budgets packed: memory stack by skornuta (skornuta/victory-memory-stack 57fb136,
|
||||
// GPL-3.0), patch 23.
|
||||
|
||||
/// Whether host lists' indirect-work budgets in memory the CPU maps share
|
||||
/// buffers (`VICTORY_BUDGET_PACK=1`; off by default). Those words are 256
|
||||
/// bytes, and each list made a shared buffer of its own for them: a
|
||||
/// committed buffer takes 64 KiB, and 602 of them held 37 MB in the first
|
||||
/// area upstream. With the switch a list's mapped budget is a 256-byte slot
|
||||
/// of a 64 KiB buffer of [`BUDGET_SLABS`], zeroed when taken, given back
|
||||
/// behind the submissions running when its list goes ([`retire`]).
|
||||
///
|
||||
/// Only the mapped words are packed. Shaders reach them through their
|
||||
/// address (a root view: no barrier names the buffer), and with the card's
|
||||
/// copy ([`card_budget`], on by default) the list only copies its notes
|
||||
/// into them at its end, with the buffer promoted from common as every
|
||||
/// buffer is, never moved between states by a barrier of ours. The card's
|
||||
/// copy is moved between states by the list's own barriers, so it stays a
|
||||
/// buffer of its own: other lists sharing it would see those barriers.
|
||||
fn budget_pack() -> bool {
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_BUDGET_PACK").is_some_and(|v| v == "1"))
|
||||
}
|
||||
|
||||
/// The bytes of one budget, and of one buffer of [`BUDGET_SLABS`].
|
||||
const BUDGET_SLOT: u64 = 256;
|
||||
const BUDGET_SLAB: u64 = 64 << 10;
|
||||
|
||||
/// The packed budgets' buffers (buffer, mapping), and the free slots
|
||||
/// (buffer by its place, offset), taken from the end.
|
||||
#[allow(clippy::type_complexity)]
|
||||
static BUDGET_SLABS: Mutex<(Vec<(ID3D12Resource, usize)>, Vec<(usize, u64)>)> = Mutex::new((Vec::new(), Vec::new()));
|
||||
|
||||
/// A host list's indirect-work budget in memory the CPU maps: a buffer of
|
||||
/// its own (as without [`budget_pack`]), or a slot of a shared one.
|
||||
enum Budget {
|
||||
Own(ID3D12Resource, usize),
|
||||
Packed(BudgetSlot),
|
||||
}
|
||||
|
||||
/// A slot of [`BUDGET_SLABS`]: its buffer (held, for the copy of the
|
||||
/// card's notes into it), where in it, and the slot's mapped address. Given
|
||||
/// back when dropped, behind the submissions running then.
|
||||
struct BudgetSlot {
|
||||
buffer: ID3D12Resource,
|
||||
slab: usize,
|
||||
offset: u64,
|
||||
data: usize,
|
||||
}
|
||||
|
||||
/// Gives a slot back when dropped ([`retire`] drops it once the
|
||||
/// submissions running at its list's end have finished).
|
||||
struct BudgetFree(usize, u64);
|
||||
|
||||
impl Drop for BudgetFree {
|
||||
fn drop(&mut self) {
|
||||
BUDGET_SLABS.lock().unwrap_or_else(|e| e.into_inner()).1.push((self.0, self.1));
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for BudgetSlot {
|
||||
fn drop(&mut self) {
|
||||
retire(BudgetFree(self.slab, self.offset));
|
||||
}
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
fn new() -> Option<Budget> {
|
||||
if !budget_pack() {
|
||||
let (b, d) = host()?.shared_buffer(BUDGET_SLOT)?;
|
||||
return Some(Budget::Own(b, d as usize));
|
||||
}
|
||||
let mut slabs = BUDGET_SLABS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if slabs.1.is_empty() {
|
||||
let (buffer, data) = host()?.shared_buffer(BUDGET_SLAB)?;
|
||||
name(&buffer, || "indirect budgets".into());
|
||||
let at = slabs.0.len();
|
||||
slabs.0.push((buffer, data as usize));
|
||||
// Taken from the end: the buffer's first slot first.
|
||||
slabs.1.extend((0..BUDGET_SLAB / BUDGET_SLOT).rev().map(|k| (at, k * BUDGET_SLOT)));
|
||||
}
|
||||
let (slab, offset) = slabs.1.pop()?;
|
||||
let (buffer, data) = &slabs.0[slab];
|
||||
let (buffer, data) = (buffer.clone(), data + offset as usize);
|
||||
drop(slabs);
|
||||
// A slot given back holds its last list's words: zeroed, as a new
|
||||
// buffer is.
|
||||
// SAFETY: the slot's 256 mapped bytes, ours alone now (its last
|
||||
// list's submissions have run).
|
||||
unsafe { std::ptr::write_bytes(data as *mut u8, 0, BUDGET_SLOT as usize) };
|
||||
Some(Budget::Packed(BudgetSlot { buffer, slab, offset, data }))
|
||||
}
|
||||
|
||||
/// The mapped address of the budget's first word.
|
||||
fn data(&self) -> usize {
|
||||
match self {
|
||||
Budget::Own(_, data) => *data,
|
||||
Budget::Packed(slot) => slot.data,
|
||||
}
|
||||
}
|
||||
|
||||
/// The buffer that holds the budget, and where in it.
|
||||
fn place(&self) -> (&ID3D12Resource, u64) {
|
||||
match self {
|
||||
Budget::Own(buffer, _) => (buffer, 0),
|
||||
Budget::Packed(slot) => (&slot.buffer, slot.offset),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether each list of a submission runs and is timed on its own, slow
|
||||
/// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics
|
||||
/// builds; the commands are noted with `VICTORY_D3D12_DRED` on).
|
||||
@@ -1998,20 +2248,42 @@ fn scratch_pool() -> bool {
|
||||
struct Spare<T> {
|
||||
kept: Vec<(T, u64)>,
|
||||
bytes: u64,
|
||||
/// The fewest bytes kept since the last [`Spare::trim`]: kept all that
|
||||
/// while and never asked for (memory stack by skornuta,
|
||||
/// skornuta/victory-memory-stack 57fb136, GPL-3.0).
|
||||
low: u64,
|
||||
}
|
||||
|
||||
impl<T> Spare<T> {
|
||||
const fn new() -> Self {
|
||||
Spare { kept: Vec::new(), bytes: 0 }
|
||||
Spare { kept: Vec::new(), bytes: 0, low: 0 }
|
||||
}
|
||||
|
||||
/// A kept thing of `size` bytes, the one given last.
|
||||
fn take(&mut self, size: u64) -> Option<T> {
|
||||
let at = self.kept.iter().rposition(|(_, s)| *s == size)?;
|
||||
self.bytes -= size;
|
||||
self.low = self.low.min(self.bytes);
|
||||
Some(self.kept.remove(at).0)
|
||||
}
|
||||
|
||||
/// With [`allocator_trim`]: takes out the oldest things kept, up to the
|
||||
/// fewest bytes kept since the last trim (none of those was asked for in
|
||||
/// all that time), to be freed. The first trim knows no window yet and
|
||||
/// takes nothing.
|
||||
fn trim(&mut self) -> Vec<(T, u64)> {
|
||||
let mut out = Vec::new();
|
||||
let mut left = self.low;
|
||||
while let Some(at) = self.kept.iter().position(|(_, s)| *s <= left) {
|
||||
let (thing, size) = self.kept.remove(at);
|
||||
left -= size;
|
||||
self.bytes -= size;
|
||||
out.push((thing, size));
|
||||
}
|
||||
self.low = self.bytes;
|
||||
out
|
||||
}
|
||||
|
||||
/// Keeps `thing` (`size` bytes) unless that takes the kept bytes past
|
||||
/// `most`: then it comes back.
|
||||
fn give(&mut self, thing: T, size: u64, most: u64) -> Option<T> {
|
||||
@@ -2081,10 +2353,33 @@ fn give_chunks(chunks: Vec<(Chunk, u64)>) {
|
||||
}
|
||||
}
|
||||
}
|
||||
// With `VICTORY_ALLOCATOR_TRIM=1`, every ten seconds: the chunks kept all
|
||||
// that while and never taken go too (memory stack by skornuta,
|
||||
// skornuta/victory-memory-stack 57fb136, GPL-3.0). No list holds them.
|
||||
if allocator_trim().is_some() {
|
||||
static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let now = now_ms();
|
||||
let last = LAST.load(Ordering::Relaxed);
|
||||
if now >= last + 10_000 && LAST.compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed).is_ok() {
|
||||
let trimmed = SPARE.lock().unwrap_or_else(|e| e.into_inner()).trim();
|
||||
for (chunk, size) in trimmed {
|
||||
ALIVE[3].fetch_sub(1, Ordering::Relaxed);
|
||||
ALIVE[4].fetch_sub(size, Ordering::Relaxed);
|
||||
ALIVE[1].fetch_sub(1, Ordering::Relaxed);
|
||||
ALIVE[2].fetch_sub(size, Ordering::Relaxed);
|
||||
SPARE_TRIMMED.fetch_add(size, Ordering::Relaxed);
|
||||
freed.push(chunk);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Freed outside the lock.
|
||||
drop(freed);
|
||||
}
|
||||
|
||||
/// Bytes of spare scratch chunks freed by the trim ([`allocator_trim`])
|
||||
/// since the start.
|
||||
pub(crate) static SPARE_TRIMMED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
/// Drops spare scratch chunks kept idle when host memory is pressured.
|
||||
fn trim_spare_chunks() {
|
||||
let freed: Vec<(Chunk, u64)> = {
|
||||
@@ -2093,6 +2388,7 @@ fn trim_spare_chunks() {
|
||||
return;
|
||||
}
|
||||
spare.bytes = 0;
|
||||
spare.low = 0;
|
||||
std::mem::take(&mut spare.kept)
|
||||
};
|
||||
let count = freed.len() as u64;
|
||||
@@ -4216,7 +4512,10 @@ impl Host {
|
||||
};
|
||||
LISTS[1].fetch_add(1, Ordering::Relaxed);
|
||||
match made {
|
||||
Ok(prelude) => Some(prelude),
|
||||
Ok(prelude) => {
|
||||
PRELUDES_ALIVE.fetch_add(1, Ordering::Relaxed);
|
||||
Some(prelude)
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "no host list for a prelude");
|
||||
None
|
||||
@@ -4236,9 +4535,9 @@ impl Host {
|
||||
&allocator,
|
||||
None,
|
||||
)?;
|
||||
let prelude = OnceLock::new();
|
||||
let prelude = Mutex::new(None);
|
||||
if !lazy_prelude() {
|
||||
let _ = prelude.set(self.make_prelude());
|
||||
*prelude.lock().unwrap_or_else(|e| e.into_inner()) = self.make_prelude().map(|p| (p, now_ms()));
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
let notes = std::sync::Arc::<Mutex<Vec<Note>>>::default();
|
||||
@@ -4264,7 +4563,7 @@ impl Host {
|
||||
);
|
||||
}
|
||||
Ok(HostList {
|
||||
allocator,
|
||||
allocator: Mutex::new((allocator, now_ms())),
|
||||
list,
|
||||
deferred: Mutex::default(),
|
||||
scratch: Mutex::default(),
|
||||
@@ -5769,6 +6068,10 @@ impl Host {
|
||||
}
|
||||
let behind = late && flying();
|
||||
stage.next("submit: gathering what to ask about");
|
||||
// The helpers awake from here to the end (`VICTORY_PASSES_HOT`,
|
||||
// `crate::shadow::passes_hot_us`): this submission's passes find
|
||||
// them so, the waking overlapping the asking below.
|
||||
let _hot = crate::shadow::hot();
|
||||
let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1;
|
||||
// The ranges shaders write are counted for it (with the relay).
|
||||
crate::shadow::preparing(this_submission);
|
||||
@@ -6579,6 +6882,25 @@ impl HostList {
|
||||
false
|
||||
}
|
||||
|
||||
/// Its prelude to [`PRELUDES`] (or gone, past [`PRELUDES_KEPT`]). Only
|
||||
/// after the list's last submission finished.
|
||||
pub(crate) fn give_prelude(&self) {
|
||||
if !prelude_pool() {
|
||||
return;
|
||||
}
|
||||
let Some(prelude) = self.prelude.lock().unwrap_or_else(|e| e.into_inner()).take() else {
|
||||
return;
|
||||
};
|
||||
let mut kept = PRELUDES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if kept.len() < PRELUDES_KEPT {
|
||||
kept.push(prelude);
|
||||
} else {
|
||||
drop(kept);
|
||||
drop(prelude);
|
||||
PRELUDES_ALIVE.fetch_sub(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Only after the list's last submission finished (every one is waited
|
||||
/// for).
|
||||
pub(crate) fn reset(&self) {
|
||||
@@ -6611,16 +6933,23 @@ impl HostList {
|
||||
give_chunks(std::mem::take(&mut scratch.chunks));
|
||||
}
|
||||
}
|
||||
// Nor runs its prelude: the next submission to need one takes it.
|
||||
self.give_prelude();
|
||||
// Open and empty since it was made or last reset: the allocator holds
|
||||
// nothing, the list nothing recorded (`HostList::leave_open`).
|
||||
if left_open {
|
||||
FRESH_OPEN[1].fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
// SAFETY: the list is not executing.
|
||||
// (`VICTORY_ALLOCATOR_TRIM=1`: an old allocator is taken anew
|
||||
// here, where it holds nothing that runs; memory stack by
|
||||
// skornuta, skornuta/victory-memory-stack 57fb136, GPL-3.0.)
|
||||
let mut allocator = self.allocator.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (allocator, made) = &mut *allocator;
|
||||
let fresh = allocator_refresh(allocator, made, &ALLOCATOR_TRIMS[0]);
|
||||
// SAFETY: the list is not executing; a fresh allocator is new
|
||||
// and empty.
|
||||
let reset = unsafe {
|
||||
self.allocator
|
||||
.Reset()
|
||||
.and_then(|()| self.list.Reset(&self.allocator, None))
|
||||
(if fresh { Ok(()) } else { allocator.Reset() }).and_then(|()| self.list.Reset(&*allocator, None))
|
||||
};
|
||||
if let Err(e) = reset {
|
||||
fail(format_args!("a host command list did not reset ({e})"));
|
||||
@@ -7059,17 +7388,23 @@ impl HostList {
|
||||
if barriers.is_empty() && syncs.is_empty() && uploads.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let Some((allocator, list)) = self
|
||||
.prelude
|
||||
.get_or_init(|| host().and_then(|h| h.make_prelude()))
|
||||
.as_ref()
|
||||
else {
|
||||
let mut held = self.prelude.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if held.is_none() {
|
||||
let kept = if prelude_pool() { PRELUDES.lock().unwrap_or_else(|e| e.into_inner()).pop() } else { None };
|
||||
*held = kept.or_else(|| host().and_then(|h| h.make_prelude()).map(|p| (p, now_ms())));
|
||||
}
|
||||
let Some(((allocator, list), made)) = held.as_mut() else {
|
||||
fail(format_args!("no host list for a state prelude"));
|
||||
};
|
||||
// (`VICTORY_ALLOCATOR_TRIM=1`: an old allocator is taken anew here,
|
||||
// before the prelude records again; memory stack by skornuta,
|
||||
// skornuta/victory-memory-stack 57fb136, GPL-3.0.)
|
||||
let fresh = allocator_refresh(allocator, made, &ALLOCATOR_TRIMS[1]);
|
||||
let (allocator, list) = (&*allocator, &*list);
|
||||
// SAFETY: the prelude is not executing (every submission is waited
|
||||
// for); the textures are live.
|
||||
// for); the textures are live. A fresh allocator is new and empty.
|
||||
let recorded = unsafe {
|
||||
allocator.Reset().and_then(|()| {
|
||||
(if fresh { Ok(()) } else { allocator.Reset() }).and_then(|()| {
|
||||
list.Reset(allocator, None)?;
|
||||
if !aliasing.is_empty() {
|
||||
list.ResourceBarrier(&aliasing);
|
||||
@@ -7380,18 +7715,16 @@ impl HostList {
|
||||
/// The host address of the list's indirect-work budget, zeroed at each
|
||||
/// submission of the list from the first use after a reset on.
|
||||
pub(crate) fn budget(&self) -> Option<u64> {
|
||||
let (buffer, data) = self
|
||||
.budget
|
||||
.get_or_init(|| {
|
||||
let (b, d) = host()?.shared_buffer(256)?;
|
||||
Some((b, d as usize))
|
||||
})
|
||||
.as_ref()?;
|
||||
// (`VICTORY_BUDGET_PACK=1`: a slot of a shared buffer; memory stack by skornuta,
|
||||
// skornuta/victory-memory-stack 57fb136, GPL-3.0.)
|
||||
let budget = self.budget.get_or_init(Budget::new).as_ref()?;
|
||||
let (buffer, offset) = budget.place();
|
||||
let data = budget.data();
|
||||
let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref();
|
||||
let mut deferred = self.deferred();
|
||||
if !deferred.budget_zeroed {
|
||||
deferred.budget_zeroed = true;
|
||||
let at = *data;
|
||||
let at = data;
|
||||
// SAFETY: the list's own mapped words, written before it runs.
|
||||
// The words after the budget hold what the clamp noted about the
|
||||
// list's last run (mesh dispatches: the largest group count
|
||||
@@ -7416,8 +7749,8 @@ impl HostList {
|
||||
self.zero_card_budget(card);
|
||||
}
|
||||
}
|
||||
// SAFETY: a live buffer.
|
||||
Some(unsafe { card.unwrap_or(buffer).GetGPUVirtualAddress() })
|
||||
// SAFETY: a live buffer; a packed budget lies `offset` into its own.
|
||||
Some(unsafe { card.map_or_else(|| buffer.GetGPUVirtualAddress() + offset, |card| card.GetGPUVirtualAddress()) })
|
||||
}
|
||||
|
||||
/// The budget's words in the card's own memory ([`card_budget`]), if
|
||||
@@ -7469,11 +7802,12 @@ impl HostList {
|
||||
if !self.deferred().budget_zeroed {
|
||||
return;
|
||||
}
|
||||
let (Some(Some(card)), Some(Some((mapped, _)))) =
|
||||
let (Some(Some(card)), Some(Some(budget))) =
|
||||
(self.card_budget.get(), self.budget.get())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let (mapped, offset) = budget.place();
|
||||
// SAFETY: an open list; both buffers are the list's own. The
|
||||
// mapped one is promoted from common to the copy destination.
|
||||
unsafe {
|
||||
@@ -7482,7 +7816,7 @@ impl HostList {
|
||||
D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
|
||||
D3D12_RESOURCE_STATE_COPY_SOURCE,
|
||||
)]);
|
||||
self.list.CopyBufferRegion(mapped, 4, card, 4, 16);
|
||||
self.list.CopyBufferRegion(mapped, offset + 4, card, 4, 16);
|
||||
self.list.ResourceBarrier(&[transition(
|
||||
card,
|
||||
D3D12_RESOURCE_STATE_COPY_SOURCE,
|
||||
@@ -10246,7 +10580,9 @@ impl Host {
|
||||
);
|
||||
self.log_video_memory("right after that change");
|
||||
}
|
||||
Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage])
|
||||
// (`VICTORY_VRAM_BUDGET_MB`: no more than that is taken as the budget)
|
||||
let budget = vram_budget_cap().map_or(own.Budget, |cap| own.Budget.min(cap));
|
||||
Some([budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage])
|
||||
}
|
||||
|
||||
/// Both of the system's memory groups for this process, in bytes: for
|
||||
@@ -10296,6 +10632,17 @@ impl Host {
|
||||
/// memory that shaders write, which upload memory cannot be. Starts in
|
||||
/// the common state (buffers move out of it implicitly).
|
||||
pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
|
||||
// (one made ahead, if it is of that size and one is in store: `crate::ahead`)
|
||||
if size == crate::ahead::SIZE
|
||||
&& let Some(made) = crate::ahead::shared()
|
||||
{
|
||||
return Some(made);
|
||||
}
|
||||
self.shared_buffer_now(size)
|
||||
}
|
||||
|
||||
/// [`Host::shared_buffer`], made now.
|
||||
pub(crate) fn shared_buffer_now(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
|
||||
MADE[2].fetch_add(1, Ordering::Relaxed);
|
||||
MADE[3].fetch_add(size, Ordering::Relaxed);
|
||||
let heap = D3D12_HEAP_PROPERTIES {
|
||||
@@ -10606,6 +10953,57 @@ pub(crate) fn transition(
|
||||
}
|
||||
}
|
||||
|
||||
/// Every translated shader indexes the descriptor heaps directly (Shader
|
||||
/// Model 6.6). Windows 10's own Direct3D 12 refuses those root signature
|
||||
/// flags ("Unsupported bit-flag set (root signature flags c00)"): no pipeline
|
||||
/// could be made, and the title failed a few seconds later with nothing said
|
||||
/// of why (RTX 2080 Ti and RTX 2070 reports, Windows 10, 2026-11-27). Said
|
||||
/// plainly here, and the process ends.
|
||||
fn require_direct_heaps(device: &ID3D12Device) {
|
||||
let mut model = D3D12_FEATURE_DATA_SHADER_MODEL { HighestShaderModel: D3D_SHADER_MODEL_6_6 };
|
||||
// SAFETY: the feature query writes the structure of the given size.
|
||||
let asked = unsafe {
|
||||
device.CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, (&raw mut model).cast(), size_of_val(&model) as u32)
|
||||
};
|
||||
let model_ok = asked.is_ok() && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0;
|
||||
let root_ok = root_with_direct_heaps(device);
|
||||
if model_ok && root_ok {
|
||||
return;
|
||||
}
|
||||
let text = format!(
|
||||
"Error: this PC's Direct3D 12 cannot run the translated shaders: they need Shader Model 6.6 with directly indexed descriptor heaps (highest shader model here {:#x}; such a root signature was {}). Windows 10's built-in Direct3D 12 does not have it, Windows 11 does; a current graphics driver is needed too.",
|
||||
model.HighestShaderModel.0,
|
||||
if root_ok { "made" } else { "refused" }
|
||||
);
|
||||
tracing::error!("{text}");
|
||||
println!("{text}");
|
||||
std::process::exit(3);
|
||||
}
|
||||
|
||||
fn root_with_direct_heaps(device: &ID3D12Device) -> bool {
|
||||
let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC {
|
||||
Version: D3D_ROOT_SIGNATURE_VERSION_1_1,
|
||||
Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 {
|
||||
Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 {
|
||||
Flags: D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED
|
||||
| D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED,
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
};
|
||||
// SAFETY: the description lives through the calls; the blob is read in
|
||||
// full before it is released.
|
||||
unsafe {
|
||||
let mut blob: Option<windows::Win32::Graphics::Direct3D::ID3DBlob> = None;
|
||||
if D3D12SerializeVersionedRootSignature(&desc, &mut blob, None).is_err() {
|
||||
return false;
|
||||
}
|
||||
let Some(blob) = blob else { return false };
|
||||
let bytes = std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize());
|
||||
device.CreateRootSignature::<ID3D12RootSignature>(0, bytes).is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
/// A window of the given client size, owned by its own message thread.
|
||||
fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
@@ -10728,6 +11126,28 @@ mod spare {
|
||||
assert_eq!(spare.bytes, 0);
|
||||
assert!(spare.kept.is_empty());
|
||||
}
|
||||
|
||||
/// A trim frees only what stayed kept through the whole window since the
|
||||
/// last one (memory stack by skornuta, skornuta/victory-memory-stack
|
||||
/// 57fb136, GPL-3.0).
|
||||
#[test]
|
||||
fn a_trim_frees_only_what_was_never_asked_for_since_the_last() {
|
||||
let mut spare: Spare<u32> = Spare::new();
|
||||
for (thing, size) in [(1, 4), (2, 4), (3, 4)] {
|
||||
assert_eq!(spare.give(thing, size, 100), None);
|
||||
}
|
||||
// The first trim knows no window yet: nothing goes.
|
||||
assert!(spare.trim().is_empty());
|
||||
assert_eq!(spare.bytes, 12);
|
||||
// One taken and given back: 8 bytes stayed kept all the while.
|
||||
assert_eq!(spare.take(4), Some(3));
|
||||
assert_eq!(spare.give(3, 4, 100), None);
|
||||
let gone = spare.trim();
|
||||
assert_eq!(gone.iter().map(|g| g.1).sum::<u64>(), 8);
|
||||
assert_eq!(gone.iter().map(|g| g.0).collect::<Vec<_>>(), vec![1, 2], "the oldest go");
|
||||
assert_eq!(spare.bytes, 4);
|
||||
assert_eq!(spare.take(4), Some(3));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -103,6 +103,111 @@ fn placed_order() -> bool {
|
||||
*ON.get_or_init(|| crate::switch::on("VICTORY_PLACED_ORDER"))
|
||||
}
|
||||
|
||||
/// Whether a fill behind a copy at its place in a list that reads only bytes the copy writes is
|
||||
/// done on the card out of the bytes the copy reads (`VICTORY_PLACED_READS=1`; off: the
|
||||
/// submission is refused for it, [`BEHIND_PLACED`], and waits until the flights have landed).
|
||||
///
|
||||
/// In the boat cutscene of the opening this was the one reason submissions were refused for:
|
||||
/// 0.2 to 0.5 of them a frame, each a wait of about 30 ms for the card, 9 to 14 ms of every
|
||||
/// frame of the submitting thread (runs v2q and cloud4, 2026-11-27, RTX 4070 SUPER: 37.9 ms a
|
||||
/// frame where the title asks for 33.3).
|
||||
fn placed_reads() -> bool {
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
*ON.get_or_init(|| crate::switch::on("VICTORY_PLACED_READS"))
|
||||
}
|
||||
|
||||
/// Fills of `does` that stand behind a copy at its place, read nothing but bytes it writes and
|
||||
/// would have to be done on the card (flights write what the copy reads or writes, or what
|
||||
/// the fill reads): they are made to read the same bytes where the copy takes them from.
|
||||
/// Returns how many.
|
||||
///
|
||||
/// A fill done on the card is done in front of all the lists, the copy at its place in one:
|
||||
/// the fill would read the destination as it was before the copy. What the copy puts there
|
||||
/// is its source as the submission finds it (so the CPU does it too, when the submission
|
||||
/// waits: [`place::Placed`] puts the source's bytes into title memory, the fill reads them
|
||||
/// there), and that the card holds in front of the lists.
|
||||
///
|
||||
/// Left as it is, and refused as before: a fill that reads more than the copy wrote, one
|
||||
/// whose memory cannot be given bytes on the card, and one with a buffer copy between the
|
||||
/// copy at its place and itself that writes what either of them reads.
|
||||
fn read_behind_placed(does: &mut [Does], written: &[(usize, usize)]) -> usize {
|
||||
let placed: Vec<(usize, (usize, usize), usize)> = does
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, d)| match *d {
|
||||
Does::Placed { dst, src, len } => Some((i, (dst, dst + len), src)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if placed.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
let mut moved = 0;
|
||||
for i in 0..does.len() {
|
||||
let Does::Fill { src, len, asked, to: true } = does[i] else {
|
||||
continue;
|
||||
};
|
||||
// From the fill back: each copy at its place whose bytes it reads (a copy may read
|
||||
// what one ahead of it wrote).
|
||||
let (mut at, mut before, mut waits) = (src, i, asked);
|
||||
let found = loop {
|
||||
let Some(&(p, to, from)) = placed.iter().rev().find(|&&(p, to, _)| p < before && meet(to, (at, at + len))) else {
|
||||
break before < i;
|
||||
};
|
||||
let copies = &does[p + 1..before];
|
||||
let between =
|
||||
|range: (usize, usize)| copies.iter().any(|d| matches!(*d, Does::Copy { dst, len: n, .. } if meet((dst, dst + n), range)));
|
||||
if at < to.0 || at + len > to.1 || between((at, at + len)) {
|
||||
break false;
|
||||
}
|
||||
waits |= touches(written, to.0, to.1) || touches(written, from, from + (to.1 - to.0));
|
||||
(at, before) = (from + (at - to.0), p);
|
||||
if between((at, at + len)) {
|
||||
break false;
|
||||
}
|
||||
};
|
||||
// (Nothing in the air writes any of it: title memory has the copy's bytes, the CPU's
|
||||
// fill reads them there.)
|
||||
if found && waits {
|
||||
does[i] = Does::Fill { src: at, len, asked: true, to: true };
|
||||
moved += 1;
|
||||
}
|
||||
}
|
||||
if moved > 0 {
|
||||
DONE[4].fetch_add(moved as u64, Ordering::Relaxed);
|
||||
}
|
||||
moved
|
||||
}
|
||||
|
||||
/// Why a submission whose fills read where a copy at its place does ([`read_behind_placed`]) is
|
||||
/// refused all the same.
|
||||
const PLACED_READER: &str = "a step other than a fill done on the card reads what a copy at its place writes";
|
||||
|
||||
/// Whether a step reads the destination of a copy at its place whose source or destination
|
||||
/// flights may write: title memory does not hold that copy's bytes until they have landed
|
||||
/// (`place::Placed`), so a texture, expanded vertices, a buffer copy or a fill that reads them
|
||||
/// there reads what was there before. Without [`read_behind_placed`] the fills behind the copy
|
||||
/// had the submission refused, and it waited; with them out of the way nothing did.
|
||||
/// Seen as one character's skin drawn as coloured noise for some seconds in the opening (runs
|
||||
/// d1 and rel2b of 2026-11-27, not in v5q and v6q with the same switches).
|
||||
fn placed_read_on_cpu(does: &[Does], written: &[(usize, usize)]) -> bool {
|
||||
does.iter().enumerate().any(|(p, d)| {
|
||||
let Does::Placed { dst, src, len } = *d else {
|
||||
return false;
|
||||
};
|
||||
if !touches(written, src, src + len) && !touches(written, dst, dst + len) {
|
||||
return false;
|
||||
}
|
||||
let to = (dst, dst + len);
|
||||
does.iter().enumerate().any(|(i, r)| match *r {
|
||||
Does::Read { from, to: end, .. } => meet((from, end), to),
|
||||
Does::Copy { src, len: n, .. } | Does::Fill { src, len: n, .. } => meet((src, src + n), to),
|
||||
Does::Placed { src, len: n, .. } => i != p && meet((src, src + n), to),
|
||||
_ => false,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Why [`plan`] refuses for [`place`].
|
||||
const BEHIND_PLACED: &str = "a copy at its place in a list writes what it reads, or reads or writes what it writes";
|
||||
|
||||
@@ -612,8 +717,9 @@ unsafe impl Send for Own {}
|
||||
static POOL: Mutex<Vec<Own>> = Mutex::new(Vec::new());
|
||||
|
||||
/// Since the last frame-rate line: fills and copies done on the card, their
|
||||
/// bytes, and submissions that waited instead, refused by a check.
|
||||
static DONE: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
|
||||
/// bytes, submissions that waited instead, refused by a check, and fills that read where a
|
||||
/// copy at its place ahead of them takes its bytes from ([`read_behind_placed`]).
|
||||
static DONE: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
|
||||
|
||||
/// What [`Host::card_steps`] took off a submission: the list that does it,
|
||||
/// for the submission to run first, and the steps the CPU leaves out (their
|
||||
@@ -678,6 +784,7 @@ impl Host {
|
||||
Ok(taken) => taken,
|
||||
Err(why) => {
|
||||
DONE[3].fetch_add(1, Ordering::Relaxed);
|
||||
count_refusal(why);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
refused(why);
|
||||
let _ = why;
|
||||
@@ -688,8 +795,12 @@ impl Host {
|
||||
|
||||
fn take_steps(&self, written: &[(usize, usize)], runs: &[&HostList]) -> Result<Option<Taken>, &'static str> {
|
||||
let mut spent = crate::timeline::span("steps on the card: chosen");
|
||||
let (does, steps) = does_of(written, runs);
|
||||
let chosen = plan(&does, stage(), placed_order(), &mut None)?;
|
||||
let (mut does, steps) = does_of(written, runs);
|
||||
let by_source = placed_reads() && read_behind_placed(&mut does, written) > 0;
|
||||
if by_source && placed_read_on_cpu(&does, written) {
|
||||
return Err(PLACED_READER);
|
||||
}
|
||||
let chosen = plan(&does, stage(), placed_order() || by_source, &mut None)?;
|
||||
if chosen.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -898,20 +1009,37 @@ fn noted(ops: &[Op]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why submissions were refused since the last line, and how often (few a frame: a list is enough).
|
||||
static REFUSALS: std::sync::Mutex<Vec<(&'static str, u32)>> = std::sync::Mutex::new(Vec::new());
|
||||
|
||||
fn count_refusal(why: &'static str) {
|
||||
let mut all = REFUSALS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
match all.iter_mut().find(|(w, _)| std::ptr::eq(*w, why)) {
|
||||
Some((_, n)) => *n += 1,
|
||||
None => all.push((why, 1)),
|
||||
}
|
||||
}
|
||||
|
||||
/// For the frame-rate line.
|
||||
pub(super) fn log(frames: f64) {
|
||||
if stage() == 0 {
|
||||
return;
|
||||
}
|
||||
let refusals = std::mem::take(&mut *REFUSALS.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
if !refusals.is_empty() {
|
||||
let all: Vec<String> = refusals.iter().map(|(why, n)| format!("{:.2} {why}", f64::from(*n) / frames)).collect();
|
||||
tracing::info!("submissions refused for the card's steps, per frame: {}", all.join("; "));
|
||||
}
|
||||
let d: Vec<f64> = DONE.iter().map(|d| d.swap(0, Ordering::Relaxed) as f64 / frames).collect();
|
||||
tracing::info!(
|
||||
"steps done on the card instead of waiting for flights, per frame (VICTORY_CARD_STEPS={}): {:.2} fills, {:.2} buffer \
|
||||
copies, {:.1} KB; {:.2} submissions refused and waited",
|
||||
copies, {:.1} KB; {:.2} submissions refused and waited; {:.2} fills read where a copy at its place takes its bytes \n from (VICTORY_PLACED_READS)",
|
||||
stage(),
|
||||
d[0],
|
||||
d[1],
|
||||
d[2] / 1024.0,
|
||||
d[3],
|
||||
d[4],
|
||||
);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
@@ -1116,6 +1244,44 @@ mod tests {
|
||||
|
||||
/// What cannot be done on the card refuses the lot, where it stands in
|
||||
/// the way.
|
||||
#[test]
|
||||
fn a_fill_behind_a_copy_at_its_place_reads_where_the_copy_does() {
|
||||
let fill = |src| Does::Fill { src, len: 0x100, asked: true, to: true };
|
||||
let mut does = vec![
|
||||
fill(0x1000),
|
||||
Does::Placed { dst: 0x1000, src: 0x9000, len: 0x200 },
|
||||
fill(0x1080),
|
||||
fill(0x1180),
|
||||
];
|
||||
// Ahead of the copy: as it was. Behind it and inside: from the source. Partly outside: as it was.
|
||||
assert_eq!(read_behind_placed(&mut does, &[(0x1000, 0x1200)]), 1);
|
||||
assert!(matches!(does[0], Does::Fill { src: 0x1000, .. }));
|
||||
assert!(matches!(does[2], Does::Fill { src: 0x9080, .. }));
|
||||
assert!(matches!(does[3], Does::Fill { src: 0x1180, .. }));
|
||||
// The one partly outside is still in the copy's way; without it nothing is.
|
||||
assert_eq!(plan(&does, 2, true, &mut None), Err(BEHIND_PLACED));
|
||||
does.pop();
|
||||
assert!(plan(&does, 2, true, &mut None).is_ok());
|
||||
// A buffer copy between them that writes what the fill reads: left alone.
|
||||
let mut does = vec![
|
||||
Does::Placed { dst: 0x1000, src: 0x9000, len: 0x200 },
|
||||
Does::Copy { dst: 0x1040, src: 0x5000, len: 0x80, asked: false },
|
||||
fill(0x1080),
|
||||
];
|
||||
assert_eq!(read_behind_placed(&mut does, &[(0x1000, 0x1200)]), 0);
|
||||
// Nothing in the air writes any of it: the CPU's fill is right.
|
||||
let mut does = vec![Does::Placed { dst: 0x1000, src: 0x9000, len: 0x200 }, Does::Fill { src: 0x1080, len: 0x100, asked: false, to: true }];
|
||||
assert_eq!(read_behind_placed(&mut does, &[(0x4000, 0x5000)]), 0);
|
||||
// Two copies in a row: the bytes are followed back through both.
|
||||
let mut does = vec![
|
||||
Does::Placed { dst: 0x9000, src: 0x7000, len: 0x200 },
|
||||
Does::Placed { dst: 0x1000, src: 0x9000, len: 0x200 },
|
||||
fill(0x1080),
|
||||
];
|
||||
assert_eq!(read_behind_placed(&mut does, &[(0x1000, 0x1200)]), 1);
|
||||
assert!(matches!(does[2], Does::Fill { src: 0x7080, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steps_in_the_way_are_refused() {
|
||||
let taken = copy(1000, 5000, 100, true);
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
//! shown the title sees no keyboard (`crate::SETTINGS_MENU_OPEN`, read by the
|
||||
//! input module); a pad still works.
|
||||
//!
|
||||
//! The settings are read once at start, so a change is saved to the file
|
||||
//! The settings are read once at start, so a change is saved at once (as well as by the save
|
||||
//! lines) to the file
|
||||
//! `VICTORY_MENU_FILE` names (`scripts\play-foxhound.ps1` sets it to
|
||||
//! `victory-settings.txt` in the repository's folder and applies it at every
|
||||
//! start) and takes effect at the next start; "SAVE AND RESTART" starts the
|
||||
@@ -100,7 +101,9 @@ const ITEMS: &[Item] = &[
|
||||
Item { var: "VICTORY_AMBIENT_SPECULAR", label: "REFLECTION ESTIMATE", values: ON_UNSET, live: false },
|
||||
Item { var: "VICTORY_AMBIENT_AIR", label: "FOG CAP", values: &[("1.5", "1.5"), ("1", "1"), ("2", "2"), ("", "NONE")], live: false },
|
||||
Item { var: "VICTORY_BVH_BUILDER", label: "RAY TRACING (SLOW, BROKEN)", values: UNSET_ON, live: false },
|
||||
Item { var: "VICTORY_WATER_LIGHT", label: "WATER LIGHT", values: &[("", "OFF (NO DARK BLOCKS)"), ("1", "ON (GREEN, DARK BLOCKS)")], live: false },
|
||||
// On unless "0": a file saved by an earlier version holds an empty value (its OFF) or "1",
|
||||
// and both start it on, so nobody keeps it off from before by accident (2026-11-27).
|
||||
Item { var: "VICTORY_WATER_LIGHT", label: "WATER LIGHT", values: &[("", "ON"), ("0", "OFF")], live: false },
|
||||
Item { var: "VICTORY_LEAVE_OUT", label: "HEAT HAZE AND DECAL DEFRAG", values: &[("02384a60fda6f2d0,731a39171b568298", "LEFT OUT"), ("", "RUN (SLOWER, SMEARS)")], live: false },
|
||||
Item { var: "VICTORY_EARLY_DEPTH", label: "EARLY DEPTH TEST", values: ON_UNSET, live: false },
|
||||
Item { var: "VICTORY_WC_NO_BACK", label: "SKIP BIG COPY-BACKS", values: ON_UNSET, live: false },
|
||||
@@ -120,6 +123,16 @@ fn get(var: &str) -> String {
|
||||
std::env::var(var).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Where the menu saves: the file `VICTORY_MENU_FILE` names (`victory play` sets it); else,
|
||||
/// however the game was started (a script, another launcher), the one `victory play` reads at
|
||||
/// every start, `victory-settings.txt` in `VICTORY_HOME` or `%LOCALAPPDATA%\victory`.
|
||||
fn settings_file() -> Option<std::path::PathBuf> {
|
||||
let set = |name: &str| std::env::var_os(name).filter(|v| !v.is_empty()).map(std::path::PathBuf::from);
|
||||
set("VICTORY_MENU_FILE")
|
||||
.or_else(|| set("VICTORY_HOME").map(|home| home.join("victory-settings.txt")))
|
||||
.or_else(|| set("LOCALAPPDATA").map(|base| base.join("victory").join("victory-settings.txt")))
|
||||
}
|
||||
|
||||
/// The first start of a new victory.exe: the seconds it plays before it starts
|
||||
/// again by itself (`VICTORY_WARMUP_RESTART`, set by the launcher while the exe
|
||||
/// has no mark under `%LOCALAPPDATA%\victory\warmed`). On the RTX 5070, every
|
||||
@@ -127,6 +140,11 @@ fn get(var: &str) -> String {
|
||||
/// it ran, and every later run was normal (27-29 fps), even after a first run of
|
||||
/// 45 seconds; a copy of an exe already run was fast at once (2026-11-27). Likely
|
||||
/// the driver's cache of the program; not ours to fix, so it is run through once.
|
||||
/// Draws in a frame from which the warm-up's time counts: the game's scenes
|
||||
/// (loading into the world: about 300, in the world: thousands), not its
|
||||
/// title screen and menus (about 10).
|
||||
const SCENE_DRAWS: u64 = 100;
|
||||
|
||||
pub(crate) fn warmup_seconds() -> Option<u64> {
|
||||
get("VICTORY_WARMUP_RESTART").parse().ok().filter(|s| *s > 0)
|
||||
}
|
||||
@@ -135,7 +153,8 @@ pub(crate) fn warmup_seconds() -> Option<u64> {
|
||||
pub(crate) fn warmup_notice(seconds: u64) -> Vec<String> {
|
||||
vec![
|
||||
"FIRST START OF THIS VERSION: A ONE-TIME WARM-UP".to_owned(),
|
||||
format!("THE GAME RESTARTS BY ITSELF IN ABOUT {seconds} SECONDS"),
|
||||
format!("THE GAME RESTARTS BY ITSELF {seconds} SECONDS AFTER IT"),
|
||||
"LOADS INTO THE GAME (PRESS A AT THE TITLE SCREEN)".to_owned(),
|
||||
"THIS HAPPENS ONCE PER NEW VERSION, AND IS NEEDED:".to_owned(),
|
||||
"WITHOUT IT THE FIRST RUN STAYS AT ABOUT 14 FPS".to_owned(),
|
||||
String::new(),
|
||||
@@ -455,10 +474,13 @@ impl Menu {
|
||||
|
||||
/// Writes the changed values over those in the settings file.
|
||||
fn save(&mut self) -> bool {
|
||||
let Some(path) = std::env::var_os("VICTORY_MENU_FILE") else {
|
||||
self.note = "NO SETTINGS FILE: START WITH VICTORY PLAY".to_owned();
|
||||
let Some(path) = settings_file() else {
|
||||
self.note = "NO FOLDER FOR THE SETTINGS FILE".to_owned();
|
||||
return false;
|
||||
};
|
||||
if let Some(dir) = path.parent() {
|
||||
let _ = std::fs::create_dir_all(dir);
|
||||
}
|
||||
let mut kept: Vec<(String, String)> = std::fs::read_to_string(&path)
|
||||
.unwrap_or_default()
|
||||
.lines()
|
||||
@@ -478,9 +500,16 @@ impl Menu {
|
||||
}
|
||||
match std::fs::write(&path, text) {
|
||||
Ok(()) => {
|
||||
tracing::info!(path = %std::path::Path::new(&path).display(), "settings menu: saved");
|
||||
tracing::info!(path = %path.display(), "settings menu: saved");
|
||||
self.started = self.values.clone();
|
||||
self.note = "SAVED. APPLIES AT THE NEXT START".to_owned();
|
||||
self.note = if std::env::var_os("VICTORY_MENU_FILE").is_some() {
|
||||
"SAVED. APPLIES AT THE NEXT START"
|
||||
} else {
|
||||
// Started some other way (a script, another launcher): the file `victory play`
|
||||
// reads at every start, which this start did not.
|
||||
"SAVED. APPLIES WHEN VICTORY.EXE STARTS THE GAME"
|
||||
}
|
||||
.to_owned();
|
||||
true
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -527,15 +556,26 @@ impl Menu {
|
||||
}
|
||||
}
|
||||
|
||||
/// The warm-up start ([`warmup_seconds`]): once its time is up, this exe is
|
||||
/// marked as warmed up (`VICTORY_WARMUP_MARK`) and the game starts again.
|
||||
/// The warm-up start ([`warmup_seconds`]): once the game has drawn whole
|
||||
/// scenes for that long, this exe is marked as warmed up
|
||||
/// (`VICTORY_WARMUP_MARK`) and the game starts again. The time counts
|
||||
/// from the first frame of [`SCENE_DRAWS`] draws or more, not from the
|
||||
/// start: a player who waited on the title screen ("press A", about ten
|
||||
/// draws a frame) was restarted after 20 seconds and still had the 14 fps
|
||||
/// first run after it (2026-11-27).
|
||||
fn warmup(&mut self) {
|
||||
static BEGAN: OnceLock<std::time::Instant> = OnceLock::new();
|
||||
static DONE: AtomicBool = AtomicBool::new(false);
|
||||
static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let Some(seconds) = warmup_seconds() else { return };
|
||||
if DONE.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let ever = crate::list::draws_ever();
|
||||
let this_frame = ever.saturating_sub(LAST.swap(ever, Ordering::Relaxed));
|
||||
if BEGAN.get().is_none() && this_frame < SCENE_DRAWS {
|
||||
return;
|
||||
}
|
||||
if BEGAN.get_or_init(std::time::Instant::now).elapsed() < Duration::from_secs(seconds) {
|
||||
return;
|
||||
}
|
||||
@@ -553,12 +593,21 @@ impl Menu {
|
||||
|
||||
/// Removes the settings file: the launcher's own settings at the next start.
|
||||
fn reset(&mut self) {
|
||||
if let Some(path) = std::env::var_os("VICTORY_MENU_FILE") {
|
||||
if let Some(path) = settings_file() {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
self.note = "RESET. PLAY DEFAULTS AT THE NEXT START".to_owned();
|
||||
}
|
||||
|
||||
/// Changes a setting and saves it at once: many players changed settings and closed the
|
||||
/// menu without the save lines, and lost them. The save lines stay (and restart, preload).
|
||||
fn change_and_save(&mut self, i: usize, step: isize) {
|
||||
self.change(i, step);
|
||||
if self.save() && live(&ITEMS[i]) {
|
||||
self.note = "SAVED. ON NOW".to_owned();
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame was presented: the keys pressed since the last one.
|
||||
pub(super) fn frame(&mut self) {
|
||||
self.warmup();
|
||||
@@ -586,9 +635,9 @@ impl Menu {
|
||||
match vk {
|
||||
VK_UP => self.at = (self.at + total - 1) % total,
|
||||
VK_DOWN => self.at = (self.at + 1) % total,
|
||||
VK_LEFT if self.at < ITEMS.len() => self.change(self.at, -1),
|
||||
VK_RIGHT if self.at < ITEMS.len() => self.change(self.at, 1),
|
||||
VK_RETURN if self.at < ITEMS.len() => self.change(self.at, 1),
|
||||
VK_LEFT if self.at < ITEMS.len() => self.change_and_save(self.at, -1),
|
||||
VK_RIGHT if self.at < ITEMS.len() => self.change_and_save(self.at, 1),
|
||||
VK_RETURN if self.at < ITEMS.len() => self.change_and_save(self.at, 1),
|
||||
VK_RETURN => match self.at - ITEMS.len() {
|
||||
0 => {
|
||||
if self.save() {
|
||||
@@ -686,6 +735,30 @@ impl Menu {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_change_is_saved_at_once_however_the_game_was_started() {
|
||||
let home = std::env::temp_dir().join(format!("victory-menu-test-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
// SAFETY: no other test in this crate reads these two.
|
||||
unsafe {
|
||||
std::env::remove_var("VICTORY_MENU_FILE");
|
||||
std::env::set_var("VICTORY_HOME", &home);
|
||||
}
|
||||
let mut menu = Menu { values: ITEMS.iter().map(|_| String::new()).collect(), started: Vec::new(), at: 0, note: String::new(), changed: false, painted: None, buffers: None, failed: false };
|
||||
menu.started = menu.values.clone();
|
||||
let dlss = ITEMS.iter().position(|i| i.var == "VICTORY_MENU_DLSS").expect("in the menu");
|
||||
menu.change_and_save(dlss, 1);
|
||||
let text = std::fs::read_to_string(home.join("victory-settings.txt")).expect("saved without a save line");
|
||||
assert!(text.contains("VICTORY_MENU_DLSS=quality"), "{text}");
|
||||
assert_eq!(menu.note, "SAVED. APPLIES WHEN VICTORY.EXE STARTS THE GAME");
|
||||
// Every note fits the box and has its letters.
|
||||
for note in [menu.note.as_str(), "SAVED. ON NOW", "SAVED. APPLIES AT THE NEXT START", "NO FOLDER FOR THE SETTINGS FILE"] {
|
||||
assert!(note.len() <= COLUMNS as usize, "{note}");
|
||||
assert!(note.bytes().all(|c| glyph(c) != glyph(b'#')), "{note}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_line_fits_and_every_character_has_a_picture() {
|
||||
let mut menu = Menu { values: ITEMS.iter().map(|_| String::new()).collect(), started: Vec::new(), at: 0, note: String::new(), changed: false, painted: None, buffers: None, failed: false };
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
//! `present` (swap chain).
|
||||
|
||||
#[cfg(windows)]
|
||||
mod ahead;
|
||||
mod ambient;
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
mod capture;
|
||||
|
||||
@@ -280,10 +280,10 @@ impl Detached {
|
||||
}
|
||||
}
|
||||
|
||||
/// A host list that has run and waits to be used again, and the bytes of
|
||||
/// upload memory it keeps.
|
||||
/// A host list that has run and waits to be used again, the bytes of
|
||||
/// upload memory it keeps, and when it was put there ([`idle_trim`]).
|
||||
#[cfg(windows)]
|
||||
struct Idle(crate::host::HostList, u64);
|
||||
struct Idle(crate::host::HostList, u64, u64);
|
||||
|
||||
// SAFETY: D3D12 objects are free-threaded, and an idle list is touched by
|
||||
// nobody until it is taken out again.
|
||||
@@ -309,6 +309,37 @@ static IDLE: std::sync::Mutex<(Vec<Idle>, u64)> = std::sync::Mutex::new((Vec::ne
|
||||
#[cfg(windows)]
|
||||
const IDLE_MOST: (usize, u64) = (512, 256 << 20);
|
||||
|
||||
// Idle-list trim: memory stack by skornuta (skornuta/victory-memory-stack 57fb136, GPL-3.0),
|
||||
// patch 13 (and the idle trim of its base).
|
||||
|
||||
/// Idle lists destroyed by [`idle_trim`] since the start.
|
||||
#[cfg(windows)]
|
||||
pub(crate) static TRIMMED_LISTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
/// After how many seconds an idle list nobody took is destroyed, with its
|
||||
/// command allocators: `VICTORY_LIST_POOL_IDLE_S=<seconds>`, or with
|
||||
/// `VICTORY_ALLOCATOR_TRIM=1` its time (`crate::host::allocator_trim`);
|
||||
/// neither: never, as before. The pool is last in, first out, so the
|
||||
/// oldest entries are the surplus of a spike.
|
||||
#[cfg(windows)]
|
||||
fn idle_trim() -> Option<u64> {
|
||||
static S: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
|
||||
*S.get_or_init(|| {
|
||||
std::env::var("VICTORY_LIST_POOL_IDLE_S")
|
||||
.ok()
|
||||
.and_then(|v| v.trim().parse().ok())
|
||||
.filter(|&s| s > 0)
|
||||
.or_else(crate::host::allocator_trim)
|
||||
})
|
||||
}
|
||||
|
||||
/// How many of the first of `pushed_at` (oldest first) are older than
|
||||
/// `max_age` at `now`.
|
||||
#[cfg(windows)]
|
||||
fn stale(pushed_at: impl Iterator<Item = u64>, now: u64, max_age: u64) -> usize {
|
||||
pushed_at.take_while(|&t| now.saturating_sub(t) > max_age).count()
|
||||
}
|
||||
|
||||
/// Whether host lists that have run are used again (on by default;
|
||||
/// `VICTORY_LIST_POOL=0`: each is made new and thrown away, as before).
|
||||
#[cfg(windows)]
|
||||
@@ -324,13 +355,13 @@ fn fresh_list() -> Option<crate::host::HostList> {
|
||||
let idle = {
|
||||
let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let taken = idle.0.pop();
|
||||
if let Some(Idle(_, bytes)) = &taken {
|
||||
if let Some(Idle(_, bytes, _)) = &taken {
|
||||
idle.1 -= bytes;
|
||||
}
|
||||
taken
|
||||
};
|
||||
match idle {
|
||||
Some(Idle(list, _)) => Some(list),
|
||||
Some(Idle(list, _, _)) => Some(list),
|
||||
None => crate::host::host().and_then(|h| h.new_list().ok()),
|
||||
}
|
||||
}
|
||||
@@ -348,7 +379,12 @@ pub(crate) fn recycle(lists: Vec<Detached>, ran: &[usize]) {
|
||||
// The descriptor slots and the upload memory its commands named.
|
||||
drop(_state);
|
||||
drop(_uploads);
|
||||
if !ran.contains(&i) || IDLE.lock().unwrap_or_else(|e| e.into_inner()).0.len() >= IDLE_MOST.0 {
|
||||
if !ran.contains(&i) {
|
||||
continue;
|
||||
}
|
||||
if IDLE.lock().unwrap_or_else(|e| e.into_inner()).0.len() >= IDLE_MOST.0 {
|
||||
// Its submission has run: its prelude serves another list.
|
||||
host.give_prelude();
|
||||
continue;
|
||||
}
|
||||
// As the title's reset does: what the list kept for its commands
|
||||
@@ -357,8 +393,21 @@ pub(crate) fn recycle(lists: Vec<Detached>, ran: &[usize]) {
|
||||
let bytes = host.scratch_kept();
|
||||
let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if idle.0.len() < IDLE_MOST.0 && idle.1 + bytes <= IDLE_MOST.1 {
|
||||
idle.0.push(Idle(host, bytes));
|
||||
let now = crate::host::now_ms();
|
||||
idle.0.push(Idle(host, bytes, now));
|
||||
idle.1 += bytes;
|
||||
// With `VICTORY_ALLOCATOR_TRIM=1` (memory stack by skornuta,
|
||||
// skornuta/victory-memory-stack 57fb136, GPL-3.0): lists the
|
||||
// frames did not need for that long are destroyed, with their
|
||||
// allocators. Their submissions have run, as every idle list's.
|
||||
if let Some(secs) = idle_trim() {
|
||||
let n = stale(idle.0.iter().map(|i| i.2), now, secs * 1000);
|
||||
let gone: Vec<Idle> = idle.0.drain(..n).collect();
|
||||
idle.1 -= gone.iter().map(|i| i.1).sum::<u64>();
|
||||
TRIMMED_LISTS.fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed);
|
||||
drop(idle);
|
||||
drop(gone);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1932,6 +1981,15 @@ mod state {
|
||||
|
||||
fn count_draw() {
|
||||
DRAWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
DRAWS_EVER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Every draw recorded since the start (the warm-up start watches it).
|
||||
static DRAWS_EVER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
/// Draws recorded since the start, any kind ([`take_counts`] empties its own count).
|
||||
pub(crate) fn draws_ever() -> u64 {
|
||||
DRAWS_EVER.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Draws of the kinds the host does not run yet (indirect, mesh), and
|
||||
@@ -2452,6 +2510,18 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::object::slot;
|
||||
|
||||
/// Only the oldest idle lists, those past the age, are stale (memory
|
||||
/// stack by skornuta, skornuta/victory-memory-stack 57fb136, GPL-3.0).
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn only_the_oldest_idle_lists_are_stale() {
|
||||
assert_eq!(stale([10, 20, 900, 950].into_iter(), 1000, 100), 2);
|
||||
assert_eq!(stale([950u64].into_iter(), 1000, 100), 0);
|
||||
assert_eq!(stale(std::iter::empty(), 1000, 100), 0);
|
||||
// A clock that reads earlier than a push does not make it stale.
|
||||
assert_eq!(stale([2000u64].into_iter(), 1000, 100), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_inline_command_falls_back_to_the_table() {
|
||||
let null = std::ptr::null();
|
||||
|
||||
@@ -770,6 +770,8 @@ pub mod known;
|
||||
mod library;
|
||||
#[cfg(windows)]
|
||||
mod make;
|
||||
#[cfg(windows)]
|
||||
pub(crate) mod samplers;
|
||||
|
||||
/// Lets the pipeline library's mapped file go from memory when no pipeline
|
||||
/// has loaded for a while (`library::trim`); called by the host's sweep.
|
||||
|
||||
@@ -573,6 +573,7 @@ impl HostPipeline {
|
||||
});
|
||||
}
|
||||
}
|
||||
super::samplers::know(&t.static_samplers);
|
||||
for (n, s) in t.static_samplers.iter().enumerate() {
|
||||
samplers.push(D3D12_STATIC_SAMPLER_DESC {
|
||||
Filter: D3D12_FILTER(s.filter_for_host(aniso_point_mip_supported) as i32),
|
||||
|
||||
@@ -205,6 +205,7 @@ pub fn fingerprint() -> String {
|
||||
if let Some(host) = crate::host::host() {
|
||||
h.update(&host.driver().to_le_bytes());
|
||||
}
|
||||
h.update(&super::samplers::order());
|
||||
h.finalize().to_hex()[..16].to_owned()
|
||||
}
|
||||
|
||||
|
||||
@@ -81,13 +81,15 @@ fn leave_out() -> &'static [String] {
|
||||
/// boats, along shores and under bridges, and take about 15 ms of the card a frame (RTX 5070,
|
||||
/// runs r_water1 and r_water3 of 2026-11-26: 25 fps with them, 30 without, the blocks gone;
|
||||
/// fxceless/victory-fork's README of 2026-11-27 names the same two programs and form). Left
|
||||
/// out there, the water has no light of its own depth (darker, bluer) and no blocks;
|
||||
/// `VICTORY_WATER_LIGHT=1` runs them as before.
|
||||
/// out there, the water has no light of its own depth (darker, bluer) and no blocks.
|
||||
/// foxhound 0.2.0-pre.3 fixed the blocks (64-lane programs on 32-lane waves:
|
||||
/// `VICTORY_LOOPS_WAVE`, `VICTORY_LDS_FIRST_INIT`), so they run now unless
|
||||
/// `VICTORY_WATER_LIGHT=0` (an empty value, an earlier version's saved OFF, runs them too).
|
||||
const WATER_LIGHT: [&str; 2] = ["5dc3b25986622949", "6f225b641c5b0708"];
|
||||
|
||||
fn water_light_left_out(shaders: &[Arc<Shader>]) -> bool {
|
||||
static ASKED: OnceLock<bool> = OnceLock::new();
|
||||
!*ASKED.get_or_init(|| std::env::var_os("VICTORY_WATER_LIGHT").is_some_and(|v| v == "1"))
|
||||
*ASKED.get_or_init(|| std::env::var_os("VICTORY_WATER_LIGHT").is_some_and(|v| v == "0"))
|
||||
&& victory_shader::emit::host_settings()[0] == 32
|
||||
&& shaders.iter().any(|s| WATER_LIGHT.contains(&s.hash.as_str()))
|
||||
}
|
||||
@@ -97,7 +99,7 @@ fn left_out(shaders: &[Arc<Shader>]) -> Option<&'static str> {
|
||||
return Some("named in VICTORY_LEAVE_OUT, left out");
|
||||
}
|
||||
if water_light_left_out(shaders) {
|
||||
return Some("the water's tiled light on a host of 32-lane waves (dark blocks; VICTORY_WATER_LIGHT=1 runs it), left out");
|
||||
return Some("the water's tiled light on a host of 32-lane waves, left out (VICTORY_WATER_LIGHT=0)");
|
||||
}
|
||||
static SKIP_RT_RESOLVE: OnceLock<bool> = OnceLock::new();
|
||||
let skip_rt = *SKIP_RT_RESOLVE.get_or_init(|| {
|
||||
@@ -112,14 +114,15 @@ fn left_out(shaders: &[Arc<Shader>]) -> Option<&'static str> {
|
||||
if skip_rt && named(shaders, b"CS_RaytracingResolve") {
|
||||
return Some("shades ray-tracing hits without BVH, left out");
|
||||
}
|
||||
// The screen probes' ray activation runs without the structure builder
|
||||
// too: left out, the probes kept stale values and surfaces lit mostly by
|
||||
// them took a magenta or violet cast (papers on a wall, irises), at no
|
||||
// frame-rate gain (bisected and measured by a tester, issue #2 of the
|
||||
// public repository, 2026-11-27). `VICTORY_ACTIVATE_RAYS=0`: left out,
|
||||
// as before.
|
||||
static SKIP_ACTIVATE_RAYS: OnceLock<bool> = OnceLock::new();
|
||||
let skip_activate = *SKIP_ACTIVATE_RAYS.get_or_init(|| {
|
||||
let builder = std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1");
|
||||
if builder {
|
||||
return std::env::var_os("VICTORY_ACTIVATE_RAYS").is_some_and(|v| v == "0");
|
||||
}
|
||||
std::env::var_os("VICTORY_ACTIVATE_RAYS").is_none_or(|v| v == "0")
|
||||
});
|
||||
let skip_activate =
|
||||
*SKIP_ACTIVATE_RAYS.get_or_init(|| std::env::var_os("VICTORY_ACTIVATE_RAYS").is_some_and(|v| v == "0"));
|
||||
if skip_activate && named(shaders, b"CS_ScreenProbes_ActivateRays") {
|
||||
return Some("ray activation shader without BVH, left out");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
//! Static samplers given to the card's driver in one order in every process.
|
||||
//!
|
||||
//! The driver (NVIDIA, 4070 SUPER) keeps static samplers in a table of its
|
||||
//! own, in the order in which a process first makes each, and a compiled
|
||||
//! pipeline holds its samplers' places in that table (`library`'s
|
||||
//! `with_static_samplers`). The driver's cache on disk finds a pipeline again
|
||||
//! only where those places are the same. The title's pipelines are made by
|
||||
//! several threads in the order the title asks for them, so the places
|
||||
//! differed from run to run and from the processes of `victory warm`:
|
||||
//!
|
||||
//! - 120 pipelines made by `victory warm --these` from a folder never used
|
||||
//! before: 13.6 s the first time, 0.6 s again in the same order, 2.5 s in
|
||||
//! the reverse order (compiled again), 0.6 s in the reverse order again.
|
||||
//! - The title started to its menu from a folder whose pipelines `victory
|
||||
//! warm` had all made: 15 pipelines a second with 12 processors busy for
|
||||
//! 13 s, on the first start and on every later one; the opening then ran
|
||||
//! at 3 to 9 frames a second for 30 s with up to 900 draws dropped
|
||||
//! (launcher run rel3, 2026-11-27). The driver's cache grew by 46 MB with
|
||||
//! every such start. A folder used for two days of runs held 6.0 GB of
|
||||
//! such variants and found most of them.
|
||||
//!
|
||||
//! So every distinct static sampler is written to a list in the cache
|
||||
//! ([`FILE`], one line each, in the order first met), and every process
|
||||
//! makes them all in that order when its device is made ([`prime`]), in root
|
||||
//! signatures of their own that live as long as the process: a sampler's
|
||||
//! place is then its line in the list, whoever asks first. A sampler met
|
||||
//! later ([`know`]) is added at the end, by one process at a time. The title
|
||||
//! has 28 in all (the driver's table holds 2,032).
|
||||
//!
|
||||
//! `VICTORY_SAMPLER_ORDER=0`: in the order each process makes them, as before.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::io::{Read, Seek, SeekFrom, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Mutex, OnceLock, RwLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use victory_shader::emit::StaticSampler;
|
||||
use windows::Win32::Graphics::Direct3D::ID3DBlob;
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
|
||||
/// The list, beside the pipeline library.
|
||||
const FILE: &str = "static-samplers.txt";
|
||||
|
||||
/// A sampler as the host is given it: filter, the three address modes, the
|
||||
/// LOD bias (bits), the anisotropy, the comparison, the border, the least
|
||||
/// and the greatest LOD (bits).
|
||||
type Words = [u32; 10];
|
||||
|
||||
static DIR: OnceLock<PathBuf> = OnceLock::new();
|
||||
|
||||
/// Those made so far in this process, for [`know`]'s quick answer.
|
||||
static SEEN: RwLock<Option<HashSet<Words>>> = RwLock::new(None);
|
||||
|
||||
struct Made {
|
||||
known: HashSet<Words>,
|
||||
/// The root signatures that hold them: kept, so that the driver keeps
|
||||
/// their places.
|
||||
kept: Vec<ID3D12RootSignature>,
|
||||
}
|
||||
|
||||
// SAFETY: D3D12 objects are free-threaded; these are only held.
|
||||
unsafe impl Send for Made {}
|
||||
|
||||
static MADE: Mutex<Option<Made>> = Mutex::new(None);
|
||||
|
||||
fn on() -> bool {
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_SAMPLER_ORDER").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// The list is kept in `dir` (the pipelines' folder of the cache) from now on.
|
||||
pub(crate) fn use_folder(dir: PathBuf) {
|
||||
let _ = DIR.set(dir);
|
||||
}
|
||||
|
||||
/// What `victory warm` adds to its fingerprint: pipelines made with the
|
||||
/// samplers in another order are not the driver's to find again.
|
||||
pub(crate) fn order() -> Vec<u8> {
|
||||
if !on() {
|
||||
return Vec::new();
|
||||
}
|
||||
// (The text names the scheme: changed when the samplers came to be made
|
||||
// first of all, before Streamline has the device.)
|
||||
let mut bytes = b"static samplers in one order, made first\n".to_vec();
|
||||
if let Some(listed) = DIR.get().and_then(|d| std::fs::read(d.join(FILE)).ok()) {
|
||||
bytes.extend(listed);
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Makes the samplers of the list, in its order: called when the device is
|
||||
/// made, before anything else has a static sampler.
|
||||
pub(crate) fn prime(device: &ID3D12Device) {
|
||||
if on() {
|
||||
let made = sync(device, &[]);
|
||||
tracing::info!(samplers = made, "static samplers made in the order of the cache's list");
|
||||
}
|
||||
}
|
||||
|
||||
/// A shader with these static samplers is about to get a pipeline, or was
|
||||
/// translated: those not yet in the list are added to it and made.
|
||||
pub(crate) fn know(samplers: &[StaticSampler]) {
|
||||
if samplers.is_empty() || !on() {
|
||||
return;
|
||||
}
|
||||
// Not `host()`: a translation must not open the device.
|
||||
let Some(host) = crate::host::host_made() else { return };
|
||||
let supported = aniso_point_mip(&host.device);
|
||||
let words: Vec<Words> = samplers.iter().map(|s| words(s, supported)).collect();
|
||||
{
|
||||
let seen = SEEN.read().unwrap_or_else(|e| e.into_inner());
|
||||
if seen.as_ref().is_some_and(|seen| words.iter().all(|w| seen.contains(w))) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
sync(&host.device, &words);
|
||||
}
|
||||
|
||||
fn aniso_point_mip(device: &ID3D12Device) -> bool {
|
||||
static SUPPORTED: OnceLock<bool> = OnceLock::new();
|
||||
*SUPPORTED.get_or_init(|| {
|
||||
let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS19::default();
|
||||
// SAFETY: the feature query writes the structure of the given size
|
||||
// (as `host::HostPipeline::new` asks it).
|
||||
unsafe {
|
||||
device.CheckFeatureSupport(
|
||||
D3D12_FEATURE_D3D12_OPTIONS19,
|
||||
(&raw mut options).cast(),
|
||||
size_of_val(&options) as u32,
|
||||
)
|
||||
}
|
||||
.is_ok()
|
||||
&& options.AnisoFilterWithPointMipSupported.as_bool()
|
||||
})
|
||||
}
|
||||
|
||||
fn words(s: &StaticSampler, aniso_point_mip_supported: bool) -> Words {
|
||||
let [u, v, w] = s.address;
|
||||
[
|
||||
s.filter_for_host(aniso_point_mip_supported),
|
||||
u,
|
||||
v,
|
||||
w,
|
||||
s.mip_lod_bias.to_bits(),
|
||||
s.max_anisotropy,
|
||||
s.comparison,
|
||||
s.border,
|
||||
s.min_lod.to_bits(),
|
||||
s.max_lod.to_bits(),
|
||||
]
|
||||
}
|
||||
|
||||
fn line(w: &Words) -> String {
|
||||
w.iter().map(|v| format!("{v:x}")).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
fn parse(line: &str) -> Option<Words> {
|
||||
let mut words = [0u32; 10];
|
||||
let mut given = line.split_ascii_whitespace();
|
||||
for w in &mut words {
|
||||
*w = u32::from_str_radix(given.next()?, 16).ok()?;
|
||||
}
|
||||
given.next().is_none().then_some(words)
|
||||
}
|
||||
|
||||
/// The list's file, open for this process alone (others wait in their own
|
||||
/// call of this), or `None` without a folder or after ten seconds.
|
||||
fn open_alone() -> Option<std::fs::File> {
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
let dir = DIR.get()?;
|
||||
let _ = std::fs::create_dir_all(dir);
|
||||
let began = Instant::now();
|
||||
loop {
|
||||
match std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).share_mode(0).open(dir.join(FILE)) {
|
||||
Ok(file) => return Some(file),
|
||||
Err(e) if began.elapsed() < Duration::from_secs(10) => {
|
||||
// (32: another process has it open.)
|
||||
let _ = e;
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "the list of static samplers could not be opened; their order is this process's own");
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes what the list holds and this process has not made yet, in the
|
||||
/// list's order, then `mine` where new (added to the list). How many this
|
||||
/// process has made in all.
|
||||
fn sync(device: &ID3D12Device, mine: &[Words]) -> usize {
|
||||
let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let made = made.get_or_insert_with(|| Made { known: HashSet::new(), kept: Vec::new() });
|
||||
let mut file = open_alone();
|
||||
let mut listed = String::new();
|
||||
if let Some(file) = &mut file {
|
||||
let _ = file.read_to_string(&mut listed);
|
||||
}
|
||||
let mut new = Vec::new();
|
||||
for w in listed.lines().filter_map(parse) {
|
||||
if made.known.insert(w) {
|
||||
new.push(w);
|
||||
}
|
||||
}
|
||||
let mut added = String::new();
|
||||
for w in mine {
|
||||
if made.known.insert(*w) {
|
||||
new.push(*w);
|
||||
added.push_str(&line(w));
|
||||
added.push('\n');
|
||||
}
|
||||
}
|
||||
for w in &new {
|
||||
match root_with(device, w) {
|
||||
Ok(root) => made.kept.push(root),
|
||||
Err(e) => tracing::warn!(error = %e, sampler = line(w), "a static sampler of the list was refused"),
|
||||
}
|
||||
}
|
||||
if let Some(file) = &mut file
|
||||
&& !added.is_empty()
|
||||
{
|
||||
if !listed.is_empty() && !listed.ends_with('\n') {
|
||||
added.insert(0, '\n');
|
||||
}
|
||||
if let Err(e) = file.seek(SeekFrom::End(0)).and_then(|_| file.write_all(added.as_bytes())) {
|
||||
tracing::warn!(error = %e, "the list of static samplers was not written");
|
||||
}
|
||||
}
|
||||
drop(file);
|
||||
let mut seen = SEEN.write().unwrap_or_else(|e| e.into_inner());
|
||||
seen.get_or_insert_default().extend(new);
|
||||
made.known.len()
|
||||
}
|
||||
|
||||
/// A root signature with the one static sampler `w`.
|
||||
fn root_with(device: &ID3D12Device, w: &Words) -> windows::core::Result<ID3D12RootSignature> {
|
||||
let sampler = D3D12_STATIC_SAMPLER_DESC {
|
||||
Filter: D3D12_FILTER(w[0] as i32),
|
||||
AddressU: D3D12_TEXTURE_ADDRESS_MODE(w[1] as i32),
|
||||
AddressV: D3D12_TEXTURE_ADDRESS_MODE(w[2] as i32),
|
||||
AddressW: D3D12_TEXTURE_ADDRESS_MODE(w[3] as i32),
|
||||
MipLODBias: f32::from_bits(w[4]),
|
||||
MaxAnisotropy: w[5],
|
||||
ComparisonFunc: D3D12_COMPARISON_FUNC(w[6] as i32),
|
||||
BorderColor: D3D12_STATIC_BORDER_COLOR(w[7] as i32),
|
||||
MinLOD: f32::from_bits(w[8]),
|
||||
MaxLOD: f32::from_bits(w[9]),
|
||||
ShaderRegister: 0,
|
||||
RegisterSpace: 0,
|
||||
ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL,
|
||||
};
|
||||
let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC {
|
||||
Version: D3D_ROOT_SIGNATURE_VERSION_1_1,
|
||||
Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 {
|
||||
Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 {
|
||||
NumStaticSamplers: 1,
|
||||
pStaticSamplers: &sampler,
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
};
|
||||
// SAFETY: the description points at `sampler`, which lives through the
|
||||
// call; the blob is read in full before it is released.
|
||||
unsafe {
|
||||
let mut blob: Option<ID3DBlob> = None;
|
||||
D3D12SerializeVersionedRootSignature(&desc, &mut blob, None)?;
|
||||
let blob = blob.ok_or_else(windows::core::Error::empty)?;
|
||||
let bytes = std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize());
|
||||
device.CreateRootSignature(0, bytes)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_line_reads_back_as_its_sampler() {
|
||||
let w: Words = [0x15, 3, 3, 3, 0, 1, 1, 0, 0, 0x4140_0000];
|
||||
assert_eq!(parse(&line(&w)), Some(w));
|
||||
assert_eq!(parse("15 3 3"), None);
|
||||
assert_eq!(parse("15 3 3 3 0 1 1 0 0 41400000 7"), None);
|
||||
assert_eq!(parse(""), None);
|
||||
}
|
||||
}
|
||||
@@ -738,6 +738,15 @@ impl Player {
|
||||
Type: D3D12_HEAP_TYPE_DEFAULT,
|
||||
..Default::default()
|
||||
};
|
||||
// (Another vendor's card, `VICTORY_REPLAY_VENDOR`: a card with no memory of its
|
||||
// own has no pool L1, so custom heaps there become plain ones.)
|
||||
let made = gpu::to_props(p);
|
||||
if std::env::var_os("VICTORY_REPLAY_VENDOR").is_some()
|
||||
&& made.Type == D3D12_HEAP_TYPE_CUSTOM
|
||||
&& made.MemoryPoolPreference == D3D12_MEMORY_POOL_L1
|
||||
{
|
||||
return card;
|
||||
}
|
||||
match (gpu::seen(p), buffers) {
|
||||
(Seen::ReadBack, _) => gpu::to_props(p),
|
||||
(_, Buffers::Card) if buffer => card,
|
||||
@@ -765,7 +774,32 @@ impl Player {
|
||||
.filter(|id| !textures.contains(id))
|
||||
.collect()
|
||||
};
|
||||
// `VICTORY_REPLAY_KEEP=<file>` with `VICTORY_REPLAY_LEAN=1`: only the resources the
|
||||
// file lists are made at all (a few commands on another vendor's card).
|
||||
let lean: Option<HashSet<u32>> = std::env::var("VICTORY_REPLAY_LEAN")
|
||||
.is_ok_and(|v| v.trim() == "1")
|
||||
.then(|| std::env::var_os("VICTORY_REPLAY_KEEP"))
|
||||
.flatten()
|
||||
.and_then(|f| {
|
||||
let text = std::fs::read_to_string(f).ok()?;
|
||||
Some(text.split(|c: char| !c.is_ascii_digit()).filter_map(|w| w.parse().ok()).collect())
|
||||
});
|
||||
// (and only the heaps they lie in)
|
||||
let lean_heaps: Option<HashSet<u32>> = lean.as_ref().map(|k| {
|
||||
self.frame
|
||||
.resources
|
||||
.iter()
|
||||
.filter(|r| k.contains(&r.id))
|
||||
.filter_map(|r| match r.place {
|
||||
Place::Placed { heap, .. } => Some(heap),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
for h in &self.frame.heaps {
|
||||
if lean_heaps.as_ref().is_some_and(|k| !k.contains(&h.id)) {
|
||||
continue;
|
||||
}
|
||||
let desc = D3D12_HEAP_DESC {
|
||||
SizeInBytes: h.size,
|
||||
Properties: props(&h.props, only.is_empty() && used_by_buffers_only.contains(&h.id)),
|
||||
@@ -781,6 +815,9 @@ impl Player {
|
||||
let mut failed = 0;
|
||||
let mut moves: BTreeMap<String, (u32, u64)> = BTreeMap::new();
|
||||
for (index, r) in self.frame.resources.iter().enumerate() {
|
||||
if lean.as_ref().is_some_and(|k| !k.contains(&r.id)) {
|
||||
continue;
|
||||
}
|
||||
let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0;
|
||||
let moved = is_buffer && chosen(r, only);
|
||||
if moved && let Place::Committed { props, .. } = &r.place {
|
||||
@@ -888,9 +925,15 @@ impl Player {
|
||||
continue;
|
||||
}
|
||||
// SAFETY: a blob the host took.
|
||||
let root = unsafe { self.device.CreateRootSignature(0, &blob.0) }
|
||||
.with_context(|| format!("root signature {id}"))?;
|
||||
self.roots.insert(*id, root);
|
||||
let made: windows::core::Result<ID3D12RootSignature> = unsafe { self.device.CreateRootSignature(0, &blob.0) };
|
||||
match made {
|
||||
Ok(root) => {
|
||||
self.roots.insert(*id, root);
|
||||
}
|
||||
// (Another vendor's card than the one recorded on may refuse one: what
|
||||
// uses it is then not made.)
|
||||
Err(e) => tracing::warn!("root signature {id} not made ({} bytes): {e}", blob.0.len()),
|
||||
}
|
||||
}
|
||||
for s in &self.frame.signatures {
|
||||
if self.signatures.contains_key(&s.id) {
|
||||
@@ -1367,9 +1410,11 @@ impl Player {
|
||||
// Batches of parts with their place in the buffer.
|
||||
let mut batches: Vec<Vec<(usize, u64)>> = vec![Vec::new()];
|
||||
let (mut at, mut most) = (0u64, 0u64);
|
||||
// (`VICTORY_REPLAY_STEPS`: each part alone and waited for.)
|
||||
let stepped = std::env::var_os("VICTORY_REPLAY_STEPS").is_some();
|
||||
for (i, (_, len, _)) in parts.iter().enumerate() {
|
||||
at = at.next_multiple_of(512);
|
||||
if at + len > STAGING && at > 0 {
|
||||
if (at + len > STAGING || stepped) && at > 0 {
|
||||
batches.push(Vec::new());
|
||||
at = 0;
|
||||
}
|
||||
@@ -1436,6 +1481,9 @@ impl Player {
|
||||
let sent = worker.send(|l| copy(self, l, &list, &buffer));
|
||||
self.worker = worker;
|
||||
stagings[k].2 = sent?;
|
||||
if stepped {
|
||||
self.worker.idle().with_context(|| format!("upload batch {n}"))?;
|
||||
}
|
||||
}
|
||||
self.worker.idle()?;
|
||||
Ok(())
|
||||
@@ -1459,26 +1507,49 @@ impl Player {
|
||||
if loaded { &mut into } else { &mut early },
|
||||
);
|
||||
}
|
||||
// `VICTORY_REPLAY_KEEP=<file>`: contents only of the resources whose numbers the
|
||||
// file lists (what a few commands read, from `--flow`): the others stay as made.
|
||||
let keep: Option<HashSet<u32>> = std::env::var_os("VICTORY_REPLAY_KEEP").and_then(|f| {
|
||||
let text = std::fs::read_to_string(f).ok()?;
|
||||
Some(text.split(|c: char| !c.is_ascii_digit()).filter_map(|w| w.parse().ok()).collect())
|
||||
});
|
||||
let textures: Vec<(Content, u64, u64)> = self
|
||||
.frame
|
||||
.contents
|
||||
.iter()
|
||||
.filter(|c| self.objects.contains_key(&c.res))
|
||||
.filter(|c| keep.as_ref().is_none_or(|k| k.contains(&c.res)))
|
||||
.map(|c| (c.clone(), c.len, c.file))
|
||||
.collect();
|
||||
let missing = self.frame.contents.len() - textures.len();
|
||||
self.worker.run(|list| {
|
||||
// SAFETY: an open list; live resources.
|
||||
unsafe {
|
||||
for all in early.chunks(1000) {
|
||||
list.ResourceBarrier(all);
|
||||
}
|
||||
list.ResourceBarrier(&[alias()]);
|
||||
for all in into.chunks(1000) {
|
||||
list.ResourceBarrier(all);
|
||||
}
|
||||
// `VICTORY_REPLAY_STEPS=<n>`: the state changes in lists of n, each waited for and
|
||||
// counted in the log (to find the one another vendor's card stops at).
|
||||
if let Some(n) = std::env::var("VICTORY_REPLAY_STEPS").ok().and_then(|v| v.trim().parse::<usize>().ok()).filter(|&n| n > 0) {
|
||||
for (k, all) in early.chunks(n).enumerate() {
|
||||
// SAFETY: an open list; live resources.
|
||||
self.worker.run(|list| unsafe { list.ResourceBarrier(all) }).with_context(|| format!("state changes of idle resources, step {k} of {n}"))?;
|
||||
}
|
||||
})?;
|
||||
// SAFETY: as above.
|
||||
self.worker.run(|list| unsafe { list.ResourceBarrier(&[alias()]) }).context("the alias barrier")?;
|
||||
for (k, all) in into.chunks(n).enumerate() {
|
||||
// SAFETY: as above.
|
||||
self.worker.run(|list| unsafe { list.ResourceBarrier(all) }).with_context(|| format!("state changes of loaded resources, step {k} of {n}"))?;
|
||||
}
|
||||
tracing::info!("state changes done: {} idle, {} loaded", early.len(), into.len());
|
||||
} else {
|
||||
self.worker.run(|list| {
|
||||
// SAFETY: an open list; live resources.
|
||||
unsafe {
|
||||
for all in early.chunks(1000) {
|
||||
list.ResourceBarrier(all);
|
||||
}
|
||||
list.ResourceBarrier(&[alias()]);
|
||||
for all in into.chunks(1000) {
|
||||
list.ResourceBarrier(all);
|
||||
}
|
||||
}
|
||||
})?;
|
||||
}
|
||||
let file = File::open(self.folder.join("contents.bin"))?;
|
||||
self.upload(&textures, &file, |player, list, parts, staging| {
|
||||
for (c, len, at) in parts {
|
||||
@@ -1486,6 +1557,9 @@ impl Player {
|
||||
continue;
|
||||
};
|
||||
let r = &player.frame.resources[o.index];
|
||||
if std::env::var_os("VICTORY_REPLAY_STEPS").is_some() {
|
||||
tracing::info!("contents of {} ({}): first {} count {} bytes {}", r.id, r.name, c.first, c.count, len);
|
||||
}
|
||||
// SAFETY: an open list; live resources.
|
||||
unsafe {
|
||||
if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 {
|
||||
@@ -3443,7 +3517,13 @@ fn make_device(frame: &Frame, debug: bool, breadcrumbs: bool) -> Result<(ID3D12D
|
||||
break;
|
||||
};
|
||||
let d = a.GetDesc1()?;
|
||||
if (d.VendorId, d.DeviceId) == (frame.vendor, frame.device) {
|
||||
// `VICTORY_REPLAY_VENDOR=<hex>`: the first adapter of that vendor instead of
|
||||
// the one recorded on (1002: AMD, whose waves can be the console's 64 lanes).
|
||||
let wanted = match std::env::var("VICTORY_REPLAY_VENDOR").ok().and_then(|v| u32::from_str_radix(v.trim(), 16).ok()) {
|
||||
Some(vendor) => d.VendorId == vendor,
|
||||
None => (d.VendorId, d.DeviceId) == (frame.vendor, frame.device),
|
||||
};
|
||||
if wanted {
|
||||
adapter = Some(a);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ pub(crate) struct AllocationInfo {
|
||||
|
||||
const _: () = assert!(size_of::<HeapProperties>() == 20);
|
||||
const _: () = assert!(size_of::<HeapDesc>() == 48);
|
||||
// placed_resource_words copies the two field spans on either side of the padding.
|
||||
// normal_placed (descriptor.rs) clears the padding words on either side of these spans.
|
||||
const _: () = assert!(std::mem::offset_of!(ResourceDesc, alignment) == 8);
|
||||
const _: () = assert!(std::mem::offset_of!(ResourceDesc, flags) == 48);
|
||||
const _: () = assert!(size_of::<ResourceDesc>() == 56);
|
||||
@@ -1307,6 +1307,11 @@ struct Hosted {
|
||||
wanted: std::sync::atomic::AtomicU32,
|
||||
/// The next host copy takes the place of one with fewer levels.
|
||||
grown: std::sync::atomic::AtomicBool,
|
||||
/// When [`slot_evict`] last let its host copy go with its slots
|
||||
/// (`crate::host::moment`; 0: not since it came back), and when a copy
|
||||
/// made after that came back: not taken so again for [`PROTECT_MS`].
|
||||
slot_evicted: std::sync::atomic::AtomicU64,
|
||||
slot_returned: std::sync::atomic::AtomicU64,
|
||||
}
|
||||
|
||||
/// Whether a texture the title places in memory is read, kept and uploaded
|
||||
@@ -1761,6 +1766,17 @@ fn hosted(this: This, make: bool) -> Option<Made> {
|
||||
// Slots the title wrote with views of it while it had no host copy
|
||||
// are made before the next submission runs.
|
||||
crate::descriptor::texture_made(this as usize);
|
||||
// Let go by `slot_evict` (`VICTORY_SLOT_EVICT=1`) and back: counted,
|
||||
// and not taken so again for a while (memory stack by skornuta,
|
||||
// skornuta/victory-memory-stack 57fb136, GPL-3.0).
|
||||
let evicted = r.host.slot_evicted.swap(0, Relaxed);
|
||||
if evicted != 0 {
|
||||
let now = crate::host::moment();
|
||||
SLOT_EVICT[3].fetch_add(1, Relaxed);
|
||||
SLOT_EVICT[4].fetch_add(u64::from(!crate::host::long_ago(evicted, FAST_BACK_MS, 0)), Relaxed);
|
||||
SLOT_EVICT[5].fetch_add(now.wrapping_sub(evicted) & 0xffff_ffff, Relaxed);
|
||||
r.host.slot_returned.store(now.max(1), Relaxed);
|
||||
}
|
||||
}
|
||||
let now = crate::host::moment();
|
||||
if r.host.used.load(Relaxed) != now {
|
||||
@@ -2340,6 +2356,12 @@ pub(crate) fn let_go_idle() {
|
||||
// state of the texture let go (it says "uploaded").
|
||||
crate::texture::unstage(at as This);
|
||||
r.host.wanted.store(u32::MAX, Relaxed);
|
||||
// Not used since: the looks pass it by (`used == 0`) until
|
||||
// a use makes its copy again. Kept, it stayed idle and every
|
||||
// look over the line sorted and locked it, finding nothing
|
||||
// to let go: a look cost 3 ms after a minute and 14 ms after
|
||||
// 30 (issue #12). The next use stamps it under this lock.
|
||||
r.host.used.store(0, Relaxed);
|
||||
made.take()
|
||||
} else {
|
||||
None
|
||||
@@ -2357,9 +2379,17 @@ pub(crate) fn let_go_idle() {
|
||||
crate::host::retire(host);
|
||||
}
|
||||
}
|
||||
// The table of textures is let go first: `slot_evict` takes it itself,
|
||||
// and a lock taken twice by one thread waits for ever (upstream's patch
|
||||
// 07: the hang of every run with `VICTORY_SLOT_EVICT=1` as soon as the
|
||||
// card passed its line).
|
||||
drop(all);
|
||||
SWEPT_US[0].fetch_add(1, Relaxed);
|
||||
SWEPT_US[1].fetch_add(began.elapsed().as_micros() as u64, Relaxed);
|
||||
SWEPT_US[2].fetch_max(began.elapsed().as_micros() as u64, Relaxed);
|
||||
// Memory stack by skornuta (skornuta/victory-memory-stack 57fb136,
|
||||
// GPL-3.0): `VICTORY_SLOT_EVICT=1`; without it, nothing.
|
||||
slot_evict(memory, idle_ms, IDLE_FRAMES);
|
||||
if went > 0 {
|
||||
crate::host::trail(|| {
|
||||
format!(
|
||||
@@ -2371,6 +2401,242 @@ pub(crate) fn let_go_idle() {
|
||||
}
|
||||
}
|
||||
|
||||
// Slot eviction: memory stack by skornuta (skornuta/victory-memory-stack 57fb136, GPL-3.0),
|
||||
// patches 06 and 07 and the slot eviction of their base.
|
||||
|
||||
/// Counts of [`slot_evict`]: textures let go though slots showed them,
|
||||
/// their bytes, slots put back to waiting, textures made again since, of
|
||||
/// them those back within [`FAST_BACK_MS`] (bad victims), the summed
|
||||
/// tenths of a second they were away, and attempts given up because a draw
|
||||
/// used the texture meanwhile.
|
||||
#[cfg(windows)]
|
||||
pub(crate) static SLOT_EVICT: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8];
|
||||
|
||||
/// [`slot_evict`] as of its last pass that looked at textures: whether it
|
||||
/// is evicting (between its two lines, on the way down); of the
|
||||
/// idle-looking textures (the last, their count), those it kept because a
|
||||
/// draw's table showed one of their slots within the idle time, and those
|
||||
/// it may not take because a slot shaders pick by index (or a dynamic one,
|
||||
/// or one no table showed lately) shows them.
|
||||
#[cfg(windows)]
|
||||
pub(crate) static SLOT_STATE: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
|
||||
|
||||
/// A texture back within this time was a bad victim; one that came back
|
||||
/// is not a victim again for [`PROTECT_MS`].
|
||||
#[cfg(windows)]
|
||||
const FAST_BACK_MS: u64 = 2_000;
|
||||
#[cfg(windows)]
|
||||
const PROTECT_MS: u64 = 60_000;
|
||||
|
||||
/// `VICTORY_SLOT_EVICT=1` (off by default): under pressure, idle host
|
||||
/// copies of textures the title fills are let go although title slots a
|
||||
/// draw reads through a table show them. Two lines: eviction starts above
|
||||
/// `VICTORY_SLOT_EVICT_PERCENT` of the card's budget (85, 50 to 97) and
|
||||
/// goes on, at most `VICTORY_SLOT_EVICT_MB` (256, 16 to 2048) a sweep,
|
||||
/// until the card is under `VICTORY_SLOT_EVICT_LOW_PERCENT` (the high one
|
||||
/// less 10, 40 to the high one less 1). The high one, the low one and the
|
||||
/// cap in bytes.
|
||||
#[cfg(windows)]
|
||||
fn slot_evict_settings() -> Option<(u64, u64, u64)> {
|
||||
static S: std::sync::OnceLock<Option<(u64, u64, u64)>> = std::sync::OnceLock::new();
|
||||
*S.get_or_init(|| {
|
||||
let num = |k: &str| std::env::var(k).ok().and_then(|v| v.trim().parse::<u64>().ok());
|
||||
(std::env::var("VICTORY_SLOT_EVICT").is_ok_and(|v| v == "1")).then(|| {
|
||||
let high = num("VICTORY_SLOT_EVICT_PERCENT").unwrap_or(85).clamp(50, 97);
|
||||
let low = num("VICTORY_SLOT_EVICT_LOW_PERCENT").unwrap_or(high.saturating_sub(10)).clamp(40, high - 1);
|
||||
(high, low, num("VICTORY_SLOT_EVICT_MB").unwrap_or(256).clamp(16, 2048) << 20)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// How many bytes over `percent` of `budget` the card's `used` is.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn excess(budget: u64, used: u64, percent: u64) -> u64 {
|
||||
used.saturating_sub(budget / 100 * percent)
|
||||
}
|
||||
|
||||
/// What a [`slot_evict`] pass does, with the card's `used` bytes of
|
||||
/// `budget`: whether eviction is on from here (`evicting`: it was on after
|
||||
/// the last pass) and how many bytes to let go now. It starts once the card
|
||||
/// is over `high` percent, then lets go of the excess over `low` percent,
|
||||
/// at most `cap` a pass, until it is under `low`, and stops: the card does
|
||||
/// not sit on one line, freeing and making copies again every second.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn slot_plan(evicting: bool, budget: u64, used: u64, high: u64, low: u64, cap: u64) -> (bool, u64) {
|
||||
if !evicting && used <= budget / 100 * high {
|
||||
return (false, 0);
|
||||
}
|
||||
match excess(budget, used, low) {
|
||||
0 => (false, 0),
|
||||
need => (true, need.min(cap)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The latest frame of `ring` (frame, milliseconds, oldest first) at or
|
||||
/// before `at_ms`; `None` if the ring does not reach back that far.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn frame_at(ring: &std::collections::VecDeque<(u64, u64)>, at_ms: u64) -> Option<u64> {
|
||||
ring.iter().rev().find(|&&(_, ms)| ms <= at_ms).map(|&(frame, _)| frame)
|
||||
}
|
||||
|
||||
/// The addresses of the oldest of `copies` (address, last use, bytes),
|
||||
/// sorted, whose bytes first cover `need`.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn oldest_covering(mut copies: Vec<(usize, u64, u64)>, need: u64) -> Vec<usize> {
|
||||
copies.sort_by_key(|&(_, used, _)| used);
|
||||
let mut sum = 0u64;
|
||||
let mut out: Vec<usize> = copies
|
||||
.into_iter()
|
||||
.take_while(|&(_, _, bytes)| {
|
||||
let more = sum < need;
|
||||
sum += bytes;
|
||||
more
|
||||
})
|
||||
.map(|(at, ..)| at)
|
||||
.collect();
|
||||
out.sort_unstable();
|
||||
out
|
||||
}
|
||||
|
||||
/// With [`slot_evict_settings`], under pressure: lets go of idle host
|
||||
/// copies of textures the title fills that only title slots hold, the ones
|
||||
/// a draw reads through a table (`crate::descriptor::evictable_slots`).
|
||||
/// The sweep ([`let_go_idle`]) takes only copies nothing but their title
|
||||
/// texture holds, and a texture drawn through a table always has a slot
|
||||
/// that shows it.
|
||||
///
|
||||
/// The slots go back to waiting first (null views: nothing reads the
|
||||
/// resource through them any more; `crate::descriptor::evict_slots`), then
|
||||
/// the copy is taken under its lock if still idle and held by no list,
|
||||
/// and retired behind the running submissions; else the slots are made
|
||||
/// again before the next submission. A list holds a copy by `Arc`
|
||||
/// (`strong_count`): such a texture is never taken. A draw that reads the
|
||||
/// texture through a table makes the copy again from title memory, and its
|
||||
/// slot after the list ([`hosted`], `HostHeap::mirror_after`). A texture
|
||||
/// any of whose slots a draw's table showed after "idle time ago" is kept:
|
||||
/// a texture drawn through a table every frame never asks for its host
|
||||
/// copy again, so its last use says nothing of that, and only its slots'
|
||||
/// table stamps do. That frame is read from a ring of (frame, time) points
|
||||
/// kept at most one a second, two minutes of them. A texture that came
|
||||
/// back is not taken again for [`PROTECT_MS`].
|
||||
///
|
||||
/// shortcut: as the sweep's, a thread that took a view of the copy and has
|
||||
/// not yet recorded its use is protected by the idle time alone.
|
||||
/// Called by the sweep with the table of textures let go; holds it itself.
|
||||
#[cfg(windows)]
|
||||
fn slot_evict(video: Option<[u64; 4]>, idle_ms: u64, frames: u64) {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let (Some((high, low, cap)), Some([budget, used, ..])) = (slot_evict_settings(), video) else {
|
||||
return;
|
||||
};
|
||||
static RING: std::sync::Mutex<std::collections::VecDeque<(u64, u64)>> =
|
||||
std::sync::Mutex::new(std::collections::VecDeque::new());
|
||||
let now_ms = crate::host::now_ms();
|
||||
let frame = crate::frame::current();
|
||||
let cutoff = {
|
||||
let mut ring = RING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// (At most a point a second: the sweep runs at every submission.)
|
||||
if ring.back().is_none_or(|&(_, ms)| now_ms >= ms + 1000) {
|
||||
ring.push_back((frame, now_ms));
|
||||
}
|
||||
while ring.len() > 120 {
|
||||
ring.pop_front();
|
||||
}
|
||||
frame_at(&ring, now_ms.saturating_sub(idle_ms))
|
||||
};
|
||||
static EVICTING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
let (on, need) = slot_plan(EVICTING.load(Relaxed), budget, used, high, low, cap);
|
||||
EVICTING.store(on, Relaxed);
|
||||
SLOT_STATE[0].store(u64::from(on), Relaxed);
|
||||
if need == 0 {
|
||||
return;
|
||||
}
|
||||
// Not yet a frame `idle_ms` back: nothing is known idle by its slots.
|
||||
let Some(cutoff) = cutoff else {
|
||||
return;
|
||||
};
|
||||
// Held to the end: a texture leaves the table before it is freed, under
|
||||
// this lock (`Drop for Resource`).
|
||||
let all = textures();
|
||||
let mut copies = Vec::new();
|
||||
let mut raws = std::collections::HashMap::new();
|
||||
for &at in all.iter() {
|
||||
// SAFETY: as in `let_go_idle`.
|
||||
let r = unsafe { &*(at as *const Resource) };
|
||||
if !fills(&r.desc) || crate::texture::host_wrote(at) {
|
||||
continue;
|
||||
}
|
||||
let back = r.host.slot_returned.load(Relaxed);
|
||||
if back != 0 && !crate::host::long_ago(back, PROTECT_MS, 0) {
|
||||
continue;
|
||||
}
|
||||
let stamp = r.host.used.load(Relaxed);
|
||||
if stamp == 0 || !crate::host::long_ago(stamp, idle_ms, frames) {
|
||||
continue;
|
||||
}
|
||||
let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some((host, _)) = made.as_ref()
|
||||
&& std::sync::Arc::strong_count(host) == 1
|
||||
{
|
||||
copies.push((at, stamp & 0xffff_ffff, host.bytes));
|
||||
raws.insert(windows::core::Interface::as_raw(&host.texture) as usize, at);
|
||||
}
|
||||
}
|
||||
if copies.is_empty() {
|
||||
return;
|
||||
}
|
||||
let (slots, kept, blocked) = crate::descriptor::evictable_slots(&raws, frame, cutoff);
|
||||
SLOT_STATE[3].store(raws.len() as u64, Relaxed);
|
||||
SLOT_STATE[2].store(blocked, Relaxed);
|
||||
SLOT_STATE[1].store(kept, Relaxed);
|
||||
copies.retain(|&(at, ..)| slots.contains_key(&at));
|
||||
let (mut n, mut bytes) = (0u64, 0u64);
|
||||
for at in oldest_covering(copies, need) {
|
||||
// SAFETY: as above (the table is held).
|
||||
let r = unsafe { &*(at as *const Resource) };
|
||||
let reset = crate::descriptor::evict_slots(at, &slots[&at]);
|
||||
SLOT_EVICT[2].fetch_add(reset, Relaxed);
|
||||
let gone = {
|
||||
let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let idle = made.as_ref().is_some_and(|(host, _)| {
|
||||
crate::host::long_ago(r.host.used.load(Relaxed), idle_ms, frames) && std::sync::Arc::strong_count(host) == 1
|
||||
});
|
||||
if idle {
|
||||
// As the sweep lets a copy go (`let_go_idle`).
|
||||
crate::texture::unstage(at as This);
|
||||
r.host.wanted.store(u32::MAX, Relaxed);
|
||||
r.host.used.store(0, Relaxed);
|
||||
r.host.slot_evicted.store(crate::host::moment().max(1), Relaxed);
|
||||
made.take()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
match gone {
|
||||
Some((host, _)) => {
|
||||
r.host.gone.store(true, Relaxed);
|
||||
KINDS[2].fetch_add(1, Relaxed);
|
||||
KINDS[3].fetch_add(host.bytes, Relaxed);
|
||||
SLOT_EVICT[0].fetch_add(1, Relaxed);
|
||||
SLOT_EVICT[1].fetch_add(host.bytes, Relaxed);
|
||||
n += 1;
|
||||
bytes += host.bytes;
|
||||
crate::host::retire(host);
|
||||
}
|
||||
None => {
|
||||
// Used meanwhile: its slots are made again before the next
|
||||
// submission.
|
||||
SLOT_EVICT[6].fetch_add(1, Relaxed);
|
||||
crate::descriptor::texture_made(at);
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(all);
|
||||
if n > 0 {
|
||||
crate::host::trail(|| format!("sweep: {n} host copies let go with their slots under pressure ({} KiB)", bytes >> 10));
|
||||
}
|
||||
}
|
||||
|
||||
/// Since the start: looks of [`let_go_idle`], their microseconds, and the
|
||||
/// longest one's.
|
||||
#[cfg(windows)]
|
||||
@@ -2935,6 +3201,8 @@ fn hand_out_resource(
|
||||
placed: std::sync::atomic::AtomicBool::new(false),
|
||||
wanted: std::sync::atomic::AtomicU32::new(u32::MAX),
|
||||
grown: std::sync::atomic::AtomicBool::new(false),
|
||||
slot_evicted: std::sync::atomic::AtomicU64::new(0),
|
||||
slot_returned: std::sync::atomic::AtomicU64::new(0),
|
||||
},
|
||||
});
|
||||
// The host copy waits for the texture's first use ([`Hosted`]).
|
||||
@@ -3184,19 +3452,25 @@ static PLACED_TEXTURES: std::sync::Mutex<std::collections::BTreeMap<(u64, [u32;
|
||||
std::sync::Mutex::new(std::collections::BTreeMap::new());
|
||||
|
||||
/// The placed textures asked for with filler words set, as asked
|
||||
/// (address and description): for [`PLACED_TWINS`].
|
||||
#[cfg(windows)]
|
||||
/// (address and description): for [`PLACED_TWINS`]. Diagnostics builds
|
||||
/// only: nothing outside `copystat` (itself diagnostics-only) consumes
|
||||
/// [`placed_filler_twins`], so a build without that feature carries
|
||||
/// neither this set nor its own mutex, nor the per-call tracking in
|
||||
/// [`texture_at`] that would otherwise take it on every placed-texture
|
||||
/// lookup, hit or not.
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
static PLACED_RAW: std::sync::Mutex<std::collections::BTreeSet<(u64, [u32; 14])>> =
|
||||
std::sync::Mutex::new(std::collections::BTreeSet::new());
|
||||
|
||||
/// Placed textures asked for a second time with other filler words in
|
||||
/// their description: each was a second resource and host copy before the
|
||||
/// filler was left out of the key ([`texture_at`]).
|
||||
#[cfg(windows)]
|
||||
/// filler was left out of the key ([`texture_at`]). Diagnostics builds
|
||||
/// only; see [`PLACED_RAW`].
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
static PLACED_TWINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
/// See [`PLACED_TWINS`].
|
||||
#[cfg(windows)]
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
pub(crate) fn placed_filler_twins() -> u64 {
|
||||
PLACED_TWINS.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
@@ -3277,6 +3551,9 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> {
|
||||
// that fills at world entry. They are not part of what a texture is.
|
||||
// `VICTORY_PLACED_FILLER=1`: kept in the key, as before.
|
||||
static KEPT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
// Only the diagnostics-only filler-twins tracking below reads `raw`;
|
||||
// the functional cache key is `key` alone.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
let raw = *desc;
|
||||
let mut key = *desc;
|
||||
if !*KEPT.get_or_init(|| std::env::var_os("VICTORY_PLACED_FILLER").is_some_and(|v| v == "1")) {
|
||||
@@ -3286,7 +3563,11 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> {
|
||||
let desc = &key;
|
||||
let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// How many resources the filler alone would have added (a count for
|
||||
// the log: `placed_filler_twins`).
|
||||
// the log: `placed_filler_twins`). Diagnostics builds only: without
|
||||
// that feature this whole block -- its mutex, its set, and its O(seen
|
||||
// so far at this address) scan on every new raw description -- does
|
||||
// not exist, not just "does nothing"; see `PLACED_RAW`.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if raw != key {
|
||||
let mut seen = PLACED_RAW.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if seen.insert((address, raw)) {
|
||||
@@ -3546,6 +3827,67 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::object::slot;
|
||||
|
||||
// Slot eviction's tests: memory stack by skornuta (skornuta/victory-memory-stack 57fb136,
|
||||
// GPL-3.0).
|
||||
|
||||
/// Between the lines nothing starts; over the high one eviction starts
|
||||
/// and takes the excess over the low one, a capped step at a time, until
|
||||
/// the card is under the low one.
|
||||
#[test]
|
||||
fn slot_eviction_starts_high_and_stops_low() {
|
||||
let (budget, high, low, cap) = (1000, 85, 75, 50);
|
||||
// Idle between the lines: nothing.
|
||||
assert_eq!(slot_plan(false, budget, 800, high, low, cap), (false, 0));
|
||||
assert_eq!(slot_plan(false, budget, 850, high, low, cap), (false, 0));
|
||||
// Over the high line: on, down toward the low one, capped.
|
||||
assert_eq!(slot_plan(false, budget, 900, high, low, cap), (true, 50));
|
||||
assert_eq!(slot_plan(false, budget, 860, high, low, cap), (true, 50));
|
||||
// On, between the lines: it goes on (the line it stops at is the low one).
|
||||
assert_eq!(slot_plan(true, budget, 800, high, low, cap), (true, 50));
|
||||
assert_eq!(slot_plan(true, budget, 770, high, low, cap), (true, 20));
|
||||
// Under the low line: off, and it stays off until the high one again.
|
||||
assert_eq!(slot_plan(true, budget, 750, high, low, cap), (false, 0));
|
||||
assert_eq!(slot_plan(false, budget, 840, high, low, cap), (false, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_frame_ring_says_the_frame_at_a_time_back() {
|
||||
let ring: std::collections::VecDeque<(u64, u64)> = [(100, 1_000), (114, 2_000), (130, 3_000)].into();
|
||||
assert_eq!(frame_at(&ring, 2_500), Some(114));
|
||||
assert_eq!(frame_at(&ring, 3_000), Some(130));
|
||||
assert_eq!(frame_at(&ring, 999), None, "the ring does not reach back that far");
|
||||
}
|
||||
|
||||
/// The oldest copies go first, until their bytes cover the need; the
|
||||
/// answer is sorted by address.
|
||||
#[test]
|
||||
fn the_oldest_copies_covering_the_need_go() {
|
||||
let copies = vec![(0x300, 30, 10), (0x100, 10, 10), (0x200, 20, 10), (0x400, 40, 10)];
|
||||
assert_eq!(oldest_covering(copies.clone(), 15), vec![0x100, 0x200]);
|
||||
assert_eq!(oldest_covering(copies.clone(), 10), vec![0x100]);
|
||||
assert_eq!(oldest_covering(copies.clone(), 0), Vec::<usize>::new());
|
||||
assert_eq!(oldest_covering(copies, 1000), vec![0x100, 0x200, 0x300, 0x400]);
|
||||
}
|
||||
|
||||
/// A slot's table stamp is the frame plus one in 31 bits: "seen since
|
||||
/// the cutoff" holds for a frame after it, also across the wrap, and
|
||||
/// never for a slot never seen.
|
||||
#[test]
|
||||
fn a_slot_seen_by_a_table_after_the_cutoff_is_seen_since() {
|
||||
use crate::descriptor::host::seen_since;
|
||||
let stamp = |frame: u64| (frame as u32).wrapping_add(1) & 0x7fff_ffff;
|
||||
assert!(seen_since(stamp(1_000), 900, 1_010));
|
||||
assert!(!seen_since(stamp(900), 900, 1_010), "at the cutoff is not after it");
|
||||
assert!(!seen_since(stamp(800), 900, 1_010));
|
||||
assert!(!seen_since(0, 900, 1_010), "never seen");
|
||||
// The read bit set: the same.
|
||||
assert!(seen_since(stamp(1_000) | 1 << 31, 900, 1_010));
|
||||
// Across the 31-bit wrap.
|
||||
let top = (1u64 << 31) - 3;
|
||||
assert!(seen_since(stamp(top + 5), top, top + 10));
|
||||
assert!(!seen_since(stamp(top - 1), top, top + 10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a8_unorm_is_not_in_the_r8_typeless_family() {
|
||||
// DXGI_FORMAT values: 60 R8_TYPELESS, 61 R8_UNORM, 62 R8_UINT,
|
||||
|
||||
@@ -24,6 +24,8 @@ static MISSES: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Keeps translated shaders in `dir` from now on.
|
||||
pub fn use_shader_cache(dir: PathBuf) {
|
||||
#[cfg(windows)]
|
||||
crate::pipeline::samplers::use_folder(dir.with_file_name("pipelines"));
|
||||
match Cache::open(dir) {
|
||||
Ok(cache) => {
|
||||
let _ = CACHE.set(cache);
|
||||
@@ -77,6 +79,8 @@ fn build() -> [u8; 32] {
|
||||
"VICTORY_BVH_FENCES",
|
||||
"VICTORY_BVH_BOUNDS",
|
||||
"VICTORY_THREAD_TICKET",
|
||||
"VICTORY_LDS_LOOP_ATOMICS",
|
||||
"VICTORY_LDS_BOUNDS",
|
||||
] {
|
||||
bytes.extend_from_slice(name.as_bytes());
|
||||
bytes.push(b'=');
|
||||
@@ -128,10 +132,14 @@ pub fn precompile(container: &[u8]) -> Result<bool, String> {
|
||||
/// there is one.
|
||||
pub(crate) fn host_shader(container: &[u8]) -> Result<HostShader, String> {
|
||||
let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string());
|
||||
match CACHE.get() {
|
||||
let shader = match CACHE.get() {
|
||||
Some(cache) => cached(cache, &build(), container, translate),
|
||||
None => translate(container),
|
||||
}
|
||||
}?;
|
||||
// Its static samplers into the list every process makes them from.
|
||||
#[cfg(windows)]
|
||||
crate::pipeline::samplers::know(&shader.static_samplers);
|
||||
Ok(shader)
|
||||
}
|
||||
|
||||
/// The cache entry's converter: the build and the container in, the
|
||||
|
||||
@@ -425,6 +425,7 @@ fn card_room_for(size: u64) -> Option<ID3D12Resource> {
|
||||
if !host.card_ready() {
|
||||
return None;
|
||||
}
|
||||
crate::ahead::want_card();
|
||||
// Only while the card has room: with this copy on it, a fifth of the
|
||||
// budget the system gives us must still be free. Copies are made when
|
||||
// the world loads, before the textures fill the card; the texture
|
||||
@@ -463,7 +464,9 @@ fn card_room_for(size: u64) -> Option<ID3D12Resource> {
|
||||
CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed);
|
||||
return None;
|
||||
}
|
||||
let buffer = host.uav_buffer(size);
|
||||
// (one made ahead, if it is of that size and one is in store: `crate::ahead`)
|
||||
let ahead = if size == crate::ahead::SIZE { crate::ahead::card() } else { None };
|
||||
let buffer = ahead.or_else(|| host.uav_buffer(size));
|
||||
if buffer.is_none() {
|
||||
CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed);
|
||||
}
|
||||
@@ -1526,6 +1529,90 @@ struct Workers {
|
||||
more: std::sync::Condvar,
|
||||
/// How many jobs there are, for [`spin`].
|
||||
there: std::sync::atomic::AtomicUsize,
|
||||
/// How many [`Hot`] stand: while one does, an idle helper waits awake
|
||||
/// ([`passes_hot_us`]).
|
||||
hot: AtomicUsize,
|
||||
/// [`now_us`] of the last job begun or ended, or of the last [`hot`].
|
||||
busy_at: AtomicU64,
|
||||
}
|
||||
|
||||
/// Microseconds since the first call (for [`Workers::busy_at`]).
|
||||
fn now_us() -> u64 {
|
||||
static BASE: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
|
||||
BASE.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
|
||||
}
|
||||
|
||||
static HOT_US: AtomicU64 = AtomicU64::new(u64::MAX);
|
||||
|
||||
/// `VICTORY_PASSES_HOT` (read here; microseconds, `0` by default: off, as
|
||||
/// before): while a submission is prepared ([`hot`], from its start to its
|
||||
/// end) the helpers are woken at its start, and an idle one waits awake for
|
||||
/// the next pass instead of sleeping, up to this long after the last work
|
||||
/// or the start, giving way to other threads of its core now and then
|
||||
/// (`yield_now`). A pass then finds them awake, and the waking at the start
|
||||
/// overlaps the submission's asking and planning. Only when work starts
|
||||
/// changes, not what is done nor by whom it may be done.
|
||||
///
|
||||
/// Measured in the title with `1` (the helpers woken at each submission's
|
||||
/// start, back asleep soon after; RTX 4090, Ryzen 9 7950X3D, DLSS Quality,
|
||||
/// the walking route through the first boat mission at the 30 fps cap): the
|
||||
/// longest frame walking went from 525 to 145 ms, 29.1 to 29.3 fps. Longer
|
||||
/// values keep cores spinning: in `wide_tests::pass_overhead` 2000 (with the
|
||||
/// submitting thread also waiting awake at the join) cut a pass's cost
|
||||
/// beyond its work from 18 to 3 us on an idle machine, but with more
|
||||
/// threads busy than cores (40 on 32) it grew from 28 to 119 us, the
|
||||
/// spinning helpers taking the cores the submitting thread and the title
|
||||
/// need.
|
||||
pub(crate) fn passes_hot_us() -> u64 {
|
||||
let v = HOT_US.load(Ordering::Relaxed);
|
||||
if v != u64::MAX {
|
||||
return v;
|
||||
}
|
||||
let v = std::env::var("VICTORY_PASSES_HOT").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0);
|
||||
HOT_US.store(v, Ordering::Relaxed);
|
||||
v
|
||||
}
|
||||
|
||||
/// Tests and benchmarks: [`passes_hot_us`] (`None`: as the environment
|
||||
/// says).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn set_passes_hot(hot: Option<u64>) {
|
||||
HOT_US.store(hot.unwrap_or(u64::MAX), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// While held, the helpers of [`wide`] are kept awake ([`passes_hot_us`]).
|
||||
pub(crate) struct Hot(bool);
|
||||
|
||||
/// Keeps the helpers awake for a while ([`passes_hot_us`]): taken where a
|
||||
/// submission's preparing begins, dropped where it ends.
|
||||
pub(crate) fn hot() -> Hot {
|
||||
if passes_hot_us() == 0 {
|
||||
return Hot(false);
|
||||
}
|
||||
let workers = workers();
|
||||
workers.busy_at.store(now_us(), Ordering::Relaxed);
|
||||
if workers.hot.fetch_add(1, Ordering::AcqRel) == 0 {
|
||||
// Woken now, they are awake when the first pass comes.
|
||||
let _queue = workers.jobs.lock().unwrap_or_else(|e| e.into_inner());
|
||||
workers.more.notify_all();
|
||||
}
|
||||
Hot(true)
|
||||
}
|
||||
|
||||
impl Drop for Hot {
|
||||
fn drop(&mut self) {
|
||||
if self.0 {
|
||||
workers().hot.fetch_sub(1, Ordering::AcqRel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// With [`hot`]: whether an idle helper is to stay awake.
|
||||
fn stay_awake(workers: &Workers) -> bool {
|
||||
let most = passes_hot_us();
|
||||
most != 0
|
||||
&& workers.hot.load(Ordering::Acquire) > 0
|
||||
&& now_us().saturating_sub(workers.busy_at.load(Ordering::Relaxed)) < most
|
||||
}
|
||||
|
||||
/// Waits awake until `there` says so, `VICTORY_WIDE_SPIN` microseconds at
|
||||
@@ -1545,9 +1632,20 @@ fn spin(there: impl Fn() -> bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many threads are kept for [`wide`].
|
||||
/// How many threads are kept for [`wide`]: three eighths of the logical processors, 2 to 8
|
||||
/// (`VICTORY_WIDE_THREADS=<n>`, 1 to 32, in its place). A quarter of them, 2 to 6, until
|
||||
/// 2026-11-27: on 16 logical processors 4 threads; with 8, the opening's cutscenes had 13
|
||||
/// seconds of 256 at 40 ms a frame or more in place of 28, and the stretch in which a scene
|
||||
/// streams in 38.9 ms a frame in place of 41.6 (runs v5q, v6q; gameplay not measured, the
|
||||
/// title's own threads want processors there, hence 6 of 16).
|
||||
fn wide_threads() -> usize {
|
||||
std::thread::available_parallelism().map_or(4, |n| n.get() / 4).clamp(2, 6)
|
||||
static ASKED: std::sync::OnceLock<Option<usize>> = std::sync::OnceLock::new();
|
||||
let asked = *ASKED.get_or_init(|| {
|
||||
let n = std::env::var("VICTORY_WIDE_THREADS").ok()?.trim().parse::<usize>().ok()?.clamp(1, 32);
|
||||
tracing::info!(n, "threads kept for refreshes on several threads (VICTORY_WIDE_THREADS)");
|
||||
Some(n)
|
||||
});
|
||||
asked.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get() * 3 / 8).clamp(2, 8))
|
||||
}
|
||||
|
||||
fn workers() -> &'static Workers {
|
||||
@@ -1557,6 +1655,8 @@ fn workers() -> &'static Workers {
|
||||
jobs: Mutex::new(std::collections::VecDeque::new()),
|
||||
more: std::sync::Condvar::new(),
|
||||
there: std::sync::atomic::AtomicUsize::new(0),
|
||||
hot: AtomicUsize::new(0),
|
||||
busy_at: AtomicU64::new(0),
|
||||
});
|
||||
STARTED.call_once(|| {
|
||||
for i in 0..wide_threads() {
|
||||
@@ -1566,21 +1666,41 @@ fn workers() -> &'static Workers {
|
||||
let workers = WORKERS.get().expect("made above");
|
||||
loop {
|
||||
priority.keep();
|
||||
let job = {
|
||||
let job = 'found: loop {
|
||||
// A little while awake first: the next work comes
|
||||
// within microseconds more often than not.
|
||||
spin(|| workers.there.load(Ordering::Acquire) > 0);
|
||||
let mut jobs = workers.jobs.lock().unwrap_or_else(|e| e.into_inner());
|
||||
loop {
|
||||
if let Some(job) = jobs.pop_front() {
|
||||
workers.there.fetch_sub(1, Ordering::AcqRel);
|
||||
break job;
|
||||
// While a submission is prepared: awake until work
|
||||
// comes (`passes_hot_us`).
|
||||
let mut turns = 0u32;
|
||||
while workers.there.load(Ordering::Acquire) == 0 && stay_awake(workers) {
|
||||
for _ in 0..32 {
|
||||
std::hint::spin_loop();
|
||||
}
|
||||
turns = turns.wrapping_add(1);
|
||||
if turns % 16 == 0 {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
jobs = workers.more.wait(jobs).unwrap_or_else(|e| e.into_inner());
|
||||
}
|
||||
let mut jobs = workers.jobs.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(job) = jobs.pop_front() {
|
||||
workers.there.fetch_sub(1, Ordering::AcqRel);
|
||||
break 'found job;
|
||||
}
|
||||
if stay_awake(workers) {
|
||||
continue;
|
||||
}
|
||||
jobs = workers.more.wait(jobs).unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(job) = jobs.pop_front() {
|
||||
workers.there.fetch_sub(1, Ordering::AcqRel);
|
||||
break 'found job;
|
||||
}
|
||||
// (Woken by `hot`, or for a job another took.)
|
||||
};
|
||||
workers.busy_at.store(now_us(), Ordering::Relaxed);
|
||||
let _working = crate::timeline::span("a job for another thread");
|
||||
job();
|
||||
workers.busy_at.store(now_us(), Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1866,6 +1986,86 @@ mod wide_tests {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
/// Waits awake `us` microseconds.
|
||||
fn busy(us: u64) {
|
||||
let began = std::time::Instant::now();
|
||||
while (began.elapsed().as_micros() as u64) < us {
|
||||
std::hint::spin_loop();
|
||||
}
|
||||
}
|
||||
|
||||
/// What a pass costs beyond its work (`VICTORY_PASSES_HOT`): passes of
|
||||
/// as many pieces as there are threads, each 20 us of work, with 300 us
|
||||
/// of the submitting thread's own work between them (as between a
|
||||
/// submission's passes), as before (the helpers asleep between passes)
|
||||
/// and with the helpers kept awake. Run with `cargo test --release -p
|
||||
/// victory-gpu -- --ignored --nocapture pass_overhead`.
|
||||
#[test]
|
||||
#[ignore = "benchmark"]
|
||||
fn pass_overhead() {
|
||||
const WORK: u64 = 20;
|
||||
const PASSES: usize = 400;
|
||||
let pieces = super::wide_threads() + 1;
|
||||
// `VICTORY_BENCH_LOAD=n`: n threads busy beside, as the title's are.
|
||||
let load: usize = std::env::var("VICTORY_BENCH_LOAD").ok().and_then(|v| v.parse().ok()).unwrap_or(0);
|
||||
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let busy_threads: Vec<_> = (0..load)
|
||||
.map(|_| {
|
||||
let stop = stop.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut x = 0u64;
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
for i in 0..10_000u64 {
|
||||
x = std::hint::black_box(x.wrapping_mul(31).wrapping_add(i));
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for (name, hot) in [("as before", 0), ("helpers hot", 2000)] {
|
||||
super::set_passes_hot(Some(hot));
|
||||
let _hot = super::hot();
|
||||
let mut took: Vec<f64> = Vec::with_capacity(PASSES);
|
||||
for _ in 0..PASSES {
|
||||
busy(300);
|
||||
let began = std::time::Instant::now();
|
||||
super::wide_each(pieces, |_| busy(WORK));
|
||||
took.push(began.elapsed().as_secs_f64() * 1e6 - WORK as f64);
|
||||
}
|
||||
took.sort_by(f64::total_cmp);
|
||||
let mean = took.iter().sum::<f64>() / PASSES as f64;
|
||||
println!(
|
||||
"{name} ({load} threads busy beside): {pieces} pieces of {WORK} us on {} threads and this one: beyond the work \
|
||||
{mean:.1} us a pass in the mean, median {:.1}, p90 {:.1}; for 24 passes {:.2} ms",
|
||||
super::wide_threads(),
|
||||
took[PASSES / 2],
|
||||
took[PASSES * 9 / 10],
|
||||
mean * 24.0 / 1000.0
|
||||
);
|
||||
}
|
||||
super::set_passes_hot(None);
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
busy_threads.into_iter().for_each(|t| t.join().unwrap());
|
||||
}
|
||||
|
||||
/// With the helpers kept awake ([`super::hot`]), every job still runs
|
||||
/// once, and `wide` returns only when all have.
|
||||
#[test]
|
||||
fn hot_helpers_run_every_job() {
|
||||
super::set_passes_hot(Some(2000));
|
||||
let hot = super::hot();
|
||||
for n in [2usize, 3, 7, 40, 1000] {
|
||||
let done = Arc::new(AtomicUsize::new(0));
|
||||
let seen = done.clone();
|
||||
super::wide_each(n, move |_| {
|
||||
seen.fetch_add(1, Ordering::Relaxed);
|
||||
});
|
||||
assert_eq!(done.load(Ordering::Relaxed), n);
|
||||
}
|
||||
drop(hot);
|
||||
super::set_passes_hot(None);
|
||||
}
|
||||
|
||||
/// Every job runs once, however many there are, and `wide` returns
|
||||
/// only when all have.
|
||||
#[test]
|
||||
|
||||
@@ -636,9 +636,13 @@ pub fn dlss_framegen_card(name: &str) -> bool {
|
||||
model.len() == 4 && (model.starts_with("40") || model.starts_with("50"))
|
||||
}
|
||||
|
||||
/// The adapter a device made with no adapter named is on (the first), its
|
||||
/// name and LUID.
|
||||
/// The card the host device is made on (`hardware_adapter`; else the first
|
||||
/// adapter, where a device made with no adapter named is), its name and LUID.
|
||||
fn default_adapter() -> Option<(String, windows::Win32::Foundation::LUID)> {
|
||||
if let Some((adapter, name, _)) = victory_shader::emit::host::hardware_adapter() {
|
||||
// SAFETY: a plain DXGI query.
|
||||
return unsafe { adapter.GetDesc1() }.ok().map(|d| (name, d.AdapterLuid));
|
||||
}
|
||||
// SAFETY: plain DXGI queries.
|
||||
unsafe {
|
||||
let factory: IDXGIFactory1 = CreateDXGIFactory1().ok()?;
|
||||
|
||||
Reference in new issue
Block a user