From 257d8bbab241c096625ccca7ff24b8a551e3ab36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9rez?= Date: Tue, 24 Nov 2026 01:21:41 +0100 Subject: [PATCH 01/36] Audio: reduce the title's XMA read advance before adding it ADVANCE_XMA_READ added the title's block count to the 5-bit read block in u32 before taking it modulo the ring size, so a count near u32::MAX overflowed (a panic in debug builds). The count is reduced modulo the ring first; the result is the same for every count that did not overflow. Co-Authored-By: Claude Opus 5.5 --- crates/victory-hle/src/modules/audio.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/victory-hle/src/modules/audio.rs b/crates/victory-hle/src/modules/audio.rs index 0a11195..4bd223a 100644 --- a/crates/victory-hle/src/modules/audio.rs +++ b/crates/victory-hle/src/modules/audio.rs @@ -471,7 +471,8 @@ impl Xma { // The decoder writes the same words. let mut slot = lock(&self.voices[index as usize]); let size = context.field(0, 22, 5).max(1); - let read = (context.field(9, 0, 5) + blocks) % size; + // The count is the title's: reduced first, so the sum stays small. + let read = (context.field(9, 0, 5) + blocks % size) % size; context.set_field(9, 0, 5, read); if blocks > 0 { context.set_field(1, 31, 1, 1); @@ -1062,6 +1063,13 @@ mod tests { assert_eq!(context.field(0, 20, 2), 0, "input used up"); assert_eq!(context.field(2, 26, 5), INPUT_INVALID); + // A count near `u32::MAX` wraps the read block like any other + // (3 + 0xffff_ffff blocks on a ring of four is block 2); the sum + // used to overflow. + context.set_field(9, 0, 5, 3); + submit(ADVANCE_XMA_READ, &[1, u32::MAX]); + assert_eq!(context.field(9, 0, 5), 2); + submit(DISABLE_XMA, &[1]); assert_eq!(produced(&xma()), None); (m.release)(acp); From ec0d15592530c535bdb049aeb5831fe7b1ef80d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9rez?= Date: Tue, 24 Nov 2026 01:21:42 +0100 Subject: [PATCH 02/36] Watch: saturate the end of announced writes and remaps kernel_will_write (fread's size times count, saturated) and title_memory_remapped added the length to the address unchecked, so a huge fread count overflowed (a panic in debug builds). The end now saturates at the top of the address space. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/watch.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index a64e3e3..2012acd 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -210,7 +210,8 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { /// The runtime calls it (as `kernel_will_write`) before the title's kernel /// reads into its own memory. pub fn writing(at: usize, len: usize) { - open(&mut guards(), at, at + len); + // The length is the title's (`fread`'s size times count, saturated). + open(&mut guards(), at, at.saturating_add(len)); } /// The runtime mapped or unmapped title memory `[at, at + len)`: what it @@ -219,7 +220,7 @@ pub fn title_memory_remapped(at: usize, len: usize) { let mut g = guards(); let blocks: Vec = g .protected - .range(at / BLOCK..(at + len).div_ceil(BLOCK)) + .range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)) .copied() .collect(); for block in blocks { @@ -364,4 +365,14 @@ mod tests { unsafe { UnmapViewOfFile(windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) }; title_memory_remapped(view, 2 * BLOCK); } + + /// A write or mapping that runs past the end of the address space (a + /// title's `fread` with a huge count) covers up to the end; the sum used + /// to overflow. Up there no test has guarded blocks. + #[test] + fn ranges_past_the_address_space_end_do_not_overflow() { + let top = usize::MAX - 16; + writing(top, PAGE); + title_memory_remapped(top, usize::MAX); + } } From 3e982f7ec436003226c134315f993d2bf23b9286 Mon Sep 17 00:00:00 2001 From: TG0000 <122870448+TG0000@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:24:21 +0100 Subject: [PATCH 03/36] BCPack: find a slot's bucket from a window table Each rANS symbol scanned all of its model's bucket starts to find the slot's bucket, then rebuilt the symbol's frequency and start from the symbol. A per-model table of the bucket at each 256-slot window's first slot now starts the search, which steps over the few buckets that begin inside the window; the symbol, frequency and remainder come straight from that bucket. The lane loop also keeps the record offset instead of dividing by the symbols per block on every symbol. Synthetic streams, release, one core (median of 3 runs, 16384 blocks): BC1 177 -> 128 ns/block, BC4 184 -> 128, BC7 591 -> 452. Tests: the window lookup against the scan for every slot of every model (shipped tables, uniform tables, one-slot buckets); a payload step against the first version's arithmetic on the shipped tables; every format's lane layout round trips at 1 to 1000 blocks; an ignored throughput benchmark. Co-Authored-By: Claude Opus 5.5 --- crates/victory-formats/src/bcpack.rs | 251 ++++++++++++++++++++++++--- 1 file changed, 223 insertions(+), 28 deletions(-) diff --git a/crates/victory-formats/src/bcpack.rs b/crates/victory-formats/src/bcpack.rs index cb4ea53..360dce1 100644 --- a/crates/victory-formats/src/bcpack.rs +++ b/crates/victory-formats/src/bcpack.rs @@ -80,7 +80,12 @@ struct Bc7Ix { /// The format's constant tables. pub struct Tables { freq: [[u32; BUCKETS]; MODELS], - start: [[u32; BUCKETS]; MODELS], + /// Each bucket's first slot; 65536 past the model's last, and one more + /// 65536 at the end so a bucket always has a next start. + start: [[u32; BUCKETS + 1]; MODELS], + /// Per model, the bucket of the first slot of each 256-slot window: the + /// search for a slot's bucket starts there and seldom moves on. + bucket: Box<[[u8; 256]; MODELS]>, /// ceil(2^32 / freq): exact division for the offsets inside a bucket. recip: [[u64; BUCKETS]; MODELS], rank1: [u8; 256], @@ -132,7 +137,8 @@ impl Tables { } let mut r = Reader(bytes); let mut freq = [[0u32; BUCKETS]; MODELS]; - let mut start = [[0u32; BUCKETS]; MODELS]; + let mut start = [[0u32; BUCKETS + 1]; MODELS]; + let mut bucket = Box::new([[0u8; 256]; MODELS]); let mut recip = [[0u64; BUCKETS]; MODELS]; for m in 0..MODELS { for f in &mut freq[m] { @@ -153,6 +159,10 @@ impl Tables { return Err(Error("a model does not tile 65536")); } start[m][used..].fill(1 << 16); + for (window, b) in bucket[m].iter_mut().enumerate() { + let first = (window as u32) << 8; + *b = start[m][1..].iter().filter(|&&s| s <= first).count() as u8; + } } let rank1 = r.bytes(); let rank3a = r.bytes(); @@ -221,6 +231,7 @@ impl Tables { Ok(Tables { freq, start, + bucket, recip, rank1, rank3a, @@ -342,33 +353,20 @@ impl Lane { let start = &t.start[usize::from(self.model)]; let slot = x & 0xffff; // The bucket: starts are ascending, and 65536 past the model's last. - let b = start[1..].iter().filter(|&&s| s <= slot).count(); - // Buckets 0 and 1 hold one symbol. Elsewhere offset and frequency - // are below 2^16, where the reciprocal divides exactly. - let sym = match b { - 0 => 0, - 1 => 1, - _ => { - let rec = t.recip[usize::from(self.model)][b]; - (1 << (b - 1)) + ((u64::from(slot - start[b]) * rec) >> 32) as u8 - } - }; - // Slot 0 is never used: symbol 0 owns 1 .. f[0] - 1. - let (f, c) = if sym == 0 { - (freq[0] - 1, 1) + let b = bucket_of(t, self.model, slot); + // Bucket 0 holds symbol 0, which owns slots 1 .. f[0] - 1 (slot 0 + // is never used). Bucket b > 0 holds 2^(b-1) symbols of frequency + // f[b] from start[b] on; offset and frequency are below 2^16, where + // the reciprocal divides exactly. + let (sym, f, rem) = if b == 0 { + (0, freq[0] - 1, slot.wrapping_sub(1)) } else { - let k = (8 - sym.leading_zeros()) as usize; - let f = freq[k]; - ( - f, - (u32::from(sym) - (1 << (k - 1))) - .wrapping_mul(f) - .wrapping_add(start[k]) - & 0xffff, - ) + let offset = slot - start[b]; + let q = ((u64::from(offset) * t.recip[usize::from(self.model)][b]) >> 32) as u32; + ((1u32 << (b - 1)) + q, freq[b], offset - q * freq[b]) }; - self.x = (x >> 16).wrapping_mul(f).wrapping_sub(c).wrapping_add(slot); - self.out = Some(sym); + self.x = (x >> 16).wrapping_mul(f).wrapping_add(rem); + self.out = Some(sym as u8); } else if self.left != 0 { // At exactly 2^24 the lane neither reads nor decodes again; only a // lane that has delivered its symbols may end up there. @@ -385,6 +383,19 @@ impl Lane { } } +/// The bucket holding `slot` (below 65536): the last whose start is at or +/// below it. The window table gives the bucket of the window's first slot; +/// later buckets that start inside the window are stepped over. +#[inline] +fn bucket_of(t: &Tables, model: u8, slot: u32) -> usize { + let start = &t.start[usize::from(model)]; + let mut b = usize::from(t.bucket[usize::from(model)][(slot >> 8) as usize]); + while start[b + 1] <= slot { + b += 1; + } + b +} + /// Decodes `per` symbols per block on every lane into `records` (one record /// of `widths.len() * per` symbols per block), taking input from `fetch` /// (given the lane that takes the byte) in the order of the schedule: each @@ -409,6 +420,8 @@ fn lanes( let stride = widths.len() * per; let full = (1u32 << widths.len()) - 1; let (mut pos, mut done, mut idle) = (0, 0u32, 0); + // Where symbol `pos` of lane 0 goes; lane j's is `per * j` further on. + let mut at = 0; while pos < blocks * per { let (mut taken, mut moved) = (0, false); for (j, lane) in lanes.iter_mut().enumerate() { @@ -429,13 +442,18 @@ fn lanes( if !lane.stalled && let Some(sym) = lane.out.take() { - records[pos / per * stride + j * per + pos % per] = sym; + records[at + j * per] = sym; done |= bit; moved = true; } } if done == full { pos += 1; + at += if pos.is_multiple_of(per) { + stride - per + 1 + } else { + 1 + }; done = 0; moved = true; } @@ -1369,6 +1387,183 @@ mod tests { } } + /// The window table finds the bucket a scan of the starts finds, for + /// every slot of every model, in the shipped tables and in ours (whose + /// buckets are wide) and in tables whose buckets are one slot wide. + #[test] + fn bucket_lookup_matches_a_scan_of_the_starts() { + let mut narrow = tables(); + for m in 0..MODELS { + // Buckets 1.. of one slot each where they fit; bucket 0 takes the rest. + let used = m / 16 + 2; + let rest = (1u32 << 16) - (1..used).map(|b| 1u32 << (b - 1)).sum::(); + for b in 0..used { + let f = if b == 0 { rest } else { 1 }; + narrow[(m * BUCKETS + b) * 2..][..2].copy_from_slice(&(f as u16).to_le_bytes()); + } + } + for t in [ + Tables::builtin().unwrap(), + Tables::parse(&tables()).unwrap(), + Tables::parse(&narrow).unwrap(), + ] { + for model in 0..MODELS as u8 { + let start = &t.start[usize::from(model)]; + for slot in 0..1u32 << 16 { + let scan = start[1..].iter().filter(|&&s| s <= slot).count(); + assert_eq!( + bucket_of(&t, model, slot), + scan, + "model {model} slot {slot}" + ); + } + } + } + } + + /// One rANS decode as first written: scan for the bucket, divide for the + /// symbol, rebuild its frequency and start from the symbol. + fn reference_decode(t: &Tables, model: u8, x: u32) -> (u8, u32) { + let (freq, start) = (&t.freq[usize::from(model)], &t.start[usize::from(model)]); + let slot = x & 0xffff; + let b = start[1..BUCKETS].iter().filter(|&&s| s <= slot).count(); + let sym = match b { + 0 => 0, + 1 => 1, + _ => (1u32 << (b - 1)) + (slot - start[b]) / freq[b], + } as u8; + let (f, c) = if sym == 0 { + (freq[0] - 1, 1) + } else { + let k = (8 - sym.leading_zeros()) as usize; + let f = freq[k]; + ( + f, + ((u32::from(sym) - (1 << (k - 1))) * f + start[k]) & 0xffff, + ) + }; + ( + sym, + (x >> 16).wrapping_mul(f).wrapping_sub(c).wrapping_add(slot), + ) + } + + /// A payload step decodes the symbol and state the first version did, for + /// every model and slot of the shipped tables and ours, at assorted states. + #[test] + fn payload_step_matches_the_reference_decode() { + for t in [ + Tables::builtin().unwrap(), + Tables::parse(&tables()).unwrap(), + ] { + for model in 0..MODELS as u8 { + for high in [0x100u32, 0x1234, 0xffff] { + for slot in 0..1u32 << 16 { + let x = high << 16 | slot; + if x <= LOW { + continue; + } + let mut lane = Lane { + phase: 3, + model, + x, + left: 1, + ..Default::default() + }; + lane.step(&t).unwrap(); + let (sym, next) = reference_decode(&t, model, x); + assert_eq!( + (lane.out, lane.x), + (Some(sym), next), + "model {model} x {x:#x}" + ); + } + } + } + } + } + + /// Pseudo-random records that fit each lane's alphabet; BC7 keeps control + /// code 0 (mode 6), the only one the synthetic tables define. + fn random_records(widths: &[u8], per: usize, blocks: usize, bc7: bool) -> Vec> { + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + (0..blocks) + .map(|_| { + let mut r: Vec = (0..widths.len() * per) + .map(|k| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let alphabet = 1u32 << (widths[k / per] + 1); + (seed as u32 % alphabet) as u8 + }) + .collect(); + if bc7 { + r[30] = 0; + r[31] = 0; + } + r + }) + .collect() + } + + /// The fast paths decode exactly what one lane step at a time does, on + /// every format's lane layout, with short and long fragments. + #[test] + fn every_layout_round_trips_through_the_lanes() { + let t = Tables::parse(&tables()).unwrap(); + let layouts: [(&[u8], usize); 6] = [ + (&[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1), + (&[3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7], 2), + (&BC4_LANES, 1), + (&[3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 2), + (&[3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4], 2), + (&[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2), + ]; + for (widths, per) in layouts { + for blocks in [1, 2, 17, 300, 1000] { + let records = random_records(widths, per, blocks, false); + let src = stream(&t, widths, per, &records); + let mut got = vec![0u8; records.concat().len()]; + let mut next = src.iter().copied(); + lanes(&t, widths, per, blocks, |_| next.next(), &mut got).unwrap(); + assert_eq!(got, records.concat(), "{widths:?} x{per}, {blocks} blocks"); + } + } + } + + /// Decode throughput on synthetic streams (no game data): + /// `cargo test --release -p victory-formats bcpack_throughput -- --ignored --nocapture`. + #[test] + #[ignore = "benchmark"] + fn bcpack_throughput() { + let t = Tables::parse(&tables()).unwrap(); + let cases: [(u8, &[u8], usize, usize); 3] = [ + (1, &[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1, 8), + (4, &BC4_LANES, 1, 8), + (7, &[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2, 16), + ]; + for (bc, widths, per, block) in cases { + // One fragment per lane holds at most 65792 bytes. + let blocks = 1 << 14; + let records = random_records(widths, per, blocks, bc == 7); + let src = stream(&t, widths, per, &records); + let mut dst = vec![0u8; blocks * block]; + decode(bc, &src, &mut dst, &t).unwrap(); + let runs = 40; + let started = std::time::Instant::now(); + for _ in 0..runs { + decode(bc, std::hint::black_box(&src), &mut dst, &t).unwrap(); + } + let secs = started.elapsed().as_secs_f64() / f64::from(runs); + println!( + "BC{bc}: {blocks} blocks, {:.1} MB out/s, {:.1} ns/block", + (blocks * block) as f64 / secs / 1e6, + secs * 1e9 / blocks as f64 + ); + } + } + /// Compares with reference outputs made outside the repository: /// `VICTORY_BCPACK_TABLES` (the table file) and `VICTORY_BCPACK_CASES`, a /// directory of `.bc` packed chunks with `.out` beside them. From 376b3cf1785380cc397fdf89027f46e3472a6b55 Mon Sep 17 00:00:00 2001 From: marquezini Date: Mon, 23 Nov 2026 23:35:59 -0300 Subject: [PATCH 04/36] Storage: a path buffer too small fails with E_FAIL, as on Xbox XPersistentLocalStorageGetPath documents E_FAIL for a pathSize smaller than the path on Xbox devices; ERROR_INSUFFICIENT_BUFFER is the PC result, which put_string gave us. --- crates/victory-hle/src/modules/storage.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/victory-hle/src/modules/storage.rs b/crates/victory-hle/src/modules/storage.rs index c8863fb..585b641 100644 --- a/crates/victory-hle/src/modules/storage.rs +++ b/crates/victory-hle/src/modules/storage.rs @@ -38,6 +38,8 @@ pub const IID_2026: Guid = Guid::new( pub static OBJECT: Object = Object::new("persistent local storage", &VTABLE); pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT), (PROVIDER, IID_2026, &OBJECT)]; +const E_FAIL: HRESULT = 0x8000_4005_u32 as i32; + type This = *const Object; /// The path titles get: the root of a virtual drive over the folder. On the @@ -63,8 +65,11 @@ extern "system" fn path_size(_: This, out: *mut usize) -> HRESULT { } } +/// A buffer too small for the path fails with `E_FAIL`, the documented +/// Xbox result (a PC gets `ERROR_INSUFFICIENT_BUFFER`). extern "system" fn path(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { match folder() { + Some(path) if size <= path.len() => E_FAIL, Some(path) => put_string(&path, size, buffer, used), None => NOT_SUPPORTED, } @@ -196,6 +201,7 @@ mod tests { let (mut buffer, mut used) = ([0u8; 4], 0); let get = method::(&OBJECT, 0x20); assert_eq!(get(this, 4, buffer.as_mut_ptr(), &mut used), S_OK); + assert_eq!(get(this, 3, buffer.as_mut_ptr(), &mut used), E_FAIL); let drive = std::str::from_utf8(&buffer[..3]).unwrap(); assert!(drive.ends_with(":\\"), "{drive}"); // Title file calls on it reach the folder. From a4e7f1d004bff927c205981c623142c8e7dbb4a4 Mon Sep 17 00:00:00 2001 From: FIocker <4461558+FIocker@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:37:31 +0100 Subject: [PATCH 05/36] GPU: replay pending descriptors before publishing the host heap --- crates/victory-gpu/src/descriptor.rs | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 9ae83bd..20b33fb 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -85,15 +85,18 @@ impl Heap { return None; } let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); - let h = self - .host - .get_or_init(|| host::HostHeap::new(self.samplers(), self.desc.count)) - .as_ref()?; - let step = u64::from(increment(self.desc.kind)?); - for i in pending.drain(..) { - h.mirror(i, self.start + u64::from(i) * step, false); - } - Some(h) + // A recorder can take the fast path as soon as the OnceLock is + // initialized. Publish only after replaying the queued writes. + self.host + .get_or_init(|| { + let step = u64::from(increment(self.desc.kind)?); + let h = host::HostHeap::new(self.samplers(), self.desc.count)?; + for i in pending.drain(..) { + h.mirror(i, self.start + u64::from(i) * step, false); + } + Some(h) + }) + .as_ref() } /// The descriptor index of `handle` in this heap, if it lies in it. From 0f369d660c9e5ace8482f2f9cc5572c9805e9416 Mon Sep 17 00:00:00 2001 From: marquezini Date: Mon, 23 Nov 2026 23:37:46 -0300 Subject: [PATCH 06/36] Capture: R16G16B16A16_UNORM targets are integers, format 89 is 10:10:10:2 Frame dumps decoded DXGI format 11 (R16G16B16A16_UNORM) as half floats, so 0x8000 came out as -0 and 0xffff as -inf, and 12-14 were not handled. Format 89 (R10G10B10_XR_BIAS_A2_UNORM) went through the B8G8R8A8 swap. --- crates/victory-gpu/src/capture.rs | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index 28c2569..e91cf62 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -336,7 +336,8 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option } return Some(out); } - 87..=93 => { + // B8G8R8A8 and B8G8R8X8 (89 is R10G10B10_XR_BIAS_A2, below). + 87 | 88 | 90..=93 => { for y in 0..h { for x in 0..w { let p = px(x, y, 4); @@ -345,7 +346,7 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option } return Some(out); } - 23..=25 => (4, Box::new(move |b| { + 23..=25 | 89 => (4, Box::new(move |b| { let v = u32_at(b, 0); [(v & 0x3ff) as f32, (v >> 10 & 0x3ff) as f32, (v >> 20 & 0x3ff) as f32] })), @@ -353,7 +354,8 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option let v = u32_at(b, 0); [small_float(v & 0x7ff, 6), small_float(v >> 11 & 0x7ff, 6), small_float(v >> 22, 5)] })), - 9..=11 => (8, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))])), + 9..=10 => (8, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))])), + 11..=14 => (8, Box::new(move |b| [0, 1, 2].map(|i| f32::from(u16_at(b, i))))), 33..=34 => (4, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), 0.0])), 1..=2 => (16, Box::new(move |b| { [0, 1, 2].map(|i| f32::from_bits(u32_at(b, i))) @@ -522,4 +524,18 @@ mod tests { fn crc_matches_the_png_check_value() { assert_eq!(super::crc32(b"IEND"), 0xae42_6082); } + + /// R16G16B16A16_UNORM is integers, not half floats; 89 is 10:10:10:2, + /// not B8G8R8A8. + #[test] + fn unorm16_and_xr_bias_targets_decode_as_their_formats() { + // Red 0x8000 (a half-float -0), green 0x4000, blue 0. + let unorm16 = [0x00, 0x80, 0x00, 0x40, 0, 0, 0xff, 0xff]; + assert_eq!(super::to_rgba(11, 1, 1, 8, &unorm16), Some(vec![255, 127, 0, 255])); + // Red 0x3ff, green 0x1ff, blue 0, alpha 3. + let xr = (0x3ffu32 | 0x1ff << 10 | 3 << 30).to_le_bytes(); + assert_eq!(super::to_rgba(89, 1, 1, 4, &xr), Some(vec![255, 127, 0, 255])); + // B8G8R8A8 still swaps to RGBA. + assert_eq!(super::to_rgba(87, 1, 1, 4, &[1, 2, 3, 4]), Some(vec![3, 2, 1, 255])); + } } From ded334bb9172865a9be7acdb8a2047358a30e4db Mon Sep 17 00:00:00 2001 From: Luiz Neves Date: Mon, 23 Nov 2026 23:43:35 -0300 Subject: [PATCH 07/36] Shaders: lower v_cvt_norm_i16_f16 and v_cvt_norm_u16_f16 The f16 source (with abs/neg) is clamped to [-1, 1] or [0, 1], scaled by 32767 or 65535 and rounded to nearest even once from the exact product; NaN gives 0. The product is formed in integers from the f16's bits, because in f32 it has up to 26 significant bits and would round first. --- crates/victory-shader/src/emit/lower.rs | 81 ++++++++++++++++++++ crates/victory-shader/src/emit/valu_tests.rs | 46 +++++++++++ 2 files changed, 127 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..2147ce4 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4213,6 +4213,8 @@ impl<'a> Lower<'a> { "v_min_i16", "v_cvt_u16_f16", "v_cvt_i16_f16", + "v_cvt_norm_i16_f16", + "v_cvt_norm_u16_f16", ]; let all = [FLOAT1, FLOAT2, FLOAT3, INT]; if !all.iter().any(|l| l.contains(&name)) @@ -4351,6 +4353,13 @@ impl<'a> Lower<'a> { }; return float_result(self, r); } + if matches!(name, "v_cvt_norm_i16_f16" | "v_cvt_norm_u16_f16") { + if v.clamp || v.omod != 0 { + return Err("modifiers on a 16-bit integer operation"); + } + let r = self.cvt_norm16(inst, name == "v_cvt_norm_i16_f16")?; + return self.write_half(inst, r, guard); + } // 16-bit integers: computed on the low halves, the low 16 bits kept. if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 { return Err("modifiers on a 16-bit integer operation"); @@ -4415,6 +4424,78 @@ impl<'a> Lower<'a> { self.write_half(inst, r, guard) } + /// `v_cvt_norm_i16_f16` / `v_cvt_norm_u16_f16`: the f16 source (with its + /// abs/neg modifiers) clamped to [-1, 1] or [0, 1], times 32767 or 65535, + /// rounded to nearest even once from the exact product; NaN gives 0. + /// Worked on the f16's bits in integers, because in f32 the product + /// (up to 26 significant bits) would round before the rounding to an + /// integer. + fn cvt_norm16(&mut self, inst: &Inst, signed: bool) -> Result { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let c = self.cur; + let k = |l: &mut Self, x: u32| l.s.m.i32(x); + let mut h = self.half_src(inst, 0)?; + if v.abs & 1 != 0 { + let m = k(self, 0x7FFF); + h = self.s.m.bin(c, Bin::And, h, m); + } + if v.neg & 1 != 0 { + let m = k(self, 0x8000); + h = self.s.m.bin(c, Bin::Xor, h, m); + } + let scale = if signed { 0x7FFF } else { 0xFFFF }; + let (k0, k1, k10) = (k(self, 0), k(self, 1), k(self, 10)); + let mag_mask = k(self, 0x7FFF); + let mag = self.s.m.bin(c, Bin::And, h, mag_mask); + let k15 = k(self, 15); + let neg = self.s.m.bin(c, Bin::LShr, h, k15); + let neg = self.s.m.cmp(c, pred::NE, neg, k0); + // |x| < 1: x = m * 2^-s with m < 2^11 and 11 <= s <= 24. + let exp = self.s.m.bin(c, Bin::LShr, mag, k10); + let man_mask = k(self, 0x3FF); + let man = self.s.m.bin(c, Bin::And, mag, man_mask); + let implicit = k(self, 0x400); + let normal = self.s.m.bin(c, Bin::Or, man, implicit); + let sub = self.s.m.cmp(c, pred::EQ, exp, k0); + let m = self.s.m.select(c, sub, man, normal); + let k25 = k(self, 25); + let s_norm = self.s.m.bin(c, Bin::Sub, k25, exp); + let k24 = k(self, 24); + let sh = self.s.m.select(c, sub, k24, s_norm); + let ks = k(self, scale); + let p = self.s.m.bin(c, Bin::Mul, m, ks); + let q = self.s.m.bin(c, Bin::LShr, p, sh); + let one_s = self.s.m.bin(c, Bin::Shl, k1, sh); + let low_mask = self.s.m.bin(c, Bin::Sub, one_s, k1); + let rem = self.s.m.bin(c, Bin::And, p, low_mask); + let half = self.s.m.bin(c, Bin::LShr, one_s, k1); + let above = self.s.m.cmp(c, pred::IUGT, rem, half); + let tie = self.s.m.cmp(c, pred::EQ, rem, half); + let odd = self.s.m.bin(c, Bin::And, q, k1); + 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 r = self.s.m.select(c, up, k1, k0); + let r = self.s.m.bin(c, Bin::Add, q, r); + // |x| >= 1 (and infinity) saturates; NaN gives 0. + let one_h = k(self, 0x3C00); + let big = self.s.m.cmp(c, pred::IUGE, mag, one_h); + let r = self.s.m.select(c, big, ks, r); + let inf = k(self, 0x7C00); + let nan = self.s.m.cmp(c, pred::IUGT, mag, inf); + let r = self.s.m.select(c, nan, k0, r); + let r = if signed { + let n = self.s.m.bin(c, Bin::Sub, k0, r); + self.s.m.select(c, neg, n, r) + } else { + self.s.m.select(c, neg, k0, r) + }; + let m16 = k(self, 0xFFFF); + Ok(self.s.m.bin(c, Bin::And, r, m16)) + } + /// Half `high` of source `k` of a packed (VOP3P) operation, in the low /// 16 bits: op_sel picks the half the low result reads, op_sel_hi the /// half the high result reads. Inline float constants are f16 values. diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 1b95ca6..1cd4b16 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -420,6 +420,52 @@ fn v_fract_f16_never_returns_one() { }); } +/// RDNA2's flt16_to_snorm16 / flt16_to_unorm16: clamp, scale by 32767 or +/// 65535, round the exact product to nearest even; NaN gives 0. +fn cvt_norm16_reference(bits: u16, signed: bool) -> u16 { + let x = f16_to_f32(bits); + if x.is_nan() { + return 0; + } + let (lo, scale) = if signed { + (-1.0, 32767.0) + } else { + (0.0, 65535.0) + }; + // f64 holds the product of an f16 and a 16-bit scale exactly. + let p = f64::from(x.clamp(lo, 1.0)) * scale; + p.round_ties_even() as i32 as u16 +} + +#[test] +fn v_cvt_norm_i16_and_u16_f16_round_the_exact_product() { + // Every 251st f16 pattern, plus the values where an f32 product would + // round before the rounding to an integer, ties, and the edges. + let mut bits: Vec = (0..=u16::MAX).step_by(251).collect(); + bits.extend([ + 0x0000, 0x8000, 0x0001, 0x8001, 0x03FF, 0x0400, 0x3800, 0xB800, 0x3801, 0xB801, 0x37FF, + 0x3BFF, 0xBBFF, 0x3C00, 0xBC00, 0x3C01, 0x7BFF, 0x7C00, 0xFC00, 0x7E00, 0xFE00, 0x7C01, + 0x3A9B, 0xBA9B, 0x2E66, 0x1400, + ]); + for (op, signed, what) in [ + (0x063u16, true, "v_cvt_norm_i16_f16"), + (0x064, false, "v_cvt_norm_u16_f16"), + ] { + // v_cvt_norm_*16_f16 v0, v1 (VOP1); v0's high half starts at 0. + let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))]); + let inputs: Vec<[u32; 4]> = bits.iter().map(|&b| [u32::from(b), 0, 0, 0]).collect(); + run_cases(&shader, &inputs, |backend, i, _, got| { + let want = cvt_norm16_reference(bits[i], signed); + assert_eq!( + got, + u32::from(want), + "{backend}: {what}({:#06x}) = {got:#010x}, want {want:#06x}", + bits[i], + ); + }); + } +} + #[test] fn v_sin_and_v_cos_f32_reduce_large_turns() { let sin_shader = build_valu_cs(&[vop1(0x035, 0, vgpr(1))]); From 404d7fd9bd9ee4f1d1a54eca9e8fed369ae29f83 Mon Sep 17 00:00:00 2001 From: Duff <19514584+Dufftwt@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:38:51 +0100 Subject: [PATCH 08/36] Shaders: PSV0 says a pixel shader runs per sample when an input does The pipeline state validation part left PSInfo.SampleFrequency at 0. DXC sets it when a pixel input is interpolated per sample (modes 6 and 7, which our lowering gives to PERSP_SAMPLE and LINEAR_SAMPLE barycentrics) or is SV_SampleIndex, and the validator compares the whole runtime info with what it derives from the module. The flag is now set for such pixel shaders. --- crates/victory-shader/src/emit/container.rs | 9 +++ crates/victory-shader/src/emit/mod.rs | 76 +++++++++++++++++++++ 2 files changed, 85 insertions(+) diff --git a/crates/victory-shader/src/emit/container.rs b/crates/victory-shader/src/emit/container.rs index b0d30f9..8b05b12 100644 --- a/crates/victory-shader/src/emit/container.rs +++ b/crates/victory-shader/src/emit/container.rs @@ -161,6 +161,15 @@ pub(crate) fn psv(p: &Psv) -> Vec { u32s(&mut out, &[48]); let mut info = [0u8; 48]; info[0] = u8::from(p.flag); + if p.stage == 0 { + // PSInfo.SampleFrequency: an input interpolated per sample, or the + // sample index. + info[1] = u8::from( + p.inputs + .iter() + .any(|e| matches!(e.interp, 6 | 7) || e.kind == 12), + ); + } let (min, max) = p.wave_size.map_or((0, u32::MAX), |n| (n, n)); info[16..20].copy_from_slice(&min.to_le_bytes()); info[20..24].copy_from_slice(&max.to_le_bytes()); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 0df1233..88cae3e 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -540,6 +540,82 @@ mod tests { assert_eq!(c[4..20], ours[..], "our hash differs from the validator's"); } + /// A pixel shader interpolating at sample positions (PERSP_SAMPLE + /// barycentrics, `SPI_PS_INPUT_ADDR` bit 0) runs at sample frequency: + /// DXC's PSV0 says so in PSInfo.SampleFrequency (runtime info byte 1) + /// whenever an input is interpolated per sample. + #[test] + fn sample_interpolated_inputs_set_psv_sample_frequency() { + let words = [ + 0xC808_0000u32, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + 0xF800_180F, + 0x0202_0202, // exp mrt0, v2, v2, v2, v2 done vm + 0xBF81_0000, + ]; + let psv_of = |input_addr: u32| { + let native = super::NativeProgram { + stage: super::HwStage::Ps, + wave64: false, + vgprs: 4, + layout: vec![], + used: vec![], + io: crate::native::StageIo::Ps { + inputs: vec![crate::native::PsInput { + usage: crate::native::Usage::Generic, + row: 0, + mask: 0b1111, + attr: 0, + flat: false, + fp16: false, + pack2: false, + row2: 0, + }], + input_addr, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let el = |name: &str, kind, usage| SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage, + half: false, + }; + let isg1 = super::container::signature(&[el("TEXCOORD", 0, 0)], true); + let osg1 = super::container::signature(&[el("SV_Target", 16, 15)], false); + let bytes = + crate::dxbc::build(&[(super::FourCC::ISG1, &isg1), (super::FourCC::OSG1, &osg1)]); + let c = super::Container::parse(&bytes).unwrap(); + let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage).unwrap(); + let io = crate::io::raise(&p, &native).unwrap(); + let st = crate::structure::structure(&p).unwrap(); + let out = super::emit(&c, &native, &p, &st, &io, &res).unwrap(); + // dxil.dll, where there is one, checks PSV0 against the module. + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut out.dxil.clone()).unwrap(); + } + let host = super::Container::parse(&out.dxil).unwrap(); + host.part(super::FourCC::PSV0).unwrap().data.to_vec() + }; + // Runtime info starts after its size; PSInfo is {DepthOutput, SampleFrequency}. + let center = psv_of(1 << 1); + assert_eq!(center[4 + 1], 0, "center interpolation is per pixel"); + let sample = psv_of(1 << 0); + assert_eq!(sample[4 + 1], 1, "PSInfo.SampleFrequency"); + } + /// A pixel shader reading channel z of an input whose element starts at /// w. Looking the channel up subtracted the element's first channel /// before checking the channel lies in it, so in a build with overflow From c2f60d6bddc228c5be5feb6e08daccbf6c4e7f94 Mon Sep 17 00:00:00 2001 From: Duff <19514584+Dufftwt@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:39:58 +0100 Subject: [PATCH 09/36] Shaders: a pixel shader writing SV_StencilRef declares StencilRef exp mrtz's channel y is lowered to an SV_StencilRef output, but the module's shader flags never had StencilRef (bit 11) and SFI0 never had D3D_SHADER_FEATURE_STENCIL_REF (0x200). DXC sets both for a pixel shader whose output signature has the stencil reference, and the validator checks the flags against the module. Both are now set when a pixel shader outputs SV_StencilRef. --- crates/victory-shader/src/emit/mod.rs | 62 ++++++++++++++++++++++++ crates/victory-shader/src/emit/shader.rs | 8 +++ 2 files changed, 70 insertions(+) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 0df1233..a882f42 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -411,6 +411,68 @@ mod tests { use super::*; use crate::native::{ComputeIo, StageIo}; + /// A pixel shader writing SV_StencilRef (channel y of `exp mrtz`). + /// DXC sets ShaderFlags.StencilRef (bit 11) for a pixel shader whose + /// output signature has SV_StencilRef, and the feature bit + /// D3D_SHADER_FEATURE_STENCIL_REF (0x200) in SFI0; the validator checks + /// both against the module. + #[test] + fn a_stencil_export_declares_the_stencil_ref_feature() { + let words = [ + 0x7E00_02F2u32, // v_mov_b32 v0, 1.0 + 0x7E02_0285, // v_mov_b32 v1, 5 + 0xF800_1883, + 0x0000_0100, // exp mrtz v0, v1, off, off done vm + 0xBF81_0000, + ]; + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 2, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let el = |name: &str, kind, comp| SigElement { + name: name.into(), + index: 0, + kind, + comp, + interp: 0, + row: None, + col: 0, + cols: 1, + usage: 1, + half: false, + }; + let osg1 = + container::signature(&[el("SV_Depth", 17, 9), el("SV_StencilRef", 20, 5)], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + let out = emit(&c, &native, &p, &st, &io, &res).unwrap(); + // dxil.dll, where there is one, checks the flags against the module. + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut out.dxil.clone()).unwrap(); + } + let host = Container::parse(&out.dxil).unwrap(); + let sfi0 = host.part(FourCC::SFI0).unwrap().data; + let features = u64::from_le_bytes(sfi0.try_into().unwrap()); + assert_ne!(features & 0x200, 0, "SFI0 {features:#x}: no StencilRef"); + } + /// A wave64 compute program that writes only EXEC's high dword /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask is /// opaque and keyed by the unchanged low dword, so building its lane bit diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 8389c17..44a315a 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -16,6 +16,7 @@ pub const ROOT_CBV_SPACE: u32 = 1; /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. pub(crate) mod flags { pub const RAW_BUFFERS: u64 = 1 << 4; + pub const STENCIL_REF: u64 = 1 << 11; pub const TYPED_UAV_LOADS: u64 = 1 << 13; pub const WAVE_OPS: u64 = 1 << 19; pub const INT64: u64 = 1 << 20; @@ -471,6 +472,10 @@ impl Shader { } else { None }; + // A pixel shader with an SV_StencilRef output (as DXC collects it). + if self.pixel && self.outputs.iter().any(|o| o.kind == 20) { + self.flags |= flags::STENCIL_REF; + } // Entry properties: shader flags (tag 0), thread-group size (4), // wave size (11). let mut props = Vec::new(); @@ -549,6 +554,9 @@ impl Shader { dxil.extend(&bitcode); let mut features = 0u64; + if self.flags & flags::STENCIL_REF != 0 { + features |= 0x200; + } if self.flags & flags::TYPED_UAV_LOADS != 0 { features |= 0x800; } From 2af66ff1d8dbd7ccd7d87488a57e2caf37d065a1 Mon Sep 17 00:00:00 2001 From: Luiz Neves Date: Mon, 23 Nov 2026 23:49:01 -0300 Subject: [PATCH 10/36] Shaders: v_cvt_u16_f16 and v_cvt_i16_f16 saturate at 16 bits They went through a 32-bit conversion, so an f16 past the i16 range (32768 up to 65504) wrapped, and infinities and NaN were undefined. The value is now clamped in f32 to the 16-bit range first (every f16 is exact there) and NaN gives 0, as the hardware's conversions do. --- crates/victory-shader/src/emit/lower.rs | 19 +++++++--- crates/victory-shader/src/emit/valu_tests.rs | 40 ++++++++++++++++++++ 2 files changed, 53 insertions(+), 6 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..c6ee447 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4357,15 +4357,22 @@ impl<'a> Lower<'a> { } let r = match name { "v_cvt_u16_f16" | "v_cvt_i16_f16" => { - // shortcut: converted through 32 bits, so out-of-range values - // wrap instead of saturating at 16 bits. + // Toward zero, saturating at the 16-bit range (infinities + // included); NaN gives 0. Clamped in f32 first, where every + // f16 is exact, so the conversion never leaves i32's range. let a = self.half_fsrc(inst, 0)?; - let op = if name == "v_cvt_u16_f16" { - Cast::FpToUi + let (lo, hi) = if name == "v_cvt_u16_f16" { + (0.0f32, 65535.0f32) } else { - Cast::FpToSi + (-32768.0, 32767.0) }; - self.s.m.cast(c, op, a, i32t) + let (lo, hi) = (self.s.m.f32(lo.to_bits()), self.s.m.f32(hi.to_bits())); + let t = self.binary(35, a, lo); + let t = self.binary(36, t, hi); + let r = self.s.m.cast(c, Cast::FpToSi, t, i32t); + let nan = self.s.m.cmp(c, pred::UNO, a, a); + let z = self.s.m.i32(0); + self.s.m.select(c, nan, z, r) } _ => { let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?); diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 1b95ca6..d5882c1 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -520,6 +520,46 @@ fn v_sin_and_v_cos_f32_reduce_large_turns() { }); } +#[test] +fn v_cvt_u16_and_i16_f16_saturate() { + // v_mov_b32 v0, 0; v_cvt_u16_f16 / v_cvt_i16_f16 v0, v1 (VOP1 0x052 / 0x053). + let cases: &[(u16, u16, u16)] = &[ + // (f16 input, u16 result, i16 result) + (0x0000, 0, 0), // 0 + (0x8000, 0, 0), // -0 + (0x3E00, 1, 1), // 1.5 -> 1 (toward zero) + (0xBE00, 0, 0xFFFF), // -1.5 -> 0 / -1 + (0x57D0, 125, 125), // 125.0 + (0x7800, 32768, 32767), // 32768 saturates i16 + (0x77FF, 32752, 32752), // 32752, the largest f16 below 32768 + (0xF800, 0, 0x8000), // -32768 fits i16 + (0xF801, 0, 0x8000), // -32800 saturates i16 + (0x7BFF, 65504, 32767), // max finite f16 + (0xFBFF, 0, 0x8000), // -65504 + (0x7C00, 0xFFFF, 32767), // +inf + (0xFC00, 0, 0x8000), // -inf + (0x7E00, 0, 0), // NaN + (0xFE00, 0, 0), // -NaN + (0x0001, 0, 0), // smallest subnormal + ]; + for (op, what, pick) in [ + (0x052u16, "v_cvt_u16_f16", 0usize), + (0x053, "v_cvt_i16_f16", 1), + ] { + let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))]); + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| [u32::from(c.0), 0, 0, 0]).collect(); + run_cases(&shader, &inputs, |backend, i, _, got| { + let want = if pick == 0 { cases[i].1 } else { cases[i].2 }; + assert_eq!( + got, + u32::from(want), + "{backend}: {what}({:#06x}) = {got:#010x}, want {want:#06x}", + cases[i].0, + ); + }); + } +} + #[test] fn v_sin_and_v_cos_f16_reduce_large_turns() { let sin_shader = build_valu_cs(&[vop1(0x060, 0, vgpr(1))]); From ff8694a69a3444bbbbdc37668181708a87d5b5cc Mon Sep 17 00:00:00 2001 From: itsRevela Date: Mon, 23 Nov 2026 20:56:27 -0600 Subject: [PATCH 11/36] Window: keep Alt and F10 from freezing the title in menu mode Alt or F10 sends WM_SYSCOMMAND SC_KEYMENU, and the default handling runs a modal menu loop on the thread that owns the window, which is the title's. The title stops drawing and reading input until a key ends the loop, with nothing on screen to say so, and Grand Theft Auto VI aborts itself about half a minute later (the deliberate write to 0 at +0x23cf683). The window procedure now drops SC_KEYMENU, next to its SC_CLOSE handling. The mouse can still open the window menu. Co-Authored-By: Claude Opus 5.5 --- crates/victory-hle/src/modules/lifecycle.rs | 69 +++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/crates/victory-hle/src/modules/lifecycle.rs b/crates/victory-hle/src/modules/lifecycle.rs index 3e5e00f..4eb9649 100644 --- a/crates/victory-hle/src/modules/lifecycle.rs +++ b/crates/victory-hle/src/modules/lifecycle.rs @@ -174,6 +174,15 @@ extern "system" fn window_proc( end_title("window closed", Box::new(|| {})); return 0; } + // Alt or F10 puts a window into menu mode: the system runs a modal menu + // loop on the thread that owns the window, which is the title's. The + // title then stops (no frames, no input) until a key ends the loop, and + // nothing shows it, since the window has no menu bar; Grand Theft Auto + // VI aborts itself about half a minute later. A console has no window + // menu. The mouse still opens it from the title bar. + if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_KEYMENU as usize { + return 0; + } // SAFETY: the procedure `hook` stored, called the way the system would. unsafe { let title = wm::GetPropW(hwnd, TITLE_PROC); @@ -366,4 +375,64 @@ mod tests { wm::DestroyWindow(hwnd); } } + + thread_local! { + /// The system commands `recording` received, low four bits cleared. + static COMMANDS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + + /// Stands in for a title's procedure: notes system commands and acts + /// on none of them (no menu loop, no minimising). + extern "system" fn recording( + hwnd: HWND, + message: u32, + wparam: WPARAM, + lparam: LPARAM, + ) -> LRESULT { + if message == wm::WM_SYSCOMMAND { + COMMANDS.with(|c| c.borrow_mut().push(wparam & 0xFFF0)); + return 0; + } + // SAFETY: the system's default procedure, called as the system would. + unsafe { wm::DefWindowProcW(hwnd, message, wparam, lparam) } + } + + #[test] + fn the_keyboard_menu_never_reaches_the_title() { + let null = std::ptr::null_mut(); + let hwnd = CreateWindowExW( + 0, + w!("STATIC"), + w!("menu"), + 0, + 0, + 0, + 10, + 10, + null, + null, + null, + std::ptr::null(), + ); + assert!(!hwnd.is_null()); + // SAFETY: our window, owned by this thread, so each message is + // handled before SendMessageW returns. `recording` stands in for the + // title's procedure and the original is put back before the window + // is destroyed. + unsafe { + let title = wm::GetPropW(hwnd, TITLE_PROC); + wm::SetPropW(hwnd, TITLE_PROC, recording as *const () as *mut c_void); + let command = |c: u32, key: u8| { + wm::SendMessageW(hwnd, wm::WM_SYSCOMMAND, c as usize, LPARAM::from(key)) + }; + command(wm::SC_KEYMENU, 0); // Alt or F10 + command(wm::SC_KEYMENU, b' '); // Alt+Space + command(wm::SC_KEYMENU | 1, 0); // the low bits are the system's + command(wm::SC_MINIMIZE, 0); + wm::SetPropW(hwnd, TITLE_PROC, title); + wm::DestroyWindow(hwnd); + } + let seen = COMMANDS.with(|c| c.borrow().clone()); + assert_eq!(seen, [wm::SC_MINIMIZE as usize]); + } } From eb30a0d9f4f8aee0a287563406adc9de06377cfb Mon Sep 17 00:00:00 2001 From: Enzo Souza Duarte Date: Tue, 24 Nov 2026 00:09:56 -0300 Subject: [PATCH 12/36] GPU: write half subnormals from f32 rectangle outputs --- crates/victory-gpu/src/primitive.rs | 31 ++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs index c11c647..68ca037 100644 --- a/crates/victory-gpu/src/primitive.rs +++ b/crates/victory-gpu/src/primitive.rs @@ -127,7 +127,19 @@ fn f32_to_half(v: f32) -> u16 { return sign | 0x7c00; // too large: infinity } if exp <= 0 { - return sign; // too small: zero + if exp < -10 { + return sign; // below half the smallest subnormal: zero + } + // Half subnormals are `m * 2^-24`. An f32 in this range is still + // normal (exponent field >= 1), so its significand has the implicit + // leading 1; shift it into the half mantissa, rounding to even. + let sig = (1u32 << 23) | man; + let shift = (14 - exp) as u32; + let halfway = 1u32 << (shift - 1); + let q = sig >> shift; + let r = sig & ((1u32 << shift) - 1); + let m = q + u32::from(r > halfway || (r == halfway && (q & 1) != 0)); + return sign | m as u16; } sign | (exp as u16) << 10 | ((man + 0x1000) >> 13) as u16 } @@ -178,4 +190,21 @@ mod tests { assert_eq!(dst[..40], [&src[..], &src[..8], &src[16..]].concat()[..]); assert_eq!(dst[40..], vertex(4.0, 6.0)[..]); } + + /// `half_to_f32` reads subnormals, so an f16 rectangle output must be + /// able to write them back instead of flushing every one to zero. + #[test] + fn half_subnormals_convert_in_both_directions() { + assert_eq!(f32_to_half(2f32.powi(-24)), 0x0001); + assert_eq!(f32_to_half(-2f32.powi(-24)), 0x8001); + assert_eq!(f32_to_half(2f32.powi(-23)), 0x0002); + assert_eq!(f32_to_half(1023.0 * 2f32.powi(-24)), 0x03ff); + // Ties go to an even mantissa: 0/1 and 1/2. + assert_eq!(f32_to_half(2f32.powi(-25)), 0x0000); + assert_eq!(f32_to_half(3.0 * 2f32.powi(-25)), 0x0002); + // Below half the smallest subnormal, and normal values, are unchanged. + assert_eq!(f32_to_half(2f32.powi(-26)), 0x0000); + assert_eq!(f32_to_half(1.5), 0x3e00); + assert_eq!(half_to_f32(0x0001), 2f32.powi(-24)); + } } From 28c1b0735ce4230303e75c366dbd019934c0e1ce Mon Sep 17 00:00:00 2001 From: marquezini Date: Tue, 24 Nov 2026 00:12:40 -0300 Subject: [PATCH 13/36] XGameSave: a read result into a small buffer is E_GS_PROVIDED_BUFFER_TOO_SMALL XGameSaveReadBlobDataResult lists E_GS_PROVIDED_BUFFER_TOO_SMALL among its errors, and the synchronous read already returns it; the result passed on XAsyncGetResult's E_NOT_SUFFICIENT_BUFFER instead. --- crates/victory-hle/src/modules/xgamesave.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/victory-hle/src/modules/xgamesave.rs b/crates/victory-hle/src/modules/xgamesave.rs index 7282284..001c4b8 100644 --- a/crates/victory-hle/src/modules/xgamesave.rs +++ b/crates/victory-hle/src/modules/xgamesave.rs @@ -786,6 +786,11 @@ extern "system" fn read_result( ) -> HRESULT { let mut used = 0; let hr = xasync::XAsyncGetResult(block, (&raw const READ).cast(), size, out.cast(), &mut used); + // The documented error for a small buffer; the result stays for a + // retry with a larger one. + if hr == xasync::E_NOT_SUFFICIENT_BUFFER { + return BUFFER_TOO_SMALL; + } if hr < 0 { return hr; } @@ -1209,6 +1214,10 @@ mod tests { ); let mut buffer = vec![0u64; size.div_ceil(8)]; let mut count = 0; + assert_eq!( + read_result(this, &mut b, 8, buffer.as_mut_ptr().cast(), &mut count), + BUFFER_TOO_SMALL + ); assert_eq!( read_result(this, &mut b, size, buffer.as_mut_ptr().cast(), &mut count), S_OK From d5704aaac67201c0b3c47512b955a83526bb54bd Mon Sep 17 00:00:00 2001 From: Pedro Fortunato Date: Tue, 24 Nov 2026 00:13:10 -0300 Subject: [PATCH 14/36] fix(shader): lower dynamic v_perm_b32 without INT64 --- crates/victory-shader/src/emit/lower.rs | 107 +++++++++++++++++++++--- 1 file changed, 94 insertions(+), 13 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..84c1272 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4770,24 +4770,22 @@ impl<'a> Lower<'a> { _ => { // A computed selector: each byte picked at run time. let (a, b, sv) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); - let i64t = self.s.m.int(64); - self.s.flags |= flags::INT64; - let wa = self.s.m.cast(c, Cast::ZExt, a, i64t); - let wb = self.s.m.cast(c, Cast::ZExt, b, i64t); - let k32 = self.s.m.int_const(i64t, 32); - let wa = self.s.m.bin(c, Bin::Shl, wa, k32); - let both = self.s.m.bin(c, Bin::Or, wa, wb); let mut r = k(self, 0); for i in 0..4u32 { let (sh, ff) = (k(self, 8 * i), k(self, 0xFF)); let sel = self.s.m.bin(c, Bin::LShr, sv, sh); let sel = self.s.m.bin(c, Bin::And, sel, ff); - // Bytes 0-7 of {src0, src1}. - let k3 = k(self, 3); - let bits = self.s.m.bin(c, Bin::Shl, sel, k3); - let bits = self.s.m.cast(c, Cast::ZExt, bits, i64t); - let x = self.s.m.bin(c, Bin::LShr, both, bits); - let x = self.s.m.cast(c, Cast::Trunc, x, self.s.t.i32); + // Select a dword and a byte within it. + // Later selects handle codes 8 and above. + let four = k(self, 4); + let zero = k(self, 0); + let high = self.s.m.bin(c, Bin::And, sel, four); + let high = self.s.m.cmp(c, pred::NE, high, zero); + let word = self.s.m.select(c, high, a, b); + let three = k(self, 3); + let index = self.s.m.bin(c, Bin::And, sel, three); + let bits = self.s.m.bin(c, Bin::Shl, index, three); + let x = self.s.m.bin(c, Bin::LShr, word, bits); let mut byte = self.s.m.bin(c, Bin::And, x, ff); // 8-11: the sign of bytes 1, 3 of src1, then of src0. for (n, src, bit) in [(8, b, 15), (9, b, 31), (10, a, 15), (11, a, 31)] @@ -6630,6 +6628,89 @@ mod tests { } } + + fn perm_features(selector: u32) -> u64 { + // Synthetic compute shader: + // v0 is the thread ID and can supply a dynamic selector. + // Store the result in LDS to keep the permutation live. + let words = [ + 0x7E02_02FFu32, + 0x817F_34AB, + 0x7E04_02FF, + 0xFE01_56CD, + 0xD744_0003, + 257 | (258 << 9) | (selector << 18), + 0x3408_0082, + 0xD834_0000, + 0x0000_0304, + S_ENDPGM, + ]; + + let code: Vec = words.iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 1 << 15, + threads: [64, 1, 1], + }), + code, + }; + + let p = ir::build(&native.code, false, 256).unwrap(); + + assert!(p.blocks.iter() + .flat_map(|b| &b.insts) + .any(|i| i.name() == "v_perm_b32")); + + let res = resource::track( + &p, &native.layout, native.stage + ).unwrap(); + + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + + let emitted = lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }).unwrap(); + + let container = + crate::Container::parse(&emitted.dxil).unwrap(); + + let features = + container.part(crate::FourCC::SFI0).unwrap(); + + u64::from_le_bytes(features.data.try_into().unwrap()) + } + + #[test] + fn perm_constant_selector_needs_no_int64() { + assert_eq!(perm_features(128) & 0x8000, 0); + } + + #[test] + fn perm_dynamic_selector_needs_no_int64() { + assert_eq!( + perm_features(256) & 0x8000, + 0, + "dynamic v_perm_b32 must not require INT64" + ); + } + #[test] fn buffer_formats_by_number() { // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, From f0ee35e9dfc700faa528ee48d3d31dd0ef101315 Mon Sep 17 00:00:00 2001 From: marquezini Date: Tue, 24 Nov 2026 00:13:26 -0300 Subject: [PATCH 15/36] XGameSave: a full host disk is E_GS_OUT_OF_LOCAL_STORAGE, not the quota An update that fit the user's 256 MB quota but not the host disk failed with E_GS_QUOTA_EXCEEDED, which tells the player to delete saves. The documentation keeps the two apart: E_GS_OUT_OF_LOCAL_STORAGE is the device out of room and can come before the quota is reached. The disk check also no longer credits the blobs an update replaces, since the new version is written before the old one is removed. --- crates/victory-hle/src/modules/xgamesave.rs | 31 +++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/victory-hle/src/modules/xgamesave.rs b/crates/victory-hle/src/modules/xgamesave.rs index 001c4b8..ebf0968 100644 --- a/crates/victory-hle/src/modules/xgamesave.rs +++ b/crates/victory-hle/src/modules/xgamesave.rs @@ -393,6 +393,21 @@ fn remaining(root: &Path) -> u64 { .min(storage::disk_free(root)) } +/// Why an update writing `written` bytes, `replaced` of them over blobs it +/// replaces, does not fit: past the per-user quota (`used` bytes kept), or +/// past the host disk's `free` bytes, which is not the user's quota (the +/// new version is written before the old one goes, so nothing it replaces +/// counts there). +fn no_room(written: u64, replaced: u64, used: u64, free: u64) -> Option { + if written > QUOTA.saturating_sub(used) + replaced { + Some(QUOTA_EXCEEDED) + } else if written > free { + Some(OUT_OF_LOCAL_STORAGE) + } else { + None + } +} + fn io_error(dir: &Path, e: &std::io::Error) -> HRESULT { tracing::warn!(dir = %dir.display(), %e, "game save"); if e.kind() == std::io::ErrorKind::StorageFull { @@ -446,8 +461,9 @@ impl Update { changed.map(|(_, size)| size).sum() }); let root = self.dir.parent().unwrap_or(&self.dir); - if written as u64 > remaining(root) + replaced { - return QUOTA_EXCEEDED; + let free = storage::disk_free(root); + if let Some(hr) = no_room(written as u64, replaced, used_bytes(root), free) { + return hr; } let display = self.display.as_deref(); let display = display.or(current.as_ref().map(|v| v.display.as_str())); @@ -950,6 +966,17 @@ mod tests { } } + /// The per-user quota and the host disk fail with their own errors. + #[test] + fn a_full_disk_is_not_the_quota() { + let mb = 1 << 20; + assert_eq!(no_room(2 * mb, 0, 0, mb), Some(OUT_OF_LOCAL_STORAGE)); + assert_eq!(no_room(2 * mb, 0, QUOTA - mb, 100 * mb), Some(QUOTA_EXCEEDED)); + // Replacing a blob of the same size fits a full quota. + assert_eq!(no_room(mb, mb, QUOTA, 100 * mb), None); + assert_eq!(no_room(mb, 0, 0, mb), None); + } + fn update(root: &Path, display: &str, changes: &[(&str, Option<&str>)]) -> HRESULT { Update { name: "Slot".into(), From f4438b38f435bcd0434bb2352128b7482fb223a9 Mon Sep 17 00:00:00 2001 From: local Date: Mon, 23 Nov 2026 22:16:27 -0500 Subject: [PATCH 16/36] Shaders: reads of uninitialized SGPRs read as zero, as VGPRs do Compute programs read SGPRs the hardware does not initialize when two branches make the paths look like they allow a read before a write, even though the branch that skips the write does not reach the read. That stops translation with 'a hardware SGPR input is not supported' and drops the program's dispatches. ComputeIo::initialized_sgprs() counts the user SGPRs, the enabled system ones and the scratch wave offset. A read of a general SGPR (0..=105) at or above that count holds whatever the previous wave left, so no program can depend on its value: read it as zero, as unset VGPRs already are. Reserved registers (VCC, trap temporaries, M0, EXEC) keep their current handling. --- crates/victory-shader/src/emit/lower.rs | 10 +++++++- crates/victory-shader/src/io.rs | 7 ++++++ crates/victory-shader/src/native.rs | 31 +++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..f90a252 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -908,8 +908,16 @@ impl<'a> Lower<'a> { for &(reg, v) in &self.x.p.inputs { let val = match reg { Reg::S(_) if self.params.contains_key(&v) => continue, // loaded on first use - Reg::S(_) => match io_inputs.get(&v) { + Reg::S(n) => match io_inputs.get(&v) { Some(&input) => self.input(input), + // Above the SGPRs the hardware initializes, a register + // holds what the last wave left, so no program depends + // on it: a read the paths only seem to allow (a branch + // past the write, taken only with one past the read) + // reads zero, as VGPRs do. + None if n <= 105 && self.x.io.initialized_sgprs.is_some_and(|k| n >= k) => { + Val::I32(self.s.m.i32(0)) + } None => Val::Missing("a hardware SGPR input"), }, Reg::Scc => Val::Missing("SCC on entry"), diff --git a/crates/victory-shader/src/io.rs b/crates/victory-shader/src/io.rs index 0b7f45b..e3cbd60 100644 --- a/crates/victory-shader/src/io.rs +++ b/crates/victory-shader/src/io.rs @@ -182,6 +182,9 @@ pub struct Io { pub inputs: Vec<(Value, Input)>, pub interps: Vec<(Site, Interp)>, pub exports: Vec, + /// Compute: how many SGPRs the hardware initializes + /// ([`ComputeIo::initialized_sgprs`](crate::native::ComputeIo::initialized_sgprs)). + pub initialized_sgprs: Option, } /// Raises the I/O of `p`, built from `native`'s patched code. Fails for @@ -287,6 +290,10 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result { let mut io = Io { inputs: inputs.clone(), + initialized_sgprs: match &native.io { + StageIo::Cs(cs) => Some(cs.initialized_sgprs()), + _ => None, + }, ..Io::default() }; let defs: std::collections::HashMap = p diff --git a/crates/victory-shader/src/native.rs b/crates/victory-shader/src/native.rs index dd62c2f..4bdd39b 100644 --- a/crates/victory-shader/src/native.rs +++ b/crates/victory-shader/src/native.rs @@ -319,6 +319,15 @@ impl ComputeIo { (ids, take(10)) } + /// SGPRs the hardware initializes: the user SGPRs, the enabled system + /// ones, then the scratch wave offset when scratch is enabled (bit 0). + /// The ones above hold whatever the previous wave left. + pub fn initialized_sgprs(&self) -> u8 { + let (ids, info) = self.system_sgprs(); + let end = ids.into_iter().chain([info]).flatten().map(|s| s + 1).max(); + end.unwrap_or(0).max(self.user_sgprs()) + (self.rsrc2 & 1) as u8 + } + /// Thread id components in v0, v1, v2 (1 to 3). pub fn thread_id_vgprs(&self) -> u8 { (self.rsrc2 >> 11 & 3) as u8 + 1 @@ -948,6 +957,28 @@ mod tests { assert_eq!((cs.thread_id_vgprs(), cs.lds_bytes()), (3, 0)); } + #[test] + fn initialized_sgprs_covers_user_system_and_scratch() { + // 5 user SGPRs, group ids x and y (s5, s6), no scratch: s0..=s6. + let cs = ComputeIo { + rsrc2: 0x1098A, + threads: [16, 16, 1], + }; + assert_eq!(cs.initialized_sgprs(), 7); + // All three group ids after 6 user SGPRs, plus the info SGPR: s0..=s9. + let cs = ComputeIo { + rsrc2: 0x78C, + threads: [8, 8, 1], + }; + assert_eq!(cs.initialized_sgprs(), 10); + // The same with scratch enabled adds the wave offset: s0..=s10. + let cs = ComputeIo { + rsrc2: 0x78D, + threads: [8, 8, 1], + }; + assert_eq!(cs.initialized_sgprs(), 11); + } + #[test] fn reads_every_native_blob() { let es = xbch(&fssm(&[(HwStage::Es, &VS_CODE)])); From 1106f43efee58f3b218b9e9d1f0ca65da4b41b72 Mon Sep 17 00:00:00 2001 From: "r4." <192970269+r4tedx@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:18:27 +0200 Subject: [PATCH 17/36] Shader tests: run the VALU GPU tests one at a time `cargo test` now and then never finishes: the seven emit::valu_tests that run on the hardware adapter and on WARP start together on the test threads, none of their dispatches completes, and the test binary keeps one core busy until it is killed (the waits spin on the fence). Any other GPU test running at that moment is stuck with them. On an RTX 5070 with a Radeon iGPU, `valu_tests` alone in a loop on main d2a4bae: 3 of 30 runs hang. With `run_cases` behind a process-wide lock: 0 of 60, and the seven tests take under 7 s. The lock is poison-tolerant, so one failing test does not fail the rest. Co-Authored-By: Claude Fable 5.2 --- crates/victory-shader/src/emit/valu_tests.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 1b95ca6..b717c47 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -166,6 +166,11 @@ fn run_cases( cases: &[[u32; 4]], mut check: impl FnMut(&str, usize, [u32; 4], u32), ) { + // One test at a time: with these tests on the hardware adapter and WARP + // from several test threads at once, now and then none of their + // dispatches ever completes and the test binary hangs. + static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(()); + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); let mut ran = 0; for (label, warp) in [("hardware", false), ("warp", true)] { let Ok(host) = Host::new(warp) else { From bf84134b2be663608ad29abeae2fb05705c8fb39 Mon Sep 17 00:00:00 2001 From: Duff <19514584+Dufftwt@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:25:27 +0100 Subject: [PATCH 18/36] Shaders: maximums and minimums order -0 below +0, as RDNA2 does v_max_f32, v_min_f32, their three-operand and f16 forms and the packed v_pk_max_f16/v_pk_min_f16 were lowered to DXIL's FMax and FMin. DXIL specifies those as a compare and select, so with a -0 and a +0 either zero can come out, depending on the operand order and the host; RDNA2 orders -0 below +0, so max(-0, +0) is +0 and min(-0, +0) is -0 in either order. A -0 that should have been +0 then turns, say, a following reciprocal square root's +inf into -inf. A new helper keeps FMax/FMin for everything but two zeros, which it resolves by their sign bits. --- crates/victory-shader/src/emit/lower.rs | 47 ++++++++++++++------ crates/victory-shader/src/emit/valu_tests.rs | 26 +++++++++++ 2 files changed, 59 insertions(+), 14 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..2cbc0f3 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1337,6 +1337,25 @@ impl<'a> Lower<'a> { ) } + /// The hardware's maximum (`max`) or minimum of two floats: as DXIL's + /// FMax/FMin, but -0 orders below +0 (RDNA2 ISA, `v_max_f32`), where + /// the compare and select DXIL specifies gives either zero. + fn max_min(&mut self, max: bool, a: V, b: V) -> V { + let c = self.cur; + let r = self.binary(if max { 35 } else { 36 }, a, b); + let (ia, ib) = (self.as_int(a), self.as_int(b)); + let either = self.s.m.bin(c, Bin::Or, ia, ib); + let magnitude = self.s.m.i32(0x7FFF_FFFF); + let either = self.s.m.bin(c, Bin::And, either, magnitude); + let zero = self.s.m.i32(0); + let zeros = self.s.m.cmp(c, pred::EQ, either, zero); + // Of two zeros, +0 unless both are -0 (max), -0 unless neither (min). + let op = if max { Bin::And } else { Bin::Or }; + let sign = self.s.m.bin(c, op, ia, ib); + let signed = self.as_float(sign); + self.s.m.select(c, zeros, signed, r) + } + fn fmad(&mut self, a: V, b: V, c: V) -> V { self.s.op( self.cur, @@ -3673,8 +3692,8 @@ impl<'a> Lower<'a> { "v_subrev_f32" => self.s.m.bin(c, Bin::Sub, bb, a), "v_mul_f32" => self.s.m.bin(c, Bin::Mul, a, bb), "v_mul_legacy_f32" => self.legacy_mul(a, bb), - "v_max_f32" => self.binary(35, a, bb), - _ => self.binary(36, a, bb), + "v_max_f32" => self.max_min(true, a, bb), + _ => self.max_min(false, a, bb), }; float(self, r) } @@ -3724,12 +3743,12 @@ impl<'a> Lower<'a> { let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); let r = match name { "v_max3_f32" => { - let t = self.binary(35, a, bb); - self.binary(35, t, cc) + let t = self.max_min(true, a, bb); + self.max_min(true, t, cc) } "v_min3_f32" => { - let t = self.binary(36, a, bb); - self.binary(36, t, cc) + let t = self.max_min(false, a, bb); + self.max_min(false, t, cc) } _ => self.med3(a, bb, cc), }; @@ -4265,8 +4284,8 @@ impl<'a> Lower<'a> { "v_sub_f16" => self.s.m.bin(c, Bin::Sub, a, b), "v_subrev_f16" => self.s.m.bin(c, Bin::Sub, b, a), "v_mul_f16" => self.s.m.bin(c, Bin::Mul, a, b), - "v_max_f16" => self.binary(35, a, b), - _ => self.binary(36, a, b), + "v_max_f16" => self.max_min(true, a, b), + _ => self.max_min(false, a, b), }; return float_result(self, r); } @@ -4296,12 +4315,12 @@ impl<'a> Lower<'a> { // product is exact; the sum rounds twice). "v_fma_f16" | "v_fmac_f16" | "v_mad_f16" | "v_mac_f16" => self.fmad(a, b, acc), "v_max3_f16" => { - let t = self.binary(35, a, b); - self.binary(35, t, acc) + let t = self.max_min(true, a, b); + self.max_min(true, t, acc) } "v_min3_f16" => { - let t = self.binary(36, a, b); - self.binary(36, t, acc) + let t = self.max_min(false, a, b); + self.max_min(false, t, acc) } _ => self.med3(a, b, acc), }; @@ -4487,8 +4506,8 @@ impl<'a> Lower<'a> { let mut f = match op { "add_f16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]), "mul_f16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]), - "min_f16" => self.binary(36, xs[0], xs[1]), - "max_f16" => self.binary(35, xs[0], xs[1]), + "min_f16" => self.max_min(false, xs[0], xs[1]), + "max_f16" => self.max_min(true, xs[0], xs[1]), // shortcut: FMad in f32, as v_fma_f16. _ => self.fmad(xs[0], xs[1], xs[2]), }; diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 1b95ca6..70d7530 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -279,6 +279,32 @@ fn v_med3_f32_matches_rdna2_with_nan() { }); } +/// RDNA2 orders -0 below +0 in its maximums and minimums; DXIL's FMax and +/// FMin compare and select, which can give either zero. +#[test] +fn max_and_min_order_negative_zero_below_positive_zero() { + let (pz, nz) = (0_u32, 0x8000_0000_u32); + // Each case has a -0 and a +0 among its first two operands. + let cases = [ + [nz, pz, nz, 0], + [pz, nz, nz, 0], + [nz, pz, pz, 0], + [pz, nz, pz, 0], + ]; + let ops = [ + ("v_max_f32", 0x110, pz), + ("v_min_f32", 0x10F, nz), + ("v_max3_f32", 0x154, pz), + ("v_min3_f32", 0x151, nz), + ]; + for (name, op, want) in ops { + let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), vgpr(3))); + run_cases(&shader, &cases, |backend, _, inp, got| { + assert_eq!(got, want, "{backend}: {name} {inp:x?}"); + }); + } +} + #[test] fn v_med3_f16_matches_rdna2_with_nan() { // v_med3_f16 v0, v1, v2, v3 (VOP3 opcode 0x357) From c249f02dd5d933537195c668d8082d82a9e50efa Mon Sep 17 00:00:00 2001 From: Saitken91 <98485913+SAitken91@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:01:02 -0600 Subject: [PATCH 19/36] Shaders: centroid position with conservative depth Pixel programs that write SV_DepthLessEqual or SV_DepthGreaterEqual failed validation: "Interpolation mode for PS input position must be linear_noperspective_centroid or linear_noperspective_sample when outputting oDepthGE or oDepthLE". The position is now declared linear_noperspective_centroid in those programs, as DXC declares it; without multisampling the value is the same. translate --validate on shaders.rpf: vertex/pixel 12172 -> 12186 validated; the error is gone from the list. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/mod.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 0df1233..66466eb 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -241,6 +241,13 @@ pub fn emit( _ => 0, }; } + // With a conservative depth output (SV_DepthLessEqual, GreaterEqual) DXIL + // wants the position centroid (or per sample), as DXC declares it then. + if pixel && outputs.iter().any(|e| matches!(e.kind, 18 | 19)) { + for e in inputs.iter_mut().filter(|e| e.kind == 3) { + e.interp = 5; + } + } // Per-primitive outputs are constant. The console never exports a // primitive id or cull flag a mesh shader writes (it culls with the // primitive export), so those rows are left out. From 9a8908c3786206a669d5fbc3bbdbe2d534354fe2 Mon Sep 17 00:00:00 2001 From: Advait Palve Date: Tue, 24 Nov 2026 10:56:01 +0530 Subject: [PATCH 20/36] core: show data_dir in config and check its asset policy 'victory config' displays game_dir, cache_dir, and test_titles, but omitted data_dir (where saves, persistent local storage, and crashes.log are stored). It also omitted data_dir from the runtime asset-policy check loop in show_config(). Include data_dir in the output and policy check, and add a unit test in victory-core asserting that a data_dir inside the repository is refused. --- apps/victory/src/main.rs | 3 ++- crates/victory-core/src/config.rs | 10 ++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index 31392ff..4cf7c31 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -180,6 +180,7 @@ fn show_config() -> Result<()> { ); println!("game_dir : {}", status(&cfg.game_dir)); println!("cache_dir : {}", cfg.cache_dir.display()); + println!("data_dir : {}", cfg.data_dir.display()); for t in &cfg.test_titles { println!("test_title : {}", status(&Some(t.clone()))); } @@ -187,7 +188,7 @@ fn show_config() -> Result<()> { .game_dir .iter() .chain(&cfg.test_titles) - .chain([&cfg.cache_dir]) + .chain([&cfg.cache_dir, &cfg.data_dir]) { if let Err(e) = victory_core::ensure_outside_repo(p) { println!("POLICY VIOLATION: {e}"); diff --git a/crates/victory-core/src/config.rs b/crates/victory-core/src/config.rs index 596aa43..9e55eb8 100644 --- a/crates/victory-core/src/config.rs +++ b/crates/victory-core/src/config.rs @@ -181,4 +181,14 @@ mod tests { }; assert!(cfg.cache_subdir("x").is_err()); } + + #[test] + fn data_inside_repo_is_refused() { + let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("data"); + let cfg = Config { + data_dir: inside, + ..Default::default() + }; + assert!(cfg.data_subdir("x").is_err()); + } } From 25b0f888cab67fc3653c7e17257075ff4c8e932a Mon Sep 17 00:00:00 2001 From: Dathinel <221246794+Dathinel@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:25:14 -0500 Subject: [PATCH 21/36] Test probe: compare direct and joined reads of a shader timestamp (cherry picked from commit 4b2ea70f0940a4317dc934000d249dce0fce50f6) --- crates/victory-shader/src/emit/lower.rs | 37 ++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..8b8302a 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -6565,8 +6565,8 @@ mod tests { const S_ENDPGM: u32 = 0xBF81_0000; - /// Lowers a compute program of constants: whether it translates. - fn lowers(words: &[u32]) -> Result<(), crate::ShaderError> { + /// Whether a synthetic compute program translates with these input registers. + fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> { let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let native = NativeProgram { stage: HwStage::Cs, @@ -6575,7 +6575,7 @@ mod tests { layout: vec![], used: vec![], io: StageIo::Cs(ComputeIo { - rsrc2: 0, + rsrc2, threads: [1, 1, 1], }), code, @@ -6626,10 +6626,39 @@ mod tests { S_ENDPGM, ]; for words in [add, sub] { - lowers(&words).unwrap(); + lowers(&words, 0).unwrap(); } } + #[test] + fn a_missing_value_stays_missing_through_two_live_joins() { + let mut words = [ + 0xF490_0180, + 0, // s_memtime s[6:7] + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) + 0xBF85_0001, // skip the first overwrite + 0xBE86_0380, // s_mov_b32 s6, 0 + 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y) + 0xBF85_0001, // skip the second overwrite + 0xBE86_0381, // s_mov_b32 s6, 1 + 0xBF07_8006, // s_cmp_lg_u32 s6, 0 + 0xBF85_0001, // use the result to branch + 0xBE83_0380, + S_ENDPGM, + ]; + let group_ids_xy = 3 << 7; + // Compare to a direct read so future timestamp support works in both cases. + let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { + Ok(()) => None, + Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), + Err(error) => panic!("{error}"), + }; + let direct = [&words[..2], &words[8..]].concat(); + assert_eq!(refusal(&words), refusal(&direct)); + words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead + lowers(&words, group_ids_xy).expect("dead timestamp"); + } + #[test] fn buffer_formats_by_number() { // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, From 3dd467ccee8d6612fa41aa17537c0b182477ceac Mon Sep 17 00:00:00 2001 From: KoLolX3 <94136289+KoLolX3@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:36:08 -0800 Subject: [PATCH 22/36] Shaders: a phi that only another read phi consumes is live too fill_phis treats a phi no one read directly as dead and fills a value with no DXIL form (an unsupported s_memtime result, say) with zero. When that value reaches a read through two joins, the first phi is only read by the second, so it was never marked read: the read lowered with a zero where the same value read directly is refused with "a scalar memory read as data". Mark the incoming phis of every read phi as read, transitively, before the phis are filled. The reproducer from #604 now agrees for the direct and the joined read, and the dead control (the timestamp replaced by a group id) still lowers. --- crates/victory-shader/src/emit/lower.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 8b8302a..c22339d 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -6508,6 +6508,20 @@ impl<'a> Lower<'a> { fn fill_phis(&mut self) -> Result<(), Stop> { let p = self.x.p; + // A phi that only another read phi consumes is live too. Without this, a value with no DXIL form that + // reaches a read through two joins is taken for dead at the first join and replaced by zero below, and the + // lowering accepts what it refuses when the same value is read directly. + let mut work: Vec = self.read_phis.iter().copied().collect(); + while let Some(v) = work.pop() { + let Some(&(b, i)) = self.phi_at.get(&v) else { + continue; + }; + for &arg in &p.blocks[b].phis[i].args { + if self.phi_at.contains_key(&arg) && self.read_phis.insert(arg) { + work.push(arg); + } + } + } for (v, b, i) in std::mem::take(&mut self.data_phis) { let phi = &p.blocks[b].phis[i]; let bit = phi.reg == Reg::Scc; From 260611acaaf5ea33748e4d74986aee500e254353 Mon Sep 17 00:00:00 2001 From: Saitken91 <98485913+SAitken91@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:58:14 -0600 Subject: [PATCH 23/36] Shaders: image_sample_o with constant offsets image_sample_o was refused by name. Its offset dword (x in bits 0-5, y in 8-13, z in 16-21, signed) becomes sample's immediate offsets when it is a constant within DXIL's -8..7; a computed or wider offset is still refused, now saying so. Module::int_value reads an integer constant. translate --validate on shaders.rpf: vertex/pixel 12172 -> 12176 validated (all four). Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/bitcode.rs | 11 +++++++++++ crates/victory-shader/src/emit/lower.rs | 21 ++++++++++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index 8b555ad..c96fefa 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -291,6 +291,17 @@ impl Module { self.constant(ty, Const::Aggregate(ids)) } + /// The value of an integer constant; `None` for anything else. + pub fn int_value(&self, v: V) -> Option { + match v { + V::Const(i) => match self.consts[i as usize].1 { + Const::Int(x) => Some(x), + _ => None, + }, + _ => None, + } + } + /// Gives constant `old` the content of `new` (both stay valid). pub fn replace_const(&mut self, old: V, new: V) { if let (V::Const(o), V::Const(n)) = (old, new) { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..0c3b903 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -5425,7 +5425,7 @@ impl<'a> Lower<'a> { return Ok(()); } let (op, sample) = match name { - "image_sample" => (60, true), + "image_sample" | "image_sample_o" => (60, true), "image_sample_lz" | "image_sample_l" => (62, true), "image_sample_b" => (61, true), "image_sample_c_lz" => (65, true), @@ -5570,6 +5570,25 @@ impl<'a> Lower<'a> { args.extend(&cs); match op { 60 => { + if offset_word { + // DXIL takes immediate offsets in -8..=7; the + // console's are 6-bit and may be computed. + let w = addr_val(self, 0)?; + let w = self + .s + .m + .int_value(w) + .ok_or("a sample offset that is not constant")? + as u32; + for (k, o) in os.iter_mut().enumerate().take(offsets) { + let x = (w >> (8 * k) & 0x3F) as i32; + let x = if x >= 32 { x - 64 } else { x }; + if !(-8..=7).contains(&x) { + return Err("a sample offset past -8..7"); + } + *o = self.s.m.i32(x as u32); + } + } args.extend(&os); args.push(fu); self.s From a0efd2d37709f9e7c3774b64a3a06ab616a643ba Mon Sep 17 00:00:00 2001 From: AlanQiang0418 Date: Tue, 24 Nov 2026 01:01:55 -0500 Subject: [PATCH 24/36] Shaders: decode GFX10 packed inline constants by operand type --- crates/victory-shader/src/emit/lower.rs | 45 +++++++++++--------- crates/victory-shader/src/emit/valu_tests.rs | 21 +++++++++ 2 files changed, 45 insertions(+), 21 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..673a1ce 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1210,6 +1210,19 @@ impl<'a> Lower<'a> { } } + /// GFX10 puts an inline f16 constant in the low half of the operand. + fn f16_operand(&mut self, inst: &Inst, op: &Operand) -> Result { + match *op { + Operand::Const(c @ 240..=248) => { + let h = [ + 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118, + ][usize::from(c - 240)]; + Ok(self.s.m.i32(h)) + } + _ => self.operand(inst, op), + } + } + fn as_float(&mut self, x: V) -> V { self.s.m.cast(self.cur, Cast::Bitcast, x, self.s.t.f32) } @@ -4078,15 +4091,9 @@ impl<'a> Lower<'a> { _ => return Err("a byte select on a 16-bit operation"), } } - let x = match (op, self.src0) { - (_, Some(x)) if k == 0 => x, - (Operand::Const(c @ 240..=248), _) => { - let h = [ - 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118, - ][usize::from(c - 240)]; - self.s.m.i32(h) - } - _ => self.operand(inst, &op)?, + let x = match self.src0 { + Some(x) if k == 0 => x, + _ => self.f16_operand(inst, &op)?, }; let c = self.cur; let x = if high { @@ -4417,22 +4424,18 @@ impl<'a> Lower<'a> { /// Half `high` of source `k` of a packed (VOP3P) operation, in the low /// 16 bits: op_sel picks the half the low result reads, op_sel_hi the - /// half the high result reads. Inline float constants are f16 values. - fn packed_src(&mut self, inst: &Inst, k: usize, high: bool) -> Result { + /// half the high result reads. Packed integer instructions see the f32 + /// bits of an inline float constant. + fn packed_src(&mut self, inst: &Inst, k: usize, high: bool, float: bool) -> Result { let Fields::Valu(v) = &inst.fields else { unreachable!() }; let op = *v.src.get(k).ok_or("a missing operand")?; let sel = if high { v.opsel_hi } else { v.opsel } >> k & 1 != 0; - let x = match op { - Operand::Const(c @ 240..=248) => { - let h = [ - 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118, - ][usize::from(c - 240)]; - // shortcut: taken to fill both halves. - self.s.m.i32(h | h << 16) - } - _ => self.operand(inst, &op)?, + let x = if float { + self.f16_operand(inst, &op)? + } else { + self.operand(inst, &op)? }; let c = self.cur; let x = if sel { @@ -4468,7 +4471,7 @@ impl<'a> Lower<'a> { for high in [false, true] { let mut xs = Vec::new(); for k in 0..n { - let h = self.packed_src(inst, k, high)?; + let h = self.packed_src(inst, k, high, float)?; if float { let mut f = self .s diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 1b95ca6..6c5e09c 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -231,6 +231,27 @@ fn f16_to_f32(bits: u16) -> f32 { f32::from_bits(f32_bits) } +#[test] +fn packed_add_selects_halves_of_inline_constants() { + // Add the inline constant 1/(2*pi) to v1 (zero) to read back its two halves. + // The same GFX10 source field (248) has a different bit pattern for a + // packed floating-point and a packed integer instruction. + let cases = [ + // v_pk_add_f16 v0, 0x3118, v1 + ([0xcc0f4000, 0x1a0202f8], 0x0000_3118), + // v_pk_add_f16 v0, 0x3118, v1 op_sel_hi:[0,1] (use low twice) + ([0xcc0f4000, 0x120202f8], 0x3118_3118), + // v_pk_add_u16 v0, 0x3e22f983, v1 + ([0xcc0a4000, 0x1a0202f8], 0x3e22_f983), + ]; + for (words, expected) in cases { + let shader = build_valu_cs(&words); + run_cases(&shader, &[[0; 4]], |backend, _, _, got| { + assert_eq!(got, expected, "{backend}: {words:08x?}"); + }); + } +} + #[test] fn v_med3_f32_matches_rdna2_with_nan() { // v_med3_f32 v0, v1, v2, v3 (VOP3 opcode 0x157) From d74558c4fc715d1be6731013e9644cbc43d70565 Mon Sep 17 00:00:00 2001 From: Carlos Sant'Anna Date: Tue, 24 Nov 2026 03:14:58 -0300 Subject: [PATCH 25/36] GPU diagnostics: describe a buffer UAV by its range, not as uav None describe looked only for a host texture, so every UAV over a buffer printed 'uav None' in device-removed reports and drop traces, though the view is made. It now prints the buffer's title range, as a buffer shader view does. --- crates/victory-gpu/src/draw.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index b6e043b..5b043a9 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1131,7 +1131,11 @@ fn describe(view: Option<&View>) -> String { None => "no view".into(), Some(v @ View::Shader(r, _)) => texture(*r as This) .unwrap_or_else(|| format!("buffer {:?}", crate::descriptor::host::buffer_range(v))), - Some(View::Unordered(r, ..)) => format!("uav {:?}", texture(*r as This)), + // 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( + || format!("uav buffer {:?}", crate::descriptor::host::buffer_range(v)), + |t| format!("uav {t}"), + ), Some(View::Placed(u, r, d)) => format!( "placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}", r[0], From 764fa19373e0e03cad31804a13290656465bcacc Mon Sep 17 00:00:00 2001 From: lameloball2813-ui <293005050+lameloball2813-ui@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:24:49 -0700 Subject: [PATCH 26/36] Loader tests: build the probe fixture under CARGO_TARGET_TMPDIR --- crates/victory-loader/tests/load_probe.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/victory-loader/tests/load_probe.rs b/crates/victory-loader/tests/load_probe.rs index 6d75d23..cf1111b 100644 --- a/crates/victory-loader/tests/load_probe.rs +++ b/crates/victory-loader/tests/load_probe.rs @@ -20,11 +20,12 @@ fn workspace_root() -> PathBuf { } /// Builds the fixture into its own target dir (the outer cargo holds the -/// lock on the main one while tests run). +/// lock on the main one while tests run), in the outer one's scratch folder +/// for tests, so that it follows `CARGO_TARGET_DIR` like the rest of the +/// build. fn build_probe() -> PathBuf { - let root = workspace_root(); - let manifest = root.join("tests/fixtures/hle-probe/Cargo.toml"); - let target = root.join("target/fixtures"); + let manifest = workspace_root().join("tests/fixtures/hle-probe/Cargo.toml"); + let target = Path::new(env!("CARGO_TARGET_TMPDIR")).join("hle-probe"); let status = Command::new(env!("CARGO")) .args(["build", "--quiet", "--manifest-path"]) .arg(&manifest) From 0064c088d216cc2ba24759b80ca63e90dcfbdcd9 Mon Sep 17 00:00:00 2001 From: fuzeofficial Date: Tue, 24 Nov 2026 15:30:02 +0900 Subject: [PATCH 27/36] GPU: upload CPU-written textures before CopyResource --- crates/victory-gpu/src/list.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 78d6d73..db13bfd 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -446,6 +446,9 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { crate::resource::host_resource(dst), crate::resource::host_resource(src), ) { + if crate::texture::title_written(from) { + crate::texture::upload(list, src, from); + } ensure_state(list, dst, COPY_DEST); ensure_state(list, src, COPY_SOURCE); crate::texture::host_written(dst); From af22e5d3a12c49a3fccc6812b06260715edcab70 Mon Sep 17 00:00:00 2001 From: EatCodeSleep2 <52021568+EatCodeSleep2@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:34:34 -0800 Subject: [PATCH 28/36] GPU: use the host upload path for texture staging copies Queue the list-owned D3D12 staging upload as a host fill so Wine does not skip it based on the title-memory VirtualQuery check. --- crates/victory-gpu/src/list.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 78d6d73..0d5d29b 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -522,7 +522,9 @@ extern "system" fn copy_texture_region( let Some((buffer, staging)) = list.upload(host, bytes) else { return; }; - list.defer_copy(staging, data, bytes as usize); + // The list owns this mapped D3D12 upload buffer. Wine can report + // its address as MEM_FREE, so use the host-upload path. + list.defer_fill(staging, data, bytes as usize); from.resource = buffer.as_raw().cast_const().cast(); from.footprint.offset = 0; #[cfg(feature = "diagnostics")] From 5864aaba28f2ef88d3e32c5710d43ce2b8ef5268 Mon Sep 17 00:00:00 2001 From: lameloball2813-ui <293005050+lameloball2813-ui@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:39:42 -0700 Subject: [PATCH 29/36] Docs: rustdoc builds the loader, GPU and shader crates without warnings --- crates/victory-gpu/src/list.rs | 2 +- crates/victory-gpu/src/shader_cache.rs | 2 +- crates/victory-loader/src/lib.rs | 2 +- crates/victory-shader/src/emit/validator.rs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 78d6d73..5dbf1a3 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -6,7 +6,7 @@ //! the table as a call. //! //! Each list records onto a host command list as its methods are called -//! (decision 0007); draw state lives in [`crate::draw`]. Methods not +//! (decision 0007); draw state lives in `crate::draw`. Methods not //! written yet log once with their caller, so a run lists what to do next. #![allow(clippy::not_unsafe_ptr_arg_deref)] diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 0cba938..998ec71 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -6,7 +6,7 @@ //! atomically; an entry that does not read back is translated again. //! //! The entry is our own encoding of [`HostShader`]: a field added to it -//! must be added to [`encode`] and [`decode`] too (entries of older builds +//! must be added to `encode` and `decode` too (entries of older builds //! are ignored anyway). use std::path::PathBuf; diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index 5a98cae..233ca47 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -4,7 +4,7 @@ //! CPU, so the machine code needs no translation. What differs is the //! platform underneath, so the loader's job is to: //! -//! 1. [`prepare`] a lightly patched copy of the image (pure, portable): mark +//! 1. [`prepare()`] a lightly patched copy of the image (pure, portable): mark //! it as a DLL, remove its entry point and import directory, and detach //! its TLS callbacks, so the Windows loader maps it, relocates it, //! allocates its static TLS and registers its unwind tables, but runs diff --git a/crates/victory-shader/src/emit/validator.rs b/crates/victory-shader/src/emit/validator.rs index 2f4108a..32171c7 100644 --- a/crates/victory-shader/src/emit/validator.rs +++ b/crates/victory-shader/src/emit/validator.rs @@ -1,6 +1,6 @@ //! The DXIL validator in `dxil.dll` (`IDxcValidator`), for tests and the //! offline batch. Translated shaders do not need it: they carry the -//! container hash we compute ([`super::container::hash`]). +//! container hash we compute (`container::hash`). //! //! The DLL is found at `VICTORY_DXIL` if set, else the newest Windows SDK's //! `bin\\x64\dxil.dll`, else wherever `LoadLibrary` finds it. From 31ce30f16954ffdf22758c6f24757a0d8ae79c62 Mon Sep 17 00:00:00 2001 From: fuzeofficial Date: Tue, 24 Nov 2026 15:42:18 +0900 Subject: [PATCH 30/36] GPU: unbind vertex buffer slots for null view arrays --- crates/victory-gpu/src/draw.rs | 6 ++++++ crates/victory-gpu/src/list.rs | 6 +++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index b6e043b..042005b 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -242,6 +242,12 @@ impl State { } } + pub(crate) fn clear_vertex_buffers(&mut self, start: u32, count: u32) { + for slot in self.vertex.iter_mut().skip(start as usize).take(count as usize) { + *slot = VertexView::default(); + } + } + pub(crate) fn set_index_buffer(&mut self, view: Option<&IndexView>) { self.index = view.copied().unwrap_or_default(); } diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 78d6d73..c52c0c7 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1007,7 +1007,11 @@ mod state { views: *const VertexView, ) { with_state(this, |_, s| { - s.set_vertex_buffers(start, items(views, count)) + if views.is_null() { + s.clear_vertex_buffers(start, count); + } else { + s.set_vertex_buffers(start, items(views, count)); + } }); } /// `(count, handles, one range, depth)`: with one range, the handles From ab3eb92941e9039b1e9bd90f6c51c64572fc425f Mon Sep 17 00:00:00 2001 From: Louis Faust Date: Mon, 23 Nov 2026 22:49:58 -0800 Subject: [PATCH 31/36] Shaders: gate the constant_color test helper to Windows Its only callers (stub_pipeline_is_created, constant_color_validates) are #[cfg(windows)], so on macOS/Linux the helper is dead code and cargo check --all-targets warns 'function constant_color is never used'. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-shader/src/emit/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 0df1233..c460527 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -447,6 +447,7 @@ mod tests { } /// A pixel shader writing a constant colour. + #[cfg(windows)] fn constant_color() -> Vec { let mut s = Shader::new(true); s.outputs.push(SigElement { From 4f53d6f1f321de42f955c6e9787f577d5bc644dd Mon Sep 17 00:00:00 2001 From: fuzeofficial Date: Tue, 24 Nov 2026 15:56:38 +0900 Subject: [PATCH 32/36] GPU: upload CPU-written sources before texture region copies --- crates/victory-gpu/src/list.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index db13bfd..411430d 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -538,6 +538,9 @@ extern "system" fn copy_texture_region( let Some(texture) = crate::resource::host_resource(src.resource) else { return; }; + if crate::texture::title_written(texture) { + crate::texture::upload(list, src.resource, texture); + } ensure_state(list, src.resource, COPY_SOURCE); from.resource = texture.as_raw().cast_const().cast(); } From 0f0c872a8f55b356c166c9c6d4185a6bda578e88 Mon Sep 17 00:00:00 2001 From: Louis Faust Date: Mon, 23 Nov 2026 22:59:38 -0800 Subject: [PATCH 33/36] Docs: drop the private intra-doc link to MICRO in texture.rs rustdoc warns that the module docs link to the private const MICRO (rustdoc::private_intra_doc_links). Plain code formatting keeps the reference without the broken link. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-formats/src/texture.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index 5d8926c..6a735b6 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -13,7 +13,7 @@ //! (`ComputeSurfaceInfoMacroTiled`, `ComputeThinBlockDimension`, //! `GetMipTailDim`, `GetMaxNumMipsInTail`, `HwlComputeSurfaceInfoLinear`, //! `ComputeSurfaceAddrFromCoordMacroTiled`), and the 256-byte micro tile -//! patterns in [`MICRO`] from `gfx10SwizzlePattern.h` (the RB+ tables, as on +//! patterns in `MICRO` from `gfx10SwizzlePattern.h` (the RB+ tables, as on //! RDNA2). addrlib carries this notice: //! //! Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved. From 51f1627d88dd2d1cc742f95a586ef1fb7ee41b27 Mon Sep 17 00:00:00 2001 From: Lyrnc <98659851+Lyrnc@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:07:26 +0300 Subject: [PATCH 34/36] Shaders: v_cmp_lg is ordered on AMD hosts too (olt | ogt, not fcmp one) v_cmp_lg_{f32,f16} ("less or greater") is ordered and not equal: false when either operand is a NaN, on RDNA2 hardware as in the ISA. It was lowered to `fcmp one`, which says the same, but the AMD D3D12 driver runs `fcmp one` as unordered and returns true for a NaN. NVIDIA and WARP get it right. It now lowers as `olt | ogt`, which all three run alike. New GPU test v_cmp_lg_is_false_for_nan covers both widths: NaN on either side, both NaN, a signalling NaN, +0 against -0, inf against inf and against -inf, and junk in the unread high halves for f16. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/bitcode.rs | 3 ++ crates/victory-shader/src/emit/lower.rs | 49 ++++++++++-------- crates/victory-shader/src/emit/valu_tests.rs | 52 ++++++++++++++++++++ 3 files changed, 84 insertions(+), 20 deletions(-) diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index 8b555ad..a5b8af8 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -103,6 +103,9 @@ pub(crate) mod pred { pub const OGE: u8 = 3; pub const OLT: u8 = 4; pub const OLE: u8 = 5; + // Not emitted: the AMD D3D12 driver treats it as UNE, so `v_cmp_lg` + // lowers as OLT | OGT instead. + #[allow(dead_code)] pub const ONE: u8 = 6; pub const ORD: u8 = 7; pub const UNO: u8 = 8; diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e898..bd01538 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4989,26 +4989,35 @@ impl<'a> Lower<'a> { } else { (self.fsrc(inst, 0)?, self.fsrc(inst, 1)?) }; - let p = match op { - "f" => pred::FALSE, - "lt" => pred::OLT, - "eq" => pred::OEQ, - "le" => pred::OLE, - "gt" => pred::OGT, - "lg" => pred::ONE, - "ge" => pred::OGE, - "o" => pred::ORD, - "u" => pred::UNO, - "nge" => pred::ULT, - "nlg" => pred::UEQ, - "ngt" => pred::ULE, - "nle" => pred::UGT, - "neq" => pred::UNE, - "nlt" => pred::UGE, - "tru" => pred::TRUE, - _ => return Err(inst.name()), - }; - self.s.m.cmp(c, p, a, b) + if op == "lg" { + // Ordered and not equal, false for a NaN, as `olt | ogt`. + // `fcmp one` means the same, but the AMD D3D12 driver + // runs it as unordered (true for a NaN) where NVIDIA + // and WARP do not; olt and ogt agree on all three. + let lt = self.s.m.cmp(c, pred::OLT, a, b); + let gt = self.s.m.cmp(c, pred::OGT, a, b); + self.s.m.bin(c, Bin::Or, lt, gt) + } else { + let p = match op { + "f" => pred::FALSE, + "lt" => pred::OLT, + "eq" => pred::OEQ, + "le" => pred::OLE, + "gt" => pred::OGT, + "ge" => pred::OGE, + "o" => pred::ORD, + "u" => pred::UNO, + "nge" => pred::ULT, + "nlg" => pred::UEQ, + "ngt" => pred::ULE, + "nle" => pred::UGT, + "neq" => pred::UNE, + "nlt" => pred::UGE, + "tru" => pred::TRUE, + _ => return Err(inst.name()), + }; + self.s.m.cmp(c, p, a, b) + } } "u64" | "i64" => { let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?); diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 1b95ca6..7a8db43 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -320,6 +320,58 @@ fn v_med3_f16_matches_rdna2_with_nan() { }); } +/// `v_cmp_lg_*` is "less or greater": ordered and not equal, so false when +/// either operand is a NaN (RDNA2 ISA; the same on gfx1036 hardware). +#[test] +fn v_cmp_lg_is_false_for_nan() { + // v_cmp_lg_{f32,f16}_e64 s20, v1, v2 (VOPC 0x005 / 0x0cd in VOP3); + // v_cndmask_b32_e64 v0, 0, 1, s20 (VOP3 0x101) + let nan = f32::NAN.to_bits(); + let (inf, ninf) = (f32::INFINITY.to_bits(), f32::NEG_INFINITY.to_bits()); + let f = f32::to_bits; + let f32_cases: &[([u32; 4], u32)] = &[ + ([f(1.0), f(2.0), 0, 0], 1), + ([f(2.0), f(1.0), 0, 0], 1), + ([f(1.0), f(1.0), 0, 0], 0), + ([f(0.0), f(-0.0), 0, 0], 0), + ([inf, ninf, 0, 0], 1), + ([inf, inf, 0, 0], 0), + ([nan, f(1.0), 0, 0], 0), + ([f(1.0), nan, 0, 0], 0), + ([nan, nan, 0, 0], 0), + ([0x7F80_0001, f(0.0), 0, 0], 0), // a signalling NaN + ]; + let f16_cases: &[([u32; 4], u32)] = &[ + ([0x3C00, 0x4000, 0, 0], 1), + ([0x4000, 0x3C00, 0, 0], 1), + ([0x3C00, 0x3C00, 0, 0], 0), + ([0x0000, 0x8000, 0, 0], 0), + ([0x7C00, 0xFC00, 0, 0], 1), + ([0x7E00, 0x3C00, 0, 0], 0), + ([0x3C00, 0x7E00, 0, 0], 0), + ([0x7E00, 0x7E00, 0, 0], 0), + ([0x7C01, 0x0000, 0, 0], 0), // a signalling NaN + ([0xABCD_3C00, 0x1234_7E00, 0, 0], 0), // only the low halves are read + ]; + for (op, what, cases) in [ + (0x005u16, "v_cmp_lg_f32", f32_cases), + (0x0cd, "v_cmp_lg_f16", f16_cases), + ] { + let mut body = vop3(op, 20, vgpr(1), vgpr(2), 0x80).to_vec(); + body.extend_from_slice(&vop3(0x101, 0, 0x80, 0x81, sgpr(20))); + let shader = build_valu_cs(&body); + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let want = cases[i].1; + assert_eq!( + got, want, + "{backend}: {what}({:#010x}, {:#010x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); + } +} + #[test] fn v_fract_f32_never_returns_one() { // v_fract_f32 v0, v1 (VOP1 opcode 0x020) From 3e39eac1c5dc5a66ac0c98464acd18b06bcc598c Mon Sep 17 00:00:00 2001 From: quaternion Date: Mon, 23 Nov 2026 23:25:18 -0500 Subject: [PATCH 35/36] fix(hle): return XAsync payloads for nonnegative results GetResultSize and GetResult only treated S_OK as success, so a provider finishing with S_FALSE and a payload left the caller's buffers untouched and the call registered forever. Any nonnegative HRESULT is a success code; return the size, let the provider write the result, report bytes used, and release the call. Add a regression completing with S_FALSE and an eight-byte payload. --- crates/victory-hle/src/modules/xasync.rs | 57 ++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 3 deletions(-) diff --git a/crates/victory-hle/src/modules/xasync.rs b/crates/victory-hle/src/modules/xasync.rs index 6795057..e603f3d 100644 --- a/crates/victory-hle/src/modules/xasync.rs +++ b/crates/victory-hle/src/modules/xasync.rs @@ -627,7 +627,9 @@ pub fn XAsyncGetResultSize(block: *mut AsyncBlock, out: *mut usize) -> HRESULT { return E_INVALIDARG; } let hr = status(block); - if hr == S_OK { + // Any nonnegative completion carries a result, not just S_OK: S_FALSE + // is a success code too and a provider may return data with it. + if hr >= 0 { // SAFETY: checked non-null. unsafe { out.write(words(block).1.load(Ordering::Acquire)) }; } @@ -656,8 +658,8 @@ pub fn XAsyncGetResult( } let hr = status(block); let size = words(block).1.load(Ordering::Acquire); - if hr != S_OK || size == 0 { - if hr == S_OK && !used.is_null() { + if hr < 0 || size == 0 { + if hr >= 0 && !used.is_null() { // SAFETY: checked non-null. unsafe { used.write(0) }; } @@ -1124,6 +1126,55 @@ mod tests { XTaskQueueCloseHandle(q); } + #[test] + fn a_nonnegative_completion_still_returns_its_payload() { + const S_FALSE: HRESULT = 1; + extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { + // SAFETY: the runtime passes valid provider data. + let data = unsafe { &*data }; + match op { + OP_BEGIN => XAsyncSchedule(data.block, 0), + OP_DO_WORK => { + XAsyncComplete(data.block, S_FALSE, 8); + S_OK + } + OP_GET_RESULT => { + // SAFETY: the caller checked eight bytes. + unsafe { data.buffer.cast::().write(0x1234) }; + S_OK + } + _ => S_OK, + } + } + let mut q = std::ptr::null(); + assert_eq!(XTaskQueueCreate(0, 0, &mut q), S_OK); + let mut block = AsyncBlock { + queue: q, + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + }; + let identity = 0x77 as *const c_void; + assert_eq!( + XAsyncBegin(&mut block, std::ptr::null_mut(), identity, std::ptr::null(), Some(provider)), + S_OK + ); + assert!(XTaskQueueDispatch(q, WORK, 0)); + assert_eq!(XAsyncGetStatus(&mut block, false), S_FALSE); + let mut size = 0; + assert_eq!(XAsyncGetResultSize(&mut block, &mut size), S_FALSE); + assert_eq!(size, 8); + let mut value = 0u64; + let mut used = 0; + assert_eq!( + XAsyncGetResult(&mut block, identity, 8, (&mut value as *mut u64).cast(), &mut used), + S_OK + ); + assert_eq!((value, used), (0x1234, 8)); + assert!(call((&raw mut block)).is_none(), "the call ends with its result"); + XTaskQueueCloseHandle(q); + } + #[test] fn run_returns_the_work_result() { extern "system" fn work(_: *mut AsyncBlock) -> HRESULT { From 8e79c80e4b71e252bcd271e0587aa662c4770008 Mon Sep 17 00:00:00 2001 From: Marvis Date: Tue, 24 Nov 2026 09:55:29 +0100 Subject: [PATCH 36/36] CI: clippy and tests on pull requests and main A Windows job on the pinned toolchain: clippy with -D warnings on the default and the --all-features (diagnostics) build, then cargo test --workspace, which includes the asset-policy test. main did not build its tests: scalar_bit_tests_lower called lowers() without the rsrc2 argument a parallel change added (0, no input registers). Also drops a double parenthesis clippy flagged in an xasync test. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 33 ++++++++++++++++++++++++ crates/victory-hle/src/modules/xasync.rs | 2 +- crates/victory-shader/src/emit/lower.rs | 2 +- 3 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..80e6a35 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,33 @@ +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/crates/victory-hle/src/modules/xasync.rs b/crates/victory-hle/src/modules/xasync.rs index 08234ac..068d75f 100644 --- a/crates/victory-hle/src/modules/xasync.rs +++ b/crates/victory-hle/src/modules/xasync.rs @@ -1179,7 +1179,7 @@ mod tests { S_OK ); assert_eq!((value, used), (0x1234, 8)); - assert!(call((&raw mut block)).is_none(), "the call ends with its result"); + assert!(call(&raw mut block).is_none(), "the call ends with its result"); XTaskQueueCloseHandle(q); } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 7b933c1..211da17 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -6960,7 +6960,7 @@ mod tests { ]; for head in bit_tests { let words: Vec = head.iter().chain(&tail).copied().collect(); - lowers(&words).unwrap(); + lowers(&words, 0).unwrap(); } }