Water light on, PS4 pads, F1 menu saves at once, long-session memory, memory switches

Rendering and memory (GPL-3.0 code ported in; credits in the source):
- Water: 64-lane compute programs on 32-lane waves keep each wave
  together through loops and set up shared memory from the first
  thread, so the water's tiled light no longer leaves dark blocks. It
  runs by default now (VICTORY_WATER_LIGHT=0 leaves it out; an empty
  value, an earlier version's saved OFF, runs it). Also cloud tiles and
  the screen probes' ray activation.
- Placed views: their padding cleared as before; folding a buffer
  view's first element into its address is VICTORY_PLACED_FOLD=1, off:
  with it on, clothing and caps swapped to other variants for single
  frames in the boat cutscene.
- Texture sweep: textures whose copy was let go leave the looks until
  used again. Static samplers made first, in one order. Small buffers
  made ahead of the first 3D frame.
- play mode: VICTORY_TEXSPK_PASS_MS=8, VICTORY_PASSES_HOT=1,
  VICTORY_HELPER_PRIORITY=1.
- Memory switches, all off: VICTORY_SLOT_EVICT, VICTORY_ALLOCATOR_TRIM,
  VICTORY_BUDGET_PACK (and VICTORY_LIST_POOL_IDLE_S).

Input: DualShock 4 (0x05C4, 0x09CC, 0x0BA0 adapter) read over HID, USB
and Bluetooth, beside the DualSense; PlayStation pads rumble, and stop
when the game ends (issue #352).

F1 menu: every change is saved at once; it saves to
victory-settings.txt in VICTORY_HOME or %LOCALAPPDATA%\victory however
the game was started (no more "NO SETTINGS FILE").

Warm-up start: its 30 s count from the first frame of 100 draws or
more, not from the start: waiting at the title screen restarted it too
early and the next run still sat at 14 fps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
trustno1-coderandClaude Opus 5.5 committed 2026-11-27 15:03:27 -08:00
1 parent df2daafeb1
commit 64d4931b3d
44 files changed
+4664 -952

No files matched your search

+73 -2
View File
@@ -62,8 +62,74 @@ fn err(e: windows::core::Error) -> String {
e.message().to_string()
}
/// The graphics card runs use: the first hardware adapter whose name holds
/// `VICTORY_ADAPTER` (any case), else the hardware adapter with the most
/// memory of its own. Windows' first adapter is often an integrated GPU (a
/// monitor on the board's outputs, a laptop), and a device made with no
/// adapter named runs there. The warm-up, the game's device and DLSS take the
/// same card, so the driver's saved pipelines are the card's that plays.
/// None: no hardware adapter (the default device is made then).
pub fn hardware_adapter() -> Option<(IDXGIAdapter1, String, u64)> {
// SAFETY: plain DXGI queries.
unsafe {
let factory: IDXGIFactory1 = CreateDXGIFactory1().ok()?;
let mut all = Vec::new();
for i in 0.. {
let Ok(adapter) = factory.EnumAdapters1(i) else { break };
let Ok(desc) = adapter.GetDesc1() else { continue };
if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 {
continue;
}
let len = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len());
all.push((adapter, String::from_utf16_lossy(&desc.Description[..len]), desc.DedicatedVideoMemory as u64));
}
pick_adapter(all, std::env::var("VICTORY_ADAPTER").ok().as_deref())
}
}
/// The adapter `hardware_adapter` takes from (adapter, name, own memory).
fn pick_adapter<A>(all: Vec<(A, String, u64)>, named: Option<&str>) -> Option<(A, String, u64)> {
let named = named.map(str::trim).filter(|n| !n.is_empty()).map(str::to_lowercase);
let mut best: Option<(A, String, u64)> = None;
for a in all {
if let Some(n) = &named
&& a.1.to_lowercase().contains(n.as_str())
{
return Some(a);
}
if best.as_ref().is_none_or(|b| a.2 > b.2) {
best = Some(a);
}
}
best
}
#[cfg(test)]
mod adapter_tests {
use super::pick_adapter;
fn cards() -> Vec<((), String, u64)> {
vec![
((), "Intel(R) Graphics".to_owned(), 128 << 20),
((), "NVIDIA GeForce RTX 4070 Ti".to_owned(), 12 << 30),
((), "AMD Radeon(TM) Graphics".to_owned(), 512 << 20),
]
}
#[test]
fn the_card_with_the_most_own_memory_unless_one_is_named() {
assert_eq!(pick_adapter(cards(), None).unwrap().1, "NVIDIA GeForce RTX 4070 Ti");
assert_eq!(pick_adapter(cards(), Some(" ")).unwrap().1, "NVIDIA GeForce RTX 4070 Ti");
assert_eq!(pick_adapter(cards(), Some("intel")).unwrap().1, "Intel(R) Graphics");
// A name no card has: the rule as without one.
assert_eq!(pick_adapter(cards(), Some("arc b580")).unwrap().1, "NVIDIA GeForce RTX 4070 Ti");
assert!(pick_adapter(Vec::<((), String, u64)>::new(), None).is_none());
}
}
impl Host {
/// The default adapter, or WARP with `warp` (or `VICTORY_WARP=1`).
/// The card `hardware_adapter` takes (else the default adapter), or WARP
/// with `warp` (or `VICTORY_WARP=1`).
pub fn new(warp: bool) -> Result<Self, String> {
let warp = warp || std::env::var("VICTORY_WARP").is_ok_and(|v| v == "1");
// SAFETY: plain D3D12/DXGI calls with valid out pointers.
@@ -85,7 +151,12 @@ impl Host {
let adapter: IDXGIAdapter = factory.EnumWarpAdapter().map_err(err)?;
D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?;
} else {
D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?;
if let Some((adapter, ..)) = hardware_adapter() {
let _ = D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device);
}
if device.is_none() {
D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?;
}
// A machine without a graphics card gives the software
// adapter as its default device (a hosted test runner,
// whose first adapter is a display stub that cannot make a
+315 -14
View File
@@ -377,6 +377,8 @@ struct Lower<'a> {
meeting: Option<V>,
/// With `pairs`: the LDS accesses that need no meeting ([`LdsOrder`]).
lds_unordered: HashSet<(usize, usize)>,
/// LDS atomics in loops that get no meeting ([`LdsOrder::looped`]).
lds_looped: HashSet<(usize, usize)>,
/// With `pairs`: the console waves of the group, and the first of this console wave's
/// exchange dwords ([`Self::exchange_dword`], made in the entry block).
pair_waves: u32,
@@ -525,7 +527,10 @@ fn lane_regions_of(st: &Structured, group: bool) -> Option<Vec<(usize, Vec<bool>
let mut regions = Vec::new();
for (d, e) in st.exits.iter().enumerate() {
let LaneExit::Branch { when, .. } = *e else { continue };
if st.wide.contains(&d) && !group || st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) {
// (a branch each host wave takes for itself separates the halves of a console wave)
if st.wide.contains(&d) && !st.host_wide.contains(&d) && !group
|| st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_)))
{
continue; // a wave-wide or uniform branch: all lanes go the same way
}
// blocks reachable from the lane branch that do not post-dominate it
@@ -558,6 +563,57 @@ pub(super) fn branches_around(st: &Structured, needs: &[usize]) -> Option<Vec<us
Some(out)
}
/// The per-lane branches (by block) that close a loop or leave one, whose wave-wide meaning
/// is known ([`Structured::wave_any`]): the ones a host wave takes together
/// ([`crate::structure::structure_wide_host`]) so that its lanes stay one wave behind the
/// loop. Not the branches the wave takes together already, nor those on scalar conditions.
pub(super) fn loop_branches(p: &Program, st: &Structured) -> HashSet<usize> {
let n = p.blocks.len();
let mut rpo = vec![usize::MAX; n];
for (i, b) in crate::ir::reverse_postorder(&p.blocks).into_iter().enumerate() {
rpo[b] = i;
}
let succ = |b: usize| -> Vec<usize> {
match p.blocks[b].exit {
Exit::Jump(t) => vec![t],
Exit::Branch { taken, not_taken } => vec![taken, not_taken],
_ => Vec::new(),
}
};
let mut out = HashSet::new();
for latch in (0..n).filter(|&b| rpo[b] != usize::MAX) {
for head in succ(latch).into_iter().filter(|&h| rpo[h] <= rpo[latch]) {
// the loop's blocks: the head, and what reaches the latch without passing it
let mut body = vec![false; n];
body[head] = true;
let mut stack = vec![latch];
while let Some(b) = stack.pop() {
if body[b] {
continue;
}
body[b] = true;
stack.extend(p.blocks[b].preds.iter().copied().filter(|&q| rpo[q] != usize::MAX));
}
for b in (0..n).filter(|&b| body[b]) {
let LaneExit::Branch { when, taken, not_taken } = st.exits[b] else { continue };
let leaves = !body[taken] || !body[not_taken] || b == latch;
let per_lane = !st.wide.contains(&b)
&& !st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_)));
if leaves && per_lane && st.wave_any.get(b).copied().flatten().is_some() {
out.insert(b);
}
}
}
}
out
}
/// Whether accesses outside a program's own shared memory are done as the console does them
/// (reads give 0, writes are dropped; `VICTORY_LDS_BOUNDS=0`: taken as inside, as before).
fn lds_bounds() -> bool {
!std::env::var("VICTORY_LDS_BOUNDS").is_ok_and(|v| v.trim() == "0")
}
/// Whether a refusal is of code that needs every lane of the wave where it stands (two host
/// waves meeting there), which the other forms of the program may give it.
pub(super) fn needs_every_lane(what: &str) -> bool {
@@ -570,6 +626,11 @@ pub(super) fn take_needs() -> Vec<usize> {
NEEDS.take()
}
/// Puts back what [`take_needs`] gave (a lowering tried in between is forgotten).
pub(super) fn set_needs(needs: Vec<usize>) {
NEEDS.set(needs);
}
fn need(block: usize) {
NEEDS.with_borrow_mut(|n| {
if !n.contains(&block) {
@@ -993,6 +1054,28 @@ pub(super) struct LdsOrder {
/// Of `unordered`, the reads near an LDS atomic: the two halves of a console wave may see
/// different values there ([`lane_uniform`] does not take them as alike).
pub(super) unstable: HashSet<(usize, usize)>,
/// LDS atomics in a loop that no plain LDS write or read leads into or stands in: they get
/// no meeting of the host waves ([`loop_atomics_on`]), with or without
/// [`with_pair_meetings`].
///
/// A meeting is a group barrier, and the host waves take a loop each on its own
/// (`crate::structure::structure_wide_host`, or lane by lane): one that makes fewer rounds
/// stands at the barrier behind the loop while the others stand at the one inside it, the
/// host lets them all go on, and the first reads what the others have not written yet.
/// Seen in `CS_SortRayTiles` (the cloud pass, 256 threads, the game, build 1.0.2.1; captures
/// cloud3 and cloud4, RTX 4070 SUPER): its counting and its scattering loop take 15
/// entries a thread, the last threads none; the host waves of those read the bins' counts
/// while the others still counted, the places they worked out overlapped, and of the 1,068
/// tiles of the sorted class 971 were left (644: 605), the others written over or never
/// moved. A tile that is not in the list gets no ray: a square of clear sky in a cloud,
/// 8 by 4 of the clouds' pixels, until a later frame traces it (seen for a second or two
/// after a cut, when no earlier frame's cloud stands in).
///
/// Without the meeting the atomic's order against the accesses around the loop is kept by
/// their own meetings and the title's barriers: what comes before the loop is asked for
/// here (nothing but atomics, back to a barrier), and what comes behind it meets first,
/// which every thread does only once its loop is done.
pub(super) looped: HashSet<(usize, usize)>,
}
/// [`LdsOrder`] of `p`: the program cut at its `s_barrier`s into pieces joined by the edges
@@ -1075,6 +1158,10 @@ pub(super) fn lds_order(p: &crate::ir::Program, st: &Structured) -> LdsOrder {
.collect();
let writes = near.iter().any(|a| a.2 == Kind::Write);
let atomics = near.iter().any(|a| a.2 == Kind::Atomic);
// (on a cycle, and nothing but atomics in it and in what leads to it)
if fwd[k] && (0..pieces).filter(|&x| x == k || bwd[x]).flat_map(|x| accesses[x].iter()).all(|a| a.2 == Kind::Atomic) {
out.looped.extend(accesses[k].iter().map(|a| (a.0, a.1)));
}
for &(b, i, kind) in &accesses[k] {
let ordered = match kind {
Kind::Read | Kind::Atomic => writes,
@@ -1338,6 +1425,13 @@ fn linear_clamp_sampler(words: &[u32]) -> bool {
s.filter & !1 == 0x14 && s.address == [3, 3, 3]
}
/// Whether LDS atomics in loops go without a meeting of the host waves ([`LdsOrder::looped`];
/// `VICTORY_LDS_LOOP_ATOMICS=0`: they meet, as before 2026-11-27).
fn loop_atomics_on() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_LDS_LOOP_ATOMICS").is_none_or(|v| v != "0"))
}
/// `VICTORY_WAVE_OWN_BITS=0`: a wave OR where not every lane runs is refused as before
/// ([`super::own_bits`]).
fn own_bits_on() -> bool {
@@ -1658,10 +1752,19 @@ impl<'a> Lower<'a> {
let mut pairs: Option<u32> = None;
let mut pair_waves = 0;
// (and only around the LDS accesses whose order counts)
let lds_order = if PAIR_MEETINGS.get() { lds_order(p, x.st) } else { LdsOrder::default() };
let lds_order = {
let all = if PAIR_MEETINGS.get() || loop_atomics_on() { lds_order(p, x.st) } else { LdsOrder::default() };
let looped = if loop_atomics_on() { all.looped } else { HashSet::new() };
if PAIR_MEETINGS.get() {
LdsOrder { looped, unordered: all.unordered, unstable: all.unstable }
} else {
LdsOrder { looped, ..LdsOrder::default() }
}
};
if let StageIo::Cs(cs) = x.native.io {
s.threads = Some(cs.threads);
s.lds_dwords = cs.lds_bytes() / 4;
s.title_lds_dwords = s.lds_dwords;
// Code reading other lanes needs the console's wave size and
// lane order; so do lane masks read as numbers, and LDS shared
// within one wave, where the console compiler leaves out barriers.
@@ -1847,6 +1950,7 @@ impl<'a> Lower<'a> {
s.prims = x.prims.clone();
s.threads = Some([ms.threads, 1, 1]);
s.lds_dwords = ms.lds_bytes.div_ceil(4);
s.title_lds_dwords = s.lds_dwords;
s.mesh = Some(super::shader::Mesh {
max_vertices: ms.max_vertices,
max_primitives: ms.max_primitives,
@@ -1979,6 +2083,7 @@ impl<'a> Lower<'a> {
pairs,
meeting: None,
lds_unordered: lds_order.unordered.clone(),
lds_looped: lds_order.looped.clone(),
pair_waves,
pair_base: None,
flat: None,
@@ -4760,6 +4865,19 @@ impl<'a> Lower<'a> {
fn wave_wide(&mut self, b: usize, when: Bool) -> Result<V, Why> {
const WHY: Why = "a wave-wide branch where not every lane runs";
let any = self.x.st.wave_any.get(b).copied().flatten().ok_or("a wave-wide branch on a scalar condition")?;
if self.x.st.host_wide.contains(&b) {
// A loop's branch each host wave takes for itself: the host wave's own answer.
// Its lanes then leave the loop together and are one wave behind it. A host wave
// whose lanes are all done goes on while the other half of its console wave
// still loops: the console would run the loop's code with those lanes off, which
// changes nothing of theirs.
let c = self.cur;
let mine = self.boolean(when, c)?;
let i1t = self.s.t.i1;
self.s.flags |= flags::WAVE_OPS;
let (name, code) = if any { ("waveAnyTrue", 113) } else { ("waveAllTrue", 114) };
return Ok(self.s.op(c, name, Attr::NoUnwind, i1t, code, &[mine]));
}
if self.exchange.is_none() && self.halves.is_none() && self.console_lanes && self.mask_data == MaskData::Console {
// The host's waves are the console's: the wave's own answer. The lanes that are
// elsewhere have no bit set, as on the console, so "some lane" needs no one but
@@ -5389,6 +5507,114 @@ impl<'a> Lower<'a> {
.collect()
}
/// An LDS write (instruction `i` of block `b`) that is the thread group's set-up of its
/// shared memory: constants to a constant address, under `v_cmpx_eq_u32 exec, 0, <the
/// thread's place in its group>`, so by the group's first thread alone. Gives that
/// thread's test and (byte address, constant) per dword written.
///
/// The console runs it only if the first thread's lane still runs there: a group whose
/// first thread has left (its pixel is not water, say) starts from what the group before
/// it left in LDS, which on the console is the neighbouring tile's sane values and on a
/// PC card is anything. Seen in `water_shading:CS_TransmissionVolumetrics_Tiled`
/// (the game, build 1.0.2.1, capture water3, RTX 4070 SUPER): it keeps the tile's least and
/// greatest depth in LDS, set to "none yet" by thread (0,0) after the lanes off the water
/// have left; of 124 tiles whose first pixel was not water 71 wrote nothing (dark slabs
/// on the water along the horizon and beside rocks, plants and hulls), of 3,250 others
/// none. Here the first thread always sets it up (`VICTORY_LDS_FIRST_INIT=0`: as the
/// console, only if its lane runs): the tile then works from its own depths alone.
fn first_thread_init(
&mut self,
b: usize,
i: usize,
addr: Option<&Operand>,
data: &[Operand],
elements: &[(u32, u32)],
) -> Option<(V, Vec<(u32, u32)>)> {
if std::env::var("VICTORY_LDS_FIRST_INIT").is_ok_and(|v| v.trim() == "0") {
return None;
}
let StageIo::Cs(cs) = self.x.native.io else { return None };
let p = self.x.p;
let insts = &p.blocks[b].insts;
// the compare that left EXEC as it is at the write
let j = (0..i).rev().find(|&j| insts[j].write(Reg::S(EXEC)).is_some())?;
let Fields::Valu(cmp) = &insts[j].fields else { return None };
if insts[j].name() != "v_cmpx_eq_u32" {
return None;
}
let place = match cmp.src.as_slice() {
[Operand::Const(128), Operand::Vector { reg, .. }] | [Operand::Vector { reg, .. }, Operand::Const(128)] => {
insts[j].read(Reg::V(*reg))?
}
_ => return None,
};
// ... of the thread's place: its x, or x | y (| z), as the program entered with them
let input = |v: Value| p.inputs.iter().find(|i| i.1 == v).and_then(|i| match i.0 {
Reg::V(c @ 0..=2) => Some(c),
_ => None,
});
let mut parts: Vec<u8> = Vec::new();
let mut open = vec![place];
while let Some(v) = open.pop() {
if let Some(c) = input(v) {
parts.push(c);
continue;
}
let made = p.blocks.iter().flat_map(|blk| &blk.insts).find(|k| k.writes.iter().any(|w| w.1 == v))?;
let Fields::Valu(or) = &made.fields else { return None };
if made.name() != "v_or_b32" || or.sdwa.is_some() || or.dpp.is_some() {
return None;
}
for op in &or.src {
let Operand::Vector { reg, .. } = op else { return None };
open.push(made.read(Reg::V(*reg))?);
}
if parts.len() + open.len() > 3 {
return None;
}
}
// (every dimension of the group that has more than one thread is tested)
if (0..3u8).any(|c| cs.threads[usize::from(c)] > 1 && !parts.contains(&c)) {
return None;
}
// the address and what is written: constants moved in since the compare
let constant = |op: &Operand| -> Option<u32> {
let Operand::Vector { reg, .. } = *op else { return None };
let k = (j + 1..i).rev().find(|&k| insts[k].write(Reg::V(reg)).is_some())?;
let Fields::Valu(mov) = &insts[k].fields else { return None };
if insts[k].name() != "v_mov_b32" || mov.sdwa.is_some() || mov.dpp.is_some() {
return None;
}
match mov.src.as_slice() {
[Operand::Const(c)] => crate::resource::inline(*c),
[Operand::Literal(x)] => Some(*x),
_ => None,
}
};
let at = constant(addr?)?;
let mut out = Vec::new();
for (e, &(off, w)) in elements.iter().enumerate() {
if w != 1 {
return None;
}
let bytes = at.checked_add(off)?;
if bytes % 4 != 0 || bytes / 4 >= cs.lds_bytes() / 4 {
return None;
}
out.push((bytes, constant(data.get(e)?)?));
}
// the first thread: every coordinate is 0, so its index in the group is
let flat = if self.console_lanes {
self.s.flags |= flags::WAVE_OPS;
self.console_thread()
} else {
let (e, i32t) = (self.s.entry, self.s.t.i32);
self.s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, &[])
};
let (c, zero) = (self.cur, self.s.m.i32(0));
Some((self.s.m.cmp(c, pred::EQ, flat, zero), out))
}
/// LDS (thread-group shared memory) and `ds_swizzle`.
fn ds(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
let Fields::Ds {
@@ -5502,16 +5728,55 @@ impl<'a> Lower<'a> {
return Err("LDS the program does not allocate");
}
let a = self.vgprs(inst, addr.as_ref().ok_or("an LDS address")?, 1)?[0];
// shortcut: LDS addresses are taken as dword-aligned and in bounds
// (out-of-bounds console accesses read 0 and drop writes).
let dword = |l: &mut Self, bytes: u32| -> V {
// shortcut: LDS addresses are taken as dword-aligned.
// Outside the program's shared memory the console reads 0 and drops writes; group-shared
// memory of the host is undefined there (and behind the program's dwords lie ours).
// So: the dword's place, and whether it is inside (`None`: not asked; the place is then
// taken as inside, as before 2026-11-27, `VICTORY_LDS_BOUNDS=0`). A place outside is
// given as the last dword inside: reads of it are replaced by 0, writes left out.
// Seen in `CS_SortRayTiles` (the cloud pass's sort of its ray tiles, 256 threads a group):
// a counting sort over 256 bins in LDS, the bin a thread clears and reads addressed by
// its number in the whole dispatch. Of the 32 groups dispatched only the first has
// entries of its own to sort; the 31 others clear and read at up to 32 KiB behind their
// 2.5 KiB.
// (The squares of clear sky that show in clouds for a second or two after a cut are not
// this: they were there with and without the bounds, captures cloud3 and cloud4 of
// 2026-11-27. The list those captures hold, 7,200 dwords, is two lists of 3,600 one
// behind the other, the tiles with cloud in them and those without; all 3,680 tiles of
// the frame were in it once each in cloud4.)
let limit = if lds_bounds() { self.s.title_lds_dwords } else { 0 };
let dword = |l: &mut Self, bytes: u32| -> (V, Option<V>) {
let c = l.cur;
let o = l.s.m.i32(bytes);
let at = l.s.m.bin(c, Bin::Add, a, o);
let two = l.s.m.i32(2);
let index = l.s.m.bin(c, Bin::LShr, at, two);
let lds = l.s.lds();
l.s.m.element(c, lds, index)
if limit == 0 {
return (l.s.m.element(c, lds, index), None);
}
let end = l.s.m.i32(limit);
let inside = l.s.m.cmp(c, pred::IULT, index, end);
let last = l.s.m.i32(limit - 1);
let index = l.s.m.select(c, inside, index, last);
(l.s.m.element(c, lds, index), Some(inside))
};
// (a guard and "inside" together; what a read gives outside)
let both = |l: &mut Self, guard: Option<V>, inside: Option<V>| -> Option<V> {
match (guard, inside) {
(Some(g), Some(i)) => Some(l.s.m.bin(l.cur, Bin::And, g, i)),
(g, None) => g,
(None, i) => i,
}
};
let read = |l: &mut Self, x: V, inside: Option<V>| -> V {
match inside {
Some(i) => {
let zero = l.s.m.i32(0);
l.s.m.select(l.cur, i, x, zero)
}
None => x,
}
};
let width = |n: &str| match n.rsplit('_').next() {
Some("b64") => 2,
@@ -5545,7 +5810,7 @@ impl<'a> Lower<'a> {
|| name.ends_with("_d16_hi")
});
if let Some(bits) = sub {
let p = dword(self, offset);
let (p, inside) = dword(self, offset);
let o = self.s.m.i32(offset);
let at = self.s.m.bin(c, Bin::Add, a, o);
let three = self.s.m.i32(3);
@@ -5555,6 +5820,7 @@ impl<'a> Lower<'a> {
if name.starts_with("ds_read") {
let reg = dst_reg.ok_or("an LDS read result")?;
let w = self.s.m.load(c, p);
let w = read(self, w, inside);
let x = self.s.m.bin(c, Bin::LShr, w, sh);
let x = if base.contains("_i") {
let k = self.s.m.i32(32 - bits);
@@ -5597,6 +5863,7 @@ impl<'a> Lower<'a> {
let ones = self.s.m.i32(u32::MAX);
let keep = self.s.m.bin(c, Bin::Xor, m, ones);
use super::bitcode::Rmw;
let guard = both(self, guard, inside);
let at = self.begin_guarded(guard);
self.s.m.atomic(self.cur, Rmw::And, p, keep);
self.s.m.atomic(self.cur, Rmw::Or, p, x);
@@ -5616,8 +5883,9 @@ impl<'a> Lower<'a> {
let mut n = 0;
for (off, w) in elements {
for k in 0..w {
let p = dword(self, off + 4 * k);
let (p, inside) = dword(self, off + 4 * k);
let x = self.s.m.load(self.cur, p);
let x = read(self, x, inside);
self.write(inst, Reg::V(reg + n), x, guard);
n += 1;
}
@@ -5632,6 +5900,18 @@ impl<'a> Lower<'a> {
} else {
return Err("an LDS write of bytes or halves");
};
if let Some((first, constants)) = self.first_thread_init(b, i, addr.as_ref(), data, &elements) {
// The group's first thread sets shared memory up, whether its lane runs or not.
let at = self.begin_guarded(Some(first));
for (bytes, x) in constants {
let (index, x) = (self.s.m.i32(bytes / 4), self.s.m.i32(x));
let lds = self.s.lds();
let ptr = self.s.m.element(self.cur, lds, index);
self.s.m.store(self.cur, ptr, x);
}
self.end_guarded(at, &[]);
return Ok(());
}
let mut stores = Vec::new();
for (e, (off, w)) in elements.into_iter().enumerate() {
let vals = self.vgprs(inst, data.get(e).ok_or("an LDS write")?, w as u8)?;
@@ -5641,8 +5921,10 @@ impl<'a> Lower<'a> {
}
let at = self.begin_guarded(guard);
for (off, x) in stores {
let p = dword(self, off);
let (p, inside) = dword(self, off);
let here = self.begin_guarded(inside);
self.s.m.store(self.cur, p, x);
self.end_guarded(here, &[]);
}
self.end_guarded(at, &[]);
return Ok(());
@@ -5677,7 +5959,20 @@ impl<'a> Lower<'a> {
Some((_, v)) => self.i32_of(v).unwrap_or(self.s.m.i32(0)),
None => self.s.m.i32(0),
};
let p = dword(self, offset);
let (p, inside) = dword(self, offset);
// (outside the memory nothing is done; a lane that runs gets 0 back, as a read does)
let outside = match inside {
Some(i) => {
let zero = self.s.m.i32(0);
let missed = match guard {
Some(g) => self.s.m.select(self.cur, g, zero, outside),
None => zero,
};
self.s.m.select(self.cur, i, outside, missed)
}
None => outside,
};
let guard = both(self, guard, inside);
if let Some(max) = match op.as_str() {
"max_f32" => Some(true),
"min_f32" => Some(false),
@@ -5832,9 +6127,15 @@ impl<'a> Lower<'a> {
&& self.lds_meet.as_ref().is_none_or(|(all, _)| all[b])
&& !self.lds_unordered.contains(&(b, i))
{
// the two host waves of a console wave meet before each LDS access: what the other
// half wrote is visible, and what it still reads is not overwritten
self.meet();
if self.lds_looped.contains(&(b, i)) {
// (in a loop the host waves take each on its own: a fence, no wait)
let (fence, void) = (self.s.m.i32(8), self.s.t.void);
self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[fence]);
} else {
// the two host waves of a console wave meet before each LDS access: what the
// other half wrote is visible, and what it still reads is not overwritten
self.meet();
}
}
// The structure builder's threads take turns through atomics (a tree
// built from its leaves up): what one wrote before its atomic is
@@ -13285,7 +13586,7 @@ impl<'a> Lower<'a> {
&& self.mask_data == MaskData::Console
&& st.scc_some.contains_key(&arg) =>
{
let per_lane = !st.wide.contains(&q)
let per_lane = (!st.wide.contains(&q) || st.host_wide.contains(&q))
&& matches!(st.exits[q], LaneExit::Branch { when, .. }
if !st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))));
if per_lane {
+77 -1
View File
@@ -625,7 +625,7 @@ pub fn emit(
// Both archived kernels use one logical wave per group and have
// validated wave32 PSOs on RTX. Explicit policy wins.
// The volumetric light's two tiled programs (`CS_TransmissionVolumetrics_Tiled`
// and `_Tiled_LocalLights`, GTA VI 1.0.2.1) are of that shape too: groups of 64,
// and `_Tiled_LocalLights`, the game, build 1.0.2.1) are of that shape too: groups of 64,
// an LDS read and write in one lane-branch region, so no other form translates
// them on 32-lane hosts and their dispatches were dropped (no volumetric light
// or fog on NVIDIA). Widened, they translate (4 and 7 branches taken wave-wide).
@@ -897,6 +897,35 @@ fn widen(
}
/// The translated program, and the wave size it requires of the host.
/// Which programs get the branches that close or leave their loops taken by each host wave
/// together where cross-lane code depends on the wave ([`emit_program`]):
/// - unset or `1`: console wave64 compute programs on a host of 32-lane waves;
/// - `2`: every compute program;
/// - `0`: none, as before.
fn loops_wave(native: &NativeProgram) -> bool {
if native.stage != HwStage::Cs {
return false;
}
match std::env::var("VICTORY_LOOPS_WAVE").ok().as_deref().map(str::trim) {
Some("0") => false,
Some("2") => true,
_ => native.wave64 && lower::host_max_wave() == 32,
}
}
/// [`emit_program_plain`]; a program that comes out depending on the host's waves is
/// translated once more with the per-lane branches that close or leave its loops taken by
/// each host wave together ([`structure::structure_wide_host`]), and that translation is the
/// one given if it needs no wider waves.
///
/// Why: the lowering turns the console's wave loops into loops each lane leaves on its own,
/// and takes the code behind a loop as code the whole wave runs together. On NVIDIA the lanes
/// that left a loop early run on as a wave of their own, so a ballot, a first-lane read or an
/// exchange between the halves of a console wave behind the loop saw a part of the wave.
/// Seen in `water_shading:CS_TransmissionVolumetrics_GenerateTiles` (the game, build 1.0.2.1, capture
/// water2): the tiles with local lights never counted themselves in (the lanes without one
/// arrived later and wrote "no lane" over their ballot), their list stayed empty and those
/// tiles of the water kept no light: dark rectangles beside lit objects.
fn emit_program(
c: &Container,
native: &NativeProgram,
@@ -904,6 +933,53 @@ fn emit_program(
st: &structure::Structured,
io: &io::Io,
res: &resource::Resources,
) -> Result<(HostShader, Option<u32>), ShaderError> {
let first = emit_program_plain(c, native, p, st, io, res);
let Ok((_, Some(wave))) = &first else {
return first;
};
if !loops_wave(native) || !st.host_wide.is_empty() {
return first;
}
let loops = lower::loop_branches(p, st);
if loops.is_empty() {
return first;
}
let needs = lower::take_needs();
let again = structure::structure_wide_host(p, &st.wide, &loops).and_then(|st| {
let res = resource::track(p, &native.layout, native.stage, Some(&st))?;
emit_program_plain(c, native, p, &st, io, &res)
});
let why = std::env::var_os("VICTORY_WAVE_WHY").is_some();
match again {
Ok((shader, Some(w))) if w <= *wave => {
if why {
eprintln!("WAVE-LOOPS {} loop branches taken by each host wave together", loops.len());
}
lower::take_needs();
Ok((shader, Some(w)))
}
other => {
if why {
let what = match &other {
Ok((_, w)) => format!("wave {w:?}"),
Err(e) => e.to_string(),
};
eprintln!("WAVE-LOOPS not taken ({} loop branches): {what}", loops.len());
}
lower::set_needs(needs);
first
}
}
}
fn emit_program_plain(
c: &Container,
native: &NativeProgram,
p: &ir::Program,
st: &structure::Structured,
io: &io::Io,
res: &resource::Resources,
) -> Result<(HostShader, Option<u32>), ShaderError> {
let sig = |fourcc| -> Result<Vec<container::SigElement>, ShaderError> {
match c.part(fourcc) {
+3
View File
@@ -233,6 +233,8 @@ pub(crate) struct Shader {
pub wave_size: Option<u32>,
/// Thread-group shared memory, in dwords.
pub lds_dwords: u32,
/// Of those, the program's own (the first ones; ours follow).
pub title_lds_dwords: u32,
lds: Option<V>,
main: V,
pub entry: usize,
@@ -286,6 +288,7 @@ impl Shader {
threads: None,
wave_size: None,
lds_dwords: 0,
title_lds_dwords: 0,
lds: None,
main,
entry,