A slot written with another texture goes on showing one that can stand for it (VICTORY_KEEP_SHOWN=1; 0: black, then grey); textures that pop are counted (VICTORY_POP_WATCH)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-25 10:39:25 -06:00
1 parent bc83b16387
commit af0013dd76
4 files changed
+527 -7

No files matched your search

+167 -5
View File
@@ -2007,7 +2007,11 @@ impl HostHeap {
}
}
let old = view_at(shown as u32, (shown >> 32) as u32);
if shown == 0 || !old.is_some_and(|old| same_placed_texture(&old, &view)) {
let kept = old.is_some_and(|old| match kin(&old, &view) {
Kin::Same => true,
kin => kin.kept(keep_shown()),
});
if shown == 0 || !kept {
#[cfg(feature = "diagnostics")]
note_before(index, shown, "neutral");
self.quick_is(index, 0);
@@ -2862,13 +2866,26 @@ impl HostHeap {
// one and uploads what it shows. Made null here, the texture
// read as nothing for as long as it waited in the queue, every
// time it got sharper.
let shown = made[index as usize];
if later
&& keep_views()
&& view_at(made[index as usize] as u32, (made[index as usize] >> 32) as u32)
.is_some_and(|old| same_placed_texture(&old, &view))
&& let Some(old) = view_at(shown as u32, (shown >> 32) as u32)
{
KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
return Some(view);
let kin = kin(&old, &view);
if kin == Kin::Same {
KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
return Some(view);
}
// And of another texture that can stand for it
// ([`keep_shown`]): black, then grey for a frame or two is
// what popped.
if is_texture_view(&old) {
let kept = kin.kept(keep_shown());
rewritten(kin, kept);
if kept {
return Some(view);
}
}
}
#[cfg(feature = "diagnostics")]
if !self.sampler && is_texture_view(&view) {
@@ -3964,6 +3981,121 @@ fn keep_views() -> bool {
*ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_VIEWS").is_none_or(|v| v != "0"))
}
/// What the texture view a slot is written with has to do with the one it
/// shows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kin {
/// A view of the same placed texture ([`same_placed_texture`]).
Same,
/// A texture of the same description placed elsewhere (moved, or one of
/// its kind).
Moved,
/// One of the same format and shape in another size: the same texture
/// with more or fewer levels, as a title streams it.
Sized,
/// A view of the same dimension, of another texture.
Other,
/// A view no shader that reads the one can read.
None,
}
impl Kin {
/// Whether the slot goes on showing what it shows, by [`keep_shown`].
fn kept(self, keep: u8) -> bool {
match self {
Kin::Same => true,
Kin::Moved | Kin::Sized => keep >= 1,
Kin::Other => keep >= 2,
Kin::None => false,
}
}
}
/// [`Kin`] of the view `old`, which a slot shows, and `new`.
fn kin(old: &View, new: &View) -> Kin {
if same_placed_texture(old, new) {
return Kin::Same;
}
if let (View::Placed(false, a, from), View::Placed(false, b, to)) = (old, new) {
if a[0] == 1 || b[0] == 1 || from[1] != to[1] {
return Kin::None;
}
// (Width, 64 bits, height, depth and levels, format: words 4 to 8.)
if a[0] == b[0] && a[2..13] == b[2..13] {
return Kin::Moved;
}
let (wide, high) = ([a[4], b[4]].map(u64::from), [a[6], b[6]].map(u64::from));
return if from[0] == to[0] && a[0] == b[0] && wide[0] * high[1] == wide[1] * high[0] {
Kin::Sized
} else {
Kin::Other
};
}
let dimension = |view: &View| match view {
View::Placed(false, resource, desc) if resource[0] != 1 => desc[1],
View::Shader(r, Some(desc)) if crate::resource::buffer_bytes(*r as crate::object::This).is_none() => desc[1],
_ => 0,
};
match (dimension(old), dimension(new)) {
(0, _) | (_, 0) => Kin::None,
(a, b) if a == b => Kin::Other,
_ => Kin::None,
}
}
/// Whether a slot that is written with a view of another texture goes on
/// showing the one it shows until the new one is made and its upload has run
/// (`VICTORY_KEEP_SHOWN`): 0: never, it reads as zeros, then as the neutral
/// texture; 1: one of the same kind in another place or size; 2: any of the
/// same dimension.
fn keep_shown() -> u8 {
#[cfg(feature = "diagnostics")]
if let Some(on) = crate::ab::pick("VICTORY_KEEP_SHOWN") {
return if on { 2 } else { 0 };
}
static KEEP: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
*KEEP.get_or_init(|| std::env::var("VICTORY_KEEP_SHOWN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1))
}
/// Slots that showed a texture and were written with a view of another,
/// since the start, by [`Kin`] (moved, sized, other, none), and those of
/// them that kept what they showed.
static REWRITTEN: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
fn rewritten(kin: Kin, kept: bool) {
use std::sync::atomic::Ordering::Relaxed;
let class = match kin {
Kin::Moved | Kin::Same => 0,
Kin::Sized => 1,
Kin::Other => 2,
Kin::None => 3,
};
REWRITTEN[class].fetch_add(1, Relaxed);
REWRITTEN[4].fetch_add(u64::from(kept), Relaxed);
let n: u64 = REWRITTEN[..4].iter().map(|n| n.load(Relaxed)).sum();
if n.is_multiple_of(5000) {
tracing::info!(
"slots that showed a texture and were written with another, since the start: {} of the same kind elsewhere, {} of another size, {} others, {} of another dimension; {} of them kept what they showed meanwhile (VICTORY_KEEP_SHOWN)",
REWRITTEN[0].load(Relaxed),
REWRITTEN[1].load(Relaxed),
REWRITTEN[2].load(Relaxed),
REWRITTEN[3].load(Relaxed),
REWRITTEN[4].load(Relaxed)
);
}
}
/// For `crate::popwatch`, since the start: slots made null as they were
/// written with another texture, such that kept the old one, slots given the
/// neutral texture, slots made null as their memory was another's.
#[cfg(feature = "diagnostics")]
pub(crate) fn pop_causes() -> [u64; 4] {
use std::sync::atomic::Ordering::Relaxed;
let all: u64 = REWRITTEN[..4].iter().map(|n| n.load(Relaxed)).sum();
let kept = REWRITTEN[4].load(Relaxed);
[all.saturating_sub(kept), kept, LATE[3].load(Relaxed), STALE[0].load(Relaxed)]
}
/// Whether a slot already made from its record is told so without the lock
/// (`VICTORY_QUICK_MIRROR=0`: with it, as before).
fn quick_mirror() -> bool {
@@ -4373,6 +4505,36 @@ mod tests {
assert!(!same_placed_texture(&low, &View::Shader(0, None)));
}
/// What may stand for a texture that is not there yet: one of its kind in
/// another place or size; another one only if asked; nothing a shader
/// cannot read in its place.
#[test]
fn a_slot_shows_on_what_can_stand_for_its_new_texture() {
let texture = [3, 0, 0, 0, 512, 0, 256, 0x8_0001, 98, 1, 0, 0x105, 0, 0];
let view = |resource: [u32; 14], format: u32, dimension: u32, address: u32| {
let mut desc = [0u32; 16];
(desc[0], desc[1], desc[10], desc[11]) = (format, dimension, address, 0xb);
View::Placed(false, resource, desc)
};
let old = view(texture, 98, 4, 0x1000_0000);
let mut twice = texture;
(twice[4], twice[6], twice[7]) = (1024, 512, 0x9_0001);
let mut square = texture;
square[6] = 512;
let mut buffer = texture;
buffer[0] = 1;
assert_eq!(kin(&old, &view(texture, 98, 4, 0x1000_0000)), Kin::Same);
assert_eq!(kin(&old, &view(texture, 98, 4, 0x2000_0000)), Kin::Moved);
assert_eq!(kin(&old, &view(twice, 98, 4, 0x2000_0000)), Kin::Sized);
assert_eq!(kin(&old, &view(square, 98, 4, 0x2000_0000)), Kin::Other);
assert_eq!(kin(&old, &view(twice, 83, 4, 0x2000_0000)), Kin::Other);
assert_eq!(kin(&old, &view(texture, 98, 9, 0x2000_0000)), Kin::None);
assert_eq!(kin(&old, &view(buffer, 98, 1, 0x2000_0000)), Kin::None);
for (kin, kept) in [(Kin::Same, [true; 3]), (Kin::Moved, [false, true, true]), (Kin::Sized, [false, true, true]), (Kin::Other, [false, false, true]), (Kin::None, [false; 3])] {
assert_eq!([0, 1, 2].map(|keep| kin.kept(keep)), kept, "{kin:?}");
}
}
/// A constant buffer view larger than the host takes is cut to what it
/// takes: the device, which such a view removes, stays.
#[test]
+14 -2
View File
@@ -8363,6 +8363,8 @@ impl Host {
.flatten();
#[cfg(feature = "diagnostics")]
let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) };
#[cfg(feature = "diagnostics")]
let watched = crate::popwatch::take(&self.device, list, texture);
#[cfg(not(feature = "diagnostics"))]
let _ = frame;
list.ResourceBarrier(&[
@@ -8374,13 +8376,23 @@ impl Host {
),
]);
copy.close();
match slot {
let flown = match slot {
Some(i) => {
let flown = self.execute_own(copy);
p.ahead[i].1 = flown;
flown
}
None => self.execute(&[copy]),
None => {
self.execute(&[copy]);
0
}
};
#[cfg(feature = "diagnostics")]
if let Some(taken) = watched {
crate::popwatch::sent(taken, flown, frame);
}
#[cfg(not(feature = "diagnostics"))]
let _ = flown;
#[cfg(feature = "diagnostics")]
if let Some((buffer, footprint)) = capture {
crate::capture::save_read_back(frame, &buffer, &footprint);
+2
View File
@@ -46,6 +46,8 @@ pub mod pipeline;
mod picked;
#[cfg(windows)]
mod pool;
#[cfg(all(windows, feature = "diagnostics"))]
mod popwatch;
#[cfg(windows)]
mod primitive;
pub mod query;
+344
View File
@@ -0,0 +1,344 @@
//! Diagnostics: textures that pop. `VICTORY_POP_WATCH=<from>-<to>[,<from>-<to>..]`
//! (seconds since the start): every presented frame in those times is read
//! back, made small on a thread of its own and compared with its neighbours,
//! block by block. Counted and logged:
//! - blips: blocks that one frame shows otherwise than the frames before and
//! after it, which agree (a texture black, grey or another one for a frame);
//! - steps: blocks that change from one frame to the next and stay so, while
//! most of the picture does not move.
//!
//! `VICTORY_POP_FOLDER=<folder>`: the three pictures around a frame with
//! blips (at most 200 times) are saved there, 640 wide; with
//! `VICTORY_POP_ALL=1` every frame's is.
use std::collections::VecDeque;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
use std::sync::{Mutex, OnceLock, mpsc};
use windows::Win32::Graphics::Direct3D12::*;
/// A small picture: so many pixels wide and high.
const WIDE: usize = 640;
const HIGH: usize = 360;
/// Pixels per side of a block.
const BLOCK: usize = 16;
/// A block changed: so much in the mean of its pixels' largest channel change.
const CHANGED: f32 = 10.0;
/// A block stayed.
const STAYED: f32 = 4.0;
/// `10-20,30-40` as seconds.
fn parse(text: &str) -> Vec<(f64, f64)> {
text.split(',')
.filter_map(|part| {
let (from, to) = part.trim().split_once('-')?;
Some((from.trim().parse().ok()?, to.trim().parse().ok()?))
})
.collect()
}
fn asked() -> &'static [(f64, f64)] {
static ASKED: OnceLock<Vec<(f64, f64)>> = OnceLock::new();
ASKED.get_or_init(|| std::env::var("VICTORY_POP_WATCH").map(|v| parse(&v)).unwrap_or_default())
}
/// Whether frames are watched now.
pub(crate) fn on() -> bool {
let asked = asked();
if asked.is_empty() {
return false;
}
let now = crate::host::now_ms() as f64 / 1e3;
asked.iter().any(|&(from, to)| now >= from && now < to)
}
/// A frame on its way back.
pub(crate) struct Taken {
buffer: ID3D12Resource,
footprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
}
struct Job {
frame: u64,
taken: Taken,
/// The submission that copies it.
flown: u64,
ms: u64,
causes: [u64; 4],
phase: Option<bool>,
}
/// Read-back buffers not in use.
static FREE: Mutex<Vec<Taken>> = Mutex::new(Vec::new());
/// Frames on their way.
static WAITING: AtomicU64 = AtomicU64::new(0);
/// Records the read-back of `texture` (in the copy-source state).
pub(crate) fn take(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, texture: &ID3D12Resource) -> Option<Taken> {
if !on() || WAITING.load(Relaxed) > 8 {
return None;
}
let free = FREE.lock().unwrap_or_else(|e| e.into_inner()).pop();
let Some(taken) = free else {
let (buffer, footprint) = crate::capture::read_back(device, list, texture)?;
return Some(Taken { buffer, footprint });
};
let to = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: a borrowed pointer the location never releases.
pResource: unsafe { std::mem::transmute_copy(&taken.buffer) },
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: taken.footprint },
};
let from = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: as above.
pResource: unsafe { std::mem::transmute_copy(texture) },
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
};
// SAFETY: an open list, live resources.
unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
Some(taken)
}
/// The list with `taken` went to the card as submission `flown` (0: it has
/// run). `frame`: the frame it shows.
pub(crate) fn sent(taken: Taken, flown: u64, frame: u64) {
static THREAD: OnceLock<Option<mpsc::Sender<Job>>> = OnceLock::new();
let Some(to) = THREAD.get_or_init(|| {
let (to, from) = mpsc::channel::<Job>();
std::thread::Builder::new().name("pop watch".into()).spawn(move || watch(&from)).ok().map(|_| to)
}) else {
return;
};
WAITING.fetch_add(1, Relaxed);
let job = Job {
frame,
taken,
flown,
ms: crate::host::now_ms(),
causes: crate::descriptor::host::pop_causes(),
phase: crate::ab::pick("VICTORY_KEEP_SHOWN"),
};
let _ = to.send(job);
}
/// What was seen of the frames so far.
#[derive(Default)]
struct Seen {
frames: u64,
blips: u64,
blip_frames: u64,
steps: u64,
still: u64,
}
struct Picture {
frame: u64,
ms: u64,
causes: [u64; 4],
phase: Option<bool>,
rgb: Vec<u8>,
/// Per block: how much it differs from the frame before.
changed: Vec<f32>,
saved: bool,
}
/// Per block, the mean of the pixels' largest channel change.
fn differ(a: &[u8], b: &[u8]) -> Vec<f32> {
let (across, down) = (WIDE / BLOCK, HIGH / BLOCK);
let mut out = vec![0.0; across * down];
for (n, sum) in out.iter_mut().enumerate() {
let (bx, by) = (n % across * BLOCK, n / across * BLOCK);
let mut total = 0u32;
for y in by..by + BLOCK {
let at = (y * WIDE + bx) * 3;
let (ra, rb) = (&a[at..at + BLOCK * 3], &b[at..at + BLOCK * 3]);
total += ra
.chunks_exact(3)
.zip(rb.chunks_exact(3))
.map(|(p, q)| p.iter().zip(q).map(|(x, y)| u32::from(x.abs_diff(*y))).max().unwrap_or(0))
.sum::<u32>();
}
*sum = total as f32 / (BLOCK * BLOCK) as f32;
}
out
}
/// The blips of `now` between `before` and `after`, and its steps (the frame
/// before `before` had `quiet` changes): numbers of blocks. `None` for the
/// steps if the picture moves.
fn judge(before: &[u8], now: &[u8], after: &[u8], quiet: &[f32]) -> (usize, Option<usize>) {
let (one, two, across) = (differ(before, now), differ(now, after), differ(before, after));
let blips = (0..one.len())
.filter(|&n| one[n] > CHANGED && two[n] > CHANGED && across[n] < STAYED && across[n] * 3.0 < one[n])
.count();
let still = one.iter().filter(|&&d| d < 3.0).count() * 10 >= one.len() * 7;
let steps = still.then(|| {
(0..one.len()).filter(|&n| one[n] > CHANGED && two[n] < STAYED && quiet.get(n).is_some_and(|&d| d < STAYED)).count()
});
(blips, steps)
}
/// `width * height` 8-bit RGBA (or BGRA) pixels made small.
fn small(rows: &[u8], width: usize, height: usize, pitch: usize, bgra: bool) -> Vec<u8> {
let mut out = Vec::with_capacity(WIDE * HIGH * 3);
for y in 0..HIGH {
for x in 0..WIDE {
let mut sum = [0u32; 3];
for sy in 0..3 {
for sx in 0..3 {
let px = ((x * 3 + sx) * 2 + 1) * width / (WIDE * 6);
let py = ((y * 3 + sy) * 2 + 1) * height / (HIGH * 6);
let p = &rows[py.min(height - 1) * pitch + px.min(width - 1) * 4..][..3];
for (s, v) in sum.iter_mut().zip(p) {
*s += u32::from(*v);
}
}
}
let c = sum.map(|s| (s / 9) as u8);
out.extend(if bgra { [c[2], c[1], c[0]] } else { c });
}
}
out
}
fn folder() -> Option<&'static PathBuf> {
static FOLDER: OnceLock<Option<PathBuf>> = OnceLock::new();
FOLDER
.get_or_init(|| {
let folder = PathBuf::from(std::env::var_os("VICTORY_POP_FOLDER")?);
std::fs::create_dir_all(&folder).ok()?;
Some(folder)
})
.as_ref()
}
fn save(p: &mut Picture) {
if p.saved {
return;
}
p.saved = true;
if let Some(folder) = folder() {
let png = crate::capture::png(WIDE as u32, HIGH as u32, &p.rgb);
let _ = std::fs::write(folder.join(format!("{:07}-f{}.png", p.ms, p.frame)), png);
}
}
fn watch(from: &mpsc::Receiver<Job>) {
let all = std::env::var_os("VICTORY_POP_ALL").is_some_and(|v| v == "1");
let mut last: VecDeque<Picture> = VecDeque::new();
let mut seen: [Seen; 2] = Default::default();
let mut told = crate::host::now_ms();
let mut sets = 0;
while let Ok(job) = from.recv() {
while crate::host::submissions().1 < job.flown {
std::thread::sleep(std::time::Duration::from_millis(1));
}
let f = job.taken.footprint.Footprint;
let (rgba, bgra) = (matches!(f.Format.0, 27..=29), matches!(f.Format.0, 87 | 90 | 91));
let mut data = std::ptr::null_mut();
// SAFETY: the copy has run; the mapping spans the footprint's rows.
let rgb = unsafe {
if !(rgba || bgra) || job.taken.buffer.Map(0, None, Some(&mut data)).is_err() {
WAITING.fetch_sub(1, Relaxed);
continue;
}
let rows = std::slice::from_raw_parts(data.cast::<u8>(), f.RowPitch as usize * f.Height as usize);
let rgb = small(rows, f.Width as usize, f.Height as usize, f.RowPitch as usize, bgra);
job.taken.buffer.Unmap(0, None);
rgb
};
FREE.lock().unwrap_or_else(|e| e.into_inner()).push(job.taken);
WAITING.fetch_sub(1, Relaxed);
// Frames that follow each other only.
if last.back().is_some_and(|p| p.frame + 1 != job.frame) {
last.clear();
}
let changed = last.back().map(|p| differ(&p.rgb, &rgb)).unwrap_or_default();
let (frame, ms, causes, phase) = (job.frame, job.ms, job.causes, job.phase);
last.push_back(Picture { frame, ms, causes, phase, rgb, changed, saved: false });
if all && let Some(p) = last.back_mut() {
save(p);
}
if last.len() > 4 {
last.pop_front();
}
if let [first, before, now, after] = last.make_contiguous() {
let (blips, steps) = judge(&before.rgb, &now.rgb, &after.rgb, &before.changed);
let side = &mut seen[usize::from(now.phase.unwrap_or(false))];
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 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:?}",
now.frame,
now.ms as f64 / 1e3
);
}
if (blips > 0 || steps.is_some_and(|s| s > 2)) && sets < 200 {
sets += 1;
save(before);
save(now);
save(after);
}
}
if crate::host::now_ms().saturating_sub(told) > 5000 {
told = crate::host::now_ms();
for (n, s) in seen.iter().enumerate().filter(|(_, s)| s.frames > 0) {
tracing::info!(
"pop watch, since the start, 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,
s.frames,
s.blip_frames,
s.blips,
s.still,
s.steps
);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn picture(color: u8) -> Vec<u8> {
vec![color; WIDE * HIGH * 3]
}
fn patch(p: &mut [u8], bx: usize, by: usize, color: u8) {
for y in by * BLOCK..(by + 1) * BLOCK {
let at = (y * WIDE + bx * BLOCK) * 3;
p[at..at + BLOCK * 3].fill(color);
}
}
#[test]
fn one_frame_otherwise_is_a_blip_and_a_lasting_change_a_step() {
let (a, mut b) = (picture(100), picture(100));
patch(&mut b, 3, 4, 0);
let quiet = vec![0.0; (WIDE / BLOCK) * (HIGH / BLOCK)];
assert_eq!(judge(&a, &b, &a, &quiet), (1, Some(0)));
assert_eq!(judge(&a, &b, &b, &quiet), (0, Some(1)));
assert_eq!(judge(&a, &a, &a, &quiet), (0, Some(0)));
// All of it changes: a cut, no step.
assert_eq!(judge(&a, &picture(0), &picture(0), &quiet), (0, None));
// What moved just before is no step either.
assert_eq!(judge(&a, &b, &b, &vec![9.0; quiet.len()]), (0, Some(0)));
}
#[test]
fn times_are_read_and_pictures_made_small() {
assert_eq!(parse("10-20, 30.5-40"), vec![(10.0, 20.0), (30.5, 40.0)]);
assert!(parse("x").is_empty());
let rows: Vec<u8> = [1u8, 2, 3, 255].repeat(1280 * 720);
let out = small(&rows, 1280, 720, 1280 * 4, true);
assert_eq!((out.len(), &out[..3]), (WIDE * HIGH * 3, &[3u8, 2, 1][..]));
}
}