Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions apps/victory/src/translate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ pub fn run(
) -> Result<()> {
let paths = crate::default_paths(paths)?;
let dll = validate.then(Validator::default_path).flatten();
let mut device_name: Option<String> = None;
if validate {
Validator::load(dll.as_deref()).map_err(anyhow::Error::msg)?;
println!(
Expand All @@ -169,15 +170,17 @@ pub fn run(
.map_or("dxil.dll".into(), |p| p.display().to_string())
);
}
if pipelines {
Host::new(false).map_err(anyhow::Error::msg)?;
}
let pairs: Vec<(String, String)> = std::env::var("VICTORY_PAIRS")
.unwrap_or_default()
.split(',')
.filter_map(|p| p.split_once('+'))
.map(|(v, p)| (v.trim().to_owned(), p.trim().to_owned()))
.collect();
if pipelines || !pairs.is_empty() {
Host::new(false)
.map(|h| device_name.insert(h.name))
.map_err(anyhow::Error::msg)?;
}
let kept = std::sync::Arc::new(Mutex::new(Vec::new()));
let threads =
jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get()));
Expand Down Expand Up @@ -270,8 +273,12 @@ pub fn run(
" {} emitted of {} mesh programs; {} validated, {} pipelines",
t.ms_emitted, t.ms_programs, t.ms_validated, t.ms_pipelines
);
if let Some(name) = &device_name {
println!("device {name}");
}
if !pairs.is_empty() {
let host = Host::new(false).map_err(anyhow::Error::msg)?;
device_name.get_or_insert(host.name.clone());
let kept = lock(&kept);
let find = |name: &str| kept.iter().find(|(l, _)| l.contains(name));
for (v, p) in &pairs {
Expand Down
114 changes: 111 additions & 3 deletions crates/victory-gpu/src/texture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,48 @@ pub(crate) struct Staging {
last: Mutex<Last>,
}

/// What a texture's staging buffer holds: the hash of the memory detiled
/// What a texture's staging buffer holds: the digest of the memory detiled
/// (memory not watched), or the write-watch asking it was detiled after,
/// with room to read the memory into.
#[derive(Default)]
struct Last {
hash: Option<blake3::Hash>,
hash: Option<u64>,
asked: u64,
read: Vec<u8>,
}

/// The digest `refresh_now` change-checks the texture's memory with, once
/// per submission when no write-watch covers it. It is not a hash anyone
/// stores or names: the only question it answers is "did these bytes
/// change", so it trades BLAKE3's exactness for memory speed. BLAKE3's
/// compute is several times the cost of the read it guards; this runs at
/// the speed of the read. A change that leaves the same digest happens
/// about one submission in 2^64 per texture, which no one will meet; a
/// stale texture would show as never-updated art, so anything cheaper
/// than a real comparison is the wrong trade.
fn digest(tiled: &[u8]) -> u64 {
// splitmix64 finalizers over 32-byte blocks with two independent
// lanes; the block length folds in so trails of zeros differ.
const P: u64 = 0x9E37_79B9_7F4A_7C15;
let mix = |x: u64| -> u64 {
let z = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
(z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB) ^ (z >> 31)
};
let (mut a, mut b) = (0x243F_6A88_85A3_08D3, 0x1319_8A2E_0370_7344 ^ P);
let (blocks, tail) = tiled.as_chunks::<32>();
for block in blocks {
let w = |i: usize| u64::from_le_bytes(block[8 * i..8 * i + 8].try_into().unwrap());
a = mix(a ^ w(0)).rotate_left(31) ^ w(1);
b = mix(b ^ w(2)).rotate_left(27) ^ w(3);
}
for (i, &byte) in tail.iter().enumerate() {
let lane = if i < 8 { &mut a } else { &mut b };
let shift = 8 * ((i % 8) as u32);
*lane = mix(*lane ^ (u64::from(byte) << shift));
}
mix(mix(a ^ b.rotate_left(32)) ^ tiled.len() as u64)
}

// SAFETY: the staging mapping is written only at submission, under
// `last`'s lock; the title memory is only read.
unsafe impl Send for Staging {}
Expand Down Expand Up @@ -213,7 +245,7 @@ impl Staging {
}
// SAFETY: committed memory of the texture's layout size.
let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) };
let hash = blake3::hash(tiled);
let hash = digest(tiled);
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexHashed, size as u64);
if last.hash == Some(hash) {
Expand Down Expand Up @@ -342,3 +374,79 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
map.insert(resource as usize, s.clone());
Some(s)
}

