texback.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. //! Textures shaders write that the title's own code then reads on the CPU.
  2. //! On the console the CPU and the GPU share memory, so what a compute pass
  3. //! stores into a texture is in title memory for the CPU to read. Here it stays
  4. //! in the texture's host copy. The title's ocean is one: its wave passes write
  5. //! a 256x256 height map (R32_FLOAT) and a displacement map (R32G32_FLOAT), and
  6. //! its CPU code samples both, which is what boats float on; it read memory
  7. //! nothing had written (run rw1, `VICTORY_READ_WATCH=1`: about 30 places in
  8. //! the title read those two kinds), and boats sank.
  9. //!
  10. //! For textures of the kinds in `VICTORY_TEXTURE_BACK` (comma-separated
  11. //! `<width>x<height>f<format>`; unset or `1`: the four water formats found by
  12. //! the upstream trace; `0`: none), a list in which shaders write one copies it
  13. //! into a read-back buffer of ours when it closes, and once the list has run
  14. //! the texels are tiled into the texture's title memory in the console's
  15. //! layout, as the console's GPU would have left them.
  16. //!
  17. //! shortcut: by kind, not by texture: textures of those kinds the title never
  18. //! reads are copied back too (about a megabyte per such list). The copy shows
  19. //! what the list's last write left; a title read in between sees the frame
  20. //! before, as it would before the console's GPU has run.
  21. use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
  22. use std::sync::{Arc, Mutex, OnceLock, Weak};
  23. use windows::Win32::Graphics::Direct3D12::*;
  24. use crate::object::This;
  25. /// The kinds copied back: (width, height, format).
  26. fn kinds() -> &'static [(u64, u32, u32)] {
  27. static KINDS: OnceLock<Vec<(u64, u32, u32)>> = OnceLock::new();
  28. KINDS.get_or_init(|| {
  29. const DEFAULT: &str = "256x256f41,256x256f16,64x64f16,128x128f36";
  30. let list = match std::env::var("VICTORY_TEXTURE_BACK").as_deref() {
  31. Ok("1") | Err(_) => DEFAULT.to_owned(),
  32. Ok(spec) => spec.to_owned(),
  33. };
  34. let kinds: Vec<(u64, u32, u32)> = list
  35. .split(',')
  36. .filter_map(|k| {
  37. let (size, format) = k.trim().split_once('f')?;
  38. let (w, h) = size.split_once('x')?;
  39. Some((w.parse().ok()?, h.parse().ok()?, format.parse().ok()?))
  40. })
  41. .collect();
  42. if !kinds.is_empty() {
  43. tracing::info!(?kinds, "textures of these kinds that shaders write are copied back into title memory (VICTORY_TEXTURE_BACK)");
  44. }
  45. kinds
  46. })
  47. }
  48. /// Whether title texture `resource` is of a kind copied back.
  49. pub(crate) fn wanted(resource: This) -> bool {
  50. let kinds = kinds();
  51. !kinds.is_empty()
  52. && crate::resource::texture_kind(resource).is_some_and(|k| kinds.contains(&k))
  53. }
  54. /// An outstanding write to a specific allocation. Mapping and resource
  55. /// changes invalidate only the writes that could touch the replaced memory.
  56. struct Ticket {
  57. owner: usize,
  58. at: usize,
  59. end: usize,
  60. valid: AtomicBool,
  61. }
  62. static TICKETS: Mutex<Vec<Weak<Ticket>>> = Mutex::new(Vec::new());
  63. static TRACKING: AtomicBool = AtomicBool::new(false);
  64. fn track(owner: usize, at: usize, end: usize) -> Arc<Ticket> {
  65. let ticket = Arc::new(Ticket { owner, at, end, valid: AtomicBool::new(true) });
  66. let mut tickets = TICKETS.lock().unwrap_or_else(|e| e.into_inner());
  67. tickets.retain(|weak| weak.strong_count() != 0);
  68. tickets.push(Arc::downgrade(&ticket));
  69. TRACKING.store(true, Ordering::Relaxed);
  70. ticket
  71. }
  72. fn invalidate(matches: impl Fn(&Ticket) -> bool) {
  73. if !TRACKING.load(Ordering::Relaxed) {
  74. return;
  75. }
  76. TICKETS.lock().unwrap_or_else(|e| e.into_inner()).retain(|weak| {
  77. let Some(ticket) = weak.upgrade() else { return false };
  78. if matches(&ticket) {
  79. ticket.valid.store(false, Ordering::Release);
  80. }
  81. true
  82. });
  83. }
  84. pub(crate) fn released(owner: usize) {
  85. invalidate(|ticket| ticket.owner == owner);
  86. }
  87. pub(crate) fn replaced(at: usize) {
  88. invalidate(|ticket| ticket.at == at);
  89. }
  90. pub(crate) fn remapped(at: usize, len: usize) {
  91. let end = at.saturating_add(len);
  92. invalidate(|ticket| at < ticket.end && ticket.at < end);
  93. }
  94. pub(crate) struct Target {
  95. pub(crate) copy: Arc<crate::resource::HostTexture>,
  96. layout: victory_formats::texture::Layout,
  97. ticket: Arc<Ticket>,
  98. }
  99. impl Target {
  100. pub(crate) fn new(resource: This) -> Option<Self> {
  101. // Keep the host copy independently of the title's resource lifetime.
  102. let copy = crate::resource::host_copy(resource)?;
  103. let _mapping = crate::watch::title_memory_reading();
  104. let (layout, at, size) = crate::resource::title_texture(resource)?;
  105. let end = at.checked_add(size).filter(|&end| at != 0 && end > at)?;
  106. let ticket = track(resource as usize, at, end);
  107. Some(Self { copy, layout, ticket })
  108. }
  109. pub(crate) fn owner(&self) -> usize { self.ticket.owner }
  110. }
  111. /// The readback resources and the allocation the pixels belong to.
  112. pub(crate) struct Back {
  113. buffer: ID3D12Resource,
  114. footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>,
  115. rows: Vec<u32>,
  116. mips: u32,
  117. layout: victory_formats::texture::Layout,
  118. ticket: Arc<Ticket>,
  119. }
  120. impl Back {
  121. pub(crate) fn range(&self) -> (usize, usize) {
  122. (self.ticket.at, self.ticket.end)
  123. }
  124. }
  125. /// Records a host copy from a texture already in COPY_SOURCE.
  126. pub(crate) fn record(list: &ID3D12GraphicsCommandList, target: Target) -> Option<Back> {
  127. if !target.ticket.valid.load(Ordering::Acquire) {
  128. return None;
  129. }
  130. let host = crate::host::host()?;
  131. let texture = &target.copy.texture;
  132. // SAFETY: a live texture kept through the command list's state tracking.
  133. let desc = unsafe { texture.GetDesc() };
  134. let mips = u32::from(desc.MipLevels.max(1));
  135. let subresources = mips * u32::from(desc.DepthOrArraySize.max(1));
  136. let n = subresources as usize;
  137. let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); n];
  138. let mut rows = vec![0u32; n];
  139. let mut total = 0u64;
  140. // SAFETY: out arrays of `n` entries.
  141. unsafe {
  142. host.device.GetCopyableFootprints(
  143. &desc,
  144. 0,
  145. subresources,
  146. 0,
  147. Some(footprints.as_mut_ptr()),
  148. Some(rows.as_mut_ptr()),
  149. None,
  150. Some(&mut total),
  151. )
  152. };
  153. // The last footprint's advertised extent can omit row-end padding.
  154. // The tiler reads a pitched slice, so the mapped buffer must include it.
  155. for (footprint, &rows) in footprints.iter().zip(&rows) {
  156. let format = footprint.Footprint;
  157. let pitched = u64::from(format.RowPitch)
  158. .checked_mul(u64::from(rows))?
  159. .checked_mul(u64::from(format.Depth))?;
  160. total = total.max(footprint.Offset.checked_add(pitched)?);
  161. }
  162. let buffer = host.read_back_buffer(total)?;
  163. for (i, footprint) in footprints.iter().enumerate() {
  164. let to = D3D12_TEXTURE_COPY_LOCATION {
  165. // SAFETY: a borrowed pointer the location never releases.
  166. pResource: unsafe { std::mem::transmute_copy(&buffer) },
  167. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  168. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *footprint },
  169. };
  170. let from = D3D12_TEXTURE_COPY_LOCATION {
  171. // SAFETY: as above.
  172. pResource: unsafe { std::mem::transmute_copy(texture) },
  173. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  174. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: i as u32 },
  175. };
  176. // SAFETY: an open list; the texture is in the copy-source state.
  177. unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
  178. }
  179. Some(Back { buffer, footprints, rows, mips, layout: target.layout, ticket: target.ticket })
  180. }
  181. /// Once the list has run, tile its texels back into the same title allocation.
  182. pub(crate) fn land(back: &Back) {
  183. static COPIED: AtomicU64 = AtomicU64::new(0);
  184. static STALE: AtomicU64 = AtomicU64::new(0);
  185. let _mapping = crate::watch::title_memory_reading();
  186. let _ticket_guard = TICKETS.lock().unwrap_or_else(|e| e.into_inner());
  187. if !back.ticket.valid.load(Ordering::Acquire) {
  188. let skipped = STALE.fetch_add(1, Ordering::Relaxed) + 1;
  189. if skipped.is_power_of_two() {
  190. tracing::info!(skipped, "skipping texture readbacks whose title allocation changed");
  191. }
  192. return;
  193. }
  194. let (at, end) = back.range();
  195. let size = end - at;
  196. let mut tiled = vec![0u8; size];
  197. // Keep title bytes the subresources do not cover.
  198. if !crate::host::read_into(at as *const u8, &mut tiled) {
  199. return;
  200. }
  201. let mut data = std::ptr::null_mut();
  202. // SAFETY: our read-back buffer, written by the list that has run.
  203. unsafe {
  204. if back.buffer.Map(0, None, Some(&mut data)).is_err() || data.is_null() {
  205. return;
  206. }
  207. }
  208. for (i, (footprint, &rows)) in back.footprints.iter().zip(&back.rows).enumerate() {
  209. let (mip, slice) = (i as u32 % back.mips, i as u32 / back.mips);
  210. let f = footprint.Footprint;
  211. let pitch = f.RowPitch as usize;
  212. let len = pitch * rows as usize * f.Depth as usize;
  213. // SAFETY: the subresource's part of the mapped buffer.
  214. let linear = unsafe { std::slice::from_raw_parts(data.cast::<u8>().add(footprint.Offset as usize), len) };
  215. if let Err(e) = back.layout.tile(&mut tiled, mip, slice, linear, pitch, pitch * rows as usize) {
  216. static ONCE: std::sync::Once = std::sync::Once::new();
  217. ONCE.call_once(|| tracing::warn!(?e, mip, slice, "a texture copied back could not be tiled"));
  218. // SAFETY: mapped above.
  219. unsafe { back.buffer.Unmap(0, None) };
  220. return;
  221. }
  222. }
  223. // SAFETY: mapped above.
  224. unsafe { back.buffer.Unmap(0, None) };
  225. crate::host::copy_mapped(at as *mut u8, tiled.as_ptr(), size, true);
  226. let copied = COPIED.fetch_add(1, Ordering::Relaxed) + 1;
  227. if copied == 1 || copied.is_multiple_of(128) {
  228. tracing::info!(copied, bytes = size, "texture readback landed");
  229. }
  230. }
  231. #[cfg(test)]
  232. mod tests {
  233. use super::*;
  234. #[test]
  235. fn only_readbacks_for_changed_allocations_are_invalidated() {
  236. let first = track(91, 0x1000, 0x2000);
  237. let next = track(92, 0x2000, 0x3000);
  238. let far = track(93, 0x4000, 0x5000);
  239. remapped(0x0f00, 0x200);
  240. assert!(!first.valid.load(Ordering::Acquire));
  241. assert!(next.valid.load(Ordering::Acquire));
  242. replaced(0x2000);
  243. assert!(!next.valid.load(Ordering::Acquire));
  244. assert!(far.valid.load(Ordering::Acquire));
  245. released(93);
  246. assert!(!far.valid.load(Ordering::Acquire));
  247. assert!(track(94, 0x2000, 0x3000).valid.load(Ordering::Acquire));
  248. }
  249. }