Frame replay: usage doc, mesh draws and a title's size in its tests

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-24 20:23:46 -06:00
1 parent d7ecfd2bba
commit af481877f3
13 files changed
+4274 -828

No files matched your search

+210 -33
View File
@@ -52,7 +52,9 @@ pub fn no_uav_barriers(cmds: Vec<Cmd>) -> (Vec<Cmd>, u32) {
/// 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()
cmds.into_iter()
.filter(|c| matches!(c, Cmd::Barriers { .. }))
.collect()
}
/// Joins the barrier calls with no work between them into one; how many
@@ -96,7 +98,9 @@ pub fn merge_barriers(cmds: Vec<Cmd>) -> (Vec<Cmd>, u32) {
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));
let covered = have
.iter()
.any(|h| matches!(h, Barrier::Uav { res: r, .. } if *r == res || *r == NONE));
if covered {
return;
}
@@ -105,16 +109,36 @@ fn join(have: &mut Vec<Barrier>, b: Barrier) {
}
have.push(b);
}
Barrier::Transition { flags: 0, res, sub, before, after } => {
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));
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]
&& 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 };
have[i] = Barrier::Transition {
flags: 0,
res,
sub,
before: first,
after,
};
} else {
have.remove(i);
if after == UNORDERED_ACCESS {
@@ -150,7 +174,12 @@ pub fn find_clamps(cmds: &[Cmd], psos: &HashSet<u32>, next: &mut u64) -> Vec<Cla
for (at, c) in cmds.iter().enumerate() {
match c {
Cmd::Pipeline { pso } => bound = *pso,
Cmd::Constants { graphics: false, param: 0, offset, values } => {
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;
@@ -159,11 +188,21 @@ pub fn find_clamps(cmds: &[Cmd], psos: &HashSet<u32>, next: &mut u64) -> Vec<Cla
}
// 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::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 });
found.push(Clamp {
at,
scratch,
bytes,
result: *next,
});
*next += bytes.next_multiple_of(256);
}
}
@@ -189,10 +228,22 @@ pub fn keep_clamped(cmds: Vec<Cmd>, clamps: &[Clamp]) -> Vec<Cmd> {
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 }],
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(Cmd::CopyBuffer {
dst: RESULTS,
dst_at: clamp.result,
src: clamp.scratch,
src_at: 0,
len: clamp.bytes,
});
out.push(moved(COPY_SOURCE, INDIRECT_ARGUMENT));
}
}
@@ -223,9 +274,23 @@ pub fn skip_clamps(cmds: Vec<Cmd>, clamps: &[Clamp]) -> Vec<Cmd> {
out.push(Cmd::Barriers { all });
}
}
Cmd::Indirect { signature, most, args, at, count, count_at } if last.contains_key(&args) => {
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 });
out.push(Cmd::Indirect {
signature,
most,
args: RESULTS,
at: result + at,
count,
count_at,
});
}
c => out.push(c),
}
@@ -247,7 +312,13 @@ mod tests {
Barrier::Uav { flags: 0, res }
}
fn moved(res: u32, before: i32, after: i32) -> Barrier {
Barrier::Transition { flags: 0, res, sub: ALL, before, after }
Barrier::Transition {
flags: 0,
res,
sub: ALL,
before,
after,
}
}
fn barriers(all: &[Barrier]) -> Cmd {
Cmd::Barriers { all: all.to_vec() }
@@ -255,18 +326,47 @@ mod tests {
#[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 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!(
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()]);
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]
@@ -286,11 +386,33 @@ mod tests {
];
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()]);
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)])]);
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]
@@ -299,29 +421,84 @@ mod tests {
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 } },
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 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!(
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);
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)]);
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)]
);
}
}
+96 -19
View File
@@ -46,9 +46,15 @@ impl Worker {
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)?;
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
@@ -100,7 +106,10 @@ pub(super) fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOU
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: flags,
..Default::default()
@@ -114,7 +123,10 @@ pub(super) fn buffer(
size: u64,
flags: D3D12_RESOURCE_FLAGS,
) -> Result<(ID3D12Resource, *mut u8)> {
let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() };
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,
@@ -124,7 +136,14 @@ pub(super) fn buffer(
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)?;
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))?;
@@ -146,7 +165,11 @@ 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) };
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)
}
@@ -161,7 +184,18 @@ pub(super) fn footprints(
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)) };
unsafe {
device.GetCopyableFootprints(
desc,
first,
count,
0,
Some(all.as_mut_ptr()),
None,
None,
Some(&mut total),
)
};
(all, total)
}
@@ -171,12 +205,17 @@ pub(super) fn sub_location(res: &ID3D12Resource, sub: u32) -> D3D12_TEXTURE_COPY
// 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 },
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 {
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) },
@@ -186,7 +225,12 @@ pub(super) fn placed_location(res: &ID3D12Resource, f: D3D12_PLACED_SUBRESOURCE_
}
/// A transition; no reference is taken.
pub(super) fn transition(res: &ID3D12Resource, sub: u32, before: u32, after: u32) -> D3D12_RESOURCE_BARRIER {
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,
@@ -204,7 +248,12 @@ pub(super) fn transition(res: &ID3D12Resource, sub: u32, before: u32, after: u32
/// 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>) {
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] {
@@ -229,7 +278,10 @@ pub(super) fn to_desc(d: &wire::Desc) -> D3D12_RESOURCE_DESC {
DepthOrArraySize: d.depth,
MipLevels: d.mips,
Format: DXGI_FORMAT(d.format),
SampleDesc: DXGI_SAMPLE_DESC { Count: d.samples[0], Quality: d.samples[1] },
SampleDesc: DXGI_SAMPLE_DESC {
Count: d.samples[0],
Quality: d.samples[1],
},
Layout: D3D12_TEXTURE_LAYOUT(d.layout),
Flags: D3D12_RESOURCE_FLAGS(d.flags),
}
@@ -260,7 +312,11 @@ pub(super) fn to_props(p: &wire::HeapProps) -> D3D12_HEAP_PROPERTIES {
}
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 }
wire::HeapProps {
kind: p.Type.0,
cpu: p.CPUPageProperty.0,
pool: p.MemoryPoolPreference.0,
}
}
/// How the CPU sees memory of a heap.
@@ -294,7 +350,13 @@ pub(super) fn seen(p: &wire::HeapProps) -> Seen {
/// 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>> {
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]]);
@@ -304,7 +366,11 @@ pub(super) fn rgb(width: u32, height: u32, pitch: u32, format: i32, rows: &[u8])
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 }
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..)?;
@@ -334,7 +400,11 @@ pub(super) fn rgb(width: u32, height: u32, pitch: u32, format: i32, rows: &[u8])
/// 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();
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;
}
@@ -354,7 +424,11 @@ pub(super) fn adapter(device: &ID3D12Device) -> (String, u32, u32) {
match desc {
Ok(d) => {
let name = String::from_utf16_lossy(&d.Description);
(name.trim_end_matches('\0').to_owned(), d.VendorId, d.DeviceId)
(
name.trim_end_matches('\0').to_owned(),
d.VendorId,
d.DeviceId,
)
}
Err(_) => ("unknown".into(), 0, 0),
}
@@ -371,7 +445,10 @@ mod tests {
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_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);
+75 -16
View File
@@ -9,7 +9,7 @@ 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;
pub(super) const SLOTS: usize = 512;
/// Entries copied from before the table (type information).
const PRE: usize = 4;
@@ -64,9 +64,24 @@ fn readable(at: usize, most: usize) -> usize {
// 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 {
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;
@@ -81,21 +96,32 @@ fn readable(at: usize, most: usize) -> usize {
/// # 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 {
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 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) };
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);
@@ -130,14 +156,20 @@ pub(super) unsafe fn ours(this: *mut c_void) -> bool {
///
/// # 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])) {
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>();
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 {
@@ -223,14 +255,28 @@ mod tests {
value: u64,
}
unsafe extern "system" fn add(this: *mut c_void, a: u64, b: u64, c: u64, d: u64, e: f64) -> 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 {
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];
@@ -249,9 +295,17 @@ mod tests {
#[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 };
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();
@@ -260,7 +314,10 @@ mod tests {
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!(
!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");
@@ -277,7 +334,9 @@ mod tests {
again(this, shim, patch);
assert_eq!(table(this), shim);
// Or to another table.
let other = Vtbl { methods: [add as *const () as usize; 8] };
let other = Vtbl {
methods: [add as *const () as usize; 8],
};
a.vtbl = &other;
again(this, shim, patch);
assert!(ours(this) && table(this) != shim);
File diff suppressed because it is too large. Load diff
+155 -48
View File
@@ -55,7 +55,10 @@ pub(super) trait Keep {
/// `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()) }
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> {
@@ -63,8 +66,12 @@ unsafe fn code(kind: i32, c: &D3D12_SHADER_BYTECODE, keep: &mut dyn Keep) -> Opt
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) })
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> {
@@ -72,34 +79,44 @@ unsafe fn layout(l: &D3D12_INPUT_LAYOUT_DESC) -> Option<Part> {
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();
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> {
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)) }];
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.push(plain(
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS.0,
(&raw const d.Flags).cast(),
4,
));
}
parts
}
@@ -107,27 +124,55 @@ pub(super) unsafe fn compute(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, keep: &mut d
/// # Safety
/// A valid description.
pub(super) unsafe fn graphics(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, keep: &mut dyn Keep) -> Vec<Part> {
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)) }];
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(
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.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>()));
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>()));
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));
}
@@ -137,7 +182,10 @@ pub(super) unsafe fn graphics(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, keep: &mut
/// # Safety
/// A valid description.
pub(super) unsafe fn stream(d: &D3D12_PIPELINE_STATE_STREAM_DESC, keep: &mut dyn Keep) -> Vec<Part> {
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;
@@ -147,7 +195,9 @@ pub(super) unsafe fn stream(d: &D3D12_PIPELINE_STATE_STREAM_DESC, keep: &mut dyn
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"));
keep.lost(&format!(
"a pipeline stream's subobject of type {kind}, and those after it"
));
break;
};
let (from, size) = match h {
@@ -158,12 +208,16 @@ pub(super) unsafe fn stream(d: &D3D12_PIPELINE_STATE_STREAM_DESC, keep: &mut dyn
};
let value = base.add(at + from);
match h {
Holds::Root => parts.push(Part::Root { root: keep.root(value.cast::<*mut c_void>().read()) }),
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);
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}"));
}
@@ -194,13 +248,15 @@ pub(super) fn make(
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"))?;
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"))?;
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());
@@ -217,7 +273,9 @@ pub(super) fn make(
.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())),
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],
@@ -227,7 +285,11 @@ pub(super) fn make(
}
})
.collect();
bytes.extend(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT.0.to_le_bytes());
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());
@@ -237,13 +299,17 @@ pub(super) fn make(
}
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 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) };
let made: windows::core::Result<ID3D12PipelineState> =
unsafe { device.CreatePipelineState(&desc) };
made.map_err(|e| e.to_string())
}
@@ -290,17 +356,44 @@ mod tests {
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 }),
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() }),
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() }),
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 }),
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 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) };
@@ -309,9 +402,23 @@ mod tests {
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!(
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()) });
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
+411 -85
View File
@@ -15,7 +15,9 @@ 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, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot};
use super::wire::{
self, ALL, Cmd, Content, Delta, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot,
};
type Fault = Box<dyn std::error::Error + Send + Sync>;
@@ -29,7 +31,7 @@ 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;
const PATIENCE: u64 = 100;
#[derive(Default)]
enum Stage {
@@ -61,19 +63,38 @@ impl Phase {
/// 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));
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()) {
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();
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;
let whole = |c: &Option<Closed>| c.as_ref().is_some_and(|c| c.0.is_some());
phase.missing += lists
.iter()
.zip(&closed)
.filter(|(p, c)| !whole(c) && r.knows(**p))
.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 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);
@@ -102,7 +123,10 @@ 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 (submits, missing) = (
std::mem::take(&mut phase.submits),
std::mem::take(&mut phase.missing),
);
let mut finished = None;
match &mut phase.stage {
Stage::Waiting => {
@@ -124,7 +148,11 @@ pub(super) fn present(r: &Recorder, texture: &ID3D12Resource, state: u32) {
if !whole {
r.problem("no frame was found whose lists were all recorded");
}
tracing::info!(presents, waited, "frame recorder: the next frame is captured");
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),
@@ -178,16 +206,36 @@ impl Reads {
};
for c in cmds {
match c {
Cmd::RootView { va, .. } | Cmd::IndexBuffer { view: Some((va, _, _)) } => whole(va),
Cmd::VertexBuffers { views: Some(views), .. } => views.iter().for_each(|(va, _, _)| whole(va)),
Cmd::RootView { va, .. }
| Cmd::IndexBuffer {
view: Some((va, _, _)),
} => whole(va),
Cmd::VertexBuffers {
views: Some(views), ..
} => views.iter().for_each(|(va, _, _)| whole(va)),
Cmd::Indirect { args, count, .. } => {
for res in [*args, *count] {
whole(&Va::At { res, offset: 0 });
}
}
Cmd::CopyResource { src, .. } => whole(&Va::At { res: *src, offset: 0 }),
Cmd::CopyBuffer { src, src_at, len, .. } => parts.entry(*src).or_default().push((*src_at, src_at + len)),
Cmd::CopyTexture { src: Loc::Placed { res, offset, size, pitch, .. }, .. } => {
Cmd::CopyResource { src, .. } => whole(&Va::At {
res: *src,
offset: 0,
}),
Cmd::CopyBuffer {
src, src_at, len, ..
} => parts.entry(*src).or_default().push((*src_at, src_at + len)),
Cmd::CopyTexture {
src:
Loc::Placed {
res,
offset,
size,
pitch,
..
},
..
} => {
// At the most: compressed formats have fewer rows.
let len = u64::from(*pitch) * u64::from(size[1]) * u64::from(size[2].max(1));
parts.entry(*res).or_default().push((*offset, offset + len));
@@ -208,7 +256,12 @@ impl Reads {
};
let mut pages: Vec<(usize, usize)> = parts
.iter()
.map(|&(from, to)| (from as usize / PAGE * PAGE, (to as usize).next_multiple_of(PAGE).min(size)))
.map(|&(from, to)| {
(
from as usize / PAGE * PAGE,
(to as usize).next_multiple_of(PAGE).min(size),
)
})
.filter(|(from, to)| from < to)
.collect();
pages.sort_unstable();
@@ -277,7 +330,10 @@ impl Capture {
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 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)?);
@@ -309,7 +365,11 @@ impl Capture {
})
}
fn timed<T>(&mut self, what: &'static str, f: impl FnOnce(&mut Self) -> Result<T, Fault>) -> Result<T, Fault> {
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();
@@ -332,14 +392,22 @@ impl Capture {
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()) };
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()) });
self.held
.push(unsafe { ID3D12Resource::from_raw(object.as_raw()) });
all.push(res.clone());
}
}
@@ -357,10 +425,21 @@ impl Capture {
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 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));
heaps
.entry(heap)
.or_default()
.push((used, offset, offset + size, res.id));
}
}
let mut idle = HashSet::new();
@@ -368,7 +447,10 @@ impl Capture {
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);
let overlaps = taken
.range(..to)
.next_back()
.is_some_and(|(_, &end)| end > from);
if overlaps {
idle.insert(id);
} else {
@@ -390,7 +472,13 @@ impl Capture {
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 });
pieces.push(Piece {
res: res.clone(),
first: at,
count: 1,
len,
at: 0,
});
at += len;
}
continue;
@@ -404,14 +492,28 @@ impl Capture {
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 });
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 });
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");
r.problem(
"contents of a texture level of over 256 MB are not in the capture",
);
}
}
}
@@ -433,7 +535,12 @@ impl Capture {
}
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)?);
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);
@@ -448,7 +555,8 @@ impl Capture {
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);
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();
@@ -456,14 +564,29 @@ impl Capture {
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) };
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 });
lock(contents).push(Content {
res: p.res.id,
first: p.first,
count: p.count,
len: p.len,
file: at,
});
}
let _ = free.send(i);
}
@@ -476,7 +599,9 @@ impl Capture {
continue;
}
let i = freed.recv()?;
let value = self.worker.send(|list| copy_out(&device, list, &self.states, &pieces, &stagings[i].0))?;
let value = self
.worker
.send(|list| copy_out(&device, list, &self.states, &pieces, &stagings[i].0))?;
self.worker.wait(value)?;
todo.send((i, pieces))?;
}
@@ -493,7 +618,9 @@ impl Capture {
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))
.filter(|res| {
matches!(res.seen, Seen::Cached | Seen::Combined) && !self.known.contains(&res.id)
})
.cloned()
.collect();
for res in fresh {
@@ -516,7 +643,12 @@ impl Capture {
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)?;
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
}
@@ -526,7 +658,14 @@ impl Capture {
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] });
self.buffers.push(CpuBuffer {
id: res.id,
res: object,
live,
through,
size,
kept: vec![0; size],
});
}
Ok(())
}
@@ -540,7 +679,12 @@ impl Capture {
.buffers
.iter()
.enumerate()
.flat_map(|(i, b)| reads.pages(b.id, b.size, self.viewed.contains(&b.id)).into_iter().map(move |(from, to)| (i, from, to)))
.flat_map(|(i, b)| {
reads
.pages(b.id, b.size, self.viewed.contains(&b.id))
.into_iter()
.map(move |(from, to)| (i, from, to))
})
.collect();
if parts.iter().any(|p| self.buffers[p.0].through.is_some()) {
let (buffers, blocks) = (&self.buffers, &self.blocks);
@@ -549,24 +693,43 @@ impl Capture {
let b = &buffers[i];
if let Some((block, at)) = b.through {
// SAFETY: an open list and live buffers.
unsafe { list.CopyBufferRegion(&blocks[block].0, at + from as u64, &b.res, from as u64, (to - from) as u64) };
unsafe {
list.CopyBufferRegion(
&blocks[block].0,
at + from as u64,
&b.res,
from as u64,
(to - from) as u64,
)
};
}
}
})?;
}
let chunks: Vec<(usize, usize, usize)> = parts
.iter()
.flat_map(|&(i, from, to)| (from..to).step_by(CHUNK).map(move |at| (i, at, CHUNK.min(to - at))))
.flat_map(|&(i, from, to)| {
(from..to)
.step_by(CHUNK)
.map(move |at| (i, at, CHUNK.min(to - 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 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 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 {
@@ -574,19 +737,30 @@ impl Capture {
let mut mine = Vec::new();
loop {
let i = next.fetch_add(1, Ordering::Relaxed);
let Some(&(b, at, len)) = chunks.get(i) else { break };
let Some(&(b, at, len)) = chunks.get(i) else {
break;
};
// 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) };
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 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 });
mine.push(Delta {
res: buffers[b].id,
at: (at + from) as u64,
len: bytes.len() as u64,
file: file_at,
});
}
}
lock(&out).extend(mine);
@@ -601,7 +775,12 @@ impl Capture {
Ok(out)
}
fn submit(&mut self, r: &Recorder, _queue: &ID3D12CommandQueue, lists: &[Option<Arc<Vec<u8>>>]) -> Result<(), Fault> {
fn submit(
&mut self,
r: &Recorder,
_queue: &ID3D12CommandQueue,
lists: &[Option<Arc<Vec<u8>>>],
) -> Result<(), Fault> {
let first = !self.started;
if first {
self.start(r)?;
@@ -615,7 +794,8 @@ impl Capture {
let heaps: Vec<Arc<Heap>> = read(&r.descriptors).visible().cloned().collect();
for h in heaps {
let runs = runs_of(r, &h.all());
self.viewed.extend(runs.iter().flat_map(|(_, _, s)| [s.res, s.counter]));
self.viewed
.extend(runs.iter().flat_map(|(_, _, s)| [s.res, s.counter]));
self.heaps.push((h, runs));
}
} else {
@@ -625,7 +805,10 @@ impl Capture {
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 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
@@ -649,10 +832,16 @@ impl Capture {
for l in lists {
numbers.push(match l {
None => {
r.problem("a list was submitted that was not recorded whole: its work is missing");
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(commands) => match self
.lists
.iter()
.position(|have| Arc::ptr_eq(have, commands))
{
Some(i) => i as u32,
None => {
self.lists.push(commands.clone());
@@ -661,7 +850,12 @@ impl Capture {
},
});
}
self.submits.push(wire::Submit { frame: self.frame, lists: numbers, deltas, views });
self.submits.push(wire::Submit {
frame: self.frame,
lists: numbers,
deltas,
views,
});
Ok(())
}
@@ -670,8 +864,14 @@ impl Capture {
// 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]))?;
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)?;
@@ -688,7 +888,10 @@ impl Capture {
});
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))?,
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;
@@ -722,20 +925,35 @@ impl Capture {
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();
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());
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)),
Cmd::Pipeline { pso } => _ = psos.insert(pso),
Cmd::RootSignature { root, .. } => _ = roots.insert(root),
Cmd::Indirect { signature, .. } => _ = signatures.insert(signature),
Cmd::BeginQuery { heap, .. }
| Cmd::EndQuery { heap, .. }
| Cmd::ResolveQuery { heap, .. } => _ = queries.insert(heap),
_ => {}
}
}
@@ -747,22 +965,38 @@ impl Capture {
.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() })
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 }));
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()
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()
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 {
@@ -771,7 +1005,12 @@ impl Capture {
}
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();
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(),
@@ -800,16 +1039,28 @@ impl Capture {
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() })
.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()
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()) })
.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),
@@ -833,7 +1084,13 @@ struct Piece {
/// 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) {
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()) {
@@ -842,7 +1099,16 @@ fn copy_out(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, states: &St
}
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();
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);
}
@@ -857,10 +1123,18 @@ fn copy_out(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, states: &St
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);
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);
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() {
@@ -884,7 +1158,14 @@ pub(super) fn read_sub(
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);
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)]);
}
@@ -895,9 +1176,15 @@ pub(super) fn read_sub(
/// buffer and offset.
fn resolved(r: &Recorder, mut s: Slot) -> Slot {
let kind = i32::from_le_bytes([s.desc[4], s.desc[5], s.desc[6], s.desc[7]]);
if s.kind == slot::SRV && s.described != 0 && kind == D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE.0 {
if s.kind == slot::SRV
&& s.described != 0
&& kind == D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE.0
{
r.problem("views of acceleration structures are null in the capture");
return Slot { kind: slot::SRV, ..Slot::EMPTY };
return Slot {
kind: slot::SRV,
..Slot::EMPTY
};
}
if s.kind == slot::CBV && s.described != 0 {
match r.va(s.address()) {
@@ -908,7 +1195,10 @@ fn resolved(r: &Recorder, mut s: Slot) -> Slot {
Va::Null {} => {}
Va::Unknown { .. } => {
// Its buffer is gone: nothing may read it.
s = Slot { kind: slot::CBV, ..Slot::EMPTY };
s = Slot {
kind: slot::CBV,
..Slot::EMPTY
};
}
}
}
@@ -964,7 +1254,8 @@ unsafe fn changed_runs(live: *const u8, kept: *mut u8, len: usize) -> Vec<(usize
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);
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() {
@@ -994,7 +1285,10 @@ mod tests {
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!(
find(&live, &mut kept),
[(PAGE, 3 * PAGE), (5 * PAGE, 5 * PAGE + 100)]
);
assert_eq!(live, kept);
assert!(find(&live, &mut kept).is_empty());
}
@@ -1002,7 +1296,13 @@ mod tests {
#[test]
fn what_a_submission_reads() {
let mut reads = Reads::default();
let part = |from, len| Cmd::CopyBuffer { dst: 9, dst_at: 0, src: 1, src_at: from, len };
let part = |from, len| Cmd::CopyBuffer {
dst: 9,
dst_at: 0,
src: 1,
src_at: from,
len,
};
reads.note(&[
part(100, 50),
part(4000, 200),
@@ -1010,18 +1310,44 @@ mod tests {
Cmd::CopyTexture {
dst: Loc::Sub { res: 9, sub: 0 },
at: [0; 3],
src: Loc::Placed { res: 2, offset: 4096, format: 28, size: [16, 16, 1], pitch: 256 },
src: Loc::Placed {
res: 2,
offset: 4096,
format: 28,
size: [16, 16, 1],
pitch: 256,
},
part: None,
},
Cmd::Indirect { signature: 1, most: 1, args: 3, at: 8, count: 0, count_at: 0 },
Cmd::RootView { graphics: true, kind: slot::CBV, param: 0, va: Va::At { res: 4, offset: 5 } },
Cmd::Indirect {
signature: 1,
most: 1,
args: 3,
at: 8,
count: 0,
count_at: 0,
},
Cmd::RootView {
graphics: true,
kind: slot::CBV,
param: 0,
va: Va::At { res: 4, offset: 5 },
},
]);
assert_eq!(reads.pages(1, 1 << 20, false), [(0, 8192), (16384, 20480)]);
assert_eq!(reads.pages(1, 20_100, false), [(0, 8192), (16384, 20_100)], "its end");
assert_eq!(
reads.pages(1, 20_100, false),
[(0, 8192), (16384, 20_100)],
"its end"
);
assert_eq!(reads.pages(2, 1 << 20, false), [(4096, 8192)]);
assert_eq!(reads.pages(3, 100, false), [(0, 100)]);
assert_eq!(reads.pages(4, 100, false), [(0, 100)]);
assert_eq!(reads.pages(5, 100, true), [(0, 100)], "a descriptor names it");
assert_eq!(
reads.pages(5, 100, true),
[(0, 100)],
"a descriptor names it"
);
assert!(reads.pages(5, 100, false).is_empty() && reads.pages(9, 100, false).is_empty());
}
+82 -11
View File
@@ -51,7 +51,15 @@ pub struct States {
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() });
self.map.insert(
res,
One {
subs: subs.max(1),
decays,
all: state,
each: Vec::new(),
},
);
}
/// A placed resource is the one in use now.
@@ -68,7 +76,11 @@ impl States {
/// 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() })
Some(if one.each.is_empty() {
vec![one.all]
} else {
one.each.clone()
})
}
pub fn change(&mut self, c: &Change) {
@@ -120,23 +132,50 @@ impl States {
/// 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 };
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::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 });
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::CopyTexture {
dst: Loc::Sub { res, sub },
..
} => out.push(promoted(*res, *sub)),
Cmd::CopyResource { dst, .. } => out.push(promoted(*dst, ALL)),
_ => {}
}
@@ -147,7 +186,13 @@ mod tests {
use super::*;
fn set(res: u32, sub: u32, after: u32) -> Change {
Change { res, sub, after, promoted: false, alias: false }
Change {
res,
sub,
after,
promoted: false,
alias: false,
}
}
#[test]
@@ -165,7 +210,13 @@ mod tests {
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 };
let copy = |res| Change {
res,
sub: ALL,
after: COPY_DEST,
promoted: true,
alias: false,
};
s.change(&copy(2));
s.change(&copy(1));
s.decay();
@@ -183,8 +234,28 @@ mod tests {
#[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);
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);
+298 -53
View File
@@ -94,7 +94,11 @@ impl<T: Wire> Wire for Option<T> {
}
}
fn get(from: &mut Dec) -> Result<Self, Bad> {
Ok(if bool::get(from)? { Some(T::get(from)?) } else { None })
Ok(if bool::get(from)? {
Some(T::get(from)?)
} else {
None
})
}
}
@@ -228,14 +232,26 @@ pub mod slot {
}
impl Slot {
pub const EMPTY: Slot = Slot { kind: slot::EMPTY, described: 0, pad: 0, res: NONE, counter: NONE, desc: [0; 52] };
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 };
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.
@@ -247,7 +263,14 @@ impl Slot {
/// 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],
self.desc[0],
self.desc[1],
self.desc[2],
self.desc[3],
self.desc[4],
self.desc[5],
self.desc[6],
self.desc[7],
])
}
@@ -276,7 +299,14 @@ impl Wire for Slot {
}
let mut desc = [0; 52];
desc[..n].copy_from_slice(from.take(n)?);
Ok(Slot { kind, described, pad: 0, res, counter, desc })
Ok(Slot {
kind,
described,
pad: 0,
res,
counter,
desc,
})
}
}
@@ -383,7 +413,11 @@ impl Cmd {
pub fn runs_shaders(&self) -> bool {
matches!(
self,
Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::Dispatch { .. } | Cmd::DispatchMesh { .. } | Cmd::Indirect { .. }
Cmd::Draw { .. }
| Cmd::DrawIndexed { .. }
| Cmd::Dispatch { .. }
| Cmd::DispatchMesh { .. }
| Cmd::Indirect { .. }
)
}
}
@@ -589,59 +623,198 @@ pub(crate) mod tests {
let mut desc = [0; 52];
desc[3] = 7;
desc[51] = 9;
Slot { kind: slot::SAMPLER, described: 1, pad: 0, res: 4, counter: 5, desc }
Slot {
kind: slot::SAMPLER,
described: 1,
pad: 0,
res: 4,
counter: 5,
desc,
}
}
fn at() -> Va {
Va::At { res: 3, offset: 1 << 40 }
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 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::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::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::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::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: 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::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::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 },
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,
},
]
}
@@ -664,13 +837,23 @@ pub(crate) mod tests {
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");
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 props = HeapProps {
kind: 4,
cpu: 3,
pool: 1,
};
let desc = Desc {
dimension: 3,
alignment: 65536,
@@ -685,7 +868,10 @@ pub(crate) mod tests {
};
let resource = Resource {
id: 2,
place: Place::Placed { heap: 1, offset: 65536 },
place: Place::Placed {
heap: 1,
offset: 65536,
},
desc,
made_in: 4,
clear: Some([28, 1, 2, 3, 4]),
@@ -699,36 +885,95 @@ pub(crate) mod tests {
vendor: 0x1002,
device: 0x744c,
notes: vec!["nothing".into()],
heaps: vec![Heap { id: 1, size: 64 << 20, props: props.clone(), alignment: 65536, flags: 0x84 }],
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 },
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] }],
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])] },
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]) }],
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 }],
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 }],
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();