#[cfg(test)]
mod tests {
use super::digest;

fn fill(seed: u64, buf: &mut [u8]) {
let mut s = seed;
for b in buf.iter_mut() {
s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
*b = (s >> 33) as u8;
}
}

#[test]
fn is_deterministic_and_changes_with_any_byte() {
let mut a = vec![0_u8; 4096];
fill(1, &mut a);
assert_eq!(digest(&a), digest(&a));
let base = digest(&a);
for pos in 0..a.len() {
let old = a[pos];
a[pos] ^= 0xff;
assert_ne!(digest(&a), base, "a flip of byte {pos} was missed");
a[pos] = old;
}
}

#[test]
fn changes_with_any_sampled_bit_of_a_large_texture() {
let mut big = vec![0_u8; 1 << 20];
fill(2, &mut big);
let base = digest(&big);
for &pos in &[0, 1, 7, 8, 31, 4095, 1 << 19, (1 << 20) - 1] {
for bit in 0..8 {
big[pos] ^= 1 << bit;
assert_ne!(digest(&big), base, "a flip of bit {pos}:{bit} was missed");
big[pos] ^= 1 << bit;
}
}
}

#[test]
fn folds_in_length_and_trailing_zeros() {
assert_ne!(digest(&[0; 63]), digest(&[0; 64]));
assert_ne!(digest(&[0; 65]), digest(&[0; 64]));
let zeros = [0_u8; 1 << 20];
assert_ne!(digest(&zeros[..1 << 19]), digest(&zeros));
}

#[test]
fn is_independent_of_capacity() {
let mut a = vec![0_u8; 4096];
fill(1, &mut a);
let mut odd = a.clone();
odd.push(0x5a);
assert_eq!(digest(&odd[..4096]), digest(&a));
}

#[test]
fn every_rewrite_of_a_frame_registers() {
// A 64 KiB frame, rewritten one byte at a time 100,000 times: the
// change-check the digest serves must catch each one.
let mut frame = vec![0_u8; 65536];
fill(3, &mut frame);
let mut h = digest(&frame);
let mut s = 7_u64;
for _ in 0..100_000 {
let i = s % 65280;
s = s.wrapping_mul(6364136223846793005).wrapping_add(1);
frame[i as usize] ^= 0x01;
let n = digest(&frame);
assert_ne!(n, h, "a rewrite of byte {i} was missed");
h = n;
}
}
}
19 changes: 18 additions & 1 deletion crates/victory-shader/src/emit/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ use crate::dxbc::{Container, FourCC};

pub struct Host {
pub device: ID3D12Device,
/// The adapter backing the device, as DXGI names it: what verdicts
/// about this host speak of as "the GPU".
pub name: String,
}

/// What the stage declares that a pipeline must match.
Expand Down Expand Up @@ -78,6 +81,20 @@ impl Host {
D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?;
}
let device = device.ok_or("no device")?;
// SAFETY: plain DXGI queries; the closures run inside the
// unsafe block above.
// The device's own adapter, so the name is honest whether the
// default was picked or WARP was asked for.
let name = device
.cast::<IDXGIDevice>()
.and_then(|d| d.GetAdapter())
.and_then(|adapter| adapter.cast::<IDXGIAdapter1>())
.and_then(|adapter| adapter.GetDesc1())
.map_or("unknown adapter".to_owned(), |desc| {
String::from_utf16_lossy(&desc.Description)
.trim_end_matches('\0')
.to_owned()
});
let mut sm = D3D12_FEATURE_DATA_SHADER_MODEL {
HighestShaderModel: D3D_SHADER_MODEL_6_6,
};
Expand All @@ -94,7 +111,7 @@ impl Host {
sm.HighestShaderModel.0
));
}
Ok(Host { device })
Ok(Host { device, name })
}
}

Expand Down