list.rs 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440
  1. //! Command allocators and command lists.
  2. //!
  3. //! The title's inlined code writes packets into a list only while its put
  4. //! pointer is below a limit, and calls the list's method otherwise. Our
  5. //! lists keep the pointer and every limit at zero, so every command reaches
  6. //! the table as a call.
  7. //!
  8. //! Each list records onto a host command list as its methods are called
  9. //! (decision 0007); draw state lives in [`crate::draw`]. Methods not
  10. //! written yet log once with their caller, so a run lists what to do next.
  11. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  12. use std::mem::offset_of;
  13. use crate::object::{
  14. self, ALLOCATOR, E_INVALIDARG, HRESULT, Iid, LIST, Object, S_OK, Table, This, guid,
  15. };
  16. use crate::queue::Written;
  17. use crate::resource::PAGEABLE_IIDS;
  18. const ALLOCATOR_IIDS: [Iid; 4] = [
  19. guid(
  20. 0x6102dee4,
  21. 0xaf59,
  22. 0x4b09,
  23. [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24],
  24. ),
  25. PAGEABLE_IIDS[0],
  26. PAGEABLE_IIDS[1],
  27. PAGEABLE_IIDS[2],
  28. ];
  29. /// The list interfaces up to `ID3D12GraphicsCommandList6` (the table has
  30. /// all their slots): those whose ids are the same as on PC, the console's
  31. /// own List5 and List6 (Grand Theft Auto VI asks for List6), then the
  32. /// device child's.
  33. const LIST_IIDS: [Iid; 10] = [
  34. guid(
  35. 0x7116d91c,
  36. 0xe7e4,
  37. 0x47ce,
  38. [0xb8, 0xc6, 0xec, 0x81, 0x68, 0xf4, 0x37, 0xe5],
  39. ),
  40. guid(
  41. 0x5b160d0f,
  42. 0xac1b,
  43. 0x4185,
  44. [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55],
  45. ),
  46. guid(
  47. 0x553103fb,
  48. 0x1fe7,
  49. 0x4557,
  50. [0xbb, 0x38, 0x94, 0x6d, 0x7d, 0x0e, 0x7c, 0xa7],
  51. ),
  52. guid(
  53. 0x38c3e585,
  54. 0xff17,
  55. 0x412c,
  56. [0x91, 0x50, 0x4f, 0xc6, 0xf9, 0xd7, 0x2a, 0x28],
  57. ),
  58. guid(
  59. 0x6fda83a7,
  60. 0xb84c,
  61. 0x4e38,
  62. [0x9a, 0xc8, 0xc7, 0xbd, 0x22, 0x01, 0x6b, 0x3d],
  63. ),
  64. guid(
  65. 0x8754318e,
  66. 0xd3a9,
  67. 0x4541,
  68. [0x98, 0xcf, 0x64, 0x5b, 0x50, 0xdc, 0x48, 0x74],
  69. ),
  70. guid(
  71. 0x55050859,
  72. 0x4024,
  73. 0x474c,
  74. [0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74],
  75. ),
  76. guid(
  77. 0xc3827890,
  78. 0x4024,
  79. 0x474c,
  80. [0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74],
  81. ),
  82. PAGEABLE_IIDS[1],
  83. PAGEABLE_IIDS[2],
  84. ];
  85. #[repr(C)]
  86. struct Allocator {
  87. object: Object,
  88. kind: u32,
  89. }
  90. /// The layout the title's inlined code reads.
  91. #[repr(C)]
  92. struct List {
  93. object: Object,
  94. kind: u32,
  95. /// The put pointer, then the plain, draw, API and unbiased API limits:
  96. /// all zero, so every inline check fails.
  97. put: [u64; 5],
  98. reserved: [u32; 64],
  99. /// State the inline code keeps for building packets; unused by us.
  100. graphics_root_headers: [u32; 128],
  101. compute_root_headers: [u32; 128],
  102. pipeline_shadow: [u32; 8],
  103. /// Newer titles' lists are larger: Grand Theft Auto VI's state flush
  104. /// (title+0x32786) copies a pipeline's 32 bytes to +0x544..+0x564 and
  105. /// tests +0x548, so its layout runs past 0x560. Its size is unknown;
  106. /// this keeps our fields clear of whatever the title writes there.
  107. newer: [u32; 256],
  108. /// Ours, after the console layout: memory handed out by
  109. /// [`allocate_upload`], kept until the list is reset; the host list the
  110. /// calls record into (decision 0007), and the draw state the title set.
  111. uploads: std::sync::Mutex<Vec<Vec<u8>>>,
  112. #[cfg(windows)]
  113. host: Option<crate::host::HostList>,
  114. #[cfg(windows)]
  115. state: std::sync::Mutex<crate::draw::State>,
  116. }
  117. const _: () = assert!(offset_of!(List, put) == 0x18);
  118. const _: () = assert!(offset_of!(List, pipeline_shadow) + 32 == 0x560);
  119. /// Runs `f` with the host list and draw state of a title list, if there
  120. /// is a host GPU.
  121. #[cfg(windows)]
  122. fn with_state(this: This, f: impl FnOnce(&crate::host::HostList, &mut crate::draw::State)) {
  123. let Some(list) = host_list(this) else { return };
  124. // SAFETY: the title passes one of our lists.
  125. let state = unsafe { &(*this.cast::<List>()).state };
  126. f(list, &mut state.lock().unwrap_or_else(|e| e.into_inner()));
  127. }
  128. /// The host list behind a title list, if there is a host GPU.
  129. #[cfg(windows)]
  130. pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> {
  131. if this.is_null() {
  132. return None;
  133. }
  134. // SAFETY: the title passes one of our lists.
  135. unsafe { (*this.cast::<List>()).host.as_ref() }
  136. }
  137. pub(crate) extern "system" fn create_allocator(
  138. _: This,
  139. kind: u32,
  140. iid: *const Iid,
  141. out: *mut This,
  142. ) -> HRESULT {
  143. let allocator = Box::new(Allocator {
  144. object: Object::new(&ALLOCATOR_FUNCTIONS),
  145. kind,
  146. });
  147. object::hand_out(ALLOCATOR, allocator, iid, &ALLOCATOR_IIDS, out)
  148. }
  149. /// Lists start open, as in D3D12.
  150. pub(crate) extern "system" fn create_list(
  151. _: This,
  152. _nodes: u32,
  153. kind: u32,
  154. allocator: This,
  155. _pipeline: This,
  156. iid: *const Iid,
  157. out: *mut This,
  158. ) -> HRESULT {
  159. new_list(kind, allocator, iid, out)
  160. }
  161. /// The console's list creation: type, flags, node mask and barrier batch
  162. /// size in a description.
  163. #[repr(C)]
  164. #[derive(Debug)]
  165. pub(crate) struct ListDesc {
  166. kind: u32,
  167. flags: u32,
  168. nodes: u32,
  169. barrier_batch: u32,
  170. }
  171. pub(crate) extern "system" fn create_list_x(
  172. _: This,
  173. desc: *const ListDesc,
  174. allocator: This,
  175. _pipeline: This,
  176. iid: *const Iid,
  177. out: *mut This,
  178. ) -> HRESULT {
  179. // SAFETY: the title passes a description (null is tolerated).
  180. let Some(desc) = (unsafe { desc.as_ref() }) else {
  181. return E_INVALIDARG;
  182. };
  183. tracing::debug!(?desc, "console command list");
  184. new_list(desc.kind, allocator, iid, out)
  185. }
  186. fn new_list(kind: u32, allocator: This, iid: *const Iid, out: *mut This) -> HRESULT {
  187. if allocator.is_null() {
  188. return E_INVALIDARG;
  189. }
  190. tracing::debug!(kind, "command list");
  191. let list = Box::new(List {
  192. object: if crate::device::newer() {
  193. Object::new(&NEWER_LIST_FUNCTIONS)
  194. } else {
  195. Object::new(&LIST_FUNCTIONS)
  196. },
  197. kind,
  198. put: [0; 5],
  199. reserved: [0; 64],
  200. graphics_root_headers: [0; 128],
  201. compute_root_headers: [0; 128],
  202. pipeline_shadow: [0; 8],
  203. newer: [0; 256],
  204. uploads: Default::default(),
  205. #[cfg(windows)]
  206. host: crate::host::host().and_then(|h| match h.new_list() {
  207. Ok(list) => Some(list),
  208. Err(e) => {
  209. tracing::warn!(error = %e, "no host command list");
  210. None
  211. }
  212. }),
  213. #[cfg(windows)]
  214. state: Default::default(),
  215. });
  216. object::hand_out(LIST, list, iid, &LIST_IIDS, out)
  217. }
  218. extern "system" fn allocator_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  219. let found = object::is(iid, &ALLOCATOR_IIDS).then_some(this);
  220. object::answer(ALLOCATOR, iid, found, out)
  221. }
  222. extern "system" fn allocator_release(this: This) -> u32 {
  223. object::release_boxed::<Allocator>(this)
  224. }
  225. /// Nothing is recorded, so there is nothing to free.
  226. extern "system" fn allocator_reset(_: This) -> HRESULT {
  227. S_OK
  228. }
  229. extern "system" fn list_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  230. object::answer(LIST, iid, object::is(iid, &LIST_IIDS).then_some(this), out)
  231. }
  232. extern "system" fn list_release(this: This) -> u32 {
  233. object::release_boxed::<List>(this)
  234. }
  235. extern "system" fn list_type(this: This) -> u32 {
  236. // SAFETY: `this` is one of our lists.
  237. unsafe { (*this.cast::<List>()).kind }
  238. }
  239. extern "system" fn close(this: This) -> HRESULT {
  240. #[cfg(windows)]
  241. if let Some(host) = host_list(this) {
  242. host.close();
  243. }
  244. S_OK
  245. }
  246. extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT {
  247. if allocator.is_null() {
  248. return E_INVALIDARG;
  249. }
  250. // Every submission of the list has run (submissions are waited for).
  251. // SAFETY: the title passes one of our lists.
  252. let uploads = unsafe { &(*this.cast::<List>()).uploads };
  253. uploads.lock().unwrap_or_else(|e| e.into_inner()).clear();
  254. #[cfg(windows)]
  255. with_state(this, |host, state| {
  256. host.reset();
  257. state.reset(pipeline);
  258. });
  259. #[cfg(not(windows))]
  260. let _ = (this, pipeline);
  261. S_OK
  262. }
  263. /// A resource barrier as titles pass it: type, flags, then a resource and
  264. /// either a subresource and two states (transition) or a second resource
  265. /// (aliasing). The same layout as the host's.
  266. #[repr(C)]
  267. #[derive(Clone, Copy)]
  268. pub(crate) struct Barrier {
  269. kind: u32,
  270. flags: u32,
  271. first: This,
  272. second: u64,
  273. last: u64,
  274. }
  275. /// The barrier on host resources, or `None` if it names a resource the host
  276. /// GPU does not have (buffers so far).
  277. #[cfg(windows)]
  278. fn host_barrier(list: &crate::host::HostList, b: &Barrier) -> Option<Barrier> {
  279. use windows::core::Interface;
  280. let host = |r: This| crate::resource::host_resource(r).map(|h| h.as_raw().cast_const().cast());
  281. match b.kind {
  282. 0 => {
  283. // A split barrier's first half: its second half transitions.
  284. const BEGIN_ONLY: u32 = 1;
  285. if b.flags & BEGIN_ONLY != 0 {
  286. return None;
  287. }
  288. // shortcut: whole resources, from the state the list tracked
  289. // (`HostList::transition`); subresources are not told apart.
  290. let wanted = crate::host::texture_state(b.last as u32);
  291. let (texture, before) = list.transition(b.first, wanted)?;
  292. Some(Barrier {
  293. kind: 0,
  294. flags: 0,
  295. first: texture.as_raw().cast_const().cast(),
  296. second: 0xffff_ffff | (u64::from(before) << 32),
  297. last: u64::from(crate::host::legal_state(texture, wanted)),
  298. })
  299. }
  300. 1 => Some(Barrier {
  301. first: if b.first.is_null() {
  302. b.first
  303. } else {
  304. host(b.first)?
  305. },
  306. second: if b.second == 0 {
  307. 0
  308. } else {
  309. host(b.second as This)? as u64
  310. },
  311. ..*b
  312. }),
  313. 2 => Some(Barrier {
  314. first: if b.first.is_null() {
  315. b.first
  316. } else {
  317. host(b.first)?
  318. },
  319. ..*b
  320. }),
  321. _ => None,
  322. }
  323. }
  324. /// An unordered access barrier on every resource: earlier shader writes
  325. /// finish before later work reads or writes.
  326. const UAV_BARRIER: Barrier = Barrier {
  327. kind: 2,
  328. flags: 0,
  329. first: std::ptr::null(),
  330. second: 0,
  331. last: 0,
  332. };
  333. /// Returns the console's barrier "actions" (none).
  334. extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> u32 {
  335. #[cfg(windows)]
  336. if let Some(list) = host_list(this)
  337. && !barriers.is_null()
  338. {
  339. // SAFETY: the title passes `count` barriers.
  340. let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) };
  341. let mut host: Vec<Barrier> = barriers
  342. .iter()
  343. .filter_map(|b| host_barrier(list, b))
  344. .collect();
  345. // Buffers have host copies, not resources the barrier can name:
  346. // a barrier on one waits for every shader write before it.
  347. if barriers.iter().any(|b| {
  348. b.kind != 1 && !b.first.is_null() && crate::resource::buffer_bytes(b.first).is_some()
  349. }) {
  350. host.push(UAV_BARRIER);
  351. }
  352. if !host.is_empty() {
  353. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
  354. const _: () = assert!(size_of::<Barrier>() == size_of::<D3D12_RESOURCE_BARRIER>());
  355. // SAFETY: the same layout; borrowed resource pointers, never
  356. // released through this slice.
  357. let host = unsafe {
  358. std::slice::from_raw_parts(
  359. host.as_ptr().cast::<D3D12_RESOURCE_BARRIER>(),
  360. host.len(),
  361. )
  362. };
  363. // SAFETY: an open list and live resources.
  364. unsafe { list.list.ResourceBarrier(host) };
  365. }
  366. }
  367. 0
  368. }
  369. /// Moves a title texture's host copy to `state` in the list, if needed.
  370. #[cfg(windows)]
  371. pub(crate) fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) {
  372. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State;
  373. if let Some((texture, before)) = list.transition(resource, state) {
  374. let state = crate::host::legal_state(texture, state);
  375. let barrier = crate::host::transition(texture, State(before as i32), State(state as i32));
  376. // SAFETY: an open list and a live texture.
  377. unsafe { list.list.ResourceBarrier(&[barrier]) };
  378. }
  379. }
  380. #[cfg(windows)]
  381. const COPY_DEST: u32 = 0x400;
  382. #[cfg(windows)]
  383. const COPY_SOURCE: u32 = 0x800;
  384. /// `len` bytes at `offset` of a title buffer, if they are inside it.
  385. #[cfg(windows)]
  386. fn buffer_range(buffer: This, offset: u64, len: u64) -> Option<*mut u8> {
  387. let (data, size) = crate::resource::buffer_bytes(buffer)?;
  388. let end = offset.checked_add(len)?;
  389. if end > size {
  390. tracing::warn!(offset, len, size, "copy outside its buffer");
  391. return None;
  392. }
  393. // SAFETY: inside the buffer, checked above.
  394. Some(unsafe { data.add(offset as usize) })
  395. }
  396. /// Buffer to buffer: both are host memory, copied at submission.
  397. extern "system" fn copy_buffer_region(
  398. this: This,
  399. dst: This,
  400. dst_offset: u64,
  401. src: This,
  402. src_offset: u64,
  403. len: u64,
  404. ) {
  405. #[cfg(windows)]
  406. if let Some(list) = host_list(this)
  407. && let Some(to) = buffer_range(dst, dst_offset, len)
  408. && let Some(from) = buffer_range(src, src_offset, len)
  409. {
  410. list.defer_copy(to, from, len as usize);
  411. }
  412. #[cfg(not(windows))]
  413. let _ = (this, dst, dst_offset, src, src_offset, len);
  414. }
  415. extern "system" fn copy_resource(this: This, dst: This, src: This) {
  416. #[cfg(windows)]
  417. {
  418. let Some(list) = host_list(this) else {
  419. return;
  420. };
  421. if let (Some(to), Some(from)) = (
  422. crate::resource::host_resource(dst),
  423. crate::resource::host_resource(src),
  424. ) {
  425. if crate::texture::title_written(from) {
  426. crate::texture::upload(list, src, from);
  427. }
  428. ensure_state(list, dst, COPY_DEST);
  429. ensure_state(list, src, COPY_SOURCE);
  430. crate::texture::host_written(dst);
  431. #[cfg(feature = "diagnostics")]
  432. list.note_op(|| format!("copy resource {src:?} to {dst:?}"));
  433. // SAFETY: an open list and live textures.
  434. unsafe { list.list.CopyResource(to, from) };
  435. } else if let (Some((to, a)), Some((from, b))) = (
  436. crate::resource::buffer_bytes(dst),
  437. crate::resource::buffer_bytes(src),
  438. ) {
  439. list.defer_copy(to, from, a.min(b) as usize);
  440. }
  441. }
  442. #[cfg(not(windows))]
  443. let _ = (this, dst, src);
  444. }
  445. extern "system" fn copy_resource_x(this: This, dst: This, src: This, _flags: u32) {
  446. copy_resource(this, dst, src);
  447. }
  448. /// A copy location as titles pass it, laid out as the host's: a resource,
  449. /// then a subresource index (type 0) or a placed footprint (type 1).
  450. #[repr(C)]
  451. #[derive(Clone, Copy)]
  452. pub(crate) struct CopyLocation {
  453. resource: This,
  454. kind: u32,
  455. footprint: crate::resource::PlacedFootprint,
  456. }
  457. /// Texture to texture on the GPU; buffer to texture through an upload
  458. /// buffer filled at submission. Texture to buffer (read back) is not done
  459. /// yet.
  460. extern "system" fn copy_texture_region(
  461. this: This,
  462. dst: *const CopyLocation,
  463. x: u32,
  464. y: u32,
  465. z: u32,
  466. src: *const CopyLocation,
  467. source_box: *const [u32; 6],
  468. ) {
  469. #[cfg(windows)]
  470. {
  471. use windows::Win32::Graphics::Direct3D12::{D3D12_BOX, D3D12_TEXTURE_COPY_LOCATION};
  472. use windows::core::Interface;
  473. const FOOTPRINT: u32 = 1;
  474. // SAFETY: the title passes both locations (null is tolerated).
  475. let (Some(list), Some(&dst), Some(&src)) =
  476. (host_list(this), unsafe { dst.as_ref() }, unsafe {
  477. src.as_ref()
  478. })
  479. else {
  480. return;
  481. };
  482. let Some(to) = crate::resource::host_resource(dst.resource) else {
  483. static ONCE: std::sync::Once = std::sync::Once::new();
  484. ONCE.call_once(|| tracing::warn!("texture to buffer copies not implemented"));
  485. return;
  486. };
  487. let mut from = src;
  488. let _upload; // keeps the source alive while this call records it
  489. #[cfg(feature = "diagnostics")]
  490. let mut read = None;
  491. if src.kind == FOOTPRINT {
  492. let (Some(host), Some(bytes)) = (crate::host::host(), src.footprint.bytes()) else {
  493. return;
  494. };
  495. let Some(data) = buffer_range(src.resource, src.footprint.offset, bytes) else {
  496. return;
  497. };
  498. let Some((buffer, staging)) = list.upload(host, bytes) else {
  499. return;
  500. };
  501. list.defer_copy(staging, data, bytes as usize);
  502. from.resource = buffer.as_raw().cast_const().cast();
  503. from.footprint.offset = 0;
  504. #[cfg(feature = "diagnostics")]
  505. {
  506. // SAFETY: a live buffer.
  507. read = Some((unsafe { buffer.GetGPUVirtualAddress() }, bytes));
  508. }
  509. _upload = buffer;
  510. } else {
  511. let Some(texture) = crate::resource::host_resource(src.resource) else {
  512. return;
  513. };
  514. ensure_state(list, src.resource, COPY_SOURCE);
  515. from.resource = texture.as_raw().cast_const().cast();
  516. }
  517. ensure_state(list, dst.resource, COPY_DEST);
  518. crate::texture::host_written(dst.resource);
  519. let mut to_location = dst;
  520. to_location.resource = to.as_raw().cast_const().cast();
  521. let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>());
  522. #[cfg(feature = "diagnostics")]
  523. {
  524. let text = || {
  525. // SAFETY: a live texture; the box is the title's or null.
  526. let (d, b) = unsafe { (to.GetDesc(), host_box.map(|b| *b)) };
  527. format!(
  528. "copy to {:?} {}x{} f{} sub/kind {} at {x},{y},{z} from {:?} kind {} footprint {:?} box {b:?}",
  529. dst.resource,
  530. d.Width,
  531. d.Height,
  532. d.Format.0,
  533. dst.kind,
  534. src.resource,
  535. src.kind,
  536. (src.kind == FOOTPRINT).then_some(src.footprint)
  537. )
  538. };
  539. match read {
  540. Some(range) => list.note_read(text, range),
  541. None => list.note_op(text),
  542. }
  543. }
  544. const _: () =
  545. assert!(size_of::<CopyLocation>() == size_of::<D3D12_TEXTURE_COPY_LOCATION>());
  546. // SAFETY: an open list; both locations in the host's layout, naming
  547. // live resources; the box is the title's (same layout).
  548. unsafe {
  549. list.list.CopyTextureRegion(
  550. (&raw const to_location).cast(),
  551. x,
  552. y,
  553. z,
  554. (&raw const from).cast(),
  555. host_box,
  556. )
  557. };
  558. }
  559. #[cfg(not(windows))]
  560. let _ = (this, dst, x, y, z, src, source_box);
  561. }
  562. #[allow(clippy::too_many_arguments)] // the method's own arguments
  563. extern "system" fn copy_texture_region_x(
  564. this: This,
  565. dst: *const CopyLocation,
  566. x: u32,
  567. y: u32,
  568. z: u32,
  569. src: *const CopyLocation,
  570. source_box: *const [u32; 6],
  571. _flags: u32,
  572. ) {
  573. copy_texture_region(this, dst, x, y, z, src, source_box);
  574. }
  575. extern "system" fn resolve(
  576. this: This,
  577. dst: This,
  578. dst_sub: u32,
  579. src: This,
  580. src_sub: u32,
  581. format: u32,
  582. ) {
  583. #[cfg(windows)]
  584. if let Some(list) = host_list(this)
  585. && let (Some(to), Some(from)) = (
  586. crate::resource::host_resource(dst),
  587. crate::resource::host_resource(src),
  588. )
  589. {
  590. use windows::Win32::Foundation::RECT;
  591. use windows::Win32::Graphics::Direct3D12::{
  592. D3D12_RESOLVE_MODE_AVERAGE, ID3D12GraphicsCommandList1,
  593. };
  594. use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
  595. use windows::core::Interface;
  596. const RESOLVE_DEST: u32 = 0x1000;
  597. const RESOLVE_SOURCE: u32 = 0x2000;
  598. ensure_state(list, dst, RESOLVE_DEST);
  599. ensure_state(list, src, RESOLVE_SOURCE);
  600. crate::texture::host_written(dst);
  601. #[cfg(feature = "diagnostics")]
  602. list.note_op(|| format!("resolve {src:?} to {dst:?} format {format}"));
  603. // SAFETY: an open list and live textures; the region is inside both.
  604. unsafe {
  605. let (a, b) = (to.GetDesc(), from.GetDesc());
  606. let format = DXGI_FORMAT(format as i32);
  607. if (a.Width, a.Height) == (b.Width, b.Height) {
  608. list.list
  609. .ResolveSubresource(to, dst_sub, from, src_sub, format);
  610. } else if let Ok(list1) = list.list.cast::<ID3D12GraphicsCommandList1>() {
  611. // The console clips a larger source to the destination.
  612. let rect = RECT {
  613. left: 0,
  614. top: 0,
  615. right: a.Width.min(b.Width) as i32,
  616. bottom: a.Height.min(b.Height) as i32,
  617. };
  618. list1.ResolveSubresourceRegion(
  619. to,
  620. dst_sub,
  621. 0,
  622. 0,
  623. from,
  624. src_sub,
  625. Some(&rect),
  626. format,
  627. D3D12_RESOLVE_MODE_AVERAGE,
  628. );
  629. }
  630. }
  631. }
  632. #[cfg(not(windows))]
  633. let _ = (this, dst, dst_sub, src, src_sub, format);
  634. }
  635. #[repr(C)]
  636. pub(crate) struct Rect {
  637. left: i32,
  638. top: i32,
  639. right: i32,
  640. bottom: i32,
  641. }
  642. extern "system" fn clear_rtv(
  643. this: This,
  644. handle: u64,
  645. color: *const [f32; 4],
  646. count: u32,
  647. rects: *const Rect,
  648. ) {
  649. #[cfg(windows)]
  650. {
  651. let (Some(list), Some(record)) = (host_list(this), crate::descriptor::rtv_record(handle))
  652. else {
  653. return;
  654. };
  655. let (Some(texture), Some(host)) = (
  656. crate::resource::host_resource(record.resource),
  657. crate::host::host(),
  658. ) else {
  659. return;
  660. };
  661. // SAFETY: the title passes four floats (null is tolerated).
  662. let Some(color) = (unsafe { color.as_ref() }) else {
  663. return;
  664. };
  665. let rects = (count > 0 && !rects.is_null()).then(|| {
  666. // SAFETY: the title passes `count` rectangles, laid out as the host's.
  667. unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) }
  668. });
  669. const RENDER_TARGET: u32 = 0x4;
  670. let rtv = host.rtv(texture, record.desc().as_ref());
  671. // SAFETY: an open list, a fresh view of a live texture.
  672. unsafe {
  673. if let Some((_, before)) = list.transition(record.resource, RENDER_TARGET) {
  674. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State;
  675. list.list.ResourceBarrier(&[crate::host::transition(
  676. texture,
  677. State(before as i32),
  678. State(RENDER_TARGET as i32),
  679. )]);
  680. }
  681. list.list.ClearRenderTargetView(rtv, color, rects);
  682. }
  683. }
  684. #[cfg(not(windows))]
  685. let _ = (this, handle, color, count, rects);
  686. }
  687. /// `ClearDepthStencilView(handle, flags, depth, stencil, count, rects)`;
  688. /// flags: 1 depth, 2 stencil.
  689. extern "system" fn clear_dsv(
  690. this: This,
  691. handle: u64,
  692. flags: u32,
  693. depth: f32,
  694. stencil: u8,
  695. count: u32,
  696. rects: *const Rect,
  697. ) {
  698. #[cfg(windows)]
  699. {
  700. use windows::Win32::Graphics::Direct3D12::D3D12_CLEAR_FLAGS;
  701. let (Some(list), Some(record)) = (host_list(this), crate::descriptor::dsv_record(handle))
  702. else {
  703. return;
  704. };
  705. let (Some(texture), Some(host)) = (
  706. crate::resource::host_resource(record.resource),
  707. crate::host::host(),
  708. ) else {
  709. return;
  710. };
  711. let rects = (count > 0 && !rects.is_null()).then(|| {
  712. // SAFETY: the title passes `count` rectangles, laid out as the host's.
  713. unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) }
  714. });
  715. const DEPTH_WRITE: u32 = 0x10;
  716. ensure_state(list, record.resource, DEPTH_WRITE);
  717. let dsv = host.dsv(texture, record.depth_desc().as_ref());
  718. // SAFETY: an open list, a fresh view of a live texture.
  719. unsafe {
  720. list.list
  721. .ClearDepthStencilView(dsv, D3D12_CLEAR_FLAGS(flags as i32 & 3), depth, stencil, rects)
  722. };
  723. }
  724. #[cfg(not(windows))]
  725. let _ = (this, handle, flags, depth, stencil, count, rects);
  726. }
  727. /// `CopyMemoryToMemoryX(destination, source, size, flags)`: GPU addresses
  728. /// are title memory, copied at submission like buffer copies (if mapped).
  729. extern "system" fn copy_memory(this: This, dst: u64, src: u64, len: u64, _flags: u32) {
  730. #[cfg(windows)]
  731. if let Some(list) = host_list(this)
  732. && dst != 0
  733. && src != 0
  734. {
  735. let len = len as usize;
  736. list.defer(move || {
  737. if crate::texture::committed(src as *const u8, len)
  738. && crate::texture::committed(dst as *const u8, len)
  739. {
  740. // SAFETY: both ranges are committed title memory.
  741. unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len) };
  742. }
  743. });
  744. }
  745. #[cfg(not(windows))]
  746. let _ = (this, dst, src, len);
  747. }
  748. /// `DriverHintX(feature, value)`: no hints for the host.
  749. extern "system" fn driver_hint(_: This, _feature: u64, _value: u64) -> u64 {
  750. 0
  751. }
  752. /// `DispatchX(x, y, z, flags)`: a dispatch with console flags, which the
  753. /// host has no use for (the ray-tracing builder dispatches this way).
  754. extern "system" fn dispatch_x(this: This, x: u32, y: u32, z: u32, _flags: u32) {
  755. #[cfg(windows)]
  756. state::dispatch(this, x, y, z);
  757. #[cfg(not(windows))]
  758. {
  759. let _ = (this, x, y, z);
  760. count_dispatch();
  761. }
  762. }
  763. /// `BeginQuery`/`EndQuery(heap, type, index)`: queries are answered when
  764. /// resolved.
  765. extern "system" fn query_mark(_: This, _heap: This, _kind: u32, _index: u32) {}
  766. /// `ResolveQueryData(heap, type, first, count, buffer, offset)`: writes
  767. /// each query's result into the buffer once the list has run. Timestamps
  768. /// (type 2) are the GPU clock then; occlusion counts (0) say a million
  769. /// samples passed and binary occlusion (1) visible, so nothing is culled
  770. /// by a query.
  771. /// shortcut: no query runs on the host GPU; results are plausible values,
  772. /// not measured ones (time spans come out as the submission's length).
  773. extern "system" fn resolve_queries(
  774. this: This,
  775. _heap: This,
  776. kind: u32,
  777. _first: u32,
  778. count: u32,
  779. buffer: This,
  780. offset: u64,
  781. ) {
  782. const OCCLUSION: u32 = 0;
  783. const BINARY: u32 = 1;
  784. const TIMESTAMP: u32 = 2;
  785. const PIPELINE_STATISTICS: u32 = 3;
  786. let Some((data, size)) = crate::resource::buffer_bytes(buffer) else {
  787. return;
  788. };
  789. let (what, bytes) = match kind {
  790. OCCLUSION => (Written::Value(1 << 20), 8),
  791. BINARY => (Written::Value(1), 8),
  792. TIMESTAMP => (Written::GpuTimestamp, 8),
  793. PIPELINE_STATISTICS => (Written::Value(0), 88),
  794. _ => (Written::Value(0), 16),
  795. };
  796. if offset + u64::from(count) * bytes > size {
  797. return;
  798. }
  799. for i in 0..u64::from(count) {
  800. // Wider results are written as 8-byte pieces.
  801. for piece in 0..bytes / 8 {
  802. // SAFETY: inside the buffer, checked above.
  803. let at = unsafe { data.add((offset + i * bytes + piece * 8) as usize) };
  804. let what = if piece == 0 { what } else { Written::Value(0) };
  805. defer_write(this, at as u64, what, 8);
  806. }
  807. }
  808. }
  809. /// IUnknown 3, object 4, device child 1, allocator 2.
  810. static ALLOCATOR_FUNCTIONS: Table<24> = {
  811. let mut f = object::d3d12_object(object::missing_table::<ALLOCATOR, 24>());
  812. f[0] = allocator_query as *const ();
  813. f[2] = allocator_release as *const ();
  814. f[7] = object::parent_device as *const (); // 0x38
  815. f[8] = allocator_reset as *const (); // 0x40
  816. f[9] = object::ignore as *const (); // 0x48 allocation callback
  817. Table(f)
  818. };
  819. extern "system" fn set_pipeline(this: This, pipeline: This) {
  820. crate::pipeline::bound(pipeline);
  821. #[cfg(windows)]
  822. with_state(this, |_, state| state.set_pipeline(pipeline));
  823. #[cfg(not(windows))]
  824. let _ = this;
  825. }
  826. /// Pipeline syncs: waits for earlier work and cache flushes, at the top or
  827. /// bottom of the pipe `(flags, control, address, size)`. Host lists order
  828. /// their own work and every submission is waited for, so there is nothing
  829. /// to do.
  830. extern "system" fn sync(_: This, _flags: u32, _control: u32, _address: u64, _size: u64) {}
  831. /// Reset with console flags `(allocator, pipeline, flags)`; the flags only
  832. /// tune the console's command memory.
  833. extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: u32) -> HRESULT {
  834. reset(this, allocator, pipeline)
  835. }
  836. /// Newer lists' 0x4a0 `(size, alignment) -> pointer`: memory the list
  837. /// owns until it is reset, which the CPU writes and the GPU reads at the
  838. /// same address; null on failure. Grand Theft Auto VI's BVH builder puts
  839. /// its instance descriptions there (and wrote through our old
  840. /// `E_NOTIMPL` as a pointer).
  841. extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mut u8 {
  842. let align = usize::try_from(alignment).unwrap_or(0).max(16);
  843. let Some(len) = usize::try_from(size).ok().and_then(|s| s.checked_add(align)) else {
  844. return std::ptr::null_mut();
  845. };
  846. if this.is_null() || !align.is_power_of_two() {
  847. return std::ptr::null_mut();
  848. }
  849. let mut block = vec![0u8; len];
  850. let start = block.as_mut_ptr();
  851. // SAFETY: the offset is below `align`, so `size` bytes fit after it.
  852. let at = unsafe { start.add(start.align_offset(align)) };
  853. // SAFETY: the title passes one of our lists.
  854. let uploads = unsafe { &(*this.cast::<List>()).uploads };
  855. // Moving the vector keeps its heap block where it is.
  856. uploads.lock().unwrap_or_else(|e| e.into_inner()).push(block);
  857. at
  858. }
  859. /// Draw state the host has no use for (root signatures: ours come with
  860. /// the pipeline; depth bounds, depth order and shading rate hints): any
  861. /// arguments, nothing returned.
  862. extern "system" fn ignored_state(_: This) {}
  863. /// The title's draw state (decision 0007, step 3), kept for its draws or
  864. /// set on the host list at once. Without a host GPU these do nothing.
  865. #[cfg(windows)]
  866. mod state {
  867. use super::{This, host_list, with_state};
  868. use crate::draw::{IndexView, VertexView};
  869. use windows::Win32::Foundation::RECT;
  870. use windows::Win32::Graphics::Direct3D12::D3D12_VIEWPORT;
  871. /// `count` items at `items`, or none.
  872. fn items<'a, T>(items: *const T, count: u32) -> &'a [T] {
  873. if items.is_null() || count == 0 {
  874. return &[];
  875. }
  876. // SAFETY: the title passes `count` items.
  877. unsafe { std::slice::from_raw_parts(items, count as usize) }
  878. }
  879. pub(super) extern "system" fn topology(this: This, topology: u32) {
  880. with_state(this, |list, s| s.set_topology(list, topology));
  881. }
  882. pub(super) extern "system" fn viewports(
  883. this: This,
  884. count: u32,
  885. viewports: *const D3D12_VIEWPORT,
  886. ) {
  887. if let Some(list) = host_list(this) {
  888. crate::draw::viewports(list, items(viewports, count));
  889. }
  890. }
  891. pub(super) extern "system" fn scissors(this: This, count: u32, rects: *const RECT) {
  892. if let Some(list) = host_list(this) {
  893. crate::draw::scissors(list, items(rects, count));
  894. }
  895. }
  896. pub(super) extern "system" fn blend_factor(this: This, factor: *const [f32; 4]) {
  897. if let Some(list) = host_list(this) {
  898. // SAFETY: the title passes four floats or null.
  899. crate::draw::blend_factor(list, unsafe { factor.as_ref() });
  900. }
  901. }
  902. pub(super) extern "system" fn stencil_ref(this: This, reference: u32) {
  903. if let Some(list) = host_list(this) {
  904. crate::draw::stencil_ref(list, reference);
  905. }
  906. }
  907. pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) {
  908. with_state(this, |_, s| s.set_heaps(items(heaps, count)));
  909. }
  910. pub(super) extern "system" fn compute_table(this: This, slot: u32, handle: u64) {
  911. with_state(this, |_, s| s.set_table(true, slot, handle));
  912. }
  913. pub(super) extern "system" fn graphics_table(this: This, slot: u32, handle: u64) {
  914. with_state(this, |_, s| s.set_table(false, slot, handle));
  915. }
  916. pub(super) extern "system" fn compute_constant(this: This, slot: u32, value: u32, offset: u32) {
  917. with_state(this, |_, s| s.set_constants(true, slot, &[value], offset));
  918. }
  919. pub(super) extern "system" fn graphics_constant(
  920. this: This,
  921. slot: u32,
  922. value: u32,
  923. offset: u32,
  924. ) {
  925. with_state(this, |_, s| s.set_constants(false, slot, &[value], offset));
  926. }
  927. pub(super) extern "system" fn compute_constants(
  928. this: This,
  929. slot: u32,
  930. count: u32,
  931. values: *const u32,
  932. offset: u32,
  933. ) {
  934. with_state(this, |_, s| {
  935. s.set_constants(true, slot, items(values, count), offset)
  936. });
  937. }
  938. pub(super) extern "system" fn graphics_constants(
  939. this: This,
  940. slot: u32,
  941. count: u32,
  942. values: *const u32,
  943. offset: u32,
  944. ) {
  945. with_state(this, |_, s| {
  946. s.set_constants(false, slot, items(values, count), offset)
  947. });
  948. }
  949. /// Root constant buffer, shader resource and unordered access views.
  950. pub(super) extern "system" fn compute_view(this: This, slot: u32, address: u64) {
  951. with_state(this, |_, s| s.set_view(true, slot, address));
  952. }
  953. pub(super) extern "system" fn graphics_view(this: This, slot: u32, address: u64) {
  954. with_state(this, |_, s| s.set_view(false, slot, address));
  955. }
  956. pub(super) extern "system" fn index_buffer(this: This, view: *const IndexView) {
  957. // SAFETY: the title passes a view or null.
  958. with_state(this, |_, s| s.set_index_buffer(unsafe { view.as_ref() }));
  959. }
  960. pub(super) extern "system" fn vertex_buffers(
  961. this: This,
  962. start: u32,
  963. count: u32,
  964. views: *const VertexView,
  965. ) {
  966. with_state(this, |_, s| {
  967. s.set_vertex_buffers(start, items(views, count))
  968. });
  969. }
  970. /// `(count, handles, one range, depth)`: with one range, the handles
  971. /// follow the first at the render target view size (128 bytes).
  972. pub(super) extern "system" fn targets(
  973. this: This,
  974. count: u32,
  975. handles: *const u64,
  976. one_range: i32,
  977. depth: *const u64,
  978. ) {
  979. let handles: Vec<u64> = if one_range != 0 && !handles.is_null() {
  980. // SAFETY: the title passes the first handle.
  981. let first = unsafe { *handles };
  982. (0..u64::from(count)).map(|i| first + 128 * i).collect()
  983. } else {
  984. items(handles, count).to_vec()
  985. };
  986. // SAFETY: the title passes a handle or null.
  987. let depth = unsafe { depth.as_ref() }.copied().unwrap_or(0);
  988. with_state(this, |list, s| s.set_targets(list, &handles, depth));
  989. }
  990. pub(super) extern "system" fn draw(
  991. this: This,
  992. vertices: u32,
  993. instances: u32,
  994. first: u32,
  995. first_instance: u32,
  996. ) {
  997. super::count_draw();
  998. with_state(this, |list, s| {
  999. s.draw(list, vertices, instances, first, first_instance)
  1000. });
  1001. }
  1002. pub(super) extern "system" fn dispatch(this: This, x: u32, y: u32, z: u32) {
  1003. super::count_dispatch();
  1004. with_state(this, |list, s| s.dispatch(list, x, y, z));
  1005. }
  1006. /// `DispatchMesh(x, y, z)` (the PC method of List6); the title's mesh
  1007. /// programs take `x` groups only.
  1008. pub(super) extern "system" fn dispatch_mesh(this: This, x: u32, y: u32, z: u32) {
  1009. super::count_draw();
  1010. if y * z != 1 {
  1011. static ONCE: std::sync::Once = std::sync::Once::new();
  1012. ONCE.call_once(|| tracing::warn!(x, y, z, "a mesh dispatch with y or z groups"));
  1013. }
  1014. with_state(this, |list, s| s.dispatch_mesh(list, x));
  1015. }
  1016. /// `DispatchMeshX(x, flags, indirect arguments, payload)`.
  1017. /// shortcut: dispatches whose group count is in GPU memory (indirect)
  1018. /// are dropped; make them ExecuteIndirect when the title uses them.
  1019. pub(super) extern "system" fn dispatch_mesh_x(
  1020. this: This,
  1021. x: u32,
  1022. _flags: u64,
  1023. indirect: u64,
  1024. _payload: u64,
  1025. ) {
  1026. super::count_draw();
  1027. if indirect != 0 {
  1028. static ONCE: std::sync::Once = std::sync::Once::new();
  1029. ONCE.call_once(|| tracing::warn!("indirect mesh dispatches dropped"));
  1030. return;
  1031. }
  1032. with_state(this, |list, s| s.dispatch_mesh(list, x));
  1033. }
  1034. pub(super) extern "system" fn draw_indexed(
  1035. this: This,
  1036. indices: u32,
  1037. instances: u32,
  1038. first: u32,
  1039. base: i32,
  1040. first_instance: u32,
  1041. ) {
  1042. super::count_draw();
  1043. with_state(this, |list, s| {
  1044. s.draw_indexed(list, indices, instances, first, base, first_instance)
  1045. });
  1046. }
  1047. }
  1048. /// Without a host GPU every draw state call is ignored.
  1049. #[cfg(not(windows))]
  1050. mod state {
  1051. pub(super) use super::dispatch;
  1052. pub(super) use super::draw;
  1053. pub(super) use super::draw as draw_indexed;
  1054. pub(super) use super::draw as dispatch_mesh;
  1055. pub(super) use super::draw as dispatch_mesh_x;
  1056. pub(super) use super::ignored_state as blend_factor;
  1057. pub(super) use super::ignored_state as compute_constant;
  1058. pub(super) use super::ignored_state as compute_constants;
  1059. pub(super) use super::ignored_state as compute_table;
  1060. pub(super) use super::ignored_state as compute_view;
  1061. pub(super) use super::ignored_state as graphics_constant;
  1062. pub(super) use super::ignored_state as graphics_constants;
  1063. pub(super) use super::ignored_state as graphics_table;
  1064. pub(super) use super::ignored_state as graphics_view;
  1065. pub(super) use super::ignored_state as heaps;
  1066. pub(super) use super::ignored_state as index_buffer;
  1067. pub(super) use super::ignored_state as scissors;
  1068. pub(super) use super::ignored_state as stencil_ref;
  1069. pub(super) use super::ignored_state as targets;
  1070. pub(super) use super::ignored_state as topology;
  1071. pub(super) use super::ignored_state as vertex_buffers;
  1072. pub(super) use super::ignored_state as viewports;
  1073. }
  1074. fn count_draw() {
  1075. DRAWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1076. }
  1077. /// Draws of the kinds the host does not run yet (indirect, mesh), and
  1078. /// dispatches, counted per frame for the log.
  1079. /// shortcut: dropped until their shaders translate (decision 0007).
  1080. #[cfg(not(windows))]
  1081. extern "system" fn draw(_: This) {
  1082. count_draw();
  1083. }
  1084. /// `ExecuteIndirect(signature, max count, arguments, offset, count buffer,
  1085. /// offset)`. Grand Theft Auto VI's signatures (title+0x2479466, 2026-11-24)
  1086. /// hold one argument each: draw (stride 16), indexed draw (20), dispatch
  1087. /// (12), mesh dispatch (12), and the console's single-pass dispatch, type
  1088. /// 105 (stride 12: the three group counts; its flags live in the
  1089. /// signature, the title passes none), run as a plain dispatch. They run
  1090. /// through the host's indirect execution (`State::execute_indirect`).
  1091. /// shortcut: signatures that change root arguments are dropped (logged
  1092. /// once per signature).
  1093. extern "system" fn execute_indirect(
  1094. this: This,
  1095. signature: This,
  1096. max: u32,
  1097. arguments: This,
  1098. offset: u64,
  1099. count: This,
  1100. count_offset: u64,
  1101. ) {
  1102. count_draw();
  1103. let Some((stride, args)) = crate::signature::layout(signature) else {
  1104. return;
  1105. };
  1106. let address = crate::resource::buffer_bytes(arguments).map(|(p, _)| p as u64 + offset);
  1107. let counter = crate::resource::buffer_bytes(count).map(|(p, _)| p as u64 + count_offset);
  1108. let mut ran = false;
  1109. #[cfg(windows)]
  1110. if let ([[kind, ..]], Some(address)) = (args, address)
  1111. && (count.is_null() || counter.is_some())
  1112. {
  1113. const DISPATCH: u32 = 2;
  1114. const DISPATCH_SINGLE: u32 = 105;
  1115. let kind = if *kind == DISPATCH_SINGLE { DISPATCH } else { *kind };
  1116. with_state(this, |list, s| {
  1117. ran = s.execute_indirect(list, (kind, stride, max), address, counter);
  1118. });
  1119. } else {
  1120. #[cfg(all(windows, feature = "diagnostics"))]
  1121. crate::pipeline::note_why(format!(
  1122. "indirect signature {args:?}: arguments in a buffer {}, count in a buffer {}",
  1123. address.is_some(),
  1124. count.is_null() || counter.is_some()
  1125. ));
  1126. }
  1127. if ran {
  1128. return;
  1129. }
  1130. INDIRECT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1131. static SEEN: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
  1132. let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
  1133. if !seen.contains(&(signature as usize)) {
  1134. seen.push(signature as usize);
  1135. tracing::info!(
  1136. stride,
  1137. ?args,
  1138. max,
  1139. address = ?address.map(|a| format!("{a:#x}")),
  1140. counted = !count.is_null(),
  1141. "indirect execution dropped (first time for this signature)"
  1142. );
  1143. }
  1144. }
  1145. /// Indirect executions dropped since the last call.
  1146. pub(crate) fn take_indirect() -> u64 {
  1147. INDIRECT.swap(0, std::sync::atomic::Ordering::Relaxed)
  1148. }
  1149. static INDIRECT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1150. fn count_dispatch() {
  1151. DISPATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1152. }
  1153. #[cfg(not(windows))]
  1154. extern "system" fn dispatch(_: This) {
  1155. count_dispatch();
  1156. }
  1157. static DRAWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1158. static DISPATCHES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1159. /// Draws (any kind, mesh and indirect included) and compute dispatches
  1160. /// recorded since the last call.
  1161. pub(crate) fn take_counts() -> (u64, u64) {
  1162. use std::sync::atomic::Ordering::Relaxed;
  1163. (DRAWS.swap(0, Relaxed), DISPATCHES.swap(0, Relaxed))
  1164. }
  1165. /// A GPU wait for a memory value `(address, comparison, reference, ...)`.
  1166. /// Lists run one after another and to completion, so a value another queue
  1167. /// or the CPU has to write first cannot be waited for; nothing to do.
  1168. extern "system" fn wait_value(_: This, _address: u64, _comparison: u32, _reference: u64) {}
  1169. /// The enhanced barriers `(group count, groups)`: buffer, texture and
  1170. /// global barriers with layouts instead of states. Every host use of a
  1171. /// title texture (clears, copies) moves its host copy to the state it needs
  1172. /// first, so only their ordering matters: one barrier on every shader
  1173. /// write (the title's buffer barriers order compute passes).
  1174. extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) {
  1175. #[cfg(windows)]
  1176. if count > 0
  1177. && let Some(list) = host_list(this)
  1178. {
  1179. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
  1180. // SAFETY: the same layout; no resource named.
  1181. let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) };
  1182. // SAFETY: an open list.
  1183. unsafe { list.list.ResourceBarrier(&[barrier]) };
  1184. }
  1185. #[cfg(not(windows))]
  1186. let _ = (this, count);
  1187. }
  1188. /// The bottom-of-pipe value writes `(address, value, flush, flags)`, 32 and
  1189. /// 64 bits: done when the list has run, as the GPU would. Flag 1 writes the
  1190. /// GPU timestamp instead (64-bit form), flag 2 the system timestamp.
  1191. extern "system" fn write32(this: This, address: u64, value: u32, _flush: u32, _flags: u32) {
  1192. defer_write(this, address, Written::Value(u64::from(value)), 4);
  1193. }
  1194. extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, flags: u32) {
  1195. const GPU_TIMESTAMP: u32 = 1;
  1196. const SYSTEM_TIMESTAMP: u32 = 2;
  1197. let what = match flags {
  1198. GPU_TIMESTAMP => Written::GpuTimestamp,
  1199. SYSTEM_TIMESTAMP => Written::SystemTimestamp,
  1200. _ => Written::Value(value),
  1201. };
  1202. defer_write(this, address, what, 8);
  1203. }
  1204. fn defer_write(this: This, address: u64, what: Written, bytes: usize) {
  1205. if address == 0 {
  1206. return;
  1207. }
  1208. #[cfg(windows)]
  1209. if let Some(list) = host_list(this) {
  1210. list.defer_write(address as *mut u8, what, bytes);
  1211. return;
  1212. }
  1213. let _ = this;
  1214. // Without a host GPU nothing runs later: write now.
  1215. what.write(address as *mut u8, bytes);
  1216. }
  1217. /// The list methods by their slot in older titles' lists (the 2020-era
  1218. /// layout): IUnknown 3, object 4, device child 1, list 1, graphics list 96
  1219. /// (59 as on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3
  1220. /// + 13): 140 slots.
  1221. const METHODS: [(usize, *const ()); 52] = [
  1222. (0, list_query as *const ()),
  1223. (2, list_release as *const ()),
  1224. (7, object::parent_device as *const ()), // 0x38
  1225. (8, list_type as *const ()), // 0x40
  1226. (9, close as *const ()), // 0x48
  1227. (10, reset as *const ()), // 0x50
  1228. (12, state::draw as *const ()), // 0x60 instanced
  1229. (13, state::draw_indexed as *const ()), // 0x68 indexed
  1230. (14, state::dispatch as *const ()), // 0x70
  1231. (15, copy_buffer_region as *const ()), // 0x78
  1232. (16, copy_texture_region as *const ()), // 0x80
  1233. (17, copy_resource as *const ()), // 0x88
  1234. (19, resolve as *const ()), // 0x98
  1235. (20, state::topology as *const ()), // 0xa0
  1236. (21, state::viewports as *const ()), // 0xa8
  1237. (22, state::scissors as *const ()), // 0xb0
  1238. (23, state::blend_factor as *const ()), // 0xb8
  1239. (24, state::stencil_ref as *const ()), // 0xc0
  1240. (25, set_pipeline as *const ()), // 0xc8
  1241. (26, barrier as *const ()), // 0xd0
  1242. (32, state::heaps as *const ()), // 0x100
  1243. (33, ignored_state as *const ()), // 0x108 compute root signature
  1244. (34, ignored_state as *const ()), // 0x110 graphics root signature
  1245. (35, state::compute_table as *const ()), // 0x118
  1246. (36, state::graphics_table as *const ()), // 0x120
  1247. (37, state::compute_constant as *const ()), // 0x128
  1248. (38, state::graphics_constant as *const ()), // 0x130
  1249. (39, state::compute_constants as *const ()), // 0x138
  1250. (40, state::graphics_constants as *const ()), // 0x140
  1251. (41, state::compute_view as *const ()), // 0x148 CBV
  1252. (42, state::graphics_view as *const ()), // 0x150 CBV
  1253. (43, state::compute_view as *const ()), // 0x158 SRV
  1254. (44, state::graphics_view as *const ()), // 0x160 SRV
  1255. (45, state::compute_view as *const ()), // 0x168 UAV
  1256. (46, state::graphics_view as *const ()), // 0x170 UAV
  1257. (47, state::index_buffer as *const ()), // 0x178
  1258. (48, state::vertex_buffers as *const ()), // 0x180
  1259. (50, state::targets as *const ()), // 0x190
  1260. (51, clear_dsv as *const ()), // 0x198
  1261. (52, clear_rtv as *const ()), // 0x1a0
  1262. (59, execute_indirect as *const ()), // 0x1d8 indirect
  1263. (60, copy_memory as *const ()), // 0x1e0
  1264. (68, ignored_state as *const ()), // 0x220 depth bounds
  1265. (69, write32 as *const ()), // 0x228
  1266. (70, write64 as *const ()), // 0x230
  1267. (71, wait_value as *const ()), // 0x238, 32 bits
  1268. (72, wait_value as *const ()), // 0x240, 64 bits
  1269. (73, ignored_state as *const ()), // 0x248 pixel shader depth order
  1270. (83, copy_texture_region_x as *const ()), // 0x298
  1271. (84, copy_resource_x as *const ()), // 0x2a0
  1272. (124, ignored_state as *const ()), // 0x3e0 shading rate
  1273. (127, state::dispatch_mesh as *const ()), // 0x3f8 mesh dispatch
  1274. ];
  1275. /// The rest of [`METHODS`], kept apart only to stay readable.
  1276. const MORE_METHODS: [(usize, *const ()); 9] = [
  1277. (28, query_mark as *const ()), // 0xe0 BeginQuery
  1278. (29, query_mark as *const ()), // 0xe8 EndQuery
  1279. (30, resolve_queries as *const ()), // 0xf0
  1280. (78, dispatch_x as *const ()), // 0x270
  1281. (98, state::dispatch_mesh_x as *const ()), // 0x310
  1282. (99, driver_hint as *const ()), // 0x318
  1283. // Pipeline syncs at the top and bottom of the pipe, 0x408 and 0x410.
  1284. (129, sync as *const ()),
  1285. (130, sync as *const ()),
  1286. (137, reset_x as *const ()), // 0x448
  1287. ];
  1288. /// Newer titles' lists have two more methods in the console part of the
  1289. /// base list, after the clears (0x198/0x1a0 as before) and before
  1290. /// ExecuteIndirect, which moved from 0x1d8 to 0x1e8: every slot from 0x1d8
  1291. /// on is two later (taken here as starting exactly at 0x1d8). Inferred from
  1292. /// Grand Theft Auto VI's call shapes: ExecuteIndirect 0x1e8, bottom-of-pipe
  1293. /// writes 0x238/0x240, waits 0x248/0x250, depth bounds 0x230, shading rate
  1294. /// 0x3f0/0x400, syncs 0x418/0x420, ResetX 0x458 (asserts on failure).
  1295. const fn newer_slot(slot: usize) -> usize {
  1296. if slot >= 59 { slot + 2 } else { slot }
  1297. }
  1298. /// Methods only newer titles' lists have. 0x490: the enhanced barrier
  1299. /// `(group count, groups)`, with 16-byte groups `(type, count, barriers)`
  1300. /// and 40-byte buffer barriers (title+0x95e0 builds them). 0x470 `(u64)`,
  1301. /// called from Grand Theft Auto VI's state flush with its result unused.
  1302. /// shortcut: 0x470's purpose is unknown; ignored until a title shows it
  1303. /// matters.
  1304. const NEWER_METHODS: [(usize, *const ()); 3] = [
  1305. (142, ignored_state as *const ()),
  1306. (146, barrier_groups as *const ()),
  1307. (148, allocate_upload as *const ()),
  1308. ];
  1309. const fn list_table(newer: bool) -> [*const (); 160] {
  1310. let mut f = object::d3d12_object(object::missing_table::<LIST, 160>());
  1311. let mut i = 0;
  1312. while i < METHODS.len() + MORE_METHODS.len() {
  1313. let (slot, method) = if i < METHODS.len() {
  1314. METHODS[i]
  1315. } else {
  1316. MORE_METHODS[i - METHODS.len()]
  1317. };
  1318. f[if newer { newer_slot(slot) } else { slot }] = method;
  1319. i += 1;
  1320. }
  1321. let mut i = 0;
  1322. while newer && i < NEWER_METHODS.len() {
  1323. f[NEWER_METHODS[i].0] = NEWER_METHODS[i].1;
  1324. i += 1;
  1325. }
  1326. f
  1327. }
  1328. /// Every slot up to the limit exists and logs, for the methods newer
  1329. /// titles add.
  1330. static LIST_FUNCTIONS: Table<160> = Table(list_table(false));
  1331. static NEWER_LIST_FUNCTIONS: Table<160> = Table(list_table(true));
  1332. #[cfg(test)]
  1333. mod tests {
  1334. use super::*;
  1335. use crate::object::slot;
  1336. #[test]
  1337. fn every_inline_command_falls_back_to_the_table() {
  1338. let null = std::ptr::null();
  1339. let mut allocator = null;
  1340. assert_eq!(
  1341. create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator),
  1342. S_OK
  1343. );
  1344. let mut list = null;
  1345. let hr = create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list);
  1346. assert_eq!(hr, S_OK);
  1347. // What the title's inline draw checks: put < draw limit.
  1348. // SAFETY: the list is 0x560 bytes.
  1349. let (put, draw_limit, api_limit) = unsafe {
  1350. let at = |o: usize| list.cast::<u8>().add(o).cast::<u64>().read();
  1351. (at(0x18), at(0x28), at(0x30))
  1352. };
  1353. assert!(put >= draw_limit && put >= api_limit);
  1354. // The console's ID3D12GraphicsCommandList6, as Grand Theft Auto VI asks.
  1355. let mut same = null;
  1356. assert_eq!(list_query(list, &LIST_IIDS[7], &mut same), S_OK);
  1357. assert_eq!(same, list);
  1358. assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x10)(list), 1);
  1359. assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x40)(list), 0);
  1360. assert_eq!(
  1361. slot::<extern "system" fn(This) -> HRESULT>(list, 0x48)(list),
  1362. S_OK
  1363. );
  1364. // List-owned upload memory: aligned, writable, gone at reset.
  1365. let p = allocate_upload(list, 40, 0x100);
  1366. assert!(!p.is_null() && (p as usize).is_multiple_of(0x100));
  1367. // SAFETY: 40 bytes were handed out.
  1368. unsafe { p.write_bytes(0xab, 40) };
  1369. assert!(allocate_upload(list, 8, 0x30).is_null(), "not a power of two");
  1370. assert_eq!(reset(list, allocator, null), S_OK);
  1371. // SAFETY: the list is ours.
  1372. assert!(unsafe { &(*list.cast::<List>()).uploads }.lock().unwrap().is_empty());
  1373. let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o);
  1374. assert_eq!(release(list), 0);
  1375. assert_eq!(release(allocator), 0);
  1376. }
  1377. }