Merge local/replay: frame recorder and replayer

Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	apps/victory/src/main.rs
This commit is contained in:
local committed 2026-11-24 20:30:25 -06:00
commit c897fa28ff
20 files changed
+12602 -7

No files matched your search

+23 -6
View File
@@ -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]) {
+21 -1
View File
@@ -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,21 @@ 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() {
let text = text();
crate::replay::record::name(object, &text);
if dred_on()
&& let Ok(object) = object.cast::<ID3D12Object>()
{
// SAFETY: a plain call on a live object.
let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text)) };
}
return;
}
if dred_on()
&& let Ok(object) = object.cast::<ID3D12Object>()
{
@@ -3153,6 +3169,8 @@ impl Host {
},
..Default::default()
})?;
#[cfg(feature = "diagnostics")]
name(&pso, || crate::replay::play::COMPARE.into());
Ok(CardWork {
sync: vec![list()?],
check: vec![list()?],
@@ -6398,6 +6416,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")]
+2
View File
@@ -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 })
}
}
+2
View File
@@ -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)]
+504
View File
@@ -0,0 +1,504 @@
//! 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)]
);
}
}
+469
View File
@@ -0,0 +1,469 @@
//! 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);
}
}
+349
View File
@@ -0,0 +1,349 @@
//! 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 = 512;
/// 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);
}
}
}
+17
View File
@@ -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
+424
View File
@@ -0,0 +1,424 @@
//! 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
File diff suppressed because it is too large. Load diff
+263
View File
@@ -0,0 +1,263 @@
//! 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(&copy(2));
s.change(&copy(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);
}
}
+986
View File
@@ -0,0 +1,986 @@
//! 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());
}
}