resource.rs 172 KB

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