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:
trustno1-coderandClaude Opus 5.5 committed 2026-11-27 15:03:27 -08:00
1 parent df2daafeb1
commit 64d4931b3d
44 files changed
+4664 -952

No files matched your search

+19 -12
View File
@@ -1,4 +1,4 @@
//! A 2560x1440 SDR display for the supported Series X retail image (GTA VI
//! A 2560x1440 SDR display for the supported Series X retail image (the game,
//! 1.0.2.1): the title presents at 3840x2160 on Series X, its scene drawn at
//! 2560x1440 and scaled up by its own temporal pass. With 1440p asked for
//! (`VICTORY_NATIVE_1440P=1`, or `VICTORY_RENDER_1080P=1` for a 1920x1080
@@ -16,11 +16,18 @@ use victory_formats::texture::{Dimension, Swizzle, Texture, TextureDesc};
use victory_hle::streamline::Mode;
use victory_loader::PreparedImage;
const RETAIL_BUILD: &str = "b99f876b74d4a77f03af5f878223b27bd647b5c35a79d5decd9f716504239e93";
/// Whether `bytes` are the stock ones whose BLAKE3 hash (hex) is `hash`.
/// The stock bytes of each place patched are kept as their hash only: no
/// bytes of the title are in this repository.
fn same(bytes: &[u8], hash: &str) -> bool {
blake3::hash(bytes).to_hex().as_str() == hash
}
pub(super) const RETAIL_BUILD: &str = "b99f876b74d4a77f03af5f878223b27bd647b5c35a79d5decd9f716504239e93";
pub(super) const WIDTH: u32 = 2560;
pub(super) const HEIGHT: u32 = 1440;
const SDR_MODE: u32 = 0x0615_c100;
const STOCK_SDR_MODE: [u8; 16] = [0, 15, 0, 0, 112, 8, 0, 0, 60, 0, 0, 0, 1, 0, 0, 0];
const STOCK_SDR_MODE: &str = "abfb5438d8153b6a0b8d08f33f4f0066e5383925b55aacc5f669131f3f51d4cf";
const SCANOUT_RESERVATION: u32 = 0x0247_ad4a;
const TEMPORAL_SCALE: u32 = 0x028f_1e7e;
const UI_VIEWPORT_LOAD: u32 = 0x0580_48d4;
@@ -34,7 +41,7 @@ pub(super) fn prepare(image: &mut PreparedImage, render_1080p: bool) -> Result<(
);
let mode = field::<16>(image, SDR_MODE)?;
ensure!(*mode == STOCK_SDR_MODE, "unexpected Series X SDR mode");
ensure!(same(&mode[..], STOCK_SDR_MODE), "unexpected Series X SDR mode");
mode[..4].copy_from_slice(&WIDTH.to_le_bytes());
mode[4..8].copy_from_slice(&HEIGHT.to_le_bytes());
@@ -79,18 +86,18 @@ pub(super) fn prepare(image: &mut PreparedImage, render_1080p: bool) -> Result<(
/// title's own temporal pass, or on Series S with the upscaler there the
/// FidelityFX path, 7).
const RENDERER_SELECTION: u32 = 0x007e_9421;
const STOCK_RENDERER_SELECTION: [u8; 8] = [0xb8, 6, 0, 0, 0, 0x0f, 0x45, 0xc1];
const STOCK_RENDERER_SELECTION: &str = "f0633abf37df17124108b1e37be64645bd4b2412b0524c2f89334f22bd948464";
/// The FidelityFX path's render size: the console check's result (Series S)
/// is noted as the FidelityFX quality mode and picks the scaled branch
/// (`movzx eax, al; mov [r14+0x90], eax; test al, al; jne`), whose scale
/// multiplies the output size.
const UPSCALER_SIZING: u32 = 0x028e_f69a;
const STOCK_UPSCALER_SIZING: [u8; 14] = [0x0f, 0xb6, 0xc0, 0x41, 0x89, 0x86, 0x90, 0, 0, 0, 0x84, 0xc0, 0x75, 0x0a];
const STOCK_UPSCALER_SIZING: &str = "2ae2ac102d12ca003cb218413ef018e4dba68fc2003654a30c1743e13a820ffd";
/// The native branch's load of 1.0, and the scaled branch's of the scale.
const NATIVE_LOAD: u32 = 0x028e_f6a8;
const STOCK_NATIVE_LOAD: [u8; 10] = [0xc5, 0xfa, 0x10, 0x05, 0x28, 0x78, 0x6d, 0x03, 0xeb, 0x08];
const STOCK_NATIVE_LOAD: &str = "2579c24601d173b086a8136edf54ffd82720e6bf186f9139274bb09a45ddadf5";
const SCALED_LOAD: u32 = 0x028e_f6b2;
const STOCK_SCALED_LOAD: [u8; 8] = [0xc5, 0xfa, 0x10, 0x05, 0xa2, 0xe2, 0x86, 0x03];
const STOCK_SCALED_LOAD: &str = "e218882c95d2e16163a409d55b3451519414eb87c4d6220785dc09852d4e14f4";
/// The scale the scaled branch loads (shared with other code: not written).
const UPSCALER_SCALE: u32 = 0x0615_d95c;
@@ -112,10 +119,10 @@ pub(super) fn prepare_upscaler(image: &mut PreparedImage, mode: Mode) -> Result<
image.original_hash.to_hex().as_str() == RETAIL_BUILD,
"the upscaler path is only known for the retail build {RETAIL_BUILD}"
);
ensure!(*field::<8>(image, RENDERER_SELECTION)? == STOCK_RENDERER_SELECTION, "unexpected renderer selection");
ensure!(*field::<14>(image, UPSCALER_SIZING)? == STOCK_UPSCALER_SIZING, "unexpected upscaler render size selection");
ensure!(*field::<10>(image, NATIVE_LOAD)? == STOCK_NATIVE_LOAD, "unexpected upscaler native scale load");
ensure!(*field::<8>(image, SCALED_LOAD)? == STOCK_SCALED_LOAD, "unexpected upscaler scaled load");
ensure!(same(&field::<8>(image, RENDERER_SELECTION)?[..], STOCK_RENDERER_SELECTION), "unexpected renderer selection");
ensure!(same(&field::<14>(image, UPSCALER_SIZING)?[..], STOCK_UPSCALER_SIZING), "unexpected upscaler render size selection");
ensure!(same(&field::<10>(image, NATIVE_LOAD)?[..], STOCK_NATIVE_LOAD), "unexpected upscaler native scale load");
ensure!(same(&field::<8>(image, SCALED_LOAD)?[..], STOCK_SCALED_LOAD), "unexpected upscaler scaled load");
ensure!(*field::<4>(image, UPSCALER_SCALE)? == (2.0f32 / 3.0).to_le_bytes(), "unexpected upscaler scale");
let temporal = f32::from_le_bytes(*field::<4>(image, TEMPORAL_SCALE)?);
ensure!(
+9 -3
View File
@@ -69,6 +69,12 @@ const SETTINGS: &[(&str, &str)] = &[
("VICTORY_UPLOAD_AHEAD", "1"),
("VICTORY_SHOW_AFTER", "1"),
("VICTORY_MAP_THREADS", "1"),
// A frame's texture passes within 8 ms together; helpers woken at each submission's start
// (foxhound 0.2.0-pre.4, from its PR #13; its launcher sets 8 and 1)
("VICTORY_TEXSPK_PASS_MS", "8"),
("VICTORY_PASSES_HOT", "1"),
// The layer's threads a frame waits for, above normal priority (foxhound: cutscene worst second 74.8 -> 63.8 ms)
("VICTORY_HELPER_PRIORITY", "1"),
// Shader writes into big write-combined copies stay on the card
("VICTORY_WC_NO_BACK", "1"),
("VICTORY_WC_NO_BACK_MIN_KB", "1024"),
@@ -747,7 +753,7 @@ fn mod_dlls(here: &Path) -> Vec<String> {
}
/// How long the first start of a new victory.exe plays before it restarts.
const WARMUP_SECONDS: u32 = 20;
const WARMUP_SECONDS: u32 = 30;
/// The file that says this victory.exe (its bytes) had its warm-up start:
/// `%LOCALAPPDATA%\victory\warmed\<hash>`. `None`: the exe could not be read.
@@ -839,8 +845,8 @@ pub(crate) fn prepare(o: &Play) -> Result<Ready> {
&& let Some(mark) = warmup_mark(&home, &program)
&& !mark.exists()
{
println!("First start of this version of victory.exe: the game restarts by itself after {WARMUP_SECONDS} seconds,");
println!("once (a new version's first run otherwise stays at about 14 fps).");
println!("First start of this version of victory.exe: the game restarts by itself {WARMUP_SECONDS} seconds after it");
println!("loads into the game (press A at the title screen), once (a new version's first run otherwise stays at about 14 fps).");
s.insert("VICTORY_WARMUP_RESTART".to_owned(), WARMUP_SECONDS.to_string());
s.insert("VICTORY_WARMUP_MARK".to_owned(), mark.to_string_lossy().into_owned());
}
+4 -2
View File
@@ -465,8 +465,10 @@ fn retranslate(folder: &std::path::Path, into: &std::path::Path, view_limit: u32
}
}
println!("{} containers not found", missing.len());
victory_shader::emit::set_host_max_wave(64);
victory_shader::emit::set_host_rdna(true);
// (`VICTORY_HOST_WAVE=32`: as for a host of 32-lane waves; `VICTORY_HOST_RDNA=0`: not AMD's.)
let wave = std::env::var("VICTORY_HOST_WAVE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(64);
victory_shader::emit::set_host_max_wave(wave);
victory_shader::emit::set_host_rdna(std::env::var_os("VICTORY_HOST_RDNA").is_none_or(|v| v != "0"));
victory_shader::emit::set_view_heap_limit(view_limit);
victory_shader::emit::set_raw_views(raw_views);
let all: Vec<_> = wanted.iter().collect();
+72 -3
View File
@@ -38,6 +38,70 @@ fn check_cpu_features() -> Result<()> {
check_cpu_features_with(has_avx2, skip.as_deref())
}
/// The executable a run was pointed at: the file itself, or, given a folder, the one
/// executable in it (of several, the one whose name begins with `game`).
/// What to tell when the executable is not the retail build that the 1440p
/// and DLSS patches know: often it is that build, changed in place by
/// another tool (an FPS unlock changed 6 bytes and kept the stock file as
/// `.exe.bak`: issue #6 of the public repository). A file beside it whose
/// name begins as the executable's, of the same size, that hashes to the
/// retail build is named.
fn changed_copy(exe: &Path) -> String {
let len = std::fs::metadata(exe).map_or(0, |m| m.len());
let stem = exe.file_stem().and_then(|s| s.to_str()).unwrap_or_default().to_ascii_lowercase();
let stock = exe
.parent()
.and_then(|dir| std::fs::read_dir(dir).ok())
.into_iter()
.flatten()
.flatten()
.map(|entry| entry.path())
.filter(|p| {
p.as_path() != exe
&& p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.to_ascii_lowercase().starts_with(&stem))
&& std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.len() == len)
})
.find(|p| std::fs::read(p).is_ok_and(|bytes| blake3::hash(&bytes).to_hex().as_str() == native_1440p::RETAIL_BUILD));
match stock {
Some(stock) => format!(
"{} is not the unchanged retail executable: it was changed in place (for example by an FPS patch). The unchanged one is {}: copy it back over the changed one, or choose the 1080p class or DLSS off. (For more than 30 fps use the launcher's frame-rate setting.)",
exe.display(),
stock.display()
),
None => format!(
"{} is not the unchanged retail executable of version 1.0.2.1 (another build, or changed in place, for example by an FPS patch). 1440p output and DLSS need the unchanged file: restore it, or choose the 1080p class or DLSS off.",
exe.display()
),
}
}
fn title_executable(given: &Path) -> Result<std::path::PathBuf> {
if !given.is_dir() {
anyhow::ensure!(given.exists(), "{} does not exist: give the title's executable, or the folder it is in", given.display());
return Ok(given.to_path_buf());
}
let mut exes: Vec<std::path::PathBuf> = std::fs::read_dir(given)
.with_context(|| format!("listing {}", given.display()))?
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.is_file() && p.extension().is_some_and(|x| x.eq_ignore_ascii_case("exe")))
.collect();
exes.sort();
let game = |p: &std::path::PathBuf| {
p.file_name().is_some_and(|n| n.to_string_lossy().to_ascii_lowercase().starts_with("game"))
};
if exes.len() > 1 && exes.iter().filter(|p| game(p)).count() == 1 {
exes.retain(game);
}
match exes.as_slice() {
[one] => Ok(one.clone()),
[] => anyhow::bail!(
"{} is a folder with no executable in it: give the title's executable, or the folder it is in",
given.display()
),
_ => anyhow::bail!("{} is a folder with {} executables in it: give the title's own", given.display(), exes.len()),
}
}
#[cfg(windows)]
pub fn run(
exe: &Path,
@@ -85,6 +149,10 @@ pub fn run(
upscaler.map(|m| format!(", scene at the {} scale ({})", m.name(), m.scale())).unwrap_or_default()
);
}
// A folder in place of the executable: the title's executable in it (reading a folder
// as a file fails with "Access is denied", which says nothing of the mistake).
let found = title_executable(exe)?;
let exe = found.as_path();
let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?;
let mut prepared = victory_loader::prepare(&original)?;
let hash = prepared.original_hash.to_hex();
@@ -102,7 +170,8 @@ pub fn run(
if upscaler.is_some() && render_1080p {
println!("display VICTORY_RENDER_1080P is left out: VICTORY_DLSS_MODE sets the scene's size");
}
let (w, h) = native_1440p::prepare(&mut prepared, render_1080p && upscaler.is_none())?;
let (w, h) = native_1440p::prepare(&mut prepared, render_1080p && upscaler.is_none())
.map_err(|e| if victory_game::identify(&hash).is_some() { e } else { e.context(changed_copy(exe)) })?;
// SAFETY: nothing else runs yet; the title and the display mode list
// read these later.
unsafe {
@@ -209,7 +278,7 @@ pub fn run(
);
println!("missing dlls {message}");
// None of their imports can be bound, so the title stops at its first
// call into one (Grand Theft Auto VI 1.0.2.1 at +0x2237178 during
// call into one (the game, build 1.0.2.1, at +0x2237178 during
// System Init, #930) with nothing saying why. Stubs only if asked for.
if execute && matches!(unimplemented, Unimplemented::Trap) {
anyhow::bail!(
@@ -406,7 +475,7 @@ fn timers(base: usize, size: usize) {
/// Debugging aid: `VICTORY_POKE=<rva>:<byte>,...` (hex) writes the byte at
/// each title+rva twice a second. A title that ends itself when its main
/// loop has not ticked for a while (Grand Theft Auto VI: 30 s) runs on
/// loop has not ticked for a while (the game: 30 s) runs on
/// through slower frames with its tick flag poked. The address must be
/// writable title data.
#[cfg(all(windows, feature = "diagnostics"))]
+17
View File
@@ -98,6 +98,13 @@ struct Totals {
pub fn run(paths: Vec<PathBuf>, verbose: bool, disasm: bool) -> Result<()> {
let paths = crate::default_paths(paths)?;
let mut t = Totals::default();
// `VICTORY_SHADER_ONLY=<hash>,<hash>`: only the containers with these hashes (the 16
// digits a run's log names a shader by); `VICTORY_SHADER_SAVE=<folder>`: each one's
// bytes written there as `<hash>.bin`.
let only: Option<Vec<String>> = std::env::var("VICTORY_SHADER_ONLY")
.ok()
.map(|v| v.split(',').map(|h| h.trim().to_ascii_lowercase()).filter(|h| !h.is_empty()).collect());
let save = std::env::var_os("VICTORY_SHADER_SAVE").map(PathBuf::from);
for root in &paths {
for entry in walkdir::WalkDir::new(root)
.into_iter()
@@ -120,6 +127,16 @@ pub fn run(paths: Vec<PathBuf>, verbose: bool, disasm: bool) -> Result<()> {
eprintln!("corrupt record {}{}", path.display(), source.label());
continue;
};
if let Some(only) = &only {
let hash = blake3::hash(&bytes).to_hex();
if !only.iter().any(|h| h == &hash[..16]) {
continue;
}
if let Some(dir) = &save {
std::fs::create_dir_all(dir)?;
std::fs::write(dir.join(format!("{}.bin", &hash[..16])), &bytes)?;
}
}
let Ok(container) = Container::parse(&bytes) else {
continue;
};
+1 -1
View File
@@ -14,7 +14,7 @@ tracing.workspace = true
anyhow.workspace = true
victory-formats.workspace = true
victory-pipeline.workspace = true
victory-shader.workspace = true
victory-shader = { workspace = true, features = ["host"] }
[build-dependencies]
blake3.workspace = true
+167
View File
@@ -0,0 +1,167 @@
//! What command lists cost in the PC's memory: N allocators with a direct list
//! each are made, then each records C small copies and runs, then each is reset,
//! then all go. After each step: the process's private bytes and its
//! write-combined private memory (committed, and in physical memory), by a walk
//! of the address space.
//!
//! cargo run --release -p victory-gpu --example list_memory [N] [C]
//!
//! Found with it (2026-11-28, RTX 4070 SUPER, 500 lists): an empty allocator and list
//! about 0.8 MB of private memory; 20,000 recorded copies 1.8 MB more each, kept over
//! resets; the driver keeps its write-combined pages after the lists go. Upload
//! buffers: most of 1-8 MB ones given back on release, 64 KB ones kept (their chunks).
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
use windows::core::Interface;
fn private_mb() -> f64 {
use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
let mut c: PROCESS_MEMORY_COUNTERS_EX = unsafe { std::mem::zeroed() };
c.cb = size_of::<PROCESS_MEMORY_COUNTERS_EX>() as u32;
// SAFETY: our own process, a counters structure of the size given.
unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), (&raw mut c).cast(), c.cb) };
c.PrivateUsage as f64 / (1 << 20) as f64
}
/// Write-combined private memory: committed MB, MB in memory (one page in
/// sixteen asked), regions.
fn write_combined() -> (f64, f64, usize) {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_PRIVATE, MEMORY_BASIC_INFORMATION, PAGE_WRITECOMBINE, VirtualQuery};
use windows_sys::Win32::System::ProcessStatus::K32QueryWorkingSetEx;
use windows_sys::Win32::System::Threading::GetCurrentProcess;
let (mut committed, mut present, mut regions) = (0u64, 0u64, 0usize);
let mut at = 0usize;
loop {
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: a query of our own address space.
if unsafe { VirtualQuery(at as *const _, &mut info, size_of::<MEMORY_BASIC_INFORMATION>()) } == 0 {
break;
}
if info.State == MEM_COMMIT && info.Type == MEM_PRIVATE && info.Protect & PAGE_WRITECOMBINE != 0 {
committed += info.RegionSize as u64;
regions += 1;
let base = info.BaseAddress as usize;
let mut asked: Vec<[usize; 2]> = (0..info.RegionSize).step_by(16 << 12).map(|o| [base + o, 0]).collect();
// SAFETY: entries of two words, as the call fills them.
if unsafe { K32QueryWorkingSetEx(GetCurrentProcess(), asked.as_mut_ptr().cast(), (asked.len() * 16) as u32) } != 0 {
present += asked.iter().filter(|a| a[1] & 1 != 0).count() as u64 * (16 << 12);
}
}
at = info.BaseAddress as usize + info.RegionSize;
}
let mb = |b: u64| b as f64 / (1 << 20) as f64;
(mb(committed), mb(present), regions)
}
fn say(step: &str) {
let (wc, wc_in, regions) = write_combined();
println!("{step:52} private {:8.0} MB; write-combined {wc:7.0} MB committed ({wc_in:6.0} MB in memory, {regions} regions)", private_mb());
}
fn main() -> windows::core::Result<()> {
let args: Vec<usize> = std::env::args().skip(1).filter_map(|a| a.parse().ok()).collect();
let (n, copies) = (args.first().copied().unwrap_or(500), args.get(1).copied().unwrap_or(20_000));
// SAFETY: plain D3D12 calls with valid out pointers; every list is waited for.
unsafe {
let mut device: Option<ID3D12Device> = None;
D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
let device = device.unwrap();
let queue: ID3D12CommandQueue =
device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() })?;
let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
let event = CreateEventW(None, false, false, None)?;
let buffer = |size: u64| -> windows::core::Result<ID3D12Resource> {
let mut r: Option<ID3D12Resource> = None;
device.CreateCommittedResource(
&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
D3D12_HEAP_FLAG_NONE,
&D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: size,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
..Default::default()
},
D3D12_RESOURCE_STATE_COMMON,
None,
&mut r,
)?;
Ok(r.unwrap())
};
let (a, b) = (buffer(1 << 20)?, buffer(1 << 20)?);
say("device and two buffers");
let mut lists = Vec::with_capacity(n);
for _ in 0..n {
let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
list.Close()?;
lists.push((allocator, list));
}
say(&format!("{n} allocators and lists made, empty"));
let mut value = 0;
for (allocator, list) in &lists {
allocator.Reset()?;
list.Reset(allocator, None)?;
for i in 0..copies as u64 {
list.CopyBufferRegion(&b, (i * 4) % (1 << 20), &a, (i * 16) % (1 << 20), 4);
}
list.Close()?;
queue.ExecuteCommandLists(&[Some(list.cast()?)]);
value += 1;
queue.Signal(&fence, value)?;
fence.SetEventOnCompletion(value, event)?;
WaitForSingleObject(event, INFINITE);
}
say(&format!("each recorded {copies} copies and ran"));
for (allocator, list) in &lists {
allocator.Reset()?;
list.Reset(allocator, None)?;
list.Close()?;
}
say("each reset (as a pooled list is)");
drop(lists);
say("all gone");
// Upload buffers made and released, as the layer's churn does.
let upload = |size: u64| -> windows::core::Result<ID3D12Resource> {
let mut r: Option<ID3D12Resource> = None;
device.CreateCommittedResource(
&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() },
D3D12_HEAP_FLAG_NONE,
&D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: size,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
..Default::default()
},
D3D12_RESOURCE_STATE_GENERIC_READ,
None,
&mut r,
)?;
Ok(r.unwrap())
};
for (count, size) in [(2000usize, 1u64 << 20), (200, 8 << 20), (8000, 64 << 10)] {
let mut alive = Vec::with_capacity(count);
for _ in 0..count {
let r = upload(size)?;
let mut data = std::ptr::null_mut();
r.Map(0, None, Some(&mut data))?;
std::ptr::write_bytes(data.cast::<u8>(), 1, size as usize);
alive.push(r);
}
say(&format!("{count} upload buffers of {} KB alive, written", size >> 10));
drop(alive);
say(" ... released");
}
}
Ok(())
}
+165
View File
@@ -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 -1
View File
@@ -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;
+25 -1
View File
@@ -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]),
+264 -58
View File
@@ -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.
+73
View File
@@ -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) {
+123 -1
View File
@@ -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
View File
@@ -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)]
+171 -5
View File
@@ -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);
+86 -13
View File
@@ -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 };
+1
View File
@@ -16,6 +16,7 @@
//! `present` (swap chain).
#[cfg(windows)]
mod ahead;
mod ambient;
#[cfg(all(windows, feature = "diagnostics"))]
mod capture;
+77 -7
View File
@@ -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();
+2
View File
@@ -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.
+1
View File
@@ -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),
+1
View File
@@ -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()
}
+14 -11
View File
@@ -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");
}
+287
View File
@@ -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);
}
}
+96 -16
View File
@@ -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;
}
+349 -7
View File
@@ -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,
+10 -2
View File
@@ -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
+210 -10
View File
@@ -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]
+6 -2
View File
@@ -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()?;
+1
View File
@@ -34,6 +34,7 @@ windows-sys = { workspace = true, features = [
"Win32_System_Power",
"Win32_System_ProcessStatus",
"Win32_System_Threading",
"Win32_UI_Input",
"Win32_UI_Input_KeyboardAndMouse",
"Win32_UI_Input_XboxController",
"Win32_UI_WindowsAndMessaging",
+25 -3
View File
@@ -629,16 +629,38 @@ fn scheduler() -> Option<&'static Scheduler> {
})
.as_ref()?;
STARTED.call_once(|| {
let workers = std::thread::available_parallelism().map_or(4, |n| n.get());
// As many workers as processors (`VICTORY_DSTORAGE_WORKERS=<n>`: that many), below
// normal priority (`VICTORY_DSTORAGE_PRIORITY=<-2..2>`, 0: normal, as before
// 2026-11-27). While a scene streams in, all of them unpack at once: in a crowded
// cutscene (timeline tl5, 176 s into a new game, 62 ms a frame) 16 workers ran 10 ms
// a frame each beside 8 listing threads of 20 ms, and the threads a frame waits for
// stood "woken, not running yet" for 9.5 ms of each frame's chain. Below them in
// priority the workers take the processors nobody of the frame wants. The process
// runs above normal (`runtime::ahead_of_other_programs`), so they still come before
// other programs' threads.
let number = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::<i32>().ok());
let workers = match number("VICTORY_DSTORAGE_WORKERS") {
Some(n) if n > 0 => n as usize,
_ => std::thread::available_parallelism().map_or(4, |n| n.get()),
};
let priority = number("VICTORY_DSTORAGE_PRIORITY").map_or(-1, |p| p.clamp(-2, 2));
let started = (0..workers)
.filter(|i| {
std::thread::Builder::new()
.name(format!("dstorage {i}"))
.spawn(|| work(scheduler))
.spawn(move || {
#[cfg(windows)]
if priority != 0 {
use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority};
// SAFETY: this thread's own priority.
unsafe { SetThreadPriority(GetCurrentThread(), priority) };
}
work(scheduler)
})
.is_ok()
})
.count();
tracing::info!(workers = started, "dstorage: workers");
tracing::info!(workers = started, priority, "dstorage: workers (VICTORY_DSTORAGE_WORKERS, VICTORY_DSTORAGE_PRIORITY)");
});
Some(scheduler)
}
+1 -1
View File
@@ -85,7 +85,7 @@ pub fn mount_at(letter: char, root: &Path) {
/// `root` as UTF-16, absolute, without trailing separators (a drive root
/// keeps its own). An empty root is the current directory, as it is to a
/// path joined to it: it is the title's folder when the title is run by its
/// file name alone (`victory run GTA6.exe`).
/// file name alone (`victory run game.exe`).
fn root_wide(root: &Path) -> Vec<u16> {
let root = if root.as_os_str().is_empty() {
Path::new(".")
+26 -7
View File
@@ -1,5 +1,7 @@
//! `gameinput.dll`: input devices from the host. Gamepads come from XInput
//! (host slots 0-3); while none is connected, the keyboard drives one
//! (host slots 0-3) and, in the slots XInput leaves empty, from HID
//! ([`playstation`]: DualShock 4, DualSense, DualSense Edge); while none is
//! connected, the keyboard drives one
//! stand-in gamepad (`FALLBACK_BUTTONS`). The keyboard is a device of its own
//! too. A poll thread turns host state into readings (a new one per change)
//! and runs device callbacks on connect and disconnect.
@@ -21,9 +23,20 @@ use super::xasync::{E_INVALIDARG, E_NOTIMPL};
use super::xgameruntime::{HRESULT, S_OK};
use crate::{HleExport, HleModule};
// PS5 pads (DualSense, DualSense Edge) read straight from HID, USB or Bluetooth (from AnyXboxX's VIctory copy).
// PS5 pads (DualSense, DualSense Edge) read straight from HID, USB or Bluetooth (from AnyXboxX's VIctory copy);
// PS4 pads (DualShock 4) and rumble from FrancescoGelosoEterea/VIscosity (d8db7a0).
#[cfg(any(windows, test))]
mod dualsense;
mod playstation;
/// Stops the motors of the PlayStation pads read over HID, before the
/// process ends (XInput pads stop by themselves when it does).
pub(crate) fn stop_rumble() {
#[cfg(windows)]
if playstation::stop_rumble() {
// Their readers send it with their next report.
std::thread::sleep(std::time::Duration::from_millis(100));
}
}
/// The documented errors.
pub const DEVICE_DISCONNECTED: HRESULT = 0x838A_0001_u32 as i32;
@@ -1266,14 +1279,15 @@ mod host {
Some(super::apply_mouse_sample(&mut self.mouse, delta, buttons, menu_open))
}
fn pad(&mut self, slot: usize) -> Option<PadState> {
// XInput first; HID PS5 pads take the slots XInput leaves free (`VICTORY_DUALSENSE`: 0 off, 1 both).
// XInput first; HID PlayStation pads (PS4 and PS5) take the slots XInput leaves free
// (`VICTORY_DUALSENSE`: 0 off, 1 both).
if slot == 0 {
let xinput = std::array::from_fn(|slot| self.xinput(slot));
self.pads = super::dualsense::slots(
super::dualsense::mode(),
self.pads = super::playstation::slots(
super::playstation::mode(),
xinput,
&mut self.hid_slots,
super::dualsense::pads,
super::playstation::pads,
);
}
#[allow(unused_mut)]
@@ -1321,6 +1335,11 @@ mod host {
}
fn rumble(&mut self, slot: usize, low: u16, high: u16) {
// A slot a HID pad has is one XInput left empty.
if let Some(id) = self.hid_slots[slot] {
super::playstation::rumble(id, low, high);
return;
}
let speeds = XINPUT_VIBRATION {
wLeftMotorSpeed: low,
wRightMotorSpeed: high,
@@ -1,670 +0,0 @@
//! PlayStation 5 pads (DualSense, DualSense Edge) read straight from HID:
//! they are not XInput devices, so without a remapper (Steam Input,
//! DS4Windows) XInput never lists them. Reports can be USB or Bluetooth. A scan
//! thread looks for new pads every [`SCAN`]; each pad has a reader thread
//! that keeps its latest state until the pad goes away. By default XInput
//! has priority over HID, since a remapper can present the same pad twice.
use super::{
A, B, DOWN, LEFT, LEFT_SHOULDER, LEFT_STICK, MENU, PadState, RIGHT, RIGHT_SHOULDER,
RIGHT_STICK, UP, VIEW, X, Y,
};
#[cfg(windows)]
const SONY: u16 = 0x054C;
/// DualSense, DualSense Edge.
#[cfg(windows)]
const PRODUCTS: [u16; 2] = [0x0CE6, 0x0DF2];
/// The D-pad hat (low nibble of the first button byte): 0 up, clockwise in
/// eighths, 8 and above centred.
fn hat(value: u8) -> u32 {
match value & 0xF {
0 => UP,
1 => UP | RIGHT,
2 => RIGHT,
3 => RIGHT | DOWN,
4 => DOWN,
5 => DOWN | LEFT,
6 => LEFT,
7 => LEFT | UP,
_ => 0,
}
}
/// Face buttons in the first button byte, the rest in the second and third
/// (the PS button and the mute button have no console pad button).
const BUTTONS: [(usize, u8, u32); 11] = [
(0, 0x10, X), // square
(0, 0x20, A), // cross
(0, 0x40, B), // circle
(0, 0x80, Y), // triangle
(1, 0x01, LEFT_SHOULDER),
(1, 0x02, RIGHT_SHOULDER),
(1, 0x10, VIEW), // create
(1, 0x20, MENU), // options
(1, 0x40, LEFT_STICK),
(1, 0x80, RIGHT_STICK),
(2, 0x02, VIEW), // touchpad click
];
/// The pad in one input report, `None` for a report of another kind.
/// `bluetooth`: the pad is connected over Bluetooth, where the full report
/// is 0x31 (one byte further in) and 0x01 is the short report the pad sends
/// before it was asked for the full one.
pub(super) fn parse(report: &[u8], bluetooth: bool) -> Option<PadState> {
// Offsets of the sticks (LX LY RX RY), the triggers (L2 R2) and the
// three button bytes.
let (sticks, triggers, buttons) = match (report.first()?, bluetooth) {
(0x01, false) => (1, 5, 8),
(0x31, true) => (2, 6, 9),
(0x01, true) => (1, 8, 5),
_ => return None,
};
if report.len() < sticks + 4 || report.len() < triggers + 2 || report.len() < buttons + 3 {
return None;
}
let bytes = &report[buttons..buttons + 3];
// 0 to 255 with 128 centred; down is positive on the pad, up here.
let axis = |v: u8| ((f32::from(v) - 127.5) / 127.5).clamp(-1.0, 1.0);
Some(PadState {
buttons: BUTTONS
.iter()
.filter(|&&(byte, mask, _)| bytes[byte] & mask != 0)
.fold(hat(bytes[0]), |all, &(_, _, bit)| all | bit),
left_trigger: f32::from(report[triggers]) / 255.0,
right_trigger: f32::from(report[triggers + 1]) / 255.0,
left_x: axis(report[sticks]),
left_y: -axis(report[sticks + 1]),
right_x: axis(report[sticks + 2]),
right_y: -axis(report[sticks + 3]),
})
}
/// The Bluetooth address in a pairing feature report (0x09, the address at
/// 1..7 on both transports), `None` when it is too short or all zeros.
fn mac(pairing: &[u8]) -> Option<[u8; 6]> {
let mac: [u8; 6] = pairing.get(1..7)?.try_into().ok()?;
(mac != [0; 6]).then_some(mac)
}
#[cfg(windows)]
pub(super) use host::pads;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Mode {
Off,
Auto,
Both,
}
#[cfg(windows)]
pub(super) fn mode() -> Mode {
static MODE: std::sync::LazyLock<Mode> =
std::sync::LazyLock::new(|| match std::env::var("VICTORY_DUALSENSE").as_deref() {
Ok("0") => Mode::Off,
Ok("1") => Mode::Both,
_ => Mode::Auto,
});
*MODE
}
/// XInput does not identify the corresponding physical HID device. Prefer
/// it in automatic mode. If both sources are requested, retain the slot of
/// every connected HID pad unless that slot has been claimed by XInput.
pub(super) fn slots(
mode: Mode,
mut xinput: [Option<PadState>; super::PADS],
assigned: &mut [Option<u64>; super::PADS],
hid: impl FnOnce() -> Vec<(u64, PadState)>,
) -> [Option<PadState>; super::PADS] {
if mode == Mode::Off || mode == Mode::Auto && xinput.iter().any(Option::is_some) {
assigned.fill(None);
return xinput;
}
let pads = hid();
for (slot, owner) in xinput.iter_mut().zip(assigned.iter_mut()) {
if slot.is_none()
&& let Some((_, state)) = pads.iter().find(|(id, _)| Some(*id) == *owner)
{
*slot = Some(*state);
} else {
*owner = None;
}
}
for (id, state) in pads {
if assigned.contains(&Some(id)) {
continue;
}
let Some(slot) = xinput.iter().position(Option::is_none) else {
break;
};
xinput[slot] = Some(state);
assigned[slot] = Some(id);
}
xinput
}
#[cfg(windows)]
mod host {
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{LazyLock, Mutex, PoisonError};
use std::time::Duration;
use windows_sys::Win32::Devices::DeviceAndDriverInstallation::{
DIGCF_DEVICEINTERFACE, DIGCF_PRESENT, SP_DEVICE_INTERFACE_DATA,
SP_DEVICE_INTERFACE_DETAIL_DATA_W, SetupDiDestroyDeviceInfoList,
SetupDiEnumDeviceInterfaces, SetupDiGetClassDevsW, SetupDiGetDeviceInterfaceDetailW,
};
use windows_sys::Win32::Devices::HumanInterfaceDevice::{
HIDD_ATTRIBUTES, HIDP_CAPS, HIDP_STATUS_SUCCESS, HidD_FreePreparsedData,
HidD_GetAttributes, HidD_GetFeature, HidD_GetHidGuid, HidD_GetPreparsedData, HidP_GetCaps,
};
use windows_sys::Win32::Foundation::{
CloseHandle, ERROR_IO_PENDING, GENERIC_READ, GENERIC_WRITE, GetLastError, HANDLE,
INVALID_HANDLE_VALUE, WAIT_TIMEOUT,
};
use windows_sys::Win32::Storage::FileSystem::{
CreateFileW, FILE_FLAG_OVERLAPPED, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,
ReadFile,
};
use windows_sys::Win32::System::IO::{
CancelIoEx, GetOverlappedResult, GetOverlappedResultEx, OVERLAPPED,
};
use windows_sys::Win32::System::Threading::CreateEventW;
use super::{PRODUCTS, PadState, SONY, mac, parse};
/// How often to look for newly connected pads.
const SCAN: Duration = Duration::from_secs(2);
/// A pad in full-report mode sends reports all the time (hundreds a
/// second); this long without one and we ask it whether it is still
/// there. Over Bluetooth Windows can keep the device after the pad is
/// switched off or out of range, and a read then waits for ever.
const QUIET_MS: u32 = 500;
struct Pad {
/// This connection's: a pad that reconnects gets a new one.
id: u64,
path: Vec<u16>,
/// The pad's Bluetooth address, the same over USB and Bluetooth:
/// one pad seen through both is opened once.
mac: Option<[u8; 6]>,
/// `None` until the first report, and while the pad is silent.
state: Option<PadState>,
}
/// The open pads, in the order they were found.
static PADS: Mutex<Vec<Pad>> = Mutex::new(Vec::new());
fn lock() -> std::sync::MutexGuard<'static, Vec<Pad>> {
PADS.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Paths found to be a pad already open over its other transport, with
/// its address: not opened again on every scan (two feature reports
/// and a log line each time) while that pad stays open.
static TWINS: Mutex<Vec<(Vec<u16>, [u8; 6])>> = Mutex::new(Vec::new());
/// The open pads' latest states with their connection ids, oldest
/// connection first, without the pads that are silent or yet to report;
/// the first call starts looking for them.
pub(in super::super) fn pads() -> Vec<(u64, PadState)> {
static STARTED: LazyLock<()> = LazyLock::new(|| {
std::thread::spawn(|| {
loop {
scan();
std::thread::sleep(SCAN);
}
});
});
LazyLock::force(&STARTED);
lock()
.iter()
.filter_map(|pad| Some((pad.id, pad.state?)))
.collect()
}
/// Windows sizes each report buffer for its top-level HID collection.
/// The calibration and pairing reports use the same feature buffer.
struct Reports {
input: Vec<u8>,
feature: Vec<u8>,
}
impl Reports {
fn for_device(handle: HANDLE) -> Option<Self> {
let mut data = 0;
// SAFETY: the device is open and the output is writable.
if !unsafe { HidD_GetPreparsedData(handle, &mut data) } {
return None;
}
let mut caps = HIDP_CAPS::default();
// SAFETY: `data` was obtained above and is released after its last use.
let status = unsafe { HidP_GetCaps(data, &mut caps) };
unsafe { HidD_FreePreparsedData(data) };
if status != HIDP_STATUS_SUCCESS
|| caps.InputReportByteLength == 0
|| caps.FeatureReportByteLength == 0
{
return None;
}
Some(Self {
input: vec![0; usize::from(caps.InputReportByteLength)],
feature: vec![0; usize::from(caps.FeatureReportByteLength)],
})
}
}
/// Feature report `id` into `buffer` (its first byte), `false` when the
/// pad did not answer. A round trip to the pad, so over Bluetooth it also
/// tells whether the pad is still there.
fn feature(handle: HANDLE, id: u8, buffer: &mut [u8]) -> bool {
buffer.fill(0);
buffer[0] = id;
// SAFETY: the buffer is as long as we say.
unsafe { HidD_GetFeature(handle, buffer.as_mut_ptr().cast(), buffer.len() as u32) }
}
/// Asks for the calibration report: it switches a pad on Bluetooth to
/// full reports (0x31), again after it reconnected; over USB it changes
/// nothing. `false` when the pad did not answer.
fn full_reports(handle: HANDLE, buffer: &mut [u8]) -> bool {
feature(handle, 0x05, buffer)
}
/// Opens the pads not open yet, each with a reader thread.
fn scan() {
let paths = hid_paths();
{
let pads = lock();
// A twin whose pad went away is opened again: over USB, say,
// after the Bluetooth link dropped with the cable still in.
TWINS
.lock()
.unwrap_or_else(PoisonError::into_inner)
.retain(|(path, mac)| {
paths.contains(path) && pads.iter().any(|pad| pad.mac == Some(*mac))
});
}
for path in paths {
// Cheap filter before opening anything: Sony's vendor id is in
// the path, as `vid_054c` (USB) or `vid&0002054c` (Bluetooth).
let lower = String::from_utf16_lossy(&path).to_ascii_lowercase();
if !lower.contains("054c") {
continue;
}
if lock().iter().any(|pad| pad.path == path)
|| TWINS
.lock()
.unwrap_or_else(PoisonError::into_inner)
.iter()
.any(|(twin, _)| *twin == path)
{
continue;
}
let Some((handle, mut reports)) = open(&path) else {
continue;
};
let bluetooth = lower.contains("{00001124-");
// A paired pad that is switched off can still be listed over
// Bluetooth: it does not answer.
if !full_reports(handle, &mut reports.feature) {
tracing::debug!(path = %lower, "DualSense listed but not answering");
// SAFETY: just opened, nothing else has it.
unsafe { CloseHandle(handle) };
continue;
}
let mac = if feature(handle, 0x09, &mut reports.feature) {
mac(&reports.feature)
} else {
None
};
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
let id = {
let mut pads = lock();
let twin = mac.is_some() && pads.iter().any(|pad| pad.mac == mac);
(!twin).then(|| {
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
pads.push(Pad {
id,
path: path.clone(),
mac,
state: None,
});
id
})
};
let Some(id) = id else {
tracing::info!(path = %lower, bluetooth, "DualSense already open over the other transport");
if let Some(mac) = mac {
TWINS
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push((path, mac));
}
// SAFETY: just opened, nothing else has it.
unsafe { CloseHandle(handle) };
continue;
};
tracing::info!(path = %lower, bluetooth, "DualSense connected");
let raw = handle as usize;
if let Err(error) = std::thread::Builder::new()
.name("DualSense reader".into())
.spawn(move || read(raw as HANDLE, id, bluetooth, reports))
{
lock().retain(|pad| pad.id != id);
// SAFETY: just opened, and no reader has it.
unsafe { CloseHandle(handle) };
tracing::warn!(%error, "could not start a DualSense reader");
}
}
}
/// Reads reports until the pad goes away, then forgets it.
fn read(handle: HANDLE, id: u64, bluetooth: bool, mut reports: Reports) {
let set = |state: Option<PadState>| {
if let Some(pad) = lock().iter_mut().find(|pad| pad.id == id) {
pad.state = state;
}
};
// SAFETY: an unnamed manual-reset event; no security attributes.
let event = unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) };
let why = 'pad: loop {
if event.is_null() {
break 'pad "no event";
}
// SAFETY: plain data; only the event is set.
let mut overlapped: OVERLAPPED = unsafe { std::mem::zeroed() };
overlapped.hEvent = event;
let mut got = 0;
// SAFETY: the buffer and `overlapped` outlive the read: every way
// out below waits for it to end first.
let started = unsafe {
ReadFile(
handle,
reports.input.as_mut_ptr(),
reports.input.len() as u32,
std::ptr::null_mut(),
&mut overlapped,
)
};
// SAFETY: plain query.
if started == 0 && unsafe { GetLastError() } != ERROR_IO_PENDING {
break 'pad "read failed";
}
loop {
// SAFETY: the read started above.
let done =
unsafe { GetOverlappedResultEx(handle, &overlapped, &mut got, QUIET_MS, 0) };
if done != 0 {
if got == 0 {
break 'pad "read nothing";
}
break;
}
// SAFETY: plain query.
if unsafe { GetLastError() } != WAIT_TIMEOUT {
break 'pad "read failed";
}
// Silent: whatever was held is not held any more, and the
// pad may be gone without the read failing.
set(None);
if !full_reports(handle, &mut reports.feature) {
// SAFETY: cancel the read and wait for it to end, so
// nothing writes into the input buffer once we return.
unsafe {
CancelIoEx(handle, &overlapped);
GetOverlappedResult(handle, &overlapped, &mut got, 1);
}
break 'pad "not answering";
}
}
if let Some(state) = parse(&reports.input[..got as usize], bluetooth) {
set(Some(state));
}
};
tracing::info!(why, bluetooth, "DualSense disconnected");
lock().retain(|pad| pad.id != id);
// SAFETY: ours, and nothing uses them any more.
unsafe {
if !event.is_null() {
CloseHandle(event);
}
CloseHandle(handle);
}
}
/// The pad at `path` opened for reading, `None` when it is something else
/// or cannot be opened.
fn open(path: &[u16]) -> Option<(HANDLE, Reports)> {
let mut name = path.to_vec();
name.push(0);
// SAFETY: a terminated path; no security attributes or template.
let handle = unsafe {
CreateFileW(
name.as_ptr(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
std::ptr::null(),
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
std::ptr::null_mut(),
)
};
if handle == INVALID_HANDLE_VALUE {
return None;
}
let mut attributes = HIDD_ATTRIBUTES {
Size: size_of::<HIDD_ATTRIBUTES>() as u32,
..Default::default()
};
// SAFETY: an open device and room for its attributes.
let ours = unsafe { HidD_GetAttributes(handle, &mut attributes) }
&& attributes.VendorID == SONY
&& PRODUCTS.contains(&attributes.ProductID);
if ours && let Some(reports) = Reports::for_device(handle) {
return Some((handle, reports));
}
// SAFETY: just opened.
unsafe { CloseHandle(handle) };
None
}
/// The device paths of the HID devices present, without terminators.
fn hid_paths() -> Vec<Vec<u16>> {
let mut paths = Vec::new();
// SAFETY: plain queries into buffers we own; the list is destroyed
// before returning.
unsafe {
let mut guid = std::mem::zeroed();
HidD_GetHidGuid(&mut guid);
let set = SetupDiGetClassDevsW(
&guid,
std::ptr::null(),
std::ptr::null_mut(),
DIGCF_PRESENT | DIGCF_DEVICEINTERFACE,
);
if set == INVALID_HANDLE_VALUE as isize {
return paths;
}
for index in 0.. {
let mut interface = SP_DEVICE_INTERFACE_DATA {
cbSize: size_of::<SP_DEVICE_INTERFACE_DATA>() as u32,
..std::mem::zeroed()
};
if SetupDiEnumDeviceInterfaces(set, std::ptr::null(), &guid, index, &mut interface)
== 0
{
break;
}
let mut size = 0;
SetupDiGetDeviceInterfaceDetailW(
set,
&interface,
std::ptr::null_mut(),
0,
&mut size,
std::ptr::null_mut(),
);
if size == 0 {
continue;
}
// u64s keep the detail's alignment.
let mut buffer = vec![0u64; (size as usize).div_ceil(8)];
let detail = buffer
.as_mut_ptr()
.cast::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>();
(*detail).cbSize = size_of::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>() as u32;
if SetupDiGetDeviceInterfaceDetailW(
set,
&interface,
detail,
size,
std::ptr::null_mut(),
std::ptr::null_mut(),
) == 0
{
continue;
}
let start = std::ptr::addr_of!((*detail).DevicePath).cast::<u16>();
let room = (size as usize
- std::mem::offset_of!(SP_DEVICE_INTERFACE_DETAIL_DATA_W, DevicePath))
/ 2;
let wide = std::slice::from_raw_parts(start, room);
let end = wide.iter().position(|&c| c == 0).unwrap_or(room);
paths.push(wide[..end].to_vec());
}
SetupDiDestroyDeviceInfoList(set);
}
paths
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn automatic_input_prefers_the_remapper_in_any_slot_and_falls_back_to_hid() {
let physical = PadState {
buttons: A,
..PadState::default()
};
let remapped = PadState {
buttons: Y,
..PadState::default()
};
let mut assigned = [None; super::super::PADS];
let none = [None; super::super::PADS];
let xinput = [None, None, Some(remapped), None];
assert_eq!(
slots(Mode::Auto, none, &mut assigned, || vec![(1, physical)])[0],
Some(physical)
);
assert_eq!(
slots(Mode::Auto, xinput, &mut assigned, || panic!(
"HID not needed"
)),
xinput
);
assert_eq!(
slots(Mode::Off, none, &mut assigned, || panic!("HID disabled")),
none
);
assert_eq!(
slots(Mode::Auto, none, &mut assigned, || vec![(2, physical)])[0],
Some(physical)
);
}
#[test]
fn a_surviving_hid_pad_keeps_its_slot_through_disconnect_and_reconnect() {
let a = PadState {
buttons: A,
..PadState::default()
};
let b = PadState {
buttons: B,
..PadState::default()
};
let x = PadState {
buttons: X,
..PadState::default()
};
let xinput = [None, Some(x), None, None];
let mut assigned = [None; super::super::PADS];
assert_eq!(
slots(Mode::Both, xinput, &mut assigned, || vec![(7, a), (8, b)]),
[Some(a), Some(x), Some(b), None]
);
assert_eq!(
slots(Mode::Both, xinput, &mut assigned, || vec![(8, b)]),
[None, Some(x), Some(b), None]
);
assert_eq!(
slots(Mode::Both, xinput, &mut assigned, || vec![(8, b), (9, a)]),
[Some(a), Some(x), Some(b), None]
);
}
#[test]
fn the_pairing_report_holds_the_address() {
let mut pairing = [0u8; 20];
pairing[0] = 0x09;
pairing[1..7].copy_from_slice(&[1, 2, 3, 4, 5, 6]);
assert_eq!(mac(&pairing), Some([1, 2, 3, 4, 5, 6]));
// a pad that answered with nothing cannot be told apart
assert_eq!(mac(&[0x09; 1]), None);
assert_eq!(mac(&[0x09, 0, 0, 0, 0, 0, 0]), None);
}
#[test]
fn a_usb_report_reads_as_a_pad() {
let mut report = [0u8; 64];
report[0] = 0x01;
report[1..5].copy_from_slice(&[0, 255, 128, 128]); // left stick: left, down
report[5] = 255; // L2
report[8] = 0x20 | 2; // cross, D-pad right
report[9] = 0x20 | 0x01; // options, L1
let pad = parse(&report, false).unwrap();
assert_eq!(pad.buttons, A | RIGHT | MENU | LEFT_SHOULDER);
assert_eq!(
(pad.left_x, pad.left_y, pad.left_trigger),
(-1.0, -1.0, 1.0)
);
assert!(pad.right_x.abs() < 0.01 && pad.right_y.abs() < 0.01);
}
#[test]
fn bluetooth_reports_read_one_byte_further_in() {
let mut report = [0u8; 78];
report[0] = 0x31;
report[2..6].copy_from_slice(&[128, 0, 255, 128]); // left up, right right
report[7] = 255; // R2
report[9] = 0x80 | 8; // triangle, D-pad centred
let pad = parse(&report, true).unwrap();
assert_eq!(pad.buttons, Y);
assert_eq!(
(pad.left_y, pad.right_x, pad.right_trigger),
(1.0, 1.0, 1.0)
);
// the same bytes over USB are not a pad report
assert_eq!(parse(&report, false), None);
}
#[test]
fn the_short_bluetooth_report_reads_too() {
let mut report = [0u8; 78];
report[0] = 0x01;
report[1..5].copy_from_slice(&[128; 4]);
report[5] = 0x40 | 4; // circle, D-pad down
report[7] = 0x02; // touchpad click
report[8] = 128; // L2 halfway
let pad = parse(&report, true).unwrap();
assert_eq!(pad.buttons, B | DOWN | VIEW);
assert!((pad.left_trigger - 0.5).abs() < 0.01);
}
}
File diff suppressed because it is too large. Load diff
@@ -501,6 +501,8 @@ pub fn wait_for_previous() {
}
fn end() {
// A pad left rumbling would run on until it is switched off.
crate::modules::gameinput::stop_rumble();
// Compiled host pipelines kept for the next run.
#[cfg(windows)]
victory_gpu::pipeline::save_pipeline_cache();
+3 -3
View File
@@ -188,7 +188,7 @@ pub extern "system" fn XMemVirtualAlloc(
if !at.is_null() && asked & 0x400 != 0 {
victory_gpu::title_memory_write_combined(at as usize, size);
}
// (Grand Theft Auto VI asks for its 32-bit heap with kind 0x42000,
// (the game asks for its 32-bit heap with kind 0x42000,
// without the 64 KiB page bits: not `placeholder` above, though the host
// makes a placeholder of it all the same.)
if !at.is_null() && constrained && kind & MEM_COMMIT == 0 && flags & ADDRESS_32BIT != 0 {
@@ -1151,7 +1151,7 @@ fn port_on() -> bool {
}
/// The title's reservations of 64 KiB pages for 32-bit graphics memory:
/// base and bytes (one, of 185 MB, in Grand Theft Auto VI).
/// base and bytes (one, of 185 MB, in the game).
static LOW_RESERVATIONS: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new());
/// Pages given another place in their section so far by [`arrange`], and
@@ -1165,7 +1165,7 @@ static ARRANGED: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
/// reservation), so that the reservation becomes one stretch of the section
/// and the GPU side can open it as one heap.
///
/// Grand Theft Auto VI takes all the pages of its 185 MB heap in one call
/// The game takes all the pages of its 185 MB heap in one call
/// and maps its five pieces in another order than their addresses (run
/// port1-1: "Scattered"). Only fresh slices are exchanged: never mapped,
/// never written (no commit bit), so every page still reads as zeros and
+43 -57
View File
@@ -1,5 +1,5 @@
//! The title's frame rate (`VICTORY_FRAME_INTERVAL_MS`, off without it): the
//! rate Grand Theft Auto VI asks for is a setting of its own, and two
//! rate the game asks for is a setting of its own, and two
//! places in its code are changed at load to read another.
//!
//! What the title does (game_scarlett_master.exe 1.0.2.1, image offsets):
@@ -38,8 +38,9 @@
//! own limiter follow the rate asked for, and +0x2241fd0 returns the rate
//! too (1000 for no limit), so the shortest step follows; the setting
//! itself is left as it is. Each site's bytes, from the load to the store of the frame time, are
//! compared before anything is written; a site whose bytes differ is left
//! alone and said so (another build of the title).
//! compared before anything is written, by their length and BLAKE3 hash (no
//! bytes of the title are kept here); a site whose bytes differ is left alone
//! and said so (another build of the title).
/// The switch: the interval in milliseconds our frame clock ticks at
/// (`victory-gpu`'s `frame`), 0 for no wait at all. `None` if unset or
@@ -89,11 +90,13 @@ pub fn title_interval_us(rate: u32, display_120: bool) -> u32 {
}
/// A read of the setting to change: its offset in the image, what it is,
/// and the bytes there (compared first; the replacement goes at the start).
/// and the length and BLAKE3 hash (hex) of the bytes there, compared first;
/// the replacement goes at the start.
pub struct Site {
pub at: usize,
pub kind: Kind,
pub bytes: &'static [u8],
pub len: usize,
pub hash: &'static str,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -115,30 +118,22 @@ pub const SITES: [Site; 3] = [
Site {
at: 0x1e0fc62,
kind: Kind::Load,
bytes: &[
0x8b, 0x87, 0x10, 0x02, 0x00, 0x00, 0xba, 0xe8, 0x03, 0x00, 0x00, 0xc5, 0xfa, 0x10, 0x0d, 0x9f, 0xa1, 0x34, 0x04, 0xb9, 0xe8,
0x03, 0x00, 0x00, 0x3d, 0xe8, 0x03, 0x00, 0x00, 0x0f, 0x42, 0xd0, 0x85, 0xc0, 0x0f, 0x44, 0xd1, 0xc5, 0xea, 0x2a, 0xc2, 0xc5,
0xf2, 0x5e, 0xc0, 0xc4, 0xe1, 0xfa, 0x2c, 0xc0, 0x89, 0x05, 0x12, 0x88, 0xae, 0x07,
],
len: 56,
hash: "cd1788fdbef9991dd4f69d96f68c438bd9b739b149e532c4839db140f95ad6e7",
},
// +0x22434a0: mov eax, [rsi+210h] ... mov [+0x98f84ac], eax
Site {
at: 0x224359a,
kind: Kind::Load,
bytes: &[
0x8b, 0x86, 0x10, 0x02, 0x00, 0x00, 0xba, 0xe8, 0x03, 0x00, 0x00, 0xc5, 0xfa, 0x10, 0x0d, 0x67, 0x68, 0xf1, 0x03, 0xb9, 0xe8,
0x03, 0x00, 0x00, 0x3d, 0xe8, 0x03, 0x00, 0x00, 0x0f, 0x42, 0xd0, 0x85, 0xc0, 0x0f, 0x44, 0xd1, 0xb1, 0xff, 0xc5, 0xea, 0x2a,
0xc2, 0xc5, 0xf2, 0x5e, 0xc0, 0xc4, 0xe1, 0xfa, 0x2c, 0xc0, 0x89, 0x05, 0xd8, 0x4e, 0x6b, 0x07,
],
len: 58,
hash: "dbf806417dd47b8d671825844b93516843e04d5c43cc3bc157cd473d9b905e50",
},
// +0x2241fd0: cmp dword [rax+210h], 0 ; je ; call ; mov eax, [rax+210h] ; vcvtsi2ss xmm0, xmm0, rax
Site {
at: 0x2241fdb,
kind: Kind::SimRate,
bytes: &[
0x83, 0xb8, 0x10, 0x02, 0x00, 0x00, 0x00, 0x74, 0x12, 0xe8, 0xc7, 0xa1, 0xe0, 0x02, 0x8b, 0x80, 0x10, 0x02, 0x00, 0x00, 0xc4,
0xe1, 0xfa, 0x2a, 0xc0,
],
len: 25,
hash: "8f23569c5501b2bf3c68aab953ce563647a47e6d2c872e4273b51a9d7f2365f1",
},
];
@@ -191,13 +186,13 @@ pub unsafe fn apply(base: usize, size: usize, rate: u32, sites: &[Site]) -> Vec<
let code = replacement(site.kind, rate);
let len = code.len();
let done = (|| {
if site.bytes.len() < len || site.at.checked_add(site.bytes.len()).is_none_or(|end| end > size) {
if site.len < len || site.at.checked_add(site.len).is_none_or(|end| end > size) {
return Patched::Failed("outside the image");
}
let at = base + site.at;
// SAFETY: inside the mapped image (checked above).
let there = unsafe { std::slice::from_raw_parts(at as *const u8, site.bytes.len()) };
if there != site.bytes {
let there = unsafe { std::slice::from_raw_parts(at as *const u8, site.len) };
if blake3::hash(there).to_hex().as_str() != site.hash {
return Patched::Differs;
}
let mut old = 0;
@@ -267,59 +262,49 @@ mod tests {
#[test]
fn the_sites_are_reads_of_the_setting() {
for site in SITES.iter().filter(|s| s.kind == Kind::Load) {
// mov eax, [rdi/rsi+210h]
assert_eq!(site.bytes[0], 0x8b);
assert!(matches!(site.bytes[1], 0x86 | 0x87));
assert_eq!(&site.bytes[2..6], &[0x10, 0x02, 0x00, 0x00]);
// mov edx, 1000 follows; the window ends with the store of eax.
assert_eq!(&site.bytes[6..11], &[0xba, 0xe8, 0x03, 0x00, 0x00]);
assert_eq!(&site.bytes[site.bytes.len() - 6..site.bytes.len() - 4], &[0x89, 0x05]);
// RIP-relative: the store is of +0x98f84ac.
let disp = i32::from_le_bytes(site.bytes[site.bytes.len() - 4..].try_into().unwrap());
let end = site.at + site.bytes.len();
assert_eq!(end as i64 + i64::from(disp), FRAME_US as i64);
}
let sim = SITES.iter().find(|s| s.kind == Kind::SimRate).unwrap();
// cmp dword [rax+210h], 0 ; ... ; mov eax, [rax+210h] at 14 ; vcvtsi2ss at 20
assert_eq!(&sim.bytes[..7], &[0x83, 0xb8, 0x10, 0x02, 0x00, 0x00, 0x00]);
assert_eq!(&sim.bytes[14..20], &[0x8b, 0x80, 0x10, 0x02, 0x00, 0x00]);
assert_eq!(&sim.bytes[20..], &[0xc4, 0xe1, 0xfa, 0x2a, 0xc0]);
fn the_replacements_load_the_rate_and_the_sites_are_hashes() {
let code = replacement(Kind::SimRate, 60);
assert_eq!(code.len() + usize::from(code[6]), 20, "the jump lands on the vcvtsi2ss");
assert_eq!(code.len() + usize::from(code[6]), 20, "the jump lands 20 bytes on (the title's vcvtsi2ss)");
assert_eq!(replacement(Kind::Load, 60), [0xb8, 60, 0, 0, 0, 0x90]);
assert_eq!(replacement(Kind::SimRate, 0)[1..5], 1000u32.to_le_bytes());
for site in &SITES {
assert!(site.hash.len() == 64 && site.hash.bytes().all(|b| b.is_ascii_hexdigit()));
assert!(site.len >= replacement(site.kind, 60).len());
}
}
#[cfg(windows)]
#[test]
fn sites_take_the_rate_and_others_are_left_alone() {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READWRITE, VirtualAlloc, VirtualFree};
let site = |at: usize, kind: Kind, bytes: &[u8]| Site {
at,
kind,
len: bytes.len(),
hash: Box::leak(blake3::hash(bytes).to_hex().to_string().into_boxed_str()),
};
// SAFETY: fresh memory of our own, written and run inside it.
unsafe {
let place = VirtualAlloc(std::ptr::null(), 0x10000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as *mut u8;
assert!(!place.is_null());
let bytes = SITES[0].bytes;
// Windows of bytes of our own (int3s): one as expected, one that differs.
let bytes: Vec<u8> = (0..56).map(|n| if n % 7 == 0 { 0x90 } else { 0xcc }).collect();
std::ptr::copy_nonoverlapping(bytes.as_ptr(), place.add(0x100), bytes.len());
let mut other = SITES[1].bytes.to_vec();
other[2] = 0x14; // [rsi+214h]
let mut other = bytes.clone();
other[2] = 0x14;
std::ptr::copy_nonoverlapping(other.as_ptr(), place.add(0x200), other.len());
// The simulation's rate as a function: rax = settings (+0x210 = 30),
// the window, ret.
let settings = [30u32; 0x100];
let sim = SITES[2].bytes;
let mut f = vec![0x48, 0xb8];
f.extend((settings.as_ptr() as u64).to_le_bytes());
let window_at = f.len();
f.extend(sim);
// The simulation's rate as a function: 20 bytes, then vcvtsi2ss
// xmm0, xmm0, rax and ret; the replacement jumps over the 20.
let mut sim = vec![0xcc_u8; 20];
sim.extend([0xc4, 0xe1, 0xfa, 0x2a, 0xc0]);
let mut f = sim.clone();
f.push(0xc3);
std::ptr::copy_nonoverlapping(f.as_ptr(), place.add(0x300), f.len());
let mine = [
Site { at: 0x100, kind: Kind::Load, bytes },
Site { at: 0x200, kind: Kind::Load, bytes: SITES[1].bytes },
Site { at: 0x300 + window_at, kind: Kind::SimRate, bytes: sim },
Site { at: 0xfff0, kind: Kind::Load, bytes },
site(0x100, Kind::Load, &bytes),
Site { at: 0x200, ..site(0x200, Kind::Load, &bytes) },
site(0x300, Kind::SimRate, &sim),
site(0xfff0, Kind::Load, &bytes),
];
let done = apply(place as usize, 0x10000, 60, &mine);
assert_eq!(done[..3], [Patched::Done, Patched::Differs, Patched::Done]);
@@ -334,3 +319,4 @@ mod tests {
}
}
}
+73 -2
View File
@@ -62,8 +62,74 @@ fn err(e: windows::core::Error) -> String {
e.message().to_string()
}
/// The graphics card runs use: the first hardware adapter whose name holds
/// `VICTORY_ADAPTER` (any case), else the hardware adapter with the most
/// memory of its own. Windows' first adapter is often an integrated GPU (a
/// monitor on the board's outputs, a laptop), and a device made with no
/// adapter named runs there. The warm-up, the game's device and DLSS take the
/// same card, so the driver's saved pipelines are the card's that plays.
/// None: no hardware adapter (the default device is made then).
pub fn hardware_adapter() -> Option<(IDXGIAdapter1, String, u64)> {
// SAFETY: plain DXGI queries.
unsafe {
let factory: IDXGIFactory1 = CreateDXGIFactory1().ok()?;
let mut all = Vec::new();
for i in 0.. {
let Ok(adapter) = factory.EnumAdapters1(i) else { break };
let Ok(desc) = adapter.GetDesc1() else { continue };
if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 {
continue;
}
let len = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len());
all.push((adapter, String::from_utf16_lossy(&desc.Description[..len]), desc.DedicatedVideoMemory as u64));
}
pick_adapter(all, std::env::var("VICTORY_ADAPTER").ok().as_deref())
}
}
/// The adapter `hardware_adapter` takes from (adapter, name, own memory).
fn pick_adapter<A>(all: Vec<(A, String, u64)>, named: Option<&str>) -> Option<(A, String, u64)> {
let named = named.map(str::trim).filter(|n| !n.is_empty()).map(str::to_lowercase);
let mut best: Option<(A, String, u64)> = None;
for a in all {
if let Some(n) = &named
&& a.1.to_lowercase().contains(n.as_str())
{
return Some(a);
}
if best.as_ref().is_none_or(|b| a.2 > b.2) {
best = Some(a);
}
}
best
}
#[cfg(test)]
mod adapter_tests {
use super::pick_adapter;
fn cards() -> Vec<((), String, u64)> {
vec![
((), "Intel(R) Graphics".to_owned(), 128 << 20),
((), "NVIDIA GeForce RTX 4070 Ti".to_owned(), 12 << 30),
((), "AMD Radeon(TM) Graphics".to_owned(), 512 << 20),
]
}
#[test]
fn the_card_with_the_most_own_memory_unless_one_is_named() {
assert_eq!(pick_adapter(cards(), None).unwrap().1, "NVIDIA GeForce RTX 4070 Ti");
assert_eq!(pick_adapter(cards(), Some(" ")).unwrap().1, "NVIDIA GeForce RTX 4070 Ti");
assert_eq!(pick_adapter(cards(), Some("intel")).unwrap().1, "Intel(R) Graphics");
// A name no card has: the rule as without one.
assert_eq!(pick_adapter(cards(), Some("arc b580")).unwrap().1, "NVIDIA GeForce RTX 4070 Ti");
assert!(pick_adapter(Vec::<((), String, u64)>::new(), None).is_none());
}
}
impl Host {
/// The default adapter, or WARP with `warp` (or `VICTORY_WARP=1`).
/// The card `hardware_adapter` takes (else the default adapter), or WARP
/// with `warp` (or `VICTORY_WARP=1`).
pub fn new(warp: bool) -> Result<Self, String> {
let warp = warp || std::env::var("VICTORY_WARP").is_ok_and(|v| v == "1");
// SAFETY: plain D3D12/DXGI calls with valid out pointers.
@@ -85,7 +151,12 @@ impl Host {
let adapter: IDXGIAdapter = factory.EnumWarpAdapter().map_err(err)?;
D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?;
} else {
D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?;
if let Some((adapter, ..)) = hardware_adapter() {
let _ = D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device);
}
if device.is_none() {
D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?;
}
// A machine without a graphics card gives the software
// adapter as its default device (a hosted test runner,
// whose first adapter is a display stub that cannot make a
+315 -14
View File
@@ -377,6 +377,8 @@ struct Lower<'a> {
meeting: Option<V>,
/// With `pairs`: the LDS accesses that need no meeting ([`LdsOrder`]).
lds_unordered: HashSet<(usize, usize)>,
/// LDS atomics in loops that get no meeting ([`LdsOrder::looped`]).
lds_looped: HashSet<(usize, usize)>,
/// With `pairs`: the console waves of the group, and the first of this console wave's
/// exchange dwords ([`Self::exchange_dword`], made in the entry block).
pair_waves: u32,
@@ -525,7 +527,10 @@ fn lane_regions_of(st: &Structured, group: bool) -> Option<Vec<(usize, Vec<bool>
let mut regions = Vec::new();
for (d, e) in st.exits.iter().enumerate() {
let LaneExit::Branch { when, .. } = *e else { continue };
if st.wide.contains(&d) && !group || st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) {
// (a branch each host wave takes for itself separates the halves of a console wave)
if st.wide.contains(&d) && !st.host_wide.contains(&d) && !group
|| st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_)))
{
continue; // a wave-wide or uniform branch: all lanes go the same way
}
// blocks reachable from the lane branch that do not post-dominate it
@@ -558,6 +563,57 @@ pub(super) fn branches_around(st: &Structured, needs: &[usize]) -> Option<Vec<us
Some(out)
}
/// The per-lane branches (by block) that close a loop or leave one, whose wave-wide meaning
/// is known ([`Structured::wave_any`]): the ones a host wave takes together
/// ([`crate::structure::structure_wide_host`]) so that its lanes stay one wave behind the
/// loop. Not the branches the wave takes together already, nor those on scalar conditions.
pub(super) fn loop_branches(p: &Program, st: &Structured) -> HashSet<usize> {
let n = p.blocks.len();
let mut rpo = vec![usize::MAX; n];
for (i, b) in crate::ir::reverse_postorder(&p.blocks).into_iter().enumerate() {
rpo[b] = i;
}
let succ = |b: usize| -> Vec<usize> {
match p.blocks[b].exit {
Exit::Jump(t) => vec![t],
Exit::Branch { taken, not_taken } => vec![taken, not_taken],
_ => Vec::new(),
}
};
let mut out = HashSet::new();
for latch in (0..n).filter(|&b| rpo[b] != usize::MAX) {
for head in succ(latch).into_iter().filter(|&h| rpo[h] <= rpo[latch]) {
// the loop's blocks: the head, and what reaches the latch without passing it
let mut body = vec![false; n];
body[head] = true;
let mut stack = vec![latch];
while let Some(b) = stack.pop() {
if body[b] {
continue;
}
body[b] = true;
stack.extend(p.blocks[b].preds.iter().copied().filter(|&q| rpo[q] != usize::MAX));
}
for b in (0..n).filter(|&b| body[b]) {
let LaneExit::Branch { when, taken, not_taken } = st.exits[b] else { continue };
let leaves = !body[taken] || !body[not_taken] || b == latch;
let per_lane = !st.wide.contains(&b)
&& !st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_)));
if leaves && per_lane && st.wave_any.get(b).copied().flatten().is_some() {
out.insert(b);
}
}
}
}
out
}
/// Whether accesses outside a program's own shared memory are done as the console does them
/// (reads give 0, writes are dropped; `VICTORY_LDS_BOUNDS=0`: taken as inside, as before).
fn lds_bounds() -> bool {
!std::env::var("VICTORY_LDS_BOUNDS").is_ok_and(|v| v.trim() == "0")
}
/// Whether a refusal is of code that needs every lane of the wave where it stands (two host
/// waves meeting there), which the other forms of the program may give it.
pub(super) fn needs_every_lane(what: &str) -> bool {
@@ -570,6 +626,11 @@ pub(super) fn take_needs() -> Vec<usize> {
NEEDS.take()
}
/// Puts back what [`take_needs`] gave (a lowering tried in between is forgotten).
pub(super) fn set_needs(needs: Vec<usize>) {
NEEDS.set(needs);
}
fn need(block: usize) {
NEEDS.with_borrow_mut(|n| {
if !n.contains(&block) {
@@ -993,6 +1054,28 @@ pub(super) struct LdsOrder {
/// Of `unordered`, the reads near an LDS atomic: the two halves of a console wave may see
/// different values there ([`lane_uniform`] does not take them as alike).
pub(super) unstable: HashSet<(usize, usize)>,
/// LDS atomics in a loop that no plain LDS write or read leads into or stands in: they get
/// no meeting of the host waves ([`loop_atomics_on`]), with or without
/// [`with_pair_meetings`].
///
/// A meeting is a group barrier, and the host waves take a loop each on its own
/// (`crate::structure::structure_wide_host`, or lane by lane): one that makes fewer rounds
/// stands at the barrier behind the loop while the others stand at the one inside it, the
/// host lets them all go on, and the first reads what the others have not written yet.
/// Seen in `CS_SortRayTiles` (the cloud pass, 256 threads, the game, build 1.0.2.1; captures
/// cloud3 and cloud4, RTX 4070 SUPER): its counting and its scattering loop take 15
/// entries a thread, the last threads none; the host waves of those read the bins' counts
/// while the others still counted, the places they worked out overlapped, and of the 1,068
/// tiles of the sorted class 971 were left (644: 605), the others written over or never
/// moved. A tile that is not in the list gets no ray: a square of clear sky in a cloud,
/// 8 by 4 of the clouds' pixels, until a later frame traces it (seen for a second or two
/// after a cut, when no earlier frame's cloud stands in).
///
/// Without the meeting the atomic's order against the accesses around the loop is kept by
/// their own meetings and the title's barriers: what comes before the loop is asked for
/// here (nothing but atomics, back to a barrier), and what comes behind it meets first,
/// which every thread does only once its loop is done.
pub(super) looped: HashSet<(usize, usize)>,
}
/// [`LdsOrder`] of `p`: the program cut at its `s_barrier`s into pieces joined by the edges
@@ -1075,6 +1158,10 @@ pub(super) fn lds_order(p: &crate::ir::Program, st: &Structured) -> LdsOrder {
.collect();
let writes = near.iter().any(|a| a.2 == Kind::Write);
let atomics = near.iter().any(|a| a.2 == Kind::Atomic);
// (on a cycle, and nothing but atomics in it and in what leads to it)
if fwd[k] && (0..pieces).filter(|&x| x == k || bwd[x]).flat_map(|x| accesses[x].iter()).all(|a| a.2 == Kind::Atomic) {
out.looped.extend(accesses[k].iter().map(|a| (a.0, a.1)));
}
for &(b, i, kind) in &accesses[k] {
let ordered = match kind {
Kind::Read | Kind::Atomic => writes,
@@ -1338,6 +1425,13 @@ fn linear_clamp_sampler(words: &[u32]) -> bool {
s.filter & !1 == 0x14 && s.address == [3, 3, 3]
}
/// Whether LDS atomics in loops go without a meeting of the host waves ([`LdsOrder::looped`];
/// `VICTORY_LDS_LOOP_ATOMICS=0`: they meet, as before 2026-11-27).
fn loop_atomics_on() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_LDS_LOOP_ATOMICS").is_none_or(|v| v != "0"))
}
/// `VICTORY_WAVE_OWN_BITS=0`: a wave OR where not every lane runs is refused as before
/// ([`super::own_bits`]).
fn own_bits_on() -> bool {
@@ -1658,10 +1752,19 @@ impl<'a> Lower<'a> {
let mut pairs: Option<u32> = None;
let mut pair_waves = 0;
// (and only around the LDS accesses whose order counts)
let lds_order = if PAIR_MEETINGS.get() { lds_order(p, x.st) } else { LdsOrder::default() };
let lds_order = {
let all = if PAIR_MEETINGS.get() || loop_atomics_on() { lds_order(p, x.st) } else { LdsOrder::default() };
let looped = if loop_atomics_on() { all.looped } else { HashSet::new() };
if PAIR_MEETINGS.get() {
LdsOrder { looped, unordered: all.unordered, unstable: all.unstable }
} else {
LdsOrder { looped, ..LdsOrder::default() }
}
};
if let StageIo::Cs(cs) = x.native.io {
s.threads = Some(cs.threads);
s.lds_dwords = cs.lds_bytes() / 4;
s.title_lds_dwords = s.lds_dwords;
// Code reading other lanes needs the console's wave size and
// lane order; so do lane masks read as numbers, and LDS shared
// within one wave, where the console compiler leaves out barriers.
@@ -1847,6 +1950,7 @@ impl<'a> Lower<'a> {
s.prims = x.prims.clone();
s.threads = Some([ms.threads, 1, 1]);
s.lds_dwords = ms.lds_bytes.div_ceil(4);
s.title_lds_dwords = s.lds_dwords;
s.mesh = Some(super::shader::Mesh {
max_vertices: ms.max_vertices,
max_primitives: ms.max_primitives,
@@ -1979,6 +2083,7 @@ impl<'a> Lower<'a> {
pairs,
meeting: None,
lds_unordered: lds_order.unordered.clone(),
lds_looped: lds_order.looped.clone(),
pair_waves,
pair_base: None,
flat: None,
@@ -4760,6 +4865,19 @@ impl<'a> Lower<'a> {
fn wave_wide(&mut self, b: usize, when: Bool) -> Result<V, Why> {
const WHY: Why = "a wave-wide branch where not every lane runs";
let any = self.x.st.wave_any.get(b).copied().flatten().ok_or("a wave-wide branch on a scalar condition")?;
if self.x.st.host_wide.contains(&b) {
// A loop's branch each host wave takes for itself: the host wave's own answer.
// Its lanes then leave the loop together and are one wave behind it. A host wave
// whose lanes are all done goes on while the other half of its console wave
// still loops: the console would run the loop's code with those lanes off, which
// changes nothing of theirs.
let c = self.cur;
let mine = self.boolean(when, c)?;
let i1t = self.s.t.i1;
self.s.flags |= flags::WAVE_OPS;
let (name, code) = if any { ("waveAnyTrue", 113) } else { ("waveAllTrue", 114) };
return Ok(self.s.op(c, name, Attr::NoUnwind, i1t, code, &[mine]));
}
if self.exchange.is_none() && self.halves.is_none() && self.console_lanes && self.mask_data == MaskData::Console {
// The host's waves are the console's: the wave's own answer. The lanes that are
// elsewhere have no bit set, as on the console, so "some lane" needs no one but
@@ -5389,6 +5507,114 @@ impl<'a> Lower<'a> {
.collect()
}
/// An LDS write (instruction `i` of block `b`) that is the thread group's set-up of its
/// shared memory: constants to a constant address, under `v_cmpx_eq_u32 exec, 0, <the
/// thread's place in its group>`, so by the group's first thread alone. Gives that
/// thread's test and (byte address, constant) per dword written.
///
/// The console runs it only if the first thread's lane still runs there: a group whose
/// first thread has left (its pixel is not water, say) starts from what the group before
/// it left in LDS, which on the console is the neighbouring tile's sane values and on a
/// PC card is anything. Seen in `water_shading:CS_TransmissionVolumetrics_Tiled`
/// (the game, build 1.0.2.1, capture water3, RTX 4070 SUPER): it keeps the tile's least and
/// greatest depth in LDS, set to "none yet" by thread (0,0) after the lanes off the water
/// have left; of 124 tiles whose first pixel was not water 71 wrote nothing (dark slabs
/// on the water along the horizon and beside rocks, plants and hulls), of 3,250 others
/// none. Here the first thread always sets it up (`VICTORY_LDS_FIRST_INIT=0`: as the
/// console, only if its lane runs): the tile then works from its own depths alone.
fn first_thread_init(
&mut self,
b: usize,
i: usize,
addr: Option<&Operand>,
data: &[Operand],
elements: &[(u32, u32)],
) -> Option<(V, Vec<(u32, u32)>)> {
if std::env::var("VICTORY_LDS_FIRST_INIT").is_ok_and(|v| v.trim() == "0") {
return None;
}
let StageIo::Cs(cs) = self.x.native.io else { return None };
let p = self.x.p;
let insts = &p.blocks[b].insts;
// the compare that left EXEC as it is at the write
let j = (0..i).rev().find(|&j| insts[j].write(Reg::S(EXEC)).is_some())?;
let Fields::Valu(cmp) = &insts[j].fields else { return None };
if insts[j].name() != "v_cmpx_eq_u32" {
return None;
}
let place = match cmp.src.as_slice() {
[Operand::Const(128), Operand::Vector { reg, .. }] | [Operand::Vector { reg, .. }, Operand::Const(128)] => {
insts[j].read(Reg::V(*reg))?
}
_ => return None,
};
// ... of the thread's place: its x, or x | y (| z), as the program entered with them
let input = |v: Value| p.inputs.iter().find(|i| i.1 == v).and_then(|i| match i.0 {
Reg::V(c @ 0..=2) => Some(c),
_ => None,
});
let mut parts: Vec<u8> = Vec::new();
let mut open = vec![place];
while let Some(v) = open.pop() {
if let Some(c) = input(v) {
parts.push(c);
continue;
}
let made = p.blocks.iter().flat_map(|blk| &blk.insts).find(|k| k.writes.iter().any(|w| w.1 == v))?;
let Fields::Valu(or) = &made.fields else { return None };
if made.name() != "v_or_b32" || or.sdwa.is_some() || or.dpp.is_some() {
return None;
}
for op in &or.src {
let Operand::Vector { reg, .. } = op else { return None };
open.push(made.read(Reg::V(*reg))?);
}
if parts.len() + open.len() > 3 {
return None;
}
}
// (every dimension of the group that has more than one thread is tested)
if (0..3u8).any(|c| cs.threads[usize::from(c)] > 1 && !parts.contains(&c)) {
return None;
}
// the address and what is written: constants moved in since the compare
let constant = |op: &Operand| -> Option<u32> {
let Operand::Vector { reg, .. } = *op else { return None };
let k = (j + 1..i).rev().find(|&k| insts[k].write(Reg::V(reg)).is_some())?;
let Fields::Valu(mov) = &insts[k].fields else { return None };
if insts[k].name() != "v_mov_b32" || mov.sdwa.is_some() || mov.dpp.is_some() {
return None;
}
match mov.src.as_slice() {
[Operand::Const(c)] => crate::resource::inline(*c),
[Operand::Literal(x)] => Some(*x),
_ => None,
}
};
let at = constant(addr?)?;
let mut out = Vec::new();
for (e, &(off, w)) in elements.iter().enumerate() {
if w != 1 {
return None;
}
let bytes = at.checked_add(off)?;
if bytes % 4 != 0 || bytes / 4 >= cs.lds_bytes() / 4 {
return None;
}
out.push((bytes, constant(data.get(e)?)?));
}
// the first thread: every coordinate is 0, so its index in the group is
let flat = if self.console_lanes {
self.s.flags |= flags::WAVE_OPS;
self.console_thread()
} else {
let (e, i32t) = (self.s.entry, self.s.t.i32);
self.s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, &[])
};
let (c, zero) = (self.cur, self.s.m.i32(0));
Some((self.s.m.cmp(c, pred::EQ, flat, zero), out))
}
/// LDS (thread-group shared memory) and `ds_swizzle`.
fn ds(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
let Fields::Ds {
@@ -5502,16 +5728,55 @@ impl<'a> Lower<'a> {
return Err("LDS the program does not allocate");
}
let a = self.vgprs(inst, addr.as_ref().ok_or("an LDS address")?, 1)?[0];
// shortcut: LDS addresses are taken as dword-aligned and in bounds
// (out-of-bounds console accesses read 0 and drop writes).
let dword = |l: &mut Self, bytes: u32| -> V {
// shortcut: LDS addresses are taken as dword-aligned.
// Outside the program's shared memory the console reads 0 and drops writes; group-shared
// memory of the host is undefined there (and behind the program's dwords lie ours).
// So: the dword's place, and whether it is inside (`None`: not asked; the place is then
// taken as inside, as before 2026-11-27, `VICTORY_LDS_BOUNDS=0`). A place outside is
// given as the last dword inside: reads of it are replaced by 0, writes left out.
// Seen in `CS_SortRayTiles` (the cloud pass's sort of its ray tiles, 256 threads a group):
// a counting sort over 256 bins in LDS, the bin a thread clears and reads addressed by
// its number in the whole dispatch. Of the 32 groups dispatched only the first has
// entries of its own to sort; the 31 others clear and read at up to 32 KiB behind their
// 2.5 KiB.
// (The squares of clear sky that show in clouds for a second or two after a cut are not
// this: they were there with and without the bounds, captures cloud3 and cloud4 of
// 2026-11-27. The list those captures hold, 7,200 dwords, is two lists of 3,600 one
// behind the other, the tiles with cloud in them and those without; all 3,680 tiles of
// the frame were in it once each in cloud4.)
let limit = if lds_bounds() { self.s.title_lds_dwords } else { 0 };
let dword = |l: &mut Self, bytes: u32| -> (V, Option<V>) {
let c = l.cur;
let o = l.s.m.i32(bytes);
let at = l.s.m.bin(c, Bin::Add, a, o);
let two = l.s.m.i32(2);
let index = l.s.m.bin(c, Bin::LShr, at, two);
let lds = l.s.lds();
l.s.m.element(c, lds, index)
if limit == 0 {
return (l.s.m.element(c, lds, index), None);
}
let end = l.s.m.i32(limit);
let inside = l.s.m.cmp(c, pred::IULT, index, end);
let last = l.s.m.i32(limit - 1);
let index = l.s.m.select(c, inside, index, last);
(l.s.m.element(c, lds, index), Some(inside))
};
// (a guard and "inside" together; what a read gives outside)
let both = |l: &mut Self, guard: Option<V>, inside: Option<V>| -> Option<V> {
match (guard, inside) {
(Some(g), Some(i)) => Some(l.s.m.bin(l.cur, Bin::And, g, i)),
(g, None) => g,
(None, i) => i,
}
};
let read = |l: &mut Self, x: V, inside: Option<V>| -> V {
match inside {
Some(i) => {
let zero = l.s.m.i32(0);
l.s.m.select(l.cur, i, x, zero)
}
None => x,
}
};
let width = |n: &str| match n.rsplit('_').next() {
Some("b64") => 2,
@@ -5545,7 +5810,7 @@ impl<'a> Lower<'a> {
|| name.ends_with("_d16_hi")
});
if let Some(bits) = sub {
let p = dword(self, offset);
let (p, inside) = dword(self, offset);
let o = self.s.m.i32(offset);
let at = self.s.m.bin(c, Bin::Add, a, o);
let three = self.s.m.i32(3);
@@ -5555,6 +5820,7 @@ impl<'a> Lower<'a> {
if name.starts_with("ds_read") {
let reg = dst_reg.ok_or("an LDS read result")?;
let w = self.s.m.load(c, p);
let w = read(self, w, inside);
let x = self.s.m.bin(c, Bin::LShr, w, sh);
let x = if base.contains("_i") {
let k = self.s.m.i32(32 - bits);
@@ -5597,6 +5863,7 @@ impl<'a> Lower<'a> {
let ones = self.s.m.i32(u32::MAX);
let keep = self.s.m.bin(c, Bin::Xor, m, ones);
use super::bitcode::Rmw;
let guard = both(self, guard, inside);
let at = self.begin_guarded(guard);
self.s.m.atomic(self.cur, Rmw::And, p, keep);
self.s.m.atomic(self.cur, Rmw::Or, p, x);
@@ -5616,8 +5883,9 @@ impl<'a> Lower<'a> {
let mut n = 0;
for (off, w) in elements {
for k in 0..w {
let p = dword(self, off + 4 * k);
let (p, inside) = dword(self, off + 4 * k);
let x = self.s.m.load(self.cur, p);
let x = read(self, x, inside);
self.write(inst, Reg::V(reg + n), x, guard);
n += 1;
}
@@ -5632,6 +5900,18 @@ impl<'a> Lower<'a> {
} else {
return Err("an LDS write of bytes or halves");
};
if let Some((first, constants)) = self.first_thread_init(b, i, addr.as_ref(), data, &elements) {
// The group's first thread sets shared memory up, whether its lane runs or not.
let at = self.begin_guarded(Some(first));
for (bytes, x) in constants {
let (index, x) = (self.s.m.i32(bytes / 4), self.s.m.i32(x));
let lds = self.s.lds();
let ptr = self.s.m.element(self.cur, lds, index);
self.s.m.store(self.cur, ptr, x);
}
self.end_guarded(at, &[]);
return Ok(());
}
let mut stores = Vec::new();
for (e, (off, w)) in elements.into_iter().enumerate() {
let vals = self.vgprs(inst, data.get(e).ok_or("an LDS write")?, w as u8)?;
@@ -5641,8 +5921,10 @@ impl<'a> Lower<'a> {
}
let at = self.begin_guarded(guard);
for (off, x) in stores {
let p = dword(self, off);
let (p, inside) = dword(self, off);
let here = self.begin_guarded(inside);
self.s.m.store(self.cur, p, x);
self.end_guarded(here, &[]);
}
self.end_guarded(at, &[]);
return Ok(());
@@ -5677,7 +5959,20 @@ impl<'a> Lower<'a> {
Some((_, v)) => self.i32_of(v).unwrap_or(self.s.m.i32(0)),
None => self.s.m.i32(0),
};
let p = dword(self, offset);
let (p, inside) = dword(self, offset);
// (outside the memory nothing is done; a lane that runs gets 0 back, as a read does)
let outside = match inside {
Some(i) => {
let zero = self.s.m.i32(0);
let missed = match guard {
Some(g) => self.s.m.select(self.cur, g, zero, outside),
None => zero,
};
self.s.m.select(self.cur, i, outside, missed)
}
None => outside,
};
let guard = both(self, guard, inside);
if let Some(max) = match op.as_str() {
"max_f32" => Some(true),
"min_f32" => Some(false),
@@ -5832,9 +6127,15 @@ impl<'a> Lower<'a> {
&& self.lds_meet.as_ref().is_none_or(|(all, _)| all[b])
&& !self.lds_unordered.contains(&(b, i))
{
// the two host waves of a console wave meet before each LDS access: what the other
// half wrote is visible, and what it still reads is not overwritten
self.meet();
if self.lds_looped.contains(&(b, i)) {
// (in a loop the host waves take each on its own: a fence, no wait)
let (fence, void) = (self.s.m.i32(8), self.s.t.void);
self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[fence]);
} else {
// the two host waves of a console wave meet before each LDS access: what the
// other half wrote is visible, and what it still reads is not overwritten
self.meet();
}
}
// The structure builder's threads take turns through atomics (a tree
// built from its leaves up): what one wrote before its atomic is
@@ -13285,7 +13586,7 @@ impl<'a> Lower<'a> {
&& self.mask_data == MaskData::Console
&& st.scc_some.contains_key(&arg) =>
{
let per_lane = !st.wide.contains(&q)
let per_lane = (!st.wide.contains(&q) || st.host_wide.contains(&q))
&& matches!(st.exits[q], LaneExit::Branch { when, .. }
if !st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))));
if per_lane {
+77 -1
View File
@@ -625,7 +625,7 @@ pub fn emit(
// Both archived kernels use one logical wave per group and have
// validated wave32 PSOs on RTX. Explicit policy wins.
// The volumetric light's two tiled programs (`CS_TransmissionVolumetrics_Tiled`
// and `_Tiled_LocalLights`, GTA VI 1.0.2.1) are of that shape too: groups of 64,
// and `_Tiled_LocalLights`, the game, build 1.0.2.1) are of that shape too: groups of 64,
// an LDS read and write in one lane-branch region, so no other form translates
// them on 32-lane hosts and their dispatches were dropped (no volumetric light
// or fog on NVIDIA). Widened, they translate (4 and 7 branches taken wave-wide).
@@ -897,6 +897,35 @@ fn widen(
}
/// The translated program, and the wave size it requires of the host.
/// Which programs get the branches that close or leave their loops taken by each host wave
/// together where cross-lane code depends on the wave ([`emit_program`]):
/// - unset or `1`: console wave64 compute programs on a host of 32-lane waves;
/// - `2`: every compute program;
/// - `0`: none, as before.
fn loops_wave(native: &NativeProgram) -> bool {
if native.stage != HwStage::Cs {
return false;
}
match std::env::var("VICTORY_LOOPS_WAVE").ok().as_deref().map(str::trim) {
Some("0") => false,
Some("2") => true,
_ => native.wave64 && lower::host_max_wave() == 32,
}
}
/// [`emit_program_plain`]; a program that comes out depending on the host's waves is
/// translated once more with the per-lane branches that close or leave its loops taken by
/// each host wave together ([`structure::structure_wide_host`]), and that translation is the
/// one given if it needs no wider waves.
///
/// Why: the lowering turns the console's wave loops into loops each lane leaves on its own,
/// and takes the code behind a loop as code the whole wave runs together. On NVIDIA the lanes
/// that left a loop early run on as a wave of their own, so a ballot, a first-lane read or an
/// exchange between the halves of a console wave behind the loop saw a part of the wave.
/// Seen in `water_shading:CS_TransmissionVolumetrics_GenerateTiles` (the game, build 1.0.2.1, capture
/// water2): the tiles with local lights never counted themselves in (the lanes without one
/// arrived later and wrote "no lane" over their ballot), their list stayed empty and those
/// tiles of the water kept no light: dark rectangles beside lit objects.
fn emit_program(
c: &Container,
native: &NativeProgram,
@@ -904,6 +933,53 @@ fn emit_program(
st: &structure::Structured,
io: &io::Io,
res: &resource::Resources,
) -> Result<(HostShader, Option<u32>), ShaderError> {
let first = emit_program_plain(c, native, p, st, io, res);
let Ok((_, Some(wave))) = &first else {
return first;
};
if !loops_wave(native) || !st.host_wide.is_empty() {
return first;
}
let loops = lower::loop_branches(p, st);
if loops.is_empty() {
return first;
}
let needs = lower::take_needs();
let again = structure::structure_wide_host(p, &st.wide, &loops).and_then(|st| {
let res = resource::track(p, &native.layout, native.stage, Some(&st))?;
emit_program_plain(c, native, p, &st, io, &res)
});
let why = std::env::var_os("VICTORY_WAVE_WHY").is_some();
match again {
Ok((shader, Some(w))) if w <= *wave => {
if why {
eprintln!("WAVE-LOOPS {} loop branches taken by each host wave together", loops.len());
}
lower::take_needs();
Ok((shader, Some(w)))
}
other => {
if why {
let what = match &other {
Ok((_, w)) => format!("wave {w:?}"),
Err(e) => e.to_string(),
};
eprintln!("WAVE-LOOPS not taken ({} loop branches): {what}", loops.len());
}
lower::set_needs(needs);
first
}
}
}
fn emit_program_plain(
c: &Container,
native: &NativeProgram,
p: &ir::Program,
st: &structure::Structured,
io: &io::Io,
res: &resource::Resources,
) -> Result<(HostShader, Option<u32>), ShaderError> {
let sig = |fourcc| -> Result<Vec<container::SigElement>, ShaderError> {
match c.part(fourcc) {
+3
View File
@@ -233,6 +233,8 @@ pub(crate) struct Shader {
pub wave_size: Option<u32>,
/// Thread-group shared memory, in dwords.
pub lds_dwords: u32,
/// Of those, the program's own (the first ones; ours follow).
pub title_lds_dwords: u32,
lds: Option<V>,
main: V,
pub entry: usize,
@@ -286,6 +288,7 @@ impl Shader {
threads: None,
wave_size: None,
lds_dwords: 0,
title_lds_dwords: 0,
lds: None,
main,
entry,
+165
View File
@@ -837,6 +837,162 @@ pub(crate) fn without_skips(p: &Program, deep: bool) -> Option<Program> {
}
v
};
// Whether the region a skip of `b` leaves out (`inside`, from `first` to `target`) holds a
// loop that never ends once no lane of the wave is left in it. The console never runs the
// region so; without the skip the lanes do, and a loop that finds its end in a block
// behind an inner `s_cbranch_execz` (the compare's SCC; on the way around that block SCC is
// the inner mask operation's "no lane") turns for ever. The lowering's bound on a loop's
// turns then ends the program before what follows the region. Such a skip stays: taken
// wave-wide ([`crate::emit`]'s `widen`) it is the console's.
// Seen in `water_shading:CS_TransmissionVolumetrics_Tiled` (the game, build 1.0.2.1, capture
// water4, RTX 4070 SUPER): the skip at 0x2da8 around the loop at 0x2e60, which writes the
// slices up to the tile's farthest and compares its counter behind the skip at 0x2e6c. A
// tile none of whose lanes took the long path ended at the bound and its 64 pixels got no
// output: 59 of 3,364 water tiles in one frame, most along the horizon, other ones each
// frame (dark tiles that flicker).
// Followed here: what is known with EXEC empty where the region starts (masks saved from
// it and narrowed from it are empty, SCC of such a narrowing is clear), along the branches
// that decides; a chain of decided branches that comes back to where it was, knowing the
// same, never ends.
let stalls = |b: usize, target: usize, first: usize, inside: &[bool]| -> bool {
use std::collections::{BTreeMap, BTreeSet};
// (dwords known to hold no lane, SCC values known)
type Facts = (BTreeSet<Value>, BTreeMap<Value, bool>);
// (block, the block come from, what is known on the way in)
type State = (usize, usize, Facts);
let exec = |r: &(Reg, Value)| matches!(r.0, Reg::S(c) if c == EXEC || c == EXEC + 1);
let none_left = |inst: &Inst, facts: &Facts| {
let mut dwords = inst.reads.iter().filter(|r| exec(r)).peekable();
dwords.peek().is_some() && dwords.all(|r| facts.0.contains(&r.1))
};
let Some(branch) = p.blocks[b].insts.last() else {
return false;
};
let mut facts: Facts = Default::default();
facts.0.extend(branch.reads.iter().filter(|r| exec(r)).map(|r| r.1));
if facts.0.is_empty() {
return false;
}
// The states after (block, from, facts): one if the block's exit is decided (none if
// it leaves the region), else each way on.
let step = |(x, from, mut facts): State| -> (bool, Vec<State>) {
let block = &p.blocks[x];
let at = block.preds.iter().position(|&q| q == from);
let merged: Vec<(Value, bool, Option<bool>)> = block
.phis
.iter()
.map(|phi| match at.and_then(|at| phi.args.get(at)) {
Some(a) => (phi.value, facts.0.contains(a), facts.1.get(a).copied()),
None => (phi.value, false, None),
})
.collect();
let set = |facts: &mut Facts, v: Value, empty: bool, scc: Option<bool>| {
if empty {
facts.0.insert(v);
} else {
facts.0.remove(&v);
}
match scc {
Some(s) => {
facts.1.insert(v, s);
}
None => {
facts.1.remove(&v);
}
}
};
for (v, empty, scc) in merged {
set(&mut facts, v, empty, scc);
}
for inst in &block.insts {
let name = inst.name();
let none = none_left(inst, &facts);
let mut empty = vec![false; inst.writes.len()];
let mut scc = None;
if matches!(name, "s_mov_b32" | "s_mov_b64")
&& inst.reads.len() == inst.writes.len()
&& inst.reads.iter().chain(&inst.writes).all(|r| matches!(r.0, Reg::S(_)))
{
for (e, r) in empty.iter_mut().zip(&inst.reads) {
*e = facts.0.contains(&r.1);
}
} else if none && name.contains("saveexec") {
// (the old EXEC is saved; `and` and `andn1` keep lanes of it only)
let narrows = name.starts_with("s_and_saveexec") || name.starts_with("s_andn1_saveexec");
for (e, w) in empty.iter_mut().zip(&inst.writes) {
*e = match w.0 {
Reg::S(_) if exec(w) => narrows,
Reg::S(_) => true,
_ => false,
};
}
scc = narrows.then_some(false);
} else if none && name.starts_with("v_cmpx") {
empty.fill(true);
}
for (e, w) in empty.into_iter().zip(&inst.writes) {
set(&mut facts, w.1, e, if w.0 == Reg::Scc { scc } else { None });
}
}
let on = |t: usize, facts: Facts| (t != target && inside[t]).then_some((t, x, facts));
match block.exit {
Exit::Jump(t) => (true, on(t, facts).into_iter().collect()),
Exit::Branch { taken, not_taken } => {
let decided = block.insts.last().and_then(|last| match last.name() {
"s_cbranch_execz" => none_left(last, &facts).then_some(taken),
"s_cbranch_execnz" => none_left(last, &facts).then_some(not_taken),
name @ ("s_cbranch_scc0" | "s_cbranch_scc1") => last
.read(Reg::Scc)
.and_then(|v| facts.1.get(&v))
.map(|&s| if s == (name == "s_cbranch_scc1") { taken } else { not_taken }),
_ => None,
});
match decided {
Some(t) => (true, on(t, facts).into_iter().collect()),
None => (
false,
on(taken, facts.clone()).into_iter().chain(on(not_taken, facts)).collect(),
),
}
}
Exit::End | Exit::Indirect => (false, Vec::new()),
}
};
let mut seen: HashSet<State> = HashSet::new();
let mut work = vec![(first, b, facts)];
// (states followed in all; past that the region is taken not to stall, as before)
let mut budget = 20_000u32;
while let Some(start) = work.pop() {
if !seen.insert(start.clone()) {
continue;
}
let mut chain = vec![start.clone()];
let mut at = start;
loop {
budget -= 1;
if budget == 0 {
return false;
}
let (decided, next) = step(at);
if !decided {
work.extend(next);
break;
}
let Some(next) = next.into_iter().next() else {
break;
};
if chain.contains(&next) {
return true;
}
if !seen.insert(next.clone()) {
break;
}
chain.push(next.clone());
at = next;
}
}
false
};
// The region a skip of `b` to `target` leaves out, if it is a pure skip.
let skipped = |b: usize, target: usize, first: usize| -> Option<Vec<bool>> {
let mut inside = vec![false; n];
@@ -885,6 +1041,15 @@ pub(crate) fn without_skips(p: &Program, deep: bool) -> Option<Program> {
if !deep && join.preds.iter().any(|&q| q != b && !inside[q]) {
return None;
}
if stalls(b, target, first, &inside) {
if std::env::var_os("VICTORY_WAVE_WHY").is_some() {
eprintln!(
"WAVE64-SKIP kept at {:#x}: a loop behind it does not end with no lane left",
p.blocks[target].offset.min(p.blocks[first].offset)
);
}
return None;
}
Some(inside)
};
let mut blocks = p.blocks.clone();
+24 -1
View File
@@ -437,6 +437,11 @@ pub struct Structured {
/// Blocks whose closing branch the whole wave takes together ([`structure_wide`]): its
/// `when` is still the lane's own bit; the wave goes by all of them.
pub wide: HashSet<usize>,
/// Those of [`Self::wide`] that each host wave decides for itself, from its own lanes
/// ([`structure_wide_host`]): the branches that close or leave a loop. Two host waves of
/// one console wave may then go different ways, so their blocks are not ones every lane
/// of the console wave runs.
pub host_wide: HashSet<usize>,
/// Per block closed by a branch on a lane mask: whether the console takes it when some
/// lane's `when` holds (`true`) or when every lane's does (`false`).
pub wave_any: Vec<Option<bool>>,
@@ -469,8 +474,22 @@ pub fn structure(program: &Program) -> Result<Structured, ShaderError> {
/// run as two host waves, which exchange that decision and can then meet (a group barrier)
/// inside the branch.
pub fn structure_wide(program: &Program, wide: &HashSet<usize>) -> Result<Structured, ShaderError> {
structure_wide_host(program, wide, &HashSet::new())
}
/// [`structure_wide`], with the branches of `host` taken together too, but by each host wave
/// on its own ([`Structured::host_wide`]). For the branches that close or leave a loop a lane
/// would otherwise leave when its own bit says so: a host whose lanes do not come together
/// again behind such a loop (NVIDIA: lanes that left early run on in a wave of their own)
/// would give the cross-lane code behind it a part of the wave.
pub fn structure_wide_host(
program: &Program,
wide: &HashSet<usize>,
host: &HashSet<usize>,
) -> Result<Structured, ShaderError> {
let mut l = Lanes::new(program)?;
l.wide = wide.clone();
l.wide = wide.union(host).copied().collect();
l.host = host.difference(wide).copied().collect();
loop {
let execs = l.masks_in_order();
let cond = l.paths()?;
@@ -532,6 +551,8 @@ struct Lanes<'a> {
active: HashSet<Value>,
/// See [`Structured::wide`].
wide: HashSet<usize>,
/// See [`Structured::host_wide`].
host: HashSet<usize>,
/// SCC values of [`Self::scc_lane`] that are set when EVERY lane's bit is (`s_cmp_eq` of
/// two masks: "no lane differs"); the others are set when some lane's is.
scc_every: HashSet<Value>,
@@ -615,6 +636,7 @@ impl<'a> Lanes<'a> {
when: vec![None; blocks.len()],
active: HashSet::new(),
wide: HashSet::new(),
host: HashSet::new(),
scc_every: HashSet::new(),
wave_any: vec![None; blocks.len()],
})
@@ -860,6 +882,7 @@ impl<'a> Lanes<'a> {
paired_masks: if self.p.wave64 { self.masks } else { Map::default() },
active: self.active,
wide: self.wide,
host_wide: self.host,
wave_any: self.wave_any,
scc_some: self
.scc_lane
+2 -2
View File
@@ -15,5 +15,5 @@
- **16:04–16:07, confirmation and install.** From a fresh copy of the opening save, the release ran 135 seconds after the first interval above 1,000 draws/frame and remained live until the harness closed it. Peak process commit was 34.42 GiB; the lowest sampled Windows commit headroom was 1.30 GiB. Zero E_OUTOFMEMORY returns and zero Rust allocation aborts appeared in the log. Across 120 high-draw caption intervals the median was 54.3 ms/frame, with 39 at or below 50 ms. The descriptor-slot warning recurred. Installed and hash-verified the release behind the existing `pareto-residency` selector. SHA-256 `d580328bf90fe54e643dad60c04481d7e4b0d7134b9b6ce70c5e0f5c77ff3cf1`. Receipt and log: `../XCL-frame-timing/pareto-residency-comparison/oom-confirm/`.
- **16:50–18:20, facial deformation & wrapped meshes (`d16` + table strides).** Added zero-sweep table view-kind lookup (`SLOT_TABLE_STRIDES = 252`, `heap_strides`) and dynamic descriptor slot stride population in `descriptor/host.rs`, plus NVIDIA-valid typed integer lowering (`bufferLoad.i32`/`bufferStore.i32` on `VIEW_INTEGER`/`VIEW_SIGNED`). Initially applying typed integer branching to non-`d16` typed loads caused shader regressions; restricting integer branching to `buffer_load_format_d16_*` and `buffer_store_format_d16_*` restored clean shading while keeping `VICTORY_TRANSLATOR` cache-compatible with `tools/cache-pareto` (`made=0`).
- **19:15–20:30, commit-gate starvation & synchronous bake uploads.** Lowered commit reserves (`has_upload_reserve`: 256 MiB bake / 512 MiB non-bake; `has_growth_reserve`: 256 MiB bake / 1024 MiB speculative bindless; pressure entry 3 GiB RAM / 4 GiB commit, recovery 5 GiB / 6 GiB), scoped 64 MiB staging-block growth gating in `pool.rs` (`REST = 2500 ms`) to speculative bindless only, expanded bake detection (`BAKE_GEOMETRY_SHADERS`, `ahead::drain`, `BAKE_PAGE_WRITTEN`), and routed one-shot ped/decoration bake uploads through a dedicated synchronous host list (`BAKE_UPLOAD` / `execute_sync_internal`) with post-upload descriptor publication (`prepare_bake_slot` / `publish_uploaded_slot`). GPU suite: 335 passed, 34 ignored.
- **20:50–21:10, alias-flood experiment reverted & clean release built.** Propagating aliased view maps/unmaps into `REMAPPED` and widening bake lookahead caused 2–4 GiB bake-pass truncations on frames 1368–1369 (`cap_alias_fix_rel`, median 70.5 ms in diagnostics capture, face-mask/shorts regression) and was reverted. Rebuilt clean release binary `target/release/victory.exe` without the alias flood (SHA-256 `38e99f1b1d6bafda2ff8de74d6566af06bc7e8cab70594d841af01752e501d73`); installation into `Downloads/leonida/victory-3d-rtx-pareto-residency.exe` deferred while user-launched PID 13544 holds the file open.
- **21:30–22:28, transmission prefilter Wave32 recovery, texture-starvation & scene-blinking fixes.** Diagnosed four linked regressions on RTX 5090 (32 GiB RAM): (1) `alphaResolve:CS_AlphTransmissionPrefilterMip_610a2fad` (`2da4beb386509b77`) was dropped under Wave32 `without_early_outs` because `resource::Tracer::descriptor()` and `live()` omitted per-instruction `lanes.guards[b][i]` when pruning dead join edges, leaving transmission buffer `0x17dff443d70` zeroed and causing `ptfx_PS_Transmission_aba1527f` (dual-source blend) and transmissive eye/alpha shaders to output black squares / corrupted blending; fixed in `crates/victory-shader/src/resource.rs` (`VICTORY_WAVE_WIDE` intentionally kept off due to known loop-widening TDR risk). (2) Completed submissions kept `Detached._state` dynamic descriptor slots pinned across `bury_lag()` (`16` submissions) in `host.rs` (`relay_land`, `settle`), exhausting NVIDIA's 262k dynamic slot pool and dropping draws; added `Detached::release_tables()` right on GPU completion plus a `settle_for_fence()` retry in `draw.rs`, and defaulted `VICTORY_INDIRECT_REST=0` in `indirect.rs` so one oversized indirect record does not zero out subsequent draws. (3) Split residency throttling into mild pressure vs. `critical_commit()` (`< 1536 MiB` commit or upload refusal) across `residency.rs`, `texture/ahead.rs`, and `pool.rs` so `VICTORY_UPLOAD_AHEAD`, `64 MiB/frame` prefetch, and one spare staging block stay active under mild 32 GiB pressure instead of stalling tens of thousands of textures on `neutral()`; fixed `descriptor/host.rs` (`prepare_bake_slot`, `publish_uploaded_slot`) and `draw.rs` (`flush_for_bake`) so pending bake slots are never prematurely overwritten with `neutral()` or silently dropped on defer/unmapped pages, and removed false `address=0x0` unordered-SRV warning spam. (4) Scoped `VICTORY_AMBIENT_AIR=1.5` to `pareto-residency` in `Downloads/leonida/Play-VIctory.cmd` to clear milky indoor ambient haze. Verification: `victory-shader` lib suite 281 passed, 0 failed, 4 ignored (including new `a_guarded_access_excludes_dead_lane_edges_at_a_join`); targeted `victory-gpu` suite 20 passed, 0 failed; RTX 5090 `translate --jobs 1 --validate --pipelines` on 154 VFX/particle/eye shaders emitted & validated 43/43 graphics + 96/111 compute pipelines (recovering `CS_AlphTransmissionPrefilterMip`, 0 regressions). Deployed release binary to `Downloads/leonida/victory-3d-rtx-pareto-residency.exe`, SHA-256 `37a410b13fcd5ef4cecfe2c27761b7132af64b00019a07c9256529b96892d7da`.
- **20:50–21:10, alias-flood experiment reverted & clean release built.** Propagating aliased view maps/unmaps into `REMAPPED` and widening bake lookahead caused 2–4 GiB bake-pass truncations on frames 1368–1369 (`cap_alias_fix_rel`, median 70.5 ms in diagnostics capture, face-mask/shorts regression) and was reverted. Rebuilt clean release binary `target/release/victory.exe` without the alias flood (SHA-256 `38e99f1b1d6bafda2ff8de74d6566af06bc7e8cab70594d841af01752e501d73`); installation into `Downloads/game/victory-3d-rtx-pareto-residency.exe` deferred while user-launched PID 13544 holds the file open.
- **21:30–22:28, transmission prefilter Wave32 recovery, texture-starvation & scene-blinking fixes.** Diagnosed four linked regressions on RTX 5090 (32 GiB RAM): (1) `alphaResolve:CS_AlphTransmissionPrefilterMip_610a2fad` (`2da4beb386509b77`) was dropped under Wave32 `without_early_outs` because `resource::Tracer::descriptor()` and `live()` omitted per-instruction `lanes.guards[b][i]` when pruning dead join edges, leaving transmission buffer `0x17dff443d70` zeroed and causing `ptfx_PS_Transmission_aba1527f` (dual-source blend) and transmissive eye/alpha shaders to output black squares / corrupted blending; fixed in `crates/victory-shader/src/resource.rs` (`VICTORY_WAVE_WIDE` intentionally kept off due to known loop-widening TDR risk). (2) Completed submissions kept `Detached._state` dynamic descriptor slots pinned across `bury_lag()` (`16` submissions) in `host.rs` (`relay_land`, `settle`), exhausting NVIDIA's 262k dynamic slot pool and dropping draws; added `Detached::release_tables()` right on GPU completion plus a `settle_for_fence()` retry in `draw.rs`, and defaulted `VICTORY_INDIRECT_REST=0` in `indirect.rs` so one oversized indirect record does not zero out subsequent draws. (3) Split residency throttling into mild pressure vs. `critical_commit()` (`< 1536 MiB` commit or upload refusal) across `residency.rs`, `texture/ahead.rs`, and `pool.rs` so `VICTORY_UPLOAD_AHEAD`, `64 MiB/frame` prefetch, and one spare staging block stay active under mild 32 GiB pressure instead of stalling tens of thousands of textures on `neutral()`; fixed `descriptor/host.rs` (`prepare_bake_slot`, `publish_uploaded_slot`) and `draw.rs` (`flush_for_bake`) so pending bake slots are never prematurely overwritten with `neutral()` or silently dropped on defer/unmapped pages, and removed false `address=0x0` unordered-SRV warning spam. (4) Scoped `VICTORY_AMBIENT_AIR=1.5` to `pareto-residency` in `Downloads/game/Play-VIctory.cmd` to clear milky indoor ambient haze. Verification: `victory-shader` lib suite 281 passed, 0 failed, 4 ignored (including new `a_guarded_access_excludes_dead_lane_edges_at_a_join`); targeted `victory-gpu` suite 20 passed, 0 failed; RTX 5090 `translate --jobs 1 --validate --pipelines` on 154 VFX/particle/eye shaders emitted & validated 43/43 graphics + 96/111 compute pipelines (recovering `CS_AlphTransmissionPrefilterMip`, 0 regressions). Deployed release binary to `Downloads/game/victory-3d-rtx-pareto-residency.exe`, SHA-256 `37a410b13fcd5ef4cecfe2c27761b7132af64b00019a07c9256529b96892d7da`.