list.rs 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333
  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 (the title 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: the title'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. crate::pipeline::bound(pipeline);
  625. #[cfg(not(windows))]
  626. let _ = this;
  627. S_OK
  628. }
  629. /// A resource barrier as titles pass it: type, flags, then a resource and
  630. /// either a subresource and two states (transition) or a second resource
  631. /// (aliasing). The same layout as the host's.
  632. #[repr(C)]
  633. #[derive(Clone, Copy)]
  634. pub(crate) struct Barrier {
  635. kind: u32,
  636. flags: u32,
  637. first: This,
  638. second: u64,
  639. last: u64,
  640. }
  641. /// The barrier on host resources, or `None` if it names a resource the host
  642. /// GPU does not have (buffers so far).
  643. #[cfg(windows)]
  644. fn host_barrier(list: &crate::host::HostList, b: &Barrier) -> Option<Barrier> {
  645. use windows::core::Interface;
  646. let host = |r: This| crate::resource::host_resource(r).map(|h| h.as_raw().cast_const().cast());
  647. match b.kind {
  648. 0 => {
  649. // A split barrier's first half: its second half transitions.
  650. const BEGIN_ONLY: u32 = 1;
  651. if b.flags & BEGIN_ONLY != 0 {
  652. return None;
  653. }
  654. // shortcut: whole resources, from the state the list tracked
  655. // (`HostList::transition`); subresources are not told apart.
  656. let wanted = crate::host::texture_state(b.last as u32);
  657. let (texture, before) = list.transition(b.first, wanted)?;
  658. Some(Barrier {
  659. kind: 0,
  660. flags: 0,
  661. first: texture.as_raw().cast_const().cast(),
  662. second: 0xffff_ffff | (u64::from(before) << 32),
  663. last: u64::from(crate::host::legal_state(texture, wanted)),
  664. })
  665. }
  666. 1 => Some(Barrier {
  667. first: if b.first.is_null() {
  668. b.first
  669. } else {
  670. host(b.first)?
  671. },
  672. second: if b.second == 0 {
  673. 0
  674. } else {
  675. host(b.second as This)? as u64
  676. },
  677. ..*b
  678. }),
  679. 2 => Some(Barrier {
  680. first: if b.first.is_null() {
  681. b.first
  682. } else {
  683. // A depth texture's unordered access is its colour twin's
  684. // (the host gives the depth texture none): the barrier is
  685. // on the texture shaders write.
  686. match crate::resource::twin_resource(b.first) {
  687. Some(twin) => twin.as_raw().cast_const().cast(),
  688. None => host(b.first)?,
  689. }
  690. },
  691. ..*b
  692. }),
  693. _ => None,
  694. }
  695. }
  696. /// An unordered access barrier on every resource: earlier shader writes
  697. /// finish before later work reads or writes.
  698. const UAV_BARRIER: Barrier = Barrier {
  699. kind: 2,
  700. flags: 0,
  701. first: std::ptr::null(),
  702. second: 0,
  703. last: 0,
  704. };
  705. /// Returns the console's barrier "actions" (none).
  706. extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> u32 {
  707. #[cfg(windows)]
  708. if let Some(list) = host_list(this)
  709. && !barriers.is_null()
  710. {
  711. if count > 0 {
  712. with_state(this, |_, state| state.synced());
  713. }
  714. // SAFETY: the title passes `count` barriers.
  715. let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) };
  716. let mut host: Vec<Barrier> = barriers
  717. .iter()
  718. .filter_map(|b| host_barrier(list, b))
  719. .collect();
  720. // Buffers have host copies, not resources the barrier can name:
  721. // a barrier on one waits for every shader write before it.
  722. if barriers.iter().any(|b| {
  723. b.kind != 1 && !b.first.is_null() && crate::resource::buffer_bytes(b.first).is_some()
  724. }) {
  725. host.push(UAV_BARRIER);
  726. #[cfg(feature = "diagnostics")]
  727. crate::copystat::add(crate::copystat::C::WaitsForBuffers, 1);
  728. }
  729. if !host.is_empty() {
  730. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
  731. const _: () = assert!(size_of::<Barrier>() == size_of::<D3D12_RESOURCE_BARRIER>());
  732. // SAFETY: the same layout; borrowed resource pointers, never
  733. // released through this slice.
  734. let host = unsafe {
  735. std::slice::from_raw_parts(
  736. host.as_ptr().cast::<D3D12_RESOURCE_BARRIER>(),
  737. host.len(),
  738. )
  739. };
  740. // SAFETY: an open list and live resources.
  741. unsafe { list.list.ResourceBarrier(host) };
  742. }
  743. }
  744. 0
  745. }
  746. /// Moves a title texture's host copy to `state` in the list, if needed.
  747. #[cfg(windows)]
  748. pub(crate) fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) {
  749. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State;
  750. if let Some((texture, before)) = list.transition(resource, state) {
  751. let state = crate::host::legal_state(texture, state);
  752. let barrier = crate::host::transition(texture, State(before as i32), State(state as i32));
  753. // SAFETY: an open list and a live texture.
  754. unsafe { list.list.ResourceBarrier(&[barrier]) };
  755. }
  756. }
  757. #[cfg(windows)]
  758. const COPY_DEST: u32 = 0x400;
  759. #[cfg(windows)]
  760. const COPY_SOURCE: u32 = 0x800;
  761. /// `len` bytes at `offset` of a title buffer, if they are inside it.
  762. #[cfg(windows)]
  763. fn buffer_range(buffer: This, offset: u64, len: u64) -> Option<*mut u8> {
  764. let (data, size) = crate::resource::buffer_bytes(buffer)?;
  765. let end = offset.checked_add(len)?;
  766. if end > size {
  767. tracing::warn!(offset, len, size, "copy outside its buffer");
  768. return None;
  769. }
  770. // SAFETY: inside the buffer, checked above.
  771. Some(unsafe { data.add(offset as usize) })
  772. }
  773. /// A copy of title memory that `list` records: on the card at its place in
  774. /// the list ([`crate::host::HostList::place_copy`]), or at submission.
  775. #[cfg(windows)]
  776. fn buffer_copy(this: This, list: &crate::host::HostList, to: *mut u8, from: *const u8, len: usize) {
  777. if len == 0 {
  778. return;
  779. }
  780. if list.place_copy(to as usize, from as usize, len) {
  781. with_state(this, |_, state| state.copied());
  782. } else {
  783. list.defer_copy(to, from, len);
  784. }
  785. }
  786. /// Buffer to buffer: both are host memory, copied at submission.
  787. extern "system" fn copy_buffer_region(
  788. this: This,
  789. dst: This,
  790. dst_offset: u64,
  791. src: This,
  792. src_offset: u64,
  793. len: u64,
  794. ) {
  795. #[cfg(windows)]
  796. if let Some(list) = host_list(this)
  797. && let Some(to) = buffer_range(dst, dst_offset, len)
  798. && let Some(from) = buffer_range(src, src_offset, len)
  799. {
  800. buffer_copy(this, list, to, from, len as usize);
  801. }
  802. #[cfg(not(windows))]
  803. let _ = (this, dst, dst_offset, src, src_offset, len);
  804. }
  805. /// Whether one of two resources is a target in a stand-in format and the
  806. /// other is not ([`crate::resource::target_format`]): their texels differ
  807. /// in size, so the host cannot copy between them (logged once).
  808. #[cfg(windows)]
  809. fn unlike(dst: This, src: This) -> bool {
  810. let unlike = crate::resource::stands_in(dst) != crate::resource::stands_in(src);
  811. if unlike {
  812. static ONCE: std::sync::Once = std::sync::Once::new();
  813. ONCE.call_once(|| {
  814. tracing::warn!(?dst, ?src, "copy between a stand-in target and title-format texels skipped")
  815. });
  816. }
  817. unlike
  818. }
  819. extern "system" fn copy_resource(this: This, dst: This, src: This) {
  820. #[cfg(windows)]
  821. {
  822. let Some(list) = host_list(this) else {
  823. return;
  824. };
  825. if let (Some(to), Some(from)) = (
  826. crate::resource::host_resource(dst),
  827. crate::resource::host_resource(src),
  828. ) {
  829. if unlike(dst, src) {
  830. return;
  831. }
  832. // A source the title fills itself is uploaded first (upstream
  833. // PR #671): a copy read whatever the host texture held.
  834. if crate::texture::title_written(from) {
  835. crate::texture::upload(list, src, from);
  836. }
  837. // Depth textures shaders also write: what they wrote, first.
  838. list.twin_use(dst, false, true);
  839. list.twin_use(src, false, false);
  840. // A destination made level by level gets its levels' memory
  841. // ahead of this list (`crate::tiles`).
  842. crate::texture::card_writes(list, dst, to, None);
  843. ensure_state(list, dst, COPY_DEST);
  844. ensure_state(list, src, COPY_SOURCE);
  845. crate::texture::host_written(dst);
  846. #[cfg(feature = "diagnostics")]
  847. list.note_op(|| format!("copy resource {src:?} to {dst:?}"));
  848. // SAFETY: an open list and live textures.
  849. unsafe { list.list.CopyResource(to, from) };
  850. } else if let (Some((to, a)), Some((from, b))) = (
  851. crate::resource::buffer_bytes(dst),
  852. crate::resource::buffer_bytes(src),
  853. ) {
  854. buffer_copy(this, list, to, from, a.min(b) as usize);
  855. }
  856. }
  857. #[cfg(not(windows))]
  858. let _ = (this, dst, src);
  859. }
  860. extern "system" fn copy_resource_x(this: This, dst: This, src: This, _flags: u32) {
  861. copy_resource(this, dst, src);
  862. }
  863. /// A copy location as titles pass it, laid out as the host's: a resource,
  864. /// then a subresource index (type 0) or a placed footprint (type 1).
  865. #[repr(C)]
  866. #[derive(Clone, Copy)]
  867. pub(crate) struct CopyLocation {
  868. resource: This,
  869. kind: u32,
  870. footprint: crate::resource::PlacedFootprint,
  871. }
  872. /// Texture to texture on the GPU; buffer to texture through an upload
  873. /// buffer filled at submission. Texture to buffer (read back) is not done
  874. /// yet.
  875. extern "system" fn copy_texture_region(
  876. this: This,
  877. dst: *const CopyLocation,
  878. x: u32,
  879. y: u32,
  880. z: u32,
  881. src: *const CopyLocation,
  882. source_box: *const [u32; 6],
  883. ) {
  884. #[cfg(windows)]
  885. {
  886. use windows::Win32::Graphics::Direct3D12::{D3D12_BOX, D3D12_TEXTURE_COPY_LOCATION};
  887. use windows::core::Interface;
  888. const FOOTPRINT: u32 = 1;
  889. // SAFETY: the title passes both locations (null is tolerated).
  890. let (Some(list), Some(&dst), Some(&src)) =
  891. (host_list(this), unsafe { dst.as_ref() }, unsafe {
  892. src.as_ref()
  893. })
  894. else {
  895. return;
  896. };
  897. let Some(to) = crate::resource::host_resource(dst.resource) else {
  898. // Texture to buffer: a read back. The list copies the texels
  899. // into a host buffer of ours; once it has run they go to the
  900. // title's buffer (`HostList::defer_read_back`).
  901. // The title reads two tiny float targets back every frame (5x1
  902. // and 1x1 RGBA32F, 80 and 16 bytes: run 90), and read a buffer
  903. // nobody wrote. `VICTORY_READ_BACK=0` leaves them unmade, as
  904. // before.
  905. static COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  906. let n = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
  907. let made = read_back(list, dst, x, y, z, src, source_box);
  908. if n <= 16 || n.is_multiple_of(4096) || made.is_err() {
  909. static REFUSED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  910. if made.is_err() && REFUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) >= 16 {
  911. return;
  912. }
  913. let source = crate::resource::host_resource(src.resource).map(|r| {
  914. // SAFETY: a live resource.
  915. let d = unsafe { r.GetDesc() };
  916. format!("{}x{} f{} mips {}", d.Width, d.Height, d.Format.0, d.MipLevels)
  917. });
  918. tracing::info!(
  919. copies = n,
  920. made = ?made,
  921. source = ?source,
  922. source_kind = src.kind,
  923. destination_kind = dst.kind,
  924. destination_offset = dst.footprint.offset,
  925. destination_bytes = ?dst.footprint.bytes(),
  926. "a texture to buffer copy (a read back)"
  927. );
  928. }
  929. return;
  930. };
  931. if unlike(dst.resource, src.resource) {
  932. return;
  933. }
  934. let mut from = src;
  935. let _upload; // keeps the source alive while this call records it
  936. #[cfg(feature = "diagnostics")]
  937. let mut read = None;
  938. if src.kind == FOOTPRINT {
  939. let (Some(host), Some(bytes)) = (crate::host::host(), src.footprint.bytes()) else {
  940. return;
  941. };
  942. let Some(data) = buffer_range(src.resource, src.footprint.offset, bytes) else {
  943. return;
  944. };
  945. let buffer = match list.place_source(data as usize, bytes as usize) {
  946. // What shaders wrote to it, at this place of the list.
  947. Some(buffer) => buffer,
  948. None => {
  949. let Some((buffer, staging)) = list.upload(host, bytes) else {
  950. return;
  951. };
  952. // The list owns this mapped D3D12 upload buffer. Wine can
  953. // report its address as MEM_FREE, so use the host-upload
  954. // path.
  955. list.defer_fill_buffer(&buffer, staging, data, bytes as usize);
  956. buffer
  957. }
  958. };
  959. from.resource = buffer.as_raw().cast_const().cast();
  960. from.footprint.offset = 0;
  961. #[cfg(feature = "diagnostics")]
  962. {
  963. // SAFETY: a live buffer.
  964. read = Some((unsafe { buffer.GetGPUVirtualAddress() }, bytes));
  965. }
  966. _upload = buffer;
  967. } else {
  968. let Some(texture) = crate::resource::host_resource(src.resource) else {
  969. return;
  970. };
  971. list.twin_use(src.resource, false, false);
  972. if crate::texture::title_written(texture) {
  973. crate::texture::upload(list, src.resource, texture);
  974. }
  975. ensure_state(list, src.resource, COPY_SOURCE);
  976. from.resource = texture.as_raw().cast_const().cast();
  977. }
  978. // A depth texture shaders also write: what they wrote, first (the
  979. // source above too).
  980. list.twin_use(dst.resource, false, true);
  981. // The first copy into a texture of the title's: what it does not
  982. // write is what title memory holds, as on the console. (The host
  983. // copy is cut from a block and held whatever lay there, and no
  984. // upload is made once a copy wrote it: the atlas the title copies
  985. // its baked decorations into, a 2048x2048 BC3 texture of which a
  986. // bake writes 256x256 at most, was drawn over a character's face
  987. // with other textures' bytes wherever nothing was baked, runs n01 and
  988. // textures-1.)
  989. static OVER: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  990. if *OVER.get_or_init(|| std::env::var_os("VICTORY_COPY_OVER_TITLE").is_none_or(|v| v != "0"))
  991. && crate::texture::title_written(to)
  992. && !crate::texture::host_wrote(dst.resource as usize)
  993. {
  994. crate::texture::upload(list, dst.resource, to);
  995. // (Done before the title's copy writes over it.)
  996. if list.used(dst.resource as usize) {
  997. ensure_state(list, dst.resource, COPY_SOURCE);
  998. }
  999. }
  1000. // A destination made level by level gets the level's memory ahead
  1001. // of this list (`crate::tiles`): the title's bake copies each level
  1002. // of its result into a block-compressed texture of that kind, and
  1003. // a copy into a level without memory is dropped.
  1004. crate::texture::card_writes(list, dst.resource, to, Some(dst.footprint.offset as u32));
  1005. ensure_state(list, dst.resource, COPY_DEST);
  1006. crate::texture::host_written(dst.resource);
  1007. let mut to_location = dst;
  1008. to_location.resource = to.as_raw().cast_const().cast();
  1009. let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>());
  1010. #[cfg(feature = "diagnostics")]
  1011. {
  1012. let text = || {
  1013. // SAFETY: a live texture; the box is the title's or null.
  1014. let (d, b) = unsafe { (to.GetDesc(), host_box.map(|b| *b)) };
  1015. format!(
  1016. "copy to {:?} {}x{} f{} sub/kind {} at {x},{y},{z} from {:?} kind {} footprint {:?} box {b:?}",
  1017. dst.resource,
  1018. d.Width,
  1019. d.Height,
  1020. d.Format.0,
  1021. dst.kind,
  1022. src.resource,
  1023. src.kind,
  1024. (src.kind == FOOTPRINT).then_some(src.footprint)
  1025. )
  1026. };
  1027. match read {
  1028. Some(range) => list.note_read(text, range),
  1029. None => list.note_op(text),
  1030. }
  1031. }
  1032. const _: () =
  1033. assert!(size_of::<CopyLocation>() == size_of::<D3D12_TEXTURE_COPY_LOCATION>());
  1034. // SAFETY: an open list; both locations in the host's layout, naming
  1035. // live resources; the box is the title's (same layout).
  1036. unsafe {
  1037. list.list.CopyTextureRegion(
  1038. (&raw const to_location).cast(),
  1039. x,
  1040. y,
  1041. z,
  1042. (&raw const from).cast(),
  1043. host_box,
  1044. )
  1045. };
  1046. }
  1047. #[cfg(not(windows))]
  1048. let _ = (this, dst, x, y, z, src, source_box);
  1049. }
  1050. /// Records a texture to buffer copy (a read back) of [`copy_texture_region`]
  1051. /// into `list`, or says why not.
  1052. #[cfg(windows)]
  1053. #[allow(clippy::too_many_arguments)] // the method's own arguments
  1054. fn read_back(
  1055. list: &crate::host::HostList,
  1056. dst: CopyLocation,
  1057. x: u32,
  1058. y: u32,
  1059. z: u32,
  1060. src: CopyLocation,
  1061. source_box: *const [u32; 6],
  1062. ) -> Result<(), &'static str> {
  1063. use windows::Win32::Graphics::Direct3D12::D3D12_BOX;
  1064. use windows::core::Interface;
  1065. const FOOTPRINT: u32 = 1;
  1066. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1067. if !*ON.get_or_init(|| std::env::var_os("VICTORY_READ_BACK").is_none_or(|v| v != "0")) {
  1068. return Err("switched off");
  1069. }
  1070. if dst.kind != FOOTPRINT || src.kind == FOOTPRINT {
  1071. return Err("not a texture subresource into a placed footprint");
  1072. }
  1073. if (x, y, z) != (0, 0, 0) {
  1074. return Err("a destination corner other than the footprint's");
  1075. }
  1076. let host = crate::host::host().ok_or("no host")?;
  1077. let (footprint, [size, row, rows, pitch]) = dst.footprint.host_rows().ok_or("an unknown format")?;
  1078. // The title's buffer holds every row at its own pitch.
  1079. let bytes = pitch * (rows - 1) + row;
  1080. let data = buffer_range(dst.resource, dst.footprint.offset, bytes).ok_or("a destination outside its buffer")?;
  1081. let texture = crate::resource::host_resource(src.resource).ok_or("no host texture")?;
  1082. let buffer = host.read_back_buffer(size).ok_or("no read-back buffer")?;
  1083. // As a texture source of any copy: what shaders wrote to a depth twin
  1084. // and what the title wrote itself first, then the state.
  1085. list.twin_use(src.resource, false, false);
  1086. if crate::texture::title_written(texture) {
  1087. crate::texture::upload(list, src.resource, texture);
  1088. }
  1089. ensure_state(list, src.resource, COPY_SOURCE);
  1090. let mut from = src;
  1091. from.resource = texture.as_raw().cast_const().cast();
  1092. let mut to = dst;
  1093. to.resource = buffer.as_raw().cast_const().cast();
  1094. to.footprint = footprint;
  1095. let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>());
  1096. #[cfg(feature = "diagnostics")]
  1097. list.note_op(|| {
  1098. format!(
  1099. "read back of {:?} sub {} into buffer {:?}+{:#x}: {rows} rows of {row} bytes",
  1100. src.resource, src.footprint.offset as u32, dst.resource, dst.footprint.offset
  1101. )
  1102. });
  1103. // SAFETY: an open list; both locations in the host's layout (asserted
  1104. // in `copy_texture_region`), naming a live texture and our buffer, which
  1105. // the list keeps until it is reset; the box is the title's.
  1106. unsafe {
  1107. list.list
  1108. .CopyTextureRegion((&raw const to).cast(), 0, 0, 0, (&raw const from).cast(), host_box)
  1109. };
  1110. list.defer_read_back(buffer, data, [row as usize, rows as usize, pitch as usize]);
  1111. Ok(())
  1112. }
  1113. #[allow(clippy::too_many_arguments)] // the method's own arguments
  1114. extern "system" fn copy_texture_region_x(
  1115. this: This,
  1116. dst: *const CopyLocation,
  1117. x: u32,
  1118. y: u32,
  1119. z: u32,
  1120. src: *const CopyLocation,
  1121. source_box: *const [u32; 6],
  1122. _flags: u32,
  1123. ) {
  1124. copy_texture_region(this, dst, x, y, z, src, source_box);
  1125. }
  1126. extern "system" fn resolve(
  1127. this: This,
  1128. dst: This,
  1129. dst_sub: u32,
  1130. src: This,
  1131. src_sub: u32,
  1132. format: u32,
  1133. ) {
  1134. #[cfg(windows)]
  1135. if let Some(list) = host_list(this)
  1136. && let (Some(to), Some(from)) = (
  1137. crate::resource::host_resource(dst),
  1138. crate::resource::host_resource(src),
  1139. )
  1140. {
  1141. use windows::Win32::Foundation::RECT;
  1142. use windows::Win32::Graphics::Direct3D12::{
  1143. D3D12_RESOLVE_MODE_AVERAGE, ID3D12GraphicsCommandList1,
  1144. };
  1145. use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
  1146. use windows::core::Interface;
  1147. const RESOLVE_DEST: u32 = 0x1000;
  1148. const RESOLVE_SOURCE: u32 = 0x2000;
  1149. if unlike(dst, src) {
  1150. return;
  1151. }
  1152. // Depth textures shaders also write: what they wrote, first.
  1153. list.twin_use(dst, false, true);
  1154. list.twin_use(src, false, false);
  1155. // As for a copy (`crate::tiles`).
  1156. crate::texture::card_writes(list, dst, to, Some(dst_sub));
  1157. ensure_state(list, dst, RESOLVE_DEST);
  1158. ensure_state(list, src, RESOLVE_SOURCE);
  1159. crate::texture::host_written(dst);
  1160. #[cfg(feature = "diagnostics")]
  1161. list.note_op(|| format!("resolve {src:?} to {dst:?} format {format}"));
  1162. // SAFETY: an open list and live textures; the region is inside both.
  1163. unsafe {
  1164. let (a, b) = (to.GetDesc(), from.GetDesc());
  1165. let format = if crate::resource::stands_in(dst) { a.Format } else { DXGI_FORMAT(format as i32) };
  1166. if (a.Width, a.Height) == (b.Width, b.Height) {
  1167. list.list
  1168. .ResolveSubresource(to, dst_sub, from, src_sub, format);
  1169. } else if let Ok(list1) = list.list.cast::<ID3D12GraphicsCommandList1>() {
  1170. // The console clips a larger source to the destination.
  1171. let rect = RECT {
  1172. left: 0,
  1173. top: 0,
  1174. right: a.Width.min(b.Width) as i32,
  1175. bottom: a.Height.min(b.Height) as i32,
  1176. };
  1177. list1.ResolveSubresourceRegion(
  1178. to,
  1179. dst_sub,
  1180. 0,
  1181. 0,
  1182. from,
  1183. src_sub,
  1184. Some(&rect),
  1185. format,
  1186. D3D12_RESOLVE_MODE_AVERAGE,
  1187. );
  1188. }
  1189. }
  1190. }
  1191. #[cfg(not(windows))]
  1192. let _ = (this, dst, dst_sub, src, src_sub, format);
  1193. }
  1194. #[repr(C)]
  1195. pub(crate) struct Rect {
  1196. left: i32,
  1197. top: i32,
  1198. right: i32,
  1199. bottom: i32,
  1200. }
  1201. extern "system" fn clear_rtv(
  1202. this: This,
  1203. handle: u64,
  1204. color: *const [f32; 4],
  1205. count: u32,
  1206. rects: *const Rect,
  1207. ) {
  1208. #[cfg(windows)]
  1209. {
  1210. let (Some(list), Some(record)) = (host_list(this), crate::descriptor::rtv_record(handle))
  1211. else {
  1212. return;
  1213. };
  1214. let (Some(texture), Some(host)) = (
  1215. crate::resource::host_resource(record.resource),
  1216. crate::host::host(),
  1217. ) else {
  1218. return;
  1219. };
  1220. // SAFETY: the title passes four floats (null is tolerated).
  1221. let Some(color) = (unsafe { color.as_ref() }) else {
  1222. return;
  1223. };
  1224. let rects = (count > 0 && !rects.is_null()).then(|| {
  1225. // SAFETY: the title passes `count` rectangles, laid out as the host's.
  1226. unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) }
  1227. });
  1228. const RENDER_TARGET: u32 = 0x4;
  1229. let rtv = host.rtv(Some(texture), record.desc().as_ref());
  1230. // SAFETY: an open list, a fresh view of a live texture.
  1231. unsafe {
  1232. if let Some((_, before)) = list.transition(record.resource, RENDER_TARGET) {
  1233. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State;
  1234. list.list.ResourceBarrier(&[crate::host::transition(
  1235. texture,
  1236. State(before as i32),
  1237. State(RENDER_TARGET as i32),
  1238. )]);
  1239. }
  1240. list.list.ClearRenderTargetView(rtv, color, rects);
  1241. }
  1242. }
  1243. #[cfg(not(windows))]
  1244. let _ = (this, handle, color, count, rects);
  1245. }
  1246. /// `ClearDepthStencilView(handle, flags, depth, stencil, count, rects)`;
  1247. /// flags: 1 depth, 2 stencil.
  1248. extern "system" fn clear_dsv(
  1249. this: This,
  1250. handle: u64,
  1251. flags: u32,
  1252. depth: f32,
  1253. stencil: u8,
  1254. count: u32,
  1255. rects: *const Rect,
  1256. ) {
  1257. #[cfg(windows)]
  1258. {
  1259. use windows::Win32::Graphics::Direct3D12::D3D12_CLEAR_FLAGS;
  1260. let (Some(list), Some(record)) = (host_list(this), crate::descriptor::dsv_record(handle))
  1261. else {
  1262. return;
  1263. };
  1264. let (Some(texture), Some(host)) = (
  1265. crate::resource::host_resource(record.resource),
  1266. crate::host::host(),
  1267. ) else {
  1268. return;
  1269. };
  1270. let rects = (count > 0 && !rects.is_null()).then(|| {
  1271. // SAFETY: the title passes `count` rectangles, laid out as the host's.
  1272. unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) }
  1273. });
  1274. const DEPTH_WRITE: u32 = 0x10;
  1275. // A depth texture shaders also write: what they wrote, first (the
  1276. // clear may be of one slice or of some rectangles).
  1277. list.twin_use(record.resource, false, true);
  1278. ensure_state(list, record.resource, DEPTH_WRITE);
  1279. if crate::resource::depth_and_unordered(record.resource) {
  1280. crate::resource::DEPTH_UNORDERED[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1281. }
  1282. let dsv = host.dsv(texture, record.depth_desc().as_ref());
  1283. // SAFETY: an open list, a fresh view of a live texture.
  1284. unsafe {
  1285. list.list
  1286. .ClearDepthStencilView(dsv, D3D12_CLEAR_FLAGS(flags as i32 & 3), depth, stencil, rects)
  1287. };
  1288. }
  1289. #[cfg(not(windows))]
  1290. let _ = (this, handle, flags, depth, stencil, count, rects);
  1291. }
  1292. /// `CopyMemoryToMemoryX(destination, source, size, flags)`: GPU addresses
  1293. /// are title memory, copied at submission like buffer copies (if mapped).
  1294. extern "system" fn copy_memory(this: This, dst: u64, src: u64, len: u64, _flags: u32) {
  1295. #[cfg(windows)]
  1296. if let Some(list) = host_list(this)
  1297. && dst != 0
  1298. && src != 0
  1299. {
  1300. let len = len as usize;
  1301. if list.place_copy(dst as usize, src as usize, len) {
  1302. with_state(this, |_, state| state.copied());
  1303. return;
  1304. }
  1305. list.defer(move || {
  1306. if crate::texture::committed(src as *const u8, len)
  1307. && crate::texture::committed(dst as *const u8, len)
  1308. {
  1309. // SAFETY: both ranges are committed title memory.
  1310. unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len) };
  1311. }
  1312. });
  1313. }
  1314. #[cfg(not(windows))]
  1315. let _ = (this, dst, src, len);
  1316. }
  1317. /// `DriverHintX(feature, value)`: no hints for the host.
  1318. extern "system" fn driver_hint(_: This, _feature: u64, _value: u64) -> u64 {
  1319. 0
  1320. }
  1321. /// `DispatchX(x, y, z, flags)`: a dispatch with console flags, which the
  1322. /// host has no use for (the ray-tracing builder dispatches this way).
  1323. extern "system" fn dispatch_x(this: This, x: u32, y: u32, z: u32, _flags: u32) {
  1324. #[cfg(windows)]
  1325. state::dispatch(this, x, y, z);
  1326. #[cfg(not(windows))]
  1327. {
  1328. let _ = (this, x, y, z);
  1329. count_dispatch();
  1330. }
  1331. }
  1332. /// `BeginQuery`/`EndQuery(heap, type, index)`: queries are answered when
  1333. /// resolved.
  1334. extern "system" fn query_mark(_: This, _heap: This, _kind: u32, _index: u32) {}
  1335. /// `ResolveQueryData(heap, type, first, count, buffer, offset)`: writes
  1336. /// each query's result into the buffer once the list has run. Timestamps
  1337. /// (type 2) are the GPU clock then; occlusion counts (0) say a million
  1338. /// samples passed and binary occlusion (1) visible, so nothing is culled
  1339. /// by a query.
  1340. /// shortcut: no query runs on the host GPU; results are plausible values,
  1341. /// not measured ones (time spans come out as the submission's length).
  1342. extern "system" fn resolve_queries(
  1343. this: This,
  1344. _heap: This,
  1345. kind: u32,
  1346. _first: u32,
  1347. count: u32,
  1348. buffer: This,
  1349. offset: u64,
  1350. ) {
  1351. const OCCLUSION: u32 = 0;
  1352. const BINARY: u32 = 1;
  1353. const TIMESTAMP: u32 = 2;
  1354. const PIPELINE_STATISTICS: u32 = 3;
  1355. let Some((data, size)) = crate::resource::buffer_bytes(buffer) else {
  1356. return;
  1357. };
  1358. let (what, bytes) = match kind {
  1359. OCCLUSION => (Written::Value(1 << 20), 8),
  1360. BINARY => (Written::Value(1), 8),
  1361. TIMESTAMP => (Written::GpuTimestamp, 8),
  1362. PIPELINE_STATISTICS => (Written::Value(0), 88),
  1363. _ => (Written::Value(0), 16),
  1364. };
  1365. let Some(end) = offset.checked_add(u64::from(count) * bytes) else {
  1366. return;
  1367. };
  1368. if end > size {
  1369. return;
  1370. }
  1371. for i in 0..u64::from(count) {
  1372. // Wider results are written as 8-byte pieces.
  1373. for piece in 0..bytes / 8 {
  1374. // SAFETY: inside the buffer, checked above.
  1375. let at = unsafe { data.add((offset + i * bytes + piece * 8) as usize) };
  1376. let what = if piece == 0 { what } else { Written::Value(0) };
  1377. defer_write(this, at as u64, what, 8);
  1378. }
  1379. }
  1380. }
  1381. /// IUnknown 3, object 4, device child 1, allocator 2.
  1382. static ALLOCATOR_FUNCTIONS: Table<24> = {
  1383. let mut f = object::d3d12_object(object::missing_table::<ALLOCATOR, 24>());
  1384. f[0] = allocator_query as *const ();
  1385. f[2] = allocator_release as *const ();
  1386. f[7] = object::parent_device as *const (); // 0x38
  1387. f[8] = allocator_reset as *const (); // 0x40
  1388. f[9] = object::ignore as *const (); // 0x48 allocation callback
  1389. Table(f)
  1390. };
  1391. extern "system" fn set_pipeline(this: This, pipeline: This) {
  1392. crate::pipeline::bound(pipeline);
  1393. #[cfg(windows)]
  1394. with_state(this, |_, state| state.set_pipeline(pipeline));
  1395. #[cfg(not(windows))]
  1396. let _ = this;
  1397. }
  1398. /// Pipeline syncs: waits for earlier work and cache flushes, at the top or
  1399. /// bottom of the pipe `(flags, control, address, size)`. The host orders
  1400. /// nothing between dispatches by itself: what shaders wrote is waited for
  1401. /// here as at the title's barriers (the ray-tracing structure builder has
  1402. /// no other wait between its stages).
  1403. /// (Arguments may be what earlier shaders wrote from here on:
  1404. /// `State::synced`.)
  1405. extern "system" fn sync(this: This, flags: u32, control: u32, address: u64, size: u64) {
  1406. #[cfg(windows)]
  1407. {
  1408. with_state(this, |_, state| state.synced());
  1409. if let Some(list) = host_list(this) {
  1410. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
  1411. #[cfg(feature = "diagnostics")]
  1412. {
  1413. // The shapes of the title's calls, each once.
  1414. static SEEN: std::sync::Mutex<Vec<(u32, u32, bool)>> = std::sync::Mutex::new(Vec::new());
  1415. let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
  1416. let shape = (flags, control, address == 0);
  1417. if seen.len() < 64 && !seen.contains(&shape) {
  1418. seen.push(shape);
  1419. tracing::info!(
  1420. flags = format_args!("{flags:#x}"),
  1421. control = format_args!("{control:#x}"),
  1422. address = format_args!("{address:#x}"),
  1423. size = format_args!("{size:#x}"),
  1424. "a pipeline sync"
  1425. );
  1426. }
  1427. crate::copystat::add(crate::copystat::C::WaitsForGroups, 1);
  1428. }
  1429. // SAFETY: the same layout; no resource named.
  1430. let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) };
  1431. // SAFETY: an open list.
  1432. unsafe { list.list.ResourceBarrier(&[barrier]) };
  1433. }
  1434. }
  1435. let _ = (this, flags, control, address, size);
  1436. }
  1437. /// Reset with console flags `(allocator, pipeline, flags)`; the flags only
  1438. /// tune the console's command memory.
  1439. extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: u32) -> HRESULT {
  1440. reset(this, allocator, pipeline)
  1441. }
  1442. /// Newer lists' 0x4a0 `(size, alignment) -> pointer`: memory the list
  1443. /// owns until it is reset, which the CPU writes and the GPU reads at the
  1444. /// same address; null on failure. The title's BVH builder puts
  1445. /// its instance descriptions there (and wrote through our old
  1446. /// `E_NOTIMPL` as a pointer).
  1447. extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mut u8 {
  1448. let align = usize::try_from(alignment).unwrap_or(0).max(16);
  1449. let Some(len) = usize::try_from(size).ok().and_then(|s| s.checked_add(align)) else {
  1450. return std::ptr::null_mut();
  1451. };
  1452. if this.is_null() || !align.is_power_of_two() {
  1453. return std::ptr::null_mut();
  1454. }
  1455. let mut block = vec![0u8; len];
  1456. let start = block.as_mut_ptr();
  1457. // SAFETY: the offset is below `align`, so `size` bytes fit after it.
  1458. let at = unsafe { start.add(start.align_offset(align)) };
  1459. // SAFETY: the title passes one of our lists.
  1460. let uploads = unsafe { &(*this.cast::<List>()).uploads };
  1461. // Moving the vector keeps its heap block where it is.
  1462. uploads.lock().unwrap_or_else(|e| e.into_inner()).push(block);
  1463. at
  1464. }
  1465. /// Draw state the host has no use for (root signatures: ours come with
  1466. /// the pipeline; depth order and shading rate hints): any arguments,
  1467. /// nothing returned.
  1468. extern "system" fn ignored_state(_: This) {}
  1469. /// The title's draw state (decision 0007, step 3), kept for its draws or
  1470. /// set on the host list at once. Without a host GPU these do nothing.
  1471. #[cfg(windows)]
  1472. mod state {
  1473. use super::{This, with_state};
  1474. use crate::draw::{IndexView, VertexView};
  1475. use windows::Win32::Foundation::RECT;
  1476. use windows::Win32::Graphics::Direct3D12::D3D12_VIEWPORT;
  1477. /// `count` items at `items`, or none.
  1478. fn items<'a, T>(items: *const T, count: u32) -> &'a [T] {
  1479. if items.is_null() || count == 0 {
  1480. return &[];
  1481. }
  1482. // SAFETY: the title passes `count` items.
  1483. unsafe { std::slice::from_raw_parts(items, count as usize) }
  1484. }
  1485. pub(super) extern "system" fn topology(this: This, topology: u32) {
  1486. with_state(this, |list, s| s.set_topology(list, topology));
  1487. }
  1488. pub(super) extern "system" fn viewports(
  1489. this: This,
  1490. count: u32,
  1491. viewports: *const D3D12_VIEWPORT,
  1492. ) {
  1493. // (Through the draw state, which keeps them for the host list
  1494. // that continues this one after a cut: `State::replay`.)
  1495. with_state(this, |list, s| s.set_viewports(list, items(viewports, count)));
  1496. }
  1497. pub(super) extern "system" fn scissors(this: This, count: u32, rects: *const RECT) {
  1498. with_state(this, |list, s| s.set_scissors(list, items(rects, count)));
  1499. }
  1500. pub(super) extern "system" fn blend_factor(this: This, factor: *const [f32; 4]) {
  1501. with_state(this, |list, s| {
  1502. // SAFETY: the title passes four floats or null.
  1503. s.set_blend_factor(list, unsafe { factor.as_ref() })
  1504. });
  1505. }
  1506. pub(super) extern "system" fn stencil_ref(this: This, reference: u32) {
  1507. with_state(this, |list, s| s.set_stencil_ref(list, reference));
  1508. }
  1509. pub(super) extern "system" fn depth_bounds(this: This, min: f32, max: f32) {
  1510. with_state(this, |list, s| s.set_depth_bounds(list, min, max));
  1511. }
  1512. pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) {
  1513. with_state(this, |_, s| s.set_heaps(items(heaps, count)));
  1514. }
  1515. pub(super) extern "system" fn compute_table(this: This, slot: u32, handle: u64) {
  1516. with_state(this, |_, s| s.set_table(true, slot, handle));
  1517. }
  1518. pub(super) extern "system" fn graphics_table(this: This, slot: u32, handle: u64) {
  1519. with_state(this, |_, s| s.set_table(false, slot, handle));
  1520. }
  1521. pub(super) extern "system" fn compute_constant(this: This, slot: u32, value: u32, offset: u32) {
  1522. with_state(this, |_, s| s.set_constants(true, slot, &[value], offset));
  1523. }
  1524. pub(super) extern "system" fn graphics_constant(
  1525. this: This,
  1526. slot: u32,
  1527. value: u32,
  1528. offset: u32,
  1529. ) {
  1530. with_state(this, |_, s| s.set_constants(false, slot, &[value], offset));
  1531. }
  1532. pub(super) extern "system" fn compute_constants(
  1533. this: This,
  1534. slot: u32,
  1535. count: u32,
  1536. values: *const u32,
  1537. offset: u32,
  1538. ) {
  1539. with_state(this, |_, s| {
  1540. s.set_constants(true, slot, items(values, count), offset)
  1541. });
  1542. }
  1543. pub(super) extern "system" fn graphics_constants(
  1544. this: This,
  1545. slot: u32,
  1546. count: u32,
  1547. values: *const u32,
  1548. offset: u32,
  1549. ) {
  1550. with_state(this, |_, s| {
  1551. s.set_constants(false, slot, items(values, count), offset)
  1552. });
  1553. }
  1554. /// Root constant buffer, shader resource and unordered access views.
  1555. pub(super) extern "system" fn compute_view(this: This, slot: u32, address: u64) {
  1556. with_state(this, |_, s| s.set_view(true, slot, address));
  1557. }
  1558. pub(super) extern "system" fn graphics_view(this: This, slot: u32, address: u64) {
  1559. with_state(this, |_, s| s.set_view(false, slot, address));
  1560. }
  1561. pub(super) extern "system" fn index_buffer(this: This, view: *const IndexView) {
  1562. // SAFETY: the title passes a view or null.
  1563. with_state(this, |_, s| s.set_index_buffer(unsafe { view.as_ref() }));
  1564. }
  1565. pub(super) extern "system" fn vertex_buffers(
  1566. this: This,
  1567. start: u32,
  1568. count: u32,
  1569. views: *const VertexView,
  1570. ) {
  1571. with_state(this, |_, s| {
  1572. if views.is_null() {
  1573. s.clear_vertex_buffers(start, count);
  1574. } else {
  1575. s.set_vertex_buffers(start, items(views, count));
  1576. }
  1577. });
  1578. }
  1579. /// `(count, handles, one range, depth)`: with one range, the handles
  1580. /// follow the first at the render target view size (128 bytes).
  1581. pub(super) extern "system" fn targets(
  1582. this: This,
  1583. count: u32,
  1584. handles: *const u64,
  1585. one_range: i32,
  1586. depth: *const u64,
  1587. ) {
  1588. let handles: Vec<u64> = if one_range != 0 && !handles.is_null() {
  1589. // SAFETY: the title passes the first handle.
  1590. let first = unsafe { *handles };
  1591. (0..u64::from(count)).map(|i| first + 128 * i).collect()
  1592. } else {
  1593. items(handles, count).to_vec()
  1594. };
  1595. // SAFETY: the title passes a handle or null.
  1596. let depth = unsafe { depth.as_ref() }.copied().unwrap_or(0);
  1597. with_state(this, |list, s| s.set_targets(list, &handles, depth));
  1598. }
  1599. pub(super) extern "system" fn draw(
  1600. this: This,
  1601. vertices: u32,
  1602. instances: u32,
  1603. first: u32,
  1604. first_instance: u32,
  1605. ) {
  1606. super::count_draw();
  1607. with_state(this, |list, s| {
  1608. s.draw(list, vertices, instances, first, first_instance)
  1609. });
  1610. }
  1611. pub(super) extern "system" fn dispatch(this: This, x: u32, y: u32, z: u32) {
  1612. super::count_dispatch();
  1613. with_state(this, |list, s| s.dispatch(list, x, y, z));
  1614. }
  1615. /// `DispatchMesh(x, y, z)` (the PC method of List6); the title's mesh
  1616. /// programs take `x` groups only.
  1617. pub(super) extern "system" fn dispatch_mesh(this: This, x: u32, y: u32, z: u32) {
  1618. super::count_draw();
  1619. if y * z != 1 {
  1620. static ONCE: std::sync::Once = std::sync::Once::new();
  1621. ONCE.call_once(|| tracing::warn!(x, y, z, "a mesh dispatch with y or z groups"));
  1622. }
  1623. with_state(this, |list, s| s.dispatch_mesh(list, x));
  1624. }
  1625. /// `DispatchMeshX(x, flags, indirect arguments, payload)`.
  1626. /// shortcut: dispatches whose group count is in GPU memory (indirect)
  1627. /// are dropped; make them ExecuteIndirect when the title uses them.
  1628. pub(super) extern "system" fn dispatch_mesh_x(
  1629. this: This,
  1630. x: u32,
  1631. _flags: u64,
  1632. indirect: u64,
  1633. _payload: u64,
  1634. ) {
  1635. super::count_draw();
  1636. if indirect != 0 {
  1637. static ONCE: std::sync::Once = std::sync::Once::new();
  1638. ONCE.call_once(|| tracing::warn!("indirect mesh dispatches dropped"));
  1639. return;
  1640. }
  1641. with_state(this, |list, s| s.dispatch_mesh(list, x));
  1642. }
  1643. pub(super) extern "system" fn draw_indexed(
  1644. this: This,
  1645. indices: u32,
  1646. instances: u32,
  1647. first: u32,
  1648. base: i32,
  1649. first_instance: u32,
  1650. ) {
  1651. super::count_draw();
  1652. with_state(this, |list, s| {
  1653. s.draw_indexed(list, indices, instances, first, base, first_instance)
  1654. });
  1655. }
  1656. }
  1657. /// Without a host GPU every draw state call is ignored.
  1658. #[cfg(not(windows))]
  1659. mod state {
  1660. pub(super) use super::dispatch;
  1661. pub(super) use super::draw;
  1662. pub(super) use super::draw as draw_indexed;
  1663. pub(super) use super::draw as dispatch_mesh;
  1664. pub(super) use super::draw as dispatch_mesh_x;
  1665. pub(super) use super::ignored_state as blend_factor;
  1666. pub(super) use super::ignored_state as compute_constant;
  1667. pub(super) use super::ignored_state as compute_constants;
  1668. pub(super) use super::ignored_state as compute_table;
  1669. pub(super) use super::ignored_state as compute_view;
  1670. pub(super) use super::ignored_state as graphics_constant;
  1671. pub(super) use super::ignored_state as graphics_constants;
  1672. pub(super) use super::ignored_state as graphics_table;
  1673. pub(super) use super::ignored_state as graphics_view;
  1674. pub(super) use super::ignored_state as heaps;
  1675. pub(super) use super::ignored_state as index_buffer;
  1676. pub(super) use super::ignored_state as scissors;
  1677. pub(super) use super::ignored_state as stencil_ref;
  1678. pub(super) use super::ignored_state as depth_bounds;
  1679. pub(super) use super::ignored_state as targets;
  1680. pub(super) use super::ignored_state as topology;
  1681. pub(super) use super::ignored_state as vertex_buffers;
  1682. pub(super) use super::ignored_state as viewports;
  1683. }
  1684. fn count_draw() {
  1685. DRAWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1686. }
  1687. /// Draws of the kinds the host does not run yet (indirect, mesh), and
  1688. /// dispatches, counted per frame for the log.
  1689. /// shortcut: dropped until their shaders translate (decision 0007).
  1690. #[cfg(not(windows))]
  1691. extern "system" fn draw(_: This) {
  1692. count_draw();
  1693. }
  1694. /// `ExecuteIndirect(signature, max count, arguments, offset, count buffer,
  1695. /// offset)`. The title's signatures (title+0x2479466, 2026-11-24)
  1696. /// hold one argument each: draw (stride 16), indexed draw (20), dispatch
  1697. /// (12), mesh dispatch (12), and the console's single-pass dispatch, type
  1698. /// 105 (stride 12: the three group counts; its flags live in the
  1699. /// signature, the title passes none), run as a plain dispatch. They run
  1700. /// through the host's indirect execution (`State::execute_indirect`).
  1701. /// shortcut: signatures that change root arguments are dropped (logged
  1702. /// once per signature).
  1703. extern "system" fn execute_indirect(
  1704. this: This,
  1705. signature: This,
  1706. max: u32,
  1707. arguments: This,
  1708. offset: u64,
  1709. count: This,
  1710. count_offset: u64,
  1711. ) {
  1712. count_draw();
  1713. let Some((stride, args)) = crate::signature::layout(signature) else {
  1714. return;
  1715. };
  1716. let address = crate::resource::buffer_bytes(arguments).map(|(p, _)| p as u64 + offset);
  1717. let counter = crate::resource::buffer_bytes(count).map(|(p, _)| p as u64 + count_offset);
  1718. let mut ran = false;
  1719. #[cfg(windows)]
  1720. if let ([[kind, ..]], Some(address)) = (args, address)
  1721. && (count.is_null() || counter.is_some())
  1722. {
  1723. const DISPATCH: u32 = 2;
  1724. const DISPATCH_SINGLE: u32 = 105;
  1725. let kind = if *kind == DISPATCH_SINGLE { DISPATCH } else { *kind };
  1726. with_state(this, |list, s| {
  1727. ran = s.execute_indirect(list, (kind, stride, max), address, counter);
  1728. });
  1729. } else {
  1730. #[cfg(all(windows, feature = "diagnostics"))]
  1731. crate::pipeline::note_why(format!(
  1732. "indirect signature {args:?}: arguments in a buffer {}, count in a buffer {}",
  1733. address.is_some(),
  1734. count.is_null() || counter.is_some()
  1735. ));
  1736. }
  1737. if ran {
  1738. return;
  1739. }
  1740. INDIRECT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1741. static SEEN: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
  1742. let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
  1743. if !seen.contains(&(signature as usize)) {
  1744. seen.push(signature as usize);
  1745. tracing::info!(
  1746. stride,
  1747. ?args,
  1748. max,
  1749. address = ?address.map(|a| format!("{a:#x}")),
  1750. counted = !count.is_null(),
  1751. "indirect execution dropped (first time for this signature)"
  1752. );
  1753. }
  1754. }
  1755. /// Indirect executions dropped since the last call.
  1756. pub(crate) fn take_indirect() -> u64 {
  1757. INDIRECT.swap(0, std::sync::atomic::Ordering::Relaxed)
  1758. }
  1759. static INDIRECT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1760. fn count_dispatch() {
  1761. DISPATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1762. }
  1763. #[cfg(not(windows))]
  1764. extern "system" fn dispatch(_: This) {
  1765. count_dispatch();
  1766. }
  1767. static DRAWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1768. static DISPATCHES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1769. /// Draws (any kind, mesh and indirect included) and compute dispatches
  1770. /// recorded since the last call.
  1771. pub(crate) fn take_counts() -> (u64, u64) {
  1772. use std::sync::atomic::Ordering::Relaxed;
  1773. (DRAWS.swap(0, Relaxed), DISPATCHES.swap(0, Relaxed))
  1774. }
  1775. /// A GPU wait for a memory value: the list's commands after it run when
  1776. /// the 32 or 64 bits at `address` compare as asked with `reference`.
  1777. #[derive(Clone, Copy, Debug)]
  1778. pub(crate) struct ValueWait {
  1779. address: u64,
  1780. comparison: u32,
  1781. reference: u64,
  1782. wide: bool,
  1783. }
  1784. impl ValueWait {
  1785. /// Whether the memory holds what is waited for now.
  1786. /// shortcut: the comparison codes are taken to be the comparison
  1787. /// functions' (1 never .. 8 always, value against reference); one not
  1788. /// known counts as met, and so does memory that is not mapped.
  1789. ///
  1790. /// The value is read through the kernel, which reports memory that is
  1791. /// not there instead of faulting (as the copies of title memory are
  1792. /// read, `crate::host::copy_mapped`). Asking Windows first whether the
  1793. /// memory is committed (`VirtualQuery`) walks the page tables to the
  1794. /// end of the region: the title keeps these values in a 1.1 GB
  1795. /// allocation (0xd00000000), where one question took about 8 ms, and a
  1796. /// queue asks at every submission and every signal, for each queue that
  1797. /// stands at a wait (the title has five queues). That was
  1798. /// 1.0-2.2 s of every cutscene frame on the thread that submits (runs
  1799. /// 36-49: "between its submissions ... kernel"; 47 of 110 looks at
  1800. /// that thread in run 49 found it in this question).
  1801. /// `VICTORY_WAIT_ASK=1` asks first, as before.
  1802. pub(crate) fn met(&self) -> bool {
  1803. #[cfg(all(windows, feature = "diagnostics"))]
  1804. let started = std::time::Instant::now();
  1805. let met = self.holds();
  1806. #[cfg(all(windows, feature = "diagnostics"))]
  1807. {
  1808. use crate::copystat::{C, add};
  1809. add(C::WaitChecks, 1);
  1810. add(C::WaitCheckNs, started.elapsed().as_nanos() as u64);
  1811. }
  1812. met
  1813. }
  1814. fn holds(&self) -> bool {
  1815. let bytes = if self.wide { 8 } else { 4 };
  1816. if self.address == 0 {
  1817. return true;
  1818. }
  1819. static ASK: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1820. if *ASK.get_or_init(|| std::env::var_os("VICTORY_WAIT_ASK").is_some_and(|v| v == "1"))
  1821. && !crate::texture::committed(self.address as *const u8, bytes)
  1822. {
  1823. return true;
  1824. }
  1825. // The low `bytes` bytes; the rest stays zero.
  1826. let mut raw = [0u8; 8];
  1827. if !crate::host::read_into(self.address as *const u8, &mut raw[..bytes]) {
  1828. return true;
  1829. }
  1830. self.holds_for(u64::from_le_bytes(raw))
  1831. }
  1832. /// Where the value waited for is: address and bytes.
  1833. #[cfg(windows)]
  1834. pub(crate) fn place(&self) -> (usize, usize) {
  1835. (self.address as usize, if self.wide { 8 } else { 4 })
  1836. }
  1837. /// Whether the wait is met with `value` at its address (its low half
  1838. /// for a 32-bit wait).
  1839. pub(crate) fn holds_for(&self, value: u64) -> bool {
  1840. let (value, reference) = if self.wide {
  1841. (value, self.reference)
  1842. } else {
  1843. (value & 0xFFFF_FFFF, self.reference & 0xFFFF_FFFF)
  1844. };
  1845. match self.comparison {
  1846. 1 => false,
  1847. 2 => value < reference,
  1848. 3 => value == reference,
  1849. 4 => value <= reference,
  1850. 5 => value > reference,
  1851. 6 => value != reference,
  1852. 7 => value >= reference,
  1853. _ => true,
  1854. }
  1855. }
  1856. }
  1857. /// The waits lists recorded since their last reset, by list.
  1858. static VALUE_WAITS: std::sync::Mutex<Vec<(usize, ValueWait)>> = std::sync::Mutex::new(Vec::new());
  1859. /// The waits of the submitted `lists` that are not met yet (taken from
  1860. /// them): what the console's GPU would stop at. The title orders work
  1861. /// between its queues this way (the title: the compute queue's
  1862. /// lighting passes wait for a value the graphics queue's depth pass writes
  1863. /// at the bottom of the pipe; run at once, they read a cleared depth
  1864. /// buffer and nothing was lit).
  1865. /// shortcut: a wait holds its whole list (and submission) back, not only
  1866. /// the commands after it.
  1867. pub(crate) fn unmet_waits(lists: &[This]) -> Vec<ValueWait> {
  1868. let mut waits = VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner());
  1869. let mut unmet = Vec::new();
  1870. waits.retain(|&(list, wait)| {
  1871. if !lists.iter().any(|&l| l as usize == list) {
  1872. return true;
  1873. }
  1874. if !wait.met() {
  1875. unmet.push(wait);
  1876. }
  1877. false
  1878. });
  1879. unmet
  1880. }
  1881. /// The waits each of the submitted `lists` recorded (taken from them),
  1882. /// met or not, at the list's first place in the submission.
  1883. #[cfg(windows)]
  1884. pub(crate) fn waits_by_list(lists: &[This]) -> Vec<Vec<ValueWait>> {
  1885. let mut waits = VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner());
  1886. let mut by = vec![Vec::new(); lists.len()];
  1887. waits.retain(|&(list, wait)| {
  1888. match lists.iter().position(|&l| l as usize == list) {
  1889. Some(i) => {
  1890. by[i].push(wait);
  1891. false
  1892. }
  1893. None => true,
  1894. }
  1895. });
  1896. by
  1897. }
  1898. fn wait_for(this: This, address: u64, comparison: u32, reference: u64, wide: bool) {
  1899. let wait = ValueWait {
  1900. address,
  1901. comparison,
  1902. reference,
  1903. wide,
  1904. };
  1905. static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1906. if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 12 {
  1907. tracing::info!(
  1908. address = format_args!("{address:#x}"),
  1909. comparison,
  1910. reference,
  1911. wide,
  1912. met = wait.met(),
  1913. "a list waits for a memory value"
  1914. );
  1915. }
  1916. #[cfg(all(windows, feature = "diagnostics"))]
  1917. if let Some(host) = host_list(this) {
  1918. crate::capture::op(std::ptr::from_ref(host) as usize, || {
  1919. format!(
  1920. "WAIT VALUE at {address:#x} comparison {comparison} reference {reference:#x} wide {wide} met {}",
  1921. wait.met()
  1922. )
  1923. });
  1924. }
  1925. // The list is cut here, and the wait stands before what follows.
  1926. #[cfg(windows)]
  1927. if crate::queue::cuts() {
  1928. cut(this, wait);
  1929. return;
  1930. }
  1931. VALUE_WAITS
  1932. .lock()
  1933. .unwrap_or_else(|e| e.into_inner())
  1934. .push((this as usize, wait));
  1935. }
  1936. extern "system" fn wait_value(this: This, address: u64, comparison: u32, reference: u64) {
  1937. wait_for(this, address, comparison, reference, false);
  1938. }
  1939. extern "system" fn wait_value64(this: This, address: u64, comparison: u32, reference: u64) {
  1940. wait_for(this, address, comparison, reference, true);
  1941. }
  1942. /// The enhanced barriers `(group count, groups)`: buffer, texture and
  1943. /// global barriers with layouts instead of states. Every host use of a
  1944. /// title texture (clears, copies) moves its host copy to the state it needs
  1945. /// first, so only their ordering matters: one barrier on every shader
  1946. /// write (the title's buffer barriers order compute passes).
  1947. extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) {
  1948. // Diagnostics: counted, and left out under `VICTORY_BARRIER_TEST=groups`.
  1949. #[cfg(all(windows, feature = "diagnostics"))]
  1950. if count > 0 {
  1951. crate::copystat::add(crate::copystat::C::WaitsForGroups, 1);
  1952. if crate::copystat::barrier_test() & 1 != 0 {
  1953. return;
  1954. }
  1955. }
  1956. #[cfg(windows)]
  1957. if count > 0
  1958. && let Some(list) = host_list(this)
  1959. {
  1960. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
  1961. with_state(this, |_, state| state.synced());
  1962. // SAFETY: the same layout; no resource named.
  1963. let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) };
  1964. // SAFETY: an open list.
  1965. unsafe { list.list.ResourceBarrier(&[barrier]) };
  1966. }
  1967. #[cfg(not(windows))]
  1968. let _ = (this, count);
  1969. }
  1970. /// The bottom-of-pipe value writes `(address, value, flush, flags)`, 32 and
  1971. /// 64 bits: done when the list has run, as the GPU would. Flag 1 writes the
  1972. /// GPU timestamp instead (64-bit form), flag 2 the system timestamp.
  1973. extern "system" fn write32(this: This, address: u64, value: u32, _flush: u32, _flags: u32) {
  1974. defer_write(this, address, Written::Value(u64::from(value)), 4);
  1975. value_written(this, address, u64::from(value));
  1976. }
  1977. extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, flags: u32) {
  1978. const GPU_TIMESTAMP: u32 = 1;
  1979. const SYSTEM_TIMESTAMP: u32 = 2;
  1980. let what = match flags {
  1981. GPU_TIMESTAMP => Written::GpuTimestamp,
  1982. SYSTEM_TIMESTAMP => Written::SystemTimestamp,
  1983. _ => Written::Value(value),
  1984. };
  1985. defer_write(this, address, what, 8);
  1986. if let Written::Value(value) = what {
  1987. value_written(this, address, value);
  1988. }
  1989. }
  1990. /// The title wrote a value at the bottom of the pipe (not a timestamp, not
  1991. /// a query result): listed (diagnostics), and with `VICTORY_CUT_WRITES=1`
  1992. /// the host list is cut right behind it, so that the value is stored when
  1993. /// the card has run the list up to there, as on the console, and not when
  1994. /// the whole list has run. Lists of other queues wait for these values
  1995. /// (the title: the compute list that builds the depth pyramid
  1996. /// waits for one, and the meshlet culling of the same frame reads that
  1997. /// pyramid). Off by default: every such write then ends a host list, and
  1998. /// each part is a submission of its own.
  1999. fn value_written(this: This, address: u64, value: u64) {
  2000. #[cfg(windows)]
  2001. {
  2002. if address == 0 || this.is_null() {
  2003. return;
  2004. }
  2005. #[cfg(not(feature = "diagnostics"))]
  2006. let _ = value;
  2007. #[cfg(feature = "diagnostics")]
  2008. if let Some(host) = host_list(this) {
  2009. crate::capture::op(std::ptr::from_ref(host) as usize, || {
  2010. format!("WRITE VALUE at {address:#x} value {value:#x}")
  2011. });
  2012. }
  2013. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  2014. if !*ON.get_or_init(|| std::env::var_os("VICTORY_CUT_WRITES").is_some_and(|v| v == "1"))
  2015. || !crate::queue::cuts()
  2016. {
  2017. return;
  2018. }
  2019. // SAFETY: the title passes one of our lists; a list is recorded by
  2020. // one thread at a time and is not submitted while it records.
  2021. let list = unsafe { &mut *this.cast_mut().cast::<List>() };
  2022. let Some(current) = list.host.as_ref() else {
  2023. return;
  2024. };
  2025. let Some(fresh) = fresh_list() else {
  2026. return;
  2027. };
  2028. current.close();
  2029. if let Some(done) = list.host.replace(fresh) {
  2030. // The part so far keeps its waits; nothing stands before the
  2031. // next one but this part itself.
  2032. let waits = std::mem::take(&mut list.gate);
  2033. list.earlier.push(Part { waits, host: done });
  2034. }
  2035. if let Some(host) = list.host.as_ref() {
  2036. list.state
  2037. .lock()
  2038. .unwrap_or_else(|e| e.into_inner())
  2039. .replay(host);
  2040. }
  2041. }
  2042. #[cfg(not(windows))]
  2043. let _ = (this, address, value);
  2044. }
  2045. fn defer_write(this: This, address: u64, what: Written, bytes: usize) {
  2046. if address == 0 {
  2047. return;
  2048. }
  2049. #[cfg(windows)]
  2050. if let Some(list) = host_list(this) {
  2051. list.defer_write(address as *mut u8, what, bytes);
  2052. return;
  2053. }
  2054. let _ = this;
  2055. // Without a host GPU nothing runs later: write now.
  2056. what.write(address as *mut u8, bytes);
  2057. }
  2058. /// The list methods by their slot in older titles' lists (the 2020-era
  2059. /// layout): IUnknown 3, object 4, device child 1, list 1, graphics list 96
  2060. /// (59 as on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3
  2061. /// + 13): 140 slots.
  2062. const METHODS: [(usize, *const ()); 52] = [
  2063. (0, list_query as *const ()),
  2064. (2, list_release as *const ()),
  2065. (7, object::parent_device as *const ()), // 0x38
  2066. (8, list_type as *const ()), // 0x40
  2067. (9, close as *const ()), // 0x48
  2068. (10, reset as *const ()), // 0x50
  2069. (12, state::draw as *const ()), // 0x60 instanced
  2070. (13, state::draw_indexed as *const ()), // 0x68 indexed
  2071. (14, state::dispatch as *const ()), // 0x70
  2072. (15, copy_buffer_region as *const ()), // 0x78
  2073. (16, copy_texture_region as *const ()), // 0x80
  2074. (17, copy_resource as *const ()), // 0x88
  2075. (19, resolve as *const ()), // 0x98
  2076. (20, state::topology as *const ()), // 0xa0
  2077. (21, state::viewports as *const ()), // 0xa8
  2078. (22, state::scissors as *const ()), // 0xb0
  2079. (23, state::blend_factor as *const ()), // 0xb8
  2080. (24, state::stencil_ref as *const ()), // 0xc0
  2081. (25, set_pipeline as *const ()), // 0xc8
  2082. (26, barrier as *const ()), // 0xd0
  2083. (32, state::heaps as *const ()), // 0x100
  2084. (33, ignored_state as *const ()), // 0x108 compute root signature
  2085. (34, ignored_state as *const ()), // 0x110 graphics root signature
  2086. (35, state::compute_table as *const ()), // 0x118
  2087. (36, state::graphics_table as *const ()), // 0x120
  2088. (37, state::compute_constant as *const ()), // 0x128
  2089. (38, state::graphics_constant as *const ()), // 0x130
  2090. (39, state::compute_constants as *const ()), // 0x138
  2091. (40, state::graphics_constants as *const ()), // 0x140
  2092. (41, state::compute_view as *const ()), // 0x148 CBV
  2093. (42, state::graphics_view as *const ()), // 0x150 CBV
  2094. (43, state::compute_view as *const ()), // 0x158 SRV
  2095. (44, state::graphics_view as *const ()), // 0x160 SRV
  2096. (45, state::compute_view as *const ()), // 0x168 UAV
  2097. (46, state::graphics_view as *const ()), // 0x170 UAV
  2098. (47, state::index_buffer as *const ()), // 0x178
  2099. (48, state::vertex_buffers as *const ()), // 0x180
  2100. (50, state::targets as *const ()), // 0x190
  2101. (51, clear_dsv as *const ()), // 0x198
  2102. (52, clear_rtv as *const ()), // 0x1a0
  2103. (59, execute_indirect as *const ()), // 0x1d8 indirect
  2104. (60, copy_memory as *const ()), // 0x1e0
  2105. (68, state::depth_bounds as *const ()), // 0x220 depth bounds
  2106. (69, write32 as *const ()), // 0x228
  2107. (70, write64 as *const ()), // 0x230
  2108. (71, wait_value as *const ()), // 0x238, 32 bits
  2109. (72, wait_value64 as *const ()), // 0x240, 64 bits
  2110. (73, ignored_state as *const ()), // 0x248 pixel shader depth order
  2111. (83, copy_texture_region_x as *const ()), // 0x298
  2112. (84, copy_resource_x as *const ()), // 0x2a0
  2113. (124, ignored_state as *const ()), // 0x3e0 shading rate
  2114. (127, state::dispatch_mesh as *const ()), // 0x3f8 mesh dispatch
  2115. ];
  2116. /// The rest of [`METHODS`], kept apart only to stay readable.
  2117. const MORE_METHODS: [(usize, *const ()); 9] = [
  2118. (28, query_mark as *const ()), // 0xe0 BeginQuery
  2119. (29, query_mark as *const ()), // 0xe8 EndQuery
  2120. (30, resolve_queries as *const ()), // 0xf0
  2121. (78, dispatch_x as *const ()), // 0x270
  2122. (98, state::dispatch_mesh_x as *const ()), // 0x310
  2123. (99, driver_hint as *const ()), // 0x318
  2124. // Pipeline syncs at the top and bottom of the pipe, 0x408 and 0x410.
  2125. (129, sync as *const ()),
  2126. (130, sync as *const ()),
  2127. (137, reset_x as *const ()), // 0x448
  2128. ];
  2129. /// Newer titles' lists have two more methods in the console part of the
  2130. /// base list, after the clears (0x198/0x1a0 as before) and before
  2131. /// ExecuteIndirect, which moved from 0x1d8 to 0x1e8: every slot from 0x1d8
  2132. /// on is two later (taken here as starting exactly at 0x1d8). Inferred from
  2133. /// The title's call shapes: ExecuteIndirect 0x1e8, bottom-of-pipe
  2134. /// writes 0x238/0x240, waits 0x248/0x250, depth bounds 0x230, shading rate
  2135. /// 0x3f0/0x400, syncs 0x418/0x420, ResetX 0x458 (asserts on failure).
  2136. const fn newer_slot(slot: usize) -> usize {
  2137. if slot >= 59 { slot + 2 } else { slot }
  2138. }
  2139. /// Methods only newer titles' lists have. 0x490: the enhanced barrier
  2140. /// `(group count, groups)`, with 16-byte groups `(type, count, barriers)`
  2141. /// and 40-byte buffer barriers (title+0x95e0 builds them). 0x470 `(u64)`,
  2142. /// called from the title's state flush with its result unused.
  2143. /// shortcut: 0x470's purpose is unknown; ignored until a title shows it
  2144. /// matters.
  2145. const NEWER_METHODS: [(usize, *const ()); 3] = [
  2146. (142, ignored_state as *const ()),
  2147. (146, barrier_groups as *const ()),
  2148. (148, allocate_upload as *const ()),
  2149. ];
  2150. const fn list_table(newer: bool) -> [*const (); 160] {
  2151. let mut f = object::d3d12_object(object::missing_table::<LIST, 160>());
  2152. let mut i = 0;
  2153. while i < METHODS.len() + MORE_METHODS.len() {
  2154. let (slot, method) = if i < METHODS.len() {
  2155. METHODS[i]
  2156. } else {
  2157. MORE_METHODS[i - METHODS.len()]
  2158. };
  2159. f[if newer { newer_slot(slot) } else { slot }] = method;
  2160. i += 1;
  2161. }
  2162. let mut i = 0;
  2163. while newer && i < NEWER_METHODS.len() {
  2164. f[NEWER_METHODS[i].0] = NEWER_METHODS[i].1;
  2165. i += 1;
  2166. }
  2167. f
  2168. }
  2169. /// Every slot up to the limit exists and logs, for the methods newer
  2170. /// titles add.
  2171. static LIST_FUNCTIONS: Table<160> = Table(list_table(false));
  2172. static NEWER_LIST_FUNCTIONS: Table<160> = Table(list_table(true));
  2173. #[cfg(test)]
  2174. mod tests {
  2175. use super::*;
  2176. use crate::object::slot;
  2177. #[test]
  2178. fn every_inline_command_falls_back_to_the_table() {
  2179. let null = std::ptr::null();
  2180. let mut allocator = null;
  2181. assert_eq!(
  2182. create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator),
  2183. S_OK
  2184. );
  2185. let mut list = null;
  2186. let hr = create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list);
  2187. assert_eq!(hr, S_OK);
  2188. // What the title's inline draw checks: put < draw limit.
  2189. // SAFETY: the list is 0x560 bytes.
  2190. let (put, draw_limit, api_limit) = unsafe {
  2191. let at = |o: usize| list.cast::<u8>().add(o).cast::<u64>().read();
  2192. (at(0x18), at(0x28), at(0x30))
  2193. };
  2194. assert!(put >= draw_limit && put >= api_limit);
  2195. // The console's ID3D12GraphicsCommandList6, as the title asks.
  2196. let mut same = null;
  2197. assert_eq!(list_query(list, &LIST_IIDS[7], &mut same), S_OK);
  2198. assert_eq!(same, list);
  2199. assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x10)(list), 1);
  2200. assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x40)(list), 0);
  2201. assert_eq!(
  2202. slot::<extern "system" fn(This) -> HRESULT>(list, 0x48)(list),
  2203. S_OK
  2204. );
  2205. // List-owned upload memory: aligned, writable, gone at reset.
  2206. let p = allocate_upload(list, 40, 0x100);
  2207. assert!(!p.is_null() && (p as usize).is_multiple_of(0x100));
  2208. // SAFETY: 40 bytes were handed out.
  2209. unsafe { p.write_bytes(0xab, 40) };
  2210. assert!(allocate_upload(list, 8, 0x30).is_null(), "not a power of two");
  2211. assert_eq!(reset(list, allocator, null), S_OK);
  2212. // SAFETY: the list is ours.
  2213. assert!(unsafe { &(*list.cast::<List>()).uploads }.lock().unwrap().is_empty());
  2214. let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o);
  2215. assert_eq!(release(list), 0);
  2216. assert_eq!(release(allocator), 0);
  2217. }
  2218. /// An offset near `u64::MAX` must not overflow and write outside the
  2219. /// query destination buffer.
  2220. #[test]
  2221. fn resolve_queries_rejects_overflowing_offset() {
  2222. let null = std::ptr::null();
  2223. let mut allocator = null;
  2224. assert_eq!(
  2225. create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator),
  2226. S_OK
  2227. );
  2228. let mut list = null;
  2229. assert_eq!(
  2230. create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list),
  2231. S_OK
  2232. );
  2233. let buffer = crate::resource::test_buffer(64);
  2234. // Used to overflow `offset + count * 8` (panic in debug, wrap in release).
  2235. resolve_queries(list, null, 0, 0, 2, buffer, u64::MAX - 8);
  2236. let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o);
  2237. for object in [buffer, list, allocator] {
  2238. assert_eq!(release(object), 0);
  2239. }
  2240. }
  2241. }