diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000000..4d4b8a318b --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,7 @@ +# Axiz-VIctory development + +- Preserve the upstream [asset policy](docs/asset-policy.md). Use generated fixtures and keep captures, caches and proprietary files outside the repository. +- Record the baseline, build configuration, workload and actual measurements before claiming a performance change. Keep gameplay, external reports and synthetic measurements distinct. +- Check the target D3D12 adapter and supported capabilities before introducing a hardware-specific path. Keep rendering and synchronization semantics covered by regression tests. +- Record imported code's author, source SHA and license in [the optimization matrix](OPTIMIZATION_MATRIX.md). Prefer small, attributable commits and retain the pinned upstream reference. +- See [build instructions](BUILD_INSTRUCTIONS.md), [benchmarks](BENCHMARKS.md) and [known issues](KNOWN_ISSUES.md) for validation. diff --git a/BENCHMARKS.md b/BENCHMARKS.md new file mode 100644 index 0000000000..8df1e2000e --- /dev/null +++ b/BENCHMARKS.md @@ -0,0 +1,44 @@ +# Benchmarks + +The local host is documented in [NVIDIA compatibility](NVIDIA_COMPATIBILITY.md). Baseline is upstream `63bcca43c6a00a758510398fa43096ce7e4f7df0`, compiled with Rust 1.98.1 and the release profile. The candidate comparison uses `e04aea17e40f0ec984a12e2a1881fe906089095d`. + +## Synthetic texture copies + +```powershell +cargo run --release --locked -p victory-formats --example texture_copy_bench +``` + +Use the same example source and toolchain in both checkouts. The harness uses one thread, warms each operation, reuses its buffers, and reports the median of seven samples copying at least 64 MiB of active bytes each. GB/s is decimal. Layout construction and allocation are outside the measurement. Tightly packed R8 uses 256 active bytes per row. The padded case adds 16 bytes per linear row. Repeated buffers exercise warm caches and the host memory subsystem. + +The table gives the median of three process runs per build, with the build order varied between runs. Each cell lists detile / tile in GB/s. The intermediate build isolates the imported change. + +| Workload | Upstream | Imported change | With packed linear copy | +| --- | ---: | ---: | ---: | +| RGBA8 64KB_D | 16.80 / 10.69 | 19.45 / 16.39 | 18.97 / 15.97 | +| RGBA8 4KB_S | 14.35 / 9.06 | 16.82 / 14.23 | 16.84 / 14.26 | +| BC7 mip 5 | 28.86 / 32.12 | 49.88 / 45.57 | 49.29 / 52.94 | +| RGBA8 volume | 10.46 / 6.81 | 15.67 / 13.63 | 15.67 / 13.64 | +| R8 linear tight | 60.82 / 40.74 | 55.77 / 39.37 | 69.64 / 72.79 | +| R8 linear padded | 47.12 / 40.31 | 46.66 / 39.91 | 46.63 / 39.17 | + +Volume tiling reached 2.00× baseline throughput. The packed R8 tiling path reached 1.79× baseline and 1.85× the intermediate build. Padded R8 varied by up to about 3% from baseline in this comparison. + +In a separate process-memory sample, both copy benchmarks reached 25.13 MiB peak working set, polled every 15 ms. Neither workload initializes a GPU. + +## Gameplay capture + +Use one interval per frame in milliseconds, with a single `frametime_ms` header and a decimal point. Export a consistent presentation or display interval from the capture tool throughout the comparison. The input may live outside this repository. + +```powershell +cargo xtask frame-stats C:\Benchmarks\capture.csv --stutter-ms 50 +``` + +Average FPS is 1000 divided by mean interval. Median FPS is the inverse median interval. The 1% and 0.1% lows invert the mean of the slowest ceiling(1% or 0.1%) intervals and require at least 100 or 1,000 frames respectively. P95, P99 and P99.9 use nearest rank. A frame misses the 30 FPS budget if it exceeds 1000/30 ms. The stutter count applies the supplied threshold independently. + +Keep separate, labeled cold-cache and warm-cache captures. Record the exact branch/SHA, driver, adapter, power and display settings, render settings, route and duration. For each configuration, capture at least three repetitions of the same route and enough frames for the tail metrics. Collect CPU and per-thread utilization, GPU utilization, peak process RAM, peak dedicated VRAM and any crash or device-removal codes alongside each capture. The interval analyzer reads only the CSV. Compare aggregate metrics across equivalent runs and inspect graphics output for differences. + +On a hybrid system, confirm from the process or GPU capture that both builds use the same NVIDIA adapter. For the pinned baseline, Windows per-application graphics preference can be used if it places the process on NVIDIA. The candidate can explicitly request the NVIDIA adapter with `VICTORY_D3D12_NVIDIA=1`. + +Gameplay and user-reported captures are pending. The synthetic copy example does not measure rendering or GPU utilization. + +For an analyzer smoke test, a generated 1,000-interval CSV with 999 intervals of 20 ms and one of 100 ms yielded 49.801 average FPS, 50.000 median FPS, 35.714 and 10.000 for the two lows, and one budget miss and stutter. This fixture only checks arithmetic. diff --git a/BUILD_INSTRUCTIONS.md b/BUILD_INSTRUCTIONS.md new file mode 100644 index 0000000000..f3cca0cb08 --- /dev/null +++ b/BUILD_INSTRUCTIONS.md @@ -0,0 +1,29 @@ +# Windows builds + +Use the pinned Rust 1.98.1 toolchain for `x86_64-pc-windows-msvc`, the Visual Studio C++ build tools, and a Windows SDK. The verified host uses MSVC tools 14.44.35207 (CL 19.44.35230) and SDK 10.0.26100.0. Cargo resolves the checked-in lockfile. + +```powershell +cargo build --release --locked -p victory +cargo build --profile diag --locked -p victory --features diagnostics +cargo test --workspace --locked --no-fail-fast -- --test-threads=1 +cargo clippy --workspace --all-targets --all-features --locked -- -D warnings +cargo xtask policy +``` + +See the [architecture](docs/architecture.md) and [asset policy](docs/asset-policy.md) for actual runtime inputs. The CLI smoke checks, self-contained tests and CPU benchmarks use no title files. + +| Profile | Local artifact | Source | +| --- | --- | --- | +| Pinned upstream release | `target/baseline/63bcca4/victory.exe` | `63bcca43c6a00a758510398fa43096ce7e4f7df0` | +| Candidate release | `target/release/victory.exe` | `7dd9a868959d6389596a1824e04a199c474ab630` | +| Candidate diagnostics | `target/diag/victory.exe` | `7dd9a868959d6389596a1824e04a199c474ab630` | + +The local builds dated 2026-11-26 retain matching PDB files. They depend on Windows D3D12 for GPU operation. The diagnostics profile adds instrumentation and should be used separately from release frame-pacing captures. + +SHA-256 values for the local executables: + +| Artifact | SHA-256 | +| --- | --- | +| Baseline release | `303520a2e0ef216abb5192e0c9426fec2fbf113e6bcead52235f1ed6f032884e` | +| Candidate release | `9e4abb9b66d9902c939350a061d8b39728bf7fb798ac6c2b3614327fadffc1e8` | +| Candidate diagnostics | `46e45b40ddba98ea0e2ca7677af37e2ef9c91ed44219805a331680c6b74a5cf6` | diff --git a/DEVELOPMENT_LOG.md b/DEVELOPMENT_LOG.md new file mode 100644 index 0000000000..b23e1d1b03 --- /dev/null +++ b/DEVELOPMENT_LOG.md @@ -0,0 +1,11 @@ +# Development log + +## 2026-11-26 + +- Pinned upstream `63bcca43c6a00a758510398fa43096ce7e4f7df0` and saved a separately named release artifact. See [build instructions](BUILD_INSTRUCTIONS.md). +- Fetched eight GPL workspace forks and compared their source and divergence. Reused brainbudt's safe-Rust texture copy optimization in `38985da7` with attribution to the original commit. See [optimization matrix](OPTIMIZATION_MATRIX.md). +- Added packed linear plane copies and regression coverage in `3d10a2ee`. Added the synthetic copy harness and frame interval analyzer in `e04aea17`. See [benchmarks](BENCHMARKS.md). +- Identified the default Intel adapter on the hybrid laptop and added opt-in NVIDIA selection in `7dd9a868`. The opt-in test checked the actual device LUID. See [NVIDIA compatibility](NVIDIA_COMPATIBILITY.md). +- Both release variants compiled and passed CLI smoke tests. Clippy passed with default and all features. The baseline and NVIDIA-opt-in candidate workspace runs reported the same five failed tests, with 867 and 872 passes respectively in the Cargo logs, including the nested fixture runner. See [known issues](KNOWN_ISSUES.md). + +Work branch is `codex/texture-copy`. The compiled source commit is `7dd9a868`. The following documentation commit records the baseline and validation. The next engineering milestone is to isolate descriptor heap sizing and shader test failures on the target GPU. diff --git a/KNOWN_ISSUES.md b/KNOWN_ISSUES.md new file mode 100644 index 0000000000..5b235f5b25 --- /dev/null +++ b/KNOWN_ISSUES.md @@ -0,0 +1,7 @@ +# Known issues + +- Upstream CPU texture and descriptor behavior can be tested with generated fixtures. Representative gameplay timing, image fidelity, the dominant frame bottleneck and sustained stability remain unmeasured on the target system. +- Upstream `dynamic_slots_are_held_until_released` asserts that the actual host heap reaches `HEAP_VIEWS`. `lists_share_a_table_and_copies_keep_their_views` asserts that allocated pairs are past a hard-coded dynamic slot boundary. Both failed on the pinned machine before the texture change. Investigate the host-dependent heap sizing and where the shader gets its index bound together. [Upstream NVIDIA descriptor-limit report](https://github.com/Marvisak/VIctory/issues/1835) +- Three other upstream hardware tests failed before the texture change. The null-buffer dispatch and 64-bit image atomic tests returned an invalid parameter error. The hardware fused dot-product test returned a different result bit pattern. These paths need independent adapter and capability checks. +- The repository's [asset policy](docs/asset-policy.md) identifies the inherited BCPack table as outside the upstream GPL license. The candidate adds source and synthetic measurement tooling. The local executable retains the upstream dependency and is kept local. +- External reports include GPU device removal entering the world on other NVIDIA setups. A synthetic texture throughput result cannot resolve that issue. [Upstream RTX 5070 Ti report](https://github.com/Marvisak/VIctory/issues/1216) diff --git a/NVIDIA_COMPATIBILITY.md b/NVIDIA_COMPATIBILITY.md new file mode 100644 index 0000000000..cac15d3bef --- /dev/null +++ b/NVIDIA_COMPATIBILITY.md @@ -0,0 +1,15 @@ +# NVIDIA compatibility + +Local discovery on 2026-11-26 found an NVIDIA GeForce RTX 5070 Ti Laptop GPU with driver 621.14 and 12,227 MiB reported by NVIDIA SMI. NVIDIA documents the laptop SKU as Blackwell with 12 GB GDDR7. DXDiag reported D3D12 DDI 12, feature level up to 12_2 and WDDM 3.2 for the NVIDIA adapter. Vulkaninfo reported Vulkan 1.4.357 for that adapter. The host also exposes Intel integrated graphics, so capture metadata should identify the adapter used. + +A local D3D12 API probe opened the RTX explicitly. It returned Shader Model 6.8 (probe ceiling), resource binding tier 3, 32-lane waves, native 16-bit shader operations, raytracing tier 1.2, mesh shader tier 1, and a point-in-time DXGI local-memory budget of 11,176 MiB. NVIDIA SMI reported compute capability 12.0. + +The default D3D12 adapter resolved to Intel Graphics in the probe. Set `VICTORY_D3D12_NVIDIA=1` for Axiz-VIctory to try compatible NVIDIA adapters in DXGI order. Mode selection is once per process. The log names the NVIDIA adapter when selected and reports fallback to the system default when none can be used. The diagnostics WARP switch takes precedence. Shader crate hardware tests use their own adapter selection. + +The CPU is an x86-64 Intel Core Ultra 9 275HX with 24 cores and 24 logical processors. Windows 11 Pro is build 26300. The OS reports 33,752,997,888 bytes of physical memory. Drive C had about 300 GiB free. The automatically managed pagefile showed a 2 GiB allocation and zero reported use at inspection. + +Git 2.56.1 and GitHub CLI 2.105.0 were available, and authenticated GitHub API and HTTPS fetch succeeded. Cargo, rustc, MSVC, the Windows SDK, DXDiag, Vulkaninfo, NVIDIA SMI and Windows Performance Recorder were available. Nsight Graphics and Nsight Systems were not found on PATH or in the standard NVIDIA installation directory checked. + +The texture-copy path changes host CPU work. Shader execution, occupancy, register pressure, queues, VRAM residency and pipeline behavior require adapter-specific captures before choosing an NVIDIA profile. The upstream runtime queries D3D12 capabilities in `crates/victory-gpu/src/host.rs`. + +[NVIDIA RTX 50 Series Laptop specifications](https://www.nvidia.com/en-gb/geforce/laptops/50-series/) diff --git a/OPTIMIZATION_MATRIX.md b/OPTIMIZATION_MATRIX.md new file mode 100644 index 0000000000..df024189cb --- /dev/null +++ b/OPTIMIZATION_MATRIX.md @@ -0,0 +1,37 @@ +# Optimization matrix + +Pinned comparison base is [Marvisak/VIctory at 63bcca4](https://github.com/Marvisak/VIctory/tree/63bcca43c6a00a758510398fa43096ce7e4f7df0). Cargo declares GPL-3.0-or-later for the project. The upstream asset policy records a BCPack table exception outside that grant. + +## Fork comparison + +Heads were fetched and compared with the pinned base on 2026-11-26. Behind/ahead counts use the merge base and include merges. Reported gameplay results are third-party claims with differing settings and workloads. + +| Repository | Head (commit UTC) | Behind/ahead | Source review and reported evidence | NVIDIA applicability and integration | +| --- | --- | ---: | --- | --- | +| [DexNom/VIctory](https://github.com/DexNom/VIctory/tree/64bd58f5fb794216894bc0e33e03a3a64d19c347) | `64bd58f`, Nov 26 01:12 | 160/19 | Separate launcher, warm-up and FSR profiles. BENCHMARK.md reports an indoor 3.52 to 4.05 FPS comparison over 93 matched presents on RX 7900 XTX, with divergent outdoor runs. | Portable copy/readback ideas merit review individually. Preset changes and launch tooling add dependencies. | +| [JMAN730/project-flamingo](https://github.com/JMAN730/project-flamingo/tree/ef535754d4298cea962a9a973a152ddfb6a07a2d) | `ef53575`, Nov 26 07:11 | 479/1138 | Parallel refresh, vectorized copies, upload retirement, and wave32 work across a wide merge queue. README describes RTX 2070 SUPER tests with ~7.3/8 GB VRAM and device loss 30–45 seconds after entering the world, plus a separate RTX 4080 Proton run. | Isolate each mechanism. Memory ordering and lifetimes make a wholesale merge high risk. | +| [Steenax6/VIctory-NVID](https://github.com/Steenax6/VIctory-NVID/tree/d787d905aa594bd1bfeff7643fe1833368235995) | `d787d90`, Nov 26 02:54 | 479/196 | Card-local buffers, texture promotion and residency policies. Switch notes report 78.6 ms in the first room and 77 ms in a 22-minute open-world run on a Windows 11 RTX 4070 Ti 12 GB. | Comparable VRAM class. Streaming policy changes texture quality and is coupled to descriptor/resource state. | +| [fxceless/victory-fork](https://github.com/fxceless/victory-fork/tree/46bf5351707b1697c04e5d871c30973ebaa3e973) | `46bf535`, Nov 26 05:52 | 479/105 | Separate instrumentation for remapping and texture worker. Run 309 includes 30.2 FPS at seven draws per frame, insufficient evidence of open-world performance. | Useful phase instrumentation. Validate thread ownership and queue ordering before taking worker code. | +| [uiliannn/VItoriaBr](https://github.com/uiliannn/VItoriaBr/tree/1361e190b7f46df996f00ea1b540ecf66785127f) | `1361e19`, Nov 26 04:09 | 479/169 | Dynamic descriptor slots, barriers and second present plane. README reports 4–6 FPS on the preset and a separate experimental 22 FPS at 1080p on RTX 5060 Ti 16 GB. | Inspect descriptor provenance and bounds independently of renderer presets. Experimental results lack a comparable local capture. | +| [WillyboPeep/victory-all-forks](https://github.com/WillyboPeep/victory-all-forks/tree/8b8319c0ac550f962784d286053aac77cd3be9dc) | `8b8319c`, Nov 25 09:04 | 479/273 | Integration ledger tracking sources and switches. Reports 4.9 to 5.2 FPS at ~5,600 draws/frame on RTX 4090 24 GB with three switches combined. | Use the ledger to trace individual changes. Combined switch result does not isolate a cause. | +| [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA/tree/033be27f336e395745667df5fe20160e375209ca) | `033be27`, Nov 26 03:41 | 479/420 | Adapter selection by description, dynamic descriptors and GPU compares. Reports 11 to 21.8 FPS on RTX 5070 12 GB in the prologue using a Series S profile at half scale, custom upscaling and skipped ray walks. | Dynamic descriptor work is the origin of the VItoriaBr variant. The quality changes make the reported speed preset unsuitable as a baseline. | +| [Xeltax/VIcky](https://github.com/Xeltax/VIcky/tree/abafd94aaad6d21c4840478e9f3ffeb09ffa3d6e) | `abafd94`, Nov 25 08:40 | 594/243 | Descends from fxceless, adds heap-cap and slot-distribution diagnostics and adjusts a shader cache key. README reports nine-minute runs from one save at 3.5–4.5 FPS in Series X mode and 5.7–6.0 in Series S mode on RTX 4080 16 GB. | Use slot-distribution instrumentation as reference. Cross-profile FPS changes cannot isolate an optimization. | + +The eight fetched heads declare GPL-3.0-or-later in their workspace manifests. Verify asset provenance and any component-specific license before importing. GitHub API returned 404 for the previously discussed `Zettrox/ztrx`. No source or license was inspected for that URL. + +## Candidates and validation + +| Area | Author and source | Mechanism and expected effect | Dependencies, risks and validation | Status | +| --- | --- | --- | --- | --- | +| CPU, allocation, streaming | brainbudt, [d331047](https://github.com/Marvisak/VIctory/pull/2736) | Derive contiguous swizzle runs, pair rows and visit depth slabs while cache lines are hot. | Safe Rust, works on host CPU independent of adapter. Verify per-element mapping, padding, tails and errors in both directions. Interacts with #2026. | Validated on synthetic copies | +| CPU, streaming | Axiz-VIctory, `3d10a2ee` | Copy packed linear rows in one span per depth slice, reducing per-row copies. | Safe Rust, no dependency. Validate padded rows and per-mip/depth gaps. | Validated on synthetic copies | +| CPU, streaming | 0xkn0wh3r3, [1ec3877](https://github.com/Marvisak/VIctory/pull/2026) | Check bounds once per row, then copy individual runs through pointers. | GPL-compatible Rust, overlapping edits with #2736. Requires verifying the run bounds for unchecked copies. | Rejected for this integration in favor of tested safe slices | +| CPU, threading, command submission | fever308, [b975c652](https://github.com/JMAN730/project-flamingo/commit/b975c652), and fxceless, [d4a528ba](https://github.com/fxceless/victory-fork/commit/d4a528ba) | Parallelize refresh and combine residency queries, or dedicate a texture upload worker. | Windows APIs and current GPU state ownership. Isolate scheduling changes and test concurrent writes, queue waits and GPU hashes. | Under investigation | +| CPU/GPU synchronization, lifetime, allocation | fever308, [694695c2](https://github.com/JMAN730/project-flamingo/commit/694695c2) | Batch retirements, page kept-resource tracking and reuse upload storage. | D3D12 fences and barriers. Exercise multiple queues, resets and retire-on-completion. | Discovered | +| VRAM, rendering, streaming | Steenax6, [83e2ba51](https://github.com/Steenax6/VIctory-NVID/commit/83e2ba51) | Start sampling at the first available level while textures stream in. | Verify fallback, binding clamps and image correctness with authorized workloads. Avoid forced mip dropping in default profiles. | Experimental | +| VRAM, RAM, graphics API overhead | uiliannn, [e40fba44](https://github.com/uiliannn/VItoriaBr/commit/e40fba44) | Dynamic descriptors within a capped heap. | D3D12. Compare with upstream's capacity calculation and shader index clamps. Verify no overlaps, rollover or early release. | Under investigation | +| Stability, error handling | Axiz-VIctory, `7dd9a868` | Opt-in NVIDIA D3D12 adapter selection avoids unintended use of integrated graphics on hybrid systems. | DXGI enumeration and feature-level 12_0. Verified the actual runtime device LUID on the RTX 5070 Ti Laptop GPU. | Validated for adapter selection | +| GPU, shader execution | 0xkn0wh3r3, [47078d7](https://github.com/Marvisak/VIctory/pull/2825) | Emit native half arithmetic when the device supports it. PR reports a focused RTX 5070 Ti result. | Inspect D3D12 capability gating, floating-point edge cases, DXIL validation and fallback. No gameplay benefit assumed. | Discovered | +| Shader compilation and cache | [Upstream #1844](https://github.com/Marvisak/VIctory/issues/1844) | Investigate whether host wave settings affect cache identity across adapters. | Check current key fields, invalidate only when generation inputs change, and test cold versus warm bytes. | Under investigation | +| Pipeline cache, filesystem I/O | [Upstream architecture](https://github.com/Marvisak/VIctory/blob/63bcca43c6a00a758510398fa43096ce7e4f7df0/docs/architecture.md) | Existing content-addressed shader cache and D3D12 pipeline library. Measure startup cache hits, conversion work and disk reads separately. | Pipeline library is adapter/driver dependent. Compare cold/warm captures with the same inputs. | Discovered | +| Frame pacing, stability, error handling | Axiz-VIctory, `e04aea17` | Offline interval summary exposes budget misses and tail latency. Runtime diagnostics already capture device removal and submission timing. | One exported interval per frame. Separate release capture from diagnostic instrumentation. | Implemented | diff --git a/README.md b/README.md index d1921e79bd..ae489e5ff3 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,14 @@ Windows SDK's `bin//x64/dxil.dll`, then falls back to the DLL search path when no SDK copy is found. This is a test/offline-validation dependency; the translated shaders do not require it at runtime. +## NVIDIA adapter selection + +Set `VICTORY_D3D12_NVIDIA=1` to prefer an NVIDIA adapter on a hybrid system. +The runtime logs the selected NVIDIA device or reports fallback to the +system default. The switch works in release and diagnostics builds. +The diagnostics WARP switch takes priority. See +[NVIDIA compatibility](NVIDIA_COMPATIBILITY.md) for the verified host. + ## Debugging A release build has no debugging aids. Build them in with diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 0000000000..abb0da6476 --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,8 @@ +# Roadmap + +1. Retain the pinned upstream release and verify changes with synthetic fixtures and the Windows test suite. +2. Reproduce and isolate the descriptor heap and shader failures on the RTX 5070 Ti Laptop GPU. Track the host heap capacity and shader index range together. +3. Capture comparable baseline and candidate runs on an authorized workload. Use release for FPS, then collect CPU, GPU, residency and copy diagnostics on separate runs to identify the dominant cost. +4. Work toward sustained 5, 10, 15, 20, 25 and 30 FPS on the same representative route. Skip demonstrated thresholds. At 30 FPS, inspect the distribution around 33.333 ms, outliers and sustained stability as well as the mean. + +Candidate areas after profiling include texture upload and copy-back, pipeline creation and cache reuse, descriptor lifetime, and CPU/GPU synchronization. Keep each change independently reviewable. diff --git a/crates/victory-formats/examples/texture_copy_bench.rs b/crates/victory-formats/examples/texture_copy_bench.rs new file mode 100644 index 0000000000..a2709bf585 --- /dev/null +++ b/crates/victory-formats/examples/texture_copy_bench.rs @@ -0,0 +1,129 @@ +//! Synthetic CPU copy throughput. No GPU or game files are used. + +use std::hint::black_box; +use std::time::Instant; + +use victory_formats::texture::{Desc, Dimension, Layout, Swizzle}; + +fn main() { + let base = Desc { + dimension: Dimension::Tex2d, + width: 1920, + height: 1080, + depth: 1, + mips: 1, + block: 1, + element_bytes: 4, + samples: 1, + swizzle: Swizzle::SW_64KB_D, + }; + let cases = [ + ("RGBA8 64KB_D", base, 0, 0), + ( + "RGBA8 4KB_S", + Desc { + swizzle: Swizzle::SW_4KB_S, + ..base + }, + 0, + 0, + ), + ( + "BC7 mip 5", + Desc { + width: 4096, + height: 4096, + mips: 13, + block: 4, + element_bytes: 16, + ..base + }, + 5, + 0, + ), + ( + "RGBA8 volume", + Desc { + dimension: Dimension::Tex3d, + width: 128, + height: 128, + depth: 64, + swizzle: Swizzle::SW_4KB_S, + ..base + }, + 0, + 0, + ), + ( + "R8 linear tight", + Desc { + width: 256, + height: 128, + element_bytes: 1, + swizzle: Swizzle::LINEAR, + ..base + }, + 0, + 0, + ), + ( + "R8 linear padded", + Desc { + width: 256, + height: 128, + element_bytes: 1, + swizzle: Swizzle::LINEAR, + ..base + }, + 0, + 16, + ), + ]; + for (name, desc, mip, padding) in cases { + let layout = Layout::new(&desc).unwrap(); + let m = layout.mips[mip as usize]; + let active = m.width as usize * desc.element_bytes as usize; + let row = active + padding; + let plane = row * m.height as usize; + let bytes = active * m.height as usize * m.depth as usize; + let mut tiled = vec![0x5a; layout.size as usize]; + let mut linear = vec![0; plane * m.depth as usize]; + let calls = (64usize << 20).div_ceil(bytes); + for detile in [true, false] { + let mut copy = || { + if detile { + layout.detile( + black_box(&tiled), + mip, + 0, + black_box(&mut linear), + row, + plane, + ) + } else { + layout.tile( + black_box(&mut tiled), + mip, + 0, + black_box(&linear), + row, + plane, + ) + } + .unwrap(); + }; + copy(); + let mut samples = [0.0; 7]; + for sample in &mut samples { + let start = Instant::now(); + for _ in 0..calls { + copy(); + } + *sample = (bytes * calls) as f64 / start.elapsed().as_secs_f64() / 1e9; + } + samples.sort_by(f64::total_cmp); + let op = if detile { "detile" } else { "tile" }; + println!("{name:20} {op:6} {:8.2} GB/s", samples[3]); + } + } +} diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index 76afb0bde9..1990ab0c7a 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -612,9 +612,13 @@ impl Layout { row_pitch: usize, depth_pitch: usize, ) -> Result<(), Error> { - self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| { - linear[l..][..len].copy_from_slice(&tiled[t..][..len]); - }) + self.walk( + Buffers::Detile { tiled, linear }, + mip, + slice, + row_pitch, + depth_pitch, + ) } /// The reverse of [`Layout::detile`]: linear rows into tiled memory. @@ -627,22 +631,23 @@ impl Layout { row_pitch: usize, depth_pitch: usize, ) -> Result<(), Error> { - self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| { - tiled[t..][..len].copy_from_slice(&linear[l..][..len]); - }) + self.walk( + Buffers::Tile { tiled, linear }, + mip, + slice, + row_pitch, + depth_pitch, + ) } - /// Visits contiguous runs as (tiled byte offset, linear byte offset, length). - #[allow(clippy::too_many_arguments)] + /// Validates the full subresource before writing any bytes. fn walk( &self, - tiled_len: usize, + mut copy: Buffers<'_>, mip: u32, slice: u32, - linear_len: usize, row_pitch: usize, depth_pitch: usize, - mut copy: impl FnMut(usize, usize, usize), ) -> Result<(), Error> { let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?; let depth = m.depth; @@ -676,68 +681,158 @@ impl Layout { .checked_mul(depth_pitch) .and_then(|offset| offset.checked_add(slice_bytes)) .ok_or(Error::TooSmall)?; + let (tiled_len, linear_len) = match © { + Buffers::Tile { tiled, linear } => (tiled.len(), linear.len()), + Buffers::Detile { tiled, linear } => (tiled.len(), linear.len()), + }; if tiled_len < self.size as usize || linear_len < need || row_pitch < bytes { return Err(Error::TooSmall); } - let linear = self.desc.swizzle == Swizzle::LINEAR; - // The row and depth contribute one common base to every column, so - // the same contiguous runs repeat on every row, including mip tails. - let mut runs = Vec::new(); - if !linear { - let mut first_linear = 0; - let mut first_tiled = self.column(m, 0) as usize; - for x in 1..m.width { - let offset = self.column(m, x) as usize; - let at = x as usize * n; - if offset != first_tiled + (at - first_linear) { - runs.push((first_tiled, first_linear, at - first_linear)); - first_tiled = offset; - first_linear = at; + if self.desc.swizzle == Swizzle::LINEAR { + let tiled_pitch = m.pitch as usize * n; + for z in 0..depth { + let base = (u64::from(first + z) * self.slice_size + m.offset) as usize; + let linear_base = z as usize * depth_pitch; + // Only active rows with no padding on either side form a span. + if tiled_pitch == bytes && row_pitch == bytes { + copy.span(base, linear_base, slice_bytes); + continue; + } + for y in 0..m.height as usize { + copy.span(base + y * tiled_pitch, linear_base + y * row_pitch, bytes); } } - runs.push((first_tiled, first_linear, bytes - first_linear)); + return Ok(()); } - // A mip can end partway through the last run. Check the other runs - // once so each row can copy them with a compile-time length. - let (body, last) = runs.split_at(runs.len().saturating_sub(1)); - let run_len = body - .first() - .map(|run| run.2) - .filter(|&len| body.iter().all(|run| run.2 == len)); - for z in 0..depth { - let (s, inner) = self.split(first + z); - let base = u64::from(s) * self.slice_size + m.offset; - for y in 0..m.height { - let linear_row = z as usize * depth_pitch + y as usize * row_pitch; - if linear { - let tiled_row = base + u64::from(y) * u64::from(m.pitch) * n as u64; - copy(tiled_row as usize, linear_row, bytes); - } else { - let tiled_row = (base + self.row(m, y, inner)) as usize; - match run_len { - Some(8) => copy_runs::<8>(body, tiled_row, linear_row, &mut copy), - Some(16) => copy_runs::<16>(body, tiled_row, linear_row, &mut copy), - Some(32) => copy_runs::<32>(body, tiled_row, linear_row, &mut copy), - _ => copy_runs::<0>(body, tiled_row, linear_row, &mut copy), + + // The low contiguous x bits repeat in every block. Tail origins are + // micro-tile aligned, so only the last run of a row can be short. + let xs = &self.pattern[0]; + let run = xs + .iter() + .enumerate() + .take_while(|&(x, &offset)| offset as usize == x * n) + .count(); + match run * n { + 4 => self.walk_runs::<4>(m, first, row_pitch, depth_pitch, &mut copy), + 8 => self.walk_runs::<8>(m, first, row_pitch, depth_pitch, &mut copy), + 16 => self.walk_runs::<16>(m, first, row_pitch, depth_pitch, &mut copy), + 32 => self.walk_runs::<32>(m, first, row_pitch, depth_pitch, &mut copy), + _ => unreachable!("GFX10 contiguous run width"), + } + Ok(()) + } + + fn walk_runs( + &self, + m: &Mip, + first: u32, + row_pitch: usize, + depth_pitch: usize, + copy: &mut Buffers<'_>, + ) { + let n = self.desc.element_bytes as usize; + let run = N / n; + let bytes = m.width as usize * n; + // Column indices are in N-byte units, shared by all rows and slices. + let columns: Vec<_> = (0..bytes / N) + .map(|i| self.column(m, (i * run) as u32) as usize / N) + .collect(); + let end = columns.len() * N; + let last = (end < bytes).then(|| self.column(m, (end / n) as u32) as usize); + // Pair short runs to keep writes to nearby tiled addresses together. + // Wide runs already transfer 32 bytes per visit. + let rows = if N < 32 { 2 } else { 1 }; + let bd = self.block[2]; + for slab in (0..m.depth).step_by(bd as usize) { + let (slice, _) = self.split(first + slab); + let base = u64::from(slice) * self.slice_size + m.offset; + for y in (0..m.height).step_by(rows) { + // Tail origins and row pairs both start on even y. The low y + // bit gives the distance to the second row in this block. + let second = (rows == 2 && y + 1 < m.height).then(|| self.pattern[1][1] as usize); + let row = base + self.row(m, y, 0); + // Depth slices in this slab share the same physical blocks. + for inner in 0..bd.min(m.depth - slab) { + let t = row as usize + self.pattern[2][inner as usize] as usize; + let l = (slab + inner) as usize * depth_pitch + y as usize * row_pitch; + copy.runs::(&columns, t, l, row_pitch, second); + if let Some(col) = last { + copy.span(t + col, l + end, bytes - end); + if let Some(dy) = second { + copy.span(t + dy + col, l + row_pitch + end, bytes - end); + } } - copy_runs::<0>(last, tiled_row, linear_row, &mut copy); } } } - Ok(()) } } -/// Copy micro-tile runs inline at a known width, or use each run's length for N = 0. -fn copy_runs( - runs: &[(usize, usize, usize)], - tiled_row: usize, - linear_row: usize, - copy: &mut impl FnMut(usize, usize, usize), -) { - for &(tiled, linear, len) in runs { - let len = if N == 0 { len } else { N }; - copy(tiled_row + tiled, linear_row + linear, len); +enum Buffers<'a> { + Detile { + tiled: &'a [u8], + linear: &'a mut [u8], + }, + Tile { + tiled: &'a mut [u8], + linear: &'a [u8], + }, +} + +impl Buffers<'_> { + fn span(&mut self, t: usize, l: usize, len: usize) { + match self { + Self::Detile { tiled, linear } => { + linear[l..][..len].copy_from_slice(&tiled[t..][..len]) + } + Self::Tile { tiled, linear } => tiled[t..][..len].copy_from_slice(&linear[l..][..len]), + } + } + + fn runs( + &mut self, + columns: &[usize], + t: usize, + l: usize, + pitch: usize, + second: Option, + ) { + let len = columns.len() * N; + match self { + Self::Detile { tiled, linear } => { + let (src, _) = tiled[t..].as_chunks::(); + let (top, rest) = linear[l..].split_at_mut(len); + let (top, _) = top.as_chunks_mut::(); + if let Some(dy) = second { + let (bottom, _) = rest[pitch - len..][..len].as_chunks_mut::(); + for ((a, b), &x) in top.iter_mut().zip(bottom).zip(columns) { + *a = src[x]; + *b = src[x + dy / N]; + } + } else { + for (out, &x) in top.iter_mut().zip(columns) { + *out = src[x]; + } + } + } + Self::Tile { tiled, linear } => { + let (dst, _) = tiled[t..].as_chunks_mut::(); + let (top, rest) = linear[l..].split_at(len); + let (top, _) = top.as_chunks::(); + if let Some(dy) = second { + let (bottom, _) = rest[pitch - len..][..len].as_chunks::(); + for ((a, b), &x) in top.iter().zip(bottom).zip(columns) { + dst[x] = *a; + dst[x + dy / N] = *b; + } + } else { + for (value, &x) in top.iter().zip(columns) { + dst[x] = *value; + } + } + } + } } } @@ -883,6 +978,83 @@ mod tests { } } + /// Active bytes copied per second on synthetic surfaces: + /// `cargo test --release -p victory-formats detile_throughput -- --ignored --nocapture`. + #[test] + #[ignore = "benchmark"] + fn detile_throughput() { + use std::hint::black_box; + use std::time::Instant; + + let bc = |n, swizzle| Desc { + block: 4, + ..desc(4096, 4096, 13, n, swizzle) + }; + let cases = [ + ("BC7 64KB_D", bc(16, Swizzle::SW_64KB_D), 0), + ("BC7 64KB_S", bc(16, Swizzle::SW_64KB_S), 0), + ("BC1 64KB_D", bc(8, Swizzle::SW_64KB_D), 0), + ( + "RGBA8 64KB_D", + desc(1920, 1080, 1, 4, Swizzle::SW_64KB_D), + 0, + ), + ("RGBA8 4KB_S", desc(1920, 1080, 1, 4, Swizzle::SW_4KB_S), 0), + ("BC7 64KB_D tail", bc(16, Swizzle::SW_64KB_D), 5), + ( + "RGBA8 3D 4KB_S", + Desc { + dimension: Dimension::Tex3d, + depth: 64, + ..desc(128, 128, 1, 4, Swizzle::SW_4KB_S) + }, + 0, + ), + ]; + for (name, d, mip) in cases { + let layout = Layout::new(&d).unwrap(); + let m = layout.mips[mip as usize]; + let row = m.width as usize * d.element_bytes as usize; + let plane = row * m.height as usize; + let bytes = plane * m.depth as usize; + let mut tiled = vec![0x5a; layout.size as usize]; + let mut linear = vec![0; bytes]; + let runs = (256usize << 20).div_ceil(bytes); + for detile in [true, false] { + let mut copy = || { + if detile { + layout.detile( + black_box(&tiled), + mip, + 0, + black_box(&mut linear), + row, + plane, + ) + } else { + layout.tile( + black_box(&mut tiled), + mip, + 0, + black_box(&linear), + row, + plane, + ) + } + .unwrap(); + }; + copy(); + let start = Instant::now(); + for _ in 0..runs { + copy(); + } + let rate = (bytes * runs) as f64 / start.elapsed().as_secs_f64() / 1e6; + let op = if detile { "detile" } else { "tile" }; + println!("{name} {op}: {rate:.1} MB/s"); + } + } + } + #[test] fn linear_layouts_require_one_sample() { let linear = desc(256, 256, 1, 4, Swizzle::LINEAR); @@ -973,10 +1145,38 @@ mod tests { ..desc(64, 32, 7, 4, Swizzle::SW_4KB_S) }, ]; - for d in cases { + // Odd dimensions exercise a short final run and an unpaired row. + // Cross a block boundary for every addressable pattern and run width. + let arrays = [ + Swizzle::LINEAR, + Swizzle::SW_256B_S, + Swizzle::SW_256B_D, + Swizzle::SW_4KB_S, + Swizzle::SW_4KB_D, + Swizzle::SW_64KB_S, + Swizzle::SW_64KB_D, + ] + .into_iter() + .flat_map(|swizzle| { + [1, 2, 4, 8, 16].map(|n| Desc { + depth: 2, + ..desc(259, 19, 8, n, swizzle) + }) + }); + let volumes = [Swizzle::LINEAR, Swizzle::SW_4KB_S, Swizzle::SW_64KB_S] + .into_iter() + .flat_map(|swizzle| { + [1, 2, 4, 8, 16].map(|n| Desc { + dimension: Dimension::Tex3d, + depth: 35, + ..desc(37, 19, 6, n, swizzle) + }) + }); + for d in cases.into_iter().chain(arrays).chain(volumes) { let l = Layout::new(&d).unwrap(); let mut seen = vec![false; l.size as usize]; - let mut tiled = vec![0u8; l.size as usize]; + let mut tiled = vec![0xcc; l.size as usize]; + let mut expected = tiled.clone(); let n = d.element_bytes as usize; let slices = if d.dimension == Dimension::Tex3d { 1 } else { d.depth }; for slice in 0..slices { @@ -986,7 +1186,9 @@ mod tests { let row = active + 13; let plane = row * m.height as usize + 11; let linear: Vec = (0..plane * m.depth as usize) - .map(|i| (i * 7 + mip as usize * 13 + slice as usize) as u8) + .map(|i| { + ((i ^ (i >> 8) ^ (i >> 16)) + mip as usize * 13 + slice as usize) as u8 + }) .collect(); l.tile(&mut tiled, mip, slice, &linear, row, plane).unwrap(); let mut back = vec![0xcc; linear.len()]; @@ -1000,7 +1202,7 @@ mod tests { for x in 0..m.width { let at = l.offset(mip, x, y, slice + z).unwrap() as usize; let source = start + x as usize * n; - assert_eq!(tiled[at..at + n], linear[source..source + n]); + expected[at..at + n].copy_from_slice(&linear[source..source + n]); assert!(at + n <= seen.len(), "{d:?} mip {mip} outside"); assert!(at.is_multiple_of(n)); assert!(!seen[at], "{d:?} mip {mip} ({x},{y},{z}) twice"); @@ -1009,6 +1211,7 @@ mod tests { } assert!(back[base + plane - 11..base + plane].iter().all(|&b| b == 0xcc)); } + assert!(tiled == expected, "{d:?} mip {mip} slice {slice}"); } } } @@ -1252,6 +1455,71 @@ mod tests { ); } + #[test] + fn contiguous_linear_rows_respect_mip_and_depth_gaps() { + let layout = Layout::new(&Desc { + dimension: Dimension::Tex3d, + depth: 3, + ..desc(256, 5, 2, 1, Swizzle::LINEAR) + }) + .unwrap(); + let row = 256; + let active = row * 5; + let pitch = active + 13; + let len = 2 * pitch + active; + let linear: Vec<_> = (0..len).map(|i| (i ^ (i >> 8)) as u8).collect(); + let mut tiled = vec![0xcc; layout.size as usize]; + let mut expected = tiled.clone(); + let mut back = vec![0xcc; len]; + + layout.tile(&mut tiled, 0, 0, &linear, row, pitch).unwrap(); + for z in 0..3 { + let offset = layout.offset(0, 0, 0, z).unwrap() as usize; + let start = z as usize * pitch; + expected[offset..][..active].copy_from_slice(&linear[start..][..active]); + } + assert_eq!(tiled, expected); + + layout.detile(&tiled, 0, 0, &mut back, row, pitch).unwrap(); + for z in 0..3 { + let start = z * pitch; + assert_eq!(back[start..][..active], linear[start..][..active]); + } + assert!(back[active..pitch].iter().all(|&byte| byte == 0xcc)); + assert!( + back[pitch + active..2 * pitch] + .iter() + .all(|&byte| byte == 0xcc) + ); + } + + #[test] + fn copy_errors_precede_writes_in_both_directions() { + for (swizzle, samples, mip, slice, error) in [ + (Swizzle::SW_64KB_D_X, 1, 0, 0, Error::Unsupported), + (Swizzle::SW_64KB_S_X, 1, 0, 0, Error::Unsupported), + (Swizzle::SW_64KB_S_T, 1, 0, 0, Error::Unsupported), + (Swizzle::SW_64KB_D, 2, 0, 0, Error::Unsupported), + (Swizzle::SW_64KB_D_X, 1, 1, 0, Error::Invalid), + (Swizzle::SW_64KB_S_X, 1, 0, 1, Error::Invalid), + (Swizzle::SW_64KB_D, 1, 0, 0, Error::TooSmall), + ] { + let l = Layout::new(&Desc { + samples, + ..desc(17, 9, 1, 16, swizzle) + }) + .unwrap(); + let mut tiled = [0xac]; + let mut linear = [0xdc]; + assert_eq!(l.tile(&mut tiled, mip, slice, &linear, 0, 0), Err(error)); + assert_eq!(l.detile(&tiled, mip, slice, &mut linear, 0, 0), Err(error)); + assert_eq!((tiled, linear), ([0xac], [0xdc])); + } + let l = volume_pitch_layout(Swizzle::SW_4KB_S); + assert_eq!(l.tile(&mut [], 0, 1, &[], 0, 0), Err(Error::Invalid)); + assert_eq!(l.detile(&[], 0, 1, &mut [], 0, 0), Err(Error::Invalid)); + } + fn volume_pitch_layout(swizzle: Swizzle) -> Layout { Layout::new(&Desc { dimension: Dimension::Tex3d, diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 74e4bf550c..76db98e8a7 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -19,8 +19,7 @@ pub(crate) struct HostHeap { step: u32, /// Slots mirroring the title's; view heaps have `dynamic` more. count: u32, - /// Dynamic slots past `count` (none in sampler heaps): [`DYNAMIC`] - /// where the host takes them, else [`MIN_DYNAMIC`]. + /// Dynamic slots past `count` (none in sampler heaps). dynamic: u32, sampler: bool, /// The record (view index and generation) each slot was last made from. @@ -84,10 +83,6 @@ pub(crate) fn near_heaps(va: u64) -> String { text } -/// The host's limit for shader-visible view heaps on resource binding -/// tiers 1 and 2; tier 3 hardware may take more. -const PORTABLE_VIEWS: u32 = 1_000_000; - /// Slots past the title's in a view heap, for tables a draw needs made /// afresh (constant buffers copied per draw). A list holds the slots it /// took until it is reset (its submissions have run) or released. @@ -95,9 +90,16 @@ const PORTABLE_VIEWS: u32 = 1_000_000; /// each a device removal shortly after; #59). const DYNAMIC: u32 = 1 << 18; -/// The dynamic slots of a heap whose host would not take [`DYNAMIC`] more -/// (a capped heap, NVIDIA): the title's slots keep their room first. +/// Keep this much transient capacity even when the title fills the heap. const MIN_DYNAMIC: u32 = 1 << 16; +/// Leave room for persistent pairs, the raw null views, and the clamp slot. +const RESERVED_VIEWS: u32 = 1024; + +fn view_ranges(requested: u32) -> (u32, u32) { + let end = victory_shader::emit::HEAP_VIEWS - RESERVED_VIEWS; + let title = requested.min(end - MIN_DYNAMIC); + (title, DYNAMIC.min(end - title)) +} impl HostHeap { pub(crate) fn new(sampler: bool, count: u32) -> Option { @@ -119,16 +121,29 @@ impl HostHeap { }) } }; - // Every slot a shader can index (title slots, also past a capped - // heap, and dynamic ones): shaders read the table as a root view, - // which has no bounds, at indices clamped below `HEAP_VIEWS`. + let (views, samplers) = (victory_shader::emit::HEAP_VIEWS, victory_shader::emit::HEAP_SAMPLERS); + let (count, extra, total) = if sampler { + (count.min(samplers), 0, samplers) + } else { + let (title, dynamic) = view_ranges(count); + (title, dynamic, views) + }; + let heap = match make(total) { + Ok(heap) => heap, + Err(error) => { + tracing::warn!(%error, count, sampler, "no host descriptor heap"); + return None; + } + }; + // Root views are unbounded. Back every index the shader can produce + // with storage, including the null slots at the end. let strides = (!sampler) - .then(|| host.upload_buffer(u64::from(count.max(victory_shader::emit::HEAP_VIEWS)) * 4)) + .then(|| host.upload_buffer(u64::from(views) * 4)) .flatten() .map(|(buffer, data)| (buffer, data as usize)); let marks = (!sampler) .then(|| { - let bytes = u64::from(count.max(victory_shader::emit::HEAP_VIEWS)) * 8; + let bytes = u64::from(views) * 8; let (buffer, data) = host.upload_buffer(bytes)?; crate::host::name(&buffer, || "view marks".into()); // Every slot unmarked (all ones) until a view is made there. @@ -137,38 +152,6 @@ impl HostHeap { Some((buffer, data as usize)) }) .flatten(); - // The larger dynamic range only where the host takes it on top of - // every title slot; else the smaller one, and the cap after that. - // Translated shaders clamp their indices below `HEAP_VIEWS` or - // `HEAP_SAMPLERS`: slots up to there exist and stay null. - let (views, samplers) = (victory_shader::emit::HEAP_VIEWS, victory_shader::emit::HEAP_SAMPLERS); - let (heap, count, extra) = if sampler { - match make(count.max(samplers)) { - Ok(heap) => (heap, count, 0), - Err(e) => { - tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); - return None; - } - } - } else if let Ok(heap) = make((count + DYNAMIC).max(views)) { - (heap, count, DYNAMIC) - } else { - // shortcut: a host that caps its heaps below `HEAP_VIEWS` (NVIDIA) - // faults on an index past them, as before the clamp. - match make(count + MIN_DYNAMIC) { - Ok(heap) => (heap, count, MIN_DYNAMIC), - Err(e) if count + MIN_DYNAMIC > PORTABLE_VIEWS => { - // shortcut: descriptors past the host's limit are left - // out; a title that reaches them needs remapping. - tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}"); - (make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - MIN_DYNAMIC, MIN_DYNAMIC) - } - Err(e) => { - tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); - return None; - } - } - }; // SAFETY: a live heap. let (cpu, step) = unsafe { ( @@ -178,9 +161,7 @@ impl HostHeap { }; tracing::debug!(count, sampler, "host descriptor heap"); // SAFETY: a live shader-visible heap. - let (gpu, total) = unsafe { - (heap.GetGPUDescriptorHandleForHeapStart().ptr, heap.GetDesc().NumDescriptors) - }; + let gpu = unsafe { heap.GetGPUDescriptorHandleForHeapStart().ptr }; GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push(( gpu, u64::from(total) * u64::from(step), @@ -198,10 +179,7 @@ impl HostHeap { kept: Mutex::new(vec![None; (count + extra) as usize]), next: Mutex::new((0, vec![false; extra as usize])), pairs: Mutex::new((count + extra, Vec::new())), - pairs_end: match victory_shader::emit::NULL_BUFFER_VIEW { - null if !sampler && null > count + extra && null < total => null - 1, - _ => total, - }, + pairs_end: victory_shader::emit::NULL_BUFFER_VIEW - 1, strides, marks, addresses: std::sync::OnceLock::new(), @@ -223,46 +201,56 @@ impl HostHeap { // they take one at a computed index (`victory_shader::emit`, "Buffer // views at computed heap indices"): a null raw SRV, and UAV below it. let null = victory_shader::emit::NULL_BUFFER_VIEW; - if !sampler && null > count + extra && null < total { + if !sampler { h.raw_view_at(null, None, 0, 0, false); h.raw_view_at(null - 1, None, 0, 0, true); - } else if !sampler { - tracing::warn!(count, total, "no room for the null buffer views: computed indices of slots without a buffer view read what is there"); } Some(h) } - /// Makes the first `total` slots null: one null slot in a CPU-side heap, - /// doubled by copies to a block, the block copied over the heap. + /// Copies an immutable CPU-side template over the shader-visible heap. fn fill_null(&self, kind: D3D12_DESCRIPTOR_HEAP_TYPE, total: u32) -> windows::core::Result<()> { - const BLOCK: u32 = 1 << 16; + use victory_shader::emit::HEAP_SAMPLERS; + static VIEWS: Mutex> = Mutex::new(None); + static SAMPLERS: Mutex> = Mutex::new(None); + let (template, slots) = if self.sampler { (&SAMPLERS, HEAP_SAMPLERS) } else { (&VIEWS, 1 << 16) }; let Some(host) = host() else { return Ok(()) }; // SAFETY: plain heap creation and copies inside live heaps. unsafe { - let block: ID3D12DescriptorHeap = - host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { - Type: kind, - NumDescriptors: BLOCK, - ..Default::default() - })?; - let start = block.GetCPUDescriptorHandleForHeapStart(); - let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { - ptr: start.ptr + (i * self.step) as usize, + let block = { + let mut cached = template.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(block) = cached.as_ref() { + block.clone() + } else { + let block: ID3D12DescriptorHeap = + host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: slots, + ..Default::default() + })?; + let start = block.GetCPUDescriptorHandleForHeapStart(); + if self.sampler { + null_sampler(start); + } else { + null_view(start); + } + let mut filled = 1; + while filled < slots { + let dst = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start.ptr + (filled * self.step) as usize, + }; + let n = filled.min(slots - filled); + host.device.CopyDescriptorsSimple(n, dst, start, kind); + filled += n; + } + *cached = Some(block.clone()); + block + } }; - if self.sampler { - null_sampler(start); - } else { - null_view(start); - } - let mut filled = 1; - while filled < BLOCK { - let n = filled.min(BLOCK - filled); - host.device.CopyDescriptorsSimple(n, at(filled), start, kind); - filled += n; - } + let start = block.GetCPUDescriptorHandleForHeapStart(); let mut done = 0; while done < total { - let n = BLOCK.min(total - done); + let n = slots.min(total - done); host.device.CopyDescriptorsSimple(n, self.cpu(done), start, kind); done += n; } @@ -2213,6 +2201,38 @@ mod tests { assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); } + #[test] + fn view_ranges_keep_null_and_pair_slots_outside_dynamic() { + let end = victory_shader::emit::HEAP_VIEWS - RESERVED_VIEWS; + assert_eq!(view_ranges(0), (0, DYNAMIC)); + assert_eq!(view_ranges(end - DYNAMIC), (end - DYNAMIC, DYNAMIC)); + assert_eq!(view_ranges(end - DYNAMIC + 1), (end - DYNAMIC + 1, DYNAMIC - 1)); + assert_eq!(view_ranges(u32::MAX), (end - MIN_DYNAMIC, MIN_DYNAMIC)); + assert!(end + 2 < victory_shader::emit::NULL_BUFFER_VIEW); + } + + #[test] + #[ignore = "synthetic D3D12 heap creation benchmark"] + fn host_heap_creation_throughput() { + assert!(host().is_some(), "a host D3D12 device is required"); + for (sampler, count) in [(true, 128), (false, 4_096), (false, 262_144)] { + drop(HostHeap::new(sampler, count).expect("warm-up heap")); + let mut durations = [std::time::Duration::ZERO; 21]; + for duration in &mut durations { + let start = std::time::Instant::now(); + let heap = HostHeap::new(sampler, count).expect("benchmark heap"); + *duration = start.elapsed(); + drop(heap); + } + durations.sort_unstable(); + eprintln!( + "sampler={sampler} title_slots={count} median_us={} p90_us={}", + durations[10].as_micros(), + durations[18].as_micros() + ); + } + } + /// Dynamic slots stay taken until given back, and runs do not wrap. #[test] fn dynamic_slots_are_held_until_released() { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 3c2ed783c5..4e4ded231d 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -190,7 +190,20 @@ fn create() -> windows::core::Result { D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?; tracing::info!("host device on the software adapter (WARP)"); } else { - D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; + if crate::switch::on("VICTORY_D3D12_NVIDIA") { + match nvidia_device() { + Ok(Some(nvidia)) => device = Some(nvidia), + Ok(None) => { + tracing::warn!("no compatible NVIDIA adapter; using the default D3D12 adapter"); + } + Err(error) => tracing::warn!( + %error, "NVIDIA adapter enumeration failed; using the default D3D12 adapter" + ), + } + } + if device.is_none() { + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; + } // Whether a GPU hang ends the run or freezes the PC (#1054). crate::tdr::log(); } @@ -269,6 +282,42 @@ fn create() -> windows::core::Result { } } +/// Create a D3D12 device on the first NVIDIA adapter that supports level 12_0. +fn nvidia_device() -> windows::core::Result> { + const NVIDIA_VENDOR_ID: u32 = 0x10de; + // SAFETY: DXGI queries and D3D12 device creation with valid out pointers. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; + for index in 0.. { + let adapter = match factory.EnumAdapters1(index) { + Ok(adapter) => adapter, + Err(error) if error.code() == DXGI_ERROR_NOT_FOUND => break, + Err(error) => return Err(error), + }; + let desc = adapter.GetDesc1()?; + if desc.VendorId != NVIDIA_VENDOR_ID + || desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 + { + continue; + } + let mut device = None; + if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).is_ok() + && device.is_some() + { + let end = desc + .Description + .iter() + .position(|&ch| ch == 0) + .unwrap_or(desc.Description.len()); + let name = String::from_utf16_lossy(&desc.Description[..end]); + tracing::info!(adapter = %name, "host device on NVIDIA"); + return Ok(device); + } + } + } + Ok(None) +} + /// Diagnostics: our process's private commit and working set, bytes. #[cfg(feature = "diagnostics")] fn process_memory() -> (u64, u64) { @@ -652,6 +701,29 @@ pub(crate) mod tests { eprintln!("PresentX compositor initialized"); } + #[test] + fn nvidia_preference_selects_the_nvidia_device() { + if !crate::switch::on("VICTORY_D3D12_NVIDIA") + || (cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_WARP")) + { + return; + } + let host = host().expect("a host D3D12 device"); + let Some(nvidia) = nvidia_device().unwrap() else { + return; // exercises the default device when NVIDIA is absent + }; + // SAFETY: LUID queries on live D3D12 devices. + unsafe { + let selected = host.device.GetAdapterLuid(); + let expected = nvidia.GetAdapterLuid(); + assert_eq!( + (selected.HighPart, selected.LowPart), + (expected.HighPart, expected.LowPart) + ); + eprintln!("host D3D12 device matches the NVIDIA adapter LUID"); + } + } + #[test] fn warp_adapter_accepts_only_software() { // This probes DXGI without creating a D3D12 device or running a title. diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 441dae7435..b61033739d 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -30,7 +30,9 @@ pub const MEMORY_SPACE: u32 = 2; /// Heap indices are clamped below these (views, samplers): the host's heaps /// are at least this large, the slots past their own null (`emit`, "Heap /// indices"). -pub const HEAP_VIEWS: u32 = 1 << 21; +// Match the portable D3D12 heap size, including on tier-3 devices that +// reject larger heaps. The runtime and standalone dispatch share this bound. +pub const HEAP_VIEWS: u32 = 1_000_000; pub const HEAP_SAMPLERS: u32 = 2048; /// The heap index of the host's null raw buffer view (the null raw /// unordered access view at the index below), read instead of a slot that diff --git a/xtask/src/frame_stats.rs b/xtask/src/frame_stats.rs new file mode 100644 index 0000000000..453fbcc558 --- /dev/null +++ b/xtask/src/frame_stats.rs @@ -0,0 +1,120 @@ +//! Offline summary of frame intervals measured by an external capture tool. + +use std::fs::File; +use std::io::{BufRead, BufReader}; +use std::path::Path; + +use anyhow::{Context, Result, ensure}; + +const FRAME_BUDGET_MS: f64 = 1000.0 / 30.0; + +pub fn run(input: &Path, stutter_ms: f64) -> Result<()> { + ensure!( + stutter_ms.is_finite() && stutter_ms > 0.0, + "invalid stutter threshold" + ); + let file = File::open(input).with_context(|| format!("opening {}", input.display()))?; + let mut frames = read_frames(BufReader::new(file))?; + let budget_misses = frames.iter().filter(|&&ms| ms > FRAME_BUDGET_MS).count(); + let stutters = frames.iter().filter(|&&ms| ms > stutter_ms).count(); + frames.sort_unstable_by(f64::total_cmp); + let count = frames.len(); + let median = frames[(count - 1) / 2].midpoint(frames[count / 2]); + println!("Frames: {count}"); + println!("Average FPS: {:.3}", 1000.0 / mean(&frames)); + println!( + "Median FPS (inverse median interval): {:.3}", + 1000.0 / median + ); + for (label, denominator) in [("1% low", 100), ("0.1% low", 1000)] { + if count >= denominator { + let start = count - count.div_ceil(denominator); + println!("{label} FPS: {:.3}", 1000.0 / mean(&frames[start..])); + } else { + println!("{label} FPS: unavailable (requires {denominator} frames)"); + } + } + for (label, per_mille) in [("P95", 950), ("P99", 990), ("P99.9", 999)] { + println!( + "{label} frametime: {:.3} ms", + percentile(&frames, per_mille) + ); + } + println!("Frames over 30 FPS budget ({FRAME_BUDGET_MS:.3} ms): {budget_misses}/{count}"); + println!( + "Stutters (> {stutter_ms:.3} ms): {stutters}/{count} ({:.3}%)", + 100.0 * stutters as f64 / count as f64 + ); + Ok(()) +} + +fn read_frames(reader: impl BufRead) -> Result> { + let mut lines = reader.lines(); + let header = lines.next().context("missing frametime_ms header")??; + ensure!( + header.trim_start_matches('\u{feff}').trim() == "frametime_ms", + "expected a frametime_ms header" + ); + let mut frames = Vec::new(); + for (index, line) in lines.enumerate() { + let number = index + 2; + let line = line.with_context(|| format!("reading line {number}"))?; + let ms: f64 = line + .trim() + .parse() + .with_context(|| format!("invalid frametime at line {number}"))?; + ensure!( + ms.is_finite() && ms > 0.0 && (1000.0 / ms).is_finite(), + "invalid frametime at line {number}" + ); + frames.push(ms); + } + ensure!(!frames.is_empty(), "capture has no frame intervals"); + Ok(frames) +} + +fn mean(values: &[f64]) -> f64 { + let mut mean = values[0]; + for (index, &value) in values.iter().enumerate().skip(1) { + mean += (value - mean) / (index + 1) as f64; + } + mean +} + +fn percentile(sorted: &[f64], per_mille: u128) -> f64 { + let rank = (sorted.len() as u128 * per_mille).div_ceil(1000); + sorted[rank as usize - 1] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_bom_and_rejects_missing_or_invalid_intervals() { + assert_eq!( + read_frames("\u{feff}frametime_ms\r\n16.7\r\n50\r\n".as_bytes()).unwrap(), + [16.7, 50.0] + ); + for bad in [ + "", + "fps\n30", + "frametime_ms\n", + "frametime_ms\nNaN", + "frametime_ms\n0", + "frametime_ms\n16,7", + ] { + assert!(read_frames(bad.as_bytes()).is_err()); + } + } + + #[test] + fn nearest_rank_preserves_tail_outliers() { + let mut frames = vec![20.0; 999]; + frames.push(100.0); + assert_eq!(percentile(&frames, 990), 20.0); + assert_eq!(percentile(&frames, 999), 20.0); + assert_eq!(percentile(&frames, 1000), 100.0); + assert!((mean(&frames) - 20.08).abs() < 1e-10); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 911ed8087c..c3d2f5d770 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,5 +1,6 @@ //! Repository maintenance. Run with `cargo xtask `. +mod frame_stats; mod policy; use std::path::{Path, PathBuf}; @@ -26,12 +27,20 @@ enum Cmd { }, /// Point git at .githooks/ so every commit runs the policy check. InstallHooks, + /// Summarize a one-column frametime_ms CSV from one capture. + FrameStats { + input: PathBuf, + /// Frames strictly above this interval count as stutters. + #[arg(long, default_value_t = 50.0)] + stutter_ms: f64, + }, } fn main() -> Result<()> { let root = workspace_root(); match Cli::parse().command { Cmd::Policy { staged } => policy::run(&root, staged), + Cmd::FrameStats { input, stutter_ms } => frame_stats::run(&input, stutter_ms), Cmd::InstallHooks => { let status = Command::new("git") .args(["config", "core.hooksPath", ".githooks"])