From c2c6bc5ef916e2bcc2cd0fc3340359dde1952351 Mon Sep 17 00:00:00 2001 From: Zack Date: Mon, 30 Nov 2026 19:18:17 -0800 Subject: [PATCH 1/5] d3d12: LEONIDA_LIST_TWIN_MOVE=1 moves the raw twins a list keeps to their views (D3D12-RDNA-GBUFFER-TERRAIN-TILES) The raw twin of a buffer view that does not begin on 16 bytes is moved to where its view begins only in the one slot views are made in beside the heaps (move_raw, where the card's CPU descriptors hold the hardware descriptor). A twin made in a slot a list keeps its views in is left at the multiple of 16 before its view, with a bias, or null. So such a card has moved twins in the title's slots and biased or null ones in the tables its lists make. monte-alt/vesper 7b7e556 (GPL-3.0, as this) moves both kinds (its TwinSlot::private) and has no bias; it draws on an RX 9070 XT the ground this tree leaves black in patches (#2770). With LEONIDA_LIST_TWIN_MOVE=1 a list's own twins are moved too where move_raw applies; elsewhere nothing changes. Off by default: that the patches come from here is a hypothesis, and which of the two kinds of card an RX 7800 XT or an RX 9070 XT is was not measured (no such card here). By turns with LEONIDA_AB in a diagnostics build; the frame line of the raw twins counts those moved. Tests: a_twin_in_a_lists_own_slot_is_moved_to_its_view (descriptor memory of the test's own: moved with the switch, biased without; it fails with the list branch of own_slot off). listed_twins_moved_readback reads through moved twins on a card that has raw twins: ignored and not run, it needs an AMD card. AI-assisted (Claude Fable 5.2; reviewed by GPT-6.2 Astra and Claude Opus 5.5). Tested on RTX 3090, driver 610.88, and on WARP: leonida-gpu lib tests 597 passed (677 with --features diagnostics), no clippy warning on the changed lines. Not run on an AMD card. Refs #2771 Refs #2770 AI-assisted: yes --- d3d12/crates/leonida-gpu/src/descriptor.rs | 7 +- .../crates/leonida-gpu/src/descriptor/host.rs | 70 +++++++++++- .../src/descriptor/host/listed_raw_tests.rs | 104 +++++++++++++++++- 3 files changed, 169 insertions(+), 12 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/descriptor.rs b/d3d12/crates/leonida-gpu/src/descriptor.rs index 1078802037..16acead525 100644 --- a/d3d12/crates/leonida-gpu/src/descriptor.rs +++ b/d3d12/crates/leonida-gpu/src/descriptor.rs @@ -650,14 +650,15 @@ static SYNC_SPLIT: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomi /// Nothing while no heap page changed. #[cfg(windows)] pub(crate) fn sync_line(frames: f64) { - let [twins, moved, lost, biased] = [0, 1, 2, 3].map(|i| host::TWINS[i].swap(0, std::sync::atomic::Ordering::Relaxed)); + let [twins, moved, lost, biased, listed] = [0, 1, 2, 3, 4].map(|i| host::TWINS[i].swap(0, std::sync::atomic::Ordering::Relaxed)); if twins > 0 { tracing::info!( - "raw twins of buffer views made per frame (LEONIDA_RAW_VIEWS=0: none): {:.0}, of them {:.1} that do not begin on 16 bytes ({:.1} null, {:.1} kept from 16 bytes before with a bias; LEONIDA_TWIN_BIAS=0: null)", + "raw twins of buffer views made per frame (LEONIDA_RAW_VIEWS=0: none): {:.0}, of them {:.1} that do not begin on 16 bytes ({:.1} null, {:.1} kept from 16 bytes before with a bias; LEONIDA_TWIN_BIAS=0: null; {:.1} of those a list keeps moved to their view with LEONIDA_LIST_TWIN_MOVE=1)", twins as f64 / frames, moved as f64 / frames, lost as f64 / frames, - biased as f64 / frames + biased as f64 / frames, + listed as f64 / frames ); } let [pages, looked, mirrored, micros, tabled, later, waited] = [0, 1, 2, 3, 4, 5, 6].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); diff --git a/d3d12/crates/leonida-gpu/src/descriptor/host.rs b/d3d12/crates/leonida-gpu/src/descriptor/host.rs index 84fb2b4450..c2d38d7ae5 100644 --- a/d3d12/crates/leonida-gpu/src/descriptor/host.rs +++ b/d3d12/crates/leonida-gpu/src/descriptor/host.rs @@ -3886,7 +3886,10 @@ impl HostHeap { LIST_VIEWS.with(|views| { let mut views = views.borrow_mut(); if views.is_none() { - *views = Some(ListViews::new()?); + let made = ListViews::new()?; + // (Its slots are this thread's own, as the one beside the heaps: `own_slot`.) + LIST_SLOTS.set((made.start, made.start + ListViews::SLOTS as usize * made.step)); + *views = Some(made); } let views = views.as_mut()?; if views.recording != recording { @@ -5190,8 +5193,9 @@ fn buffer_view_ok(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: /// Raw twins ([`raw_twins`]) made since the last frame line, and those of them that /// do not begin on 16 bytes, as a raw view must ([`move_raw`]), and those of /// these that could not be moved there (null), and those of these kept from -/// the 16 bytes before them with a bias instead ([`twin_bias`]). -pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; +/// the 16 bytes before them with a bias instead ([`twin_bias`]), and those +/// moved in a slot a list keeps its views in ([`list_twin_move`]). +pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; /// Whether the raw twin of a buffer view that does not begin on 16 bytes is /// kept, made from the multiple of 16 before the view, with the bytes it @@ -5227,13 +5231,71 @@ fn with_twin_bias(word: u32, bias: u32) -> u32 { (word & !VIEW_BIAS_MASK) | ((bias << VIEW_BIAS_SHIFT) & VIEW_BIAS_MASK) } +thread_local! { + /// Where the slots this thread keeps a recording's views in lie ([`ListViews`]: their + /// first byte and the one past their last; none before it has any), for [`own_slot`]. + /// (Plain data: no destructor.) + static LIST_SLOTS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) }; +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`list_twin_move`], for its thread only. + pub(crate) static TEST_LIST_TWIN_MOVE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Whether the raw twin of a view a list keeps is moved to where its view begins, as the one +/// made beside the heaps is (`LEONIDA_LIST_TWIN_MOVE=1`; off by default: left where it was +/// made, with a bias or null). Only where the card's descriptors can be moved ([`move_raw`]); +/// a list's slot ([`ListViews`]) is this thread's own in a heap the card does not see, as +/// [`staged`]'s. By turns with `LEONIDA_AB`. +/// +/// Such a twin is left where it was made, at the multiple of 16 before its view: with a bias +/// ([`twin_bias`]), or null where the view begins off its dwords (16-bit values at an odd +/// one). So a card whose descriptors [`move_raw`] moves has moved twins in the title's slots +/// and biased or null ones in the tables its lists make, and a card it does not move (an +/// RX 6800: [`twin_bias`]) biased ones everywhere. Which of the two an RX 7800 XT or an +/// RX 9070 XT is was not measured here (no such card). What cards have shown: on an +/// RX 7900 XT the picture broke when twins were first kept with a bias (#2702, where the +/// reporter asked for the bias only where `move_raw` cannot apply), and monte-alt/vesper +/// 7b7e556 (GPL-3.0, as this), which moves both kinds (its `TwinSlot::private`) and has no +/// bias, draws on an RX 9070 XT the ground this tree leaves black in patches (#2770). +/// Whether those patches come from here is not known until it is tried on such a card: +/// `listed_twins_moved_readback` (ignored: it needs one) reads through moved twins there. +fn list_twin_move() -> bool { + #[cfg(test)] + if let Some(on) = TEST_LIST_TWIN_MOVE.get() { + return on; + } + crate::asked!("LEONIDA_LIST_TWIN_MOVE") +} + +/// Which slot of this thread's own, in a heap the card does not see, `twin` is, if it is one +/// [`move_raw`] may write: the one views are made in beside the heaps ([`staged`]; false), or +/// one of those it keeps a recording's views in ([`list_twin_move`]; true). +fn own_slot(twin: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { + if staged(false, 1).is_some_and(|s| s.ptr == twin.ptr) { + return Some(false); + } + let (from, to) = LIST_SLOTS.get(); + ((from..to).contains(&twin.ptr) && list_twin_move()).then_some(true) +} + /// For a raw twin at `twin` showing from `start` (GPU address) `bytes`, /// `by` bytes before its view ([`twin_window`]): moved to the view /// ([`move_raw`]) where it can be, else kept with a dword-aligned bias /// ([`twin_bias`]), else made null. fn settle_twin(twin: D3D12_CPU_DESCRIPTOR_HANDLE, start: u64, bytes: u32, by: u32) { use std::sync::atomic::Ordering::Relaxed; - if by == 0 || (staged(false, 1).is_some_and(|s| s.ptr == twin.ptr) && move_raw(twin, start, bytes, by)) { + if by == 0 { + return; + } + if let Some(listed) = own_slot(twin) + && move_raw(twin, start, bytes, by) + { + if listed { + TWINS[4].fetch_add(1, Relaxed); + } return; } if twin_bias() && by < 16 && by.is_multiple_of(4) && by < bytes { diff --git a/d3d12/crates/leonida-gpu/src/descriptor/host/listed_raw_tests.rs b/d3d12/crates/leonida-gpu/src/descriptor/host/listed_raw_tests.rs index 24da6bf47a..5e5b3ab17c 100644 --- a/d3d12/crates/leonida-gpu/src/descriptor/host/listed_raw_tests.rs +++ b/d3d12/crates/leonida-gpu/src/descriptor/host/listed_raw_tests.rs @@ -18,6 +18,22 @@ void main() { } "#; +/// Whether a list's own twins are moved ([`list_twin_move`]), on a test's thread until it is +/// dropped. +struct TwinMove(Option); + +impl TwinMove { + fn set(on: bool) -> Self { + Self(TEST_LIST_TWIN_MOVE.replace(Some(on))) + } +} + +impl Drop for TwinMove { + fn drop(&mut self) { + TEST_LIST_TWIN_MOVE.set(self.0); + } +} + /// A per-list view at 4, 8 and 12 bytes past a multiple of 16: its raw twin is made from the /// multiple of 16 before it with the bias in its slot's stride word (`twin_bias`), and a program /// that adds the bias reads the view's own dwords through it, and zeros past its end. Public @@ -25,6 +41,24 @@ void main() { #[test] #[ignore = "offscreen descriptor probe requiring a host with raw view twins"] fn listed_off_alignment_raw_twin_readback() { + listed_readback(false); +} + +/// The same with the twins a list keeps moved to their views (`LEONIDA_LIST_TWIN_MOVE=1`), for +/// a card whose descriptors `move_raw` moves (not run on one: there was none here): the slots' +/// stride words then hold no bias, and a program reads the view's own dwords through the twin +/// with a bias of 0, and zeros past its end. On a card it does not move, the twins keep their +/// bias, as above. +#[test] +#[ignore = "offscreen descriptor probe requiring a host with raw view twins"] +fn listed_twins_moved_readback() { + listed_readback(true); +} + +/// [`listed_off_alignment_raw_twin_readback`], with a list's own twins moved where they can be +/// if `move_twins`. +fn listed_readback(move_twins: bool) { + let _moved = TwinMove::set(move_twins); const SIZE: u64 = 4096; const POISON: u32 = 0xfeed_face; let host = host().expect("an active D3D12 device"); @@ -181,11 +215,14 @@ fn listed_off_alignment_raw_twin_readback() { heap.copy_from(slot + 1, cpu.slot(1)); } let expected = [values[start as usize], values[start as usize + 1]]; - // The words: R32_UINT (4 bytes, integer) and the twin's bias, made and copied alike. + // The words: R32_UINT (4 bytes, integer) and the twin's bias, made and copied alike; no + // bias where the twin was moved to its view. + let moved = word(first) & leonida_shader::emit::VIEW_BIAS_MASK == 0; + let kept = if moved { 0 } else { bias }; for slot in [first, first + 1] { assert_eq!( word(slot), - 4 | leonida_shader::emit::VIEW_INTEGER | bias << leonida_shader::emit::VIEW_BIAS_SHIFT, + 4 | leonida_shader::emit::VIEW_INTEGER | kept << leonida_shader::emit::VIEW_BIAS_SHIFT, "stride word of slot {slot}" ); } @@ -195,8 +232,10 @@ fn listed_off_alignment_raw_twin_readback() { // The view's own two dwords, then nothing past its end. run(heap.raw + slot, first + 3, slot, [0, target_bias], expected); run(heap.raw + slot, first + 3, slot, [8, target_bias], [0; 2]); - // Without the bias: the 16 bytes before the view's place, where the twin begins. - run(heap.raw + slot, first + 3, first + 2, [0, target_bias], [values[4], values[5]]); + // Without the bias: where the twin begins, at its view if it was moved, else the 16 + // bytes before the view's place. + let begins = if moved { expected } else { [values[4], values[5]] }; + run(heap.raw + slot, first + 3, first + 2, [0, target_bias], begins); } for slot in [first + 2, first + 4] { run(slot, slot + 1, first + 2, [bias, target_bias], expected); @@ -209,8 +248,10 @@ fn listed_off_alignment_raw_twin_readback() { target_bias + 8, target_bias, ); + // A list's twin is moved exactly where that is asked for and the card's descriptors can be. + assert_eq!(moved, move_twins && srv_guard, "bias {bias}: move asked {move_twins}, layout guard {srv_guard}"); println!( - "source bias {bias}, target bias {target_bias}: listed twins read right with their bias, public transfer correct, existing layout guard SRV={srv_guard} UAV={uav_guard}" + "source bias {bias}, target bias {target_bias}: listed twins read right (moved to their views: {moved}), public transfer correct, existing layout guard SRV={srv_guard} UAV={uav_guard}" ); } } @@ -454,3 +495,56 @@ fn sub_dword_views_null_twins_and_recycled_raw_cbv_clears_bias() { "constant_raw_at must clear stale twin bias when recycling a dynamic slot" ); } + +/// With `LEONIDA_LIST_TWIN_MOVE=1` a raw twin in a slot a list keeps its views in is moved to +/// where its view begins, as one in the slot beside the heaps is: the programs add no bias, and +/// one off its dwords is no null view. Without it, and in a slot that is not the thread's own, +/// it stays where it was made, with its bias. +#[test] +fn a_twin_in_a_lists_own_slot_is_moved_to_its_view() { + if !twin_bias() { + return; + } + // What a card whose descriptors can be moved holds for a raw buffer view (`move_raw`): its + // address, its bytes, then words that are not looked at. Made up, in memory that stands + // for the slots: no card is asked. + const START: u64 = 0x12_3456_7000; + const BYTES: u32 = 400; + let made = [START as u32, (START >> 32) as u32, BYTES, 0x1234_abcd, 5, 6, 7, 8]; + let mut slots = [made; 2]; + let first = slots.as_mut_ptr(); + let at = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: first.wrapping_add(i) as usize }; + // SAFETY: a slot of `slots`, which lives to the end of the test and is read through `first` alone. + let read = |i: usize| unsafe { first.add(i).read() }; + // SAFETY: as above. + let reset = |i: usize| unsafe { first.add(i).write(made) }; + let moved = |by: u32| { + let to = START + u64::from(by); + [to as u32, (to >> 32) as u32, BYTES - by, 0x1234_abcd, 5, 6, 7, 8] + }; + let _ = take_twin_bias(); + // The first of the two is a list's; the second is no slot of the thread's. + let was = LIST_SLOTS.replace((at(0).ptr, at(1).ptr)); + { + let _on = TwinMove::set(true); + for by in [8u32, 2, 15] { + reset(0); + settle_twin(at(0), START, BYTES, by); + assert_eq!(take_twin_bias(), 0, "moved by {by}: nothing for the programs to add"); + assert_eq!(read(0), moved(by), "moved by {by}"); + } + // Not the descriptor it is taken for (another size): not moved, kept with its bias. + reset(0); + settle_twin(at(0), START, BYTES + 4, 8); + assert_eq!((take_twin_bias(), read(0)), (8, made)); + // No slot of the thread's own. + settle_twin(at(1), START, BYTES, 8); + assert_eq!((take_twin_bias(), read(1)), (8, made)); + } + { + let _off = TwinMove::set(false); + settle_twin(at(0), START, BYTES, 8); + assert_eq!((take_twin_bias(), read(0)), (8, made), "without LEONIDA_LIST_TWIN_MOVE=1: as before"); + } + LIST_SLOTS.set(was); +} From 4aac11147c0aae42436576e30c5b7f3eaa380dfd Mon Sep 17 00:00:00 2001 From: Zack Date: Mon, 30 Nov 2026 19:46:52 -0800 Subject: [PATCH 2/5] d3d12: LEONIDA_HOST_WAVE32=1 translates for waves of 32 lanes on an RDNA card (D3D12-RDNA-GBUFFER-TERRAIN-TILES) On a card whose widest wave has 64 lanes the translator emits the forms for 64 lanes (a console wave64 compute program runs with WaveSize(64)); a card of 32 lanes, every NVIDIA card, gets other forms of the same programs. The forms for 64 lanes run on AMD cards only, and none was at hand here. monte-alt/vesper 7b7e556 (GPL-3.0, as this) takes the forms for 32 lanes by default on such a card for the programs they fit (its VESPER_RDNA_WAVE32, default 2), and draws on an RX 9070 XT the ground this tree leaves black in patches (#2770; #2771 on an RX 7800 XT). With LEONIDA_HOST_WAVE32=1 the translator takes an AMD card with waves of 32 to 64 lanes (set_host_rdna) for one of 32: it gets what an NVIDIA card gets, WaveSize(32) declared where a form depends on it. A program the forms for 32 lanes cannot take is refused as there ("no wave32 lowering for this wave64 program"); vesper leaves those at 64, which this does not. Off by default: a switch to tell the two sets of forms apart on such a card. Reading found no defect in the forms for 64 lanes. The shader cache keys on the lanes taken (host_settings) and on the switch's value, so a run with it translates anew. host_wave32() says what the switch came to on the card, for the log. emit/lower.rs is over the repository's file size limit as it is on main (753,642 bytes of 655,360): the decision and its test are in emit/mod.rs, and lower.rs grows by the lines that ask it. AI-assisted (Claude Fable 5.2; reviewed by GPT-6.2 Astra and Claude Opus 5.5). Tested on RTX 3090, driver 610.88: leonida-shader lib tests 404 passed, also with --features diagnostics; no clippy warning on the changed lines. With LEONIDA_WARP=1 396 pass and 8 fail, the same 8 that fail on main (d4fabd3fe) so. Not run on an AMD card. Refs #2771 Refs #2770 AI-assisted: yes --- d3d12/crates/leonida-shader/src/emit/lower.rs | 10 ++++- d3d12/crates/leonida-shader/src/emit/mod.rs | 42 +++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/d3d12/crates/leonida-shader/src/emit/lower.rs b/d3d12/crates/leonida-shader/src/emit/lower.rs index 149963d93d..b893de23f3 100644 --- a/d3d12/crates/leonida-shader/src/emit/lower.rs +++ b/d3d12/crates/leonida-shader/src/emit/lower.rs @@ -2140,7 +2140,15 @@ pub(super) fn host_max_wave() -> u32 { if let Some(lanes) = TEST_HOST_WAVE.get() { return lanes; } - HOST_MAX_WAVE.load(std::sync::atomic::Ordering::Relaxed) + host_lanes()[1] +} + +/// The lanes of the host's widest wave ([`set_host_max_wave`]), and those the translator takes +/// it to have (`super::told_lanes`: `LEONIDA_HOST_WAVE32`). +pub(super) fn host_lanes() -> [u32; 2] { + let lanes = HOST_MAX_WAVE.load(std::sync::atomic::Ordering::Relaxed); + let rdna = HOST_RDNA.load(std::sync::atomic::Ordering::Relaxed); + [lanes, super::told_lanes(lanes, rdna, super::wave32_asked())] } #[cfg(test)] diff --git a/d3d12/crates/leonida-shader/src/emit/mod.rs b/d3d12/crates/leonida-shader/src/emit/mod.rs index f8730d8d4a..f1beb5faed 100644 --- a/d3d12/crates/leonida-shader/src/emit/mod.rs +++ b/d3d12/crates/leonida-shader/src/emit/mod.rs @@ -365,6 +365,37 @@ pub fn rdna_float() -> u32 { }) } +/// The lanes the translator takes a host whose widest wave is `lanes` to have: 32 where they +/// are more, on an AMD card with waves of 32 to 64 (`rdna`: [`set_host_rdna`]) that is `asked` +/// for it with `LEONIDA_HOST_WAVE32=1` (off by default). That translates for such a card as for +/// a card with waves of 32, to tell the two sets of forms apart on it: those for 32 lanes are +/// what every NVIDIA card runs (a program then declares `WaveSize(32)`, which such a card takes; +/// one whose narrowest wave is wider would not, so it is left alone), those for 64 lanes run +/// only on a card that has such waves. A program the forms for 32 lanes cannot take is refused, +/// as on a card of 32 lanes ("no wave32 lowering for this wave64 program"; monte-alt/vesper +/// 7b7e556, GPL-3.0 as this, takes the forms for 32 by default on such a card for the programs +/// they fit and leaves the others at 64: its `VESPER_RDNA_WAVE32`, which the reports name among +/// what was not told apart). For #2770 and #2771 (black patches of ground on an RX 9070 XT and +/// an RX 7800 XT); not run on such a card here. +/// +/// Part of the translation: the shader cache keys on the lanes taken ([`host_settings`]). +fn told_lanes(lanes: u32, rdna: bool, asked: bool) -> u32 { + if rdna && asked && lanes > 32 { 32 } else { lanes } +} + +/// Whether `LEONIDA_HOST_WAVE32=1` asks for [`told_lanes`]' 32. +fn wave32_asked() -> bool { + static ASKED: std::sync::OnceLock = std::sync::OnceLock::new(); + *ASKED.get_or_init(|| std::env::var_os("LEONIDA_HOST_WAVE32").is_some_and(|v| v == "1")) +} + +/// With `LEONIDA_HOST_WAVE32=1`: the lanes of the host's widest wave, and those the translator +/// takes it to have ([`told_lanes`]; the same where the host is not such a card), for the log. +/// `None` without it. +pub fn host_wave32() -> Option<[u32; 2]> { + wave32_asked().then(lower::host_lanes) +} + /// The bits of [`rdna_float`]. pub mod rdna { /// `v_max_f32` and the like: the host's FMax and FMin, without the code @@ -1755,6 +1786,17 @@ mod tests { use super::lower::LOOP_LIMIT; use super::parse_loop_limit; + /// `LEONIDA_HOST_WAVE32=1` has the translator take an AMD card with waves of 32 to 64 for + /// one of 32, and changes nothing without it or on another card. + #[test] + fn a_card_with_waves_of_32_to_64_is_taken_for_one_of_32_only_when_asked() { + use super::told_lanes; + assert_eq!([told_lanes(64, true, true), told_lanes(32, true, true), told_lanes(0, true, true)], [32, 32, 0]); + assert_eq!([told_lanes(64, true, false), told_lanes(32, true, false)], [64, 32], "not asked"); + assert_eq!([told_lanes(64, false, true), told_lanes(128, false, true)], [64, 128], "not such a card"); + assert_eq!(told_lanes(64, false, false), 64); + } + /// The LLVM text `dxc -dumpbin` prints for a DXIL container, when dxc /// is installed. #[cfg(windows)] From 7fc86a59215ec793e0041a8749e4ef71b34367d9 Mon Sep 17 00:00:00 2001 From: Zack Date: Mon, 30 Nov 2026 19:47:11 -0800 Subject: [PATCH 3/5] d3d12: LEONIDA_TARGET_BARRIERS applies the title's target barriers and syncs to the host's textures (D3D12-RDNA-GBUFFER-TERRAIN-TILES) The title's enhanced barriers (Barrier(group count, groups)) and its pipeline syncs each record one wait for shader writes, an unordered access barrier with no resource, and move no texture: the groups are not read. A host texture changes state where the host sees it used, and a view a shader picks from the heap by a number it computes is not seen (host.rs: "directly indexed textures are not transitioned"). So what a draw wrote into a target is read by such a shader with the texture still in its target state, and with no wait before it that names targets; D3D12 asks for the texture to leave the target state first. monte-alt/vesper 7b7e556 (GPL-3.0, as this) moves the textures such barriers name and waits at the others (its summarize_barrier_groups and classify_texture_direct_transition), and draws on an RX 9070 XT the ground this tree leaves black in patches (#2770; #2771 on an RX 7800 XT). LEONIDA_TARGET_BARRIERS is a set of two bits, off by default: - 1: a texture barrier that names a texture and leaves it to be read (by shaders, or as a copy's source after draws) moves the host's texture to that state through the list's own tracking, as a legacy transition of the title's does. Behind draws into it, a copy into it, or no access among the lists run together; never behind unordered access or any access, and not back towards a target (the next draw does that). By the accesses, or by the layout where the barrier names no access after it. A barrier on a part of a texture moves it only if the host's texture is one subresource. - 2: a barrier on all memory (a texture barrier that names no texture, a global barrier) and a pipeline sync record a wait for everything (HostList::wait_for_everything: the wait of the copies done at their place in a list) in place of the one for shader writes, if the list recorded a draw, a clear or a resolve into a target since its last. A list whose calls are only written down (LEONIDA_THIN) writes down what the groups ask when the title calls and does it when it is replayed; with the switch off a call is written down as before. The frame lines say how many waits and moves a frame; one line says what the switch was taken as, and one what LEONIDA_HOST_WAVE32 came to on the card. That this is what the issues show is a hypothesis: no AMD card was here, there is no report of the patches from an RX 6800, and what the waits cost a frame is not measured. The debug layer has not said that the recorded barriers are legal (it is not on the machine, and installing it needs elevation): the lists ran on an RTX 3090 and on WARP. Tests (list::groups, list::thin): what a barrier asks, by its words; through the list's own methods on the card, a texture drawn into is moved by a barrier that names it (each bit alone, and both), also one another list drew into, submitted with it and before it; a part of a texture; the waits at barriers that name no texture and at syncs, after a clear and a resolve the card does; a call written down and replayed. Each fails with its part of the change taken out. No test records a draw through a title list (it needs a console pipeline): the mark a draw sets (State::bind) is covered by reading only. AI-assisted (Claude Fable 5.2; reviewed by GPT-6.2 Astra and Claude Opus 5.5). Tested on RTX 3090, driver 610.88, and on WARP (LEONIDA_D3D12_WARP=1): leonida-gpu lib tests 597 passed (677 with --features diagnostics), no clippy warning on the changed lines. Not run on an AMD card. Refs #2771 Refs #2770 AI-assisted: yes --- d3d12/crates/leonida-gpu/src/draw.rs | 71 +- d3d12/crates/leonida-gpu/src/host/place.rs | 9 + d3d12/crates/leonida-gpu/src/list.rs | 140 ++- d3d12/crates/leonida-gpu/src/list/groups.rs | 1096 +++++++++++++++++++ d3d12/crates/leonida-gpu/src/list/thin.rs | 64 +- 5 files changed, 1351 insertions(+), 29 deletions(-) create mode 100644 d3d12/crates/leonida-gpu/src/list/groups.rs diff --git a/d3d12/crates/leonida-gpu/src/draw.rs b/d3d12/crates/leonida-gpu/src/draw.rs index 6fac25f06e..ea044bb013 100644 --- a/d3d12/crates/leonida-gpu/src/draw.rs +++ b/d3d12/crates/leonida-gpu/src/draw.rs @@ -1027,7 +1027,9 @@ fn barrier_merge() -> bool { static WAITS: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; /// For the frame-rate line: what became of the title's waits for every -/// shader write. +/// shader write, and for what was drawn into targets. And, with the first, +/// what `LEONIDA_HOST_WAVE32=1` came to on this card (the translator's +/// switch: `leonida_shader::emit::host_wave32`). pub(crate) fn waits_line(frames: f64) { let [recorded, left_out, could] = [0, 1, 2].map(|i| WAITS[i].swap(0, Ordering::Relaxed) as f64 / frames); if recorded + left_out > 0.0 { @@ -1037,8 +1039,39 @@ pub(crate) fn waits_line(frames: f64) { u8::from(barrier_merge()) ); } + let [all, left_out, named] = [0, 1, 2].map(|i| TARGET_WAITS[i].swap(0, Ordering::Relaxed) as f64 / frames); + if all + left_out + named > 0.0 { + tracing::info!( + "the title's waits for what was drawn into targets per frame (LEONIDA_TARGET_BARRIERS; without it \ + none): {all:.0} recorded for every target, {left_out:.0} left out with nothing drawn since the last; \ + {named:.0} textures its barriers left to be read (each moved to that state unless it was in it)" + ); + } + if let Some([card, taken]) = leonida_shader::emit::host_wave32() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + if card == taken { + tracing::info!( + "LEONIDA_HOST_WAVE32=1 changes nothing here: not an AMD card with waves of 32 to 64 lanes (its \ + widest wave has {card})" + ); + } else { + tracing::info!( + "LEONIDA_HOST_WAVE32=1: programs are translated for waves of {taken} lanes on this card, whose \ + widest wave has {card}; one the forms for {taken} lanes cannot take is refused, as on a card \ + of {taken} lanes" + ); + } + }); + } } +/// Since the last frame-rate line: the title's waits for what was drawn into targets +/// (`crate::list::groups`) that were recorded for every target, those left out +/// ([`State::wait_for_targets`]), and the textures its barriers left to be read (each asked +/// to be in its read state: a move unless it was there). +pub(crate) static TARGET_WAITS: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; + /// Since the last frame-rate line: the title's direct dispatches recorded, by the groups each /// runs (none, 1, up to 16, up to 256, up to 4,096, more), and those of them whose program can /// store to buffers. @@ -1122,6 +1155,10 @@ pub(crate) struct State { /// recorded since can write through unordered access /// ([`State::wait_for_writes`]). waited: bool, + /// The host list has had a wait for what was drawn into targets, and + /// nothing recorded since draws, clears or resolves into one + /// ([`State::wait_for_targets`]). + targets_waited: bool, /// The user data bound last, of the last stage that has some (for the /// report of a removed device, `crate::host::indirects`). #[cfg(feature = "diagnostics")] @@ -2751,6 +2788,7 @@ impl State { pub(crate) fn replay(&mut self, list: &HostList) { // Another host list, or one a pass of ours wrote in (an upscale). self.waited = false; + self.targets_waited = false; self.host_pipeline = 0; self.host_roots = [0; 2]; self.host_heaps = [0; 2]; @@ -3069,6 +3107,11 @@ impl State { if compute || p.stages.iter().any(|stage| stage.translated().writes) { self.waited = false; } + // What is drawn with it is drawn into the targets: the title's next + // wait for those is one ([`State::wait_for_targets`]). + if !compute { + self.targets_waited = false; + } #[cfg(feature = "diagnostics")] if batch_why() { list.batch_writer(&p.name); @@ -6319,6 +6362,32 @@ impl State { needed } + /// A clear or a resolve into a target was recorded: the title's next + /// wait for what was drawn into targets is one + /// ([`State::wait_for_targets`]; a draw says so where it binds). + pub(crate) fn targets_written(&mut self) { + self.targets_waited = false; + } + + /// The title asks for what was drawn into targets to be there for what + /// reads them next (`crate::list::groups`): whether a wait for it is to + /// be recorded into `list`. Not if the list has had one and has recorded + /// no draw, clear or resolve into a target since: between two waits of a + /// host list only what it records itself comes, and what other lists + /// drew before it is behind its first wait, which is always recorded. + pub(crate) fn wait_for_targets(&mut self, list: &HostList) -> bool { + const WAIT_USE: usize = usize::MAX - 0x7b; + // Another host list (a new one after a cut, or this one after its + // reset): what ran before it is not known here. + if list.first_use(WAIT_USE) { + self.targets_waited = false; + } + let needed = !self.targets_waited; + TARGET_WAITS[usize::from(!needed)].fetch_add(1, Ordering::Relaxed); + self.targets_waited = true; + needed + } + /// The title waits for earlier work (a barrier or a pipeline sync). pub(crate) fn synced(&mut self) { // (Not with 3 and 4: there an execution's own record says whether the batch has it.) diff --git a/d3d12/crates/leonida-gpu/src/host/place.rs b/d3d12/crates/leonida-gpu/src/host/place.rs index e26386b1db..97d0ff2f49 100644 --- a/d3d12/crates/leonida-gpu/src/host/place.rs +++ b/d3d12/crates/leonida-gpu/src/host/place.rs @@ -312,6 +312,15 @@ fn shaders_own(src: usize, len: usize) -> Option> { } impl HostList { + /// Records a wait for everything recorded so far, what was drawn into + /// targets too ([`wait_for_all`]), at this place of the list: where the + /// title's barriers and pipeline syncs ask for one behind its draws + /// (`crate::list::groups`). + pub(crate) fn wait_for_everything(&self, host: &Host) { + // SAFETY: an open list: the title records into it. + unsafe { wait_for_all(host, &self.list) }; + } + /// Copies `len` bytes of title memory at `src` to `dst`, at this place of /// the list (see the file). `false` if it is to be done at submission. pub(crate) fn place_copy(&self, dst: usize, src: usize, len: usize) -> bool { diff --git a/d3d12/crates/leonida-gpu/src/list.rs b/d3d12/crates/leonida-gpu/src/list.rs index 5b689e4608..df3cba1252 100644 --- a/d3d12/crates/leonida-gpu/src/list.rs +++ b/d3d12/crates/leonida-gpu/src/list.rs @@ -20,6 +20,8 @@ use crate::resource::PAGEABLE_IIDS; #[cfg(windows)] pub(crate) mod thin; +#[cfg(windows)] +mod groups; const ALLOCATOR_IIDS: [Iid; 4] = [ guid( @@ -899,6 +901,41 @@ const UAV_BARRIER: Barrier = Barrier { last: 0, }; +/// Records the wait a barrier group or a pipeline sync of the title's asks +/// for into its host list: for everything where it comes after draws into +/// targets (`targets`: [`groups`]) and the list drew since its last +/// (`crate::draw::State::wait_for_targets`), else for every shader write +/// ([`UAV_BARRIER`]; not where the list has nothing to wait for: +/// `State::wait_for_writes`). +#[cfg(windows)] +fn wait(this: This, list: &crate::host::HostList, targets: bool) { + let (mut writes, mut all) = (true, false); + with_state(this, |list, state| { + writes = state.wait_for_writes(list); + all = targets && state.wait_for_targets(list); + }); + // (A test's count of the two, on its thread.) + #[cfg(test)] + let count = |which: usize| { + let mut waits = groups::TEST_WAITS.get(); + waits[which] += 1; + groups::TEST_WAITS.set(waits); + }; + if all && let Some(host) = crate::host::host() { + #[cfg(test)] + count(0); + list.wait_for_everything(host); + } else if writes { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; + #[cfg(test)] + count(1); + // SAFETY: the same layout; no resource named. + let barrier = unsafe { std::mem::transmute::(UAV_BARRIER) }; + // SAFETY: an open list. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + } +} + /// Returns the console's barrier "actions" (none). extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> u32 { #[cfg(windows)] @@ -1824,6 +1861,8 @@ extern "system" fn resolve( crate::texture::card_writes(list, dst, to, Some(dst_sub)); ensure_state(list, dst, RESOLVE_DEST); ensure_state(list, src, RESOLVE_SOURCE); + // (A write into a target: `crate::draw::State::wait_for_targets`.) + with_state(this, |_, state| state.targets_written()); crate::texture::host_written(dst); crate::texture::host_write_listed(list, dst, to); #[cfg(feature = "diagnostics")] @@ -1902,6 +1941,8 @@ extern "system" fn clear_rtv( }); const RENDER_TARGET: u32 = 0x4; let rtv = host.rtv(Some(texture), record.desc().as_ref()); + // (A write into a target: `crate::draw::State::wait_for_targets`.) + with_state(this, |_, state| state.targets_written()); // SAFETY: an open list, a fresh view of a live texture. unsafe { if let Some((_, before)) = list.transition(record.resource, RENDER_TARGET) { @@ -1952,6 +1993,7 @@ extern "system" fn clear_dsv( // clear may be of one slice or of some rectangles). list.twin_use(record.resource, false, true); ensure_state(list, record.resource, DEPTH_WRITE); + with_state(this, |_, state| state.targets_written()); if crate::resource::depth_and_unordered(record.resource) { crate::resource::DEPTH_UNORDERED[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); } @@ -2082,7 +2124,11 @@ extern "system" fn set_pipeline(this: This, pipeline: This) { /// bottom of the pipe `(flags, control, address, size)`. The host orders /// nothing between dispatches by itself: what shaders wrote is waited for /// here as at the title's barriers (the ray-tracing structure builder has -/// no other wait between its stages). +/// no other wait between its stages), and what was drawn into targets where +/// that is waited for ([`groups`]: every sync, as the Vulkan layer takes +/// each for a barrier on everything, `runtime/shims/d3d12_xs_device.cpp` +/// `record_console_pipeline_sync`; which flags name the targets' caches is +/// not measured). /// (Arguments may be what earlier shaders wrote from here on: /// `State::synced`.) extern "system" fn sync(this: This, flags: u32, control: u32, address: u64, size: u64) { @@ -2090,10 +2136,6 @@ extern "system" fn sync(this: This, flags: u32, control: u32, address: u64, size { with_state(this, |_, state| state.synced()); if let Some(list) = host_list(this) { - use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; - // (Not where the list has nothing to wait for: - // `State::wait_for_writes`.) - let needed = wait_for_writes(this); #[cfg(feature = "diagnostics")] { // The shapes of the title's calls, each once. @@ -2112,12 +2154,7 @@ extern "system" fn sync(this: This, flags: u32, control: u32, address: u64, size } crate::copystat::add(crate::copystat::C::WaitsForGroups, 1); } - if needed { - // SAFETY: the same layout; no resource named. - let barrier = unsafe { std::mem::transmute::(UAV_BARRIER) }; - // SAFETY: an open list. - unsafe { list.list.ResourceBarrier(&[barrier]) }; - } + wait(this, list, groups::waits()); } } let _ = (this, flags, control, address, size); @@ -2726,33 +2763,86 @@ extern "system" fn wait_value64(this: This, address: u64, comparison: u32, refer /// global barriers with layouts instead of states. Every host use of a /// title texture (clears, copies) moves its host copy to the state it needs /// first, so only their ordering matters: one barrier on every shader -/// write (the title's buffer barriers order compute passes). -extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { +/// write (the title's buffer barriers order compute passes); and what the +/// groups ask of the textures the host draws into, which a shader that +/// picks its views from the heap reads with no host use to move them +/// ([`groups`]). +extern "system" fn barrier_groups(this: This, count: u32, groups: *const u8) { + #[cfg(windows)] + { + // SAFETY: the title's groups, as it passes them. + let (words, len) = unsafe { groups::words(count, groups) }; + barrier_groups_words(this, &words[..len]); + } + #[cfg(not(windows))] + let _ = (this, count, groups); +} + +/// [`barrier_groups`] of a call as [`groups::words`] wrote it down (a list +/// whose calls are only written down does it later, on a thread of ours): +/// the group count, whether a wait for every target is asked, and the +/// textures to move to a read state. +#[cfg(windows)] +pub(super) fn barrier_groups_words(this: This, w: &[u64]) { + let count = w.first().copied().unwrap_or(0); // Diagnostics: counted, and left out under `LEONIDA_BARRIER_TEST=groups`. - #[cfg(all(windows, feature = "diagnostics"))] + #[cfg(feature = "diagnostics")] if count > 0 { crate::copystat::add(crate::copystat::C::WaitsForGroups, 1); if crate::copystat::barrier_test() & 1 != 0 { return; } } - #[cfg(windows)] if count > 0 && let Some(list) = host_list(this) { - use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; with_state(this, |_, state| state.synced()); - // (Not where the list has nothing to wait for: - // `State::wait_for_writes`.) - if wait_for_writes(this) { - // SAFETY: the same layout; no resource named. - let barrier = unsafe { std::mem::transmute::(UAV_BARRIER) }; - // SAFETY: an open list. - unsafe { list.list.ResourceBarrier(&[barrier]) }; + let mut targets = w.get(1).is_some_and(|&flags| flags & groups::EVERY != 0); + for named in w.get(2..).unwrap_or_default().chunks_exact(2) { + let (resource, state) = (named[0] as This, named[1] as u32); + // The host's texture of that name, if all of it is the barrier's: a host texture + // has one state (as for the title's legacy barriers, `host_barrier`), and what + // is drawn into another level or slice next would move all of it back. + let copy = if crate::resource::is_resource(resource) { crate::resource::made_copy(resource) } else { None }; + let host = crate::host::host(); + let whole = copy.is_some_and(|copy| { + state & groups::PART == 0 || host.is_some_and(|host| one_subresource(host, ©.texture)) + }); + if whole { + ensure_state(list, resource, state & !(groups::DRAWN | groups::PART)); + crate::draw::TARGET_WAITS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } else { + // (Nothing of that name to move, be it that the host has made no texture + // for it: what was drawn into it is waited for.) + targets |= state & groups::DRAWN != 0; + } } + wait(this, list, targets); } - #[cfg(not(windows))] - let _ = (this, count); +} + +/// Whether a host texture is one subresource (one level, one slice, one +/// plane, as the card counts its format's): a barrier on a part of it is +/// then on all of it. +#[cfg(windows)] +fn one_subresource(host: &crate::host::Host, texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource) -> bool { + use windows::Win32::Graphics::Direct3D12::{ + D3D12_FEATURE_DATA_FORMAT_INFO, D3D12_FEATURE_FORMAT_INFO, D3D12_RESOURCE_DIMENSION_TEXTURE3D, + }; + // SAFETY: a plain query. + let desc = unsafe { texture.GetDesc() }; + // (A volume's levels are one slice each.) + let slices = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { desc.DepthOrArraySize }; + if desc.MipLevels != 1 || slices != 1 { + return false; + } + // (Depth with stencil is two planes. Not said: not taken for one.) + let mut info = D3D12_FEATURE_DATA_FORMAT_INFO { Format: desc.Format, PlaneCount: 0 }; + // SAFETY: a plain query that fills our structure. + let said = unsafe { + host.device.CheckFeatureSupport(D3D12_FEATURE_FORMAT_INFO, (&raw mut info).cast(), size_of_val(&info) as u32) + }; + said.is_ok() && info.PlaneCount == 1 } /// The bottom-of-pipe value writes `(address, value, flush, flags)`, 32 and diff --git a/d3d12/crates/leonida-gpu/src/list/groups.rs b/d3d12/crates/leonida-gpu/src/list/groups.rs new file mode 100644 index 0000000000..566888bae4 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/list/groups.rs @@ -0,0 +1,1096 @@ +//! What the title's barriers and pipeline syncs behind draws into targets ask +//! of the host's textures: `LEONIDA_TARGET_BARRIERS=3` (1: named textures +//! moved to their read state, 2: waits for what was drawn; off by default). +//! +//! The title tells the console when what it drew into a target has to be +//! there for the shaders that read it next: with a texture barrier of its +//! enhanced barriers (`Barrier(group count, groups)`, a newer list's 0x490; +//! render target or depth write access before, shader resource after, or +//! only the layouts where it is the texture's first or last use among the +//! lists run together), and with pipeline syncs. The retail title also +//! records texture barriers that name no texture (measured for the Vulkan +//! layer: `docs/d3d12_vulkan.md`, "List slot 146: texture barrier with no +//! resource"), which that layer takes for barriers on all memory and all +//! work (`runtime/shims/d3d12_xs_device.cpp` `console_barrier_groups`, whose +//! `kMaxConsoleBarrierGroups` says the measured calls pass one group). +//! +//! The host records one wait for shader writes for any of them (an unordered +//! access barrier with no resource) and moves no texture: a host texture +//! changes state where the host sees it used, and a view a shader picks from +//! the heap by a number it computes is not seen (`host.rs`: "directly indexed +//! textures are not transitioned"). So what a draw wrote into a target is +//! read by such a shader with the texture still in its target state and with +//! no wait that names targets before it. D3D12 asks for the texture to leave +//! the target state first. Where that would show is a card that keeps what +//! it draws in a cache of its own, and a target's compression beside it, +//! until then (a hypothesis: not measured on one); an NVIDIA card has shown +//! nothing of it. +//! +//! With the switch, after monte-alt/vesper 7b7e556 (GPL-3.0, as this; its +//! `summarize_barrier_groups` and `classify_texture_direct_transition`, +//! which say "Bindless SRV reads ... never call `HostList::transition`, so +//! RTV/DSV <-> SRV texture barriers MUST remain ordered"), in two parts, +//! each a bit of it: +//! +//! - 1: a texture barrier that names a texture and leaves it to be read (by +//! shaders, or as a copy's source after draws) moves the texture's host +//! copy to that state ([`read_state`]), as a legacy transition barrier of +//! the title's does (`super::host_barrier`); the draw that writes it next +//! moves it back, as every draw does for its targets. Vesper takes the +//! barriers that name the accesses on both sides; here also those that +//! only name the layouts (a texture's first or last use among the lists +//! run together: the idiom of the PC's enhanced barriers, whose layout +//! words the title passes as the PC's, `legacy_state_for_layout` in +//! `d3d12_xs_device.cpp`). All of a texture is moved, as for the legacy +//! barriers: a barrier on some of its levels, slices or planes moves it +//! only if it has no others, and else waits. +//! - 2: a barrier on all memory (a texture barrier that names none, a global +//! one) and a pipeline sync that come after target writes +//! ([`Global::waits`]) record a wait for everything in place of the one +//! for shader writes (`crate::host::HostList::wait_for_everything`, the +//! wait of the copies done at their place in a list), if the list drew +//! anything since its last (`crate::draw::State::wait_for_targets`). +//! +//! Only towards reads: a barrier back to a target state at a list's first +//! use of the texture would be moved to the list's start +//! (`HostList::transition`), before the reads it comes after; and not from +//! unordered access or from any access, which a shader may have written +//! through a view the host does not see, behind that start. +//! +//! Off by default: that this is what #2770 and #2771 show (black patches of +//! ground on an RX 9070 XT and an RX 7800 XT, in a different place every +//! frame, which vesper does not show on the RX 9070 XT) is a hypothesis. No +//! such card was here, there is no report of them from an RX 6800, and what +//! the waits cost a frame is not measured. Read in the code and run on an +//! RTX 3090 and on WARP, where the tests below say what is recorded and that +//! it runs. The debug layer has not said that it is legal: it was not on the +//! machine (it needs the system's own SDK layers, also beside the Agility +//! SDK's). + +use crate::object::This; +use windows::Win32::Graphics::Direct3D12 as d3d; + +/// `D3D12_BARRIER_ACCESS` words, the console's as the PC's. +const COMMON: u32 = d3d::D3D12_BARRIER_ACCESS_COMMON.0 as u32; +const RENDER_TARGET: u32 = d3d::D3D12_BARRIER_ACCESS_RENDER_TARGET.0 as u32; +const DEPTH_WRITE: u32 = d3d::D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE.0 as u32; +const DEPTH_READ: u32 = d3d::D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ.0 as u32; +const SHADER_RESOURCE: u32 = d3d::D3D12_BARRIER_ACCESS_SHADER_RESOURCE.0 as u32; +const COPY_DEST: u32 = d3d::D3D12_BARRIER_ACCESS_COPY_DEST.0 as u32; +const COPY_SOURCE: u32 = d3d::D3D12_BARRIER_ACCESS_COPY_SOURCE.0 as u32; +const RESOLVE_SOURCE: u32 = d3d::D3D12_BARRIER_ACCESS_RESOLVE_SOURCE.0 as u32; +const NO_ACCESS: u32 = d3d::D3D12_BARRIER_ACCESS_NO_ACCESS.0 as u32; + +/// `D3D12_BARRIER_SYNC`: the half of a split barrier that stands elsewhere. +const SYNC_SPLIT: u32 = d3d::D3D12_BARRIER_SYNC_SPLIT.0 as u32; + +const fn layout(layout: d3d::D3D12_BARRIER_LAYOUT) -> u32 { + layout.0 as u32 +} + +/// `D3D12_BARRIER_LAYOUT` words a texture is left in to be read: by shaders; +/// as depth and by shaders; by anything that reads; by any access that needs +/// no layout of its own (shaders and copies among them); as a copy's source. +/// And the one that says there is nothing in it to keep. +const SHADER_LAYOUTS: [u32; 3] = [ + layout(d3d::D3D12_BARRIER_LAYOUT_SHADER_RESOURCE), + layout(d3d::D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_SHADER_RESOURCE), + layout(d3d::D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_SHADER_RESOURCE), +]; +const DEPTH_READ_LAYOUT: u32 = layout(d3d::D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ); +const READ_LAYOUTS: [u32; 3] = [ + layout(d3d::D3D12_BARRIER_LAYOUT_GENERIC_READ), + layout(d3d::D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_GENERIC_READ), + layout(d3d::D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_GENERIC_READ), +]; +const COMMON_LAYOUTS: [u32; 3] = [ + layout(d3d::D3D12_BARRIER_LAYOUT_COMMON), + layout(d3d::D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COMMON), + layout(d3d::D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COMMON), +]; +const COPY_LAYOUTS: [u32; 3] = [ + layout(d3d::D3D12_BARRIER_LAYOUT_COPY_SOURCE), + layout(d3d::D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COPY_SOURCE), + layout(d3d::D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COPY_SOURCE), +]; +const UNDEFINED_LAYOUT: u32 = layout(d3d::D3D12_BARRIER_LAYOUT_UNDEFINED); + +/// `D3D12_TEXTURE_BARRIER_FLAG_DISCARD`: what the texture holds is not kept. +const DISCARD: u32 = d3d::D3D12_TEXTURE_BARRIER_FLAG_DISCARD.0 as u32; + +/// Host states (`D3D12_RESOURCE_STATES`) a texture is read in. +const HOST_DEPTH_READ: u32 = d3d::D3D12_RESOURCE_STATE_DEPTH_READ.0 as u32; +const HOST_SHADER_RESOURCE: u32 = d3d::D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE.0 as u32; +const HOST_COPY_SOURCE: u32 = d3d::D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32; +const HOST_RESOLVE_SOURCE: u32 = d3d::D3D12_RESOURCE_STATE_RESOLVE_SOURCE.0 as u32; + +/// `D3D12_BARRIER_GROUP`: 16 bytes (`super::NEWER_METHODS` says where the +/// title builds them); `kind` 0 global, 1 texture, 2 buffer barriers. +#[repr(C)] +#[derive(Clone, Copy)] +struct Group { + kind: u32, + count: u32, + barriers: *const u8, +} + +/// The words every barrier begins with, and all of `D3D12_GLOBAL_BARRIER`. +#[repr(C)] +#[derive(Clone, Copy)] +struct Global { + sync_before: u32, + sync_after: u32, + access_before: u32, + access_after: u32, +} + +/// `D3D12_TEXTURE_BARRIER`, 64 bytes: the words, the layouts before and after, the texture, +/// its subresources (`first_level` is all ones for all of them, else an index or a first mip +/// level of the range the next words give) and the flags. +#[repr(C)] +#[derive(Clone, Copy)] +struct Texture { + global: Global, + layout_before: u32, + layout_after: u32, + resource: This, + first_level: u32, + _range: [u32; 5], + flags: u32, + _pad: u32, +} + +const _: () = assert!(size_of::() == 16 && size_of::() == 16); +const _: () = { + use std::mem::offset_of; + assert!(size_of::() == size_of::()); + assert!(offset_of!(Texture, resource) == offset_of!(d3d::D3D12_TEXTURE_BARRIER, pResource)); + assert!(offset_of!(Texture, first_level) == offset_of!(d3d::D3D12_TEXTURE_BARRIER, Subresources)); + assert!(offset_of!(Texture, flags) == offset_of!(d3d::D3D12_TEXTURE_BARRIER, Flags)); +}; + +/// The most groups of a call and barriers of a group that are looked at +/// (the bounds of `console_barrier_groups` of the Vulkan layer); a call with +/// more waits as one that names no texture. +const MOST_GROUPS: u32 = 1024; +const MOST_BARRIERS: u32 = 65536; + +/// The switch's name, and its bits: the textures the title's barriers name +/// are moved, and its barriers on all memory and its syncs wait for what +/// was drawn (the module's text). +const SWITCH: &str = "LEONIDA_TARGET_BARRIERS"; +const MOVES: u8 = 1; +const WAITS: u8 = 2; + +#[cfg(test)] +thread_local! { + /// A test's choice for [`bits`], for its thread only. + pub(crate) static TEST_BITS: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// The waits this thread recorded for the title's barriers and syncs (`super::wait`): + /// for everything, and for shader writes alone. + pub(crate) static TEST_WAITS: std::cell::Cell<[u32; 2]> = const { std::cell::Cell::new([0; 2]) }; +} + +/// The bits `LEONIDA_TARGET_BARRIERS` set to `value` asks for: its number's +/// (1, 2, or 3 for both); none where it is not set or is no number. +fn bits_of(value: Option<&std::ffi::OsStr>) -> u8 { + let number = value.and_then(|v| v.to_str()).and_then(|v| v.trim().parse::().ok()); + number.unwrap_or(0) & (MOVES | WAITS) +} + +/// What of the title's barriers and syncs behind target writes is applied to +/// the host's textures ([`MOVES`], [`WAITS`]; the module's text): what +/// `LEONIDA_TARGET_BARRIERS` says, none where it is not set; both or none by +/// turns with `LEONIDA_AB` in a diagnostics build. +fn bits() -> u8 { + #[cfg(test)] + if let Some(bits) = TEST_BITS.get() { + return bits; + } + #[cfg(feature = "diagnostics")] + { + static BIT: std::sync::OnceLock> = std::sync::OnceLock::new(); + if let Some(bit) = *BIT.get_or_init(|| crate::ab::bit(SWITCH)) { + return if crate::ab::on(bit) { MOVES | WAITS } else { 0 }; + } + } + static BITS: std::sync::OnceLock = std::sync::OnceLock::new(); + *BITS.get_or_init(|| { + let set = std::env::var_os(SWITCH); + let bits = bits_of(set.as_deref()); + if let Some(set) = set { + // (Said once where it is set, also if it came to nothing: a log says which run it is.) + tracing::info!( + "LEONIDA_TARGET_BARRIERS={set:?} is taken as {bits}: 1 moves the textures the title's barriers leave to \ + be read to that state, 2 waits for what was drawn into targets at its barriers on all memory and \ + its pipeline syncs, 3 both, 0 neither (one wait for shader writes for each, as without it)" + ); + } + bits + }) +} + +/// Whether a pipeline sync of the title's waits for what was drawn into +/// targets ([`WAITS`]). +pub(super) fn waits() -> bool { + bits() & WAITS != 0 +} + +impl Global { + /// The first half of a split barrier: its second half is the barrier. + fn begins(self) -> bool { + self.sync_after == SYNC_SPLIT + } + + /// It names no access before it: the memory's first use among the lists + /// run together. (By the access alone: a barrier that names one is taken + /// by it, also where it says that no work comes before.) + fn first(self) -> bool { + self.access_before == NO_ACCESS + } + + /// It names no access after it: the memory's last use among the lists + /// run together. + fn last(self) -> bool { + self.access_after == NO_ACCESS + } + + /// It comes after draws into the memory it names. + fn drawn(self) -> bool { + self.access_before & (RENDER_TARGET | DEPTH_WRITE) != 0 + } + + /// Whether what was drawn into targets is waited for at this barrier: + /// it comes after draws; or, where it is for all memory (`all`: a global + /// barrier, or a texture barrier that names no texture), after any access, + /// or before reads with nothing of these lists before it (what the lists + /// before them drew). + fn waits(self, all: bool) -> bool { + if self.begins() { + false + } else if self.first() { + let a = self.access_after; + all && !self.last() && (a == COMMON || a & SHADER_RESOURCE != 0) + } else { + self.drawn() || all && self.access_before == COMMON + } + } +} + +/// The host state a texture barrier leaves its texture in for the shaders +/// or the copy that read it next, if it leaves it to be read only: by the +/// access after it, or, where it names none (the texture's last use among +/// the lists run together, or any access), by the layout after it. +/// +/// Only behind draws into it, a copy into it, or no access among these +/// lists: a list's first move of a texture is done before the list +/// (`HostList::transition`). Draws and copies come ahead of that because the +/// host sees them; a shader's write through a view it picks from the heap +/// would not, so nothing is moved behind unordered access, nor behind any +/// access (which may be that), nor behind reads. +fn read_state(b: &Texture) -> Option { + let g = b.global; + if g.begins() { + return None; + } + let target = g.drawn() && g.access_before & !(RENDER_TARGET | DEPTH_WRITE | DEPTH_READ) == 0; + let copied = g.access_before == COPY_DEST; + if !(g.first() || target || copied) { + return None; + } + if !g.last() && g.access_after != COMMON { + let a = g.access_after; + if a & SHADER_RESOURCE != 0 && a & !(SHADER_RESOURCE | DEPTH_READ | COPY_SOURCE | RESOLVE_SOURCE) == 0 { + let also = |access: u32, state: u32| if a & access != 0 { state } else { 0 }; + return Some( + HOST_SHADER_RESOURCE + | also(DEPTH_READ, HOST_DEPTH_READ) + | also(COPY_SOURCE, HOST_COPY_SOURCE) + | also(RESOLVE_SOURCE, HOST_RESOLVE_SOURCE), + ); + } + return (target && a == COPY_SOURCE).then_some(HOST_COPY_SOURCE); + } + let l = b.layout_after; + if SHADER_LAYOUTS.contains(&l) { + Some(HOST_SHADER_RESOURCE) + } else if l == DEPTH_READ_LAYOUT { + Some(HOST_DEPTH_READ | HOST_SHADER_RESOURCE) + } else if READ_LAYOUTS.contains(&l) || COMMON_LAYOUTS.contains(&l) && (target || copied) { + Some(HOST_SHADER_RESOURCE | HOST_COPY_SOURCE) + } else if COPY_LAYOUTS.contains(&l) && target { + Some(HOST_COPY_SOURCE) + } else { + None + } +} + +/// In a texture's state word (no host state has these bits). [`DRAWN`]: its +/// barrier comes after draws into it, so where the host has no texture of +/// that name to move, what was drawn is waited for. [`PART`]: its barrier +/// names some of its subresources, not all. +pub(super) const DRAWN: u32 = 0x8000_0000; +pub(super) const PART: u32 = 0x4000_0000; + +/// What a call of the title's enhanced barriers asks of targets. With +/// `moves`, `named` is given each texture a barrier leaves to be read and +/// its host state ([`read_state`]) with [`DRAWN`] and [`PART`]. The answer +/// is whether any other barrier waits for what was drawn ([`Global::waits`]). +/// +/// # Safety +/// `groups` is null or the title's `count` groups, each with its barriers. +unsafe fn asked(count: u32, groups: *const u8, moves: bool, mut named: impl FnMut(This, u32)) -> bool { + if groups.is_null() { + return false; + } + let mut every = count > MOST_GROUPS; + for g in 0..count.min(MOST_GROUPS) as usize { + // SAFETY: one of the caller's groups. + let group = unsafe { groups.cast::().add(g).read_unaligned() }; + if group.barriers.is_null() || group.kind > 1 { + continue; + } + every |= group.count > MOST_BARRIERS; + for i in 0..group.count.min(MOST_BARRIERS) as usize { + if group.kind == 0 { + // SAFETY: one of the group's global barriers. + let b = unsafe { group.barriers.cast::().add(i).read_unaligned() }; + every |= b.waits(true); + continue; + } + // SAFETY: one of the group's texture barriers. + let b = unsafe { group.barriers.cast::().add(i).read_unaligned() }; + let none = b.resource.is_null(); + match read_state(&b) { + Some(state) if moves && !none => { + let drawn = if b.global.drawn() { DRAWN } else { 0 }; + let part = if b.first_level != u32::MAX { PART } else { 0 }; + named(b.resource, state | drawn | part); + } + // (Nothing of a texture whose first use says it holds nothing to keep.) + _ if b.global.first() && (b.layout_before == UNDEFINED_LAYOUT || b.flags & DISCARD != 0) => {} + _ => every |= b.global.waits(none), + } + } + } + every +} + +/// The textures a call may move by name. +const NAMED: usize = 31; + +/// The words a call is at most ([`words`]). +pub(super) const WORDS: usize = 2 + 2 * NAMED; + +/// In the second word: a wait for every target. +pub(super) const EVERY: u64 = 1; + +/// A call of the title's enhanced barriers as it is written down and done +/// ([`super::barrier_groups_words`]; a list whose calls are only written +/// down keeps no pointer of the title's): the group count; then, with the +/// switch on ([`bits`]), [`EVERY`] or 0 and a texture and its host state +/// (with [`DRAWN`] and [`PART`]) for each the call moves. How many words: +/// one with the switch off, as before it was there. +/// +/// # Safety +/// `groups` is null or the title's `count` groups, each with its barriers. +pub(super) unsafe fn words(count: u32, groups: *const u8) -> ([u64; WORDS], usize) { + let mut w = [0u64; WORDS]; + let mut len = 1; + w[0] = u64::from(count); + let bits = if count > 0 { bits() } else { 0 }; + if bits != 0 { + len = 2; + let waits = bits & WAITS != 0; + // (A call that names more textures than fit: the rest are not moved, and every target + // is waited for instead, where that is on.) + let mut left_out = false; + // SAFETY: the caller's. + let every = unsafe { + asked(count, groups, bits & MOVES != 0, |resource, state| { + if len + 2 <= WORDS { + // (What was drawn is only waited for with that part on.) + let state = if waits { state } else { state & !DRAWN }; + (w[len], w[len + 1]) = (resource as u64, u64::from(state)); + len += 2; + } else { + left_out = true; + } + }) + }; + if left_out { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!( + "a barrier call of the title's leaves more than {NAMED} textures to be read: the others are not \ + moved to that state (LEONIDA_TARGET_BARRIERS; with its 2, every target is waited for instead)" + ); + }); + } + w[1] = if waits && (every || left_out) { EVERY } else { 0 }; + } + (w, len) +} + +#[cfg(test)] +pub(super) mod tests { + use super::*; + + /// `D3D12_BARRIER_SYNC` words: no work, the work a draw does, that of its colour targets, + /// of its depth target, of every shader, of a copy. And unordered access. + const SYNC_NONE: u32 = d3d::D3D12_BARRIER_SYNC_NONE.0 as u32; + const SYNC_DRAW: u32 = d3d::D3D12_BARRIER_SYNC_DRAW.0 as u32; + const SYNC_RENDER_TARGET: u32 = d3d::D3D12_BARRIER_SYNC_RENDER_TARGET.0 as u32; + const SYNC_DEPTH: u32 = d3d::D3D12_BARRIER_SYNC_DEPTH_STENCIL.0 as u32; + const SYNC_ALL_SHADING: u32 = d3d::D3D12_BARRIER_SYNC_ALL_SHADING.0 as u32; + const SYNC_COPY: u32 = d3d::D3D12_BARRIER_SYNC_COPY.0 as u32; + const UNORDERED: u32 = d3d::D3D12_BARRIER_ACCESS_UNORDERED_ACCESS.0 as u32; + /// `D3D12_BARRIER_LAYOUT` words: a colour target, unordered access, a depth target, a + /// shader resource, a copy's source and its destination. + const TARGET_LAYOUT: u32 = layout(d3d::D3D12_BARRIER_LAYOUT_RENDER_TARGET); + const UNORDERED_LAYOUT: u32 = layout(d3d::D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS); + const DEPTH_LAYOUT: u32 = layout(d3d::D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE); + const SHADER_LAYOUT: u32 = layout(d3d::D3D12_BARRIER_LAYOUT_SHADER_RESOURCE); + const COPY_SOURCE_LAYOUT: u32 = layout(d3d::D3D12_BARRIER_LAYOUT_COPY_SOURCE); + const COPY_DEST_LAYOUT: u32 = layout(d3d::D3D12_BARRIER_LAYOUT_COPY_DEST); + /// The host states of a colour and of a depth target that is drawn into. + pub(in crate::list) const TARGET: u32 = d3d::D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32; + const DEPTH_TARGET: u32 = d3d::D3D12_RESOURCE_STATE_DEPTH_WRITE.0 as u32; + + fn b(sync_before: u32, sync_after: u32, access_before: u32, access_after: u32) -> Global { + Global { sync_before, sync_after, access_before, access_after } + } + + /// A texture barrier with these words on all of `resource`, from one layout to the other. + fn texture(global: Global, layouts: [u32; 2], resource: This) -> Texture { + Texture { + global, + layout_before: layouts[0], + layout_after: layouts[1], + resource, + first_level: u32::MAX, + _range: [0; 5], + flags: 0, + _pad: 0, + } + } + + /// [`texture`] from a colour target that was drawn into to shader reads. + fn drawn(resource: This) -> Texture { + let words = b(SYNC_RENDER_TARGET, SYNC_ALL_SHADING, RENDER_TARGET, SHADER_RESOURCE); + texture(words, [TARGET_LAYOUT, SHADER_LAYOUT], resource) + } + + /// A test's choice of the switch's bits on its thread, until it is dropped. + pub(in crate::list) struct Bits(Option); + + impl Bits { + pub(in crate::list) fn set(bits: u8) -> Self { + Self(TEST_BITS.replace(Some(bits))) + } + } + + impl Drop for Bits { + fn drop(&mut self) { + TEST_BITS.set(self.0); + } + } + + /// The card, for a test that records into the host list of a title list: not without + /// one, nor where a title list has none (`LEONIDA_THIN=1`). + pub(in crate::list) fn card() -> Option<&'static crate::host::Host> { + crate::host::host().filter(|_| !crate::list::thin::on()) + } + + /// A title list of its own allocator, open: the allocator and the list. + pub(in crate::list) fn title_list() -> (This, This) { + use crate::list::{ALLOCATOR_IIDS, LIST_IIDS, create_allocator, create_list}; + let null = std::ptr::null(); + let (mut allocator, mut list) = (null, null); + assert_eq!(create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), 0); + assert_eq!(create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list), 0); + (allocator, list) + } + + /// A title texture of 64 by 64 texels the host can draw into, of `levels` mip levels: a + /// colour target, or with `depth` a depth one. + pub(in crate::list) fn title_target(depth: bool, levels: u32) -> This { + // R8G8B8A8_UNORM (28) that allows render targets (flag 1), or R32_TYPELESS (39) that + // allows depth (flag 2). + let (format, flags) = if depth { (39, 2) } else { (28, 1) }; + title_texture(format, flags, levels, 1) + } + + /// A title texture of 64 by 64 texels, `levels` mip levels and `samples` samples a texel, + /// of DXGI format `format` with the resource flags `flags`. + fn title_texture(format: u32, flags: u32, levels: u32, samples: u32) -> This { + #[repr(C, align(8))] + struct Words([u32; 14]); + // The words of its description: a 2D texture. + let words = Words([3, 0, 0, 0, 64, 0, 64, 1 | levels << 16, format, samples, 0, 0x105, flags, 0]); + let layout = std::alloc::Layout::from_size_align(1 << 20, 65536).unwrap(); + // SAFETY: memory that stands for the title's, kept as long as the process. + let address = unsafe { std::alloc::alloc_zeroed(layout) } as u64; + let iid = crate::object::guid(0x696442be, 0xa72e, 0x4059, [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad]); + let mut out: This = std::ptr::null(); + let hr = crate::resource::create_at_address( + std::ptr::null(), + address, + words.0.as_ptr().cast(), + 0, + std::ptr::null(), + &iid, + &mut out, + ); + assert_eq!(hr, 0, "a title texture"); + out + } + + /// One group with the one texture barrier `barrier`, as the title passes them: the + /// group's words, and the barrier's they point to. + fn one(barrier: Texture) -> Box<([u64; 2], [u64; 8])> { + // SAFETY: plain words of the same size (the barrier has no byte that is not a field's). + let mut both = Box::new(([0u64; 2], unsafe { std::mem::transmute::(barrier) })); + let group = Group { kind: 1, count: 1, barriers: both.1.as_ptr().cast() }; + // SAFETY: as above. + both.0 = unsafe { std::mem::transmute::(group) }; + both + } + + /// [`one`] from a colour target that was drawn into to shader reads. + pub(in crate::list) fn drawn_then_read(resource: This) -> Box<([u64; 2], [u64; 8])> { + one(drawn(resource)) + } + + /// One group with `count` texture barriers as [`drawn_then_read`]'s, each on `resource`: + /// the group's words, and the barriers' they point to. + pub(in crate::list) fn many_drawn_then_read(resource: This, count: usize) -> ([u64; 2], Vec<[u64; 8]>) { + // SAFETY: plain words of the same size (the barrier has no byte that is not a field's). + let barriers = vec![unsafe { std::mem::transmute::(drawn(resource)) }; count]; + let group = Group { kind: 1, count: count as u32, barriers: barriers.as_ptr().cast() }; + // SAFETY: as above. + (unsafe { std::mem::transmute::(group) }, barriers) + } + + /// The title's call with one group (of [`one`]) on `list`. + fn call(list: This, groups: &([u64; 2], [u64; 8])) { + crate::list::barrier_groups(list, 1, groups.0.as_ptr().cast()); + } + + /// Moves `resource` to host state `to` in `list` as `ensure_state` does (the barrier is + /// recorded, so the list stays true): the state it left, if that was another. + pub(in crate::list) fn left(list: &crate::host::HostList, resource: This, to: u32) -> Option { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State; + let (texture, before) = list.transition(resource, to)?; + let barrier = crate::host::transition(texture, State(before as i32), State(to as i32)); + // SAFETY: an open list and a live texture. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + Some(before) + } + + /// Closes title lists and runs what they recorded in one submission, each behind what + /// its first uses ask of the textures it names (the submission's own doing): the card + /// took all of it (and the debug layer, where there is one in a diagnostics build with + /// `LEONIDA_D3D12_DEBUG=1`, had nothing against it). Then the lists are reset, to record + /// again. + pub(in crate::list) fn run(host: &crate::host::Host, lists: &[(This, This)]) { + use crate::object::slot; + for &(_, list) in lists { + assert_eq!(slot:: i32>(list, 0x48)(list), 0); + } + let host_list = |&(_, list): &(This, This)| crate::list::host_list(list).expect("a host list"); + let recorded: Vec<_> = lists.iter().map(host_list).collect(); + host.execute(&recorded); + // SAFETY: a plain query. + unsafe { host.device.GetDeviceRemovedReason() }.expect("the card ran what the lists recorded"); + assert_eq!(host.log_messages(), None); + for &(allocator, list) in lists { + assert_eq!(crate::list::reset(list, allocator, std::ptr::null()), 0); + } + } + + /// Lets a title list and its allocator go. + pub(in crate::list) fn release((allocator, list): (This, This)) { + for object in [list, allocator] { + assert_eq!(crate::object::slot:: u32>(object, 0x10)(object), 0); + } + } + + /// What [`asked`] says of `groups` with the textures moved: those it names with their + /// state words, and whether every target is waited for. + fn of(groups: &[Group]) -> (Vec<(usize, u32)>, bool) { + let mut named = Vec::new(); + // SAFETY: groups of this test, each with its barriers. + let every = + unsafe { asked(groups.len() as u32, groups.as_ptr().cast(), true, |r, s| named.push((r as usize, s))) }; + (named, every) + } + + /// What the switch's value asks for: nothing where it is not set or is no number, else + /// the two low bits of its number. + #[test] + fn the_switch_is_off_unless_it_is_a_number() { + let of = |value: &str| bits_of(Some(std::ffi::OsStr::new(value))); + assert_eq!(bits_of(None), 0); + assert_eq!([of("0"), of("1"), of("2"), of("3"), of(" 3 "), of("7")], [0, MOVES, WAITS, 3, 3, 3]); + assert_eq!([of(""), of("yes"), of("off"), of("-1"), of("4")], [0; 5]); + } + + /// Behind draws into it (or a copy into it, or nothing among these lists) and before + /// shader reads: the state its readers need, with the other reads the barrier names + /// beside it; a copy's source behind draws. Where the barrier names no access after it, + /// by the layout it leaves the texture in. + #[test] + fn a_barrier_that_leaves_a_texture_to_be_read_names_its_read_state() { + let (draw, depth, shade) = (SYNC_RENDER_TARGET, SYNC_DEPTH, SYNC_ALL_SHADING); + let layouts = [TARGET_LAYOUT, SHADER_LAYOUT]; + let depths = [DEPTH_LAYOUT, DEPTH_READ_LAYOUT]; + let of = |words: Global, layouts: [u32; 2]| read_state(&texture(words, layouts, 0x1000 as This)); + let read = Some(HOST_SHADER_RESOURCE); + let depth_read = Some(HOST_DEPTH_READ | HOST_SHADER_RESOURCE); + assert_eq!(of(b(draw, shade, RENDER_TARGET, SHADER_RESOURCE), layouts), read); + assert_eq!(of(b(depth, shade, DEPTH_WRITE, SHADER_RESOURCE), [DEPTH_LAYOUT, SHADER_LAYOUT]), read); + assert_eq!(of(b(depth, depth | shade, DEPTH_WRITE, SHADER_RESOURCE | DEPTH_READ), depths), depth_read); + let both = b(depth, depth | shade, DEPTH_WRITE | DEPTH_READ, SHADER_RESOURCE | DEPTH_READ); + assert_eq!(of(both, depths), depth_read); + assert_eq!( + of(b(draw, shade | SYNC_COPY, RENDER_TARGET, SHADER_RESOURCE | COPY_SOURCE | RESOLVE_SOURCE), layouts), + Some(HOST_SHADER_RESOURCE | HOST_COPY_SOURCE | HOST_RESOLVE_SOURCE) + ); + let copy = [TARGET_LAYOUT, COPY_SOURCE_LAYOUT]; + assert_eq!(of(b(draw, SYNC_COPY, RENDER_TARGET, COPY_SOURCE), copy), Some(HOST_COPY_SOURCE)); + assert_eq!(of(b(SYNC_COPY, shade, COPY_DEST, SHADER_RESOURCE), [COPY_DEST_LAYOUT, SHADER_LAYOUT]), read); + // The second half of a split barrier is the barrier. + assert_eq!(of(b(SYNC_SPLIT, shade, RENDER_TARGET, SHADER_RESOURCE), layouts), read); + // The texture's first use among the lists run together: no access before. + assert_eq!(of(b(SYNC_NONE, shade, NO_ACCESS, SHADER_RESOURCE), layouts), read); + assert_eq!(of(b(SYNC_NONE, shade, NO_ACCESS, SHADER_RESOURCE), [UNORDERED_LAYOUT, SHADER_LAYOUT]), read); + // (By the access it names, also where it says that no work comes before.) + assert_eq!(of(b(SYNC_NONE, shade, RENDER_TARGET, SHADER_RESOURCE), layouts), read); + // Its last: no access after, and the layout says what it is left for. + assert_eq!(of(b(draw, SYNC_NONE, RENDER_TARGET, NO_ACCESS), layouts), read); + assert_eq!(of(b(SYNC_NONE, SYNC_NONE, NO_ACCESS, NO_ACCESS), layouts), read); + assert_eq!(of(b(depth, SYNC_NONE, DEPTH_WRITE, NO_ACCESS), depths), depth_read); + let any = Some(HOST_SHADER_RESOURCE | HOST_COPY_SOURCE); + for generic in READ_LAYOUTS { + assert_eq!(of(b(draw, SYNC_NONE, RENDER_TARGET, NO_ACCESS), [TARGET_LAYOUT, generic]), any); + } + for (common, queue) in COMMON_LAYOUTS.into_iter().zip(SHADER_LAYOUTS) { + // Any access after draws: shaders and copies may read it. After nothing: no move. + assert_eq!(of(b(draw, shade, RENDER_TARGET, COMMON), [TARGET_LAYOUT, common]), any); + assert_eq!(of(b(SYNC_NONE, shade, NO_ACCESS, COMMON), [UNDEFINED_LAYOUT, common]), None); + assert_eq!(of(b(draw, SYNC_NONE, RENDER_TARGET, NO_ACCESS), [TARGET_LAYOUT, queue]), read); + } + for copy in COPY_LAYOUTS { + assert_eq!(of(b(draw, SYNC_NONE, RENDER_TARGET, NO_ACCESS), [TARGET_LAYOUT, copy]), Some(HOST_COPY_SOURCE)); + assert_eq!(of(b(SYNC_COPY, SYNC_NONE, COPY_DEST, NO_ACCESS), [COPY_DEST_LAYOUT, copy]), None); + } + } + + /// Nothing else is a move: not back to a target, not to or from unordered access, not + /// from any access (which may be unordered access) or from reads, also where the barrier + /// says that no work comes before or after it; not the half of a split barrier that only + /// begins, not a texture let go into a layout that is written, or with nothing kept. + #[test] + fn a_barrier_that_leaves_a_texture_to_be_written_names_no_state() { + let (draw, depth, shade) = (SYNC_RENDER_TARGET, SYNC_DEPTH, SYNC_ALL_SHADING); + let layouts = [TARGET_LAYOUT, SHADER_LAYOUT]; + for (words, layouts) in [ + (b(shade, draw, SHADER_RESOURCE, RENDER_TARGET), [SHADER_LAYOUT, TARGET_LAYOUT]), + (b(SYNC_NONE, draw, NO_ACCESS, RENDER_TARGET), [UNDEFINED_LAYOUT, TARGET_LAYOUT]), + (b(draw, shade, RENDER_TARGET, UNORDERED), [TARGET_LAYOUT, UNORDERED_LAYOUT]), + (b(shade, shade, UNORDERED, SHADER_RESOURCE), [UNORDERED_LAYOUT, SHADER_LAYOUT]), + (b(shade, SYNC_NONE, UNORDERED, NO_ACCESS), [UNORDERED_LAYOUT, SHADER_LAYOUT]), + (b(shade, shade, COMMON, SHADER_RESOURCE), [0, SHADER_LAYOUT]), + (b(shade, shade, COMMON, SHADER_RESOURCE), [UNORDERED_LAYOUT, SHADER_LAYOUT]), + (b(draw | shade, shade, RENDER_TARGET | UNORDERED, SHADER_RESOURCE), layouts), + (b(shade, SYNC_COPY, SHADER_RESOURCE, COPY_SOURCE), [SHADER_LAYOUT, COPY_SOURCE_LAYOUT]), + (b(SYNC_COPY, SYNC_COPY, COPY_DEST, COPY_SOURCE), [COPY_DEST_LAYOUT, COPY_SOURCE_LAYOUT]), + (b(draw, SYNC_SPLIT, RENDER_TARGET, SHADER_RESOURCE), layouts), + (b(draw, shade, RENDER_TARGET, SHADER_RESOURCE | UNORDERED), layouts), + (b(depth, depth, DEPTH_WRITE, DEPTH_READ), [DEPTH_LAYOUT, DEPTH_READ_LAYOUT]), + (b(draw, SYNC_NONE, RENDER_TARGET, NO_ACCESS), [TARGET_LAYOUT, TARGET_LAYOUT]), + (b(depth, SYNC_NONE, DEPTH_WRITE, NO_ACCESS), [DEPTH_LAYOUT, UNDEFINED_LAYOUT]), + (b(draw, SYNC_NONE, RENDER_TARGET, NO_ACCESS), [TARGET_LAYOUT, UNORDERED_LAYOUT]), + (b(SYNC_NONE, shade, COMMON, SHADER_RESOURCE), layouts), + (b(SYNC_NONE, shade, UNORDERED, SHADER_RESOURCE), [UNORDERED_LAYOUT, SHADER_LAYOUT]), + (b(draw, SYNC_NONE, RENDER_TARGET, UNORDERED), layouts), + ] { + let barrier = texture(words, layouts, 0x1000 as This); + let (before, after) = (words.access_before, words.access_after); + assert_eq!(read_state(&barrier), None, "{before:#x} to {after:#x}, {layouts:?}"); + } + } + + /// A barrier behind draws waits for them, whatever follows, also as the memory's last use; + /// one behind other writes does not. One on all memory also behind any access, and before + /// reads with nothing of these lists before it. + #[test] + fn a_barrier_behind_target_writes_waits_for_them() { + let (draw, depth, shade) = (SYNC_DRAW, SYNC_DEPTH, SYNC_ALL_SHADING); + for all in [false, true] { + assert!(b(draw, shade, RENDER_TARGET, SHADER_RESOURCE).waits(all)); + assert!(b(depth, shade, DEPTH_WRITE | DEPTH_READ, UNORDERED).waits(all)); + assert!(b(SYNC_SPLIT, shade, RENDER_TARGET, SHADER_RESOURCE).waits(all)); + assert!(b(draw, SYNC_NONE, RENDER_TARGET, NO_ACCESS).waits(all)); + assert!(!b(draw, SYNC_SPLIT, RENDER_TARGET, SHADER_RESOURCE).waits(all)); + assert!(!b(shade, shade, UNORDERED, SHADER_RESOURCE).waits(all)); + assert!(!b(shade, draw, SHADER_RESOURCE, RENDER_TARGET).waits(all)); + assert!(!b(SYNC_NONE, draw, NO_ACCESS, RENDER_TARGET).waits(all)); + assert!(!b(SYNC_NONE, SYNC_NONE, NO_ACCESS, NO_ACCESS).waits(all)); + assert_eq!(b(shade, shade, COMMON, SHADER_RESOURCE).waits(all), all); + assert_eq!(b(0x1, 0x1, COMMON, COMMON).waits(all), all); + assert_eq!(b(SYNC_NONE, shade, NO_ACCESS, SHADER_RESOURCE).waits(all), all); + assert_eq!(b(SYNC_NONE, shade, NO_ACCESS, COMMON).waits(all), all); + // (By the access it names, also where it says that no work comes before.) + assert_eq!(b(SYNC_NONE, shade, COMMON, SHADER_RESOURCE).waits(all), all); + assert!(!b(SYNC_NONE, shade, UNORDERED, SHADER_RESOURCE).waits(all)); + } + } + + /// A call's groups: a named texture is moved, one that names none and a global barrier + /// wait for every target, buffer barriers and barriers behind other writes ask nothing. + #[test] + fn a_calls_groups_say_what_moves_and_what_waits() { + let (draw, depth, shade) = (SYNC_RENDER_TARGET, SYNC_DEPTH, SYNC_ALL_SHADING); + let (colour, shadows) = (0x1000 as This, 0x2000 as This); + let first = b(SYNC_NONE, shade, NO_ACCESS, SHADER_RESOURCE); + let depth_read = b(depth, depth | shade, DEPTH_WRITE, SHADER_RESOURCE | DEPTH_READ); + let mut named = [ + drawn(colour), + // One slice of several, drawn into. + texture(depth_read, [DEPTH_LAYOUT, DEPTH_READ_LAYOUT], shadows), + // Back to a target: left to the draw that writes it. + texture(b(shade, draw, SHADER_RESOURCE, RENDER_TARGET), [SHADER_LAYOUT, TARGET_LAYOUT], colour), + // Its first use among these lists: moved, and not drawn into by them. + texture(first, [TARGET_LAYOUT, SHADER_LAYOUT], colour), + ]; + (named[1].first_level, named[1]._range) = (0, [1, 2, 1, 0, 1]); + let group = |kind: u32, count: usize, barriers: *const u8| Group { kind, count: count as u32, barriers }; + let moves = [group(1, named.len(), named.as_ptr().cast())]; + let read = HOST_SHADER_RESOURCE; + assert_eq!( + of(&moves), + (vec![(0x1000, read | DRAWN), (0x2000, HOST_DEPTH_READ | read | DRAWN | PART), (0x1000, read)], false) + ); + // With the textures not moved (the switch's other bit alone) those drawn into wait. + // SAFETY: groups of this test, each with its barriers. + assert!(unsafe { asked(1, moves.as_ptr().cast(), false, |_, _| unreachable!()) }); + + // The retail title's kind: a texture barrier with no resource. + let none = [drawn(std::ptr::null()), texture(first, [TARGET_LAYOUT, SHADER_LAYOUT], std::ptr::null())]; + assert_eq!(of(&[group(1, 1, none.as_ptr().cast())]), (vec![], true)); + assert_eq!(of(&[group(1, 1, none[1..].as_ptr().cast())]), (vec![], true), "what the lists before drew"); + // A named one that moves nothing (to unordered access) waits too. + let unordered = [texture(b(draw, shade, RENDER_TARGET, UNORDERED), [TARGET_LAYOUT, UNORDERED_LAYOUT], colour)]; + assert_eq!(of(&[group(1, 1, unordered.as_ptr().cast())]), (vec![], true)); + let globals = [b(shade, shade, UNORDERED, SHADER_RESOURCE), b(depth, shade, DEPTH_WRITE, SHADER_RESOURCE)]; + assert_eq!(of(&[group(0, 1, globals.as_ptr().cast())]), (vec![], false)); + assert_eq!(of(&[group(0, 2, globals.as_ptr().cast())]), (vec![], true)); + // Behind any access: a wait where the barrier is for all memory, nothing for one texture. + let any = b(shade, shade, COMMON, SHADER_RESOURCE); + let any = [texture(any, [0, SHADER_LAYOUT], std::ptr::null()), texture(any, [0, SHADER_LAYOUT], colour)]; + assert_eq!(of(&[group(1, 1, any.as_ptr().cast())]), (vec![], true)); + assert_eq!(of(&[group(1, 1, any[1..].as_ptr().cast())]), (vec![], false)); + assert_eq!(of(&[group(0, 1, any.as_ptr().cast())]), (vec![], true), "the words of a global barrier"); + // A texture taken up with nothing in it to keep: nothing to wait for. + let mut fresh = [texture(first, [UNDEFINED_LAYOUT, UNORDERED_LAYOUT], std::ptr::null()); 2]; + (fresh[0].global.access_after, fresh[1].layout_before, fresh[1].flags) = (COMMON, TARGET_LAYOUT, DISCARD); + assert_eq!(of(&[group(1, 2, fresh.as_ptr().cast())]), (vec![], false)); + + // Buffer barriers (40 bytes each: not read), an unknown kind, a group with no barriers. + let buffers = [0u8; 80]; + let others = [group(2, 2, buffers.as_ptr()), group(7, 1, buffers.as_ptr()), group(1, 3, std::ptr::null())]; + assert_eq!(of(&others), (vec![], false)); + // SAFETY: no groups at all. + assert!(!unsafe { asked(3, std::ptr::null(), true, |_, _| unreachable!()) }); + } + + /// The words of a call: its group count alone with the switch off, as before it was + /// there; the textures it moves with that part on, marked as drawn into where the other + /// part may have to wait for them; and a wait for every target where a texture did not fit. + #[test] + fn a_call_is_written_down_as_its_moves_and_its_wait() { + let many: Vec = (1..=NAMED + 1).map(|i| drawn((i * 0x100) as This)).collect(); + // (Textures the lists before these drew into: their first use among these.) + let first = b(SYNC_NONE, SYNC_ALL_SHADING, NO_ACCESS, SHADER_RESOURCE); + let firsts = vec![texture(first, [TARGET_LAYOUT, SHADER_LAYOUT], 0x100 as This); NAMED + 1]; + let read = u64::from(HOST_SHADER_RESOURCE); + let marked = read | u64::from(DRAWN); + let of = |bits: u8, barriers: &[Texture]| { + let _bits = Bits::set(bits); + let group = [Group { kind: 1, count: barriers.len() as u32, barriers: barriers.as_ptr().cast() }]; + // SAFETY: a group of this test, with its barriers. + let (w, len) = unsafe { words(1, group.as_ptr().cast()) }; + w[..len].to_vec() + }; + assert_eq!(of(0, &many[..2]), [1]); + assert_eq!(of(MOVES, &many[..2]), [1, 0, 0x100, read, 0x200, read]); + assert_eq!(of(WAITS, &many[..2]), [1, EVERY], "not moved: waited for"); + assert_eq!(of(MOVES | WAITS, &many[..2]), [1, 0, 0x100, marked, 0x200, marked]); + let full = of(MOVES | WAITS, &many[..NAMED]); + assert_eq!((full.len(), full[1]), (WORDS, 0), "all of them fit"); + let over = of(MOVES | WAITS, &many); + assert_eq!((over.len(), over[1], over[WORDS - 2]), (WORDS, EVERY, (NAMED * 0x100) as u64)); + assert_eq!(of(MOVES, &many)[1], 0, "no wait with that part off"); + assert_eq!(of(MOVES | WAITS, &firsts[..NAMED])[..4], [1, 0, 0x100, read], "not drawn into by these lists"); + assert_eq!(of(MOVES | WAITS, &firsts)[1], EVERY, "what the lists before drew into the one left out"); + let _bits = Bits::set(MOVES | WAITS); + // SAFETY: no groups. + let (w, len) = unsafe { words(0, std::ptr::null()) }; + assert_eq!(w[..len], [0]); + } + + /// Through the list's own method, on the card: a texture the list drew into, which a + /// barrier of the title's then names, is in the state its readers need (the next draw + /// into it moves it back, as for any target); a depth texture too, still readable as depth. + /// Without that part of the switch they stay targets, as before, and with the other part + /// alone what was drawn is waited for instead. What was recorded runs. + #[test] + fn a_named_barrier_moves_the_texture_the_list_drew_into() { + let Some(host) = card() else { + return; // no host GPU here + }; + for bits in [0, MOVES, WAITS, MOVES | WAITS] { + let _bits = Bits::set(bits); + let moved = bits & MOVES != 0; + let title = title_list(); + let (colour, depth) = (title_target(false, 1), title_target(true, 1)); + let host_list = crate::list::host_list(title.1).expect("a host list"); + // As a draw does for its targets (`State::prepare_for`). + crate::list::ensure_state(host_list, colour, TARGET); + crate::list::ensure_state(host_list, depth, DEPTH_TARGET); + let waits = TEST_WAITS.get(); + let depth_read = b(SYNC_DEPTH, SYNC_DEPTH | SYNC_ALL_SHADING, DEPTH_WRITE, SHADER_RESOURCE | DEPTH_READ); + call(title.1, &drawn_then_read(colour)); + call(title.1, &one(texture(depth_read, [DEPTH_LAYOUT, DEPTH_READ_LAYOUT], depth))); + // (With the waits alone the first of the two barriers finds the list's first wait due.) + let all = u32::from(bits == WAITS); + let recorded = TEST_WAITS.get(); + assert_eq!([recorded[0] - waits[0], recorded[1] - waits[1]], [all, 2 - all], "bits {bits}"); + assert_eq!(left(host_list, colour, TARGET), moved.then_some(HOST_SHADER_RESOURCE), "bits {bits}"); + assert_eq!( + left(host_list, depth, DEPTH_TARGET), + moved.then_some(HOST_DEPTH_READ | HOST_SHADER_RESOURCE), + "bits {bits}" + ); + run(host, &[title]); + release(title); + } + } + + /// A barrier on one level of a texture that has several moves nothing (a host texture has + /// one state, and the draw into its next level would move all of it back): what was drawn + /// is waited for instead. So for the depth of a texture that has stencil beside it. On the + /// one level of a texture that has no other it is a move. + #[test] + fn a_barrier_on_a_part_of_a_texture_moves_it_only_if_that_is_all_of_it() { + let Some(host) = card() else { + return; // no host GPU here + }; + let _bits = Bits::set(MOVES | WAITS); + let title = title_list(); + let (chain, single) = (title_target(false, 3), title_target(false, 1)); + // R24G8_TYPELESS (44) that allows depth (flag 2): two planes. + let stencil = title_texture(44, 2, 1, 1); + let host_list = crate::list::host_list(title.1).expect("a host list"); + for target in [chain, single] { + crate::list::ensure_state(host_list, target, TARGET); + } + crate::list::ensure_state(host_list, stencil, DEPTH_TARGET); + let made = crate::resource::made_copy(stencil).expect("the host's texture of it"); + // SAFETY: a plain query. + let format = unsafe { made.texture.GetDesc() }.Format.0; + assert!(matches!(format, 19..=22 | 44..=47), "a format of two planes: {format}"); + let depth_read = b(SYNC_DEPTH, SYNC_DEPTH | SYNC_ALL_SHADING, DEPTH_WRITE, SHADER_RESOURCE | DEPTH_READ); + let depth_read = texture(depth_read, [DEPTH_LAYOUT, DEPTH_READ_LAYOUT], stencil); + let waits = TEST_WAITS.get(); + // The first level, slice and plane of each. + for mut part in [drawn(single), depth_read, drawn(chain)] { + (part.first_level, part._range) = (0, [1, 0, 1, 0, 1]); + call(title.1, &one(part)); + } + let recorded = TEST_WAITS.get(); + // (One wait for what was drawn: nothing was, between the two that ask for it.) + assert_eq!([recorded[0] - waits[0], recorded[1] - waits[1]], [1, 2], "the one moved, the others waited for"); + assert_eq!(left(host_list, single, TARGET), Some(HOST_SHADER_RESOURCE)); + assert_eq!(left(host_list, chain, TARGET), None, "still a target"); + assert_eq!(left(host_list, stencil, DEPTH_TARGET), None, "still a target"); + // All of it: a move. + call(title.1, &one(depth_read)); + assert_eq!(left(host_list, stencil, DEPTH_TARGET), Some(HOST_DEPTH_READ | HOST_SHADER_RESOURCE)); + run(host, &[title]); + release(title); + } + + /// A texture one list drew into, named by the first barrier of the next as it is where + /// the lists are not run together (no work and no access before, only its layouts): the + /// second list has it in the state its readers need from its start, and the first use + /// of it there is brought about before the list runs; also where both are submitted at + /// once. + #[test] + fn a_texture_another_list_drew_into_is_moved_at_its_first_barrier() { + let Some(host) = card() else { + return; // no host GPU here + }; + for (bits, together) in [(0, false), (MOVES, false), (MOVES, true)] { + let _bits = Bits::set(bits); + let (drawing, reading) = (title_list(), title_list()); + let colour = title_target(false, 1); + let host_list = |title: (This, This)| crate::list::host_list(title.1).expect("a host list"); + // The first list draws into it (`State::prepare_for`). + crate::list::ensure_state(host_list(drawing), colour, TARGET); + if !together { + run(host, &[drawing]); + } + // The second names it before anything else. + let first = b(SYNC_NONE, SYNC_ALL_SHADING, NO_ACCESS, SHADER_RESOURCE); + call(reading.1, &one(texture(first, [TARGET_LAYOUT, SHADER_LAYOUT], colour))); + // (Its next draw into it finds it read, and moves it back; without the move the + // draw is the list's first use of it, and records nothing.) + let read = (bits != 0).then_some(HOST_SHADER_RESOURCE); + assert_eq!(left(host_list(reading), colour, TARGET), read, "bits {bits}, together {together}"); + if together { + run(host, &[drawing, reading]); + } else { + run(host, &[reading]); + } + release(drawing); + release(reading); + } + } + + /// A barrier that names no texture (the retail title's kind) after the list drew: a wait + /// for everything is recorded in place of the one for shader writes, once; again only + /// after the list drew, cleared or resolved into a target again. A texture drawn into + /// that the host has no copy of waits the same way, one only taken up does not. Without + /// that part of the switch there is the wait for shader writes each time, as before. + #[test] + fn a_barrier_that_names_no_texture_waits_for_what_was_drawn() { + let Some(host) = card() else { + return; // no host GPU here + }; + for bits in [0, MOVES, WAITS, MOVES | WAITS] { + let _bits = Bits::set(bits); + let on = u32::from(bits & WAITS != 0); + let title = title_list(); + let list = title.1; + let none = drawn_then_read(std::ptr::null()); + let waits = TEST_WAITS.get(); + let mut calls = 0; + let mut all = |groups: &([u64; 2], [u64; 8])| { + call(list, groups); + calls += 1; + let now = TEST_WAITS.get(); + assert_eq!(now[0] - waits[0] + now[1] - waits[1], calls, "one wait or the other for each call"); + now[0] - waits[0] + }; + // What ran before this list is not known to it: its first is recorded. + assert_eq!(all(&none), on, "bits {bits}"); + assert_eq!(all(&none), on, "nothing drawn since"); + crate::list::with_state(list, |_, state| state.targets_written()); + assert_eq!(all(&none), 2 * on, "drawn into a target since"); + // A texture no host use has made a copy of: nothing of that name to move. + let unused = title_target(false, 1); + assert_eq!(all(&drawn_then_read(unused)), 2 * on, "nothing drawn since"); + crate::list::with_state(list, |_, state| state.targets_written()); + let first = b(SYNC_NONE, SYNC_ALL_SHADING, NO_ACCESS, SHADER_RESOURCE); + let taken_up = one(texture(first, [TARGET_LAYOUT, SHADER_LAYOUT], unused)); + // (With the moves it would be moved if the host had it; a barrier on one texture + // with nothing of these lists before it asks for no wait.) + assert_eq!(all(&taken_up), 2 * on, "bits {bits}: only taken up"); + assert_eq!(all(&drawn_then_read(unused)), 3 * on, "bits {bits}: drawn into"); + assert!(crate::resource::made_copy(unused).is_none(), "and none is made for a barrier"); + run(host, &[title]); + release(title); + } + } + + /// What the title's own clears write is waited for as what its draws write: a clear of a + /// colour target and one of a depth target, through the list's methods, each make the + /// next barrier that names no texture, and the next pipeline sync, a wait for everything. + #[test] + fn a_clear_into_a_target_is_waited_for_as_a_draw_is() { + let Some(host) = card() else { + return; // no host GPU here + }; + let _bits = Bits::set(WAITS); + let title = title_list(); + let list = title.1; + let (colour, depth) = (title_target(false, 1), title_target(true, 1)); + // The title's views of them, a slot of descriptor memory each; the depth view as + // D32_FLOAT (40) of the 2D texture (3), which is without a format of its own. + let slots = Box::new([[0u64; 16]; 2]); + let (colour_view, depth_view) = (slots[0].as_ptr() as u64, slots[1].as_ptr() as u64); + crate::descriptor::create_rtv(std::ptr::null(), colour, std::ptr::null(), colour_view); + crate::descriptor::create_dsv(std::ptr::null(), depth, &[40, 3, 0, 0, 0, 0], depth_view); + let none = drawn_then_read(std::ptr::null()); + let waits = TEST_WAITS.get(); + let all = || TEST_WAITS.get()[0] - waits[0]; + call(list, &none); + call(list, &none); + assert_eq!(all(), 1, "the list's first, and nothing drawn since"); + crate::list::clear_rtv(list, colour_view, &[0.0, 0.5, 1.0, 1.0], 0, std::ptr::null()); + call(list, &none); + call(list, &none); + assert_eq!(all(), 2, "the colour target was cleared"); + crate::list::clear_dsv(list, depth_view, 1, 1.0, 0, 0, std::ptr::null()); + crate::list::sync(list, 0x1, 0, 0, 0); + crate::list::sync(list, 0x1, 0, 0, 0); + assert_eq!(all(), 3, "the depth target was cleared"); + run(host, &[title]); + release(title); + } + + /// So is a resolve into one, through the list's own method (the card resolves it). + #[test] + fn a_resolve_into_a_target_is_waited_for_as_a_draw_is() { + let Some(host) = card() else { + return; // no host GPU here + }; + let _bits = Bits::set(WAITS); + let title = title_list(); + let list = title.1; + // Colour targets of R8G8B8A8_UNORM (28): one of 4 samples a texel, and the one it is + // resolved into. + let (samples, resolved) = (title_texture(28, 1, 1, 4), title_target(false, 1)); + let none = drawn_then_read(std::ptr::null()); + let waits = TEST_WAITS.get(); + let all = || TEST_WAITS.get()[0] - waits[0]; + call(list, &none); + call(list, &none); + assert_eq!(all(), 1, "the list's first, and nothing drawn since"); + crate::list::resolve(list, resolved, 0, samples, 0, 28); + call(list, &none); + call(list, &none); + assert_eq!(all(), 2, "a target was resolved into"); + run(host, &[title]); + release(title); + } + + /// A pipeline sync after the list drew waits as a barrier that names no texture does. + #[test] + fn a_pipeline_sync_waits_for_what_was_drawn() { + let Some(host) = card() else { + return; // no host GPU here + }; + for bits in [0, MOVES, WAITS, MOVES | WAITS] { + let _bits = Bits::set(bits); + let on = u32::from(bits & WAITS != 0); + let title = title_list(); + let list = title.1; + let waits = TEST_WAITS.get(); + let sync = || { + crate::list::sync(list, 0x1, 0, 0, 0); + let now = TEST_WAITS.get(); + [now[0] - waits[0], now[1] - waits[1]] + }; + assert_eq!(sync(), [on, 1 - on], "bits {bits}"); + assert_eq!(sync(), [on, 2 - on], "nothing drawn since"); + crate::list::with_state(list, |_, state| state.targets_written()); + assert_eq!(sync(), [2 * on, 3 - 2 * on], "bits {bits}"); + run(host, &[title]); + release(title); + } + } +} diff --git a/d3d12/crates/leonida-gpu/src/list/thin.rs b/d3d12/crates/leonida-gpu/src/list/thin.rs index ab25e1c2bf..5a3c9cc395 100644 --- a/d3d12/crates/leonida-gpu/src/list/thin.rs +++ b/d3d12/crates/leonida-gpu/src/list/thin.rs @@ -673,8 +673,11 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> } 0 } -extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { - front(this).put(BARRIER_GROUPS, &[u64::from(count)]); +extern "system" fn barrier_groups(this: This, count: u32, groups: *const u8) { + // What the groups ask of targets is read now, while the title's array is there. + // SAFETY: the title's groups, as it passes them. + let (words, len) = unsafe { super::groups::words(count, groups) }; + front(this).put(BARRIER_GROUPS, &words[..len]); } extern "system" fn viewports(this: This, count: u32, items: *const D3D12_VIEWPORT) { let count = if items.is_null() { 0 } else { count }; @@ -845,7 +848,7 @@ fn translate(list: This, stream: &[u64], left: impl Fn() -> bool) -> (u64, bool) BARRIER => { super::barrier(list, n as u32, at_or(w, 1)); } - BARRIER_GROUPS => super::barrier_groups(list, n as u32, std::ptr::null()), + BARRIER_GROUPS => super::barrier_groups_words(list, w), VIEWPORTS => state::viewports(list, n as u32, at(w, 1, n)), SCISSORS => state::scissors(list, n as u32, at(w, 1, n)), BLEND_FACTOR => state::blend_factor(list, at(w, 1, n)), @@ -1075,4 +1078,59 @@ mod tests { let at = |r: &Arc| order.iter().position(|o| Arc::ptr_eq(o, r)); assert_eq!([at(&waited), at(&first), at(&second)], [Some(0), Some(1), Some(2)]); } + + /// A call of the enhanced barriers is done from what was read of its groups when it was + /// written down (the title's arrays may be gone by then): the texture one names is moved + /// to the state its readers need, and one that names none waits for what was drawn. All + /// the words of a call that names more textures than fit are written and read back; with + /// the switch off a call is its group count alone, as before there was one. + #[test] + fn enhanced_barriers_are_done_from_what_was_written_down() { + use super::super::groups::tests::{Bits, TARGET, card, drawn_then_read, left, release, run}; + use super::super::groups::tests::{many_drawn_then_read, title_list, title_target}; + use super::super::groups::{EVERY, TEST_WAITS, WORDS, words}; + let Some(host) = card() else { + return; // no host GPU here + }; + let _both = Bits::set(3); + let title = title_list(); + let colour = title_target(false, 1); + let host_list = super::super::host_list(title.1).expect("a host list"); + // As a draw does for its targets (`State::prepare_for`). + super::super::ensure_state(host_list, colour, TARGET); + let mut f = Front::default(); + f.recording = Some(Arc::new(Recording::new(0))); + for resource in [colour, std::ptr::null()] { + // (As `barrier_groups` writes a call down; the groups go at the end of the turn.) + let groups = drawn_then_read(resource); + // SAFETY: a group of this test, with its barrier. + let (one, len) = unsafe { words(1, groups.0.as_ptr().cast()) }; + f.put(BARRIER_GROUPS, &one[..len]); + } + { + let (group, _barriers) = many_drawn_then_read(colour, WORDS); + // SAFETY: a group of this test, with its barriers. + let (all, len) = unsafe { words(1, group.as_ptr().cast()) }; + assert_eq!((len, all[1]), (WORDS, EVERY), "as many as fit, and a wait for the others"); + f.put(BARRIER_GROUPS, &all[..len]); + let _off = Bits::set(0); + // SAFETY: as above. + let (count, len) = unsafe { words(1, group.as_ptr().cast()) }; + f.put(BARRIER_GROUPS, &count[..len]); + } + let stream = std::mem::take(&mut f.words); + assert_eq!( + stream.len(), + (1 + 4) + (1 + 2) + (1 + WORDS) + (1 + 1), + "a texture and its state; only the wait; all that fit; the group count alone" + ); + let waits = TEST_WAITS.get(); + assert_eq!(translate(title.1, &stream, || false), (4, false)); + let recorded = TEST_WAITS.get(); + // (For everything once: nothing was drawn between the two calls that ask for it.) + assert_eq!([recorded[0] - waits[0], recorded[1] - waits[1]], [1, 3], "for everything, else for shader writes"); + assert_eq!(left(host_list, colour, TARGET), Some(0x40 | 0x80)); + run(host, &[title]); + release(title); + } } From a3df308fb3eb5989e9c3ab1f875e5580386ab2d1 Mon Sep 17 00:00:00 2001 From: Zack Date: Mon, 30 Nov 2026 19:52:15 -0800 Subject: [PATCH 4/5] d3d12: switches.md lists LEONIDA_TARGET_BARRIERS, LEONIDA_LIST_TWIN_MOVE and LEONIDA_HOST_WAVE32 (D3D12-RDNA-GBUFFER-TERRAIN-TILES) Regenerated with tools/d3d12_switches.py for the three names of this branch: LEONIDA_TARGET_BARRIERS, LEONIDA_LIST_TWIN_MOVE and LEONIDA_HOST_WAVE32. The comments of the first and the last now begin with the sentence that says what the switch does, which is the one the page takes. The page was behind the sources before this branch: regenerated on d4fabd3fe it changes 13 rows that are not this branch's (the rows whose first file is now apps/leonida/src/leonida.rs, some counts of files, the names test code makes up), and those come with this. This branch's own are the three new rows, the count of names, and one file more for LEONIDA_AB, LEONIDA_D3D12_DEBUG and LEONIDA_THIN. AI-assisted (Claude Fable 5.2). python -I tools/d3d12_switches.py --check d3d12/docs/switches.md: no difference. The two comments are the only change to the code: leonida-gpu lib tests 597 passed (677 with --features diagnostics) on RTX 3090, driver 610.88, and on WARP, no clippy warning on the changed lines. Refs #2771 Refs #2770 AI-assisted: yes --- d3d12/crates/leonida-gpu/src/list/groups.rs | 6 ++-- d3d12/crates/leonida-shader/src/emit/mod.rs | 24 +++++++------- d3d12/docs/switches.md | 35 +++++++++++---------- 3 files changed, 34 insertions(+), 31 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/list/groups.rs b/d3d12/crates/leonida-gpu/src/list/groups.rs index 566888bae4..f0b59bbe51 100644 --- a/d3d12/crates/leonida-gpu/src/list/groups.rs +++ b/d3d12/crates/leonida-gpu/src/list/groups.rs @@ -1,6 +1,6 @@ -//! What the title's barriers and pipeline syncs behind draws into targets ask -//! of the host's textures: `LEONIDA_TARGET_BARRIERS=3` (1: named textures -//! moved to their read state, 2: waits for what was drawn; off by default). +//! `LEONIDA_TARGET_BARRIERS=3` does to the host's textures what the title's +//! barriers and syncs behind draws into targets ask (1: named textures moved +//! to their read state, 2: waits for what was drawn; off by default). //! //! The title tells the console when what it drew into a target has to be //! there for the shaders that read it next: with a texture barrier of its diff --git a/d3d12/crates/leonida-shader/src/emit/mod.rs b/d3d12/crates/leonida-shader/src/emit/mod.rs index f1beb5faed..c786b5bb0f 100644 --- a/d3d12/crates/leonida-shader/src/emit/mod.rs +++ b/d3d12/crates/leonida-shader/src/emit/mod.rs @@ -365,18 +365,18 @@ pub fn rdna_float() -> u32 { }) } -/// The lanes the translator takes a host whose widest wave is `lanes` to have: 32 where they -/// are more, on an AMD card with waves of 32 to 64 (`rdna`: [`set_host_rdna`]) that is `asked` -/// for it with `LEONIDA_HOST_WAVE32=1` (off by default). That translates for such a card as for -/// a card with waves of 32, to tell the two sets of forms apart on it: those for 32 lanes are -/// what every NVIDIA card runs (a program then declares `WaveSize(32)`, which such a card takes; -/// one whose narrowest wave is wider would not, so it is left alone), those for 64 lanes run -/// only on a card that has such waves. A program the forms for 32 lanes cannot take is refused, -/// as on a card of 32 lanes ("no wave32 lowering for this wave64 program"; monte-alt/vesper -/// 7b7e556, GPL-3.0 as this, takes the forms for 32 by default on such a card for the programs -/// they fit and leaves the others at 64: its `VESPER_RDNA_WAVE32`, which the reports name among -/// what was not told apart). For #2770 and #2771 (black patches of ground on an RX 9070 XT and -/// an RX 7800 XT); not run on such a card here. +/// `LEONIDA_HOST_WAVE32=1` (off by default): an AMD card with waves of 32 to 64 lanes is taken +/// for one of 32 and gets the forms an NVIDIA card gets, to tell the two sets of forms apart on +/// it. This is the lanes the translator takes a host whose widest wave is `lanes` to have: 32 +/// where they are more, if it is such a card (`rdna`: [`set_host_rdna`]) and it is `asked`. The +/// forms for 32 lanes are what every NVIDIA card runs (a program then declares `WaveSize(32)`, +/// which such a card takes; one whose narrowest wave is wider would not, so it is left alone), +/// those for 64 lanes run only on a card that has such waves. A program the forms for 32 lanes +/// cannot take is refused, as on a card of 32 lanes ("no wave32 lowering for this wave64 +/// program"; monte-alt/vesper 7b7e556, GPL-3.0 as this, takes the forms for 32 by default on +/// such a card for the programs they fit and leaves the others at 64: its `VESPER_RDNA_WAVE32`, +/// which the reports name among what was not told apart). For #2770 and #2771 (black patches +/// of ground on an RX 9070 XT and an RX 7800 XT); not run on such a card here. /// /// Part of the translation: the shader cache keys on the lanes taken ([`host_settings`]). fn told_lanes(lanes: u32, rdna: bool, asked: bool) -> u32 { diff --git a/d3d12/docs/switches.md b/d3d12/docs/switches.md index 7cb7061e91..01a71c4d8d 100644 --- a/d3d12/docs/switches.md +++ b/d3d12/docs/switches.md @@ -6,7 +6,7 @@ It says which names exist and what the code's own comments say of them. It is ** settings and says nothing of what a switch gains: for that read [findings.md](findings.md) first, and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. -646 names; 606 have a sentence of a comment below, the others no comment or only a bare list. +649 names; 609 have a sentence of a comment below, the others no comment or only a bare list. - **Kind**: how the code reads it, where that can be told. "see the code" is a number, a path, a list or a switch read some other way; its default is not given here. @@ -21,24 +21,29 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | Name | Kind | A/B | L | F | Named in | In the code's words | |---|---|---|---|---|---|---| +| `LEONIDA_AB` | see the code | | | yes | `leonida/leonida.rs` +38 | `LEONIDA_AB=<seconds>,<switch>[,<switch>..]`: every so many seconds, at a present, the next phase begins; switch number n is on in the phases whose number has bit n, so that all combinations come one after another, again... | | `LEONIDA_AUDIO_CAPTURE` | see the code | | | | `leonida/main.rs` +1 | `LEONIDA_AUDIO_CAPTURE=<file.wav>` records what the title plays, 48 kHz stereo 16-bit, through process loopback: our own process tree only, never the rest of the host's mix. | +| `LEONIDA_CAPTURE` | see the code | | yes | | `leonida/leonida.rs` +4 | Presented frames written to PNG files, to see what reaches the screen: with `LEONIDA_CAPTURE=<folder>`, every frame whose number is a power of two (the frames the log reports) is saved as `frame-<n>.png`, at half size. | | `LEONIDA_CARD_AWAKE` | see the code | yes | yes | yes | `leonida/replay.rs` +4 | Keeps the card's clocks up between submissions (`LEONIDA_CARD_AWAKE=1`; off by default). | | `LEONIDA_CRASH_SAVE` | see the code | | | | `leonida/run.rs` | `LEONIDA_CRASH_SAVE=<rva>:<len>,...` (hex) writes those title ranges to `crash-<rva>.bin` in the cache dir on a crash. | | `LEONIDA_D3D12_DRED` | off unless set and not `0` | | yes | yes | `leonida/replay.rs` +7 | Whether device-removed data is on (`LEONIDA_D3D12_DRED`, diagnostics builds). | +| `LEONIDA_DLSS_DIR` | see the code | | yes | | `leonida/leonida.rs` +3 | ... `LEONIDA_DLSS_SDK`, and `nvngx_dlss.dll` is looked for in `LEONIDA_DLSS_DIR` (else beside the executable).... | | `LEONIDA_DUMP_MATCH` | see the code | | | | `leonida/translate.rs` | `LEONIDA_DUMP_MATCH=<dir>;<text>\|<text>...`: the containers whose line holds one of the texts (a name, `#hash`), as the title has them. | | `LEONIDA_DXIL` | see the code | | | | `leonida/main.rs` +1 | The DLL is found at `LEONIDA_DXIL` if set, else the newest Windows SDK's `bin\<version>\x64\dxil.dll`, else wherever `LoadLibrary` finds it. | -| `LEONIDA_EMIT_DUMP` | see the code | | | | `leonida/translate.rs` +1 | `LEONIDA_EMIT_DUMP` with `--list`: every emitted shader as a file. | +| `LEONIDA_EMIT_DUMP` | see the code | | | | `leonida/translate.rs` +2 | `LEONIDA_EMIT_DUMP` with `--list`: every emitted shader as a file. | | `LEONIDA_FAIL_DUMP` | see the code | | | | `leonida/translate.rs` | `LEONIDA_FAIL_DUMP=<dir>`: the first 3 containers of each failure reason, as the title has them (`.cdxil`), to work on a translator gap offline | | `LEONIDA_FIND_PLAYER` | see the code | | | | `leonida/player.rs` +2 | Diagnostics only (`LEONIDA_FIND_PLAYER=<start s>,<seconds>`): finds, at run time, where the title keeps the local player's position, and how to reach it from the title's image, so that a teleport can write there (`player... | | `LEONIDA_FSR_UPSCALER` | see the code | | yes | yes | `leonida/run.rs` +6 | The title upscales with FidelityFX on Series S, and on the other consoles when the loader makes it (`LEONIDA_FSR_UPSCALER=1`, leonida-loader's hooks.rs). | | `LEONIDA_GAME_ACTIONS` | see the code | | | | `leonida/game_actions.rs` +7 | Where the title's own code for the trainer menu's game actions is, and the hook that runs them once a frame on the title's own thread (`docs/mod-menu.md`, "Game actions"). Off unless `LEONIDA_GAME_ACTIONS=1`. | | `LEONIDA_GAME_ACTIONS_RUN` | see the code | | | | `leonida/game_actions.rs` | ...by default until it has been seen to work in the title). - `LEONIDA_GAME_ACTIONS_RUN="<s>:<command>;..."` asks for commands that many seconds after the start, for a test without the keyboard: `info`, `cheat <n>`, `wanted... | | `LEONIDA_GAME_ACTIONS_WARP` | see the code | | | | `leonida/game_actions.rs` +1 | ...ts results into the log: the arguments are the asker's). - `LEONIDA_GAME_ACTIONS_WARP=1` lets a teleport write the ped's position on the title's thread: an experiment, the title's own function for moving a ped was not fo... | +| `LEONIDA_GAME_DIR` | see the code | | | | `leonida/leonida.rs` +7 | With `LEONIDA_GAME_DIR` set to the folder of the Xbox package: every place is in the code of `game_scarlett_master.exe` exactly once and points inside the image. | | `LEONIDA_HOST_MAX_WAVE` | see the code | | | | `leonida/translate.rs` | `LEONIDA_HOST_MAX_WAVE=32`: translate as for a host whose waves have at most 32 lanes (as the runtime does on such a card). | | `LEONIDA_HOST_RDNA` | see the code | | | yes | `leonida/translate.rs` | `LEONIDA_HOST_RDNA=1`: as for an AMD RDNA card (`LEONIDA_RDNA_FLOAT`). | | `LEONIDA_HOST_WAVE` | see the code | | | yes | `leonida/main.rs` | Set `LEONIDA_HOST_WAVE` and `LEONIDA_VIEW_LIMIT` to what the run's log says of the host. | | `LEONIDA_INDIRECT_BATCH` | see the code | | yes | yes | `leonida/replay.rs` +9 | Whether indirect executions of one record are clamped in batches (`crate::indirect::batch`; `LEONIDA_INDIRECT_BATCH=0`: each on its own, or in windows ([`windows`])). | | `LEONIDA_KBM_SPEED` | see the code | | | | `leonida/player_context.rs` | `LEONIDA_PLAYER_VEHICLE_AT=off` leaves it unused. - `LEONIDA_KBM_SPEED=1`: how fast the ped moves ([`SpeedRule`]). | +| `LEONIDA_KEYS` | see the code | | | | `leonida/leonida.rs` +2 | The scripted keys (`LEONIDA_KEYS`) also press the first pad's buttons, by the stand-in pad's table: with a real pad connected the stand-in is not there, and a title that listens to the pad (the title's start screen) saw... | | `LEONIDA_KEYS_FILE` | see the code | | | | `leonida/player_find.rs` +2 | Then, for `<seconds>`, it reads every candidate's position every `LEONIDA_PLAYER_INTERVAL_MS` (250) together with the keys held at that moment (the file `LEONIDA_KEYS_FILE` names). | | `LEONIDA_LUA` | see the code | | | | `leonida/run.rs` +2 | `LEONIDA_LUA=0` turns it all off: no thread, and a present pays one atomic load in [`tick`]. | | `LEONIDA_NATIVE_ALL` | see the code | | | | `leonida/native_scan.rs` | ... handlers for a run to be listed and to enter the union. - `LEONIDA_NATIVE_ALL=1`: also scan read-only and image-backed memory (the default is private/mapped memory a program can write to). - `LEONIDA_NATIVE_LOOSE=1`: a... | @@ -97,15 +102,13 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_CACHE_DIR` | see the code | | yes | | `leonida-core/config.rs` +2 | | | `LEONIDA_CONFIG` | see the code | | | | `leonida-core/config.rs` +2 | Resolution order for each value: environment variable, then the config file (`LEONIDA_CONFIG`, else `./leonida.toml`), then the default. | | `LEONIDA_DATA_DIR` | see the code | | | | `leonida-core/config.rs` +2 | | -| `LEONIDA_GAME_DIR` | see the code | | | | `leonida-core/config.rs` +6 | With `LEONIDA_GAME_DIR` set to the folder of the Xbox package: every place is in the code of `game_scarlett_master.exe` exactly once and points inside the image. | -| `LEONIDA_LOG` | see the code | | yes | | `leonida-core/logging.rs` +1 | Filter with `LEONIDA_LOG` (falls back to `RUST_LOG`), e.g. | +| `LEONIDA_LOG` | see the code | | yes | | `leonida-core/logging.rs` +2 | Filter with `LEONIDA_LOG` (falls back to `RUST_LOG`), e.g. | | `LEONIDA_TEST_TITLES` | see the code | | | | `leonida-core/config.rs` | | ## leonida-gpu | Name | Kind | A/B | L | F | Named in | In the code's words | |---|---|---|---|---|---|---| -| `LEONIDA_AB` | see the code | | | yes | `leonida-gpu/ab.rs` +36 | `LEONIDA_AB=<seconds>,<switch>[,<switch>..]`: every so many seconds, at a present, the next phase begins; switch number n is on in the phases whose number has bit n, so that all combinations come one after another, again... | | `LEONIDA_ACTIVATE_RAYS` | see the code | | yes | | `leonida-gpu/pipeline/make.rs` +1 | | | `LEONIDA_ADAPTER` | see the code | | yes | | `leonida-gpu/host.rs` +3 | LOCAL: the card `LEONIDA_ADAPTER` names, for a PC with more than one. | | `LEONIDA_AHEAD_INDEX` | on, `0` turns it off | yes | | | `leonida-gpu/watch.rs` | Whether the page ranges asked ahead ([`Journal::ahead`]) are kept in order, so that the one that holds a range is found in a few steps (`LEONIDA_AHEAD_INDEX=0`: a list looked through from its start, as before). | @@ -157,7 +160,6 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_BVH_QUARANTINE` | see the code | | | | `leonida-gpu/pipeline.rs` | `LEONIDA_BVH_QUARANTINE=1`: what the structure builder's stages store stays in the host's copies and is not copied back into title memory. | | `LEONIDA_BVH_SIZES_WAIT` | see the code | | | | `leonida-gpu/memory.rs` | Whether a submission that asks for the sizes of structures is waited for, and landed, before the title goes on (`LEONIDA_BVH_SIZES_WAIT=1`; off). | | `LEONIDA_BVH_TRACE` | see the code | | | | `leonida-gpu/memory.rs` | `LEONIDA_BVH_TRACE=1`: the sizes the builder is asked for (its program of one thread that stores a structure's compacted size) and when title memory has them, and the copies to a place of that size. | -| `LEONIDA_CAPTURE` | see the code | | yes | | `leonida-gpu/capture.rs` +3 | Presented frames written to PNG files, to see what reaches the screen: with `LEONIDA_CAPTURE=<folder>`, every frame whose number is a power of two (the frames the log reports) is saved as `frame-<n>.png`, at half size. | | `LEONIDA_CAPTURE_ALL` | see the code | | | | `leonida-gpu/capture.rs` +1 | `LEONIDA_CAPTURE_ALL=1`: every frame for as long as the title runs. | | `LEONIDA_CAPTURE_FRAMES` | see the code | | | | `leonida-gpu/capture.rs` | Frames listed in `LEONIDA_CAPTURE_FRAMES` (comma-separated): saved too, and their draws traced at debug level. | | `LEONIDA_CAPTURE_SHOWN` | see the code | | | yes | `leonida-gpu/host.rs` +1 | With `LEONIDA_CAPTURE=<folder>` and `LEONIDA_CAPTURE_SHOWN=1`, every buffer the native swap chain presents while a file named `rec` is in the folder is saved as `shown-<n>.png` (half size), and `shown-times.txt` gets a l... | @@ -203,7 +205,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_CUT_WAITS` | see the code | | | | `leonida-gpu/queue.rs` | `LEONIDA_CUT_WAITS=0` holds whole lists, as before. | | `LEONIDA_CUT_WRITES` | see the code | | | | `leonida-gpu/list.rs` | The title wrote a value at the bottom of the pipe (not a timestamp, not a query result): listed (diagnostics), and with `LEONIDA_CUT_WRITES=1` the host list is cut right behind it, so that the value is stored when the ca... | | `LEONIDA_D3D12_BACKGROUND` | see the code | | | yes | `leonida-gpu/host.rs` | `LEONIDA_D3D12_BACKGROUND=0`: the runtime's background work (the driver compiling shaders again on the "D3D Background Thread"s, for minutes after pipelines were made or loaded) is switched off. | -| `LEONIDA_D3D12_DEBUG` | off unless set and not `0` | | | | `leonida-gpu/host.rs` +7 | With `LEONIDA_D3D12_DEBUG` set (diagnostics builds): the debug layer's messages. | +| `LEONIDA_D3D12_DEBUG` | off unless set and not `0` | | | | `leonida-gpu/host.rs` +8 | With `LEONIDA_D3D12_DEBUG` set (diagnostics builds): the debug layer's messages. | | `LEONIDA_D3D12_GBV` | off unless set and not `0` | | | | `leonida-gpu/host.rs` | GPU-based validation (`LEONIDA_D3D12_GBV`): out-of-range descriptor heap indices and the like become messages naming the command instead of page faults. | | `LEONIDA_D3D12_WARP` | off unless set and not `0` | | | | `leonida-gpu/host.rs` +2 | A switch used to be on whenever its variable existed, so `LEONIDA_D3D12_WARP=0` (typed to switch it off, or left over from comparing two runs) still selected the software adapter. | | `LEONIDA_DECLARE_ONCE` | see the code | | | | `leonida-gpu/host.rs` | Declared once until the list next writes title memory (but with `LEONIDA_DECLARE_ONCE=0`): the dispatches of a frame declared the same ranges thousands of times, each a step of its own. | @@ -211,7 +213,6 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_DIRECT_WRITES` | see the code | | | | `leonida-gpu/host.rs` | `LEONIDA_DIRECT_WRITES=0` writes as before. | | `LEONIDA_DISPLAY_MODE` | see the code | | | | `leonida-gpu/dxgi.rs` | `LEONIDA_DISPLAY_MODE=WxH` if set (as a console reports the television it is plugged into: a Series X on a 1080p set lists a 1080p mode), else 3840x2160. shortcut: not yet the host display's own size by default; make it... | | `LEONIDA_DLSS_DEPTH_INVERTED` | see the code | | | | `leonida-gpu/dlss.rs` | ...`, `LEONIDA_DLSS_HDR=0\|1` (default: by the colour format), `LEONIDA_DLSS_DEPTH_INVERTED=0\|1` (default: by near > far), `LEONIDA_DLSS_SHARPNESS=<0..1>`.... | -| `LEONIDA_DLSS_DIR` | see the code | | yes | | `leonida-gpu/dlss.rs` +2 | ... `LEONIDA_DLSS_SDK`, and `nvngx_dlss.dll` is looked for in `LEONIDA_DLSS_DIR` (else beside the executable).... | | `LEONIDA_DLSS_HDR` | see the code | | | | `leonida-gpu/dlss.rs` | ...ion vectors the other way), `LEONIDA_DLSS_JITTER_SIGN=-1`, `LEONIDA_DLSS_HDR=0\|1` (default: by the colour format), `LEONIDA_DLSS_DEPTH_INVERTED=0\|1` (default: by near > far), `LEONIDA_DLSS_SHARPNESS=<0..1>`.... | | `LEONIDA_DLSS_JITTER_SIGN` | see the code | | | | `leonida-gpu/dlss.rs` | ... `LEONIDA_DLSS_MV_SIGN=-1` (motion vectors the other way), `LEONIDA_DLSS_JITTER_SIGN=-1`, `LEONIDA_DLSS_HDR=0\|1` (default: by the colour format), `LEONIDA_DLSS_DEPTH_INVERTED=0\|1` (default: by near > far), `LEONIDA_DLSS_... | | `LEONIDA_DLSS_MV_SIGN` | see the code | | | | `leonida-gpu/dlss.rs` | ..., which the render scale decides: `LEONIDA_RENDER_SCALE`), `LEONIDA_DLSS_MV_SIGN=-1` (motion vectors the other way), `LEONIDA_DLSS_JITTER_SIGN=-1`, `LEONIDA_DLSS_HDR=0\|1` (default: by the colour format), `LEONIDA_DLSS_DE... | @@ -249,7 +250,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_FAULT_BOOK` | see the code | | | | `leonida-gpu/faultbook.rs` | A book of the title's write faults on guarded view memory (`LEONIDA_FAULT_BOOK=<file>`; builds with diagnostics): which block, when in the frame, what it waited for, and what else happened to the block (taken by a refres... | | `LEONIDA_FAULT_BOOK_AT` | see the code | | | | `leonida-gpu/faultbook.rs` | ...efresh, asked about), for 40 frames from each of the times `LEONIDA_FAULT_BOOK_AT` gives (seconds after the start; 150,210,270 unless given).... | | `LEONIDA_FENCE_CHECK` | see the code | | | | `leonida-gpu/host.rs` | `LEONIDA_FENCE_CHECK=0`: goes on, as before. | -| `LEONIDA_FETCH_CHECK` | see the code | | yes | | `leonida-gpu/host/menu.rs` +3 | Pieces of card copies that came down while a later flight was writing them (`LEONIDA_FETCH_CHECK`, with `LEONIDA_RELAY_COPY`). | +| `LEONIDA_FETCH_CHECK` | see the code | | yes | yes | `leonida-gpu/host/menu.rs` +3 | Pieces of card copies that came down while a later flight was writing them (`LEONIDA_FETCH_CHECK`, with `LEONIDA_RELAY_COPY`). | | `LEONIDA_FG_GBUFFER` | see the code | | | yes | `leonida-gpu/fg.rs` +1 | Whether the G-buffer pass's depth and velocity targets are frame generation's inputs where no upscale hands any over (`LEONIDA_FG_GBUFFER=0`: not, as before). | | `LEONIDA_FG_HUDLESS` | see the code | | | | `leonida-gpu/fg.rs` | ...s `Present`. - [`before_target_draw`] (from `crate::draw`; `LEONIDA_FG_HUDLESS`, on, `0` off): the picture without the interface.... | | `LEONIDA_FG_LIMIT_FPS` | see the code | | yes | | `leonida-gpu/fg.rs` +1 | `LEONIDA_FG_LIMIT_FPS=<n>`: Reflex holds the frames **shown** to n a second (its frame limit, `frameLimitUs`), so that they come evenly; unset or 0: no limit, as before. | @@ -276,7 +277,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_GPU_TIMING` | off unless set and not `0` | | | yes | `leonida-gpu/copystat.rs` +1 | With `LEONIDA_GPU_TIMING`: a GPU timestamp before each noted command and at the end, and where they are read back. | | `LEONIDA_GPU_TIMING_KINDS` | see the code | | | | `leonida-gpu/copystat.rs` | (`LEONIDA_GPU_TIMING_KINDS=<n>`: so many of the heaviest are listed instead of forty.) | | `LEONIDA_GPU_TIMING_SLOW_MS` | see the code | | | | `leonida-gpu/host.rs` | From how many milliseconds a list of the timing run is logged as slow, with what its time is made of (`LEONIDA_GPU_TIMING_SLOW_MS`, 50). | -| `LEONIDA_GROUP_PACK` | see the code | | | yes | `leonida-gpu/draw.rs` +6 | `LEONIDA_GROUP_PACK=<K>`: the most console groups of 32 threads a host group runs (2, 4 or 8; 0, 1 or unset: one to a group, as the console does). | +| `LEONIDA_GROUP_PACK` | see the code | | | yes | `leonida-gpu/draw.rs` +7 | `LEONIDA_GROUP_PACK=<K>`: the most console groups of 32 threads a host group runs (2, 4 or 8; 0, 1 or unset: one to a group, as the console does). | | `LEONIDA_GUARD_ASK` | see the code | | | | `leonida-gpu/watch.rs` | `LEONIDA_GUARD_ASK=1` asks every time, as before. | | `LEONIDA_GUARD_HOLES` | see the code | | | | `leonida-gpu/watch.rs` | `LEONIDA_GUARD_HOLES=0` looks at the first address only, as before. | | `LEONIDA_GUARD_HOT` | see the code | yes | | | `leonida-gpu/watch.rs` | Also with the switch: - a block the title writes again soon after each time it was taken rests longer ([`hot_rest`]; `LEONIDA_GUARD_HOT=0`: 3 ms as before); - view memory is not asked of the kernel, which refuses it ([`V... | @@ -296,6 +297,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_HELD_RESCHEDULE` | on, `0` turns it off | yes | | | `leonida-gpu/descriptor/host.rs` | ...ken by [`TextureQueue::room`] before its own look was due (`LEONIDA_HELD_RESCHEDULE=0`: left in, as before).... | | `LEONIDA_HELPER_OWN` | see the code | | | | `leonida-gpu/shader_cache.rs` +1 | Whether a pixel shader's helper lane reads its own value where the console reads the first lane's (`lower.rs` `first_lane`); on unless `LEONIDA_HELPER_OWN=0`. | | `LEONIDA_HELPER_PRIORITY` | on, `0` turns it off | yes | | | `leonida-gpu/cores.rs` +5 | Whether the threads the submitting thread waits for run at its priority (`LEONIDA_HELPER_PRIORITY`, on unless `0`; `LEONIDA_AB` can flip it while the title runs): above normal, ahead of the title's threads and of the thr... | +| `LEONIDA_HOST_WAVE32` | see the code | | | | `leonida-gpu/draw.rs` +2 | `LEONIDA_HOST_WAVE32=1` (off by default): an AMD card with waves of 32 to 64 lanes is taken for one of 32 and gets the forms an NVIDIA card gets, to tell the two sets of forms apart on it. | | `LEONIDA_HURRY` | on, `0` turns it off | yes | | yes | `leonida-gpu/list/thin.rs` | Whether what the thread that prepares submissions stands at is translated first, and above normal priority while it is (`LEONIDA_HURRY`, on unless `0`: in turn, as before; `LEONIDA_AB` can flip it while the title runs). | | `LEONIDA_INDEX_HEAP_SPANS` | off unless set and not `0` | yes | yes | yes | `leonida-gpu/draw.rs` +1 | | | `LEONIDA_INDIRECT_BATCH_2` | see the code | yes | | | `leonida-gpu/draw.rs` | (`LEONIDA_AB=<s>,LEONIDA_INDIRECT_BATCH_2`, `..._3` or `..._4`: that setting while the switch is on, so that one run measures it against the setting in one scene.) | @@ -353,6 +355,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_LIST_FRONTS` | see the code | yes | | yes | `leonida-gpu/host.rs` | Whether a list's steps are gone through for what they refresh once, when the list is closed, by the thread that closes it (`LEONIDA_LIST_FRONTS=0`: by the thread that prepares the submission, for every submission, as bef... | | `LEONIDA_LIST_POOL` | see the code | | | | `leonida-gpu/list.rs` | Whether host lists that have run are used again (on by default; `LEONIDA_LIST_POOL=0`: each is made new and thrown away, as before). | | `LEONIDA_LIST_SLOTS` | see the code | | | | `leonida-gpu/draw.rs` | For the frame listing, after a draw whose shader `LEONIDA_LIST_SLOTS` names: the heap slots it will pick textures from by index, and what the title and the host hold there (one `~slot` line each), with the words they wer... | +| `LEONIDA_LIST_TWIN_MOVE` | off unless set and not `0` | yes | | | `leonida-gpu/descriptor/host.rs` +1 | Whether the raw twin of a view a list keeps is moved to where its view begins, as the one made beside the heaps is (`LEONIDA_LIST_TWIN_MOVE=1`; off by default: left where it was made, with a bias or null). | | `LEONIDA_LIST_VIEWS` | on, `0` turns it off | yes | | | `leonida-gpu/descriptor/host.rs` | Whether a list makes a view its tables hold once (`LEONIDA_LIST_VIEWS=0`: for every table). | | `LEONIDA_MAPPED_BY_PAGE` | see the code | | | | `leonida-gpu/texture.rs` | ... pass over the heap's views at 90-160 ms a frame (run 81). `LEONIDA_MAPPED_BY_PAGE=1`: by page.... | | `LEONIDA_MAPPED_BY_VIEWS` | see the code | | | | `leonida-gpu/texture.rs` | `LEONIDA_MAPPED_BY_VIEWS=0`: the host is asked, as before. | @@ -509,6 +512,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_TABLED_TEXTURES` | see the code | | | | `leonida-gpu/descriptor/host.rs` | `LEONIDA_TABLED_TEXTURES=1` keeps them in it as before. | | `LEONIDA_TABLES_EARLY` | on, `0` turns it off | yes | | | `leonida-gpu/host.rs` | `LEONIDA_TABLES_EARLY=0`: at the end of the landing, as before. | | `LEONIDA_TAKE_PARTS` | on, `0` turns it off | yes | | | `leonida-gpu/watch.rs` | Of a page taken before, the parts written since, where they are known (`LEONIDA_TAKE_PARTS=0`: the page). | +| `LEONIDA_TARGET_BARRIERS` | see the code | yes | | | `leonida-gpu/list/groups.rs` | `LEONIDA_TARGET_BARRIERS=3` does to the host's textures what the title's barriers and syncs behind draws into targets ask (1: named textures moved to their read state, 2: waits for what was drawn; off by default). | | `LEONIDA_TARGET_VARIANTS` | see the code | | | | `leonida-gpu/pipeline/make.rs` | Whether a draw into views of other formats than its pipeline declares gets a host pipeline for those formats ([`for_formats`]); on unless `LEONIDA_TARGET_VARIANTS=0`. | | `LEONIDA_TEARING` | off unless set and not `0` | | | | `leonida-gpu/host.rs` | `LEONIDA_TEARING=1`, where the system has it; off by default (unset or `0`: presents wait for the refresh, as before). | | `LEONIDA_TELL_EARLY` | see the code | yes | | | `leonida-gpu/host.rs` | ...at their shaders wrote is back in title memory, not after (`LEONIDA_TELL_EARLY=1`, or by turns with `LEONIDA_AB=<s>,LEONIDA_TELL_EARLY`; off by default).... | @@ -535,7 +539,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_TEXTURE_STAGE_MB` | see the code | | | | `leonida-gpu/draw.rs` | `LEONIDA_TEXTURE_STAGE_MB` sets it: a backlog of tens of thousands of textures (a scene's first minutes) then drains in fewer frames. | | `LEONIDA_TEXTURE_STAGE_MS` | see the code | | | | `leonida-gpu/draw.rs` | | | `LEONIDA_TEXTURE_SWEEP` | see the code | | | | `leonida-gpu/resource.rs` | `LEONIDA_TEXTURE_SWEEP=0` lets nothing go. | -| `LEONIDA_THIN` | see the code | | yes | yes | `leonida-gpu/draw.rs` +7 | List calls that only write down their arguments (`LEONIDA_THIN=1`); what they mean is worked out by threads of ours, beside the title's. | +| `LEONIDA_THIN` | see the code | | yes | yes | `leonida-gpu/draw.rs` +8 | List calls that only write down their arguments (`LEONIDA_THIN=1`); what they mean is worked out by threads of ours, beside the title's. | | `LEONIDA_THIN_PARK` | off unless set and not `0` | yes | | yes | `leonida-gpu/list/thin.rs` +1 | Whether thread `i` of the `threads` that translate takes no work now: with `LEONIDA_THIN_PARK` (off unless asked for; by turns under A/B) the last `LEONIDA_THIN_PARK_N` (2) of them sleep, so that one run measures fewer t... | | `LEONIDA_THIN_PARK_N` | see the code | | | | `leonida-gpu/list/thin.rs` | ..._PARK` (off unless asked for; by turns under A/B) the last `LEONIDA_THIN_PARK_N` (2) of them sleep, so that one run measures fewer threads against all of them.... | | `LEONIDA_THIN_THREADS` | see the code | | yes | yes | `leonida-gpu/list/thin.rs` +1 | | @@ -621,7 +625,6 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_KBM` | see the code | | | | `leonida-hle/modules/gameinput.rs` +1 | `LEONIDA_KBM=classic` brings back the single table of before ([`super::fallback`]); `LEONIDA_KBM_DRIVE=on\|off\|auto` forces the driving table on or off (a test), `auto` being the default; `LEONIDA_KBM_SETTLE_MS` (400; 0..... | | `LEONIDA_KBM_DRIVE` | see the code | | | | `leonida-hle/modules/gameinput.rs` +1 | `LEONIDA_KBM_DRIVE=on\|off\|auto` forces the driving table on or off (a test), `auto` being the default; `LEONIDA_KBM_SETTLE_MS` (400; 0..3000) is the pause after a change. | | `LEONIDA_KBM_SETTLE_MS` | see the code | | | | `leonida-hle/modules/gameinput/kbm.rs` | `LEONIDA_KBM_SETTLE_MS` (400; 0..3000) is the pause after a change. | -| `LEONIDA_KEYS` | see the code | | | | `leonida-hle/modules/gameinput.rs` +1 | The scripted keys (`LEONIDA_KEYS`) also press the first pad's buttons, by the stand-in pad's table: with a real pad connected the stand-in is not there, and a title that listens to the pad (the title's start screen) saw... | | `LEONIDA_MAP_LEAN` | see the code | | | | `leonida-hle/modules/xmem.rs` | Whether a mapping change asks the host only for what it needs: no split of a placeholder that is already the view's own, no commit of section pages that are committed (`LEONIDA_MAP_LEAN=0`: both every time, as before). | | `LEONIDA_MOUSE_CURVE` | see the code | | | | `leonida-hle/modules/gameinput.rs` | | | `LEONIDA_MOUSE_DEADZONE` | see the code | | | | `leonida-hle/modules/gameinput.rs` | | @@ -683,7 +686,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_LOOPS_WAVE` | see the code | | | yes | `leonida-shader/emit/lower.rs` +4 | `LEONIDA_LOOPS_WAVE`: - unset or `1`: console wave64 compute programs on a host of 32-lane waves; - `0`: none; - `2`: every compute program. | | `LEONIDA_LSHL_ADD_SCC` | see the code | | | | `leonida-shader/emit/lower.rs` | `LEONIDA_LSHL_ADD_SCC=0` restores the old lowering. | | `LEONIDA_MED3_CLAMP` | see the code | | | yes | `leonida-shader/emit/lower.rs` | Whether the median of a value and two constants that are normal numbers or infinities is a clamp (`Lower::med3_clamp`; `LEONIDA_MED3_CLAMP=0`: the general form, as before): the same bits, with fewer instructions (bounds... | -| `LEONIDA_MESH_COUNTS` | see the code | | | yes | `leonida-shader/emit/lower.rs` +1 | A mesh program's own output counts (`LEONIDA_MESH_COUNTS=1`; off by default). | +| `LEONIDA_MESH_COUNTS` | see the code | | | yes | `leonida-shader/emit/lower.rs` +2 | A mesh program's own output counts (`LEONIDA_MESH_COUNTS=1`; off by default). | | `LEONIDA_MESH_LOOP_EXITS` | see the code | | | yes | `leonida-shader/emit/lower.rs` | `LEONIDA_MESH_LOOP_EXITS`, on unless `0` (then a lane at the limit leaves the program from inside the loop, [`Lower::abort_block`], as before). | | `LEONIDA_MINMAX_NONZERO` | see the code | | | yes | `leonida-shader/emit/lower.rs` | Whether a float maximum or minimum with a constant whose magnitude bits are not all zero leaves out the test for two zeros (`Lower::max_min`; `LEONIDA_MINMAX_NONZERO=0`: as before). | | `LEONIDA_NAN_EXACT` | see the code | | | yes | `leonida-shader/emit/lower.rs` +1 | Whether a float compare and the program's other NaN tests tell a NaN by its bits (`\|x\| > the bits of infinity`, [`Lower::is_nan_f32`]) instead of an unordered `fcmp` (on; `LEONIDA_NAN_EXACT=0`: as before). | @@ -693,8 +696,8 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_SCALAR_MINMAX_SCC` | see the code | | | | `leonida-shader/emit/lower.rs` | `LEONIDA_SCALAR_MINMAX_SCC=0` restores the old lowering. | | `LEONIDA_SHADER_LOOP_LIMIT` | see the code | | | | `leonida-shader/emit/mod.rs` | With the `diagnostics` feature, `LEONIDA_SHADER_LOOP_LIMIT` (decimal or `0x` hex, at least 1) sets it instead. | | `LEONIDA_SHADER_OPT` | see the code | | | yes | `leonida-shader/emit/bitcode/opt.rs` +2 | `LEONIDA_SHADER_OPT`: - unset: every pass but the wide loads (447). - `0`: none (the module as the lowering made it). - a number (decimal or `0x` hex): those passes; 1 dead code, 2 constants and identities, 4 one instruc... | -| `LEONIDA_SHADER_SOURCE_HASH` | see the code | | | | `leonida-shader/emit/mod.rs` | | -| `LEONIDA_SHADER_SWITCHES` | see the code | | | | `leonida-shader/emit/mesh_counts.rs` +2 | | +| `LEONIDA_SHADER_SOURCE_HASH` | see the code | | | | `leonida-shader/emit/mod.rs` +1 | | +| `LEONIDA_SHADER_SWITCHES` | see the code | | | | `leonida-shader/emit/mesh_counts.rs` +3 | | | `LEONIDA_WARP` | see the code | | | | `leonida-shader/emit/diff_tests.rs` +1 | Set `LEONIDA_WARP=1` to draw on WARP. | | `LEONIDA_WAVE_WHY` | see the code | | | yes | `leonida-shader/emit/lds_flags.rs` +2 | `LEONIDA_WAVE_WHY=1`: why a program keeps 64-lane waves (one line per reason) | | `LEONIDA_WAVE_WIDE_LAST` | see the code | | | yes | `leonida-shader/emit/mod.rs` | `LEONIDA_WAVE_WIDE_LAST=all` takes every group [`widen`] does, `0` none; `LEONIDA_WAVE_WIDE=0` turns the form off everywhere. | @@ -710,7 +713,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. ## Only in tests -Read by test code alone, or made up by it: `LEONIDA_A`, `LEONIDA_B`, `LEONIDA_BCPACK_CASES`, `LEONIDA_BCPACK_TABLES`, `LEONIDA_BENCH_CS`, `LEONIDA_BENCH_EXPECT_HEAP_SWEEP`, `LEONIDA_BENCH_FILE`, `LEONIDA_BENCH_HOLES`, `LEONIDA_BENCH_N`, `LEONIDA_BENCH_S`, `LEONIDA_BENCH_THREADS`, `LEONIDA_BENCH_WARP`, `LEONIDA_BLOCK_WAY`, `LEONIDA_CONSOLE_DXC`, `LEONIDA_DIFF_ONLY`, `LEONIDA_EXIT_CHILD`, `LEONIDA_HOST_LOCK_CHILD`, `LEONIDA_MENU_PREVIEW`, `LEONIDA_NONE_SUCH`, `LEONIDA_PC_DXC`, `LEONIDA_PLACES_DIR`, `LEONIDA_PLACES_RUN`, `LEONIDA_PROBE`, `LEONIDA_PROBE_STREAMLINE`, `LEONIDA_REF_PS`, `LEONIDA_REF_VS`, `LEONIDA_SAVE_CHILD`, `LEONIDA_SAVE_OP`, `LEONIDA_SAVE_STOP`, `LEONIDA_TEST_D3D_DEBUG`, `LEONIDA_TEST_ROUNDS`, `LEONIDA_TILES_TEST_CARD`, `LEONIDA_TRAP_LOG`, `LEONIDA_XMA_REFERENCE`, `LEONIDA_XMA_STREAMS`. +Read by test code alone, or made up by it: `LEONIDA_A`, `LEONIDA_B`, `LEONIDA_BCPACK_CASES`, `LEONIDA_BCPACK_TABLES`, `LEONIDA_BENCH_CS`, `LEONIDA_BENCH_EXPECT_HEAP_SWEEP`, `LEONIDA_BENCH_FILE`, `LEONIDA_BENCH_HOLES`, `LEONIDA_BENCH_N`, `LEONIDA_BENCH_S`, `LEONIDA_BENCH_THREADS`, `LEONIDA_BENCH_WARP`, `LEONIDA_BLOCK_WAY`, `LEONIDA_CONSOLE_DXC`, `LEONIDA_DIFF_ONLY`, `LEONIDA_EXIT_CHILD`, `LEONIDA_HOST_LOCK_CHILD`, `LEONIDA_LONG`, `LEONIDA_MENU_PREVIEW`, `LEONIDA_NONE_SUCH`, `LEONIDA_PC_DXC`, `LEONIDA_PLACES_DIR`, `LEONIDA_PLACES_RUN`, `LEONIDA_PROBE`, `LEONIDA_PROBE_STREAMLINE`, `LEONIDA_REF_PS`, `LEONIDA_REF_VS`, `LEONIDA_SAVE_CHILD`, `LEONIDA_SAVE_OP`, `LEONIDA_SAVE_STOP`, `LEONIDA_TEST_D3D_DEBUG`, `LEONIDA_TEST_FOLDER`, `LEONIDA_TEST_KEYS`, `LEONIDA_TEST_ROUNDS`, `LEONIDA_TILES_TEST_CARD`, `LEONIDA_TRAP_LOG`, `LEONIDA_XMA_REFERENCE`, `LEONIDA_XMA_STREAMS`. ## Only in comments From 6f7d5910cb95fe6f3956cbfddac24197a859f3f1 Mon Sep 17 00:00:00 2001 From: Zack Date: Mon, 30 Nov 2026 22:31:33 -0800 Subject: [PATCH 5/5] d3d12: cache one_subresource per texture, split target-barrier move counter, and test LIST_SLOTS Refs #2771 Refs #2770 AI-assisted: yes --- .../src/descriptor/host/listed_raw_tests.rs | 69 +++++++++++++++++++ d3d12/crates/leonida-gpu/src/draw.rs | 11 +-- d3d12/crates/leonida-gpu/src/list.rs | 66 ++++++++++++++---- d3d12/crates/leonida-gpu/src/list/groups.rs | 14 ++++ 4 files changed, 141 insertions(+), 19 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/descriptor/host/listed_raw_tests.rs b/d3d12/crates/leonida-gpu/src/descriptor/host/listed_raw_tests.rs index 5e5b3ab17c..5e7044d354 100644 --- a/d3d12/crates/leonida-gpu/src/descriptor/host/listed_raw_tests.rs +++ b/d3d12/crates/leonida-gpu/src/descriptor/host/listed_raw_tests.rs @@ -548,3 +548,72 @@ fn a_twin_in_a_lists_own_slot_is_moved_to_its_view() { } LIST_SLOTS.set(was); } + +/// Calling [`HostHeap::make_listed`] on a fresh thread populates [`LIST_SLOTS`] with that +/// thread's real [`ListViews`] descriptor range, and [`own_slot`] recognizes every slot inside +/// that range (and rejects handles outside it) when `LEONIDA_LIST_TWIN_MOVE=1`. +#[test] +fn make_listed_populates_thread_list_slots_for_own_slot() { + let Some(host) = host() else { + return; // no host D3D12 device + }; + std::thread::spawn(move || { + assert_eq!(LIST_SLOTS.get(), (0, 0), "fresh thread starts with empty LIST_SLOTS"); + let heap = HostHeap::new(false, 4).expect("host view heap"); + let first = heap.dynamic(2).expect("dynamic slots"); + const SIZE: u64 = 4096; + let title = Box::new([0u32; SIZE as usize / 4]); + let address = title.as_ptr() as u64; + struct Registration(u64); + impl Drop for Registration { + fn drop(&mut self) { + crate::shadow::unregister(self.0 as usize, self.0); + } + } + crate::shadow::register(address as usize, address, SIZE); + let _registered = Registration(address); + let _source = crate::shadow::find(address, SIZE).expect("registered buffer shadow"); + let _ = &host.device; + + let resource = [1, 0, 0, 0, SIZE as u32, 0, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0]; + let mut desc = [0u32; 16]; + desc[..10].copy_from_slice(&[42, 1, 5768, 0, 6, 0, 2, 0, 0, 0]); + (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); + let mut rec = [0u32; 8]; + crate::descriptor::record(rec.as_mut_ptr() as u64, View::Placed(false, resource, desc)); + assert!( + heap.make_listed(1, [rec[0], rec[1], rec[2]], first).is_some(), + "make_listed must succeed on a real placed buffer view" + ); + flush_listed(); + + let (from, to) = LIST_SLOTS.get(); + let expected = LIST_VIEWS.with(|views| { + let views = views.borrow(); + let v = views.as_ref().expect("LIST_VIEWS initialized by make_listed"); + (v.start, v.start + ListViews::SLOTS as usize * v.step, v.step) + }); + assert_ne!(from, 0); + assert_eq!((from, to), (expected.0, expected.1)); + let step = expected.2; + + { + let _off = TwinMove::set(false); + assert_eq!(own_slot(D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from }), None); + assert_eq!(own_slot(D3D12_CPU_DESCRIPTOR_HANDLE { ptr: to - step }), None); + } + { + let _on = TwinMove::set(true); + assert_eq!(own_slot(D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from }), Some(true)); + assert_eq!(own_slot(D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from + step }), Some(true)); + assert_eq!(own_slot(D3D12_CPU_DESCRIPTOR_HANDLE { ptr: to - step }), Some(true)); + assert_eq!(own_slot(D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from.wrapping_sub(step) }), None); + assert_eq!(own_slot(D3D12_CPU_DESCRIPTOR_HANDLE { ptr: to }), None); + if let Some(staging) = staged(false, 1) { + assert_eq!(own_slot(staging), Some(false)); + } + } + }) + .join() + .expect("LIST_SLOTS worker thread"); +} diff --git a/d3d12/crates/leonida-gpu/src/draw.rs b/d3d12/crates/leonida-gpu/src/draw.rs index 88a0f7ba4e..6b2e990b1d 100644 --- a/d3d12/crates/leonida-gpu/src/draw.rs +++ b/d3d12/crates/leonida-gpu/src/draw.rs @@ -1041,12 +1041,13 @@ pub(crate) fn waits_line(frames: f64) { u8::from(barrier_merge()) ); } - let [all, left_out, named] = [0, 1, 2].map(|i| TARGET_WAITS[i].swap(0, Ordering::Relaxed) as f64 / frames); + let [all, left_out, named, inline] = + [0, 1, 2, 3].map(|i| TARGET_WAITS[i].swap(0, Ordering::Relaxed) as f64 / frames); if all + left_out + named > 0.0 { tracing::info!( "the title's waits for what was drawn into targets per frame (LEONIDA_TARGET_BARRIERS; without it \ none): {all:.0} recorded for every target, {left_out:.0} left out with nothing drawn since the last; \ - {named:.0} textures its barriers left to be read (each moved to that state unless it was in it)" + {named:.0} host textures named for reading ({inline:.0} transitioned in the list, the rest at submission or already in state)" ); } if let Some([card, taken]) = leonida_shader::emit::host_wave32() { @@ -1070,9 +1071,9 @@ pub(crate) fn waits_line(frames: f64) { /// Since the last frame-rate line: the title's waits for what was drawn into targets /// (`crate::list::groups`) that were recorded for every target, those left out -/// ([`State::wait_for_targets`]), and the textures its barriers left to be read (each asked -/// to be in its read state: a move unless it was there). -pub(crate) static TARGET_WAITS: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; +/// ([`State::wait_for_targets`]), the host textures its barriers named for reading, and +/// those of them that recorded an in-list transition barrier (`ensure_state_moved`). +pub(crate) static TARGET_WAITS: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; /// Since the last frame-rate line: the title's direct dispatches recorded, by the groups each /// runs (none, 1, up to 16, up to 256, up to 4,096, more), and those of them whose program can diff --git a/d3d12/crates/leonida-gpu/src/list.rs b/d3d12/crates/leonida-gpu/src/list.rs index df3cba1252..19472f3e94 100644 --- a/d3d12/crates/leonida-gpu/src/list.rs +++ b/d3d12/crates/leonida-gpu/src/list.rs @@ -1194,13 +1194,22 @@ pub fn upscale_inputs(textures: &[*const std::ffi::c_void]) -> Vec { /// Moves a title texture's host copy to `state` in the list, if needed. #[cfg(windows)] pub(crate) fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) { + let _ = ensure_state_moved(list, resource, state); +} + +/// As [`ensure_state`], telling whether the texture was already tracked in a +/// different state by `list` and recorded an in-list transition barrier here. +#[cfg(windows)] +fn ensure_state_moved(list: &crate::host::HostList, resource: This, state: u32) -> bool { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State; if let Some((texture, before)) = list.transition(resource, state) { let state = crate::host::legal_state(texture, state); let barrier = crate::host::transition(texture, State(before as i32), State(state as i32)); // SAFETY: an open list and a live texture. unsafe { list.list.ResourceBarrier(&[barrier]) }; + return true; } + false } #[cfg(windows)] @@ -2806,11 +2815,14 @@ pub(super) fn barrier_groups_words(this: This, w: &[u64]) { let copy = if crate::resource::is_resource(resource) { crate::resource::made_copy(resource) } else { None }; let host = crate::host::host(); let whole = copy.is_some_and(|copy| { - state & groups::PART == 0 || host.is_some_and(|host| one_subresource(host, ©.texture)) + state & groups::PART == 0 || host.is_some_and(|host| one_subresource(host, ©)) }); if whole { - ensure_state(list, resource, state & !(groups::DRAWN | groups::PART)); + let moved = ensure_state_moved(list, resource, state & !(groups::DRAWN | groups::PART)); crate::draw::TARGET_WAITS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if moved { + crate::draw::TARGET_WAITS[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } } else { // (Nothing of that name to move, be it that the host has made no texture // for it: what was drawn into it is waited for.) @@ -2821,28 +2833,54 @@ pub(super) fn barrier_groups_words(this: This, w: &[u64]) { } } +#[cfg(all(windows, test))] +thread_local! { + /// Device queries made by [`one_subresource`] on this thread (for cache tests). + pub(super) static ONE_SUBRESOURCE_QUERIES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Whether a host texture is one subresource (one level, one slice, one /// plane, as the card counts its format's): a barrier on a part of it is -/// then on all of it. +/// then on all of it. Cached per [`crate::resource::HostTexture::serial`] so +/// repeated partial barriers do not query the driver again. #[cfg(windows)] -fn one_subresource(host: &crate::host::Host, texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource) -> bool { +fn one_subresource(host: &crate::host::Host, copy: &crate::resource::HostTexture) -> bool { + use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; use windows::Win32::Graphics::Direct3D12::{ D3D12_FEATURE_DATA_FORMAT_INFO, D3D12_FEATURE_FORMAT_INFO, D3D12_RESOURCE_DIMENSION_TEXTURE3D, }; + const SLOTS: usize = 4096; + static CACHE: [AtomicU64; SLOTS] = [const { AtomicU64::new(0) }; SLOTS]; + + let serial = copy.serial; + let slot = (serial as usize).wrapping_mul(0x9E37_79B1) & (SLOTS - 1); + if serial > 0 && serial < (1u64 << 62) { + let entry = CACHE[slot].load(Relaxed); + if (entry >> 2) == serial && (entry & 3) != 0 { + return (entry & 3) == 2; + } + } + #[cfg(test)] + ONE_SUBRESOURCE_QUERIES.with(|q| q.set(q.get() + 1)); // SAFETY: a plain query. - let desc = unsafe { texture.GetDesc() }; + let desc = unsafe { copy.texture.GetDesc() }; // (A volume's levels are one slice each.) let slices = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { desc.DepthOrArraySize }; - if desc.MipLevels != 1 || slices != 1 { - return false; - } - // (Depth with stencil is two planes. Not said: not taken for one.) - let mut info = D3D12_FEATURE_DATA_FORMAT_INFO { Format: desc.Format, PlaneCount: 0 }; - // SAFETY: a plain query that fills our structure. - let said = unsafe { - host.device.CheckFeatureSupport(D3D12_FEATURE_FORMAT_INFO, (&raw mut info).cast(), size_of_val(&info) as u32) + let one = if desc.MipLevels != 1 || slices != 1 { + false + } else { + // (Depth with stencil is two planes. Not said: not taken for one.) + let mut info = D3D12_FEATURE_DATA_FORMAT_INFO { Format: desc.Format, PlaneCount: 0 }; + // SAFETY: a plain query that fills our structure. + let said = unsafe { + host.device.CheckFeatureSupport(D3D12_FEATURE_FORMAT_INFO, (&raw mut info).cast(), size_of_val(&info) as u32) + }; + said.is_ok() && info.PlaneCount == 1 }; - said.is_ok() && info.PlaneCount == 1 + if serial > 0 && serial < (1u64 << 62) { + CACHE[slot].store((serial << 2) | (1 + u64::from(one)), Relaxed); + } + one } /// The bottom-of-pipe value writes `(address, value, flush, flags)`, 32 and diff --git a/d3d12/crates/leonida-gpu/src/list/groups.rs b/d3d12/crates/leonida-gpu/src/list/groups.rs index f0b59bbe51..43ce87b17c 100644 --- a/d3d12/crates/leonida-gpu/src/list/groups.rs +++ b/d3d12/crates/leonida-gpu/src/list/groups.rs @@ -905,17 +905,31 @@ pub(super) mod tests { let depth_read = b(SYNC_DEPTH, SYNC_DEPTH | SYNC_ALL_SHADING, DEPTH_WRITE, SHADER_RESOURCE | DEPTH_READ); let depth_read = texture(depth_read, [DEPTH_LAYOUT, DEPTH_READ_LAYOUT], stencil); let waits = TEST_WAITS.get(); + let queries_before = crate::list::ONE_SUBRESOURCE_QUERIES.with(std::cell::Cell::get); // The first level, slice and plane of each. for mut part in [drawn(single), depth_read, drawn(chain)] { (part.first_level, part._range) = (0, [1, 0, 1, 0, 1]); call(title.1, &one(part)); } + let queries_first = crate::list::ONE_SUBRESOURCE_QUERIES.with(std::cell::Cell::get); + assert_eq!(queries_first - queries_before, 3, "each host texture queried at most once"); let recorded = TEST_WAITS.get(); // (One wait for what was drawn: nothing was, between the two that ask for it.) assert_eq!([recorded[0] - waits[0], recorded[1] - waits[1]], [1, 2], "the one moved, the others waited for"); assert_eq!(left(host_list, single, TARGET), Some(HOST_SHADER_RESOURCE)); assert_eq!(left(host_list, chain, TARGET), None, "still a target"); assert_eq!(left(host_list, stencil, DEPTH_TARGET), None, "still a target"); + // Repeated partial barriers hit the per-texture cache without querying the device again. + for mut part in [drawn(single), depth_read, drawn(chain)] { + (part.first_level, part._range) = (0, [1, 0, 1, 0, 1]); + call(title.1, &one(part)); + } + assert_eq!( + crate::list::ONE_SUBRESOURCE_QUERIES.with(std::cell::Cell::get), + queries_first, + "second partial-barrier pass must hit the per-texture cache" + ); + assert_eq!(left(host_list, single, TARGET), Some(HOST_SHADER_RESOURCE)); // All of it: a move. call(title.1, &one(depth_read)); assert_eq!(left(host_list, stencil, DEPTH_TARGET), Some(HOST_DEPTH_READ | HOST_SHADER_RESOURCE));