Merge local/next

This commit is contained in:
local committed 2026-11-25 00:01:05 -06:00
commit bf9ebebf60
41 files changed
+4711 -511

No files matched your search

+34 -3
View File
@@ -861,12 +861,16 @@ impl HostHeap {
let enough = self.free.load(std::sync::atomic::Ordering::Relaxed) >= n
&& n < self.too_long.load(std::sync::atomic::Ordering::Relaxed);
let n = n as usize;
// Search from `next` on, then from the start.
let starts = (*next as usize..self.dynamic as usize).chain(0..*next as usize);
// Search from `next` on, then from the start (extending past cursor by
// n - 1 so contiguous runs crossing the cursor are not missed).
let cursor = *next as usize;
let end = self.dynamic as usize;
let second_end = cursor.saturating_add(n.saturating_sub(1)).min(end);
let starts = (cursor..end).chain(0..second_end);
let mut run = 0;
let mut found = None;
let mut last = usize::MAX;
for at in starts.take(if enough { DYNAMIC as usize } else { 0 }) {
for at in starts.take(if enough { usize::MAX } else { 0 }) {
// A run cannot wrap past the end.
if at != last.wrapping_add(1) {
run = 0;
@@ -2850,4 +2854,31 @@ mod tests {
assert_eq!(heap.dynamic(50), Some(4));
assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40));
}
#[test]
fn dynamic_search_can_find_a_run_across_the_cursor() {
let Some(heap) = HostHeap::new(false, 4) else {
eprintln!("no host descriptor heap; skipped");
return;
};
let first = heap.dynamic(1).unwrap();
let left = heap.dynamic(2).unwrap();
let right = heap.dynamic(2).unwrap();
let rest = heap.dynamic(heap.dynamic - 5).unwrap();
assert_eq!((first, left, right, rest), (4, 5, 7, 9));
// Reallocating the left half puts the cursor back in the middle.
heap.release(left, 2);
assert_eq!(heap.dynamic(2), Some(left));
heap.release(left, 2);
heap.release(right, 2);
assert_eq!(heap.dynamic(4), Some(left));
assert_eq!(heap.dynamic(1), None);
// A free slot at each physical end does not form a two-slot range.
heap.release(first, 1);
let last = first + heap.dynamic - 1;
heap.release(last, 1);
assert_eq!(heap.dynamic(2), None);
}
}
+1
View File
@@ -1718,6 +1718,7 @@ impl State {
}
#[cfg(feature = "diagnostics")]
let refreshed = std::time::Instant::now();
crate::watch::look_at_holes();
self.heap_textures(list, heap, host);
#[cfg(feature = "diagnostics")]
for (sum, time) in HEAP_SPLIT.iter().zip([looked - started, refreshed - looked, refreshed.elapsed()]) {
+2 -1
View File
@@ -214,7 +214,8 @@ mod tests {
let mut second = 0;
assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut second), S_OK);
assert!(second > first);
assert!(before.elapsed() <= Duration::from_millis(50));
// At the tick, not at the time-out (a busy PC may wake it late).
assert!(before.elapsed() <= Duration::from_millis(500));
assert_eq!(wait(null, 0, 0, std::ptr::null(), 0, &mut second), TIMEOUT);
// Tokens count frames, a frame started early on a time-out too.
let mut early = 0;
+182 -29
View File
@@ -704,6 +704,22 @@ fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
#[cfg(test)]
mod tests {
/// Zeros for a title destination that went meanwhile are no fault.
#[test]
fn zeros_where_nothing_is_are_lost() {
use windows_sys::Win32::System::Memory::*;
// SAFETY: a reservation of ours, its first page committed.
unsafe {
let at = VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
assert!(!VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE).is_null());
at.write_bytes(7, 4096);
super::zero(at, 4096);
assert!(std::slice::from_raw_parts(at, 4096).iter().all(|&b| b == 0));
super::zero(at.add(4096), 4096);
VirtualFree(at.cast(), 0, MEM_RELEASE);
}
}
#[test]
fn sparse_copies_preserve_islands_and_observe_remaps() {
use windows_sys::Win32::System::Memory::*;
@@ -4709,7 +4725,7 @@ impl Host {
for list in runs {
for step in &list.deferred().copies {
if let Step::Refresh(shadow, address, len) = step
&& !shadow.unwatched()
&& shadow.asked_ahead()
{
let span = spans
.entry(std::sync::Arc::as_ptr(shadow) as usize)
@@ -4719,6 +4735,8 @@ impl Host {
}
}
let ranges: Vec<(usize, usize)> = spans.into_values().collect();
#[cfg(feature = "diagnostics")]
SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed);
crate::watch::ask_once(&ranges);
#[cfg(feature = "diagnostics")]
split.part(0);
@@ -6215,9 +6233,11 @@ impl std::hash::Hasher for AddressHash {
/// in under flights' writes; the lists' steps, the refreshes among them; the
/// snapshots; what goes to copies in the card's memory; the lists sent; and
/// of the steps: the refreshes, and the copies and fills (those with the
/// refreshes a copy of title memory flushes).
/// refreshes a copy of title memory flushes). Of the asking, which ranges it
/// is of. Of the refreshes, those before ranges are given to shaders, one
/// copy at a time: nanoseconds, and how many.
#[cfg(feature = "diagnostics")]
static SPLIT: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8];
static SPLIT: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
/// Since the last frame-rate line: flushes of refreshes, their refreshes,
/// those known to copy nothing, and those done on several threads.
@@ -6234,6 +6254,11 @@ impl Split {
Split(std::cell::Cell::new(std::time::Instant::now()))
}
/// Nanoseconds since the last part.
fn so_far(&self) -> u64 {
self.0.get().elapsed().as_nanos() as u64
}
/// What came since the last part was part `i`.
fn part(&self, i: usize) {
let now = std::time::Instant::now();
@@ -6248,13 +6273,14 @@ fn split_line(frames: f64) {
let f: Vec<f64> = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect();
let a: Vec<f64> = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect();
let h: Vec<f64> = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
let s: Vec<f64> = crate::shadow::send_stats().iter().map(|&n| n as f64 / (1 << 20) as f64 / frames).collect();
let s: Vec<f64> = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect();
tracing::info!(
"preparing per frame, the submitting thread: {:.1} ms asking the write watch, {:.1} putting the title's bytes under flights' \
"preparing per frame, the submitting thread: {:.1} ms asking the write watch ({:.1} of them finding what to ask), {:.1} putting the title's bytes under flights' \
writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \
several threads; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \
several threads, {:.1} one at a time in {:.0} before shader writes; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \
card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {})",
ms[0],
ms[8],
ms[1],
ms[2],
ms[6],
@@ -6262,6 +6288,8 @@ fn split_line(frames: f64) {
f[1],
f[2],
f[3],
ms[9],
ms[10] * 1e6,
ms[7],
ms[3],
ms[4],
@@ -6269,12 +6297,17 @@ fn split_line(frames: f64) {
if crate::watch::light() { "on" } else { "off" },
);
tracing::info!(
"asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB; view ranges: {:.0} answered by their \
"asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \
written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \
bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \
waiting for the guards, {:.1} ms changing protections; pages taken again for the card: {:.1} MB compared, {:.1} MB of them \
as they were, {:.1} MB to go up (VICTORY_SEND_CHANGED)",
waiting for the guards, {:.1} ms changing protections; pages taken for the card: {:.1} MB compared, {:.1} MB of them \
as they were, {:.1} MB to go up in {:.0} runs (VICTORY_SEND_CHANGED)",
a[0],
a[1] / 1024.0,
a[11] / 1e6,
a[12],
a[10],
a[9],
a[2],
a[3],
a[4],
@@ -6282,9 +6315,10 @@ fn split_line(frames: f64) {
a[6],
a[7] / 1e6,
a[8] / 1e6,
s[0],
s[1],
s[2],
s[0] / 1048576.0,
s[1] / 1048576.0,
s[2] / 1048576.0,
s[3],
);
tracing::info!(
"the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures",
@@ -6414,7 +6448,12 @@ impl Batch {
Self::update(&shadow, from, to);
}
#[cfg(feature = "diagnostics")]
SPLIT[6].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
{
let ns = started.elapsed().as_nanos() as u64;
SPLIT[6].fetch_add(ns, Ordering::Relaxed);
SPLIT[9].fetch_add(ns, Ordering::Relaxed);
SPLIT[10].fetch_add(1, Ordering::Relaxed);
}
}
/// Brings `[from, to)` of a copy up to date, timed.
@@ -6497,7 +6536,7 @@ impl Batch {
let ranges: Vec<(usize, usize)> = self
.refreshes
.iter()
.filter(|r| !r.0.unwatched())
.filter(|r| r.0.asked_ahead())
.map(|r| (r.1, r.2))
.collect();
crate::watch::ask_ahead(&ranges);
@@ -6586,7 +6625,10 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b
}
#[cfg(feature = "diagnostics")]
let moved = std::time::Instant::now();
let whole = read(src, dst, len);
let since = crate::watch::changes();
// (A title destination that is away only while the runtime changes a
// mapping beside it is written when that is done.)
let whole = read(src, dst, len) || title_dst && crate::watch::again_after_change(since, || read(src, dst, len));
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64);
if whole {
@@ -6596,6 +6638,7 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b
// not all mapped. Then the destination stays as it is (the kernel may
// have written its first pages).
if title_dst && !ask_first && !crate::texture::committed(dst, len) {
crate::watch::lost("a copy of the title's", dst as usize, len);
return;
}
#[cfg(feature = "diagnostics")]
@@ -6655,14 +6698,29 @@ fn read_pieces(src: *const u8, dst: *mut u8, len: usize) {
if !read(at as *const u8, to, n) {
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
// SAFETY: inside the destination, which is mapped.
unsafe { to.write_bytes(0, n) };
zero(to, n);
}
});
}
});
}
/// Zeros at `to`, in one 4 KiB page or two. It may be title memory (the
/// destination of a title's copy), which can go between the question whether
/// it is there and this.
fn zero(to: *mut u8, n: usize) {
static ZEROS: [u8; 4096] = [0; 4096];
if n <= ZEROS.len() && crate::safecopy::on() {
// SAFETY: a destination that is not there fails the copy.
if !unsafe { crate::safecopy::copy(to, ZEROS.as_ptr(), n) } {
crate::watch::lost("zeros", to as usize, n);
}
return;
}
// SAFETY: inside the destination, which is mapped.
unsafe { to.write_bytes(0, n) };
}
/// Reads title memory at `src` into `dst`; false if a page of it is not
/// readable.
pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
@@ -6716,6 +6774,7 @@ pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
use windows_sys::Win32::System::Threading::GetCurrentProcess;
let direct = direct_writes();
let since = crate::watch::changes();
let write = |at: usize, n: usize| {
let from = src.wrapping_add(at - dst as usize);
if crate::safecopy::on() {
@@ -6742,7 +6801,16 @@ pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
for_pieces(dst as usize, len, 64 << 10, |at, n| {
if !write(at, n) {
for_pieces(at, n, 4 << 10, |at, n| {
write(at, n);
if write(at, n) {
return;
}
// The kernel's write (`VICTORY_SAFE_COPY=0`) fails where a
// refresh guarded the block again since the caller opened
// it; and any where the runtime was changing a mapping.
crate::watch::writing(at, n);
if !write(at, n) && !crate::watch::again_after_change(since, || write(at, n)) {
crate::watch::lost("a host copy's bytes", at, n);
}
});
}
});
@@ -7795,6 +7863,50 @@ mod refresh_tests {
at
}
/// Title memory of `blocks` pages in a placeholder, one view to a page,
/// and every fourth page not there: as a title that streams has it.
fn with_holes(blocks: usize) -> usize {
use windows_sys::Win32::System::Memory::{
MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS,
VirtualAlloc2, VirtualFree,
};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
// SAFETY: a placeholder and a section of our own.
unsafe {
let at = VirtualAlloc2(
GetCurrentProcess(),
std::ptr::null(),
blocks * PAGE,
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
PAGE_NOACCESS,
std::ptr::null_mut(),
0,
) as usize;
assert_ne!(at, 0);
let len = blocks * PAGE;
let section =
CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, (len >> 32) as u32, len as u32, std::ptr::null());
for block in (0..blocks).filter(|b| b % 4 != 3) {
let to = at + block * PAGE;
VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
let view = MapViewOfFile3(
section,
GetCurrentProcess(),
to as *const _,
(block * PAGE) as u64,
PAGE,
MEM_REPLACE_PLACEHOLDER,
PAGE_READWRITE,
std::ptr::null_mut(),
0,
);
assert_eq!(view.Value as usize, to);
crate::title_memory_remapped(to, PAGE);
}
at
}
}
fn memory(len: usize) -> *mut u8 {
// SAFETY: a plain allocation.
unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() }
@@ -7946,6 +8058,10 @@ mod refresh_tests {
/// card's side of those that have one, hold what title memory holds, and
/// title memory what was written last.
///
/// Into the first copy shaders write besides through a view nobody
/// declared, words the title does not write: nothing that goes up ever
/// puts an older value over those.
///
/// (It fails in the first rounds if `landed_beside` notes nothing, or
/// only takes the block out of the guards' clean ones and leaves its bit,
/// or if a fault leaves the bit; in some thousand rounds,
@@ -7964,6 +8080,9 @@ mod refresh_tests {
let data = memory(len);
(Shadow::unbacked(start as u64, data, len as u64, false), start, len, data as usize)
};
// What was last written so, by offset.
let mut undeclared = std::collections::HashMap::new();
let exact = std::env::var_os("VICTORY_SEND_CHANGED").is_none_or(|v| v != "0");
let stop = AtomicBool::new(false);
// Also when an assertion fails on one of the threads.
struct Stop<'a>(&'a AtomicBool);
@@ -8068,6 +8187,16 @@ mod refresh_tests {
let mut value = 1u32;
for round in 0..rounds {
check(round, &mut random, false);
if exact {
let c = &carded[0];
let mut card = c.card.lock().unwrap();
for _ in 0..40 {
value += 1;
let at = random.below(LEN / 32) * 32 + 4 * 6;
card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
undeclared.insert(at, value);
}
}
// The flight of this submission: its shaders' writes.
for (which, c) in carded.iter().enumerate() {
if c.flying.swap(true, Ordering::Acquire) {
@@ -8113,7 +8242,17 @@ mod refresh_tests {
let (held, there) = (bytes(c.data, c.len), bytes(c.start, c.len));
assert_eq!(first(held, there), None, "round {round}: a card copy's CPU side (class {})", c.class);
let card = c.card.lock().unwrap();
assert_eq!(first(&card.2, there), None, "round {round}: a card copy's card side (class {})", c.class);
let mut side = card.2.clone();
if c.class == carded[0].class {
// (They may have been landed meanwhile, by a flight
// that declared their range, and may not.)
for (&at, &value) in &undeclared {
let on_card = u32::from_le_bytes(side[at..at + 4].try_into().unwrap());
assert_eq!(on_card, value, "round {round}: an older value at {at:#x}");
side[at..at + 4].copy_from_slice(&there[at..at + 4]);
}
}
assert_eq!(first(&side, there), None, "round {round}: a card copy's card side (class {})", c.class);
}
assert_eq!(first(bytes(plain.3, plain.2), bytes(plain.1, plain.2)), None, "round {round}: the other copy");
}
@@ -8197,8 +8336,9 @@ mod refresh_tests {
}
}
/// A part of a copy in the card's memory taken again goes up only if it
/// differs (with `VICTORY_SEND_CHANGED=1`), whole when never taken.
/// Of a copy in the card's memory only the dwords title memory changed go
/// up, and none beside them, not even between two in 64 bytes; a page
/// never taken goes up whole.
#[test]
fn only_what_differs_goes_up() {
let region = title(4 * PAGE, true);
@@ -8217,18 +8357,24 @@ mod refresh_tests {
copy.update(region, 4 * PAGE);
let again = copy.take_dirty();
// SAFETY: as above.
unsafe { ((region + 2 * PAGE + 128) as *mut u8).write_volatile(9) };
unsafe {
((region + 2 * PAGE + 129) as *mut u8).write_volatile(9);
((region + 2 * PAGE + 136) as *mut u32).write_volatile(9);
((region + 2 * PAGE + 140) as *mut u32).write_volatile(9);
// The value that was there.
((region + 2 * PAGE + 132) as *mut u32).write_volatile(0);
}
copy.update(region, 4 * PAGE);
let written = copy.take_dirty();
if std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v == "1") {
if std::env::var_os("VICTORY_SEND_CHANGED").is_none_or(|v| v != "0") {
assert_eq!(again, []);
assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 192)]);
assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 132), (2 * PAGE + 136, 2 * PAGE + 144)]);
} else {
assert_eq!(again, [(PAGE, 2 * PAGE)]);
assert_eq!(written, [(2 * PAGE, 3 * PAGE)]);
}
// SAFETY: as above.
assert_eq!(unsafe { data.add(2 * PAGE + 128).read() }, 9);
assert_eq!(unsafe { data.add(2 * PAGE + 129).read() }, 9);
}
/// The refreshes of a frame as run record-1 had them: 30 submissions, the
@@ -8243,12 +8389,17 @@ mod refresh_tests {
const EACH: usize = 224 << 10;
const BIG: usize = 174 << 20;
let watched = title(3000 * EACH, false);
let views = title(1400 * EACH, true);
// `VICTORY_BENCH_HOLES=0`: views without holes.
let holes = std::env::var_os("VICTORY_BENCH_HOLES").is_none_or(|v| v != "0");
let views = if holes { with_holes(1400 * EACH / PAGE) } else { title(1400 * EACH, true) };
let there = |at: usize| !holes || (at - views) / PAGE % 4 != 3;
let big = title(BIG, true);
// SAFETY: the test's own memory.
unsafe {
std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH);
std::ptr::write_bytes(views as *mut u8, 1, 1400 * EACH);
for at in (views..views + 1400 * EACH).step_by(PAGE).filter(|&at| there(at)) {
std::ptr::write_bytes(at as *mut u8, 1, PAGE);
}
std::ptr::write_bytes(big as *mut u8, 1, BIG);
}
let mut small = Vec::new();
@@ -8271,8 +8422,10 @@ mod refresh_tests {
// The title's writes, and the relay's beside the submission.
for _ in 0..9 {
let at = views + random.below(1400 * EACH / 8) * 8;
// SAFETY: the test's own memory.
unsafe { (at as *mut u64).write_volatile(frame as u64) };
if there(at) {
// SAFETY: the test's own memory.
unsafe { (at as *mut u64).write_volatile(frame as u64) };
}
}
for _ in 0..60 {
let at = watched + random.below(3000 * EACH / 8) * 8;
+110 -6
View File
@@ -29,7 +29,7 @@
//! garbage records cannot run for seconds either.
//!
//! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535
//! groups per dimension and 2^20 per dispatch, one-dimensional mesh
//! groups per dimension, in x 2^20 ([`widest`]), and 2^20 per dispatch, one-dimensional mesh
//! dispatches, the budget) cut legitimate work beyond them; raise them if
//! the title needs more.
@@ -107,9 +107,11 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
cost = count * instances;
draw_counts = uint2(count, instances);
} else if (active && kind == 2) {
uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u));
// x * y fits 32 bits; the whole count may not.
if (g.z != 0 && g.x * g.y > GROUPS / g.z) {
uint3 g = src_args.Load3(src_at);
// Up to WIDEST groups in x run as asked (`widest`).
g = min(g, uint3(g.x <= WIDEST ? WIDEST : 65535u, 65535u, 65535u));
// x * y fits 32 bits where it is looked at; the whole count may not.
if ((g.y != 0 && g.x > GROUPS / g.y) || (g.z != 0 && g.x * g.y > GROUPS / g.z)) {
g = uint3(0, 0, 0);
}
cost = g.x * g.y * g.z * 64u;
@@ -237,9 +239,42 @@ fn make_for(device: &ID3D12Device) -> windows::core::Result<Clamp> {
make_from(device, SOURCE)
}
/// The most groups in x that an indirect dispatch runs as the title asks:
/// 65,535 is the most D3D12 names for a dispatch, 2^20 ([`SOURCE`]'s GROUPS)
/// what is bounded here anyway (`VICTORY_INDIRECT_WIDE=0`: 65,535; a record
/// that asks for more still runs 65,535).
///
/// The title's tile lists are dispatches of one group per tile, and two of
/// them are classes of the picture's 8x4 tiles, 115,200 in all at
/// 2560x1440: in a captured frame 67,440 and 47,760 (the program
/// 2dc364df5d3278b8 and 940c2635dc1312f4). Cut to 65,535 the first list lost
/// its last 1,905 tiles, the lowest of the picture. The console runs what it
/// is asked (its dispatch counts are 32 bits), and so does an AMD card, whose
/// dispatch packets and group numbers are the same; D3D12 does not look at
/// indirect counts. Other cards stay at 65,535.
fn widest(amd: bool) -> u32 {
let on = std::env::var_os("VICTORY_INDIRECT_WIDE").is_none_or(|v| v != "0");
if amd && on { 1 << 20 } else { 65_535 }
}
/// Whether `device` is an AMD card's.
fn amd(device: &ID3D12Device) -> bool {
use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIAdapter1, IDXGIFactory4};
// SAFETY: plain queries.
unsafe {
CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
.and_then(|f| f.EnumAdapterByLuid::<IDXGIAdapter1>(device.GetAdapterLuid()))
.and_then(|a| a.GetDesc1())
.is_ok_and(|d| d.VendorId == 0x1002)
}
}
/// The clamp compiled from `source` (ours, or in the benchmark the one it
/// replaced).
fn make_from(device: &ID3D12Device, source: &str) -> windows::core::Result<Clamp> {
#[cfg(feature = "diagnostics")]
let batched = source == batch::SOURCE;
let source = &format!("#define WIDEST {}u\n{source}", widest(amd(device)));
let mut code: Option<ID3DBlob> = None;
let mut errors: Option<ID3DBlob> = None;
// SAFETY: the source and names live through the call; out pointers ours.
@@ -1027,11 +1062,11 @@ void main() {
1,
[5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC],
);
// Record 2 exceeds 65,535 in X -> clamped to (65535, 1, 1).
// Record 2 exceeds what any card runs in X -> clamped to (65535, 1, 1).
write_record(
&mut initial_src,
2,
[100_000, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567],
[(1 << 20) + 1, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567],
);
for slot in 3..MAX as usize {
// Each garbage slot would clamp to 65535 * 16 * 1 = 1,048,560 groups
@@ -1832,6 +1867,75 @@ void main() {
sig.unwrap()
}
/// An AMD card runs every group of an indirect dispatch of more than
/// 65,535, each under its own number: the title's tile lists
/// ([`widest`]), clamped one by one and in a batch. Others are not asked.
#[test]
fn card_runs_wide_indirect_dispatches() {
const CS: &str = r#"
#define RS "UAV(u0)"
RWByteAddressBuffer seen : register(u0);
[RootSignature(RS)]
[numthreads(1, 1, 1)]
void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) {
uint was;
seen.InterlockedAdd(0, 1, was);
seen.InterlockedMax(4, group.x, was);
seen.InterlockedMax(8, thread.x, was);
seen.InterlockedAdd(16 + group.x * 4, 1, was);
}
"#;
let Some(mut gpu) = WarpHarness::on(false) else {
return;
};
if !amd(&gpu.device) || widest(true) == 65_535 {
return;
}
let worker = compile_cs(&gpu.device, CS).expect("the worker must compile");
let pass = make_from(&gpu.device, batch::SOURCE).expect("the batched clamp must compile");
let sig = gpu.signature(2, 12);
for asked in [67_440u32, 115_200, 1 << 20, (1 << 20) + 1] {
let runs = if asked > 1 << 20 { 65_535 } else { asked };
for batched in [false, true] {
let (src, src_ptr, src_gpu) = gpu.shared_buffer(1024);
let (_budget, budget_ptr, budget_gpu) = gpu.shared_buffer(256);
let (_table, table_ptr, table_gpu) = gpu.shared_buffer(batch::TABLE);
let size = 16 + (4 << 20) + 16;
let seen = gpu.default_uav(size);
let (back, back_ptr, _) = gpu.shared_buffer(size);
let dst = gpu.default_uav(64 << 10);
// SAFETY: mapped buffers, which nothing reads yet; an open
// list and live buffers.
unsafe {
std::ptr::write_bytes(budget_ptr, 0, 256);
for (w, word) in [asked, 1, 1].into_iter().enumerate() {
src_ptr.cast::<u32>().add(w).write_volatile(word);
}
if batched {
batch::record(&pass, &gpu.list, (&dst, D3D12_RESOURCE_STATE_COMMON), budget_gpu, [src_gpu; 4], table_gpu);
assert_eq!(batch::Table::new(table_ptr, 0, [1, 0, 0, 0]).place(1, 0, 2), Some(0));
} else {
let to = (&dst, D3D12_RESOURCE_STATE_COMMON);
assert!(record_clamp_as(&gpu.clamp, &gpu.list, to, budget_gpu, (&src, 0), None, (2, 12, 1), false));
}
gpu.list.SetComputeRootSignature(&worker.root);
gpu.list.SetPipelineState(&worker.pso);
gpu.list.SetComputeRootUnorderedAccessView(0, seen.GetGPUVirtualAddress());
gpu.list.ExecuteIndirect(&sig, 1, &dst, 0, None, 0);
gpu.list.ResourceBarrier(&[uav_barrier()]);
gpu.list.ResourceBarrier(&[transition(&seen, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
gpu.list.CopyBufferRegion(&back, 0, &seen, 0, size);
}
gpu.submit_and_wait();
// SAFETY: the list has run; mapped words.
let word = |i: usize| unsafe { back_ptr.cast::<u32>().add(i).read_volatile() };
assert_eq!([word(0), word(1), word(2)], [runs, runs - 1, runs - 1], "asked for {asked}, batched {batched}");
let wrong = (0..runs as usize).find(|&g| word(4 + g) != 1);
assert_eq!((wrong, word(4 + runs as usize)), (None, 0), "every group once, asked for {asked}");
}
}
}
/// What a batch's table says of records added to it: one job per
/// record, charged for every execution that reads it, and none for what
/// the pass cannot read.
+3 -2
View File
@@ -81,8 +81,9 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
record[1] = min(record[1], (1u << 26) / max(record[0], 1u));
cost = record[0] * record[1];
} else if (kind == 2) {
uint3 g = min(uint3(record[0], record[1], record[2]), uint3(65535u, 65535u, 65535u));
if (g.z != 0 && g.x * g.y > GROUPS / g.z) {
uint3 g = uint3(record[0], record[1], record[2]);
g = min(g, uint3(g.x <= WIDEST ? WIDEST : 65535u, 65535u, 65535u));
if ((g.y != 0 && g.x > GROUPS / g.y) || (g.z != 0 && g.x * g.y > GROUPS / g.z)) {
g = uint3(0, 0, 0);
}
cost = g.x * g.y * g.z * 64u;
+41
View File
@@ -329,6 +329,26 @@ pub(crate) fn views_gone(at: usize, len: usize) {
}
}
/// How many bytes of `[at, at + len)` views of physical pages show; `None`
/// if no view touches it (nothing is mapped there, or memory of another
/// kind). The runtime's own record of what it mapped: no question to the
/// host.
pub(crate) fn shown_bytes(at: usize, len: usize) -> Option<u64> {
let end = at.saturating_add(len);
let v = views();
let first = v.views.range(..=at).next_back();
let rest = v.views.range(at.saturating_add(1)..end.max(at.saturating_add(1)));
let (mut there, mut any) = (0u64, false);
for (&base, view) in first.into_iter().chain(rest) {
let (from, to) = (base.max(at), base.saturating_add(view.0).min(end));
if from < to {
there += (to - from) as u64;
any = true;
}
}
any.then_some(there)
}
/// How the views cover `[at, at + len)`.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub(crate) enum Cover {
@@ -1074,6 +1094,27 @@ mod tests {
/// Views as the runtime tells them: a range inside one view, or over
/// views that continue each other in one section, is one run; over
/// views from elsewhere it is scattered; over a gap it has holes.
#[test]
fn the_views_say_how_much_of_a_range_is_there() {
const K64: usize = 64 << 10;
// Addresses nothing has: only the record is asked.
let at = 0x7ff1_0000_0000_usize;
for (block, blocks) in [(0, 1), (1, 1), (4, 2)] {
super::title_memory_view(at + block * K64, blocks * K64, 7, 0);
}
let shown = |from: usize, len: usize| super::shown_bytes(at + from, len);
assert_eq!(shown(0, 8 * K64), Some(4 * K64 as u64));
assert_eq!(shown(100, K64), Some(K64 as u64));
assert_eq!(shown(K64 + 100, 2 * K64), Some(K64 as u64 - 100));
assert_eq!(shown(5 * K64 + 1, 10), Some(10));
assert_eq!(shown(2 * K64, 2 * K64), None);
assert_eq!(shown(6 * K64, 2 * K64), None);
super::views_gone(at + K64, K64);
assert_eq!(shown(0, 2 * K64), Some(K64 as u64));
super::views_gone(at, 8 * K64);
assert_eq!(shown(0, 8 * K64), None);
}
#[test]
fn views_say_what_one_placed_buffer_could_show() {
let mut views = BTreeMap::new();
+85 -3
View File
@@ -133,6 +133,16 @@ pub(crate) fn spent(which: usize, from: std::time::Instant) -> std::time::Instan
/// For the frame-rate line: where landing went, per frame.
pub(crate) fn log(frames: f64) {
let t: Vec<f64> = TAKEN.iter().map(|t| t.swap(0, Ordering::Relaxed) as f64 / frames).collect();
if t[0] > 0.0 {
tracing::info!(
"blocks landed in beside the guards per frame: {:.0}, {:.0} of them held by the copy they were landed through, which takes \
them no more (VICTORY_LAND_TAKEN={})",
t[0],
t[1],
u8::from(taken()),
);
}
let s: Vec<f64> = STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
if s[stat::PIECES] == 0.0 && s[stat::REST] == 0.0 {
return;
@@ -416,8 +426,39 @@ pub(crate) struct Notes {
pages: Vec<usize>,
/// Per piece, from the first such page to the last: address, bytes.
spans: Vec<(usize, usize)>,
/// Per piece put beside the guards, all of it: its 64 KiB block and the
/// copy it was landed through (which the job holds until the flush).
landed: Vec<(usize, *const crate::shadow::Shadow)>,
}
// SAFETY: the pointers are used by the job that has the notes, in `flush`.
unsafe impl Send for Notes {}
/// Whether a copy a landing went through is noted as up to date with it
/// (`VICTORY_LAND_TAKEN=0`: it is not, and the next refresh copies the 64
/// KiB again and sends them up to the card, as before).
///
/// What a landing puts into title memory the copy holds already: the card
/// wrote it there, and a copy in the card's memory was given it on the CPU's
/// side by the same merge. But the block counted as written, for that copy
/// as for every other one, so the next refresh copied the whole block, sent
/// it up and had the card hash it again: some 900 blocks a frame landed
/// beside the guards, of the 103 MB a frame that went up (run record-1).
///
/// Why it may be left out ([`crate::shadow::Shadow::landed`]): the copy held
/// title memory's bytes of the block before the landing, if it had taken it
/// after the block's last noted write and no write was to be noted (the
/// block's bit, `crate::watch::block_published`), and the landing put the
/// same bytes into both. Only where one copy alone landed in the block.
fn taken() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_LAND_TAKEN").is_none_or(|v| v != "0"))
}
/// Since the last frame-rate line: blocks landed in beside the guards, and
/// those of them the copy was noted as up to date with.
static TAKEN: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
impl Notes {
/// At the end of a job: what it wrote beside the guards is noted.
pub(crate) fn flush(&mut self) {
@@ -425,9 +466,24 @@ impl Notes {
return;
}
let noting = std::time::Instant::now();
crate::watch::landed_beside(&self.pages, &self.spans);
let (now, blocks) = crate::watch::landed_beside(&self.pages, &self.spans);
TAKEN[0].fetch_add(blocks.len() as u64, Ordering::Relaxed);
if taken() {
for (block, before) in blocks {
let mut through = self.landed.iter().filter(|l| l.0 == block).map(|l| l.1);
let Some(copy) = through.next() else {
continue;
};
if !copy.is_null() && through.all(|other| other == copy) {
// SAFETY: the job holds its copies until this is done.
let copy = unsafe { &*copy };
TAKEN[1].fetch_add(u64::from(copy.landed(block, before, now)), Ordering::Relaxed);
}
}
}
self.pages.clear();
self.spans.clear();
self.landed.clear();
spent(stat::NOTES, noting);
}
}
@@ -447,9 +503,10 @@ pub(crate) unsafe fn piece(
parts: &[(usize, usize)],
take: bool,
notes: &mut Notes,
copy: *const crate::shadow::Shadow,
) -> u64 {
// SAFETY: the caller's.
unsafe { piece_at(title, now, held, parts, take, notes, beside_on()) }
unsafe { piece_at(title, now, held, parts, take, notes, beside_on(), copy) }
}
/// [`piece`], and whether a view of ours is looked for.
@@ -464,6 +521,7 @@ unsafe fn piece_at(
take: bool,
notes: &mut Notes,
beside: bool,
copy: *const crate::shadow::Shadow,
) -> u64 {
let Some(end) = parts.last().map(|p| p.1) else {
return 0;
@@ -499,6 +557,7 @@ unsafe fn piece_at(
spent(stat::NOTES, opening);
}
let into = beside.unwrap_or(title);
let since = crate::watch::changes();
let (mut pages, mut new_pages, mut blocks, mut dwords, mut missing) = (0, 0u64, 0, 0, 0);
let mut span: Option<(usize, usize)> = None;
for_pages(title, parts, |from, n| {
@@ -508,7 +567,26 @@ unsafe fn piece_at(
}
// SAFETY: the caller's; title memory, by an address that shows it
// (`beside`) or the title's own.
let done = unsafe { crate::safecopy::merge(into.wrapping_add(from) as *mut u8, now.add(from), held.add(from), n, take) };
let merge = |take| unsafe { crate::safecopy::merge(into.wrapping_add(from) as *mut u8, now.add(from), held.add(from), n, take) };
let mut done = merge(take && beside.is_some());
if !done.there && beside.is_none() {
// Away only while the runtime changes a mapping beside it: the
// rest of it when that is done. What is still not there then is
// taken as the caller says.
let mut put = done.dwords;
let again = crate::watch::again_after_change(since, || {
done = merge(false);
put += done.dwords;
done.there
});
if !again && take {
done = merge(true);
put += done.dwords;
}
done.dwords = put;
// (What was new to the first try was new.)
done.new = done.new.max(1);
}
blocks += done.new;
dwords += done.dwords;
missing += u64::from(!done.there);
@@ -527,6 +605,10 @@ unsafe fn piece_at(
});
if let Some((from, to)) = span {
notes.spans.push((from, to - from));
// Not through a copy that is not to be noted, if that is asked: the
// block then has two.
let through = if missing == 0 { copy } else { std::ptr::null() };
notes.landed.push((title / BLOCK, through));
}
count(stat::NEW_PIECES, u64::from(new_pages > 0));
count(stat::PAGES, pages);
+40 -3
View File
@@ -192,7 +192,7 @@ fn a_piece_lands_what_the_card_wrote_in_its_parts() {
let asked = crate::watch::writes(title.at, title.at + BLOCK, true).expect("a view").0;
let mut notes = Notes::default();
// SAFETY: vectors of `len` bytes.
let put = unsafe { piece(title.at + from, now.as_ptr(), held.as_mut_ptr(), &parts, true, &mut notes) };
let put = unsafe { piece(title.at + from, now.as_ptr(), held.as_mut_ptr(), &parts, true, &mut notes, std::ptr::null()) };
notes.flush();
let mut expect_held = base.clone();
let mut expect = there.clone();
@@ -213,6 +213,43 @@ fn a_piece_lands_what_the_card_wrote_in_its_parts() {
}
}
/// A piece whose title memory is away only while the runtime changes a
/// mapping lands when that is done; where it stays away the copy's CPU side
/// takes the card's bytes (`take`) or not.
#[test]
fn a_piece_waits_for_a_change_of_mapping() {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, VirtualAlloc, VirtualFree};
assert!(crate::safecopy::on());
// SAFETY: a reservation of ours, nothing of it committed.
let at = unsafe { VirtualAlloc(std::ptr::null(), BLOCK, MEM_RESERVE, PAGE_NOACCESS) } as usize;
assert_ne!(at, 0);
let now = [9u8; 100];
for take in [true, false] {
let mut held = [0u8; 100];
// SAFETY: arrays of 100 bytes.
let put = unsafe { piece(at, now.as_ptr(), held.as_mut_ptr(), &[(0, 100)], take, &mut Notes::default(), std::ptr::null()) };
assert_eq!((put, held), (0, [if take { 9 } else { 0 }; 100]));
}
let (began, wait) = std::sync::mpsc::channel();
let change = std::thread::spawn(move || {
let _changing = crate::watch::title_memory_remapping();
began.send(()).unwrap();
std::thread::sleep(std::time::Duration::from_millis(50));
// SAFETY: the reservation's first page.
assert!(!unsafe { VirtualAlloc(at as _, PAGE, MEM_COMMIT, PAGE_READWRITE) }.is_null());
});
wait.recv().unwrap();
let mut held = [0u8; 100];
// SAFETY: as above.
let put = unsafe { piece(at, now.as_ptr(), held.as_mut_ptr(), &[(0, 100)], true, &mut Notes::default(), std::ptr::null()) };
change.join().unwrap();
assert_eq!((put, held), (100, now));
// SAFETY: committed by now.
assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, 100) }, now);
// SAFETY: our reservation.
unsafe { VirtualFree(at as _, 0, MEM_RELEASE) };
}
/// Landings on several threads beside title threads that write the same
/// blocks (other dwords) and a thread that refreshes a copy, guarding what
/// it takes: no write of the title's is lost or undone, all the card wrote
@@ -292,7 +329,7 @@ fn landings_beside_the_title_and_its_refreshes_lose_nothing() {
let offset = address - at;
// SAFETY: each job its own pieces of the two vectors.
unsafe {
piece(address, now.as_ptr().add(offset), (into + offset) as *mut u8, &[(0, len)], true, &mut notes);
piece(address, now.as_ptr().add(offset), (into + offset) as *mut u8, &[(0, len)], true, &mut notes, std::ptr::null());
}
}
notes.flush();
@@ -420,7 +457,7 @@ fn what_landing_costs() {
let mut notes = Notes::default();
for &(at, now, held) in &landing[jobs[j].clone()] {
// SAFETY: each its own bytes.
unsafe { piece_at(at, now as *const u8, held as *mut u8, &[(0, BLOCK)], true, &mut notes, beside) };
unsafe { piece_at(at, now as *const u8, held as *mut u8, &[(0, BLOCK)], true, &mut notes, beside, std::ptr::null()) };
}
notes.flush();
});
+2 -2
View File
@@ -72,6 +72,6 @@ pub use host::on_failure;
pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view};
#[cfg(windows)]
pub use watch::{
title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_unmapping,
writing as kernel_will_write,
kernel_writing, title_memory_allocated, title_memory_freed, title_memory_reading, title_memory_remapped,
title_memory_remapping, title_memory_unmapping, writing as kernel_will_write,
};
+81 -3
View File
@@ -296,13 +296,19 @@ impl GraphicsState {
.map(|e| {
let slot = e.InputSlot.min(31) as usize;
let format = e.Format.0 as u32;
let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32);
// An appended element starts at the next multiple of
// min(4, its size) after the previous one, where D3D12 (and
// vkd3d) place it; the host pipeline gets the title's
// descriptions, so the offsets read here must match.
let offset = if e.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT {
next[slot]
.checked_next_multiple_of(bytes.clamp(1, 4))
.unwrap_or(u32::MAX)
} else {
e.AlignedByteOffset
};
let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32);
next[slot] = offset + bytes;
next[slot] = offset.saturating_add(bytes);
Input {
slot: slot as u32,
offset,
@@ -437,6 +443,19 @@ impl HostPipeline {
}
let host = host()?;
let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS19::default();
// SAFETY: the feature query writes the structure of the given size.
// Older runtimes may not recognize OPTIONS19; that means no support.
let aniso_point_mip_supported = unsafe {
host.device.CheckFeatureSupport(
D3D12_FEATURE_D3D12_OPTIONS19,
(&raw mut options).cast(),
size_of_val(&options) as u32,
)
}
.is_ok()
&& options.AnisoFilterWithPointMipSupported.as_bool();
// The root signature the translated shaders' bindings define.
let mut params: Vec<D3D12_ROOT_PARAMETER1> = Vec::new();
// The ranges table parameters point at, alive until the root
@@ -544,7 +563,7 @@ impl HostPipeline {
}
for (n, s) in t.static_samplers.iter().enumerate() {
samplers.push(D3D12_STATIC_SAMPLER_DESC {
Filter: D3D12_FILTER(s.filter as i32),
Filter: D3D12_FILTER(s.filter_for_host(aniso_point_mip_supported) as i32),
AddressU: D3D12_TEXTURE_ADDRESS_MODE(s.address[0] as i32),
AddressV: D3D12_TEXTURE_ADDRESS_MODE(s.address[1] as i32),
AddressW: D3D12_TEXTURE_ADDRESS_MODE(s.address[2] as i32),
@@ -1431,4 +1450,63 @@ mod tests {
assert_eq!(run_draw(0.6, 1.0), 0, "depth 0.5 outside [0.6, 1.0] must be rejected");
assert_eq!(run_draw(0.4, 0.6), 255, "depth 0.5 inside [0.4, 0.6] must pass");
}
fn element(format: DXGI_FORMAT, offset: u32) -> D3D12_INPUT_ELEMENT_DESC {
D3D12_INPUT_ELEMENT_DESC {
SemanticName: PCSTR(c"TEXCOORD".as_ptr().cast()),
SemanticIndex: 0,
Format: format,
InputSlot: 0,
AlignedByteOffset: offset,
InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,
InstanceDataStepRate: 0,
}
}
fn offsets(inputs: &[D3D12_INPUT_ELEMENT_DESC]) -> Vec<u32> {
let state = GraphicsState {
inputs: inputs.to_vec(),
..GraphicsState::default()
};
state.elements().iter().map(|e| e.offset).collect()
}
/// An appended element after one of 1 or 2 bytes started right after
/// it; D3D12 aligns it to min(4, its size), so the rectangle expansion
/// read its vertices from the wrong bytes.
#[test]
fn appended_elements_are_aligned() {
const APPEND: u32 = D3D12_APPEND_ALIGNED_ELEMENT;
// RG8 (2 bytes) then RG32 float: 4, not 2.
let a = [
element(DXGI_FORMAT_R8G8_UNORM, 0),
element(DXGI_FORMAT_R32G32_FLOAT, APPEND),
];
assert_eq!(offsets(&a), [0, 4]);
// R8 then R16 float: 2, not 1; then R8 packs right after it.
let b = [
element(DXGI_FORMAT_R8_UNORM, 0),
element(DXGI_FORMAT_R16_FLOAT, APPEND),
element(DXGI_FORMAT_R8_UNORM, APPEND),
];
assert_eq!(offsets(&b), [0, 2, 4]);
// Already aligned layouts are unchanged.
let c = [
element(DXGI_FORMAT_R8G8B8A8_UNORM, 0),
element(DXGI_FORMAT_R32G32_FLOAT, APPEND),
element(DXGI_FORMAT_R32G32B32_FLOAT, APPEND),
];
assert_eq!(offsets(&c), [0, 4, 12]);
}
/// An explicit offset near 4 GiB overflowed the next appended offset
/// (a panic in debug builds).
#[test]
fn a_huge_explicit_offset_does_not_overflow() {
let inputs = [
element(DXGI_FORMAT_R32G32B32A32_FLOAT, u32::MAX - 8),
element(DXGI_FORMAT_R32_FLOAT, D3D12_APPEND_ALIGNED_ELEMENT),
];
let _ = offsets(&inputs);
}
}
+46 -2
View File
@@ -55,6 +55,8 @@ enum Kind {
F16,
Unorm8,
Unorm16,
Snorm8,
Snorm16,
}
/// Component count and kind of the vertex formats rectangles use.
@@ -69,7 +71,16 @@ fn components(format: u32) -> Option<(usize, Kind)> {
54 => (1, Kind::F16),
11 => (4, Kind::Unorm16),
35 => (2, Kind::Unorm16),
56 => (1, Kind::Unorm16),
28 | 29 | 87 | 91 => (4, Kind::Unorm8),
49 => (2, Kind::Unorm8),
61 => (1, Kind::Unorm8),
13 => (4, Kind::Snorm16),
37 => (2, Kind::Snorm16),
58 => (1, Kind::Snorm16),
31 => (4, Kind::Snorm8),
51 => (2, Kind::Snorm8),
63 => (1, Kind::Snorm8),
_ => return None,
})
}
@@ -78,8 +89,8 @@ impl Kind {
fn bytes(self) -> usize {
match self {
Kind::F32 => 4,
Kind::F16 | Kind::Unorm16 => 2,
Kind::Unorm8 => 1,
Kind::F16 | Kind::Unorm16 | Kind::Snorm16 => 2,
Kind::Unorm8 | Kind::Snorm8 => 1,
}
}
@@ -90,6 +101,8 @@ impl Kind {
Kind::F16 => half_to_f32(u16::from_le_bytes([b[0], b[1]])),
Kind::Unorm16 => f32::from(u16::from_le_bytes([b[0], b[1]])) / 65535.0,
Kind::Unorm8 => f32::from(b[0]) / 255.0,
Kind::Snorm16 => (f32::from(i16::from_le_bytes([b[0], b[1]])) / 32767.0).max(-1.0),
Kind::Snorm8 => (f32::from(b[0] as i8) / 127.0).max(-1.0),
}
}
@@ -103,6 +116,10 @@ impl Kind {
b.copy_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_le_bytes())
}
Kind::Unorm8 => b[0] = (v.clamp(0.0, 1.0) * 255.0).round() as u8,
Kind::Snorm16 => {
b.copy_from_slice(&((v.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes())
}
Kind::Snorm8 => b[0] = (v.clamp(-1.0, 1.0) * 127.0).round() as i8 as u8,
}
}
}
@@ -218,6 +235,33 @@ mod tests {
assert_eq!(dst[40..], vertex(4.0, 6.0)[..]);
}
#[test]
fn normalized_attributes_are_interpolated_in_their_own_range() {
let vertex = |rg: [u8; 2], u16_value: u16, u8_value: u8, snorm8: i8, snorm16: i16| {
[
&rg[..],
&u16_value.to_le_bytes(),
&[u8_value, snorm8 as u8],
&snorm16.to_le_bytes(),
]
.concat()
};
let src = [
vertex([3, 250], 1000, 10, i8::MIN, -23000),
vertex([8, 200], 500, 3, -120, -18000),
vertex([20, 253], 10000, 100, -120, -32000),
]
.concat();
let mut dst = [0; 6 * 8];
expand_rects(
&src,
&mut dst,
8,
&[(0, 49), (2, 56), (4, 61), (5, 63), (6, 58)],
);
assert_eq!(dst[40..], vertex([15, 255], 10500, 107, -127, -32767));
}
/// `half_to_f32` reads subnormals, so an f16 rectangle output must be
/// able to write them back instead of flushing every one to zero.
#[test]
+4
View File
@@ -8,6 +8,10 @@ use super::wire::{ALL, Barrier, Cmd, NONE, Va, slot};
/// The buffer the clamped arguments of all clamp passes lie in, in lists
/// edited by [`clamps`].
pub const RESULTS: u32 = u32::MAX - 1;
/// The buffer texels are read back through (`play::pixel`).
pub const PROBE: u32 = u32::MAX - 2;
/// A buffer of the card's that depth goes through on the way there.
pub const SCRATCH: u32 = u32::MAX - 3;
const INDIRECT_ARGUMENT: i32 = 0x200;
const UNORDERED_ACCESS: i32 = 0x8;
+14 -1
View File
@@ -32,6 +32,7 @@ use super::wire::{
pub mod diverge;
pub mod look;
mod merge;
pub mod pixel;
mod upcopies;
/// The name of the argument clamp's pipeline, by which its passes are
@@ -363,6 +364,12 @@ pub fn listing(folder: &Path, lists: (u32, u32), line: &mut dyn FnMut(&str)) ->
other => format!("{other:?}"),
};
line(&format!("buffer {} {} bytes, {place}: {}", r.id, r.desc.width, r.name));
} else {
let d = &r.desc;
line(&format!(
"texture {} {}x{}x{} mips {} f{}: {}",
r.id, d.width, d.height, d.depth, d.mips, d.format, r.name
));
}
}
let mut place = 0;
@@ -468,6 +475,8 @@ pub struct Player {
card_writes: HashSet<u32>,
/// The results of clamp passes ([`RESULTS`]).
results: Option<ID3D12Resource>,
/// Other buffers of ours that commands name.
extra: HashMap<u32, ID3D12Resource>,
commands: Vec<Vec<Cmd>>,
/// Resources in the states of the start (not those of the end).
fresh: bool,
@@ -535,6 +544,7 @@ impl Player {
merging: false,
card_writes: HashSet::new(),
results: None,
extra: HashMap::new(),
commands,
fresh: true,
at: States::default(),
@@ -632,7 +642,10 @@ impl Player {
if id == RESULTS {
return self.results.as_ref();
}
self.objects.get(&id).map(|o| &o.res)
self.objects
.get(&id)
.map(|o| &o.res)
.or_else(|| self.extra.get(&id))
}
fn va(&self, va: &Va) -> u64 {
+843
View File
@@ -0,0 +1,843 @@
//! What draws a pixel: `--pixel`. After every command that can change a
//! texture, the texel under the pixel is copied out of it (of a draw: of its
//! targets, where the pixel lies in its viewport, and of the textures shaders
//! may write; of a dispatch: of those; of a copy, clear or resolve: of where
//! it goes), and commands that changed one are named with the values before
//! and after.
use super::edit::{PROBE, SCRATCH};
use super::*;
/// What to look at.
#[derive(Clone, Debug, Default)]
pub struct Pixels {
/// Points of the presented picture.
pub points: Vec<(u32, u32)>,
/// Texels of textures: resource, subresource, place.
pub texels: Vec<(u32, u32, u32, u32)>,
/// Only these lists are looked into.
pub lists: Option<(u32, u32)>,
/// Depth targets too (a copy of the whole target for each draw).
pub depth: bool,
/// Textures shaders may write too.
pub written: bool,
/// Indirect draws that are run one by one: list, command.
pub split: Vec<(u32, u32)>,
}
/// Bytes a sample has.
const ROOM: u64 = 512;
/// The most samples of one run.
const MOST: usize = 1 << 20;
#[derive(Clone, Debug)]
struct Sample {
list: u32,
command: usize,
/// Of a split draw: which one.
part: u32,
before: bool,
spot: Spot,
pso: u32,
what: &'static str,
}
/// A texture's part that a sample can be taken from.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct Spot {
res: u32,
sub: u32,
x: u32,
y: u32,
z: u32,
/// The point of the picture it stands for (or [`OWN`]).
point: usize,
format: i32,
depth: bool,
}
/// In [`Spot::point`]: a texel asked for by itself.
const OWN: usize = usize::MAX;
/// The texel of a target of `size` that shows the point `(x, y)` of a picture
/// of `picture`, drawn through `view` (x, y, width, height): none if the
/// target has another shape than the picture.
fn texel(
(x, y): (u32, u32),
picture: (u32, u32),
view: [f32; 4],
size: (u32, u32),
) -> Option<(u32, u32)> {
let (w, h) = (picture.0 as f32, picture.1 as f32);
if !same_shape((view[2], view[3]), (w, h)) || view[2] < 16.0 {
return None;
}
let a = (view[0] + (x as f32 + 0.5) / w * view[2]).floor();
let b = (view[1] + (y as f32 + 0.5) / h * view[3]).floor();
(a >= 0.0 && b >= 0.0 && a < size.0 as f32 && b < size.1 as f32).then_some((a as u32, b as u32))
}
fn same_shape(a: (f32, f32), b: (f32, f32)) -> bool {
(0.97..1.03).contains(&(a.0 * b.1 / (a.1 * b.0).max(1e-6)))
}
/// A float from a small one's bits (5 bits of exponent, `mantissa` of
/// mantissa, no sign).
fn small(bits: u32, mantissa: u32) -> f32 {
let (e, m) = (
bits >> mantissa & 31,
(bits & ((1 << mantissa) - 1)) as f32,
);
let unit = (1u32 << mantissa) as f32;
match e {
0 => m / unit * 2f32.powi(-14),
31 if m == 0.0 => f32::INFINITY,
31 => f32::NAN,
e => (1.0 + m / unit) * 2f32.powi(e as i32 - 15),
}
}
/// Bytes of a texel of a format; 0 for formats not read.
fn texel_bytes(format: i32) -> usize {
match format {
1..=4 => 16,
5..=8 => 12,
9..=22 => 8,
23..=47 => 4,
48..=59 => 2,
60..=65 => 1,
67 | 85..=93 => 4,
_ => 0,
}
}
/// A texel in words.
fn texel_text(format: i32, b: &[u8]) -> String {
let n = texel_bytes(format);
if n == 0 || b.len() < n {
return format!("{b:02x?}");
}
let word = |i: usize| u32::from_le_bytes([b[i * 4], b[i * 4 + 1], b[i * 4 + 2], b[i * 4 + 3]]);
let float = |i: usize| f32::from_bits(word(i));
let short = |i: usize| u16::from_le_bytes([b[i * 2], b[i * 2 + 1]]);
let half = |i: usize| {
let v = small(u32::from(short(i) & 0x7FFF), 10);
if short(i) >> 15 != 0 { -v } else { v }
};
let unorm16 = |i: usize| f32::from(short(i)) / 65535.0;
let snorm16 = |i: usize| f32::from(short(i) as i16) / 32767.0;
let unorm8 = |i: usize| f32::from(b[i]) / 255.0;
let snorm8 = |i: usize| f32::from(b[i] as i8) / 127.0;
let all: Vec<f32> = match format {
1 | 2 => (0..4).map(float).collect(),
5 | 6 => (0..3).map(float).collect(),
9 | 10 => (0..4).map(half).collect(),
11 => (0..4).map(unorm16).collect(),
13 => (0..4).map(snorm16).collect(),
15 | 16 => (0..2).map(float).collect(),
23 | 24 => vec![
(word(0) & 1023) as f32 / 1023.0,
(word(0) >> 10 & 1023) as f32 / 1023.0,
(word(0) >> 20 & 1023) as f32 / 1023.0,
(word(0) >> 30) as f32 / 3.0,
],
26 => vec![
small(word(0) & 2047, 6),
small(word(0) >> 11 & 2047, 6),
small(word(0) >> 22, 5),
],
27..=29 | 87 | 90 | 91 => (0..4).map(unorm8).collect(),
31 => (0..4).map(snorm8).collect(),
33 | 34 => (0..2).map(half).collect(),
35 => (0..2).map(unorm16).collect(),
37 => (0..2).map(snorm16).collect(),
39..=41 => vec![float(0)],
48 | 49 => (0..2).map(unorm8).collect(),
51 => (0..2).map(snorm8).collect(),
53 | 54 => vec![half(0)],
55 | 56 => vec![unorm16(0)],
58 => vec![snorm16(0)],
60 | 61 => vec![unorm8(0)],
63 => vec![snorm8(0)],
_ => Vec::new(),
};
let all: Vec<String> = all.iter().map(|v| format!("{v:.5}")).collect();
format!("{} {:02x?}", all.join(" "), &b[..n]).trim().to_owned()
}
/// One draw of an indirect call that has many.
fn part_of(c: &Cmd, i: u32, stride: u32) -> Cmd {
match c {
Cmd::Indirect {
signature,
args,
at,
..
} => Cmd::Indirect {
signature: *signature,
most: 1,
args: *args,
at: at + u64::from(i) * u64::from(stride),
count: NONE,
count_at: 0,
},
c => c.clone(),
}
}
fn transition(res: u32, sub: u32, before: u32, after: u32) -> Barrier {
Barrier::Transition {
flags: 0,
res,
sub,
before: before as i32,
after: after as i32,
}
}
/// What is known of the frame's textures.
struct Textures {
/// Formats copies have.
copied_as: HashMap<u32, i32>,
/// Textures shaders may write and that have the picture's shape.
shaped: Vec<u32>,
/// The viewport targets of a size were last drawn through.
drawn: HashMap<(u32, u32), [f32; 4]>,
}
impl Player {
fn texture(&self, id: u32) -> Option<&wire::Resource> {
let o = self.objects.get(&id)?;
let r = &self.frame.resources[o.index];
(r.desc.dimension != D3D12_RESOURCE_DIMENSION_BUFFER.0 && r.desc.samples[0] <= 1)
.then_some(r)
}
/// What a view of a target is of: subresource, depth slice, size, format.
fn seen_by(&self, s: &Slot) -> Option<(u32, u32, (u32, u32), i32)> {
let r = self.texture(s.res)?;
let word = |i: usize| {
u32::from_le_bytes([
s.desc[i * 4],
s.desc[i * 4 + 1],
s.desc[i * 4 + 2],
s.desc[i * 4 + 3],
])
};
let (mut mip, mut slice, mut z, mut format) = (0, 0, 0, 0);
if s.described != 0 {
format = word(0) as i32;
match (s.kind, word(1) as i32) {
// 2D, 2D array and 3D views.
(slot::RTV, 4) => mip = word(2),
(slot::RTV, 5) => (mip, slice) = (word(2), word(3)),
(slot::RTV, 8) => (mip, z) = (word(2), word(3)),
(slot::DSV, 3) => mip = word(3),
(slot::DSV, 4) => (mip, slice) = (word(3), word(4)),
_ => return None,
}
}
if format == 0 {
format = r.desc.format;
}
let mips = u32::from(r.desc.mips.max(1));
let mip = mip.min(mips - 1);
let size = (
(r.desc.width as u32 >> mip).max(1),
(r.desc.height >> mip).max(1),
);
Some((mip + slice * mips, z, size, format))
}
/// Width and height of the presented picture.
pub fn picture_size(&self) -> Option<(u32, u32)> {
self.frame.presents.last().map(|p| (p.width, p.height))
}
/// Says which commands change the texels under points of the picture.
pub fn pixel(&mut self, o: &Options, p: &Pixels, say: &mut dyn FnMut(String)) -> Result<()> {
let picture = self.picture_size().context("no picture was presented")?;
self.set_merging(o.merge)?;
let mut report = Report::default();
let submits = self.edited(o, &mut report, &[]);
let counts = self.counts_of(o, p, &submits)?;
let mut samples: Vec<Sample> = Vec::new();
let made = self.sampled(p, &submits, picture, &counts, &mut samples)?;
let bytes = self.probed(o, &made, samples.len() as u64 * ROOM)?;
say(format!(
"{} texels taken; picture {}x{}; points {:?}",
samples.len(),
picture.0,
picture.1,
p.points
));
report.notes.drain(..).for_each(&mut *say);
let mut last: HashMap<(u32, u32, (u32, u32), usize), Vec<u8>> = HashMap::new();
let mut said = None;
for (i, s) in samples.iter().enumerate() {
let t = &s.spot;
let n = texel_bytes(t.format).max(1);
let now = bytes[i * ROOM as usize..][..n].to_vec();
let was = last.insert((t.res, t.sub, (t.x, t.y), t.point), now.clone());
if was.as_ref() == Some(&now) {
continue;
}
let point = match t.point {
OWN => String::new(),
n => format!("point {n} "),
};
let spot = format!(
" {point}{} sub {} at {},{}:",
self.called(t.res),
t.sub,
t.x,
t.y
);
let now = texel_text(t.format, &now);
if s.before {
// Seen for the first time, or changed by what is not looked
// into.
if was.is_some() {
say(format!("{spot} changed unseen to {now}"));
}
continue;
}
if said != Some((s.list, s.command, s.part)) {
said = Some((s.list, s.command, s.part));
let part = match p.split.contains(&(s.list, s.command as u32)) {
true => format!(" draw {}", s.part),
false => String::new(),
};
let of = match s.pso {
NONE => String::new(),
pso => format!(" of {pso} {}", self.pipeline_name(pso)),
};
say(format!("{}:{}{part} {}{of}", s.list, s.command, s.what));
}
let was = was.map_or("?".to_owned(), |w| texel_text(t.format, &w));
say(format!("{spot} {was} -> {now}"));
}
Ok(())
}
/// Runs the frame with commands that copy to [`PROBE`], which is of
/// `len` bytes; its bytes after that.
fn probed(&mut self, o: &Options, submits: &[Vec<Vec<Cmd>>], len: u64) -> Result<Vec<u8>> {
let (back, data) = gpu::buffer(
&self.device,
D3D12_HEAP_TYPE_READBACK,
len.max(4),
D3D12_RESOURCE_FLAG_NONE,
)?;
self.extra.insert(PROBE, back);
self.restore(o.restore)?;
let built = self.build(submits, o)?;
self.fresh = false;
self.send(&built, o)?;
// SAFETY: the mapping; the copies into it have run.
let bytes = unsafe { std::slice::from_raw_parts(data, len as usize) }.to_vec();
self.extra.remove(&PROBE);
Ok(bytes)
}
/// How many draws the calls to be split have.
fn counts_of(
&mut self,
o: &Options,
p: &Pixels,
submits: &[Vec<Vec<Cmd>>],
) -> Result<HashMap<(u32, u32), u32>> {
let mut counts = HashMap::new();
if p.split.is_empty() {
return Ok(counts);
}
const ARGS: u32 = 0x200;
let mut made = submits.to_vec();
let mut asked: Vec<(u32, u32)> = Vec::new();
for (here, cmds) in made.iter_mut().flatten().enumerate() {
let mut out = Vec::new();
for (n, c) in std::mem::take(cmds).into_iter().enumerate() {
let key = (here as u32, n as u32);
if let Cmd::Indirect {
most,
count,
count_at,
..
} = c
&& p.split.contains(&key)
{
counts.insert(key, most);
if count != NONE {
out.push(Cmd::Barriers {
all: vec![transition(count, ALL, ARGS, COPY_SOURCE)],
});
out.push(Cmd::CopyBuffer {
dst: PROBE,
dst_at: asked.len() as u64 * 4,
src: count,
src_at: count_at,
len: 4,
});
out.push(Cmd::Barriers {
all: vec![transition(count, ALL, COPY_SOURCE, ARGS)],
});
asked.push(key);
}
}
out.push(c);
}
*cmds = out;
}
let bytes = self.probed(o, &made, asked.len() as u64 * 4)?;
for (key, n) in asked.iter().zip(bytes.chunks_exact(4)) {
if let Some(most) = counts.get_mut(key) {
*most = (*most).min(u32::from_le_bytes([n[0], n[1], n[2], n[3]]));
}
}
Ok(counts)
}
fn textures(&self, picture: (u32, u32)) -> Textures {
let textures = || {
self.frame
.resources
.iter()
.filter(|r| self.texture(r.id).is_some())
};
let shaped = textures()
.filter(|r| {
let d = &r.desc;
d.dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D.0
&& d.flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0
&& d.width as u32 * 4 >= picture.0
&& same_shape(
(d.width as f32, d.height as f32),
(picture.0 as f32, picture.1 as f32),
)
})
.map(|r| r.id)
.collect();
let copied_as = textures()
.map(|r| {
let f = gpu::footprints(&self.device, &gpu::to_desc(&r.desc), 0, 1).0;
(r.id, f[0].Footprint.Format.0)
})
.collect();
Textures {
copied_as,
shaped,
drawn: HashMap::new(),
}
}
/// The spots of a texture (of its subresource `sub`) that is written not
/// as a target.
fn spots_of(
&self,
p: &Pixels,
t: &Textures,
picture: (u32, u32),
id: u32,
sub: u32,
out: &mut Vec<Spot>,
) {
let Some(r) = self.texture(id) else { return };
let depth = r.desc.flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0;
for &(res, at, x, y) in &p.texels {
if res == id && (sub == at || sub == ALL) {
out.push(Spot {
res,
sub: at,
x,
y,
z: 0,
point: OWN,
format: r.desc.format,
depth,
});
}
}
if r.desc.dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D.0 || !(sub == 0 || sub == ALL) {
return;
}
let size = (r.desc.width as u32, r.desc.height);
let whole = [0.0, 0.0, size.0 as f32, size.1 as f32];
let view = t.drawn.get(&size).copied().unwrap_or(whole);
for (point, at) in p.points.iter().enumerate() {
if let Some((x, y)) = texel(*at, picture, view, size) {
out.push(Spot {
res: id,
sub: 0,
x,
y,
z: 0,
point,
format: r.desc.format,
depth,
});
}
}
}
/// Whether a texture is the one in use of those that share its memory.
fn in_use(&self, states: &States, id: u32) -> bool {
self.objects.get(&id).is_some_and(|o| {
!self.frame.resources[o.index].idle || states.used.contains_key(&id)
})
}
/// The commands that copy the texels of `spots` to [`PROBE`] from `first`
/// on; `copied`: a copy to them went before.
fn take(
&self,
spots: &[Spot],
first: u64,
states: &States,
t: &Textures,
copied: bool,
scratch: &mut u64,
out: &mut Vec<Cmd>,
) {
let (mut to, mut from, mut copies) = (Vec::new(), Vec::new(), Vec::new());
let mut moved = HashSet::new();
for (i, s) in spots.iter().enumerate() {
let Some(r) = self.texture(s.res) else {
continue;
};
let all = states.get(s.res).unwrap_or(vec![COMMON]);
let mut state = all
.get(s.sub as usize)
.or(all.first())
.copied()
.unwrap_or(COMMON);
if copied && state == COMMON {
state = COPY_DEST;
}
if state & COPY_SOURCE == 0 && moved.insert((s.res, s.sub)) {
to.push(transition(s.res, s.sub, state, COPY_SOURCE));
from.push(transition(s.res, s.sub, COPY_SOURCE, state));
}
let offset = (first + i as u64) * ROOM;
if !s.depth {
copies.push(Cmd::CopyTexture {
dst: Loc::Placed {
res: PROBE,
offset,
format: t.copied_as.get(&s.res).copied().unwrap_or(r.desc.format),
size: [1, 1, 1],
pitch: 256,
},
at: [0; 3],
src: Loc::Sub {
res: s.res,
sub: s.sub,
},
part: Some([s.x, s.y, s.z, s.x + 1, s.y + 1, s.z + 1]),
});
continue;
}
// Depth is only copied whole.
let mip = s.sub % u32::from(r.desc.mips.max(1));
let w = (r.desc.width as u32 >> mip).max(1);
let h = (r.desc.height >> mip).max(1);
let bytes = texel_bytes(s.format) as u64;
let pitch = (w * bytes as u32).next_multiple_of(256);
*scratch = (*scratch).max(u64::from(pitch) * u64::from(h));
copies.push(Cmd::CopyTexture {
dst: Loc::Placed {
res: SCRATCH,
offset: 0,
format: t.copied_as.get(&s.res).copied().unwrap_or(r.desc.format),
size: [w, h, 1],
pitch,
},
at: [0; 3],
src: Loc::Sub {
res: s.res,
sub: s.sub,
},
part: None,
});
copies.push(Cmd::Barriers {
all: vec![transition(SCRATCH, ALL, COPY_DEST, COPY_SOURCE)],
});
copies.push(Cmd::CopyBuffer {
dst: PROBE,
dst_at: offset,
src: SCRATCH,
src_at: u64::from(pitch) * u64::from(s.y) + u64::from(s.x) * bytes,
len: bytes,
});
copies.push(Cmd::Barriers {
all: vec![transition(SCRATCH, ALL, COPY_SOURCE, COPY_DEST)],
});
}
if !to.is_empty() {
out.push(Cmd::Barriers { all: to });
}
out.extend(copies);
if !from.is_empty() {
out.push(Cmd::Barriers { all: from });
}
}
/// The frame's lists with copies of texels after commands.
fn sampled(
&mut self,
p: &Pixels,
submits: &[Vec<Vec<Cmd>>],
picture: (u32, u32),
counts: &HashMap<(u32, u32), u32>,
samples: &mut Vec<Sample>,
) -> Result<Vec<Vec<Vec<Cmd>>>> {
let strides: HashMap<u32, u32> = self
.frame
.signatures
.iter()
.map(|s| (s.id, s.stride))
.collect();
let dispatching: HashSet<u32> = self
.frame
.signatures
.iter()
.filter(|s| {
s.args
.iter()
.any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32)
})
.map(|s| s.id)
.collect();
let mut t = self.textures(picture);
let mut states = self.start_states();
let mut known: HashSet<Spot> = HashSet::new();
let mut made = Vec::new();
let mut here = 0;
let mut scratch = 0u64;
for lists in submits {
let mut out_lists = Vec::new();
for cmds in lists {
let wanted = p.lists.is_none_or(|(a, b)| (a..=b).contains(&here));
let mut out = Vec::with_capacity(cmds.len());
let mut pso = NONE;
let mut targets: Vec<Slot> = Vec::new();
let mut view: Option<[f32; 4]> = None;
for (n, c) in cmds.iter().enumerate() {
match c {
Cmd::Pipeline { pso: id } => pso = *id,
Cmd::Targets { colors, depth } => {
targets = colors.iter().chain(depth).copied().collect();
}
Cmd::Viewports { all } => {
view = all.first().map(|v| [v[0], v[1], v[2], v[3]]);
}
_ => {}
}
let dispatches = matches!(c, Cmd::Dispatch { .. })
|| matches!(c, Cmd::Indirect { signature, .. } if dispatching.contains(signature));
let draws = c.runs_shaders() && !dispatches;
let mut spots: Vec<Spot> = Vec::new();
let looked = wanted && c.works() && samples.len() < MOST;
for s in targets.iter().filter(|_| looked && draws) {
let Some((sub, z, size, format)) = self.seen_by(s) else {
continue;
};
let depth = s.kind == slot::DSV;
let spot = |x, y, point| Spot {
res: s.res,
sub,
x,
y,
z,
point,
format,
depth,
};
let view = view.unwrap_or([0.0, 0.0, size.0 as f32, size.1 as f32]);
for (point, at) in p.points.iter().enumerate() {
if let Some((x, y)) = texel(*at, picture, view, size) {
t.drawn.insert(size, view);
spots.push(spot(x, y, point));
}
}
for &(res, at, x, y) in &p.texels {
if (res, at) == (s.res, sub) {
spots.push(spot(x, y, OWN));
}
}
}
if looked && c.runs_shaders() {
let all = p.texels.iter().map(|t| t.0);
let some = p.written && (dispatches || !targets.is_empty());
let all: HashSet<u32> =
all.chain(t.shaped.iter().copied().filter(|_| some)).collect();
for id in all {
let writable = states
.get(id)
.is_some_and(|s| s.iter().any(|s| s & UNORDERED_ACCESS != 0));
if writable && self.in_use(&states, id) {
self.spots_of(p, &t, picture, id, ALL, &mut spots);
}
}
}
let mut copied = false;
if looked {
let mut to = None;
match c {
Cmd::CopyTexture {
dst: Loc::Sub { res, sub },
..
} => to = Some((*res, *sub, true)),
Cmd::CopyResource { dst, .. } => to = Some((*dst, ALL, true)),
Cmd::Resolve { dst, dst_sub, .. }
| Cmd::ResolveRegion { dst, dst_sub, .. } => {
to = Some((*dst, *dst_sub, false));
}
Cmd::ClearTarget { view, .. } | Cmd::ClearDepth { view, .. } => {
to = self.seen_by(view).map(|s| (view.res, s.0, false));
}
_ => {}
}
if let Some((res, sub, is_copy)) = to {
copied = is_copy;
self.spots_of(p, &t, picture, res, sub, &mut spots);
}
}
let mut seen = HashSet::new();
spots.retain(|s| {
(p.depth || !s.depth) && texel_bytes(s.format) > 0 && seen.insert(*s)
});
let what = match c {
Cmd::Draw { .. } => "Draw",
Cmd::DrawIndexed { .. } => "DrawIndexed",
Cmd::DispatchMesh { .. } => "DispatchMesh",
Cmd::Dispatch { .. } => "Dispatch",
Cmd::Indirect { .. } if dispatches => "indirect Dispatch",
Cmd::Indirect { .. } => "indirect draw",
Cmd::ClearTarget { .. } | Cmd::ClearDepth { .. } => "clear",
Cmd::Resolve { .. } | Cmd::ResolveRegion { .. } => "resolve",
_ => "copy",
};
let runs = if c.runs_shaders() { pso } else { NONE };
let mut take = |before: bool, part: u32, spots: &[Spot], out: &mut Vec<Cmd>| {
let first = samples.len() as u64;
self.take(spots, first, &states, &t, copied && !before, &mut scratch, out);
samples.extend(spots.iter().map(|spot| Sample {
list: here,
command: n,
part,
before,
spot: *spot,
pso: runs,
what,
}));
};
// What was not seen before this command, as it is now.
let new: Vec<Spot> =
spots.iter().filter(|s| known.insert(**s)).copied().collect();
if !new.is_empty() {
take(true, 0, &new, &mut out);
}
match (counts.get(&(here, n as u32)), c) {
(Some(&count), Cmd::Indirect { signature, .. }) => {
let stride = strides.get(signature).copied().unwrap_or(0);
for i in 0..count {
out.push(part_of(c, i, stride));
take(false, i, &spots, &mut out);
}
}
_ => {
out.push(c.clone());
if !spots.is_empty() {
take(false, 0, &spots, &mut out);
}
}
}
let mut all = Vec::new();
states::changes(c, &mut all);
all.iter().for_each(|c| states.change(c));
}
out_lists.push(out);
here += 1;
}
states.decay();
made.push(out_lists);
}
if scratch > 0 {
let buffer = gpu::buffer(
&self.device,
D3D12_HEAP_TYPE_DEFAULT,
scratch,
D3D12_RESOURCE_FLAG_NONE,
)?;
self.extra.insert(SCRATCH, buffer.0);
}
Ok(made)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn points_lie_in_viewports_of_the_pictures_shape() {
let whole = |w: u32, h: u32| ([0.0, 0.0, w as f32, h as f32], (w, h));
let picture = (3840, 2160);
let (view, size) = whole(1920, 1080);
assert_eq!(texel((3839, 2159), picture, view, size), Some((1919, 1079)));
assert_eq!(texel((0, 0), picture, view, size), Some((0, 0)));
let (view, size) = whole(2048, 2048);
assert_eq!(texel((0, 0), picture, view, size), None);
// A part of a larger target.
let part = [0.0, 0.0, 1920.0, 1080.0];
assert_eq!(
texel((1920, 1080), picture, part, (3840, 2160)),
Some((960, 540))
);
let beside = [1920.0, 0.0, 1920.0, 1080.0];
assert_eq!(texel((1920, 1080), picture, beside, (1920, 1080)), None);
}
#[test]
fn texels_are_read() {
assert_eq!(
texel_text(41, &1.5f32.to_le_bytes()),
"1.50000 [00, 00, c0, 3f]"
);
assert_eq!(
texel_text(28, &[255, 0, 0, 51]),
"1.00000 0.00000 0.00000 0.20000 [ff, 00, 00, 33]"
);
assert!(
texel_text(10, &[0, 0x3C, 0, 0xBC, 0, 0, 0, 0x38])
.starts_with("1.00000 -1.00000 0.00000 0.50000 ")
);
let v = 0x3C0u32 | 0x380 << 11 | 0x200 << 22;
assert!(texel_text(26, &v.to_le_bytes()).starts_with("1.00000 0.50000 2.00000 "));
assert_eq!(texel_text(42, &[1, 2, 3, 4]), "[01, 02, 03, 04]");
// Too few bytes, or a format that is not read.
assert_eq!(texel_text(41, &[1]), "[01]");
assert_eq!(texel_text(98, &[1, 2]), "[01, 02]");
}
#[test]
fn an_indirect_draw_is_taken_apart() {
let all = Cmd::Indirect {
signature: 1,
most: 8,
args: 2,
at: 100,
count: 3,
count_at: 4,
};
let one = Cmd::Indirect {
signature: 1,
most: 1,
args: 2,
at: 124,
count: NONE,
count_at: 0,
};
assert_eq!(part_of(&all, 2, 12), one);
}
}
+84 -13
View File
@@ -585,7 +585,7 @@ pub(crate) fn family(format: u32) -> u32 {
(44, 47),
(48, 52),
(53, 59),
(60, 65),
(60, 64),
(70, 72),
(73, 75),
(76, 78),
@@ -695,8 +695,7 @@ const NO_FOOTPRINT: PlacedFootprint = PlacedFootprint {
row_pitch: 0,
};
/// One subresource's size in an upload buffer: footprint (offset 0), rows
/// and bytes per row. Planes of depth-stencil formats are not told apart.
/// One subresource's upload footprint (offset 0), row count and unpadded row size.
fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32, u64)> {
const PITCH: u64 = 256;
if desc.dimension == BUFFER {
@@ -716,11 +715,18 @@ fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32,
} else {
u32::from(desc.depth_or_array_size).max(1)
};
let (mip, slice) = (index % mips, index / mips);
if slice >= slices {
return None;
}
let (element, block) = element(desc.format)?;
let mip = index % mips;
let plane = index / mips / slices;
let depth_stencil = matches!(desc.format, 19..=22 | 44..=47);
// Each plane contains all the mip levels and array slices. Depth and
// stencil copies use separate formats and 512-byte row alignment.
let (format, pitch_alignment) = match (depth_stencil, plane) {
(true, 0) => (39, 512), // DXGI_FORMAT_R32_TYPELESS
(true, 1) => (60, 512), // DXGI_FORMAT_R8_TYPELESS
(false, 0) => (desc.format, PITCH),
_ => return None,
};
let (element, block) = element(format)?;
let width = (desc.width >> mip).max(1).next_multiple_of(block);
let height = (u64::from(desc.height) >> mip)
.max(1)
@@ -733,18 +739,18 @@ fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32,
let row_size = width / block * element;
let footprint = PlacedFootprint {
offset: 0,
format: desc.format,
format,
width: u32::try_from(width).ok()?,
height: u32::try_from(height).ok()?,
depth,
row_pitch: u32::try_from(row_size.next_multiple_of(PITCH)).ok()?,
row_pitch: u32::try_from(row_size.next_multiple_of(pitch_alignment)).ok()?,
};
Some((footprint, u32::try_from(height / block).ok()?, row_size))
}
/// Device method: where each subresource goes in an upload buffer, rows
/// 256-byte and subresources 512-byte aligned, as on PC. Unknown sizes give
/// the documented all-ones values.
/// Places subresources at 512-byte boundaries in an upload buffer.
/// Row pitch is aligned to 512 bytes for depth/stencil planes and 256 bytes
/// otherwise. Unknown sizes give the documented all-ones values.
pub(crate) extern "system" fn copyable_footprints(
_: This,
desc: *const ResourceDesc,
@@ -2559,6 +2565,22 @@ mod tests {
use super::*;
use crate::object::slot;
#[test]
fn a8_unorm_is_not_in_the_r8_typeless_family() {
// DXGI_FORMAT values: 60 R8_TYPELESS, 61 R8_UNORM, 62 R8_UINT,
// 63 R8_SNORM, 64 R8_SINT, 65 A8_UNORM. The R8 typeless family is
// 60..=64; A8_UNORM has no typeless family and cannot be cast to R8,
// so it must stand alone rather than fold into R8_TYPELESS.
assert_eq!(family(60), 60);
for f in 61..=64 {
assert_eq!(family(f), 60);
}
assert_eq!(family(65), 65);
// Boundaries: 59 belongs to the preceding family, 66 is unmapped.
assert_eq!(family(59), 53);
assert_eq!(family(66), 66);
}
type Release = extern "system" fn(This) -> u32;
type Map = extern "system" fn(This, u32, *const c_void, *mut *mut u8) -> HRESULT;
type Address = extern "system" fn(This) -> u64;
@@ -2790,6 +2812,55 @@ mod tests {
assert_eq!(t, u64::MAX, "no second subresource");
}
#[test]
fn depth_stencil_footprints_follow_the_pc_plane_order() {
// Native D3D12 reports the same layout for both depth/stencil families
// and their view formats. Mips vary fastest, then array slices, then planes.
let expected = [
(512, 39, 16, 8),
(4_608, 39, 8, 4),
(6_656, 39, 16, 8),
(10_752, 39, 8, 4),
(12_800, 60, 16, 8),
(16_896, 60, 8, 4),
(18_944, 60, 16, 8),
(23_040, 60, 8, 4),
];
for format in (19..=22).chain(44..=47) {
let desc = ResourceDesc {
depth_or_array_size: 2,
..texture(16, 8, format, 2)
};
let mut layouts = [NO_FOOTPRINT; 8];
let (mut rows, mut sizes, mut total) = ([0; 8], [0; 8], 0);
copyable_footprints(
std::ptr::null(),
&desc,
0,
8,
512,
layouts.as_mut_ptr(),
rows.as_mut_ptr(),
sizes.as_mut_ptr(),
&mut total,
);
assert_eq!(
layouts.map(|l| (l.offset, l.format, l.width, l.height)),
expected,
"format {format}"
);
assert!(
layouts.iter().all(|l| l.depth == 1 && l.row_pitch == 512),
"format {format}"
);
assert_eq!(rows, [8, 4, 8, 4, 8, 4, 8, 4], "format {format}");
assert_eq!(sizes, [64, 32, 64, 32, 16, 8, 16, 8], "format {format}");
assert_eq!(total, 24_072, "format {format}");
assert!(subresource(&desc, 8).is_none(), "format {format}");
}
}
/// A 4x4 texture filled from a title buffer through our list and queue,
/// then read back from the host GPU.
#[cfg(windows)]
-141
View File
@@ -75,46 +75,6 @@ std::arch::global_asm!(
"vzeroupper",
"xor eax, eax",
"ret",
".globl victory_safe_update",
".globl victory_safe_update_at",
".globl victory_safe_update_after",
".globl victory_safe_update_failed",
// rcx destination, rdx source, r8 bytes (whole 64s, not none), r9 where
// the offset of the first 64 bytes that differed goes (-1: none did) and
// behind it the offset of the end of the last: stores the 64s that
// differ. eax: whether all could be read.
"victory_safe_update:",
"xor r10d, r10d",
"mov r11, -1",
"xor eax, eax",
"2:",
"victory_safe_update_at:",
"vmovdqu ymm0, ymmword ptr [rdx + r10]",
"vmovdqu ymm1, ymmword ptr [rdx + r10 + 32]",
"victory_safe_update_after:",
"vpxor ymm2, ymm0, ymmword ptr [rcx + r10]",
"vpxor ymm3, ymm1, ymmword ptr [rcx + r10 + 32]",
"vpor ymm2, ymm2, ymm3",
"vptest ymm2, ymm2",
"jz 3f",
"vmovdqu ymmword ptr [rcx + r10], ymm0",
"vmovdqu ymmword ptr [rcx + r10 + 32], ymm1",
"cmp r11, -1",
"cmove r11, r10",
"lea rax, [r10 + 64]",
"3:",
"add r10, 64",
"cmp r10, r8",
"jb 2b",
"mov qword ptr [r9], r11",
"mov qword ptr [r9 + 8], rax",
"vzeroupper",
"mov eax, 1",
"ret",
"victory_safe_update_failed:",
"vzeroupper",
"xor eax, eax",
"ret",
".globl victory_safe_merge",
".globl victory_safe_merge_at",
".globl victory_safe_merge_after",
@@ -185,63 +145,12 @@ unsafe extern "system" {
fn victory_safe_put_at();
fn victory_safe_put_after();
fn victory_safe_put_failed();
fn victory_safe_update(dst: *mut u8, src: *const u8, len: usize, changed: *mut [usize; 2]) -> u32;
fn victory_safe_update_at();
fn victory_safe_update_after();
fn victory_safe_update_failed();
fn victory_safe_merge(title: *mut u8, now: *const u8, held: *mut u8, blocks: usize, counts: *mut [u64; 2]) -> usize;
fn victory_safe_merge_at();
fn victory_safe_merge_after();
fn victory_safe_merge_failed();
}
/// What [`update`] found.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Updated {
/// Every byte was the same already; nothing was stored.
Same,
/// The bytes that changed lie in these offsets.
Changed(usize, usize),
/// Not all of the source could be read; some may have been copied.
Failed,
}
/// Makes `dst` hold what `src` holds, storing only what differs. The source
/// may change meanwhile: what is compared is what is stored, read once.
///
/// # Safety
/// As [`copy`]'s, and the destination is memory of ours that nothing else
/// writes.
pub(crate) unsafe fn update(dst: *mut u8, src: *const u8, len: usize) -> Updated {
let whole = len / 64 * 64;
let (mut from, mut to) = (usize::MAX, 0);
if whole > 0 {
let mut changed = [usize::MAX, 0];
// SAFETY: the source's faults leave through the failing exit; the
// rest is the caller's.
if unsafe { victory_safe_update(dst, src, whole, &mut changed) } == 0 {
return Updated::Failed;
}
[from, to] = changed;
}
if whole < len {
let mut rest = [0u8; 64];
let rest = &mut rest[..len - whole];
// SAFETY: as above; `rest` is ours.
unsafe {
if !copy(rest.as_mut_ptr(), src.add(whole), rest.len()) {
return Updated::Failed;
}
let held = std::slice::from_raw_parts_mut(dst.add(whole), rest.len());
if held != rest {
held.copy_from_slice(rest);
(from, to) = (from.min(whole), len);
}
}
}
if from >= to { Updated::Same } else { Updated::Changed(from, to) }
}
/// What [`merge`] did.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Merged {
@@ -445,10 +354,6 @@ pub(crate) fn failing_exit(at: usize) -> Option<usize> {
if (from..to).contains(&at) {
return Some(victory_safe_put_failed as *const () as usize);
}
let (from, to) = (victory_safe_update_at as *const () as usize, victory_safe_update_after as *const () as usize);
if (from..to).contains(&at) {
return Some(victory_safe_update_failed as *const () as usize);
}
let (from, to) = (victory_safe_merge_at as *const () as usize, victory_safe_merge_after as *const () as usize);
(from..to).contains(&at).then_some(victory_safe_merge_failed as *const () as usize)
}
@@ -504,52 +409,6 @@ mod tests {
}
}
/// An update makes the two the same, says where they differed (to 64
/// bytes), stores nothing where they did not, and fails at a page that
/// is not there.
#[test]
fn updates_store_what_differs() {
assert!(on());
let (src, dst) = (Pages::new(1 << 14), Pages::new(1 << 14));
for len in [0usize, 1, 63, 64, 65, 200, 4096, 5000] {
for (da, sa) in [(0usize, 0usize), (3, 0), (0, 5)] {
for changed in [vec![], vec![0usize], vec![len / 2], vec![len.saturating_sub(1)], vec![1, len / 3, len / 2]] {
src.fill();
// SAFETY: inside the two allocations.
unsafe {
std::ptr::write_bytes(dst.0, 0xEE, dst.1);
std::ptr::copy_nonoverlapping(src.0.add(sa), dst.0.add(da), len);
let at: std::collections::BTreeSet<usize> = changed.iter().copied().filter(|&i| i < len).collect();
for &i in &at {
*src.0.add(sa + i) ^= 0x40;
}
let found = update(dst.0.add(da), src.0.add(sa), len);
match (at.iter().min(), at.iter().max()) {
(Some(&first), Some(&last)) => {
let Updated::Changed(from, to) = found else {
panic!("{len} {at:?}: {found:?}")
};
assert_eq!(from, first / 64 * 64);
assert_eq!(to, ((last / 64 + 1) * 64).min(len));
}
_ => assert_eq!(found, Updated::Same),
}
let (to, from) = (std::slice::from_raw_parts(dst.0, dst.1), std::slice::from_raw_parts(src.0, src.1));
assert_eq!(to[da..da + len], from[sa..sa + len]);
assert!(to[..da].iter().chain(&to[da + len..]).all(|&x| x == 0xEE));
}
}
}
}
// SAFETY: our allocation.
unsafe {
VirtualFree(src.0.add(4096).cast(), 4096, MEM_DECOMMIT);
assert_eq!(update(dst.0, src.0, 8192), Updated::Failed);
assert_eq!(update(dst.0, src.0.add(4096), 10), Updated::Failed);
assert_ne!(update(dst.0, src.0, 4096), Updated::Failed);
}
}
/// The dwords that changed are stored, and no byte of any other, at
/// every alignment and length; a page that is not there fails.
#[test]
+121 -11
View File
@@ -47,30 +47,58 @@ impl Fields {
} else {
linear(self.min) << 4 | linear(self.mag) << 2 | u32::from(self.mip == 2)
};
let min_lod = finite_lod(self.min_lod, 0.0);
// Without a mip filter the console clamps sampling to `min_lod`.
let max_lod = if self.mip == 0 {
min_lod
} else {
finite_lod(self.max_lod, min_lod).max(min_lod)
};
D3D12_SAMPLER_DESC {
Filter: D3D12_FILTER((reduction << 7 | filter) as i32),
AddressU: D3D12_TEXTURE_ADDRESS_MODE(self.address[0] as i32),
AddressV: D3D12_TEXTURE_ADDRESS_MODE(self.address[1] as i32),
AddressW: D3D12_TEXTURE_ADDRESS_MODE(self.address[2] as i32),
MipLODBias: self.bias,
AddressU: address_mode(self.address[0]),
AddressV: address_mode(self.address[1]),
AddressW: address_mode(self.address[2]),
MipLODBias: if self.bias.is_nan() {
0.0
} else {
self.bias
.clamp(D3D12_MIP_LOD_BIAS_MIN, D3D12_MIP_LOD_BIAS_MAX)
},
MaxAnisotropy: if aniso {
self.anisotropy.clamp(1, 16)
} else {
1
},
ComparisonFunc: D3D12_COMPARISON_FUNC(self.compare.max(1) as i32),
BorderColor: self.border,
MinLOD: self.min_lod,
// Without a mip filter the console samples mip 0 only.
MaxLOD: if self.mip == 0 {
self.min_lod
ComparisonFunc: if reduction == 1 {
D3D12_COMPARISON_FUNC(self.compare as i32)
} else {
self.max_lod
D3D12_COMPARISON_FUNC_NEVER
},
BorderColor: self.border,
MinLOD: min_lod,
MaxLOD: max_lod,
}
}
}
/// Maps a console address mode (`1..=5`) to host D3D12, falling back to `CLAMP`.
fn address_mode(mode: u32) -> D3D12_TEXTURE_ADDRESS_MODE {
match mode {
1..=5 => D3D12_TEXTURE_ADDRESS_MODE(mode as i32),
_ => D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
}
}
/// Sanitizes an LOD bound for D3D12, substituting `fallback` for `NaN` and clamping infinities.
fn finite_lod(value: f32, fallback: f32) -> f32 {
if value.is_nan() {
fallback
} else {
value.clamp(-D3D12_FLOAT32_MAX, D3D12_FLOAT32_MAX)
}
}
/// The console's sampler description (27 words): flags, magnification,
/// minification, mip and depth filters, filter mode, three address modes,
/// minimum and maximum LOD, LOD bias, secondary bias, anisotropy, its bias
@@ -116,4 +144,86 @@ mod tests {
w[16] = 1;
assert_eq!(console(&w).Filter.0, 0x5);
}
#[test]
fn mip_none_clamps_to_min_lod_and_inverted_lod_range_clamps() {
let mut w = [0u32; 27];
w[3] = 0; // mip none
w[9] = 3.0f32.to_bits();
w[10] = 8.0f32.to_bits();
let d = console(&w);
assert_eq!((d.MinLOD, d.MaxLOD), (3.0, 3.0));
w[9] = f32::NAN.to_bits();
w[10] = 8.0f32.to_bits();
let d = console(&w);
assert_eq!((d.MinLOD, d.MaxLOD), (0.0, 0.0));
w[9] = f32::INFINITY.to_bits();
w[10] = 8.0f32.to_bits();
let d = console(&w);
assert_eq!((d.MinLOD, d.MaxLOD), (D3D12_FLOAT32_MAX, D3D12_FLOAT32_MAX));
w[3] = 2; // linear mips
w[9] = 4.0f32.to_bits();
w[10] = 1.0f32.to_bits();
let d = console(&w);
assert_eq!((d.MinLOD, d.MaxLOD), (4.0, 4.0));
w[9] = f32::NAN.to_bits();
w[10] = f32::INFINITY.to_bits();
let d = console(&w);
assert_eq!((d.MinLOD, d.MaxLOD), (0.0, D3D12_FLOAT32_MAX));
w[9] = 2.5f32.to_bits();
w[10] = f32::NAN.to_bits();
let d = console(&w);
assert_eq!((d.MinLOD, d.MaxLOD), (2.5, 2.5));
w[9] = f32::NEG_INFINITY.to_bits();
w[10] = f32::NEG_INFINITY.to_bits();
let d = console(&w);
assert_eq!(
(d.MinLOD, d.MaxLOD),
(-D3D12_FLOAT32_MAX, -D3D12_FLOAT32_MAX)
);
}
#[test]
fn bias_address_and_comparison_stay_in_host_bounds() {
let mut w = [0u32; 27];
w[6..9].copy_from_slice(&[0, 6, 3]);
w[11] = 24.0f32.to_bits();
w[16] = 99;
let d = console(&w);
assert_eq!(d.MipLODBias, D3D12_MIP_LOD_BIAS_MAX);
assert_eq!(
[d.AddressU, d.AddressV, d.AddressW],
[D3D12_TEXTURE_ADDRESS_MODE_CLAMP; 3]
);
assert_eq!(d.ComparisonFunc, D3D12_COMPARISON_FUNC_NEVER);
w[11] = (-24.0f32).to_bits();
w[5] = 1; // minimum reduction
w[16] = 4; // less-or-equal, ignored when reduction != 1
let d = console(&w);
assert_eq!(d.MipLODBias, D3D12_MIP_LOD_BIAS_MIN);
assert_eq!(d.ComparisonFunc, D3D12_COMPARISON_FUNC_NEVER);
w[11] = f32::NAN.to_bits();
w[5] = 0; // plain mode, reduction == 1 from compare == 4
w[6..9].copy_from_slice(&[1, 4, 5]);
w[16] = 4;
let d = console(&w);
assert_eq!(d.MipLODBias, 0.0);
assert_eq!(
[d.AddressU, d.AddressV, d.AddressW],
[
D3D12_TEXTURE_ADDRESS_MODE_WRAP,
D3D12_TEXTURE_ADDRESS_MODE_BORDER,
D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE,
]
);
assert_eq!(d.ComparisonFunc, D3D12_COMPARISON_FUNC_LESS_EQUAL);
}
}
+157 -60
View File
@@ -939,6 +939,8 @@ fn give_back(v: Vec<u8>) {
}
const NOT_WATCHED: u8 = 2;
/// Watched, not by the kernel but by the guards, when last asked about.
const GUARDED: u8 = 3;
/// Where `a` and `b` (of one length) first differ, compared eight bytes at
/// a time.
@@ -1505,30 +1507,34 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> {
runs
}
/// Whether pages of a copy in the card's memory that a refresh takes again
/// go up to the card only where they are not what the CPU's side holds
/// already (`VICTORY_SEND_CHANGED=1`; off by default).
/// Whether a refresh of a copy in the card's memory takes, and sends up,
/// the dwords that title memory changed and no others
/// (`VICTORY_SEND_CHANGED=0`: the 64 KiB pages written since it last took
/// them, whole, as before).
///
/// A refresh copies the 64 KiB pages that were written since it last took
/// them, and all of each went up and was hashed there again. Most of them
/// the title did not write: the relay put what shaders wrote into title
/// memory, and the card and the CPU's side hold those bytes already
/// ([`Shadow::card_merge_relay`]). Run record-1: 1,500 pieces (98 MB) a
/// frame fetched from the card, 103 MB in 328 ranges sent up, 322 hash
/// passes, while the title's own writes took some 260 guards off.
/// A page that counts as written is mostly not the title's doing, or not all
/// of it: a word the title wrote, and around it what shaders wrote and the
/// title never touched; or only what the relay put into title memory, which
/// the card and the CPU's side hold already ([`Shadow::card_merge_relay`]).
/// Sent up whole, such a page goes over whatever the card holds there that
/// did not come back yet, or never will (a write through a view nobody
/// declared): what stood on the card, newer, was gone.
///
/// What it rests on: the card's side holds what the CPU's side holds, but
/// for ranges shaders may be writing (no refresh touches them) and what is
/// still to go up. A page's first taking always goes up whole, so does one
/// that could not be read; after that every byte that changes on the CPU's
/// side goes up (the bytes compared are the bytes stored).
/// What it rests on: the CPU's side is what the card's side was last known
/// to hold, for every range no shader may be writing (no refresh touches
/// the others). So a dword goes up only if title memory holds another value
/// of it than the CPU's side, which then holds it too; title memory is read
/// once, what is compared is what is stored and sent. Dwords, not bytes:
/// no shader writes less, and the title's bytes beside a changed one in its
/// dword are those the CPU's side holds.
///
/// Why it is not on by default: a shader that writes a copy through a view
/// nobody declared (`crate::draw`, buffers picked by index) breaks that
/// rule. Taken again, its page went up over what it wrote; with the switch
/// its bytes stay, as they would on the console, until the title changes the
/// same 64 bytes: clearing them to the zeros they held before is then no
/// change.
/// A page never taken goes up whole as long as no shader's write was ever
/// declared for the copy. After that it is compared as any other: the CPU's
/// side and the card's began as zeros, both.
///
/// What it cannot know: that the title wrote a value over the same value.
/// Where a shader wrote in between, through a view nobody declared, the
/// shader's stays.
fn send_changed() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| {
@@ -1536,19 +1542,19 @@ fn send_changed() -> bool {
if crate::copystat::mode() != 0 {
return false;
}
std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v == "1") && crate::safecopy::on()
std::env::var_os("VICTORY_SEND_CHANGED").is_none_or(|v| v != "0")
})
}
/// Since the last frame-rate line, of pages taken again into copies in the
/// Since the last frame-rate line, of pages taken into copies in the
/// card's memory ([`send_changed`]): bytes compared, those of pages that
/// held the same, and bytes to go up.
static SEND: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
/// held the same, bytes to go up, and the runs they are.
static SEND: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4];
/// [`SEND`], taken.
#[cfg(feature = "diagnostics")]
pub(crate) fn send_stats() -> [u64; 3] {
[0, 1, 2].map(|i| SEND[i].swap(0, Ordering::Relaxed))
pub(crate) fn send_stats() -> [u64; 4] {
[0, 1, 2, 3].map(|i| SEND[i].swap(0, Ordering::Relaxed))
}
/// Whether what shaders wrote goes into title memory run by run
@@ -1602,6 +1608,7 @@ fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize {
if crate::safecopy::on() {
PUT[0].fetch_add(1, Ordering::Relaxed);
PUT[2].fetch_add(merged.len() as u64, Ordering::Relaxed);
let since = crate::watch::changes();
// SAFETY: title memory; a page of it that is not there fails the
// put, and the rest is put page by page.
if unsafe { crate::safecopy::put_changed(at as *mut u8, title, merged) } {
@@ -1610,8 +1617,14 @@ fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize {
let mut from = 0;
while from < merged.len() {
let n = (4096 - (at + from) % 4096).min(merged.len() - from);
let (was, now) = (&title[from..from + n], &merged[from..from + n]);
// SAFETY: as above.
unsafe { crate::safecopy::put_changed((at + from) as *mut u8, &title[from..from + n], &merged[from..from + n]) };
let put = || unsafe { crate::safecopy::put_changed((at + from) as *mut u8, was, now) };
// A page that is away only while the runtime changes a mapping
// beside it gets its bytes when that is done.
if !put() && !crate::watch::again_after_change(since, put) {
crate::watch::lost("what shaders wrote", at + from, n);
}
from += n;
}
return merged.len();
@@ -1655,7 +1668,35 @@ pub(crate) fn land_as_before(start: usize, now: usize, held: usize, n: usize, ti
#[cfg(test)]
mod merge_tests {
use super::{changed_runs, dword_runs};
use super::{changed_runs, dword_runs, put_changed};
/// What shaders wrote reaches a page that is away only while the runtime
/// changes a mapping; a page that stays away loses it, and nothing else.
#[test]
fn a_put_waits_for_a_change_of_mapping() {
use windows_sys::Win32::System::Memory::{
MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, VirtualFree,
};
// SAFETY: a reservation of ours, nothing of it committed.
let at = unsafe { VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS) } as usize;
assert_ne!(at, 0);
put_changed(at, &[0; 64], &[3; 64]);
let (began, wait) = std::sync::mpsc::channel();
let change = std::thread::spawn(move || {
let _changing = crate::watch::title_memory_remapping();
began.send(()).unwrap();
std::thread::sleep(std::time::Duration::from_millis(50));
// SAFETY: the reservation's first page.
assert!(!unsafe { VirtualAlloc(at as _, 4096, MEM_COMMIT, PAGE_READWRITE) }.is_null());
});
wait.recv().unwrap();
put_changed(at, &[0; 64], &[1; 64]);
change.join().unwrap();
// SAFETY: committed by now.
assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, 64) }, [1; 64]);
// SAFETY: our reservation.
unsafe { VirtualFree(at as _, 0, MEM_RELEASE) };
}
/// Whole dwords around every changed byte and no other, whatever the
/// alignment; small gaps joined only when asked.
@@ -2017,6 +2058,14 @@ impl Shadow {
self.watched.load(Ordering::Relaxed) == NOT_WATCHED
}
/// Whether a submission asks the kernel about the copy's ranges ahead:
/// not of memory that is not watched, nor of view memory, which the
/// kernel would refuse (and with it the ranges asked about together).
pub(crate) fn asked_ahead(&self) -> bool {
let watched = self.watched.load(Ordering::Relaxed);
watched != NOT_WATCHED && (watched != GUARDED || !crate::watch::light())
}
/// The copy's own number (see the field).
pub(crate) fn id(&self) -> u64 {
self.id
@@ -2774,7 +2823,7 @@ impl Shadow {
if from >= to {
return true;
}
if self.watched.load(Ordering::Relaxed) != 1 {
if !matches!(self.watched.load(Ordering::Relaxed), 1 | GUARDED) {
return false;
}
// Around ranges shaders are writing the refresh asks gap by gap.
@@ -2804,7 +2853,8 @@ impl Shadow {
fn update_free(&self, from: usize, to: usize) -> usize {
if self.watched.load(Ordering::Relaxed) != NOT_WATCHED {
if let Some((now, written)) = crate::watch::writes(from, to, true) {
self.watched.store(1, Ordering::Relaxed);
let guarded = crate::watch::guarded(from, to);
self.watched.store(if guarded { GUARDED } else { 1 }, Ordering::Relaxed);
let copied = self.copy_stale(from, to, now, &written);
self.refresh_check(from, to);
#[cfg(feature = "diagnostics")]
@@ -2982,34 +3032,47 @@ impl Shadow {
/// Copies title memory `[from, to)` (inside the buffer) into the copy;
/// `known`: the copy held it before ([`send_changed`]).
fn take(&self, from: usize, to: usize, known: bool) -> usize {
if !known || self.card.is_none() || !send_changed() {
return self.copy(from, to);
thread_local! {
/// A page of title memory, as read.
static TITLE: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
}
let Some(card) = self.card.as_ref().filter(|_| send_changed()) else {
return self.copy(from, to);
};
let whole = !known && card.before.lock().unwrap_or_else(|e| e.into_inner()).is_none();
let start = self.start as usize;
let mut at = from;
while at < to {
let n = (PAGE - at % PAGE).min(to - at);
// SAFETY: inside the mapping of the copy's CPU side, which
// nothing else writes there: no shader's range holds it.
let found = unsafe { crate::safecopy::update(self.data.add(at - start), at as *const u8, n) };
SEND[0].fetch_add(n as u64, Ordering::Relaxed);
match found {
crate::safecopy::Updated::Same => {
TITLE.with_borrow_mut(|title| {
title.resize(PAGE, 0);
let mut at = from;
while at < to {
let n = (PAGE - at % PAGE).min(to - at);
let title = &mut title[..n];
// (Pages that are not there read as zeros.)
crate::host::copy_mapped(title.as_mut_ptr(), at as *const u8, n, false);
// SAFETY: inside the mapping of the copy's CPU side, which
// nothing else reads or writes there (the card copies from
// it): no shader's range holds it, and the parts of a
// refresh lie apart.
let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at - start), n) };
let was = crate::host::upcheck::on().then(|| held.to_vec());
let runs = if whole { vec![(0, n)] } else { dword_runs(at, held, title, 0) };
for &(a, len) in &runs {
held[a..a + len].copy_from_slice(&title[a..a + len]);
self.changed(at - start + a, at - start + a + len);
}
self.card_changed_runs(runs.iter().map(|&(a, len)| (at - start + a, at - start + a + len)));
if let Some(was) = was {
crate::host::upcheck::note(self.id, at - start, &was, held);
}
SEND[0].fetch_add(n as u64, Ordering::Relaxed);
if runs.is_empty() {
SEND[1].fetch_add(n as u64, Ordering::Relaxed);
}
crate::safecopy::Updated::Changed(a, b) => {
SEND[2].fetch_add((b - a) as u64, Ordering::Relaxed);
self.changed(at - start + a, at - start + b);
self.card_changed(at - start + a, at - start + b);
}
// A page is not there: as before, around it, and all of it
// goes up.
crate::safecopy::Updated::Failed => {
self.copy(at, at + n);
}
SEND[2].fetch_add(runs.iter().map(|r| r.1 as u64).sum(), Ordering::Relaxed);
SEND[3].fetch_add(runs.len() as u64, Ordering::Relaxed);
at += n;
}
at += n;
}
});
to - from
}
@@ -3044,16 +3107,24 @@ impl Shadow {
/// The CPU side's bytes at offsets `[from, to)` changed: they go to the
/// card's side before the next submission.
fn card_changed(&self, from: usize, to: usize) {
self.card_changed_runs(std::iter::once((from, to)));
}
/// [`Shadow::card_changed`] of each of `runs`.
fn card_changed_runs(&self, runs: impl Iterator<Item = (usize, usize)>) {
let Some(card) = &self.card else {
return;
};
if from >= to {
let mut runs = runs.filter(|r| r.0 < r.1).peekable();
if runs.peek().is_none() {
return;
}
let mut dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner());
match dirty.last_mut() {
Some(last) if from <= last.1 && to >= last.0 => *last = (last.0.min(from), last.1.max(to)),
_ => dirty.push((from, to)),
for (from, to) in runs {
match dirty.last_mut() {
Some(last) if from <= last.1 && to >= last.0 => *last = (last.0.min(from), last.1.max(to)),
_ => dirty.push((from, to)),
}
}
}
@@ -3379,7 +3450,7 @@ impl Shadow {
// Where title memory is not mapped the CPU's side keeps what
// the card wrote, as before.
let merged =
unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, self.data.add(lo), &parts, true, notes) };
unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, self.data.add(lo), &parts, true, notes, self) };
self.walls_merged(hi - lo, merged as usize);
put += merged;
}
@@ -3409,7 +3480,33 @@ impl Shadow {
// keeps out what else writes them. Title memory that is not there
// is looked at again when the next flight that declared the range
// lands.
unsafe { crate::land::piece(self.start as usize + at, self.data.add(at), held.add(at), &[(0, n)], false, notes) }
unsafe { crate::land::piece(self.start as usize + at, self.data.add(at), held.add(at), &[(0, n)], false, notes, self) }
}
/// What shaders wrote in 64 KiB block `block` (of title memory) of this
/// copy was put into title memory beside the guard, which was noted as a
/// write with number `now`, `before` the number of the block's last write
/// before. If the copy held title memory's bytes of the block ahead of
/// that it holds them still, and is noted to ([`crate::land`] says why);
/// whether it was.
///
/// That it did: it took the whole block after that write, and no other
/// came that is not noted yet. Looked at after the note, whatever comes
/// later has a number above it: a write of the title's takes the block's
/// bit, until an asking has noted it.
pub(crate) fn landed(&self, block: usize, before: u64, now: u64) -> bool {
let Some(page) = block.checked_sub(self.start as usize / PAGE) else {
return false;
};
let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
let Some(at) = copied.get_mut(page) else {
return false;
};
let held = *at != 0 && *at >= before && crate::watch::block_published(block);
if held {
*at = (*at).max(now);
}
held
}
}
+44
View File
@@ -1119,6 +1119,16 @@ pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 {
}
let start = at as usize;
let end = start.saturating_add(len);
// Streamed textures lie in views of physical pages, of which the runtime
// knows which are there: one look, where the host was asked for every
// 64 KiB of the texture (and once more for each that is not there).
// `VICTORY_MAPPED_BY_VIEWS=0`: the host is asked, as before.
static BY_VIEWS: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if *BY_VIEWS.get_or_init(|| std::env::var_os("VICTORY_MAPPED_BY_VIEWS").is_none_or(|v| v != "0"))
&& let Some(there) = crate::inplace::shown_bytes(start, len)
{
return there;
}
if !committed(at, 1) && !committed((end - 1) as *const u8, 1) {
return 0;
}
@@ -1417,6 +1427,40 @@ mod allocation_costs {
drop(all);
}
/// What a look at how much of a texture is there costs: by questions to
/// the host, and by the runtime's record of its views.
#[test]
#[ignore = "a measurement, not a check"]
fn look_costs() {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc};
const BLOCK: usize = 64 << 10;
for (name, blocks, there) in [("350 KB, all there", 6, 6), ("22 MB, all there", 350, 350), ("22 MB, 1 MB there", 350, 16)] {
let make = || {
// SAFETY: a reservation of our own, of which the first part
// is committed and touched.
unsafe {
let at = VirtualAlloc(std::ptr::null(), blocks * BLOCK, MEM_RESERVE, PAGE_READWRITE);
VirtualAlloc(at, there * BLOCK, MEM_COMMIT, PAGE_READWRITE);
std::ptr::write_bytes(at.cast::<u8>(), 1, there * BLOCK);
at as usize
}
};
let (asked, noted) = (make(), make());
for block in 0..there {
crate::title_memory_view(noted + block * BLOCK, BLOCK, 9, 0);
}
for (how, at) in [("asking the host", asked), ("by the views", noted)] {
const N: u32 = 200;
let began = std::time::Instant::now();
for _ in 0..N {
assert_eq!(super::mapped_bytes(at as *const u8, blocks * BLOCK), (there * BLOCK) as u64);
}
println!("{name}, {how}: {:.1} us a look", began.elapsed().as_secs_f64() * 1e6 / f64::from(N));
}
crate::inplace::views_gone(noted, blocks * BLOCK);
}
}
#[test]
#[ignore = "a measurement, not a check"]
fn allocation_costs() {
File diff suppressed because it is too large. Load diff