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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,8 @@ Thumbs.db

# A TypeScript sample shipped with the systematic-debugging skill; .ts is not on the policy allowlist.
/.claude/skills/systematic-debugging/condition-based-waiting-example.ts

disasm.txt
disasm-adaptive.txt
translate-results.txt
shader-dumps/
1 change: 0 additions & 1 deletion TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@ The goal: a console-like experience on PC. The game starts straight into play, h

| ID | Task | Where | Needs |
|----|------|-------|-------|
| C-1 | CI is red on clippy: `resource.rs:2553` (`placed_filler_twins` unused), `indirect.rs:2453` (`depth_written` never read), `fpsbox.rs:174` (`contains_key` then `insert`), `draw.rs:2577` (`sort_unstable_by_key`), `queue.rs:672`, `shadow.rs:2803` and `shadow.rs:3325` (`is_multiple_of`). All in `leonida-gpu`, all inherited from victory-gta6. | `leonida-gpu` | - |
| C-2 | Failing test `indirect::tests::warp_budget_saturates_without_wraparound_and_preserves_draw_fields`, inherited from victory-gta6. Upstream VIctory `4ab20fc` ("the indirect budget is charged in record order and no longer wraps") may fix it; not checked. | `leonida-gpu` | - |
| C-3 | `cargo fmt --check` reports about 1,420 differences. Run `cargo fmt` once, in a pull request of its own, at a moment when no other pull request is open (it touches almost every file), then add the check to CI. | all | - |
| C-4 | 163 `shortcut:` markers where the code approximates the console (79 in `leonida-gpu`, 55 in `leonida-shader`, 23 in `leonida-hle`, 4 in `leonida-formats`, 2 in `leonida-loader`). Replace them with the console's real behaviour, one per pull request. | all | game |
Expand Down
44 changes: 44 additions & 0 deletions crates/leonida-gpu/src/descriptor/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ pub(crate) struct HostHeap {
/// (`leonida_shader::emit::SLOT_STRIDES`): an upload buffer of
/// `SLOT_STRIDES_COUNT` dwords, its GPU address and its mapping.
strides: Option<(ID3D12Resource, u64, usize)>,
/// View heaps: the title address of the view at each slot, for shaders
/// that take a heap-picked descriptor's address as a pointer
/// (`leonida_shader::emit::SLOT_VIEW_ADDRS`): an upload buffer of
/// 2 * `SLOT_VIEW_ADDRS_COUNT` dwords, its GPU address and its mapping.
view_addrs: Option<(ID3D12Resource, u64, usize)>,
/// Title slots holding buffer views. Such a view gets its host slot
/// (and its memory a host copy) only when something reads it: a draw
/// through a table, or [`HostHeap::buffer_slots`] for shaders that pick
Expand Down Expand Up @@ -943,6 +948,19 @@ impl HostHeap {
Some((buffer, gpu, data as usize))
})
.flatten();
let view_addrs = (!sampler)
.then(|| {
let bytes = u64::from(leonida_shader::emit::SLOT_VIEW_ADDRS_COUNT) * 8;
let (buffer, data) = host.upload_buffer(bytes)?;
// SAFETY: the buffer's whole mapping; a live buffer.
let gpu = unsafe {
std::ptr::write_bytes(data, 0, bytes as usize);
buffer.GetGPUVirtualAddress()
};
crate::host::name(&buffer, || "view addresses by view heap slot".to_owned());
Some((buffer, gpu, data as usize))
})
.flatten();
let h = HostHeap {
heap,
cpu,
Expand All @@ -957,6 +975,7 @@ impl HostHeap {
free: std::sync::atomic::AtomicU32::new(DYNAMIC),
too_long: std::sync::atomic::AtomicU32::new(u32::MAX),
strides,
view_addrs,
buffers: Mutex::default(),
changed: Mutex::default(),
textures: Mutex::default(),
Expand Down Expand Up @@ -1119,6 +1138,16 @@ impl HostHeap {
self.strides.as_ref().map(|s| &s.0)
}

/// The GPU address table of title view addresses by view heap slot.
pub(crate) fn view_addrs_gpu(&self) -> Option<u64> {
self.view_addrs.as_ref().map(|s| s.1)
}

/// The table's buffer, for a list to hold.
pub(crate) fn view_addrs_buffer(&self) -> Option<&ID3D12Resource> {
self.view_addrs.as_ref().map(|s| &s.0)
}

/// Up to `max` title slots whose texture view is due at `frame`, each
/// with its write number, in the order to serve them
/// ([`TextureQueue::due`]), and the queue's counts
Expand Down Expand Up @@ -1603,6 +1632,21 @@ impl HostHeap {
// dword, either value is one the slot had).
unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0)) };
}
if let Some((_, _, data)) = &self.view_addrs
&& index < leonida_shader::emit::SLOT_VIEW_ADDRS_COUNT
{
let (lo, hi) = view
.and_then(buffer_range)
.map_or((0u32, 0u32), |(start, _)| {
(start as u32, (start >> 32) as u32)
});
let p = *data as *mut u32;
// SAFETY: inside the mapping; shaders read it while we write.
unsafe {
p.add(index as usize * 2).write_volatile(lo);
p.add(index as usize * 2 + 1).write_volatile(hi);
}
}
let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
let was = if stride.is_some() {
buffers.insert(index);
Expand Down
47 changes: 36 additions & 11 deletions crates/leonida-gpu/src/draw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1225,7 +1225,7 @@ impl State {
if srv && slot == leonida_shader::emit::SLOT_STRIDES {
// Ours, not the title's: the shader picks buffers
// from the view heap by an index it computes.
match self.heap_buffers(list) {
match self.heap_buffers(list, false) {
// SAFETY: an open list; the table lives as long
// as the heap the list holds.
Some(gpu) => unsafe {
Expand All @@ -1239,6 +1239,24 @@ impl State {
}
continue;
}
if srv && slot == leonida_shader::emit::SLOT_VIEW_ADDRS {
// Ours: the title address of each view in the heap.
match self.heap_buffers(list, true) {
// SAFETY: an open list; the table lives as long
// as the heap the list holds.
Some(gpu) => unsafe {
if compute {
l.SetComputeRootShaderResourceView(param, gpu);
} else {
l.SetGraphicsRootShaderResourceView(param, gpu);
}
},
None => once!(
"a shader reads view addresses from a view heap that is not set"
),
}
continue;
}
let tabled = srv && crate::pipeline::host::bounded_root_srvs();
let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot))
else {
Expand Down Expand Up @@ -1518,25 +1536,29 @@ impl State {
}

/// For a shader that picks buffers from the view heap by an index it
/// computes (SM 6.6 dynamic resources): the GPU address of the heap's
/// table of element strides, with every buffer view of the heap given
/// its host slot and its memory brought up to date when `list` is
/// submitted. Tables tell us which views a draw reads; nothing tells
/// us which of the heap's a computed index names, so all of them are
/// made ready, once per list.
/// computes (SM 6.6 dynamic resources): the GPU address of the stride or
/// title-address table selected by `view_addrs`. Every buffer view of
/// the heap gets its host slot and its memory is brought up to date when
/// `list` is submitted. Tables tell us which views a draw reads; nothing
/// tells us which of the heap's a computed index names, so all are made
/// ready, once per list.
/// shortcut: the buffers are read, not written: what such a shader
/// writes through a picked unordered access view stays in the host
/// copy. A list refreshes them where it first runs such a shader;
/// title writes recorded later in the same list are not seen.
fn heap_buffers(&self, list: &HostList) -> Option<u64> {
fn heap_buffers(&self, list: &HostList, view_addrs: bool) -> Option<u64> {
let heap = self
.heaps
.iter()
.filter(|&&h| h != 0)
.map(|&h| crate::descriptor::heap(h as This))
.find(|h| !h.samplers())?;
let host = heap.host()?;
let gpu = host.strides_gpu()?;
let gpu = if view_addrs {
host.view_addrs_gpu()?
} else {
host.strides_gpu()?
};
// One key per list, as textures have: no title resource is there.
const ONCE: usize = usize::MAX - 0x5e;
if !list.first_use(ONCE) {
Expand All @@ -1546,6 +1568,9 @@ impl State {
if let Some(buffer) = host.strides_buffer() {
list.keep(buffer);
}
if let Some(buffer) = host.view_addrs_buffer() {
list.keep(buffer);
}
// The pass itself once per frame: per list it ran up to 51 times a
// frame over 81,000 views and 4,100 host copies, 18 s of every
// frame (2026-11-24, run 11).
Expand Down Expand Up @@ -2574,7 +2599,7 @@ impl State {
let draws: u32 = census.1.values().sum();
if draws > 0 {
let mut rects: Vec<([i32; 4], u32)> = census.1.iter().map(|(r, n)| (*r, *n)).collect();
rects.sort_unstable_by(|a, b| b.1.cmp(&a.1));
rects.sort_unstable_by_key(|r| std::cmp::Reverse(r.1));
let scissors: Vec<String> = rects
.iter()
.take(5)
Expand Down Expand Up @@ -3321,7 +3346,7 @@ impl State {
// the record drawn before it.
if (6..=8).contains(&why_not) {
static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 256 == 0 {
if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) .is_multiple_of(256) {
let (last_copy, last_offset) = self.last_indirect;
tracing::info!(
"a window miss (one in 256): cause {why_not}, kind {kind}, stride {stride}, buffer {} offset {offset:#x} ({} left); the command before it on the list: buffer {last_copy} offset \
Expand Down
4 changes: 2 additions & 2 deletions crates/leonida-gpu/src/fpsbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ pub(crate) fn draw(host: &crate::host::Host, list: &ID3D12GraphicsCommandList, b
made.clear();
}
let key = (tenths, format.0, scale);
if !made.contains_key(&key) {
if let std::collections::hash_map::Entry::Vacant(e) = made.entry(key) {
let (w, h, lit) = bitmap(&text(tenths), scale);
let pitch = (w as usize * bytes).next_multiple_of(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT as usize);
let Some((buffer, data)) = host.shared_buffer((pitch * h as usize) as u64) else {
Expand All @@ -185,7 +185,7 @@ pub(crate) fn draw(host: &crate::host::Host, list: &ID3D12GraphicsCommandList, b
pixel(format, lit[y * w as usize + x], &mut out[at..at + bytes]);
}
}
made.insert(key, Made { buffer, width: w, height: h, pitch: pitch as u32 });
e.insert(Made { buffer, width: w, height: h, pitch: pitch as u32 });
}
let Some(m) = made.get(&key) else {
return;
Expand Down
1 change: 1 addition & 0 deletions crates/leonida-gpu/src/indirect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2450,6 +2450,7 @@ void work() {
heap_pairs: [[Option<ID3D12DescriptorHeap>; 2]; 2],
tables: [D3D12_GPU_DESCRIPTOR_HANDLE; 2],
targets: [D3D12_CPU_DESCRIPTOR_HANDLE; 2],
#[allow(dead_code)] // TODO C-2: pending upstream VIctory 4ab20fc
depth_written: D3D12_CPU_DESCRIPTOR_HANDLE,
depth_tested: D3D12_CPU_DESCRIPTOR_HANDLE,
stamps: ID3D12QueryHeap,
Expand Down
1 change: 1 addition & 0 deletions crates/leonida-gpu/src/pipeline/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,7 @@ impl HostPipeline {
slot == leonida_shader::emit::SLOT_FAULTS
} else {
slot == leonida_shader::emit::SLOT_STRIDES
|| slot == leonida_shader::emit::SLOT_VIEW_ADDRS
|| slot == leonida_shader::emit::SLOT_MEMORY
};
if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() {
Expand Down
2 changes: 1 addition & 1 deletion crates/leonida-gpu/src/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -687,7 +687,7 @@ fn send_joined(joined: &mut Joined) {
let sent = JOINED[1].fetch_add(1, Ordering::Relaxed) + 1;
JOINED[2].fetch_add(order.len() as u64, Ordering::Relaxed);
JOINED[3].fetch_add(joined.signals.len() as u64, Ordering::Relaxed);
if sent % 2048 == 0 {
if sent.is_multiple_of(2048) {
let n: Vec<u64> = JOINED.iter().map(|n| n.swap(0, Ordering::Relaxed)).collect();
tracing::info!(
"parts joined (LEONIDA_JOIN_PARTS=1): {} parts went to the host in {} submissions ({:.1} parts, {:.1} lists each), {} signals delivered behind them, {} waits passed for a write of a part not sent yet",
Expand Down
2 changes: 2 additions & 0 deletions crates/leonida-gpu/src/resource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2553,10 +2553,12 @@ static PLACED_TWINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64

/// See [`PLACED_TWINS`].
#[cfg(windows)]
#[allow(dead_code)] // read by the copystat memory log (diagnostics builds)
pub(crate) fn placed_filler_twins() -> u64 {
PLACED_TWINS.load(std::sync::atomic::Ordering::Relaxed)
}


/// Width, height and format of texture `this` (`None` for a buffer), for
/// `crate::texback`'s kinds.
#[cfg(windows)]
Expand Down
4 changes: 2 additions & 2 deletions crates/leonida-gpu/src/shadow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2935,7 +2935,7 @@ impl Shadow {
}
OWN_WRITES[1].fetch_add(bytes.len() as u64, Ordering::Relaxed);
let n = OWN_WRITES[0].fetch_add(1, Ordering::Relaxed) + 1;
if n % 16384 == 0 {
if n.is_multiple_of(16384) {
tracing::info!(
"what shaders wrote, stored through views of our own (LEONIDA_BACK_OWN_VIEW=1), since the start: {n} stretches {} MB, {} pages noted current for the copy that wrote them (not copied in again), {} stretches written the old way; with LEONIDA_BACK_OWN_CHECK=1: {} stores the title's address did not show, {} pages noted current whose CPU side differs from title memory, {} of those with the guard clean",
OWN_WRITES[1].load(Ordering::Relaxed) >> 20,
Expand Down Expand Up @@ -3457,7 +3457,7 @@ impl Shadow {
COPY_CHANGED[1].fetch_add(sent as u64, Ordering::Relaxed);
COPY_CHANGED[2].fetch_add(stretches.len() as u64, Ordering::Relaxed);
let calls = COPY_CHANGED[3].fetch_add(1, Ordering::Relaxed) + 1;
if calls % 65536 == 0 {
if calls.is_multiple_of(65536) {
tracing::info!(
"copies in the card's memory, refreshed by what differs (LEONIDA_COPY_CHANGED=1), since the start: {calls} refreshes read {} MB of title memory the title had written to; {} MB of it differed from the copy and went on to the card, in {} stretches",
COPY_CHANGED[0].load(Ordering::Relaxed) >> 20,
Expand Down
4 changes: 2 additions & 2 deletions crates/leonida-gpu/src/watch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,7 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve
fn failed_asking(start: usize, end: usize) {
use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery};
static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 2048 != 0 {
if !N.fetch_add(1, std::sync::atomic::Ordering::Relaxed).is_multiple_of(2048) {
return;
}
// SAFETY: plain data filled in by the query.
Expand Down Expand Up @@ -869,7 +869,7 @@ fn protect_here(g: &mut Guards, from: usize, to: usize) {
#[cfg(feature = "diagnostics")]
{
static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 1024 == 0 {
if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) .is_multiple_of(1024) {
tracing::info!("a block of title memory could not be made read-only (one in 1024): {:#x}: {error}", block * BLOCK);
}
}
Expand Down
59 changes: 58 additions & 1 deletion crates/leonida-shader/src/emit/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2743,9 +2743,66 @@ impl<'a> Lower<'a> {
/// descriptor holds more in the second dword, the stride from bit 16
/// up; code that takes the address masks those away.)
fn view_address(&mut self, site: Site) -> Option<(V, V)> {
use super::shader::USER_VIEW_ADDRESS;
use super::shader::{SLOT_VIEW_ADDRS, SLOT_VIEW_ADDRS_COUNT, USER_VIEW_ADDRESS};
let a = self.scalar.get(&site).copied()?;
let rp = *self.x.native.layout.get(a.param)?;
let count = match self.x.p.blocks.get(site.0)?.insts.get(site.1)?.name()
.strip_prefix("s_load_dword")?
{
"" => 1,
"x2" => 2,
"x4" => 4,
"x8" => 8,
"x16" => 16,
_ => return None,
};
if rp.root == RootType::ResourceHeap
&& let Some(dynamic) = a.dynamic
&& count <= 4
{
let c = self.cur;
let mut slot = self.i32_of(dynamic).ok()?;
if a.offset != 0 {
let offset = self.s.m.i32(a.offset);
slot = self.s.m.bin(c, Bin::Add, slot, offset);
}
let five = self.s.m.i32(5);
slot = self.s.m.bin(c, Bin::LShr, slot, five);
let last = self.s.m.i32(SLOT_VIEW_ADDRS_COUNT - 1);
slot = self
.s
.op(c, "binary.i32", Attr::ReadNone, self.s.t.i32, 40, &[slot, last]);
self.s.m.tag(slot, Tag::Clamp);
let three = self.s.m.i32(3);
let at = self.s.m.bin(c, Bin::Shl, slot, three);
let h = self.s.root_srv_handle(SLOT_VIEW_ADDRS);
let u = self.s.m.undef(self.s.t.i32);
let mask = self.s.m.i8(1);
let align = self.s.m.i32(4);
let low = self.s.op(
c,
"rawBufferLoad.f32",
Attr::ReadOnly,
self.s.t.res_ret,
139,
&[h, at, u, mask, align],
);
let raw_lo = self.s.m.extract(c, low, 0);
let lo = self.as_int(raw_lo);
let four = self.s.m.i32(4);
let hi_at = self.s.m.bin(c, Bin::Add, at, four);
let high = self.s.op(
c,
"rawBufferLoad.f32",
Attr::ReadOnly,
self.s.t.res_ret,
139,
&[h, hi_at, u, mask, align],
);
let raw_hi = self.s.m.extract(c, high, 0);
let hi = self.as_int(raw_hi);
return Some((lo, hi));
}
if rp.root != RootType::Table || a.dynamic.is_some() || a.offset % 32 != 0 {
return None;
}
Expand Down
3 changes: 2 additions & 1 deletion crates/leonida-shader/src/emit/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,8 @@ pub use lower::set_host_max_wave;
pub use rect::rect_list_gs;
pub use shader::{
MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES,
SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
SLOT_STRIDES_COUNT, SLOT_VIEW_ADDRS, SLOT_VIEW_ADDRS_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE,
USER_VIEW_ADDRESS, USER_VIEW_BIAS,
set_view_heap_limit, view_heap_limit,
};

Expand Down
Loading