Merge day/textures
This commit is contained in:
commit
f6e2b31ceb
20 files changed
+1887
-84
No files matched your search
@@ -514,8 +514,8 @@ pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) {
|
||||
}
|
||||
|
||||
/// Runs `f` with the host heap of the title's largest view heap, if there is
|
||||
/// one (reports: nothing is waited for).
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
/// one (nothing is waited for).
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn with_view_heap<T>(f: impl FnOnce(&host::HostHeap) -> T) -> Option<T> {
|
||||
let heaps = SHADER_HEAPS.try_read().ok()?;
|
||||
let host = heaps
|
||||
|
||||
@@ -365,6 +365,13 @@ fn neutral_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<ID3D12Res
|
||||
|
||||
static FLIPS: Mutex<Vec<Flip>> = Mutex::new(Vec::new());
|
||||
|
||||
/// 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.
|
||||
pub(crate) fn flip_now() {
|
||||
let _ = super::with_view_heap(HostHeap::texture_slots_flip);
|
||||
}
|
||||
|
||||
/// Since the start: slots made from their new view after its upload had run,
|
||||
/// and those the title had written again by then.
|
||||
pub(crate) static FLIPPED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
|
||||
@@ -754,6 +761,20 @@ pub(crate) fn remapped(at: usize, len: usize) {
|
||||
ranges.push((start, end));
|
||||
}
|
||||
|
||||
/// Ranges of memory, those that touch made one (DexNom/VIctory 921d8d3b:
|
||||
/// several threads map and write, some 5,000 ranges a frame, the same
|
||||
/// textures' over and over, and each was looked up).
|
||||
fn join(ranges: &mut Vec<(u64, u64)>) {
|
||||
ranges.sort_unstable();
|
||||
ranges.dedup_by(|next, last| {
|
||||
if next.0 > last.1 {
|
||||
return false;
|
||||
}
|
||||
last.1 = last.1.max(next.1);
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
/// Frames for which a slot a draw read through a table counts as a table's
|
||||
/// slot ([`HostHeap::tabled`]).
|
||||
const TABLED_FRAMES: u64 = 240;
|
||||
@@ -1037,6 +1058,17 @@ fn view_stride(view: &View) -> Option<u32> {
|
||||
})
|
||||
}
|
||||
|
||||
/// 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.
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
/// A buffer view's structure stride, whether it is raw, and its format;
|
||||
/// `None` if `view` is not a buffer view.
|
||||
fn view_elements(view: &View) -> Option<(u32, bool, u32)> {
|
||||
@@ -1732,10 +1764,11 @@ impl HostHeap {
|
||||
pub(crate) fn texture_slots_remapped(&self, frame: u64) -> usize {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
self.texture_slots_page_written(frame);
|
||||
let ranges = std::mem::take(&mut *REMAPPED.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
let mut ranges = std::mem::take(&mut *REMAPPED.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_in(start, end)).collect()
|
||||
@@ -2022,24 +2055,36 @@ impl HostHeap {
|
||||
/// `handle` views, or something else: until then it shows the neutral
|
||||
/// texture ([`show_after`]).
|
||||
pub(crate) fn texture_slot_show_after(&self, list: &crate::host::HostList, index: u32, handle: u64) {
|
||||
if self.show_later(index, handle) {
|
||||
self.flip(list, index, handle, Some(crate::frame::current()));
|
||||
}
|
||||
}
|
||||
|
||||
/// What slot `index` shows until the texture the record at `handle` views
|
||||
/// is shown. False: it shows it, or there is none.
|
||||
fn show_later(&self, index: u32, handle: u64) -> bool {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let key = record_key(handle);
|
||||
let view = view_at(key as u32, (key >> 32) as u32);
|
||||
let (true, Some(view)) = (key != 0, view) else {
|
||||
return;
|
||||
return false;
|
||||
};
|
||||
let stale = {
|
||||
let _made = self.made.lock(index);
|
||||
let Some(shown) = self.made.get(index) else {
|
||||
return;
|
||||
return false;
|
||||
};
|
||||
if shown == key {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
// (As `mirror`.)
|
||||
let stale = self.note_buffer(index, Some(&view), true);
|
||||
let old = view_at(shown as u32, (shown >> 32) as u32);
|
||||
if shown == 0 || !old.is_some_and(|old| same_placed_texture(&old, &view)) {
|
||||
let kept = old.is_some_and(|old| match kin(&old, &view) {
|
||||
Kin::Same => true,
|
||||
kin => kin.kept(keep_shown()),
|
||||
});
|
||||
if shown == 0 || !kept {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
note_before(index, shown, "neutral");
|
||||
self.quick_is(index, 0);
|
||||
@@ -2053,7 +2098,21 @@ impl HostHeap {
|
||||
stale
|
||||
};
|
||||
self.unmake_stale(index, stale);
|
||||
self.flip(list, index, handle, Some(crate::frame::current()));
|
||||
true
|
||||
}
|
||||
|
||||
/// [`HostHeap::texture_slot_show_after`] of a texture whose upload `job`
|
||||
/// makes: shown when that has run.
|
||||
pub(crate) fn texture_slot_show_ahead(&self, job: &crate::texture::ahead::Job, index: u32, handle: u64) {
|
||||
if !self.show_later(index, handle) {
|
||||
return;
|
||||
}
|
||||
let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle));
|
||||
let late = Some(crate::frame::current());
|
||||
job.then(move || {
|
||||
let flip = Flip { after: 0, heap, index, handle, key, late };
|
||||
FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip);
|
||||
});
|
||||
}
|
||||
|
||||
/// [`HostHeap::mirror`] of a slot whose table a draw read: a texture made
|
||||
@@ -2067,6 +2126,7 @@ impl HostHeap {
|
||||
&& let Some(View::Shader(resource, _)) = placed_texture(&view).or(Some(view))
|
||||
&& crate::resource::buffer_bytes(resource as crate::object::This).is_none()
|
||||
&& crate::resource::host_resource(resource as crate::object::This).is_some_and(crate::pool::fresh)
|
||||
&& !crate::texture::ahead::there(resource as crate::object::This)
|
||||
{
|
||||
return self.texture_slot_show_after(list, index, handle);
|
||||
}
|
||||
@@ -2131,8 +2191,14 @@ impl HostHeap {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
note_before(f.index, shown, if f.late.is_some() { "shown after its upload" } else { "flip" });
|
||||
self.put(f.index);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
let was = shown;
|
||||
self.made.set(f.index, f.key);
|
||||
self.keep(f.index, kept);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if f.late.is_some() && was != 0 {
|
||||
same_bytes(was, f.key);
|
||||
}
|
||||
if let Some(since) = f.late {
|
||||
let frames = crate::frame::current().saturating_sub(since);
|
||||
let n = LATE[0].fetch_add(1, Relaxed) + 1;
|
||||
@@ -2380,12 +2446,13 @@ impl HostHeap {
|
||||
}
|
||||
}
|
||||
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)) };
|
||||
unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0) | kind) };
|
||||
}
|
||||
let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let was = if stride.is_some() {
|
||||
@@ -2916,13 +2983,27 @@ impl HostHeap {
|
||||
// time it got sharper.
|
||||
if later
|
||||
&& keep_views()
|
||||
&& view_at(shown as u32, (shown >> 32) as u32)
|
||||
.is_some_and(|old| same_placed_texture(&old, &view))
|
||||
&& let Some(old) = view_at(shown as u32, (shown >> 32) as u32)
|
||||
{
|
||||
KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
drop(held);
|
||||
self.unmake_stale(index, stale);
|
||||
return Some(view);
|
||||
let kin = kin(&old, &view);
|
||||
if kin == Kin::Same {
|
||||
KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
drop(held);
|
||||
self.unmake_stale(index, stale);
|
||||
return Some(view);
|
||||
}
|
||||
// And of another texture that can stand for it
|
||||
// ([`keep_shown`]): black, then grey for a frame or two is
|
||||
// what popped.
|
||||
if is_texture_view(&old) {
|
||||
let kept = kin.kept(keep_shown());
|
||||
rewritten(kin, kept);
|
||||
if kept {
|
||||
drop(held);
|
||||
self.unmake_stale(index, stale);
|
||||
return Some(view);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if !self.sampler && is_texture_view(&view) {
|
||||
@@ -4016,6 +4097,160 @@ fn keep_views() -> bool {
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_VIEWS").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// What the texture view a slot is written with has to do with the one it
|
||||
/// shows.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Kin {
|
||||
/// A view of the same placed texture ([`same_placed_texture`]).
|
||||
Same,
|
||||
/// A texture of the same description placed elsewhere (moved, or one of
|
||||
/// its kind).
|
||||
Moved,
|
||||
/// One of the same format and shape in another size: the same texture
|
||||
/// with more or fewer levels, as a title streams it.
|
||||
Sized,
|
||||
/// A view of the same dimension, of another texture.
|
||||
Other,
|
||||
/// A view no shader that reads the one can read.
|
||||
None,
|
||||
}
|
||||
|
||||
impl Kin {
|
||||
/// Whether the slot goes on showing what it shows, by [`keep_shown`].
|
||||
fn kept(self, keep: u8) -> bool {
|
||||
match self {
|
||||
Kin::Same => true,
|
||||
Kin::Moved | Kin::Sized => keep >= 1,
|
||||
Kin::Other => keep >= 2,
|
||||
Kin::None => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Kin`] of the view `old`, which a slot shows, and `new`.
|
||||
fn kin(old: &View, new: &View) -> Kin {
|
||||
if same_placed_texture(old, new) {
|
||||
return Kin::Same;
|
||||
}
|
||||
if let (View::Placed(false, a, from), View::Placed(false, b, to)) = (old, new) {
|
||||
if a[0] == 1 || b[0] == 1 || from[1] != to[1] {
|
||||
return Kin::None;
|
||||
}
|
||||
// (Width, 64 bits, height, depth and levels, format: words 4 to 8.)
|
||||
if a[0] == b[0] && a[2..13] == b[2..13] {
|
||||
return Kin::Moved;
|
||||
}
|
||||
let (wide, high) = ([a[4], b[4]].map(u64::from), [a[6], b[6]].map(u64::from));
|
||||
return if from[0] == to[0] && a[0] == b[0] && wide[0] * high[1] == wide[1] * high[0] {
|
||||
Kin::Sized
|
||||
} else {
|
||||
Kin::Other
|
||||
};
|
||||
}
|
||||
let dimension = |view: &View| match view {
|
||||
View::Placed(false, resource, desc) if resource[0] != 1 => desc[1],
|
||||
View::Shader(r, Some(desc)) if crate::resource::buffer_bytes(*r as crate::object::This).is_none() => desc[1],
|
||||
_ => 0,
|
||||
};
|
||||
match (dimension(old), dimension(new)) {
|
||||
(0, _) | (_, 0) => Kin::None,
|
||||
(a, b) if a == b => Kin::Other,
|
||||
_ => Kin::None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a slot that is written with a view of another texture goes on
|
||||
/// showing the one it shows until the new one is made and its upload has run
|
||||
/// (`VICTORY_KEEP_SHOWN`): 0: never, it reads as zeros, then as the neutral
|
||||
/// texture; 1: one of the same kind in another place or size; 2: any of the
|
||||
/// same dimension.
|
||||
fn keep_shown() -> u8 {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if let Some(on) = crate::ab::pick("VICTORY_KEEP_SHOWN") {
|
||||
return if on { 2 } else { 0 };
|
||||
}
|
||||
static KEEP: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
|
||||
*KEEP.get_or_init(|| std::env::var("VICTORY_KEEP_SHOWN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1))
|
||||
}
|
||||
|
||||
/// Slots that showed a texture and were written with a view of another,
|
||||
/// since the start, by [`Kin`] (moved, sized, other, none), and those of
|
||||
/// them that kept what they showed.
|
||||
static REWRITTEN: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
|
||||
|
||||
fn rewritten(kin: Kin, kept: bool) {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let class = match kin {
|
||||
Kin::Moved | Kin::Same => 0,
|
||||
Kin::Sized => 1,
|
||||
Kin::Other => 2,
|
||||
Kin::None => 3,
|
||||
};
|
||||
REWRITTEN[class].fetch_add(1, Relaxed);
|
||||
REWRITTEN[4].fetch_add(u64::from(kept), Relaxed);
|
||||
let n: u64 = REWRITTEN[..4].iter().map(|n| n.load(Relaxed)).sum();
|
||||
if n.is_multiple_of(5000) {
|
||||
tracing::info!(
|
||||
"slots that showed a texture and were written with another, since the start: {} of the same kind elsewhere, {} of another size, {} others, {} of another dimension; {} of them kept what they showed meanwhile (VICTORY_KEEP_SHOWN)",
|
||||
REWRITTEN[0].load(Relaxed),
|
||||
REWRITTEN[1].load(Relaxed),
|
||||
REWRITTEN[2].load(Relaxed),
|
||||
REWRITTEN[3].load(Relaxed),
|
||||
REWRITTEN[4].load(Relaxed)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Diagnostics: whether a texture that a slot showed until its new one came
|
||||
/// holds the new one's bytes (the title moved it), by the bytes their host
|
||||
/// copies were filled from: equal, different, not known.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
fn same_bytes(old: u64, new: u64) {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
static SEEN: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
|
||||
let view = |key: u64| view_at(key as u32, (key >> 32) as u32);
|
||||
let (Some(old), Some(new)) = (view(old), view(new)) else {
|
||||
return;
|
||||
};
|
||||
let held = |view: &View| {
|
||||
let View::Placed(false, resource, desc) = view else {
|
||||
return None;
|
||||
};
|
||||
let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
|
||||
crate::resource::texture_held(crate::resource::texture_at_made(address, resource)?)
|
||||
};
|
||||
let class = match kin(&old, &new) {
|
||||
Kin::Moved => 0,
|
||||
Kin::Same | Kin::None => return,
|
||||
_ => 3,
|
||||
};
|
||||
let which = match (held(&old), held(&new)) {
|
||||
(Some(a), Some(b)) if a == b => 0,
|
||||
(Some(a), Some(b)) if a.0 == b.0 => 1,
|
||||
_ => 2,
|
||||
};
|
||||
SEEN[class + which].fetch_add(1, Relaxed);
|
||||
let n: u64 = SEEN.iter().map(|n| n.load(Relaxed)).sum();
|
||||
if n.is_multiple_of(1000) {
|
||||
let seen: Vec<u64> = SEEN.iter().map(|n| n.load(Relaxed)).collect();
|
||||
tracing::info!(
|
||||
"slots that went on showing another texture until the new one came, since the start: of one of the same kind elsewhere {} had the new one's bytes, {} others, {} not known; of others {}, {}, {}",
|
||||
seen[0], seen[1], seen[2], seen[3], seen[4], seen[5]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// For `crate::popwatch`, since the start: slots made null as they were
|
||||
/// written with another texture, such that kept the old one, slots given the
|
||||
/// neutral texture, slots made null as their memory was another's.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
pub(crate) fn pop_causes() -> [u64; 4] {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let all: u64 = REWRITTEN[..4].iter().map(|n| n.load(Relaxed)).sum();
|
||||
let kept = REWRITTEN[4].load(Relaxed);
|
||||
[all.saturating_sub(kept), kept, LATE[3].load(Relaxed), STALE[0].load(Relaxed)]
|
||||
}
|
||||
|
||||
/// Whether a slot already made from its record is told so without the lock
|
||||
/// (`VICTORY_QUICK_MIRROR=0`: with it, as before).
|
||||
fn quick_mirror() -> bool {
|
||||
@@ -4425,6 +4660,61 @@ mod tests {
|
||||
assert!(!same_placed_texture(&low, &View::Shader(0, None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranges_that_touch_are_one() {
|
||||
let mut ranges = vec![(40, 50), (30, 40), (35, 40), (10, 20), (45, 60), (60, 61), (1, 1)];
|
||||
join(&mut ranges);
|
||||
assert_eq!(ranges, [(1, 1), (10, 20), (30, 61)]);
|
||||
join(&mut ranges);
|
||||
assert_eq!(ranges.len(), 3);
|
||||
}
|
||||
|
||||
/// Typed buffer views of integer formats are marked in the table of
|
||||
/// strides; float, normalized, raw and structured ones are not.
|
||||
#[test]
|
||||
fn integer_typed_buffer_views_are_marked_in_the_table_of_strides() {
|
||||
use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED};
|
||||
// Format, dimension (buffer), first element, count, stride, counter, flags.
|
||||
let uav = |format, stride, flags| View::Unordered(0, 0, Some([format, 1, 0, 0, 64, stride, 0, 0, flags, 0]));
|
||||
assert_eq!(view_kind(&uav(12, 0, 0)), VIEW_INTEGER, "R16G16B16A16_UINT");
|
||||
assert_eq!(view_kind(&uav(59, 0, 0)), VIEW_INTEGER | VIEW_SIGNED, "R16_SINT");
|
||||
assert_eq!(view_kind(&uav(10, 0, 0)), 0, "R16G16B16A16_FLOAT");
|
||||
assert_eq!(view_kind(&uav(58, 0, 0)), 0, "R16_SNORM");
|
||||
assert_eq!(view_kind(&uav(39, 0, 1)), 0, "raw");
|
||||
assert_eq!(view_kind(&uav(0, 16, 0)), 0, "structured");
|
||||
assert_eq!(view_stride(&uav(12, 0, 0)), Some(8));
|
||||
}
|
||||
|
||||
/// What may stand for a texture that is not there yet: one of its kind in
|
||||
/// another place or size; another one only if asked; nothing a shader
|
||||
/// cannot read in its place.
|
||||
#[test]
|
||||
fn a_slot_shows_on_what_can_stand_for_its_new_texture() {
|
||||
let texture = [3, 0, 0, 0, 512, 0, 256, 0x8_0001, 98, 1, 0, 0x105, 0, 0];
|
||||
let view = |resource: [u32; 14], format: u32, dimension: u32, address: u32| {
|
||||
let mut desc = [0u32; 16];
|
||||
(desc[0], desc[1], desc[10], desc[11]) = (format, dimension, address, 0xb);
|
||||
View::Placed(false, resource, desc)
|
||||
};
|
||||
let old = view(texture, 98, 4, 0x1000_0000);
|
||||
let mut twice = texture;
|
||||
(twice[4], twice[6], twice[7]) = (1024, 512, 0x9_0001);
|
||||
let mut square = texture;
|
||||
square[6] = 512;
|
||||
let mut buffer = texture;
|
||||
buffer[0] = 1;
|
||||
assert_eq!(kin(&old, &view(texture, 98, 4, 0x1000_0000)), Kin::Same);
|
||||
assert_eq!(kin(&old, &view(texture, 98, 4, 0x2000_0000)), Kin::Moved);
|
||||
assert_eq!(kin(&old, &view(twice, 98, 4, 0x2000_0000)), Kin::Sized);
|
||||
assert_eq!(kin(&old, &view(square, 98, 4, 0x2000_0000)), Kin::Other);
|
||||
assert_eq!(kin(&old, &view(twice, 83, 4, 0x2000_0000)), Kin::Other);
|
||||
assert_eq!(kin(&old, &view(texture, 98, 9, 0x2000_0000)), Kin::None);
|
||||
assert_eq!(kin(&old, &view(buffer, 98, 1, 0x2000_0000)), Kin::None);
|
||||
for (kin, kept) in [(Kin::Same, [true; 3]), (Kin::Moved, [false, true, true]), (Kin::Sized, [false, true, true]), (Kin::Other, [false, false, true]), (Kin::None, [false; 3])] {
|
||||
assert_eq!([0, 1, 2].map(|keep| kin.kept(keep)), kept, "{kin:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A constant buffer view larger than the host takes is cut to what it
|
||||
/// takes: the device, which such a view removes, stays.
|
||||
#[test]
|
||||
|
||||
@@ -2404,7 +2404,7 @@ impl State {
|
||||
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) {
|
||||
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);
|
||||
}
|
||||
@@ -2422,7 +2422,27 @@ impl State {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some(view) = &view {
|
||||
// The first upload of a texture no list has used: on a queue of
|
||||
// its own, and the slot shows it as soon as that has run.
|
||||
let ahead = if late && !tabled && texture.is_some_and(crate::pool::fresh) {
|
||||
crate::texture::ahead::take(resource, first, there.filter(|_| partly.is_none()).unwrap_or(u64::MAX))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(ahead) = &ahead {
|
||||
use crate::texture::ahead::Taken;
|
||||
let (Taken::New(job) | Taken::Known(job)) = ahead;
|
||||
if let Some(handle) = heap.handle(index) {
|
||||
host.texture_slot_show_ahead(job, index, handle);
|
||||
}
|
||||
if let Taken::New(job) = ahead {
|
||||
crate::texture::ahead::send(job);
|
||||
}
|
||||
}
|
||||
let late = late && ahead.is_none();
|
||||
if let Some(view) = &view
|
||||
&& ahead.is_none()
|
||||
{
|
||||
// (What was found mapped of it a moment ago is not asked
|
||||
// again, unless the host copy may need more.)
|
||||
crate::texture::PICKING.set(Some(there.filter(|_| partly.is_none()).unwrap_or(u64::MAX)));
|
||||
|
||||
@@ -8702,6 +8702,7 @@ impl Host {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) };
|
||||
#[cfg(feature = "diagnostics")]
|
||||
let watched = crate::popwatch::take(&self.device, list, texture);
|
||||
p.panel.draw(self, copy, &back, (width, height), format);
|
||||
#[cfg(not(feature = "diagnostics"))]
|
||||
let _ = frame;
|
||||
@@ -8714,13 +8715,23 @@ impl Host {
|
||||
),
|
||||
]);
|
||||
copy.close();
|
||||
match slot {
|
||||
let flown = match slot {
|
||||
Some(i) => {
|
||||
let flown = self.execute_own(copy);
|
||||
p.ahead[i].1 = flown;
|
||||
flown
|
||||
}
|
||||
None => self.execute(&[copy]),
|
||||
None => {
|
||||
self.execute(&[copy]);
|
||||
0
|
||||
}
|
||||
};
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if let Some(taken) = watched {
|
||||
crate::popwatch::sent(taken, flown, frame);
|
||||
}
|
||||
#[cfg(not(feature = "diagnostics"))]
|
||||
let _ = flown;
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if let Some((buffer, footprint)) = capture {
|
||||
crate::capture::save_read_back(frame, &buffer, &footprint);
|
||||
|
||||
@@ -46,6 +46,8 @@ pub mod pipeline;
|
||||
mod picked;
|
||||
#[cfg(windows)]
|
||||
mod pool;
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
mod popwatch;
|
||||
#[cfg(windows)]
|
||||
mod primitive;
|
||||
pub mod query;
|
||||
|
||||
@@ -151,6 +151,17 @@ fn host_blend(blend: &D3D12_BLEND_DESC, targets: &D3D12_RT_FORMAT_ARRAY) -> D3D1
|
||||
}
|
||||
|
||||
impl GraphicsState {
|
||||
/// Whether the draws are a pass over the screen: no vertex input, no
|
||||
/// depth or stencil, a target. Such passes fill tables once; their shaders
|
||||
/// are few. (After Belobug/VIctory-Belobug-AMD 18e57db8.)
|
||||
pub(crate) fn screen_pass(&self) -> bool {
|
||||
self.inputs.is_empty()
|
||||
&& (self.depth_format == DXGI_FORMAT_UNKNOWN
|
||||
|| !self.depth.DepthEnable.as_bool() && !self.depth.StencilEnable.as_bool())
|
||||
&& self.targets.NumRenderTargets > 0
|
||||
&& self.topology == D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE
|
||||
}
|
||||
|
||||
/// Takes in one subobject of a stream: its type, then its data at +4
|
||||
/// (+8 for those holding pointers).
|
||||
///
|
||||
|
||||
@@ -13,7 +13,13 @@
|
||||
//! whose pipeline is not ready is dropped, as an untranslated one is.
|
||||
//!
|
||||
//! The default budget is half a second per title frame. A pass the title
|
||||
//! runs only once and whose pipeline takes longer is lost.
|
||||
//! runs only once and whose pipeline takes longer is lost. Passes over the
|
||||
//! screen (no vertex input, no depth) have workers and a longer budget of
|
||||
//! their own ([`screen_budget`]): the title fills its lighting tables with
|
||||
//! such draws once, at the world's first frame, and behind a world's worth of
|
||||
//! pipelines they were dropped; that run had no lamps and no diffuse light to
|
||||
//! its end (run textures-d2, the first after a new translation; Belobug
|
||||
//! 18e57db8 found the same).
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
|
||||
@@ -33,6 +39,8 @@ pub(crate) struct Pending {
|
||||
/// whether a draw or dispatch has requested it yet.
|
||||
key: String,
|
||||
used: AtomicBool,
|
||||
/// A pass over the screen ([`GraphicsState::screen_pass`]).
|
||||
screen: bool,
|
||||
}
|
||||
|
||||
// SAFETY: D3D12 objects are free-threaded; the graphics state (whose input
|
||||
@@ -50,6 +58,7 @@ impl Pending {
|
||||
}
|
||||
key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes());
|
||||
Pending {
|
||||
screen: graphics.as_ref().is_some_and(|g| g.screen_pass()),
|
||||
shaders,
|
||||
graphics,
|
||||
queue_state: AtomicU8::new(NOT_QUEUED),
|
||||
@@ -113,6 +122,21 @@ fn wait_budget() -> Duration {
|
||||
})
|
||||
}
|
||||
|
||||
/// As [`wait_budget`], for passes over the screen (`VICTORY_SCREEN_WAIT_MS`,
|
||||
/// 10 s; 0: like the others). Below the title's 30 s watchdog.
|
||||
fn screen_budget() -> Duration {
|
||||
static BUDGET: OnceLock<Duration> = OnceLock::new();
|
||||
*BUDGET.get_or_init(|| {
|
||||
let millis = std::env::var("VICTORY_SCREEN_WAIT_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(10_000);
|
||||
Duration::from_millis(millis)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether passes over the screen go before the others.
|
||||
fn screens_first() -> bool {
|
||||
!screen_budget().is_zero()
|
||||
}
|
||||
|
||||
/// Pipelines queued and not made yet.
|
||||
static WAITING: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
@@ -167,16 +191,18 @@ fn shared_budget() -> bool {
|
||||
|
||||
/// Waits for `p` while frame `frame` has budget left.
|
||||
fn wait(p: &Pending, frame: u64) {
|
||||
let budget = wait_budget();
|
||||
let screen = p.screen && screens_first();
|
||||
let budget = if screen { screen_budget() } else { wait_budget() };
|
||||
if budget.is_zero() {
|
||||
return;
|
||||
}
|
||||
// The frame the budget belongs to, and what was waited of it (or is
|
||||
// taken by a thread waiting now).
|
||||
static SPENT: Mutex<(u64, Duration)> = Mutex::new((u64::MAX, Duration::ZERO));
|
||||
// taken by a thread waiting now); of the passes over the screen too.
|
||||
static SPENT: [Mutex<(u64, Duration)>; 2] = [const { Mutex::new((u64::MAX, Duration::ZERO)) }; 2];
|
||||
let spent_of = &SPENT[usize::from(screen)];
|
||||
let shared = shared_budget();
|
||||
let left = {
|
||||
let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut spent = spent_of.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if spent.0 != frame {
|
||||
*spent = (frame, Duration::ZERO);
|
||||
}
|
||||
@@ -201,8 +227,16 @@ fn wait(p: &Pending, frame: u64) {
|
||||
}
|
||||
drop(held);
|
||||
let waited = started.elapsed().min(left);
|
||||
if screen && waited > Duration::from_millis(500) {
|
||||
tracing::info!(
|
||||
ms = waited.as_millis() as u64,
|
||||
made = p.made.get().is_some(),
|
||||
shaders = ?p.shaders,
|
||||
"a pass over the screen was waited for (VICTORY_SCREEN_WAIT_MS=0: dropped past half a second a frame)"
|
||||
);
|
||||
}
|
||||
{
|
||||
let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut spent = spent_of.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// A frame that began meanwhile has its own budget.
|
||||
if spent.0 == frame {
|
||||
if shared {
|
||||
@@ -225,6 +259,9 @@ const REQUESTED: u8 = 2;
|
||||
const MAKING: u8 = 3;
|
||||
|
||||
struct Queue {
|
||||
/// Requested passes over the screen: before all others, and the only ones
|
||||
/// [`SCREEN_WORKERS`] take.
|
||||
screen: VecDeque<Arc<Pending>>,
|
||||
early: VecDeque<Arc<Pending>>,
|
||||
requested: VecDeque<Arc<Pending>>,
|
||||
}
|
||||
@@ -232,6 +269,7 @@ struct Queue {
|
||||
impl Queue {
|
||||
const fn new() -> Self {
|
||||
Self {
|
||||
screen: VecDeque::new(),
|
||||
early: VecDeque::new(),
|
||||
requested: VecDeque::new(),
|
||||
}
|
||||
@@ -245,7 +283,9 @@ impl Queue {
|
||||
return None;
|
||||
}
|
||||
p.queue_state.store(priority, Ordering::Relaxed);
|
||||
if priority == REQUESTED {
|
||||
if priority == REQUESTED && p.screen && screens_first() {
|
||||
self.screen.push_back(p.clone());
|
||||
} else if priority == REQUESTED {
|
||||
self.requested.push_back(p.clone());
|
||||
} else {
|
||||
self.early.push_back(p.clone());
|
||||
@@ -253,12 +293,16 @@ impl Queue {
|
||||
Some(prev == NOT_QUEUED)
|
||||
}
|
||||
|
||||
fn pop(&mut self) -> Option<Arc<Pending>> {
|
||||
let p = self.requested.pop_front().or_else(|| {
|
||||
// An early entry can have been promoted and claimed already.
|
||||
std::iter::from_fn(|| self.early.pop_front())
|
||||
.find(|p| p.queue_state.load(Ordering::Relaxed) == EARLY)
|
||||
})?;
|
||||
fn pop(&mut self, screens_only: bool) -> Option<Arc<Pending>> {
|
||||
let mut p = self.screen.pop_front();
|
||||
if p.is_none() && !screens_only {
|
||||
p = self.requested.pop_front().or_else(|| {
|
||||
// An early entry can have been promoted and claimed already.
|
||||
std::iter::from_fn(|| self.early.pop_front())
|
||||
.find(|p| p.queue_state.load(Ordering::Relaxed) == EARLY)
|
||||
});
|
||||
}
|
||||
let p = p?;
|
||||
p.queue_state.store(MAKING, Ordering::Relaxed);
|
||||
Some(p)
|
||||
}
|
||||
@@ -284,14 +328,21 @@ fn start(p: &Arc<Pending>, priority: u8) {
|
||||
if new {
|
||||
PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed);
|
||||
}
|
||||
AVAILABLE.notify_one();
|
||||
if p.screen {
|
||||
AVAILABLE.notify_all();
|
||||
} else {
|
||||
AVAILABLE.notify_one();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn next() -> Arc<Pending> {
|
||||
/// Workers that make passes over the screen alone, besides the others.
|
||||
const SCREEN_WORKERS: usize = 2;
|
||||
|
||||
fn next(screens_only: bool) -> Arc<Pending> {
|
||||
let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
loop {
|
||||
if let Some(p) = queue.pop() {
|
||||
if let Some(p) = queue.pop(screens_only) {
|
||||
return p;
|
||||
}
|
||||
queue = AVAILABLE.wait(queue).unwrap_or_else(|e| e.into_inner());
|
||||
@@ -320,14 +371,16 @@ fn workers() -> bool {
|
||||
std::thread::available_parallelism().map_or(2, |n| n.get()),
|
||||
);
|
||||
tracing::info!(workers, "pipeline workers");
|
||||
for i in 0..workers {
|
||||
let screens = if screens_first() { SCREEN_WORKERS } else { 0 };
|
||||
for i in 0..workers + screens {
|
||||
let screens_only = i >= workers;
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name(format!("victory-pipelines-{i}"))
|
||||
.spawn(|| {
|
||||
.spawn(move || {
|
||||
// Below the title's own threads (loading, recording),
|
||||
// and the streaming one, which is below normal itself
|
||||
// (`VICTORY_PIPELINE_LOWEST=0`: level with it, as before).
|
||||
let lowest = std::env::var_os("VICTORY_PIPELINE_LOWEST").is_none_or(|v| v != "0");
|
||||
let lowest = !screens_only && std::env::var_os("VICTORY_PIPELINE_LOWEST").is_none_or(|v| v != "0");
|
||||
// SAFETY: a plain call on our own thread.
|
||||
unsafe {
|
||||
use windows::Win32::System::Threading::*;
|
||||
@@ -335,7 +388,7 @@ fn workers() -> bool {
|
||||
let _ = SetThreadPriority(GetCurrentThread(), priority);
|
||||
}
|
||||
loop {
|
||||
next().make();
|
||||
next(screens_only).make();
|
||||
if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 {
|
||||
drained();
|
||||
} else {
|
||||
@@ -425,10 +478,28 @@ mod tests {
|
||||
assert_eq!(queue.push(&promoted, REQUESTED), Some(false));
|
||||
assert_eq!(queue.push(&promoted, REQUESTED), None);
|
||||
|
||||
assert!(Arc::ptr_eq(&queue.pop().unwrap(), &requested));
|
||||
assert!(Arc::ptr_eq(&queue.pop().unwrap(), &promoted));
|
||||
assert!(Arc::ptr_eq(&queue.pop(false).unwrap(), &requested));
|
||||
assert!(Arc::ptr_eq(&queue.pop(false).unwrap(), &promoted));
|
||||
assert_eq!(queue.push(&promoted, REQUESTED), None);
|
||||
assert!(Arc::ptr_eq(&queue.pop().unwrap(), &earlier));
|
||||
assert!(queue.pop().is_none());
|
||||
assert!(Arc::ptr_eq(&queue.pop(false).unwrap(), &earlier));
|
||||
assert!(queue.pop(false).is_none());
|
||||
}
|
||||
|
||||
/// Passes over the screen go before all others, and workers of their own
|
||||
/// take nothing else.
|
||||
#[test]
|
||||
fn passes_over_the_screen_go_first() {
|
||||
let of = |screen| {
|
||||
let mut p = Pending::new(Vec::new(), None);
|
||||
p.screen = screen;
|
||||
Arc::new(p)
|
||||
};
|
||||
let (world, screen) = (of(false), of(true));
|
||||
let mut queue = Queue::new();
|
||||
assert_eq!(queue.push(&world, REQUESTED), Some(true));
|
||||
assert_eq!(queue.push(&screen, REQUESTED), Some(true));
|
||||
assert!(Arc::ptr_eq(&queue.pop(true).unwrap(), &screen));
|
||||
assert!(queue.pop(true).is_none());
|
||||
assert!(Arc::ptr_eq(&queue.pop(false).unwrap(), &world));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
//! Diagnostics: textures that pop. `VICTORY_POP_WATCH=<from>-<to>[,<from>-<to>..]`
|
||||
//! (seconds since the start): every presented frame in those times is read
|
||||
//! back, made small on a thread of its own and compared with its neighbours,
|
||||
//! block by block. Counted and logged:
|
||||
//! - blips: blocks that one frame shows otherwise than the frames before and
|
||||
//! after it, which agree (a texture black, grey or another one for a frame);
|
||||
//! - steps: blocks that change from one frame to the next and stay so, while
|
||||
//! most of the picture does not move;
|
||||
//! - lone blocks: blocks found in neither neighbour, wherever the camera may
|
||||
//! have moved them, while the neighbours' blocks there are found in each
|
||||
//! other (a blip while the camera moves).
|
||||
//!
|
||||
//! `VICTORY_POP_FOLDER=<folder>`: the three pictures around a frame with
|
||||
//! blips (at most 200 times) are saved there, 640 wide; with
|
||||
//! `VICTORY_POP_ALL=1` every frame's is.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
|
||||
use std::sync::{Mutex, OnceLock, mpsc};
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
|
||||
/// A small picture: so many pixels wide and high.
|
||||
const WIDE: usize = 640;
|
||||
const HIGH: usize = 360;
|
||||
/// Pixels per side of a block.
|
||||
const BLOCK: usize = 16;
|
||||
/// A block changed: so much in the mean of its pixels' largest channel change.
|
||||
const CHANGED: f32 = 10.0;
|
||||
/// A block stayed.
|
||||
const STAYED: f32 = 4.0;
|
||||
|
||||
/// `10-20,30-40` as seconds.
|
||||
fn parse(text: &str) -> Vec<(f64, f64)> {
|
||||
text.split(',')
|
||||
.filter_map(|part| {
|
||||
let (from, to) = part.trim().split_once('-')?;
|
||||
Some((from.trim().parse().ok()?, to.trim().parse().ok()?))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn asked() -> &'static [(f64, f64)] {
|
||||
static ASKED: OnceLock<Vec<(f64, f64)>> = OnceLock::new();
|
||||
ASKED.get_or_init(|| std::env::var("VICTORY_POP_WATCH").map(|v| parse(&v)).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Whether frames are watched now.
|
||||
pub(crate) fn on() -> bool {
|
||||
let asked = asked();
|
||||
if asked.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let now = crate::host::now_ms() as f64 / 1e3;
|
||||
asked.iter().any(|&(from, to)| now >= from && now < to)
|
||||
}
|
||||
|
||||
/// A frame on its way back.
|
||||
pub(crate) struct Taken {
|
||||
buffer: ID3D12Resource,
|
||||
footprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
|
||||
}
|
||||
|
||||
struct Job {
|
||||
frame: u64,
|
||||
taken: Taken,
|
||||
/// The submission that copies it.
|
||||
flown: u64,
|
||||
ms: u64,
|
||||
causes: [u64; 4],
|
||||
phase: usize,
|
||||
}
|
||||
|
||||
/// Read-back buffers not in use.
|
||||
static FREE: Mutex<Vec<Taken>> = Mutex::new(Vec::new());
|
||||
/// How far a block is looked for in a neighbour's picture, in pixels of half
|
||||
/// the small picture's size, and the side of a block there.
|
||||
const REACH: i32 = 14;
|
||||
const HALF_BLOCK: usize = BLOCK / 2;
|
||||
|
||||
/// A small picture at half its size, as brightness and two colour differences.
|
||||
fn half(rgb: &[u8]) -> Vec<[i16; 3]> {
|
||||
let (w, h) = (WIDE / 2, HIGH / 2);
|
||||
let mut out = Vec::with_capacity(w * h);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let mut s = [0i16; 3];
|
||||
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
|
||||
let at = ((y * 2 + dy) * WIDE + x * 2 + dx) * 3;
|
||||
for (s, v) in s.iter_mut().zip(&rgb[at..at + 3]) {
|
||||
*s += i16::from(*v);
|
||||
}
|
||||
}
|
||||
out.push(s.map(|s| s / 4));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Per block of `a`: how much it differs from the place in `b` that is most
|
||||
/// like it, as [`differ`] says it.
|
||||
fn moved(a: &[[i16; 3]], b: &[[i16; 3]]) -> Vec<f32> {
|
||||
let (w, h) = (WIDE / 2, HIGH / 2);
|
||||
let (across, down) = (WIDE / BLOCK, HIGH / BLOCK);
|
||||
let mut out = vec![f32::MAX; across * down];
|
||||
for (n, best) in out.iter_mut().enumerate() {
|
||||
let (bx, by) = (n % across * HALF_BLOCK, n / across * HALF_BLOCK);
|
||||
let mut least = u32::MAX;
|
||||
for dy in -REACH..=REACH {
|
||||
let y0 = by as i32 + dy;
|
||||
if y0 < 0 || y0 as usize + HALF_BLOCK > h {
|
||||
continue;
|
||||
}
|
||||
for dx in -REACH..=REACH {
|
||||
let x0 = bx as i32 + dx;
|
||||
if x0 < 0 || x0 as usize + HALF_BLOCK > w {
|
||||
continue;
|
||||
}
|
||||
let mut sum = 0u32;
|
||||
for row in 0..HALF_BLOCK {
|
||||
let ra = &a[(by + row) * w + bx..][..HALF_BLOCK];
|
||||
let rb = &b[(y0 as usize + row) * w + x0 as usize..][..HALF_BLOCK];
|
||||
sum += ra
|
||||
.iter()
|
||||
.zip(rb)
|
||||
.map(|(p, q)| (0..3).map(|i| p[i].abs_diff(q[i])).max().unwrap_or(0) as u32)
|
||||
.sum::<u32>();
|
||||
if sum >= least {
|
||||
break;
|
||||
}
|
||||
}
|
||||
least = least.min(sum);
|
||||
}
|
||||
}
|
||||
*best = least as f32 / (HALF_BLOCK * HALF_BLOCK) as f32;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Blocks of `now` found in neither neighbour, where `before` is found in
|
||||
/// `after`.
|
||||
fn lone(before: &[[i16; 3]], now: &[[i16; 3]], after: &[[i16; 3]]) -> Vec<usize> {
|
||||
let (one, two) = (moved(now, before), moved(now, after));
|
||||
let both = moved(before, after);
|
||||
// A cut on either side is none.
|
||||
if one.iter().filter(|&&d| d > CHANGED).count() * 4 > one.len()
|
||||
|| two.iter().filter(|&&d| d > CHANGED).count() * 4 > two.len()
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
(0..one.len()).filter(|&n| one[n] > CHANGED && two[n] > CHANGED && both[n] < CHANGED / 2.0).collect()
|
||||
}
|
||||
|
||||
/// Frames on their way.
|
||||
static WAITING: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Records the read-back of `texture` (in the copy-source state).
|
||||
pub(crate) fn take(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, texture: &ID3D12Resource) -> Option<Taken> {
|
||||
if !on() || WAITING.load(Relaxed) > 8 {
|
||||
return None;
|
||||
}
|
||||
let free = FREE.lock().unwrap_or_else(|e| e.into_inner()).pop();
|
||||
let Some(taken) = free else {
|
||||
let (buffer, footprint) = crate::capture::read_back(device, list, texture)?;
|
||||
return Some(Taken { buffer, footprint });
|
||||
};
|
||||
let to = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: a borrowed pointer the location never releases.
|
||||
pResource: unsafe { std::mem::transmute_copy(&taken.buffer) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: taken.footprint },
|
||||
};
|
||||
let from = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: as above.
|
||||
pResource: unsafe { std::mem::transmute_copy(texture) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
|
||||
};
|
||||
// SAFETY: an open list, live resources.
|
||||
unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
|
||||
Some(taken)
|
||||
}
|
||||
|
||||
/// The list with `taken` went to the card as submission `flown` (0: it has
|
||||
/// run). `frame`: the frame it shows.
|
||||
pub(crate) fn sent(taken: Taken, flown: u64, frame: u64) {
|
||||
static THREAD: OnceLock<Option<mpsc::Sender<Job>>> = OnceLock::new();
|
||||
let Some(to) = THREAD.get_or_init(|| {
|
||||
let (to, from) = mpsc::channel::<Job>();
|
||||
std::thread::Builder::new().name("pop watch".into()).spawn(move || watch(&from)).ok().map(|_| to)
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
WAITING.fetch_add(1, Relaxed);
|
||||
let job = Job {
|
||||
frame,
|
||||
taken,
|
||||
flown,
|
||||
ms: crate::host::now_ms(),
|
||||
causes: crate::descriptor::host::pop_causes(),
|
||||
phase: usize::from(crate::ab::pick("VICTORY_KEEP_SHOWN").unwrap_or(false))
|
||||
+ 2 * usize::from(crate::ab::pick("VICTORY_UPLOAD_AHEAD").unwrap_or(false)),
|
||||
};
|
||||
let _ = to.send(job);
|
||||
}
|
||||
|
||||
/// What was seen of the frames so far.
|
||||
#[derive(Default)]
|
||||
struct Seen {
|
||||
frames: u64,
|
||||
blips: u64,
|
||||
blip_frames: u64,
|
||||
steps: u64,
|
||||
still: u64,
|
||||
lone: u64,
|
||||
lone_frames: u64,
|
||||
}
|
||||
|
||||
struct Picture {
|
||||
frame: u64,
|
||||
ms: u64,
|
||||
causes: [u64; 4],
|
||||
phase: usize,
|
||||
rgb: Vec<u8>,
|
||||
half: Vec<[i16; 3]>,
|
||||
/// Per block: how much it differs from the frame before.
|
||||
changed: Vec<f32>,
|
||||
saved: bool,
|
||||
}
|
||||
|
||||
/// Per block, the mean of the pixels' largest channel change.
|
||||
fn differ(a: &[u8], b: &[u8]) -> Vec<f32> {
|
||||
let (across, down) = (WIDE / BLOCK, HIGH / BLOCK);
|
||||
let mut out = vec![0.0; across * down];
|
||||
for (n, sum) in out.iter_mut().enumerate() {
|
||||
let (bx, by) = (n % across * BLOCK, n / across * BLOCK);
|
||||
let mut total = 0u32;
|
||||
for y in by..by + BLOCK {
|
||||
let at = (y * WIDE + bx) * 3;
|
||||
let (ra, rb) = (&a[at..at + BLOCK * 3], &b[at..at + BLOCK * 3]);
|
||||
total += ra
|
||||
.chunks_exact(3)
|
||||
.zip(rb.chunks_exact(3))
|
||||
.map(|(p, q)| p.iter().zip(q).map(|(x, y)| u32::from(x.abs_diff(*y))).max().unwrap_or(0))
|
||||
.sum::<u32>();
|
||||
}
|
||||
*sum = total as f32 / (BLOCK * BLOCK) as f32;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The blips of `now` between `before` and `after`, and its steps (the frame
|
||||
/// before `before` had `quiet` changes): numbers of blocks. `None` for the
|
||||
/// steps if the picture moves.
|
||||
fn judge(before: &[u8], now: &[u8], after: &[u8], quiet: &[f32]) -> (usize, Option<usize>) {
|
||||
let (one, two, across) = (differ(before, now), differ(now, after), differ(before, after));
|
||||
let blips = (0..one.len())
|
||||
.filter(|&n| one[n] > CHANGED && two[n] > CHANGED && across[n] < STAYED && across[n] * 3.0 < one[n])
|
||||
.count();
|
||||
let still = one.iter().filter(|&&d| d < 3.0).count() * 10 >= one.len() * 7;
|
||||
let steps = still.then(|| {
|
||||
(0..one.len()).filter(|&n| one[n] > CHANGED && two[n] < STAYED && quiet.get(n).is_some_and(|&d| d < STAYED)).count()
|
||||
});
|
||||
(blips, steps)
|
||||
}
|
||||
|
||||
/// `width * height` 8-bit RGBA (or BGRA) pixels made small.
|
||||
fn small(rows: &[u8], width: usize, height: usize, pitch: usize, bgra: bool) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(WIDE * HIGH * 3);
|
||||
for y in 0..HIGH {
|
||||
for x in 0..WIDE {
|
||||
let mut sum = [0u32; 3];
|
||||
for sy in 0..3 {
|
||||
for sx in 0..3 {
|
||||
let px = ((x * 3 + sx) * 2 + 1) * width / (WIDE * 6);
|
||||
let py = ((y * 3 + sy) * 2 + 1) * height / (HIGH * 6);
|
||||
let p = &rows[py.min(height - 1) * pitch + px.min(width - 1) * 4..][..3];
|
||||
for (s, v) in sum.iter_mut().zip(p) {
|
||||
*s += u32::from(*v);
|
||||
}
|
||||
}
|
||||
}
|
||||
let c = sum.map(|s| (s / 9) as u8);
|
||||
out.extend(if bgra { [c[2], c[1], c[0]] } else { c });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn folder() -> Option<&'static PathBuf> {
|
||||
static FOLDER: OnceLock<Option<PathBuf>> = OnceLock::new();
|
||||
FOLDER
|
||||
.get_or_init(|| {
|
||||
let folder = PathBuf::from(std::env::var_os("VICTORY_POP_FOLDER")?);
|
||||
std::fs::create_dir_all(&folder).ok()?;
|
||||
Some(folder)
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
fn save(p: &mut Picture) {
|
||||
if p.saved {
|
||||
return;
|
||||
}
|
||||
p.saved = true;
|
||||
if let Some(folder) = folder() {
|
||||
let png = crate::capture::png(WIDE as u32, HIGH as u32, &p.rgb);
|
||||
let _ = std::fs::write(folder.join(format!("{:07}-f{}.png", p.ms, p.frame)), png);
|
||||
}
|
||||
}
|
||||
|
||||
fn watch(from: &mpsc::Receiver<Job>) {
|
||||
let all = std::env::var_os("VICTORY_POP_ALL").is_some_and(|v| v == "1");
|
||||
let mut last: VecDeque<Picture> = VecDeque::new();
|
||||
let mut seen: [Seen; 4] = Default::default();
|
||||
let mut told = crate::host::now_ms();
|
||||
let mut sets = 0;
|
||||
while let Ok(job) = from.recv() {
|
||||
while crate::host::submissions().1 < job.flown {
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
let f = job.taken.footprint.Footprint;
|
||||
let (rgba, bgra) = (matches!(f.Format.0, 27..=29), matches!(f.Format.0, 87 | 90 | 91));
|
||||
let mut data = std::ptr::null_mut();
|
||||
// SAFETY: the copy has run; the mapping spans the footprint's rows.
|
||||
let rgb = unsafe {
|
||||
if !(rgba || bgra) || job.taken.buffer.Map(0, None, Some(&mut data)).is_err() {
|
||||
WAITING.fetch_sub(1, Relaxed);
|
||||
continue;
|
||||
}
|
||||
let rows = std::slice::from_raw_parts(data.cast::<u8>(), f.RowPitch as usize * f.Height as usize);
|
||||
let rgb = small(rows, f.Width as usize, f.Height as usize, f.RowPitch as usize, bgra);
|
||||
job.taken.buffer.Unmap(0, None);
|
||||
rgb
|
||||
};
|
||||
FREE.lock().unwrap_or_else(|e| e.into_inner()).push(job.taken);
|
||||
WAITING.fetch_sub(1, Relaxed);
|
||||
// Frames that follow each other only.
|
||||
if last.back().is_some_and(|p| p.frame + 1 != job.frame) {
|
||||
last.clear();
|
||||
}
|
||||
let changed = last.back().map(|p| differ(&p.rgb, &rgb)).unwrap_or_default();
|
||||
let (frame, ms, causes, phase) = (job.frame, job.ms, job.causes, job.phase);
|
||||
let half = half(&rgb);
|
||||
last.push_back(Picture { frame, ms, causes, phase, rgb, half, changed, saved: false });
|
||||
if all && let Some(p) = last.back_mut() {
|
||||
save(p);
|
||||
}
|
||||
if last.len() > 4 {
|
||||
last.pop_front();
|
||||
}
|
||||
if let [first, before, now, after] = last.make_contiguous() {
|
||||
let (blips, steps) = judge(&before.rgb, &now.rgb, &after.rgb, &before.changed);
|
||||
let side = &mut seen[now.phase];
|
||||
side.frames += 1;
|
||||
side.blips += blips as u64;
|
||||
side.blip_frames += u64::from(blips > 0);
|
||||
side.still += u64::from(steps.is_some());
|
||||
side.steps += steps.unwrap_or(0) as u64;
|
||||
let lone = lone(&before.half, &now.half, &after.half);
|
||||
side.lone += lone.len() as u64;
|
||||
side.lone_frames += u64::from(!lone.is_empty());
|
||||
if blips > 0 || lone.len() > 1 || steps.is_some_and(|s| s > 0) {
|
||||
let since: Vec<u64> = now.causes.iter().zip(&first.causes).map(|(a, b)| a.saturating_sub(*b)).collect();
|
||||
tracing::info!(
|
||||
"pop watch: frame {} at {:.2} s: {blips} blips, {steps:?} steps, lone blocks {lone:?}; in the two frames before it [made null for another texture, kept, neutral, stale] {since:?}",
|
||||
now.frame,
|
||||
now.ms as f64 / 1e3
|
||||
);
|
||||
}
|
||||
if (blips > 0 || lone.len() > 1 || steps.is_some_and(|s| s > 2)) && sets < 200 {
|
||||
sets += 1;
|
||||
save(before);
|
||||
save(now);
|
||||
save(after);
|
||||
}
|
||||
}
|
||||
if crate::host::now_ms().saturating_sub(told) > 5000 {
|
||||
told = crate::host::now_ms();
|
||||
for (n, s) in seen.iter().enumerate().filter(|(_, s)| s.frames > 0) {
|
||||
tracing::info!(
|
||||
"pop watch, since the start, A/B VICTORY_KEEP_SHOWN {} VICTORY_UPLOAD_AHEAD {}: {} frames, blips in {} of them ({} blocks of 16x16), {} frames whose picture stood still with {} blocks stepped, lone blocks in {} frames ({} blocks)",
|
||||
n & 1,
|
||||
n >> 1,
|
||||
s.frames,
|
||||
s.blip_frames,
|
||||
s.blips,
|
||||
s.still,
|
||||
s.steps,
|
||||
s.lone_frames,
|
||||
s.lone
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn picture(color: u8) -> Vec<u8> {
|
||||
vec![color; WIDE * HIGH * 3]
|
||||
}
|
||||
|
||||
fn patch(p: &mut [u8], bx: usize, by: usize, color: u8) {
|
||||
for y in by * BLOCK..(by + 1) * BLOCK {
|
||||
let at = (y * WIDE + bx * BLOCK) * 3;
|
||||
p[at..at + BLOCK * 3].fill(color);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_frame_otherwise_is_a_blip_and_a_lasting_change_a_step() {
|
||||
let (a, mut b) = (picture(100), picture(100));
|
||||
patch(&mut b, 3, 4, 0);
|
||||
let quiet = vec![0.0; (WIDE / BLOCK) * (HIGH / BLOCK)];
|
||||
assert_eq!(judge(&a, &b, &a, &quiet), (1, Some(0)));
|
||||
assert_eq!(judge(&a, &b, &b, &quiet), (0, Some(1)));
|
||||
assert_eq!(judge(&a, &a, &a, &quiet), (0, Some(0)));
|
||||
// All of it changes: a cut, no step.
|
||||
assert_eq!(judge(&a, &picture(0), &picture(0), &quiet), (0, None));
|
||||
// What moved just before is no step either.
|
||||
assert_eq!(judge(&a, &b, &b, &vec![9.0; quiet.len()]), (0, Some(0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_one_frame_alone_shows_is_found_while_the_camera_moves() {
|
||||
// A picture of noise, moved by 6 pixels a frame.
|
||||
let at = |shift: usize| -> Vec<u8> {
|
||||
(0..HIGH)
|
||||
.flat_map(|y| (0..WIDE).map(move |x| ((x + shift) / 8 * 37 + y / 8 * 91) as u8))
|
||||
.flat_map(|v| [v, v.wrapping_mul(3), 255 - v])
|
||||
.collect()
|
||||
};
|
||||
let (a, mut b, c) = (at(0), at(8), at(16));
|
||||
assert!(lone(&half(&a), &half(&b), &half(&c)).is_empty());
|
||||
patch(&mut b, 20, 10, 128);
|
||||
assert_eq!(lone(&half(&a), &half(&b), &half(&c)), vec![10 * (WIDE / BLOCK) + 20]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn times_are_read_and_pictures_made_small() {
|
||||
assert_eq!(parse("10-20, 30.5-40"), vec![(10.0, 20.0), (30.5, 40.0)]);
|
||||
assert!(parse("x").is_empty());
|
||||
let rows: Vec<u8> = [1u8, 2, 3, 255].repeat(1280 * 720);
|
||||
let out = small(&rows, 1280, 720, 1280 * 4, true);
|
||||
assert_eq!((out.len(), &out[..3]), (WIDE * HIGH * 3, &[3u8, 2, 1][..]));
|
||||
}
|
||||
}
|
||||
@@ -1177,6 +1177,8 @@ pub(crate) struct HostTexture {
|
||||
pub(crate) grown: std::sync::atomic::AtomicBool,
|
||||
/// What the last submitted upload put in it.
|
||||
pub(crate) holds: std::sync::Arc<Holds>,
|
||||
/// Who makes its first upload (`crate::texture::ahead`).
|
||||
pub(crate) ahead: std::sync::atomic::AtomicU8,
|
||||
/// The texture's flags (asked once: the runtime takes 100 ns to say, and
|
||||
/// every texture of every draw is asked about).
|
||||
flags: u32,
|
||||
@@ -2295,6 +2297,7 @@ impl HostTexture {
|
||||
serial: SERIAL.fetch_add(1, Relaxed) + 1,
|
||||
grown: Default::default(),
|
||||
holds: Default::default(),
|
||||
ahead: crate::texture::ahead::fresh(),
|
||||
flags,
|
||||
}
|
||||
}
|
||||
@@ -2319,6 +2322,7 @@ impl HostTexture {
|
||||
serial: SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1,
|
||||
grown: Default::default(),
|
||||
holds: Default::default(),
|
||||
ahead: crate::texture::ahead::fresh(),
|
||||
flags,
|
||||
}
|
||||
}
|
||||
@@ -2968,6 +2972,13 @@ pub(crate) fn texture_at_made(address: u64, desc: &[u32; 14]) -> Option<This> {
|
||||
Some(*found as This)
|
||||
}
|
||||
|
||||
/// From which level on the title texture's host copy was filled, and from
|
||||
/// which bytes (diagnostics).
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
pub(crate) fn texture_held(resource: This) -> Option<(u32, crate::texture::Digest)> {
|
||||
*made_copy(resource)?.holds.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// The resource for a texture placed at `address` with the resource
|
||||
/// description `desc` (as words), made on first use.
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
//! (directly indexed views are not known per draw); plane 0 is uploaded
|
||||
//! (every mip and array slice), depth and stencil planes are not.
|
||||
|
||||
pub(crate) mod ahead;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
@@ -745,6 +747,7 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
|
||||
return;
|
||||
};
|
||||
let texture = ©.texture;
|
||||
ahead::listed(©);
|
||||
let Some(staging) = staging(resource, ©, first) else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
//! First uploads of textures picked by index on a copy queue of their own
|
||||
//! (`VICTORY_UPLOAD_AHEAD`): read, detiled and copied by threads of ours as
|
||||
//! soon as the texture pass has made them, and the slots that wait for them
|
||||
//! shown when the copy has run. Recorded into the pass's list, as every other
|
||||
//! upload is, the copy ran with the frame that needs it, so a slot that shows
|
||||
//! its texture only after its upload ([`crate::descriptor::host::show_after`])
|
||||
//! was black or grey in that frame, and in the next.
|
||||
//!
|
||||
//! Only a texture that no list has used is taken: made in the last second,
|
||||
//! in the common state, and never asked for an upload before
|
||||
//! ([`crate::resource::HostTexture::ahead`]). It stays in the common state
|
||||
//! (a copy queue's copies leave it there), from which the card's shaders read
|
||||
//! it as any texture.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering::Relaxed};
|
||||
use std::sync::{Arc, Condvar, Mutex, OnceLock};
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
use windows::core::Interface;
|
||||
|
||||
use super::Staging;
|
||||
use crate::object::This;
|
||||
use crate::resource::HostTexture;
|
||||
|
||||
/// [`HostTexture::ahead`]: no upload was asked for yet; one is on its way
|
||||
/// here; it has run; one was recorded into a list.
|
||||
pub(crate) const NONE: u8 = 0;
|
||||
const PENDING: u8 = 1;
|
||||
const DONE: u8 = 2;
|
||||
pub(crate) const LISTED: u8 = 3;
|
||||
|
||||
/// Bytes of title memory on their way at most: past it uploads go into the
|
||||
/// lists, as before.
|
||||
const MOST: u64 = 96 << 20;
|
||||
/// Bytes and textures of one submission at most.
|
||||
const BATCH: (u64, usize) = (16 << 20, 64);
|
||||
|
||||
/// Whether it is on (`VICTORY_UPLOAD_AHEAD`; off).
|
||||
pub(crate) fn on() -> bool {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if let Some(on) = crate::ab::pick("VICTORY_UPLOAD_AHEAD") {
|
||||
return on;
|
||||
}
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_UPLOAD_AHEAD").is_some_and(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// An upload on its way.
|
||||
pub(crate) struct Job {
|
||||
staging: Arc<Staging>,
|
||||
copy: Arc<HostTexture>,
|
||||
asked: std::time::Instant,
|
||||
/// What to do when it has run; `None`: it has.
|
||||
then: Mutex<Option<Vec<Box<dyn FnOnce() + Send>>>>,
|
||||
}
|
||||
|
||||
impl Job {
|
||||
/// Calls `f` when the copy has run: now if it has.
|
||||
pub(crate) fn then(&self, f: impl FnOnce() + Send + 'static) {
|
||||
let mut then = self.then.lock().unwrap_or_else(|e| e.into_inner());
|
||||
match then.as_mut() {
|
||||
Some(then) => then.push(Box::new(f)),
|
||||
None => {
|
||||
drop(then);
|
||||
f();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a texture asked for here gets.
|
||||
pub(crate) enum Taken {
|
||||
/// A job of its own, to be [`send`] once what follows it is added.
|
||||
New(Arc<Job>),
|
||||
/// One already on its way, or that has run.
|
||||
Known(Arc<Job>),
|
||||
}
|
||||
|
||||
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 LANDED: Condvar = Condvar::new();
|
||||
static BYTES: AtomicU64 = AtomicU64::new(0);
|
||||
/// Since the start: uploads, bytes, microseconds from the asking until the
|
||||
/// copy had run, the longest; askings turned down; waits of lists.
|
||||
static STATS: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6];
|
||||
|
||||
/// Takes the first upload of `resource`'s levels from `first` on, `there` of
|
||||
/// whose bytes are mapped (`u64::MAX`: not known). `None`: the list's.
|
||||
pub(crate) fn take(resource: This, first: u32, there: u64) -> Option<Taken> {
|
||||
if on() { claim(resource, first, there) } else { None }
|
||||
}
|
||||
|
||||
fn claim(resource: This, first: u32, there: u64) -> Option<Taken> {
|
||||
workers()?;
|
||||
let turned_down = || {
|
||||
STATS[4].fetch_add(1, Relaxed);
|
||||
None
|
||||
};
|
||||
let copy = crate::resource::host_copy(resource)?;
|
||||
if copy.ahead.load(Relaxed) == PENDING {
|
||||
let way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
|
||||
return way.iter().find(|(serial, _)| *serial == copy.serial).map(|(_, job)| Taken::Known(job.clone()));
|
||||
}
|
||||
if BYTES.load(Relaxed) >= MOST
|
||||
|| copy.flags() & 0x7 != 0
|
||||
|| copy.state.load(Relaxed) != 0
|
||||
|| copy.grown.load(Relaxed)
|
||||
|| copy.tiled.is_some()
|
||||
|| copy.holds.lock().unwrap_or_else(|e| e.into_inner()).is_some()
|
||||
|| !crate::pool::fresh(©.texture)
|
||||
|| super::host_wrote(resource as usize)
|
||||
|| crate::resource::alias_of(resource).is_some()
|
||||
{
|
||||
return turned_down();
|
||||
}
|
||||
if copy.ahead.compare_exchange(NONE, PENDING, Relaxed, Relaxed).is_err() {
|
||||
return turned_down();
|
||||
}
|
||||
super::PICKING.set(Some(there));
|
||||
let staging = super::staging(resource, ©, first);
|
||||
super::PICKING.set(None);
|
||||
let Some(staging) = staging.filter(|s| {
|
||||
!s.on_demand && s.first == s.level0 && !s.uploaded.load(Relaxed) && s.once.load(Relaxed)
|
||||
}) else {
|
||||
copy.ahead.store(LISTED, Relaxed);
|
||||
return turned_down();
|
||||
};
|
||||
if super::no_wait() && super::fill_unlocked() {
|
||||
staging.expected.store(if there == u64::MAX { super::mapped_bytes(staging.memory, staging.read) } else { there }, Relaxed);
|
||||
}
|
||||
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()));
|
||||
Some(Taken::New(job))
|
||||
}
|
||||
|
||||
/// Sends a job of [`take`] on its way.
|
||||
pub(crate) fn send(job: &Arc<Job>) {
|
||||
QUEUE.0.lock().unwrap_or_else(|e| e.into_inner()).push_back(job.clone());
|
||||
QUEUE.1.notify_one();
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
if copy.ahead.compare_exchange(NONE, LISTED, Relaxed, Relaxed) != Err(PENDING) {
|
||||
return;
|
||||
}
|
||||
STATS[5].fetch_add(1, Relaxed);
|
||||
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let started = std::time::Instant::now();
|
||||
while way.iter().any(|(serial, _)| *serial == copy.serial) && started.elapsed().as_millis() < 1000 {
|
||||
way = LANDED.wait_timeout(way, std::time::Duration::from_millis(50)).unwrap_or_else(|e| e.into_inner()).0;
|
||||
}
|
||||
}
|
||||
|
||||
/// The copy queue and its threads, made on first use.
|
||||
fn workers() -> Option<&'static ID3D12CommandQueue> {
|
||||
/// Free-threaded.
|
||||
struct Queue(ID3D12CommandQueue);
|
||||
// SAFETY: a command queue is free-threaded.
|
||||
unsafe impl Send for Queue {}
|
||||
// SAFETY: as above.
|
||||
unsafe impl Sync for Queue {}
|
||||
static WORKERS: OnceLock<Option<Queue>> = OnceLock::new();
|
||||
WORKERS
|
||||
.get_or_init(|| {
|
||||
let host = crate::host::host()?;
|
||||
// SAFETY: plain object creation.
|
||||
let queue: ID3D12CommandQueue = unsafe {
|
||||
host.device
|
||||
.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
|
||||
Type: D3D12_COMMAND_LIST_TYPE_COPY,
|
||||
..Default::default()
|
||||
})
|
||||
.ok()?
|
||||
};
|
||||
for n in 0..2 {
|
||||
let worker = Worker::new(&host.device, queue.clone()).ok()?;
|
||||
std::thread::Builder::new().name(format!("uploads ahead {n}")).spawn(move || worker.work()).ok()?;
|
||||
}
|
||||
Some(Queue(queue))
|
||||
})
|
||||
.as_ref()
|
||||
.map(|q| &q.0)
|
||||
}
|
||||
|
||||
struct Worker {
|
||||
queue: ID3D12CommandQueue,
|
||||
allocator: ID3D12CommandAllocator,
|
||||
list: ID3D12GraphicsCommandList,
|
||||
fence: ID3D12Fence,
|
||||
}
|
||||
|
||||
// SAFETY: a worker's objects are its thread's own; the queue is free-threaded.
|
||||
unsafe impl Send for Worker {}
|
||||
|
||||
impl Worker {
|
||||
fn new(device: &ID3D12Device, queue: ID3D12CommandQueue) -> windows::core::Result<Worker> {
|
||||
// SAFETY: plain object creation.
|
||||
unsafe {
|
||||
let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
|
||||
let list: ID3D12GraphicsCommandList =
|
||||
device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
|
||||
list.Close()?;
|
||||
Ok(Worker { queue, allocator, list, fence: device.CreateFence(0, D3D12_FENCE_FLAG_NONE)? })
|
||||
}
|
||||
}
|
||||
|
||||
fn work(self) {
|
||||
let mut value = 0;
|
||||
loop {
|
||||
let mut jobs = Vec::new();
|
||||
{
|
||||
let mut queue = QUEUE.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||
while queue.is_empty() {
|
||||
queue = QUEUE.1.wait(queue).unwrap_or_else(|e| e.into_inner());
|
||||
}
|
||||
let mut bytes = 0;
|
||||
while bytes < BATCH.0 && jobs.len() < BATCH.1
|
||||
&& let Some(job) = queue.pop_front()
|
||||
{
|
||||
bytes += job.staging.read as u64;
|
||||
jobs.push(job);
|
||||
}
|
||||
}
|
||||
value += 1;
|
||||
if let Err(e) = self.copy(&jobs, value) {
|
||||
tracing::warn!(error = %e, "uploads ahead did not run");
|
||||
}
|
||||
finish(jobs);
|
||||
}
|
||||
}
|
||||
|
||||
fn copy(&self, jobs: &[Arc<Job>], value: u64) -> windows::core::Result<()> {
|
||||
for job in jobs {
|
||||
job.staging.refresh();
|
||||
}
|
||||
// SAFETY: this worker's allocator and list, whose last submission has
|
||||
// run; the jobs hold what the list names until after the wait.
|
||||
unsafe {
|
||||
self.allocator.Reset()?;
|
||||
self.list.Reset(&self.allocator, None)?;
|
||||
for job in jobs {
|
||||
job.record(&self.list);
|
||||
}
|
||||
self.list.Close()?;
|
||||
self.queue.ExecuteCommandLists(&[Some(self.list.cast()?)]);
|
||||
self.queue.Signal(&self.fence, value)?;
|
||||
// (Without an event: this waits.)
|
||||
self.fence.SetEventOnCompletion(value, windows::Win32::Foundation::HANDLE::default())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Job {
|
||||
/// # Safety
|
||||
/// `list` is an open copy list, and the job lives until it has run.
|
||||
unsafe fn record(&self, list: &ID3D12GraphicsCommandList) {
|
||||
let (s, texture) = (&self.staging, &self.copy.texture);
|
||||
for (i, footprint) in s.footprints.iter().enumerate() {
|
||||
let to = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: a borrowed pointer the location never releases.
|
||||
pResource: unsafe { std::mem::transmute_copy(texture) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: s.first - s.level0 + i as u32 },
|
||||
};
|
||||
let from = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: as above.
|
||||
pResource: unsafe { std::mem::transmute_copy(&s.buffer) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
|
||||
PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: s.base + footprint.Offset, ..*footprint },
|
||||
},
|
||||
};
|
||||
// SAFETY: the caller's.
|
||||
unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The jobs' copies have run.
|
||||
fn finish(jobs: Vec<Arc<Job>>) {
|
||||
for job in &jobs {
|
||||
job.staging.uploaded.store(true, Relaxed);
|
||||
job.staging.dirty.store(false, Relaxed);
|
||||
job.staging.note_held();
|
||||
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;
|
||||
let bytes = STATS[1].fetch_add(job.staging.read as u64, Relaxed) + job.staging.read as u64;
|
||||
let all = STATS[2].fetch_add(us, Relaxed) + us;
|
||||
let most = STATS[3].fetch_max(us, Relaxed).max(us);
|
||||
if n == 1 || n.is_multiple_of(5000) {
|
||||
tracing::info!(
|
||||
"textures uploaded ahead of the lists (VICTORY_UPLOAD_AHEAD=1), since the start: {n}, {} MB, {:.1} ms from the asking until they were there, the longest {:.0}; {} turned down, {} waited for by lists",
|
||||
bytes >> 20,
|
||||
all as f64 / n as f64 / 1e3,
|
||||
most as f64 / 1e3,
|
||||
STATS[4].load(Relaxed),
|
||||
STATS[5].load(Relaxed)
|
||||
);
|
||||
}
|
||||
let then = job.then.lock().unwrap_or_else(|e| e.into_inner()).take();
|
||||
for f in then.into_iter().flatten() {
|
||||
f();
|
||||
}
|
||||
}
|
||||
crate::descriptor::host::flip_now();
|
||||
}
|
||||
|
||||
/// Whether `resource`'s host copy was filled here: no list still brings what
|
||||
/// it shows.
|
||||
pub(crate) fn there(resource: This) -> bool {
|
||||
crate::resource::made_copy(resource).is_some_and(|copy| copy.ahead.load(Relaxed) == DONE)
|
||||
}
|
||||
|
||||
/// The state of [`HostTexture::ahead`] of a new host copy.
|
||||
pub(crate) fn fresh() -> AtomicU8 {
|
||||
AtomicU8::new(NONE)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The texels of a placed texture arrive by the copy queue, all levels of
|
||||
/// them, and what waits for them is called then; a second asking finds the
|
||||
/// first on its way, and a later one is the list's.
|
||||
#[test]
|
||||
fn a_placed_texture_is_filled_ahead_of_the_lists() {
|
||||
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc};
|
||||
let Some(host) = crate::host::host() else { return };
|
||||
// 256x256 BC7, nine levels.
|
||||
let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0];
|
||||
let whole = crate::resource::placed_bytes(&desc).unwrap() as usize;
|
||||
// SAFETY: memory of our own that stays.
|
||||
let at = unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }.cast::<u8>();
|
||||
// SAFETY: as above.
|
||||
unsafe { (0..whole).for_each(|i| at.add(i).write((i * 13 + i / 509) as u8)) };
|
||||
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;
|
||||
}
|
||||
assert!(!there(texture));
|
||||
let Some(Taken::New(job)) = claim(texture, 0, u64::MAX) else { panic!("not taken") };
|
||||
let (told, heard) = std::sync::mpsc::channel();
|
||||
let also = told.clone();
|
||||
let Some(Taken::Known(same)) = claim(texture, 0, u64::MAX) else { panic!("not known") };
|
||||
assert!(Arc::ptr_eq(&job, &same));
|
||||
job.then(move || told.send(1).unwrap());
|
||||
same.then(move || also.send(2).unwrap());
|
||||
send(&job);
|
||||
let wait = std::time::Duration::from_secs(20);
|
||||
assert_eq!((heard.recv_timeout(wait), heard.recv_timeout(wait)), (Ok(1), Ok(2)));
|
||||
assert!(there(texture) && claim(texture, 0, u64::MAX).is_none());
|
||||
// Level 0 as the card has it, and as the layout says.
|
||||
let layout = crate::resource::texture_memory(texture)
|
||||
.and_then(|(_, d)| crate::resource::texture_layout(&d).map(|t| t.planes[0].layout.clone()))
|
||||
.unwrap();
|
||||
let (pitch, rows) = (1024usize, 64usize);
|
||||
let mut expected = vec![0u8; pitch * rows];
|
||||
// SAFETY: the memory above.
|
||||
let tiled = unsafe { std::slice::from_raw_parts(at, whole) };
|
||||
layout.detile(tiled, 0, 0, &mut expected, pitch, pitch * rows).unwrap();
|
||||
let back = host.read_back_buffer((pitch * rows) as u64).unwrap();
|
||||
let list = host.new_list().unwrap();
|
||||
list.close();
|
||||
list.reset();
|
||||
let footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
|
||||
Offset: 0,
|
||||
Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
|
||||
Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(98),
|
||||
Width: 256,
|
||||
Height: 256,
|
||||
Depth: 1,
|
||||
RowPitch: pitch as u32,
|
||||
},
|
||||
};
|
||||
let to = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: a borrowed pointer the location never releases.
|
||||
pResource: unsafe { std::mem::transmute_copy(&back) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint },
|
||||
};
|
||||
let from = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: as above.
|
||||
pResource: unsafe { std::mem::transmute_copy(©.texture) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
|
||||
};
|
||||
// SAFETY: an open list, live resources; the mapping spans the buffer.
|
||||
unsafe {
|
||||
list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None);
|
||||
list.close();
|
||||
host.execute(&[&list]);
|
||||
let mut data = std::ptr::null_mut();
|
||||
back.Map(0, None, Some(&mut data)).unwrap();
|
||||
let seen = std::slice::from_raw_parts(data.cast::<u8>(), pitch * rows);
|
||||
assert!(seen == expected.as_slice(), "level 0's blocks");
|
||||
back.Unmap(0, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
use std::alloc::{Layout, alloc, dealloc};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::ffi::c_void;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, LazyLock, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
|
||||
|
||||
use windows_sys::Win32::Foundation::{
|
||||
@@ -1090,6 +1090,7 @@ pub extern "system" fn XMemMapPhysicalPages(
|
||||
let pages = (!pages.is_null()).then(|| unsafe { std::slice::from_raw_parts(pages, n) }.to_vec());
|
||||
let mut costed = Costed::begin(Some(n));
|
||||
let _called = victory_gpu::timeline::span("the title's XMemMapPhysicalPages");
|
||||
let _busy = Busy::begin();
|
||||
let mut physical = physical();
|
||||
if let Some(costed) = &mut costed {
|
||||
costed.waited = costed.started.elapsed().as_nanos() as u64;
|
||||
@@ -1179,6 +1180,7 @@ pub extern "system" fn XMemMapPhysicalPagesScatter(
|
||||
pub fn map_alias(to: u64, from: u64, len: u64) -> bool {
|
||||
let (to, from, len) = (to as usize, from as usize, len as usize);
|
||||
let _costed = Costed::begin(None);
|
||||
let _busy = Busy::begin();
|
||||
let mut physical = physical();
|
||||
// As in `XMemMapPhysicalPages`: no read in place meets the gap.
|
||||
let _changing = victory_gpu::title_memory_remapping();
|
||||
@@ -1218,6 +1220,7 @@ pub fn map_aliases(ranges: &[(u64, u64, u64)]) -> bool {
|
||||
let mut ok = true;
|
||||
let mut at = 0;
|
||||
while at < pages.len() {
|
||||
let _busy = Busy::begin();
|
||||
let mut physical = physical();
|
||||
let mut ops: Vec<Op> = Vec::new();
|
||||
let mut touched = std::collections::HashSet::new();
|
||||
@@ -1245,6 +1248,7 @@ fn scatter(wanted: &[(usize, usize)]) -> bool {
|
||||
let mut ok = true;
|
||||
let mut at = 0;
|
||||
while at < wanted.len() {
|
||||
let _busy = Busy::begin();
|
||||
let mut costed = Costed::begin(None);
|
||||
let mut ops: Vec<Op> = Vec::new();
|
||||
let mut physical = physical();
|
||||
@@ -1280,7 +1284,9 @@ fn scatter(wanted: &[(usize, usize)]) -> bool {
|
||||
const GROUP: usize = 64;
|
||||
|
||||
/// How many threads map a group of pages side by side (`VICTORY_MAP_THREADS`;
|
||||
/// 1: the caller alone, a page after the other, as before).
|
||||
/// 1: the caller alone, a page after the other, as before; `auto`, which it
|
||||
/// is unless set: 1 while mapping takes little of the time, [`WIDE`] while the
|
||||
/// title streams as fast as its pages are mapped, [`Busy`]).
|
||||
///
|
||||
/// Mapping and unmapping a view wait for a lock that every protection change
|
||||
/// of a view takes too, and our guards make 100,000 of those a second, from
|
||||
@@ -1293,10 +1299,74 @@ fn side_by_side() -> usize {
|
||||
if let Some(on) = victory_gpu::switched("VICTORY_MAP_THREADS") {
|
||||
return if on { 8 } else { 1 };
|
||||
}
|
||||
static THREADS: LazyLock<usize> = LazyLock::new(|| {
|
||||
std::env::var("VICTORY_MAP_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(8).clamp(1, 32)
|
||||
match asked_threads() {
|
||||
Some(n) => n,
|
||||
None if BUSY.2.load(Ordering::Relaxed) => WIDE,
|
||||
None => 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Threads while the title streams fast: they stand in the host's queue side
|
||||
/// by side, each for a millisecond or two a page in the world's first seconds.
|
||||
const WIDE: usize = 16;
|
||||
|
||||
/// `VICTORY_MAP_THREADS` as a number; `None`: by how much there is to map.
|
||||
fn asked_threads() -> Option<usize> {
|
||||
static ASKED: LazyLock<Option<usize>> = LazyLock::new(|| {
|
||||
std::env::var("VICTORY_MAP_THREADS").ok().and_then(|v| v.trim().parse().ok()).map(|n: usize| n.clamp(1, 32))
|
||||
});
|
||||
*THREADS
|
||||
*ASKED
|
||||
}
|
||||
|
||||
/// Of the window under way: when it began, the nanoseconds spent mapping in
|
||||
/// it; and whether the last one was busy.
|
||||
static BUSY: (Mutex<Option<std::time::Instant>>, AtomicU64, std::sync::atomic::AtomicBool) =
|
||||
(Mutex::new(None), AtomicU64::new(0), std::sync::atomic::AtomicBool::new(false));
|
||||
|
||||
/// Counts the time a mapping call of the title's takes, as long as it lives.
|
||||
/// More than a quarter of a window, and the calls are what loading waits for
|
||||
/// (one thread of the title's makes them); less than a twentieth, they are
|
||||
/// not any more.
|
||||
struct Busy(std::time::Instant);
|
||||
|
||||
impl Busy {
|
||||
fn begin() -> Busy {
|
||||
Busy(std::time::Instant::now())
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether mapping is busy after a window of `window` with `spent` in it.
|
||||
fn busy_after(was: bool, spent: std::time::Duration, window: std::time::Duration) -> bool {
|
||||
spent * if was { 20 } else { 4 } > window
|
||||
}
|
||||
|
||||
impl Drop for Busy {
|
||||
fn drop(&mut self) {
|
||||
const WINDOW: std::time::Duration = std::time::Duration::from_millis(250);
|
||||
let now = std::time::Instant::now();
|
||||
let all = BUSY.1.fetch_add((now - self.0).as_nanos() as u64, Ordering::Relaxed) + (now - self.0).as_nanos() as u64;
|
||||
let mut began = BUSY.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let window = now - *began.get_or_insert(self.0);
|
||||
if window < WINDOW {
|
||||
return;
|
||||
}
|
||||
*began = Some(now);
|
||||
BUSY.1.store(0, Ordering::Relaxed);
|
||||
let was = BUSY.2.load(Ordering::Relaxed);
|
||||
let is = busy_after(was, std::time::Duration::from_nanos(all), window);
|
||||
if was != is {
|
||||
BUSY.2.store(is, Ordering::Relaxed);
|
||||
static SAID: AtomicU64 = AtomicU64::new(0);
|
||||
if asked_threads().is_none() && SAID.fetch_add(1, Ordering::Relaxed) < 200 {
|
||||
tracing::info!(
|
||||
"title pages are mapped by {} (VICTORY_MAP_THREADS): {:.0} ms of the last {:.0} ms went into mapping calls",
|
||||
if is { "several threads" } else { "the caller alone" },
|
||||
all as f64 / 1e6,
|
||||
window.as_secs_f64() * 1e3
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A page of address space to unmap and, with a slice, map anew.
|
||||
@@ -1438,7 +1508,7 @@ mod pool {
|
||||
static STARTED: std::sync::Once = std::sync::Once::new();
|
||||
let pool = POOL.get_or_init(|| Pool { batches: Mutex::default(), more: Condvar::new() });
|
||||
STARTED.call_once(|| {
|
||||
let started = (1..side_by_side())
|
||||
let started = (1..super::asked_threads().unwrap_or(super::WIDE).max(side_by_side()))
|
||||
.filter(|i| std::thread::Builder::new().name(format!("mapping {i}")).spawn(|| serve(pool)).is_ok())
|
||||
.count();
|
||||
tracing::info!(started, "threads that map pages side by side (VICTORY_MAP_THREADS=1: none)");
|
||||
@@ -2439,6 +2509,15 @@ mod tests {
|
||||
assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapping_is_busy_from_a_quarter_of_the_time_to_a_twentieth() {
|
||||
let ms = std::time::Duration::from_millis;
|
||||
assert!(!busy_after(false, ms(60), ms(250)) && busy_after(false, ms(70), ms(250)));
|
||||
assert!(busy_after(true, ms(15), ms(250)) && !busy_after(true, ms(12), ms(250)));
|
||||
// A window without a call, then one short one.
|
||||
assert!(!busy_after(true, ms(5), ms(4000)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_windows_cover_one_run_in_place() {
|
||||
let (a, b) = (allocate(3), allocate(1));
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
//! Cube samples with gradients select their level by the footprint (after
|
||||
//! DexNom/VIctory 921d8d3b).
|
||||
|
||||
use super::host::{Dispatch, Host, Root, View};
|
||||
use super::intersect_tests::build_compute_shader;
|
||||
use crate::native::{
|
||||
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
|
||||
};
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
|
||||
/// The level is the red channel on all six faces so every sample returns
|
||||
/// its selected mip directly (including the fraction with trilinear filtering).
|
||||
#[test]
|
||||
fn guest_cube_gradient_selects_mip_by_footprint() {
|
||||
const SIZE: usize = 64;
|
||||
const MIPS: u16 = 7;
|
||||
let mut words = vec![
|
||||
0xBE81_0380,
|
||||
0xBE83_0380, // s1, s3 = 0 (upper halves of the tables)
|
||||
0xF40C_0400,
|
||||
0xFA00_0000, // cube SRV to s[16:23] from s[0:1]
|
||||
0xF408_0300,
|
||||
0xFA00_0020, // raw output UAV to s[12:15] from s[0:1]+32
|
||||
0xF408_0601,
|
||||
0xFA00_0000, // sampler to s[24:27] from s[2:3]
|
||||
0x7E1E_0280, // v15 = 0 for output byte offsets
|
||||
];
|
||||
let cases = [
|
||||
// image_sample_d: successive XY footprints (in texels).
|
||||
(0x22, 1.0, 0.0, 0.0),
|
||||
(0x22, 2.0, 0.0, 1.0),
|
||||
(0x22, 16.0, 0.0, 4.0),
|
||||
(0x22, 0.000001, 0.0, 0.0),
|
||||
(0x22, 0.0, 0.0, 0.0),
|
||||
// image_sample_d_cl: an instruction-specified minimum level.
|
||||
(0x23, 1.0, 3.0, 3.0),
|
||||
(0x23, 16.0, 2.0, 4.0),
|
||||
(0x23, 0.0, 2.0, 2.0),
|
||||
// image_sample_l and image_sample_lz: the level is given directly.
|
||||
(0x24, 0.0, 2.0, 2.0),
|
||||
(0x27, 0.0, 0.0, 0.0),
|
||||
];
|
||||
for (i, &(op, footprint, lod, _)) in cases.iter().enumerate() {
|
||||
let delta = footprint / SIZE as f32;
|
||||
let mut addr = Vec::new();
|
||||
if op == 0x22 || op == 0x23 {
|
||||
addr.extend([delta, 0.0, 0.0, delta]); // derivatives along the face
|
||||
}
|
||||
addr.extend([1.5f32, 1.5, 0.0]); // positive X face, center
|
||||
if op == 0x23 || op == 0x24 {
|
||||
addr.push(lod);
|
||||
}
|
||||
for (reg, value) in addr.iter().enumerate() {
|
||||
words.extend([0x7E00_02FF | ((reg as u32) << 17), value.to_bits()]);
|
||||
}
|
||||
// MIMG, CUBE, dmask:R, v0... inputs, SRV s16, sampler s24, result v10.
|
||||
words.extend([0xF000_0118 | (op << 18), 0x00C4_0A00]);
|
||||
// buffer_store_dword v10, v15, s[12:15], 0 offen offset:i*4
|
||||
words.extend([0xE070_1000 | (i as u32 * 4), 0x8003_0A0F]);
|
||||
}
|
||||
words.push(0xBF81_0000); // s_endpgm
|
||||
let table = |slot, user_data| RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data,
|
||||
slot,
|
||||
};
|
||||
let range = |kind, at, words, slot, user_data| UsedResource {
|
||||
kind,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: at,
|
||||
lower_bound: 0,
|
||||
stride: 0,
|
||||
dwords: words,
|
||||
user_data,
|
||||
slot,
|
||||
};
|
||||
let native = NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 16,
|
||||
layout: vec![table(0, 0), table(1, 2)],
|
||||
used: vec![
|
||||
range(ResourceType::Srv, 0, 8, 0, 0),
|
||||
range(ResourceType::Uav, 8, 4, 0, 0),
|
||||
range(ResourceType::Sampler, 0, 4, 1, 2),
|
||||
],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 3 << 1,
|
||||
threads: [1, 1, 1],
|
||||
}),
|
||||
code: words.into_iter().flat_map(u32::to_le_bytes).collect(),
|
||||
};
|
||||
let (shader, _) = build_compute_shader(&native).unwrap();
|
||||
let texels: Vec<_> = (0..6)
|
||||
.flat_map(|_| {
|
||||
(0..MIPS).flat_map(|mip| std::iter::repeat_n([f32::from(mip); 4], (SIZE >> mip).pow(2)))
|
||||
})
|
||||
.collect();
|
||||
let sampler = D3D12_SAMPLER_DESC {
|
||||
Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR,
|
||||
AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
|
||||
AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
|
||||
AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
|
||||
MaxLOD: f32::MAX,
|
||||
MaxAnisotropy: 1,
|
||||
..Default::default()
|
||||
};
|
||||
for (name, warp) in [("WARP", true), ("hardware", false)] {
|
||||
let Ok(host) = Host::new(warp) else {
|
||||
eprintln!("no SM 6.6 {name} device; skipped");
|
||||
continue;
|
||||
};
|
||||
let (root, pso) = host.compute_pipeline(&shader).unwrap();
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(
|
||||
0,
|
||||
Root::Constants(vec![0; shader.user_data_dwords() as usize]),
|
||||
)],
|
||||
views: &[
|
||||
View::Cube(SIZE as u32, MIPS, &texels),
|
||||
View::RawUav(cases.len() as u32),
|
||||
],
|
||||
samplers: &[sampler],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let levels: Vec<_> = out[0].iter().copied().map(f32::from_bits).collect();
|
||||
let expected = cases.map(|(_, _, _, mip)| mip);
|
||||
assert_eq!(levels.as_slice(), expected, "{name}");
|
||||
}
|
||||
}
|
||||
@@ -1164,7 +1164,7 @@ fn translated_compute_matches_pc() {
|
||||
typed_view(DXGI_FORMAT_R8_UNORM, 1),
|
||||
typed_view(DXGI_FORMAT_R16_FLOAT, 2),
|
||||
typed_view(DXGI_FORMAT_R8G8B8A8_SNORM, 4),
|
||||
View::Cube(4, &cube_texels),
|
||||
View::Cube(4, 1, &cube_texels),
|
||||
])
|
||||
.collect();
|
||||
let root_cbv = floats(64, -0.125);
|
||||
|
||||
@@ -994,8 +994,8 @@ fn transition(
|
||||
pub enum View<'a> {
|
||||
/// An RGBA32F texture SRV (width, height, texels).
|
||||
Texture(u32, u32, &'a [[f32; 4]]),
|
||||
/// An RGBA32F cube SRV (face size, texels of faces +x -x +y -y +z -z).
|
||||
Cube(u32, &'a [[f32; 4]]),
|
||||
/// An RGBA32F cube SRV (face size, mip count, texels in D3D subresource order).
|
||||
Cube(u32, u16, &'a [[f32; 4]]),
|
||||
/// A raw buffer UAV of this many dwords, zeroed.
|
||||
RawUav(u32),
|
||||
/// An RGBA32F texture UAV (width, height), zeroed.
|
||||
@@ -1170,20 +1170,23 @@ impl Host {
|
||||
at.ptr += i * view_size;
|
||||
match *v {
|
||||
View::Texture(..) | View::Cube(..) => {
|
||||
let (w, h, texels, faces) = match *v {
|
||||
View::Texture(w, h, t) => (w, h, t, 1),
|
||||
View::Cube(n, t) => (n, n, t, 6),
|
||||
let (w, h, mut texels, faces, mips) = match *v {
|
||||
View::Texture(w, h, t) => (w, h, t, 1, 1),
|
||||
View::Cube(n, mips, t) => (n, n, t, 6, mips),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let mut desc = texture(w, h, D3D12_RESOURCE_FLAG_NONE);
|
||||
desc.DepthOrArraySize = faces as u16;
|
||||
desc.MipLevels = mips;
|
||||
let tex = make(
|
||||
D3D12_HEAP_TYPE_DEFAULT,
|
||||
&desc,
|
||||
D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
)?;
|
||||
let pitch = (w as usize * 16).next_multiple_of(256);
|
||||
for face in 0..faces as usize {
|
||||
for sub in 0..u32::from(mips) * faces {
|
||||
let mip = sub % u32::from(mips);
|
||||
let (w, h) = ((w >> mip).max(1), (h >> mip).max(1));
|
||||
let pitch = (w as usize * 16).next_multiple_of(256);
|
||||
let upload = make(
|
||||
D3D12_HEAP_TYPE_UPLOAD,
|
||||
&buffer((pitch * h as usize) as u64, D3D12_RESOURCE_FLAG_NONE),
|
||||
@@ -1191,9 +1194,10 @@ impl Host {
|
||||
)?;
|
||||
let mut p = std::ptr::null_mut();
|
||||
upload.Map(0, None, Some(&mut p)).map_err(err)?;
|
||||
let texels = &texels[face * (w * h) as usize..];
|
||||
let (level, rest) = texels.split_at((w * h) as usize);
|
||||
texels = rest;
|
||||
for y in 0..h as usize {
|
||||
let row = &texels[y * w as usize..(y + 1) * w as usize];
|
||||
let row = &level[y * w as usize..(y + 1) * w as usize];
|
||||
std::ptr::copy_nonoverlapping(
|
||||
row.as_ptr().cast::<u8>(),
|
||||
p.cast::<u8>().add(y * pitch),
|
||||
@@ -1202,7 +1206,7 @@ impl Host {
|
||||
}
|
||||
upload.Unmap(0, None);
|
||||
let mut at_face = subresource(&tex);
|
||||
at_face.Anonymous.SubresourceIndex = face as u32;
|
||||
at_face.Anonymous.SubresourceIndex = sub;
|
||||
list.CopyTextureRegion(
|
||||
&at_face,
|
||||
0,
|
||||
@@ -1224,7 +1228,7 @@ impl Host {
|
||||
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
|
||||
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
|
||||
TextureCube: D3D12_TEXCUBE_SRV {
|
||||
MipLevels: 1,
|
||||
MipLevels: u32::from(mips),
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
|
||||
@@ -162,13 +162,19 @@ fn build(
|
||||
wide: bool,
|
||||
descriptor: Descriptor,
|
||||
) -> Result<(HostShader, resource::Resources), ShaderError> {
|
||||
let native = native(&program(wide, descriptor));
|
||||
build_compute_shader(&native(&program(wide, descriptor)))
|
||||
}
|
||||
|
||||
/// `native`, a compute program, translated (the tests' own way: no container).
|
||||
pub(super) fn build_compute_shader(
|
||||
native: &NativeProgram,
|
||||
) -> Result<(HostShader, resource::Resources), ShaderError> {
|
||||
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))?;
|
||||
let io = io::raise(&p, &native).expect("io::raise");
|
||||
let io = io::raise(&p, native).expect("io::raise");
|
||||
let lowered = lower::lower(&lower::Parts {
|
||||
native: &native,
|
||||
native,
|
||||
p: &p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
|
||||
@@ -6594,10 +6594,7 @@ impl<'a> Lower<'a> {
|
||||
/// typed loads do (channels past the format's read 0, 0, 0, 1).
|
||||
// shortcut: the descriptor's channel swizzle is taken as the identity
|
||||
// (it is for raw views and the descriptors code builds), elements of 4
|
||||
// bytes or more as dword-aligned. Norm formats divide, which the AMD
|
||||
// driver does 1 ULP off the hardware's correctly rounded conversion for
|
||||
// some values; correct it with an integer check if a title compares
|
||||
// converted values exactly.
|
||||
// bytes or more as dword-aligned.
|
||||
fn format_load(&mut self, h: V, off: V, format: u8, channels: u32) -> Result<Vec<V>, Why> {
|
||||
let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?;
|
||||
let c = self.cur;
|
||||
@@ -6660,10 +6657,15 @@ impl<'a> Lower<'a> {
|
||||
// 4 loaded 16_16_UNORM's 65535 as the half 0x3BFF, not 0x3C00.
|
||||
let x = match numeric {
|
||||
Numeric::Unorm => {
|
||||
let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
|
||||
let top = (1u64 << w) - 1;
|
||||
let max = self.s.m.f32((top as f32).to_bits());
|
||||
let q = self.s.m.bin(c, Bin::SDiv, f, max);
|
||||
let q = if w <= 16 {
|
||||
let q = self.norm_quotient(field, w);
|
||||
self.as_float(q)
|
||||
} else {
|
||||
let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
|
||||
let max = self.s.m.f32((top as f32).to_bits());
|
||||
self.s.m.bin(c, Bin::SDiv, f, max)
|
||||
};
|
||||
let (high, one) = (self.s.m.i32(top as u32), self.s.m.f32(1.0f32.to_bits()));
|
||||
let at_top = self.s.m.cmp(c, pred::EQ, field, high);
|
||||
let q = self.s.m.select(c, at_top, one, q);
|
||||
@@ -6671,10 +6673,23 @@ impl<'a> Lower<'a> {
|
||||
}
|
||||
Numeric::Snorm => {
|
||||
let s = signed(self);
|
||||
let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
|
||||
let top = (1u32 << (w - 1)) - 1;
|
||||
let max = self.s.m.f32((top as f32).to_bits());
|
||||
let q = self.s.m.bin(c, Bin::SDiv, f, max);
|
||||
let q = if w <= 17 {
|
||||
// The magnitude's quotient, signed (codes at and
|
||||
// below -top are -1.0 below).
|
||||
let (zero, sign) = (self.s.m.i32(0), self.s.m.i32(0x8000_0000));
|
||||
let neg = self.s.m.cmp(c, pred::SLT, s, zero);
|
||||
let minus = self.s.m.bin(c, Bin::Sub, zero, s);
|
||||
let m = self.s.m.select(c, neg, minus, s);
|
||||
let q = self.norm_quotient(m, w - 1);
|
||||
let sign = self.s.m.select(c, neg, sign, zero);
|
||||
let q = self.s.m.bin(c, Bin::Or, q, sign);
|
||||
self.as_float(q)
|
||||
} else {
|
||||
let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
|
||||
let max = self.s.m.f32((top as f32).to_bits());
|
||||
self.s.m.bin(c, Bin::SDiv, f, max)
|
||||
};
|
||||
// The lowest value is -1.0 too, as is the one above it.
|
||||
let (high, one) = (self.s.m.i32(top), self.s.m.f32(1.0f32.to_bits()));
|
||||
let at_top = self.s.m.cmp(c, pred::SGE, s, high);
|
||||
@@ -6724,6 +6739,144 @@ impl<'a> Lower<'a> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The bits of the float nearest to `a / d`, `d = 2^w - 1`, for codes
|
||||
/// `0 <= a < d` and `w <= 16`: what the console's buffer unit gives for
|
||||
/// a normalized code. The host's division is not exact (the RX 6700 XT
|
||||
/// returns 8-bit codes one ulp high and some 16-bit codes one ulp low),
|
||||
/// and titles truncate `x * d` back to the code (a material index in a
|
||||
/// vertex colour's alpha), which a quotient one ulp low turns into the
|
||||
/// code below.
|
||||
///
|
||||
/// `Q = floor(a * 2^32 / d) = a * K + floor(a * r / d)` with `K =
|
||||
/// floor(2^32 / d)` and `r = 2^32 mod d` (no division when `r` is 1:
|
||||
/// widths dividing 32). `a / d` is never exact for `0 < a < d` (`d`
|
||||
/// odd, `r` coprime to it), so `Q` rounds to 24 bits up exactly when
|
||||
/// its highest dropped bit is set, and the result is that integer (at
|
||||
/// most 2^24, so its conversion is exact on any host) scaled by a power
|
||||
/// of two; `Q` itself when it fits, the quotient's further bits then
|
||||
/// lying below half an ulp. That holds for every code of every width but
|
||||
/// 11 and 12 (checked for all codes of widths 2 to 16), which take
|
||||
/// [`Self::exact_norm`]. The host's conversion of a larger integer is
|
||||
/// not relied on: WARP rounds those above 2^31 otherwise.
|
||||
fn norm_quotient(&mut self, a: V, w: u32) -> V {
|
||||
if matches!(w, 11 | 12) {
|
||||
return self.exact_norm(a, w);
|
||||
}
|
||||
let c = self.cur;
|
||||
let d = (1u64 << w) - 1;
|
||||
let (kk, r) = ((1u64 << 32) / d, (1u64 << 32) % d);
|
||||
let k = |l: &mut Self, v: u64| l.s.m.i32(v as u32);
|
||||
let (one, kv) = (k(self, 1), k(self, kk));
|
||||
let mut q = self.s.m.bin(c, Bin::Mul, a, kv);
|
||||
if r != 1 {
|
||||
let (rv, dv) = (k(self, r), k(self, d));
|
||||
let t = self.s.m.bin(c, Bin::Mul, a, rv);
|
||||
let more = self.s.m.bin(c, Bin::UDiv, t, dv);
|
||||
q = self.s.m.bin(c, Bin::Add, q, more);
|
||||
}
|
||||
// The bits to drop (1 to 8) from the exponent of `q >> 8`, which
|
||||
// converts exactly (fewer than 25 bits); none when `q` fits.
|
||||
let k8 = k(self, 8);
|
||||
let top = self.s.m.bin(c, Bin::LShr, q, k8);
|
||||
let top = self.s.m.cast(c, Cast::UiToFp, top, self.s.t.f32);
|
||||
let top = self.as_int(top);
|
||||
let k23 = k(self, 23);
|
||||
let e = self.s.m.bin(c, Bin::LShr, top, k23);
|
||||
let bias = k(self, 127 + 15);
|
||||
let shift = self.s.m.bin(c, Bin::Sub, e, bias);
|
||||
let (zero, b24) = (k(self, 0), k(self, 1 << 24));
|
||||
let fits = self.s.m.cmp(c, pred::IULT, q, b24);
|
||||
let shift = self.s.m.select(c, fits, zero, shift);
|
||||
// Rounded up when the highest dropped bit is set: `a / d` is never
|
||||
// exact, so a dropped half is more than half, never a tie.
|
||||
let up = self.s.m.bin(c, Bin::Shl, q, one);
|
||||
let up = self.s.m.bin(c, Bin::LShr, up, shift);
|
||||
let up = self.s.m.bin(c, Bin::And, up, one);
|
||||
let m = self.s.m.bin(c, Bin::LShr, q, shift);
|
||||
let m = self.s.m.bin(c, Bin::Add, m, up);
|
||||
// At most 2^24: exact as a float, and so its scale by 2^(shift - 32).
|
||||
let f = self.s.m.cast(c, Cast::UiToFp, m, self.s.t.f32);
|
||||
let b95 = k(self, 127 - 32);
|
||||
let scale = self.s.m.bin(c, Bin::Add, shift, b95);
|
||||
let scale = self.s.m.bin(c, Bin::Shl, scale, k23);
|
||||
let scale = self.as_float(scale);
|
||||
let f = self.s.m.bin(c, Bin::Mul, f, scale);
|
||||
self.as_int(f)
|
||||
}
|
||||
|
||||
/// [`Self::norm_quotient`] in integers only, for any width up to 16: `Q`
|
||||
/// as there, 8 more bits when that leaves fewer than 25 (codes of wide
|
||||
/// formats near 0), then rounded to 24 bits to nearest even with the
|
||||
/// remainder as sticky bit, and assembled as float bits.
|
||||
fn exact_norm(&mut self, a: V, w: u32) -> V {
|
||||
let c = self.cur;
|
||||
let d = (1u64 << w) - 1;
|
||||
let (kk, r) = ((1u64 << 32) / d, (1u64 << 32) % d);
|
||||
let k = |l: &mut Self, v: u64| l.s.m.i32(v as u32);
|
||||
let (one, zero, dv, k8) = (k(self, 1), k(self, 0), k(self, d), k(self, 8));
|
||||
let kv = k(self, kk);
|
||||
let mut q = self.s.m.bin(c, Bin::Mul, a, kv);
|
||||
let mut rem = a;
|
||||
if r != 1 {
|
||||
let rv = k(self, r);
|
||||
let t = self.s.m.bin(c, Bin::Mul, a, rv);
|
||||
let more = self.s.m.bin(c, Bin::UDiv, t, dv);
|
||||
q = self.s.m.bin(c, Bin::Add, q, more);
|
||||
rem = self.s.m.bin(c, Bin::URem, t, dv);
|
||||
}
|
||||
// The exponent's bias less the 32 (or 40) fraction bits of `q`; the
|
||||
// shift below is added.
|
||||
let mut bias = k(self, 127 + 23 - 32);
|
||||
if kk < 1 << 24 {
|
||||
// Fewer than 25 bits for the smallest codes: 8 more.
|
||||
let t = self.s.m.bin(c, Bin::Shl, rem, k8);
|
||||
let more = self.s.m.bin(c, Bin::UDiv, t, dv);
|
||||
let rest = self.s.m.bin(c, Bin::URem, t, dv);
|
||||
let wide = self.s.m.bin(c, Bin::Shl, q, k8);
|
||||
let wide = self.s.m.bin(c, Bin::Or, wide, more);
|
||||
let limit = k(self, 1 << 24);
|
||||
let small = self.s.m.cmp(c, pred::IULT, q, limit);
|
||||
q = self.s.m.select(c, small, wide, q);
|
||||
rem = self.s.m.select(c, small, rest, rem);
|
||||
let b40 = k(self, 127 + 23 - 40);
|
||||
bias = self.s.m.select(c, small, b40, bias);
|
||||
}
|
||||
// Bits to drop: the bit length less 24, 1 to 8.
|
||||
let mut shift = one;
|
||||
for bit in 25..32 {
|
||||
let at = k(self, 1 << bit);
|
||||
let ge = self.s.m.cmp(c, pred::IUGE, q, at);
|
||||
let add = self.s.m.select(c, ge, one, zero);
|
||||
shift = self.s.m.bin(c, Bin::Add, shift, add);
|
||||
}
|
||||
let mant = self.s.m.bin(c, Bin::LShr, q, shift);
|
||||
let below = self.s.m.bin(c, Bin::Sub, shift, one);
|
||||
let half = self.s.m.bin(c, Bin::LShr, q, below);
|
||||
let half = self.s.m.bin(c, Bin::And, half, one);
|
||||
let low = self.s.m.bin(c, Bin::Shl, one, below);
|
||||
let low = self.s.m.bin(c, Bin::Sub, low, one);
|
||||
let low = self.s.m.bin(c, Bin::And, q, low);
|
||||
let rest = self.s.m.bin(c, Bin::Or, low, rem);
|
||||
let sticky = self.s.m.cmp(c, pred::NE, rest, zero);
|
||||
let odd = self.s.m.bin(c, Bin::And, mant, one);
|
||||
let tie = self.s.m.select(c, sticky, one, odd);
|
||||
let up = self.s.m.bin(c, Bin::And, half, tie);
|
||||
let mant = self.s.m.bin(c, Bin::Add, mant, up);
|
||||
// Rounding up to 2^24 moves to the next exponent.
|
||||
let k24 = k(self, 24);
|
||||
let carry = self.s.m.bin(c, Bin::LShr, mant, k24);
|
||||
let mant = self.s.m.bin(c, Bin::LShr, mant, carry);
|
||||
let e = self.s.m.bin(c, Bin::Add, bias, shift);
|
||||
let e = self.s.m.bin(c, Bin::Add, e, carry);
|
||||
let k23 = k(self, 23);
|
||||
let e = self.s.m.bin(c, Bin::Shl, e, k23);
|
||||
let fraction = k(self, 0x7F_FFFF);
|
||||
let m = self.s.m.bin(c, Bin::And, mant, fraction);
|
||||
let bits = self.s.m.bin(c, Bin::Or, e, m);
|
||||
let is_zero = self.s.m.cmp(c, pred::EQ, a, zero);
|
||||
self.s.m.select(c, is_zero, zero, bits)
|
||||
}
|
||||
|
||||
/// Channels of buffer format `format`, as [`Self::format_load`] gives
|
||||
/// them, as d16 data: 16 bits each, two per dword, low half first (an
|
||||
/// odd last high half 0). Integer formats keep their low 16 bits; the
|
||||
@@ -7152,6 +7305,33 @@ 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)?;
|
||||
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)
|
||||
}))
|
||||
}
|
||||
|
||||
/// 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).
|
||||
fn integer_view(&mut self, src: &Source) -> Result<Option<(V, V)>, Why> {
|
||||
let Some(word) = self.slot_word(src)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let c = self.cur;
|
||||
let zero = self.s.m.i32(0);
|
||||
let [int, signed] = [super::shader::VIEW_INTEGER, super::shader::VIEW_SIGNED].map(|bit| {
|
||||
let bit = self.s.m.i32(bit);
|
||||
let x = self.s.m.bin(c, Bin::And, word, bit);
|
||||
self.s.m.cmp(c, pred::NE, x, zero)
|
||||
});
|
||||
Ok(Some((int, signed)))
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
let Source::Loaded { load, first } = src else {
|
||||
return Ok(None);
|
||||
};
|
||||
@@ -10938,11 +11118,14 @@ impl<'a> Lower<'a> {
|
||||
let width = self.s.m.extract(c, d, 0);
|
||||
let width = self.s.m.cast(c, Cast::UiToFp, width, self.s.t.f32);
|
||||
let texels = self.s.m.bin(c, Bin::Mul, longer, width);
|
||||
// log2 = natural logarithm / ln 2; a length of 0 gives
|
||||
// DXIL's logarithm is the one to base 2 (it was taken for
|
||||
// the natural one: every level came out 1.44 times too
|
||||
// high; DexNom/VIctory 921d8d3b). A length of 0 gives
|
||||
// minus infinity, which the sampler clamps to level 0.
|
||||
let ln = self.unary(23, texels);
|
||||
let per_ln2 = self.s.m.f32(std::f32::consts::LOG2_E.to_bits());
|
||||
let lod = self.s.m.bin(c, Bin::Mul, ln, per_ln2);
|
||||
// SampleLevel takes no clamp: the instruction's least
|
||||
// level is applied here.
|
||||
let lod = self.unary(23, texels);
|
||||
let lod = if has_cl { self.binary(35, lod, clamp) } else { lod };
|
||||
args.extend(&os);
|
||||
args.push(lod);
|
||||
call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
|
||||
@@ -11509,8 +11692,14 @@ impl<'a> Lower<'a> {
|
||||
let mut vals =
|
||||
self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?;
|
||||
if d16 {
|
||||
// shortcut: d16 data is taken as f16 (integer formats would
|
||||
// keep 16 bits), widened for the 32-bit float store.
|
||||
// d16 data is taken as f16, widened for the 32-bit float
|
||||
// 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.
|
||||
let integer = if typed { self.integer_view(src)? } else { None };
|
||||
let mut wide = Vec::new();
|
||||
for k in 0..count {
|
||||
let mut x = vals[(k / 2) as usize];
|
||||
@@ -11522,7 +11711,16 @@ impl<'a> Lower<'a> {
|
||||
let f = self
|
||||
.s
|
||||
.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
|
||||
wide.push(self.as_int(f));
|
||||
let mut w = self.as_int(f);
|
||||
if let Some((int, signed)) = integer {
|
||||
let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
|
||||
let zero_ext = self.s.m.bin(c, Bin::And, x, low);
|
||||
let up = self.s.m.bin(c, Bin::Shl, x, k16);
|
||||
let sign_ext = self.s.m.bin(c, Bin::AShr, up, k16);
|
||||
let n = self.s.m.select(c, signed, sign_ext, zero_ext);
|
||||
w = self.s.m.select(c, int, n, w);
|
||||
}
|
||||
wide.push(w);
|
||||
}
|
||||
vals = wide;
|
||||
}
|
||||
@@ -11657,16 +11855,24 @@ impl<'a> Lower<'a> {
|
||||
return Err("a buffer result");
|
||||
};
|
||||
if d16 {
|
||||
// Two f16 channels per VGPR (an odd last high half 0).
|
||||
// Two f16 channels per VGPR (an odd last high half 0); the low
|
||||
// 16 bits of an integer view's (see the stores above).
|
||||
let integer = if typed { self.integer_view(src)? } else { None };
|
||||
let k16 = self.s.m.i32(16);
|
||||
let i32t = self.s.t.i32;
|
||||
for k in 0..count.div_ceil(2) {
|
||||
let mut x = None;
|
||||
for ch in (2 * k..(2 * k + 2).min(count)).rev() {
|
||||
let f = self.s.m.extract(c, r, ch);
|
||||
let h = self
|
||||
let mut h = self
|
||||
.s
|
||||
.op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
|
||||
if let Some((int, _)) = integer {
|
||||
let bits = self.as_int(f);
|
||||
let low = self.s.m.i32(0xFFFF);
|
||||
let low = self.s.m.bin(c, Bin::And, bits, low);
|
||||
h = self.s.m.select(c, int, low, h);
|
||||
}
|
||||
x = Some(match x {
|
||||
Some(hi) => {
|
||||
let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
|
||||
|
||||
@@ -83,6 +83,8 @@
|
||||
mod bitcode;
|
||||
mod container;
|
||||
#[cfg(all(test, windows))]
|
||||
mod cube_lod_tests;
|
||||
#[cfg(all(test, windows))]
|
||||
mod diff_tests;
|
||||
#[cfg(all(test, windows))]
|
||||
mod intersect_tests;
|
||||
@@ -118,7 +120,7 @@ pub use lower::{host_settings, set_host_max_wave};
|
||||
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, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
|
||||
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,
|
||||
raw_views, set_raw_views, set_view_heap_limit, view_heap_limit,
|
||||
};
|
||||
|
||||
|
||||
@@ -24,6 +24,14 @@ 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 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
|
||||
/// (`UINT` or `SINT`), whose 16-bit typed accesses (`_d16`) pass bits.
|
||||
/// (After VIctory 4243a96a.)
|
||||
pub const VIEW_INTEGER: u32 = 1 << 31;
|
||||
/// With [`VIEW_INTEGER`]: a signed (`SINT`) format.
|
||||
pub const VIEW_SIGNED: u32 = 1 << 30;
|
||||
/// Dwords of the [`SLOT_STRIDES`] buffer: heap indices are clamped to it.
|
||||
pub const SLOT_STRIDES_COUNT: u32 = 1 << 21;
|
||||
|
||||
@@ -93,6 +101,8 @@ pub(crate) mod flags {
|
||||
pub const DOUBLES: u64 = 1 << 2;
|
||||
pub const STENCIL_REF: u64 = 1 << 11;
|
||||
pub const TYPED_UAV_LOADS: u64 = 1 << 13;
|
||||
/// Unordered views in a vertex, geometry or mesh program.
|
||||
pub const UAVS_EVERY_STAGE: u64 = 1 << 16;
|
||||
pub const ROVS: u64 = 1 << 18;
|
||||
pub const WAVE_OPS: u64 = 1 << 19;
|
||||
pub const BARYCENTRICS: u64 = 1 << 22;
|
||||
@@ -557,6 +567,13 @@ impl Shader {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Unordered views outside pixel and compute programs (memory by
|
||||
// address), as DXC counts them: ranges declared below, not views
|
||||
// picked from the heap (VIctory a1a2077a).
|
||||
let compute = self.threads.is_some() && self.mesh.is_none() && self.geometry.is_none();
|
||||
if !self.root_uavs.is_empty() && !self.pixel && !compute {
|
||||
self.flags |= flags::UAVS_EVERY_STAGE;
|
||||
}
|
||||
let mut resources = None;
|
||||
let mut bindings = Vec::new();
|
||||
let i32c = |s: &mut Self, v: u32| {
|
||||
@@ -871,6 +888,9 @@ impl Shader {
|
||||
if self.flags & flags::DOUBLES != 0 {
|
||||
features |= 0x1;
|
||||
}
|
||||
if self.flags & flags::UAVS_EVERY_STAGE != 0 {
|
||||
features |= 0x4;
|
||||
}
|
||||
if self.flags & flags::STENCIL_REF != 0 {
|
||||
features |= 0x200;
|
||||
}
|
||||
|
||||
@@ -415,6 +415,66 @@ fn normalized_buffer_formats_load_their_ends_exactly() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Codes of the normalized formats sampled below: every 8-bit code; for
|
||||
/// 16 bits a stride, the RX 6700 XT's division misses (257, 261, ...) and
|
||||
/// the ends.
|
||||
fn normalized_codes(bits: u32) -> Vec<u32> {
|
||||
if bits <= 10 {
|
||||
return (0..1 << bits).collect();
|
||||
}
|
||||
let edges = [1, 2, 3, 255, 256, 257, 261, 265, 269, 511, 512, 1000, 0x7FFF, 0x8000, 0x8001, 0xFFFE];
|
||||
(0..=0xFFFF).step_by(257).chain(edges).collect()
|
||||
}
|
||||
|
||||
/// Every normalized code loads as the float nearest its exact quotient,
|
||||
/// as the console's buffer unit converts it, not as the host divides (the
|
||||
/// RX 6700 XT gave 125 of the 8-bit codes one ulp high and 16-bit codes
|
||||
/// such as 257 one ulp low): unsigned and signed, 8, 10 (the x channel of
|
||||
/// 2_10_10_10) and 16 bits, the signed formats' two lowest codes -1.0.
|
||||
#[test]
|
||||
fn normalized_buffer_formats_load_correctly_rounded_quotients() {
|
||||
let x = 0;
|
||||
// (format, bits, signed): 8_UNORM, 16_UNORM, 8_SNORM, 16_SNORM,
|
||||
// 2_10_10_10_UNORM and _SNORM.
|
||||
for (format, bits, signed) in [(1u8, 8u32, false), (7, 16, false), (2, 8, true), (8, 16, true), (50, 10, false), (51, 10, true)] {
|
||||
let shader = tbuffer_load_of_v1(x, format);
|
||||
let cases: Vec<[u32; 4]> = normalized_codes(bits).iter().map(|&a| [a, 0, 0, 0]).collect();
|
||||
run_cases(&shader, &cases, |backend, _, [a, ..], got| {
|
||||
let want = if signed {
|
||||
let top = (1i32 << (bits - 1)) - 1;
|
||||
let s = ((a << (32 - bits)) as i32) >> (32 - bits);
|
||||
(s.max(-top) as f32 / top as f32).to_bits()
|
||||
} else {
|
||||
(a as f32 / ((1u32 << bits) - 1) as f32).to_bits()
|
||||
};
|
||||
let sign = if signed { "signed" } else { "unsigned" };
|
||||
assert_eq!(got, want, "{backend}: {bits}-bit {sign} normalized {a:#x} loads as {got:#010x}, want {want:#010x}");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// A title truncates `x * (2^n - 1)` back to the code it stored (the
|
||||
/// material index a mesh program reads from a vertex colour's alpha, as
|
||||
/// `v_mul_legacy_f32` by 255.0 then `v_cvt_u32_f32`): every code comes back
|
||||
/// as itself, on hardware and WARP, which a quotient one ulp low breaks.
|
||||
#[test]
|
||||
fn normalized_codes_truncate_back_to_themselves() {
|
||||
let x = 0;
|
||||
for (format, bits) in [(1u8, 8u32), (7, 16)] {
|
||||
let scale = (((1u32 << bits) - 1) as f32).to_bits();
|
||||
let mut body = buffer_store_dword(1, 8, 0).to_vec();
|
||||
body.extend(mtbuf(x, 0, 8, format));
|
||||
// v_mul_legacy_f32 v0, literal, v0; v_cvt_u32_f32 v0, v0.
|
||||
body.extend([0x07 << 25 | 0xFF, scale]);
|
||||
body.push(vop1(0x07, 0, vgpr(0)));
|
||||
let shader = build_valu_cs(&body);
|
||||
let cases: Vec<[u32; 4]> = normalized_codes(bits).iter().map(|&a| [a, 0, 0, 0]).collect();
|
||||
run_cases(&shader, &cases, |backend, _, [a, ..], got| {
|
||||
assert_eq!(got, a, "{backend}: {bits}-bit code {a} comes back as {got}");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packed_add_selects_halves_of_inline_constants() {
|
||||
// Add the inline constant 1/(2*pi) to v1 (zero) to read back its two halves.
|
||||
|
||||
Reference in new issue
Block a user