resource.rs 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844
  1. //! Heaps, committed and placed resources, and resource sizes.
  2. //!
  3. //! Heaps and resources are host memory and a resource's GPU address is its
  4. //! CPU address, as on the console; textures also get a host copy, and
  5. //! buffers a host copy when a draw reads them (`shadow`).
  6. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  7. use std::alloc::{Layout, alloc_zeroed, dealloc};
  8. use std::ffi::c_void;
  9. use std::ptr::NonNull;
  10. use victory_formats::texture;
  11. use crate::object::{
  12. self, E_INVALIDARG, E_OUTOFMEMORY, HEAP, HRESULT, Iid, Object, RESOURCE, S_OK, Table, This,
  13. guid,
  14. };
  15. /// The interfaces every device child also answers for.
  16. pub(crate) const PAGEABLE_IIDS: [Iid; 3] = [
  17. guid(
  18. 0x63ee58fb,
  19. 0x1268,
  20. 0x4835,
  21. [0x86, 0xda, 0xf0, 0x08, 0xce, 0x62, 0xf0, 0xd6],
  22. ),
  23. guid(
  24. 0x905db94b,
  25. 0xa00c,
  26. 0x4140,
  27. [0x9d, 0xf5, 0x2b, 0x64, 0xca, 0x9e, 0xa3, 0x57],
  28. ),
  29. guid(
  30. 0xc4fec28f,
  31. 0x7966,
  32. 0x4e95,
  33. [0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8],
  34. ),
  35. ];
  36. const HEAP_IIDS: [Iid; 4] = [
  37. guid(
  38. 0x6b3b2502,
  39. 0x6e51,
  40. 0x45b3,
  41. [0x90, 0xee, 0x98, 0x84, 0x26, 0x5e, 0x8d, 0xf3],
  42. ),
  43. PAGEABLE_IIDS[0],
  44. PAGEABLE_IIDS[1],
  45. PAGEABLE_IIDS[2],
  46. ];
  47. const RESOURCE_IIDS: [Iid; 4] = [
  48. guid(
  49. 0x696442be,
  50. 0xa72e,
  51. 0x4059,
  52. [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad],
  53. ),
  54. PAGEABLE_IIDS[0],
  55. PAGEABLE_IIDS[1],
  56. PAGEABLE_IIDS[2],
  57. ];
  58. const KIB_64: u64 = 64 << 10;
  59. const MIB_4: u64 = 4 << 20;
  60. #[repr(C)]
  61. #[derive(Debug, Clone, Copy)]
  62. pub(crate) struct HeapProperties {
  63. kind: u32,
  64. cpu_pages: u32,
  65. pool: u32,
  66. creation_nodes: u32,
  67. visible_nodes: u32,
  68. }
  69. #[repr(C)]
  70. #[derive(Debug, Clone, Copy)]
  71. pub(crate) struct HeapDesc {
  72. size: u64,
  73. properties: HeapProperties,
  74. alignment: u64,
  75. flags: u32,
  76. }
  77. #[repr(C)]
  78. #[derive(Debug, Clone, Copy)]
  79. pub(crate) struct ResourceDesc {
  80. dimension: u32,
  81. alignment: u64,
  82. width: u64,
  83. height: u32,
  84. depth_or_array_size: u16,
  85. mip_levels: u16,
  86. format: u32,
  87. sample_count: u32,
  88. sample_quality: u32,
  89. layout: u32,
  90. flags: u32,
  91. }
  92. #[repr(C)]
  93. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  94. pub(crate) struct AllocationInfo {
  95. size: u64,
  96. alignment: u64,
  97. }
  98. const _: () = assert!(size_of::<HeapProperties>() == 20);
  99. const _: () = assert!(size_of::<HeapDesc>() == 48);
  100. const _: () = assert!(size_of::<ResourceDesc>() == 56);
  101. const BUFFER: u32 = 1;
  102. const TEXTURE_3D: u32 = 4;
  103. /// Bytes per element and the element's width in texels (4 for block
  104. /// compression), by DXGI format number. `None` for 1-bit and video
  105. /// formats. The console adds 116/117 (10-bit float color), 118-120 (16-bit
  106. /// depth with 8-bit stencil, two planes: 3 bytes per texel), 189 (signed
  107. /// 10-bit color), 190 (two 4-bit channels) and 191 (24/8 color).
  108. pub(crate) fn element(format: u32) -> Option<(u64, u64)> {
  109. Some(match format {
  110. 1..=4 => (16, 1),
  111. 5..=8 => (12, 1),
  112. 9..=22 => (8, 1),
  113. 23..=47 | 67 | 87..=93 | 116 | 117 | 189 | 191 => (4, 1),
  114. 118..=120 => (3, 1),
  115. 48..=59 | 68 | 69 | 85 | 86 | 115 => (2, 1),
  116. 60..=65 | 190 => (1, 1),
  117. 70..=72 | 79..=81 => (8, 4),
  118. 73..=78 | 82..=84 | 94..=99 => (16, 4),
  119. _ => return None,
  120. })
  121. }
  122. /// A texture's layout in console memory, as the console's layout library
  123. /// gives it (`victory-hle`'s `xg` serves the same): the description's
  124. /// layout field is `0x100 | swizzle mode`, 1 linear, 0 the library's pick.
  125. pub(crate) fn texture_layout(desc: &ResourceDesc) -> Option<texture::Texture> {
  126. use texture::{Dimension, Swizzle, TextureDesc};
  127. const TEXTURE_1D: u32 = 2;
  128. const TEXTURE_2D: u32 = 3;
  129. const RENDER_TARGET: u32 = 1;
  130. const DEPTH: u32 = 2;
  131. let dimension = match desc.dimension {
  132. TEXTURE_1D => Dimension::Tex1d,
  133. TEXTURE_2D => Dimension::Tex2d,
  134. TEXTURE_3D => Dimension::Tex3d,
  135. _ => return None,
  136. };
  137. let swizzle = match desc.layout {
  138. 0 if dimension == Dimension::Tex1d => Swizzle::LINEAR,
  139. 0 if desc.flags & DEPTH != 0 => Swizzle::SW_64KB_Z_X,
  140. 0 if desc.flags & RENDER_TARGET != 0 => Swizzle::SW_64KB_R_X,
  141. 0 => Swizzle::SW_4KB_S,
  142. 1 => Swizzle::LINEAR,
  143. l if l & !0xff == 0x100 => Swizzle(l & 0xff),
  144. _ => return None,
  145. };
  146. texture::Texture::new(&TextureDesc {
  147. dimension,
  148. width: u32::try_from(desc.width).ok()?,
  149. height: desc.height,
  150. depth_or_array: u32::from(desc.depth_or_array_size),
  151. mips: u32::from(desc.mip_levels),
  152. format: desc.format,
  153. samples: desc.sample_count.max(1),
  154. swizzle,
  155. })
  156. .ok()
  157. }
  158. /// Bytes and alignment a resource takes: buffers their width (64 KiB
  159. /// aligned), textures their console layout (formats it does not know:
  160. /// every mip of every array slice and sample, packed, 64 KiB aligned),
  161. /// rounded up to the alignment.
  162. fn footprint(desc: &ResourceDesc) -> Option<AllocationInfo> {
  163. if desc.dimension != BUFFER
  164. && let Some(t) = texture_layout(desc)
  165. {
  166. // As the console: the layout's own alignment unless more is asked
  167. // (4 KiB for 4 KiB modes, where PC says 64 KiB). Grand Theft Auto
  168. // VI keeps these sizes in its texture tables, and its streaming
  169. // asserts when they disagree with the streamed layout.
  170. let alignment = desc.alignment.max(t.alignment);
  171. if !alignment.is_power_of_two() {
  172. return None;
  173. }
  174. return Some(AllocationInfo {
  175. size: t.size.checked_next_multiple_of(alignment)?,
  176. alignment,
  177. });
  178. }
  179. let bytes = if desc.dimension == BUFFER {
  180. desc.width
  181. } else {
  182. let (element, block) = element(desc.format)?;
  183. let (depth, slices) = if desc.dimension == TEXTURE_3D {
  184. (u64::from(desc.depth_or_array_size), 1)
  185. } else {
  186. (1, u64::from(desc.depth_or_array_size))
  187. };
  188. let height = u64::from(desc.height);
  189. let mips = mip_count(desc);
  190. let mut chain = 0u64;
  191. for mip in 0..mips.min(64) {
  192. let w = (desc.width >> mip).max(1).div_ceil(block);
  193. let h = (height >> mip).max(1).div_ceil(block);
  194. let d = (depth >> mip).max(1);
  195. chain = chain.checked_add(w.checked_mul(h)?.checked_mul(d)?.checked_mul(element)?)?;
  196. }
  197. chain
  198. .checked_mul(slices)?
  199. .checked_mul(u64::from(desc.sample_count.max(1)))?
  200. };
  201. if bytes == 0 {
  202. return None;
  203. }
  204. let minimum = if desc.sample_count > 1 { MIB_4 } else { KIB_64 };
  205. let alignment = desc.alignment.max(minimum);
  206. if !alignment.is_power_of_two() {
  207. return None;
  208. }
  209. Some(AllocationInfo {
  210. size: bytes.checked_next_multiple_of(KIB_64)?,
  211. alignment,
  212. })
  213. }
  214. /// A format as the host has it. The console's 16-bit depth with stencil
  215. /// (and its typeless views) has no PC format: the 24-bit ones stand in.
  216. pub(crate) fn pc_format(format: u32) -> u32 {
  217. match format {
  218. 118 => 45,
  219. 119 => 46,
  220. 120 => 47,
  221. other => other,
  222. }
  223. }
  224. /// The typeless format of a format's family (itself if it has none).
  225. pub(crate) fn family(format: u32) -> u32 {
  226. const FAMILIES: [(u32, u32); 22] = [
  227. (1, 4),
  228. (5, 8),
  229. (9, 14),
  230. (15, 18),
  231. (19, 22),
  232. (23, 25),
  233. (27, 32),
  234. (33, 38),
  235. (39, 43),
  236. (44, 47),
  237. (48, 52),
  238. (53, 59),
  239. (60, 65),
  240. (70, 72),
  241. (73, 75),
  242. (76, 78),
  243. (79, 81),
  244. (82, 84),
  245. (90, 91),
  246. (92, 93),
  247. (94, 96),
  248. (97, 99),
  249. ];
  250. match format {
  251. 87 => 90,
  252. 88 => 92,
  253. f => FAMILIES
  254. .iter()
  255. .find(|&&(first, last)| (first..=last).contains(&f))
  256. .map_or(f, |&(first, _)| first),
  257. }
  258. }
  259. /// sRGB formats and their linear twins.
  260. pub(crate) const SRGB: [(u32, u32); 3] = [(29, 28), (91, 87), (93, 88)];
  261. /// The format a view of a title texture must name when its host copy is
  262. /// typeless (see [`DEPTH_FORMATS`], [`SRGB`]): the title's own; `None` if
  263. /// the host copy is typed.
  264. pub(crate) fn view_format(this: This) -> Option<u32> {
  265. let own = pc_format(resource(this).desc.format);
  266. let host = host_resource(this)?;
  267. // SAFETY: a live resource.
  268. let format = unsafe { host.GetDesc() }.Format.0 as u32;
  269. (format != own).then_some(own)
  270. }
  271. /// Depth formats with their typeless family: depth textures that shaders
  272. /// read are made typeless on the host, which only allows views of
  273. /// typeless depth resources.
  274. pub(crate) const DEPTH_FORMATS: [(u32, u32); 4] = [(20, 19), (40, 39), (45, 44), (55, 53)];
  275. /// Mip levels, the full chain for 0.
  276. fn mip_count(desc: &ResourceDesc) -> u32 {
  277. let depth = if desc.dimension == TEXTURE_3D {
  278. u64::from(desc.depth_or_array_size)
  279. } else {
  280. 1
  281. };
  282. match desc.mip_levels {
  283. 0 => {
  284. 64 - desc
  285. .width
  286. .max(u64::from(desc.height))
  287. .max(depth)
  288. .max(1)
  289. .leading_zeros()
  290. }
  291. n => u32::from(n),
  292. }
  293. }
  294. #[repr(C)]
  295. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  296. pub(crate) struct PlacedFootprint {
  297. pub(crate) offset: u64,
  298. format: u32,
  299. width: u32,
  300. height: u32,
  301. depth: u32,
  302. row_pitch: u32,
  303. }
  304. impl PlacedFootprint {
  305. /// The bytes it spans in a buffer: every row pitched but the last.
  306. pub(crate) fn bytes(&self) -> Option<u64> {
  307. let (element, block) = element(self.format)?;
  308. let lines = u64::from(self.height).div_ceil(block) * u64::from(self.depth);
  309. let last = u64::from(self.width).div_ceil(block) * element;
  310. Some(u64::from(self.row_pitch) * lines.saturating_sub(1) + last)
  311. }
  312. }
  313. const _: () = assert!(size_of::<PlacedFootprint>() == 32);
  314. const NO_FOOTPRINT: PlacedFootprint = PlacedFootprint {
  315. offset: u64::MAX,
  316. format: 0,
  317. width: 0,
  318. height: 0,
  319. depth: 0,
  320. row_pitch: 0,
  321. };
  322. /// One subresource's size in an upload buffer: footprint (offset 0), rows
  323. /// and bytes per row. Planes of depth-stencil formats are not told apart.
  324. fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32, u64)> {
  325. const PITCH: u64 = 256;
  326. if desc.dimension == BUFFER {
  327. let footprint = PlacedFootprint {
  328. offset: 0,
  329. format: 0,
  330. width: u32::try_from(desc.width).ok()?,
  331. height: 1,
  332. depth: 1,
  333. row_pitch: u32::try_from(desc.width.next_multiple_of(PITCH)).ok()?,
  334. };
  335. return (index == 0).then_some((footprint, 1, desc.width));
  336. }
  337. let mips = mip_count(desc);
  338. let slices = if desc.dimension == TEXTURE_3D {
  339. 1
  340. } else {
  341. u32::from(desc.depth_or_array_size).max(1)
  342. };
  343. let (mip, slice) = (index % mips, index / mips);
  344. if slice >= slices {
  345. return None;
  346. }
  347. let (element, block) = element(desc.format)?;
  348. let width = (desc.width >> mip).max(1).next_multiple_of(block);
  349. let height = (u64::from(desc.height) >> mip)
  350. .max(1)
  351. .next_multiple_of(block);
  352. let depth = if desc.dimension == TEXTURE_3D {
  353. (u32::from(desc.depth_or_array_size) >> mip).max(1)
  354. } else {
  355. 1
  356. };
  357. let row_size = width / block * element;
  358. let footprint = PlacedFootprint {
  359. offset: 0,
  360. format: desc.format,
  361. width: u32::try_from(width).ok()?,
  362. height: u32::try_from(height).ok()?,
  363. depth,
  364. row_pitch: u32::try_from(row_size.next_multiple_of(PITCH)).ok()?,
  365. };
  366. Some((footprint, u32::try_from(height / block).ok()?, row_size))
  367. }
  368. /// Device method: where each subresource goes in an upload buffer, rows
  369. /// 256-byte and subresources 512-byte aligned, as on PC. Unknown sizes give
  370. /// the documented all-ones values.
  371. pub(crate) extern "system" fn copyable_footprints(
  372. _: This,
  373. desc: *const ResourceDesc,
  374. first: u32,
  375. count: u32,
  376. base: u64,
  377. layouts: *mut PlacedFootprint,
  378. rows: *mut u32,
  379. row_sizes: *mut u64,
  380. total: *mut u64,
  381. ) {
  382. const PLACEMENT: u64 = 512;
  383. // SAFETY: the title passes a description (null is tolerated).
  384. let desc = unsafe { desc.as_ref() };
  385. let mut end = base;
  386. let mut known = desc.is_some();
  387. for i in 0..count {
  388. let one = desc.and_then(|d| subresource(d, first + i));
  389. let (layout, row_count, row_size) = match one {
  390. Some((mut footprint, row_count, row_size)) => {
  391. footprint.offset = end.next_multiple_of(PLACEMENT);
  392. let pitch = u64::from(footprint.row_pitch);
  393. let lines = u64::from(row_count) * u64::from(footprint.depth);
  394. end = footprint.offset + pitch * lines.saturating_sub(1) + row_size;
  395. (footprint, row_count, row_size)
  396. }
  397. None => {
  398. known = false;
  399. (NO_FOOTPRINT, u32::MAX, u64::MAX)
  400. }
  401. };
  402. let i = i as usize;
  403. // SAFETY: each output is null or holds `count` entries.
  404. unsafe {
  405. if !layouts.is_null() {
  406. layouts.add(i).write(layout);
  407. }
  408. if !rows.is_null() {
  409. rows.add(i).write(row_count);
  410. }
  411. if !row_sizes.is_null() {
  412. row_sizes.add(i).write(row_size);
  413. }
  414. }
  415. }
  416. if !known {
  417. tracing::warn!(?desc, "no footprint for this resource");
  418. }
  419. if !total.is_null() {
  420. // SAFETY: checked non-null.
  421. unsafe { total.write(if known { end - base } else { u64::MAX }) };
  422. }
  423. }
  424. /// Device method: the footprint of resources placed one after another.
  425. /// Returns a 16-byte value, through a hidden first argument. Invalid input
  426. /// gives the documented size `u64::MAX`.
  427. pub(crate) extern "system" fn allocation_info(
  428. out: *mut AllocationInfo,
  429. _: This,
  430. _visible: u32,
  431. count: u32,
  432. descs: *const ResourceDesc,
  433. ) -> *mut AllocationInfo {
  434. let descs = if descs.is_null() {
  435. &[][..]
  436. } else {
  437. // SAFETY: the title passes `count` descriptions.
  438. unsafe { std::slice::from_raw_parts(descs, count as usize) }
  439. };
  440. // SAFETY: the caller passes room for the value.
  441. unsafe { out.write(place(descs.iter(), |_, _| ())) };
  442. out
  443. }
  444. /// The newer description: the plain one, then a sampler feedback mip
  445. /// region (width, height, depth).
  446. #[repr(C)]
  447. pub(crate) struct ResourceDesc1 {
  448. desc: ResourceDesc,
  449. mip_region: [u32; 3],
  450. }
  451. const _: () = assert!(size_of::<ResourceDesc1>() == 72);
  452. /// Where one resource goes in [`allocation_info2`]'s placement.
  453. #[repr(C)]
  454. pub(crate) struct AllocationInfo1 {
  455. offset: u64,
  456. alignment: u64,
  457. size: u64,
  458. }
  459. /// Device method 0x360 (`ID3D12Device8`): [`allocation_info`] for newer
  460. /// descriptions, also telling where each resource goes.
  461. pub(crate) extern "system" fn allocation_info2(
  462. out: *mut AllocationInfo,
  463. _: This,
  464. _visible: u32,
  465. count: u32,
  466. descs: *const ResourceDesc1,
  467. each: *mut AllocationInfo1,
  468. ) -> *mut AllocationInfo {
  469. let descs = if descs.is_null() {
  470. &[][..]
  471. } else {
  472. // SAFETY: the title passes `count` descriptions.
  473. unsafe { std::slice::from_raw_parts(descs, count as usize) }
  474. };
  475. let total = place(descs.iter().map(|d| &d.desc), |i, info| {
  476. if !each.is_null() {
  477. // SAFETY: the title passes room for `count` entries.
  478. unsafe { each.add(i).write(info) };
  479. }
  480. });
  481. // SAFETY: the caller passes room for the value.
  482. unsafe { out.write(total) };
  483. out
  484. }
  485. /// Resources placed one after another: the whole footprint, telling `each`
  486. /// where every resource goes. Unknown sizes give the documented `u64::MAX`.
  487. fn place<'a>(
  488. descs: impl Iterator<Item = &'a ResourceDesc>,
  489. mut each: impl FnMut(usize, AllocationInfo1),
  490. ) -> AllocationInfo {
  491. let mut total = AllocationInfo {
  492. size: 0,
  493. alignment: KIB_64,
  494. };
  495. for (i, desc) in descs.enumerate() {
  496. let Some(one) = footprint(desc) else {
  497. tracing::warn!(?desc, "no size for this resource");
  498. each(
  499. i,
  500. AllocationInfo1 {
  501. offset: u64::MAX,
  502. alignment: 0,
  503. size: u64::MAX,
  504. },
  505. );
  506. return AllocationInfo {
  507. size: u64::MAX,
  508. alignment: 0,
  509. };
  510. };
  511. tracing::debug!(?desc, ?one, "allocation info");
  512. let offset = total.size.next_multiple_of(one.alignment);
  513. each(
  514. i,
  515. AllocationInfo1 {
  516. offset,
  517. alignment: one.alignment,
  518. size: one.size,
  519. },
  520. );
  521. total.size = offset + one.size;
  522. total.alignment = total.alignment.max(one.alignment);
  523. }
  524. total
  525. }
  526. /// Zeroed host memory standing in for GPU memory.
  527. pub(crate) struct Memory {
  528. ptr: NonNull<u8>,
  529. layout: Layout,
  530. /// Set when the memory came from the title's allocator, with these
  531. /// allocation attributes (it goes back there).
  532. attributes: Option<u64>,
  533. }
  534. pub type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void;
  535. pub type FreeRoutine = extern "system" fn(*mut c_void, u64);
  536. static ALLOCATOR: std::sync::OnceLock<(AllocRoutine, FreeRoutine)> = std::sync::OnceLock::new();
  537. /// Committed resources get their memory from the title's general
  538. /// allocator, as on the console, where titles hook it to place graphics
  539. /// memory themselves (Grand Theft Auto VI places its back buffers in a
  540. /// block of its own and checks they fill it). The runtime names it before
  541. /// the device exists.
  542. pub fn use_allocator(alloc: AllocRoutine, free: FreeRoutine) {
  543. let _ = ALLOCATOR.set((alloc, free));
  544. }
  545. /// Maps the physical pages behind one range of title memory at another,
  546. /// `(to, from, len)` (`from` 0 unmaps); false on failure.
  547. pub type PageMapper = fn(u64, u64, u64) -> bool;
  548. static PAGE_MAPPER: std::sync::OnceLock<PageMapper> = std::sync::OnceLock::new();
  549. /// The runtime's page mapper, for the queues' page-mapping copies (memory
  550. /// is the runtime's, as on the console).
  551. pub fn use_page_mapper(mapper: PageMapper) {
  552. let _ = PAGE_MAPPER.set(mapper);
  553. }
  554. pub(crate) fn page_mapper() -> Option<PageMapper> {
  555. PAGE_MAPPER.get().copied()
  556. }
  557. /// Allocation attributes for resource memory: allocator id, page size
  558. /// (bits 14-15: 2 MiB pages from 2 MiB up, else 64 KiB), alignment as log2
  559. /// (bits 24-28) and memory type (bits 29-32: write-combined for GPU-only
  560. /// heaps, cacheable for the CPU-visible ones).
  561. /// shortcut: the console runtime's own choice of page size and memory type
  562. /// is not known; this is the plausible one.
  563. fn resource_attributes(info: AllocationInfo, heap_kind: u32) -> u64 {
  564. const GRAPHICS_ALLOCATOR: u64 = 128 << 16;
  565. const DEFAULT_HEAP: u32 = 1;
  566. let pages: u64 = if info.size >= 2 << 20 { 2 } else { 1 };
  567. let memory: u64 = if heap_kind == DEFAULT_HEAP { 1 } else { 3 };
  568. let alignment = u64::from(info.alignment.max(1).trailing_zeros());
  569. GRAPHICS_ALLOCATOR | pages << 14 | alignment << 24 | memory << 29
  570. }
  571. impl Memory {
  572. /// A committed resource's memory: from the title's allocator if the
  573. /// runtime named one, else our own; zeroed either way.
  574. fn for_resource(info: AllocationInfo, heap_kind: u32) -> Result<Memory, HRESULT> {
  575. let Some(&(alloc, _)) = ALLOCATOR.get() else {
  576. return Memory::new(info);
  577. };
  578. let layout = Layout::from_size_align(info.size as usize, info.alignment as usize)
  579. .map_err(|_| E_INVALIDARG)?;
  580. let attributes = resource_attributes(info, heap_kind);
  581. let ptr =
  582. NonNull::new(alloc(layout.size(), attributes).cast::<u8>()).ok_or(E_OUTOFMEMORY)?;
  583. // SAFETY: the allocator handed out `size` bytes.
  584. unsafe { ptr.as_ptr().write_bytes(0, layout.size()) };
  585. Ok(Memory {
  586. ptr,
  587. layout,
  588. attributes: Some(attributes),
  589. })
  590. }
  591. /// `size` zeroed bytes aligned to `alignment` (a power of two).
  592. pub(crate) fn zeroed(size: u64, alignment: u64) -> Result<Memory, HRESULT> {
  593. Memory::new(AllocationInfo { size, alignment })
  594. }
  595. pub(crate) fn address(&self) -> u64 {
  596. self.ptr.as_ptr() as u64
  597. }
  598. fn new(info: AllocationInfo) -> Result<Memory, HRESULT> {
  599. let layout = usize::try_from(info.size)
  600. .ok()
  601. .zip(usize::try_from(info.alignment).ok())
  602. .filter(|&(size, _)| size > 0)
  603. .and_then(|(size, align)| Layout::from_size_align(size, align).ok())
  604. .ok_or(E_INVALIDARG)?;
  605. // SAFETY: the size is non-zero.
  606. let ptr = NonNull::new(unsafe { alloc_zeroed(layout) }).ok_or(E_OUTOFMEMORY)?;
  607. Ok(Memory {
  608. ptr,
  609. layout,
  610. attributes: None,
  611. })
  612. }
  613. }
  614. impl Drop for Memory {
  615. fn drop(&mut self) {
  616. match (self.attributes, ALLOCATOR.get()) {
  617. (Some(attributes), Some(&(_, free))) => free(self.ptr.as_ptr().cast(), attributes),
  618. // SAFETY: allocated in `new` with this layout.
  619. _ => unsafe { dealloc(self.ptr.as_ptr(), self.layout) },
  620. }
  621. }
  622. }
  623. #[repr(C)]
  624. struct Heap {
  625. object: Object,
  626. desc: HeapDesc,
  627. memory: Memory,
  628. }
  629. pub(crate) extern "system" fn create_heap(
  630. _: This,
  631. desc: *const HeapDesc,
  632. iid: *const Iid,
  633. out: *mut This,
  634. ) -> HRESULT {
  635. // SAFETY: the title passes a description (null is tolerated).
  636. let Some(&desc) = (unsafe { desc.as_ref() }) else {
  637. return E_INVALIDARG;
  638. };
  639. tracing::debug!(
  640. size = desc.size,
  641. kind = desc.properties.kind,
  642. flags = format_args!("{:#x}", desc.flags),
  643. "heap"
  644. );
  645. if desc.alignment != 0 && !desc.alignment.is_power_of_two() {
  646. return E_INVALIDARG;
  647. }
  648. let info = AllocationInfo {
  649. size: desc.size,
  650. alignment: desc.alignment.max(KIB_64),
  651. };
  652. let memory = match Memory::new(info) {
  653. Ok(memory) => memory,
  654. Err(hr) => return hr,
  655. };
  656. let heap = Box::new(Heap {
  657. object: Object::new(&HEAP_FUNCTIONS),
  658. desc,
  659. memory,
  660. });
  661. object::hand_out(HEAP, heap, iid, &HEAP_IIDS, out)
  662. }
  663. extern "system" fn heap_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  664. object::answer(HEAP, iid, object::is(iid, &HEAP_IIDS).then_some(this), out)
  665. }
  666. extern "system" fn heap_release(this: This) -> u32 {
  667. object::release_boxed::<Heap>(this)
  668. }
  669. extern "system" fn heap_desc(this: This, out: *mut HeapDesc) {
  670. if !out.is_null() {
  671. // SAFETY: `this` is a heap; the title passes room for a description.
  672. unsafe { out.write((*this.cast::<Heap>()).desc) };
  673. }
  674. }
  675. /// A resource's memory: its own, or a range of a heap it holds a reference
  676. /// to.
  677. enum Backing {
  678. Committed(Memory),
  679. Placed {
  680. heap: This,
  681. offset: u64,
  682. },
  683. /// Memory the title mapped itself, at this address.
  684. Address(*mut u8),
  685. }
  686. impl Drop for Backing {
  687. fn drop(&mut self) {
  688. if let Backing::Placed { heap, .. } = *self {
  689. heap_release(heap);
  690. }
  691. }
  692. }
  693. #[repr(C)]
  694. struct Resource {
  695. object: Object,
  696. desc: ResourceDesc,
  697. heap: HeapProperties,
  698. heap_flags: u32,
  699. backing: Backing,
  700. /// Textures also live on the host GPU (decision 0007); buffers do not
  701. /// yet.
  702. #[cfg(windows)]
  703. host: Option<std::sync::Arc<HostTexture>>,
  704. }
  705. /// A title texture's host copy and the state it is in. The title's barriers
  706. /// name console states (looser than the host's), so we transition from this
  707. /// one. Lists that use the texture hold it until they are reset: the title
  708. /// may release a resource whose commands it recorded but not yet submitted
  709. /// (console memory outlives the object; a host texture must outlive the
  710. /// lists that name it).
  711. #[cfg(windows)]
  712. pub(crate) struct HostTexture {
  713. pub(crate) texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource,
  714. pub(crate) state: std::sync::atomic::AtomicU32,
  715. }
  716. /// Moves the host texture to `wanted` (a host texture state); the host
  717. /// resource and the state it leaves, if that is a change.
  718. #[cfg(windows)]
  719. pub(crate) fn host_transition(this: This, wanted: u32) -> Option<(*mut c_void, u32)> {
  720. use windows::core::Interface;
  721. let host = resource(this).host.as_ref()?;
  722. let before = host
  723. .state
  724. .swap(wanted, std::sync::atomic::Ordering::Relaxed);
  725. (before != wanted).then(|| (host.texture.as_raw(), before))
  726. }
  727. /// The host GPU's copy of a title resource, if it has one.
  728. #[cfg(windows)]
  729. pub(crate) fn host_resource<'a>(
  730. this: This,
  731. ) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
  732. if this.is_null() {
  733. return None;
  734. }
  735. resource(this).host.as_deref().map(|h| &h.texture)
  736. }
  737. /// A title texture's host copy, shared, for a list to hold.
  738. #[cfg(windows)]
  739. pub(crate) fn host_copy(this: This) -> Option<std::sync::Arc<HostTexture>> {
  740. if this.is_null() {
  741. return None;
  742. }
  743. resource(this).host.clone()
  744. }
  745. /// A host texture like the title's: same description, in GPU memory,
  746. /// without the console's layout and flags.
  747. #[cfg(windows)]
  748. fn host_texture(
  749. desc: &ResourceDesc,
  750. state: u32,
  751. clear: *const c_void,
  752. ) -> Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
  753. use windows::Win32::Graphics::Direct3D12::*;
  754. const PC_FLAGS: u32 = 0xf; // render target, depth, UAV, no shader access
  755. if desc.dimension == BUFFER {
  756. return None;
  757. }
  758. let host = crate::host::host()?;
  759. let mut d = *desc;
  760. d.layout = 0;
  761. d.alignment = 0;
  762. d.flags &= PC_FLAGS;
  763. // PC refuses depth targets that are also unordered-access (the console
  764. // allows both; Grand Theft Auto VI's shadow maps ask for it).
  765. // shortcut: the host copy loses UAV use; give it a second view-only
  766. // copy if draws write it as a UAV.
  767. const DEPTH: u32 = 2;
  768. const UNORDERED: u32 = 4;
  769. if d.flags & DEPTH != 0 {
  770. d.flags &= !UNORDERED;
  771. }
  772. d.format = pc_format(d.format);
  773. const DENY_SHADER_RESOURCE: u32 = 8;
  774. if d.flags & DENY_SHADER_RESOURCE == 0
  775. && let Some(&(_, typeless)) = DEPTH_FORMATS.iter().find(|&&(f, _)| f == d.format)
  776. {
  777. d.format = typeless;
  778. }
  779. // The host has no sRGB unordered access: such textures are typeless,
  780. // their unordered access views plain UNORM.
  781. if d.flags & UNORDERED != 0 && SRGB.iter().any(|&(srgb, _)| srgb == d.format) {
  782. d.format = family(d.format);
  783. }
  784. // The clear value names the format too: format, then color or depth
  785. // and stencil (5 words).
  786. let clear_value = (!clear.is_null()).then(|| {
  787. // SAFETY: the title passes a whole clear value.
  788. let mut value = unsafe { clear.cast::<[u32; 5]>().read_unaligned() };
  789. value[0] = pc_format(value[0]);
  790. value
  791. });
  792. let heap = D3D12_HEAP_PROPERTIES {
  793. Type: D3D12_HEAP_TYPE_DEFAULT,
  794. ..Default::default()
  795. };
  796. let mut texture: Option<ID3D12Resource> = None;
  797. // SAFETY: the description has the host layout (checked size, same
  798. // fields); the out pointer is ours.
  799. let made = unsafe {
  800. host.device.CreateCommittedResource(
  801. &heap,
  802. D3D12_HEAP_FLAG_NONE,
  803. (&raw const d).cast(),
  804. D3D12_RESOURCE_STATES(
  805. crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32,
  806. ),
  807. // The same layout: format, then color or depth and stencil.
  808. clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()),
  809. &mut texture,
  810. )
  811. };
  812. if let Err(e) = made {
  813. tracing::warn!(error = %e, desc = ?d, "no host texture");
  814. }
  815. if let Some(t) = &texture {
  816. crate::host::name(t, || {
  817. format!("texture {}x{} f{} flags {:#x}", d.width, d.height, d.format, d.flags)
  818. });
  819. }
  820. texture
  821. }
  822. /// A texture's console memory and description; `None` for buffers.
  823. pub(crate) fn texture_memory(this: This) -> Option<(*const u8, ResourceDesc)> {
  824. if this.is_null() {
  825. return None;
  826. }
  827. let r = resource(this);
  828. (r.desc.dimension != BUFFER).then(|| (r.data().cast_const(), r.desc))
  829. }
  830. /// A buffer's host memory and size; `None` for textures.
  831. pub(crate) fn buffer_bytes(this: This) -> Option<(*mut u8, u64)> {
  832. if this.is_null() {
  833. return None;
  834. }
  835. let r = resource(this);
  836. (r.desc.dimension == BUFFER).then(|| (r.data(), r.desc.width))
  837. }
  838. impl Resource {
  839. fn data(&self) -> *mut u8 {
  840. match self.backing {
  841. Backing::Committed(ref memory) => memory.ptr.as_ptr(),
  842. // SAFETY: placement checked the range lies inside the heap.
  843. Backing::Placed { heap, offset } => unsafe {
  844. (*heap.cast::<Heap>())
  845. .memory
  846. .ptr
  847. .as_ptr()
  848. .add(offset as usize)
  849. },
  850. Backing::Address(at) => at,
  851. }
  852. }
  853. }
  854. fn resource<'a>(this: This) -> &'a Resource {
  855. // SAFETY: called from resource methods only.
  856. unsafe { &*this.cast::<Resource>() }
  857. }
  858. // The creation methods' own arguments, passed on.
  859. #[allow(clippy::too_many_arguments)]
  860. fn hand_out_resource(
  861. desc: ResourceDesc,
  862. heap: HeapProperties,
  863. heap_flags: u32,
  864. backing: Backing,
  865. state: u32,
  866. clear: *const c_void,
  867. iid: *const Iid,
  868. out: *mut This,
  869. ) -> HRESULT {
  870. #[cfg(not(windows))]
  871. let _ = (state, clear);
  872. #[cfg(windows)]
  873. let host = host_texture(&desc, state, clear);
  874. let resource = Box::new(Resource {
  875. object: Object::new(&RESOURCE_FUNCTIONS),
  876. desc,
  877. heap,
  878. heap_flags,
  879. backing,
  880. #[cfg(windows)]
  881. host: host.map(|texture| {
  882. let state = crate::host::legal_state(&texture, crate::host::texture_state(state));
  883. std::sync::Arc::new(HostTexture {
  884. texture,
  885. state: state.into(),
  886. })
  887. }),
  888. });
  889. #[cfg(windows)]
  890. if desc.dimension == BUFFER {
  891. let at = std::ptr::from_ref::<Resource>(&resource) as usize;
  892. crate::shadow::register(at, resource.data() as u64, desc.width);
  893. }
  894. object::hand_out(RESOURCE, resource, iid, &RESOURCE_IIDS, out)
  895. }
  896. #[cfg(windows)]
  897. impl Drop for Resource {
  898. fn drop(&mut self) {
  899. #[cfg(feature = "diagnostics")]
  900. if self
  901. .host
  902. .as_ref()
  903. .is_some_and(|h| std::sync::Arc::strong_count(h) > 1)
  904. {
  905. // Before lists held their textures, this freed a texture that
  906. // lists not yet run still named (a GPU page fault).
  907. static OUTLIVED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  908. let n = OUTLIVED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
  909. if n.is_power_of_two() {
  910. tracing::info!(
  911. n,
  912. desc = ?self.desc,
  913. "a title texture was released while a list not yet reset names its host copy"
  914. );
  915. }
  916. }
  917. crate::texture::forget(std::ptr::from_ref::<Resource>(self) as usize);
  918. crate::descriptor::forget(std::ptr::from_ref::<Resource>(self) as usize);
  919. if self.desc.dimension == BUFFER {
  920. crate::shadow::unregister(
  921. std::ptr::from_ref::<Resource>(self) as usize,
  922. self.data() as u64,
  923. );
  924. }
  925. }
  926. }
  927. pub(crate) extern "system" fn create_committed(
  928. _: This,
  929. heap: *const HeapProperties,
  930. heap_flags: u32,
  931. desc: *const ResourceDesc,
  932. state: u32,
  933. clear: *const c_void,
  934. iid: *const Iid,
  935. out: *mut This,
  936. ) -> HRESULT {
  937. // SAFETY: the title passes both descriptions (null is tolerated).
  938. let (Some(&heap), Some(&desc)) = (unsafe { (heap.as_ref(), desc.as_ref()) }) else {
  939. return E_INVALIDARG;
  940. };
  941. let Some(info) = footprint(&desc) else {
  942. tracing::warn!(?desc, "no size for this resource");
  943. return E_INVALIDARG;
  944. };
  945. tracing::debug!(
  946. dimension = desc.dimension,
  947. size = info.size,
  948. heap = heap.kind,
  949. "committed resource"
  950. );
  951. let memory = match Memory::for_resource(info, heap.kind) {
  952. Ok(memory) => memory,
  953. Err(hr) => return hr,
  954. };
  955. hand_out_resource(
  956. desc,
  957. heap,
  958. heap_flags,
  959. Backing::Committed(memory),
  960. state,
  961. clear,
  962. iid,
  963. out,
  964. )
  965. }
  966. /// Device method 0x3f8, inferred from Grand Theft Auto VI's calls
  967. /// (title+0x193e1b4: its back buffers, heap flag "allow display"): the
  968. /// committed resource creation of the enhanced-barrier interfaces,
  969. /// `(heap, heap flags, desc1, initial layout, clear value, protected
  970. /// session, castable format count, castable formats, iid, out)`. The host
  971. /// copy starts in the common state, as layouts are not tracked.
  972. #[allow(clippy::too_many_arguments)] // the method's own arguments
  973. pub(crate) extern "system" fn create_committed3(
  974. this: This,
  975. heap: *const HeapProperties,
  976. heap_flags: u32,
  977. desc: *const ResourceDesc,
  978. _layout: u32,
  979. clear: *const c_void,
  980. _protected: This,
  981. _castable_count: u32,
  982. _castable: *const u32,
  983. iid: *const Iid,
  984. out: *mut This,
  985. ) -> HRESULT {
  986. const COMMON: u32 = 0;
  987. create_committed(this, heap, heap_flags, desc, COMMON, clear, iid, out)
  988. }
  989. /// Registered page pools (64 KiB pages the title maps into tiled
  990. /// resources by page index): first address and page count; a handle is an
  991. /// index plus one, a removed pool leaves `None`.
  992. static PAGE_POOLS: std::sync::Mutex<Vec<Option<(u64, u32)>>> = std::sync::Mutex::new(Vec::new());
  993. fn page_pools() -> std::sync::MutexGuard<'static, Vec<Option<(u64, u32)>>> {
  994. PAGE_POOLS.lock().unwrap_or_else(|e| e.into_inner())
  995. }
  996. /// Device method 0x250: `(address, page count, handle out)`.
  997. pub(crate) extern "system" fn register_page_pool(
  998. _: This,
  999. address: u64,
  1000. pages: u32,
  1001. out: *mut usize,
  1002. ) -> HRESULT {
  1003. if out.is_null() || pages == 0 || !address.is_multiple_of(KIB_64) {
  1004. return E_INVALIDARG;
  1005. }
  1006. tracing::debug!(address = format_args!("{address:#x}"), pages, "page pool");
  1007. let mut pools = page_pools();
  1008. pools.push(Some((address, pages)));
  1009. // SAFETY: checked non-null; the title passes room for a handle.
  1010. unsafe { out.write(pools.len()) };
  1011. S_OK
  1012. }
  1013. /// Device method 0x258.
  1014. pub(crate) extern "system" fn unregister_page_pool(_: This, handle: usize) -> HRESULT {
  1015. match page_pools().get_mut(handle.wrapping_sub(1)) {
  1016. Some(pool @ Some(_)) => {
  1017. *pool = None;
  1018. S_OK
  1019. }
  1020. _ => E_INVALIDARG,
  1021. }
  1022. }
  1023. /// Device method 0x428, one of the `ID3D12Device9` to `ID3D12Device11`
  1024. /// additions. From Grand Theft Auto VI's call: a resource at a virtual
  1025. /// address the title mapped itself, `(address, desc1, initial barrier
  1026. /// layout, clear value, iid, out)`, as `CreatePlacedResourceX` with
  1027. /// enhanced barriers. GPU addresses are CPU addresses, so the resource is
  1028. /// a view of that memory. `D3D12_RESOURCE_DESC1` starts like the plain
  1029. /// description; its sampler feedback region is not needed.
  1030. pub(crate) extern "system" fn create_at_address(
  1031. _: This,
  1032. address: u64,
  1033. desc: *const ResourceDesc,
  1034. layout: u32,
  1035. clear: *const c_void,
  1036. iid: *const Iid,
  1037. out: *mut This,
  1038. ) -> HRESULT {
  1039. // SAFETY: the title passes a description (null is tolerated).
  1040. let Some(&desc) = (unsafe { desc.as_ref() }) else {
  1041. return E_INVALIDARG;
  1042. };
  1043. if address == 0 {
  1044. return E_INVALIDARG;
  1045. }
  1046. tracing::debug!(
  1047. address = format_args!("{address:#x}"),
  1048. dimension = desc.dimension,
  1049. width = desc.width,
  1050. layout,
  1051. "resource at an address"
  1052. );
  1053. const COMMON: u32 = 0;
  1054. const DEFAULT: HeapProperties = HeapProperties {
  1055. kind: 1,
  1056. cpu_pages: 0,
  1057. pool: 0,
  1058. creation_nodes: 1,
  1059. visible_nodes: 1,
  1060. };
  1061. hand_out_resource(
  1062. desc,
  1063. DEFAULT,
  1064. 0,
  1065. Backing::Address(address as *mut u8),
  1066. COMMON,
  1067. clear,
  1068. iid,
  1069. out,
  1070. )
  1071. }
  1072. /// Textures the title placed in its own memory and views without a
  1073. /// resource object (device 0x230, Grand Theft Auto VI's streamed and
  1074. /// interface textures), by address and description: a resource at that
  1075. /// address, made the first time a draw reads one.
  1076. /// shortcut: never released (one host texture per distinct address and
  1077. /// description viewed); release them when the title unmaps or reuses the
  1078. /// memory once streaming grows VRAM use.
  1079. #[cfg(windows)]
  1080. static PLACED_TEXTURES: std::sync::Mutex<std::collections::BTreeMap<(u64, [u32; 14]), usize>> =
  1081. std::sync::Mutex::new(std::collections::BTreeMap::new());
  1082. /// The resource for a texture placed at `address` with the resource
  1083. /// description `desc` (as words), made on first use.
  1084. #[cfg(windows)]
  1085. pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> {
  1086. let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner());
  1087. if let Some(&r) = map.get(&(address, *desc)) {
  1088. return Some(r as This);
  1089. }
  1090. // SAFETY: 56 bytes in the description's layout.
  1091. let d = unsafe { desc.as_ptr().cast::<ResourceDesc>().read_unaligned() };
  1092. if d.dimension == BUFFER {
  1093. return None;
  1094. }
  1095. let mut out = std::ptr::null();
  1096. let made = create_at_address(
  1097. std::ptr::null(),
  1098. address,
  1099. &d,
  1100. 0,
  1101. std::ptr::null(),
  1102. &RESOURCE_IIDS[0],
  1103. &mut out,
  1104. );
  1105. if made != S_OK {
  1106. return None;
  1107. }
  1108. map.insert((address, *desc), out as usize);
  1109. resource(out).host.is_some().then_some(out)
  1110. }
  1111. pub(crate) extern "system" fn create_placed(
  1112. _: This,
  1113. heap: This,
  1114. offset: u64,
  1115. desc: *const ResourceDesc,
  1116. state: u32,
  1117. clear: *const c_void,
  1118. iid: *const Iid,
  1119. out: *mut This,
  1120. ) -> HRESULT {
  1121. // SAFETY: the title passes a description (null is tolerated).
  1122. let Some(&desc) = (unsafe { desc.as_ref() }) else {
  1123. return E_INVALIDARG;
  1124. };
  1125. if heap.is_null() {
  1126. return E_INVALIDARG;
  1127. }
  1128. // SAFETY: the title passes one of our heaps.
  1129. let h = unsafe { &*heap.cast::<Heap>() };
  1130. let fits = footprint(&desc).is_some_and(|info| {
  1131. offset.is_multiple_of(info.alignment)
  1132. && offset
  1133. .checked_add(info.size)
  1134. .is_some_and(|end| end <= h.desc.size)
  1135. });
  1136. if !fits {
  1137. tracing::warn!(
  1138. ?desc,
  1139. offset,
  1140. heap = h.desc.size,
  1141. "placed resource does not fit"
  1142. );
  1143. return E_INVALIDARG;
  1144. }
  1145. object::add_ref(heap);
  1146. let backing = Backing::Placed { heap, offset };
  1147. hand_out_resource(
  1148. desc,
  1149. h.desc.properties,
  1150. h.desc.flags,
  1151. backing,
  1152. state,
  1153. clear,
  1154. iid,
  1155. out,
  1156. )
  1157. }
  1158. extern "system" fn resource_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  1159. object::answer(
  1160. RESOURCE,
  1161. iid,
  1162. object::is(iid, &RESOURCE_IIDS).then_some(this),
  1163. out,
  1164. )
  1165. }
  1166. extern "system" fn resource_release(this: This) -> u32 {
  1167. object::release_boxed::<Resource>(this)
  1168. }
  1169. /// Memory is always mapped (subresources are not told apart yet); a null
  1170. /// `out` only asks for residency.
  1171. extern "system" fn map(this: This, _sub: u32, _read: *const c_void, out: *mut *mut u8) -> HRESULT {
  1172. if !out.is_null() {
  1173. // SAFETY: checked non-null; the title passes room for a pointer.
  1174. unsafe { out.write(resource(this).data()) };
  1175. }
  1176. S_OK
  1177. }
  1178. extern "system" fn unmap(_: This, _sub: u32, _written: *const c_void) {}
  1179. extern "system" fn resource_desc(this: This, out: *mut ResourceDesc) {
  1180. if !out.is_null() {
  1181. // SAFETY: checked non-null; the title passes room for a description.
  1182. unsafe { out.write(resource(this).desc) };
  1183. }
  1184. }
  1185. /// Device method `GetCustomHeapProperties`, returning its struct through a
  1186. /// hidden first argument: what a standard heap type is as a custom heap.
  1187. /// Memory is unified and cache-coherent (as the architecture query says),
  1188. /// so every type is in pool L0, default heaps are not CPU-visible and the
  1189. /// others are write-back.
  1190. pub(crate) extern "system" fn custom_heap_properties(
  1191. out: *mut HeapProperties,
  1192. _: This,
  1193. nodes: u32,
  1194. kind: u32,
  1195. ) -> *mut HeapProperties {
  1196. const CUSTOM: u32 = 4;
  1197. const NOT_AVAILABLE: u32 = 1;
  1198. const WRITE_BACK: u32 = 3;
  1199. const L0: u32 = 1;
  1200. let nodes = nodes.max(1);
  1201. let cpu_pages = match kind {
  1202. 1 => NOT_AVAILABLE,
  1203. 2 | 3 => WRITE_BACK,
  1204. _ => 0,
  1205. };
  1206. let properties = HeapProperties {
  1207. kind: CUSTOM,
  1208. cpu_pages,
  1209. pool: if cpu_pages == 0 { 0 } else { L0 },
  1210. creation_nodes: nodes,
  1211. visible_nodes: nodes,
  1212. };
  1213. // SAFETY: the title passes room for the result (null is tolerated).
  1214. if let Some(out) = unsafe { out.as_mut() } {
  1215. *out = properties;
  1216. }
  1217. out
  1218. }
  1219. extern "system" fn gpu_address(this: This) -> u64 {
  1220. let r = resource(this);
  1221. let at = r.data() as u64;
  1222. // The console's GPU addresses fit in 40 bits; its ray-tracing builder
  1223. // refuses others (diagnostics: which memory breaks that).
  1224. #[cfg(feature = "diagnostics")]
  1225. if at >> 40 != 0 {
  1226. static ONCE: [std::sync::Once; 2] = [std::sync::Once::new(), std::sync::Once::new()];
  1227. let backing = match r.backing {
  1228. Backing::Committed(ref m) => format!("committed, attributes {:?}", m.attributes),
  1229. Backing::Placed { offset, .. } => format!("placed in a heap at {offset:#x}"),
  1230. Backing::Address(_) => "at a title address".into(),
  1231. };
  1232. ONCE[usize::from(r.desc.dimension == BUFFER)].call_once(|| {
  1233. tracing::warn!(address = format_args!("{at:#x}"), backing, desc = ?r.desc, "a GPU address above 40 bits")
  1234. });
  1235. }
  1236. at
  1237. }
  1238. extern "system" fn heap_properties(
  1239. this: This,
  1240. properties: *mut HeapProperties,
  1241. flags: *mut u32,
  1242. ) -> HRESULT {
  1243. let r = resource(this);
  1244. // SAFETY: either pointer may be null; otherwise the title passes room.
  1245. unsafe {
  1246. if let Some(p) = properties.as_mut() {
  1247. *p = r.heap;
  1248. }
  1249. if let Some(f) = flags.as_mut() {
  1250. *f = r.heap_flags;
  1251. }
  1252. }
  1253. S_OK
  1254. }
  1255. /// IUnknown 3, object 4, device child 1, heap 1.
  1256. static HEAP_FUNCTIONS: Table<24> = {
  1257. let mut f = object::d3d12_object(object::missing_table::<HEAP, 24>());
  1258. f[0] = heap_query as *const ();
  1259. f[2] = heap_release as *const ();
  1260. f[7] = object::parent_device as *const (); // 0x38
  1261. f[8] = heap_desc as *const (); // 0x40
  1262. Table(f)
  1263. };
  1264. /// IUnknown 3, object 4, device child 1, resource 10 (7 as on PC, then 3
  1265. /// console ones).
  1266. static RESOURCE_FUNCTIONS: Table<32> = {
  1267. let mut f = object::d3d12_object(object::missing_table::<RESOURCE, 32>());
  1268. f[0] = resource_query as *const ();
  1269. f[2] = resource_release as *const ();
  1270. f[7] = object::parent_device as *const (); // 0x38
  1271. f[8] = map as *const (); // 0x40
  1272. f[9] = unmap as *const (); // 0x48
  1273. f[10] = resource_desc as *const (); // 0x50
  1274. f[11] = gpu_address as *const (); // 0x58
  1275. f[14] = heap_properties as *const (); // 0x70
  1276. Table(f)
  1277. };
  1278. #[cfg(test)]
  1279. mod tests {
  1280. use super::*;
  1281. use crate::object::slot;
  1282. type Release = extern "system" fn(This) -> u32;
  1283. type Map = extern "system" fn(This, u32, *const c_void, *mut *mut u8) -> HRESULT;
  1284. type Address = extern "system" fn(This) -> u64;
  1285. const PROPERTIES: HeapProperties = HeapProperties {
  1286. kind: 1,
  1287. cpu_pages: 0,
  1288. pool: 0,
  1289. creation_nodes: 0,
  1290. visible_nodes: 0,
  1291. };
  1292. fn buffer(width: u64) -> ResourceDesc {
  1293. ResourceDesc {
  1294. dimension: BUFFER,
  1295. alignment: 0,
  1296. width,
  1297. height: 1,
  1298. depth_or_array_size: 1,
  1299. mip_levels: 1,
  1300. format: 0,
  1301. sample_count: 1,
  1302. sample_quality: 0,
  1303. layout: 1,
  1304. flags: 0,
  1305. }
  1306. }
  1307. fn texture(width: u64, height: u32, format: u32, mips: u16) -> ResourceDesc {
  1308. ResourceDesc {
  1309. dimension: 3,
  1310. width,
  1311. height,
  1312. format,
  1313. mip_levels: mips,
  1314. layout: 0,
  1315. ..buffer(0)
  1316. }
  1317. }
  1318. fn heap(size: u64) -> This {
  1319. let desc = HeapDesc {
  1320. size,
  1321. properties: PROPERTIES,
  1322. alignment: 0,
  1323. flags: 0,
  1324. };
  1325. let mut heap = std::ptr::null();
  1326. assert_eq!(
  1327. create_heap(std::ptr::null(), &desc, &HEAP_IIDS[0], &mut heap),
  1328. S_OK
  1329. );
  1330. heap
  1331. }
  1332. #[test]
  1333. fn heaps_are_zeroed_aligned_memory() {
  1334. let heap = heap(1 << 20);
  1335. // SAFETY: a heap we just made.
  1336. let memory = unsafe { &(*heap.cast::<Heap>()).memory };
  1337. assert_eq!(memory.ptr.as_ptr() as u64 % KIB_64, 0);
  1338. let mut back = std::mem::MaybeUninit::<HeapDesc>::uninit();
  1339. slot::<extern "system" fn(This, *mut HeapDesc)>(heap, 0x40)(heap, back.as_mut_ptr());
  1340. // SAFETY: written above.
  1341. assert_eq!(unsafe { back.assume_init() }.size, 1 << 20);
  1342. assert_eq!(slot::<Release>(heap, 0x10)(heap), 0);
  1343. let bad = HeapDesc {
  1344. size: 1 << 20,
  1345. properties: PROPERTIES,
  1346. alignment: 3,
  1347. flags: 0,
  1348. };
  1349. let mut out = std::ptr::null();
  1350. assert_eq!(
  1351. create_heap(std::ptr::null(), &bad, &HEAP_IIDS[0], &mut out),
  1352. E_INVALIDARG
  1353. );
  1354. }
  1355. #[test]
  1356. fn device_setup_heap_properties_and_resources_at_addresses() {
  1357. let device = crate::device::device();
  1358. // GetCustomHeapProperties (0xd0): the struct comes back through the
  1359. // hidden first argument, which is also returned.
  1360. type Custom =
  1361. extern "system" fn(*mut HeapProperties, This, u32, u32) -> *mut HeapProperties;
  1362. let mut p = PROPERTIES;
  1363. let back = slot::<Custom>(device, 0xd0)(&mut p, device, 1, 2);
  1364. assert_eq!(back, &raw mut p);
  1365. assert_eq!(
  1366. (
  1367. p.kind,
  1368. p.cpu_pages,
  1369. p.pool,
  1370. p.creation_nodes,
  1371. p.visible_nodes
  1372. ),
  1373. (4, 3, 1, 1, 1),
  1374. "upload: custom, write-back, L0"
  1375. );
  1376. slot::<Custom>(device, 0xd0)(&mut p, device, 1, 1);
  1377. assert_eq!(p.cpu_pages, 1, "default: not CPU-visible");
  1378. // 0x428: a buffer over memory the title owns, as GTA VI asks.
  1379. type At = extern "system" fn(
  1380. This,
  1381. u64,
  1382. *const ResourceDesc,
  1383. u32,
  1384. *const c_void,
  1385. *const Iid,
  1386. *mut This,
  1387. ) -> HRESULT;
  1388. let memory = vec![0u8; 0x1_0000];
  1389. let address = memory.as_ptr() as u64;
  1390. let mut r = std::ptr::null();
  1391. let create = slot::<At>(device, 0x428);
  1392. let desc = buffer(0x1_0000);
  1393. let null = std::ptr::null();
  1394. assert_eq!(
  1395. create(
  1396. device,
  1397. address,
  1398. &desc,
  1399. u32::MAX,
  1400. null,
  1401. &RESOURCE_IIDS[0],
  1402. &mut r
  1403. ),
  1404. 0
  1405. );
  1406. assert_eq!(slot::<Address>(r, 0x58)(r), address);
  1407. assert_eq!(slot::<Release>(r, 0x10)(r), 0);
  1408. // The title's memory is still there after the release.
  1409. assert_eq!(memory[0xffff], 0);
  1410. assert_ne!(
  1411. create(device, 0, &desc, u32::MAX, null, &RESOURCE_IIDS[0], &mut r),
  1412. 0
  1413. );
  1414. }
  1415. #[test]
  1416. fn sizes_cover_every_mip() {
  1417. let size = |d: &ResourceDesc| footprint(d).map(|i| i.size);
  1418. assert_eq!(size(&buffer(256)), Some(KIB_64));
  1419. // Textures take their console layout and its alignment (4 KiB
  1420. // standard swizzle when the description leaves it to the library):
  1421. // 512x512 BC7 with 10 mips is 0x56000 bytes, 4 KiB aligned, as on
  1422. // the console.
  1423. let layout = |d: &ResourceDesc| texture_layout(d).unwrap().size;
  1424. let rgba = texture(256, 256, 28, 0);
  1425. assert_eq!(size(&rgba), Some(layout(&rgba).next_multiple_of(4096)));
  1426. let bc7 = footprint(&texture(512, 512, 98, 10));
  1427. let console = AllocationInfo {
  1428. size: 0x56000,
  1429. alignment: 0x1000,
  1430. };
  1431. assert_eq!(bc7, Some(console));
  1432. assert!(layout(&rgba) >= 4 * (256 * 256 * 4) / 3, "every mip");
  1433. // BC1 is 8 bytes per 4x4 block: 1024x1024, one mip = 512 KiB.
  1434. assert_eq!(size(&texture(1024, 1024, 71, 1)), Some(512 << 10));
  1435. assert_eq!(size(&texture(16, 16, 66, 1)), None, "1-bit format");
  1436. // Linear layout (1) and an explicit mode (64 KiB display, 0x10a).
  1437. let linear = ResourceDesc {
  1438. layout: 1,
  1439. ..texture(100, 60, 28, 1)
  1440. };
  1441. assert_eq!(
  1442. texture_layout(&linear).unwrap().planes[0]
  1443. .layout
  1444. .desc
  1445. .swizzle
  1446. .0,
  1447. 0
  1448. );
  1449. let display = ResourceDesc {
  1450. layout: 0x10a,
  1451. ..texture(100, 60, 28, 1)
  1452. };
  1453. assert_eq!(
  1454. texture_layout(&display).unwrap().planes[0]
  1455. .layout
  1456. .desc
  1457. .swizzle
  1458. .0,
  1459. 10
  1460. );
  1461. let mut info = AllocationInfo {
  1462. size: 0,
  1463. alignment: 0,
  1464. };
  1465. let descs = [buffer(100), texture(256, 256, 28, 0)];
  1466. allocation_info(&mut info, std::ptr::null(), 0, 2, descs.as_ptr());
  1467. assert_eq!(
  1468. info,
  1469. AllocationInfo {
  1470. size: KIB_64 + size(&descs[1]).unwrap(),
  1471. alignment: KIB_64
  1472. }
  1473. );
  1474. allocation_info(&mut info, std::ptr::null(), 0, 1, &texture(1, 1, 999, 1));
  1475. assert_eq!(info.size, u64::MAX);
  1476. }
  1477. #[test]
  1478. fn upload_footprints_follow_the_pc_rules() {
  1479. let null = std::ptr::null();
  1480. let mut layouts = [NO_FOOTPRINT; 2];
  1481. let (mut rows, mut sizes, mut total) = ([0; 2], [0; 2], 0);
  1482. let mut footprints = |desc: &ResourceDesc, first, count| {
  1483. let (l, r, s) = (layouts.as_mut_ptr(), rows.as_mut_ptr(), sizes.as_mut_ptr());
  1484. copyable_footprints(null, desc, first, count, 0, l, r, s, &mut total);
  1485. (layouts, rows, sizes, total)
  1486. };
  1487. // 100x60 RGBA8, 2 mips: 400-byte rows pitched to 512.
  1488. let (l, r, s, t) = footprints(&texture(100, 60, 28, 2), 0, 2);
  1489. assert_eq!((l[0].row_pitch, r[0], s[0]), (512, 60, 400));
  1490. // Mip 1 (50x30, 200-byte rows) starts after 59 pitched rows and one
  1491. // packed row, rounded up to 512.
  1492. assert_eq!(l[1].offset, (512 * 59 + 400u64).next_multiple_of(512));
  1493. assert_eq!((l[1].width, l[1].height, r[1]), (50, 30, 30));
  1494. assert_eq!(t, l[1].offset + 256 * 29 + 200);
  1495. // BC1: rows of 4x4 blocks, 8 bytes each.
  1496. let (_, r, s, _) = footprints(&texture(64, 64, 71, 1), 0, 1);
  1497. assert_eq!((r[0], s[0]), (16, 128));
  1498. let (_, _, _, t) = footprints(&texture(64, 64, 71, 1), 1, 1);
  1499. assert_eq!(t, u64::MAX, "no second subresource");
  1500. }
  1501. /// A 4x4 texture filled from a title buffer through our list and queue,
  1502. /// then read back from the host GPU.
  1503. #[cfg(windows)]
  1504. #[test]
  1505. fn buffer_data_reaches_the_host_texture() {
  1506. use windows::Win32::Graphics::Direct3D12::*;
  1507. let Some(host) = crate::host::host() else {
  1508. return; // no host GPU here
  1509. };
  1510. let null = std::ptr::null();
  1511. let iid = &RESOURCE_IIDS[0];
  1512. const COPY_DEST: u32 = 0x400;
  1513. let (mut image, mut source) = (null, null);
  1514. let rgba = texture(4, 4, 28, 1);
  1515. assert_eq!(
  1516. create_committed(
  1517. null,
  1518. &PROPERTIES,
  1519. 0,
  1520. &rgba,
  1521. COPY_DEST,
  1522. null.cast(),
  1523. iid,
  1524. &mut image
  1525. ),
  1526. S_OK
  1527. );
  1528. assert_eq!(
  1529. create_committed(
  1530. null,
  1531. &PROPERTIES,
  1532. 0,
  1533. &buffer(1024),
  1534. 0,
  1535. null.cast(),
  1536. iid,
  1537. &mut source
  1538. ),
  1539. S_OK
  1540. );
  1541. let (data, _) = buffer_bytes(source).unwrap();
  1542. // SAFETY: the buffer holds 1024 bytes.
  1543. let bytes = unsafe { std::slice::from_raw_parts_mut(data, 1024) };
  1544. for (i, b) in bytes.iter_mut().enumerate() {
  1545. *b = (i % 251) as u8;
  1546. }
  1547. let queue_iid = guid(
  1548. 0x0ec870a6,
  1549. 0x5d7e,
  1550. 0x4c22,
  1551. [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed],
  1552. );
  1553. let allocator_iid = guid(
  1554. 0x6102dee4,
  1555. 0xaf59,
  1556. 0x4b09,
  1557. [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24],
  1558. );
  1559. let list_iid = guid(
  1560. 0x5b160d0f,
  1561. 0xac1b,
  1562. 0x4185,
  1563. [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55],
  1564. );
  1565. let (mut queue, mut allocator, mut list) = (null, null, null);
  1566. let queue_desc = [0u32; 4];
  1567. assert_eq!(
  1568. crate::queue::create(null, queue_desc.as_ptr().cast(), &queue_iid, &mut queue),
  1569. S_OK
  1570. );
  1571. assert_eq!(
  1572. crate::list::create_allocator(null, 0, &allocator_iid, &mut allocator),
  1573. S_OK
  1574. );
  1575. assert_eq!(
  1576. crate::list::create_list(null, 0, 0, allocator, null, &list_iid, &mut list),
  1577. S_OK
  1578. );
  1579. #[repr(C)]
  1580. struct Location {
  1581. resource: This,
  1582. kind: u32,
  1583. footprint: PlacedFootprint,
  1584. }
  1585. let rows = PlacedFootprint {
  1586. offset: 0,
  1587. format: 28,
  1588. width: 4,
  1589. height: 4,
  1590. depth: 1,
  1591. row_pitch: 256,
  1592. };
  1593. let to = Location {
  1594. resource: image,
  1595. kind: 0,
  1596. footprint: PlacedFootprint { offset: 0, ..rows },
  1597. };
  1598. let from = Location {
  1599. resource: source,
  1600. kind: 1,
  1601. footprint: rows,
  1602. };
  1603. type Copy =
  1604. extern "system" fn(This, *const Location, u32, u32, u32, *const Location, *const u8);
  1605. slot::<Copy>(list, 0x80)(list, &to, 0, 0, 0, &from, null.cast());
  1606. slot::<extern "system" fn(This) -> HRESULT>(list, 0x48)(list);
  1607. slot::<extern "system" fn(This, u32, *const This)>(queue, 0x50)(queue, 1, &list);
  1608. // Read the host texture back into a readback buffer.
  1609. let readback_heap = D3D12_HEAP_PROPERTIES {
  1610. Type: D3D12_HEAP_TYPE_READBACK,
  1611. ..Default::default()
  1612. };
  1613. let readback_desc = D3D12_RESOURCE_DESC {
  1614. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  1615. Width: 1024,
  1616. Height: 1,
  1617. DepthOrArraySize: 1,
  1618. MipLevels: 1,
  1619. SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC {
  1620. Count: 1,
  1621. Quality: 0,
  1622. },
  1623. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  1624. ..Default::default()
  1625. };
  1626. let mut readback: Option<ID3D12Resource> = None;
  1627. // SAFETY: plain creation of a readback buffer.
  1628. unsafe {
  1629. host.device
  1630. .CreateCommittedResource(
  1631. &readback_heap,
  1632. D3D12_HEAP_FLAG_NONE,
  1633. &readback_desc,
  1634. D3D12_RESOURCE_STATE_COPY_DEST,
  1635. None,
  1636. &mut readback,
  1637. )
  1638. .unwrap();
  1639. }
  1640. let readback = readback.unwrap();
  1641. let host_image = host_resource(image).unwrap();
  1642. let back = host.new_list().unwrap();
  1643. let (_, before) = host_transition(image, 0x800).unwrap();
  1644. // The upload list holds the texture until it is reset.
  1645. assert!(std::sync::Arc::strong_count(&host_copy(image).unwrap()) > 2);
  1646. use windows::core::Interface;
  1647. let out_to = Location {
  1648. resource: readback.as_raw().cast_const().cast(),
  1649. kind: 1,
  1650. footprint: rows,
  1651. };
  1652. let out_from = Location {
  1653. resource: host_image.as_raw().cast_const().cast(),
  1654. kind: 0,
  1655. footprint: to.footprint,
  1656. };
  1657. // SAFETY: an open list, live resources, locations in the host layout.
  1658. unsafe {
  1659. back.list.ResourceBarrier(&[crate::host::transition(
  1660. host_image,
  1661. D3D12_RESOURCE_STATES(before as i32),
  1662. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1663. )]);
  1664. back.list.CopyTextureRegion(
  1665. (&raw const out_to).cast(),
  1666. 0,
  1667. 0,
  1668. 0,
  1669. (&raw const out_from).cast(),
  1670. None,
  1671. );
  1672. }
  1673. back.close();
  1674. host.execute(&[&back]);
  1675. let mut mapped = std::ptr::null_mut();
  1676. // SAFETY: the copy finished (execute waits); the buffer is 1024 bytes.
  1677. let read = unsafe {
  1678. readback
  1679. .Map(
  1680. 0,
  1681. Some(&D3D12_RANGE {
  1682. Begin: 0,
  1683. End: 1024,
  1684. }),
  1685. Some(&mut mapped),
  1686. )
  1687. .unwrap();
  1688. std::slice::from_raw_parts(mapped.cast::<u8>(), 1024)
  1689. };
  1690. for row in 0..4 {
  1691. let at = row * 256;
  1692. assert_eq!(read[at..at + 16], bytes[at..at + 16], "row {row}");
  1693. }
  1694. }
  1695. #[test]
  1696. fn committed_and_placed_resources_map_at_their_gpu_address() {
  1697. let null = std::ptr::null();
  1698. let mut committed = null;
  1699. let hr = create_committed(
  1700. null,
  1701. &PROPERTIES,
  1702. 0,
  1703. &buffer(256),
  1704. 0,
  1705. null.cast(),
  1706. &RESOURCE_IIDS[0],
  1707. &mut committed,
  1708. );
  1709. assert_eq!(hr, S_OK);
  1710. let mut data = std::ptr::null_mut();
  1711. assert_eq!(
  1712. slot::<Map>(committed, 0x40)(committed, 0, null.cast(), &mut data),
  1713. S_OK
  1714. );
  1715. assert_eq!(slot::<Address>(committed, 0x58)(committed), data as u64);
  1716. // SAFETY: the buffer is at least 256 zeroed bytes.
  1717. assert_eq!(unsafe { *data.add(255) }, 0);
  1718. assert_eq!(slot::<Release>(committed, 0x10)(committed), 0);
  1719. let heap = heap(4 * KIB_64);
  1720. let place = |offset, desc: &ResourceDesc, out: &mut This| {
  1721. create_placed(
  1722. null,
  1723. heap,
  1724. offset,
  1725. desc,
  1726. 0,
  1727. null.cast(),
  1728. &RESOURCE_IIDS[0],
  1729. out,
  1730. )
  1731. };
  1732. let mut placed = null;
  1733. assert_eq!(place(KIB_64, &buffer(KIB_64), &mut placed), S_OK);
  1734. // SAFETY: a heap we made.
  1735. let base = unsafe { (*heap.cast::<Heap>()).memory.ptr.as_ptr() } as u64;
  1736. assert_eq!(slot::<Address>(placed, 0x58)(placed), base + KIB_64);
  1737. let mut other = null;
  1738. assert_eq!(
  1739. place(4 * KIB_64, &buffer(1), &mut other),
  1740. E_INVALIDARG,
  1741. "past the end"
  1742. );
  1743. assert_eq!(
  1744. place(100, &buffer(1), &mut other),
  1745. E_INVALIDARG,
  1746. "misaligned"
  1747. );
  1748. // The resource keeps the heap alive.
  1749. assert_eq!(slot::<Release>(heap, 0x10)(heap), 1);
  1750. assert_eq!(slot::<Release>(placed, 0x10)(placed), 0);
  1751. }
  1752. }