resource.rs 139 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739
  1. //! Heaps, committed and placed resources, and resource sizes.
  2. //!
  3. //! Heaps and resources are host memory and a resource's GPU address is its
  4. //! CPU address, as on the console; textures also get a host copy, and
  5. //! buffers a host copy when a draw reads them (`shadow`).
  6. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  7. use std::alloc::{Layout, alloc_zeroed, dealloc};
  8. use std::ffi::c_void;
  9. use std::ptr::NonNull;
  10. use victory_formats::texture;
  11. use crate::object::{
  12. self, E_INVALIDARG, E_OUTOFMEMORY, HEAP, HRESULT, Iid, Object, RESOURCE, S_OK, Table, This,
  13. guid,
  14. };
  15. /// The interfaces every device child also answers for.
  16. pub(crate) const PAGEABLE_IIDS: [Iid; 3] = [
  17. guid(
  18. 0x63ee58fb,
  19. 0x1268,
  20. 0x4835,
  21. [0x86, 0xda, 0xf0, 0x08, 0xce, 0x62, 0xf0, 0xd6],
  22. ),
  23. guid(
  24. 0x905db94b,
  25. 0xa00c,
  26. 0x4140,
  27. [0x9d, 0xf5, 0x2b, 0x64, 0xca, 0x9e, 0xa3, 0x57],
  28. ),
  29. guid(
  30. 0xc4fec28f,
  31. 0x7966,
  32. 0x4e95,
  33. [0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8],
  34. ),
  35. ];
  36. const HEAP_IIDS: [Iid; 4] = [
  37. guid(
  38. 0x6b3b2502,
  39. 0x6e51,
  40. 0x45b3,
  41. [0x90, 0xee, 0x98, 0x84, 0x26, 0x5e, 0x8d, 0xf3],
  42. ),
  43. PAGEABLE_IIDS[0],
  44. PAGEABLE_IIDS[1],
  45. PAGEABLE_IIDS[2],
  46. ];
  47. const RESOURCE_IIDS: [Iid; 4] = [
  48. guid(
  49. 0x696442be,
  50. 0xa72e,
  51. 0x4059,
  52. [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad],
  53. ),
  54. PAGEABLE_IIDS[0],
  55. PAGEABLE_IIDS[1],
  56. PAGEABLE_IIDS[2],
  57. ];
  58. const KIB_64: u64 = 64 << 10;
  59. const MIB_4: u64 = 4 << 20;
  60. #[repr(C)]
  61. #[derive(Debug, Clone, Copy)]
  62. pub(crate) struct HeapProperties {
  63. kind: u32,
  64. cpu_pages: u32,
  65. pool: u32,
  66. creation_nodes: u32,
  67. visible_nodes: u32,
  68. }
  69. #[repr(C)]
  70. #[derive(Debug, Clone, Copy)]
  71. pub(crate) struct HeapDesc {
  72. size: u64,
  73. properties: HeapProperties,
  74. alignment: u64,
  75. flags: u32,
  76. }
  77. #[repr(C)]
  78. #[derive(Debug, Clone, Copy)]
  79. pub(crate) struct ResourceDesc {
  80. dimension: u32,
  81. alignment: u64,
  82. width: u64,
  83. height: u32,
  84. depth_or_array_size: u16,
  85. mip_levels: u16,
  86. format: u32,
  87. sample_count: u32,
  88. sample_quality: u32,
  89. layout: u32,
  90. flags: u32,
  91. }
  92. #[repr(C)]
  93. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  94. pub(crate) struct AllocationInfo {
  95. size: u64,
  96. alignment: u64,
  97. }
  98. const _: () = assert!(size_of::<HeapProperties>() == 20);
  99. const _: () = assert!(size_of::<HeapDesc>() == 48);
  100. const _: () = assert!(size_of::<ResourceDesc>() == 56);
  101. const BUFFER: u32 = 1;
  102. const TEXTURE_3D: u32 = 4;
  103. /// Bytes per element and the element's width in texels (4 for block
  104. /// compression), by DXGI format number. `None` for 1-bit and video
  105. /// formats. The console adds 116/117 (10-bit float color), 118-120 (16-bit
  106. /// depth with 8-bit stencil, two planes: 3 bytes per texel), 189 (signed
  107. /// 10-bit color), 190 (two 4-bit channels) and 191 (24/8 color).
  108. pub(crate) fn element(format: u32) -> Option<(u64, u64)> {
  109. Some(match format {
  110. 1..=4 => (16, 1),
  111. 5..=8 => (12, 1),
  112. 9..=22 => (8, 1),
  113. 23..=47 | 67 | 87..=93 | 116 | 117 | 189 | 191 => (4, 1),
  114. 118..=120 => (3, 1),
  115. 48..=59 | 68 | 69 | 85 | 86 | 115 => (2, 1),
  116. 60..=65 | 190 => (1, 1),
  117. 70..=72 | 79..=81 => (8, 4),
  118. 73..=78 | 82..=84 | 94..=99 => (16, 4),
  119. _ => return None,
  120. })
  121. }
  122. /// A texture's layout in console memory, as the console's layout library
  123. /// gives it (`victory-hle`'s `xg` serves the same): the description's
  124. /// layout field is `0x100 | swizzle mode`, 1 linear, 0 the library's pick.
  125. pub(crate) fn texture_layout(desc: &ResourceDesc) -> Option<texture::Texture> {
  126. use texture::{Dimension, Swizzle, TextureDesc};
  127. const TEXTURE_1D: u32 = 2;
  128. const TEXTURE_2D: u32 = 3;
  129. const RENDER_TARGET: u32 = 1;
  130. const DEPTH: u32 = 2;
  131. let dimension = match desc.dimension {
  132. TEXTURE_1D => Dimension::Tex1d,
  133. TEXTURE_2D => Dimension::Tex2d,
  134. TEXTURE_3D => Dimension::Tex3d,
  135. _ => return None,
  136. };
  137. let swizzle = match desc.layout {
  138. 0 if dimension == Dimension::Tex1d => Swizzle::LINEAR,
  139. 0 if desc.flags & DEPTH != 0 => Swizzle::SW_64KB_Z_X,
  140. 0 if desc.flags & RENDER_TARGET != 0 => Swizzle::SW_64KB_R_X,
  141. 0 => Swizzle::SW_4KB_S,
  142. 1 => Swizzle::LINEAR,
  143. l if l & !0xff == 0x100 => Swizzle(l & 0xff),
  144. _ => return None,
  145. };
  146. texture::Texture::new(&TextureDesc {
  147. dimension,
  148. width: u32::try_from(desc.width).ok()?,
  149. height: desc.height,
  150. depth_or_array: u32::from(desc.depth_or_array_size),
  151. mips: u32::from(desc.mip_levels),
  152. format: desc.format,
  153. samples: desc.sample_count.max(1),
  154. swizzle,
  155. })
  156. .ok()
  157. }
  158. /// Bytes and alignment a resource takes: buffers their width (64 KiB
  159. /// aligned), textures their console layout (formats it does not know:
  160. /// every mip of every array slice and sample, packed, 64 KiB aligned),
  161. /// rounded up to the alignment.
  162. fn footprint(desc: &ResourceDesc) -> Option<AllocationInfo> {
  163. if desc.dimension != BUFFER
  164. && let Some(t) = texture_layout(desc)
  165. {
  166. // As the console: the layout's own alignment unless more is asked
  167. // (4 KiB for 4 KiB modes, where PC says 64 KiB).
  168. // The title keeps these sizes in its texture tables, and its streaming
  169. // asserts when they disagree with the streamed layout.
  170. let alignment = desc.alignment.max(t.alignment);
  171. if !alignment.is_power_of_two() {
  172. return None;
  173. }
  174. return Some(AllocationInfo {
  175. size: t.size.checked_next_multiple_of(alignment)?,
  176. alignment,
  177. });
  178. }
  179. let bytes = if desc.dimension == BUFFER {
  180. desc.width
  181. } else {
  182. let (element, block) = element(desc.format)?;
  183. let (depth, slices) = if desc.dimension == TEXTURE_3D {
  184. (u64::from(desc.depth_or_array_size), 1)
  185. } else {
  186. (1, u64::from(desc.depth_or_array_size))
  187. };
  188. let height = u64::from(desc.height);
  189. let mips = mip_count(desc);
  190. let mut chain = 0u64;
  191. for mip in 0..mips.min(64) {
  192. let w = (desc.width >> mip).max(1).div_ceil(block);
  193. let h = (height >> mip).max(1).div_ceil(block);
  194. let d = (depth >> mip).max(1);
  195. chain = chain.checked_add(w.checked_mul(h)?.checked_mul(d)?.checked_mul(element)?)?;
  196. }
  197. chain
  198. .checked_mul(slices)?
  199. .checked_mul(u64::from(desc.sample_count.max(1)))?
  200. };
  201. if bytes == 0 {
  202. return None;
  203. }
  204. let minimum = if desc.sample_count > 1 { MIB_4 } else { KIB_64 };
  205. let alignment = desc.alignment.max(minimum);
  206. if !alignment.is_power_of_two() {
  207. return None;
  208. }
  209. Some(AllocationInfo {
  210. size: bytes.checked_next_multiple_of(KIB_64)?,
  211. alignment,
  212. })
  213. }
  214. /// A format as the host has it. The console's 16-bit depth with stencil
  215. /// (and its typeless views) has no PC format: the 24-bit ones stand in.
  216. pub(crate) fn pc_format(format: u32) -> u32 {
  217. match format {
  218. 118 => 45,
  219. 119 => 46,
  220. 120 => 47,
  221. other => other,
  222. }
  223. }
  224. /// The format of a texture the host GPU renders to or writes as unordered
  225. /// access, for the title's `format`. The console's GPU does both with the
  226. /// 16-bit colour formats B5G5R5A1 (86) and B4G4R4A4 (115), and
  227. /// the title has full-screen targets in both; a host that refuses either use
  228. /// (NVIDIA) refused the whole texture, so every pass that wrote it drew
  229. /// nothing. There 8-bit RGBA stands in: the same channels in the same
  230. /// order, every 4-bit level exact and every 5-bit level within 1/510.
  231. /// The title's pipelines and views of such targets name the stand-in too
  232. /// ([`view_format`], the host view checks).
  233. /// shortcut: copies between such a target and a texture the title fills
  234. /// itself in the 16-bit format are skipped ([`stands_in`]); convert them
  235. /// if a pass turns out to need one.
  236. pub(crate) fn target_format(format: u32) -> u32 {
  237. const STAND_INS: [(u32, u32); 2] = [(86, 28), (115, 28)];
  238. let Some(i) = STAND_INS.iter().position(|&(f, _)| f == format) else {
  239. return format;
  240. };
  241. #[cfg(windows)]
  242. {
  243. use windows::Win32::Graphics::Direct3D12::*;
  244. static REFUSED: std::sync::OnceLock<[bool; 2]> = std::sync::OnceLock::new();
  245. let refused = REFUSED.get_or_init(|| {
  246. STAND_INS.map(|(f, _)| {
  247. let Some(host) = crate::host::host() else {
  248. return false;
  249. };
  250. let mut support = D3D12_FEATURE_DATA_FORMAT_SUPPORT {
  251. Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(f as i32),
  252. ..Default::default()
  253. };
  254. // SAFETY: a plain query into our own structure.
  255. let asked = unsafe {
  256. host.device.CheckFeatureSupport(
  257. D3D12_FEATURE_FORMAT_SUPPORT,
  258. (&raw mut support).cast(),
  259. size_of_val(&support) as u32,
  260. )
  261. };
  262. let both = D3D12_FORMAT_SUPPORT1_RENDER_TARGET.0
  263. | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0;
  264. let refused = asked.is_err() || support.Support1.0 & both != both;
  265. if refused {
  266. tracing::info!(format = f, "the host does not render to this format: 8-bit RGBA stands in");
  267. }
  268. refused
  269. })
  270. });
  271. if refused[i] {
  272. return STAND_INS[i].1;
  273. }
  274. }
  275. format
  276. }
  277. /// Whether the host copy of the title texture `this` is in a stand-in
  278. /// format ([`target_format`]): its texels are not laid out as the title's.
  279. #[cfg(windows)]
  280. pub(crate) fn stands_in(this: This) -> bool {
  281. if this.is_null() {
  282. return false;
  283. }
  284. let own = pc_format(resource(this).desc.format);
  285. target_format(own) != own
  286. && host_resource(this)
  287. // SAFETY: a live resource.
  288. .is_some_and(|host| unsafe { host.GetDesc() }.Format.0 as u32 == target_format(own))
  289. }
  290. /// Depth textures the title also asks unordered access for (the console
  291. /// allows both; the host copy loses the unordered access): how many were
  292. /// made, and how often such a texture was bound as the depth target,
  293. /// cleared as depth, and asked for an unordered access view the host could
  294. /// not give. Measured to decide what such textures need (a colour twin, or
  295. /// to be colour textures altogether).
  296. pub(crate) static DEPTH_UNORDERED: [std::sync::atomic::AtomicU64; 4] =
  297. [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  298. /// Whether the title asked for both depth and unordered access for `this`.
  299. #[cfg(windows)]
  300. pub(crate) fn depth_and_unordered(this: This) -> bool {
  301. !this.is_null() && resource(this).desc.flags & 6 == 6
  302. }
  303. /// The colour twin of a depth texture the title also writes as unordered
  304. /// access. The console allows both on one texture; the host gives a depth
  305. /// texture no unordered access, so shaders write a colour texture of the
  306. /// same size and format family instead, and one is copied into the other
  307. /// when a side is used after the other was written
  308. /// (`HostList::twin_use`).
  309. /// shortcut: whole textures are copied, not the mips and slices written.
  310. /// A depth texture with a stencil plane gets a twin for each plane (
  311. /// the title's tiled lighting writes each pixel's material class into
  312. /// the depth plane and masks into the stencil plane, then draws each class
  313. /// with the depth test "equal"): the stencil plane's is copied through a
  314. /// buffer, the depth plane's is drawn into the plane by a pass of ours
  315. /// (`HostList::pass_plane`). Unordered access views of a multisampled
  316. /// texture stay null.
  317. #[cfg(windows)]
  318. pub(crate) struct Twin {
  319. /// The colour texture and the state it is in, as a host copy's.
  320. pub(crate) colour: std::sync::Arc<HostTexture>,
  321. /// Which side lacks what the other was written last, after the lists
  322. /// submitted so far: bit 0 the depth texture, bit 1 the twin.
  323. pub(crate) behind: std::sync::atomic::AtomicU32,
  324. /// For a depth texture with a stencil plane, `colour` is the twin of
  325. /// that plane (8 bits a texel) and this the buffer the two are copied
  326. /// through: no colour format shares a family with a depth-stencil
  327. /// format, but the host copies between a buffer and one plane.
  328. pub(crate) through: Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource>,
  329. /// For a depth texture with a stencil plane: the twin of its depth
  330. /// plane, 16 bits a texel for the console's 16-bit depth-stencil
  331. /// formats and a 32-bit float otherwise. No host colour format holds
  332. /// the bits of a 24-bit depth plane, so the two are not copied: a pass
  333. /// draws the twin into the plane.
  334. pub(crate) plane: Option<std::sync::Arc<HostTexture>>,
  335. }
  336. #[cfg(windows)]
  337. impl Drop for Twin {
  338. fn drop(&mut self) {
  339. TWINS[0].fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
  340. }
  341. }
  342. /// Colour twins alive, depth textures with unordered access left without
  343. /// one, and the copies recorded into depth textures and into twins since
  344. /// the last frame-rate line.
  345. #[cfg(windows)]
  346. pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 4] =
  347. [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  348. /// Depth planes drawn from their twins by the pass since the last
  349. /// frame-rate line; and since the start, how often a depth plane's twin
  350. /// lacked what was written to the plane (not given to it), and how often a
  351. /// depth plane was used in the list that had written its twin, before the
  352. /// pass (which runs when the list closes).
  353. #[cfg(windows)]
  354. pub(crate) static PLANES: [std::sync::atomic::AtomicU64; 3] =
  355. [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  356. /// The colour twin of title texture `this`, if it has one.
  357. #[cfg(windows)]
  358. pub(crate) fn twin(this: This) -> Option<std::sync::Arc<Twin>> {
  359. if this.is_null() {
  360. return None;
  361. }
  362. hosted(this, true).and_then(|made| made.1)
  363. }
  364. /// The twin's texture, for the unordered access views of `this`.
  365. #[cfg(windows)]
  366. pub(crate) fn twin_resource<'a>(
  367. this: This,
  368. ) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
  369. if this.is_null() {
  370. return None;
  371. }
  372. let (_, twin) = hosted(this, true)?;
  373. // SAFETY: as in `host_resource`: the twin lives as long as the host
  374. // copy, which a depth texture keeps until the title releases it.
  375. twin.map(|t| unsafe { &*std::ptr::from_ref(&t.colour.texture) })
  376. }
  377. /// The texture of the twin of the depth plane of `this`, a depth texture
  378. /// with a stencil plane, for the unordered access views of that plane.
  379. #[cfg(windows)]
  380. pub(crate) fn twin_plane_resource<'a>(
  381. this: This,
  382. ) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
  383. if this.is_null() {
  384. return None;
  385. }
  386. let (_, twin) = hosted(this, true)?;
  387. let twin = twin?;
  388. // SAFETY: as in `twin_resource`.
  389. twin.plane
  390. .as_ref()
  391. .map(|p| unsafe { &*std::ptr::from_ref(&p.texture) })
  392. }
  393. /// The colour twin for a texture described by `desc` whose host copy is
  394. /// `depth`, if the title asks for depth and unordered access both and the
  395. /// host can copy between the two: the same size, mips and slices in the
  396. /// depth format's typeless family (R16 for 16-bit depth, R32 for 32-bit),
  397. /// or R8 for the stencil plane of a format that has one, with unordered
  398. /// access only. A format with a stencil plane gets a twin for its depth
  399. /// plane too, R16 for the console's 16-bit depth-stencil formats and R32
  400. /// otherwise. `VICTORY_DEPTH_TWINS=0` makes none (such views stay null),
  401. /// `VICTORY_DEPTH_TWINS=stencil` only those of formats with a stencil
  402. /// plane, `VICTORY_DEPTH_TWINS=nodepth` none for the depth planes of such
  403. /// formats.
  404. #[cfg(windows)]
  405. fn twin_texture(
  406. desc: &ResourceDesc,
  407. depth: &windows::Win32::Graphics::Direct3D12::ID3D12Resource,
  408. ) -> Option<std::sync::Arc<Twin>> {
  409. use std::sync::atomic::Ordering::Relaxed;
  410. use windows::Win32::Graphics::Direct3D12::*;
  411. const DEPTH_AND_UNORDERED: u32 = 6;
  412. const UNORDERED: u32 = 4;
  413. const UNORDERED_ACCESS: u32 = 0x8;
  414. // R32 and R16 typeless: the families of the depth formats of one plane.
  415. const ONE_PLANE: [u32; 2] = [39, 53];
  416. if desc.dimension == BUFFER || desc.flags & DEPTH_AND_UNORDERED != DEPTH_AND_UNORDERED {
  417. return None;
  418. }
  419. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  420. if !*ON.get_or_init(|| std::env::var_os("VICTORY_DEPTH_TWINS").is_none_or(|v| v != "0")) {
  421. return None;
  422. }
  423. // R32G8X24 and R24G8 typeless: depth with a stencil plane, whose twin
  424. // is R8 typeless.
  425. const WITH_STENCIL: [u32; 2] = [19, 44];
  426. const R8_TYPELESS: u32 = 60;
  427. let typeless = family(pc_format(desc.format));
  428. let stencil = WITH_STENCIL.contains(&typeless);
  429. static STENCIL_ONLY: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  430. let stencil_only = *STENCIL_ONLY
  431. .get_or_init(|| std::env::var_os("VICTORY_DEPTH_TWINS").is_some_and(|v| v == "stencil"));
  432. if !stencil && stencil_only {
  433. return None;
  434. }
  435. if !(stencil || ONE_PLANE.contains(&typeless)) || desc.sample_count > 1 {
  436. TWINS[1].fetch_add(1, Relaxed);
  437. return None;
  438. }
  439. let host = crate::host::host()?;
  440. let mut d = *desc;
  441. d.layout = 0;
  442. d.alignment = 0;
  443. d.flags = UNORDERED;
  444. d.format = if stencil { R8_TYPELESS } else { typeless };
  445. let heap = D3D12_HEAP_PROPERTIES {
  446. Type: D3D12_HEAP_TYPE_DEFAULT,
  447. ..Default::default()
  448. };
  449. let mut texture: Option<ID3D12Resource> = None;
  450. // SAFETY: the description has the host layout, as in `host_texture`;
  451. // the out pointer is ours.
  452. let made = unsafe {
  453. host.device.CreateCommittedResource(
  454. &heap,
  455. D3D12_HEAP_FLAG_NONE,
  456. (&raw const d).cast(),
  457. D3D12_RESOURCE_STATES(UNORDERED_ACCESS as i32),
  458. None,
  459. &mut texture,
  460. )
  461. };
  462. if let Err(e) = made {
  463. tracing::warn!(error = %e, desc = ?d, "no colour twin for a depth texture");
  464. }
  465. let Some(texture) = texture else {
  466. TWINS[1].fetch_add(1, Relaxed);
  467. return None;
  468. };
  469. crate::host::name(&texture, || {
  470. format!("depth twin {}x{} f{}", d.width, d.height, d.format)
  471. });
  472. // The buffer a stencil plane and its twin are copied through: as big
  473. // as the plane's mips and slices laid out for a copy (they follow the
  474. // depth plane's in the texture's subresources).
  475. let through = if stencil {
  476. // SAFETY: a live texture.
  477. let of = unsafe { depth.GetDesc() };
  478. let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize);
  479. let mut bytes = 0;
  480. // SAFETY: a plain query; the out pointer is ours.
  481. unsafe {
  482. host.device.GetCopyableFootprints(
  483. &of,
  484. planes,
  485. planes,
  486. 0,
  487. None,
  488. None,
  489. None,
  490. Some(&mut bytes),
  491. );
  492. }
  493. let Some(buffer) = host.uav_buffer(bytes) else {
  494. TWINS[1].fetch_add(1, Relaxed);
  495. return None;
  496. };
  497. Some(buffer)
  498. } else {
  499. None
  500. };
  501. // The twin of the depth plane of a format with a stencil plane: R16
  502. // typeless (53) for the console's 16-bit depth-stencil formats (118 to
  503. // 120), whose shaders write 16-bit steps, R32 typeless (39) otherwise.
  504. static NO_PLANE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  505. let no_plane = *NO_PLANE
  506. .get_or_init(|| std::env::var_os("VICTORY_DEPTH_TWINS").is_some_and(|v| v == "nodepth"));
  507. let plane = if stencil && !no_plane {
  508. d.format = if (118..=120).contains(&desc.format) {
  509. 53
  510. } else {
  511. 39
  512. };
  513. let mut texture: Option<ID3D12Resource> = None;
  514. // SAFETY: as for the first twin.
  515. let made = unsafe {
  516. host.device.CreateCommittedResource(
  517. &heap,
  518. D3D12_HEAP_FLAG_NONE,
  519. (&raw const d).cast(),
  520. D3D12_RESOURCE_STATES(UNORDERED_ACCESS as i32),
  521. None,
  522. &mut texture,
  523. )
  524. };
  525. if let Err(e) = made {
  526. tracing::warn!(error = %e, desc = ?d, "no twin for a depth plane");
  527. }
  528. texture.map(|texture| {
  529. crate::host::name(&texture, || {
  530. format!("depth plane twin {}x{} f{}", d.width, d.height, d.format)
  531. });
  532. std::sync::Arc::new(HostTexture::new(texture, UNORDERED_ACCESS))
  533. })
  534. } else {
  535. None
  536. };
  537. TWINS[0].fetch_add(1, Relaxed);
  538. Some(std::sync::Arc::new(Twin {
  539. colour: std::sync::Arc::new(HostTexture::new(texture, UNORDERED_ACCESS)),
  540. behind: std::sync::atomic::AtomicU32::new(0),
  541. through,
  542. plane,
  543. }))
  544. }
  545. /// The typeless format of a format's family (itself if it has none).
  546. pub(crate) fn family(format: u32) -> u32 {
  547. const FAMILIES: [(u32, u32); 22] = [
  548. (1, 4),
  549. (5, 8),
  550. (9, 14),
  551. (15, 18),
  552. (19, 22),
  553. (23, 25),
  554. (27, 32),
  555. (33, 38),
  556. (39, 43),
  557. (44, 47),
  558. (48, 52),
  559. (53, 59),
  560. (60, 65),
  561. (70, 72),
  562. (73, 75),
  563. (76, 78),
  564. (79, 81),
  565. (82, 84),
  566. (90, 91),
  567. (92, 93),
  568. (94, 96),
  569. (97, 99),
  570. ];
  571. match format {
  572. 87 => 90,
  573. 88 => 92,
  574. f => FAMILIES
  575. .iter()
  576. .find(|&&(first, last)| (first..=last).contains(&f))
  577. .map_or(f, |&(first, _)| first),
  578. }
  579. }
  580. /// sRGB formats and their linear twins.
  581. pub(crate) const SRGB: [(u32, u32); 3] = [(29, 28), (91, 87), (93, 88)];
  582. /// The format a view of a title texture must name when its host copy is
  583. /// typeless (see [`DEPTH_FORMATS`], [`SRGB`]): the title's own; `None` if
  584. /// the host copy is typed.
  585. pub(crate) fn view_format(this: This) -> Option<u32> {
  586. // First: a view of no resource (a typed null view) has none.
  587. let host = host_resource(this)?;
  588. let own = pc_format(resource(this).desc.format);
  589. // SAFETY: a live resource.
  590. let format = unsafe { host.GetDesc() }.Format.0 as u32;
  591. // A stand-in target is typed.
  592. (format != own && format != target_format(own)).then_some(own)
  593. }
  594. /// Depth formats with their typeless family: depth textures that shaders
  595. /// read are made typeless on the host, which only allows views of
  596. /// typeless depth resources.
  597. pub(crate) const DEPTH_FORMATS: [(u32, u32); 4] = [(20, 19), (40, 39), (45, 44), (55, 53)];
  598. /// Mip levels, the full chain for 0.
  599. fn mip_count(desc: &ResourceDesc) -> u32 {
  600. let depth = if desc.dimension == TEXTURE_3D {
  601. u64::from(desc.depth_or_array_size)
  602. } else {
  603. 1
  604. };
  605. match desc.mip_levels {
  606. 0 => {
  607. 64 - desc
  608. .width
  609. .max(u64::from(desc.height))
  610. .max(depth)
  611. .max(1)
  612. .leading_zeros()
  613. }
  614. n => u32::from(n),
  615. }
  616. }
  617. #[repr(C)]
  618. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  619. pub(crate) struct PlacedFootprint {
  620. pub(crate) offset: u64,
  621. format: u32,
  622. width: u32,
  623. height: u32,
  624. depth: u32,
  625. row_pitch: u32,
  626. }
  627. impl PlacedFootprint {
  628. /// The bytes it spans in a buffer: every row pitched but the last.
  629. pub(crate) fn bytes(&self) -> Option<u64> {
  630. let (element, block) = element(self.format)?;
  631. let lines = u64::from(self.height).div_ceil(block) * u64::from(self.depth);
  632. let last = u64::from(self.width).div_ceil(block) * element;
  633. Some(u64::from(self.row_pitch) * lines.saturating_sub(1) + last)
  634. }
  635. /// For a read back through a host buffer: this footprint at offset 0
  636. /// with its rows pitched as the host wants them (multiples of 256
  637. /// bytes), then the bytes that buffer needs, the bytes of a row, the
  638. /// rows, and the title's own pitch.
  639. pub(crate) fn host_rows(&self) -> Option<(PlacedFootprint, [u64; 4])> {
  640. let (element, block) = element(self.format)?;
  641. let lines = (u64::from(self.height).div_ceil(block) * u64::from(self.depth)).max(1);
  642. let row = u64::from(self.width).div_ceil(block) * element;
  643. let pitch = row.max(1).next_multiple_of(256);
  644. let host = PlacedFootprint {
  645. offset: 0,
  646. row_pitch: u32::try_from(pitch).ok()?,
  647. ..*self
  648. };
  649. Some((host, [pitch * lines, row, lines, u64::from(self.row_pitch)]))
  650. }
  651. }
  652. const _: () = assert!(size_of::<PlacedFootprint>() == 32);
  653. const NO_FOOTPRINT: PlacedFootprint = PlacedFootprint {
  654. offset: u64::MAX,
  655. format: 0,
  656. width: 0,
  657. height: 0,
  658. depth: 0,
  659. row_pitch: 0,
  660. };
  661. /// One subresource's size in an upload buffer: footprint (offset 0), rows
  662. /// and bytes per row. Planes of depth-stencil formats are not told apart.
  663. fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32, u64)> {
  664. const PITCH: u64 = 256;
  665. if desc.dimension == BUFFER {
  666. let footprint = PlacedFootprint {
  667. offset: 0,
  668. format: 0,
  669. width: u32::try_from(desc.width).ok()?,
  670. height: 1,
  671. depth: 1,
  672. row_pitch: u32::try_from(desc.width.next_multiple_of(PITCH)).ok()?,
  673. };
  674. return (index == 0).then_some((footprint, 1, desc.width));
  675. }
  676. let mips = mip_count(desc);
  677. let slices = if desc.dimension == TEXTURE_3D {
  678. 1
  679. } else {
  680. u32::from(desc.depth_or_array_size).max(1)
  681. };
  682. let (mip, slice) = (index % mips, index / mips);
  683. if slice >= slices {
  684. return None;
  685. }
  686. let (element, block) = element(desc.format)?;
  687. let width = (desc.width >> mip).max(1).next_multiple_of(block);
  688. let height = (u64::from(desc.height) >> mip)
  689. .max(1)
  690. .next_multiple_of(block);
  691. let depth = if desc.dimension == TEXTURE_3D {
  692. (u32::from(desc.depth_or_array_size) >> mip).max(1)
  693. } else {
  694. 1
  695. };
  696. let row_size = width / block * element;
  697. let footprint = PlacedFootprint {
  698. offset: 0,
  699. format: desc.format,
  700. width: u32::try_from(width).ok()?,
  701. height: u32::try_from(height).ok()?,
  702. depth,
  703. row_pitch: u32::try_from(row_size.next_multiple_of(PITCH)).ok()?,
  704. };
  705. Some((footprint, u32::try_from(height / block).ok()?, row_size))
  706. }
  707. /// Device method: where each subresource goes in an upload buffer, rows
  708. /// 256-byte and subresources 512-byte aligned, as on PC. Unknown sizes give
  709. /// the documented all-ones values.
  710. pub(crate) extern "system" fn copyable_footprints(
  711. _: This,
  712. desc: *const ResourceDesc,
  713. first: u32,
  714. count: u32,
  715. base: u64,
  716. layouts: *mut PlacedFootprint,
  717. rows: *mut u32,
  718. row_sizes: *mut u64,
  719. total: *mut u64,
  720. ) {
  721. const PLACEMENT: u64 = 512;
  722. // SAFETY: the title passes a description (null is tolerated).
  723. let desc = unsafe { desc.as_ref() };
  724. let mut end = base;
  725. let mut known = desc.is_some();
  726. for i in 0..count {
  727. let one = desc.and_then(|d| subresource(d, first + i));
  728. let (layout, row_count, row_size) = match one {
  729. Some((mut footprint, row_count, row_size)) => {
  730. footprint.offset = end.next_multiple_of(PLACEMENT);
  731. let pitch = u64::from(footprint.row_pitch);
  732. let lines = u64::from(row_count) * u64::from(footprint.depth);
  733. end = footprint.offset + pitch * lines.saturating_sub(1) + row_size;
  734. (footprint, row_count, row_size)
  735. }
  736. None => {
  737. known = false;
  738. (NO_FOOTPRINT, u32::MAX, u64::MAX)
  739. }
  740. };
  741. let i = i as usize;
  742. // SAFETY: each output is null or holds `count` entries.
  743. unsafe {
  744. if !layouts.is_null() {
  745. layouts.add(i).write(layout);
  746. }
  747. if !rows.is_null() {
  748. rows.add(i).write(row_count);
  749. }
  750. if !row_sizes.is_null() {
  751. row_sizes.add(i).write(row_size);
  752. }
  753. }
  754. }
  755. if !known {
  756. tracing::warn!(?desc, "no footprint for this resource");
  757. }
  758. if !total.is_null() {
  759. // SAFETY: checked non-null.
  760. unsafe { total.write(if known { end - base } else { u64::MAX }) };
  761. }
  762. }
  763. /// Device method: the footprint of resources placed one after another.
  764. /// Returns a 16-byte value, through a hidden first argument. Invalid input
  765. /// gives the documented size `u64::MAX`.
  766. pub(crate) extern "system" fn allocation_info(
  767. out: *mut AllocationInfo,
  768. _: This,
  769. _visible: u32,
  770. count: u32,
  771. descs: *const ResourceDesc,
  772. ) -> *mut AllocationInfo {
  773. let descs = if descs.is_null() {
  774. &[][..]
  775. } else {
  776. // SAFETY: the title passes `count` descriptions.
  777. unsafe { std::slice::from_raw_parts(descs, count as usize) }
  778. };
  779. // SAFETY: the caller passes room for the value.
  780. unsafe { out.write(place(descs.iter(), |_, _| ())) };
  781. out
  782. }
  783. /// The newer description: the plain one, then a sampler feedback mip
  784. /// region (width, height, depth).
  785. #[repr(C)]
  786. pub(crate) struct ResourceDesc1 {
  787. desc: ResourceDesc,
  788. mip_region: [u32; 3],
  789. }
  790. const _: () = assert!(size_of::<ResourceDesc1>() == 72);
  791. /// Where one resource goes in [`allocation_info2`]'s placement.
  792. #[repr(C)]
  793. pub(crate) struct AllocationInfo1 {
  794. offset: u64,
  795. alignment: u64,
  796. size: u64,
  797. }
  798. /// Device method 0x360 (`ID3D12Device8`): [`allocation_info`] for newer
  799. /// descriptions, also telling where each resource goes.
  800. pub(crate) extern "system" fn allocation_info2(
  801. out: *mut AllocationInfo,
  802. _: This,
  803. _visible: u32,
  804. count: u32,
  805. descs: *const ResourceDesc1,
  806. each: *mut AllocationInfo1,
  807. ) -> *mut AllocationInfo {
  808. let descs = if descs.is_null() {
  809. &[][..]
  810. } else {
  811. // SAFETY: the title passes `count` descriptions.
  812. unsafe { std::slice::from_raw_parts(descs, count as usize) }
  813. };
  814. let total = place(descs.iter().map(|d| &d.desc), |i, info| {
  815. if !each.is_null() {
  816. // SAFETY: the title passes room for `count` entries.
  817. unsafe { each.add(i).write(info) };
  818. }
  819. });
  820. // SAFETY: the caller passes room for the value.
  821. unsafe { out.write(total) };
  822. out
  823. }
  824. /// Resources placed one after another: the whole footprint, telling `each`
  825. /// where every resource goes. Unknown sizes give the documented `u64::MAX`.
  826. fn place<'a>(
  827. descs: impl Iterator<Item = &'a ResourceDesc>,
  828. mut each: impl FnMut(usize, AllocationInfo1),
  829. ) -> AllocationInfo {
  830. let mut total = AllocationInfo {
  831. size: 0,
  832. alignment: KIB_64,
  833. };
  834. for (i, desc) in descs.enumerate() {
  835. let Some(one) = footprint(desc) else {
  836. tracing::warn!(?desc, "no size for this resource");
  837. each(
  838. i,
  839. AllocationInfo1 {
  840. offset: u64::MAX,
  841. alignment: 0,
  842. size: u64::MAX,
  843. },
  844. );
  845. return AllocationInfo {
  846. size: u64::MAX,
  847. alignment: 0,
  848. };
  849. };
  850. tracing::debug!(?desc, ?one, "allocation info");
  851. let offset = total.size.next_multiple_of(one.alignment);
  852. each(
  853. i,
  854. AllocationInfo1 {
  855. offset,
  856. alignment: one.alignment,
  857. size: one.size,
  858. },
  859. );
  860. total.size = offset + one.size;
  861. total.alignment = total.alignment.max(one.alignment);
  862. }
  863. total
  864. }
  865. /// Zeroed host memory standing in for GPU memory.
  866. pub(crate) struct Memory {
  867. ptr: NonNull<u8>,
  868. layout: Layout,
  869. /// Set when the memory came from the title's allocator, with these
  870. /// allocation attributes (it goes back there).
  871. attributes: Option<u64>,
  872. }
  873. pub type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void;
  874. pub type FreeRoutine = extern "system" fn(*mut c_void, u64);
  875. static ALLOCATOR: std::sync::OnceLock<(AllocRoutine, FreeRoutine)> = std::sync::OnceLock::new();
  876. /// Committed resources get their memory from the title's general
  877. /// allocator, as on the console, where titles hook it to place graphics
  878. /// memory themselves (the title places its back buffers in a
  879. /// block of its own and checks they fill it). The runtime names it before
  880. /// the device exists.
  881. pub fn use_allocator(alloc: AllocRoutine, free: FreeRoutine) {
  882. let _ = ALLOCATOR.set((alloc, free));
  883. }
  884. /// Maps the physical pages behind one range of title memory at another,
  885. /// `(to, from, len)` (`from` 0 unmaps); false on failure.
  886. pub type PageMapper = fn(u64, u64, u64) -> bool;
  887. static PAGE_MAPPER: std::sync::OnceLock<PageMapper> = std::sync::OnceLock::new();
  888. /// The runtime's page mapper, for the queues' page-mapping copies (memory
  889. /// is the runtime's, as on the console).
  890. pub fn use_page_mapper(mapper: PageMapper) {
  891. let _ = PAGE_MAPPER.set(mapper);
  892. }
  893. pub(crate) fn page_mapper() -> Option<PageMapper> {
  894. PAGE_MAPPER.get().copied()
  895. }
  896. /// Allocation attributes for resource memory: allocator id, page size
  897. /// (bits 14-15: 2 MiB pages from 2 MiB up, else 64 KiB), alignment as log2
  898. /// (bits 24-28) and memory type (bits 29-32: write-combined for GPU-only
  899. /// heaps, cacheable for the CPU-visible ones).
  900. /// shortcut: the console runtime's own choice of page size and memory type
  901. /// is not known; this is the plausible one.
  902. fn resource_attributes(info: AllocationInfo, heap_kind: u32) -> u64 {
  903. const GRAPHICS_ALLOCATOR: u64 = 128 << 16;
  904. const DEFAULT_HEAP: u32 = 1;
  905. let pages: u64 = if info.size >= 2 << 20 { 2 } else { 1 };
  906. let memory: u64 = if heap_kind == DEFAULT_HEAP { 1 } else { 3 };
  907. let alignment = u64::from(info.alignment.max(1).trailing_zeros());
  908. GRAPHICS_ALLOCATOR | pages << 14 | alignment << 24 | memory << 29
  909. }
  910. impl Memory {
  911. /// A committed resource's memory: from the title's allocator if the
  912. /// runtime named one, else our own; zeroed either way.
  913. fn for_resource(info: AllocationInfo, heap_kind: u32) -> Result<Memory, HRESULT> {
  914. let Some(&(alloc, _)) = ALLOCATOR.get() else {
  915. return Memory::new(info);
  916. };
  917. let layout = Layout::from_size_align(info.size as usize, info.alignment as usize)
  918. .map_err(|_| E_INVALIDARG)?;
  919. let attributes = resource_attributes(info, heap_kind);
  920. let ptr =
  921. NonNull::new(alloc(layout.size(), attributes).cast::<u8>()).ok_or(E_OUTOFMEMORY)?;
  922. // SAFETY: the allocator handed out `size` bytes.
  923. unsafe { ptr.as_ptr().write_bytes(0, layout.size()) };
  924. Ok(Memory {
  925. ptr,
  926. layout,
  927. attributes: Some(attributes),
  928. })
  929. }
  930. /// `size` zeroed bytes aligned to `alignment` (a power of two).
  931. pub(crate) fn zeroed(size: u64, alignment: u64) -> Result<Memory, HRESULT> {
  932. Memory::new(AllocationInfo { size, alignment })
  933. }
  934. pub(crate) fn address(&self) -> u64 {
  935. self.ptr.as_ptr() as u64
  936. }
  937. fn new(info: AllocationInfo) -> Result<Memory, HRESULT> {
  938. let layout = usize::try_from(info.size)
  939. .ok()
  940. .zip(usize::try_from(info.alignment).ok())
  941. .filter(|&(size, _)| size > 0)
  942. .and_then(|(size, align)| Layout::from_size_align(size, align).ok())
  943. .ok_or(E_INVALIDARG)?;
  944. // SAFETY: the size is non-zero.
  945. let ptr = NonNull::new(unsafe { alloc_zeroed(layout) }).ok_or(E_OUTOFMEMORY)?;
  946. // The big ones are named in the log: the memory line counts our own
  947. // allocations by size, and these are the title's memory given out
  948. // of ours (a heap it made through the device, a descriptor heap).
  949. if info.size >= 32 << 20 {
  950. tracing::info!(mb = info.size >> 20, at = ?ptr, "memory for the title from our allocator (a heap or a descriptor heap)");
  951. }
  952. Ok(Memory {
  953. ptr,
  954. layout,
  955. attributes: None,
  956. })
  957. }
  958. }
  959. impl Drop for Memory {
  960. fn drop(&mut self) {
  961. match (self.attributes, ALLOCATOR.get()) {
  962. (Some(attributes), Some(&(_, free))) => free(self.ptr.as_ptr().cast(), attributes),
  963. // SAFETY: allocated in `new` with this layout.
  964. _ => unsafe { dealloc(self.ptr.as_ptr(), self.layout) },
  965. }
  966. }
  967. }
  968. #[repr(C)]
  969. struct Heap {
  970. object: Object,
  971. desc: HeapDesc,
  972. memory: Memory,
  973. }
  974. pub(crate) extern "system" fn create_heap(
  975. _: This,
  976. desc: *const HeapDesc,
  977. iid: *const Iid,
  978. out: *mut This,
  979. ) -> HRESULT {
  980. // SAFETY: the title passes a description (null is tolerated).
  981. let Some(&desc) = (unsafe { desc.as_ref() }) else {
  982. return E_INVALIDARG;
  983. };
  984. tracing::debug!(
  985. size = desc.size,
  986. kind = desc.properties.kind,
  987. flags = format_args!("{:#x}", desc.flags),
  988. "heap"
  989. );
  990. if desc.alignment != 0 && !desc.alignment.is_power_of_two() {
  991. return E_INVALIDARG;
  992. }
  993. let info = AllocationInfo {
  994. size: desc.size,
  995. alignment: desc.alignment.max(KIB_64),
  996. };
  997. let memory = match Memory::new(info) {
  998. Ok(memory) => memory,
  999. Err(hr) => return hr,
  1000. };
  1001. let heap = Box::new(Heap {
  1002. object: Object::new(&HEAP_FUNCTIONS),
  1003. desc,
  1004. memory,
  1005. });
  1006. object::hand_out(HEAP, heap, iid, &HEAP_IIDS, out)
  1007. }
  1008. extern "system" fn heap_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  1009. object::answer(HEAP, iid, object::is(iid, &HEAP_IIDS).then_some(this), out)
  1010. }
  1011. extern "system" fn heap_release(this: This) -> u32 {
  1012. object::release_boxed::<Heap>(this)
  1013. }
  1014. extern "system" fn heap_desc(this: This, out: *mut HeapDesc) {
  1015. if !out.is_null() {
  1016. // SAFETY: `this` is a heap; the title passes room for a description.
  1017. unsafe { out.write((*this.cast::<Heap>()).desc) };
  1018. }
  1019. }
  1020. /// A resource's memory: its own, or a range of a heap it holds a reference
  1021. /// to.
  1022. enum Backing {
  1023. Committed(Memory),
  1024. Placed {
  1025. heap: This,
  1026. offset: u64,
  1027. },
  1028. /// Memory the title mapped itself, at this address.
  1029. Address(*mut u8),
  1030. }
  1031. impl Drop for Backing {
  1032. fn drop(&mut self) {
  1033. if let Backing::Placed { heap, .. } = *self {
  1034. heap_release(heap);
  1035. }
  1036. }
  1037. }
  1038. #[repr(C)]
  1039. struct Resource {
  1040. object: Object,
  1041. desc: ResourceDesc,
  1042. heap: HeapProperties,
  1043. heap_flags: u32,
  1044. backing: Backing,
  1045. /// Textures also live on the host GPU (decision 0007); buffers do not
  1046. /// yet. With, for a depth texture the title also writes as unordered
  1047. /// access, the colour texture shaders write instead ([`Twin`]).
  1048. #[cfg(windows)]
  1049. host: Hosted,
  1050. }
  1051. /// A title texture's host copy and the state it is in. The title's barriers
  1052. /// name console states (looser than the host's), so we transition from this
  1053. /// one. Lists that use the texture hold it until they are reset: the title
  1054. /// may release a resource whose commands it recorded but not yet submitted
  1055. /// (console memory outlives the object; a host texture must outlive the
  1056. /// lists that name it).
  1057. #[cfg(windows)]
  1058. pub(crate) struct HostTexture {
  1059. pub(crate) texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource,
  1060. pub(crate) state: std::sync::atomic::AtomicU32,
  1061. /// The bytes the host gives it.
  1062. bytes: u64,
  1063. /// Whether its contents come from title memory ([`fills`]): counted in
  1064. /// [`KINDS`] while it lives.
  1065. filled: bool,
  1066. }
  1067. /// What a title texture has on the host: its host copy and, for a depth
  1068. /// texture shaders also write, the colour twin.
  1069. #[cfg(windows)]
  1070. type Made = (std::sync::Arc<HostTexture>, Option<std::sync::Arc<Twin>>);
  1071. /// A title texture's host side. The host copy is made when something first
  1072. /// uses the texture, not when the title creates it: the title
  1073. /// had created 3,871 textures (9.2 GB on the host) before its world's first
  1074. /// frame, of which a frame's lists name some hundreds (run 23), on a card
  1075. /// with 12 GB. A title texture is memory the title has either way; its host
  1076. /// copy is the card's.
  1077. #[cfg(windows)]
  1078. struct Hosted {
  1079. /// The host copy (and twin) once made. Taken out again only by
  1080. /// [`let_go_idle`] and when the title releases the resource.
  1081. made: std::sync::Mutex<Option<Made>>,
  1082. /// The state and clear value the title created the texture with.
  1083. state: u32,
  1084. clear: Option<[u32; 5]>,
  1085. /// When the host copy was last asked for (`crate::host::moment`),
  1086. /// written under `made`'s lock.
  1087. used: std::sync::atomic::AtomicU64,
  1088. /// The host refused to make it: not tried again.
  1089. refused: std::sync::atomic::AtomicBool,
  1090. /// Its host copy was let go as idle once.
  1091. gone: std::sync::atomic::AtomicBool,
  1092. /// A texture of [`PLACED_TEXTURES`].
  1093. placed: std::sync::atomic::AtomicBool,
  1094. }
  1095. /// Counts for the memory line: host copies of textures the title fills
  1096. /// alive and their bytes; such copies let go as idle since the start and
  1097. /// their bytes; made again after that and their bytes; and host copies made
  1098. /// since the start.
  1099. #[cfg(windows)]
  1100. pub(crate) static KINDS: [std::sync::atomic::AtomicU64; 7] =
  1101. [const { std::sync::atomic::AtomicU64::new(0) }; 7];
  1102. /// Every title texture alive (not buffers), by address: for the sweep and
  1103. /// the memory line. A texture leaves the table before it is freed.
  1104. #[cfg(windows)]
  1105. static TEXTURES: std::sync::Mutex<std::collections::BTreeSet<usize>> =
  1106. std::sync::Mutex::new(std::collections::BTreeSet::new());
  1107. #[cfg(windows)]
  1108. fn textures() -> std::sync::MutexGuard<'static, std::collections::BTreeSet<usize>> {
  1109. TEXTURES.lock().unwrap_or_else(|e| e.into_inner())
  1110. }
  1111. /// The title textures the host renders to or writes (targets, depth,
  1112. /// unordered access), by the address of their memory: what a view the
  1113. /// title places in that memory in another format shows ([`alias_of`]). A
  1114. /// texture leaves the table before it is freed.
  1115. #[cfg(windows)]
  1116. static TARGETS_AT: std::sync::Mutex<std::collections::BTreeMap<u64, usize>> =
  1117. std::sync::Mutex::new(std::collections::BTreeMap::new());
  1118. /// For `this`, a texture made for a view the title placed in memory
  1119. /// ([`texture_at`]): the title texture the host writes that lies in the
  1120. /// same memory, if there is one of the same size, levels and layers with
  1121. /// texels of the same width. The console reads such a texture through the
  1122. /// view as it is
  1123. /// (the title packs light as R9G9B9E5 into R32_UINT textures
  1124. /// with compute shaders, which cannot write R9G9B9E5, and samples them
  1125. /// through R9G9B9E5 views placed at the textures' addresses: the sky, the
  1126. /// sky and light probes, the bounced light the lighting pass adds). On the
  1127. /// host the two are two textures and what the shaders wrote exists in one
  1128. /// of them only: the other was filled from title memory, which nothing
  1129. /// writes, so everything read through such a view was black.
  1130. /// Textures of several levels or layers count too (the screen probes'
  1131. /// light atlas has four levels, the camera's sky light cache six layers,
  1132. /// the cloud and sky tables are volumes): only textures of one level and
  1133. /// one layer were found at first, and the programs behind the others read
  1134. /// the title's unwritten memory - the sky light cache's second stage wrote
  1135. /// all zeros from a first stage that held light (run 88).
  1136. /// `VICTORY_ALIAS_COPY=0`: none is found, as before; `=1`: only textures
  1137. /// of one level and one layer, as at first.
  1138. #[cfg(windows)]
  1139. pub(crate) fn alias_of(this: This) -> Option<This> {
  1140. use std::sync::atomic::Ordering::Relaxed;
  1141. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1142. if this.is_null()
  1143. || !*ON.get_or_init(|| std::env::var_os("VICTORY_ALIAS_COPY").is_none_or(|v| v != "0"))
  1144. {
  1145. return None;
  1146. }
  1147. static WHOLE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1148. let whole =
  1149. *WHOLE.get_or_init(|| std::env::var_os("VICTORY_ALIAS_COPY").is_none_or(|v| v != "1"));
  1150. let r = resource(this);
  1151. // A level count of 0 asks for a full chain: not counted here.
  1152. let one = |d: &ResourceDesc| {
  1153. d.dimension != BUFFER
  1154. && d.mip_levels >= 1
  1155. && d.depth_or_array_size >= 1
  1156. && (whole || (d.mip_levels == 1 && d.depth_or_array_size == 1))
  1157. && d.sample_count <= 1
  1158. };
  1159. if !r.host.placed.load(Relaxed) || !fills(&r.desc) || !one(&r.desc) {
  1160. return None;
  1161. }
  1162. // Under the table's lock: a texture leaves it before it is freed.
  1163. let targets = TARGETS_AT.lock().unwrap_or_else(|e| e.into_inner());
  1164. let other = *targets.get(&(r.data() as u64))? as This;
  1165. let o = resource(other);
  1166. const DEPTH: u32 = 0x2;
  1167. let same = one(&o.desc)
  1168. && o.desc.dimension == r.desc.dimension
  1169. && o.desc.width == r.desc.width
  1170. && o.desc.height == r.desc.height
  1171. && o.desc.mip_levels == r.desc.mip_levels
  1172. && o.desc.depth_or_array_size == r.desc.depth_or_array_size
  1173. && o.desc.flags & DEPTH == 0
  1174. && target_format(o.desc.format) == o.desc.format
  1175. && element(o.desc.format).is_some_and(|e| e.1 == 1 && Some(e) == element(r.desc.format));
  1176. same.then_some(other)
  1177. }
  1178. /// Whether host copies are made on first use. On by default;
  1179. /// `VICTORY_LAZY_TEXTURES=0` makes each when the title creates its texture,
  1180. /// as before.
  1181. #[cfg(windows)]
  1182. fn lazy() -> bool {
  1183. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1184. *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_TEXTURES").is_none_or(|v| v != "0"))
  1185. }
  1186. /// Whether a texture described by `desc` takes its contents from title
  1187. /// memory: one the host neither renders to nor writes (no target, depth or
  1188. /// unordered access flag). Its host copy can be made again from that
  1189. /// memory; any other texture's contents exist on the host alone.
  1190. #[cfg(windows)]
  1191. fn fills(desc: &ResourceDesc) -> bool {
  1192. const TARGET_DEPTH_UNORDERED: u32 = 0x7;
  1193. desc.dimension != BUFFER && desc.flags & TARGET_DEPTH_UNORDERED == 0
  1194. }
  1195. /// Whether the title fills texture `this` itself ([`fills`]).
  1196. #[cfg(windows)]
  1197. pub(crate) fn title_fills(this: This) -> bool {
  1198. !this.is_null() && fills(&resource(this).desc)
  1199. }
  1200. /// Whether `this` is a texture whose host copy is not made yet (and may
  1201. /// still be): a descriptor slot written with a view of it waits
  1202. /// (`crate::descriptor::make_waiting`).
  1203. #[cfg(windows)]
  1204. pub(crate) fn host_waits(this: This) -> bool {
  1205. if this.is_null() || !lazy() {
  1206. return false;
  1207. }
  1208. let r = resource(this);
  1209. r.desc.dimension != BUFFER
  1210. && !r.host.refused.load(std::sync::atomic::Ordering::Relaxed)
  1211. && r.host.made.lock().unwrap_or_else(|e| e.into_inner()).is_none()
  1212. }
  1213. /// The host side of title texture `this`: made now if it is not there and
  1214. /// `make` says so. `None` for buffers and for textures the host refuses.
  1215. #[cfg(windows)]
  1216. fn hosted(this: This, make: bool) -> Option<Made> {
  1217. use std::sync::atomic::Ordering::Relaxed;
  1218. let r = resource(this);
  1219. if r.desc.dimension == BUFFER {
  1220. return None;
  1221. }
  1222. let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
  1223. if made.is_none() {
  1224. if !make || r.host.refused.load(Relaxed) {
  1225. return None;
  1226. }
  1227. let clear = r
  1228. .host
  1229. .clear
  1230. .as_ref()
  1231. .map_or(std::ptr::null(), |c| std::ptr::from_ref(c).cast::<c_void>());
  1232. let Some(texture) = host_texture(&r.desc, r.host.state, clear) else {
  1233. r.host.refused.store(true, Relaxed);
  1234. return None;
  1235. };
  1236. let twin = twin_texture(&r.desc, &texture);
  1237. // One line per depth texture with unordered access: its address is
  1238. // the one target dumps and the captured frame's list of commands
  1239. // name.
  1240. if r.desc.flags & 6 == 6 {
  1241. tracing::info!(
  1242. resource = ?this,
  1243. desc = ?r.desc,
  1244. twin = twin.is_some(),
  1245. "depth texture with unordered access"
  1246. );
  1247. }
  1248. let state = crate::host::legal_state(&texture, crate::host::texture_state(r.host.state));
  1249. let mut host = HostTexture::new(texture, state);
  1250. host.filled = fills(&r.desc);
  1251. if host.filled {
  1252. KINDS[0].fetch_add(1, Relaxed);
  1253. KINDS[1].fetch_add(host.bytes, Relaxed);
  1254. }
  1255. if r.host.gone.load(Relaxed) {
  1256. KINDS[4].fetch_add(1, Relaxed);
  1257. KINDS[5].fetch_add(host.bytes, Relaxed);
  1258. }
  1259. KINDS[6].fetch_add(1, Relaxed);
  1260. *made = Some((std::sync::Arc::new(host), twin));
  1261. // Slots the title wrote with views of it while it had no host copy
  1262. // are made before the next submission runs.
  1263. crate::descriptor::texture_made(this as usize);
  1264. }
  1265. r.host.used.store(crate::host::moment(), Relaxed);
  1266. made.clone()
  1267. }
  1268. /// The host copy of title texture `this` if it is made, without making it
  1269. /// (for diagnostics, which must not count as a use).
  1270. #[cfg(all(windows, feature = "diagnostics"))]
  1271. pub(crate) fn host_made<'a>(
  1272. this: This,
  1273. ) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
  1274. if this.is_null() {
  1275. return None;
  1276. }
  1277. let (host, _) = hosted(this, false)?;
  1278. // SAFETY: as in `host_resource`.
  1279. Some(unsafe { &*std::ptr::from_ref(&host.texture) })
  1280. }
  1281. /// Unconditional host-texture floor for a given local VRAM budget (`None` when
  1282. /// the adapter does not report one): up to 2 GiB, capped at a quarter of the
  1283. /// reported budget so 4–6 GiB cards do not bypass the budget check early.
  1284. #[cfg(any(windows, test))]
  1285. fn texture_floor_bytes(vram_budget: Option<u64>) -> u64 {
  1286. const MAX_FLOOR: u64 = 2 << 30;
  1287. match vram_budget {
  1288. Some(budget) => MAX_FLOOR.min(budget / 4),
  1289. None => MAX_FLOOR,
  1290. }
  1291. }
  1292. /// Whether more host copies of textures the title fills may be made for
  1293. /// shaders that pick textures by index (`draw.rs` `heap_textures`): always
  1294. /// up to [`texture_floor_bytes`] bytes of them, beyond that while the card's
  1295. /// memory in use by this process is under nine tenths of the budget the system
  1296. /// gives it ([`room_percent`] says another share; `VICTORY_TEXTURE_BUDGET_MB`
  1297. /// sets a limit on those copies' bytes instead). Past the budget the system moves the card's memory into the PC's,
  1298. /// which ended runs 20 and 24.
  1299. #[cfg(windows)]
  1300. pub(crate) fn room(memory: Option<[u64; 4]>) -> bool {
  1301. use std::sync::atomic::Ordering::Relaxed;
  1302. const WITHOUT_BUDGET: u64 = 4 << 30;
  1303. static LIMIT: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
  1304. let limit = *LIMIT.get_or_init(|| {
  1305. let mb = std::env::var("VICTORY_TEXTURE_BUDGET_MB").ok()?;
  1306. mb.trim().parse::<u64>().ok().map(|mb| mb << 20)
  1307. });
  1308. let filled = KINDS[1].load(Relaxed);
  1309. if let Some(limit) = limit {
  1310. return filled < limit;
  1311. }
  1312. let floor = texture_floor_bytes(memory.map(|[budget, ..]| budget));
  1313. if filled < floor {
  1314. return true;
  1315. }
  1316. match memory {
  1317. Some([budget, used, ..]) => used < budget / 100 * room_percent(),
  1318. None => filled < WITHOUT_BUDGET,
  1319. }
  1320. }
  1321. /// The share of the card's budget, in percent, up to which host copies of
  1322. /// textures picked by index are made ([`room`]): 90 unless
  1323. /// `VICTORY_TEXTURE_ROOM_PERCENT` says another (50 to 97). At 90 about a
  1324. /// tenth of the budget, 1,020 MB of 10,200, stays unused while thousands of
  1325. /// textures wait (runs 170-174); the card copies of title buffers from
  1326. /// 1 MiB up take 449 MB more of the card than before (941 against 492),
  1327. /// and 94 gives the textures about that much back.
  1328. #[cfg(windows)]
  1329. fn room_percent() -> u64 {
  1330. static PERCENT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  1331. *PERCENT.get_or_init(|| {
  1332. std::env::var("VICTORY_TEXTURE_ROOM_PERCENT")
  1333. .ok()
  1334. .and_then(|v| v.trim().parse::<u64>().ok())
  1335. .map_or(90, |percent| percent.clamp(50, 97))
  1336. })
  1337. }
  1338. /// For the card accounting line ([`card_accounting`]): the title texture
  1339. /// made for a view of memory at `address` with the resource description
  1340. /// `desc`, if there is one ([`texture_at`] makes it; this does not).
  1341. #[cfg(windows)]
  1342. pub(crate) fn placed_known(address: u64, desc: &[u32; 14]) -> Option<This> {
  1343. // Without the filler words and with them: whichever `texture_at` keeps.
  1344. let mut key = *desc;
  1345. key[1] = 0;
  1346. key[13] = 0;
  1347. let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner());
  1348. map.get(&(address, key)).or_else(|| map.get(&(address, *desc))).map(|&r| r as This)
  1349. }
  1350. /// For the card accounting line: whether title texture `this` has a host
  1351. /// copy now (2), had one that was let go and not made again (1), or never
  1352. /// had one (0); the bytes (its host copy's on the card, or without one
  1353. /// what its console layout takes in title memory); and where its title
  1354. /// memory is. `None` for buffers. Not a use of the texture.
  1355. #[cfg(windows)]
  1356. pub(crate) fn copy_state(this: This) -> Option<(u8, u64, u64)> {
  1357. use std::sync::atomic::Ordering::Relaxed;
  1358. if this.is_null() {
  1359. return None;
  1360. }
  1361. let r = resource(this);
  1362. if r.desc.dimension == BUFFER {
  1363. return None;
  1364. }
  1365. let memory = r.data() as u64;
  1366. let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
  1367. Some(match made.as_ref() {
  1368. Some((host, _)) => (2, host.bytes, memory),
  1369. None => (u8::from(r.host.gone.load(Relaxed)), footprint(&r.desc).map_or(0, |f| f.size), memory),
  1370. })
  1371. }
  1372. /// One line of where the card's memory is and what the queue of textures
  1373. /// picked by index would need (`VICTORY_CARD_ACCOUNTING=1`; `draw.rs`
  1374. /// `card_accounting` says when, and hands over the queue's side: `room`
  1375. /// as the pass found it, `due` its counts, `never` and `gone` the memory
  1376. /// of the due textures without a host copy). The line holds
  1377. /// - the host copies of textures the title fills that are alive: how
  1378. /// many, their bytes, and the bytes of the levels whose title memory is
  1379. /// not mapped (a host copy is made with every level of the description;
  1380. /// a texture streaming in has its small levels only). A copy's bytes
  1381. /// are shared out to its levels by their texels, so that part is an
  1382. /// estimate;
  1383. /// - the due slots: how many, and their textures by what they have on
  1384. /// the card (a host copy alive: no card memory needed; never one; one
  1385. /// that was let go), with the bytes the last two would need and how
  1386. /// much of their memory is mapped now;
  1387. /// - the host copies let go, made again and made since the line before.
  1388. ///
  1389. /// The textures are noted under the table's lock (their memory, their
  1390. /// description, their copy's bytes: about a millisecond for 18,000) and
  1391. /// the kernel is asked about their memory on a thread of its own, after
  1392. /// the lock is given back: one question for a texture that is all there
  1393. /// (up to 256 pages each; 18,000 textures of 5.5 GB are 1.4 million
  1394. /// pages, some 20,000 questions), one per level and array slice more for
  1395. /// one that is not. Not measured: a tenth to half a second is expected,
  1396. /// and the line says what it took. No line is begun while one is walking.
  1397. #[cfg(windows)]
  1398. pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, gone: Vec<(u64, u64)>) {
  1399. use std::sync::atomic::Ordering::Relaxed;
  1400. static WALKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  1401. // Host copies let go and their bytes, made again and their bytes, and
  1402. // made in all, at the line before.
  1403. static BEFORE: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
  1404. if WALKING.swap(true, Relaxed) {
  1405. return;
  1406. }
  1407. let began = std::time::Instant::now();
  1408. let mut copies: Vec<(usize, ResourceDesc, u64)> = Vec::new();
  1409. // Textures the title fills without a host copy: never one, one let go.
  1410. let mut without = [0u64; 2];
  1411. {
  1412. let all = textures();
  1413. for &at in all.iter() {
  1414. // SAFETY: as in `let_go_idle`.
  1415. let r = unsafe { &*(at as *const Resource) };
  1416. if !fills(&r.desc) {
  1417. continue;
  1418. }
  1419. let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
  1420. match made.as_ref() {
  1421. Some((host, _)) => copies.push((r.data() as usize, r.desc, host.bytes)),
  1422. None => without[usize::from(r.host.gone.load(Relaxed))] += 1,
  1423. }
  1424. }
  1425. }
  1426. let kinds = KINDS.each_ref().map(|k| k.load(Relaxed));
  1427. let mut since = [0u64; 5];
  1428. for ((slot, now), before) in since.iter_mut().zip([kinds[2], kinds[3], kinds[4], kinds[5], kinds[6]]).zip(&BEFORE) {
  1429. *slot = now.saturating_sub(before.swap(now, Relaxed));
  1430. }
  1431. let video = crate::host::host().and_then(|h| h.video_memory());
  1432. let noted_us = began.elapsed().as_micros() as u64;
  1433. let walk = move || {
  1434. fn texels(m: &texture::Mip) -> u64 {
  1435. u64::from(m.width) * u64::from(m.height) * u64::from(m.depth)
  1436. }
  1437. let began = std::time::Instant::now();
  1438. // Copies; their bytes; the bytes of levels not mapped; copies with
  1439. // a level not mapped; with the largest level not mapped; with no
  1440. // level mapped; copies without a console layout (not asked).
  1441. let mut c = [0u64; 7];
  1442. for &(memory, desc, bytes) in &copies {
  1443. c[0] += 1;
  1444. c[1] += bytes;
  1445. let Some(layout) = texture_layout(&desc).map(|t| t.planes[0].layout.clone()) else {
  1446. c[6] += 1;
  1447. continue;
  1448. };
  1449. if layout.size == 0 || crate::texture::committed(memory as *const u8, layout.size as usize) {
  1450. continue;
  1451. }
  1452. c[3] += 1;
  1453. // Every slice holds the whole chain: the levels of the tail in
  1454. // its first block, the others after it from the smallest up
  1455. // (`victory_formats::texture::Layout`).
  1456. let mips = &layout.mips;
  1457. let tail = (layout.first_tail_mip as usize).min(mips.len());
  1458. let there = |from: u64, to: u64| {
  1459. (0..u64::from(layout.slices)).all(|slice| {
  1460. let at = memory as u64 + slice * layout.slice_size + from;
  1461. crate::texture::committed(at as *const u8, (to - from) as usize)
  1462. })
  1463. };
  1464. let all: u64 = mips.iter().map(texels).sum::<u64>().max(1);
  1465. let (mut missing, mut any) = (0u64, false);
  1466. for (level, m) in mips.iter().enumerate().take(tail) {
  1467. let end = if level == 0 { layout.slice_size } else { mips[level - 1].offset };
  1468. if end <= m.offset {
  1469. continue;
  1470. }
  1471. if there(m.offset, end) {
  1472. any = true;
  1473. } else {
  1474. missing += texels(m);
  1475. c[4] += u64::from(level == 0);
  1476. }
  1477. }
  1478. if tail < mips.len() {
  1479. if there(0, layout.alignment.min(layout.slice_size).max(1)) {
  1480. any = true;
  1481. } else {
  1482. missing += mips[tail..].iter().map(texels).sum::<u64>();
  1483. }
  1484. }
  1485. c[2] += (u128::from(bytes) * u128::from(missing) / u128::from(all)) as u64;
  1486. c[5] += u64::from(!any);
  1487. }
  1488. // Of the due textures without a host copy: how many; the bytes of
  1489. // their memory; with all of it mapped, and those bytes; with part
  1490. // of it mapped, and the bytes that are; with none of it mapped.
  1491. let mapped = |list: &[(u64, u64)]| {
  1492. let mut n = [0u64; 7];
  1493. for &(at, len) in list {
  1494. n[0] += 1;
  1495. n[1] += len;
  1496. let there = crate::texture::mapped_bytes(at as *const u8, len as usize);
  1497. if len > 0 && there >= len {
  1498. n[2] += 1;
  1499. n[3] += len;
  1500. } else if there > 0 {
  1501. n[4] += 1;
  1502. n[5] += there;
  1503. } else {
  1504. n[6] += 1;
  1505. }
  1506. }
  1507. n
  1508. };
  1509. let (never, gone) = (mapped(&never), mapped(&gone));
  1510. let [budget_mb, used_mb] = video.map_or([0, 0], |v| [v[0] >> 20, v[1] >> 20]);
  1511. let [copies_n, copies_mb, unmapped_mb, partly, largest, nothing, unknown] =
  1512. [c[0], c[1] >> 20, c[2] >> 20, c[3], c[4], c[5], c[6]];
  1513. let [without_never, without_gone] = without;
  1514. let [due_slots, due_uploaded, due_other, alive_n, alive_mb] = [due[0], due[1], due[2], due[3], due[4] >> 20];
  1515. let [never_n, never_mb, never_whole, never_whole_mb, never_part, never_part_mb, never_none] =
  1516. [never[0], never[1] >> 20, never[2], never[3] >> 20, never[4], never[5] >> 20, never[6]];
  1517. let [gone_n, gone_mb, gone_whole, gone_whole_mb, gone_part, gone_part_mb, gone_none] =
  1518. [gone[0], gone[1] >> 20, gone[2], gone[3] >> 20, gone[4], gone[5] >> 20, gone[6]];
  1519. let [let_go, let_go_mb, again, again_mb, made] = [since[0], since[1] >> 20, since[2], since[3] >> 20, since[4]];
  1520. let walk_ms = began.elapsed().as_millis() as u64;
  1521. tracing::info!(
  1522. "card accounting: room {room}, the card {used_mb} MB in use of a budget of {budget_mb} MB; host copies of textures the title \
  1523. fills: {copies_n} alive {copies_mb} MB, of which {unmapped_mb} MB are levels whose title memory is not mapped ({partly} copies \
  1524. with such a level, {largest} of them the largest level, {nothing} with no level mapped; {unknown} without a console layout, not \
  1525. asked); title textures without a host copy: {without_never} never had one, {without_gone} had one let go; due slots: \
  1526. {due_slots} ({due_uploaded} uploaded before, {due_other} of nothing the title fills), their textures: {alive_n} with a host \
  1527. copy alive ({alive_mb} MB, no card memory needed); {never_n} that never had one ({never_mb} MB of title memory: {never_whole} \
  1528. all mapped {never_whole_mb} MB, {never_part} in part {never_part_mb} MB mapped, {never_none} not mapped); {gone_n} whose host \
  1529. copy was let go ({gone_mb} MB: {gone_whole} all mapped {gone_whole_mb} MB, {gone_part} in part {gone_part_mb} MB mapped, \
  1530. {gone_none} not mapped); since the line before: {let_go} host copies let go {let_go_mb} MB, {again} made again {again_mb} MB, \
  1531. {made} made in all; noting took {noted_us} us on the frame's thread, the walk {walk_ms} ms on its own"
  1532. );
  1533. WALKING.store(false, Relaxed);
  1534. };
  1535. if std::thread::Builder::new().name("card accounting".into()).spawn(walk).is_err() {
  1536. WALKING.store(false, Relaxed);
  1537. }
  1538. }
  1539. /// Lets go of the host copies of textures the title fills that nothing
  1540. /// names any more: placed textures were never released (one host texture
  1541. /// per address and description ever viewed: 18,639 of them, 2.5 GB, after
  1542. /// nine minutes of run 24), nor those of texture objects before the title
  1543. /// released them. A host copy goes when
  1544. /// - the title fills the texture ([`fills`]) and the host never copied
  1545. /// into it: its contents are in title memory;
  1546. /// - only the resource holds it: no list not yet reset names it (a list
  1547. /// holds the copies of the textures it uses, `HostList::transition`);
  1548. /// - only the host copy holds the host texture: no descriptor slot views
  1549. /// it (a slot keeps what it views, `HostHeap::kept`), so no shader can
  1550. /// read it through a slot made earlier, by a table or by an index;
  1551. /// - nothing asked for it for `IDLE_MS` and `IDLE_FRAMES` frames.
  1552. ///
  1553. /// The next use makes the host copy anew and uploads the title's memory
  1554. /// again (its staging state goes with it). The title resource stays: its
  1555. /// address is what views and lists name.
  1556. /// shortcut: [`host_resource`] hands out the host texture without holding
  1557. /// it; a thread that asked for it and has not yet recorded its use (which
  1558. /// makes the list or the slot hold it) is protected by that idle time alone.
  1559. /// Every caller uses it at once, within the title's call.
  1560. /// Called before a submission starts, by the thread that submits.
  1561. /// `VICTORY_TEXTURE_SWEEP=0` lets nothing go.
  1562. #[cfg(windows)]
  1563. pub(crate) fn let_go_idle() {
  1564. use std::sync::atomic::Ordering::Relaxed;
  1565. const IDLE_FRAMES: u64 = 4;
  1566. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1567. if !*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SWEEP").is_none_or(|v| v != "0")) {
  1568. return;
  1569. }
  1570. let idle_ms = crate::host::vram_idle_ms(crate::host::host().and_then(|h| h.video_memory()));
  1571. // For the trail (`crate::host::trail`): how many went, their bytes,
  1572. // and the first one.
  1573. let (mut went, mut bytes, mut first) = (0u64, 0u64, None);
  1574. let all = textures();
  1575. for &at in all.iter() {
  1576. // SAFETY: a texture leaves the table before it is freed, under the
  1577. // lock held here (`Drop for Resource`).
  1578. let r = unsafe { &*(at as *const Resource) };
  1579. if !fills(&r.desc) || crate::texture::host_wrote(at) {
  1580. continue;
  1581. }
  1582. let gone = {
  1583. let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
  1584. let idle = made.as_ref().is_some_and(|(host, _)| {
  1585. crate::host::long_ago(r.host.used.load(Relaxed), idle_ms, IDLE_FRAMES)
  1586. && std::sync::Arc::strong_count(host) == 1
  1587. && crate::host::references(&host.texture) == 1
  1588. });
  1589. if idle {
  1590. // Under the lock: the next use must not find the staging
  1591. // state of the texture let go (it says "uploaded").
  1592. crate::texture::unstage(at as This);
  1593. made.take()
  1594. } else {
  1595. None
  1596. }
  1597. };
  1598. if let Some((host, _)) = gone {
  1599. r.host.gone.store(true, Relaxed);
  1600. KINDS[2].fetch_add(1, Relaxed);
  1601. KINDS[3].fetch_add(host.bytes, Relaxed);
  1602. went += 1;
  1603. bytes += host.bytes;
  1604. if first.is_none() {
  1605. first = Some(at);
  1606. }
  1607. crate::host::retire(host);
  1608. }
  1609. }
  1610. if went > 0 {
  1611. crate::host::trail(|| {
  1612. format!(
  1613. "sweep: {went} host copies of textures the title fills let go ({} KiB), each held by its title texture alone (no list, no slot); the first: title texture {:#x}",
  1614. bytes >> 10,
  1615. first.unwrap_or(0)
  1616. )
  1617. });
  1618. }
  1619. }
  1620. /// For the memory line: title textures with a host copy the host renders
  1621. /// to or writes and those copies' bytes (twins included); title textures
  1622. /// without a host copy and the bytes of title memory they are; host copies
  1623. /// of textures the title fills and their bytes; of all title textures,
  1624. /// the placed ones with a host copy; the bytes of the twins alone (the
  1625. /// layer's own: the console has no second texture for a depth texture
  1626. /// shaders write); and, of the host copies of placed textures the title
  1627. /// fills, the bytes of those whose title memory is not mapped any more and
  1628. /// of those a descriptor slot still shows (the card holds a texture the
  1629. /// title has given up for as long as a slot shows it). The last two are
  1630. /// estimates from every 16th such texture: asking Windows about the memory
  1631. /// of all 16,000 takes too long.
  1632. #[cfg(all(windows, feature = "diagnostics"))]
  1633. pub(crate) fn census() -> [u64; 10] {
  1634. const EVERY: u64 = 16;
  1635. let mut count = [0u64; 10];
  1636. let mut placed_filled = 0u64;
  1637. let all = textures();
  1638. for &at in all.iter() {
  1639. // SAFETY: as in `let_go_idle`.
  1640. let r = unsafe { &*(at as *const Resource) };
  1641. let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
  1642. match made.as_ref() {
  1643. Some((host, twin)) => {
  1644. let kind = if host.filled { 4 } else { 0 };
  1645. count[kind] += 1;
  1646. count[kind + 1] += host.bytes + twin.as_ref().map_or(0, |t| t.colour.bytes);
  1647. count[7] += twin.as_ref().map_or(0, |t| t.colour.bytes);
  1648. let placed = r.host.placed.load(std::sync::atomic::Ordering::Relaxed);
  1649. if placed {
  1650. count[6] += 1;
  1651. }
  1652. if placed && host.filled {
  1653. placed_filled += 1;
  1654. // Its first page: a texture's smallest mips lie there,
  1655. // and are mapped first and unmapped last.
  1656. if placed_filled.is_multiple_of(EVERY) && !crate::texture::committed(r.data().cast_const(), 1) {
  1657. count[8] += host.bytes * EVERY;
  1658. if crate::host::references(&host.texture) > 1 {
  1659. count[9] += host.bytes * EVERY;
  1660. }
  1661. }
  1662. }
  1663. }
  1664. None => {
  1665. count[2] += 1;
  1666. count[3] += footprint(&r.desc).map_or(0, |f| f.size);
  1667. }
  1668. }
  1669. }
  1670. count
  1671. }
  1672. /// Host textures alive (the title's and the twins) and the bytes the host
  1673. /// gives them, for the memory line.
  1674. #[cfg(windows)]
  1675. pub(crate) static HOST_TEXTURES: [std::sync::atomic::AtomicU64; 2] =
  1676. [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  1677. /// The bytes the host allocates for `texture`.
  1678. #[cfg(windows)]
  1679. fn host_bytes(texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource) -> u64 {
  1680. let Some(host) = crate::host::host() else {
  1681. return 0;
  1682. };
  1683. // SAFETY: plain queries on a live resource and device.
  1684. unsafe {
  1685. let desc = texture.GetDesc();
  1686. host.device.GetResourceAllocationInfo(0, &[desc]).SizeInBytes
  1687. }
  1688. }
  1689. #[cfg(windows)]
  1690. impl HostTexture {
  1691. fn new(texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, state: u32) -> HostTexture {
  1692. use std::sync::atomic::Ordering::Relaxed;
  1693. let bytes = host_bytes(&texture);
  1694. HOST_TEXTURES[0].fetch_add(1, Relaxed);
  1695. HOST_TEXTURES[1].fetch_add(bytes, Relaxed);
  1696. HostTexture {
  1697. texture,
  1698. state: std::sync::atomic::AtomicU32::new(state),
  1699. bytes,
  1700. filled: false,
  1701. }
  1702. }
  1703. }
  1704. #[cfg(windows)]
  1705. impl Drop for HostTexture {
  1706. fn drop(&mut self) {
  1707. use std::sync::atomic::Ordering::Relaxed;
  1708. HOST_TEXTURES[0].fetch_sub(1, Relaxed);
  1709. HOST_TEXTURES[1].fetch_sub(self.bytes, Relaxed);
  1710. if self.filled {
  1711. KINDS[0].fetch_sub(1, Relaxed);
  1712. KINDS[1].fetch_sub(self.bytes, Relaxed);
  1713. }
  1714. }
  1715. }
  1716. /// How many textures placed in title memory have a resource of ours
  1717. /// (never released), for the memory line.
  1718. #[cfg(all(windows, feature = "diagnostics"))]
  1719. pub(crate) fn placed_textures() -> u64 {
  1720. PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()).len() as u64
  1721. }
  1722. /// Moves the host texture to `wanted` (a host texture state); the host
  1723. /// resource and the state it leaves, if that is a change.
  1724. #[cfg(windows)]
  1725. pub(crate) fn host_transition(this: This, wanted: u32) -> Option<(*mut c_void, u32)> {
  1726. use windows::core::Interface;
  1727. let (host, _) = hosted(this, true)?;
  1728. let before = host
  1729. .state
  1730. .swap(wanted, std::sync::atomic::Ordering::Relaxed);
  1731. (before != wanted).then(|| (host.texture.as_raw(), before))
  1732. }
  1733. /// The host GPU's copy of a title resource, if it has one: made now if
  1734. /// this is the texture's first use ([`Hosted`]). Asking is a use; what must
  1735. /// not count as one asks `host_made`.
  1736. #[cfg(windows)]
  1737. pub(crate) fn host_resource<'a>(
  1738. this: This,
  1739. ) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
  1740. if this.is_null() {
  1741. return None;
  1742. }
  1743. let (host, _) = hosted(this, true)?;
  1744. // SAFETY: the resource holds the host copy until the title releases it
  1745. // (lists and slots that name the texture hold it past that), or until
  1746. // `let_go_idle` takes it: only from a texture the title fills, that no
  1747. // list and no slot holds and that nothing asked for in seconds (the
  1748. // asking just made is noted under the same lock).
  1749. Some(unsafe { &*std::ptr::from_ref(&host.texture) })
  1750. }
  1751. /// A title texture's host copy, shared, for a list to hold.
  1752. #[cfg(windows)]
  1753. pub(crate) fn host_copy(this: This) -> Option<std::sync::Arc<HostTexture>> {
  1754. if this.is_null() {
  1755. return None;
  1756. }
  1757. hosted(this, true).map(|made| made.0)
  1758. }
  1759. /// A host texture like the title's: same description, in GPU memory,
  1760. /// without the console's layout and flags.
  1761. #[cfg(windows)]
  1762. fn host_texture(
  1763. desc: &ResourceDesc,
  1764. state: u32,
  1765. clear: *const c_void,
  1766. ) -> Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
  1767. use windows::Win32::Graphics::Direct3D12::*;
  1768. const PC_FLAGS: u32 = 0xf; // render target, depth, UAV, no shader access
  1769. if desc.dimension == BUFFER {
  1770. return None;
  1771. }
  1772. let host = crate::host::host()?;
  1773. let mut d = *desc;
  1774. d.layout = 0;
  1775. d.alignment = 0;
  1776. d.flags &= PC_FLAGS;
  1777. // PC refuses depth targets that are also unordered-access (the console
  1778. // allows both; the title's shadow maps ask for it).
  1779. // The host copy loses the unordered access: shaders write a colour
  1780. // twin instead ([`Twin`]).
  1781. const DEPTH: u32 = 2;
  1782. const UNORDERED: u32 = 4;
  1783. if d.flags & DEPTH != 0 {
  1784. if d.flags & UNORDERED != 0 {
  1785. DEPTH_UNORDERED[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1786. }
  1787. d.flags &= !UNORDERED;
  1788. }
  1789. d.format = pc_format(d.format);
  1790. const TARGET: u32 = 1;
  1791. if d.flags & (TARGET | UNORDERED) != 0 {
  1792. d.format = target_format(d.format);
  1793. }
  1794. const DENY_SHADER_RESOURCE: u32 = 8;
  1795. if d.flags & DENY_SHADER_RESOURCE == 0
  1796. && let Some(&(_, typeless)) = DEPTH_FORMATS.iter().find(|&&(f, _)| f == d.format)
  1797. {
  1798. d.format = typeless;
  1799. }
  1800. // The host has no sRGB unordered access: such textures are typeless,
  1801. // their unordered access views plain UNORM.
  1802. if d.flags & UNORDERED != 0 && SRGB.iter().any(|&(srgb, _)| srgb == d.format) {
  1803. d.format = family(d.format);
  1804. }
  1805. // The clear value names the format too: format, then color or depth
  1806. // and stencil (5 words).
  1807. let clear_value = (!clear.is_null()).then(|| {
  1808. // SAFETY: the title passes a whole clear value.
  1809. let mut value = unsafe { clear.cast::<[u32; 5]>().read_unaligned() };
  1810. value[0] = pc_format(value[0]);
  1811. if d.flags & (TARGET | UNORDERED) != 0 {
  1812. value[0] = target_format(value[0]);
  1813. }
  1814. value
  1815. });
  1816. let heap = D3D12_HEAP_PROPERTIES {
  1817. Type: D3D12_HEAP_TYPE_DEFAULT,
  1818. ..Default::default()
  1819. };
  1820. // A texture the title fills, whose every subresource is uploaded before
  1821. // anything reads it: cut from a block (what the piece held before shows
  1822. // in no texel).
  1823. if fills(desc)
  1824. && d.sample_count <= 1
  1825. && clear_value.is_none()
  1826. && texture_layout(desc).is_some_and(|t| !t.planes[0].layout.desc.swizzle.xor())
  1827. // SAFETY: the description has the host layout, as below.
  1828. && let Some(t) = unsafe {
  1829. crate::pool::texture(
  1830. &host.device,
  1831. (&raw const d).cast(),
  1832. D3D12_RESOURCE_STATES(crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32),
  1833. )
  1834. }
  1835. {
  1836. crate::host::name(&t, || {
  1837. format!("texture {}x{} f{} flags {:#x} (in a block)", d.width, d.height, d.format, d.flags)
  1838. });
  1839. return Some(t);
  1840. }
  1841. let mut texture: Option<ID3D12Resource> = None;
  1842. // SAFETY: the description has the host layout (checked size, same
  1843. // fields); the out pointer is ours.
  1844. let made = unsafe {
  1845. host.device.CreateCommittedResource(
  1846. &heap,
  1847. D3D12_HEAP_FLAG_NONE,
  1848. (&raw const d).cast(),
  1849. D3D12_RESOURCE_STATES(
  1850. crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32,
  1851. ),
  1852. // The same layout: format, then color or depth and stencil.
  1853. clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()),
  1854. &mut texture,
  1855. )
  1856. };
  1857. if let Err(e) = made {
  1858. tracing::warn!(error = %e, desc = ?d, "no host texture");
  1859. }
  1860. if let Some(t) = &texture {
  1861. crate::host::name(t, || {
  1862. format!("texture {}x{} f{} flags {:#x}", d.width, d.height, d.format, d.flags)
  1863. });
  1864. }
  1865. texture
  1866. }
  1867. /// A texture's console memory and description; `None` for buffers.
  1868. pub(crate) fn texture_memory(this: This) -> Option<(*const u8, ResourceDesc)> {
  1869. if this.is_null() {
  1870. return None;
  1871. }
  1872. let r = resource(this);
  1873. (r.desc.dimension != BUFFER).then(|| (r.data().cast_const(), r.desc))
  1874. }
  1875. /// A buffer's host memory and size; `None` for textures.
  1876. pub(crate) fn buffer_bytes(this: This) -> Option<(*mut u8, u64)> {
  1877. if this.is_null() {
  1878. return None;
  1879. }
  1880. let r = resource(this);
  1881. (r.desc.dimension == BUFFER).then(|| (r.data(), r.desc.width))
  1882. }
  1883. impl Resource {
  1884. fn data(&self) -> *mut u8 {
  1885. match self.backing {
  1886. Backing::Committed(ref memory) => memory.ptr.as_ptr(),
  1887. // SAFETY: placement checked the range lies inside the heap.
  1888. Backing::Placed { heap, offset } => unsafe {
  1889. (*heap.cast::<Heap>())
  1890. .memory
  1891. .ptr
  1892. .as_ptr()
  1893. .add(offset as usize)
  1894. },
  1895. Backing::Address(at) => at,
  1896. }
  1897. }
  1898. }
  1899. fn resource<'a>(this: This) -> &'a Resource {
  1900. // SAFETY: called from resource methods only.
  1901. unsafe { &*this.cast::<Resource>() }
  1902. }
  1903. // The creation methods' own arguments, passed on.
  1904. #[allow(clippy::too_many_arguments)]
  1905. fn hand_out_resource(
  1906. desc: ResourceDesc,
  1907. heap: HeapProperties,
  1908. heap_flags: u32,
  1909. backing: Backing,
  1910. state: u32,
  1911. clear: *const c_void,
  1912. iid: *const Iid,
  1913. out: *mut This,
  1914. ) -> HRESULT {
  1915. #[cfg(not(windows))]
  1916. let _ = (state, clear);
  1917. let resource = Box::new(Resource {
  1918. object: Object::new(&RESOURCE_FUNCTIONS),
  1919. desc,
  1920. heap,
  1921. heap_flags,
  1922. backing,
  1923. #[cfg(windows)]
  1924. host: Hosted {
  1925. made: std::sync::Mutex::new(None),
  1926. state,
  1927. // SAFETY: the title passes a whole clear value (the format,
  1928. // then color or depth and stencil: 5 words) or null.
  1929. clear: (!clear.is_null()).then(|| unsafe { clear.cast::<[u32; 5]>().read_unaligned() }),
  1930. used: std::sync::atomic::AtomicU64::new(0),
  1931. refused: std::sync::atomic::AtomicBool::new(false),
  1932. gone: std::sync::atomic::AtomicBool::new(false),
  1933. placed: std::sync::atomic::AtomicBool::new(false),
  1934. },
  1935. });
  1936. // The host copy waits for the texture's first use ([`Hosted`]).
  1937. #[cfg(windows)]
  1938. if desc.dimension != BUFFER {
  1939. let at = std::ptr::from_ref::<Resource>(&resource) as usize;
  1940. textures().insert(at);
  1941. if !fills(&desc) {
  1942. TARGETS_AT
  1943. .lock()
  1944. .unwrap_or_else(|e| e.into_inner())
  1945. .insert(resource.data() as u64, at);
  1946. }
  1947. if !lazy() {
  1948. let _ = hosted(at as This, true);
  1949. }
  1950. }
  1951. #[cfg(windows)]
  1952. if desc.dimension == BUFFER {
  1953. let at = std::ptr::from_ref::<Resource>(&resource) as usize;
  1954. crate::shadow::register(at, resource.data() as u64, desc.width);
  1955. }
  1956. object::hand_out(RESOURCE, resource, iid, &RESOURCE_IIDS, out)
  1957. }
  1958. #[cfg(windows)]
  1959. impl Drop for Resource {
  1960. fn drop(&mut self) {
  1961. // Out of the table of textures first: the sweep looks at the ones
  1962. // in it, under its lock.
  1963. if self.desc.dimension != BUFFER {
  1964. textures().remove(&(std::ptr::from_ref::<Resource>(self) as usize));
  1965. if !fills(&self.desc) {
  1966. let mut targets = TARGETS_AT.lock().unwrap_or_else(|e| e.into_inner());
  1967. let at = self.data() as u64;
  1968. if targets.get(&at) == Some(&(std::ptr::from_ref::<Resource>(self) as usize)) {
  1969. targets.remove(&at);
  1970. }
  1971. }
  1972. }
  1973. let made = self
  1974. .host
  1975. .made
  1976. .get_mut()
  1977. .unwrap_or_else(|e| e.into_inner())
  1978. .take();
  1979. #[cfg(feature = "diagnostics")]
  1980. if made
  1981. .as_ref()
  1982. .is_some_and(|(h, _)| std::sync::Arc::strong_count(h) > 1)
  1983. {
  1984. // Before lists held their textures, this freed a texture that
  1985. // lists not yet run still named (a GPU page fault).
  1986. static OUTLIVED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1987. let n = OUTLIVED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
  1988. if n.is_power_of_two() {
  1989. tracing::info!(
  1990. n,
  1991. desc = ?self.desc,
  1992. "a title texture was released while a list not yet reset names its host copy"
  1993. );
  1994. }
  1995. }
  1996. // A running submission may still read the host copy (and a depth
  1997. // texture's colour twin).
  1998. if let Some((host, twin)) = made {
  1999. crate::host::retire(host);
  2000. if let Some(twin) = twin {
  2001. crate::host::retire(twin);
  2002. }
  2003. }
  2004. crate::texture::forget(std::ptr::from_ref::<Resource>(self) as usize);
  2005. crate::descriptor::forget(std::ptr::from_ref::<Resource>(self) as usize);
  2006. if self.desc.dimension == BUFFER {
  2007. crate::shadow::unregister(
  2008. std::ptr::from_ref::<Resource>(self) as usize,
  2009. self.data() as u64,
  2010. );
  2011. }
  2012. }
  2013. }
  2014. pub(crate) extern "system" fn create_committed(
  2015. _: This,
  2016. heap: *const HeapProperties,
  2017. heap_flags: u32,
  2018. desc: *const ResourceDesc,
  2019. state: u32,
  2020. clear: *const c_void,
  2021. iid: *const Iid,
  2022. out: *mut This,
  2023. ) -> HRESULT {
  2024. // SAFETY: the title passes both descriptions (null is tolerated).
  2025. let (Some(&heap), Some(&desc)) = (unsafe { (heap.as_ref(), desc.as_ref()) }) else {
  2026. return E_INVALIDARG;
  2027. };
  2028. let Some(info) = footprint(&desc) else {
  2029. tracing::warn!(?desc, "no size for this resource");
  2030. return E_INVALIDARG;
  2031. };
  2032. tracing::debug!(
  2033. dimension = desc.dimension,
  2034. size = info.size,
  2035. heap = heap.kind,
  2036. "committed resource"
  2037. );
  2038. let memory = match Memory::for_resource(info, heap.kind) {
  2039. Ok(memory) => memory,
  2040. Err(hr) => return hr,
  2041. };
  2042. hand_out_resource(
  2043. desc,
  2044. heap,
  2045. heap_flags,
  2046. Backing::Committed(memory),
  2047. state,
  2048. clear,
  2049. iid,
  2050. out,
  2051. )
  2052. }
  2053. /// Device method 0x3f8, inferred from the title's calls
  2054. /// (title+0x193e1b4: its back buffers, heap flag "allow display"): the
  2055. /// committed resource creation of the enhanced-barrier interfaces,
  2056. /// `(heap, heap flags, desc1, initial layout, clear value, protected
  2057. /// session, castable format count, castable formats, iid, out)`. The host
  2058. /// copy starts in the common state, as layouts are not tracked.
  2059. #[allow(clippy::too_many_arguments)] // the method's own arguments
  2060. pub(crate) extern "system" fn create_committed3(
  2061. this: This,
  2062. heap: *const HeapProperties,
  2063. heap_flags: u32,
  2064. desc: *const ResourceDesc,
  2065. _layout: u32,
  2066. clear: *const c_void,
  2067. _protected: This,
  2068. _castable_count: u32,
  2069. _castable: *const u32,
  2070. iid: *const Iid,
  2071. out: *mut This,
  2072. ) -> HRESULT {
  2073. const COMMON: u32 = 0;
  2074. create_committed(this, heap, heap_flags, desc, COMMON, clear, iid, out)
  2075. }
  2076. /// Registered page pools (64 KiB pages the title maps into tiled
  2077. /// resources by page index): first address and page count; a handle is an
  2078. /// index plus one, a removed pool leaves `None`.
  2079. static PAGE_POOLS: std::sync::Mutex<Vec<Option<(u64, u32)>>> = std::sync::Mutex::new(Vec::new());
  2080. fn page_pools() -> std::sync::MutexGuard<'static, Vec<Option<(u64, u32)>>> {
  2081. PAGE_POOLS.lock().unwrap_or_else(|e| e.into_inner())
  2082. }
  2083. /// Device method 0x250: `(address, page count, handle out)`.
  2084. pub(crate) extern "system" fn register_page_pool(
  2085. _: This,
  2086. address: u64,
  2087. pages: u32,
  2088. out: *mut usize,
  2089. ) -> HRESULT {
  2090. if out.is_null() || pages == 0 || !address.is_multiple_of(KIB_64) {
  2091. return E_INVALIDARG;
  2092. }
  2093. tracing::debug!(address = format_args!("{address:#x}"), pages, "page pool");
  2094. let mut pools = page_pools();
  2095. pools.push(Some((address, pages)));
  2096. // SAFETY: checked non-null; the title passes room for a handle.
  2097. unsafe { out.write(pools.len()) };
  2098. S_OK
  2099. }
  2100. /// Device method 0x258.
  2101. pub(crate) extern "system" fn unregister_page_pool(_: This, handle: usize) -> HRESULT {
  2102. match page_pools().get_mut(handle.wrapping_sub(1)) {
  2103. Some(pool @ Some(_)) => {
  2104. *pool = None;
  2105. S_OK
  2106. }
  2107. _ => E_INVALIDARG,
  2108. }
  2109. }
  2110. /// Device method 0x428, one of the `ID3D12Device9` to `ID3D12Device11`
  2111. /// additions. From the title's call: a resource at a virtual
  2112. /// address the title mapped itself, `(address, desc1, initial barrier
  2113. /// layout, clear value, iid, out)`, as `CreatePlacedResourceX` with
  2114. /// enhanced barriers. GPU addresses are CPU addresses, so the resource is
  2115. /// a view of that memory. `D3D12_RESOURCE_DESC1` starts like the plain
  2116. /// description; its sampler feedback region is not needed.
  2117. pub(crate) extern "system" fn create_at_address(
  2118. _: This,
  2119. address: u64,
  2120. desc: *const ResourceDesc,
  2121. layout: u32,
  2122. clear: *const c_void,
  2123. iid: *const Iid,
  2124. out: *mut This,
  2125. ) -> HRESULT {
  2126. // SAFETY: the title passes a description (null is tolerated).
  2127. let Some(&desc) = (unsafe { desc.as_ref() }) else {
  2128. return E_INVALIDARG;
  2129. };
  2130. if address == 0 {
  2131. return E_INVALIDARG;
  2132. }
  2133. tracing::debug!(
  2134. address = format_args!("{address:#x}"),
  2135. dimension = desc.dimension,
  2136. width = desc.width,
  2137. layout,
  2138. "resource at an address"
  2139. );
  2140. const COMMON: u32 = 0;
  2141. const DEFAULT: HeapProperties = HeapProperties {
  2142. kind: 1,
  2143. cpu_pages: 0,
  2144. pool: 0,
  2145. creation_nodes: 1,
  2146. visible_nodes: 1,
  2147. };
  2148. hand_out_resource(
  2149. desc,
  2150. DEFAULT,
  2151. 0,
  2152. Backing::Address(address as *mut u8),
  2153. COMMON,
  2154. clear,
  2155. iid,
  2156. out,
  2157. )
  2158. }
  2159. /// Textures the title placed in its own memory and views without a
  2160. /// resource object (device 0x230, the title's streamed and
  2161. /// interface textures), by address and description: a resource at that
  2162. /// address, made the first time a draw reads one.
  2163. /// The resource is kept for the run (views and lists name its address);
  2164. /// its host texture is let go when nothing names it any more
  2165. /// ([`let_go_idle`]) and made again on the next use.
  2166. #[cfg(windows)]
  2167. static PLACED_TEXTURES: std::sync::Mutex<std::collections::BTreeMap<(u64, [u32; 14]), usize>> =
  2168. std::sync::Mutex::new(std::collections::BTreeMap::new());
  2169. /// The placed textures asked for with filler words set, as asked
  2170. /// (address and description): for [`PLACED_TWINS`].
  2171. #[cfg(windows)]
  2172. static PLACED_RAW: std::sync::Mutex<std::collections::BTreeSet<(u64, [u32; 14])>> =
  2173. std::sync::Mutex::new(std::collections::BTreeSet::new());
  2174. /// Placed textures asked for a second time with other filler words in
  2175. /// their description: each was a second resource and host copy before the
  2176. /// filler was left out of the key ([`texture_at`]).
  2177. #[cfg(windows)]
  2178. static PLACED_TWINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  2179. /// See [`PLACED_TWINS`].
  2180. #[cfg(windows)]
  2181. pub(crate) fn placed_filler_twins() -> u64 {
  2182. PLACED_TWINS.load(std::sync::atomic::Ordering::Relaxed)
  2183. }
  2184. /// The bytes of title memory a texture with the resource description
  2185. /// `desc` (as words) takes where the title placed it; `None` for a buffer
  2186. /// and for a description without a size.
  2187. #[cfg(windows)]
  2188. pub(crate) fn placed_bytes(desc: &[u32; 14]) -> Option<u64> {
  2189. // SAFETY: 56 bytes in the description's layout.
  2190. let d = unsafe { desc.as_ptr().cast::<ResourceDesc>().read_unaligned() };
  2191. if d.dimension == BUFFER {
  2192. return None;
  2193. }
  2194. footprint(&d).map(|f| f.size)
  2195. }
  2196. /// The resource [`texture_at`] made for a texture placed at `address` with
  2197. /// the description `desc`, if it has made one: never made here (for the
  2198. /// frame listing, which must not count as a use).
  2199. #[cfg(all(windows, feature = "diagnostics"))]
  2200. pub(crate) fn texture_at_made(address: u64, desc: &[u32; 14]) -> Option<This> {
  2201. let mut key = *desc;
  2202. key[1] = 0;
  2203. key[13] = 0;
  2204. let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner());
  2205. let found = map.get(&(address, key)).or_else(|| map.get(&(address, *desc)))?;
  2206. Some(*found as This)
  2207. }
  2208. /// The resource for a texture placed at `address` with the resource
  2209. /// description `desc` (as words), made on first use.
  2210. #[cfg(windows)]
  2211. pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> {
  2212. // Words 1 and 13 of the description are the filler of its layout
  2213. // (after the dimension, and at the end): the title leaves there what
  2214. // its stack held, and two views of one texture that differed only in
  2215. // them each got a resource and a host copy of their own, on a card
  2216. // that fills at world entry. They are not part of what a texture is.
  2217. // `VICTORY_PLACED_FILLER=1`: kept in the key, as before.
  2218. static KEPT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  2219. let raw = *desc;
  2220. let mut key = *desc;
  2221. if !*KEPT.get_or_init(|| std::env::var_os("VICTORY_PLACED_FILLER").is_some_and(|v| v == "1")) {
  2222. key[1] = 0;
  2223. key[13] = 0;
  2224. }
  2225. let desc = &key;
  2226. let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner());
  2227. // How many resources the filler alone would have added (a count for
  2228. // the log: `placed_filler_twins`).
  2229. if raw != key {
  2230. let mut seen = PLACED_RAW.lock().unwrap_or_else(|e| e.into_inner());
  2231. if seen.insert((address, raw)) {
  2232. let others = seen.range((address, [0; 14])..=(address, [u32::MAX; 14])).filter(|(_, r)| {
  2233. let mut blank = *r;
  2234. blank[1] = 0;
  2235. blank[13] = 0;
  2236. blank == key
  2237. });
  2238. if others.count() > 1 {
  2239. PLACED_TWINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2240. }
  2241. }
  2242. }
  2243. if let Some(&r) = map.get(&(address, *desc)) {
  2244. return Some(r as This);
  2245. }
  2246. // SAFETY: 56 bytes in the description's layout.
  2247. let d = unsafe { desc.as_ptr().cast::<ResourceDesc>().read_unaligned() };
  2248. if d.dimension == BUFFER {
  2249. return None;
  2250. }
  2251. let mut out = std::ptr::null();
  2252. let made = create_at_address(
  2253. std::ptr::null(),
  2254. address,
  2255. &d,
  2256. 0,
  2257. std::ptr::null(),
  2258. &RESOURCE_IIDS[0],
  2259. &mut out,
  2260. );
  2261. if made != S_OK {
  2262. return None;
  2263. }
  2264. map.insert((address, *desc), out as usize);
  2265. crate::texture::placed_in_host_written(address, desc);
  2266. resource(out)
  2267. .host
  2268. .placed
  2269. .store(true, std::sync::atomic::Ordering::Relaxed);
  2270. Some(out)
  2271. }
  2272. pub(crate) extern "system" fn create_placed(
  2273. _: This,
  2274. heap: This,
  2275. offset: u64,
  2276. desc: *const ResourceDesc,
  2277. state: u32,
  2278. clear: *const c_void,
  2279. iid: *const Iid,
  2280. out: *mut This,
  2281. ) -> HRESULT {
  2282. // SAFETY: the title passes a description (null is tolerated).
  2283. let Some(&desc) = (unsafe { desc.as_ref() }) else {
  2284. return E_INVALIDARG;
  2285. };
  2286. if heap.is_null() {
  2287. return E_INVALIDARG;
  2288. }
  2289. // SAFETY: the title passes one of our heaps.
  2290. let h = unsafe { &*heap.cast::<Heap>() };
  2291. let fits = footprint(&desc).is_some_and(|info| {
  2292. offset.is_multiple_of(info.alignment)
  2293. && offset
  2294. .checked_add(info.size)
  2295. .is_some_and(|end| end <= h.desc.size)
  2296. });
  2297. if !fits {
  2298. tracing::warn!(
  2299. ?desc,
  2300. offset,
  2301. heap = h.desc.size,
  2302. "placed resource does not fit"
  2303. );
  2304. return E_INVALIDARG;
  2305. }
  2306. object::add_ref(heap);
  2307. let backing = Backing::Placed { heap, offset };
  2308. hand_out_resource(
  2309. desc,
  2310. h.desc.properties,
  2311. h.desc.flags,
  2312. backing,
  2313. state,
  2314. clear,
  2315. iid,
  2316. out,
  2317. )
  2318. }
  2319. extern "system" fn resource_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  2320. object::answer(
  2321. RESOURCE,
  2322. iid,
  2323. object::is(iid, &RESOURCE_IIDS).then_some(this),
  2324. out,
  2325. )
  2326. }
  2327. extern "system" fn resource_release(this: This) -> u32 {
  2328. object::release_boxed::<Resource>(this)
  2329. }
  2330. /// Memory is always mapped (subresources are not told apart yet); a null
  2331. /// `out` only asks for residency.
  2332. extern "system" fn map(this: This, _sub: u32, _read: *const c_void, out: *mut *mut u8) -> HRESULT {
  2333. if !out.is_null() {
  2334. // SAFETY: checked non-null; the title passes room for a pointer.
  2335. unsafe { out.write(resource(this).data()) };
  2336. }
  2337. S_OK
  2338. }
  2339. extern "system" fn unmap(_: This, _sub: u32, _written: *const c_void) {}
  2340. extern "system" fn resource_desc(this: This, out: *mut ResourceDesc) {
  2341. if !out.is_null() {
  2342. // SAFETY: checked non-null; the title passes room for a description.
  2343. unsafe { out.write(resource(this).desc) };
  2344. }
  2345. }
  2346. /// Device method `GetCustomHeapProperties`, returning its struct through a
  2347. /// hidden first argument: what a standard heap type is as a custom heap.
  2348. /// Memory is unified and cache-coherent (as the architecture query says),
  2349. /// so every type is in pool L0, default heaps are not CPU-visible and the
  2350. /// others are write-back.
  2351. pub(crate) extern "system" fn custom_heap_properties(
  2352. out: *mut HeapProperties,
  2353. _: This,
  2354. nodes: u32,
  2355. kind: u32,
  2356. ) -> *mut HeapProperties {
  2357. const CUSTOM: u32 = 4;
  2358. const NOT_AVAILABLE: u32 = 1;
  2359. const WRITE_BACK: u32 = 3;
  2360. const L0: u32 = 1;
  2361. let nodes = nodes.max(1);
  2362. let cpu_pages = match kind {
  2363. 1 => NOT_AVAILABLE,
  2364. 2 | 3 => WRITE_BACK,
  2365. _ => 0,
  2366. };
  2367. let properties = HeapProperties {
  2368. kind: CUSTOM,
  2369. cpu_pages,
  2370. pool: if cpu_pages == 0 { 0 } else { L0 },
  2371. creation_nodes: nodes,
  2372. visible_nodes: nodes,
  2373. };
  2374. // SAFETY: the title passes room for the result (null is tolerated).
  2375. if let Some(out) = unsafe { out.as_mut() } {
  2376. *out = properties;
  2377. }
  2378. out
  2379. }
  2380. extern "system" fn gpu_address(this: This) -> u64 {
  2381. let r = resource(this);
  2382. let at = r.data() as u64;
  2383. // The console's GPU addresses fit in 40 bits; its ray-tracing builder
  2384. // refuses others (diagnostics: which memory breaks that).
  2385. #[cfg(feature = "diagnostics")]
  2386. if at >> 40 != 0 {
  2387. static ONCE: [std::sync::Once; 2] = [std::sync::Once::new(), std::sync::Once::new()];
  2388. let backing = match r.backing {
  2389. Backing::Committed(ref m) => format!("committed, attributes {:?}", m.attributes),
  2390. Backing::Placed { offset, .. } => format!("placed in a heap at {offset:#x}"),
  2391. Backing::Address(_) => "at a title address".into(),
  2392. };
  2393. ONCE[usize::from(r.desc.dimension == BUFFER)].call_once(|| {
  2394. tracing::warn!(address = format_args!("{at:#x}"), backing, desc = ?r.desc, "a GPU address above 40 bits")
  2395. });
  2396. }
  2397. at
  2398. }
  2399. extern "system" fn heap_properties(
  2400. this: This,
  2401. properties: *mut HeapProperties,
  2402. flags: *mut u32,
  2403. ) -> HRESULT {
  2404. let r = resource(this);
  2405. // SAFETY: either pointer may be null; otherwise the title passes room.
  2406. unsafe {
  2407. if let Some(p) = properties.as_mut() {
  2408. *p = r.heap;
  2409. }
  2410. if let Some(f) = flags.as_mut() {
  2411. *f = r.heap_flags;
  2412. }
  2413. }
  2414. S_OK
  2415. }
  2416. /// IUnknown 3, object 4, device child 1, heap 1.
  2417. static HEAP_FUNCTIONS: Table<24> = {
  2418. let mut f = object::d3d12_object(object::missing_table::<HEAP, 24>());
  2419. f[0] = heap_query as *const ();
  2420. f[2] = heap_release as *const ();
  2421. f[7] = object::parent_device as *const (); // 0x38
  2422. f[8] = heap_desc as *const (); // 0x40
  2423. Table(f)
  2424. };
  2425. /// IUnknown 3, object 4, device child 1, resource 10 (7 as on PC, then 3
  2426. /// console ones).
  2427. static RESOURCE_FUNCTIONS: Table<32> = {
  2428. let mut f = object::d3d12_object(object::missing_table::<RESOURCE, 32>());
  2429. f[0] = resource_query as *const ();
  2430. f[2] = resource_release as *const ();
  2431. f[7] = object::parent_device as *const (); // 0x38
  2432. f[8] = map as *const (); // 0x40
  2433. f[9] = unmap as *const (); // 0x48
  2434. f[10] = resource_desc as *const (); // 0x50
  2435. f[11] = gpu_address as *const (); // 0x58
  2436. f[14] = heap_properties as *const (); // 0x70
  2437. Table(f)
  2438. };
  2439. #[cfg(test)]
  2440. mod tests {
  2441. use super::*;
  2442. use crate::object::slot;
  2443. type Release = extern "system" fn(This) -> u32;
  2444. type Map = extern "system" fn(This, u32, *const c_void, *mut *mut u8) -> HRESULT;
  2445. type Address = extern "system" fn(This) -> u64;
  2446. const PROPERTIES: HeapProperties = HeapProperties {
  2447. kind: 1,
  2448. cpu_pages: 0,
  2449. pool: 0,
  2450. creation_nodes: 0,
  2451. visible_nodes: 0,
  2452. };
  2453. fn buffer(width: u64) -> ResourceDesc {
  2454. ResourceDesc {
  2455. dimension: BUFFER,
  2456. alignment: 0,
  2457. width,
  2458. height: 1,
  2459. depth_or_array_size: 1,
  2460. mip_levels: 1,
  2461. format: 0,
  2462. sample_count: 1,
  2463. sample_quality: 0,
  2464. layout: 1,
  2465. flags: 0,
  2466. }
  2467. }
  2468. fn texture(width: u64, height: u32, format: u32, mips: u16) -> ResourceDesc {
  2469. ResourceDesc {
  2470. dimension: 3,
  2471. width,
  2472. height,
  2473. format,
  2474. mip_levels: mips,
  2475. layout: 0,
  2476. ..buffer(0)
  2477. }
  2478. }
  2479. fn heap(size: u64) -> This {
  2480. let desc = HeapDesc {
  2481. size,
  2482. properties: PROPERTIES,
  2483. alignment: 0,
  2484. flags: 0,
  2485. };
  2486. let mut heap = std::ptr::null();
  2487. assert_eq!(
  2488. create_heap(std::ptr::null(), &desc, &HEAP_IIDS[0], &mut heap),
  2489. S_OK
  2490. );
  2491. heap
  2492. }
  2493. #[test]
  2494. fn heaps_are_zeroed_aligned_memory() {
  2495. let heap = heap(1 << 20);
  2496. // SAFETY: a heap we just made.
  2497. let memory = unsafe { &(*heap.cast::<Heap>()).memory };
  2498. assert_eq!(memory.ptr.as_ptr() as u64 % KIB_64, 0);
  2499. let mut back = std::mem::MaybeUninit::<HeapDesc>::uninit();
  2500. slot::<extern "system" fn(This, *mut HeapDesc)>(heap, 0x40)(heap, back.as_mut_ptr());
  2501. // SAFETY: written above.
  2502. assert_eq!(unsafe { back.assume_init() }.size, 1 << 20);
  2503. assert_eq!(slot::<Release>(heap, 0x10)(heap), 0);
  2504. let bad = HeapDesc {
  2505. size: 1 << 20,
  2506. properties: PROPERTIES,
  2507. alignment: 3,
  2508. flags: 0,
  2509. };
  2510. let mut out = std::ptr::null();
  2511. assert_eq!(
  2512. create_heap(std::ptr::null(), &bad, &HEAP_IIDS[0], &mut out),
  2513. E_INVALIDARG
  2514. );
  2515. }
  2516. #[test]
  2517. fn device_setup_heap_properties_and_resources_at_addresses() {
  2518. let device = crate::device::device();
  2519. // GetCustomHeapProperties (0xd0): the struct comes back through the
  2520. // hidden first argument, which is also returned.
  2521. type Custom =
  2522. extern "system" fn(*mut HeapProperties, This, u32, u32) -> *mut HeapProperties;
  2523. let mut p = PROPERTIES;
  2524. let back = slot::<Custom>(device, 0xd0)(&mut p, device, 1, 2);
  2525. assert_eq!(back, &raw mut p);
  2526. assert_eq!(
  2527. (
  2528. p.kind,
  2529. p.cpu_pages,
  2530. p.pool,
  2531. p.creation_nodes,
  2532. p.visible_nodes
  2533. ),
  2534. (4, 3, 1, 1, 1),
  2535. "upload: custom, write-back, L0"
  2536. );
  2537. slot::<Custom>(device, 0xd0)(&mut p, device, 1, 1);
  2538. assert_eq!(p.cpu_pages, 1, "default: not CPU-visible");
  2539. // 0x428: a buffer over memory the title owns, as the title asks.
  2540. type At = extern "system" fn(
  2541. This,
  2542. u64,
  2543. *const ResourceDesc,
  2544. u32,
  2545. *const c_void,
  2546. *const Iid,
  2547. *mut This,
  2548. ) -> HRESULT;
  2549. let memory = vec![0u8; 0x1_0000];
  2550. let address = memory.as_ptr() as u64;
  2551. let mut r = std::ptr::null();
  2552. let create = slot::<At>(device, 0x428);
  2553. let desc = buffer(0x1_0000);
  2554. let null = std::ptr::null();
  2555. assert_eq!(
  2556. create(
  2557. device,
  2558. address,
  2559. &desc,
  2560. u32::MAX,
  2561. null,
  2562. &RESOURCE_IIDS[0],
  2563. &mut r
  2564. ),
  2565. 0
  2566. );
  2567. assert_eq!(slot::<Address>(r, 0x58)(r), address);
  2568. assert_eq!(slot::<Release>(r, 0x10)(r), 0);
  2569. // The title's memory is still there after the release.
  2570. assert_eq!(memory[0xffff], 0);
  2571. assert_ne!(
  2572. create(device, 0, &desc, u32::MAX, null, &RESOURCE_IIDS[0], &mut r),
  2573. 0
  2574. );
  2575. }
  2576. #[test]
  2577. fn sizes_cover_every_mip() {
  2578. let size = |d: &ResourceDesc| footprint(d).map(|i| i.size);
  2579. assert_eq!(size(&buffer(256)), Some(KIB_64));
  2580. // Textures take their console layout and its alignment (4 KiB
  2581. // standard swizzle when the description leaves it to the library):
  2582. // 512x512 BC7 with 10 mips is 0x56000 bytes, 4 KiB aligned, as on
  2583. // the console.
  2584. let layout = |d: &ResourceDesc| texture_layout(d).unwrap().size;
  2585. let rgba = texture(256, 256, 28, 0);
  2586. assert_eq!(size(&rgba), Some(layout(&rgba).next_multiple_of(4096)));
  2587. let bc7 = footprint(&texture(512, 512, 98, 10));
  2588. let console = AllocationInfo {
  2589. size: 0x56000,
  2590. alignment: 0x1000,
  2591. };
  2592. assert_eq!(bc7, Some(console));
  2593. assert!(layout(&rgba) >= 4 * (256 * 256 * 4) / 3, "every mip");
  2594. // BC1 is 8 bytes per 4x4 block: 1024x1024, one mip = 512 KiB.
  2595. assert_eq!(size(&texture(1024, 1024, 71, 1)), Some(512 << 10));
  2596. assert_eq!(size(&texture(16, 16, 66, 1)), None, "1-bit format");
  2597. // Linear layout (1) and an explicit mode (64 KiB display, 0x10a).
  2598. let linear = ResourceDesc {
  2599. layout: 1,
  2600. ..texture(100, 60, 28, 1)
  2601. };
  2602. assert_eq!(
  2603. texture_layout(&linear).unwrap().planes[0]
  2604. .layout
  2605. .desc
  2606. .swizzle
  2607. .0,
  2608. 0
  2609. );
  2610. let display = ResourceDesc {
  2611. layout: 0x10a,
  2612. ..texture(100, 60, 28, 1)
  2613. };
  2614. assert_eq!(
  2615. texture_layout(&display).unwrap().planes[0]
  2616. .layout
  2617. .desc
  2618. .swizzle
  2619. .0,
  2620. 10
  2621. );
  2622. let mut info = AllocationInfo {
  2623. size: 0,
  2624. alignment: 0,
  2625. };
  2626. let descs = [buffer(100), texture(256, 256, 28, 0)];
  2627. allocation_info(&mut info, std::ptr::null(), 0, 2, descs.as_ptr());
  2628. assert_eq!(
  2629. info,
  2630. AllocationInfo {
  2631. size: KIB_64 + size(&descs[1]).unwrap(),
  2632. alignment: KIB_64
  2633. }
  2634. );
  2635. allocation_info(&mut info, std::ptr::null(), 0, 1, &texture(1, 1, 999, 1));
  2636. assert_eq!(info.size, u64::MAX);
  2637. }
  2638. #[test]
  2639. fn upload_footprints_follow_the_pc_rules() {
  2640. let null = std::ptr::null();
  2641. let mut layouts = [NO_FOOTPRINT; 2];
  2642. let (mut rows, mut sizes, mut total) = ([0; 2], [0; 2], 0);
  2643. let mut footprints = |desc: &ResourceDesc, first, count| {
  2644. let (l, r, s) = (layouts.as_mut_ptr(), rows.as_mut_ptr(), sizes.as_mut_ptr());
  2645. copyable_footprints(null, desc, first, count, 0, l, r, s, &mut total);
  2646. (layouts, rows, sizes, total)
  2647. };
  2648. // 100x60 RGBA8, 2 mips: 400-byte rows pitched to 512.
  2649. let (l, r, s, t) = footprints(&texture(100, 60, 28, 2), 0, 2);
  2650. assert_eq!((l[0].row_pitch, r[0], s[0]), (512, 60, 400));
  2651. // Mip 1 (50x30, 200-byte rows) starts after 59 pitched rows and one
  2652. // packed row, rounded up to 512.
  2653. assert_eq!(l[1].offset, (512 * 59 + 400u64).next_multiple_of(512));
  2654. assert_eq!((l[1].width, l[1].height, r[1]), (50, 30, 30));
  2655. assert_eq!(t, l[1].offset + 256 * 29 + 200);
  2656. // BC1: rows of 4x4 blocks, 8 bytes each.
  2657. let (_, r, s, _) = footprints(&texture(64, 64, 71, 1), 0, 1);
  2658. assert_eq!((r[0], s[0]), (16, 128));
  2659. let (_, _, _, t) = footprints(&texture(64, 64, 71, 1), 1, 1);
  2660. assert_eq!(t, u64::MAX, "no second subresource");
  2661. }
  2662. /// A 4x4 texture filled from a title buffer through our list and queue,
  2663. /// then read back from the host GPU.
  2664. #[cfg(windows)]
  2665. #[test]
  2666. fn buffer_data_reaches_the_host_texture() {
  2667. use windows::Win32::Graphics::Direct3D12::*;
  2668. let Some(host) = crate::host::host() else {
  2669. return; // no host GPU here
  2670. };
  2671. let null = std::ptr::null();
  2672. let iid = &RESOURCE_IIDS[0];
  2673. const COPY_DEST: u32 = 0x400;
  2674. let (mut image, mut source) = (null, null);
  2675. let rgba = texture(4, 4, 28, 1);
  2676. assert_eq!(
  2677. create_committed(
  2678. null,
  2679. &PROPERTIES,
  2680. 0,
  2681. &rgba,
  2682. COPY_DEST,
  2683. null.cast(),
  2684. iid,
  2685. &mut image
  2686. ),
  2687. S_OK
  2688. );
  2689. assert_eq!(
  2690. create_committed(
  2691. null,
  2692. &PROPERTIES,
  2693. 0,
  2694. &buffer(1024),
  2695. 0,
  2696. null.cast(),
  2697. iid,
  2698. &mut source
  2699. ),
  2700. S_OK
  2701. );
  2702. let (data, _) = buffer_bytes(source).unwrap();
  2703. // SAFETY: the buffer holds 1024 bytes.
  2704. let bytes = unsafe { std::slice::from_raw_parts_mut(data, 1024) };
  2705. for (i, b) in bytes.iter_mut().enumerate() {
  2706. *b = (i % 251) as u8;
  2707. }
  2708. let queue_iid = guid(
  2709. 0x0ec870a6,
  2710. 0x5d7e,
  2711. 0x4c22,
  2712. [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed],
  2713. );
  2714. let allocator_iid = guid(
  2715. 0x6102dee4,
  2716. 0xaf59,
  2717. 0x4b09,
  2718. [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24],
  2719. );
  2720. let list_iid = guid(
  2721. 0x5b160d0f,
  2722. 0xac1b,
  2723. 0x4185,
  2724. [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55],
  2725. );
  2726. let (mut queue, mut allocator, mut list) = (null, null, null);
  2727. let queue_desc = [0u32; 4];
  2728. assert_eq!(
  2729. crate::queue::create(null, queue_desc.as_ptr().cast(), &queue_iid, &mut queue),
  2730. S_OK
  2731. );
  2732. assert_eq!(
  2733. crate::list::create_allocator(null, 0, &allocator_iid, &mut allocator),
  2734. S_OK
  2735. );
  2736. assert_eq!(
  2737. crate::list::create_list(null, 0, 0, allocator, null, &list_iid, &mut list),
  2738. S_OK
  2739. );
  2740. #[repr(C)]
  2741. struct Location {
  2742. resource: This,
  2743. kind: u32,
  2744. footprint: PlacedFootprint,
  2745. }
  2746. let rows = PlacedFootprint {
  2747. offset: 0,
  2748. format: 28,
  2749. width: 4,
  2750. height: 4,
  2751. depth: 1,
  2752. row_pitch: 256,
  2753. };
  2754. let to = Location {
  2755. resource: image,
  2756. kind: 0,
  2757. footprint: PlacedFootprint { offset: 0, ..rows },
  2758. };
  2759. let from = Location {
  2760. resource: source,
  2761. kind: 1,
  2762. footprint: rows,
  2763. };
  2764. type Copy =
  2765. extern "system" fn(This, *const Location, u32, u32, u32, *const Location, *const u8);
  2766. slot::<Copy>(list, 0x80)(list, &to, 0, 0, 0, &from, null.cast());
  2767. slot::<extern "system" fn(This) -> HRESULT>(list, 0x48)(list);
  2768. slot::<extern "system" fn(This, u32, *const This)>(queue, 0x50)(queue, 1, &list);
  2769. // Read the host texture back into a readback buffer.
  2770. let readback_heap = D3D12_HEAP_PROPERTIES {
  2771. Type: D3D12_HEAP_TYPE_READBACK,
  2772. ..Default::default()
  2773. };
  2774. let readback_desc = D3D12_RESOURCE_DESC {
  2775. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  2776. Width: 1024,
  2777. Height: 1,
  2778. DepthOrArraySize: 1,
  2779. MipLevels: 1,
  2780. SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC {
  2781. Count: 1,
  2782. Quality: 0,
  2783. },
  2784. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  2785. ..Default::default()
  2786. };
  2787. let mut readback: Option<ID3D12Resource> = None;
  2788. // SAFETY: plain creation of a readback buffer.
  2789. unsafe {
  2790. host.device
  2791. .CreateCommittedResource(
  2792. &readback_heap,
  2793. D3D12_HEAP_FLAG_NONE,
  2794. &readback_desc,
  2795. D3D12_RESOURCE_STATE_COPY_DEST,
  2796. None,
  2797. &mut readback,
  2798. )
  2799. .unwrap();
  2800. }
  2801. let readback = readback.unwrap();
  2802. let host_image = host_resource(image).unwrap();
  2803. let back = host.new_list().unwrap();
  2804. let (_, before) = host_transition(image, 0x800).unwrap();
  2805. // The upload list holds the texture until it is reset.
  2806. assert!(std::sync::Arc::strong_count(&host_copy(image).unwrap()) > 2);
  2807. use windows::core::Interface;
  2808. let out_to = Location {
  2809. resource: readback.as_raw().cast_const().cast(),
  2810. kind: 1,
  2811. footprint: rows,
  2812. };
  2813. let out_from = Location {
  2814. resource: host_image.as_raw().cast_const().cast(),
  2815. kind: 0,
  2816. footprint: to.footprint,
  2817. };
  2818. // SAFETY: an open list, live resources, locations in the host layout.
  2819. unsafe {
  2820. back.list.ResourceBarrier(&[crate::host::transition(
  2821. host_image,
  2822. D3D12_RESOURCE_STATES(before as i32),
  2823. D3D12_RESOURCE_STATE_COPY_SOURCE,
  2824. )]);
  2825. back.list.CopyTextureRegion(
  2826. (&raw const out_to).cast(),
  2827. 0,
  2828. 0,
  2829. 0,
  2830. (&raw const out_from).cast(),
  2831. None,
  2832. );
  2833. }
  2834. back.close();
  2835. host.execute(&[&back]);
  2836. let mut mapped = std::ptr::null_mut();
  2837. // SAFETY: the copy finished (execute waits); the buffer is 1024 bytes.
  2838. let read = unsafe {
  2839. readback
  2840. .Map(
  2841. 0,
  2842. Some(&D3D12_RANGE {
  2843. Begin: 0,
  2844. End: 1024,
  2845. }),
  2846. Some(&mut mapped),
  2847. )
  2848. .unwrap();
  2849. std::slice::from_raw_parts(mapped.cast::<u8>(), 1024)
  2850. };
  2851. for row in 0..4 {
  2852. let at = row * 256;
  2853. assert_eq!(read[at..at + 16], bytes[at..at + 16], "row {row}");
  2854. }
  2855. }
  2856. /// A 16-bit depth texture the title also asks unordered access for gets
  2857. /// a colour twin, and the host copies one into the other, both ways: a
  2858. /// pattern put into the twin is copied to the depth texture, the twin
  2859. /// is overwritten with zeros, and the pattern comes back from the depth
  2860. /// texture. A copy the host does not allow ends the test (with the
  2861. /// debug layer's message under `VICTORY_D3D12_DEBUG=1` in a diagnostics
  2862. /// build).
  2863. #[cfg(windows)]
  2864. #[test]
  2865. fn a_depth_texture_and_its_twin_copy_into_each_other() {
  2866. use windows::Win32::Graphics::Direct3D12::*;
  2867. use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC};
  2868. let Some(host) = crate::host::host() else {
  2869. return; // no host GPU here
  2870. };
  2871. let null = std::ptr::null();
  2872. const DEPTH_WRITE: u32 = 0x10;
  2873. let desc = ResourceDesc {
  2874. flags: 6,
  2875. ..texture(4, 4, 55, 1)
  2876. };
  2877. let mut depth = null;
  2878. assert_eq!(
  2879. create_committed(
  2880. null,
  2881. &PROPERTIES,
  2882. 0,
  2883. &desc,
  2884. DEPTH_WRITE,
  2885. null.cast(),
  2886. &RESOURCE_IIDS[0],
  2887. &mut depth
  2888. ),
  2889. S_OK
  2890. );
  2891. let host_depth = host_resource(depth).unwrap();
  2892. let Some(twin) = twin_resource(depth) else {
  2893. return; // twins are turned off
  2894. };
  2895. // SAFETY: live resources.
  2896. let (d, t) = unsafe { (host_depth.GetDesc(), twin.GetDesc()) };
  2897. // Both R16 typeless: one a depth texture, one with unordered access.
  2898. assert_eq!((d.Format.0, d.Flags.0), (53, 2));
  2899. assert_eq!((t.Format.0, t.Flags.0), (53, 4));
  2900. // Four rows of four 16-bit texels, 256 bytes apart as copies place
  2901. // them: the pattern, then as many zeros.
  2902. let mut pattern = vec![0u8; 1024];
  2903. for row in 0..4 {
  2904. for b in 0..8 {
  2905. pattern[row * 256 + b] = (1 + row * 8 + b) as u8;
  2906. }
  2907. }
  2908. let (upload, data) = host.upload_buffer(2048).unwrap();
  2909. // SAFETY: the buffer's mapping, 2048 bytes.
  2910. unsafe {
  2911. std::ptr::copy_nonoverlapping(pattern.as_ptr(), data, 1024);
  2912. std::ptr::write_bytes(data.add(1024), 0, 1024);
  2913. }
  2914. let readback_heap = D3D12_HEAP_PROPERTIES {
  2915. Type: D3D12_HEAP_TYPE_READBACK,
  2916. ..Default::default()
  2917. };
  2918. let readback_desc = D3D12_RESOURCE_DESC {
  2919. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  2920. Width: 1024,
  2921. Height: 1,
  2922. DepthOrArraySize: 1,
  2923. MipLevels: 1,
  2924. SampleDesc: DXGI_SAMPLE_DESC {
  2925. Count: 1,
  2926. Quality: 0,
  2927. },
  2928. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  2929. ..Default::default()
  2930. };
  2931. let mut readback: Option<ID3D12Resource> = None;
  2932. // SAFETY: plain creation of a readback buffer.
  2933. unsafe {
  2934. host.device
  2935. .CreateCommittedResource(
  2936. &readback_heap,
  2937. D3D12_HEAP_FLAG_NONE,
  2938. &readback_desc,
  2939. D3D12_RESOURCE_STATE_COPY_DEST,
  2940. None,
  2941. &mut readback,
  2942. )
  2943. .unwrap();
  2944. }
  2945. let readback = readback.unwrap();
  2946. // A texture's one subresource; the four rows of a buffer at `offset`.
  2947. let whole = |texture: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION {
  2948. // SAFETY: a borrowed pointer the location never releases.
  2949. pResource: unsafe { std::mem::transmute_copy(texture) },
  2950. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  2951. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  2952. SubresourceIndex: 0,
  2953. },
  2954. };
  2955. let rows = |buffer: &ID3D12Resource, offset: u64| D3D12_TEXTURE_COPY_LOCATION {
  2956. // SAFETY: as above.
  2957. pResource: unsafe { std::mem::transmute_copy(buffer) },
  2958. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  2959. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  2960. PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
  2961. Offset: offset,
  2962. Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
  2963. Format: DXGI_FORMAT(53),
  2964. Width: 4,
  2965. Height: 4,
  2966. Depth: 1,
  2967. RowPitch: 256,
  2968. },
  2969. },
  2970. },
  2971. };
  2972. let (written, tested, source, dest) = (
  2973. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  2974. D3D12_RESOURCE_STATE_DEPTH_WRITE,
  2975. D3D12_RESOURCE_STATE_COPY_SOURCE,
  2976. D3D12_RESOURCE_STATE_COPY_DEST,
  2977. );
  2978. let moved = crate::host::transition;
  2979. let list = host.new_list().unwrap();
  2980. // SAFETY: an open list and live resources; the two textures are one
  2981. // size in one format family.
  2982. unsafe {
  2983. let l = &list.list;
  2984. // The pattern into the twin, the twin into the depth texture.
  2985. l.ResourceBarrier(&[moved(twin, written, dest), moved(host_depth, tested, dest)]);
  2986. l.CopyTextureRegion(&whole(twin), 0, 0, 0, &rows(&upload, 0), None);
  2987. l.ResourceBarrier(&[moved(twin, dest, source)]);
  2988. l.CopyResource(host_depth, twin);
  2989. // Zeros over the twin, then the depth texture back into it.
  2990. l.ResourceBarrier(&[moved(twin, source, dest)]);
  2991. l.CopyTextureRegion(&whole(twin), 0, 0, 0, &rows(&upload, 1024), None);
  2992. l.ResourceBarrier(&[moved(host_depth, dest, source)]);
  2993. l.CopyResource(twin, host_depth);
  2994. // The twin read back; both textures to the states they had.
  2995. l.ResourceBarrier(&[moved(twin, dest, source)]);
  2996. l.CopyTextureRegion(&rows(&readback, 0), 0, 0, 0, &whole(twin), None);
  2997. l.ResourceBarrier(&[
  2998. moved(twin, source, written),
  2999. moved(host_depth, source, tested),
  3000. ]);
  3001. }
  3002. list.close();
  3003. host.execute(&[&list]);
  3004. let mut mapped = std::ptr::null_mut();
  3005. // SAFETY: the copies finished (execute waits); the buffer is 1024 bytes.
  3006. let read = unsafe {
  3007. readback
  3008. .Map(
  3009. 0,
  3010. Some(&D3D12_RANGE {
  3011. Begin: 0,
  3012. End: 1024,
  3013. }),
  3014. Some(&mut mapped),
  3015. )
  3016. .unwrap();
  3017. std::slice::from_raw_parts(mapped.cast::<u8>(), 1024)
  3018. };
  3019. for row in 0..4 {
  3020. let at = row * 256;
  3021. assert_eq!(read[at..at + 8], pattern[at..at + 8], "row {row}");
  3022. }
  3023. }
  3024. /// A depth texture with a stencil plane that the title also asks
  3025. /// unordered access for gets a twin of the stencil plane, and what
  3026. /// shaders write there is in the stencil plane once the list is closed:
  3027. /// a pattern put into the twin is read back from the plane.
  3028. #[cfg(windows)]
  3029. #[test]
  3030. fn a_stencil_planes_twin_reaches_the_plane() {
  3031. use std::sync::atomic::Ordering::Relaxed;
  3032. use windows::Win32::Graphics::Direct3D12::*;
  3033. use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC};
  3034. let Some(host) = crate::host::host() else {
  3035. return; // no host GPU here
  3036. };
  3037. let null = std::ptr::null();
  3038. const DEPTH_WRITE: u32 = 0x10;
  3039. let desc = ResourceDesc {
  3040. flags: 6,
  3041. ..texture(4, 4, 45, 1)
  3042. };
  3043. let mut depth = null;
  3044. assert_eq!(
  3045. create_committed(
  3046. null,
  3047. &PROPERTIES,
  3048. 0,
  3049. &desc,
  3050. DEPTH_WRITE,
  3051. null.cast(),
  3052. &RESOURCE_IIDS[0],
  3053. &mut depth
  3054. ),
  3055. S_OK
  3056. );
  3057. let host_depth = host_resource(depth).unwrap();
  3058. let Some(twin) = twin_resource(depth) else {
  3059. return; // twins are turned off
  3060. };
  3061. // SAFETY: live resources.
  3062. let (d, t) = unsafe { (host_depth.GetDesc(), twin.GetDesc()) };
  3063. // R24G8 typeless with depth, R8 typeless with unordered access.
  3064. assert_eq!((d.Format.0, d.Flags.0), (44, 2));
  3065. assert_eq!((t.Format.0, t.Flags.0), (60, 4));
  3066. // Four rows of four texels, 256 bytes apart as copies place them.
  3067. let mut pattern = vec![0u8; 1024];
  3068. for row in 0..4 {
  3069. for b in 0..4 {
  3070. pattern[row * 256 + b] = (1 + row * 4 + b) as u8;
  3071. }
  3072. }
  3073. let (upload, data) = host.upload_buffer(1024).unwrap();
  3074. // SAFETY: the buffer's mapping, 1024 bytes.
  3075. unsafe { std::ptr::copy_nonoverlapping(pattern.as_ptr(), data, 1024) };
  3076. let readback_heap = D3D12_HEAP_PROPERTIES {
  3077. Type: D3D12_HEAP_TYPE_READBACK,
  3078. ..Default::default()
  3079. };
  3080. let readback_desc = D3D12_RESOURCE_DESC {
  3081. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  3082. // Room for the rows as the host places them (512 bytes apart
  3083. // for the stencil plane on NVIDIA, not 256).
  3084. Width: 4096,
  3085. Height: 1,
  3086. DepthOrArraySize: 1,
  3087. MipLevels: 1,
  3088. SampleDesc: DXGI_SAMPLE_DESC {
  3089. Count: 1,
  3090. Quality: 0,
  3091. },
  3092. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  3093. ..Default::default()
  3094. };
  3095. let mut readback: Option<ID3D12Resource> = None;
  3096. // SAFETY: plain creation of a readback buffer.
  3097. unsafe {
  3098. host.device
  3099. .CreateCommittedResource(
  3100. &readback_heap,
  3101. D3D12_HEAP_FLAG_NONE,
  3102. &readback_desc,
  3103. D3D12_RESOURCE_STATE_COPY_DEST,
  3104. None,
  3105. &mut readback,
  3106. )
  3107. .unwrap();
  3108. }
  3109. let readback = readback.unwrap();
  3110. // How the host lays the stencil plane (subresource 1) out in a buffer.
  3111. let mut plane = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
  3112. // SAFETY: a plain query writing one footprint.
  3113. unsafe {
  3114. host.device
  3115. .GetCopyableFootprints(&d, 1, 1, 0, Some(&mut plane), None, None, None);
  3116. }
  3117. let pattern_rows = D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
  3118. Offset: 0,
  3119. Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
  3120. Format: DXGI_FORMAT(60),
  3121. Width: 4,
  3122. Height: 4,
  3123. Depth: 1,
  3124. RowPitch: 256,
  3125. },
  3126. };
  3127. // A subresource of a texture; rows of a buffer.
  3128. let whole = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION {
  3129. // SAFETY: a borrowed pointer the location never releases.
  3130. pResource: unsafe { std::mem::transmute_copy(texture) },
  3131. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  3132. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  3133. SubresourceIndex: index,
  3134. },
  3135. };
  3136. let rows = |buffer: &ID3D12Resource, placed: D3D12_PLACED_SUBRESOURCE_FOOTPRINT| {
  3137. D3D12_TEXTURE_COPY_LOCATION {
  3138. // SAFETY: as above.
  3139. pResource: unsafe { std::mem::transmute_copy(buffer) },
  3140. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  3141. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  3142. PlacedFootprint: placed,
  3143. },
  3144. }
  3145. };
  3146. let (written, source, dest) = (
  3147. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  3148. D3D12_RESOURCE_STATE_COPY_SOURCE,
  3149. D3D12_RESOURCE_STATE_COPY_DEST,
  3150. );
  3151. let moved = crate::host::transition;
  3152. // The pattern into the twin, where a shader would write it.
  3153. let fill = host.new_list().unwrap();
  3154. // SAFETY: an open list and live resources.
  3155. unsafe {
  3156. let l = &fill.list;
  3157. l.ResourceBarrier(&[moved(twin, written, dest)]);
  3158. l.CopyTextureRegion(&whole(twin, 0), 0, 0, 0, &rows(&upload, pattern_rows), None);
  3159. l.ResourceBarrier(&[moved(twin, dest, written)]);
  3160. }
  3161. fill.close();
  3162. host.execute(&[&fill]);
  3163. // A list in which a shader writes the twin: closing it copies the
  3164. // twin into the stencil plane.
  3165. let list = host.new_list().unwrap();
  3166. assert!(list.twin_use(depth, true, true));
  3167. list.twins_written();
  3168. list.close();
  3169. host.execute(&[&list]);
  3170. // The stencil plane read back from the state the list left it in.
  3171. let state = host_copy(depth).unwrap().state.load(Relaxed);
  3172. let state = D3D12_RESOURCE_STATES(state as i32);
  3173. let back = host.new_list().unwrap();
  3174. // SAFETY: an open list and live resources; a whole subresource.
  3175. unsafe {
  3176. let l = &back.list;
  3177. l.ResourceBarrier(&[moved(host_depth, state, source)]);
  3178. let (to, from) = (rows(&readback, plane), whole(host_depth, 1));
  3179. l.CopyTextureRegion(&to, 0, 0, 0, &from, None);
  3180. l.ResourceBarrier(&[moved(host_depth, source, state)]);
  3181. }
  3182. back.close();
  3183. host.execute(&[&back]);
  3184. let mut mapped = std::ptr::null_mut();
  3185. // SAFETY: the copies finished (execute waits); the buffer is 4096 bytes.
  3186. let read = unsafe {
  3187. readback
  3188. .Map(
  3189. 0,
  3190. Some(&D3D12_RANGE {
  3191. Begin: 0,
  3192. End: 4096,
  3193. }),
  3194. Some(&mut mapped),
  3195. )
  3196. .unwrap();
  3197. std::slice::from_raw_parts(mapped.cast::<u8>(), 4096)
  3198. };
  3199. let pitch = plane.Footprint.RowPitch as usize;
  3200. for row in 0..4 {
  3201. let (at, from) = (row * pitch, row * 256);
  3202. assert_eq!(read[at..at + 4], pattern[from..from + 4], "row {row}");
  3203. }
  3204. }
  3205. /// The depth plane of a depth-stencil texture is drawn from the plane's
  3206. /// twin when the list that wrote the twin closes: class numbers are put
  3207. /// into the twin of a texture in the console's 16-bit depth-stencil
  3208. /// format, and draws with the depth test "equal" at the depth the
  3209. /// title's lighting computes for a class (the number times the float
  3210. /// nearest 1/65535) then cover the texels of that class and no other.
  3211. #[cfg(windows)]
  3212. #[test]
  3213. fn a_depth_planes_twin_is_drawn_into_the_plane() {
  3214. use std::sync::atomic::Ordering::Relaxed;
  3215. use windows::Win32::Foundation::RECT;
  3216. use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY;
  3217. use windows::Win32::Graphics::Direct3D12::*;
  3218. use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC};
  3219. use windows::core::s;
  3220. let Some(host) = crate::host::host() else {
  3221. return; // no host GPU here
  3222. };
  3223. let null = std::ptr::null();
  3224. const DEPTH_WRITE: u32 = 0x10;
  3225. let desc = ResourceDesc {
  3226. flags: 6,
  3227. ..texture(4, 4, 118, 1)
  3228. };
  3229. let mut depth = null;
  3230. assert_eq!(
  3231. create_committed(
  3232. null,
  3233. &PROPERTIES,
  3234. 0,
  3235. &desc,
  3236. DEPTH_WRITE,
  3237. null.cast(),
  3238. &RESOURCE_IIDS[0],
  3239. &mut depth
  3240. ),
  3241. S_OK
  3242. );
  3243. let host_depth = host_resource(depth).unwrap();
  3244. let Some(plane) = twin_plane_resource(depth) else {
  3245. return; // these twins are turned off
  3246. };
  3247. // SAFETY: live resources.
  3248. let (d, t) = unsafe { (host_depth.GetDesc(), plane.GetDesc()) };
  3249. // R24G8 typeless with depth, R16 typeless with unordered access.
  3250. assert_eq!((d.Format.0, d.Flags.0), (44, 2));
  3251. assert_eq!((t.Format.0, t.Flags.0), (53, 4));
  3252. // Four rows of four class numbers (16 bits each), 256 bytes apart
  3253. // as copies place them. 128 and 129 are the classes whose 24-bit
  3254. // depth lies nearest a half step.
  3255. const CLASSES: [u16; 16] = [
  3256. 8, 65, 128, 129, 65, 8, 129, 128, 0, 255, 65, 64, 129, 130, 8, 65,
  3257. ];
  3258. let mut pattern = vec![0u8; 1024];
  3259. for (i, class) in CLASSES.into_iter().enumerate() {
  3260. let at = i / 4 * 256 + i % 4 * 2;
  3261. pattern[at..at + 2].copy_from_slice(&class.to_le_bytes());
  3262. }
  3263. let (upload, data) = host.upload_buffer(1024).unwrap();
  3264. // SAFETY: the buffer's mapping, 1024 bytes.
  3265. unsafe { std::ptr::copy_nonoverlapping(pattern.as_ptr(), data, 1024) };
  3266. let buffer = |kind: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES| {
  3267. let heap = D3D12_HEAP_PROPERTIES {
  3268. Type: kind,
  3269. ..Default::default()
  3270. };
  3271. let desc = D3D12_RESOURCE_DESC {
  3272. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  3273. Width: 1024,
  3274. Height: 1,
  3275. DepthOrArraySize: 1,
  3276. MipLevels: 1,
  3277. SampleDesc: DXGI_SAMPLE_DESC {
  3278. Count: 1,
  3279. Quality: 0,
  3280. },
  3281. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  3282. ..Default::default()
  3283. };
  3284. let mut made: Option<ID3D12Resource> = None;
  3285. // SAFETY: plain creation of a buffer.
  3286. unsafe {
  3287. host.device
  3288. .CreateCommittedResource(
  3289. &heap,
  3290. D3D12_HEAP_FLAG_NONE,
  3291. &desc,
  3292. state,
  3293. None,
  3294. &mut made,
  3295. )
  3296. .unwrap();
  3297. }
  3298. made.unwrap()
  3299. };
  3300. let readback = buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST);
  3301. // The colour target the draws cover: 4x4, 8 bits a texel.
  3302. let target = {
  3303. let heap = D3D12_HEAP_PROPERTIES {
  3304. Type: D3D12_HEAP_TYPE_DEFAULT,
  3305. ..Default::default()
  3306. };
  3307. let desc = D3D12_RESOURCE_DESC {
  3308. Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  3309. Width: 4,
  3310. Height: 4,
  3311. DepthOrArraySize: 1,
  3312. MipLevels: 1,
  3313. Format: DXGI_FORMAT(61),
  3314. SampleDesc: DXGI_SAMPLE_DESC {
  3315. Count: 1,
  3316. Quality: 0,
  3317. },
  3318. Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET,
  3319. ..Default::default()
  3320. };
  3321. let mut made: Option<ID3D12Resource> = None;
  3322. // SAFETY: plain creation of a texture.
  3323. unsafe {
  3324. host.device
  3325. .CreateCommittedResource(
  3326. &heap,
  3327. D3D12_HEAP_FLAG_NONE,
  3328. &desc,
  3329. D3D12_RESOURCE_STATE_RENDER_TARGET,
  3330. None,
  3331. &mut made,
  3332. )
  3333. .unwrap();
  3334. }
  3335. made.unwrap()
  3336. };
  3337. let rows_of = |format: i32| D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
  3338. Offset: 0,
  3339. Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
  3340. Format: DXGI_FORMAT(format),
  3341. Width: 4,
  3342. Height: 4,
  3343. Depth: 1,
  3344. RowPitch: 256,
  3345. },
  3346. };
  3347. // A texture's one subresource; rows of a buffer.
  3348. let whole = |texture: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION {
  3349. // SAFETY: a borrowed pointer the location never releases.
  3350. pResource: unsafe { std::mem::transmute_copy(texture) },
  3351. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  3352. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  3353. SubresourceIndex: 0,
  3354. },
  3355. };
  3356. let rows = |buffer: &ID3D12Resource, placed: D3D12_PLACED_SUBRESOURCE_FOOTPRINT| {
  3357. D3D12_TEXTURE_COPY_LOCATION {
  3358. // SAFETY: as above.
  3359. pResource: unsafe { std::mem::transmute_copy(buffer) },
  3360. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  3361. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  3362. PlacedFootprint: placed,
  3363. },
  3364. }
  3365. };
  3366. let (written, source, dest, tested, drawn) = (
  3367. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  3368. D3D12_RESOURCE_STATE_COPY_SOURCE,
  3369. D3D12_RESOURCE_STATE_COPY_DEST,
  3370. D3D12_RESOURCE_STATE_DEPTH_WRITE,
  3371. D3D12_RESOURCE_STATE_RENDER_TARGET,
  3372. );
  3373. let moved = crate::host::transition;
  3374. // The class numbers into the twin, where a shader would write them.
  3375. let fill = host.new_list().unwrap();
  3376. // SAFETY: an open list and live resources.
  3377. unsafe {
  3378. let l = &fill.list;
  3379. l.ResourceBarrier(&[moved(plane, written, dest)]);
  3380. l.CopyTextureRegion(&whole(plane), 0, 0, 0, &rows(&upload, rows_of(53)), None);
  3381. l.ResourceBarrier(&[moved(plane, dest, written)]);
  3382. }
  3383. fill.close();
  3384. host.execute(&[&fill]);
  3385. // A list in which a shader writes the twins: closing it draws the
  3386. // depth plane's twin into the plane.
  3387. let list = host.new_list().unwrap();
  3388. assert!(list.twin_use(depth, true, true));
  3389. list.twins_written();
  3390. list.close();
  3391. host.execute(&[&list]);
  3392. // The draws: a triangle over the target at the depth of a class,
  3393. // as the title's lighting places its rectangles.
  3394. const SOURCE: &str = r#"
  3395. #define RS "RootConstants(num32BitConstants = 1, b0)"
  3396. cbuffer Drawn : register(b0) { uint number; };
  3397. [RootSignature(RS)]
  3398. float4 corner(uint i : SV_VertexID) : SV_Position {
  3399. float z = float(number) * asfloat(0x37800080);
  3400. return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, z, 1.0);
  3401. }
  3402. float4 lit() : SV_Target { return 1.0; }
  3403. "#;
  3404. let vs = crate::host::compile(SOURCE, s!("corner"), s!("vs_5_1")).unwrap();
  3405. let ps = crate::host::compile(SOURCE, s!("lit"), s!("ps_5_1")).unwrap();
  3406. let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
  3407. pShaderBytecode: bytes.as_ptr().cast(),
  3408. BytecodeLength: bytes.len(),
  3409. };
  3410. let mut blend = D3D12_BLEND_DESC::default();
  3411. blend.RenderTarget[0].RenderTargetWriteMask = 0xf;
  3412. let mut formats = [DXGI_FORMAT(0); 8];
  3413. formats[0] = DXGI_FORMAT(61);
  3414. // SAFETY: plain creation; the description points at live data.
  3415. let (signature, pipeline) = unsafe {
  3416. let signature: ID3D12RootSignature =
  3417. host.device.CreateRootSignature(0, &vs[..]).unwrap();
  3418. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  3419. pRootSignature: std::mem::transmute_copy(&signature),
  3420. VS: code(&vs[..]),
  3421. PS: code(&ps[..]),
  3422. BlendState: blend,
  3423. SampleMask: u32::MAX,
  3424. RasterizerState: D3D12_RASTERIZER_DESC {
  3425. FillMode: D3D12_FILL_MODE_SOLID,
  3426. CullMode: D3D12_CULL_MODE_NONE,
  3427. DepthClipEnable: true.into(),
  3428. ..Default::default()
  3429. },
  3430. // As the title's lighting: test "equal", nothing written.
  3431. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  3432. DepthEnable: true.into(),
  3433. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO,
  3434. DepthFunc: D3D12_COMPARISON_FUNC_EQUAL,
  3435. ..Default::default()
  3436. },
  3437. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  3438. NumRenderTargets: 1,
  3439. RTVFormats: formats,
  3440. DSVFormat: DXGI_FORMAT(45),
  3441. SampleDesc: DXGI_SAMPLE_DESC {
  3442. Count: 1,
  3443. Quality: 0,
  3444. },
  3445. ..Default::default()
  3446. };
  3447. let pipeline: ID3D12PipelineState =
  3448. host.device.CreateGraphicsPipelineState(&desc).unwrap();
  3449. (signature, pipeline)
  3450. };
  3451. let state = host_copy(depth).unwrap().state.load(Relaxed);
  3452. let state = D3D12_RESOURCE_STATES(state as i32);
  3453. let colour = host.rtv(Some(&target), None);
  3454. let depth_view = host.dsv(
  3455. host_depth,
  3456. Some(&D3D12_DEPTH_STENCIL_VIEW_DESC {
  3457. Format: DXGI_FORMAT(45),
  3458. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D,
  3459. ..Default::default()
  3460. }),
  3461. );
  3462. let back = host.new_list().unwrap();
  3463. // SAFETY: an open list and live resources and views.
  3464. unsafe {
  3465. let l = &back.list;
  3466. if state != tested {
  3467. l.ResourceBarrier(&[moved(host_depth, state, tested)]);
  3468. }
  3469. l.ClearRenderTargetView(colour, &[0.0; 4], None);
  3470. l.SetGraphicsRootSignature(&signature);
  3471. l.SetPipelineState(&pipeline);
  3472. l.OMSetRenderTargets(1, Some(&colour), false, Some(&depth_view));
  3473. l.RSSetViewports(&[D3D12_VIEWPORT {
  3474. TopLeftX: 0.0,
  3475. TopLeftY: 0.0,
  3476. Width: 4.0,
  3477. Height: 4.0,
  3478. MinDepth: 0.0,
  3479. MaxDepth: 1.0,
  3480. }]);
  3481. l.RSSetScissorRects(&[RECT {
  3482. left: 0,
  3483. top: 0,
  3484. right: 4,
  3485. bottom: 4,
  3486. }]);
  3487. l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(4));
  3488. // Classes 65 and 129 are drawn; the others are not.
  3489. for class in [65u32, 129] {
  3490. l.SetGraphicsRoot32BitConstant(0, class, 0);
  3491. l.DrawInstanced(3, 1, 0, 0);
  3492. }
  3493. l.ResourceBarrier(&[moved(&target, drawn, source)]);
  3494. let (to, from) = (rows(&readback, rows_of(61)), whole(&target));
  3495. l.CopyTextureRegion(&to, 0, 0, 0, &from, None);
  3496. }
  3497. back.close();
  3498. host.execute(&[&back]);
  3499. let mut mapped = std::ptr::null_mut();
  3500. // SAFETY: the copy finished (execute waits); the buffer is 1024 bytes.
  3501. let read = unsafe {
  3502. readback
  3503. .Map(
  3504. 0,
  3505. Some(&D3D12_RANGE {
  3506. Begin: 0,
  3507. End: 1024,
  3508. }),
  3509. Some(&mut mapped),
  3510. )
  3511. .unwrap();
  3512. std::slice::from_raw_parts(mapped.cast::<u8>(), 1024)
  3513. };
  3514. for (i, class) in CLASSES.into_iter().enumerate() {
  3515. let covered = read[i / 4 * 256 + i % 4] != 0;
  3516. let drawn = matches!(class, 65 | 129);
  3517. assert_eq!(covered, drawn, "texel {i}, class {class}");
  3518. }
  3519. }
  3520. #[test]
  3521. fn committed_and_placed_resources_map_at_their_gpu_address() {
  3522. let null = std::ptr::null();
  3523. let mut committed = null;
  3524. let hr = create_committed(
  3525. null,
  3526. &PROPERTIES,
  3527. 0,
  3528. &buffer(256),
  3529. 0,
  3530. null.cast(),
  3531. &RESOURCE_IIDS[0],
  3532. &mut committed,
  3533. );
  3534. assert_eq!(hr, S_OK);
  3535. let mut data = std::ptr::null_mut();
  3536. assert_eq!(
  3537. slot::<Map>(committed, 0x40)(committed, 0, null.cast(), &mut data),
  3538. S_OK
  3539. );
  3540. assert_eq!(slot::<Address>(committed, 0x58)(committed), data as u64);
  3541. // SAFETY: the buffer is at least 256 zeroed bytes.
  3542. assert_eq!(unsafe { *data.add(255) }, 0);
  3543. assert_eq!(slot::<Release>(committed, 0x10)(committed), 0);
  3544. let heap = heap(4 * KIB_64);
  3545. let place = |offset, desc: &ResourceDesc, out: &mut This| {
  3546. create_placed(
  3547. null,
  3548. heap,
  3549. offset,
  3550. desc,
  3551. 0,
  3552. null.cast(),
  3553. &RESOURCE_IIDS[0],
  3554. out,
  3555. )
  3556. };
  3557. let mut placed = null;
  3558. assert_eq!(place(KIB_64, &buffer(KIB_64), &mut placed), S_OK);
  3559. // SAFETY: a heap we made.
  3560. let base = unsafe { (*heap.cast::<Heap>()).memory.ptr.as_ptr() } as u64;
  3561. assert_eq!(slot::<Address>(placed, 0x58)(placed), base + KIB_64);
  3562. let mut other = null;
  3563. assert_eq!(
  3564. place(4 * KIB_64, &buffer(1), &mut other),
  3565. E_INVALIDARG,
  3566. "past the end"
  3567. );
  3568. assert_eq!(
  3569. place(100, &buffer(1), &mut other),
  3570. E_INVALIDARG,
  3571. "misaligned"
  3572. );
  3573. // The resource keeps the heap alive.
  3574. assert_eq!(slot::<Release>(heap, 0x10)(heap), 1);
  3575. assert_eq!(slot::<Release>(placed, 0x10)(placed), 0);
  3576. }
  3577. #[test]
  3578. fn texture_floor_scales_with_vram_budget() {
  3579. const GIB: u64 = 1 << 30;
  3580. assert_eq!(texture_floor_bytes(None), 2 * GIB);
  3581. assert_eq!(texture_floor_bytes(Some(4 * GIB)), GIB);
  3582. assert_eq!(texture_floor_bytes(Some(6 * GIB)), 6 * GIB / 4);
  3583. assert_eq!(texture_floor_bytes(Some(8 * GIB)), 2 * GIB);
  3584. assert_eq!(texture_floor_bytes(Some(12 * GIB)), 2 * GIB);
  3585. assert_eq!(texture_floor_bytes(Some(24 * GIB)), 2 * GIB);
  3586. assert_eq!(texture_floor_bytes(Some(32 * GIB)), 2 * GIB);
  3587. }
  3588. }