tiles.rs 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587
  1. //! Levels on demand: host copies of title textures that take the card's
  2. //! memory level by level, as the title holds the levels.
  3. //!
  4. //! The title places a texture's whole chain of levels in its address space
  5. //! and holds only some of them: the smallest first, at the start of the
  6. //! texture's memory. The memory of the larger ones is either not mapped,
  7. //! or belongs to the next texture, which the title packs where they would
  8. //! be (run 188). A host copy was a committed texture: every level of it
  9. //! took the card's memory from the first upload on. Run 189's accounting
  10. //! line counted 2.2 to 3.0 GB of 4.3 to 5.5 GB of host copies in levels
  11. //! whose title memory was not mapped, on some 1,600 copies; with about
  12. //! 2.2 to 3.1 GB of render targets that filled the card, and textures
  13. //! that needed a new host copy waited for room (the main character's face
  14. //! among them, runs 188 and 189).
  15. //!
  16. //! Here such a texture is a reserved one (`CreateReservedResource`): it has
  17. //! every level, so level numbers and sizes are what they were, but no
  18. //! memory. The rules:
  19. //! - A level is given tiles of a heap of ours (`UpdateTileMappings`, on the
  20. //! queue) only in a submission-time step of a list that also writes all
  21. //! of that level: the upload of the texture (`texture.rs` `upload`, which
  22. //! copies every level from the staging buffer every time), or, before
  23. //! the card itself writes the texture (a copy, a resolve), an upload of
  24. //! every level with every level given (`texture.rs` `make_whole`). The
  25. //! step runs when the list is submitted, before the list is executed, so
  26. //! the mapping is ahead of the copy on the queue. Tiles hold what their
  27. //! last owner left; no level is shown before it is written whole.
  28. //! - Which levels are held is said by one function, at the moment the
  29. //! staging buffer is filled (`Staging::held_levels`): the levels whose
  30. //! title memory is mapped and lies before the start of the next texture
  31. //! placed in this one's span. The staging buffer holds zeros for the
  32. //! others, and the step gives tiles by that same answer.
  33. //! - The small levels the card packs into shared tiles are given together
  34. //! when any of them is held; the upload writes all of them (zeros for
  35. //! the ones not held).
  36. //! - A shader must not reach a level without memory (it reads zeros: a
  37. //! black texture). The host view of a slot is made from the first level
  38. //! that is held and has tiles ([`show_from`], `descriptor/host.rs`
  39. //! `make`), and the slots of a texture are made again when that level
  40. //! changes (`HostHeap::texture_views_remade`).
  41. //! - shortcut: tiles are not taken back while the host copy lives. A level
  42. //! the title lets go of, or that turns out to be the next texture's,
  43. //! keeps its tiles; it is hidden by the views and written with zeros at
  44. //! the next upload. Its tiles go back when the host copy does.
  45. //!
  46. //! Only for a texture the title places in memory and fills, two-dimensional,
  47. //! one layer, more than one level, of [`floor`] bytes or more, whose memory
  48. //! is not all its own when the host copy is made (`resource.rs` `hosted`);
  49. //! every other texture is made as before. Off unless
  50. //! `VICTORY_LEVELS_ON_DEMAND=1`.
  51. use std::sync::Mutex;
  52. use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
  53. use windows::Win32::Graphics::Direct3D12::*;
  54. use crate::host::host;
  55. /// The card's tile: 64 KiB.
  56. const TILE: u64 = 64 << 10;
  57. /// Tiles in one heap of the pool (64 MiB). The largest level given is a
  58. /// 4096x4096 one of one byte a texel: 256 tiles.
  59. const HEAP_TILES: u32 = 1024;
  60. /// Since the start, or now: such textures alive; the bytes all their
  61. /// levels would take; the bytes of the tiles given to them; the bytes of
  62. /// the pool's heaps; such textures made in all; levels given; calls of
  63. /// `UpdateTileMappings`; their microseconds; heaps given back to the card;
  64. /// uploads that left a held level without tiles (the card had no room, or
  65. /// no heap could be had); uploads recorded again for such a level.
  66. pub(crate) static STATS: [AtomicU64; 11] = [const { AtomicU64::new(0) }; 11];
  67. /// Whether textures are made this way: the switch
  68. /// (`VICTORY_LEVELS_ON_DEMAND=1`; off by default), and a card that reads
  69. /// zeros from, and drops writes to, levels without memory (tiled resources
  70. /// tier 2).
  71. pub(crate) fn wanted() -> bool {
  72. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  73. *ON.get_or_init(|| {
  74. if !std::env::var_os("VICTORY_LEVELS_ON_DEMAND").is_some_and(|v| v == "1") {
  75. return false;
  76. }
  77. let Some(host) = host() else {
  78. return false;
  79. };
  80. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default();
  81. // SAFETY: a plain query into a struct of its own size.
  82. let asked = unsafe {
  83. host.device.CheckFeatureSupport(
  84. D3D12_FEATURE_D3D12_OPTIONS,
  85. (&raw mut options).cast(),
  86. size_of_val(&options) as u32,
  87. )
  88. };
  89. let tier = options.TiledResourcesTier.0;
  90. let on = asked.is_ok() && tier >= 2;
  91. tracing::info!(
  92. tier,
  93. on,
  94. floor_kb = floor() >> 10,
  95. "host copies of title textures take the card's memory level by level (VICTORY_LEVELS_ON_DEMAND=1)"
  96. );
  97. on
  98. })
  99. }
  100. fn parse_floor(value: Option<&str>) -> u64 {
  101. value
  102. .and_then(|v| v.trim().parse::<u64>().ok())
  103. .map_or(1 << 20, |kb| kb.max(64).saturating_mul(1024))
  104. }
  105. /// The bytes from which a texture is made this way: a megabyte, or
  106. /// `VICTORY_LEVELS_MIN_KB`. (The accounting of run 189: the levels not
  107. /// held are 1.9 MB a copy on some 1,600 copies; a 512x512 texture has six
  108. /// tiles at most, and most of the calls for nothing.)
  109. pub(crate) fn floor() -> u64 {
  110. static BYTES: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  111. *BYTES.get_or_init(|| parse_floor(std::env::var("VICTORY_LEVELS_MIN_KB").ok().as_deref()))
  112. }
  113. /// The bytes of the tiles given to textures now: the card's memory they
  114. /// hold (`resource.rs` `room` counts it with the other host copies).
  115. pub(crate) fn given_total() -> u64 {
  116. STATS[2].load(Ordering::Relaxed)
  117. }
  118. /// One heap of the pool and its free runs of tiles (first tile, tiles), in
  119. /// order, no two touching.
  120. struct Heap {
  121. heap: ID3D12Heap,
  122. free: Vec<(u32, u32)>,
  123. }
  124. // SAFETY: a heap of the device, named only in queue and device calls, which
  125. // any thread may make; its free runs are plain numbers behind `POOL`'s lock.
  126. unsafe impl Send for Heap {}
  127. impl Heap {
  128. fn free_tiles(&self) -> u32 {
  129. self.free.iter().map(|run| run.1).sum()
  130. }
  131. }
  132. /// The pool's heaps by place; a place is empty after its heap went back to
  133. /// the card (a texture names its heaps by place).
  134. static POOL: Mutex<Vec<Option<Heap>>> = Mutex::new(Vec::new());
  135. /// `count` tiles of one heap, in as many runs as it takes, the lowest free
  136. /// tiles first (single free tiles are used up before a long run is cut):
  137. /// the heap, its place in the pool and the runs (first tile, tiles). A new
  138. /// heap is made when no heap has that many free.
  139. fn take(device: &ID3D12Device, count: u32) -> Option<(ID3D12Heap, usize, Vec<(u32, u32)>)> {
  140. if count == 0 || count > HEAP_TILES {
  141. return None;
  142. }
  143. let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
  144. let found = pool.iter().position(|h| h.as_ref().is_some_and(|h| h.free_tiles() >= count));
  145. let index = match found {
  146. Some(index) => index,
  147. None => {
  148. let desc = D3D12_HEAP_DESC {
  149. SizeInBytes: u64::from(HEAP_TILES) * TILE,
  150. Properties: D3D12_HEAP_PROPERTIES {
  151. Type: D3D12_HEAP_TYPE_DEFAULT,
  152. ..Default::default()
  153. },
  154. Alignment: 0,
  155. Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES,
  156. };
  157. let mut made: Option<ID3D12Heap> = None;
  158. // SAFETY: plain creation; the out pointer is ours.
  159. if let Err(e) = unsafe { device.CreateHeap::<ID3D12Heap>(&raw const desc, &raw mut made) } {
  160. tracing::warn!(error = %e, "no heap for texture levels given on demand: those levels stay empty");
  161. return None;
  162. }
  163. let fresh = Heap {
  164. heap: made?,
  165. free: vec![(0, HEAP_TILES)],
  166. };
  167. STATS[3].fetch_add(u64::from(HEAP_TILES) * TILE, Ordering::Relaxed);
  168. match pool.iter().position(Option::is_none) {
  169. Some(index) => {
  170. pool[index] = Some(fresh);
  171. index
  172. }
  173. None => {
  174. pool.push(Some(fresh));
  175. pool.len() - 1
  176. }
  177. }
  178. }
  179. };
  180. let h = pool[index].as_mut()?;
  181. let mut runs = Vec::new();
  182. let mut left = count;
  183. while left > 0 {
  184. let &(start, tiles) = h.free.first()?;
  185. let part = tiles.min(left);
  186. runs.push((start, part));
  187. if part == tiles {
  188. h.free.remove(0);
  189. } else {
  190. h.free[0] = (start + part, tiles - part);
  191. }
  192. left -= part;
  193. }
  194. Some((h.heap.clone(), index, runs))
  195. }
  196. /// Gives the runs `runs` of the pool's heap at `index` back; runs that
  197. /// touch become one. A heap with every tile free goes back to the card,
  198. /// unless it is the pool's only one. (Called when the texture that held
  199. /// the tiles is dropped: nothing on the card reads through its mappings
  200. /// any more, as for any host texture that is dropped.)
  201. fn give_back(index: usize, runs: &[(u32, u32)]) {
  202. let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
  203. let Some(Some(h)) = pool.get_mut(index) else {
  204. return;
  205. };
  206. h.free.extend_from_slice(runs);
  207. h.free.sort_unstable();
  208. let mut joined: Vec<(u32, u32)> = Vec::with_capacity(h.free.len());
  209. for &(from, tiles) in &h.free {
  210. match joined.last_mut() {
  211. Some(last) if last.0 + last.1 == from => last.1 += tiles,
  212. _ => joined.push((from, tiles)),
  213. }
  214. }
  215. h.free = joined;
  216. let all_free = h.free_tiles() == HEAP_TILES;
  217. if all_free && pool.iter().flatten().count() > 1 {
  218. pool[index] = None;
  219. STATS[3].fetch_sub(u64::from(HEAP_TILES) * TILE, Ordering::Relaxed);
  220. STATS[8].fetch_add(1, Ordering::Relaxed);
  221. }
  222. }
  223. /// What is given so far to one texture.
  224. struct Given {
  225. /// Per level with tiles of its own: whether it has them.
  226. levels: Vec<bool>,
  227. /// Whether the small levels the card packs together have theirs.
  228. packed: bool,
  229. /// The runs taken: the heap's place, first tile, tiles.
  230. runs: Vec<(usize, u32, u32)>,
  231. }
  232. /// A host texture made without memory, and the tiles its levels have been
  233. /// given.
  234. pub(crate) struct Tiled {
  235. /// Tiles of each level that has tiles of its own (level 0 first).
  236. standard: Vec<u32>,
  237. /// The tiles of the levels the card packs together (0: there are none);
  238. /// they are the levels from `standard.len()` on.
  239. packed: u32,
  240. /// Levels in all.
  241. levels: u32,
  242. /// The bytes all its tiles would take.
  243. pub(crate) full: u64,
  244. given: Mutex<Given>,
  245. /// The first level a view of the texture may show: the first one that
  246. /// is held or was written by the card and has tiles (`u32::MAX`: none
  247. /// yet).
  248. shown: AtomicU32,
  249. /// The levels held at the last upload (a bit a level).
  250. held: AtomicU32,
  251. /// The levels the card itself wrote, in lists submitted so far.
  252. card: AtomicU32,
  253. /// The levels a recorded list of the card's own writes has already
  254. /// written with zeros first ([`Tiled::claim`]).
  255. claimed: AtomicU32,
  256. }
  257. impl Tiled {
  258. /// For `texture`, just made reserved with `levels` levels and one
  259. /// layer: how the card cuts it into tiles. `None` if the card will not
  260. /// say, or cuts it in a way this does not handle; the caller then makes
  261. /// the texture the old way.
  262. pub(crate) fn make(device: &ID3D12Device, texture: &ID3D12Resource, levels: u32) -> Option<Tiled> {
  263. if levels == 0 || levels > 16 {
  264. return None;
  265. }
  266. let mut total = 0u32;
  267. let mut packed = D3D12_PACKED_MIP_INFO::default();
  268. let mut shape = D3D12_TILE_SHAPE::default();
  269. let mut count = levels;
  270. let mut tilings = vec![D3D12_SUBRESOURCE_TILING::default(); levels as usize];
  271. // SAFETY: outputs of our own, `count` tilings of them.
  272. unsafe {
  273. device.GetResourceTiling(
  274. texture,
  275. Some(&raw mut total),
  276. Some(&raw mut packed),
  277. Some(&raw mut shape),
  278. Some(&raw mut count),
  279. 0,
  280. tilings.as_mut_ptr(),
  281. );
  282. }
  283. let standard_levels = u32::from(packed.NumStandardMips);
  284. if total == 0 || standard_levels + u32::from(packed.NumPackedMips) != levels || standard_levels > count {
  285. return None;
  286. }
  287. let mut standard = Vec::with_capacity(standard_levels as usize);
  288. for tiling in &tilings[..standard_levels as usize] {
  289. let tiles = tiling
  290. .WidthInTiles
  291. .checked_mul(u32::from(tiling.HeightInTiles))
  292. .and_then(|n| n.checked_mul(u32::from(tiling.DepthInTiles)))
  293. .unwrap_or(0);
  294. if tiles == 0 || tiles > HEAP_TILES || tiling.StartTileIndexInOverallResource == D3D12_PACKED_TILE {
  295. return None;
  296. }
  297. standard.push(tiles);
  298. }
  299. let packed_tiles = if packed.NumPackedMips > 0 { packed.NumTilesForPackedMips } else { 0 };
  300. if (packed.NumPackedMips > 0 && packed_tiles == 0) || packed_tiles > HEAP_TILES {
  301. return None;
  302. }
  303. let full = u64::from(total) * TILE;
  304. STATS[0].fetch_add(1, Ordering::Relaxed);
  305. STATS[1].fetch_add(full, Ordering::Relaxed);
  306. STATS[4].fetch_add(1, Ordering::Relaxed);
  307. Some(Tiled {
  308. given: Mutex::new(Given {
  309. levels: vec![false; standard.len()],
  310. packed: false,
  311. runs: Vec::new(),
  312. }),
  313. standard,
  314. packed: packed_tiles,
  315. levels,
  316. full,
  317. shown: AtomicU32::new(u32::MAX),
  318. held: AtomicU32::new(0),
  319. card: AtomicU32::new(0),
  320. claimed: AtomicU32::new(0),
  321. })
  322. }
  323. /// At the submission of a list that uploads every level of `texture`
  324. /// from its staging buffer, of which `held` are the title's now (the
  325. /// others are zeros there): tiles for the held ones that have none.
  326. /// `room`: whether the card has room for more host copies
  327. /// (`resource.rs` `room`). Without room no held level gets tiles: the
  328. /// list still brings the levels that have theirs up to date (which
  329. /// takes none of the card's memory), and its copies into the others go
  330. /// nowhere. (An upload of a host copy that exists passes the full
  331. /// card's gate in `draw.rs` on the ground that it takes no memory;
  332. /// with tiles given here regardless, the line would not bound these
  333. /// textures.)
  334. /// Returns whether the first level a view may show changed, and
  335. /// whether a level named is still without tiles (no room, or no heap
  336. /// could be had): the caller has the upload recorded again later, or
  337. /// the level would stay empty until the title writes the texture.
  338. pub(crate) fn uploaded(&self, texture: &ID3D12Resource, held: u32, room: bool) -> (bool, bool) {
  339. match host() {
  340. Some(host) => self.uploaded_on(host.queue(), &host.device, texture, held, room),
  341. None => (false, false),
  342. }
  343. }
  344. /// [`Tiled::uploaded`] on a queue and a device.
  345. pub(crate) fn uploaded_on(
  346. &self,
  347. queue: &ID3D12CommandQueue,
  348. device: &ID3D12Device,
  349. texture: &ID3D12Resource,
  350. held: u32,
  351. room: bool,
  352. ) -> (bool, bool) {
  353. let held = held & self.every_level();
  354. let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner());
  355. self.held.store(held, Ordering::Relaxed);
  356. let card = self.card.load(Ordering::Relaxed);
  357. let named = held | card;
  358. // The levels the card itself writes are few and are not kept
  359. // waiting: a write of the card's into no memory is lost.
  360. let changed = self.give_locked(&mut given, queue, device, texture, named, if room { named } else { card });
  361. let missing = self.without_locked(&given, named) != 0;
  362. (changed, missing)
  363. }
  364. /// At the submission of a list in which the card itself writes the
  365. /// levels `levels` of `texture` (after zeros, if they were new:
  366. /// [`Tiled::claim`]): tiles for those that have none. Returns whether
  367. /// the first level a view may show changed.
  368. /// Only the levels this list writes get tiles here: a held level that
  369. /// is waiting for room is written by no copy of this list, and tiles
  370. /// hold what their last owner left.
  371. pub(crate) fn card_wrote(&self, texture: &ID3D12Resource, levels: u32) -> bool {
  372. match host() {
  373. Some(host) => self.card_wrote_on(host.queue(), &host.device, texture, levels),
  374. None => false,
  375. }
  376. }
  377. /// [`Tiled::card_wrote`] on a queue and a device.
  378. pub(crate) fn card_wrote_on(
  379. &self,
  380. queue: &ID3D12CommandQueue,
  381. device: &ID3D12Device,
  382. texture: &ID3D12Resource,
  383. levels: u32,
  384. ) -> bool {
  385. let levels = levels & self.every_level();
  386. let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner());
  387. let prev = self.card.load(Ordering::Relaxed);
  388. let changed = self.give_locked(
  389. &mut given,
  390. queue,
  391. device,
  392. texture,
  393. prev | levels | self.held.load(Ordering::Relaxed),
  394. levels,
  395. );
  396. // Only levels that actually received tiles (or already had them) saw
  397. // the card's write; a level that got no tiles saw its zeros and write
  398. // dropped, so neither `card` nor `claimed` should keep it.
  399. let without = self.without_locked(&given, levels);
  400. let backed = levels & !without;
  401. if backed != 0 {
  402. self.card.fetch_or(backed, Ordering::Relaxed);
  403. }
  404. if without != 0 {
  405. self.unclaim(without);
  406. }
  407. changed
  408. }
  409. /// The bits of the levels that get their tiles with level `level`:
  410. /// itself, or every level the card packs together if it is one of them.
  411. pub(crate) fn with_level(&self, level: u32) -> u32 {
  412. let first_packed = self.standard.len() as u32;
  413. if level < first_packed {
  414. 1 << level
  415. } else if level < self.levels {
  416. self.every_level() & !((1u32 << first_packed) - 1)
  417. } else {
  418. 0
  419. }
  420. }
  421. /// Of `levels`, the ones that have no tiles now and that no list
  422. /// recorded before has claimed: the caller's list writes them with
  423. /// zeros before the card's own write, so that what the write does not
  424. /// cover is not what the tiles' last owner left.
  425. pub(crate) fn claim(&self, levels: u32) -> u32 {
  426. let fresh = self.without(levels);
  427. fresh & !self.claimed.fetch_or(fresh, Ordering::Relaxed)
  428. }
  429. /// Gives up the claim on `levels` ([`Tiled::claim`]): the zeros of the
  430. /// list that claimed them never reached tiles of theirs (the list was
  431. /// reset without being submitted, the zeros could not be recorded, or
  432. /// no tiles could be had), so the next list that writes them sends its
  433. /// own.
  434. /// shortcut: a second list recorded between the claim and this sends
  435. /// no zeros; if it is the first whose write gets tiles, what that
  436. /// write does not cover is what the tiles' last owner left.
  437. pub(crate) fn unclaim(&self, levels: u32) {
  438. self.claimed.fetch_and(!levels, Ordering::Relaxed);
  439. }
  440. /// Of `levels` (a bit a level), the ones that have no tiles now.
  441. pub(crate) fn without(&self, levels: u32) -> u32 {
  442. let given = self.given.lock().unwrap_or_else(|e| e.into_inner());
  443. self.without_locked(&given, levels)
  444. }
  445. fn without_locked(&self, given: &Given, levels: u32) -> u32 {
  446. let first_packed = self.standard.len() as u32;
  447. let mut without = 0;
  448. for level in 0..self.levels.min(32) {
  449. let has = if level < first_packed { given.levels[level as usize] } else { given.packed };
  450. if !has {
  451. without |= 1 << level;
  452. }
  453. }
  454. levels & without
  455. }
  456. /// Gives tiles to the levels of `texture` that both `named` and `may`
  457. /// name (a bit a level, level 0 the lowest) and that have none yet;
  458. /// the levels the card packs together get theirs when any of them is
  459. /// so named. `named`: the levels that are the title's or the card's
  460. /// own, by which the first level a view may show is told; `may`: the
  461. /// ones of them that may get tiles in this call. To be called only
  462. /// from a submission-time step of a list that writes every level of
  463. /// `may`, whole: the call is ahead of that list on `queue`, and tiles
  464. /// hold what their last owner left.
  465. /// Returns whether the first level a view may show changed
  466. /// ([`Tiled::first_shown`]): the caller has the texture's slots made
  467. /// again.
  468. #[cfg(test)]
  469. pub(crate) fn give_on(
  470. &self,
  471. queue: &ID3D12CommandQueue,
  472. device: &ID3D12Device,
  473. texture: &ID3D12Resource,
  474. named: u32,
  475. may: u32,
  476. ) -> bool {
  477. let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner());
  478. self.give_locked(&mut given, queue, device, texture, named, may)
  479. }
  480. fn give_locked(
  481. &self,
  482. given: &mut Given,
  483. queue: &ID3D12CommandQueue,
  484. device: &ID3D12Device,
  485. texture: &ID3D12Resource,
  486. named: u32,
  487. may: u32,
  488. ) -> bool {
  489. let has = |level: u32| level < 32 && named & (1 << level) != 0;
  490. let now = |level: u32| level < 32 && named & may & (1 << level) != 0;
  491. let first_packed = self.standard.len() as u32;
  492. // (subresource, tiles, the level if it has tiles of its own) to map now.
  493. let mut wanted: Vec<(u32, u32, Option<usize>)> = Vec::new();
  494. for level in 0..first_packed {
  495. if !given.levels[level as usize] && now(level) {
  496. wanted.push((level, self.standard[level as usize], Some(level as usize)));
  497. }
  498. }
  499. if self.packed > 0 && !given.packed && (first_packed..self.levels).any(now) {
  500. wanted.push((first_packed, self.packed, None));
  501. }
  502. for (subresource, tiles, level) in wanted {
  503. let Some((heap, index, runs)) = take(device, tiles) else {
  504. continue;
  505. };
  506. let at = D3D12_TILED_RESOURCE_COORDINATE {
  507. X: 0,
  508. Y: 0,
  509. Z: 0,
  510. Subresource: subresource,
  511. };
  512. let size = D3D12_TILE_REGION_SIZE {
  513. NumTiles: tiles,
  514. ..Default::default()
  515. };
  516. // One region, the subresource's tiles in order, on as many
  517. // ranges of the heap as the runs taken.
  518. let flags = vec![D3D12_TILE_RANGE_FLAG_NONE; runs.len()];
  519. let starts: Vec<u32> = runs.iter().map(|run| run.0).collect();
  520. let counts: Vec<u32> = runs.iter().map(|run| run.1).collect();
  521. let began = std::time::Instant::now();
  522. // SAFETY: a live reserved texture and a live heap of ours; one
  523. // region of `tiles` tiles from the subresource's first tile;
  524. // `runs.len()` ranges whose counts add up to `tiles`, in three
  525. // arrays of that length that live through the call.
  526. unsafe {
  527. queue.UpdateTileMappings(
  528. texture,
  529. 1,
  530. Some(&raw const at),
  531. Some(&raw const size),
  532. &heap,
  533. runs.len() as u32,
  534. Some(flags.as_ptr()),
  535. Some(starts.as_ptr()),
  536. Some(counts.as_ptr()),
  537. D3D12_TILE_MAPPING_FLAG_NONE,
  538. );
  539. }
  540. STATS[6].fetch_add(1, Ordering::Relaxed);
  541. STATS[7].fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed);
  542. match level {
  543. Some(level) => given.levels[level] = true,
  544. None => given.packed = true,
  545. }
  546. for &(start, count) in &runs {
  547. given.runs.push((index, start, count));
  548. }
  549. STATS[2].fetch_add(u64::from(tiles) * TILE, Ordering::Relaxed);
  550. STATS[5].fetch_add(1, Ordering::Relaxed);
  551. }
  552. let with_tiles = |level: u32| {
  553. if level < first_packed {
  554. given.levels[level as usize]
  555. } else {
  556. given.packed
  557. }
  558. };
  559. let shown = (0..self.levels).find(|&level| has(level) && with_tiles(level)).unwrap_or(u32::MAX);
  560. self.shown.swap(shown, Ordering::Relaxed) != shown
  561. }
  562. /// The first level a view of the texture may show; `None` while no
  563. /// level is both held and given (the views are then as the title made
  564. /// them, and read zeros).
  565. pub(crate) fn first_shown(&self) -> Option<u32> {
  566. let shown = self.shown.load(Ordering::Relaxed);
  567. (shown != u32::MAX).then_some(shown)
  568. }
  569. /// Whether level `level` has tiles.
  570. #[cfg(test)]
  571. fn has_tiles(&self, level: u32) -> bool {
  572. let given = self.given.lock().unwrap_or_else(|e| e.into_inner());
  573. match given.levels.get(level as usize) {
  574. Some(&has) => has,
  575. None => level < self.levels && given.packed,
  576. }
  577. }
  578. /// Whether every level has tiles.
  579. #[cfg(test)]
  580. fn whole(&self) -> bool {
  581. let given = self.given.lock().unwrap_or_else(|e| e.into_inner());
  582. given.levels.iter().all(|&has| has) && (self.packed == 0 || given.packed)
  583. }
  584. /// A bit for every level of the texture.
  585. pub(crate) fn every_level(&self) -> u32 {
  586. if self.levels >= 32 { u32::MAX } else { (1 << self.levels) - 1 }
  587. }
  588. /// The bytes of the tiles it has now.
  589. pub(crate) fn given_bytes(&self) -> u64 {
  590. let given = self.given.lock().unwrap_or_else(|e| e.into_inner());
  591. given.runs.iter().map(|run| u64::from(run.2) * TILE).sum()
  592. }
  593. }
  594. impl Drop for Tiled {
  595. fn drop(&mut self) {
  596. let given = self.given.get_mut().unwrap_or_else(|e| e.into_inner());
  597. let mut bytes = 0;
  598. let mut by_heap: std::collections::BTreeMap<usize, Vec<(u32, u32)>> = std::collections::BTreeMap::new();
  599. for &(index, start, tiles) in &given.runs {
  600. by_heap.entry(index).or_default().push((start, tiles));
  601. bytes += u64::from(tiles) * TILE;
  602. }
  603. for (index, runs) in by_heap {
  604. give_back(index, &runs);
  605. }
  606. STATS[0].fetch_sub(1, Ordering::Relaxed);
  607. STATS[1].fetch_sub(self.full, Ordering::Relaxed);
  608. STATS[2].fetch_sub(bytes, Ordering::Relaxed);
  609. }
  610. }
  611. /// Keeps a two-dimensional shader view (2D or 2D array) from the levels
  612. /// before `first` of a texture of `levels` levels: it starts at `first` if
  613. /// it started before it, shows as many levels fewer (clamped to the
  614. /// remaining levels), and reduces `ResourceMinLODClamp` by the same shift so
  615. /// the effective minimum LOD stays at the same resource level.
  616. pub(crate) fn show_from(desc: &mut D3D12_SHADER_RESOURCE_VIEW_DESC, first: u32, levels: u32) {
  617. if first >= levels {
  618. return;
  619. }
  620. let clamp = |most: &mut u32, mips: &mut u32, min_lod: &mut f32| {
  621. if first <= *most {
  622. return;
  623. }
  624. let fewer = first - *most;
  625. *most = first;
  626. if *mips != u32::MAX {
  627. *mips = mips.saturating_sub(fewer).clamp(1, levels - first);
  628. }
  629. if *min_lod > 0.0 {
  630. *min_lod = (*min_lod - fewer as f32).max(0.0);
  631. }
  632. };
  633. match desc.ViewDimension {
  634. D3D12_SRV_DIMENSION_TEXTURE2D => {
  635. // SAFETY: `ViewDimension` selects `Texture2D`.
  636. let view = unsafe { &mut desc.Anonymous.Texture2D };
  637. clamp(&mut view.MostDetailedMip, &mut view.MipLevels, &mut view.ResourceMinLODClamp);
  638. }
  639. D3D12_SRV_DIMENSION_TEXTURE2DARRAY => {
  640. // SAFETY: `ViewDimension` selects `Texture2DArray`.
  641. let view = unsafe { &mut desc.Anonymous.Texture2DArray };
  642. clamp(&mut view.MostDetailedMip, &mut view.MipLevels, &mut view.ResourceMinLODClamp);
  643. }
  644. _ => {}
  645. }
  646. }
  647. /// For the log, with the texture queue's line: what this saves, and what
  648. /// the mapping calls cost since the line before.
  649. pub(crate) fn status() {
  650. static BEFORE: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
  651. let s: Vec<u64> = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect();
  652. if s[4] == 0 {
  653. return;
  654. }
  655. let calls = s[6] - BEFORE[0].swap(s[6], Ordering::Relaxed);
  656. let micros = s[7] - BEFORE[1].swap(s[7], Ordering::Relaxed);
  657. tracing::info!(
  658. "textures with levels on demand: {} alive ({} made so far), {} MB of the card given to {} levels in all, \
  659. {} MB of the card not allocated for levels the title does not hold ({} MB if every level had memory); \
  660. the pool's heaps {} MB ({} given back to the card so far); since the line before: {} calls of \
  661. UpdateTileMappings in {} microseconds; in all {} calls, {} microseconds; {} uploads left a held \
  662. level without memory (no room on the card, or no heap), {} uploads were recorded again for one",
  663. s[0],
  664. s[4],
  665. s[2] >> 20,
  666. s[5],
  667. s[1].saturating_sub(s[2]) >> 20,
  668. s[1] >> 20,
  669. s[3] >> 20,
  670. s[8],
  671. calls,
  672. micros,
  673. s[6],
  674. s[7],
  675. s[9],
  676. s[10],
  677. );
  678. }
  679. /// On the card, without the title: what levels on demand relies on, with
  680. /// the pool and the mapping call of this module on a device of the test's
  681. /// own. One test, one device: the pool is one for the process, and its
  682. /// heaps belong to the device that made them.
  683. ///
  684. /// Run by name, alone, no game needed:
  685. /// `cargo test -p victory-gpu --release -- --ignored levels_on_demand --nocapture`
  686. ///
  687. /// It runs on the SOFTWARE adapter unless `VICTORY_TILES_TEST_CARD=1`: on
  688. /// that adapter nothing reaches the card or its driver, so nothing it does
  689. /// can reset the driver or touch the screen. Wherever it runs, the debug
  690. /// layer is switched on if Windows has it (the optional feature "Graphics
  691. /// Tools"), its messages are printed after every step, and the test stops
  692. /// at the first error or lost device with the step's name, before
  693. /// anything else is sent. On the card it does not run without the layer,
  694. /// and no wait is longer than 1.5 s.
  695. #[cfg(test)]
  696. mod tests {
  697. use windows::Win32::Foundation::{HANDLE, WAIT_OBJECT_0};
  698. use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
  699. use windows::Win32::Graphics::Dxgi::Common::*;
  700. use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject};
  701. use windows::core::{Interface, s};
  702. use super::*;
  703. use crate::host::{compile, transition, warp_adapter};
  704. const SIDE: u32 = 1024;
  705. const LEVELS: u16 = 11;
  706. /// Two views of one texture read at the same place and level: the
  707. /// first as the layer makes it for a texture whose level 0 has no
  708. /// memory, the second as the title asked.
  709. const LOOK: &str = r#"
  710. #define RS "DescriptorTable(SRV(t0, numDescriptors = 2)), UAV(u0), StaticSampler(s0, filter = FILTER_MIN_MAG_MIP_POINT)"
  711. Texture2D<float4> clamped : register(t0);
  712. Texture2D<float4> whole : register(t1);
  713. SamplerState nearest : register(s0);
  714. RWByteAddressBuffer words : register(u0);
  715. [RootSignature(RS)]
  716. [numthreads(1, 1, 1)]
  717. void look() {
  718. float4 a = clamped.SampleLevel(nearest, float2(0.3, 0.3), 0);
  719. float4 b = whole.SampleLevel(nearest, float2(0.3, 0.3), 0);
  720. words.Store(0, (uint)(a.x * 255.0 + 0.5));
  721. words.Store(4, (uint)(b.x * 255.0 + 0.5));
  722. }
  723. "#;
  724. /// Where each level of a texture lies in a buffer of all of them: its
  725. /// place, its rows, the bytes of a row that are the level's own, and
  726. /// the buffer's bytes.
  727. struct Laid {
  728. footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>,
  729. rows: Vec<u32>,
  730. wide: Vec<u64>,
  731. total: u64,
  732. }
  733. struct Rig {
  734. device: ID3D12Device,
  735. queue: ID3D12CommandQueue,
  736. allocator: ID3D12CommandAllocator,
  737. list: ID3D12GraphicsCommandList,
  738. fence: ID3D12Fence,
  739. event: HANDLE,
  740. submitted: u64,
  741. /// The debug layer's messages, if Windows has the layer.
  742. messages: Option<ID3D12InfoQueue>,
  743. /// What the test is doing, for the message when it stops.
  744. step: &'static str,
  745. /// On the card, not on the software adapter.
  746. card: bool,
  747. }
  748. impl Rig {
  749. /// The software adapter, or the default one with
  750. /// `VICTORY_TILES_TEST_CARD=1`; `None` without one, without tiled
  751. /// resources of tier 2, or on the card without the debug layer.
  752. fn new() -> Option<Rig> {
  753. // SAFETY: plain object creation on a device of our own.
  754. unsafe {
  755. let card = std::env::var_os("VICTORY_TILES_TEST_CARD").is_some_and(|v| v == "1");
  756. // The debug layer, before the device is made: a call that
  757. // is not well formed is then refused and named by the
  758. // runtime, not handed to the driver.
  759. let mut layer: Option<ID3D12Debug> = None;
  760. let layered = D3D12GetDebugInterface(&mut layer).is_ok() && layer.is_some();
  761. layer.iter().for_each(|l| l.EnableDebugLayer());
  762. if card && !layered {
  763. eprintln!("no D3D12 debug layer (Windows optional feature \"Graphics Tools\"): not run on the card without it");
  764. return None;
  765. }
  766. let mut device: Option<ID3D12Device> = None;
  767. if card {
  768. D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?;
  769. } else {
  770. let adapter = warp_adapter().ok()?;
  771. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?;
  772. }
  773. let device = device?;
  774. let messages = device.cast::<ID3D12InfoQueue>().ok();
  775. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default();
  776. device
  777. .CheckFeatureSupport(
  778. D3D12_FEATURE_D3D12_OPTIONS,
  779. (&raw mut options).cast(),
  780. size_of_val(&options) as u32,
  781. )
  782. .ok()?;
  783. eprintln!(
  784. "levels on demand, {}: tiled resources tier {}, debug layer {}",
  785. if card { "ON THE CARD" } else { "on the software adapter" },
  786. options.TiledResourcesTier.0,
  787. if messages.is_some() { "on" } else { "not installed" }
  788. );
  789. if options.TiledResourcesTier.0 < 2 {
  790. return None;
  791. }
  792. let queue: ID3D12CommandQueue = device
  793. .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  794. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  795. ..Default::default()
  796. })
  797. .ok()?;
  798. let allocator: ID3D12CommandAllocator =
  799. device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?;
  800. let list: ID3D12GraphicsCommandList = device
  801. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)
  802. .ok()?;
  803. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  804. let event = CreateEventW(None, false, false, None).ok()?;
  805. Some(Rig {
  806. device,
  807. queue,
  808. allocator,
  809. list,
  810. fence,
  811. event,
  812. submitted: 0,
  813. messages,
  814. step: "making the device",
  815. card,
  816. })
  817. }
  818. }
  819. /// Prints what the debug layer said since the last call; the first
  820. /// error among it (as `host.rs` `log_messages` reads them).
  821. fn said(&self) -> Option<String> {
  822. let queue = self.messages.as_ref()?;
  823. let mut first_error = None;
  824. // SAFETY: each message is read into a buffer of the size the
  825. // queue reports, then the queue is emptied.
  826. unsafe {
  827. for i in 0..queue.GetNumStoredMessages() {
  828. let mut size = 0;
  829. if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
  830. continue;
  831. }
  832. let mut buffer = vec![0u64; size.div_ceil(8)];
  833. let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  834. if queue.GetMessage(i, Some(message), &mut size).is_ok() {
  835. let m = &*message;
  836. let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
  837. let text = String::from_utf8_lossy(text);
  838. let text = text.trim_end_matches('\0');
  839. eprintln!("D3D12 says (severity {}, id {}): {text}", m.Severity.0, m.ID.0);
  840. if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() {
  841. first_error = Some(text.to_owned());
  842. }
  843. }
  844. }
  845. queue.ClearStoredMessages();
  846. }
  847. first_error
  848. }
  849. /// Stops the test, naming the step, if the device is lost or the
  850. /// debug layer reported an error: nothing more is sent after it.
  851. fn check(&self, what: &str) {
  852. let error = self.said();
  853. // SAFETY: a plain query.
  854. let removed = unsafe { self.device.GetDeviceRemovedReason() };
  855. assert!(removed.is_ok(), "{}, {what}: the device is lost: {removed:?}", self.step);
  856. assert!(error.is_none(), "{}, {what}: the debug layer reports an error: {}", self.step, error.unwrap_or_default());
  857. }
  858. /// Gives tiles as a submission would, and stops if the mapping
  859. /// call was refused.
  860. fn give(&self, tiled: &Tiled, texture: &ID3D12Resource, levels: u32) {
  861. tiled.give_on(&self.queue, &self.device, texture, levels, levels);
  862. self.check("tiles given");
  863. }
  864. /// Records with `record`, runs the list behind what is already on
  865. /// the queue (tile mappings among it), waits for the card and
  866. /// opens the list again.
  867. fn run(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) {
  868. record(&self.list);
  869. self.submitted += 1;
  870. // SAFETY: our list, queue and fence; the allocator is reset
  871. // only after the card finished everything recorded from it.
  872. unsafe {
  873. self.list.Close().unwrap();
  874. let run: ID3D12CommandList = self.list.cast().unwrap();
  875. self.queue.ExecuteCommandLists(&[Some(run)]);
  876. self.queue.Signal(&self.fence, self.submitted).unwrap();
  877. self.fence.SetEventOnCompletion(self.submitted, self.event).unwrap();
  878. // Never without end: a step is a few copies of a few
  879. // megabytes. On the card the limit stays under Windows' own
  880. // two seconds; the software adapter, which compiles its
  881. // shader on first use and resets nothing, gets longer.
  882. let limit = if self.card { 1500 } else { 20_000 };
  883. let waited = WaitForSingleObject(self.event, limit);
  884. self.check("a submission");
  885. assert!(
  886. waited == WAIT_OBJECT_0,
  887. "{}: a submission did not finish within {limit} ms; stopped before another is sent",
  888. self.step
  889. );
  890. self.allocator.Reset().unwrap();
  891. self.list.Reset(&self.allocator, None).unwrap();
  892. }
  893. }
  894. fn buffer(&self, kind: D3D12_HEAP_TYPE, flags: D3D12_RESOURCE_FLAGS, state: D3D12_RESOURCE_STATES, bytes: u64) -> ID3D12Resource {
  895. let heap = D3D12_HEAP_PROPERTIES {
  896. Type: kind,
  897. ..Default::default()
  898. };
  899. let desc = D3D12_RESOURCE_DESC {
  900. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  901. Width: bytes,
  902. Height: 1,
  903. DepthOrArraySize: 1,
  904. MipLevels: 1,
  905. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  906. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  907. Flags: flags,
  908. ..Default::default()
  909. };
  910. let mut out: Option<ID3D12Resource> = None;
  911. // SAFETY: plain buffer creation.
  912. unsafe {
  913. self.device
  914. .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out)
  915. .unwrap();
  916. }
  917. out.unwrap()
  918. }
  919. /// A square texture description of `side` texels and `levels`
  920. /// levels; `reserved`: in the layout a texture without memory of
  921. /// its own must have.
  922. fn desc(format: DXGI_FORMAT, side: u32, levels: u16, reserved: bool) -> D3D12_RESOURCE_DESC {
  923. D3D12_RESOURCE_DESC {
  924. Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  925. Width: u64::from(side),
  926. Height: side,
  927. DepthOrArraySize: 1,
  928. MipLevels: levels,
  929. Format: format,
  930. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  931. Layout: if reserved { D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE } else { D3D12_TEXTURE_LAYOUT_UNKNOWN },
  932. ..Default::default()
  933. }
  934. }
  935. /// A texture without memory, in the state copies into it need, and
  936. /// how the card cuts it.
  937. fn reserved(&self, desc: &D3D12_RESOURCE_DESC) -> (ID3D12Resource, Tiled) {
  938. let mut made: Option<ID3D12Resource> = None;
  939. // SAFETY: plain creation; a texture that is no target has no clear value.
  940. let asked = unsafe {
  941. self.device
  942. .CreateReservedResource(desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut made)
  943. };
  944. // The layer's reason first, if it refused.
  945. self.check("a texture without memory made");
  946. asked.expect("a reserved texture");
  947. let texture = made.expect("a reserved texture");
  948. let tiled = Tiled::make(&self.device, &texture, u32::from(desc.MipLevels)).expect("the card says how it cuts the texture");
  949. (texture, tiled)
  950. }
  951. fn footprints(&self, desc: &D3D12_RESOURCE_DESC) -> Laid {
  952. let levels = usize::from(desc.MipLevels);
  953. let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); levels];
  954. let mut rows = vec![0u32; levels];
  955. let mut wide = vec![0u64; levels];
  956. let mut total = 0u64;
  957. // SAFETY: outputs for `levels` subresources.
  958. unsafe {
  959. self.device.GetCopyableFootprints(
  960. desc,
  961. 0,
  962. levels as u32,
  963. 0,
  964. Some(footprints.as_mut_ptr()),
  965. Some(rows.as_mut_ptr()),
  966. Some(wide.as_mut_ptr()),
  967. Some(&mut total),
  968. );
  969. }
  970. Laid {
  971. footprints,
  972. rows,
  973. wide,
  974. total,
  975. }
  976. }
  977. /// An upload buffer of `total` bytes in which the bytes of each
  978. /// level are `byte(level)`.
  979. fn filled(&self, layout: &Laid, byte: impl Fn(usize) -> u8) -> ID3D12Resource {
  980. let (footprints, rows) = (&layout.footprints, &layout.rows);
  981. let upload = self.buffer(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ, layout.total);
  982. // SAFETY: the buffer is `total` bytes; each level's rows lie inside it.
  983. unsafe {
  984. let mut data = std::ptr::null_mut();
  985. upload.Map(0, None, Some(&mut data)).unwrap();
  986. for (level, f) in footprints.iter().enumerate() {
  987. let len = rows[level] as usize * f.Footprint.RowPitch as usize;
  988. std::slice::from_raw_parts_mut(data.cast::<u8>().add(f.Offset as usize), len).fill(byte(level));
  989. }
  990. upload.Unmap(0, None);
  991. }
  992. upload
  993. }
  994. /// Copies every level of `texture` from `upload`, then every level
  995. /// back, and gives for each level the first sixteen bytes read of
  996. /// its first row and of the row and column half way (another tile
  997. /// of a level of several).
  998. fn round_trip(
  999. &mut self,
  1000. texture: &ID3D12Resource,
  1001. layout: &Laid,
  1002. upload: Option<&ID3D12Resource>,
  1003. ) -> Vec<[Vec<u8>; 2]> {
  1004. let (footprints, rows) = (&layout.footprints, &layout.rows);
  1005. let back = self.buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST, layout.total);
  1006. self.run(|list| {
  1007. // SAFETY: an open list; the texture and buffers outlive the run.
  1008. unsafe {
  1009. if let Some(upload) = upload {
  1010. for (level, f) in footprints.iter().enumerate() {
  1011. list.CopyTextureRegion(&sub(texture, level as u32), 0, 0, 0, &placed(upload, *f), None);
  1012. }
  1013. }
  1014. list.ResourceBarrier(&[transition(texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
  1015. for (level, f) in footprints.iter().enumerate() {
  1016. list.CopyTextureRegion(&placed(&back, *f), 0, 0, 0, &sub(texture, level as u32), None);
  1017. }
  1018. list.ResourceBarrier(&[transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST)]);
  1019. }
  1020. });
  1021. let mut read = Vec::new();
  1022. // SAFETY: a read-back buffer of `total` bytes the finished list copied into.
  1023. unsafe {
  1024. let mut data = std::ptr::null_mut();
  1025. back.Map(0, None, Some(&mut data)).unwrap();
  1026. for (level, f) in footprints.iter().enumerate() {
  1027. let pitch = f.Footprint.RowPitch as usize;
  1028. let len = rows[level] as usize * pitch;
  1029. let bytes = std::slice::from_raw_parts(data.cast::<u8>().cast_const().add(f.Offset as usize), len);
  1030. // The bytes of a row that are the level's own (its
  1031. // blocks or texels; the rest of the pitch is padding).
  1032. let own = layout.wide[level] as usize;
  1033. let wide = own.min(len).min(16);
  1034. let first = bytes[..wide].to_vec();
  1035. let middle = (rows[level] as usize / 2) * pitch + ((own / 2) & !15);
  1036. let far = if rows[level] >= 2 && own >= 32 && middle + wide <= len {
  1037. bytes[middle..middle + wide].to_vec()
  1038. } else {
  1039. first.clone()
  1040. };
  1041. read.push([first, far]);
  1042. }
  1043. back.Unmap(0, None);
  1044. }
  1045. read
  1046. }
  1047. }
  1048. fn sub(texture: &ID3D12Resource, index: u32) -> D3D12_TEXTURE_COPY_LOCATION {
  1049. D3D12_TEXTURE_COPY_LOCATION {
  1050. // SAFETY: a borrowed pointer the location never releases.
  1051. pResource: unsafe { std::mem::transmute_copy(texture) },
  1052. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  1053. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: index },
  1054. }
  1055. }
  1056. fn placed(buffer: &ID3D12Resource, footprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT) -> D3D12_TEXTURE_COPY_LOCATION {
  1057. D3D12_TEXTURE_COPY_LOCATION {
  1058. // SAFETY: as above.
  1059. pResource: unsafe { std::mem::transmute_copy(buffer) },
  1060. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  1061. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint },
  1062. }
  1063. }
  1064. fn all(bytes: &[Vec<u8>; 2], want: u8) -> bool {
  1065. bytes.iter().all(|part| part.iter().all(|&b| b == want))
  1066. }
  1067. /// The levels from `first` on, a bit a level.
  1068. fn from_level(first: u32) -> u32 {
  1069. (u32::MAX << first) & ((1 << u32::from(LEVELS)) - 1)
  1070. }
  1071. /// (i) Levels arrive one by one: after each step every level with
  1072. /// tiles reads back its own bytes and every level without reads zeros.
  1073. fn levels_arrive(rig: &mut Rig, format: DXGI_FORMAT) {
  1074. rig.step = if format == DXGI_FORMAT_BC7_UNORM { "step 1, levels arrive (BC7)" } else { "step 1, levels arrive (BC3)" };
  1075. let desc = Rig::desc(format, SIDE, LEVELS, true);
  1076. let (texture, tiled) = rig.reserved(&desc);
  1077. // (The card packs the levels smaller than a tile into shared
  1078. // tiles; the software adapter may give each its own.)
  1079. eprintln!(
  1080. "format {}: {} levels with tiles of their own ({:?} tiles), {} tiles for the packed ones",
  1081. format.0,
  1082. tiled.standard.len(),
  1083. tiled.standard,
  1084. tiled.packed
  1085. );
  1086. assert!(!rig.card || tiled.packed > 0, "on the card a 1024 texture has levels smaller than a tile");
  1087. let layout = rig.footprints(&desc);
  1088. let upload = rig.filled(&layout, |level| level as u8 + 1);
  1089. for first in [3u32, 1, 0] {
  1090. // Ahead of the list on the queue, as at a submission.
  1091. rig.give(&tiled, &texture, from_level(first));
  1092. let read = rig.round_trip(&texture, &layout, Some(&upload));
  1093. for (level, bytes) in read.iter().enumerate() {
  1094. let want = if tiled.has_tiles(level as u32) { level as u8 + 1 } else { 0 };
  1095. assert!(all(bytes, want), "format {} from level {first}: level {level} reads {bytes:?}, wanted {want}", format.0);
  1096. }
  1097. }
  1098. assert!(tiled.whole());
  1099. assert_eq!(tiled.first_shown(), Some(0));
  1100. }
  1101. /// (ii) A copy on the card into a level without tiles is dropped; the
  1102. /// same copy in a list that runs after the level was given lands.
  1103. fn a_card_copy_lands_after_the_give(rig: &mut Rig) {
  1104. rig.step = "step 2, a copy on the card into a level without tiles";
  1105. let format = DXGI_FORMAT_BC7_UNORM;
  1106. let desc = Rig::desc(format, SIDE, LEVELS, true);
  1107. let (texture, tiled) = rig.reserved(&desc);
  1108. let layout = rig.footprints(&desc);
  1109. // The last level with tiles of its own, and a texture of its size
  1110. // with every byte 0x5a to copy from.
  1111. let level = tiled.standard.len() as u32 - 1;
  1112. let source_desc = Rig::desc(format, SIDE >> level, 1, false);
  1113. let source_layout = rig.footprints(&source_desc);
  1114. let source_bytes = rig.filled(&source_layout, |_| 0x5a);
  1115. let mut made: Option<ID3D12Resource> = None;
  1116. let heap = D3D12_HEAP_PROPERTIES {
  1117. Type: D3D12_HEAP_TYPE_DEFAULT,
  1118. ..Default::default()
  1119. };
  1120. // SAFETY: plain texture creation.
  1121. unsafe {
  1122. rig.device
  1123. .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &source_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut made)
  1124. .unwrap();
  1125. }
  1126. let source = made.unwrap();
  1127. rig.run(|list| {
  1128. // SAFETY: an open list and live resources.
  1129. unsafe {
  1130. list.CopyTextureRegion(&sub(&source, 0), 0, 0, 0, &placed(&source_bytes, source_layout.footprints[0]), None);
  1131. list.ResourceBarrier(&[transition(&source, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
  1132. // No tiles yet: this copy goes nowhere.
  1133. list.CopyTextureRegion(&sub(&texture, level), 0, 0, 0, &sub(&source, 0), None);
  1134. }
  1135. });
  1136. let before = rig.round_trip(&texture, &layout, None);
  1137. assert!(all(&before[level as usize], 0), "a copy into a level without tiles left {:?}", before[level as usize]);
  1138. // As `texture.rs` `card_writes` has it: the give at the list's
  1139. // submission, the copy in the list.
  1140. assert_ne!(tiled.claim(tiled.with_level(level)), 0, "the level is new");
  1141. rig.give(&tiled, &texture, tiled.with_level(level));
  1142. rig.run(|list| {
  1143. // SAFETY: as above.
  1144. unsafe { list.CopyTextureRegion(&sub(&texture, level), 0, 0, 0, &sub(&source, 0), None) };
  1145. });
  1146. let after = rig.round_trip(&texture, &layout, None);
  1147. assert!(all(&after[level as usize], 0x5a), "the copy after the give left {:?}", after[level as usize]);
  1148. assert_eq!(tiled.claim(tiled.with_level(level)), 0, "claimed once");
  1149. }
  1150. /// (iii) Tiles a texture gave back go to the next one, which reads
  1151. /// what was written into it and zeros where it has no tiles; what a
  1152. /// level given and not written reads is printed (the reason no level
  1153. /// is given outside a list that writes it).
  1154. fn a_reused_tile_reads_as_written(rig: &mut Rig) {
  1155. rig.step = "step 3, a reused tile";
  1156. let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true);
  1157. let layout = rig.footprints(&desc);
  1158. let (first, first_tiles) = rig.reserved(&desc);
  1159. let level = first_tiles.standard.len() as u32 - 1;
  1160. rig.give(&first_tiles, &first, 1 << level);
  1161. let upload = rig.filled(&layout, |_| 0xa5);
  1162. let read = rig.round_trip(&first, &layout, Some(&upload));
  1163. assert!(all(&read[level as usize], 0xa5));
  1164. let runs = first_tiles.given.lock().unwrap().runs.clone();
  1165. drop(first_tiles);
  1166. drop(first);
  1167. let (second, second_tiles) = rig.reserved(&desc);
  1168. rig.give(&second_tiles, &second, 1 << level);
  1169. let reused = second_tiles.given.lock().unwrap().runs == runs;
  1170. let unwritten = rig.round_trip(&second, &layout, None);
  1171. eprintln!(
  1172. "a level given tiles and not written reads {:?} (its tiles are the first texture's: {reused})",
  1173. &unwritten[level as usize][0][..4]
  1174. );
  1175. let upload = rig.filled(&layout, |_| 0x3c);
  1176. let read = rig.round_trip(&second, &layout, Some(&upload));
  1177. assert!(all(&read[level as usize], 0x3c), "the reused level reads {:?}", read[level as usize]);
  1178. assert!(all(&read[0], 0), "level 0 has no tiles and reads {:?}", read[0]);
  1179. }
  1180. /// (iv) A level whose tiles come from several runs of the heap (single
  1181. /// free tiles between taken ones) reads as written in every tile.
  1182. fn a_level_on_several_ranges(rig: &mut Rig) {
  1183. rig.step = "step 4, a level on several ranges of the heap";
  1184. // Three single tiles; the first and the last go back, the middle
  1185. // one stays taken.
  1186. let singles: Vec<_> = (0..3).map(|_| take(&rig.device, 1).expect("a tile")).collect();
  1187. give_back(singles[0].1, &singles[0].2);
  1188. give_back(singles[2].1, &singles[2].2);
  1189. let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true);
  1190. let layout = rig.footprints(&desc);
  1191. let (texture, tiled) = rig.reserved(&desc);
  1192. // Level 1 of a 1024 texture: four tiles.
  1193. assert!(tiled.standard.len() > 1 && tiled.standard[1] >= 2);
  1194. rig.give(&tiled, &texture, 1 << 1);
  1195. let runs = tiled.given.lock().unwrap().runs.len();
  1196. eprintln!("level 1 ({} tiles) was mapped on {runs} ranges", tiled.standard[1]);
  1197. assert!(runs >= 2, "the single free tiles were not used first");
  1198. let upload = rig.filled(&layout, |_| 0x77);
  1199. let read = rig.round_trip(&texture, &layout, Some(&upload));
  1200. assert!(all(&read[1], 0x77), "level 1 reads {:?}", read[1]);
  1201. give_back(singles[1].1, &singles[1].2);
  1202. }
  1203. /// (v) A view made by [`show_from`] of a texture whose level 0 has no
  1204. /// tiles returns level 1's colour for a sample at level 0; the view as
  1205. /// the title asked returns zero.
  1206. fn the_view_starts_at_the_first_level_with_tiles(rig: &mut Rig) -> Option<()> {
  1207. rig.step = "step 5, the view from the first level with tiles";
  1208. let cs = compile(LOOK, s!("look"), s!("cs_5_1")).ok()?;
  1209. let format = DXGI_FORMAT_R8G8B8A8_UNORM;
  1210. let desc = Rig::desc(format, SIDE, LEVELS, true);
  1211. let layout = rig.footprints(&desc);
  1212. let (texture, tiled) = rig.reserved(&desc);
  1213. // Every level but the largest; each level's bytes are sixteen
  1214. // times its number plus one.
  1215. rig.give(&tiled, &texture, from_level(1));
  1216. assert_eq!(tiled.first_shown(), Some(1));
  1217. let upload = rig.filled(&layout, |level| (level as u8 + 1) * 16);
  1218. rig.round_trip(&texture, &layout, Some(&upload));
  1219. // SAFETY: plain object creation; the views are made in a heap
  1220. // that lives to the end of the function, of a live texture.
  1221. let (root, pipeline, views, words, back) = unsafe {
  1222. let root: ID3D12RootSignature = rig.device.CreateRootSignature(0, &cs[..]).ok()?;
  1223. let pipeline: ID3D12PipelineState = rig
  1224. .device
  1225. .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  1226. pRootSignature: std::mem::transmute_copy(&root),
  1227. CS: D3D12_SHADER_BYTECODE {
  1228. pShaderBytecode: cs.as_ptr().cast(),
  1229. BytecodeLength: cs.len(),
  1230. },
  1231. ..Default::default()
  1232. })
  1233. .ok()?;
  1234. let views: ID3D12DescriptorHeap = rig
  1235. .device
  1236. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  1237. Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  1238. NumDescriptors: 2,
  1239. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  1240. NodeMask: 0,
  1241. })
  1242. .ok()?;
  1243. let as_asked = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1244. Format: format,
  1245. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
  1246. Shader4ComponentMapping: 5768,
  1247. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1248. Texture2D: D3D12_TEX2D_SRV {
  1249. MostDetailedMip: 0,
  1250. MipLevels: u32::MAX,
  1251. PlaneSlice: 0,
  1252. ResourceMinLODClamp: 0.0,
  1253. },
  1254. },
  1255. };
  1256. let mut shown = as_asked;
  1257. show_from(&mut shown, tiled.first_shown()?, u32::from(LEVELS));
  1258. assert_eq!(shown.Anonymous.Texture2D.MostDetailedMip, 1);
  1259. let step = rig.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize;
  1260. let mut at = views.GetCPUDescriptorHandleForHeapStart();
  1261. rig.device.CreateShaderResourceView(&texture, Some(&raw const shown), at);
  1262. at.ptr += step;
  1263. rig.device.CreateShaderResourceView(&texture, Some(&raw const as_asked), at);
  1264. let words = rig.buffer(
  1265. D3D12_HEAP_TYPE_DEFAULT,
  1266. D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  1267. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  1268. 256,
  1269. );
  1270. let back = rig.buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST, 256);
  1271. (root, pipeline, views, words, back)
  1272. };
  1273. // Before the one dispatch: the pipeline and both views are sound.
  1274. rig.check("the pipeline and the views made");
  1275. rig.run(|list| {
  1276. // SAFETY: an open list and live objects.
  1277. unsafe {
  1278. list.ResourceBarrier(&[transition(&texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)]);
  1279. list.SetDescriptorHeaps(&[Some(views.clone())]);
  1280. list.SetComputeRootSignature(&root);
  1281. list.SetPipelineState(&pipeline);
  1282. list.SetComputeRootDescriptorTable(0, views.GetGPUDescriptorHandleForHeapStart());
  1283. list.SetComputeRootUnorderedAccessView(1, words.GetGPUVirtualAddress());
  1284. list.Dispatch(1, 1, 1);
  1285. list.ResourceBarrier(&[transition(&words, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
  1286. list.CopyBufferRegion(&back, 0, &words, 0, 16);
  1287. }
  1288. });
  1289. // SAFETY: a read-back buffer the finished list copied sixteen bytes into.
  1290. let read = unsafe {
  1291. let mut data = std::ptr::null_mut();
  1292. let range = D3D12_RANGE { Begin: 0, End: 16 };
  1293. back.Map(0, Some(&range), Some(&mut data)).unwrap();
  1294. let read = std::slice::from_raw_parts(data.cast::<u32>(), 2).to_vec();
  1295. back.Unmap(0, None);
  1296. read
  1297. };
  1298. eprintln!("a sample at level 0: {} through the view from level 1, {} through the view as asked", read[0], read[1]);
  1299. assert_eq!(read[0], 32, "the view from the first level with tiles reads level 1");
  1300. assert_eq!(read[1], 0, "the view from level 0 reads a level without tiles");
  1301. Some(())
  1302. }
  1303. fn a_full_card_keeps_new_levels_waiting(rig: &mut Rig) {
  1304. rig.step = "step 6, no room on the card: held levels wait, and get their tiles when asked again";
  1305. let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true);
  1306. let (texture, tiled) = rig.reserved(&desc);
  1307. let layout = rig.footprints(&desc);
  1308. let upload = rig.filled(&layout, |level| level as u8 + 1);
  1309. let read_as_given = |rig: &mut Rig, what: &str| {
  1310. let read = rig.round_trip(&texture, &layout, Some(&upload));
  1311. for (level, bytes) in read.iter().enumerate() {
  1312. let want = if tiled.has_tiles(level as u32) { level as u8 + 1 } else { 0 };
  1313. assert!(all(bytes, want), "{what}: level {level} reads {bytes:?}, wanted {want}");
  1314. }
  1315. };
  1316. // No room: nothing is given, the held levels are said to wait,
  1317. // nothing is shown, every level reads zeros.
  1318. let (changed, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(3), false);
  1319. rig.check("an upload without room");
  1320. assert!(!changed && waiting, "without room: changed {changed}, waiting {waiting}");
  1321. assert_eq!(tiled.given_bytes(), 0, "without room no tile is given");
  1322. assert_eq!(tiled.first_shown(), None);
  1323. read_as_given(rig, "without room");
  1324. // Asked again with room: the same levels get theirs.
  1325. let (changed, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(3), true);
  1326. rig.check("the upload again, with room");
  1327. assert!(changed && !waiting, "with room: changed {changed}, waiting {waiting}");
  1328. assert!(tiled.has_tiles(3) && !tiled.has_tiles(2));
  1329. assert_eq!(tiled.first_shown(), Some(3));
  1330. read_as_given(rig, "with room");
  1331. // More levels held and no room again: the ones that have tiles
  1332. // are brought up to date, the new ones wait, the view stays.
  1333. let before = tiled.given_bytes();
  1334. let (changed, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(1), false);
  1335. rig.check("more levels held, without room");
  1336. assert!(!changed && waiting, "more levels without room: changed {changed}, waiting {waiting}");
  1337. assert_eq!(tiled.given_bytes(), before);
  1338. assert_eq!(tiled.first_shown(), Some(3));
  1339. read_as_given(rig, "more levels without room");
  1340. // The card's own write is not kept waiting, and brings only its
  1341. // own level: level 1 still waits although it is held.
  1342. assert_eq!(tiled.claim(1 << 0), 1 << 0);
  1343. let changed = tiled.card_wrote_on(&rig.queue, &rig.device, &texture, 1 << 0);
  1344. rig.check("the card's own write, without room");
  1345. assert!(changed && tiled.has_tiles(0) && !tiled.has_tiles(1) && !tiled.has_tiles(2));
  1346. assert_eq!(tiled.first_shown(), Some(0));
  1347. assert_eq!(tiled.claim(1 << 0), 0, "a level with tiles is not claimed again");
  1348. // With room everything held gets its tiles.
  1349. let (_, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(1), true);
  1350. rig.check("the last upload, with room");
  1351. assert!(!waiting && tiled.whole());
  1352. read_as_given(rig, "everything given");
  1353. }
  1354. fn a_claim_given_up_is_made_again(rig: &mut Rig) {
  1355. rig.step = "step 7, a claim whose zeros never landed is given up";
  1356. let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true);
  1357. let (_texture, tiled) = rig.reserved(&desc);
  1358. let level = tiled.with_level(2);
  1359. assert_eq!(tiled.claim(level), level, "the level is new");
  1360. assert_eq!(tiled.claim(level), 0, "claimed once");
  1361. // The list that claimed it was reset without being submitted.
  1362. tiled.unclaim(level);
  1363. assert_eq!(tiled.claim(level), level, "claimed again after it was given up");
  1364. // The small levels the card packs together are claimed together.
  1365. let small = tiled.with_level(u32::from(LEVELS) - 1);
  1366. assert!(!rig.card || small.count_ones() > 1, "on the card a 1024 texture has several levels in one tile");
  1367. assert_eq!(tiled.claim(1 << (u32::from(LEVELS) - 1)), 1 << (u32::from(LEVELS) - 1));
  1368. tiled.unclaim(small);
  1369. assert_eq!(tiled.claim(small), small);
  1370. }
  1371. /// On the software adapter unless `VICTORY_TILES_TEST_CARD=1`.
  1372. #[test]
  1373. #[ignore = "on the card: run it by name with --ignored --nocapture"]
  1374. fn levels_on_demand_on_the_card() {
  1375. let Some(mut rig) = Rig::new() else {
  1376. eprintln!("no adapter with tiled resources of tier 2, or no debug layer for a run on the card; skipped");
  1377. return;
  1378. };
  1379. rig.check("the device made");
  1380. levels_arrive(&mut rig, DXGI_FORMAT_BC7_UNORM);
  1381. levels_arrive(&mut rig, DXGI_FORMAT_BC3_UNORM);
  1382. a_card_copy_lands_after_the_give(&mut rig);
  1383. a_reused_tile_reads_as_written(&mut rig);
  1384. a_level_on_several_ranges(&mut rig);
  1385. a_full_card_keeps_new_levels_waiting(&mut rig);
  1386. a_claim_given_up_is_made_again(&mut rig);
  1387. if the_view_starts_at_the_first_level_with_tiles(&mut rig).is_none() {
  1388. eprintln!("the view test's shader or objects could not be made; that part was skipped");
  1389. }
  1390. rig.step = "the end";
  1391. rig.check("every step done");
  1392. eprintln!(
  1393. "all steps passed {}",
  1394. if rig.card { "ON THE CARD" } else { "on the software adapter; VICTORY_TILES_TEST_CARD=1 is the run on the card" }
  1395. );
  1396. let s: Vec<u64> = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect();
  1397. eprintln!(
  1398. "{} calls of UpdateTileMappings took {} microseconds in all ({} a call); the pool's heaps {} MB, {} given back",
  1399. s[6],
  1400. s[7],
  1401. s[7] / s[6].max(1),
  1402. s[3] >> 20,
  1403. s[8]
  1404. );
  1405. }
  1406. #[test]
  1407. fn floor_saturates_instead_of_wrapping() {
  1408. assert_eq!(parse_floor(None), 1 << 20);
  1409. assert_eq!(parse_floor(Some("0")), 64 << 10);
  1410. assert_eq!(parse_floor(Some("2048")), 2048 << 10);
  1411. assert_eq!(parse_floor(Some(&(1u64 << 54).to_string())), u64::MAX);
  1412. assert_eq!(parse_floor(Some(&u64::MAX.to_string())), u64::MAX);
  1413. }
  1414. #[test]
  1415. fn show_from_clamps_2d_and_2d_array_and_adjusts_min_lod() {
  1416. let mut srv2d = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1417. Format: DXGI_FORMAT_R8G8B8A8_UNORM,
  1418. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
  1419. Shader4ComponentMapping: 5768,
  1420. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1421. Texture2D: D3D12_TEX2D_SRV {
  1422. MostDetailedMip: 0,
  1423. MipLevels: 12,
  1424. PlaneSlice: 0,
  1425. ResourceMinLODClamp: 3.5,
  1426. },
  1427. },
  1428. };
  1429. show_from(&mut srv2d, 3, 11);
  1430. // SAFETY: `ViewDimension` is `TEXTURE2D`.
  1431. let v2d = unsafe { srv2d.Anonymous.Texture2D };
  1432. assert_eq!(v2d.MostDetailedMip, 3);
  1433. // Clamped to remaining levels (11 - 3 = 8), not 12 - 3 = 9.
  1434. assert_eq!(v2d.MipLevels, 8);
  1435. assert_eq!(v2d.ResourceMinLODClamp, 0.5);
  1436. let mut srv_arr = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1437. Format: DXGI_FORMAT_R8G8B8A8_UNORM,
  1438. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY,
  1439. Shader4ComponentMapping: 5768,
  1440. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1441. Texture2DArray: D3D12_TEX2D_ARRAY_SRV {
  1442. MostDetailedMip: 0,
  1443. MipLevels: 6,
  1444. FirstArraySlice: 0,
  1445. ArraySize: 1,
  1446. PlaneSlice: 0,
  1447. ResourceMinLODClamp: 1.5,
  1448. },
  1449. },
  1450. };
  1451. show_from(&mut srv_arr, 2, 11);
  1452. // SAFETY: `ViewDimension` is `TEXTURE2DARRAY`.
  1453. let varr = unsafe { srv_arr.Anonymous.Texture2DArray };
  1454. assert_eq!(varr.MostDetailedMip, 2);
  1455. assert_eq!(varr.MipLevels, 4);
  1456. assert_eq!(varr.ResourceMinLODClamp, 0.0);
  1457. }
  1458. #[test]
  1459. fn card_wrote_failure_does_not_poison_card_mask() {
  1460. let Some(host) = host() else {
  1461. return;
  1462. };
  1463. // A dummy live resource (never mapped because `take()` rejects `HEAP_TILES + 1`).
  1464. let heap = D3D12_HEAP_PROPERTIES {
  1465. Type: D3D12_HEAP_TYPE_DEFAULT,
  1466. ..Default::default()
  1467. };
  1468. let desc = Rig::desc(DXGI_FORMAT_R8G8B8A8_UNORM, 64, 2, false);
  1469. let mut tex: Option<ID3D12Resource> = None;
  1470. // SAFETY: plain texture creation on the host device.
  1471. unsafe {
  1472. host.device
  1473. .CreateCommittedResource(
  1474. &heap,
  1475. D3D12_HEAP_FLAG_NONE,
  1476. &desc,
  1477. D3D12_RESOURCE_STATE_COMMON,
  1478. None,
  1479. &mut tex,
  1480. )
  1481. .unwrap();
  1482. }
  1483. let tex = tex.unwrap();
  1484. STATS[0].fetch_add(1, Ordering::Relaxed);
  1485. STATS[1].fetch_add(TILE, Ordering::Relaxed);
  1486. let mut tiled = Tiled {
  1487. // Level 0 demands > HEAP_TILES so `take()` fails deterministically.
  1488. standard: vec![HEAP_TILES + 1, 1],
  1489. packed: 0,
  1490. levels: 2,
  1491. full: TILE,
  1492. given: Mutex::new(Given {
  1493. levels: vec![false, false],
  1494. packed: false,
  1495. runs: Vec::new(),
  1496. }),
  1497. shown: AtomicU32::new(u32::MAX),
  1498. held: AtomicU32::new(0),
  1499. card: AtomicU32::new(0),
  1500. claimed: AtomicU32::new(0),
  1501. };
  1502. assert_eq!(tiled.claim(1 << 0), 1 << 0);
  1503. let changed = tiled.card_wrote_on(host.queue(), &host.device, &tex, 1 << 0);
  1504. assert!(!changed);
  1505. assert_eq!(tiled.card.load(Ordering::Relaxed), 0, "failed tile allocation must not poison `card`");
  1506. assert_eq!(tiled.first_shown(), None);
  1507. assert_eq!(tiled.claim(1 << 0), 1 << 0, "failed level must be unclaimed");
  1508. // Even if level 0 later becomes allocatable, an upload with `room == false`
  1509. // that does not hold level 0 must not treat level 0 as card-owned.
  1510. tiled.standard[0] = 1;
  1511. let (changed, waiting) = tiled.uploaded_on(host.queue(), &host.device, &tex, 1 << 1, false);
  1512. assert!(!changed && waiting);
  1513. assert!(!tiled.has_tiles(0));
  1514. assert_eq!(tiled.given_bytes(), 0);
  1515. }
  1516. }