From af481877f3cf2af6e5d3dabd11df597c713ce848 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 20:23:46 -0600 Subject: [PATCH] Frame replay: usage doc, mesh draws and a title's size in its tests Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/replay.rs | 5 +- crates/victory-gpu/src/replay/edit.rs | 243 ++++- crates/victory-gpu/src/replay/gpu.rs | 115 ++- crates/victory-gpu/src/replay/hook.rs | 91 +- crates/victory-gpu/src/replay/play.rs | 1235 ++++++++++++++++++----- crates/victory-gpu/src/replay/pso.rs | 203 +++- crates/victory-gpu/src/replay/record.rs | 1035 +++++++++++++++---- crates/victory-gpu/src/replay/snap.rs | 496 +++++++-- crates/victory-gpu/src/replay/states.rs | 93 +- crates/victory-gpu/src/replay/wire.rs | 351 ++++++- crates/victory-gpu/tests/replay.rs | 948 ++++++++++++++--- crates/victory-gpu/tests/replay_big.rs | 185 +++- docs/replay.md | 102 ++ 13 files changed, 4274 insertions(+), 828 deletions(-) create mode 100644 docs/replay.md diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index 61de570..cad167a 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -85,7 +85,10 @@ fn range(text: &str) -> Option<(u32, u32)> { pub(crate) fn run(r: Replay) -> Result<()> { let only = match &r.only { - Some(text) => Some(range(text).with_context(|| format!("--only {text}: not a list or a range of lists (3..7)"))?), + Some(text) => Some( + range(text) + .with_context(|| format!("--only {text}: not a list or a range of lists (3..7)"))?, + ), None => None, }; let options = Options { diff --git a/crates/victory-gpu/src/replay/edit.rs b/crates/victory-gpu/src/replay/edit.rs index a49a343..08184a3 100644 --- a/crates/victory-gpu/src/replay/edit.rs +++ b/crates/victory-gpu/src/replay/edit.rs @@ -52,7 +52,9 @@ pub fn no_uav_barriers(cmds: Vec) -> (Vec, u32) { /// Barriers only: what a list left out still does to the states of /// resources. pub fn barriers_only(cmds: Vec) -> Vec { - 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) -> (Vec, u32) { fn join(have: &mut Vec, 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, 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, next: &mut u64) -> Vec 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, next: &mut u64) -> Vec 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, clamps: &[Clamp]) -> Vec { 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, clamps: &[Clamp]) -> Vec { 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::>(), [(5, 24, 0), (5, 1200, 256)]); + assert_eq!( + found + .iter() + .map(|c| (c.scratch, c.bytes, c.result)) + .collect::>(), + [(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)] + ); } } diff --git a/crates/victory-gpu/src/replay/gpu.rs b/crates/victory-gpu/src/replay/gpu.rs index 61ed472..97ff62e 100644 --- a/crates/victory-gpu/src/replay/gpu.rs +++ b/crates/victory-gpu/src/replay/gpu.rs @@ -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) { +pub(super) fn moves( + res: &ID3D12Resource, + from: &[u32], + to: &[u32], + out: &mut Vec, +) { 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> { +pub(super) fn rgb( + width: u32, + height: u32, + pitch: u32, + format: i32, + rows: &[u8], +) -> Option> { 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); diff --git a/crates/victory-gpu/src/replay/hook.rs b/crates/victory-gpu/src/replay/hook.rs index e4ceca4..e18c3c3 100644 --- a/crates/victory-gpu/src/replay/hook.rs +++ b/crates/victory-gpu/src/replay/hook.rs @@ -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::()) }; - 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::(), + ) + }; + 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::() }; 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::(); + let shim = (before as *const u8) + .sub(std::mem::offset_of!(Shim, table)) + .cast::(); if (*shim).orig as usize == now { this.cast::().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::()).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); diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index c7c7131..8543f6a 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -21,8 +21,13 @@ use windows::core::Interface; use super::edit::{self, Clamp, RESULTS}; use super::gpu::{self, Seen, Worker}; use super::snap::read_sub; -use super::states::{self, COMMON, COPY_DEST, COPY_SOURCE, DEPTH_WRITE, RENDER_TARGET, RESOLVE_DEST, States, UNORDERED_ACCESS}; -use super::wire::{self, ALL, Barrier, Cmd, Content, Delta, Frame, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot}; +use super::states::{ + self, COMMON, COPY_DEST, COPY_SOURCE, DEPTH_WRITE, RENDER_TARGET, RESOLVE_DEST, States, + UNORDERED_ACCESS, +}; +use super::wire::{ + self, ALL, Barrier, Cmd, Content, Delta, Frame, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot, +}; /// The name of the argument clamp's pipeline, by which its passes are /// recognised. @@ -151,14 +156,32 @@ impl Report { /// The report as text. pub fn text(&self, what: &str) -> String { let mut t = String::new(); - let ms = |v: &[f64]| v.iter().map(|x| format!("{x:.2}")).collect::>().join(" "); - let _ = writeln!(t, "{what}: {:.2} ms on the card (median of {})", self.median_ms(), self.frame_ms.len()); + let ms = |v: &[f64]| { + v.iter() + .map(|x| format!("{x:.2}")) + .collect::>() + .join(" ") + }; + let _ = writeln!( + t, + "{what}: {:.2} ms on the card (median of {})", + self.median_ms(), + self.frame_ms.len() + ); let _ = writeln!(t, " loops, ms: {}", ms(&self.frame_ms)); let (busy, delta) = (median(&self.busy_ms), median(&self.delta_ms)); let idle = (self.median_ms() - busy - delta).max(0.0); - let _ = writeln!(t, " submissions busy {busy:.2} ms, copies standing for CPU writes {delta:.2} ms, between submissions {idle:.2} ms"); + let _ = writeln!( + t, + " submissions busy {busy:.2} ms, copies standing for CPU writes {delta:.2} ms, between submissions {idle:.2} ms" + ); let _ = writeln!(t, " by submission (lists: ms): {}", { - self.submits.iter().enumerate().map(|(i, (n, ms))| format!("{i} ({n}): {ms:.2}")).collect::>().join(", ") + self.submits + .iter() + .enumerate() + .map(|(i, (n, ms))| format!("{i} ({n}): {ms:.2}")) + .collect::>() + .join(", ") }); if !self.categories.is_empty() { let _ = writeln!(t, " by kind of command, ms (commands):"); @@ -173,8 +196,13 @@ impl Report { } } match self.picture { - Some((_, true)) => drop(writeln!(t, " picture: the same bytes as presented")), - Some((db, false)) => drop(writeln!(t, " picture: differs from the presented one, PSNR {db:.1} dB")), + Some((_, true)) => _ = writeln!(t, " picture: the same bytes as presented"), + Some((db, false)) => { + _ = writeln!( + t, + " picture: differs from the presented one, PSNR {db:.1} dB" + ) + } None => {} } for n in &self.notes { @@ -197,14 +225,20 @@ pub fn find(folder: &Path) -> Result { return Ok(folder.to_owned()); } let mut best: Option<(u32, PathBuf)> = None; - for entry in std::fs::read_dir(folder).with_context(|| format!("{}", folder.display()))?.flatten() { + for entry in std::fs::read_dir(folder) + .with_context(|| format!("{}", folder.display()))? + .flatten() + { let name = entry.file_name().to_string_lossy().into_owned(); - let Some(n) = name.strip_prefix("capture-").and_then(|n| n.parse().ok()) else { continue }; + let Some(n) = name.strip_prefix("capture-").and_then(|n| n.parse().ok()) else { + continue; + }; if entry.path().join("frame.bin").exists() && best.as_ref().is_none_or(|b| b.0 < n) { best = Some((n, entry.path())); } } - best.map(|b| b.1).ok_or_else(|| anyhow!("no capture (frame.bin) in {}", folder.display())) + best.map(|b| b.1) + .ok_or_else(|| anyhow!("no capture (frame.bin) in {}", folder.display())) } /// Loads a capture and runs it: the whole of `victory replay`. The reports, @@ -214,9 +248,19 @@ pub fn replay(folder: &Path, options: &Options) -> Result> let mut out = Vec::new(); if options.compare && options.edited() { let image = Some(player.folder.join("replay-unchanged.png")); - out.push(("unchanged".into(), player.run(&Options { image, ..options.plain() })?)); + out.push(( + "unchanged".into(), + player.run(&Options { + image, + ..options.plain() + })?, + )); } - let what = if options.edited() { "with the experiments" } else { "unchanged" }; + let what = if options.edited() { + "with the experiments" + } else { + "unchanged" + }; out.push((what.into(), player.run(options)?)); Ok(out) } @@ -292,14 +336,19 @@ impl Player { let (device, info) = make_device(&frame, options.debug)?; // SAFETY: plain creation and queries. let (queue, frequency) = unsafe { - let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { - Type: D3D12_COMMAND_LIST_TYPE_DIRECT, - ..Default::default() - })?; + let queue: ID3D12CommandQueue = + device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + })?; let frequency = queue.GetTimestampFrequency()? as f64; (queue, frequency) }; - let commands: Vec> = frame.lists.iter().map(|l| Cmd::all(&l.commands.0)).collect::>()?; + let commands: Vec> = frame + .lists + .iter() + .map(|l| Cmd::all(&l.commands.0)) + .collect::>()?; let mut player = Player { folder, worker: Worker::new(&device, &queue)?, @@ -324,7 +373,11 @@ impl Player { results: None, commands, fresh: true, - notes: frame.notes.iter().map(|n| format!("recorder: {n}")).collect(), + notes: frame + .notes + .iter() + .map(|n| format!("recorder: {n}")) + .collect(), frame, }; player.check()?; @@ -344,8 +397,15 @@ impl Player { step("contents", &mut at); player.make_masters()?; step("copies to restore from", &mut at); - let steps: Vec = steps.iter().map(|(w, d)| format!("{w} {:.1} s", d.as_secs_f64())).collect(); - player.notes.push(format!("loaded in {:.1} s: {}", began.elapsed().as_secs_f64(), steps.join(", "))); + let steps: Vec = steps + .iter() + .map(|(w, d)| format!("{w} {:.1} s", d.as_secs_f64())) + .collect(); + player.notes.push(format!( + "loaded in {:.1} s: {}", + began.elapsed().as_secs_f64(), + steps.join(", ") + )); Ok(player) } @@ -356,16 +416,39 @@ impl Player { /// Says what of the frame is not there. fn check(&mut self) -> Result<()> { - let missing = self.frame.submits.iter().flat_map(|s| &s.lists).filter(|&&l| l == MISSING).count(); + let missing = self + .frame + .submits + .iter() + .flat_map(|s| &s.lists) + .filter(|&&l| l == MISSING) + .count(); if missing > 0 { - self.note(format!("{missing} lists of the frame were not recorded: the frame is incomplete")); + self.note(format!( + "{missing} lists of the frame were not recorded: the frame is incomplete" + )); } if self.frame.submits.is_empty() { bail!("the capture has no submission"); } - let unknown = self.commands.iter().flatten().filter(|c| matches!(c, Cmd::RootView { va: Va::Unknown { .. }, .. })).count(); + let unknown = self + .commands + .iter() + .flatten() + .filter(|c| { + matches!( + c, + Cmd::RootView { + va: Va::Unknown { .. }, + .. + } + ) + }) + .count(); if unknown > 0 { - self.note(format!("{unknown} root views name memory in no known buffer: they are null in the replay")); + self.note(format!( + "{unknown} root views name memory in no known buffer: they are null in the replay" + )); } Ok(()) } @@ -394,7 +477,10 @@ impl Player { MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() }; - let card = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let card = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; match (gpu::seen(p), buffers) { (Seen::ReadBack, _) => gpu::to_props(p), (_, Buffers::Card) if buffer => card, @@ -415,7 +501,12 @@ impl Player { textures.insert(heap); } } - self.frame.heaps.iter().map(|h| h.id).filter(|id| !textures.contains(id)).collect() + self.frame + .heaps + .iter() + .map(|h| h.id) + .filter(|id| !textures.contains(id)) + .collect() }; for h in &self.frame.heaps { let desc = D3D12_HEAP_DESC { @@ -426,7 +517,8 @@ impl Player { }; let mut heap: Option = None; // SAFETY: plain creation. - unsafe { self.device.CreateHeap(&desc, &mut heap) }.with_context(|| format!("heap {}", h.id))?; + unsafe { self.device.CreateHeap(&desc, &mut heap) } + .with_context(|| format!("heap {}", h.id))?; self._heaps.extend(heap.map(|heap| (h.id, heap))); } let mut failed = 0; @@ -443,25 +535,65 @@ impl Player { let result = unsafe { match &r.place { Place::Placed { heap, offset } => match self._heaps.get(heap) { - Some(h) => self.device.CreatePlacedResource(h, *offset, &desc, D3D12_RESOURCE_STATE_COMMON, clear, &mut made), + Some(h) => self.device.CreatePlacedResource( + h, + *offset, + &desc, + D3D12_RESOURCE_STATE_COMMON, + clear, + &mut made, + ), None => Err(windows::core::Error::empty()), }, Place::Committed { props: p, flags } => { let p = props(p, is_buffer); - let state = if p.Type == D3D12_HEAP_TYPE_READBACK { D3D12_RESOURCE_STATE_COPY_DEST } else { D3D12_RESOURCE_STATE_COMMON }; - self.device.CreateCommittedResource(&p, D3D12_HEAP_FLAGS(flags & !DROP), &desc, state, clear, &mut made) + let state = if p.Type == D3D12_HEAP_TYPE_READBACK { + D3D12_RESOURCE_STATE_COPY_DEST + } else { + D3D12_RESOURCE_STATE_COMMON + }; + self.device.CreateCommittedResource( + &p, + D3D12_HEAP_FLAGS(flags & !DROP), + &desc, + state, + clear, + &mut made, + ) } Place::BackBuffer {} => { - let p = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; - self.device.CreateCommittedResource(&p, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut made) + let p = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + self.device.CreateCommittedResource( + &p, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut made, + ) } } }; match (result, made) { (Ok(()), Some(res)) => { // SAFETY: a live resource. - let va = if is_buffer { unsafe { res.GetGPUVirtualAddress() } } else { 0 }; - self.objects.insert(r.id, Object { res, va, index, subs: gpu::subresources(&r.desc) }); + let va = if is_buffer { + unsafe { res.GetGPUVirtualAddress() } + } else { + 0 + }; + self.objects.insert( + r.id, + Object { + res, + va, + index, + subs: gpu::subresources(&r.desc), + }, + ); } (e, _) => { if failed == 0 { @@ -483,7 +615,8 @@ impl Player { fn make_pipelines(&mut self) -> Result<()> { for (id, blob) in &self.frame.roots { // SAFETY: a blob the host took. - let root = unsafe { self.device.CreateRootSignature(0, &blob.0) }.with_context(|| format!("root signature {id}"))?; + let root = unsafe { self.device.CreateRootSignature(0, &blob.0) } + .with_context(|| format!("root signature {id}"))?; self.roots.insert(*id, root); } for s in &self.frame.signatures { @@ -495,11 +628,18 @@ impl Player { }; let mut made: Option = None; // SAFETY: a description the host took. - unsafe { self.device.CreateCommandSignature(&desc, self.roots.get(&s.root), &mut made)? }; + unsafe { + self.device + .CreateCommandSignature(&desc, self.roots.get(&s.root), &mut made)? + }; self.signatures.extend(made.map(|m| (s.id, m))); } for q in &self.frame.query_heaps { - let desc = D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE(q.kind), Count: q.count, NodeMask: 0 }; + let desc = D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE(q.kind), + Count: q.count, + NodeMask: 0, + }; let mut made: Option = None; // SAFETY: plain creation. unsafe { self.device.CreateQueryHeap(&desc, &mut made)? }; @@ -510,7 +650,9 @@ impl Player { let next = AtomicUsize::new(0); type Made = std::result::Result; let made: std::sync::Mutex> = std::sync::Mutex::default(); - let threads = std::thread::available_parallelism().map_or(4, |n| n.get() / 2).max(1); + let threads = std::thread::available_parallelism() + .map_or(4, |n| n.get() / 2) + .max(1); let (frame, roots) = (&self.frame, &self.roots); std::thread::scope(|scope| { for _ in 0..threads { @@ -522,8 +664,11 @@ impl Player { read_at(&file, &mut bytes, c.at).ok()?; Some(bytes) }; - let m = super::pso::make(&device, &p.parts, |id| roots.get(&id).cloned(), code); - made.lock().unwrap_or_else(|e| e.into_inner()).push((p.id, m)); + let m = + super::pso::make(&device, &p.parts, |id| roots.get(&id).cloned(), code); + made.lock() + .unwrap_or_else(|e| e.into_inner()) + .push((p.id, m)); } }); } @@ -536,7 +681,11 @@ impl Player { } } if let Some((id, e)) = refused.first() { - let n = format!("{} pipelines could not be made again, first {}: {e}", refused.len(), self.pipeline_name(*id)); + let n = format!( + "{} pipelines could not be made again, first {}: {e}", + refused.len(), + self.pipeline_name(*id) + ); self.note(n); } Ok(()) @@ -549,7 +698,15 @@ impl Player { return format!("pipeline {id}"); }; let code: Vec = self.hashes(p); - format!("{} (DXIL {})", if p.name.is_empty() { "unnamed" } else { &p.name }, code.join(" ")) + format!( + "{} (DXIL {})", + if p.name.is_empty() { + "unnamed" + } else { + &p.name + }, + code.join(" ") + ) } fn hashes(&self, p: &wire::Pipeline) -> Vec { @@ -580,23 +737,45 @@ impl Player { (slot::CBV, described) => { let mut d: D3D12_CONSTANT_BUFFER_VIEW_DESC = Default::default(); if described && let Some(o) = self.objects.get(&s.res) { - d = s.desc.as_ptr().cast::().read_unaligned(); + d = s + .desc + .as_ptr() + .cast::() + .read_unaligned(); d.BufferLocation = o.va + s.address(); } self.device.CreateConstantBufferView(Some(&d), at); } (slot::SRV, true) => { - let d = s.desc.as_ptr().cast::().read_unaligned(); + let d = s + .desc + .as_ptr() + .cast::() + .read_unaligned(); self.device.CreateShaderResourceView(res, Some(&d), at); } - (slot::SRV, false) if res.is_some() => self.device.CreateShaderResourceView(res, None, at), + (slot::SRV, false) if res.is_some() => { + self.device.CreateShaderResourceView(res, None, at) + } (slot::UAV, true) => { - let d = s.desc.as_ptr().cast::().read_unaligned(); - self.device.CreateUnorderedAccessView(res, counter, Some(&d), at); + let d = s + .desc + .as_ptr() + .cast::() + .read_unaligned(); + self.device + .CreateUnorderedAccessView(res, counter, Some(&d), at); + } + (slot::UAV, false) if res.is_some() => { + self.device + .CreateUnorderedAccessView(res, None::<&ID3D12Resource>, None, at) } - (slot::UAV, false) if res.is_some() => self.device.CreateUnorderedAccessView(res, None::<&ID3D12Resource>, None, at), (slot::SAMPLER, true) => { - let d = s.desc.as_ptr().cast::().read_unaligned(); + let d = s + .desc + .as_ptr() + .cast::() + .read_unaligned(); self.device.CreateSampler(&d, at); } _ if sampler => { @@ -615,7 +794,12 @@ impl Player { ViewDimension: D3D12_UAV_DIMENSION_BUFFER, ..Default::default() }; - self.device.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&d), at); + self.device.CreateUnorderedAccessView( + None::<&ID3D12Resource>, + None::<&ID3D12Resource>, + Some(&d), + at, + ); } _ => { let d = D3D12_SHADER_RESOURCE_VIEW_DESC { @@ -624,7 +808,8 @@ impl Player { Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, ..Default::default() }; - self.device.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&d), at); + self.device + .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&d), at); } } } @@ -635,7 +820,12 @@ impl Player { // version of the heaps of its own: lists are sent without waiting, // so a heap cannot be written between them. let mut now: HashMap<(u32, u32), Slot> = HashMap::new(); - let replaced: HashSet<(u32, u32)> = self.frame.submits.iter().flat_map(|s| s.views.iter().map(|v| (v.0, v.1))).collect(); + let replaced: HashSet<(u32, u32)> = self + .frame + .submits + .iter() + .flat_map(|s| s.views.iter().map(|v| (v.0, v.1))) + .collect(); for h in &self.frame.descriptor_heaps { for (id, i) in replaced.iter().filter(|k| k.0 == h.id) { let k = h.runs.partition_point(|run| run.0 <= *i); @@ -650,9 +840,17 @@ impl Player { let mut versions: Vec> = vec![Vec::new()]; let mut touched: HashSet<(u32, u32)> = HashSet::new(); for s in &self.frame.submits { - let live = |old: Option<&Slot>| old.is_some_and(|o| o.kind == slot::SAMPLER || o.res != NONE); - let news: Vec<&(u32, u32, Slot)> = s.views.iter().filter(|(h, i, v)| now.get(&(*h, *i)) != Some(v)).collect(); - if news.iter().any(|(h, i, _)| live(now.get(&(*h, *i))) || touched.contains(&(*h, *i))) { + let live = + |old: Option<&Slot>| old.is_some_and(|o| o.kind == slot::SAMPLER || o.res != NONE); + let news: Vec<&(u32, u32, Slot)> = s + .views + .iter() + .filter(|(h, i, v)| now.get(&(*h, *i)) != Some(v)) + .collect(); + if news + .iter() + .any(|(h, i, _)| live(now.get(&(*h, *i))) || touched.contains(&(*h, *i))) + { versions.push(Vec::new()); touched.clear(); } @@ -671,7 +869,12 @@ impl Player { let sampler = h.kind == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0; let kind = D3D12_DESCRIPTOR_HEAP_TYPE(h.kind); let make = |flags| -> windows::core::Result { - let d = D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: h.count, Flags: flags, NodeMask: 0 }; + let d = D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: h.count, + Flags: flags, + NodeMask: 0, + }; // SAFETY: plain creation. unsafe { self.device.CreateDescriptorHeap(&d) } }; @@ -680,24 +883,29 @@ impl Player { unsafe { let step = self.device.GetDescriptorHandleIncrementSize(kind) as usize; let start = cpu.GetCPUDescriptorHandleForHeapStart(); - let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + i as usize * step }; + let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start.ptr + i as usize * step, + }; self.view(&Slot::EMPTY, start, sampler); let mut filled = 1; while filled < h.count { let n = filled.min(h.count - filled).min(1 << 16); // Sources and destinations do not overlap. - self.device.CopyDescriptorsSimple(n, at(filled), start, kind); + self.device + .CopyDescriptorsSimple(n, at(filled), start, kind); filled += n; } for (first, n, s) in &h.runs { self.view(s, at(*first), sampler); for i in 1..*n { - self.device.CopyDescriptorsSimple(1, at(first + i), at(*first), kind); + self.device + .CopyDescriptorsSimple(1, at(first + i), at(*first), kind); } } let mut all = Vec::new(); for changes in &versions { - let mine: Vec<&(u32, u32, Slot)> = changes.iter().filter(|(id, _, _)| *id == h.id).collect(); + let mine: Vec<&(u32, u32, Slot)> = + changes.iter().filter(|(id, _, _)| *id == h.id).collect(); for (_, i, s) in &mine { if *i < h.count { self.view(s, at(*i), sampler); @@ -706,7 +914,10 @@ impl Player { if mine.is_empty() && let Some(Version { heap, gpu }) = all.last() { - let same = Version { heap: ID3D12DescriptorHeap::clone(heap), gpu: *gpu }; + let same = Version { + heap: ID3D12DescriptorHeap::clone(heap), + gpu: *gpu, + }; all.push(same); continue; } @@ -716,15 +927,30 @@ impl Player { // last one, and lists before see them too. Err(_) if !all.is_empty() => { full += 1; - let Some(Version { heap, gpu }) = all.last() else { break }; - let same = Version { heap: ID3D12DescriptorHeap::clone(heap), gpu: *gpu }; - self.device.CopyDescriptorsSimple(h.count, same.heap.GetCPUDescriptorHandleForHeapStart(), start, kind); + let Some(Version { heap, gpu }) = all.last() else { + break; + }; + let same = Version { + heap: ID3D12DescriptorHeap::clone(heap), + gpu: *gpu, + }; + self.device.CopyDescriptorsSimple( + h.count, + same.heap.GetCPUDescriptorHandleForHeapStart(), + start, + kind, + ); all.push(same); continue; } Err(e) => return Err(e.into()), }; - self.device.CopyDescriptorsSimple(h.count, heap.GetCPUDescriptorHandleForHeapStart(), start, kind); + self.device.CopyDescriptorsSimple( + h.count, + heap.GetCPUDescriptorHandleForHeapStart(), + start, + kind, + ); let gpu = heap.GetGPUDescriptorHandleForHeapStart().ptr; all.push(Version { heap, gpu }); } @@ -733,10 +959,15 @@ impl Player { } self.descriptors = made; if versions.len() > 1 { - self.notes.push(format!("{} versions of the descriptor heaps (views replaced during the frame)", versions.len())); + self.notes.push(format!( + "{} versions of the descriptor heaps (views replaced during the frame)", + versions.len() + )); } if full > 0 { - self.note(format!("{full} versions of descriptor heaps had no room: earlier lists see later views")); + self.note(format!( + "{full} versions of descriptor heaps had no room: earlier lists see later views" + )); } // Render target and depth views. let mut views: [HashSet; 2] = Default::default(); @@ -746,8 +977,8 @@ impl Player { views[0].extend(colors); views[1].extend(depth); } - Cmd::ClearTarget { view, .. } => drop(views[0].insert(*view)), - Cmd::ClearDepth { view, .. } => drop(views[1].insert(*view)), + Cmd::ClearTarget { view, .. } => _ = views[0].insert(*view), + Cmd::ClearDepth { view, .. } => _ = views[1].insert(*view), _ => {} } } @@ -755,8 +986,15 @@ impl Player { if all.is_empty() { continue; } - let kind = [D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_TYPE_DSV][i]; - let d = D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: all.len() as u32, ..Default::default() }; + let kind = [ + D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + ][i]; + let d = D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: all.len() as u32, + ..Default::default() + }; // SAFETY: plain creation; slots of the heap just made. unsafe { let heap: ID3D12DescriptorHeap = self.device.CreateDescriptorHeap(&d)?; @@ -765,23 +1003,43 @@ impl Player { for s in all { let res = self.objects.get(&s.res).map(|o| &o.res); if i == 0 { - let d = s.desc.as_ptr().cast::().read_unaligned(); + let d = s + .desc + .as_ptr() + .cast::() + .read_unaligned(); // Without either there is nothing to make a view of. let null = D3D12_RENDER_TARGET_VIEW_DESC { Format: DXGI_FORMAT(28), ViewDimension: D3D12_RTV_DIMENSION_TEXTURE2D, ..Default::default() }; - let d = if s.described != 0 { Some(&d as *const _) } else if res.is_none() { Some(&null as *const _) } else { None }; + let d = if s.described != 0 { + Some(&d as *const _) + } else if res.is_none() { + Some(&null as *const _) + } else { + None + }; self.device.CreateRenderTargetView(res, d, at); } else { - let d = s.desc.as_ptr().cast::().read_unaligned(); + let d = s + .desc + .as_ptr() + .cast::() + .read_unaligned(); let null = D3D12_DEPTH_STENCIL_VIEW_DESC { Format: DXGI_FORMAT(40), ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, ..Default::default() }; - let d = if s.described != 0 { Some(&d as *const _) } else if res.is_none() { Some(&null as *const _) } else { None }; + let d = if s.described != 0 { + Some(&d as *const _) + } else if res.is_none() { + Some(&null as *const _) + } else { + None + }; self.device.CreateDepthStencilView(res, d, at); } self.targets.insert(*s, at); @@ -821,7 +1079,12 @@ impl Player { } let mut stagings: Vec<(ID3D12Resource, usize, u64)> = Vec::new(); for _ in 0..batches.len().min(2) { - let (b, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_UPLOAD, most, D3D12_RESOURCE_FLAG_NONE)?; + let (b, data) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_UPLOAD, + most, + D3D12_RESOURCE_FLAG_NONE, + )?; stagings.push((b, data as usize, 0)); } for (n, batch) in batches.iter().enumerate() { @@ -836,11 +1099,19 @@ impl Player { while let Some(&(i, at)) = batch.get(next.fetch_add(1, Ordering::Relaxed)) { let (_, len, from) = &parts[i]; // SAFETY: this part's own bytes of the mapping. - let to = unsafe { std::slice::from_raw_parts_mut((map + at as usize) as *mut u8, *len as usize) }; + let to = unsafe { + std::slice::from_raw_parts_mut( + (map + at as usize) as *mut u8, + *len as usize, + ) + }; if *from == ZERO { to.fill(0); } else if let Err(e) = read_at(file, to, *from) { - failed.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert(e); + failed + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get_or_insert(e); } } }); @@ -849,7 +1120,10 @@ impl Player { if let Some(e) = failed.into_inner().unwrap_or_else(|e| e.into_inner()) { return Err(e).context("the capture's contents"); } - let list: Vec<(&T, u64, u64)> = batch.iter().map(|&(i, at)| (&parts[i].0, parts[i].1, at)).collect(); + let list: Vec<(&T, u64, u64)> = batch + .iter() + .map(|&(i, at)| (&parts[i].0, parts[i].1, at)) + .collect(); let buffer = stagings[k].0.clone(); // The worker is another part of the player than `copy` uses. let other = Worker::new(&self.device, &self.worker.queue)?; @@ -869,9 +1143,16 @@ impl Player { let mut early = Vec::new(); let mut into = Vec::new(); for r in &self.frame.resources { - let (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else { continue }; + let (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else { + continue; + }; let loaded = !r.idle && known.contains(&r.id); - gpu::moves(&o.res, &[COMMON], if loaded { &[COPY_DEST] } else { state }, if loaded { &mut into } else { &mut early }); + gpu::moves( + &o.res, + &[COMMON], + if loaded { &[COPY_DEST] } else { state }, + if loaded { &mut into } else { &mut early }, + ); } let textures: Vec<(Content, u64, u64)> = self .frame @@ -896,7 +1177,9 @@ impl Player { let file = File::open(self.folder.join("contents.bin"))?; self.upload(&textures, &file, |player, list, parts, staging| { for (c, len, at) in parts { - let Some(o) = player.objects.get(&c.res) else { continue }; + let Some(o) = player.objects.get(&c.res) else { + continue; + }; let r = &player.frame.resources[o.index]; // SAFETY: an open list; live resources. unsafe { @@ -904,11 +1187,23 @@ impl Player { list.CopyBufferRegion(&o.res, c.first, staging, *at, *len); continue; } - let (all, _) = gpu::footprints(&player.device, &gpu::to_desc(&r.desc), c.first as u32, c.count); + let (all, _) = gpu::footprints( + &player.device, + &gpu::to_desc(&r.desc), + c.first as u32, + c.count, + ); for (i, mut f) in all.into_iter().enumerate() { f.Offset += at; let to = gpu::sub_location(&o.res, c.first as u32 + i as u32); - list.CopyTextureRegion(&to, 0, 0, 0, &gpu::placed_location(staging, f), None); + list.CopyTextureRegion( + &to, + 0, + 0, + 0, + &gpu::placed_location(staging, f), + None, + ); } } } @@ -916,7 +1211,9 @@ impl Player { // To the states of the frame's start. let mut back = Vec::new(); for r in &self.frame.resources { - let (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else { continue }; + let (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else { + continue; + }; if !r.idle && known.contains(&r.id) { gpu::moves(&o.res, &[COPY_DEST], state, &mut back); } @@ -928,13 +1225,21 @@ impl Player { } })?; if missing > 0 { - self.note(format!("contents of {missing} parts of resources that could not be made are left out")); + self.note(format!( + "contents of {missing} parts of resources that could not be made are left out" + )); } // What the CPU had put into the memory both see by the first // submission: part of the start of the frame. let file = File::open(self.folder.join("deltas.bin"))?; let named = self.named_buffers(); - let of = |s: &wire::Submit| s.deltas.iter().filter(|d| named.contains(&d.res)).cloned().collect::>(); + let of = |s: &wire::Submit| { + s.deltas + .iter() + .filter(|d| named.contains(&d.res)) + .cloned() + .collect::>() + }; // In memory the card cannot write, bytes looked at first when a // later submission read them can stand there from the start. let upload: HashSet = self @@ -946,17 +1251,25 @@ impl Player { .collect(); let mut first = of(&self.frame.submits[0]); let mut seen: HashSet<(u32, u64)> = HashSet::new(); - let pages = |d: &Delta| (d.at / 4096..(d.at + d.len).div_ceil(4096)).map(|p| (d.res, p)).collect::>(); + let pages = |d: &Delta| { + (d.at / 4096..(d.at + d.len).div_ceil(4096)) + .map(|p| (d.res, p)) + .collect::>() + }; first.iter().for_each(|d| seen.extend(pages(d))); let mut rest: Vec> = vec![Vec::new()]; for s in self.frame.submits.iter().skip(1) { - let (early, late): (Vec, Vec) = - of(s).into_iter().partition(|d| upload.contains(&d.res) && pages(d).iter().all(|p| !seen.contains(p))); + let (early, late): (Vec, Vec) = of(s).into_iter().partition(|d| { + upload.contains(&d.res) && pages(d).iter().all(|p| !seen.contains(p)) + }); early.iter().for_each(|d| seen.extend(pages(d))); first.extend(early); rest.push(late); } - let first: Vec<(Delta, u64, u64)> = first.into_iter().map(|d| (d.clone(), d.len, d.file)).collect(); + let first: Vec<(Delta, u64, u64)> = first + .into_iter() + .map(|d| (d.clone(), d.len, d.file)) + .collect(); self.upload(&first, &file, |player, list, parts, staging| { for (d, len, at) in parts { if let Some(o) = player.objects.get(&d.res) { @@ -977,7 +1290,12 @@ impl Player { } } if total > 0 { - let (buffer, _) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, total, D3D12_RESOURCE_FLAG_NONE)?; + let (buffer, _) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_DEFAULT, + total, + D3D12_RESOURCE_FLAG_NONE, + )?; self.deltas = Some(buffer.clone()); self.upload(&later, &file, |_, list, parts, staging| { for ((to, _), len, at) in parts { @@ -1001,22 +1319,28 @@ impl Player { for c in self.commands.iter().flatten() { match c { Cmd::RootView { va: v, .. } => va(v), - Cmd::IndexBuffer { view: Some((v, _, _)) } => va(v), - Cmd::VertexBuffers { views: Some(all), .. } => all.iter().for_each(|(v, _, _)| va(v)), + Cmd::IndexBuffer { + view: Some((v, _, _)), + } => va(v), + Cmd::VertexBuffers { + views: Some(all), .. + } => all.iter().for_each(|(v, _, _)| va(v)), Cmd::WriteImmediate { all } => all.iter().for_each(|(v, _, _)| va(v)), _ => {} } } for c in self.commands.iter().flatten() { match c { - Cmd::CopyBuffer { dst, src, .. } | Cmd::CopyResource { dst, src } => named.extend([*dst, *src]), + Cmd::CopyBuffer { dst, src, .. } | Cmd::CopyResource { dst, src } => { + named.extend([*dst, *src]) + } Cmd::CopyTexture { dst, src, .. } => { for Loc::Sub { res, .. } | Loc::Placed { res, .. } in [dst, src] { named.insert(*res); } } Cmd::Indirect { args, count, .. } => named.extend([*args, *count]), - Cmd::ResolveQuery { dst, .. } => drop(named.insert(*dst)), + Cmd::ResolveQuery { dst, .. } => _ = named.insert(*dst), _ => {} } } @@ -1041,15 +1365,27 @@ impl Player { states.add(r.id, subs, r.state[0], decays); if r.state.len() > 1 { for (i, s) in r.state.iter().enumerate() { - states.change(&states::Change { res: r.id, sub: i as u32, after: *s, promoted: false, alias: false }); + states.change(&states::Change { + res: r.id, + sub: i as u32, + after: *s, + promoted: false, + alias: false, + }); } } } // Resources in a state they are written in at some time, or written // some other way. - const WRITE: u32 = RENDER_TARGET | UNORDERED_ACCESS | DEPTH_WRITE | COPY_DEST | RESOLVE_DEST; - let mut written: HashSet = - self.frame.resources.iter().filter(|r| r.state.iter().any(|s| s & WRITE != 0)).map(|r| r.id).collect(); + const WRITE: u32 = + RENDER_TARGET | UNORDERED_ACCESS | DEPTH_WRITE | COPY_DEST | RESOLVE_DEST; + let mut written: HashSet = self + .frame + .resources + .iter() + .filter(|r| r.state.iter().any(|s| s & WRITE != 0)) + .map(|r| r.id) + .collect(); for (i, s) in self.frame.submits.iter().enumerate() { for &l in s.lists.iter().filter(|&&l| l != MISSING) { for c in &self.commands[l as usize] { @@ -1061,19 +1397,38 @@ impl Player { match c { Cmd::Barriers { all } => { for b in all { - if let Barrier::Transition { res, before, after, .. } = b + if let Barrier::Transition { + res, before, after, .. + } = b && (*before | *after) as u32 & WRITE != 0 { written.insert(*res); } } } - Cmd::CopyBuffer { dst, .. } | Cmd::CopyResource { dst, .. } | Cmd::ResolveQuery { dst, .. } => drop(written.insert(*dst)), - Cmd::CopyTexture { dst: Loc::Sub { res, .. } | Loc::Placed { res, .. }, .. } => drop(written.insert(*res)), - Cmd::Resolve { dst, .. } | Cmd::ResolveRegion { dst, .. } => drop(written.insert(*dst)), - Cmd::RootView { kind: slot::UAV, va: Va::At { res, .. }, .. } => drop(written.insert(*res)), + Cmd::CopyBuffer { dst, .. } + | Cmd::CopyResource { dst, .. } + | Cmd::ResolveQuery { dst, .. } => _ = written.insert(*dst), + Cmd::CopyTexture { + dst: Loc::Sub { res, .. } | Loc::Placed { res, .. }, + .. + } => _ = written.insert(*res), + Cmd::Resolve { dst, .. } | Cmd::ResolveRegion { dst, .. } => { + _ = written.insert(*dst) + } + Cmd::RootView { + kind: slot::UAV, + va: Va::At { res, .. }, + .. + } => _ = written.insert(*res), Cmd::WriteImmediate { all } => { - written.extend(all.iter().filter_map(|(va, _, _)| if let Va::At { res, .. } = va { Some(*res) } else { None })); + written.extend(all.iter().filter_map(|(va, _, _)| { + if let Va::At { res, .. } = va { + Some(*res) + } else { + None + } + })); } _ => {} } @@ -1085,15 +1440,28 @@ impl Player { } } // Buffers any unordered-access view names. - let is_buffer = - |id: u32| self.objects.get(&id).is_some_and(|o| self.frame.resources[o.index].desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0); - let simultaneous = |id: u32| { + let is_buffer = |id: u32| { self.objects.get(&id).is_some_and(|o| { - self.frame.resources[o.index].desc.flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 != 0 + self.frame.resources[o.index].desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 }) }; - let views = self.frame.descriptor_heaps.iter().flat_map(|h| h.runs.iter().map(|(_, _, s)| s)); - let late = self.frame.submits.iter().flat_map(|s| s.views.iter().map(|(_, _, s)| s)); + let simultaneous = |id: u32| { + self.objects.get(&id).is_some_and(|o| { + self.frame.resources[o.index].desc.flags + & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 + != 0 + }) + }; + let views = self + .frame + .descriptor_heaps + .iter() + .flat_map(|h| h.runs.iter().map(|(_, _, s)| s)); + let late = self + .frame + .submits + .iter() + .flat_map(|s| s.views.iter().map(|(_, _, s)| s)); for s in views.chain(late).filter(|s| s.kind == slot::UAV) { for id in [s.res, s.counter] { if is_buffer(id) || simultaneous(id) { @@ -1102,7 +1470,8 @@ impl Player { } } for id in self.start.keys() { - self.end.insert(*id, states.get(*id).unwrap_or(vec![COMMON])); + self.end + .insert(*id, states.get(*id).unwrap_or(vec![COMMON])); } let mut ids: Vec = written .into_iter() @@ -1140,12 +1509,22 @@ impl Player { ..Default::default() } } else { - D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() } + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + } }; let mut made: Option = None; // SAFETY: plain creation. let result = unsafe { - self.device.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut made) + self.device.CreateCommittedResource( + &props, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut made, + ) }; match (result, made) { (Ok(()), Some(m)) => { @@ -1153,10 +1532,17 @@ impl Player { in_pc += if pc { size } else { 0 }; self.masters.push((id, m)); } - (e, _) => self.note(format!("no copy of resource {id} to restore it from ({e:?})")), + (e, _) => self.note(format!( + "no copy of resource {id} to restore it from ({e:?})" + )), } } - tracing::info!(resources = self.masters.len(), mb = total >> 20, in_pc_memory_mb = in_pc >> 20, "copies of what the frame changes"); + tracing::info!( + resources = self.masters.len(), + mb = total >> 20, + in_pc_memory_mb = in_pc >> 20, + "copies of what the frame changes" + ); // Filled now: the resources are as at the frame's start. Masters // stay in the copy-source state (buffers decay). let (masters, objects, start) = (&self.masters, &self.objects, &self.start); @@ -1165,7 +1551,10 @@ impl Player { for (id, m) in some { let Some(state) = start.get(id) else { continue }; let o = &objects[id]; - let to: Vec = state.iter().map(|&s| if s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }).collect(); + let to: Vec = state + .iter() + .map(|&s| if s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }) + .collect(); gpu::moves(&o.res, state, &to, &mut before); gpu::moves(&o.res, &to, state, &mut after); before.push(gpu::transition(m, ALL, COMMON, COPY_DEST)); @@ -1191,8 +1580,12 @@ impl Player { // SAFETY: plain queries. unsafe { let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; - let adapter: IDXGIAdapter3 = factory.EnumAdapterByLuid(self.device.GetAdapterLuid()).ok()?; - adapter.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own).ok()?; + let adapter: IDXGIAdapter3 = factory + .EnumAdapterByLuid(self.device.GetAdapterLuid()) + .ok()?; + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own) + .ok()?; } Some(own.Budget.saturating_sub(own.CurrentUsage)) } @@ -1202,10 +1595,17 @@ impl Player { if self.fresh { return Ok(()); } - let restored: HashMap = if contents { self.masters.iter().map(|(id, m)| (*id, m)).collect() } else { HashMap::new() }; - let (mut idle, mut into, mut back, mut plain) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let restored: HashMap = if contents { + self.masters.iter().map(|(id, m)| (*id, m)).collect() + } else { + HashMap::new() + }; + let (mut idle, mut into, mut back, mut plain) = + (Vec::new(), Vec::new(), Vec::new(), Vec::new()); for (id, start) in &self.start { - let Some(o) = self.objects.get(id) else { continue }; + let Some(o) = self.objects.get(id) else { + continue; + }; let end = self.end.get(id).unwrap_or(start); if restored.contains_key(id) { gpu::moves(&o.res, end, &[COPY_DEST], &mut into); @@ -1236,23 +1636,39 @@ impl Player { } fn pipelines_named(&self, name: &str) -> HashSet { - self.frame.pipelines.iter().filter(|p| p.name == name).map(|p| p.id).collect() + self.frame + .pipelines + .iter() + .filter(|p| p.name == name) + .map(|p| p.id) + .collect() } /// The frame's lists, edited: for each submission, its lists' commands. - fn edited(&mut self, o: &Options, report: &mut Report, clamps: &[Vec]) -> Vec>> { + fn edited( + &mut self, + o: &Options, + report: &mut Report, + clamps: &[Vec], + ) -> Vec>> { let skip: HashSet = self .frame .pipelines .iter() .filter(|p| { let hashes = self.hashes(p); - o.skip_shaders.iter().any(|s| !s.is_empty() && (p.name.contains(s.as_str()) || hashes.iter().any(|h| h.contains(s.as_str())))) + o.skip_shaders.iter().any(|s| { + !s.is_empty() + && (p.name.contains(s.as_str()) + || hashes.iter().any(|h| h.contains(s.as_str()))) + }) }) .map(|p| p.id) .collect(); if !o.skip_shaders.is_empty() { - report.notes.push(format!("{} pipelines match --skip-shader", skip.len())); + report + .notes + .push(format!("{} pipelines match --skip-shader", skip.len())); } let hash = self.pipelines_named(COMPARE); let (mut skipped, mut hashed, mut uavs, mut merged) = (0, 0, 0, 0); @@ -1268,7 +1684,9 @@ impl Player { lists.push(edit::barriers_only(cmds)); continue; } - if o.skip_clamps && let Some(c) = clamps.get(here as usize) { + if o.skip_clamps + && let Some(c) = clamps.get(here as usize) + { cmds = edit::skip_clamps(cmds, c); } let mut n; @@ -1293,16 +1711,24 @@ impl Player { out.push(lists); } if !skip.is_empty() { - report.notes.push(format!("--skip-shader left out {skipped} commands")); + report + .notes + .push(format!("--skip-shader left out {skipped} commands")); } if o.skip_hash_passes { - report.notes.push(format!("--skip-hash-passes left out {hashed} dispatches")); + report + .notes + .push(format!("--skip-hash-passes left out {hashed} dispatches")); } if o.no_barriers { - report.notes.push(format!("--no-barriers left out {uavs} unordered-access barriers")); + report.notes.push(format!( + "--no-barriers left out {uavs} unordered-access barriers" + )); } if o.merge_barriers { - report.notes.push(format!("--merge-barriers joined {merged} barrier calls to ones before them")); + report.notes.push(format!( + "--merge-barriers joined {merged} barrier calls to ones before them" + )); } out } @@ -1325,11 +1751,22 @@ impl Player { submits.push(lists); } let n: usize = clamps.iter().map(Vec::len).sum(); - report.notes.push(format!("--skip-clamps: {n} clamp passes, {} KB of arguments kept from a first run", next >> 10)); + report.notes.push(format!( + "--skip-clamps: {n} clamp passes, {} KB of arguments kept from a first run", + next >> 10 + )); if n == 0 { return Ok(clamps); } - self.results = Some(gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, next, D3D12_RESOURCE_FLAG_NONE)?.0); + self.results = Some( + gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_DEFAULT, + next, + D3D12_RESOURCE_FLAG_NONE, + )? + .0, + ); let built = self.build(&submits, &Options::default())?; self.restore(true)?; self.send(&built, false)?; @@ -1344,15 +1781,32 @@ impl Player { let count: usize = submits .iter() .flatten() - .map(|c| 2 + if o.detailed { c.iter().filter(|c| c.works() || matches!(c, Cmd::Barriers { .. })).count() } else { 0 }) + .map(|c| { + 2 + if o.detailed { + c.iter() + .filter(|c| c.works() || matches!(c, Cmd::Barriers { .. })) + .count() + } else { + 0 + } + }) .sum::() + 2 * submits.len(); let mut heap: Option = None; - let desc = D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: count.max(1) as u32, NodeMask: 0 }; + let desc = D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: count.max(1) as u32, + NodeMask: 0, + }; // SAFETY: plain creation. unsafe { self.device.CreateQueryHeap(&desc, &mut heap)? }; let heap = heap.context("no timestamps")?; - let (back, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_READBACK, count.max(1) as u64 * 8, D3D12_RESOURCE_FLAG_NONE)?; + let (back, data) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_READBACK, + count.max(1) as u64 * 8, + D3D12_RESOURCE_FLAG_NONE, + )?; let mut next = 0u32; let mut steps = Vec::new(); for (i, lists) in submits.iter().enumerate() { @@ -1365,7 +1819,9 @@ impl Player { let mut seen = HashSet::new(); let mut after = Vec::new(); for (d, at) in parts { - let Some(ob) = self.objects.get(&d.res) else { continue }; + let Some(ob) = self.objects.get(&d.res) else { + continue; + }; open.1.CopyBufferRegion(&ob.res, d.at, from, *at, d.len); if seen.insert(d.res) { // Back to the common state by itself, for @@ -1382,7 +1838,8 @@ impl Player { let mut built = Vec::new(); for cmds in lists { let open = self.open(&heap, &mut next)?; - let stamps = self.translate(&open.1, cmds, i, o.detailed.then_some((&heap, &mut next))); + let stamps = + self.translate(&open.1, cmds, i, o.detailed.then_some((&heap, &mut next))); built.push(self.close(open, &heap, &mut next, stamps)?); } steps.push((delta, built)); @@ -1405,12 +1862,27 @@ impl Player { let open = self.plain_list()?; // SAFETY: an open list; `next` queries were written. unsafe { - open.1.ResolveQueryData(&heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, next.max(1), &back, 0); + open.1.ResolveQueryData( + &heap, + D3D12_QUERY_TYPE_TIMESTAMP, + 0, + next.max(1), + &back, + 0, + ); open.1.Close()?; } open }; - Ok(Sends { steps, joints, resolve, _heap: heap, _back: back, data: data as usize, count: next }) + Ok(Sends { + steps, + joints, + resolve, + _heap: heap, + _back: back, + data: data as usize, + count: next, + }) } /// Records a wait for everything before, with all caches written out. @@ -1422,7 +1894,10 @@ impl Player { unsafe { let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS12::default(); let size = size_of::() as u32; - let known = self.device.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS12, (&raw mut o).cast(), size).is_ok(); + let known = self + .device + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS12, (&raw mut o).cast(), size) + .is_ok(); if known && o.EnhancedBarriersSupported.as_bool() && let Ok(list) = list.cast::() @@ -1436,7 +1911,9 @@ impl Player { list.Barrier(&[D3D12_BARRIER_GROUP { Type: D3D12_BARRIER_TYPE_GLOBAL, NumBarriers: 1, - Anonymous: D3D12_BARRIER_GROUP_0 { pGlobalBarriers: all.as_ptr() }, + Anonymous: D3D12_BARRIER_GROUP_0 { + pGlobalBarriers: all.as_ptr(), + }, }]); } else { list.ResourceBarrier(&[alias(), uav_barrier(None)]); @@ -1447,13 +1924,24 @@ impl Player { fn plain_list(&self) -> Result<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)> { // SAFETY: plain creation. unsafe { - let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let list = self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + let allocator: ID3D12CommandAllocator = self + .device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list = self.device.CreateCommandList( + 0, + D3D12_COMMAND_LIST_TYPE_DIRECT, + &allocator, + None, + )?; Ok((allocator, list)) } } - fn open(&self, heap: &ID3D12QueryHeap, next: &mut u32) -> Result<(ID3D12CommandAllocator, ID3D12GraphicsCommandList, u32)> { + fn open( + &self, + heap: &ID3D12QueryHeap, + next: &mut u32, + ) -> Result<(ID3D12CommandAllocator, ID3D12GraphicsCommandList, u32)> { let (allocator, list) = self.plain_list()?; // SAFETY: an open list; a query of the heap. unsafe { list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, *next) }; @@ -1471,10 +1959,17 @@ impl Player { // SAFETY: as above. unsafe { list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, *next); - list.Close().context("a list of the frame could not be recorded again")?; + list.Close() + .context("a list of the frame could not be recorded again")?; } *next += 1; - Ok(Built { _allocator: allocator, list, first, last: *next - 1, stamps }) + Ok(Built { + _allocator: allocator, + list, + first, + last: *next - 1, + stamps, + }) } /// Records commands into a list, in submission `submit`. @@ -1499,7 +1994,11 @@ impl Player { .frame .signatures .iter() - .filter(|s| s.args.iter().any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32)) + .filter(|s| { + s.args + .iter() + .any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32) + }) .map(|s| s.id) .collect(); let mut stamps = Vec::new(); @@ -1518,13 +2017,21 @@ impl Player { let category = match c { Cmd::Barriers { .. } => "barriers", Cmd::Dispatch { .. } if clamps.contains(&bound) => "argument clamps (ours)", - Cmd::Dispatch { .. } if compares.contains(&bound) => "hash and compare passes (ours)", + Cmd::Dispatch { .. } if compares.contains(&bound) => { + "hash and compare passes (ours)" + } Cmd::Dispatch { .. } => "dispatches", - Cmd::Indirect { signature, .. } if dispatches.contains(signature) => "indirect dispatches", + Cmd::Indirect { signature, .. } if dispatches.contains(signature) => { + "indirect dispatches" + } Cmd::Indirect { .. } if mesh.contains(&bound) => "indirect mesh draws", Cmd::Indirect { .. } => "indirect draws", - Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::DispatchMesh { .. } => "draws", - Cmd::ClearDepth { .. } | Cmd::ClearTarget { .. } | Cmd::Discard { .. } => "clears", + Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::DispatchMesh { .. } => { + "draws" + } + Cmd::ClearDepth { .. } | Cmd::ClearTarget { .. } | Cmd::Discard { .. } => { + "clears" + } Cmd::Resolve { .. } | Cmd::ResolveRegion { .. } => "resolves", _ => "copies", }; @@ -1542,8 +2049,19 @@ impl Player { // SAFETY: the caller's. unsafe { match c { - Cmd::Draw { vertices, instances, first, first_instance } => l.DrawInstanced(*vertices, *instances, *first, *first_instance), - Cmd::DrawIndexed { indices, instances, first, base, first_instance } => { + Cmd::Draw { + vertices, + instances, + first, + first_instance, + } => l.DrawInstanced(*vertices, *instances, *first, *first_instance), + Cmd::DrawIndexed { + indices, + instances, + first, + base, + first_instance, + } => { l.DrawIndexedInstanced(*indices, *instances, *first, *base, *first_instance); } Cmd::Dispatch { groups } => l.Dispatch(groups[0], groups[1], groups[2]), @@ -1552,7 +2070,13 @@ impl Player { l.DispatchMesh(groups[0], groups[1], groups[2]); } } - Cmd::CopyBuffer { dst, dst_at, src, src_at, len } => { + Cmd::CopyBuffer { + dst, + dst_at, + src, + src_at, + len, + } => { if let (Some(dst), Some(src)) = (res(*dst), res(*src)) { l.CopyBufferRegion(dst, *dst_at, src, *src_at, *len); } @@ -1560,7 +2084,13 @@ impl Player { Cmd::CopyTexture { dst, at, src, part } => { let side = |loc: &Loc| match loc { Loc::Sub { res: id, sub } => Some(gpu::sub_location(res(*id)?, *sub)), - Loc::Placed { res: id, offset, format, size, pitch } => { + Loc::Placed { + res: id, + offset, + format, + size, + pitch, + } => { let f = D3D12_SUBRESOURCE_FOOTPRINT { Format: DXGI_FORMAT(*format), Width: size[0], @@ -1568,12 +2098,32 @@ impl Player { Depth: size[2], RowPitch: *pitch, }; - Some(gpu::placed_location(res(*id)?, D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: *offset, Footprint: f })) + Some(gpu::placed_location( + res(*id)?, + D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: *offset, + Footprint: f, + }, + )) } }; if let (Some(dst), Some(src)) = (side(dst), side(src)) { - let part = part.map(|p| D3D12_BOX { left: p[0], top: p[1], front: p[2], right: p[3], bottom: p[4], back: p[5] }); - l.CopyTextureRegion(&dst, at[0], at[1], at[2], &src, part.as_ref().map(|p| p as *const _)); + let part = part.map(|p| D3D12_BOX { + left: p[0], + top: p[1], + front: p[2], + right: p[3], + bottom: p[4], + back: p[5], + }); + l.CopyTextureRegion( + &dst, + at[0], + at[1], + at[2], + &src, + part.as_ref().map(|p| p as *const _), + ); } } Cmd::CopyResource { dst, src } => { @@ -1581,27 +2131,63 @@ impl Player { l.CopyResource(dst, src); } } - Cmd::Resolve { dst, dst_sub, src, src_sub, format } => { + Cmd::Resolve { + dst, + dst_sub, + src, + src_sub, + format, + } => { if let (Some(dst), Some(src)) = (res(*dst), res(*src)) { l.ResolveSubresource(dst, *dst_sub, src, *src_sub, DXGI_FORMAT(*format)); } } - Cmd::ResolveRegion { dst, dst_sub, at, src, src_sub, part, format, mode } => { - if let (Some(dst), Some(src), Ok(l)) = (res(*dst), res(*src), l.cast::()) { + Cmd::ResolveRegion { + dst, + dst_sub, + at, + src, + src_sub, + part, + format, + mode, + } => { + if let (Some(dst), Some(src), Ok(l)) = + (res(*dst), res(*src), l.cast::()) + { let part = part.map(to_rect); let part = part.as_ref().map(|r| r as *const _); - l.ResolveSubresourceRegion(dst, *dst_sub, at[0], at[1], src, *src_sub, part, DXGI_FORMAT(*format), D3D12_RESOLVE_MODE(*mode)); + l.ResolveSubresourceRegion( + dst, + *dst_sub, + at[0], + at[1], + src, + *src_sub, + part, + DXGI_FORMAT(*format), + D3D12_RESOLVE_MODE(*mode), + ); } } Cmd::Topology { kind } => l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(*kind)), Cmd::Viewports { all } => { let all: Vec = all .iter() - .map(|v| D3D12_VIEWPORT { TopLeftX: v[0], TopLeftY: v[1], Width: v[2], Height: v[3], MinDepth: v[4], MaxDepth: v[5] }) + .map(|v| D3D12_VIEWPORT { + TopLeftX: v[0], + TopLeftY: v[1], + Width: v[2], + Height: v[3], + MinDepth: v[4], + MaxDepth: v[5], + }) .collect(); l.RSSetViewports(&all); } - Cmd::Scissors { all } => l.RSSetScissorRects(&all.iter().map(|r| to_rect(*r)).collect::>()), + Cmd::Scissors { all } => { + l.RSSetScissorRects(&all.iter().map(|r| to_rect(*r)).collect::>()) + } Cmd::BlendFactor { factor } => l.OMSetBlendFactor(factor.as_ref()), Cmd::StencilRef { value } => l.OMSetStencilRef(*value), Cmd::DepthBounds { min, max } => { @@ -1615,27 +2201,52 @@ impl Player { } } Cmd::Barriers { all } => { - let all: Vec = all.iter().filter_map(|b| self.barrier(b)).collect(); + let all: Vec = + all.iter().filter_map(|b| self.barrier(b)).collect(); barriers(l, &all); } Cmd::Heaps { heaps } => { - let all: Vec> = - heaps.iter().filter_map(|id| Some(Some(self.descriptors.get(id)?.0.get(version)?.heap.clone()))).collect(); + let all: Vec> = heaps + .iter() + .filter_map(|id| { + Some(Some(self.descriptors.get(id)?.0.get(version)?.heap.clone())) + }) + .collect(); l.SetDescriptorHeaps(&all); } Cmd::RootSignature { graphics, root } => { let root = self.roots.get(root); - if *graphics { l.SetGraphicsRootSignature(root) } else { l.SetComputeRootSignature(root) } + if *graphics { + l.SetGraphicsRootSignature(root) + } else { + l.SetComputeRootSignature(root) + } } - Cmd::Table { graphics, param, heap, slot } => { + Cmd::Table { + graphics, + param, + heap, + slot, + } => { if let Some((versions, step)) = self.descriptors.get(heap) && let Some(v) = versions.get(version) { - let at = D3D12_GPU_DESCRIPTOR_HANDLE { ptr: v.gpu + u64::from(*slot) * step }; - if *graphics { l.SetGraphicsRootDescriptorTable(*param, at) } else { l.SetComputeRootDescriptorTable(*param, at) } + let at = D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: v.gpu + u64::from(*slot) * step, + }; + if *graphics { + l.SetGraphicsRootDescriptorTable(*param, at) + } else { + l.SetComputeRootDescriptorTable(*param, at) + } } } - Cmd::Constants { graphics, param, offset, values } => { + Cmd::Constants { + graphics, + param, + offset, + values, + } => { let (n, data) = (values.len() as u32, values.as_ptr().cast()); if *graphics { l.SetGraphicsRoot32BitConstants(*param, n, data, *offset); @@ -1643,7 +2254,12 @@ impl Player { l.SetComputeRoot32BitConstants(*param, n, data, *offset); } } - Cmd::RootView { graphics, kind, param, va } => { + Cmd::RootView { + graphics, + kind, + param, + va, + } => { let va = self.va(va); match (*kind, *graphics) { (slot::CBV, true) => l.SetGraphicsRootConstantBufferView(*param, va), @@ -1655,14 +2271,20 @@ impl Player { } } Cmd::IndexBuffer { view } => { - let v = view.as_ref().map(|(va, size, format)| D3D12_INDEX_BUFFER_VIEW { - BufferLocation: self.va(va), - SizeInBytes: *size, - Format: DXGI_FORMAT(*format), - }); + let v = view + .as_ref() + .map(|(va, size, format)| D3D12_INDEX_BUFFER_VIEW { + BufferLocation: self.va(va), + SizeInBytes: *size, + Format: DXGI_FORMAT(*format), + }); l.IASetIndexBuffer(v.as_ref().map(|v| v as *const _)); } - Cmd::VertexBuffers { start, views, count } => match views { + Cmd::VertexBuffers { + start, + views, + count, + } => match views { Some(views) => { let all: Vec = views .iter() @@ -1674,10 +2296,14 @@ impl Player { .collect(); l.IASetVertexBuffers(*start, Some(&all)); } - None => l.IASetVertexBuffers(*start, Some(&vec![D3D12_VERTEX_BUFFER_VIEW::default(); *count as usize])), + None => l.IASetVertexBuffers( + *start, + Some(&vec![D3D12_VERTEX_BUFFER_VIEW::default(); *count as usize]), + ), }, Cmd::Targets { colors, depth } => { - let colors: Vec = colors.iter().map(view).collect(); + let colors: Vec = + colors.iter().map(view).collect(); let depth = depth.as_ref().map(view); l.OMSetRenderTargets( colors.len() as u32, @@ -1686,26 +2312,50 @@ impl Player { depth.as_ref().map(|d| d as *const _), ); } - Cmd::ClearDepth { view: v, flags, depth, stencil, rects } => { + Cmd::ClearDepth { + view: v, + flags, + depth, + stencil, + rects, + } => { let rects: Vec = rects.iter().map(|r| to_rect(*r)).collect(); let rects = (!rects.is_empty()).then_some(&rects[..]); if self.objects.contains_key(&v.res) { - l.ClearDepthStencilView(view(v), D3D12_CLEAR_FLAGS(*flags), *depth, *stencil, rects); + l.ClearDepthStencilView( + view(v), + D3D12_CLEAR_FLAGS(*flags), + *depth, + *stencil, + rects, + ); } } - Cmd::ClearTarget { view: v, color, rects } => { + Cmd::ClearTarget { + view: v, + color, + rects, + } => { let rects: Vec = rects.iter().map(|r| to_rect(*r)).collect(); let rects = (!rects.is_empty()).then_some(&rects[..]); if self.objects.contains_key(&v.res) { l.ClearRenderTargetView(view(v), color, rects); } } - Cmd::Discard { res: id, rects, subs } => { + Cmd::Discard { + res: id, + rects, + subs, + } => { if let Some(r) = res(*id) { let rects: Vec = rects.iter().map(|r| to_rect(*r)).collect(); let region = subs.map(|s| D3D12_DISCARD_REGION { NumRects: rects.len() as u32, - pRects: if rects.is_empty() { std::ptr::null() } else { rects.as_ptr() }, + pRects: if rects.is_empty() { + std::ptr::null() + } else { + rects.as_ptr() + }, FirstSubresource: s[0], NumSubresources: s[1], }); @@ -1722,24 +2372,51 @@ impl Player { l.EndQuery(h, D3D12_QUERY_TYPE(*kind), *index); } } - Cmd::ResolveQuery { heap, kind, first, count, dst, at } => { + Cmd::ResolveQuery { + heap, + kind, + first, + count, + dst, + at, + } => { if let (Some(h), Some(dst)) = (self.queries.get(heap), res(*dst)) { l.ResolveQueryData(h, D3D12_QUERY_TYPE(*kind), *first, *count, dst, *at); } } - Cmd::Indirect { signature, most, args, at, count, count_at } => { + Cmd::Indirect { + signature, + most, + args, + at, + count, + count_at, + } => { if let (Some(s), Some(a)) = (self.signatures.get(signature), res(*args)) { l.ExecuteIndirect(s, *most, a, *at, res(*count), *count_at); } } Cmd::WriteImmediate { all } => { if let Ok(l) = l.cast::() { - let all: Vec<&(Va, u32, i32)> = all.iter().filter(|(va, _, _)| self.va(va) != 0).collect(); - let params: Vec = - all.iter().map(|(va, v, _)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: self.va(va), Value: *v }).collect(); - let modes: Vec = all.iter().map(|(_, _, m)| D3D12_WRITEBUFFERIMMEDIATE_MODE(*m)).collect(); + let all: Vec<&(Va, u32, i32)> = + all.iter().filter(|(va, _, _)| self.va(va) != 0).collect(); + let params: Vec = all + .iter() + .map(|(va, v, _)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { + Dest: self.va(va), + Value: *v, + }) + .collect(); + let modes: Vec = all + .iter() + .map(|(_, _, m)| D3D12_WRITEBUFFERIMMEDIATE_MODE(*m)) + .collect(); if !params.is_empty() { - l.WriteBufferImmediate(params.len() as u32, params.as_ptr(), Some(modes.as_ptr())); + l.WriteBufferImmediate( + params.len() as u32, + params.as_ptr(), + Some(modes.as_ptr()), + ); } } } @@ -1749,20 +2426,38 @@ impl Player { fn barrier(&self, b: &Barrier) -> Option { Some(match b { - Barrier::Transition { flags, res, sub, before, after } => { - let mut t = gpu::transition(self.resource(*res)?, *sub, *before as u32, *after as u32); + Barrier::Transition { + flags, + res, + sub, + before, + after, + } => { + let mut t = + gpu::transition(self.resource(*res)?, *sub, *before as u32, *after as u32); t.Flags = D3D12_RESOURCE_BARRIER_FLAGS(*flags); t } Barrier::Uav { flags, res } => { - let mut u = uav_barrier(if *res == NONE { None } else { Some(self.resource(*res)?) }); + let mut u = uav_barrier(if *res == NONE { + None + } else { + Some(self.resource(*res)?) + }); u.Flags = D3D12_RESOURCE_BARRIER_FLAGS(*flags); u } - Barrier::Alias { flags, before, after } => { + Barrier::Alias { + flags, + before, + after, + } => { let side = |id: &u32| -> std::mem::ManuallyDrop> { // SAFETY: a borrowed pointer (or none) never released. - self.resource(*id).map_or(std::mem::ManuallyDrop::new(None), |r| unsafe { std::mem::transmute_copy(r) }) + self.resource(*id) + .map_or(std::mem::ManuallyDrop::new(None), |r| unsafe { + std::mem::transmute_copy(r) + }) }; D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, @@ -1811,17 +2506,28 @@ impl Player { for all in &submissions { self.worker.queue.ExecuteCommandLists(all); } - self.worker.queue.ExecuteCommandLists(&[cast(&s.resolve.1)?]); + self.worker + .queue + .ExecuteCommandLists(&[cast(&s.resolve.1)?]); } - self.worker.idle().context("the card was lost running the frame")?; + self.worker + .idle() + .context("the card was lost running the frame")?; // SAFETY: the mapping of `count` resolved timestamps. Ok(unsafe { std::slice::from_raw_parts(s.data as *const u64, s.count as usize) }.to_vec()) } /// Runs the frame as the options say. pub fn run(&mut self, o: &Options) -> Result { - let mut report = Report { notes: self.notes.clone(), ..Default::default() }; - let clamps = if o.skip_clamps { self.clamp_results(&mut report)? } else { Vec::new() }; + let mut report = Report { + notes: self.notes.clone(), + ..Default::default() + }; + let clamps = if o.skip_clamps { + self.clamp_results(&mut report)? + } else { + Vec::new() + }; let submits = self.edited(o, &mut report, &clamps); let built = self.build(&submits, o)?; let mut stamps = Vec::new(); @@ -1829,20 +2535,33 @@ impl Player { self.restore(o.restore)?; self.fresh = false; stamps = self.send(&built, o.one_submit)?; - let ms = |a: u32, b: u32| stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency; + let ms = |a: u32, b: u32| { + stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency + }; let lists: Vec<&Built> = built.steps.iter().flat_map(|(_, l)| l).collect(); let (Some(first), Some(last)) = (lists.first(), lists.last()) else { bail!("no lists to run"); }; let delta = built.steps.iter().filter_map(|(d, _)| d.as_ref()); - report.delta_ms.push(delta.filter(|d| d.first > first.first).map(|d| ms(d.first, d.last)).sum()); + report.delta_ms.push( + delta + .filter(|d| d.first > first.first) + .map(|d| ms(d.first, d.last)) + .sum(), + ); report.frame_ms.push(ms(first.first, last.last)); let each = |l: &[Built]| match (l.first(), l.last()) { (Some(a), Some(b)) => ms(a.first, b.last), _ => 0.0, }; - report.submits = built.steps.iter().map(|(_, l)| (l.len(), each(l))).collect(); - report.busy_ms.push(report.submits.iter().map(|s| s.1).sum()); + report.submits = built + .steps + .iter() + .map(|(_, l)| (l.len(), each(l))) + .collect(); + report + .busy_ms + .push(report.submits.iter().map(|s| s.1).sum()); } if o.detailed { self.detail(&built, &stamps, o, &mut report); @@ -1871,12 +2590,21 @@ impl Player { } } } - report.categories = kinds.into_iter().map(|(k, (ms, n))| (k.to_owned(), ms, n)).collect(); + report.categories = kinds + .into_iter() + .map(|(k, (ms, n))| (k.to_owned(), ms, n)) + .collect(); report.categories.sort_by(|a, b| b.1.total_cmp(&a.1)); - let mut all: Vec<(f64, u32, u32)> = shaders.into_iter().map(|(pso, (ms, n))| (ms, n, pso)).collect(); + let mut all: Vec<(f64, u32, u32)> = shaders + .into_iter() + .map(|(pso, (ms, n))| (ms, n, pso)) + .collect(); all.sort_by(|a, b| b.0.total_cmp(&a.0)); all.truncate(o.top); - report.shaders = all.into_iter().map(|(ms, n, pso)| (ms, n, self.pipeline_name(pso))).collect(); + report.shaders = all + .into_iter() + .map(|(ms, n, pso)| (ms, n, self.pipeline_name(pso))) + .collect(); } /// Saves the presented picture and compares it with the recorded one. @@ -1886,17 +2614,28 @@ impl Player { return Ok(()); }; let Some(bytes) = self.contents(p.res)? else { - report.notes.push("the presented texture is not there".into()); + report + .notes + .push("the presented texture is not there".into()); return Ok(()); }; let Some(rgb) = gpu::rgb(p.width, p.height, p.pitch, p.format, &bytes) else { - report.notes.push("the presented format is not shown".into()); + report + .notes + .push("the presented format is not shown".into()); return Ok(()); }; - let path = o.image.clone().unwrap_or_else(|| self.folder.join("replay.png")); + let path = o + .image + .clone() + .unwrap_or_else(|| self.folder.join("replay.png")); std::fs::write(&path, crate::capture::png(p.width, p.height, &rgb))?; let mut recorded = vec![0; bytes.len()]; - read_at(&File::open(self.folder.join("present.bin"))?, &mut recorded, p.file)?; + read_at( + &File::open(self.folder.join("present.bin"))?, + &mut recorded, + p.file, + )?; let was = gpu::rgb(p.width, p.height, p.pitch, p.format, &recorded).unwrap_or_default(); report.picture = Some((gpu::psnr(&rgb, &was), rows_equal(&p, &bytes, &recorded))); report.notes.push(format!( @@ -1924,8 +2663,17 @@ impl Player { let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0; let states = if self.fresh { &self.start } else { &self.end }; let state = states.get(&id).cloned().unwrap_or(vec![COMMON]); - let (f, total) = if is_buffer { (Vec::new(), r.desc.width) } else { gpu::footprints(&self.device, &desc, sub, 1) }; - let (back, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_FLAG_NONE)?; + let (f, total) = if is_buffer { + (Vec::new(), r.desc.width) + } else { + gpu::footprints(&self.device, &desc, sub, 1) + }; + let (back, data) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_READBACK, + total, + D3D12_RESOURCE_FLAG_NONE, + )?; self.worker.run(|list| { if is_buffer { // SAFETY: an open list; live buffers. @@ -1944,12 +2692,18 @@ impl Player { } })?; // SAFETY: the buffer's mapping; the copy into it has run. - Ok(Some(unsafe { std::slice::from_raw_parts(data, total as usize) }.to_vec())) + Ok(Some( + unsafe { std::slice::from_raw_parts(data, total as usize) }.to_vec(), + )) } /// The id of the resource of a name (tests). pub fn named(&self, name: &str) -> Option { - self.frame.resources.iter().find(|r| r.name == name).map(|r| r.id) + self.frame + .resources + .iter() + .find(|r| r.name == name) + .map(|r| r.id) } } @@ -1978,7 +2732,12 @@ fn rows_equal(p: &wire::Present, a: &[u8], b: &[u8]) -> bool { } fn to_rect(r: [i32; 4]) -> RECT { - RECT { left: r[0], top: r[1], right: r[2], bottom: r[3] } + RECT { + left: r[0], + top: r[1], + right: r[2], + bottom: r[3], + } } /// # Safety @@ -1997,7 +2756,9 @@ fn uav_barrier(res: Option<&ID3D12Resource>) -> D3D12_RESOURCE_BARRIER { Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { // SAFETY: a borrowed pointer (or none) never released. - pResource: res.map_or(std::mem::ManuallyDrop::new(None), |r| unsafe { std::mem::transmute_copy(r) }), + pResource: res.map_or(std::mem::ManuallyDrop::new(None), |r| unsafe { + std::mem::transmute_copy(r) + }), }), }, } @@ -2042,7 +2803,9 @@ fn make_device(frame: &Frame, debug: bool) -> Result<(ID3D12Device, Option Result<(ID3D12Device, Option = None; match &adapter { @@ -2081,13 +2847,19 @@ fn debug_messages(q: &ID3D12InfoQueue) -> Vec { let m = &*message; if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 { let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); - let text = || String::from_utf8_lossy(text).trim_end_matches('\0').to_owned(); + let text = || { + String::from_utf8_lossy(text) + .trim_end_matches('\0') + .to_owned() + }; seen.entry(m.ID.0).or_insert_with(|| (0, text())).0 += 1; } } q.ClearStoredMessages(); } - seen.into_iter().map(|(id, (n, text))| format!("debug layer: {n} errors {id}, first: {text}")).collect() + seen.into_iter() + .map(|(id, (n, text))| format!("debug layer: {n} errors {id}, first: {text}")) + .collect() } #[cfg(test)] @@ -2106,7 +2878,10 @@ mod tests { } // The last complete one; itself when named. assert_eq!(find(dir.path()).unwrap(), dir.path().join("capture-10")); - assert_eq!(find(&dir.path().join("capture-2")).unwrap(), dir.path().join("capture-2")); + assert_eq!( + find(&dir.path().join("capture-2")).unwrap(), + dir.path().join("capture-2") + ); } #[test] @@ -2125,7 +2900,11 @@ mod tests { assert!(t.contains("a frame: 11.00 ms"), "{t}"); assert!(t.contains("between submissions 1.50 ms"), "{t}"); assert!(t.contains("PSNR 40.0 dB"), "{t}"); - let o = Options { skip_clamps: true, buffers: Buffers::Card, ..Default::default() }; + let o = Options { + skip_clamps: true, + buffers: Buffers::Card, + ..Default::default() + }; assert!(o.edited() && !o.plain().edited() && o.plain().buffers == Buffers::Card); } } diff --git a/crates/victory-gpu/src/replay/pso.rs b/crates/victory-gpu/src/replay/pso.rs index c1baa0d..aec3fbc 100644 --- a/crates/victory-gpu/src/replay/pso.rs +++ b/crates/victory-gpu/src/replay/pso.rs @@ -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::(), size) }.to_vec()) } + Part::Plain { + kind, + data: Blob(unsafe { std::slice::from_raw_parts(at.cast::(), size) }.to_vec()), + } } unsafe fn code(kind: i32, c: &D3D12_SHADER_BYTECODE, keep: &mut dyn Keep) -> Option { @@ -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::(), c.BytecodeLength) }; - Some(Part::Code { kind, blob: keep.code(bytes) }) + let bytes = + unsafe { std::slice::from_raw_parts(c.pShaderBytecode.cast::(), c.BytecodeLength) }; + Some(Part::Code { + kind, + blob: keep.code(bytes), + }) } unsafe fn layout(l: &D3D12_INPUT_LAYOUT_DESC) -> Option { @@ -72,34 +79,44 @@ unsafe fn layout(l: &D3D12_INPUT_LAYOUT_DESC) -> Option { 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 { +pub(super) unsafe fn compute( + d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, + keep: &mut dyn Keep, +) -> Vec { // 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 { +pub(super) unsafe fn graphics( + d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, + keep: &mut dyn Keep, +) -> Vec { // 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::())); + parts.push(plain( + 8, + (&raw const d.BlendState).cast(), + size_of::(), + )); parts.push(plain(9, (&raw const d.SampleMask).cast(), 4)); - parts.push(plain(10, (&raw const d.RasterizerState).cast(), size_of::())); - parts.push(plain(11, (&raw const d.DepthStencilState).cast(), size_of::())); + parts.push(plain( + 10, + (&raw const d.RasterizerState).cast(), + size_of::(), + )); + parts.push(plain( + 11, + (&raw const d.DepthStencilState).cast(), + size_of::(), + )); 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::())); + let targets = D3D12_RT_FORMAT_ARRAY { + RTFormats: d.RTVFormats, + NumRenderTargets: d.NumRenderTargets, + }; + parts.push(plain( + 15, + (&raw const targets).cast(), + size_of::(), + )); parts.push(plain(16, (&raw const d.DSVFormat).cast(), 4)); - parts.push(plain(17, (&raw const d.SampleDesc).cast(), size_of::())); + parts.push(plain( + 17, + (&raw const d.SampleDesc).cast(), + size_of::(), + )); 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 { +pub(super) unsafe fn stream( + d: &D3D12_PIPELINE_STATE_STREAM_DESC, + keep: &mut dyn Keep, +) -> Vec { let base = d.pPipelineStateSubobjectStream.cast::().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::().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 = bytes.chunks_exact(8).map(|c| u64::from_le_bytes(c.try_into().unwrap_or_default())).collect(); + let mut words: Vec = 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 = unsafe { device.CreatePipelineState(&desc) }; + let made: windows::core::Result = + 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::(), pPipelineStateSubobjectStream: (&raw mut s).cast() }; + let d = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: size_of::(), + 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::()); - 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()) + } + ); } } diff --git a/crates/victory-gpu/src/replay/record.rs b/crates/victory-gpu/src/replay/record.rs index 799fe1e..c839d60 100644 --- a/crates/victory-gpu/src/replay/record.rs +++ b/crates/victory-gpu/src/replay/record.rs @@ -60,9 +60,17 @@ impl Settings { pub fn from_env() -> Option { let folder = PathBuf::from(std::env::var_os("VICTORY_RECORD").filter(|v| !v.is_empty())?); let at = parse_at(&std::env::var("VICTORY_RECORD_AT").unwrap_or_default()); - let frames = std::env::var("VICTORY_RECORD_FRAMES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1); + let frames = std::env::var("VICTORY_RECORD_FRAMES") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(1); let always = std::env::var_os("VICTORY_RECORD_ALWAYS").is_some_and(|v| v == "1"); - Some(Settings { folder, at, frames: std::cmp::max(frames, 1), always }) + Some(Settings { + folder, + at, + frames: std::cmp::max(frames, 1), + always, + }) } } @@ -148,11 +156,21 @@ impl Heap { if slots.is_null() { std::alloc::handle_alloc_error(layout); } - Heap { id, kind: desc.Type.0, count: desc.NumDescriptors, flags: desc.Flags.0, cpu, gpu, step, slots } + Heap { + id, + kind: desc.Type.0, + count: desc.NumDescriptors, + flags: desc.Flags.0, + cpu, + gpu, + step, + slots, + } } fn layout(count: u32) -> std::alloc::Layout { - std::alloc::Layout::array::(count.max(1) as usize).unwrap_or(std::alloc::Layout::new::()) + std::alloc::Layout::array::(count.max(1) as usize) + .unwrap_or(std::alloc::Layout::new::()) } pub(super) fn visible(&self) -> bool { @@ -202,8 +220,13 @@ pub(super) struct Heaps { impl Heaps { fn add(&mut self, heap: Arc) { let end = heap.cpu + heap.count as usize * heap.step; - let gone: Vec = - self.by_cpu.range(..end).rev().take_while(|(_, h)| h.cpu + h.count as usize * h.step > heap.cpu).map(|(&k, _)| k).collect(); + let gone: Vec = self + .by_cpu + .range(..end) + .rev() + .take_while(|(_, h)| h.cpu + h.count as usize * h.step > heap.cpu) + .map(|(&k, _)| k) + .collect(); for k in gone { self.by_cpu.remove(&k); } @@ -400,7 +423,12 @@ impl Recorder { signatures: Mutex::default(), queries: Mutex::default(), names: Mutex::default(), - codes: Mutex::new(Codes { file: Some(file), at: 0, index: HashMap::new(), all: Vec::new() }), + codes: Mutex::new(Codes { + file: Some(file), + at: 0, + index: HashMap::new(), + all: Vec::new(), + }), states: Mutex::default(), queues: Mutex::default(), device: Mutex::default(), @@ -433,7 +461,16 @@ impl Recorder { /// The problems so far. pub(super) fn problems(&self) -> Vec { - lock(&self.problems).iter().map(|(what, n)| if *n == 1 { what.clone() } else { format!("{what} ({n} times)") }).collect() + lock(&self.problems) + .iter() + .map(|(what, n)| { + if *n == 1 { + what.clone() + } else { + format!("{what} ({n} times)") + } + }) + .collect() } pub(super) fn arm(&self, on: bool) { @@ -444,6 +481,12 @@ impl Recorder { lock(&self.device).clone() } + /// Whether a list was made through the hooked device (the swap chain may + /// have others). + pub(super) fn knows(&self, p: Ptr) -> bool { + read(&self.lists).contains_key(&(p as usize)) + } + /// The state of a list, if its methods are still ours. pub(super) fn list(&self, p: Ptr) -> Option> { let state = read(&self.lists).get(&(p as usize)).cloned()?; @@ -461,7 +504,10 @@ impl Recorder { return Va::Null {}; } match read(&self.addresses).range(..=address).next_back() { - Some((&start, &(size, res))) if address - start < size => Va::At { res, offset: address - start }, + Some((&start, &(size, res))) if address - start < size => Va::At { + res, + offset: address - start, + }, _ => Va::Unknown { address }, } } @@ -498,13 +544,19 @@ impl Recorder { let id = self.id(); let seen = match &place { Place::Committed { props, .. } => gpu::seen(props), - Place::Placed { heap, .. } => lock(&self.heaps).get(heap).map_or(gpu::Seen::No, |h| gpu::seen(&h.props)), + Place::Placed { heap, .. } => lock(&self.heaps) + .get(heap) + .map_or(gpu::Seen::No, |h| gpu::seen(&h.props)), Place::BackBuffer {} => gpu::Seen::No, }; let subs = gpu::subresources(&desc); let is_buffer = desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0; // SAFETY: a live buffer. - let va = if is_buffer { unsafe { object.GetGPUVirtualAddress() } } else { 0 }; + let va = if is_buffer { + unsafe { object.GetGPUVirtualAddress() } + } else { + 0 + }; let placed = matches!(place, Place::Placed { .. }); let late = self.watching.load(Ordering::SeqCst); { @@ -520,13 +572,30 @@ impl Recorder { if va != 0 { write(&self.addresses).insert(va, (desc.width, id)); } - let res = Arc::new(Res { id, ptr: p as usize, place, desc, made_in, clear, subs, seen, late }); + let res = Arc::new(Res { + id, + ptr: p as usize, + place, + desc, + made_in, + clear, + subs, + seen, + late, + }); write(&self.resources).insert(id, res); self.ids.set(p as usize, id); if late { lock(&self.held).push(ID3D12Resource::clone(&object)); } - self.tell_gone(&*object, Gone::Resource { id, ptr: p as usize, va }); + self.tell_gone( + &*object, + Gone::Resource { + id, + ptr: p as usize, + va, + }, + ); id } @@ -557,12 +626,18 @@ impl Recorder { /// Has us told when an object dies. fn tell_gone(&self, object: &impl Interface, what: Gone) { const KEY: GUID = GUID::from_u128(0x3d0d5c1e_7a1b_4a53_9a3e_5f2b1e6b9c41); - let notice = Box::into_raw(Box::new(Notice { methods: &NOTICE, references: AtomicU32::new(1), what })); + let notice = Box::into_raw(Box::new(Notice { + methods: &NOTICE, + references: AtomicU32::new(1), + what, + })); // SAFETY: a COM object of ours with one reference, which this drops // at the end; the object takes its own. unsafe { let notice = IUnknown::from_raw(notice.cast()); - let set = object.cast::().and_then(|o| o.SetPrivateDataInterface(&KEY, ¬ice)); + let set = object + .cast::() + .and_then(|o| o.SetPrivateDataInterface(&KEY, ¬ice)); if set.is_err() { self.problem("an object's end cannot be followed"); std::mem::forget(notice); @@ -620,14 +695,21 @@ impl Recorder { } let i = codes.all.len() as u32; let at = codes.at; - let wrote = codes.file.as_mut().is_some_and(|f| f.write_all(bytes).is_ok()); + let wrote = codes + .file + .as_mut() + .is_some_and(|f| f.write_all(bytes).is_ok()); if !wrote { drop(codes); self.problem("shader code could not be written"); return u32::MAX; } codes.at += bytes.len() as u64; - codes.all.push(wire::Code { at, len: bytes.len() as u64, hash }); + codes.all.push(wire::Code { + at, + len: bytes.len() as u64, + hash, + }); codes.index.insert(hash, i); i } @@ -681,7 +763,11 @@ struct NoticeTable { add: unsafe extern "system" fn(Ptr) -> u32, release: unsafe extern "system" fn(Ptr) -> u32, } -static NOTICE: NoticeTable = NoticeTable { query: notice_query, add: notice_add, release: notice_release }; +static NOTICE: NoticeTable = NoticeTable { + query: notice_query, + add: notice_add, + release: notice_release, +}; unsafe extern "system" fn notice_query(this: Ptr, iid: *const GUID, out: Out) -> HRESULT { // SAFETY: COM's rules: a valid id and place for the answer. @@ -698,13 +784,21 @@ unsafe extern "system" fn notice_query(this: Ptr, iid: *const GUID, out: Out) -> unsafe extern "system" fn notice_add(this: Ptr) -> u32 { // SAFETY: one of ours, alive while a reference is. - unsafe { (*this.cast::()).references.fetch_add(1, Ordering::Relaxed) + 1 } + unsafe { + (*this.cast::()) + .references + .fetch_add(1, Ordering::Relaxed) + + 1 + } } unsafe extern "system" fn notice_release(this: Ptr) -> u32 { // SAFETY: as above; the last reference frees the box it was made as. unsafe { - let left = (*this.cast::()).references.fetch_sub(1, Ordering::AcqRel) - 1; + let left = (*this.cast::()) + .references + .fetch_sub(1, Ordering::AcqRel) + - 1; if left == 0 { let notice = Box::from_raw(this.cast::()); if let Some(r) = recorder() { @@ -831,10 +925,19 @@ macro_rules! not_recorded { fn device_table(t: &mut [usize; hook::SLOTS]) { set!(t, ID3D12Device_Vtbl.CreateCommandQueue = create_queue); - set!(t, ID3D12Device_Vtbl.CreateGraphicsPipelineState = create_graphics); - set!(t, ID3D12Device_Vtbl.CreateComputePipelineState = create_compute); + set!( + t, + ID3D12Device_Vtbl.CreateGraphicsPipelineState = create_graphics + ); + set!( + t, + ID3D12Device_Vtbl.CreateComputePipelineState = create_compute + ); set!(t, ID3D12Device_Vtbl.CreateCommandList = create_list); - set!(t, ID3D12Device_Vtbl.CreateDescriptorHeap = create_descriptors); + set!( + t, + ID3D12Device_Vtbl.CreateDescriptorHeap = create_descriptors + ); set!(t, ID3D12Device_Vtbl.CreateRootSignature = create_root); set!(t, ID3D12Device_Vtbl.CreateConstantBufferView = create_cbv); set!(t, ID3D12Device_Vtbl.CreateShaderResourceView = create_srv); @@ -843,12 +946,21 @@ fn device_table(t: &mut [usize; hook::SLOTS]) { set!(t, ID3D12Device_Vtbl.CreateDepthStencilView = create_dsv); set!(t, ID3D12Device_Vtbl.CreateSampler = create_sampler); set!(t, ID3D12Device_Vtbl.CopyDescriptors = copy_descriptors); - set!(t, ID3D12Device_Vtbl.CopyDescriptorsSimple = copy_descriptors_simple); - set!(t, ID3D12Device_Vtbl.CreateCommittedResource = create_committed); + set!( + t, + ID3D12Device_Vtbl.CopyDescriptorsSimple = copy_descriptors_simple + ); + set!( + t, + ID3D12Device_Vtbl.CreateCommittedResource = create_committed + ); set!(t, ID3D12Device_Vtbl.CreateHeap = create_heap); set!(t, ID3D12Device_Vtbl.CreatePlacedResource = create_placed); set!(t, ID3D12Device_Vtbl.CreateQueryHeap = create_queries); - set!(t, ID3D12Device_Vtbl.CreateCommandSignature = create_signature); + set!( + t, + ID3D12Device_Vtbl.CreateCommandSignature = create_signature + ); set!(t, ID3D12Device1_Vtbl.CreatePipelineLibrary = create_library); set!(t, ID3D12Device2_Vtbl.CreatePipelineState = create_stream); let _ = device_rest(t); @@ -889,8 +1001,14 @@ fn queue_rest(t: &mut [usize; hook::SLOTS]) -> &'static [(usize, &'static str)] } fn library_table(t: &mut [usize; hook::SLOTS]) { - set!(t, ID3D12PipelineLibrary_Vtbl.LoadGraphicsPipeline = load_graphics); - set!(t, ID3D12PipelineLibrary_Vtbl.LoadComputePipeline = load_compute); + set!( + t, + ID3D12PipelineLibrary_Vtbl.LoadGraphicsPipeline = load_graphics + ); + set!( + t, + ID3D12PipelineLibrary_Vtbl.LoadComputePipeline = load_compute + ); set!(t, ID3D12PipelineLibrary1_Vtbl.LoadPipeline = load_stream); } @@ -898,48 +1016,153 @@ fn list_table(t: &mut [usize; hook::SLOTS]) { set!(t, ID3D12GraphicsCommandList_Vtbl.Close = list_close); set!(t, ID3D12GraphicsCommandList_Vtbl.Reset = list_reset); set!(t, ID3D12GraphicsCommandList_Vtbl.DrawInstanced = draw); - set!(t, ID3D12GraphicsCommandList_Vtbl.DrawIndexedInstanced = draw_indexed); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.DrawIndexedInstanced = draw_indexed + ); set!(t, ID3D12GraphicsCommandList_Vtbl.Dispatch = dispatch); - set!(t, ID3D12GraphicsCommandList_Vtbl.CopyBufferRegion = copy_buffer); - set!(t, ID3D12GraphicsCommandList_Vtbl.CopyTextureRegion = copy_texture); - set!(t, ID3D12GraphicsCommandList_Vtbl.CopyResource = copy_resource); - set!(t, ID3D12GraphicsCommandList_Vtbl.ResolveSubresource = resolve); - set!(t, ID3D12GraphicsCommandList_Vtbl.IASetPrimitiveTopology = topology); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.CopyBufferRegion = copy_buffer + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.CopyTextureRegion = copy_texture + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.CopyResource = copy_resource + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.ResolveSubresource = resolve + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.IASetPrimitiveTopology = topology + ); set!(t, ID3D12GraphicsCommandList_Vtbl.RSSetViewports = viewports); - set!(t, ID3D12GraphicsCommandList_Vtbl.RSSetScissorRects = scissors); - set!(t, ID3D12GraphicsCommandList_Vtbl.OMSetBlendFactor = blend_factor); - set!(t, ID3D12GraphicsCommandList_Vtbl.OMSetStencilRef = stencil_ref); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetPipelineState = set_pipeline); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.RSSetScissorRects = scissors + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.OMSetBlendFactor = blend_factor + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.OMSetStencilRef = stencil_ref + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetPipelineState = set_pipeline + ); set!(t, ID3D12GraphicsCommandList_Vtbl.ResourceBarrier = barrier); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetDescriptorHeaps = set_heaps); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootSignature = root_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootSignature = root_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootDescriptorTable = table_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootDescriptorTable = table_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstant = constant_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstant = constant_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstants = constants_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstants = constants_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootConstantBufferView = cbv_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootConstantBufferView = cbv_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootShaderResourceView = srv_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootShaderResourceView = srv_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootUnorderedAccessView = uav_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootUnorderedAccessView = uav_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.IASetIndexBuffer = index_buffer); - set!(t, ID3D12GraphicsCommandList_Vtbl.IASetVertexBuffers = vertex_buffers); - set!(t, ID3D12GraphicsCommandList_Vtbl.OMSetRenderTargets = targets); - set!(t, ID3D12GraphicsCommandList_Vtbl.ClearDepthStencilView = clear_depth); - set!(t, ID3D12GraphicsCommandList_Vtbl.ClearRenderTargetView = clear_target); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetDescriptorHeaps = set_heaps + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRootSignature = root_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootSignature = root_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRootDescriptorTable = table_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootDescriptorTable = table_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstant = constant_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstant = constant_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstants = constants_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstants = constants_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRootConstantBufferView = cbv_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootConstantBufferView = cbv_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRootShaderResourceView = srv_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootShaderResourceView = srv_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRootUnorderedAccessView = uav_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootUnorderedAccessView = uav_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.IASetIndexBuffer = index_buffer + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.IASetVertexBuffers = vertex_buffers + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.OMSetRenderTargets = targets + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.ClearDepthStencilView = clear_depth + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.ClearRenderTargetView = clear_target + ); set!(t, ID3D12GraphicsCommandList_Vtbl.DiscardResource = discard); set!(t, ID3D12GraphicsCommandList_Vtbl.BeginQuery = begin_query); set!(t, ID3D12GraphicsCommandList_Vtbl.EndQuery = end_query); - set!(t, ID3D12GraphicsCommandList_Vtbl.ResolveQueryData = resolve_query); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.ResolveQueryData = resolve_query + ); set!(t, ID3D12GraphicsCommandList_Vtbl.ExecuteIndirect = indirect); - set!(t, ID3D12GraphicsCommandList1_Vtbl.ResolveSubresourceRegion = resolve_region); - set!(t, ID3D12GraphicsCommandList1_Vtbl.OMSetDepthBounds = depth_bounds); - set!(t, ID3D12GraphicsCommandList2_Vtbl.WriteBufferImmediate = write_immediate); - set!(t, ID3D12GraphicsCommandList6_Vtbl.DispatchMesh = dispatch_mesh); + set!( + t, + ID3D12GraphicsCommandList1_Vtbl.ResolveSubresourceRegion = resolve_region + ); + set!( + t, + ID3D12GraphicsCommandList1_Vtbl.OMSetDepthBounds = depth_bounds + ); + set!( + t, + ID3D12GraphicsCommandList2_Vtbl.WriteBufferImmediate = write_immediate + ); + set!( + t, + ID3D12GraphicsCommandList6_Vtbl.DispatchMesh = dispatch_mesh + ); let _ = list_rest(t); } @@ -990,7 +1213,10 @@ pub(super) fn not_recorded_calls() -> Vec<(String, u64)> { for &(slot, name) in names { let what = match (class, name) { // Submissions are in order anyway: the replay has one queue. - (hook::QUEUE, "Wait") => "waits of the drawing queue (the swap chain makes some) are not replayed".to_owned(), + (hook::QUEUE, "Wait") => { + "waits of the drawing queue (the swap chain makes some) are not replayed" + .to_owned() + } _ => format!("{of} method {name} is not recorded, and was called"), }; all.push((what, hook::count(class, slot))); @@ -1011,7 +1237,12 @@ fn made(hr: HRESULT, out: Out) -> Option<(&'static Recorder, Ptr)> { Some((recorder()?, p)) } -unsafe extern "system" fn create_queue(this: Ptr, desc: *const D3D12_COMMAND_QUEUE_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_queue( + this: Ptr, + desc: *const D3D12_COMMAND_QUEUE_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: the caller's arguments, passed on; then a new queue no other // thread knows. unsafe { @@ -1037,9 +1268,14 @@ unsafe extern "system" fn create_list( ) -> HRESULT { // SAFETY: as above. unsafe { - let hr = own!(this, ID3D12Device_Vtbl.CreateCommandList)(this, nodes, kind, allocator, pso, iid, out); + let hr = own!(this, ID3D12Device_Vtbl.CreateCommandList)( + this, nodes, kind, allocator, pso, iid, out, + ); if let Some((r, p)) = made(hr, out) { - let state = Arc::new(ListState { kind: kind.0, inner: Mutex::default() }); + let state = Arc::new(ListState { + kind: kind.0, + inner: Mutex::default(), + }); // Every interface of it we hook, and the one it is submitted as. static ONE: OnceLock = OnceLock::new(); let iids = [ @@ -1049,21 +1285,32 @@ unsafe extern "system" fn create_list( ID3D12GraphicsCommandList4::IID, ID3D12GraphicsCommandList6::IID, ]; - let same = *ONE.get_or_init(|| iids.iter().all(|iid| query(p, iid).is_none_or(|q| q.as_raw() == p))); + let same = *ONE.get_or_init(|| { + iids.iter() + .all(|iid| query(p, iid).is_none_or(|q| q.as_raw() == p)) + }); let mut all = vec![p]; if !same { - all.extend(iids.iter().filter_map(|iid| query(p, iid)).map(|q| q.as_raw())); + all.extend( + iids.iter() + .filter_map(|iid| query(p, iid)) + .map(|q| q.as_raw()), + ); } { let mut inner = lock(&state.inner); - inner.whole = r.armed.load(Ordering::SeqCst) && kind == D3D12_COMMAND_LIST_TYPE_DIRECT; + inner.whole = + r.armed.load(Ordering::SeqCst) && kind == D3D12_COMMAND_LIST_TYPE_DIRECT; begin(&mut inner, r, pso); } for q in all { // The state's address is kept for good, as the table is. hook::install(q, Arc::into_raw(state.clone()).cast(), list_table); write(&r.lists).insert(q as usize, state.clone()); - r.tell_gone(&*borrow::(q), Gone::List { ptr: q as usize }); + r.tell_gone( + &*borrow::(q), + Gone::List { ptr: q as usize }, + ); } } hr @@ -1075,11 +1322,20 @@ fn begin(inner: &mut ListInner, r: &Recorder, pso: Ptr) { inner.bytes = Vec::new(); inner.changes.clear(); if inner.whole && !pso.is_null() { - Cmd::Pipeline { pso: r.object(pso, "a pipeline") }.put(&mut inner.bytes); + Cmd::Pipeline { + pso: r.object(pso, "a pipeline"), + } + .put(&mut inner.bytes); } } -unsafe extern "system" fn create_library(this: Ptr, blob: *const c_void, size: usize, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_library( + this: Ptr, + blob: *const c_void, + size: usize, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { let hr = own!(this, ID3D12Device1_Vtbl.CreatePipelineLibrary)(this, blob, size, iid, out); @@ -1095,7 +1351,12 @@ unsafe extern "system" fn create_library(this: Ptr, blob: *const c_void, size: u } } -unsafe extern "system" fn create_graphics(this: Ptr, desc: *const D3D12_GRAPHICS_PIPELINE_STATE_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_graphics( + this: Ptr, + desc: *const D3D12_GRAPHICS_PIPELINE_STATE_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above; the description is valid, as it was accepted. unsafe { let hr = own!(this, ID3D12Device_Vtbl.CreateGraphicsPipelineState)(this, desc, iid, out); @@ -1106,7 +1367,12 @@ unsafe extern "system" fn create_graphics(this: Ptr, desc: *const D3D12_GRAPHICS } } -unsafe extern "system" fn create_compute(this: Ptr, desc: *const D3D12_COMPUTE_PIPELINE_STATE_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_compute( + this: Ptr, + desc: *const D3D12_COMPUTE_PIPELINE_STATE_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { let hr = own!(this, ID3D12Device_Vtbl.CreateComputePipelineState)(this, desc, iid, out); @@ -1117,7 +1383,12 @@ unsafe extern "system" fn create_compute(this: Ptr, desc: *const D3D12_COMPUTE_P } } -unsafe extern "system" fn create_stream(this: Ptr, desc: *const D3D12_PIPELINE_STATE_STREAM_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_stream( + this: Ptr, + desc: *const D3D12_PIPELINE_STATE_STREAM_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { let hr = own!(this, ID3D12Device2_Vtbl.CreatePipelineState)(this, desc, iid, out); @@ -1137,7 +1408,8 @@ unsafe extern "system" fn load_graphics( ) -> HRESULT { // SAFETY: as above. unsafe { - let hr = own!(this, ID3D12PipelineLibrary_Vtbl.LoadGraphicsPipeline)(this, name, desc, iid, out); + let hr = + own!(this, ID3D12PipelineLibrary_Vtbl.LoadGraphicsPipeline)(this, name, desc, iid, out); if let Some((r, p)) = made(hr, out) { r.pipeline(p, pso::graphics(&*desc, &mut Keeper(r))); } @@ -1154,7 +1426,8 @@ unsafe extern "system" fn load_compute( ) -> HRESULT { // SAFETY: as above. unsafe { - let hr = own!(this, ID3D12PipelineLibrary_Vtbl.LoadComputePipeline)(this, name, desc, iid, out); + let hr = + own!(this, ID3D12PipelineLibrary_Vtbl.LoadComputePipeline)(this, name, desc, iid, out); if let Some((r, p)) = made(hr, out) { r.pipeline(p, pso::compute(&*desc, &mut Keeper(r))); } @@ -1179,13 +1452,24 @@ unsafe extern "system" fn load_stream( } } -unsafe extern "system" fn create_root(this: Ptr, nodes: u32, blob: *const c_void, size: usize, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_root( + this: Ptr, + nodes: u32, + blob: *const c_void, + size: usize, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { - let hr = own!(this, ID3D12Device_Vtbl.CreateRootSignature)(this, nodes, blob, size, iid, out); + let hr = + own!(this, ID3D12Device_Vtbl.CreateRootSignature)(this, nodes, blob, size, iid, out); if let Some((r, p)) = made(hr, out) { // D3D12 may answer with an object it made before. - let known = r.ids.get(p as usize).filter(|id| lock(&r.roots).contains_key(id)); + let known = r + .ids + .get(p as usize) + .filter(|id| lock(&r.roots).contains_key(id)); let bytes = std::slice::from_raw_parts(blob.cast::(), size).to_vec(); let id = known.unwrap_or_else(|| r.id()); lock(&r.roots).insert(id, Arc::new(bytes)); @@ -1208,8 +1492,11 @@ unsafe extern "system" fn create_signature( if let Some((r, p)) = made(hr, out) { let id = r.id(); let d = &*desc; - let args: Vec<[u32; 4]> = - std::slice::from_raw_parts(d.pArgumentDescs.cast::<[u32; 4]>(), d.NumArgumentDescs as usize).to_vec(); + let args: Vec<[u32; 4]> = std::slice::from_raw_parts( + d.pArgumentDescs.cast::<[u32; 4]>(), + d.NumArgumentDescs as usize, + ) + .to_vec(); // Arguments that are GPU addresses lie in buffers; they are not // rewritten for a replay. let addresses = [ @@ -1219,31 +1506,63 @@ unsafe extern "system" fn create_signature( D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW, D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW, ]; - if args.iter().any(|a| addresses.iter().any(|t| t.0 as u32 == a[0])) { + if args + .iter() + .any(|a| addresses.iter().any(|t| t.0 as u32 == a[0])) + { r.problem("a command signature with GPU addresses among its arguments: a replay reads the recorded addresses"); } - let root = if root.is_null() { NONE } else { r.object(root, "a root signature") }; - lock(&r.signatures).insert(id, wire::Signature { id, stride: d.ByteStride, args, root }); + let root = if root.is_null() { + NONE + } else { + r.object(root, "a root signature") + }; + lock(&r.signatures).insert( + id, + wire::Signature { + id, + stride: d.ByteStride, + args, + root, + }, + ); r.ids.set(p as usize, id); } hr } } -unsafe extern "system" fn create_queries(this: Ptr, desc: *const D3D12_QUERY_HEAP_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_queries( + this: Ptr, + desc: *const D3D12_QUERY_HEAP_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { let hr = own!(this, ID3D12Device_Vtbl.CreateQueryHeap)(this, desc, iid, out); if let Some((r, p)) = made(hr, out) { let id = r.id(); - lock(&r.queries).insert(id, wire::QueryHeap { id, kind: (*desc).Type.0, count: (*desc).Count }); + lock(&r.queries).insert( + id, + wire::QueryHeap { + id, + kind: (*desc).Type.0, + count: (*desc).Count, + }, + ); r.ids.set(p as usize, id); } hr } } -unsafe extern "system" fn create_descriptors(this: Ptr, desc: *const D3D12_DESCRIPTOR_HEAP_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_descriptors( + this: Ptr, + desc: *const D3D12_DESCRIPTOR_HEAP_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { let hr = own!(this, ID3D12Device_Vtbl.CreateDescriptorHeap)(this, desc, iid, out); @@ -1252,18 +1571,34 @@ unsafe extern "system" fn create_descriptors(this: Ptr, desc: *const D3D12_DESCR let d = &*desc; let visible = d.Flags.0 & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 != 0; let cpu = heap.GetCPUDescriptorHandleForHeapStart().ptr; - let gpu = if visible { heap.GetGPUDescriptorHandleForHeapStart().ptr } else { 0 }; - let step = own!(this, ID3D12Device_Vtbl.GetDescriptorHandleIncrementSize)(this, d.Type) as usize; + let gpu = if visible { + heap.GetGPUDescriptorHandleForHeapStart().ptr + } else { + 0 + }; + let step = own!(this, ID3D12Device_Vtbl.GetDescriptorHandleIncrementSize)(this, d.Type) + as usize; let id = r.id(); write(&r.descriptors).add(Arc::new(Heap::new(id, d, cpu, gpu, step.max(1)))); r.ids.set(p as usize, id); - r.tell_gone(&*heap, Gone::Heap { id, ptr: p as usize }); + r.tell_gone( + &*heap, + Gone::Heap { + id, + ptr: p as usize, + }, + ); } hr } } -unsafe extern "system" fn create_heap(this: Ptr, desc: *const D3D12_HEAP_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_heap( + this: Ptr, + desc: *const D3D12_HEAP_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { let hr = own!(this, ID3D12Device_Vtbl.CreateHeap)(this, desc, iid, out); @@ -1277,7 +1612,13 @@ unsafe extern "system" fn create_heap(this: Ptr, desc: *const D3D12_HEAP_DESC, i } fn heap_of(id: u32, d: &D3D12_HEAP_DESC) -> wire::Heap { - wire::Heap { id, size: d.SizeInBytes, props: gpu::from_props(&d.Properties), alignment: d.Alignment, flags: d.Flags.0 } + wire::Heap { + id, + size: d.SizeInBytes, + props: gpu::from_props(&d.Properties), + alignment: d.Alignment, + flags: d.Flags.0, + } } unsafe fn clear_of(clear: *const D3D12_CLEAR_VALUE) -> Option<[u32; 5]> { @@ -1299,9 +1640,14 @@ unsafe extern "system" fn create_committed( ) -> HRESULT { // SAFETY: as above. unsafe { - let hr = own!(this, ID3D12Device_Vtbl.CreateCommittedResource)(this, props, flags, desc, state, clear, iid, out); + let hr = own!(this, ID3D12Device_Vtbl.CreateCommittedResource)( + this, props, flags, desc, state, clear, iid, out, + ); if let Some((r, p)) = made(hr, out) { - let place = Place::Committed { props: gpu::from_props(&*props), flags: flags.0 }; + let place = Place::Committed { + props: gpu::from_props(&*props), + flags: flags.0, + }; r.add(p, place, state.0, clear_of(clear)); } hr @@ -1321,7 +1667,9 @@ unsafe extern "system" fn create_placed( ) -> HRESULT { // SAFETY: as above. unsafe { - let hr = own!(this, ID3D12Device_Vtbl.CreatePlacedResource)(this, heap, offset, desc, state, clear, iid, out); + let hr = own!(this, ID3D12Device_Vtbl.CreatePlacedResource)( + this, heap, offset, desc, state, clear, iid, out, + ); if let Some((r, p)) = made(hr, out) { // One opened from memory was not seen made. let heap = r.ids.get(heap as usize).unwrap_or_else(|| { @@ -1338,23 +1686,50 @@ unsafe extern "system" fn create_placed( } } -unsafe extern "system" fn create_cbv(this: Ptr, desc: *const D3D12_CONSTANT_BUFFER_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { +unsafe extern "system" fn create_cbv( + this: Ptr, + desc: *const D3D12_CONSTANT_BUFFER_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) { // SAFETY: as above. unsafe { own!(this, ID3D12Device_Vtbl.CreateConstantBufferView)(this, desc, at); if let Some(r) = recorder().filter(|_| !ours()) { - r.set_view(at.ptr, &Slot::new(slot::CBV, NONE, NONE, desc.cast(), size_of::())); + r.set_view( + at.ptr, + &Slot::new( + slot::CBV, + NONE, + NONE, + desc.cast(), + size_of::(), + ), + ); } } } -unsafe extern "system" fn create_srv(this: Ptr, res: Ptr, desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { +unsafe extern "system" fn create_srv( + this: Ptr, + res: Ptr, + desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) { // SAFETY: as above. unsafe { own!(this, ID3D12Device_Vtbl.CreateShaderResourceView)(this, res, desc, at); if let Some(r) = recorder().filter(|_| !ours()) { let id = r.resource(res); - r.set_view(at.ptr, &Slot::new(slot::SRV, id, NONE, desc.cast(), size_of::())); + r.set_view( + at.ptr, + &Slot::new( + slot::SRV, + id, + NONE, + desc.cast(), + size_of::(), + ), + ); } } } @@ -1371,40 +1746,84 @@ unsafe extern "system" fn create_uav( own!(this, ID3D12Device_Vtbl.CreateUnorderedAccessView)(this, res, counter, desc, at); if let Some(r) = recorder().filter(|_| !ours()) { let (id, counter) = (r.resource(res), r.resource(counter)); - r.set_view(at.ptr, &Slot::new(slot::UAV, id, counter, desc.cast(), size_of::())); + r.set_view( + at.ptr, + &Slot::new( + slot::UAV, + id, + counter, + desc.cast(), + size_of::(), + ), + ); } } } -unsafe extern "system" fn create_rtv(this: Ptr, res: Ptr, desc: *const D3D12_RENDER_TARGET_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { +unsafe extern "system" fn create_rtv( + this: Ptr, + res: Ptr, + desc: *const D3D12_RENDER_TARGET_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) { // SAFETY: as above. unsafe { own!(this, ID3D12Device_Vtbl.CreateRenderTargetView)(this, res, desc, at); if let Some(r) = recorder().filter(|_| !ours()) { let id = r.resource(res); - r.set_view(at.ptr, &Slot::new(slot::RTV, id, NONE, desc.cast(), size_of::())); + r.set_view( + at.ptr, + &Slot::new( + slot::RTV, + id, + NONE, + desc.cast(), + size_of::(), + ), + ); } } } -unsafe extern "system" fn create_dsv(this: Ptr, res: Ptr, desc: *const D3D12_DEPTH_STENCIL_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { +unsafe extern "system" fn create_dsv( + this: Ptr, + res: Ptr, + desc: *const D3D12_DEPTH_STENCIL_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) { // SAFETY: as above. unsafe { own!(this, ID3D12Device_Vtbl.CreateDepthStencilView)(this, res, desc, at); if let Some(r) = recorder().filter(|_| !ours()) { let id = r.resource(res); - r.set_view(at.ptr, &Slot::new(slot::DSV, id, NONE, desc.cast(), size_of::())); + r.set_view( + at.ptr, + &Slot::new( + slot::DSV, + id, + NONE, + desc.cast(), + size_of::(), + ), + ); } } } -unsafe extern "system" fn create_sampler(this: Ptr, desc: *const D3D12_SAMPLER_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { +unsafe extern "system" fn create_sampler( + this: Ptr, + desc: *const D3D12_SAMPLER_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) { const _: () = assert!(size_of::() == 52); // SAFETY: as above. unsafe { own!(this, ID3D12Device_Vtbl.CreateSampler)(this, desc, at); if let Some(r) = recorder().filter(|_| !ours()) { - r.set_view(at.ptr, &Slot::new(slot::SAMPLER, NONE, NONE, desc.cast(), 52)); + r.set_view( + at.ptr, + &Slot::new(slot::SAMPLER, NONE, NONE, desc.cast(), 52), + ); } } } @@ -1439,12 +1858,21 @@ unsafe extern "system" fn copy_descriptors( // SAFETY: as above; the arrays have as many entries as the counts say, // and null sizes mean one descriptor each. unsafe { - own!(this, ID3D12Device_Vtbl.CopyDescriptors)(this, n_to, to, to_sizes, n_from, from, from_sizes, kind); + own!(this, ID3D12Device_Vtbl.CopyDescriptors)( + this, n_to, to, to_sizes, n_from, from, from_sizes, kind, + ); let Some(r) = recorder().filter(|_| !ours()) else { return; }; - let step = own!(this, ID3D12Device_Vtbl.GetDescriptorHandleIncrementSize)(this, kind) as usize; - let size = |sizes: *const u32, i: u32| if sizes.is_null() { 1 } else { *sizes.add(i as usize) }; + let step = + own!(this, ID3D12Device_Vtbl.GetDescriptorHandleIncrementSize)(this, kind) as usize; + let size = |sizes: *const u32, i: u32| { + if sizes.is_null() { + 1 + } else { + *sizes.add(i as usize) + } + }; let (mut i, mut j, mut done_to, mut done_from) = (0, 0, 0, 0); while i < n_to && j < n_from { let n = (size(to_sizes, i) - done_to).min(size(from_sizes, j) - done_from); @@ -1528,26 +1956,64 @@ unsafe extern "system" fn list_reset(this: Ptr, allocator: Ptr, pso: Ptr) -> HRE { let mut inner = lock(&state.inner); inner.closed = None; - inner.whole = r.armed.load(Ordering::SeqCst) && state.kind == D3D12_COMMAND_LIST_TYPE_DIRECT.0; + inner.whole = + r.armed.load(Ordering::SeqCst) && state.kind == D3D12_COMMAND_LIST_TYPE_DIRECT.0; begin(&mut inner, r, pso); } hr } } -unsafe extern "system" fn draw(this: Ptr, vertices: u32, instances: u32, first: u32, first_instance: u32) { +unsafe extern "system" fn draw( + this: Ptr, + vertices: u32, + instances: u32, + first: u32, + first_instance: u32, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.DrawInstanced)(this, vertices, instances, first, first_instance); - note(this, |_| Cmd::Draw { vertices, instances, first, first_instance }); + own!(this, ID3D12GraphicsCommandList_Vtbl.DrawInstanced)( + this, + vertices, + instances, + first, + first_instance, + ); + note(this, |_| Cmd::Draw { + vertices, + instances, + first, + first_instance, + }); } } -unsafe extern "system" fn draw_indexed(this: Ptr, indices: u32, instances: u32, first: u32, base: i32, first_instance: u32) { +unsafe extern "system" fn draw_indexed( + this: Ptr, + indices: u32, + instances: u32, + first: u32, + base: i32, + first_instance: u32, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.DrawIndexedInstanced)(this, indices, instances, first, base, first_instance); - note(this, |_| Cmd::DrawIndexed { indices, instances, first, base, first_instance }); + own!(this, ID3D12GraphicsCommandList_Vtbl.DrawIndexedInstanced)( + this, + indices, + instances, + first, + base, + first_instance, + ); + note(this, |_| Cmd::DrawIndexed { + indices, + instances, + first, + base, + first_instance, + }); } } @@ -1567,11 +2033,26 @@ unsafe extern "system" fn dispatch_mesh(this: Ptr, x: u32, y: u32, z: u32) { } } -unsafe extern "system" fn copy_buffer(this: Ptr, dst: Ptr, dst_at: u64, src: Ptr, src_at: u64, len: u64) { +unsafe extern "system" fn copy_buffer( + this: Ptr, + dst: Ptr, + dst_at: u64, + src: Ptr, + src_at: u64, + len: u64, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.CopyBufferRegion)(this, dst, dst_at, src, src_at, len); - note(this, |r| Cmd::CopyBuffer { dst: r.resource(dst), dst_at, src: r.resource(src), src_at, len }); + own!(this, ID3D12GraphicsCommandList_Vtbl.CopyBufferRegion)( + this, dst, dst_at, src, src_at, len, + ); + note(this, |r| Cmd::CopyBuffer { + dst: r.resource(dst), + dst_at, + src: r.resource(src), + src_at, + len, + }); } } @@ -1580,11 +2061,20 @@ unsafe fn location(r: &Recorder, l: &D3D12_TEXTURE_COPY_LOCATION) -> Loc { unsafe { let res = r.resource(std::mem::transmute_copy::<_, Ptr>(&l.pResource)); if l.Type == D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX { - return Loc::Sub { res, sub: l.Anonymous.SubresourceIndex }; + return Loc::Sub { + res, + sub: l.Anonymous.SubresourceIndex, + }; } let p = l.Anonymous.PlacedFootprint; let f = p.Footprint; - Loc::Placed { res, offset: p.Offset, format: f.Format.0, size: [f.Width, f.Height, f.Depth], pitch: f.RowPitch } + Loc::Placed { + res, + offset: p.Offset, + format: f.Format.0, + size: [f.Width, f.Height, f.Depth], + pitch: f.RowPitch, + } } } @@ -1617,7 +2107,9 @@ unsafe extern "system" fn copy_texture( dst: location(r, &*dst), at: [x, y, z], src: location(r, &*src), - part: part.as_ref().map(|b| [b.left, b.top, b.front, b.right, b.bottom, b.back]), + part: part + .as_ref() + .map(|b| [b.left, b.top, b.front, b.right, b.bottom, b.back]), }); } } @@ -1626,15 +2118,33 @@ unsafe extern "system" fn copy_resource(this: Ptr, dst: Ptr, src: Ptr) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.CopyResource)(this, dst, src); - note_change(this, |r| Cmd::CopyResource { dst: r.resource(dst), src: r.resource(src) }); + note_change(this, |r| Cmd::CopyResource { + dst: r.resource(dst), + src: r.resource(src), + }); } } -unsafe extern "system" fn resolve(this: Ptr, dst: Ptr, dst_sub: u32, src: Ptr, src_sub: u32, format: DXGI_FORMAT) { +unsafe extern "system" fn resolve( + this: Ptr, + dst: Ptr, + dst_sub: u32, + src: Ptr, + src_sub: u32, + format: DXGI_FORMAT, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.ResolveSubresource)(this, dst, dst_sub, src, src_sub, format); - note(this, |r| Cmd::Resolve { dst: r.resource(dst), dst_sub, src: r.resource(src), src_sub, format: format.0 }); + own!(this, ID3D12GraphicsCommandList_Vtbl.ResolveSubresource)( + this, dst, dst_sub, src, src_sub, format, + ); + note(this, |r| Cmd::Resolve { + dst: r.resource(dst), + dst_sub, + src: r.resource(src), + src_sub, + format: format.0, + }); } } @@ -1653,7 +2163,10 @@ unsafe extern "system" fn resolve_region( ) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList1_Vtbl.ResolveSubresourceRegion)(this, dst, dst_sub, x, y, src, src_sub, part, format, mode); + own!( + this, + ID3D12GraphicsCommandList1_Vtbl.ResolveSubresourceRegion + )(this, dst, dst_sub, x, y, src, src_sub, part, format, mode); note(this, |r| Cmd::ResolveRegion { dst: r.resource(dst), dst_sub, @@ -1676,7 +2189,10 @@ unsafe fn rects(n: u32, all: *const RECT) -> Vec<[i32; 4]> { return Vec::new(); } // SAFETY: `n` rectangles. - unsafe { std::slice::from_raw_parts(all, n as usize) }.iter().map(rect).collect() + unsafe { std::slice::from_raw_parts(all, n as usize) } + .iter() + .map(rect) + .collect() } unsafe extern "system" fn topology(this: Ptr, kind: D3D_PRIMITIVE_TOPOLOGY) { @@ -1691,7 +2207,11 @@ unsafe extern "system" fn viewports(this: Ptr, n: u32, all: *const D3D12_VIEWPOR // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.RSSetViewports)(this, n, all); - note(this, |_| Cmd::Viewports { all: (0..n as usize).map(|i| all.add(i).cast::<[f32; 6]>().read()).collect() }); + note(this, |_| Cmd::Viewports { + all: (0..n as usize) + .map(|i| all.add(i).cast::<[f32; 6]>().read()) + .collect(), + }); } } @@ -1707,7 +2227,9 @@ unsafe extern "system" fn blend_factor(this: Ptr, factor: *const f32) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.OMSetBlendFactor)(this, factor); - note(this, |_| Cmd::BlendFactor { factor: factor.cast::<[f32; 4]>().as_ref().copied() }); + note(this, |_| Cmd::BlendFactor { + factor: factor.cast::<[f32; 4]>().as_ref().copied(), + }); } } @@ -1731,7 +2253,9 @@ unsafe extern "system" fn set_pipeline(this: Ptr, pso: Ptr) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.SetPipelineState)(this, pso); - note(this, |r| Cmd::Pipeline { pso: r.object(pso, "a pipeline") }); + note(this, |r| Cmd::Pipeline { + pso: r.object(pso, "a pipeline"), + }); } } @@ -1747,13 +2271,18 @@ unsafe extern "system" fn barrier(this: Ptr, n: u32, all: *const D3D12_RESOURCE_ let a = &b.Anonymous.Aliasing; Barrier::Alias { flags: b.Flags.0, - before: r.resource(std::mem::transmute_copy::<_, Ptr>(&a.pResourceBefore)), - after: r.resource(std::mem::transmute_copy::<_, Ptr>(&a.pResourceAfter)), + before: r + .resource(std::mem::transmute_copy::<_, Ptr>(&a.pResourceBefore)), + after: r + .resource(std::mem::transmute_copy::<_, Ptr>(&a.pResourceAfter)), } } - D3D12_RESOURCE_BARRIER_TYPE_UAV => { - Barrier::Uav { flags: b.Flags.0, res: r.resource(std::mem::transmute_copy::<_, Ptr>(&b.Anonymous.UAV.pResource)) } - } + D3D12_RESOURCE_BARRIER_TYPE_UAV => Barrier::Uav { + flags: b.Flags.0, + res: r.resource(std::mem::transmute_copy::<_, Ptr>( + &b.Anonymous.UAV.pResource, + )), + }, _ => { let t = &b.Anonymous.Transition; Barrier::Transition { @@ -1775,7 +2304,11 @@ unsafe extern "system" fn set_heaps(this: Ptr, n: u32, all: *const Ptr) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.SetDescriptorHeaps)(this, n, all); - note(this, |r| Cmd::Heaps { heaps: (0..n as usize).map(|i| r.object(*all.add(i), "a descriptor heap")).collect() }); + note(this, |r| Cmd::Heaps { + heaps: (0..n as usize) + .map(|i| r.object(*all.add(i), "a descriptor heap")) + .collect(), + }); } } @@ -1783,15 +2316,24 @@ unsafe extern "system" fn root_compute(this: Ptr, root: Ptr) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRootSignature)(this, root); - note(this, |r| Cmd::RootSignature { graphics: false, root: r.object(root, "a root signature") }); + note(this, |r| Cmd::RootSignature { + graphics: false, + root: r.object(root, "a root signature"), + }); } } unsafe extern "system" fn root_graphics(this: Ptr, root: Ptr) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootSignature)(this, root); - note(this, |r| Cmd::RootSignature { graphics: true, root: r.object(root, "a root signature") }); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootSignature + )(this, root); + note(this, |r| Cmd::RootSignature { + graphics: true, + root: r.object(root, "a root signature"), + }); } } @@ -1803,13 +2345,21 @@ fn table(r: &Recorder, graphics: bool, param: u32, at: u64) -> Cmd { if heap == NONE { r.problem("a descriptor table in no heap seen made"); } - Cmd::Table { graphics, param, heap, slot } + Cmd::Table { + graphics, + param, + heap, + slot, + } } unsafe extern "system" fn table_compute(this: Ptr, param: u32, at: D3D12_GPU_DESCRIPTOR_HANDLE) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRootDescriptorTable)(this, param, at); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetComputeRootDescriptorTable + )(this, param, at); note(this, |r| table(r, false, param, at.ptr)); } } @@ -1817,7 +2367,10 @@ unsafe extern "system" fn table_compute(this: Ptr, param: u32, at: D3D12_GPU_DES unsafe extern "system" fn table_graphics(this: Ptr, param: u32, at: D3D12_GPU_DESCRIPTOR_HANDLE) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootDescriptorTable)(this, param, at); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootDescriptorTable + )(this, param, at); note(this, |r| table(r, true, param, at.ptr)); } } @@ -1825,37 +2378,83 @@ unsafe extern "system" fn table_graphics(this: Ptr, param: u32, at: D3D12_GPU_DE unsafe extern "system" fn constant_compute(this: Ptr, param: u32, value: u32, offset: u32) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstant)(this, param, value, offset); - note(this, |_| Cmd::Constants { graphics: false, param, offset, values: vec![value] }); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstant + )(this, param, value, offset); + note(this, |_| Cmd::Constants { + graphics: false, + param, + offset, + values: vec![value], + }); } } unsafe extern "system" fn constant_graphics(this: Ptr, param: u32, value: u32, offset: u32) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstant)(this, param, value, offset); - note(this, |_| Cmd::Constants { graphics: true, param, offset, values: vec![value] }); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstant + )(this, param, value, offset); + note(this, |_| Cmd::Constants { + graphics: true, + param, + offset, + values: vec![value], + }); } } unsafe fn values(n: u32, data: *const c_void) -> Vec { // SAFETY: `n` values, of any alignment. - (0..n as usize).map(|i| unsafe { data.cast::().add(i).read_unaligned() }).collect() + (0..n as usize) + .map(|i| unsafe { data.cast::().add(i).read_unaligned() }) + .collect() } -unsafe extern "system" fn constants_compute(this: Ptr, param: u32, n: u32, data: *const c_void, offset: u32) { +unsafe extern "system" fn constants_compute( + this: Ptr, + param: u32, + n: u32, + data: *const c_void, + offset: u32, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstants)(this, param, n, data, offset); - note(this, |_| Cmd::Constants { graphics: false, param, offset, values: values(n, data) }); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstants + )(this, param, n, data, offset); + note(this, |_| Cmd::Constants { + graphics: false, + param, + offset, + values: values(n, data), + }); } } -unsafe extern "system" fn constants_graphics(this: Ptr, param: u32, n: u32, data: *const c_void, offset: u32) { +unsafe extern "system" fn constants_graphics( + this: Ptr, + param: u32, + n: u32, + data: *const c_void, + offset: u32, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstants)(this, param, n, data, offset); - note(this, |_| Cmd::Constants { graphics: true, param, offset, values: values(n, data) }); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstants + )(this, param, n, data, offset); + note(this, |_| Cmd::Constants { + graphics: true, + param, + offset, + values: values(n, data), + }); } } @@ -1892,11 +2491,20 @@ unsafe extern "system" fn index_buffer(this: Ptr, view: *const D3D12_INDEX_BUFFE // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.IASetIndexBuffer)(this, view); - note(this, |r| Cmd::IndexBuffer { view: view.as_ref().map(|v| (address(r, v.BufferLocation), v.SizeInBytes, v.Format.0)) }); + note(this, |r| Cmd::IndexBuffer { + view: view + .as_ref() + .map(|v| (address(r, v.BufferLocation), v.SizeInBytes, v.Format.0)), + }); } } -unsafe extern "system" fn vertex_buffers(this: Ptr, start: u32, n: u32, views: *const D3D12_VERTEX_BUFFER_VIEW) { +unsafe extern "system" fn vertex_buffers( + this: Ptr, + start: u32, + n: u32, + views: *const D3D12_VERTEX_BUFFER_VIEW, +) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.IASetVertexBuffers)(this, start, n, views); @@ -1905,7 +2513,9 @@ unsafe extern "system" fn vertex_buffers(this: Ptr, start: u32, n: u32, views: * count: n, views: (!views.is_null()).then(|| { let all = std::slice::from_raw_parts(views, n as usize); - all.iter().map(|v| (address(r, v.BufferLocation), v.SizeInBytes, v.StrideInBytes)).collect() + all.iter() + .map(|v| (address(r, v.BufferLocation), v.SizeInBytes, v.StrideInBytes)) + .collect() }), }); } @@ -1920,7 +2530,9 @@ unsafe extern "system" fn targets( ) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.OMSetRenderTargets)(this, n, colors, range, depth); + own!(this, ID3D12GraphicsCommandList_Vtbl.OMSetRenderTargets)( + this, n, colors, range, depth, + ); note(this, |r| { let colors = (0..n as usize) .map(|i| { @@ -1928,10 +2540,14 @@ unsafe extern "system" fn targets( return r.view((*colors.add(i)).ptr); } let all = read(&r.descriptors); - all.cpu((*colors).ptr).map_or(Slot::EMPTY, |(h, first)| h.get(first + i as u32)) + all.cpu((*colors).ptr) + .map_or(Slot::EMPTY, |(h, first)| h.get(first + i as u32)) }) .collect(); - Cmd::Targets { colors, depth: depth.as_ref().map(|d| r.view(d.ptr)) } + Cmd::Targets { + colors, + depth: depth.as_ref().map(|d| r.view(d.ptr)), + } }); } } @@ -1948,16 +2564,34 @@ unsafe extern "system" fn clear_depth( ) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.ClearDepthStencilView)(this, view, flags, depth, stencil, n, all); - note(this, |r| Cmd::ClearDepth { view: r.view(view.ptr), flags: flags.0, depth, stencil, rects: rects(n, all) }); + own!(this, ID3D12GraphicsCommandList_Vtbl.ClearDepthStencilView)( + this, view, flags, depth, stencil, n, all, + ); + note(this, |r| Cmd::ClearDepth { + view: r.view(view.ptr), + flags: flags.0, + depth, + stencil, + rects: rects(n, all), + }); } } -unsafe extern "system" fn clear_target(this: Ptr, view: D3D12_CPU_DESCRIPTOR_HANDLE, color: *const f32, n: u32, all: *const RECT) { +unsafe extern "system" fn clear_target( + this: Ptr, + view: D3D12_CPU_DESCRIPTOR_HANDLE, + color: *const f32, + n: u32, + all: *const RECT, +) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.ClearRenderTargetView)(this, view, color, n, all); - note(this, |r| Cmd::ClearTarget { view: r.view(view.ptr), color: color.cast::<[f32; 4]>().read(), rects: rects(n, all) }); + note(this, |r| Cmd::ClearTarget { + view: r.view(view.ptr), + color: color.cast::<[f32; 4]>().read(), + rects: rects(n, all), + }); } } @@ -1967,8 +2601,12 @@ unsafe extern "system" fn discard(this: Ptr, res: Ptr, region: *const D3D12_DISC own!(this, ID3D12GraphicsCommandList_Vtbl.DiscardResource)(this, res, region); note(this, |r| Cmd::Discard { res: r.resource(res), - rects: region.as_ref().map_or(Vec::new(), |d| rects(d.NumRects, d.pRects)), - subs: region.as_ref().map(|d| [d.FirstSubresource, d.NumSubresources]), + rects: region + .as_ref() + .map_or(Vec::new(), |d| rects(d.NumRects, d.pRects)), + subs: region + .as_ref() + .map(|d| [d.FirstSubresource, d.NumSubresources]), }); } } @@ -1977,7 +2615,11 @@ unsafe extern "system" fn begin_query(this: Ptr, heap: Ptr, kind: D3D12_QUERY_TY // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.BeginQuery)(this, heap, kind, index); - note(this, |r| Cmd::BeginQuery { heap: r.object(heap, "a query heap"), kind: kind.0, index }); + note(this, |r| Cmd::BeginQuery { + heap: r.object(heap, "a query heap"), + kind: kind.0, + index, + }); } } @@ -1985,22 +2627,53 @@ unsafe extern "system" fn end_query(this: Ptr, heap: Ptr, kind: D3D12_QUERY_TYPE // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.EndQuery)(this, heap, kind, index); - note(this, |r| Cmd::EndQuery { heap: r.object(heap, "a query heap"), kind: kind.0, index }); + note(this, |r| Cmd::EndQuery { + heap: r.object(heap, "a query heap"), + kind: kind.0, + index, + }); } } -unsafe extern "system" fn resolve_query(this: Ptr, heap: Ptr, kind: D3D12_QUERY_TYPE, first: u32, count: u32, dst: Ptr, at: u64) { +unsafe extern "system" fn resolve_query( + this: Ptr, + heap: Ptr, + kind: D3D12_QUERY_TYPE, + first: u32, + count: u32, + dst: Ptr, + at: u64, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.ResolveQueryData)(this, heap, kind, first, count, dst, at); - note(this, |r| Cmd::ResolveQuery { heap: r.object(heap, "a query heap"), kind: kind.0, first, count, dst: r.resource(dst), at }); + own!(this, ID3D12GraphicsCommandList_Vtbl.ResolveQueryData)( + this, heap, kind, first, count, dst, at, + ); + note(this, |r| Cmd::ResolveQuery { + heap: r.object(heap, "a query heap"), + kind: kind.0, + first, + count, + dst: r.resource(dst), + at, + }); } } -unsafe extern "system" fn indirect(this: Ptr, signature: Ptr, most: u32, args: Ptr, at: u64, count: Ptr, count_at: u64) { +unsafe extern "system" fn indirect( + this: Ptr, + signature: Ptr, + most: u32, + args: Ptr, + at: u64, + count: Ptr, + count_at: u64, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.ExecuteIndirect)(this, signature, most, args, at, count, count_at); + own!(this, ID3D12GraphicsCommandList_Vtbl.ExecuteIndirect)( + this, signature, most, args, at, count, count_at, + ); note(this, |r| Cmd::Indirect { signature: r.object(signature, "a command signature"), most, @@ -2025,7 +2698,11 @@ unsafe extern "system" fn write_immediate( all: (0..n as usize) .map(|i| { let p = all.add(i).read(); - let mode = if modes.is_null() { 0 } else { modes.add(i).read().0 }; + let mode = if modes.is_null() { + 0 + } else { + modes.add(i).read().0 + }; (address(r, p.Dest), p.Value, mode) }) .collect(), @@ -2075,7 +2752,11 @@ mod tests { all.remove(2); assert_eq!(at(&all, 0x2000), None); let h = heap(4, 0, 0, 2); - let s = Slot { kind: slot::SRV, res: 5, ..Slot::EMPTY }; + let s = Slot { + kind: slot::SRV, + res: 5, + ..Slot::EMPTY + }; h.set(1, &s); h.set(2, &s); assert_eq!(h.all(), [Slot::EMPTY, s]); diff --git a/crates/victory-gpu/src/replay/snap.rs b/crates/victory-gpu/src/replay/snap.rs index 02b8a4f..d9832d2 100644 --- a/crates/victory-gpu/src/replay/snap.rs +++ b/crates/victory-gpu/src/replay/snap.rs @@ -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; @@ -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>); - let closed: Vec> = lists.iter().map(|&p| r.list(p).and_then(|l| l.closed())).collect(); + let closed: Vec> = 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| 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>>> = closed.iter().map(|c| c.as_ref().and_then(|c| c.0.clone())).collect(); + let commands: Vec>>> = 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(&mut self, what: &'static str, f: impl FnOnce(&mut Self) -> Result) -> Result { + fn timed( + &mut self, + what: &'static str, + f: impl FnOnce(&mut Self) -> Result, + ) -> Result { 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 = 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 = 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> = 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 = self.buffers.iter_mut().map(|b| Kept(b.kept.as_mut_ptr())).collect(); + let kept: Vec = self + .buffers + .iter_mut() + .map(|b| Kept(b.kept.as_mut_ptr())) + .collect(); let next = AtomicUsize::new(0); let out: std::sync::Mutex> = std::sync::Mutex::default(); let failed: std::sync::Mutex> = 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>>]) -> Result<(), Fault> { + fn submit( + &mut self, + r: &Recorder, + _queue: &ID3D12CommandQueue, + lists: &[Option>>], + ) -> Result<(), Fault> { let first = !self.started; if first { self.start(r)?; @@ -615,7 +794,8 @@ impl Capture { let heaps: Vec> = 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 = { let all = lock(&r.heaps); - let used: HashSet = - resources.iter().filter_map(|res| if let Place::Placed { heap, .. } = res.place { Some(heap) } else { None }).collect(); + let used: HashSet = 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 = { 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 = from.iter().map(|&s| if s == COMMON || s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }).collect(); + let to: Vec = 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()); } diff --git a/crates/victory-gpu/src/replay/states.rs b/crates/victory-gpu/src/replay/states.rs index c159423..b7379f4 100644 --- a/crates/victory-gpu/src/replay/states.rs +++ b/crates/victory-gpu/src/replay/states.rs @@ -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> { 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) { - 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(©(2)); s.change(©(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); diff --git a/crates/victory-gpu/src/replay/wire.rs b/crates/victory-gpu/src/replay/wire.rs index b82667f..a5623c2 100644 --- a/crates/victory-gpu/src/replay/wire.rs +++ b/crates/victory-gpu/src/replay/wire.rs @@ -94,7 +94,11 @@ impl Wire for Option { } } fn get(from: &mut Dec) -> Result { - 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 { - 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::>(), (1..=LAST_CMD).collect::>()); - 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::>(), + (1..=LAST_CMD).collect::>() + ); + 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(); diff --git a/crates/victory-gpu/tests/replay.rs b/crates/victory-gpu/tests/replay.rs index 3d5eb5a..9f80bc9 100644 --- a/crates/victory-gpu/tests/replay.rs +++ b/crates/victory-gpu/tests/replay.rs @@ -14,7 +14,9 @@ use victory_gpu::replay::play::{self, Buffers, Options, Player}; use victory_gpu::replay::record::{self, At, Settings}; use windows::Win32::Foundation::{HANDLE, HWND, RECT}; use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; -use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, ID3DBlob}; +use windows::Win32::Graphics::Direct3D::{ + D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, ID3DBlob, +}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; use windows::Win32::Graphics::Dxgi::*; @@ -54,6 +56,172 @@ V vs(float2 at : POSITION, float3 color : COLOR1) { V v; v.at = float4(at, 0.4, float4 ps(V v) : SV_Target { return float4(v.color, 1); } "#; +/// A quad from a mesh shader, its texture picked from the heap by index. +const MESH: &str = r#" +#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), RootConstants(num32BitConstants=5, b0)" +cbuffer C : register(b0) { float4 place; uint pick; }; +struct V { float4 at : SV_Position; float2 uv : UV; }; +[RootSignature(RS)] +[numthreads(1, 1, 1)] +[outputtopology("triangle")] +void ms(out vertices V v[4], out indices uint3 t[2]) { + SetMeshOutputCounts(4, 2); + for (uint i = 0; i < 4; i++) { + float2 c = float2(i & 1, i >> 1); + v[i].at = float4(place.xy + c * place.zw, 0.3, 1); + v[i].uv = c; + } + t[0] = uint3(0, 1, 2); + t[1] = uint3(2, 1, 3); +} +[RootSignature(RS)] +float4 ps(V v) : SV_Target { + Texture2D t = ResourceDescriptorHeap[pick]; + return t.Load(int3(v.uv * 16, 0)) * 0.5 + float4(v.uv, 0, 0) * 0.5; +} +"#; + +/// Compiles with the Windows SDK's dxc, if there is one. +fn dxc(source: &str, entry: &str, target: &str) -> Option> { + let kits = std::fs::read_dir("C:/Program Files (x86)/Windows Kits/10/bin").ok()?; + let exe = kits + .flatten() + .map(|e| e.path().join("x64/dxc.exe")) + .filter(|p| p.exists()) + .max()?; + let dir = tempfile::tempdir().ok()?; + let (from, to) = (dir.path().join("a.hlsl"), dir.path().join("a.dxil")); + std::fs::write(&from, source).ok()?; + let out = std::process::Command::new(exe) + .args(["-T", target, "-E", entry, "-Fo"]) + .arg(&to) + .arg(&from) + .output() + .ok()?; + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + std::fs::read(to).ok() +} + +/// The mesh pipeline, from a stream, by way of a pipeline library; and the +/// signature of its indirect draws. `None` without dxc or mesh shaders. +fn mesh(device: &ID3D12Device, blend: D3D12_BLEND_DESC) -> Option<(Made, ID3D12CommandSignature)> { + #[repr(C, align(8))] + struct Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); + #[repr(C)] + struct Stream { + root: Sub<*mut std::ffi::c_void>, + ms: Sub, + ps: Sub, + blend: Sub, + mask: Sub, + raster: Sub, + depth: Sub, + targets: Sub, + dsv: Sub, + samples: Sub, + topology: Sub, + } + let (ms, ps) = (dxc(MESH, "ms", "ms_6_6")?, dxc(MESH, "ps", "ps_6_6")?); + // SAFETY: plain queries and creation; the stream holds whole subobjects. + unsafe { + let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + let size = size_of::() as u32; + device + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, (&raw mut o).cast(), size) + .ok()?; + if o.MeshShaderTier == D3D12_MESH_SHADER_TIER_NOT_SUPPORTED { + return None; + } + let root: ID3D12RootSignature = device.CreateRootSignature(0, &ms).unwrap(); + let mut formats = D3D12_RT_FORMAT_ARRAY { + NumRenderTargets: 1, + ..Default::default() + }; + formats.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let mut stream = Stream { + root: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, + root.as_raw(), + ), + ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, code(&ms)), + ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, code(&ps)), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, blend), + mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, u32::MAX), + raster: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, + D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + ..Default::default() + }, + ), + depth: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, + D3D12_DEPTH_STENCIL_DESC::default(), + ), + targets: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, + formats, + ), + dsv: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, + DXGI_FORMAT_D32_FLOAT, + ), + samples: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, + DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ), + topology: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + ), + }; + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: size_of::(), + pPipelineStateSubobjectStream: (&raw mut stream).cast(), + }; + let library: ID3D12PipelineLibrary1 = device + .cast::() + .unwrap() + .CreatePipelineLibrary::(&[]) + .unwrap() + .cast() + .unwrap(); + { + let made: ID3D12PipelineState = device + .cast::() + .unwrap() + .CreatePipelineState(&desc) + .unwrap(); + library.StorePipeline(w!("mesh"), &made).unwrap(); + } + let pso: ID3D12PipelineState = library.LoadPipeline(w!("mesh"), &desc).unwrap(); + record::name(&pso, "a mesh pipeline"); + let argument = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH, + ..Default::default() + }; + let mut signature: Option = None; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: 12, + NumArgumentDescs: 1, + pArgumentDescs: &argument, + NodeMask: 0, + }; + device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut signature) + .unwrap(); + Some((Made { root, pso }, signature.unwrap())) + } +} + /// Writes the arguments of indirect draws (two records: six vertices, and /// one far too many that the clamp cuts to none). const ARGS: &str = r#" @@ -114,19 +282,36 @@ fn compile(source: &str, entry: PCSTR, target: PCSTR) -> Vec { // SAFETY: the source and names live through the call; the blobs' own // bytes. unsafe { - let r = D3DCompile(source.as_ptr().cast(), source.len(), None, None, None, entry, target, 1 << 20, 0, &mut code, Some(&mut errors)); + let r = D3DCompile( + source.as_ptr().cast(), + source.len(), + None, + None, + None, + entry, + target, + 1 << 20, + 0, + &mut code, + Some(&mut errors), + ); if r.is_err() { let e = errors.unwrap(); - let text = std::slice::from_raw_parts(e.GetBufferPointer().cast::(), e.GetBufferSize()); + let text = + std::slice::from_raw_parts(e.GetBufferPointer().cast::(), e.GetBufferSize()); panic!("{}", String::from_utf8_lossy(text)); } let code = code.unwrap(); - std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()).to_vec() + std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()) + .to_vec() } } fn code(bytes: &[u8]) -> D3D12_SHADER_BYTECODE { - D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() } + D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + } } fn compute(device: &ID3D12Device, source: &str) -> Made { @@ -152,14 +337,21 @@ fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { 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() } } -fn texture_desc(size: u32, format: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { +fn texture_desc( + size: u32, + format: DXGI_FORMAT, + flags: D3D12_RESOURCE_FLAGS, +) -> D3D12_RESOURCE_DESC { D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: u64::from(size), @@ -167,7 +359,10 @@ fn texture_desc(size: u32, format: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS) -> DepthOrArraySize: 1, MipLevels: 1, Format: format, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Flags: flags, ..Default::default() } @@ -182,11 +377,25 @@ enum In { Shared, } -fn committed(device: &ID3D12Device, place: In, desc: &D3D12_RESOURCE_DESC, state: D3D12_RESOURCE_STATES) -> (ID3D12Resource, *mut u8) { +fn committed( + device: &ID3D12Device, + place: In, + desc: &D3D12_RESOURCE_DESC, + state: D3D12_RESOURCE_STATES, +) -> (ID3D12Resource, *mut u8) { let heap = match place { - In::Card => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, - In::Upload => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, - In::Back => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + In::Card => D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + In::Upload => D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_UPLOAD, + ..Default::default() + }, + In::Back => D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }, In::Shared => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, @@ -198,7 +407,9 @@ fn committed(device: &ID3D12Device, place: In, desc: &D3D12_RESOURCE_DESC, state let mut data = std::ptr::null_mut(); // SAFETY: plain creation and mapping. unsafe { - device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, desc, state, None, &mut made).unwrap(); + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, desc, state, None, &mut made) + .unwrap(); let made = made.unwrap(); if place != In::Card { made.Map(0, None, Some(&mut data)).unwrap(); @@ -207,7 +418,11 @@ fn committed(device: &ID3D12Device, place: In, desc: &D3D12_RESOURCE_DESC, state } } -fn moved(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { +fn moved( + res: &ID3D12Resource, + before: D3D12_RESOURCE_STATES, + after: D3D12_RESOURCE_STATES, +) -> D3D12_RESOURCE_BARRIER { D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Anonymous: D3D12_RESOURCE_BARRIER_0 { @@ -227,7 +442,9 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER { D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Anonymous: D3D12_RESOURCE_BARRIER_0 { - UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: ManuallyDrop::new(None) }), + UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: ManuallyDrop::new(None), + }), }, ..Default::default() } @@ -283,10 +500,15 @@ struct Scene { lists: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)>, draw: Made, plain: Made, + mesh: Option<(Made, ID3D12CommandSignature)>, vertices: (ID3D12Resource, *mut u8), samplers: ID3D12DescriptorHeap, still: Vec<(&'static str, ID3D12Resource, D3D12_RESOURCE_STATES)>, - copies: (ID3D12CommandQueue, ID3D12CommandAllocator, ID3D12GraphicsCommandList), + copies: ( + ID3D12CommandQueue, + ID3D12CommandAllocator, + ID3D12GraphicsCommandList, + ), args: Made, clamp: Made, add: Made, @@ -318,19 +540,28 @@ impl Scene { // SAFETY: plain creation throughout. unsafe { let queue: ID3D12CommandQueue = device - .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) .unwrap(); let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); let lists = (0..3) .map(|_| { - let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); - let list: ID3D12GraphicsCommandList = - device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + let allocator: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .unwrap(); + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .unwrap(); list.Close().unwrap(); (allocator, list) }) .collect(); - let (vs, ps) = (compile(DRAW, s!("vs"), s!("vs_5_1")), compile(DRAW, s!("ps"), s!("ps_5_1"))); + let (vs, ps) = ( + compile(DRAW, s!("vs"), s!("vs_5_1")), + compile(DRAW, s!("ps"), s!("ps_5_1")), + ); let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap(); let mut blend = D3D12_BLEND_DESC::default(); blend.RenderTarget[0].RenderTargetWriteMask = 15; @@ -355,14 +586,20 @@ impl Scene { PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, NumRenderTargets: 1, DSVFormat: DXGI_FORMAT_D32_FLOAT, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, ..Default::default() }; desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap(); record::name(&pso, "a drawing pipeline"); let draw = Made { root, pso }; - let (vs, ps) = (compile(PLAIN, s!("vs"), s!("vs_5_1")), compile(PLAIN, s!("ps"), s!("ps_5_1"))); + let (vs, ps) = ( + compile(PLAIN, s!("vs"), s!("vs_5_1")), + compile(PLAIN, s!("ps"), s!("ps_5_1")), + ); let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap(); let element = |name, index, format, at| D3D12_INPUT_ELEMENT_DESC { SemanticName: name, @@ -379,19 +616,43 @@ impl Scene { ]; desc.pRootSignature = std::mem::transmute_copy(&root); (desc.VS, desc.PS) = (code(&vs), code(&ps)); - desc.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: elements.as_ptr(), NumElements: 2 }; + desc.InputLayout = D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: elements.as_ptr(), + NumElements: 2, + }; let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap(); let plain = Made { root, pso }; let clamp = compute(device, CLAMP); record::name(&clamp.pso, play::CLAMP); - let argument = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, ..Default::default() }; - let mut signature: Option = None; - let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 16, NumArgumentDescs: 1, pArgumentDescs: &argument, NodeMask: 0 }; - device.CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut signature).unwrap(); - let heap = |kind, count, flags| -> ID3D12DescriptorHeap { - device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: count, Flags: flags, NodeMask: 0 }).unwrap() + let argument = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, + ..Default::default() }; - let samplers = heap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE); + let mut signature: Option = None; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: 16, + NumArgumentDescs: 1, + pArgumentDescs: &argument, + NodeMask: 0, + }; + device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut signature) + .unwrap(); + let heap = |kind, count, flags| -> ID3D12DescriptorHeap { + device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: count, + Flags: flags, + NodeMask: 0, + }) + .unwrap() + }; + let samplers = heap( + D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, + 4, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ); let sampler = D3D12_SAMPLER_DESC { Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR, AddressU: D3D12_TEXTURE_ADDRESS_MODE_WRAP, @@ -401,25 +662,61 @@ impl Scene { ..Default::default() }; let mut at = samplers.GetCPUDescriptorHandleForHeapStart(); - at.ptr += 2 * device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) as usize; + at.ptr += 2 * device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) + as usize; device.CreateSampler(&sampler, at); - let views = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 5000, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE); - let rtvs = heap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE); - let dsvs = heap(D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE); + let views = heap( + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + 5000, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ); + let rtvs = heap( + D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + 1, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + ); + let dsvs = heap( + D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + 1, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + ); let rgba = DXGI_FORMAT_R8G8B8A8_UNORM; - let (target, _) = committed(device, In::Card, &texture_desc(SIZE, rgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), FROM); + let (target, _) = committed( + device, + In::Card, + &texture_desc(SIZE, rgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), + FROM, + ); let (depth, _) = committed( device, In::Card, - &texture_desc(SIZE, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL), + &texture_desc( + SIZE, + DXGI_FORMAT_D32_FLOAT, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ), D3D12_RESOURCE_STATE_DEPTH_WRITE, ); - let (fixed, _) = committed(device, In::Card, &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_NONE), TO); - let (image, _) = committed(device, In::Card, &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), UAV); + let (fixed, _) = committed( + device, + In::Card, + &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_NONE), + TO, + ); + let (image, _) = committed( + device, + In::Card, + &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + UAV, + ); let mut memory: Option = None; let desc = D3D12_HEAP_DESC { SizeInBytes: 4 << 20, - Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Properties: D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, Alignment: 0, Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, }; @@ -428,7 +725,9 @@ impl Scene { let placed = || { let mut made: Option = None; let d = texture_desc(16, rgba, D3D12_RESOURCE_FLAG_NONE); - device.CreatePlacedResource(&memory, 65536, &d, TO, None, &mut made).unwrap(); + device + .CreatePlacedResource(&memory, 65536, &d, TO, None, &mut made) + .unwrap(); made.unwrap() }; // Two textures in one place. @@ -449,7 +748,12 @@ impl Scene { &buffer_desc(65536, D3D12_RESOURCE_FLAG_NONE), D3D12_RESOURCE_STATE_GENERIC_READ, ); - let back = committed(device, In::Back, &buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE), TO); + let back = committed( + device, + In::Back, + &buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE), + TO, + ); let vertices = committed( device, In::Upload, @@ -468,29 +772,61 @@ impl Scene { MipLevels: 3, ..texture_desc(16, DXGI_FORMAT_R16_FLOAT, D3D12_RESOURCE_FLAG_NONE) }; - let stencil = texture_desc(32, DXGI_FORMAT_R32G8X24_TYPELESS, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); - let (write, read) = (D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); - [("blocks", blocks, TO, READ), ("volume", volume, TO, read), ("stencil", stencil, write, write)].map(|(name, d, made_in, ends)| { + let stencil = texture_desc( + 32, + DXGI_FORMAT_R32G8X24_TYPELESS, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ); + let (write, read) = ( + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + ); + [ + ("blocks", blocks, TO, READ), + ("volume", volume, TO, read), + ("stencil", stencil, write, write), + ] + .map(|(name, d, made_in, ends)| { let (t, _) = committed(device, In::Card, &d, made_in); record::name(&t, name); (name, t, ends) }) }; - let copies: (ID3D12CommandQueue, ID3D12CommandAllocator, ID3D12GraphicsCommandList) = { + let copies: ( + ID3D12CommandQueue, + ID3D12CommandAllocator, + ID3D12GraphicsCommandList, + ) = { let queue = device - .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COPY, ..Default::default() }) + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_COPY, + ..Default::default() + }) + .unwrap(); + let allocator: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY) + .unwrap(); + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None) .unwrap(); - let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY).unwrap(); - let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None).unwrap(); list.Close().unwrap(); (queue, allocator, list) }; - for (r, n) in [(&sum, "sum"), (&image, "image"), (&target, "target"), (&shared.0, "shared"), (&one, "one"), (&other, "other")] { + for (r, n) in [ + (&sum, "sum"), + (&image, "image"), + (&target, "target"), + (&shared.0, "shared"), + (&one, "one"), + (&other, "other"), + ] { record::name(r, n); } device.CreateRenderTargetView(&target, None, rtvs.GetCPUDescriptorHandleForHeapStart()); device.CreateDepthStencilView(&depth, None, dsvs.GetCPUDescriptorHandleForHeapStart()); - let step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let step = device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + as usize; let swap = window.then(|| swap_chain(&queue)); let scene = Scene { device: device.clone(), @@ -501,6 +837,7 @@ impl Scene { lists, draw, plain, + mesh: mesh(device, blend), vertices, samplers, still: still.to_vec(), @@ -531,24 +868,45 @@ impl Scene { swap, }; // Null views everywhere, by copies of a slot made elsewhere. - let block = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16, D3D12_DESCRIPTOR_HEAP_FLAG_NONE); + let block = heap( + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + 16, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + ); let null = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: rgba, ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, - Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() } }, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MipLevels: 1, + ..Default::default() + }, + }, }; let from = block.GetCPUDescriptorHandleForHeapStart(); for i in 0..16 { - let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from.ptr + i * step }; + let at = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: from.ptr + i * step, + }; device.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&null), at); } for i in (0..4992).step_by(16) { - device.CopyDescriptorsSimple(16, scene.cpu(i), from, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + device.CopyDescriptorsSimple( + 16, + scene.cpu(i), + from, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + ); } // The rest with the other copying method, in unlike pieces. let to = [scene.cpu(4992), scene.cpu(4994)]; - let sources = [from, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from.ptr + 4 * step }]; + let sources = [ + from, + D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: from.ptr + 4 * step, + }, + ]; device.CopyDescriptors( 2, to.as_ptr(), @@ -560,7 +918,12 @@ impl Scene { ); scene.show(4001, &scene.other); scene.show(4002, &scene.one); - device.CreateUnorderedAccessView(&scene.image, None::<&ID3D12Resource>, None, scene.cpu(7)); + device.CreateUnorderedAccessView( + &scene.image, + None::<&ID3D12Resource>, + None, + scene.cpu(7), + ); scene } } @@ -568,13 +931,18 @@ impl Scene { fn cpu(&self, i: usize) -> D3D12_CPU_DESCRIPTOR_HANDLE { // SAFETY: a slot of the heap. let start = unsafe { self.views.GetCPUDescriptorHandleForHeapStart() }; - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + i * self.step } + D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start.ptr + i * self.step, + } } /// Slot `i` shows `texture`. fn show(&self, i: usize, texture: &ID3D12Resource) { // SAFETY: a slot of the heap and a live texture. - unsafe { self.device.CreateShaderResourceView(texture, None, self.cpu(i)) }; + unsafe { + self.device + .CreateShaderResourceView(texture, None, self.cpu(i)) + }; } fn wait(&mut self) { @@ -582,7 +950,9 @@ impl Scene { // SAFETY: our queue, fence and event. unsafe { self.queue.Signal(&self.fence, self.value).unwrap(); - self.fence.SetEventOnCompletion(self.value, self.event).unwrap(); + self.fence + .SetEventOnCompletion(self.value, self.event) + .unwrap(); WaitForSingleObject(self.event, INFINITE); self.device.GetDeviceRemovedReason().unwrap(); } @@ -599,7 +969,8 @@ impl Scene { } fn send(&self, lists: &[&ID3D12GraphicsCommandList]) { - let all: Vec> = lists.iter().map(|l| Some(l.cast().unwrap())).collect(); + let all: Vec> = + lists.iter().map(|l| Some(l.cast().unwrap())).collect(); // SAFETY: closed lists. unsafe { self.queue.ExecuteCommandLists(&all) }; } @@ -611,7 +982,13 @@ impl Scene { let mut c = color; c[1] = c[1].wrapping_add((x * 8 + y) as u8); // SAFETY: inside the mapping (16 rows of 256 bytes). - unsafe { self.texels.1.add(at + y * 256 + x * 4).cast::<[u8; 4]>().write(c) }; + unsafe { + self.texels + .1 + .add(at + y * 256 + x * 4) + .cast::<[u8; 4]>() + .write(c) + }; } } } @@ -621,13 +998,17 @@ impl Scene { // SAFETY: a borrowed pointer never released. pResource: unsafe { std::mem::transmute_copy(&self.texels.0) }, Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint(at, 16) }, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: footprint(at, 16), + }, }; let to = D3D12_TEXTURE_COPY_LOCATION { // SAFETY: as above. pResource: unsafe { std::mem::transmute_copy(texture) }, Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, }; // SAFETY: an open list; live resources. unsafe { l.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; @@ -643,10 +1024,24 @@ impl Scene { l.SetGraphicsRoot32BitConstant(0, pick, 0); l.SetGraphicsRootConstantBufferView(1, self.constants.0.GetGPUVirtualAddress() + at); l.SetGraphicsRootDescriptorTable(2, self.views.GetGPUDescriptorHandleForHeapStart()); - let step = self.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); + let step = self + .device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); let first = self.samplers.GetGPUDescriptorHandleForHeapStart().ptr; - l.SetGraphicsRootDescriptorTable(3, D3D12_GPU_DESCRIPTOR_HANDLE { ptr: first + 2 * u64::from(step) }); - l.ExecuteIndirect(&self.signature, 1, &self.scratch, record * 16, None::<&ID3D12Resource>, 0); + l.SetGraphicsRootDescriptorTable( + 3, + D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: first + 2 * u64::from(step), + }, + ); + l.ExecuteIndirect( + &self.signature, + 1, + &self.scratch, + record * 16, + None::<&ID3D12Resource>, + 0, + ); } } @@ -659,7 +1054,14 @@ impl Scene { l.SetComputeRootShaderResourceView(0, self.shared.0.GetGPUVirtualAddress() + 65536); l.SetComputeRootUnorderedAccessView(1, self.arguments.GetGPUVirtualAddress()); l.Dispatch(1, 1, 1); - l.ResourceBarrier(&[uav_barrier(), moved(&self.arguments, UAV, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)]); + l.ResourceBarrier(&[ + uav_barrier(), + moved( + &self.arguments, + UAV, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + ), + ]); l.ResourceBarrier(&[uav_barrier(), moved(&self.scratch, before, UAV)]); l.SetComputeRootSignature(&self.clamp.root); l.SetPipelineState(&self.clamp.pso); @@ -671,7 +1073,11 @@ impl Scene { l.SetComputeRootUnorderedAccessView(4, self.budget.GetGPUVirtualAddress()); l.Dispatch(1, 1, 1); l.ResourceBarrier(&[uav_barrier(), moved(&self.scratch, UAV, ARGUMENTS)]); - l.ResourceBarrier(&[moved(&self.arguments, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, UAV)]); + l.ResourceBarrier(&[moved( + &self.arguments, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + UAV, + )]); } } @@ -688,11 +1094,24 @@ impl Scene { fn targets(&self, l: &ID3D12GraphicsCommandList) { // SAFETY: an open list; live objects. unsafe { - let (rtv, dsv) = (self.rtvs.GetCPUDescriptorHandleForHeapStart(), self.dsvs.GetCPUDescriptorHandleForHeapStart()); + let (rtv, dsv) = ( + self.rtvs.GetCPUDescriptorHandleForHeapStart(), + self.dsvs.GetCPUDescriptorHandleForHeapStart(), + ); l.OMSetRenderTargets(1, Some(&rtv), false, Some(&dsv)); let size = SIZE as f32; - l.RSSetViewports(&[D3D12_VIEWPORT { Width: size, Height: size, MaxDepth: 1.0, ..Default::default() }]); - l.RSSetScissorRects(&[RECT { left: 0, top: 0, right: SIZE as i32, bottom: SIZE as i32 }]); + l.RSSetViewports(&[D3D12_VIEWPORT { + Width: size, + Height: size, + MaxDepth: 1.0, + ..Default::default() + }]); + l.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: SIZE as i32, + bottom: SIZE as i32, + }]); l.SetDescriptorHeaps(&[Some(self.views.clone()), Some(self.samplers.clone())]); } } @@ -703,15 +1122,34 @@ impl Scene { // card does not use now. unsafe { let x = 0.5 + 0.05 * n as f32; - let vertices = [[x, 0.4, 1.0, 0.0, 0.0], [x + 0.3, 0.4, 0.0, 1.0, 0.0], [x, 0.9, 0.0, 0.0, 1.0f32]]; + let vertices = [ + [x, 0.4, 1.0, 0.0, 0.0], + [x + 0.3, 0.4, 0.0, 1.0, 0.0], + [x, 0.9, 0.0, 0.0, 1.0f32], + ]; self.vertices.1.cast::<[[f32; 5]; 3]>().write(vertices); - self.vertices.1.add(1024).cast::<[u16; 4]>().write([9, 2, 0, 1]); + self.vertices + .1 + .add(1024) + .cast::<[u16; 4]>() + .write([9, 2, 0, 1]); let at = self.vertices.0.GetGPUVirtualAddress(); l.SetGraphicsRootSignature(&self.plain.root); l.SetPipelineState(&self.plain.pso); l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - l.IASetVertexBuffers(0, Some(&[D3D12_VERTEX_BUFFER_VIEW { BufferLocation: at, SizeInBytes: 60, StrideInBytes: 20 }])); - let indices = D3D12_INDEX_BUFFER_VIEW { BufferLocation: at + 1024, SizeInBytes: 8, Format: DXGI_FORMAT_R16_UINT }; + l.IASetVertexBuffers( + 0, + Some(&[D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: at, + SizeInBytes: 60, + StrideInBytes: 20, + }]), + ); + let indices = D3D12_INDEX_BUFFER_VIEW { + BufferLocation: at + 1024, + SizeInBytes: 8, + Format: DXGI_FORMAT_R16_UINT, + }; l.IASetIndexBuffer(Some(&indices)); l.DrawIndexedInstanced(3, 1, 1, 0, 0); } @@ -752,16 +1190,34 @@ impl Scene { self.device.CreateDepthStencilView(t, Some(&view), dsv); let both = D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL; l.ClearDepthStencilView(dsv, both, 0.75, 3, None); - let part = RECT { left: 5, top: 6, right: 20, bottom: 17 }; + let part = RECT { + left: 5, + top: 6, + right: 20, + bottom: 17, + }; l.ClearDepthStencilView(dsv, both, 0.25, 200, Some(&[part])); continue; } let desc = t.GetDesc(); - let layers = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { desc.DepthOrArraySize }; + let layers = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { + 1 + } else { + desc.DepthOrArraySize + }; for sub in 0..u32::from(layers * desc.MipLevels) { let mut f = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); let mut total = 0; - self.device.GetCopyableFootprints(&desc, sub, 1, at, Some(&mut f), None, None, Some(&mut total)); + self.device.GetCopyableFootprints( + &desc, + sub, + 1, + at, + Some(&mut f), + None, + None, + Some(&mut total), + ); at = (at + total).next_multiple_of(512); let from = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&up), @@ -785,13 +1241,26 @@ impl Scene { // SAFETY: as above. unsafe { let desc = t.GetDesc(); - let layers = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { desc.DepthOrArraySize }; + let layers = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { + 1 + } else { + desc.DepthOrArraySize + }; let planes = if name == "stencil" { 2 } else { 1 }; let mut subs = Vec::new(); for sub in 0..u32::from(layers * desc.MipLevels) * planes { let mut f = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); let (mut rows, mut len) = (0, 0); - self.device.GetCopyableFootprints(&desc, sub, 1, 0, Some(&mut f), Some(&mut rows), Some(&mut len), None); + self.device.GetCopyableFootprints( + &desc, + sub, + 1, + 0, + Some(&mut f), + Some(&mut rows), + Some(&mut len), + None, + ); let l = self.open(0); l.ResourceBarrier(&[moved(&t, state, FROM)]); let to = D3D12_TEXTURE_COPY_LOCATION { @@ -806,7 +1275,10 @@ impl Scene { self.wait(); let pitch = f.Footprint.RowPitch as usize; let rows = (0..rows as usize * f.Footprint.Depth as usize) - .map(|r| std::slice::from_raw_parts(self.back.1.add(r * pitch), len as usize).to_vec()) + .map(|r| { + std::slice::from_raw_parts(self.back.1.add(r * pitch), len as usize) + .to_vec() + }) .collect(); subs.push((pitch, rows)); } @@ -841,7 +1313,10 @@ impl Scene { self.give(40, 7 + n); let l = self.open(0); l.ResourceBarrier(&[moved(&self.target, FROM, TARGET)]); - let (rtv, dsv) = (self.rtvs.GetCPUDescriptorHandleForHeapStart(), self.dsvs.GetCPUDescriptorHandleForHeapStart()); + let (rtv, dsv) = ( + self.rtvs.GetCPUDescriptorHandleForHeapStart(), + self.dsvs.GetCPUDescriptorHandleForHeapStart(), + ); l.ClearRenderTargetView(rtv, &[0.1 * n as f32, 0.2, 0.3, 1.0], None); l.ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None); self.arguments(&l, COMMON); @@ -858,6 +1333,12 @@ impl Scene { // The second: other constants and another texture in the same // places, and the second texture in the memory of the first. self.show(4000, &self.other); + // Arguments of a mesh draw. + self.constants + .1 + .add(1024) + .cast::<[u32; 3]>() + .write([1, 1, 1]); self.place(0, [-0.9, 0.3, 0.6, 0.6]); self.place(256, [0.3, -0.8, 0.6, 0.5]); self.give(40, 100 + n); @@ -873,6 +1354,26 @@ impl Scene { l.ResourceBarrier(&[moved(&self.one, TO, READ)]); self.arguments(&l, ARGUMENTS); self.quad(&l, 4002, 256, 0); + if let Some((made, signature)) = &self.mesh { + l.SetGraphicsRootSignature(&made.root); + l.SetPipelineState(&made.pso); + let constants = [ + (-0.3f32).to_bits(), + (-0.9f32).to_bits(), + 0.5f32.to_bits(), + 0.4f32.to_bits(), + 4002, + ]; + l.SetGraphicsRoot32BitConstants(0, 5, constants.as_ptr().cast(), 0); + l.ExecuteIndirect( + signature, + 1, + &self.constants.0, + 1024, + None::<&ID3D12Resource>, + 0, + ); + } l.ResourceBarrier(&[moved(&self.scratch, ARGUMENTS, COMMON)]); // And back, for the next frame. l.ResourceBarrier(&[moved(&self.one, READ, TO)]); @@ -909,7 +1410,9 @@ impl Scene { queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); self.value += 1; queue.Signal(&self.fence, self.value).unwrap(); - self.fence.SetEventOnCompletion(self.value, self.event).unwrap(); + self.fence + .SetEventOnCompletion(self.value, self.event) + .unwrap(); WaitForSingleObject(self.event, INFINITE); if let Some((swap, _)) = &self.swap { swap.Present(0, DXGI_PRESENT(0)).unwrap(); @@ -928,12 +1431,16 @@ impl Scene { let to = |at: u64, size| D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&self.back.0), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint(at, size) }, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: footprint(at, size), + }, }; let of = |t: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(t), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, }; l.ResourceBarrier(&[moved(&self.image, UAV, FROM)]); l.CopyTextureRegion(&to(0, SIZE), 0, 0, 0, &of(&self.target), None); @@ -943,7 +1450,9 @@ impl Scene { l.Close().unwrap(); self.send(&[&l]); self.wait(); - let at = |from: usize, n: usize| std::slice::from_raw_parts(self.back.1.add(from), n).to_vec(); + let at = |from: usize, n: usize| { + std::slice::from_raw_parts(self.back.1.add(from), n).to_vec() + }; Outcome { still, picture: at(0, (SIZE * 512) as usize), @@ -960,7 +1469,9 @@ fn sub_of(t: &ID3D12Resource, sub: u32) -> D3D12_TEXTURE_COPY_LOCATION { // SAFETY: a borrowed pointer never released. pResource: unsafe { std::mem::transmute_copy(t) }, Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub }, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: sub, + }, } } @@ -986,20 +1497,40 @@ fn footprint(at: u64, size: u32) -> D3D12_PLACED_SUBRESOURCE_FOOTPRINT { fn swap_chain(queue: &ID3D12CommandQueue) -> (IDXGISwapChain3, HWND) { // SAFETY: plain creation. unsafe { - let hwnd = - CreateWindowExW(WINDOW_EX_STYLE(0), w!("STATIC"), w!("replay test"), WS_POPUP, 0, 0, 64, 64, None, None, None, None).unwrap(); + let hwnd = CreateWindowExW( + WINDOW_EX_STYLE(0), + w!("STATIC"), + w!("replay test"), + WS_POPUP, + 0, + 0, + 64, + 64, + None, + None, + None, + None, + ) + .unwrap(); let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap(); let desc = DXGI_SWAP_CHAIN_DESC1 { Width: 64, Height: 64, Format: DXGI_FORMAT_R8G8B8A8_UNORM, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, BufferCount: 2, SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, ..Default::default() }; - let chain = factory.CreateSwapChainForHwnd(queue, hwnd, &desc, None, None).unwrap().cast().unwrap(); + let chain = factory + .CreateSwapChainForHwnd(queue, hwnd, &desc, None, None) + .unwrap() + .cast() + .unwrap(); (chain, hwnd) } } @@ -1015,7 +1546,10 @@ fn check(player: &mut Player, options: &Options, expected: &Outcome, what: &str) assert_eq!(report.frame_ms.len(), options.loops as usize); assert!(report.median_ms() > 0.0); let (db, same) = report.picture.unwrap(); - assert!(same && db.is_infinite(), "{what}: the picture differs ({db} dB)"); + assert!( + same && db.is_infinite(), + "{what}: the picture differs ({db} dB)" + ); let mut get = |name: &str| { let id = player.named(name).unwrap(); player.contents(id).unwrap().unwrap() @@ -1023,19 +1557,38 @@ fn check(player: &mut Player, options: &Options, expected: &Outcome, what: &str) assert_eq!(get("sum"), expected.sum, "{what}: sum"); assert_eq!(rows(&get("image")), expected.image, "{what}: image"); assert_eq!(get("target"), expected.picture, "{what}: target"); - assert!(get("shared") == expected.shared, "{what}: memory the CPU sees"); + assert!( + get("shared") == expected.shared, + "{what}: memory the CPU sees" + ); for still in &expected.still { let id = player.named(still.name).unwrap(); for (sub, (pitch, rows)) in still.subs.iter().enumerate() { let have = player.contents_of(id, sub as u32).unwrap().unwrap(); for (r, row) in rows.iter().enumerate() { - assert_eq!(&have[r * pitch..][..row.len()], &row[..], "{what}: {} subresource {sub} row {r}", still.name); + assert_eq!( + &have[r * pitch..][..row.len()], + &row[..], + "{what}: {} subresource {sub} row {r}", + still.name + ); } } } // Nothing was left out but what another queue ran. - let known = ["submissions,", "waits of the drawing queue", "lists sent to a queue other than"]; - assert!(!report.notes.iter().any(|n| n.contains("recorder:") && !known.iter().any(|k| n.contains(k))), "{what}: {:?}", report.notes); + let known = [ + "submissions,", + "waits of the drawing queue", + "lists sent to a queue other than", + ]; + assert!( + !report + .notes + .iter() + .any(|n| n.contains("recorder:") && !known.iter().any(|k| n.contains(k))), + "{what}: {:?}", + report.notes + ); assert!(report.notes.iter().any(|n| n.contains(known[2]))); report } @@ -1068,82 +1621,213 @@ fn a_frame_is_recorded_and_replayed() { // Something is in the picture. assert!(without.sum.iter().any(|&b| b != 0)); for s in &without.still { - assert!(s.subs.iter().all(|(_, rows)| rows.iter().flatten().any(|&b| b != 0)), "{}", s.name); + assert!( + s.subs + .iter() + .all(|(_, rows)| rows.iter().flatten().any(|&b| b != 0)), + "{}", + s.name + ); } - assert_eq!(without.still.iter().map(|s| s.subs.len()).collect::>(), [15, 3, 2]); - let colors: std::collections::HashSet<[u8; 4]> = - without.picture.chunks_exact(4).map(|c| [c[0], c[1], c[2], c[3]]).collect(); + assert_eq!( + without + .still + .iter() + .map(|s| s.subs.len()) + .collect::>(), + [15, 3, 2] + ); + let colors: std::collections::HashSet<[u8; 4]> = without + .picture + .chunks_exact(4) + .map(|c| [c[0], c[1], c[2], c[3]]) + .collect(); assert!(colors.len() > 30, "{}", colors.len()); // With it: armed at the first present, the fourth frame is captured (a // frame whose lists are all recorded comes first). assert!(!record::on()); let dir = tempfile::tempdir().unwrap(); - let settings = Settings { folder: dir.path().to_owned(), at: At::Frame(1), frames: 1, always: false }; + let settings = Settings { + folder: dir.path().to_owned(), + at: At::Frame(1), + frames: 1, + always: false, + }; let folder = record::start(settings, &device).unwrap(); assert!(record::on()); assert_ne!(table_of(&device), own, "the device is hooked"); assert!( - record::start(Settings { folder: dir.path().to_owned(), at: At::Trigger, frames: 1, always: false }, &device).is_err(), + record::start( + Settings { + folder: dir.path().to_owned(), + at: At::Trigger, + frames: 1, + always: false + }, + &device + ) + .is_err(), "one recorder a process" ); eprintln!("recorder on"); let mut scene = Scene::new(&device, true); eprintln!("scene made"); (0..4).for_each(|n| scene.frame(n)); - assert_eq!(record::finished(), Some(folder.clone()), "see {}", folder.display()); + assert_eq!( + record::finished(), + Some(folder.clone()), + "see {}", + folder.display() + ); let expected = scene.outcome(); // It goes on as it did without the recorder. scene.frame(4); let after = scene.outcome(); - assert!(after == without, "the recorder changed what the program makes"); + assert!( + after == without, + "the recorder changed what the program makes" + ); drop(scene); record::unhook(&device); assert_eq!(table_of(&device), own, "the device is as it was"); - for name in ["frame.bin", "contents.bin", "deltas.bin", "shaders.bin", "present.bin", "notes.txt", "frame-0.png"] { + for name in [ + "frame.bin", + "contents.bin", + "deltas.bin", + "shaders.bin", + "present.bin", + "notes.txt", + "frame-0.png", + ] { assert!(folder.join(name).exists(), "{name}"); } - println!("{}", std::fs::read_to_string(folder.join("notes.txt")).unwrap()); + println!( + "{}", + std::fs::read_to_string(folder.join("notes.txt")).unwrap() + ); - let plain = Options { loops: 3, ..Default::default() }; + let plain = Options { + loops: 3, + ..Default::default() + }; let mut player = Player::load(dir.path(), &plain).unwrap(); check(&mut player, &plain, &expected, "unchanged"); - let detailed = Options { detailed: true, ..plain.clone() }; + let detailed = Options { + detailed: true, + ..plain.clone() + }; let report = check(&mut player, &detailed, &expected, "detailed"); - let count = |kind: &str| report.categories.iter().find(|c| c.0 == kind).map_or(0, |c| c.2); + let count = |kind: &str| { + report + .categories + .iter() + .find(|c| c.0 == kind) + .map_or(0, |c| c.2) + }; assert_eq!(count("argument clamps (ours)"), 3); assert_eq!(count("indirect draws"), 5); + assert_eq!(count("draws"), 1); + let meshes = count("indirect mesh draws"); + println!("{meshes} mesh draws"); + if meshes > 0 { + assert!( + report + .shaders + .iter() + .any(|s| s.2.starts_with("a mesh pipeline (DXIL ")), + "{:?}", + report.shaders + ); + } assert_eq!(count("dispatches"), 6); assert_eq!(count("clears"), 2); - assert!(report.shaders.iter().any(|s| s.2.starts_with("a drawing pipeline (DXIL ")), "{:?}", report.shaders); - let merged = Options { merge_barriers: true, ..plain.clone() }; + assert!( + report + .shaders + .iter() + .any(|s| s.2.starts_with("a drawing pipeline (DXIL ")), + "{:?}", + report.shaders + ); + let merged = Options { + merge_barriers: true, + ..plain.clone() + }; check(&mut player, &merged, &expected, "merged barriers"); - let clamps = Options { skip_clamps: true, ..plain.clone() }; + let clamps = Options { + skip_clamps: true, + ..plain.clone() + }; let report = check(&mut player, &clamps, &expected, "without clamps"); - assert!(report.notes.iter().any(|n| n.contains("3 clamp passes")), "{:?}", report.notes); - let one = Options { one_submit: true, ..plain.clone() }; + assert!( + report.notes.iter().any(|n| n.contains("3 clamp passes")), + "{:?}", + report.notes + ); + let one = Options { + one_submit: true, + ..plain.clone() + }; check(&mut player, &one, &expected, "one submission"); - let hash = Options { skip_hash_passes: true, ..plain.clone() }; - check(&mut player, &hash, &expected, "without hash passes (there are none)"); + let hash = Options { + skip_hash_passes: true, + ..plain.clone() + }; + check( + &mut player, + &hash, + &expected, + "without hash passes (there are none)", + ); // These change what is drawn: they run, and then the frame is as before. - let no_barriers = Options { no_barriers: true, ..plain.clone() }; + let no_barriers = Options { + no_barriers: true, + ..plain.clone() + }; player.run(&no_barriers).unwrap(); - let some = Options { only: Some((0, 1)), ..plain.clone() }; + let some = Options { + only: Some((0, 1)), + ..plain.clone() + }; player.run(&some).unwrap(); - let skip = Options { skip_shaders: vec!["a drawing".into()], ..plain.clone() }; + let skip = Options { + skip_shaders: vec!["a drawing".into()], + ..plain.clone() + }; let report = player.run(&skip).unwrap(); - assert!(!report.picture.unwrap().1, "without its draws the picture is another"); - assert!(report.notes.iter().any(|n| n.contains("1 pipelines match")) && report.notes.iter().any(|n| n.contains("left out 5 commands"))); - let kept = Options { restore: false, ..plain.clone() }; + assert!( + !report.picture.unwrap().1, + "without its draws the picture is another" + ); + assert!( + report.notes.iter().any(|n| n.contains("1 pipelines match")) + && report + .notes + .iter() + .any(|n| n.contains("left out 5 commands")) + ); + let kept = Options { + restore: false, + ..plain.clone() + }; player.run(&kept).unwrap(); check(&mut player, &plain, &expected, "unchanged again"); drop(player); for buffers in [Buffers::Card, Buffers::Pc] { - let o = Options { buffers, ..plain.clone() }; + let o = Options { + buffers, + ..plain.clone() + }; let mut player = Player::load(dir.path(), &o).unwrap(); check(&mut player, &o, &expected, &format!("buffers {buffers:?}")); } - let o = Options { compare: true, merge_barriers: true, loops: 2, ..Default::default() }; + let o = Options { + compare: true, + merge_barriers: true, + loops: 2, + ..Default::default() + }; let both = play::replay(dir.path(), &o).unwrap(); assert_eq!(both.len(), 2); assert!(both.iter().all(|(_, r)| r.picture.unwrap().1)); @@ -1157,9 +1841,17 @@ fn a_frame_is_recorded_and_replayed() { let _ = q.GetMessage(i, None, &mut size); let mut buffer = vec![0u64; size.div_ceil(8)]; let m = buffer.as_mut_ptr().cast::(); - if q.GetMessage(i, Some(m), &mut size).is_ok() && (*m).Severity.0 <= D3D12_MESSAGE_SEVERITY_WARNING.0 { - let text = std::slice::from_raw_parts((*m).pDescription, (*m).DescriptionByteLength); - println!("D3D12 {} {}: {}", (*m).Severity.0, (*m).ID.0, String::from_utf8_lossy(text)); + if q.GetMessage(i, Some(m), &mut size).is_ok() + && (*m).Severity.0 <= D3D12_MESSAGE_SEVERITY_WARNING.0 + { + let text = + std::slice::from_raw_parts((*m).pDescription, (*m).DescriptionByteLength); + println!( + "D3D12 {} {}: {}", + (*m).Severity.0, + (*m).ID.0, + String::from_utf8_lossy(text) + ); } } } diff --git a/crates/victory-gpu/tests/replay_big.rs b/crates/victory-gpu/tests/replay_big.rs index 34a9b95..9f60399 100644 --- a/crates/victory-gpu/tests/replay_big.rs +++ b/crates/victory-gpu/tests/replay_big.rs @@ -3,7 +3,8 @@ //! thousands of textures and buffers, a view heap of 1.5 million slots, 30 //! submissions of 40,000 calls. //! -//! `BIG_TEXTURES` (17000) and `BIG_FOLDER` (a temporary one) change it. +//! `BIG_TEXTURES` (17000), `BIG_CARD` (600 buffers of 1 MB in the card's +//! memory) and `BIG_FOLDER` (a temporary one) change it. #![cfg(all(windows, feature = "diagnostics"))] use std::mem::ManuallyDrop; @@ -24,12 +25,18 @@ const VIEWS: u32 = 1_500_000; fn buffer(device: &ID3D12Device, kind: u32, size: u64) -> (ID3D12Resource, *mut u8) { let (heap, state, flags) = match kind { 0 => ( - D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, ), 1 => ( - D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_UPLOAD, + ..Default::default() + }, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_FLAG_NONE, ), @@ -50,7 +57,10 @@ fn buffer(device: &ID3D12Device, kind: u32, size: u64) -> (ID3D12Resource, *mut 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() @@ -59,7 +69,9 @@ fn buffer(device: &ID3D12Device, kind: u32, size: u64) -> (ID3D12Resource, *mut let mut data = std::ptr::null_mut(); // SAFETY: plain creation and mapping. unsafe { - device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut made).unwrap(); + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut made) + .unwrap(); let made = made.unwrap(); if kind > 0 { made.Map(0, None, Some(&mut data)).unwrap(); @@ -72,7 +84,11 @@ fn buffer(device: &ID3D12Device, kind: u32, size: u64) -> (ID3D12Resource, *mut } } -fn barrier(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { +fn barrier( + res: &ID3D12Resource, + before: D3D12_RESOURCE_STATES, + after: D3D12_RESOURCE_STATES, +) -> D3D12_RESOURCE_BARRIER { D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Anonymous: D3D12_RESOURCE_BARRIER_0 { @@ -88,6 +104,14 @@ fn barrier(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RES } } +/// A number from the environment. +fn number(name: &str, otherwise: usize) -> usize { + std::env::var(name) + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(otherwise) +} + struct Big { device: ID3D12Device, queue: ID3D12CommandQueue, @@ -105,7 +129,10 @@ struct Big { impl Big { fn new(device: &ID3D12Device, textures: usize) -> Big { let texture = |size: u32, flags, state| { - let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: u64::from(size), @@ -113,24 +140,45 @@ impl Big { DepthOrArraySize: 1, MipLevels: if size == 256 { 9 } else { 1 }, Format: DXGI_FORMAT_R8G8B8A8_UNORM, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Flags: flags, ..Default::default() }; let mut made: Option = None; // SAFETY: plain creation. - unsafe { device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut made).unwrap() }; + unsafe { + device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + state, + None, + &mut made, + ) + .unwrap() + }; made.unwrap() }; // SAFETY: plain creation; slots of the heap just made. unsafe { let queue: ID3D12CommandQueue = device - .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) .unwrap(); let lists = (0..SUBMITS) .map(|_| { - let a: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); - let l: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &a, None).unwrap(); + let a: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .unwrap(); + let l: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &a, None) + .unwrap(); l.Close().unwrap(); (a, l) }) @@ -143,26 +191,47 @@ impl Big { NodeMask: 0, }) .unwrap(); - let step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let step = device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + as usize; let start = views.GetCPUDescriptorHandleForHeapStart().ptr; let textures: Vec = (0..textures) - .map(|_| texture(256, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE)) + .map(|_| { + texture( + 256, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE, + ) + }) .collect(); for i in 0..VIEWS as usize { - let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start + i * step }; + let at = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start + i * step, + }; device.CreateShaderResourceView(&textures[i % textures.len()], None, at); } - let shared: Vec<(ID3D12Resource, *mut u8)> = (0..1000).map(|_| buffer(device, 2, 1 << 20)).collect(); + let shared: Vec<(ID3D12Resource, *mut u8)> = + (0..1000).map(|_| buffer(device, 2, 1 << 20)).collect(); for (i, (b, _)) in shared.iter().enumerate() { let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT_R32_TYPELESS, ViewDimension: D3D12_SRV_DIMENSION_BUFFER, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { - Buffer: D3D12_BUFFER_SRV { NumElements: 1 << 18, Flags: D3D12_BUFFER_SRV_FLAG_RAW, ..Default::default() }, + Buffer: D3D12_BUFFER_SRV { + NumElements: 1 << 18, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + ..Default::default() + }, }, }; - device.CreateShaderResourceView(b, Some(&desc), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start + i * step }); + device.CreateShaderResourceView( + b, + Some(&desc), + D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start + i * step, + }, + ); } Big { device: device.clone(), @@ -171,11 +240,17 @@ impl Big { value: 0, lists, _textures: textures, - card: (0..600).map(|_| buffer(device, 0, 1 << 20).0).collect(), + card: (0..number("BIG_CARD", 600)) + .map(|_| buffer(device, 0, 1 << 20).0) + .collect(), shared, upload: (0..1000).map(|_| buffer(device, 1, 1 << 20)).collect(), views, - target: texture(1024, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE), + target: texture( + 1024, + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE, + ), } } } @@ -194,6 +269,21 @@ impl Big { } fn frame(&mut self, n: usize) { + if n == 0 { + // Nothing in the card's buffers is all zero, as in a title's. + // SAFETY: a list whose last run has finished; live buffers. + unsafe { + let (a, l) = &self.lists[0]; + a.Reset().unwrap(); + l.Reset(a, None).unwrap(); + for (i, card) in self.card.iter().enumerate() { + l.CopyBufferRegion(card, 0, &self.upload[i % self.upload.len()].0, 0, 1 << 20); + } + l.Close().unwrap(); + self.queue.ExecuteCommandLists(&[Some(l.cast().unwrap())]); + } + self.wait(); + } for s in 0..SUBMITS { // SAFETY: lists whose last run has finished; mappings written // inside their bounds. @@ -206,8 +296,16 @@ impl Big { let card = &self.card[(i * 7 + s) % self.card.len()]; let from = &self.upload[(i + s * 31) % self.upload.len()].0; l.CopyBufferRegion(card, (i % 1000 * 1000) as u64 & !3, from, 0, 256); - l.ResourceBarrier(&[barrier(card, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); - l.ResourceBarrier(&[barrier(card, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST)]); + l.ResourceBarrier(&[barrier( + card, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + l.ResourceBarrier(&[barrier( + card, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_DEST, + )]); l.SetMarker(1, None, 0); } l.Close().unwrap(); @@ -231,8 +329,10 @@ fn a_frame_of_a_titles_size() { // SAFETY: plain creation. unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).unwrap() }; let device = device.unwrap(); - let textures = std::env::var("BIG_TEXTURES").ok().and_then(|v| v.parse().ok()).unwrap_or(17_000); - let timed = |what: &str, began: Instant| println!("{what}: {:.1} ms", began.elapsed().as_secs_f64() * 1e3); + let textures = number("BIG_TEXTURES", 17_000); + let timed = |what: &str, began: Instant| { + println!("{what}: {:.1} ms", began.elapsed().as_secs_f64() * 1e3) + }; let began = Instant::now(); { let mut big = Big::new(&device, textures); @@ -245,7 +345,12 @@ fn a_frame_of_a_titles_size() { } let dir = tempfile::tempdir().unwrap(); let folder = std::env::var_os("BIG_FOLDER").map_or(dir.path().to_owned(), Into::into); - let settings = Settings { folder, at: At::Frame(4), frames: 1, always: false }; + let settings = Settings { + folder, + at: At::Frame(4), + frames: 1, + always: false, + }; let folder = record::start(settings, &device).unwrap(); let began = Instant::now(); let mut big = Big::new(&device, textures); @@ -253,17 +358,39 @@ fn a_frame_of_a_titles_size() { for n in 0..8 { let began = Instant::now(); big.frame(n); - timed(["frame", "frame, lists recorded", "frame, captured", "frame, after"][[0, 0, 0, 0, 1, 1, 2, 3][n]], began); + timed( + [ + "frame", + "frame, lists recorded", + "frame, captured", + "frame, after", + ][[0, 0, 0, 0, 1, 1, 2, 3][n]], + began, + ); } assert_eq!(record::finished(), Some(folder.clone())); drop(big); record::unhook(&device); - println!("{}", std::fs::read_to_string(folder.join("notes.txt")).unwrap()); + println!( + "{}", + std::fs::read_to_string(folder.join("notes.txt")).unwrap() + ); for f in std::fs::read_dir(&folder).unwrap().flatten() { - println!("{:>8} MB {}", f.metadata().unwrap().len() >> 20, f.file_name().to_string_lossy()); + println!( + "{:>8} MB {}", + f.metadata().unwrap().len() >> 20, + f.file_name().to_string_lossy() + ); } let began = Instant::now(); - let reports = play::replay(&folder, &Options { loops: 3, ..Default::default() }).unwrap(); + let reports = play::replay( + &folder, + &Options { + loops: 3, + ..Default::default() + }, + ) + .unwrap(); timed("loaded and replayed", began); for (what, r) in &reports { println!("{}", r.text(what)); diff --git a/docs/replay.md b/docs/replay.md new file mode 100644 index 0000000..7333348 --- /dev/null +++ b/docs/replay.md @@ -0,0 +1,102 @@ +# Recording a frame and running it again + +A diagnostics build can write down one frame's D3D12 work (what the host +layer sends to the card, and the memory it reads) and run it again without +the title, to see where the card's time goes and to try changes in seconds. +Code: `crates/victory-gpu/src/replay`. + +## Recording + +Off unless `VICTORY_RECORD` is set. Build with +`cargo build --locked --profile diag -p victory --features diagnostics`. + +| variable | meaning | +|---|---| +| `VICTORY_RECORD=` | on; the capture goes to `\capture-` (outside the repository) | +| `VICTORY_RECORD_AT=` or `f` | when: seconds after the device was made, or a number of presents. Unset: only the trigger file | +| file `\go` | when it appears, the capture starts (always watched) | +| `VICTORY_RECORD_FRAMES=` | frames to capture (1) | +| `VICTORY_RECORD_ALWAYS=1` | record lists from the start: needed only if notes say lists were not recorded (a title that submits old lists again) | + +At the time given, lists are recorded for a few frames, until a frame's lists +were all recorded; the next frame is captured: everything sent to the drawing +queue between two presents (the first may be the swap chain's own work for +the frame before). One capture per process. At the frame's first submission +the card is drained and its memory copied out; before each later one the card +is drained again and what the CPU changed is written. The title stands still +meanwhile. `frame recorder: the frame is captured` in the log and `frame.bin` +in the folder mean it is done; `failed.txt` that it failed. + +**Read `notes.txt`**: everything that could not be recorded is listed there +(and in every replay's report). Only the line with the totals, waits of the +drawing queue and lists of another queue (the relay's copies) are expected. + +Measured on a made-up frame of a title's size (12,000 resources, 1.5 million +views, 30 submissions, 40,000 calls): a frame takes 3-10 ms more with the +recorder on, the capture stands still for 5.4 s and is 9 GB (8 GB of the card's +memory at 2.3 GB/s, 1 GB the CPU wrote). The recorder holds a copy of the +memory both sides see that the frame reads, and 1 GB or more of read-back +buffers, until it is done. + +## Running it + + victory replay [--loops 5] [--timing detailed] [experiments] + +`` is the one given as `VICTORY_RECORD` (its last capture) or a +capture. Each loop puts back what the one before changed and sends the frame +without waiting between submissions. Reported, from timestamps on the card: +the frame (first list's start to last list's end), each submission, copies +that stand for what the CPU wrote between submissions (not the title's cost), +and gaps. With `--timing detailed`, each command: sums by kind and the +costliest pipelines with the names the runtime logs and their DXIL hashes +(blake3). A command's time is from the end of the one before to its own end: +draws overlap, so it is a share of the list, not a cost alone; the extra +timestamps cost a little too. The picture goes to `replay.png` and is compared +with the presented one. + +| switch | does | +|---|---| +| `--compare` | runs the frame unchanged first and prints the difference | +| `--skip-clamps` | no argument clamps and no barriers of their scratch buffers; draws read arguments kept from a first run | +| `--skip-hash-passes` | no compare/rehash passes over card buffers | +| `--no-barriers` | no unordered-access barriers | +| `--merge-barriers` | joins barrier calls with no work between them | +| `--buffers vram` / `sysmem` | all buffers in the card's / the PC's memory | +| `--one-submit` | one `ExecuteCommandLists`, with a full wait between the former ones | +| `--only 3..7` | runs these lists; of the others only barriers | +| `--skip-shader ` | leaves out what runs pipelines with the text in their name or DXIL hash (repeatable) | +| `--no-restore` | leaves what a loop changed | +| `--debug-layer` | D3D12's debug layer; its errors in the report | + +Use the median of several loops; the first is slower. An experiment that +leaves out waits or work can draw another picture and, with wild data, lose +the device: save work in other programs first. Do not run the title at the +same time. + +## Limits + +- Not recorded, but reported when used: reserved (tiled) resources, bundles, + ray tracing, render passes, enhanced barriers, predication, stream output, + `ClearUnorderedAccessView`, shading rate, newer creation methods + (`CreateCommittedResource1` and on). +- Not kept: contents of multisampled textures, of textures in memory the CPU + sees, and of texture levels over 256 MB; resources of other queues' work. +- Texture states come from the barriers seen. A resource that overlaps the + one last used (aliasing) is taken as without contents. +- Addresses in memory are not rewritten: indirect arguments with addresses + (vertex buffers, root views) are reported, and would be wrong. Descriptors + and root arguments are. +- Views replaced during the frame get a heap of their own per submission in + the replay (64 MB for two million views). +- Upload heaps become custom write-combined ones in the replay, as the card + writes what the CPU wrote. +- What the CPU changes in memory both see is taken before each submission, by + pages of 4 KiB, of what that submission reads of it (all of a buffer that a + descriptor names). Pages the card wrote there are part of it: they count as + copies, and set the card's own results to the recorded ones. +- The card's clocks are the system's: other programs on the card change the + times. + +Tests: `cargo test -p victory-gpu --features diagnostics` (`tests/replay.rs` +runs a small program and compares every byte; `VICTORY_TEST_D3D_DEBUG=1` adds +the debug layer) and `tests/replay_big.rs` (`--ignored`).