diff --git a/.github/workflows/d3d12.yml b/.github/workflows/d3d12.yml new file mode 100644 index 0000000000..3cf56fa817 --- /dev/null +++ b/.github/workflows/d3d12.yml @@ -0,0 +1,88 @@ +# Builds and tests the D3D12 runtime (d3d12/, Rust: leonida.exe and its crates) when it changes. Until now no workflow +# ran its tests, so a change that broke one of them reached main unseen. It needs no GPU and no game files: the tests +# that need a device or the title skip themselves. +# +# Measured on main 060c47160 (Windows 11, toolchain from d3d12/rust-toolchain.toml): the workspace builds in about +# 4 minutes and its tests take about 11; 1441 pass, 58 are ignored, and one fails, the xtask asset-policy test, because +# two sources are over its 640 KiB limit (crates/leonida-gpu/src/host.rs, crates/leonida-shader/src/emit/lower.rs). +# `cargo clippy -D warnings` also fails on main (about 25 findings in five crates) and `cargo fmt --check` would +# reformat most of the tree. So the tests are the gate; the policy test and clippy run as reports until those are fixed, +# and formatting is left out so it does not collide with the open d3d12 pull requests. +name: D3D12 runtime + +on: + push: + branches: [main] + paths: + - "d3d12/**" + # leonida-lua's tests read mods/example_lua. + - "mods/**" + - ".github/workflows/d3d12.yml" + pull_request: + paths: + - "d3d12/**" + # leonida-lua's tests read mods/example_lua. + - "mods/**" + - ".github/workflows/d3d12.yml" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + # Each non-PR run has its own group so a queued push or dispatch cannot replace it. + group: d3d12-${{ github.event_name }}-${{ github.event.pull_request.number || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + d3d12: + name: d3d12 (windows-latest) + # The crates are Windows-only today (leonida-gpu does not build on macOS); Linux follows #2577 if it lands. + runs-on: windows-latest + timeout-minutes: 70 + defaults: + run: + working-directory: d3d12 + shell: bash + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # The runner's own rustup installs the toolchain pinned in d3d12/rust-toolchain.toml, no third-party action. + - name: Rust toolchain + run: | + rustup show active-toolchain || rustup toolchain install + rustc --version + echo "RUSTC_HASH=$(rustc -vV | tr -d '\r' | awk '/^commit-hash: /{print $2}')" >> "$GITHUB_ENV" + - name: Cache Cargo downloads + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + key: d3d12-windows-cargo-${{ env.RUSTC_HASH }}-${{ hashFiles('d3d12/Cargo.lock') }} + restore-keys: | + d3d12-windows-cargo-${{ env.RUSTC_HASH }}- + d3d12-windows-cargo- + - name: Build + run: cargo build --workspace --all-targets --locked + # The features of the executable people run (d3d12/scripts/build-nvidia.ps1, without dlss); no other step builds them. + - name: Build as shipped (diagnostics, mimalloc) + run: cargo build -p leonida --features diagnostics,mimalloc --locked + # The software adapter of the runner does not do the depth bounds test as this one expects, and #2663 fixes that + # in the renderer; drop the --skip with it. A failing test here also stops the crates after leonida-gpu. + - name: Tests (no GPU, no game data) + timeout-minutes: 30 + run: cargo test --workspace --exclude xtask --locked -- --skip depth_bounds_pipeline_loads_and_filters_draws + # tests/replay.rs is compiled only with the diagnostics feature. + - name: Replay test (diagnostics) + timeout-minutes: 15 + run: cargo test -p leonida-gpu --features diagnostics --test replay --locked + # Report only until host.rs and lower.rs are split under the limit; make it blocking then. + - name: Asset policy (report) + continue-on-error: true + run: cargo test -p xtask --locked + # Report only until the existing findings are fixed; make it blocking (-D warnings) then. + - name: Clippy (report) + continue-on-error: true + run: cargo clippy --workspace --all-targets --locked -- -D warnings diff --git a/d3d12/.github/workflows/ci.yml b/d3d12/.github/workflows/ci.yml deleted file mode 100644 index 80e6a359ed..0000000000 --- a/d3d12/.github/workflows/ci.yml +++ /dev/null @@ -1,33 +0,0 @@ -name: CI - -on: - pull_request: - push: - branches: [main] - -permissions: - contents: read - -concurrency: - group: ci-${{ github.ref }} - cancel-in-progress: true - -env: - CARGO_TERM_COLOR: always - -jobs: - check: - runs-on: windows-latest - timeout-minutes: 60 - steps: - - uses: actions/checkout@v5 - # The version and components pinned in rust-toolchain.toml. - - run: rustup toolchain install - - uses: Swatinem/rust-cache@v2 - - name: Clippy - run: cargo clippy --workspace --all-targets --locked -- -D warnings - - name: Clippy, diagnostics build - run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings - # Includes xtask's repository_passes_policy, the asset-policy check. - - name: Tests - run: cargo test --workspace --locked diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index 0baea51097..b380d0c330 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -5337,6 +5337,8 @@ pub(crate) mod indirects; mod font; #[cfg(feature = "diagnostics")] mod panel; +// Frame-time percentiles and what stalls frames, with the frame-rate line. +mod frametime; // Leonida: the F1 settings menu and the frame-rate line, in every build. mod menu; // Leonida: the trainer menu laid over the picture (`leonida-menu`, F4). @@ -12361,6 +12363,8 @@ struct Meter { logged: std::time::Instant, /// The caption the window had, once read. caption: Option>, + /// Frame times and stalls, logged with the line. + stalls: frametime::Meter, } impl Meter { @@ -12374,6 +12378,10 @@ impl Meter { drawn: crate::draw::drawn(), logged: now, caption: None, + stalls: frametime::Meter::new( + crate::pipeline::made(), + RESIDENT[1].load(Ordering::Relaxed), + ), } } @@ -12389,6 +12397,7 @@ impl Meter { tracing::debug!(target: "leonida_gpu::frame", token = crate::frame::current(), "present"); #[cfg(feature = "diagnostics")] crate::copystat::presented(); + self.stalls.presented(std::time::Instant::now()); self.frames += 1; #[cfg(feature = "diagnostics")] { @@ -12409,6 +12418,13 @@ impl Meter { let five = self.logged.elapsed() >= std::time::Duration::from_secs(5); if five { self.logged = std::time::Instant::now(); + // (Here: the frame times are this meter's.) + self.stalls.line( + crate::pipeline::making(), + crate::pipeline::made(), + RESIDENT[1].load(Ordering::Relaxed), + crate::residency::available_commit(), + ); } // (The copy counters run from one five-second line to the next.) #[cfg(feature = "diagnostics")] diff --git a/d3d12/crates/leonida-gpu/src/host/frametime.rs b/d3d12/crates/leonida-gpu/src/host/frametime.rs new file mode 100644 index 0000000000..75e6e0d401 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/frametime.rs @@ -0,0 +1,284 @@ +//! Frame times as a distribution, not only a mean, so that stalls show: every +//! presented frame's time goes in, and with the frame-rate line, every five +//! seconds, one line gives the median, the 95th and 99th percentiles, the +//! longest frame and how many took over 100 ms and over a second, beside what +//! stalls frames: host pipelines queued and made a second, waits for new +//! memory to be resident, and the commit the system has left. The panel (F3) +//! shows the last one. + +use std::time::Instant; + +/// Frame times kept for the percentiles of one line (about 13 s at 300 fps); +/// past it the counts and the longest frame stay exact. +const KEPT: usize = 4096; + +/// The times of the frames since the last [`FrameTimes::take`], in ms. +#[derive(Default)] +pub(super) struct FrameTimes { + ms: Vec, + frames: u32, + longest: f32, + over_100: u32, + over_1s: u32, +} + +/// What [`FrameTimes::take`] gives back, in ms. The percentiles are nearest +/// rank: a value some frame took, such that that share of frames took as +/// long or less. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(super) struct Summary { + pub(super) frames: u32, + pub(super) p50: f32, + pub(super) p95: f32, + pub(super) p99: f32, + pub(super) longest: f32, + pub(super) over_100: u32, + pub(super) over_1s: u32, +} + +impl FrameTimes { + pub(super) fn push(&mut self, ms: f32) { + self.frames += 1; + self.longest = self.longest.max(ms); + self.over_100 += u32::from(ms > 100.0); + self.over_1s += u32::from(ms > 1000.0); + if self.ms.len() < KEPT { + self.ms.push(ms); + } + } + + /// The frames since the last call (none: `None`), and a fresh start. + pub(super) fn take(&mut self) -> Option { + if self.frames == 0 { + return None; + } + self.ms.sort_unstable_by(f32::total_cmp); + let n = self.ms.len(); + // Nearest rank, in whole numbers: the ceil(p * n / 100)-th time. + let at = |percent: usize| self.ms[(percent * n).div_ceil(100).clamp(1, n) - 1]; + let summary = Summary { + frames: self.frames, + p50: at(50), + p95: at(95), + p99: at(99), + longest: self.longest, + over_100: self.over_100, + over_1s: self.over_1s, + }; + self.ms.clear(); + (self.frames, self.longest, self.over_100, self.over_1s) = (0, 0.0, 0, 0); + Some(summary) + } +} + +/// One line's numbers. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(super) struct Stalls { + pub(super) times: Summary, + /// Host pipelines queued or being made. + pub(super) queued: u64, + pub(super) made_per_s: f64, + /// Waits for new memory to be resident, ms a frame. + pub(super) resident_ms: f64, + pub(super) commit_left_gb: f64, +} + +/// The last line's numbers, for the panel. +#[cfg(feature = "diagnostics")] +pub(super) static LAST: std::sync::Mutex> = std::sync::Mutex::new(None); + +/// The frame-rate meter's part: frame times, and the totals the next line +/// counts from. +pub(super) struct Meter { + times: FrameTimes, + last: Option, + since: Instant, + made: u64, + resident_us: u64, +} + +impl Meter { + /// From the totals so far (`made` host pipelines, `resident_us` waited for + /// new memory), so that the first line counts only what came after. + pub(super) fn new(made: u64, resident_us: u64) -> Meter { + Meter { + times: FrameTimes::default(), + last: None, + since: Instant::now(), + made, + resident_us, + } + } + + /// A frame was presented at `now`. + pub(super) fn presented(&mut self, now: Instant) { + if let Some(last) = self.last.replace(now) { + self.times.push((now - last).as_secs_f32() * 1000.0); + } + } + + /// Logs the line, from the totals since the start: `made` host pipelines, + /// `resident_us` waited for new memory; `queued` and `commit` (bytes) now. + pub(super) fn line(&mut self, queued: u64, made: u64, resident_us: u64, commit: u64) { + let Some(times) = self.times.take() else { + return; + }; + let now = Instant::now(); + let seconds = (now - self.since).as_secs_f64().max(1e-3); + let stalls = Stalls { + times, + queued, + made_per_s: made.saturating_sub(self.made) as f64 / seconds, + resident_ms: resident_us.saturating_sub(self.resident_us) as f64 + / 1e3 + / f64::from(times.frames), + commit_left_gb: commit as f64 / f64::from(1u32 << 30), + }; + (self.since, self.made, self.resident_us) = (now, made, resident_us); + tracing::info!( + "frame times over {seconds:.1} s, {} frames: median {:.1} ms, 95th percentile {:.1}, 99th {:.1}, longest {:.1}; \ + {} over 100 ms, {} over 1 s; host pipelines {queued} queued or being made, {:.1} made a second; waits for new memory to be \ + resident {:.2} ms a frame; commit left {:.1} GB", + times.frames, + times.p50, + times.p95, + times.p99, + times.longest, + times.over_100, + times.over_1s, + stalls.made_per_s, + stalls.resident_ms, + stalls.commit_left_gb + ); + #[cfg(feature = "diagnostics")] + if let Ok(mut last) = LAST.lock() { + *last = Some(stalls); + } + } +} + +/// A frame time for the panel in at most four or five characters: ms up to +/// 9999, then whole seconds with an S. +#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] +fn short(ms: f32) -> String { + if ms < 9999.5 { + format!("{ms:.0}") + } else { + format!("{:.0}S", ms / 1000.0) + } +} + +/// The panel's lines for `s`, with `pipeline_wait_ms` a frame (summed over +/// threads, over the panel's half second; the rest over the five-second +/// line), each at most 40 characters of the panel's font. +#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] +pub(super) fn panel_lines(s: &Stalls, pipeline_wait_ms: f64) -> [String; 5] { + let t = &s.times; + let (p50, p95, p99, max) = (short(t.p50), short(t.p95), short(t.p99), short(t.longest)); + [ + format!("P50 {p50} P95 {p95} P99 {p99} MAX {max}"), + format!("OVER 100 MS {} OVER 1 S {}", t.over_100, t.over_1s), + format!("PIPES PENDING {} MADE/S {:.1}", s.queued, s.made_per_s), + format!( + "WAITS PIPES {pipeline_wait_ms:.1} RESIDENT {:.1} MS", + s.resident_ms + ), + format!("COMMIT LEFT {:.1} GB", s.commit_left_gb), + ] +} + +#[cfg(test)] +mod tests { + use super::{FrameTimes, Stalls, Summary, panel_lines}; + + #[test] + fn frame_times_give_percentiles_counts_and_the_longest() { + let mut t = FrameTimes::default(); + assert_eq!(t.take(), None, "no frame, no line"); + // 98 smooth frames, one hitch and one stall. + for _ in 0..98 { + t.push(10.0); + } + t.push(150.0); + t.push(2000.0); + let s = t.take().unwrap(); + assert_eq!( + (s.frames, s.p50, s.p95, s.longest), + (100, 10.0, 10.0, 2000.0) + ); + assert_eq!(s.p99, 150.0, "the 99th of 100 frames is the second longest"); + assert_eq!((s.over_100, s.over_1s), (2, 1)); + assert_eq!(t.take(), None, "taking starts afresh"); + } + + #[test] + fn percentiles_are_nearest_rank_without_float_rounding() { + let mut t = FrameTimes::default(); + for ms in 1..=20 { + t.push(ms as f32); + } + let s = t.take().unwrap(); + // ceil(0.95 * 20) = 19, ceil(0.99 * 20) = 20, ceil(0.5 * 20) = 10. + assert_eq!((s.p50, s.p95, s.p99), (10.0, 19.0, 20.0)); + // Ranks are whole numbers, (percent * n).div_ceil(100), so no float + // can move one. For 50, 95 and 99 a float rank, ceil(p / 100 * n), + // happens to agree for every n up to 4096: this case pins the + // direction (up, not down) at 100 frames. + for ms in 1..=100 { + t.push(ms as f32); + } + let s = t.take().unwrap(); + assert_eq!((s.p50, s.p95, s.p99), (50.0, 95.0, 99.0)); + } + + #[test] + fn past_the_kept_times_the_counts_stay_exact() { + let mut t = FrameTimes::default(); + for _ in 0..super::KEPT { + t.push(16.0); + } + for _ in 0..10 { + t.push(1500.0); + } + let s = t.take().unwrap(); + assert_eq!(s.frames as usize, super::KEPT + 10); + assert_eq!((s.over_100, s.over_1s, s.longest), (10, 10, 1500.0)); + } + + #[test] + fn the_panel_lines_fit_its_box_and_font() { + // Long stalls too: 10 s and more (the launcher's pipeline budget), + // up to a minute without a present. + for ms in [9999.0, 10_000.0, 99_999.0, 600_000.0] { + let s = Stalls { + times: Summary { + frames: 9999, + p50: ms, + p95: ms, + p99: ms, + longest: ms, + over_100: 9999, + over_1s: 9999, + }, + queued: 99999, + made_per_s: 999.9, + resident_ms: 999.9, + commit_left_gb: 99.9, + }; + for line in panel_lines(&s, 9999.9) { + assert!( + line.len() <= 40, + "{line:?} is longer than the panel's 40 columns" + ); + assert!( + line.bytes().all(|c| c == b' ' + || crate::host::font::glyph(c) != crate::host::font::glyph(b'#')), + "{line:?} has a character the panel cannot draw" + ); + } + } + assert_eq!(super::short(9999.0), "9999"); + assert_eq!(super::short(10_000.0), "10S"); + assert_eq!(super::short(600_000.0), "600S"); + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/panel.rs b/d3d12/crates/leonida-gpu/src/host/panel.rs index a722f20aa7..6ba7daf7be 100644 --- a/d3d12/crates/leonida-gpu/src/host/panel.rs +++ b/d3d12/crates/leonida-gpu/src/host/panel.rs @@ -28,7 +28,7 @@ const GLYPH: (u32, u32) = (5, 7); const CELL: (u32, u32) = (6, 9); /// Characters in a line, lines, and the box's rim in dots. const COLUMNS: u32 = 40; -const LINES: u32 = 9; +const LINES: u32 = 14; const RIM: u32 = 3; /// The texts are put into one of these in turn: the card reads the others, @@ -118,7 +118,7 @@ fn painted(lines: &[String], scale: u32, colours: [&[u8]; 2], pitch: usize) -> V #[derive(Clone, Copy, Default)] struct Counters([u64; COUNTERS]); -const COUNTERS: usize = 11; +const COUNTERS: usize = 12; impl Counters { fn now() -> Counters { @@ -138,6 +138,7 @@ impl Counters { crate::drops::totals().1, peek(C::RecordNs), crate::draw::drawn(), + peek(C::PipelineWaitUs), ]) } @@ -159,7 +160,9 @@ fn text(c: &[f64; COUNTERS], ms: f64, worst: f64, cost: f64, host: &Host) -> Vec let (working, private) = crate::copystat::process_memory(); let [budget, used, _, shared] = host.video_memory().unwrap_or_default(); let idle = (c[1] / 1e3).min(ms); - vec![ + // The frame-time line's last numbers (every five seconds), once there is one. + let stalls = super::frametime::LAST.lock().ok().and_then(|last| *last); + let mut lines = vec![ // LOCAL (11/26): with frame generation, the frames shown beside those rendered. match crate::fg::shown_per_frame() { 1 => format!("FPS {:.1} FRAME {ms:.1} MS", 1e3 / ms.max(0.001)), @@ -173,7 +176,11 @@ fn text(c: &[f64; COUNTERS], ms: f64, worst: f64, cost: f64, host: &Host) -> Vec format!("RAM {:.1} GB IN MEMORY {:.1}", gb(private), gb(working)), format!("VRAM {:.1}/{:.1} GB SHARED {:.1}", gb(used), gb(budget), gb(shared)), format!("THIS PANEL {:.0} US A FRAME", cost), - ] + ]; + if let Some(s) = stalls { + lines.extend(super::frametime::panel_lines(&s, c[11] / 1e3)); + } + lines } /// The buffers of a box that size and format. diff --git a/d3d12/crates/leonida-gpu/src/pipeline.rs b/d3d12/crates/leonida-gpu/src/pipeline.rs index 808cd87c45..f8a7652f65 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline.rs @@ -839,6 +839,13 @@ pub(crate) fn making() -> u64 { make::waiting() } +/// Host pipelines created or loaded from the library since the start. +#[cfg(windows)] +pub(crate) fn made() -> u64 { + use std::sync::atomic::Ordering::Relaxed; + library::MADE.load(Relaxed) + library::LOADED.load(Relaxed) +} + /// Draws and dispatches dropped since the last [`take_drops`], by reason /// (diagnostics). #[cfg(all(windows, feature = "diagnostics"))] diff --git a/d3d12/crates/leonida-gpu/src/pipeline/make.rs b/d3d12/crates/leonida-gpu/src/pipeline/make.rs index 42189790a5..66e4e82aed 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/make.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/make.rs @@ -519,7 +519,12 @@ fn wait(p: &Pending, frame: u64) { if left.is_zero() { return; } + // Before the promotion: the queue's lock it may wait for is part of this + // frame's wait, not on top of it. let started = Instant::now(); + if await_first() { + promote(p); + } let (lock, done) = &DONE; let mut held = lock.lock().unwrap_or_else(|e| e.into_inner()); while p.made.get().is_none() { @@ -567,10 +572,35 @@ fn wait(p: &Pending, frame: u64) { ); } +/// Whether a pipeline a frame waits for goes before the others asked for +/// ([`AWAITED`]). A draw's pipeline went to the back of the queue: on the +/// first visit to the world about 1,700 were queued at once (562 of them took +/// over a second each), and with the launcher's 10 s budget every frame waited +/// its whole budget for one that a thousand others stood before, then dropped +/// its draws anyway: 0.35 fps for three and a half minutes (RTX 3080, 8 +/// workers). On by default; `LEONIDA_PIPELINE_AWAIT_FIRST=0`: in the order +/// asked, as before. +fn await_first() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_PIPELINE_AWAIT_FIRST").is_none_or(|v| v != "0")) +} + +/// Moves `p`, asked for and not taken by a worker yet, to the front of its +/// list as a frame begins to wait for it. (A frame waiting again for one +/// already moved or being made does not take the lock.) +fn promote(p: &Pending) { + if p.queue_state.load(Ordering::Relaxed) == REQUESTED { + QUEUE.lock().unwrap_or_else(|e| e.into_inner()).promote(p); + } +} + const NOT_QUEUED: u8 = 0; const EARLY: u8 = 1; const REQUESTED: u8 = 2; -const MAKING: u8 = 3; +/// Requested, and a frame waits for it: at the front of its list, after +/// those awaited before it ([`Queue::promote`]). +const AWAITED: u8 = 3; +const MAKING: u8 = 4; /// How many workers may make pipelines at once that are known to take long /// and that no draw has asked for: a quarter of them. On a fresh cache (a @@ -638,6 +668,36 @@ impl Queue { Some(prev == NOT_QUEUED) } + /// Moves `p` from its place among those asked for to the front, after + /// those awaited before it; whether it moved (not if a worker has it, it + /// is not asked for, or it was moved already). Behind the earlier ones, + /// not before them: with the shared budget their frames' waits have run + /// out, but taking them in turn keeps any from waiting forever. It does + /// not stop a make a worker has begun: the next free worker takes it. + fn promote(&mut self, p: &Pending) -> bool { + if p.queue_state.load(Ordering::Relaxed) != REQUESTED { + return false; + } + let list = if p.screen && screens_first() { + &mut self.screen + } else { + &mut self.requested + }; + let Some(at) = list.iter().position(|q| std::ptr::eq(Arc::as_ptr(q), p)) else { + return false; + }; + let Some(q) = list.remove(at) else { + return false; + }; + q.queue_state.store(AWAITED, Ordering::Relaxed); + let front = list + .iter() + .position(|q| q.queue_state.load(Ordering::Relaxed) != AWAITED) + .unwrap_or(list.len()); + list.insert(front, q); + true + } + fn pop(&mut self, screens_only: bool, slow_limit: usize) -> Option> { // An early entry can have been promoted and claimed already. let unclaimed = |list: &mut VecDeque>| { @@ -930,4 +990,63 @@ mod tests { assert!(queue.pop(true, 1).is_none()); assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &world)); } + + fn in_order(queue: &mut Queue, screens_only: bool, expected: &[&Arc]) { + let made: Vec<_> = std::iter::from_fn(|| queue.pop(screens_only, 1)).collect(); + assert_eq!(made.len(), expected.len()); + for (i, (got, want)) in made.iter().zip(expected).enumerate() { + assert!(Arc::ptr_eq(got, want), "pipeline {i} out of order"); + } + } + + /// A pipeline a frame waits for is made next, before those asked for + /// earlier; those awaited keep their order among themselves. + #[test] + fn an_awaited_pipeline_is_made_before_those_asked_earlier() { + let new = || Arc::new(Pending::new(Vec::new(), None)); + let (a, b, c, d, e) = (new(), new(), new(), new(), new()); + let mut queue = Queue::new(); + for p in [&a, &b, &c, &d] { + assert_eq!(queue.push_as(p, REQUESTED, false), Some(true)); + } + // c, then a, are waited for: they go first, c before a, once each. + assert!(queue.promote(&c)); + assert!(queue.promote(&a)); + assert!(!queue.promote(&a)); + // One a draw has not asked for, or that a worker has, stays where it is. + assert!(!queue.promote(&e)); + assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &c)); + assert!(!queue.promote(&c)); + in_order(&mut queue, false, &[&a, &b, &d]); + } + + #[test] + fn an_awaited_early_pipeline_is_claimed_once() { + let new = || Arc::new(Pending::new(Vec::new(), None)); + let (early, asked) = (new(), new()); + let mut queue = Queue::new(); + assert_eq!(queue.push_as(&early, EARLY, false), Some(true)); + assert_eq!(queue.push_as(&asked, REQUESTED, false), Some(true)); + assert_eq!(queue.push_as(&early, REQUESTED, false), Some(false)); + assert!(queue.promote(&early)); + // Already past asked for: a draw asking again changes nothing. + assert_eq!(queue.push_as(&early, REQUESTED, false), None); + // (The early list's stale entry is passed over.) + in_order(&mut queue, false, &[&early, &asked]); + } + + #[test] + fn an_awaited_pass_over_the_screen_goes_first_among_them() { + let pass = || { + let mut p = Pending::new(Vec::new(), None); + p.screen = true; + Arc::new(p) + }; + let (first, second) = (pass(), pass()); + let mut queue = Queue::new(); + assert_eq!(queue.push(&first, REQUESTED), Some(true)); + assert_eq!(queue.push(&second, REQUESTED), Some(true)); + assert!(queue.promote(&second)); + in_order(&mut queue, true, &[&second, &first]); + } } diff --git a/docs/boot.md b/docs/boot.md index 688d91dd1f..e6fbea5872 100644 --- a/docs/boot.md +++ b/docs/boot.md @@ -90,8 +90,8 @@ fresh name or delete the old one. `LEONIDA_D3D12=vulkan` selects the Vulkan-back traces command lists, resources and pipelines; without it the layer uses the Windows D3D12 device, and the `[d3d12-trace]` lines are only what the Xbox-ABI proxy forwards (device creation, queue, fence and allocator calls), which `boot_trace.py` summarizes without complaint. A run on the Vulkan device prints -`[rt] d3d12: Vulkan device: `; check the log for it (a runtime built without the Vulkan headers accepts the -variable and stays on the Windows device). Keep the traces out of the repository: they can quote whatever the game prints. +`[rt] d3d12: Vulkan device: `; check the log for it (a runtime built without the Vulkan headers stays on the Windows +device and says so in one `[rt] d3d12_xs: LEONIDA_D3D12=vulkan is set, but ...` line). Keep the traces out of the repository: they can quote whatever the game prints. Useful switches: diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 5bd6182ea0..083c91e0d2 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2918,6 +2918,16 @@ Pipeline creation: so they no longer reach `pipeline_cache.session.bin`. `LEONIDA_HEAVY_PIPELINE_CACHE_MS=0` turns the heavy cache off, and with it the `pipelineCreationCacheControl` feature unless `LEONIDA_PIPELINE_COMPILE=cache-only` asks for it. A cache-only create (`cache-only`) is left as it is. + A driver can stop keeping new pipelines once its cache is large, with no error. On NVIDIA 610.88 (RTX 5060 Ti), + a 1.23 GB or 1.35 GB cache came back from `vkGetPipelineCacheData` the same size to the byte after a 2 s compile + (with the 1.35 GB one the next process compiled the pipeline again; a hit then comes only from the driver's own + disk cache), where an empty cache grew ~210 KiB and served the next process in 0.01 s. In the game, seeded with + the 1.23 GB file, 68 of ~110 builds over 200 ms were slow again in the next run; started with no seed, 5 of 164 + were. An older cache of other pipelines stopped growing at 4.9 GB, so the point is not a fixed size. The runtime + takes the cache's size when it creates it and at each session save, counts the title's builds that took at least + 200 ms (a hit takes a few milliseconds), and says once when 16 or more of them compiled while the cache grew by + less than 64 KiB. The remedy is a smaller seed: without `pipeline_cache.bin`, the session file holds only what the + title builds. `LEONIDA_SKIP_COMPUTE=[,...]` (`all`: every compute program) never builds the matching compute programs at play and drops their dispatches, direct and indirect; the first dropped dispatch of each is logged. It is a way past a program that hangs the GPU while the program or its input is fixed, not a fix. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 4bed82a4f3..765b2611a6 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2223,6 +2223,13 @@ if(NOT TARGET Vulkan::Headers) FetchContent_MakeAvailable(VulkanHeaders) endif() endif() +# LEONIDA_D3D12=vulkan asked of a runtime with no Vulkan-backed device (shims/d3d12_backend.h). Outside the block +# below on purpose: a configure without the Vulkan headers is the case it is about. +add_executable(d3d12_backend_test test/d3d12_backend_test.cpp) +if(WIN32 AND MSVC) + target_compile_options(d3d12_backend_test PRIVATE /W4 /permissive- /utf-8) +endif() +add_test(NAME d3d12_backend COMMAND d3d12_backend_test) # The Windows runtime's D3D12 layer needs newer headers than the portable Vulkan tools, so only its builds check. if(TARGET Vulkan::Headers AND WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/vulkan_headers_version.cmake") diff --git a/runtime/shims/d3d12_backend.h b/runtime/shims/d3d12_backend.h new file mode 100644 index 0000000000..7bba99dc51 --- /dev/null +++ b/runtime/shims/d3d12_backend.h @@ -0,0 +1,23 @@ +// Which device D3D12XboxCreateDevice puts behind the Xbox-ABI proxy, as LEONIDA_D3D12 asks (RT-VULKAN-REQUESTED-NOT-BUILT). +// Header only, so the test needs neither a device nor the Vulkan headers. +#pragma once + +#include + +namespace rt::d3d12_xs::backend { + +// LEONIDA_D3D12=vulkan, exactly: the one value that selects the Vulkan-backed device. +inline bool vulkan_requested(const char* value) { return value && std::strcmp(value, "vulkan") == 0; } + +// What to tell the user when the variable asks for the Vulkan-backed device and this runtime has none, else null. +// A runtime configured without the Vulkan headers is built without LEONIDA_VULKAN_DEVICE: it used to take the variable +// without a word and run the title on the host's D3D12 device, which stops somewhere else and looks like a boot result. +inline const char* vulkan_not_built_note(const char* value, bool vulkan_built) { + if (vulkan_built || !vulkan_requested(value)) return nullptr; + return "LEONIDA_D3D12=vulkan is set, but this runtime was built without the Vulkan-backed device (its configure " + "found no Vulkan headers), so the title gets the host's D3D12 device instead. Configure again with " + "VULKAN_SDK set or -DLEONIDA_VULKAN_HEADERS_FETCH=ON; -DLEONIDA_REQUIRE_VULKAN=ON makes a configure " + "without the headers fail"; +} + +} // namespace rt::d3d12_xs::backend diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 79752e5141..e627a29db0 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -148,6 +148,10 @@ struct VulkanDeviceInfo { bool sampler_anisotropy = false; bool sampler_mirror_clamp_to_edge = false; bool sampler_filter_minmax = false; + // VkPhysicalDeviceSamplerFilterMinmaxProperties::filterMinmaxImageComponentMapping. Without it a minimum/maximum + // reduction defines only the R component of a sample, and only through an identity-swizzled view (Vulkan + // specification, Texel Filtering); G, B and A are undefined (D3D-994: Polaris on the AMD Windows driver). + bool sampler_filter_minmax_component_mapping = false; // VK_KHR_calibrated_timestamps or VK_EXT_calibrated_timestamps is enabled on `device` (QueueClock). bool calibrated_timestamps = false; // VK_EXT_conditional_rendering (with its conditionalRendering feature) is enabled: SetPredication works, and diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 54805bf636..1c97dad489 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -2924,6 +2924,41 @@ bool startup_cache_checkpoints_enabled() { } // Writes the session cache at a startup checkpoint or during device teardown. The size cap applies to either write. +// RT-PIPELINE-CACHE-GROWTH-STALL: says once when the title's builds keep compiling but the driver's cache stops +// growing, so the next run would compile them again (pipeline_cache_store::GrowthWatch). The size is taken when the +// cache is created and at every session save, also one over the write limit. +std::mutex& pipeline_cache_growth_mutex() { + static std::mutex mutex; + return mutex; +} + +leonida::pipeline_cache_store::GrowthWatch& pipeline_cache_growth() { + static leonida::pipeline_cache_store::GrowthWatch watch; + return watch; +} + +void note_pipeline_cache_size(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache) { + std::size_t size = 0; + if (!cache || !vk.vkGetPipelineCacheData || vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS) + return; + std::lock_guard lock(pipeline_cache_growth_mutex()); + pipeline_cache_growth().observe(size, leonida::pipeline_profile::compiled_builds().load()); +} + +void report_pipeline_cache_growth(std::size_t size) { + const auto compiled = leonida::pipeline_profile::compiled_builds().load(); + std::lock_guard lock(pipeline_cache_growth_mutex()); + auto& watch = pipeline_cache_growth(); + const std::size_t before = watch.bytes(); + const unsigned long long builds = compiled - watch.compiled(); + if (watch.stalled(size, compiled)) + std::fprintf(stderr, "[rt] d3d12: the Vulkan pipeline cache grew %zu bytes (to %zu) over %llu pipeline builds " + "that compiled: the driver no longer keeps new pipelines, so the next run compiles them " + "again. A large pipeline_cache.bin or pipeline_cache.session.bin can cause it " + "(docs/d3d12_vulkan.md, pipeline caches)\n", + size > before ? size - before : 0, size, builds); +} + void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, bool checkpoint = false, const char* op = nullptr) { if (!cache || !vk.vkGetPipelineCacheData) return; @@ -2934,6 +2969,7 @@ void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDev std::size_t size = 0; if (vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS || size <= sizeof(VkPipelineCacheHeaderVersionOne)) return; + report_pipeline_cache_growth(size); const std::size_t seed = g_offline_seed_bytes.load(std::memory_order_relaxed); if (leonida::pipeline_cache_store::over_save_limit(size, seed, limit)) { std::fprintf(stderr, "[rt] d3d12: pipeline cache is %zu bytes (%zu of them the offline seed), over the " @@ -3788,6 +3824,7 @@ struct DeviceState { else if (!direct_session_cache() && !compile_helper::build_host) pipeline_cache_seeded = merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); } + note_pipeline_cache_size(vk, info.device, pipeline_cache_handle); if (!pipeline_journal_dir().empty()) { char text[32] = {}; size_t length = 0; @@ -13739,6 +13776,10 @@ struct DeviceState { reduction.reductionMode = g::vulkan_reduction_mode(sampler.filter_mode); reduction.pNext = sampler_info.pNext; sampler_info.pNext = &reduction; + if (!info.sampler_filter_minmax_component_mapping) + log_once("minimum/maximum filter sampler without filterMinmaxImageComponentMapping; only R is " + "defined, mode", + int(sampler.filter_mode)); } else { log_once("minimum/maximum filter sampler without samplerFilterMinmax; blended instead, mode", int(sampler.filter_mode)); @@ -31734,6 +31775,13 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin info.sampler_anisotropy = chosen_features.samplerAnisotropy; info.sampler_mirror_clamp_to_edge = chosen12.samplerMirrorClampToEdge; info.sampler_filter_minmax = chosen12.samplerFilterMinmax; + if (info.sampler_filter_minmax) { + VkPhysicalDeviceSamplerFilterMinmaxProperties minmax{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES}; + VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &minmax}; + vkGetPhysicalDeviceProperties2(info.physical, &properties); + info.sampler_filter_minmax_component_mapping = minmax.filterMinmaxImageComponentMapping == VK_TRUE; + } enable12.runtimeDescriptorArray = info.bindless; enable12.descriptorBindingSampledImageUpdateAfterBind = info.bindless; enable12.descriptorBindingStorageImageUpdateAfterBind = info.bindless; diff --git a/runtime/shims/d3d12_xs.cpp b/runtime/shims/d3d12_xs.cpp index a6c7934e44..b584b04076 100644 --- a/runtime/shims/d3d12_xs.cpp +++ b/runtime/shims/d3d12_xs.cpp @@ -20,6 +20,7 @@ #ifdef LEONIDA_VULKAN_DEVICE #include "d3d12_com.h" #endif +#include "d3d12_backend.h" #include "d3d12_trace.h" #include "d3d12_xs_device.h" #include "d3d12_xs_rootsig.h" @@ -198,12 +199,24 @@ HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, cons const bool pc_lists = getenv_s(&lists_length, lists_mode, "LEONIDA_D3D12_LISTS") == 0 && std::strcmp(lists_mode, "pc") == 0; -#ifdef LEONIDA_VULKAN_DEVICE // Opt-in until the Vulkan device covers the first frame: LEONIDA_D3D12=vulkan puts the Vulkan-backed device // behind the same proxy instead of the host's D3D12 device. char backend[16] = {}; size_t backend_length = 0; - if (getenv_s(&backend_length, backend, "LEONIDA_D3D12") == 0 && std::strcmp(backend, "vulkan") == 0) { + const bool backend_read = getenv_s(&backend_length, backend, "LEONIDA_D3D12") == 0; +#ifdef LEONIDA_VULKAN_DEVICE + constexpr bool vulkan_built = true; +#else + constexpr bool vulkan_built = false; +#endif + // A runtime configured without the Vulkan headers has no such device: say so once instead of running the title on + // the host's device as if nothing had been asked. + if (const char* note = rt::d3d12_xs::backend::vulkan_not_built_note(backend_read ? backend : nullptr, vulkan_built)) { + static std::atomic noted{false}; + if (!noted.exchange(true, std::memory_order_relaxed)) std::fprintf(stderr, "[rt] d3d12_xs: %s\n", note); + } +#ifdef LEONIDA_VULKAN_DEVICE + if (backend_read && rt::d3d12_xs::backend::vulkan_requested(backend)) { ID3D12Device* vulkan = nullptr; HRESULT vhr = rt::d3d12::create_vulkan_device_standalone( __uuidof(ID3D12Device), reinterpret_cast(&vulkan), rt::d3d12::QueueTestSettings::ignore); diff --git a/runtime/src/pipeline_cache_store.h b/runtime/src/pipeline_cache_store.h index 5b93d93f03..151ada16e8 100644 --- a/runtime/src/pipeline_cache_store.h +++ b/runtime/src/pipeline_cache_store.h @@ -73,4 +73,42 @@ inline bool header_matches(const void* data, std::size_t size, const cached_pso: std::memcmp(bytes + 16, identity.cache_uuid, sizeof(identity.cache_uuid)) == 0; } +// Whether the driver still keeps the pipelines the title compiles (RT-PIPELINE-CACHE-GROWTH-STALL). A driver can stop +// adding to a large cache without any error. Measured on NVIDIA 610.88 (RTX 5060 Ti): after a 2 s compile, a 1.23 GB +// or 1.35 GB cache came back from vkGetPipelineCacheData the same size to the byte, where an empty cache grew ~210 KiB +// for the same module; an older cache of other pipelines stopped at 4.9 GB, so there is no fixed size to test. +// Instead two sizes of the live cache are compared with the builds that compiled in between (pipeline_profile:: +// compiled_builds): each one adds tens to hundreds of KiB when the driver keeps it. +inline constexpr unsigned long long stalled_after_builds = 16; +inline constexpr std::size_t stalled_below_bytes = std::size_t{64} << 10; // 64 KiB + +class GrowthWatch { +public: + // The cache's size and the compiled-build count when it is created, or at a save. + void observe(std::size_t bytes, unsigned long long compiled) { + bytes_ = bytes; + compiled_ = compiled; + known_ = true; + } + + // At a later size: true once, the first time at least stalled_after_builds builds compiled since the last + // observation while the cache grew by less than stalled_below_bytes. The new size is recorded either way. + bool stalled(std::size_t bytes, unsigned long long compiled) { + const bool stall = known_ && !reported_ && compiled >= compiled_ && compiled - compiled_ >= stalled_after_builds && + bytes < bytes_ + stalled_below_bytes; + if (stall) reported_ = true; + observe(bytes, compiled); + return stall; + } + + std::size_t bytes() const { return bytes_; } + unsigned long long compiled() const { return compiled_; } + +private: + std::size_t bytes_ = 0; + unsigned long long compiled_ = 0; + bool known_ = false; + bool reported_ = false; +}; + } // namespace leonida::pipeline_cache_store diff --git a/runtime/src/pipeline_profile.h b/runtime/src/pipeline_profile.h index f81c00c7de..965d8f5255 100644 --- a/runtime/src/pipeline_profile.h +++ b/runtime/src/pipeline_profile.h @@ -39,23 +39,33 @@ inline long long thread_cpu_us() { return -1; } +// Title pipeline builds that took long enough to have compiled rather than come from the pipeline cache: a cache hit +// takes a few milliseconds, also while the title keeps every core busy. Counted whether or not profiling is on; the +// session cache save compares the count with how much the cache grew (pipeline_cache_store::GrowthWatch). +inline constexpr long long compiled_build_us = 200000; // 200 ms +inline std::atomic& compiled_builds() { + static std::atomic count{0}; + return count; +} + class DriverCall { public: DriverCall(const char* stage, const char* origin, const char* program, const char* fragment = "-", - unsigned unbound = 0) { + unsigned unbound = 0) + : start_(std::chrono::steady_clock::now()) { if (!enabled()) return; static std::atomic sequence{0}; id_ = sequence.fetch_add(1, std::memory_order_relaxed) + 1; - start_ = std::chrono::steady_clock::now(); cpu_start_ = thread_cpu_us(); std::fprintf(stderr, "[rt] pso-driver begin id=%llu unix_ms=%lld stage=%s origin=%s program=%s ps=%s mask=%u\n", id_, unix_ms(), stage, origin, program, fragment, unbound); } void finish(int result) const { - if (!id_) return; const auto us = std::chrono::duration_cast( std::chrono::steady_clock::now() - start_).count(); + if (result == 0 && us >= compiled_build_us) compiled_builds().fetch_add(1, std::memory_order_relaxed); + if (!id_) return; const long long cpu = thread_cpu_us(); std::fprintf(stderr, "[rt] pso-driver end id=%llu unix_ms=%lld us=%lld cpu_us=%lld result=%d\n", id_, unix_ms(), static_cast(us), cpu >= 0 && cpu_start_ >= 0 ? cpu - cpu_start_ : -1, diff --git a/runtime/test/d3d12_backend_test.cpp b/runtime/test/d3d12_backend_test.cpp new file mode 100644 index 0000000000..51c9a1e516 --- /dev/null +++ b/runtime/test/d3d12_backend_test.cpp @@ -0,0 +1,41 @@ +// d3d12_backend.h (RT-VULKAN-REQUESTED-NOT-BUILT): LEONIDA_D3D12=vulkan in a runtime that has no Vulkan-backed device +// gets a note; every other case gets none. CPU only: no device, no Vulkan headers, no game file. +#include "../shims/d3d12_backend.h" + +#include +#include + +namespace backend = rt::d3d12_xs::backend; + +static int failures = 0; +static void check(bool condition, const char* what) { + std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); + if (!condition) ++failures; +} + +int main() { + check(backend::vulkan_requested("vulkan"), "requested: vulkan"); + check(!backend::vulkan_requested(nullptr), "requested: the variable is not set"); + check(!backend::vulkan_requested(""), "requested: an empty value"); + check(!backend::vulkan_requested("Vulkan"), "requested: another case is another value, as the device branch reads it"); + check(!backend::vulkan_requested("vulkan "), "requested: a trailing space is another value"); + check(!backend::vulkan_requested("host"), "requested: another backend name"); + + const char* note = backend::vulkan_not_built_note("vulkan", false); + check(note != nullptr, "note: vulkan asked of a runtime without the device"); + check(note && std::strstr(note, "LEONIDA_D3D12=vulkan") && std::strstr(note, "host's D3D12 device"), + "note: names the variable and the device the title gets"); + check(note && std::strstr(note, "LEONIDA_VULKAN_HEADERS_FETCH") && std::strstr(note, "LEONIDA_REQUIRE_VULKAN") && + std::strstr(note, "VULKAN_SDK"), + "note: names the ways to get the headers and the option that fails the configure"); + + check(backend::vulkan_not_built_note("vulkan", true) == nullptr, "note: none when the device is built in"); + check(backend::vulkan_not_built_note(nullptr, false) == nullptr, "note: none when the variable is not set"); + check(backend::vulkan_not_built_note("", false) == nullptr, "note: none for an empty value"); + check(backend::vulkan_not_built_note("Vulkan", false) == nullptr, + "note: none for a value the Vulkan build would not take either"); + check(backend::vulkan_not_built_note(nullptr, true) == nullptr, "note: none, device built in and nothing asked"); + + std::printf("%d failures\n", failures); + return failures ? 1 : 0; +} diff --git a/runtime/test/d3d12_descriptor_test.cpp b/runtime/test/d3d12_descriptor_test.cpp index 63e4735708..d8e8dbc68a 100644 --- a/runtime/test/d3d12_descriptor_test.cpp +++ b/runtime/test/d3d12_descriptor_test.cpp @@ -340,6 +340,7 @@ int main() { info.bindless_partially_bound = d.partially_bound; info.image_view_min_lod = d.image_view_min_lod; info.sampler_filter_minmax = d.sampler_filter_minmax; + info.sampler_filter_minmax_component_mapping = d.sampler_filter_minmax_component_mapping; info.custom_border_color = d.custom_border_color; info.custom_border_color_without_format = d.custom_border_color_without_format; ID3D12Device* inner = nullptr; @@ -2607,24 +2608,28 @@ int main() { (bc1_props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT) != 0; constexpr std::array want_min{16, 16, 16, 255}; constexpr std::array want_max{240, 240, 240, 255}; + // Without filterMinmaxImageComponentMapping only R of a reduced sample is defined (D3D-994): compare R + // there, all four channels where the device maps every component. + const std::size_t mm_compared = d.sampler_filter_minmax_component_mapping ? 4 : 1; UINT min_matches = 0, max_matches = 0, blend_diff_min = 0, blend_diff_max = 0; for (UINT i = 0; i < texels; ++i) { const auto* got_min = &mm_pixels[0 * bytes + i * 4]; const auto* got_max = &mm_pixels[1 * bytes + i * 4]; const auto* got_blend = &mm_pixels[2 * bytes + i * 4]; if (rgba8_minmax) { - min_matches += std::memcmp(got_min, want_min.data(), 4) == 0; - max_matches += std::memcmp(got_max, want_max.data(), 4) == 0; - blend_diff_min += std::memcmp(got_blend, want_min.data(), 4) != 0; - blend_diff_max += std::memcmp(got_blend, want_max.data(), 4) != 0; + min_matches += std::memcmp(got_min, want_min.data(), mm_compared) == 0; + max_matches += std::memcmp(got_max, want_max.data(), mm_compared) == 0; + blend_diff_min += std::memcmp(got_blend, want_min.data(), mm_compared) != 0; + blend_diff_max += std::memcmp(got_blend, want_max.data(), mm_compared) != 0; } else { min_matches += std::memcmp(got_min, got_blend, 4) == 0; max_matches += std::memcmp(got_max, got_blend, 4) == 0; } } - std::printf("sampler reduction min/max (RGBA8=%s, BC1=%s): min %u/%u, max %u/%u (blend differed: %u/%u vs " - "min, %u/%u vs max)\n", - rgba8_minmax ? "yes" : "no", bc1_minmax ? "yes" : "no", min_matches, texels, max_matches, + std::printf("sampler reduction min/max (RGBA8=%s, BC1=%s, compared %s): min %u/%u, max %u/%u (blend " + "differed: %u/%u vs min, %u/%u vs max)\n", + rgba8_minmax ? "yes" : "no", bc1_minmax ? "yes" : "no", mm_compared == 4 ? "RGBA" : "R only", + min_matches, texels, max_matches, texels, blend_diff_min, texels, blend_diff_max, texels); EXPECT(min_matches == texels && max_matches == texels); if (rgba8_minmax) EXPECT(blend_diff_min == texels && blend_diff_max == texels); diff --git a/runtime/test/pipeline_cache_store_test.cpp b/runtime/test/pipeline_cache_store_test.cpp index 7af94bca62..a1b093191d 100644 --- a/runtime/test/pipeline_cache_store_test.cpp +++ b/runtime/test/pipeline_cache_store_test.cpp @@ -95,7 +95,48 @@ static int test_header() { return 0; } +static int test_growth() { + using store::GrowthWatch; + constexpr auto builds = store::stalled_after_builds; + constexpr auto kept = store::stalled_below_bytes; + // No size at creation: nothing to compare with yet, and the first save becomes the reference. + GrowthWatch fresh; + CHECK(!fresh.stalled(1000, builds * 4)); + CHECK(fresh.stalled(1000, builds * 5)); + // A cache that grows with its builds is fine at any size. + GrowthWatch growing; + growing.observe(std::size_t{1} << 30, 10); + CHECK(!growing.stalled((std::size_t{1} << 30) + kept, 10 + builds)); + CHECK(growing.bytes() == (std::size_t{1} << 30) + kept); + CHECK(growing.compiled() == 10 + builds); + // Too few builds compiled to tell: a few cache-sized misses can be refused for other reasons. + GrowthWatch few; + few.observe(5000, 0); + CHECK(!few.stalled(5000, builds - 1)); + // Enough compiled builds and less than stalled_below_bytes of growth: said once, then never again. + GrowthWatch stuck; + stuck.observe(1346482377, 100); + CHECK(stuck.stalled(1346482377 + kept - 1, 100 + builds)); + CHECK(!stuck.stalled(1346482377 + kept - 1, 100 + builds * 3)); + // Builds and growth are counted from the previous save: growth then, none now. + GrowthWatch interval; + interval.observe(2000, 0); + CHECK(!interval.stalled(2000 + kept * 8, builds * 3)); + CHECK(interval.stalled(2000 + kept * 8, builds * 4)); + // Too few builds at one save still moves the reference to that save. + GrowthWatch moved; + moved.observe(2000, 0); + CHECK(!moved.stalled(2000, builds - 1)); + CHECK(moved.stalled(2000, builds * 2 - 1)); + // A count that went backwards (a second device's counter view) is not read as a huge number of builds. + GrowthWatch backwards; + backwards.observe(3000, 50); + CHECK(!backwards.stalled(3000, 10)); + return 0; +} + int main() { if (const int failed = test_limit()) return failed; - return test_header(); + if (const int failed = test_header()) return failed; + return test_growth(); } diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 96357d3256..ef75b76221 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -103,6 +103,7 @@ class Device { bool partially_bound = false; // and its slots can stay empty bool image_view_min_lod = false; bool sampler_filter_minmax = false; + bool sampler_filter_minmax_component_mapping = false; // filterMinmaxImageComponentMapping (D3D-994) bool vertex_attribute_divisor = false; bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled bool storage_image_extended_formats = false; // typed r8ui storage images @@ -460,6 +461,13 @@ class Device { enable12.descriptorBindingPartiallyBound = partially_bound; sampler_filter_minmax = features12.samplerFilterMinmax == VK_TRUE; enable12.samplerFilterMinmax = sampler_filter_minmax; + if (sampler_filter_minmax) { + VkPhysicalDeviceSamplerFilterMinmaxProperties minmax{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES}; + VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &minmax}; + instance_fn("vkGetPhysicalDeviceProperties2")(physical, &properties); + sampler_filter_minmax_component_mapping = minmax.filterMinmaxImageComponentMapping == VK_TRUE; + } shader_output_viewport_index = features12.shaderOutputViewportIndex == VK_TRUE; enable12.shaderOutputViewportIndex = shader_output_viewport_index; vulkan_memory_model = features12.vulkanMemoryModel == VK_TRUE;