xg.rs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. //! `xg_xs.dll`: the console's texture layout library. Titles ask it which
  2. //! swizzle mode a texture should use, how large it is, where each mip and
  3. //! slice lies, and to copy linear data into tiled memory and back. Served
  4. //! from `victory_formats::texture`.
  5. //!
  6. //! The title imports `XGCreateTextureComputer` and
  7. //! `XGSuggestSwizzleMode` and calls these computer methods: Release (0x08),
  8. //! the layout (0x10), copies into (0x40) and out of (0x48) a subresource,
  9. //! and the 64 KiB tiling (0x50). The other slots log and fail.
  10. #![allow(non_snake_case)]
  11. // Title code passes pointers the real library would trust.
  12. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  13. use std::sync::atomic::{AtomicU32, Ordering};
  14. use victory_formats::texture::{Dimension, Error, Layout, Swizzle, Texture, TextureDesc};
  15. use super::xasync::{E_INVALIDARG, E_NOTIMPL};
  16. use super::xgameruntime::{HRESULT, S_OK};
  17. use crate::{HleModule, hle_export};
  18. const E_FAIL: HRESULT = 0x8000_4005_u32 as i32;
  19. /// `D3D12_RESOURCE_DESC`, whose layout field carries `0x100 | swizzle
  20. /// mode` on the console (1 row major, 0 "pick one").
  21. #[repr(C)]
  22. #[derive(Debug, Clone, Copy)]
  23. pub struct ResourceDesc {
  24. pub dimension: u32,
  25. pub alignment: u64,
  26. pub width: u64,
  27. pub height: u32,
  28. pub depth_or_array: u16,
  29. pub mips: u16,
  30. pub format: u32,
  31. pub samples: u32,
  32. pub quality: u32,
  33. pub layout: u32,
  34. pub flags: u32,
  35. }
  36. const _: () = assert!(size_of::<ResourceDesc>() == 0x38);
  37. const SWIZZLED: u32 = 0x100;
  38. const ROW_MAJOR: u32 = 1;
  39. const ALLOW_RENDER_TARGET: u32 = 1;
  40. const ALLOW_DEPTH_STENCIL: u32 = 2;
  41. const TEXTURE_1D: u32 = 2;
  42. const TEXTURE_3D: u32 = 4;
  43. /// The mode the console's library picks for a description: linear for 1D,
  44. /// the XOR render and depth modes for targets, else 4 KiB standard
  45. /// (`.ttpf` textures without a mode of their own use it).
  46. ///
  47. /// shortcut: the rule of the library's older optimal-mode function (any
  48. /// size, 2D, 3D and cubes alike); `XGSuggestSwizzleMode` itself is newer
  49. /// than every copy we could check. Revisit if streamed textures come out
  50. /// scrambled.
  51. fn suggested(desc: &ResourceDesc) -> Swizzle {
  52. if desc.dimension == TEXTURE_1D {
  53. Swizzle::LINEAR
  54. } else if desc.flags & ALLOW_DEPTH_STENCIL != 0 {
  55. Swizzle::SW_64KB_Z_X
  56. } else if desc.flags & ALLOW_RENDER_TARGET != 0 {
  57. Swizzle::SW_64KB_R_X
  58. } else {
  59. Swizzle::SW_4KB_S
  60. }
  61. }
  62. /// `(desc, flags, out layout)`; the title passes flags 0 and puts the
  63. /// result in the description's layout field.
  64. pub extern "system" fn XGSuggestSwizzleMode(
  65. desc: *const ResourceDesc,
  66. _flags: u32,
  67. out: *mut u32,
  68. ) -> HRESULT {
  69. // SAFETY: the title passes a description and room for the layout
  70. // (either may be null).
  71. match unsafe { (desc.as_ref(), out.as_mut()) } {
  72. (Some(desc), Some(out)) => {
  73. *out = SWIZZLED | suggested(desc).0;
  74. S_OK
  75. }
  76. _ => E_INVALIDARG,
  77. }
  78. }
  79. #[repr(C)]
  80. pub struct Computer {
  81. vtable: &'static Vtable,
  82. refs: AtomicU32,
  83. desc: ResourceDesc,
  84. mips: u32,
  85. texture: Texture,
  86. }
  87. type This = *mut Computer;
  88. fn computer<'a>(this: This) -> &'a Computer {
  89. // SAFETY: called from computer methods only.
  90. unsafe { &*this }
  91. }
  92. pub extern "system" fn XGCreateTextureComputer(
  93. desc: *const ResourceDesc,
  94. out: *mut This,
  95. ) -> HRESULT {
  96. // SAFETY: the title passes a description and room for a pointer.
  97. let (Some(&desc), false) = (unsafe { desc.as_ref() }, out.is_null()) else {
  98. return E_INVALIDARG;
  99. };
  100. let Some(texture) = texture(&desc) else {
  101. tracing::warn!(?desc, "no texture layout");
  102. return E_INVALIDARG;
  103. };
  104. tracing::debug!(
  105. width = desc.width,
  106. height = desc.height,
  107. format = desc.format,
  108. layout = format_args!("{:#x}", desc.layout),
  109. size = texture.size,
  110. "texture computer"
  111. );
  112. let mips = texture.planes[0].layout.mips.len() as u32;
  113. let computer = Box::new(Computer {
  114. vtable: &VTABLE,
  115. refs: AtomicU32::new(1),
  116. desc,
  117. mips,
  118. texture,
  119. });
  120. // SAFETY: checked non-null.
  121. unsafe { out.write(Box::into_raw(computer)) };
  122. S_OK
  123. }
  124. fn texture(desc: &ResourceDesc) -> Option<Texture> {
  125. let dimension = match desc.dimension {
  126. TEXTURE_1D => Dimension::Tex1d,
  127. 3 => Dimension::Tex2d,
  128. TEXTURE_3D => Dimension::Tex3d,
  129. _ => return None,
  130. };
  131. let swizzle = match desc.layout {
  132. 0 => suggested(desc),
  133. ROW_MAJOR => Swizzle::LINEAR,
  134. l if l & !0xff == SWIZZLED => Swizzle(l & 0xff),
  135. _ => return None,
  136. };
  137. let texture = Texture::new(&TextureDesc {
  138. dimension,
  139. width: u32::try_from(desc.width).ok()?,
  140. height: desc.height,
  141. depth_or_array: u32::from(desc.depth_or_array),
  142. mips: u32::from(desc.mips),
  143. format: desc.format,
  144. samples: desc.samples.max(1),
  145. swizzle,
  146. })
  147. .ok()?;
  148. // The layout struct has room for 15 mips.
  149. (texture.planes[0].layout.mips.len() <= MIPS).then_some(texture)
  150. }
  151. const MIPS: usize = 15;
  152. /// One mip in the layout the title reads (offsets 0x00, 0x08, 0x10 and
  153. /// 0x1c are read by the title; the rest follow the library's
  154. /// older public shape).
  155. #[repr(C)]
  156. #[derive(Debug, Default, Clone, Copy)]
  157. pub struct MipOut {
  158. pub size: u64,
  159. pub offset: u64,
  160. pub slice_size: u64,
  161. pub pitch_texels: u32,
  162. pub pitch_bytes: u32,
  163. pub alignment: u32,
  164. /// Width, height in elements, depth or array size.
  165. pub padded: [u32; 3],
  166. pub elements: [u32; 2],
  167. pub texels: [u32; 2],
  168. pub depth_or_array: u32,
  169. pub samples: u32,
  170. pub swizzle: u32,
  171. pub bank_rotation: [u64; 2],
  172. pub slice_depth: u32,
  173. pub in_tail: u32,
  174. /// Where a tail mip starts in elements: x bits 0-10, y 11-21.
  175. pub tail_position: u32,
  176. }
  177. #[repr(C)]
  178. #[derive(Debug, Clone, Copy)]
  179. pub struct PlaneOut {
  180. /// 1 data, 7 depth, 8 stencil (metadata planes are not made).
  181. pub usage: u32,
  182. pub size: u64,
  183. pub slice_size: u64,
  184. pub offset: u64,
  185. pub alignment: u64,
  186. pub element_bytes: u32,
  187. pub standard_mips: u32,
  188. pub tail_mips: u32,
  189. pub mips: [MipOut; MIPS],
  190. }
  191. #[repr(C)]
  192. #[derive(Debug, Clone, Copy)]
  193. pub struct LayoutOut {
  194. pub size: u64,
  195. pub alignment: u64,
  196. pub mips: u32,
  197. pub planes: u32,
  198. pub plane: [PlaneOut; 4],
  199. pub dimension: u32,
  200. }
  201. const _: () = assert!(size_of::<MipOut>() == 0x70);
  202. const _: () = assert!(size_of::<PlaneOut>() == 0x6c8);
  203. const _: () = assert!(size_of::<LayoutOut>() == 0x1b40);
  204. /// The mode a tail mip is reported in: the 256-byte one of its kind (3 for
  205. /// the render kind, which GFX10 lacks), the depth mode itself.
  206. fn tail_swizzle(swizzle: Swizzle) -> u32 {
  207. match swizzle.0 {
  208. 2 | 6 | 10 | 18 | 22 | 26 => Swizzle::SW_256B_D.0,
  209. 23 | 27 => 3,
  210. 24 => swizzle.0,
  211. _ => Swizzle::SW_256B_S.0,
  212. }
  213. }
  214. fn mip_out(desc: &ResourceDesc, l: &Layout, i: usize) -> MipOut {
  215. let m = &l.mips[i];
  216. let bpe = u64::from(l.desc.element_bytes);
  217. let block = l.desc.block;
  218. let three_d = desc.dimension == TEXTURE_3D;
  219. let array = u32::from(desc.depth_or_array).max(1);
  220. let mut out = MipOut {
  221. pitch_texels: m.pitch * block,
  222. pitch_bytes: m.pitch * l.desc.element_bytes,
  223. padded: [m.pitch, m.rows, if three_d { m.depth_pitch } else { array }],
  224. elements: [m.width, m.height],
  225. texels: [((desc.width >> i) as u32).max(1), (desc.height >> i).max(1)],
  226. depth_or_array: if three_d { m.depth } else { array },
  227. samples: l.desc.samples,
  228. slice_depth: l.block[2],
  229. ..MipOut::default()
  230. };
  231. let slice = u64::from(m.pitch) * u64::from(m.rows) * bpe;
  232. let depth = u64::from(if three_d { m.depth_pitch } else { 1 });
  233. match m.tail {
  234. None => {
  235. out.offset = m.offset;
  236. out.slice_size = slice * u64::from(l.desc.samples);
  237. out.size = out.slice_size * depth;
  238. out.alignment = l.alignment as u32;
  239. out.swizzle = l.desc.swizzle.0;
  240. }
  241. Some(t) => {
  242. out.in_tail = 1;
  243. out.alignment = 256;
  244. out.swizzle = tail_swizzle(l.desc.swizzle);
  245. if l.thick {
  246. // A 3D tail mip is placed by position, not by offset.
  247. out.slice_size = l.alignment / u64::from(l.block[2]);
  248. out.tail_position = t.x | t.y << 11;
  249. } else {
  250. out.offset = u64::from(t.offset);
  251. out.slice_size = slice;
  252. }
  253. out.size = out.slice_size * depth;
  254. }
  255. }
  256. out
  257. }
  258. extern "system" fn add_ref(this: This) -> u32 {
  259. computer(this).refs.fetch_add(1, Ordering::Relaxed) + 1
  260. }
  261. extern "system" fn release(this: This) -> u32 {
  262. let left = computer(this).refs.fetch_sub(1, Ordering::AcqRel) - 1;
  263. if left == 0 {
  264. // SAFETY: made by `Box::into_raw` in `XGCreateTextureComputer`; the
  265. // last reference is gone.
  266. drop(unsafe { Box::from_raw(this) });
  267. }
  268. left
  269. }
  270. extern "system" fn layout(this: This, out: *mut LayoutOut) -> HRESULT {
  271. if out.is_null() {
  272. return E_INVALIDARG;
  273. }
  274. let c = computer(this);
  275. // SAFETY: the title passes room for the layout; every field is plain
  276. // data, so zeroes are a valid start.
  277. let out = unsafe {
  278. out.write_bytes(0, 1);
  279. &mut *out
  280. };
  281. out.size = c.texture.size;
  282. out.alignment = c.texture.alignment;
  283. out.mips = c.mips;
  284. out.planes = c.texture.planes.len() as u32;
  285. out.dimension = c.desc.dimension;
  286. // The library calls a depth plane "depth" only beside stencil or
  287. // without mips.
  288. let depth =
  289. c.desc.flags & ALLOW_DEPTH_STENCIL != 0 && (c.texture.planes.len() > 1 || c.mips == 1);
  290. for (plane, p) in out.plane.iter_mut().zip(&c.texture.planes) {
  291. let l = &p.layout;
  292. plane.usage = match (p.stencil, depth) {
  293. (true, _) => 8,
  294. (false, true) => 7,
  295. (false, false) => 1,
  296. };
  297. plane.size = l.size;
  298. plane.slice_size = l.slice_size;
  299. plane.offset = p.offset;
  300. plane.alignment = l.alignment;
  301. plane.element_bytes = l.desc.element_bytes;
  302. plane.standard_mips = l.first_tail_mip;
  303. plane.tail_mips = c.mips - l.first_tail_mip;
  304. for (i, mip) in plane.mips.iter_mut().take(l.mips.len()).enumerate() {
  305. *mip = mip_out(&c.desc, l, i);
  306. }
  307. }
  308. S_OK
  309. }
  310. /// The plane, its mip and array slice for a subresource index, and the
  311. /// tiled bytes and the linear bytes the copy touches.
  312. struct CopyArgs<'a> {
  313. layout: &'a Layout,
  314. mip: u32,
  315. slice: u32,
  316. tiled: usize,
  317. linear: usize,
  318. }
  319. fn copy_args(
  320. c: &Computer,
  321. plane: u32,
  322. subresource: u32,
  323. row: u32,
  324. depth: u32,
  325. ) -> Option<CopyArgs<'_>> {
  326. let p = c.texture.planes.get(plane as usize)?;
  327. let l = &p.layout;
  328. let (mip, slice) = (subresource % c.mips, subresource / c.mips);
  329. let m = l.mips.get(mip as usize)?;
  330. let bytes = m.width as usize * l.desc.element_bytes as usize;
  331. let depths = l.subresource_depth(mip) as usize;
  332. let linear = (depths - 1) * depth as usize + (m.height as usize - 1) * row as usize + bytes;
  333. Some(CopyArgs {
  334. layout: l,
  335. mip,
  336. slice,
  337. tiled: (p.offset + l.size) as usize,
  338. linear,
  339. })
  340. }
  341. fn result(r: Result<(), Error>) -> HRESULT {
  342. match r {
  343. Ok(()) => S_OK,
  344. Err(Error::Unsupported) => E_NOTIMPL,
  345. Err(_) => E_INVALIDARG,
  346. }
  347. }
  348. /// `(tiled base, plane, subresource, linear, row pitch, depth pitch)`.
  349. extern "system" fn copy_into(
  350. this: This,
  351. tiled: *mut u8,
  352. plane: u32,
  353. subresource: u32,
  354. linear: *const u8,
  355. row: u32,
  356. depth: u32,
  357. ) -> HRESULT {
  358. let c = computer(this);
  359. let Some(a) = copy_args(c, plane, subresource, row, depth) else {
  360. return E_INVALIDARG;
  361. };
  362. if tiled.is_null() || linear.is_null() {
  363. return E_INVALIDARG;
  364. }
  365. let offset = c.texture.planes[plane as usize].offset as usize;
  366. // SAFETY: the title's memory holds the whole texture and its rows.
  367. let (tiled, linear) = unsafe {
  368. (
  369. std::slice::from_raw_parts_mut(tiled.add(offset), a.tiled - offset),
  370. std::slice::from_raw_parts(linear, a.linear),
  371. )
  372. };
  373. let r = a
  374. .layout
  375. .tile(tiled, a.mip, a.slice, linear, row as usize, depth as usize);
  376. if r.is_err() {
  377. tracing::warn!(?r, desc = ?c.desc, subresource, "copy into a texture failed");
  378. }
  379. result(r)
  380. }
  381. /// `(linear, plane, subresource, sample, tiled base, row pitch, depth
  382. /// pitch)`.
  383. #[allow(clippy::too_many_arguments)]
  384. extern "system" fn copy_from(
  385. this: This,
  386. linear: *mut u8,
  387. plane: u32,
  388. subresource: u32,
  389. _sample: u32,
  390. tiled: *const u8,
  391. row: u32,
  392. depth: u32,
  393. ) -> HRESULT {
  394. let c = computer(this);
  395. let Some(a) = copy_args(c, plane, subresource, row, depth) else {
  396. return E_INVALIDARG;
  397. };
  398. if tiled.is_null() || linear.is_null() {
  399. return E_INVALIDARG;
  400. }
  401. let offset = c.texture.planes[plane as usize].offset as usize;
  402. // SAFETY: the title's memory holds the whole texture and its rows.
  403. let (tiled, linear) = unsafe {
  404. (
  405. std::slice::from_raw_parts(tiled.add(offset), a.tiled - offset),
  406. std::slice::from_raw_parts_mut(linear, a.linear),
  407. )
  408. };
  409. let r = a
  410. .layout
  411. .detile(tiled, a.mip, a.slice, linear, row as usize, depth as usize);
  412. if r.is_err() {
  413. tracing::warn!(?r, desc = ?c.desc, subresource, "copy out of a texture failed");
  414. }
  415. result(r)
  416. }
  417. #[repr(C)]
  418. pub struct PackedMips {
  419. pub standard: u8,
  420. pub packed: u8,
  421. pub tiles: u32,
  422. pub start: u32,
  423. }
  424. #[repr(C)]
  425. pub struct SubresourceTiling {
  426. pub width: u32,
  427. pub height: u16,
  428. pub depth: u16,
  429. pub start: u32,
  430. }
  431. const TILE: u64 = 64 << 10;
  432. /// `(total tiles, packed mips, tile shape in texels, in: room / out:
  433. /// count, first, subresource tilings)`, in 64 KiB tiles of plane 0, for 2D
  434. /// 64 KiB modes only (others fail, as on the console). The mip tail is the
  435. /// packed part, tile 0 of each slice; tilings list the standard mips of
  436. /// every slice in turn. With a tail the console's library lists two slices
  437. /// at most and zeroes all but the first; so do we (the title reads slice 0
  438. /// only).
  439. extern "system" fn tiling(
  440. this: This,
  441. tiles: *mut u32,
  442. packed: *mut PackedMips,
  443. shape: *mut [u32; 3],
  444. count: *mut u32,
  445. first: u32,
  446. out: *mut SubresourceTiling,
  447. ) -> HRESULT {
  448. let c = computer(this);
  449. let l = &c.texture.planes[0].layout;
  450. if l.alignment != TILE {
  451. return E_FAIL;
  452. }
  453. if l.thick {
  454. return E_NOTIMPL;
  455. }
  456. let standard = l.first_tail_mip;
  457. let tail = standard < c.mips;
  458. let tail_tiles = match standard {
  459. 0 => l.slice_size / TILE,
  460. s if s < c.mips => l.mips[s as usize - 1].offset / TILE,
  461. _ => 0,
  462. };
  463. let block = l.desc.block;
  464. // SAFETY: each output is null or room for its value; `out` has room
  465. // for `*count` entries.
  466. unsafe {
  467. if let Some(t) = tiles.as_mut() {
  468. *t = (l.size / TILE) as u32;
  469. }
  470. if let Some(p) = packed.as_mut() {
  471. *p = PackedMips {
  472. standard: standard as u8,
  473. packed: (c.mips - standard) as u8,
  474. tiles: tail_tiles as u32,
  475. start: 0,
  476. };
  477. }
  478. if let Some(s) = shape.as_mut() {
  479. *s = [l.block[0] * block, l.block[1] * block, l.block[2]];
  480. }
  481. if let Some(n) = count.as_mut() {
  482. let slices = if tail { l.slices.min(2) } else { l.slices };
  483. let wanted = (standard * slices).saturating_sub(first).min(*n);
  484. for i in 0..wanted {
  485. let (slice, mip) = ((first + i) / standard, (first + i) % standard);
  486. let m = &l.mips[mip as usize];
  487. let entry = if tail && slice > 0 {
  488. SubresourceTiling {
  489. width: 0,
  490. height: 0,
  491. depth: 0,
  492. start: 0,
  493. }
  494. } else {
  495. SubresourceTiling {
  496. width: m.pitch / l.block[0],
  497. height: (m.rows / l.block[1]) as u16,
  498. depth: 1,
  499. start: ((u64::from(slice) * l.slice_size + m.offset) / TILE) as u32,
  500. }
  501. };
  502. out.add(i as usize).write(entry);
  503. }
  504. *n = wanted;
  505. }
  506. }
  507. S_OK
  508. }
  509. /// Slot 0x30 `(plane, mip, x, y, z or slice, sample, bit position)`: an
  510. /// element's byte offset from the texture's start. The title reads
  511. /// texels of a 128x4 `4KB_S` texture on the CPU through it (title+0x5151c90);
  512. /// an error returned as an offset made it read wild memory. 0 if outside.
  513. extern "system" fn element_offset(
  514. this: This,
  515. plane: u32,
  516. mip: u32,
  517. x: u64,
  518. y: u32,
  519. z: u32,
  520. _sample: u32,
  521. bit: *mut u32,
  522. ) -> u64 {
  523. if !bit.is_null() {
  524. // SAFETY: the caller passes room for the bit position or null.
  525. unsafe { bit.write(0) };
  526. }
  527. let Some(p) = computer(this).texture.planes.get(plane as usize) else {
  528. return 0;
  529. };
  530. let x = u32::try_from(x).unwrap_or(u32::MAX);
  531. match p.layout.offset(mip, x, y, z) {
  532. Ok(at) => p.offset + at,
  533. Err(e) => {
  534. tracing::warn!(?e, mip, x, y, z, "texel outside its texture");
  535. 0
  536. }
  537. }
  538. }
  539. /// Slots the title does not call: size, alignment, offsets, coordinates,
  540. /// view descriptor, tiled-resource query.
  541. extern "system" fn unused(this: This) -> HRESULT {
  542. tracing::warn!(desc = ?computer(this).desc, "unimplemented texture computer method");
  543. E_NOTIMPL
  544. }
  545. #[repr(C)]
  546. struct Vtable([*const (); 13]);
  547. // SAFETY: function addresses only.
  548. unsafe impl Sync for Vtable {}
  549. static VTABLE: Vtable = Vtable([
  550. add_ref as *const (), // 0x00
  551. release as *const (), // 0x08
  552. layout as *const (), // 0x10
  553. unused as *const (), // 0x18 size
  554. unused as *const (), // 0x20 alignment
  555. unused as *const (), // 0x28 mip offset
  556. element_offset as *const (), // 0x30
  557. unused as *const (), // 0x38 element coordinate
  558. copy_into as *const (), // 0x40
  559. copy_from as *const (), // 0x48
  560. tiling as *const (), // 0x50
  561. unused as *const (), // 0x58 view descriptor
  562. unused as *const (), // 0x60 tiled resource?
  563. ]);
  564. pub(crate) fn module() -> HleModule {
  565. HleModule {
  566. name: "xg",
  567. dlls: &["xg_xs.dll"],
  568. exports: vec![
  569. hle_export!(XGCreateTextureComputer),
  570. hle_export!(XGSuggestSwizzleMode),
  571. ],
  572. }
  573. }
  574. #[cfg(test)]
  575. mod tests {
  576. use super::*;
  577. fn desc(width: u64, height: u32, mips: u16, format: u32, layout: u32) -> ResourceDesc {
  578. ResourceDesc {
  579. dimension: 3,
  580. alignment: 0,
  581. width,
  582. height,
  583. depth_or_array: 1,
  584. mips,
  585. format,
  586. samples: 1,
  587. quality: 0,
  588. layout,
  589. flags: 0,
  590. }
  591. }
  592. /// Method `index` of a computer, as the title calls it.
  593. fn slot<T: Copy>(c: This, index: usize) -> T {
  594. // SAFETY: the computer is live; T is the slot's function type.
  595. unsafe { std::mem::transmute_copy(&(*c).vtable.0[index]) }
  596. }
  597. fn create(d: &ResourceDesc) -> This {
  598. let mut c = std::ptr::null_mut();
  599. assert_eq!(XGCreateTextureComputer(d, &mut c), S_OK);
  600. c
  601. }
  602. /// Element offsets: linear rows of 1 KiB (128 elements), 0 outside.
  603. #[test]
  604. fn element_offsets_follow_the_layout() {
  605. type Offset = extern "system" fn(This, u32, u32, u64, u32, u32, u32, *mut u32) -> u64;
  606. let c = create(&desc(128, 4, 1, 11, 0x100));
  607. let offset: Offset = slot(c, 6);
  608. let mut bit = 7;
  609. assert_eq!(offset(c, 0, 0, 3, 1, 0, 0, &mut bit), (128 + 3) * 8);
  610. assert_eq!(bit, 0);
  611. assert_eq!(offset(c, 0, 0, 128, 0, 0, 0, std::ptr::null_mut()), 0);
  612. slot::<extern "system" fn(This) -> u32>(c, 1)(c);
  613. }
  614. #[test]
  615. fn suggestions_follow_the_use() {
  616. let mut out = 0;
  617. let mut d = desc(256, 256, 1, 98, 0);
  618. assert_eq!(XGSuggestSwizzleMode(&d, 0, &mut out), S_OK);
  619. assert_eq!(out, 0x105);
  620. d.flags = ALLOW_RENDER_TARGET;
  621. XGSuggestSwizzleMode(&d, 0, &mut out);
  622. assert_eq!(out, 0x11b);
  623. d.flags = ALLOW_DEPTH_STENCIL;
  624. XGSuggestSwizzleMode(&d, 0, &mut out);
  625. assert_eq!(out, 0x118);
  626. // A 1D texture has no tiled layout, whatever its use.
  627. d.dimension = TEXTURE_1D;
  628. XGSuggestSwizzleMode(&d, 0, &mut out);
  629. assert_eq!(out, 0x100);
  630. }
  631. /// The title's calls: layout, then a copy in and out of each mip.
  632. #[test]
  633. fn layout_and_copies_through_the_object() {
  634. // 256x256 BC7, full chain, 64 KiB display mode.
  635. let c = create(&desc(256, 256, 0, 98, 0x10a));
  636. // SAFETY: plain data, filled by the call.
  637. let mut l: Box<LayoutOut> = Box::new(unsafe { std::mem::zeroed() });
  638. let get: extern "system" fn(This, *mut LayoutOut) -> HRESULT = slot(c, 2);
  639. assert_eq!(get(c, &mut *l), S_OK);
  640. assert_eq!(
  641. (l.size, l.alignment, l.mips, l.planes),
  642. (131072, 65536, 9, 1)
  643. );
  644. let p = &l.plane[0];
  645. assert_eq!((p.standard_mips, p.tail_mips, p.element_bytes), (1, 8, 16));
  646. assert_eq!((p.mips[0].offset, p.mips[0].pitch_bytes), (65536, 1024));
  647. assert_eq!((p.mips[1].offset, p.mips[1].in_tail), (32768, 1));
  648. type Into = extern "system" fn(This, *mut u8, u32, u32, *const u8, u32, u32) -> HRESULT;
  649. type From =
  650. extern "system" fn(This, *mut u8, u32, u32, u32, *const u8, u32, u32) -> HRESULT;
  651. let (into, from): (Into, From) = (slot(c, 8), slot(c, 9));
  652. let mut tiled = vec![0u8; l.size as usize];
  653. for mip in 0..9u32 {
  654. let m = &p.mips[mip as usize];
  655. let row = m.elements[0] * 16;
  656. let rows: Vec<u8> = (0..row * m.elements[1]).map(|i| (i ^ mip) as u8).collect();
  657. assert_eq!(
  658. into(c, tiled.as_mut_ptr(), 0, mip, rows.as_ptr(), row, 0),
  659. S_OK
  660. );
  661. let mut back = vec![0u8; rows.len()];
  662. assert_eq!(
  663. from(c, back.as_mut_ptr(), 0, mip, 0, tiled.as_ptr(), row, 0),
  664. S_OK
  665. );
  666. assert_eq!(back, rows, "mip {mip}");
  667. }
  668. // 0x50: one tile for the tail, one for mip 0.
  669. type Tiling = extern "system" fn(
  670. This,
  671. *mut u32,
  672. *mut PackedMips,
  673. *mut [u32; 3],
  674. *mut u32,
  675. u32,
  676. *mut SubresourceTiling,
  677. ) -> HRESULT;
  678. let tiling: Tiling = slot(c, 10);
  679. let (mut tiles, mut shape, mut n) = (0, [0; 3], 4);
  680. let mut packed = PackedMips {
  681. standard: 0,
  682. packed: 0,
  683. tiles: 0,
  684. start: 0,
  685. };
  686. let mut subs: Vec<SubresourceTiling> = (0..4)
  687. .map(|_| SubresourceTiling {
  688. width: 0,
  689. height: 0,
  690. depth: 0,
  691. start: 0,
  692. })
  693. .collect();
  694. assert_eq!(
  695. tiling(
  696. c,
  697. &mut tiles,
  698. &mut packed,
  699. &mut shape,
  700. &mut n,
  701. 0,
  702. subs.as_mut_ptr()
  703. ),
  704. S_OK
  705. );
  706. assert_eq!(
  707. (tiles, packed.standard, packed.packed, packed.tiles),
  708. (2, 1, 8, 1)
  709. );
  710. assert_eq!((shape, n, subs[0].start), ([256, 256, 1], 1, 1));
  711. assert_eq!(release(c), 0);
  712. // 4 KiB modes have no 64 KiB tiling.
  713. let null = std::ptr::null_mut::<u8>();
  714. let c = create(&desc(256, 256, 0, 98, 0x105));
  715. assert_eq!(
  716. tiling(
  717. c,
  718. &mut tiles,
  719. null.cast(),
  720. null.cast(),
  721. null.cast(),
  722. 0,
  723. null.cast()
  724. ),
  725. E_FAIL
  726. );
  727. assert_eq!(release(c), 0);
  728. }
  729. #[test]
  730. fn bad_descriptions_fail() {
  731. let mut c = std::ptr::null_mut();
  732. let bad = desc(256, 256, 1, 0, 0x10a);
  733. assert_eq!(XGCreateTextureComputer(&bad, &mut c), E_INVALIDARG);
  734. let bad = desc(256, 256, 1, 28, 0x103);
  735. assert_eq!(XGCreateTextureComputer(&bad, &mut c), E_INVALIDARG);
  736. assert!(module().exports.len() == 2);
  737. }
  738. }