play.rs 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034
  1. //! The replayer: makes a captured frame's objects again, puts their
  2. //! contents back, and runs the frame as often as asked, with its time on
  3. //! the card and experiments on it (`super::edit`).
  4. use std::collections::{BTreeMap, HashMap, HashSet};
  5. use std::fmt::Write as _;
  6. use std::fs::File;
  7. use std::os::windows::fs::FileExt;
  8. use std::path::{Path, PathBuf};
  9. use std::sync::atomic::{AtomicUsize, Ordering};
  10. use std::time::Instant;
  11. use anyhow::{Context, Result, anyhow, bail};
  12. use windows::Win32::Foundation::RECT;
  13. use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY};
  14. use windows::Win32::Graphics::Direct3D12::*;
  15. use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
  16. use windows::Win32::Graphics::Dxgi::*;
  17. use windows::core::Interface;
  18. use super::edit::{self, Clamp, RESULTS};
  19. use super::gpu::{self, Seen, Worker};
  20. use super::snap::read_sub;
  21. use super::states::{
  22. self, COMMON, COPY_DEST, COPY_SOURCE, DEPTH_WRITE, RENDER_TARGET, RESOLVE_DEST, States,
  23. UNORDERED_ACCESS,
  24. };
  25. use super::wire::{
  26. self, ALL, Barrier, Cmd, Content, Delta, Frame, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot,
  27. };
  28. pub mod diverge;
  29. /// The name of the argument clamp's pipeline, by which its passes are
  30. /// recognised.
  31. pub const CLAMP: &str = "victory: argument clamp";
  32. /// The name of the pipeline that compares and hashes card buffers.
  33. pub const COMPARE: &str = "victory: card compare";
  34. /// An upload buffer contents come back through.
  35. const STAGING: u64 = 256 << 20;
  36. /// Where buffers the CPU saw lie in a replay.
  37. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
  38. pub enum Buffers {
  39. /// Where they lay.
  40. #[default]
  41. AsRecorded,
  42. /// All in the card's memory.
  43. Card,
  44. /// All in the PC's memory, the card's own buffers too.
  45. Pc,
  46. }
  47. #[derive(Clone, Debug)]
  48. pub struct Options {
  49. pub loops: u32,
  50. /// Put back, before each run, what the run before changed.
  51. pub restore: bool,
  52. /// Time every command, not only lists.
  53. pub detailed: bool,
  54. /// Shaders listed.
  55. pub top: usize,
  56. /// Where the picture goes (default: `replay.png` in the capture).
  57. pub image: Option<PathBuf>,
  58. pub buffers: Buffers,
  59. pub no_barriers: bool,
  60. pub merge_barriers: bool,
  61. pub skip_clamps: bool,
  62. pub skip_hash_passes: bool,
  63. pub one_submit: bool,
  64. /// A full wait after every command that works.
  65. pub wait_all: bool,
  66. /// Each list sent on its own, and waited for.
  67. pub wait_lists: bool,
  68. /// Run only these lists (by their place in the frame).
  69. pub only: Option<(u32, u32)>,
  70. /// Skip what runs a pipeline whose name or shader hash has one of
  71. /// these in it.
  72. pub skip_shaders: Vec<String>,
  73. /// Run the frame unchanged first, and compare.
  74. pub compare: bool,
  75. /// The debug layer, if it is installed.
  76. pub debug: bool,
  77. }
  78. impl Default for Options {
  79. fn default() -> Self {
  80. Options {
  81. loops: 5,
  82. restore: true,
  83. detailed: false,
  84. top: 20,
  85. image: None,
  86. buffers: Buffers::AsRecorded,
  87. no_barriers: false,
  88. merge_barriers: false,
  89. skip_clamps: false,
  90. skip_hash_passes: false,
  91. one_submit: false,
  92. wait_all: false,
  93. wait_lists: false,
  94. only: None,
  95. skip_shaders: Vec::new(),
  96. compare: false,
  97. debug: false,
  98. }
  99. }
  100. }
  101. impl Options {
  102. fn edited(&self) -> bool {
  103. self.no_barriers
  104. || self.merge_barriers
  105. || self.skip_clamps
  106. || self.skip_hash_passes
  107. || self.one_submit
  108. || self.wait_all
  109. || self.wait_lists
  110. || self.only.is_some()
  111. || !self.skip_shaders.is_empty()
  112. }
  113. /// The same without the experiments.
  114. fn plain(&self) -> Options {
  115. Options {
  116. no_barriers: false,
  117. merge_barriers: false,
  118. skip_clamps: false,
  119. skip_hash_passes: false,
  120. one_submit: false,
  121. wait_all: false,
  122. wait_lists: false,
  123. only: None,
  124. skip_shaders: Vec::new(),
  125. ..self.clone()
  126. }
  127. }
  128. }
  129. /// How a run went.
  130. #[derive(Clone, Debug, Default)]
  131. pub struct Report {
  132. /// Per loop: from the first list's start to the last one's end, in ms.
  133. pub frame_ms: Vec<f64>,
  134. /// Per loop: how long the lists of submissions ran.
  135. pub busy_ms: Vec<f64>,
  136. /// Per loop: copies of ours that stand for what the CPU wrote.
  137. pub delta_ms: Vec<f64>,
  138. /// Of the last loop, by submission: lists, ms.
  139. pub submits: Vec<(usize, f64)>,
  140. /// With detailed timing, of the last loop: ms and count by category.
  141. pub categories: Vec<(String, f64, u32)>,
  142. /// With detailed timing: ms, count and name of the costliest pipelines.
  143. pub shaders: Vec<(f64, u32, String)>,
  144. /// Against the presented picture: dB (infinite: the same), and whether
  145. /// its bytes are the same.
  146. pub picture: Option<(f64, bool)>,
  147. /// Of each loop's picture: dB against the presented one, and its hash.
  148. pub pictures: Vec<(f64, String)>,
  149. /// Things to know: from the capture and the replay.
  150. pub notes: Vec<String>,
  151. }
  152. impl Report {
  153. pub fn median_ms(&self) -> f64 {
  154. median(&self.frame_ms)
  155. }
  156. /// The report as text.
  157. pub fn text(&self, what: &str) -> String {
  158. let mut t = String::new();
  159. let ms = |v: &[f64]| {
  160. v.iter()
  161. .map(|x| format!("{x:.2}"))
  162. .collect::<Vec<_>>()
  163. .join(" ")
  164. };
  165. let _ = writeln!(
  166. t,
  167. "{what}: {:.2} ms on the card (median of {})",
  168. self.median_ms(),
  169. self.frame_ms.len()
  170. );
  171. let _ = writeln!(t, " loops, ms: {}", ms(&self.frame_ms));
  172. let (busy, delta) = (median(&self.busy_ms), median(&self.delta_ms));
  173. let idle = (self.median_ms() - busy - delta).max(0.0);
  174. let _ = writeln!(
  175. t,
  176. " submissions busy {busy:.2} ms, copies standing for CPU writes {delta:.2} ms, between submissions {idle:.2} ms"
  177. );
  178. let _ = writeln!(t, " by submission (lists: ms): {}", {
  179. self.submits
  180. .iter()
  181. .enumerate()
  182. .map(|(i, (n, ms))| format!("{i} ({n}): {ms:.2}"))
  183. .collect::<Vec<_>>()
  184. .join(", ")
  185. });
  186. if !self.categories.is_empty() {
  187. let _ = writeln!(t, " by kind of command, ms (commands):");
  188. for (name, ms, n) in &self.categories {
  189. let _ = writeln!(t, " {ms:8.2} {n:6} {name}");
  190. }
  191. }
  192. if !self.shaders.is_empty() {
  193. let _ = writeln!(t, " costliest pipelines, ms (commands):");
  194. for (ms, n, name) in &self.shaders {
  195. let _ = writeln!(t, " {ms:8.2} {n:6} {name}");
  196. }
  197. }
  198. match self.picture {
  199. Some((_, true)) => _ = writeln!(t, " picture: the same bytes as presented"),
  200. Some((db, false)) => {
  201. _ = writeln!(
  202. t,
  203. " picture: differs from the presented one, PSNR {db:.1} dB"
  204. )
  205. }
  206. None => {}
  207. }
  208. if self.pictures.len() > 1 {
  209. let all: Vec<String> = self
  210. .pictures
  211. .iter()
  212. .map(|(db, hash)| format!("{db:.1} dB {}", &hash[..8]))
  213. .collect();
  214. let kinds: HashSet<&String> = self.pictures.iter().map(|p| &p.1).collect();
  215. let _ = writeln!(
  216. t,
  217. " pictures of the loops: {} different: {}",
  218. kinds.len(),
  219. all.join(", ")
  220. );
  221. }
  222. for n in &self.notes {
  223. let _ = writeln!(t, " note: {n}");
  224. }
  225. t
  226. }
  227. }
  228. fn median(v: &[f64]) -> f64 {
  229. let mut v = v.to_vec();
  230. v.sort_by(f64::total_cmp);
  231. v.get(v.len() / 2).copied().unwrap_or(0.0)
  232. }
  233. /// The folder of a capture: `folder`, or the last `capture-<n>` in it that
  234. /// is complete.
  235. pub fn find(folder: &Path) -> Result<PathBuf> {
  236. if folder.join("frame.bin").exists() {
  237. return Ok(folder.to_owned());
  238. }
  239. let mut best: Option<(u32, PathBuf)> = None;
  240. for entry in std::fs::read_dir(folder)
  241. .with_context(|| format!("{}", folder.display()))?
  242. .flatten()
  243. {
  244. let name = entry.file_name().to_string_lossy().into_owned();
  245. let Some(n) = name.strip_prefix("capture-").and_then(|n| n.parse().ok()) else {
  246. continue;
  247. };
  248. if entry.path().join("frame.bin").exists() && best.as_ref().is_none_or(|b| b.0 < n) {
  249. best = Some((n, entry.path()));
  250. }
  251. }
  252. best.map(|b| b.1)
  253. .ok_or_else(|| anyhow!("no capture (frame.bin) in {}", folder.display()))
  254. }
  255. /// Writes the DXIL of the pipelines whose name has `text` in it to `shaders`
  256. /// in the capture, and the pipelines' descriptions; what was written.
  257. pub fn dump(folder: &Path, text: &str) -> Result<Vec<String>> {
  258. let folder = find(folder)?;
  259. let frame = Frame::read(&folder.join("frame.bin"))?;
  260. let file = File::open(folder.join("shaders.bin"))?;
  261. let to = folder.join("shaders");
  262. std::fs::create_dir_all(&to)?;
  263. let mut out = Vec::new();
  264. for p in frame.pipelines.iter().filter(|p| p.name.contains(text)) {
  265. let mut line = format!("pipeline {} {}:", p.id, p.name);
  266. for part in &p.parts {
  267. match part {
  268. wire::Part::Code { kind, blob } => {
  269. let c = &frame.codes[*blob as usize];
  270. let mut bytes = vec![0; c.len as usize];
  271. read_at(&file, &mut bytes, c.at)?;
  272. let name: String = c.hash[..8].iter().map(|b| format!("{b:02x}")).collect();
  273. std::fs::write(to.join(format!("{name}.dxil")), bytes)?;
  274. let _ = write!(line, " {kind}={name}.dxil");
  275. }
  276. wire::Part::Root { root } => {
  277. if let Some((_, blob)) = frame.roots.iter().find(|r| r.0 == *root) {
  278. std::fs::write(to.join(format!("root-{root}.bin")), &blob.0)?;
  279. }
  280. let _ = write!(line, " root-{root}.bin");
  281. }
  282. other => {
  283. let _ = write!(line, " {other:?}");
  284. }
  285. }
  286. }
  287. out.push(line);
  288. }
  289. Ok(out)
  290. }
  291. /// Loads a capture and runs it: the whole of `victory replay`. The reports,
  292. /// with what each is of.
  293. pub fn replay(folder: &Path, options: &Options) -> Result<Vec<(String, Report)>> {
  294. let mut player = Player::load(folder, options)?;
  295. let mut out = Vec::new();
  296. if options.compare && options.edited() {
  297. let image = Some(player.folder.join("replay-unchanged.png"));
  298. out.push((
  299. "unchanged".into(),
  300. player.run(&Options {
  301. image,
  302. ..options.plain()
  303. })?,
  304. ));
  305. }
  306. let what = if options.edited() {
  307. "with the experiments"
  308. } else {
  309. "unchanged"
  310. };
  311. out.push((what.into(), player.run(options)?));
  312. Ok(out)
  313. }
  314. struct Object {
  315. res: ID3D12Resource,
  316. va: u64,
  317. /// In the capture's `resources`.
  318. index: usize,
  319. subs: u32,
  320. }
  321. /// One version of a shader-visible descriptor heap.
  322. struct Version {
  323. heap: ID3D12DescriptorHeap,
  324. gpu: u64,
  325. }
  326. pub struct Player {
  327. pub folder: PathBuf,
  328. frame: Frame,
  329. device: ID3D12Device,
  330. worker: Worker,
  331. info: Option<ID3D12InfoQueue>,
  332. frequency: f64,
  333. objects: HashMap<u32, Object>,
  334. _heaps: HashMap<u32, ID3D12Heap>,
  335. roots: HashMap<u32, ID3D12RootSignature>,
  336. pipelines: HashMap<u32, ID3D12PipelineState>,
  337. signatures: HashMap<u32, ID3D12CommandSignature>,
  338. queries: HashMap<u32, ID3D12QueryHeap>,
  339. /// Descriptor heaps by id, in their versions; each submission's version.
  340. descriptors: HashMap<u32, (Vec<Version>, u64)>,
  341. version_of: Vec<usize>,
  342. /// Render target and depth views by what they are of.
  343. targets: HashMap<Slot, D3D12_CPU_DESCRIPTOR_HANDLE>,
  344. _target_heaps: Vec<ID3D12DescriptorHeap>,
  345. /// Copies of what the frame changes, as at its start.
  346. masters: Vec<(u32, ID3D12Resource)>,
  347. /// What the CPU wrote between submissions, and for each submission
  348. /// where in it.
  349. deltas: Option<ID3D12Resource>,
  350. delta_parts: Vec<Vec<(Delta, u64)>>,
  351. /// States at the start of the frame and after it.
  352. start: HashMap<u32, Vec<u32>>,
  353. end: HashMap<u32, Vec<u32>>,
  354. /// The results of clamp passes ([`RESULTS`]).
  355. results: Option<ID3D12Resource>,
  356. commands: Vec<Vec<Cmd>>,
  357. /// Resources in the states of the start (not those of the end).
  358. fresh: bool,
  359. /// States as the last run left them (`diverge`).
  360. at: States,
  361. notes: Vec<String>,
  362. }
  363. /// What a command of a list is timed as.
  364. type Stamp = (usize, &'static str, u32);
  365. /// A list made from commands, with what its timestamps are of.
  366. struct Built {
  367. _allocator: ID3D12CommandAllocator,
  368. list: ID3D12GraphicsCommandList,
  369. /// The query of its start; its end is the one before the next list's.
  370. first: u32,
  371. last: u32,
  372. stamps: Vec<Stamp>,
  373. }
  374. impl Player {
  375. pub fn load(folder: &Path, options: &Options) -> Result<Player> {
  376. let folder = find(folder)?;
  377. let began = Instant::now();
  378. let frame = Frame::read(&folder.join("frame.bin"))?;
  379. let (device, info) = make_device(&frame, options.debug)?;
  380. // SAFETY: plain creation and queries.
  381. let (queue, frequency) = unsafe {
  382. let queue: ID3D12CommandQueue =
  383. device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  384. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  385. ..Default::default()
  386. })?;
  387. let frequency = queue.GetTimestampFrequency()? as f64;
  388. (queue, frequency)
  389. };
  390. let commands: Vec<Vec<Cmd>> = frame
  391. .lists
  392. .iter()
  393. .map(|l| Cmd::all(&l.commands.0))
  394. .collect::<std::result::Result<_, _>>()?;
  395. let mut player = Player {
  396. folder,
  397. worker: Worker::new(&device, &queue)?,
  398. device,
  399. info,
  400. frequency,
  401. objects: HashMap::new(),
  402. _heaps: HashMap::new(),
  403. roots: HashMap::new(),
  404. pipelines: HashMap::new(),
  405. signatures: HashMap::new(),
  406. queries: HashMap::new(),
  407. descriptors: HashMap::new(),
  408. version_of: Vec::new(),
  409. targets: HashMap::new(),
  410. _target_heaps: Vec::new(),
  411. masters: Vec::new(),
  412. deltas: None,
  413. delta_parts: Vec::new(),
  414. start: HashMap::new(),
  415. end: HashMap::new(),
  416. results: None,
  417. commands,
  418. fresh: true,
  419. at: States::default(),
  420. notes: frame
  421. .notes
  422. .iter()
  423. .map(|n| format!("recorder: {n}"))
  424. .collect(),
  425. frame,
  426. };
  427. player.check()?;
  428. let mut steps: Vec<(&str, std::time::Duration)> = Vec::new();
  429. let mut step = |what: &'static str, at: &mut Instant| {
  430. steps.push((what, at.elapsed()));
  431. *at = Instant::now();
  432. };
  433. let mut at = Instant::now();
  434. player.make_resources(options.buffers)?;
  435. step("resources", &mut at);
  436. player.make_pipelines()?;
  437. step("pipelines", &mut at);
  438. player.make_descriptors()?;
  439. step("descriptors", &mut at);
  440. player.load_contents()?;
  441. step("contents", &mut at);
  442. player.make_masters()?;
  443. step("copies to restore from", &mut at);
  444. let steps: Vec<String> = steps
  445. .iter()
  446. .map(|(w, d)| format!("{w} {:.1} s", d.as_secs_f64()))
  447. .collect();
  448. player.notes.push(format!(
  449. "loaded in {:.1} s: {}",
  450. began.elapsed().as_secs_f64(),
  451. steps.join(", ")
  452. ));
  453. Ok(player)
  454. }
  455. fn note(&mut self, n: String) {
  456. tracing::warn!("{n}");
  457. self.notes.push(n);
  458. }
  459. /// Says what of the frame is not there.
  460. fn check(&mut self) -> Result<()> {
  461. let missing = self
  462. .frame
  463. .submits
  464. .iter()
  465. .flat_map(|s| &s.lists)
  466. .filter(|&&l| l == MISSING)
  467. .count();
  468. if missing > 0 {
  469. self.note(format!(
  470. "{missing} lists of the frame were not recorded: the frame is incomplete"
  471. ));
  472. }
  473. if self.frame.submits.is_empty() {
  474. bail!("the capture has no submission");
  475. }
  476. let unknown = self
  477. .commands
  478. .iter()
  479. .flatten()
  480. .filter(|c| {
  481. matches!(
  482. c,
  483. Cmd::RootView {
  484. va: Va::Unknown { .. },
  485. ..
  486. }
  487. )
  488. })
  489. .count();
  490. if unknown > 0 {
  491. self.note(format!(
  492. "{unknown} root views name memory in no known buffer: they are null in the replay"
  493. ));
  494. }
  495. Ok(())
  496. }
  497. fn resource(&self, id: u32) -> Option<&ID3D12Resource> {
  498. if id == RESULTS {
  499. return self.results.as_ref();
  500. }
  501. self.objects.get(&id).map(|o| &o.res)
  502. }
  503. fn va(&self, va: &Va) -> u64 {
  504. match va {
  505. Va::At { res, offset } => self.objects.get(res).map_or(0, |o| o.va + offset),
  506. _ => 0,
  507. }
  508. }
  509. fn make_resources(&mut self, buffers: Buffers) -> Result<()> {
  510. // A heap of memory the CPU sees becomes one the card may write too:
  511. // what the CPU wrote is put back by the card.
  512. let props = |p: &wire::HeapProps, buffer: bool| -> D3D12_HEAP_PROPERTIES {
  513. let pc = |page| D3D12_HEAP_PROPERTIES {
  514. Type: D3D12_HEAP_TYPE_CUSTOM,
  515. CPUPageProperty: page,
  516. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  517. ..Default::default()
  518. };
  519. let card = D3D12_HEAP_PROPERTIES {
  520. Type: D3D12_HEAP_TYPE_DEFAULT,
  521. ..Default::default()
  522. };
  523. match (gpu::seen(p), buffers) {
  524. (Seen::ReadBack, _) => gpu::to_props(p),
  525. (_, Buffers::Card) if buffer => card,
  526. (Seen::No, Buffers::Pc) if buffer => pc(D3D12_CPU_PAGE_PROPERTY_WRITE_BACK),
  527. (Seen::Combined, _) if p.kind > D3D12_HEAP_TYPE_CUSTOM.0 => card,
  528. (Seen::Combined, _) => pc(D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE),
  529. _ => gpu::to_props(p),
  530. }
  531. };
  532. // Flags a replay has no use for: sharing, display, not zeroed.
  533. const DROP: i32 = 0x1 | 0x8 | 0x20 | 0x1000;
  534. let used_by_buffers_only: HashSet<u32> = {
  535. let mut textures = HashSet::new();
  536. for r in &self.frame.resources {
  537. if let Place::Placed { heap, .. } = r.place
  538. && r.desc.dimension != D3D12_RESOURCE_DIMENSION_BUFFER.0
  539. {
  540. textures.insert(heap);
  541. }
  542. }
  543. self.frame
  544. .heaps
  545. .iter()
  546. .map(|h| h.id)
  547. .filter(|id| !textures.contains(id))
  548. .collect()
  549. };
  550. for h in &self.frame.heaps {
  551. let desc = D3D12_HEAP_DESC {
  552. SizeInBytes: h.size,
  553. Properties: props(&h.props, used_by_buffers_only.contains(&h.id)),
  554. Alignment: h.alignment,
  555. Flags: D3D12_HEAP_FLAGS(h.flags & !DROP),
  556. };
  557. let mut heap: Option<ID3D12Heap> = None;
  558. // SAFETY: plain creation.
  559. unsafe { self.device.CreateHeap(&desc, &mut heap) }
  560. .with_context(|| format!("heap {}", h.id))?;
  561. self._heaps.extend(heap.map(|heap| (h.id, heap)));
  562. }
  563. let mut failed = 0;
  564. for (index, r) in self.frame.resources.iter().enumerate() {
  565. let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0;
  566. let desc = gpu::to_desc(&r.desc);
  567. let mut made: Option<ID3D12Resource> = None;
  568. let clear: Option<D3D12_CLEAR_VALUE> = r.clear.map(|c| {
  569. // SAFETY: 20 bytes that were a clear value.
  570. unsafe { std::mem::transmute::<[u32; 5], D3D12_CLEAR_VALUE>(c) }
  571. });
  572. let clear = clear.as_ref().map(|c| c as *const _);
  573. // SAFETY: plain creation from a description the host took.
  574. let result = unsafe {
  575. match &r.place {
  576. Place::Placed { heap, offset } => match self._heaps.get(heap) {
  577. Some(h) => self.device.CreatePlacedResource(
  578. h,
  579. *offset,
  580. &desc,
  581. D3D12_RESOURCE_STATE_COMMON,
  582. clear,
  583. &mut made,
  584. ),
  585. None => Err(windows::core::Error::empty()),
  586. },
  587. Place::Committed { props: p, flags } => {
  588. let p = props(p, is_buffer);
  589. let state = if p.Type == D3D12_HEAP_TYPE_READBACK {
  590. D3D12_RESOURCE_STATE_COPY_DEST
  591. } else {
  592. D3D12_RESOURCE_STATE_COMMON
  593. };
  594. self.device.CreateCommittedResource(
  595. &p,
  596. D3D12_HEAP_FLAGS(flags & !DROP),
  597. &desc,
  598. state,
  599. clear,
  600. &mut made,
  601. )
  602. }
  603. Place::BackBuffer {} => {
  604. let p = D3D12_HEAP_PROPERTIES {
  605. Type: D3D12_HEAP_TYPE_DEFAULT,
  606. ..Default::default()
  607. };
  608. self.device.CreateCommittedResource(
  609. &p,
  610. D3D12_HEAP_FLAG_NONE,
  611. &desc,
  612. D3D12_RESOURCE_STATE_COMMON,
  613. None,
  614. &mut made,
  615. )
  616. }
  617. }
  618. };
  619. match (result, made) {
  620. (Ok(()), Some(res)) => {
  621. // SAFETY: a live resource.
  622. let va = if is_buffer {
  623. unsafe { res.GetGPUVirtualAddress() }
  624. } else {
  625. 0
  626. };
  627. self.objects.insert(
  628. r.id,
  629. Object {
  630. res,
  631. va,
  632. index,
  633. subs: gpu::subresources(&r.desc),
  634. },
  635. );
  636. }
  637. (e, _) => {
  638. if failed == 0 {
  639. tracing::warn!("resource {} not made: {e:?}: {r:?}", r.id);
  640. }
  641. failed += 1;
  642. }
  643. }
  644. if !is_buffer {
  645. self.start.insert(r.id, r.state.clone());
  646. }
  647. }
  648. if failed > 0 {
  649. self.note(format!("{failed} resources could not be made again"));
  650. }
  651. Ok(())
  652. }
  653. fn make_pipelines(&mut self) -> Result<()> {
  654. for (id, blob) in &self.frame.roots {
  655. // SAFETY: a blob the host took.
  656. let root = unsafe { self.device.CreateRootSignature(0, &blob.0) }
  657. .with_context(|| format!("root signature {id}"))?;
  658. self.roots.insert(*id, root);
  659. }
  660. for s in &self.frame.signatures {
  661. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  662. ByteStride: s.stride,
  663. NumArgumentDescs: s.args.len() as u32,
  664. pArgumentDescs: s.args.as_ptr().cast(),
  665. NodeMask: 0,
  666. };
  667. let mut made: Option<ID3D12CommandSignature> = None;
  668. // SAFETY: a description the host took.
  669. unsafe {
  670. self.device
  671. .CreateCommandSignature(&desc, self.roots.get(&s.root), &mut made)?
  672. };
  673. self.signatures.extend(made.map(|m| (s.id, m)));
  674. }
  675. for q in &self.frame.query_heaps {
  676. let desc = D3D12_QUERY_HEAP_DESC {
  677. Type: D3D12_QUERY_HEAP_TYPE(q.kind),
  678. Count: q.count,
  679. NodeMask: 0,
  680. };
  681. let mut made: Option<ID3D12QueryHeap> = None;
  682. // SAFETY: plain creation.
  683. unsafe { self.device.CreateQueryHeap(&desc, &mut made)? };
  684. self.queries.extend(made.map(|m| (q.id, m)));
  685. }
  686. let file = File::open(self.folder.join("shaders.bin"))?;
  687. let device: ID3D12Device2 = self.device.cast()?;
  688. let next = AtomicUsize::new(0);
  689. type Made = std::result::Result<ID3D12PipelineState, String>;
  690. let made: std::sync::Mutex<Vec<(u32, Made)>> = std::sync::Mutex::default();
  691. let threads = std::thread::available_parallelism()
  692. .map_or(4, |n| n.get() / 2)
  693. .max(1);
  694. let (frame, roots) = (&self.frame, &self.roots);
  695. std::thread::scope(|scope| {
  696. for _ in 0..threads {
  697. scope.spawn(|| {
  698. while let Some(p) = frame.pipelines.get(next.fetch_add(1, Ordering::Relaxed)) {
  699. let code = |i: u32| {
  700. let c = frame.codes.get(i as usize)?;
  701. let mut bytes = vec![0; c.len as usize];
  702. read_at(&file, &mut bytes, c.at).ok()?;
  703. Some(bytes)
  704. };
  705. let m =
  706. super::pso::make(&device, &p.parts, |id| roots.get(&id).cloned(), code);
  707. made.lock()
  708. .unwrap_or_else(|e| e.into_inner())
  709. .push((p.id, m));
  710. }
  711. });
  712. }
  713. });
  714. let mut refused = Vec::new();
  715. for (id, m) in made.into_inner().unwrap_or_else(|e| e.into_inner()) {
  716. match m {
  717. Ok(p) => drop(self.pipelines.insert(id, p)),
  718. Err(e) => refused.push((id, e)),
  719. }
  720. }
  721. if let Some((id, e)) = refused.first() {
  722. let n = format!(
  723. "{} pipelines could not be made again, first {}: {e}",
  724. refused.len(),
  725. self.pipeline_name(*id)
  726. );
  727. self.note(n);
  728. }
  729. Ok(())
  730. }
  731. /// A pipeline's name for reports: what the host layer called it and the
  732. /// hashes of its shaders.
  733. fn pipeline_name(&self, id: u32) -> String {
  734. let Some(p) = self.frame.pipelines.iter().find(|p| p.id == id) else {
  735. return format!("pipeline {id}");
  736. };
  737. let code: Vec<String> = self.hashes(p);
  738. format!(
  739. "{} (DXIL {})",
  740. if p.name.is_empty() {
  741. "unnamed"
  742. } else {
  743. &p.name
  744. },
  745. code.join(" ")
  746. )
  747. }
  748. fn hashes(&self, p: &wire::Pipeline) -> Vec<String> {
  749. p.parts
  750. .iter()
  751. .filter_map(|part| match part {
  752. wire::Part::Code { blob, .. } => {
  753. let c = self.frame.codes.get(*blob as usize)?;
  754. Some(c.hash[..8].iter().map(|b| format!("{b:02x}")).collect())
  755. }
  756. _ => None,
  757. })
  758. .collect()
  759. }
  760. /// Makes a view; one of a resource that is not there is null.
  761. ///
  762. /// # Safety
  763. /// `at` is a slot of a heap of the view's type.
  764. unsafe fn view(&self, s: &Slot, at: D3D12_CPU_DESCRIPTOR_HANDLE, sampler: bool) {
  765. let gone = s.res != NONE && !self.objects.contains_key(&s.res);
  766. let res = self.objects.get(&s.res).map(|o| &o.res);
  767. let counter = self.objects.get(&s.counter).map(|o| &o.res);
  768. // The descriptions lie in the slot unaligned.
  769. // SAFETY: the slot's description is of its kind; the resources live.
  770. unsafe {
  771. match (s.kind, s.described != 0 && !gone) {
  772. (slot::CBV, described) => {
  773. let mut d: D3D12_CONSTANT_BUFFER_VIEW_DESC = Default::default();
  774. if described && let Some(o) = self.objects.get(&s.res) {
  775. d = s
  776. .desc
  777. .as_ptr()
  778. .cast::<D3D12_CONSTANT_BUFFER_VIEW_DESC>()
  779. .read_unaligned();
  780. d.BufferLocation = o.va + s.address();
  781. }
  782. self.device.CreateConstantBufferView(Some(&d), at);
  783. }
  784. (slot::SRV, true) => {
  785. let d = s
  786. .desc
  787. .as_ptr()
  788. .cast::<D3D12_SHADER_RESOURCE_VIEW_DESC>()
  789. .read_unaligned();
  790. self.device.CreateShaderResourceView(res, Some(&d), at);
  791. }
  792. (slot::SRV, false) if res.is_some() => {
  793. self.device.CreateShaderResourceView(res, None, at)
  794. }
  795. (slot::UAV, true) => {
  796. let d = s
  797. .desc
  798. .as_ptr()
  799. .cast::<D3D12_UNORDERED_ACCESS_VIEW_DESC>()
  800. .read_unaligned();
  801. self.device
  802. .CreateUnorderedAccessView(res, counter, Some(&d), at);
  803. }
  804. (slot::UAV, false) if res.is_some() => {
  805. self.device
  806. .CreateUnorderedAccessView(res, None::<&ID3D12Resource>, None, at)
  807. }
  808. (slot::SAMPLER, true) => {
  809. let d = s
  810. .desc
  811. .as_ptr()
  812. .cast::<D3D12_SAMPLER_DESC>()
  813. .read_unaligned();
  814. self.device.CreateSampler(&d, at);
  815. }
  816. _ if sampler => {
  817. let d = D3D12_SAMPLER_DESC {
  818. Filter: D3D12_FILTER_MIN_MAG_MIP_POINT,
  819. AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  820. AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  821. AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  822. ..Default::default()
  823. };
  824. self.device.CreateSampler(&d, at);
  825. }
  826. (slot::UAV, _) => {
  827. let d = D3D12_UNORDERED_ACCESS_VIEW_DESC {
  828. Format: DXGI_FORMAT(41),
  829. ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
  830. ..Default::default()
  831. };
  832. self.device.CreateUnorderedAccessView(
  833. None::<&ID3D12Resource>,
  834. None::<&ID3D12Resource>,
  835. Some(&d),
  836. at,
  837. );
  838. }
  839. _ => {
  840. let d = D3D12_SHADER_RESOURCE_VIEW_DESC {
  841. Format: DXGI_FORMAT(41),
  842. ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
  843. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  844. ..Default::default()
  845. };
  846. self.device
  847. .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&d), at);
  848. }
  849. }
  850. }
  851. }
  852. fn make_descriptors(&mut self) -> Result<()> {
  853. // A submission whose views replace ones that were in use gets a
  854. // version of the heaps of its own: lists are sent without waiting,
  855. // so a heap cannot be written between them.
  856. let mut now: HashMap<(u32, u32), Slot> = HashMap::new();
  857. let replaced: HashSet<(u32, u32)> = self
  858. .frame
  859. .submits
  860. .iter()
  861. .flat_map(|s| s.views.iter().map(|v| (v.0, v.1)))
  862. .collect();
  863. for h in &self.frame.descriptor_heaps {
  864. for (id, i) in replaced.iter().filter(|k| k.0 == h.id) {
  865. let k = h.runs.partition_point(|run| run.0 <= *i);
  866. if let Some((first, n, s)) = k.checked_sub(1).and_then(|k| h.runs.get(k))
  867. && i - first < *n
  868. {
  869. now.insert((*id, *i), *s);
  870. }
  871. }
  872. }
  873. // What each version changes against the one before.
  874. let mut versions: Vec<Vec<(u32, u32, Slot)>> = vec![Vec::new()];
  875. let mut touched: HashSet<(u32, u32)> = HashSet::new();
  876. for s in &self.frame.submits {
  877. let live =
  878. |old: Option<&Slot>| old.is_some_and(|o| o.kind == slot::SAMPLER || o.res != NONE);
  879. let news: Vec<&(u32, u32, Slot)> = s
  880. .views
  881. .iter()
  882. .filter(|(h, i, v)| now.get(&(*h, *i)) != Some(v))
  883. .collect();
  884. if news
  885. .iter()
  886. .any(|(h, i, _)| live(now.get(&(*h, *i))) || touched.contains(&(*h, *i)))
  887. {
  888. versions.push(Vec::new());
  889. touched.clear();
  890. }
  891. for (h, i, v) in news {
  892. now.insert((*h, *i), *v);
  893. touched.insert((*h, *i));
  894. if let Some(last) = versions.last_mut() {
  895. last.push((*h, *i, *v));
  896. }
  897. }
  898. self.version_of.push(versions.len() - 1);
  899. }
  900. let mut made = HashMap::new();
  901. let mut full = 0;
  902. for h in &self.frame.descriptor_heaps {
  903. let sampler = h.kind == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0;
  904. let kind = D3D12_DESCRIPTOR_HEAP_TYPE(h.kind);
  905. let make = |flags| -> windows::core::Result<ID3D12DescriptorHeap> {
  906. let d = D3D12_DESCRIPTOR_HEAP_DESC {
  907. Type: kind,
  908. NumDescriptors: h.count,
  909. Flags: flags,
  910. NodeMask: 0,
  911. };
  912. // SAFETY: plain creation.
  913. unsafe { self.device.CreateDescriptorHeap(&d) }
  914. };
  915. let cpu = make(D3D12_DESCRIPTOR_HEAP_FLAG_NONE)?;
  916. // SAFETY: slots of the heap just made; threads write other ones.
  917. unsafe {
  918. let step = self.device.GetDescriptorHandleIncrementSize(kind) as usize;
  919. let start = cpu.GetCPUDescriptorHandleForHeapStart();
  920. let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE {
  921. ptr: start.ptr + i as usize * step,
  922. };
  923. self.view(&Slot::EMPTY, start, sampler);
  924. let mut filled = 1;
  925. while filled < h.count {
  926. let n = filled.min(h.count - filled).min(1 << 16);
  927. // Sources and destinations do not overlap.
  928. self.device
  929. .CopyDescriptorsSimple(n, at(filled), start, kind);
  930. filled += n;
  931. }
  932. for (first, n, s) in &h.runs {
  933. self.view(s, at(*first), sampler);
  934. for i in 1..*n {
  935. self.device
  936. .CopyDescriptorsSimple(1, at(first + i), at(*first), kind);
  937. }
  938. }
  939. let mut all = Vec::new();
  940. for changes in &versions {
  941. let mine: Vec<&(u32, u32, Slot)> =
  942. changes.iter().filter(|(id, _, _)| *id == h.id).collect();
  943. for (_, i, s) in &mine {
  944. if *i < h.count {
  945. self.view(s, at(*i), sampler);
  946. }
  947. }
  948. if mine.is_empty()
  949. && let Some(Version { heap, gpu }) = all.last()
  950. {
  951. let same = Version {
  952. heap: ID3D12DescriptorHeap::clone(heap),
  953. gpu: *gpu,
  954. };
  955. all.push(same);
  956. continue;
  957. }
  958. let heap = match make(D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) {
  959. Ok(heap) => heap,
  960. // Room for no more of them: the changes go into the
  961. // last one, and lists before see them too.
  962. Err(_) if !all.is_empty() => {
  963. full += 1;
  964. let Some(Version { heap, gpu }) = all.last() else {
  965. break;
  966. };
  967. let same = Version {
  968. heap: ID3D12DescriptorHeap::clone(heap),
  969. gpu: *gpu,
  970. };
  971. self.device.CopyDescriptorsSimple(
  972. h.count,
  973. same.heap.GetCPUDescriptorHandleForHeapStart(),
  974. start,
  975. kind,
  976. );
  977. all.push(same);
  978. continue;
  979. }
  980. Err(e) => return Err(e.into()),
  981. };
  982. self.device.CopyDescriptorsSimple(
  983. h.count,
  984. heap.GetCPUDescriptorHandleForHeapStart(),
  985. start,
  986. kind,
  987. );
  988. let gpu = heap.GetGPUDescriptorHandleForHeapStart().ptr;
  989. all.push(Version { heap, gpu });
  990. }
  991. made.insert(h.id, (all, step as u64));
  992. }
  993. }
  994. self.descriptors = made;
  995. if versions.len() > 1 {
  996. self.notes.push(format!(
  997. "{} versions of the descriptor heaps (views replaced during the frame)",
  998. versions.len()
  999. ));
  1000. }
  1001. if full > 0 {
  1002. self.note(format!(
  1003. "{full} versions of descriptor heaps had no room: earlier lists see later views"
  1004. ));
  1005. }
  1006. // Render target and depth views.
  1007. let mut views: [HashSet<Slot>; 2] = Default::default();
  1008. for c in self.commands.iter().flatten() {
  1009. match c {
  1010. Cmd::Targets { colors, depth } => {
  1011. views[0].extend(colors);
  1012. views[1].extend(depth);
  1013. }
  1014. Cmd::ClearTarget { view, .. } => _ = views[0].insert(*view),
  1015. Cmd::ClearDepth { view, .. } => _ = views[1].insert(*view),
  1016. _ => {}
  1017. }
  1018. }
  1019. for (i, all) in views.iter().enumerate() {
  1020. if all.is_empty() {
  1021. continue;
  1022. }
  1023. let kind = [
  1024. D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  1025. D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  1026. ][i];
  1027. let d = D3D12_DESCRIPTOR_HEAP_DESC {
  1028. Type: kind,
  1029. NumDescriptors: all.len() as u32,
  1030. ..Default::default()
  1031. };
  1032. // SAFETY: plain creation; slots of the heap just made.
  1033. unsafe {
  1034. let heap: ID3D12DescriptorHeap = self.device.CreateDescriptorHeap(&d)?;
  1035. let step = self.device.GetDescriptorHandleIncrementSize(kind) as usize;
  1036. let mut at = heap.GetCPUDescriptorHandleForHeapStart();
  1037. for s in all {
  1038. let res = self.objects.get(&s.res).map(|o| &o.res);
  1039. if i == 0 {
  1040. let d = s
  1041. .desc
  1042. .as_ptr()
  1043. .cast::<D3D12_RENDER_TARGET_VIEW_DESC>()
  1044. .read_unaligned();
  1045. // Without either there is nothing to make a view of.
  1046. let null = D3D12_RENDER_TARGET_VIEW_DESC {
  1047. Format: DXGI_FORMAT(28),
  1048. ViewDimension: D3D12_RTV_DIMENSION_TEXTURE2D,
  1049. ..Default::default()
  1050. };
  1051. let d = if s.described != 0 {
  1052. Some(&d as *const _)
  1053. } else if res.is_none() {
  1054. Some(&null as *const _)
  1055. } else {
  1056. None
  1057. };
  1058. self.device.CreateRenderTargetView(res, d, at);
  1059. } else {
  1060. let d = s
  1061. .desc
  1062. .as_ptr()
  1063. .cast::<D3D12_DEPTH_STENCIL_VIEW_DESC>()
  1064. .read_unaligned();
  1065. let null = D3D12_DEPTH_STENCIL_VIEW_DESC {
  1066. Format: DXGI_FORMAT(40),
  1067. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D,
  1068. ..Default::default()
  1069. };
  1070. let d = if s.described != 0 {
  1071. Some(&d as *const _)
  1072. } else if res.is_none() {
  1073. Some(&null as *const _)
  1074. } else {
  1075. None
  1076. };
  1077. self.device.CreateDepthStencilView(res, d, at);
  1078. }
  1079. self.targets.insert(*s, at);
  1080. at.ptr += step;
  1081. }
  1082. self._target_heaps.push(heap);
  1083. }
  1084. }
  1085. Ok(())
  1086. }
  1087. /// Reads parts of files into upload memory and has `copy` record what
  1088. /// is done with each.
  1089. fn upload<T: Sync>(
  1090. &mut self,
  1091. parts: &[(T, u64, u64)],
  1092. file: &File,
  1093. mut copy: impl FnMut(&Player, &ID3D12GraphicsCommandList, &[(&T, u64, u64)], &ID3D12Resource),
  1094. ) -> Result<()> {
  1095. // Batches of parts with their place in the buffer.
  1096. let mut batches: Vec<Vec<(usize, u64)>> = vec![Vec::new()];
  1097. let (mut at, mut most) = (0u64, 0u64);
  1098. for (i, (_, len, _)) in parts.iter().enumerate() {
  1099. at = at.next_multiple_of(512);
  1100. if at + len > STAGING && at > 0 {
  1101. batches.push(Vec::new());
  1102. at = 0;
  1103. }
  1104. if let Some(b) = batches.last_mut() {
  1105. b.push((i, at));
  1106. }
  1107. at += len;
  1108. most = most.max(at);
  1109. }
  1110. if parts.is_empty() {
  1111. return Ok(());
  1112. }
  1113. let mut stagings: Vec<(ID3D12Resource, usize, u64)> = Vec::new();
  1114. for _ in 0..batches.len().min(2) {
  1115. let (b, data) = gpu::buffer(
  1116. &self.device,
  1117. D3D12_HEAP_TYPE_UPLOAD,
  1118. most,
  1119. D3D12_RESOURCE_FLAG_NONE,
  1120. )?;
  1121. stagings.push((b, data as usize, 0));
  1122. }
  1123. for (n, batch) in batches.iter().enumerate() {
  1124. let k = n % stagings.len();
  1125. self.worker.wait(stagings[k].2)?;
  1126. let map = stagings[k].1;
  1127. let next = AtomicUsize::new(0);
  1128. let failed: std::sync::Mutex<Option<std::io::Error>> = std::sync::Mutex::default();
  1129. std::thread::scope(|scope| {
  1130. for _ in 0..8.min(batch.len()) {
  1131. scope.spawn(|| {
  1132. while let Some(&(i, at)) = batch.get(next.fetch_add(1, Ordering::Relaxed)) {
  1133. let (_, len, from) = &parts[i];
  1134. // SAFETY: this part's own bytes of the mapping.
  1135. let to = unsafe {
  1136. std::slice::from_raw_parts_mut(
  1137. (map + at as usize) as *mut u8,
  1138. *len as usize,
  1139. )
  1140. };
  1141. if *from == ZERO {
  1142. to.fill(0);
  1143. } else if let Err(e) = read_at(file, to, *from) {
  1144. failed
  1145. .lock()
  1146. .unwrap_or_else(|e| e.into_inner())
  1147. .get_or_insert(e);
  1148. }
  1149. }
  1150. });
  1151. }
  1152. });
  1153. if let Some(e) = failed.into_inner().unwrap_or_else(|e| e.into_inner()) {
  1154. return Err(e).context("the capture's contents");
  1155. }
  1156. let list: Vec<(&T, u64, u64)> = batch
  1157. .iter()
  1158. .map(|&(i, at)| (&parts[i].0, parts[i].1, at))
  1159. .collect();
  1160. let buffer = stagings[k].0.clone();
  1161. // The worker is another part of the player than `copy` uses.
  1162. let other = Worker::new(&self.device, &self.worker.queue)?;
  1163. let mut worker = std::mem::replace(&mut self.worker, other);
  1164. let sent = worker.send(|l| copy(self, l, &list, &buffer));
  1165. self.worker = worker;
  1166. stagings[k].2 = sent?;
  1167. }
  1168. self.worker.idle()?;
  1169. Ok(())
  1170. }
  1171. fn load_contents(&mut self) -> Result<()> {
  1172. // Idle aliases first: a change of their state may write memory the
  1173. // one in use holds.
  1174. let known: HashSet<u32> = self.frame.contents.iter().map(|c| c.res).collect();
  1175. let mut early = Vec::new();
  1176. let mut into = Vec::new();
  1177. for r in &self.frame.resources {
  1178. let (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else {
  1179. continue;
  1180. };
  1181. let loaded = !r.idle && known.contains(&r.id);
  1182. gpu::moves(
  1183. &o.res,
  1184. &[COMMON],
  1185. if loaded { &[COPY_DEST] } else { state },
  1186. if loaded { &mut into } else { &mut early },
  1187. );
  1188. }
  1189. let textures: Vec<(Content, u64, u64)> = self
  1190. .frame
  1191. .contents
  1192. .iter()
  1193. .filter(|c| self.objects.contains_key(&c.res))
  1194. .map(|c| (c.clone(), c.len, c.file))
  1195. .collect();
  1196. let missing = self.frame.contents.len() - textures.len();
  1197. self.worker.run(|list| {
  1198. // SAFETY: an open list; live resources.
  1199. unsafe {
  1200. for all in early.chunks(1000) {
  1201. list.ResourceBarrier(all);
  1202. }
  1203. list.ResourceBarrier(&[alias()]);
  1204. for all in into.chunks(1000) {
  1205. list.ResourceBarrier(all);
  1206. }
  1207. }
  1208. })?;
  1209. let file = File::open(self.folder.join("contents.bin"))?;
  1210. self.upload(&textures, &file, |player, list, parts, staging| {
  1211. for (c, len, at) in parts {
  1212. let Some(o) = player.objects.get(&c.res) else {
  1213. continue;
  1214. };
  1215. let r = &player.frame.resources[o.index];
  1216. // SAFETY: an open list; live resources.
  1217. unsafe {
  1218. if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 {
  1219. list.CopyBufferRegion(&o.res, c.first, staging, *at, *len);
  1220. continue;
  1221. }
  1222. let (all, _) = gpu::footprints(
  1223. &player.device,
  1224. &gpu::to_desc(&r.desc),
  1225. c.first as u32,
  1226. c.count,
  1227. );
  1228. for (i, mut f) in all.into_iter().enumerate() {
  1229. f.Offset += at;
  1230. let to = gpu::sub_location(&o.res, c.first as u32 + i as u32);
  1231. list.CopyTextureRegion(
  1232. &to,
  1233. 0,
  1234. 0,
  1235. 0,
  1236. &gpu::placed_location(staging, f),
  1237. None,
  1238. );
  1239. }
  1240. }
  1241. }
  1242. })?;
  1243. // To the states of the frame's start.
  1244. let mut back = Vec::new();
  1245. for r in &self.frame.resources {
  1246. let (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else {
  1247. continue;
  1248. };
  1249. if !r.idle && known.contains(&r.id) {
  1250. gpu::moves(&o.res, &[COPY_DEST], state, &mut back);
  1251. }
  1252. }
  1253. self.worker.run(|list| {
  1254. for all in back.chunks(1000) {
  1255. // SAFETY: an open list; live resources.
  1256. unsafe { list.ResourceBarrier(all) };
  1257. }
  1258. })?;
  1259. if missing > 0 {
  1260. self.note(format!(
  1261. "contents of {missing} parts of resources that could not be made are left out"
  1262. ));
  1263. }
  1264. // What the CPU had put into the memory both see by the first
  1265. // submission: part of the start of the frame.
  1266. let file = File::open(self.folder.join("deltas.bin"))?;
  1267. let named = self.named_buffers();
  1268. let of = |s: &wire::Submit| {
  1269. s.deltas
  1270. .iter()
  1271. .filter(|d| named.contains(&d.res))
  1272. .cloned()
  1273. .collect::<Vec<Delta>>()
  1274. };
  1275. // In memory the card cannot write, bytes looked at first when a
  1276. // later submission read them can stand there from the start.
  1277. let upload: HashSet<u32> = self
  1278. .frame
  1279. .resources
  1280. .iter()
  1281. .filter(|r| matches!(&r.place, Place::Committed { props, .. } if props.kind == D3D12_HEAP_TYPE_UPLOAD.0))
  1282. .map(|r| r.id)
  1283. .collect();
  1284. let mut first = of(&self.frame.submits[0]);
  1285. let mut seen: HashSet<(u32, u64)> = HashSet::new();
  1286. let pages = |d: &Delta| {
  1287. (d.at / 4096..(d.at + d.len).div_ceil(4096))
  1288. .map(|p| (d.res, p))
  1289. .collect::<Vec<_>>()
  1290. };
  1291. first.iter().for_each(|d| seen.extend(pages(d)));
  1292. let mut rest: Vec<Vec<Delta>> = vec![Vec::new()];
  1293. for s in self.frame.submits.iter().skip(1) {
  1294. let (early, late): (Vec<Delta>, Vec<Delta>) = of(s).into_iter().partition(|d| {
  1295. upload.contains(&d.res) && pages(d).iter().all(|p| !seen.contains(p))
  1296. });
  1297. early.iter().for_each(|d| seen.extend(pages(d)));
  1298. first.extend(early);
  1299. rest.push(late);
  1300. }
  1301. let first: Vec<(Delta, u64, u64)> = first
  1302. .into_iter()
  1303. .map(|d| (d.clone(), d.len, d.file))
  1304. .collect();
  1305. self.upload(&first, &file, |player, list, parts, staging| {
  1306. for (d, len, at) in parts {
  1307. if let Some(o) = player.objects.get(&d.res) {
  1308. // SAFETY: an open list; live buffers.
  1309. unsafe { list.CopyBufferRegion(&o.res, d.at, staging, *at, *len) };
  1310. }
  1311. }
  1312. })?;
  1313. // The later ones wait in a buffer of their own.
  1314. let mut later: Vec<((u64, Delta), u64, u64)> = Vec::new();
  1315. let mut total = 0u64;
  1316. self.delta_parts = vec![Vec::new(); self.frame.submits.len()];
  1317. for (i, all) in rest.into_iter().enumerate() {
  1318. for d in all {
  1319. later.push(((total, d.clone()), d.len, d.file));
  1320. total += d.len;
  1321. self.delta_parts[i].push((d, total - later.last().map_or(0, |l| l.1)));
  1322. }
  1323. }
  1324. if total > 0 {
  1325. let (buffer, _) = gpu::buffer(
  1326. &self.device,
  1327. D3D12_HEAP_TYPE_DEFAULT,
  1328. total,
  1329. D3D12_RESOURCE_FLAG_NONE,
  1330. )?;
  1331. self.deltas = Some(buffer.clone());
  1332. self.upload(&later, &file, |_, list, parts, staging| {
  1333. for ((to, _), len, at) in parts {
  1334. // SAFETY: an open list; live buffers.
  1335. unsafe { list.CopyBufferRegion(&buffer, *to, staging, *at, *len) };
  1336. }
  1337. })?;
  1338. }
  1339. Ok(())
  1340. }
  1341. /// The buffers the frame names, in commands or descriptors: what the CPU
  1342. /// writes to others (buffers it has results fetched to) is of no use.
  1343. fn named_buffers(&self) -> HashSet<u32> {
  1344. let mut named = HashSet::new();
  1345. let mut va = |va: &Va| {
  1346. if let Va::At { res, .. } = va {
  1347. named.insert(*res);
  1348. }
  1349. };
  1350. for c in self.commands.iter().flatten() {
  1351. match c {
  1352. Cmd::RootView { va: v, .. } => va(v),
  1353. Cmd::IndexBuffer {
  1354. view: Some((v, _, _)),
  1355. } => va(v),
  1356. Cmd::VertexBuffers {
  1357. views: Some(all), ..
  1358. } => all.iter().for_each(|(v, _, _)| va(v)),
  1359. Cmd::WriteImmediate { all } => all.iter().for_each(|(v, _, _)| va(v)),
  1360. _ => {}
  1361. }
  1362. }
  1363. for c in self.commands.iter().flatten() {
  1364. match c {
  1365. Cmd::CopyBuffer { dst, src, .. } | Cmd::CopyResource { dst, src } => {
  1366. named.extend([*dst, *src])
  1367. }
  1368. Cmd::CopyTexture { dst, src, .. } => {
  1369. for Loc::Sub { res, .. } | Loc::Placed { res, .. } in [dst, src] {
  1370. named.insert(*res);
  1371. }
  1372. }
  1373. Cmd::Indirect { args, count, .. } => named.extend([*args, *count]),
  1374. Cmd::ResolveQuery { dst, .. } => _ = named.insert(*dst),
  1375. _ => {}
  1376. }
  1377. }
  1378. for h in &self.frame.descriptor_heaps {
  1379. named.extend(h.runs.iter().flat_map(|(_, _, s)| [s.res, s.counter]));
  1380. }
  1381. for s in &self.frame.submits {
  1382. named.extend(s.views.iter().flat_map(|(_, _, s)| [s.res, s.counter]));
  1383. }
  1384. named
  1385. }
  1386. /// Copies of what the frame changes; and the states it leaves.
  1387. fn make_masters(&mut self) -> Result<()> {
  1388. let mut states = States::default();
  1389. for r in &self.frame.resources {
  1390. if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 {
  1391. continue;
  1392. }
  1393. let subs = gpu::subresources(&r.desc);
  1394. let decays = r.desc.flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 != 0;
  1395. states.add(r.id, subs, r.state[0], decays);
  1396. if r.state.len() > 1 {
  1397. for (i, s) in r.state.iter().enumerate() {
  1398. states.change(&states::Change {
  1399. res: r.id,
  1400. sub: i as u32,
  1401. after: *s,
  1402. promoted: false,
  1403. alias: false,
  1404. });
  1405. }
  1406. }
  1407. }
  1408. // Resources in a state they are written in at some time, or written
  1409. // some other way.
  1410. const WRITE: u32 =
  1411. RENDER_TARGET | UNORDERED_ACCESS | DEPTH_WRITE | COPY_DEST | RESOLVE_DEST;
  1412. let mut written: HashSet<u32> = self
  1413. .frame
  1414. .resources
  1415. .iter()
  1416. .filter(|r| r.state.iter().any(|s| s & WRITE != 0))
  1417. .map(|r| r.id)
  1418. .collect();
  1419. for (i, s) in self.frame.submits.iter().enumerate() {
  1420. for &l in s.lists.iter().filter(|&&l| l != MISSING) {
  1421. for c in &self.commands[l as usize] {
  1422. let mut changes = Vec::new();
  1423. states::changes(c, &mut changes);
  1424. for ch in &changes {
  1425. states.change(ch);
  1426. }
  1427. match c {
  1428. Cmd::Barriers { all } => {
  1429. for b in all {
  1430. if let Barrier::Transition {
  1431. res, before, after, ..
  1432. } = b
  1433. && (*before | *after) as u32 & WRITE != 0
  1434. {
  1435. written.insert(*res);
  1436. }
  1437. }
  1438. }
  1439. Cmd::CopyBuffer { dst, .. }
  1440. | Cmd::CopyResource { dst, .. }
  1441. | Cmd::ResolveQuery { dst, .. } => _ = written.insert(*dst),
  1442. Cmd::CopyTexture {
  1443. dst: Loc::Sub { res, .. } | Loc::Placed { res, .. },
  1444. ..
  1445. } => _ = written.insert(*res),
  1446. Cmd::Resolve { dst, .. } | Cmd::ResolveRegion { dst, .. } => {
  1447. _ = written.insert(*dst)
  1448. }
  1449. Cmd::RootView {
  1450. kind: slot::UAV,
  1451. va: Va::At { res, .. },
  1452. ..
  1453. } => _ = written.insert(*res),
  1454. Cmd::WriteImmediate { all } => {
  1455. written.extend(all.iter().filter_map(|(va, _, _)| {
  1456. if let Va::At { res, .. } = va {
  1457. Some(*res)
  1458. } else {
  1459. None
  1460. }
  1461. }));
  1462. }
  1463. _ => {}
  1464. }
  1465. }
  1466. }
  1467. states.decay();
  1468. if i > 0 {
  1469. written.extend(self.delta_parts[i].iter().map(|(d, _)| d.res));
  1470. }
  1471. }
  1472. // Buffers any unordered-access view names.
  1473. let is_buffer = |id: u32| {
  1474. self.objects.get(&id).is_some_and(|o| {
  1475. self.frame.resources[o.index].desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0
  1476. })
  1477. };
  1478. let simultaneous = |id: u32| {
  1479. self.objects.get(&id).is_some_and(|o| {
  1480. self.frame.resources[o.index].desc.flags
  1481. & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0
  1482. != 0
  1483. })
  1484. };
  1485. let views = self
  1486. .frame
  1487. .descriptor_heaps
  1488. .iter()
  1489. .flat_map(|h| h.runs.iter().map(|(_, _, s)| s));
  1490. let late = self
  1491. .frame
  1492. .submits
  1493. .iter()
  1494. .flat_map(|s| s.views.iter().map(|(_, _, s)| s));
  1495. for s in views.chain(late).filter(|s| s.kind == slot::UAV) {
  1496. for id in [s.res, s.counter] {
  1497. if is_buffer(id) || simultaneous(id) {
  1498. written.insert(id);
  1499. }
  1500. }
  1501. }
  1502. for id in self.start.keys() {
  1503. self.end
  1504. .insert(*id, states.get(*id).unwrap_or(vec![COMMON]));
  1505. }
  1506. let mut ids: Vec<u32> = written
  1507. .into_iter()
  1508. .filter(|id| {
  1509. self.objects.get(id).is_some_and(|o| {
  1510. let r = &self.frame.resources[o.index];
  1511. let back = matches!(&r.place, Place::Committed { props, .. } if gpu::seen(props) == Seen::ReadBack);
  1512. !r.idle && !back && !matches!(r.place, Place::BackBuffer {})
  1513. })
  1514. })
  1515. .collect();
  1516. ids.sort_unstable();
  1517. let mut total = 0u64;
  1518. let mut in_pc = 0u64;
  1519. for id in ids {
  1520. let o = &self.objects[&id];
  1521. let r = &self.frame.resources[o.index];
  1522. let mut desc = gpu::to_desc(&r.desc);
  1523. desc.Alignment = 0;
  1524. // Copies are only copied to and from; a depth format needs its
  1525. // flag.
  1526. if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 {
  1527. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  1528. }
  1529. // SAFETY: a plain query.
  1530. let size = unsafe { self.device.GetResourceAllocationInfo(0, &[desc]) }.SizeInBytes;
  1531. let room = self.room();
  1532. let buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0;
  1533. let pc = buffer && room.is_some_and(|room| room < size + (1 << 30));
  1534. let props = if pc {
  1535. D3D12_HEAP_PROPERTIES {
  1536. Type: D3D12_HEAP_TYPE_CUSTOM,
  1537. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE,
  1538. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  1539. ..Default::default()
  1540. }
  1541. } else {
  1542. D3D12_HEAP_PROPERTIES {
  1543. Type: D3D12_HEAP_TYPE_DEFAULT,
  1544. ..Default::default()
  1545. }
  1546. };
  1547. let mut made: Option<ID3D12Resource> = None;
  1548. // SAFETY: plain creation.
  1549. let result = unsafe {
  1550. self.device.CreateCommittedResource(
  1551. &props,
  1552. D3D12_HEAP_FLAG_NONE,
  1553. &desc,
  1554. D3D12_RESOURCE_STATE_COMMON,
  1555. None,
  1556. &mut made,
  1557. )
  1558. };
  1559. match (result, made) {
  1560. (Ok(()), Some(m)) => {
  1561. total += size;
  1562. in_pc += if pc { size } else { 0 };
  1563. self.masters.push((id, m));
  1564. }
  1565. (e, _) => self.note(format!(
  1566. "no copy of resource {id} to restore it from ({e:?})"
  1567. )),
  1568. }
  1569. }
  1570. tracing::info!(
  1571. resources = self.masters.len(),
  1572. mb = total >> 20,
  1573. in_pc_memory_mb = in_pc >> 20,
  1574. "copies of what the frame changes"
  1575. );
  1576. // Filled now: the resources are as at the frame's start. Masters
  1577. // stay in the copy-source state (buffers decay).
  1578. let (masters, objects, start) = (&self.masters, &self.objects, &self.start);
  1579. for some in masters.chunks(256) {
  1580. let (mut before, mut after) = (Vec::new(), Vec::new());
  1581. for (id, m) in some {
  1582. let Some(state) = start.get(id) else { continue };
  1583. let o = &objects[id];
  1584. let to: Vec<u32> = state
  1585. .iter()
  1586. .map(|&s| if s & COPY_SOURCE != 0 { s } else { COPY_SOURCE })
  1587. .collect();
  1588. gpu::moves(&o.res, state, &to, &mut before);
  1589. gpu::moves(&o.res, &to, state, &mut after);
  1590. before.push(gpu::transition(m, ALL, COMMON, COPY_DEST));
  1591. after.push(gpu::transition(m, ALL, COPY_DEST, COPY_SOURCE));
  1592. }
  1593. self.worker.run(|list| {
  1594. // SAFETY: an open list; live resources of one size.
  1595. unsafe {
  1596. barriers(list, &before);
  1597. for (id, m) in some {
  1598. list.CopyResource(m, &objects[id].res);
  1599. }
  1600. barriers(list, &after);
  1601. }
  1602. })?;
  1603. }
  1604. Ok(())
  1605. }
  1606. /// What is free of the card's memory budget.
  1607. fn room(&self) -> Option<u64> {
  1608. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  1609. // SAFETY: plain queries.
  1610. unsafe {
  1611. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?;
  1612. let adapter: IDXGIAdapter3 = factory
  1613. .EnumAdapterByLuid(self.device.GetAdapterLuid())
  1614. .ok()?;
  1615. adapter
  1616. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  1617. .ok()?;
  1618. }
  1619. Some(own.Budget.saturating_sub(own.CurrentUsage))
  1620. }
  1621. /// Puts back what a run changed.
  1622. fn restore(&mut self, contents: bool) -> Result<()> {
  1623. if self.fresh {
  1624. return Ok(());
  1625. }
  1626. let restored: HashMap<u32, &ID3D12Resource> = if contents {
  1627. self.masters.iter().map(|(id, m)| (*id, m)).collect()
  1628. } else {
  1629. HashMap::new()
  1630. };
  1631. let (mut idle, mut into, mut back, mut plain) =
  1632. (Vec::new(), Vec::new(), Vec::new(), Vec::new());
  1633. for (id, start) in &self.start {
  1634. let Some(o) = self.objects.get(id) else {
  1635. continue;
  1636. };
  1637. let end = self.end.get(id).unwrap_or(start);
  1638. if restored.contains_key(id) {
  1639. gpu::moves(&o.res, end, &[COPY_DEST], &mut into);
  1640. gpu::moves(&o.res, &[COPY_DEST], start, &mut back);
  1641. } else if self.frame.resources[o.index].idle {
  1642. gpu::moves(&o.res, end, start, &mut idle);
  1643. } else {
  1644. gpu::moves(&o.res, end, start, &mut plain);
  1645. }
  1646. }
  1647. let objects = &self.objects;
  1648. self.worker.run(|list| {
  1649. // SAFETY: an open list; live resources, each copied from one of
  1650. // its own description.
  1651. unsafe {
  1652. barriers(list, &idle);
  1653. barriers(list, &[alias()]);
  1654. barriers(list, &plain);
  1655. barriers(list, &into);
  1656. for (id, m) in &restored {
  1657. list.CopyResource(&objects[id].res, *m);
  1658. }
  1659. barriers(list, &back);
  1660. }
  1661. })?;
  1662. self.fresh = true;
  1663. Ok(())
  1664. }
  1665. fn pipelines_named(&self, name: &str) -> HashSet<u32> {
  1666. self.frame
  1667. .pipelines
  1668. .iter()
  1669. .filter(|p| p.name == name)
  1670. .map(|p| p.id)
  1671. .collect()
  1672. }
  1673. /// The frame's lists, edited: for each submission, its lists' commands.
  1674. fn edited(
  1675. &mut self,
  1676. o: &Options,
  1677. report: &mut Report,
  1678. clamps: &[Vec<Clamp>],
  1679. ) -> Vec<Vec<Vec<Cmd>>> {
  1680. let skip: HashSet<u32> = self
  1681. .frame
  1682. .pipelines
  1683. .iter()
  1684. .filter(|p| {
  1685. let hashes = self.hashes(p);
  1686. o.skip_shaders.iter().any(|s| {
  1687. !s.is_empty()
  1688. && (p.name.contains(s.as_str())
  1689. || hashes.iter().any(|h| h.contains(s.as_str())))
  1690. })
  1691. })
  1692. .map(|p| p.id)
  1693. .collect();
  1694. if !o.skip_shaders.is_empty() {
  1695. report
  1696. .notes
  1697. .push(format!("{} pipelines match --skip-shader", skip.len()));
  1698. }
  1699. let hash = self.pipelines_named(COMPARE);
  1700. let (mut skipped, mut hashed, mut uavs, mut merged) = (0, 0, 0, 0);
  1701. let mut place = 0;
  1702. let mut out = Vec::new();
  1703. for s in &self.frame.submits {
  1704. let mut lists = Vec::new();
  1705. for &l in s.lists.iter().filter(|&&l| l != MISSING) {
  1706. let mut cmds = self.commands[l as usize].clone();
  1707. let here = place;
  1708. place += 1;
  1709. if o.only.is_some_and(|(from, to)| here < from || here > to) {
  1710. lists.push(edit::barriers_only(cmds));
  1711. continue;
  1712. }
  1713. if o.skip_clamps
  1714. && let Some(c) = clamps.get(here as usize)
  1715. {
  1716. cmds = edit::skip_clamps(cmds, c);
  1717. }
  1718. let mut n;
  1719. if !skip.is_empty() {
  1720. (cmds, n) = edit::skip_pipelines(cmds, &skip);
  1721. skipped += n;
  1722. }
  1723. if o.skip_hash_passes {
  1724. (cmds, n) = edit::skip_pipelines(cmds, &hash);
  1725. hashed += n;
  1726. }
  1727. if o.no_barriers {
  1728. (cmds, n) = edit::no_uav_barriers(cmds);
  1729. uavs += n;
  1730. }
  1731. if o.merge_barriers {
  1732. (cmds, n) = edit::merge_barriers(cmds);
  1733. merged += n;
  1734. }
  1735. lists.push(cmds);
  1736. }
  1737. out.push(lists);
  1738. }
  1739. if !skip.is_empty() {
  1740. report
  1741. .notes
  1742. .push(format!("--skip-shader left out {skipped} commands"));
  1743. }
  1744. if o.skip_hash_passes {
  1745. report
  1746. .notes
  1747. .push(format!("--skip-hash-passes left out {hashed} dispatches"));
  1748. }
  1749. if o.no_barriers {
  1750. report.notes.push(format!(
  1751. "--no-barriers left out {uavs} unordered-access barriers"
  1752. ));
  1753. }
  1754. if o.merge_barriers {
  1755. report.notes.push(format!(
  1756. "--merge-barriers joined {merged} barrier calls to ones before them"
  1757. ));
  1758. }
  1759. out
  1760. }
  1761. /// The clamp passes of each list of the frame, in order, and their
  1762. /// results in [`RESULTS`] (by a run that keeps them).
  1763. fn clamp_results(&mut self, report: &mut Report) -> Result<Vec<Vec<Clamp>>> {
  1764. let psos = self.pipelines_named(CLAMP);
  1765. let mut next = 0;
  1766. let mut clamps = Vec::new();
  1767. let mut submits = Vec::new();
  1768. for s in &self.frame.submits {
  1769. let mut lists = Vec::new();
  1770. for &l in s.lists.iter().filter(|&&l| l != MISSING) {
  1771. let cmds = self.commands[l as usize].clone();
  1772. let found = edit::find_clamps(&cmds, &psos, &mut next);
  1773. lists.push(edit::keep_clamped(cmds, &found));
  1774. clamps.push(found);
  1775. }
  1776. submits.push(lists);
  1777. }
  1778. let n: usize = clamps.iter().map(Vec::len).sum();
  1779. report.notes.push(format!(
  1780. "--skip-clamps: {n} clamp passes, {} KB of arguments kept from a first run",
  1781. next >> 10
  1782. ));
  1783. if n == 0 {
  1784. return Ok(clamps);
  1785. }
  1786. self.results = Some(
  1787. gpu::buffer(
  1788. &self.device,
  1789. D3D12_HEAP_TYPE_DEFAULT,
  1790. next,
  1791. D3D12_RESOURCE_FLAG_NONE,
  1792. )?
  1793. .0,
  1794. );
  1795. let built = self.build(&submits, &Options::default())?;
  1796. self.restore(true)?;
  1797. self.send(&built, &Options::default())?;
  1798. self.fresh = false;
  1799. Ok(clamps)
  1800. }
  1801. /// Makes the lists of all submissions, and before each one's the copies
  1802. /// of what the CPU wrote.
  1803. fn build(&self, submits: &[Vec<Vec<Cmd>>], o: &Options) -> Result<Sends> {
  1804. // Room for the timestamps of every command that has one.
  1805. let count: usize = submits
  1806. .iter()
  1807. .flatten()
  1808. .map(|c| {
  1809. 2 + if o.detailed {
  1810. c.iter()
  1811. .filter(|c| c.works() || matches!(c, Cmd::Barriers { .. }))
  1812. .count()
  1813. } else {
  1814. 0
  1815. }
  1816. })
  1817. .sum::<usize>()
  1818. + 2 * submits.len();
  1819. let mut heap: Option<ID3D12QueryHeap> = None;
  1820. let desc = D3D12_QUERY_HEAP_DESC {
  1821. Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP,
  1822. Count: count.max(1) as u32,
  1823. NodeMask: 0,
  1824. };
  1825. // SAFETY: plain creation.
  1826. unsafe { self.device.CreateQueryHeap(&desc, &mut heap)? };
  1827. let heap = heap.context("no timestamps")?;
  1828. let (back, data) = gpu::buffer(
  1829. &self.device,
  1830. D3D12_HEAP_TYPE_READBACK,
  1831. count.max(1) as u64 * 8,
  1832. D3D12_RESOURCE_FLAG_NONE,
  1833. )?;
  1834. let mut next = 0u32;
  1835. let mut steps = Vec::new();
  1836. for (i, lists) in submits.iter().enumerate() {
  1837. let parts = self.delta_parts.get(i).filter(|p| !p.is_empty());
  1838. let delta = match (parts, &self.deltas) {
  1839. (Some(parts), Some(from)) => {
  1840. let open = self.open(&heap, &mut next)?;
  1841. // SAFETY: an open list; live buffers.
  1842. unsafe {
  1843. let mut seen = HashSet::new();
  1844. let mut after = Vec::new();
  1845. for (d, at) in parts {
  1846. let Some(ob) = self.objects.get(&d.res) else {
  1847. continue;
  1848. };
  1849. open.1.CopyBufferRegion(&ob.res, d.at, from, *at, d.len);
  1850. if seen.insert(d.res) {
  1851. // Back to the common state by itself, for
  1852. // lists in the same submission.
  1853. after.push(gpu::transition(&ob.res, ALL, COPY_DEST, COMMON));
  1854. }
  1855. }
  1856. barriers(&open.1, &after);
  1857. }
  1858. Some(self.close(open, &heap, &mut next, Vec::new())?)
  1859. }
  1860. _ => None,
  1861. };
  1862. let mut built = Vec::new();
  1863. for cmds in lists {
  1864. let open = self.open(&heap, &mut next)?;
  1865. let stamps = self.translate(
  1866. &open.1,
  1867. cmds,
  1868. i,
  1869. o.detailed.then_some((&heap, &mut next)),
  1870. o.wait_all,
  1871. );
  1872. built.push(self.close(open, &heap, &mut next, stamps)?);
  1873. }
  1874. steps.push((delta, built));
  1875. }
  1876. // Between submissions that are sent as one: everything waits. A list
  1877. // each: one cannot stand twice in a submission.
  1878. let mut joints = Vec::new();
  1879. if o.one_submit {
  1880. for _ in 0..2 * submits.len() {
  1881. let open = self.plain_list()?;
  1882. // SAFETY: an open list.
  1883. unsafe {
  1884. self.wait_for_all(&open.1);
  1885. open.1.Close()?;
  1886. }
  1887. joints.push(open);
  1888. }
  1889. }
  1890. let resolve = {
  1891. let open = self.plain_list()?;
  1892. // SAFETY: an open list; `next` queries were written.
  1893. unsafe {
  1894. open.1.ResolveQueryData(
  1895. &heap,
  1896. D3D12_QUERY_TYPE_TIMESTAMP,
  1897. 0,
  1898. next.max(1),
  1899. &back,
  1900. 0,
  1901. );
  1902. open.1.Close()?;
  1903. }
  1904. open
  1905. };
  1906. Ok(Sends {
  1907. steps,
  1908. joints,
  1909. resolve,
  1910. _heap: heap,
  1911. _back: back,
  1912. data: data as usize,
  1913. count: next,
  1914. })
  1915. }
  1916. /// Records a wait for everything before, with all caches written out.
  1917. ///
  1918. /// # Safety
  1919. /// An open list.
  1920. unsafe fn wait_for_all(&self, list: &ID3D12GraphicsCommandList) {
  1921. // SAFETY: the caller's; a feature structure of its size.
  1922. unsafe {
  1923. let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS12::default();
  1924. let size = size_of::<D3D12_FEATURE_DATA_D3D12_OPTIONS12>() as u32;
  1925. let known = self
  1926. .device
  1927. .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS12, (&raw mut o).cast(), size)
  1928. .is_ok();
  1929. if known
  1930. && o.EnhancedBarriersSupported.as_bool()
  1931. && let Ok(list) = list.cast::<ID3D12GraphicsCommandList7>()
  1932. {
  1933. let all = [D3D12_GLOBAL_BARRIER {
  1934. SyncBefore: D3D12_BARRIER_SYNC_ALL,
  1935. SyncAfter: D3D12_BARRIER_SYNC_ALL,
  1936. AccessBefore: D3D12_BARRIER_ACCESS_COMMON,
  1937. AccessAfter: D3D12_BARRIER_ACCESS_COMMON,
  1938. }];
  1939. list.Barrier(&[D3D12_BARRIER_GROUP {
  1940. Type: D3D12_BARRIER_TYPE_GLOBAL,
  1941. NumBarriers: 1,
  1942. Anonymous: D3D12_BARRIER_GROUP_0 {
  1943. pGlobalBarriers: all.as_ptr(),
  1944. },
  1945. }]);
  1946. } else {
  1947. list.ResourceBarrier(&[alias(), uav_barrier(None)]);
  1948. }
  1949. }
  1950. }
  1951. fn plain_list(&self) -> Result<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)> {
  1952. // SAFETY: plain creation.
  1953. unsafe {
  1954. let allocator: ID3D12CommandAllocator = self
  1955. .device
  1956. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  1957. let list = self.device.CreateCommandList(
  1958. 0,
  1959. D3D12_COMMAND_LIST_TYPE_DIRECT,
  1960. &allocator,
  1961. None,
  1962. )?;
  1963. Ok((allocator, list))
  1964. }
  1965. }
  1966. fn open(
  1967. &self,
  1968. heap: &ID3D12QueryHeap,
  1969. next: &mut u32,
  1970. ) -> Result<(ID3D12CommandAllocator, ID3D12GraphicsCommandList, u32)> {
  1971. let (allocator, list) = self.plain_list()?;
  1972. // SAFETY: an open list; a query of the heap.
  1973. unsafe { list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, *next) };
  1974. *next += 1;
  1975. Ok((allocator, list, *next - 1))
  1976. }
  1977. fn close(
  1978. &self,
  1979. (allocator, list, first): (ID3D12CommandAllocator, ID3D12GraphicsCommandList, u32),
  1980. heap: &ID3D12QueryHeap,
  1981. next: &mut u32,
  1982. stamps: Vec<Stamp>,
  1983. ) -> Result<Built> {
  1984. // SAFETY: as above.
  1985. unsafe {
  1986. list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, *next);
  1987. list.Close()
  1988. .context("a list of the frame could not be recorded again")?;
  1989. }
  1990. *next += 1;
  1991. Ok(Built {
  1992. _allocator: allocator,
  1993. list,
  1994. first,
  1995. last: *next - 1,
  1996. stamps,
  1997. })
  1998. }
  1999. /// Records commands into a list, in submission `submit`.
  2000. fn translate(
  2001. &self,
  2002. list: &ID3D12GraphicsCommandList,
  2003. cmds: &[Cmd],
  2004. submit: usize,
  2005. mut stamp: Option<(&ID3D12QueryHeap, &mut u32)>,
  2006. wait: bool,
  2007. ) -> Vec<Stamp> {
  2008. let version = self.version_of.get(submit).copied().unwrap_or(0);
  2009. let clamps = self.pipelines_named(CLAMP);
  2010. let compares = self.pipelines_named(COMPARE);
  2011. let mesh: HashSet<u32> = self
  2012. .frame
  2013. .pipelines
  2014. .iter()
  2015. .filter(|p| p.parts.iter().any(|part| matches!(part, wire::Part::Code { kind, .. } if *kind == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0)))
  2016. .map(|p| p.id)
  2017. .collect();
  2018. let dispatches: HashSet<u32> = self
  2019. .frame
  2020. .signatures
  2021. .iter()
  2022. .filter(|s| {
  2023. s.args
  2024. .iter()
  2025. .any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32)
  2026. })
  2027. .map(|s| s.id)
  2028. .collect();
  2029. let mut stamps = Vec::new();
  2030. let mut bound = NONE;
  2031. for c in cmds {
  2032. if let Cmd::Pipeline { pso } = c {
  2033. bound = *pso;
  2034. }
  2035. // SAFETY: an open list; the objects are the frame's, alive with
  2036. // the player; commands the host recorded the same way.
  2037. unsafe { self.command(list, c, version) };
  2038. if wait && c.works() {
  2039. // SAFETY: an open list.
  2040. unsafe { self.wait_for_all(list) };
  2041. }
  2042. let timed = c.works() || matches!(c, Cmd::Barriers { .. });
  2043. if timed && let Some((heap, next)) = &mut stamp {
  2044. // SAFETY: as above.
  2045. unsafe { list.EndQuery(*heap, D3D12_QUERY_TYPE_TIMESTAMP, **next) };
  2046. let category = match c {
  2047. Cmd::Barriers { .. } => "barriers",
  2048. Cmd::Dispatch { .. } if clamps.contains(&bound) => "argument clamps (ours)",
  2049. Cmd::Dispatch { .. } if compares.contains(&bound) => {
  2050. "hash and compare passes (ours)"
  2051. }
  2052. Cmd::Dispatch { .. } => "dispatches",
  2053. Cmd::Indirect { signature, .. } if dispatches.contains(signature) => {
  2054. "indirect dispatches"
  2055. }
  2056. Cmd::Indirect { .. } if mesh.contains(&bound) => "indirect mesh draws",
  2057. Cmd::Indirect { .. } => "indirect draws",
  2058. Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::DispatchMesh { .. } => {
  2059. "draws"
  2060. }
  2061. Cmd::ClearDepth { .. } | Cmd::ClearTarget { .. } | Cmd::Discard { .. } => {
  2062. "clears"
  2063. }
  2064. Cmd::Resolve { .. } | Cmd::ResolveRegion { .. } => "resolves",
  2065. _ => "copies",
  2066. };
  2067. let runs = if c.runs_shaders() { bound } else { NONE };
  2068. stamps.push((**next as usize, category, runs));
  2069. **next += 1;
  2070. }
  2071. }
  2072. stamps
  2073. }
  2074. unsafe fn command(&self, l: &ID3D12GraphicsCommandList, c: &Cmd, version: usize) {
  2075. let res = |id: u32| self.resource(id);
  2076. let view = |s: &Slot| self.targets.get(s).copied().unwrap_or_default();
  2077. // SAFETY: the caller's.
  2078. unsafe {
  2079. match c {
  2080. Cmd::Draw {
  2081. vertices,
  2082. instances,
  2083. first,
  2084. first_instance,
  2085. } => l.DrawInstanced(*vertices, *instances, *first, *first_instance),
  2086. Cmd::DrawIndexed {
  2087. indices,
  2088. instances,
  2089. first,
  2090. base,
  2091. first_instance,
  2092. } => {
  2093. l.DrawIndexedInstanced(*indices, *instances, *first, *base, *first_instance);
  2094. }
  2095. Cmd::Dispatch { groups } => l.Dispatch(groups[0], groups[1], groups[2]),
  2096. Cmd::DispatchMesh { groups } => {
  2097. if let Ok(l) = l.cast::<ID3D12GraphicsCommandList6>() {
  2098. l.DispatchMesh(groups[0], groups[1], groups[2]);
  2099. }
  2100. }
  2101. Cmd::CopyBuffer {
  2102. dst,
  2103. dst_at,
  2104. src,
  2105. src_at,
  2106. len,
  2107. } => {
  2108. if let (Some(dst), Some(src)) = (res(*dst), res(*src)) {
  2109. l.CopyBufferRegion(dst, *dst_at, src, *src_at, *len);
  2110. }
  2111. }
  2112. Cmd::CopyTexture { dst, at, src, part } => {
  2113. let side = |loc: &Loc| match loc {
  2114. Loc::Sub { res: id, sub } => Some(gpu::sub_location(res(*id)?, *sub)),
  2115. Loc::Placed {
  2116. res: id,
  2117. offset,
  2118. format,
  2119. size,
  2120. pitch,
  2121. } => {
  2122. let f = D3D12_SUBRESOURCE_FOOTPRINT {
  2123. Format: DXGI_FORMAT(*format),
  2124. Width: size[0],
  2125. Height: size[1],
  2126. Depth: size[2],
  2127. RowPitch: *pitch,
  2128. };
  2129. Some(gpu::placed_location(
  2130. res(*id)?,
  2131. D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
  2132. Offset: *offset,
  2133. Footprint: f,
  2134. },
  2135. ))
  2136. }
  2137. };
  2138. if let (Some(dst), Some(src)) = (side(dst), side(src)) {
  2139. let part = part.map(|p| D3D12_BOX {
  2140. left: p[0],
  2141. top: p[1],
  2142. front: p[2],
  2143. right: p[3],
  2144. bottom: p[4],
  2145. back: p[5],
  2146. });
  2147. l.CopyTextureRegion(
  2148. &dst,
  2149. at[0],
  2150. at[1],
  2151. at[2],
  2152. &src,
  2153. part.as_ref().map(|p| p as *const _),
  2154. );
  2155. }
  2156. }
  2157. Cmd::CopyResource { dst, src } => {
  2158. if let (Some(dst), Some(src)) = (res(*dst), res(*src)) {
  2159. l.CopyResource(dst, src);
  2160. }
  2161. }
  2162. Cmd::Resolve {
  2163. dst,
  2164. dst_sub,
  2165. src,
  2166. src_sub,
  2167. format,
  2168. } => {
  2169. if let (Some(dst), Some(src)) = (res(*dst), res(*src)) {
  2170. l.ResolveSubresource(dst, *dst_sub, src, *src_sub, DXGI_FORMAT(*format));
  2171. }
  2172. }
  2173. Cmd::ResolveRegion {
  2174. dst,
  2175. dst_sub,
  2176. at,
  2177. src,
  2178. src_sub,
  2179. part,
  2180. format,
  2181. mode,
  2182. } => {
  2183. if let (Some(dst), Some(src), Ok(l)) =
  2184. (res(*dst), res(*src), l.cast::<ID3D12GraphicsCommandList1>())
  2185. {
  2186. let part = part.map(to_rect);
  2187. let part = part.as_ref().map(|r| r as *const _);
  2188. l.ResolveSubresourceRegion(
  2189. dst,
  2190. *dst_sub,
  2191. at[0],
  2192. at[1],
  2193. src,
  2194. *src_sub,
  2195. part,
  2196. DXGI_FORMAT(*format),
  2197. D3D12_RESOLVE_MODE(*mode),
  2198. );
  2199. }
  2200. }
  2201. Cmd::Topology { kind } => l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(*kind)),
  2202. Cmd::Viewports { all } => {
  2203. let all: Vec<D3D12_VIEWPORT> = all
  2204. .iter()
  2205. .map(|v| D3D12_VIEWPORT {
  2206. TopLeftX: v[0],
  2207. TopLeftY: v[1],
  2208. Width: v[2],
  2209. Height: v[3],
  2210. MinDepth: v[4],
  2211. MaxDepth: v[5],
  2212. })
  2213. .collect();
  2214. l.RSSetViewports(&all);
  2215. }
  2216. Cmd::Scissors { all } => {
  2217. l.RSSetScissorRects(&all.iter().map(|r| to_rect(*r)).collect::<Vec<_>>())
  2218. }
  2219. Cmd::BlendFactor { factor } => l.OMSetBlendFactor(factor.as_ref()),
  2220. Cmd::StencilRef { value } => l.OMSetStencilRef(*value),
  2221. Cmd::DepthBounds { min, max } => {
  2222. if let Ok(l) = l.cast::<ID3D12GraphicsCommandList1>() {
  2223. l.OMSetDepthBounds(*min, *max);
  2224. }
  2225. }
  2226. Cmd::Pipeline { pso } => {
  2227. if let Some(p) = self.pipelines.get(pso) {
  2228. l.SetPipelineState(p);
  2229. }
  2230. }
  2231. Cmd::Barriers { all } => {
  2232. let all: Vec<D3D12_RESOURCE_BARRIER> =
  2233. all.iter().filter_map(|b| self.barrier(b)).collect();
  2234. barriers(l, &all);
  2235. }
  2236. Cmd::Heaps { heaps } => {
  2237. let all: Vec<Option<ID3D12DescriptorHeap>> = heaps
  2238. .iter()
  2239. .filter_map(|id| {
  2240. Some(Some(self.descriptors.get(id)?.0.get(version)?.heap.clone()))
  2241. })
  2242. .collect();
  2243. l.SetDescriptorHeaps(&all);
  2244. }
  2245. Cmd::RootSignature { graphics, root } => {
  2246. let root = self.roots.get(root);
  2247. if *graphics {
  2248. l.SetGraphicsRootSignature(root)
  2249. } else {
  2250. l.SetComputeRootSignature(root)
  2251. }
  2252. }
  2253. Cmd::Table {
  2254. graphics,
  2255. param,
  2256. heap,
  2257. slot,
  2258. } => {
  2259. if let Some((versions, step)) = self.descriptors.get(heap)
  2260. && let Some(v) = versions.get(version)
  2261. {
  2262. let at = D3D12_GPU_DESCRIPTOR_HANDLE {
  2263. ptr: v.gpu + u64::from(*slot) * step,
  2264. };
  2265. if *graphics {
  2266. l.SetGraphicsRootDescriptorTable(*param, at)
  2267. } else {
  2268. l.SetComputeRootDescriptorTable(*param, at)
  2269. }
  2270. }
  2271. }
  2272. Cmd::Constants {
  2273. graphics,
  2274. param,
  2275. offset,
  2276. values,
  2277. } => {
  2278. let (n, data) = (values.len() as u32, values.as_ptr().cast());
  2279. if *graphics {
  2280. l.SetGraphicsRoot32BitConstants(*param, n, data, *offset);
  2281. } else {
  2282. l.SetComputeRoot32BitConstants(*param, n, data, *offset);
  2283. }
  2284. }
  2285. Cmd::RootView {
  2286. graphics,
  2287. kind,
  2288. param,
  2289. va,
  2290. } => {
  2291. let va = self.va(va);
  2292. match (*kind, *graphics) {
  2293. (slot::CBV, true) => l.SetGraphicsRootConstantBufferView(*param, va),
  2294. (slot::CBV, false) => l.SetComputeRootConstantBufferView(*param, va),
  2295. (slot::SRV, true) => l.SetGraphicsRootShaderResourceView(*param, va),
  2296. (slot::SRV, false) => l.SetComputeRootShaderResourceView(*param, va),
  2297. (_, true) => l.SetGraphicsRootUnorderedAccessView(*param, va),
  2298. (_, false) => l.SetComputeRootUnorderedAccessView(*param, va),
  2299. }
  2300. }
  2301. Cmd::IndexBuffer { view } => {
  2302. let v = view
  2303. .as_ref()
  2304. .map(|(va, size, format)| D3D12_INDEX_BUFFER_VIEW {
  2305. BufferLocation: self.va(va),
  2306. SizeInBytes: *size,
  2307. Format: DXGI_FORMAT(*format),
  2308. });
  2309. l.IASetIndexBuffer(v.as_ref().map(|v| v as *const _));
  2310. }
  2311. Cmd::VertexBuffers {
  2312. start,
  2313. views,
  2314. count,
  2315. } => match views {
  2316. Some(views) => {
  2317. let all: Vec<D3D12_VERTEX_BUFFER_VIEW> = views
  2318. .iter()
  2319. .map(|(va, size, stride)| D3D12_VERTEX_BUFFER_VIEW {
  2320. BufferLocation: self.va(va),
  2321. SizeInBytes: *size,
  2322. StrideInBytes: *stride,
  2323. })
  2324. .collect();
  2325. l.IASetVertexBuffers(*start, Some(&all));
  2326. }
  2327. None => l.IASetVertexBuffers(
  2328. *start,
  2329. Some(&vec![D3D12_VERTEX_BUFFER_VIEW::default(); *count as usize]),
  2330. ),
  2331. },
  2332. Cmd::Targets { colors, depth } => {
  2333. let colors: Vec<D3D12_CPU_DESCRIPTOR_HANDLE> =
  2334. colors.iter().map(view).collect();
  2335. let depth = depth.as_ref().map(view);
  2336. l.OMSetRenderTargets(
  2337. colors.len() as u32,
  2338. (!colors.is_empty()).then_some(colors.as_ptr()),
  2339. false,
  2340. depth.as_ref().map(|d| d as *const _),
  2341. );
  2342. }
  2343. Cmd::ClearDepth {
  2344. view: v,
  2345. flags,
  2346. depth,
  2347. stencil,
  2348. rects,
  2349. } => {
  2350. let rects: Vec<RECT> = rects.iter().map(|r| to_rect(*r)).collect();
  2351. let rects = (!rects.is_empty()).then_some(&rects[..]);
  2352. if self.objects.contains_key(&v.res) {
  2353. l.ClearDepthStencilView(
  2354. view(v),
  2355. D3D12_CLEAR_FLAGS(*flags),
  2356. *depth,
  2357. *stencil,
  2358. rects,
  2359. );
  2360. }
  2361. }
  2362. Cmd::ClearTarget {
  2363. view: v,
  2364. color,
  2365. rects,
  2366. } => {
  2367. let rects: Vec<RECT> = rects.iter().map(|r| to_rect(*r)).collect();
  2368. let rects = (!rects.is_empty()).then_some(&rects[..]);
  2369. if self.objects.contains_key(&v.res) {
  2370. l.ClearRenderTargetView(view(v), color, rects);
  2371. }
  2372. }
  2373. Cmd::Discard {
  2374. res: id,
  2375. rects,
  2376. subs,
  2377. } => {
  2378. if let Some(r) = res(*id) {
  2379. let rects: Vec<RECT> = rects.iter().map(|r| to_rect(*r)).collect();
  2380. let region = subs.map(|s| D3D12_DISCARD_REGION {
  2381. NumRects: rects.len() as u32,
  2382. pRects: if rects.is_empty() {
  2383. std::ptr::null()
  2384. } else {
  2385. rects.as_ptr()
  2386. },
  2387. FirstSubresource: s[0],
  2388. NumSubresources: s[1],
  2389. });
  2390. l.DiscardResource(r, region.as_ref().map(|r| r as *const _));
  2391. }
  2392. }
  2393. Cmd::BeginQuery { heap, kind, index } => {
  2394. if let Some(h) = self.queries.get(heap) {
  2395. l.BeginQuery(h, D3D12_QUERY_TYPE(*kind), *index);
  2396. }
  2397. }
  2398. Cmd::EndQuery { heap, kind, index } => {
  2399. if let Some(h) = self.queries.get(heap) {
  2400. l.EndQuery(h, D3D12_QUERY_TYPE(*kind), *index);
  2401. }
  2402. }
  2403. Cmd::ResolveQuery {
  2404. heap,
  2405. kind,
  2406. first,
  2407. count,
  2408. dst,
  2409. at,
  2410. } => {
  2411. if let (Some(h), Some(dst)) = (self.queries.get(heap), res(*dst)) {
  2412. l.ResolveQueryData(h, D3D12_QUERY_TYPE(*kind), *first, *count, dst, *at);
  2413. }
  2414. }
  2415. Cmd::Indirect {
  2416. signature,
  2417. most,
  2418. args,
  2419. at,
  2420. count,
  2421. count_at,
  2422. } => {
  2423. if let (Some(s), Some(a)) = (self.signatures.get(signature), res(*args)) {
  2424. l.ExecuteIndirect(s, *most, a, *at, res(*count), *count_at);
  2425. }
  2426. }
  2427. Cmd::WriteImmediate { all } => {
  2428. if let Ok(l) = l.cast::<ID3D12GraphicsCommandList2>() {
  2429. let all: Vec<&(Va, u32, i32)> =
  2430. all.iter().filter(|(va, _, _)| self.va(va) != 0).collect();
  2431. let params: Vec<D3D12_WRITEBUFFERIMMEDIATE_PARAMETER> = all
  2432. .iter()
  2433. .map(|(va, v, _)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER {
  2434. Dest: self.va(va),
  2435. Value: *v,
  2436. })
  2437. .collect();
  2438. let modes: Vec<D3D12_WRITEBUFFERIMMEDIATE_MODE> = all
  2439. .iter()
  2440. .map(|(_, _, m)| D3D12_WRITEBUFFERIMMEDIATE_MODE(*m))
  2441. .collect();
  2442. if !params.is_empty() {
  2443. l.WriteBufferImmediate(
  2444. params.len() as u32,
  2445. params.as_ptr(),
  2446. Some(modes.as_ptr()),
  2447. );
  2448. }
  2449. }
  2450. }
  2451. }
  2452. }
  2453. }
  2454. fn barrier(&self, b: &Barrier) -> Option<D3D12_RESOURCE_BARRIER> {
  2455. Some(match b {
  2456. Barrier::Transition {
  2457. flags,
  2458. res,
  2459. sub,
  2460. before,
  2461. after,
  2462. } => {
  2463. let mut t =
  2464. gpu::transition(self.resource(*res)?, *sub, *before as u32, *after as u32);
  2465. t.Flags = D3D12_RESOURCE_BARRIER_FLAGS(*flags);
  2466. t
  2467. }
  2468. Barrier::Uav { flags, res } => {
  2469. let mut u = uav_barrier(if *res == NONE {
  2470. None
  2471. } else {
  2472. Some(self.resource(*res)?)
  2473. });
  2474. u.Flags = D3D12_RESOURCE_BARRIER_FLAGS(*flags);
  2475. u
  2476. }
  2477. Barrier::Alias {
  2478. flags,
  2479. before,
  2480. after,
  2481. } => {
  2482. let side = |id: &u32| -> std::mem::ManuallyDrop<Option<ID3D12Resource>> {
  2483. // SAFETY: a borrowed pointer (or none) never released.
  2484. self.resource(*id)
  2485. .map_or(std::mem::ManuallyDrop::new(None), |r| unsafe {
  2486. std::mem::transmute_copy(r)
  2487. })
  2488. };
  2489. D3D12_RESOURCE_BARRIER {
  2490. Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
  2491. Flags: D3D12_RESOURCE_BARRIER_FLAGS(*flags),
  2492. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  2493. Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER {
  2494. pResourceBefore: side(before),
  2495. pResourceAfter: side(after),
  2496. }),
  2497. },
  2498. }
  2499. }
  2500. })
  2501. }
  2502. /// Sends the frame, waits for it, and reads the timestamps.
  2503. fn send(&mut self, s: &Sends, o: &Options) -> Result<Vec<u64>> {
  2504. let cast = |l: &ID3D12GraphicsCommandList| l.cast::<ID3D12CommandList>().map(Some);
  2505. let mut submissions: Vec<Vec<Option<ID3D12CommandList>>> = Vec::new();
  2506. for (delta, lists) in &s.steps {
  2507. if let Some(d) = delta {
  2508. submissions.push(vec![cast(&d.list)?]);
  2509. }
  2510. let mut all = Vec::new();
  2511. for l in lists {
  2512. all.push(cast(&l.list)?);
  2513. }
  2514. if !all.is_empty() {
  2515. submissions.push(all);
  2516. }
  2517. }
  2518. if o.one_submit {
  2519. let mut all = Vec::new();
  2520. for (i, lists) in submissions.into_iter().enumerate() {
  2521. if i > 0
  2522. && let Some(joint) = s.joints.get(i)
  2523. {
  2524. all.push(cast(&joint.1)?);
  2525. }
  2526. all.extend(lists);
  2527. }
  2528. submissions = vec![all];
  2529. }
  2530. // SAFETY: closed lists whose last run has finished.
  2531. unsafe {
  2532. for all in &submissions {
  2533. if !o.wait_lists {
  2534. self.worker.queue.ExecuteCommandLists(all);
  2535. continue;
  2536. }
  2537. for l in all {
  2538. self.worker.queue.ExecuteCommandLists(&[l.clone()]);
  2539. self.worker.idle()?;
  2540. }
  2541. }
  2542. self.worker
  2543. .queue
  2544. .ExecuteCommandLists(&[cast(&s.resolve.1)?]);
  2545. }
  2546. self.worker
  2547. .idle()
  2548. .context("the card was lost running the frame")?;
  2549. // SAFETY: the mapping of `count` resolved timestamps.
  2550. Ok(unsafe { std::slice::from_raw_parts(s.data as *const u64, s.count as usize) }.to_vec())
  2551. }
  2552. /// Runs the frame as the options say.
  2553. pub fn run(&mut self, o: &Options) -> Result<Report> {
  2554. let mut report = Report {
  2555. notes: self.notes.clone(),
  2556. ..Default::default()
  2557. };
  2558. let clamps = if o.skip_clamps {
  2559. self.clamp_results(&mut report)?
  2560. } else {
  2561. Vec::new()
  2562. };
  2563. let submits = self.edited(o, &mut report, &clamps);
  2564. let built = self.build(&submits, o)?;
  2565. let mut stamps = Vec::new();
  2566. for _ in 0..o.loops.max(1) {
  2567. self.restore(o.restore)?;
  2568. self.fresh = false;
  2569. stamps = self.send(&built, o)?;
  2570. if let Some((db, _, hash, _)) = self.picture_now()? {
  2571. report.pictures.push((db, hash));
  2572. }
  2573. let ms = |a: u32, b: u32| {
  2574. stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency
  2575. };
  2576. let lists: Vec<&Built> = built.steps.iter().flat_map(|(_, l)| l).collect();
  2577. let (Some(first), Some(last)) = (lists.first(), lists.last()) else {
  2578. bail!("no lists to run");
  2579. };
  2580. let delta = built.steps.iter().filter_map(|(d, _)| d.as_ref());
  2581. report.delta_ms.push(
  2582. delta
  2583. .filter(|d| d.first > first.first)
  2584. .map(|d| ms(d.first, d.last))
  2585. .sum(),
  2586. );
  2587. report.frame_ms.push(ms(first.first, last.last));
  2588. let each = |l: &[Built]| match (l.first(), l.last()) {
  2589. (Some(a), Some(b)) => ms(a.first, b.last),
  2590. _ => 0.0,
  2591. };
  2592. report.submits = built
  2593. .steps
  2594. .iter()
  2595. .map(|(_, l)| (l.len(), each(l)))
  2596. .collect();
  2597. report
  2598. .busy_ms
  2599. .push(report.submits.iter().map(|s| s.1).sum());
  2600. }
  2601. if o.detailed {
  2602. self.detail(&built, &stamps, o, &mut report);
  2603. }
  2604. self.picture(o, &mut report)?;
  2605. if let Some(q) = &self.info {
  2606. report.notes.extend(debug_messages(q));
  2607. }
  2608. Ok(report)
  2609. }
  2610. /// The last loop's time by command.
  2611. fn detail(&self, built: &Sends, stamps: &[u64], o: &Options, report: &mut Report) {
  2612. let mut kinds: BTreeMap<&str, (f64, u32)> = BTreeMap::new();
  2613. let mut shaders: HashMap<u32, (f64, u32)> = HashMap::new();
  2614. for l in built.steps.iter().flat_map(|(_, l)| l) {
  2615. let mut before = stamps[l.first as usize];
  2616. for &(at, kind, pso) in &l.stamps {
  2617. let ms = stamps[at].saturating_sub(before) as f64 * 1e3 / self.frequency;
  2618. before = before.max(stamps[at]);
  2619. let k = kinds.entry(kind).or_default();
  2620. *k = (k.0 + ms, k.1 + 1);
  2621. if pso != NONE {
  2622. let s = shaders.entry(pso).or_default();
  2623. *s = (s.0 + ms, s.1 + 1);
  2624. }
  2625. }
  2626. }
  2627. report.categories = kinds
  2628. .into_iter()
  2629. .map(|(k, (ms, n))| (k.to_owned(), ms, n))
  2630. .collect();
  2631. report.categories.sort_by(|a, b| b.1.total_cmp(&a.1));
  2632. let mut all: Vec<(f64, u32, u32)> = shaders
  2633. .into_iter()
  2634. .map(|(pso, (ms, n))| (ms, n, pso))
  2635. .collect();
  2636. all.sort_by(|a, b| b.0.total_cmp(&a.0));
  2637. all.truncate(o.top);
  2638. report.shaders = all
  2639. .into_iter()
  2640. .map(|(ms, n, pso)| (ms, n, self.pipeline_name(pso)))
  2641. .collect();
  2642. }
  2643. /// The presented picture as it is now: dB against the recorded one,
  2644. /// whether its bytes are the same, its hash, and its pixels.
  2645. fn picture_now(&mut self) -> Result<Option<(f64, bool, String, Vec<u8>)>> {
  2646. let Some(p) = self.frame.presents.last().cloned() else {
  2647. return Ok(None);
  2648. };
  2649. let Some(bytes) = self.contents(p.res)? else {
  2650. return Ok(None);
  2651. };
  2652. let Some(rgb) = gpu::rgb(p.width, p.height, p.pitch, p.format, &bytes) else {
  2653. return Ok(None);
  2654. };
  2655. let mut recorded = vec![0; bytes.len()];
  2656. read_at(
  2657. &File::open(self.folder.join("present.bin"))?,
  2658. &mut recorded,
  2659. p.file,
  2660. )?;
  2661. let was = gpu::rgb(p.width, p.height, p.pitch, p.format, &recorded).unwrap_or_default();
  2662. let hash = blake3::hash(&rgb).to_hex().to_string();
  2663. Ok(Some((
  2664. gpu::psnr(&rgb, &was),
  2665. rows_equal(&p, &bytes, &recorded),
  2666. hash,
  2667. rgb,
  2668. )))
  2669. }
  2670. /// Saves the presented picture and compares it with the recorded one.
  2671. fn picture(&mut self, o: &Options, report: &mut Report) -> Result<()> {
  2672. let Some(p) = self.frame.presents.last().cloned() else {
  2673. report.notes.push("no picture was presented".into());
  2674. return Ok(());
  2675. };
  2676. let Some(bytes) = self.contents(p.res)? else {
  2677. report
  2678. .notes
  2679. .push("the presented texture is not there".into());
  2680. return Ok(());
  2681. };
  2682. let Some(rgb) = gpu::rgb(p.width, p.height, p.pitch, p.format, &bytes) else {
  2683. report
  2684. .notes
  2685. .push("the presented format is not shown".into());
  2686. return Ok(());
  2687. };
  2688. let path = o
  2689. .image
  2690. .clone()
  2691. .unwrap_or_else(|| self.folder.join("replay.png"));
  2692. std::fs::write(&path, crate::capture::png(p.width, p.height, &rgb))?;
  2693. let mut recorded = vec![0; bytes.len()];
  2694. read_at(
  2695. &File::open(self.folder.join("present.bin"))?,
  2696. &mut recorded,
  2697. p.file,
  2698. )?;
  2699. let was = gpu::rgb(p.width, p.height, p.pitch, p.format, &recorded).unwrap_or_default();
  2700. report.picture = Some((gpu::psnr(&rgb, &was), rows_equal(&p, &bytes, &recorded)));
  2701. report.notes.push(format!(
  2702. "picture {} (blake3 {}; recorded {})",
  2703. path.display(),
  2704. &blake3::hash(&rgb).to_hex()[..16],
  2705. &blake3::hash(&was).to_hex()[..16]
  2706. ));
  2707. Ok(())
  2708. }
  2709. /// What a resource holds now (after a run): a buffer's bytes, or a
  2710. /// texture's first subresource in its copyable layout.
  2711. pub fn contents(&mut self, id: u32) -> Result<Option<Vec<u8>>> {
  2712. self.contents_of(id, 0)
  2713. }
  2714. /// As [`Player::contents`], of a texture's subresource `sub`.
  2715. pub fn contents_of(&mut self, id: u32, sub: u32) -> Result<Option<Vec<u8>>> {
  2716. let Some(o) = self.objects.get(&id) else {
  2717. return Ok(None);
  2718. };
  2719. let (res, r, subs) = (o.res.clone(), &self.frame.resources[o.index], o.subs);
  2720. let desc = gpu::to_desc(&r.desc);
  2721. let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0;
  2722. let states = if self.fresh { &self.start } else { &self.end };
  2723. let state = states.get(&id).cloned().unwrap_or(vec![COMMON]);
  2724. let (f, total) = if is_buffer {
  2725. (Vec::new(), r.desc.width)
  2726. } else {
  2727. gpu::footprints(&self.device, &desc, sub, 1)
  2728. };
  2729. let (back, data) = gpu::buffer(
  2730. &self.device,
  2731. D3D12_HEAP_TYPE_READBACK,
  2732. total,
  2733. D3D12_RESOURCE_FLAG_NONE,
  2734. )?;
  2735. self.worker.run(|list| {
  2736. if is_buffer {
  2737. // SAFETY: an open list; live buffers.
  2738. unsafe { list.CopyBufferRegion(&back, 0, &res, 0, total) };
  2739. } else if state.len() == 1 || subs == 1 {
  2740. read_sub(list, &res, sub, state[0], &back, f[0]);
  2741. } else {
  2742. let (mut before, mut after) = (Vec::new(), Vec::new());
  2743. gpu::moves(&res, &state, &[COPY_SOURCE], &mut before);
  2744. gpu::moves(&res, &[COPY_SOURCE], &state, &mut after);
  2745. // SAFETY: an open list; live resources.
  2746. unsafe { barriers(list, &before) };
  2747. read_sub(list, &res, sub, COPY_SOURCE, &back, f[0]);
  2748. // SAFETY: as above.
  2749. unsafe { barriers(list, &after) };
  2750. }
  2751. })?;
  2752. // SAFETY: the buffer's mapping; the copy into it has run.
  2753. Ok(Some(
  2754. unsafe { std::slice::from_raw_parts(data, total as usize) }.to_vec(),
  2755. ))
  2756. }
  2757. /// The id of the resource of a name (tests).
  2758. pub fn named(&self, name: &str) -> Option<u32> {
  2759. self.frame
  2760. .resources
  2761. .iter()
  2762. .find(|r| r.name == name)
  2763. .map(|r| r.id)
  2764. }
  2765. }
  2766. /// Everything to send for a frame.
  2767. struct Sends {
  2768. /// For each submission: the copies of what the CPU wrote, its lists.
  2769. steps: Vec<(Option<Built>, Vec<Built>)>,
  2770. joints: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)>,
  2771. resolve: (ID3D12CommandAllocator, ID3D12GraphicsCommandList),
  2772. _heap: ID3D12QueryHeap,
  2773. _back: ID3D12Resource,
  2774. data: usize,
  2775. count: u32,
  2776. }
  2777. fn rows_equal(p: &wire::Present, a: &[u8], b: &[u8]) -> bool {
  2778. let texel = match p.format {
  2779. 9..=14 => 8,
  2780. _ => 4,
  2781. };
  2782. (0..p.height as usize).all(|y| {
  2783. let from = y * p.pitch as usize;
  2784. let to = from + p.width as usize * texel;
  2785. a.get(from..to) == b.get(from..to)
  2786. })
  2787. }
  2788. fn to_rect(r: [i32; 4]) -> RECT {
  2789. RECT {
  2790. left: r[0],
  2791. top: r[1],
  2792. right: r[2],
  2793. bottom: r[3],
  2794. }
  2795. }
  2796. /// # Safety
  2797. /// An open list; barriers of live resources.
  2798. unsafe fn barriers(list: &ID3D12GraphicsCommandList, all: &[D3D12_RESOURCE_BARRIER]) {
  2799. for some in all.chunks(1000) {
  2800. // SAFETY: the caller's.
  2801. unsafe { list.ResourceBarrier(some) };
  2802. }
  2803. }
  2804. fn uav_barrier(res: Option<&ID3D12Resource>) -> D3D12_RESOURCE_BARRIER {
  2805. D3D12_RESOURCE_BARRIER {
  2806. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  2807. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  2808. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  2809. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  2810. // SAFETY: a borrowed pointer (or none) never released.
  2811. pResource: res.map_or(std::mem::ManuallyDrop::new(None), |r| unsafe {
  2812. std::mem::transmute_copy(r)
  2813. }),
  2814. }),
  2815. },
  2816. }
  2817. }
  2818. /// Any placed resource to any other: waits for all writes.
  2819. fn alias() -> D3D12_RESOURCE_BARRIER {
  2820. D3D12_RESOURCE_BARRIER {
  2821. Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
  2822. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  2823. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  2824. Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER {
  2825. pResourceBefore: std::mem::ManuallyDrop::new(None),
  2826. pResourceAfter: std::mem::ManuallyDrop::new(None),
  2827. }),
  2828. },
  2829. }
  2830. }
  2831. fn read_at(file: &File, mut to: &mut [u8], mut at: u64) -> std::io::Result<()> {
  2832. while !to.is_empty() {
  2833. let n = file.seek_read(to, at)?;
  2834. if n == 0 {
  2835. return Err(std::io::ErrorKind::UnexpectedEof.into());
  2836. }
  2837. to = &mut to[n..];
  2838. at += n as u64;
  2839. }
  2840. Ok(())
  2841. }
  2842. fn make_device(frame: &Frame, debug: bool) -> Result<(ID3D12Device, Option<ID3D12InfoQueue>)> {
  2843. // SAFETY: plain creation and queries.
  2844. unsafe {
  2845. if debug {
  2846. let mut layer: Option<ID3D12Debug> = None;
  2847. match D3D12GetDebugInterface(&mut layer) {
  2848. Ok(()) => layer.iter().for_each(|l| {
  2849. l.EnableDebugLayer();
  2850. // Every shader access checked on the card: very slow.
  2851. if std::env::var_os("VICTORY_REPLAY_GBV").is_some()
  2852. && let Ok(l) = l.cast::<ID3D12Debug1>()
  2853. {
  2854. l.SetEnableGPUBasedValidation(true);
  2855. }
  2856. }),
  2857. Err(e) => tracing::warn!("no debug layer: {e}"),
  2858. }
  2859. }
  2860. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  2861. let mut adapter = None;
  2862. for i in 0.. {
  2863. let Ok(a) = factory.EnumAdapters1(i) else {
  2864. break;
  2865. };
  2866. let d = a.GetDesc1()?;
  2867. if (d.VendorId, d.DeviceId) == (frame.vendor, frame.device) {
  2868. adapter = Some(a);
  2869. break;
  2870. }
  2871. }
  2872. if adapter.is_none() {
  2873. tracing::warn!(
  2874. "the adapter recorded on ({}) is not here: the default one is used",
  2875. frame.adapter
  2876. );
  2877. }
  2878. let mut device: Option<ID3D12Device> = None;
  2879. match &adapter {
  2880. Some(a) => D3D12CreateDevice(a, D3D_FEATURE_LEVEL_12_0, &mut device)?,
  2881. None => D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?,
  2882. }
  2883. let device = device.context("no device")?;
  2884. let info = device.cast::<ID3D12InfoQueue>().ok();
  2885. Ok((device, info))
  2886. }
  2887. }
  2888. /// The debug layer's errors: how many of each kind, and its first text.
  2889. fn debug_messages(q: &ID3D12InfoQueue) -> Vec<String> {
  2890. let mut seen: BTreeMap<i32, (u32, String)> = BTreeMap::new();
  2891. // SAFETY: messages read into buffers of the size asked for.
  2892. unsafe {
  2893. for i in 0..q.GetNumStoredMessages() {
  2894. let mut size = 0;
  2895. if q.GetMessage(i, None, &mut size).is_err() {
  2896. continue;
  2897. }
  2898. let mut buffer = vec![0u64; size.div_ceil(8)];
  2899. let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  2900. if q.GetMessage(i, Some(message), &mut size).is_err() {
  2901. continue;
  2902. }
  2903. let m = &*message;
  2904. if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 {
  2905. let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
  2906. let text = || {
  2907. String::from_utf8_lossy(text)
  2908. .trim_end_matches('\0')
  2909. .to_owned()
  2910. };
  2911. seen.entry(m.ID.0).or_insert_with(|| (0, text())).0 += 1;
  2912. }
  2913. }
  2914. q.ClearStoredMessages();
  2915. }
  2916. seen.into_iter()
  2917. .map(|(id, (n, text))| format!("debug layer: {n} errors {id}, first: {text}"))
  2918. .collect()
  2919. }
  2920. #[cfg(test)]
  2921. mod tests {
  2922. use super::*;
  2923. #[test]
  2924. fn captures_are_found() {
  2925. let dir = tempfile::tempdir().unwrap();
  2926. assert!(find(dir.path()).is_err());
  2927. for n in [1, 2, 10, 11] {
  2928. std::fs::create_dir(dir.path().join(format!("capture-{n}"))).unwrap();
  2929. }
  2930. for n in [1, 2, 10] {
  2931. std::fs::write(dir.path().join(format!("capture-{n}/frame.bin")), "").unwrap();
  2932. }
  2933. // The last complete one; itself when named.
  2934. assert_eq!(find(dir.path()).unwrap(), dir.path().join("capture-10"));
  2935. assert_eq!(
  2936. find(&dir.path().join("capture-2")).unwrap(),
  2937. dir.path().join("capture-2")
  2938. );
  2939. }
  2940. #[test]
  2941. fn reports() {
  2942. assert_eq!(median(&[]), 0.0);
  2943. assert_eq!(median(&[3.0, 1.0, 2.0]), 2.0);
  2944. let r = Report {
  2945. frame_ms: vec![10.0, 12.0, 11.0],
  2946. busy_ms: vec![9.0; 3],
  2947. delta_ms: vec![0.5; 3],
  2948. submits: vec![(2, 9.0)],
  2949. picture: Some((40.0, false)),
  2950. ..Default::default()
  2951. };
  2952. let t = r.text("a frame");
  2953. assert!(t.contains("a frame: 11.00 ms"), "{t}");
  2954. assert!(t.contains("between submissions 1.50 ms"), "{t}");
  2955. assert!(t.contains("PSNR 40.0 dB"), "{t}");
  2956. let o = Options {
  2957. skip_clamps: true,
  2958. buffers: Buffers::Card,
  2959. ..Default::default()
  2960. };
  2961. assert!(o.edited() && !o.plain().edited() && o.plain().buffers == Buffers::Card);
  2962. }
  2963. }