diverge.rs 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  1. //! Where identical runs of a frame part: every list is run several times
  2. //! from the very same memory (what the frame writes is put back before each,
  3. //! and everything before it was run once), so what differs after it was made
  4. //! different by it; then the first command of the list that does so, by
  5. //! halving the list. The state after the last run is what the rest goes on
  6. //! from, so each finding is a root, not a consequence.
  7. use super::*;
  8. /// A part of memory compared as one.
  9. const PIECE: usize = 64 << 10;
  10. /// Where a run's contents come down: for each resource (and subresource) the
  11. /// frame writes, its place in read-back memory.
  12. struct Reader {
  13. blocks: Vec<(ID3D12Resource, usize)>,
  14. parts: Vec<Part>,
  15. }
  16. #[derive(Clone)]
  17. struct Part {
  18. id: u32,
  19. /// `None` for a buffer.
  20. sub: Option<(u32, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)>,
  21. block: usize,
  22. at: u64,
  23. len: u64,
  24. }
  25. /// One way to run commands `from..to` of a list.
  26. struct Unit<'a> {
  27. submit: usize,
  28. cmds: &'a [Cmd],
  29. from: usize,
  30. to: usize,
  31. /// With the copies of what the CPU wrote before the submission.
  32. delta: bool,
  33. }
  34. /// What differed between runs: part and piece.
  35. type Pieces = Vec<(usize, usize)>;
  36. /// What to look at.
  37. #[derive(Clone, Debug)]
  38. pub struct Search {
  39. /// Runs of each list.
  40. pub runs: u32,
  41. /// Only these lists (the others are run once).
  42. pub lists: Option<(u32, u32)>,
  43. /// Roots looked for in one list.
  44. pub roots: u32,
  45. /// A full wait after each command.
  46. pub wait_all: bool,
  47. /// Experiments on the frame.
  48. pub options: Options,
  49. }
  50. impl Player {
  51. /// Looks for what makes identical runs differ; `say` gets the findings
  52. /// as they are made.
  53. pub fn diverge(&mut self, s: &Search, say: &mut dyn FnMut(String)) -> Result<()> {
  54. let mut report = Report::default();
  55. let clamps = if s.options.skip_clamps {
  56. self.clamp_results(&mut report)?
  57. } else {
  58. Vec::new()
  59. };
  60. let submits = self.edited(&s.options, &mut report, &clamps);
  61. self.restore(true)?;
  62. self.fresh = false;
  63. let ids: Vec<u32> = self.masters.iter().map(|m| m.0).collect();
  64. let reader = self.reader(&ids)?;
  65. let mb: u64 = reader.parts.iter().map(|p| p.len).sum::<u64>() >> 20;
  66. say(format!(
  67. "{} resources the frame writes ({mb} MB in {} parts) compared after each list, {} runs of each",
  68. self.masters.len(),
  69. reader.parts.len(),
  70. s.runs
  71. ));
  72. let mut states = self.start_states();
  73. let mut global = 0u32;
  74. for (i, lists) in submits.iter().enumerate() {
  75. for (j, cmds) in lists.iter().enumerate() {
  76. let here = global;
  77. global += 1;
  78. let delta = j == 0;
  79. let wanted = s.lists.is_none_or(|(a, b)| (a..=b).contains(&here));
  80. let mut from = 0;
  81. let mut roots = 0;
  82. loop {
  83. let unit = Unit {
  84. submit: i,
  85. cmds,
  86. from,
  87. to: cmds.len(),
  88. delta: delta && from == 0,
  89. };
  90. let looks = wanted && cmds[from..].iter().any(Cmd::works);
  91. let runs = if looks { s.runs } else { 1 };
  92. let pieces = self.trials(&reader, &unit, &states, runs, s.wait_all)?;
  93. if pieces.is_empty() || roots >= s.roots {
  94. self.commit(&unit, &mut states)?;
  95. break;
  96. }
  97. roots += 1;
  98. // The shortest start of the rest that differs.
  99. let works: Vec<usize> =
  100. (from..cmds.len()).filter(|&c| cmds[c].works()).collect();
  101. let (mut lo, mut hi) = (0, works.len() - 1);
  102. while lo < hi {
  103. let mid = (lo + hi) / 2;
  104. let cut = Unit {
  105. to: works[mid] + 1,
  106. ..unit
  107. };
  108. self.put_back(&states)?;
  109. if self
  110. .trials(&reader, &cut, &states, s.runs, s.wait_all)?
  111. .is_empty()
  112. {
  113. lo = mid + 1;
  114. } else {
  115. hi = mid;
  116. }
  117. }
  118. let at = works[lo];
  119. let cut = Unit { to: at + 1, ..unit };
  120. self.put_back(&states)?;
  121. let pieces = self.trials(&reader, &cut, &states, s.runs.max(6), s.wait_all)?;
  122. say(format!(
  123. "list {here} (submission {i}, its list {j}), command {at} of {}: {}",
  124. cmds.len(),
  125. self.describe(cmds, at)
  126. ));
  127. self.put_back(&states)?;
  128. for line in self.compare(&reader, &cut, &states, &pieces, s.wait_all)? {
  129. say(format!(" {line}"));
  130. }
  131. self.commit(&cut, &mut states)?;
  132. from = at + 1;
  133. if from >= cmds.len() {
  134. break;
  135. }
  136. }
  137. }
  138. states.decay();
  139. if s.lists.is_some_and(|(_, b)| global > b) {
  140. break;
  141. }
  142. if i % 5 == 4 {
  143. say(format!("submission {i} done"));
  144. }
  145. }
  146. self.restore_all()?;
  147. Ok(())
  148. }
  149. /// Looks for where the picture's variants are decided: at each list (or,
  150. /// of one list, each `step` commands in `commands`) the rest of the frame
  151. /// is run several times from the same memory. Where the runs' pictures
  152. /// agree from a point on but not from the one before, what lies between
  153. /// decides.
  154. pub fn diverge_picture(
  155. &mut self,
  156. s: &Search,
  157. commands: Option<(u32, u32)>,
  158. step: usize,
  159. say: &mut dyn FnMut(String),
  160. ) -> Result<()> {
  161. let mut report = Report::default();
  162. let submits = self.edited(&s.options, &mut report, &[]);
  163. let flat: Vec<(usize, usize, &Vec<Cmd>)> = submits
  164. .iter()
  165. .enumerate()
  166. .flat_map(|(i, lists)| lists.iter().enumerate().map(move |(j, c)| (i, j, c)))
  167. .collect();
  168. self.restore(true)?;
  169. self.fresh = false;
  170. let mut states = self.start_states();
  171. for (here, &(i, j, cmds)) in flat.iter().enumerate() {
  172. let inside = s.lists.is_some_and(|(a, b)| a == b && a as usize == here);
  173. let looks = s
  174. .lists
  175. .is_none_or(|(a, b)| (a as usize..=b as usize).contains(&here));
  176. let works: Vec<usize> = (0..cmds.len()).filter(|&c| cmds[c].works()).collect();
  177. // Where the list is cut.
  178. let mut cuts: Vec<usize> = vec![0];
  179. if inside {
  180. let (a, b) = commands.unwrap_or((0, u32::MAX));
  181. let some = works
  182. .iter()
  183. .map(|&c| c + 1)
  184. .filter(|c| (a as usize..=b as usize).contains(c));
  185. cuts.extend(some.step_by(step.max(1)));
  186. }
  187. for (k, &from) in cuts.iter().enumerate() {
  188. if looks && !works.is_empty() {
  189. let mut pictures: Vec<(f64, String, Vec<u8>)> = Vec::new();
  190. for run in 0..s.runs {
  191. if run > 0 {
  192. self.put_back(&states)?;
  193. }
  194. let mut now = states.clone();
  195. let first = Unit {
  196. submit: i,
  197. cmds,
  198. from,
  199. to: cmds.len(),
  200. delta: j == 0 && from == 0,
  201. };
  202. self.go(&first, s.wait_all)?;
  203. now = self.after(&first, &now);
  204. for (n, &(i, j, cmds)) in flat.iter().enumerate().skip(here + 1) {
  205. if flat[n - 1].0 != i {
  206. now.decay();
  207. }
  208. let unit = Unit {
  209. submit: i,
  210. cmds,
  211. from: 0,
  212. to: cmds.len(),
  213. delta: j == 0,
  214. };
  215. self.go(&unit, s.wait_all)?;
  216. now = self.after(&unit, &now);
  217. }
  218. self.at = now;
  219. if let Some((db, _, hash, rgb)) = self.picture_now()? {
  220. pictures.push((db, hash, rgb));
  221. }
  222. }
  223. self.put_back(&states)?;
  224. let least = pictures
  225. .iter()
  226. .enumerate()
  227. .flat_map(|(a, x)| pictures[a + 1..].iter().map(|y| gpu::psnr(&x.2, &y.2)))
  228. .fold(f64::INFINITY, f64::min);
  229. let kinds: HashSet<&String> = pictures.iter().map(|p| &p.1).collect();
  230. let db: Vec<String> = pictures.iter().map(|p| format!("{:.1}", p.0)).collect();
  231. say(format!(
  232. "from list {here} (submission {i}, its list {j}), command {from}: {} pictures of {}, the least alike {least:.1} dB; against the recorded: {}",
  233. kinds.len(),
  234. pictures.len(),
  235. db.join(" ")
  236. ));
  237. }
  238. // On to the next cut.
  239. let to = cuts.get(k + 1).copied().unwrap_or(cmds.len());
  240. let unit = Unit {
  241. submit: i,
  242. cmds,
  243. from,
  244. to,
  245. delta: j == 0 && from == 0,
  246. };
  247. self.go(&unit, s.wait_all)?;
  248. self.commit(&unit, &mut states)?;
  249. self.at = states.clone();
  250. if inside && looks {
  251. let last = (from..to).rev().find(|&c| cmds[c].works());
  252. if let Some(c) = last {
  253. say(format!(" command {c}: {}", self.describe(cmds, c)));
  254. }
  255. }
  256. }
  257. if flat.get(here + 1).is_none_or(|n| n.0 != i) {
  258. states.decay();
  259. self.at = states.clone();
  260. }
  261. if s.lists.is_some_and(|(_, b)| here >= b as usize) {
  262. break;
  263. }
  264. }
  265. Ok(())
  266. }
  267. /// The states of textures at the frame's start.
  268. fn start_states(&self) -> States {
  269. let mut states = States::default();
  270. for (id, all) in &self.start {
  271. let Some(o) = self.objects.get(id) else {
  272. continue;
  273. };
  274. let flags = self.frame.resources[o.index].desc.flags;
  275. let decays = flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 != 0;
  276. states.add(*id, o.subs, all[0], decays);
  277. for (i, s) in all.iter().enumerate().filter(|_| all.len() > 1) {
  278. states.change(&states::Change {
  279. res: *id,
  280. sub: i as u32,
  281. after: *s,
  282. promoted: false,
  283. alias: false,
  284. });
  285. }
  286. }
  287. states
  288. }
  289. fn after(&self, unit: &Unit, states: &States) -> States {
  290. let mut after = states.clone();
  291. let mut all = Vec::new();
  292. for c in &unit.cmds[unit.from..unit.to] {
  293. states::changes(c, &mut all);
  294. }
  295. all.iter().for_each(|c| after.change(c));
  296. after
  297. }
  298. /// Says which resources that are not put back before a run are changed
  299. /// by one all the same.
  300. pub fn check_written(&mut self, say: &mut dyn FnMut(String)) -> Result<()> {
  301. // What is put back, is as it was.
  302. {
  303. let ids: Vec<u32> = self.masters.iter().map(|m| m.0).collect();
  304. let reader = self.reader(&ids)?;
  305. let start = self.start_states();
  306. let before = self.hashes_now(&reader, &start)?;
  307. let mut again = self.hashes_now(&reader, &start)?;
  308. say(format!(
  309. "read twice, {} parts differ",
  310. before.iter().zip(&again).filter(|(a, b)| a != b).count()
  311. ));
  312. for i in 0..3 {
  313. self.run(&Options {
  314. loops: 1,
  315. ..Options::default()
  316. })?;
  317. let ran = {
  318. let end: Vec<(u32, Vec<u32>)> =
  319. self.end.iter().map(|(k, v)| (*k, v.clone())).collect();
  320. let mut s = start.clone();
  321. for (id, v) in end {
  322. for (sub, st) in v.iter().enumerate() {
  323. let sub = if v.len() == 1 { ALL } else { sub as u32 };
  324. s.change(&states::Change {
  325. res: id,
  326. sub,
  327. after: *st,
  328. promoted: false,
  329. alias: false,
  330. });
  331. }
  332. }
  333. self.hashes_now(&reader, &s)?
  334. };
  335. self.restore(true)?;
  336. again = self.hashes_now(&reader, &start)?;
  337. let differ: Vec<usize> = (0..before.len())
  338. .filter(|&i| before[i] != again[i])
  339. .collect();
  340. let changed = (0..before.len()).filter(|&i| before[i] != ran[i]).count();
  341. say(format!(
  342. "run {i}: {changed} parts changed by the frame, {} not put back as they were",
  343. differ.len()
  344. ));
  345. for &d in differ.iter().take(20) {
  346. let pieces = before[d]
  347. .iter()
  348. .zip(&again[d])
  349. .filter(|(a, b)| a != b)
  350. .count();
  351. say(format!(
  352. " {} {:?}: {pieces} of {} pieces",
  353. self.called(reader.parts[d].id),
  354. reader.parts[d].sub.map(|s| s.0),
  355. before[d].len()
  356. ));
  357. }
  358. }
  359. }
  360. let put_back: HashSet<u32> = self.masters.iter().map(|m| m.0).collect();
  361. let others: Vec<u32> = self
  362. .objects
  363. .keys()
  364. .copied()
  365. .filter(|id| !put_back.contains(id))
  366. .collect();
  367. let reader = self.reader(&others)?;
  368. self.restore(true)?;
  369. let start = self.start_states();
  370. let before = self.hashes_now(&reader, &start)?;
  371. let o = Options {
  372. loops: 1,
  373. ..Options::default()
  374. };
  375. self.run(&o)?;
  376. self.restore(true)?;
  377. let after = self.hashes_now(&reader, &start)?;
  378. let mut n = 0;
  379. for (i, (a, b)) in before.iter().zip(&after).enumerate() {
  380. let pieces = a.iter().zip(b).filter(|(a, b)| a != b).count();
  381. if pieces > 0 {
  382. n += 1;
  383. let p = &reader.parts[i];
  384. let r = &self.frame.resources[self.objects[&p.id].index];
  385. say(format!(
  386. "not put back, but changed: {} {:?} idle {} late {}: {pieces} pieces of {}",
  387. self.called(p.id),
  388. r.place,
  389. r.idle,
  390. r.late,
  391. a.len()
  392. ));
  393. }
  394. }
  395. say(format!(
  396. "{} parts of {} resources looked at, {n} changed",
  397. reader.parts.len(),
  398. others.len()
  399. ));
  400. Ok(())
  401. }
  402. fn reader(&self, ids: &[u32]) -> Result<Reader> {
  403. const BLOCK: u64 = 512 << 20;
  404. let mut parts = Vec::new();
  405. let mut sizes: Vec<u64> = vec![0];
  406. for id in ids {
  407. let o = &self.objects[id];
  408. let r = &self.frame.resources[o.index];
  409. let back = matches!(&r.place, Place::Committed { props, .. } if gpu::seen(props) == Seen::ReadBack);
  410. if r.desc.samples[0] > 1 || back {
  411. continue;
  412. }
  413. let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0;
  414. let desc = gpu::to_desc(&r.desc);
  415. for sub in 0..o.subs {
  416. let (sub, len) = if is_buffer {
  417. (None, r.desc.width)
  418. } else {
  419. let (f, total) = gpu::footprints(&self.device, &desc, sub, 1);
  420. (Some((sub, f[0])), total)
  421. };
  422. let last = sizes.len() - 1;
  423. let at = sizes[last].next_multiple_of(512);
  424. let (block, at) = if at + len > BLOCK && at > 0 {
  425. sizes.push(0);
  426. (last + 1, 0)
  427. } else {
  428. (last, at)
  429. };
  430. sizes[block] = at + len;
  431. parts.push(Part {
  432. id: *id,
  433. sub,
  434. block,
  435. at,
  436. len,
  437. });
  438. }
  439. }
  440. let mut blocks = Vec::new();
  441. for size in sizes {
  442. let (b, data) = gpu::buffer(
  443. &self.device,
  444. D3D12_HEAP_TYPE_READBACK,
  445. size,
  446. D3D12_RESOURCE_FLAG_NONE,
  447. )?;
  448. blocks.push((b, data as usize));
  449. }
  450. Ok(Reader { blocks, parts })
  451. }
  452. /// Runs the unit once; resources are as at its start.
  453. fn go(&mut self, unit: &Unit, wait: bool) -> Result<()> {
  454. let mut lists = Vec::new();
  455. if unit.delta
  456. && let Some(parts) = self.delta_parts.get(unit.submit).filter(|p| !p.is_empty())
  457. && let Some(from) = &self.deltas
  458. {
  459. let l = self.plain_list()?;
  460. for (d, at) in parts {
  461. if let Some(o) = self.objects.get(&d.res) {
  462. // SAFETY: an open list; live buffers.
  463. unsafe { l.1.CopyBufferRegion(&o.res, d.at, from, *at, d.len) };
  464. }
  465. }
  466. // SAFETY: as above.
  467. unsafe { l.1.Close()? };
  468. lists.push(l);
  469. }
  470. let l = self.plain_list()?;
  471. // What the commands before have set, without what they do.
  472. let before: Vec<Cmd> = unit.cmds[..unit.from]
  473. .iter()
  474. .filter(|c| {
  475. !c.works()
  476. && !matches!(
  477. c,
  478. Cmd::Barriers { .. } | Cmd::BeginQuery { .. } | Cmd::EndQuery { .. }
  479. )
  480. })
  481. .cloned()
  482. .collect();
  483. self.translate(&l.1, &before, unit.submit, None, false);
  484. self.translate(
  485. &l.1,
  486. &unit.cmds[unit.from..unit.to],
  487. unit.submit,
  488. None,
  489. wait,
  490. );
  491. // SAFETY: an open list.
  492. unsafe { l.1.Close()? };
  493. lists.push(l);
  494. for l in &lists {
  495. // SAFETY: a closed list; waited for before it goes.
  496. unsafe { self.worker.queue.ExecuteCommandLists(&[Some(l.1.cast()?)]) };
  497. self.worker.idle().context("the card was lost")?;
  498. }
  499. Ok(())
  500. }
  501. /// Hashes of all parts' pieces, as memory is now (in `states`).
  502. fn hashes_now(&mut self, reader: &Reader, states: &States) -> Result<Vec<Vec<u64>>> {
  503. let objects = &self.objects;
  504. for block in 0..reader.blocks.len() {
  505. let parts: Vec<&Part> = reader.parts.iter().filter(|p| p.block == block).collect();
  506. let (mut before, mut after) = (Vec::new(), Vec::new());
  507. let mut seen = HashSet::new();
  508. for p in parts.iter().filter(|p| p.sub.is_some()) {
  509. if seen.insert(p.id) {
  510. let state = states.get(p.id).unwrap_or(vec![COMMON]);
  511. let to: Vec<u32> = state
  512. .iter()
  513. .map(|&s| if s & COPY_SOURCE != 0 { s } else { COPY_SOURCE })
  514. .collect();
  515. gpu::moves(&objects[&p.id].res, &state, &to, &mut before);
  516. gpu::moves(&objects[&p.id].res, &to, &state, &mut after);
  517. }
  518. }
  519. let to = &reader.blocks[block].0;
  520. self.worker.run(|list| {
  521. // SAFETY: an open list; live resources.
  522. unsafe {
  523. barriers(list, &before);
  524. for p in &parts {
  525. let res = &objects[&p.id].res;
  526. match p.sub {
  527. None => list.CopyBufferRegion(to, p.at, res, 0, p.len),
  528. Some((sub, mut f)) => {
  529. f.Offset = p.at;
  530. list.CopyTextureRegion(
  531. &gpu::placed_location(to, f),
  532. 0,
  533. 0,
  534. 0,
  535. &gpu::sub_location(res, sub),
  536. None,
  537. );
  538. }
  539. }
  540. }
  541. barriers(list, &after);
  542. }
  543. })?;
  544. }
  545. let next = AtomicUsize::new(0);
  546. let out: std::sync::Mutex<Vec<Vec<u64>>> =
  547. std::sync::Mutex::new(vec![Vec::new(); reader.parts.len()]);
  548. std::thread::scope(|scope| {
  549. for _ in 0..16 {
  550. scope.spawn(|| {
  551. while let Some((i, p)) = {
  552. let i = next.fetch_add(1, Ordering::Relaxed);
  553. reader.parts.get(i).map(|p| (i, p))
  554. } {
  555. let all: Vec<u64> = reader
  556. .bytes(p)
  557. .chunks(PIECE)
  558. .map(|c| {
  559. let h = blake3::hash(c);
  560. u64::from_le_bytes(h.as_bytes()[..8].try_into().unwrap_or_default())
  561. })
  562. .collect();
  563. out.lock().unwrap_or_else(|e| e.into_inner())[i] = all;
  564. }
  565. });
  566. }
  567. });
  568. Ok(out.into_inner().unwrap_or_else(|e| e.into_inner()))
  569. }
  570. /// Runs the unit `runs` times (memory is as at its start, and is put
  571. /// back between runs) and compares. Memory is as the last run left it.
  572. fn trials(
  573. &mut self,
  574. reader: &Reader,
  575. unit: &Unit,
  576. states: &States,
  577. runs: u32,
  578. wait: bool,
  579. ) -> Result<Pieces> {
  580. let after = self.after(unit, states);
  581. let mut first: Option<Vec<Vec<u64>>> = None;
  582. let mut pieces = std::collections::BTreeSet::new();
  583. for run in 0..runs {
  584. if run > 0 {
  585. self.put_back_from(&after, states)?;
  586. }
  587. self.go(unit, wait)?;
  588. if runs == 1 {
  589. break;
  590. }
  591. let now = self.hashes_now(reader, &after)?;
  592. match &first {
  593. None => first = Some(now),
  594. Some(first) => {
  595. for (p, (a, b)) in first.iter().zip(&now).enumerate() {
  596. pieces.extend(
  597. a.iter()
  598. .zip(b)
  599. .enumerate()
  600. .filter(|(_, (a, b))| a != b)
  601. .map(|(i, _)| (p, i)),
  602. );
  603. }
  604. }
  605. }
  606. }
  607. self.at = after;
  608. Ok(pieces.into_iter().collect())
  609. }
  610. /// Puts memory back to the start of a unit in `states`, from where the
  611. /// last run left it.
  612. fn put_back(&mut self, states: &States) -> Result<()> {
  613. let from = self.at.clone();
  614. self.put_back_from(&from, states)
  615. }
  616. fn put_back_from(&mut self, from: &States, to: &States) -> Result<()> {
  617. self.copy_masters(from, to, false)?;
  618. self.at = to.clone();
  619. Ok(())
  620. }
  621. /// What memory holds after the last run is the start of what follows.
  622. fn commit(&mut self, unit: &Unit, states: &mut States) -> Result<()> {
  623. *states = self.after(unit, states);
  624. self.copy_masters(&states.clone(), states, true)?;
  625. Ok(())
  626. }
  627. /// Copies the masters over the resources (which are in `from` and go to
  628. /// `to`), or the resources into the masters.
  629. fn copy_masters(&mut self, from: &States, to: &States, save: bool) -> Result<()> {
  630. let known: HashMap<u32, &ID3D12Resource> =
  631. self.masters.iter().map(|(id, m)| (*id, m)).collect();
  632. let (mut before, mut after, mut plain) = (Vec::new(), Vec::new(), Vec::new());
  633. let here = if save { COPY_SOURCE } else { COPY_DEST };
  634. for id in self.start.keys() {
  635. let Some(o) = self.objects.get(id) else {
  636. continue;
  637. };
  638. let (a, b) = (
  639. from.get(*id).unwrap_or(vec![COMMON]),
  640. to.get(*id).unwrap_or(vec![COMMON]),
  641. );
  642. let Some(m) = known.get(id) else {
  643. gpu::moves(&o.res, &a, &b, &mut plain);
  644. continue;
  645. };
  646. gpu::moves(&o.res, &a, &[here], &mut before);
  647. gpu::moves(&o.res, &[here], &b, &mut after);
  648. if save {
  649. before.push(gpu::transition(m, ALL, COPY_SOURCE, COPY_DEST));
  650. after.push(gpu::transition(m, ALL, COPY_DEST, COPY_SOURCE));
  651. }
  652. }
  653. let objects = &self.objects;
  654. self.worker.run(|list| {
  655. // SAFETY: an open list; live resources of one description.
  656. unsafe {
  657. barriers(list, &plain);
  658. barriers(list, &before);
  659. for (id, m) in &known {
  660. if save {
  661. list.CopyResource(*m, &objects[id].res);
  662. } else {
  663. list.CopyResource(&objects[id].res, *m);
  664. }
  665. }
  666. barriers(list, &after);
  667. }
  668. })?;
  669. Ok(())
  670. }
  671. /// The masters hold another state than the frame's start now.
  672. fn restore_all(&mut self) -> Result<()> {
  673. self.note("the player's copies are no longer of the frame's start: load it again".into());
  674. Ok(())
  675. }
  676. /// A command in words: its pipeline, what its list bound for it, and the
  677. /// barriers since the last command that worked.
  678. fn describe(&self, cmds: &[Cmd], at: usize) -> String {
  679. let mut pso = NONE;
  680. let mut binds: BTreeMap<(bool, u32), String> = BTreeMap::new();
  681. let mut since: Vec<String> = Vec::new();
  682. let mut targets = String::new();
  683. for c in &cmds[..at] {
  684. match c {
  685. Cmd::Pipeline { pso: p } => pso = *p,
  686. Cmd::RootSignature { graphics, .. } => binds.retain(|k, _| k.0 != *graphics),
  687. Cmd::RootView {
  688. graphics,
  689. kind,
  690. param,
  691. va,
  692. } => {
  693. let kind = ["", "cbv", "srv", "uav"]
  694. .get(*kind as usize)
  695. .copied()
  696. .unwrap_or("");
  697. let text = match va {
  698. Va::At { res, offset } => {
  699. format!("{kind} {} +{offset:#x}", self.called(*res))
  700. }
  701. _ => format!("{kind} null"),
  702. };
  703. binds.insert((*graphics, *param), text);
  704. }
  705. Cmd::Table {
  706. graphics,
  707. param,
  708. heap,
  709. slot,
  710. } => {
  711. binds.insert(
  712. (*graphics, *param),
  713. format!("table heap {heap} slot {slot}"),
  714. );
  715. }
  716. Cmd::Constants {
  717. graphics,
  718. param,
  719. offset,
  720. values,
  721. } => {
  722. let text = format!("constants +{offset} {values:x?}");
  723. binds
  724. .entry((*graphics, *param))
  725. .and_modify(|t| *t = format!("{t}, {text}"))
  726. .or_insert(text);
  727. }
  728. Cmd::Targets { colors, depth } => {
  729. let all: Vec<String> = colors
  730. .iter()
  731. .chain(depth)
  732. .map(|s| self.called(s.res))
  733. .collect();
  734. targets = all.join(", ");
  735. }
  736. Cmd::Barriers { all } => since.extend(all.iter().map(|b| match b {
  737. Barrier::Transition {
  738. res, before, after, ..
  739. } => format!("{} {before:#x}->{after:#x}", self.called(*res)),
  740. Barrier::Uav { res: 0, .. } => "all uav".into(),
  741. Barrier::Uav { res, .. } => format!("uav {}", self.called(*res)),
  742. Barrier::Alias { .. } => "alias".into(),
  743. })),
  744. _ => {}
  745. }
  746. if c.works() {
  747. since.clear();
  748. }
  749. }
  750. let graphics = !matches!(cmds[at], Cmd::Dispatch { .. });
  751. let binds: Vec<String> = binds
  752. .iter()
  753. .filter(|(k, _)| k.0 == graphics)
  754. .map(|(k, t)| format!("[{}] {t}", k.1))
  755. .collect();
  756. let mut text = format!("{:?}", cmds[at]);
  757. if cmds[at].runs_shaders() {
  758. text += &format!(" of {}", self.pipeline_name(pso));
  759. text += &format!("\n bound: {}", binds.join("; "));
  760. if graphics && !targets.is_empty() {
  761. text += &format!("\n targets: {targets}");
  762. }
  763. }
  764. text + &format!(
  765. "\n barriers since the command before: {}",
  766. since.join("; ")
  767. )
  768. }
  769. /// Says which lists (of the list in `s.lists`: which commands) change
  770. /// words of a buffer, and to what.
  771. pub fn watch(
  772. &mut self,
  773. s: &Search,
  774. parts: &[(u32, u64, u64)],
  775. say: &mut dyn FnMut(String),
  776. ) -> Result<()> {
  777. let mut report = Report::default();
  778. let submits = self.edited(&s.options, &mut report, &[]);
  779. self.restore(true)?;
  780. self.fresh = false;
  781. let words = |p: &mut Player| -> Result<Vec<Vec<u32>>> {
  782. parts
  783. .iter()
  784. .map(|&(id, at, len)| {
  785. let bytes = p.slice(id, at, len)?;
  786. Ok(bytes
  787. .chunks_exact(4)
  788. .map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default()))
  789. .collect())
  790. })
  791. .collect()
  792. };
  793. let mut was = words(self)?;
  794. say(format!("at the start: {was:x?}"));
  795. let mut global = 0u32;
  796. for (i, lists) in submits.iter().enumerate() {
  797. for (j, cmds) in lists.iter().enumerate() {
  798. let here = global;
  799. global += 1;
  800. let inside = s.lists.is_some_and(|(a, b)| (a..=b).contains(&here));
  801. let mut cuts: Vec<usize> = vec![0];
  802. if inside {
  803. cuts.extend((0..cmds.len()).filter(|&c| cmds[c].works()).map(|c| c + 1));
  804. }
  805. if *cuts.last().unwrap_or(&0) != cmds.len() {
  806. cuts.push(cmds.len());
  807. }
  808. for k in 0..cuts.len() - 1 {
  809. let unit = Unit {
  810. submit: i,
  811. cmds,
  812. from: cuts[k],
  813. to: cuts[k + 1],
  814. delta: j == 0 && k == 0,
  815. };
  816. self.go(&unit, s.wait_all)?;
  817. let now = words(self)?;
  818. if now != was {
  819. if inside {
  820. let last = (unit.from..unit.to)
  821. .rev()
  822. .find(|&c| cmds[c].works())
  823. .unwrap_or(unit.to - 1);
  824. say(format!(
  825. "list {here} (submission {i}, its list {j}) command {last}: {}",
  826. self.describe(cmds, last)
  827. ));
  828. } else {
  829. say(format!("list {here} (submission {i}, its list {j})"));
  830. }
  831. for (n, (a, b)) in was.iter().zip(&now).enumerate() {
  832. let changed: Vec<String> = a
  833. .iter()
  834. .zip(b)
  835. .enumerate()
  836. .filter(|(_, (a, b))| a != b)
  837. .take(40)
  838. .map(|(w, (a, b))| format!("+{:#x}: {a:x} -> {b:x}", w * 4))
  839. .collect();
  840. if !changed.is_empty() {
  841. say(format!(" part {n}: {}", changed.join(", ")));
  842. }
  843. }
  844. was = now;
  845. }
  846. }
  847. if s.options.only.is_some_and(|(_, b)| here >= b) {
  848. return Ok(());
  849. }
  850. }
  851. }
  852. Ok(())
  853. }
  854. /// Each draw of one list whose pipeline's name has `text` in it, run
  855. /// alone (with what prepares its arguments) from the memory at the list's
  856. /// start, `runs` times: how many different contents its targets get.
  857. pub fn diverge_draws(
  858. &mut self,
  859. s: &Search,
  860. text: &str,
  861. say: &mut dyn FnMut(String),
  862. ) -> Result<()> {
  863. let mut report = Report::default();
  864. let submits = self.edited(&s.options, &mut report, &[]);
  865. let flat: Vec<(usize, usize, &Vec<Cmd>)> = submits
  866. .iter()
  867. .enumerate()
  868. .flat_map(|(i, lists)| lists.iter().enumerate().map(move |(j, c)| (i, j, c)))
  869. .collect();
  870. let wanted = s.lists.map_or(0, |l| l.0 as usize);
  871. self.restore(true)?;
  872. self.fresh = false;
  873. let mut states = self.start_states();
  874. for (here, &(i, j, cmds)) in flat.iter().enumerate() {
  875. if here < wanted {
  876. let unit = Unit {
  877. submit: i,
  878. cmds,
  879. from: 0,
  880. to: cmds.len(),
  881. delta: j == 0,
  882. };
  883. self.go(&unit, s.wait_all)?;
  884. self.commit(&unit, &mut states)?;
  885. if flat.get(here + 1).is_none_or(|n| n.0 != i) {
  886. states.decay();
  887. }
  888. self.at = states.clone();
  889. continue;
  890. }
  891. let mut last = 0;
  892. let mut pso = NONE;
  893. let mut targets: Vec<u32> = Vec::new();
  894. for (c, cmd) in cmds.iter().enumerate() {
  895. match cmd {
  896. Cmd::Pipeline { pso: p } => pso = *p,
  897. Cmd::Targets { colors, depth } => {
  898. targets = colors
  899. .iter()
  900. .chain(depth)
  901. .map(|s| s.res)
  902. .filter(|r| *r != NONE)
  903. .collect()
  904. }
  905. _ => {}
  906. }
  907. if !matches!(
  908. cmd,
  909. Cmd::Indirect { .. }
  910. | Cmd::Draw { .. }
  911. | Cmd::DrawIndexed { .. }
  912. | Cmd::DispatchMesh { .. }
  913. ) {
  914. continue;
  915. }
  916. let from = std::mem::replace(&mut last, c + 1);
  917. if !self.pipeline_name(pso).contains(text) {
  918. continue;
  919. }
  920. targets.sort_unstable();
  921. targets.dedup();
  922. let reader = self.reader(&targets)?;
  923. let unit = Unit {
  924. submit: i,
  925. cmds,
  926. from,
  927. to: c + 1,
  928. delta: false,
  929. };
  930. // Barriers before it in the list are made up for: textures
  931. // are in the states the list has them in here.
  932. let mut before = states.clone();
  933. let mut all = Vec::new();
  934. cmds[..from]
  935. .iter()
  936. .for_each(|c| states::changes(c, &mut all));
  937. all.iter().for_each(|c| before.change(c));
  938. let after = self.after(&unit, &before);
  939. let mut kinds: HashMap<Vec<Vec<u64>>, u32> = HashMap::new();
  940. for _ in 0..s.runs {
  941. let at = self.at.clone();
  942. self.copy_masters(&at, &before, false)?;
  943. self.at = before.clone();
  944. self.go(&unit, s.wait_all)?;
  945. self.at = after.clone();
  946. *kinds.entry(self.hashes_now(&reader, &after)?).or_default() += 1;
  947. }
  948. let at = self.at.clone();
  949. self.copy_masters(&at, &before, false)?;
  950. self.at = before.clone();
  951. if kinds.len() > 1 || std::env::var_os("VICTORY_REPLAY_PEEK").is_some() {
  952. self.peek(cmds, c, i, say)?;
  953. }
  954. let mut counts: Vec<u32> = kinds.values().copied().collect();
  955. counts.sort_unstable();
  956. say(format!(
  957. "command {c} (from {from}) {:?} of {}: {} outcomes {counts:?}",
  958. cmd,
  959. self.pipeline_name(pso),
  960. counts.len()
  961. ));
  962. }
  963. break;
  964. }
  965. Ok(())
  966. }
  967. /// `len` bytes of a buffer from `at`.
  968. fn slice(&mut self, id: u32, at: u64, len: u64) -> Result<Vec<u8>> {
  969. let Some(o) = self.objects.get(&id) else {
  970. return Ok(Vec::new());
  971. };
  972. let len = len.min(self.frame.resources[o.index].desc.width.saturating_sub(at));
  973. if len == 0 {
  974. return Ok(Vec::new());
  975. }
  976. let res = o.res.clone();
  977. let (back, data) = gpu::buffer(
  978. &self.device,
  979. D3D12_HEAP_TYPE_READBACK,
  980. len,
  981. D3D12_RESOURCE_FLAG_NONE,
  982. )?;
  983. self.worker.run(|list| {
  984. // SAFETY: an open list; live buffers.
  985. unsafe { list.CopyBufferRegion(&back, 0, &res, at, len) };
  986. })?;
  987. // SAFETY: the mapping; the copy into it has run.
  988. Ok(unsafe { std::slice::from_raw_parts(data, len as usize) }.to_vec())
  989. }
  990. /// The words of a buffer view (raw or typed, of words).
  991. fn view_words(&mut self, s: &Slot, first: u64, n: u64) -> Result<Vec<u32>> {
  992. let at = u64::from_le_bytes([
  993. s.desc[16], s.desc[17], s.desc[18], s.desc[19], s.desc[20], s.desc[21], s.desc[22],
  994. s.desc[23],
  995. ]);
  996. let count = u64::from(u32::from_le_bytes([
  997. s.desc[24], s.desc[25], s.desc[26], s.desc[27],
  998. ]));
  999. let n = n.min(count.saturating_sub(first));
  1000. let bytes = self.slice(s.res, (at + first) * 4, n * 4)?;
  1001. Ok(bytes
  1002. .chunks_exact(4)
  1003. .map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default()))
  1004. .collect())
  1005. }
  1006. /// What a mesh draw of the title's (with its usual constants) reads.
  1007. fn peek(
  1008. &mut self,
  1009. cmds: &[Cmd],
  1010. at: usize,
  1011. submit: usize,
  1012. say: &mut dyn FnMut(String),
  1013. ) -> Result<()> {
  1014. let mut v = [0u32; 16];
  1015. let mut heap = NONE;
  1016. for c in &cmds[..at] {
  1017. match c {
  1018. Cmd::Constants {
  1019. graphics: true,
  1020. param: 0,
  1021. offset,
  1022. values,
  1023. } => {
  1024. for (k, x) in values.iter().enumerate() {
  1025. if let Some(at) = v.get_mut(*offset as usize + k) {
  1026. *at = *x;
  1027. }
  1028. }
  1029. }
  1030. Cmd::Heaps { heaps } => heap = heaps.first().copied().unwrap_or(NONE),
  1031. _ => {}
  1032. }
  1033. }
  1034. say(format!(" constants {v:x?}"));
  1035. let slot = |p: &Player, byte: u32| p.slot_at(heap, byte >> 5, submit);
  1036. for (name, byte, n) in [
  1037. ("y+0", v[9], 64u64),
  1038. ("y+32 (matrices)", v[9] + 32, 64),
  1039. ("y+64", v[9] + 64, 32),
  1040. ("y+96 (instances)", v[9] + 96, 64),
  1041. ("y+128 (meshlets)", v[9] + 128, 64),
  1042. ("y+192 (visible)", v[9] + 192, 64),
  1043. ("x+1600", v[8] + 1600, 0),
  1044. ("x+2752", v[8] + 2752, 0),
  1045. ("x+2848", v[8] + 2848, 0),
  1046. ] {
  1047. let s = slot(self, byte);
  1048. let words = if s.kind == slot::SRV {
  1049. self.view_words(&s, 0, n)?
  1050. } else {
  1051. Vec::new()
  1052. };
  1053. say(format!(
  1054. " {name}: slot {} {}: {words:x?}",
  1055. byte >> 5,
  1056. self.slot_text(&s)
  1057. ));
  1058. }
  1059. // The list of visible meshlets, as the mesh shader finds it.
  1060. let lists = slot(self, v[8] + 2752);
  1061. let word = self.view_words(&lists, u64::from((v[13] & 0x07ff_ffff) & 0x07ff_ffff), 4)?;
  1062. let typed = slot(self, v[8] + 1600);
  1063. let index = self.view_words(&typed, 510, 1)?;
  1064. say(format!(
  1065. " list words {word:x?} (count {}, first {}), typed view slot {index:x?}",
  1066. word.first().map_or(0, |w| w >> 15),
  1067. word.first().map_or(0, |w| w & 0x7fff)
  1068. ));
  1069. if let (Some(w), Some(i)) = (word.first(), index.first()) {
  1070. let s = self.slot_at(heap, i & 0x07ff_ffff, submit);
  1071. say(format!(" typed view: {}", self.slot_text(&s)));
  1072. if s.kind == slot::SRV && s.res != NONE {
  1073. let list =
  1074. self.view_words(&s, u64::from(w & 0x7fff) * 16, u64::from(w >> 15) + 16)?;
  1075. say(format!(" visible meshlets: {list:x?}"));
  1076. }
  1077. }
  1078. Ok(())
  1079. }
  1080. /// What the heap slots hold that a draw's constants name, as the title's
  1081. /// shaders find them: byte offsets in the view heap among its first
  1082. /// constants, a descriptor of 32 bytes each.
  1083. pub fn slots(&self, list: u32, command: usize, say: &mut dyn FnMut(String)) -> Result<()> {
  1084. let mut here = 0;
  1085. for (i, s) in self.frame.submits.iter().enumerate() {
  1086. for &l in s.lists.iter().filter(|&&l| l != MISSING) {
  1087. if here == list {
  1088. let cmds = &self.commands[l as usize];
  1089. say(self.describe(cmds, command));
  1090. let mut values = [[0u32; 16]; 3];
  1091. let mut heap = NONE;
  1092. for c in &cmds[..command] {
  1093. match c {
  1094. Cmd::Constants {
  1095. param,
  1096. offset,
  1097. values: v,
  1098. ..
  1099. } => {
  1100. for (k, x) in v.iter().enumerate() {
  1101. if let Some(all) = values.get_mut(*param as usize)
  1102. && let Some(at) = all.get_mut(*offset as usize + k)
  1103. {
  1104. *at = *x;
  1105. }
  1106. }
  1107. }
  1108. Cmd::Heaps { heaps } => heap = heaps.first().copied().unwrap_or(NONE),
  1109. _ => {}
  1110. }
  1111. }
  1112. say(format!("heap {heap}, constants {values:x?}"));
  1113. let mut bases: Vec<u32> = values
  1114. .iter()
  1115. .flatten()
  1116. .map(|v| v >> 5)
  1117. .filter(|v| *v > 64)
  1118. .collect();
  1119. bases.dedup();
  1120. for base in bases {
  1121. for k in 0..12 {
  1122. let s = self.slot_at(heap, base + k, i);
  1123. if s.kind != slot::EMPTY {
  1124. say(format!(" slot {base}+{k}: {}", self.slot_text(&s)));
  1125. } else {
  1126. say(format!(" slot {base}+{k}: never written"));
  1127. }
  1128. }
  1129. }
  1130. }
  1131. here += 1;
  1132. }
  1133. }
  1134. Ok(())
  1135. }
  1136. /// A heap slot as it was for a submission.
  1137. fn slot_at(&self, heap: u32, at: u32, submit: usize) -> Slot {
  1138. let late = self.frame.submits[..=submit].iter().rev().find_map(|s| {
  1139. s.views
  1140. .iter()
  1141. .rev()
  1142. .find(|(h, i, _)| *h == heap && *i == at)
  1143. .map(|v| v.2)
  1144. });
  1145. late.unwrap_or_else(|| {
  1146. let runs = self
  1147. .frame
  1148. .descriptor_heaps
  1149. .iter()
  1150. .find(|h| h.id == heap)
  1151. .map(|h| &h.runs);
  1152. runs.and_then(|runs| {
  1153. let k = runs.partition_point(|r| r.0 <= at).checked_sub(1)?;
  1154. let (first, n, s) = &runs[k];
  1155. (at - first < *n).then_some(*s)
  1156. })
  1157. .unwrap_or(Slot::EMPTY)
  1158. })
  1159. }
  1160. fn slot_text(&self, s: &Slot) -> String {
  1161. let word = |i: usize| {
  1162. u32::from_le_bytes([
  1163. s.desc[i * 4],
  1164. s.desc[i * 4 + 1],
  1165. s.desc[i * 4 + 2],
  1166. s.desc[i * 4 + 3],
  1167. ])
  1168. };
  1169. let kind = ["empty", "cbv", "srv", "uav", "sampler", "rtv", "dsv"]
  1170. .get(s.kind as usize)
  1171. .copied()
  1172. .unwrap_or("?");
  1173. let res = if s.res == NONE {
  1174. "null".into()
  1175. } else {
  1176. self.called(s.res)
  1177. };
  1178. match s.kind {
  1179. slot::CBV => format!("cbv {res} +{:#x} size {:#x}", s.address(), word(2)),
  1180. _ => format!(
  1181. "{kind} format {} dimension {} first {} count {} stride {} flags {}: {res}",
  1182. word(0),
  1183. word(1),
  1184. word(if s.kind == slot::SRV { 4 } else { 2 }),
  1185. word(if s.kind == slot::SRV { 6 } else { 4 }),
  1186. word(if s.kind == slot::SRV { 7 } else { 5 }),
  1187. word(if s.kind == slot::SRV { 8 } else { 8 }),
  1188. ),
  1189. }
  1190. }
  1191. pub(super) fn called(&self, id: u32) -> String {
  1192. let Some(o) = self.objects.get(&id) else {
  1193. return format!("resource {id} (not there)");
  1194. };
  1195. let r = &self.frame.resources[o.index];
  1196. let d = &r.desc;
  1197. if d.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 {
  1198. let kind = match &r.place {
  1199. Place::Committed { props, .. } => format!("{:?}", gpu::seen(props)),
  1200. _ => "placed".into(),
  1201. };
  1202. format!("#{id} '{}' buffer {:#x} {kind}", r.name, d.width)
  1203. } else {
  1204. format!(
  1205. "#{id} '{}' {}x{}x{} m{} f{}",
  1206. r.name, d.width, d.height, d.depth, d.mips, d.format
  1207. )
  1208. }
  1209. }
  1210. /// Runs the unit until two runs differ, and says how.
  1211. fn compare(
  1212. &mut self,
  1213. reader: &Reader,
  1214. unit: &Unit,
  1215. states: &States,
  1216. pieces: &Pieces,
  1217. wait: bool,
  1218. ) -> Result<Vec<String>> {
  1219. let after = self.after(unit, states);
  1220. let parts: std::collections::BTreeSet<usize> = pieces.iter().map(|p| p.0).collect();
  1221. let mut seen: Vec<(Vec<Vec<u64>>, Vec<Vec<u8>>)> = Vec::new();
  1222. for run in 0..8 {
  1223. if run > 0 {
  1224. self.put_back_from(&after, states)?;
  1225. }
  1226. self.go(unit, wait)?;
  1227. let hashes = self.hashes_now(reader, &after)?;
  1228. if seen.iter().any(|(h, _)| *h == hashes) {
  1229. continue;
  1230. }
  1231. let data = parts
  1232. .iter()
  1233. .map(|&p| reader.bytes(&reader.parts[p]).to_vec())
  1234. .collect();
  1235. seen.push((hashes, data));
  1236. if seen.len() == 2 {
  1237. break;
  1238. }
  1239. }
  1240. let mut out = Vec::new();
  1241. // The arguments it ran with.
  1242. if let Some(Cmd::Indirect { args, at, .. }) = unit.cmds.get(unit.to - 1)
  1243. && let Some((p, part)) = reader.parts.iter().enumerate().find(|(_, p)| p.id == *args)
  1244. {
  1245. let bytes = &reader.bytes(part)[*at as usize..];
  1246. let words: Vec<u32> = bytes
  1247. .chunks_exact(4)
  1248. .take(8)
  1249. .map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default()))
  1250. .collect();
  1251. let each: HashSet<&Vec<u64>> = seen.iter().map(|s| &s.0[p]).collect();
  1252. out.push(format!(
  1253. "arguments {words:x?} (the same in all runs: {})",
  1254. each.len() == 1
  1255. ));
  1256. }
  1257. self.at = after;
  1258. let [(_, a), (_, b)] = &seen[..] else {
  1259. out.push("it did not differ when looked at again".into());
  1260. return Ok(out);
  1261. };
  1262. // And without the command.
  1263. let before = Unit {
  1264. to: unit.to - 1,
  1265. ..*unit
  1266. };
  1267. self.put_back(states)?;
  1268. self.go(&before, wait)?;
  1269. self.at = self.after(&before, states);
  1270. let now = self.at.clone();
  1271. self.hashes_now(reader, &now)?;
  1272. let without: Vec<Vec<u8>> = parts
  1273. .iter()
  1274. .map(|&p| reader.bytes(&reader.parts[p]).to_vec())
  1275. .collect();
  1276. let to = self.folder.join("diverge");
  1277. let _ = std::fs::create_dir_all(&to);
  1278. for (k, &p) in parts.iter().enumerate().take(12) {
  1279. let part = &reader.parts[p];
  1280. // Both contents, to look at.
  1281. let sub = part.sub.map_or(0, |s| s.0);
  1282. let _ = std::fs::write(to.join(format!("{}-{sub}-0.bin", part.id)), &without[k]);
  1283. let changed = |v: &[u8]| {
  1284. v.chunks_exact(4)
  1285. .zip(without[k].chunks_exact(4))
  1286. .filter(|(x, y)| x != y)
  1287. .count()
  1288. };
  1289. out.push(format!(
  1290. "it changes {} dwords in one run, {} in another",
  1291. changed(&a[k]),
  1292. changed(&b[k])
  1293. ));
  1294. let _ = std::fs::write(to.join(format!("{}-{sub}-a.bin", part.id)), &a[k]);
  1295. let _ = std::fs::write(to.join(format!("{}-{sub}-b.bin", part.id)), &b[k]);
  1296. let words = |v: &[u8]| -> Vec<u32> {
  1297. v.chunks_exact(4)
  1298. .map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default()))
  1299. .collect()
  1300. };
  1301. let (x, y) = (words(&a[k]), words(&b[k]));
  1302. let differ: Vec<usize> = (0..x.len().min(y.len()))
  1303. .filter(|&i| x[i] != y[i])
  1304. .collect();
  1305. if differ.is_empty() {
  1306. continue;
  1307. }
  1308. // The same words in another order: an order, not a value.
  1309. let sorted = |v: &[u32]| {
  1310. let mut s: Vec<u32> = differ.iter().map(|&i| v[i]).collect();
  1311. s.sort_unstable();
  1312. s
  1313. };
  1314. let order = if sorted(&x) == sorted(&y) {
  1315. " (the same values in another order)"
  1316. } else {
  1317. ""
  1318. };
  1319. let sub = part.sub.map_or(String::new(), |(s, f)| {
  1320. format!(" subresource {s} pitch {}", f.Footprint.RowPitch)
  1321. });
  1322. let sample: Vec<String> = differ
  1323. .iter()
  1324. .take(8)
  1325. .map(|&i| format!("+{:#x}: {:08x} {:08x}", i * 4, x[i], y[i]))
  1326. .collect();
  1327. out.push(format!(
  1328. "writes {}{sub}: {} of {} dwords differ, {:#x}..{:#x}{order}: {}",
  1329. self.called(part.id),
  1330. differ.len(),
  1331. x.len(),
  1332. differ[0] * 4,
  1333. differ[differ.len() - 1] * 4 + 4,
  1334. sample.join(", ")
  1335. ));
  1336. }
  1337. if parts.len() > 12 {
  1338. out.push(format!("and {} more parts", parts.len() - 12));
  1339. }
  1340. Ok(out)
  1341. }
  1342. }
  1343. impl Reader {
  1344. fn bytes(&self, p: &Part) -> &[u8] {
  1345. // SAFETY: a part of a mapped block; copies into it have run.
  1346. unsafe {
  1347. std::slice::from_raw_parts(
  1348. (self.blocks[p.block].1 + p.at as usize) as *const u8,
  1349. p.len as usize,
  1350. )
  1351. }
  1352. }
  1353. }