Publish the pareto-residency Windows build and portable launcher
This commit is contained in:
1 parent
efeef1d65b
commit
545f89019e
20 files changed
+1671
-217
No files matched your search
@@ -426,6 +426,48 @@ fn neutral_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<ID3D12Res
|
||||
|
||||
static FLIPS: Mutex<Vec<Flip>> = Mutex::new(Vec::new());
|
||||
|
||||
/// Deferred slot flips recorded into an open or not-yet-submitted command
|
||||
/// list (`HostHeap::flip`), tracked so a one-shot decoration bake draw can
|
||||
/// promote them out of the `neutral()` gray stand-in before sampling them.
|
||||
pub(crate) struct PendingListFlip {
|
||||
id: u64,
|
||||
pub(crate) origin: (usize, u64),
|
||||
flip: Flip,
|
||||
}
|
||||
|
||||
impl PendingListFlip {
|
||||
pub(crate) fn index(&self) -> u32 {
|
||||
self.flip.index
|
||||
}
|
||||
|
||||
pub(crate) fn handle(&self) -> u64 {
|
||||
self.flip.handle
|
||||
}
|
||||
|
||||
pub(crate) fn key(&self) -> u64 {
|
||||
self.flip.key
|
||||
}
|
||||
}
|
||||
|
||||
static NEXT_PENDING_FLIP: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
static PENDING_LIST_FLIPS: Mutex<Vec<PendingListFlip>> = Mutex::new(Vec::new());
|
||||
static PENDING_LIST_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
|
||||
fn take_pending_list_flip(id: u64) -> Option<Flip> {
|
||||
if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let pos = pending.iter().position(|p| p.id == id)?;
|
||||
let entry = pending.swap_remove(pos);
|
||||
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
|
||||
Some(entry.flip)
|
||||
}
|
||||
|
||||
fn remove_pending_list_flip(id: u64) {
|
||||
let _ = take_pending_list_flip(id);
|
||||
}
|
||||
|
||||
/// Makes the slots whose new texture's upload has run
|
||||
/// ([`HostHeap::texture_slots_flip`]); on any thread. Not if the heap is at
|
||||
/// something else: the next texture pass does.
|
||||
@@ -714,6 +756,12 @@ impl Spans {
|
||||
/// pass last took the ranges ([`page_written`]). Kept apart from
|
||||
/// [`REMAPPED`] so that what such writes do is counted by itself.
|
||||
static PAGE_WRITTEN: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
|
||||
/// Physical-page writes retained specifically for one-shot decoration/ped
|
||||
/// texture bakes when `VICTORY_PAGE_WRITES` bit 2 is off (the default): normal
|
||||
/// frames stay free of queue flooding while every bake still sees freshly
|
||||
/// DirectStorage-streamed texture bytes immediately instead of waiting on
|
||||
/// `RECHECK_FRAMES`.
|
||||
static BAKE_PAGE_WRITTEN: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
|
||||
|
||||
/// Since the start: such ranges kept for a pass; ranges dropped because no
|
||||
/// pass took them; slots of placed textures that held bytes of them when a
|
||||
@@ -1105,29 +1153,46 @@ pub(crate) fn device_removed() -> Option<String> {
|
||||
pub(crate) static PLACED_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
pub(crate) static OBJECT_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
/// Bytes per element of a buffer view, as the console's descriptor holds
|
||||
/// them for indexed reads (structured: the stride; raw: 1, the index is the
|
||||
/// byte; typed: the format's); `None` if `view` is not a buffer view.
|
||||
fn view_stride(view: &View) -> Option<u32> {
|
||||
let (stride, raw, format) = view_elements(view)?;
|
||||
Some(if stride > 0 {
|
||||
/// Bytes per element and typed integer format bits of a buffer view, decoded
|
||||
/// in a single pass over the view descriptor; `(None, 0)` if not a buffer view.
|
||||
fn view_stride_and_kind(view: &View) -> (Option<u32>, u32) {
|
||||
use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED};
|
||||
let Some((stride, raw, format)) = view_elements(view) else {
|
||||
return (None, 0);
|
||||
};
|
||||
let bytes = if stride > 0 {
|
||||
stride
|
||||
} else if raw {
|
||||
1
|
||||
} else {
|
||||
crate::resource::element(format).map_or(0, |(bytes, _)| bytes as u32)
|
||||
})
|
||||
};
|
||||
let kind = if stride == 0 && !raw {
|
||||
match format {
|
||||
3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62 => VIEW_INTEGER,
|
||||
4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64 => VIEW_INTEGER | VIEW_SIGNED,
|
||||
_ => 0,
|
||||
}
|
||||
} else {
|
||||
0
|
||||
};
|
||||
(Some(bytes), kind)
|
||||
}
|
||||
|
||||
/// What else the table of strides says of a typed buffer view of an integer
|
||||
/// format (`victory_shader::emit::VIEW_INTEGER`); 0 for any other view.
|
||||
/// Packed [`victory_shader::emit::SLOT_STRIDES`] word for `view`.
|
||||
fn view_stride_word(view: &View) -> u32 {
|
||||
let (stride, kind) = view_stride_and_kind(view);
|
||||
stride.unwrap_or(0) | kind
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn view_stride(view: &View) -> Option<u32> {
|
||||
view_stride_and_kind(view).0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn view_kind(view: &View) -> u32 {
|
||||
use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED};
|
||||
match view_elements(view) {
|
||||
Some((0, false, 3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62)) => VIEW_INTEGER,
|
||||
Some((0, false, 4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64)) => VIEW_INTEGER | VIEW_SIGNED,
|
||||
_ => 0,
|
||||
}
|
||||
view_stride_and_kind(view).1
|
||||
}
|
||||
|
||||
/// A buffer view's structure stride, whether it is raw, and its format;
|
||||
@@ -1740,7 +1805,7 @@ impl HostHeap {
|
||||
pub(crate) fn texture_news(&self) -> (u64, bool) {
|
||||
let writes = self.textures.lock().unwrap_or_else(|e| e.into_inner()).writes;
|
||||
let noted = |ranges: &Mutex<Vec<(u64, u64)>>| !ranges.lock().unwrap_or_else(|e| e.into_inner()).is_empty();
|
||||
(writes, noted(&REMAPPED) || noted(&PAGE_WRITTEN))
|
||||
(writes, noted(&REMAPPED) || noted(&PAGE_WRITTEN) || noted(&BAKE_PAGE_WRITTEN))
|
||||
}
|
||||
|
||||
/// Every title slot of the queue that is due at `frame`, and whether
|
||||
@@ -1888,7 +1953,48 @@ impl HostHeap {
|
||||
if ranges.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
self.slots_written_under(&ranges, frame, crate::watch::page_writes() & 2 != 0)[2]
|
||||
let due = crate::watch::page_writes() & 2 != 0;
|
||||
let made_due = self.slots_written_under(&ranges, frame, due)[2];
|
||||
if !due {
|
||||
let mut kept = BAKE_PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
|
||||
kept.extend(ranges);
|
||||
if kept.len() > 256 {
|
||||
join(&mut kept);
|
||||
const MOST: usize = 1 << 14;
|
||||
if kept.len() > MOST {
|
||||
let drop_n = kept.len() - MOST;
|
||||
kept.drain(..drop_n);
|
||||
}
|
||||
}
|
||||
}
|
||||
made_due
|
||||
}
|
||||
|
||||
/// Wakes uploaded placed-texture slots touched by recent physical-page
|
||||
/// writes (DirectStorage completions) immediately (`due = frame`) right
|
||||
/// before a one-shot ped/decoration bake draw.
|
||||
pub(crate) fn texture_slots_bake_written(&self, frame: u64) -> usize {
|
||||
let mut ranges = std::mem::take(&mut *BAKE_PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
if ranges.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
join(&mut ranges);
|
||||
let mut slots: Vec<u32> = {
|
||||
let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
|
||||
ranges.iter().flat_map(|&(start, end)| placed.slots_holding(start, end)).collect()
|
||||
};
|
||||
if slots.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
slots.sort_unstable();
|
||||
slots.dedup();
|
||||
slots.retain(|&slot| !self.tabled_lately(slot, frame));
|
||||
let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
|
||||
slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0));
|
||||
for &slot in &slots {
|
||||
textures.changed(slot, frame, frame);
|
||||
}
|
||||
slots.len()
|
||||
}
|
||||
|
||||
/// [`HostHeap::texture_slots_page_written`] for `ranges` (start, end):
|
||||
@@ -2183,6 +2289,7 @@ impl HostHeap {
|
||||
/// reads the table's dynamic slots).
|
||||
pub(crate) fn mirror_after(&self, list: &crate::host::HostList, index: u32, handle: u64) {
|
||||
if show_after()
|
||||
&& !crate::texture::BAKING.get()
|
||||
&& index < self.count
|
||||
&& !self.texture_slot_made_from(index, handle)
|
||||
&& let Some(view) = super::view(handle)
|
||||
@@ -2197,14 +2304,143 @@ impl HostHeap {
|
||||
}
|
||||
|
||||
fn flip(&self, list: &crate::host::HostList, index: u32, handle: u64, late: Option<u64>) {
|
||||
use std::sync::atomic::Ordering::{Relaxed, Release};
|
||||
let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle));
|
||||
let id = NEXT_PENDING_FLIP.fetch_add(1, Relaxed);
|
||||
let origin = (std::ptr::from_ref(list) as usize, list.epoch());
|
||||
{
|
||||
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
pending.push(PendingListFlip {
|
||||
id,
|
||||
origin,
|
||||
flip: Flip { after: 0, heap, index, handle, key, late },
|
||||
});
|
||||
PENDING_LIST_COUNT.store(pending.len(), Release);
|
||||
}
|
||||
struct PendingGuard(u64);
|
||||
impl PendingGuard {
|
||||
fn id(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
impl Drop for PendingGuard {
|
||||
fn drop(&mut self) {
|
||||
remove_pending_list_flip(self.0);
|
||||
}
|
||||
}
|
||||
let guard = PendingGuard(id);
|
||||
list.defer_host(move || {
|
||||
let after = crate::host::submissions().0;
|
||||
let flip = Flip { after, heap, index, handle, key, late };
|
||||
// Call a `&self` method so Rust 2021+ moves the whole `guard`
|
||||
// into this closure rather than copying `guard.0` and dropping
|
||||
// `guard` immediately at the end of `flip()`.
|
||||
let Some(mut flip) = take_pending_list_flip(guard.id()) else {
|
||||
return;
|
||||
};
|
||||
flip.after = crate::host::submissions().0;
|
||||
FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip);
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether any deferred slot flip or view remake for this heap requires
|
||||
/// settling in-flight GPU submissions before exposing real textures to a
|
||||
/// one-shot decoration bake draw.
|
||||
pub(crate) fn needs_gpu_settle_for_bake(&self) -> bool {
|
||||
let own = std::ptr::from_ref(self) as usize;
|
||||
let finished = crate::host::submissions().1;
|
||||
if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) > 0 {
|
||||
let pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if pending.iter().any(|p| p.flip.heap == own) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
{
|
||||
let flips = FLIPS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if flips.iter().any(|f| f.heap == own && f.after > finished) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
let after = RESHOWN_AFTER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
after.iter().any(|&(at, _)| at > finished)
|
||||
}
|
||||
|
||||
/// Drains deferred flips still sitting in unsubmitted command lists for
|
||||
/// this heap so a decoration bake can mirror them out of `neutral()`.
|
||||
/// Entries that cannot be promoted yet (unmapped memory or deferred
|
||||
/// staging) must be returned via [`HostHeap::restore_pending_list_flip`].
|
||||
pub(crate) fn take_pending_list_flips(&self) -> Vec<PendingListFlip> {
|
||||
if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let own = std::ptr::from_ref(self) as usize;
|
||||
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (mine, rest): (Vec<PendingListFlip>, Vec<PendingListFlip>) =
|
||||
pending.drain(..).partition(|p| p.flip.heap == own);
|
||||
*pending = rest;
|
||||
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
|
||||
mine
|
||||
}
|
||||
|
||||
/// Re-queues an unpromoted deferred flip drained by
|
||||
/// [`HostHeap::take_pending_list_flips`] so its originating command list
|
||||
/// still flips it out of `neutral()` once submitted.
|
||||
pub(crate) fn restore_pending_list_flip(&self, item: PendingListFlip) {
|
||||
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
pending.push(item);
|
||||
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
|
||||
/// Whether title descriptor slot `handle` still holds record `key`.
|
||||
pub(crate) fn slot_still_at(&self, handle: u64, key: u64) -> bool {
|
||||
key != 0 && record_key(handle) == key
|
||||
}
|
||||
|
||||
/// Looks up `(view, key)` for slot `index` prior to a synchronous bake
|
||||
/// upload without replacing its current host descriptor with `neutral()`;
|
||||
/// [`HostHeap::publish_uploaded_slot`] exposes the real descriptor and
|
||||
/// updates `Spans`/stride tracking once the GPU copy finishes.
|
||||
pub(crate) fn prepare_bake_slot(&self, index: u32, handle: u64) -> Option<(View, u64)> {
|
||||
if index >= self.count {
|
||||
return None;
|
||||
}
|
||||
let key = record_key(handle);
|
||||
let view = (key != 0).then(|| view_at(key as u32, (key >> 32) as u32)).flatten()?;
|
||||
Some((view, key))
|
||||
}
|
||||
|
||||
/// Exposes the real host descriptor for slot `index` after its synchronous
|
||||
/// bake upload has completed on the GPU, updating `Spans`/stride tracking
|
||||
/// without re-queuing the slot in `TextureQueue`.
|
||||
pub(crate) fn publish_uploaded_slot(&self, index: u32, handle: u64, key: u64) -> bool {
|
||||
if index >= self.count || key == 0 {
|
||||
return false;
|
||||
}
|
||||
let (published, stale) = {
|
||||
let _made = self.made.lock(index);
|
||||
if self.made.get(index) == Some(key) {
|
||||
return false;
|
||||
}
|
||||
if record_key(handle) != key {
|
||||
return false;
|
||||
}
|
||||
let Some(view) = view_at(key as u32, (key >> 32) as u32) else {
|
||||
return false;
|
||||
};
|
||||
let stale = self.note_buffer(index, Some(&view), true);
|
||||
if let Some(kept) = make(&view, self.at(index)) {
|
||||
self.put(index);
|
||||
self.quick_is(index, 0);
|
||||
self.clear_twin(index);
|
||||
self.made.set(index, key);
|
||||
self.keep(index, kept);
|
||||
(true, stale)
|
||||
} else {
|
||||
(false, stale)
|
||||
}
|
||||
};
|
||||
self.unmake_stale(index, stale);
|
||||
published
|
||||
}
|
||||
|
||||
/// Makes the slots whose new view's upload has run
|
||||
/// ([`HostHeap::texture_slot_flip`]); returns how many.
|
||||
pub(crate) fn texture_slots_flip(&self) -> usize {
|
||||
@@ -2222,6 +2458,7 @@ impl HostHeap {
|
||||
ready
|
||||
};
|
||||
let mut flipped = 0;
|
||||
let mut late_flipped = 0;
|
||||
for f in ready {
|
||||
let _made = self.made.lock(f.index);
|
||||
let Some(shown) = self.made.get(f.index) else {
|
||||
@@ -2264,6 +2501,7 @@ impl HostHeap {
|
||||
same_bytes(was, f.key);
|
||||
}
|
||||
if let Some(since) = f.late {
|
||||
late_flipped += 1;
|
||||
let frames = crate::frame::current().saturating_sub(since);
|
||||
let n = LATE[0].fetch_add(1, Relaxed) + 1;
|
||||
let all = LATE[1].fetch_add(frames, Relaxed) + frames;
|
||||
@@ -2282,7 +2520,7 @@ impl HostHeap {
|
||||
}
|
||||
}
|
||||
FLIPPED[0].fetch_add(flipped as u64, Relaxed);
|
||||
flipped
|
||||
flipped + late_flipped
|
||||
}
|
||||
|
||||
/// The memory of the texture title slot `index` views is there (again):
|
||||
@@ -2311,6 +2549,7 @@ impl HostHeap {
|
||||
}
|
||||
self.put(index);
|
||||
self.clear_twin(index);
|
||||
self.write_stride(index, 0);
|
||||
self.keep(index, None);
|
||||
}
|
||||
|
||||
@@ -2506,15 +2745,8 @@ impl HostHeap {
|
||||
textures.remove(slot);
|
||||
}
|
||||
}
|
||||
let stride = view.and_then(view_stride);
|
||||
let kind = view.map_or(0, view_kind);
|
||||
if let Some((_, _, data)) = &self.strides
|
||||
&& index < victory_shader::emit::SLOT_STRIDES_COUNT
|
||||
{
|
||||
// SAFETY: inside the mapping; shaders read it while we write (a
|
||||
// dword, either value is one the slot had).
|
||||
unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0) | kind) };
|
||||
}
|
||||
let (stride, kind) = view.map_or((None, 0), view_stride_and_kind);
|
||||
self.write_stride(index, stride.unwrap_or(0) | kind);
|
||||
let was = if stride.is_some() {
|
||||
self.buffers.put(index);
|
||||
true
|
||||
@@ -2527,6 +2759,20 @@ impl HostHeap {
|
||||
stale
|
||||
}
|
||||
|
||||
/// Writes `word` (stride | format kind) for view-heap slot `index` into
|
||||
/// the host's [`victory_shader::emit::SLOT_STRIDES`] table.
|
||||
#[inline]
|
||||
fn write_stride(&self, index: u32, word: u32) {
|
||||
if let Some((_, _, data)) = &self.strides
|
||||
&& index < victory_shader::emit::SLOT_STRIDES_COUNT
|
||||
{
|
||||
// SAFETY: inside the mapping; shaders read it while we write (a
|
||||
// single aligned dword: either value is one the slot had, and
|
||||
// dynamic slots are exclusively owned until submission finishes).
|
||||
unsafe { (*data as *mut u32).add(index as usize).write_volatile(word) };
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives back `n` dynamic slots from `first` (an index [`dynamic`]
|
||||
/// returned).
|
||||
///
|
||||
@@ -2554,6 +2800,7 @@ impl HostHeap {
|
||||
}
|
||||
self.put(index);
|
||||
self.twin_made(index, kept.is_some() && twinned(view));
|
||||
self.write_stride(index, if kept.is_some() { view_stride_word(view) } else { 0 });
|
||||
self.keep(index, kept.flatten());
|
||||
}
|
||||
|
||||
@@ -2586,13 +2833,14 @@ impl HostHeap {
|
||||
}
|
||||
let twin = twinned(&view);
|
||||
let kept = make_twinned(&view, views.slot(at), Some(views.slot(at + 1)))?;
|
||||
let stride_word = view_stride_word(&view);
|
||||
let listed = Listed {
|
||||
kind: crate::draw::view_kind(&view),
|
||||
texture: is_texture_view(&view),
|
||||
ready: (0, 0, false),
|
||||
tabled: None,
|
||||
};
|
||||
views.made.insert(words, ListView { view, at, twin, kept, listed });
|
||||
views.made.insert(words, ListView { view, at, twin, stride_word, kept, listed });
|
||||
}
|
||||
let made = &views.made[&words];
|
||||
self.copy_from(index, views.slot(made.at));
|
||||
@@ -2602,6 +2850,7 @@ impl HostHeap {
|
||||
} else {
|
||||
self.clear_twin(index);
|
||||
}
|
||||
self.write_stride(index, made.stride_word);
|
||||
self.keep(index, made.kept.clone());
|
||||
Some(made.listed)
|
||||
})
|
||||
@@ -2626,6 +2875,7 @@ impl HostHeap {
|
||||
} else {
|
||||
null_view(self.at(index));
|
||||
self.put(index);
|
||||
self.write_stride(index, 0);
|
||||
}
|
||||
self.clear_twin(index);
|
||||
self.keep(index, None);
|
||||
@@ -2712,6 +2962,7 @@ impl HostHeap {
|
||||
self.put(index);
|
||||
// (Bound by its handle, not read by index.)
|
||||
self.clear_twin(index);
|
||||
self.write_stride(index, 1);
|
||||
self.keep(index, Some(buffer.clone()));
|
||||
}
|
||||
|
||||
@@ -2721,6 +2972,7 @@ impl HostHeap {
|
||||
null_buffer_view(self.at(index));
|
||||
self.put(index);
|
||||
self.clear_twin(index);
|
||||
self.write_stride(index, 0);
|
||||
self.keep(index, None);
|
||||
}
|
||||
|
||||
@@ -2755,6 +3007,7 @@ impl HostHeap {
|
||||
};
|
||||
self.put(index);
|
||||
self.clear_twin(index);
|
||||
self.write_stride(index, 1);
|
||||
self.keep(index, Some(buffer.clone()));
|
||||
}
|
||||
|
||||
@@ -2784,6 +3037,7 @@ impl HostHeap {
|
||||
};
|
||||
self.put(index);
|
||||
self.clear_twin(index);
|
||||
self.write_stride(index, 0);
|
||||
self.keep(index, None);
|
||||
}
|
||||
|
||||
@@ -2841,6 +3095,7 @@ impl HostHeap {
|
||||
unsafe { host.device.CreateShaderResourceView(buffer, Some(&raw), twin) };
|
||||
}
|
||||
self.twin_made(index, twin.is_some());
|
||||
self.write_stride(index, 0);
|
||||
// After the descriptor: what it showed is let go when nothing shows
|
||||
// it any more.
|
||||
self.keep(index, holds.then(|| buffer.clone()));
|
||||
@@ -4084,24 +4339,27 @@ fn make_twinned(
|
||||
}
|
||||
const BUFFER: u32 = 1;
|
||||
if resource[0] != BUFFER {
|
||||
// shortcut: unordered access to a texture the title placed
|
||||
// itself is not mirrored; give it a resource as shader
|
||||
// views of such textures get when a dispatch writes one.
|
||||
// Each texture is said once (the first 64), with how many times
|
||||
// such a view was asked for so far: what shaders write through
|
||||
// them is lost.
|
||||
static SAID: Mutex<std::collections::BTreeSet<u64>> = Mutex::new(std::collections::BTreeSet::new());
|
||||
static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let times = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
|
||||
let at = u64::from(desc[10]) | u64::from(desc[11]) << 32;
|
||||
let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if (said.len() < 64 && said.insert(at)) || times.is_power_of_two() {
|
||||
tracing::warn!(
|
||||
address = format_args!("{at:#x}"),
|
||||
times,
|
||||
"placed unordered texture view not mirrored (null: writes through it are lost): resource {resource:?}, view {:?}",
|
||||
&desc[..10]
|
||||
);
|
||||
if *unordered || at != 0 {
|
||||
// shortcut: unordered access to a texture the title placed
|
||||
// itself is not mirrored; give it a resource as shader
|
||||
// views of such textures get when a dispatch writes one.
|
||||
// Each texture is said once (the first 64), with how many times
|
||||
// such a view was asked for so far: what shaders write through
|
||||
// them is lost.
|
||||
static SAID: Mutex<std::collections::BTreeSet<u64>> = Mutex::new(std::collections::BTreeSet::new());
|
||||
static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let times = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
|
||||
let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if (said.len() < 64 && said.insert(at)) || times.is_power_of_two() {
|
||||
tracing::warn!(
|
||||
address = format_args!("{at:#x}"),
|
||||
unordered = *unordered,
|
||||
times,
|
||||
"placed texture view not mirrored (null): resource {resource:?}, view {:?}",
|
||||
&desc[..10]
|
||||
);
|
||||
}
|
||||
}
|
||||
return None;
|
||||
}
|
||||
@@ -5446,6 +5704,71 @@ mod tests {
|
||||
heap.release(last, 1);
|
||||
assert_eq!(heap.dynamic(2), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_slots_populate_and_clear_stride_table() {
|
||||
use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED};
|
||||
let Some(heap) = HostHeap::new(false, 4) else {
|
||||
return; // no host GPU
|
||||
};
|
||||
let Some((_, _, data)) = heap.strides else {
|
||||
panic!("view heap should allocate strides table");
|
||||
};
|
||||
let read_stride = |slot: u32| -> u32 {
|
||||
// SAFETY: inside `SLOT_STRIDES_COUNT` mapping of `heap.strides`.
|
||||
unsafe { *(data as *const u32).add(slot as usize) }
|
||||
};
|
||||
let memory = vec![0u64; 1 << 11];
|
||||
let addr = (memory.as_ptr() as u64).next_multiple_of(4096);
|
||||
let placed_typed = |uav: bool, dxgi_fmt: u32, elems: u32| {
|
||||
let resource: [u32; 14] = [1, 0, 0, 0, 4096, 0, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0];
|
||||
let mut desc = [0u32; 16];
|
||||
// [format, dim=1 (buffer), mapping/pad, ..., num_elements @6, stride @7, flags @8]
|
||||
let words = if uav {
|
||||
[dxgi_fmt, 1, 0, 0, elems, 0, 0, 0, 0, 0]
|
||||
} else {
|
||||
[dxgi_fmt, 1, 5768, 0, 0, 0, elems, 0, 0, 0]
|
||||
};
|
||||
desc[..10].copy_from_slice(&words);
|
||||
(desc[10], desc[11]) = (addr as u32, (addr >> 32) as u32);
|
||||
View::Placed(uav, resource, desc)
|
||||
};
|
||||
|
||||
let s0 = heap.dynamic(4).unwrap();
|
||||
// R16G16B16A16_UINT (12): 8 bytes + VIEW_INTEGER
|
||||
let u16x4 = placed_typed(true, 12, 64);
|
||||
heap.make_at(s0, &u16x4);
|
||||
assert_eq!(read_stride(s0), 8 | VIEW_INTEGER);
|
||||
|
||||
// R16_SINT (59): 2 bytes + VIEW_INTEGER | VIEW_SIGNED
|
||||
let s16 = placed_typed(false, 59, 64);
|
||||
heap.make_at(s0 + 1, &s16);
|
||||
assert_eq!(read_stride(s0 + 1), 2 | VIEW_INTEGER | VIEW_SIGNED);
|
||||
|
||||
// R16G16B16A16_FLOAT (10): 8 bytes, no integer bits
|
||||
let f16x4 = placed_typed(true, 10, 64);
|
||||
heap.make_at(s0 + 2, &f16x4);
|
||||
assert_eq!(read_stride(s0 + 2), 8);
|
||||
|
||||
// Clearing / nulling / raw views overwrite stale bits cleanly.
|
||||
heap.make_null(s0);
|
||||
assert_eq!(read_stride(s0), 0);
|
||||
heap.null_raw_at(s0 + 1);
|
||||
assert_eq!(read_stride(s0 + 1), 0);
|
||||
heap.null_raw_uav_at(s0 + 2);
|
||||
assert_eq!(read_stride(s0 + 2), 0);
|
||||
|
||||
// `make_listed` (both cold creation and cached copy hit) must populate strides.
|
||||
let mut slot_mem = [0u32; 8];
|
||||
crate::descriptor::record(slot_mem.as_mut_ptr() as u64, u16x4);
|
||||
let rec = [slot_mem[0], slot_mem[1], slot_mem[2]];
|
||||
assert!(heap.make_listed(0x1234, rec, s0).is_some());
|
||||
assert_eq!(read_stride(s0), 8 | VIEW_INTEGER);
|
||||
heap.make_null(s0 + 3);
|
||||
assert_eq!(read_stride(s0 + 3), 0);
|
||||
assert!(heap.make_listed(0x1234, rec, s0 + 3).is_some());
|
||||
assert_eq!(read_stride(s0 + 3), 8 | VIEW_INTEGER);
|
||||
}
|
||||
}
|
||||
|
||||
/// What is known of a record a list's tables hold, in that recording of the
|
||||
@@ -5466,6 +5789,7 @@ struct ListView {
|
||||
/// Its descriptor's slot in [`ListViews`]; its raw twin's is the next.
|
||||
at: u32,
|
||||
twin: bool,
|
||||
stride_word: u32,
|
||||
kept: Kept,
|
||||
listed: Listed,
|
||||
}
|
||||
@@ -5544,3 +5868,74 @@ pub(crate) fn note_listed(recording: u64, words: [u32; 3], listed: Listed) {
|
||||
pub(crate) fn list_views() -> bool {
|
||||
crate::toggled!("VICTORY_LIST_VIEWS")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod bake_flip_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn pending_list_flips_promote_once_and_clean_up() {
|
||||
let heap = 0xdead_beefusize;
|
||||
let id1 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let id2 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
{
|
||||
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
pending.push(PendingListFlip {
|
||||
id: id1,
|
||||
origin: (1, 1),
|
||||
flip: Flip { after: 0, heap, index: 7, handle: 0, key: 11, late: Some(1) },
|
||||
});
|
||||
pending.push(PendingListFlip {
|
||||
id: id2,
|
||||
origin: (2, 1),
|
||||
flip: Flip { after: 0, heap, index: 8, handle: 0, key: 12, late: Some(1) },
|
||||
});
|
||||
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
let taken = take_pending_list_flip(id1).expect("id1 should be present");
|
||||
assert_eq!(taken.index, 7);
|
||||
assert!(take_pending_list_flip(id1).is_none(), "second take must be a no-op");
|
||||
remove_pending_list_flip(id2);
|
||||
assert!(take_pending_list_flip(id2).is_none(), "removed entry must be gone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deferred_flip_closure_keeps_pending_entry_alive_until_called_or_dropped() {
|
||||
let heap = 0xcafe_babeusize;
|
||||
let id1 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let id2 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
{
|
||||
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for (id, idx) in [(id1, 10), (id2, 11)] {
|
||||
pending.push(PendingListFlip {
|
||||
id,
|
||||
origin: (3, 1),
|
||||
flip: Flip { after: 0, heap, index: idx, handle: 0, key: 20, late: Some(1) },
|
||||
});
|
||||
}
|
||||
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
struct TestGuard(u64);
|
||||
impl TestGuard {
|
||||
fn id(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
impl Drop for TestGuard {
|
||||
fn drop(&mut self) {
|
||||
remove_pending_list_flip(self.0);
|
||||
}
|
||||
}
|
||||
let make_cb = |id: u64| -> Box<dyn Fn() -> Option<u32> + Send + 'static> {
|
||||
let guard = TestGuard(id);
|
||||
Box::new(move || take_pending_list_flip(guard.id()).map(|f| f.index))
|
||||
};
|
||||
let cb1 = make_cb(id1);
|
||||
let cb2 = make_cb(id2);
|
||||
// Must still be present after make_cb returns (guard moved, not dropped).
|
||||
assert_eq!(cb1(), Some(10));
|
||||
assert_eq!(cb1(), None);
|
||||
drop(cb2);
|
||||
assert!(take_pending_list_flip(id2).is_none(), "dropping uncalled closure cleans up entry");
|
||||
}
|
||||
}
|
||||
+396
-73
@@ -217,12 +217,45 @@ const BAKE_AHEAD: [u64; 2] = [12, 2];
|
||||
/// until something is new, the next bakes of the frame need no pass.
|
||||
static BAKE_SERVED: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Free-threaded wrapper around a reusable upload-only [`HostList`] protected
|
||||
/// by [`BAKE_UPLOAD`]. D3D12 command allocators, lists, and retained COM
|
||||
/// resources are free-threaded when externally synchronized.
|
||||
struct BakeList(HostList);
|
||||
// SAFETY: accessed exclusively under `BAKE_UPLOAD`'s mutex.
|
||||
unsafe impl Send for BakeList {}
|
||||
|
||||
/// Serializes synchronous one-shot ped/decoration bake uploads across
|
||||
/// concurrent `VICTORY_THIN=1` recording threads and owns the reusable
|
||||
/// upload-only host command list.
|
||||
static BAKE_UPLOAD: std::sync::Mutex<Option<BakeList>> = std::sync::Mutex::new(None);
|
||||
|
||||
/// Pending descriptor publications for a synchronous bake upload pass: slots
|
||||
/// stay on `neutral()` (or their previous compatible view) until the dedicated
|
||||
/// upload list has finished executing on the host GPU.
|
||||
struct BakeSync {
|
||||
publish: Vec<(u32, u64, u64)>,
|
||||
keep: Vec<std::sync::Arc<crate::resource::HostTexture>>,
|
||||
}
|
||||
|
||||
/// The pixel shaders of the title's decoration bake (the title:
|
||||
/// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the
|
||||
/// frame listings print it. They draw into a 256x256 corner of 2048x2048
|
||||
/// targets and name no texture in a table.
|
||||
pub(crate) const BAKE_PIXEL_SHADERS: [&str; 4] =
|
||||
["c0a7fe77b1862e10", "0d1575a396dfe513", "b7cfd8dda91ebb6b", "280967ad158cee0b"];
|
||||
pub(crate) const BAKE_PIXEL_SHADERS: [&str; 7] = [
|
||||
"c0a7fe77b1862e10",
|
||||
"0d1575a396dfe513",
|
||||
"b7cfd8dda91ebb6b",
|
||||
"280967ad158cee0b",
|
||||
"fa455c8a3c32577b",
|
||||
"d126bcae5d5d8d26",
|
||||
"fcee612943c008e0",
|
||||
];
|
||||
|
||||
/// Geometry stages shared by every ped texture compositor / decoration bake
|
||||
/// permutation (`vertex 089d6271be6650ef` fullscreen-triangle ped baker and
|
||||
/// `mesh d4111a6e6ea49d91` decoration projection mesh), catching pixel-shader
|
||||
/// permutations beyond `BAKE_PIXEL_SHADERS`.
|
||||
const BAKE_GEOMETRY_SHADERS: [&str; 2] = ["089d6271be6650ef", "d4111a6e6ea49d91"];
|
||||
|
||||
/// Since the start: early runs of the texture pass, and those of them
|
||||
/// made for a bake draw.
|
||||
@@ -1714,6 +1747,24 @@ impl State {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if srv && slot == victory_shader::emit::SLOT_TABLE_STRIDES {
|
||||
// Ours: the shader inspects typed view kinds for its
|
||||
// descriptor tables only (already mirrored by `tables`),
|
||||
// so bind the strides buffer without sweeping the heap.
|
||||
match self.heap_strides(list) {
|
||||
// SAFETY: an open list; the table lives as long
|
||||
// as the heap the list holds.
|
||||
Some(gpu) => unsafe {
|
||||
if compute {
|
||||
l.SetComputeRootShaderResourceView(param, gpu);
|
||||
} else {
|
||||
l.SetGraphicsRootShaderResourceView(param, gpu);
|
||||
}
|
||||
},
|
||||
None => once!("a shader inspects table view kinds without a view heap set"),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let tabled = srv && crate::pipeline::host::bounded_root_srvs();
|
||||
let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot))
|
||||
else {
|
||||
@@ -1872,7 +1923,10 @@ impl State {
|
||||
Some((index, shadow)) => (*index, address.zip(shadow.clone())),
|
||||
None => {
|
||||
let shadow = address.and_then(|a| find(a).map(|s| (a, s)));
|
||||
let Some(index) = host.dynamic(1) else {
|
||||
let Some(index) = host.dynamic(1).or_else(|| {
|
||||
crate::host::settle_for_fence();
|
||||
host.dynamic(1)
|
||||
}) else {
|
||||
return false;
|
||||
};
|
||||
self.dynamic.push((key.0, index, 1));
|
||||
@@ -1943,7 +1997,10 @@ impl State {
|
||||
Some((index, shadow)) => (*index, address.zip(shadow.clone())),
|
||||
None => {
|
||||
let shadow = address.and_then(|a| crate::shadow::find(a, 1).map(|s| (a, s)));
|
||||
let Some(index) = host.dynamic(1) else {
|
||||
let Some(index) = host.dynamic(1).or_else(|| {
|
||||
crate::host::settle_for_fence();
|
||||
host.dynamic(1)
|
||||
}) else {
|
||||
return false;
|
||||
};
|
||||
self.dynamic.push((key.0, index, 1));
|
||||
@@ -2053,7 +2110,7 @@ impl State {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
let refreshed = std::time::Instant::now();
|
||||
stage.next("the heap pass: textures");
|
||||
self.heap_textures(list, heap, host);
|
||||
let _ = self.heap_textures(list, heap, host, None);
|
||||
stage.end();
|
||||
#[cfg(feature = "diagnostics")]
|
||||
HEAP_SPLIT[2].fetch_add(refreshed.elapsed().as_nanos() as u64, Ordering::Relaxed);
|
||||
@@ -2062,20 +2119,179 @@ impl State {
|
||||
Some(gpu)
|
||||
}
|
||||
|
||||
/// The GPU address of the bound view heap's stride/kind table without
|
||||
/// running the bindless heap buffer/texture sweep (for shaders that only
|
||||
/// inspect descriptors already mirrored via their descriptor tables).
|
||||
fn heap_strides(&self, list: &HostList) -> Option<u64> {
|
||||
let heap = self
|
||||
.heaps
|
||||
.iter()
|
||||
.filter(|&&h| h != 0)
|
||||
.map(|&h| crate::descriptor::heap(h as This))
|
||||
.find(|h| !h.samplers())?;
|
||||
let host = heap.host()?;
|
||||
let gpu = host.strides_gpu()?;
|
||||
// Tag bit 1 (distinct from `heap_buffers`'s `| 1` and aligned guest pointers).
|
||||
if list.first_use(gpu as usize | 2)
|
||||
&& let Some(buffer) = host.strides_buffer()
|
||||
{
|
||||
list.keep(buffer);
|
||||
}
|
||||
Some(gpu)
|
||||
}
|
||||
|
||||
/// Ensures textures claimed by background copy-queue uploads
|
||||
/// (`VICTORY_UPLOAD_AHEAD=1`) or deferred behind the `neutral()` gray
|
||||
/// stand-in (`VICTORY_SHOW_AFTER=1` / `shows_other`) have finished
|
||||
/// uploading and flipped to their real descriptors before a one-shot
|
||||
/// decoration bake draw samples them.
|
||||
fn flush_for_bake(
|
||||
&self,
|
||||
list: &HostList,
|
||||
host: &crate::descriptor::host::HostHeap,
|
||||
mut sync: Option<&mut BakeSync>,
|
||||
) {
|
||||
static RESCUED: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4];
|
||||
let drained = crate::texture::ahead::drain();
|
||||
let mut settled = false;
|
||||
let mut flipped = 0usize;
|
||||
for _ in 0..4 {
|
||||
let need_settle = host.needs_gpu_settle_for_bake();
|
||||
if need_settle {
|
||||
settled = true;
|
||||
crate::host::settle_for_fence();
|
||||
}
|
||||
flipped += host.texture_views_remade();
|
||||
flipped += host.texture_slots_flip();
|
||||
if !need_settle || !host.needs_gpu_settle_for_bake() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let pending = host.take_pending_list_flips();
|
||||
let mut promoted = 0usize;
|
||||
if !pending.is_empty() {
|
||||
let this_list = (std::ptr::from_ref(list) as usize, list.epoch());
|
||||
let sampled = UsedResource {
|
||||
kind: ResourceType::Srv,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
lower_bound: 0,
|
||||
stride: 0,
|
||||
dwords: 8,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
};
|
||||
for item in pending {
|
||||
let (origin, index, handle, key) = (item.origin, item.index(), item.handle(), item.key());
|
||||
if !host.slot_still_at(handle, key) {
|
||||
continue;
|
||||
}
|
||||
let Some(view) = crate::descriptor::view(handle) else {
|
||||
continue;
|
||||
};
|
||||
if let View::Placed(_, resource, desc) = &view {
|
||||
let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
|
||||
let len = crate::resource::placed_bytes(resource).unwrap_or(1);
|
||||
if crate::texture::mapped_bytes(address as *const u8, len as usize) == 0 {
|
||||
host.restore_pending_list_flip(item);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if sync.is_some() || origin != this_list {
|
||||
let placed = crate::descriptor::host::placed_texture(&view);
|
||||
if let Some(&View::Shader(resource, _)) = placed.as_ref().or(Some(&view)) {
|
||||
let resource = resource as This;
|
||||
let texture = crate::resource::host_resource(resource);
|
||||
let title_fills = texture.is_some_and(crate::texture::title_written);
|
||||
let first = match (&placed, &view) {
|
||||
(Some(_), View::Placed(_, _, desc)) => crate::resource::first_mip(desc),
|
||||
_ => 0,
|
||||
};
|
||||
if let (Some(sync), Some(copy)) = (sync.as_deref_mut(), crate::resource::host_copy(resource)) {
|
||||
sync.keep.push(copy);
|
||||
}
|
||||
if title_fills
|
||||
&& !crate::texture::ahead::there(resource)
|
||||
&& (sync.is_some() || !crate::texture::unchanged(resource, first))
|
||||
{
|
||||
let was_staged = crate::texture::is_staged(resource);
|
||||
let _ = crate::residency::take_staging_deferred();
|
||||
readable(list, sampled.kind, &view);
|
||||
let failed = crate::residency::take_staging_deferred() || crate::residency::upload_refused();
|
||||
if !was_staged {
|
||||
crate::texture::unstage(resource);
|
||||
}
|
||||
if failed {
|
||||
host.restore_pending_list_flip(item);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(sync) = sync.as_deref_mut() {
|
||||
sync.publish.push((index, handle, key));
|
||||
} else {
|
||||
let _ = host.mirror(index, handle, true);
|
||||
}
|
||||
promoted += 1;
|
||||
}
|
||||
}
|
||||
if drained > 0 || settled || flipped > 0 || promoted > 0 {
|
||||
let n = RESCUED[0].fetch_add(1, Ordering::Relaxed) + 1;
|
||||
let all_drained = RESCUED[1].fetch_add(drained as u64, Ordering::Relaxed) + drained as u64;
|
||||
let all_flipped = RESCUED[2].fetch_add(flipped as u64, Ordering::Relaxed) + flipped as u64;
|
||||
let all_promoted = RESCUED[3].fetch_add(promoted as u64, Ordering::Relaxed) + promoted as u64;
|
||||
if n.is_power_of_two() {
|
||||
tracing::info!(
|
||||
frame = crate::frame::current(),
|
||||
flushes = n,
|
||||
drained_ahead = all_drained,
|
||||
flipped = all_flipped,
|
||||
promoted_from_lists = all_promoted,
|
||||
settled,
|
||||
"flushed deferred texture stand-ins before decoration bake"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a graphics draw is a one-shot texture compositor / decoration
|
||||
/// bake whose bindless texture inputs must be flushed and up to date
|
||||
/// before recording the draw. Matches known bake pixel/geometry shaders
|
||||
/// and structurally detects depth-less 4+ MRT square atlas bakes
|
||||
/// (`>= 512x512`) so unseen NPC/head/clothing shader permutations never
|
||||
/// bake `neutral()` or `null` stand-ins into permanent ped textures.
|
||||
fn is_bake_draw(&self, p: &HostPipeline) -> bool {
|
||||
if p.stages.iter().any(|s| {
|
||||
let h = s.shader.hash.as_str();
|
||||
BAKE_PIXEL_SHADERS.contains(&h) || BAKE_GEOMETRY_SHADERS.contains(&h)
|
||||
}) {
|
||||
return true;
|
||||
}
|
||||
self.depth == 0
|
||||
&& self.targets.len() >= 4
|
||||
&& self
|
||||
.targets
|
||||
.first()
|
||||
.and_then(|&t| crate::resource::texture_kind(t as This))
|
||||
.is_some_and(|(w, h, _)| w >= 512 && w == u64::from(h))
|
||||
}
|
||||
|
||||
/// Runs the pass that uploads textures picked by index
|
||||
/// ([`State::heap_textures`]) where nothing has asked for it yet
|
||||
/// ([`early_budgets`]): once a frame for a few milliseconds, at the
|
||||
/// frame's first draw with a view heap set, and with a larger budget
|
||||
/// of its own before every draw whose pixel shader is one of the
|
||||
/// title's bake programs. The uploads are recorded into `list` ahead
|
||||
/// of the draw being bound, as the world's pass records them.
|
||||
/// title's bake programs. For decoration bakes, uploads run synchronously
|
||||
/// on a dedicated internal command list and descriptors are published only
|
||||
/// after the GPU copy finishes so concurrent `VICTORY_THIN=1` lists can
|
||||
/// never submit a bake draw ahead of its texture uploads.
|
||||
fn early_textures(&self, list: &HostList, p: &HostPipeline, compute: bool) {
|
||||
let (early_ms, bake_ms) = early_budgets();
|
||||
if compute || (early_ms == 0 && bake_ms == 0) {
|
||||
return;
|
||||
}
|
||||
let bake = bake_ms > 0
|
||||
&& p.stages.iter().any(|s| BAKE_PIXEL_SHADERS.contains(&s.shader.hash.as_str()));
|
||||
let is_bake = bake_ms > 0 && self.is_bake_draw(p);
|
||||
static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
|
||||
// The milliseconds this frame's bake draws have taken so far: a
|
||||
// frame has several, and together they get `bake_ms`.
|
||||
@@ -2085,15 +2301,9 @@ impl State {
|
||||
if first {
|
||||
BAKED_MS.store(0, Ordering::Relaxed);
|
||||
}
|
||||
let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed));
|
||||
let budget = if bake && left > 0 {
|
||||
// What a bake may read must be there now: up to 2 GiB.
|
||||
(left, 2 << 30)
|
||||
} else if first && early_ms > 0 {
|
||||
(early_ms, 64 << 20)
|
||||
} else {
|
||||
if !is_bake && !(first && early_ms > 0) {
|
||||
return;
|
||||
};
|
||||
}
|
||||
let Some(heap) = self
|
||||
.heaps
|
||||
.iter()
|
||||
@@ -2106,34 +2316,102 @@ impl State {
|
||||
let Some(host) = heap.host() else {
|
||||
return;
|
||||
};
|
||||
let bake = bake && left > 0;
|
||||
if bake && !first && bake_exact() {
|
||||
let (writes, noted) = host.texture_news();
|
||||
if !noted && BAKE_SERVED.load(Ordering::Relaxed) == writes + 1 {
|
||||
if is_bake {
|
||||
let began = std::time::Instant::now();
|
||||
let mut bake_slot = BAKE_UPLOAD.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let gpu = crate::host::host();
|
||||
if bake_slot.is_none()
|
||||
&& let Some(gpu) = gpu
|
||||
{
|
||||
match gpu.new_list() {
|
||||
Ok(upload_list) => *bake_slot = Some(BakeList(upload_list)),
|
||||
Err(e) => tracing::warn!(error = %e, "no host list for synchronous bake uploads"),
|
||||
}
|
||||
}
|
||||
let exact = bake_exact();
|
||||
if let (Some(gpu), Some(BakeList(bake_list))) = (gpu, bake_slot.as_ref()) {
|
||||
let mut sync = BakeSync { publish: Vec::new(), keep: Vec::new() };
|
||||
crate::texture::BAKING.set(exact);
|
||||
self.flush_for_bake(bake_list, host, Some(&mut sync));
|
||||
let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed));
|
||||
let run_pass = left > 0
|
||||
&& (first
|
||||
|| !exact
|
||||
|| {
|
||||
let (writes, noted) = host.texture_news();
|
||||
noted || BAKE_SERVED.load(Ordering::Relaxed) != writes + 1
|
||||
});
|
||||
let mut served = false;
|
||||
if run_pass {
|
||||
let n = EARLY_TEXTURE_PASSES[1].fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if n.is_power_of_two() {
|
||||
let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed));
|
||||
tracing::info!(
|
||||
frame,
|
||||
bakes = n,
|
||||
queued_at_the_last_pass = slots,
|
||||
due_at_the_last_pass = due,
|
||||
uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed),
|
||||
"a draw of the title's decoration bake: textures picked by index are uploaded synchronously first (VICTORY_BAKE_TEXTURES_MS=0: not)"
|
||||
);
|
||||
}
|
||||
BAKE_SERVED.store(0, Ordering::Relaxed);
|
||||
PASS_BUDGET.set(Some((left, 2 << 30, true)));
|
||||
served = self.heap_textures(bake_list, heap, host, Some(&mut sync));
|
||||
PASS_BUDGET.set(None);
|
||||
}
|
||||
crate::texture::BAKING.set(false);
|
||||
if bake_list.has_recorded_work() {
|
||||
bake_list.close();
|
||||
gpu.execute_sync_internal(bake_list);
|
||||
bake_list.reset();
|
||||
} else if !sync.publish.is_empty() {
|
||||
crate::host::settle_for_fence();
|
||||
}
|
||||
for (index, handle, key) in sync.publish {
|
||||
let _ = host.publish_uploaded_slot(index, handle, key);
|
||||
}
|
||||
host.texture_views_remade();
|
||||
host.texture_slots_flip();
|
||||
drop(sync.keep);
|
||||
if run_pass && served && exact {
|
||||
BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed);
|
||||
}
|
||||
BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
}
|
||||
let n = EARLY_TEXTURE_PASSES[usize::from(bake)].fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if bake && n.is_power_of_two() {
|
||||
let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed));
|
||||
tracing::info!(
|
||||
frame,
|
||||
bakes = n,
|
||||
queued_at_the_last_pass = slots,
|
||||
due_at_the_last_pass = due,
|
||||
uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed),
|
||||
"a draw of the title's decoration bake: textures picked by index are uploaded first (VICTORY_BAKE_TEXTURES_MS=0: not)"
|
||||
);
|
||||
}
|
||||
let began = std::time::Instant::now();
|
||||
PASS_BUDGET.set(Some((budget.0, budget.1, bake)));
|
||||
crate::texture::BAKING.set(bake && bake_exact());
|
||||
self.heap_textures(list, heap, host);
|
||||
crate::texture::BAKING.set(false);
|
||||
PASS_BUDGET.set(None);
|
||||
if bake {
|
||||
// Fallback when no host GPU list can be created (e.g. headless tests).
|
||||
crate::texture::BAKING.set(exact);
|
||||
self.flush_for_bake(list, host, None);
|
||||
crate::texture::BAKING.set(false);
|
||||
let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed));
|
||||
if left == 0 {
|
||||
return;
|
||||
}
|
||||
if !first && exact {
|
||||
let (writes, noted) = host.texture_news();
|
||||
if !noted && BAKE_SERVED.load(Ordering::Relaxed) == writes + 1 {
|
||||
return;
|
||||
}
|
||||
}
|
||||
EARLY_TEXTURE_PASSES[1].fetch_add(1, Ordering::Relaxed);
|
||||
PASS_BUDGET.set(Some((left, 2 << 30, true)));
|
||||
crate::texture::BAKING.set(exact);
|
||||
let _ = self.heap_textures(list, heap, host, None);
|
||||
crate::texture::BAKING.set(false);
|
||||
PASS_BUDGET.set(None);
|
||||
BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
let budget = if first && early_ms > 0 {
|
||||
(early_ms, 64 << 20)
|
||||
} else {
|
||||
return;
|
||||
};
|
||||
EARLY_TEXTURE_PASSES[0].fetch_add(1, Ordering::Relaxed);
|
||||
PASS_BUDGET.set(Some((budget.0, budget.1, false)));
|
||||
let _ = self.heap_textures(list, heap, host, None);
|
||||
PASS_BUDGET.set(None);
|
||||
}
|
||||
|
||||
/// The queue's side of the card accounting line
|
||||
@@ -2230,10 +2508,11 @@ impl State {
|
||||
list: &HostList,
|
||||
heap: &crate::descriptor::Heap,
|
||||
host: &crate::descriptor::host::HostHeap,
|
||||
) {
|
||||
mut sync: Option<&mut BakeSync>,
|
||||
) -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_TEXTURES").is_none_or(|v| v != "0")) {
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
let memory = crate::host::host().and_then(|h| h.video_memory());
|
||||
// `VICTORY_TEXTURE_STAGE_MB` sets it: a backlog of tens of thousands of
|
||||
@@ -2285,6 +2564,10 @@ impl State {
|
||||
// Slots whose texture's memory the runtime mapped, unmapped or
|
||||
// wrote since the last pass are due again.
|
||||
host.texture_slots_remapped(frame);
|
||||
let baking = crate::texture::BAKING.get();
|
||||
if baking {
|
||||
host.texture_slots_bake_written(frame);
|
||||
}
|
||||
host.texture_slots_short(frame);
|
||||
// The slots of textures whose first level with memory (levels on
|
||||
// demand), or whose host copy for one with more levels, changed since
|
||||
@@ -2298,11 +2581,6 @@ impl State {
|
||||
host.texture_slots_waiting(frame);
|
||||
}
|
||||
let required = PASS_BUDGET.get().is_some_and(|(_, _, bake)| bake);
|
||||
if !crate::residency::admit_texture_pass(required) {
|
||||
BAKE_SERVED.store(0, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
let baking = crate::texture::BAKING.get();
|
||||
let (mut due, census) = host.texture_slots_due(frame, if baking { 1 << 16 } else { 4096 });
|
||||
// (Those that are due later after all that are due.)
|
||||
let on_time = due.len();
|
||||
@@ -2370,17 +2648,22 @@ impl State {
|
||||
let bytes_at_most = if required || asked.is_some() {
|
||||
bytes_at_most
|
||||
} else {
|
||||
crate::residency::prefetch_limit(bytes_at_most, crate::residency::pressured(),
|
||||
crate::residency::limited_host_ram(), crate::texture::live_staging_bytes())
|
||||
crate::residency::prefetch_limit(
|
||||
bytes_at_most,
|
||||
crate::residency::pressured(),
|
||||
crate::residency::critical_commit(),
|
||||
crate::residency::limited_host_ram(),
|
||||
crate::texture::live_staging_bytes(),
|
||||
)
|
||||
};
|
||||
|
||||
let began = std::time::Instant::now();
|
||||
BAKE_SERVED.store(0, Ordering::Relaxed);
|
||||
if sync.is_none() {
|
||||
BAKE_SERVED.store(0, Ordering::Relaxed);
|
||||
}
|
||||
let mut served = true;
|
||||
for (index, write) in due {
|
||||
if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span
|
||||
|| !crate::residency::admit_texture_pass(required)
|
||||
{
|
||||
if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span {
|
||||
served = false;
|
||||
break;
|
||||
}
|
||||
@@ -2524,23 +2807,41 @@ impl State {
|
||||
);
|
||||
}
|
||||
}
|
||||
// Gate new host texture creation / staging on commit reserve after
|
||||
// `mapped == 0` reclamation (`texture_slot_gone`) has run, and
|
||||
// before mirroring a slot to an unuploaded texture.
|
||||
if !crate::residency::admit_texture_pass(required) {
|
||||
served = false;
|
||||
break;
|
||||
}
|
||||
// A slot that shows the texture by an earlier view of it (one
|
||||
// from another level) goes on doing so until the upload of what
|
||||
// the new one shows has run.
|
||||
let sync_bake = sync.is_some();
|
||||
let shows_other = !baking
|
||||
&& !sync_bake
|
||||
&& crate::resource::held_only()
|
||||
&& heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle));
|
||||
// A slot that shows nothing of it yet, or something else, shows it
|
||||
// when the upload has run too.
|
||||
let late = !shows_other
|
||||
&& !baking
|
||||
&& !sync_bake
|
||||
&& crate::descriptor::host::show_after()
|
||||
&& heap.handle(index).is_some_and(|handle| !host.texture_slot_made_from(index, handle));
|
||||
let view = heap.handle(index).and_then(|handle| {
|
||||
if shows_other || late { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) }
|
||||
});
|
||||
let (view, bake_key) = if sync_bake {
|
||||
match heap.handle(index).and_then(|handle| host.prepare_bake_slot(index, handle)) {
|
||||
Some((view, key)) => (Some(view), Some(key)),
|
||||
None => (None, None),
|
||||
}
|
||||
} else {
|
||||
let view = heap.handle(index).and_then(|handle| {
|
||||
if shows_other || late { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) }
|
||||
});
|
||||
(view, None)
|
||||
};
|
||||
let at_once = || {
|
||||
if late && let Some(handle) = heap.handle(index) {
|
||||
if (late || bake_key.is_some()) && let Some(handle) = heap.handle(index) {
|
||||
let _ = host.mirror(index, handle, true);
|
||||
}
|
||||
};
|
||||
@@ -2581,16 +2882,23 @@ impl State {
|
||||
let same = !tabled && crate::texture::unchanged(resource, first);
|
||||
if same {
|
||||
HEAP_TEXTURES_SAME.fetch_add(1, Ordering::Relaxed);
|
||||
if shows_other && let Some(handle) = heap.handle(index) {
|
||||
let _ = host.mirror(index, handle, true);
|
||||
}
|
||||
// Its bytes are in, or on the way there in a list before.
|
||||
if late && texture.is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource) {
|
||||
if let Some(handle) = heap.handle(index) {
|
||||
host.texture_slot_show_after(list, index, handle);
|
||||
if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, heap.handle(index)) {
|
||||
if let Some(copy) = crate::resource::host_copy(resource) {
|
||||
sync.keep.push(copy);
|
||||
}
|
||||
sync.publish.push((index, handle, key));
|
||||
} else {
|
||||
at_once();
|
||||
if shows_other && let Some(handle) = heap.handle(index) {
|
||||
let _ = host.mirror(index, handle, true);
|
||||
}
|
||||
// Its bytes are in, or on the way there in a list before.
|
||||
if late && texture.is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource) {
|
||||
if let Some(handle) = heap.handle(index) {
|
||||
host.texture_slot_show_after(list, index, handle);
|
||||
}
|
||||
} else {
|
||||
at_once();
|
||||
}
|
||||
}
|
||||
let again = partly.map(|mapped| (frame + 1, mapped));
|
||||
let memory = if again.is_none() && heap_recheck() { crate::texture::title_span(resource, first) } else { None };
|
||||
@@ -2625,6 +2933,7 @@ impl State {
|
||||
break;
|
||||
}
|
||||
let late = late && ahead.is_none();
|
||||
let _ = crate::residency::take_staging_deferred();
|
||||
if let Some(view) = &view
|
||||
&& ahead.is_none()
|
||||
{
|
||||
@@ -2634,12 +2943,21 @@ impl State {
|
||||
readable(list, sampled.kind, view);
|
||||
crate::texture::PICKING.set(None);
|
||||
}
|
||||
// A failed allocation leaves this slot due. Publishing it or
|
||||
// marking it served would lose the only retry for some materials.
|
||||
if ahead.is_none() && crate::residency::upload_refused() {
|
||||
// A failed or deferred staging allocation leaves this slot due.
|
||||
// Publishing it or marking it served would lose the only retry for
|
||||
// some materials.
|
||||
if ahead.is_none()
|
||||
&& (crate::residency::take_staging_deferred() || crate::residency::upload_refused())
|
||||
{
|
||||
served = false;
|
||||
break;
|
||||
}
|
||||
if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, heap.handle(index)) {
|
||||
if let Some(copy) = crate::resource::host_copy(resource) {
|
||||
sync.keep.push(copy);
|
||||
}
|
||||
sync.publish.push((index, handle, key));
|
||||
}
|
||||
if shows_other && let Some(handle) = heap.handle(index) {
|
||||
host.texture_slot_flip(list, index, handle);
|
||||
}
|
||||
@@ -2672,7 +2990,7 @@ impl State {
|
||||
let text: String = format!("{view:?}").chars().take(300).collect();
|
||||
tracing::error!(why, slot = index, "the host device went while textures picked by index were made ready; last: {text}");
|
||||
crate::host::log_removal_context();
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
let (bytes, whole) = crate::texture::staged(resource, there.is_none()).unwrap_or((0, true));
|
||||
// Not all of it there: looked at again next frame, and from
|
||||
@@ -2723,9 +3041,10 @@ impl State {
|
||||
None => host.texture_slot_done(index, write, again),
|
||||
}
|
||||
}
|
||||
if baking && served {
|
||||
if sync.is_none() && baking && served {
|
||||
BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed);
|
||||
}
|
||||
served
|
||||
}
|
||||
|
||||
/// For the frame listing, after a dropped dispatch's line: its group
|
||||
@@ -3440,7 +3759,10 @@ impl State {
|
||||
made.push((slot, first * 32));
|
||||
continue;
|
||||
}
|
||||
let Some(first) = host.dynamic(n) else {
|
||||
let Some(first) = host.dynamic(n).or_else(|| {
|
||||
crate::host::settle_for_fence();
|
||||
host.dynamic(n)
|
||||
}) else {
|
||||
// No room: the draw must not run with the title's own
|
||||
// offsets (slots never made for it); `bind` drops it.
|
||||
made.push((slot, u32::MAX));
|
||||
@@ -3488,11 +3810,12 @@ impl State {
|
||||
TESTED_DEPTH.set((tested.0, true));
|
||||
}
|
||||
} else if let Some(view) = crate::descriptor::host::listed_view(recording, words) {
|
||||
let _ = crate::residency::take_staging_deferred();
|
||||
TESTED_DEPTH.set((tested.0, false));
|
||||
readable(list, kind, &view);
|
||||
let depth = TESTED_DEPTH.get().1;
|
||||
TESTED_DEPTH.set((tested.0, tested.1 || depth));
|
||||
if kind == ResourceType::Srv {
|
||||
if kind == ResourceType::Srv && !crate::residency::take_staging_deferred() {
|
||||
listed.ready = (list.epoch(), tested.0, depth);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4912,7 +4912,7 @@ impl Host {
|
||||
let mut telling = std::time::Instant::now();
|
||||
for item in items {
|
||||
telling = match item {
|
||||
Late::Run(flight) => {
|
||||
Late::Run(mut flight) => {
|
||||
last = flight.number;
|
||||
for &i in &flight.order {
|
||||
read_backs(flight.lists[i].host());
|
||||
@@ -4923,6 +4923,9 @@ impl Host {
|
||||
if let Some(own) = flight.own {
|
||||
own.landed();
|
||||
}
|
||||
for detached in &mut flight.lists {
|
||||
detached.release_tables();
|
||||
}
|
||||
landed.push((flight.lists, flight.order));
|
||||
crate::land::spent(crate::land::stat::READ_BACKS, telling)
|
||||
}
|
||||
@@ -5125,6 +5128,14 @@ impl Host {
|
||||
let _ = self.submit(runs, &[], false);
|
||||
}
|
||||
|
||||
/// Runs a closed internal upload-only host list synchronously without
|
||||
/// draining title queues (`queue::before_sync`), so it is deadlock-safe
|
||||
/// when invoked from `VICTORY_THIN=1` worker threads. Settles in-flight
|
||||
/// GPU work and waits for the upload list's fence before returning.
|
||||
pub(crate) fn execute_sync_internal(&self, list: &HostList) {
|
||||
let _ = self.submit(&[list], &[], false);
|
||||
}
|
||||
|
||||
/// A queue's submission with [`late`]: the host lists `lists`, taken
|
||||
/// from the title's, go to the card in `order` and are not waited for.
|
||||
/// They join the line of flights and are settled, with the others in
|
||||
@@ -5382,7 +5393,7 @@ impl Host {
|
||||
let mut landed = Vec::new();
|
||||
for item in items {
|
||||
match item {
|
||||
Late::Run(flight) => {
|
||||
Late::Run(mut flight) => {
|
||||
last = flight.number;
|
||||
for &i in &flight.order {
|
||||
read_backs(flight.lists[i].host());
|
||||
@@ -5390,6 +5401,9 @@ impl Host {
|
||||
if let Some(card) = flight.card {
|
||||
self.card_done(card);
|
||||
}
|
||||
for detached in &mut flight.lists {
|
||||
detached.release_tables();
|
||||
}
|
||||
landed.push((flight.lists, flight.order));
|
||||
}
|
||||
Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
|
||||
@@ -6348,6 +6362,13 @@ impl HostList {
|
||||
self.epoch.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Whether any deferred steps or texture state transitions have been
|
||||
/// recorded into this list since creation or its last [`HostList::reset`].
|
||||
pub(crate) fn has_recorded_work(&self) -> bool {
|
||||
!self.deferred().copies.is_empty()
|
||||
|| !self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
|
||||
}
|
||||
|
||||
/// Moves a title texture's host copy to `wanted` (a host state) in this
|
||||
/// list: the host texture and the state it leaves, if that is a change.
|
||||
/// The list's first use of a texture records nothing: its prelude brings
|
||||
|
||||
@@ -295,12 +295,10 @@ pub(crate) fn amd(device: &ID3D12Device) -> bool {
|
||||
|
||||
/// Whether a record that does not fit in what is left of its list's budget
|
||||
/// takes the rest, so that every record after it runs empty too
|
||||
/// (`VICTORY_INDIRECT_REST=0`: it takes nothing, and the next one that fits
|
||||
/// runs). A list whose budget one garbage record empties loses all its later
|
||||
/// draws, and which record that is may differ from frame to frame. The frame
|
||||
/// line says how many records a frame are refused.
|
||||
/// (`VICTORY_INDIRECT_REST=1`; off by default so one oversized record takes
|
||||
/// nothing and later valid draws still run).
|
||||
fn rest() -> u32 {
|
||||
u32::from(std::env::var("VICTORY_INDIRECT_REST").map_or(true, |v| v != "0"))
|
||||
u32::from(std::env::var("VICTORY_INDIRECT_REST").is_ok_and(|v| v == "1"))
|
||||
}
|
||||
|
||||
/// The clamp compiled from `source` (ours, or in the benchmark the one it
|
||||
@@ -2607,7 +2605,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
|
||||
/// left then, and the records as clamped.
|
||||
fn four_records_of_a_group(rest: bool) -> Option<(u32, Vec<u32>)> {
|
||||
let mut warp = WarpHarness::new()?;
|
||||
let source = if rest { SOURCE.to_owned() } else { SOURCE.replace("REST ?", "false ?") };
|
||||
let source = SOURCE.replace("REST ?", if rest { "true ?" } else { "false ?" });
|
||||
let clamp = make_from(&warp.device, &source).expect("the clamp must compile on WARP");
|
||||
const KIND_DRAW: u32 = 0;
|
||||
const STRIDE: u32 = 16;
|
||||
|
||||
@@ -203,6 +203,12 @@ impl Detached {
|
||||
pub(crate) fn host(&self) -> &crate::host::HostList {
|
||||
&self.host
|
||||
}
|
||||
|
||||
/// Releases this list's dynamic descriptor slots once its GPU submission
|
||||
/// has completed, without waiting for the full `bury_lag` allocator delay.
|
||||
pub(crate) fn release_tables(&mut self) {
|
||||
self._state.tables_done();
|
||||
}
|
||||
}
|
||||
|
||||
/// A host list that has run and waits to be used again, and the bytes of
|
||||
|
||||
@@ -524,6 +524,7 @@ impl HostPipeline {
|
||||
slot == victory_shader::emit::SLOT_FAULTS
|
||||
} else {
|
||||
slot == victory_shader::emit::SLOT_STRIDES
|
||||
|| slot == victory_shader::emit::SLOT_TABLE_STRIDES
|
||||
|| slot == victory_shader::emit::SLOT_MEMORY
|
||||
};
|
||||
if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() {
|
||||
|
||||
@@ -52,7 +52,14 @@ pub(crate) fn room(memory: Option<[u64; 4]>) {
|
||||
pool.reclaim(tick, limit, true);
|
||||
}
|
||||
if let Ok(mut pool) = STAGING.try_lock() {
|
||||
pool.reclaim(tick, if pressure { 0 } else { limit }, true);
|
||||
let staging_limit = if crate::residency::critical_commit() {
|
||||
0
|
||||
} else if pressure {
|
||||
1
|
||||
} else {
|
||||
limit
|
||||
};
|
||||
pool.reclaim(tick, staging_limit, true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -379,6 +386,13 @@ pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPi
|
||||
// Copies from a buffer begin at multiples of 512.
|
||||
let bytes = bytes.next_multiple_of(512);
|
||||
let (piece, memory, again) = lock(&STAGING).take(bytes, 512, now(), || {
|
||||
// Only gate speculative bindless prefetch on staging-pool growth
|
||||
// headroom; table-bound textures and decoration bakes are sampled
|
||||
// immediately and would otherwise read uninitialized/reused VRAM.
|
||||
let speculative = crate::texture::PICKING.get().is_some() && !crate::texture::BAKING.get();
|
||||
if speculative && !crate::residency::allow_staging_growth(false) {
|
||||
return None;
|
||||
}
|
||||
let (buffer, data) = host.upload_buffer(BLOCK)?;
|
||||
crate::host::name(&buffer, || "staging of textures (a block)".into());
|
||||
Some(Upload(buffer, data))
|
||||
|
||||
@@ -3,6 +3,7 @@ use std::sync::OnceLock;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
|
||||
|
||||
const MIB: u64 = 1 << 20;
|
||||
const GIB: u64 = 1 << 30;
|
||||
static PRESSURED: AtomicBool = AtomicBool::new(false);
|
||||
static HEADROOM: AtomicU64 = AtomicU64::new(u64::MAX);
|
||||
@@ -25,30 +26,68 @@ pub(crate) fn allocation_error(error: &windows::core::Error) {
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static STAGING_DEFERRED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
pub(crate) fn note_staging_deferred() {
|
||||
STAGING_DEFERRED.set(true);
|
||||
}
|
||||
|
||||
pub(crate) fn take_staging_deferred() -> bool {
|
||||
STAGING_DEFERRED.replace(false)
|
||||
}
|
||||
|
||||
pub(crate) fn upload_refused() -> bool {
|
||||
crate::host::coarse_ms() < RETRY_UPLOAD_AT.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn has_upload_reserve(commit: u64, bake: bool) -> bool {
|
||||
commit >= if bake { 2 * GIB } else { 4 * GIB }
|
||||
fn sample_commit(now: u64) -> u64 {
|
||||
let next = NEXT_COMMIT_SAMPLE.load(Ordering::Relaxed);
|
||||
if now >= next
|
||||
&& NEXT_COMMIT_SAMPLE
|
||||
.compare_exchange(next, now.saturating_add(32), Ordering::Relaxed, Ordering::Relaxed)
|
||||
.is_ok()
|
||||
&& let Some(status) = memory_status()
|
||||
{
|
||||
AVAILABLE_COMMIT.store(status.ullAvailPageFile, Ordering::Relaxed);
|
||||
}
|
||||
AVAILABLE_COMMIT.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Leave commit for game allocations and submissions already in flight. Direct
|
||||
/// texture consumers bypass this gate. Bake prefetch gets priority over lookahead.
|
||||
fn has_upload_reserve(commit: u64, bake: bool) -> bool {
|
||||
// Keep a protective floor against Rust/game OOM aborts without starving
|
||||
// bindless world textures or one-shot ped decoration bakes when steady-state
|
||||
// commit headroom sits in the 1-4 GiB range on 32 GiB hosts.
|
||||
commit >= if bake { 256 * MIB } else { 512 * MIB }
|
||||
}
|
||||
|
||||
fn has_growth_reserve(commit: u64, bake: bool) -> bool {
|
||||
// Growing a fresh 64 MiB upload block for speculative bindless prefetch
|
||||
// requires more headroom than reusing slices already committed inside the
|
||||
// staging pool.
|
||||
commit >= if bake { 256 * MIB } else { 1024 * MIB }
|
||||
}
|
||||
|
||||
/// Leave commit for game allocations and submissions already in flight while
|
||||
/// still letting bindless textures and one-shot material bakes upload.
|
||||
pub(crate) fn admit_texture_pass(bake: bool) -> bool {
|
||||
let now = crate::host::coarse_ms();
|
||||
if now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) {
|
||||
return false;
|
||||
}
|
||||
let next = NEXT_COMMIT_SAMPLE.load(Ordering::Relaxed);
|
||||
if now >= next && NEXT_COMMIT_SAMPLE.compare_exchange(
|
||||
next, now.saturating_add(32), Ordering::Relaxed, Ordering::Relaxed,
|
||||
).is_ok() {
|
||||
if let Some(status) = memory_status() {
|
||||
AVAILABLE_COMMIT.store(status.ullAvailPageFile, Ordering::Relaxed);
|
||||
}
|
||||
has_upload_reserve(sample_commit(now), bake)
|
||||
}
|
||||
|
||||
/// Whether the staging allocator may commit a brand-new OS upload buffer
|
||||
/// (reusing existing free ranges in already-committed pool blocks stays open
|
||||
/// whenever `admit_texture_pass` is true).
|
||||
pub(crate) fn allow_staging_growth(bake: bool) -> bool {
|
||||
let now = crate::host::coarse_ms();
|
||||
if now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) {
|
||||
return false;
|
||||
}
|
||||
has_upload_reserve(AVAILABLE_COMMIT.load(Ordering::Relaxed), bake)
|
||||
has_growth_reserve(sample_commit(now), bake)
|
||||
}
|
||||
|
||||
pub(crate) fn limited_host_ram() -> bool {
|
||||
@@ -58,9 +97,9 @@ pub(crate) fn limited_host_ram() -> bool {
|
||||
|
||||
fn next_pressure(was: bool, physical: u64, commit: u64) -> bool {
|
||||
if was {
|
||||
physical < 6 * GIB || commit < 8 * GIB
|
||||
physical < 5 * GIB || commit < 6 * GIB
|
||||
} else {
|
||||
physical <= 4 * GIB || commit <= 6 * GIB
|
||||
physical <= 3 * GIB || commit <= 4 * GIB
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,13 +139,20 @@ pub(crate) fn pressured() -> bool {
|
||||
PRESSURED.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// True when OS commit headroom is critically low (< 1.5 GiB) or an allocation
|
||||
/// just failed with `E_OUTOFMEMORY`, requiring emergency throttling.
|
||||
pub(crate) fn critical_commit() -> bool {
|
||||
let now = crate::host::coarse_ms();
|
||||
now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) || sample_commit(now) < 1536 * MIB
|
||||
}
|
||||
|
||||
/// A soft per-frame admission limit. A single texture can cross it. The
|
||||
/// queue retains unserved slots so they can be retried on later frames.
|
||||
pub(crate) fn prefetch_limit(bytes: u64, pressure: bool, limited: bool, staging: u64) -> u64 {
|
||||
if pressure {
|
||||
pub(crate) fn prefetch_limit(bytes: u64, pressure: bool, critical: bool, limited: bool, staging: u64) -> u64 {
|
||||
if critical {
|
||||
bytes.min(16 << 20)
|
||||
} else if limited && staging >= GIB {
|
||||
bytes.min(32 << 20)
|
||||
} else if pressure || (limited && staging >= GIB) {
|
||||
bytes.min(64 << 20)
|
||||
} else {
|
||||
bytes
|
||||
}
|
||||
@@ -118,32 +164,38 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn bake_and_lookahead_leave_room_for_live_game_allocations() {
|
||||
for (commit, bake, lookahead) in [
|
||||
(277 << 20, false, false), (2 * GIB, true, false), (4 * GIB, true, true),
|
||||
for (commit, bake, lookahead, growth) in [
|
||||
(128 * MIB, false, false, false),
|
||||
(256 * MIB, true, false, false),
|
||||
(512 * MIB, true, true, false),
|
||||
(768 * MIB, true, true, false),
|
||||
(1024 * MIB, true, true, true),
|
||||
] {
|
||||
assert_eq!(has_upload_reserve(commit, true), bake);
|
||||
assert_eq!(has_upload_reserve(commit, false), lookahead);
|
||||
assert_eq!(has_growth_reserve(commit, false), growth);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn either_constraint_enters_pressure_and_both_must_recover() {
|
||||
assert!(next_pressure(false, 12 * GIB, 6 * GIB));
|
||||
assert!(next_pressure(false, 4 * GIB, 16 * GIB));
|
||||
assert!(next_pressure(true, 5 * GIB, 9 * GIB));
|
||||
assert!(next_pressure(true, 7 * GIB, 7 * GIB));
|
||||
assert!(!next_pressure(true, 6 * GIB, 8 * GIB));
|
||||
assert!(!next_pressure(false, 5 * GIB, 7 * GIB));
|
||||
assert!(next_pressure(false, 12 * GIB, 4 * GIB));
|
||||
assert!(next_pressure(false, 3 * GIB, 16 * GIB));
|
||||
assert!(next_pressure(true, 4 * GIB, 7 * GIB));
|
||||
assert!(next_pressure(true, 6 * GIB, 5 * GIB));
|
||||
assert!(!next_pressure(true, 5 * GIB, 6 * GIB));
|
||||
assert!(!next_pressure(false, 4 * GIB, 5 * GIB));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefetch_respects_existing_budgets_and_resumes_after_recovery() {
|
||||
assert_eq!(prefetch_limit(512 << 20, false, true, GIB), 32 << 20);
|
||||
assert_eq!(prefetch_limit(512 << 20, false, true, GIB - 1), 512 << 20);
|
||||
assert_eq!(prefetch_limit(512 << 20, false, false, 2 * GIB), 512 << 20);
|
||||
assert_eq!(prefetch_limit(0, true, false, 0), 0);
|
||||
assert_eq!(prefetch_limit(8 << 20, true, false, 0), 8 << 20);
|
||||
assert_eq!(prefetch_limit(512 << 20, true, false, 0), 16 << 20);
|
||||
assert_eq!(prefetch_limit(192 << 20, false, false, 0), 192 << 20);
|
||||
assert_eq!(prefetch_limit(512 << 20, false, false, true, GIB), 64 << 20);
|
||||
assert_eq!(prefetch_limit(512 << 20, false, false, true, GIB - 1), 512 << 20);
|
||||
assert_eq!(prefetch_limit(512 << 20, false, false, false, 2 * GIB), 512 << 20);
|
||||
assert_eq!(prefetch_limit(0, true, true, false, 0), 0);
|
||||
assert_eq!(prefetch_limit(8 << 20, true, true, false, 0), 8 << 20);
|
||||
assert_eq!(prefetch_limit(512 << 20, true, false, false, 0), 64 << 20);
|
||||
assert_eq!(prefetch_limit(512 << 20, true, true, false, 0), 16 << 20);
|
||||
assert_eq!(prefetch_limit(192 << 20, false, false, false, 0), 192 << 20);
|
||||
}
|
||||
}
|
||||
@@ -91,6 +91,11 @@ pub(crate) struct Staging {
|
||||
/// recorded again about a second later if the card has room by then
|
||||
/// ([`upload`]).
|
||||
waiting: std::sync::atomic::AtomicU64,
|
||||
/// Recorded for a one-shot decoration bake (`BAKING`): submission-time
|
||||
/// refresh must wait for title memory to stop remapping
|
||||
/// (`title_memory_reading`) instead of taking `no_wait()` /
|
||||
/// `refresh_unlocked()` or the 30-frame partial-read throttle.
|
||||
exact: std::sync::atomic::AtomicBool,
|
||||
}
|
||||
|
||||
/// What a texture's staging buffer holds: the hash of the memory detiled
|
||||
@@ -756,6 +761,10 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
|
||||
return;
|
||||
};
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let baking = BAKING.get();
|
||||
if baking {
|
||||
staging.exact.store(true, Relaxed);
|
||||
}
|
||||
let picking = PICKING.get();
|
||||
if picking.is_none() {
|
||||
// A draw samples it through a table: kept and checked from here on.
|
||||
@@ -810,8 +819,10 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
|
||||
// The host texture has the staging buffer's contents: only the check
|
||||
// at submission is left, and what it finds changed the next list that
|
||||
// samples the texture uploads (a frame late where every list of the
|
||||
// frame was recorded before that check).
|
||||
if staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) {
|
||||
// frame was recorded before that check). During a one-shot bake we
|
||||
// always record the copy so any change found at submission lands in
|
||||
// VRAM before the bake draw executes.
|
||||
if !baking && staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::copystat::add(crate::copystat::C::TexSkipped, 1);
|
||||
list.defer_texture(staging);
|
||||
@@ -1254,12 +1265,13 @@ impl Staging {
|
||||
let start = self.memory as usize;
|
||||
let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
let last = &mut *last;
|
||||
let exact = self.exact.swap(false, std::sync::atomic::Ordering::Relaxed);
|
||||
let alone = self.once.load(std::sync::atomic::Ordering::Relaxed);
|
||||
if alone && last.hash.is_some() {
|
||||
if alone && !exact && last.hash.is_some() {
|
||||
return 0;
|
||||
}
|
||||
if !alone && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) {
|
||||
if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) {
|
||||
if !exact && last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) {
|
||||
return 0;
|
||||
}
|
||||
last.asked = now;
|
||||
@@ -1303,7 +1315,7 @@ impl Staging {
|
||||
last.hot_until = frame + HOT_FRAMES;
|
||||
}
|
||||
let hot = hot_textures() && frame < last.hot_until;
|
||||
if unwritten && !turn && !hot {
|
||||
if !exact && unwritten && !turn && !hot {
|
||||
return 0;
|
||||
}
|
||||
blind = unwritten;
|
||||
@@ -1322,7 +1334,7 @@ impl Staging {
|
||||
// stays mapped (see `crate::watch::title_memory_reading`; without
|
||||
// it a page went between the asking and the read in runs 71 and
|
||||
// 74).
|
||||
let _mapped = if no_wait() {
|
||||
let _mapped = if no_wait() && !exact {
|
||||
// Not waited for: while the runtime remaps title memory the
|
||||
// texture is read through the kernel instead, whole or not at
|
||||
// all (`no_wait`).
|
||||
@@ -1342,7 +1354,7 @@ impl Staging {
|
||||
// unmapped pages is slow, and nothing tells us when pages
|
||||
// arrive): a mip that streams in shows up to 30 frames late.
|
||||
let frame = crate::frame::current();
|
||||
if last.partial.is_some_and(|at| frame < at + 30) {
|
||||
if !exact && last.partial.is_some_and(|at| frame < at + 30) {
|
||||
return 0;
|
||||
}
|
||||
last.partial = Some(frame);
|
||||
@@ -1878,6 +1890,13 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O
|
||||
let (piece, buffer, base, data) = match crate::pool::staging(host, total) {
|
||||
Some((piece, buffer, base, data)) => (Some(piece), buffer, base, data),
|
||||
None => {
|
||||
let speculative = PICKING.get().is_some() && !BAKING.get();
|
||||
if crate::residency::upload_refused()
|
||||
|| (speculative && !crate::residency::allow_staging_growth(false))
|
||||
{
|
||||
crate::residency::note_staging_deferred();
|
||||
return None;
|
||||
}
|
||||
let (buffer, data) = host.upload_buffer(total)?;
|
||||
crate::host::name(&buffer, || {
|
||||
format!(
|
||||
@@ -1919,6 +1938,7 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O
|
||||
detiled: std::sync::atomic::AtomicU32::new(0),
|
||||
judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2],
|
||||
waiting: std::sync::atomic::AtomicU64::new(0),
|
||||
exact: std::sync::atomic::AtomicBool::new(BAKING.get()),
|
||||
});
|
||||
map.insert(resource as usize, s.clone());
|
||||
Some(s)
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
//! it as any texture.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering::Relaxed};
|
||||
use std::sync::atomic::{AtomicU8, AtomicU64, AtomicUsize, Ordering::Relaxed};
|
||||
use std::sync::{Arc, Condvar, Mutex, OnceLock};
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
@@ -80,6 +80,7 @@ pub(crate) enum Taken {
|
||||
static QUEUE: (Mutex<VecDeque<Arc<Job>>>, Condvar) = (Mutex::new(VecDeque::new()), Condvar::new());
|
||||
/// Those on their way, by host copy ([`HostTexture::serial`]).
|
||||
static ON_THEIR_WAY: Mutex<Vec<(u64, Arc<Job>)>> = Mutex::new(Vec::new());
|
||||
static IN_FLIGHT: AtomicUsize = AtomicUsize::new(0);
|
||||
static LANDED: Condvar = Condvar::new();
|
||||
static BYTES: AtomicU64 = AtomicU64::new(0);
|
||||
/// Since the start: uploads, bytes, microseconds from the asking until the
|
||||
@@ -104,7 +105,7 @@ fn claim(resource: This, first: u32, there: u64) -> Option<Taken> {
|
||||
return way.iter().find(|(serial, _)| *serial == copy.serial).map(|(_, job)| Taken::Known(job.clone()));
|
||||
}
|
||||
let most = if crate::residency::limited_host_ram() { 32 << 20 } else { MOST };
|
||||
if crate::residency::pressured()
|
||||
if !crate::residency::allow_staging_growth(false)
|
||||
|| BYTES.load(Relaxed) >= most
|
||||
|| copy.flags() & 0x7 != 0
|
||||
|| copy.state.load(Relaxed) != 0
|
||||
@@ -134,7 +135,11 @@ fn claim(resource: This, first: u32, there: u64) -> Option<Taken> {
|
||||
}
|
||||
let job = Arc::new(Job { staging, copy, asked: std::time::Instant::now(), then: Mutex::new(Some(Vec::new())) });
|
||||
BYTES.fetch_add(job.staging.read as u64, Relaxed);
|
||||
ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()).push((job.copy.serial, job.clone()));
|
||||
{
|
||||
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
|
||||
way.push((job.copy.serial, job.clone()));
|
||||
IN_FLIGHT.store(way.len(), std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
Some(Taken::New(job))
|
||||
}
|
||||
|
||||
@@ -144,6 +149,25 @@ pub(crate) fn send(job: &Arc<Job>) {
|
||||
QUEUE.1.notify_one();
|
||||
}
|
||||
|
||||
/// Waits until every upload currently on its way here has finished copying
|
||||
/// and run its completion callbacks (queuing slot flips into `FLIPS`).
|
||||
/// Returns how many jobs were waited for.
|
||||
pub(crate) fn drain() -> usize {
|
||||
if IN_FLIGHT.load(std::sync::atomic::Ordering::Acquire) == 0 {
|
||||
return 0;
|
||||
}
|
||||
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let waiting = way.len();
|
||||
let started = std::time::Instant::now();
|
||||
while !way.is_empty() && started.elapsed().as_millis() < 2000 {
|
||||
way = LANDED
|
||||
.wait_timeout(way, std::time::Duration::from_millis(50))
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.0;
|
||||
}
|
||||
waiting
|
||||
}
|
||||
|
||||
/// A list is about to record an upload into `copy`: one on its way here runs
|
||||
/// first, and no other is taken after it.
|
||||
pub(crate) fn listed(copy: &HostTexture) {
|
||||
@@ -293,11 +317,6 @@ fn finish(jobs: Vec<Arc<Job>>) {
|
||||
job.copy.ahead.store(DONE, Relaxed);
|
||||
BYTES.fetch_sub(job.staging.read as u64, Relaxed);
|
||||
}
|
||||
{
|
||||
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
|
||||
way.retain(|(serial, _)| !jobs.iter().any(|job| job.copy.serial == *serial));
|
||||
LANDED.notify_all();
|
||||
}
|
||||
for job in &jobs {
|
||||
let us = job.asked.elapsed().as_micros() as u64;
|
||||
let n = STATS[0].fetch_add(1, Relaxed) + 1;
|
||||
@@ -319,6 +338,14 @@ fn finish(jobs: Vec<Arc<Job>>) {
|
||||
f();
|
||||
}
|
||||
}
|
||||
// Remove from `ON_THEIR_WAY` only after `job.then` callbacks have queued
|
||||
// their `FLIPS` entries so `drain()` observes every flip ready to apply.
|
||||
{
|
||||
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
|
||||
way.retain(|(serial, _)| !jobs.iter().any(|job| job.copy.serial == *serial));
|
||||
IN_FLIGHT.store(way.len(), std::sync::atomic::Ordering::Release);
|
||||
LANDED.notify_all();
|
||||
}
|
||||
crate::descriptor::host::flip_now();
|
||||
}
|
||||
|
||||
@@ -416,4 +443,31 @@ mod tests {
|
||||
back.Unmap(0, None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drain_waits_until_then_callbacks_have_run() {
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc};
|
||||
let Some(_host) = crate::host::host() else { return };
|
||||
let desc = [3u32, 0, 0, 0, 128, 0, 128, 0x8_0001, 98, 1, 0, 0x105, 0, 0];
|
||||
let whole = crate::resource::placed_bytes(&desc).unwrap() as usize;
|
||||
// SAFETY: memory of our own that stays for the test.
|
||||
let at = unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }.cast::<u8>();
|
||||
// SAFETY: as above.
|
||||
unsafe { std::ptr::write_bytes(at, 0x5a, whole) };
|
||||
let texture = crate::resource::texture_at(at as u64, &desc).unwrap();
|
||||
crate::resource::want_level(texture, 0);
|
||||
let copy = crate::resource::host_copy(texture).unwrap();
|
||||
if !crate::pool::fresh(©.texture) {
|
||||
return;
|
||||
}
|
||||
let Some(Taken::New(job)) = claim(texture, 0, u64::MAX) else { panic!("not taken") };
|
||||
let ran = Arc::new(AtomicBool::new(false));
|
||||
let flag = ran.clone();
|
||||
job.then(move || flag.store(true, std::sync::atomic::Ordering::Release));
|
||||
send(&job);
|
||||
assert!(drain() >= 1);
|
||||
assert!(ran.load(std::sync::atomic::Ordering::Acquire), "job.then callback must run before drain() returns");
|
||||
assert_eq!(drain(), 0);
|
||||
}
|
||||
}
|
||||
@@ -1228,12 +1228,43 @@ fn translated_compute_matches_pc() {
|
||||
let mut root_views: Vec<(u8, bool)> = cs_c.root_cbvs.iter().map(|&s| (s, false)).collect();
|
||||
root_views.extend(cs_c.root_srvs.iter().map(|&s| (s, true)));
|
||||
root_views.sort_unstable();
|
||||
let view_strides: Vec<u32> = views
|
||||
.iter()
|
||||
.map(|v| match *v {
|
||||
View::RawUav(_) => 1,
|
||||
View::HalfUav(_) => 8,
|
||||
View::Buffer { stride, .. } => match stride {
|
||||
Stride::Raw => 1,
|
||||
Stride::Typed => 16,
|
||||
Stride::Structured(s) => s,
|
||||
Stride::Format(f, bytes) => {
|
||||
let kind = match f.0 as u32 {
|
||||
3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62 => {
|
||||
super::VIEW_INTEGER
|
||||
}
|
||||
4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64 => {
|
||||
super::VIEW_INTEGER | super::VIEW_SIGNED
|
||||
}
|
||||
_ => 0,
|
||||
};
|
||||
bytes | kind
|
||||
}
|
||||
},
|
||||
_ => 0,
|
||||
})
|
||||
.collect();
|
||||
for (n, (slot, srv)) in root_views.into_iter().enumerate() {
|
||||
assert_eq!(slot, 4 + u8::from(srv), "{name}: root view");
|
||||
let data = if srv {
|
||||
root_srv.clone()
|
||||
let data = if srv
|
||||
&& (slot == super::SLOT_STRIDES || slot == super::SLOT_TABLE_STRIDES)
|
||||
{
|
||||
view_strides.clone()
|
||||
} else {
|
||||
root_cbv.clone()
|
||||
assert_eq!(slot, 4 + u8::from(srv), "{name}: root view");
|
||||
if srv {
|
||||
root_srv.clone()
|
||||
} else {
|
||||
root_cbv.clone()
|
||||
}
|
||||
};
|
||||
roots.push((1 + n as u32, Root::View { srv, data }));
|
||||
}
|
||||
|
||||
@@ -1004,6 +1004,12 @@ pub enum View<'a> {
|
||||
UintTextureUav(u32, u32),
|
||||
/// A typed RGBA16F buffer UAV of this many elements, zeroed.
|
||||
HalfUav(u32),
|
||||
/// A typed buffer UAV pre-filled with `data` (`format`, bytes per element).
|
||||
TypedUav {
|
||||
data: &'a [u32],
|
||||
format: DXGI_FORMAT,
|
||||
elem_bytes: u32,
|
||||
},
|
||||
/// A constant buffer of these dwords.
|
||||
Cbv(&'a [u32]),
|
||||
/// A buffer SRV over these dwords.
|
||||
@@ -1279,6 +1285,46 @@ impl Host {
|
||||
)?;
|
||||
uavs.push((b, None, n, rb));
|
||||
}
|
||||
View::TypedUav {
|
||||
data,
|
||||
format,
|
||||
elem_bytes,
|
||||
} => {
|
||||
let n = data.len() as u32;
|
||||
let bytes = u64::from(n) * 4;
|
||||
let elements = (bytes / u64::from(elem_bytes)) as u32;
|
||||
let b = make(
|
||||
D3D12_HEAP_TYPE_DEFAULT,
|
||||
&buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS),
|
||||
D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
)?;
|
||||
let up = upload(data)?;
|
||||
list.CopyBufferRegion(&b, 0, &up, 0, bytes);
|
||||
list.ResourceBarrier(&[transition(
|
||||
&b,
|
||||
D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
|
||||
)]);
|
||||
keep.push(up);
|
||||
let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
|
||||
Format: format,
|
||||
ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
|
||||
Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 {
|
||||
Buffer: D3D12_BUFFER_UAV {
|
||||
NumElements: elements,
|
||||
Flags: D3D12_BUFFER_UAV_FLAG_NONE,
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
};
|
||||
dev.CreateUnorderedAccessView(&b, None, Some(&desc), at);
|
||||
let rb = make(
|
||||
D3D12_HEAP_TYPE_READBACK,
|
||||
&buffer(bytes, D3D12_RESOURCE_FLAG_NONE),
|
||||
D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
)?;
|
||||
uavs.push((b, None, n, rb));
|
||||
}
|
||||
View::TextureUav(w, h) => {
|
||||
let t = make(
|
||||
D3D12_HEAP_TYPE_DEFAULT,
|
||||
|
||||
@@ -7501,7 +7501,7 @@ impl<'a> Lower<'a> {
|
||||
/// `ResourceHeap`): read from the host's table by heap slot in the
|
||||
/// current block.
|
||||
fn slot_stride(&mut self, src: &Source) -> Result<Option<V>, Why> {
|
||||
let word = self.slot_word(src)?;
|
||||
let word = self.slot_word(src, false)?;
|
||||
Ok(word.map(|word| {
|
||||
let bits = self.s.m.i32(super::shader::VIEW_STRIDE_BITS);
|
||||
self.s.m.bin(self.cur, Bin::And, word, bits)
|
||||
@@ -7509,10 +7509,9 @@ impl<'a> Lower<'a> {
|
||||
}
|
||||
|
||||
/// Whether the typed buffer view `src` names is one of an integer format,
|
||||
/// and whether a signed one, as [`Self::slot_stride`] (`None`: a view the
|
||||
/// program does not pick from the heap).
|
||||
/// and whether a signed one (`ResourceHeap` or `Table`).
|
||||
fn integer_view(&mut self, src: &Source) -> Result<Option<(V, V)>, Why> {
|
||||
let Some(word) = self.slot_word(src)? else {
|
||||
let Some(word) = self.slot_word(src, true)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let c = self.cur;
|
||||
@@ -7526,19 +7525,22 @@ impl<'a> Lower<'a> {
|
||||
}
|
||||
|
||||
/// The host's word for the buffer view `src` names: its stride and
|
||||
/// format kind ([`super::shader::SLOT_STRIDES`]).
|
||||
fn slot_word(&mut self, src: &Source) -> Result<Option<V>, Why> {
|
||||
/// format kind ([`super::shader::SLOT_STRIDES`] for `ResourceHeap`,
|
||||
/// [`super::shader::SLOT_TABLE_STRIDES`] for `Table` when `allow_table`).
|
||||
fn slot_word(&mut self, src: &Source, allow_table: bool) -> Result<Option<V>, Why> {
|
||||
let Source::Loaded { load, first } = src else {
|
||||
return Ok(None);
|
||||
};
|
||||
let heap = self
|
||||
let srv_slot = match self
|
||||
.scalar
|
||||
.get(load)
|
||||
.and_then(|a| self.x.native.layout.get(a.param))
|
||||
.is_some_and(|p| p.root == RootType::ResourceHeap);
|
||||
if !heap {
|
||||
return Ok(None);
|
||||
}
|
||||
.map(|p| p.root)
|
||||
{
|
||||
Some(RootType::ResourceHeap) => super::shader::SLOT_STRIDES,
|
||||
Some(RootType::Table) if allow_table => super::shader::SLOT_TABLE_STRIDES,
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let key = (self.cur, *load, *first);
|
||||
if let Some(&v) = self.strides.get(&key) {
|
||||
return Ok(Some(v));
|
||||
@@ -7553,7 +7555,7 @@ impl<'a> Lower<'a> {
|
||||
self.s.m.tag(slot, Tag::Clamp);
|
||||
let two = self.s.m.i32(2);
|
||||
let byte = self.s.m.bin(c, Bin::Shl, slot, two);
|
||||
let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES);
|
||||
let h = self.s.root_srv_handle(srv_slot);
|
||||
let iu = self.s.m.undef(self.s.t.i32);
|
||||
let mask = self.s.m.i8(1);
|
||||
let align = self.s.m.i32(4);
|
||||
@@ -11901,9 +11903,11 @@ impl<'a> Lower<'a> {
|
||||
// store; through a view of an integer format it is a 16-bit
|
||||
// integer, zero- or sign-extended (VIctory 4243a96a: the face
|
||||
// network keeps its halves in UINT views; its output was
|
||||
// noise). shortcut: that is known of the views a program
|
||||
// picks from the heap, not of those in its tables; and the
|
||||
// handle stays a float one, whose bits the drivers pass.
|
||||
// noise). Both `ResourceHeap` (`SLOT_STRIDES`) and `Table`
|
||||
// (`SLOT_TABLE_STRIDES`, dynamic table snapshots included)
|
||||
// populate the view-kind bits, while the handle stays a float
|
||||
// one (`0x409`), whose raw bits RTX and WARP pass bit-exact
|
||||
// without extra CFG blocks or touching non-d16 shaders.
|
||||
let integer = if typed { self.integer_view(src)? } else { None };
|
||||
let mut wide = Vec::new();
|
||||
for k in 0..count {
|
||||
|
||||
@@ -122,7 +122,7 @@ pub use lower::{host_settings, set_host_max_wave, set_host_rdna};
|
||||
pub use rect::rect_list_gs;
|
||||
pub use shader::{
|
||||
MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES,
|
||||
SLOT_STRIDES_COUNT, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
|
||||
SLOT_STRIDES_COUNT, SLOT_TABLE_STRIDES, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
|
||||
raw_views, set_raw_views, set_view_heap_limit, view_heap_limit,
|
||||
};
|
||||
|
||||
@@ -485,17 +485,45 @@ pub fn emit(
|
||||
};
|
||||
// The program in two other forms: without its early-outs, and
|
||||
// without any branch that only skips code no lane is left for.
|
||||
let form = |p: Option<ir::Program>| {
|
||||
p.and_then(|p| {
|
||||
let st = structure::structure(&p).ok()?;
|
||||
let io = io::raise(&p, native).ok()?;
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).ok()?;
|
||||
Some((p, st, io, res))
|
||||
})
|
||||
let form = |label: &str, p: Option<ir::Program>| {
|
||||
let Some(p) = p else {
|
||||
if why {
|
||||
eprintln!("WAVE64-FORM {label}: ir returned None");
|
||||
}
|
||||
return None;
|
||||
};
|
||||
let st = match structure::structure(&p) {
|
||||
Ok(st) => st,
|
||||
Err(e) => {
|
||||
if why {
|
||||
eprintln!("WAVE64-FORM {label}: structure failed: {e}");
|
||||
}
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let io = match io::raise(&p, native) {
|
||||
Ok(io) => io,
|
||||
Err(e) => {
|
||||
if why {
|
||||
eprintln!("WAVE64-FORM {label}: io::raise failed: {e}");
|
||||
}
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let res = match resource::track(&p, &native.layout, native.stage, Some(&st)) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
if why {
|
||||
eprintln!("WAVE64-FORM {label}: resource::track failed: {e}");
|
||||
}
|
||||
return None;
|
||||
}
|
||||
};
|
||||
Some((p, st, io, res))
|
||||
};
|
||||
let forms = [
|
||||
("without early-outs", form(ir::without_early_outs(p))),
|
||||
("without skips", form(ir::without_skips(p, false))),
|
||||
("without early-outs", form("without early-outs", ir::without_early_outs(p))),
|
||||
("without skips", form("without skips", ir::without_skips(p, false))),
|
||||
];
|
||||
for (name, f) in &forms {
|
||||
if let Some((p, st, io, res)) = f {
|
||||
@@ -539,7 +567,7 @@ pub fn emit(
|
||||
// lane runs, where the two host waves can exchange.
|
||||
// (`VICTORY_WAVE_DEEP_SKIPS=0` and `VICTORY_WAVE_WIDE=0` turn the two off.)
|
||||
let deep_on = std::env::var_os("VICTORY_WAVE_DEEP_SKIPS").is_none_or(|v| v != "0");
|
||||
let deep = if deep_on { form(ir::without_skips(p, true)) } else { None };
|
||||
let deep = if deep_on { form("without skips, scalars followed", ir::without_skips(p, true)) } else { None };
|
||||
if let Some((p, st, io, res)) = &deep {
|
||||
let again = emit_program(c, native, p, st, io, res);
|
||||
report("without skips, scalars followed", &again);
|
||||
@@ -700,7 +728,22 @@ fn widen(
|
||||
|| matches!(&r, Ok((_, Some(64)))) && !needs.is_empty();
|
||||
if !stuck {
|
||||
if why {
|
||||
eprintln!("WAVE64-WIDE {} branches taken wave-wide", wide.len());
|
||||
let order = ir::reverse_postorder(&p.blocks);
|
||||
let mut rpo = vec![0usize; p.blocks.len()];
|
||||
for (i, &b) in order.iter().enumerate() {
|
||||
rpo[b] = i;
|
||||
}
|
||||
let mut sorted: Vec<usize> = wide.iter().copied().collect();
|
||||
sorted.sort_unstable();
|
||||
let desc: Vec<String> = sorted
|
||||
.iter()
|
||||
.map(|&b| {
|
||||
let back = matches!(p.blocks[b].exit, ir::Exit::Branch { taken, not_taken } if rpo[taken] <= rpo[b] || rpo[not_taken] <= rpo[b]);
|
||||
let nm = p.blocks[b].insts.last().map_or("?", |i| i.name());
|
||||
format!("B{b}({nm}{})", if back { ",BACK" } else { "" })
|
||||
})
|
||||
.collect();
|
||||
eprintln!("WAVE64-WIDE {} branches taken wave-wide: [{}]", wide.len(), desc.join(", "));
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
@@ -24,6 +24,11 @@ pub const ROOT_CBV_SPACE: u32 = 1;
|
||||
/// root SRV also tells the host that the buffer views of the whole heap
|
||||
/// must be ready when it runs, not only those its tables name.
|
||||
pub const SLOT_STRIDES: u8 = 255;
|
||||
/// The same table of strides and format kinds as [`SLOT_STRIDES`], bound for
|
||||
/// shaders that only inspect views from descriptor tables (`RootType::Table`).
|
||||
/// Kept distinct from [`SLOT_STRIDES`] so the host binds the table without
|
||||
/// running the full bindless heap buffer sweep.
|
||||
pub const SLOT_TABLE_STRIDES: u8 = 252;
|
||||
/// The bits of a [`SLOT_STRIDES`] dword that hold the stride.
|
||||
pub const VIEW_STRIDE_BITS: u32 = (1 << 30) - 1;
|
||||
/// In a [`SLOT_STRIDES`] dword: a typed buffer view of an integer format
|
||||
|
||||
@@ -2057,3 +2057,337 @@ fn rdna_forms_give_what_the_spelled_out_ones_give() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`.
|
||||
const fn mubuf_idxen(op: u8, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] {
|
||||
[
|
||||
0x38 << 26 | (op as u32) << 18 | 1 << 13,
|
||||
0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32,
|
||||
]
|
||||
}
|
||||
|
||||
/// SMEM `s_load_dwordx4 s[dst:dst+3], s[base:base+1], byte_offset` (soffset = null).
|
||||
const fn s_load_dwordx4_off(dst: u8, base: u8, byte_offset: u32) -> [u32; 2] {
|
||||
[
|
||||
0x3D << 26 | 0x02 << 18 | (dst as u32) << 6 | (base as u32 >> 1),
|
||||
(125 << 25) | (byte_offset & 0x1F_FFFF),
|
||||
]
|
||||
}
|
||||
|
||||
/// Builds a compute shader whose descriptors live in a `RootType::Table` at
|
||||
/// `s4` (like `compute_graph_ops` and `ped_standard_head_cs`).
|
||||
fn build_table_typed_cs(body: &[u32], used: Vec<UsedResource>) -> HostShader {
|
||||
let mut words = Vec::new();
|
||||
words.push(s_mov_b32(5, 0x80)); // s5 = 0
|
||||
words.extend_from_slice(body);
|
||||
words.push(S_ENDPGM);
|
||||
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
let native = NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 8,
|
||||
layout: vec![RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 4,
|
||||
slot: 0,
|
||||
}],
|
||||
used,
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 5 << 1, // 5 user SGPRs: s0..s4
|
||||
threads: [4, 1, 1],
|
||||
}),
|
||||
code,
|
||||
};
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
let res =
|
||||
resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track");
|
||||
let io = io::raise(&p, &native).expect("io::raise");
|
||||
let lowered = lower::lower(&lower::Parts {
|
||||
native: &native,
|
||||
p: &p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
})
|
||||
.expect("lower");
|
||||
let shader = HostShader {
|
||||
stage: HwStage::Cs,
|
||||
dxil: lowered.dxil,
|
||||
user_data: lowered.user_data,
|
||||
samplers: lowered.samplers,
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: res.root_indexed_views,
|
||||
};
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
shader
|
||||
}
|
||||
|
||||
/// `compute_graph_ops` (facial lip-sync & wrapped submesh solver) binds
|
||||
/// `R16G16B16A16_UINT` / `R16_UINT` UAVs via `RootType::Table` (which on NVIDIA
|
||||
/// are snapshotted into dynamic descriptor slots) and reads/writes FP16 bit
|
||||
/// patterns with `buffer_load_format_d16_xyzw` and `buffer_store_format_d16_xyzw`.
|
||||
/// Verify bit-exact round-trips for UINT, SINT, and FLOAT views (including
|
||||
/// non-zero table offsets matching dynamic descriptor snapshots) on hardware
|
||||
/// GPU and WARP.
|
||||
#[test]
|
||||
fn typed_d16_table_uav_roundtrip_uint_sint_and_float() {
|
||||
use windows::Win32::Graphics::Dxgi::Common::{
|
||||
DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_SINT,
|
||||
DXGI_FORMAT_R16G16B16A16_UINT,
|
||||
};
|
||||
let _serial = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut body = Vec::new();
|
||||
// s[8:11] = table[0] (src typed UAV), s[12:15] = table[1] (dst typed UAV),
|
||||
// s[16:19] = table[2] (raw UAV dump of loaded v[2:3]).
|
||||
body.extend_from_slice(&s_load_dwordx4_off(8, 4, 0));
|
||||
body.extend_from_slice(&s_load_dwordx4_off(12, 4, 32));
|
||||
body.extend_from_slice(&s_load_dwordx4_off(16, 4, 64));
|
||||
// buffer_load_format_d16_xyzw v[2:3], v0, s[8:11], 0 idxen (op 0x83)
|
||||
body.extend_from_slice(&mubuf_idxen(0x83, 2, 0, 8));
|
||||
// buffer_store_format_d16_xyzw v[2:3], v0, s[12:15], 0 idxen (op 0x87)
|
||||
body.extend_from_slice(&mubuf_idxen(0x87, 2, 0, 12));
|
||||
// Also dump thread 0's loaded v[2:3] into raw UAV (table[2]) to verify the load itself.
|
||||
// v4 = v0 << 3 (byte offset = thread * 8)
|
||||
body.push(0x3408_0083); // v_lshlrev_b32 v4, 3, v0
|
||||
// buffer_store_dwordx2 v[2:3], v4, s[16:19], 0 offen (op 0x1D, offen bit 12)
|
||||
body.extend_from_slice(&[
|
||||
0x38 << 26 | 0x1D << 18 | 1 << 12,
|
||||
0x80 << 24 | (16u32 >> 2) << 16 | (2u32 << 8) | 4u32,
|
||||
]);
|
||||
let used = (0..3u32)
|
||||
.map(|k| UsedResource {
|
||||
kind: ResourceType::Uav,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: k * 8,
|
||||
lower_bound: k,
|
||||
stride: 4,
|
||||
dwords: 4,
|
||||
user_data: 4,
|
||||
slot: 0,
|
||||
})
|
||||
.collect();
|
||||
let shader = build_table_typed_cs(&body, used);
|
||||
assert!(
|
||||
shader.root_srvs.contains(&super::SLOT_TABLE_STRIDES),
|
||||
"table typed d16 shader should request SLOT_TABLE_STRIDES"
|
||||
);
|
||||
assert!(
|
||||
!shader.root_srvs.contains(&super::SLOT_STRIDES),
|
||||
"table-only shader must not trigger the bindless SLOT_STRIDES sweep"
|
||||
);
|
||||
|
||||
// 4 elements x 4 u16 channels = 8 u32 dwords.
|
||||
// Includes FP16 subnormal (0x0001), -0.0 (0x8000), 1.0 (0x3C00), -1.0 (0xBC00),
|
||||
// NaN (0x7E00), max u16 (0xFFFF), and arbitrary patterns.
|
||||
let uint_bits: [u32; 8] = [
|
||||
0x3C00_0001, 0x7E00_BC00,
|
||||
0xFFFF_8000, 0xABCD_1234,
|
||||
0x0002_0000, 0x7BFF_FBFF,
|
||||
0xDEAD_BEEF, 0xCAFE_BABE,
|
||||
];
|
||||
let sint_bits: [u32; 8] = [
|
||||
0xFFFF_8000, 0x7FFF_0001,
|
||||
0xC000_0000, 0x8001_7FFE,
|
||||
0xFFFF_FFFF, 0x0000_0000,
|
||||
0xFEDC_BA98, 0x7654_3210,
|
||||
];
|
||||
// Normal finite FP16 values that round-trip cleanly through f32.
|
||||
let float_bits: [u32; 8] = [
|
||||
0x4000_3C00, 0x3800_BC00, // 1.0, 2.0, -1.0, 0.5
|
||||
0xC200_3400, 0x4500_0000, // 0.25, -3.0, 0.0, 5.0
|
||||
0x3E00_BE00, 0x4400_C400, // -1.5, 1.5, -4.0, 4.0
|
||||
0x3C00_0000, 0x4200_C000, // 0.0, 1.0, -2.0, 3.0
|
||||
];
|
||||
let zeros = [0u32; 8];
|
||||
|
||||
let cases = [
|
||||
("R16G16B16A16_UINT @0", DXGI_FORMAT_R16G16B16A16_UINT, 8 | super::VIEW_INTEGER, &uint_bits, 0u32),
|
||||
("R16G16B16A16_UINT @3 (dynamic offset)", DXGI_FORMAT_R16G16B16A16_UINT, 8 | super::VIEW_INTEGER, &uint_bits, 3u32),
|
||||
("R16G16B16A16_SINT @0", DXGI_FORMAT_R16G16B16A16_SINT, 8 | super::VIEW_INTEGER | super::VIEW_SIGNED, &sint_bits, 0u32),
|
||||
("R16G16B16A16_FLOAT @0", DXGI_FORMAT_R16G16B16A16_FLOAT, 8, &float_bits, 0u32),
|
||||
];
|
||||
|
||||
for (backend, warp) in [("hardware", false), ("warp", true)] {
|
||||
let Ok(host) = Host::new(warp) else { continue };
|
||||
let (root, pso) = host
|
||||
.compute_pipeline(&shader)
|
||||
.unwrap_or_else(|e| panic!("{backend}: compute_pipeline failed: {e}"));
|
||||
for &(label, format, stride_word, input, base_slot) in &cases {
|
||||
let mut views = Vec::new();
|
||||
let mut strides = Vec::new();
|
||||
for _ in 0..base_slot {
|
||||
views.push(View::RawUav(1));
|
||||
strides.push(0u32);
|
||||
}
|
||||
let uav_base = base_slot as usize;
|
||||
views.push(View::TypedUav { data: input, format, elem_bytes: 8 });
|
||||
strides.push(stride_word);
|
||||
views.push(View::TypedUav { data: &zeros, format, elem_bytes: 8 });
|
||||
strides.push(stride_word);
|
||||
views.push(View::RawUav(8));
|
||||
strides.push(1);
|
||||
|
||||
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
for u in &shader.user_data {
|
||||
if u.root == RootType::Table && u.slot == 0 {
|
||||
ud[u.index as usize] = base_slot * 32;
|
||||
}
|
||||
}
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![
|
||||
(0, Root::Constants(ud)),
|
||||
(1, Root::View { srv: true, data: strides }),
|
||||
],
|
||||
views: &views,
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{backend} {label}: dispatch failed: {e}"));
|
||||
assert_eq!(
|
||||
out[uav_base + 2],
|
||||
input,
|
||||
"{backend} {label}: buffer_load_format_d16_xyzw mismatch"
|
||||
);
|
||||
assert_eq!(
|
||||
out[uav_base + 1],
|
||||
input,
|
||||
"{backend} {label}: buffer_store_format_d16_xyzw mismatch"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Non-`d16` typed loads (`buffer_load_format_x`) are used by
|
||||
/// `CS_BlendshapeTranslationsHSSGraphOutputExtract` (reading `HSSGraphOut`
|
||||
/// `R16_UINT`) and `CS_PedStandardSkinning_*` (reading bone indices). Verify
|
||||
/// exact integer bits for `R16_UINT`, `R16_SINT`, and `R32_UINT`.
|
||||
#[test]
|
||||
fn typed_non_d16_table_load_preserves_integer_bits() {
|
||||
use windows::Win32::Graphics::Dxgi::Common::{
|
||||
DXGI_FORMAT_R16_SINT, DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R32_UINT,
|
||||
};
|
||||
let _serial = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut body = Vec::new();
|
||||
// s[8:11] = table[0] (src typed SRV), s[12:15] = table[1] (raw UAV out)
|
||||
body.extend_from_slice(&s_load_dwordx4_off(8, 4, 0));
|
||||
body.extend_from_slice(&s_load_dwordx4_off(12, 4, 32));
|
||||
// buffer_load_format_x v2, v0, s[8:11], 0 idxen (op 0x00)
|
||||
body.extend_from_slice(&mubuf_idxen(0x00, 2, 0, 8));
|
||||
// v4 = v0 << 2 (byte offset = thread * 4)
|
||||
body.push(0x3408_0082); // v_lshlrev_b32 v4, 2, v0
|
||||
// buffer_store_dword v2, v4, s[12:15], 0 offen (op 0x1C, offen bit 12)
|
||||
body.extend_from_slice(&[
|
||||
0x38 << 26 | 0x1C << 18 | 1 << 12,
|
||||
0x80 << 24 | (12u32 >> 2) << 16 | (2u32 << 8) | 4u32,
|
||||
]);
|
||||
let used = vec![
|
||||
UsedResource {
|
||||
kind: ResourceType::Srv,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
lower_bound: 0,
|
||||
stride: 4,
|
||||
dwords: 4,
|
||||
user_data: 4,
|
||||
slot: 0,
|
||||
},
|
||||
UsedResource {
|
||||
kind: ResourceType::Uav,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 8,
|
||||
lower_bound: 1,
|
||||
stride: 4,
|
||||
dwords: 4,
|
||||
user_data: 4,
|
||||
slot: 0,
|
||||
},
|
||||
];
|
||||
let shader = build_table_typed_cs(&body, used);
|
||||
// Non-d16 typed loads stay untouched (no SLOT_TABLE_STRIDES root SRV, no
|
||||
// CFG branches) so non-d16 pixel/mesh/particle/skinning shaders keep
|
||||
// identical DXIL and pipeline cache keys while still preserving raw bits.
|
||||
assert!(
|
||||
!shader.root_srvs.contains(&super::SLOT_TABLE_STRIDES),
|
||||
"non-d16 typed load should not add SLOT_TABLE_STRIDES"
|
||||
);
|
||||
|
||||
let r16_data = [0x3C00_0001u32, 0xFFFF_BC00u32];
|
||||
let r32_data = [0xDEAD_BEEFu32, 0x0000_0001, 0x8000_0000, 0x7FFF_FFFF];
|
||||
let cases: [(&str, _, u32, &[u32], [u32; 4]); 3] = [
|
||||
(
|
||||
"R16_UINT",
|
||||
DXGI_FORMAT_R16_UINT,
|
||||
2,
|
||||
&r16_data,
|
||||
[0x0001, 0x3C00, 0xBC00, 0xFFFF],
|
||||
),
|
||||
(
|
||||
"R16_SINT",
|
||||
DXGI_FORMAT_R16_SINT,
|
||||
2,
|
||||
&r16_data,
|
||||
[0x0001, 0x3C00, 0xFFFF_BC00, 0xFFFF_FFFF],
|
||||
),
|
||||
(
|
||||
"R32_UINT",
|
||||
DXGI_FORMAT_R32_UINT,
|
||||
4,
|
||||
&r32_data,
|
||||
r32_data,
|
||||
),
|
||||
];
|
||||
|
||||
for (backend, warp) in [("hardware", false), ("warp", true)] {
|
||||
let Ok(host) = Host::new(warp) else { continue };
|
||||
let (root, pso) = host
|
||||
.compute_pipeline(&shader)
|
||||
.unwrap_or_else(|e| panic!("{backend}: compute_pipeline failed: {e}"));
|
||||
for &(label, format, elem_bytes, input, want) in &cases {
|
||||
let views = [
|
||||
View::Buffer {
|
||||
data: input,
|
||||
stride: super::host::Stride::Format(format, elem_bytes),
|
||||
},
|
||||
View::RawUav(4),
|
||||
];
|
||||
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
for u in &shader.user_data {
|
||||
if u.root == RootType::Table && u.slot == 0 {
|
||||
ud[u.index as usize] = 0;
|
||||
}
|
||||
}
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views: &views,
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{backend} {label}: dispatch failed: {e}"));
|
||||
assert_eq!(out[0], want, "{backend} {label}: buffer_load_format_x mismatch");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -227,9 +227,9 @@ pub fn track(
|
||||
let mut offset_at =
|
||||
std::collections::BTreeMap::<usize, (Vec<usize>, Vec<Value>, Vec<Site>)>::new();
|
||||
for (b, block) in p.blocks.iter().enumerate() {
|
||||
t.at.set(Some(b));
|
||||
for (i, inst) in block.insts.iter().enumerate() {
|
||||
let site = (b, i);
|
||||
t.at.set(Some(site));
|
||||
if let Some(value) = t.restored(inst, Some(b)) {
|
||||
out.restored_lanes.insert(site, value);
|
||||
}
|
||||
@@ -240,7 +240,7 @@ pub fn track(
|
||||
let mut first_lane = Vec::new();
|
||||
let mut offset = Vec::new();
|
||||
let mut descriptor = |op: &Operand, role| -> Result<(), ShaderError> {
|
||||
let source = t.descriptor(inst, op, b).map_err(fail)?;
|
||||
let source = t.descriptor(inst, op, site).map_err(fail)?;
|
||||
// A descriptor the code keeps per lane ([`Tracer::lane_copies`])
|
||||
// is the same in every lane: its loop is lowered as it stands
|
||||
// and needs no proof.
|
||||
@@ -417,8 +417,8 @@ struct Tracer<'a> {
|
||||
meets: std::cell::RefCell<Meets>,
|
||||
/// Reverse-postorder index per block.
|
||||
rpo: Vec<usize>,
|
||||
/// The block of the access being traced ([`Self::live`]).
|
||||
at: std::cell::Cell<Option<usize>>,
|
||||
/// The instruction site of the access being traced ([`Self::live`]).
|
||||
at: std::cell::Cell<Option<Site>>,
|
||||
}
|
||||
|
||||
/// What lanes are known to satisfy: each [`Bool`] where its flag is set,
|
||||
@@ -1119,8 +1119,8 @@ impl<'a> Tracer<'a> {
|
||||
self.address(lo, hi, extra)
|
||||
}
|
||||
|
||||
/// The source of the descriptor operand `op` of `inst`, in block `at`.
|
||||
fn descriptor(&self, inst: &Inst, op: &Operand, at: usize) -> Result<Source, &'static str> {
|
||||
/// The source of the descriptor operand `op` of `inst`, at `at`.
|
||||
fn descriptor(&self, inst: &Inst, op: &Operand, at: Site) -> Result<Source, &'static str> {
|
||||
let Operand::Scalar { code, dwords } = *op else {
|
||||
return Err("a descriptor not in SGPRs");
|
||||
};
|
||||
@@ -1135,8 +1135,14 @@ impl<'a> Tracer<'a> {
|
||||
{
|
||||
words = raw.to_vec();
|
||||
}
|
||||
// Only the lanes that reach the access read the descriptor.
|
||||
let mut known = Vec::from_iter(self.lanes.map(|l| (l.reach[at], true)));
|
||||
// Only the lanes that reach and run the access read the descriptor.
|
||||
let mut known = Vec::new();
|
||||
if let Some(l) = self.lanes {
|
||||
known.push((l.reach[at.0], true));
|
||||
if let Some(guard) = l.guards[at.0][at.1] {
|
||||
known.push((guard, true));
|
||||
}
|
||||
}
|
||||
self.classify(&words, &mut Vec::new(), &mut known)
|
||||
}
|
||||
|
||||
@@ -1288,7 +1294,10 @@ impl<'a> Tracer<'a> {
|
||||
let (Some(at), Some(lanes)) = (self.at.get(), self.lanes) else {
|
||||
return t;
|
||||
};
|
||||
let mut known = vec![(lanes.reach[at], true)];
|
||||
let mut known = vec![(lanes.reach[at.0], true)];
|
||||
if let Some(guard) = lanes.guards[at.0][at.1] {
|
||||
known.push((guard, true));
|
||||
}
|
||||
for _ in 0..MAX_JOINS {
|
||||
let Term::Value(v) = t else { break };
|
||||
let Some((block, i)) = self.phis[v.0 as usize] else {
|
||||
@@ -4098,4 +4107,45 @@ pub(crate) mod tests {
|
||||
assert_eq!(r.waterfall.compares.len(), 2);
|
||||
assert_eq!(r.waterfall.reads.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_guarded_access_excludes_dead_lane_edges_at_a_join() {
|
||||
// Lanes failing `v_cmp_gt_u32` clear EXEC and take `s_cbranch_execz`
|
||||
// directly to the join block without initializing the immediate
|
||||
// sampler `s[8:11]`. The join's `image_sample_lz` is guarded by EXEC,
|
||||
// so only the arm where `s[8:11]` was built can execute it.
|
||||
let code: Vec<u8> = [
|
||||
0xBE84_0300u32, // s_mov_b32 s4, s0
|
||||
0xBE85_0380, // s_mov_b32 s5, 0
|
||||
0xF40C_0302,
|
||||
0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0
|
||||
0x7E04_0D00, // v_cvt_f32_u32 v2, v0
|
||||
0x7E06_0302, // v_mov_b32 v3, v2
|
||||
0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0
|
||||
0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
|
||||
0x877E_6A7E, // s_and_b32 exec_lo, exec_lo, vcc_lo
|
||||
0xBF88_0004, // s_cbranch_execz -> join (skips 4 dwords)
|
||||
0xBE88_0380, // s_mov_b32 s8, 0
|
||||
0xBE89_0380, // s_mov_b32 s9, 0
|
||||
0xBE8A_0380, // s_mov_b32 s10, 0
|
||||
0xBE8B_0380, // s_mov_b32 s11, 0
|
||||
0xF09C_0F08,
|
||||
0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11]
|
||||
S_ENDPGM,
|
||||
]
|
||||
.iter()
|
||||
.flat_map(|w| w.to_le_bytes())
|
||||
.collect();
|
||||
let p = crate::ir::build(&code, false, 256).unwrap();
|
||||
let structured = lanes(&p).expect("structured form");
|
||||
assert!(structured.guards[2][0].is_some(), "join access must carry an EXEC guard");
|
||||
let r = track(&p, &[param(Table, 0, 1)], HwStage::Cs, Some(&structured)).unwrap();
|
||||
assert!(
|
||||
r.descriptors
|
||||
.iter()
|
||||
.any(|d| d.role == Role::Sampler && d.source == Source::Constant(vec![0; 4])),
|
||||
"guarded join should resolve the immediate sampler from the live arm: {:?}",
|
||||
r.descriptors
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user