Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
86184c68f3 | ||
|
|
f0d1eb7682 | ||
|
|
5d62b86f4a | ||
|
|
ebd07c1dbb | ||
|
|
b78c91f127 | ||
|
|
e4f94bc86f | ||
|
|
9a97e0a537 | ||
|
|
21f8d46d02 | ||
|
|
a7c7819db4 | ||
|
|
f0114565e0 | ||
|
|
6a9d4732e9 | ||
|
|
604908e486 | ||
|
|
e4dbd89cd3 | ||
|
|
5d65b5d333 | ||
|
|
3f3e525d55 |
No files matched your search
Generated
+19
@@ -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",
|
||||
|
||||
@@ -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,6 +72,7 @@ opt-level = 2
|
||||
|
||||
[profile.release]
|
||||
debug = "line-tables-only"
|
||||
lto = "thin"
|
||||
|
||||
# The development build: release code generation plus the `diagnostics`
|
||||
# feature (`cargo build --profile diag -p victory --features diagnostics`),
|
||||
|
||||
@@ -9,28 +9,37 @@
|
||||
A performance- and low-memory-tuned fork of [VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA) (built on [foxhound](https://github.com/readmet3xt-lab/foxhound) / [VIctory](https://github.com/Marvisak/VIctory)) that runs a game file natively on Windows from files **you** supply.
|
||||
|
||||
> **This repository contains no game files, code, or assets.** You must supply your own legally obtained game file (`.exe`). Not affiliated with or endorsed by any developer, publisher, NVIDIA, or AMD. See [docs/asset-policy.md](docs/asset-policy.md).
|
||||
>
|
||||
> **Having issues? (crashes, pagefile, flashing/lighting, low FPS, DLSS/FSR, build errors)** → Open the full **[Troubleshooting Guide (`docs/troubleshooting.md`)](docs/troubleshooting.md)**.
|
||||
|
||||
---
|
||||
|
||||
## What This Fork Adds
|
||||
|
||||
- **6 GB / 4 GB VRAM support (`VICTORY_TEXTURE_DROP_MIPS`):** Drops top texture mip levels (`1` = Half for 6 GB GPUs, `2` = Quarter for 4 GB GPUs) to keep VRAM comfortably under budget. Toggleable in the **F1** menu (`TEXTURE SCALE (VRAM)`).
|
||||
- **16 GB RAM stability & OOM recovery:** Caps idle upload/list pools automatically on `<= 32 GB` hosts, drains idle pools under critical commit pressure, and retries `E_OUTOFMEMORY` in command-list preludes instead of crashing.
|
||||
- **Custom windowed output sizes (`VICTORY_OUTPUT`):** True `1280x720` and `1664x936` output patching that works cleanly alongside DLSS and FSR 3 Frame Generation. Toggleable in **F1** (`OUTPUT SIZE (WINDOW)`).
|
||||
- **CPU submit-thread optimizations:** Lock-free `watch::AHEAD_KEPT` + binary-searched `ahead_contains`, `RwLock<Guards>` shared-read fast path, lock-free `Shadow::pending_len` & `Card::before`, merged `copied`/`ranged` lock, incremental `HeapRanges` spans, zero-alloc `HostList::prelude()` fast path, and reused `Batch` scratch buffers.
|
||||
- **DLSS Super Resolution + AMD FSR 3 / DLSS Frame Generation:** Full F1 settings menu, F3 stats panel, HUD-less FSR 3 2X Frame Generation for RTX 20/30 and non-NVIDIA DX12 GPUs, and DLSS FG (2x–6x) for RTX 40/50.
|
||||
- **Portable 6 GB / 16 GB launcher (`scripts/play-6gb.ps1`):** Pre-configured with verified settings (`VICTORY_FAST_CORES=0` for hybrid P+E CPUs, `VICTORY_PORT_CONSTANTS=1`, aligned `SLOT_EVICT` thresholds, `VICTORY_PIPELINE_WAIT_MS=50`, and ReBAR GPU windows).
|
||||
- **6 GB / 4 GB VRAM support (`VICTORY_TEXTURE_DROP_MIPS`):** Drops top texture mip levels (`1` = sharp Half textures default in `play-6gb.ps1`, keeping peak VRAM around `4.3 GB` — **850 MiB** below the 5.15 GiB DXGI budget with zero WDDM paging; `2` = Quarter for 4 GB cards). Toggleable in the **F1** menu (`TEXTURE SCALE (VRAM)`).
|
||||
- **16 GB RAM stability & OOM recovery:** Automatically caps idle `STAGING`, upload `send::SPARE` (`128 MiB`), and CPU snapshot (`128 MiB`) pools on `<= 20 GB` / `<= 32 GB` RAM hosts, drains idle pools under critical commit pressure, tracks pagefile-growth commit headroom, retries `E_OUTOFMEMORY` in command-list preludes, and uses ThinLTO release builds (`opt-in --features mimalloc` kept off by default on 16 GB RAM).
|
||||
- **Custom windowed output sizes (`VICTORY_OUTPUT`) & DLSS Ultra Performance:** True `1280x720` and `1664x936` windowed output patching plus `640X360 (ULTRA FAST)` (`ultraperformance`, default in `play-6gb.ps1` for stable 10+ FPS even when a gaming laptop is heatsoaked) in **F1** (`SERIES S PICTURE` / `OUTPUT SIZE (WINDOW)`), working cleanly alongside DLSS and FSR 3 Frame Generation (with Reflex gated to active FG and automatic stuck-FG re-arm).
|
||||
- **Multi-threaded translation, off-submit recycling, lock-free queues & GPU barrier/RT optimizations:**
|
||||
- **Off-submit landed list recycling (`VICTORY_LAND_OFF_SUBMIT`, on by default):** Moves `land()` (resetting 220+ command lists/allocators per frame) off the single submitting thread onto the dedicated `victory-late-wait` thread (`after the sending`: `43.8 ms → 0.3 ms`).
|
||||
- **Zero-convoy command recording (`uav_buffer_for_list`, lock-free `queue::behind` unfold, `PLACED_TEXTURES` `RwLock`):** Removes `victory-ahead`'s global `mapped()` copy-queue fence wait from command-list scratch buffers (`make_card_budget`, `batch_place`, `indirect_scratch`), moves `queue::behind::Lane` unfolding outside the lane mutex, and switches `PLACED_TEXTURES` lookups to a read-only `RwLock` fast path (`list::thin` CPU time `-20%`, heavy-scene GPU busy `96–100%`).
|
||||
- **Lock-free fence settles, batched descriptor copies & fast dynamic reclaim:** `settle_for_fence()` waits only for target flights via `relay_wait` without holding `host.submitted`; `reclaim_dynamic()` recycles landed dynamic slots on `DYNAMIC_EPOCH`; `make_listed_batch()` batches contiguous `CopyDescriptors` with per-recording `ListViews` safety; `TextureQueue::due_and_census_capped()` cuts texture-queue lock waits by `82%`.
|
||||
- **3-tier thread priority (`cores.rs`):** Runs `victory-submit` / `victory-wide` at `+2` (`HIGHEST`), `VICTORY_THIN=1` (`8` `victory-list` workers) at `+1` (`ABOVE_NORMAL`), and title spin-threads at `0` (`NORMAL`).
|
||||
- **Fast descriptor & draw-state paths:** O(1) `FxHasher` view maps + split `VIEW_SHAPES` `RwLock`, 64-bit `Vec<u64>` dynamic descriptor bitset, in-place `State::reset()` (reusing Vec/HashMap capacity across 220+ lists/frame), stack-allocated `OMSetRenderTargets`, lock-free 64 MiB texture/staging pool block allocation, 16-way sharded `RETIRED` queues, and chunked `JournalGuard` in `Batch::flush_due()`.
|
||||
- **Hybrid 2 MiB streaming sections (`VICTORY_SECTION_MB=2`) + GPU-read-only UAV skip (`VICTORY_GPU_RO_SKIP=1`):** Splits multi-GB physical streaming pools into 2 MiB Windows file-mapping sections to slash section-lock contention during remaps while keeping `VICTORY_PORT_CONSTANTS=1`'s 185 MiB 32-bit graphics heap in one contiguous section (`CPU preparing: 53–54 ms → 37–43 ms`); also tracks `PAGE_GRAPHICS_READONLY` / `EXECUTE` / `EXECUTE_READ` allocations (`XMemVirtualAlloc` + `VirtualProtect`) so GPU-read-only sub-ranges are omitted from shader UAV write compares (`~340 MB/frame` skipped whenever a buffer isn't placed in-place).
|
||||
- **Direct CBVs, coalesced fills & cutscene fixes:** Direct 256-byte in-place CBVs (`VICTORY_DIRECT_CBV`), per-list CBV deduplication, sorted/overlap-coalesced `Batch::fill()`, `START_HOT_FRAMES=4` cutscene texture-hash fix, fused write-watch `ask_once`, AVX2 `word_runs`, and `VICTORY_DEPTH_PLANE_NOW=1` depth-plane sync.
|
||||
- **Visual & stability fixes:** Bit-level NaN/Inf-safe compositor saturate (`VICTORY_COMPOSE_NAN`, prevents black sun/specks), `ambient::raise()` NaN/negative scrub, `bcpack.rs` BC7 dictionary entry 0 index fix, `E_OUTOFMEMORY` host-texture retry (`NoTexture::ForNow` cooldown so transient VRAM spikes don't leave permanent black textures), GFX10 `v_add_f16` inline float constants (`240..=248`), SDWA `UNUSED_SEXT` fix, overlay buffer leak fixes (replacing `std::mem::forget` with `host::retire`), and `list::thin` untranslated chunk cleanup.
|
||||
- **Portable 6 GB / 16 GB launcher (`scripts/play-6gb.ps1`):** Pre-configured for 6 GB VRAM / 16 GB RAM PCs (`VICTORY_THIN=1`, `VICTORY_THIN_THREADS=8`, `VICTORY_LAND_OFF_SUBMIT=1`, `VICTORY_GPU_RO_SKIP=1`, `VICTORY_SECTION_MB=2`, `VICTORY_FAST_CORES=0`, `VICTORY_FAULT_UNLOCKED=1`, `VICTORY_GUARD_HOT=50`, `VICTORY_FRESH_OPEN=0`, `VICTORY_DEPTH_PLANE_NOW=1`, `VICTORY_PORT_CONSTANTS=1`, `VICTORY_TEXTURE_ROOM_PERCENT=65`, `VICTORY_CARD_ROOM_FOR_TARGETS_MB=1024`, `VICTORY_PIPELINE_WAIT_MS=50`).
|
||||
|
||||
---
|
||||
|
||||
## Requirements
|
||||
|
||||
| Component | Minimum (6 GB / 16 GB Preset) | Recommended |
|
||||
| Component | Minimum (4–6 GB / 16 GB Preset) | Recommended (6–8 GB Target) |
|
||||
| :--- | :--- | :--- |
|
||||
| **OS** | Windows 10 or 11 (64-bit) | Windows 11 (64-bit) |
|
||||
| **CPU** | x64 with AVX2 (4+ cores) | 6–8+ cores |
|
||||
| **RAM** | **16 GB** *(set a 32–48 GB SSD pagefile)* | 32 GB or more |
|
||||
| **GPU** | **6 GB VRAM** DX12 GPU (RTX 20/30/40/50 for DLSS; any DX12 GPU for FSR 3) | 12 GB+ NVIDIA RTX |
|
||||
| **CPU** | x64 with AVX2 (4+ cores) | 6–8+ cores (12+ threads) |
|
||||
| **RAM** | **16 GB** *(set a 32–48 GB SSD pagefile)* | **16 GB** (w/ SSD pagefile) or 32 GB |
|
||||
| **GPU** | **4–6 GB VRAM** DX12 GPU (RTX 20/30/40/50 for DLSS; any DX12 GPU for FSR 3) | **6–8 GB VRAM** NVIDIA RTX (e.g. RTX 3050 6 GB / 3060 / 4050 / 4060) |
|
||||
| **Storage** | SSD with 50+ GB free (for game file + pagefile + shader cache) | NVMe SSD |
|
||||
| **Build Tools** | [Rust](https://rustup.rs) + [VS Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) ("Desktop development with C++") | — |
|
||||
|
||||
@@ -49,8 +58,8 @@ A performance- and low-memory-tuned fork of [VIctory-NVIDIA](https://github.com/
|
||||
Open **PowerShell** in a folder where you want the project (outside your game file folder):
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/theme613/theme613crap.git
|
||||
cd theme613crap
|
||||
git clone https://theme613.ggff.net:8443/theme613/6gbvram---16gb-ram.git
|
||||
cd 6gbvram---16gb-ram
|
||||
```
|
||||
|
||||
### Step 3 — Download Upscaler / Frame-Gen DLLs (One-Time)
|
||||
@@ -70,29 +79,41 @@ NVIDIA's and AMD's redistributables are not stored in this repo — run the incl
|
||||
|
||||
Replace `D:\path\to\your.exe` with the path to **your own game file (`.exe`)**. The first launch builds `target\release\victory.exe` automatically (takes a few minutes).
|
||||
|
||||
**Option A — 6–8 GB VRAM GPUs / 16 GB RAM Laptops (Recommended for RTX 3050 / 3060 / 4050 / 4060):**
|
||||
**Option A — 6–8 GB VRAM GPUs / 16 GB RAM Laptops (Default & Recommended for RTX 3050 / 3060 / 4050 / 4060):**
|
||||
```powershell
|
||||
# Sharp 1080p windowed (960x540 DLSS Perf, Half textures, FG off):
|
||||
powershell -ExecutionPolicy Bypass -File scripts\play-6gb.ps1 -Exe 'D:\path\to\your.exe'
|
||||
# Sharp Half textures (DropMips=1) + 1080p windowed + DLSS Ultra Perf + FSR 3 2X FG (~20 FPS steady, VRAM ~4.3 GB):
|
||||
powershell -ExecutionPolicy Bypass -File scripts\play-6gb.ps1 -Exe 'D:\path\to\your.exe' -TuneSettings
|
||||
|
||||
# Same with FSR 3 2X Frame Generation ON:
|
||||
powershell -ExecutionPolicy Bypass -File scripts\play-6gb.ps1 -Exe 'D:\path\to\your.exe' -FrameGen
|
||||
# Same with Frame Generation OFF (raw real FPS / lowest input lag):
|
||||
powershell -ExecutionPolicy Bypass -File scripts\play-6gb.ps1 -Exe 'D:\path\to\your.exe' -TuneSettings -NoFrameGen
|
||||
|
||||
# Extra GPU headroom (936p or 720p windowed):
|
||||
powershell -ExecutionPolicy Bypass -File scripts\play-6gb.ps1 -Exe 'D:\path\to\your.exe' -Output 936
|
||||
# Extra crisp 540p->1080p internal resolution (DLSS Performance + sharp Half textures):
|
||||
powershell -ExecutionPolicy Bypass -File scripts\play-6gb.ps1 -Exe 'D:\path\to\your.exe' -Dlss performance -TuneSettings
|
||||
|
||||
# Extra GPU/VRAM headroom at 936p windowed:
|
||||
powershell -ExecutionPolicy Bypass -File scripts\play-6gb.ps1 -Exe 'D:\path\to\your.exe' -Output 936 -TuneSettings
|
||||
```
|
||||
|
||||
**Option B — 12 GB+ VRAM GPUs / 32 GB+ RAM Desktops:**
|
||||
**Option B — Higher-VRAM Desktops (12 GB+ VRAM / 32 GB+ RAM):**
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File scripts\play-nvidia.ps1 -Exe 'D:\path\to\your.exe'
|
||||
```
|
||||
|
||||
*(Optional: C: drive low on space? Run `setx VICTORY_HOME D:\victory` once and open a new PowerShell window — caches, saves, settings, and logs will go there instead of `%LOCALAPPDATA%\victory`.)*
|
||||
|
||||
### Step 5 — In-Game Controls & Tuning
|
||||
### Step 5 — Updating Later (`git pull` & Rebuild)
|
||||
Whenever new updates are pushed, pull `main` and rebuild `victory.exe` (since `play-6gb.ps1` only auto-builds when `target\release\victory.exe` does not exist yet):
|
||||
|
||||
```powershell
|
||||
cd 6gbvram---16gb-ram
|
||||
git pull origin main
|
||||
cargo build --release --locked -j 4 -p victory
|
||||
```
|
||||
|
||||
### Step 6 — In-Game Controls & Tuning
|
||||
- Press **`F1`** anytime to open the **Settings Menu** (Arrow keys to navigate, Enter to select, `SAVE AND RESTART NOW` to apply):
|
||||
- **`OUTPUT SIZE (WINDOW)`**: `1080P (DEFAULT)` / `936P` / `720P (FASTEST)`
|
||||
- **`DLSS`** / **`SERIES S PICTURE`**: `960X540 (FASTEST)` / `1113X626` / `1280X720`
|
||||
- **`DLSS`** / **`SERIES S PICTURE`**: `640X360 (ULTRA FAST)` / `960X540 (FASTEST)` / `1113X626` / `1280X720` / `1920X1080`
|
||||
- **`TEXTURE SCALE (VRAM)`**: `FULL` / `HALF (6GB GPU)` / `QUARTER (4GB GPU)`
|
||||
- **`FRAME GENERATION`**: `OFF` / `2X` (FSR 3 on RTX 20/30 or any DX12 card; DLSS FG 2x–6x on RTX 40/50)
|
||||
- **`WATER LIGHT`**, **`LIGHT ESTIMATE`**, **`REFLECTION ESTIMATE`**, **`FOG CAP`**
|
||||
@@ -105,7 +126,7 @@ powershell -ExecutionPolicy Bypass -File scripts\play-nvidia.ps1 -Exe 'D:\path\t
|
||||
|
||||
If you don't want to mess with Rust, PowerShell, pagefiles, or tuning flags by hand:
|
||||
1. Download and open **Google Antigravity**.
|
||||
2. Clone or open this repository folder in Antigravity.
|
||||
2. Clone `https://theme613.ggff.net:8443/theme613/6gbvram---16gb-ram.git` (or open your cloned `6gbvram---16gb-ram` folder) in Antigravity.
|
||||
3. Paste the prompt below (just replace the path with your own game file `.exe` path) and let Antigravity set up, build, and tune everything for your exact PC:
|
||||
|
||||
```text
|
||||
@@ -128,21 +149,36 @@ Please do the following step by step:
|
||||
|
||||
## Measured Performance Gains (6 GB VRAM / 16 GB RAM Laptop)
|
||||
|
||||
All numbers below were measured on the same Windows 11 gaming laptop (**Intel Core i5-12450HX [4 P-cores + 4 E-cores], 16 GB RAM, NVIDIA GeForce RTX 3050 6 GB Laptop GPU** — measured even while GPU power was capped at **26–30 W**) in an open-world test scene (`0` crashes, `0` OOMs):
|
||||
All numbers below were measured on the same Windows 11 gaming laptop (**Intel Core i5-12450HX [4 P-cores + 4 E-cores], 16 GB RAM, NVIDIA GeForce RTX 3050 6 GB Laptop GPU** — measured even while GPU power was capped at **26–31 W**) in an open-world test scene (`0` crashes, `0` OOMs, full lighting ON):
|
||||
|
||||
| Metric | Before (Stock `VIctory-NVIDIA` on 6 GB / 16 GB) | After (This Fork + Tuned Preset) | Change |
|
||||
| Metric | Before (Warm Baseline on 6 GB / 16 GB) | After (This Fork — Latest `main`) | Change |
|
||||
| :--- | :---: | :---: | :---: |
|
||||
| **Shader-warm frame stall** | `1.9 fps` (`520 ms` pipeline wait stalls) | `0` stalls (`VICTORY_PIPELINE_WAIT_MS=50`) | **Eliminated** |
|
||||
| **CPU `preparing` per frame** | `94.2 ms` | **`45.0 ms`** *(720p)* / **`53.7 ms`** *(1080p)* | **−52% (2.1× faster)** |
|
||||
| **GPU idle bubbles (waiting on CPU)** | `24.2 ms` *(with `FAST_CORES=2`)* | **`8.4 ms`** *(1080p)* / **`16.7 ms`** *(720p)* | **GPU 97–99% busy** |
|
||||
| **Standard open-world scene (~6k draws, real FPS)** | `8.5 fps` real (`117.8 ms`) | **`10.1–10.4 fps` real** *(720p)* / **`9.0–9.8 fps`** *(sharp 1080p + all visuals)* | **+19% to +22% real** |
|
||||
| **Heavy open-world scene (~11k draws, real FPS)** | `4.8 fps` real (`208 ms`) | **`7.3 fps` real** *(720p)* / **`6.0 fps` real** *(sharp 1080p)* | **+25% to +52% real** |
|
||||
| **With FSR 3 2X Frame Gen (HUD-less)** | `17.0 fps` displayed (`8.5` base) | **`18.0–19.6 fps`** *(sharp 1080p, 96/96 HUD-less)* | **+15% + cleaner pacing** |
|
||||
| **VRAM usage (6 GB card, 5.2 GiB DXGI budget)** | `5,291 MiB` peak *(hitting `no room` stalls)* | **`4,604–4,872 MiB` avg** | **Up to −687 MiB VRAM** |
|
||||
| **System RAM (16 GB host)** | `16,513 MiB` private commit | **`14,703–14,900 MiB`** private / **`5.1–6.4 GiB`** working set | **−1.6 to −1.8 GiB RAM** |
|
||||
| **Texture eviction `sweep()` overhead** | `8.0 ms/frame` *(when `ROOM% > SLOT_EVICT%`)* | **`0.3 ms/frame`** *(aligned `85% / 92%`)* | **26× faster** |
|
||||
| **Submit-thread `after the sending` (`land()`)** | `43.8 ms` *(blocking single submit thread)* | **`0.3 ms`** *(offloaded to `victory-late-wait`)* | **146× faster (−43.5 ms)** |
|
||||
| **GPU idle bubbles (heavy 11k draws / steady 6k)** | `51.1 ms` *(card 61% busy)* | **`0.0–5.3 ms`** heavy (**96–100%** busy) / **`9.5–13.6 ms`** steady | **−80% to −100% idle gap** |
|
||||
| **CPU constant buffer fills (`PORT_CONSTANTS=1`)** | `12,691` fills/frame (`4.9 MB`) | **`3,523–3,744`** fills/frame (`1.0–1.1 MB`) | **−71% fills / −78% KB** |
|
||||
| **CPU frame `preparing` (steady 6k draws)** | `53–54 ms` (`21–23 ms` copies) | **`47–56 ms`** (`18–22 ms` copies, full lighting) | **Clean visuals + fast sync** |
|
||||
| **Open-world steady (~6k draws, 1080p real FPS, warm)** | `7.85 fps` med (`~128 ms`) | **`10.0–10.8 fps`** warm (`92.5–100.4 ms`) | **+27% to +38% warm real** |
|
||||
| **Open-world steady (~6k draws, 720p real FPS, warm)** | — | **`10.3–10.9 fps`** (`91.7 ms`, cool `78 °C`) | **~11 fps real** |
|
||||
| **Heavy cutscene (~11k–12.3k draws, real FPS, warm)** | `4.70 fps` med (`4.80` peak, `~210 ms`) | **`6.3–6.8 fps`** (1080p sharp `DropMips=1`, full lighting) | **+34% to +45% warm real** |
|
||||
| **With FSR 3 2X Frame Gen (HUD-less)** | `15.7` steady / `9.5` heavy | **`20.2–21.6 fps`** steady / **`12.6–13.6 fps`** heavy | **Smooth 20+ FPS steady** |
|
||||
| **VRAM usage (6 GB card, 5.15 GiB DXGI budget)** | `5,164–5,291 MiB` peak *(WDDM paging stalls)* | **`4,301 MiB`** *(sharp `DropMips=1`, **850 MiB** under budget!)* | **−850+ MiB under budget** |
|
||||
| **System RAM (16 GB laptop)** | `16,513 MiB` private | **`14,618–14,914 MiB`** private | **−1.6 to −1.9 GiB RAM** |
|
||||
|
||||
> **Hybrid CPU note (`i5-12450HX` 4P + 4E):** Switching `VICTORY_FAST_CORES=2` → `0` alone lifted real FPS from **`8.9 → 10.1 fps`** (**+13.5%**, peak `10.4`) on ~6k-draw views and **`6.3 → 7.3 fps`** (**+16%**) on heavy ~11k-draw views, while cutting CPU `preparing` from `59.4 → 45.0 ms` with zero visual loss. Unlocking a 30 W-capped laptop GPU up to its full 65 W Performance Mode adds further real-FPS headroom on top of these numbers.
|
||||
### Latest Changes — Hybrid 2 MiB Sections, GPU-RO Skip, Stable 10–11.7 FPS Steady & +56% Heavy Scene Speedup
|
||||
|
||||
- **Hybrid 2 MiB streaming sections (`VICTORY_SECTION_MB=2`, `xmem.rs` — after `RyanCase94` / `fxceless#1274` / `sagouindupm/Mandy`):** Splits multi-GB physical streaming pools into 2 MiB `CreateFileMappingW` sections while keeping `VICTORY_PORT_CONSTANTS=1`'s 185 MiB 32-bit graphics heap in one contiguous section (preserving `84` hash passes/frame instead of `337` and keeping 1080p real open-world FPS at **`10.0–10.8 fps`** with full lighting intact).
|
||||
- **GPU-read-only UAV skip (`VICTORY_GPU_RO_SKIP=1`, `xmem.rs`, `shadow.rs`, `host.rs`, `draw.rs`, `memory.rs` — after `mikael-jarvinen` / `VIctory-NVIDIA#1014` / `sagouindupm/Mandy`):** Tracks console `PAGE_GRAPHICS_READONLY` / `EXECUTE` / `EXECUTE_READ` intervals across `XMemVirtualAlloc` and `VirtualProtect` and subtracts them from shader UAV write declarations (plus `VICTORY_GPU_RO_CHECK=1` verification mode), clipping `~340 MB/frame` of CPU-written constant pools whenever a buffer isn't placed in-place.
|
||||
- **BC7 dictionary entry 0 & `E_OUTOFMEMORY` texture retry (`bcpack.rs`, `resource.rs` — from `sagouindupm/Mandy` / upstream `VIctory#3198`):** Fixes `bcpack.rs` skipping entry 0's leading index and changes `E_OUTOFMEMORY` host-texture creation failures from permanent black refusal into a 1-second cooldown retry (`NoTexture::ForNow`).
|
||||
|
||||
- **Zero-convoy command recording (`host.rs`, `ahead.rs`, `queue/behind.rs`, `resource.rs`):** Added `uav_buffer_for_list()` / `shared_buffer_now_unmapped()` to eliminate `50–86 ms` stalls behind `victory-ahead` on the global `mapped()` copy-queue mutex; moved `queue::behind::Lane` unfolding outside the lane lock (eliminating `22–50 ms` lock convoys across all 8 list workers, title submits, and `victory-late-wait`); converted `PLACED_TEXTURES` to a read-only-fast-path `RwLock`.
|
||||
- **Heavy-scene lock-free fence settles, batched descriptors & dynamic reclaim (`host.rs`, `draw.rs`, `descriptor/host.rs`):** Lock-free `settle_for_fence()` under `VICTORY_RELAY`, `DYNAMIC_EPOCH` + `reclaim_dynamic()`, `HostHeap::make_listed_batch()` with per-recording `ListViews` cache safety, and capped `TextureQueue::due_and_census_capped()` (`-82%` texture-queue lock wait).
|
||||
- **Off-submit landed list recycling (`VICTORY_LAND_OFF_SUBMIT`, `host.rs`) & 3-tier thread priority (`cores.rs`):** Delegates `land()` to `victory-late-wait` (`43.8 ms → 0.3 ms`) and prioritizes `victory-submit`/`victory-wide` (`+2`), `victory-list` (`+1`), and title threads (`0`).
|
||||
- **O(1) descriptor & draw-state fast paths (`descriptor.rs`, `descriptor/host.rs`, `draw.rs`, `host.rs`):** `FxHasher` view/shape maps with split `VIEW_SHAPES` `RwLock`, 64-bit `Vec<u64>` dynamic slot bitset, in-place `State::reset()`, stack-allocated `OMSetRenderTargets`, and chunked `JournalGuard` in `Batch::flush_due()`.
|
||||
- **Visual, stability & memory fixes:** Bit-level NaN/Inf-safe compositor saturate (`VICTORY_COMPOSE_NAN`), `ambient::raise()` NaN/negative scrub, GFX10 `v_add_f16` inline float constants (`240..=248`), SDWA `UNUSED_SEXT` fix, `VICTORY_DEPTH_PLANE_NOW=1` depth-plane sync, lock-free 64 MiB pool allocation, 16-way sharded `RETIRED` queues, Reflex gated to active FG + stuck-FG auto re-arm (`VICTORY_FRAMEGEN_REARM=90`), ThinLTO release builds, and overlay/`list::thin` leak fixes.
|
||||
- **Direct CBVs & cutscene texture fixes (`ebd07c1`):** Direct 256-byte in-place CBVs (`VICTORY_DIRECT_CBV`), per-list CBV dedup, coalesced `Batch::fill()`, and `START_HOT_FRAMES=4` cutscene texture-hash fix.
|
||||
|
||||
> **Hybrid CPU & stronger GPU note:** On Intel 12th–14th gen hybrid CPUs (`i5-12450HX` 4P + 4E), `VICTORY_FAST_CORES=0` adds `+13.5%` real FPS over `FAST_CORES=2`. With the submit thread now down to **`52.4 ms`** (~19 real FPS CPU ceiling), higher-wattage RTX 3060 / 4050 / 4060 6–8 GB GPUs can push toward **15–19 real FPS** (`30–38 FPS` with 2× FG), while 30–35 W RTX 3050 6 GB laptops are now primarily GPU-bound (`85%` card utilization at `10.8–12.8 real fps`).
|
||||
|
||||
---
|
||||
|
||||
@@ -158,13 +194,27 @@ All numbers below were measured on the same Windows 11 gaming laptop (**Intel Co
|
||||
|
||||
## Tips for Gaming Laptops (6 GB VRAM / 16 GB RAM)
|
||||
|
||||
1. **Use AC Power + Performance Mode (`Fn + Q` / OEM control panel):** Many gaming laptops cap the GPU to 30–35 W in Balanced mode even when capable of 65–115 W. Unlocking GPU TGP + raising fan speed gives a direct real-FPS boost.
|
||||
1. **Use AC Power + Performance / Max Fan Mode (`Fn + Q` / OEM control panel):** Many gaming laptops cap the GPU to 30–35 W in Balanced mode or thermally throttle the CPU once the heatsink reaches 85–86 °C on long sessions. Keeping fans on Performance/Max and elevating the back of the laptop for airflow sustains peak FPS.
|
||||
2. **Don't choke CPU wattage in Custom Mode:** This compatibility layer uses all CPU cores heavily. Keep CPU cross-loading power limit generous (45–55 W+) and keep Windows Power Plan on High Performance / 100% min processor state on AC.
|
||||
3. **Close background apps before launching:** Browsers, Discord, and IDEs eat RAM and CPU cores on 16 GB systems.
|
||||
4. **First-time shader warm-up:** New open-world areas compile pipelines on first visit (capped to 50 ms/frame in `play-6gb.ps1` to avoid long stalls) and run smoothly once cached.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting & Common Fixes
|
||||
|
||||
For full step-by-step fixes, see the dedicated **[Troubleshooting Guide (`docs/troubleshooting.md`)](docs/troubleshooting.md)**:
|
||||
|
||||
- **[16 GB RAM crashes / `E_OUTOFMEMORY` — Step-by-step 32–48 GB SSD pagefile guide](docs/troubleshooting.md#1-out-of-memory--crashes-on-16-gb-ram-3248-gb-ssd-pagefile-setup)**
|
||||
- **[Wrong F1 settings / pitch-black indoors — How to reset `victory-settings.txt`](docs/troubleshooting.md#2-wrong-or-broken-f1-settings-how-to-reset)**
|
||||
- **[Blinding sun, indoor flashing, white dots, blurry graphics, or missing heads](docs/troubleshooting.md#3-graphics--lighting-issues)**
|
||||
- **[Low FPS, roaming VRAM stutters, input lag, & laptop thermal throttling](docs/troubleshooting.md#4-low-fps-stuttering-input-lag--laptop-thermal-throttling)**
|
||||
- **[DLSS / AMD FSR 3 Frame Generation not working](docs/troubleshooting.md#5-dlss-or-fsr-3-frame-generation-not-working)**
|
||||
- **[Build errors, `git pull` rebuild, Windows 10 DX12, & low C: space](docs/troubleshooting.md#6-build-git-pull-windows-10--launch-errors)**
|
||||
- **[Shader preloading (`-Preload`) & pop-in in new areas](docs/troubleshooting.md#7-shader-preloading--pop-in-in-new-areas)**
|
||||
|
||||
---
|
||||
|
||||
## Known Limitations
|
||||
|
||||
- **Hardware ray tracing is off by default** (`RAY TRACING` in F1 is slow/broken on current builds); indirect lighting and reflections use the emulator's `LIGHT ESTIMATE` + `REFLECTION ESTIMATE` + `WATER LIGHT` shaders instead.
|
||||
@@ -179,6 +229,6 @@ Built on the work of the community:
|
||||
- **[VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA)** — NVIDIA Streamline DLSS/FG, FSR 3 FG, F1 settings menu, F3 stats panel
|
||||
- **[foxhound](https://github.com/readmet3xt-lab/foxhound)** — fast descriptor sync, card-side compares, ambient/reflection estimates
|
||||
- **[VIctory](https://github.com/Marvisak/VIctory)** — core loader, runtime services, D3D12 backend, shader recompiler
|
||||
- **[Dathinel/victory-4gb](https://github.com/Dathinel/victory-4gb)**, **[fxceless/victory-fork](https://github.com/fxceless/victory-fork)**, **[avatarmanz/VIctory-7900XTX](https://github.com/avatarmanz/VIctory-7900XTX)**, **[codec-d/cool_fox](https://github.com/codec-d/cool_fox)**, **[Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD)**, **[DexNom/VIctory](https://github.com/DexNom/VIctory)**
|
||||
- **[Dathinel/victory-4gb](https://github.com/Dathinel/victory-4gb)**, **[sagouindupm/Mandy](https://github.com/sagouindupm/Mandy)**, **[Androtim/MiniVI](https://github.com/Androtim/MiniVI)**, **[aszterrr/VIctory-NVIDIA-Azter](https://github.com/aszterrr/VIctory-NVIDIA-Azter)**, **[fxceless/victory-fork](https://github.com/fxceless/victory-fork)**, **[avatarmanz/VIctory-7900XTX](https://github.com/avatarmanz/VIctory-7900XTX)**, **[codec-d/cool_fox](https://github.com/codec-d/cool_fox)**, **[Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD)**, **[DexNom/VIctory](https://github.com/DexNom/VIctory)**
|
||||
|
||||
Licensed under **GPL-3.0-or-later** (see [LICENSE](LICENSE)).
|
||||
@@ -30,6 +30,10 @@ diagnostics = [
|
||||
"victory-loader/diagnostics",
|
||||
"victory-shader/diagnostics",
|
||||
]
|
||||
# Optional: Rust allocations through mimalloc instead of the shared process heap.
|
||||
# Best on 32+ GB RAM hosts; on 16 GB RAM hosts its per-thread arenas inflate
|
||||
# process working set by ~5 GB and cause pagefile thrashing.
|
||||
mimalloc = ["victory-hle/mimalloc"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -210,7 +210,7 @@ impl Tables {
|
||||
})
|
||||
.collect();
|
||||
let bc7 = (0..DICTIONARY)
|
||||
.map(|_| {
|
||||
.map(|k| {
|
||||
let mut ep = Bc7Ep {
|
||||
ctrl: r.u16(),
|
||||
..Default::default()
|
||||
@@ -222,10 +222,16 @@ impl Tables {
|
||||
bits: [r.u8(), r.u8()],
|
||||
..Default::default()
|
||||
};
|
||||
// Unused: the widths again in all entries but the first.
|
||||
r.u16();
|
||||
// Only 15 slots for set 1, which no entry uses (0 bits).
|
||||
for v in &mut ix.ix.as_flattened_mut()[..31] {
|
||||
// Entry 0 holds all 32 indices right after its widths; the
|
||||
// others repeat the widths (unused) and hold 31, as set 1
|
||||
// has only 15 slots, which no entry uses (0 bits).
|
||||
let n = if k == 0 {
|
||||
32
|
||||
} else {
|
||||
r.u16();
|
||||
31
|
||||
};
|
||||
for v in &mut ix.ix.as_flattened_mut()[..n] {
|
||||
*v = r.u16() as i16;
|
||||
}
|
||||
(ep, ix)
|
||||
@@ -1704,6 +1710,12 @@ mod tests {
|
||||
#[test]
|
||||
fn bc7_dictionary_indices_line_up() {
|
||||
let t = Tables::builtin().unwrap();
|
||||
// Entry 0 keeps its leading index (no repeated widths before it).
|
||||
let (ep0, ix0) = &t.bc7[0];
|
||||
assert_eq!(ep0.ctrl, 0);
|
||||
assert_eq!(ix0.bits, [4, 0]);
|
||||
assert_eq!(ix0.ix[0], [2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
|
||||
assert_eq!(ix0.ix[1], [0; 16]);
|
||||
for (k, (_, ix)) in t.bc7.iter().enumerate() {
|
||||
let anchor = 0..1 << (ix.bits[0] - 1);
|
||||
let ok = (ix.bits[1] != 0 || ix.ix[1] == [0; 16]) && anchor.contains(&ix.ix[0][0]);
|
||||
|
||||
@@ -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,12 +26,15 @@ tempfile.workspace = true
|
||||
[features]
|
||||
# Debugging switches (frame capture, the host debug layer, per-draw data).
|
||||
diagnostics = []
|
||||
# The Rust side allocates through mimalloc (per-thread caches) instead of the
|
||||
# process heap it shares with the title and the drivers.
|
||||
mimalloc = ["dep:mimalloc"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Cryptography", "Win32_Security_WinTrust", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] }
|
||||
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Cryptography", "Win32_Security_WinTrust", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] }
|
||||
windows = { workspace = true, features = [
|
||||
"Win32_Graphics_Direct3D",
|
||||
"Win32_Graphics_Direct3D_Fxc",
|
||||
|
||||
@@ -152,7 +152,7 @@ fn fill() {
|
||||
continue;
|
||||
}
|
||||
if more_shared
|
||||
&& let Some((buffer, data)) = host.shared_buffer_now(SIZE)
|
||||
&& let Some((buffer, data)) = host.shared_buffer_now_unmapped(SIZE)
|
||||
{
|
||||
SHARED.lock().unwrap_or_else(|e| e.into_inner()).push(Shared(buffer, data as usize));
|
||||
}
|
||||
|
||||
@@ -467,7 +467,9 @@ void raise(uint3 at : SV_DispatchThreadID) {
|
||||
found = all + 1.2 * float3(dot(sr.xyz, n), dot(sg.xyz, n), dot(sb.xyz, n)) / sum;
|
||||
found = clamp(found, 0.2 * all, 2.5 * all);
|
||||
found = lerp(found, cells[CELLS].rgb, 0.2) * level * open;
|
||||
if (any(isnan(found)) || any(isinf(found)) || any(found < 0.0)) found = 0.0;
|
||||
float3 was = unpack(light[p]);
|
||||
if (any(isnan(was)) || any(isinf(was)) || any(was < 0.0)) was = 0.0;
|
||||
// Magenta/violet garbage the probes' memory held (green far under red and
|
||||
// blue): dropped, as VIctory-Belobug-AMD does (ambient.rs, "Filter magenta
|
||||
// garbage probes"). Seen on an RTX 5080 as a purple-blue glow on a lit
|
||||
|
||||
@@ -24,13 +24,32 @@ V vs(uint id : SV_VertexID) {
|
||||
return v;
|
||||
}
|
||||
[RootSignature(RS)]
|
||||
// Bit-level NaN/Inf-safe saturate (from aki-gta6/aki-runtime 33c21b9 via ProjectLeonida/mandy a8d2f48):
|
||||
// plain saturate(NaN) evaluates to 0.0 (black specks / black sun).
|
||||
float clean1(float x) {
|
||||
#if CLEAN
|
||||
return (asuint(x) & 0x7FFFFFFFu) > 0x7F800000u ? 1.0 : saturate(x);
|
||||
#else
|
||||
return saturate(x);
|
||||
#endif
|
||||
}
|
||||
float3 clean(float3 x) {
|
||||
return float3(clean1(x.r), clean1(x.g), clean1(x.b));
|
||||
}
|
||||
float4 ps(V v) : SV_Target {
|
||||
float4 s = scene.SampleLevel(smooth_, v.uv, 0);
|
||||
float4 o = over.SampleLevel(smooth_, v.uv, 0);
|
||||
return float4(saturate(o.rgb + s.rgb * (1 - saturate(o.a))), 1);
|
||||
return float4(clean(o.rgb + s.rgb * (1 - clean1(o.a))), 1);
|
||||
}
|
||||
"#;
|
||||
|
||||
/// Whether the composer's clamp keeps a NaN from coming out black
|
||||
/// (`VICTORY_COMPOSE_NAN=0`: plain `saturate`, as before).
|
||||
fn clean() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_COMPOSE_NAN").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
pub(crate) struct Composer {
|
||||
root: ID3D12RootSignature,
|
||||
pso: ID3D12PipelineState,
|
||||
@@ -43,13 +62,14 @@ unsafe impl Send for Composer {}
|
||||
unsafe impl Sync for Composer {}
|
||||
|
||||
fn compile(entry: PCSTR, target: PCSTR) -> windows::core::Result<ID3DBlob> {
|
||||
let source = format!("#define CLEAN {}\n{SOURCE}", u8::from(clean()));
|
||||
let mut code: Option<ID3DBlob> = None;
|
||||
// SAFETY: the source and names live through the call; the out pointer is
|
||||
// ours.
|
||||
unsafe {
|
||||
D3DCompile(
|
||||
SOURCE.as_ptr().cast(),
|
||||
SOURCE.len(),
|
||||
source.as_ptr().cast(),
|
||||
source.len(),
|
||||
s!("compose"),
|
||||
None,
|
||||
None,
|
||||
|
||||
@@ -129,8 +129,22 @@ pub(crate) enum C {
|
||||
WaitsForGroups,
|
||||
WaitsForBuffers,
|
||||
IndirectBounded,
|
||||
/// Our reads of title memory (`crate::host`'s `read_plain`: one copy or
|
||||
/// one kernel read each, [`ReadCall`]), by the faults the handler took on
|
||||
/// their thread meanwhile ([`read_fault`]): none (calls, nanoseconds);
|
||||
/// guards alone (calls, nanoseconds, faults); others (calls,
|
||||
/// nanoseconds, faults, the guards' among them counted as guards').
|
||||
ReadCalls,
|
||||
ReadNs,
|
||||
ReadGuardCalls,
|
||||
ReadGuardNs,
|
||||
ReadGuardFaults,
|
||||
ReadOtherCalls,
|
||||
ReadOtherNs,
|
||||
ReadOtherFaults,
|
||||
}
|
||||
const COUNTERS: usize = 80;
|
||||
const _: () = assert!((C::ReadOtherFaults as usize) < COUNTERS);
|
||||
/// One of some sets of counters, each in lines of the processor's memory of
|
||||
/// its own: a set for all threads had them wait for each other's lines at
|
||||
/// every list call (what counts here is summed up for the log alone).
|
||||
@@ -183,6 +197,126 @@ pub(crate) fn mode() -> u8 {
|
||||
})
|
||||
}
|
||||
|
||||
/// What the fault handler (`crate::watch`'s, the first in the process) made
|
||||
/// of a fault on a thread inside one of our reads of title memory
|
||||
/// ([`ReadCall`]). The first two are guards, the rest others.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum ReadFault {
|
||||
/// A guard page of Windows' (`PAGE_GUARD`: the first access raises
|
||||
/// `STATUS_GUARD_PAGE_VIOLATION` and clears it): the copy fails.
|
||||
PageGuard = 1,
|
||||
/// A write into a block we guard (made read-only to see the title's
|
||||
/// writes), opened by this thread or found opened: the copy goes on.
|
||||
OurGuard = 2,
|
||||
/// An access violation reading (or with no address): memory not there,
|
||||
/// not committed or not readable: the copy fails.
|
||||
NotThere = 3,
|
||||
/// A write into memory not writable and not guarded by us: the copy
|
||||
/// fails.
|
||||
NotWritable = 4,
|
||||
/// A view the runtime keeps lazily or in its books alone, made a mapping
|
||||
/// of the host's: the access is made again.
|
||||
MadeReal = 5,
|
||||
/// Any other exception (an in-page error, ...): the copy fails.
|
||||
Other = 6,
|
||||
}
|
||||
|
||||
impl ReadFault {
|
||||
/// What a fault the handler sends to the copy's failing exit is, by its
|
||||
/// exception code.
|
||||
pub(crate) fn failed(code: i32) -> ReadFault {
|
||||
use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, STATUS_GUARD_PAGE_VIOLATION};
|
||||
if code == STATUS_GUARD_PAGE_VIOLATION {
|
||||
ReadFault::PageGuard
|
||||
} else if code == EXCEPTION_ACCESS_VIOLATION {
|
||||
ReadFault::NotThere
|
||||
} else {
|
||||
ReadFault::Other
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`ReadFault`]'s kinds, and 0 (none).
|
||||
const READ_KINDS: usize = 7;
|
||||
|
||||
thread_local! {
|
||||
/// Read calls running on this thread ([`ReadCall`]).
|
||||
static READING: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
|
||||
/// The faults the handler took on this thread inside read calls, by kind
|
||||
/// ([`read_fault`]).
|
||||
static READ_FAULTS: std::cell::Cell<[u32; READ_KINDS]> = const { std::cell::Cell::new([0; READ_KINDS]) };
|
||||
}
|
||||
|
||||
/// The faults in read calls as the handler noted them, for [`log`]: frame
|
||||
/// (`crate::frame::current`, 24 bits), kind (3), 4 KiB page (37); 0 is a
|
||||
/// slot not written. A ring: what [`log`] has not taken when it comes round
|
||||
/// again is lost (and counted so).
|
||||
const RING: usize = 1 << 16;
|
||||
static FAULT_RING: [AtomicU64; RING] = [const { AtomicU64::new(0) }; RING];
|
||||
/// The faults noted in [`FAULT_RING`] so far.
|
||||
static FAULT_NOTED: AtomicU64 = AtomicU64::new(0);
|
||||
const RING_FRAME: u64 = (1 << 24) - 1;
|
||||
const RING_PAGE: u64 = (1 << 37) - 1;
|
||||
|
||||
/// The handler took a fault of `kind` at `at` on this thread. Inside a read
|
||||
/// call it is counted for the call and noted in [`FAULT_RING`]; elsewhere
|
||||
/// nothing is done. It runs in the fault handler: no allocation, no lock, no
|
||||
/// log (a thread-local and two atomics).
|
||||
pub(crate) fn read_fault(kind: ReadFault, at: usize) {
|
||||
if !READING.try_with(|r| r.get() != 0).unwrap_or(false) {
|
||||
return;
|
||||
}
|
||||
let k = kind as usize;
|
||||
let _ = READ_FAULTS.try_with(|f| {
|
||||
let mut n = f.get();
|
||||
n[k] = n[k].wrapping_add(1);
|
||||
f.set(n);
|
||||
});
|
||||
let noted = (crate::frame::current() & RING_FRAME) << 40 | (k as u64) << 37 | (at as u64 >> 12) & RING_PAGE;
|
||||
let slot = FAULT_NOTED.fetch_add(1, Relaxed) as usize % RING;
|
||||
FAULT_RING[slot].store(noted, Relaxed);
|
||||
}
|
||||
|
||||
/// One of our reads of title memory, timed until dropped and counted by the
|
||||
/// faults the handler took on this thread meanwhile ([`read_fault`]): none,
|
||||
/// guards alone, or others ([`C::ReadCalls`] and on).
|
||||
pub(crate) struct ReadCall {
|
||||
began: std::time::Instant,
|
||||
faults: [u32; READ_KINDS],
|
||||
}
|
||||
|
||||
impl ReadCall {
|
||||
pub(crate) fn begin() -> ReadCall {
|
||||
let _ = READING.try_with(|r| r.set(r.get() + 1));
|
||||
let faults = READ_FAULTS.try_with(std::cell::Cell::get).unwrap_or([0; READ_KINDS]);
|
||||
ReadCall { began: std::time::Instant::now(), faults }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ReadCall {
|
||||
fn drop(&mut self) {
|
||||
let ns = self.began.elapsed().as_nanos() as u64;
|
||||
let _ = READING.try_with(|r| r.set(r.get().saturating_sub(1)));
|
||||
let now = READ_FAULTS.try_with(std::cell::Cell::get).unwrap_or(self.faults);
|
||||
let new = |k: ReadFault| u64::from(now[k as usize].wrapping_sub(self.faults[k as usize]));
|
||||
let guards = new(ReadFault::PageGuard) + new(ReadFault::OurGuard);
|
||||
let others = new(ReadFault::NotThere) + new(ReadFault::NotWritable) + new(ReadFault::MadeReal) + new(ReadFault::Other);
|
||||
if guards != 0 {
|
||||
add(C::ReadGuardFaults, guards);
|
||||
}
|
||||
let (calls, time) = if others != 0 {
|
||||
add(C::ReadOtherFaults, others);
|
||||
(C::ReadOtherCalls, C::ReadOtherNs)
|
||||
} else if guards != 0 {
|
||||
(C::ReadGuardCalls, C::ReadGuardNs)
|
||||
} else {
|
||||
(C::ReadCalls, C::ReadNs)
|
||||
};
|
||||
add(calls, 1);
|
||||
add(time, ns);
|
||||
}
|
||||
}
|
||||
|
||||
/// Per source range (start, length): copies, bytes, microseconds, memory type.
|
||||
type Ranges = HashMap<(usize, usize), (u64, u64, u64, u32)>;
|
||||
static RANGES: Mutex<Option<Ranges>> = Mutex::new(None);
|
||||
@@ -404,14 +538,22 @@ fn big_blocks() -> String {
|
||||
|
||||
/// The system's allocator with every block counted in [`OWN`] (two atomic
|
||||
/// additions per allocation and per release: diagnostics builds only).
|
||||
/// With the `mimalloc` feature the blocks come from mimalloc instead.
|
||||
#[cfg(any(feature = "diagnostics", test))]
|
||||
struct Counting;
|
||||
|
||||
// SAFETY: every call goes to the system's allocator unchanged; only
|
||||
#[cfg(all(any(feature = "diagnostics", test), not(feature = "mimalloc")))]
|
||||
const INNER: std::alloc::System = std::alloc::System;
|
||||
#[cfg(all(any(feature = "diagnostics", test), feature = "mimalloc"))]
|
||||
const INNER: mimalloc::MiMalloc = mimalloc::MiMalloc;
|
||||
|
||||
// SAFETY: every call goes to the underlying allocator unchanged; only
|
||||
// counters are kept beside it.
|
||||
#[cfg(any(feature = "diagnostics", test))]
|
||||
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 +563,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 +575,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);
|
||||
@@ -449,6 +591,7 @@ unsafe impl std::alloc::GlobalAlloc for Counting {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "diagnostics", test))]
|
||||
#[global_allocator]
|
||||
static HEAP: Counting = Counting;
|
||||
|
||||
@@ -792,7 +935,8 @@ fn log_memory() {
|
||||
host copies the host renders to or writes: {} alive {:.0} MB; host copies the title \
|
||||
fills: {} alive {:.0} MB ({} of them placed), {} let go {:.0} MB and {} made again \
|
||||
{:.0} MB since the start; {} host copies made in all; passes that made none for lack of \
|
||||
room: {}; the card: {:.0} MB in use of a budget of {:.0} MB, {:.0} MB of the PC's memory \
|
||||
room: {}; host copies the card had no room for, asked again a second later: {}, made so: {}; \
|
||||
the card: {:.0} MB in use of a budget of {:.0} MB, {:.0} MB of the PC's memory \
|
||||
shared with it in use",
|
||||
census[2],
|
||||
mb(census[3]),
|
||||
@@ -807,6 +951,8 @@ fn log_memory() {
|
||||
mb(kinds[5]),
|
||||
kinds[6],
|
||||
crate::draw::HEAP_TEXTURES_FULL.load(Relaxed),
|
||||
crate::resource::NOT_MADE_FOR_NOW.load(Relaxed),
|
||||
crate::resource::MADE_AFTER_NO_ROOM.load(Relaxed),
|
||||
mb(card[1]),
|
||||
mb(card[0]),
|
||||
mb(card[3]),
|
||||
@@ -1156,6 +1302,194 @@ fn page_faults() -> u64 {
|
||||
u64::from(c.PageFaultCount)
|
||||
}
|
||||
|
||||
/// What [`log`] keeps of the faults in read calls from one line to the
|
||||
/// next: where its taking of [`FAULT_RING`] ended, the faults noted in
|
||||
/// frames not over then, and the last frame it looked at with its faulted
|
||||
/// pages (on guards, others), in order.
|
||||
struct FaultsTaken {
|
||||
next: u64,
|
||||
held: Vec<u64>,
|
||||
last: Option<(u64, [Vec<u64>; 2])>,
|
||||
}
|
||||
|
||||
static FAULTS_TAKEN: Mutex<FaultsTaken> = Mutex::new(FaultsTaken { next: 0, held: Vec::new(), last: None });
|
||||
|
||||
/// The faults in read calls since the last line, as [`log`] prints them.
|
||||
struct ReadFaults {
|
||||
/// By kind ([`ReadFault`]), as noted.
|
||||
kinds: [u64; READ_KINDS],
|
||||
/// Over the frames that ended (on guards, others): faulted 4 KiB pages
|
||||
/// that faulted in the frame before too, and the rest.
|
||||
repeat: [u64; 2],
|
||||
new: [u64; 2],
|
||||
/// Noted since the last line, and lost to the ring's wrapping.
|
||||
noted: u64,
|
||||
lost: u64,
|
||||
/// The busiest ranges, for their own line.
|
||||
busiest: String,
|
||||
}
|
||||
|
||||
/// How many of the sorted pages of `a` are in the sorted `b`.
|
||||
fn in_both(a: &[u64], b: &[u64]) -> u64 {
|
||||
let (mut i, mut k, mut n) = (0, 0, 0);
|
||||
while i < a.len() && k < b.len() {
|
||||
match a[i].cmp(&b[k]) {
|
||||
std::cmp::Ordering::Less => i += 1,
|
||||
std::cmp::Ordering::Greater => k += 1,
|
||||
std::cmp::Ordering::Equal => {
|
||||
n += 1;
|
||||
i += 1;
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// Takes what [`read_fault`] noted since the last line ([`FAULT_RING`]): its
|
||||
/// kinds; per frame that is over, its faulted pages against the frame
|
||||
/// before's; and the three ranges that faulted most, by allocation (asking
|
||||
/// Windows about the most faulted 2 MiB pieces, four at most).
|
||||
fn read_faults() -> ReadFaults {
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
MEM_COMMIT, MEM_FREE, MEM_IMAGE, MEM_MAPPED, MEM_PRIVATE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, PAGE_GUARD,
|
||||
VirtualQuery,
|
||||
};
|
||||
let frame_of = |v: u64| v >> 40;
|
||||
let kind_of = |v: u64| (v >> 37 & 7) as usize;
|
||||
let page_of = |v: u64| v & RING_PAGE;
|
||||
// Guards (0) or others (1).
|
||||
let group_of = |v: u64| usize::from(kind_of(v) > ReadFault::OurGuard as usize);
|
||||
let mut t = FAULTS_TAKEN.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let head = FAULT_NOTED.load(Relaxed);
|
||||
let mut lost = head.saturating_sub(t.next).saturating_sub(RING as u64);
|
||||
let mut noted = Vec::new();
|
||||
for i in t.next.max(head.saturating_sub(RING as u64))..head {
|
||||
let v = FAULT_RING[(i % RING as u64) as usize].swap(0, Relaxed);
|
||||
if v != 0 {
|
||||
noted.push(v);
|
||||
}
|
||||
}
|
||||
t.next = head;
|
||||
let mut kinds = [0u64; READ_KINDS];
|
||||
for &v in ¬ed {
|
||||
kinds[kind_of(v)] += 1;
|
||||
}
|
||||
// The busiest 2 MiB pieces: faults (guards, others), pages, lowest and
|
||||
// highest page.
|
||||
let mut by_page: Vec<(u64, usize)> = noted.iter().map(|&v| (page_of(v), group_of(v))).collect();
|
||||
by_page.sort_unstable();
|
||||
let mut pieces: Vec<(u64, [u64; 2], u64, u64, u64)> = Vec::new();
|
||||
for (i, &(page, group)) in by_page.iter().enumerate() {
|
||||
let piece = page >> 9;
|
||||
if pieces.last().is_none_or(|p| p.0 != piece) {
|
||||
pieces.push((piece, [0; 2], 0, page, page));
|
||||
}
|
||||
let p = pieces.last_mut().expect("pushed");
|
||||
p.1[group] += 1;
|
||||
p.2 += u64::from(i == 0 || by_page[i - 1].0 != page);
|
||||
p.4 = page;
|
||||
}
|
||||
pieces.sort_unstable_by_key(|p| std::cmp::Reverse(p.1[0] + p.1[1]));
|
||||
// By allocation: its base, the region of the first piece's lowest page
|
||||
// (base, bytes, state, type, protection), faults, pages, lowest and
|
||||
// highest page.
|
||||
let mut ranges: Vec<(usize, (usize, usize, u32, u32, u32), [u64; 2], u64, u64, u64)> = Vec::new();
|
||||
for p in pieces.iter().take(4) {
|
||||
// SAFETY: plain data filled in by the query.
|
||||
let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: a valid out pointer of the right size; nothing is touched.
|
||||
let asked = unsafe { VirtualQuery((p.3 << 12) as usize as *const _, &mut m, size_of_val(&m)) } != 0;
|
||||
let base = if asked && m.State != MEM_FREE { m.AllocationBase as usize } else { (p.0 << 21) as usize };
|
||||
let region = if asked { (m.BaseAddress as usize, m.RegionSize, m.State, m.Type, m.Protect) } else { (0, 0, 0, 0, 0) };
|
||||
match ranges.iter_mut().find(|r| r.0 == base) {
|
||||
Some(r) => {
|
||||
r.2 = [r.2[0] + p.1[0], r.2[1] + p.1[1]];
|
||||
r.3 += p.2;
|
||||
r.4 = r.4.min(p.3);
|
||||
r.5 = r.5.max(p.4);
|
||||
}
|
||||
None => ranges.push((base, region, p.1, p.2, p.3, p.4)),
|
||||
}
|
||||
}
|
||||
ranges.sort_by_key(|r| std::cmp::Reverse(r.2[0] + r.2[1]));
|
||||
let state = |s: u32| match s {
|
||||
MEM_COMMIT => "committed",
|
||||
MEM_RESERVE => "reserved",
|
||||
MEM_FREE => "free",
|
||||
_ => "?",
|
||||
};
|
||||
let kind = |k: u32| match k {
|
||||
MEM_PRIVATE => "private",
|
||||
MEM_MAPPED => "mapped",
|
||||
MEM_IMAGE => "image",
|
||||
_ => "-",
|
||||
};
|
||||
let busiest: Vec<String> = ranges
|
||||
.iter()
|
||||
.take(3)
|
||||
.map(|&(base, (at, bytes, s, k, protect), faults, pages, low, high)| {
|
||||
format!(
|
||||
"allocation {base:#x} (region {at:#x}+{bytes:#x} {} {} protect {protect:#x}{}): {} faults ({} on guards, {} others) \
|
||||
on {pages} pages of 4 KiB from {:#x} to {:#x}",
|
||||
state(s),
|
||||
kind(k),
|
||||
if protect & PAGE_GUARD != 0 { " guard" } else { "" },
|
||||
faults[0] + faults[1],
|
||||
faults[0],
|
||||
faults[1],
|
||||
low << 12,
|
||||
(high + 1) << 12,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
// Frames that are over: each one's pages against the frame before's.
|
||||
let now = crate::frame::current() & RING_FRAME;
|
||||
let mut all = std::mem::take(&mut t.held);
|
||||
all.extend_from_slice(¬ed);
|
||||
let (over, mut held): (Vec<u64>, Vec<u64>) = all.into_iter().partition(|&v| frame_of(v) < now);
|
||||
// (Frames that do not end, as while loading: kept to a ring's worth.)
|
||||
if held.len() > RING {
|
||||
lost += (held.len() - RING) as u64;
|
||||
held.drain(..held.len() - RING);
|
||||
}
|
||||
t.held = held;
|
||||
let mut keys: Vec<(u64, usize, u64)> = over.iter().map(|&v| (frame_of(v), group_of(v), page_of(v))).collect();
|
||||
keys.sort_unstable();
|
||||
keys.dedup();
|
||||
let (mut repeat, mut new) = ([0u64; 2], [0u64; 2]);
|
||||
let mut i = 0;
|
||||
while i < keys.len() {
|
||||
let frame = keys[i].0;
|
||||
let mut pages: [Vec<u64>; 2] = [Vec::new(), Vec::new()];
|
||||
while i < keys.len() && keys[i].0 == frame {
|
||||
pages[keys[i].1].push(keys[i].2);
|
||||
i += 1;
|
||||
}
|
||||
// (Noted late, of a frame looked at already: left out.)
|
||||
if t.last.as_ref().is_some_and(|l| frame <= l.0) {
|
||||
continue;
|
||||
}
|
||||
for g in 0..2 {
|
||||
let again = match &t.last {
|
||||
Some((last, before)) if last + 1 == frame => in_both(&pages[g], &before[g]),
|
||||
_ => 0,
|
||||
};
|
||||
repeat[g] += again;
|
||||
new[g] += pages[g].len() as u64 - again;
|
||||
}
|
||||
t.last = Some((frame, pages));
|
||||
}
|
||||
ReadFaults {
|
||||
kinds,
|
||||
repeat,
|
||||
new,
|
||||
noted: noted.len() as u64,
|
||||
lost,
|
||||
busiest: if busiest.is_empty() { "none".into() } else { busiest.join("; ") },
|
||||
}
|
||||
}
|
||||
|
||||
/// Logs the counters per frame, and the ranges that took most bytes. The
|
||||
/// counters run from line to line, so they are divided by the frames
|
||||
/// presented since the last line, not by `frames` (the frames of the last
|
||||
@@ -1170,12 +1504,25 @@ pub(crate) fn log(frames: f64) {
|
||||
let c: Vec<f64> = (0..COUNTERS).map(|i| taken(i) as f64 / frames).collect();
|
||||
let mb = |v: f64| v / 1e6;
|
||||
let ms = |v: f64| v / 1e3;
|
||||
// Our reads of title memory, by the faults taken in them.
|
||||
let r = read_faults();
|
||||
let read_calls = c[C::ReadCalls as usize] + c[C::ReadGuardCalls as usize] + c[C::ReadOtherCalls as usize];
|
||||
let [no_fault_ms, guard_fault_ms, other_fault_ms] = [C::ReadNs, C::ReadGuardNs, C::ReadOtherNs].map(|t| c[t as usize] / 1e6);
|
||||
let kind = |k: ReadFault| r.kinds[k as usize] as f64 / frames;
|
||||
let [repeat_guard, repeat_other] = r.repeat.map(|n| n as f64 / frames);
|
||||
let [new_guard, new_other] = r.new.map(|n| n as f64 / frames);
|
||||
tracing::info!(
|
||||
"copies per frame: {:.1} submissions; {:.0} title copies {:.1} MB; {:.0} refreshes {:.1} MB, \
|
||||
{:.0} skipped {:.1} MB; {:.0} runs {:.1} ms; {:.0} queries {:.2} ms, moves {:.2} ms, \
|
||||
{:.2} MB unmapped; {:.0} page faults; {:.0} watches {:.2} ms, {:.1} MB checked, {:.1} MB \
|
||||
unchanged; {:.1} fallbacks; {:.0} guard faults; textures {:.1} MB watched and \
|
||||
changed, {:.1} MB hashed, {:.1} MB of them changed, {:.1} changes the guard did not see",
|
||||
changed, {:.1} MB hashed, {:.1} MB of them changed, {:.1} changes the guard did not see; \
|
||||
reads of title memory (read_plain, safe copy {}): read_calls {read_calls:.0}, no_fault_ms {no_fault_ms:.2} in {:.0} \
|
||||
calls, guard_fault_ms {guard_fault_ms:.2} in {:.1} calls (guard_fault_count {:.1}: {:.1} guard pages of Windows', \
|
||||
{:.1} our guards), other_fault_ms {other_fault_ms:.2} in {:.1} calls (other_fault_count {:.1}: {:.1} not there, {:.1} \
|
||||
not writable, {:.1} views made real, {:.1} other exceptions); their faulted pages of 4 KiB: guards repeat_fault_pages \
|
||||
{repeat_guard:.1} new_fault_pages {new_guard:.1}, others repeat_fault_pages {repeat_other:.1} new_fault_pages \
|
||||
{new_other:.1} ({} faults noted since the last line, {} lost)",
|
||||
c[C::Submissions as usize],
|
||||
c[C::Copies as usize],
|
||||
mb(c[C::CopyBytes as usize]),
|
||||
@@ -1200,7 +1547,22 @@ pub(crate) fn log(frames: f64) {
|
||||
mb(c[C::TexHashed as usize]),
|
||||
mb(c[C::TexChanged as usize]),
|
||||
c[C::TexHot as usize],
|
||||
if crate::safecopy::on() { "on" } else { "off" },
|
||||
c[C::ReadCalls as usize],
|
||||
c[C::ReadGuardCalls as usize],
|
||||
c[C::ReadGuardFaults as usize],
|
||||
kind(ReadFault::PageGuard),
|
||||
kind(ReadFault::OurGuard),
|
||||
c[C::ReadOtherCalls as usize],
|
||||
c[C::ReadOtherFaults as usize],
|
||||
kind(ReadFault::NotThere),
|
||||
kind(ReadFault::NotWritable),
|
||||
kind(ReadFault::MadeReal),
|
||||
kind(ReadFault::Other),
|
||||
r.noted,
|
||||
r.lost,
|
||||
);
|
||||
tracing::info!(" faults in reads of title memory, the busiest ranges since the last line: {}", r.busiest);
|
||||
tracing::info!(
|
||||
"recording per frame ({frames:.0} frames): {:.0} list calls {:.1} ms (all recording \
|
||||
threads); {:.1} ms waiting for pipelines; dynamic slots: {:.0} tables asked, {:.0} \
|
||||
|
||||
@@ -83,12 +83,26 @@ fn helper_priority() -> Option<i32> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Effective priority for critical submission/helper threads (`from <= 2`) vs
|
||||
/// background list-translation workers (`from == 3`): when `VICTORY_HELPER_PRIORITY`
|
||||
/// is positive (e.g. `1`), critical submit/wide threads run one tier higher (`+2`,
|
||||
/// `HIGHEST`) than list-translation workers (`+1`, `ABOVE_NORMAL`), which in turn
|
||||
/// stay ahead of the title's busy-wait threads (`0`, `NORMAL`).
|
||||
fn effective_priority(from: u32, requested: i32) -> i32 {
|
||||
if from <= 2 && requested > 0 {
|
||||
(requested + 1).min(2)
|
||||
} else {
|
||||
requested
|
||||
}
|
||||
}
|
||||
|
||||
fn ask(what: &str, from: u32) {
|
||||
use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, SetThreadSelectedCpuSets};
|
||||
if let Some(priority) = helper_priority() {
|
||||
if let Some(requested) = helper_priority() {
|
||||
let priority = effective_priority(from, requested);
|
||||
// SAFETY: this thread's own priority.
|
||||
let set = unsafe { SetThreadPriority(GetCurrentThread(), priority) } != 0;
|
||||
tracing::debug!(what, priority, set, "the thread's priority (VICTORY_HELPER_PRIORITY)");
|
||||
tracing::debug!(what, from, priority, set, "the thread's priority (VICTORY_HELPER_PRIORITY)");
|
||||
}
|
||||
if stage() < from {
|
||||
return;
|
||||
@@ -152,7 +166,11 @@ impl Priority {
|
||||
if self.applied == Some(on) {
|
||||
return;
|
||||
}
|
||||
let priority = if on { THREAD_PRIORITY_ABOVE_NORMAL } else { THREAD_PRIORITY_NORMAL };
|
||||
let priority = if on {
|
||||
helper_priority().map_or(THREAD_PRIORITY_ABOVE_NORMAL, |p| effective_priority(2, p))
|
||||
} else {
|
||||
THREAD_PRIORITY_NORMAL
|
||||
};
|
||||
// SAFETY: our own thread.
|
||||
unsafe { SetThreadPriority(GetCurrentThread(), priority) };
|
||||
self.applied = Some(on);
|
||||
|
||||
@@ -458,13 +458,17 @@ pub(crate) fn sync_heaps() {
|
||||
let before = host.copied_before(frame);
|
||||
let of_tables = std::sync::atomic::AtomicU64::new(0);
|
||||
crate::land::each_view(true, before.len().div_ceil(records_a_job), &|n| {
|
||||
let mut local_tabled = 0u64;
|
||||
for &index in before.chunks(records_a_job).nth(n).unwrap_or_default() {
|
||||
if host.copied_tabled(index, frame) {
|
||||
of_tables.fetch_add(1, Relaxed);
|
||||
local_tabled += 1;
|
||||
} else {
|
||||
host.mirror(index, start + u64::from(index) * step, false);
|
||||
}
|
||||
}
|
||||
if local_tabled != 0 {
|
||||
of_tables.fetch_add(local_tabled, Relaxed);
|
||||
}
|
||||
});
|
||||
let of_tables = of_tables.into_inner();
|
||||
tabled += of_tables;
|
||||
@@ -489,6 +493,7 @@ pub(crate) fn sync_heaps() {
|
||||
let began = std::time::Instant::now();
|
||||
let copied = host.copied_begin(step as usize);
|
||||
let samplers = heap.samplers();
|
||||
let copied_waits = host.copied_waits();
|
||||
let in_place = sync_in_place() && step == 32 && crate::safecopy::on();
|
||||
let found: Vec<std::sync::Mutex<SyncPart>> = parts.chunks(pages_a_job).map(|_| Default::default()).collect();
|
||||
crate::land::each_view(true, found.len(), &|n| {
|
||||
@@ -553,39 +558,41 @@ pub(crate) fn sync_heaps() {
|
||||
.and_then(|b| b.try_into().ok())
|
||||
.map_or(0, u32::from_le_bytes)
|
||||
};
|
||||
if !samplers && word(0) == VIEW_TAG {
|
||||
// A draw's own table: the draw makes what it
|
||||
// reads of it (`draw.rs` `tables`).
|
||||
if host.copied_tabled(index, frame) {
|
||||
out.tabled += 1;
|
||||
continue;
|
||||
}
|
||||
// Buffer views and placed textures get no host
|
||||
// slot from this anyway, they wait for a draw
|
||||
// or a pass: noted some frames on, unless a
|
||||
// draw's table turns out to hold them.
|
||||
if matches!(word(2) >> KIND_SHIFT, CONSTANT | PLACED) && host.copied_waits() {
|
||||
out.wait.push(index);
|
||||
continue;
|
||||
}
|
||||
let w0 = word(0);
|
||||
if samplers {
|
||||
out.make.push(index);
|
||||
out.kinds[3] += 1;
|
||||
continue;
|
||||
}
|
||||
// No view, in a slot that shows none: nothing to make or
|
||||
// unmake (32,000 of 41,000 a frame on the water, run
|
||||
// b2-water).
|
||||
if word(0) != VIEW_TAG && host.shows_none(index) {
|
||||
out.nothing += 1;
|
||||
if w0 != VIEW_TAG {
|
||||
// No view, in a slot that shows none: nothing to make or
|
||||
// unmake (32,000 of 41,000 a frame on the water, run
|
||||
// b2-water).
|
||||
if host.shows_none(index) {
|
||||
out.nothing += 1;
|
||||
} else {
|
||||
out.make.push(index);
|
||||
out.kinds[0] += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// A draw's own table: the draw makes what it
|
||||
// reads of it (`draw.rs` `tables`).
|
||||
if host.copied_tabled(index, frame) {
|
||||
out.tabled += 1;
|
||||
continue;
|
||||
}
|
||||
let w2 = word(2);
|
||||
// Buffer views and placed textures get no host
|
||||
// slot from this anyway, they wait for a draw
|
||||
// or a pass: noted some frames on, unless a
|
||||
// draw's table turns out to hold them.
|
||||
if copied_waits && matches!(w2 >> KIND_SHIFT, CONSTANT | PLACED) {
|
||||
out.wait.push(index);
|
||||
continue;
|
||||
}
|
||||
out.make.push(index);
|
||||
out.kinds[if samplers {
|
||||
3
|
||||
} else if word(0) != VIEW_TAG {
|
||||
0
|
||||
} else if word(2) >> KIND_SHIFT == 0 {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
}] += 1;
|
||||
out.kinds[if w2 >> KIND_SHIFT == 0 { 1 } else { 2 }] += 1;
|
||||
}
|
||||
}
|
||||
*found[n].lock().unwrap_or_else(|e| e.into_inner()) = out;
|
||||
@@ -1019,7 +1026,7 @@ const DSV_TAG: u32 = u32::from_le_bytes(*b"vDSV");
|
||||
|
||||
/// A shader view or sampler as the title described it (descriptions in the
|
||||
/// host's layout, kept as words), for the host to build its own from.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub(crate) enum View {
|
||||
/// Constant buffer: GPU address and size.
|
||||
Constant(u64, u32),
|
||||
@@ -1076,16 +1083,53 @@ impl View {
|
||||
/// without the address: as many as the title has kinds of textures and
|
||||
/// buffers, however often it moves them).
|
||||
/// `VICTORY_VIEW_INLINE=0`: every view is an entry, as before.
|
||||
/// Fast non-cryptographic 64-bit hasher for internal view/shape lookup maps
|
||||
/// (keeps lock hold times O(1) without extra crate dependencies).
|
||||
#[derive(Default)]
|
||||
struct FxHasher(u64);
|
||||
|
||||
impl std::hash::Hasher for FxHasher {
|
||||
#[inline]
|
||||
fn finish(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
#[inline]
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
const K: u64 = 0x517c_c1b7_2722_0a95;
|
||||
let mut h = self.0;
|
||||
let mut chunks = bytes.chunks_exact(8);
|
||||
for c in &mut chunks {
|
||||
let v = u64::from_ne_bytes(c.try_into().expect("8-byte chunk"));
|
||||
h = (h.rotate_left(5) ^ v).wrapping_mul(K);
|
||||
}
|
||||
for &b in chunks.remainder() {
|
||||
h = (h.rotate_left(5) ^ u64::from(b)).wrapping_mul(K);
|
||||
}
|
||||
self.0 = h;
|
||||
}
|
||||
#[inline]
|
||||
fn write_u32(&mut self, i: u32) {
|
||||
self.0 = (self.0.rotate_left(5) ^ u64::from(i)).wrapping_mul(0x517c_c1b7_2722_0a95);
|
||||
}
|
||||
#[inline]
|
||||
fn write_u64(&mut self, i: u64) {
|
||||
self.0 = (self.0.rotate_left(5) ^ i).wrapping_mul(0x517c_c1b7_2722_0a95);
|
||||
}
|
||||
#[inline]
|
||||
fn write_usize(&mut self, i: usize) {
|
||||
self.write_u64(i as u64);
|
||||
}
|
||||
}
|
||||
|
||||
type FastMap<K, V> = std::collections::HashMap<K, V, std::hash::BuildHasherDefault<FxHasher>>;
|
||||
|
||||
struct Views {
|
||||
/// Each entry's view and generation.
|
||||
list: Vec<(View, u32)>,
|
||||
index: std::collections::BTreeMap<View, u32>,
|
||||
index: FastMap<View, u32>,
|
||||
/// Entries naming each resource.
|
||||
by_resource: std::collections::BTreeMap<usize, Vec<u32>>,
|
||||
by_resource: FastMap<usize, Vec<u32>>,
|
||||
free: Vec<u32>,
|
||||
/// The shapes of views of placed memory, and where each is.
|
||||
shapes: Vec<Shape>,
|
||||
shape_index: std::collections::BTreeMap<Shape, u32>,
|
||||
/// Entries of views that no resource releases (constant buffer views
|
||||
/// and views of placed memory that did not fit a record), oldest first,
|
||||
/// with the generation each was made at: past [`ownerless_cap`] the
|
||||
@@ -1093,19 +1137,45 @@ struct Views {
|
||||
ownerless: std::collections::VecDeque<(u32, u32)>,
|
||||
}
|
||||
|
||||
/// Append-only table of placed-view shapes, kept under its own `RwLock` so
|
||||
/// frequent `PLACED` lookups across recording threads never stall behind
|
||||
/// `VIEWS` resource-creation or `forget` writes.
|
||||
struct ViewShapes {
|
||||
/// The shapes of views of placed memory, and where each is.
|
||||
shapes: Vec<Shape>,
|
||||
shape_index: FastMap<Shape, u32>,
|
||||
}
|
||||
|
||||
/// Read far more often than written: every slot a draw reads through a
|
||||
/// table is looked up here, on several recording threads at once in the
|
||||
/// world. Readers share it; only a view not seen before (a new table entry
|
||||
/// or shape) and a released resource take it alone.
|
||||
static VIEWS: std::sync::RwLock<Views> = std::sync::RwLock::new(Views {
|
||||
list: Vec::new(),
|
||||
index: std::collections::BTreeMap::new(),
|
||||
by_resource: std::collections::BTreeMap::new(),
|
||||
free: Vec::new(),
|
||||
shapes: Vec::new(),
|
||||
shape_index: std::collections::BTreeMap::new(),
|
||||
ownerless: std::collections::VecDeque::new(),
|
||||
});
|
||||
/// world. Readers share it; only a view not seen before (a new table entry)
|
||||
/// and a released resource take it alone.
|
||||
static VIEWS: std::sync::OnceLock<std::sync::RwLock<Views>> = std::sync::OnceLock::new();
|
||||
|
||||
static VIEW_SHAPES: std::sync::OnceLock<std::sync::RwLock<ViewShapes>> = std::sync::OnceLock::new();
|
||||
|
||||
#[inline]
|
||||
fn views_lock() -> &'static std::sync::RwLock<Views> {
|
||||
VIEWS.get_or_init(|| {
|
||||
std::sync::RwLock::new(Views {
|
||||
list: Vec::new(),
|
||||
index: FastMap::default(),
|
||||
by_resource: FastMap::default(),
|
||||
free: Vec::new(),
|
||||
ownerless: std::collections::VecDeque::new(),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn shapes_lock() -> &'static std::sync::RwLock<ViewShapes> {
|
||||
VIEW_SHAPES.get_or_init(|| {
|
||||
std::sync::RwLock::new(ViewShapes {
|
||||
shapes: Vec::new(),
|
||||
shape_index: FastMap::default(),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// How many table entries of views without a resource are kept
|
||||
/// ([`Views::ownerless`]). Once the shapes of placed views are full (the
|
||||
@@ -1249,7 +1319,7 @@ fn placed_words(shape: u32, address: u64) -> [u32; 2] {
|
||||
kind_words(PLACED, u64::from(shape) << PLACED_ADDRESS_BITS | address)
|
||||
}
|
||||
|
||||
impl Views {
|
||||
impl ViewShapes {
|
||||
/// The number of `shape`, a new one if it is not there yet; `None` when
|
||||
/// the shapes are full (the view is then a table entry).
|
||||
fn shape(&mut self, shape: Shape) -> Option<u32> {
|
||||
@@ -1278,7 +1348,9 @@ impl Views {
|
||||
desc[12..].copy_from_slice(&rest[10..]);
|
||||
Some(View::Placed(unordered, resource, desc))
|
||||
}
|
||||
}
|
||||
|
||||
impl Views {
|
||||
/// The record words of `view` as a table entry, if it has one.
|
||||
fn entry_of(&self, view: &View) -> Option<[u32; 2]> {
|
||||
let &i = self.index.get(view)?;
|
||||
@@ -1362,8 +1434,8 @@ fn words_for(view: View) -> [u32; 2] {
|
||||
let (shape, address) = shape_of(*unordered, resource, desc);
|
||||
if address >> PLACED_ADDRESS_BITS == 0 {
|
||||
// Nearly every placed view has a shape seen before.
|
||||
let known = views_read().shape_index.get(&shape).copied();
|
||||
let shape = known.or_else(|| views_write().shape(shape));
|
||||
let known = shapes_read().shape_index.get(&shape).copied();
|
||||
let shape = known.or_else(|| shapes_write().shape(shape));
|
||||
if let Some(shape) = shape {
|
||||
NAMED_WHOLE[1].fetch_add(1, Relaxed);
|
||||
return placed_words(shape, address);
|
||||
@@ -1381,12 +1453,13 @@ fn words_for(view: View) -> [u32; 2] {
|
||||
}
|
||||
|
||||
fn views_read() -> std::sync::RwLockReadGuard<'static, Views> {
|
||||
match VIEWS.try_read() {
|
||||
let lock = views_lock();
|
||||
match lock.try_read() {
|
||||
Ok(views) => views,
|
||||
Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(),
|
||||
Err(std::sync::TryLockError::WouldBlock) => {
|
||||
let started = std::time::Instant::now();
|
||||
let views = VIEWS.read().unwrap_or_else(|e| e.into_inner());
|
||||
let views = lock.read().unwrap_or_else(|e| e.into_inner());
|
||||
waited(1, started);
|
||||
views
|
||||
}
|
||||
@@ -1394,18 +1467,47 @@ fn views_read() -> std::sync::RwLockReadGuard<'static, Views> {
|
||||
}
|
||||
|
||||
fn views_write() -> std::sync::RwLockWriteGuard<'static, Views> {
|
||||
match VIEWS.try_write() {
|
||||
let lock = views_lock();
|
||||
match lock.try_write() {
|
||||
Ok(views) => views,
|
||||
Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(),
|
||||
Err(std::sync::TryLockError::WouldBlock) => {
|
||||
let started = std::time::Instant::now();
|
||||
let views = VIEWS.write().unwrap_or_else(|e| e.into_inner());
|
||||
let views = lock.write().unwrap_or_else(|e| e.into_inner());
|
||||
waited(1, started);
|
||||
views
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn shapes_read() -> std::sync::RwLockReadGuard<'static, ViewShapes> {
|
||||
let lock = shapes_lock();
|
||||
match lock.try_read() {
|
||||
Ok(shapes) => shapes,
|
||||
Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(),
|
||||
Err(std::sync::TryLockError::WouldBlock) => {
|
||||
let started = std::time::Instant::now();
|
||||
let shapes = lock.read().unwrap_or_else(|e| e.into_inner());
|
||||
waited(1, started);
|
||||
shapes
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn shapes_write() -> std::sync::RwLockWriteGuard<'static, ViewShapes> {
|
||||
let lock = shapes_lock();
|
||||
match lock.try_write() {
|
||||
Ok(shapes) => shapes,
|
||||
Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(),
|
||||
Err(std::sync::TryLockError::WouldBlock) => {
|
||||
let started = std::time::Instant::now();
|
||||
let shapes = lock.write().unwrap_or_else(|e| e.into_inner());
|
||||
waited(1, started);
|
||||
shapes
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// For the memory line: the distinct views kept ([`Views`]), those of them
|
||||
/// free for reuse, and the bytes the table and its index hold for them (an
|
||||
/// estimate: an entry of the table, and one of the index with its share of
|
||||
@@ -1418,6 +1520,7 @@ fn views_write() -> std::sync::RwLockWriteGuard<'static, Views> {
|
||||
pub(crate) fn views_kept() -> [u64; 8] {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let views = views_read();
|
||||
let shapes = shapes_read();
|
||||
let each = size_of::<(View, u32)>() as u64;
|
||||
let shape = size_of::<Shape>() as u64;
|
||||
let (mut constants, mut placed) = (0, 0);
|
||||
@@ -1433,11 +1536,11 @@ pub(crate) fn views_kept() -> [u64; 8] {
|
||||
views.free.len() as u64,
|
||||
views.list.capacity() as u64 * each
|
||||
+ views.index.len() as u64 * each * 3 / 2
|
||||
+ views.shapes.capacity() as u64 * shape
|
||||
+ views.shape_index.len() as u64 * shape * 3 / 2,
|
||||
+ shapes.shapes.capacity() as u64 * shape
|
||||
+ shapes.shape_index.len() as u64 * shape * 3 / 2,
|
||||
constants,
|
||||
placed,
|
||||
views.shapes.len() as u64,
|
||||
shapes.shapes.len() as u64,
|
||||
NAMED_WHOLE[0].load(Relaxed),
|
||||
NAMED_WHOLE[1].load(Relaxed),
|
||||
]
|
||||
@@ -1657,6 +1760,9 @@ pub(crate) fn forget(resource: usize) {
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.remove(&resource);
|
||||
if !views_read().by_resource.contains_key(&resource) {
|
||||
return;
|
||||
}
|
||||
let mut views = views_write();
|
||||
let Some(entries) = views.by_resource.remove(&resource) else {
|
||||
return;
|
||||
@@ -1687,7 +1793,7 @@ fn view_at(i: u32, generation: u32) -> Option<View> {
|
||||
(*current == generation).then(|| view.clone())
|
||||
}
|
||||
CONSTANT => Some(constant_of(i, generation)),
|
||||
PLACED => views_read().placed_of(i, generation),
|
||||
PLACED => shapes_read().placed_of(i, generation),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -2324,11 +2430,9 @@ mod tests {
|
||||
fn ownerless_entries_are_capped() {
|
||||
let mut views = Views {
|
||||
list: Vec::new(),
|
||||
index: std::collections::BTreeMap::new(),
|
||||
by_resource: std::collections::BTreeMap::new(),
|
||||
index: FastMap::default(),
|
||||
by_resource: FastMap::default(),
|
||||
free: Vec::new(),
|
||||
shapes: Vec::new(),
|
||||
shape_index: std::collections::BTreeMap::new(),
|
||||
ownerless: std::collections::VecDeque::new(),
|
||||
};
|
||||
let placed = |n: u32| View::Placed(false, [n; 14], [n; 16]);
|
||||
@@ -2422,8 +2526,8 @@ mod tests {
|
||||
View::Placed(_, r, _) => *r == kept,
|
||||
_ => false,
|
||||
};
|
||||
let entries = || VIEWS.read().unwrap().list.iter().filter(|(v, _)| mine(v)).count();
|
||||
let shapes = || VIEWS.read().unwrap().shapes.iter().filter(|s| s.1 == kept).count();
|
||||
let entries = || views_read().list.iter().filter(|(v, _)| mine(v)).count();
|
||||
let shapes = || shapes_read().shapes.iter().filter(|s| s.1 == kept).count();
|
||||
for n in 0..20_000u64 {
|
||||
let address = 0x6_0000_0000 + n * 0x100;
|
||||
create_cbv(null, &[address as u32, (address >> 32) as u32, 512, 0], at);
|
||||
|
||||
@@ -26,6 +26,7 @@ fn raw_view_clamp() -> bool {
|
||||
/// A set of a heap's slots, a bit for each: no lock (a pass that went through
|
||||
/// a set of 70,000 under its lock kept everyone who writes slots waiting for
|
||||
/// 5 ms of a frame, timeline thin-6).
|
||||
#[derive(Default)]
|
||||
struct Slots(Vec<std::sync::atomic::AtomicU64>);
|
||||
|
||||
impl Slots {
|
||||
@@ -50,6 +51,13 @@ impl Slots {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `slot` is set; `None` if the set reaches no word for it (it
|
||||
/// is empty, [`tabled_bits`] off).
|
||||
fn has(&self, slot: u32) -> Option<bool> {
|
||||
let bit = 1 << (slot % 64);
|
||||
self.0.get(slot as usize / 64).map(|bits| bits.load(std::sync::atomic::Ordering::Acquire) & bit != 0)
|
||||
}
|
||||
|
||||
fn of(n: usize, mut bits: u64, out: &mut Vec<u32>, which: &impl Fn(u32) -> bool) {
|
||||
while bits != 0 {
|
||||
let slot = n as u32 * 64 + bits.trailing_zeros();
|
||||
@@ -174,8 +182,8 @@ pub(crate) struct HostHeap {
|
||||
/// made for a draw takes it, and lets go of what the slot held under it).
|
||||
kept: Box<[Mutex<Option<ID3D12Resource>>]>,
|
||||
/// Where the search for free dynamic slots starts, and which are taken
|
||||
/// (by lists not yet reset).
|
||||
next: Mutex<(u32, Vec<bool>)>,
|
||||
/// (by lists not yet reset), 64 slots per `u64` word.
|
||||
next: Mutex<(u32, Vec<u64>)>,
|
||||
/// How many dynamic slots are free (changed under `next`'s lock): with
|
||||
/// fewer than a table needs, the search is not made. Once the world
|
||||
/// had taken them all, every later table of the frame searched every
|
||||
@@ -212,6 +220,10 @@ pub(crate) struct HostHeap {
|
||||
textures: Mutex<TextureQueue>,
|
||||
/// What `textures` holds, read without its lock ([`QueueMarks`]).
|
||||
marks: std::sync::Arc<QueueMarks>,
|
||||
/// The "in the texture queue" bit per slot ([`tabled_bits`]), shared with
|
||||
/// the queue, which sets and clears it in step with its slot map; read
|
||||
/// here without the queue's lock. Empty (no word) when the toggle is off.
|
||||
queue_bits: std::sync::Arc<Slots>,
|
||||
/// Per title slot, the frame (plus one; 0: never) in which a draw last
|
||||
/// read it through a table, or made a table it lies in (with
|
||||
/// [`TABLED_READ`] set if the draw read it). The draw that
|
||||
@@ -1129,6 +1141,35 @@ fn queue_marks() -> bool {
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_QUEUE_MARKS").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// `VICTORY_TABLED_BITS=1`: keep a one-bit-per-slot "in the texture queue"
|
||||
/// set ([`HostHeap::queue_bits`], a packed [`Slots`]) beside the queue, so
|
||||
/// a slot a draw reads through a table and that was never queued is found
|
||||
/// not queued by a single bit load, and [`HostHeap::tabled_in_as`] skips
|
||||
/// the texture-queue lock without reading the slot's full mark.
|
||||
///
|
||||
/// INVARIANT (the bit can never be stale): the set mirrors the queue's slot
|
||||
/// map exactly because the only two places that change membership are
|
||||
/// [`TextureQueue::put`] (adds a slot) and [`TextureQueue::take_out`]
|
||||
/// (removes one), and each sets or clears the bit under the queue's lock,
|
||||
/// in the same step it inserts into or removes from `slots`. Every other
|
||||
/// queue method (`written`, `changed`, `done`, `remove`, `hold`, `room`,
|
||||
/// `later`, `partly`, `recheck`) reaches membership only through those two,
|
||||
/// so no enqueue/dequeue/remap/evict/slot-reuse path can leave the bit
|
||||
/// clear while the slot is queued (which would wrongly skip the lock) or
|
||||
/// set while it is gone. A clear bit therefore proves "not queued", which
|
||||
/// is all the lock-skip relies on.
|
||||
///
|
||||
/// Off by default, and inert when off: [`HostHeap::queue_bits`] is then an
|
||||
/// empty [`Slots`] whose `put`/`remove`/load are no-ops reaching no word,
|
||||
/// so no bit is touched on the hot path and [`HostHeap::tabled_in_as`]
|
||||
/// keeps its old marks-only skip. Independent of and composable with
|
||||
/// `VICTORY_JOIN_FEWER`/`VICTORY_RELAY_EACH`, which touch neither the queue
|
||||
/// nor the heaps.
|
||||
fn tabled_bits() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_TABLED_BITS").is_some_and(|v| v == "1"))
|
||||
}
|
||||
|
||||
/// The queue's lock was not taken at place `site` (`super::queue_site`), as
|
||||
/// nothing would have changed: counted in `super::QUEUE_LOCK`, by the
|
||||
/// thread in batches (these happen hundreds of thousands of times in five
|
||||
@@ -1207,17 +1248,26 @@ pub(crate) struct TextureQueue {
|
||||
/// What `slots` holds, for reading without the lock (the host heap
|
||||
/// keeps the same; none in tests made without a heap).
|
||||
marks: std::sync::Arc<QueueMarks>,
|
||||
/// The "in the queue" bit per slot ([`tabled_bits`]), set and cleared
|
||||
/// here in step with `slots`; empty (no word) when the toggle is off, so
|
||||
/// `put`/`remove` are no-ops. Shared with the host heap, which reads it
|
||||
/// without the lock.
|
||||
bits: std::sync::Arc<Slots>,
|
||||
}
|
||||
|
||||
impl TextureQueue {
|
||||
/// An empty queue whose marks are `marks`.
|
||||
fn with_marks(marks: std::sync::Arc<QueueMarks>) -> Self {
|
||||
TextureQueue { marks, ..Default::default() }
|
||||
/// An empty queue whose marks are `marks` and whose in-queue bits are
|
||||
/// `bits`.
|
||||
fn with_marks(marks: std::sync::Arc<QueueMarks>, bits: std::sync::Arc<Slots>) -> Self {
|
||||
TextureQueue { marks, bits, ..Default::default() }
|
||||
}
|
||||
|
||||
/// Slot `index` holds `waiting` now.
|
||||
fn put(&mut self, index: u32, waiting: Waiting) {
|
||||
self.marks.set(index, waiting.write);
|
||||
// Set in step with the insert (no-op when `tabled_bits` is off): the
|
||||
// bit is now true iff the slot is in `slots`.
|
||||
self.bits.put(index);
|
||||
self.slots.insert(index, waiting);
|
||||
}
|
||||
|
||||
@@ -1227,6 +1277,10 @@ impl TextureQueue {
|
||||
if was {
|
||||
self.marks.set(index, 0);
|
||||
}
|
||||
// Clear in step with the remove (no-op when `tabled_bits` is off, and
|
||||
// when the slot was not there): the bit is now true iff the slot is
|
||||
// in `slots`.
|
||||
self.bits.remove(index);
|
||||
was
|
||||
}
|
||||
|
||||
@@ -1270,9 +1324,15 @@ impl TextureQueue {
|
||||
/// slots in the first gameplay area kept it 1-5 ms a pass, and the
|
||||
/// title's recording threads, whose every descriptor copy notes its slot
|
||||
/// here, waited that long behind it (run timeline, 2026-11-26).
|
||||
#[cfg(test)]
|
||||
fn due_and_census(&self, frame: u64) -> (Due, [u64; 6]) {
|
||||
self.due_and_census_capped(frame, usize::MAX)
|
||||
}
|
||||
|
||||
fn due_and_census_capped(&self, frame: u64, cap: usize) -> (Due, [u64; 6]) {
|
||||
let mut due = Due::default();
|
||||
let mut c = [self.slots.len() as u64, 0, 0, 0, 0, 0];
|
||||
let early_stop = (cap > 0 && cap <= 256).then(|| cap.saturating_mul(2));
|
||||
for (&index, w) in &self.slots {
|
||||
let again = w.checked.2 != 0;
|
||||
if w.mapped > 0 {
|
||||
@@ -1294,6 +1354,11 @@ impl TextureQueue {
|
||||
} else {
|
||||
due.fresh.push((w.written, index, w.write));
|
||||
}
|
||||
if let Some(limit) = early_stop
|
||||
&& due.fresh.len() + due.again.len() >= limit
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
(due, c)
|
||||
@@ -1795,7 +1860,11 @@ pub(crate) fn slot_story(slot: u32) -> String {
|
||||
let mut text = if index < host.count {
|
||||
format!("title slot {index}, made from {}", host.describe_slot(index).unwrap_or_default())
|
||||
} else {
|
||||
let taken = host.next.lock().unwrap_or_else(|e| e.into_inner()).1.get((index - host.count) as usize).copied();
|
||||
let taken = {
|
||||
let guard = host.next.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let bit = (index - host.count) as usize;
|
||||
guard.1.get(bit / 64).map(|w| (w >> (bit % 64)) & 1 != 0)
|
||||
};
|
||||
format!("dynamic slot {} (taken {taken:?})", index - host.count)
|
||||
};
|
||||
if twin {
|
||||
@@ -1978,6 +2047,116 @@ fn dynamic_slots(count: u32, null: u32) -> u32 {
|
||||
null.saturating_sub(count).min(most).max(DYNAMIC)
|
||||
}
|
||||
|
||||
/// Finds the first contiguous run of `n` zero bits in `words` within `[lo, hi)`.
|
||||
fn find_free_run(words: &[u64], lo: usize, hi: usize, n: usize) -> Option<usize> {
|
||||
if n == 0 {
|
||||
return (lo <= hi).then_some(lo);
|
||||
}
|
||||
if lo >= hi || hi - lo < n {
|
||||
return None;
|
||||
}
|
||||
let first_word = lo / 64;
|
||||
let last_word = (hi - 1) / 64;
|
||||
let lo_bit = lo % 64;
|
||||
let hi_bit = hi % 64;
|
||||
let mut run = 0usize;
|
||||
for (w, &raw) in words.iter().enumerate().take(last_word + 1).skip(first_word) {
|
||||
let mut taken = raw;
|
||||
if w == first_word && lo_bit != 0 {
|
||||
taken |= (1u64 << lo_bit) - 1;
|
||||
}
|
||||
if w == last_word && hi_bit != 0 {
|
||||
taken |= !0u64 << hi_bit;
|
||||
}
|
||||
if taken == u64::MAX {
|
||||
run = 0;
|
||||
continue;
|
||||
}
|
||||
if taken == 0 {
|
||||
if n <= 64 {
|
||||
return Some(w * 64 - run);
|
||||
}
|
||||
run += 64;
|
||||
if run >= n {
|
||||
return Some((w + 1) * 64 - run);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let mut free = !taken;
|
||||
if run > 0 {
|
||||
let prefix = taken.trailing_zeros() as usize;
|
||||
if run + prefix >= n {
|
||||
return Some(w * 64 - run);
|
||||
}
|
||||
if prefix > 0 {
|
||||
free &= !((1u64 << prefix) - 1);
|
||||
}
|
||||
run = 0;
|
||||
}
|
||||
while free != 0 {
|
||||
let b = free.trailing_zeros() as usize;
|
||||
let len = (free >> b).trailing_ones() as usize;
|
||||
if len >= n {
|
||||
return Some(w * 64 + b);
|
||||
}
|
||||
if b + len == 64 {
|
||||
run = len;
|
||||
break;
|
||||
}
|
||||
free &= !(((1u64 << len) - 1) << b);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Sets `n` bits starting at `first` in `words`.
|
||||
fn set_bits(words: &mut [u64], first: usize, n: usize) {
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
let end = first + n;
|
||||
let first_word = first / 64;
|
||||
let last_word = (end - 1) / 64;
|
||||
let lo_mask = !0u64 << (first % 64);
|
||||
let hi_bit = end % 64;
|
||||
let hi_mask = if hi_bit == 0 { !0u64 } else { (1u64 << hi_bit) - 1 };
|
||||
if first_word == last_word {
|
||||
words[first_word] |= lo_mask & hi_mask;
|
||||
} else {
|
||||
words[first_word] |= lo_mask;
|
||||
words[first_word + 1..last_word].fill(!0u64);
|
||||
words[last_word] |= hi_mask;
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears bits in `[start, end)` in `words` and returns how many were set.
|
||||
fn clear_and_count_bits(words: &mut [u64], start: usize, end: usize) -> u32 {
|
||||
if start >= end {
|
||||
return 0;
|
||||
}
|
||||
let first_word = start / 64;
|
||||
let last_word = (end - 1) / 64;
|
||||
let lo_mask = !0u64 << (start % 64);
|
||||
let hi_bit = end % 64;
|
||||
let hi_mask = if hi_bit == 0 { !0u64 } else { (1u64 << hi_bit) - 1 };
|
||||
if first_word == last_word {
|
||||
let mask = lo_mask & hi_mask;
|
||||
let given = (words[first_word] & mask).count_ones();
|
||||
words[first_word] &= !mask;
|
||||
given
|
||||
} else {
|
||||
let mut given = (words[first_word] & lo_mask).count_ones();
|
||||
words[first_word] &= !lo_mask;
|
||||
for w in &mut words[first_word + 1..last_word] {
|
||||
given += w.count_ones();
|
||||
*w = 0;
|
||||
}
|
||||
given += (words[last_word] & hi_mask).count_ones();
|
||||
words[last_word] &= !hi_mask;
|
||||
given
|
||||
}
|
||||
}
|
||||
|
||||
impl HostHeap {
|
||||
pub(crate) fn new(sampler: bool, count: u32) -> Option<Self> {
|
||||
let host = host()?;
|
||||
@@ -2067,6 +2246,13 @@ impl HostHeap {
|
||||
})
|
||||
.flatten();
|
||||
let marks = std::sync::Arc::new(QueueMarks::new(if sampler { 0 } else { count as usize }));
|
||||
// A word per 64 slots only when `tabled_bits` is on; otherwise empty,
|
||||
// so every `put`/`remove`/`has` reaches no word and does nothing.
|
||||
let queue_bits = std::sync::Arc::new(if sampler || !tabled_bits() {
|
||||
Slots::default()
|
||||
} else {
|
||||
Slots::new(count as usize)
|
||||
});
|
||||
let h = HostHeap {
|
||||
id: NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
||||
buffer_sweep: Mutex::default(),
|
||||
@@ -2089,14 +2275,24 @@ impl HostHeap {
|
||||
waiting: Mutex::default(),
|
||||
away: Mutex::default(),
|
||||
kept: (0..count + extra).map(|_| Mutex::new(None)).collect(),
|
||||
next: Mutex::new((0, vec![false; extra as usize])),
|
||||
next: {
|
||||
let mut words = vec![0u64; (extra as usize).div_ceil(64)];
|
||||
let rem = (extra as usize) % 64;
|
||||
if rem != 0
|
||||
&& let Some(last) = words.last_mut()
|
||||
{
|
||||
*last = !0u64 << rem;
|
||||
}
|
||||
Mutex::new((0, words))
|
||||
},
|
||||
free: std::sync::atomic::AtomicU32::new(extra),
|
||||
too_long: std::sync::atomic::AtomicU32::new(u32::MAX),
|
||||
strides,
|
||||
buffers: Slots::new(count as usize),
|
||||
changed: Slots::new(count as usize),
|
||||
textures: Mutex::new(TextureQueue::with_marks(marks.clone())),
|
||||
textures: Mutex::new(TextureQueue::with_marks(marks.clone(), queue_bits.clone())),
|
||||
marks,
|
||||
queue_bits,
|
||||
tabled: (0..if sampler { 0 } else { count })
|
||||
.map(|_| std::sync::atomic::AtomicU32::new(0))
|
||||
.collect(),
|
||||
@@ -2250,7 +2446,17 @@ impl HostHeap {
|
||||
/// Whether the queue holds title slot `index`, by its marks
|
||||
/// ([`QueueMarks`]), without its lock; `None`: ask the queue (the marks
|
||||
/// are not used, or do not reach the slot).
|
||||
///
|
||||
/// With [`tabled_bits`] the dedicated in-queue bit answers instead: it
|
||||
/// is kept in step with the queue's slot map (see [`tabled_bits`]'
|
||||
/// invariant), so a clear bit proves "not queued" even when the marks
|
||||
/// are off. Off by default, so the marks path below is unchanged.
|
||||
fn queued(&self, index: u32) -> Option<bool> {
|
||||
if tabled_bits()
|
||||
&& let Some(set) = self.queue_bits.has(index)
|
||||
{
|
||||
return Some(set);
|
||||
}
|
||||
if !queue_marks() {
|
||||
return None;
|
||||
}
|
||||
@@ -2277,22 +2483,12 @@ impl HostHeap {
|
||||
let cursor = *next as usize;
|
||||
let end = self.dynamic as usize;
|
||||
let second_end = cursor.saturating_add(n.saturating_sub(1)).min(end);
|
||||
let starts = (cursor..end).chain(0..second_end);
|
||||
let mut run = 0;
|
||||
let mut found = None;
|
||||
let mut last = usize::MAX;
|
||||
for at in starts.take(if enough { usize::MAX } else { 0 }) {
|
||||
// A run cannot wrap past the end.
|
||||
if at != last.wrapping_add(1) {
|
||||
run = 0;
|
||||
}
|
||||
last = at;
|
||||
run = if taken[at] { 0 } else { run + 1 };
|
||||
if run == n {
|
||||
found = Some(at + 1 - n);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let found = if enough {
|
||||
find_free_run(taken, cursor, end, n)
|
||||
.or_else(|| find_free_run(taken, 0, second_end, n))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let Some(first) = found else {
|
||||
if enough {
|
||||
self.too_long.fetch_min(n as u32, std::sync::atomic::Ordering::Relaxed);
|
||||
@@ -2309,7 +2505,7 @@ impl HostHeap {
|
||||
};
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::copystat::add(crate::copystat::C::DynamicNs, started.elapsed().as_nanos() as u64);
|
||||
taken[first..first + n].fill(true);
|
||||
set_bits(taken, first, n);
|
||||
self.free.fetch_sub(n as u32, std::sync::atomic::Ordering::Relaxed);
|
||||
*next = ((first + n) % end) as u32;
|
||||
Some(self.count + first as u32)
|
||||
@@ -2349,7 +2545,7 @@ impl HostHeap {
|
||||
/// the lock (the pass asked it slot by slot, under the lock each time);
|
||||
/// and the queue's counts ([`TextureQueue::census`]).
|
||||
pub(crate) fn texture_slots_due_known(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, Vec<Option<Checked>>, [u64; 6]) {
|
||||
let (due, census) = self.queue(super::queue_site::DUE).due_and_census(frame);
|
||||
let (due, census) = self.queue(super::queue_site::DUE).due_and_census_capped(frame, max);
|
||||
let (order, known) = if max == 0 { (Vec::new(), Vec::new()) } else { due.ordered(max) };
|
||||
(order, known, census)
|
||||
}
|
||||
@@ -3507,12 +3703,12 @@ impl HostHeap {
|
||||
return;
|
||||
};
|
||||
let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let start = at as usize;
|
||||
let end = (at + n).min(self.dynamic) as usize;
|
||||
if let Some(slots) = guard.1.get_mut(at as usize..end) {
|
||||
let given = slots.iter().filter(|taken| **taken).count() as u32;
|
||||
if start < end {
|
||||
let given = clear_and_count_bits(&mut guard.1, start, end);
|
||||
self.free.fetch_add(given, std::sync::atomic::Ordering::Relaxed);
|
||||
self.too_long.store(u32::MAX, std::sync::atomic::Ordering::Relaxed);
|
||||
slots.fill(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3530,59 +3726,180 @@ impl HostHeap {
|
||||
}
|
||||
|
||||
/// Makes slot `index` (a dynamic one) the view the record `words` names,
|
||||
/// from this thread's descriptor of it if the recording `recording` has
|
||||
/// made one, else as [`HostHeap::make_at`] does, and keeps that
|
||||
/// ([`ListViews`]). What is known of the record in this recording;
|
||||
/// `None` (the slot is not made): not a view kept so.
|
||||
/// from this thread's descriptor of it if this frame's cache has made one,
|
||||
/// else as [`HostHeap::make_at`] does, and keeps that ([`ListViews`]).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn make_listed(&self, recording: u64, words: [u32; 3], index: u32) -> Option<Listed> {
|
||||
if self.sampler {
|
||||
return None;
|
||||
}
|
||||
let epoch = LIST_VIEWS_GEN.load(std::sync::atomic::Ordering::Acquire);
|
||||
LIST_VIEWS.with(|views| {
|
||||
let mut views = views.borrow_mut();
|
||||
if views.is_none() {
|
||||
*views = Some(ListViews::new()?);
|
||||
}
|
||||
let views = views.as_mut()?;
|
||||
if views.recording != recording {
|
||||
views.recording = recording;
|
||||
views.made.clear();
|
||||
}
|
||||
views.prepare(recording, epoch);
|
||||
let twins = self.twins.get(index as usize).is_some();
|
||||
if !views.made.contains_key(&words) {
|
||||
let view = super::view_at(words[1], words[2])?;
|
||||
let at = 2 * views.made.len() as u32;
|
||||
// (A constant buffer's bytes are copied for each draw.)
|
||||
if at >= ListViews::SLOTS || matches!(view, View::Constant(..)) {
|
||||
return None;
|
||||
}
|
||||
let twin = twinned(&view);
|
||||
let kept = make_twinned(&view, views.slot(at), Some(views.slot(at + 1)))?;
|
||||
let stride_word = view_stride_word(&view);
|
||||
let listed = Listed {
|
||||
kind: crate::draw::view_kind(&view),
|
||||
texture: is_texture_view(&view),
|
||||
ready: (0, 0, false),
|
||||
tabled: None,
|
||||
};
|
||||
views.made.insert(words, ListView { view, at, twin, stride_word, kept, listed });
|
||||
}
|
||||
let made = &views.made[&words];
|
||||
self.copy_from(index, views.slot(made.at));
|
||||
if made.twin && twins {
|
||||
self.copy_from(self.raw + index, views.slot(made.at + 1));
|
||||
let (at, twin, stride_word, listed) = {
|
||||
let made = views.get_or_make(recording, words)?;
|
||||
self.keep_ref(index, made.kept.as_ref());
|
||||
(made.at, made.twin, made.stride_word, made.listed)
|
||||
};
|
||||
self.copy_from(index, views.slot(at));
|
||||
if twin && twins {
|
||||
self.copy_from(self.raw + index, views.slot(at + 1));
|
||||
self.twins[index as usize].store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
} else {
|
||||
self.clear_twin(index);
|
||||
}
|
||||
self.write_stride(index, made.stride_word);
|
||||
self.keep(index, made.kept.clone());
|
||||
Some(made.listed)
|
||||
self.write_stride(index, stride_word);
|
||||
Some(listed)
|
||||
})
|
||||
}
|
||||
|
||||
/// Batched version of [`HostHeap::make_listed`] for a whole descriptor
|
||||
/// table `[first .. first + n)`: acquires the thread-local [`ListViews`]
|
||||
/// once per table and emits one `ID3D12Device::CopyDescriptors` call per
|
||||
/// contiguous run of listed slots instead of one COM call per slot.
|
||||
pub(crate) fn make_listed_batch(
|
||||
&self,
|
||||
recording: u64,
|
||||
first: u32,
|
||||
table: u64,
|
||||
n: u32,
|
||||
out: &mut Vec<Option<([u32; 3], Listed)>>,
|
||||
) {
|
||||
out.clear();
|
||||
let count = n as usize;
|
||||
if self.sampler || count == 0 {
|
||||
out.resize(count, None);
|
||||
return;
|
||||
}
|
||||
let Some(host) = host() else {
|
||||
out.resize(count, None);
|
||||
return;
|
||||
};
|
||||
let epoch = LIST_VIEWS_GEN.load(std::sync::atomic::Ordering::Acquire);
|
||||
let has_twins = !self.twins.is_empty();
|
||||
LIST_VIEWS.with(|views| {
|
||||
let mut views = views.borrow_mut();
|
||||
if views.is_none() {
|
||||
*views = ListViews::new();
|
||||
}
|
||||
let Some(views) = views.as_mut() else {
|
||||
out.resize(count, None);
|
||||
return;
|
||||
};
|
||||
views.prepare(recording, epoch);
|
||||
|
||||
const BATCH: usize = 64;
|
||||
let mut run_dst_start = 0u32;
|
||||
let mut run_len = 0usize;
|
||||
let mut srcs = [D3D12_CPU_DESCRIPTOR_HANDLE::default(); BATCH];
|
||||
let mut twin_dst_start = 0u32;
|
||||
let mut twin_len = 0usize;
|
||||
let mut twin_srcs = [D3D12_CPU_DESCRIPTOR_HANDLE::default(); BATCH];
|
||||
|
||||
let flush_main = |dst_start: u32, len: usize, buf: &[D3D12_CPU_DESCRIPTOR_HANDLE; BATCH]| {
|
||||
if len == 0 {
|
||||
return;
|
||||
}
|
||||
let dst = self.cpu(dst_start);
|
||||
let dst_len = len as u32;
|
||||
// SAFETY: `dst..dst+len` lies inside this host heap and each `buf[..len]`
|
||||
// is a valid non-shader-visible CPU descriptor in `ListViews`.
|
||||
unsafe {
|
||||
if len == 1 {
|
||||
host.device.CopyDescriptorsSimple(
|
||||
1,
|
||||
dst,
|
||||
buf[0],
|
||||
D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
|
||||
);
|
||||
} else {
|
||||
host.device.CopyDescriptors(
|
||||
1,
|
||||
&dst,
|
||||
Some(&dst_len),
|
||||
dst_len,
|
||||
buf.as_ptr(),
|
||||
None,
|
||||
D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
for k in 0..n {
|
||||
let index = first + k;
|
||||
let Some(words) = super::record_at(table + u64::from(k) * 32) else {
|
||||
if run_len > 0 {
|
||||
flush_main(run_dst_start, run_len, &srcs);
|
||||
run_len = 0;
|
||||
}
|
||||
out.push(None);
|
||||
continue;
|
||||
};
|
||||
let Some(m) = views.get_or_make(recording, words) else {
|
||||
if run_len > 0 {
|
||||
flush_main(run_dst_start, run_len, &srcs);
|
||||
run_len = 0;
|
||||
}
|
||||
out.push(None);
|
||||
continue;
|
||||
};
|
||||
let (at, twin, stride_word, listed) = (m.at, m.twin, m.stride_word, m.listed);
|
||||
self.keep_ref(index, m.kept.as_ref());
|
||||
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if let Some(written) = self.written.get(index as usize) {
|
||||
written.store(crate::host::coarse_ms() as u32, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
if run_len == 0 {
|
||||
run_dst_start = index;
|
||||
} else if run_dst_start + run_len as u32 != index || run_len == BATCH {
|
||||
flush_main(run_dst_start, run_len, &srcs);
|
||||
run_dst_start = index;
|
||||
run_len = 0;
|
||||
}
|
||||
srcs[run_len] = views.slot(at);
|
||||
run_len += 1;
|
||||
|
||||
if twin && has_twins && (index as usize) < self.twins.len() {
|
||||
let twin_dst = self.raw + index;
|
||||
if twin_len == 0 {
|
||||
twin_dst_start = twin_dst;
|
||||
} else if twin_dst_start + twin_len as u32 != twin_dst || twin_len == BATCH {
|
||||
flush_main(twin_dst_start, twin_len, &twin_srcs);
|
||||
twin_dst_start = twin_dst;
|
||||
twin_len = 0;
|
||||
}
|
||||
twin_srcs[twin_len] = views.slot(at + 1);
|
||||
twin_len += 1;
|
||||
self.twins[index as usize].store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
} else if has_twins {
|
||||
self.clear_twin(index);
|
||||
}
|
||||
|
||||
self.write_stride(index, stride_word);
|
||||
out.push(Some((words, listed)));
|
||||
}
|
||||
|
||||
if run_len > 0 {
|
||||
flush_main(run_dst_start, run_len, &srcs);
|
||||
}
|
||||
if twin_len > 0 {
|
||||
flush_main(twin_dst_start, twin_len, &twin_srcs);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// As [`HostHeap::copy_to`], from the slot `from`, which the card does not
|
||||
/// see.
|
||||
#[cfg(test)]
|
||||
fn copy_from(&self, to: u32, from: D3D12_CPU_DESCRIPTOR_HANDLE) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if let Some(written) = self.written.get(to as usize) {
|
||||
@@ -3650,7 +3967,32 @@ impl HostHeap {
|
||||
// A running submission may still read the old resource through
|
||||
// this slot.
|
||||
if let Some(old) = old {
|
||||
crate::host::retire_resource(old);
|
||||
if index < self.count {
|
||||
crate::host::retire_resource(old);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reference-taking variant of [`HostHeap::keep`] that avoids COM `AddRef`/`Release`
|
||||
/// when `self.kept[index]` already holds the same `ID3D12Resource`, and drops
|
||||
/// displaced dynamic-slot resources directly (dynamic slots are only reused after
|
||||
/// their previous flight finished on the GPU).
|
||||
fn keep_ref(&self, index: u32, resource: Option<&ID3D12Resource>) {
|
||||
let Some(slot) = self.kept.get(index as usize) else {
|
||||
return;
|
||||
};
|
||||
let old = {
|
||||
use windows::core::Interface;
|
||||
let mut slot = slot.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if slot.as_ref().map(Interface::as_raw) == resource.map(Interface::as_raw) {
|
||||
return;
|
||||
}
|
||||
std::mem::replace(&mut *slot, resource.cloned())
|
||||
};
|
||||
if let Some(old) = old {
|
||||
if index < self.count {
|
||||
crate::host::retire_resource(old);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6781,7 +7123,7 @@ mod tests {
|
||||
#[test]
|
||||
fn the_texture_queue_marks_what_it_holds() {
|
||||
let marks = std::sync::Arc::new(QueueMarks::new(32));
|
||||
let mut q = TextureQueue::with_marks(marks.clone());
|
||||
let mut q = TextureQueue::with_marks(marks.clone(), std::sync::Arc::new(Slots::new(32)));
|
||||
let write = |q: &TextureQueue, index: u32| q.due(u64::MAX, 100).iter().find(|d| d.0 == index).unwrap().1;
|
||||
q.written(1, 1, 0, false);
|
||||
q.written(2, 1, 0, false);
|
||||
@@ -6968,20 +7310,24 @@ struct ListView {
|
||||
stride_word: u32,
|
||||
kept: Kept,
|
||||
listed: Listed,
|
||||
/// Recording id that last populated `listed.ready` / `listed.tabled`.
|
||||
made_recording: u64,
|
||||
}
|
||||
|
||||
/// Global generation bumped whenever a live texture/buffer changes its
|
||||
/// underlying host `ID3D12Resource` mid-frame (`slot_evict`, `want_level`, etc.).
|
||||
static LIST_VIEWS_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
/// Invalidates thread-local [`ListViews`] caches when a live host resource is replaced.
|
||||
pub(crate) fn invalidate_list_views() {
|
||||
LIST_VIEWS_GEN.fetch_add(1, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
|
||||
/// The descriptors a thread made for one recording of a list, by the record
|
||||
/// they were made from, in a heap the card does not see.
|
||||
///
|
||||
/// The title's culling and lighting dispatches each bind a table of their own
|
||||
/// that differs in one constant buffer, and the same thirty views beside it:
|
||||
/// each was found, checked, made and brought up to date anew for every
|
||||
/// dispatch, some 2,500 indirect dispatches in the one recording job the
|
||||
/// frame waits for last (timeline waits-2: 24 of 65 ms). Here a list makes a
|
||||
/// view once, as it makes a table once (`crate::draw::State::tables`), and
|
||||
/// copies its descriptor.
|
||||
struct ListViews {
|
||||
recording: u64,
|
||||
epoch: u64,
|
||||
heap: ID3D12DescriptorHeap,
|
||||
step: usize,
|
||||
start: usize,
|
||||
@@ -7005,7 +7351,59 @@ impl ListViews {
|
||||
.ok()?;
|
||||
let step = host.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize;
|
||||
let start = heap.GetCPUDescriptorHandleForHeapStart().ptr;
|
||||
Some(ListViews { recording: 0, heap, step, start, made: Default::default() })
|
||||
Some(ListViews { recording: 0, epoch: u64::MAX, heap, step, start, made: Default::default() })
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare(&mut self, recording: u64, epoch: u64) {
|
||||
if self.recording != recording || self.epoch != epoch || self.made.len() >= (Self::SLOTS as usize / 2).saturating_sub(64) {
|
||||
self.recording = recording;
|
||||
self.epoch = epoch;
|
||||
self.made.clear();
|
||||
}
|
||||
}
|
||||
|
||||
fn get_or_make(&mut self, recording: u64, words: [u32; 3]) -> Option<&mut ListView> {
|
||||
use std::collections::hash_map::Entry;
|
||||
let slot_count = self.made.len() as u32;
|
||||
let (start, step) = (self.start, self.step);
|
||||
match self.made.entry(words) {
|
||||
Entry::Occupied(entry) => {
|
||||
let entry = entry.into_mut();
|
||||
if entry.made_recording != recording {
|
||||
entry.made_recording = recording;
|
||||
entry.listed.ready = (0, 0, false);
|
||||
entry.listed.tabled = None;
|
||||
}
|
||||
Some(entry)
|
||||
}
|
||||
Entry::Vacant(vacant) => {
|
||||
let view = super::view_at(words[1], words[2])?;
|
||||
let at = 2 * slot_count;
|
||||
// (A constant buffer's bytes are copied for each draw.)
|
||||
if at >= Self::SLOTS || matches!(view, View::Constant(..)) {
|
||||
return None;
|
||||
}
|
||||
let slot_at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start + i as usize * step };
|
||||
let twin = twinned(&view);
|
||||
let kept = make_twinned(&view, slot_at(at), Some(slot_at(at + 1)))?;
|
||||
let stride_word = view_stride_word(&view);
|
||||
let listed = Listed {
|
||||
kind: crate::draw::view_kind(&view),
|
||||
texture: is_texture_view(&view),
|
||||
ready: (0, 0, false),
|
||||
tabled: None,
|
||||
};
|
||||
Some(vacant.insert(ListView {
|
||||
view,
|
||||
at,
|
||||
twin,
|
||||
stride_word,
|
||||
kept,
|
||||
listed,
|
||||
made_recording: recording,
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7023,16 +7421,17 @@ thread_local! {
|
||||
pub(crate) fn listed_view(recording: u64, words: [u32; 3]) -> Option<View> {
|
||||
LIST_VIEWS.with(|views| {
|
||||
let views = views.borrow();
|
||||
let views = views.as_ref().filter(|v| v.recording == recording)?;
|
||||
views.made.get(&words).map(|m| m.view.clone())
|
||||
let views = views.as_ref()?;
|
||||
views.made.get(&words).filter(|m| m.made_recording == recording).map(|m| m.view.clone())
|
||||
})
|
||||
}
|
||||
|
||||
/// Notes what is known of the record `words` in `recording`.
|
||||
pub(crate) fn note_listed(recording: u64, words: [u32; 3], listed: Listed) {
|
||||
LIST_VIEWS.with(|views| {
|
||||
if let Some(views) = views.borrow_mut().as_mut().filter(|v| v.recording == recording)
|
||||
if let Some(views) = views.borrow_mut().as_mut()
|
||||
&& let Some(made) = views.made.get_mut(&words)
|
||||
&& made.made_recording == recording
|
||||
{
|
||||
made.listed = listed;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
//! Per-present dip recorder (diagnostics only). For each present slower than
|
||||
//! the dip threshold it logs one row carrying the five signals that tell the
|
||||
//! five dip causes apart, so a slow frame can be attributed to its dominant
|
||||
//! cause without any behaviour change: the whole module is compiled only
|
||||
//! under the `diagnostics` feature and is never reached in a release build.
|
||||
//!
|
||||
//! The five discriminating signals, read cheaply at the present:
|
||||
//! - being-made host pipelines (`crate::pipeline::making`): a pipeline /
|
||||
//! late-shader-compile transient shows as a non-zero gauge.
|
||||
//! - the process hard page-fault delta since the previous present (from
|
||||
//! `PROCESS_MEMORY_COUNTERS.PageFaultCount`), with the last-sampled
|
||||
//! available physical RAM for context: a paging stall shows as a
|
||||
//! fault burst while free RAM is low.
|
||||
//! - the committed private-bytes delta (`PagefileUsage`): a host alloc /
|
||||
//! free burst shows as a large swing without the other signals.
|
||||
//! - the idle-sweep delta (`crate::resource::SWEPT_US`: look count, total
|
||||
//! microseconds, longest one): a trim / eviction spike landing on the
|
||||
//! frame shows here.
|
||||
//! - the preparing and card-wait deltas (`SUBMISSION_US`): a card-merge /
|
||||
//! relay / settle wait shows as a preparing or GPU-wait jump with no
|
||||
//! fault, no sweep, and the being-made gauge at zero.
|
||||
//!
|
||||
//! A fixed ring of the most recent presents also keeps (frame_ms, being_made)
|
||||
//! so the steady-window floor (min / 1%-low fps, median / mean ms over the
|
||||
//! 0-being-made frames) can be summarised from the same source.
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
/// The slow-frame threshold in milliseconds (`VICTORY_DIP_MS`, default 120).
|
||||
pub(crate) fn dip_ms() -> f64 {
|
||||
static MS: OnceLock<f64> = OnceLock::new();
|
||||
*MS.get_or_init(|| {
|
||||
std::env::var("VICTORY_DIP_MS")
|
||||
.ok()
|
||||
.and_then(|s| s.trim().parse::<f64>().ok())
|
||||
.filter(|v| *v > 0.0)
|
||||
.unwrap_or(120.0)
|
||||
})
|
||||
}
|
||||
|
||||
/// Previous-present cumulative readings, so each present logs deltas. All
|
||||
/// start at 0; the first present seeds them and is not itself attributed
|
||||
/// (its deltas would be meaningless against a zero baseline).
|
||||
static PREV_FAULTS: AtomicU64 = AtomicU64::new(0);
|
||||
static PREV_PRIVATE: AtomicU64 = AtomicU64::new(0);
|
||||
static PREV_SWEEP_LOOKS: AtomicU64 = AtomicU64::new(0);
|
||||
static PREV_SWEEP_US: AtomicU64 = AtomicU64::new(0);
|
||||
static PREV_PREPARE_US: AtomicU64 = AtomicU64::new(0);
|
||||
static PREV_GPUWAIT_US: AtomicU64 = AtomicU64::new(0);
|
||||
static PREV_PIPEWAIT_US: AtomicU64 = AtomicU64::new(0);
|
||||
static FRAME_INDEX: AtomicU64 = AtomicU64::new(0);
|
||||
static SEEDED: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// How many recent presents the steady-window ring keeps.
|
||||
const RING: usize = 4096;
|
||||
|
||||
/// One present's summary for the steady-window floor.
|
||||
struct Row {
|
||||
frame_ms: f32,
|
||||
being_made: u64,
|
||||
}
|
||||
|
||||
fn ring() -> &'static Mutex<Vec<Row>> {
|
||||
static R: OnceLock<Mutex<Vec<Row>>> = OnceLock::new();
|
||||
R.get_or_init(|| Mutex::new(Vec::with_capacity(RING)))
|
||||
}
|
||||
|
||||
/// The process hard page-fault count and committed private bytes, from one
|
||||
/// `K32GetProcessMemoryInfo` call (the same call `host::private_bytes` uses).
|
||||
fn process_faults_and_private() -> (u64, u64) {
|
||||
use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
|
||||
use windows_sys::Win32::System::Threading::GetCurrentProcess;
|
||||
let mut c = PROCESS_MEMORY_COUNTERS {
|
||||
cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: our own process and a sized structure.
|
||||
unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
|
||||
(u64::from(c.PageFaultCount), c.PagefileUsage as u64)
|
||||
}
|
||||
|
||||
/// Called once per present with the just-measured inter-present interval and
|
||||
/// the being-made gauge. Logs one attribution row when the frame is slower
|
||||
/// than the dip threshold; always pushes into the steady-window ring.
|
||||
pub(crate) fn present(frame_ms: f32, being_made: u64) {
|
||||
let index = FRAME_INDEX.fetch_add(1, Relaxed);
|
||||
|
||||
let (faults, private) = process_faults_and_private();
|
||||
let [prepare_us, gpuwait_us] = crate::host::submission_us_now();
|
||||
let sweep_looks = crate::resource::SWEPT_US[0].load(Relaxed);
|
||||
let sweep_us = crate::resource::SWEPT_US[1].load(Relaxed);
|
||||
let pipewait_us = crate::copystat::peek(crate::copystat::C::PipelineWaitUs);
|
||||
|
||||
let prev_faults = PREV_FAULTS.swap(faults, Relaxed);
|
||||
let prev_private = PREV_PRIVATE.swap(private, Relaxed);
|
||||
let prev_sweep_looks = PREV_SWEEP_LOOKS.swap(sweep_looks, Relaxed);
|
||||
let prev_sweep_us = PREV_SWEEP_US.swap(sweep_us, Relaxed);
|
||||
let prev_prepare_us = PREV_PREPARE_US.swap(prepare_us, Relaxed);
|
||||
let prev_gpuwait_us = PREV_GPUWAIT_US.swap(gpuwait_us, Relaxed);
|
||||
let prev_pipewait_us = PREV_PIPEWAIT_US.swap(pipewait_us, Relaxed);
|
||||
|
||||
{
|
||||
let mut r = ring().lock().unwrap();
|
||||
if r.len() == RING {
|
||||
r.remove(0);
|
||||
}
|
||||
r.push(Row { frame_ms, being_made });
|
||||
}
|
||||
|
||||
// The first present only seeds the previous-reading cells.
|
||||
if SEEDED.swap(1, Relaxed) == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
if f64::from(frame_ms) <= dip_ms() {
|
||||
return;
|
||||
}
|
||||
|
||||
let hard_fault_delta = faults.saturating_sub(prev_faults);
|
||||
let private_mib = private >> 20;
|
||||
let private_delta_mib = (private as i64 - prev_private as i64) / (1 << 20);
|
||||
let sweep_looks_delta = sweep_looks.saturating_sub(prev_sweep_looks);
|
||||
let sweep_ms_delta = sweep_us.saturating_sub(prev_sweep_us) as f64 / 1000.0;
|
||||
let prepare_ms_delta = prepare_us.saturating_sub(prev_prepare_us) as f64 / 1000.0;
|
||||
let gpuwait_ms_delta = gpuwait_us.saturating_sub(prev_gpuwait_us) as f64 / 1000.0;
|
||||
let pipewait_ms_delta = pipewait_us.saturating_sub(prev_pipewait_us) as f64 / 1000.0;
|
||||
let avail_mib = crate::residency::avail_phys_mib();
|
||||
|
||||
tracing::info!(
|
||||
target: "victory_gpu::dip",
|
||||
frame = index,
|
||||
frame_ms = frame_ms,
|
||||
being_made,
|
||||
hard_fault_delta,
|
||||
avail_mib,
|
||||
private_mib,
|
||||
private_delta_mib,
|
||||
sweep_looks_delta,
|
||||
sweep_ms_delta,
|
||||
prepare_ms_delta,
|
||||
gpuwait_ms_delta,
|
||||
pipewait_ms_delta,
|
||||
"slow present"
|
||||
);
|
||||
}
|
||||
|
||||
/// Over the steady-window ring, restricted to the frames the title made with
|
||||
/// nothing being compiled (`being_made == 0`), the floor: min fps, 1%-low
|
||||
/// fps, median ms and mean ms. Returned as one formatted line. Available for
|
||||
/// an on-demand summary; the run also reconstructs the floor from the logged
|
||||
/// dip rows and the frame-rate lines, so this may be unused in a given build.
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn steady_summary() -> String {
|
||||
let r = ring().lock().unwrap();
|
||||
let mut steady: Vec<f32> = r
|
||||
.iter()
|
||||
.filter(|row| row.being_made == 0)
|
||||
.map(|row| row.frame_ms)
|
||||
.collect();
|
||||
let n = steady.len();
|
||||
if n == 0 {
|
||||
return "steady window: no 0-being-made frames".to_string();
|
||||
}
|
||||
steady.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
||||
let worst_ms = steady[n - 1];
|
||||
let median_ms = steady[n / 2];
|
||||
let mean_ms = steady.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
|
||||
// The 1%-low frame time is the 99th-percentile slow frame; its fps is the
|
||||
// conventional 1%-low floor.
|
||||
let p99_idx = ((n as f64) * 0.99).ceil() as usize;
|
||||
let p99_ms = steady[p99_idx.min(n - 1)];
|
||||
let min_fps = 1000.0 / f64::from(worst_ms);
|
||||
let low1_fps = 1000.0 / f64::from(p99_ms);
|
||||
let median_fps = 1000.0 / f64::from(median_ms);
|
||||
let mean_fps = 1000.0 / mean_ms;
|
||||
format!(
|
||||
"steady window (0 being made): frames={n} min_fps={min_fps:.2} \
|
||||
1pct_low_fps={low1_fps:.2} median_fps={median_fps:.2} median_ms={median_ms:.1} \
|
||||
mean_fps={mean_fps:.2} mean_ms={mean_ms:.1} worst_ms={worst_ms:.1}"
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn push(frame_ms: f32, being_made: u64) {
|
||||
let mut r = ring().lock().unwrap();
|
||||
r.push(Row { frame_ms, being_made });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steady_summary_uses_only_zero_being_made_frames() {
|
||||
ring().lock().unwrap().clear();
|
||||
// Three steady frames at 100/120/140 ms and one compile frame at
|
||||
// 500 ms that must be excluded from the floor.
|
||||
push(100.0, 0);
|
||||
push(120.0, 0);
|
||||
push(140.0, 0);
|
||||
push(500.0, 3);
|
||||
let s = steady_summary();
|
||||
assert!(s.contains("frames=3"), "{s}");
|
||||
// Worst steady frame is 140 ms -> min fps ~= 7.14.
|
||||
assert!(s.contains("min_fps=7.1"), "{s}");
|
||||
// Median of 100/120/140 is 120 ms.
|
||||
assert!(s.contains("median_ms=120.0"), "{s}");
|
||||
ring().lock().unwrap().clear();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steady_summary_empty_when_all_being_made() {
|
||||
ring().lock().unwrap().clear();
|
||||
push(300.0, 2);
|
||||
assert!(steady_summary().contains("no 0-being-made frames"));
|
||||
ring().lock().unwrap().clear();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dip_ms_defaults_to_120() {
|
||||
// With VICTORY_DIP_MS unset in the test process the default holds.
|
||||
assert_eq!(dip_ms(), 120.0);
|
||||
}
|
||||
}
|
||||
+202
-38
@@ -1433,8 +1433,44 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho
|
||||
|
||||
impl State {
|
||||
pub(crate) fn reset(&mut self, pipeline: This) {
|
||||
*self = State::default();
|
||||
for (heap, id, first, n) in self.dynamic.drain(..) {
|
||||
crate::descriptor::release_dynamic(heap, id, first, n);
|
||||
}
|
||||
self.pipeline = pipeline as usize;
|
||||
self.heaps = [0; 2];
|
||||
self.graphics.clear();
|
||||
self.compute.clear();
|
||||
self.vertex = Default::default();
|
||||
self.index = IndexView::default();
|
||||
self.targets.clear();
|
||||
self.depth = 0;
|
||||
self.depth_state = 0;
|
||||
self.topology = 0;
|
||||
self.topology_set = false;
|
||||
self.target_handles.clear();
|
||||
self.depth_handle = 0;
|
||||
self.targets_set = false;
|
||||
self.host_targets = None;
|
||||
self.viewports.clear();
|
||||
self.scissors.clear();
|
||||
self.blend = None;
|
||||
self.stencil = None;
|
||||
self.depth_bounds = None;
|
||||
self.window = None;
|
||||
self.batch = None;
|
||||
#[cfg(feature = "diagnostics")]
|
||||
self.user.clear();
|
||||
self.ambient_tables.clear();
|
||||
self.host_pipeline = 0;
|
||||
self.host_roots = [0; 2];
|
||||
self.host_heaps = [0; 2];
|
||||
self.host_heaps_set = false;
|
||||
self.fresh_tables.clear();
|
||||
self.root_srv_slots.clear();
|
||||
self.root_uav_slots.clear();
|
||||
self.tables_gone = false;
|
||||
self.recording = 0;
|
||||
self.rebinds = [0; 2];
|
||||
}
|
||||
|
||||
/// The title's topology; console-only ones become host lists (see
|
||||
@@ -1617,17 +1653,33 @@ impl State {
|
||||
return;
|
||||
}
|
||||
self.host_targets = Some(now);
|
||||
let rtvs: Vec<_> = views.iter().map(|(texture, desc)| host.rtv(*texture, desc.as_ref())).collect();
|
||||
let dsv = dsv.map(|(texture, record)| host.dsv(texture, record.depth_desc().as_ref()));
|
||||
// SAFETY: an open list; the views were just made.
|
||||
unsafe {
|
||||
list.list.OMSetRenderTargets(
|
||||
rtvs.len() as u32,
|
||||
(!rtvs.is_empty()).then_some(rtvs.as_ptr()),
|
||||
false,
|
||||
dsv.as_ref().map(std::ptr::from_ref),
|
||||
)
|
||||
};
|
||||
if views.len() <= 8 {
|
||||
let mut rtvs = [D3D12_CPU_DESCRIPTOR_HANDLE::default(); 8];
|
||||
for (dst, &(texture, ref desc)) in rtvs.iter_mut().zip(views.iter()) {
|
||||
*dst = host.rtv(texture, desc.as_ref());
|
||||
}
|
||||
// SAFETY: an open list; the views were just made.
|
||||
unsafe {
|
||||
list.list.OMSetRenderTargets(
|
||||
views.len() as u32,
|
||||
(!views.is_empty()).then_some(rtvs.as_ptr()),
|
||||
false,
|
||||
dsv.as_ref().map(std::ptr::from_ref),
|
||||
)
|
||||
};
|
||||
} else {
|
||||
let rtvs: Vec<_> = views.iter().map(|(texture, desc)| host.rtv(*texture, desc.as_ref())).collect();
|
||||
// SAFETY: an open list; the views were just made.
|
||||
unsafe {
|
||||
list.list.OMSetRenderTargets(
|
||||
rtvs.len() as u32,
|
||||
(!rtvs.is_empty()).then_some(rtvs.as_ptr()),
|
||||
false,
|
||||
dsv.as_ref().map(std::ptr::from_ref),
|
||||
)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Viewports, scissors, the blend factor and the stencil reference: set
|
||||
@@ -2310,9 +2362,7 @@ impl State {
|
||||
let len = s.left(a).min(limit);
|
||||
s.refresh(list, a, len);
|
||||
if writes {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::host::wide_write(a, len, self.pipeline);
|
||||
s.gpu_writes(list, a, len);
|
||||
s.shader_writes(list, a, len, self.pipeline);
|
||||
}
|
||||
};
|
||||
if !crate::pipeline::host::bounded_root_srvs() {
|
||||
@@ -2349,7 +2399,7 @@ impl State {
|
||||
None => {
|
||||
let shadow = address.and_then(|a| find(a).map(|s| (a, s)));
|
||||
let Some(index) = host.dynamic(1).or_else(|| {
|
||||
crate::host::settle_for_fence();
|
||||
crate::host::reclaim_dynamic();
|
||||
host.dynamic(1)
|
||||
}) else {
|
||||
return false;
|
||||
@@ -2423,7 +2473,7 @@ impl State {
|
||||
None => {
|
||||
let shadow = address.and_then(|a| crate::shadow::find(a, 1).map(|s| (a, s)));
|
||||
let Some(index) = host.dynamic(1).or_else(|| {
|
||||
crate::host::settle_for_fence();
|
||||
crate::host::reclaim_dynamic();
|
||||
host.dynamic(1)
|
||||
}) else {
|
||||
return false;
|
||||
@@ -3187,6 +3237,25 @@ impl State {
|
||||
if FRAME.swap(frame, Ordering::Relaxed) != frame {
|
||||
SPENT.store(0, Ordering::Relaxed);
|
||||
}
|
||||
let baking = crate::texture::BAKING.get();
|
||||
let required = PASS_BUDGET.get().is_some_and(|(_, _, bake)| bake);
|
||||
let frame_pass = !required && !baking && sync.is_none();
|
||||
// If an earlier pass in this same frame already exhausted the
|
||||
// `VICTORY_TEXSPK_PASS_MS` budget, still flip any newly-completed
|
||||
// texture uploads visible, then bail before taking the global
|
||||
// texture-queue lock and scanning tens of thousands of slots for a
|
||||
// loop that would immediately time out on iteration 0.
|
||||
if frame_pass
|
||||
&& let Some(cap) = texspk_pass_ms()
|
||||
&& PASS_FRAME.load(Ordering::Relaxed) == frame
|
||||
&& PASS_FRAME_NANOS.load(Ordering::Relaxed) >= cap.saturating_mul(1_000_000)
|
||||
{
|
||||
before(1, || {
|
||||
host.texture_views_remade();
|
||||
host.texture_slots_flip();
|
||||
});
|
||||
return false;
|
||||
}
|
||||
// No more of them are made while the card has no room
|
||||
// (`resource::room`): by what is alive now, not by what was ever
|
||||
// staged (4 GB in all, after which later textures stayed empty for
|
||||
@@ -3203,9 +3272,21 @@ impl State {
|
||||
if !room {
|
||||
HEAP_TEXTURES_FULL.fetch_add(1, Ordering::Relaxed);
|
||||
once!("textures picked by index: the card has no room for more; they wait");
|
||||
// When the card is full and this is a normal frame/early pass, still
|
||||
// flip completed uploads immediately, but rate-limit full-card queue
|
||||
// scans to once per frame so `self.textures` does not stall workers.
|
||||
if frame_pass {
|
||||
static LAST_FULL_FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
|
||||
if LAST_FULL_FRAME.swap(frame, Ordering::Relaxed) == frame {
|
||||
before(1, || {
|
||||
host.texture_views_remade();
|
||||
host.texture_slots_flip();
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut refused = 0;
|
||||
let baking = crate::texture::BAKING.get();
|
||||
before(0, || {
|
||||
// Room again: the slots held back while the card was full are
|
||||
// due now (`full_card_pass`).
|
||||
@@ -3233,10 +3314,15 @@ impl State {
|
||||
if room {
|
||||
before(0, || host.texture_slots_waiting(frame));
|
||||
}
|
||||
let required = PASS_BUDGET.get().is_some_and(|(_, _, bake)| bake);
|
||||
// (And what the queue knew of each, `known`: see `Tells`.)
|
||||
let (mut due, mut known, census) =
|
||||
before(2, || host.texture_slots_due_known(frame, if baking { 1 << 16 } else { 4096 }));
|
||||
let due_cap = if baking {
|
||||
if room { 1 << 16 } else { 4096 }
|
||||
} else if !room && !required {
|
||||
128
|
||||
} else {
|
||||
4096
|
||||
};
|
||||
let (mut due, mut known, census) = before(2, || host.texture_slots_due_known(frame, due_cap));
|
||||
// (Those that are due later after all that are due.)
|
||||
let on_time = due.len();
|
||||
if baking {
|
||||
@@ -3322,7 +3408,6 @@ impl State {
|
||||
// A frame's runs of the pass (its own and the early ones, not those
|
||||
// before a bake) within `VICTORY_TEXSPK_PASS_MS` together
|
||||
// ([`texspk_pass_ms`]).
|
||||
let frame_pass = !required && !baking && sync.is_none();
|
||||
let span = match texspk_pass_ms() {
|
||||
Some(cap) if frame_pass => {
|
||||
if PASS_FRAME.swap(frame, Ordering::Relaxed) != frame {
|
||||
@@ -3489,10 +3574,11 @@ impl State {
|
||||
outcome(slot_outcome::HELD);
|
||||
if full_card_pass() {
|
||||
// Held back for the frames of about four seconds
|
||||
// (`most`), or until the card has room; the pass
|
||||
// goes on, within a count that bounds one pass.
|
||||
// (`most`), or until the card has room; cap refusals
|
||||
// per pass at 256 so full-card cutscenes do not thrash
|
||||
// thousands of held-slot tells under the queue lock.
|
||||
tells.tell(index, write, Told::Held(frame + most));
|
||||
if refused > 1024 {
|
||||
if refused > 256 {
|
||||
break;
|
||||
}
|
||||
} else if refused > 256 {
|
||||
@@ -3846,6 +3932,9 @@ impl State {
|
||||
once!("a dispatch with a graphics pipeline");
|
||||
return;
|
||||
}
|
||||
if self.sky_miss_left_out(p) {
|
||||
return;
|
||||
}
|
||||
if !self.bind(list, p, true) {
|
||||
DROPPED.fetch_add(1, Ordering::Relaxed);
|
||||
// A stage of the structure builder that cannot be bound is a
|
||||
@@ -3882,6 +3971,7 @@ impl State {
|
||||
// SAFETY: an open list with everything set.
|
||||
unsafe { list.list.Dispatch(x, y, z) };
|
||||
self.buffers_written();
|
||||
self.planes_now(list);
|
||||
DISPATCHED.fetch_add(1, Ordering::Relaxed);
|
||||
if let Some(role) = p.stages.first().and_then(|s| s.shader.ambient)
|
||||
&& crate::ambient::on()
|
||||
@@ -3892,6 +3982,38 @@ impl State {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which surfaces a dispatch of the reflections' miss program (`CS_RayMiss`) is of:
|
||||
/// its first root constant (`MISS_OPAQUE`, `MISS_ALPHA`, then water's); `u32::MAX` if unknown.
|
||||
fn miss_layer(&self, p: &HostPipeline) -> u32 {
|
||||
p.stages
|
||||
.first()
|
||||
.map(|s| s.translated())
|
||||
.and_then(|t| t.used.iter().find(|u| u.root == RootType::Constants))
|
||||
.and_then(|u| match self.roots_ref(true).get(usize::from(u.slot)) {
|
||||
Some(Root::Constants(c)) => c.first().copied(),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(u32::MAX)
|
||||
}
|
||||
|
||||
/// Whether this dispatch of `p` is the reflections' miss program (`CS_RayMiss`)
|
||||
/// for opaque or transparent surfaces and should be skipped (`VICTORY_SKIP_RAYMISS=1`
|
||||
/// or `VICTORY_AMBIENT_SPECULAR=0`; `VICTORY_RAYMISS_KEEP=1` always runs it).
|
||||
/// Water's layer is always kept so water reflections stay intact.
|
||||
fn sky_miss_left_out(&self, p: &HostPipeline) -> bool {
|
||||
static SKIP: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
let skip = *SKIP.get_or_init(|| {
|
||||
if std::env::var("VICTORY_RAYMISS_KEEP").is_ok_and(|v| v.trim() == "1") {
|
||||
return false;
|
||||
}
|
||||
std::env::var("VICTORY_SKIP_RAYMISS").is_ok_and(|v| v.trim() == "1")
|
||||
|| std::env::var("VICTORY_AMBIENT_SPECULAR").is_ok_and(|v| v.trim() == "0")
|
||||
});
|
||||
skip
|
||||
&& p.stages.first().and_then(|s| s.shader.ambient) == Some(crate::ambient::Role::Miss)
|
||||
&& matches!(self.miss_layer(p), crate::ambient::MISS_OPAQUE | crate::ambient::MISS_ALPHA)
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
@@ -4480,6 +4602,7 @@ impl State {
|
||||
unsafe { l6.DispatchMesh(x.min(65_535), 1, 1) };
|
||||
self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
|
||||
self.mesh_scissor(list, false);
|
||||
self.planes_now(list);
|
||||
DRAWN.fetch_add(1, Ordering::Relaxed);
|
||||
true
|
||||
}
|
||||
@@ -4735,10 +4858,15 @@ impl State {
|
||||
made.push((slot, first * 32));
|
||||
continue;
|
||||
}
|
||||
let Some(first) = host.dynamic(n).or_else(|| {
|
||||
crate::host::settle_for_fence();
|
||||
host.dynamic(n)
|
||||
}) else {
|
||||
let mut first = host.dynamic(n);
|
||||
for _ in 0..3 {
|
||||
if first.is_some() {
|
||||
break;
|
||||
}
|
||||
crate::host::reclaim_dynamic();
|
||||
first = host.dynamic(n);
|
||||
}
|
||||
let Some(first) = first else {
|
||||
// No room: the draw must not run with the title's own
|
||||
// offsets (slots never made for it); `bind` drops it.
|
||||
made.push((slot, u32::MAX));
|
||||
@@ -4764,15 +4892,20 @@ impl State {
|
||||
self.recording = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
let recording = self.recording;
|
||||
// Batch all `ListViews` lookups and `CopyDescriptors` across the
|
||||
// table in one thread-local borrow instead of one COM call per slot.
|
||||
let mut batch_listed: Vec<Option<([u32; 3], crate::descriptor::host::Listed)>> = Vec::new();
|
||||
if list_views {
|
||||
host.make_listed_batch(recording, first, table, n, &mut batch_listed);
|
||||
}
|
||||
// The whole range: a shader may index past the entries its
|
||||
// used-resource list names (descriptor arrays).
|
||||
for k in 0..n {
|
||||
let index = first + k;
|
||||
// A view this list has made before: its descriptor copied,
|
||||
// and nothing more if nothing changed in the list since.
|
||||
// A view this frame's cache has made: its descriptor was copied
|
||||
// in the batch above, and nothing more if nothing changed since.
|
||||
if list_views
|
||||
&& let Some(words) = crate::descriptor::record_at(table + u64::from(k) * 32)
|
||||
&& let Some(mut listed) = host.make_listed(recording, words, index)
|
||||
&& let Some((words, mut listed)) = batch_listed.get(k as usize).copied().flatten()
|
||||
{
|
||||
let kind = group
|
||||
.entry(k)
|
||||
@@ -4820,12 +4953,28 @@ impl State {
|
||||
let used = group.entry(k);
|
||||
match crate::descriptor::view(table + u64::from(k) * 32) {
|
||||
Some(View::Constant(address, size)) => {
|
||||
let Some((buffer, gpu, to)) = list.scratch_held(u64::from(size)) else {
|
||||
// Direct 256-byte-aligned in-place CBV fast path: when
|
||||
// `VICTORY_PORT_CONSTANTS=1` already has the constant heap
|
||||
// in place on the card and `gpu` is 256-byte aligned, bind
|
||||
// directly with zero scratch alloc, zero `Step::Fill`, and
|
||||
// zero CPU copy (`VICTORY_DIRECT_CBV=0` disables).
|
||||
static DIRECT_CBV: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
if *DIRECT_CBV.get_or_init(|| std::env::var_os("VICTORY_DIRECT_CBV").is_none_or(|v| v != "0"))
|
||||
&& crate::port::on()
|
||||
&& let Some(shadow) = crate::shadow::find(address, u64::from(size)).filter(|s| s.in_place())
|
||||
{
|
||||
let gpu = shadow.gpu(address);
|
||||
let aligned = u64::from(size).next_multiple_of(256);
|
||||
if gpu.is_multiple_of(256) && shadow.left(address) >= aligned {
|
||||
host.constant_at(index, &shadow.buffer, gpu, size);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let slot = (std::ptr::from_ref(heap) as usize, index);
|
||||
let Some((buffer, gpu)) = list.constant_scratch(address as *const u8, size, slot) else {
|
||||
host.make_null(index);
|
||||
continue;
|
||||
};
|
||||
let slot = (std::ptr::from_ref(heap) as usize, index);
|
||||
list.defer_constants(to, address as *const u8, size as usize, slot);
|
||||
host.constant_at(index, &buffer, gpu, size);
|
||||
}
|
||||
Some(view) => {
|
||||
@@ -4970,6 +5119,7 @@ impl State {
|
||||
viewports(list, &self.viewports);
|
||||
}
|
||||
self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
|
||||
self.planes_now(list);
|
||||
DRAWN.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
if !ran {
|
||||
@@ -5153,6 +5303,7 @@ impl State {
|
||||
.DrawIndexedInstanced(indices, instances, first, base, first_instance)
|
||||
};
|
||||
self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
|
||||
self.planes_now(list);
|
||||
DRAWN.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
if !ran {
|
||||
@@ -5164,6 +5315,16 @@ impl State {
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// A draw or dispatch was just recorded: the depth planes its shaders
|
||||
/// wrote through their twins are drawn into the planes now
|
||||
/// (`crate::host::depth_plane_now`), and the title's bindings, which
|
||||
/// that pass replaced, set again.
|
||||
fn planes_now(&mut self, list: &HostList) {
|
||||
if list.planes_now() {
|
||||
self.replay(list);
|
||||
}
|
||||
}
|
||||
|
||||
/// Shaders that can write buffers were recorded: arguments may be others
|
||||
/// from here on.
|
||||
fn buffers_written(&mut self) {
|
||||
@@ -5269,6 +5430,10 @@ impl State {
|
||||
crate::pipeline::note_drop(self.pipeline as This);
|
||||
return false;
|
||||
};
|
||||
if kind == DISPATCH && self.sky_miss_left_out(p) {
|
||||
once!("reflections' miss program left out for opaque and transparent surfaces (VICTORY_RAYMISS_KEEP=1 runs it)");
|
||||
return false;
|
||||
}
|
||||
// Indirect rectangles (the title's tiled lighting, 256
|
||||
// indirect draws a frame, makes their corners from the vertex
|
||||
// number) are completed by the pipeline's geometry stage: the
|
||||
@@ -5538,6 +5703,7 @@ impl State {
|
||||
self.host_roots[1] = 0;
|
||||
}
|
||||
}
|
||||
self.planes_now(list);
|
||||
// The scratch buffer stays readable as arguments: the next draw of
|
||||
// the window reads it with no barrier, and the next clamp moves it
|
||||
// back (`crate::indirect`).
|
||||
@@ -5765,9 +5931,7 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) {
|
||||
// A shader that cannot store to buffers leaves the range as
|
||||
// the title has it: nothing to find afterwards.
|
||||
if STORES.get() || !write_skip() {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::host::wide_write(address, len, 0);
|
||||
shadow.gpu_writes(list, address, len);
|
||||
shadow.shader_writes(list, address, len, 0);
|
||||
} else {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
|
||||
+1157
-128
File diff suppressed because it is too large.
Load diff
@@ -225,6 +225,8 @@ pub(super) enum FillTo {
|
||||
/// A descriptor slot that shows the fill's memory, and nothing else does
|
||||
/// (title heap, slot): it is made to show our buffer instead.
|
||||
Slot(usize, u32),
|
||||
/// Multiple deduplicated descriptor slots sharing the same fill.
|
||||
Slots(Vec<(usize, u32)>),
|
||||
/// A buffer the card can write, filled from its beginning.
|
||||
Buffer(ID3D12Resource),
|
||||
}
|
||||
@@ -659,6 +661,8 @@ enum To {
|
||||
Copy(Arc<Shadow>, usize),
|
||||
/// A descriptor slot (title heap, slot).
|
||||
Slot(usize, u32),
|
||||
/// Multiple deduplicated descriptor slots sharing one fill.
|
||||
Slots(Vec<(usize, u32)>),
|
||||
/// A buffer's beginning.
|
||||
Buffer(ID3D12Resource),
|
||||
}
|
||||
@@ -900,6 +904,7 @@ impl Host {
|
||||
}
|
||||
_ => match fill_to(runs, steps[i]) {
|
||||
Some(FillTo::Slot(heap, index)) => To::Slot(heap, index),
|
||||
Some(FillTo::Slots(slots)) => To::Slots(slots),
|
||||
Some(FillTo::Buffer(buffer)) => To::Buffer(buffer),
|
||||
None => continue,
|
||||
},
|
||||
@@ -957,7 +962,7 @@ impl Host {
|
||||
match &op.to {
|
||||
To::Copy(to, dst) => writes.push((&to.buffer, to.offset(*dst as u64), op.at, len)),
|
||||
To::Buffer(buffer) => writes.push((buffer, 0, op.at, len)),
|
||||
To::Slot(..) => {}
|
||||
To::Slot(..) | To::Slots(..) => {}
|
||||
}
|
||||
}
|
||||
record(level == 0, &own.list.list, &own.between, &reads, &writes);
|
||||
@@ -972,11 +977,19 @@ impl Host {
|
||||
let parts = if ops.len() < 256 { 1 } else { 8 };
|
||||
crate::land::each_under(parts, &|part| {
|
||||
for op in &ops {
|
||||
if let To::Slot(heap, index) = &op.to
|
||||
&& *index as usize / 4 % parts == part
|
||||
{
|
||||
// (A heap that is gone: nothing can read the slot.)
|
||||
crate::descriptor::constant_slot(*heap, *index, &own.between, gpu + op.at, op.len as u32);
|
||||
match &op.to {
|
||||
To::Slot(heap, index) if *index as usize / 4 % parts == part => {
|
||||
// (A heap that is gone: nothing can read the slot.)
|
||||
crate::descriptor::constant_slot(*heap, *index, &own.between, gpu + op.at, op.len as u32);
|
||||
}
|
||||
To::Slots(slots) => {
|
||||
for &(heap, index) in slots {
|
||||
if index as usize / 4 % parts == part {
|
||||
crate::descriptor::constant_slot(heap, index, &own.between, gpu + op.at, op.len as u32);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1023,7 +1036,7 @@ fn noted(ops: &[Op]) {
|
||||
for op in ops {
|
||||
let (to, dst) = match &op.to {
|
||||
To::Copy(to, dst) => (to.span(), *dst),
|
||||
To::Slot(..) | To::Buffer(_) => ((0, 0), 0),
|
||||
To::Slot(..) | To::Slots(..) | To::Buffer(_) => ((0, 0), 0),
|
||||
};
|
||||
let e = noted.entry((op.len, op.from.0.span(), to)).or_default();
|
||||
*e = (e.0 + 1, op.from.1, dst);
|
||||
|
||||
@@ -118,7 +118,13 @@ const S_RES: &str = "VICTORY_MENU_S_RES";
|
||||
/// The Series S scene sizes and the DLSS mode of each (the picture is 1920x1080). Only DLSS
|
||||
/// changes it: the title's own FidelityFX path from 540 stopped it at the start (0xc0000094,
|
||||
/// a division by zero in the title, 2026-11-28), so with DLSS off the scene stays at 720.
|
||||
const S_MODES: [(&str, &str); 4] = [("1080", "dlaa"), ("720", "quality"), ("626", "balanced"), ("540", "performance")];
|
||||
const S_MODES: [(&str, &str); 5] = [
|
||||
("1080", "dlaa"),
|
||||
("720", "quality"),
|
||||
("626", "balanced"),
|
||||
("540", "performance"),
|
||||
("360", "ultraperformance"),
|
||||
];
|
||||
const ABOUT_S_RES: [&str; 3] = [
|
||||
"THE SIZE THE GAME RENDERS AT. THE PICTURE IS 1920X1080.",
|
||||
"OTHER THAN 720 NEEDS DLSS: THIS SETS ITS MODE (1080 IS",
|
||||
@@ -148,7 +154,7 @@ const STAGES: &[(&str, &str)] = &[("2", "2"), ("1", "1"), ("0", "0 OFF")];
|
||||
#[rustfmt::skip]
|
||||
const ITEMS: &[Item] = &[
|
||||
// The launcher's own choices.
|
||||
Item { var: "VICTORY_MENU_DLSS", label: "DLSS", values: &[("quality", "QUALITY"), ("balanced", "BALANCED"), ("performance", "PERFORMANCE"), ("dlaa", "DLAA (NATIVE)"), ("off", "OFF")], live: false },
|
||||
Item { var: "VICTORY_MENU_DLSS", label: "DLSS", values: &[("quality", "QUALITY"), ("balanced", "BALANCED"), ("performance", "PERFORMANCE"), ("ultraperformance", "ULTRA PERF"), ("dlaa", "DLAA (NATIVE)"), ("off", "OFF")], live: false },
|
||||
Item { var: "VICTORY_MENU_FRAMEGEN", label: "FRAME GENERATION", values: &[("0", "OFF"), ("2", "2X"), ("3", "3X"), ("4", "4X"), ("5", "5X"), ("6", "6X (MOST)")], live: false },
|
||||
// DLSS Frame Generation where it runs (RTX 40 and later), else AMD's FSR 3 (2X only).
|
||||
Item { var: "VICTORY_MENU_FG_TYPE", label: "FRAME GEN TYPE", values: &[("auto", "AUTO"), ("dlss", "DLSS"), ("fsr", "FSR 3 (OLDER CARDS)")], live: false },
|
||||
@@ -163,7 +169,7 @@ const ITEMS: &[Item] = &[
|
||||
Item { var: "VICTORY_MENU_CONSOLE", label: "CONSOLE", values: &[("series-x", "SERIES X"), ("series-s", "SERIES S (FASTER)")], live: false },
|
||||
Item { var: X_RES, label: "SERIES X PICTURE", values: &[("1440", "2560X1440"), ("1080to1440", "1080P TO 1440P"), ("4k", "3840X2160")], live: false },
|
||||
// In place of SERIES X PICTURE when CONSOLE is Series S.
|
||||
Item { var: S_RES, label: "SERIES S PICTURE", values: &[("1080", "1920X1080 (DLAA)"), ("720", "1280X720 (THE GAME)"), ("626", "1113X626"), ("540", "960X540 (FASTEST)")], live: false },
|
||||
Item { var: S_RES, label: "SERIES S PICTURE", values: &[("1080", "1920X1080 (DLAA)"), ("720", "1280X720 (THE GAME)"), ("626", "1113X626"), ("540", "960X540 (FASTEST)"), ("360", "640X360 (ULTRA FAST)")], live: false },
|
||||
// The layer's switches.
|
||||
Item { var: "VICTORY_DLSS_PRESET", label: "DLSS MODEL", values: &[("", "DEFAULT"), ("k", "K"), ("j", "J"), ("m", "M"), ("l", "L")], live: false },
|
||||
Item { var: "VICTORY_AMBIENT", label: "LIGHT ESTIMATE", values: &[("0.8", "0.8"), ("1", "1"), ("0.5", "0.5"), ("", "OFF")], live: false },
|
||||
@@ -965,7 +971,9 @@ impl Menu {
|
||||
let _ours = crate::replay::record::unrecorded();
|
||||
let scale = (height / 540).max(1);
|
||||
if self.buffers.as_ref().is_none_or(|b| (b.format, b.scale) != (format, scale)) {
|
||||
std::mem::forget(self.buffers.take());
|
||||
if let Some(old) = self.buffers.take() {
|
||||
crate::host::retire(old);
|
||||
}
|
||||
self.buffers = Buffers::new(host, format, scale);
|
||||
self.failed = self.buffers.is_none();
|
||||
self.changed = true;
|
||||
|
||||
@@ -389,8 +389,9 @@ impl Panel {
|
||||
let _ours = crate::replay::record::unrecorded();
|
||||
let scale = scale(height);
|
||||
if self.buffers.as_ref().is_none_or(|b| (b.format, b.scale) != (format, scale)) {
|
||||
// (What the card may still read stays: a picture's size changes once or twice in a run.)
|
||||
std::mem::forget(self.buffers.take());
|
||||
if let Some(old) = self.buffers.take() {
|
||||
crate::host::retire(old);
|
||||
}
|
||||
self.buffers = Buffers::new(host, PANEL, format, scale);
|
||||
self.failed = self.buffers.is_none();
|
||||
self.changed = true;
|
||||
@@ -440,8 +441,9 @@ impl Notice {
|
||||
}
|
||||
let since = *self.since.get_or_insert_with(Instant::now);
|
||||
if since.elapsed() > NOTICE_FOR {
|
||||
// (Its buffers stay: the card may still read them.)
|
||||
std::mem::forget(self.buffers.take());
|
||||
if let Some(old) = self.buffers.take() {
|
||||
crate::host::retire(old);
|
||||
}
|
||||
self.done = true;
|
||||
return;
|
||||
}
|
||||
@@ -449,7 +451,9 @@ impl Notice {
|
||||
let _ours = crate::replay::record::unrecorded();
|
||||
let scale = scale(height);
|
||||
if self.buffers.as_ref().is_none_or(|b| (b.format, b.scale) != (format, scale)) {
|
||||
std::mem::forget(self.buffers.take());
|
||||
if let Some(old) = self.buffers.take() {
|
||||
crate::host::retire(old);
|
||||
}
|
||||
self.buffers = Buffers::new(host, self.shape, format, scale);
|
||||
self.written = false;
|
||||
if self.buffers.is_none() {
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
//! Diagnostics: where the refreshes of host copies spend their time, by the
|
||||
//! path that runs them: [`super::Batch::refresh_front`] (`front`),
|
||||
//! [`super::Batch::refresh_ahead`] (`ahead`), the flushes of
|
||||
//! [`super::Batch::flush_all`] (`flush`) and [`super::Batch::flush_one`]
|
||||
//! (`one`). Per path: the pass that tells the copies known to copy nothing
|
||||
//! (`clean_check_ms`: on the submitting thread, or spread over the threads
|
||||
//! with the submitting thread waiting), the updates of the others
|
||||
//! (`dirty_update_ms`, `dirty_update_count`) and the path's whole time,
|
||||
//! which is what the preparing line's "refreshes" adds up (part 6 of the
|
||||
//! submitting thread's split). Since the last frame-rate line ([`line`]).
|
||||
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
|
||||
use std::time::Instant;
|
||||
|
||||
/// The paths.
|
||||
pub(super) const FRONT: usize = 0;
|
||||
pub(super) const AHEAD: usize = 1;
|
||||
pub(super) const FLUSH: usize = 2;
|
||||
pub(super) const ONE: usize = 3;
|
||||
|
||||
/// Per path: nanoseconds in all and the times it ran; the clean checks on
|
||||
/// the submitting thread (nanoseconds, passes, copies) and those spread
|
||||
/// over the threads (the same); the updates (the submitting thread's
|
||||
/// nanoseconds from the first to the last, copies updated, textures
|
||||
/// refreshed beside them); and on the threads, summed: nanoseconds of clean
|
||||
/// checks, of updates, of textures.
|
||||
const ALL_NS: usize = 0;
|
||||
const RUNS: usize = 1;
|
||||
const SERIAL_NS: usize = 2;
|
||||
const SERIAL_PASSES: usize = 3;
|
||||
const SERIAL_COPIES: usize = 4;
|
||||
const THREADED_NS: usize = 5;
|
||||
const THREADED_PASSES: usize = 6;
|
||||
const THREADED_COPIES: usize = 7;
|
||||
const UPDATE_NS: usize = 8;
|
||||
const UPDATES: usize = 9;
|
||||
const TEXTURES: usize = 10;
|
||||
const THREADS_CHECK_NS: usize = 11;
|
||||
const THREADS_UPDATE_NS: usize = 12;
|
||||
const THREADS_TEXTURE_NS: usize = 13;
|
||||
const FIELDS: usize = 14;
|
||||
|
||||
static N: [[AtomicU64; FIELDS]; 4] = [const { [const { AtomicU64::new(0) }; FIELDS] }; 4];
|
||||
|
||||
fn add(path: usize, field: usize, n: u64) {
|
||||
N[path][field].fetch_add(n, Relaxed);
|
||||
}
|
||||
|
||||
fn since(began: Instant) -> u64 {
|
||||
began.elapsed().as_nanos() as u64
|
||||
}
|
||||
|
||||
/// The path ran, `ns` in all (as the frame line's "refreshes" counts it).
|
||||
pub(super) fn ran(path: usize, ns: u64) {
|
||||
add(path, ALL_NS, ns);
|
||||
add(path, RUNS, 1);
|
||||
}
|
||||
|
||||
/// A clean check of `copies` copies began at `began`, on the submitting
|
||||
/// thread or (`threaded`) spread over the threads.
|
||||
pub(super) fn checked(path: usize, threaded: bool, began: Instant, copies: usize) {
|
||||
let [ns, passes, of] = if threaded {
|
||||
[THREADED_NS, THREADED_PASSES, THREADED_COPIES]
|
||||
} else {
|
||||
[SERIAL_NS, SERIAL_PASSES, SERIAL_COPIES]
|
||||
};
|
||||
add(path, ns, since(began));
|
||||
add(path, passes, 1);
|
||||
add(path, of, copies as u64);
|
||||
}
|
||||
|
||||
/// Updates of `updates` copies (and `textures` textures beside them) began
|
||||
/// at `began` on the submitting thread, which waited for the last.
|
||||
pub(super) fn updated(path: usize, began: Instant, updates: usize, textures: usize) {
|
||||
add(path, UPDATE_NS, since(began));
|
||||
add(path, UPDATES, updates as u64);
|
||||
add(path, TEXTURES, textures as u64);
|
||||
}
|
||||
|
||||
/// On one of the threads: a clean check of `copies` copies began at `began`.
|
||||
pub(super) fn thread_checked(path: usize, began: Instant, copies: usize) {
|
||||
add(path, THREADS_CHECK_NS, since(began));
|
||||
add(path, THREADED_COPIES, copies as u64);
|
||||
}
|
||||
|
||||
/// On one of the threads: updates of `updates` copies began at `began`.
|
||||
pub(super) fn thread_updated(path: usize, began: Instant, updates: usize) {
|
||||
add(path, THREADS_UPDATE_NS, since(began));
|
||||
add(path, UPDATES, updates as u64);
|
||||
}
|
||||
|
||||
/// One update or texture of a fan-out, timed on its thread until dropped.
|
||||
pub(super) struct OnThread(usize, usize, Instant);
|
||||
|
||||
impl OnThread {
|
||||
pub(super) fn new(path: usize, texture: bool) -> OnThread {
|
||||
OnThread(path, if texture { THREADS_TEXTURE_NS } else { THREADS_UPDATE_NS }, Instant::now())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for OnThread {
|
||||
fn drop(&mut self) {
|
||||
add(self.0, self.1, since(self.2));
|
||||
}
|
||||
}
|
||||
|
||||
/// For the frame-rate line, per frame over `frames`, beside the preparing
|
||||
/// line of the same frames.
|
||||
pub(super) fn line(frames: f64) {
|
||||
let n: [[f64; FIELDS]; 4] = std::array::from_fn(|p| std::array::from_fn(|f| N[p][f].swap(0, Relaxed) as f64 / frames));
|
||||
let ms = |p: usize, f: usize| n[p][f] / 1e6;
|
||||
let check = |p: usize| {
|
||||
format!(
|
||||
"clean_check_ms {:.2} (serial {:.2} in {:.1} passes over {:.0} copies, threaded {:.2} in {:.1} passes over {:.0} copies)",
|
||||
ms(p, SERIAL_NS) + ms(p, THREADED_NS),
|
||||
ms(p, SERIAL_NS),
|
||||
n[p][SERIAL_PASSES],
|
||||
n[p][SERIAL_COPIES],
|
||||
ms(p, THREADED_NS),
|
||||
n[p][THREADED_PASSES],
|
||||
n[p][THREADED_COPIES],
|
||||
)
|
||||
};
|
||||
let all: f64 = (0..4).map(|p| ms(p, ALL_NS)).sum();
|
||||
tracing::info!(
|
||||
"refresh loop per frame, by path (diagnostics; the \"in all\" of the four together is the preparing line's \
|
||||
\"refreshes\", {all:.2} ms): front {:.1} runs: {}, dirty_update_ms {:.2} (the fan-out; on the threads {:.2} \
|
||||
updates + {:.2} textures), dirty_update_count {:.0} + {:.0} textures, {:.2} in all; ahead {:.1} runs: \
|
||||
clean_check_ms {:.2} and dirty_update_ms {:.2} (both summed over the threads, over {:.0} copies), \
|
||||
dirty_update_count {:.0}, {:.2} in all; flush {:.1} runs: {}, dirty_update_ms {:.2}, dirty_update_count {:.0}, \
|
||||
{:.2} in all; one at a time {:.1} runs: clean_check_ms {:.2}, dirty_update_ms {:.2}, dirty_update_count {:.0}, \
|
||||
{:.2} in all",
|
||||
n[FRONT][RUNS],
|
||||
check(FRONT),
|
||||
ms(FRONT, UPDATE_NS),
|
||||
ms(FRONT, THREADS_UPDATE_NS),
|
||||
ms(FRONT, THREADS_TEXTURE_NS),
|
||||
n[FRONT][UPDATES],
|
||||
n[FRONT][TEXTURES],
|
||||
ms(FRONT, ALL_NS),
|
||||
n[AHEAD][RUNS],
|
||||
ms(AHEAD, THREADS_CHECK_NS),
|
||||
ms(AHEAD, THREADS_UPDATE_NS),
|
||||
n[AHEAD][THREADED_COPIES],
|
||||
n[AHEAD][UPDATES],
|
||||
ms(AHEAD, ALL_NS),
|
||||
n[FLUSH][RUNS],
|
||||
check(FLUSH),
|
||||
ms(FLUSH, UPDATE_NS),
|
||||
n[FLUSH][UPDATES],
|
||||
ms(FLUSH, ALL_NS),
|
||||
n[ONE][RUNS],
|
||||
(ms(ONE, ALL_NS) - ms(ONE, UPDATE_NS)).max(0.0),
|
||||
ms(ONE, UPDATE_NS),
|
||||
n[ONE][UPDATES],
|
||||
ms(ONE, ALL_NS),
|
||||
);
|
||||
}
|
||||
@@ -122,7 +122,9 @@ static SPARE: Mutex<Vec<Memory>> = Mutex::new(Vec::new());
|
||||
/// On hosts with <= 32 GiB RAM, cap the idle upload pool at 256 MiB (instead
|
||||
/// of 768 MiB) so streaming bursts have more commit headroom.
|
||||
fn kept() -> u64 {
|
||||
if on_card() || crate::residency::limited_host_ram() {
|
||||
if crate::residency::tight_host_ram() {
|
||||
128 << 20
|
||||
} else if on_card() || crate::residency::limited_host_ram() {
|
||||
256 << 20
|
||||
} else {
|
||||
768 << 20
|
||||
|
||||
@@ -15,6 +15,19 @@
|
||||
//! share, [`console`] which console model the title sees. Planned:
|
||||
//! `present` (swap chain).
|
||||
|
||||
// These are style/pedantic lints new in the toolchain (rust 1.98's clippy)
|
||||
// that fire on pre-existing code the VICTORY_LIST_ALLOC_CAP_MB work never
|
||||
// touched (some of it in the committed base). Suppressing them at crate root
|
||||
// keeps `cargo clippy -D warnings` green without rewriting unrelated or
|
||||
// committed source; the exact set below is only the lints clippy reported.
|
||||
#![allow(clippy::collapsible_if)]
|
||||
#![allow(clippy::derivable_impls)]
|
||||
#![allow(clippy::for_kv_map)]
|
||||
#![allow(clippy::identity_op)]
|
||||
#![allow(clippy::manual_contains)]
|
||||
#![allow(clippy::manual_is_multiple_of)]
|
||||
#![allow(clippy::unnecessary_lazy_evaluations)]
|
||||
|
||||
#[cfg(windows)]
|
||||
mod ahead;
|
||||
mod ambient;
|
||||
@@ -26,6 +39,16 @@ pub mod console;
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
mod copystat;
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
mod dipstat;
|
||||
|
||||
/// Release builds with the `mimalloc` feature: the Rust side allocates
|
||||
/// through mimalloc (per-thread caches) instead of the process heap, which
|
||||
/// it shares with the title and the drivers. Diagnostics builds count every
|
||||
/// block through `copystat`'s allocator, which then uses mimalloc too.
|
||||
#[cfg(all(feature = "mimalloc", not(all(windows, feature = "diagnostics"))))]
|
||||
#[global_allocator]
|
||||
static MIMALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc;
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
mod faultbook;
|
||||
#[cfg(windows)]
|
||||
mod cores;
|
||||
@@ -134,7 +157,7 @@ pub fn frames_begun() -> u64 {
|
||||
#[cfg(windows)]
|
||||
pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view};
|
||||
#[cfg(windows)]
|
||||
pub use shadow::title_memory_write_combined;
|
||||
pub use shadow::{title_memory_gpu_readonly, title_memory_gpu_writable, title_memory_write_combined};
|
||||
#[cfg(windows)]
|
||||
pub use watch::{
|
||||
SoftViews, kernel_writing, soft_view_guards, title_memory_allocated, title_memory_freed, title_memory_made_real,
|
||||
|
||||
@@ -422,12 +422,18 @@ pub(crate) fn recycle(lists: Vec<Detached>, ran: &[usize]) {
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn trim_idle() {
|
||||
const PRESSURED_KEEP: usize = 64;
|
||||
// Under physical-RAM pressure (VICTORY_RAM_PRESSURE_MB) keep a tighter
|
||||
// but still generous idle pool so loose allocators are shed, without
|
||||
// cutting below what a steady frame reuses. Unchanged (64) when the
|
||||
// feature is off, since `ram_critical()` is then always false.
|
||||
const RAM_CRITICAL_KEEP: usize = 24;
|
||||
let keep = if crate::residency::ram_critical() { RAM_CRITICAL_KEEP } else { PRESSURED_KEEP };
|
||||
let freed: Vec<Idle> = {
|
||||
let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if idle.0.len() <= PRESSURED_KEEP {
|
||||
if idle.0.len() <= keep {
|
||||
return;
|
||||
}
|
||||
let dropped = idle.0.split_off(PRESSURED_KEEP);
|
||||
let dropped = idle.0.split_off(keep);
|
||||
let dropped_bytes: u64 = dropped.iter().map(|Idle(_, b, _)| *b).sum();
|
||||
idle.1 = idle.1.saturating_sub(dropped_bytes);
|
||||
dropped
|
||||
@@ -2344,12 +2350,113 @@ extern "system" fn wait_value64(this: This, address: u64, comparison: u32, refer
|
||||
wait_for(this, address, comparison, reference, true);
|
||||
}
|
||||
|
||||
/// Whether enhanced barrier groups are inspected before emitting a full
|
||||
/// global UAV barrier (`VICTORY_SMART_BARRIERS=1`, off by default: skipping
|
||||
/// non-UAV barriers can omit state syncs for render targets/lighting buffers).
|
||||
#[cfg(windows)]
|
||||
fn smart_barriers() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_SMART_BARRIERS").is_some_and(|v| v == "1"))
|
||||
}
|
||||
|
||||
/// Enhanced barrier groups `[kept, skipped]` since the last log interval.
|
||||
#[cfg(windows)]
|
||||
pub(crate) static BARRIER_GROUPS_STATS: [std::sync::atomic::AtomicU64; 2] =
|
||||
[const { std::sync::atomic::AtomicU64::new(0) }; 2];
|
||||
|
||||
/// Returns `true` if the enhanced barrier groups in `groups[0..count]` require
|
||||
/// a global UAV synchronization barrier (ordering a prior shader UAV write),
|
||||
/// or `false` if they are purely non-UAV transitions (e.g. RT/DSV/copy texture
|
||||
/// layout transitions that our texture state tracker already emits explicitly,
|
||||
/// or `SYNC_NONE` / `NO_ACCESS` barriers).
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn barrier_groups_needs_uav(count: u32, groups: *const u8) -> bool {
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
if count == 0 {
|
||||
return false;
|
||||
}
|
||||
if !smart_barriers() || groups.is_null() || count > 64 {
|
||||
BARRIER_GROUPS_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
return true;
|
||||
}
|
||||
let needs_access = |sync_before: D3D12_BARRIER_SYNC, access_before: D3D12_BARRIER_ACCESS| -> bool {
|
||||
if sync_before == D3D12_BARRIER_SYNC_NONE {
|
||||
return false;
|
||||
}
|
||||
// `COMMON` (0) or `UNORDERED_ACCESS` (0x80) may order a prior UAV write;
|
||||
// pure RT/DSV/copy/SRV/no-access transitions do not need a global UAV drain.
|
||||
access_before == D3D12_BARRIER_ACCESS_COMMON
|
||||
|| (access_before.0 & D3D12_BARRIER_ACCESS_UNORDERED_ACCESS.0) != 0
|
||||
};
|
||||
// SAFETY: the title passes `count` valid `D3D12_BARRIER_GROUP` entries
|
||||
// whose inner barrier arrays are valid for the duration of the call.
|
||||
let slice = unsafe { std::slice::from_raw_parts(groups.cast::<D3D12_BARRIER_GROUP>(), count as usize) };
|
||||
for g in slice {
|
||||
let n = g.NumBarriers as usize;
|
||||
if n == 0 {
|
||||
continue;
|
||||
}
|
||||
if n > 4096 {
|
||||
BARRIER_GROUPS_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
return true;
|
||||
}
|
||||
match g.Type {
|
||||
D3D12_BARRIER_TYPE_GLOBAL => {
|
||||
let p = unsafe { g.Anonymous.pGlobalBarriers };
|
||||
if p.is_null() {
|
||||
BARRIER_GROUPS_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
return true;
|
||||
}
|
||||
let bs = unsafe { std::slice::from_raw_parts(p, n) };
|
||||
if bs.iter().any(|b| needs_access(b.SyncBefore, b.AccessBefore)) {
|
||||
BARRIER_GROUPS_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
D3D12_BARRIER_TYPE_BUFFER => {
|
||||
let p = unsafe { g.Anonymous.pBufferBarriers };
|
||||
if p.is_null() {
|
||||
BARRIER_GROUPS_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
return true;
|
||||
}
|
||||
let bs = unsafe { std::slice::from_raw_parts(p, n) };
|
||||
if bs.iter().any(|b| needs_access(b.SyncBefore, b.AccessBefore)) {
|
||||
BARRIER_GROUPS_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
D3D12_BARRIER_TYPE_TEXTURE => {
|
||||
let p = unsafe { g.Anonymous.pTextureBarriers };
|
||||
if p.is_null() {
|
||||
BARRIER_GROUPS_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
return true;
|
||||
}
|
||||
let bs = unsafe { std::slice::from_raw_parts(p, n) };
|
||||
if bs.iter().any(|b| needs_access(b.SyncBefore, b.AccessBefore)) {
|
||||
BARRIER_GROUPS_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
BARRIER_GROUPS_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
BARRIER_GROUPS_STATS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
false
|
||||
}
|
||||
|
||||
/// The enhanced barriers `(group count, groups)`: buffer, texture and
|
||||
/// global barriers with layouts instead of states. Every host use of a
|
||||
/// title texture (clears, copies) moves its host copy to the state it needs
|
||||
/// first, so only their ordering matters: one barrier on every shader
|
||||
/// write (the title's buffer barriers order compute passes).
|
||||
extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) {
|
||||
extern "system" fn barrier_groups(this: This, count: u32, groups: *const u8) {
|
||||
#[cfg(windows)]
|
||||
if count == 0 || (!groups.is_null() && !barrier_groups_needs_uav(count, groups)) {
|
||||
return;
|
||||
}
|
||||
// Diagnostics: counted, and left out under `VICTORY_BARRIER_TEST=groups`.
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
if count > 0 {
|
||||
@@ -2370,7 +2477,7 @@ extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) {
|
||||
unsafe { list.list.ResourceBarrier(&[barrier]) };
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = (this, count);
|
||||
let _ = (this, count, groups);
|
||||
}
|
||||
|
||||
/// The bottom-of-pipe value writes `(address, value, flush, flags)`, 32 and
|
||||
|
||||
@@ -83,6 +83,7 @@ impl Front {
|
||||
{
|
||||
recording.abandoned.store(true, Release);
|
||||
}
|
||||
drop_untranslated(&self.words);
|
||||
self.words.clear();
|
||||
}
|
||||
|
||||
@@ -265,6 +266,10 @@ impl Recording {
|
||||
impl Drop for Recording {
|
||||
fn drop(&mut self) {
|
||||
let inner = self.inner.get_mut().unwrap_or_else(|e| e.into_inner());
|
||||
// Only `chunks` hold untranslated `UPLOAD`/`EXTERNAL` boxes; `kept` was already consumed by `translate`.
|
||||
for stream in &inner.chunks {
|
||||
drop_untranslated(stream);
|
||||
}
|
||||
give_back(inner.chunks.drain(..).chain(std::mem::take(&mut inner.kept)).collect());
|
||||
if inner.back != 0 {
|
||||
if !inner.closed {
|
||||
@@ -277,6 +282,28 @@ impl Drop for Recording {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops boxed `UPLOAD` and `EXTERNAL` payloads owned by an untranslated chunk
|
||||
/// before its word buffer is cleared or dropped.
|
||||
fn drop_untranslated(stream: &[u64]) {
|
||||
let mut i = 0;
|
||||
while i < stream.len() {
|
||||
let (op, len) = (stream[i] & 0xffff, (stream[i] >> 16) as usize);
|
||||
let next = i + 1 + len;
|
||||
if let Some(&ptr) = stream.get(i + 1)
|
||||
&& next <= stream.len()
|
||||
{
|
||||
if op == UPLOAD {
|
||||
// SAFETY: `Box::into_raw` created in `allocate_upload` and never translated.
|
||||
drop(unsafe { Box::from_raw(ptr as *mut Upload) });
|
||||
} else if op == EXTERNAL {
|
||||
// SAFETY: `Box::into_raw` created in `put_external` and never translated.
|
||||
drop(unsafe { Box::from_raw(ptr as *mut super::External) });
|
||||
}
|
||||
}
|
||||
i = next.max(i + 1);
|
||||
}
|
||||
}
|
||||
|
||||
fn give_back(streams: Vec<Vec<u64>>) {
|
||||
let mut words = held(&WORDS);
|
||||
for mut s in streams {
|
||||
@@ -563,8 +590,10 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) ->
|
||||
}
|
||||
0
|
||||
}
|
||||
extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) {
|
||||
front(this).put(BARRIER_GROUPS, &[u64::from(count)]);
|
||||
extern "system" fn barrier_groups(this: This, count: u32, groups: *const u8) {
|
||||
if super::barrier_groups_needs_uav(count, groups) {
|
||||
front(this).put(BARRIER_GROUPS, &[1]);
|
||||
}
|
||||
}
|
||||
extern "system" fn viewports(this: This, count: u32, items: *const D3D12_VIEWPORT) {
|
||||
let count = if items.is_null() { 0 } else { count };
|
||||
|
||||
@@ -769,7 +769,7 @@ impl Memory {
|
||||
&& !self.pages.contains_key(&page)
|
||||
{
|
||||
self.copies[k].refresh(list, at, n);
|
||||
self.copies[k].gpu_writes(list, at, n);
|
||||
self.copies[k].shader_writes(list, at, n, 1);
|
||||
self.stats.back += 1;
|
||||
}
|
||||
at += n;
|
||||
|
||||
@@ -115,6 +115,38 @@ fn left_out(shaders: &[Arc<Shader>]) -> Option<&'static str> {
|
||||
if skip_rt && named(shaders, b"CS_RaytracingResolve") {
|
||||
return Some("shades ray-tracing hits without BVH, left out");
|
||||
}
|
||||
// Opt-in (`VICTORY_DEAD_RT=1`, off by default because several of these
|
||||
// passes initialize shadow masks or screen-probe inputs used by lighting):
|
||||
// skips additional RT/screen-probe compute prefixes when BVH is off.
|
||||
static SKIP_DEAD_RT: OnceLock<bool> = OnceLock::new();
|
||||
let skip_dead_rt = *SKIP_DEAD_RT.get_or_init(|| {
|
||||
let builder = std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1");
|
||||
if builder {
|
||||
return false;
|
||||
}
|
||||
std::env::var_os("VICTORY_DEAD_RT").is_some_and(|v| v == "1")
|
||||
});
|
||||
if skip_dead_rt {
|
||||
const DEAD_RT_PREFIXES: [&[u8]; 14] = [
|
||||
b"CS_RayBudgeting_",
|
||||
b"CS_GenerateRayCoords",
|
||||
b"CS_RaytraceShadows_",
|
||||
b"CS_RaytraceVBuffer_",
|
||||
b"CS_IrradianceCache_",
|
||||
b"CS_Primary_",
|
||||
b"CS_ScreenProbes_TraceRays_BVH_",
|
||||
b"CS_ScreenProbes_EvaluateRayRequests",
|
||||
b"CS_ScreenProbes_GenerateRayBins",
|
||||
b"CS_ScreenProbes_GenerateShaderBins",
|
||||
b"CS_ScreenProbes_PrefilterRadianceMips",
|
||||
b"CS_ScreenProbes_RadianceSpatialFilter",
|
||||
b"CS_ScreenProbes_ResponsivenessSpatialFilter",
|
||||
b"CS_ScreenProbes_Inject",
|
||||
];
|
||||
if DEAD_RT_PREFIXES.iter().any(|p| named(shaders, p)) {
|
||||
return Some("dead BVH ray-tracing compute pass without BVH, left out (VICTORY_DEAD_RT=0: run)");
|
||||
}
|
||||
}
|
||||
// The screen probes' ray activation runs without the structure builder
|
||||
// too: left out, the probes kept stale values and surfaces lit mostly by
|
||||
// them took a magenta or violet cast (papers on a wall, irises), at no
|
||||
|
||||
+128
-40
@@ -43,7 +43,8 @@ static SPARES: AtomicUsize = AtomicUsize::new(SPARE);
|
||||
/// Asked once a second.
|
||||
pub(crate) fn room(memory: Option<[u64; 4]>) {
|
||||
let pressure = crate::residency::pressured();
|
||||
let limit = spares(memory, crate::host::keep_freed() && !pressure);
|
||||
let host_low = crate::residency::host_room_low();
|
||||
let limit = if host_low { SPARE } else { spares(memory, crate::host::keep_freed() && !pressure) };
|
||||
SPARES.store(limit, Ordering::Relaxed);
|
||||
let tick = now();
|
||||
// A full pool can become idle while another subsystem needs the VRAM.
|
||||
@@ -52,12 +53,15 @@ pub(crate) fn room(memory: Option<[u64; 4]>) {
|
||||
pool.reclaim(tick, limit, true);
|
||||
}
|
||||
if let Ok(mut pool) = STAGING.try_lock() {
|
||||
let tight = crate::residency::tight_host_ram();
|
||||
let staging_limit = if crate::residency::critical_commit() {
|
||||
0
|
||||
} else if pressure {
|
||||
} else if pressure || host_low {
|
||||
1
|
||||
} else if tight {
|
||||
2
|
||||
} else {
|
||||
limit
|
||||
limit.min(STAGING_KEPT)
|
||||
};
|
||||
pool.reclaim(tick, staging_limit, true);
|
||||
}
|
||||
@@ -205,21 +209,26 @@ struct Pool<B> {
|
||||
spare: usize,
|
||||
most: usize,
|
||||
retry_growth_at: u64,
|
||||
/// Blocks being made ahead by a thread outside the lock ([`take_from`]),
|
||||
/// counted as empty ones so that no two threads make the same one.
|
||||
making_ahead: usize,
|
||||
}
|
||||
|
||||
impl<B: Clone> Pool<B> {
|
||||
const fn new(most: usize) -> Pool<B> {
|
||||
Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0, most, retry_growth_at: 0 }
|
||||
Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0, most, retry_growth_at: 0, making_ahead: 0 }
|
||||
}
|
||||
|
||||
/// A piece of `len` bytes and the memory it lies in, and whether that
|
||||
/// part was ever used before; `make` makes a block when none has room.
|
||||
#[cfg(test)]
|
||||
fn take(&mut self, len: u64, align: u64, now: u64, make: impl FnMut() -> Option<B>) -> Option<(Piece, B, bool)> {
|
||||
self.take_ripe(len, align, now, Ripe::ALL, make)
|
||||
}
|
||||
|
||||
/// The same from a block that is ripe, if one has room; `make` makes one
|
||||
/// ahead too, when few are empty.
|
||||
#[cfg(test)]
|
||||
fn take_ripe(
|
||||
&mut self,
|
||||
len: u64,
|
||||
@@ -228,6 +237,33 @@ impl<B: Clone> Pool<B> {
|
||||
ripe: Ripe,
|
||||
mut make: impl FnMut() -> Option<B>,
|
||||
) -> Option<(Piece, B, bool)> {
|
||||
let (i, start) = match self.cut(len, align, now, ripe)? {
|
||||
Some(found) => found,
|
||||
None => {
|
||||
if !self.may_grow(now) {
|
||||
return None;
|
||||
}
|
||||
let Some(memory) = make() else {
|
||||
self.failed_growth(now);
|
||||
return None;
|
||||
};
|
||||
self.add_and_cut(memory, ripe.started, len, align)?
|
||||
}
|
||||
};
|
||||
if self.short_ahead(now, ripe) {
|
||||
match make() {
|
||||
Some(memory) => {
|
||||
self.add(memory, ripe.started);
|
||||
}
|
||||
None => self.failed_growth(now),
|
||||
}
|
||||
}
|
||||
self.taken(i, start, len, ripe)
|
||||
}
|
||||
|
||||
/// Where a piece of `len` bytes was cut from a block there is: `None`
|
||||
/// if it is never pooled, `Some(None)` if no block has room.
|
||||
fn cut(&mut self, len: u64, align: u64, now: u64, ripe: Ripe) -> Option<Option<(usize, u64)>> {
|
||||
// With blocks made ahead, what would be an allocation of its own (and
|
||||
// new when the card first reads it) lies in one of those too.
|
||||
if len == 0 || len > if ripe.ahead > 0 { BLOCK } else { BLOCK / 2 } {
|
||||
@@ -251,47 +287,41 @@ impl<B: Clone> Pool<B> {
|
||||
unripe.sort_unstable();
|
||||
found = unripe.into_iter().find_map(|(_, i)| Some((i, self.blocks[i].as_mut()?.free.take(len, align)?)));
|
||||
}
|
||||
// A failed 64 MiB block must not trigger another driver call for each
|
||||
// small texture. Existing free ranges remain usable during backoff.
|
||||
let (i, start) = match found {
|
||||
Some(found) => found,
|
||||
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)?)
|
||||
}
|
||||
};
|
||||
if ripe.ahead > 0 {
|
||||
if !ripe.is(self.blocks[i].as_ref()?) {
|
||||
let n = UNRIPE.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if n.is_power_of_two() {
|
||||
tracing::info!("textures cut from blocks made while lists ran that still run: {n}");
|
||||
}
|
||||
}
|
||||
let empty = self.blocks.iter().flatten().filter(|b| b.free.whole(BLOCK)).count();
|
||||
if empty < ripe.ahead
|
||||
&& let Some(memory) = self.grow(now, &mut make)
|
||||
{
|
||||
self.add(memory, ripe.started);
|
||||
Some(found)
|
||||
}
|
||||
|
||||
fn may_grow(&self, now: u64) -> bool {
|
||||
now >= self.retry_growth_at
|
||||
}
|
||||
|
||||
fn failed_growth(&mut self, now: u64) {
|
||||
self.retry_growth_at = now.saturating_add(500);
|
||||
}
|
||||
|
||||
fn add_and_cut(&mut self, memory: B, made: u64, len: u64, align: u64) -> Option<(usize, u64)> {
|
||||
let i = self.add(memory, made);
|
||||
Some((i, self.blocks[i].as_mut()?.free.take(len, align)?))
|
||||
}
|
||||
|
||||
fn short_ahead(&self, now: u64, ripe: Ripe) -> bool {
|
||||
ripe.ahead > 0
|
||||
&& self.may_grow(now)
|
||||
&& self.blocks.iter().flatten().filter(|b| b.free.whole(BLOCK)).count() + self.making_ahead < ripe.ahead
|
||||
}
|
||||
|
||||
fn taken(&mut self, i: usize, start: u64, len: u64, ripe: Ripe) -> Option<(Piece, B, bool)> {
|
||||
let block = self.blocks[i].as_mut()?;
|
||||
if ripe.ahead > 0 && !ripe.is(block) {
|
||||
let n = UNRIPE.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if n.is_power_of_two() {
|
||||
tracing::info!("textures cut from blocks made while lists ran that still run: {n}");
|
||||
}
|
||||
}
|
||||
let block = self.blocks[i].as_mut()?;
|
||||
let again = start < block.used_to;
|
||||
block.used_to = block.used_to.max(start + len);
|
||||
Some((Piece { block: i, start, len }, block.memory.clone(), again))
|
||||
}
|
||||
|
||||
fn grow(&mut self, now: u64, make: &mut impl FnMut() -> Option<B>) -> Option<B> {
|
||||
if now < self.retry_growth_at {
|
||||
return None;
|
||||
}
|
||||
let block = make();
|
||||
if block.is_none() {
|
||||
self.retry_growth_at = now.saturating_add(500);
|
||||
}
|
||||
block
|
||||
}
|
||||
|
||||
fn add(&mut self, memory: B, made: u64) -> usize {
|
||||
let i = match self.blocks.iter().position(Option::is_none) {
|
||||
Some(i) => i,
|
||||
@@ -398,6 +428,64 @@ fn lock<T>(m: &'static Mutex<T>) -> std::sync::MutexGuard<'static, T> {
|
||||
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Cuts from a pool behind a lock while making new 64 MiB blocks outside the lock,
|
||||
/// so `CreateHeap` / `MakeResident` waits never stall other texture/staging callers.
|
||||
fn take_from<B: Clone + 'static>(
|
||||
pool: &'static Mutex<Pool<B>>,
|
||||
len: u64,
|
||||
align: u64,
|
||||
ripe: impl Fn() -> Ripe,
|
||||
mut make: impl FnMut() -> Option<B>,
|
||||
) -> Option<(Piece, B, bool)> {
|
||||
let first = ripe();
|
||||
let mut p = lock(pool);
|
||||
let (i, start) = match p.cut(len, align, now(), first)? {
|
||||
Some(found) => found,
|
||||
None => {
|
||||
if !p.may_grow(now()) {
|
||||
return None;
|
||||
}
|
||||
drop(p);
|
||||
let made = make();
|
||||
let mark = ripe().started;
|
||||
p = lock(pool);
|
||||
let Some(memory) = made else {
|
||||
p.failed_growth(now());
|
||||
return None;
|
||||
};
|
||||
p.add_and_cut(memory, mark, len, align)?
|
||||
}
|
||||
};
|
||||
let ahead = p.short_ahead(now(), first);
|
||||
if ahead {
|
||||
p.making_ahead += 1;
|
||||
}
|
||||
let taken = p.taken(i, start, len, first);
|
||||
drop(p);
|
||||
if ahead {
|
||||
struct Making<B: Clone + 'static>(&'static Mutex<Pool<B>>);
|
||||
impl<B: Clone + 'static> Drop for Making<B> {
|
||||
fn drop(&mut self) {
|
||||
let mut p = lock(self.0);
|
||||
p.making_ahead = p.making_ahead.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
let making = Making(pool);
|
||||
let made = make();
|
||||
let mark = ripe().started;
|
||||
let mut p = lock(pool);
|
||||
std::mem::forget(making);
|
||||
p.making_ahead = p.making_ahead.saturating_sub(1);
|
||||
match made {
|
||||
Some(memory) => {
|
||||
p.add(memory, mark);
|
||||
}
|
||||
None => p.failed_growth(now()),
|
||||
}
|
||||
}
|
||||
taken
|
||||
}
|
||||
|
||||
/// Bytes of the pieces textures hold now.
|
||||
static HELD: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
@@ -527,7 +615,7 @@ pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPi
|
||||
}
|
||||
// Copies from a buffer begin at multiples of 512.
|
||||
let bytes = bytes.next_multiple_of(512);
|
||||
let (piece, memory, again) = lock(&STAGING).take(bytes, 512, now(), || {
|
||||
let (piece, memory, again) = take_from(&STAGING, bytes, 512, || Ripe::ALL, || {
|
||||
// Only gate speculative bindless prefetch on staging-pool growth
|
||||
// headroom; table-bound textures and decoration bakes are sampled
|
||||
// immediately and would otherwise read uninitialized/reused VRAM.
|
||||
@@ -823,7 +911,7 @@ pub(crate) unsafe fn texture(
|
||||
0
|
||||
};
|
||||
#[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) = take_from(&TEXTURES, info.SizeInBytes, info.Alignment.max(1), Ripe::now, || {
|
||||
let desc = D3D12_HEAP_DESC {
|
||||
SizeInBytes: BLOCK,
|
||||
Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
|
||||
|
||||
@@ -297,12 +297,19 @@ impl<W: Work> Lane<W> {
|
||||
while self.step(limit) {}
|
||||
}
|
||||
|
||||
/// The parts of `entry`, which stands for them, in place `at`.
|
||||
fn unfold(state: &mut State<W>, at: usize, entry: Entry<W>) {
|
||||
/// Unfolds `entry` without holding the lane lock, returning its parts and
|
||||
/// metadata ready to be inserted back into `state.items`.
|
||||
fn unfold_parts(entry: Entry<W>) -> (u64, usize, usize, u64, Vec<W>) {
|
||||
let began = Instant::now();
|
||||
let (number, queue, runs, mark) = (entry.number, entry.queue, usize::from(entry.what.runs()), entry.mark);
|
||||
let parts = entry.what.unfold();
|
||||
STATS[UNFOLDING].fetch_add(began.elapsed().as_micros() as u64, Relaxed);
|
||||
(number, queue, runs, mark, parts)
|
||||
}
|
||||
|
||||
/// Inserts already-unfolded parts of an entry back at their order position.
|
||||
fn insert_unfolded(state: &mut State<W>, (number, queue, runs, mark, parts): (u64, usize, usize, u64, Vec<W>)) {
|
||||
let at = state.items.iter().position(|e| e.number > number).unwrap_or(state.items.len());
|
||||
state.runs -= runs;
|
||||
state.runs += parts.iter().filter(|p| p.runs()).count();
|
||||
for (i, what) in parts.into_iter().enumerate() {
|
||||
@@ -374,11 +381,12 @@ impl<W: Work> Lane<W> {
|
||||
if entry.what.folded() {
|
||||
// Its parts take its place: behind everything before it, before
|
||||
// everything after it (they share its number; the first of them
|
||||
// is found first).
|
||||
// is found first). Unfold outside the lane lock so thin list
|
||||
// workers and title submits do not convoy behind `unfold()`.
|
||||
let unfolded = Self::unfold_parts(entry);
|
||||
let mut state = self.lock();
|
||||
state.running = None;
|
||||
let at = state.items.iter().position(|e| e.number > entry.number).unwrap_or(state.items.len());
|
||||
Self::unfold(&mut state, at, entry);
|
||||
Self::insert_unfolded(&mut state, unfolded);
|
||||
drop(state);
|
||||
self.moved.notify_all();
|
||||
return true;
|
||||
@@ -397,11 +405,13 @@ impl<W: Work> Lane<W> {
|
||||
// (Back where it was: parts of one submission share a number.)
|
||||
if next.what.folded() {
|
||||
let free = next.what.ask().is_none_or(|ask| W::met(&ask));
|
||||
let mut state = self.lock();
|
||||
if free {
|
||||
Self::unfold(&mut state, at, next);
|
||||
let unfolded = Self::unfold_parts(next);
|
||||
let mut state = self.lock();
|
||||
Self::insert_unfolded(&mut state, unfolded);
|
||||
continue;
|
||||
}
|
||||
let mut state = self.lock();
|
||||
state.items.insert(at, next);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,11 @@ const MIB: u64 = 1 << 20;
|
||||
const GIB: u64 = 1 << 30;
|
||||
static PRESSURED: AtomicBool = AtomicBool::new(false);
|
||||
static HEADROOM: AtomicU64 = AtomicU64::new(u64::MAX);
|
||||
/// Last physical available RAM sampled by [`refresh`] (bytes). `u64::MAX`
|
||||
/// until the first sample, so [`ram_critical`] stays off before then.
|
||||
static AVAIL_PHYS: AtomicU64 = AtomicU64::new(u64::MAX);
|
||||
/// Latched RAM-pressure state for [`ram_critical`]'s hysteresis.
|
||||
static RAM_CRITICAL: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
fn memory_status() -> Option<MEMORYSTATUSEX> {
|
||||
// SAFETY: the API initializes the fields of a correctly sized structure.
|
||||
@@ -15,6 +20,144 @@ fn memory_status() -> Option<MEMORYSTATUSEX> {
|
||||
(unsafe { GlobalMemoryStatusEx(&mut status) } != 0).then_some(status)
|
||||
}
|
||||
|
||||
/// What is left to commit, as the layer's decisions count it: what is left
|
||||
/// under the system's commit limit now, plus what its pagefiles may still
|
||||
/// grow by ([`commit_growth`]).
|
||||
fn available_commit(status: &MEMORYSTATUSEX) -> u64 {
|
||||
status.ullAvailPageFile.saturating_add(commit_growth(status))
|
||||
}
|
||||
|
||||
/// How much more the system's commit limit can grow: Windows grows a
|
||||
/// system-managed pagefile when commit reaches the limit, up to three times
|
||||
/// RAM (at least 4 GB) and an eighth of its volume, and a custom one up to its
|
||||
/// maximum, capped by free volume space less 8 GB.
|
||||
/// `VICTORY_COMMIT_GROWTH=0`: the limit of the moment alone, as before.
|
||||
fn commit_growth(status: &MEMORYSTATUSEX) -> u64 {
|
||||
static OFF: OnceLock<bool> = OnceLock::new();
|
||||
if *OFF.get_or_init(|| std::env::var_os("VICTORY_COMMIT_GROWTH").is_some_and(|v| v == "0")) {
|
||||
return 0;
|
||||
}
|
||||
static FILES: OnceLock<Vec<Pagefile>> = OnceLock::new();
|
||||
let files = FILES.get_or_init(|| {
|
||||
let files = pagefiles();
|
||||
let said: Vec<String> = files
|
||||
.iter()
|
||||
.map(|f| match f.max_mb {
|
||||
Some(mb) => format!("{} up to {mb} MB", f.root),
|
||||
None => format!("{} system-managed", f.root),
|
||||
})
|
||||
.collect();
|
||||
tracing::info!(
|
||||
pagefiles = ?said,
|
||||
commit_limit_mib = status.ullTotalPageFile >> 20,
|
||||
"pagefiles: commit can grow beyond the limit of the moment (VICTORY_COMMIT_GROWTH=0: not counted)"
|
||||
);
|
||||
files
|
||||
});
|
||||
if files.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
static GROWTH: AtomicU64 = AtomicU64::new(0);
|
||||
let now = crate::host::coarse_ms();
|
||||
let next = NEXT.load(Ordering::Relaxed);
|
||||
if now >= next
|
||||
&& NEXT
|
||||
.compare_exchange(next, now.saturating_add(5000), Ordering::Relaxed, Ordering::Relaxed)
|
||||
.is_ok()
|
||||
{
|
||||
let size_now = status.ullTotalPageFile.saturating_sub(status.ullTotalPhys);
|
||||
let mut most = 0u64;
|
||||
let mut room = 0u64;
|
||||
let mut roots: Vec<&str> = Vec::new();
|
||||
for file in files {
|
||||
let Some((total, free)) = volume_space(&file.root) else { continue };
|
||||
most += match file.max_mb {
|
||||
Some(mb) => mb * MIB,
|
||||
None => (3 * status.ullTotalPhys).max(4 * GIB).min(total / 8),
|
||||
};
|
||||
if !roots.contains(&file.root.as_str()) {
|
||||
roots.push(&file.root);
|
||||
room += free.saturating_sub(8 * GIB);
|
||||
}
|
||||
}
|
||||
GROWTH.store(most.saturating_sub(size_now).min(room), Ordering::Relaxed);
|
||||
}
|
||||
GROWTH.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
struct Pagefile {
|
||||
root: String,
|
||||
max_mb: Option<u64>,
|
||||
}
|
||||
|
||||
fn pagefiles() -> Vec<Pagefile> {
|
||||
use windows_sys::Win32::System::Registry::{HKEY_LOCAL_MACHINE, RRF_RT_REG_MULTI_SZ, RegGetValueW};
|
||||
let wide = |s: &str| s.encode_utf16().chain([0]).collect::<Vec<u16>>();
|
||||
let key = wide(r"SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management");
|
||||
let value = wide("PagingFiles");
|
||||
let mut bytes = 0u32;
|
||||
// SAFETY: a size query, then the read into a buffer of that size.
|
||||
let sized = unsafe {
|
||||
RegGetValueW(
|
||||
HKEY_LOCAL_MACHINE,
|
||||
key.as_ptr(),
|
||||
value.as_ptr(),
|
||||
RRF_RT_REG_MULTI_SZ,
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null_mut(),
|
||||
&mut bytes,
|
||||
)
|
||||
};
|
||||
if sized != 0 || bytes == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut buffer = vec![0u16; (bytes as usize).div_ceil(2)];
|
||||
// SAFETY: as above; the buffer holds `bytes` bytes.
|
||||
let read = unsafe {
|
||||
RegGetValueW(
|
||||
HKEY_LOCAL_MACHINE,
|
||||
key.as_ptr(),
|
||||
value.as_ptr(),
|
||||
RRF_RT_REG_MULTI_SZ,
|
||||
std::ptr::null_mut(),
|
||||
buffer.as_mut_ptr().cast(),
|
||||
&mut bytes,
|
||||
)
|
||||
};
|
||||
if read != 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let system_drive = std::env::var("SystemDrive").unwrap_or_else(|_| "C:".into());
|
||||
let len = (bytes as usize / 2).min(buffer.len());
|
||||
String::from_utf16_lossy(&buffer[..len])
|
||||
.split('\0')
|
||||
.filter_map(|entry| parse_pagefile(entry, &system_drive))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn parse_pagefile(entry: &str, system_drive: &str) -> Option<Pagefile> {
|
||||
let mut parts = entry.split_whitespace();
|
||||
let path = parts.next()?;
|
||||
let drive = path.get(..2).filter(|d| d.ends_with(':'))?;
|
||||
let drive = if drive.starts_with('?') { system_drive.get(..2)? } else { drive };
|
||||
let sizes: Vec<u64> = parts.filter_map(|p| p.parse().ok()).collect();
|
||||
let max_mb = match sizes.as_slice() {
|
||||
[_, max] if *max > 0 => Some(*max),
|
||||
_ => None,
|
||||
};
|
||||
Some(Pagefile { root: format!(r"{}\", drive.to_ascii_uppercase()), max_mb })
|
||||
}
|
||||
|
||||
fn volume_space(root: &str) -> Option<(u64, u64)> {
|
||||
use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW;
|
||||
let wide: Vec<u16> = root.encode_utf16().chain([0]).collect();
|
||||
let (mut free, mut total, mut total_free) = (0u64, 0u64, 0u64);
|
||||
// SAFETY: a path and three out-values of ours.
|
||||
let ok = unsafe { GetDiskFreeSpaceExW(wide.as_ptr(), &mut free, &mut total, &mut total_free) } != 0;
|
||||
ok.then_some((total, free))
|
||||
}
|
||||
|
||||
// The texture sweep may run for seconds inside a single submitted frame.
|
||||
static NEXT_COMMIT_SAMPLE: AtomicU64 = AtomicU64::new(0);
|
||||
static AVAILABLE_COMMIT: AtomicU64 = AtomicU64::new(u64::MAX);
|
||||
@@ -50,7 +193,7 @@ fn sample_commit(now: u64) -> u64 {
|
||||
.is_ok()
|
||||
&& let Some(status) = memory_status()
|
||||
{
|
||||
AVAILABLE_COMMIT.store(status.ullAvailPageFile, Ordering::Relaxed);
|
||||
AVAILABLE_COMMIT.store(available_commit(&status), Ordering::Relaxed);
|
||||
}
|
||||
AVAILABLE_COMMIT.load(Ordering::Relaxed)
|
||||
}
|
||||
@@ -95,6 +238,14 @@ pub(crate) fn limited_host_ram() -> bool {
|
||||
*LIMITED.get_or_init(|| memory_status().is_some_and(|s| s.ullTotalPhys <= 32 * GIB))
|
||||
}
|
||||
|
||||
/// True on hosts with <= 20 GiB physical RAM (e.g. 16 GB laptops), where idle
|
||||
/// pools (staging blocks, snapshot buffers, upload scratch, command allocators)
|
||||
/// should stay lean to leave physical RAM free for Windows and avoid paging.
|
||||
pub(crate) fn tight_host_ram() -> bool {
|
||||
static TIGHT: OnceLock<bool> = OnceLock::new();
|
||||
*TIGHT.get_or_init(|| memory_status().is_some_and(|s| s.ullTotalPhys <= 20 * GIB))
|
||||
}
|
||||
|
||||
fn next_pressure(was: bool, physical: u64, commit: u64) -> bool {
|
||||
if was {
|
||||
physical < 5 * GIB || commit < 6 * GIB
|
||||
@@ -106,8 +257,10 @@ fn next_pressure(was: bool, physical: u64, commit: u64) -> bool {
|
||||
/// Called by the once-per-second submission sweep. A failed sample keeps the last good state.
|
||||
pub(crate) fn refresh() {
|
||||
let Some(status) = memory_status() else { return };
|
||||
let (physical, commit) = (status.ullAvailPhys, status.ullAvailPageFile);
|
||||
let (physical, commit) = (status.ullAvailPhys, available_commit(&status));
|
||||
HEADROOM.store(physical.min(commit), Ordering::Relaxed);
|
||||
AVAIL_PHYS.store(physical, Ordering::Relaxed);
|
||||
refresh_ram_critical(physical);
|
||||
let was = pressured();
|
||||
let pressure = next_pressure(was, physical, commit);
|
||||
if pressure != was {
|
||||
@@ -139,6 +292,45 @@ pub(crate) fn pressured() -> bool {
|
||||
PRESSURED.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// How long host copies of placed textures whose title memory is no longer
|
||||
/// mapped may stay cached when host memory is tight: 5 s below a quarter of
|
||||
/// RAM (at most 16 GiB left), 1 s below 8 GiB. `VICTORY_HOST_TEXTURE_SWEEP=0`
|
||||
/// restores the card-only rule.
|
||||
pub(crate) fn host_texture_idle_ms() -> Option<u64> {
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
if !*ON.get_or_init(|| std::env::var_os("VICTORY_HOST_TEXTURE_SWEEP").is_none_or(|v| v != "0")) {
|
||||
return None;
|
||||
}
|
||||
host_texture_idle_for(headroom()?, total_physical())
|
||||
}
|
||||
|
||||
pub(crate) fn host_room_low() -> bool {
|
||||
host_texture_idle_ms().is_some()
|
||||
}
|
||||
|
||||
fn total_physical() -> u64 {
|
||||
static TOTAL: OnceLock<u64> = OnceLock::new();
|
||||
*TOTAL.get_or_init(|| memory_status().map_or(0, |s| s.ullTotalPhys))
|
||||
}
|
||||
|
||||
fn host_texture_idle_for(head: u64, total: u64) -> Option<u64> {
|
||||
// Only engage the unmapped host-texture sweep on >20 GiB RAM hosts where
|
||||
// large system-RAM caches can accumulate without triggering VRAM eviction.
|
||||
// On 16 GiB / 6 GiB VRAM hosts, physical headroom is routinely <8 GiB and
|
||||
// overriding the card's VRAM sweep starves GPU texture blocks.
|
||||
if total <= 20 * GIB {
|
||||
return None;
|
||||
}
|
||||
let line = (total / 4).min(16 * GIB);
|
||||
if head < 8 * GIB {
|
||||
Some(1_000)
|
||||
} else if head < line {
|
||||
Some(5_000)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// True when OS commit headroom is critically low (< 1.5 GiB) or an allocation
|
||||
/// just failed with `E_OUTOFMEMORY`, requiring emergency throttling.
|
||||
pub(crate) fn critical_commit() -> bool {
|
||||
@@ -146,6 +338,51 @@ pub(crate) fn critical_commit() -> bool {
|
||||
now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) || sample_commit(now) < 1536 * MIB
|
||||
}
|
||||
|
||||
/// `VICTORY_RAM_PRESSURE_MB`: when set to N > 0, the physical-RAM threshold
|
||||
/// (in MiB) below which the once-a-second host sweep also runs the heavy
|
||||
/// fence-safe trims that are otherwise gated on OS commit headroom
|
||||
/// ([`critical_commit`]). On a 16 GB box the pagefile keeps commit headroom
|
||||
/// wide while physical RAM is exhausted, so those trims never fire; this
|
||||
/// re-points them at physical RAM. Parsed once; unset or 0 leaves the whole
|
||||
/// feature inert (no new sample, no new branch taken anywhere).
|
||||
fn ram_pressure_bytes() -> Option<u64> {
|
||||
static THRESHOLD: OnceLock<Option<u64>> = OnceLock::new();
|
||||
*THRESHOLD.get_or_init(|| {
|
||||
let mb: u64 = std::env::var("VICTORY_RAM_PRESSURE_MB").ok()?.trim().parse().ok()?;
|
||||
(mb > 0).then(|| mb * MIB)
|
||||
})
|
||||
}
|
||||
|
||||
/// Recompute the latched RAM-pressure state from a fresh physical-RAM
|
||||
/// sample, with hysteresis: enter below the threshold, leave only once free
|
||||
/// RAM climbs past the threshold plus a margin, so it does not flap around
|
||||
/// the line. A no-op when the feature is off. Called from [`refresh`].
|
||||
fn refresh_ram_critical(physical: u64) {
|
||||
let Some(threshold) = ram_pressure_bytes() else { return };
|
||||
const MARGIN: u64 = 256 * MIB;
|
||||
let was = RAM_CRITICAL.load(Ordering::Relaxed);
|
||||
let now = if was { physical <= threshold + MARGIN } else { physical < threshold };
|
||||
if now != was {
|
||||
RAM_CRITICAL.store(now, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// True only when `VICTORY_RAM_PRESSURE_MB` is set to N > 0 and the last
|
||||
/// sampled physical available RAM is under N MiB (with hysteresis). Reads a
|
||||
/// cached atomic, so it is cheap to call from the hot path; it is always
|
||||
/// false when the feature is unset, which keeps today's behavior unchanged.
|
||||
pub(crate) fn ram_critical() -> bool {
|
||||
ram_pressure_bytes().is_some() && RAM_CRITICAL.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Last physical available RAM sampled by [`refresh`], in bytes, if the
|
||||
/// RAM-pressure feature is on and a sample has been taken. For the sweep's
|
||||
/// one-line pressure log.
|
||||
pub(crate) fn avail_phys_mib() -> Option<u64> {
|
||||
let bytes = AVAIL_PHYS.load(Ordering::Relaxed);
|
||||
(bytes != u64::MAX).then(|| bytes >> 20)
|
||||
}
|
||||
|
||||
/// A soft per-frame admission limit. A single texture can cross it. The
|
||||
/// queue retains unserved slots so they can be retried on later frames.
|
||||
pub(crate) fn prefetch_limit(bytes: u64, pressure: bool, critical: bool, limited: bool, staging: u64) -> u64 {
|
||||
@@ -198,4 +435,28 @@ mod tests {
|
||||
assert_eq!(prefetch_limit(512 << 20, true, true, false, 0), 16 << 20);
|
||||
assert_eq!(prefetch_limit(192 << 20, false, false, false, 0), 192 << 20);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pagefile_entries_say_their_volume_and_largest_size() {
|
||||
let f = parse_pagefile(r"?:\pagefile.sys", "C:").unwrap();
|
||||
assert_eq!((f.root.as_str(), f.max_mb), (r"C:\", None));
|
||||
let f = parse_pagefile(r"d:\pagefile.sys 0 0", "C:").unwrap();
|
||||
assert_eq!((f.root.as_str(), f.max_mb), (r"D:\", None));
|
||||
let f = parse_pagefile(r"C:\pagefile.sys 16384 49152", "C:").unwrap();
|
||||
assert_eq!((f.root.as_str(), f.max_mb), (r"C:\", Some(49152)));
|
||||
assert!(parse_pagefile("", "C:").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_texture_idle_follows_host_commit_not_only_the_card() {
|
||||
assert_eq!(host_texture_idle_for(20 * GIB, 64 * GIB), None);
|
||||
assert_eq!(host_texture_idle_for(16 * GIB, 64 * GIB), None);
|
||||
assert_eq!(host_texture_idle_for(15 * GIB, 64 * GIB), Some(5_000));
|
||||
assert_eq!(host_texture_idle_for(8 * GIB, 64 * GIB), Some(5_000));
|
||||
assert_eq!(host_texture_idle_for(7 * GIB, 64 * GIB), Some(1_000));
|
||||
assert_eq!(host_texture_idle_for(9 * GIB, 32 * GIB), None);
|
||||
assert_eq!(host_texture_idle_for(7 * GIB, 32 * GIB), Some(1_000));
|
||||
assert_eq!(host_texture_idle_for(3 * GIB, 16 * GIB), None);
|
||||
assert_eq!(host_texture_idle_for(1 * GIB, 0), None);
|
||||
}
|
||||
}
|
||||
@@ -391,10 +391,12 @@ pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 4] =
|
||||
/// frame-rate line; and since the start, how often a depth plane's twin
|
||||
/// lacked what was written to the plane (not given to it), and how often a
|
||||
/// depth plane was used in the list that had written its twin, before the
|
||||
/// pass (which runs when the list closes).
|
||||
/// pass (which runs when the list closes); and since the start, the
|
||||
/// planes drawn right after the shader that wrote their twin
|
||||
/// (`crate::host::depth_plane_now`).
|
||||
#[cfg(windows)]
|
||||
pub(crate) static PLANES: [std::sync::atomic::AtomicU64; 3] =
|
||||
[const { std::sync::atomic::AtomicU64::new(0) }; 3];
|
||||
pub(crate) static PLANES: [std::sync::atomic::AtomicU64; 4] =
|
||||
[const { std::sync::atomic::AtomicU64::new(0) }; 4];
|
||||
|
||||
/// The colour twin of title texture `this`, if it has one.
|
||||
#[cfg(windows)]
|
||||
@@ -1298,6 +1300,10 @@ struct Hosted {
|
||||
used: std::sync::atomic::AtomicU64,
|
||||
/// The host refused to make it: not tried again.
|
||||
refused: std::sync::atomic::AtomicBool,
|
||||
/// When the card last had no room for it (`crate::host::moment`; 0:
|
||||
/// never): it is tried again on a use after [`NO_ROOM_AGAIN_MS`]
|
||||
/// ([`NoTexture::ForNow`]).
|
||||
no_room: std::sync::atomic::AtomicU64,
|
||||
/// Its host copy was let go as idle once.
|
||||
gone: std::sync::atomic::AtomicBool,
|
||||
/// A texture of [`PLACED_TEXTURES`].
|
||||
@@ -1571,6 +1577,7 @@ pub(crate) fn want_level(this: This, first: u32) {
|
||||
HELD[2].fetch_add(1, Relaxed);
|
||||
if let Some(old) = made.take() {
|
||||
REPLACED.lock().unwrap_or_else(|e| e.into_inner()).push((crate::host::moment(), old));
|
||||
crate::descriptor::host::invalidate_list_views();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1831,6 +1838,12 @@ fn hosted(this: This, make: bool) -> Option<Made> {
|
||||
if !make || r.host.refused.load(Relaxed) {
|
||||
return None;
|
||||
}
|
||||
// The card had no room for it a moment ago: not asked again on
|
||||
// every use (`NO_ROOM_AGAIN_MS`).
|
||||
let no_room = r.host.no_room.load(Relaxed);
|
||||
if no_room != 0 && !crate::host::long_ago(no_room, NO_ROOM_AGAIN_MS, 0) {
|
||||
return None;
|
||||
}
|
||||
let clear = r
|
||||
.host
|
||||
.clear
|
||||
@@ -1862,7 +1875,7 @@ fn hosted(this: This, make: bool) -> Option<Made> {
|
||||
&& (!crate::texture::committed(r.data().cast_const(), bytes as usize)
|
||||
|| crate::descriptor::host::next_start(start, start.saturating_add(bytes)).is_some()
|
||||
|| crate::descriptor::host::first_viewed(start).is_some_and(|first| first > 0));
|
||||
let reserved = if partly { host_texture_as(&r.desc, r.host.state, clear, true) } else { None };
|
||||
let reserved = if partly { host_texture_as(&r.desc, r.host.state, clear, true).ok() } else { None };
|
||||
let cut = reserved
|
||||
.as_ref()
|
||||
.zip(crate::host::host())
|
||||
@@ -1892,13 +1905,30 @@ fn hosted(this: This, make: bool) -> Option<Made> {
|
||||
}
|
||||
}
|
||||
let texture = match texture {
|
||||
Some(texture) => Some(texture),
|
||||
Some(texture) => Ok(texture),
|
||||
None => host_texture(&r.desc.levels_from(base), r.host.state, clear),
|
||||
};
|
||||
let Some(texture) = texture else {
|
||||
r.host.refused.store(true, Relaxed);
|
||||
return None;
|
||||
let texture = match texture {
|
||||
Ok(texture) => texture,
|
||||
Err(NoTexture::Refused) => {
|
||||
r.host.refused.store(true, Relaxed);
|
||||
return None;
|
||||
}
|
||||
// Upstream VIctory #3198 / sagouindupm/Mandy 94fa12a: a texture
|
||||
// whose host texture could not be made kept that answer for the
|
||||
// run, so a texture first asked for while the card was full read
|
||||
// black to the end. Out of room is not a refusal: retry later.
|
||||
Err(NoTexture::ForNow) => {
|
||||
r.host.no_room.store(crate::host::moment().max(1), Relaxed);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
NOT_MADE_FOR_NOW.fetch_add(1, Relaxed);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if r.host.no_room.swap(0, Relaxed) != 0 {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
MADE_AFTER_NO_ROOM.fetch_add(1, Relaxed);
|
||||
}
|
||||
let twin = twin_texture(&r.desc, &texture);
|
||||
// One line per depth texture with unordered access: its address is
|
||||
// the one target dumps and the captured frame's list of commands
|
||||
@@ -2014,7 +2044,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,
|
||||
@@ -2049,15 +2079,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<u64> = std::sync::OnceLock::new();
|
||||
let most = *MOST.get_or_init(|| {
|
||||
static ASKED: std::sync::OnceLock<Option<u64>> = 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::<u64>().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<u64> = std::sync::OnceLock::new();
|
||||
let settle = *SETTLE.get_or_init(|| {
|
||||
std::env::var("VICTORY_CARD_ROOM_FOR_TARGETS_SETTLE_MS")
|
||||
@@ -2067,6 +2098,8 @@ pub(crate) fn targets_room_kept() -> u64 {
|
||||
});
|
||||
// Every host texture's bytes less those of the copies the title fills.
|
||||
let targets = HOST_TEXTURES[1].load(Relaxed).saturating_sub(KINDS[1].load(Relaxed));
|
||||
static PEAK: AtomicU64 = AtomicU64::new(0);
|
||||
let peak = PEAK.fetch_max(targets, Relaxed).max(targets);
|
||||
// The targets' bytes at their last change of 64 MiB or more, and when
|
||||
// they last grew by that much.
|
||||
static GREW: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
|
||||
@@ -2075,7 +2108,21 @@ pub(crate) fn targets_room_kept() -> u64 {
|
||||
let (last, since) = targets_seen(last, since, targets, now);
|
||||
GREW[0].store(last, Relaxed);
|
||||
GREW[1].store(since, Relaxed);
|
||||
targets_kept(most, targets, now.saturating_sub(since), settle)
|
||||
static FLAT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
if *FLAT.get_or_init(|| std::env::var_os("VICTORY_CARD_ROOM_FOR_TARGETS_MB").is_some()) {
|
||||
return targets_kept(most, targets, now.saturating_sub(since), settle);
|
||||
}
|
||||
targets_kept_from_peak(most, targets, peak)
|
||||
}
|
||||
|
||||
#[cfg(any(windows, test))]
|
||||
fn targets_most(asked: Option<u64>, 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
|
||||
@@ -2106,6 +2153,14 @@ fn targets_kept(most: u64, targets: u64, still_ms: u64, settle: u64) -> u64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// Room kept for render targets without the flat switch: half as much again as
|
||||
/// their peak (at least 256 MiB, capped at `most`), less what they hold now.
|
||||
#[cfg(any(windows, test))]
|
||||
fn targets_kept_from_peak(most: u64, targets: u64, peak: u64) -> u64 {
|
||||
const LEAST: u64 = 256 << 20;
|
||||
peak.saturating_add(peak / 2).max(LEAST).min(most).saturating_sub(targets)
|
||||
}
|
||||
|
||||
/// What [`room`] weighs now, in MB, for the log: the card's budget, its
|
||||
/// use, the free part of the texture blocks, what is kept for card copies
|
||||
/// of title buffers and for render targets, and the line. `None` without
|
||||
@@ -2123,7 +2178,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),
|
||||
@@ -2202,7 +2257,7 @@ pub(crate) fn placed_known(address: u64, desc: &[u32; 14]) -> Option<This> {
|
||||
let mut key = *desc;
|
||||
key[1] = 0;
|
||||
key[13] = 0;
|
||||
let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let map = PLACED_TEXTURES.read().unwrap_or_else(|e| e.into_inner());
|
||||
map.get(&(address, key)).or_else(|| map.get(&(address, *desc))).map(|&r| r as This)
|
||||
}
|
||||
|
||||
@@ -2456,14 +2511,18 @@ pub(crate) fn let_go_idle() {
|
||||
static KEEP: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
let keep = *KEEP
|
||||
.get_or_init(|| !matches!(std::env::var("VICTORY_TEXTURE_KEEP").as_deref(), Ok("0") | Ok("1")));
|
||||
let (idle_ms, most) = match memory {
|
||||
Some([budget, used, ..]) if keep => {
|
||||
let used = used.saturating_sub(crate::pool::texture_room())
|
||||
+ crate::shadow::card_room_kept()
|
||||
+ targets_room_kept();
|
||||
crate::host::vram_keep_below(budget, used, room_line(budget))
|
||||
}
|
||||
_ => (crate::host::vram_idle_ms(memory), u64::MAX),
|
||||
let host_idle = crate::residency::host_texture_idle_ms();
|
||||
let (idle_ms, most) = match host_idle {
|
||||
Some(ms) => (ms, u64::MAX),
|
||||
None => match memory {
|
||||
Some([budget, used, ..]) if keep => {
|
||||
let used = used.saturating_sub(crate::pool::texture_room())
|
||||
+ crate::shadow::card_room_kept()
|
||||
+ targets_room_kept(budget);
|
||||
crate::host::vram_keep_below(budget, used, room_line(budget))
|
||||
}
|
||||
_ => (crate::host::vram_idle_ms(memory), u64::MAX),
|
||||
},
|
||||
};
|
||||
// For the trail (`crate::host::trail`): how many went, their bytes,
|
||||
// and the first one.
|
||||
@@ -2491,7 +2550,7 @@ pub(crate) fn let_go_idle() {
|
||||
let whole = *WHOLE.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SWEEP").is_some_and(|v| v == "whole"));
|
||||
let part = if most != u64::MAX {
|
||||
0
|
||||
} else if whole || idle_ms < 60_000 {
|
||||
} else if whole || (idle_ms < 60_000 && host_idle.is_none()) {
|
||||
usize::MAX
|
||||
} else {
|
||||
PART
|
||||
@@ -2515,6 +2574,15 @@ pub(crate) fn let_go_idle() {
|
||||
if used == 0 || !fills(&r.desc) || !crate::host::long_ago(used, idle_ms, IDLE_FRAMES) || crate::texture::host_wrote(at) {
|
||||
continue;
|
||||
}
|
||||
if host_idle.is_some() {
|
||||
let unmapped = r.host.placed.load(Relaxed)
|
||||
&& footprint(&r.desc).is_some_and(|f| {
|
||||
f.size > 0 && crate::texture::mapped_bytes(r.data().cast_const(), f.size as usize) == 0
|
||||
});
|
||||
if !unmapped {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let gone = {
|
||||
let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let idle = made.as_ref().is_some_and(|(host, _)| {
|
||||
@@ -2766,6 +2834,9 @@ fn slot_evict(video: Option<[u64; 4]>, idle_ms: u64, frames: u64) {
|
||||
// SAFETY: as above (the table is held).
|
||||
let r = unsafe { &*(at as *const Resource) };
|
||||
let reset = crate::descriptor::evict_slots(at, &slots[&at]);
|
||||
if reset > 0 {
|
||||
crate::descriptor::host::invalidate_list_views();
|
||||
}
|
||||
SLOT_EVICT[2].fetch_add(reset, Relaxed);
|
||||
let gone = {
|
||||
let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
|
||||
@@ -2932,6 +3003,13 @@ pub(crate) fn census() -> [u64; 10] {
|
||||
pub(crate) static HOST_TEXTURES: [std::sync::atomic::AtomicU64; 2] =
|
||||
[const { std::sync::atomic::AtomicU64::new(0) }; 2];
|
||||
|
||||
/// Bytes of host copies of textures the title fills that are alive now, for
|
||||
/// the RAM-pressure sweep's before/after freed-bytes measure.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn host_textures_alive_bytes() -> u64 {
|
||||
HOST_TEXTURES[1].load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// The bytes the host allocates for `texture`.
|
||||
#[cfg(windows)]
|
||||
fn host_bytes(texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource) -> u64 {
|
||||
@@ -3016,7 +3094,7 @@ impl Drop for HostTexture {
|
||||
/// (never released), for the memory line.
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
pub(crate) fn placed_textures() -> u64 {
|
||||
PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()).len() as u64
|
||||
PLACED_TEXTURES.read().unwrap_or_else(|e| e.into_inner()).len() as u64
|
||||
}
|
||||
|
||||
/// Moves the host texture to `wanted` (a host texture state); the host
|
||||
@@ -3076,6 +3154,36 @@ pub(crate) fn made_copy(this: This) -> Option<std::sync::Arc<HostTexture>> {
|
||||
hosted(this, false).map(|made| made.0)
|
||||
}
|
||||
|
||||
/// Why [`host_texture`] made no host texture.
|
||||
#[cfg(windows)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum NoTexture {
|
||||
/// The host will not make this description: not asked again.
|
||||
Refused,
|
||||
/// The card had no room then (`E_OUTOFMEMORY`), or there was no host
|
||||
/// yet: asked again on a later use (upstream VIctory #3198).
|
||||
ForNow,
|
||||
}
|
||||
|
||||
/// How long a texture the card had no room for waits before it is asked
|
||||
/// for again ([`Hosted::no_room`]): each ask is a `CreateCommittedResource`.
|
||||
#[cfg(windows)]
|
||||
const NO_ROOM_AGAIN_MS: u64 = 1000;
|
||||
|
||||
/// Host textures not made for lack of room, and made on a later use after
|
||||
/// that, since the start (for the memory line).
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
pub(crate) static NOT_MADE_FOR_NOW: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
pub(crate) static MADE_AFTER_NO_ROOM: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
/// What a failed host texture creation means for the texture: only a card
|
||||
/// out of memory is worth asking again.
|
||||
#[cfg(windows)]
|
||||
fn no_texture(code: HRESULT) -> NoTexture {
|
||||
if code == E_OUTOFMEMORY { NoTexture::ForNow } else { NoTexture::Refused }
|
||||
}
|
||||
|
||||
/// A host texture like the title's: same description, in GPU memory,
|
||||
/// without the console's layout and flags.
|
||||
#[cfg(windows)]
|
||||
@@ -3083,7 +3191,7 @@ fn host_texture(
|
||||
desc: &ResourceDesc,
|
||||
state: u32,
|
||||
clear: *const c_void,
|
||||
) -> Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
|
||||
) -> Result<windows::Win32::Graphics::Direct3D12::ID3D12Resource, NoTexture> {
|
||||
host_texture_as(desc, state, clear, false)
|
||||
}
|
||||
|
||||
@@ -3095,13 +3203,13 @@ fn host_texture_as(
|
||||
state: u32,
|
||||
clear: *const c_void,
|
||||
reserved: bool,
|
||||
) -> Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
|
||||
) -> Result<windows::Win32::Graphics::Direct3D12::ID3D12Resource, NoTexture> {
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
const PC_FLAGS: u32 = 0xf; // render target, depth, UAV, no shader access
|
||||
if desc.dimension == BUFFER {
|
||||
return None;
|
||||
return Err(NoTexture::Refused);
|
||||
}
|
||||
let host = crate::host::host()?;
|
||||
let host = crate::host::host().ok_or(NoTexture::ForNow)?;
|
||||
let mut d = *desc;
|
||||
d.layout = 0;
|
||||
d.alignment = 0;
|
||||
@@ -3168,7 +3276,7 @@ fn host_texture_as(
|
||||
crate::host::name(&t, || {
|
||||
format!("texture {}x{} f{} flags {:#x} (in a block)", d.width, d.height, d.format, d.flags)
|
||||
});
|
||||
return Some(t);
|
||||
return Ok(t);
|
||||
}
|
||||
let mut texture: Option<ID3D12Resource> = None;
|
||||
let made = if reserved {
|
||||
@@ -3203,24 +3311,32 @@ fn host_texture_as(
|
||||
)
|
||||
}
|
||||
};
|
||||
// Out of room may come back each second for many textures: its first
|
||||
// and then every power-of-two-th line only.
|
||||
let said = |e: &windows::core::Error, what: &str| {
|
||||
let why = no_texture(e.code().0);
|
||||
static NO_ROOM: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let n = (why == NoTexture::ForNow).then(|| NO_ROOM.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1);
|
||||
if n.is_none_or(u64::is_power_of_two) {
|
||||
tracing::warn!(error = %e, desc = ?d, reserved, ?why, times = n, "{what}");
|
||||
}
|
||||
why
|
||||
};
|
||||
if let Err(e) = &made {
|
||||
crate::residency::allocation_error(e);
|
||||
tracing::warn!(error = %e, desc = ?d, reserved, "no host texture");
|
||||
return Err(said(e, "no host texture"));
|
||||
}
|
||||
if !reserved
|
||||
&& made.is_ok()
|
||||
&& let Some(t) = &texture
|
||||
&& let Err(e) = crate::host::resident(&host.device, t).and_then(|()| crate::host::mapped(&host.device))
|
||||
{
|
||||
tracing::warn!(error = %e, desc = ?d, "a host texture is not resident");
|
||||
texture = None;
|
||||
return Err(said(&e, "a host texture is not resident"));
|
||||
}
|
||||
if let Some(t) = &texture {
|
||||
crate::host::name(t, || {
|
||||
format!("texture {}x{} f{} flags {:#x}", d.width, d.height, d.format, d.flags)
|
||||
});
|
||||
}
|
||||
texture
|
||||
let texture = texture.ok_or(NoTexture::Refused)?;
|
||||
crate::host::name(&texture, || {
|
||||
format!("texture {}x{} f{} flags {:#x}", d.width, d.height, d.format, d.flags)
|
||||
});
|
||||
Ok(texture)
|
||||
}
|
||||
|
||||
/// The host copy of title texture `this` if it is made and was made
|
||||
@@ -3368,6 +3484,7 @@ fn hand_out_resource(
|
||||
clear: (!clear.is_null()).then(|| unsafe { clear.cast::<[u32; 5]>().read_unaligned() }),
|
||||
used: std::sync::atomic::AtomicU64::new(0),
|
||||
refused: std::sync::atomic::AtomicBool::new(false),
|
||||
no_room: std::sync::atomic::AtomicU64::new(0),
|
||||
gone: std::sync::atomic::AtomicBool::new(false),
|
||||
placed: std::sync::atomic::AtomicBool::new(false),
|
||||
wanted: std::sync::atomic::AtomicU32::new(u32::MAX),
|
||||
@@ -3619,8 +3736,8 @@ pub(crate) extern "system" fn create_at_address(
|
||||
/// its host texture is let go when nothing names it any more
|
||||
/// ([`let_go_idle`]) and made again on the next use.
|
||||
#[cfg(windows)]
|
||||
static PLACED_TEXTURES: std::sync::Mutex<std::collections::BTreeMap<(u64, [u32; 14]), usize>> =
|
||||
std::sync::Mutex::new(std::collections::BTreeMap::new());
|
||||
static PLACED_TEXTURES: std::sync::RwLock<std::collections::BTreeMap<(u64, [u32; 14]), usize>> =
|
||||
std::sync::RwLock::new(std::collections::BTreeMap::new());
|
||||
|
||||
/// The placed textures asked for with filler words set, as asked
|
||||
/// (address and description): for [`PLACED_TWINS`]. Diagnostics builds
|
||||
@@ -3699,7 +3816,7 @@ pub(crate) fn texture_at_made(address: u64, desc: &[u32; 14]) -> Option<This> {
|
||||
let mut key = *desc;
|
||||
key[1] = 0;
|
||||
key[13] = 0;
|
||||
let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let map = PLACED_TEXTURES.read().unwrap_or_else(|e| e.into_inner());
|
||||
let found = map.get(&(address, key)).or_else(|| map.get(&(address, *desc)))?;
|
||||
Some(*found as This)
|
||||
}
|
||||
@@ -3732,7 +3849,13 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> {
|
||||
key[13] = 0;
|
||||
}
|
||||
let desc = &key;
|
||||
let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// Fast read-only path: 99.9%+ of placed-texture lookups during list
|
||||
// recording hit an existing resource and need no exclusive lock.
|
||||
#[cfg(not(feature = "diagnostics"))]
|
||||
if let Some(&r) = PLACED_TEXTURES.read().unwrap_or_else(|e| e.into_inner()).get(&(address, *desc)) {
|
||||
return Some(r as This);
|
||||
}
|
||||
let mut map = PLACED_TEXTURES.write().unwrap_or_else(|e| e.into_inner());
|
||||
// How many resources the filler alone would have added (a count for
|
||||
// the log: `placed_filler_twins`). Diagnostics builds only: without
|
||||
// that feature this whole block -- its mutex, its set, and its O(seen
|
||||
@@ -5355,6 +5478,14 @@ float4 lit() : SV_Target { return 1.0; }
|
||||
// `VICTORY_CARD_ROOM_FOR_TARGETS_SETTLE_MS=0`: kept as before.
|
||||
assert_eq!(targets_kept(most, 2432 * MIB, 600_000, 0), 640 * MIB);
|
||||
|
||||
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, 7_256 * MIB), 7_256 * MIB / 10 * 3);
|
||||
assert_eq!(targets_most(Some(1536 * MIB), 7 * GIB), 1536 * MIB);
|
||||
assert_eq!(targets_kept_from_peak(most, 390 * MIB, 390 * MIB), 195 * MIB);
|
||||
assert_eq!(targets_kept_from_peak(most, 0, 0), 256 * MIB);
|
||||
|
||||
// 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));
|
||||
assert_eq!(targets_seen(2000 * MIB, 1_000, 2064 * MIB, 9_000), (2064 * MIB, 9_000));
|
||||
|
||||
@@ -99,6 +99,14 @@ fn build() -> [u8; 32] {
|
||||
bytes.extend_from_slice(b"VICTORY_EARLY_DEPTH=1");
|
||||
bytes.push(0);
|
||||
}
|
||||
for name in ["VICTORY_LEGACY_MUL", "VICTORY_RDNA_FLOAT"] {
|
||||
if let Some(value) = std::env::var_os(name) {
|
||||
bytes.extend_from_slice(name.as_bytes());
|
||||
bytes.push(b'=');
|
||||
bytes.extend_from_slice(value.as_encoded_bytes());
|
||||
bytes.push(0);
|
||||
}
|
||||
}
|
||||
// And which clean-up passes ran over the translated code.
|
||||
bytes.extend_from_slice(&victory_shader::emit::shader_opt().to_le_bytes());
|
||||
bytes
|
||||
|
||||
@@ -560,6 +560,19 @@ fn window_mapped_most() -> u64 {
|
||||
})
|
||||
}
|
||||
|
||||
/// Maximum VRAM budget percentage up to which windows may be placed in card
|
||||
/// memory (`VICTORY_WINDOWS_VRAM_PERCENT`, 50..=95; default 80).
|
||||
fn window_vram_percent() -> u64 {
|
||||
static PCT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
|
||||
*PCT.get_or_init(|| {
|
||||
std::env::var("VICTORY_WINDOWS_VRAM_PERCENT")
|
||||
.ok()
|
||||
.and_then(|v| v.trim().parse().ok())
|
||||
.unwrap_or(80)
|
||||
.clamp(50, 95)
|
||||
})
|
||||
}
|
||||
|
||||
/// Bytes alive of windows in card memory the CPU maps.
|
||||
static WINDOW_MAPPED_BYTES: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
@@ -572,7 +585,7 @@ fn window_mapped_for(size: u64) -> Option<(ID3D12Resource, *mut u8)> {
|
||||
}
|
||||
let host = host()?;
|
||||
if let Some([budget, used, ..]) = host.video_memory()
|
||||
&& used + size > budget / 10 * 8
|
||||
&& used + size > budget * window_vram_percent() / 100
|
||||
{
|
||||
return None;
|
||||
}
|
||||
@@ -608,7 +621,7 @@ fn window_room_for(size: u64) -> Option<ID3D12Resource> {
|
||||
return None;
|
||||
}
|
||||
if let Some([budget, used, ..]) = host.video_memory()
|
||||
&& used + size > budget / 10 * 8
|
||||
&& used + size > budget * window_vram_percent() / 100
|
||||
{
|
||||
return None;
|
||||
}
|
||||
@@ -1381,14 +1394,14 @@ fn snapshots_kept() -> usize {
|
||||
/// the largest, and of those the largest one and the next ones up to `KEPT`
|
||||
/// bytes in all.
|
||||
fn give_back(v: Vec<u8>) {
|
||||
const KEPT: usize = 512 << 20;
|
||||
let cap: usize = if crate::residency::tight_host_ram() { 128 << 20 } else { 512 << 20 };
|
||||
let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
pool.push(v);
|
||||
pool.sort_by_key(|v| std::cmp::Reverse(v.capacity()));
|
||||
let (mut kept, mut total) = (0, 0usize);
|
||||
for v in pool.iter().take(snapshots_kept()) {
|
||||
total = total.saturating_add(v.capacity());
|
||||
if kept > 0 && total > KEPT {
|
||||
if kept > 0 && total > cap {
|
||||
break;
|
||||
}
|
||||
kept += 1;
|
||||
@@ -2432,6 +2445,228 @@ fn wc_no_back_min() -> u64 {
|
||||
/// were left on the card ([`wc_no_back`]), since the last frame-rate line.
|
||||
pub(crate) static WC_LEFT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Title memory the title asked for with read-only GPU page protection
|
||||
/// (`PAGE_GRAPHICS_READONLY` / `PAGE_GRAPHICS_EXECUTE` /
|
||||
/// `PAGE_GRAPHICS_EXECUTE_READ`, without `PAGE_GRAPHICS_READWRITE` or
|
||||
/// `PAGE_GRAPHICS_EXECUTE_READWRITE`). Kept sorted and merged as disjoint
|
||||
/// `[start, end)` intervals.
|
||||
///
|
||||
/// On console hardware the GPU MMU forbids shader stores to these pages.
|
||||
/// A title may still place one large buffer across adjacent regions of
|
||||
/// different GPU protections (for example a CPU-written constant ring with
|
||||
/// `PAGE_GRAPHICS_EXECUTE_READ` followed by GPU-written skinning pools with
|
||||
/// `PAGE_GRAPHICS_READWRITE`) and bind one raw UAV over the whole buffer.
|
||||
/// Subtracting these read-only intervals from shader UAV write declarations
|
||||
/// avoids false read-after-write waits on CPU constant fills and skips
|
||||
/// hashing/comparing pages shaders cannot write.
|
||||
static GPU_READONLY: RwLock<Vec<(u64, u64)>> = RwLock::new(Vec::new());
|
||||
|
||||
/// Lowest start and highest end across `GPU_READONLY` (both 0 when empty), for
|
||||
/// a lock-free fast path on hot shader write declarations.
|
||||
static GPU_READONLY_BOUNDS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
|
||||
|
||||
fn update_gpu_ro_bounds(all: &[(u64, u64)]) {
|
||||
let (lo, hi) = match (all.first(), all.last()) {
|
||||
(Some(&(first, _)), Some(&(_, last))) => (first, last),
|
||||
_ => (0, 0),
|
||||
};
|
||||
GPU_READONLY_BOUNDS[0].store(lo, Ordering::Relaxed);
|
||||
GPU_READONLY_BOUNDS[1].store(hi, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Whether shader UAV write declarations leave out what the title asked to
|
||||
/// be GPU-read-only (`VICTORY_GPU_RO_SKIP=1`; off by default until
|
||||
/// measured; never with `VICTORY_GPU_RO_CHECK=1`).
|
||||
///
|
||||
/// Memory the title protects with `PAGE_GRAPHICS_READONLY`,
|
||||
/// `PAGE_GRAPHICS_EXECUTE` or `PAGE_GRAPHICS_EXECUTE_READ` (the public
|
||||
/// `winnt.h` bits, as trustno1-coder/VIctory-NVIDIA#1014 reads them) is
|
||||
/// mapped read-only for the GPU, so no shader store can land there. A
|
||||
/// title may still bind one raw UAV over a buffer that spans such pages and
|
||||
/// writable ones (the world's 174 MB heap begins with 27 MB of
|
||||
/// CPU-written constants): what its shaders may write there was compared
|
||||
/// on the card after every submission, and CPU fills there waited for the
|
||||
/// flights. The picture cannot change: only bytes no shader can write are
|
||||
/// no longer looked at.
|
||||
pub(crate) fn gpu_ro_skip() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| !gpu_ro_check() && crate::switch::on("VICTORY_GPU_RO_SKIP"))
|
||||
}
|
||||
|
||||
/// Verification mode (`VICTORY_GPU_RO_CHECK=1`, off by default): keeps full
|
||||
/// UAV ranges declared and warns if any GPU compare pass ever sees a changed
|
||||
/// 64 KiB piece inside a GPU-read-only region.
|
||||
pub(crate) fn gpu_ro_check() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_GPU_RO_CHECK").is_some_and(|v| v == "1"))
|
||||
}
|
||||
|
||||
/// Bytes of shader UAV write declarations clipped away as GPU-read-only since
|
||||
/// the last frame-rate line.
|
||||
pub(crate) static GPU_RO_LEFT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Records `[at, at + len)` as GPU-read-only title memory.
|
||||
pub fn title_memory_gpu_readonly(at: usize, len: usize) {
|
||||
let Some(end) = (at as u64).checked_add(len as u64) else {
|
||||
return;
|
||||
};
|
||||
let start = at as u64;
|
||||
if len == 0 {
|
||||
return;
|
||||
}
|
||||
let mut all = GPU_READONLY.write().unwrap_or_else(|e| e.into_inner());
|
||||
let mut merged = Vec::with_capacity(all.len() + 1);
|
||||
let mut inserted = false;
|
||||
let (mut cur_s, mut cur_e) = (start, end);
|
||||
for &(a, b) in all.iter() {
|
||||
if b < cur_s {
|
||||
merged.push((a, b));
|
||||
} else if a > cur_e {
|
||||
if !inserted {
|
||||
merged.push((cur_s, cur_e));
|
||||
inserted = true;
|
||||
}
|
||||
merged.push((a, b));
|
||||
} else {
|
||||
cur_s = cur_s.min(a);
|
||||
cur_e = cur_e.max(b);
|
||||
}
|
||||
}
|
||||
if !inserted {
|
||||
merged.push((cur_s, cur_e));
|
||||
}
|
||||
*all = merged;
|
||||
update_gpu_ro_bounds(&all);
|
||||
drop(all);
|
||||
tracing::info!(
|
||||
start = format_args!("{start:#x}"),
|
||||
len = format_args!("{len:#x}"),
|
||||
"GPU-read-only title memory noted (VICTORY_GPU_RO_SKIP={})",
|
||||
u8::from(gpu_ro_skip())
|
||||
);
|
||||
}
|
||||
|
||||
/// Removes `[at, at + len)` from GPU-read-only tracking (splitting any larger
|
||||
/// interval that contains it).
|
||||
pub fn title_memory_gpu_writable(at: usize, len: usize) {
|
||||
if len == 0 {
|
||||
return;
|
||||
}
|
||||
let start = at as u64;
|
||||
let end = start.saturating_add(len as u64);
|
||||
let hi = GPU_READONLY_BOUNDS[1].load(Ordering::Relaxed);
|
||||
if hi <= start || GPU_READONLY_BOUNDS[0].load(Ordering::Relaxed) >= end {
|
||||
return;
|
||||
}
|
||||
let mut all = GPU_READONLY.write().unwrap_or_else(|e| e.into_inner());
|
||||
let mut next = Vec::with_capacity(all.len() + 1);
|
||||
for &(a, b) in all.iter() {
|
||||
if b <= start || a >= end {
|
||||
next.push((a, b));
|
||||
} else {
|
||||
if a < start {
|
||||
next.push((a, start));
|
||||
}
|
||||
if b > end {
|
||||
next.push((end, b));
|
||||
}
|
||||
}
|
||||
}
|
||||
*all = next;
|
||||
update_gpu_ro_bounds(&all);
|
||||
}
|
||||
|
||||
/// The title let go of `[at, at + len)` (`len` 0: the whole allocation at
|
||||
/// `at`): GPU-read-only intervals in it are forgotten.
|
||||
pub(crate) fn gpu_readonly_freed(at: usize, len: usize) {
|
||||
let start = at as u64;
|
||||
if GPU_READONLY_BOUNDS[1].load(Ordering::Relaxed) <= start {
|
||||
return;
|
||||
}
|
||||
if len != 0 {
|
||||
title_memory_gpu_writable(at, len);
|
||||
return;
|
||||
}
|
||||
// The whole allocation (its regions that share its base), while it is
|
||||
// still there: read-only parts noted at offsets in it go too.
|
||||
let mut end = start;
|
||||
// SAFETY: plain queries of our own address space.
|
||||
unsafe {
|
||||
use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery};
|
||||
loop {
|
||||
let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
|
||||
if VirtualQuery(end as *const _, &mut info, size_of::<MEMORY_BASIC_INFORMATION>()) == 0
|
||||
|| info.AllocationBase as u64 != start
|
||||
|| info.RegionSize == 0
|
||||
{
|
||||
break;
|
||||
}
|
||||
end = info.BaseAddress as u64 + info.RegionSize as u64;
|
||||
}
|
||||
}
|
||||
if end > start {
|
||||
title_memory_gpu_writable(at, (end - start) as usize);
|
||||
return;
|
||||
}
|
||||
let mut all = GPU_READONLY.write().unwrap_or_else(|e| e.into_inner());
|
||||
let before = all.len();
|
||||
all.retain(|&(a, _)| a != start);
|
||||
if all.len() != before {
|
||||
update_gpu_ro_bounds(&all);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `[start, start + len)` overlaps any GPU-read-only region.
|
||||
pub(crate) fn overlaps_gpu_readonly(start: u64, len: u64) -> bool {
|
||||
let end = start.saturating_add(len);
|
||||
if len == 0
|
||||
|| GPU_READONLY_BOUNDS[1].load(Ordering::Relaxed) <= start
|
||||
|| GPU_READONLY_BOUNDS[0].load(Ordering::Relaxed) >= end
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let all = GPU_READONLY.read().unwrap_or_else(|e| e.into_inner());
|
||||
let i = all.partition_point(|&(_, b)| b <= start);
|
||||
all.get(i).is_some_and(|&(a, _)| a < end)
|
||||
}
|
||||
|
||||
/// Subtracts GPU-read-only regions from `[start, start + len)`.
|
||||
/// Returns `None` when nothing overlaps (fast path, zero allocation), or
|
||||
/// `Some(remaining)` with the GPU-writable sub-ranges inside `[start, end)`.
|
||||
fn writable_subranges(start: u64, len: u64) -> Option<Vec<(u64, u64)>> {
|
||||
let end = start.saturating_add(len);
|
||||
if len == 0
|
||||
|| GPU_READONLY_BOUNDS[1].load(Ordering::Relaxed) <= start
|
||||
|| GPU_READONLY_BOUNDS[0].load(Ordering::Relaxed) >= end
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let all = GPU_READONLY.read().unwrap_or_else(|e| e.into_inner());
|
||||
let mut i = all.partition_point(|&(_, b)| b <= start);
|
||||
if all.get(i).is_none_or(|&(a, _)| a >= end) {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut cursor = start;
|
||||
while let Some(&(a, b)) = all.get(i) {
|
||||
if a >= end {
|
||||
break;
|
||||
}
|
||||
if a > cursor {
|
||||
out.push((cursor, a));
|
||||
}
|
||||
cursor = cursor.max(b.min(end));
|
||||
if cursor >= end {
|
||||
break;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
if cursor < end {
|
||||
out.push((cursor, end));
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Whether a title buffer in write-combined memory gets one copy, in card
|
||||
/// memory the CPU maps (`D3D12_HEAP_TYPE_GPU_UPLOAD`: a resizable BAR, this
|
||||
/// PC's 4070 SUPER has a 16 GiB one) instead of two sides
|
||||
@@ -2465,7 +2700,7 @@ fn wc_mapped_for(size: u64) -> Option<(ID3D12Resource, *mut u8)> {
|
||||
}
|
||||
let host = host()?;
|
||||
if let Some([budget, used, ..]) = host.video_memory()
|
||||
&& used + size > budget / 10 * 8
|
||||
&& used + size > budget * window_vram_percent() / 100
|
||||
{
|
||||
return None;
|
||||
}
|
||||
@@ -3492,6 +3727,33 @@ impl Shadow {
|
||||
list.defer_gpu_write(self, address as usize, len as usize);
|
||||
}
|
||||
|
||||
/// Shaders of `list` may write `[address, address + len)` through an
|
||||
/// unordered-access view. As [`Shadow::gpu_writes`] (which also serves
|
||||
/// copies we record ourselves), but with [`gpu_ro_skip`] the parts the
|
||||
/// title asked to be GPU-read-only ([`title_memory_gpu_readonly`]) are
|
||||
/// left out: the console's GPU cannot write them.
|
||||
/// After mikael-jarvinen, trustno1-coder/VIctory-NVIDIA#1014, and
|
||||
/// sagouindupm/Mandy commit d384243 (GPL-3.0-or-later).
|
||||
pub(crate) fn shader_writes(self: &Arc<Self>, list: &HostList, address: u64, len: u64, pipeline: usize) {
|
||||
if gpu_ro_skip() && self.place.is_none() {
|
||||
let len = len.min(self.left(address));
|
||||
if let Some(ranges) = writable_subranges(address, len) {
|
||||
let kept: u64 = ranges.iter().map(|&(a, b)| b - a).sum();
|
||||
GPU_RO_LEFT.fetch_add(len - kept, Ordering::Relaxed);
|
||||
for (a, b) in ranges {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::host::wide_write(a, b - a, pipeline);
|
||||
self.gpu_writes(list, a, b - a);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::host::wide_write(address, len, pipeline);
|
||||
let _ = pipeline;
|
||||
self.gpu_writes(list, address, len);
|
||||
}
|
||||
|
||||
/// Whether all of the copy's title memory was asked for write-combined
|
||||
/// ([`title_memory_write_combined`]); found once.
|
||||
fn write_combined(&self) -> bool {
|
||||
@@ -3912,6 +4174,26 @@ impl Shadow {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Shadow::changed`] for multiple offset ranges under a single `kept` lock.
|
||||
fn changed_runs(&self, runs: impl Iterator<Item = (usize, usize)>) {
|
||||
if !keeps() {
|
||||
return;
|
||||
}
|
||||
let mut runs = runs.filter(|r| r.0 < r.1).peekable();
|
||||
if runs.peek().is_none() {
|
||||
return;
|
||||
}
|
||||
let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if kept.0.is_empty() {
|
||||
return;
|
||||
}
|
||||
for (from, to) in runs {
|
||||
for piece in self.pieces(from, to) {
|
||||
kept.0[piece] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether shaders of a submission not yet copied back may be writing
|
||||
/// the copy.
|
||||
#[inline]
|
||||
@@ -4216,6 +4498,12 @@ impl Shadow {
|
||||
/// nothing, and knows it without asking anything
|
||||
/// (`crate::watch::nothing_new`). `false` if it would have to ask.
|
||||
pub(crate) fn nothing_new(&self, address: usize, len: usize) -> bool {
|
||||
let j = crate::watch::read_journal();
|
||||
self.nothing_new_in(&j, address, len)
|
||||
}
|
||||
|
||||
/// [`Shadow::nothing_new`] using an already-held write-watch journal read guard.
|
||||
pub(crate) fn nothing_new_in(&self, j: &crate::watch::JournalGuard, address: usize, len: usize) -> bool {
|
||||
if self.place.is_some() {
|
||||
return true;
|
||||
}
|
||||
@@ -4235,7 +4523,7 @@ impl Shadow {
|
||||
}
|
||||
let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let ranged = Self::ranged_in(&copied.1, from, to);
|
||||
let same = crate::watch::nothing_new(from, to, start / PAGE, &copied.0, ranged);
|
||||
let same = crate::watch::nothing_new_in(j, from, to, start / PAGE, &copied.0, ranged);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if same {
|
||||
use crate::copystat::{C, add};
|
||||
@@ -4255,11 +4543,15 @@ impl Shadow {
|
||||
/// [`Shadow::update`] of `[from, to)` (inside the buffer) where no
|
||||
/// shader writes.
|
||||
fn update_free(&self, from: usize, to: usize) -> usize {
|
||||
if self.watched.load(Ordering::Relaxed) != NOT_WATCHED {
|
||||
let prev = self.watched.load(Ordering::Relaxed);
|
||||
if prev != NOT_WATCHED {
|
||||
if let Some((now, written)) = crate::watch::writes(from, to, true) {
|
||||
// (A range whose blocks rest after a write has no guard now.)
|
||||
let guarded = crate::watch::guarded(from, to) || self.watched.load(Ordering::Relaxed) == GUARDED;
|
||||
self.watched.store(if guarded { GUARDED } else { 1 }, Ordering::Relaxed);
|
||||
let guarded = prev == GUARDED || crate::watch::guarded(from, to);
|
||||
let next = if guarded { GUARDED } else { 1 };
|
||||
if next != prev {
|
||||
self.watched.store(next, Ordering::Relaxed);
|
||||
}
|
||||
let copied = self.copy_stale(from, to, now, &written);
|
||||
self.refresh_check(from, to);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
@@ -4393,8 +4685,14 @@ impl Shadow {
|
||||
if let Some((first, known)) = run {
|
||||
runs.push(((first * PAGE).max(from), ((last + 1) * PAGE).min(to), known));
|
||||
}
|
||||
let runs = by_parts(runs, &again_at, &crate::watch::parts_written(&again_at));
|
||||
let bytes = self.take_all(runs);
|
||||
let bytes = if runs.is_empty() {
|
||||
0
|
||||
} else if again_at.is_empty() {
|
||||
self.take_all(runs)
|
||||
} else {
|
||||
let runs = by_parts(runs, &again_at, &crate::watch::parts_written(&again_at));
|
||||
self.take_all(runs)
|
||||
};
|
||||
if crate::watch::light() {
|
||||
// All of the range is in the copy as of this asking.
|
||||
let ranged = &mut copied.1;
|
||||
@@ -4532,6 +4830,7 @@ impl Shadow {
|
||||
};
|
||||
let whole = !known && card.before.get().is_none();
|
||||
let start = self.start as usize;
|
||||
let (mut send0, mut send1, mut send2, mut send3) = (0u64, 0u64, 0u64, 0u64);
|
||||
TITLE.with_borrow_mut(|title| {
|
||||
title.resize(PAGE, 0);
|
||||
let mut at = from;
|
||||
@@ -4546,24 +4845,37 @@ 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) };
|
||||
let mut page_bytes = 0u64;
|
||||
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);
|
||||
page_bytes += len as u64;
|
||||
}
|
||||
if !runs.is_empty() {
|
||||
self.changed_runs(runs.iter().map(|&(a, len)| (at - start + a, at - start + a + len)));
|
||||
self.card_changed_runs(runs.iter().map(|&(a, len)| (at - start + a, at - start + a + len)));
|
||||
}
|
||||
self.card_changed_runs(runs.iter().map(|&(a, len)| (at - start + a, at - start + a + len)));
|
||||
if let Some(was) = was {
|
||||
crate::host::upcheck::note(self.id, at - start, &was, held);
|
||||
}
|
||||
SEND[0].fetch_add(n as u64, Ordering::Relaxed);
|
||||
send0 += n as u64;
|
||||
if runs.is_empty() {
|
||||
SEND[1].fetch_add(n as u64, Ordering::Relaxed);
|
||||
send1 += n as u64;
|
||||
} else {
|
||||
send2 += page_bytes;
|
||||
send3 += runs.len() as u64;
|
||||
}
|
||||
SEND[2].fetch_add(runs.iter().map(|r| r.1 as u64).sum(), Ordering::Relaxed);
|
||||
SEND[3].fetch_add(runs.len() as u64, Ordering::Relaxed);
|
||||
at += n;
|
||||
}
|
||||
});
|
||||
SEND[0].fetch_add(send0, Ordering::Relaxed);
|
||||
if send1 != 0 {
|
||||
SEND[1].fetch_add(send1, Ordering::Relaxed);
|
||||
}
|
||||
if send2 != 0 {
|
||||
SEND[2].fetch_add(send2, Ordering::Relaxed);
|
||||
SEND[3].fetch_add(send3, Ordering::Relaxed);
|
||||
}
|
||||
to - from
|
||||
}
|
||||
|
||||
@@ -6161,6 +6473,100 @@ mod window_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod gpu_readonly_tests {
|
||||
use super::{
|
||||
gpu_readonly_freed, overlaps_gpu_readonly, title_memory_gpu_readonly, title_memory_gpu_writable,
|
||||
writable_subranges,
|
||||
};
|
||||
|
||||
/// Simulates a single placed buffer spanning a GPU-read-only CPU constant
|
||||
/// ring followed by GPU-read-write pools: subtracting GPU-read-only pages
|
||||
/// keeps only the writable suffix.
|
||||
#[test]
|
||||
fn clips_gpu_readonly_prefix_and_keeps_writable_suffix() {
|
||||
let base = 0x7e10_0000_0000usize;
|
||||
let ro_len = 0x0100_0000usize; // 16 MiB GPU-read-only constant ring
|
||||
let rw_len = 0x09e0_0000usize; // ~158 MiB GPU-writable pools
|
||||
let total = (ro_len + rw_len) as u64;
|
||||
|
||||
title_memory_gpu_readonly(base, ro_len);
|
||||
title_memory_gpu_writable(base + ro_len, rw_len);
|
||||
|
||||
assert_eq!(
|
||||
writable_subranges(base as u64, total),
|
||||
Some(vec![((base + ro_len) as u64, base as u64 + total)])
|
||||
);
|
||||
assert!(overlaps_gpu_readonly(base as u64, 0x1000));
|
||||
assert!(overlaps_gpu_readonly((base + ro_len - 0x1000) as u64, 0x2000));
|
||||
assert!(!overlaps_gpu_readonly((base + ro_len) as u64, 0x1000));
|
||||
assert_eq!(writable_subranges((base + ro_len) as u64, rw_len as u64), None);
|
||||
|
||||
gpu_readonly_freed(base, ro_len + rw_len);
|
||||
assert_eq!(writable_subranges(base as u64, total), None);
|
||||
}
|
||||
|
||||
/// Middle holes split into two writable ranges, wholly read-only ranges
|
||||
/// return an empty list, and disjoint ranges take the fast `None` path.
|
||||
#[test]
|
||||
fn splits_middle_hole_suffix_and_whole_ro() {
|
||||
let base = 0x7e20_0000_0000usize;
|
||||
title_memory_gpu_readonly(base + 0x2_0000, 0x3_0000);
|
||||
|
||||
// Wholly inside RO.
|
||||
assert_eq!(writable_subranges((base + 0x2_0000) as u64, 0x3_0000), Some(vec![]));
|
||||
assert_eq!(writable_subranges((base + 0x3_0000) as u64, 0x1_0000), Some(vec![]));
|
||||
|
||||
// Middle RO hole splits into two writable halves.
|
||||
assert_eq!(
|
||||
writable_subranges(base as u64, 0x8_0000),
|
||||
Some(vec![
|
||||
(base as u64, (base + 0x2_0000) as u64),
|
||||
((base + 0x5_0000) as u64, (base + 0x8_0000) as u64),
|
||||
])
|
||||
);
|
||||
|
||||
// Suffix RO leaves prefix only.
|
||||
assert_eq!(
|
||||
writable_subranges(base as u64, 0x4_0000),
|
||||
Some(vec![(base as u64, (base + 0x2_0000) as u64)])
|
||||
);
|
||||
|
||||
// Disjoint ranges before and after take the fast None path.
|
||||
assert_eq!(writable_subranges(base as u64, 0x2_0000), None);
|
||||
assert_eq!(writable_subranges((base + 0x5_0000) as u64, 0x3_0000), None);
|
||||
|
||||
gpu_readonly_freed(base + 0x2_0000, 0);
|
||||
assert!(!overlaps_gpu_readonly((base + 0x2_0000) as u64, 0x3_0000));
|
||||
}
|
||||
|
||||
/// Adjacent/overlapping read-only intervals merge, and marking a sub-range
|
||||
/// writable splits or clears them cleanly.
|
||||
#[test]
|
||||
fn merges_and_splits_gpu_readonly_intervals() {
|
||||
let base = 0x7e30_0000_0000usize;
|
||||
title_memory_gpu_readonly(base, 0x2_0000);
|
||||
title_memory_gpu_readonly(base + 0x2_0000, 0x2_0000); // adjacent
|
||||
title_memory_gpu_readonly(base + 0x3_0000, 0x3_0000); // overlapping -> [0..0x6_0000)
|
||||
|
||||
assert_eq!(writable_subranges(base as u64, 0x6_0000), Some(vec![]));
|
||||
|
||||
// Carve out [0x2_0000..0x4_0000) as writable.
|
||||
title_memory_gpu_writable(base + 0x2_0000, 0x2_0000);
|
||||
assert_eq!(
|
||||
writable_subranges(base as u64, 0x6_0000),
|
||||
Some(vec![((base + 0x2_0000) as u64, (base + 0x4_0000) as u64)])
|
||||
);
|
||||
assert!(overlaps_gpu_readonly(base as u64, 0x1_0000));
|
||||
assert!(!overlaps_gpu_readonly((base + 0x2_0000) as u64, 0x2_0000));
|
||||
assert!(overlaps_gpu_readonly((base + 0x5_0000) as u64, 0x1_0000));
|
||||
|
||||
// Clean up both halves.
|
||||
gpu_readonly_freed(base, 0x6_0000);
|
||||
assert!(!overlaps_gpu_readonly(base as u64, 0x6_0000));
|
||||
}
|
||||
}
|
||||
|
||||
/// For device-removed reports: the copy of title memory whose host range
|
||||
/// starts closest below host GPU address `va`, and where `va` is in it.
|
||||
pub(crate) fn near(va: u64) -> String {
|
||||
|
||||
@@ -283,6 +283,8 @@ struct Calls {
|
||||
framegen_on: bool,
|
||||
framegen_times: u32,
|
||||
simulating: Option<u32>,
|
||||
/// Whether Reflex low latency is on ([`set_reflex`]).
|
||||
reflex_on: bool,
|
||||
}
|
||||
|
||||
static CALLS: Mutex<Calls> = Mutex::new(Calls {
|
||||
@@ -291,6 +293,7 @@ static CALLS: Mutex<Calls> = Mutex::new(Calls {
|
||||
framegen_on: false,
|
||||
framegen_times: 0,
|
||||
simulating: None,
|
||||
reflex_on: false,
|
||||
});
|
||||
|
||||
fn calls() -> std::sync::MutexGuard<'static, Calls> {
|
||||
@@ -930,18 +933,11 @@ pub(crate) fn device_made(device: &ID3D12Device) -> Option<ID3D12CommandQueue> {
|
||||
&& functions.reflex_set_options.is_some()
|
||||
&& functions.pcl_set_marker.is_some();
|
||||
if have {
|
||||
if let Some(reflex) = functions.reflex_set_options {
|
||||
let options = abi::ReflexOptions {
|
||||
base: abi::BaseStructure::new(abi::REFLEX_OPTIONS, 1),
|
||||
mode: abi::REFLEX_LOW_LATENCY,
|
||||
frame_limit_us: 0,
|
||||
use_markers_to_optimize: false,
|
||||
virtual_key: 0,
|
||||
id_thread: 0,
|
||||
};
|
||||
// SAFETY: filled options.
|
||||
let code = unsafe { reflex(&options) };
|
||||
tracing::info!(code, result = abi::result_name(code), "Streamline: Reflex low latency on (needed by frame generation)");
|
||||
// Only while frame generation is on: ready but off, Reflex's
|
||||
// pacing can put the submitting thread to sleep in Present.
|
||||
if framegen_times() != 0 {
|
||||
set_reflex(&functions, true);
|
||||
calls().reflex_on = true;
|
||||
}
|
||||
queue = proxied_queue(sl, device);
|
||||
}
|
||||
@@ -954,6 +950,27 @@ pub(crate) fn device_made(device: &ID3D12Device) -> Option<ID3D12CommandQueue> {
|
||||
queue
|
||||
}
|
||||
|
||||
/// Reflex low latency on (frame generation needs it) or off.
|
||||
fn set_reflex(functions: &Functions, on: bool) {
|
||||
let Some(reflex) = functions.reflex_set_options else { return };
|
||||
let options = abi::ReflexOptions {
|
||||
base: abi::BaseStructure::new(abi::REFLEX_OPTIONS, 1),
|
||||
mode: if on { abi::REFLEX_LOW_LATENCY } else { abi::REFLEX_OFF },
|
||||
frame_limit_us: 0,
|
||||
use_markers_to_optimize: false,
|
||||
virtual_key: 0,
|
||||
id_thread: 0,
|
||||
};
|
||||
// SAFETY: filled options.
|
||||
let code = unsafe { reflex(&options) };
|
||||
tracing::info!(
|
||||
on,
|
||||
code,
|
||||
result = abi::result_name(code),
|
||||
"Streamline: Reflex low latency (only while frame generation is on)"
|
||||
);
|
||||
}
|
||||
|
||||
fn log_version(sl: &Sl, feature: u32, name: &str) {
|
||||
let mut version = abi::FeatureVersion {
|
||||
base: abi::BaseStructure::new(abi::FEATURE_VERSION, 1),
|
||||
@@ -1807,6 +1824,10 @@ pub(crate) fn present_begins(frame: u64, planes: Planes<'_>) -> Option<Presentin
|
||||
}
|
||||
}
|
||||
let wanted = framegen_wanted();
|
||||
if (wanted != 0) != calls.reflex_on {
|
||||
set_reflex(functions, wanted != 0);
|
||||
calls.reflex_on = wanted != 0;
|
||||
}
|
||||
let on = on && wanted != 0;
|
||||
let times = if on { wanted } else { 0 };
|
||||
if on != calls.framegen_on || times != calls.framegen_times {
|
||||
@@ -1814,8 +1835,7 @@ pub(crate) fn present_begins(frame: u64, planes: Planes<'_>) -> Option<Presentin
|
||||
// `VICTORY_FRAMEGEN_X=2..6`: frames shown for each one rendered (2 unless set), no more
|
||||
// than this card and driver generate (the state says how many: 5 on an RTX 50).
|
||||
let mut generated = wanted.max(2) - 1;
|
||||
if on
|
||||
&& generated > 1
|
||||
if generated > 1
|
||||
&& let Some(get_state) = functions.dlssg_get_state
|
||||
{
|
||||
let mut state = abi::DlssgState::default();
|
||||
@@ -2005,11 +2025,57 @@ pub(crate) fn present_ends(presenting: Option<Presenting>) {
|
||||
"DLSS Frame Generation status changed (0 ok, 1 output too small, 2 Reflex not seen, 4 HDR format, 8 constants invalid, 16 back buffer index not asked)"
|
||||
);
|
||||
}
|
||||
let (count, rearm) = stuck_step(
|
||||
FG_STUCK.load(Relaxed),
|
||||
calls.framegen_times,
|
||||
state.num_frames_actually_presented,
|
||||
rearm_after(),
|
||||
);
|
||||
FG_STUCK.store(count, Relaxed);
|
||||
if rearm && let Some(set_options) = functions.dlssg_set_options {
|
||||
let options = abi::DlssgOptions::new(abi::DLSSG_OFF);
|
||||
// SAFETY: filled options for viewport 0, on the presenting thread.
|
||||
let code = unsafe { set_options(&viewport, &options) };
|
||||
calls.framegen_on = false;
|
||||
calls.framegen_times = 0;
|
||||
FG_PER.store(1, Relaxed);
|
||||
let rearms = FG_REARMS.fetch_add(1, Relaxed) + 1;
|
||||
tracing::warn!(
|
||||
frame,
|
||||
presents = rearm_after(),
|
||||
rearms,
|
||||
code,
|
||||
"DLSS Frame Generation showed one frame a present that long with more asked: switched off to re-arm"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
spent(T_AFTER, began);
|
||||
}
|
||||
|
||||
static FG_STUCK: AtomicU32 = AtomicU32::new(0);
|
||||
static FG_REARMS: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
/// `VICTORY_FRAMEGEN_REARM=<presents>`: presents in a row with 1 frame shown
|
||||
/// while >=2 are asked before switching DLSS FG off and on again (90 default; 0 off).
|
||||
fn rearm_after() -> u32 {
|
||||
static AFTER: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
|
||||
*AFTER.get_or_init(|| {
|
||||
std::env::var("VICTORY_FRAMEGEN_REARM")
|
||||
.ok()
|
||||
.and_then(|v| v.trim().parse().ok())
|
||||
.unwrap_or(90)
|
||||
})
|
||||
}
|
||||
|
||||
fn stuck_step(count: u32, asked: u32, shown: u32, limit: u32) -> (u32, bool) {
|
||||
if limit == 0 || asked < 2 || shown >= 2 {
|
||||
return (0, false);
|
||||
}
|
||||
let count = count + 1;
|
||||
if count >= limit { (0, true) } else { (count, false) }
|
||||
}
|
||||
|
||||
/// Our swap chain's buffers are about to be made again: frame generation is
|
||||
/// off until the next present with an upscaling (Streamline asks so).
|
||||
pub(crate) fn resizing() {
|
||||
|
||||
@@ -110,12 +110,22 @@ struct Last {
|
||||
/// first checks, and after the hash found a change the guard had not
|
||||
/// seen ([`hot_textures`]). 0: not checked under the guard yet.
|
||||
hot_until: u64,
|
||||
/// Cached negative result from write-watch (`writes(..., false)` returned
|
||||
/// `None` or the range is already guarded view memory), avoiding a
|
||||
/// guaranteed-failing `GetWriteWatch` syscall on every refresh.
|
||||
not_watched: bool,
|
||||
}
|
||||
|
||||
/// Frames a guarded texture is hashed at every check from its first check,
|
||||
/// and after the hash found a change the guard did not see.
|
||||
/// Frames a guarded texture is hashed at every check after the hash found
|
||||
/// a change the guard did not see.
|
||||
const HOT_FRAMES: u64 = 64;
|
||||
|
||||
/// Initial hot frames on a guarded texture's very first check: long enough
|
||||
/// to catch ring-of-3 animated/video textures (which then promote to full
|
||||
/// [`HOT_FRAMES`] via `found_blind`), without forcing hundreds of megabytes
|
||||
/// of static cutscene/world textures to be re-hashed every frame for 64 frames.
|
||||
const START_HOT_FRAMES: u64 = 4;
|
||||
|
||||
/// Whether a guarded texture whose memory the hash found changed although
|
||||
/// the guard saw no write is hashed at every check for a while
|
||||
/// ([`HOT_FRAMES`]), not every eighth frame. A title that writes such a
|
||||
@@ -1449,20 +1459,26 @@ impl Staging {
|
||||
if alone && !exact && last.hash.is_some() {
|
||||
return 0;
|
||||
}
|
||||
if !alone && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) {
|
||||
if !exact && last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) {
|
||||
return 0;
|
||||
if !alone && !last.not_watched {
|
||||
if crate::watch::guarded(start, start + size) {
|
||||
last.not_watched = true;
|
||||
} else if let Some((now, changed)) = waited(1, || crate::watch::writes_since(start, start + size, false, last.asked)) {
|
||||
if !exact && !changed {
|
||||
return 0;
|
||||
}
|
||||
last.asked = now;
|
||||
// Read through the copy, which stands unmapped pages: memory of
|
||||
// big pools is too slow to ask page by page.
|
||||
with_read(size, |read| {
|
||||
crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false);
|
||||
self.detile(read);
|
||||
});
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::copystat::add(crate::copystat::C::TexWatched, size as u64);
|
||||
return size;
|
||||
} else {
|
||||
last.not_watched = true;
|
||||
}
|
||||
last.asked = now;
|
||||
// Read through the copy, which stands unmapped pages: memory of
|
||||
// big pools is too slow to ask page by page.
|
||||
with_read(size, |read| {
|
||||
crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false);
|
||||
self.detile(read);
|
||||
});
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::copystat::add(crate::copystat::C::TexWatched, size as u64);
|
||||
return size;
|
||||
}
|
||||
// View memory has no write-watch, and a texture there was hashed
|
||||
// whole at every check: 229 MB and 51 ms a frame in a gameplay view
|
||||
@@ -1479,19 +1495,20 @@ impl Staging {
|
||||
let mut blind = false;
|
||||
if !alone
|
||||
&& *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0"))
|
||||
&& let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, true))
|
||||
&& let Some((now, changed)) = waited(1, || crate::watch::writes_since(start, start + size, true, last.asked))
|
||||
{
|
||||
const HASH_EVERY: u64 = 8;
|
||||
let unwritten = last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked);
|
||||
let unwritten = !changed;
|
||||
last.asked = now;
|
||||
let frame = crate::frame::current();
|
||||
let turn = frame
|
||||
.wrapping_add((start >> 16) as u64)
|
||||
.is_multiple_of(HASH_EVERY);
|
||||
// A texture starts hot: one written that way from its first
|
||||
// frames on changes before the hash has ever caught it.
|
||||
// A texture starts hot briefly: one written through an alias view
|
||||
// from its first frames on changes within 1-3 frames and is then
|
||||
// promoted to full `HOT_FRAMES` by `found_blind`.
|
||||
if last.hot_until == 0 {
|
||||
last.hot_until = frame + HOT_FRAMES;
|
||||
last.hot_until = frame + START_HOT_FRAMES;
|
||||
}
|
||||
let hot = hot_textures() && frame < last.hot_until;
|
||||
if !exact && unwritten && !turn && !hot {
|
||||
|
||||
+192
-64
@@ -164,6 +164,14 @@ fn journal_mut() -> std::sync::RwLockWriteGuard<'static, Journal> {
|
||||
waited(2, || JOURNAL.write().unwrap_or_else(|e| e.into_inner()))
|
||||
}
|
||||
|
||||
/// Shared read guard over the write-watch journal so a batch of `nothing_new`
|
||||
/// checks can acquire the lock once instead of per buffer.
|
||||
pub(crate) struct JournalGuard(std::sync::RwLockReadGuard<'static, Journal>);
|
||||
|
||||
pub(crate) fn read_journal() -> JournalGuard {
|
||||
JournalGuard(journal())
|
||||
}
|
||||
|
||||
/// Since the last line: waits and nanoseconds of waiting, of all threads, for
|
||||
/// the ranges held ([`ASKING`]), the journal to read it, the journal to note
|
||||
/// in it, and the guards (faults of the title's among them).
|
||||
@@ -261,6 +269,14 @@ thread_local! {
|
||||
fn kernel_written(first: usize, last: usize) -> Option<Vec<(usize, u16)>> {
|
||||
use windows_sys::Win32::System::Memory::GetWriteWatch;
|
||||
const WRITE_WATCH_FLAG_RESET: u32 = 1;
|
||||
// Every call, refused ones too: the 4 KiB pages it walks, and its whole
|
||||
// time (until `_whole` is dropped, the answer made).
|
||||
#[cfg(feature = "diagnostics")]
|
||||
let _whole = {
|
||||
tally(13, 1);
|
||||
tally(14, ((last - first) * PAGE / KERNEL_PAGE) as u64);
|
||||
Tallied(15, std::time::Instant::now())
|
||||
};
|
||||
FOUND.with(|found| {
|
||||
let mut found = found.borrow_mut();
|
||||
let mut count = (last - first) * PAGE / KERNEL_PAGE;
|
||||
@@ -367,17 +383,33 @@ pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) {
|
||||
if kept_active() {
|
||||
return;
|
||||
}
|
||||
let skip_guarded = light();
|
||||
let mut pieces: Vec<(usize, usize)> = ranges
|
||||
.iter()
|
||||
// Not view memory known by its bits: the kernel would refuse the
|
||||
// asking (and, asked together with others, theirs).
|
||||
// Not view memory known by its bits or guarded read-only: the kernel
|
||||
// would refuse the asking (and, asked together with others, theirs).
|
||||
.filter(|r| r.0 < r.1 && !published(r.0, r.1))
|
||||
.map(|&(start, end)| (start / PAGE, end.div_ceil(PAGE)))
|
||||
.filter(|&(first, last)| !(skip_guarded && PROTECTED.any(first, last)))
|
||||
.collect();
|
||||
if pieces.len() < 2 {
|
||||
return;
|
||||
}
|
||||
pieces.sort_unstable();
|
||||
// Collapse duplicate or fully-contained page spans before asking.
|
||||
let mut write = 0usize;
|
||||
for read in 1..pieces.len() {
|
||||
let (a, b) = pieces[read];
|
||||
if a >= pieces[write].0 && b <= pieces[write].1 {
|
||||
continue;
|
||||
}
|
||||
write += 1;
|
||||
pieces[write] = (a, b);
|
||||
}
|
||||
pieces.truncate(write + 1);
|
||||
if pieces.len() < 2 {
|
||||
return;
|
||||
}
|
||||
let _all = Asking::hold_all();
|
||||
let (mut asked, mut written) = (Vec::new(), Vec::new());
|
||||
let mut i = 0;
|
||||
@@ -392,7 +424,7 @@ pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) {
|
||||
last = last.max(pieces[k].1);
|
||||
k += 1;
|
||||
}
|
||||
ask_run(&pieces[i..k], &mut asked, &mut written);
|
||||
ask_run(&pieces[i..k], &mut asked, &mut written, false);
|
||||
i = k;
|
||||
}
|
||||
sort_merge_ahead(&mut asked);
|
||||
@@ -578,63 +610,63 @@ pub(crate) fn once() -> bool {
|
||||
}
|
||||
|
||||
/// With [`once`]: asks about `ranges` (everything a submission's lists
|
||||
/// refresh) as [`ask_ahead`] does, and lets that asking stand until
|
||||
/// [`ask_once_end`].
|
||||
/// refresh) in a single pass (merged runs and isolated ranges together) and
|
||||
/// lets that asking stand until [`ask_once_end`].
|
||||
pub(crate) fn ask_once(ranges: &[(usize, usize)]) {
|
||||
if !once() {
|
||||
return;
|
||||
}
|
||||
ask_once_end();
|
||||
ask_ahead(ranges);
|
||||
ask_rest(ranges);
|
||||
}
|
||||
|
||||
/// [`ask_once`] after its [`ask_ahead`]: what that left to `writes`, and the
|
||||
/// asking stands.
|
||||
fn ask_rest(ranges: &[(usize, usize)]) {
|
||||
let _all = Asking::hold_all();
|
||||
let mut ahead = {
|
||||
let mut j = journal_mut();
|
||||
std::mem::take(&mut j.ahead)
|
||||
};
|
||||
// `ask_ahead` leaves a range that lies alone to `writes`, which asks
|
||||
// once per flush: with one asking for the submission that was every
|
||||
// such range asked again at each of its 70 flushes (run 76: 2,300
|
||||
// askings a frame with the switch on, as without it). They are asked
|
||||
// here, once; what is not write-watched stays with `writes`.
|
||||
let mut written = Vec::new();
|
||||
let mut extra = Vec::new();
|
||||
for &(start, end) in ranges {
|
||||
if start >= end || published(start, end) {
|
||||
let skip_guarded = light();
|
||||
let mut pieces: Vec<(usize, usize)> = ranges
|
||||
.iter()
|
||||
.filter(|r| r.0 < r.1 && !published(r.0, r.1))
|
||||
.map(|&(start, end)| (start / PAGE, end.div_ceil(PAGE)))
|
||||
.filter(|&(first, last)| !(skip_guarded && PROTECTED.any(first, last)))
|
||||
.collect();
|
||||
if pieces.is_empty() {
|
||||
return;
|
||||
}
|
||||
pieces.sort_unstable();
|
||||
// Collapse exact duplicates and fully-contained page spans in O(N).
|
||||
let mut write = 0usize;
|
||||
for read in 1..pieces.len() {
|
||||
let (a, b) = pieces[read];
|
||||
if a >= pieces[write].0 && b <= pieces[write].1 {
|
||||
continue;
|
||||
}
|
||||
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
|
||||
if !ahead_contains(&ahead, first, last)
|
||||
&& !extra.iter().any(|&(a, b)| a <= first && last <= b)
|
||||
&& let Some(pages) = kernel_written(first, last)
|
||||
write += 1;
|
||||
pieces[write] = (a, b);
|
||||
}
|
||||
pieces.truncate(write + 1);
|
||||
let _all = Asking::hold_all();
|
||||
let (mut asked, mut written) = (Vec::new(), Vec::new());
|
||||
let mut i = 0;
|
||||
while i < pieces.len() {
|
||||
let first = pieces[i].0;
|
||||
let mut last = pieces[i].1;
|
||||
let mut k = i + 1;
|
||||
while k < pieces.len()
|
||||
&& pieces[k].0 <= last + AHEAD_GAP
|
||||
&& last.max(pieces[k].1) - first <= AHEAD_MAX
|
||||
{
|
||||
written.extend(pages);
|
||||
extra.push((first, last));
|
||||
last = last.max(pieces[k].1);
|
||||
k += 1;
|
||||
}
|
||||
ask_run(&pieces[i..k], &mut asked, &mut written, true);
|
||||
i = k;
|
||||
}
|
||||
if !extra.is_empty() {
|
||||
ahead.extend(extra);
|
||||
sort_merge_ahead(&mut ahead);
|
||||
}
|
||||
sort_merge_ahead(&mut asked);
|
||||
note_hot(&written);
|
||||
let mut j = journal_mut();
|
||||
// A number of its own, and the one this asking stands under: between
|
||||
// the two parts another thread may have asked about a range of the
|
||||
// second, copied it, and the title written it since. Under the first
|
||||
// part's number that write was older than the copy, and never copied.
|
||||
let now = next_asking();
|
||||
j.ahead_asked = now;
|
||||
for (page, parts) in written {
|
||||
j.note(page, parts, now);
|
||||
}
|
||||
let kept = !ahead.is_empty();
|
||||
let kept = !asked.is_empty();
|
||||
j.kept = kept;
|
||||
j.ahead = ahead;
|
||||
j.ahead = asked;
|
||||
AHEAD_KEPT.store(kept, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
|
||||
@@ -686,10 +718,11 @@ fn elsewhere(at: usize, len: usize) -> Vec<(usize, Vec<usize>)> {
|
||||
|
||||
/// One kernel asking for `pieces` (page ranges in order); by halves if it
|
||||
/// fails, as a run across two reservations or into memory that is not
|
||||
/// write-watched does. A piece alone is left to [`writes`]. Adds what was
|
||||
/// asked to `asked` and the pages found written to `written`.
|
||||
fn ask_run(pieces: &[(usize, usize)], asked: &mut Vec<(usize, usize)>, written: &mut Vec<(usize, u16)>) {
|
||||
if pieces.len() < 2 {
|
||||
/// write-watched does. When `ask_single` is false, a piece alone is left to
|
||||
/// [`writes`]. Adds what was asked to `asked` and the pages found written to
|
||||
/// `written`.
|
||||
fn ask_run(pieces: &[(usize, usize)], asked: &mut Vec<(usize, usize)>, written: &mut Vec<(usize, u16)>, ask_single: bool) {
|
||||
if pieces.is_empty() || (!ask_single && pieces.len() < 2) {
|
||||
return;
|
||||
}
|
||||
let first = pieces[0].0;
|
||||
@@ -699,9 +732,12 @@ fn ask_run(pieces: &[(usize, usize)], asked: &mut Vec<(usize, usize)>, written:
|
||||
asked.push((first, last));
|
||||
return;
|
||||
}
|
||||
if pieces.len() < 2 {
|
||||
return;
|
||||
}
|
||||
let (a, b) = pieces.split_at(pieces.len() / 2);
|
||||
ask_run(a, asked, written);
|
||||
ask_run(b, asked, written);
|
||||
ask_run(a, asked, written, ask_single);
|
||||
ask_run(b, asked, written, ask_single);
|
||||
}
|
||||
|
||||
/// What [`writes`] would say of `[start, end)` from the journal alone, if
|
||||
@@ -729,7 +765,13 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve
|
||||
materialize(start, end.saturating_sub(start));
|
||||
}
|
||||
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
|
||||
let of = |j: &Journal| -> Vec<(usize, u64)> { j.written.range(first..last).map(|(&p, &w)| (p, w)).collect() };
|
||||
let of = |j: &Journal| -> Vec<(usize, u64)> {
|
||||
if first + 1 == last {
|
||||
j.written.get(&first).map(|&w| vec![(first, w)]).unwrap_or_default()
|
||||
} else {
|
||||
j.written.range(first..last).map(|(&p, &w)| (p, w)).collect()
|
||||
}
|
||||
};
|
||||
// Asked ahead with the submission's other ranges: the journal has it.
|
||||
let ahead = |j: &Journal| ahead_contains(&j.ahead, first, last).then(|| (j.ahead_asked, of(j)));
|
||||
if let Some(known) = ahead(&journal()) {
|
||||
@@ -800,29 +842,79 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve
|
||||
Some(answer)
|
||||
}
|
||||
|
||||
/// Like [`writes`], but returns `(asking, changed_since)` without allocating a
|
||||
/// per-page vector on the hot fast paths (`ahead` or `published`).
|
||||
pub(crate) fn writes_since(start: usize, end: usize, guarded: bool, since: u64) -> Option<(u64, bool)> {
|
||||
if guarded && soft().is_none() {
|
||||
materialize(start, end.saturating_sub(start));
|
||||
}
|
||||
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
|
||||
let newer = |j: &Journal| -> bool {
|
||||
if since == 0 {
|
||||
return true;
|
||||
}
|
||||
if first + 1 == last {
|
||||
j.written.get(&first).is_some_and(|&w| w > since)
|
||||
} else {
|
||||
j.written.range(first..last).any(|(_, &w)| w > since)
|
||||
}
|
||||
};
|
||||
{
|
||||
let j = journal();
|
||||
if ahead_contains(&j.ahead, first, last) {
|
||||
return Some((j.ahead_asked, newer(&j)));
|
||||
}
|
||||
}
|
||||
if guarded && published(start, end) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
tally(2, 1);
|
||||
crate::faultbook::note(crate::faultbook::What::Known, first, last, 0);
|
||||
}
|
||||
let j = journal();
|
||||
return Some((next_asking(), newer(&j)));
|
||||
}
|
||||
let (now, written) = writes(start, end, guarded)?;
|
||||
let changed = since == 0 || written.iter().any(|&(_, w)| w > since);
|
||||
Some((now, changed))
|
||||
}
|
||||
|
||||
/// Whether nothing of `[start, end)` was written that a copy with the notes
|
||||
/// `copied` (the asking after which each page from page `base` on was taken)
|
||||
/// and `ranged` (the asking after which a range that holds this one was
|
||||
/// taken whole, or 0) does not hold, as [`writes`] would answer with nothing
|
||||
/// asked: the submission's asking covers the range, or its blocks are known
|
||||
/// by their bits. `false` if something would have to be asked.
|
||||
pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64], ranged: u64) -> bool {
|
||||
pub(crate) fn nothing_new_in(j: &JournalGuard, start: usize, end: usize, base: usize, copied: &[u64], ranged: u64) -> bool {
|
||||
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
|
||||
// The bits first, then the journal, as in `writes`.
|
||||
let known = published(start, end);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if known {
|
||||
crate::faultbook::note(crate::faultbook::What::Known, first, last, 1);
|
||||
}
|
||||
let j = journal();
|
||||
if !known && !ahead_contains(&j.ahead, first, last) {
|
||||
let covered = {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
let known = published(start, end);
|
||||
if known {
|
||||
crate::faultbook::note(crate::faultbook::What::Known, first, last, 1);
|
||||
}
|
||||
known || ahead_contains(&j.0.ahead, first, last)
|
||||
}
|
||||
#[cfg(not(feature = "diagnostics"))]
|
||||
{
|
||||
ahead_contains(&j.0.ahead, first, last) || published(start, end)
|
||||
}
|
||||
};
|
||||
if !covered {
|
||||
return false;
|
||||
}
|
||||
let Some(taken) = first.checked_sub(base).and_then(|from| copied.get(from..last - base)) else {
|
||||
return false;
|
||||
};
|
||||
(ranged != 0 || taken.iter().all(|&at| at != 0))
|
||||
&& j.written.range(first..last).all(|(&page, &write)| write <= taken[page - first].max(ranged))
|
||||
if ranged == 0 && taken.iter().any(|&at| at == 0) {
|
||||
return false;
|
||||
}
|
||||
if first + 1 == last {
|
||||
j.0.written.get(&first).is_none_or(|&write| write <= taken[0].max(ranged))
|
||||
} else {
|
||||
j.0.written.range(first..last).all(|(&page, &write)| write <= taken[page - first].max(ranged))
|
||||
}
|
||||
}
|
||||
|
||||
impl Tracked {
|
||||
@@ -1500,18 +1592,30 @@ fn published(start: usize, end: usize) -> bool {
|
||||
/// opened by ourselves; nanoseconds waiting for the guards' lock and
|
||||
/// nanoseconds of changing protections (all threads); questions to Windows
|
||||
/// about holes; kernel askings refused; nanoseconds in kernel askings; the
|
||||
/// 4 KiB pages they found written.
|
||||
/// 4 KiB pages they found written; calls of [`kernel_written`], refused ones
|
||||
/// among them, the 4 KiB pages they walked, and their nanoseconds whole.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
static ASKS: [std::sync::atomic::AtomicU64; 13] = [const { std::sync::atomic::AtomicU64::new(0) }; 13];
|
||||
static ASKS: [std::sync::atomic::AtomicU64; 16] = [const { std::sync::atomic::AtomicU64::new(0) }; 16];
|
||||
|
||||
#[cfg(feature = "diagnostics")]
|
||||
fn tally(what: usize, n: u64) {
|
||||
ASKS[what].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Tallies the nanoseconds since it was made under `.0` when dropped.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
struct Tallied(usize, std::time::Instant);
|
||||
|
||||
#[cfg(feature = "diagnostics")]
|
||||
impl Drop for Tallied {
|
||||
fn drop(&mut self) {
|
||||
tally(self.0, self.1.elapsed().as_nanos() as u64);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`ASKS`], taken.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
pub(crate) fn asks() -> [u64; 13] {
|
||||
pub(crate) fn asks() -> [u64; 16] {
|
||||
std::array::from_fn(|i| ASKS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
|
||||
}
|
||||
|
||||
@@ -2942,6 +3046,7 @@ pub fn title_memory_unmapping(at: usize, len: usize) {
|
||||
/// was noted of its blocks (guarded, clean, absent) would be taken for true
|
||||
/// of the next memory at the address.
|
||||
pub fn title_memory_freed(at: usize, len: usize) {
|
||||
crate::shadow::gpu_readonly_freed(at, len);
|
||||
crate::shadow::write_combined_freed(at, len);
|
||||
let mut g = guards();
|
||||
let first = at / BLOCK;
|
||||
@@ -3157,6 +3262,19 @@ pub(crate) fn install() {
|
||||
// SAFETY: as above.
|
||||
let context = unsafe { (*info).ContextRecord };
|
||||
let fail = move |exit: usize| {
|
||||
// (A fault that fails one of our reads, counted for it.)
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::copystat::read_fault(
|
||||
if r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION as NTSTATUS
|
||||
&& r.NumberParameters >= 2
|
||||
&& r.ExceptionInformation[0] == WRITE
|
||||
{
|
||||
crate::copystat::ReadFault::NotWritable
|
||||
} else {
|
||||
crate::copystat::ReadFault::failed(r.ExceptionCode)
|
||||
},
|
||||
if r.NumberParameters >= 2 { r.ExceptionInformation[1] } else { 0 },
|
||||
);
|
||||
// SAFETY: the context the system passes, to go on from.
|
||||
unsafe { (*context).Rip = exit as u64 };
|
||||
EXCEPTION_CONTINUE_EXECUTION
|
||||
@@ -3172,6 +3290,8 @@ pub(crate) fn install() {
|
||||
None => materialize(r.ExceptionInformation[1], 1),
|
||||
}
|
||||
{
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::copystat::read_fault(crate::copystat::ReadFault::MadeReal, r.ExceptionInformation[1]);
|
||||
return EXCEPTION_CONTINUE_EXECUTION;
|
||||
}
|
||||
if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS
|
||||
@@ -3205,6 +3325,7 @@ pub(crate) fn install() {
|
||||
{
|
||||
crate::copystat::add(crate::copystat::C::GuardFaults, 1);
|
||||
crate::faultbook::note(crate::faultbook::What::Site, r.ExceptionAddress as usize, block, 0);
|
||||
crate::copystat::read_fault(crate::copystat::ReadFault::OurGuard, at);
|
||||
}
|
||||
return EXCEPTION_CONTINUE_EXECUTION;
|
||||
}
|
||||
@@ -3215,6 +3336,8 @@ pub(crate) fn install() {
|
||||
if writable(at) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::faultbook::note(crate::faultbook::What::Open, block, began.elapsed().as_nanos() as usize, 0);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::copystat::read_fault(crate::copystat::ReadFault::OurGuard, at);
|
||||
return EXCEPTION_CONTINUE_EXECUTION;
|
||||
}
|
||||
for _ in 0..64 {
|
||||
@@ -3232,6 +3355,8 @@ pub(crate) fn install() {
|
||||
if !PROTECTED.any(block, block + 1) && writable(at) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::faultbook::note(crate::faultbook::What::Open, block, 0, 0);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::copystat::read_fault(crate::copystat::ReadFault::OurGuard, at);
|
||||
return EXCEPTION_CONTINUE_EXECUTION;
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
@@ -3255,11 +3380,14 @@ pub(crate) fn install() {
|
||||
FAULTS[2].fetch_add(held, std::sync::atomic::Ordering::Relaxed);
|
||||
crate::faultbook::note(crate::faultbook::What::Fault, block, opened << 32 | ns, held);
|
||||
crate::faultbook::note(crate::faultbook::What::Site, r.ExceptionAddress as usize, block, 0);
|
||||
crate::copystat::read_fault(crate::copystat::ReadFault::OurGuard, at);
|
||||
}
|
||||
return EXCEPTION_CONTINUE_EXECUTION;
|
||||
}
|
||||
}
|
||||
if writable(at) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::copystat::read_fault(crate::copystat::ReadFault::OurGuard, at);
|
||||
return EXCEPTION_CONTINUE_EXECUTION;
|
||||
}
|
||||
match ours {
|
||||
@@ -3750,7 +3878,7 @@ mod tests {
|
||||
let (copied, _) = writes(p, p + 4 * PAGE, false).expect("watched");
|
||||
// SAFETY: committed pages of ours.
|
||||
unsafe { ((p + PAGE) as *mut u8).write_volatile(1) };
|
||||
ask_rest(&ranges);
|
||||
ask_once(&ranges);
|
||||
let last = journal().written.get(&(p / PAGE + 1)).copied();
|
||||
ask_once_end();
|
||||
assert!(last.is_some_and(|last| last > copied), "{last:?} is not after {copied}");
|
||||
|
||||
@@ -55,6 +55,7 @@ tempfile.workspace = true
|
||||
|
||||
[features]
|
||||
# Debugging switches (scripted keys and the like).
|
||||
mimalloc = ["victory-gpu/mimalloc"]
|
||||
diagnostics = ["victory-gpu/diagnostics", "victory-loader/diagnostics", "dep:windows", "dep:windows-core"]
|
||||
|
||||
[lints]
|
||||
|
||||
@@ -11,6 +11,12 @@
|
||||
//! Resolution order for every import: an implementation in [`modules`],
|
||||
//! then the host if [`HostPolicy`] allows that DLL, then `Missing`.
|
||||
|
||||
// A style lint new in the toolchain (rust 1.98's clippy) that fires on
|
||||
// pre-existing code (gameinput.rs, unchanged from the committed base) the
|
||||
// VICTORY_LIST_ALLOC_CAP_MB work never touched. Suppressed at crate root so
|
||||
// `cargo clippy -D warnings` is green without rewriting unrelated source.
|
||||
#![allow(clippy::some_filter)]
|
||||
|
||||
mod host;
|
||||
mod image_watch;
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
//! Thread affinity the title asks for (`VICTORY_AFFINITY`).
|
||||
//!
|
||||
//! The title creates its threads suspended and pins each to the console's
|
||||
//! cores (`SetThreadGroupAffinity`, e.g. its five command-list recorders to
|
||||
//! mask 0x1f00 = logical processors 8–12), Bink pins its workers with
|
||||
//! `SetThreadAffinityMask` and sets ideal processors. On this PC those masks
|
||||
//! squeeze busy threads onto a few cores (measured: recording 210 → 165 ms
|
||||
//! summed a frame with the masks lifted).
|
||||
//!
|
||||
//! `VICTORY_AFFINITY=free` (fox port: default OFF, i.e. console, until A/B): calls from title code succeed, report the
|
||||
//! previous mask the title set (or the thread's real one) and are remembered
|
||||
//! per thread id, so a get after a set returns what the title expects, but the
|
||||
//! thread is not narrowed. `VICTORY_AFFINITY=console` (default in the fox port): passed to Windows as
|
||||
//! before. Only the title's imports reach these functions; the layer's own
|
||||
//! threads are never touched.
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::ffi::c_void;
|
||||
use std::sync::atomic::{AtomicU8, Ordering::Relaxed};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::{HleModule, hle_export};
|
||||
|
||||
/// `GROUP_AFFINITY`.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct GroupAffinity {
|
||||
pub mask: usize,
|
||||
pub group: u16,
|
||||
pub reserved: [u16; 3],
|
||||
}
|
||||
|
||||
/// `PROCESSOR_NUMBER`.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct ProcessorNumber {
|
||||
pub group: u16,
|
||||
pub number: u8,
|
||||
pub reserved: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Mode {
|
||||
Free,
|
||||
Console,
|
||||
}
|
||||
|
||||
fn mode() -> Mode {
|
||||
static MODE: AtomicU8 = AtomicU8::new(0);
|
||||
match MODE.load(Relaxed) {
|
||||
1 => return Mode::Free,
|
||||
2 => return Mode::Console,
|
||||
_ => {}
|
||||
}
|
||||
let m = match std::env::var("VICTORY_AFFINITY").ok().as_deref().map(str::trim) {
|
||||
Some("free") => Mode::Free,
|
||||
None | Some("") | Some("console") => Mode::Console,
|
||||
Some(other) => {
|
||||
tracing::warn!(value = other, "VICTORY_AFFINITY: unknown value, using console (the fox base)");
|
||||
Mode::Console
|
||||
}
|
||||
};
|
||||
MODE.store(if m == Mode::Free { 1 } else { 2 }, Relaxed);
|
||||
m
|
||||
}
|
||||
|
||||
/// What the title asked for, per thread id, and what it has asked so far.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Book {
|
||||
masks: HashMap<u32, GroupAffinity>,
|
||||
ideal: HashMap<u32, ProcessorNumber>,
|
||||
/// Mask → how many set calls asked for it.
|
||||
seen: BTreeMap<usize, u64>,
|
||||
ignored: u64,
|
||||
ideal_ignored: u64,
|
||||
/// Set calls counted in the last summary.
|
||||
logged: u64,
|
||||
}
|
||||
|
||||
impl Book {
|
||||
/// Records a set the title made; returns what the title set before, if anything.
|
||||
pub fn set(&mut self, thread: u32, affinity: GroupAffinity) -> Option<GroupAffinity> {
|
||||
self.ignored += 1;
|
||||
*self.seen.entry(affinity.mask).or_default() += 1;
|
||||
self.masks.insert(thread, GroupAffinity { reserved: [0; 3], ..affinity })
|
||||
}
|
||||
|
||||
/// What the title last set for `thread`.
|
||||
pub fn get(&self, thread: u32) -> Option<GroupAffinity> {
|
||||
self.masks.get(&thread).copied()
|
||||
}
|
||||
|
||||
/// Records an ideal processor; returns the one the title set before.
|
||||
pub fn set_ideal(&mut self, thread: u32, ideal: ProcessorNumber) -> Option<ProcessorNumber> {
|
||||
self.ideal_ignored += 1;
|
||||
self.ideal.insert(thread, ProcessorNumber { reserved: 0, ..ideal })
|
||||
}
|
||||
|
||||
/// "N set calls ignored, masks seen: 0x1f00 x5, 0xff x8" (most asked first).
|
||||
pub fn summary(&self) -> String {
|
||||
let mut seen: Vec<_> = self.seen.iter().collect();
|
||||
seen.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
|
||||
let masks: Vec<String> = seen.iter().map(|(m, n)| format!("{m:#x} x{n}")).collect();
|
||||
let mut line = format!(
|
||||
"thread affinity: {} set calls ignored, masks seen: {}",
|
||||
self.ignored,
|
||||
if masks.is_empty() { "none".into() } else { masks.join(", ") }
|
||||
);
|
||||
if self.ideal_ignored > 0 {
|
||||
line += &format!("; {} ideal-processor calls ignored", self.ideal_ignored);
|
||||
}
|
||||
line
|
||||
}
|
||||
}
|
||||
|
||||
static BOOK: Mutex<Option<Book>> = Mutex::new(None);
|
||||
|
||||
fn with_book<R>(f: impl FnOnce(&mut Book) -> R) -> R {
|
||||
let mut book = BOOK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
f(book.get_or_insert_with(Book::default))
|
||||
}
|
||||
|
||||
/// The first ignored call logs that masks are not applied and registers the
|
||||
/// exit summary; later ones log the summary at most every 5 s while calls come.
|
||||
fn note_ignored() {
|
||||
static FIRST: std::sync::Once = std::sync::Once::new();
|
||||
FIRST.call_once(|| {
|
||||
tracing::info!("thread affinity: title masks are not applied (VICTORY_AFFINITY=free)");
|
||||
// SAFETY: registering a plain function with the CRT.
|
||||
unsafe { atexit(at_exit) };
|
||||
});
|
||||
static LAST: Mutex<Option<Instant>> = Mutex::new(None);
|
||||
let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let now = Instant::now();
|
||||
if last.is_none_or(|t| now - t >= Duration::from_secs(5)) {
|
||||
*last = Some(now);
|
||||
drop(last);
|
||||
log_summary();
|
||||
}
|
||||
}
|
||||
|
||||
fn log_summary() {
|
||||
if let Some(line) = with_book(|b| {
|
||||
(b.ignored + b.ideal_ignored != b.logged).then(|| {
|
||||
b.logged = b.ignored + b.ideal_ignored;
|
||||
b.summary()
|
||||
})
|
||||
}) {
|
||||
tracing::info!("{line}");
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" fn at_exit() {
|
||||
log_summary();
|
||||
}
|
||||
|
||||
unsafe extern "C" {
|
||||
fn atexit(f: extern "C" fn()) -> i32;
|
||||
}
|
||||
|
||||
#[link(name = "kernel32")]
|
||||
unsafe extern "system" {
|
||||
#[link_name = "SetThreadGroupAffinity"]
|
||||
fn host_set_group(thread: *mut c_void, affinity: *const GroupAffinity, previous: *mut GroupAffinity) -> i32;
|
||||
#[link_name = "GetThreadGroupAffinity"]
|
||||
fn host_get_group(thread: *mut c_void, affinity: *mut GroupAffinity) -> i32;
|
||||
#[link_name = "SetThreadAffinityMask"]
|
||||
fn host_set_mask(thread: *mut c_void, mask: usize) -> usize;
|
||||
#[link_name = "SetThreadIdealProcessorEx"]
|
||||
fn host_set_ideal(thread: *mut c_void, ideal: *const ProcessorNumber, previous: *mut ProcessorNumber) -> i32;
|
||||
#[link_name = "GetThreadIdealProcessorEx"]
|
||||
fn host_get_ideal(thread: *mut c_void, ideal: *mut ProcessorNumber) -> i32;
|
||||
#[link_name = "GetThreadId"]
|
||||
fn host_thread_id(thread: *mut c_void) -> u32;
|
||||
}
|
||||
|
||||
/// The thread's id, or `None` for a handle Windows does not know (the call
|
||||
/// then goes to Windows, which fails it the usual way).
|
||||
fn thread_id(thread: *mut c_void) -> Option<u32> {
|
||||
// SAFETY: a query on the title's handle.
|
||||
let id = unsafe { host_thread_id(thread) };
|
||||
(id != 0).then_some(id)
|
||||
}
|
||||
|
||||
/// The thread's real affinity.
|
||||
fn real_group(thread: *mut c_void) -> Option<GroupAffinity> {
|
||||
let mut a = GroupAffinity::default();
|
||||
// SAFETY: a query into our own struct.
|
||||
(unsafe { host_get_group(thread, &mut a) } != 0).then_some(a)
|
||||
}
|
||||
|
||||
pub extern "system" fn SetThreadGroupAffinity(
|
||||
thread: *mut c_void,
|
||||
affinity: *const GroupAffinity,
|
||||
previous: *mut GroupAffinity,
|
||||
) -> i32 {
|
||||
let id = thread_id(thread);
|
||||
let (Mode::Free, Some(id), false) = (mode(), id, affinity.is_null()) else {
|
||||
// SAFETY: the title's own arguments.
|
||||
return unsafe { host_set_group(thread, affinity, previous) };
|
||||
};
|
||||
// SAFETY: the title passes a valid GROUP_AFFINITY.
|
||||
let asked = unsafe { *affinity };
|
||||
let before = with_book(|b| b.set(id, asked)).or_else(|| real_group(thread)).unwrap_or_default();
|
||||
if !previous.is_null() {
|
||||
// SAFETY: the title passes room for one GROUP_AFFINITY.
|
||||
unsafe { *previous = before };
|
||||
}
|
||||
note_ignored();
|
||||
1
|
||||
}
|
||||
|
||||
pub extern "system" fn GetThreadGroupAffinity(thread: *mut c_void, affinity: *mut GroupAffinity) -> i32 {
|
||||
if mode() == Mode::Free
|
||||
&& !affinity.is_null()
|
||||
&& let Some(set) = thread_id(thread).and_then(|id| with_book(|b| b.get(id)))
|
||||
{
|
||||
// SAFETY: the title passes room for one GROUP_AFFINITY.
|
||||
unsafe { *affinity = set };
|
||||
return 1;
|
||||
}
|
||||
// SAFETY: the title's own arguments.
|
||||
unsafe { host_get_group(thread, affinity) }
|
||||
}
|
||||
|
||||
pub extern "system" fn SetThreadAffinityMask(thread: *mut c_void, mask: usize) -> usize {
|
||||
let (Mode::Free, Some(id), true) = (mode(), thread_id(thread), mask != 0) else {
|
||||
// SAFETY: the title's own arguments.
|
||||
return unsafe { host_set_mask(thread, mask) };
|
||||
};
|
||||
let before = with_book(|b| b.set(id, GroupAffinity { mask, ..Default::default() }))
|
||||
.or_else(|| real_group(thread))
|
||||
.map_or(0, |a| a.mask);
|
||||
note_ignored();
|
||||
// A previous mask of 0 would read as failure.
|
||||
if before == 0 { mask } else { before }
|
||||
}
|
||||
|
||||
pub extern "system" fn SetThreadIdealProcessorEx(
|
||||
thread: *mut c_void,
|
||||
ideal: *const ProcessorNumber,
|
||||
previous: *mut ProcessorNumber,
|
||||
) -> i32 {
|
||||
let (Mode::Free, Some(id), false) = (mode(), thread_id(thread), ideal.is_null()) else {
|
||||
// SAFETY: the title's own arguments.
|
||||
return unsafe { host_set_ideal(thread, ideal, previous) };
|
||||
};
|
||||
// SAFETY: the title passes a valid PROCESSOR_NUMBER.
|
||||
let asked = unsafe { *ideal };
|
||||
let before = with_book(|b| b.set_ideal(id, asked)).or_else(|| {
|
||||
let mut p = ProcessorNumber::default();
|
||||
// SAFETY: a query into our own struct.
|
||||
(unsafe { host_get_ideal(thread, &mut p) } != 0).then_some(p)
|
||||
});
|
||||
if !previous.is_null() {
|
||||
// SAFETY: the title passes room for one PROCESSOR_NUMBER.
|
||||
unsafe { *previous = before.unwrap_or_default() };
|
||||
}
|
||||
note_ignored();
|
||||
1
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "affinity",
|
||||
dlls: &[
|
||||
"kernel32.dll",
|
||||
"kernelbase.dll",
|
||||
"api-ms-win-core-processtopology-*",
|
||||
"api-ms-win-core-processthreads-*",
|
||||
],
|
||||
exports: vec![
|
||||
hle_export!(SetThreadGroupAffinity),
|
||||
hle_export!(GetThreadGroupAffinity),
|
||||
hle_export!(SetThreadAffinityMask),
|
||||
hle_export!(SetThreadIdealProcessorEx),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn mask(m: usize) -> GroupAffinity {
|
||||
GroupAffinity { mask: m, group: 0, reserved: [7; 3] }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_get_after_a_set_returns_what_was_set() {
|
||||
let mut b = Book::default();
|
||||
assert_eq!(b.get(10), None);
|
||||
assert_eq!(b.set(10, mask(0x1f00)), None);
|
||||
assert_eq!(b.get(10), Some(GroupAffinity { mask: 0x1f00, group: 0, reserved: [0; 3] }));
|
||||
// The previous mask is the one set before.
|
||||
assert_eq!(b.set(10, mask(0xff)).map(|a| a.mask), Some(0x1f00));
|
||||
assert_eq!(b.get(10).map(|a| a.mask), Some(0xff));
|
||||
assert_eq!(b.get(11), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summary_counts_masks_most_asked_first() {
|
||||
let mut b = Book::default();
|
||||
for t in 0..5 {
|
||||
b.set(t, mask(0x1f00));
|
||||
}
|
||||
b.set(20, mask(0xff));
|
||||
b.set(21, mask(0x3fff));
|
||||
b.set(22, mask(0x3fff));
|
||||
assert_eq!(b.summary(), "thread affinity: 8 set calls ignored, masks seen: 0x1f00 x5, 0x3fff x2, 0xff x1");
|
||||
b.set_ideal(20, ProcessorNumber { group: 0, number: 3, reserved: 9 });
|
||||
assert_eq!(
|
||||
b.set_ideal(20, ProcessorNumber::default()),
|
||||
Some(ProcessorNumber { group: 0, number: 3, reserved: 0 })
|
||||
);
|
||||
assert!(b.summary().ends_with("; 2 ideal-processor calls ignored"), "{}", b.summary());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_summary() {
|
||||
assert_eq!(Book::default().summary(), "thread affinity: 0 set calls ignored, masks seen: none");
|
||||
}
|
||||
}
|
||||
@@ -85,7 +85,7 @@ pub fn mount_at(letter: char, root: &Path) {
|
||||
/// `root` as UTF-16, absolute, without trailing separators (a drive root
|
||||
/// keeps its own). An empty root is the current directory, as it is to a
|
||||
/// path joined to it: it is the title's folder when the title is run by its
|
||||
/// file name alone (`victory run game.exe`).
|
||||
/// file name alone (`victory run GTA6.exe`).
|
||||
fn root_wide(root: &Path) -> Vec<u16> {
|
||||
let root = if root.as_os_str().is_empty() {
|
||||
Path::new(".")
|
||||
|
||||
@@ -85,8 +85,7 @@ fn title_path(module: *mut c_void) -> Option<String> {
|
||||
|
||||
/// `GetModuleFileName`'s contract: copy with a NUL; if it does not fit,
|
||||
/// truncate to the buffer, report `ERROR_INSUFFICIENT_BUFFER` and return
|
||||
/// the buffer size. A name that fits clears the last error, as the host
|
||||
/// does: titles tell a truncated name from a whole one by it.
|
||||
/// the buffer size.
|
||||
fn copy_truncated<T: Copy + Default>(text: &[T], out: &mut [T]) -> u32 {
|
||||
let Some(room) = out.len().checked_sub(1) else {
|
||||
host::set_last_error(ERROR_INSUFFICIENT_BUFFER);
|
||||
@@ -99,12 +98,9 @@ fn copy_truncated<T: Copy + Default>(text: &[T], out: &mut [T]) -> u32 {
|
||||
host::set_last_error(ERROR_INSUFFICIENT_BUFFER);
|
||||
return out.len() as u32;
|
||||
}
|
||||
host::set_last_error(ERROR_SUCCESS);
|
||||
n as u32
|
||||
}
|
||||
|
||||
const ERROR_SUCCESS: u32 = 0;
|
||||
|
||||
const ERROR_INSUFFICIENT_BUFFER: u32 = 122;
|
||||
|
||||
/// Console-only DLLs we implement load as a pseudo handle (titles load
|
||||
@@ -724,34 +720,6 @@ mod tests {
|
||||
assert_eq!(&small, &[b'C', b':', b'\\', 0]);
|
||||
}
|
||||
|
||||
/// A name that fits clears the last error, as the host does: titles tell
|
||||
/// a truncated name from a whole one by it.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_module_name_that_fits_clears_the_last_error() {
|
||||
use windows_sys::Win32::Foundation::{GetLastError, SetLastError};
|
||||
// SAFETY: this thread's last error.
|
||||
let last_error = || unsafe { GetLastError() };
|
||||
// SAFETY: sets this thread's last error.
|
||||
let stale = || unsafe { SetLastError(ERROR_INSUFFICIENT_BUFFER) };
|
||||
let base = 0x7200_0000_0000;
|
||||
runtime::set_image_path(base, std::path::Path::new(r"C:\title\game.exe"));
|
||||
let module = base as *mut c_void;
|
||||
let (mut wide, mut narrow) = ([0u16; 512], [0u8; 512]);
|
||||
stale();
|
||||
assert_eq!(GetModuleFileNameW(module, wide.as_mut_ptr(), 512), 17);
|
||||
assert_eq!(last_error(), 0, "a title image, wide");
|
||||
stale();
|
||||
assert_eq!(GetModuleFileNameA(module, narrow.as_mut_ptr(), 512), 17);
|
||||
assert_eq!(last_error(), 0, "a title image, narrow");
|
||||
// An exact fit is whole too (17 characters and the NUL).
|
||||
stale();
|
||||
assert_eq!(GetModuleFileNameA(module, narrow.as_mut_ptr(), 18), 17);
|
||||
assert_eq!(last_error(), 0);
|
||||
assert_eq!(GetModuleFileNameA(module, narrow.as_mut_ptr(), 17), 17);
|
||||
assert_eq!(last_error(), ERROR_INSUFFICIENT_BUFFER);
|
||||
}
|
||||
|
||||
/// The title's arguments come right after the program, and the list ends
|
||||
/// in a null pointer; without any there is only the program.
|
||||
#[test]
|
||||
|
||||
@@ -21,6 +21,8 @@ pub mod dstorage;
|
||||
pub mod fidelityfx;
|
||||
#[cfg(windows)]
|
||||
pub mod files;
|
||||
#[cfg(windows)]
|
||||
pub mod affinity;
|
||||
pub mod gameinput;
|
||||
pub mod kernel;
|
||||
#[cfg(windows)]
|
||||
@@ -74,6 +76,8 @@ pub(crate) fn all() -> Vec<HleModule> {
|
||||
#[cfg(windows)]
|
||||
all.push(xmem::module());
|
||||
#[cfg(windows)]
|
||||
all.push(affinity::module());
|
||||
#[cfg(windows)]
|
||||
all.push(xsystem::module());
|
||||
all
|
||||
}
|
||||
@@ -843,25 +843,16 @@ pub fn pending_with(
|
||||
type Data = Mutex<(Option<Box<dyn FnOnce() -> Result<Vec<u8>, HRESULT> + Send>>, Vec<u8>)>;
|
||||
extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT {
|
||||
// SAFETY: the runtime passes valid provider data; the context is the
|
||||
// shared state until cleanup releases it.
|
||||
// boxed state until cleanup frees it.
|
||||
let data = unsafe { &*data };
|
||||
let state = data.context.cast::<Data>();
|
||||
match op {
|
||||
// SAFETY: from `Arc::into_raw` in `pending_with`; released once.
|
||||
OP_CLEANUP => drop(unsafe { Arc::from_raw(state) }),
|
||||
// SAFETY: boxed in `pending_with`; nothing runs after cleanup.
|
||||
OP_CLEANUP => drop(unsafe { Box::from_raw(state) }),
|
||||
OP_BEGIN => {
|
||||
let Some(call) = call(data.block) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
// SAFETY: the context is a live `Arc`; this takes a count of
|
||||
// our own, which the thread keeps. Cleanup may run first (a
|
||||
// cancel ends the call), so the thread must not borrow it.
|
||||
let state = unsafe {
|
||||
Arc::increment_strong_count(state);
|
||||
Arc::from_raw(state)
|
||||
};
|
||||
let work = state.lock().unwrap_or_else(|e| e.into_inner()).0.take();
|
||||
let block = data.block as usize;
|
||||
// SAFETY: as above; cleanup waits for completion.
|
||||
let work = unsafe { &*state }.lock().unwrap_or_else(|e| e.into_inner()).0.take();
|
||||
let (block, state) = (data.block as usize, state as usize);
|
||||
std::thread::spawn(move || {
|
||||
let result = work.map_or(Err(E_ABORT), |work| work());
|
||||
let (hr, len) = match &result {
|
||||
@@ -869,13 +860,11 @@ pub fn pending_with(
|
||||
Err(hr) => (*hr, 0),
|
||||
};
|
||||
if let Ok(bytes) = result {
|
||||
// SAFETY: the call is pending, so its state lives.
|
||||
let state = unsafe { &*(state as *const Data) };
|
||||
state.lock().unwrap_or_else(|e| e.into_inner()).1 = bytes;
|
||||
}
|
||||
// Completes the call this began with, not whatever the
|
||||
// block holds by now: a canceled call is over (and does
|
||||
// not touch the block again), and the title may have
|
||||
// begun another call on it.
|
||||
complete_call(&call, block as *mut AsyncBlock, hr, len);
|
||||
XAsyncComplete(block as *mut AsyncBlock, hr, len);
|
||||
});
|
||||
}
|
||||
// SAFETY: as above; the runtime checked the buffer's size.
|
||||
@@ -889,18 +878,12 @@ pub fn pending_with(
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
let state: Arc<Data> = Arc::new(Mutex::new((Some(Box::new(work)), Vec::new())));
|
||||
let context = Arc::into_raw(state);
|
||||
let hr = XAsyncBegin(
|
||||
block,
|
||||
context.cast_mut().cast(),
|
||||
identity,
|
||||
std::ptr::null(),
|
||||
Some(provider),
|
||||
);
|
||||
let state: Box<Data> = Box::new(Mutex::new((Some(Box::new(work)), Vec::new())));
|
||||
let context = Box::into_raw(state);
|
||||
let hr = XAsyncBegin(block, context.cast(), identity, std::ptr::null(), Some(provider));
|
||||
if hr < 0 {
|
||||
// SAFETY: refused before the call existed; still ours.
|
||||
drop(unsafe { Arc::from_raw(context) });
|
||||
drop(unsafe { Box::from_raw(context) });
|
||||
}
|
||||
hr
|
||||
}
|
||||
@@ -1505,86 +1488,6 @@ mod tests {
|
||||
XTaskQueueCloseHandle(q);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_canceled_pending_call_cannot_complete_the_next_call_on_its_block() {
|
||||
extern "system" fn idle(_: u32, _: *const ProviderData) -> HRESULT {
|
||||
S_OK
|
||||
}
|
||||
let (release, gate) = std::sync::mpsc::channel::<()>();
|
||||
let mut block = AsyncBlock {
|
||||
queue: std::ptr::null(),
|
||||
context: std::ptr::null_mut(),
|
||||
callback: None,
|
||||
internal: [0; 4],
|
||||
};
|
||||
let first = 0x91 as *const c_void;
|
||||
assert_eq!(
|
||||
pending_with(&mut block, first, move || {
|
||||
let _ = gate.recv();
|
||||
Ok(vec![1, 2])
|
||||
}),
|
||||
S_OK
|
||||
);
|
||||
XAsyncCancel(&mut block);
|
||||
assert_eq!(XAsyncGetStatus(&mut block, false), E_ABORT);
|
||||
|
||||
// The title reuses the block for a new call, zeroed as new blocks are.
|
||||
block.internal = [0; 4];
|
||||
let second = 0x92 as *const c_void;
|
||||
assert_eq!(
|
||||
XAsyncBegin(
|
||||
&mut block,
|
||||
std::ptr::null_mut(),
|
||||
second,
|
||||
std::ptr::null(),
|
||||
Some(idle)
|
||||
),
|
||||
S_OK
|
||||
);
|
||||
assert_eq!(XAsyncGetStatus(&mut block, false), E_PENDING);
|
||||
|
||||
// The canceled call's work ends now: it must not finish the new call.
|
||||
assert!(release.send(()).is_ok());
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
assert_eq!(
|
||||
XAsyncGetStatus(&mut block, false),
|
||||
E_PENDING,
|
||||
"the second call is still pending"
|
||||
);
|
||||
XAsyncComplete(&mut block, S_OK, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pending_call_hands_out_what_its_work_returns() {
|
||||
let mut block = AsyncBlock {
|
||||
queue: std::ptr::null(),
|
||||
context: std::ptr::null_mut(),
|
||||
callback: None,
|
||||
internal: [0; 4],
|
||||
};
|
||||
let identity = 0x93 as *const c_void;
|
||||
assert_eq!(
|
||||
pending_with(&mut block, identity, || Ok(vec![7, 8, 9])),
|
||||
S_OK
|
||||
);
|
||||
assert_eq!(XAsyncGetStatus(&mut block, true), S_OK);
|
||||
let mut size = 0;
|
||||
assert_eq!(XAsyncGetResultSize(&mut block, &mut size), S_OK);
|
||||
assert_eq!(size, 3);
|
||||
let mut out = [0u8; 3];
|
||||
assert_eq!(
|
||||
XAsyncGetResult(
|
||||
&mut block,
|
||||
identity,
|
||||
out.len(),
|
||||
out.as_mut_ptr().cast(),
|
||||
std::ptr::null_mut()
|
||||
),
|
||||
S_OK
|
||||
);
|
||||
assert_eq!(out, [7, 8, 9]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_returns_the_work_result() {
|
||||
extern "system" fn work(_: *mut AsyncBlock) -> HRESULT {
|
||||
|
||||
@@ -60,14 +60,20 @@ pub const FIRST: u32 = 32;
|
||||
/// the yard's frame replayed turn by turn, dispatches and draws 18.47 -> 18.45
|
||||
/// ms (12 loops) and 18.23 -> 18.16 (5 loops): the driver joins the loads.
|
||||
pub const WIDE: u32 = 64;
|
||||
/// Strip dead single-block `waveReadLaneFirst` waterfall loops whose payload
|
||||
/// (e.g. a sample using a uniform heap handle) is loop-invariant.
|
||||
pub const WATERFALL: u32 = 128;
|
||||
/// Hoist loop-invariant and duplicated pure `createHandleFromHeap` (+
|
||||
/// `annotateHandle`) chains to their dominating preheader / definition block
|
||||
/// so [`REUSE`] deduplicates them.
|
||||
pub const HOIST_HANDLES: u32 = 256;
|
||||
/// The passes over the module.
|
||||
pub const MODULE: u32 = DEAD | FOLD | REUSE | FACTS | LOADS;
|
||||
pub const MODULE: u32 = DEAD | FOLD | REUSE | FACTS | LOADS | WATERFALL | HOIST_HANDLES;
|
||||
/// Every pass.
|
||||
pub const ALL: u32 = MODULE | FIRST | WIDE;
|
||||
/// The passes that run when nothing says which: every one but [`WIDE`],
|
||||
/// which no card has shown a gain for yet (`VICTORY_SHADER_OPT=127` asks
|
||||
/// for it).
|
||||
pub const DEFAULT: u32 = ALL & !WIDE;
|
||||
/// The passes that run when nothing says which: the baseline 63 set until
|
||||
/// newer passes (`WATERFALL`, `HOIST_HANDLES`) are verified and promoted.
|
||||
pub const DEFAULT: u32 = DEAD | FOLD | REUSE | FACTS | LOADS | FIRST;
|
||||
|
||||
/// What the instructions a module writes use, of the features a shader
|
||||
/// declares by flag (the validator's "flags must match usage").
|
||||
@@ -109,6 +115,26 @@ struct Tree {
|
||||
children: Vec<Vec<usize>>,
|
||||
/// Per block: the reached blocks that branch to it, once per edge.
|
||||
preds: Vec<Vec<usize>>,
|
||||
/// Immediate dominator of each block (`usize::MAX` if unreachable).
|
||||
idom: Vec<usize>,
|
||||
/// Depth in the dominator tree (entry = 0).
|
||||
depth: Vec<u32>,
|
||||
}
|
||||
|
||||
impl Tree {
|
||||
fn dominates(&self, a: usize, mut b: usize) -> bool {
|
||||
if a == b {
|
||||
return true;
|
||||
}
|
||||
if self.idom[b] == usize::MAX {
|
||||
return false;
|
||||
}
|
||||
let da = self.depth[a];
|
||||
while self.depth[b] > da {
|
||||
b = self.idom[b];
|
||||
}
|
||||
a == b
|
||||
}
|
||||
}
|
||||
|
||||
/// The comparison that holds exactly when `p` does not (floats 0-15,
|
||||
@@ -229,12 +255,21 @@ pub(super) fn effect(f: &Func) -> Effect {
|
||||
impl Module {
|
||||
/// Runs the clean-up passes named in `passes` ([`ALL`]: every one).
|
||||
pub(crate) fn optimise(&mut self, passes: u32) {
|
||||
if passes & (FOLD | REUSE | FACTS | LOADS) != 0 {
|
||||
if passes & (FOLD | REUSE | FACTS | LOADS | WATERFALL | HOIST_HANDLES) != 0 {
|
||||
// Values merged in one round can make two joins the same in
|
||||
// the next (a loop's registers that only go round), and a
|
||||
// branch that goes one way leaves blocks with one way in.
|
||||
for _ in 0..4 {
|
||||
let mut changed = self.merge(passes);
|
||||
let mut changed = false;
|
||||
if passes & WATERFALL != 0 {
|
||||
changed |= self.strip_dead_waterfalls();
|
||||
}
|
||||
if passes & HOIST_HANDLES != 0 {
|
||||
changed |= self.hoist_handles();
|
||||
}
|
||||
if passes & (FOLD | REUSE | FACTS | LOADS) != 0 {
|
||||
changed |= self.merge(passes);
|
||||
}
|
||||
if passes & FOLD != 0 {
|
||||
changed |= self.prune();
|
||||
}
|
||||
@@ -341,13 +376,17 @@ impl Module {
|
||||
}
|
||||
}
|
||||
let mut children = vec![Vec::new(); n];
|
||||
let mut depth = vec![0u32; n];
|
||||
for &b in &order[1..] {
|
||||
children[idom[b]].push(b);
|
||||
depth[b] = depth[idom[b]] + 1;
|
||||
}
|
||||
Tree {
|
||||
order,
|
||||
children,
|
||||
preds,
|
||||
idom,
|
||||
depth,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -997,6 +1036,735 @@ impl Module {
|
||||
true
|
||||
}
|
||||
|
||||
/// [`WATERFALL`]: strips single-block `waveReadLaneFirst` waterfall loops
|
||||
/// whose payload is loop-invariant (e.g. sampling through a uniform heap
|
||||
/// handle where the original console shader kept a dead per-lane copy of
|
||||
/// the descriptor words for waterfall comparison).
|
||||
fn strip_dead_waterfalls(&mut self) -> bool {
|
||||
let effects = self.effects();
|
||||
let tree = self.dominator_tree();
|
||||
let n_insts = self.insts.len();
|
||||
let mut def_block = vec![usize::MAX; n_insts];
|
||||
for &b in &tree.order {
|
||||
for &i in self.blocks[b].phis.iter().chain(&self.blocks[b].body) {
|
||||
def_block[i as usize] = b;
|
||||
}
|
||||
}
|
||||
let mut repl: Vec<Option<V>> = vec![None; n_insts];
|
||||
let mut changed = false;
|
||||
|
||||
for &b in &tree.order {
|
||||
let Some(Term::CondBr(cond, t, f)) = self.blocks[b].term else {
|
||||
continue;
|
||||
};
|
||||
let (back_is_true, exit) = if t == b && f != b {
|
||||
(true, f)
|
||||
} else if f == b && t != b {
|
||||
(false, t)
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
if tree.preds[b].len() != 2 {
|
||||
continue;
|
||||
}
|
||||
let Some(&entry_pred) = tree.preds[b].iter().find(|&&p| p != b) else {
|
||||
continue;
|
||||
};
|
||||
if self.blocks[b].phis.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Body must have no writes (stores/atomics/barriers) and every
|
||||
// lane op must be a `waveReadLaneFirst` of a loop-invariant value.
|
||||
let mut has_wrlf = false;
|
||||
let mut body_ok = true;
|
||||
for &i in &self.blocks[b].body {
|
||||
let c = self.class(&effects, i);
|
||||
if c == Effect::Writes {
|
||||
body_ok = false;
|
||||
break;
|
||||
}
|
||||
if c == Effect::Lanes {
|
||||
match self.wrlf_arg(V::Inst(i)) {
|
||||
Some(arg) if !matches!(arg, V::Inst(a) if def_block[a as usize] == b) => {
|
||||
has_wrlf = true;
|
||||
}
|
||||
_ => {
|
||||
body_ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !body_ok || !has_wrlf {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Identify optional counter limit (`iter_next < K`, `K >= 64`) and
|
||||
// the negated waterfall match condition (`!match_mask`).
|
||||
let (retry_v, iter_phi) = if back_is_true {
|
||||
self.split_waterfall_back(b, entry_pred, cond)
|
||||
} else {
|
||||
// `CondBr(match_or_done, exit, b)` — uncommon, skip conservatively.
|
||||
continue;
|
||||
};
|
||||
let Some(mut retry_terms) = self.collect_negated_wrlf_terms(b, &def_block, retry_v, 8) else {
|
||||
continue;
|
||||
};
|
||||
retry_terms.sort_unstable();
|
||||
retry_terms.dedup();
|
||||
if retry_terms.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Compute tainted instructions in `b` (phis, lane ops, and anything
|
||||
// transitively depending on them).
|
||||
let mut tainted = std::collections::HashSet::<u32>::new();
|
||||
for &p in &self.blocks[b].phis {
|
||||
tainted.insert(p);
|
||||
}
|
||||
for &i in &self.blocks[b].body {
|
||||
let mut is_t = self.class(&effects, i) == Effect::Lanes;
|
||||
if !is_t {
|
||||
for_each_operand(&self.insts[i as usize].op, |v| {
|
||||
if let V::Inst(u) = v
|
||||
&& tainted.contains(&u)
|
||||
{
|
||||
is_t = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
if is_t {
|
||||
tainted.insert(i);
|
||||
}
|
||||
}
|
||||
|
||||
// Every non-counter phi must be `select(match_mask, inv_val, phi)`
|
||||
// where `inv_val` is NOT tainted.
|
||||
let mut phi_updates: Vec<(u32, u32, V)> = Vec::new();
|
||||
let mut phis_ok = true;
|
||||
for &p in &self.blocks[b].phis {
|
||||
if Some(p) == iter_phi {
|
||||
continue;
|
||||
}
|
||||
let Op::Phi(inc) = &self.insts[p as usize].op else {
|
||||
phis_ok = false;
|
||||
break;
|
||||
};
|
||||
if inc.len() != 2 {
|
||||
phis_ok = false;
|
||||
break;
|
||||
}
|
||||
let Some(&(V::Inst(ni), _)) = inc.iter().find(|&&(_, from)| from == b) else {
|
||||
phis_ok = false;
|
||||
break;
|
||||
};
|
||||
if def_block[ni as usize] != b {
|
||||
phis_ok = false;
|
||||
break;
|
||||
}
|
||||
let Op::Select(sc, tv, fv) = self.insts[ni as usize].op else {
|
||||
phis_ok = false;
|
||||
break;
|
||||
};
|
||||
let new_val = if fv == V::Inst(p) {
|
||||
let Some(mut mt) = self.collect_wrlf_terms(b, &def_block, sc, 8) else {
|
||||
phis_ok = false;
|
||||
break;
|
||||
};
|
||||
mt.sort_unstable();
|
||||
mt.dedup();
|
||||
if mt != retry_terms {
|
||||
phis_ok = false;
|
||||
break;
|
||||
}
|
||||
tv
|
||||
} else if tv == V::Inst(p) {
|
||||
let Some(mut nt) = self.collect_negated_wrlf_terms(b, &def_block, sc, 8) else {
|
||||
phis_ok = false;
|
||||
break;
|
||||
};
|
||||
nt.sort_unstable();
|
||||
nt.dedup();
|
||||
if nt != retry_terms {
|
||||
phis_ok = false;
|
||||
break;
|
||||
}
|
||||
fv
|
||||
} else {
|
||||
phis_ok = false;
|
||||
break;
|
||||
};
|
||||
if matches!(new_val, V::Inst(u) if tainted.contains(&u)) {
|
||||
phis_ok = false;
|
||||
break;
|
||||
}
|
||||
phi_updates.push((p, ni, new_val));
|
||||
}
|
||||
if !phis_ok {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Ensure no other tainted instruction in `b` escapes to another block.
|
||||
let mut allowed_escape = std::collections::HashSet::<u32>::new();
|
||||
for &(p, ni, _) in &phi_updates {
|
||||
allowed_escape.insert(p);
|
||||
allowed_escape.insert(ni);
|
||||
}
|
||||
let mut escapes = false;
|
||||
for &ob in &tree.order {
|
||||
if ob == b {
|
||||
continue;
|
||||
}
|
||||
for &i in self.blocks[ob].phis.iter().chain(&self.blocks[ob].body) {
|
||||
for_each_operand(&self.insts[i as usize].op, |v| {
|
||||
if let V::Inst(u) = v
|
||||
&& tainted.contains(&u)
|
||||
&& !allowed_escape.contains(&u)
|
||||
{
|
||||
escapes = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(Term::CondBr(c, ..)) = self.blocks[ob].term
|
||||
&& let V::Inst(u) = c
|
||||
&& tainted.contains(&u)
|
||||
&& !allowed_escape.contains(&u)
|
||||
{
|
||||
escapes = true;
|
||||
}
|
||||
if escapes {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if escapes {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Sound to eliminate the loop! Keep `b` executing once straight to `exit`.
|
||||
for &(p, ni, new_val) in &phi_updates {
|
||||
repl[p as usize] = Some(new_val);
|
||||
repl[ni as usize] = Some(new_val);
|
||||
}
|
||||
self.blocks[b].phis.clear();
|
||||
self.blocks[b].term = Some(Term::Br(exit));
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if !changed {
|
||||
return false;
|
||||
}
|
||||
for blk in &mut self.blocks {
|
||||
if let Some(Term::CondBr(c, t, f)) = blk.term {
|
||||
blk.term = Some(Term::CondBr(resolve(&repl, c), t, f));
|
||||
}
|
||||
}
|
||||
let (blocks, insts) = (&self.blocks, &mut self.insts);
|
||||
for blk in blocks {
|
||||
for &i in blk.phis.iter().chain(&blk.body) {
|
||||
map_operands(&mut insts[i as usize].op, |v| resolve(&repl, v));
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn wrlf_arg(&self, v: V) -> Option<V> {
|
||||
let V::Inst(i) = v else { return None };
|
||||
let Op::Call(f, args) = &self.insts[i as usize].op else {
|
||||
return None;
|
||||
};
|
||||
if self.funcs[*f as usize].name.starts_with("dx.op.waveReadLaneFirst") && args.len() >= 2 {
|
||||
Some(args[1])
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn unpack64(&self, v: V) -> Option<(V, V)> {
|
||||
let V::Inst(i) = v else { return None };
|
||||
let Op::Bin(Bin::Or, a, b) = self.insts[i as usize].op else {
|
||||
return None;
|
||||
};
|
||||
let as_lo = |x: V| match x {
|
||||
V::Inst(k) => match self.insts[k as usize].op {
|
||||
Op::Cast(Cast::ZExt, src) => Some(src),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
let as_hi = |x: V| match x {
|
||||
V::Inst(k) => match self.insts[k as usize].op {
|
||||
Op::Bin(Bin::Shl, V::Inst(z), sh) if self.int_k(sh) == Some((64, 32)) => {
|
||||
match self.insts[z as usize].op {
|
||||
Op::Cast(Cast::ZExt, src) => Some(src),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
if let (Some(lo), Some(hi)) = (as_lo(a), as_hi(b)) {
|
||||
Some((lo, hi))
|
||||
} else if let (Some(lo), Some(hi)) = (as_lo(b), as_hi(a)) {
|
||||
Some((lo, hi))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn is_wrlf_eq(&self, b: usize, def_block: &[usize], i: u32) -> bool {
|
||||
if def_block[i as usize] != b {
|
||||
return false;
|
||||
}
|
||||
let Op::Cmp(pred::EQ, a, c) = self.insts[i as usize].op else {
|
||||
return false;
|
||||
};
|
||||
let in_b = |v: V| matches!(v, V::Inst(x) if def_block[x as usize] == b);
|
||||
let pair_matches = |w: V, raw: V| -> bool {
|
||||
if in_b(w) && !in_b(raw) && self.wrlf_arg(w) == Some(raw) {
|
||||
return true;
|
||||
}
|
||||
if let (Some((w0, w1)), Some((r0, r1))) = (self.unpack64(w), self.unpack64(raw)) {
|
||||
return in_b(w0)
|
||||
&& in_b(w1)
|
||||
&& !in_b(r0)
|
||||
&& !in_b(r1)
|
||||
&& self.wrlf_arg(w0) == Some(r0)
|
||||
&& self.wrlf_arg(w1) == Some(r1);
|
||||
}
|
||||
false
|
||||
};
|
||||
pair_matches(a, c) || pair_matches(c, a)
|
||||
}
|
||||
|
||||
fn collect_wrlf_terms(&self, b: usize, def_block: &[usize], v: V, depth: u32) -> Option<Vec<u32>> {
|
||||
if depth == 0 {
|
||||
return None;
|
||||
}
|
||||
let V::Inst(i) = v else { return None };
|
||||
if self.is_wrlf_eq(b, def_block, i) {
|
||||
return Some(vec![i]);
|
||||
}
|
||||
if let Op::Bin(Bin::And, x, y) = self.insts[i as usize].op {
|
||||
let mut a = self.collect_wrlf_terms(b, def_block, x, depth - 1)?;
|
||||
let mut c = self.collect_wrlf_terms(b, def_block, y, depth - 1)?;
|
||||
a.append(&mut c);
|
||||
return Some(a);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn collect_negated_wrlf_terms(
|
||||
&self,
|
||||
b: usize,
|
||||
def_block: &[usize],
|
||||
v: V,
|
||||
depth: u32,
|
||||
) -> Option<Vec<u32>> {
|
||||
if depth == 0 {
|
||||
return None;
|
||||
}
|
||||
let V::Inst(i) = v else { return None };
|
||||
match self.insts[i as usize].op {
|
||||
Op::Bin(Bin::Xor, x, y) => {
|
||||
if self.int_k(y) == Some((1, 1)) {
|
||||
self.collect_wrlf_terms(b, def_block, x, depth - 1)
|
||||
} else if self.int_k(x) == Some((1, 1)) {
|
||||
self.collect_wrlf_terms(b, def_block, y, depth - 1)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
Op::Select(cond, tv, fv) if self.int_k(fv) == Some((1, 1)) => {
|
||||
let mut a = self.collect_wrlf_terms(b, def_block, cond, depth - 1)?;
|
||||
let mut c = self.collect_negated_wrlf_terms(b, def_block, tv, depth - 1)?;
|
||||
a.append(&mut c);
|
||||
Some(a)
|
||||
}
|
||||
Op::Bin(Bin::Or, x, y) => {
|
||||
let mut a = self.collect_negated_wrlf_terms(b, def_block, x, depth - 1)?;
|
||||
let mut c = self.collect_negated_wrlf_terms(b, def_block, y, depth - 1)?;
|
||||
a.append(&mut c);
|
||||
Some(a)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn split_waterfall_back(&self, b: usize, entry_pred: usize, cond: V) -> (V, Option<u32>) {
|
||||
let is_limit = |v: V| -> Option<u32> {
|
||||
let V::Inst(i) = v else { return None };
|
||||
let (next_v, lim_v) = match self.insts[i as usize].op {
|
||||
Op::Cmp(pred::IULT, x, y) => (x, y),
|
||||
Op::Cmp(pred::IUGT, y, x) => (x, y),
|
||||
_ => return None,
|
||||
};
|
||||
let (_, k) = self.int_k(lim_v)?;
|
||||
if k < 64 {
|
||||
return None;
|
||||
}
|
||||
let V::Inst(ni) = next_v else { return None };
|
||||
let Op::Bin(Bin::Add, a, c) = self.insts[ni as usize].op else {
|
||||
return None;
|
||||
};
|
||||
let phi_v = if self.int_k(c) == Some((32, 1)) {
|
||||
a
|
||||
} else if self.int_k(a) == Some((32, 1)) {
|
||||
c
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
let V::Inst(p) = phi_v else { return None };
|
||||
if !self.blocks[b].phis.contains(&p) {
|
||||
return None;
|
||||
}
|
||||
let Op::Phi(inc) = &self.insts[p as usize].op else {
|
||||
return None;
|
||||
};
|
||||
if inc.len() == 2
|
||||
&& inc.iter().any(|&(val, from)| from == entry_pred && self.int_k(val) == Some((32, 0)))
|
||||
&& inc.iter().any(|&(val, from)| from == b && val == V::Inst(ni))
|
||||
{
|
||||
Some(p)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
if let V::Inst(i) = cond
|
||||
&& let Op::Bin(Bin::And, x, y) = self.insts[i as usize].op
|
||||
{
|
||||
if let Some(p) = is_limit(y) {
|
||||
return (x, Some(p));
|
||||
}
|
||||
if let Some(p) = is_limit(x) {
|
||||
return (y, Some(p));
|
||||
}
|
||||
}
|
||||
(cond, None)
|
||||
}
|
||||
|
||||
/// [`HOIST_HANDLES`]: hoists loop-invariant `createHandleFromHeap` (+
|
||||
/// `annotateHandle`) chains out of loops, and hoists constant or duplicated
|
||||
/// pure handle chains to their deepest dominating operand block so
|
||||
/// [`REUSE`] deduplicates them.
|
||||
fn hoist_handles(&mut self) -> bool {
|
||||
let effects = self.effects();
|
||||
let tree = self.dominator_tree();
|
||||
let n_blocks = self.blocks.len();
|
||||
let n_insts = self.insts.len();
|
||||
let mut def_block = vec![usize::MAX; n_insts];
|
||||
for &b in &tree.order {
|
||||
for &i in self.blocks[b].phis.iter().chain(&self.blocks[b].body) {
|
||||
def_block[i as usize] = b;
|
||||
}
|
||||
}
|
||||
|
||||
// Identify natural loops: for each back-edge `tail -> hdr` where `hdr`
|
||||
// dominates `tail`, collect all blocks in the loop.
|
||||
let mut enclosing: Vec<Vec<usize>> = vec![Vec::new(); n_blocks];
|
||||
for &tail in &tree.order {
|
||||
for &hdr in successors(self.blocks[tail].term).iter() {
|
||||
if !tree.dominates(hdr, tail) {
|
||||
continue;
|
||||
}
|
||||
let mut in_loop = vec![false; n_blocks];
|
||||
in_loop[hdr] = true;
|
||||
let mut stack = Vec::new();
|
||||
if tail != hdr {
|
||||
in_loop[tail] = true;
|
||||
stack.push(tail);
|
||||
}
|
||||
while let Some(cur) = stack.pop() {
|
||||
for &p in &tree.preds[cur] {
|
||||
if !in_loop[p] {
|
||||
in_loop[p] = true;
|
||||
stack.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (blk, &yes) in in_loop.iter().enumerate() {
|
||||
if yes && !enclosing[blk].contains(&hdr) {
|
||||
enclosing[blk].push(hdr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for hdrs in &mut enclosing {
|
||||
hdrs.sort_by_key(|&h| tree.depth[h]);
|
||||
}
|
||||
|
||||
let is_heap_handle = |f: u32| self.funcs[f as usize].name == "dx.op.createHandleFromHeap";
|
||||
let is_annotate = |f: u32| self.funcs[f as usize].name == "dx.op.annotateHandle";
|
||||
|
||||
// Build structural key for each `createHandleFromHeap` to detect
|
||||
// duplicates across sibling branches.
|
||||
let mut handle_counts: HashMap<String, u32> = HashMap::new();
|
||||
let mut handle_keys: HashMap<u32, (String, bool)> = HashMap::new();
|
||||
for &b in &tree.order {
|
||||
for &i in &self.blocks[b].body {
|
||||
if let Op::Call(f, args) = &self.insts[i as usize].op
|
||||
&& is_heap_handle(*f)
|
||||
&& args.len() >= 4
|
||||
{
|
||||
let idx_s = self.pure_expr_sig(args[1], &effects, 6);
|
||||
let is_const_idx = self.is_const_pure(args[1], &effects, 6);
|
||||
let k = format!("{}:{:?}:{:?}", idx_s, args[2], args[3]);
|
||||
*handle_counts.entry(k.clone()).or_default() += 1;
|
||||
handle_keys.insert(i, (k, is_const_idx));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Map `createHandleFromHeap` -> `annotateHandle`s in the same block.
|
||||
let mut annots: HashMap<u32, Vec<u32>> = HashMap::new();
|
||||
for &b in &tree.order {
|
||||
for &i in &self.blocks[b].body {
|
||||
if let Op::Call(f, args) = &self.insts[i as usize].op
|
||||
&& is_annotate(*f)
|
||||
&& let Some(&V::Inst(h)) = args.get(1)
|
||||
&& def_block[h as usize] == b
|
||||
{
|
||||
annots.entry(h).or_default().push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut moved = vec![false; n_insts];
|
||||
let mut to_append: Vec<Vec<u32>> = vec![Vec::new(); n_blocks];
|
||||
let mut changed = false;
|
||||
|
||||
for &b in &tree.order {
|
||||
if b == 0 {
|
||||
continue;
|
||||
}
|
||||
let body_snapshot = self.blocks[b].body.clone();
|
||||
for h in body_snapshot {
|
||||
if moved[h as usize] {
|
||||
continue;
|
||||
}
|
||||
let Some((key, is_const_idx)) = handle_keys.get(&h) else {
|
||||
continue;
|
||||
};
|
||||
// 1) Try hoisting out of enclosing loops (outermost first).
|
||||
let mut chosen: Option<(usize, Vec<u32>)> = None;
|
||||
for &hdr in &enclosing[b] {
|
||||
let pre = tree.idom[hdr];
|
||||
if pre == hdr || pre == usize::MAX || pre == b {
|
||||
continue;
|
||||
}
|
||||
if let Some(slice) = self.collect_hoist_slice(h, pre, &tree, &def_block, &effects) {
|
||||
chosen = Some((pre, slice));
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 2) For constant indices (e.g. samplers) or handles used >=2
|
||||
// times, hoist to the deepest dominating leaf block.
|
||||
if chosen.is_none()
|
||||
&& (*is_const_idx || handle_counts.get(key).copied().unwrap_or(0) >= 2)
|
||||
&& let Some((target, slice)) = self.collect_hoist_deepest(h, b, &tree, &def_block, &effects)
|
||||
&& target != b
|
||||
{
|
||||
chosen = Some((target, slice));
|
||||
}
|
||||
|
||||
let Some((target, slice)) = chosen else {
|
||||
continue;
|
||||
};
|
||||
for inst_id in slice {
|
||||
if !moved[inst_id as usize] && def_block[inst_id as usize] != target {
|
||||
moved[inst_id as usize] = true;
|
||||
def_block[inst_id as usize] = target;
|
||||
to_append[target].push(inst_id);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if let Some(list) = annots.get(&h) {
|
||||
for &a in list {
|
||||
if !moved[a as usize] && def_block[a as usize] != target {
|
||||
moved[a as usize] = true;
|
||||
def_block[a as usize] = target;
|
||||
to_append[target].push(a);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !changed {
|
||||
return false;
|
||||
}
|
||||
for b in 0..n_blocks {
|
||||
self.blocks[b].body.retain(|&i| !moved[i as usize]);
|
||||
}
|
||||
for (b, extra) in to_append.into_iter().enumerate() {
|
||||
self.blocks[b].body.extend(extra);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn is_hoistable_pure(&self, i: u32, effects: &[Effect]) -> bool {
|
||||
matches!(
|
||||
self.insts[i as usize].op,
|
||||
Op::Bin(..) | Op::Cast(..) | Op::Cmp(..) | Op::Select(..) | Op::Extract(..) | Op::Call(..)
|
||||
) && self.class(effects, i) == Effect::Pure
|
||||
}
|
||||
|
||||
fn pure_expr_sig(&self, v: V, effects: &[Effect], depth: u32) -> String {
|
||||
let V::Inst(i) = v else {
|
||||
return format!("{v:?}");
|
||||
};
|
||||
if depth == 0 || !self.is_hoistable_pure(i, effects) {
|
||||
return format!("I{i}");
|
||||
}
|
||||
match &self.insts[i as usize].op {
|
||||
Op::Bin(op, a, b) => format!(
|
||||
"B({:?},{},{})",
|
||||
op,
|
||||
self.pure_expr_sig(*a, effects, depth - 1),
|
||||
self.pure_expr_sig(*b, effects, depth - 1)
|
||||
),
|
||||
Op::Cast(op, a) => format!("C({:?},{})", op, self.pure_expr_sig(*a, effects, depth - 1)),
|
||||
Op::Call(f, args) => {
|
||||
let parts: Vec<String> = args
|
||||
.iter()
|
||||
.map(|&a| self.pure_expr_sig(a, effects, depth - 1))
|
||||
.collect();
|
||||
format!("F({f},{})", parts.join(","))
|
||||
}
|
||||
_ => format!("I{i}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_const_pure(&self, v: V, effects: &[Effect], depth: u32) -> bool {
|
||||
match v {
|
||||
V::Const(_) => true,
|
||||
V::Inst(i) if depth > 0 && self.is_hoistable_pure(i, effects) => {
|
||||
let mut ok = true;
|
||||
for_each_operand(&self.insts[i as usize].op, |op| {
|
||||
if !self.is_const_pure(op, effects, depth - 1) {
|
||||
ok = false;
|
||||
}
|
||||
});
|
||||
ok
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Collects the pure DAG rooted at `root` whose instructions do not yet
|
||||
/// dominate `target`, returning them in topological order (operands first).
|
||||
fn collect_hoist_slice(
|
||||
&self,
|
||||
root: u32,
|
||||
target: usize,
|
||||
tree: &Tree,
|
||||
def_block: &[usize],
|
||||
effects: &[Effect],
|
||||
) -> Option<Vec<u32>> {
|
||||
let mut order = Vec::new();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn dfs(
|
||||
m: &Module,
|
||||
i: u32,
|
||||
target: usize,
|
||||
tree: &Tree,
|
||||
def_block: &[usize],
|
||||
effects: &[Effect],
|
||||
seen: &mut std::collections::HashSet<u32>,
|
||||
order: &mut Vec<u32>,
|
||||
) -> bool {
|
||||
let db = def_block[i as usize];
|
||||
if db == usize::MAX {
|
||||
return false;
|
||||
}
|
||||
if tree.dominates(db, target) {
|
||||
return true;
|
||||
}
|
||||
if !seen.insert(i) {
|
||||
return true;
|
||||
}
|
||||
if order.len() >= 16 || !m.is_hoistable_pure(i, effects) {
|
||||
return false;
|
||||
}
|
||||
let mut ok = true;
|
||||
for_each_operand(&m.insts[i as usize].op, |v| {
|
||||
if let V::Inst(u) = v
|
||||
&& !dfs(m, u, target, tree, def_block, effects, seen, order)
|
||||
{
|
||||
ok = false;
|
||||
}
|
||||
});
|
||||
if ok {
|
||||
order.push(i);
|
||||
}
|
||||
ok
|
||||
}
|
||||
dfs(self, root, target, tree, def_block, effects, &mut seen, &mut order).then_some(order)
|
||||
}
|
||||
|
||||
/// Walks the pure DAG rooted at `root` (up to 16 pure instructions in
|
||||
/// non-entry blocks) to find the deepest dominating leaf block `target`.
|
||||
fn collect_hoist_deepest(
|
||||
&self,
|
||||
root: u32,
|
||||
cur_block: usize,
|
||||
tree: &Tree,
|
||||
def_block: &[usize],
|
||||
effects: &[Effect],
|
||||
) -> Option<(usize, Vec<u32>)> {
|
||||
let mut order = Vec::new();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut deepest = 0usize;
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn dfs(
|
||||
m: &Module,
|
||||
i: u32,
|
||||
tree: &Tree,
|
||||
def_block: &[usize],
|
||||
effects: &[Effect],
|
||||
seen: &mut std::collections::HashSet<u32>,
|
||||
order: &mut Vec<u32>,
|
||||
deepest: &mut usize,
|
||||
) -> bool {
|
||||
let db = def_block[i as usize];
|
||||
if db == usize::MAX {
|
||||
return false;
|
||||
}
|
||||
if db == 0 || !m.is_hoistable_pure(i, effects) || order.len() >= 16 {
|
||||
if tree.depth[db] > tree.depth[*deepest] {
|
||||
*deepest = db;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if !seen.insert(i) {
|
||||
return true;
|
||||
}
|
||||
let mut ok = true;
|
||||
for_each_operand(&m.insts[i as usize].op, |v| {
|
||||
if let V::Inst(u) = v
|
||||
&& !dfs(m, u, tree, def_block, effects, seen, order, deepest)
|
||||
{
|
||||
ok = false;
|
||||
}
|
||||
});
|
||||
if ok {
|
||||
order.push(i);
|
||||
}
|
||||
ok
|
||||
}
|
||||
if !dfs(self, root, tree, def_block, effects, &mut seen, &mut order, &mut deepest) {
|
||||
return None;
|
||||
}
|
||||
if !tree.dominates(deepest, cur_block) {
|
||||
return None;
|
||||
}
|
||||
// Keep only instructions not already dominating `deepest`.
|
||||
order.retain(|&i| !tree.dominates(def_block[i as usize], deepest));
|
||||
Some((deepest, order))
|
||||
}
|
||||
|
||||
/// Whether instruction `i` must stay whatever reads it.
|
||||
fn has_effect(&self, effects: &[Effect], i: u32) -> bool {
|
||||
match &self.insts[i as usize].op {
|
||||
|
||||
@@ -142,6 +142,17 @@ const POPS_PACKER: u16 = 25;
|
||||
/// The operand `src_pops_exiting_wave_id`.
|
||||
const POPS_EXITING: u8 = 239;
|
||||
|
||||
/// Whether pixel float colour outputs are held to the console's HDR range
|
||||
/// `[-65024, 65024]` (`VICTORY_HDR_CLAMP=1`: on; off by default because
|
||||
/// clamping every MRT pixel output adds heavy GPU overhead on 6 GB laptops,
|
||||
/// while `VICTORY_COMPOSE_NAN` + `ambient.rs` already scrub NaNs at compose).
|
||||
fn hdr_clamp() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_HDR_CLAMP").is_some_and(|v| v == "1"))
|
||||
}
|
||||
|
||||
const HDR_MAX: f32 = 65024.0;
|
||||
|
||||
/// The instructions inside a pixel program's ordered section
|
||||
/// (primitive-ordered pixel shading, which the console compiler makes of
|
||||
/// rasterizer ordered views): from the write of `POPS_PACKER`, along every
|
||||
@@ -1466,7 +1477,24 @@ pub(super) fn host_rdna() -> u32 {
|
||||
if let Some(bits) = TEST_RDNA.get() {
|
||||
return bits;
|
||||
}
|
||||
if HOST_RDNA.load(std::sync::atomic::Ordering::Relaxed) { super::rdna_float() } else { 0 }
|
||||
static EXPLICIT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
let explicit = *EXPLICIT.get_or_init(|| std::env::var_os("VICTORY_RDNA_FLOAT").is_some());
|
||||
if HOST_RDNA.load(std::sync::atomic::Ordering::Relaxed) || explicit {
|
||||
super::rdna_float()
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
/// Optional override for `v_mul_legacy_f32` lowering (`VICTORY_LEGACY_MUL`):
|
||||
/// `plain` emits plain `fmul`; `isnan` emits `r = a * b; select(isnan(r), 0.0, r)`.
|
||||
fn legacy_mul_mode() -> u8 {
|
||||
static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
|
||||
*MODE.get_or_init(|| match std::env::var("VICTORY_LEGACY_MUL").as_deref() {
|
||||
Ok("plain") => 1,
|
||||
Ok("isnan") => 2,
|
||||
_ => 0,
|
||||
})
|
||||
}
|
||||
|
||||
/// The refusal of a first half of an interpolation whose result is read
|
||||
@@ -4248,6 +4276,21 @@ impl<'a> Lower<'a> {
|
||||
self.s.m.select(c, keep, r, t)
|
||||
}
|
||||
|
||||
/// Holds a pixel float colour output to `[-65024, 65024]` (`VICTORY_HDR_CLAMP`).
|
||||
/// Prevents >65504 values from becoming `+Inf` in 16-bit float host targets.
|
||||
fn clamp_hdr(&mut self, f: V) -> V {
|
||||
if !hdr_clamp() {
|
||||
return f;
|
||||
}
|
||||
let c = self.cur;
|
||||
let min = self.s.m.f32((-HDR_MAX).to_bits());
|
||||
let max = self.s.m.f32(HDR_MAX.to_bits());
|
||||
let lo = self.binary(35, f, min); // FMax
|
||||
let hi = self.binary(36, lo, max); // FMin
|
||||
let nan = self.is_nan_f32(f);
|
||||
self.s.m.select(c, nan, max, hi)
|
||||
}
|
||||
|
||||
/// Whether an f32 value is NaN, tested in integer arithmetic so host
|
||||
/// drivers (such as NVIDIA) do not fold `fcmp uno` away under fast-math.
|
||||
fn is_nan_f32(&mut self, f: V) -> V {
|
||||
@@ -4357,6 +4400,16 @@ impl<'a> Lower<'a> {
|
||||
/// `0 × anything = 0`, as in D3D9.
|
||||
fn legacy_mul(&mut self, a: V, b: V) -> V {
|
||||
let c = self.cur;
|
||||
match legacy_mul_mode() {
|
||||
1 => return self.s.m.bin(c, Bin::Mul, a, b),
|
||||
2 => {
|
||||
let m = self.s.m.bin(c, Bin::Mul, a, b);
|
||||
let nan = self.s.m.cmp(c, pred::UNO, m, m);
|
||||
let zero = self.s.m.f32(0);
|
||||
return self.s.m.select(c, nan, zero, m);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if host_rdna() & super::rdna::LEGACY != 0 {
|
||||
let m = self.s.m.bin(c, Bin::Mul, a, b);
|
||||
let zero = self.s.m.f32(0);
|
||||
@@ -10045,15 +10098,17 @@ impl<'a> Lower<'a> {
|
||||
return Err("a 16-bit result outside a VGPR");
|
||||
};
|
||||
let mut high = v.opsel >> 3 & 1 != 0;
|
||||
// SDWA: the word written, the other one kept (preserve) or zero
|
||||
// (pad; a sign extension above the high word adds nothing).
|
||||
// UNUSED_SEXT extends bit 15 only for WORD_0. WORD_1 has
|
||||
// nothing above it to extend, and its low word is zero-padded.
|
||||
let mut keep = true;
|
||||
let mut sext = false;
|
||||
if let Some(sd) = v.sdwa {
|
||||
match (sd.dst_sel, sd.dst_unused) {
|
||||
(4, 2) => {}
|
||||
(5, 2) => high = true,
|
||||
(4 | 6, _) => keep = false,
|
||||
(5, _) => (high, keep) = (true, false),
|
||||
(4, 1) => (keep, sext) = (false, true),
|
||||
(4, 0) | (6, 0..=2) => keep = false,
|
||||
(5, 0 | 1) => (high, keep) = (true, false),
|
||||
_ => return Err("an SDWA destination of a 16-bit operation"),
|
||||
}
|
||||
}
|
||||
@@ -10064,7 +10119,10 @@ impl<'a> Lower<'a> {
|
||||
};
|
||||
let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
|
||||
let x = self.s.m.bin(c, Bin::And, x, low);
|
||||
let r = if high {
|
||||
let r = if sext {
|
||||
let shifted = self.s.m.bin(c, Bin::Shl, x, k16);
|
||||
self.s.m.bin(c, Bin::AShr, shifted, k16)
|
||||
} else if high {
|
||||
let o = self.s.m.bin(c, Bin::And, old, low);
|
||||
let x = self.s.m.bin(c, Bin::Shl, x, k16);
|
||||
self.s.m.bin(c, Bin::Or, o, x)
|
||||
@@ -13202,16 +13260,21 @@ impl<'a> Lower<'a> {
|
||||
.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
|
||||
x = self.as_int(f);
|
||||
}
|
||||
let is_ps = !mesh && matches!(self.x.native.stage, HwStage::Ps);
|
||||
let el = &mut elements(self, primitive)[id];
|
||||
el.usage |= 1 << col;
|
||||
let hdr = is_ps && el.kind == 16;
|
||||
let (suffix, x) = match el.comp {
|
||||
9 if half.is_some() => (".f32", self.as_float(x)),
|
||||
9 if half.is_some() => {
|
||||
let f = self.as_float(x);
|
||||
(".f32", if hdr { self.clamp_hdr(f) } else { f })
|
||||
}
|
||||
9 => {
|
||||
let f = match self.floats.get(&value) {
|
||||
Some(&f) => f,
|
||||
None => self.as_float(x),
|
||||
};
|
||||
(".f32", f)
|
||||
(".f32", if hdr { self.clamp_hdr(f) } else { f })
|
||||
}
|
||||
_ => (".i32", x),
|
||||
};
|
||||
@@ -14314,4 +14377,31 @@ mod tests {
|
||||
// A 16-bit float is a half already, sign included.
|
||||
assert_eq!(half(0xBC00 << half_shift(16)), -1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sdwa_16bit_reserved_dst_unused_is_refused() {
|
||||
for dst_sel in [4u32, 5] {
|
||||
// v_cvt_i16_f16_sdwa v1, v0 dst_sel:{WORD_0,WORD_1} dst_unused:3 (reserved);
|
||||
// ds_write_b32 v0, v1 to keep v1 live.
|
||||
let sdwa_ext = (dst_sel << 8) | (3 << 11) | (4 << 16);
|
||||
let words = [
|
||||
0x7E02_A6F9, // v_cvt_i16_f16 v1, sdwa
|
||||
sdwa_ext,
|
||||
0xD834_0000,
|
||||
0x0000_0100, // ds_write_b32 v0, v1
|
||||
S_ENDPGM,
|
||||
];
|
||||
let err = lowers(&words, 1 << 15).expect_err("reserved dst_unused must fail");
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
crate::ShaderError::Unsupported {
|
||||
what: "an SDWA destination of a 16-bit operation",
|
||||
..
|
||||
}
|
||||
),
|
||||
"unexpected error for dst_sel={dst_sel}: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1421,7 +1421,7 @@ mod tests {
|
||||
assert_eq!(parse_shader_opt(Some("0")), 0);
|
||||
assert_eq!(parse_shader_opt(Some(" 1 ")), 1);
|
||||
assert_eq!(parse_shader_opt(Some("0x1")), 1);
|
||||
assert_eq!(parse_shader_opt(Some("127")), all);
|
||||
assert_eq!(parse_shader_opt(Some("511")), all);
|
||||
assert_eq!(parse_shader_opt(Some("0xffffffff")), all);
|
||||
assert_eq!(parse_shader_opt(Some("on")), usual);
|
||||
}
|
||||
@@ -2753,7 +2753,7 @@ mod tests {
|
||||
let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap();
|
||||
let io = crate::io::raise(&p, &native).unwrap();
|
||||
let st = crate::structure::structure(&p).unwrap();
|
||||
let l = super::lower::lower(&super::lower::Parts {
|
||||
super::lower::lower(&super::lower::Parts {
|
||||
native: &native,
|
||||
p: &p,
|
||||
st: &st,
|
||||
@@ -2764,8 +2764,7 @@ mod tests {
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
})
|
||||
.unwrap();
|
||||
l
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -375,6 +375,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> Left {
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let f16_inline = name == "v_add_f16";
|
||||
let lanes = |op: &Operand,
|
||||
vec: &HashMap<Value, Vec<Sym>>,
|
||||
uni: &HashMap<Value, Sym>|
|
||||
@@ -392,6 +393,12 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> Left {
|
||||
Some(x) => one(uni.get(&x).copied().unwrap_or(Sym::Uni(x))),
|
||||
None => one(Sym::Unknown),
|
||||
},
|
||||
Operand::Const(c @ 240..=248) if f16_inline => {
|
||||
let h = [
|
||||
0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118,
|
||||
][usize::from(c - 240)];
|
||||
one(Sym::K(h))
|
||||
}
|
||||
Operand::Const(c) => one(crate::resource::inline(c).map_or(Sym::Unknown, Sym::K)),
|
||||
Operand::Literal(x) => one(Sym::K(x)),
|
||||
_ => one(Sym::Unknown),
|
||||
@@ -1289,4 +1296,39 @@ mod tests {
|
||||
assert_eq!(per_lane(&bad_ident, all), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v_add_f16_inline_float_constants_are_not_zero_identity() {
|
||||
let run = |src_const: u16| -> (Option<Shape>, Value, Value) {
|
||||
let mut w = vec![sop1(0, 0x3D, 193)]; // s_or_saveexec_b32 s0, -1
|
||||
w.extend(vop3(1, 0x101, 128, 256, 0)); // v_cndmask_b32 v1, 0, v0, s0
|
||||
w.push(vop2(1, 0x32, src_const, 1)); // v_add_f16 v1, <const>, v1
|
||||
for ctrl in [0x00B1u16, 0x004E, 0x0164, 0x0168] {
|
||||
w.push(vop2(1, 0x32, 0xFA, 1));
|
||||
w.push(dpp16(1, ctrl, 0xF, 0xF, false));
|
||||
}
|
||||
w.extend(vop3(2, 0x378, 257, 128, 128)); // v_permlanex16_b32 v2, v1, 0, 0
|
||||
w.push(vop2(1, 0x32, 258, 1)); // v_add_f16 v1, v2, v1
|
||||
w.extend(vop3(1, 0x360, 257, 128 + 31, 0)); // v_readlane_b32 s1, v1, 31
|
||||
w.push(sop1(EXEC, 0x03, 0)); // s_mov_b32 exec_lo, s0
|
||||
|
||||
let p = build(&w, false);
|
||||
let insts = &p.blocks[0].insts;
|
||||
let saved = insts[0].write(Reg::S(0)).unwrap();
|
||||
let v0_in = insts[1].read(Reg::V(0)).unwrap();
|
||||
let s1 = insts[insts.len() - 3].write(Reg::S(1)).unwrap();
|
||||
let sec = §ions(&p, 0)[&0];
|
||||
(sec.shapes.get(&s1).copied(), v0_in, saved)
|
||||
};
|
||||
|
||||
let (zero_shape, v0_in, saved) = run(128);
|
||||
assert_eq!(
|
||||
zero_shape,
|
||||
Some(Shape::Active(Op::AddH, v0_in, saved, 0))
|
||||
);
|
||||
for c in 240..=248u16 {
|
||||
let (shape, _, _) = run(c);
|
||||
assert_eq!(shape, None, "inline float const {c} was treated as identity");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
# Troubleshooting Guide (6 GB VRAM / 16 GB RAM & Windows)
|
||||
|
||||
> Back to main setup guide: **[README.md](../README.md)** · Detailed memory notes: **[windows-memory.md](windows-memory.md)** · DLSS/FG details: **[dlss.md](dlss.md)**
|
||||
|
||||
## Quick Jump
|
||||
|
||||
- [1. Out of Memory / Crashes on 16 GB RAM (32–48 GB SSD Pagefile Setup)](#1-out-of-memory--crashes-on-16-gb-ram-3248-gb-ssd-pagefile-setup)
|
||||
- [2. Wrong or Broken F1 Settings (How to Reset)](#2-wrong-or-broken-f1-settings-how-to-reset)
|
||||
- [3. Graphics & Lighting Issues (Blinding Sun, Indoor Flashing, White Dots, Blurry Image, Missing Heads)](#3-graphics--lighting-issues)
|
||||
- [4. Low FPS, Stuttering, Input Lag, & Laptop Thermal Throttling](#4-low-fps-stuttering-input-lag--laptop-thermal-throttling)
|
||||
- [5. DLSS or FSR 3 Frame Generation Not Working](#5-dlss-or-fsr-3-frame-generation-not-working)
|
||||
- [6. Build, Git Pull, Windows 10, & Launch Errors](#6-build-git-pull-windows-10--launch-errors)
|
||||
- [7. Shader Preloading (`-Preload`) & Pop-In in New Areas](#7-shader-preloading--pop-in-in-new-areas)
|
||||
- [8. Collecting Logs for Bug Reports](#8-collecting-logs-for-bug-reports)
|
||||
|
||||
---
|
||||
|
||||
## 1. Out of Memory / Crashes on 16 GB RAM (32–48 GB SSD Pagefile Setup)
|
||||
|
||||
Open-world texture and buffer streaming temporarily reserves more virtual commit than 16 GB of physical RAM. If Windows' pagefile is too small, the emulator will crash with `E_OUTOFMEMORY` or exit during loading.
|
||||
|
||||
### Step-by-Step: Set a 32–48 GB Custom SSD Pagefile
|
||||
1. Press **`Win + R`**, type **`sysdm.cpl`**, and press **Enter**.
|
||||
2. Open the **Advanced** tab → under **Performance**, click **Settings…**.
|
||||
3. Open the **Advanced** tab → under **Virtual memory**, click **Change…**.
|
||||
4. Uncheck **Automatically manage paging file size for all drives**.
|
||||
5. Select your fastest **SSD** (C: or D: with at least 60 GB free).
|
||||
6. Select **Custom size**:
|
||||
- **Initial size (MB):** `32768` *(32 GB)*
|
||||
- **Maximum size (MB):** `49152` *(48 GB)*
|
||||
7. Click **Set** → **OK** → **OK** → **Restart your PC**.
|
||||
|
||||
### Verify It Worked
|
||||
- Open **Task Manager** (`Ctrl + Shift + Esc`) → **Performance** → **Memory**.
|
||||
- Check **Committed**: the right-hand limit should now show **48–64 GB** (16 GB RAM + 32–48 GB pagefile).
|
||||
- Before launching, close heavy background apps (Chrome/Edge tabs, Discord, IDEs) to maximize free physical RAM.
|
||||
|
||||
---
|
||||
|
||||
## 2. Wrong or Broken F1 Settings (How to Reset)
|
||||
|
||||
Changes saved in the **F1** menu are written to `victory-settings.txt` and **override the launcher script on every future launch**. If you accidentally turned off lighting, broke resolution, or switched to blurry settings:
|
||||
|
||||
- **In-game (easiest):** Press **`F1`**, scroll to **`RESET ALL TO PLAY DEFAULTS`**, and press **Enter**. *(Do NOT press `SAVE AND RESTART NOW` if you want to discard bad changes.)*
|
||||
- **Outside the game:** Delete the saved settings file and relaunch:
|
||||
```powershell
|
||||
Remove-Item "$env:LOCALAPPDATA\victory\victory-settings.txt" -ErrorAction SilentlyContinue
|
||||
# If you set VICTORY_HOME (for example D:\victory):
|
||||
Remove-Item "$env:VICTORY_HOME\victory-settings.txt" -ErrorAction SilentlyContinue
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Graphics & Lighting Issues
|
||||
|
||||
### Pitch-black character / dark rooms indoors with glowing eyes
|
||||
- **Cause:** `LIGHT ESTIMATE` (`VICTORY_AMBIENT`) and/or `REFLECTION ESTIMATE` (`VICTORY_AMBIENT_SPECULAR`) was saved as OFF in `victory-settings.txt`.
|
||||
- **Fix:** Reset F1 settings to defaults (see [Section 2](#2-wrong-or-broken-f1-settings-how-to-reset)). `play-6gb.ps1` uses `VICTORY_AMBIENT=0.65` and `VICTORY_AMBIENT_SPECULAR=1`.
|
||||
|
||||
### Sunlight looks blinding / overexposed
|
||||
- **Cause:** `VICTORY_AMBIENT` set too high (`0.8`–`1.0`).
|
||||
- **Fix:** Lower **`LIGHT ESTIMATE`** in F1 (or set `VICTORY_AMBIENT=0.65` / `0.55`).
|
||||
|
||||
### Indoor rooms flashing / strobing bright and dark
|
||||
- **Cause:** `VICTORY_AMBIENT_ONCE=1` can oscillate frame-to-frame indoors where there is little direct light.
|
||||
- **Fix:** Do **not** set `VICTORY_AMBIENT_ONCE=1`. Use the default `play-6gb.ps1` settings (`VICTORY_AMBIENT=0.65`, `VICTORY_AMBIENT_ONCE` unset).
|
||||
|
||||
### White dots / specular fireflies / violet tint
|
||||
- **Cause:** Skipping screen-probe or reflection shaders via extra hashes in `VICTORY_LEAVE_OUT`.
|
||||
- **Fix:** Only leave out the 2 safe passes (`VICTORY_LEAVE_OUT=02384a60fda6f2d0,731a39171b568298`), which is already default in `play-6gb.ps1`. If shiny surfaces still show bright speckles, toggle **`REFLECTION ESTIMATE`** in F1.
|
||||
|
||||
### Image looks very blurry or textures look muddy
|
||||
- **Cause:** Running `640x360` DLSS Ultra Performance (`-Dlss ultraperformance`) and/or Quarter textures (`-DropMips 2`).
|
||||
- **Fix:** Use the sharp 1080p default (`960x540` DLSS Performance + Half textures):
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File scripts\play-6gb.ps1 -Exe 'D:\path\to\your.exe' -Dlss performance -DropMips 1
|
||||
```
|
||||
You can also change **`SERIES S PICTURE`** (`960X540` / `1113X626` / `1280X720`) and **`TEXTURE SCALE (VRAM)`** (`HALF (6GB GPU)`) in F1.
|
||||
|
||||
### Missing character heads or disappearing geometry
|
||||
- **Cause:** `VICTORY_THIN=1` (`THIN LISTS = 1` in F1) can drop geometry/heads on some builds and increases RAM usage on 16 GB PCs.
|
||||
- **Fix:** Keep **`THIN LISTS`** set to **`0`** (`VICTORY_THIN=0`, default in `play-6gb.ps1`).
|
||||
|
||||
### Dark/blocky patches on water
|
||||
- **Cause:** `WATER LIGHT` turned off, or outdated shader cache from an older build.
|
||||
- **Fix:** Keep **`WATER LIGHT: ON`** in F1 (`VICTORY_WATER_LIGHT=1`).
|
||||
|
||||
---
|
||||
|
||||
## 4. Low FPS, Stuttering, Input Lag, & Laptop Thermal Throttling
|
||||
|
||||
### Laptop FPS starts fine (~10–12 real / 20–24 FG) then drops after 15–20 minutes
|
||||
- **Cause:** Thermal throttling — once a gaming laptop heatsink saturates at **85–86 °C**, CPU turbo clocks drop by 30–40%, directly lowering FPS.
|
||||
- **Fix:**
|
||||
- Always play plugged into **AC power**.
|
||||
- Switch your OEM control app (Lenovo Vantage / Armoury Crate / NitroSense / OMEN) to **Performance Mode** (`Fn + Q`) with **Max / Performance fan curve**.
|
||||
- Elevate the back of the laptop 1–2 cm (or use a cooling pad) so bottom intake vents breathe freely.
|
||||
|
||||
### Low FPS on Intel 12th–14th Gen hybrid CPUs (P-cores + E-cores)
|
||||
- **Cause:** Pinning worker threads exclusively to P-cores (`VICTORY_FAST_CORES=2`) starves the submission and recording threads on 4P+4E / 6P+4E CPUs.
|
||||
- **Fix:** Keep **`VICTORY_FAST_CORES=0`** (already default in `play-6gb.ps1` — typically +13% to +16% real FPS on hybrid CPUs).
|
||||
|
||||
### Stuttering while roaming on 6 GB VRAM GPUs
|
||||
- **Cause:** VRAM exceeding your DXGI local budget (~5.0–5.2 GB on 6 GB cards), causing Windows (WDDM) to spill textures over PCIe into system RAM.
|
||||
- **Fix:**
|
||||
- Press **`F3`** to watch the `VRAM X.X / Y.Y GB` readout — keep usage comfortably below the budget (`4.2–4.8 GB`).
|
||||
- Keep `DropMips=1` with `WINDOWS_BAR_MB=128–256` (default in `play-6gb.ps1`), or drop to `-DropMips 2` (`QUARTER` in F1) on 4 GB cards.
|
||||
- Ensure `VICTORY_SLOT_EVICT_PERCENT` (`92`) stays strictly higher than `VICTORY_TEXTURE_ROOM_PERCENT` (`82–85`) so eviction doesn't thrash every second.
|
||||
|
||||
### Sluggish controls / input lag with Frame Generation ON
|
||||
- **Cause:** Frame Generation adds ~1 frame of presentation latency (noticeable when base real FPS is ~10 fps).
|
||||
- **Fix:** Launch with **`-NoFrameGen`** or set **`FRAME GENERATION: OFF`** in F1 for lowest input latency:
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File scripts\play-6gb.ps1 -Exe 'D:\path\to\your.exe' -NoFrameGen
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. DLSS or FSR 3 Frame Generation Not Working
|
||||
|
||||
- **Missing DLLs:** Make sure you ran the one-time download scripts from inside the repository folder:
|
||||
```powershell
|
||||
.\Get-NVIDIA-DLSS.cmd
|
||||
.\Get-AMD-FSR.cmd
|
||||
```
|
||||
- **Window not focused:** Both DLSS FG and FSR 3 FG only generate interpolated frames while the game window is the active focused window.
|
||||
- **RTX 20 / 30 or AMD / Intel GPU:** Use **AMD FSR 3 (`-FgType fsr`, default in `play-6gb.ps1`)** for 2X Frame Generation. Native DLSS Frame Generation (`-FgType dlss`) requires **RTX 40 / 50** plus **Hardware-Accelerated GPU Scheduling (HAGS)** enabled in *Windows Settings → System → Display → Graphics → Default graphics settings*.
|
||||
- **Do not enable `MFG UNLOCKER` on RTX 20/30:** Multi-Frame Generation unlocker only applies to RTX 40/50 DLSS FG.
|
||||
|
||||
---
|
||||
|
||||
## 6. Build, Git Pull, Windows 10, & Launch Errors
|
||||
|
||||
### PowerShell says "running scripts is disabled on this system"
|
||||
Always launch with `-ExecutionPolicy Bypass`:
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File scripts\play-6gb.ps1 -Exe 'D:\path\to\your.exe'
|
||||
```
|
||||
|
||||
### `cargo build` fails with `linker 'link.exe' not found` or missing Windows SDK
|
||||
1. Open **Visual Studio Installer** → **Modify** Visual Studio Build Tools.
|
||||
2. Check **"Desktop development with C++"** (ensure **MSVC v143 build tools** and **Windows 10/11 SDK** are checked on the right).
|
||||
3. Install, close PowerShell, open a **new** PowerShell window, and retry.
|
||||
|
||||
### Ran `git pull`, but nothing changed in-game
|
||||
`scripts\play-6gb.ps1` only builds automatically when `target\release\victory.exe` does not exist yet. After pulling new code, always rebuild:
|
||||
```powershell
|
||||
git pull origin main
|
||||
cargo build --release --locked -j 4 -p victory
|
||||
```
|
||||
|
||||
### Windows 10 DX12 / Shader Model 6.6 error on startup
|
||||
Run the Agility SDK helper script once and update your GPU driver:
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File scripts\get-d3d12.ps1
|
||||
```
|
||||
|
||||
### C: drive running out of disk space (shader cache / saves)
|
||||
Move caches, saves, settings, and logs to another drive (e.g. `D:\victory`) once, then open a new PowerShell window:
|
||||
```powershell
|
||||
setx VICTORY_HOME D:\victory
|
||||
```
|
||||
|
||||
### "Game file (.exe) not found"
|
||||
Wrap paths containing spaces in single quotes:
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File scripts\play-6gb.ps1 -Exe 'D:\My Folder\your.exe'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Shader Preloading (`-Preload`) & Pop-In in New Areas
|
||||
|
||||
- Every shader translated during gameplay is automatically cached on disk (`%LOCALAPPDATA%\victory\cache\shaders` or `$env:VICTORY_HOME\cache\shaders`), so areas you have already visited load cleanly on future runs.
|
||||
- When entering **brand-new areas** for the first time, new shaders compile in the background (capped at 50 ms/frame by `VICTORY_PIPELINE_WAIT_MS=50` to avoid 500 ms freezes, which can briefly cause objects to pop in).
|
||||
- To translate all shaders ahead of time once (~10–20 minutes on a laptop CPU, eliminates new-area pop-in; does not change steady FPS in already-cached areas):
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File scripts\play-6gb.ps1 -Exe 'D:\path\to\your.exe' -Preload
|
||||
```
|
||||
Or select **`PRELOAD SHADERS (RESTARTS THE GAME)`** in the F1 menu.
|
||||
|
||||
---
|
||||
|
||||
## 8. Collecting Logs for Bug Reports
|
||||
|
||||
If you hit a crash, freeze, or graphical bug, capture a log with `-LogFile` and share the last ~100 lines along with your CPU, GPU, RAM, Windows version, and a screenshot of the **`F3`** stats panel:
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File scripts\play-6gb.ps1 -Exe 'D:\path\to\your.exe' -LogFile D:\victory.log
|
||||
```
|
||||
@@ -0,0 +1,2 @@
|
||||
@echo off
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0play-6gb.ps1" %*
|
||||
+78
-19
@@ -4,17 +4,23 @@
|
||||
.EXAMPLE
|
||||
powershell -ExecutionPolicy Bypass -File scripts\play-6gb.ps1 -Exe 'D:\path\to\your.exe'
|
||||
.EXAMPLE
|
||||
powershell -ExecutionPolicy Bypass -File scripts\play-6gb.ps1 -Exe 'D:\path\to\your.exe' -FrameGen -Output 936
|
||||
powershell -ExecutionPolicy Bypass -File scripts\play-6gb.ps1 -Exe 'D:\path\to\your.exe' -NoFrameGen
|
||||
.EXAMPLE
|
||||
powershell -ExecutionPolicy Bypass -File scripts\play-6gb.ps1 -Exe 'D:\path\to\your.exe' -TuneSettings
|
||||
#>
|
||||
param(
|
||||
[string]$Exe = '',
|
||||
[ValidateSet('1080', '936', '720')][string]$Output = '1080',
|
||||
[ValidateSet('performance', 'balanced', 'quality', 'dlaa', 'off')][string]$Dlss = 'performance',
|
||||
[ValidateSet('ultraperformance', 'performance', 'balanced', 'quality', 'dlaa', 'off')][string]$Dlss = 'ultraperformance',
|
||||
[ValidateRange(0, 2)][int]$DropMips = 1,
|
||||
[switch]$FrameGen,
|
||||
[switch]$NoFrameGen,
|
||||
[ValidateSet('fsr', 'dlss', 'auto')][string]$FgType = 'fsr',
|
||||
[ValidateRange(2, 6)][int]$FrameGenX = 2,
|
||||
[switch]$TuneSettings,
|
||||
[switch]$Preload,
|
||||
[string]$DataDir = '',
|
||||
[string]$CacheDir = '',
|
||||
[string]$LogFile = ''
|
||||
)
|
||||
|
||||
@@ -22,8 +28,8 @@ $ErrorActionPreference = 'Continue'
|
||||
$repo = Split-Path -Parent $PSScriptRoot
|
||||
$victory = Join-Path $repo 'target\release\victory.exe'
|
||||
$homeDir = if ($env:VICTORY_HOME) { $env:VICTORY_HOME } else { Join-Path $env:LOCALAPPDATA 'victory' }
|
||||
$cacheDir = Join-Path $homeDir 'cache'
|
||||
$dataDir = Join-Path $homeDir 'data'
|
||||
$cacheDir = if ($CacheDir) { $CacheDir } elseif ($env:VICTORY_CACHE_DIR) { $env:VICTORY_CACHE_DIR } else { Join-Path $homeDir 'cache' }
|
||||
$dataDir = if ($DataDir) { $DataDir } elseif ($env:VICTORY_DATA_DIR) { $env:VICTORY_DATA_DIR } else { Join-Path $homeDir 'data' }
|
||||
$menuFile = Join-Path $homeDir 'victory-settings.txt'
|
||||
$slDir = if ($env:VICTORY_STREAMLINE_DIR) { $env:VICTORY_STREAMLINE_DIR } else { Join-Path $repo 'nvidia-sdk\Streamline\bin\x64' }
|
||||
$fxDir = if ($env:VICTORY_FIDELITYFX_DIR) { $env:VICTORY_FIDELITYFX_DIR } else { Join-Path $repo 'amd-sdk\FidelityFX\bin' }
|
||||
@@ -76,19 +82,19 @@ if (Test-Path -LiteralPath $menuFile) {
|
||||
|
||||
$seriesS = $true
|
||||
$res = '1080to1440'
|
||||
$sRes = '540'
|
||||
$sRes = if ($Dlss -eq 'ultraperformance') { '360' } elseif ($Dlss -eq 'balanced') { '626' } elseif ($Dlss -eq 'quality') { '720' } elseif ($Dlss -eq 'dlaa') { '1080' } else { '540' }
|
||||
$dlssMode = $Dlss
|
||||
$fgOn = [bool]$FrameGen
|
||||
$fgOn = if ($NoFrameGen) { $false } else { $true }
|
||||
$timesWanted = $FrameGenX
|
||||
$fgKind = $FgType
|
||||
$fpsWanted = 1000
|
||||
|
||||
if ($menu.Contains('VICTORY_MENU_CONSOLE')) { $seriesS = $menu['VICTORY_MENU_CONSOLE'] -eq 'series-s' }
|
||||
if ($menu['VICTORY_MENU_RES'] -in '1440', '1080to1440', '4k') { $res = $menu['VICTORY_MENU_RES'] }
|
||||
if ($menu['VICTORY_MENU_S_RES'] -in '1080', '720', '626', '540') { $sRes = $menu['VICTORY_MENU_S_RES'] }
|
||||
if ($menu['VICTORY_MENU_DLSS'] -in 'off', 'dlaa', 'quality', 'balanced', 'performance') { $dlssMode = $menu['VICTORY_MENU_DLSS'] }
|
||||
if ($menu['VICTORY_MENU_S_RES'] -in '1080', '720', '626', '540', '360') { $sRes = $menu['VICTORY_MENU_S_RES'] }
|
||||
if ($menu['VICTORY_MENU_DLSS'] -in 'off', 'dlaa', 'quality', 'balanced', 'performance', 'ultraperformance') { $dlssMode = $menu['VICTORY_MENU_DLSS'] }
|
||||
if ($seriesS -and $dlssMode -ne 'off' -and $menu.Contains('VICTORY_MENU_S_RES')) {
|
||||
$sMap = @{ '1080' = 'dlaa'; '720' = 'quality'; '626' = 'balanced'; '540' = 'performance' }
|
||||
$sMap = @{ '1080' = 'dlaa'; '720' = 'quality'; '626' = 'balanced'; '540' = 'performance'; '360' = 'ultraperformance' }
|
||||
if ($sMap.ContainsKey($sRes)) { $dlssMode = $sMap[$sRes] }
|
||||
}
|
||||
if ($menu.Contains('VICTORY_MENU_FRAMEGEN')) {
|
||||
@@ -105,8 +111,25 @@ $settings = [ordered]@{
|
||||
VICTORY_DATA_DIR = $dataDir
|
||||
VICTORY_LOG = 'info'
|
||||
|
||||
# Shader optimiser level (447 = WATERFALL | HOIST_HANDLES): verified GPU win
|
||||
VICTORY_SHADER_OPT = '447'
|
||||
# Physical-RAM-pressure trimming for 16 GB PCs (4096 = start eviction ~2 GB ahead of the cliff; A/B paging max -27%)
|
||||
VICTORY_RAM_PRESSURE_MB = '4096'
|
||||
# Hold back zero-yield (<1 MiB freed) heavy sweeps so churn stops spiking frames (A/B paging churn -4.3x)
|
||||
VICTORY_TRIM_MIN_MS = '5000'
|
||||
# Submission-path toggles: flatten frame-time spikes (A/B mean 137 -> 120 ms, fewer slow outliers)
|
||||
VICTORY_SUBMIT_FRAMES = '3'
|
||||
VICTORY_JOIN_FEWER = '1'
|
||||
VICTORY_RELAY_EACH = '1'
|
||||
VICTORY_TABLED_BITS = '1'
|
||||
|
||||
# CPU threading & submission (FAST_CORES=0 uses both P+E cores on hybrid CPUs)
|
||||
VICTORY_THIN = '0'
|
||||
VICTORY_THIN = '1'
|
||||
VICTORY_THIN_THREADS = '8'
|
||||
VICTORY_LAND_OFF_SUBMIT = '1'
|
||||
VICTORY_FAULT_UNLOCKED = '1'
|
||||
VICTORY_GUARD_HOT = '50'
|
||||
VICTORY_FRESH_OPEN = '0'
|
||||
VICTORY_ASYNC_SUBMIT = '1'
|
||||
VICTORY_JOIN_PARTS = '8'
|
||||
VICTORY_RELAY = '2'
|
||||
@@ -116,6 +139,7 @@ $settings = [ordered]@{
|
||||
VICTORY_JOIN_COPIES = '1'
|
||||
VICTORY_CARD_STEPS = '2'
|
||||
VICTORY_CARD_AWAKE = '1'
|
||||
VICTORY_CARD_SPANS = '0'
|
||||
VICTORY_CARD_BUFFERS_MIN_KB = '64'
|
||||
VICTORY_CARD_BUFFERS_MB = '1280'
|
||||
VICTORY_CARD_ROOM_FOR_TARGETS_MB = '1024'
|
||||
@@ -127,14 +151,19 @@ $settings = [ordered]@{
|
||||
VICTORY_SHOW_AFTER = '1'
|
||||
VICTORY_MAP_THREADS = '1'
|
||||
VICTORY_FAST_CORES = '0'
|
||||
VICTORY_INPLACE = '1'
|
||||
VICTORY_INPLACE_MB = '512'
|
||||
# In-place off: A3 showed it places only ~185 MB here and INPLACE=0 keeps the GPU win
|
||||
VICTORY_INPLACE = '0'
|
||||
VICTORY_TEXSPK_PASS_MS = '8'
|
||||
VICTORY_PASSES_HOT = '1'
|
||||
VICTORY_HELPER_PRIORITY = '1'
|
||||
VICTORY_WC_NO_BACK = '1'
|
||||
VICTORY_WC_NO_BACK_MIN_KB = '1024'
|
||||
VICTORY_GPU_RO_SKIP = '1'
|
||||
VICTORY_SECTION_MB = '2'
|
||||
VICTORY_SOFT_VIEWS = 'copies'
|
||||
VICTORY_COPY_BESIDE = '1'
|
||||
VICTORY_STORE_BESIDE = '1'
|
||||
VICTORY_WINDOWS_VRAM_PERCENT = '85'
|
||||
|
||||
# Texture streaming + 6 GB VRAM mip scale
|
||||
VICTORY_TEXTURE_POOL = '1'
|
||||
@@ -160,25 +189,51 @@ $settings = [ordered]@{
|
||||
# Visuals (windowed by default; toggleable in F1 menu)
|
||||
VICTORY_AMBIENT = '0.8'
|
||||
VICTORY_AMBIENT_AIR = '1.5'
|
||||
VICTORY_AMBIENT_SHADE = '0.5,0.5'
|
||||
VICTORY_AMBIENT_SPECULAR = '1'
|
||||
VICTORY_WATER_LIGHT = '1'
|
||||
VICTORY_EARLY_DEPTH = '1'
|
||||
VICTORY_DEPTH_PLANE_NOW = '1'
|
||||
# Heat haze + decal defrag (visually safe)
|
||||
VICTORY_LEAVE_OUT = '02384a60fda6f2d0,731a39171b568298'
|
||||
|
||||
# Pipeline caching + short wait cap to prevent 500 ms shader-compile freezes
|
||||
VICTORY_PIPELINE_BOOK = '1'
|
||||
VICTORY_PIPELINE_WAIT_MS = '50'
|
||||
|
||||
# Memory stack (SLOT_EVICT aligned above ROOM% to prevent eviction thrashing)
|
||||
# Memory stack (SLOT_EVICT sits just above ROOM% so idle textures evict cleanly when roaming)
|
||||
VICTORY_SLOT_EVICT = '1'
|
||||
VICTORY_SLOT_EVICT_PERCENT = '92'
|
||||
VICTORY_SLOT_EVICT_LOW_PERCENT = '82'
|
||||
VICTORY_ALLOCATOR_TRIM = '1'
|
||||
VICTORY_BUDGET_PACK = '1'
|
||||
# Shed the loading/cutscene command-allocator high-water peak (~GBs) under RAM pressure
|
||||
VICTORY_LIST_ALLOC_CAP_MB = '512'
|
||||
VICTORY_TEARING = '1'
|
||||
VICTORY_FPS_LINE = '1'
|
||||
}
|
||||
|
||||
if ($TuneSettings) {
|
||||
$xmlPath = Join-Path $dataDir '7952987A\storage\settings\settings.xml'
|
||||
if (Test-Path -LiteralPath $xmlPath) {
|
||||
$bak = "$xmlPath.bak"
|
||||
if (-not (Test-Path -LiteralPath $bak)) { Copy-Item -LiteralPath $xmlPath -Destination $bak }
|
||||
$c = Get-Content -LiteralPath $xmlPath -Raw
|
||||
$c = $c -replace '<motionBlur value="true" />','<motionBlur value="false" />'
|
||||
$c = $c -replace '<rtDynamicShadows value="true" />','<rtDynamicShadows value="false" />'
|
||||
$c = $c -replace '<shadowParticleShadows value="true" />','<shadowParticleShadows value="false" />'
|
||||
$c = $c -replace '<ssroSampleCount value="2" />','<ssroSampleCount value="1" />'
|
||||
$c = $c -replace '<grassLod value="[^"]+" />','<grassLod value="0.350000" />'
|
||||
$c = $c -replace '<lodScale value="[^"]+" />','<lodScale value="0.750000" />'
|
||||
$c = $c -replace '<smallCullThreshold value="[^"]+" />','<smallCullThreshold value="2.000000" />'
|
||||
$c = $c -replace '<waterReflectionResX value="512" />','<waterReflectionResX value="256" />'
|
||||
$c = $c -replace '<waterReflectionResY value="256" />','<waterReflectionResY value="128" />'
|
||||
$c = $c -replace '<width value="3840" />','<width value="1920" />'
|
||||
$c = $c -replace '<height value="2160" />','<height value="1080" />'
|
||||
Set-Content -LiteralPath $xmlPath -Value $c -NoNewline
|
||||
}
|
||||
}
|
||||
|
||||
if ($Output -eq '936') { $settings['VICTORY_OUTPUT'] = '1664x936' }
|
||||
elseif ($Output -eq '720') { $settings['VICTORY_OUTPUT'] = '1280x720' }
|
||||
|
||||
@@ -193,22 +248,26 @@ if ($dlssMode -ne 'off' -and (Test-Path (Join-Path $slDir 'sl.interposer.dll')))
|
||||
$settings['VICTORY_STREAMLINE_DIR'] = $slDir
|
||||
}
|
||||
|
||||
$barMb = '0'
|
||||
# Fixed texture-queue room line (verified winning setting); was DropMips-derived 70/65
|
||||
$roomPct = '75'
|
||||
|
||||
if ($dlssMode -ne 'off' -and $fgOn) {
|
||||
if ($fgKind -ne 'dlss' -and (Test-Path (Join-Path $fxDir 'amd_fidelityfx_framegeneration_dx12.dll'))) {
|
||||
$settings['VICTORY_FSR_FRAMEGEN'] = '1'
|
||||
$settings['VICTORY_FIDELITYFX_DIR'] = $fxDir
|
||||
$settings['VICTORY_FRAMEGEN_X'] = [string]$timesWanted
|
||||
$settings['VICTORY_TEXTURE_ROOM_PERCENT'] = '82'
|
||||
$settings['VICTORY_WINDOWS_BAR_MB'] = '128'
|
||||
$settings['VICTORY_TEXTURE_ROOM_PERCENT'] = $roomPct
|
||||
$settings['VICTORY_WINDOWS_BAR_MB'] = $barMb
|
||||
} elseif ($fgKind -eq 'dlss') {
|
||||
$settings['VICTORY_FRAMEGEN'] = '1'
|
||||
$settings['VICTORY_FRAMEGEN_X'] = [string]$timesWanted
|
||||
$settings['VICTORY_TEXTURE_ROOM_PERCENT'] = '82'
|
||||
$settings['VICTORY_WINDOWS_BAR_MB'] = '128'
|
||||
$settings['VICTORY_TEXTURE_ROOM_PERCENT'] = $roomPct
|
||||
$settings['VICTORY_WINDOWS_BAR_MB'] = $barMb
|
||||
}
|
||||
} else {
|
||||
$settings['VICTORY_TEXTURE_ROOM_PERCENT'] = '85'
|
||||
$settings['VICTORY_WINDOWS_BAR_MB'] = '256'
|
||||
$settings['VICTORY_TEXTURE_ROOM_PERCENT'] = $roomPct
|
||||
$settings['VICTORY_WINDOWS_BAR_MB'] = $barMb
|
||||
}
|
||||
|
||||
$settings['VICTORY_FRAME_INTERVAL_US'] = [string][int][math]::Round(1000000 / $fpsWanted)
|
||||
|
||||
Reference in new issue
Block a user