First uploads of textures picked by index run on a copy queue of their own, their slots show them when they have (VICTORY_UPLOAD_AHEAD=1; off); blips found while the camera moves
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
af0013dd76
commit
1cfc476831
7 files changed
+654
-21
No files matched your search
@@ -497,8 +497,8 @@ pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) {
|
||||
}
|
||||
|
||||
/// Runs `f` with the host heap of the title's largest view heap, if there is
|
||||
/// one (reports: nothing is waited for).
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
/// one (nothing is waited for).
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn with_view_heap<T>(f: impl FnOnce(&host::HostHeap) -> T) -> Option<T> {
|
||||
let heaps = SHADER_HEAPS.try_read().ok()?;
|
||||
let host = heaps
|
||||
|
||||
@@ -326,6 +326,13 @@ fn neutral_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<ID3D12Res
|
||||
|
||||
static FLIPS: Mutex<Vec<Flip>> = Mutex::new(Vec::new());
|
||||
|
||||
/// Makes the slots whose new texture's upload has run
|
||||
/// ([`HostHeap::texture_slots_flip`]); on any thread. Not if the heap is at
|
||||
/// something else: the next texture pass does.
|
||||
pub(crate) fn flip_now() {
|
||||
let _ = super::with_view_heap(HostHeap::texture_slots_flip);
|
||||
}
|
||||
|
||||
/// Since the start: slots made from their new view after its upload had run,
|
||||
/// and those the title had written again by then.
|
||||
pub(crate) static FLIPPED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
|
||||
@@ -1986,19 +1993,27 @@ impl HostHeap {
|
||||
/// `handle` views, or something else: until then it shows the neutral
|
||||
/// texture ([`show_after`]).
|
||||
pub(crate) fn texture_slot_show_after(&self, list: &crate::host::HostList, index: u32, handle: u64) {
|
||||
if self.show_later(index, handle) {
|
||||
self.flip(list, index, handle, Some(crate::frame::current()));
|
||||
}
|
||||
}
|
||||
|
||||
/// What slot `index` shows until the texture the record at `handle` views
|
||||
/// is shown. False: it shows it, or there is none.
|
||||
fn show_later(&self, index: u32, handle: u64) -> bool {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let key = record_key(handle);
|
||||
let view = view_at(key as u32, (key >> 32) as u32);
|
||||
let (true, Some(view)) = (key != 0, view) else {
|
||||
return;
|
||||
return false;
|
||||
};
|
||||
{
|
||||
let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Some(&shown) = made.get(index as usize) else {
|
||||
return;
|
||||
return false;
|
||||
};
|
||||
if shown == key {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
// (As `mirror`.)
|
||||
for stale in self.note_buffer(index, Some(&view), true) {
|
||||
@@ -2023,7 +2038,21 @@ impl HostHeap {
|
||||
self.keep(index, kept);
|
||||
}
|
||||
}
|
||||
self.flip(list, index, handle, Some(crate::frame::current()));
|
||||
true
|
||||
}
|
||||
|
||||
/// [`HostHeap::texture_slot_show_after`] of a texture whose upload `job`
|
||||
/// makes: shown when that has run.
|
||||
pub(crate) fn texture_slot_show_ahead(&self, job: &crate::texture::ahead::Job, index: u32, handle: u64) {
|
||||
if !self.show_later(index, handle) {
|
||||
return;
|
||||
}
|
||||
let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle));
|
||||
let late = Some(crate::frame::current());
|
||||
job.then(move || {
|
||||
let flip = Flip { after: 0, heap, index, handle, key, late };
|
||||
FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip);
|
||||
});
|
||||
}
|
||||
|
||||
/// [`HostHeap::mirror`] of a slot whose table a draw read: a texture made
|
||||
@@ -2037,6 +2066,7 @@ impl HostHeap {
|
||||
&& let Some(View::Shader(resource, _)) = placed_texture(&view).or(Some(view))
|
||||
&& crate::resource::buffer_bytes(resource as crate::object::This).is_none()
|
||||
&& crate::resource::host_resource(resource as crate::object::This).is_some_and(crate::pool::fresh)
|
||||
&& !crate::texture::ahead::there(resource as crate::object::This)
|
||||
{
|
||||
return self.texture_slot_show_after(list, index, handle);
|
||||
}
|
||||
@@ -2101,8 +2131,14 @@ impl HostHeap {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
note_before(f.index, *shown, if f.late.is_some() { "shown after its upload" } else { "flip" });
|
||||
self.put(f.index);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
let was = *shown;
|
||||
*shown = f.key;
|
||||
self.keep(f.index, kept);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if f.late.is_some() && was != 0 {
|
||||
same_bytes(was, f.key);
|
||||
}
|
||||
if let Some(since) = f.late {
|
||||
let frames = crate::frame::current().saturating_sub(since);
|
||||
let n = LATE[0].fetch_add(1, Relaxed) + 1;
|
||||
@@ -4085,6 +4121,45 @@ fn rewritten(kin: Kin, kept: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Diagnostics: whether a texture that a slot showed until its new one came
|
||||
/// holds the new one's bytes (the title moved it), by the bytes their host
|
||||
/// copies were filled from: equal, different, not known.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
fn same_bytes(old: u64, new: u64) {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
static SEEN: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
|
||||
let view = |key: u64| view_at(key as u32, (key >> 32) as u32);
|
||||
let (Some(old), Some(new)) = (view(old), view(new)) else {
|
||||
return;
|
||||
};
|
||||
let held = |view: &View| {
|
||||
let View::Placed(false, resource, desc) = view else {
|
||||
return None;
|
||||
};
|
||||
let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
|
||||
crate::resource::texture_held(crate::resource::texture_at_made(address, resource)?)
|
||||
};
|
||||
let class = match kin(&old, &new) {
|
||||
Kin::Moved => 0,
|
||||
Kin::Same | Kin::None => return,
|
||||
_ => 3,
|
||||
};
|
||||
let which = match (held(&old), held(&new)) {
|
||||
(Some(a), Some(b)) if a == b => 0,
|
||||
(Some(a), Some(b)) if a.0 == b.0 => 1,
|
||||
_ => 2,
|
||||
};
|
||||
SEEN[class + which].fetch_add(1, Relaxed);
|
||||
let n: u64 = SEEN.iter().map(|n| n.load(Relaxed)).sum();
|
||||
if n.is_multiple_of(1000) {
|
||||
let seen: Vec<u64> = SEEN.iter().map(|n| n.load(Relaxed)).collect();
|
||||
tracing::info!(
|
||||
"slots that went on showing another texture until the new one came, since the start: of one of the same kind elsewhere {} had the new one's bytes, {} others, {} not known; of others {}, {}, {}",
|
||||
seen[0], seen[1], seen[2], seen[3], seen[4], seen[5]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// For `crate::popwatch`, since the start: slots made null as they were
|
||||
/// written with another texture, such that kept the old one, slots given the
|
||||
/// neutral texture, slots made null as their memory was another's.
|
||||
|
||||
@@ -2380,7 +2380,7 @@ impl State {
|
||||
let _ = host.mirror(index, handle, true);
|
||||
}
|
||||
// Its bytes are in, or on the way there in a list before.
|
||||
if late && texture.is_some_and(crate::pool::fresh) {
|
||||
if late && texture.is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource) {
|
||||
if let Some(handle) = heap.handle(index) {
|
||||
host.texture_slot_show_after(list, index, handle);
|
||||
}
|
||||
@@ -2398,7 +2398,27 @@ impl State {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some(view) = &view {
|
||||
// The first upload of a texture no list has used: on a queue of
|
||||
// its own, and the slot shows it as soon as that has run.
|
||||
let ahead = if late && !tabled && texture.is_some_and(crate::pool::fresh) {
|
||||
crate::texture::ahead::take(resource, first, there.filter(|_| partly.is_none()).unwrap_or(u64::MAX))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(ahead) = &ahead {
|
||||
use crate::texture::ahead::Taken;
|
||||
let (Taken::New(job) | Taken::Known(job)) = ahead;
|
||||
if let Some(handle) = heap.handle(index) {
|
||||
host.texture_slot_show_ahead(job, index, handle);
|
||||
}
|
||||
if let Taken::New(job) = ahead {
|
||||
crate::texture::ahead::send(job);
|
||||
}
|
||||
}
|
||||
let late = late && ahead.is_none();
|
||||
if let Some(view) = &view
|
||||
&& ahead.is_none()
|
||||
{
|
||||
// (What was found mapped of it a moment ago is not asked
|
||||
// again, unless the host copy may need more.)
|
||||
crate::texture::PICKING.set(Some(there.filter(|_| partly.is_none()).unwrap_or(u64::MAX)));
|
||||
|
||||
@@ -5,7 +5,10 @@
|
||||
//! - blips: blocks that one frame shows otherwise than the frames before and
|
||||
//! after it, which agree (a texture black, grey or another one for a frame);
|
||||
//! - steps: blocks that change from one frame to the next and stay so, while
|
||||
//! most of the picture does not move.
|
||||
//! most of the picture does not move;
|
||||
//! - lone blocks: blocks found in neither neighbour, wherever the camera may
|
||||
//! have moved them, while the neighbours' blocks there are found in each
|
||||
//! other (a blip while the camera moves).
|
||||
//!
|
||||
//! `VICTORY_POP_FOLDER=<folder>`: the three pictures around a frame with
|
||||
//! blips (at most 200 times) are saved there, 640 wide; with
|
||||
@@ -66,11 +69,89 @@ struct Job {
|
||||
flown: u64,
|
||||
ms: u64,
|
||||
causes: [u64; 4],
|
||||
phase: Option<bool>,
|
||||
phase: usize,
|
||||
}
|
||||
|
||||
/// Read-back buffers not in use.
|
||||
static FREE: Mutex<Vec<Taken>> = Mutex::new(Vec::new());
|
||||
/// How far a block is looked for in a neighbour's picture, in pixels of half
|
||||
/// the small picture's size, and the side of a block there.
|
||||
const REACH: i32 = 14;
|
||||
const HALF_BLOCK: usize = BLOCK / 2;
|
||||
|
||||
/// A small picture at half its size, as brightness and two colour differences.
|
||||
fn half(rgb: &[u8]) -> Vec<[i16; 3]> {
|
||||
let (w, h) = (WIDE / 2, HIGH / 2);
|
||||
let mut out = Vec::with_capacity(w * h);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let mut s = [0i16; 3];
|
||||
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
|
||||
let at = ((y * 2 + dy) * WIDE + x * 2 + dx) * 3;
|
||||
for (s, v) in s.iter_mut().zip(&rgb[at..at + 3]) {
|
||||
*s += i16::from(*v);
|
||||
}
|
||||
}
|
||||
out.push(s.map(|s| s / 4));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Per block of `a`: how much it differs from the place in `b` that is most
|
||||
/// like it, as [`differ`] says it.
|
||||
fn moved(a: &[[i16; 3]], b: &[[i16; 3]]) -> Vec<f32> {
|
||||
let (w, h) = (WIDE / 2, HIGH / 2);
|
||||
let (across, down) = (WIDE / BLOCK, HIGH / BLOCK);
|
||||
let mut out = vec![f32::MAX; across * down];
|
||||
for (n, best) in out.iter_mut().enumerate() {
|
||||
let (bx, by) = (n % across * HALF_BLOCK, n / across * HALF_BLOCK);
|
||||
let mut least = u32::MAX;
|
||||
for dy in -REACH..=REACH {
|
||||
let y0 = by as i32 + dy;
|
||||
if y0 < 0 || y0 as usize + HALF_BLOCK > h {
|
||||
continue;
|
||||
}
|
||||
for dx in -REACH..=REACH {
|
||||
let x0 = bx as i32 + dx;
|
||||
if x0 < 0 || x0 as usize + HALF_BLOCK > w {
|
||||
continue;
|
||||
}
|
||||
let mut sum = 0u32;
|
||||
for row in 0..HALF_BLOCK {
|
||||
let ra = &a[(by + row) * w + bx..][..HALF_BLOCK];
|
||||
let rb = &b[(y0 as usize + row) * w + x0 as usize..][..HALF_BLOCK];
|
||||
sum += ra
|
||||
.iter()
|
||||
.zip(rb)
|
||||
.map(|(p, q)| (0..3).map(|i| p[i].abs_diff(q[i])).max().unwrap_or(0) as u32)
|
||||
.sum::<u32>();
|
||||
if sum >= least {
|
||||
break;
|
||||
}
|
||||
}
|
||||
least = least.min(sum);
|
||||
}
|
||||
}
|
||||
*best = least as f32 / (HALF_BLOCK * HALF_BLOCK) as f32;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Blocks of `now` found in neither neighbour, where `before` is found in
|
||||
/// `after`.
|
||||
fn lone(before: &[[i16; 3]], now: &[[i16; 3]], after: &[[i16; 3]]) -> Vec<usize> {
|
||||
let (one, two) = (moved(now, before), moved(now, after));
|
||||
let both = moved(before, after);
|
||||
// A cut on either side is none.
|
||||
if one.iter().filter(|&&d| d > CHANGED).count() * 4 > one.len()
|
||||
|| two.iter().filter(|&&d| d > CHANGED).count() * 4 > two.len()
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
(0..one.len()).filter(|&n| one[n] > CHANGED && two[n] > CHANGED && both[n] < CHANGED / 2.0).collect()
|
||||
}
|
||||
|
||||
/// Frames on their way.
|
||||
static WAITING: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
@@ -118,7 +199,8 @@ pub(crate) fn sent(taken: Taken, flown: u64, frame: u64) {
|
||||
flown,
|
||||
ms: crate::host::now_ms(),
|
||||
causes: crate::descriptor::host::pop_causes(),
|
||||
phase: crate::ab::pick("VICTORY_KEEP_SHOWN"),
|
||||
phase: usize::from(crate::ab::pick("VICTORY_KEEP_SHOWN").unwrap_or(false))
|
||||
+ 2 * usize::from(crate::ab::pick("VICTORY_UPLOAD_AHEAD").unwrap_or(false)),
|
||||
};
|
||||
let _ = to.send(job);
|
||||
}
|
||||
@@ -131,14 +213,17 @@ struct Seen {
|
||||
blip_frames: u64,
|
||||
steps: u64,
|
||||
still: u64,
|
||||
lone: u64,
|
||||
lone_frames: u64,
|
||||
}
|
||||
|
||||
struct Picture {
|
||||
frame: u64,
|
||||
ms: u64,
|
||||
causes: [u64; 4],
|
||||
phase: Option<bool>,
|
||||
phase: usize,
|
||||
rgb: Vec<u8>,
|
||||
half: Vec<[i16; 3]>,
|
||||
/// Per block: how much it differs from the frame before.
|
||||
changed: Vec<f32>,
|
||||
saved: bool,
|
||||
@@ -228,7 +313,7 @@ fn save(p: &mut Picture) {
|
||||
fn watch(from: &mpsc::Receiver<Job>) {
|
||||
let all = std::env::var_os("VICTORY_POP_ALL").is_some_and(|v| v == "1");
|
||||
let mut last: VecDeque<Picture> = VecDeque::new();
|
||||
let mut seen: [Seen; 2] = Default::default();
|
||||
let mut seen: [Seen; 4] = Default::default();
|
||||
let mut told = crate::host::now_ms();
|
||||
let mut sets = 0;
|
||||
while let Ok(job) = from.recv() {
|
||||
@@ -257,7 +342,8 @@ fn watch(from: &mpsc::Receiver<Job>) {
|
||||
}
|
||||
let changed = last.back().map(|p| differ(&p.rgb, &rgb)).unwrap_or_default();
|
||||
let (frame, ms, causes, phase) = (job.frame, job.ms, job.causes, job.phase);
|
||||
last.push_back(Picture { frame, ms, causes, phase, rgb, changed, saved: false });
|
||||
let half = half(&rgb);
|
||||
last.push_back(Picture { frame, ms, causes, phase, rgb, half, changed, saved: false });
|
||||
if all && let Some(p) = last.back_mut() {
|
||||
save(p);
|
||||
}
|
||||
@@ -266,21 +352,24 @@ fn watch(from: &mpsc::Receiver<Job>) {
|
||||
}
|
||||
if let [first, before, now, after] = last.make_contiguous() {
|
||||
let (blips, steps) = judge(&before.rgb, &now.rgb, &after.rgb, &before.changed);
|
||||
let side = &mut seen[usize::from(now.phase.unwrap_or(false))];
|
||||
let side = &mut seen[now.phase];
|
||||
side.frames += 1;
|
||||
side.blips += blips as u64;
|
||||
side.blip_frames += u64::from(blips > 0);
|
||||
side.still += u64::from(steps.is_some());
|
||||
side.steps += steps.unwrap_or(0) as u64;
|
||||
if blips > 0 || steps.is_some_and(|s| s > 0) {
|
||||
let lone = lone(&before.half, &now.half, &after.half);
|
||||
side.lone += lone.len() as u64;
|
||||
side.lone_frames += u64::from(!lone.is_empty());
|
||||
if blips > 0 || lone.len() > 1 || steps.is_some_and(|s| s > 0) {
|
||||
let since: Vec<u64> = now.causes.iter().zip(&first.causes).map(|(a, b)| a.saturating_sub(*b)).collect();
|
||||
tracing::info!(
|
||||
"pop watch: frame {} at {:.2} s: {blips} blips, {steps:?} steps; in the two frames before it [made null for another texture, kept, neutral, stale] {since:?}",
|
||||
"pop watch: frame {} at {:.2} s: {blips} blips, {steps:?} steps, lone blocks {lone:?}; in the two frames before it [made null for another texture, kept, neutral, stale] {since:?}",
|
||||
now.frame,
|
||||
now.ms as f64 / 1e3
|
||||
);
|
||||
}
|
||||
if (blips > 0 || steps.is_some_and(|s| s > 2)) && sets < 200 {
|
||||
if (blips > 0 || lone.len() > 1 || steps.is_some_and(|s| s > 2)) && sets < 200 {
|
||||
sets += 1;
|
||||
save(before);
|
||||
save(now);
|
||||
@@ -291,13 +380,16 @@ fn watch(from: &mpsc::Receiver<Job>) {
|
||||
told = crate::host::now_ms();
|
||||
for (n, s) in seen.iter().enumerate().filter(|(_, s)| s.frames > 0) {
|
||||
tracing::info!(
|
||||
"pop watch, since the start, VICTORY_KEEP_SHOWN {} in its A/B phases: {} frames, blips in {} of them ({} blocks of 16x16), {} frames whose picture stood still with {} blocks stepped",
|
||||
n,
|
||||
"pop watch, since the start, A/B VICTORY_KEEP_SHOWN {} VICTORY_UPLOAD_AHEAD {}: {} frames, blips in {} of them ({} blocks of 16x16), {} frames whose picture stood still with {} blocks stepped, lone blocks in {} frames ({} blocks)",
|
||||
n & 1,
|
||||
n >> 1,
|
||||
s.frames,
|
||||
s.blip_frames,
|
||||
s.blips,
|
||||
s.still,
|
||||
s.steps
|
||||
s.steps,
|
||||
s.lone_frames,
|
||||
s.lone
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -333,6 +425,21 @@ mod tests {
|
||||
assert_eq!(judge(&a, &b, &b, &vec![9.0; quiet.len()]), (0, Some(0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_one_frame_alone_shows_is_found_while_the_camera_moves() {
|
||||
// A picture of noise, moved by 6 pixels a frame.
|
||||
let at = |shift: usize| -> Vec<u8> {
|
||||
(0..HIGH)
|
||||
.flat_map(|y| (0..WIDE).map(move |x| ((x + shift) / 8 * 37 + y / 8 * 91) as u8))
|
||||
.flat_map(|v| [v, v.wrapping_mul(3), 255 - v])
|
||||
.collect()
|
||||
};
|
||||
let (a, mut b, c) = (at(0), at(8), at(16));
|
||||
assert!(lone(&half(&a), &half(&b), &half(&c)).is_empty());
|
||||
patch(&mut b, 20, 10, 128);
|
||||
assert_eq!(lone(&half(&a), &half(&b), &half(&c)), vec![10 * (WIDE / BLOCK) + 20]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn times_are_read_and_pictures_made_small() {
|
||||
assert_eq!(parse("10-20, 30.5-40"), vec![(10.0, 20.0), (30.5, 40.0)]);
|
||||
|
||||
@@ -1177,6 +1177,8 @@ pub(crate) struct HostTexture {
|
||||
pub(crate) grown: std::sync::atomic::AtomicBool,
|
||||
/// What the last submitted upload put in it.
|
||||
pub(crate) holds: std::sync::Arc<Holds>,
|
||||
/// Who makes its first upload (`crate::texture::ahead`).
|
||||
pub(crate) ahead: std::sync::atomic::AtomicU8,
|
||||
/// The texture's flags (asked once: the runtime takes 100 ns to say, and
|
||||
/// every texture of every draw is asked about).
|
||||
flags: u32,
|
||||
@@ -2295,6 +2297,7 @@ impl HostTexture {
|
||||
serial: SERIAL.fetch_add(1, Relaxed) + 1,
|
||||
grown: Default::default(),
|
||||
holds: Default::default(),
|
||||
ahead: crate::texture::ahead::fresh(),
|
||||
flags,
|
||||
}
|
||||
}
|
||||
@@ -2319,6 +2322,7 @@ impl HostTexture {
|
||||
serial: SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1,
|
||||
grown: Default::default(),
|
||||
holds: Default::default(),
|
||||
ahead: crate::texture::ahead::fresh(),
|
||||
flags,
|
||||
}
|
||||
}
|
||||
@@ -2968,6 +2972,13 @@ pub(crate) fn texture_at_made(address: u64, desc: &[u32; 14]) -> Option<This> {
|
||||
Some(*found as This)
|
||||
}
|
||||
|
||||
/// From which level on the title texture's host copy was filled, and from
|
||||
/// which bytes (diagnostics).
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
pub(crate) fn texture_held(resource: This) -> Option<(u32, crate::texture::Digest)> {
|
||||
*made_copy(resource)?.holds.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// The resource for a texture placed at `address` with the resource
|
||||
/// description `desc` (as words), made on first use.
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
//! (directly indexed views are not known per draw); plane 0 is uploaded
|
||||
//! (every mip and array slice), depth and stencil planes are not.
|
||||
|
||||
pub(crate) mod ahead;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
@@ -745,6 +747,7 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
|
||||
return;
|
||||
};
|
||||
let texture = ©.texture;
|
||||
ahead::listed(©);
|
||||
let Some(staging) = staging(resource, ©, first) else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
//! First uploads of textures picked by index on a copy queue of their own
|
||||
//! (`VICTORY_UPLOAD_AHEAD`): read, detiled and copied by threads of ours as
|
||||
//! soon as the texture pass has made them, and the slots that wait for them
|
||||
//! shown when the copy has run. Recorded into the pass's list, as every other
|
||||
//! upload is, the copy ran with the frame that needs it, so a slot that shows
|
||||
//! its texture only after its upload ([`crate::descriptor::host::show_after`])
|
||||
//! was black or grey in that frame, and in the next.
|
||||
//!
|
||||
//! Only a texture that no list has used is taken: made in the last second,
|
||||
//! in the common state, and never asked for an upload before
|
||||
//! ([`crate::resource::HostTexture::ahead`]). It stays in the common state
|
||||
//! (a copy queue's copies leave it there), from which the card's shaders read
|
||||
//! it as any texture.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering::Relaxed};
|
||||
use std::sync::{Arc, Condvar, Mutex, OnceLock};
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
use windows::core::Interface;
|
||||
|
||||
use super::Staging;
|
||||
use crate::object::This;
|
||||
use crate::resource::HostTexture;
|
||||
|
||||
/// [`HostTexture::ahead`]: no upload was asked for yet; one is on its way
|
||||
/// here; it has run; one was recorded into a list.
|
||||
pub(crate) const NONE: u8 = 0;
|
||||
const PENDING: u8 = 1;
|
||||
const DONE: u8 = 2;
|
||||
pub(crate) const LISTED: u8 = 3;
|
||||
|
||||
/// Bytes of title memory on their way at most: past it uploads go into the
|
||||
/// lists, as before.
|
||||
const MOST: u64 = 96 << 20;
|
||||
/// Bytes and textures of one submission at most.
|
||||
const BATCH: (u64, usize) = (16 << 20, 64);
|
||||
|
||||
/// Whether it is on (`VICTORY_UPLOAD_AHEAD`; off).
|
||||
pub(crate) fn on() -> bool {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if let Some(on) = crate::ab::pick("VICTORY_UPLOAD_AHEAD") {
|
||||
return on;
|
||||
}
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_UPLOAD_AHEAD").is_some_and(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// An upload on its way.
|
||||
pub(crate) struct Job {
|
||||
staging: Arc<Staging>,
|
||||
copy: Arc<HostTexture>,
|
||||
asked: std::time::Instant,
|
||||
/// What to do when it has run; `None`: it has.
|
||||
then: Mutex<Option<Vec<Box<dyn FnOnce() + Send>>>>,
|
||||
}
|
||||
|
||||
impl Job {
|
||||
/// Calls `f` when the copy has run: now if it has.
|
||||
pub(crate) fn then(&self, f: impl FnOnce() + Send + 'static) {
|
||||
let mut then = self.then.lock().unwrap_or_else(|e| e.into_inner());
|
||||
match then.as_mut() {
|
||||
Some(then) => then.push(Box::new(f)),
|
||||
None => {
|
||||
drop(then);
|
||||
f();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a texture asked for here gets.
|
||||
pub(crate) enum Taken {
|
||||
/// A job of its own, to be [`send`] once what follows it is added.
|
||||
New(Arc<Job>),
|
||||
/// One already on its way, or that has run.
|
||||
Known(Arc<Job>),
|
||||
}
|
||||
|
||||
static QUEUE: (Mutex<VecDeque<Arc<Job>>>, Condvar) = (Mutex::new(VecDeque::new()), Condvar::new());
|
||||
/// Those on their way, by host copy ([`HostTexture::serial`]).
|
||||
static ON_THEIR_WAY: Mutex<Vec<(u64, Arc<Job>)>> = Mutex::new(Vec::new());
|
||||
static LANDED: Condvar = Condvar::new();
|
||||
static BYTES: AtomicU64 = AtomicU64::new(0);
|
||||
/// Since the start: uploads, bytes, microseconds from the asking until the
|
||||
/// copy had run, the longest; askings turned down; waits of lists.
|
||||
static STATS: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6];
|
||||
|
||||
/// Takes the first upload of `resource`'s levels from `first` on, `there` of
|
||||
/// whose bytes are mapped (`u64::MAX`: not known). `None`: the list's.
|
||||
pub(crate) fn take(resource: This, first: u32, there: u64) -> Option<Taken> {
|
||||
if on() { claim(resource, first, there) } else { None }
|
||||
}
|
||||
|
||||
fn claim(resource: This, first: u32, there: u64) -> Option<Taken> {
|
||||
workers()?;
|
||||
let turned_down = || {
|
||||
STATS[4].fetch_add(1, Relaxed);
|
||||
None
|
||||
};
|
||||
let copy = crate::resource::host_copy(resource)?;
|
||||
if copy.ahead.load(Relaxed) == PENDING {
|
||||
let way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
|
||||
return way.iter().find(|(serial, _)| *serial == copy.serial).map(|(_, job)| Taken::Known(job.clone()));
|
||||
}
|
||||
if BYTES.load(Relaxed) >= MOST
|
||||
|| copy.flags() & 0x7 != 0
|
||||
|| copy.state.load(Relaxed) != 0
|
||||
|| copy.grown.load(Relaxed)
|
||||
|| copy.tiled.is_some()
|
||||
|| copy.holds.lock().unwrap_or_else(|e| e.into_inner()).is_some()
|
||||
|| !crate::pool::fresh(©.texture)
|
||||
|| super::host_wrote(resource as usize)
|
||||
|| crate::resource::alias_of(resource).is_some()
|
||||
{
|
||||
return turned_down();
|
||||
}
|
||||
if copy.ahead.compare_exchange(NONE, PENDING, Relaxed, Relaxed).is_err() {
|
||||
return turned_down();
|
||||
}
|
||||
super::PICKING.set(Some(there));
|
||||
let staging = super::staging(resource, ©, first);
|
||||
super::PICKING.set(None);
|
||||
let Some(staging) = staging.filter(|s| {
|
||||
!s.on_demand && s.first == s.level0 && !s.uploaded.load(Relaxed) && s.once.load(Relaxed)
|
||||
}) else {
|
||||
copy.ahead.store(LISTED, Relaxed);
|
||||
return turned_down();
|
||||
};
|
||||
if super::no_wait() && super::fill_unlocked() {
|
||||
staging.expected.store(if there == u64::MAX { super::mapped_bytes(staging.memory, staging.read) } else { there }, Relaxed);
|
||||
}
|
||||
let job = Arc::new(Job { staging, copy, asked: std::time::Instant::now(), then: Mutex::new(Some(Vec::new())) });
|
||||
BYTES.fetch_add(job.staging.read as u64, Relaxed);
|
||||
ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()).push((job.copy.serial, job.clone()));
|
||||
Some(Taken::New(job))
|
||||
}
|
||||
|
||||
/// Sends a job of [`take`] on its way.
|
||||
pub(crate) fn send(job: &Arc<Job>) {
|
||||
QUEUE.0.lock().unwrap_or_else(|e| e.into_inner()).push_back(job.clone());
|
||||
QUEUE.1.notify_one();
|
||||
}
|
||||
|
||||
/// A list is about to record an upload into `copy`: one on its way here runs
|
||||
/// first, and no other is taken after it.
|
||||
pub(crate) fn listed(copy: &HostTexture) {
|
||||
if copy.ahead.compare_exchange(NONE, LISTED, Relaxed, Relaxed) != Err(PENDING) {
|
||||
return;
|
||||
}
|
||||
STATS[5].fetch_add(1, Relaxed);
|
||||
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let started = std::time::Instant::now();
|
||||
while way.iter().any(|(serial, _)| *serial == copy.serial) && started.elapsed().as_millis() < 1000 {
|
||||
way = LANDED.wait_timeout(way, std::time::Duration::from_millis(50)).unwrap_or_else(|e| e.into_inner()).0;
|
||||
}
|
||||
}
|
||||
|
||||
/// The copy queue and its threads, made on first use.
|
||||
fn workers() -> Option<&'static ID3D12CommandQueue> {
|
||||
/// Free-threaded.
|
||||
struct Queue(ID3D12CommandQueue);
|
||||
// SAFETY: a command queue is free-threaded.
|
||||
unsafe impl Send for Queue {}
|
||||
// SAFETY: as above.
|
||||
unsafe impl Sync for Queue {}
|
||||
static WORKERS: OnceLock<Option<Queue>> = OnceLock::new();
|
||||
WORKERS
|
||||
.get_or_init(|| {
|
||||
let host = crate::host::host()?;
|
||||
// SAFETY: plain object creation.
|
||||
let queue: ID3D12CommandQueue = unsafe {
|
||||
host.device
|
||||
.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
|
||||
Type: D3D12_COMMAND_LIST_TYPE_COPY,
|
||||
..Default::default()
|
||||
})
|
||||
.ok()?
|
||||
};
|
||||
for n in 0..2 {
|
||||
let worker = Worker::new(&host.device, queue.clone()).ok()?;
|
||||
std::thread::Builder::new().name(format!("uploads ahead {n}")).spawn(move || worker.work()).ok()?;
|
||||
}
|
||||
Some(Queue(queue))
|
||||
})
|
||||
.as_ref()
|
||||
.map(|q| &q.0)
|
||||
}
|
||||
|
||||
struct Worker {
|
||||
queue: ID3D12CommandQueue,
|
||||
allocator: ID3D12CommandAllocator,
|
||||
list: ID3D12GraphicsCommandList,
|
||||
fence: ID3D12Fence,
|
||||
}
|
||||
|
||||
// SAFETY: a worker's objects are its thread's own; the queue is free-threaded.
|
||||
unsafe impl Send for Worker {}
|
||||
|
||||
impl Worker {
|
||||
fn new(device: &ID3D12Device, queue: ID3D12CommandQueue) -> windows::core::Result<Worker> {
|
||||
// SAFETY: plain object creation.
|
||||
unsafe {
|
||||
let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
|
||||
let list: ID3D12GraphicsCommandList =
|
||||
device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
|
||||
list.Close()?;
|
||||
Ok(Worker { queue, allocator, list, fence: device.CreateFence(0, D3D12_FENCE_FLAG_NONE)? })
|
||||
}
|
||||
}
|
||||
|
||||
fn work(self) {
|
||||
let mut value = 0;
|
||||
loop {
|
||||
let mut jobs = Vec::new();
|
||||
{
|
||||
let mut queue = QUEUE.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||
while queue.is_empty() {
|
||||
queue = QUEUE.1.wait(queue).unwrap_or_else(|e| e.into_inner());
|
||||
}
|
||||
let mut bytes = 0;
|
||||
while bytes < BATCH.0 && jobs.len() < BATCH.1
|
||||
&& let Some(job) = queue.pop_front()
|
||||
{
|
||||
bytes += job.staging.read as u64;
|
||||
jobs.push(job);
|
||||
}
|
||||
}
|
||||
value += 1;
|
||||
if let Err(e) = self.copy(&jobs, value) {
|
||||
tracing::warn!(error = %e, "uploads ahead did not run");
|
||||
}
|
||||
finish(jobs);
|
||||
}
|
||||
}
|
||||
|
||||
fn copy(&self, jobs: &[Arc<Job>], value: u64) -> windows::core::Result<()> {
|
||||
for job in jobs {
|
||||
job.staging.refresh();
|
||||
}
|
||||
// SAFETY: this worker's allocator and list, whose last submission has
|
||||
// run; the jobs hold what the list names until after the wait.
|
||||
unsafe {
|
||||
self.allocator.Reset()?;
|
||||
self.list.Reset(&self.allocator, None)?;
|
||||
for job in jobs {
|
||||
job.record(&self.list);
|
||||
}
|
||||
self.list.Close()?;
|
||||
self.queue.ExecuteCommandLists(&[Some(self.list.cast()?)]);
|
||||
self.queue.Signal(&self.fence, value)?;
|
||||
// (Without an event: this waits.)
|
||||
self.fence.SetEventOnCompletion(value, windows::Win32::Foundation::HANDLE::default())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Job {
|
||||
/// # Safety
|
||||
/// `list` is an open copy list, and the job lives until it has run.
|
||||
unsafe fn record(&self, list: &ID3D12GraphicsCommandList) {
|
||||
let (s, texture) = (&self.staging, &self.copy.texture);
|
||||
for (i, footprint) in s.footprints.iter().enumerate() {
|
||||
let to = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: a borrowed pointer the location never releases.
|
||||
pResource: unsafe { std::mem::transmute_copy(texture) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: s.first - s.level0 + i as u32 },
|
||||
};
|
||||
let from = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: as above.
|
||||
pResource: unsafe { std::mem::transmute_copy(&s.buffer) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
|
||||
PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: s.base + footprint.Offset, ..*footprint },
|
||||
},
|
||||
};
|
||||
// SAFETY: the caller's.
|
||||
unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The jobs' copies have run.
|
||||
fn finish(jobs: Vec<Arc<Job>>) {
|
||||
for job in &jobs {
|
||||
job.staging.uploaded.store(true, Relaxed);
|
||||
job.staging.dirty.store(false, Relaxed);
|
||||
job.staging.note_held();
|
||||
job.copy.ahead.store(DONE, Relaxed);
|
||||
BYTES.fetch_sub(job.staging.read as u64, Relaxed);
|
||||
}
|
||||
{
|
||||
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
|
||||
way.retain(|(serial, _)| !jobs.iter().any(|job| job.copy.serial == *serial));
|
||||
LANDED.notify_all();
|
||||
}
|
||||
for job in &jobs {
|
||||
let us = job.asked.elapsed().as_micros() as u64;
|
||||
let n = STATS[0].fetch_add(1, Relaxed) + 1;
|
||||
let bytes = STATS[1].fetch_add(job.staging.read as u64, Relaxed) + job.staging.read as u64;
|
||||
let all = STATS[2].fetch_add(us, Relaxed) + us;
|
||||
let most = STATS[3].fetch_max(us, Relaxed).max(us);
|
||||
if n == 1 || n.is_multiple_of(5000) {
|
||||
tracing::info!(
|
||||
"textures uploaded ahead of the lists (VICTORY_UPLOAD_AHEAD=1), since the start: {n}, {} MB, {:.1} ms from the asking until they were there, the longest {:.0}; {} turned down, {} waited for by lists",
|
||||
bytes >> 20,
|
||||
all as f64 / n as f64 / 1e3,
|
||||
most as f64 / 1e3,
|
||||
STATS[4].load(Relaxed),
|
||||
STATS[5].load(Relaxed)
|
||||
);
|
||||
}
|
||||
let then = job.then.lock().unwrap_or_else(|e| e.into_inner()).take();
|
||||
for f in then.into_iter().flatten() {
|
||||
f();
|
||||
}
|
||||
}
|
||||
crate::descriptor::host::flip_now();
|
||||
}
|
||||
|
||||
/// Whether `resource`'s host copy was filled here: no list still brings what
|
||||
/// it shows.
|
||||
pub(crate) fn there(resource: This) -> bool {
|
||||
crate::resource::made_copy(resource).is_some_and(|copy| copy.ahead.load(Relaxed) == DONE)
|
||||
}
|
||||
|
||||
/// The state of [`HostTexture::ahead`] of a new host copy.
|
||||
pub(crate) fn fresh() -> AtomicU8 {
|
||||
AtomicU8::new(NONE)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The texels of a placed texture arrive by the copy queue, all levels of
|
||||
/// them, and what waits for them is called then; a second asking finds the
|
||||
/// first on its way, and a later one is the list's.
|
||||
#[test]
|
||||
fn a_placed_texture_is_filled_ahead_of_the_lists() {
|
||||
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc};
|
||||
let Some(host) = crate::host::host() else { return };
|
||||
// 256x256 BC7, nine levels.
|
||||
let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0];
|
||||
let whole = crate::resource::placed_bytes(&desc).unwrap() as usize;
|
||||
// SAFETY: memory of our own that stays.
|
||||
let at = unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }.cast::<u8>();
|
||||
// SAFETY: as above.
|
||||
unsafe { (0..whole).for_each(|i| at.add(i).write((i * 13 + i / 509) as u8)) };
|
||||
let texture = crate::resource::texture_at(at as u64, &desc).unwrap();
|
||||
crate::resource::want_level(texture, 0);
|
||||
let copy = crate::resource::host_copy(texture).unwrap();
|
||||
if !crate::pool::fresh(©.texture) {
|
||||
return;
|
||||
}
|
||||
assert!(!there(texture));
|
||||
let Some(Taken::New(job)) = claim(texture, 0, u64::MAX) else { panic!("not taken") };
|
||||
let (told, heard) = std::sync::mpsc::channel();
|
||||
let also = told.clone();
|
||||
let Some(Taken::Known(same)) = claim(texture, 0, u64::MAX) else { panic!("not known") };
|
||||
assert!(Arc::ptr_eq(&job, &same));
|
||||
job.then(move || told.send(1).unwrap());
|
||||
same.then(move || also.send(2).unwrap());
|
||||
send(&job);
|
||||
let wait = std::time::Duration::from_secs(20);
|
||||
assert_eq!((heard.recv_timeout(wait), heard.recv_timeout(wait)), (Ok(1), Ok(2)));
|
||||
assert!(there(texture) && claim(texture, 0, u64::MAX).is_none());
|
||||
// Level 0 as the card has it, and as the layout says.
|
||||
let layout = crate::resource::texture_memory(texture)
|
||||
.and_then(|(_, d)| crate::resource::texture_layout(&d).map(|t| t.planes[0].layout.clone()))
|
||||
.unwrap();
|
||||
let (pitch, rows) = (1024usize, 64usize);
|
||||
let mut expected = vec![0u8; pitch * rows];
|
||||
// SAFETY: the memory above.
|
||||
let tiled = unsafe { std::slice::from_raw_parts(at, whole) };
|
||||
layout.detile(tiled, 0, 0, &mut expected, pitch, pitch * rows).unwrap();
|
||||
let back = host.read_back_buffer((pitch * rows) as u64).unwrap();
|
||||
let list = host.new_list().unwrap();
|
||||
list.close();
|
||||
list.reset();
|
||||
let footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
|
||||
Offset: 0,
|
||||
Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
|
||||
Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(98),
|
||||
Width: 256,
|
||||
Height: 256,
|
||||
Depth: 1,
|
||||
RowPitch: pitch as u32,
|
||||
},
|
||||
};
|
||||
let to = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: a borrowed pointer the location never releases.
|
||||
pResource: unsafe { std::mem::transmute_copy(&back) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint },
|
||||
};
|
||||
let from = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: as above.
|
||||
pResource: unsafe { std::mem::transmute_copy(©.texture) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
|
||||
};
|
||||
// SAFETY: an open list, live resources; the mapping spans the buffer.
|
||||
unsafe {
|
||||
list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None);
|
||||
list.close();
|
||||
host.execute(&[&list]);
|
||||
let mut data = std::ptr::null_mut();
|
||||
back.Map(0, None, Some(&mut data)).unwrap();
|
||||
let seen = std::slice::from_raw_parts(data.cast::<u8>(), pitch * rows);
|
||||
assert!(seen == expected.as_slice(), "level 0's blocks");
|
||||
back.Unmap(0, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user