2
0

list.rs 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  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. ensure_state(list, dst, COPY_DEST);
  426. ensure_state(list, src, COPY_SOURCE);
  427. crate::texture::host_written(dst);
  428. #[cfg(feature = "diagnostics")]
  429. list.note_op(|| format!("copy resource {src:?} to {dst:?}"));
  430. // SAFETY: an open list and live textures.
  431. unsafe { list.list.CopyResource(to, from) };
  432. } else if let (Some((to, a)), Some((from, b))) = (
  433. crate::resource::buffer_bytes(dst),
  434. crate::resource::buffer_bytes(src),
  435. ) {
  436. list.defer_copy(to, from, a.min(b) as usize);
  437. }
  438. }
  439. #[cfg(not(windows))]
  440. let _ = (this, dst, src);
  441. }
  442. extern "system" fn copy_resource_x(this: This, dst: This, src: This, _flags: u32) {
  443. copy_resource(this, dst, src);
  444. }
  445. /// A copy location as titles pass it, laid out as the host's: a resource,
  446. /// then a subresource index (type 0) or a placed footprint (type 1).
  447. #[repr(C)]
  448. #[derive(Clone, Copy)]
  449. pub(crate) struct CopyLocation {
  450. resource: This,
  451. kind: u32,
  452. footprint: crate::resource::PlacedFootprint,
  453. }
  454. /// Texture to texture on the GPU; buffer to texture through an upload
  455. /// buffer filled at submission. Texture to buffer (read back) is not done
  456. /// yet.
  457. extern "system" fn copy_texture_region(
  458. this: This,
  459. dst: *const CopyLocation,
  460. x: u32,
  461. y: u32,
  462. z: u32,
  463. src: *const CopyLocation,
  464. source_box: *const [u32; 6],
  465. ) {
  466. #[cfg(windows)]
  467. {
  468. use windows::Win32::Graphics::Direct3D12::{D3D12_BOX, D3D12_TEXTURE_COPY_LOCATION};
  469. use windows::core::Interface;
  470. const FOOTPRINT: u32 = 1;
  471. // SAFETY: the title passes both locations (null is tolerated).
  472. let (Some(list), Some(&dst), Some(&src)) =
  473. (host_list(this), unsafe { dst.as_ref() }, unsafe {
  474. src.as_ref()
  475. })
  476. else {
  477. return;
  478. };
  479. let Some(to) = crate::resource::host_resource(dst.resource) else {
  480. static ONCE: std::sync::Once = std::sync::Once::new();
  481. ONCE.call_once(|| tracing::warn!("texture to buffer copies not implemented"));
  482. return;
  483. };
  484. let mut from = src;
  485. let _upload; // keeps the source alive while this call records it
  486. #[cfg(feature = "diagnostics")]
  487. let mut read = None;
  488. if src.kind == FOOTPRINT {
  489. let (Some(host), Some(bytes)) = (crate::host::host(), src.footprint.bytes()) else {
  490. return;
  491. };
  492. let Some(data) = buffer_range(src.resource, src.footprint.offset, bytes) else {
  493. return;
  494. };
  495. let Some((buffer, staging)) = list.upload(host, bytes) else {
  496. return;
  497. };
  498. list.defer_copy(staging, data, bytes as usize);
  499. from.resource = buffer.as_raw().cast_const().cast();
  500. from.footprint.offset = 0;
  501. #[cfg(feature = "diagnostics")]
  502. {
  503. // SAFETY: a live buffer.
  504. read = Some((unsafe { buffer.GetGPUVirtualAddress() }, bytes));
  505. }
  506. _upload = buffer;
  507. } else {
  508. let Some(texture) = crate::resource::host_resource(src.resource) else {
  509. return;
  510. };
  511. ensure_state(list, src.resource, COPY_SOURCE);
  512. from.resource = texture.as_raw().cast_const().cast();
  513. }
  514. ensure_state(list, dst.resource, COPY_DEST);
  515. crate::texture::host_written(dst.resource);
  516. let mut to_location = dst;
  517. to_location.resource = to.as_raw().cast_const().cast();
  518. let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>());
  519. #[cfg(feature = "diagnostics")]
  520. {
  521. let text = || {
  522. // SAFETY: a live texture; the box is the title's or null.
  523. let (d, b) = unsafe { (to.GetDesc(), host_box.map(|b| *b)) };
  524. format!(
  525. "copy to {:?} {}x{} f{} sub/kind {} at {x},{y},{z} from {:?} kind {} footprint {:?} box {b:?}",
  526. dst.resource,
  527. d.Width,
  528. d.Height,
  529. d.Format.0,
  530. dst.kind,
  531. src.resource,
  532. src.kind,
  533. (src.kind == FOOTPRINT).then_some(src.footprint)
  534. )
  535. };
  536. match read {
  537. Some(range) => list.note_read(text, range),
  538. None => list.note_op(text),
  539. }
  540. }
  541. const _: () =
  542. assert!(size_of::<CopyLocation>() == size_of::<D3D12_TEXTURE_COPY_LOCATION>());
  543. // SAFETY: an open list; both locations in the host's layout, naming
  544. // live resources; the box is the title's (same layout).
  545. unsafe {
  546. list.list.CopyTextureRegion(
  547. (&raw const to_location).cast(),
  548. x,
  549. y,
  550. z,
  551. (&raw const from).cast(),
  552. host_box,
  553. )
  554. };
  555. }
  556. #[cfg(not(windows))]
  557. let _ = (this, dst, x, y, z, src, source_box);
  558. }
  559. #[allow(clippy::too_many_arguments)] // the method's own arguments
  560. extern "system" fn copy_texture_region_x(
  561. this: This,
  562. dst: *const CopyLocation,
  563. x: u32,
  564. y: u32,
  565. z: u32,
  566. src: *const CopyLocation,
  567. source_box: *const [u32; 6],
  568. _flags: u32,
  569. ) {
  570. copy_texture_region(this, dst, x, y, z, src, source_box);
  571. }
  572. extern "system" fn resolve(
  573. this: This,
  574. dst: This,
  575. dst_sub: u32,
  576. src: This,
  577. src_sub: u32,
  578. format: u32,
  579. ) {
  580. #[cfg(windows)]
  581. if let Some(list) = host_list(this)
  582. && let (Some(to), Some(from)) = (
  583. crate::resource::host_resource(dst),
  584. crate::resource::host_resource(src),
  585. )
  586. {
  587. use windows::Win32::Foundation::RECT;
  588. use windows::Win32::Graphics::Direct3D12::{
  589. D3D12_RESOLVE_MODE_AVERAGE, ID3D12GraphicsCommandList1,
  590. };
  591. use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
  592. use windows::core::Interface;
  593. const RESOLVE_DEST: u32 = 0x1000;
  594. const RESOLVE_SOURCE: u32 = 0x2000;
  595. ensure_state(list, dst, RESOLVE_DEST);
  596. ensure_state(list, src, RESOLVE_SOURCE);
  597. crate::texture::host_written(dst);
  598. #[cfg(feature = "diagnostics")]
  599. list.note_op(|| format!("resolve {src:?} to {dst:?} format {format}"));
  600. // SAFETY: an open list and live textures; the region is inside both.
  601. unsafe {
  602. let (a, b) = (to.GetDesc(), from.GetDesc());
  603. let format = DXGI_FORMAT(format as i32);
  604. if (a.Width, a.Height) == (b.Width, b.Height) {
  605. list.list
  606. .ResolveSubresource(to, dst_sub, from, src_sub, format);
  607. } else if let Ok(list1) = list.list.cast::<ID3D12GraphicsCommandList1>() {
  608. // The console clips a larger source to the destination.
  609. let rect = RECT {
  610. left: 0,
  611. top: 0,
  612. right: a.Width.min(b.Width) as i32,
  613. bottom: a.Height.min(b.Height) as i32,
  614. };
  615. list1.ResolveSubresourceRegion(
  616. to,
  617. dst_sub,
  618. 0,
  619. 0,
  620. from,
  621. src_sub,
  622. Some(&rect),
  623. format,
  624. D3D12_RESOLVE_MODE_AVERAGE,
  625. );
  626. }
  627. }
  628. }
  629. #[cfg(not(windows))]
  630. let _ = (this, dst, dst_sub, src, src_sub, format);
  631. }
  632. #[repr(C)]
  633. pub(crate) struct Rect {
  634. left: i32,
  635. top: i32,
  636. right: i32,
  637. bottom: i32,
  638. }
  639. extern "system" fn clear_rtv(
  640. this: This,
  641. handle: u64,
  642. color: *const [f32; 4],
  643. count: u32,
  644. rects: *const Rect,
  645. ) {
  646. #[cfg(windows)]
  647. {
  648. let (Some(list), Some(record)) = (host_list(this), crate::descriptor::rtv_record(handle))
  649. else {
  650. return;
  651. };
  652. let (Some(texture), Some(host)) = (
  653. crate::resource::host_resource(record.resource),
  654. crate::host::host(),
  655. ) else {
  656. return;
  657. };
  658. // SAFETY: the title passes four floats (null is tolerated).
  659. let Some(color) = (unsafe { color.as_ref() }) else {
  660. return;
  661. };
  662. let rects = (count > 0 && !rects.is_null()).then(|| {
  663. // SAFETY: the title passes `count` rectangles, laid out as the host's.
  664. unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) }
  665. });
  666. const RENDER_TARGET: u32 = 0x4;
  667. let rtv = host.rtv(texture, record.desc().as_ref());
  668. // SAFETY: an open list, a fresh view of a live texture.
  669. unsafe {
  670. if let Some((_, before)) = list.transition(record.resource, RENDER_TARGET) {
  671. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State;
  672. list.list.ResourceBarrier(&[crate::host::transition(
  673. texture,
  674. State(before as i32),
  675. State(RENDER_TARGET as i32),
  676. )]);
  677. }
  678. list.list.ClearRenderTargetView(rtv, color, rects);
  679. }
  680. }
  681. #[cfg(not(windows))]
  682. let _ = (this, handle, color, count, rects);
  683. }
  684. /// `ClearDepthStencilView(handle, flags, depth, stencil, count, rects)`;
  685. /// flags: 1 depth, 2 stencil.
  686. extern "system" fn clear_dsv(
  687. this: This,
  688. handle: u64,
  689. flags: u32,
  690. depth: f32,
  691. stencil: u8,
  692. count: u32,
  693. rects: *const Rect,
  694. ) {
  695. #[cfg(windows)]
  696. {
  697. use windows::Win32::Graphics::Direct3D12::D3D12_CLEAR_FLAGS;
  698. let (Some(list), Some(record)) = (host_list(this), crate::descriptor::dsv_record(handle))
  699. else {
  700. return;
  701. };
  702. let (Some(texture), Some(host)) = (
  703. crate::resource::host_resource(record.resource),
  704. crate::host::host(),
  705. ) else {
  706. return;
  707. };
  708. let rects = (count > 0 && !rects.is_null()).then(|| {
  709. // SAFETY: the title passes `count` rectangles, laid out as the host's.
  710. unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) }
  711. });
  712. const DEPTH_WRITE: u32 = 0x10;
  713. ensure_state(list, record.resource, DEPTH_WRITE);
  714. let dsv = host.dsv(texture, record.depth_desc().as_ref());
  715. // SAFETY: an open list, a fresh view of a live texture.
  716. unsafe {
  717. list.list
  718. .ClearDepthStencilView(dsv, D3D12_CLEAR_FLAGS(flags as i32 & 3), depth, stencil, rects)
  719. };
  720. }
  721. #[cfg(not(windows))]
  722. let _ = (this, handle, flags, depth, stencil, count, rects);
  723. }
  724. /// `CopyMemoryToMemoryX(destination, source, size, flags)`: GPU addresses
  725. /// are title memory, copied at submission like buffer copies (if mapped).
  726. extern "system" fn copy_memory(this: This, dst: u64, src: u64, len: u64, _flags: u32) {
  727. #[cfg(windows)]
  728. if let Some(list) = host_list(this)
  729. && dst != 0
  730. && src != 0
  731. {
  732. let len = len as usize;
  733. list.defer(move || {
  734. if crate::texture::committed(src as *const u8, len)
  735. && crate::texture::committed(dst as *const u8, len)
  736. {
  737. // SAFETY: both ranges are committed title memory.
  738. unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len) };
  739. }
  740. });
  741. }
  742. #[cfg(not(windows))]
  743. let _ = (this, dst, src, len);
  744. }
  745. /// `DriverHintX(feature, value)`: no hints for the host.
  746. extern "system" fn driver_hint(_: This, _feature: u64, _value: u64) -> u64 {
  747. 0
  748. }
  749. /// `DispatchX(x, y, z, flags)`: a dispatch with console flags, which the
  750. /// host has no use for (the ray-tracing builder dispatches this way).
  751. extern "system" fn dispatch_x(this: This, x: u32, y: u32, z: u32, _flags: u32) {
  752. #[cfg(windows)]
  753. state::dispatch(this, x, y, z);
  754. #[cfg(not(windows))]
  755. {
  756. let _ = (this, x, y, z);
  757. count_dispatch();
  758. }
  759. }
  760. /// `BeginQuery`/`EndQuery(heap, type, index)`: queries are answered when
  761. /// resolved.
  762. extern "system" fn query_mark(_: This, _heap: This, _kind: u32, _index: u32) {}
  763. /// `ResolveQueryData(heap, type, first, count, buffer, offset)`: writes
  764. /// each query's result into the buffer once the list has run. Timestamps
  765. /// (type 2) are the GPU clock then; occlusion counts (0) say a million
  766. /// samples passed and binary occlusion (1) visible, so nothing is culled
  767. /// by a query.
  768. /// shortcut: no query runs on the host GPU; results are plausible values,
  769. /// not measured ones (time spans come out as the submission's length).
  770. extern "system" fn resolve_queries(
  771. this: This,
  772. _heap: This,
  773. kind: u32,
  774. _first: u32,
  775. count: u32,
  776. buffer: This,
  777. offset: u64,
  778. ) {
  779. const OCCLUSION: u32 = 0;
  780. const BINARY: u32 = 1;
  781. const TIMESTAMP: u32 = 2;
  782. const PIPELINE_STATISTICS: u32 = 3;
  783. let Some((data, size)) = crate::resource::buffer_bytes(buffer) else {
  784. return;
  785. };
  786. let (what, bytes) = match kind {
  787. OCCLUSION => (Written::Value(1 << 20), 8),
  788. BINARY => (Written::Value(1), 8),
  789. TIMESTAMP => (Written::GpuTimestamp, 8),
  790. PIPELINE_STATISTICS => (Written::Value(0), 88),
  791. _ => (Written::Value(0), 16),
  792. };
  793. if offset + u64::from(count) * bytes > size {
  794. return;
  795. }
  796. for i in 0..u64::from(count) {
  797. // Wider results are written as 8-byte pieces.
  798. for piece in 0..bytes / 8 {
  799. // SAFETY: inside the buffer, checked above.
  800. let at = unsafe { data.add((offset + i * bytes + piece * 8) as usize) };
  801. let what = if piece == 0 { what } else { Written::Value(0) };
  802. defer_write(this, at as u64, what, 8);
  803. }
  804. }
  805. }
  806. /// IUnknown 3, object 4, device child 1, allocator 2.
  807. static ALLOCATOR_FUNCTIONS: Table<24> = {
  808. let mut f = object::d3d12_object(object::missing_table::<ALLOCATOR, 24>());
  809. f[0] = allocator_query as *const ();
  810. f[2] = allocator_release as *const ();
  811. f[7] = object::parent_device as *const (); // 0x38
  812. f[8] = allocator_reset as *const (); // 0x40
  813. f[9] = object::ignore as *const (); // 0x48 allocation callback
  814. Table(f)
  815. };
  816. extern "system" fn set_pipeline(this: This, pipeline: This) {
  817. crate::pipeline::bound(pipeline);
  818. #[cfg(windows)]
  819. with_state(this, |_, state| state.set_pipeline(pipeline));
  820. #[cfg(not(windows))]
  821. let _ = this;
  822. }
  823. /// Pipeline syncs: waits for earlier work and cache flushes, at the top or
  824. /// bottom of the pipe `(flags, control, address, size)`. Host lists order
  825. /// their own work and every submission is waited for, so there is nothing
  826. /// to do.
  827. extern "system" fn sync(_: This, _flags: u32, _control: u32, _address: u64, _size: u64) {}
  828. /// Reset with console flags `(allocator, pipeline, flags)`; the flags only
  829. /// tune the console's command memory.
  830. extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: u32) -> HRESULT {
  831. reset(this, allocator, pipeline)
  832. }
  833. /// Newer lists' 0x4a0 `(size, alignment) -> pointer`: memory the list
  834. /// owns until it is reset, which the CPU writes and the GPU reads at the
  835. /// same address; null on failure. Grand Theft Auto VI's BVH builder puts
  836. /// its instance descriptions there (and wrote through our old
  837. /// `E_NOTIMPL` as a pointer).
  838. extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mut u8 {
  839. let align = usize::try_from(alignment).unwrap_or(0).max(16);
  840. let Some(len) = usize::try_from(size).ok().and_then(|s| s.checked_add(align)) else {
  841. return std::ptr::null_mut();
  842. };
  843. if this.is_null() || !align.is_power_of_two() {
  844. return std::ptr::null_mut();
  845. }
  846. let mut block = vec![0u8; len];
  847. let start = block.as_mut_ptr();
  848. // SAFETY: the offset is below `align`, so `size` bytes fit after it.
  849. let at = unsafe { start.add(start.align_offset(align)) };
  850. // SAFETY: the title passes one of our lists.
  851. let uploads = unsafe { &(*this.cast::<List>()).uploads };
  852. // Moving the vector keeps its heap block where it is.
  853. uploads.lock().unwrap_or_else(|e| e.into_inner()).push(block);
  854. at
  855. }
  856. /// Draw state the host has no use for (root signatures: ours come with
  857. /// the pipeline; depth bounds, depth order and shading rate hints): any
  858. /// arguments, nothing returned.
  859. extern "system" fn ignored_state(_: This) {}
  860. /// The title's draw state (decision 0007, step 3), kept for its draws or
  861. /// set on the host list at once. Without a host GPU these do nothing.
  862. #[cfg(windows)]
  863. mod state {
  864. use super::{This, host_list, with_state};
  865. use crate::draw::{IndexView, VertexView};
  866. use windows::Win32::Foundation::RECT;
  867. use windows::Win32::Graphics::Direct3D12::D3D12_VIEWPORT;
  868. /// `count` items at `items`, or none.
  869. fn items<'a, T>(items: *const T, count: u32) -> &'a [T] {
  870. if items.is_null() || count == 0 {
  871. return &[];
  872. }
  873. // SAFETY: the title passes `count` items.
  874. unsafe { std::slice::from_raw_parts(items, count as usize) }
  875. }
  876. pub(super) extern "system" fn topology(this: This, topology: u32) {
  877. with_state(this, |list, s| s.set_topology(list, topology));
  878. }
  879. pub(super) extern "system" fn viewports(
  880. this: This,
  881. count: u32,
  882. viewports: *const D3D12_VIEWPORT,
  883. ) {
  884. if let Some(list) = host_list(this) {
  885. crate::draw::viewports(list, items(viewports, count));
  886. }
  887. }
  888. pub(super) extern "system" fn scissors(this: This, count: u32, rects: *const RECT) {
  889. if let Some(list) = host_list(this) {
  890. crate::draw::scissors(list, items(rects, count));
  891. }
  892. }
  893. pub(super) extern "system" fn blend_factor(this: This, factor: *const [f32; 4]) {
  894. if let Some(list) = host_list(this) {
  895. // SAFETY: the title passes four floats or null.
  896. crate::draw::blend_factor(list, unsafe { factor.as_ref() });
  897. }
  898. }
  899. pub(super) extern "system" fn stencil_ref(this: This, reference: u32) {
  900. if let Some(list) = host_list(this) {
  901. crate::draw::stencil_ref(list, reference);
  902. }
  903. }
  904. pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) {
  905. with_state(this, |_, s| s.set_heaps(items(heaps, count)));
  906. }
  907. pub(super) extern "system" fn compute_table(this: This, slot: u32, handle: u64) {
  908. with_state(this, |_, s| s.set_table(true, slot, handle));
  909. }
  910. pub(super) extern "system" fn graphics_table(this: This, slot: u32, handle: u64) {
  911. with_state(this, |_, s| s.set_table(false, slot, handle));
  912. }
  913. pub(super) extern "system" fn compute_constant(this: This, slot: u32, value: u32, offset: u32) {
  914. with_state(this, |_, s| s.set_constants(true, slot, &[value], offset));
  915. }
  916. pub(super) extern "system" fn graphics_constant(
  917. this: This,
  918. slot: u32,
  919. value: u32,
  920. offset: u32,
  921. ) {
  922. with_state(this, |_, s| s.set_constants(false, slot, &[value], offset));
  923. }
  924. pub(super) extern "system" fn compute_constants(
  925. this: This,
  926. slot: u32,
  927. count: u32,
  928. values: *const u32,
  929. offset: u32,
  930. ) {
  931. with_state(this, |_, s| {
  932. s.set_constants(true, slot, items(values, count), offset)
  933. });
  934. }
  935. pub(super) extern "system" fn graphics_constants(
  936. this: This,
  937. slot: u32,
  938. count: u32,
  939. values: *const u32,
  940. offset: u32,
  941. ) {
  942. with_state(this, |_, s| {
  943. s.set_constants(false, slot, items(values, count), offset)
  944. });
  945. }
  946. /// Root constant buffer, shader resource and unordered access views.
  947. pub(super) extern "system" fn compute_view(this: This, slot: u32, address: u64) {
  948. with_state(this, |_, s| s.set_view(true, slot, address));
  949. }
  950. pub(super) extern "system" fn graphics_view(this: This, slot: u32, address: u64) {
  951. with_state(this, |_, s| s.set_view(false, slot, address));
  952. }
  953. pub(super) extern "system" fn index_buffer(this: This, view: *const IndexView) {
  954. // SAFETY: the title passes a view or null.
  955. with_state(this, |_, s| s.set_index_buffer(unsafe { view.as_ref() }));
  956. }
  957. pub(super) extern "system" fn vertex_buffers(
  958. this: This,
  959. start: u32,
  960. count: u32,
  961. views: *const VertexView,
  962. ) {
  963. with_state(this, |_, s| {
  964. s.set_vertex_buffers(start, items(views, count))
  965. });
  966. }
  967. /// `(count, handles, one range, depth)`: with one range, the handles
  968. /// follow the first at the render target view size (128 bytes).
  969. pub(super) extern "system" fn targets(
  970. this: This,
  971. count: u32,
  972. handles: *const u64,
  973. one_range: i32,
  974. depth: *const u64,
  975. ) {
  976. let handles: Vec<u64> = if one_range != 0 && !handles.is_null() {
  977. // SAFETY: the title passes the first handle.
  978. let first = unsafe { *handles };
  979. (0..u64::from(count)).map(|i| first + 128 * i).collect()
  980. } else {
  981. items(handles, count).to_vec()
  982. };
  983. // SAFETY: the title passes a handle or null.
  984. let depth = unsafe { depth.as_ref() }.copied().unwrap_or(0);
  985. with_state(this, |list, s| s.set_targets(list, &handles, depth));
  986. }
  987. pub(super) extern "system" fn draw(
  988. this: This,
  989. vertices: u32,
  990. instances: u32,
  991. first: u32,
  992. first_instance: u32,
  993. ) {
  994. super::count_draw();
  995. with_state(this, |list, s| {
  996. s.draw(list, vertices, instances, first, first_instance)
  997. });
  998. }
  999. pub(super) extern "system" fn dispatch(this: This, x: u32, y: u32, z: u32) {
  1000. super::count_dispatch();
  1001. with_state(this, |list, s| s.dispatch(list, x, y, z));
  1002. }
  1003. /// `DispatchMesh(x, y, z)` (the PC method of List6); the title's mesh
  1004. /// programs take `x` groups only.
  1005. pub(super) extern "system" fn dispatch_mesh(this: This, x: u32, y: u32, z: u32) {
  1006. super::count_draw();
  1007. if y * z != 1 {
  1008. static ONCE: std::sync::Once = std::sync::Once::new();
  1009. ONCE.call_once(|| tracing::warn!(x, y, z, "a mesh dispatch with y or z groups"));
  1010. }
  1011. with_state(this, |list, s| s.dispatch_mesh(list, x));
  1012. }
  1013. /// `DispatchMeshX(x, flags, indirect arguments, payload)`.
  1014. /// shortcut: dispatches whose group count is in GPU memory (indirect)
  1015. /// are dropped; make them ExecuteIndirect when the title uses them.
  1016. pub(super) extern "system" fn dispatch_mesh_x(
  1017. this: This,
  1018. x: u32,
  1019. _flags: u64,
  1020. indirect: u64,
  1021. _payload: u64,
  1022. ) {
  1023. super::count_draw();
  1024. if indirect != 0 {
  1025. static ONCE: std::sync::Once = std::sync::Once::new();
  1026. ONCE.call_once(|| tracing::warn!("indirect mesh dispatches dropped"));
  1027. return;
  1028. }
  1029. with_state(this, |list, s| s.dispatch_mesh(list, x));
  1030. }
  1031. pub(super) extern "system" fn draw_indexed(
  1032. this: This,
  1033. indices: u32,
  1034. instances: u32,
  1035. first: u32,
  1036. base: i32,
  1037. first_instance: u32,
  1038. ) {
  1039. super::count_draw();
  1040. with_state(this, |list, s| {
  1041. s.draw_indexed(list, indices, instances, first, base, first_instance)
  1042. });
  1043. }
  1044. }
  1045. /// Without a host GPU every draw state call is ignored.
  1046. #[cfg(not(windows))]
  1047. mod state {
  1048. pub(super) use super::dispatch;
  1049. pub(super) use super::draw;
  1050. pub(super) use super::draw as draw_indexed;
  1051. pub(super) use super::draw as dispatch_mesh;
  1052. pub(super) use super::draw as dispatch_mesh_x;
  1053. pub(super) use super::ignored_state as blend_factor;
  1054. pub(super) use super::ignored_state as compute_constant;
  1055. pub(super) use super::ignored_state as compute_constants;
  1056. pub(super) use super::ignored_state as compute_table;
  1057. pub(super) use super::ignored_state as compute_view;
  1058. pub(super) use super::ignored_state as graphics_constant;
  1059. pub(super) use super::ignored_state as graphics_constants;
  1060. pub(super) use super::ignored_state as graphics_table;
  1061. pub(super) use super::ignored_state as graphics_view;
  1062. pub(super) use super::ignored_state as heaps;
  1063. pub(super) use super::ignored_state as index_buffer;
  1064. pub(super) use super::ignored_state as scissors;
  1065. pub(super) use super::ignored_state as stencil_ref;
  1066. pub(super) use super::ignored_state as targets;
  1067. pub(super) use super::ignored_state as topology;
  1068. pub(super) use super::ignored_state as vertex_buffers;
  1069. pub(super) use super::ignored_state as viewports;
  1070. }
  1071. fn count_draw() {
  1072. DRAWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1073. }
  1074. /// Draws of the kinds the host does not run yet (indirect, mesh), and
  1075. /// dispatches, counted per frame for the log.
  1076. /// shortcut: dropped until their shaders translate (decision 0007).
  1077. #[cfg(not(windows))]
  1078. extern "system" fn draw(_: This) {
  1079. count_draw();
  1080. }
  1081. /// `ExecuteIndirect(signature, max count, arguments, offset, count buffer,
  1082. /// offset)`. Grand Theft Auto VI's signatures (title+0x2479466, 2026-11-24)
  1083. /// hold one argument each: draw (stride 16), indexed draw (20), dispatch
  1084. /// (12), mesh dispatch (12), and the console's single-pass dispatch, type
  1085. /// 105 (stride 12: the three group counts; its flags live in the
  1086. /// signature, the title passes none), run as a plain dispatch. They run
  1087. /// through the host's indirect execution (`State::execute_indirect`).
  1088. /// shortcut: signatures that change root arguments are dropped (logged
  1089. /// once per signature).
  1090. extern "system" fn execute_indirect(
  1091. this: This,
  1092. signature: This,
  1093. max: u32,
  1094. arguments: This,
  1095. offset: u64,
  1096. count: This,
  1097. count_offset: u64,
  1098. ) {
  1099. count_draw();
  1100. let Some((stride, args)) = crate::signature::layout(signature) else {
  1101. return;
  1102. };
  1103. let address = crate::resource::buffer_bytes(arguments).map(|(p, _)| p as u64 + offset);
  1104. let counter = crate::resource::buffer_bytes(count).map(|(p, _)| p as u64 + count_offset);
  1105. let mut ran = false;
  1106. #[cfg(windows)]
  1107. if let ([[kind, ..]], Some(address)) = (args, address)
  1108. && (count.is_null() || counter.is_some())
  1109. {
  1110. const DISPATCH: u32 = 2;
  1111. const DISPATCH_SINGLE: u32 = 105;
  1112. let kind = if *kind == DISPATCH_SINGLE { DISPATCH } else { *kind };
  1113. with_state(this, |list, s| {
  1114. ran = s.execute_indirect(list, (kind, stride, max), address, counter);
  1115. });
  1116. } else {
  1117. #[cfg(all(windows, feature = "diagnostics"))]
  1118. crate::pipeline::note_why(format!(
  1119. "indirect signature {args:?}: arguments in a buffer {}, count in a buffer {}",
  1120. address.is_some(),
  1121. count.is_null() || counter.is_some()
  1122. ));
  1123. }
  1124. if ran {
  1125. return;
  1126. }
  1127. INDIRECT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1128. static SEEN: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
  1129. let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
  1130. if !seen.contains(&(signature as usize)) {
  1131. seen.push(signature as usize);
  1132. tracing::info!(
  1133. stride,
  1134. ?args,
  1135. max,
  1136. address = ?address.map(|a| format!("{a:#x}")),
  1137. counted = !count.is_null(),
  1138. "indirect execution dropped (first time for this signature)"
  1139. );
  1140. }
  1141. }
  1142. /// Indirect executions dropped since the last call.
  1143. pub(crate) fn take_indirect() -> u64 {
  1144. INDIRECT.swap(0, std::sync::atomic::Ordering::Relaxed)
  1145. }
  1146. static INDIRECT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1147. fn count_dispatch() {
  1148. DISPATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1149. }
  1150. #[cfg(not(windows))]
  1151. extern "system" fn dispatch(_: This) {
  1152. count_dispatch();
  1153. }
  1154. static DRAWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1155. static DISPATCHES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1156. /// Draws (any kind, mesh and indirect included) and compute dispatches
  1157. /// recorded since the last call.
  1158. pub(crate) fn take_counts() -> (u64, u64) {
  1159. use std::sync::atomic::Ordering::Relaxed;
  1160. (DRAWS.swap(0, Relaxed), DISPATCHES.swap(0, Relaxed))
  1161. }
  1162. /// A GPU wait for a memory value `(address, comparison, reference, ...)`.
  1163. /// Lists run one after another and to completion, so a value another queue
  1164. /// or the CPU has to write first cannot be waited for; nothing to do.
  1165. extern "system" fn wait_value(_: This, _address: u64, _comparison: u32, _reference: u64) {}
  1166. /// The enhanced barriers `(group count, groups)`: buffer, texture and
  1167. /// global barriers with layouts instead of states. Every host use of a
  1168. /// title texture (clears, copies) moves its host copy to the state it needs
  1169. /// first, so only their ordering matters: one barrier on every shader
  1170. /// write (the title's buffer barriers order compute passes).
  1171. extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) {
  1172. #[cfg(windows)]
  1173. if count > 0
  1174. && let Some(list) = host_list(this)
  1175. {
  1176. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
  1177. // SAFETY: the same layout; no resource named.
  1178. let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) };
  1179. // SAFETY: an open list.
  1180. unsafe { list.list.ResourceBarrier(&[barrier]) };
  1181. }
  1182. #[cfg(not(windows))]
  1183. let _ = (this, count);
  1184. }
  1185. /// The bottom-of-pipe value writes `(address, value, flush, flags)`, 32 and
  1186. /// 64 bits: done when the list has run, as the GPU would. Flag 1 writes the
  1187. /// GPU timestamp instead (64-bit form), flag 2 the system timestamp.
  1188. extern "system" fn write32(this: This, address: u64, value: u32, _flush: u32, _flags: u32) {
  1189. defer_write(this, address, Written::Value(u64::from(value)), 4);
  1190. }
  1191. extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, flags: u32) {
  1192. const GPU_TIMESTAMP: u32 = 1;
  1193. const SYSTEM_TIMESTAMP: u32 = 2;
  1194. let what = match flags {
  1195. GPU_TIMESTAMP => Written::GpuTimestamp,
  1196. SYSTEM_TIMESTAMP => Written::SystemTimestamp,
  1197. _ => Written::Value(value),
  1198. };
  1199. defer_write(this, address, what, 8);
  1200. }
  1201. fn defer_write(this: This, address: u64, what: Written, bytes: usize) {
  1202. if address == 0 {
  1203. return;
  1204. }
  1205. #[cfg(windows)]
  1206. if let Some(list) = host_list(this) {
  1207. list.defer_write(address as *mut u8, what, bytes);
  1208. return;
  1209. }
  1210. let _ = this;
  1211. // Without a host GPU nothing runs later: write now.
  1212. what.write(address as *mut u8, bytes);
  1213. }
  1214. /// The list methods by their slot in older titles' lists (the 2020-era
  1215. /// layout): IUnknown 3, object 4, device child 1, list 1, graphics list 96
  1216. /// (59 as on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3
  1217. /// + 13): 140 slots.
  1218. const METHODS: [(usize, *const ()); 52] = [
  1219. (0, list_query as *const ()),
  1220. (2, list_release as *const ()),
  1221. (7, object::parent_device as *const ()), // 0x38
  1222. (8, list_type as *const ()), // 0x40
  1223. (9, close as *const ()), // 0x48
  1224. (10, reset as *const ()), // 0x50
  1225. (12, state::draw as *const ()), // 0x60 instanced
  1226. (13, state::draw_indexed as *const ()), // 0x68 indexed
  1227. (14, state::dispatch as *const ()), // 0x70
  1228. (15, copy_buffer_region as *const ()), // 0x78
  1229. (16, copy_texture_region as *const ()), // 0x80
  1230. (17, copy_resource as *const ()), // 0x88
  1231. (19, resolve as *const ()), // 0x98
  1232. (20, state::topology as *const ()), // 0xa0
  1233. (21, state::viewports as *const ()), // 0xa8
  1234. (22, state::scissors as *const ()), // 0xb0
  1235. (23, state::blend_factor as *const ()), // 0xb8
  1236. (24, state::stencil_ref as *const ()), // 0xc0
  1237. (25, set_pipeline as *const ()), // 0xc8
  1238. (26, barrier as *const ()), // 0xd0
  1239. (32, state::heaps as *const ()), // 0x100
  1240. (33, ignored_state as *const ()), // 0x108 compute root signature
  1241. (34, ignored_state as *const ()), // 0x110 graphics root signature
  1242. (35, state::compute_table as *const ()), // 0x118
  1243. (36, state::graphics_table as *const ()), // 0x120
  1244. (37, state::compute_constant as *const ()), // 0x128
  1245. (38, state::graphics_constant as *const ()), // 0x130
  1246. (39, state::compute_constants as *const ()), // 0x138
  1247. (40, state::graphics_constants as *const ()), // 0x140
  1248. (41, state::compute_view as *const ()), // 0x148 CBV
  1249. (42, state::graphics_view as *const ()), // 0x150 CBV
  1250. (43, state::compute_view as *const ()), // 0x158 SRV
  1251. (44, state::graphics_view as *const ()), // 0x160 SRV
  1252. (45, state::compute_view as *const ()), // 0x168 UAV
  1253. (46, state::graphics_view as *const ()), // 0x170 UAV
  1254. (47, state::index_buffer as *const ()), // 0x178
  1255. (48, state::vertex_buffers as *const ()), // 0x180
  1256. (50, state::targets as *const ()), // 0x190
  1257. (51, clear_dsv as *const ()), // 0x198
  1258. (52, clear_rtv as *const ()), // 0x1a0
  1259. (59, execute_indirect as *const ()), // 0x1d8 indirect
  1260. (60, copy_memory as *const ()), // 0x1e0
  1261. (68, ignored_state as *const ()), // 0x220 depth bounds
  1262. (69, write32 as *const ()), // 0x228
  1263. (70, write64 as *const ()), // 0x230
  1264. (71, wait_value as *const ()), // 0x238, 32 bits
  1265. (72, wait_value as *const ()), // 0x240, 64 bits
  1266. (73, ignored_state as *const ()), // 0x248 pixel shader depth order
  1267. (83, copy_texture_region_x as *const ()), // 0x298
  1268. (84, copy_resource_x as *const ()), // 0x2a0
  1269. (124, ignored_state as *const ()), // 0x3e0 shading rate
  1270. (127, state::dispatch_mesh as *const ()), // 0x3f8 mesh dispatch
  1271. ];
  1272. /// The rest of [`METHODS`], kept apart only to stay readable.
  1273. const MORE_METHODS: [(usize, *const ()); 9] = [
  1274. (28, query_mark as *const ()), // 0xe0 BeginQuery
  1275. (29, query_mark as *const ()), // 0xe8 EndQuery
  1276. (30, resolve_queries as *const ()), // 0xf0
  1277. (78, dispatch_x as *const ()), // 0x270
  1278. (98, state::dispatch_mesh_x as *const ()), // 0x310
  1279. (99, driver_hint as *const ()), // 0x318
  1280. // Pipeline syncs at the top and bottom of the pipe, 0x408 and 0x410.
  1281. (129, sync as *const ()),
  1282. (130, sync as *const ()),
  1283. (137, reset_x as *const ()), // 0x448
  1284. ];
  1285. /// Newer titles' lists have two more methods in the console part of the
  1286. /// base list, after the clears (0x198/0x1a0 as before) and before
  1287. /// ExecuteIndirect, which moved from 0x1d8 to 0x1e8: every slot from 0x1d8
  1288. /// on is two later (taken here as starting exactly at 0x1d8). Inferred from
  1289. /// Grand Theft Auto VI's call shapes: ExecuteIndirect 0x1e8, bottom-of-pipe
  1290. /// writes 0x238/0x240, waits 0x248/0x250, depth bounds 0x230, shading rate
  1291. /// 0x3f0/0x400, syncs 0x418/0x420, ResetX 0x458 (asserts on failure).
  1292. const fn newer_slot(slot: usize) -> usize {
  1293. if slot >= 59 { slot + 2 } else { slot }
  1294. }
  1295. /// Methods only newer titles' lists have. 0x490: the enhanced barrier
  1296. /// `(group count, groups)`, with 16-byte groups `(type, count, barriers)`
  1297. /// and 40-byte buffer barriers (title+0x95e0 builds them). 0x470 `(u64)`,
  1298. /// called from Grand Theft Auto VI's state flush with its result unused.
  1299. /// shortcut: 0x470's purpose is unknown; ignored until a title shows it
  1300. /// matters.
  1301. const NEWER_METHODS: [(usize, *const ()); 3] = [
  1302. (142, ignored_state as *const ()),
  1303. (146, barrier_groups as *const ()),
  1304. (148, allocate_upload as *const ()),
  1305. ];
  1306. const fn list_table(newer: bool) -> [*const (); 160] {
  1307. let mut f = object::d3d12_object(object::missing_table::<LIST, 160>());
  1308. let mut i = 0;
  1309. while i < METHODS.len() + MORE_METHODS.len() {
  1310. let (slot, method) = if i < METHODS.len() {
  1311. METHODS[i]
  1312. } else {
  1313. MORE_METHODS[i - METHODS.len()]
  1314. };
  1315. f[if newer { newer_slot(slot) } else { slot }] = method;
  1316. i += 1;
  1317. }
  1318. let mut i = 0;
  1319. while newer && i < NEWER_METHODS.len() {
  1320. f[NEWER_METHODS[i].0] = NEWER_METHODS[i].1;
  1321. i += 1;
  1322. }
  1323. f
  1324. }
  1325. /// Every slot up to the limit exists and logs, for the methods newer
  1326. /// titles add.
  1327. static LIST_FUNCTIONS: Table<160> = Table(list_table(false));
  1328. static NEWER_LIST_FUNCTIONS: Table<160> = Table(list_table(true));
  1329. #[cfg(test)]
  1330. mod tests {
  1331. use super::*;
  1332. use crate::object::slot;
  1333. #[test]
  1334. fn every_inline_command_falls_back_to_the_table() {
  1335. let null = std::ptr::null();
  1336. let mut allocator = null;
  1337. assert_eq!(
  1338. create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator),
  1339. S_OK
  1340. );
  1341. let mut list = null;
  1342. let hr = create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list);
  1343. assert_eq!(hr, S_OK);
  1344. // What the title's inline draw checks: put < draw limit.
  1345. // SAFETY: the list is 0x560 bytes.
  1346. let (put, draw_limit, api_limit) = unsafe {
  1347. let at = |o: usize| list.cast::<u8>().add(o).cast::<u64>().read();
  1348. (at(0x18), at(0x28), at(0x30))
  1349. };
  1350. assert!(put >= draw_limit && put >= api_limit);
  1351. // The console's ID3D12GraphicsCommandList6, as Grand Theft Auto VI asks.
  1352. let mut same = null;
  1353. assert_eq!(list_query(list, &LIST_IIDS[7], &mut same), S_OK);
  1354. assert_eq!(same, list);
  1355. assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x10)(list), 1);
  1356. assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x40)(list), 0);
  1357. assert_eq!(
  1358. slot::<extern "system" fn(This) -> HRESULT>(list, 0x48)(list),
  1359. S_OK
  1360. );
  1361. // List-owned upload memory: aligned, writable, gone at reset.
  1362. let p = allocate_upload(list, 40, 0x100);
  1363. assert!(!p.is_null() && (p as usize).is_multiple_of(0x100));
  1364. // SAFETY: 40 bytes were handed out.
  1365. unsafe { p.write_bytes(0xab, 40) };
  1366. assert!(allocate_upload(list, 8, 0x30).is_null(), "not a power of two");
  1367. assert_eq!(reset(list, allocator, null), S_OK);
  1368. // SAFETY: the list is ours.
  1369. assert!(unsafe { &(*list.cast::<List>()).uploads }.lock().unwrap().is_empty());
  1370. let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o);
  1371. assert_eq!(release(list), 0);
  1372. assert_eq!(release(allocator), 0);
  1373. }
  1374. }