diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index c58e527..b6fa38c 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -158,6 +158,8 @@ pub fn run( } let exe_name = exe.file_name().unwrap_or_default().to_string_lossy(); show(&exe_name, image.bind_imports(&with_dlls, policy)?); + #[cfg(windows)] + apply_patches(image.base()); if !execute { println!("not executing (pass --execute to start the title)"); return Ok(0); @@ -514,3 +516,88 @@ mod tests { pub fn run(_: &Path, _: Unimplemented, _: bool, _: bool, _: Console, _: &[String]) -> Result { anyhow::bail!("running titles requires Windows") } + + +/// Local build (techniques from Palmwave, an XCL fork, for Grand Theft Auto VI 1.0.2.1): patches +/// of the title's code in memory (the file is never touched), each written only where the bytes +/// it expects are found, so another build of the title is left alone. +/// `VICTORY_PATCH=:=;...` adds patches; `VICTORY_PATCH_DEFAULTS=0` +/// drops the built-in ones (`VICTORY_PATCH_SKIP=,...` drops some of them, by number). +#[cfg(windows)] +fn apply_patches(base: usize) { + #[link(name = "kernel32")] + unsafe extern "system" { + fn VirtualProtect(address: *const core::ffi::c_void, size: usize, protect: u32, old: *mut u32) -> i32; + } + const PAGE_EXECUTE_READWRITE: u32 = 0x40; + // (number, rva, expected, new, what) + const DEFAULTS: [(u32, usize, &str, &str, &str); 10] = [ + (1, 0x2215bdc, "732e", "9090", "hang detector"), + (2, 0x2215c70, "7404", "9090", "hang detector"), + (3, 0x2215d84, "7404", "9090", "hang detector"), + (4, 0x22a3b5, "e8a6f7ffff", "31c0909090", "indirect diffuse / stochastic reflection pass"), + (5, 0x22aee6, "e875ecffff", "31c0909090", "indirect diffuse / stochastic reflection pass"), + (6, 0x7b4e6a, "8b8944010000", "b90100000090", "world render resolution mode"), + (7, 0x25d2fe2, "e819a4ffff", "0f1f440000", "alpha-resolve blur / scattering / ray-marched gather"), + (8, 0x327b92e, "7408", "9090", "alpha-resolve blur / scattering / ray-marched gather"), + (9, 0x125912d, "e85ef50102", "0f1f440000", "alpha-resolve blur / scattering / ray-marched gather"), + (10, 0x5267747, "0f84ae050000", "0f8432050000", "audio lock stop after ~2 minutes"), + ]; + let hex = |s: &str| -> Option> { + let s = s.trim(); + (s.len() % 2 == 0).then_some(())?; + (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok()).collect() + }; + let mut skip: Vec = std::env::var("VICTORY_PATCH_SKIP") + .unwrap_or_default() + .split(',') + .filter_map(|n| n.trim().parse().ok()) + .collect(); + // Patches 4, 5 and 7-9 switch off the title's lighting passes (indirect + // diffuse, scattering, ray-marched gather): with them interiors came out + // black (run vu14 against vu15). Only with VICTORY_PATCH_HEAVY=1. + if std::env::var("VICTORY_PATCH_HEAVY").map_or(true, |v| v.trim() != "1") { + skip.extend([4, 5, 7, 8, 9]); + } + let mut list: Vec<(String, usize, Vec, Vec)> = Vec::new(); + if std::env::var("VICTORY_PATCH_DEFAULTS").map_or(true, |v| v.trim() != "0") { + for (n, rva, old, new, what) in DEFAULTS { + if !skip.contains(&n) { + list.push((format!("{n} ({what})"), rva, hex(old).unwrap(), hex(new).unwrap())); + } + } + } + for entry in std::env::var("VICTORY_PATCH").unwrap_or_default().split(';').filter(|e| !e.trim().is_empty()) { + let parsed = (|| { + let (rva, rest) = entry.split_once(':')?; + let (old, new) = rest.split_once('=')?; + let rva = usize::from_str_radix(rva.trim().trim_start_matches("0x"), 16).ok()?; + Some((rva, hex(old)?, hex(new)?)) + })(); + match parsed { + Some((rva, old, new)) if old.len() == new.len() => list.push((entry.trim().to_string(), rva, old, new)), + _ => println!("patch ignored (bad syntax): {entry}"), + } + } + for (name, rva, old, new) in list { + let at = base + rva; + // SAFETY: an address inside the title's image, which we mapped; read and written + // only after checking the expected bytes, with the page made writable for the write. + unsafe { + let here = std::slice::from_raw_parts(at as *const u8, old.len()); + if here != old.as_slice() { + println!("patch {name}: not applied (bytes differ: another build?)"); + continue; + } + let mut prot = 0u32; + if VirtualProtect(at as *const _, new.len(), PAGE_EXECUTE_READWRITE, &mut prot) == 0 { + println!("patch {name}: not applied (page protection)"); + continue; + } + std::ptr::copy_nonoverlapping(new.as_ptr(), at as *mut u8, new.len()); + let mut back = 0u32; + VirtualProtect(at as *const _, new.len(), prot, &mut back); + println!("patch {name}: applied at +{rva:#x}"); + } + } +} diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index c23217c..f9d9e87 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1052,6 +1052,8 @@ impl State { #[cfg(feature = "diagnostics")] list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true)); #[cfg(feature = "diagnostics")] + self.trace_dispatch(&p.name, x, y, z); + #[cfg(feature = "diagnostics")] self.probe_small(list, true); // SAFETY: an open list with everything set. unsafe { list.list.Dispatch(x, y, z) }; @@ -1340,11 +1342,11 @@ impl State { let targets: Vec = self .targets .iter() - .filter_map(|&t| crate::resource::host_resource(t as This)) - .map(|t| { + .filter_map(|&t| { + let res = crate::resource::host_resource(t as This)?; // SAFETY: a live resource. - let d = unsafe { t.GetDesc() }; - format!("{}x{} f{}", d.Width, d.Height, d.Format.0) + let d = unsafe { res.GetDesc() }; + Some(format!("{t:#x} {}x{} f{}", d.Width, d.Height, d.Format.0)) }) .collect(); let v = self.vertex[0]; @@ -1366,6 +1368,22 @@ impl State { } } + /// Dispatches in listed frames, at debug level: their pipeline, shaders, + /// and what they read and write (diagnostics builds). + #[cfg(feature = "diagnostics")] + fn trace_dispatch(&self, shaders: &str, x: u32, y: u32, z: u32) { + if !tracing::enabled!(tracing::Level::DEBUG) + || !crate::capture::listed(crate::queue::presented() + 1) + { + return; + } + tracing::debug!( + "dispatch {x}x{y}x{z} pipeline {:#x} {shaders} reads {:?}", + self.pipeline, + self.reads(true) + ); + } + /// In a listed frame: each small buffer (64 bytes at most) the draw's /// tables name, as title memory now and as its host copy when the list /// is submitted (before the GPU runs it) and after it has run. @@ -1505,6 +1523,15 @@ impl State { }); text } + (RootType::Descriptor, Some(Root::View(address))) => { + let rw = match u.kind { + ResourceType::Uav => "uav", + ResourceType::Srv => "srv", + ResourceType::Cbv => "cbv", + _ => "view", + }; + format!("{rw} root {address:#x}") + } (root, _) => format!("{root:?}"), }; out.push(format!( @@ -1936,18 +1963,33 @@ fn describe(view: Option<&View>) -> String { }; match view { None => "no view".into(), - Some(v @ View::Shader(r, _)) => texture(*r as This).unwrap_or_else(|| { - let range = crate::descriptor::host::buffer_range(v); - format!("buffer {range:?}{}", small(range)) - }), - // A buffer has no host texture: its title range, as for a shader view. - Some(v @ View::Unordered(r, ..)) => texture(*r as This).map_or_else( - || { - let range = crate::descriptor::host::buffer_range(v); - format!("uav buffer {range:?}{}", small(range)) - }, - |t| format!("uav {t}"), - ), + Some(v @ (View::Shader(r, _) | View::Unordered(r, ..))) => { + let kind = if matches!(v, View::Unordered(..)) { + "uav" + } else { + "srv" + }; + match texture(*r as This) { + Some(t) => format!("{kind} {r:#x} {t}"), + None => { + let range = crate::descriptor::host::buffer_range(v); + match range { + Some((at, len)) => { + format!("{kind} {r:#x} buffer {at:#x}+{len}{}", small(range)) + } + None => { + let mem = crate::resource::texture_memory(*r as This) + .map_or(0, |(p, _)| p as u64); + if mem != 0 { + format!("{kind} {r:#x} mem {mem:#x}") + } else { + format!("{kind} {r:#x}") + } + } + } + } + } + } Some(View::Placed(u, r, d)) => format!( "placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}", r[0], @@ -2809,6 +2851,34 @@ void main() { // SAFETY: plain device query. assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); } + + #[cfg(feature = "diagnostics")] + #[test] + fn describe_includes_kind_and_resource_address() { + assert_eq!(describe(None), "no view"); + assert_eq!(describe(Some(&View::Shader(0, None))), "srv 0x0"); + assert_eq!(describe(Some(&View::Unordered(0, 0, None))), "uav 0x0"); + + let buf = buffer(256); + let (addr, _) = crate::resource::buffer_bytes(buf).unwrap(); + let addr = addr as u64; + // Raw buffer SRV and UAV (format R32_TYPELESS=39, dim BUFFER=1, raw flag=1). + let srv_words = [39, 1, 0x1688, 0, 0, 0, 64, 0, 1, 0]; + let uav_words = [39, 1, 0, 0, 64, 0, 0, 0, 1, 0]; + let srv = describe(Some(&View::Shader(buf as usize, Some(srv_words)))); + let uav = describe(Some(&View::Unordered(buf as usize, 0, Some(uav_words)))); + assert_eq!(srv, format!("srv {:#x} buffer {addr:#x}+256", buf as usize)); + assert_eq!(uav, format!("uav {:#x} buffer {addr:#x}+256", buf as usize)); + + if crate::host::host().is_some() { + let mem = title_memory(1 << 20); + let tex = texture_at_address(mem, &texture_words(64, 64, 28, 0x105, 4)); + let tex_srv = describe(Some(&View::Shader(tex as usize, None))); + let tex_uav = describe(Some(&View::Unordered(tex as usize, 0, None))); + assert!(tex_srv.starts_with(&format!("srv {:#x} 64x64 ", tex as usize)), "{tex_srv}"); + assert!(tex_uav.starts_with(&format!("uav {:#x} 64x64 ", tex as usize)), "{tex_uav}"); + } + } } #[cfg(all(test, feature = "diagnostics"))] diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index cd613c4..86dd2e4 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -91,6 +91,39 @@ struct Layout { owner: Vec>, } +/// `VICTORY_SPARSE_PAGE_BITMAP=0` restores the original bitmap scans. +fn sparse_page_bitmap() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| !std::env::var("VICTORY_SPARSE_PAGE_BITMAP").is_ok_and(|v| v.trim() == "0")) +} + +impl Layout { + /// Whether any mark names a missing page or a region with no block. + fn has_misses(&self, marks: &[u32], sparse: bool) -> bool { + let is_missing = |entry: usize| { + entry / BLOCK == 0 + || entry / BLOCK >= self.blocks.len() + || self.owner.get(entry).is_none_or(Option::is_none) + }; + if sparse { + for (w, &mark) in marks.iter().enumerate() { + let mut bits = mark; + while bits != 0 { + let entry = w * 32 + bits.trailing_zeros() as usize; + if is_missing(entry) { + return true; + } + bits &= bits - 1; + } + } + return false; + } + marks.iter().enumerate().any(|(w, &mark)| { + (0..32).filter(|b| mark >> b & 1 != 0).any(|b| is_missing(w * 32 + b)) + }) + } +} + /// A view heap's page table, shared by every list using title memory with /// the heap bound, and the view pairs of the copies it names. struct Shared { @@ -395,12 +428,7 @@ pub(crate) fn bind(list: &HostList, key: usize) -> Option { let l = layout(key); // SAFETY: the bitmap is mapped and the list's run is over. let marks = unsafe { std::slice::from_raw_parts(data as *const u32, words) }; - marks.iter().enumerate().any(|(w, &mark)| { - (0..32).filter(|b| mark >> b & 1 != 0).any(|b| { - let entry = w * 32 + b; - entry / BLOCK == 0 || l.blocks.get(entry / BLOCK).is_none() || l.owner.get(entry).is_none_or(|o| o.is_none()) - }) - }) + l.has_misses(marks, sparse_page_bitmap()) }); list.defer_after(move || { let Layout { copies, blocks, owner } = &*layout(key); @@ -412,7 +440,11 @@ pub(crate) fn bind(list: &HostList, key: usize) -> Option { let marks = unsafe { std::slice::from_raw_parts_mut(data as *mut u32, words) }; let (mut pages, mut regions, mut missed) = (0, 0, Vec::new()); let mut writes = Vec::new(); + let sparse = sparse_page_bitmap(); for (w, mark) in marks.iter_mut().enumerate() { + if sparse && *mark == 0 { + continue; + } let mut bits = std::mem::take(mark); while bits != 0 { let entry = w * 32 + bits.trailing_zeros() as usize; @@ -472,6 +504,68 @@ pub(crate) fn bind(list: &HostList, key: usize) -> Option { mod tests { use super::*; + #[test] + fn sparse_page_bitmap_matches_named_pages_and_misses() { + let mut layout = Layout { + blocks: vec![usize::MAX, 1, 2], + owner: vec![Some(0); 3 * BLOCK - 1], + ..Layout::default() + }; + layout.owner[2 * BLOCK + 32] = None; + for (entries, expected) in [ + (vec![], false), + (vec![BLOCK + 31, 2 * BLOCK + 31], false), + (vec![BLOCK + 1, 2 * BLOCK + 32], true), + (vec![31, BLOCK + 31], true), + (vec![3 * BLOCK - 1], true), + (vec![3 * BLOCK + 33], true), + ] { + let mut marks = vec![0; (4 * BLOCK) / 32]; + for entry in entries { + marks[entry / 32] |= 1 << (entry % 32); + } + assert_eq!(layout.has_misses(&marks, false), expected); + assert_eq!(layout.has_misses(&marks, true), expected); + } + } + + #[test] + #[ignore = "offline performance benchmark"] + fn sparse_page_bitmap_benchmark() { + use std::hint::black_box; + use std::time::Instant; + + let layout = Layout { + blocks: vec![0; 33], + owner: vec![Some(0); 33 * BLOCK], + ..Layout::default() + }; + let mut marks = vec![0; ((CAPACITY + 1) * BLOCK) / 32]; + for entry in (BLOCK..33 * BLOCK).step_by(1021) { + marks[entry / 32] |= 1 << (entry % 32); + } + for (label, first) in [("all pages named", 0), ("early region miss", 8)] { + marks[0] = first; + let mut times = [Vec::new(), Vec::new()]; + for sample in 0..10 { + for mode in [sample % 2, 1 - sample % 2] { + let start = Instant::now(); + for _ in 0..40 { + black_box(layout.has_misses(black_box(&marks), mode != 0)); + } + if sample > 0 { + times[mode].push(start.elapsed()); + } + } + } + for samples in &mut times { + samples.sort_unstable(); + } + let medians = times.map(|s| s[s.len() / 2].as_secs_f64() * 1e6 / 40.0); + println!("{label}: {:.2} us per original scan, {:.2} us sparse", medians[0], medians[1]); + } + } + /// The shader's lookup (`victory_shader` lowering) over a table's /// dwords: the view index and the byte offset in that view. fn look_up(dwords: &[u32], address: u64) -> (u32, u32) { diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index 4cc5dd8..370451f 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -35,11 +35,19 @@ use windows::core::{HSTRING, Interface, PCWSTR}; static DIR: OnceLock = OnceLock::new(); -/// Keeps the pipeline library and the early list in `dir` from now on. +/// Keeps the pipeline library and the early list in a per-build subfolder of +/// `dir` from now on, so builds with different translators, root signatures, +/// or pipeline descriptions never mix `host-pipelines.bin`. pub fn use_pipeline_cache(dir: PathBuf) { + let dir = build_dir(dir); + tracing::info!(dir = %dir.display(), "pipeline cache"); let _ = DIR.set(dir); } +fn build_dir(dir: PathBuf) -> PathBuf { + dir.join(format!("build-{}", &tag(&[])[..16])) +} + /// Host pipelines created, loaded from the library, and title pipelines /// started at creation, since the start. pub(crate) static MADE: AtomicU64 = AtomicU64::new(0); @@ -195,6 +203,7 @@ fn tag(blob: &[u8]) -> String { translator, include_bytes!("../shader_cache.rs"), &limit, + include_bytes!("../pipeline.rs"), include_bytes!("host.rs"), include_bytes!("library.rs"), ] { @@ -558,4 +567,13 @@ mod tests { assert_eq!(final_bytes.len(), 4096); assert!(final_bytes.iter().all(|&b| b == final_bytes[0])); } + + #[test] + fn build_dir_scopes_library_per_build_fingerprint() { + let dir = build_dir(PathBuf::from("pipelines")); + let name = dir.file_name().unwrap().to_str().unwrap(); + assert!(name.starts_with("build-")); + assert_eq!(name.len(), "build-".len() + 16); + assert_eq!(name, format!("build-{}", &tag(&[])[..16])); + } } diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 04a93ed..47e88a0 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -222,7 +222,9 @@ impl Written { Written::GpuTimestamp => { static START: std::sync::OnceLock = std::sync::OnceLock::new(); let elapsed = START.get_or_init(std::time::Instant::now).elapsed(); - (elapsed.as_nanos() / (1_000_000_000 / u128::from(TIMESTAMP_FREQUENCY))) as u64 + let real = + (elapsed.as_nanos() / (1_000_000_000 / u128::from(TIMESTAMP_FREQUENCY))) as u64; + gpu_clock(real) } Written::SystemTimestamp => system_timestamp(), }; @@ -237,6 +239,50 @@ impl Written { } } +fn parse_clock_scale(clock: Option<&str>, scale: Option<&str>) -> u64 { + if clock.is_some_and(|v| v.trim() == "real") { + return 1; + } + scale + .and_then(|v| v.trim().parse().ok()) + .filter(|&n: &u64| n >= 1) + .unwrap_or(16) +} + +fn scale_clock(last: &AtomicU64, real: u64, scale: u64) -> u64 { + if scale == 1 { + return real; + } + // Strictly increasing, so two timestamps of one frame never read equal. + let want = real / scale; + let mut prev = last.load(Ordering::Relaxed); + loop { + let next = want.max(prev + 1); + match last.compare_exchange_weak(prev, next, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => return next, + Err(now) => prev = now, + } + } +} + +/// Local build: the GPU clock titles read. Our GPU work runs on the CPU's timeline (copies, +/// waits), so the real clock tells Grand Theft Auto VI its GPU takes ~500 ms a frame and its +/// dynamic resolution drops to the minimum (a pixelated picture). `VICTORY_GPU_CLOCK=scaled` +/// (default) runs the clock `VICTORY_GPU_CLOCK_SCALE` (default 16) times slower than real time, +/// so the same work measures 16 times shorter while time still moves forward; +/// `VICTORY_GPU_CLOCK=real` keeps the real clock. +fn gpu_clock(real: u64) -> u64 { + static SCALE: std::sync::OnceLock = std::sync::OnceLock::new(); + static LAST: AtomicU64 = AtomicU64::new(0); + let scale = *SCALE.get_or_init(|| { + parse_clock_scale( + std::env::var("VICTORY_GPU_CLOCK").ok().as_deref(), + std::env::var("VICTORY_GPU_CLOCK_SCALE").ok().as_deref(), + ) + }); + scale_clock(&LAST, real, scale) +} + fn system_timestamp() -> u64 { #[cfg(windows)] { @@ -609,4 +655,20 @@ mod tests { Written::GpuTimestamp.write(at[1..].as_mut_ptr().cast(), 8); assert!(at[1] > first); } + + #[test] + fn gpu_clock_scales_and_stays_strictly_increasing() { + assert_eq!(parse_clock_scale(None, None), 16); + assert_eq!(parse_clock_scale(Some("real"), Some("32")), 1); + assert_eq!(parse_clock_scale(Some("scaled"), Some("8")), 8); + assert_eq!(parse_clock_scale(None, Some("0")), 16); + assert_eq!(parse_clock_scale(None, Some("bad")), 16); + + let last = AtomicU64::new(0); + assert_eq!(scale_clock(&last, 160, 16), 10); + assert_eq!(scale_clock(&last, 160, 16), 11); + assert_eq!(scale_clock(&last, 165, 16), 12); + assert_eq!(scale_clock(&last, 1600, 16), 100); + assert_eq!(scale_clock(&last, 500, 1), 500); + } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index d914c95..e81e2a3 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -16,7 +16,7 @@ //! themselves, every buffer range the heap's views reach //! (`crate::bindless`). -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashSet}; use std::sync::atomic::AtomicU32; use std::sync::{Arc, Mutex}; @@ -50,8 +50,11 @@ pub(crate) struct Shadow { before: Mutex, } -/// Snapshot segments (offset, bytes) and the pieces compared. -type Snapshot = (Vec<(usize, Vec)>, std::collections::HashSet); +/// Disjoint snapshot segments (offset, bytes), in order. +type Segments = Vec<(usize, Vec)>; + +/// A snapshot and the pieces already compared. +type Snapshot = (Segments, HashSet); /// Snapshot memory kept for reuse (already touched, so no page faults). static POOL: Mutex>> = Mutex::new(Vec::new()); @@ -97,6 +100,179 @@ fn give_back(v: Vec) { /// Snapshot memory kept for reuse. const POOL_BYTES: usize = 2 << 30; +/// `VICTORY_INCREMENTAL_SNAPSHOTS=0` uses the original coalesced snapshots. +fn incremental_snapshots() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| !std::env::var("VICTORY_INCREMENTAL_SNAPSHOTS").is_ok_and(|v| v.trim() == "0")) +} + +/// Saves each newly covered byte once. Existing bytes must keep their first +/// value, even if the mapped copy has since been refreshed elsewhere. +fn snapshot_gaps<'a>( + segments: &mut Segments, + mut from: usize, + to: usize, + host: impl Fn(usize, usize) -> &'a [u8], +) -> usize { + let mut i = segments.partition_point(|(at, bytes)| at + bytes.len() <= from); + let mut copied = 0; + while from < to { + let end = match segments.get(i) { + Some((at, bytes)) if *at <= from => { + from = at + bytes.len(); + i += 1; + continue; + } + Some((at, _)) => to.min(*at), + None => to, + }; + let mut bytes = pooled(end - from); + bytes.extend_from_slice(host(from, end)); + segments.insert(i, (from, bytes)); + copied += end - from; + from = end; + i += 1; + } + copied +} + +fn snapshot_coalesced<'a>( + segments: &mut Segments, + from: usize, + to: usize, + host: impl Fn(usize, usize) -> &'a [u8], +) -> usize { + let first = segments.partition_point(|(at, bytes)| at + bytes.len() < from); + let last = first + segments[first..].iter().take_while(|(at, _)| *at <= to).count(); + if let [(at, bytes)] = &segments[first..last] + && *at <= from + && to <= at + bytes.len() + { + return 0; + } + let start = segments.get(first).filter(|_| first < last).map_or(from, |s| s.0.min(from)); + let end = segments[first..last].last().map_or(to, |(at, bytes)| (at + bytes.len()).max(to)); + let mut grown = pooled(end - start); + let mut at = start; + for (taken, bytes) in segments.drain(first..last) { + grown.extend_from_slice(host(at, taken)); + grown.extend_from_slice(&bytes); + at = taken + bytes.len(); + give_back(bytes); + } + grown.extend_from_slice(host(at, end)); + segments.insert(first, (start, grown)); + end - start +} + +/// Finds the consecutive snapshot segments covering the entire interval. +fn snapshot_cover( + segments: &[(usize, Vec)], + from: usize, + to: usize, +) -> Option<&[(usize, Vec)]> { + let start = segments.partition_point(|(at, bytes)| at + bytes.len() <= from); + let mut covered = from; + for (i, (at, bytes)) in segments[start..].iter().enumerate() { + if *at > covered { + return None; + } + covered = at + bytes.len(); + if covered >= to { + return Some(&segments[start..=start + i]); + } + } + None +} + +/// A covered page usually lies in one segment. Assemble just that page when +/// it crosses a snapshot boundary, so copy-back still merges one page at a time. +fn snapshot_piece<'a>( + segments: &'a [(usize, Vec)], + from: usize, + n: usize, + scratch: &'a mut Vec, +) -> &'a [u8] { + let (start, bytes) = &segments[0]; + if let Some(bytes) = bytes.get(from - start..from - start + n) { + return bytes; + } + scratch.clear(); + let to = from + n; + for (at, bytes) in segments { + let end = (at + bytes.len()).min(to); + scratch.extend_from_slice(&bytes[from.saturating_sub(*at)..end - at]); + if end == to { + break; + } + } + scratch +} + +/// Start parallel scans at 32 MiB of unchecked full pages. +const PAGES_PER_WORKER: usize = (16 << 20) / PAGE; + +/// `VICTORY_PARALLEL_COPY_BACK=0` compares every page on the submit thread. +fn copy_back_workers() -> usize { + static WORKERS: std::sync::OnceLock = std::sync::OnceLock::new(); + *WORKERS.get_or_init(|| { + if std::env::var("VICTORY_PARALLEL_COPY_BACK").is_ok_and(|v| v.trim() == "0") { + 1 + } else { + std::thread::available_parallelism().map_or(1, |n| (n.get() / 2).clamp(1, 4)) + } + }) +} + +/// Known full pages in copy order, with whether their snapshot differs. +type PageChanges = Vec<(usize, bool)>; + +fn scan_pages( + data: &[u8], + from: usize, + before: &[(usize, Vec)], + pages: &mut [(usize, bool)], + workers: usize, +) { + let scan = |batch: &mut [(usize, bool)]| { + let mut segment = before; + let mut scratch = Vec::new(); + for (at, changed) in batch { + while segment[0].0 + segment[0].1.len() <= *at { + segment = &segment[1..]; + } + let host = &data[*at - from..*at - from + PAGE]; + *changed = host != snapshot_piece(segment, *at, PAGE, &mut scratch); + } + }; + if pages.is_empty() { + return; + } + let workers = workers.min((pages.len() / PAGES_PER_WORKER).max(1)); + if workers == 1 { + scan(pages); + return; + } + let chunk = pages.len().div_ceil(workers); + let started = std::thread::scope(|scope| { + let mut batches = pages.chunks_mut(chunk); + let first = batches.next().expect("pages are nonempty"); + let mut started = true; + for batch in batches { + let task = std::thread::Builder::new().spawn_scoped(scope, || scan(batch)); + if task.is_err() { + started = false; + break; + } + } + scan(first); + started + }); + if !started { + scan(pages); + } +} + // SAFETY: D3D12 resources are free-threaded; `data` is a persistent mapping // written only on the submitting thread. unsafe impl Send for Shadow {} @@ -187,18 +363,21 @@ impl Shadow { // SAFETY: inside the mapping; only the submitting thread writes it. let host = unsafe { std::slice::from_raw_parts(self.data.add(from - start), n) }; let mut title = vec![0u8; n]; - if !crate::host::read_into(from as *const u8, &mut title) || title == host { + if !crate::host::read_into(from as *const u8, &mut title) { return 0; } - { - let _writing = crate::watch::writing(from, n); - crate::host::write_mapped(from as *mut u8, host.as_ptr(), n); + let mut runs = Vec::new(); + changed_runs(host, &title, &mut runs); + if runs.is_empty() { + return 0; } + let mut writable = Writable::default(); + let written = write_runs(from, n, host, &runs, &mut writable, back_mode()); // Our write is not the title's: the copy holds the page as it is. if let Some(t) = &self.tracked { t.taken(&[page / PAGE]); } - n + written } /// Brings `len` bytes at `address` up to date when `list` is submitted, @@ -245,11 +424,10 @@ impl Shadow { /// At submission, after the range's refresh: a submitted list's shaders /// write this range. Its bytes are kept to tell later what the GPU wrote: - /// per copy and submission, segments covering the ranges the submission - /// declares (the world declares overlapping views of its 174 MB heap - /// dozens of times; one segment over all of them copied most of the - /// heap), in reused memory (fresh snapshots cost ~2.3 million page - /// faults per world frame). + /// per copy and submission, bytes from only the declared ranges, in + /// reused memory (fresh snapshots cost ~2.3 million page faults per + /// world frame). In the world, many overlapping views extend the saved + /// range of the same 174 MB heap. pub(crate) fn writing(&self, address: usize, len: usize) { self.pending .lock() @@ -262,35 +440,19 @@ impl Shadow { // SAFETY: inside the mapping. let host = |a: usize, b: usize| unsafe { std::slice::from_raw_parts(self.data.add(a), b - a) }; let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); - let segments = &mut before.0; - // The segments the range overlaps or touches. - let first = segments.partition_point(|(at, bytes)| at + bytes.len() < from); - let last = first + segments[first..].iter().take_while(|(at, _)| *at <= to).count(); - if let [(at, bytes)] = &segments[first..last] - && *at <= from - && to <= at + bytes.len() - { - return; - } - let start = segments.get(first).filter(|_| first < last).map_or(from, |s| s.0.min(from)); - let end = segments[first..last].last().map_or(to, |(at, bytes)| (at + bytes.len()).max(to)); #[cfg(feature = "diagnostics")] let _timed = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::SnapshotUs); + let copied = if incremental_snapshots() { + snapshot_gaps(&mut before.0, from, to, host) + } else { + snapshot_coalesced(&mut before.0, from, to, host) + }; #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::SnapshotBytes, (end - start) as u64); - #[cfg(feature = "diagnostics")] - crate::copystat::snapshot(self.start, self.len, (end - start) as u64); - // Parts newly covered from the copy, the rest as it was taken. - let mut grown = pooled(end - start); - let mut at = start; - for (taken, bytes) in segments.drain(first..last) { - grown.extend_from_slice(host(at, taken)); - grown.extend_from_slice(&bytes); - at = taken + bytes.len(); - give_back(bytes); + if copied != 0 { + crate::copystat::add(crate::copystat::C::SnapshotBytes, copied as u64); + crate::copystat::snapshot(self.start, self.len, copied as u64); } - grown.extend_from_slice(host(at, end)); - segments.insert(first, (start, grown)); + let _ = copied; } /// After the submission ran: copies the bytes its shaders wrote back @@ -317,52 +479,63 @@ impl Shadow { let mut written = 0; let (from, to) = self.inside(address, len); let start = self.start as usize; - if let Some((taken, before)) = segments.iter().find(|(at, bytes)| *at <= from && to <= at + bytes.len()) - && back + if back && from < to + && let Some(mut before) = snapshot_cover(segments, from, to) { - let before = &before[from - taken..to - taken]; #[cfg(feature = "diagnostics")] let _timed = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::CompareUs); - // By 64 KiB piece: the copy compared with its bytes before the - // submission, title memory read only where the GPU wrote. - const PIECE: usize = 64 << 10; - let mut title = vec![0u8; PIECE]; + let scanned = self.scan_copy_back(from, to, before, compared); + let mut scanned = scanned.map(Vec::into_iter); + // By page: title memory is read only where the copy differs + // from its snapshot. Read and write those pages in order. + let mut old_piece = Vec::new(); + let mut title = Vec::new(); + let mut runs = Vec::new(); + let mut writable = Writable::default(); + let mode = back_mode(); let mut synced = Vec::new(); let mut at = from; while at < to { - let n = (PIECE - (start + at) % PIECE).min(to - at); - // SAFETY: inside the mapping; only the submitting thread - // writes it. - let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; - let old = &before[at - from..at - from + n]; - let title = &mut title[..n]; + let n = (PAGE - (start + at) % PAGE).min(to - at); // A whole piece is compared once per submission, whichever // declared ranges overlap it: then what the GPU wrote there // went back. - if n == PIECE && !compared.insert(start + at) { + if n == PAGE && !compared.insert(start + at) { at += n; continue; } #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::CompareBytes, n as u64); - if host != old && crate::host::read_into((start + at) as *const u8, title) { - // Title memory with the GPU's bytes put in; the copy - // takes the title's bytes in turn. - let mut changed = false; - for ((t, h), o) in title.iter_mut().zip(host.iter_mut()).zip(old) { - if *h != *o && *t != *h { - *t = *h; - changed = true; - } - *h = *t; + let mut known_changed = false; + if n == PAGE + && let Some(scan) = &mut scanned + { + let (page, changed) = scan.next().expect("matches the unchecked pages"); + debug_assert_eq!(page, at); + if !changed { + at += n; + continue; } - if changed { - let _writing = crate::watch::writing(start + at, n); - crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); - written += n; + known_changed = true; + } + while before[0].0 + before[0].1.len() <= at { + before = &before[1..]; + } + let old = snapshot_piece(before, at, n, &mut old_piece); + // SAFETY: inside the mapping; the parallel scan has joined + // and only this thread writes the copy. + let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; + if known_changed || host != old { + if title.len() < n { + title.resize(n, 0); + } + let title = &mut title[..n]; + if crate::host::read_into((start + at) as *const u8, title) { + diff_piece_runs(host, old, title, &mut runs); + written += write_runs(start + at, n, title, &runs, &mut writable, mode); + synced.push((start + at) / PAGE); } - synced.push((start + at) / PAGE); } at += n; } @@ -388,6 +561,35 @@ impl Shadow { written } + fn scan_copy_back( + &self, + from: usize, + to: usize, + before: &[(usize, Vec)], + compared: &HashSet, + ) -> Option { + let workers = copy_back_workers(); + let start = self.start as usize; + let first = (start + from).next_multiple_of(PAGE); + let end = (start + to) / PAGE * PAGE; + if workers <= 1 || end.saturating_sub(first) / PAGE < 2 * PAGES_PER_WORKER { + return None; + } + let mut pages: PageChanges = (first..end) + .step_by(PAGE) + .filter(|at| !compared.contains(at)) + .map(|at| (at - start, false)) + .collect(); + if pages.len() < 2 * PAGES_PER_WORKER { + return None; + } + // SAFETY: the whole range is in the mapping and the GPU is done. + // Workers only read, and join before this thread changes any bytes. + let host = unsafe { std::slice::from_raw_parts(self.data.add(from), to - from) }; + scan_pages(host, from, before, &mut pages, workers); + Some(pages) + } + /// At submission: copies what changed of `[address, address + len)` /// since it was last copied (all of it if the memory is not /// write-watched). Returns the bytes copied. @@ -808,12 +1010,12 @@ mod tests { copy.writing(p + PAGE, 2 * PAGE); copy.writing(p + PAGE, PAGE); copy.writing(p + 80, 8); - assert_eq!(bytes(©), 72 + 2 * PAGE + 100, "merged where they overlap or touch"); + assert_eq!(bytes(©), 72 + 2 * PAGE + 100, "only the declared union"); // The GPU writes inside two ranges. copy.write_host((p + 20) as u64, &[1, 2, 3]); copy.write_host((p + PAGE + 5) as u64, &[9]); - assert_eq!(copy.copy_back(p + 16, 64), 64, "the range's part of the piece"); - assert_eq!(copy.copy_back(p + PAGE, 2 * PAGE), PAGE, "the piece written"); + assert_eq!(copy.copy_back(p + 16, 64), 3, "only the changed bytes go back"); + assert_eq!(copy.copy_back(p + PAGE, 2 * PAGE), 1, "only the changed byte goes back"); assert_eq!(copy.copy_back(p + PAGE, PAGE), 0, "compared once"); assert_eq!(copy.copy_back(p + 3 * PAGE, 100), 0); assert_eq!(copy.copy_back(p + 80, 8), 0); @@ -863,4 +1065,512 @@ mod tests { crate::host::BUFFER_UNORDERED_ACCESS ); } + + #[test] + fn incremental_snapshot_preserves_first_bytes_across_overlaps_and_gaps() { + let mut host = vec![0; 2 * PAGE + 41]; + let mut incremental = Segments::new(); + let mut coalesced = Segments::new(); + let mut bytes = 0; + for (from, to, value) in [ + (9, PAGE - 10, 0x11), + (PAGE + 9, PAGE + 81, 0x22), + (PAGE - 18, PAGE + 29, 0x33), + (0, PAGE + 1, 0x44), + (PAGE + 81, 2 * PAGE + 41, 0x55), + ] { + host[from..to].fill(value); + let read = |a, b| &host[a..b]; + bytes += snapshot_gaps(&mut incremental, from, to, read); + snapshot_coalesced(&mut coalesced, from, to, read); + if value == 0x22 { + assert!(snapshot_cover(&incremental, 9, PAGE + 81).is_none()); + } + } + assert_eq!(bytes, host.len()); + assert_eq!(snapshot_gaps(&mut incremental, 0, host.len(), |a, b| &host[a..b]), 0); + let want = &coalesced[0].1; + let mut before = snapshot_cover(&incremental, 0, host.len()).unwrap(); + let mut scratch = Vec::new(); + for from in (0..host.len()).step_by(PAGE) { + while before[0].0 + before[0].1.len() <= from { + before = &before[1..]; + } + let n = PAGE.min(host.len() - from); + assert_eq!(snapshot_piece(before, from, n, &mut scratch), &want[from..from + n]); + } + } + + #[test] + #[ignore = "offline performance benchmark"] + fn snapshot_overlap_benchmark() { + use std::hint::black_box; + use std::time::Instant; + + const MIB: usize = 1 << 20; + let host = vec![0x5au8; 174 * MIB]; + let mut runs = [Vec::new(), Vec::new()]; + let mut totals = [0; 2]; + for sample in 0..8 { + for mode in [sample % 2, 1 - sample % 2] { + let mut segments = Segments::new(); + let start = Instant::now(); + let read = |a, b| &black_box(&host)[a..b]; + let mut copied = 0; + for from in (0..12).map(|i| i * 12 * MIB) { + let to = from + 32 * MIB; + copied += if mode == 0 { + snapshot_coalesced(&mut segments, from, to, read) + } else { + snapshot_gaps(&mut segments, from, to, read) + }; + } + black_box(&segments); + if sample > 0 { + runs[mode].push(start.elapsed()); + } + totals[mode] = copied; + for (_, bytes) in segments.drain(..) { + give_back(bytes); + } + } + } + for (mode, samples) in runs.iter_mut().enumerate() { + samples.sort_unstable(); + let name = ["coalesced", "incremental"][mode]; + let elapsed = samples[samples.len() / 2].as_secs_f64() * 1000.0; + println!("{name}: {} MiB copied, {elapsed:.2} ms median", totals[mode] / MIB); + } + } + + #[test] + fn parallel_copy_back_scan_matches_serial_on_selected_pages() { + let pages = 2 * PAGES_PER_WORKER + 3; + let len = pages * PAGE; + let mut host = vec![0xc3; len]; + let boundary = 17 * PAGE + 5; + let before = [ + (0, host[..boundary].to_vec()), + (boundary, host[boundary..].to_vec()), + ]; + let changed = [0, 17, pages - 1]; + for i in changed { + host[i * PAGE + 7] ^= 1; + } + let mut parallel: PageChanges = (0..pages).filter(|&p| p != 1).map(|p| (p * PAGE, false)).collect(); + let mut serial = parallel.clone(); + scan_pages(&host, 0, &before, &mut parallel, 4); + scan_pages(&host, 0, &before, &mut serial, 1); + assert_eq!(parallel, serial); + assert_eq!( + parallel.iter().filter_map(|&(at, different)| different.then_some(at / PAGE)).collect::>(), + changed + ); + } + + #[test] + fn large_copy_back_preserves_title_bytes_and_skips_compared_pages() { + let len = (2 * PAGES_PER_WORKER + 4) * PAGE; + let title = title_memory(len); + let start = title.as_mut_ptr() as usize; + register(start, start as u64, len as u64); + let Some(copy) = find(start as u64, len as u64) else { + unregister(start, start as u64); + return; + }; + copy.update(start, len); + let boundary = 17 * PAGE + 123; + copy.writing(start + 16, boundary - 16); + copy.writing(start + boundary, len - boundary - 16); + copy.writing(start + 8, len - 16); + copy.writing(start + 8 * PAGE, PAGE); + + for (at, value) in [(9, 1), (8 * PAGE + 9, 2), (boundary + 1, 3), (len - 10, 4)] { + copy.write_host((start + at) as u64, &[value]); + } + title[boundary] = 0xc3; + assert_eq!(copy.copy_back(start + 8 * PAGE, PAGE), 1); + assert_eq!(copy.copy_back(start + 8, len - 16), 3); + assert_eq!( + [title[9], title[8 * PAGE + 9], title[boundary], title[boundary + 1], title[len - 10]], + [1, 2, 0xc3, 3, 4] + ); + copy.keep_writes(start + 16, boundary - 16); + copy.keep_writes(start + boundary, len - boundary - 16); + unregister(start, start as u64); + } + + #[test] + #[ignore = "offline performance benchmark"] + fn copy_back_scan_benchmark() { + use std::hint::black_box; + use std::time::Instant; + + for mib in [32, 160] { + let len = mib << 20; + let mut host = vec![0x5a; len]; + let before = [(0, host.clone())]; + for i in (7..len / PAGE).step_by(83) { + host[i * PAGE + 9] ^= 1; + } + let mut times = [Vec::new(), Vec::new()]; + for sample in 0..10 { + for mode in [sample % 2, 1 - sample % 2] { + let mut pages: PageChanges = (0..len).step_by(PAGE).map(|at| (at, false)).collect(); + let start = Instant::now(); + scan_pages(black_box(&host), 0, black_box(&before), &mut pages, [1, 4][mode]); + black_box(pages); + if sample > 0 { + times[mode].push(start.elapsed()); + } + } + } + for samples in &mut times { + samples.sort_unstable(); + } + let medians = times.map(|s| s[s.len() / 2].as_secs_f64() * 1000.0); + println!("{mib} MiB: {:.2} ms serial, {:.2} ms parallel", medians[0], medians[1]); + } + } + + #[test] + fn copy_back_page_writes_only_changed_runs() { + let p = crate::watch::tests::pool(2); + let len = 2 * PAGE; + register(p, p as u64, len as u64); + let Some(copy) = find(p as u64, len as u64) else { + unregister(p, p as u64); + return; // no host GPU here + }; + // Seed title memory and take it into the copy. + for off in 0..64 { + // SAFETY: our pool. + unsafe { ((p + off) as *mut u8).write_volatile(0x11) }; + } + copy.update(p, len); + // Shader writes bytes 10..14 and 40..42; byte 20 stays equal to title memory. + copy.write_host((p + 10) as u64, &[0xaa, 0xbb, 0xcc, 0xdd]); + copy.write_host((p + 40) as u64, &[0xee, 0xff]); + assert_eq!(copy.copy_back_page(p), 6); + // SAFETY: our pool. + let byte = |off: usize| unsafe { ((p + off) as *const u8).read_volatile() }; + assert_eq!((10..14).map(byte).collect::>(), [0xaa, 0xbb, 0xcc, 0xdd]); + assert_eq!((40..42).map(byte).collect::>(), [0xee, 0xff]); + assert_eq!(byte(9), 0x11); + assert_eq!(byte(14), 0x11); + assert_eq!(byte(39), 0x11); + assert_eq!(byte(42), 0x11); + assert_eq!(copy.copy_back_page(p), 0); + unregister(p, p as u64); + } + + struct Rng(u64); + impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + fn below(&mut self, n: usize) -> usize { + (self.next() % n as u64) as usize + } + } + + fn title_memory(len: usize) -> &'static mut [u8] { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, + }; + // SAFETY: fresh committed allocation, kept for the test process. + unsafe { + let p = VirtualAlloc(std::ptr::null(), len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + assert!(!p.is_null()); + std::slice::from_raw_parts_mut(p.cast(), len) + } + } + + #[test] + fn fast_diff_and_changed_runs_match_byte_reference() { + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + for round in 0..500 { + let n = 1 + rng.below(300); + let old: Vec = (0..n).map(|_| rng.next() as u8).collect(); + let mut host = old.clone(); + let mut title = old.clone(); + for _ in 0..rng.below(1 + round % 20) { + let i = rng.below(n); + host[i] = host[i].wrapping_add(1 + rng.below(255) as u8); + } + for _ in 0..rng.below(1 + round % 12) { + let i = rng.below(n); + title[i] = title[i].wrapping_add(1 + rng.below(255) as u8); + } + + let mut ref_host = host.clone(); + let mut ref_title = title.clone(); + let mut ref_runs: Vec<(usize, usize)> = Vec::new(); + for (k, ((t, h), o)) in ref_title + .iter_mut() + .zip(ref_host.iter_mut()) + .zip(&old) + .enumerate() + { + if *h != *o && *t != *h { + *t = *h; + push_run(&mut ref_runs, k); + } + *h = *t; + } + let mut runs = Vec::new(); + diff_piece_runs(&mut host, &old, &mut title, &mut runs); + assert_eq!(runs, ref_runs); + assert_eq!(title, ref_title); + assert_eq!(host, ref_host); + + let ref_changed: Vec<(usize, usize)> = { + let mut r = Vec::new(); + for k in 0..n { + if host[k] != old[k] { + push_run(&mut r, k); + } + } + r + }; + changed_runs(&host, &old, &mut runs); + assert_eq!(runs, ref_changed); + } + } + + #[test] + fn write_runs_writes_same_bytes_in_direct_and_kernel_modes() { + const N: usize = 64 << 10; + for protect in [false, true] { + let mut outputs = Vec::new(); + for mode in [BackMode::Kernel, BackMode::Direct] { + let title = title_memory(N); + let mut rng = Rng(7); + for b in title.iter_mut() { + *b = rng.next() as u8; + } + let old = title.to_vec(); + let mut host = old.clone(); + for _ in 0..400 { + let i = rng.below(N); + host[i] ^= 0x5a; + } + // GPU wrote bytes title already holds: not written. + host[100..104].copy_from_slice(&[9, 9, 9, 9]); + title[100..104].copy_from_slice(&[9, 9, 9, 9]); + // Title concurrently wrote byte 200 (GPU did not). + title[200] ^= 0xff; + if protect { + use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; + let mut was = 0; + // SAFETY: our own allocation. + unsafe { VirtualProtect(title.as_ptr().cast(), N, PAGE_READONLY, &mut was) }; + assert!(!Writable::default().covers(title.as_ptr() as usize, N)); + } + let mut title_buf = title.to_vec(); + let mut runs = Vec::new(); + diff_piece_runs(&mut host, &old, &mut title_buf, &mut runs); + // Runs never bridge unchanged byte 200 or title-matching 100..104. + assert!(!runs.iter().any(|&(a, b)| (a..b).contains(&200))); + assert!(!runs.iter().any(|&(a, b)| a < 104 && b > 100)); + let mut w = Writable::default(); + let written = write_runs(title.as_ptr() as usize, N, &title_buf, &runs, &mut w, mode); + let expected_written: usize = runs.iter().map(|&(a, b)| b - a).sum(); + assert_eq!(written, expected_written); + if !protect { + assert_eq!(title, title_buf); + assert_eq!(title[200], old[200] ^ 0xff); + } + outputs.push((written, title.to_vec())); + } + assert_eq!(outputs[0], outputs[1], "protect {protect}"); + } + } + + #[test] + fn writable_caches_region_across_pieces() { + const N: usize = 256 << 10; + let mem = title_memory(N); + let at = mem.as_ptr() as usize; + let mut w = Writable::default(); + assert!(w.covers(at, 64 << 10)); + assert!(w.from <= at && w.to >= at + N); + assert!(w.covers(at + (64 << 10), 64 << 10)); + assert!(w.covers(at + (128 << 10), 64 << 10)); + } +} + +fn push_run(runs: &mut Vec<(usize, usize)>, idx: usize) { + match runs.last_mut() { + Some((_, e)) if *e == idx => *e = idx + 1, + _ => runs.push((idx, idx + 1)), + } +} + +/// Finds the byte runs in `[0..n)` that the GPU changed (`host != old`) and title memory does +/// not already hold (`title != host`), putting those bytes into `title` and `title`'s bytes into +/// `host`. Skips equal 32-byte stretches (`host == old`); runs are never merged across unchanged +/// bytes or bytes already equal to the title's. +fn diff_piece_runs( + host: &mut [u8], + old: &[u8], + title: &mut [u8], + runs: &mut Vec<(usize, usize)>, +) { + runs.clear(); + let n = host.len().min(old.len()).min(title.len()); + let mut k = 0; + while k + 32 <= n { + let h: &[u8; 32] = host[k..k + 32].try_into().unwrap(); + let o: &[u8; 32] = old[k..k + 32].try_into().unwrap(); + if h == o { + let t: &[u8; 32] = title[k..k + 32].try_into().unwrap(); + if h != t { + host[k..k + 32].copy_from_slice(t); + } + } else { + for idx in k..k + 32 { + if host[idx] != old[idx] && title[idx] != host[idx] { + title[idx] = host[idx]; + push_run(runs, idx); + } + host[idx] = title[idx]; + } + } + k += 32; + } + for idx in k..n { + if host[idx] != old[idx] && title[idx] != host[idx] { + title[idx] = host[idx]; + push_run(runs, idx); + } + host[idx] = title[idx]; + } +} + +/// Finds the byte runs where `host` differs from `title`, skipping equal 32-byte stretches. +fn changed_runs(host: &[u8], title: &[u8], runs: &mut Vec<(usize, usize)>) { + runs.clear(); + let n = host.len().min(title.len()); + let mut k = 0; + while k + 32 <= n { + let h: &[u8; 32] = host[k..k + 32].try_into().unwrap(); + let t: &[u8; 32] = title[k..k + 32].try_into().unwrap(); + if h != t { + for idx in k..k + 32 { + if host[idx] != title[idx] { + push_run(runs, idx); + } + } + } + k += 32; + } + for idx in k..n { + if host[idx] != title[idx] { + push_run(runs, idx); + } + } +} + +/// How the copy-back writes title memory. +#[derive(Clone, Copy, PartialEq, Debug)] +enum BackMode { + /// One `WriteProcessMemory` per run of changed bytes. + Kernel, + /// Plain stores where the piece is committed read-write (at most one query per region), + /// the kernel elsewhere (read-only or otherwise protected title memory). + Direct, +} + +/// Local build: `VICTORY_COPY_BACK_KERNEL=1` writes every run through the kernel again. +fn back_mode() -> BackMode { + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + *MODE.get_or_init(|| { + if std::env::var("VICTORY_COPY_BACK_KERNEL").is_ok_and(|v| v.trim() == "1") { + BackMode::Kernel + } else { + BackMode::Direct + } + }) +} + +/// Writes each `(r0, r1)` run from `bytes` into title memory at `at`, opening write guards on +/// `[at, at + len)` first and using plain stores when the region is committed read-write. +fn write_runs( + at: usize, + len: usize, + bytes: &[u8], + runs: &[(usize, usize)], + writable: &mut Writable, + mode: BackMode, +) -> usize { + if runs.is_empty() { + return 0; + } + let _writing = crate::watch::writing(at, len); + let direct = mode == BackMode::Direct && writable.covers(at, len); + let mut written = 0; + for &(r0, r1) in runs { + let dst = (at + r0) as *mut u8; + let src = &bytes[r0..r1]; + if direct { + // SAFETY: committed read-write title memory (`writable.covers` checked `[at, at + len)`), + // and `bytes` is our own buffer. + unsafe { std::ptr::copy_nonoverlapping(src.as_ptr(), dst, src.len()) }; + } else { + crate::host::write_mapped(dst, src.as_ptr(), src.len()); + } + written += src.len(); + } + written +} + +/// The last title region found committed and read-write (`[from, to)`), kept for the pieces +/// after it: a query costs about as much as walking the region (~80 us for a 64 MB heap). +/// Only read-write answers are kept: a block the write guards (`crate::watch`) opened since +/// is asked again. +#[derive(Default)] +struct Writable { + from: usize, + to: usize, +} + +impl Writable { + /// Whether all of `[at, at + n)` is committed and read-write (a plain store cannot fault + /// there except into the write guards' handler, which opens the block). + fn covers(&mut self, at: usize, n: usize) -> bool { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READWRITE, PAGE_GUARD, + PAGE_READWRITE, VirtualQuery, + }; + let end = at + n; + let mut p = at; + while p < end { + if (self.from..self.to).contains(&p) { + p = self.to; + continue; + } + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + if unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) } == 0 { + return false; + } + let base = info.Protect & 0xff; + let next = info.BaseAddress as usize + info.RegionSize; + if info.State != MEM_COMMIT + || info.Protect & PAGE_GUARD != 0 + || (base != PAGE_READWRITE && base != PAGE_EXECUTE_READWRITE) + || next <= p + { + return false; + } + (self.from, self.to) = (info.BaseAddress as usize, next); + p = next; + } + true + } } diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 92445b9..c88dd27 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -147,6 +147,11 @@ extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out return from_win32(&error); } tracing::info!(path = name, iid = iid_text(iid), "dstorage: file opened"); + if name.contains("core_restofworld") + && !super::gameinput::GAME_LOADING.swap(true, std::sync::atomic::Ordering::Relaxed) + { + tracing::info!("the title loads the game: automatic A stops"); + } // SAFETY: a handle we just opened and nobody else owns. let file = unsafe { std::fs::File::from_raw_handle(handle) }; let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { file }); diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index 28de6b3..b8fa9e9 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -1293,7 +1293,16 @@ mod host { return None; } self.empty_until[slot] = None; - Some(convert(&state.Gamepad)) + let mut pad = convert(&state.Gamepad); + // Local build: automatic A/Down go to a connected pad too (the keyboard is no + // stand-in pad while one is connected). + if super::auto_a() { + pad.buttons |= super::A; + } + if super::auto_down() { + pad.buttons |= super::DOWN; + } + Some(pad) } fn keys(&mut self) -> Vec { @@ -1301,6 +1310,12 @@ mod host { let mut down = scripted(); #[cfg(not(feature = "diagnostics"))] let mut down = Vec::new(); + if super::auto_a() && !down.contains(&0x0D) { + down.push(0x0D); + } + if super::auto_down() && !down.contains(&0x28) { + down.push(0x28); + } if focused() { // Left/right modifier keys only, as devices report them; no // mouse buttons (below 0x08). @@ -2121,4 +2136,88 @@ mod tests { assert_eq!(pad(back).buttons, A); release(back); } + + #[test] + fn auto_a_and_down_follow_mode_and_loading_flag() { + assert_eq!(parse_auto_a(None), 0); + assert_eq!(parse_auto_a(Some(" 1 ")), 1); + assert_eq!(parse_auto_a(Some("2")), 2); + assert_eq!(parse_auto_a(Some("0")), 0); + + // Initial 3 s grace period. + assert!(!auto_a_at(1, false, 3000)); + assert!(!auto_down_at(2, 3000)); + + // Mode 1: pulses A for 0.3 s every 2 s until GAME_LOADING is set; never presses down. + assert!(auto_a_at(1, false, 4000)); + assert!(auto_a_at(1, false, 4299)); + assert!(!auto_a_at(1, false, 4300)); + assert!(!auto_a_at(1, true, 4000)); + assert!(!auto_down_at(1, 5100)); + + // Mode 2: continues after GAME_LOADING and alternates A with D-pad down (4 s cycle). + assert!(auto_a_at(2, true, 4000)); + assert!(!auto_down_at(2, 4000)); + assert!(auto_down_at(2, 5000)); + assert!(auto_down_at(2, 5299)); + assert!(!auto_down_at(2, 5300)); + assert!(auto_a_at(2, true, 6000)); + assert!(!auto_down_at(2, 6000)); + } +} + +/// Local build: set when the title starts loading the game (it opens its world pack). +pub(crate) static GAME_LOADING: std::sync::atomic::AtomicBool = + std::sync::atomic::AtomicBool::new(false); + +fn parse_auto_a(value: Option<&str>) -> u8 { + match value.map(str::trim) { + Some("1") => 1, + Some("2") => 2, + _ => 0, + } +} + +fn auto_mode() -> (u8, Option) { + static STATE: LazyLock<(u8, Option)> = LazyLock::new(|| { + let mode = parse_auto_a(std::env::var("VICTORY_AUTO_A").ok().as_deref()); + (mode, (mode != 0).then(Instant::now)) + }); + *STATE +} + +fn auto_a_at(mode: u8, loading: bool, ms: u128) -> bool { + if mode == 0 || (mode == 1 && loading) { + return false; + } + ms > 3000 && ms % 2000 < 300 +} + +fn auto_down_at(mode: u8, ms: u128) -> bool { + mode == 2 && ms > 3000 && (1000..1300).contains(&(ms % 4000)) +} + +/// Local build: `VICTORY_AUTO_A=1` holds A (the stand-in pad's Enter) for 0.3 s every 2 s, +/// whether or not the window has focus, until the title loads the game: the profile screen +/// ("PLAYER A") is passed without anyone at the keyboard. `VICTORY_AUTO_A=2` keeps pressing A +/// after the game loads (first-run screens). +fn auto_a() -> bool { + let (mode, Some(start)) = auto_mode() else { + return false; + }; + auto_a_at( + mode, + GAME_LOADING.load(std::sync::atomic::Ordering::Relaxed), + start.elapsed().as_millis(), + ) +} + +/// Local build: with `VICTORY_AUTO_A=2`, D-pad down for 0.3 s between every other A (each 4 s: +/// A, down, A), so a menu whose first item does not advance (the legal notices: "Copyright", +/// "Photosensitivity", then "Next") is walked down to its button. +fn auto_down() -> bool { + let (mode, Some(start)) = auto_mode() else { + return false; + }; + auto_down_at(mode, start.elapsed().as_millis()) } diff --git a/crates/victory-shader/src/emit/container.rs b/crates/victory-shader/src/emit/container.rs index 222deb7..7a2acb3 100644 --- a/crates/victory-shader/src/emit/container.rs +++ b/crates/victory-shader/src/emit/container.rs @@ -44,6 +44,7 @@ impl SigElement { 18 => 68, 19 => 67, 20 => 69, + 28 => 23, // barycentrics 30 => 25, // cull primitive _ => 0, } @@ -150,6 +151,8 @@ pub(crate) struct Binding { } pub(crate) struct Psv<'a> { + /// The entry point name in runtime info version 3 (validator 1.8). + pub entry_name: Option<&'a str>, /// PSV shader kind: 0 pixel, 1 vertex, 5 compute. pub stage: u8, /// Vertex: writes `SV_Position`. Pixel: writes depth. @@ -168,7 +171,7 @@ pub(crate) struct Psv<'a> { pub wave_size: Option, } -/// `PSV0` with runtime info version 2 (validator 1.6). +/// `PSV0` with runtime info version 2, or version 3 with an entry name. pub(crate) fn psv(p: &Psv) -> Vec { let vectors = |els: &[SigElement]| { els.iter() @@ -184,7 +187,7 @@ pub(crate) fn psv(p: &Psv) -> Vec { out.extend(v.to_le_bytes()); } }; - u32s(&mut out, &[48]); + u32s(&mut out, &[if p.entry_name.is_some() { 52 } else { 48 }]); let mut info = [0u8; 48]; info[0] = u8::from(p.flag); if p.stage == 0 { @@ -225,6 +228,9 @@ pub(crate) fn psv(p: &Psv) -> Vec { info[26..28].copy_from_slice(&(max as u16).to_le_bytes()); } out.extend(info); + if p.entry_name.is_some() { + u32s(&mut out, &[1]); // First name, after the empty string. + } u32s(&mut out, &[p.bindings.len() as u32]); if !p.bindings.is_empty() { u32s(&mut out, &[24]); @@ -237,6 +243,9 @@ pub(crate) fn psv(p: &Psv) -> Vec { } // Names of arbitrary semantics (system values use ""), then indices. let mut strings = vec![0u8]; + if let Some(name) = p.entry_name { + strings.extend(name.bytes().chain([0])); + } let mut indices: Vec = Vec::new(); let mut elements = Vec::new(); for e in p.inputs.iter().chain(p.outputs).chain(p.prims) { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 3dd9f3d..013cc34 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -24,6 +24,18 @@ mod bvh; type Why = &'static str; +fn interpolation_mode(kind: Barycentric) -> Result { + Ok(match kind { + Barycentric::PerspectiveCenter => 2, + Barycentric::PerspectiveCentroid => 3, + Barycentric::PerspectiveSample => 6, + Barycentric::LinearCenter => 4, + Barycentric::LinearCentroid => 5, + Barycentric::LinearSample => 7, + Barycentric::PerspectivePullModel => return Err("pull-model interpolation"), + }) +} + #[derive(Debug, Clone, Copy)] enum Val { I32(V), @@ -318,6 +330,7 @@ struct Lower<'a> { data_phis: Vec<(V, usize, usize)>, read_phis: HashSet, params: HashMap, + barycentrics: HashMap, user_data: Option, user_reads: BTreeMap, /// Handles of root SRVs and UAVs read as bounded views, by user-data @@ -804,6 +817,7 @@ impl<'a> Lower<'a> { data_phis: Vec::new(), read_phis: HashSet::new(), params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(), + barycentrics: HashMap::new(), user_data: None, user_reads: BTreeMap::new(), root_views: HashMap::new(), @@ -1676,6 +1690,12 @@ impl<'a> Lower<'a> { }, Reg::Scc => Val::Missing("SCC on entry"), Reg::V(_) => match io_inputs.get(&v) { + Some(&Input::Barycentric { kind, index }) => { + // Attribute interpolation only needs a signature input + // when the shader directly reads the coordinates. + self.barycentrics.insert(v, (kind, index)); + continue; + } Some(&input) => self.input(input), // Registers no one set read as zero (the validator // refuses reads of undef). @@ -1841,6 +1861,47 @@ impl<'a> Lower<'a> { } } + fn barycentric_input(&mut self, kind: Barycentric, index: u8) -> Result { + let mode = interpolation_mode(kind)?; + if index >= 2 { + return Err("a barycentric component"); + } + let id = if let Some(id) = self + .s + .inputs + .iter() + .position(|e| e.kind == 28 && e.interp == mode) + { + id + } else { + let perspective = |mode| matches!(mode, 2 | 3 | 6); + let mut count = 0; + for e in self.s.inputs.iter().filter(|e| e.kind == 28) { + if perspective(e.interp) == perspective(mode) { + return Err("two direct barycentric inputs of the same interpolation type"); + } + count += 1; + } + let id = self.s.inputs.len(); + self.s.inputs.push(SigElement { + name: "SV_Barycentrics".into(), + index: count, + kind: 28, + comp: 9, + interp: mode, + row: None, + col: 0, + cols: 3, + usage: 0, + half: false, + }); + id + }; + self.s.flags |= flags::BARYCENTRICS; + // Console I and J weight vertices 1 and 2, which are DXIL's y and z. + Ok(self.load_any_input(id, index + 1)) + } + /// The DXIL form of an IR value. fn get(&mut self, v: Value) -> Result { if self.phi_at.contains_key(&v) { @@ -1860,6 +1921,11 @@ impl<'a> Lower<'a> { self.vals.insert(v, val); return Ok(val); } + if let Some(&(kind, index)) = self.barycentrics.get(&v) { + let val = self.barycentric_input(kind, index)?; + self.vals.insert(v, val); + return Ok(val); + } Err("a value defined after its use") } @@ -6542,6 +6608,73 @@ impl<'a> Lower<'a> { } Ok(()) } + "v_cvt_f32_f64" => { + // Double to float in integer arithmetic (no 64-bit float on + // the host path): round to nearest even, overflow to + // infinity, NaN kept quiet, results below the float range + // flushed to signed zero (as the console flushes f32 + // denormals by default). + let x = self.src64(inst, 0)?; + let (lo, hi) = self.split64(x); + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let sign = { + let m = k(self, 0x8000_0000); + self.s.m.bin(c, Bin::And, hi, m) + }; + let e = { + let (k20, m) = (k(self, 20), k(self, 0x7FF)); + let t = self.s.m.bin(c, Bin::LShr, hi, k20); + self.s.m.bin(c, Bin::And, t, m) + }; + let m = { + let (mh, k3, k29) = (k(self, 0xF_FFFF), k(self, 3), k(self, 29)); + let t = self.s.m.bin(c, Bin::And, hi, mh); + let t = self.s.m.bin(c, Bin::Shl, t, k3); + let u = self.s.m.bin(c, Bin::LShr, lo, k29); + self.s.m.bin(c, Bin::Or, t, u) + }; + let rest = { + let r = k(self, 0x1FFF_FFFF); + self.s.m.bin(c, Bin::And, lo, r) + }; + // Normal: sign | (e - 896) << 23 | m, plus the rounding carry. + let (k896, k23, one, half) = (k(self, 896), k(self, 23), k(self, 1), k(self, 0x1000_0000)); + let e32 = self.s.m.bin(c, Bin::Sub, e, k896); + let ebits = self.s.m.bin(c, Bin::Shl, e32, k23); + let bits = self.s.m.bin(c, Bin::Or, sign, ebits); + let bits = self.s.m.bin(c, Bin::Or, bits, m); + let above = self.s.m.cmp(c, pred::IUGT, rest, half); + let tie = self.s.m.cmp(c, pred::EQ, rest, half); + let odd = self.s.m.bin(c, Bin::And, m, one); + let k0 = k(self, 0); + let odd = self.s.m.cmp(c, pred::NE, odd, k0); + let tie_up = self.s.m.bin(c, Bin::And, tie, odd); + let up = self.s.m.bin(c, Bin::Or, above, tie_up); + let zero = k(self, 0); + let carry = self.s.m.select(c, up, one, zero); + let normal = self.s.m.bin(c, Bin::Add, bits, carry); + // Exponent ranges, by the double's exponent: <= 896 to zero, + // >= 1151 to infinity, 0x7FF infinity or NaN. + let inf = { + let i = k(self, 0x7F80_0000); + self.s.m.bin(c, Bin::Or, sign, i) + }; + let nan = { + let q = k(self, 0x7FC0_0000); + self.s.m.bin(c, Bin::Or, sign, q) + }; + let mantissa = self.s.m.bin(c, Bin::Or, m, rest); + let has_mantissa = self.s.m.cmp(c, pred::NE, mantissa, zero); + let special = self.s.m.select(c, has_mantissa, nan, inf); + let (k7ff, k1151) = (k(self, 0x7FF), k(self, 1151)); + let small = self.s.m.cmp(c, pred::IULE, e, k896); + let big = self.s.m.cmp(c, pred::IUGE, e, k1151); + let all = self.s.m.cmp(c, pred::EQ, e, k7ff); + let r = self.s.m.select(c, big, inf, normal); + let r = self.s.m.select(c, small, sign, r); + let r = self.s.m.select(c, all, special, r); + int(self, r) + } // An SGPR spilled to a VGPR lane and read back is the SGPR, in // every stage (in compute the VGPR's other lanes may hold what has // no host value, a descriptor's address say). @@ -8025,18 +8158,7 @@ impl<'a> Lower<'a> { attribute, barycentric, .. - } => ( - attribute, - match barycentric { - Barycentric::PerspectiveCenter => 2, - Barycentric::PerspectiveCentroid => 3, - Barycentric::PerspectiveSample => 6, - Barycentric::LinearCenter => 4, - Barycentric::LinearCentroid => 5, - Barycentric::LinearSample => 7, - Barycentric::PerspectivePullModel => return Err("pull-model interpolation"), - }, - ), + } => (attribute, interpolation_mode(*barycentric)?), // P0, the provoking vertex: a flat (nointerpolation) input. Interp::Vertex { attribute, @@ -8534,6 +8656,15 @@ impl<'a> Lower<'a> { "image_get_resinfo" => (72, false), _ => return Err(name), }; + if matches!(op, 60 | 61) + && let StageIo::Cs(cs) = self.x.native.io + { + let [x, y, z] = cs.threads; + let linear_quads = y == 1 && z == 1 && x.is_multiple_of(4); + let tiled_quads = x.is_multiple_of(2) && y.is_multiple_of(2); + // Keep the existing validator target for incompatible groups. + self.s.compute_derivatives = linear_quads || tiled_quads; + } if op == 72 { // Width, height, depth or layers, levels (per dmask) of the level // in the first address: DXIL's dimensions; a channel DXIL leaves @@ -10521,7 +10652,15 @@ impl<'a> Lower<'a> { let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); let arg = phi.args[n]; let read = live.contains(&(phi.value, n)); - let x = match (self.vals.get(&arg).copied(), bit) { + let mut value = self.vals.get(&arg).copied(); + if read + && value.is_none() + && (self.params.contains_key(&arg) || self.barycentrics.contains_key(&arg)) + { + // A live phi can be the first read of an entry input. + value = Some(self.get(arg).unwrap_or_else(Val::Missing)); + } + let x = match (value, bit) { (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x, // No lane from this edge reads it, or no lane comes // along it at all: any value will do. @@ -10763,6 +10902,16 @@ mod tests { layout: Vec, used: Vec, wave64: bool, + ) -> Result { + lower_compute(words, layout, used, wave64, [1, 1, 1]) + } + + fn lower_compute( + words: &[u32], + layout: Vec, + used: Vec, + wave64: bool, + threads: [u32; 3], ) -> Result { let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum(); @@ -10775,7 +10924,7 @@ mod tests { io: StageIo::Cs(ComputeIo { // The layout's user SGPRs (at least two), 512 bytes of LDS. rsrc2: 1 << 15 | sgprs.max(2) << 1, - threads: [1, 1, 1], + threads, }), code, }; @@ -10796,6 +10945,42 @@ mod tests { }) } + #[test] + fn implicit_compute_sampling_validates_with_quad_threads() { + use super::super::validator::Validator; + + let words = [ + 0xBE82_0300, // s_mov_b32 s2, s0 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xBE84_0301, // s_mov_b32 s4, s1 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF40C_0201, + 0xFA00_0000, // s_load_dwordx8 s[8:15], s[2:3], null + 0xF408_0402, + 0xFA00_0000, // s_load_dwordx4 s[16:19], s[4:5], null + 0xF080_0F08, + 0x0082_0400, // image_sample v[4:7], v[0:1], s[8:15], s[16:19] + 0xD834_0000, + 0x0000_0400, // ds_write_b32 v0, v4 + S_ENDPGM, + ]; + for (threads, runtime_info_size) in [([4, 1, 1], 52), ([2, 2, 1], 52), ([1, 1, 1], 48)] { + let (layout, used) = texture_tables(); + let mut shader = lower_compute(&words, layout, used, false, threads).unwrap(); + let container = crate::Container::parse(&shader.dxil).unwrap(); + let psv = container.part(crate::FourCC::PSV0).unwrap(); + assert_eq!( + u32::from_le_bytes(psv.data[..4].try_into().unwrap()), + runtime_info_size + ); + if runtime_info_size == 52 + && let Ok(mut validator) = Validator::load(Validator::default_path().as_deref()) + { + validator.validate(&mut shader.dxil).unwrap(); + } + } + } + /// Root parameter `slot` in user SGPRs from `user_data` on. fn root(root: RootType, user_data: u8, slot: u8) -> RootParam { RootParam { diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index b90058a..3a072cb 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -528,6 +528,7 @@ fn signature(part: &[u8]) -> Result, ShaderError> { 8 => 2, 9 => 13, 10 => 12, + 23 => 28, // barycentrics 64 => 16, 65 => 17, 66 => 14, @@ -1252,6 +1253,56 @@ mod tests { assert_eq!(sample[4 + 1], 1, "PSInfo.SampleFrequency"); } + #[test] + fn direct_barycentrics_reach_pixel_export_through_a_join() { + let words = [ + 0xBF06_8000u32, // s_cmp_eq_u32 s0, 0 + 0xBF85_0001, // s_cbranch_scc1 to the export + 0x7E00_0280, // v_mov_b32 v0, 0 + 0xF800_180F, + 0x0100_0100, // exp mrt0 v0, v1, v0, v1 done vm + 0xBF81_0000, + ]; + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 2, + layout: vec![crate::RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: vec![], + io: StageIo::Ps { + inputs: vec![], + input_addr: 1 << 1, // Perspective center I and J. + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let osg = rows(&[("SV_Target", 16, false)], false); + let c = crate::dxbc::build(&[(FourCC::OSG1, &osg)]); + let c = Container::parse(&c).unwrap(); + let p = ir::build(&native.code, false, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let mut shader = emit(&c, &native, &p, &st, &io, &res).unwrap(); + let output = Container::parse(&shader.dxil).unwrap(); + let sig = super::signature(output.part(FourCC::ISG1).unwrap().data).unwrap(); + assert_eq!((sig[0].kind, sig[0].row, sig[0].cols), (28, None, 3)); + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut shader.dxil).unwrap(); + } + } + /// Emits a pixel program of `words` with these inputs and signatures. fn emit_pixel( words: &[u32], diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 7861589..826f43c 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -39,6 +39,7 @@ pub(crate) mod flags { pub const ROVS: u64 = 1 << 18; pub const WAVE_OPS: u64 = 1 << 19; pub const INT64: u64 = 1 << 20; + pub const BARYCENTRICS: u64 = 1 << 22; pub const ATOMIC64_TYPED: u64 = 1 << 27; pub const RESOURCE_HEAP: u64 = 1 << 30; pub const SAMPLER_HEAP: u64 = 1 << 31; @@ -113,6 +114,8 @@ pub(crate) struct Shader { pub nonuniform_handles: u32, /// A compute shader with this thread-group size. pub threads: Option<[u32; 3]>, + /// Compute sampling with implicit derivatives needs validator 1.8. + pub compute_derivatives: bool, /// The wave size a compute shader requires (`WaveSize`). pub wave_size: Option, /// Thread-group shared memory, in dwords. @@ -196,6 +199,7 @@ impl Shader { fused: false, nonuniform_handles: 0, threads: None, + compute_derivatives: false, wave_size: None, lds_dwords: 0, lds: None, @@ -885,7 +889,13 @@ impl Shader { let six = i32c(&mut self, 6); let version = self.m.md_node(vec![Some(one), Some(six)]); self.m.named_md("dx.version", vec![version]); - self.m.named_md("dx.valver", vec![version]); + let validator = if self.compute_derivatives { + let eight = i32c(&mut self, 8); + self.m.md_node(vec![Some(one), Some(eight)]) + } else { + version + }; + self.m.named_md("dx.valver", vec![validator]); // Program kinds: 0 pixel, 1 vertex, 2 geometry, 5 compute, 13 mesh. let (name, kind) = match (self.threads, self.pixel) { _ if self.mesh.is_some() => ("ms", 13u32), @@ -925,6 +935,9 @@ impl Shader { if self.flags & flags::INT64 != 0 { features |= 0x8000; } + if self.flags & flags::BARYCENTRICS != 0 { + features |= 0x2_0000; + } if self.flags & flags::RESOURCE_HEAP != 0 { features |= 0x200_0000; } @@ -946,6 +959,7 @@ impl Shader { self.outputs.iter().any(|o| o.kind == 3) }; let psv0 = container::psv(&Psv { + entry_name: self.compute_derivatives.then_some("main"), stage: kind as u8, flag: flag && self.threads.is_none(), inputs: &self.inputs,