resource.rs 170 KB

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