2
0

capture.rs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. //! Presented frames written to PNG files, to see what reaches the screen:
  2. //! with `VICTORY_CAPTURE=<folder>`, every frame whose number is a power of
  3. //! two (the frames the log reports) is saved as `frame-<n>.png`, at half
  4. //! size. Only in builds with diagnostics.
  5. use std::path::PathBuf;
  6. use windows::Win32::Graphics::Direct3D12::*;
  7. use windows::Win32::Graphics::Dxgi::Common::*;
  8. /// The folder frames go to, if capturing.
  9. pub(crate) fn folder() -> Option<&'static PathBuf> {
  10. static FOLDER: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new();
  11. FOLDER
  12. .get_or_init(|| std::env::var_os("VICTORY_CAPTURE").map(PathBuf::from))
  13. .as_ref()
  14. }
  15. /// Frames listed in `VICTORY_CAPTURE_FRAMES` (comma-separated): saved
  16. /// too, and their draws traced at debug level.
  17. pub(crate) fn listed(n: u64) -> bool {
  18. static LIST: std::sync::OnceLock<Vec<u64>> = std::sync::OnceLock::new();
  19. let named = LIST
  20. .get_or_init(|| {
  21. let list = std::env::var("VICTORY_CAPTURE_FRAMES").unwrap_or_default();
  22. list.split(',')
  23. .filter_map(|f| f.trim().parse().ok())
  24. .collect()
  25. })
  26. .contains(&n);
  27. // `VICTORY_CAPTURE_WORLD`: also the 2nd and the 6th frame after the first
  28. // one that ran 500 draws or more (a title's first 3D frames: their
  29. // numbers depend on how long the menus were shown), and the 30th and
  30. // the 80th (the title opens with a cutscene made in the
  31. // engine: later shots of it, in case the first is dark by design).
  32. //
  33. // `VICTORY_CAPTURE_WORLD_ALSO` (comma-separated): more frames counted
  34. // from that first one (the title's blue patches show from
  35. // about the 118th frame on, when the window's model has arrived and
  36. // the reflections hold values: none of the four above has them).
  37. static ALSO: std::sync::OnceLock<Vec<u64>> = std::sync::OnceLock::new();
  38. let also = ALSO.get_or_init(|| {
  39. let list = std::env::var("VICTORY_CAPTURE_WORLD_ALSO").unwrap_or_default();
  40. list.split(',')
  41. .filter_map(|f| f.trim().parse().ok())
  42. .collect()
  43. });
  44. let first = WORLD.load(std::sync::atomic::Ordering::Relaxed);
  45. let after = n.wrapping_sub(first);
  46. named || first != u64::MAX && ([2, 6, 30, 80].contains(&after) || also.contains(&after))
  47. }
  48. /// With a capture folder, for the frames [`listed`]: `what` is added to
  49. /// the frame's `frame-<n>-ops.txt`, one line per draw, dispatch, copy or
  50. /// drop in the order recorded (the title records on several threads, so
  51. /// lines of different lists interleave; each names its list). The file
  52. /// says which pass writes which target, to find the pass whose output
  53. /// stays empty.
  54. #[cfg(feature = "diagnostics")]
  55. pub(crate) fn op(list: usize, what: impl FnOnce() -> String) {
  56. use std::io::Write;
  57. let frame = crate::queue::presented() + 1;
  58. if !listed(frame) {
  59. // Before the world: the last lines are kept, and written out when
  60. // it starts (`before-world-ops.txt`): what the title drew just
  61. // before (the title shows a title card there, whose text
  62. // did not show).
  63. if world_on() && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX {
  64. // At most 300 lines of a frame: the world's first frame alone
  65. // (thousands of operations, recorded before it is known to be
  66. // the world's) pushed everything before it out.
  67. static IN_FRAME: std::sync::Mutex<(u64, u32)> = std::sync::Mutex::new((0, 0));
  68. {
  69. let mut in_frame = IN_FRAME.lock().unwrap_or_else(|e| e.into_inner());
  70. if in_frame.0 != frame {
  71. *in_frame = (frame, 0);
  72. }
  73. in_frame.1 += 1;
  74. if in_frame.1 > 300 {
  75. return;
  76. }
  77. }
  78. let what = what();
  79. let mut ring = RING.lock().unwrap_or_else(|e| e.into_inner());
  80. if ring.len() >= RING_LINES {
  81. ring.pop_front();
  82. }
  83. ring.push_back(format!("frame {frame} list {list:#x} {what}"));
  84. }
  85. return;
  86. }
  87. let Some(folder) = folder() else {
  88. return;
  89. };
  90. static FILE: std::sync::Mutex<Option<(u64, u64, std::fs::File)>> = std::sync::Mutex::new(None);
  91. let what = what();
  92. let mut file = FILE.lock().unwrap_or_else(|e| e.into_inner());
  93. if file.as_ref().is_none_or(|f| f.0 != frame) {
  94. let Ok(made) = std::fs::File::create(folder.join(format!("frame-{frame}-ops.txt"))) else {
  95. return;
  96. };
  97. *file = Some((frame, 0, made));
  98. }
  99. if let Some((_, n, f)) = file.as_mut() {
  100. *n += 1;
  101. let _ = writeln!(f, "{n} list {list:#x} {what}");
  102. }
  103. }
  104. /// The last lines of [`op`] before the world.
  105. #[cfg(feature = "diagnostics")]
  106. static RING: std::sync::Mutex<std::collections::VecDeque<String>> =
  107. std::sync::Mutex::new(std::collections::VecDeque::new());
  108. #[cfg(feature = "diagnostics")]
  109. const RING_LINES: usize = 6000;
  110. /// Whether `VICTORY_CAPTURE_WORLD` is set.
  111. fn world_on() -> bool {
  112. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  113. *ON.get_or_init(|| std::env::var_os("VICTORY_CAPTURE_WORLD").is_some())
  114. }
  115. /// The first frame that ran 500 draws or more (`VICTORY_CAPTURE_WORLD`).
  116. static WORLD: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX);
  117. /// At the present of `frame`: the draws run on the host so far.
  118. pub(crate) fn frame_drew(frame: u64, drawn: u64) {
  119. use std::sync::atomic::Ordering::Relaxed;
  120. static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  121. let before = LAST.swap(drawn, Relaxed);
  122. if world_on()
  123. && drawn.saturating_sub(before) >= 500
  124. && WORLD.compare_exchange(u64::MAX, frame, Relaxed, Relaxed).is_ok()
  125. {
  126. tracing::info!(frame, "the first frame of 500 draws or more: frames {} and {} are captured", frame + 2, frame + 6);
  127. #[cfg(feature = "diagnostics")]
  128. if let Some(folder) = folder() {
  129. let lines: Vec<String> = std::mem::take(&mut *RING.lock().unwrap_or_else(|e| e.into_inner())).into();
  130. let _ = std::fs::write(folder.join("before-world-ops.txt"), lines.join("
  131. "));
  132. }
  133. }
  134. }
  135. /// Whether frame `n` is saved.
  136. pub(crate) fn wanted(n: u64) -> bool {
  137. // Before the world, with `VICTORY_CAPTURE_WORLD`: every 16th frame too
  138. // (small pictures of menus, loading screens and title cards).
  139. let before_world = world_on() && n.is_multiple_of(16) && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX;
  140. // In the world: every 8th frame's picture, a timeline of the opening
  141. // cutscene (its shots do not fall on the same frame numbers from run to
  142. // run, so single frames cannot be compared between runs).
  143. let first = WORLD.load(std::sync::atomic::Ordering::Relaxed);
  144. let in_world = world_on() && first != u64::MAX && n > first && (n - first).is_multiple_of(8);
  145. folder().is_some() && (n.is_power_of_two() || listed(n) || before_world || in_world)
  146. }
  147. /// Saves 8-bit RGBA or BGRA rows (`pitch` bytes apart) as frame `n`.
  148. pub(crate) fn save(n: u64, width: u32, height: u32, pitch: usize, bgra: bool, rows: &[u8]) {
  149. save_as(&format!("frame-{n}"), width, height, pitch, bgra, rows);
  150. }
  151. /// Saves 8-bit RGBA or BGRA rows as `<name>.png`, at half size.
  152. fn save_as(name: &str, width: u32, height: u32, pitch: usize, bgra: bool, rows: &[u8]) {
  153. let Some(folder) = folder() else { return };
  154. let (w, h) = ((width / 2).max(1), (height / 2).max(1));
  155. // Filter byte 0 per row, then RGB of every other pixel of every other row.
  156. let mut raw = Vec::with_capacity((w as usize * 3 + 1) * h as usize);
  157. for y in 0..h as usize {
  158. raw.push(0);
  159. let row = &rows[(2 * y).min(height as usize - 1) * pitch..];
  160. for x in 0..w as usize {
  161. let p = &row[(2 * x).min(width as usize - 1) * 4..][..3];
  162. if bgra {
  163. raw.extend([p[2], p[1], p[0]]);
  164. } else {
  165. raw.extend_from_slice(p);
  166. }
  167. }
  168. }
  169. let png = encode(w, h, &raw);
  170. let path = folder.join(format!("{name}.png"));
  171. match std::fs::write(&path, png) {
  172. Ok(()) => tracing::info!(path = %path.display(), "frame saved"),
  173. Err(e) => tracing::warn!(error = %e, path = %path.display(), "frame not saved"),
  174. }
  175. }
  176. /// A PNG of `width * height` pixels of 8-bit RGB.
  177. pub(crate) fn png(width: u32, height: u32, rgb: &[u8]) -> Vec<u8> {
  178. let row = width as usize * 3;
  179. let mut raw = Vec::with_capacity((row + 1) * height as usize);
  180. for line in rgb.chunks_exact(row.max(1)) {
  181. raw.push(0);
  182. raw.extend_from_slice(line);
  183. }
  184. encode(width, height, &raw)
  185. }
  186. /// A PNG of rows of RGB, each behind its filter byte.
  187. fn encode(w: u32, h: u32, raw: &[u8]) -> Vec<u8> {
  188. let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
  189. let mut header = Vec::new();
  190. header.extend(w.to_be_bytes());
  191. header.extend(h.to_be_bytes());
  192. header.extend([8, 2, 0, 0, 0]); // 8-bit RGB
  193. chunk(&mut png, b"IHDR", &header);
  194. let mut compressed = vec![0u8; zlib_rs::compress_bound(raw.len())];
  195. let (idat, rc) = zlib_rs::compress_slice(&mut compressed, raw, zlib_rs::DeflateConfig::new(3));
  196. debug_assert_eq!(rc, zlib_rs::ReturnCode::Ok);
  197. chunk(&mut png, b"IDAT", idat);
  198. chunk(&mut png, b"IEND", &[]);
  199. png
  200. }
  201. fn chunk(png: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
  202. png.extend((data.len() as u32).to_be_bytes());
  203. let start = png.len();
  204. png.extend(kind);
  205. png.extend(data);
  206. let crc = crc32(&png[start..]);
  207. png.extend(crc.to_be_bytes());
  208. }
  209. fn crc32(bytes: &[u8]) -> u32 {
  210. let mut crc = !0u32;
  211. for &b in bytes {
  212. crc ^= u32::from(b);
  213. for _ in 0..8 {
  214. crc = (crc >> 1) ^ (0xedb8_8320 & (crc & 1).wrapping_neg());
  215. }
  216. }
  217. !crc
  218. }
  219. /// Records a copy of `texture` (in the copy-source state) into a
  220. /// readback buffer.
  221. pub(crate) fn read_back(
  222. device: &ID3D12Device,
  223. list: &ID3D12GraphicsCommandList,
  224. texture: &ID3D12Resource,
  225. ) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> {
  226. read_back_of(device, list, texture, 0)
  227. }
  228. /// As [`read_back`], of subresource `sub` (the stencil plane of a
  229. /// one-level, one-slice depth-stencil texture is subresource 1).
  230. fn read_back_of(
  231. device: &ID3D12Device,
  232. list: &ID3D12GraphicsCommandList,
  233. texture: &ID3D12Resource,
  234. sub: u32,
  235. ) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> {
  236. let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
  237. let mut total = 0;
  238. // SAFETY: a live texture; outputs for one subresource.
  239. unsafe {
  240. let desc = texture.GetDesc();
  241. device.GetCopyableFootprints(
  242. &desc,
  243. sub,
  244. 1,
  245. 0,
  246. Some(&mut footprint),
  247. None,
  248. None,
  249. Some(&mut total),
  250. );
  251. }
  252. let heap = D3D12_HEAP_PROPERTIES {
  253. Type: D3D12_HEAP_TYPE_READBACK,
  254. ..Default::default()
  255. };
  256. let desc = D3D12_RESOURCE_DESC {
  257. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  258. Width: total,
  259. Height: 1,
  260. DepthOrArraySize: 1,
  261. MipLevels: 1,
  262. SampleDesc: DXGI_SAMPLE_DESC {
  263. Count: 1,
  264. Quality: 0,
  265. },
  266. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  267. ..Default::default()
  268. };
  269. let mut buffer: Option<ID3D12Resource> = None;
  270. // SAFETY: plain creation; an open list; locations naming live resources.
  271. unsafe {
  272. device
  273. .CreateCommittedResource(
  274. &heap,
  275. D3D12_HEAP_FLAG_NONE,
  276. &desc,
  277. D3D12_RESOURCE_STATE_COPY_DEST,
  278. None,
  279. &mut buffer,
  280. )
  281. .ok()?;
  282. let buffer = buffer?;
  283. let to = D3D12_TEXTURE_COPY_LOCATION {
  284. pResource: std::mem::transmute_copy(&buffer),
  285. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  286. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  287. PlacedFootprint: footprint,
  288. },
  289. };
  290. let from = D3D12_TEXTURE_COPY_LOCATION {
  291. pResource: std::mem::transmute_copy(texture),
  292. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  293. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  294. SubresourceIndex: sub,
  295. },
  296. };
  297. list.CopyTextureRegion(&to, 0, 0, 0, &from, None);
  298. Some((buffer, footprint))
  299. }
  300. }
  301. /// Saves a frame read back by [`read_back`] (8-bit color only).
  302. pub(crate) fn save_read_back(
  303. frame: u64,
  304. buffer: &ID3D12Resource,
  305. footprint: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
  306. ) {
  307. let f = footprint.Footprint;
  308. let bgra = match f.Format {
  309. DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_R8G8B8A8_UNORM_SRGB => false,
  310. DXGI_FORMAT_B8G8R8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM_SRGB => true,
  311. other => {
  312. tracing::warn!(format = other.0, "frame not saved: not 8-bit color");
  313. return;
  314. }
  315. };
  316. let mut data = std::ptr::null_mut();
  317. // SAFETY: the copy finished (every submission is waited for); the
  318. // mapping spans the footprint's rows.
  319. unsafe {
  320. if buffer.Map(0, None, Some(&mut data)).is_err() {
  321. return;
  322. }
  323. let len = f.RowPitch as usize * f.Height as usize;
  324. let rows = std::slice::from_raw_parts(data.cast::<u8>(), len);
  325. save(frame, f.Width, f.Height, f.RowPitch as usize, bgra, rows);
  326. buffer.Unmap(0, None);
  327. }
  328. }
  329. /// With `VICTORY_DUMP_TARGETS` set: title textures the frames listed in
  330. /// `VICTORY_CAPTURE_FRAMES` render to or write, in first-use order, saved
  331. /// at that frame's present as `frame-<n>-<i>-<resource>-<w>x<h>-f<format>.png`
  332. /// (what each holds at the end of the frame; formats normalized to show
  333. /// structure: floats scaled by their largest value, depth by its range).
  334. /// The host copies are held: the title may release a target before the
  335. /// frame is presented.
  336. static TARGETS: std::sync::Mutex<Vec<(usize, std::sync::Arc<crate::resource::HostTexture>)>> =
  337. std::sync::Mutex::new(Vec::new());
  338. fn dump_on() -> bool {
  339. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  340. *ON.get_or_init(|| folder().is_some() && std::env::var_os("VICTORY_DUMP_TARGETS").is_some())
  341. }
  342. /// Notes a title texture the frame being built renders to or writes.
  343. pub(crate) fn note_target(resource: crate::object::This) {
  344. if resource.is_null() || !dump_on() || !listed(crate::queue::presented() + 1) {
  345. return;
  346. }
  347. let mut targets = TARGETS.lock().unwrap_or_else(|e| e.into_inner());
  348. if !targets.iter().any(|&(r, _)| r == resource as usize)
  349. && let Some(copy) = crate::resource::host_copy(resource)
  350. {
  351. targets.push((resource as usize, copy));
  352. }
  353. }
  354. /// At the present of frame `frame`: saves the noted targets.
  355. pub(crate) fn dump_targets(frame: u64) {
  356. use std::sync::atomic::Ordering::Relaxed;
  357. let targets = std::mem::take(&mut *TARGETS.lock().unwrap_or_else(|e| e.into_inner()));
  358. let Some(host) = crate::host::host() else { return };
  359. for (i, (resource, copy)) in targets.iter().enumerate() {
  360. let texture = &copy.texture;
  361. // SAFETY: a live resource.
  362. let d = unsafe { texture.GetDesc() };
  363. if d.SampleDesc.Count > 1 || d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D {
  364. continue;
  365. }
  366. // Every submission has run; the dump's list moves it there and back.
  367. let state = copy.state.load(Relaxed);
  368. dump_one(host, texture, state, frame, i, *resource as crate::object::This, &d);
  369. }
  370. }
  371. fn dump_one(
  372. host: &crate::host::Host,
  373. texture: &ID3D12Resource,
  374. state: u32,
  375. frame: u64,
  376. i: usize,
  377. resource: crate::object::This,
  378. d: &D3D12_RESOURCE_DESC,
  379. ) {
  380. let Ok(list) = host.new_list() else { return };
  381. let state = D3D12_RESOURCE_STATES(crate::host::legal_state(texture, state) as i32);
  382. let copy = D3D12_RESOURCE_STATE_COPY_SOURCE;
  383. // SAFETY: an open list of ours and a live texture.
  384. let read = unsafe {
  385. if state != copy {
  386. list.list
  387. .ResourceBarrier(&[crate::host::transition(texture, state, copy)]);
  388. }
  389. let read = read_back(&host.device, &list.list, texture);
  390. // The stencil plane of a depth-stencil target, which the title's
  391. // lighting reads (material class in the low bits; 0x08 "inside a
  392. // room", which the lamps of a room are multiplied by): the plane
  393. // after the depth plane of a one-level, one-slice texture.
  394. let stencil = (matches!(d.Format.0, 19..=22 | 44..=47)
  395. && d.MipLevels == 1
  396. && d.DepthOrArraySize == 1)
  397. .then(|| read_back_of(&host.device, &list.list, texture, 1))
  398. .flatten();
  399. if state != copy {
  400. list.list
  401. .ResourceBarrier(&[crate::host::transition(texture, copy, state)]);
  402. }
  403. (read, stencil)
  404. };
  405. let (read, stencil) = read;
  406. list.close();
  407. host.execute(&[&list]);
  408. if let Some((buffer, footprint)) = stencil {
  409. stencil_values(&buffer, &footprint, frame, resource);
  410. }
  411. let Some((buffer, footprint)) = read else { return };
  412. let f = footprint.Footprint;
  413. let mut data = std::ptr::null_mut();
  414. // SAFETY: the copy finished; the mapping spans the footprint's rows.
  415. unsafe {
  416. if buffer.Map(0, None, Some(&mut data)).is_err() {
  417. return;
  418. }
  419. let pitch = f.RowPitch as usize;
  420. let rows = std::slice::from_raw_parts(data.cast::<u8>(), pitch * f.Height as usize);
  421. // A 24-bit depth plane comes back as 32-bit words: which depth values
  422. // (low 24 bits) and which top bytes it holds, the most common first.
  423. if matches!(d.Format.0, 44..=47) {
  424. let mut depths = std::collections::HashMap::<u32, u32>::new();
  425. let mut tops = std::collections::HashMap::<u32, u32>::new();
  426. for y in 0..f.Height as usize {
  427. for x in 0..f.Width as usize {
  428. let at = y * pitch + x * 4;
  429. let w = u32::from_le_bytes(rows[at..at + 4].try_into().unwrap_or([0; 4]));
  430. *depths.entry(w & 0xff_ffff).or_default() += 1;
  431. *tops.entry(w >> 24).or_default() += 1;
  432. }
  433. }
  434. let most = |m: std::collections::HashMap<u32, u32>| {
  435. let mut v: Vec<(u32, u32)> = m.into_iter().collect();
  436. v.sort_by_key(|e| std::cmp::Reverse(e.1));
  437. (v.len(), v.into_iter().take(12).collect::<Vec<_>>())
  438. };
  439. tracing::info!(?resource, depths = ?most(depths), top_bytes = ?most(tops), "24-bit depth plane values (value, texels)");
  440. }
  441. if let Some(rgba) = to_rgba(f.Format.0 as u32, f.Width as usize, f.Height as usize, pitch, rows) {
  442. let name = format!(
  443. "frame-{frame}-{i:02}-{resource:?}-{}x{}-f{}",
  444. d.Width, d.Height, d.Format.0
  445. );
  446. save_as(&name, f.Width, f.Height, f.Width as usize * 4, false, &rgba);
  447. } else {
  448. tracing::info!(format = f.Format.0, ?resource, "target not dumped: format");
  449. }
  450. buffer.Unmap(0, None);
  451. }
  452. }
  453. /// Logs which values a stencil plane read back by [`read_back_of`] holds
  454. /// (the most common first), how many texels have each of its bits, and the
  455. /// box of the texels with bit 3 (0x08).
  456. fn stencil_values(
  457. buffer: &ID3D12Resource,
  458. footprint: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
  459. frame: u64,
  460. resource: crate::object::This,
  461. ) {
  462. let f = footprint.Footprint;
  463. let (w, h, pitch) = (f.Width as usize, f.Height as usize, f.RowPitch as usize);
  464. let mut data = std::ptr::null_mut();
  465. // SAFETY: the copy finished; the mapping spans the footprint's rows of
  466. // one byte a texel, the last row without its padding.
  467. unsafe {
  468. if h == 0 || w == 0 || buffer.Map(0, None, Some(&mut data)).is_err() {
  469. return;
  470. }
  471. let rows = std::slice::from_raw_parts(data.cast::<u8>(), pitch * (h - 1) + w);
  472. let mut values = [0u32; 256];
  473. let mut bits = [0u32; 8];
  474. // Left, top, right, bottom of the texels with bit 3.
  475. let mut inside = [u32::MAX, u32::MAX, 0, 0];
  476. for y in 0..h {
  477. for (x, &v) in rows[y * pitch..y * pitch + w].iter().enumerate() {
  478. values[usize::from(v)] += 1;
  479. for (bit, count) in bits.iter_mut().enumerate() {
  480. *count += u32::from(v >> bit & 1);
  481. }
  482. if v & 8 != 0 {
  483. inside = [
  484. inside[0].min(x as u32),
  485. inside[1].min(y as u32),
  486. inside[2].max(x as u32),
  487. inside[3].max(y as u32),
  488. ];
  489. }
  490. }
  491. }
  492. let mut most: Vec<(usize, u32)> = values
  493. .iter()
  494. .copied()
  495. .enumerate()
  496. .filter(|v| v.1 != 0)
  497. .collect();
  498. most.sort_by_key(|v| std::cmp::Reverse(v.1));
  499. most.truncate(16);
  500. tracing::info!(
  501. frame,
  502. ?resource,
  503. width = w,
  504. height = h,
  505. values = ?most,
  506. texels_with_bit = ?bits,
  507. bit3_box = ?inside,
  508. "stencil plane values (value, texels)"
  509. );
  510. buffer.Unmap(0, None);
  511. }
  512. }
  513. fn half(h: u16) -> f32 {
  514. let (sign, exp, man) = ((h >> 15) as u32, ((h >> 10) & 0x1f) as i32, (h & 0x3ff) as f32);
  515. let v = match exp {
  516. 0 => man * 2f32.powi(-24),
  517. 31 => f32::INFINITY,
  518. e => (1.0 + man / 1024.0) * 2f32.powi(e - 15),
  519. };
  520. if sign == 1 { -v } else { v }
  521. }
  522. /// A float packed in `bits` with a 5-bit exponent and `man` mantissa bits
  523. /// (the 11- and 10-bit floats of R11G11B10).
  524. fn small_float(bits: u32, man: u32) -> f32 {
  525. let (exp, m) = ((bits >> man) & 0x1f, (bits & ((1 << man) - 1)) as f32);
  526. match exp {
  527. 0 => m / (1 << man) as f32 * 2f32.powi(-14),
  528. 31 => f32::INFINITY,
  529. e => (1.0 + m / (1 << man) as f32) * 2f32.powi(e as i32 - 15),
  530. }
  531. }
  532. /// Rows of a host format as 8-bit RGBA: 8-bit color as is, everything else
  533. /// as channel values scaled so the largest finite one is white (single
  534. /// channels: lowest black, highest white, as grey). `None` for formats not
  535. /// handled.
  536. fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option<Vec<u8>> {
  537. let mut out = Vec::with_capacity(w * h * 4);
  538. let px = |x: usize, y: usize, n: usize| &rows[y * pitch + x * n..][..n];
  539. let u16_at = |b: &[u8], i: usize| u16::from_le_bytes([b[2 * i], b[2 * i + 1]]);
  540. let u32_at = |b: &[u8], i: usize| u32::from_le_bytes(b[4 * i..4 * i + 4].try_into().unwrap_or([0; 4]));
  541. // Channel values as floats, then scaled.
  542. type Decode = Box<dyn Fn(&[u8]) -> [f32; 3]>;
  543. let (n, decode): (usize, Decode) = match format {
  544. 27..=32 => {
  545. for y in 0..h {
  546. for x in 0..w {
  547. let p = px(x, y, 4);
  548. out.extend([p[0], p[1], p[2], 255]);
  549. }
  550. }
  551. return Some(out);
  552. }
  553. // B8G8R8A8 and B8G8R8X8 (89 is R10G10B10_XR_BIAS_A2, below).
  554. 87 | 88 | 90..=93 => {
  555. for y in 0..h {
  556. for x in 0..w {
  557. let p = px(x, y, 4);
  558. out.extend([p[2], p[1], p[0], 255]);
  559. }
  560. }
  561. return Some(out);
  562. }
  563. 23..=25 | 89 => (4, Box::new(move |b| {
  564. let v = u32_at(b, 0);
  565. [(v & 0x3ff) as f32, (v >> 10 & 0x3ff) as f32, (v >> 20 & 0x3ff) as f32]
  566. })),
  567. 26 => (4, Box::new(move |b| {
  568. let v = u32_at(b, 0);
  569. [small_float(v & 0x7ff, 6), small_float(v >> 11 & 0x7ff, 6), small_float(v >> 22, 5)]
  570. })),
  571. 9..=10 => (8, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))])),
  572. 11..=14 => (8, Box::new(move |b| [0, 1, 2].map(|i| f32::from(u16_at(b, i))))),
  573. 33..=34 => (4, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), 0.0])),
  574. 1..=2 => (16, Box::new(move |b| {
  575. [0, 1, 2].map(|i| f32::from_bits(u32_at(b, i)))
  576. })),
  577. 15..=16 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)), f32::from_bits(u32_at(b, 1)), 0.0])),
  578. 35..=38 => (4, Box::new(move |b| [f32::from(u16_at(b, 0)), f32::from(u16_at(b, 1)), 0.0])),
  579. 48..=52 => (2, Box::new(move |b| [f32::from(b[0]), f32::from(b[1]), 0.0])),
  580. // Single channels (and depth planes): shown as grey.
  581. 39..=43 => (4, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])),
  582. 19..=22 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])),
  583. 44..=47 => (4, Box::new(move |b| [(u32_at(b, 0) & 0xff_ffff) as f32; 3])),
  584. 53..=54 => (2, Box::new(move |b| [half(u16_at(b, 0)); 3])),
  585. 55..=59 => (2, Box::new(move |b| [f32::from(u16_at(b, 0)); 3])),
  586. 60..=65 => (1, Box::new(move |b| [f32::from(b[0]); 3])),
  587. _ => return None,
  588. };
  589. let values: Vec<[f32; 3]> = (0..h)
  590. .flat_map(|y| (0..w).map(move |x| (x, y)))
  591. .map(|(x, y)| decode(px(x, y, n)))
  592. .collect();
  593. let grey = matches!(format, 19..=22 | 39..=47 | 53..=65);
  594. let finite = values.iter().flatten().copied().filter(|v| v.is_finite());
  595. let (low, high) = if grey {
  596. finite.fold((f32::MAX, f32::MIN), |(l, h), v| (l.min(v), h.max(v)))
  597. } else {
  598. (0.0, finite.fold(0.0f32, f32::max))
  599. };
  600. let range = (high - low).max(1e-20);
  601. // How much of the target holds anything: a lit scene and one bright
  602. // lamp on black have the same highest value.
  603. let above = values.iter().filter(|v| v.iter().any(|c| c.is_finite() && *c > low)).count();
  604. let nonzero_percent = above as f32 * 100.0 / values.len().max(1) as f32;
  605. tracing::info!(format, low, high, nonzero_percent, "target values");
  606. // Small float colour targets (the 1x1 luminance and exposure targets):
  607. // every texel's four channels as numbers. The picture has no alpha and
  608. // eight bits a channel.
  609. if matches!(format, 1..=2 | 9..=10) && w * h <= 16 {
  610. for y in 0..h {
  611. for x in 0..w {
  612. let b = px(x, y, n);
  613. let texel: [f32; 4] = if n == 16 {
  614. [0, 1, 2, 3].map(|i| f32::from_bits(u32_at(b, i)))
  615. } else {
  616. [0, 1, 2, 3].map(|i| half(u16_at(b, i)))
  617. };
  618. tracing::info!(format, x, y, ?texel, "target texel");
  619. }
  620. }
  621. }
  622. // R32_UINT targets hold packed light (the title reads them back as
  623. // R9G9B9E5): as floats their low, high and share above the lowest say
  624. // nothing. How many texels hold any bit, and the highest channel value
  625. // of the packed reading.
  626. if format == 42 {
  627. let (mut set, mut packed_high) = (0usize, 0f32);
  628. for y in 0..h {
  629. for x in 0..w {
  630. let v = u32_at(px(x, y, 4), 0);
  631. set += usize::from(v != 0);
  632. let scale = 2f32.powi((v >> 27) as i32 - 24);
  633. for k in 0..3 {
  634. packed_high = packed_high.max((v >> (9 * k) & 0x1ff) as f32 * scale);
  635. }
  636. }
  637. }
  638. let nonzero_bits_percent = set as f32 * 100.0 / (w * h).max(1) as f32;
  639. tracing::info!(format, nonzero_bits_percent, packed_high, "target values as packed light");
  640. // The same words as plain numbers, by class. Tables of indices and
  641. // masks say nothing as floats or as packed light: in the title's
  642. // shadow-mask table 0 is a block in full shadow, a word up to 255
  643. // one value for the block, above that a block of the atlas, and all
  644. // ones a texel never written.
  645. let mut classes = [0usize; 6];
  646. let mut highest_below_ones = 0u32;
  647. for y in 0..h {
  648. for x in 0..w {
  649. let v = u32_at(px(x, y, 4), 0);
  650. classes[match v {
  651. 0 => 0,
  652. 1..=15 => 1,
  653. 16..=255 => 2,
  654. 256..=0x00ff_ffff => 3,
  655. u32::MAX => 5,
  656. _ => 4,
  657. }] += 1;
  658. if v != u32::MAX {
  659. highest_below_ones = highest_below_ones.max(v);
  660. }
  661. }
  662. }
  663. tracing::info!(
  664. format,
  665. width = w,
  666. height = h,
  667. zero = classes[0],
  668. one_to_15 = classes[1],
  669. to_255 = classes[2],
  670. to_24_bits = classes[3],
  671. larger = classes[4],
  672. all_ones = classes[5],
  673. highest_below_ones,
  674. "target values as words"
  675. );
  676. }
  677. // Float colours (scene light) go through a cube root: scaled linearly,
  678. // a night scene under one lamp of 50 units came out all black.
  679. let curved = matches!(format, 1..=2 | 9..=10 | 26);
  680. for v in values {
  681. let c = v.map(|c| {
  682. let t = ((c - low) / range).clamp(0.0, 1.0);
  683. ((if curved { t.cbrt() } else { t }) * 255.0) as u8
  684. });
  685. out.extend([c[0], c[1], c[2], 255]);
  686. }
  687. Some(out)
  688. }
  689. /// Pixels per side of the grid [`probe`] reads.
  690. const GRID: u32 = 4;
  691. /// Bytes between the grid's pixels in the readback buffer (placement
  692. /// alignment).
  693. const SLOT: u64 = 512;
  694. /// Records copies of a grid of pixels of `texture` (8-bit color, in the
  695. /// copy-source state) into a readback buffer, to tell black frames.
  696. pub(crate) fn probe(
  697. device: &ID3D12Device,
  698. list: &ID3D12GraphicsCommandList,
  699. texture: &ID3D12Resource,
  700. ) -> Option<ID3D12Resource> {
  701. // SAFETY: a live resource.
  702. let d = unsafe { texture.GetDesc() };
  703. if !matches!(d.Format.0, 27..=29 | 87 | 90 | 91) {
  704. return None;
  705. }
  706. let desc = D3D12_RESOURCE_DESC {
  707. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  708. Width: SLOT * u64::from(GRID * GRID),
  709. Height: 1,
  710. DepthOrArraySize: 1,
  711. MipLevels: 1,
  712. SampleDesc: DXGI_SAMPLE_DESC {
  713. Count: 1,
  714. Quality: 0,
  715. },
  716. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  717. ..Default::default()
  718. };
  719. let heap = D3D12_HEAP_PROPERTIES {
  720. Type: D3D12_HEAP_TYPE_READBACK,
  721. ..Default::default()
  722. };
  723. let mut buffer: Option<ID3D12Resource> = None;
  724. // SAFETY: plain creation; an open list; locations naming live resources.
  725. unsafe {
  726. device
  727. .CreateCommittedResource(
  728. &heap,
  729. D3D12_HEAP_FLAG_NONE,
  730. &desc,
  731. D3D12_RESOURCE_STATE_COPY_DEST,
  732. None,
  733. &mut buffer,
  734. )
  735. .ok()?;
  736. let buffer = buffer?;
  737. for i in 0..GRID * GRID {
  738. let (x, y) = (
  739. (2 * (i % GRID) + 1) * d.Width as u32 / (2 * GRID),
  740. (2 * (i / GRID) + 1) * d.Height / (2 * GRID),
  741. );
  742. let to = D3D12_TEXTURE_COPY_LOCATION {
  743. pResource: std::mem::transmute_copy(&buffer),
  744. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  745. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  746. PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
  747. Offset: SLOT * u64::from(i),
  748. Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
  749. Format: d.Format,
  750. Width: 1,
  751. Height: 1,
  752. Depth: 1,
  753. RowPitch: 256,
  754. },
  755. },
  756. },
  757. };
  758. let from = D3D12_TEXTURE_COPY_LOCATION {
  759. pResource: std::mem::transmute_copy(texture),
  760. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  761. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  762. SubresourceIndex: 0,
  763. },
  764. };
  765. let pixel = D3D12_BOX {
  766. left: x,
  767. top: y,
  768. front: 0,
  769. right: x + 1,
  770. bottom: y + 1,
  771. back: 1,
  772. };
  773. list.CopyTextureRegion(&to, 0, 0, 0, &from, Some(&pixel));
  774. }
  775. Some(buffer)
  776. }
  777. }
  778. /// Whether every pixel [`probe`] read is (near) black.
  779. pub(crate) fn black(buffer: &ID3D12Resource) -> bool {
  780. let mut data = std::ptr::null_mut();
  781. // SAFETY: the copies finished (every submission is waited for).
  782. unsafe {
  783. if buffer.Map(0, None, Some(&mut data)).is_err() {
  784. return false;
  785. }
  786. let bytes =
  787. std::slice::from_raw_parts(data.cast::<u8>(), (SLOT * u64::from(GRID * GRID)) as usize);
  788. let level = bytes
  789. .chunks(SLOT as usize)
  790. .flat_map(|pixel| pixel[..3].iter().copied())
  791. .max()
  792. .unwrap_or(0);
  793. buffer.Unmap(0, None);
  794. let mut levels = LEVELS.lock().unwrap_or_else(|e| e.into_inner());
  795. if levels.len() == 12 {
  796. levels.pop_front();
  797. }
  798. levels.push_back(level);
  799. level < 8
  800. }
  801. }
  802. /// The brightest probed channel of the last frames, oldest first: a fade
  803. /// darkens over several, a glitch drops at once.
  804. static LEVELS: std::sync::Mutex<std::collections::VecDeque<u8>> =
  805. std::sync::Mutex::new(std::collections::VecDeque::new());
  806. pub(crate) fn recent_levels() -> Vec<u8> {
  807. let levels = LEVELS.lock().unwrap_or_else(|e| e.into_inner());
  808. levels.iter().copied().collect()
  809. }
  810. #[cfg(test)]
  811. mod tests {
  812. #[test]
  813. fn crc_matches_the_png_check_value() {
  814. assert_eq!(super::crc32(b"IEND"), 0xae42_6082);
  815. }
  816. /// R16G16B16A16_UNORM is integers, not half floats; 89 is 10:10:10:2,
  817. /// not B8G8R8A8.
  818. #[test]
  819. fn unorm16_and_xr_bias_targets_decode_as_their_formats() {
  820. // Red 0x8000 (a half-float -0), green 0x4000, blue 0.
  821. let unorm16 = [0x00, 0x80, 0x00, 0x40, 0, 0, 0xff, 0xff];
  822. assert_eq!(super::to_rgba(11, 1, 1, 8, &unorm16), Some(vec![255, 127, 0, 255]));
  823. // Red 0x3ff, green 0x1ff, blue 0, alpha 3.
  824. let xr = (0x3ffu32 | 0x1ff << 10 | 3 << 30).to_le_bytes();
  825. assert_eq!(super::to_rgba(89, 1, 1, 4, &xr), Some(vec![255, 127, 0, 255]));
  826. // B8G8R8A8 still swaps to RGBA.
  827. assert_eq!(super::to_rgba(87, 1, 1, 4, &[1, 2, 3, 4]), Some(vec![3, 2, 1, 255]));
  828. }
  829. }