diff --git a/.cargo/config.toml b/.cargo/config.toml index 9741f113e..2cfd6b230 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,7 @@ [alias] xtask = "run --quiet --package xtask --" + +# AVX2, BMI and FMA wherever the compiler finds a use for them (the title's +# own code needs AVX2 already: the consoles' processors have it). +[target.x86_64-pc-windows-msvc] +rustflags = ["-C", "target-cpu=x86-64-v3"] diff --git a/.gitignore b/.gitignore index 65e781aec..b295ae819 100644 --- a/.gitignore +++ b/.gitignore @@ -84,3 +84,6 @@ Thumbs.db # What the F1 menu saved /victory-settings.txt /victory-settings.*.txt + +# The game folder the launch and precache scripts remember (a path on this PC) +/game_dir.txt diff --git a/Cargo.lock b/Cargo.lock index 9a656d8bf..f1095b10e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -248,6 +248,15 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libmimalloc-sys" +version = "0.1.49" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9" +dependencies = [ + "cc", +] + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -275,6 +284,15 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "mimalloc" +version = "0.1.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d4139bb28d14ad1facf21d5eb8825051b326e172d216b39f6d31df53cc97862" +dependencies = [ + "libmimalloc-sys", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -676,6 +694,7 @@ version = "0.1.0" dependencies = [ "anyhow", "blake3", + "mimalloc", "tempfile", "tracing", "victory-formats", diff --git a/Cargo.toml b/Cargo.toml index 4e21b692d..37931b169 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ license = "GPL-3.0-or-later" publish = false [workspace.dependencies] +mimalloc = { version = "0.1", default-features = false } # Internal crates victory-core = { path = "crates/victory-core" } victory-pe = { path = "crates/victory-pe" } @@ -71,9 +72,26 @@ opt-level = 2 [profile.release] debug = "line-tables-only" +# One unit a crate and inlining across crates: the thread that prepares +# submissions spends its frame in small calls from victory-gpu into +# victory-hle and victory-shader and back. +lto = "thin" +codegen-units = 1 # The development build: release code generation plus the `diagnostics` # feature (`cargo build --profile diag -p victory --features diagnostics`), # kept in its own folder so it does not evict the plain release build. [profile.diag] inherits = "release" + +# A build for the PC it is built on: release plus whole-program optimisation +# (`lto`, one code generation unit). Built with the CPU's own instructions +# (`scripts\play-foxhound.ps1 -Build native` sets RUSTFLAGS=-C target-cpu=native: +# AVX-512 on a Ryzen 9000), so the exe may not start on another processor. +# Into target\native, beside the release build, not in its place. Slower to +# build (several minutes more); helps the CPU side (the shader translator, +# hashing, copies), not the card. +[profile.native] +inherits = "release" +lto = "fat" +codegen-units = 1 diff --git a/PRECACHE.cmd b/PRECACHE.cmd new file mode 100644 index 000000000..ddf808cb4 --- /dev/null +++ b/PRECACHE.cmd @@ -0,0 +1,12 @@ +@echo off +rem Precaching: every shader of the title translated and the recorded pipelines built ahead of play, +rem into C:\VictoryCache (VICTORY_SHADER_CACHE_DIR) with the victory.exe VILauncher built. ASCII only. +rem PRECACHE.cmd as above +rem PRECACHE.cmd -GameDir "E:\Game" another game folder (else game_dir.txt, asked once) +setlocal +set "PS1=%~dp0scripts\precache.ps1" +set "PSH=powershell" +where pwsh >nul 2>nul && set "PSH=pwsh" +%PSH% -NoProfile -ExecutionPolicy Bypass -File "%PS1%" %* +echo. +pause diff --git a/README.md b/README.md index e6bd64b3b..351e49b01 100644 --- a/README.md +++ b/README.md @@ -216,6 +216,9 @@ speed, in the picture and in simply being able to play it: card a frame. They are left out there: no blocks and 30 fps instead of 25 on the first boat ride (RTX 5070), with water that is darker and bluer. WATER LIGHT in the menu (`VICTORY_WATER_LIGHT=1`) runs them again. + `--set VICTORY_WATER_VOLUME_PORTALS=1` separately enables an experimental + lowering for the volume-portals compute shader on 32-lane hosts. An explicit + `VICTORY_WAVE_WIDE` setting takes precedence. - **One command to play**: the launcher builds the layer the first time and applies what the menu saved. - **`Get-NVIDIA-DLSS.cmd`**: the eight NVIDIA files that are loaded, about @@ -354,6 +357,9 @@ to check memory on systems with 32 GB of RAM or GPUs with 8 GB of VRAM. - [docs/architecture.md](docs/architecture.md): the layer's parts. - [docs/findings.md](docs/findings.md): measurements behind the choices. - [docs/dlss.md](docs/dlss.md): DLSS and Frame Generation. +- [docs/ryzen-9900x-rtx-3070ti.md](docs/ryzen-9900x-rtx-3070ti.md): a + two-die Ryzen with an 8 GB card: what the layer does for it and the + settings to start from. - [docs/linux-proton.md](docs/linux-proton.md): building on Linux and first runs under Proton (experimental). - [docs/fork-ray-tracing.md](docs/fork-ray-tracing.md): the title's ray tracing @@ -365,6 +371,12 @@ to check memory on systems with 32 GB of RAM or GPUs with 8 GB of VRAM. A tree of other people's work with a little on top; the history is kept. +- **[VIctory-Neo](https://github.com/KyleS98/VIctory-Neo)** by KyleS98, + merged on 2026-11-28 (GPL-3.0-or-later, from the same base, `63b902f`): + translated shaders that wait less, the layer's threads on the die the + title does not use (`VICTORY_OWN_CPUS`), write faults without the write + watch's lock, no loop that keeps the card awake, the reflections' hold + indoors and its speed measurements (docs/speed-methods.md). - **[foxhound](https://github.com/readmet3xt-lab/foxhound)** by readmet3xt-lab: the base of this fork since 2026-11-26, and through it: - **[VIctory](https://github.com/Marvisak/VIctory)** by Marvisak and its diff --git a/apps/victory/Cargo.toml b/apps/victory/Cargo.toml index efaa1091e..0641b505a 100644 --- a/apps/victory/Cargo.toml +++ b/apps/victory/Cargo.toml @@ -22,6 +22,10 @@ clap.workspace = true walkdir.workspace = true [features] +default = ["mimalloc"] +# Our own allocations through mimalloc (`--no-default-features`: the process +# heap, as before). +mimalloc = ["victory-hle/mimalloc"] # Debug-level logs and the debugging switches (frame capture, stack dumps, # the host debug layer, scripted keys). Off in a plain release build. diagnostics = [ diff --git a/apps/victory/build.rs b/apps/victory/build.rs index 1fe647dd4..4c443dffe 100644 --- a/apps/victory/build.rs +++ b/apps/victory/build.rs @@ -8,6 +8,22 @@ //! the `D3D12` folder (or Windows' own, without one) came too late and every //! start asked for 614. Loaded on its first use instead, it reads that version. fn main() { + // The commit this build is of, for the log's first lines (a launcher that + // builds the repository by itself says nothing of which one it built). + let commit = std::process::Command::new("git") + .args(["rev-parse", "--short=10", "HEAD"]) + .output() + .ok() + .filter(|o| o.status.success()) + .and_then(|o| String::from_utf8(o.stdout).ok()) + .map(|s| s.trim().to_owned()) + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| "unknown".to_owned()); + println!("cargo:rustc-env=VICTORY_COMMIT={commit}"); + for git in ["../../.git/HEAD", "../../.git/refs/heads", "../../.git/packed-refs"] { + println!("cargo:rerun-if-changed={git}"); + } + println!("cargo:rerun-if-changed=build.rs"); if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") { println!("cargo:rustc-link-arg-bins=/EXPORT:D3D12SDKVersion,DATA"); println!("cargo:rustc-link-arg-bins=/EXPORT:D3D12SDKPath,DATA"); diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index b7ee76fd7..cbcf2ea66 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -526,6 +526,12 @@ fn main() -> Result<()> { title_args, } => { victory_hle::runtime::set_title_args(title_args); + // MFG Unlocker where `VICTORY_MFG_UNLOCKER_DLL` names it, as `play` does: a launcher + // that starts `run` itself (VILauncher) had no way to load it. + #[cfg(windows)] + if execute { + play::load_mfg(); + } run::run(&exe, unimplemented, strict, execute, console) } #[cfg(all(windows, feature = "diagnostics"))] @@ -578,6 +584,31 @@ fn show_config() -> Result<()> { } /// Paths given on the command line, or the configured game + test titles. +/// The folder of the translated shaders, with the pipelines beside it: +/// `\shaders` where that is set, else the cache's +/// `shaders`. `victory run`, `shaders`, `warm` and `preload` all +/// keep to it, so that a preload fills the folder the runs read. +/// +/// A launcher that keeps the cache in a folder of its own may empty it: on +/// an RTX 3070 Ti started by VILauncher, 7 of 11 sessions in a day began +/// with no translation and no pipeline library (hits=0, about 2,250 +/// shaders translated and 800 pipelines made again, the first cutscene +/// black for a minute), the sessions after a change of its launch options +/// or an update. A folder it does not know of keeps them. +pub(crate) fn shader_cache_dir(cfg: &victory_core::Config) -> Result { + match std::env::var_os("VICTORY_SHADER_CACHE_DIR").filter(|v| !v.is_empty()) { + Some(root) => { + use anyhow::Context as _; + let dir = PathBuf::from(root).join("shaders"); + std::fs::create_dir_all(&dir).with_context(|| format!("creating {} (VICTORY_SHADER_CACHE_DIR)", dir.display()))?; + // (On stderr: the processes of `warm` answer on stdout, line by line.) + eprintln!("shaders kept in {} (VICTORY_SHADER_CACHE_DIR)", dir.display()); + Ok(dir) + } + None => cfg.cache_subdir("shaders"), + } +} + pub(crate) fn default_paths(paths: Vec) -> Result> { if !paths.is_empty() { return Ok(paths); diff --git a/apps/victory/src/play.rs b/apps/victory/src/play.rs index 141e932d6..f4957d0f1 100644 --- a/apps/victory/src/play.rs +++ b/apps/victory/src/play.rs @@ -62,7 +62,9 @@ const SETTINGS: &[(&str, &str)] = &[ ("VICTORY_CARD_REHASH_RUNS", "1"), ("VICTORY_JOIN_COPIES", "1"), ("VICTORY_CARD_STEPS", "2"), - ("VICTORY_CARD_AWAKE", "1"), + // Neo: no loop that keeps the card's clocks up. It took a tenth of the card (RTX 3090 Ti, the + // prologue's cell: the card 86 % busy with it and 76 % without, 30.7 and 31.7 frames a second). + ("VICTORY_CARD_AWAKE", "0"), ("VICTORY_CARD_BUFFERS_MIN_KB", "64"), ("VICTORY_INDIRECT_WINDOW", "1"), ("VICTORY_INDIRECT_BATCH", "2"), @@ -102,17 +104,33 @@ const SETTINGS: &[(&str, &str)] = &[ ("VICTORY_AMBIENT", "0.8"), ("VICTORY_AMBIENT_AIR", "1.5"), ("VICTORY_AMBIENT_SPECULAR", "1"), + // Indoors, without it: the reflections the title resolves hold the sky's light (a + // terrarium's glass, a table top and a floor show white), and the dust in the air is lit + // as under the open sky (white specks) + ("VICTORY_AMBIENT_REFLECT", "1"), + ("VICTORY_AMBIENT_REFLECT_IN", "CS_TemporalResolve2_Opaque,CS_TemporalResolve1_Alpha"), + ("VICTORY_AMBIENT_ALPHA", "4"), // Pixel programs keep the console's early depth test ("VICTORY_EARLY_DEPTH", "1"), // Left out: the decal heap's defragmentation and the heat-haze pass ("VICTORY_LEAVE_OUT", "02384a60fda6f2d0,731a39171b568298"), // Pipelines the title makes are written down, for `victory warm` ("VICTORY_PIPELINE_BOOK", "1"), - // Memory stack (skornuta): texture slots left unused are given back, old command allocators - // are taken anew, small buffers share card memory (off since .8; on again 2026-11-28) - ("VICTORY_SLOT_EVICT", "1"), - ("VICTORY_ALLOCATOR_TRIM", "1"), - ("VICTORY_BUDGET_PACK", "1"), + // (The tree this is built on turns the memory stack on here: VICTORY_SLOT_EVICT, + // VICTORY_ALLOCATOR_TRIM, VICTORY_BUDGET_PACK. Not in Neo: in the prologue's cell on an + // RTX 3090 Ti it took 38.5 frames a second where 39.4 ran without, and the process held as + // much memory either way; `--set VICTORY_SLOT_EVICT=1` and so on turn it on.) + // Neo, measured in the prologue's cell on an RTX 3090 Ti and a Ryzen 9 9950X3D (README): + // the title's write faults open their block without the write watch's one lock, and a + // store that faults is done beside the guard (one that changes nothing is left out) + ("VICTORY_FAULT_UNLOCKED", "1"), + ("VICTORY_STORE_BESIDE", "1"), + // On a processor of two dies the layer's own threads keep to the die the title does not use + ("VICTORY_OWN_CPUS", "auto"), + // The title's own rate is 60, not 30: above 30 frames a second it would otherwise step + // 1/30 s a frame and run fast (the same loop of an idle animation 6.07 s at 36.8 frames a + // second without, 7.43 s with; 7.33 s at 30) + ("VICTORY_FRAME_INTERVAL_MS", "16.667"), ]; /// Path settings a start keeps from its surroundings; every other @@ -370,6 +388,11 @@ fn settings(o: &Play, menu: &[(String, String)], streamline: Option<&Path>) -> ( } let mut set = |k: &str, v: &str| drop(s.insert(k.to_owned(), v.to_owned())); set("VICTORY_FRAME_INTERVAL_US", &(1_000_000.0 / f64::from(fps)).round().to_string()); + // The title's own rate with it (`VICTORY_FRAME_INTERVAL_MS`, 60 in `SETTINGS`): a cap under 60 + // is the rate the title is given too, 30 its own. + if (1..60).contains(&fps) { + set("VICTORY_FRAME_INTERVAL_MS", &format!("{:.3}", 1000.0 / f64::from(fps))); + } for (k, v) in menu.iter().filter(|(k, _)| !k.starts_with("VICTORY_MENU_")) { if v.is_empty() { s.remove(k); diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index b27a6953a..909e94e84 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -117,6 +117,16 @@ pub fn run( if execute { check_cpu_features()?; } + // Which build, and with which switches: a launcher that builds and starts + // the layer by itself (VILauncher) shows neither, and a switch that never + // reached the layer looked like one that changed nothing. + let mut switches: Vec = std::env::vars() + .filter(|(k, _)| k.starts_with("VICTORY_")) + .map(|(k, v)| format!("{k}={v}")) + .collect(); + switches.sort(); + println!("build commit {}", env!("VICTORY_COMMIT")); + victory_hle::log_build(env!("VICTORY_COMMIT"), &switches.join(" ")); // A title that relaunched itself: the old process must be gone first. victory_hle::modules::lifecycle::wait_for_previous(); let cfg = victory_core::Config::load()?; @@ -156,10 +166,15 @@ pub fn run( 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(); - match victory_game::identify(&hash) { + let build = victory_game::identify(&hash); + match build { Some(build) => println!("build {} ({hash})", build.label), None => println!("build unknown ({hash})"), } + // (Not with the title's FidelityFX path asked for: DLSS, frame + // generation and `VICTORY_FSR_PATH` take the title's FidelityFX + // upscaler, which the known build's patches turn off.) + apply_title_patches(&mut prepared, build, upscaler.is_none())?; // A 1440p output instead of the Series X's 4K one (`native_1440p`): the // patched image goes to a folder of its own, beside the stock one. @@ -211,7 +226,7 @@ pub fn run( } else { cfg.cache_subdir("images")? }; - victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); + victory_hle::modules::d3d12x::use_shader_cache(crate::shader_cache_dir(&cfg)?); let image = victory_loader::load(&prepared, &images)?; // The program is mapped from the copy `load` wrote: the file's bytes // and their patched copy are not read again, and were held for the @@ -761,3 +776,68 @@ mod cpu_check_tests { pub fn run(_: &Path, _: Unimplemented, _: bool, _: bool, _: Console) -> Result<()> { anyhow::bail!("running titles requires Windows") } + +/// Bytes as lower-case hex. +#[cfg(windows)] +fn hex_str(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +/// The known build's code patches (`VICTORY_TITLE_PATCHES=0`: none; none +/// either unless `own_upscaler`: they make the title keep its own upscaler, +/// and the FidelityFX path of DLSS and frame generation needs the title's +/// choice left alone), then +/// any from `VICTORY_TITLE_PATCH=::,...`. The old +/// bytes must be there (another build of the title is refused), and the +/// patched copy has a file name of its own. +#[cfg(windows)] +fn apply_title_patches( + prepared: &mut victory_loader::PreparedImage, + build: Option<&victory_game::KnownBuild>, + own_upscaler: bool, +) -> Result<()> { + let mut patches = Vec::new(); + let mut names = Vec::new(); + if !own_upscaler && build.is_some_and(|b| !b.patches.is_empty()) { + println!("title patch none: the title's FidelityFX path is asked for, its choice of upscaler is left to it"); + } else if std::env::var("VICTORY_TITLE_PATCHES").as_deref() != Ok("0") { + for p in build.map_or(&[][..], |b| b.patches) { + patches.push((p.rva, p.expect.to_vec(), p.write.to_vec())); + names.push(p.name.to_owned()); + } + } + let spec = std::env::var("VICTORY_TITLE_PATCH").unwrap_or_default(); + for one in spec.split(',').filter(|p| !p.trim().is_empty()) { + let parts: Vec<&str> = one.split(':').collect(); + anyhow::ensure!( + parts.len() == 3, + "VICTORY_TITLE_PATCH entry is not ::: {one}" + ); + let rva = u32::from_str_radix(parts[0].trim().trim_start_matches("0x"), 16)?; + patches.push((rva, from_hex(parts[1])?, from_hex(parts[2])?)); + names.push("VICTORY_TITLE_PATCH".to_owned()); + } + if patches.is_empty() { + return Ok(()); + } + prepared.patch(&patches)?; + for ((rva, old, new), name) in patches.iter().zip(names) { + println!( + "title patch +{rva:#x} {name}: {} -> {}", + hex_str(old), + hex_str(new) + ); + } + Ok(()) +} + +/// Bytes from hex digits. +#[cfg(windows)] +fn from_hex(s: &str) -> Result> { + let s = s.trim(); + anyhow::ensure!(s.len().is_multiple_of(2), "odd hex length: {s}"); + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).map_err(anyhow::Error::from)) + .collect() +} diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index a86ab3e64..8d7823e24 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -175,7 +175,7 @@ pub fn warm(paths: Vec, file: &Path, jobs: Option) -> Result<()> // (what is done stays in the cache; the next warm-up goes on from there). let limit = std::env::var("VICTORY_WARM_SECONDS").ok().and_then(|v| v.trim().parse::().ok()); let cfg = victory_core::Config::load()?; - victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); + victory_hle::modules::d3d12x::use_shader_cache(crate::shader_cache_dir(&cfg)?); let paths = crate::default_paths(paths)?; let threads = jobs.unwrap_or(4).max(1); let began = std::time::Instant::now(); @@ -419,7 +419,7 @@ fn may_hold_shaders(path: &std::path::Path) -> bool { /// Every shader found into the cache runs translate from. pub fn precompile(paths: Vec, jobs: Option) -> Result<()> { let cfg = victory_core::Config::load()?; - victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); + victory_hle::modules::d3d12x::use_shader_cache(crate::shader_cache_dir(&cfg)?); let paths = crate::default_paths(paths)?; let threads = jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get())); diff --git a/apps/victory/src/warm.rs b/apps/victory/src/warm.rs index 6d3ee9fa8..c55d3f552 100644 --- a/apps/victory/src/warm.rs +++ b/apps/victory/src/warm.rs @@ -23,7 +23,7 @@ const SLOW_MS: f64 = 1000.0; fn folder() -> Result { let cfg = victory_core::Config::load()?; - Ok(cfg.cache_subdir("shaders")?.with_file_name("pipelines")) + Ok(crate::shader_cache_dir(&cfg)?.with_file_name("pipelines")) } pub fn run(jobs: Option, limit: Option, again: bool, used: bool, these: Option) -> Result<()> { @@ -160,7 +160,7 @@ pub fn run(jobs: Option, limit: Option, again: bool, used: bool, t pub fn into_library(jobs: Option) -> Result<()> { let dir = folder()?; let cfg = victory_core::Config::load()?; - known::use_library(cfg.cache_subdir("shaders")?); + known::use_library(crate::shader_cache_dir(&cfg)?); let keys = known::keys(&dir); let read = |file: &str| std::fs::read_to_string(dir.join(file)).unwrap_or_default(); let (bad, early, slow) = (read("warm-bad.txt"), read("early-pipelines.txt"), read("slow-pipelines.txt")); @@ -269,7 +269,7 @@ fn child(these: &[usize], mut each: impl FnMut(usize, f64, bool)) -> (usize, Opt fn make(dir: &Path, these: &str) -> Result<()> { let these: Vec = these.split(',').map(|n| n.parse().context("--these")).collect::>()?; let cfg = victory_core::Config::load()?; - victory_hle::known_pipelines::use_translations(cfg.cache_subdir("shaders")?); + victory_hle::known_pipelines::use_translations(crate::shader_cache_dir(&cfg)?); let mut out = std::io::stdout(); known::make(dir, &these, |n, came| { let told = match came { diff --git a/crates/victory-game/src/lib.rs b/crates/victory-game/src/lib.rs index affa682b4..13e967eb5 100644 --- a/crates/victory-game/src/lib.rs +++ b/crates/victory-game/src/lib.rs @@ -12,10 +12,55 @@ pub struct KnownBuild { pub label: &'static str, /// BLAKE3 of the original executable, hex. pub blake3: &'static str, + /// Changes to its code made before it is mapped. + pub patches: &'static [CodePatch], } -/// Builds we support. Empty until the executable is available. -pub const KNOWN_BUILDS: &[KnownBuild] = &[]; +/// A change to title code: at `rva`, the bytes `expect` (a short signature +/// checked before anything is written) become `write`, our own code. +#[derive(Debug, Clone, Copy)] +pub struct CodePatch { + /// Our name for it, as logged. + pub name: &'static str, + pub rva: u32, + pub expect: &'static [u8], + pub write: &'static [u8], +} + +/// `mov eax, 6; ret`: the upscaler a Series X uses. +const UPSCALER_6: &[u8] = &[0xb8, 0x06, 0x00, 0x00, 0x00, 0xc3]; + +/// Builds we support. +pub const KNOWN_BUILDS: &[KnownBuild] = &[KnownBuild { + label: "Xbox Series master", + blake3: "b99f876b74d4a77f03af5f878223b27bd647b5c35a79d5decd9f716504239e93", + // The title picks its upscaler by console: on a Series S with the + // FidelityFX upscaler's capability, FSR 4 (type 7), else its own + // (type 6, as on a Series X). Both functions that make the choice + // return 6, so a Series S runs its own render profile with its own + // upscaler. (From fxceless/victory-fork#798, where FSR 4's frames were + // black with `--console series-s`.) On this tree FSR 4 runs, through + // the translator, and costs: in the prologue's cell (RTX 3090 Ti, + // 4,300 to 4,700 draws a frame) a median of 28.5 frames a second with + // it against 30.9 without, 88 against 38 MB a frame of title memory + // copied for the card and 21.6 against 0.8 MB a frame copied back. + // Not applied when the title's FidelityFX path is asked for (DLSS, + // frame generation, `VICTORY_FSR_PATH`: `victory run` says so). + patches: &[ + CodePatch { + name: "upscaler choice", + rva: 0x7e_93f0, + expect: &[0x48, 0x83, 0xec, 0x28, 0x80, 0x3d], + write: UPSCALER_6, + }, + CodePatch { + name: "upscaler choice (the per-frame copy)", + rva: 0x540_0190, + expect: &[0x48, 0x83, 0xec, 0x28, 0x48, 0x8b], + write: UPSCALER_6, + }, + ], +}]; /// Looks up a build by the BLAKE3 hash of its executable. pub fn identify(blake3_hex: &str) -> Option<&'static KnownBuild> { @@ -23,3 +68,25 @@ pub fn identify(blake3_hex: &str) -> Option<&'static KnownBuild> { .iter() .find(|b| b.blake3.eq_ignore_ascii_case(blake3_hex)) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn known_builds_are_well_formed() { + for build in KNOWN_BUILDS { + assert_eq!(build.blake3.len(), 64); + assert!(build.blake3.bytes().all(|b| b.is_ascii_hexdigit())); + assert_eq!( + identify(&build.blake3.to_uppercase()).map(|b| b.label), + Some(build.label) + ); + for patch in build.patches { + assert!(!patch.write.is_empty(), "{}", patch.name); + assert_eq!(patch.expect.len(), patch.write.len(), "{}", patch.name); + } + } + assert!(identify("00").is_none()); + } +} diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index 2b4c5b007..52b0abc89 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -8,6 +8,7 @@ license.workspace = true publish.workspace = true [dependencies] +mimalloc = { workspace = true, optional = true } blake3.workspace = true zlib-rs.workspace = true tracing.workspace = true @@ -25,6 +26,9 @@ tempfile.workspace = true [features] # Debugging switches (frame capture, the host debug layer, per-draw data). diagnostics = [] +# Our own allocations come from mimalloc (a cache of blocks per thread), not +# from the process heap that the title's threads and the drivers use too. +mimalloc = ["dep:mimalloc"] [lints] workspace = true diff --git a/crates/victory-gpu/src/ambient.rs b/crates/victory-gpu/src/ambient.rs index e7153c1b3..cbac3574c 100644 --- a/crates/victory-gpu/src/ambient.rs +++ b/crates/victory-gpu/src/ambient.rs @@ -36,6 +36,11 @@ //! sky's light indoors too, a brown veil at sunset. `VICTORY_AMBIENT_AIR` //! bounds what the air scatters by a multiple of the light around. //! +//! Transparent surfaces and particles take their light from a volume the +//! title's rays fill: without them it holds the sky's light everywhere, and +//! the dust of a room shows as white specks. `VICTORY_AMBIENT_ALPHA` bounds +//! it as the air's ([`alpha`]). +//! //! Reflections are traced too, at half the picture's size: rays the //! title's screen-space march resolves (`CS_ResolveScreenSpace`) take the //! light seen on screen; the others go to the structures, find nothing, and @@ -68,10 +73,33 @@ pub(crate) enum Role { /// Gives the reflection rays that found nothing the sky's light /// (`CS_RayMiss`, not `CS_RayMiss_Volumetrics` nor the screen probes'). Miss, + /// Filters the light of transparent surfaces and particles, a volume + /// before the eye (`CS_SpatialFilterAlpha`, the last program that writes + /// it). + Alpha, + /// Resolves the traced reflections (`VICTORY_AMBIENT_REFLECT_IN` names + /// the programs): after it each texel is held to a multiple of the light + /// around ([`reflect`]). + Reflect, } /// The program's part in this, by its name in the container. pub(crate) fn role(container: &[u8]) -> Option { + role_in(container, reflect_in()) +} + +/// [`role`], with the texts that name the reflections' resolves (looked for +/// last, so that no text takes a program of the other roles). +fn role_in(container: &[u8], reflect_in: &[String]) -> Option { + let has = |name: &[u8]| container.windows(name.len()).any(|w| w == name); + if let Some(found) = role_fixed(container) { + return Some(found); + } + reflect_in.iter().any(|name| has(name.as_bytes())).then_some(Role::Reflect) +} + +/// The roles named in the code. +fn role_fixed(container: &[u8]) -> Option { let has = |name: &[u8]| container.windows(name.len()).any(|w| w == name); if has(b"CS_ScreenProbes_TemporalResolve") { Some(Role::Resolve) @@ -79,6 +107,8 @@ pub(crate) fn role(container: &[u8]) -> Option { Some(Role::Radiance) } else if has(b"CS_AccumulateLocalLightInscatteringVolume") { Some(Role::Air) + } else if has(b"CS_SpatialFilterAlpha") { + Some(Role::Alpha) } else if is_miss(container) { Some(Role::Miss) } else { @@ -102,6 +132,9 @@ pub(crate) const DEPTH: (u8, u32) = (0, 464); pub(crate) const RADIANCE: (u8, u32) = (1, 16); /// Where the light the air scatters is. pub(crate) const AIR: (u8, u32) = (1, 32); +/// Where the filter writes the light of transparent surfaces (a volume of +/// R11G11B10; its direction goes to (1, 16)). +pub(crate) const ALPHA: (u8, u32) = (1, 24); /// Where the miss program writes the reflected light (R11G11B10, half the /// picture's size) and where it reads the depth it is given (a 32-bit depth /// of the picture's size). @@ -156,6 +189,64 @@ fn parse_specular(set: &str) -> Option { Some(Specular { share, sky }) } +/// Where the reflections' resolves write them: the first of these places +/// that holds a 2D image of their format (R32_UINT holding R9G9B9E5; the +/// opaque surfaces' resolve has it at the first, the transparent ones' at the +/// second). +pub(crate) const REFLECTIONS: [(u8, u32); 2] = [(1, 128), (1, 136)]; + +/// The most a resolved reflection may hold, as a multiple of the light +/// around (`VICTORY_AMBIENT_REFLECT=`; unset, `0` or `off`: the +/// title's own). Acts only while `VICTORY_AMBIENT` is set and the builder +/// does not run. Ported from TaynanGT/Vice-Tay#99 (fc9ef8a, fa90adf), itself +/// from Serph91P's avatarmanz/VIctory-7900XTX#314 (6c7e3a87, GPL-3.0); the +/// idea and the switch's name are beloooo's (VIctory-Belobug-AMD 44dcd437). +fn reflect() -> f32 { + static SET: OnceLock = OnceLock::new(); + *SET.get_or_init(|| parse_reflect(&std::env::var("VICTORY_AMBIENT_REFLECT").unwrap_or_default())) +} + +fn parse_reflect(set: &str) -> f32 { + set.trim().parse().ok().filter(|v: &f32| v.is_finite() && *v > 0.0).unwrap_or(0.0) +} + +/// The texts in the names of the programs that resolve the reflections +/// (`VICTORY_AMBIENT_REFLECT_IN=[,]`, e.g. +/// `CS_TemporalResolve2_Opaque,CS_TemporalResolve1_Alpha`); none while the +/// hold is off. +fn reflect_in() -> &'static [String] { + static SET: OnceLock> = OnceLock::new(); + SET.get_or_init(|| { + let held = reflect(); + if held == 0.0 { + return Vec::new(); + } + let names = parse_reflect_in(&std::env::var("VICTORY_AMBIENT_REFLECT_IN").unwrap_or_default()); + if names.is_empty() { + tracing::warn!("VICTORY_AMBIENT_REFLECT without VICTORY_AMBIENT_REFLECT_IN: no reflections are held"); + } else { + tracing::info!(held, ?names, "reflections held to a multiple of the light around (VICTORY_AMBIENT_REFLECT)"); + } + names + }) +} + +fn parse_reflect_in(set: &str) -> Vec { + set.split(',').map(str::trim).filter(|t| !t.is_empty()).map(str::to_owned).collect() +} + +/// Reflections' resolves held since the start. +static HELD: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// A resolve of the reflections was held after. +fn note_held() { + use std::sync::atomic::Ordering::Relaxed; + let n = HELD.fetch_add(1, Relaxed) + 1; + if n == 1 || n.is_multiple_of(5000) { + tracing::info!(n, "reflections held after their resolve, since the start (VICTORY_AMBIENT_REFLECT)"); + } +} + fn specular() -> Option { static SET: OnceLock> = OnceLock::new(); *SET.get_or_init(|| parse_specular(&std::env::var("VICTORY_AMBIENT_SPECULAR").unwrap_or_default())) @@ -191,6 +282,28 @@ fn air() -> f32 { }) } +/// The most light transparent surfaces and particles get from around them, +/// as a multiple of the light around (`VICTORY_AMBIENT_ALPHA=`; +/// unset or 0: what the title has). +/// +/// The title keeps that light in a volume before the eye (32x16 cells, 64 +/// deep; a mean and a direction a cell) from rays of its own +/// (`CS_GatherAlphaVBuffer`, `CS_ShadeAlpha`, then a variance and a spatial +/// filter). Without the structures its rays find the sky from everywhere, +/// and the dust in a room's air is lit as under the open sky: white specks +/// all over the picture (the first house of the story, RTX 3090 Ti; flipped +/// on and off in one view with `VICTORY_AB`, they are there without the +/// bound and gone with it, at 1 and at 4). Under the sky the light around is +/// of the sky's order and the bound changes nothing seen (the deck outside +/// that house, the same way). +fn alpha() -> f32 { + static SET: OnceLock = OnceLock::new(); + *SET.get_or_init(|| { + let set = std::env::var("VICTORY_AMBIENT_ALPHA").unwrap_or_default(); + set.trim().parse().ok().filter(|v: &f32| v.is_finite() && *v > 0.0).unwrap_or(0.0) + }) +} + /// Strength and radius of the creases' shade. fn shade() -> [f32; 2] { static SET: OnceLock<[f32; 2]> = OnceLock::new(); @@ -388,7 +501,7 @@ void reflect_light(uint3 at : SV_DispatchThreadID) { } #endif -#ifdef RAISE +#if defined(RAISE) || defined(HOLD) RWTexture2D light : register(u0); float3 unpack(uint v) { return float3(v & 511, (v >> 9) & 511, (v >> 18) & 511) * exp2(float(v >> 27) - 24.0); @@ -402,6 +515,40 @@ uint pack(float3 c) { uint3 m = min(uint3(c * scale + 0.5), 511u); return m.r | (m.g << 9) | (m.b << 18) | (uint(e) << 27); } +#endif + +#ifdef HOLD +// The resolved reflections: no brighter than `most` times the light around, +// as the estimate has it at the four points about the texel (with a fifth of +// the room's slow mean), or the constant; hue kept. +[RootSignature(RS)] +[numthreads(8, 8, 1)] +void hold(uint3 at : SV_DispatchThreadID) { + uint w, h; + light.GetDimensions(w, h); + if (at.x >= w || at.y >= h) return; + float3 around = float3(1.0, 0.98, 0.94) * constant; + if (constant <= 0.0) { + float2 g = (float2(at.xy) + 0.5) / float2(w, h) * float2(PX, PY) - 0.5; + int2 g0 = int2(floor(g)); + float2 f = g - float2(g0); + around = 0; + for (int k = 0; k < 4; k++) { + int2 q = clamp(g0 + int2(k & 1, k >> 1), int2(0, 0), int2(PX, PY) - 1); + float2 b = float2(k & 1 ? f.x : 1 - f.x, k >> 1 ? f.y : 1 - f.y); + uint at0 = (q.y * PX + q.x) * 3; + around += b.x * b.y * float3(points[at0].w, points[at0 + 1].w, points[at0 + 2].w); + } + around = lerp(around, cells[CELLS].rgb, 0.2); + } + float top = most * dot(around, LUMA); + float3 c = unpack(light[at.xy]); + float has = dot(c, LUMA); + if (has > top) light[at.xy] = pack(c * (top / max(has, 1e-9))); +} +#endif + +#ifdef RAISE [RootSignature(RS)] [numthreads(8, 8, 1)] void raise(uint3 at : SV_DispatchThreadID) { @@ -507,6 +654,8 @@ struct Pass { raise: ID3D12PipelineState, air: ID3D12PipelineState, reflect: ID3D12PipelineState, + /// Made only while the hold of the reflections is on. + hold: Option, cells: ID3D12Resource, points: ID3D12Resource, } @@ -539,6 +688,13 @@ fn make(device: &ID3D12Device, buffer: impl Fn(u64) -> Option) - let raise = pipeline("RAISE", s!("raise"))?; let air = pipeline("AIR", s!("clear_air"))?; let reflect = pipeline("REFLECT", s!("reflect_light"))?; + // Not made unless the hold is on, and on its own: without it the rest of + // the stand-in still runs. + let hold = if reflect_in().is_empty() { + None + } else { + pipeline("HOLD", s!("hold")).inspect_err(|e| tracing::warn!(%e, "no hold of the reflections")).ok() + }; let made = |bytes| buffer(bytes).ok_or_else(windows::core::Error::empty); Ok(Pass { root: root.ok_or_else(windows::core::Error::empty)?, @@ -549,6 +705,7 @@ fn make(device: &ID3D12Device, buffer: impl Fn(u64) -> Option) - raise, air, reflect, + hold, cells: made(CELL_BYTES)?, points: made(POINT_BYTES)?, }) @@ -703,6 +860,13 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { if role == Role::Air && (constant > 0.0 || air() == 0.0) { return false; } + if role == Role::Alpha && (constant > 0.0 || alpha() == 0.0) { + return false; + } + // The traced reflections are the title's own while its rays run. + if role == Role::Reflect && (pass.hold.is_none() || crate::pipeline::builder_runs()) { + return false; + } static SAID: Mutex = Mutex::new(0); { let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); @@ -722,8 +886,8 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { words[6] = views.depth_size[0]; words[7] = views.depth_size[1]; words[8] = 0.04f32.to_bits(); - words[9] = 4.0f32.to_bits(); - words[10] = air().to_bits(); + words[9] = if role == Role::Reflect { reflect() } else { 4.0f32 }.to_bits(); + words[10] = if role == Role::Alpha { alpha() } else { air() }.to_bits(); words[11] = if once() { 1.0f32 } else { 0.0 }.to_bits(); let l = &list.list; // SAFETY: an open list with the heap of the views set; the title's @@ -748,7 +912,9 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { run(&pass.mean, 1, 1, 1); KEPT.store(true, Ordering::Relaxed); } - Role::Air => run(&pass.air, views.size[0].div_ceil(8), views.size[1].div_ceil(8), views.slices.div_ceil(2)), + Role::Air | Role::Alpha => { + run(&pass.air, views.size[0].div_ceil(8), views.size[1].div_ceil(8), views.slices.div_ceil(2)) + } Role::Resolve => { if constant == 0.0 { run(&pass.place, 8, 9, 1); @@ -756,6 +922,12 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { } run(&pass.raise, views.size[0].div_ceil(8), views.size[1].div_ceil(8), 1); } + Role::Reflect => { + if let Some(hold) = &pass.hold { + run(hold, views.size[0].div_ceil(8), views.size[1].div_ceil(8), 1); + note_held(); + } + } Role::Miss => { // The points afresh, from this frame's depth: the diffuse // stand-in makes them later in the frame. @@ -798,6 +970,8 @@ mod tests { assert_eq!(role(b"..CS_ScreenProbes_TemporalResolve_a911b49c_Wrapped.."), Some(Role::Resolve)); assert_eq!(role(b"..CS_CacheScreenSpaceRadiance_eed2fc35.."), Some(Role::Radiance)); assert_eq!(role(b"CS_AccumulateLocalLightInscatteringVolume_7e2f5eef"), Some(Role::Air)); + assert_eq!(role(b"..indirect_light_probes:CS_SpatialFilterAlpha_08e7839f_Wrapped.."), Some(Role::Alpha)); + assert_eq!(role(b"..CS_VarianceFilterAlpha_b92710bc_Wrapped.."), None); assert_eq!(role(b"CS_TemporalResolve"), None); assert_eq!(role(b"..CS_RayMiss_de6b91a6_Wrapped.."), Some(Role::Miss)); assert_eq!(role(b"..CS_RayMiss_Volumetrics_3c5d8c00_Wrapped.."), None); diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 44a91dbe9..41a15a600 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -402,16 +402,26 @@ fn big_blocks() -> String { if text.is_empty() { "none".into() } else { text.join(", ") } } -/// The system's allocator with every block counted in [`OWN`] (two atomic -/// additions per allocation and per release: diagnostics builds only). +/// The allocator with every block counted in [`OWN`] (two atomic additions +/// per allocation and per release). The blocks are the system's, or with the +/// `mimalloc` feature mimalloc's ([`INNER`]). struct Counting; -// SAFETY: every call goes to the system's allocator unchanged; only -// counters are kept beside it. +/// Where [`Counting`] gets its blocks. The process heap is one heap for our +/// threads, the title's and the drivers', taken with its lock; the thread +/// that prepares submissions and its helpers make and grow vectors +/// thousands of times a frame. +#[cfg(not(feature = "mimalloc"))] +const INNER: std::alloc::System = std::alloc::System; +#[cfg(feature = "mimalloc")] +const INNER: mimalloc::MiMalloc = mimalloc::MiMalloc; + +// SAFETY: every call goes to the allocator beneath unchanged; only counters +// are kept beside it. unsafe impl std::alloc::GlobalAlloc for Counting { unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 { // SAFETY: the caller's contract, passed on. - let at = unsafe { std::alloc::System.alloc(layout) }; + let at = unsafe { INNER.alloc(layout) }; if !at.is_null() { own(layout.size(), true); big(at, layout.size(), true); @@ -421,7 +431,7 @@ unsafe impl std::alloc::GlobalAlloc for Counting { unsafe fn alloc_zeroed(&self, layout: std::alloc::Layout) -> *mut u8 { // SAFETY: the caller's contract, passed on. - let at = unsafe { std::alloc::System.alloc_zeroed(layout) }; + let at = unsafe { INNER.alloc_zeroed(layout) }; if !at.is_null() { own(layout.size(), true); big(at, layout.size(), true); @@ -433,12 +443,12 @@ unsafe impl std::alloc::GlobalAlloc for Counting { own(layout.size(), false); big(at, layout.size(), false); // SAFETY: the caller's contract, passed on. - unsafe { std::alloc::System.dealloc(at, layout) }; + unsafe { INNER.dealloc(at, layout) }; } unsafe fn realloc(&self, at: *mut u8, layout: std::alloc::Layout, size: usize) -> *mut u8 { // SAFETY: the caller's contract, passed on. - let moved = unsafe { std::alloc::System.realloc(at, layout, size) }; + let moved = unsafe { INNER.realloc(at, layout, size) }; if !moved.is_null() { own(layout.size(), false); own(size, true); diff --git a/crates/victory-gpu/src/cores.rs b/crates/victory-gpu/src/cores.rs index b0a6e1396..ec9f2f8c9 100644 --- a/crates/victory-gpu/src/cores.rs +++ b/crates/victory-gpu/src/cores.rs @@ -1,10 +1,24 @@ //! Which processors our own threads run on, where a processor has two kinds -//! of cores. `cpu_sets` and `keep_on_fast_cores` are fxceless/victory-fork's -//! (`framelog.rs`, commit 0b0074e0, GPL-3.0-or-later, as this). +//! of cores, or its cores in more than one group around a cache of their own +//! (a Ryzen of two dies: 9900X, 9950X, 7900X, 5900X ...). `cpu_sets` and +//! `keep_on_fast_cores` are fxceless/victory-fork's (`framelog.rs`, commit +//! 0b0074e0, GPL-3.0-or-later, as this). -/// The system's processor sets of group 0: each one's id and its efficiency -/// class (higher is faster). -fn cpu_sets() -> Vec<(u32, u8)> { +/// One of the system's processor sets of group 0. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Set { + id: u32, + /// Efficiency class: higher is faster. + class: u8, + /// The last-level cache it shares (a Ryzen's die: its L3). + cache: u8, + /// The system's ranking of it for single threads (CPPC's preferred + /// cores; 0 where Windows does not say). + rank: u8, +} + +/// The system's processor sets of group 0. +fn cpu_sets() -> Vec { use windows_sys::Win32::System::SystemInformation::{GetSystemCpuSetInformation, SYSTEM_CPU_SET_INFORMATION}; use windows_sys::Win32::System::Threading::GetCurrentProcess; let mut bytes = 0u32; @@ -24,20 +38,214 @@ fn cpu_sets() -> Vec<(u32, u8)> { // SAFETY: the record's type is CpuSet (the only one there is). let set = unsafe { &info.Anonymous.CpuSet }; if set.Group == 0 { - sets.push((set.Id, set.EfficiencyClass)); + // SAFETY: a byte of the union's four, zero where it is reserved. + let rank = unsafe { set.Anonymous2.SchedulingClass }; + sets.push(Set { id: set.Id, class: set.EfficiencyClass, cache: set.LastLevelCacheIndex, rank }); } at += info.Size as usize; } sets } +/// One of the system's processors (group 0): its set's id, its number, and the +/// last-level cache it shares. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Cpu { + id: u32, + logical: u8, + cache: u8, +} + +fn cpus() -> Vec { + use windows_sys::Win32::System::SystemInformation::{GetSystemCpuSetInformation, SYSTEM_CPU_SET_INFORMATION}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut bytes = 0u32; + // SAFETY: a size query, then the call into a buffer of that size. + unsafe { GetSystemCpuSetInformation(std::ptr::null_mut(), 0, &mut bytes, GetCurrentProcess(), 0) }; + let mut buffer = vec![0u64; (bytes as usize).div_ceil(8).max(1)]; + // SAFETY: as above; the buffer holds `bytes` bytes, aligned for the records. + let ok = unsafe { GetSystemCpuSetInformation(buffer.as_mut_ptr().cast(), bytes, &mut bytes, GetCurrentProcess(), 0) }; + let mut all = Vec::new(); + let mut at = 0usize; + while ok != 0 && at + size_of::() <= bytes as usize { + // SAFETY: a record inside the buffer; each says its own size. + let info = unsafe { &*(buffer.as_ptr().cast::().add(at).cast::()) }; + if info.Size == 0 { + break; + } + // SAFETY: the record's type is CpuSet (the only one there is). + let set = unsafe { &info.Anonymous.CpuSet }; + if set.Group == 0 { + all.push(Cpu { id: set.Id, logical: set.LogicalProcessorIndex, cache: set.LastLevelCacheIndex }); + } + at += info.Size as usize; + } + all +} + +/// The processors the title keeps its threads on: the console's sixteen, +/// the first sixteen here. +const TITLE_PROCESSORS: usize = 16; + +/// The processors `asked` names among `all`: `-` by their +/// numbers; `auto`, those of every last-level cache but the one processor 0 +/// has, if there is more than one (a processor of two dies) and processor +/// 0's holds the title's sixteen ([`TITLE_PROCESSORS`]). `None`: not +/// understood, or none. +fn own_of(asked: &str, all: &[Cpu]) -> Option> { + let asked = asked.trim(); + let chosen: Vec = if asked.eq_ignore_ascii_case("auto") { + let first = all.iter().find(|c| c.logical == 0)?.cache; + // The title keeps its threads on the first sixteen processors: only + // where those are one die is the other die free for ours. On a die of + // twelve (a Ryzen 9 9900X) four of the title's sixteen lie on the + // other die, and ours crowded there beside them: the frame of 3,500 to + // 5,000 draws 63.9 ms where it was 44.7 with ours on every processor + // (RTX 3070 Ti, 2026-11-28). + if all.iter().filter(|c| c.cache == first).count() < TITLE_PROCESSORS { + return None; + } + all.iter().filter(|c| c.cache != first).map(|c| c.id).collect() + } else { + let (from, to) = asked.split_once('-')?; + let (from, to) = (from.trim().parse::().ok()?, to.trim().parse::().ok()?); + all.iter().filter(|c| (from..=to).contains(&c.logical)).map(|c| c.id).collect() + }; + (!chosen.is_empty() && chosen.len() < all.len()).then_some(chosen) +} + +/// Whether the many threads whose work is ahead of what a frame waits for +/// (lists translated, records made) run on every processor while the others +/// of ours keep to their own ([`keep_own_threads`]; `VICTORY_OWN_CPUS_MANY=1`, +/// off by default: they keep to ours too, see there). +fn roaming() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_OWN_CPUS").is_some() && std::env::var_os("VICTORY_OWN_CPUS_MANY").is_some_and(|v| v == "1")) +} + +/// The processors our own threads keep to, as the start names them +/// ([`keep_own_threads`]); `None`: none named. +fn own() -> Option<&'static Vec> { + static OWN: std::sync::OnceLock>> = std::sync::OnceLock::new(); + OWN.get_or_init(|| { + let asked = std::env::var("VICTORY_OWN_CPUS").ok()?; + let all = cpus(); + let own = own_of(&asked, &all); + match &own { + Some(own) => tracing::info!(asked, processors = own.len(), of = all.len(), "our own threads are kept on these processors (VICTORY_OWN_CPUS)"), + None => tracing::warn!(asked, of = all.len(), "VICTORY_OWN_CPUS: no processors of that name, or all of them: left as it is"), + } + own + }) + .as_ref() +} + +/// How many threads translate the title's lists where the start does not +/// say (`VICTORY_THIN_THREADS`): eight, or with processors of our own a +/// quarter as many as those, two to eight. +/// +/// Eight on sixteen processors of our own, beside the thread that prepares +/// submissions, its eight helpers and the pools, were more threads than those +/// processors run at a time: the usual frame was shorter than with the +/// threads on every processor, and one frame in ten far longer. With four, +/// five and six in their place (the prologue's cell, Ryzen 9 9950X3D, RTX +/// 3090 Ti, Series S profile, DLSS off, medians of five-second readings and +/// the lowest of them): 39.4 and 38.2 frames a second, 38.8 and 37.5, 39.0 +/// and 36.4; with eight 38.4 and 34.3; with eight on every processor 37.4 and +/// 36.2. The thread that prepares submissions worked 22.8 ms a frame with +/// four where it worked 24.4. +pub(crate) fn list_threads() -> usize { + own().map_or(8, |own| (own.len() / 4).clamp(2, 8)) +} + +/// The processors our own threads run on, where a start names them +/// (`VICTORY_OWN_CPUS=-`, or `auto`: on a processor of two dies, +/// the die the title does not use; not given: any, as before). +/// +/// The title gives each of its threads an affinity of its own, to the +/// console's sixteen processors: here the first sixteen, on a Ryzen of two +/// dies one die. Our threads have none and ran on all of them: the thread +/// that prepares submissions half its time on the title's die, beside the +/// title's threads on their cores' second halves, and the other half on the +/// other die, its memory and its locks crossing between the two (a timeline +/// of the prologue's cell, Ryzen 9 9950X3D: the title's threads on processors +/// 0 to 15 alone, the preparing thread 48 % there). Asked for as the +/// process's default sets, the choice holds for every thread that has neither +/// an affinity nor sets of its own: ours, the drivers', and not the title's. +/// +/// The many threads that translate lists and make records keep to them too +/// (`VICTORY_OWN_CPUS_MANY=1`: they run on every processor). On the title's +/// die they took turns with the title's main thread on its two processors +/// (half of what ran there in a timeline was ours), and that thread's own +/// work is the longest part of a frame's chain, 22 of 27 ms. Fewer of them +/// are made in their place ([`list_threads`]). +/// +/// `VICTORY_OWN_CPUS_ON=0` leaves them as they were (and `VICTORY_AB` can +/// flip it while the title runs). +pub(crate) fn keep_own_threads() { + use std::sync::atomic::{AtomicU8, Ordering::Relaxed}; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, SetProcessDefaultCpuSets}; + let Some(own) = own() else { + return; + }; + // 0: not asked yet; 1: kept; 2: let go. + static APPLIED: AtomicU8 = AtomicU8::new(0); + let want = if crate::toggled!("VICTORY_OWN_CPUS_ON") { 1 } else { 2 }; + if APPLIED.swap(want, Relaxed) == want { + return; + } + // SAFETY: our own process, and a list of the system's own set ids (or none: the default again). + let ok = unsafe { + if want == 1 { + SetProcessDefaultCpuSets(GetCurrentProcess(), own.as_ptr(), own.len() as u32) + } else { + SetProcessDefaultCpuSets(GetCurrentProcess(), std::ptr::null(), 0) + } + }; + if ok == 0 { + tracing::warn!(error = %std::io::Error::last_os_error(), "the process's default processor sets could not be set (VICTORY_OWN_CPUS)"); + } +} + /// The sets of the fastest class, if there are slower ones too. -fn fast_of(sets: &[(u32, u8)]) -> Vec { - let best = sets.iter().map(|c| c.1).max().unwrap_or(0); - let fast: Vec = sets.iter().filter(|c| c.1 == best).map(|c| c.0).collect(); +fn fast_of(sets: &[Set]) -> Vec { + let best = sets.iter().map(|c| c.class).max().unwrap_or(0); + let fast: Vec = sets.iter().filter(|c| c.class == best).map(|c| c.id).collect(); if fast.len() == sets.len() { Vec::new() } else { fast } } +/// Where all cores are of one kind but share more than one last-level +/// cache (a Ryzen 9 9900X: two dies of six cores, 32 MB of L3 each): the +/// sets of one cache, that of the best-ranked core (the system's preferred +/// cores; a tie: the first cache, a Ryzen's first die). Otherwise none. +/// +/// The threads a frame waits for hand their work to each other (the +/// submitting thread, the threads that spread its refreshes, those that +/// land copies, the one that makes the heaps' records): on one die what +/// one wrote is in the cache the next reads; across the two it goes over +/// the link between them, at several times the latency (on Zen 4 and 5 +/// about 70-100 ns against 10-15). The title's own threads are not asked +/// for and keep both dies. +fn one_cache_of(sets: &[Set]) -> Vec { + let Some(first) = sets.first() else { return Vec::new() }; + if sets.iter().any(|s| s.class != first.class) || sets.iter().all(|s| s.cache == first.cache) { + return Vec::new(); + } + let best = sets.iter().max_by(|a, b| a.rank.cmp(&b.rank).then(b.cache.cmp(&a.cache))).map_or(first.cache, |s| s.cache); + sets.iter().filter(|s| s.cache == best).map(|s| s.id).collect() +} + +/// `VICTORY_ONE_CCD`: on a processor whose cores are alike but in groups +/// around caches of their own, the threads `VICTORY_FAST_CORES` 1 and 2 +/// name (those a frame waits for, and those they share their work with) +/// are kept on one group ([`one_cache_of`]); 0: not (as before). Those of +/// 3 (the many that translate lists) are left to every core either way: +/// with the helpers they would be more threads than one die runs at once. +fn one_ccd() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("VICTORY_ONE_CCD").map_or(true, |v| v.trim() != "0")) +} + /// `VICTORY_FAST_CORES`: 0: no thread asks; 1: the threads a frame waits for /// one by one; 2 (the default): the threads they share their work with too; /// 3: those that work beside the rest as well (lists translated, descriptors @@ -90,24 +298,68 @@ fn ask(what: &str, from: u32) { let set = unsafe { SetThreadPriority(GetCurrentThread(), priority) } != 0; tracing::debug!(what, priority, set, "the thread's priority (VICTORY_HELPER_PRIORITY)"); } + // With processors of our own (`keep_own_threads`) and + // `VICTORY_OWN_CPUS_MANY=1`: the many threads whose work is ahead of what + // a frame waits for run on any, the title's too. + if from == 3 && roaming() { + static ALL: std::sync::OnceLock> = std::sync::OnceLock::new(); + let all = ALL.get_or_init(|| cpus().iter().map(|c| c.id).collect()); + // SAFETY: our own thread and a list of the system's own set ids. + let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), all.as_ptr(), all.len() as u32) }; + tracing::debug!(what, ok, "the thread runs on any processor (VICTORY_OWN_CPUS_MANY)"); + } + // An experiment's own word on this kind of thread + // (`VICTORY_THREAD_CPUS==-;=...`, the name a + // beginning of the thread's): those processors, whatever the rest says. + static BY_NAME: std::sync::OnceLock)>> = std::sync::OnceLock::new(); + let by_name = BY_NAME.get_or_init(|| { + let asked = std::env::var("VICTORY_THREAD_CPUS").unwrap_or_default(); + let all = cpus(); + asked + .split(';') + .filter_map(|part| { + let (name, range) = part.split_once('=')?; + let own = own_of(range, &all).or_else(|| (range.trim() == "all").then(|| all.iter().map(|c| c.id).collect()))?; + tracing::info!(name, processors = own.len(), "threads of this name run on these processors (VICTORY_THREAD_CPUS)"); + Some((name.trim().to_owned(), own)) + }) + .collect() + }); + if let Some((_, own)) = by_name.iter().find(|(name, _)| what.starts_with(name.as_str())) { + // SAFETY: our own thread and a list of the system's own set ids. + unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), own.as_ptr(), own.len() as u32) }; + return; + } if stage() < from { return; } - static FAST: std::sync::OnceLock<(Vec, usize)> = std::sync::OnceLock::new(); - let (fast, of) = FAST.get_or_init(|| { + static FAST: std::sync::OnceLock<(Vec, Vec, usize)> = std::sync::OnceLock::new(); + let (fast, one_cache, of) = FAST.get_or_init(|| { let sets = cpu_sets(); - (fast_of(&sets), sets.len()) + (fast_of(&sets), one_cache_of(&sets), sets.len()) }); - // All alike (or nothing known): nothing to ask for. - if fast.is_empty() { + if !fast.is_empty() { + // SAFETY: our own thread and a list of the system's own set ids. + let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), fast.as_ptr(), fast.len() as u32) }; + if ok == 0 { + tracing::warn!(what, error = %std::io::Error::last_os_error(), "the thread could not be kept on the fast cores"); + } else { + tracing::info!(what, fast = fast.len(), of, "the thread is kept on the fast cores (VICTORY_FAST_CORES=0: not)"); + } + return; + } + // All alike: on one die of two, if there are two, for the threads a frame waits for; + // not with processors of our own (`VICTORY_OWN_CPUS`): those are the die the title + // does not use, and the best-ranked die is likely the title's own. + if one_cache.is_empty() || from > 2 || !one_ccd() || own().is_some() { return; } // SAFETY: our own thread and a list of the system's own set ids. - let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), fast.as_ptr(), fast.len() as u32) }; + let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), one_cache.as_ptr(), one_cache.len() as u32) }; if ok == 0 { - tracing::warn!(what, error = %std::io::Error::last_os_error(), "the thread could not be kept on the fast cores"); + tracing::warn!(what, error = %std::io::Error::last_os_error(), "the thread could not be kept on one die"); } else { - tracing::info!(what, fast = fast.len(), of, "the thread is kept on the fast cores (VICTORY_FAST_CORES=0: not)"); + tracing::info!(what, sets = one_cache.len(), of, "the thread is kept on one die, beside its cache (VICTORY_ONE_CCD=0: not)"); } } @@ -163,12 +415,59 @@ impl Priority { mod tests { use super::*; + fn set(id: u32, class: u8, cache: u8, rank: u8) -> Set { + Set { id, class, cache, rank } + } + + #[test] + fn our_own_processors_are_a_range_or_the_other_caches() { + let all: Vec = (0..8u8).map(|n| Cpu { id: 256 + u32::from(n), logical: n, cache: n / 4 }).collect(); + assert_eq!(own_of("4-7", &all), Some(vec![260, 261, 262, 263])); + assert_eq!(own_of(" 6 - 9 ", &all), Some(vec![262, 263])); + assert_eq!(own_of("auto", &all), Some(vec![260, 261, 262, 263])); + // All of them, none of them, one cache, nonsense: nothing asked for. + assert_eq!(own_of("0-7", &all), None); + assert_eq!(own_of("9-12", &all), None); + let one: Vec = (0..8u8).map(|n| Cpu { id: 256 + u32::from(n), logical: n, cache: 0 }).collect(); + assert_eq!(own_of("auto", &one), None); + assert_eq!(own_of("fast", &all), None); + assert!(!cpus().is_empty()); + } + #[test] fn the_fast_cores_are_those_of_the_best_class_if_there_is_a_worse_one() { - assert_eq!(fast_of(&[(256, 1), (257, 1), (258, 0)]), [256, 257]); - assert!(fast_of(&[(256, 0), (257, 0)]).is_empty()); + assert_eq!(fast_of(&[set(256, 1, 0, 0), set(257, 1, 0, 0), set(258, 0, 0, 0)]), [256, 257]); + assert!(fast_of(&[set(256, 0, 0, 0), set(257, 0, 0, 0)]).is_empty()); assert!(fast_of(&[]).is_empty()); assert!(!cpu_sets().is_empty()); std::thread::spawn(|| keep_on_fast_cores("test")).join().unwrap(); } + + #[test] + fn auto_takes_the_other_die_only_where_the_first_holds_the_titles_sixteen() { + let dies = |per: u8| -> Vec { (0..per * 2).map(|i| Cpu { id: 256 + u32::from(i), logical: i, cache: i / per }).collect() }; + // 9950X: two dies of sixteen: the second. + assert_eq!(own_of("auto", &dies(16)), Some((272..288).collect())); + // 9900X: two dies of twelve: the title's sixteen spill over, none. + assert_eq!(own_of("auto", &dies(12)), None); + // A range is taken as asked, whatever the dies. + assert_eq!(own_of("12-23", &dies(12)), Some((268..280).collect())); + } + + #[test] + fn two_dies_of_alike_cores_keep_one_die() { + // A 9900X: 24 sets, 12 on each die's cache; no ranking given: the first die. + let two: Vec = (0..24).map(|i| set(256 + i, 0, (i / 12) as u8 * 12, 0)).collect(); + assert_eq!(one_cache_of(&two), (256..268).collect::>()); + // The system's preferred cores on the second die: that one. + let mut ranked = two.clone(); + ranked[15].rank = 9; + assert_eq!(one_cache_of(&ranked), (268..280).collect::>()); + // One die (a 9800X3D), or two kinds of cores (left to `fast_of`): none. + let one: Vec = (0..16).map(|i| set(256 + i, 0, 0, 0)).collect(); + assert!(one_cache_of(&one).is_empty()); + let hybrid = [set(256, 1, 0, 0), set(257, 0, 1, 0)]; + assert!(one_cache_of(&hybrid).is_empty()); + assert!(one_cache_of(&[]).is_empty()); + } } diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index d331dd46e..2c129cb24 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -3197,14 +3197,17 @@ impl HostHeap { if key == 0 { return; } - match view_at(key as u32, (key >> 32) as u32) { - Some(view) => null_for(&view, self.at(index)), - None => null_view(self.at(index)), - } + let kept = match view_at(key as u32, (key >> 32) as u32) { + Some(view) => neutral_for(&view, self.at(index)), + None => { + null_view(self.at(index)); + None + } + }; self.put(index); self.clear_twin(index); self.write_stride(index, 0); - self.keep(index, None); + self.keep(index, kept); } /// The slots [`HostHeap::note_buffer`] found stale for slot `index`, with @@ -3520,13 +3523,15 @@ impl HostHeap { /// host cannot. pub(crate) fn make_at(&self, index: u32, view: &View) { let kept = make_twinned(view, self.at(index), self.twin(index)); - if kept.is_none() { - null_for(view, self.at(index)); - } + let stand_in = if kept.is_none() { + neutral_for(view, self.at(index)) + } else { + None + }; self.put(index); self.twin_made(index, kept.is_some() && twinned(view)); self.write_stride(index, if kept.is_some() { view_stride_word(view) } else { 0 }); - self.keep(index, kept.flatten()); + self.keep(index, kept.flatten().or(stand_in)); } /// Makes slot `index` (a dynamic one) the view the record `words` names, @@ -4092,14 +4097,16 @@ impl HostHeap { } else { make_twinned(&view, self.at(index), self.twin(index)) }; - if kept.is_none() && !self.sampler { - null_for(&view, self.at(index)); - } + let stand_in = if kept.is_none() && !self.sampler { + neutral_for(&view, self.at(index)) + } else { + None + }; if kept.is_some() || !self.sampler { self.put(index); } self.twin_made(index, kept.is_some() && twinned(&view)); - self.keep(index, kept.flatten()); + self.keep(index, kept.flatten().or(stand_in)); self.quick_is(index, if later { 0 } else { key }); drop(held); self.unmake_stale(index, stale); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e3a7be8bf..f2359cb45 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -3773,6 +3773,8 @@ impl State { DISPATCHED.fetch_add(1, Ordering::Relaxed); if let Some(role) = p.stages.first().and_then(|s| s.shader.ambient) && crate::ambient::on() + // A resolve of no groups writes nothing: a hold would rewrite what the image held before. + && !(role == crate::ambient::Role::Reflect && (x == 0 || y == 0 || z == 0)) && self.ambient(list, p, role) { self.host_pipeline = 0; @@ -3783,7 +3785,23 @@ impl State { /// The stand-in for the indirect light after a dispatch of `p` /// (`crate::ambient`). Whether it recorded anything. fn ambient(&self, list: &HostList, p: &HostPipeline, role: crate::ambient::Role) -> bool { - use crate::ambient::{AIR, DEPTH, LIGHT, MISS_DEPTH, MISS_LIGHT, MissNote, RADIANCE, Role, Views}; + use crate::ambient::{ + AIR, ALPHA, DEPTH, LIGHT, MISS_DEPTH, MISS_LIGHT, MissNote, RADIANCE, REFLECTIONS, Role, Views, + }; + // Each part has a switch of its own, on unless 0, that `VICTORY_AB` can flip while the + // title runs (diagnostics builds): one scene with and without it. The light the + // surfaces send out is kept either way. + let live = match role { + Role::Resolve => crate::toggled!("VICTORY_AMBIENT_ON"), + Role::Miss => crate::toggled!("VICTORY_AMBIENT_SPECULAR_ON"), + Role::Air => crate::toggled!("VICTORY_AMBIENT_AIR_ON"), + Role::Alpha => crate::toggled!("VICTORY_AMBIENT_ALPHA_ON"), + Role::Reflect => crate::toggled!("VICTORY_AMBIENT_REFLECT_ON"), + Role::Radiance => true, + }; + if !live { + return false; + } let Some(t) = p.stages.first().map(|s| s.translated()) else { return false; }; @@ -3810,7 +3828,7 @@ impl State { // 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"); + let alpha_too = crate::toggled!("VICTORY_AMBIENT_SPECULAR_ALPHA"); if role == Role::Miss && !(layer == crate::ambient::MISS_OPAQUE || (alpha_too && layer == crate::ambient::MISS_ALPHA)) { @@ -3850,7 +3868,9 @@ impl State { Role::Resolve => LIGHT, Role::Radiance => RADIANCE, Role::Air => AIR, + Role::Alpha => ALPHA, Role::Miss => MISS_LIGHT, + Role::Reflect => REFLECTIONS[0], }; // Variants of the miss program bind the rays' image and the depth at // other places of their tables than the one found first (run @@ -3911,6 +3931,15 @@ impl State { d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && d.Format.0 == 26 }) }), + // The first of the places that holds a 2D image of the format + // (R32_UINT holding R9G9B9E5), else the first such in the tables. + Role::Reflect => { + let fits = |d: &D3D12_RESOURCE_DESC| d.Format.0 == 42 && d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D; + REFLECTIONS + .iter() + .find_map(|&at| entry(ResourceType::Uav, at).filter(|(d, _)| fits(d))) + .or_else(|| scan(ResourceType::Uav, &fits)) + } _ => entry(ResourceType::Uav, at), }; let usual_depth = |at: (u8, u32)| { @@ -4008,12 +4037,14 @@ impl State { } plain }), - Role::Radiance | Role::Air => image, + Role::Radiance | Role::Air | Role::Alpha | Role::Reflect => image, }; let (Some((of, image)), Some((seen, depth))) = (image, depth) else { once!(?role, "no stand-in for the indirect light: other tables"); if role == Role::Miss { crate::ambient::note_miss(MissNote::NotReady); + } + if matches!(role, Role::Miss | Role::Alpha) { // Once per program: what its tables hold, so one run names // the place of the rays' image and of the depth. static SEEN: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); @@ -4047,7 +4078,7 @@ impl State { return false; }; // (R32_UINT holding R9G9B9E5; R11G11B10_FLOAT.) - let format = if role == Role::Resolve { 42 } else { 26 }; + let format = if matches!(role, Role::Resolve | Role::Reflect) { 42 } else { 26 }; let volume = of.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; // The miss program's image is of half the picture's size, its depth // (32-bit) of the whole. @@ -4070,8 +4101,8 @@ impl State { } _ => (seen.Width, seen.Height) == (of.Width, of.Height), }; - if of.Format.0 != format || !sizes || volume != (role == Role::Air) { - once!(?role, format = of.Format.0, "no stand-in for the indirect light: another image"); + if of.Format.0 != format || !sizes || volume != matches!(role, Role::Air | Role::Alpha) { + once!(?role, format = of.Format.0, width = of.Width, height = of.Height, slices = of.DepthOrArraySize, "no stand-in for the indirect light: another image"); if role == Role::Miss { crate::ambient::note_miss(MissNote::NotReady); } @@ -5412,12 +5443,19 @@ impl State { self.drew(Some(p)); } // The stand-in for reflections after the program that gives rays - // that found nothing the sky (`crate::ambient`, `Role::Miss`): the + // that found nothing the sky (`crate::ambient`, `Role::Miss`), and + // the bound of the transparent surfaces' light (`Role::Alpha`): the // execution held back is recorded first. (Not after one joined to // the run before: the tables noted are another program's.) if kind == DISPATCH && !joined - && let Some(role @ crate::ambient::Role::Miss) = p.stages.first().and_then(|s| s.shader.ambient) + && let Some( + role @ (crate::ambient::Role::Miss | crate::ambient::Role::Alpha | crate::ambient::Role::Reflect), + ) = p.stages.first().and_then(|s| s.shader.ambient) + // The reflections' resolve not after a count buffer: a count of 0 + // runs no resolve, and the hold would rewrite the image's earlier + // contents (Vice-Tay fa90adf). + && (role != crate::ambient::Role::Reflect || counter.is_none()) && crate::ambient::on() { unsettle_indirect(list); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 66710676f..1af6c2cc0 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -76,7 +76,28 @@ unsafe impl Sync for Host {} /// releases reach the host at once, from its own threads, while the host /// runs a submission: freeing there is a GPU page fault on the freed /// texture (a device hang). -static RETIRED: Mutex> = Mutex::new(std::collections::VecDeque::new()); +/// +/// A queue to each thread that retires, of [`RETIRED_QUEUES`] taken in turn +/// ([`retired`]), each in the order its thread retired. One queue under one +/// lock was what the threads that record the title's lists waited for: eight +/// of them let go of some 20,000 slots' resources a frame, each a push of a +/// few nanoseconds, but a thread that finds the lock taken sleeps and is +/// woken 50 microseconds later or more. 3.3 of the 22 ms a frame each of +/// them was at work, and 0.7 ms of the submitting thread's frame (a profile +/// of the prologue's cell, RTX 3090 Ti, Ryzen 9 9950X3D, Series S profile). +static RETIRED: [Mutex>; RETIRED_QUEUES] = + [const { Mutex::new(std::collections::VecDeque::new()) }; RETIRED_QUEUES]; +const RETIRED_QUEUES: usize = 32; + +/// This thread's queue of [`RETIRED`]. +fn retired() -> &'static Mutex> { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + thread_local! { + static MINE: usize = NEXT.fetch_add(1, Ordering::Relaxed) % RETIRED_QUEUES; + } + // (A thread that is ending has none any more: the first.) + &RETIRED[MINE.try_with(|mine| *mine).unwrap_or(0)] +} /// Submissions started and finished (waited for). static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -481,7 +502,7 @@ pub(crate) fn retire(object: T) { return; } RETIREMENTS[1].fetch_add(1, Ordering::Relaxed); - RETIRED + retired() .lock() .unwrap_or_else(|e| e.into_inner()) .push_back((started, Retired::Any(Box::new(object)))); @@ -497,7 +518,7 @@ pub(crate) fn retire_resource(object: ID3D12Resource) { return; } RETIREMENTS[1].fetch_add(1, Ordering::Relaxed); - RETIRED.lock().unwrap_or_else(|e| e.into_inner()).push_back((started, Retired::Resource(object))); + retired().lock().unwrap_or_else(|e| e.into_inner()).push_back((started, Retired::Resource(object))); } /// How many submissions later than it could (the last one that may use it @@ -515,18 +536,20 @@ fn bury_lag() -> u64 { } /// Drops what waited for submissions up to `finished` ([`bury_lag`]). The -/// numbers come in order, but for threads that overtake each other: one of -/// those is dropped a little later than it could be. +/// numbers of a queue come in order, but for a submission begun between a +/// thread's two looks ([`retire`]): what follows such a one is dropped a +/// little later than it could be. fn bury(finished: u64) { let finished = finished.saturating_sub(bury_lag()); - let done: Vec<(u64, Retired)> = { - let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner()); + let mut done: Vec<(u64, Retired)> = Vec::new(); + for queue in &RETIRED { + let mut retired = queue.lock().unwrap_or_else(|e| e.into_inner()); let n = retired.iter().take_while(|(at, _)| *at <= finished).count(); - if n == 0 { - return; + if n != 0 { + done.extend(retired.drain(..n)); } - retired.drain(..n).collect() - }; + } + // (Dropped with no queue's lock held: a release each.) drop(done); } @@ -2615,9 +2638,19 @@ struct CardRange { /// Looked at by `crate::picked`, and not declared: what is found changed /// there was written through a view nobody declared. Not landed. picked: bool, + /// Picked by [`lazy`]: compared and stored (mode 2), and what is found + /// tells `lazy` which pieces were written lately. + lazy: bool, } impl CardPlan { + /// [`lazy`] is told which of its pieces the compare found written. + fn lazy_found(&self, differs: &[u32]) { + for r in self.ranges.iter().filter(|r| r.lazy && r.compared) { + lazy::found(&r.shadow, &r.span, |p| differs.get((r.at + p) as usize).is_some_and(|&d| torn::flagged(d))); + } + } + /// `crate::picked` is told where what it looked at changed, by the /// compare's results. fn picked_found(&self, differs: &[u32]) { @@ -3111,6 +3144,9 @@ struct Line { /// The title memory the flights' shaders and texture readbacks may write /// (address, end), in order and joined. written: Vec<(usize, usize)>, + /// `written`, with big card copies' parts only where written lately + /// ([`lazy::narrow`]; empty when that is off): what steps wait for. + narrow: Vec<(usize, usize)>, /// Host lists in the flights. lists: usize, /// The value signalled on the host's fence behind the last flight. @@ -3139,6 +3175,7 @@ unsafe impl Send for Line {} static LINE: Mutex = Mutex::new(Line { line: Vec::new(), written: Vec::new(), + narrow: Vec::new(), lists: 0, target: 0, settling: false, @@ -3154,6 +3191,33 @@ fn line() -> std::sync::MutexGuard<'static, Line> { LINE.lock().unwrap_or_else(|e| e.into_inner()) } +impl Line { + /// What steps of a submission wait for (or are done on the card for): + /// `written`, or with [`lazy::narrow`] its narrowed form. + fn blocking(&self) -> &Vec<(usize, usize)> { + if lazy::narrow() { &self.narrow } else { &self.written } + } + + /// A flight's declared writes and texture read-backs join `written` (and + /// `narrow`). + fn joined(&mut self, back: &[Declared], textures: &[(usize, usize)]) { + join_ranges(&mut self.written, back.iter().flat_map(|(_, r)| r.iter().copied()).chain(textures.iter().copied())); + if lazy::narrow() { + let mut more: Vec<(usize, usize)> = textures.to_vec(); + for (shadow, ranges) in back { + if lazy::on(shadow) { + for &(from, to) in ranges { + lazy::hot_within(shadow, from, to, &mut more); + } + } else { + more.extend(ranges.iter().copied()); + } + } + join_ranges(&mut self.narrow, more); + } + } +} + /// Why flights were settled ([`LATE_STATS`]' places from 2 on). pub(crate) const WHY_SYNC: usize = 2; const WHY_CARD_DONE: usize = 3; @@ -3218,10 +3282,10 @@ fn flying() -> bool { fn late_blocked(runs: &[&HostList]) -> Option { let (written, copies) = { let line = line(); - if line.written.is_empty() { + if line.blocking().is_empty() { return None; } - (line.written.clone(), card_steps::copies(&line)) + (line.blocking().clone(), card_steps::copies(&line)) }; blocked_by(&written, runs, true).or_else(|| card_steps::copied_read(&copies, runs).then_some(WHY_READ)) } @@ -4199,6 +4263,7 @@ mod card_steps; #[cfg(feature = "diagnostics")] pub(crate) mod indirects; mod font; +mod lazy; mod menu; mod panel; mod place; @@ -4906,6 +4971,12 @@ impl Host { }; // The same pieces in fewer passes (`rehash_runs`). let runs = if joins { crate::shadow::joined_piece_runs(runs) } else { runs }; + // Pending pieces keep their hashes (`lazy`). + let runs = if lazy::on(shadow) && !whole.iter().any(|s| Arc::ptr_eq(s, shadow)) { + lazy::hold_back(shadow, runs) + } else { + runs + }; CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed); CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::(), Ordering::Relaxed); for run in runs { @@ -4946,10 +5017,36 @@ impl Host { } } let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); + let lazy_copy = twin && lazy::on(shadow); + let start = shadow.span().0 as usize; for (from, to) in spans { let Some(span) = shadow.card_span(from, to) else { continue; }; + if lazy_copy { + // Only what `lazy` picks; the rest is left pending. + for (i0, i1) in lazy::select(shadow, &span) { + let (lo, hi) = (shadow.card_piece(&span, i0).0, shadow.card_piece(&span, i1 - 1).1); + if lo >= hi { + continue; + } + let span = shadow.card_run(lo, hi); + let compared = u64::from(at + span.pieces) * 4 <= work.differs.2; + plan.ranges.push(CardRange { + shadow: shadow.clone(), + declared: (start + lo, start + hi), + span, + at, + compared, + picked: false, + lazy: true, + }); + if compared { + at += span.pieces; + } + } + continue; + } let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2; plan.ranges.push(CardRange { shadow: shadow.clone(), @@ -4958,12 +5055,44 @@ impl Host { at, compared, picked: false, + lazy: false, }); if compared { at += span.pieces; } } } + // `lazy`: the pieces forced by a send and the sweep's next ones, of + // the copies declared or sent up here. + if lazy::min().is_some() { + let mut copies: Vec<&Arc> = Vec::new(); + for shadow in declared.iter().map(|d| &d.0).chain(plan._synced.iter()) { + if lazy::on(shadow) + && shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()) + && !copies.iter().any(|s| Arc::ptr_eq(s, shadow)) + { + copies.push(shadow); + } + } + for shadow in copies { + let start = shadow.span().0 as usize; + for span in lazy::sweep(shadow) { + let compared = u64::from(at + span.pieces) * 4 <= work.differs.2; + plan.ranges.push(CardRange { + shadow: shadow.clone(), + declared: (start + span.from as usize, start + span.to as usize), + span, + at, + compared, + picked: false, + lazy: true, + }); + if compared { + at += span.pieces; + } + } + } + } for (shadow, from, len) in looked { let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); if let Some(span) = shadow.card_span(*from, from + len) @@ -4977,6 +5106,7 @@ impl Host { at, compared: true, picked: true, + lazy: false, }); at += span.pieces; } @@ -5015,7 +5145,10 @@ impl Host { list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress()); // (What is only looked at keeps its hashes: what // changed there is the next declared range's to land.) - card_pass(list, &r.span, size as u32, r.at, if flown && !r.picked { 2 } else { 1 }); + // (`lazy`'s keep what they find: a piece left out + // keeps its old hashes, one compared takes new ones.) + let mode = if r.lazy || flown && !r.picked { 2 } else { 1 }; + card_pass(list, &r.span, size as u32, r.at, mode); CARD_PASSES[2].fetch_add(1, Ordering::Relaxed); } list.Close()?; @@ -5145,6 +5278,7 @@ impl Host { let mut seen = std::collections::HashSet::new(); for &(plan, behind) in plans { plan.picked_found(differs); + plan.lazy_found(differs); let flags: Vec<(usize, u32, bool)> = plan .ranges .iter() @@ -5479,6 +5613,7 @@ impl Host { let Line { line: items, written, + narrow, lists, settling, poke, @@ -5492,16 +5627,31 @@ impl Host { landing.clear(); // What is still in the air, from the flights that are. written.clear(); + narrow.clear(); *lists = 0; let mut ranges = Vec::new(); + let mut narrowed = Vec::new(); for item in items.iter() { if let Late::Run(flight) = item { *lists += flight.order.len().max(1); ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied())); ranges.extend(flight.texture_back_ranges.iter().copied()); + if lazy::narrow() { + narrowed.extend(flight.texture_back_ranges.iter().copied()); + for (shadow, r) in &flight.back { + if lazy::on(shadow) { + for &(from, to) in r { + lazy::hot_within(shadow, from, to, &mut narrowed); + } + } else { + narrowed.extend(r.iter().copied()); + } + } + } } } join_ranges(written, ranges); + join_ranges(narrow, narrowed); *settling = false; // The landed lists are reset, and what queues hold looked at, // by the helper thread (they take locks a waiter may hold). @@ -5539,6 +5689,7 @@ impl Host { let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new(); let mut total = 0u64; plan.picked_found(differs); + plan.lazy_found(differs); for (i, r) in plan.ranges.iter().enumerate().filter(|(_, r)| !r.picked) { for p in 0..r.span.pieces { if r.compared && !torn::flagged(differs[(r.at + p) as usize]) { @@ -5714,14 +5865,8 @@ impl Host { let sizes = crate::memory::asked_sizes(order.iter().map(|&i| lists[i].host())); let most = { let mut line = line(); - let Line { line: items, written, lists: flying, target, .. } = &mut *line; - join_ranges( - written, - sent.back - .iter() - .flat_map(|(_, ranges)| ranges.iter().copied()) - .chain(sent.texture_back_ranges.iter().copied()), - ); + line.joined(&sent.back, &sent.texture_back_ranges); + let Line { line: items, lists: flying, target, .. } = &mut *line; *flying += order.len(); *target = *submitted; items.push(Late::Run(Flight { @@ -5770,14 +5915,8 @@ impl Host { let number = sent.number; { let mut line = line(); - let Line { line: items, written, lists: flying, target, .. } = &mut *line; - join_ranges( - written, - sent.back - .iter() - .flat_map(|(_, ranges)| ranges.iter().copied()) - .chain(sent.texture_back_ranges.iter().copied()), - ); + line.joined(&sent.back, &sent.texture_back_ranges); + let Line { line: items, lists: flying, target, .. } = &mut *line; *flying += 1; *target = *submitted; items.push(Late::Run(Flight { @@ -5837,6 +5976,7 @@ impl Host { } line.settling = true; line.written.clear(); + line.narrow.clear(); line.lists = 0; std::mem::take(&mut line.line) }; @@ -6020,6 +6160,7 @@ impl Host { crate::streamline::hudless_submitted(id); } } + crate::cores::keep_own_threads(); let was_working = working(true); submitting(1, runs.len()); // The round of the heaps' records asked for when the title submitted @@ -6049,7 +6190,7 @@ impl Host { // Only until the flights that may write what is read have // landed: their copy-back's end, not the card's other work. relay_wait(why, |line| { - blocked_by(&line.written, runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs) + blocked_by(line.blocking(), runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs) }); } else { self.settle(&mut submitted, why); diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index 3baf286c5..f0f966f53 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -580,7 +580,7 @@ pub(super) fn cut_for(runs: &[&HostList]) -> Option { if first + 1 == runs.len() { return None; } - let written = line().written.clone(); + let written = line().blocking().clone(); blocked_by(&written, runs, false)?; let (does, steps) = does_of(&written, runs); let mut behind = None; @@ -769,10 +769,10 @@ impl Host { } let (written, copies) = { let line = line(); - if line.written.is_empty() { + if line.blocking().is_empty() { return None; } - (line.written.clone(), copies(&line)) + (line.blocking().clone(), copies(&line)) }; blocked_by(&written, runs, false)?; let taken = if copied_read(&copies, runs) { diff --git a/crates/victory-gpu/src/host/lazy.rs b/crates/victory-gpu/src/host/lazy.rs new file mode 100644 index 000000000..3ea40fd39 --- /dev/null +++ b/crates/victory-gpu/src/host/lazy.rs @@ -0,0 +1,311 @@ +//! Fewer compares of big copies in the card's memory (`VICTORY_LAZY_COMPARE_MB=`, +//! off by default). +//! +//! A copy whose shader writes are declared is compared on the card after +//! every submission, every declared piece. For the constants heap +//! (174 MB) that is 2.2 GB of the card's reads a frame to find about +//! 2.6 MB that shaders wrote. With this switch, of a copy at least that +//! large, a submission compares only: +//! +//! - the pieces found written lately ("hot", for `VICTORY_LAZY_HOT` +//! compares, 64 by default, after the last time one was found written); +//! - the pieces about to be sent up that were left out of a compare since +//! their last one ("forced": they are not hashed again when sent, so the +//! compare still sees what shaders wrote there before); +//! - the next `VICTORY_LAZY_SWEEP` pieces (128 by default) of those left +//! out, in turn, so a piece written for the first time is found within a +//! sweep of the copy. +//! +//! The other declared pieces are left out and marked pending; their hashes +//! stay as they were, so what shaders wrote there is found when the sweep +//! or a send reaches them. These compares store the hashes they make +//! (mode 2), so a piece the CPU sent up and nothing wrote is not found +//! again. What is found is fetched and merged as before: a merge takes only +//! the bytes that differ from the CPU's side, so a piece found that nothing +//! wrote costs a fetch and nothing else. Left out: shader bytes in a 4 KiB +//! page that the CPU sends up before the piece's compare are lost. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use crate::shadow::{CardSpan, Shadow}; + +/// The smallest copy (bytes) taken this way, if on. +pub(super) fn min() -> Option { + static MIN: OnceLock> = OnceLock::new(); + *MIN.get_or_init(|| { + let mb = std::env::var("VICTORY_LAZY_COMPARE_MB").ok()?.trim().parse::().ok().filter(|&mb| mb > 0)?; + tracing::info!( + mb, + hot = hot_life(), + sweep = sweep_len(), + "copies in the card's memory this large are compared only where written lately, before a send, and in a sweep \ + (VICTORY_LAZY_COMPARE_MB)" + ); + Some(mb << 20) + }) +} + +fn hot_life() -> u8 { + static N: OnceLock = OnceLock::new(); + *N.get_or_init(|| std::env::var("VICTORY_LAZY_HOT").ok().and_then(|v| v.trim().parse().ok()).filter(|&n| n > 0).unwrap_or(64)) +} + +fn sweep_len() -> usize { + static N: OnceLock = OnceLock::new(); + *N.get_or_init(|| std::env::var("VICTORY_LAZY_SWEEP").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(128)) +} + +/// Whether what flights may write of such a copy counts, for the steps that +/// wait for flights or are done on the card in their order, as only its +/// pieces written lately (`VICTORY_LAZY_NARROW=1`, with +/// `VICTORY_LAZY_COMPARE_MB`). The skinning passes declare the whole +/// constants heap written; every constant read of it then waited or was +/// done on the card (5.5 ms a frame of planning on the submitting thread). +/// A piece written for the first time is read as the title has it until the +/// sweep finds it, as its write-back is late until then anyway. +pub(super) fn narrow() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + let on = min().is_some() && std::env::var_os("VICTORY_LAZY_NARROW").is_some_and(|v| v == "1"); + if on { + tracing::info!("flights' writes to big card copies count only where written lately (VICTORY_LAZY_NARROW)"); + } + on + }) +} + +/// Of the title range `[from, to)` of `shadow`: the parts in pieces written +/// lately, as title ranges. +pub(super) fn hot_within(shadow: &Shadow, from: usize, to: usize, out: &mut Vec<(usize, usize)>) { + let start = shadow.span().0 as usize; + let len = shadow.span().1 as usize; + let (lo, hi) = (from.max(start) - start, to.min(start + len).saturating_sub(start)); + if lo >= hi { + return; + } + let (first, last) = (shadow.card_piece_of(lo), shadow.card_piece_of(hi - 1)); + let states = STATES.lock().unwrap_or_else(|e| e.into_inner()); + let Some(state) = states.as_ref().and_then(|s| s.get(&shadow.id())) else { + return; + }; + for piece in first..=last { + if state.hot.get(piece as usize).is_some_and(|&h| h > 0) { + let (a, b) = piece_offsets(shadow, piece); + let (a, b) = (a.max(lo) + start, b.min(hi) + start); + match out.last_mut() { + Some(last) if last.1 >= a => last.1 = last.1.max(b), + _ => out.push((a, b)), + } + } + } +} + +/// Whether `shadow` is compared this way. +pub(super) fn on(shadow: &Shadow) -> bool { + min().is_some_and(|min| shadow.span().1 >= min) +} + +#[derive(Default)] +struct State { + /// Per piece: compares left while it counts as written lately. + hot: Vec, + /// Per piece: left out of a compare since it was last compared. + pending: Vec, + /// Per piece: pending and sent up without being hashed again. + forced: Vec, + cursor: usize, +} + +impl State { + fn sized(&mut self, pieces: usize) { + if self.hot.len() < pieces { + self.hot.resize(pieces, 0); + self.pending.resize(pieces, false); + self.forced.resize(pieces, false); + } + } +} + +static STATES: Mutex>> = Mutex::new(None); + +/// Since the last line: pieces compared (hot, forced, swept), left out, found. +static STATS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; + +fn with(shadow: &Shadow, f: impl FnOnce(&mut State) -> R) -> R { + let pieces = pieces_of(shadow); + let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner()); + let state = states.get_or_insert_with(HashMap::new).entry(shadow.id()).or_default(); + state.sized(pieces); + f(state) +} + +/// How many pieces the copy has (piece 0 holds offset 0). +fn pieces_of(shadow: &Shadow) -> usize { + let len = shadow.span().1 as usize; + if len == 0 { 0 } else { shadow.card_piece_of(len - 1) as usize + 1 } +} + +/// The offsets of the copy's piece `piece`. +fn piece_offsets(shadow: &Shadow, piece: u32) -> (usize, usize) { + let full = shadow.card_run(0, usize::MAX); + shadow.card_piece(&full, piece - full.first) +} + +/// Contiguous runs of the sorted, unique `pieces`, as spans of the copy. +fn runs_of(shadow: &Shadow, pieces: &[u32]) -> Vec { + let mut out = Vec::new(); + let mut i = 0; + while i < pieces.len() { + let mut j = i + 1; + while j < pieces.len() && pieces[j] == pieces[j - 1] + 1 { + j += 1; + } + let lo = piece_offsets(shadow, pieces[i]).0; + let hi = piece_offsets(shadow, pieces[j - 1]).1; + if lo < hi { + out.push(shadow.card_run(lo, hi)); + } + i = j; + } + out +} + +/// The hash passes after a send: of `runs`, the pending pieces are left +/// out (and forced into this submission's compare). +pub(super) fn hold_back(shadow: &Shadow, runs: Vec) -> Vec { + let mut kept: Vec = with(shadow, |state| { + let mut kept = Vec::new(); + for run in &runs { + for piece in run.first..run.first + run.pieces { + let p = piece as usize; + if state.pending.get(p).copied().unwrap_or(false) { + state.forced[p] = true; + } else { + kept.push(piece); + } + } + } + kept + }); + kept.sort_unstable(); + kept.dedup(); + runs_of(shadow, &kept) +} + +/// Of a declared `span` of the copy: the runs `[i0, i1)` of its pieces (by +/// index in the span) to compare now; the others are marked pending. +pub(super) fn select(shadow: &Shadow, span: &CardSpan) -> Vec<(u32, u32)> { + with(shadow, |state| { + let mut out: Vec<(u32, u32)> = Vec::new(); + let (mut now, mut left) = (0u64, 0u64); + for i in 0..span.pieces { + let p = (span.first + i) as usize; + let Some(&hot) = state.hot.get(p) else { + continue; + }; + if hot > 0 || state.forced[p] { + state.pending[p] = false; + state.forced[p] = false; + now += 1; + match out.last_mut() { + Some(last) if last.1 == i => last.1 = i + 1, + _ => out.push((i, i + 1)), + } + } else { + state.pending[p] = true; + left += 1; + } + } + STATS[0].fetch_add(now, Ordering::Relaxed); + STATS[3].fetch_add(left, Ordering::Relaxed); + out + }) +} + +/// After the declared spans: the copy's forced pieces still pending, and the +/// next pending pieces of the sweep, as spans to compare now. +pub(super) fn sweep(shadow: &Shadow) -> Vec { + let pieces: Vec = with(shadow, |state| { + let n = state.pending.len(); + let mut out = Vec::new(); + for p in 0..n { + if state.forced[p] { + state.forced[p] = false; + state.pending[p] = false; + out.push(p as u32); + } + } + STATS[1].fetch_add(out.len() as u64, Ordering::Relaxed); + let (mut taken, mut looked) = (0, 0); + while taken < sweep_len() && looked < n { + let p = state.cursor % n.max(1); + state.cursor = (p + 1) % n.max(1); + looked += 1; + if state.pending[p] { + state.pending[p] = false; + out.push(p as u32); + taken += 1; + } + } + STATS[2].fetch_add(taken as u64, Ordering::Relaxed); + out + }); + let mut pieces = pieces; + pieces.sort_unstable(); + pieces.dedup(); + runs_of(shadow, &pieces) +} + +/// A compared piece of the copy was found written (`flagged`) or not. +pub(super) fn found(shadow: &Shadow, span: &CardSpan, flagged: impl Fn(u32) -> bool) { + let life = hot_life(); + let mut hits = 0; + with(shadow, |state| { + for i in 0..span.pieces { + let p = (span.first + i) as usize; + let Some(hot) = state.hot.get_mut(p) else { + continue; + }; + if flagged(i) { + *hot = life; + hits += 1; + } else { + *hot = hot.saturating_sub(1); + } + } + }); + STATS[4].fetch_add(hits, Ordering::Relaxed); + log(); +} + +fn log() { + static LAST: Mutex> = Mutex::new(None); + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + let now = std::time::Instant::now(); + if last.is_some_and(|t| now.duration_since(t).as_secs() < 5) { + return; + } + let first = last.is_none(); + *last = Some(now); + if first { + return; + } + let [hot, forced, swept, left, found] = std::array::from_fn(|i| STATS[i].swap(0, Ordering::Relaxed)); + let hot_now: usize = STATES + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .map_or(0, |s| s.values().map(|s| s.hot.iter().filter(|&&h| h > 0).count()).sum()); + tracing::info!( + hot, + forced, + swept, + left, + found, + hot_now, + "lazy compares in the last 5 s (VICTORY_LAZY_COMPARE_MB): pieces compared as written lately, before a send, in the \ + sweep; left out; found written; written lately now" + ); +} diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 2f1beef00..1d4061305 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -2673,6 +2673,15 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { }; let _ = host.log_messages(); let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile"); + // The clamp as with `VICTORY_INDIRECT_REST=1` (off by default since + // 545f890): a record that does not fit takes the rest of the budget, + // so what the big records spend shows in the small one after them. + let rest = make_from(&host.device, &SOURCE.replace("REST ?", "true ?")).expect("the clamp must compile"); + let bound = |src: (&ID3D12Resource, u64), spec: (u32, u32, u32)| { + let bytes = validate_layout(spec, src.1, None)?; + let (budget, dst) = (list.budget()?, list.indirect_scratch(bytes)?); + clamp_into(&list, &rest, &dst, budget, src, None, spec, false).then_some(dst) + }; const KIND_DISPATCH: u32 = 2; const STRIDE: u32 = 12; let signature = { @@ -2725,8 +2734,8 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() }; for round in 0..2 { // Spends the budget (clamped, not executed), then one group. - bound(&list, (&big, 0), None, (KIND_DISPATCH, STRIDE, 3)).unwrap(); - let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap(); + bound((&big, 0), (KIND_DISPATCH, STRIDE, 3)).unwrap(); + let scratch = bound((&small, 0), (KIND_DISPATCH, STRIDE, 1)).unwrap(); // SAFETY: an open list; the worker's root signature and // pipeline; buffers the test holds until the list has run. unsafe { @@ -2747,7 +2756,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { } // A recording with only the small record: the budget is empty // again, so it runs. - let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap(); + let scratch = bound((&small, 0), (KIND_DISPATCH, STRIDE, 1)).unwrap(); // SAFETY: as above. unsafe { list.list.SetComputeRootSignature(&worker.root); @@ -3154,7 +3163,10 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) { let Some(mut warp) = WarpHarness::new() else { return; }; - let pass = make_from(&warp.device, batch::SOURCE).expect("the batched clamp must compile on WARP"); + // A record that does not fit takes the rest (`VICTORY_INDIRECT_REST=1`, + // off by default since 545f890): the budget this test charges. + let source = batch::SOURCE.replace("REST ?", "true ?"); + let pass = make_from(&warp.device, &source).expect("the batched clamp must compile on WARP"); const BUDGET: u32 = 1 << 27; // 2^26 vertices each, as much as a draw is let run: two fill it. for (times, records, filled) in [(1u32, 3u64, 2usize), (2, 1, 1), (1, 1, 1), (3, 1, 0)] { diff --git a/crates/victory-gpu/src/list/thin.rs b/crates/victory-gpu/src/list/thin.rs index eb7e115c2..848e15b4a 100644 --- a/crates/victory-gpu/src/list/thin.rs +++ b/crates/victory-gpu/src/list/thin.rs @@ -300,7 +300,8 @@ fn back_list(kind: u32) -> This { } fn start() { - let threads = std::env::var("VICTORY_THIN_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(8usize).clamp(1, 32); + let threads = + std::env::var("VICTORY_THIN_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or_else(crate::cores::list_threads).clamp(1, 32); for i in 0..threads { let worker = move || { crate::cores::keep_many_on_fast_cores("victory-list"); diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index f8cd62849..d3b2a2dfa 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -516,7 +516,30 @@ fn skipped_shader(p: &Pipeline) -> Option<&str> { #[cfg(all(windows, feature = "diagnostics"))] pub(crate) fn is_skipped(this: This) -> bool { - !this.is_null() && skipped_shader(pipeline(this)).is_some() + !this.is_null() && (skipped_shader(pipeline(this)).is_some() || skipped_in_turn(pipeline(this))) +} + +/// `VICTORY_SKIP_A` to `VICTORY_SKIP_D` (shader hashes, as +/// `VICTORY_SKIP_PIPELINES` takes them): skipped only while the group's +/// switch (`VICTORY_SKIP_A_ON` and so on) is on, and `VICTORY_AB` flips +/// those while the title runs: one view with and without a pass. +#[cfg(all(windows, feature = "diagnostics"))] +fn skipped_in_turn(p: &Pipeline) -> bool { + static GROUPS: OnceLock<[Vec; 4]> = OnceLock::new(); + let groups = GROUPS.get_or_init(|| { + ["VICTORY_SKIP_A", "VICTORY_SKIP_B", "VICTORY_SKIP_C", "VICTORY_SKIP_D"] + .map(|name| parse_skip_hashes(&std::env::var(name).unwrap_or_default())) + }); + if groups.iter().all(Vec::is_empty) { + return false; + } + let on = [ + crate::asked_for!("VICTORY_SKIP_A_ON"), + crate::asked_for!("VICTORY_SKIP_B_ON"), + crate::asked_for!("VICTORY_SKIP_C_ON"), + crate::asked_for!("VICTORY_SKIP_D_ON"), + ]; + groups.iter().zip(on).any(|(hashes, on)| on && p.shaders.iter().any(|shader| hashes.contains(&shader.hash))) } /// Counts a draw or dispatch of `this` intentionally skipped or dropped diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index d5343c84b..515d9a5aa 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -1237,14 +1237,15 @@ mod tests { let (root, root_blob) = root_signature(&host.device, &[], &[], false).unwrap(); let mut g = GraphicsState::default(); - // Subobject 21 (`DEPTH_STENCIL1`) with `DepthBoundsTestEnable = true`, - // depth test itself off so only depth bounds gates the draw. + // Subobject 21 (`DEPTH_STENCIL1`) enables depth bounds. + // Keep the depth buffer active. ALWAYS and a zero write mask leave + // depth bounds as the only test that can reject a fragment. #[repr(C, align(8))] struct Sub21(u32, D3D12_DEPTH_STENCIL_DESC1); let sub = Sub21( 21, D3D12_DEPTH_STENCIL_DESC1 { - DepthEnable: false.into(), + DepthEnable: true.into(), DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS, DepthBoundsTestEnable: true.into(), diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index 06db5a1e9..40f1f5632 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -637,15 +637,56 @@ pub(crate) fn pipeline( Ok(pso) } +/// As [`save`], from a worker while more pipelines are still queued. +/// +/// Every save serialises the whole library (over a gigabyte once it is warm) +/// and, while it does, holds off every store; in the middle of a burst of new +/// pipelines (a new area, a cutscene) that is exactly when the title is +/// waiting on them, and the write competes with texture streaming for the +/// disk. Saves in a burst are kept to one every `VICTORY_LIBRARY_SAVE_BUSY_S` +/// seconds (default 180; 20 as before); the save when the queue runs dry and +/// the one at exit are as they were. +pub(crate) fn save_while_busy() { + static LAST: Mutex> = Mutex::new(None); + static EVERY: OnceLock = OnceLock::new(); + let every = *EVERY.get_or_init(|| { + let secs = std::env::var("VICTORY_LIBRARY_SAVE_BUSY_S").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(180); + std::time::Duration::from_secs(secs) + }); + { + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + match *last { + // The first busy save of the run waits a full interval too. + None => { + *last = Some(std::time::Instant::now()); + return; + } + Some(t) if t.elapsed() < every => return, + _ => *last = Some(std::time::Instant::now()), + } + } + save(false); +} + /// Writes the library and the early list if pipelines were added since the /// last save and `SAVE_EVERY` has passed (or `now`). +/// +/// Under host memory pressure ([`crate::residency::pressured`]) the interval +/// is `SAVE_EVERY_PRESSURED` instead: the serialised library (over a gigabyte +/// once warm) is written through the PC's memory, and on a 32 GB PC that ran +/// pressured for a whole session (log of 2026-11-27, commit headroom 3.4 GB) +/// those pages pushed the title's own out, and its threads stalled on page +/// faults. The save at exit (`now`) is unchanged, so nothing made is lost +/// unless the process ends without one. pub(crate) fn save(now: bool) { static LAST: Mutex> = Mutex::new(None); const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(20); + const SAVE_EVERY_PRESSURED: std::time::Duration = std::time::Duration::from_secs(600); let (Some(dir), Some(library)) = (DIR.get(), library()) else { return }; { let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); - if !now && last.is_some_and(|t| t.elapsed() < SAVE_EVERY) { + let every = if crate::residency::pressured() { SAVE_EVERY_PRESSURED } else { SAVE_EVERY }; + if !now && last.is_some_and(|t| t.elapsed() < every) { return; } *last = Some(std::time::Instant::now()); diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 226f47843..22d903b01 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -599,7 +599,7 @@ fn workers() -> bool { if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 { drained(); } else { - super::library::save(false); + super::library::save_while_busy(); } } }); diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index f94df0483..4b6da36f6 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -76,6 +76,41 @@ fn spares(memory: Option<[u64; 4]>, keep: bool) -> usize { } } +/// Pieces of up to this many bytes are of the small class ([`class_of`]). +const SMALL_PIECE: u64 = 256 << 10; + +/// The size class a texture's piece of `len` bytes is cut from: with +/// [`classes`], 1 for small pieces (up to [`SMALL_PIECE`]) and 2 for the +/// others, each from blocks of their own; 0 (any block, as before) without. +fn class_of(len: u64) -> u8 { + if !classes() { + return 0; + } + if len <= SMALL_PIECE { 1 } else { 2 } +} + +/// Whether textures' small and large pieces are cut from blocks of their own +/// (`VICTORY_POOL_CLASSES=1`; off by default). +/// +/// Mixed in the same 64 MiB blocks, the many small textures (13,363 of +/// 15,836 in pieces of 64 KiB on an 8 GiB card, Series S, [`stats_on`]) and +/// the few large ones leave holes between them as they come and go: 1,260 MB +/// of 3,648 free in 1,655 ranges there, and 1.0 to 1.7 GB free in the blocks +/// throughout the runs on an RTX 3070 Ti (2026-11-28), card memory the +/// texture queue counts as room while a large texture finds no range in it +/// and a new block is made. Kept apart, a small texture's hole is the next +/// small texture's place, and the large ones' blocks empty out and go. +fn classes() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var_os("VICTORY_POOL_CLASSES").is_some_and(|v| v == "1"); + if on { + tracing::info!("texture blocks: small and large pieces in blocks of their own (VICTORY_POOL_CLASSES=1)"); + } + on + }) +} + /// Milliseconds until a piece given back is used again. (It was three /// frames, a tenth of a second while the title shows a loading screen at 30 /// a second, with up to 18 submissions in the air.) @@ -194,6 +229,8 @@ struct Block { /// When that was (ms). #[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] since: u64, + /// The size class of the pieces cut from it ([`class_of`]; 0: any). + class: u8, } struct Pool { @@ -226,6 +263,20 @@ impl Pool { align: u64, now: u64, ripe: Ripe, + make: impl FnMut() -> Option, + ) -> Option<(Piece, B, bool)> { + self.take_class(len, align, now, ripe, 0, make) + } + + /// [`Self::take_ripe`] from a block of size class `class` ([`class_of`]; + /// 0: any block, as before), or an empty one, which takes that class. + fn take_class( + &mut self, + len: u64, + align: u64, + now: u64, + ripe: Ripe, + class: u8, mut make: impl FnMut() -> Option, ) -> Option<(Piece, B, bool)> { // With blocks made ahead, what would be an allocation of its own (and @@ -235,12 +286,22 @@ impl Pool { } self.rested(now); let mut found = None; - for (i, block) in self.blocks.iter_mut().enumerate() { - if let Some(block) = block - && ripe.is(block) - && let Some(start) = block.free.take(len, align) - { - found = Some((i, start)); + // Blocks of the class first, then empty ones of another (given the class). + for pass in 0..2 { + for (i, block) in self.blocks.iter_mut().enumerate() { + if let Some(block) = block + && ripe.is(block) + && (class == 0 || block.class == class || (pass == 1 && block.free.whole(BLOCK))) + && let Some(start) = block.free.take(len, align) + { + if class != 0 { + block.class = class; + } + found = Some((i, start)); + break; + } + } + if found.is_some() || class == 0 { break; } } @@ -258,7 +319,9 @@ impl Pool { None => { let memory = self.grow(now, &mut make)?; let i = self.add(memory, ripe.started); - (i, self.blocks[i].as_mut()?.free.take(len, align)?) + let block = self.blocks[i].as_mut()?; + block.class = class; + (i, block.free.take(len, align)?) } }; if ripe.ahead > 0 { @@ -300,7 +363,7 @@ impl Pool { self.blocks.len() - 1 } }; - self.blocks[i] = Some(Block { memory, free: Ranges::new(BLOCK), used_to: 0, made, since: crate::host::now_ms() }); + self.blocks[i] = Some(Block { memory, free: Ranges::new(BLOCK), used_to: 0, made, since: crate::host::now_ms(), class: 0 }); i } @@ -822,8 +885,9 @@ pub(crate) unsafe fn texture( } else { 0 }; + let class = class_of(info.SizeInBytes); #[cfg_attr(not(feature = "diagnostics"), allow(unused_variables))] - let (piece, heap, again) = lock(&TEXTURES).take_ripe(info.SizeInBytes, info.Alignment.max(1), now(), Ripe::now(), || { + let (piece, heap, again) = lock(&TEXTURES).take_class(info.SizeInBytes, info.Alignment.max(1), now(), Ripe::now(), class, || { let desc = D3D12_HEAP_DESC { SizeInBytes: BLOCK, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, @@ -886,6 +950,32 @@ pub(crate) unsafe fn texture( mod tests { use super::*; + #[test] + fn small_and_large_pieces_keep_to_blocks_of_their_own() { + let made = std::cell::Cell::new(0u64); + let mut pool: Pool = Pool::new(SPARE_KEPT); + let mut make = || { + made.set(made.get() + 1); + Some(made.get()) + }; + let (small, a, _) = pool.take_class(65536, 65536, 0, Ripe::ALL, 1, &mut make).unwrap(); + let (large, b, _) = pool.take_class(4 << 20, 65536, 0, Ripe::ALL, 2, &mut make).unwrap(); + assert_ne!(a, b, "a large piece does not go into the small pieces' block"); + let (_, c, _) = pool.take_class(65536, 65536, 0, Ripe::ALL, 1, &mut make).unwrap(); + assert_eq!(a, c, "small pieces share their block"); + // Emptied, a block takes pieces of the other class. + pool.give(small, 0); + pool.give(large, 0); + let (_, d, _) = pool.take_class(65536, 65536, REST, Ripe::ALL, 1, &mut make).unwrap(); + assert_eq!(d, a); + let (_, e, _) = pool.take_class(1 << 20, 65536, REST, Ripe::ALL, 2, &mut make).unwrap(); + assert_eq!(e, b, "the emptied large block is used again, no new block"); + assert_eq!(made.get(), 2); + // Class 0: any block, as before. + let (_, f, _) = pool.take_class(65536, 65536, REST, Ripe::ALL, 0, &mut make).unwrap(); + assert!(f == a || f == b); + } + #[test] fn ranges_are_cut_aligned_and_join_again() { let mut r = Ranges::new(1024); diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 597ede594..db18104b0 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1886,7 +1886,7 @@ pub(crate) fn room(memory: Option<[u64; 4]>) -> bool { // world makes in its first frame ([`targets_room_kept`]) counts as // used. Some([budget, used, ..]) => { - used.saturating_sub(crate::pool::texture_room()) + crate::shadow::card_room_kept() + targets_room_kept() + used.saturating_sub(crate::pool::texture_room()) + crate::shadow::card_room_kept() + targets_room_kept(budget) < room_line(budget) } None => filled < WITHOUT_BUDGET, @@ -1895,7 +1895,8 @@ pub(crate) fn room(memory: Option<[u64; 4]>) -> bool { /// The bytes of the card's memory the texture queue leaves free for /// render targets and other host copies the host itself writes that are -/// not made yet: `VICTORY_CARD_ROOM_FOR_TARGETS_MB` (3,072; 0: none, as +/// not made yet: `VICTORY_CARD_ROOM_FOR_TARGETS_MB` (not given: 3,072, or +/// three tenths of a smaller card's `budget`, [`targets_most`]; 0: none, as /// before) less what such copies hold now. /// /// Measured (runs 193, 197, 198): 652 MB of them before the world, 2,255 @@ -1921,15 +1922,16 @@ pub(crate) fn room(memory: Option<[u64; 4]>) -> bool { /// for targets against a line of 9,527 MB). The reserve comes back when /// the targets grow by 64 MiB again (a new scene's), for as long again. #[cfg(windows)] -pub(crate) fn targets_room_kept() -> u64 { +pub(crate) fn targets_room_kept(budget: u64) -> u64 { use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; - static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); - let most = *MOST.get_or_init(|| { + static ASKED: std::sync::OnceLock> = std::sync::OnceLock::new(); + let asked = *ASKED.get_or_init(|| { std::env::var("VICTORY_CARD_ROOM_FOR_TARGETS_MB") .ok() .and_then(|v| v.trim().parse::().ok()) - .map_or(3072 << 20, |mb| mb.min(8192) << 20) + .map(|mb| mb.min(8192) << 20) }); + let most = targets_most(asked, budget); static SETTLE: std::sync::OnceLock = std::sync::OnceLock::new(); let settle = *SETTLE.get_or_init(|| { std::env::var("VICTORY_CARD_ROOM_FOR_TARGETS_SETTLE_MS") @@ -1950,6 +1952,29 @@ pub(crate) fn targets_room_kept() -> u64 { targets_kept(most, targets, now.saturating_sub(since), settle) } +/// The most [`targets_room_kept`] keeps: `asked` (`VICTORY_CARD_ROOM_FOR_TARGETS_MB`) +/// if given, else 3,072 MiB, but no more than three tenths of the card's +/// `budget` (0: not known, the 3,072). +/// +/// The 3,072 were measured on 12 GB cards at 1440p (budgets of 10.2 to +/// 10.6 GB, where three tenths are more than that, so nothing changes +/// there). On an 8 GB card (RTX 3060 Ti, 3070, 3070 Ti: budgets of 4.9 to +/// 7.3 GB, docs/windows-memory.md) a flat 3,072 kept 40 to 60 % of the +/// budget from the texture queue: the scene stayed black with the queue +/// "waiting for room", and a reserve of 1,536 MB brought it back. Three +/// tenths give 1,470 MB of a 4.9 GB budget and 2,190 MB of 7.3 GB, which +/// still holds the targets of the Series S profile (1080p out) and most of +/// 1440p's first frame; past it the targets only take room as they come. +#[cfg(any(windows, test))] +fn targets_most(asked: Option, budget: u64) -> u64 { + const MOST: u64 = 3072 << 20; + match asked { + Some(asked) => asked, + None if budget == 0 => MOST, + None => MOST.min(budget / 10 * 3), + } +} + /// [`targets_room_kept`]'s record of the targets' bytes (`last`) and of /// when they last grew by 64 MiB (`since`, ms), with `targets` now: a fall /// of 64 MiB lowers the record (so that growing back counts as growth), a @@ -1967,11 +1992,18 @@ fn targets_seen(last: u64, since: u64, targets: u64, now: u64) -> (u64, u64) { } /// What [`targets_room_kept`] keeps of `most`: what the targets do not -/// hold yet, or nothing once they hold half of it or more and have not -/// grown for `settle` ms (`still_ms`; `settle` 0: always kept). +/// hold yet, or nothing once they hold half of it, or 1 GiB, or more and +/// have not grown for `settle` ms (`still_ms`; `settle` 0: always kept). +/// +/// (Half alone was never reached on the Series S profile: its world's +/// targets level off at about 1,420 MB, under half of 3,072, so 1,650 MB +/// stayed kept for the whole run while 2,000 textures waited "no room" +/// (RTX 3070 Ti, 2026-11-28, five minutes in the world). Before the world +/// they are some 650 MB, under either.) #[cfg(any(windows, test))] fn targets_kept(most: u64, targets: u64, still_ms: u64, settle: u64) -> u64 { - if settle > 0 && targets >= most / 2 && still_ms >= settle { + const ENOUGH: u64 = 1 << 30; + if settle > 0 && targets >= (most / 2).min(ENOUGH) && still_ms >= settle { 0 } else { most.saturating_sub(targets) @@ -1995,7 +2027,7 @@ pub(crate) fn room_terms(memory: Option<[u64; 4]>) -> Option<[u64; 6]> { used, crate::pool::texture_room(), crate::shadow::card_room_kept(), - targets_room_kept(), + targets_room_kept(budget), room_line(budget), ] .map(|bytes| bytes >> 20), @@ -2332,7 +2364,7 @@ pub(crate) fn let_go_idle() { Some([budget, used, ..]) if keep => { let used = used.saturating_sub(crate::pool::texture_room()) + crate::shadow::card_room_kept() - + targets_room_kept(); + + targets_room_kept(budget); crate::host::vram_keep_below(budget, used, room_line(budget)) } _ => (crate::host::vram_idle_ms(memory), u64::MAX), @@ -2588,6 +2620,10 @@ fn slot_evict(video: Option<[u64; 4]>, idle_ms: u64, frames: u64) { frame_at(&ring, now_ms.saturating_sub(idle_ms)) }; static EVICTING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + let line_pct = (room_line(budget) * 100 / budget.max(1)).clamp(50, 97); + let high = high.min(line_pct); + let low = low.min(high.saturating_sub(5).max(40)); + let used = used.saturating_sub(crate::pool::texture_room()); 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); @@ -5219,13 +5255,33 @@ float4 lit() : SV_Target { return 1.0; } const MIB: u64 = 1 << 20; let most = 3072 * MIB; // Before the world: kept, however long. - assert_eq!(targets_kept(most, 652 * MIB, 60_000, 20_000), 2420 * MIB); + assert_eq!(targets_kept(most, 652 * MIB, 300_000, 20_000), 2420 * MIB); + // On 8 GB GPUs / Series S / DLSS, world targets settle around 1,185-1,450 MB. + assert_eq!(targets_kept(most, 1185 * MIB, 25_000, 20_000), 0); // The world's first frames: still growing. assert_eq!(targets_kept(most, 2083 * MIB, 5_000, 20_000), 989 * MIB); // Settled: nothing kept. assert_eq!(targets_kept(most, 2432 * MIB, 20_000, 20_000), 0); // `VICTORY_CARD_ROOM_FOR_TARGETS_SETTLE_MS=0`: kept as before. assert_eq!(targets_kept(most, 2432 * MIB, 600_000, 0), 640 * MIB); + // Series S: its world's targets level off at 1,420 MB, under half + // the most, and still settle (1 GiB is enough); a menu's do not. + assert_eq!(targets_kept(most, 1420 * MIB, 20_000, 20_000), 0); + assert_eq!(targets_kept(most, 1420 * MIB, 5_000, 20_000), 1652 * MIB); + assert_eq!(targets_kept(most, 652 * MIB, 600_000, 20_000), 2420 * MIB); + + // The most kept: 3,072 MiB on big cards, three tenths of an 8 GB + // card's budget, and what the switch says whatever the card. + const GIB: u64 = 1 << 30; + assert_eq!(targets_most(None, 0), most); + assert_eq!(targets_most(None, 10_600 * MIB), most); + assert_eq!(targets_most(None, 15 * GIB), most); + assert_eq!(targets_most(None, 7_256 * MIB), 7_256 * MIB / 10 * 3); + assert!((2_100 * MIB..2_200 * MIB).contains(&targets_most(None, 7_256 * MIB))); + assert!((1_450 * MIB..1_500 * MIB).contains(&targets_most(None, 4_923 * MIB))); + assert_eq!(targets_most(Some(1536 * MIB), 7 * GIB), 1536 * MIB); + assert_eq!(targets_most(Some(0), 7 * GIB), 0); + assert_eq!(targets_most(Some(3072 * MIB), 5 * GIB), most); // Growth of 64 MiB restarts the clock; less does not. assert_eq!(targets_seen(2000 * MIB, 1_000, 2050 * MIB, 9_000), (2000 * MIB, 1_000)); diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 39687d8b7..d485e6576 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -60,12 +60,23 @@ fn build() -> [u8; 32] { bytes.extend_from_slice(&limit.to_le_bytes()); // Which group barriers wait is part of the translation too. bytes.push(victory_shader::emit::group_sync()); + // And whether waterfalls are proven by their shape: by its effect, not + // its switch's text, since the default changed (on in VIctory-Neo, off + // here) and a translation cached with it on must not be served without. + // And the programs left without shared memory's bounds, by the list in + // effect (its default changed here from upstream's face programs to none). + bytes.extend_from_slice(b"lds-exempt:"); + bytes.extend_from_slice(victory_shader::emit::lds_bounds_exempt_list().join(",").as_bytes()); + bytes.push(0); + bytes.extend_from_slice(b"shape"); + bytes.push(b'0' + victory_shader::resource::waterfall_shape_mode()); // So are the switches that pick the form of a wave64 program: // without them here a run with `VICTORY_WAVE_WIDE=0` was // served the translations an earlier run of the same // executable had cached with the switch unset. for name in [ "VICTORY_WAVE_WIDE", + "VICTORY_WATER_VOLUME_PORTALS", "VICTORY_WAVE_DEEP_SKIPS", "VICTORY_WAVE_OWN_BITS", "VICTORY_WAVE_LOCAL", @@ -81,6 +92,8 @@ fn build() -> [u8; 32] { "VICTORY_THREAD_TICKET", "VICTORY_LDS_LOOP_ATOMICS", "VICTORY_LDS_BOUNDS", + "VICTORY_WATERFALL_SHAPE", + "VICTORY_LDS_BOUNDS_EXEMPT", ] { bytes.extend_from_slice(name.as_bytes()); bytes.push(b'='); @@ -131,7 +144,12 @@ pub fn precompile(container: &[u8]) -> Result { /// The translation of a console shader container, from the cache when /// there is one. pub(crate) fn host_shader(container: &[u8]) -> Result { - let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string()); + // (The container's name as run logs give it, for the settings that name programs.) + let translate = |c: &[u8]| { + let hash = blake3::hash(c).to_hex(); + victory_shader::emit::with_program(&hash[..16], || victory_shader::emit::translate(c)) + .map_err(|e| e.to_string()) + }; let shader = match CACHE.get() { Some(cache) => cached(cache, &build(), container, translate), None => translate(container), diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 2ac83e472..ebdaa1b55 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -2642,7 +2642,7 @@ fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize { } return merged.len(); } - let mut runs = dword_runs(at, title, merged, 0); + let mut runs = word_runs(at, title, merged); if runs.len() > 64 { runs = dword_runs(at, title, merged, 32); PUT[3].fetch_add(1, Ordering::Relaxed); @@ -4511,7 +4511,7 @@ impl Shadow { // refresh lie apart. let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at - start), n) }; let was = crate::host::upcheck::on().then(|| held.to_vec()); - let runs = if whole { vec![(0, n)] } else { dword_runs(at, held, title, 0) }; + let runs = if whole { vec![(0, n)] } else { word_runs(at, held, title) }; for &(a, len) in &runs { held[a..a + len].copy_from_slice(&title[a..a + len]); self.changed(at - start + a, at - start + a + len); diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 1e63f3431..8c5bb9885 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -1759,12 +1759,46 @@ fn guards() -> std::sync::MutexGuard<'static, Guards> { Ok(g) => g, // (Held by this, whoever panicked with it: not to be asked for again.) Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), - Err(std::sync::TryLockError::WouldBlock) => waited(3, || GUARDS.lock().unwrap_or_else(|e| e.into_inner())), + Err(std::sync::TryLockError::WouldBlock) => waited(3, guards_awake), }; settle(&mut g); g } +/// The guards' lock, held by another thread: waited for awake at first +/// (`VICTORY_GUARDS_SPIN=` at most, 0: not at all, asleep at +/// once as before), then asleep. +/// +/// The lock is held a few microseconds at a time (some bits, or one change +/// of a run of blocks' protection) and taken thousands of times a frame by +/// the thread that prepares submissions and the six that share its +/// refreshes, all at once, and by the title's threads in their write +/// faults. Asleep, a thread is woken in 50 microseconds and more: a profile +/// of the prologue's cell (RTX 3090 Ti, Series S profile, 31 frames a +/// second) had the preparing thread 2.2 ms of a 32 ms frame in this wait +/// alone, and each of the six helpers as long. +fn guards_awake() -> std::sync::MutexGuard<'static, Guards> { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + let most = *MOST.get_or_init(|| std::env::var("VICTORY_GUARDS_SPIN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)); + if most > 0 { + let began = std::time::Instant::now(); + loop { + for _ in 0..24 { + std::hint::spin_loop(); + } + match GUARDS.try_lock() { + Ok(g) => return g, + Err(std::sync::TryLockError::Poisoned(e)) => return e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => {} + } + if began.elapsed().as_micros() as u64 >= most { + break; + } + } + } + GUARDS.lock().unwrap_or_else(|e| e.into_inner()) +} + /// The 4 KiB pages of title memory that what shaders wrote was put into, /// and the frame it last was: in pieces made when first needed and never let /// go. Some 20,000 pages a frame are noted by the relay and the landing @@ -3185,11 +3219,45 @@ pub(crate) fn install() { }); } +/// The protection of the one page `at` lies in, where the system has that +/// page in memory (`None`: it has not, or would not say). +/// +/// `VirtualQuery` answers for the whole run of pages around an address that +/// are alike, and walks to the end of it to say how long it is: for a view of +/// hundreds of megabytes whose blocks are all read-only, hundreds of +/// microseconds with the address space held against every change of +/// protection. A write fault of the title's on a block that another of its +/// threads is opening asked so ([`writable`]): 91 such questions a frame of +/// 245 microseconds each, 22 ms a frame of the title's threads' time, and the +/// openings themselves (a change of protection each) 235 microseconds behind +/// them; 3.2 ms of every frame's chain (a timeline of the prologue's cell at +/// 38 frames a second, RTX 3090 Ti, Ryzen 9 9950X3D). This asks about one +/// page and walks nothing. `VICTORY_PAGE_ASK=0`: the region, as before. +fn page_protection(at: usize) -> Option { + use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + if !crate::toggled!("VICTORY_PAGE_ASK") { + return None; + } + // SAFETY: plain data, the address asked about in it. + let mut info: PSAPI_WORKING_SET_EX_INFORMATION = unsafe { std::mem::zeroed() }; + info.VirtualAddress = at as *mut _; + // SAFETY: our own process; an array of one record of that size. + let ok = unsafe { K32QueryWorkingSetEx(GetCurrentProcess(), std::ptr::from_mut(&mut info).cast(), size_of_val(&info) as u32) } != 0; + // SAFETY: every form of the answer is these bits. + let flags = unsafe { info.VirtualAttributes.Flags }; + // Bit 0: the page is in memory; bits 4 to 14: its protection then. + (ok && flags & 1 != 0).then(|| ((flags >> 4) & 0x7ff) as u32) +} + /// Whether `at` is committed read-write memory now. fn writable(at: usize) -> bool { use windows_sys::Win32::System::Memory::{ MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_READWRITE, VirtualQuery, }; + if let Some(protection) = page_protection(at) { + return protection == PAGE_READWRITE; + } // SAFETY: plain data filled in by the query. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; // SAFETY: a valid out pointer of the right size. diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index 8f4eb0898..1a7a6563d 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -56,6 +56,8 @@ tempfile.workspace = true [features] # Debugging switches (scripted keys and the like). diagnostics = ["victory-gpu/diagnostics", "victory-loader/diagnostics", "dep:windows", "dep:windows-core"] +# See victory-gpu's feature of the same name. +mimalloc = ["victory-gpu/mimalloc"] [lints] workspace = true diff --git a/crates/victory-hle/src/lib.rs b/crates/victory-hle/src/lib.rs index acd059294..c0085741b 100644 --- a/crates/victory-hle/src/lib.rs +++ b/crates/victory-hle/src/lib.rs @@ -80,6 +80,12 @@ impl ImportResolver for HleResolver { // The registry is code-only, so the "Missing" outcome can be checked on any // host; host pass-through itself needs Windows. +/// The log's line of which build this is and with which switches +/// (`victory run` says it first thing). +pub fn log_build(commit: &str, switches: &str) { + tracing::info!(commit, switches, "victory build and switches"); +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index 933e31a8d..715b43831 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -208,15 +208,134 @@ trait Source: Send { fn rumble(&mut self, slot: usize, low: u16, high: u16); } +/// What a key of the stand-in pad is, where a start says so. +#[derive(Clone, Copy, Debug, PartialEq)] +enum PadKey { + Button(u32), + LeftTrigger, + RightTrigger, +} + +/// `VICTORY_PAD_KEYS=pc`: the keyboard as third-person games on a PC have +/// it, on the pad layout that is usual for them (A run, X jump, Y into a +/// vehicle, B reload, the left bumper the weapons, the right one cover, a +/// press of the left stick crouch, of the right one a look back). With the +/// mouse ([`Look`]): W/A/S/D walk, the mouse looks, its buttons shoot and +/// aim. +const PC_KEYS: &str = "LShift=A,Space=X,F=Y,R=B,Tab=LB,Q=RB,LCtrl=L3,C=R3,V=View"; + +/// The keys a start gives the stand-in pad (`VICTORY_PAD_KEYS==