list.rs 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219
  1. //! Command allocators and command lists.
  2. //!
  3. //! The title's inlined code writes packets into a list only while its put
  4. //! pointer is below a limit, and calls the list's method otherwise. Our
  5. //! lists keep the pointer and every limit at zero, so every command reaches
  6. //! the table as a call.
  7. //!
  8. //! Each list records onto a host command list as its methods are called
  9. //! (decision 0007); draw state lives in `crate::draw`. Methods not
  10. //! written yet log once with their caller, so a run lists what to do next.
  11. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  12. use std::mem::offset_of;
  13. use crate::object::{
  14. self, ALLOCATOR, E_INVALIDARG, HRESULT, Iid, LIST, Object, S_OK, Table, This, guid,
  15. };
  16. use crate::queue::Written;
  17. use crate::resource::PAGEABLE_IIDS;
  18. const ALLOCATOR_IIDS: [Iid; 4] = [
  19. guid(
  20. 0x6102dee4,
  21. 0xaf59,
  22. 0x4b09,
  23. [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24],
  24. ),
  25. PAGEABLE_IIDS[0],
  26. PAGEABLE_IIDS[1],
  27. PAGEABLE_IIDS[2],
  28. ];
  29. /// The list interfaces up to `ID3D12GraphicsCommandList6` (the table has
  30. /// all their slots): those whose ids are the same as on PC, the console's
  31. /// own List5 and List6 (Grand Theft Auto VI asks for List6), then the
  32. /// device child's.
  33. const LIST_IIDS: [Iid; 10] = [
  34. guid(
  35. 0x7116d91c,
  36. 0xe7e4,
  37. 0x47ce,
  38. [0xb8, 0xc6, 0xec, 0x81, 0x68, 0xf4, 0x37, 0xe5],
  39. ),
  40. guid(
  41. 0x5b160d0f,
  42. 0xac1b,
  43. 0x4185,
  44. [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55],
  45. ),
  46. guid(
  47. 0x553103fb,
  48. 0x1fe7,
  49. 0x4557,
  50. [0xbb, 0x38, 0x94, 0x6d, 0x7d, 0x0e, 0x7c, 0xa7],
  51. ),
  52. guid(
  53. 0x38c3e585,
  54. 0xff17,
  55. 0x412c,
  56. [0x91, 0x50, 0x4f, 0xc6, 0xf9, 0xd7, 0x2a, 0x28],
  57. ),
  58. guid(
  59. 0x6fda83a7,
  60. 0xb84c,
  61. 0x4e38,
  62. [0x9a, 0xc8, 0xc7, 0xbd, 0x22, 0x01, 0x6b, 0x3d],
  63. ),
  64. guid(
  65. 0x8754318e,
  66. 0xd3a9,
  67. 0x4541,
  68. [0x98, 0xcf, 0x64, 0x5b, 0x50, 0xdc, 0x48, 0x74],
  69. ),
  70. guid(
  71. 0x55050859,
  72. 0x4024,
  73. 0x474c,
  74. [0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74],
  75. ),
  76. guid(
  77. 0xc3827890,
  78. 0x4024,
  79. 0x474c,
  80. [0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74],
  81. ),
  82. PAGEABLE_IIDS[1],
  83. PAGEABLE_IIDS[2],
  84. ];
  85. #[repr(C)]
  86. struct Allocator {
  87. object: Object,
  88. kind: u32,
  89. }
  90. /// The layout the title's inlined code reads.
  91. #[repr(C)]
  92. struct List {
  93. object: Object,
  94. kind: u32,
  95. /// The put pointer, then the plain, draw, API and unbiased API limits:
  96. /// all zero, so every inline check fails.
  97. put: [u64; 5],
  98. reserved: [u32; 64],
  99. /// State the inline code keeps for building packets; unused by us.
  100. graphics_root_headers: [u32; 128],
  101. compute_root_headers: [u32; 128],
  102. pipeline_shadow: [u32; 8],
  103. /// Newer titles' lists are larger: Grand Theft Auto VI's state flush
  104. /// (title+0x32786) copies a pipeline's 32 bytes to +0x544..+0x564 and
  105. /// tests +0x548, so its layout runs past 0x560. Its size is unknown;
  106. /// this keeps our fields clear of whatever the title writes there.
  107. newer: [u32; 256],
  108. /// Ours, after the console layout: memory handed out by
  109. /// [`allocate_upload`], kept until the list is reset; the host list the
  110. /// calls record into (decision 0007), and the draw state the title set.
  111. uploads: std::sync::Mutex<Vec<Vec<u8>>>,
  112. #[cfg(windows)]
  113. host: Option<crate::host::HostList>,
  114. #[cfg(windows)]
  115. state: std::sync::Mutex<crate::draw::State>,
  116. /// The parts of the recording before `host`, in order, each closed: the
  117. /// list is cut at its waits for memory values ([`cut`]).
  118. #[cfg(windows)]
  119. earlier: Vec<Part>,
  120. /// The waits recorded before the first work of `host`: the queue stands
  121. /// at them before it runs `host`.
  122. #[cfg(windows)]
  123. gate: Vec<ValueWait>,
  124. }
  125. /// One part of a title list cut at its waits: the waits the queue stands
  126. /// at, then the host list that runs once they are met.
  127. #[cfg(windows)]
  128. struct Part {
  129. waits: Vec<ValueWait>,
  130. host: crate::host::HostList,
  131. }
  132. const _: () = assert!(offset_of!(List, put) == 0x18);
  133. const _: () = assert!(offset_of!(List, pipeline_shadow) + 32 == 0x560);
  134. /// Runs `f` with the host list and draw state of a title list, if there
  135. /// is a host GPU.
  136. #[cfg(windows)]
  137. fn with_state(this: This, f: impl FnOnce(&crate::host::HostList, &mut crate::draw::State)) {
  138. let Some(list) = host_list(this) else { return };
  139. #[cfg(feature = "diagnostics")]
  140. let started = std::time::Instant::now();
  141. // SAFETY: the title passes one of our lists.
  142. let state = unsafe { &(*this.cast::<List>()).state };
  143. f(list, &mut state.lock().unwrap_or_else(|e| e.into_inner()));
  144. #[cfg(feature = "diagnostics")]
  145. crate::copystat::recorded(started);
  146. }
  147. /// The submission of `lists` has run: each gives its descriptor tables'
  148. /// slots back ([`crate::draw::State::tables_done`]). A list cut at waits
  149. /// keeps them: its state goes with its last part.
  150. #[cfg(windows)]
  151. pub(crate) fn tables_done(lists: &[This]) {
  152. for &this in lists {
  153. if this.is_null() {
  154. continue;
  155. }
  156. // SAFETY: the title passes our lists.
  157. let list = unsafe { &*this.cast::<List>() };
  158. if list.earlier.is_empty() {
  159. list.state.lock().unwrap_or_else(|e| e.into_inner()).tables_done();
  160. }
  161. }
  162. }
  163. /// The host list behind a title list, if there is a host GPU.
  164. #[cfg(windows)]
  165. pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> {
  166. if this.is_null() {
  167. return None;
  168. }
  169. // SAFETY: the title passes one of our lists.
  170. unsafe { (*this.cast::<List>()).host.as_ref() }
  171. }
  172. /// The host side of a submitted list, taken from it: a queue that waits
  173. /// for a fence runs it later, and the title may reset the list meanwhile.
  174. /// With it go the upload memory and the dynamic descriptor slots its
  175. /// commands name, kept until it has run.
  176. #[cfg(windows)]
  177. pub(crate) struct Detached {
  178. host: crate::host::HostList,
  179. _uploads: Vec<Vec<u8>>,
  180. _state: crate::draw::State,
  181. }
  182. #[cfg(windows)]
  183. impl Detached {
  184. pub(crate) fn host(&self) -> &crate::host::HostList {
  185. &self.host
  186. }
  187. }
  188. /// A host list that has run and waits to be used again, and the bytes of
  189. /// upload memory it keeps.
  190. #[cfg(windows)]
  191. struct Idle(crate::host::HostList, u64);
  192. // SAFETY: D3D12 objects are free-threaded, and an idle list is touched by
  193. // nobody until it is taken out again.
  194. #[cfg(windows)]
  195. unsafe impl Send for Idle {}
  196. /// Host lists that have run, reset and ready to record: the host side of
  197. /// a list a queue held, or of a part of a list cut at a wait, is taken
  198. /// from the title's list at its submission, and the title's list needs
  199. /// another. Each was made new and thrown away after its run: a hundred a
  200. /// frame in gameplay, each two command allocators and two lists, and for
  201. /// four in ten a budget and an argument buffer (run 61: "104 host lists
  202. /// made 21.2 ms" a frame, and the graphics kernel's time to free them).
  203. #[cfg(windows)]
  204. static IDLE: std::sync::Mutex<(Vec<Idle>, u64)> = std::sync::Mutex::new((Vec::new(), 0));
  205. /// The most host lists kept idle, and the most upload memory they may keep
  206. /// between them (a list keeps scratch chunks over a reset only while lists
  207. /// do not share them, `VICTORY_SCRATCH_POOL=0`).
  208. #[cfg(windows)]
  209. const IDLE_MOST: (usize, u64) = (128, 256 << 20);
  210. /// Whether host lists that have run are used again (on by default;
  211. /// `VICTORY_LIST_POOL=0`: each is made new and thrown away, as before).
  212. #[cfg(windows)]
  213. fn pools() -> bool {
  214. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  215. *ON.get_or_init(|| std::env::var_os("VICTORY_LIST_POOL").is_none_or(|v| v != "0"))
  216. }
  217. /// A host list open for recording: one that has run, as a title's list is
  218. /// after its reset, or a new one.
  219. #[cfg(windows)]
  220. fn fresh_list() -> Option<crate::host::HostList> {
  221. let idle = {
  222. let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner());
  223. let taken = idle.0.pop();
  224. if let Some(Idle(_, bytes)) = &taken {
  225. idle.1 -= bytes;
  226. }
  227. taken
  228. };
  229. match idle {
  230. Some(Idle(list, _)) => Some(list),
  231. None => crate::host::host().and_then(|h| h.new_list().ok()),
  232. }
  233. }
  234. /// The host sides of lists whose submission has run (submissions are
  235. /// waited for; `ran` names the ones it ran, by their place in `lists`):
  236. /// what they held is let go, as before, and the host lists are reset and
  237. /// kept for [`fresh_list`].
  238. #[cfg(windows)]
  239. pub(crate) fn recycle(lists: Vec<Detached>, ran: &[usize]) {
  240. if !pools() {
  241. return;
  242. }
  243. for (i, Detached { host, _uploads, _state }) in lists.into_iter().enumerate() {
  244. // The descriptor slots and the upload memory its commands named.
  245. drop(_state);
  246. drop(_uploads);
  247. if !ran.contains(&i) || IDLE.lock().unwrap_or_else(|e| e.into_inner()).0.len() >= IDLE_MOST.0 {
  248. continue;
  249. }
  250. // As the title's reset does: what the list kept for its commands
  251. // goes, its allocators stay.
  252. host.reset();
  253. let bytes = host.scratch_kept();
  254. let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner());
  255. if idle.0.len() < IDLE_MOST.0 && idle.1 + bytes <= IDLE_MOST.1 {
  256. idle.0.push(Idle(host, bytes));
  257. idle.1 += bytes;
  258. }
  259. }
  260. }
  261. /// A wait for a memory value recorded into list `this`, with waits cut
  262. /// into lists (`crate::queue::cuts`). On the console the queue runs the
  263. /// list up to the wait, stands there until the value is in memory, and
  264. /// runs on; the list's bottom-of-pipe writes before the wait are done by
  265. /// then, and other queues may be waiting for exactly those. So the
  266. /// recording is cut here: the host list so far is closed and kept as a
  267. /// part of its own ([`Part`]), the title's calls record into a new host
  268. /// list from here on, and the wait stands before that one. A submission
  269. /// then gives the queue the parts in order ([`detach_parts`]).
  270. ///
  271. /// A wait before any work (the first call after a reset, or a wait right
  272. /// after another) cuts nothing: it joins the waits before the current
  273. /// host list.
  274. /// shortcut: a bottom-of-pipe write is done when its part has run, not at
  275. /// its place in the part: a queue waiting for it starts later than on the
  276. /// console, never earlier, and nothing can wait for itself that way (a
  277. /// part has no wait after its first work).
  278. #[cfg(windows)]
  279. fn cut(this: This, wait: ValueWait) {
  280. if this.is_null() {
  281. return;
  282. }
  283. // SAFETY: the title passes one of our lists; a list is recorded by one
  284. // thread at a time and is not submitted while it records.
  285. let list = unsafe { &mut *this.cast_mut().cast::<List>() };
  286. let Some(current) = list.host.as_ref() else {
  287. return;
  288. };
  289. if current.untouched() {
  290. list.gate.push(wait);
  291. return;
  292. }
  293. let Some(fresh) = fresh_list() else {
  294. // shortcut: without a new host list the wait stands before the part
  295. // it was recorded in.
  296. static ONCE: std::sync::Once = std::sync::Once::new();
  297. ONCE.call_once(|| tracing::warn!("no host list for the part after a wait: the wait moves to the part's start"));
  298. list.gate.push(wait);
  299. return;
  300. };
  301. current.close();
  302. static CUTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  303. if CUTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 {
  304. tracing::info!(parts = list.earlier.len() + 2, "a list is cut at a wait for a memory value");
  305. }
  306. if let Some(done) = list.host.replace(fresh) {
  307. let waits = std::mem::replace(&mut list.gate, vec![wait]);
  308. list.earlier.push(Part { waits, host: done });
  309. }
  310. // What the title set so far, on the new host list.
  311. if let Some(host) = list.host.as_ref() {
  312. list.state
  313. .lock()
  314. .unwrap_or_else(|e| e.into_inner())
  315. .replay(host);
  316. }
  317. }
  318. /// Whether list `this` recorded a wait for a memory value (with waits cut
  319. /// into lists).
  320. #[cfg(windows)]
  321. pub(crate) fn cut_list(this: This) -> bool {
  322. if this.is_null() {
  323. return false;
  324. }
  325. // SAFETY: one of our lists, closed and submitted: nothing records
  326. // into it.
  327. let list = unsafe { &*this.cast::<List>() };
  328. !list.earlier.is_empty() || !list.gate.is_empty()
  329. }
  330. /// What a queue is given for submitted lists that were cut at their waits:
  331. /// the waits it stands at, the host lists it runs once they are met, and
  332. /// the order those run in.
  333. #[cfg(windows)]
  334. pub(crate) type Parts = Vec<(Vec<ValueWait>, Vec<Detached>, Vec<usize>)>;
  335. /// Takes the host sides of the submitted `lists`, part by part ([`cut`]),
  336. /// and leaves each list a new, closed host list for its next reset, as
  337. /// [`detach`] does. What comes back is in the order the queue runs it: a
  338. /// new entry starts at every part that has waits; host lists without
  339. /// waits join the entry before them. The list's upload memory and draw
  340. /// state (its dynamic descriptor slots) go with its last part, which runs
  341. /// last.
  342. /// shortcut: a list the submission names a second time runs again only if
  343. /// it has one part and that part is in the entry being filled; otherwise
  344. /// the second naming is dropped (logged once).
  345. #[cfg(windows)]
  346. pub(crate) fn detach_parts(lists: &[This]) -> Parts {
  347. let mut parts: Parts = vec![(Vec::new(), Vec::new(), Vec::new())];
  348. // The lists taken: where its one host list is (entry, place), or none
  349. // for a list of several parts.
  350. let mut seen: Vec<(This, Option<(usize, usize)>)> = Vec::new();
  351. for &this in lists {
  352. if this.is_null() {
  353. continue;
  354. }
  355. if let Some(&(_, at)) = seen.iter().find(|(t, _)| *t == this) {
  356. match at {
  357. Some((entry, place)) if entry + 1 == parts.len() => parts[entry].2.push(place),
  358. _ => {
  359. static ONCE: std::sync::Once = std::sync::Once::new();
  360. ONCE.call_once(|| {
  361. tracing::warn!("a list named twice by a submission that waits for memory values runs once")
  362. });
  363. }
  364. }
  365. continue;
  366. }
  367. let Some(fresh) = fresh_list() else {
  368. continue;
  369. };
  370. // A new host list is open; the title's next call on its list is a
  371. // reset, which wants it closed.
  372. fresh.close();
  373. // SAFETY: one of our lists, closed and submitted: nothing records
  374. // into it until the title resets it.
  375. let list = unsafe { &mut *this.cast_mut().cast::<List>() };
  376. let Some(host) = list.host.replace(fresh) else {
  377. continue;
  378. };
  379. let earlier = std::mem::take(&mut list.earlier);
  380. let gate = std::mem::take(&mut list.gate);
  381. let uploads = std::mem::take(&mut *list.uploads.lock().unwrap_or_else(|e| e.into_inner()));
  382. let state = std::mem::take(&mut *list.state.lock().unwrap_or_else(|e| e.into_inner()));
  383. let single = earlier.is_empty() && gate.is_empty();
  384. let mut pieces: Vec<(Vec<ValueWait>, Detached)> = earlier
  385. .into_iter()
  386. .map(|part| {
  387. (
  388. part.waits,
  389. Detached {
  390. host: part.host,
  391. _uploads: Vec::new(),
  392. _state: Default::default(),
  393. },
  394. )
  395. })
  396. .collect();
  397. pieces.push((
  398. gate,
  399. Detached {
  400. host,
  401. _uploads: uploads,
  402. _state: state,
  403. },
  404. ));
  405. let mut last = None;
  406. for (waits, detached) in pieces {
  407. if !waits.is_empty() {
  408. parts.push((waits, Vec::new(), Vec::new()));
  409. }
  410. let entry = parts.len() - 1;
  411. let (_, taken, order) = &mut parts[entry];
  412. let place = taken.len();
  413. order.push(place);
  414. taken.push(detached);
  415. last = Some((entry, place));
  416. }
  417. seen.push((this, if single { last } else { None }));
  418. }
  419. // (The first entry is empty if the first list begins with a wait.)
  420. parts.retain(|(_, taken, _)| !taken.is_empty());
  421. parts
  422. }
  423. /// Takes the host sides of submitted lists (each once, however often the
  424. /// submission names it) and leaves each list a new, closed host list for
  425. /// its next reset: what was taken, and which of them run in what order.
  426. #[cfg(windows)]
  427. pub(crate) fn detach(lists: &[This]) -> (Vec<Detached>, Vec<usize>) {
  428. let mut taken: Vec<(This, Detached)> = Vec::new();
  429. let mut order = Vec::new();
  430. for &this in lists {
  431. if this.is_null() {
  432. continue;
  433. }
  434. if let Some(i) = taken.iter().position(|(t, _)| *t == this) {
  435. order.push(i);
  436. continue;
  437. }
  438. let Some(fresh) = fresh_list() else {
  439. continue;
  440. };
  441. // A new host list is open; the title's next call on its list is a
  442. // reset, which wants it closed.
  443. fresh.close();
  444. let list = this.cast_mut().cast::<List>();
  445. // SAFETY: one of our lists, closed and submitted: nothing records
  446. // into it until the title resets it.
  447. let (host, uploads, state) = unsafe {
  448. let Some(host) = (*list).host.replace(fresh) else {
  449. continue;
  450. };
  451. let uploads =
  452. std::mem::take(&mut *(*list).uploads.lock().unwrap_or_else(|e| e.into_inner()));
  453. let state =
  454. std::mem::take(&mut *(*list).state.lock().unwrap_or_else(|e| e.into_inner()));
  455. (host, uploads, state)
  456. };
  457. order.push(taken.len());
  458. taken.push((
  459. this,
  460. Detached {
  461. host,
  462. _uploads: uploads,
  463. _state: state,
  464. },
  465. ));
  466. }
  467. (taken.into_iter().map(|(_, d)| d).collect(), order)
  468. }
  469. pub(crate) extern "system" fn create_allocator(
  470. _: This,
  471. kind: u32,
  472. iid: *const Iid,
  473. out: *mut This,
  474. ) -> HRESULT {
  475. let allocator = Box::new(Allocator {
  476. object: Object::new(&ALLOCATOR_FUNCTIONS),
  477. kind,
  478. });
  479. object::hand_out(ALLOCATOR, allocator, iid, &ALLOCATOR_IIDS, out)
  480. }
  481. /// Lists start open, as in D3D12.
  482. pub(crate) extern "system" fn create_list(
  483. _: This,
  484. _nodes: u32,
  485. kind: u32,
  486. allocator: This,
  487. pipeline: This,
  488. iid: *const Iid,
  489. out: *mut This,
  490. ) -> HRESULT {
  491. new_list(kind, allocator, pipeline, iid, out)
  492. }
  493. /// The console's list creation: type, flags, node mask and barrier batch
  494. /// size in a description.
  495. #[repr(C)]
  496. #[derive(Debug)]
  497. pub(crate) struct ListDesc {
  498. kind: u32,
  499. flags: u32,
  500. nodes: u32,
  501. barrier_batch: u32,
  502. }
  503. pub(crate) extern "system" fn create_list_x(
  504. _: This,
  505. desc: *const ListDesc,
  506. allocator: This,
  507. pipeline: This,
  508. iid: *const Iid,
  509. out: *mut This,
  510. ) -> HRESULT {
  511. // SAFETY: the title passes a description (null is tolerated).
  512. let Some(desc) = (unsafe { desc.as_ref() }) else {
  513. return E_INVALIDARG;
  514. };
  515. tracing::debug!(?desc, "console command list");
  516. new_list(desc.kind, allocator, pipeline, iid, out)
  517. }
  518. /// `pipeline` is the list's initial pipeline (null: none), bound until the
  519. /// title sets another, as after a reset.
  520. fn new_list(
  521. kind: u32,
  522. allocator: This,
  523. pipeline: This,
  524. iid: *const Iid,
  525. out: *mut This,
  526. ) -> HRESULT {
  527. if allocator.is_null() {
  528. return E_INVALIDARG;
  529. }
  530. tracing::debug!(kind, "command list");
  531. let list = Box::new(List {
  532. object: if crate::device::newer() {
  533. Object::new(&NEWER_LIST_FUNCTIONS)
  534. } else {
  535. Object::new(&LIST_FUNCTIONS)
  536. },
  537. kind,
  538. put: [0; 5],
  539. reserved: [0; 64],
  540. graphics_root_headers: [0; 128],
  541. compute_root_headers: [0; 128],
  542. pipeline_shadow: [0; 8],
  543. newer: [0; 256],
  544. uploads: Default::default(),
  545. #[cfg(windows)]
  546. host: crate::host::host().and_then(|h| match h.new_list() {
  547. Ok(list) => Some(list),
  548. Err(e) => {
  549. tracing::warn!(error = %e, "no host command list");
  550. None
  551. }
  552. }),
  553. #[cfg(windows)]
  554. state: {
  555. let mut state = crate::draw::State::default();
  556. state.set_pipeline(pipeline);
  557. std::sync::Mutex::new(state)
  558. },
  559. #[cfg(windows)]
  560. earlier: Vec::new(),
  561. #[cfg(windows)]
  562. gate: Vec::new(),
  563. });
  564. #[cfg(not(windows))]
  565. let _ = pipeline;
  566. object::hand_out(LIST, list, iid, &LIST_IIDS, out)
  567. }
  568. extern "system" fn allocator_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  569. let found = object::is(iid, &ALLOCATOR_IIDS).then_some(this);
  570. object::answer(ALLOCATOR, iid, found, out)
  571. }
  572. extern "system" fn allocator_release(this: This) -> u32 {
  573. object::release_boxed::<Allocator>(this)
  574. }
  575. /// Nothing is recorded, so there is nothing to free.
  576. extern "system" fn allocator_reset(_: This) -> HRESULT {
  577. S_OK
  578. }
  579. extern "system" fn list_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  580. object::answer(LIST, iid, object::is(iid, &LIST_IIDS).then_some(this), out)
  581. }
  582. extern "system" fn list_release(this: This) -> u32 {
  583. object::release_boxed::<List>(this)
  584. }
  585. extern "system" fn list_type(this: This) -> u32 {
  586. // SAFETY: `this` is one of our lists.
  587. unsafe { (*this.cast::<List>()).kind }
  588. }
  589. extern "system" fn close(this: This) -> HRESULT {
  590. #[cfg(windows)]
  591. if let Some(host) = host_list(this) {
  592. host.close();
  593. }
  594. S_OK
  595. }
  596. extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT {
  597. if allocator.is_null() {
  598. return E_INVALIDARG;
  599. }
  600. // A wait recorded and never submitted goes with the recording.
  601. VALUE_WAITS
  602. .lock()
  603. .unwrap_or_else(|e| e.into_inner())
  604. .retain(|&(list, _)| list != this as usize);
  605. // Every submission of the list has run (submissions are waited for).
  606. // SAFETY: the title passes one of our lists.
  607. let uploads = unsafe { &(*this.cast::<List>()).uploads };
  608. uploads.lock().unwrap_or_else(|e| e.into_inner()).clear();
  609. // The parts of a recording that was cut and never submitted go with it
  610. // (a submission takes the parts it runs).
  611. #[cfg(windows)]
  612. {
  613. // SAFETY: the title passes one of our lists, and neither records
  614. // into it nor submits it during its reset.
  615. let list = unsafe { &mut *this.cast_mut().cast::<List>() };
  616. list.earlier.clear();
  617. list.gate.clear();
  618. }
  619. #[cfg(windows)]
  620. with_state(this, |host, state| {
  621. host.reset();
  622. state.reset(pipeline);
  623. });
  624. #[cfg(not(windows))]
  625. let _ = (this, pipeline);
  626. S_OK
  627. }
  628. /// A resource barrier as titles pass it: type, flags, then a resource and
  629. /// either a subresource and two states (transition) or a second resource
  630. /// (aliasing). The same layout as the host's.
  631. #[repr(C)]
  632. #[derive(Clone, Copy)]
  633. pub(crate) struct Barrier {
  634. kind: u32,
  635. flags: u32,
  636. first: This,
  637. second: u64,
  638. last: u64,
  639. }
  640. /// The barrier on host resources, or `None` if it names a resource the host
  641. /// GPU does not have (buffers so far).
  642. #[cfg(windows)]
  643. fn host_barrier(list: &crate::host::HostList, b: &Barrier) -> Option<Barrier> {
  644. use windows::core::Interface;
  645. let host = |r: This| crate::resource::host_resource(r).map(|h| h.as_raw().cast_const().cast());
  646. match b.kind {
  647. 0 => {
  648. // A split barrier's first half: its second half transitions.
  649. const BEGIN_ONLY: u32 = 1;
  650. if b.flags & BEGIN_ONLY != 0 {
  651. return None;
  652. }
  653. // shortcut: whole resources, from the state the list tracked
  654. // (`HostList::transition`); subresources are not told apart.
  655. let wanted = crate::host::texture_state(b.last as u32);
  656. let (texture, before) = list.transition(b.first, wanted)?;
  657. Some(Barrier {
  658. kind: 0,
  659. flags: 0,
  660. first: texture.as_raw().cast_const().cast(),
  661. second: 0xffff_ffff | (u64::from(before) << 32),
  662. last: u64::from(crate::host::legal_state(texture, wanted)),
  663. })
  664. }
  665. 1 => Some(Barrier {
  666. first: if b.first.is_null() {
  667. b.first
  668. } else {
  669. host(b.first)?
  670. },
  671. second: if b.second == 0 {
  672. 0
  673. } else {
  674. host(b.second as This)? as u64
  675. },
  676. ..*b
  677. }),
  678. 2 => Some(Barrier {
  679. first: if b.first.is_null() {
  680. b.first
  681. } else {
  682. // A depth texture's unordered access is its colour twin's
  683. // (the host gives the depth texture none): the barrier is
  684. // on the texture shaders write.
  685. match crate::resource::twin_resource(b.first) {
  686. Some(twin) => twin.as_raw().cast_const().cast(),
  687. None => host(b.first)?,
  688. }
  689. },
  690. ..*b
  691. }),
  692. _ => None,
  693. }
  694. }
  695. /// An unordered access barrier on every resource: earlier shader writes
  696. /// finish before later work reads or writes.
  697. const UAV_BARRIER: Barrier = Barrier {
  698. kind: 2,
  699. flags: 0,
  700. first: std::ptr::null(),
  701. second: 0,
  702. last: 0,
  703. };
  704. /// Returns the console's barrier "actions" (none).
  705. extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> u32 {
  706. #[cfg(windows)]
  707. if let Some(list) = host_list(this)
  708. && !barriers.is_null()
  709. {
  710. // SAFETY: the title passes `count` barriers.
  711. let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) };
  712. let mut host: Vec<Barrier> = barriers
  713. .iter()
  714. .filter_map(|b| host_barrier(list, b))
  715. .collect();
  716. // Buffers have host copies, not resources the barrier can name:
  717. // a barrier on one waits for every shader write before it.
  718. if barriers.iter().any(|b| {
  719. b.kind != 1 && !b.first.is_null() && crate::resource::buffer_bytes(b.first).is_some()
  720. }) {
  721. host.push(UAV_BARRIER);
  722. #[cfg(feature = "diagnostics")]
  723. crate::copystat::add(crate::copystat::C::WaitsForBuffers, 1);
  724. }
  725. if !host.is_empty() {
  726. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
  727. const _: () = assert!(size_of::<Barrier>() == size_of::<D3D12_RESOURCE_BARRIER>());
  728. // SAFETY: the same layout; borrowed resource pointers, never
  729. // released through this slice.
  730. let host = unsafe {
  731. std::slice::from_raw_parts(
  732. host.as_ptr().cast::<D3D12_RESOURCE_BARRIER>(),
  733. host.len(),
  734. )
  735. };
  736. // SAFETY: an open list and live resources.
  737. unsafe { list.list.ResourceBarrier(host) };
  738. }
  739. }
  740. 0
  741. }
  742. /// Moves a title texture's host copy to `state` in the list, if needed.
  743. #[cfg(windows)]
  744. pub(crate) fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) {
  745. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State;
  746. if let Some((texture, before)) = list.transition(resource, state) {
  747. let state = crate::host::legal_state(texture, state);
  748. let barrier = crate::host::transition(texture, State(before as i32), State(state as i32));
  749. // SAFETY: an open list and a live texture.
  750. unsafe { list.list.ResourceBarrier(&[barrier]) };
  751. }
  752. }
  753. #[cfg(windows)]
  754. const COPY_DEST: u32 = 0x400;
  755. #[cfg(windows)]
  756. const COPY_SOURCE: u32 = 0x800;
  757. /// `len` bytes at `offset` of a title buffer, if they are inside it.
  758. #[cfg(windows)]
  759. fn buffer_range(buffer: This, offset: u64, len: u64) -> Option<*mut u8> {
  760. let (data, size) = crate::resource::buffer_bytes(buffer)?;
  761. let end = offset.checked_add(len)?;
  762. if end > size {
  763. tracing::warn!(offset, len, size, "copy outside its buffer");
  764. return None;
  765. }
  766. // SAFETY: inside the buffer, checked above.
  767. Some(unsafe { data.add(offset as usize) })
  768. }
  769. /// Buffer to buffer: both are host memory, copied at submission.
  770. extern "system" fn copy_buffer_region(
  771. this: This,
  772. dst: This,
  773. dst_offset: u64,
  774. src: This,
  775. src_offset: u64,
  776. len: u64,
  777. ) {
  778. #[cfg(windows)]
  779. if let Some(list) = host_list(this)
  780. && let Some(to) = buffer_range(dst, dst_offset, len)
  781. && let Some(from) = buffer_range(src, src_offset, len)
  782. {
  783. list.defer_copy(to, from, len as usize);
  784. }
  785. #[cfg(not(windows))]
  786. let _ = (this, dst, dst_offset, src, src_offset, len);
  787. }
  788. /// Whether one of two resources is a target in a stand-in format and the
  789. /// other is not ([`crate::resource::target_format`]): their texels differ
  790. /// in size, so the host cannot copy between them (logged once).
  791. #[cfg(windows)]
  792. fn unlike(dst: This, src: This) -> bool {
  793. let unlike = crate::resource::stands_in(dst) != crate::resource::stands_in(src);
  794. if unlike {
  795. static ONCE: std::sync::Once = std::sync::Once::new();
  796. ONCE.call_once(|| {
  797. tracing::warn!(?dst, ?src, "copy between a stand-in target and title-format texels skipped")
  798. });
  799. }
  800. unlike
  801. }
  802. extern "system" fn copy_resource(this: This, dst: This, src: This) {
  803. #[cfg(windows)]
  804. {
  805. let Some(list) = host_list(this) else {
  806. return;
  807. };
  808. if let (Some(to), Some(from)) = (
  809. crate::resource::host_resource(dst),
  810. crate::resource::host_resource(src),
  811. ) {
  812. if unlike(dst, src) {
  813. return;
  814. }
  815. // A source the title fills itself is uploaded first (upstream
  816. // PR #671): a copy read whatever the host texture held.
  817. if crate::texture::title_written(from) {
  818. crate::texture::upload(list, src, from);
  819. }
  820. // Depth textures shaders also write: what they wrote, first.
  821. list.twin_use(dst, false, true);
  822. list.twin_use(src, false, false);
  823. ensure_state(list, dst, COPY_DEST);
  824. ensure_state(list, src, COPY_SOURCE);
  825. crate::texture::host_written(dst);
  826. #[cfg(feature = "diagnostics")]
  827. list.note_op(|| format!("copy resource {src:?} to {dst:?}"));
  828. // SAFETY: an open list and live textures.
  829. unsafe { list.list.CopyResource(to, from) };
  830. } else if let (Some((to, a)), Some((from, b))) = (
  831. crate::resource::buffer_bytes(dst),
  832. crate::resource::buffer_bytes(src),
  833. ) {
  834. list.defer_copy(to, from, a.min(b) as usize);
  835. }
  836. }
  837. #[cfg(not(windows))]
  838. let _ = (this, dst, src);
  839. }
  840. extern "system" fn copy_resource_x(this: This, dst: This, src: This, _flags: u32) {
  841. copy_resource(this, dst, src);
  842. }
  843. /// A copy location as titles pass it, laid out as the host's: a resource,
  844. /// then a subresource index (type 0) or a placed footprint (type 1).
  845. #[repr(C)]
  846. #[derive(Clone, Copy)]
  847. pub(crate) struct CopyLocation {
  848. resource: This,
  849. kind: u32,
  850. footprint: crate::resource::PlacedFootprint,
  851. }
  852. /// Texture to texture on the GPU; buffer to texture through an upload
  853. /// buffer filled at submission. Texture to buffer (read back) is not done
  854. /// yet.
  855. extern "system" fn copy_texture_region(
  856. this: This,
  857. dst: *const CopyLocation,
  858. x: u32,
  859. y: u32,
  860. z: u32,
  861. src: *const CopyLocation,
  862. source_box: *const [u32; 6],
  863. ) {
  864. #[cfg(windows)]
  865. {
  866. use windows::Win32::Graphics::Direct3D12::{D3D12_BOX, D3D12_TEXTURE_COPY_LOCATION};
  867. use windows::core::Interface;
  868. const FOOTPRINT: u32 = 1;
  869. // SAFETY: the title passes both locations (null is tolerated).
  870. let (Some(list), Some(&dst), Some(&src)) =
  871. (host_list(this), unsafe { dst.as_ref() }, unsafe {
  872. src.as_ref()
  873. })
  874. else {
  875. return;
  876. };
  877. let Some(to) = crate::resource::host_resource(dst.resource) else {
  878. // Texture to buffer: a read back. The list copies the texels
  879. // into a host buffer of ours; once it has run they go to the
  880. // title's buffer (`HostList::defer_read_back`). Grand Theft
  881. // Auto VI reads two tiny float targets back every frame (5x1
  882. // and 1x1 RGBA32F, 80 and 16 bytes: run 90), and read a buffer
  883. // nobody wrote. `VICTORY_READ_BACK=0` leaves them unmade, as
  884. // before.
  885. static COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  886. let n = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
  887. let made = read_back(list, dst, x, y, z, src, source_box);
  888. if n <= 16 || n % 4096 == 0 || made.is_err() {
  889. static REFUSED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  890. if made.is_err() && REFUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) >= 16 {
  891. return;
  892. }
  893. let source = crate::resource::host_resource(src.resource).map(|r| {
  894. // SAFETY: a live resource.
  895. let d = unsafe { r.GetDesc() };
  896. format!("{}x{} f{} mips {}", d.Width, d.Height, d.Format.0, d.MipLevels)
  897. });
  898. tracing::info!(
  899. copies = n,
  900. made = ?made,
  901. source = ?source,
  902. source_kind = src.kind,
  903. destination_kind = dst.kind,
  904. destination_offset = dst.footprint.offset,
  905. destination_bytes = ?dst.footprint.bytes(),
  906. "a texture to buffer copy (a read back)"
  907. );
  908. }
  909. return;
  910. };
  911. if unlike(dst.resource, src.resource) {
  912. return;
  913. }
  914. let mut from = src;
  915. let _upload; // keeps the source alive while this call records it
  916. #[cfg(feature = "diagnostics")]
  917. let mut read = None;
  918. if src.kind == FOOTPRINT {
  919. let (Some(host), Some(bytes)) = (crate::host::host(), src.footprint.bytes()) else {
  920. return;
  921. };
  922. let Some(data) = buffer_range(src.resource, src.footprint.offset, bytes) else {
  923. return;
  924. };
  925. let Some((buffer, staging)) = list.upload(host, bytes) else {
  926. return;
  927. };
  928. // The list owns this mapped D3D12 upload buffer. Wine can report
  929. // its address as MEM_FREE, so use the host-upload path.
  930. list.defer_fill(staging, data, bytes as usize);
  931. from.resource = buffer.as_raw().cast_const().cast();
  932. from.footprint.offset = 0;
  933. #[cfg(feature = "diagnostics")]
  934. {
  935. // SAFETY: a live buffer.
  936. read = Some((unsafe { buffer.GetGPUVirtualAddress() }, bytes));
  937. }
  938. _upload = buffer;
  939. } else {
  940. let Some(texture) = crate::resource::host_resource(src.resource) else {
  941. return;
  942. };
  943. list.twin_use(src.resource, false, false);
  944. if crate::texture::title_written(texture) {
  945. crate::texture::upload(list, src.resource, texture);
  946. }
  947. ensure_state(list, src.resource, COPY_SOURCE);
  948. from.resource = texture.as_raw().cast_const().cast();
  949. }
  950. // A depth texture shaders also write: what they wrote, first (the
  951. // source above too).
  952. list.twin_use(dst.resource, false, true);
  953. ensure_state(list, dst.resource, COPY_DEST);
  954. crate::texture::host_written(dst.resource);
  955. let mut to_location = dst;
  956. to_location.resource = to.as_raw().cast_const().cast();
  957. let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>());
  958. #[cfg(feature = "diagnostics")]
  959. {
  960. let text = || {
  961. // SAFETY: a live texture; the box is the title's or null.
  962. let (d, b) = unsafe { (to.GetDesc(), host_box.map(|b| *b)) };
  963. format!(
  964. "copy to {:?} {}x{} f{} sub/kind {} at {x},{y},{z} from {:?} kind {} footprint {:?} box {b:?}",
  965. dst.resource,
  966. d.Width,
  967. d.Height,
  968. d.Format.0,
  969. dst.kind,
  970. src.resource,
  971. src.kind,
  972. (src.kind == FOOTPRINT).then_some(src.footprint)
  973. )
  974. };
  975. match read {
  976. Some(range) => list.note_read(text, range),
  977. None => list.note_op(text),
  978. }
  979. }
  980. const _: () =
  981. assert!(size_of::<CopyLocation>() == size_of::<D3D12_TEXTURE_COPY_LOCATION>());
  982. // SAFETY: an open list; both locations in the host's layout, naming
  983. // live resources; the box is the title's (same layout).
  984. unsafe {
  985. list.list.CopyTextureRegion(
  986. (&raw const to_location).cast(),
  987. x,
  988. y,
  989. z,
  990. (&raw const from).cast(),
  991. host_box,
  992. )
  993. };
  994. }
  995. #[cfg(not(windows))]
  996. let _ = (this, dst, x, y, z, src, source_box);
  997. }
  998. /// Records a texture to buffer copy (a read back) of [`copy_texture_region`]
  999. /// into `list`, or says why not.
  1000. #[cfg(windows)]
  1001. #[allow(clippy::too_many_arguments)] // the method's own arguments
  1002. fn read_back(
  1003. list: &crate::host::HostList,
  1004. dst: CopyLocation,
  1005. x: u32,
  1006. y: u32,
  1007. z: u32,
  1008. src: CopyLocation,
  1009. source_box: *const [u32; 6],
  1010. ) -> Result<(), &'static str> {
  1011. use windows::Win32::Graphics::Direct3D12::D3D12_BOX;
  1012. use windows::core::Interface;
  1013. const FOOTPRINT: u32 = 1;
  1014. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1015. if !*ON.get_or_init(|| std::env::var_os("VICTORY_READ_BACK").is_none_or(|v| v != "0")) {
  1016. return Err("switched off");
  1017. }
  1018. if dst.kind != FOOTPRINT || src.kind == FOOTPRINT {
  1019. return Err("not a texture subresource into a placed footprint");
  1020. }
  1021. if (x, y, z) != (0, 0, 0) {
  1022. return Err("a destination corner other than the footprint's");
  1023. }
  1024. let host = crate::host::host().ok_or("no host")?;
  1025. let (footprint, [size, row, rows, pitch]) = dst.footprint.host_rows().ok_or("an unknown format")?;
  1026. // The title's buffer holds every row at its own pitch.
  1027. let bytes = pitch * (rows - 1) + row;
  1028. let data = buffer_range(dst.resource, dst.footprint.offset, bytes).ok_or("a destination outside its buffer")?;
  1029. let texture = crate::resource::host_resource(src.resource).ok_or("no host texture")?;
  1030. let buffer = host.read_back_buffer(size).ok_or("no read-back buffer")?;
  1031. // As a texture source of any copy: what shaders wrote to a depth twin
  1032. // and what the title wrote itself first, then the state.
  1033. list.twin_use(src.resource, false, false);
  1034. if crate::texture::title_written(texture) {
  1035. crate::texture::upload(list, src.resource, texture);
  1036. }
  1037. ensure_state(list, src.resource, COPY_SOURCE);
  1038. let mut from = src;
  1039. from.resource = texture.as_raw().cast_const().cast();
  1040. let mut to = dst;
  1041. to.resource = buffer.as_raw().cast_const().cast();
  1042. to.footprint = footprint;
  1043. let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>());
  1044. #[cfg(feature = "diagnostics")]
  1045. list.note_op(|| {
  1046. format!(
  1047. "read back of {:?} sub {} into buffer {:?}+{:#x}: {rows} rows of {row} bytes",
  1048. src.resource, src.footprint.offset as u32, dst.resource, dst.footprint.offset
  1049. )
  1050. });
  1051. // SAFETY: an open list; both locations in the host's layout (asserted
  1052. // in `copy_texture_region`), naming a live texture and our buffer, which
  1053. // the list keeps until it is reset; the box is the title's.
  1054. unsafe {
  1055. list.list
  1056. .CopyTextureRegion((&raw const to).cast(), 0, 0, 0, (&raw const from).cast(), host_box)
  1057. };
  1058. list.defer_read_back(buffer, data, [row as usize, rows as usize, pitch as usize]);
  1059. Ok(())
  1060. }
  1061. #[allow(clippy::too_many_arguments)] // the method's own arguments
  1062. extern "system" fn copy_texture_region_x(
  1063. this: This,
  1064. dst: *const CopyLocation,
  1065. x: u32,
  1066. y: u32,
  1067. z: u32,
  1068. src: *const CopyLocation,
  1069. source_box: *const [u32; 6],
  1070. _flags: u32,
  1071. ) {
  1072. copy_texture_region(this, dst, x, y, z, src, source_box);
  1073. }
  1074. extern "system" fn resolve(
  1075. this: This,
  1076. dst: This,
  1077. dst_sub: u32,
  1078. src: This,
  1079. src_sub: u32,
  1080. format: u32,
  1081. ) {
  1082. #[cfg(windows)]
  1083. if let Some(list) = host_list(this)
  1084. && let (Some(to), Some(from)) = (
  1085. crate::resource::host_resource(dst),
  1086. crate::resource::host_resource(src),
  1087. )
  1088. {
  1089. use windows::Win32::Foundation::RECT;
  1090. use windows::Win32::Graphics::Direct3D12::{
  1091. D3D12_RESOLVE_MODE_AVERAGE, ID3D12GraphicsCommandList1,
  1092. };
  1093. use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
  1094. use windows::core::Interface;
  1095. const RESOLVE_DEST: u32 = 0x1000;
  1096. const RESOLVE_SOURCE: u32 = 0x2000;
  1097. if unlike(dst, src) {
  1098. return;
  1099. }
  1100. // Depth textures shaders also write: what they wrote, first.
  1101. list.twin_use(dst, false, true);
  1102. list.twin_use(src, false, false);
  1103. ensure_state(list, dst, RESOLVE_DEST);
  1104. ensure_state(list, src, RESOLVE_SOURCE);
  1105. crate::texture::host_written(dst);
  1106. #[cfg(feature = "diagnostics")]
  1107. list.note_op(|| format!("resolve {src:?} to {dst:?} format {format}"));
  1108. // SAFETY: an open list and live textures; the region is inside both.
  1109. unsafe {
  1110. let (a, b) = (to.GetDesc(), from.GetDesc());
  1111. let format = if crate::resource::stands_in(dst) { a.Format } else { DXGI_FORMAT(format as i32) };
  1112. if (a.Width, a.Height) == (b.Width, b.Height) {
  1113. list.list
  1114. .ResolveSubresource(to, dst_sub, from, src_sub, format);
  1115. } else if let Ok(list1) = list.list.cast::<ID3D12GraphicsCommandList1>() {
  1116. // The console clips a larger source to the destination.
  1117. let rect = RECT {
  1118. left: 0,
  1119. top: 0,
  1120. right: a.Width.min(b.Width) as i32,
  1121. bottom: a.Height.min(b.Height) as i32,
  1122. };
  1123. list1.ResolveSubresourceRegion(
  1124. to,
  1125. dst_sub,
  1126. 0,
  1127. 0,
  1128. from,
  1129. src_sub,
  1130. Some(&rect),
  1131. format,
  1132. D3D12_RESOLVE_MODE_AVERAGE,
  1133. );
  1134. }
  1135. }
  1136. }
  1137. #[cfg(not(windows))]
  1138. let _ = (this, dst, dst_sub, src, src_sub, format);
  1139. }
  1140. #[repr(C)]
  1141. pub(crate) struct Rect {
  1142. left: i32,
  1143. top: i32,
  1144. right: i32,
  1145. bottom: i32,
  1146. }
  1147. extern "system" fn clear_rtv(
  1148. this: This,
  1149. handle: u64,
  1150. color: *const [f32; 4],
  1151. count: u32,
  1152. rects: *const Rect,
  1153. ) {
  1154. #[cfg(windows)]
  1155. {
  1156. let (Some(list), Some(record)) = (host_list(this), crate::descriptor::rtv_record(handle))
  1157. else {
  1158. return;
  1159. };
  1160. let (Some(texture), Some(host)) = (
  1161. crate::resource::host_resource(record.resource),
  1162. crate::host::host(),
  1163. ) else {
  1164. return;
  1165. };
  1166. // SAFETY: the title passes four floats (null is tolerated).
  1167. let Some(color) = (unsafe { color.as_ref() }) else {
  1168. return;
  1169. };
  1170. let rects = (count > 0 && !rects.is_null()).then(|| {
  1171. // SAFETY: the title passes `count` rectangles, laid out as the host's.
  1172. unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) }
  1173. });
  1174. const RENDER_TARGET: u32 = 0x4;
  1175. let rtv = host.rtv(Some(texture), record.desc().as_ref());
  1176. // SAFETY: an open list, a fresh view of a live texture.
  1177. unsafe {
  1178. if let Some((_, before)) = list.transition(record.resource, RENDER_TARGET) {
  1179. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State;
  1180. list.list.ResourceBarrier(&[crate::host::transition(
  1181. texture,
  1182. State(before as i32),
  1183. State(RENDER_TARGET as i32),
  1184. )]);
  1185. }
  1186. list.list.ClearRenderTargetView(rtv, color, rects);
  1187. }
  1188. }
  1189. #[cfg(not(windows))]
  1190. let _ = (this, handle, color, count, rects);
  1191. }
  1192. /// `ClearDepthStencilView(handle, flags, depth, stencil, count, rects)`;
  1193. /// flags: 1 depth, 2 stencil.
  1194. extern "system" fn clear_dsv(
  1195. this: This,
  1196. handle: u64,
  1197. flags: u32,
  1198. depth: f32,
  1199. stencil: u8,
  1200. count: u32,
  1201. rects: *const Rect,
  1202. ) {
  1203. #[cfg(windows)]
  1204. {
  1205. use windows::Win32::Graphics::Direct3D12::D3D12_CLEAR_FLAGS;
  1206. let (Some(list), Some(record)) = (host_list(this), crate::descriptor::dsv_record(handle))
  1207. else {
  1208. return;
  1209. };
  1210. let (Some(texture), Some(host)) = (
  1211. crate::resource::host_resource(record.resource),
  1212. crate::host::host(),
  1213. ) else {
  1214. return;
  1215. };
  1216. let rects = (count > 0 && !rects.is_null()).then(|| {
  1217. // SAFETY: the title passes `count` rectangles, laid out as the host's.
  1218. unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) }
  1219. });
  1220. const DEPTH_WRITE: u32 = 0x10;
  1221. // A depth texture shaders also write: what they wrote, first (the
  1222. // clear may be of one slice or of some rectangles).
  1223. list.twin_use(record.resource, false, true);
  1224. ensure_state(list, record.resource, DEPTH_WRITE);
  1225. if crate::resource::depth_and_unordered(record.resource) {
  1226. crate::resource::DEPTH_UNORDERED[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1227. }
  1228. let dsv = host.dsv(texture, record.depth_desc().as_ref());
  1229. // SAFETY: an open list, a fresh view of a live texture.
  1230. unsafe {
  1231. list.list
  1232. .ClearDepthStencilView(dsv, D3D12_CLEAR_FLAGS(flags as i32 & 3), depth, stencil, rects)
  1233. };
  1234. }
  1235. #[cfg(not(windows))]
  1236. let _ = (this, handle, flags, depth, stencil, count, rects);
  1237. }
  1238. /// `CopyMemoryToMemoryX(destination, source, size, flags)`: GPU addresses
  1239. /// are title memory, copied at submission like buffer copies (if mapped).
  1240. extern "system" fn copy_memory(this: This, dst: u64, src: u64, len: u64, _flags: u32) {
  1241. #[cfg(windows)]
  1242. if let Some(list) = host_list(this)
  1243. && dst != 0
  1244. && src != 0
  1245. {
  1246. let len = len as usize;
  1247. list.defer(move || {
  1248. if crate::texture::committed(src as *const u8, len)
  1249. && crate::texture::committed(dst as *const u8, len)
  1250. {
  1251. // SAFETY: both ranges are committed title memory.
  1252. unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len) };
  1253. }
  1254. });
  1255. }
  1256. #[cfg(not(windows))]
  1257. let _ = (this, dst, src, len);
  1258. }
  1259. /// `DriverHintX(feature, value)`: no hints for the host.
  1260. extern "system" fn driver_hint(_: This, _feature: u64, _value: u64) -> u64 {
  1261. 0
  1262. }
  1263. /// `DispatchX(x, y, z, flags)`: a dispatch with console flags, which the
  1264. /// host has no use for (the ray-tracing builder dispatches this way).
  1265. extern "system" fn dispatch_x(this: This, x: u32, y: u32, z: u32, _flags: u32) {
  1266. #[cfg(windows)]
  1267. state::dispatch(this, x, y, z);
  1268. #[cfg(not(windows))]
  1269. {
  1270. let _ = (this, x, y, z);
  1271. count_dispatch();
  1272. }
  1273. }
  1274. /// `BeginQuery`/`EndQuery(heap, type, index)`: queries are answered when
  1275. /// resolved.
  1276. extern "system" fn query_mark(_: This, _heap: This, _kind: u32, _index: u32) {}
  1277. /// `ResolveQueryData(heap, type, first, count, buffer, offset)`: writes
  1278. /// each query's result into the buffer once the list has run. Timestamps
  1279. /// (type 2) are the GPU clock then; occlusion counts (0) say a million
  1280. /// samples passed and binary occlusion (1) visible, so nothing is culled
  1281. /// by a query.
  1282. /// shortcut: no query runs on the host GPU; results are plausible values,
  1283. /// not measured ones (time spans come out as the submission's length).
  1284. extern "system" fn resolve_queries(
  1285. this: This,
  1286. _heap: This,
  1287. kind: u32,
  1288. _first: u32,
  1289. count: u32,
  1290. buffer: This,
  1291. offset: u64,
  1292. ) {
  1293. const OCCLUSION: u32 = 0;
  1294. const BINARY: u32 = 1;
  1295. const TIMESTAMP: u32 = 2;
  1296. const PIPELINE_STATISTICS: u32 = 3;
  1297. let Some((data, size)) = crate::resource::buffer_bytes(buffer) else {
  1298. return;
  1299. };
  1300. let (what, bytes) = match kind {
  1301. OCCLUSION => (Written::Value(1 << 20), 8),
  1302. BINARY => (Written::Value(1), 8),
  1303. TIMESTAMP => (Written::GpuTimestamp, 8),
  1304. PIPELINE_STATISTICS => (Written::Value(0), 88),
  1305. _ => (Written::Value(0), 16),
  1306. };
  1307. if offset + u64::from(count) * bytes > size {
  1308. return;
  1309. }
  1310. for i in 0..u64::from(count) {
  1311. // Wider results are written as 8-byte pieces.
  1312. for piece in 0..bytes / 8 {
  1313. // SAFETY: inside the buffer, checked above.
  1314. let at = unsafe { data.add((offset + i * bytes + piece * 8) as usize) };
  1315. let what = if piece == 0 { what } else { Written::Value(0) };
  1316. defer_write(this, at as u64, what, 8);
  1317. }
  1318. }
  1319. }
  1320. /// IUnknown 3, object 4, device child 1, allocator 2.
  1321. static ALLOCATOR_FUNCTIONS: Table<24> = {
  1322. let mut f = object::d3d12_object(object::missing_table::<ALLOCATOR, 24>());
  1323. f[0] = allocator_query as *const ();
  1324. f[2] = allocator_release as *const ();
  1325. f[7] = object::parent_device as *const (); // 0x38
  1326. f[8] = allocator_reset as *const (); // 0x40
  1327. f[9] = object::ignore as *const (); // 0x48 allocation callback
  1328. Table(f)
  1329. };
  1330. extern "system" fn set_pipeline(this: This, pipeline: This) {
  1331. crate::pipeline::bound(pipeline);
  1332. #[cfg(windows)]
  1333. with_state(this, |_, state| state.set_pipeline(pipeline));
  1334. #[cfg(not(windows))]
  1335. let _ = this;
  1336. }
  1337. /// Pipeline syncs: waits for earlier work and cache flushes, at the top or
  1338. /// bottom of the pipe `(flags, control, address, size)`. Host lists order
  1339. /// their own work and every submission is waited for, so there is nothing
  1340. /// to do.
  1341. extern "system" fn sync(_: This, _flags: u32, _control: u32, _address: u64, _size: u64) {}
  1342. /// Reset with console flags `(allocator, pipeline, flags)`; the flags only
  1343. /// tune the console's command memory.
  1344. extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: u32) -> HRESULT {
  1345. reset(this, allocator, pipeline)
  1346. }
  1347. /// Newer lists' 0x4a0 `(size, alignment) -> pointer`: memory the list
  1348. /// owns until it is reset, which the CPU writes and the GPU reads at the
  1349. /// same address; null on failure. Grand Theft Auto VI's BVH builder puts
  1350. /// its instance descriptions there (and wrote through our old
  1351. /// `E_NOTIMPL` as a pointer).
  1352. extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mut u8 {
  1353. let align = usize::try_from(alignment).unwrap_or(0).max(16);
  1354. let Some(len) = usize::try_from(size).ok().and_then(|s| s.checked_add(align)) else {
  1355. return std::ptr::null_mut();
  1356. };
  1357. if this.is_null() || !align.is_power_of_two() {
  1358. return std::ptr::null_mut();
  1359. }
  1360. let mut block = vec![0u8; len];
  1361. let start = block.as_mut_ptr();
  1362. // SAFETY: the offset is below `align`, so `size` bytes fit after it.
  1363. let at = unsafe { start.add(start.align_offset(align)) };
  1364. // SAFETY: the title passes one of our lists.
  1365. let uploads = unsafe { &(*this.cast::<List>()).uploads };
  1366. // Moving the vector keeps its heap block where it is.
  1367. uploads.lock().unwrap_or_else(|e| e.into_inner()).push(block);
  1368. at
  1369. }
  1370. /// Draw state the host has no use for (root signatures: ours come with
  1371. /// the pipeline; depth order and shading rate hints): any arguments,
  1372. /// nothing returned.
  1373. extern "system" fn ignored_state(_: This) {}
  1374. /// Depth bounds `(min, max)`.
  1375. /// shortcut: not set on the host list (no host pipeline of ours enables
  1376. /// the test, `pipeline::host`); the first values are logged, so a run
  1377. /// shows whether the title uses the test at all.
  1378. extern "system" fn depth_bounds(_: This, min: f32, max: f32) {
  1379. static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1380. if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 8 {
  1381. tracing::info!(min, max, "the title sets depth bounds, which the host is not given");
  1382. }
  1383. }
  1384. /// The title's draw state (decision 0007, step 3), kept for its draws or
  1385. /// set on the host list at once. Without a host GPU these do nothing.
  1386. #[cfg(windows)]
  1387. mod state {
  1388. use super::{This, with_state};
  1389. use crate::draw::{IndexView, VertexView};
  1390. use windows::Win32::Foundation::RECT;
  1391. use windows::Win32::Graphics::Direct3D12::D3D12_VIEWPORT;
  1392. /// `count` items at `items`, or none.
  1393. fn items<'a, T>(items: *const T, count: u32) -> &'a [T] {
  1394. if items.is_null() || count == 0 {
  1395. return &[];
  1396. }
  1397. // SAFETY: the title passes `count` items.
  1398. unsafe { std::slice::from_raw_parts(items, count as usize) }
  1399. }
  1400. pub(super) extern "system" fn topology(this: This, topology: u32) {
  1401. with_state(this, |list, s| s.set_topology(list, topology));
  1402. }
  1403. pub(super) extern "system" fn viewports(
  1404. this: This,
  1405. count: u32,
  1406. viewports: *const D3D12_VIEWPORT,
  1407. ) {
  1408. // (Through the draw state, which keeps them for the host list
  1409. // that continues this one after a cut: `State::replay`.)
  1410. with_state(this, |list, s| s.set_viewports(list, items(viewports, count)));
  1411. }
  1412. pub(super) extern "system" fn scissors(this: This, count: u32, rects: *const RECT) {
  1413. with_state(this, |list, s| s.set_scissors(list, items(rects, count)));
  1414. }
  1415. pub(super) extern "system" fn blend_factor(this: This, factor: *const [f32; 4]) {
  1416. with_state(this, |list, s| {
  1417. // SAFETY: the title passes four floats or null.
  1418. s.set_blend_factor(list, unsafe { factor.as_ref() })
  1419. });
  1420. }
  1421. pub(super) extern "system" fn stencil_ref(this: This, reference: u32) {
  1422. with_state(this, |list, s| s.set_stencil_ref(list, reference));
  1423. }
  1424. pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) {
  1425. with_state(this, |_, s| s.set_heaps(items(heaps, count)));
  1426. }
  1427. pub(super) extern "system" fn compute_table(this: This, slot: u32, handle: u64) {
  1428. with_state(this, |_, s| s.set_table(true, slot, handle));
  1429. }
  1430. pub(super) extern "system" fn graphics_table(this: This, slot: u32, handle: u64) {
  1431. with_state(this, |_, s| s.set_table(false, slot, handle));
  1432. }
  1433. pub(super) extern "system" fn compute_constant(this: This, slot: u32, value: u32, offset: u32) {
  1434. with_state(this, |_, s| s.set_constants(true, slot, &[value], offset));
  1435. }
  1436. pub(super) extern "system" fn graphics_constant(
  1437. this: This,
  1438. slot: u32,
  1439. value: u32,
  1440. offset: u32,
  1441. ) {
  1442. with_state(this, |_, s| s.set_constants(false, slot, &[value], offset));
  1443. }
  1444. pub(super) extern "system" fn compute_constants(
  1445. this: This,
  1446. slot: u32,
  1447. count: u32,
  1448. values: *const u32,
  1449. offset: u32,
  1450. ) {
  1451. with_state(this, |_, s| {
  1452. s.set_constants(true, slot, items(values, count), offset)
  1453. });
  1454. }
  1455. pub(super) extern "system" fn graphics_constants(
  1456. this: This,
  1457. slot: u32,
  1458. count: u32,
  1459. values: *const u32,
  1460. offset: u32,
  1461. ) {
  1462. with_state(this, |_, s| {
  1463. s.set_constants(false, slot, items(values, count), offset)
  1464. });
  1465. }
  1466. /// Root constant buffer, shader resource and unordered access views.
  1467. pub(super) extern "system" fn compute_view(this: This, slot: u32, address: u64) {
  1468. with_state(this, |_, s| s.set_view(true, slot, address));
  1469. }
  1470. pub(super) extern "system" fn graphics_view(this: This, slot: u32, address: u64) {
  1471. with_state(this, |_, s| s.set_view(false, slot, address));
  1472. }
  1473. pub(super) extern "system" fn index_buffer(this: This, view: *const IndexView) {
  1474. // SAFETY: the title passes a view or null.
  1475. with_state(this, |_, s| s.set_index_buffer(unsafe { view.as_ref() }));
  1476. }
  1477. pub(super) extern "system" fn vertex_buffers(
  1478. this: This,
  1479. start: u32,
  1480. count: u32,
  1481. views: *const VertexView,
  1482. ) {
  1483. with_state(this, |_, s| {
  1484. if views.is_null() {
  1485. s.clear_vertex_buffers(start, count);
  1486. } else {
  1487. s.set_vertex_buffers(start, items(views, count));
  1488. }
  1489. });
  1490. }
  1491. /// `(count, handles, one range, depth)`: with one range, the handles
  1492. /// follow the first at the render target view size (128 bytes).
  1493. pub(super) extern "system" fn targets(
  1494. this: This,
  1495. count: u32,
  1496. handles: *const u64,
  1497. one_range: i32,
  1498. depth: *const u64,
  1499. ) {
  1500. let handles: Vec<u64> = if one_range != 0 && !handles.is_null() {
  1501. // SAFETY: the title passes the first handle.
  1502. let first = unsafe { *handles };
  1503. (0..u64::from(count)).map(|i| first + 128 * i).collect()
  1504. } else {
  1505. items(handles, count).to_vec()
  1506. };
  1507. // SAFETY: the title passes a handle or null.
  1508. let depth = unsafe { depth.as_ref() }.copied().unwrap_or(0);
  1509. with_state(this, |list, s| s.set_targets(list, &handles, depth));
  1510. }
  1511. pub(super) extern "system" fn draw(
  1512. this: This,
  1513. vertices: u32,
  1514. instances: u32,
  1515. first: u32,
  1516. first_instance: u32,
  1517. ) {
  1518. super::count_draw();
  1519. with_state(this, |list, s| {
  1520. s.draw(list, vertices, instances, first, first_instance)
  1521. });
  1522. }
  1523. pub(super) extern "system" fn dispatch(this: This, x: u32, y: u32, z: u32) {
  1524. super::count_dispatch();
  1525. with_state(this, |list, s| s.dispatch(list, x, y, z));
  1526. }
  1527. /// `DispatchMesh(x, y, z)` (the PC method of List6); the title's mesh
  1528. /// programs take `x` groups only.
  1529. pub(super) extern "system" fn dispatch_mesh(this: This, x: u32, y: u32, z: u32) {
  1530. super::count_draw();
  1531. if y * z != 1 {
  1532. static ONCE: std::sync::Once = std::sync::Once::new();
  1533. ONCE.call_once(|| tracing::warn!(x, y, z, "a mesh dispatch with y or z groups"));
  1534. }
  1535. with_state(this, |list, s| s.dispatch_mesh(list, x));
  1536. }
  1537. /// `DispatchMeshX(x, flags, indirect arguments, payload)`.
  1538. /// shortcut: dispatches whose group count is in GPU memory (indirect)
  1539. /// are dropped; make them ExecuteIndirect when the title uses them.
  1540. pub(super) extern "system" fn dispatch_mesh_x(
  1541. this: This,
  1542. x: u32,
  1543. _flags: u64,
  1544. indirect: u64,
  1545. _payload: u64,
  1546. ) {
  1547. super::count_draw();
  1548. if indirect != 0 {
  1549. static ONCE: std::sync::Once = std::sync::Once::new();
  1550. ONCE.call_once(|| tracing::warn!("indirect mesh dispatches dropped"));
  1551. return;
  1552. }
  1553. with_state(this, |list, s| s.dispatch_mesh(list, x));
  1554. }
  1555. pub(super) extern "system" fn draw_indexed(
  1556. this: This,
  1557. indices: u32,
  1558. instances: u32,
  1559. first: u32,
  1560. base: i32,
  1561. first_instance: u32,
  1562. ) {
  1563. super::count_draw();
  1564. with_state(this, |list, s| {
  1565. s.draw_indexed(list, indices, instances, first, base, first_instance)
  1566. });
  1567. }
  1568. }
  1569. /// Without a host GPU every draw state call is ignored.
  1570. #[cfg(not(windows))]
  1571. mod state {
  1572. pub(super) use super::dispatch;
  1573. pub(super) use super::draw;
  1574. pub(super) use super::draw as draw_indexed;
  1575. pub(super) use super::draw as dispatch_mesh;
  1576. pub(super) use super::draw as dispatch_mesh_x;
  1577. pub(super) use super::ignored_state as blend_factor;
  1578. pub(super) use super::ignored_state as compute_constant;
  1579. pub(super) use super::ignored_state as compute_constants;
  1580. pub(super) use super::ignored_state as compute_table;
  1581. pub(super) use super::ignored_state as compute_view;
  1582. pub(super) use super::ignored_state as graphics_constant;
  1583. pub(super) use super::ignored_state as graphics_constants;
  1584. pub(super) use super::ignored_state as graphics_table;
  1585. pub(super) use super::ignored_state as graphics_view;
  1586. pub(super) use super::ignored_state as heaps;
  1587. pub(super) use super::ignored_state as index_buffer;
  1588. pub(super) use super::ignored_state as scissors;
  1589. pub(super) use super::ignored_state as stencil_ref;
  1590. pub(super) use super::ignored_state as targets;
  1591. pub(super) use super::ignored_state as topology;
  1592. pub(super) use super::ignored_state as vertex_buffers;
  1593. pub(super) use super::ignored_state as viewports;
  1594. }
  1595. fn count_draw() {
  1596. DRAWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1597. }
  1598. /// Draws of the kinds the host does not run yet (indirect, mesh), and
  1599. /// dispatches, counted per frame for the log.
  1600. /// shortcut: dropped until their shaders translate (decision 0007).
  1601. #[cfg(not(windows))]
  1602. extern "system" fn draw(_: This) {
  1603. count_draw();
  1604. }
  1605. /// `ExecuteIndirect(signature, max count, arguments, offset, count buffer,
  1606. /// offset)`. Grand Theft Auto VI's signatures (title+0x2479466, 2026-11-24)
  1607. /// hold one argument each: draw (stride 16), indexed draw (20), dispatch
  1608. /// (12), mesh dispatch (12), and the console's single-pass dispatch, type
  1609. /// 105 (stride 12: the three group counts; its flags live in the
  1610. /// signature, the title passes none), run as a plain dispatch. They run
  1611. /// through the host's indirect execution (`State::execute_indirect`).
  1612. /// shortcut: signatures that change root arguments are dropped (logged
  1613. /// once per signature).
  1614. extern "system" fn execute_indirect(
  1615. this: This,
  1616. signature: This,
  1617. max: u32,
  1618. arguments: This,
  1619. offset: u64,
  1620. count: This,
  1621. count_offset: u64,
  1622. ) {
  1623. count_draw();
  1624. let Some((stride, args)) = crate::signature::layout(signature) else {
  1625. return;
  1626. };
  1627. let address = crate::resource::buffer_bytes(arguments).map(|(p, _)| p as u64 + offset);
  1628. let counter = crate::resource::buffer_bytes(count).map(|(p, _)| p as u64 + count_offset);
  1629. let mut ran = false;
  1630. #[cfg(windows)]
  1631. if let ([[kind, ..]], Some(address)) = (args, address)
  1632. && (count.is_null() || counter.is_some())
  1633. {
  1634. const DISPATCH: u32 = 2;
  1635. const DISPATCH_SINGLE: u32 = 105;
  1636. let kind = if *kind == DISPATCH_SINGLE { DISPATCH } else { *kind };
  1637. with_state(this, |list, s| {
  1638. ran = s.execute_indirect(list, (kind, stride, max), address, counter);
  1639. });
  1640. } else {
  1641. #[cfg(all(windows, feature = "diagnostics"))]
  1642. crate::pipeline::note_why(format!(
  1643. "indirect signature {args:?}: arguments in a buffer {}, count in a buffer {}",
  1644. address.is_some(),
  1645. count.is_null() || counter.is_some()
  1646. ));
  1647. }
  1648. if ran {
  1649. return;
  1650. }
  1651. INDIRECT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1652. static SEEN: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
  1653. let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
  1654. if !seen.contains(&(signature as usize)) {
  1655. seen.push(signature as usize);
  1656. tracing::info!(
  1657. stride,
  1658. ?args,
  1659. max,
  1660. address = ?address.map(|a| format!("{a:#x}")),
  1661. counted = !count.is_null(),
  1662. "indirect execution dropped (first time for this signature)"
  1663. );
  1664. }
  1665. }
  1666. /// Indirect executions dropped since the last call.
  1667. pub(crate) fn take_indirect() -> u64 {
  1668. INDIRECT.swap(0, std::sync::atomic::Ordering::Relaxed)
  1669. }
  1670. static INDIRECT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1671. fn count_dispatch() {
  1672. DISPATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1673. }
  1674. #[cfg(not(windows))]
  1675. extern "system" fn dispatch(_: This) {
  1676. count_dispatch();
  1677. }
  1678. static DRAWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1679. static DISPATCHES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1680. /// Draws (any kind, mesh and indirect included) and compute dispatches
  1681. /// recorded since the last call.
  1682. pub(crate) fn take_counts() -> (u64, u64) {
  1683. use std::sync::atomic::Ordering::Relaxed;
  1684. (DRAWS.swap(0, Relaxed), DISPATCHES.swap(0, Relaxed))
  1685. }
  1686. /// A GPU wait for a memory value: the list's commands after it run when
  1687. /// the 32 or 64 bits at `address` compare as asked with `reference`.
  1688. #[derive(Clone, Copy, Debug)]
  1689. pub(crate) struct ValueWait {
  1690. address: u64,
  1691. comparison: u32,
  1692. reference: u64,
  1693. wide: bool,
  1694. }
  1695. impl ValueWait {
  1696. /// Whether the memory holds what is waited for now.
  1697. /// shortcut: the comparison codes are taken to be the comparison
  1698. /// functions' (1 never .. 8 always, value against reference); one not
  1699. /// known counts as met, and so does memory that is not mapped.
  1700. ///
  1701. /// The value is read through the kernel, which reports memory that is
  1702. /// not there instead of faulting (as the copies of title memory are
  1703. /// read, `crate::host::copy_mapped`). Asking Windows first whether the
  1704. /// memory is committed (`VirtualQuery`) walks the page tables to the
  1705. /// end of the region: the title keeps these values in a 1.1 GB
  1706. /// allocation (0xd00000000), where one question took about 8 ms, and a
  1707. /// queue asks at every submission and every signal, for each queue that
  1708. /// stands at a wait (Grand Theft Auto VI has five queues). That was
  1709. /// 1.0-2.2 s of every cutscene frame on the thread that submits (runs
  1710. /// 36-49: "between its submissions ... kernel"; 47 of 110 looks at
  1711. /// that thread in run 49 found it in this question).
  1712. /// `VICTORY_WAIT_ASK=1` asks first, as before.
  1713. pub(crate) fn met(&self) -> bool {
  1714. #[cfg(all(windows, feature = "diagnostics"))]
  1715. let started = std::time::Instant::now();
  1716. let met = self.holds();
  1717. #[cfg(all(windows, feature = "diagnostics"))]
  1718. {
  1719. use crate::copystat::{C, add};
  1720. add(C::WaitChecks, 1);
  1721. add(C::WaitCheckNs, started.elapsed().as_nanos() as u64);
  1722. }
  1723. met
  1724. }
  1725. fn holds(&self) -> bool {
  1726. let bytes = if self.wide { 8 } else { 4 };
  1727. if self.address == 0 {
  1728. return true;
  1729. }
  1730. static ASK: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1731. if *ASK.get_or_init(|| std::env::var_os("VICTORY_WAIT_ASK").is_some_and(|v| v == "1"))
  1732. && !crate::texture::committed(self.address as *const u8, bytes)
  1733. {
  1734. return true;
  1735. }
  1736. // The low `bytes` bytes; the rest stays zero.
  1737. let mut raw = [0u8; 8];
  1738. if !crate::host::read_into(self.address as *const u8, &mut raw[..bytes]) {
  1739. return true;
  1740. }
  1741. self.holds_for(u64::from_le_bytes(raw))
  1742. }
  1743. /// Where the value waited for is: address and bytes.
  1744. #[cfg(windows)]
  1745. pub(crate) fn place(&self) -> (usize, usize) {
  1746. (self.address as usize, if self.wide { 8 } else { 4 })
  1747. }
  1748. /// Whether the wait is met with `value` at its address (its low half
  1749. /// for a 32-bit wait).
  1750. pub(crate) fn holds_for(&self, value: u64) -> bool {
  1751. let (value, reference) = if self.wide {
  1752. (value, self.reference)
  1753. } else {
  1754. (value & 0xFFFF_FFFF, self.reference & 0xFFFF_FFFF)
  1755. };
  1756. match self.comparison {
  1757. 1 => false,
  1758. 2 => value < reference,
  1759. 3 => value == reference,
  1760. 4 => value <= reference,
  1761. 5 => value > reference,
  1762. 6 => value != reference,
  1763. 7 => value >= reference,
  1764. _ => true,
  1765. }
  1766. }
  1767. }
  1768. /// The waits lists recorded since their last reset, by list.
  1769. static VALUE_WAITS: std::sync::Mutex<Vec<(usize, ValueWait)>> = std::sync::Mutex::new(Vec::new());
  1770. /// The waits of the submitted `lists` that are not met yet (taken from
  1771. /// them): what the console's GPU would stop at. The title orders work
  1772. /// between its queues this way (Grand Theft Auto VI: the compute queue's
  1773. /// lighting passes wait for a value the graphics queue's depth pass writes
  1774. /// at the bottom of the pipe; run at once, they read a cleared depth
  1775. /// buffer and nothing was lit).
  1776. /// shortcut: a wait holds its whole list (and submission) back, not only
  1777. /// the commands after it.
  1778. pub(crate) fn unmet_waits(lists: &[This]) -> Vec<ValueWait> {
  1779. let mut waits = VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner());
  1780. let mut unmet = Vec::new();
  1781. waits.retain(|&(list, wait)| {
  1782. if !lists.iter().any(|&l| l as usize == list) {
  1783. return true;
  1784. }
  1785. if !wait.met() {
  1786. unmet.push(wait);
  1787. }
  1788. false
  1789. });
  1790. unmet
  1791. }
  1792. /// The waits each of the submitted `lists` recorded (taken from them),
  1793. /// met or not, at the list's first place in the submission.
  1794. #[cfg(windows)]
  1795. pub(crate) fn waits_by_list(lists: &[This]) -> Vec<Vec<ValueWait>> {
  1796. let mut waits = VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner());
  1797. let mut by = vec![Vec::new(); lists.len()];
  1798. waits.retain(|&(list, wait)| {
  1799. match lists.iter().position(|&l| l as usize == list) {
  1800. Some(i) => {
  1801. by[i].push(wait);
  1802. false
  1803. }
  1804. None => true,
  1805. }
  1806. });
  1807. by
  1808. }
  1809. fn wait_for(this: This, address: u64, comparison: u32, reference: u64, wide: bool) {
  1810. let wait = ValueWait {
  1811. address,
  1812. comparison,
  1813. reference,
  1814. wide,
  1815. };
  1816. static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1817. if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 12 {
  1818. tracing::info!(
  1819. address = format_args!("{address:#x}"),
  1820. comparison,
  1821. reference,
  1822. wide,
  1823. met = wait.met(),
  1824. "a list waits for a memory value"
  1825. );
  1826. }
  1827. #[cfg(all(windows, feature = "diagnostics"))]
  1828. if let Some(host) = host_list(this) {
  1829. crate::capture::op(std::ptr::from_ref(host) as usize, || {
  1830. format!(
  1831. "WAIT VALUE at {address:#x} comparison {comparison} reference {reference:#x} wide {wide} met {}",
  1832. wait.met()
  1833. )
  1834. });
  1835. }
  1836. // The list is cut here, and the wait stands before what follows.
  1837. #[cfg(windows)]
  1838. if crate::queue::cuts() {
  1839. cut(this, wait);
  1840. return;
  1841. }
  1842. VALUE_WAITS
  1843. .lock()
  1844. .unwrap_or_else(|e| e.into_inner())
  1845. .push((this as usize, wait));
  1846. }
  1847. extern "system" fn wait_value(this: This, address: u64, comparison: u32, reference: u64) {
  1848. wait_for(this, address, comparison, reference, false);
  1849. }
  1850. extern "system" fn wait_value64(this: This, address: u64, comparison: u32, reference: u64) {
  1851. wait_for(this, address, comparison, reference, true);
  1852. }
  1853. /// The enhanced barriers `(group count, groups)`: buffer, texture and
  1854. /// global barriers with layouts instead of states. Every host use of a
  1855. /// title texture (clears, copies) moves its host copy to the state it needs
  1856. /// first, so only their ordering matters: one barrier on every shader
  1857. /// write (the title's buffer barriers order compute passes).
  1858. extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) {
  1859. // Diagnostics: counted, and left out under `VICTORY_BARRIER_TEST=groups`.
  1860. #[cfg(all(windows, feature = "diagnostics"))]
  1861. if count > 0 {
  1862. crate::copystat::add(crate::copystat::C::WaitsForGroups, 1);
  1863. if crate::copystat::barrier_test() & 1 != 0 {
  1864. return;
  1865. }
  1866. }
  1867. #[cfg(windows)]
  1868. if count > 0
  1869. && let Some(list) = host_list(this)
  1870. {
  1871. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
  1872. // SAFETY: the same layout; no resource named.
  1873. let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) };
  1874. // SAFETY: an open list.
  1875. unsafe { list.list.ResourceBarrier(&[barrier]) };
  1876. }
  1877. #[cfg(not(windows))]
  1878. let _ = (this, count);
  1879. }
  1880. /// The bottom-of-pipe value writes `(address, value, flush, flags)`, 32 and
  1881. /// 64 bits: done when the list has run, as the GPU would. Flag 1 writes the
  1882. /// GPU timestamp instead (64-bit form), flag 2 the system timestamp.
  1883. extern "system" fn write32(this: This, address: u64, value: u32, _flush: u32, _flags: u32) {
  1884. defer_write(this, address, Written::Value(u64::from(value)), 4);
  1885. value_written(this, address, u64::from(value));
  1886. }
  1887. extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, flags: u32) {
  1888. const GPU_TIMESTAMP: u32 = 1;
  1889. const SYSTEM_TIMESTAMP: u32 = 2;
  1890. let what = match flags {
  1891. GPU_TIMESTAMP => Written::GpuTimestamp,
  1892. SYSTEM_TIMESTAMP => Written::SystemTimestamp,
  1893. _ => Written::Value(value),
  1894. };
  1895. defer_write(this, address, what, 8);
  1896. if let Written::Value(value) = what {
  1897. value_written(this, address, value);
  1898. }
  1899. }
  1900. /// The title wrote a value at the bottom of the pipe (not a timestamp, not
  1901. /// a query result): listed (diagnostics), and with `VICTORY_CUT_WRITES=1`
  1902. /// the host list is cut right behind it, so that the value is stored when
  1903. /// the card has run the list up to there, as on the console, and not when
  1904. /// the whole list has run. Lists of other queues wait for these values
  1905. /// (Grand Theft Auto VI: the compute list that builds the depth pyramid
  1906. /// waits for one, and the meshlet culling of the same frame reads that
  1907. /// pyramid). Off by default: every such write then ends a host list, and
  1908. /// each part is a submission of its own.
  1909. fn value_written(this: This, address: u64, value: u64) {
  1910. #[cfg(windows)]
  1911. {
  1912. if address == 0 || this.is_null() {
  1913. return;
  1914. }
  1915. #[cfg(not(feature = "diagnostics"))]
  1916. let _ = value;
  1917. #[cfg(feature = "diagnostics")]
  1918. if let Some(host) = host_list(this) {
  1919. crate::capture::op(std::ptr::from_ref(host) as usize, || {
  1920. format!("WRITE VALUE at {address:#x} value {value:#x}")
  1921. });
  1922. }
  1923. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1924. if !*ON.get_or_init(|| std::env::var_os("VICTORY_CUT_WRITES").is_some_and(|v| v == "1"))
  1925. || !crate::queue::cuts()
  1926. {
  1927. return;
  1928. }
  1929. // SAFETY: the title passes one of our lists; a list is recorded by
  1930. // one thread at a time and is not submitted while it records.
  1931. let list = unsafe { &mut *this.cast_mut().cast::<List>() };
  1932. let Some(current) = list.host.as_ref() else {
  1933. return;
  1934. };
  1935. let Some(fresh) = fresh_list() else {
  1936. return;
  1937. };
  1938. current.close();
  1939. if let Some(done) = list.host.replace(fresh) {
  1940. // The part so far keeps its waits; nothing stands before the
  1941. // next one but this part itself.
  1942. let waits = std::mem::take(&mut list.gate);
  1943. list.earlier.push(Part { waits, host: done });
  1944. }
  1945. if let Some(host) = list.host.as_ref() {
  1946. list.state
  1947. .lock()
  1948. .unwrap_or_else(|e| e.into_inner())
  1949. .replay(host);
  1950. }
  1951. }
  1952. #[cfg(not(windows))]
  1953. let _ = (this, address, value);
  1954. }
  1955. fn defer_write(this: This, address: u64, what: Written, bytes: usize) {
  1956. if address == 0 {
  1957. return;
  1958. }
  1959. #[cfg(windows)]
  1960. if let Some(list) = host_list(this) {
  1961. list.defer_write(address as *mut u8, what, bytes);
  1962. return;
  1963. }
  1964. let _ = this;
  1965. // Without a host GPU nothing runs later: write now.
  1966. what.write(address as *mut u8, bytes);
  1967. }
  1968. /// The list methods by their slot in older titles' lists (the 2020-era
  1969. /// layout): IUnknown 3, object 4, device child 1, list 1, graphics list 96
  1970. /// (59 as on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3
  1971. /// + 13): 140 slots.
  1972. const METHODS: [(usize, *const ()); 52] = [
  1973. (0, list_query as *const ()),
  1974. (2, list_release as *const ()),
  1975. (7, object::parent_device as *const ()), // 0x38
  1976. (8, list_type as *const ()), // 0x40
  1977. (9, close as *const ()), // 0x48
  1978. (10, reset as *const ()), // 0x50
  1979. (12, state::draw as *const ()), // 0x60 instanced
  1980. (13, state::draw_indexed as *const ()), // 0x68 indexed
  1981. (14, state::dispatch as *const ()), // 0x70
  1982. (15, copy_buffer_region as *const ()), // 0x78
  1983. (16, copy_texture_region as *const ()), // 0x80
  1984. (17, copy_resource as *const ()), // 0x88
  1985. (19, resolve as *const ()), // 0x98
  1986. (20, state::topology as *const ()), // 0xa0
  1987. (21, state::viewports as *const ()), // 0xa8
  1988. (22, state::scissors as *const ()), // 0xb0
  1989. (23, state::blend_factor as *const ()), // 0xb8
  1990. (24, state::stencil_ref as *const ()), // 0xc0
  1991. (25, set_pipeline as *const ()), // 0xc8
  1992. (26, barrier as *const ()), // 0xd0
  1993. (32, state::heaps as *const ()), // 0x100
  1994. (33, ignored_state as *const ()), // 0x108 compute root signature
  1995. (34, ignored_state as *const ()), // 0x110 graphics root signature
  1996. (35, state::compute_table as *const ()), // 0x118
  1997. (36, state::graphics_table as *const ()), // 0x120
  1998. (37, state::compute_constant as *const ()), // 0x128
  1999. (38, state::graphics_constant as *const ()), // 0x130
  2000. (39, state::compute_constants as *const ()), // 0x138
  2001. (40, state::graphics_constants as *const ()), // 0x140
  2002. (41, state::compute_view as *const ()), // 0x148 CBV
  2003. (42, state::graphics_view as *const ()), // 0x150 CBV
  2004. (43, state::compute_view as *const ()), // 0x158 SRV
  2005. (44, state::graphics_view as *const ()), // 0x160 SRV
  2006. (45, state::compute_view as *const ()), // 0x168 UAV
  2007. (46, state::graphics_view as *const ()), // 0x170 UAV
  2008. (47, state::index_buffer as *const ()), // 0x178
  2009. (48, state::vertex_buffers as *const ()), // 0x180
  2010. (50, state::targets as *const ()), // 0x190
  2011. (51, clear_dsv as *const ()), // 0x198
  2012. (52, clear_rtv as *const ()), // 0x1a0
  2013. (59, execute_indirect as *const ()), // 0x1d8 indirect
  2014. (60, copy_memory as *const ()), // 0x1e0
  2015. (68, depth_bounds as *const ()), // 0x220 depth bounds
  2016. (69, write32 as *const ()), // 0x228
  2017. (70, write64 as *const ()), // 0x230
  2018. (71, wait_value as *const ()), // 0x238, 32 bits
  2019. (72, wait_value64 as *const ()), // 0x240, 64 bits
  2020. (73, ignored_state as *const ()), // 0x248 pixel shader depth order
  2021. (83, copy_texture_region_x as *const ()), // 0x298
  2022. (84, copy_resource_x as *const ()), // 0x2a0
  2023. (124, ignored_state as *const ()), // 0x3e0 shading rate
  2024. (127, state::dispatch_mesh as *const ()), // 0x3f8 mesh dispatch
  2025. ];
  2026. /// The rest of [`METHODS`], kept apart only to stay readable.
  2027. const MORE_METHODS: [(usize, *const ()); 9] = [
  2028. (28, query_mark as *const ()), // 0xe0 BeginQuery
  2029. (29, query_mark as *const ()), // 0xe8 EndQuery
  2030. (30, resolve_queries as *const ()), // 0xf0
  2031. (78, dispatch_x as *const ()), // 0x270
  2032. (98, state::dispatch_mesh_x as *const ()), // 0x310
  2033. (99, driver_hint as *const ()), // 0x318
  2034. // Pipeline syncs at the top and bottom of the pipe, 0x408 and 0x410.
  2035. (129, sync as *const ()),
  2036. (130, sync as *const ()),
  2037. (137, reset_x as *const ()), // 0x448
  2038. ];
  2039. /// Newer titles' lists have two more methods in the console part of the
  2040. /// base list, after the clears (0x198/0x1a0 as before) and before
  2041. /// ExecuteIndirect, which moved from 0x1d8 to 0x1e8: every slot from 0x1d8
  2042. /// on is two later (taken here as starting exactly at 0x1d8). Inferred from
  2043. /// Grand Theft Auto VI's call shapes: ExecuteIndirect 0x1e8, bottom-of-pipe
  2044. /// writes 0x238/0x240, waits 0x248/0x250, depth bounds 0x230, shading rate
  2045. /// 0x3f0/0x400, syncs 0x418/0x420, ResetX 0x458 (asserts on failure).
  2046. const fn newer_slot(slot: usize) -> usize {
  2047. if slot >= 59 { slot + 2 } else { slot }
  2048. }
  2049. /// Methods only newer titles' lists have. 0x490: the enhanced barrier
  2050. /// `(group count, groups)`, with 16-byte groups `(type, count, barriers)`
  2051. /// and 40-byte buffer barriers (title+0x95e0 builds them). 0x470 `(u64)`,
  2052. /// called from Grand Theft Auto VI's state flush with its result unused.
  2053. /// shortcut: 0x470's purpose is unknown; ignored until a title shows it
  2054. /// matters.
  2055. const NEWER_METHODS: [(usize, *const ()); 3] = [
  2056. (142, ignored_state as *const ()),
  2057. (146, barrier_groups as *const ()),
  2058. (148, allocate_upload as *const ()),
  2059. ];
  2060. const fn list_table(newer: bool) -> [*const (); 160] {
  2061. let mut f = object::d3d12_object(object::missing_table::<LIST, 160>());
  2062. let mut i = 0;
  2063. while i < METHODS.len() + MORE_METHODS.len() {
  2064. let (slot, method) = if i < METHODS.len() {
  2065. METHODS[i]
  2066. } else {
  2067. MORE_METHODS[i - METHODS.len()]
  2068. };
  2069. f[if newer { newer_slot(slot) } else { slot }] = method;
  2070. i += 1;
  2071. }
  2072. let mut i = 0;
  2073. while newer && i < NEWER_METHODS.len() {
  2074. f[NEWER_METHODS[i].0] = NEWER_METHODS[i].1;
  2075. i += 1;
  2076. }
  2077. f
  2078. }
  2079. /// Every slot up to the limit exists and logs, for the methods newer
  2080. /// titles add.
  2081. static LIST_FUNCTIONS: Table<160> = Table(list_table(false));
  2082. static NEWER_LIST_FUNCTIONS: Table<160> = Table(list_table(true));
  2083. #[cfg(test)]
  2084. mod tests {
  2085. use super::*;
  2086. use crate::object::slot;
  2087. #[test]
  2088. fn every_inline_command_falls_back_to_the_table() {
  2089. let null = std::ptr::null();
  2090. let mut allocator = null;
  2091. assert_eq!(
  2092. create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator),
  2093. S_OK
  2094. );
  2095. let mut list = null;
  2096. let hr = create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list);
  2097. assert_eq!(hr, S_OK);
  2098. // What the title's inline draw checks: put < draw limit.
  2099. // SAFETY: the list is 0x560 bytes.
  2100. let (put, draw_limit, api_limit) = unsafe {
  2101. let at = |o: usize| list.cast::<u8>().add(o).cast::<u64>().read();
  2102. (at(0x18), at(0x28), at(0x30))
  2103. };
  2104. assert!(put >= draw_limit && put >= api_limit);
  2105. // The console's ID3D12GraphicsCommandList6, as Grand Theft Auto VI asks.
  2106. let mut same = null;
  2107. assert_eq!(list_query(list, &LIST_IIDS[7], &mut same), S_OK);
  2108. assert_eq!(same, list);
  2109. assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x10)(list), 1);
  2110. assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x40)(list), 0);
  2111. assert_eq!(
  2112. slot::<extern "system" fn(This) -> HRESULT>(list, 0x48)(list),
  2113. S_OK
  2114. );
  2115. // List-owned upload memory: aligned, writable, gone at reset.
  2116. let p = allocate_upload(list, 40, 0x100);
  2117. assert!(!p.is_null() && (p as usize).is_multiple_of(0x100));
  2118. // SAFETY: 40 bytes were handed out.
  2119. unsafe { p.write_bytes(0xab, 40) };
  2120. assert!(allocate_upload(list, 8, 0x30).is_null(), "not a power of two");
  2121. assert_eq!(reset(list, allocator, null), S_OK);
  2122. // SAFETY: the list is ours.
  2123. assert!(unsafe { &(*list.cast::<List>()).uploads }.lock().unwrap().is_empty());
  2124. let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o);
  2125. assert_eq!(release(list), 0);
  2126. assert_eq!(release(allocator), 0);
  2127. }
  2128. }