resource.rs 141 KB

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