texture.rs 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. //! Texture layouts of the console GPU (RDNA2, GFX10.3): a texture's size and
  2. //! alignment, where each mip and array slice starts, the address of each
  3. //! element, and copies between tiled memory and linear rows.
  4. //!
  5. //! Units: an element is a texel, or a 4x4 block of a block-compressed
  6. //! format. Mips of one array slice (or one depth slab of a thick 3D texture)
  7. //! are stored together, smallest first: the mip tail (the small mips sharing
  8. //! one block) at offset 0, mip 0 last.
  9. //!
  10. //! The algorithm follows AMD's address library (addrlib), as shipped in Mesa
  11. //! under `src/amd/addrlib`: block dimensions, mip placement and mip tails
  12. //! from `gfx10addrlib.cpp` and `addrlib2.cpp`
  13. //! (`ComputeSurfaceInfoMacroTiled`, `ComputeThinBlockDimension`,
  14. //! `GetMipTailDim`, `GetMaxNumMipsInTail`, `HwlComputeSurfaceInfoLinear`,
  15. //! `ComputeSurfaceAddrFromCoordMacroTiled`), and the 256-byte micro tile
  16. //! patterns in [`MICRO`] from `gfx10SwizzlePattern.h` (the RB+ tables, as on
  17. //! RDNA2). addrlib carries this notice:
  18. //!
  19. //! Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved.
  20. //! SPDX-License-Identifier: MIT
  21. //!
  22. //! Permission is hereby granted, free of charge, to any person obtaining a
  23. //! copy of this software and associated documentation files (the
  24. //! "Software"), to deal in the Software without restriction, including
  25. //! without limitation the rights to use, copy, modify, merge, publish,
  26. //! distribute, sublicense, and/or sell copies of the Software, and to permit
  27. //! persons to whom the Software is furnished to do so, subject to the
  28. //! following conditions: the above copyright notice and this permission
  29. //! notice shall be included in all copies or substantial portions of the
  30. //! Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  31. //! EXPRESS OR IMPLIED.
  32. /// A swizzle mode, by its hardware number (addrlib's `ADDR_SW_*` order).
  33. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  34. pub struct Swizzle(pub u32);
  35. impl Swizzle {
  36. pub const LINEAR: Swizzle = Swizzle(0);
  37. pub const SW_256B_S: Swizzle = Swizzle(1);
  38. pub const SW_256B_D: Swizzle = Swizzle(2);
  39. pub const SW_4KB_S: Swizzle = Swizzle(5);
  40. pub const SW_4KB_D: Swizzle = Swizzle(6);
  41. pub const SW_64KB_S: Swizzle = Swizzle(9);
  42. pub const SW_64KB_D: Swizzle = Swizzle(10);
  43. pub const SW_64KB_S_T: Swizzle = Swizzle(17);
  44. pub const SW_64KB_D_T: Swizzle = Swizzle(18);
  45. pub const SW_4KB_S_X: Swizzle = Swizzle(21);
  46. pub const SW_4KB_D_X: Swizzle = Swizzle(22);
  47. pub const SW_4KB_R_X: Swizzle = Swizzle(23);
  48. pub const SW_64KB_Z_X: Swizzle = Swizzle(24);
  49. pub const SW_64KB_S_X: Swizzle = Swizzle(25);
  50. pub const SW_64KB_D_X: Swizzle = Swizzle(26);
  51. pub const SW_64KB_R_X: Swizzle = Swizzle(27);
  52. /// log2 of the block size in bytes (0 for linear); `None` for modes
  53. /// GFX10 does not have.
  54. pub fn block_log2(self) -> Option<u32> {
  55. Some(match self.0 {
  56. 0 => 0,
  57. 1 | 2 => 8,
  58. 5 | 6 | 21..=23 => 12,
  59. 9 | 10 | 17 | 18 | 24..=27 => 16,
  60. _ => return None,
  61. })
  62. }
  63. fn standard(self) -> bool {
  64. matches!(self.0, 1 | 5 | 9 | 17 | 21 | 25)
  65. }
  66. fn display(self) -> bool {
  67. matches!(self.0, 2 | 6 | 10 | 18 | 22 | 26)
  68. }
  69. fn z_order(self) -> bool {
  70. self.0 == 24
  71. }
  72. /// Pipe and bank XOR modes (`_T`, `_X`): their addresses depend on the
  73. /// GPU's pipe configuration.
  74. pub fn xor(self) -> bool {
  75. self.0 >= 16
  76. }
  77. }
  78. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  79. pub enum Dimension {
  80. Tex1d,
  81. Tex2d,
  82. Tex3d,
  83. }
  84. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  85. pub enum Error {
  86. /// The description makes no texture (zero size, bad element size, a
  87. /// mode this dimension cannot use, too many mips).
  88. Invalid,
  89. /// A valid layout whose addressing is not implemented here.
  90. Unsupported,
  91. /// A buffer is smaller than the layout or the rows need.
  92. TooSmall,
  93. }
  94. /// One plane of a texture.
  95. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  96. pub struct Desc {
  97. pub dimension: Dimension,
  98. /// In texels.
  99. pub width: u32,
  100. pub height: u32,
  101. /// Depth of a 3D texture, else the array size.
  102. pub depth: u32,
  103. pub mips: u32,
  104. /// 1, 2, 4, 8 or 16.
  105. pub element_bytes: u32,
  106. /// Texels per element side: 1, or 4 for block compression.
  107. pub block: u32,
  108. pub samples: u32,
  109. pub swizzle: Swizzle,
  110. }
  111. /// Elements along one side of mip `mip`, as data and copies see it: texels
  112. /// halve rounding down (to at least 1), then round up to whole elements.
  113. fn dim(texels: u32, mip: u32, block: u32) -> u32 {
  114. (texels >> mip).max(1).div_ceil(block)
  115. }
  116. /// Elements along one side of mip `mip` for placement (padding, tail,
  117. /// offsets): addrlib halves mip 0's elements rounding up, which can be one
  118. /// more than [`dim`] for odd sizes.
  119. fn padded_dim(texels: u32, mip: u32, block: u32) -> u32 {
  120. texels.max(1).div_ceil(block).div_ceil(1 << mip)
  121. }
  122. /// Where one mip lives inside a slice.
  123. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  124. pub struct Mip {
  125. /// Size in elements (depth 1 unless the texture is 3D).
  126. pub width: u32,
  127. pub height: u32,
  128. pub depth: u32,
  129. /// Padded size in elements: whole blocks, or the tail's share of one.
  130. pub pitch: u32,
  131. pub rows: u32,
  132. pub depth_pitch: u32,
  133. /// Byte offset of its first block in the slice (0 in the tail).
  134. pub offset: u64,
  135. /// In the mip tail: byte offset inside the tail block and the element
  136. /// position the mip starts at.
  137. pub tail: Option<Tail>,
  138. }
  139. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  140. pub struct Tail {
  141. pub offset: u32,
  142. pub x: u32,
  143. pub y: u32,
  144. }
  145. #[derive(Debug, Clone, PartialEq, Eq)]
  146. pub struct Layout {
  147. pub desc: Desc,
  148. /// Block dimensions in elements (linear: the pitch alignment, 1, 1).
  149. pub block: [u32; 3],
  150. /// 3D blocks span `block[2]` depth slices (GFX10 3D `S` and `D` modes).
  151. pub thick: bool,
  152. /// Array slices, depth slabs of `block[2]` slices (thick), or depth
  153. /// slices (thin and linear 3D).
  154. pub slices: u32,
  155. /// Bytes of one slice: its whole mip chain.
  156. pub slice_size: u64,
  157. pub size: u64,
  158. pub alignment: u64,
  159. /// The first mip in the tail; `mips.len()` without one.
  160. pub first_tail_mip: u32,
  161. pub mips: Vec<Mip>,
  162. /// Byte offsets inside a block of each element coordinate bit, per
  163. /// axis; empty for linear and unsupported modes.
  164. pattern: [Vec<u32>; 3],
  165. }
  166. /// Micro tile (256 bytes) patterns by log2 of the element size: for each
  167. /// address bit, the element coordinate bit it takes (`x0`, `y1`, `z0`...),
  168. /// `--` for the bits inside an element. Thin `S`, thin `D`, thick `S`
  169. /// (also the `D` 3D modes). From addrlib's `GFX10_SW_256_S_RBPLUS`,
  170. /// `GFX10_SW_256_D_RBPLUS` and `GFX10_SW_4K_S3_RBPLUS` patterns; the larger
  171. /// blocks add bits Y, X (thin) or Y, X, Z (thick) in turn.
  172. const MICRO: [[&[u8; 16]; 5]; 3] = [
  173. [
  174. b"x0x1x2x3y0y1y2y3",
  175. b"--x0x1x2y0y1y2x3",
  176. b"----x0x1y0y1y2x2",
  177. b"------x0y0y1x1x2",
  178. b"--------y0y1x0x1",
  179. ],
  180. [
  181. b"x0x1x2y1y0y2x3y3",
  182. b"--x0x1x2y0y1y2x3",
  183. b"----x0x1y0y1x2y2",
  184. b"------x0y0x1x2y1",
  185. b"--------x0y0x1y1",
  186. ],
  187. [
  188. b"x0x1z0y0z1y1x2z2",
  189. b"--x0z0y0z1y1x1z2",
  190. b"----x0y0z0y1x1z1",
  191. b"------x0z0y0x1z1",
  192. b"--------z0y0x0z1",
  193. ],
  194. ];
  195. /// For each axis, the address bit each coordinate bit lands on.
  196. fn pattern(kind: usize, element_log2: u32, block_log2: u32) -> [Vec<u32>; 3] {
  197. let mut axes: [Vec<u32>; 3] = Default::default();
  198. let micro = MICRO[kind][element_log2 as usize];
  199. for bit in 0..8u32 {
  200. let (axis, index) = (micro[2 * bit as usize], micro[2 * bit as usize + 1]);
  201. let axis = match axis {
  202. b'x' => 0,
  203. b'y' => 1,
  204. b'z' => 2,
  205. _ => continue,
  206. };
  207. let index = usize::from(index - b'0');
  208. let to = &mut axes[axis];
  209. if to.len() <= index {
  210. to.resize(index + 1, 0);
  211. }
  212. to[index] = bit;
  213. }
  214. let order: &[usize] = if kind == 2 { &[1, 0, 2] } else { &[1, 0] };
  215. for (bit, axis) in (8..block_log2).zip(order.iter().cycle()) {
  216. axes[*axis].push(bit);
  217. }
  218. axes
  219. }
  220. /// Byte offsets inside a block for coordinates 0..2^bits of one axis.
  221. fn spread(bits: &[u32]) -> Vec<u32> {
  222. (0..1u32 << bits.len())
  223. .map(|c| {
  224. bits.iter()
  225. .enumerate()
  226. .map(|(i, &to)| ((c >> i) & 1) << to)
  227. .sum()
  228. })
  229. .collect()
  230. }
  231. const MAX_MIPS: u32 = 16;
  232. /// The largest width, height and depth (or array size) accepted, in texels.
  233. /// GFX10's image descriptors hold at most 16384 texels per side, so no
  234. /// texture the GPU can use is refused. The bound also keeps every size
  235. /// computed below within `u64` (and its `u32` steps), which unchecked
  236. /// values from a title would otherwise overflow.
  237. const MAX_EXTENT: u32 = 1 << 14;
  238. /// 256-byte micro tile dimensions by log2 element size, 2D and 3D.
  239. const BLOCK_256_2D: [[u32; 2]; 5] = [[16, 16], [16, 8], [8, 8], [8, 4], [4, 4]];
  240. const BLOCK_256_3D: [[u32; 3]; 5] = [[8, 4, 8], [4, 4, 8], [4, 4, 4], [4, 2, 4], [2, 2, 4]];
  241. const BLOCK_1K_3D: [[u32; 3]; 5] = [[16, 8, 8], [8, 8, 8], [8, 8, 4], [8, 4, 4], [4, 4, 4]];
  242. impl Layout {
  243. pub fn new(desc: &Desc) -> Result<Layout, Error> {
  244. let d = *desc;
  245. let block_log2 = d.swizzle.block_log2().ok_or(Error::Invalid)?;
  246. let valid = (1..=MAX_EXTENT).contains(&d.width)
  247. && (1..=MAX_EXTENT).contains(&d.height)
  248. && (1..=MAX_EXTENT).contains(&d.depth)
  249. && (1..=MAX_MIPS).contains(&d.mips)
  250. && d.element_bytes.is_power_of_two()
  251. && d.element_bytes <= 16
  252. && matches!(d.block, 1 | 4)
  253. && d.samples.is_power_of_two()
  254. && d.samples <= 8
  255. && (d.samples == 1 || (d.dimension == Dimension::Tex2d && d.mips == 1))
  256. && (d.dimension != Dimension::Tex1d || d.height == 1)
  257. && (d.dimension != Dimension::Tex3d
  258. || matches!(d.swizzle.0, 0 | 5 | 9 | 17 | 21 | 24..=27));
  259. if !valid {
  260. return Err(Error::Invalid);
  261. }
  262. if block_log2 == 0 {
  263. Ok(Layout::linear(d))
  264. } else {
  265. Ok(Layout::tiled(d, block_log2))
  266. }
  267. }
  268. /// `HwlComputeSurfaceInfoLinear`: rows aligned to 256 bytes, mips packed
  269. /// smallest first, a 3D texture's depth slices each hold the chain.
  270. fn linear(d: Desc) -> Layout {
  271. let bpe = u64::from(d.element_bytes);
  272. let align = 256 / d.element_bytes;
  273. let three_d = d.dimension == Dimension::Tex3d;
  274. let mut mips = vec![];
  275. let mut offset = 0;
  276. for i in (0..d.mips).rev() {
  277. let h = padded_dim(d.height, i, d.block);
  278. let pitch = padded_dim(d.width, i, d.block).next_multiple_of(align);
  279. mips.push(Mip {
  280. width: dim(d.width, i, d.block),
  281. height: dim(d.height, i, d.block),
  282. depth: if three_d { dim(d.depth, i, 1) } else { 1 },
  283. pitch,
  284. rows: h,
  285. depth_pitch: if three_d { d.depth } else { 1 },
  286. offset,
  287. tail: None,
  288. });
  289. offset += u64::from(pitch) * u64::from(h) * bpe;
  290. }
  291. mips.reverse();
  292. Layout {
  293. desc: d,
  294. block: [align, 1, 1],
  295. thick: false,
  296. slices: d.depth,
  297. slice_size: offset,
  298. size: offset * u64::from(d.depth),
  299. alignment: 256,
  300. first_tail_mip: d.mips,
  301. mips,
  302. pattern: Default::default(),
  303. }
  304. }
  305. fn tiled(d: Desc, block_log2: u32) -> Layout {
  306. let element_log2 = d.element_bytes.trailing_zeros();
  307. let bpe = u64::from(d.element_bytes);
  308. let block_bytes = 1u64 << block_log2;
  309. let thick = d.dimension == Dimension::Tex3d && (d.swizzle.standard() || d.swizzle.display());
  310. let block = if thick {
  311. // ComputeThickBlockDimension
  312. let amp = (block_log2 - 10) / 3;
  313. let rest = (block_log2 - 10) % 3;
  314. let b = BLOCK_1K_3D[element_log2 as usize];
  315. [b[0] << amp, b[1] << (amp + rest / 2), b[2] << (amp + u32::from(rest != 0))]
  316. } else {
  317. // ComputeThinBlockDimension
  318. let samples_log2 = d.samples.trailing_zeros();
  319. let elements_log2 = block_log2 - element_log2 - samples_log2;
  320. let wide = samples_log2 & 1 == 0 || block_log2 & 1 != 0;
  321. let w = (elements_log2 + u32::from(wide)) / 2;
  322. [1 << w, 1 << (elements_log2 - w), 1]
  323. };
  324. let slices = d.depth.next_multiple_of(block[2]);
  325. let three_d = d.dimension == Dimension::Tex3d;
  326. // Mip depths placed by a thick layout (thin ones store depth as
  327. // slices).
  328. let mip_depth = |i: u32| if thick { padded_dim(d.depth, i, 1) } else { 1 };
  329. let depth_of = |i: u32| if three_d { dim(d.depth, i, 1) } else { 1 };
  330. let (width, height) = (|i| dim(d.width, i, d.block), |i| dim(d.height, i, d.block));
  331. let padded = |i| (padded_dim(d.width, i, d.block), padded_dim(d.height, i, d.block));
  332. let mut mips = Vec::with_capacity(d.mips as usize);
  333. let mut first_tail_mip = d.mips;
  334. let mut slice_size = 0u64;
  335. if d.mips == 1 {
  336. mips.push(Mip {
  337. width: width(0),
  338. height: height(0),
  339. depth: depth_of(0),
  340. pitch: width(0).next_multiple_of(block[0]),
  341. rows: height(0).next_multiple_of(block[1]),
  342. depth_pitch: if three_d { slices } else { 1 },
  343. offset: 0,
  344. tail: None,
  345. });
  346. slice_size = u64::from(mips[0].pitch)
  347. * u64::from(mips[0].rows)
  348. * bpe
  349. * u64::from(d.samples);
  350. } else {
  351. // GetMipTailDim: the largest mip the tail takes.
  352. let mut tail_max = block;
  353. if thick {
  354. match block_log2 % 3 {
  355. 0 => tail_max[1] >>= 1,
  356. 1 => tail_max[0] >>= 1,
  357. _ => tail_max[2] >>= 1,
  358. }
  359. } else {
  360. tail_max[0] >>= 1;
  361. }
  362. // GetMaxNumMipsInTail; 256-byte blocks have no tail
  363. // (`ComputeSurfaceInfoMicroTiled`).
  364. let effective = if thick {
  365. block_log2 - (block_log2 - 8) / 3
  366. } else {
  367. block_log2
  368. };
  369. let max_in_tail = match effective {
  370. 8 => 0,
  371. 9..=11 => 1 + (1 << (effective - 9)),
  372. _ => effective - 4,
  373. };
  374. // dsMipmapHtileFix: 8- and 16-bit depth enter the tail as 32-bit.
  375. let mut fixed = tail_max;
  376. if d.swizzle.z_order() && element_log2 <= 1 {
  377. let b = BLOCK_256_2D[element_log2 as usize];
  378. fixed[0] /= b[0] / BLOCK_256_2D[2][0];
  379. fixed[1] /= b[1] / BLOCK_256_2D[2][1];
  380. }
  381. let mut sizes = vec![];
  382. for i in 0..d.mips {
  383. let (w, h) = padded(i);
  384. if w <= fixed[0] && h <= fixed[1] && d.mips - i <= max_in_tail {
  385. first_tail_mip = i;
  386. slice_size += block_bytes / u64::from(block[2]);
  387. break;
  388. }
  389. let pitch = w.next_multiple_of(block[0]);
  390. let rows = h.next_multiple_of(block[1]);
  391. let depth = mip_depth(i).next_multiple_of(block[2]);
  392. let one = u64::from(pitch) * u64::from(rows) * bpe;
  393. slice_size += one;
  394. sizes.push(one * u64::from(block[2]));
  395. mips.push(Mip {
  396. width: width(i),
  397. height: height(i),
  398. depth: depth_of(i),
  399. pitch,
  400. rows,
  401. depth_pitch: if three_d { depth } else { 1 },
  402. offset: 0,
  403. tail: None,
  404. });
  405. }
  406. // Standard mips from the smallest up, after the tail block.
  407. let mut offset = if first_tail_mip < d.mips {
  408. block_bytes
  409. } else {
  410. 0
  411. };
  412. for i in (0..first_tail_mip as usize).rev() {
  413. mips[i].offset = offset;
  414. offset += sizes[i];
  415. }
  416. let micro = if thick {
  417. let b = BLOCK_256_3D[element_log2 as usize];
  418. [b[0], b[1]]
  419. } else {
  420. BLOCK_256_2D[element_log2 as usize]
  421. };
  422. let (mut pitch, mut rows) = (tail_max[0], tail_max[1]);
  423. for i in first_tail_mip..d.mips {
  424. let m = max_in_tail - 1 - (i - first_tail_mip);
  425. let offset = if m > 6 { 16 << m } else { m << 8 };
  426. // Address bits 8.. of the offset, odd ones x, even ones y.
  427. let bits = |from: u32| (0..6).map(|b| ((offset >> (from + 2 * b)) & 1) << b).sum();
  428. let (mut x, mut y): (u32, u32) = (bits(9), bits(8));
  429. if block_log2 & 1 != 0 {
  430. std::mem::swap(&mut x, &mut y);
  431. if element_log2 & 1 != 0 {
  432. y = (y << 1) | (x & 1);
  433. x >>= 1;
  434. }
  435. }
  436. mips.push(Mip {
  437. width: width(i),
  438. height: height(i),
  439. depth: depth_of(i),
  440. pitch,
  441. rows,
  442. depth_pitch: if thick {
  443. mip_depth(i).next_multiple_of(BLOCK_256_3D[element_log2 as usize][2])
  444. } else {
  445. 1
  446. },
  447. offset: 0,
  448. tail: Some(Tail {
  449. offset,
  450. x: x * micro[0],
  451. y: y * micro[1],
  452. }),
  453. });
  454. pitch = (pitch >> 1).max(micro[0]);
  455. rows = (rows >> 1).max(micro[1]);
  456. }
  457. }
  458. // Thick layouts store each depth slab's chain together.
  459. let slab = if thick { u64::from(block[2]) } else { 1 };
  460. let slice_size = slice_size * slab;
  461. let slices = slices / block[2];
  462. let addressable = !d.swizzle.xor() && d.samples == 1;
  463. let pattern = if addressable {
  464. let kind = if thick {
  465. 2
  466. } else {
  467. usize::from(d.swizzle.display())
  468. };
  469. pattern(kind, element_log2, block_log2).map(|bits| spread(&bits))
  470. } else {
  471. Default::default()
  472. };
  473. Layout {
  474. desc: d,
  475. block,
  476. thick,
  477. slices,
  478. slice_size,
  479. size: slice_size * u64::from(slices),
  480. alignment: block_bytes,
  481. first_tail_mip,
  482. mips,
  483. pattern,
  484. }
  485. }
  486. /// Whether [`Layout::offset`] and the copies work for this layout:
  487. /// linear and the modes without pipe or bank XOR, single-sampled.
  488. ///
  489. /// shortcut: no addressing for the XOR modes (`_X`, `_T`) and MSAA;
  490. /// they need the GPU's pipe and bank configuration (Series X and S
  491. /// differ). Titles use them for render targets and depth, which the
  492. /// host renders; add them when a title copies into or out of one.
  493. pub fn addressable(&self) -> bool {
  494. self.desc.swizzle == Swizzle::LINEAR || !self.pattern[0].is_empty()
  495. }
  496. /// The slice and the depth inside it for `z` (an array slice or a 3D
  497. /// depth slice).
  498. fn split(&self, z: u32) -> (u32, u32) {
  499. if self.thick {
  500. (z / self.block[2], z % self.block[2])
  501. } else {
  502. (z, 0)
  503. }
  504. }
  505. /// Byte offset of element (`x`, `y`) of mip `mip` in array slice or
  506. /// depth slice `z`. Coordinates must lie inside the mip.
  507. pub fn offset(&self, mip: u32, x: u32, y: u32, z: u32) -> Result<u64, Error> {
  508. let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?;
  509. let depth = if self.desc.dimension == Dimension::Tex3d {
  510. m.depth
  511. } else {
  512. self.slices
  513. };
  514. let inside = x < m.width && y < m.height && z < depth;
  515. if !inside || !self.addressable() {
  516. return Err(if inside {
  517. Error::Unsupported
  518. } else {
  519. Error::Invalid
  520. });
  521. }
  522. let (slice, z) = self.split(z);
  523. let base = u64::from(slice) * self.slice_size + m.offset;
  524. if self.desc.swizzle == Swizzle::LINEAR {
  525. let row = u64::from(y) * u64::from(m.pitch) + u64::from(x);
  526. return Ok(base + row * u64::from(self.desc.element_bytes));
  527. }
  528. Ok(base + self.row(m, y, z) + self.column(m, x))
  529. }
  530. /// The part of an address that depends on the row (and depth in a
  531. /// thick block).
  532. fn row(&self, m: &Mip, y: u32, z: u32) -> u64 {
  533. let [bw, bh, _] = self.block;
  534. let log2 = self.alignment.trailing_zeros();
  535. // In the tail the pattern of the shifted position gives the mip's
  536. // offset inside the tail block.
  537. let y = y + m.tail.map_or(0, |t| t.y);
  538. let blocks = u64::from(y / bh) * u64::from(m.pitch / bw);
  539. (blocks << log2) + u64::from(self.pattern[1][(y % bh) as usize] | self.pattern[2][z as usize])
  540. }
  541. /// The part of an address that depends on the column.
  542. fn column(&self, m: &Mip, x: u32) -> u64 {
  543. let bw = self.block[0];
  544. let x = x + m.tail.map_or(0, |t| t.x);
  545. (u64::from(x / bw) << self.alignment.trailing_zeros())
  546. + u64::from(self.pattern[0][(x % bw) as usize])
  547. }
  548. /// Depth slices a subresource of mip `mip` covers: the mip's depth for
  549. /// 3D textures, else 1 (one array slice).
  550. pub fn subresource_depth(&self, mip: u32) -> u32 {
  551. self.mips.get(mip as usize).map_or(0, |m| m.depth)
  552. }
  553. /// Copies one subresource out of tiled memory (the whole texture,
  554. /// [`Layout::size`] bytes) into linear rows: mip `mip` of array slice
  555. /// `slice` (3D: every depth slice of the mip, `slice` 0). Rows are
  556. /// `row_pitch` bytes apart, depth slices `depth_pitch`.
  557. pub fn detile(
  558. &self,
  559. tiled: &[u8],
  560. mip: u32,
  561. slice: u32,
  562. linear: &mut [u8],
  563. row_pitch: usize,
  564. depth_pitch: usize,
  565. ) -> Result<(), Error> {
  566. self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| {
  567. linear[l..][..len].copy_from_slice(&tiled[t..][..len]);
  568. })
  569. }
  570. /// The reverse of [`Layout::detile`]: linear rows into tiled memory.
  571. pub fn tile(
  572. &self,
  573. tiled: &mut [u8],
  574. mip: u32,
  575. slice: u32,
  576. linear: &[u8],
  577. row_pitch: usize,
  578. depth_pitch: usize,
  579. ) -> Result<(), Error> {
  580. self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| {
  581. tiled[t..][..len].copy_from_slice(&linear[l..][..len]);
  582. })
  583. }
  584. /// Visits contiguous runs as (tiled byte offset, linear byte offset, length).
  585. #[allow(clippy::too_many_arguments)]
  586. fn walk(
  587. &self,
  588. tiled_len: usize,
  589. mip: u32,
  590. slice: u32,
  591. linear_len: usize,
  592. row_pitch: usize,
  593. depth_pitch: usize,
  594. mut copy: impl FnMut(usize, usize, usize),
  595. ) -> Result<(), Error> {
  596. let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?;
  597. let depth = m.depth;
  598. let first = if self.desc.dimension == Dimension::Tex3d {
  599. if slice != 0 {
  600. return Err(Error::Invalid);
  601. }
  602. 0
  603. } else {
  604. slice
  605. };
  606. if first >= self.slices {
  607. return Err(Error::Invalid);
  608. }
  609. if !self.addressable() {
  610. return Err(Error::Unsupported);
  611. }
  612. let n = self.desc.element_bytes as usize;
  613. let bytes = m.width as usize * n;
  614. let need = (depth as usize - 1) * depth_pitch + (m.height as usize - 1) * row_pitch + bytes;
  615. if tiled_len < self.size as usize || linear_len < need || row_pitch < bytes {
  616. return Err(Error::TooSmall);
  617. }
  618. let linear = self.desc.swizzle == Swizzle::LINEAR;
  619. // The row and depth contribute one common base to every column, so
  620. // the same contiguous runs repeat on every row, including mip tails.
  621. let mut runs = Vec::new();
  622. if !linear {
  623. let mut first_linear = 0;
  624. let mut first_tiled = self.column(m, 0) as usize;
  625. for x in 1..m.width {
  626. let offset = self.column(m, x) as usize;
  627. let at = x as usize * n;
  628. if offset != first_tiled + (at - first_linear) {
  629. runs.push((first_tiled, first_linear, at - first_linear));
  630. first_tiled = offset;
  631. first_linear = at;
  632. }
  633. }
  634. runs.push((first_tiled, first_linear, bytes - first_linear));
  635. }
  636. for z in 0..depth {
  637. let (s, inner) = self.split(first + z);
  638. let base = u64::from(s) * self.slice_size + m.offset;
  639. for y in 0..m.height {
  640. let linear_row = z as usize * depth_pitch + y as usize * row_pitch;
  641. if linear {
  642. let tiled_row = base + u64::from(y) * u64::from(m.pitch) * n as u64;
  643. copy(tiled_row as usize, linear_row, bytes);
  644. } else {
  645. let tiled_row = (base + self.row(m, y, inner)) as usize;
  646. for &(tiled, linear, len) in &runs {
  647. copy(tiled_row + tiled, linear_row + linear, len);
  648. }
  649. }
  650. }
  651. }
  652. Ok(())
  653. }
  654. }
  655. /// What a DXGI format stores per element: bytes, texels per element side
  656. /// (4 for block compression), and whether its stencil is a second plane
  657. /// (the GPU keeps depth and stencil apart).
  658. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  659. pub struct Format {
  660. pub bytes: u32,
  661. pub block: u32,
  662. pub stencil: bool,
  663. }
  664. /// By DXGI format number. `None` for 96-bit, 1-bit, packed 4:2:2 and video
  665. /// formats.
  666. ///
  667. /// shortcut: those formats have no layout here; add them when a title uses
  668. /// one.
  669. pub fn format(dxgi: u32) -> Option<Format> {
  670. let (bytes, block, stencil) = match dxgi {
  671. 1..=4 => (16, 1, false),
  672. 9..=18 => (8, 1, false),
  673. 19..=22 | 44..=47 => (4, 1, true),
  674. 23..=43 | 67 | 87..=93 | 116 | 117 => (4, 1, false),
  675. 48..=59 | 85 | 86 | 115 => (2, 1, false),
  676. 118..=120 => (2, 1, true),
  677. 60..=65 => (1, 1, false),
  678. 70..=72 | 79..=81 => (8, 4, false),
  679. 73..=78 | 82..=84 | 94..=99 => (16, 4, false),
  680. _ => return None,
  681. };
  682. Some(Format {
  683. bytes,
  684. block,
  685. stencil,
  686. })
  687. }
  688. /// A texture as the console allocates it: a D3D12-style description with
  689. /// a swizzle mode.
  690. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  691. pub struct TextureDesc {
  692. pub dimension: Dimension,
  693. /// In texels.
  694. pub width: u32,
  695. pub height: u32,
  696. /// Depth of a 3D texture, else the array size.
  697. pub depth_or_array: u32,
  698. /// 0: the full chain.
  699. pub mips: u32,
  700. /// DXGI format number.
  701. pub format: u32,
  702. pub samples: u32,
  703. pub swizzle: Swizzle,
  704. }
  705. #[derive(Debug, Clone, PartialEq, Eq)]
  706. pub struct Plane {
  707. /// From the start of the texture.
  708. pub offset: u64,
  709. pub stencil: bool,
  710. pub layout: Layout,
  711. }
  712. /// Every data plane of a texture (depth, then stencil), placed one after
  713. /// the other.
  714. ///
  715. /// shortcut: no compression metadata planes (HTILE, CMASK, FMASK, DCC);
  716. /// the console adds them to render targets and depth buffers unless the
  717. /// description denies them, so those are smaller here than on the console.
  718. /// The host GPU renders them, so nothing reads that memory; add the planes
  719. /// if a title sizes a pool from console sizes and runs out.
  720. #[derive(Debug, Clone, PartialEq, Eq)]
  721. pub struct Texture {
  722. pub planes: Vec<Plane>,
  723. pub size: u64,
  724. pub alignment: u64,
  725. }
  726. impl Texture {
  727. pub fn new(desc: &TextureDesc) -> Result<Texture, Error> {
  728. let f = format(desc.format).ok_or(Error::Invalid)?;
  729. let depth3d = if desc.dimension == Dimension::Tex3d {
  730. desc.depth_or_array
  731. } else {
  732. 1
  733. };
  734. let mips = match desc.mips {
  735. 0 => 32 - desc.width.max(desc.height).max(depth3d).max(1).leading_zeros(),
  736. n => n,
  737. };
  738. let plane = |bytes| Desc {
  739. dimension: desc.dimension,
  740. width: desc.width,
  741. height: desc.height,
  742. depth: desc.depth_or_array,
  743. mips,
  744. element_bytes: bytes,
  745. block: f.block,
  746. samples: desc.samples.max(1),
  747. swizzle: desc.swizzle,
  748. };
  749. let mut planes = vec![Plane {
  750. offset: 0,
  751. stencil: false,
  752. layout: Layout::new(&plane(f.bytes))?,
  753. }];
  754. if f.stencil {
  755. let layout = Layout::new(&plane(1))?;
  756. let offset = planes[0].layout.size.next_multiple_of(layout.alignment);
  757. planes.push(Plane {
  758. offset,
  759. stencil: true,
  760. layout,
  761. });
  762. }
  763. let last = &planes[planes.len() - 1];
  764. let size = last.offset + last.layout.size;
  765. let alignment = planes.iter().map(|p| p.layout.alignment).max().unwrap_or(1);
  766. Ok(Texture {
  767. planes,
  768. size,
  769. alignment,
  770. })
  771. }
  772. }
  773. #[cfg(test)]
  774. mod tests {
  775. use super::*;
  776. fn desc(w: u32, h: u32, mips: u32, bpe: u32, swizzle: Swizzle) -> Desc {
  777. Desc {
  778. dimension: Dimension::Tex2d,
  779. width: w,
  780. height: h,
  781. depth: 1,
  782. mips,
  783. element_bytes: bpe,
  784. block: 1,
  785. samples: 1,
  786. swizzle,
  787. }
  788. }
  789. /// Sizes past the hardware's 16384 texels per side are refused instead
  790. /// of overflowing the size arithmetic (found by random-input testing).
  791. #[test]
  792. fn extents_past_the_hardware_limit_are_invalid() {
  793. for swizzle in [Swizzle::LINEAR, Swizzle::SW_64KB_D_X] {
  794. let largest = Layout::new(&desc(MAX_EXTENT, MAX_EXTENT, 15, 16, swizzle)).unwrap();
  795. assert!(largest.size >= u64::from(MAX_EXTENT) * u64::from(MAX_EXTENT) * 16);
  796. for (w, h) in [
  797. (MAX_EXTENT + 1, 1),
  798. (1, MAX_EXTENT + 1),
  799. (u32::MAX, u32::MAX),
  800. ] {
  801. let result = Layout::new(&desc(w, h, 1, 16, swizzle));
  802. assert_eq!(result, Err(Error::Invalid), "{w}x{h}");
  803. }
  804. let mut deep = desc(1, 1, 1, 16, swizzle);
  805. deep.depth = u32::MAX;
  806. assert_eq!(Layout::new(&deep), Err(Error::Invalid));
  807. }
  808. }
  809. #[test]
  810. fn blocks_hold_their_size_in_elements() {
  811. for log2 in [8u32, 12, 16] {
  812. let swizzle = match log2 {
  813. 8 => Swizzle::SW_256B_S,
  814. 12 => Swizzle::SW_4KB_S,
  815. _ => Swizzle::SW_64KB_D,
  816. };
  817. for e in 0..5 {
  818. let l = Layout::new(&desc(1, 1, 1, 1 << e, swizzle)).unwrap();
  819. let [w, h, d] = l.block;
  820. assert_eq!(u64::from(w * h * d) << e, 1 << log2, "{log2} {e}");
  821. // The pattern covers exactly the block's coordinates.
  822. assert_eq!(l.pattern[0].len() as u32, w);
  823. assert_eq!(l.pattern[1].len() as u32, h);
  824. }
  825. }
  826. // 64 KiB, 16-byte elements: 64x64 (a 256x256 BC7 texture).
  827. let l = Layout::new(&desc(64, 64, 1, 16, Swizzle::SW_64KB_D)).unwrap();
  828. assert_eq!(l.block, [64, 64, 1]);
  829. assert_eq!((l.size, l.alignment), (65536, 65536));
  830. }
  831. /// Every element of every mip and slice lands on its own address, inside
  832. /// the texture, and tiling then detiling gives the rows back.
  833. #[test]
  834. fn addresses_are_a_bijection_and_copies_round_trip() {
  835. let cases = [
  836. desc(64, 64, 7, 16, Swizzle::SW_64KB_D),
  837. desc(100, 60, 7, 4, Swizzle::SW_64KB_D),
  838. desc(250, 175, 8, 8, Swizzle::SW_4KB_S),
  839. desc(33, 17, 6, 1, Swizzle::SW_4KB_D),
  840. desc(40, 9, 3, 2, Swizzle::SW_64KB_S),
  841. desc(30, 20, 5, 4, Swizzle::LINEAR),
  842. desc(83, 31, 6, 1, Swizzle::SW_256B_S),
  843. Desc {
  844. block: 4,
  845. ..desc(109, 71, 6, 16, Swizzle::SW_256B_D)
  846. },
  847. Desc {
  848. depth: 3,
  849. ..desc(70, 70, 4, 16, Swizzle::SW_4KB_S)
  850. },
  851. Desc {
  852. dimension: Dimension::Tex3d,
  853. depth: 16,
  854. ..desc(64, 32, 7, 4, Swizzle::SW_4KB_S)
  855. },
  856. ];
  857. for d in cases {
  858. let l = Layout::new(&d).unwrap();
  859. let mut seen = vec![false; l.size as usize];
  860. let mut tiled = vec![0u8; l.size as usize];
  861. let n = d.element_bytes as usize;
  862. let slices = if d.dimension == Dimension::Tex3d { 1 } else { d.depth };
  863. for slice in 0..slices {
  864. for mip in 0..d.mips {
  865. let m = l.mips[mip as usize];
  866. let active = m.width as usize * n;
  867. let row = active + 13;
  868. let plane = row * m.height as usize + 11;
  869. let linear: Vec<u8> = (0..plane * m.depth as usize)
  870. .map(|i| (i * 7 + mip as usize * 13 + slice as usize) as u8)
  871. .collect();
  872. l.tile(&mut tiled, mip, slice, &linear, row, plane).unwrap();
  873. let mut back = vec![0xcc; linear.len()];
  874. l.detile(&tiled, mip, slice, &mut back, row, plane).unwrap();
  875. for z in 0..m.depth {
  876. let base = z as usize * plane;
  877. for y in 0..m.height {
  878. let start = base + y as usize * row;
  879. assert_eq!(back[start..start + active], linear[start..start + active]);
  880. assert!(back[start + active..start + row].iter().all(|&b| b == 0xcc));
  881. for x in 0..m.width {
  882. let at = l.offset(mip, x, y, slice + z).unwrap() as usize;
  883. let source = start + x as usize * n;
  884. assert_eq!(tiled[at..at + n], linear[source..source + n]);
  885. assert!(at + n <= seen.len(), "{d:?} mip {mip} outside");
  886. assert!(at.is_multiple_of(n));
  887. assert!(!seen[at], "{d:?} mip {mip} ({x},{y},{z}) twice");
  888. seen[at] = true;
  889. }
  890. }
  891. assert!(back[base + plane - 11..base + plane].iter().all(|&b| b == 0xcc));
  892. }
  893. }
  894. }
  895. }
  896. }
  897. /// Hand-checked: in a 64 KiB `D` block of 4-byte elements, x bits go to
  898. /// address bits 2, 3, 6, 9, 11, 13, 15 and y bits to 4, 5, 7, 8, 10, 12,
  899. /// 14; a 4 KiB `S` block of 16-byte elements is 16x16 with y first.
  900. #[test]
  901. fn hand_checked_addresses() {
  902. let l = Layout::new(&desc(128, 128, 1, 4, Swizzle::SW_64KB_D)).unwrap();
  903. assert_eq!(l.offset(0, 1, 0, 0), Ok(1 << 2));
  904. assert_eq!(l.offset(0, 4, 0, 0), Ok(1 << 6));
  905. assert_eq!(l.offset(0, 0, 4, 0), Ok(1 << 7));
  906. assert_eq!(l.offset(0, 0, 8, 0), Ok(1 << 8));
  907. assert_eq!(l.offset(0, 64, 64, 0), Ok((1 << 15) | (1 << 14)));
  908. let l = Layout::new(&desc(32, 32, 1, 16, Swizzle::SW_4KB_S)).unwrap();
  909. assert_eq!(l.block, [16, 16, 1]);
  910. assert_eq!(l.offset(0, 0, 1, 0), Ok(1 << 4));
  911. assert_eq!(l.offset(0, 1, 0, 0), Ok(1 << 6));
  912. // Blocks row by row: (16, 0) is the second block, (0, 16) the third.
  913. assert_eq!(l.offset(0, 16, 0, 0), Ok(4096));
  914. assert_eq!(l.offset(0, 0, 16, 0), Ok(8192));
  915. }
  916. /// A 256x256 BC7 chain in 64 KiB `D`: one tail block holding mips 1-8,
  917. /// then mip 0; mip 1 sits at x = 32 elements, 32 KiB into the tail.
  918. #[test]
  919. fn mip_tail_comes_first() {
  920. let l = Layout::new(&desc(64, 64, 9, 16, Swizzle::SW_64KB_D)).unwrap();
  921. assert_eq!(l.first_tail_mip, 1);
  922. assert_eq!(l.size, 2 * 65536);
  923. assert_eq!(l.mips[0].offset, 65536);
  924. assert_eq!(
  925. l.mips[1].tail,
  926. Some(Tail {
  927. offset: 32768,
  928. x: 32,
  929. y: 0
  930. })
  931. );
  932. assert_eq!(l.offset(1, 0, 0, 0), Ok(32768));
  933. // 4 KiB blocks hold fewer tail mips: 16x16 BC7 mips stay outside.
  934. let l = Layout::new(&desc(64, 64, 9, 16, Swizzle::SW_4KB_S)).unwrap();
  935. assert_eq!(l.first_tail_mip, 3);
  936. assert_eq!(l.mips[2].offset, 4096);
  937. assert_eq!(l.mips[1].offset, 8192);
  938. assert_eq!(l.mips[0].offset, 8192 + 16384);
  939. }
  940. #[test]
  941. fn depth_stencil_is_two_planes() {
  942. let t = Texture::new(&TextureDesc {
  943. dimension: Dimension::Tex2d,
  944. width: 1920,
  945. height: 1080,
  946. depth_or_array: 1,
  947. mips: 1,
  948. format: 20,
  949. samples: 1,
  950. swizzle: Swizzle::SW_64KB_Z_X,
  951. })
  952. .unwrap();
  953. assert_eq!(t.planes.len(), 2);
  954. // 4-byte depth in 128x128 blocks, 1-byte stencil in 256x256 blocks.
  955. assert_eq!(t.planes[0].layout.size, 1920 * 1152 * 4);
  956. assert_eq!(t.planes[1].offset, t.planes[0].layout.size);
  957. assert_eq!(t.planes[1].layout.size, 2048 * 1280);
  958. assert!(!t.planes[0].layout.addressable());
  959. }
  960. #[test]
  961. fn bad_descriptions_and_buffers_are_refused() {
  962. assert_eq!(
  963. Layout::new(&desc(0, 4, 1, 4, Swizzle::SW_4KB_S)),
  964. Err(Error::Invalid)
  965. );
  966. assert_eq!(
  967. Layout::new(&desc(4, 4, 1, 12, Swizzle::SW_4KB_S)),
  968. Err(Error::Invalid)
  969. );
  970. assert_eq!(
  971. Layout::new(&desc(4, 4, 1, 4, Swizzle(3))),
  972. Err(Error::Invalid)
  973. );
  974. let l = Layout::new(&desc(64, 64, 1, 4, Swizzle::SW_4KB_S)).unwrap();
  975. let mut out = vec![0; 64 * 64 * 4];
  976. assert_eq!(
  977. l.detile(&[0; 100], 0, 0, &mut out, 256, 0),
  978. Err(Error::TooSmall)
  979. );
  980. assert_eq!(l.offset(0, 64, 0, 0), Err(Error::Invalid));
  981. }
  982. }