Record and replay a frame's D3D12 work (diagnostics builds)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
eca1d231e3
commit
59a556e4b0
15 files changed
+8270
-7
No files matched your search
@@ -178,6 +178,27 @@ fn save_as(name: &str, width: u32, height: u32, pitch: usize, bgra: bool, rows:
|
||||
}
|
||||
}
|
||||
}
|
||||
let png = encode(w, h, &raw);
|
||||
let path = folder.join(format!("{name}.png"));
|
||||
match std::fs::write(&path, png) {
|
||||
Ok(()) => tracing::info!(path = %path.display(), "frame saved"),
|
||||
Err(e) => tracing::warn!(error = %e, path = %path.display(), "frame not saved"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A PNG of `width * height` pixels of 8-bit RGB.
|
||||
pub(crate) fn png(width: u32, height: u32, rgb: &[u8]) -> Vec<u8> {
|
||||
let row = width as usize * 3;
|
||||
let mut raw = Vec::with_capacity((row + 1) * height as usize);
|
||||
for line in rgb.chunks_exact(row.max(1)) {
|
||||
raw.push(0);
|
||||
raw.extend_from_slice(line);
|
||||
}
|
||||
encode(width, height, &raw)
|
||||
}
|
||||
|
||||
/// A PNG of rows of RGB, each behind its filter byte.
|
||||
fn encode(w: u32, h: u32, raw: &[u8]) -> Vec<u8> {
|
||||
let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
|
||||
let mut header = Vec::new();
|
||||
header.extend(w.to_be_bytes());
|
||||
@@ -185,15 +206,11 @@ fn save_as(name: &str, width: u32, height: u32, pitch: usize, bgra: bool, rows:
|
||||
header.extend([8, 2, 0, 0, 0]); // 8-bit RGB
|
||||
chunk(&mut png, b"IHDR", &header);
|
||||
let mut compressed = vec![0u8; zlib_rs::compress_bound(raw.len())];
|
||||
let (idat, rc) = zlib_rs::compress_slice(&mut compressed, &raw, zlib_rs::DeflateConfig::new(3));
|
||||
let (idat, rc) = zlib_rs::compress_slice(&mut compressed, raw, zlib_rs::DeflateConfig::new(3));
|
||||
debug_assert_eq!(rc, zlib_rs::ReturnCode::Ok);
|
||||
chunk(&mut png, b"IDAT", idat);
|
||||
chunk(&mut png, b"IEND", &[]);
|
||||
let path = folder.join(format!("{name}.png"));
|
||||
match std::fs::write(&path, png) {
|
||||
Ok(()) => tracing::info!(path = %path.display(), "frame saved"),
|
||||
Err(e) => tracing::warn!(error = %e, path = %path.display(), "frame not saved"),
|
||||
}
|
||||
png
|
||||
}
|
||||
|
||||
fn chunk(png: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
|
||||
|
||||
@@ -602,6 +602,9 @@ fn create() -> windows::core::Result<Host> {
|
||||
D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
|
||||
}
|
||||
let device = device.ok_or_else(windows::core::Error::empty)?;
|
||||
// Before anything is made with it (`VICTORY_RECORD`).
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::replay::record::from_env(&device);
|
||||
// `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the
|
||||
// driver compiling shaders again on the "D3D Background Thread"s,
|
||||
// for minutes after pipelines were made or loaded) is switched off.
|
||||
@@ -1295,8 +1298,14 @@ fn timing() -> bool {
|
||||
}
|
||||
|
||||
/// Names a host object for the device-removed report, which names the
|
||||
/// allocations a page fault hit (only with device-removed data on).
|
||||
/// allocations a page fault hit (only with device-removed data on), or for
|
||||
/// the frame recorder (`VICTORY_RECORD`).
|
||||
pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if crate::replay::record::on() {
|
||||
crate::replay::record::name(object, &text());
|
||||
return;
|
||||
}
|
||||
if dred_on()
|
||||
&& let Ok(object) = object.cast::<ID3D12Object>()
|
||||
{
|
||||
@@ -3126,6 +3135,8 @@ impl Host {
|
||||
},
|
||||
..Default::default()
|
||||
})?;
|
||||
#[cfg(feature = "diagnostics")]
|
||||
name(&pso, || crate::replay::play::COMPARE.into());
|
||||
Ok(CardWork {
|
||||
sync: vec![list()?],
|
||||
check: vec![list()?],
|
||||
@@ -6353,6 +6364,8 @@ impl Host {
|
||||
if let Some((buffer, footprint)) = capture {
|
||||
crate::capture::save_read_back(frame, &buffer, &footprint);
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::replay::record::present(texture, state);
|
||||
let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
|
||||
p.meter.frame(p.hwnd);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
|
||||
@@ -279,6 +279,8 @@ fn make_from(device: &ID3D12Device, source: &str) -> windows::core::Result<Clamp
|
||||
},
|
||||
..Default::default()
|
||||
})?;
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::host::name(&pso, || crate::replay::play::CLAMP.into());
|
||||
Ok(Clamp { root, pso })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,6 +42,8 @@ mod pool;
|
||||
mod primitive;
|
||||
pub mod query;
|
||||
pub mod queue;
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
pub mod replay;
|
||||
pub mod resource;
|
||||
pub mod root;
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
//! Experiments on a list's commands: the same list with something left out
|
||||
//! or put otherwise.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use super::wire::{ALL, Barrier, Cmd, NONE, Va};
|
||||
|
||||
/// The buffer the clamped arguments of all clamp passes lie in, in lists
|
||||
/// edited by [`clamps`].
|
||||
pub const RESULTS: u32 = u32::MAX - 1;
|
||||
|
||||
const INDIRECT_ARGUMENT: i32 = 0x200;
|
||||
const UNORDERED_ACCESS: i32 = 0x8;
|
||||
const COPY_SOURCE: i32 = 0x800;
|
||||
|
||||
/// Drops what runs a pipeline of `psos`; how many commands that were.
|
||||
pub fn skip_pipelines(cmds: Vec<Cmd>, psos: &HashSet<u32>) -> (Vec<Cmd>, u32) {
|
||||
let mut bound = NONE;
|
||||
let mut dropped = 0;
|
||||
let out = cmds
|
||||
.into_iter()
|
||||
.filter(|c| {
|
||||
if let Cmd::Pipeline { pso } = c {
|
||||
bound = *pso;
|
||||
}
|
||||
let drop = c.runs_shaders() && psos.contains(&bound);
|
||||
dropped += u32::from(drop);
|
||||
!drop
|
||||
})
|
||||
.collect();
|
||||
(out, dropped)
|
||||
}
|
||||
|
||||
/// Drops unordered-access barriers; how many.
|
||||
pub fn no_uav_barriers(cmds: Vec<Cmd>) -> (Vec<Cmd>, u32) {
|
||||
let mut dropped = 0;
|
||||
let out = cmds
|
||||
.into_iter()
|
||||
.filter_map(|c| match c {
|
||||
Cmd::Barriers { mut all } => {
|
||||
let n = all.len();
|
||||
all.retain(|b| !matches!(b, Barrier::Uav { .. }));
|
||||
dropped += (n - all.len()) as u32;
|
||||
(!all.is_empty()).then_some(Cmd::Barriers { all })
|
||||
}
|
||||
c => Some(c),
|
||||
})
|
||||
.collect();
|
||||
(out, dropped)
|
||||
}
|
||||
|
||||
/// Barriers only: what a list left out still does to the states of
|
||||
/// resources.
|
||||
pub fn barriers_only(cmds: Vec<Cmd>) -> Vec<Cmd> {
|
||||
cmds.into_iter().filter(|c| matches!(c, Cmd::Barriers { .. })).collect()
|
||||
}
|
||||
|
||||
/// Joins the barrier calls with no work between them into one; how many
|
||||
/// calls that saved.
|
||||
pub fn merge_barriers(cmds: Vec<Cmd>) -> (Vec<Cmd>, u32) {
|
||||
let mut out: Vec<Cmd> = Vec::with_capacity(cmds.len());
|
||||
let mut open: Option<usize> = None;
|
||||
let mut saved = 0;
|
||||
for c in cmds {
|
||||
match c {
|
||||
Cmd::Barriers { all } => {
|
||||
if let Some(i) = open
|
||||
&& let Cmd::Barriers { all: have } = &mut out[i]
|
||||
{
|
||||
for b in all {
|
||||
join(have, b);
|
||||
}
|
||||
saved += 1;
|
||||
} else {
|
||||
open = Some(out.len());
|
||||
let mut have = Vec::new();
|
||||
for b in all {
|
||||
join(&mut have, b);
|
||||
}
|
||||
out.push(Cmd::Barriers { all: have });
|
||||
}
|
||||
}
|
||||
c => {
|
||||
if c.works() || matches!(c, Cmd::BeginQuery { .. } | Cmd::EndQuery { .. }) {
|
||||
open = None;
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.retain(|c| !matches!(c, Cmd::Barriers { all } if all.is_empty()));
|
||||
(out, saved)
|
||||
}
|
||||
|
||||
/// Adds a barrier to a call's.
|
||||
fn join(have: &mut Vec<Barrier>, b: Barrier) {
|
||||
match b {
|
||||
Barrier::Uav { res, .. } => {
|
||||
let covered = have.iter().any(|h| matches!(h, Barrier::Uav { res: r, .. } if *r == res || *r == NONE));
|
||||
if covered {
|
||||
return;
|
||||
}
|
||||
if res == NONE {
|
||||
have.retain(|h| !matches!(h, Barrier::Uav { .. }));
|
||||
}
|
||||
have.push(b);
|
||||
}
|
||||
Barrier::Transition { flags: 0, res, sub, before, after } => {
|
||||
// The last one of this resource, if it is of the same part of it.
|
||||
let last = have.iter().rposition(|h| matches!(h, Barrier::Transition { res: r, .. } if *r == res));
|
||||
if let Some(i) = last
|
||||
&& let Barrier::Transition { flags: 0, sub: s, before: first, after: until, .. } = have[i]
|
||||
&& s == sub
|
||||
&& until == before
|
||||
{
|
||||
if first != after {
|
||||
have[i] = Barrier::Transition { flags: 0, res, sub, before: first, after };
|
||||
} else {
|
||||
have.remove(i);
|
||||
if after == UNORDERED_ACCESS {
|
||||
// Still a wait for the writes before.
|
||||
join(have, Barrier::Uav { flags: 0, res });
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
have.push(b);
|
||||
}
|
||||
b => have.push(b),
|
||||
}
|
||||
}
|
||||
|
||||
/// A clamp pass of ours found in a list.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Clamp {
|
||||
/// The command that dispatches it.
|
||||
pub at: usize,
|
||||
/// The scratch buffer it writes the arguments to, from its start.
|
||||
pub scratch: u32,
|
||||
pub bytes: u64,
|
||||
/// Where its arguments are in [`RESULTS`].
|
||||
pub result: u64,
|
||||
}
|
||||
|
||||
/// The clamp passes of a list (`psos`: the clamp's pipelines), given places
|
||||
/// in the results from `next` on.
|
||||
pub fn find_clamps(cmds: &[Cmd], psos: &HashSet<u32>, next: &mut u64) -> Vec<Clamp> {
|
||||
let (mut bound, mut constants, mut to) = (NONE, [0u32; 6], None);
|
||||
let mut found = Vec::new();
|
||||
for (at, c) in cmds.iter().enumerate() {
|
||||
match c {
|
||||
Cmd::Pipeline { pso } => bound = *pso,
|
||||
Cmd::Constants { graphics: false, param: 0, offset, values } => {
|
||||
for (i, v) in values.iter().enumerate() {
|
||||
if let Some(c) = constants.get_mut(*offset as usize + i) {
|
||||
*c = *v;
|
||||
}
|
||||
}
|
||||
}
|
||||
// The clamp's parameters: constants (kind, stride, records,
|
||||
// ...), arguments, count, then where it writes.
|
||||
Cmd::RootView { graphics: false, param: 3, va: Va::At { res, offset: 0 }, .. } => to = Some(*res),
|
||||
Cmd::Dispatch { .. } if psos.contains(&bound) => {
|
||||
if let Some(scratch) = to {
|
||||
let bytes = u64::from(constants[1]) * u64::from(constants[2]);
|
||||
found.push(Clamp { at, scratch, bytes, result: *next });
|
||||
*next += bytes.next_multiple_of(256);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The list with a copy of what each clamp wrote into the results.
|
||||
pub fn keep_clamped(cmds: Vec<Cmd>, clamps: &[Clamp]) -> Vec<Cmd> {
|
||||
let mut out = Vec::with_capacity(cmds.len() + 3 * clamps.len());
|
||||
let mut open: Option<Clamp> = None;
|
||||
for (at, c) in cmds.into_iter().enumerate() {
|
||||
if let Some(clamp) = clamps.iter().find(|c| c.at == at) {
|
||||
open = Some(*clamp);
|
||||
}
|
||||
let readable = |b: &Barrier, scratch: u32| matches!(b, Barrier::Transition { res, after: INDIRECT_ARGUMENT, .. } if *res == scratch);
|
||||
let done = match (&c, open) {
|
||||
(Cmd::Barriers { all }, Some(clamp)) => all.iter().any(|b| readable(b, clamp.scratch)),
|
||||
_ => false,
|
||||
};
|
||||
out.push(c);
|
||||
if done && let Some(clamp) = open.take() {
|
||||
let moved = |before, after| Cmd::Barriers {
|
||||
all: vec![Barrier::Transition { flags: 0, res: clamp.scratch, sub: ALL, before, after }],
|
||||
};
|
||||
out.push(moved(INDIRECT_ARGUMENT, COPY_SOURCE));
|
||||
out.push(Cmd::CopyBuffer { dst: RESULTS, dst_at: clamp.result, src: clamp.scratch, src_at: 0, len: clamp.bytes });
|
||||
out.push(moved(COPY_SOURCE, INDIRECT_ARGUMENT));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The list without its clamp passes and the barriers of their scratch
|
||||
/// buffers; what they bounded is read from the results instead.
|
||||
pub fn skip_clamps(cmds: Vec<Cmd>, clamps: &[Clamp]) -> Vec<Cmd> {
|
||||
let scratches: HashSet<u32> = clamps.iter().map(|c| c.scratch).collect();
|
||||
let by_at: HashMap<usize, &Clamp> = clamps.iter().map(|c| (c.at, c)).collect();
|
||||
let mut last: HashMap<u32, u64> = HashMap::new();
|
||||
let mut out = Vec::with_capacity(cmds.len());
|
||||
for (at, c) in cmds.into_iter().enumerate() {
|
||||
if let Some(clamp) = by_at.get(&at) {
|
||||
last.insert(clamp.scratch, clamp.result);
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
Cmd::Barriers { mut all } => {
|
||||
let of_scratch = |b: &Barrier| matches!(b, Barrier::Transition { res, .. } if scratches.contains(res));
|
||||
if all.iter().any(of_scratch) {
|
||||
// The waits made with the scratch buffer's moves are the
|
||||
// clamp's too.
|
||||
all.retain(|b| !of_scratch(b) && !matches!(b, Barrier::Uav { res: NONE, .. }));
|
||||
}
|
||||
if !all.is_empty() {
|
||||
out.push(Cmd::Barriers { all });
|
||||
}
|
||||
}
|
||||
Cmd::Indirect { signature, most, args, at, count, count_at } if last.contains_key(&args) => {
|
||||
let result = last.get(&args).copied().unwrap_or(0);
|
||||
out.push(Cmd::Indirect { signature, most, args: RESULTS, at: result + at, count, count_at });
|
||||
}
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pso(pso: u32) -> Cmd {
|
||||
Cmd::Pipeline { pso }
|
||||
}
|
||||
fn go() -> Cmd {
|
||||
Cmd::Dispatch { groups: [1, 1, 1] }
|
||||
}
|
||||
fn uav(res: u32) -> Barrier {
|
||||
Barrier::Uav { flags: 0, res }
|
||||
}
|
||||
fn moved(res: u32, before: i32, after: i32) -> Barrier {
|
||||
Barrier::Transition { flags: 0, res, sub: ALL, before, after }
|
||||
}
|
||||
fn barriers(all: &[Barrier]) -> Cmd {
|
||||
Cmd::Barriers { all: all.to_vec() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pipelines_are_skipped() {
|
||||
let list = vec![pso(1), go(), pso(2), go(), go(), Cmd::CopyResource { dst: 1, src: 2 }, pso(1), go()];
|
||||
let (out, n) = skip_pipelines(list.clone(), &HashSet::from([2]));
|
||||
assert_eq!(n, 2);
|
||||
assert_eq!(out, vec![pso(1), go(), pso(2), Cmd::CopyResource { dst: 1, src: 2 }, pso(1), go()]);
|
||||
assert_eq!(skip_pipelines(list.clone(), &HashSet::new()), (list, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uav_barriers_are_dropped() {
|
||||
let list = vec![barriers(&[uav(0)]), go(), barriers(&[uav(1), moved(1, 8, 4)])];
|
||||
assert_eq!(no_uav_barriers(list.clone()), (vec![go(), barriers(&[moved(1, 8, 4)])], 2));
|
||||
assert_eq!(barriers_only(list.clone()), vec![list[0].clone(), list[2].clone()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn barriers_are_merged() {
|
||||
let list = vec![
|
||||
barriers(&[moved(1, 0, 8)]),
|
||||
pso(1),
|
||||
barriers(&[uav(2), moved(1, 8, 64)]),
|
||||
barriers(&[uav(0), uav(3)]),
|
||||
go(),
|
||||
// There and back again: nothing is left but the wait.
|
||||
barriers(&[moved(1, 8, 64)]),
|
||||
barriers(&[moved(1, 64, 8)]),
|
||||
go(),
|
||||
barriers(&[moved(4, 4, 128)]),
|
||||
barriers(&[moved(4, 128, 4)]),
|
||||
];
|
||||
let (out, saved) = merge_barriers(list);
|
||||
assert_eq!(saved, 4);
|
||||
assert_eq!(out, vec![barriers(&[moved(1, 0, 64), uav(0)]), pso(1), go(), barriers(&[uav(1)]), go()]);
|
||||
// Parts of a resource are not mixed up.
|
||||
let part = |sub, before, after| Barrier::Transition { flags: 0, res: 1, sub, before, after };
|
||||
let list = vec![barriers(&[part(0, 4, 8)]), barriers(&[part(1, 4, 8)]), barriers(&[part(ALL, 8, 64)])];
|
||||
assert_eq!(merge_barriers(list).0, vec![barriers(&[part(0, 4, 8), part(1, 4, 8), part(ALL, 8, 64)])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clamps_are_found_kept_and_skipped() {
|
||||
let clamp = |scratch, stride, records| {
|
||||
vec![
|
||||
barriers(&[uav(0), moved(scratch, 0, 8)]),
|
||||
pso(9),
|
||||
Cmd::Constants { graphics: false, param: 0, offset: 0, values: vec![10, stride, records, 0, 0, 0] },
|
||||
Cmd::RootView { graphics: false, kind: 3, param: 3, va: Va::At { res: scratch, offset: 0 } },
|
||||
go(),
|
||||
barriers(&[uav(0), moved(scratch, 8, 0x200)]),
|
||||
]
|
||||
};
|
||||
let run = |args, at| Cmd::Indirect { signature: 1, most: 1, args, at, count: 0, count_at: 0 };
|
||||
let mut list = clamp(5, 12, 2);
|
||||
list.extend([pso(1), run(5, 12), run(5, 0), run(6, 0)]);
|
||||
list.extend(clamp(5, 12, 100));
|
||||
list.extend([pso(1), run(5, 24), barriers(&[moved(5, 0x200, 0)])]);
|
||||
let mut next = 0;
|
||||
let found = find_clamps(&list, &HashSet::from([9]), &mut next);
|
||||
assert_eq!(found.iter().map(|c| (c.scratch, c.bytes, c.result)).collect::<Vec<_>>(), [(5, 24, 0), (5, 1200, 256)]);
|
||||
assert_eq!(next, 256 + 1280);
|
||||
let kept = keep_clamped(list.clone(), &found);
|
||||
assert_eq!(kept.len(), list.len() + 6);
|
||||
assert_eq!(kept[7], Cmd::CopyBuffer { dst: RESULTS, dst_at: 0, src: 5, src_at: 0, len: 24 });
|
||||
assert_eq!(kept.iter().filter(|c| matches!(c, Cmd::CopyBuffer { .. })).count(), 2);
|
||||
let skipped = skip_clamps(list, &found);
|
||||
assert!(!skipped.iter().any(|c| matches!(c, Cmd::Dispatch { .. } | Cmd::Barriers { .. })));
|
||||
let runs: Vec<(u32, u64)> =
|
||||
skipped.iter().filter_map(|c| if let Cmd::Indirect { args, at, .. } = c { Some((*args, *at)) } else { None }).collect();
|
||||
assert_eq!(runs, [(RESULTS, 12), (RESULTS, 0), (6, 0), (RESULTS, 256 + 24)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
//! Small D3D12 helpers the recorder and the replayer share.
|
||||
|
||||
use windows::Win32::Foundation::HANDLE;
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
use windows::Win32::Graphics::Dxgi::Common::*;
|
||||
use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
|
||||
use windows::core::{Interface, Result};
|
||||
|
||||
use super::wire;
|
||||
|
||||
/// Lists of our own on a queue, with a fence.
|
||||
pub(super) struct Worker {
|
||||
pub(super) device: ID3D12Device,
|
||||
pub(super) queue: ID3D12CommandQueue,
|
||||
fence: ID3D12Fence,
|
||||
event: HANDLE,
|
||||
value: u64,
|
||||
/// Allocator, list, and the fence value its last run ends with.
|
||||
lists: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList, u64)>,
|
||||
}
|
||||
|
||||
// SAFETY: D3D12 objects are free-threaded; a worker is used by one thread
|
||||
// at a time (`&mut self`).
|
||||
unsafe impl Send for Worker {}
|
||||
|
||||
impl Worker {
|
||||
pub(super) fn new(device: &ID3D12Device, queue: &ID3D12CommandQueue) -> Result<Worker> {
|
||||
// SAFETY: plain object creation.
|
||||
unsafe {
|
||||
Ok(Worker {
|
||||
device: device.clone(),
|
||||
queue: queue.clone(),
|
||||
fence: device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?,
|
||||
event: CreateEventW(None, false, false, None)?,
|
||||
value: 0,
|
||||
lists: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Records a list and sends it; the value [`Worker::wait`] takes.
|
||||
pub(super) fn send(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) -> Result<u64> {
|
||||
// SAFETY: lists and allocators of ours whose last run has finished.
|
||||
unsafe {
|
||||
let done = self.fence.GetCompletedValue();
|
||||
let i = match self.lists.iter().position(|l| l.2 <= done) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
|
||||
let list: ID3D12GraphicsCommandList =
|
||||
self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
|
||||
list.Close()?;
|
||||
self.lists.push((allocator, list, 0));
|
||||
self.lists.len() - 1
|
||||
}
|
||||
};
|
||||
let (allocator, list, last) = &mut self.lists[i];
|
||||
allocator.Reset()?;
|
||||
list.Reset(&*allocator, None)?;
|
||||
record(list);
|
||||
list.Close()?;
|
||||
self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
|
||||
self.value += 1;
|
||||
*last = self.value;
|
||||
self.queue.Signal(&self.fence, self.value)?;
|
||||
}
|
||||
Ok(self.value)
|
||||
}
|
||||
|
||||
/// Everything sent to the queue so far has run.
|
||||
pub(super) fn idle(&mut self) -> Result<()> {
|
||||
self.value += 1;
|
||||
// SAFETY: our queue and fence.
|
||||
unsafe { self.queue.Signal(&self.fence, self.value)? };
|
||||
self.wait(self.value)
|
||||
}
|
||||
|
||||
pub(super) fn wait(&self, value: u64) -> Result<()> {
|
||||
// SAFETY: our fence and event.
|
||||
unsafe {
|
||||
if self.fence.GetCompletedValue() < value {
|
||||
self.fence.SetEventOnCompletion(value, self.event)?;
|
||||
WaitForSingleObject(self.event, INFINITE);
|
||||
}
|
||||
self.device.GetDeviceRemovedReason()
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends and waits.
|
||||
pub(super) fn run(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) -> Result<()> {
|
||||
let value = self.send(record)?;
|
||||
self.wait(value)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC {
|
||||
D3D12_RESOURCE_DESC {
|
||||
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
|
||||
Width: size.max(1),
|
||||
Height: 1,
|
||||
DepthOrArraySize: 1,
|
||||
MipLevels: 1,
|
||||
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
|
||||
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
|
||||
Flags: flags,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A buffer of ours; heap types that are mapped come with their mapping.
|
||||
pub(super) fn buffer(
|
||||
device: &ID3D12Device,
|
||||
kind: D3D12_HEAP_TYPE,
|
||||
size: u64,
|
||||
flags: D3D12_RESOURCE_FLAGS,
|
||||
) -> Result<(ID3D12Resource, *mut u8)> {
|
||||
let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() };
|
||||
let state = match kind {
|
||||
D3D12_HEAP_TYPE_UPLOAD => D3D12_RESOURCE_STATE_GENERIC_READ,
|
||||
D3D12_HEAP_TYPE_READBACK => D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
_ => D3D12_RESOURCE_STATE_COMMON,
|
||||
};
|
||||
let mut made: Option<ID3D12Resource> = None;
|
||||
let mut data = std::ptr::null_mut();
|
||||
// SAFETY: plain creation and mapping.
|
||||
unsafe {
|
||||
device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(size, flags), state, None, &mut made)?;
|
||||
let made = made.ok_or_else(windows::core::Error::empty)?;
|
||||
if kind == D3D12_HEAP_TYPE_UPLOAD || kind == D3D12_HEAP_TYPE_READBACK {
|
||||
made.Map(0, None, Some(&mut data))?;
|
||||
}
|
||||
Ok((made, data.cast()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Planes of a format (depth and stencil, or a video format's).
|
||||
pub(super) fn planes(format: i32) -> u32 {
|
||||
match format {
|
||||
19..=22 | 44..=47 | 103..=106 => 2,
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Subresources of a texture (1 for a buffer).
|
||||
pub(super) fn subresources(d: &wire::Desc) -> u32 {
|
||||
if d.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 {
|
||||
return 1;
|
||||
}
|
||||
let layers = if d.dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D.0 { 1 } else { u32::from(d.depth) };
|
||||
u32::from(d.mips.max(1)) * layers.max(1) * planes(d.format)
|
||||
}
|
||||
|
||||
/// The layout of `count` subresources from `first` in a buffer, and its
|
||||
/// size.
|
||||
pub(super) fn footprints(
|
||||
device: &ID3D12Device,
|
||||
desc: &D3D12_RESOURCE_DESC,
|
||||
first: u32,
|
||||
count: u32,
|
||||
) -> (Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>, u64) {
|
||||
let mut all = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize];
|
||||
let mut total = 0;
|
||||
// SAFETY: outputs for `count` subresources.
|
||||
unsafe { device.GetCopyableFootprints(desc, first, count, 0, Some(all.as_mut_ptr()), None, None, Some(&mut total)) };
|
||||
(all, total)
|
||||
}
|
||||
|
||||
/// A location naming a subresource; no reference is taken.
|
||||
pub(super) fn sub_location(res: &ID3D12Resource, sub: u32) -> D3D12_TEXTURE_COPY_LOCATION {
|
||||
D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: a borrowed pointer the location never releases.
|
||||
pResource: unsafe { std::mem::transmute_copy(res) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub },
|
||||
}
|
||||
}
|
||||
|
||||
/// A location naming bytes of a buffer; no reference is taken.
|
||||
pub(super) fn placed_location(res: &ID3D12Resource, f: D3D12_PLACED_SUBRESOURCE_FOOTPRINT) -> D3D12_TEXTURE_COPY_LOCATION {
|
||||
D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: as above.
|
||||
pResource: unsafe { std::mem::transmute_copy(res) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: f },
|
||||
}
|
||||
}
|
||||
|
||||
/// A transition; no reference is taken.
|
||||
pub(super) fn transition(res: &ID3D12Resource, sub: u32, before: u32, after: u32) -> D3D12_RESOURCE_BARRIER {
|
||||
D3D12_RESOURCE_BARRIER {
|
||||
Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
|
||||
Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
|
||||
Anonymous: D3D12_RESOURCE_BARRIER_0 {
|
||||
Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
|
||||
// SAFETY: as above.
|
||||
pResource: unsafe { std::mem::transmute_copy(res) },
|
||||
Subresource: sub,
|
||||
StateBefore: D3D12_RESOURCE_STATES(before as i32),
|
||||
StateAfter: D3D12_RESOURCE_STATES(after as i32),
|
||||
}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The barriers that move a texture from `from` (one state, or one for each
|
||||
/// subresource) to `to`.
|
||||
pub(super) fn moves(res: &ID3D12Resource, from: &[u32], to: &[u32], out: &mut Vec<D3D12_RESOURCE_BARRIER>) {
|
||||
let n = from.len().max(to.len());
|
||||
if n == 1 {
|
||||
if from[0] != to[0] {
|
||||
out.push(transition(res, wire::ALL, from[0], to[0]));
|
||||
}
|
||||
return;
|
||||
}
|
||||
for i in 0..n {
|
||||
let (a, b) = (from[i.min(from.len() - 1)], to[i.min(to.len() - 1)]);
|
||||
if a != b {
|
||||
out.push(transition(res, i as u32, a, b));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn to_desc(d: &wire::Desc) -> D3D12_RESOURCE_DESC {
|
||||
D3D12_RESOURCE_DESC {
|
||||
Dimension: D3D12_RESOURCE_DIMENSION(d.dimension),
|
||||
Alignment: d.alignment,
|
||||
Width: d.width,
|
||||
Height: d.height,
|
||||
DepthOrArraySize: d.depth,
|
||||
MipLevels: d.mips,
|
||||
Format: DXGI_FORMAT(d.format),
|
||||
SampleDesc: DXGI_SAMPLE_DESC { Count: d.samples[0], Quality: d.samples[1] },
|
||||
Layout: D3D12_TEXTURE_LAYOUT(d.layout),
|
||||
Flags: D3D12_RESOURCE_FLAGS(d.flags),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn from_desc(d: &D3D12_RESOURCE_DESC) -> wire::Desc {
|
||||
wire::Desc {
|
||||
dimension: d.Dimension.0,
|
||||
alignment: d.Alignment,
|
||||
width: d.Width,
|
||||
height: d.Height,
|
||||
depth: d.DepthOrArraySize,
|
||||
mips: d.MipLevels,
|
||||
format: d.Format.0,
|
||||
samples: [d.SampleDesc.Count, d.SampleDesc.Quality],
|
||||
layout: d.Layout.0,
|
||||
flags: d.Flags.0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn to_props(p: &wire::HeapProps) -> D3D12_HEAP_PROPERTIES {
|
||||
D3D12_HEAP_PROPERTIES {
|
||||
Type: D3D12_HEAP_TYPE(p.kind),
|
||||
CPUPageProperty: D3D12_CPU_PAGE_PROPERTY(p.cpu),
|
||||
MemoryPoolPreference: D3D12_MEMORY_POOL(p.pool),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn from_props(p: &D3D12_HEAP_PROPERTIES) -> wire::HeapProps {
|
||||
wire::HeapProps { kind: p.Type.0, cpu: p.CPUPageProperty.0, pool: p.MemoryPoolPreference.0 }
|
||||
}
|
||||
|
||||
/// How the CPU sees memory of a heap.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum Seen {
|
||||
/// Not at all: the card's own.
|
||||
No,
|
||||
/// Cached, read and written.
|
||||
Cached,
|
||||
/// Write-combined: slow to read.
|
||||
Combined,
|
||||
/// A read-back heap: the CPU only reads.
|
||||
ReadBack,
|
||||
}
|
||||
|
||||
pub(super) fn seen(p: &wire::HeapProps) -> Seen {
|
||||
match D3D12_HEAP_TYPE(p.kind) {
|
||||
D3D12_HEAP_TYPE_DEFAULT => Seen::No,
|
||||
D3D12_HEAP_TYPE_UPLOAD => Seen::Combined,
|
||||
D3D12_HEAP_TYPE_READBACK => Seen::ReadBack,
|
||||
D3D12_HEAP_TYPE_CUSTOM => match D3D12_CPU_PAGE_PROPERTY(p.cpu) {
|
||||
D3D12_CPU_PAGE_PROPERTY_WRITE_BACK => Seen::Cached,
|
||||
D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE => Seen::Combined,
|
||||
_ => Seen::No,
|
||||
},
|
||||
// GPU upload heaps (type 5).
|
||||
_ => Seen::Combined,
|
||||
}
|
||||
}
|
||||
|
||||
/// 8-bit RGB of a presented texture's rows (and the greatest channel value
|
||||
/// of the format, for the signal-to-noise ratio). `None` for formats not
|
||||
/// shown.
|
||||
pub(super) fn rgb(width: u32, height: u32, pitch: u32, format: i32, rows: &[u8]) -> Option<Vec<u8>> {
|
||||
let mut out = Vec::with_capacity((width * height * 3) as usize);
|
||||
let half = |b: &[u8]| {
|
||||
let h = u16::from_le_bytes([b[0], b[1]]);
|
||||
let (s, e, m) = (h >> 15, (h >> 10) & 31, f32::from(h & 1023));
|
||||
let v = match e {
|
||||
0 => m * 2f32.powi(-24),
|
||||
31 => 65536.0,
|
||||
e => (1.0 + m / 1024.0) * 2f32.powi(i32::from(e) - 15),
|
||||
};
|
||||
if s == 1 { 0 } else { (v.min(1.0) * 255.0) as u8 }
|
||||
};
|
||||
for y in 0..height as usize {
|
||||
let row = rows.get(y * pitch as usize..)?;
|
||||
for x in 0..width as usize {
|
||||
match format {
|
||||
27..=32 => out.extend_from_slice(row.get(x * 4..x * 4 + 3)?),
|
||||
87 | 88 | 90..=93 => {
|
||||
let p = row.get(x * 4..x * 4 + 3)?;
|
||||
out.extend([p[2], p[1], p[0]]);
|
||||
}
|
||||
23..=25 => {
|
||||
let p = row.get(x * 4..x * 4 + 4)?;
|
||||
let v = u32::from_le_bytes([p[0], p[1], p[2], p[3]]);
|
||||
out.extend([(v >> 2) as u8, (v >> 12) as u8, (v >> 22) as u8]);
|
||||
}
|
||||
9..=14 => {
|
||||
let p = row.get(x * 8..x * 8 + 6)?;
|
||||
out.extend([half(p), half(&p[2..]), half(&p[4..])]);
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Peak signal-to-noise ratio of two pictures of 8-bit channels, in dB
|
||||
/// (infinite if equal).
|
||||
pub(super) fn psnr(a: &[u8], b: &[u8]) -> f64 {
|
||||
let sum: u64 = a.iter().zip(b).map(|(&x, &y)| u64::from(x.abs_diff(y)).pow(2)).sum();
|
||||
if sum == 0 && a.len() == b.len() {
|
||||
return f64::INFINITY;
|
||||
}
|
||||
let mean = sum as f64 / a.len().min(b.len()).max(1) as f64;
|
||||
10.0 * (255.0 * 255.0 / mean).log10()
|
||||
}
|
||||
|
||||
/// The adapter a device is on: name, vendor and device number.
|
||||
pub(super) fn adapter(device: &ID3D12Device) -> (String, u32, u32) {
|
||||
use windows::Win32::Graphics::Dxgi::*;
|
||||
// SAFETY: plain queries.
|
||||
let desc = unsafe {
|
||||
CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
|
||||
.and_then(|f| f.EnumAdapterByLuid::<IDXGIAdapter1>(device.GetAdapterLuid()))
|
||||
.and_then(|a| a.GetDesc1())
|
||||
};
|
||||
match desc {
|
||||
Ok(d) => {
|
||||
let name = String::from_utf16_lossy(&d.Description);
|
||||
(name.trim_end_matches('\0').to_owned(), d.VendorId, d.DeviceId)
|
||||
}
|
||||
Err(_) => ("unknown".into(), 0, 0),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn pictures() {
|
||||
assert_eq!(rgb(1, 1, 4, 28, &[1, 2, 3, 4]).unwrap(), [1, 2, 3]);
|
||||
assert_eq!(rgb(1, 1, 4, 87, &[1, 2, 3, 4]).unwrap(), [3, 2, 1]);
|
||||
let v = (1023u32 | 512 << 10).to_le_bytes();
|
||||
assert_eq!(rgb(1, 1, 4, 24, &v).unwrap(), [255, 128, 0]);
|
||||
// 1.0, 0.5 and -1.0 as halves.
|
||||
assert_eq!(rgb(1, 1, 8, 10, &[0, 0x3c, 0, 0x38, 0, 0xbc, 0, 0]).unwrap(), [255, 127, 0]);
|
||||
assert!(rgb(1, 1, 4, 41, &[0; 4]).is_none());
|
||||
assert!(rgb(2, 2, 8, 28, &[0; 12]).is_none(), "too few rows");
|
||||
assert_eq!(psnr(&[1, 2], &[1, 2]), f64::INFINITY);
|
||||
assert!((psnr(&[0; 4], &[255; 4])).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn states_of_subresources() {
|
||||
assert_eq!(planes(44), 2);
|
||||
let mut d = from_desc(&buffer_desc(10, D3D12_RESOURCE_FLAG_NONE));
|
||||
assert_eq!(subresources(&d), 1);
|
||||
assert_eq!(from_desc(&to_desc(&d)), d);
|
||||
(d.dimension, d.depth, d.mips, d.format) = (3, 6, 4, 19);
|
||||
assert_eq!(subresources(&d), 48);
|
||||
d.dimension = 4;
|
||||
assert_eq!(subresources(&d), 8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
//! Methods of single COM objects replaced: an object's method table pointer
|
||||
//! is set to a copy of its table ([`Shim`]) with some entries changed. Other
|
||||
//! objects of the class keep theirs, so what is not asked for is untouched.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::ffi::c_void;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// Methods in a copied table: more than any D3D12 interface has (an
|
||||
/// interface's private methods may follow its public ones).
|
||||
pub(super) const SLOTS: usize = 192;
|
||||
/// Entries copied from before the table (type information).
|
||||
const PRE: usize = 4;
|
||||
|
||||
/// A copied method table. Objects point at `table`; what we keep for them
|
||||
/// lies before it. Never freed: an object may still use it while it dies.
|
||||
#[repr(C)]
|
||||
struct Shim {
|
||||
state: *const c_void,
|
||||
orig: *const usize,
|
||||
pre: [usize; PRE],
|
||||
table: [usize; SLOTS],
|
||||
}
|
||||
|
||||
const TO_ORIG: usize = std::mem::offset_of!(Shim, table) - std::mem::offset_of!(Shim, orig);
|
||||
|
||||
/// The shims made, by the address objects point at.
|
||||
static MADE: Mutex<BTreeSet<usize>> = Mutex::new(BTreeSet::new());
|
||||
|
||||
unsafe fn shim(this: *mut c_void) -> *const Shim {
|
||||
// SAFETY: the caller's object points into a shim.
|
||||
unsafe {
|
||||
let table = *this.cast::<*const u8>();
|
||||
table.sub(std::mem::offset_of!(Shim, table)).cast()
|
||||
}
|
||||
}
|
||||
|
||||
/// The object's own method table, as `T` (an interface's `_Vtbl`).
|
||||
///
|
||||
/// # Safety
|
||||
/// `this` is an object [`install`] was called for, of an interface `T` is
|
||||
/// the table of.
|
||||
pub(super) unsafe fn orig<T>(this: *mut c_void) -> &'static T {
|
||||
// SAFETY: the caller's.
|
||||
unsafe { &*(*shim(this)).orig.cast::<T>() }
|
||||
}
|
||||
|
||||
/// What [`install`] was given for the object.
|
||||
///
|
||||
/// # Safety
|
||||
/// As [`orig`]; `T` is what `state` pointed at.
|
||||
pub(super) unsafe fn state<T>(this: *mut c_void) -> &'static T {
|
||||
// SAFETY: the caller's.
|
||||
unsafe { &*(*shim(this)).state.cast::<T>() }
|
||||
}
|
||||
|
||||
/// Bytes readable from `at` on (up to a limit): what is copied of a table
|
||||
/// must not run past its module's data.
|
||||
fn readable(at: usize, most: usize) -> usize {
|
||||
use windows_sys::Win32::System::Memory::*;
|
||||
let mut end = at;
|
||||
while end < at + most {
|
||||
// SAFETY: a plain query.
|
||||
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: as above.
|
||||
let n = unsafe { VirtualQuery(end as *const c_void, &mut info, size_of::<MEMORY_BASIC_INFORMATION>()) };
|
||||
const READ: u32 = PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
|
||||
if n == 0 || info.State != MEM_COMMIT || info.Protect & READ == 0 || info.Protect & PAGE_GUARD != 0 {
|
||||
break;
|
||||
}
|
||||
end = info.BaseAddress as usize + info.RegionSize;
|
||||
}
|
||||
end.min(at + most) - at
|
||||
}
|
||||
|
||||
/// Gives the object a table of its own, changed by `patch`. `state` is what
|
||||
/// [`state`] answers; it must live for good. False if the object has one
|
||||
/// already (then nothing changes).
|
||||
///
|
||||
/// # Safety
|
||||
/// `this` is a live COM object no other thread uses yet; what `patch` puts
|
||||
/// into the table are functions of the methods' types.
|
||||
pub(super) unsafe fn install(this: *mut c_void, state: *const c_void, patch: impl FnOnce(&mut [usize; SLOTS])) -> bool {
|
||||
let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// SAFETY: a live COM object starts with its table's address.
|
||||
let at = unsafe { *this.cast::<usize>() };
|
||||
if made.contains(&at) {
|
||||
return false;
|
||||
}
|
||||
let mut new = Box::new(Shim { state, orig: at as *const usize, pre: [0; PRE], table: [0; SLOTS] });
|
||||
let have = readable(at, SLOTS * 8) / 8;
|
||||
// SAFETY: `have` entries are readable; the object's table is at least
|
||||
// as long as its interface, and what lies behind it is only copied.
|
||||
unsafe { std::ptr::copy_nonoverlapping(at as *const usize, new.table.as_mut_ptr(), have) };
|
||||
if readable(at - PRE * 8, PRE * 8) == PRE * 8 {
|
||||
// SAFETY: as above.
|
||||
unsafe { std::ptr::copy_nonoverlapping((at as *const usize).sub(PRE), new.pre.as_mut_ptr(), PRE) };
|
||||
}
|
||||
patch(&mut new.table);
|
||||
let new: &'static Shim = Box::leak(new);
|
||||
made.insert(new.table.as_ptr() as usize);
|
||||
// SAFETY: the object's first word, its table's address.
|
||||
unsafe { this.cast::<*const usize>().write(new.table.as_ptr()) };
|
||||
true
|
||||
}
|
||||
|
||||
/// The table the object points at.
|
||||
///
|
||||
/// # Safety
|
||||
/// `this` is a live COM object.
|
||||
pub(super) unsafe fn table(this: *mut c_void) -> usize {
|
||||
// SAFETY: the caller's.
|
||||
unsafe { *this.cast::<usize>() }
|
||||
}
|
||||
|
||||
/// Whether the object points at a shim of ours.
|
||||
///
|
||||
/// # Safety
|
||||
/// `this` is a live COM object.
|
||||
pub(super) unsafe fn ours(this: *mut c_void) -> bool {
|
||||
// SAFETY: the caller's.
|
||||
let at = unsafe { table(this) };
|
||||
MADE.lock().unwrap_or_else(|e| e.into_inner()).contains(&at)
|
||||
}
|
||||
|
||||
/// After a method that may have set the object's table pointer anew: it
|
||||
/// points at its shim (`before`, where it pointed) again. A table it did
|
||||
/// not have before gets a shim of its own.
|
||||
///
|
||||
/// # Safety
|
||||
/// As [`install`]; `before` is a shim's table.
|
||||
pub(super) unsafe fn again(this: *mut c_void, before: usize, patch: impl FnOnce(&mut [usize; SLOTS])) {
|
||||
// SAFETY: the caller's.
|
||||
unsafe {
|
||||
let now = table(this);
|
||||
if now == before {
|
||||
return;
|
||||
}
|
||||
let shim = (before as *const u8).sub(std::mem::offset_of!(Shim, table)).cast::<Shim>();
|
||||
if (*shim).orig as usize == now {
|
||||
this.cast::<usize>().write(before);
|
||||
} else {
|
||||
install(this, (*shim).state, patch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives the object its own table back, if it points at a shim of ours
|
||||
/// (tests).
|
||||
///
|
||||
/// # Safety
|
||||
/// `this` is a live object, used by no other thread now.
|
||||
pub(super) unsafe fn remove(this: *mut c_void) {
|
||||
let made = MADE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// SAFETY: as in `install`.
|
||||
unsafe {
|
||||
let at = *this.cast::<usize>();
|
||||
if made.contains(&at) {
|
||||
let own = (*shim(this)).orig;
|
||||
this.cast::<*const usize>().write(own);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Classes of [`uncounted`] calls.
|
||||
pub(super) const LIST: usize = 0;
|
||||
pub(super) const DEVICE: usize = 1;
|
||||
pub(super) const QUEUE: usize = 2;
|
||||
const CLASSES: usize = 3;
|
||||
|
||||
#[allow(clippy::declare_interior_mutable_const)]
|
||||
const ZERO: AtomicU64 = AtomicU64::new(0);
|
||||
static COUNTS: [AtomicU64; CLASSES * SLOTS] = [ZERO; CLASSES * SLOTS];
|
||||
|
||||
/// How often a method the recorder does not record was called.
|
||||
pub(super) fn count(class: usize, slot: usize) -> u64 {
|
||||
COUNTS[class * SLOTS + slot].load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// A method the recorder does not know how to record: counts the call in
|
||||
/// [`COUNTS`] and goes on to the object's own. Any arguments pass as they
|
||||
/// are: only the scratch register `rax` is used.
|
||||
#[unsafe(naked)]
|
||||
unsafe extern "system" fn noted<const AT: usize>() {
|
||||
core::arch::naked_asm!(
|
||||
"lock inc qword ptr [rip + {counts} + {at} * 8]",
|
||||
"mov rax, [rcx]",
|
||||
"mov rax, [rax - {orig}]",
|
||||
"jmp qword ptr [rax + ({at} % {slots}) * 8]",
|
||||
counts = sym COUNTS,
|
||||
at = const AT,
|
||||
orig = const TO_ORIG,
|
||||
slots = const SLOTS,
|
||||
)
|
||||
}
|
||||
|
||||
/// [`noted`] for method `SLOT` of a class, `AT` being `class * SLOTS + slot`.
|
||||
pub(super) fn noted_entry<const AT: usize>() -> usize {
|
||||
noted::<AT> as *const () as usize
|
||||
}
|
||||
|
||||
/// The slot of a method in its table.
|
||||
macro_rules! method {
|
||||
($vtbl:ident . $name:ident) => {
|
||||
std::mem::offset_of!(windows::Win32::Graphics::Direct3D12::$vtbl, $name) / 8
|
||||
};
|
||||
}
|
||||
pub(super) use method;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[repr(C)]
|
||||
struct Vtbl {
|
||||
methods: [usize; 8],
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct Object {
|
||||
vtbl: *const Vtbl,
|
||||
value: u64,
|
||||
}
|
||||
|
||||
unsafe extern "system" fn add(this: *mut c_void, a: u64, b: u64, c: u64, d: u64, e: f64) -> u64 {
|
||||
// SAFETY: one of the test's objects.
|
||||
unsafe { (*this.cast::<Object>()).value + a + b + c + d + e as u64 }
|
||||
}
|
||||
|
||||
type Add = unsafe extern "system" fn(*mut c_void, u64, u64, u64, u64, f64) -> u64;
|
||||
|
||||
unsafe extern "system" fn double(this: *mut c_void, a: u64, b: u64, c: u64, d: u64, e: f64) -> u64 {
|
||||
// SAFETY: an object with a shim whose first method is `add`.
|
||||
unsafe {
|
||||
let first = orig::<[Add; 1]>(this)[0];
|
||||
first(this, a, b, c, d, e) * 2 + *state::<u64>(this)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn call(object: &mut Object, slot: usize) -> u64 {
|
||||
// SAFETY: an entry of `Add`'s type.
|
||||
unsafe {
|
||||
let f: Add = std::mem::transmute((*object.vtbl).methods[slot]);
|
||||
f((&raw mut *object).cast(), 1, 2, 3, 4, 5.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_object_is_changed_and_changed_back() {
|
||||
static STATE: u64 = 1000;
|
||||
let vtbl = Vtbl { methods: [add as *const () as usize; 8] };
|
||||
let mut a = Object { vtbl: &vtbl, value: 100 };
|
||||
let mut b = Object { vtbl: &vtbl, value: 200 };
|
||||
// SAFETY: the test's objects; entries of `Add`'s type.
|
||||
unsafe {
|
||||
let this: *mut c_void = (&raw mut a).cast();
|
||||
let patch = |t: &mut [usize; SLOTS]| {
|
||||
t[0] = double as *const () as usize;
|
||||
t[2] = noted_entry::<{ QUEUE * SLOTS + 2 }>();
|
||||
};
|
||||
assert!(install(this, (&raw const STATE).cast(), patch));
|
||||
assert!(!install(this, (&raw const STATE).cast(), patch), "only once");
|
||||
assert_eq!(call(&mut a, 0), 230 + 1000);
|
||||
assert_eq!(call(&mut a, 1), 115);
|
||||
assert_eq!(call(&mut b, 0), 215, "other objects are untouched");
|
||||
// Counted, and passed on with all its arguments.
|
||||
let before = count(QUEUE, 2);
|
||||
assert_eq!(call(&mut a, 2), 115);
|
||||
assert_eq!(call(&mut a, 2), 115);
|
||||
assert_eq!(count(QUEUE, 2), before + 2);
|
||||
// A method that set the table pointer anew.
|
||||
let shim = table(this);
|
||||
assert!(ours(this));
|
||||
a.vtbl = &vtbl;
|
||||
assert!(!ours(this));
|
||||
again(this, shim, patch);
|
||||
assert_eq!(table(this), shim);
|
||||
// Or to another table.
|
||||
let other = Vtbl { methods: [add as *const () as usize; 8] };
|
||||
a.vtbl = &other;
|
||||
again(this, shim, patch);
|
||||
assert!(ours(this) && table(this) != shim);
|
||||
assert_eq!(call(&mut a, 0), 230 + 1000);
|
||||
remove(this);
|
||||
assert!(std::ptr::eq(a.vtbl, &other));
|
||||
assert_eq!(call(&mut a, 0), 115);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
//! One frame's D3D12 work recorded and run again, to find out what it costs
|
||||
//! the card and to try changes on it in seconds (docs/replay.md).
|
||||
//!
|
||||
//! [`record`] hooks the host's D3D12 objects (`hook`) and keeps what a frame
|
||||
//! needs; `snap` writes one frame down; [`play`] runs it. `wire` is what a
|
||||
//! capture holds, `pso` pipeline descriptions, `states` the states textures
|
||||
//! are in, `edit` the experiments, `gpu` helpers.
|
||||
|
||||
mod edit;
|
||||
mod gpu;
|
||||
mod hook;
|
||||
pub mod play;
|
||||
mod pso;
|
||||
pub mod record;
|
||||
mod snap;
|
||||
mod states;
|
||||
mod wire;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,317 @@
|
||||
//! Pipeline descriptions as parts: every form D3D12 takes them in (graphics,
|
||||
//! compute, stream) is kept as the subobjects of a stream, and made again
|
||||
//! from them as a stream.
|
||||
|
||||
use std::ffi::{CString, c_void};
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
use windows::Win32::Graphics::Dxgi::Common::*;
|
||||
use windows::core::{Interface, PCSTR};
|
||||
|
||||
use super::wire::{Blob, Part};
|
||||
|
||||
/// What a subobject holds, by its type: bytes, and whether it starts with a
|
||||
/// pointer (aligned to 8).
|
||||
enum Holds {
|
||||
Root,
|
||||
Code,
|
||||
Layout,
|
||||
/// Pointers the recorder does not follow.
|
||||
Pointers(usize),
|
||||
Plain(usize),
|
||||
}
|
||||
|
||||
fn holds(kind: i32) -> Option<Holds> {
|
||||
Some(match kind {
|
||||
0 => Holds::Root,
|
||||
1..=6 | 24 | 25 => Holds::Code,
|
||||
7 => Holds::Pointers(size_of::<D3D12_STREAM_OUTPUT_DESC>()),
|
||||
8 => Holds::Plain(size_of::<D3D12_BLEND_DESC>()),
|
||||
9 | 13 | 14 | 16 | 18 | 20 => Holds::Plain(4),
|
||||
10 => Holds::Plain(size_of::<D3D12_RASTERIZER_DESC>()),
|
||||
11 => Holds::Plain(size_of::<D3D12_DEPTH_STENCIL_DESC>()),
|
||||
12 => Holds::Layout,
|
||||
15 => Holds::Plain(size_of::<D3D12_RT_FORMAT_ARRAY>()),
|
||||
17 => Holds::Plain(size_of::<DXGI_SAMPLE_DESC>()),
|
||||
19 => Holds::Pointers(size_of::<D3D12_CACHED_PIPELINE_STATE>()),
|
||||
21 => Holds::Plain(size_of::<D3D12_DEPTH_STENCIL_DESC1>()),
|
||||
22 => Holds::Pointers(size_of::<D3D12_VIEW_INSTANCING_DESC>()),
|
||||
26 => Holds::Plain(size_of::<D3D12_DEPTH_STENCIL_DESC2>()),
|
||||
27 => Holds::Plain(size_of::<D3D12_RASTERIZER_DESC1>()),
|
||||
28 => Holds::Plain(size_of::<D3D12_RASTERIZER_DESC2>()),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// What the parts need from the recorder.
|
||||
pub(super) trait Keep {
|
||||
fn root(&mut self, root: *mut c_void) -> u32;
|
||||
fn code(&mut self, code: &[u8]) -> u32;
|
||||
/// Something in a description that is not kept.
|
||||
fn lost(&mut self, what: &str);
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `at` points at a value of `size` bytes.
|
||||
unsafe fn plain(kind: i32, at: *const c_void, size: usize) -> Part {
|
||||
// SAFETY: the caller's.
|
||||
Part::Plain { kind, data: Blob(unsafe { std::slice::from_raw_parts(at.cast::<u8>(), size) }.to_vec()) }
|
||||
}
|
||||
|
||||
unsafe fn code(kind: i32, c: &D3D12_SHADER_BYTECODE, keep: &mut dyn Keep) -> Option<Part> {
|
||||
if c.pShaderBytecode.is_null() || c.BytecodeLength == 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the description's own code.
|
||||
let bytes = unsafe { std::slice::from_raw_parts(c.pShaderBytecode.cast::<u8>(), c.BytecodeLength) };
|
||||
Some(Part::Code { kind, blob: keep.code(bytes) })
|
||||
}
|
||||
|
||||
unsafe fn layout(l: &D3D12_INPUT_LAYOUT_DESC) -> Option<Part> {
|
||||
if l.pInputElementDescs.is_null() || l.NumElements == 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the description's own elements, with their names.
|
||||
let elements = unsafe { std::slice::from_raw_parts(l.pInputElementDescs, l.NumElements as usize) }
|
||||
.iter()
|
||||
.map(|e| {
|
||||
// SAFETY: as above.
|
||||
let name = unsafe { e.SemanticName.to_string() }.unwrap_or_default();
|
||||
let rest = [
|
||||
e.SemanticIndex,
|
||||
e.Format.0 as u32,
|
||||
e.InputSlot,
|
||||
e.AlignedByteOffset,
|
||||
e.InputSlotClass.0 as u32,
|
||||
e.InstanceDataStepRate,
|
||||
];
|
||||
(name, rest)
|
||||
})
|
||||
.collect();
|
||||
Some(Part::Layout { elements })
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// A valid description.
|
||||
pub(super) unsafe fn compute(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, keep: &mut dyn Keep) -> Vec<Part> {
|
||||
// SAFETY: the caller's description.
|
||||
unsafe {
|
||||
let mut parts = vec![Part::Root { root: keep.root(std::mem::transmute_copy(&d.pRootSignature)) }];
|
||||
parts.extend(code(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS.0, &d.CS, keep));
|
||||
if d.Flags.0 != 0 {
|
||||
parts.push(plain(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS.0, (&raw const d.Flags).cast(), 4));
|
||||
}
|
||||
parts
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// A valid description.
|
||||
pub(super) unsafe fn graphics(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, keep: &mut dyn Keep) -> Vec<Part> {
|
||||
// SAFETY: the caller's description.
|
||||
unsafe {
|
||||
let mut parts = vec![Part::Root { root: keep.root(std::mem::transmute_copy(&d.pRootSignature)) }];
|
||||
for (kind, c) in [(1, &d.VS), (2, &d.PS), (3, &d.DS), (4, &d.HS), (5, &d.GS)] {
|
||||
parts.extend(code(kind, c, keep));
|
||||
}
|
||||
if d.StreamOutput.NumEntries != 0 {
|
||||
keep.lost("a pipeline's stream output");
|
||||
}
|
||||
parts.push(plain(8, (&raw const d.BlendState).cast(), size_of::<D3D12_BLEND_DESC>()));
|
||||
parts.push(plain(9, (&raw const d.SampleMask).cast(), 4));
|
||||
parts.push(plain(10, (&raw const d.RasterizerState).cast(), size_of::<D3D12_RASTERIZER_DESC>()));
|
||||
parts.push(plain(11, (&raw const d.DepthStencilState).cast(), size_of::<D3D12_DEPTH_STENCIL_DESC>()));
|
||||
parts.extend(layout(&d.InputLayout));
|
||||
parts.push(plain(13, (&raw const d.IBStripCutValue).cast(), 4));
|
||||
parts.push(plain(14, (&raw const d.PrimitiveTopologyType).cast(), 4));
|
||||
let targets = D3D12_RT_FORMAT_ARRAY { RTFormats: d.RTVFormats, NumRenderTargets: d.NumRenderTargets };
|
||||
parts.push(plain(15, (&raw const targets).cast(), size_of::<D3D12_RT_FORMAT_ARRAY>()));
|
||||
parts.push(plain(16, (&raw const d.DSVFormat).cast(), 4));
|
||||
parts.push(plain(17, (&raw const d.SampleDesc).cast(), size_of::<DXGI_SAMPLE_DESC>()));
|
||||
if d.Flags.0 != 0 {
|
||||
parts.push(plain(20, (&raw const d.Flags).cast(), 4));
|
||||
}
|
||||
parts
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// A valid description.
|
||||
pub(super) unsafe fn stream(d: &D3D12_PIPELINE_STATE_STREAM_DESC, keep: &mut dyn Keep) -> Vec<Part> {
|
||||
let base = d.pPipelineStateSubobjectStream.cast::<u8>().cast_const();
|
||||
let mut parts = Vec::new();
|
||||
let mut at = 0usize;
|
||||
while at + 4 <= d.SizeInBytes {
|
||||
// SAFETY: the caller's stream holds whole subobjects, each at a
|
||||
// multiple of the size of a pointer.
|
||||
unsafe {
|
||||
let kind = base.add(at).cast::<i32>().read();
|
||||
let Some(h) = holds(kind) else {
|
||||
keep.lost(&format!("a pipeline stream's subobject of type {kind}, and those after it"));
|
||||
break;
|
||||
};
|
||||
let (from, size) = match h {
|
||||
Holds::Root => (8, 8),
|
||||
Holds::Code | Holds::Layout => (8, 16),
|
||||
Holds::Pointers(n) => (8, n),
|
||||
Holds::Plain(n) => (4, n),
|
||||
};
|
||||
let value = base.add(at + from);
|
||||
match h {
|
||||
Holds::Root => parts.push(Part::Root { root: keep.root(value.cast::<*mut c_void>().read()) }),
|
||||
Holds::Code => parts.extend(code(kind, &*value.cast(), keep)),
|
||||
Holds::Layout => parts.extend(layout(&*value.cast())),
|
||||
Holds::Pointers(_) => {
|
||||
// A cached blob is only a shortcut.
|
||||
let empty = std::slice::from_raw_parts(value, size).iter().all(|&b| b == 0);
|
||||
if kind != D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO.0 && !empty {
|
||||
keep.lost(&format!("a pipeline stream's subobject of type {kind}"));
|
||||
}
|
||||
}
|
||||
Holds::Plain(n) => parts.push(plain(kind, value.cast(), n)),
|
||||
}
|
||||
at += (from + size).next_multiple_of(8);
|
||||
}
|
||||
}
|
||||
parts
|
||||
}
|
||||
|
||||
/// A pipeline made again.
|
||||
pub(super) fn make(
|
||||
device: &ID3D12Device2,
|
||||
parts: &[Part],
|
||||
root: impl Fn(u32) -> Option<ID3D12RootSignature>,
|
||||
code: impl Fn(u32) -> Option<Vec<u8>>,
|
||||
) -> Result<ID3D12PipelineState, String> {
|
||||
// Everything the stream points at, kept until the pipeline is made.
|
||||
let mut codes: Vec<Vec<u8>> = Vec::new();
|
||||
let mut names: Vec<CString> = Vec::new();
|
||||
let mut elements: Vec<Vec<D3D12_INPUT_ELEMENT_DESC>> = Vec::new();
|
||||
let mut bytes: Vec<u8> = Vec::new();
|
||||
let mut roots = Vec::new();
|
||||
for part in parts {
|
||||
bytes.resize(bytes.len().next_multiple_of(8), 0);
|
||||
match part {
|
||||
Part::Root { root: 0 } => {}
|
||||
Part::Root { root: id } => {
|
||||
let r = root(*id).ok_or_else(|| format!("root signature {id} is not in the capture"))?;
|
||||
bytes.extend([0u8; 8]);
|
||||
bytes.extend((r.as_raw() as usize).to_le_bytes());
|
||||
roots.push(r);
|
||||
}
|
||||
Part::Code { kind, blob } => {
|
||||
let c = code(*blob).ok_or_else(|| format!("shader {blob} is not in the capture"))?;
|
||||
bytes.extend(kind.to_le_bytes());
|
||||
bytes.extend([0u8; 4]);
|
||||
bytes.extend((c.as_ptr() as usize).to_le_bytes());
|
||||
bytes.extend(c.len().to_le_bytes());
|
||||
codes.push(c);
|
||||
}
|
||||
Part::Plain { kind, data } => {
|
||||
bytes.extend(kind.to_le_bytes());
|
||||
bytes.extend_from_slice(&data.0);
|
||||
}
|
||||
Part::Layout { elements: all } => {
|
||||
let made: Vec<D3D12_INPUT_ELEMENT_DESC> = all
|
||||
.iter()
|
||||
.map(|(name, r)| {
|
||||
names.push(CString::new(name.as_str()).unwrap_or_default());
|
||||
D3D12_INPUT_ELEMENT_DESC {
|
||||
SemanticName: PCSTR(names.last().map_or(std::ptr::null(), |n| n.as_ptr().cast())),
|
||||
SemanticIndex: r[0],
|
||||
Format: DXGI_FORMAT(r[1] as i32),
|
||||
InputSlot: r[2],
|
||||
AlignedByteOffset: r[3],
|
||||
InputSlotClass: D3D12_INPUT_CLASSIFICATION(r[4] as i32),
|
||||
InstanceDataStepRate: r[5],
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
bytes.extend(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT.0.to_le_bytes());
|
||||
bytes.extend([0u8; 4]);
|
||||
bytes.extend((made.as_ptr() as usize).to_le_bytes());
|
||||
bytes.extend((made.len() as u64).to_le_bytes());
|
||||
elements.push(made);
|
||||
}
|
||||
}
|
||||
}
|
||||
bytes.resize(bytes.len().next_multiple_of(8), 0);
|
||||
// Aligned for the pointers in it.
|
||||
let mut words: Vec<u64> = bytes.chunks_exact(8).map(|c| u64::from_le_bytes(c.try_into().unwrap_or_default())).collect();
|
||||
let desc = D3D12_PIPELINE_STATE_STREAM_DESC {
|
||||
SizeInBytes: words.len() * 8,
|
||||
pPipelineStateSubobjectStream: words.as_mut_ptr().cast(),
|
||||
};
|
||||
// SAFETY: a stream of whole subobjects; all it points at is alive.
|
||||
let made: windows::core::Result<ID3D12PipelineState> = unsafe { device.CreatePipelineState(&desc) };
|
||||
made.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Kept {
|
||||
codes: Vec<Vec<u8>>,
|
||||
lost: Vec<String>,
|
||||
}
|
||||
|
||||
impl Keep for Kept {
|
||||
fn root(&mut self, root: *mut c_void) -> u32 {
|
||||
root as usize as u32
|
||||
}
|
||||
fn code(&mut self, code: &[u8]) -> u32 {
|
||||
self.codes.push(code.to_vec());
|
||||
self.codes.len() as u32 - 1
|
||||
}
|
||||
fn lost(&mut self, what: &str) {
|
||||
self.lost.push(what.into());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_is_taken_apart() {
|
||||
#[repr(C, align(8))]
|
||||
struct Sub<T>(i32, T);
|
||||
#[repr(C)]
|
||||
struct Stream {
|
||||
root: Sub<usize>,
|
||||
ms: Sub<D3D12_SHADER_BYTECODE>,
|
||||
blend: Sub<D3D12_BLEND_DESC>,
|
||||
mask: Sub<u32>,
|
||||
raster: Sub<D3D12_RASTERIZER_DESC>,
|
||||
depth: Sub<D3D12_DEPTH_STENCIL_DESC>,
|
||||
targets: Sub<D3D12_RT_FORMAT_ARRAY>,
|
||||
dsv: Sub<DXGI_FORMAT>,
|
||||
samples: Sub<DXGI_SAMPLE_DESC>,
|
||||
unknown: Sub<u32>,
|
||||
}
|
||||
let bytes = [1u8, 2, 3];
|
||||
let mut s = Stream {
|
||||
root: Sub(0, 77),
|
||||
ms: Sub(25, D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: 3 }),
|
||||
blend: Sub(8, D3D12_BLEND_DESC::default()),
|
||||
mask: Sub(9, 5),
|
||||
raster: Sub(10, D3D12_RASTERIZER_DESC { DepthBias: 6, ..Default::default() }),
|
||||
depth: Sub(11, D3D12_DEPTH_STENCIL_DESC::default()),
|
||||
targets: Sub(15, D3D12_RT_FORMAT_ARRAY { NumRenderTargets: 3, ..Default::default() }),
|
||||
dsv: Sub(16, DXGI_FORMAT(40)),
|
||||
samples: Sub(17, DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }),
|
||||
unknown: Sub(99, 0),
|
||||
};
|
||||
let d = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: size_of::<Stream>(), pPipelineStateSubobjectStream: (&raw mut s).cast() };
|
||||
let mut kept = Kept::default();
|
||||
// SAFETY: the stream above.
|
||||
let parts = unsafe { stream(&d, &mut kept) };
|
||||
assert_eq!(kept.codes, [vec![1, 2, 3]]);
|
||||
assert_eq!(kept.lost.len(), 1, "the unknown subobject is reported");
|
||||
assert_eq!(parts.len(), 9);
|
||||
assert_eq!(parts[0], Part::Root { root: 77 });
|
||||
assert_eq!(parts[1], Part::Code { kind: 25, blob: 0 });
|
||||
assert_eq!(parts[3], Part::Plain { kind: 9, data: Blob(5u32.to_le_bytes().to_vec()) });
|
||||
let Part::Plain { kind: 10, data } = &parts[4] else { panic!("{:?}", parts[4]) };
|
||||
assert_eq!(data.0.len(), size_of::<D3D12_RASTERIZER_DESC>());
|
||||
assert_eq!(parts[7], Part::Plain { kind: 16, data: Blob(40u32.to_le_bytes().to_vec()) });
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,923 @@
|
||||
//! One frame written down: what its submissions run, what the card's
|
||||
//! memory held at its start, and what the CPU put into memory both see
|
||||
//! before each submission.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::fs::File;
|
||||
use std::os::windows::fs::FileExt;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
use windows::core::Interface;
|
||||
|
||||
use super::gpu::{self, Seen, Worker};
|
||||
use super::record::{At, Heap, Ours, Recorder, Res, lock, not_recorded_calls, read};
|
||||
use super::states::{COMMON, COPY_SOURCE, Change, States};
|
||||
use super::wire::{self, ALL, Cmd, Content, Delta, MISSING, NONE, Place, Slot, Va, ZERO, slot};
|
||||
|
||||
type Fault = Box<dyn std::error::Error + Send + Sync>;
|
||||
|
||||
/// A read-back buffer contents go through, and how many there are.
|
||||
const STAGING: u64 = 256 << 20;
|
||||
const STAGINGS: usize = 4;
|
||||
/// The most of a buffer in one piece.
|
||||
const PIECE: u64 = 32 << 20;
|
||||
/// What the CPU changes is kept in units of.
|
||||
const PAGE: usize = 4096;
|
||||
/// What one thread compares at a time.
|
||||
const CHUNK: usize = 1 << 20;
|
||||
/// Frames waited, at the most, for one whose lists are all recorded.
|
||||
const PATIENCE: u64 = 300;
|
||||
|
||||
#[derive(Default)]
|
||||
enum Stage {
|
||||
#[default]
|
||||
Waiting,
|
||||
/// Lists are recorded, since this many presents.
|
||||
Armed(u64),
|
||||
Capturing(Box<Capture>),
|
||||
Done,
|
||||
}
|
||||
|
||||
/// Where the recorder is.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Phase {
|
||||
presents: u64,
|
||||
stage: Stage,
|
||||
/// Submissions of this frame so far, and lists among them that were not
|
||||
/// recorded.
|
||||
submits: u32,
|
||||
missing: u32,
|
||||
}
|
||||
|
||||
impl Phase {
|
||||
pub(super) fn done(&self) -> bool {
|
||||
matches!(self.stage, Stage::Done)
|
||||
}
|
||||
}
|
||||
|
||||
/// A submission to a queue other than the drawing one: left out.
|
||||
pub(super) fn other_queue(r: &Recorder, lists: u32) {
|
||||
if r.watching.load(Ordering::SeqCst) {
|
||||
r.problem_times("lists sent to a queue other than the drawing one are not in the capture", u64::from(lists));
|
||||
}
|
||||
}
|
||||
|
||||
/// A submission to the drawing queue, made by `go`.
|
||||
pub(super) fn submit(r: &Recorder, queue: &ID3D12CommandQueue, lists: &[*mut std::ffi::c_void], go: impl FnOnce()) {
|
||||
let mut phase = lock(&r.submits);
|
||||
type Closed = (Option<Arc<Vec<u8>>>, Arc<Vec<Change>>);
|
||||
let closed: Vec<Option<Closed>> = lists.iter().map(|&p| r.list(p).and_then(|l| l.closed())).collect();
|
||||
phase.submits += 1;
|
||||
phase.missing += closed.iter().filter(|c| c.as_ref().is_none_or(|c| c.0.is_none())).count() as u32;
|
||||
if let Stage::Capturing(c) = &mut phase.stage {
|
||||
let commands: Vec<Option<Arc<Vec<u8>>>> = closed.iter().map(|c| c.as_ref().and_then(|c| c.0.clone())).collect();
|
||||
let _ours = Ours::new();
|
||||
if let Err(e) = c.submit(r, queue, &commands) {
|
||||
stop(r, &mut phase, &*e);
|
||||
}
|
||||
}
|
||||
go();
|
||||
let mut states = lock(&r.states);
|
||||
for change in closed.iter().flatten().flat_map(|c| c.1.iter()) {
|
||||
states.change(change);
|
||||
}
|
||||
states.decay();
|
||||
}
|
||||
|
||||
/// The capture failed.
|
||||
fn stop(r: &Recorder, phase: &mut Phase, e: &(dyn std::error::Error + Send + Sync)) {
|
||||
tracing::error!("frame recorder: the capture failed: {e}");
|
||||
let _ = std::fs::write(r.folder.join("failed.txt"), e.to_string());
|
||||
phase.stage = Stage::Done;
|
||||
r.watching.store(false, Ordering::SeqCst);
|
||||
r.arm(false);
|
||||
lock(&r.held).clear();
|
||||
}
|
||||
|
||||
pub(super) fn present(r: &Recorder, texture: &ID3D12Resource, state: u32) {
|
||||
let mut phase = lock(&r.submits);
|
||||
phase.presents += 1;
|
||||
let presents = phase.presents;
|
||||
let (submits, missing) = (std::mem::take(&mut phase.submits), std::mem::take(&mut phase.missing));
|
||||
let mut finished = None;
|
||||
match &mut phase.stage {
|
||||
Stage::Waiting => {
|
||||
let due = match r.settings.at {
|
||||
At::Seconds(s) => r.began.elapsed().as_secs_f64() >= s,
|
||||
At::Frame(f) => presents >= f,
|
||||
At::Trigger => false,
|
||||
};
|
||||
if due || r.settings.folder.join("go").exists() {
|
||||
tracing::info!(presents, "frame recorder: lists are recorded from now on");
|
||||
r.arm(true);
|
||||
phase.stage = Stage::Armed(presents);
|
||||
}
|
||||
}
|
||||
Stage::Armed(since) => {
|
||||
let waited = presents - *since;
|
||||
let whole = submits > 0 && missing == 0;
|
||||
if waited >= 2 && (whole || waited > PATIENCE) {
|
||||
if !whole {
|
||||
r.problem("no frame was found whose lists were all recorded");
|
||||
}
|
||||
tracing::info!(presents, waited, "frame recorder: the next frame is captured");
|
||||
match Capture::new(r) {
|
||||
Ok(c) => phase.stage = Stage::Capturing(Box::new(c)),
|
||||
Err(e) => stop(r, &mut phase, &*e),
|
||||
}
|
||||
}
|
||||
}
|
||||
Stage::Capturing(c) if c.started => {
|
||||
let _ours = Ours::new();
|
||||
let done = c.present(r, texture, state).and_then(|()| {
|
||||
if c.frame < r.settings.frames {
|
||||
return Ok(false);
|
||||
}
|
||||
c.finish(r)?;
|
||||
Ok(true)
|
||||
});
|
||||
match done {
|
||||
Ok(false) => {}
|
||||
Ok(true) => {
|
||||
r.watching.store(false, Ordering::SeqCst);
|
||||
r.arm(false);
|
||||
if let Stage::Capturing(c) = std::mem::replace(&mut phase.stage, Stage::Done) {
|
||||
finished = Some((c, std::mem::take(&mut *lock(&r.held))));
|
||||
}
|
||||
}
|
||||
Err(e) => stop(r, &mut phase, &*e),
|
||||
}
|
||||
}
|
||||
// A frame without a submission: the next one.
|
||||
Stage::Capturing(_) | Stage::Done => {}
|
||||
}
|
||||
drop(phase);
|
||||
// What was kept alive goes without a lock held.
|
||||
drop(finished);
|
||||
}
|
||||
|
||||
/// A buffer the CPU sees.
|
||||
struct CpuBuffer {
|
||||
id: u32,
|
||||
res: ID3D12Resource,
|
||||
/// Where it is read: its mapping, or the read-back copy of it.
|
||||
live: *const u8,
|
||||
/// The read-back buffer and the offset in it, for one that is slow to
|
||||
/// read.
|
||||
through: Option<(usize, u64)>,
|
||||
size: usize,
|
||||
/// What it held at the submission before (zeros before the first).
|
||||
kept: Vec<u8>,
|
||||
}
|
||||
|
||||
// SAFETY: the mapping is of a buffer the struct holds.
|
||||
unsafe impl Send for CpuBuffer {}
|
||||
// SAFETY: as above; the mapping is only read.
|
||||
unsafe impl Sync for CpuBuffer {}
|
||||
|
||||
struct Capture {
|
||||
worker: Worker,
|
||||
others: Vec<Worker>,
|
||||
/// Resources the frame can use, kept alive.
|
||||
held: Vec<ID3D12Resource>,
|
||||
started: bool,
|
||||
frame: u32,
|
||||
states: States,
|
||||
idle: HashSet<u32>,
|
||||
heaps: Vec<(Arc<Heap>, Vec<(u32, u32, Slot)>)>,
|
||||
contents: Vec<Content>,
|
||||
buffers: Vec<CpuBuffer>,
|
||||
known: HashSet<u32>,
|
||||
/// Read-back buffers for the slow ones: the buffer, its mapping, size,
|
||||
/// and how much of it is taken.
|
||||
blocks: Vec<(ID3D12Resource, usize, u64, u64)>,
|
||||
deltas: File,
|
||||
delta_at: AtomicU64,
|
||||
lists: Vec<Arc<Vec<u8>>>,
|
||||
submits: Vec<wire::Submit>,
|
||||
presents: Vec<wire::Present>,
|
||||
present_file: File,
|
||||
present_at: u64,
|
||||
calls: Vec<(String, u64)>,
|
||||
began: Instant,
|
||||
took: BTreeMap<&'static str, std::time::Duration>,
|
||||
}
|
||||
|
||||
impl Capture {
|
||||
fn new(r: &Recorder) -> Result<Capture, Fault> {
|
||||
let _ours = Ours::new();
|
||||
let device = r.device().ok_or("no device")?;
|
||||
let queues = lock(&r.queues).clone();
|
||||
let direct = queues.iter().find(|q| q.1 == D3D12_COMMAND_LIST_TYPE_DIRECT.0).ok_or("no drawing queue")?;
|
||||
let mut others = Vec::new();
|
||||
for (queue, _) in queues.iter().filter(|q| q.0 != direct.0) {
|
||||
others.push(Worker::new(&device, queue)?);
|
||||
}
|
||||
Ok(Capture {
|
||||
worker: Worker::new(&device, &direct.0)?,
|
||||
others,
|
||||
held: Vec::new(),
|
||||
started: false,
|
||||
frame: 0,
|
||||
states: States::default(),
|
||||
idle: HashSet::new(),
|
||||
heaps: Vec::new(),
|
||||
contents: Vec::new(),
|
||||
buffers: Vec::new(),
|
||||
known: HashSet::new(),
|
||||
blocks: Vec::new(),
|
||||
deltas: File::create(r.folder.join("deltas.bin"))?,
|
||||
delta_at: AtomicU64::new(0),
|
||||
lists: Vec::new(),
|
||||
submits: Vec::new(),
|
||||
presents: Vec::new(),
|
||||
present_file: File::create(r.folder.join("present.bin"))?,
|
||||
present_at: 0,
|
||||
calls: not_recorded_calls(),
|
||||
began: Instant::now(),
|
||||
took: BTreeMap::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn timed<T>(&mut self, what: &'static str, f: impl FnOnce(&mut Self) -> Result<T, Fault>) -> Result<T, Fault> {
|
||||
let began = Instant::now();
|
||||
let out = f(self);
|
||||
*self.took.entry(what).or_default() += began.elapsed();
|
||||
out
|
||||
}
|
||||
|
||||
/// Before the first submission of the frame: what the card holds.
|
||||
fn start(&mut self, r: &Recorder) -> Result<(), Fault> {
|
||||
self.began = Instant::now();
|
||||
r.watching.store(true, Ordering::SeqCst);
|
||||
self.started = true;
|
||||
self.worker.idle()?;
|
||||
for w in &mut self.others {
|
||||
w.idle()?;
|
||||
}
|
||||
let mut all: Vec<Arc<Res>> = Vec::new();
|
||||
{
|
||||
let live = read(&r.resources);
|
||||
for res in live.values() {
|
||||
let object = res.object();
|
||||
// SAFETY: a live resource, or one whose end waits for the
|
||||
// lock held here (`Recorder::gone`): the count tells which.
|
||||
let count = unsafe { (Interface::vtable(&*object).base__.base__.base__.base__.AddRef)(object.as_raw()) };
|
||||
if count <= 1 {
|
||||
// Dying: the reference does not bring it back, and
|
||||
// giving it back would end it a second time.
|
||||
continue;
|
||||
}
|
||||
// SAFETY: the reference just taken.
|
||||
self.held.push(unsafe { ID3D12Resource::from_raw(object.as_raw()) });
|
||||
all.push(res.clone());
|
||||
}
|
||||
}
|
||||
all.sort_by_key(|res| res.id);
|
||||
self.states = lock(&r.states).clone();
|
||||
self.idle = self.find_idle(&all);
|
||||
self.timed("contents of the card's memory", |c| c.snapshot(r, &all))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Of placed resources that overlap, those that are not the one used
|
||||
/// last.
|
||||
fn find_idle(&self, all: &[Arc<Res>]) -> HashSet<u32> {
|
||||
let mut heaps: HashMap<u32, Vec<(u64, u64, u64, u32)>> = HashMap::new();
|
||||
for res in all {
|
||||
if let Place::Placed { heap, offset } = res.place {
|
||||
// SAFETY: a plain query.
|
||||
let info = unsafe { self.worker.device.GetResourceAllocationInfo(0, &[gpu::to_desc(&res.desc)]) };
|
||||
let size = if info.SizeInBytes == u64::MAX { res.desc.width } else { info.SizeInBytes };
|
||||
let used = self.states.used.get(&res.id).copied().unwrap_or(0);
|
||||
heaps.entry(heap).or_default().push((used, offset, offset + size, res.id));
|
||||
}
|
||||
}
|
||||
let mut idle = HashSet::new();
|
||||
for (_, mut list) in heaps {
|
||||
list.sort_by(|a, b| b.cmp(a));
|
||||
let mut taken: BTreeMap<u64, u64> = BTreeMap::new();
|
||||
for (_, from, to, id) in list {
|
||||
let overlaps = taken.range(..to).next_back().is_some_and(|(_, &end)| end > from);
|
||||
if overlaps {
|
||||
idle.insert(id);
|
||||
} else {
|
||||
taken.insert(from, to);
|
||||
}
|
||||
}
|
||||
}
|
||||
idle
|
||||
}
|
||||
|
||||
fn snapshot(&mut self, r: &Recorder, all: &[Arc<Res>]) -> Result<(), Fault> {
|
||||
let device = self.worker.device.clone();
|
||||
let mut pieces: Vec<Piece> = Vec::new();
|
||||
for res in all.iter().filter(|res| res.seen == Seen::No) {
|
||||
if matches!(res.place, Place::BackBuffer {}) || self.idle.contains(&res.id) {
|
||||
continue;
|
||||
}
|
||||
if res.is_buffer() {
|
||||
let mut at = 0;
|
||||
while at < res.desc.width {
|
||||
let len = PIECE.min(res.desc.width - at);
|
||||
pieces.push(Piece { res: res.clone(), first: at, count: 1, len, at: 0 });
|
||||
at += len;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if res.desc.samples[0] > 1 {
|
||||
r.problem("contents of multisampled textures are not in the capture");
|
||||
continue;
|
||||
}
|
||||
let desc = gpu::to_desc(&res.desc);
|
||||
let (_, total) = gpu::footprints(&device, &desc, 0, res.subs);
|
||||
if total == u64::MAX {
|
||||
r.problem("contents of a texture without a copyable layout are not in the capture");
|
||||
} else if total <= STAGING {
|
||||
pieces.push(Piece { res: res.clone(), first: 0, count: res.subs, len: total, at: 0 });
|
||||
} else {
|
||||
for sub in 0..res.subs {
|
||||
let (_, len) = gpu::footprints(&device, &desc, sub, 1);
|
||||
if len <= STAGING {
|
||||
pieces.push(Piece { res: res.clone(), first: u64::from(sub), count: 1, len, at: 0 });
|
||||
} else {
|
||||
r.problem("contents of a texture level of over 256 MB are not in the capture");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Into batches, one read-back buffer each.
|
||||
let mut batches: Vec<Vec<Piece>> = vec![Vec::new()];
|
||||
let mut at = 0u64;
|
||||
for mut p in pieces {
|
||||
at = at.next_multiple_of(512);
|
||||
if at + p.len > STAGING {
|
||||
batches.push(Vec::new());
|
||||
at = 0;
|
||||
}
|
||||
p.at = at;
|
||||
at += p.len;
|
||||
if let Some(b) = batches.last_mut() {
|
||||
b.push(p);
|
||||
}
|
||||
}
|
||||
let mut stagings = Vec::new();
|
||||
for _ in 0..STAGINGS.min(batches.len()) {
|
||||
stagings.push(gpu::buffer(&device, D3D12_HEAP_TYPE_READBACK, STAGING, D3D12_RESOURCE_FLAG_NONE)?);
|
||||
}
|
||||
let file = File::create(r.folder.join("contents.bin"))?;
|
||||
let end = AtomicU64::new(0);
|
||||
let contents: std::sync::Mutex<Vec<Content>> = std::sync::Mutex::default();
|
||||
let failed: std::sync::Mutex<Option<std::io::Error>> = std::sync::Mutex::default();
|
||||
let (todo, work) = std::sync::mpsc::channel::<(usize, Vec<Piece>)>();
|
||||
let work = std::sync::Mutex::new(work);
|
||||
let (free, freed) = std::sync::mpsc::channel::<usize>();
|
||||
for i in 0..stagings.len() {
|
||||
free.send(i)?;
|
||||
}
|
||||
let maps: Vec<usize> = stagings.iter().map(|s| s.1 as usize).collect();
|
||||
std::thread::scope(|scope| -> Result<(), Fault> {
|
||||
for _ in 0..stagings.len() {
|
||||
let (work, free, maps, file, end, contents, failed) = (&work, free.clone(), &maps, &file, &end, &contents, &failed);
|
||||
scope.spawn(move || {
|
||||
loop {
|
||||
let next = lock(work).recv();
|
||||
let Ok((i, pieces)) = next else { break };
|
||||
for p in pieces {
|
||||
// SAFETY: inside the buffer's mapping; the copy
|
||||
// into it has run.
|
||||
let bytes = unsafe { std::slice::from_raw_parts((maps[i] + p.at as usize) as *const u8, p.len as usize) };
|
||||
let at = if zero(bytes) { ZERO } else { end.fetch_add(p.len, Ordering::Relaxed) };
|
||||
if at != ZERO
|
||||
&& let Err(e) = write_at(file, bytes, at)
|
||||
{
|
||||
lock(failed).get_or_insert(e);
|
||||
}
|
||||
lock(contents).push(Content { res: p.res.id, first: p.first, count: p.count, len: p.len, file: at });
|
||||
}
|
||||
let _ = free.send(i);
|
||||
}
|
||||
});
|
||||
}
|
||||
// Moved in: the writers end when it goes.
|
||||
let todo = todo;
|
||||
for pieces in batches {
|
||||
if pieces.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let i = freed.recv()?;
|
||||
let value = self.worker.send(|list| copy_out(&device, list, &self.states, &pieces, &stagings[i].0))?;
|
||||
self.worker.wait(value)?;
|
||||
todo.send((i, pieces))?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
if let Some(e) = lock(&failed).take() {
|
||||
return Err(e.into());
|
||||
}
|
||||
self.contents = contents.into_inner().unwrap_or_else(|e| e.into_inner());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Buffers the CPU sees that were not known yet.
|
||||
fn new_buffers(&mut self, r: &Recorder) -> Result<(), Fault> {
|
||||
let fresh: Vec<Arc<Res>> = read(&r.resources)
|
||||
.values()
|
||||
.filter(|res| matches!(res.seen, Seen::Cached | Seen::Combined) && !self.known.contains(&res.id))
|
||||
.cloned()
|
||||
.collect();
|
||||
for res in fresh {
|
||||
self.known.insert(res.id);
|
||||
if !res.is_buffer() {
|
||||
r.problem("contents of textures in memory the CPU sees are not in the capture");
|
||||
continue;
|
||||
}
|
||||
// Those alive at the start are held, those made since too.
|
||||
let object = ID3D12Resource::clone(&res.object());
|
||||
let size = res.desc.width as usize;
|
||||
let (live, through) = if res.seen == Seen::Cached {
|
||||
let mut data = std::ptr::null_mut();
|
||||
// SAFETY: a live buffer in memory the CPU sees.
|
||||
unsafe { object.Map(0, None, Some(&mut data))? };
|
||||
(data.cast::<u8>().cast_const(), None)
|
||||
} else {
|
||||
let room = self.blocks.iter().position(|b| b.3 + size as u64 <= b.2);
|
||||
let i = match room {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
let len = STAGING.max(size as u64);
|
||||
let (b, data) = gpu::buffer(&self.worker.device, D3D12_HEAP_TYPE_READBACK, len, D3D12_RESOURCE_FLAG_NONE)?;
|
||||
self.blocks.push((b, data as usize, len, 0));
|
||||
self.blocks.len() - 1
|
||||
}
|
||||
};
|
||||
let b = &mut self.blocks[i];
|
||||
let at = b.3;
|
||||
b.3 = (at + size as u64).next_multiple_of(256);
|
||||
((b.1 + at as usize) as *const u8, Some((i, at)))
|
||||
};
|
||||
self.buffers.push(CpuBuffer { id: res.id, res: object, live, through, size, kept: vec![0; size] });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What changed in buffers the CPU sees since the submission before.
|
||||
fn changed(&mut self, r: &Recorder) -> Result<Vec<Delta>, Fault> {
|
||||
self.new_buffers(r)?;
|
||||
if self.buffers.iter().any(|b| b.through.is_some()) {
|
||||
let (buffers, blocks) = (&self.buffers, &self.blocks);
|
||||
self.worker.run(|list| {
|
||||
for b in buffers {
|
||||
if let Some((i, at)) = b.through {
|
||||
// SAFETY: an open list and live buffers.
|
||||
unsafe { list.CopyBufferRegion(&blocks[i].0, at, &b.res, 0, b.size as u64) };
|
||||
}
|
||||
}
|
||||
})?;
|
||||
}
|
||||
let chunks: Vec<(usize, usize)> =
|
||||
self.buffers.iter().enumerate().flat_map(|(i, b)| (0..b.size).step_by(CHUNK).map(move |at| (i, at))).collect();
|
||||
// Each chunk is one thread's; threads share what is kept by parts.
|
||||
struct Kept(*mut u8);
|
||||
// SAFETY: parts of it are used by one thread each.
|
||||
unsafe impl Sync for Kept {}
|
||||
let kept: Vec<Kept> = self.buffers.iter_mut().map(|b| Kept(b.kept.as_mut_ptr())).collect();
|
||||
let next = AtomicUsize::new(0);
|
||||
let out: std::sync::Mutex<Vec<Delta>> = std::sync::Mutex::default();
|
||||
let failed: std::sync::Mutex<Option<std::io::Error>> = std::sync::Mutex::default();
|
||||
let threads = std::thread::available_parallelism().map_or(4, |n| n.get() / 2).clamp(1, 16).min(chunks.len().max(1));
|
||||
let (buffers, file, end) = (&self.buffers, &self.deltas, &self.delta_at);
|
||||
std::thread::scope(|scope| {
|
||||
for _ in 0..threads {
|
||||
scope.spawn(|| {
|
||||
let mut mine = Vec::new();
|
||||
loop {
|
||||
let i = next.fetch_add(1, Ordering::Relaxed);
|
||||
let Some(&(b, at)) = chunks.get(i) else { break };
|
||||
let len = CHUNK.min(buffers[b].size - at);
|
||||
// SAFETY: a chunk of the buffer's memory (it may
|
||||
// change meanwhile: what is kept is what was read)
|
||||
// and of what is kept, which no other thread has.
|
||||
let runs = unsafe { changed_runs(buffers[b].live.add(at), kept[b].0.add(at), len) };
|
||||
for (from, to) in runs {
|
||||
// SAFETY: as above.
|
||||
let bytes = unsafe { std::slice::from_raw_parts(kept[b].0.add(at + from), to - from) };
|
||||
let file_at = end.fetch_add(bytes.len() as u64, Ordering::Relaxed);
|
||||
if let Err(e) = write_at(file, bytes, file_at) {
|
||||
lock(&failed).get_or_insert(e);
|
||||
}
|
||||
mine.push(Delta { res: buffers[b].id, at: (at + from) as u64, len: bytes.len() as u64, file: file_at });
|
||||
}
|
||||
}
|
||||
lock(&out).extend(mine);
|
||||
});
|
||||
}
|
||||
});
|
||||
if let Some(e) = lock(&failed).take() {
|
||||
return Err(e.into());
|
||||
}
|
||||
let mut out = out.into_inner().unwrap_or_else(|e| e.into_inner());
|
||||
out.sort_by_key(|d| (d.res, d.at));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn submit(&mut self, r: &Recorder, _queue: &ID3D12CommandQueue, lists: &[Option<Arc<Vec<u8>>>]) -> Result<(), Fault> {
|
||||
let first = !self.started;
|
||||
if first {
|
||||
self.start(r)?;
|
||||
} else {
|
||||
self.timed("waiting for the card", |c| Ok(c.worker.idle()?))?;
|
||||
}
|
||||
let deltas = self.timed("what the CPU changed", |c| c.changed(r))?;
|
||||
// Descriptors last: their memory is ready now.
|
||||
let mut written = std::mem::take(&mut *lock(&r.writes));
|
||||
let mut views = Vec::new();
|
||||
if first {
|
||||
let heaps: Vec<Arc<Heap>> = read(&r.descriptors).visible().cloned().collect();
|
||||
for h in heaps {
|
||||
let runs = runs_of(r, &h.all());
|
||||
self.heaps.push((h, runs));
|
||||
}
|
||||
} else {
|
||||
written.sort_unstable();
|
||||
let mut seen = HashSet::new();
|
||||
for (heap, at, n) in written {
|
||||
let h = match self.heaps.iter().find(|(h, _)| h.id == heap) {
|
||||
Some((h, _)) => h.clone(),
|
||||
None => {
|
||||
let found = read(&r.descriptors).visible().find(|h| h.id == heap).cloned();
|
||||
let Some(h) = found else { continue };
|
||||
self.heaps.push((h.clone(), Vec::new()));
|
||||
h
|
||||
}
|
||||
};
|
||||
for i in at..at + n {
|
||||
if seen.insert((heap, i)) {
|
||||
views.push((heap, i, resolved(r, h.get(i))));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut numbers = Vec::new();
|
||||
for l in lists {
|
||||
numbers.push(match l {
|
||||
None => {
|
||||
r.problem("a list was submitted that was not recorded whole: its work is missing");
|
||||
MISSING
|
||||
}
|
||||
Some(commands) => match self.lists.iter().position(|have| Arc::ptr_eq(have, commands)) {
|
||||
Some(i) => i as u32,
|
||||
None => {
|
||||
self.lists.push(commands.clone());
|
||||
self.lists.len() as u32 - 1
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
self.submits.push(wire::Submit { frame: self.frame, lists: numbers, deltas, views });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn present(&mut self, r: &Recorder, texture: &ID3D12Resource, state: u32) -> Result<(), Fault> {
|
||||
self.worker.idle()?;
|
||||
// SAFETY: a live texture.
|
||||
let desc = unsafe { texture.GetDesc() };
|
||||
let (f, total) = gpu::footprints(&self.worker.device, &desc, 0, 1);
|
||||
let (back, data) = gpu::buffer(&self.worker.device, D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_FLAG_NONE)?;
|
||||
self.worker.run(|list| read_sub(list, texture, 0, state, &back, f[0]))?;
|
||||
// SAFETY: the buffer's mapping; the copy into it has run.
|
||||
let bytes = unsafe { std::slice::from_raw_parts(data, total as usize) };
|
||||
write_at(&self.present_file, bytes, self.present_at)?;
|
||||
let id = r.resource(texture.as_raw());
|
||||
let (width, height, pitch) = (desc.Width as u32, desc.Height, f[0].Footprint.RowPitch);
|
||||
self.presents.push(wire::Present {
|
||||
submits: self.submits.len() as u32,
|
||||
res: id,
|
||||
width,
|
||||
height,
|
||||
format: desc.Format.0,
|
||||
pitch,
|
||||
file: self.present_at,
|
||||
});
|
||||
self.present_at += total;
|
||||
match gpu::rgb(width, height, pitch, desc.Format.0, bytes) {
|
||||
Some(rgb) => std::fs::write(r.folder.join(format!("frame-{}.png", self.frame)), crate::capture::png(width, height, &rgb))?,
|
||||
None => r.problem("the presented format is not shown in a PNG"),
|
||||
}
|
||||
self.frame += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes `frame.bin`.
|
||||
fn finish(&mut self, r: &Recorder) -> Result<(), Fault> {
|
||||
let mut resources: Vec<wire::Resource> = Vec::new();
|
||||
{
|
||||
let names = lock(&r.names);
|
||||
for res in read(&r.resources).values() {
|
||||
let state = match (res.is_buffer(), res.late) {
|
||||
(true, _) => vec![COMMON],
|
||||
(_, true) => vec![res.made_in as u32],
|
||||
_ => self.states.get(res.id).unwrap_or(vec![COMMON]),
|
||||
};
|
||||
resources.push(wire::Resource {
|
||||
id: res.id,
|
||||
place: res.place.clone(),
|
||||
desc: res.desc.clone(),
|
||||
made_in: res.made_in,
|
||||
clear: res.clear,
|
||||
state,
|
||||
idle: self.idle.contains(&res.id),
|
||||
late: res.late,
|
||||
name: names.get(&res.id).cloned().unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
}
|
||||
resources.sort_by_key(|res| res.id);
|
||||
let mut heaps: Vec<wire::Heap> = {
|
||||
let all = lock(&r.heaps);
|
||||
let used: HashSet<u32> =
|
||||
resources.iter().filter_map(|res| if let Place::Placed { heap, .. } = res.place { Some(heap) } else { None }).collect();
|
||||
used.iter().filter_map(|id| all.get(id).cloned()).collect()
|
||||
};
|
||||
heaps.sort_by_key(|h| h.id);
|
||||
// What the lists name.
|
||||
let (mut psos, mut roots, mut signatures, mut queries) = (HashSet::new(), HashSet::new(), HashSet::new(), HashSet::new());
|
||||
for l in &self.lists {
|
||||
for c in Cmd::all(l)? {
|
||||
match c {
|
||||
Cmd::Pipeline { pso } => drop(psos.insert(pso)),
|
||||
Cmd::RootSignature { root, .. } => drop(roots.insert(root)),
|
||||
Cmd::Indirect { signature, .. } => drop(signatures.insert(signature)),
|
||||
Cmd::BeginQuery { heap, .. } | Cmd::EndQuery { heap, .. } | Cmd::ResolveQuery { heap, .. } => drop(queries.insert(heap)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let pipelines: Vec<wire::Pipeline> = {
|
||||
let all = lock(&r.pipelines);
|
||||
let names = lock(&r.names);
|
||||
let mut out: Vec<wire::Pipeline> = psos
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let parts = all.get(id)?;
|
||||
Some(wire::Pipeline { id: *id, parts: parts.to_vec(), name: names.get(id).cloned().unwrap_or_default() })
|
||||
})
|
||||
.collect();
|
||||
out.sort_by_key(|p| p.id);
|
||||
out
|
||||
};
|
||||
roots.extend(pipelines.iter().flat_map(|p| &p.parts).filter_map(|p| if let wire::Part::Root { root } = p { Some(*root) } else { None }));
|
||||
let signatures: Vec<wire::Signature> = {
|
||||
let all = lock(&r.signatures);
|
||||
signatures.iter().filter_map(|id| all.get(id).cloned()).collect()
|
||||
};
|
||||
roots.extend(signatures.iter().map(|s| s.root));
|
||||
roots.remove(&NONE);
|
||||
let roots: Vec<(u32, wire::Blob)> = {
|
||||
let all = lock(&r.roots);
|
||||
roots.iter().filter_map(|id| Some((*id, wire::Blob(all.get(id)?.to_vec())))).collect()
|
||||
};
|
||||
for ((what, before), (_, now)) in self.calls.iter().zip(not_recorded_calls()) {
|
||||
if now > *before {
|
||||
r.problem_times(what, now - before);
|
||||
}
|
||||
}
|
||||
let (adapter, vendor, device) = gpu::adapter(&self.worker.device);
|
||||
let mut notes = r.problems();
|
||||
let bytes: u64 = self.contents.iter().filter(|c| c.file != ZERO).map(|c| c.len).sum();
|
||||
notes.push(format!(
|
||||
"{} submissions, {} lists, {} resources, {} pipelines; {} MB of the card's memory, {} MB of changes by the CPU; {:.1} s: {}",
|
||||
self.submits.len(),
|
||||
self.lists.len(),
|
||||
resources.len(),
|
||||
pipelines.len(),
|
||||
bytes >> 20,
|
||||
self.delta_at.load(Ordering::Relaxed) >> 20,
|
||||
self.began.elapsed().as_secs_f64(),
|
||||
self.took.iter().map(|(what, d)| format!("{what} {:.1} s", d.as_secs_f64())).collect::<Vec<_>>().join(", ")
|
||||
));
|
||||
for n in ¬es {
|
||||
tracing::info!("frame recorder: {n}");
|
||||
}
|
||||
let frame = wire::Frame {
|
||||
adapter,
|
||||
vendor,
|
||||
device,
|
||||
notes: notes.clone(),
|
||||
heaps,
|
||||
resources,
|
||||
roots,
|
||||
codes: lock(&r.codes).all.clone(),
|
||||
pipelines,
|
||||
signatures,
|
||||
descriptor_heaps: self
|
||||
.heaps
|
||||
.iter()
|
||||
.map(|(h, runs)| wire::DescriptorHeap { id: h.id, kind: h.kind, count: h.count, flags: h.flags, runs: runs.clone() })
|
||||
.collect(),
|
||||
query_heaps: {
|
||||
let all = lock(&r.queries);
|
||||
queries.iter().filter_map(|id| all.get(id).cloned()).collect()
|
||||
},
|
||||
lists: self
|
||||
.lists
|
||||
.iter()
|
||||
.map(|l| wire::List { kind: D3D12_COMMAND_LIST_TYPE_DIRECT.0, commands: wire::Blob(l.to_vec()) })
|
||||
.collect(),
|
||||
submits: std::mem::take(&mut self.submits),
|
||||
contents: std::mem::take(&mut self.contents),
|
||||
presents: std::mem::take(&mut self.presents),
|
||||
};
|
||||
frame.write(&r.folder.join("frame.bin"))?;
|
||||
std::fs::write(r.folder.join("notes.txt"), notes.join("\n"))?;
|
||||
tracing::info!(folder = %r.folder.display(), "frame recorder: the frame is captured");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A part of a resource in a read-back buffer, `at` bytes in.
|
||||
struct Piece {
|
||||
res: Arc<Res>,
|
||||
first: u64,
|
||||
count: u32,
|
||||
len: u64,
|
||||
at: u64,
|
||||
}
|
||||
|
||||
/// Records the copies of `pieces` into `to`. Textures are moved to a state
|
||||
/// they can be copied from and back.
|
||||
fn copy_out(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, states: &States, pieces: &[Piece], to: &ID3D12Resource) {
|
||||
let (mut before, mut after) = (Vec::new(), Vec::new());
|
||||
let mut seen = HashSet::new();
|
||||
for p in pieces.iter().filter(|p| !p.res.is_buffer()) {
|
||||
if !seen.insert(p.res.id) {
|
||||
continue;
|
||||
}
|
||||
let from = states.get(p.res.id).unwrap_or(vec![COMMON]);
|
||||
// From the common state a texture is promoted by the copy.
|
||||
let to: Vec<u32> = from.iter().map(|&s| if s == COMMON || s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }).collect();
|
||||
gpu::moves(&p.res.object(), &from, &to, &mut before);
|
||||
gpu::moves(&p.res.object(), &to, &from, &mut after);
|
||||
}
|
||||
// SAFETY: an open list; live resources.
|
||||
unsafe {
|
||||
if !before.is_empty() {
|
||||
list.ResourceBarrier(&before);
|
||||
}
|
||||
for p in pieces {
|
||||
let object = p.res.object();
|
||||
if p.res.is_buffer() {
|
||||
list.CopyBufferRegion(to, p.at, &*object, p.first, p.len);
|
||||
continue;
|
||||
}
|
||||
let (all, _) = gpu::footprints(device, &gpu::to_desc(&p.res.desc), p.first as u32, p.count);
|
||||
for (i, mut f) in all.into_iter().enumerate() {
|
||||
f.Offset += p.at;
|
||||
list.CopyTextureRegion(&gpu::placed_location(to, f), 0, 0, 0, &gpu::sub_location(&object, p.first as u32 + i as u32), None);
|
||||
}
|
||||
}
|
||||
if !after.is_empty() {
|
||||
list.ResourceBarrier(&after);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the copy of a texture's subresource, in `state`, into `to`.
|
||||
pub(super) fn read_sub(
|
||||
list: &ID3D12GraphicsCommandList,
|
||||
texture: &ID3D12Resource,
|
||||
sub: u32,
|
||||
state: u32,
|
||||
to: &ID3D12Resource,
|
||||
f: D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
|
||||
) {
|
||||
let there = state == COMMON || state & COPY_SOURCE != 0;
|
||||
// SAFETY: an open list; live resources.
|
||||
unsafe {
|
||||
if !there {
|
||||
list.ResourceBarrier(&[gpu::transition(texture, ALL, state, COPY_SOURCE)]);
|
||||
}
|
||||
list.CopyTextureRegion(&gpu::placed_location(to, f), 0, 0, 0, &gpu::sub_location(texture, sub), None);
|
||||
if !there {
|
||||
list.ResourceBarrier(&[gpu::transition(texture, ALL, COPY_SOURCE, state)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A slot as it goes into the file: a constant buffer view's address as
|
||||
/// buffer and offset.
|
||||
fn resolved(r: &Recorder, mut s: Slot) -> Slot {
|
||||
if s.kind == slot::CBV && s.described != 0 {
|
||||
match r.va(s.address()) {
|
||||
Va::At { res, offset } => {
|
||||
s.res = res;
|
||||
s.set_address(offset);
|
||||
}
|
||||
Va::Null {} => {}
|
||||
Va::Unknown { .. } => {
|
||||
// Its buffer is gone: nothing may read it.
|
||||
s = Slot { kind: slot::CBV, ..Slot::EMPTY };
|
||||
}
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The slots as runs of equal ones, empty ones left out.
|
||||
fn runs_of(r: &Recorder, all: &[Slot]) -> Vec<(u32, u32, Slot)> {
|
||||
let mut runs: Vec<(u32, u32, Slot)> = Vec::new();
|
||||
for (i, s) in all.iter().enumerate() {
|
||||
if s.kind == slot::EMPTY {
|
||||
continue;
|
||||
}
|
||||
match runs.last_mut() {
|
||||
Some((first, n, same)) if *first + *n == i as u32 && same == s => *n += 1,
|
||||
_ => runs.push((i as u32, 1, *s)),
|
||||
}
|
||||
}
|
||||
for run in &mut runs {
|
||||
run.2 = resolved(r, run.2);
|
||||
}
|
||||
runs
|
||||
}
|
||||
|
||||
/// Whether all bytes are zero.
|
||||
fn zero(bytes: &[u8]) -> bool {
|
||||
// SAFETY: any bytes are a number.
|
||||
let (a, b, c) = unsafe { bytes.align_to::<u128>() };
|
||||
a.iter().chain(c).all(|&x| x == 0) && b.iter().all(|&x| x == 0)
|
||||
}
|
||||
|
||||
fn write_at(file: &File, mut bytes: &[u8], mut at: u64) -> std::io::Result<()> {
|
||||
while !bytes.is_empty() {
|
||||
let n = file.seek_write(bytes, at)?;
|
||||
if n == 0 {
|
||||
return Err(std::io::ErrorKind::WriteZero.into());
|
||||
}
|
||||
bytes = &bytes[n..];
|
||||
at += n as u64;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Compares `len` bytes at `live` with those at `kept`, page by page, brings
|
||||
/// the changed ones in `kept` up to date, and answers their runs.
|
||||
///
|
||||
/// # Safety
|
||||
/// Both are `len` bytes; `kept` is the caller's alone.
|
||||
unsafe fn changed_runs(live: *const u8, kept: *mut u8, len: usize) -> Vec<(usize, usize)> {
|
||||
let mut runs: Vec<(usize, usize)> = Vec::new();
|
||||
let mut at = 0;
|
||||
while at < len {
|
||||
let n = PAGE.min(len - at);
|
||||
// SAFETY: the caller's.
|
||||
unsafe {
|
||||
let same = std::slice::from_raw_parts(live.add(at), n) == std::slice::from_raw_parts(kept.add(at), n);
|
||||
if !same {
|
||||
std::ptr::copy_nonoverlapping(live.add(at), kept.add(at), n);
|
||||
match runs.last_mut() {
|
||||
Some(last) if last.1 == at => last.1 = at + n,
|
||||
_ => runs.push((at, at + n)),
|
||||
}
|
||||
}
|
||||
}
|
||||
at += n;
|
||||
}
|
||||
runs
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn changes_are_found_by_page() {
|
||||
let mut live = vec![0u8; 5 * PAGE + 100];
|
||||
let mut kept = live.clone();
|
||||
let find = |live: &[u8], kept: &mut [u8]| {
|
||||
// SAFETY: two arrays of one length.
|
||||
unsafe { changed_runs(live.as_ptr(), kept.as_mut_ptr(), live.len()) }
|
||||
};
|
||||
assert!(find(&live, &mut kept).is_empty());
|
||||
live[PAGE + 5] = 1;
|
||||
live[2 * PAGE] = 2;
|
||||
live[5 * PAGE + 99] = 3;
|
||||
assert_eq!(find(&live, &mut kept), [(PAGE, 3 * PAGE), (5 * PAGE, 5 * PAGE + 100)]);
|
||||
assert_eq!(live, kept);
|
||||
assert!(find(&live, &mut kept).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zeros() {
|
||||
assert!(zero(&[]));
|
||||
assert!(zero(&[0; 1001]));
|
||||
for i in [0, 7, 500, 1000] {
|
||||
let mut b = [0u8; 1001];
|
||||
b[i] = 1;
|
||||
assert!(!zero(&b));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
//! The states textures are in, as lists that ran left them: from the
|
||||
//! barriers, the copies that promote a texture out of the common state, and
|
||||
//! the decay at the end of a submission. Buffers are in the common state
|
||||
//! between submissions, always, and are not kept here.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::wire::{ALL, Barrier, Cmd, Loc};
|
||||
|
||||
pub const COMMON: u32 = 0;
|
||||
pub const RENDER_TARGET: u32 = 0x4;
|
||||
pub const UNORDERED_ACCESS: u32 = 0x8;
|
||||
pub const DEPTH_WRITE: u32 = 0x10;
|
||||
pub const COPY_DEST: u32 = 0x400;
|
||||
pub const COPY_SOURCE: u32 = 0x800;
|
||||
pub const RESOLVE_DEST: u32 = 0x1000;
|
||||
|
||||
/// A change of state a list makes, to apply when it runs.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Change {
|
||||
pub res: u32,
|
||||
pub sub: u32,
|
||||
pub after: u32,
|
||||
/// A copy into it: it is in the copy-destination state afterwards if it
|
||||
/// was in the common state, else as it was.
|
||||
pub promoted: bool,
|
||||
/// An aliasing barrier made it the one in use.
|
||||
pub alias: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct One {
|
||||
subs: u32,
|
||||
/// Decays to the common state after each submission.
|
||||
decays: bool,
|
||||
all: u32,
|
||||
each: Vec<u32>,
|
||||
}
|
||||
|
||||
/// The states of textures, by id.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct States {
|
||||
map: HashMap<u32, One>,
|
||||
touched: Vec<u32>,
|
||||
/// When a placed resource was last the one in use (made, or named by an
|
||||
/// aliasing barrier), by id; higher is later.
|
||||
pub used: HashMap<u32, u64>,
|
||||
clock: u64,
|
||||
}
|
||||
|
||||
impl States {
|
||||
/// A texture of `subs` subresources starts in `state`.
|
||||
pub fn add(&mut self, res: u32, subs: u32, state: u32, decays: bool) {
|
||||
self.map.insert(res, One { subs: subs.max(1), decays, all: state, each: Vec::new() });
|
||||
}
|
||||
|
||||
/// A placed resource is the one in use now.
|
||||
pub fn in_use(&mut self, res: u32) {
|
||||
self.clock += 1;
|
||||
self.used.insert(res, self.clock);
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, res: u32) {
|
||||
self.map.remove(&res);
|
||||
self.used.remove(&res);
|
||||
}
|
||||
|
||||
/// One state, or one for each subresource.
|
||||
pub fn get(&self, res: u32) -> Option<Vec<u32>> {
|
||||
let one = self.map.get(&res)?;
|
||||
Some(if one.each.is_empty() { vec![one.all] } else { one.each.clone() })
|
||||
}
|
||||
|
||||
pub fn change(&mut self, c: &Change) {
|
||||
if c.alias {
|
||||
self.in_use(c.res);
|
||||
return;
|
||||
}
|
||||
let Some(one) = self.map.get_mut(&c.res) else {
|
||||
return;
|
||||
};
|
||||
let new = |old: u32| match (c.promoted, old) {
|
||||
(true, COMMON) => COPY_DEST,
|
||||
(true, old) => old,
|
||||
(false, _) => c.after,
|
||||
};
|
||||
if c.sub == ALL || one.subs == 1 {
|
||||
one.all = new(one.all);
|
||||
if c.promoted {
|
||||
one.each.iter_mut().for_each(|s| *s = new(*s));
|
||||
} else {
|
||||
one.each.clear();
|
||||
}
|
||||
} else if c.sub < one.subs {
|
||||
if one.each.is_empty() {
|
||||
one.each = vec![one.all; one.subs as usize];
|
||||
}
|
||||
let s = &mut one.each[c.sub as usize];
|
||||
*s = new(*s);
|
||||
if one.each.iter().all(|s| *s == one.each[0]) {
|
||||
one.all = one.each[0];
|
||||
one.each.clear();
|
||||
}
|
||||
}
|
||||
if one.decays {
|
||||
self.touched.push(c.res);
|
||||
}
|
||||
}
|
||||
|
||||
/// The end of a submission (one `ExecuteCommandLists`).
|
||||
pub fn decay(&mut self) {
|
||||
for res in std::mem::take(&mut self.touched) {
|
||||
if let Some(one) = self.map.get_mut(&res) {
|
||||
one.all = COMMON;
|
||||
one.each.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The changes a command makes.
|
||||
pub fn changes(cmd: &Cmd, out: &mut Vec<Change>) {
|
||||
let promoted = |res, sub| Change { res, sub, after: COPY_DEST, promoted: true, alias: false };
|
||||
match cmd {
|
||||
Cmd::Barriers { all } => {
|
||||
for b in all {
|
||||
match *b {
|
||||
// The first half of a split barrier changes nothing yet.
|
||||
Barrier::Transition { flags, res, sub, after, .. } if flags & 1 == 0 => {
|
||||
out.push(Change { res, sub, after: after as u32, promoted: false, alias: false });
|
||||
}
|
||||
Barrier::Alias { after, .. } if after != 0 => {
|
||||
out.push(Change { res: after, sub: ALL, after: 0, promoted: false, alias: true });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Cmd::CopyTexture { dst: Loc::Sub { res, sub }, .. } => out.push(promoted(*res, *sub)),
|
||||
Cmd::CopyResource { dst, .. } => out.push(promoted(*dst, ALL)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn set(res: u32, sub: u32, after: u32) -> Change {
|
||||
Change { res, sub, after, promoted: false, alias: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn states_are_followed() {
|
||||
let mut s = States::default();
|
||||
s.add(1, 4, COPY_DEST, false);
|
||||
s.add(2, 1, COMMON, false);
|
||||
s.add(3, 2, COMMON, true);
|
||||
assert_eq!(s.get(1), Some(vec![COPY_DEST]));
|
||||
s.change(&set(1, 2, 0x80));
|
||||
assert_eq!(s.get(1), Some(vec![COPY_DEST, COPY_DEST, 0x80, COPY_DEST]));
|
||||
for sub in [0, 1, 3] {
|
||||
s.change(&set(1, sub, 0x80));
|
||||
}
|
||||
assert_eq!(s.get(1), Some(vec![0x80]), "equal states are one again");
|
||||
// A copy into a texture in the common state leaves it a copy
|
||||
// destination; one into a texture in another state changes nothing.
|
||||
let copy = |res| Change { res, sub: ALL, after: COPY_DEST, promoted: true, alias: false };
|
||||
s.change(©(2));
|
||||
s.change(©(1));
|
||||
s.decay();
|
||||
assert_eq!(s.get(2), Some(vec![COPY_DEST]));
|
||||
assert_eq!(s.get(1), Some(vec![0x80]));
|
||||
// Simultaneous access decays.
|
||||
s.change(&set(3, 1, UNORDERED_ACCESS));
|
||||
assert_eq!(s.get(3), Some(vec![COMMON, UNORDERED_ACCESS]));
|
||||
s.decay();
|
||||
assert_eq!(s.get(3), Some(vec![COMMON]));
|
||||
s.remove(3);
|
||||
assert_eq!(s.get(3), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_change_states() {
|
||||
let mut out = Vec::new();
|
||||
let t = |flags| Barrier::Transition { flags, res: 1, sub: 0, before: 4, after: 8 };
|
||||
changes(&Cmd::Barriers { all: vec![t(1), t(2), Barrier::Alias { flags: 0, before: 3, after: 4 }, Barrier::Uav { flags: 0, res: 1 }] }, &mut out);
|
||||
assert_eq!(out.len(), 2);
|
||||
assert_eq!(out[0], set(1, 0, 8));
|
||||
assert!(out[1].alias && out[1].res == 4);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,741 @@
|
||||
//! What a capture holds and how it is written: plain little-endian bytes,
|
||||
//! fields in order. Read on the machine that wrote it; nothing here is kept
|
||||
//! compatible between versions beyond the number in [`VERSION`].
|
||||
|
||||
/// Changes with every change of the layout.
|
||||
pub const VERSION: u32 = 1;
|
||||
/// The first bytes of `frame.bin`.
|
||||
pub const MAGIC: [u8; 8] = *b"VICFRAME";
|
||||
|
||||
/// Why bytes could not be read back.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Bad(pub &'static str);
|
||||
|
||||
impl std::fmt::Display for Bad {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "the capture cannot be read: {}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Bad {}
|
||||
|
||||
/// Bytes being read.
|
||||
pub struct Dec<'a> {
|
||||
pub bytes: &'a [u8],
|
||||
}
|
||||
|
||||
impl<'a> Dec<'a> {
|
||||
pub fn new(bytes: &'a [u8]) -> Self {
|
||||
Dec { bytes }
|
||||
}
|
||||
|
||||
pub fn take(&mut self, n: usize) -> Result<&'a [u8], Bad> {
|
||||
if self.bytes.len() < n {
|
||||
return Err(Bad("it ends too early"));
|
||||
}
|
||||
let (head, tail) = self.bytes.split_at(n);
|
||||
self.bytes = tail;
|
||||
Ok(head)
|
||||
}
|
||||
}
|
||||
|
||||
/// A value that can be written and read back.
|
||||
pub trait Wire: Sized {
|
||||
fn put(&self, out: &mut Vec<u8>);
|
||||
fn get(from: &mut Dec) -> Result<Self, Bad>;
|
||||
}
|
||||
|
||||
macro_rules! numbers {
|
||||
($($t:ty),*) => {$(
|
||||
impl Wire for $t {
|
||||
fn put(&self, out: &mut Vec<u8>) {
|
||||
out.extend_from_slice(&self.to_le_bytes());
|
||||
}
|
||||
fn get(from: &mut Dec) -> Result<Self, Bad> {
|
||||
let bytes = from.take(size_of::<$t>())?;
|
||||
Ok(<$t>::from_le_bytes(bytes.try_into().map_err(|_| Bad("a number"))?))
|
||||
}
|
||||
}
|
||||
)*};
|
||||
}
|
||||
numbers!(u8, u16, u32, i32, u64, f32);
|
||||
|
||||
impl Wire for bool {
|
||||
fn put(&self, out: &mut Vec<u8>) {
|
||||
out.push(u8::from(*self));
|
||||
}
|
||||
fn get(from: &mut Dec) -> Result<Self, Bad> {
|
||||
Ok(u8::get(from)? != 0)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Wire> Wire for Vec<T> {
|
||||
fn put(&self, out: &mut Vec<u8>) {
|
||||
(self.len() as u32).put(out);
|
||||
for x in self {
|
||||
x.put(out);
|
||||
}
|
||||
}
|
||||
fn get(from: &mut Dec) -> Result<Self, Bad> {
|
||||
let n = u32::get(from)? as usize;
|
||||
// At least a byte each: a wild count is refused, not allocated.
|
||||
if n > from.bytes.len() {
|
||||
return Err(Bad("a list longer than the file"));
|
||||
}
|
||||
(0..n).map(|_| T::get(from)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Wire> Wire for Option<T> {
|
||||
fn put(&self, out: &mut Vec<u8>) {
|
||||
self.is_some().put(out);
|
||||
if let Some(x) = self {
|
||||
x.put(out);
|
||||
}
|
||||
}
|
||||
fn get(from: &mut Dec) -> Result<Self, Bad> {
|
||||
Ok(if bool::get(from)? { Some(T::get(from)?) } else { None })
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Wire + Copy + Default, const N: usize> Wire for [T; N] {
|
||||
fn put(&self, out: &mut Vec<u8>) {
|
||||
for x in self {
|
||||
x.put(out);
|
||||
}
|
||||
}
|
||||
fn get(from: &mut Dec) -> Result<Self, Bad> {
|
||||
let mut all = [T::default(); N];
|
||||
for x in &mut all {
|
||||
*x = T::get(from)?;
|
||||
}
|
||||
Ok(all)
|
||||
}
|
||||
}
|
||||
|
||||
impl Wire for String {
|
||||
fn put(&self, out: &mut Vec<u8>) {
|
||||
(self.len() as u32).put(out);
|
||||
out.extend_from_slice(self.as_bytes());
|
||||
}
|
||||
fn get(from: &mut Dec) -> Result<Self, Bad> {
|
||||
let n = u32::get(from)? as usize;
|
||||
String::from_utf8(from.take(n)?.to_vec()).map_err(|_| Bad("a name that is not text"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes copied whole.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Default)]
|
||||
pub struct Blob(pub Vec<u8>);
|
||||
|
||||
impl Wire for Blob {
|
||||
fn put(&self, out: &mut Vec<u8>) {
|
||||
(self.0.len() as u64).put(out);
|
||||
out.extend_from_slice(&self.0);
|
||||
}
|
||||
fn get(from: &mut Dec) -> Result<Self, Bad> {
|
||||
let n = u64::get(from)? as usize;
|
||||
Ok(Blob(from.take(n)?.to_vec()))
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! tuples {
|
||||
($($t:ident $i:tt),*) => {
|
||||
impl<$($t: Wire),*> Wire for ($($t,)*) {
|
||||
fn put(&self, out: &mut Vec<u8>) {
|
||||
$(self.$i.put(out);)*
|
||||
}
|
||||
fn get(from: &mut Dec) -> Result<Self, Bad> {
|
||||
Ok(($($t::get(from)?,)*))
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
tuples!(A 0, B 1);
|
||||
tuples!(A 0, B 1, C 2);
|
||||
|
||||
macro_rules! wire_struct {
|
||||
($(#[$meta:meta])* $name:ident { $($(#[$fmeta:meta])* $f:ident : $t:ty),* $(,)? }) => {
|
||||
$(#[$meta])*
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct $name { $($(#[$fmeta])* pub $f: $t),* }
|
||||
impl Wire for $name {
|
||||
fn put(&self, out: &mut Vec<u8>) {
|
||||
$(self.$f.put(out);)*
|
||||
}
|
||||
fn get(from: &mut Dec) -> Result<Self, Bad> {
|
||||
Ok($name { $($f: <$t>::get(from)?),* })
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! wire_enum {
|
||||
($(#[$meta:meta])* $name:ident { $($(#[$vmeta:meta])* $tag:literal $var:ident { $($f:ident : $t:ty),* $(,)? }),* $(,)? }) => {
|
||||
$(#[$meta])*
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum $name { $($(#[$vmeta])* $var { $($f: $t),* }),* }
|
||||
impl Wire for $name {
|
||||
fn put(&self, out: &mut Vec<u8>) {
|
||||
match self {
|
||||
$($name::$var { $($f),* } => {
|
||||
out.push($tag);
|
||||
$($f.put(out);)*
|
||||
})*
|
||||
}
|
||||
}
|
||||
fn get(from: &mut Dec) -> Result<Self, Bad> {
|
||||
Ok(match u8::get(from)? {
|
||||
$($tag => $name::$var { $($f: <$t>::get(from)?),* },)*
|
||||
_ => return Err(Bad("a kind that does not exist")),
|
||||
})
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// No object.
|
||||
pub const NONE: u32 = 0;
|
||||
/// All subresources.
|
||||
pub const ALL: u32 = u32::MAX;
|
||||
|
||||
/// What a descriptor slot holds: the view last made in it. `res` and
|
||||
/// `counter` are object ids; `desc` the view's description as D3D12 lays it
|
||||
/// out (a sampler's is the longest: 52 bytes). In a capture file a constant
|
||||
/// buffer view's buffer is in `res` and, in place of the address, the
|
||||
/// offset in it.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Slot {
|
||||
pub kind: u8,
|
||||
/// Whether a description was given.
|
||||
pub described: u8,
|
||||
pub pad: u16,
|
||||
pub res: u32,
|
||||
pub counter: u32,
|
||||
pub desc: [u8; 52],
|
||||
}
|
||||
|
||||
/// Kinds of [`Slot`].
|
||||
pub mod slot {
|
||||
pub const EMPTY: u8 = 0;
|
||||
pub const CBV: u8 = 1;
|
||||
pub const SRV: u8 = 2;
|
||||
pub const UAV: u8 = 3;
|
||||
pub const SAMPLER: u8 = 4;
|
||||
pub const RTV: u8 = 5;
|
||||
pub const DSV: u8 = 6;
|
||||
}
|
||||
|
||||
impl Slot {
|
||||
pub const EMPTY: Slot = Slot { kind: slot::EMPTY, described: 0, pad: 0, res: NONE, counter: NONE, desc: [0; 52] };
|
||||
|
||||
/// A slot of `kind` with the description at `desc` (`size` bytes), if any.
|
||||
///
|
||||
/// # Safety
|
||||
/// `desc` is null or points at a description of `size` bytes.
|
||||
pub unsafe fn new(kind: u8, res: u32, counter: u32, desc: *const u8, size: usize) -> Slot {
|
||||
let mut s = Slot { kind, res, counter, ..Slot::EMPTY };
|
||||
if !desc.is_null() {
|
||||
s.described = 1;
|
||||
// SAFETY: the caller's description, at most 52 bytes of it.
|
||||
unsafe { std::ptr::copy_nonoverlapping(desc, s.desc.as_mut_ptr(), size.min(52)) };
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// A constant buffer view's address (or its offset, in a file).
|
||||
pub fn address(&self) -> u64 {
|
||||
u64::from_le_bytes([
|
||||
self.desc[0], self.desc[1], self.desc[2], self.desc[3], self.desc[4], self.desc[5], self.desc[6], self.desc[7],
|
||||
])
|
||||
}
|
||||
|
||||
pub fn set_address(&mut self, address: u64) {
|
||||
self.desc[..8].copy_from_slice(&address.to_le_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
impl Wire for Slot {
|
||||
fn put(&self, out: &mut Vec<u8>) {
|
||||
out.push(self.kind);
|
||||
out.push(self.described);
|
||||
self.res.put(out);
|
||||
self.counter.put(out);
|
||||
// Most descriptions are 40 bytes or less.
|
||||
let n = self.desc.iter().rposition(|&b| b != 0).map_or(0, |i| i + 1);
|
||||
out.push(n as u8);
|
||||
out.extend_from_slice(&self.desc[..n]);
|
||||
}
|
||||
fn get(from: &mut Dec) -> Result<Self, Bad> {
|
||||
let (kind, described) = (u8::get(from)?, u8::get(from)?);
|
||||
let (res, counter) = (u32::get(from)?, u32::get(from)?);
|
||||
let n = u8::get(from)? as usize;
|
||||
if n > 52 {
|
||||
return Err(Bad("a view's description"));
|
||||
}
|
||||
let mut desc = [0; 52];
|
||||
desc[..n].copy_from_slice(from.take(n)?);
|
||||
Ok(Slot { kind, described, pad: 0, res, counter, desc })
|
||||
}
|
||||
}
|
||||
|
||||
wire_enum! {
|
||||
/// A GPU address.
|
||||
Va {
|
||||
0 Null {},
|
||||
1 At { res: u32, offset: u64 },
|
||||
/// In no buffer the recorder knows.
|
||||
2 Unknown { address: u64 },
|
||||
}
|
||||
}
|
||||
|
||||
wire_enum! {
|
||||
/// One side of a texture copy.
|
||||
Loc {
|
||||
0 Sub { res: u32, sub: u32 },
|
||||
1 Placed { res: u32, offset: u64, format: i32, size: [u32; 3], pitch: u32 },
|
||||
}
|
||||
}
|
||||
|
||||
wire_enum! {
|
||||
/// One barrier of a `ResourceBarrier` call.
|
||||
Barrier {
|
||||
0 Transition { flags: i32, res: u32, sub: u32, before: i32, after: i32 },
|
||||
1 Alias { flags: i32, before: u32, after: u32 },
|
||||
2 Uav { flags: i32, res: u32 },
|
||||
}
|
||||
}
|
||||
|
||||
wire_enum! {
|
||||
/// A command of a list, objects by id, views by what they hold.
|
||||
Cmd {
|
||||
1 Draw { vertices: u32, instances: u32, first: u32, first_instance: u32 },
|
||||
2 DrawIndexed { indices: u32, instances: u32, first: u32, base: i32, first_instance: u32 },
|
||||
3 Dispatch { groups: [u32; 3] },
|
||||
4 DispatchMesh { groups: [u32; 3] },
|
||||
5 CopyBuffer { dst: u32, dst_at: u64, src: u32, src_at: u64, len: u64 },
|
||||
6 CopyTexture { dst: Loc, at: [u32; 3], src: Loc, part: Option<[u32; 6]> },
|
||||
7 CopyResource { dst: u32, src: u32 },
|
||||
8 Resolve { dst: u32, dst_sub: u32, src: u32, src_sub: u32, format: i32 },
|
||||
9 ResolveRegion { dst: u32, dst_sub: u32, at: [u32; 2], src: u32, src_sub: u32, part: Option<[i32; 4]>, format: i32, mode: i32 },
|
||||
10 Topology { kind: i32 },
|
||||
11 Viewports { all: Vec<[f32; 6]> },
|
||||
12 Scissors { all: Vec<[i32; 4]> },
|
||||
13 BlendFactor { factor: Option<[f32; 4]> },
|
||||
14 StencilRef { value: u32 },
|
||||
15 Pipeline { pso: u32 },
|
||||
16 Barriers { all: Vec<Barrier> },
|
||||
17 Heaps { heaps: Vec<u32> },
|
||||
18 RootSignature { graphics: bool, root: u32 },
|
||||
19 Table { graphics: bool, param: u32, heap: u32, slot: u32 },
|
||||
20 Constants { graphics: bool, param: u32, offset: u32, values: Vec<u32> },
|
||||
21 RootView { graphics: bool, kind: u8, param: u32, va: Va },
|
||||
22 IndexBuffer { view: Option<(Va, u32, i32)> },
|
||||
23 VertexBuffers { start: u32, count: u32, views: Option<Vec<(Va, u32, u32)>> },
|
||||
24 Targets { colors: Vec<Slot>, depth: Option<Slot> },
|
||||
25 ClearDepth { view: Slot, flags: i32, depth: f32, stencil: u8, rects: Vec<[i32; 4]> },
|
||||
26 ClearTarget { view: Slot, color: [f32; 4], rects: Vec<[i32; 4]> },
|
||||
27 Discard { res: u32, rects: Vec<[i32; 4]>, subs: Option<[u32; 2]> },
|
||||
28 BeginQuery { heap: u32, kind: i32, index: u32 },
|
||||
29 EndQuery { heap: u32, kind: i32, index: u32 },
|
||||
30 ResolveQuery { heap: u32, kind: i32, first: u32, count: u32, dst: u32, at: u64 },
|
||||
31 Indirect { signature: u32, most: u32, args: u32, at: u64, count: u32, count_at: u64 },
|
||||
32 WriteImmediate { all: Vec<(Va, u32, i32)> },
|
||||
33 DepthBounds { min: f32, max: f32 },
|
||||
}
|
||||
}
|
||||
|
||||
/// The highest kind number of [`Cmd`].
|
||||
#[cfg(test)]
|
||||
const LAST_CMD: u8 = 33;
|
||||
|
||||
impl Cmd {
|
||||
/// The commands of a list's bytes.
|
||||
pub fn all(bytes: &[u8]) -> Result<Vec<Cmd>, Bad> {
|
||||
let mut from = Dec::new(bytes);
|
||||
let mut all = Vec::new();
|
||||
while !from.bytes.is_empty() {
|
||||
all.push(Cmd::get(&mut from)?);
|
||||
}
|
||||
Ok(all)
|
||||
}
|
||||
|
||||
/// Whether it makes the card work (and is timed on its own).
|
||||
pub fn works(&self) -> bool {
|
||||
self.runs_shaders()
|
||||
|| matches!(
|
||||
self,
|
||||
Cmd::CopyBuffer { .. }
|
||||
| Cmd::CopyTexture { .. }
|
||||
| Cmd::CopyResource { .. }
|
||||
| Cmd::Resolve { .. }
|
||||
| Cmd::ResolveRegion { .. }
|
||||
| Cmd::ClearDepth { .. }
|
||||
| Cmd::ClearTarget { .. }
|
||||
| Cmd::Discard { .. }
|
||||
| Cmd::ResolveQuery { .. }
|
||||
| Cmd::WriteImmediate { .. }
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether it runs the pipeline bound.
|
||||
pub fn runs_shaders(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::Dispatch { .. } | Cmd::DispatchMesh { .. } | Cmd::Indirect { .. }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
wire_struct! {
|
||||
HeapProps { kind: i32, cpu: i32, pool: i32 }
|
||||
}
|
||||
|
||||
wire_struct! {
|
||||
/// A resource description (`D3D12_RESOURCE_DESC`).
|
||||
Desc {
|
||||
dimension: i32,
|
||||
alignment: u64,
|
||||
width: u64,
|
||||
height: u32,
|
||||
depth: u16,
|
||||
mips: u16,
|
||||
format: i32,
|
||||
samples: [u32; 2],
|
||||
layout: i32,
|
||||
flags: i32,
|
||||
}
|
||||
}
|
||||
|
||||
wire_struct! {
|
||||
Heap { id: u32, size: u64, props: HeapProps, alignment: u64, flags: i32 }
|
||||
}
|
||||
|
||||
wire_enum! {
|
||||
/// How a resource got its memory.
|
||||
Place {
|
||||
0 Committed { props: HeapProps, flags: i32 },
|
||||
1 Placed { heap: u32, offset: u64 },
|
||||
/// A swap chain's buffer.
|
||||
2 BackBuffer {},
|
||||
}
|
||||
}
|
||||
|
||||
wire_struct! {
|
||||
Resource {
|
||||
id: u32,
|
||||
place: Place,
|
||||
desc: Desc,
|
||||
/// The state it was made in.
|
||||
made_in: i32,
|
||||
clear: Option<[u32; 5]>,
|
||||
/// Its states at the start of the frame: one, or one for each
|
||||
/// subresource. Buffers start in the common state.
|
||||
state: Vec<u32>,
|
||||
/// Not the one in use where placed resources overlap: its contents
|
||||
/// are not in the capture.
|
||||
idle: bool,
|
||||
/// Made after the frame started.
|
||||
late: bool,
|
||||
name: String,
|
||||
}
|
||||
}
|
||||
|
||||
wire_enum! {
|
||||
/// A part of a pipeline description.
|
||||
Part {
|
||||
0 Root { root: u32 },
|
||||
/// Shader code: the number of its blob ([`Frame::codes`]).
|
||||
1 Code { kind: i32, blob: u32 },
|
||||
/// Plain data.
|
||||
2 Plain { kind: i32, data: Blob },
|
||||
3 Layout { elements: Vec<(String, [u32; 6])> },
|
||||
}
|
||||
}
|
||||
|
||||
wire_struct! {
|
||||
Pipeline { id: u32, parts: Vec<Part>, name: String }
|
||||
}
|
||||
|
||||
wire_struct! {
|
||||
/// Bytes in `shaders.bin`.
|
||||
Code { at: u64, len: u64, hash: [u8; 32] }
|
||||
}
|
||||
|
||||
wire_struct! {
|
||||
Signature { id: u32, stride: u32, args: Vec<[u32; 4]>, root: u32 }
|
||||
}
|
||||
|
||||
wire_struct! {
|
||||
DescriptorHeap { id: u32, kind: i32, count: u32, flags: i32, runs: Vec<(u32, u32, Slot)> }
|
||||
}
|
||||
|
||||
wire_struct! {
|
||||
QueryHeap { id: u32, kind: i32, count: u32 }
|
||||
}
|
||||
|
||||
wire_struct! {
|
||||
List { kind: i32, commands: Blob }
|
||||
}
|
||||
|
||||
wire_struct! {
|
||||
/// Bytes the CPU (or an earlier submission) put into a buffer the CPU
|
||||
/// sees, by the time a submission went to the card (in `deltas.bin`).
|
||||
Delta { res: u32, at: u64, len: u64, file: u64 }
|
||||
}
|
||||
|
||||
wire_struct! {
|
||||
Submit {
|
||||
frame: u32,
|
||||
/// Lists by number; [`MISSING`] for one that was not recorded.
|
||||
lists: Vec<u32>,
|
||||
deltas: Vec<Delta>,
|
||||
/// Descriptor slots written since the submission before.
|
||||
views: Vec<(u32, u32, Slot)>,
|
||||
}
|
||||
}
|
||||
|
||||
/// In [`Submit::lists`].
|
||||
pub const MISSING: u32 = u32::MAX;
|
||||
|
||||
wire_struct! {
|
||||
/// Contents at the start of the frame, in `contents.bin`: of a buffer,
|
||||
/// `len` bytes from `first`; of a texture, `count` subresources from
|
||||
/// `first`, laid out as `GetCopyableFootprints` lays them out.
|
||||
Content {
|
||||
res: u32,
|
||||
first: u64,
|
||||
count: u32,
|
||||
len: u64,
|
||||
/// Where in the file; [`ZERO`] if all bytes are zero.
|
||||
file: u64,
|
||||
}
|
||||
}
|
||||
|
||||
/// In [`Content::file`].
|
||||
pub const ZERO: u64 = u64::MAX;
|
||||
|
||||
wire_struct! {
|
||||
/// A frame's picture: a texture as it was when presented (in
|
||||
/// `present.bin`).
|
||||
Present { submits: u32, res: u32, width: u32, height: u32, format: i32, pitch: u32, file: u64 }
|
||||
}
|
||||
|
||||
wire_struct! {
|
||||
Frame {
|
||||
adapter: String,
|
||||
vendor: u32,
|
||||
device: u32,
|
||||
/// What the recorder could not record, and how it went.
|
||||
notes: Vec<String>,
|
||||
heaps: Vec<Heap>,
|
||||
resources: Vec<Resource>,
|
||||
roots: Vec<(u32, Blob)>,
|
||||
codes: Vec<Code>,
|
||||
pipelines: Vec<Pipeline>,
|
||||
signatures: Vec<Signature>,
|
||||
descriptor_heaps: Vec<DescriptorHeap>,
|
||||
query_heaps: Vec<QueryHeap>,
|
||||
lists: Vec<List>,
|
||||
submits: Vec<Submit>,
|
||||
contents: Vec<Content>,
|
||||
presents: Vec<Present>,
|
||||
}
|
||||
}
|
||||
|
||||
impl Frame {
|
||||
pub fn write(&self, path: &std::path::Path) -> std::io::Result<()> {
|
||||
let mut out = MAGIC.to_vec();
|
||||
VERSION.put(&mut out);
|
||||
self.put(&mut out);
|
||||
std::fs::write(path, out)
|
||||
}
|
||||
|
||||
pub fn read(path: &std::path::Path) -> anyhow::Result<Frame> {
|
||||
let bytes = std::fs::read(path)?;
|
||||
let mut from = Dec::new(&bytes);
|
||||
if from.take(8)? != MAGIC {
|
||||
return Err(Bad("it is not a frame").into());
|
||||
}
|
||||
if u32::get(&mut from)? != VERSION {
|
||||
return Err(Bad("it was made by another version of the recorder").into());
|
||||
}
|
||||
let frame = Frame::get(&mut from)?;
|
||||
if !from.bytes.is_empty() {
|
||||
return Err(Bad("bytes after its end").into());
|
||||
}
|
||||
Ok(frame)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
|
||||
fn there_and_back<T: Wire + PartialEq + std::fmt::Debug>(x: &T) {
|
||||
let mut out = Vec::new();
|
||||
x.put(&mut out);
|
||||
let mut from = Dec::new(&out);
|
||||
assert_eq!(&T::get(&mut from).unwrap(), x);
|
||||
assert!(from.bytes.is_empty(), "bytes left over");
|
||||
// Cut anywhere, it is refused and does not panic.
|
||||
for n in 0..out.len() {
|
||||
assert!(T::get(&mut Dec::new(&out[..n])).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
fn view() -> Slot {
|
||||
let mut desc = [0; 52];
|
||||
desc[3] = 7;
|
||||
desc[51] = 9;
|
||||
Slot { kind: slot::SAMPLER, described: 1, pad: 0, res: 4, counter: 5, desc }
|
||||
}
|
||||
|
||||
fn at() -> Va {
|
||||
Va::At { res: 3, offset: 1 << 40 }
|
||||
}
|
||||
|
||||
pub(crate) fn every_command() -> Vec<Cmd> {
|
||||
let placed = Loc::Placed { res: 5, offset: 512, format: 28, size: [4, 5, 6], pitch: 256 };
|
||||
let rects = vec![[1, 2, 3, 4]];
|
||||
vec![
|
||||
Cmd::Draw { vertices: 1, instances: 2, first: 3, first_instance: 4 },
|
||||
Cmd::DrawIndexed { indices: 1, instances: 2, first: 3, base: -4, first_instance: 5 },
|
||||
Cmd::Dispatch { groups: [1, 2, 3] },
|
||||
Cmd::DispatchMesh { groups: [4, 5, 6] },
|
||||
Cmd::CopyBuffer { dst: 1, dst_at: 2, src: 3, src_at: 4, len: 5 },
|
||||
Cmd::CopyTexture { dst: Loc::Sub { res: 1, sub: 2 }, at: [3, 4, 5], src: placed, part: Some([1, 2, 3, 4, 5, 6]) },
|
||||
Cmd::CopyResource { dst: 1, src: 2 },
|
||||
Cmd::Resolve { dst: 1, dst_sub: 2, src: 3, src_sub: 4, format: 28 },
|
||||
Cmd::ResolveRegion { dst: 1, dst_sub: 2, at: [3, 4], src: 5, src_sub: 6, part: Some([0, 1, 2, 3]), format: 28, mode: 1 },
|
||||
Cmd::Topology { kind: 4 },
|
||||
Cmd::Viewports { all: vec![[0.0, 1.0, 2.0, 3.0, 0.5, 1.0]; 2] },
|
||||
Cmd::Scissors { all: rects.clone() },
|
||||
Cmd::BlendFactor { factor: Some([0.1, 0.2, 0.3, 0.4]) },
|
||||
Cmd::BlendFactor { factor: None },
|
||||
Cmd::StencilRef { value: 255 },
|
||||
Cmd::Pipeline { pso: 9 },
|
||||
Cmd::Barriers {
|
||||
all: vec![
|
||||
Barrier::Transition { flags: 1, res: 2, sub: ALL, before: 4, after: 8 },
|
||||
Barrier::Alias { flags: 0, before: 1, after: 2 },
|
||||
Barrier::Uav { flags: 0, res: 0 },
|
||||
],
|
||||
},
|
||||
Cmd::Heaps { heaps: vec![1, 2] },
|
||||
Cmd::RootSignature { graphics: true, root: 3 },
|
||||
Cmd::Table { graphics: false, param: 1, heap: 2, slot: 1 << 20 },
|
||||
Cmd::Constants { graphics: true, param: 1, offset: 2, values: vec![3, 4, 5] },
|
||||
Cmd::RootView { graphics: true, kind: slot::CBV, param: 1, va: at() },
|
||||
Cmd::IndexBuffer { view: Some((at(), 5, 42)) },
|
||||
Cmd::IndexBuffer { view: None },
|
||||
Cmd::VertexBuffers { start: 1, count: 1, views: Some(vec![(Va::Unknown { address: 5 }, 6, 7)]) },
|
||||
Cmd::VertexBuffers { start: 1, count: 3, views: None },
|
||||
Cmd::Targets { colors: vec![view(); 3], depth: Some(view()) },
|
||||
Cmd::ClearDepth { view: view(), flags: 3, depth: 0.5, stencil: 7, rects: rects.clone() },
|
||||
Cmd::ClearTarget { view: view(), color: [1.0, 2.0, 3.0, 4.0], rects: Vec::new() },
|
||||
Cmd::Discard { res: 1, rects, subs: Some([0, 2]) },
|
||||
Cmd::BeginQuery { heap: 1, kind: 0, index: 2 },
|
||||
Cmd::EndQuery { heap: 1, kind: 2, index: 3 },
|
||||
Cmd::ResolveQuery { heap: 1, kind: 2, first: 3, count: 4, dst: 5, at: 6 },
|
||||
Cmd::Indirect { signature: 1, most: 2, args: 3, at: 4, count: 5, count_at: 6 },
|
||||
Cmd::WriteImmediate { all: vec![(at(), 1, 2), (Va::Null {}, 3, 4)] },
|
||||
Cmd::DepthBounds { min: 0.25, max: 0.75 },
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_command_comes_back() {
|
||||
let all = every_command();
|
||||
let mut bytes = Vec::new();
|
||||
for c in &all {
|
||||
there_and_back(c);
|
||||
c.put(&mut bytes);
|
||||
}
|
||||
assert_eq!(Cmd::all(&bytes).unwrap(), all);
|
||||
assert!(Cmd::all(&[250]).is_err());
|
||||
// Every kind there is stands in the list above.
|
||||
let kinds: std::collections::BTreeSet<u8> = all
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let mut out = Vec::new();
|
||||
c.put(&mut out);
|
||||
out[0]
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(kinds.into_iter().collect::<Vec<_>>(), (1..=LAST_CMD).collect::<Vec<u8>>());
|
||||
assert!(Cmd::all(&[LAST_CMD + 1]).is_err(), "a kind was added: bring LAST_CMD and the list above up to date");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_comes_back() {
|
||||
let props = HeapProps { kind: 4, cpu: 3, pool: 1 };
|
||||
let desc = Desc {
|
||||
dimension: 3,
|
||||
alignment: 65536,
|
||||
width: 1 << 33,
|
||||
height: 5,
|
||||
depth: 6,
|
||||
mips: 7,
|
||||
format: 28,
|
||||
samples: [1, 0],
|
||||
layout: 1,
|
||||
flags: 4,
|
||||
};
|
||||
let resource = Resource {
|
||||
id: 2,
|
||||
place: Place::Placed { heap: 1, offset: 65536 },
|
||||
desc,
|
||||
made_in: 4,
|
||||
clear: Some([28, 1, 2, 3, 4]),
|
||||
state: vec![1, 2, 3],
|
||||
idle: false,
|
||||
late: true,
|
||||
name: "a texture".into(),
|
||||
};
|
||||
let frame = Frame {
|
||||
adapter: "a card".into(),
|
||||
vendor: 0x1002,
|
||||
device: 0x744c,
|
||||
notes: vec!["nothing".into()],
|
||||
heaps: vec![Heap { id: 1, size: 64 << 20, props: props.clone(), alignment: 65536, flags: 0x84 }],
|
||||
resources: vec![
|
||||
resource.clone(),
|
||||
Resource { place: Place::Committed { props, flags: 8 }, ..resource.clone() },
|
||||
Resource { place: Place::BackBuffer {}, clear: None, ..resource },
|
||||
],
|
||||
roots: vec![(3, Blob(vec![1, 2, 3]))],
|
||||
codes: vec![Code { at: 1, len: 2, hash: [7; 32] }],
|
||||
pipelines: vec![Pipeline {
|
||||
id: 4,
|
||||
parts: vec![
|
||||
Part::Root { root: 3 },
|
||||
Part::Code { kind: 25, blob: 0 },
|
||||
Part::Plain { kind: 8, data: Blob(vec![9; 20]) },
|
||||
Part::Layout { elements: vec![("POSITION".into(), [1, 2, 3, 4, 5, 6])] },
|
||||
],
|
||||
name: "a pipeline".into(),
|
||||
}],
|
||||
signatures: vec![Signature { id: 5, stride: 12, args: vec![[10, 0, 0, 0]], root: 0 }],
|
||||
descriptor_heaps: vec![DescriptorHeap { id: 6, kind: 0, count: 10, flags: 1, runs: vec![(0, 9, Slot::EMPTY), (9, 1, view())] }],
|
||||
query_heaps: vec![QueryHeap { id: 7, kind: 1, count: 8 }],
|
||||
lists: vec![List { kind: 0, commands: Blob(vec![1, 2]) }],
|
||||
submits: vec![Submit {
|
||||
frame: 0,
|
||||
lists: vec![0, MISSING],
|
||||
deltas: vec![Delta { res: 2, at: 4096, len: 8192, file: 0 }],
|
||||
views: vec![(6, 3, view())],
|
||||
}],
|
||||
contents: vec![Content { res: 2, first: 0, count: 3, len: 100, file: ZERO }],
|
||||
presents: vec![Present { submits: 1, res: 2, width: 4, height: 5, format: 28, pitch: 256, file: 0 }],
|
||||
};
|
||||
there_and_back(&frame);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("frame.bin");
|
||||
frame.write(&path).unwrap();
|
||||
assert_eq!(Frame::read(&path).unwrap(), frame);
|
||||
std::fs::write(&path, b"VICFRAMEnothing at all").unwrap();
|
||||
assert!(Frame::read(&path).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,909 @@
|
||||
//! The frame recorder and replayer on the PC's own adapter (skipped without
|
||||
//! one): a small program with clears, indirect draws of textures picked from
|
||||
//! a heap, compute, buffers the CPU changes between submissions, descriptors
|
||||
//! replaced between them, and textures that share memory. It runs without
|
||||
//! the recorder, then with it, then one frame of it is replayed; every
|
||||
//! picture and buffer must be the same.
|
||||
//!
|
||||
//! `VICTORY_TEST_D3D_DEBUG=1` runs it under the debug layer.
|
||||
#![cfg(all(windows, feature = "diagnostics"))]
|
||||
|
||||
use std::mem::ManuallyDrop;
|
||||
|
||||
use victory_gpu::replay::play::{self, Buffers, Options, Player};
|
||||
use victory_gpu::replay::record::{self, At, Settings};
|
||||
use windows::Win32::Foundation::{HANDLE, HWND, RECT};
|
||||
use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
|
||||
use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, ID3DBlob};
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
use windows::Win32::Graphics::Dxgi::Common::*;
|
||||
use windows::Win32::Graphics::Dxgi::*;
|
||||
use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
|
||||
use windows::Win32::UI::WindowsAndMessaging::*;
|
||||
use windows::core::{Interface, PCSTR, s, w};
|
||||
|
||||
const SIZE: u32 = 128;
|
||||
|
||||
const DRAW: &str = r#"
|
||||
#define RS "RootConstants(num32BitConstants=2, b0), CBV(b1), DescriptorTable(SRV(t0, numDescriptors=unbounded)), StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_POINT)"
|
||||
cbuffer Pick : register(b0) { uint pick; uint pad; };
|
||||
cbuffer Place : register(b1) { float4 place; };
|
||||
Texture2D all[] : register(t0);
|
||||
SamplerState point_sampler : register(s0);
|
||||
struct V { float4 at : SV_Position; float2 uv : UV; };
|
||||
[RootSignature(RS)]
|
||||
V vs(uint i : SV_VertexID) {
|
||||
float2 c = float2(i & 1, (i >> 1) & 1);
|
||||
if (i == 3) c = float2(1, 0);
|
||||
if (i == 4) c = float2(0, 1);
|
||||
if (i == 5) c = float2(1, 1);
|
||||
V v;
|
||||
v.uv = c;
|
||||
v.at = float4(place.xy + c * place.zw, 0.5, 1);
|
||||
return v;
|
||||
}
|
||||
float4 ps(V v) : SV_Target { return all[NonUniformResourceIndex(pick)].SampleLevel(point_sampler, v.uv, 0); }
|
||||
"#;
|
||||
|
||||
/// Writes the arguments of indirect draws (two records: six vertices, and
|
||||
/// one far too many that the clamp cuts to none).
|
||||
const ARGS: &str = r#"
|
||||
#define RS "SRV(t0), UAV(u0)"
|
||||
ByteAddressBuffer from : register(t0);
|
||||
RWByteAddressBuffer args : register(u0);
|
||||
[RootSignature(RS)]
|
||||
[numthreads(1, 1, 1)]
|
||||
void main() {
|
||||
args.Store4(0, uint4(from.Load(0), 1, 0, 0));
|
||||
args.Store4(16, uint4(4000000000u, 1, 0, 0));
|
||||
}
|
||||
"#;
|
||||
|
||||
/// The argument clamp's parameters, with a simple bound.
|
||||
const CLAMP: &str = r#"
|
||||
#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)"
|
||||
cbuffer C : register(b0) { uint kind; uint stride; uint records; uint args_offset; uint has_count; uint count_offset; };
|
||||
ByteAddressBuffer from : register(t0);
|
||||
ByteAddressBuffer count : register(t1);
|
||||
RWByteAddressBuffer to : register(u0);
|
||||
RWByteAddressBuffer budget : register(u1);
|
||||
[RootSignature(RS)]
|
||||
[numthreads(64, 1, 1)]
|
||||
void main(uint3 id : SV_DispatchThreadID) {
|
||||
if (id.x >= records) return;
|
||||
uint4 a = from.Load4(args_offset + id.x * stride);
|
||||
if (a.x > 1000) a.x = 0;
|
||||
to.Store4(id.x * stride, a);
|
||||
uint was;
|
||||
budget.InterlockedAdd(0, a.x, was);
|
||||
}
|
||||
"#;
|
||||
|
||||
/// Adds what the CPU gives to what was there, and writes it on.
|
||||
const ADD: &str = r#"
|
||||
#define RS "SRV(t0), DescriptorTable(UAV(u0)), UAV(u1)"
|
||||
ByteAddressBuffer from : register(t0);
|
||||
RWTexture2D<float4> image : register(u0);
|
||||
RWByteAddressBuffer sum : register(u1);
|
||||
[RootSignature(RS)]
|
||||
[numthreads(8, 8, 1)]
|
||||
void main(uint3 id : SV_DispatchThreadID) {
|
||||
uint at = (id.y * 16 + id.x) * 4;
|
||||
uint v = from.Load(at) + sum.Load(at) * 3;
|
||||
sum.Store(at, v);
|
||||
image[id.xy] = image[id.xy] + float4((v & 15) / 255.0, 0, 1 / 255.0, 1);
|
||||
}
|
||||
"#;
|
||||
|
||||
struct Made {
|
||||
root: ID3D12RootSignature,
|
||||
pso: ID3D12PipelineState,
|
||||
}
|
||||
|
||||
fn compile(source: &str, entry: PCSTR, target: PCSTR) -> Vec<u8> {
|
||||
let (mut code, mut errors): (Option<ID3DBlob>, Option<ID3DBlob>) = (None, None);
|
||||
// SAFETY: the source and names live through the call; the blobs' own
|
||||
// bytes.
|
||||
unsafe {
|
||||
let r = D3DCompile(source.as_ptr().cast(), source.len(), None, None, None, entry, target, 1 << 20, 0, &mut code, Some(&mut errors));
|
||||
if r.is_err() {
|
||||
let e = errors.unwrap();
|
||||
let text = std::slice::from_raw_parts(e.GetBufferPointer().cast::<u8>(), e.GetBufferSize());
|
||||
panic!("{}", String::from_utf8_lossy(text));
|
||||
}
|
||||
let code = code.unwrap();
|
||||
std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()).to_vec()
|
||||
}
|
||||
}
|
||||
|
||||
fn code(bytes: &[u8]) -> D3D12_SHADER_BYTECODE {
|
||||
D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() }
|
||||
}
|
||||
|
||||
fn compute(device: &ID3D12Device, source: &str) -> Made {
|
||||
let cs = compile(source, s!("main"), s!("cs_5_1"));
|
||||
// SAFETY: plain creation.
|
||||
unsafe {
|
||||
let root: ID3D12RootSignature = device.CreateRootSignature(0, &cs).unwrap();
|
||||
let pso = device
|
||||
.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
|
||||
pRootSignature: std::mem::transmute_copy(&root),
|
||||
CS: code(&cs),
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap();
|
||||
Made { root, pso }
|
||||
}
|
||||
}
|
||||
|
||||
fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC {
|
||||
D3D12_RESOURCE_DESC {
|
||||
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
|
||||
Width: size,
|
||||
Height: 1,
|
||||
DepthOrArraySize: 1,
|
||||
MipLevels: 1,
|
||||
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
|
||||
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
|
||||
Flags: flags,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn texture_desc(size: u32, format: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC {
|
||||
D3D12_RESOURCE_DESC {
|
||||
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
|
||||
Width: u64::from(size),
|
||||
Height: size,
|
||||
DepthOrArraySize: 1,
|
||||
MipLevels: 1,
|
||||
Format: format,
|
||||
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
|
||||
Flags: flags,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum In {
|
||||
Card,
|
||||
Upload,
|
||||
Back,
|
||||
/// The PC's memory, mapped, that shaders write too.
|
||||
Shared,
|
||||
}
|
||||
|
||||
fn committed(device: &ID3D12Device, place: In, desc: &D3D12_RESOURCE_DESC, state: D3D12_RESOURCE_STATES) -> (ID3D12Resource, *mut u8) {
|
||||
let heap = match place {
|
||||
In::Card => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
|
||||
In::Upload => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() },
|
||||
In::Back => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() },
|
||||
In::Shared => D3D12_HEAP_PROPERTIES {
|
||||
Type: D3D12_HEAP_TYPE_CUSTOM,
|
||||
CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
|
||||
MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
let mut made: Option<ID3D12Resource> = None;
|
||||
let mut data = std::ptr::null_mut();
|
||||
// SAFETY: plain creation and mapping.
|
||||
unsafe {
|
||||
device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, desc, state, None, &mut made).unwrap();
|
||||
let made = made.unwrap();
|
||||
if place != In::Card {
|
||||
made.Map(0, None, Some(&mut data)).unwrap();
|
||||
}
|
||||
(made, data.cast())
|
||||
}
|
||||
}
|
||||
|
||||
fn moved(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER {
|
||||
D3D12_RESOURCE_BARRIER {
|
||||
Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
|
||||
Anonymous: D3D12_RESOURCE_BARRIER_0 {
|
||||
Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
|
||||
// SAFETY: a borrowed pointer never released.
|
||||
pResource: unsafe { std::mem::transmute_copy(res) },
|
||||
Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
|
||||
StateBefore: before,
|
||||
StateAfter: after,
|
||||
}),
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn uav_barrier() -> D3D12_RESOURCE_BARRIER {
|
||||
D3D12_RESOURCE_BARRIER {
|
||||
Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
|
||||
Anonymous: D3D12_RESOURCE_BARRIER_0 {
|
||||
UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: ManuallyDrop::new(None) }),
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn aliased(before: &ID3D12Resource, after: &ID3D12Resource) -> D3D12_RESOURCE_BARRIER {
|
||||
D3D12_RESOURCE_BARRIER {
|
||||
Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
|
||||
Anonymous: D3D12_RESOURCE_BARRIER_0 {
|
||||
Aliasing: ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER {
|
||||
// SAFETY: borrowed pointers never released.
|
||||
pResourceBefore: unsafe { std::mem::transmute_copy(before) },
|
||||
// SAFETY: as above.
|
||||
pResourceAfter: unsafe { std::mem::transmute_copy(after) },
|
||||
}),
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
const COMMON: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COMMON;
|
||||
const TARGET: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_RENDER_TARGET;
|
||||
const READ: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
|
||||
const UAV: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
|
||||
const TO: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COPY_DEST;
|
||||
const FROM: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COPY_SOURCE;
|
||||
const ARGUMENTS: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
|
||||
|
||||
/// What the program ends with.
|
||||
#[derive(PartialEq, Debug)]
|
||||
struct Outcome {
|
||||
picture: Vec<u8>,
|
||||
image: Vec<u8>,
|
||||
sum: Vec<u8>,
|
||||
shared: Vec<u8>,
|
||||
}
|
||||
|
||||
struct Scene {
|
||||
device: ID3D12Device,
|
||||
queue: ID3D12CommandQueue,
|
||||
fence: ID3D12Fence,
|
||||
event: HANDLE,
|
||||
value: u64,
|
||||
lists: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)>,
|
||||
draw: Made,
|
||||
args: Made,
|
||||
clamp: Made,
|
||||
add: Made,
|
||||
signature: ID3D12CommandSignature,
|
||||
views: ID3D12DescriptorHeap,
|
||||
step: usize,
|
||||
rtvs: ID3D12DescriptorHeap,
|
||||
dsvs: ID3D12DescriptorHeap,
|
||||
target: ID3D12Resource,
|
||||
_depth: ID3D12Resource,
|
||||
fixed: ID3D12Resource,
|
||||
one: ID3D12Resource,
|
||||
other: ID3D12Resource,
|
||||
_heap: ID3D12Heap,
|
||||
image: ID3D12Resource,
|
||||
sum: ID3D12Resource,
|
||||
arguments: ID3D12Resource,
|
||||
scratch: ID3D12Resource,
|
||||
budget: ID3D12Resource,
|
||||
shared: (ID3D12Resource, *mut u8),
|
||||
constants: (ID3D12Resource, *mut u8),
|
||||
texels: (ID3D12Resource, *mut u8),
|
||||
back: (ID3D12Resource, *mut u8),
|
||||
swap: Option<(IDXGISwapChain3, HWND)>,
|
||||
}
|
||||
|
||||
impl Scene {
|
||||
fn new(device: &ID3D12Device, window: bool) -> Scene {
|
||||
// SAFETY: plain creation throughout.
|
||||
unsafe {
|
||||
let queue: ID3D12CommandQueue = device
|
||||
.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() })
|
||||
.unwrap();
|
||||
let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
|
||||
let lists = (0..3)
|
||||
.map(|_| {
|
||||
let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap();
|
||||
let list: ID3D12GraphicsCommandList =
|
||||
device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap();
|
||||
list.Close().unwrap();
|
||||
(allocator, list)
|
||||
})
|
||||
.collect();
|
||||
let (vs, ps) = (compile(DRAW, s!("vs"), s!("vs_5_1")), compile(DRAW, s!("ps"), s!("ps_5_1")));
|
||||
let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap();
|
||||
let mut blend = D3D12_BLEND_DESC::default();
|
||||
blend.RenderTarget[0].RenderTargetWriteMask = 15;
|
||||
let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
|
||||
pRootSignature: std::mem::transmute_copy(&root),
|
||||
VS: code(&vs),
|
||||
PS: code(&ps),
|
||||
BlendState: blend,
|
||||
SampleMask: u32::MAX,
|
||||
RasterizerState: D3D12_RASTERIZER_DESC {
|
||||
FillMode: D3D12_FILL_MODE_SOLID,
|
||||
CullMode: D3D12_CULL_MODE_NONE,
|
||||
DepthClipEnable: true.into(),
|
||||
..Default::default()
|
||||
},
|
||||
DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
|
||||
DepthEnable: true.into(),
|
||||
DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
|
||||
DepthFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL,
|
||||
..Default::default()
|
||||
},
|
||||
PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
|
||||
NumRenderTargets: 1,
|
||||
DSVFormat: DXGI_FORMAT_D32_FLOAT,
|
||||
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
|
||||
..Default::default()
|
||||
};
|
||||
desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap();
|
||||
record::name(&pso, "a drawing pipeline");
|
||||
let draw = Made { root, pso };
|
||||
let clamp = compute(device, CLAMP);
|
||||
record::name(&clamp.pso, play::CLAMP);
|
||||
let argument = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, ..Default::default() };
|
||||
let mut signature: Option<ID3D12CommandSignature> = None;
|
||||
let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 16, NumArgumentDescs: 1, pArgumentDescs: &argument, NodeMask: 0 };
|
||||
device.CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut signature).unwrap();
|
||||
let heap = |kind, count, flags| -> ID3D12DescriptorHeap {
|
||||
device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: count, Flags: flags, NodeMask: 0 }).unwrap()
|
||||
};
|
||||
let views = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 5000, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE);
|
||||
let rtvs = heap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE);
|
||||
let dsvs = heap(D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE);
|
||||
let rgba = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
let (target, _) = committed(device, In::Card, &texture_desc(SIZE, rgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), FROM);
|
||||
let (depth, _) = committed(
|
||||
device,
|
||||
In::Card,
|
||||
&texture_desc(SIZE, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL),
|
||||
D3D12_RESOURCE_STATE_DEPTH_WRITE,
|
||||
);
|
||||
let (fixed, _) = committed(device, In::Card, &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_NONE), TO);
|
||||
let (image, _) = committed(device, In::Card, &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), UAV);
|
||||
let mut memory: Option<ID3D12Heap> = None;
|
||||
let desc = D3D12_HEAP_DESC {
|
||||
SizeInBytes: 4 << 20,
|
||||
Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
|
||||
Alignment: 0,
|
||||
Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES,
|
||||
};
|
||||
device.CreateHeap(&desc, &mut memory).unwrap();
|
||||
let memory = memory.unwrap();
|
||||
let placed = || {
|
||||
let mut made: Option<ID3D12Resource> = None;
|
||||
let d = texture_desc(16, rgba, D3D12_RESOURCE_FLAG_NONE);
|
||||
device.CreatePlacedResource(&memory, 65536, &d, TO, None, &mut made).unwrap();
|
||||
made.unwrap()
|
||||
};
|
||||
// Two textures in one place.
|
||||
let (one, other) = (placed(), placed());
|
||||
let uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
|
||||
let card = |size| committed(device, In::Card, &buffer_desc(size, uav), COMMON).0;
|
||||
let (sum, arguments, scratch, budget) = (card(1024), card(4096), card(4096), card(256));
|
||||
let shared = committed(device, In::Shared, &buffer_desc(70_000, uav), COMMON);
|
||||
let constants = committed(
|
||||
device,
|
||||
In::Upload,
|
||||
&buffer_desc(8192, D3D12_RESOURCE_FLAG_NONE),
|
||||
D3D12_RESOURCE_STATE_GENERIC_READ,
|
||||
);
|
||||
let texels = committed(
|
||||
device,
|
||||
In::Upload,
|
||||
&buffer_desc(65536, D3D12_RESOURCE_FLAG_NONE),
|
||||
D3D12_RESOURCE_STATE_GENERIC_READ,
|
||||
);
|
||||
let back = committed(device, In::Back, &buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE), TO);
|
||||
for (r, n) in [(&sum, "sum"), (&image, "image"), (&target, "target"), (&shared.0, "shared"), (&one, "one"), (&other, "other")] {
|
||||
record::name(r, n);
|
||||
}
|
||||
device.CreateRenderTargetView(&target, None, rtvs.GetCPUDescriptorHandleForHeapStart());
|
||||
device.CreateDepthStencilView(&depth, None, dsvs.GetCPUDescriptorHandleForHeapStart());
|
||||
let step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize;
|
||||
let swap = window.then(|| swap_chain(&queue));
|
||||
let scene = Scene {
|
||||
device: device.clone(),
|
||||
queue,
|
||||
fence,
|
||||
event: CreateEventW(None, false, false, None).unwrap(),
|
||||
value: 0,
|
||||
lists,
|
||||
draw,
|
||||
args: compute(device, ARGS),
|
||||
clamp,
|
||||
add: compute(device, ADD),
|
||||
signature: signature.unwrap(),
|
||||
views,
|
||||
step,
|
||||
rtvs,
|
||||
dsvs,
|
||||
target,
|
||||
_depth: depth,
|
||||
fixed,
|
||||
one,
|
||||
other,
|
||||
_heap: memory,
|
||||
image,
|
||||
sum,
|
||||
arguments,
|
||||
scratch,
|
||||
budget,
|
||||
shared,
|
||||
constants,
|
||||
texels,
|
||||
back,
|
||||
swap,
|
||||
};
|
||||
// Null views everywhere, by copies of a slot made elsewhere.
|
||||
let block = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16, D3D12_DESCRIPTOR_HEAP_FLAG_NONE);
|
||||
let null = D3D12_SHADER_RESOURCE_VIEW_DESC {
|
||||
Format: rgba,
|
||||
ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
|
||||
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
|
||||
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() } },
|
||||
};
|
||||
let from = block.GetCPUDescriptorHandleForHeapStart();
|
||||
for i in 0..16 {
|
||||
let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from.ptr + i * step };
|
||||
device.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&null), at);
|
||||
}
|
||||
for i in (0..4992).step_by(16) {
|
||||
device.CopyDescriptorsSimple(16, scene.cpu(i), from, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
|
||||
}
|
||||
// The rest with the other copying method, in unlike pieces.
|
||||
let to = [scene.cpu(4992), scene.cpu(4994)];
|
||||
let sources = [from, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from.ptr + 4 * step }];
|
||||
device.CopyDescriptors(
|
||||
2,
|
||||
to.as_ptr(),
|
||||
Some([2u32, 6].as_ptr()),
|
||||
2,
|
||||
sources.as_ptr(),
|
||||
Some([4u32, 4].as_ptr()),
|
||||
D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
|
||||
);
|
||||
scene.show(4001, &scene.other);
|
||||
scene.show(4002, &scene.one);
|
||||
device.CreateUnorderedAccessView(&scene.image, None::<&ID3D12Resource>, None, scene.cpu(7));
|
||||
scene
|
||||
}
|
||||
}
|
||||
|
||||
fn cpu(&self, i: usize) -> D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
// SAFETY: a slot of the heap.
|
||||
let start = unsafe { self.views.GetCPUDescriptorHandleForHeapStart() };
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + i * self.step }
|
||||
}
|
||||
|
||||
/// Slot `i` shows `texture`.
|
||||
fn show(&self, i: usize, texture: &ID3D12Resource) {
|
||||
// SAFETY: a slot of the heap and a live texture.
|
||||
unsafe { self.device.CreateShaderResourceView(texture, None, self.cpu(i)) };
|
||||
}
|
||||
|
||||
fn wait(&mut self) {
|
||||
self.value += 1;
|
||||
// SAFETY: our queue, fence and event.
|
||||
unsafe {
|
||||
self.queue.Signal(&self.fence, self.value).unwrap();
|
||||
self.fence.SetEventOnCompletion(self.value, self.event).unwrap();
|
||||
WaitForSingleObject(self.event, INFINITE);
|
||||
self.device.GetDeviceRemovedReason().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn open(&self, i: usize) -> ID3D12GraphicsCommandList {
|
||||
let (allocator, list) = &self.lists[i];
|
||||
// SAFETY: its last run was waited for.
|
||||
unsafe {
|
||||
allocator.Reset().unwrap();
|
||||
list.Reset(allocator, None).unwrap();
|
||||
}
|
||||
list.clone()
|
||||
}
|
||||
|
||||
fn send(&self, lists: &[&ID3D12GraphicsCommandList]) {
|
||||
let all: Vec<Option<ID3D12CommandList>> = lists.iter().map(|l| Some(l.cast().unwrap())).collect();
|
||||
// SAFETY: closed lists.
|
||||
unsafe { self.queue.ExecuteCommandLists(&all) };
|
||||
}
|
||||
|
||||
/// Fills rows of a 16x16 texture in the upload buffer at `at`.
|
||||
fn fill(&self, at: usize, color: [u8; 4]) {
|
||||
for y in 0..16 {
|
||||
for x in 0..16 {
|
||||
let mut c = color;
|
||||
c[1] = c[1].wrapping_add((x * 8 + y) as u8);
|
||||
// SAFETY: inside the mapping (16 rows of 256 bytes).
|
||||
unsafe { self.texels.1.add(at + y * 256 + x * 4).cast::<[u8; 4]>().write(c) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn texture_copy(&self, l: &ID3D12GraphicsCommandList, texture: &ID3D12Resource, at: u64) {
|
||||
let from = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: a borrowed pointer never released.
|
||||
pResource: unsafe { std::mem::transmute_copy(&self.texels.0) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint(at, 16) },
|
||||
};
|
||||
let to = 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 { l.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
|
||||
}
|
||||
|
||||
/// A quad of the texture in slot `pick`, at the constants at `at`.
|
||||
fn quad(&self, l: &ID3D12GraphicsCommandList, pick: u32, at: u64, record: u64) {
|
||||
// SAFETY: an open list; live objects.
|
||||
unsafe {
|
||||
l.SetGraphicsRootSignature(&self.draw.root);
|
||||
l.SetPipelineState(&self.draw.pso);
|
||||
l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
|
||||
l.SetGraphicsRoot32BitConstant(0, pick, 0);
|
||||
l.SetGraphicsRootConstantBufferView(1, self.constants.0.GetGPUVirtualAddress() + at);
|
||||
l.SetGraphicsRootDescriptorTable(2, self.views.GetGPUDescriptorHandleForHeapStart());
|
||||
l.ExecuteIndirect(&self.signature, 1, &self.scratch, record * 16, None::<&ID3D12Resource>, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The arguments made and clamped, as the host layer does it.
|
||||
fn arguments(&self, l: &ID3D12GraphicsCommandList, before: D3D12_RESOURCE_STATES) {
|
||||
// SAFETY: an open list; live objects.
|
||||
unsafe {
|
||||
l.SetComputeRootSignature(&self.args.root);
|
||||
l.SetPipelineState(&self.args.pso);
|
||||
l.SetComputeRootShaderResourceView(0, self.shared.0.GetGPUVirtualAddress() + 65536);
|
||||
l.SetComputeRootUnorderedAccessView(1, self.arguments.GetGPUVirtualAddress());
|
||||
l.Dispatch(1, 1, 1);
|
||||
l.ResourceBarrier(&[uav_barrier(), moved(&self.arguments, UAV, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)]);
|
||||
l.ResourceBarrier(&[uav_barrier(), moved(&self.scratch, before, UAV)]);
|
||||
l.SetComputeRootSignature(&self.clamp.root);
|
||||
l.SetPipelineState(&self.clamp.pso);
|
||||
let constants = [0u32, 16, 2, 0, 0, 0];
|
||||
l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
|
||||
l.SetComputeRootShaderResourceView(1, self.arguments.GetGPUVirtualAddress());
|
||||
l.SetComputeRootShaderResourceView(2, self.arguments.GetGPUVirtualAddress());
|
||||
l.SetComputeRootUnorderedAccessView(3, self.scratch.GetGPUVirtualAddress());
|
||||
l.SetComputeRootUnorderedAccessView(4, self.budget.GetGPUVirtualAddress());
|
||||
l.Dispatch(1, 1, 1);
|
||||
l.ResourceBarrier(&[uav_barrier(), moved(&self.scratch, UAV, ARGUMENTS)]);
|
||||
l.ResourceBarrier(&[moved(&self.arguments, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, UAV)]);
|
||||
}
|
||||
}
|
||||
|
||||
fn place(&self, at: usize, place: [f32; 4]) {
|
||||
// SAFETY: inside the mapping.
|
||||
unsafe { self.constants.1.add(at).cast::<[f32; 4]>().write(place) };
|
||||
}
|
||||
|
||||
fn give(&self, at: usize, value: u32) {
|
||||
// SAFETY: inside the mapping.
|
||||
unsafe { self.shared.1.add(at).cast::<u32>().write(value) };
|
||||
}
|
||||
|
||||
fn targets(&self, l: &ID3D12GraphicsCommandList) {
|
||||
// SAFETY: an open list; live objects.
|
||||
unsafe {
|
||||
let (rtv, dsv) = (self.rtvs.GetCPUDescriptorHandleForHeapStart(), self.dsvs.GetCPUDescriptorHandleForHeapStart());
|
||||
l.OMSetRenderTargets(1, Some(&rtv), false, Some(&dsv));
|
||||
let size = SIZE as f32;
|
||||
l.RSSetViewports(&[D3D12_VIEWPORT { Width: size, Height: size, MaxDepth: 1.0, ..Default::default() }]);
|
||||
l.RSSetScissorRects(&[RECT { left: 0, top: 0, right: SIZE as i32, bottom: SIZE as i32 }]);
|
||||
l.SetDescriptorHeaps(&[Some(self.views.clone())]);
|
||||
}
|
||||
}
|
||||
|
||||
fn frame(&mut self, n: u32) {
|
||||
// SAFETY: open lists of ours, live objects; memory is written while
|
||||
// the card does not use it.
|
||||
unsafe {
|
||||
self.wait();
|
||||
if n == 0 {
|
||||
self.fill(0, [200, 10, 30, 255]);
|
||||
self.fill(8192, [10, 40, 220, 255]);
|
||||
let l = self.open(0);
|
||||
self.texture_copy(&l, &self.fixed, 0);
|
||||
self.texture_copy(&l, &self.other, 8192);
|
||||
l.ResourceBarrier(&[moved(&self.fixed, TO, READ), moved(&self.other, TO, READ)]);
|
||||
l.Close().unwrap();
|
||||
self.send(&[&l]);
|
||||
self.wait();
|
||||
}
|
||||
// The first submission.
|
||||
self.show(4000, &self.fixed);
|
||||
self.place(0, [-1.0 + 0.1 * n as f32, -1.0, 0.5, 0.5]);
|
||||
self.place(256, [0.0, 0.0, 0.5, 0.5]);
|
||||
self.give(65536, 6);
|
||||
self.give(40, 7 + n);
|
||||
let l = self.open(0);
|
||||
l.ResourceBarrier(&[moved(&self.target, FROM, TARGET)]);
|
||||
let (rtv, dsv) = (self.rtvs.GetCPUDescriptorHandleForHeapStart(), self.dsvs.GetCPUDescriptorHandleForHeapStart());
|
||||
l.ClearRenderTargetView(rtv, &[0.1 * n as f32, 0.2, 0.3, 1.0], None);
|
||||
l.ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None);
|
||||
self.arguments(&l, COMMON);
|
||||
self.targets(&l);
|
||||
self.quad(&l, 4000, 0, 0);
|
||||
self.quad(&l, 4001, 256, 0);
|
||||
// Nothing: the clamp cut it to no vertices.
|
||||
self.quad(&l, 4001, 0, 1);
|
||||
l.ResourceBarrier(&[moved(&self.scratch, ARGUMENTS, COMMON)]);
|
||||
l.Close().unwrap();
|
||||
self.send(&[&l]);
|
||||
self.wait();
|
||||
// The second: other constants and another texture in the same
|
||||
// places, and the second texture in the memory of the first.
|
||||
self.show(4000, &self.other);
|
||||
self.place(0, [-0.9, 0.3, 0.6, 0.6]);
|
||||
self.place(256, [0.3, -0.8, 0.6, 0.5]);
|
||||
self.give(40, 100 + n);
|
||||
self.give(65536, 3);
|
||||
self.fill(16384, [30, 200, 10 + 5 * n as u8, 255]);
|
||||
let l = self.open(1);
|
||||
self.targets(&l);
|
||||
self.arguments(&l, COMMON);
|
||||
self.quad(&l, 4000, 0, 0);
|
||||
l.ResourceBarrier(&[moved(&self.other, READ, TO)]);
|
||||
l.ResourceBarrier(&[aliased(&self.other, &self.one)]);
|
||||
self.texture_copy(&l, &self.one, 16384);
|
||||
l.ResourceBarrier(&[moved(&self.one, TO, READ)]);
|
||||
self.arguments(&l, ARGUMENTS);
|
||||
self.quad(&l, 4002, 256, 0);
|
||||
l.ResourceBarrier(&[moved(&self.scratch, ARGUMENTS, COMMON)]);
|
||||
// And back, for the next frame.
|
||||
l.ResourceBarrier(&[moved(&self.one, READ, TO)]);
|
||||
l.ResourceBarrier(&[aliased(&self.one, &self.other)]);
|
||||
self.texture_copy(&l, &self.other, 8192);
|
||||
l.ResourceBarrier(&[moved(&self.other, TO, READ)]);
|
||||
l.Close().unwrap();
|
||||
let second = l;
|
||||
let l = self.open(2);
|
||||
l.SetDescriptorHeaps(&[Some(self.views.clone())]);
|
||||
l.SetComputeRootSignature(&self.add.root);
|
||||
l.SetPipelineState(&self.add.pso);
|
||||
l.SetComputeRootShaderResourceView(0, self.shared.0.GetGPUVirtualAddress());
|
||||
let table = self.views.GetGPUDescriptorHandleForHeapStart().ptr + 7 * self.step as u64;
|
||||
l.SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE { ptr: table });
|
||||
l.SetComputeRootUnorderedAccessView(2, self.sum.GetGPUVirtualAddress());
|
||||
for _ in 0..3 {
|
||||
l.Dispatch(2, 2, 1);
|
||||
l.ResourceBarrier(&[uav_barrier()]);
|
||||
}
|
||||
// The card writes memory the CPU sees.
|
||||
l.ResourceBarrier(&[moved(&self.sum, UAV, FROM)]);
|
||||
l.CopyBufferRegion(&self.shared.0, 30_000, &self.sum, 0, 1024);
|
||||
l.ResourceBarrier(&[moved(&self.target, TARGET, FROM)]);
|
||||
l.Close().unwrap();
|
||||
self.send(&[&second, &l]);
|
||||
if let Some((swap, _)) = &self.swap {
|
||||
swap.Present(0, DXGI_PRESENT(0)).unwrap();
|
||||
}
|
||||
record::present(&self.target, FROM);
|
||||
}
|
||||
}
|
||||
|
||||
/// What everything holds now.
|
||||
fn outcome(&mut self) -> Outcome {
|
||||
self.wait();
|
||||
let l = self.open(0);
|
||||
// SAFETY: an open list; live objects.
|
||||
unsafe {
|
||||
let to = |at: u64, size| D3D12_TEXTURE_COPY_LOCATION {
|
||||
pResource: std::mem::transmute_copy(&self.back.0),
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint(at, size) },
|
||||
};
|
||||
let of = |t: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION {
|
||||
pResource: std::mem::transmute_copy(t),
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
|
||||
};
|
||||
l.ResourceBarrier(&[moved(&self.image, UAV, FROM)]);
|
||||
l.CopyTextureRegion(&to(0, SIZE), 0, 0, 0, &of(&self.target), None);
|
||||
l.CopyTextureRegion(&to(1 << 18, 16), 0, 0, 0, &of(&self.image), None);
|
||||
l.ResourceBarrier(&[moved(&self.image, FROM, UAV)]);
|
||||
l.CopyBufferRegion(&self.back.0, 1 << 19, &self.sum, 0, 1024);
|
||||
l.Close().unwrap();
|
||||
self.send(&[&l]);
|
||||
self.wait();
|
||||
let at = |from: usize, n: usize| std::slice::from_raw_parts(self.back.1.add(from), n).to_vec();
|
||||
Outcome {
|
||||
picture: at(0, (SIZE * 512) as usize),
|
||||
image: rows(&at(1 << 18, 4096)),
|
||||
sum: at(1 << 19, 1024),
|
||||
shared: std::slice::from_raw_parts(self.shared.1, 70_000).to_vec(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The 64 bytes of each row of a 16x16 texture.
|
||||
fn rows(bytes: &[u8]) -> Vec<u8> {
|
||||
bytes.chunks(256).flat_map(|r| r[..64].to_vec()).collect()
|
||||
}
|
||||
|
||||
fn footprint(at: u64, size: u32) -> D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
|
||||
D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
|
||||
Offset: at,
|
||||
Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
|
||||
Format: DXGI_FORMAT_R8G8B8A8_UNORM,
|
||||
Width: size,
|
||||
Height: size,
|
||||
Depth: 1,
|
||||
RowPitch: (size * 4).next_multiple_of(256),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// A swap chain of a window that is never shown.
|
||||
fn swap_chain(queue: &ID3D12CommandQueue) -> (IDXGISwapChain3, HWND) {
|
||||
// SAFETY: plain creation.
|
||||
unsafe {
|
||||
let hwnd =
|
||||
CreateWindowExW(WINDOW_EX_STYLE(0), w!("STATIC"), w!("replay test"), WS_POPUP, 0, 0, 64, 64, None, None, None, None).unwrap();
|
||||
let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap();
|
||||
let desc = DXGI_SWAP_CHAIN_DESC1 {
|
||||
Width: 64,
|
||||
Height: 64,
|
||||
Format: DXGI_FORMAT_R8G8B8A8_UNORM,
|
||||
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
|
||||
BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
|
||||
BufferCount: 2,
|
||||
SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
|
||||
..Default::default()
|
||||
};
|
||||
let chain = factory.CreateSwapChainForHwnd(queue, hwnd, &desc, None, None).unwrap().cast().unwrap();
|
||||
(chain, hwnd)
|
||||
}
|
||||
}
|
||||
|
||||
fn table_of(device: &ID3D12Device) -> usize {
|
||||
// SAFETY: a live COM object starts with its table's address.
|
||||
unsafe { *device.as_raw().cast::<usize>() }
|
||||
}
|
||||
|
||||
fn check(player: &mut Player, options: &Options, expected: &Outcome, what: &str) -> play::Report {
|
||||
let report = player.run(options).unwrap();
|
||||
println!("{}", report.text(what));
|
||||
assert_eq!(report.frame_ms.len(), options.loops as usize);
|
||||
assert!(report.median_ms() > 0.0);
|
||||
let (db, same) = report.picture.unwrap();
|
||||
assert!(same && db.is_infinite(), "{what}: the picture differs ({db} dB)");
|
||||
let mut get = |name: &str| {
|
||||
let id = player.named(name).unwrap();
|
||||
player.contents(id).unwrap().unwrap()
|
||||
};
|
||||
assert_eq!(get("sum"), expected.sum, "{what}: sum");
|
||||
assert_eq!(rows(&get("image")), expected.image, "{what}: image");
|
||||
assert_eq!(get("target"), expected.picture, "{what}: target");
|
||||
assert!(get("shared") == expected.shared, "{what}: memory the CPU sees");
|
||||
assert!(!report.notes.iter().any(|n| n.contains("recorder:") && !n.contains("submissions,") && !n.contains("waits of the")), "{what}: {:?}", report.notes);
|
||||
report
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_is_recorded_and_replayed() {
|
||||
let debug = std::env::var_os("VICTORY_TEST_D3D_DEBUG").is_some();
|
||||
let mut device: Option<ID3D12Device> = None;
|
||||
// SAFETY: plain creation.
|
||||
unsafe {
|
||||
if debug {
|
||||
let mut layer: Option<ID3D12Debug> = None;
|
||||
D3D12GetDebugInterface(&mut layer).unwrap();
|
||||
layer.unwrap().EnableDebugLayer();
|
||||
}
|
||||
let _ = D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device);
|
||||
}
|
||||
let Some(device) = device else {
|
||||
eprintln!("no adapter: skipped");
|
||||
return;
|
||||
};
|
||||
let own = table_of(&device);
|
||||
// Without the recorder.
|
||||
let without = {
|
||||
let mut scene = Scene::new(&device, false);
|
||||
(0..5).for_each(|n| scene.frame(n));
|
||||
scene.outcome()
|
||||
};
|
||||
eprintln!("ran without the recorder");
|
||||
// Something is in the picture.
|
||||
assert!(without.sum.iter().any(|&b| b != 0));
|
||||
let colors: std::collections::HashSet<[u8; 4]> =
|
||||
without.picture.chunks_exact(4).map(|c| [c[0], c[1], c[2], c[3]]).collect();
|
||||
assert!(colors.len() > 30, "{}", colors.len());
|
||||
|
||||
// With it: armed at the first present, the fourth frame is captured (a
|
||||
// frame whose lists are all recorded comes first).
|
||||
assert!(!record::on());
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let settings = Settings { folder: dir.path().to_owned(), at: At::Frame(1), frames: 1 };
|
||||
let folder = record::start(settings, &device).unwrap();
|
||||
assert!(record::on());
|
||||
assert_ne!(table_of(&device), own, "the device is hooked");
|
||||
assert!(
|
||||
record::start(Settings { folder: dir.path().to_owned(), at: At::Trigger, frames: 1 }, &device).is_err(),
|
||||
"one recorder a process"
|
||||
);
|
||||
eprintln!("recorder on");
|
||||
let mut scene = Scene::new(&device, true);
|
||||
eprintln!("scene made");
|
||||
(0..4).for_each(|n| scene.frame(n));
|
||||
assert_eq!(record::finished(), Some(folder.clone()), "see {}", folder.display());
|
||||
let expected = scene.outcome();
|
||||
// It goes on as it did without the recorder.
|
||||
scene.frame(4);
|
||||
let after = scene.outcome();
|
||||
assert!(after == without, "the recorder changed what the program makes");
|
||||
drop(scene);
|
||||
record::unhook(&device);
|
||||
assert_eq!(table_of(&device), own, "the device is as it was");
|
||||
for name in ["frame.bin", "contents.bin", "deltas.bin", "shaders.bin", "present.bin", "notes.txt", "frame-0.png"] {
|
||||
assert!(folder.join(name).exists(), "{name}");
|
||||
}
|
||||
println!("{}", std::fs::read_to_string(folder.join("notes.txt")).unwrap());
|
||||
|
||||
let plain = Options { loops: 3, ..Default::default() };
|
||||
let mut player = Player::load(dir.path(), &plain).unwrap();
|
||||
check(&mut player, &plain, &expected, "unchanged");
|
||||
let detailed = Options { detailed: true, ..plain.clone() };
|
||||
let report = check(&mut player, &detailed, &expected, "detailed");
|
||||
let count = |kind: &str| report.categories.iter().find(|c| c.0 == kind).map_or(0, |c| c.2);
|
||||
assert_eq!(count("argument clamps (ours)"), 3);
|
||||
assert_eq!(count("indirect draws"), 5);
|
||||
assert_eq!(count("dispatches"), 6);
|
||||
assert_eq!(count("clears"), 2);
|
||||
assert!(report.shaders.iter().any(|s| s.2.starts_with("a drawing pipeline (DXIL ")), "{:?}", report.shaders);
|
||||
let merged = Options { merge_barriers: true, ..plain.clone() };
|
||||
check(&mut player, &merged, &expected, "merged barriers");
|
||||
let clamps = Options { skip_clamps: true, ..plain.clone() };
|
||||
let report = check(&mut player, &clamps, &expected, "without clamps");
|
||||
assert!(report.notes.iter().any(|n| n.contains("3 clamp passes")), "{:?}", report.notes);
|
||||
let one = Options { one_submit: true, ..plain.clone() };
|
||||
check(&mut player, &one, &expected, "one submission");
|
||||
let hash = Options { skip_hash_passes: true, ..plain.clone() };
|
||||
check(&mut player, &hash, &expected, "without hash passes (there are none)");
|
||||
// These change what is drawn: they run, and then the frame is as before.
|
||||
let no_barriers = Options { no_barriers: true, ..plain.clone() };
|
||||
player.run(&no_barriers).unwrap();
|
||||
let some = Options { only: Some((0, 1)), ..plain.clone() };
|
||||
player.run(&some).unwrap();
|
||||
let skip = Options { skip_shaders: vec!["a drawing".into()], ..plain.clone() };
|
||||
let report = player.run(&skip).unwrap();
|
||||
assert!(!report.picture.unwrap().1, "without its draws the picture is another");
|
||||
assert!(report.notes.iter().any(|n| n.contains("1 pipelines match")) && report.notes.iter().any(|n| n.contains("left out 5 commands")));
|
||||
let kept = Options { restore: false, ..plain.clone() };
|
||||
player.run(&kept).unwrap();
|
||||
check(&mut player, &plain, &expected, "unchanged again");
|
||||
drop(player);
|
||||
for buffers in [Buffers::Card, Buffers::Pc] {
|
||||
let o = Options { buffers, ..plain.clone() };
|
||||
let mut player = Player::load(dir.path(), &o).unwrap();
|
||||
check(&mut player, &o, &expected, &format!("buffers {buffers:?}"));
|
||||
}
|
||||
let o = Options { compare: true, merge_barriers: true, loops: 2, ..Default::default() };
|
||||
let both = play::replay(dir.path(), &o).unwrap();
|
||||
assert_eq!(both.len(), 2);
|
||||
assert!(both.iter().all(|(_, r)| r.picture.unwrap().1));
|
||||
assert!(folder.join("replay.png").exists() && folder.join("replay-unchanged.png").exists());
|
||||
if debug {
|
||||
let q = device.cast::<ID3D12InfoQueue>().unwrap();
|
||||
// SAFETY: plain queries; messages read into buffers of their size.
|
||||
unsafe {
|
||||
for i in 0..q.GetNumStoredMessages() {
|
||||
let mut size = 0;
|
||||
let _ = q.GetMessage(i, None, &mut size);
|
||||
let mut buffer = vec![0u64; size.div_ceil(8)];
|
||||
let m = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
|
||||
if q.GetMessage(i, Some(m), &mut size).is_ok() && (*m).Severity.0 <= D3D12_MESSAGE_SEVERITY_WARNING.0 {
|
||||
let text = std::slice::from_raw_parts((*m).pDescription, (*m).DescriptionByteLength);
|
||||
println!("D3D12 {} {}: {}", (*m).Severity.0, (*m).ID.0, String::from_utf8_lossy(text));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user