host.rs 197 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491
  1. //! Host descriptor heaps behind the title's shader-visible heaps (decision
  2. //! 0007, step 3). Translated shaders index the heaps directly at the
  3. //! title's descriptor positions, so each host heap keeps the title heap's
  4. //! order: slot `i` is made from what the title wrote at slot `i`, when it
  5. //! writes it (view creation and descriptor copies) and again when a draw
  6. //! reads it through a table and finds the slot changed.
  7. use std::sync::Mutex;
  8. use windows::Win32::Graphics::Direct3D12::*;
  9. use windows::Win32::Graphics::Dxgi::Common::*;
  10. use super::{VIEW_TAG, View, view_at};
  11. use crate::host::host;
  12. pub(crate) struct HostHeap {
  13. pub(crate) heap: ID3D12DescriptorHeap,
  14. cpu: usize,
  15. step: u32,
  16. /// Slots mirroring the title's; view heaps have `dynamic` more.
  17. count: u32,
  18. /// Dynamic slots past `count`: [`DYNAMIC`] in view heaps, none in
  19. /// sampler heaps. (Upstream falls back to 2^16 on a capped host heap;
  20. /// ours keeps 2^18 there: 2^16 and 2^17 both ran out in this title.)
  21. dynamic: u32,
  22. sampler: bool,
  23. /// Where the raw twins of the title's slots start
  24. /// (`victory_shader::emit::raw_views`; 0: there are none), and which of
  25. /// them are not null.
  26. raw: u32,
  27. twins: Vec<std::sync::atomic::AtomicBool>,
  28. /// The record (view index and generation) each slot was last made from.
  29. made: Mutex<Vec<u64>>,
  30. /// The records of the title's heap as the pass over records copied in
  31. /// as bytes last saw them ([`HostHeap::copied_changes`]). Made on first
  32. /// use.
  33. copied: Mutex<Vec<u8>>,
  34. /// New ones of them that wait for a draw ([`HostHeap::copied_wait`]),
  35. /// by the frame they were found in.
  36. waiting: Mutex<std::collections::VecDeque<(u64, Vec<u32>)>>,
  37. /// The slots made from a texture whose memory was found away, with what
  38. /// they were made from and when that was
  39. /// ([`HostHeap::texture_slot_gone`]).
  40. away: Mutex<std::collections::HashMap<u32, (u64, u64)>>,
  41. /// The host resource each slot views, held while the slot does: shaders
  42. /// index heaps directly, so a slot the title has not rewritten since it
  43. /// released the resource may still be read, and a freed host resource
  44. /// read there is a GPU page fault (the console reads stale memory).
  45. kept: Mutex<Vec<Option<ID3D12Resource>>>,
  46. /// Where the search for free dynamic slots starts, and which are taken
  47. /// (by lists not yet reset).
  48. next: Mutex<(u32, Vec<bool>)>,
  49. /// How many dynamic slots are free (changed under `next`'s lock): with
  50. /// fewer than a table needs, the search is not made. Once the world
  51. /// had taken them all, every later table of the frame searched every
  52. /// slot before it was refused.
  53. free: std::sync::atomic::AtomicU32,
  54. /// The shortest table that found no run of free slots since slots were
  55. /// last given back (changed under `next`'s lock; `u32::MAX`: none).
  56. /// Until something is given back the free runs only shrink, so a table
  57. /// of that length or longer is refused without the search. Enough
  58. /// slots were free, but in pieces, and every such table walked the
  59. /// whole ring before it was refused: 0.33 ms each with 131,072 slots,
  60. /// 1.0 s of the recording threads in a frame that refused 3,143 (run
  61. /// 45), under the lock all of them need. (A free run that lies across
  62. /// the place the search starts from is seen by neither.)
  63. too_long: std::sync::atomic::AtomicU32,
  64. /// View heaps: the bytes per element of the buffer view at each title
  65. /// slot, for shaders that pick a buffer by an index they compute
  66. /// (`victory_shader::emit::SLOT_STRIDES`): an upload buffer of
  67. /// `SLOT_STRIDES_COUNT` dwords, its GPU address and its mapping.
  68. strides: Option<(ID3D12Resource, u64, usize)>,
  69. /// Title slots holding buffer views. Such a view gets its host slot
  70. /// (and its memory a host copy) only when something reads it: a draw
  71. /// through a table, or [`HostHeap::buffer_slots`] for shaders that pick
  72. /// buffers from the whole heap.
  73. buffers: Mutex<std::collections::BTreeSet<u32>>,
  74. /// Of those and of the slots that left the set: the ones written since
  75. /// [`HostHeap::buffer_changes`] last took them.
  76. changed: Mutex<std::collections::HashSet<u32>>,
  77. /// Title slots holding a view of a texture the title may fill itself (a
  78. /// placed texture, a texture object), with the frame from which they
  79. /// are due: such a texture is uploaded when a draw reads it through a
  80. /// table; one a shader picks by a computed index is brought up to date
  81. /// from here ([`HostHeap::texture_slots_due`]).
  82. textures: Mutex<TextureQueue>,
  83. /// Per title slot, the frame (plus one; 0: never) in which a draw last
  84. /// read it through a table, or made a table it lies in (with
  85. /// [`TABLED_READ`] set if the draw read it). The draw that
  86. /// reads such a slot brings its texture up to date itself and the slot
  87. /// then leaves `textures`; a write of a slot that was a table's within
  88. /// the last [`TABLED_FRAMES`] frames is due only [`TABLED_GRACE`]
  89. /// frames later, by when its draw has read it. A title that builds a
  90. /// table per draw writes thousands of texture views a frame into slots
  91. /// only tables read (the title: some 2,500 a frame in its
  92. /// opening cutscene, a few hundred textures over and over), and every
  93. /// one of them stood in the queue of textures picked by index, ahead
  94. /// of or behind the ones shaders do pick by index.
  95. tabled: Vec<std::sync::atomic::AtomicU32>,
  96. /// The title memory each placed texture view of this heap describes,
  97. /// by slot and by address ([`Spans`]): which slots a newer view of
  98. /// other memory there makes stale, and which to look at again when the
  99. /// runtime maps, unmaps or writes memory ([`remapped`]).
  100. placed: std::sync::Arc<Mutex<Spans>>,
  101. }
  102. /// The spans of every view heap made ([`HostHeap::placed`]), for the
  103. /// texture code, which has no heap at hand ([`next_start`],
  104. /// [`first_viewed`]).
  105. static PLACED_SPANS: Mutex<Vec<std::sync::Weak<Mutex<Spans>>>> = Mutex::new(Vec::new());
  106. /// Where the next texture placed inside `[start, end)` starts, past the
  107. /// first bytes of the one at `start` ([`HEAD`]): what is there of the
  108. /// texture at `start` ends there, whatever its full size. `None`: no view
  109. /// in a slot shaders pick by index describes memory in that range.
  110. pub(crate) fn next_start(start: u64, end: u64) -> Option<u64> {
  111. let heaps = PLACED_SPANS.lock().unwrap_or_else(|e| e.into_inner());
  112. heaps
  113. .iter()
  114. .filter_map(std::sync::Weak::upgrade)
  115. .filter_map(|spans| spans.lock().unwrap_or_else(|e| e.into_inner()).next_start(start, end))
  116. .min()
  117. }
  118. /// The lowest level that a view of the placed texture at `start` shows,
  119. /// over the slots shaders pick by index that hold one now. The title
  120. /// views a texture from the first level it holds. `None`: no such slot.
  121. pub(crate) fn first_viewed(start: u64) -> Option<u32> {
  122. let heaps = PLACED_SPANS.lock().unwrap_or_else(|e| e.into_inner());
  123. heaps
  124. .iter()
  125. .filter_map(std::sync::Weak::upgrade)
  126. .filter_map(|spans| spans.lock().unwrap_or_else(|e| e.into_inner()).first_viewed(start))
  127. .min()
  128. }
  129. /// Levels on demand (`crate::tiles`): where the placed textures start
  130. /// whose first level with memory changed since a texture pass last took
  131. /// them ([`HostHeap::texture_views_remade`]).
  132. static RESHOWN: Mutex<Vec<u64>> = Mutex::new(Vec::new());
  133. /// The first level with memory of the placed texture at `start` changed:
  134. /// its slots are made again at the next texture pass.
  135. pub(crate) fn levels_changed(start: u64) {
  136. RESHOWN.lock().unwrap_or_else(|e| e.into_inner()).push(start);
  137. }
  138. /// [`levels_changed`] once the submissions begun so far (that of the list
  139. /// whose step calls this among them) have run.
  140. pub(crate) fn levels_changed_after(start: u64) {
  141. let after = crate::host::submissions().0;
  142. RESHOWN_AFTER.lock().unwrap_or_else(|e| e.into_inner()).push((after, start));
  143. }
  144. static RESHOWN_AFTER: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
  145. /// Slots that show a placed texture from another level than the title's view
  146. /// in them says now, and are made from that view when the upload it needs
  147. /// has run ([`HostHeap::texture_slot_flip`]).
  148. struct Flip {
  149. /// The submission to wait for.
  150. after: u64,
  151. /// The heap (its address), the slot, where its record is and which
  152. /// record it was.
  153. heap: usize,
  154. index: u32,
  155. handle: u64,
  156. key: u64,
  157. }
  158. static FLIPS: Mutex<Vec<Flip>> = Mutex::new(Vec::new());
  159. /// Since the start: slots made from their new view after its upload had run,
  160. /// and those the title had written again by then.
  161. pub(crate) static FLIPPED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  162. /// The key of the record at `handle`, a view's descriptor slot; 0: none.
  163. fn record_key(handle: u64) -> u64 {
  164. // SAFETY: the handle is a descriptor slot in title memory.
  165. let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() };
  166. if tag == VIEW_TAG { u64::from(generation) << 32 | u64::from(i) } else { 0 }
  167. }
  168. /// Levels on demand (`crate::tiles`): where the placed textures start
  169. /// whose last upload left a held level without tiles (the card had no
  170. /// room, or no heap could be had), and when (`crate::host::moment`). A
  171. /// texture pass makes their slots due again once the card has room
  172. /// ([`HostHeap::texture_slots_waiting`]).
  173. static WAITING: Mutex<std::collections::BTreeMap<u64, u64>> = Mutex::new(std::collections::BTreeMap::new());
  174. /// The last upload of the placed texture at `start` left a held level
  175. /// without tiles. A texture picked by index is uploaded once and then
  176. /// only when its memory is found changed, and its staging buffer goes
  177. /// with the upload: without this the level stayed empty (the texture
  178. /// blurred, or black if no level had tiles) for as long as the title left
  179. /// its memory alone, where a texture refused for want of room is tried
  180. /// again.
  181. pub(crate) fn levels_waiting(start: u64) {
  182. WAITING.lock().unwrap_or_else(|e| e.into_inner()).insert(start, crate::host::moment());
  183. }
  184. /// Placed textures (by the start of their memory) filled while the runtime
  185. /// was remapping with less than was mapped of them
  186. /// (`crate::texture::fill_unlocked`), whose slots the next texture pass
  187. /// makes due again; and how often in a row that was, which ends it: memory
  188. /// that is shown and cannot be read would be uploaded again every frame.
  189. static SHORT: Mutex<(std::collections::BTreeSet<u64>, std::collections::BTreeMap<u64, u32>)> =
  190. Mutex::new((std::collections::BTreeSet::new(), std::collections::BTreeMap::new()));
  191. /// Fillings in a row of one texture that got less than was mapped, after
  192. /// which its slots wait for the next notice of its memory.
  193. const SHORT_IN_A_ROW: u32 = 8;
  194. /// The placed texture at `start` was filled with less than was mapped.
  195. pub(crate) fn read_short(start: u64) {
  196. let mut short = SHORT.lock().unwrap_or_else(|e| e.into_inner());
  197. let times = short.1.entry(start).or_insert(0);
  198. *times += 1;
  199. if *times <= SHORT_IN_A_ROW {
  200. short.0.insert(start);
  201. }
  202. }
  203. /// The placed texture at `start` was filled with all that was mapped.
  204. pub(crate) fn read_all(start: u64) {
  205. let mut short = SHORT.lock().unwrap_or_else(|e| e.into_inner());
  206. if !short.1.is_empty() {
  207. short.1.remove(&start);
  208. }
  209. }
  210. /// Title memory by the placed texture views that describe it: per span of
  211. /// memory (its start, its end at full size) the title slots holding a
  212. /// view of a texture that takes exactly that span. A console title need
  213. /// not clear a descriptor when it streams a texture out, so a newer view
  214. /// that cannot be there together with an older one is all that says the
  215. /// older one is stale ([`Rule`] says when that is). Views of one span with
  216. /// different descriptions (the formats of one family, say) are one
  217. /// texture's.
  218. ///
  219. /// Spans may overlap: a texture's smallest levels lie at the start of its
  220. /// memory, and a title that holds only those puts the next texture where
  221. /// the larger ones would be (the title: three 512x256 textures
  222. /// of 0x2c000 bytes each whose starts are 0x2000 and 0x4000 apart, all
  223. /// three read by the same frame's draws, run 188). What is there of a
  224. /// texture ends where the next one starts.
  225. /// No host heap is needed, so it is tested without one.
  226. #[derive(Default)]
  227. pub(crate) struct Spans {
  228. /// When a newer view makes an older one stale.
  229. rule: Rule,
  230. by_start: std::collections::BTreeMap<u64, (u64, std::collections::BTreeSet<u32>)>,
  231. by_slot: std::collections::HashMap<u32, u64>,
  232. /// The level each slot's view starts at, and where what it is read from
  233. /// ends ([`Spans::shows`]).
  234. first: std::collections::HashMap<u32, (u32, u64)>,
  235. /// The bytes a placed texture takes, by resource description: worked
  236. /// out once for each (a title writes the views of a few thousand
  237. /// descriptions, thousands of times a frame).
  238. sizes: std::collections::HashMap<[u32; 14], Option<u64>>,
  239. }
  240. /// When a view the title writes makes an older view of other memory stale.
  241. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
  242. pub(crate) enum Rule {
  243. /// When it starts where the older one starts: at the same address
  244. /// with another length, or within the older one's first [`HEAD`]
  245. /// bytes (or the older within its own). No two textures share the
  246. /// block of their smallest levels. A view that only reaches into the
  247. /// address range of an older texture's larger levels says nothing.
  248. #[default]
  249. Start,
  250. /// Whenever their spans at full size overlap (the rule until run
  251. /// 188, where it made null the slots of textures packed as above:
  252. /// each view written took its neighbours out of the queue and off the
  253. /// card, for good). `VICTORY_STALE_TEXTURES=overlap`.
  254. Overlap,
  255. /// Never; a view that would be stale under [`Rule::Overlap`] is left
  256. /// out of the spans instead. `VICTORY_STALE_TEXTURES=0`, as before.
  257. Never,
  258. }
  259. /// The first bytes of a placed texture that are its own under
  260. /// [`Rule::Start`]: the 4 KiB block its smallest levels share. (Of 129
  261. /// pairs of overlapping neighbours in the listings of runs 188 and 189,
  262. /// none starts closer than 0x2000 to the one before it.)
  263. const HEAD: u64 = 4096;
  264. impl Spans {
  265. /// The bytes of title memory a placed texture with the resource
  266. /// description `desc` takes (`crate::resource::placed_bytes`).
  267. fn bytes(&mut self, desc: &[u32; 14]) -> Option<u64> {
  268. if let Some(&known) = self.sizes.get(desc) {
  269. return known;
  270. }
  271. let bytes = crate::resource::placed_bytes(desc);
  272. self.sizes.insert(*desc, bytes);
  273. bytes
  274. }
  275. /// The starts of the spans that overlap `[start, end)`, each taken to
  276. /// end where the next one starts: the last span that starts before
  277. /// `start`, if it reaches past it at full size, and every span that
  278. /// starts inside.
  279. fn overlapping(&self, start: u64, end: u64) -> Vec<u64> {
  280. let before = self
  281. .by_start
  282. .range(..start)
  283. .next_back()
  284. .filter(|(_, span)| span.0 > start)
  285. .map(|(at, _)| *at);
  286. before.into_iter().chain(self.by_start.range(start..end).map(|(at, _)| *at)).collect()
  287. }
  288. /// Slot `index` holds a view of a texture in `[start, end)`. `newer`:
  289. /// the title wrote it now, so the slots whose views cannot be there
  290. /// with it ([`Rule`]) are stale: they are returned, and forgotten.
  291. /// Otherwise (a draw made the slot from what it held), and under
  292. /// [`Rule::Never`], a view that clashes with other spans is left out.
  293. fn note(&mut self, index: u32, start: u64, end: u64, newer: bool) -> Vec<u32> {
  294. let same = |span: Option<&(u64, std::collections::BTreeSet<u32>)>| span.is_some_and(|s| s.0 == end);
  295. if self.by_slot.get(&index) == Some(&start) && same(self.by_start.get(&start)) {
  296. return Vec::new();
  297. }
  298. self.forget(index);
  299. if end <= start {
  300. return Vec::new();
  301. }
  302. let rule = self.rule;
  303. // The spans the view cannot be there with.
  304. let clashing: Vec<u64> = match rule {
  305. Rule::Start => self
  306. .by_start
  307. .range(start.saturating_sub(HEAD - 1)..start.saturating_add(HEAD))
  308. .map(|(at, _)| *at)
  309. .collect(),
  310. Rule::Overlap | Rule::Never => self.overlapping(start, end),
  311. };
  312. let mut stale = Vec::new();
  313. for at in clashing {
  314. if at == start && same(self.by_start.get(&at)) {
  315. continue;
  316. }
  317. if !newer || rule == Rule::Never {
  318. return stale;
  319. }
  320. if let Some((old_end, slots)) = self.by_start.remove(&at) {
  321. // The first of them are said with both spans, to tell a
  322. // replacement from a neighbour in one launch's log.
  323. static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  324. if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 48 {
  325. tracing::info!(
  326. slot = index,
  327. start = format_args!("{start:#x}"),
  328. end = format_args!("{end:#x}"),
  329. stale_start = format_args!("{at:#x}"),
  330. stale_end = format_args!("{old_end:#x}"),
  331. stale_slots = slots.len(),
  332. rule = ?rule,
  333. "a placed texture view makes older views of other memory stale"
  334. );
  335. }
  336. for slot in slots {
  337. self.by_slot.remove(&slot);
  338. stale.push(slot);
  339. }
  340. }
  341. }
  342. self.by_start.entry(start).or_insert_with(|| (end, Default::default())).1.insert(index);
  343. self.by_slot.insert(index, start);
  344. stale
  345. }
  346. /// The view in slot `index` starts at level `first` of its texture; the
  347. /// memory of that and the smaller levels ends at `end`.
  348. fn shows(&mut self, index: u32, first: u32, end: u64) {
  349. self.first.insert(index, (first, end));
  350. }
  351. /// Whether slot `index`'s view is read from memory at or past `start`.
  352. fn reaches(&self, index: u32, start: u64) -> bool {
  353. self.first.get(&index).is_none_or(|&(_, end)| end > start)
  354. }
  355. /// The lowest level a view of the texture at `start` starts at.
  356. fn first_viewed(&self, start: u64) -> Option<u32> {
  357. self.by_start.get(&start)?.1.iter().filter_map(|slot| self.first.get(slot)).map(|&(first, _)| first).min()
  358. }
  359. /// The first span that starts inside `[start, end)` past the first
  360. /// [`HEAD`] bytes of it.
  361. fn next_start(&self, start: u64, end: u64) -> Option<u64> {
  362. self.by_start.range(start.saturating_add(HEAD)..end).next().map(|(at, _)| *at)
  363. }
  364. /// The slots that hold a view of the texture at `start`.
  365. fn slots_at(&self, start: u64) -> Vec<u32> {
  366. self.by_start.get(&start).map(|span| span.1.iter().copied().collect()).unwrap_or_default()
  367. }
  368. /// Slot `index` holds no placed texture view any more.
  369. fn forget(&mut self, index: u32) {
  370. self.first.remove(&index);
  371. let Some(start) = self.by_slot.remove(&index) else {
  372. return;
  373. };
  374. if let Some(span) = self.by_start.get_mut(&start) {
  375. span.1.remove(&index);
  376. if span.1.is_empty() {
  377. self.by_start.remove(&start);
  378. }
  379. }
  380. }
  381. /// The slots whose texture's memory overlaps `[start, end)`.
  382. fn slots_in(&self, start: u64, end: u64) -> Vec<u32> {
  383. self.overlapping(start, end)
  384. .iter()
  385. .filter_map(|at| self.by_start.get(at))
  386. .flat_map(|span| span.1.iter().copied())
  387. .filter(|&slot| self.reaches(slot, start))
  388. .collect()
  389. }
  390. /// The slots of the textures that hold bytes of `[start, end)`, for a
  391. /// write there: as [`Spans::slots_in`], but when a texture starts at
  392. /// `start` itself the one before it is left out (it ends where that
  393. /// one starts, and a request that fills a texture begins at its first
  394. /// byte: `slots_in` would name its neighbour with every such write).
  395. fn slots_holding(&self, start: u64, end: u64) -> Vec<u32> {
  396. if end <= start {
  397. return Vec::new();
  398. }
  399. let before = if self.by_start.contains_key(&start) {
  400. None
  401. } else {
  402. self.by_start.range(..start).next_back().filter(|(_, span)| span.0 > start).map(|(_, span)| span)
  403. };
  404. before
  405. .into_iter()
  406. .chain(self.by_start.range(start..end).map(|(_, span)| span))
  407. .flat_map(|span| span.1.iter().copied())
  408. .filter(|&slot| self.reaches(slot, start))
  409. .collect()
  410. }
  411. }
  412. /// Title memory written behind the guards' back whose bytes are there
  413. /// (DirectStorage's reads into physical pages, at the addresses the title
  414. /// has them mapped; `crate::watch::title_memory_written`), since a texture
  415. /// pass last took the ranges ([`page_written`]). Kept apart from
  416. /// [`REMAPPED`] so that what such writes do is counted by itself.
  417. static PAGE_WRITTEN: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
  418. /// Since the start: such ranges kept for a pass; ranges dropped because no
  419. /// pass took them; slots of placed textures that held bytes of them when a
  420. /// pass took them; of those, the slots whose texture had been uploaded
  421. /// before the write (out of the queue, or in it after an upload): they are
  422. /// the ones that kept the bytes from before, and the ones made due when
  423. /// `VICTORY_PAGE_WRITES` asks for it.
  424. pub(crate) static PAGE_WRITES: [std::sync::atomic::AtomicU64; 4] =
  425. [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  426. /// Frames from the pass that takes a written range to the look at its
  427. /// slots: the levels of one texture arrive in a few requests, and a look
  428. /// two frames on takes those of the next frame with it.
  429. const PAGE_WRITE_AFTER: u64 = 2;
  430. /// The bytes of a write the guards do not see are in title memory `[at,
  431. /// at + len)`: the placed textures there changed with no descriptor
  432. /// written and nothing mapped. Kept for the next texture pass
  433. /// ([`HostHeap::texture_slots_page_written`]), as [`remapped`] keeps its
  434. /// ranges; locks one mutex and calls nothing.
  435. pub(crate) fn page_written(at: usize, len: usize) {
  436. use std::sync::atomic::Ordering::Relaxed;
  437. /// Ranges kept until a pass takes them.
  438. const MOST: usize = 1 << 15;
  439. let (start, end) = (at as u64, at.saturating_add(len) as u64);
  440. if end <= SPANNED[0].load(Relaxed) || start >= SPANNED[1].load(Relaxed) {
  441. return;
  442. }
  443. let mut ranges = PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
  444. PAGE_WRITES[0].fetch_add(1, Relaxed);
  445. if let Some(last) = ranges.last_mut()
  446. && last.1 == start
  447. {
  448. last.1 = end;
  449. return;
  450. }
  451. if ranges.len() >= MOST {
  452. PAGE_WRITES[1].fetch_add(ranges.len() as u64, Relaxed);
  453. ranges.clear();
  454. }
  455. ranges.push((start, end));
  456. }
  457. /// Title memory the runtime mapped, unmapped or is about to write since a
  458. /// texture pass last took the ranges ([`remapped`]).
  459. static REMAPPED: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
  460. /// The lowest start and the highest end of any span of [`Spans`] so far
  461. /// (the start is `u64::MAX` until there is one): what the runtime does to
  462. /// memory outside is none of the texture pass's business.
  463. static SPANNED: [std::sync::atomic::AtomicU64; 2] = [
  464. std::sync::atomic::AtomicU64::new(u64::MAX),
  465. std::sync::atomic::AtomicU64::new(0),
  466. ];
  467. /// Since the start: slots whose view a newer view of other memory there
  468. /// made stale; ranges of memory noted as mapped, unmapped or written;
  469. /// ranges dropped because no pass took them; slots made due by such
  470. /// ranges; and made slots whose memory was found unmapped (made null).
  471. pub(crate) static STALE: [std::sync::atomic::AtomicU64; 5] =
  472. [const { std::sync::atomic::AtomicU64::new(0) }; 5];
  473. /// When a view the title writes makes older views of other memory stale
  474. /// ([`Rule`]): where it starts in the block of their smallest levels, by
  475. /// default; `VICTORY_STALE_TEXTURES=0`: never, as before;
  476. /// `VICTORY_STALE_TEXTURES=overlap`: wherever their spans overlap, the rule
  477. /// until run 188.
  478. fn stale_rule() -> Rule {
  479. static RULE: std::sync::OnceLock<Rule> = std::sync::OnceLock::new();
  480. *RULE.get_or_init(|| match std::env::var("VICTORY_STALE_TEXTURES").as_deref() {
  481. Ok("0") => Rule::Never,
  482. Ok("overlap") => Rule::Overlap,
  483. _ => Rule::Start,
  484. })
  485. }
  486. /// The runtime mapped or unmapped title memory `[at, at + len)`, or is
  487. /// about to write it through the kernel (`crate::watch`): the placed
  488. /// textures there may have arrived, gone, or changed with no descriptor
  489. /// written. The range is kept for the next texture pass
  490. /// ([`HostHeap::texture_slots_remapped`]). Called with the runtime's own
  491. /// locks held: this locks one mutex of its own and calls nothing.
  492. pub(crate) fn remapped(at: usize, len: usize) {
  493. use std::sync::atomic::Ordering::Relaxed;
  494. /// Ranges kept until a pass takes them.
  495. const MOST: usize = 1 << 15;
  496. let (start, end) = (at as u64, at.saturating_add(len) as u64);
  497. if end <= SPANNED[0].load(Relaxed) || start >= SPANNED[1].load(Relaxed) {
  498. return;
  499. }
  500. let mut ranges = REMAPPED.lock().unwrap_or_else(|e| e.into_inner());
  501. STALE[1].fetch_add(1, Relaxed);
  502. // Pages are mapped one after the other.
  503. if let Some(last) = ranges.last_mut()
  504. && last.1 == start
  505. {
  506. last.1 = end;
  507. return;
  508. }
  509. if ranges.len() >= MOST {
  510. // No pass runs (no shader that picks textures by index is bound):
  511. // the slots there are looked at when they are due, as before.
  512. STALE[2].fetch_add(ranges.len() as u64, Relaxed);
  513. ranges.clear();
  514. }
  515. ranges.push((start, end));
  516. }
  517. /// Frames for which a slot a draw read through a table counts as a table's
  518. /// slot ([`HostHeap::tabled`]).
  519. const TABLED_FRAMES: u64 = 240;
  520. /// Frames a write of a table's slot waits in the queue for the draw that
  521. /// reads it, before the slot is taken for one shaders pick by index.
  522. /// Frames as `crate::frame::current` counts them: in its opening cutscene
  523. /// The title begins two or three of them per frame it presents
  524. /// (435 begun in the 353 s of run 52's, for some 140 presented).
  525. const TABLED_GRACE: u64 = 8;
  526. /// Frames for which a record copied into a slot a draw read through a
  527. /// table is left to such a draw ([`HostHeap::copied_tabled`]).
  528. const COPIED_FRAMES: u32 = 8;
  529. /// Frames a record copied into any other slot waits for one, before it is
  530. /// taken for one shaders pick by index ([`HostHeap::copied_wait`]).
  531. const COPIED_GRACE: u64 = 4;
  532. /// In [`HostHeap::tabled`]: a draw read the slot in that frame.
  533. const TABLED_READ: u32 = 1 << 31;
  534. /// Since the start: writes of texture views into slots that count as a
  535. /// table's (due later), and slots that left the queue because a draw read
  536. /// them through a table.
  537. pub(crate) static TABLED_WRITES: [std::sync::atomic::AtomicU64; 2] =
  538. [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  539. /// Whether slots draws read through tables leave the queue of textures
  540. /// picked by index; `VICTORY_TABLED_TEXTURES=1` keeps them in it as
  541. /// before.
  542. fn tabled_out() -> bool {
  543. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  544. *ON.get_or_init(|| std::env::var_os("VICTORY_TABLED_TEXTURES").is_none_or(|v| v != "1"))
  545. }
  546. /// What the queue of textures picked by index knows of a title slot.
  547. #[derive(Clone, Copy, Debug, PartialEq, Eq)]
  548. struct Waiting {
  549. /// The frame from which the slot is due.
  550. due: u64,
  551. /// The frame it was written in.
  552. written: u64,
  553. /// Which write of the queue put it here: the pass hands it back with
  554. /// what it did, so a slot written again meanwhile stays as written.
  555. write: u64,
  556. /// Looks in a row that found nothing to upload (its memory not mapped,
  557. /// or no more of it than at the last upload).
  558. looks: u8,
  559. /// Bytes of its memory that were mapped when it was last uploaded
  560. /// without all of it there; 0: not uploaded yet.
  561. mapped: u64,
  562. /// For a slot uploaded whole and looked at again
  563. /// ([`TextureQueue::recheck`]): where its memory is (address, bytes),
  564. /// the fingerprint it had at the upload, how many looks found it
  565. /// unchanged, and the frame of the upload. A fingerprint of 0: none.
  566. checked: (u64, u64, u64, u8, u64),
  567. }
  568. /// The queue of title slots whose texture view waits to be brought up to
  569. /// date for shaders that pick textures by index: which are due, and in
  570. /// which order (no host heap needed, so it is tested without one).
  571. #[derive(Default)]
  572. pub(crate) struct TextureQueue {
  573. slots: std::collections::BTreeMap<u32, Waiting>,
  574. writes: u64,
  575. /// Slots held back because the card had no room for the host copy
  576. /// they need ([`TextureQueue::hold`]), each with the write it was
  577. /// held as.
  578. held: std::collections::BTreeMap<u32, u64>,
  579. }
  580. impl TextureQueue {
  581. /// A texture view was written into slot `index` in `frame`, due from
  582. /// frame `due`. `seen`: it was not written, a draw or the pass made
  583. /// the host slot from a view the queue may hold already, which then
  584. /// stays as it is.
  585. fn written(&mut self, index: u32, frame: u64, due: u64, seen: bool) {
  586. if seen && self.slots.contains_key(&index) {
  587. return;
  588. }
  589. self.writes += 1;
  590. let write = self.writes;
  591. self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) });
  592. }
  593. fn remove(&mut self, index: u32) {
  594. self.slots.remove(&index);
  595. }
  596. /// Up to `max` slots due at `frame`, each with its write number, in
  597. /// the order to serve them:
  598. /// - first the ones looked at before (their memory was not mapped, or
  599. /// only part of it): the look is a query, and memory that has
  600. /// arrived since is what the title streamed in last;
  601. /// - then the others, the newest write first and the oldest next, in
  602. /// turns: slot order served the low slots of a backlog of
  603. /// 25,000-40,000 while the textures of the shot on screen waited
  604. /// (run 52: 98% of the drawn pixels had no colour texture in the
  605. /// first 3D frames).
  606. fn due(&self, frame: u64, max: usize) -> Vec<(u32, u64)> {
  607. let mut again: Vec<(u64, u32, u64)> = Vec::new();
  608. let mut fresh: Vec<(u64, u32, u64)> = Vec::new();
  609. for (&index, w) in self.slots.iter().filter(|(_, w)| w.due <= frame) {
  610. let class = if w.looks > 0 || w.mapped > 0 { &mut again } else { &mut fresh };
  611. class.push((w.written, index, w.write));
  612. }
  613. // By the number of the write, counted over the run.
  614. let newest_first = |a: &(u64, u32, u64), b: &(u64, u32, u64)| b.2.cmp(&a.2);
  615. again.sort_unstable_by(newest_first);
  616. fresh.sort_unstable_by(newest_first);
  617. let mut order: Vec<(u32, u64)> = again.iter().map(|&(_, index, write)| (index, write)).collect();
  618. let (mut new, mut old) = (0, fresh.len());
  619. while new < old && order.len() < max {
  620. order.push((fresh[new].1, fresh[new].2));
  621. new += 1;
  622. if new < old && order.len() < max {
  623. old -= 1;
  624. order.push((fresh[old].1, fresh[old].2));
  625. }
  626. }
  627. order.truncate(max);
  628. order
  629. }
  630. /// The entry of `index` if it is still the write the pass was handed.
  631. fn same(&mut self, index: u32, write: u64) -> Option<&mut Waiting> {
  632. self.slots.get_mut(&index).filter(|w| w.write == write)
  633. }
  634. /// Slot `index` is up to date: out of the queue until written again.
  635. fn done(&mut self, index: u32, write: u64) {
  636. if self.same(index, write).is_some() {
  637. self.slots.remove(&index);
  638. }
  639. }
  640. /// Nothing to upload at slot `index` now: looked at again after 1, 2,
  641. /// 4, ... frames, at most `most`.
  642. fn later(&mut self, index: u32, write: u64, frame: u64, most: u64) {
  643. if let Some(w) = self.same(index, write) {
  644. w.due = frame + (1u64 << w.looks.min(16)).min(most.max(1));
  645. w.looks = w.looks.saturating_add(1);
  646. }
  647. }
  648. /// The card has no room for the host copy slot `index` needs: it is
  649. /// not handed out again before frame `due`, or before the card has
  650. /// room again ([`TextureQueue::room`]). Nothing else of it changes: it
  651. /// is not a slot "waiting for its memory", and when it is due it has
  652. /// its old place among the slots never looked at. (It stayed due, so
  653. /// every pass on a full card looked at the same few hundred slots
  654. /// again and stopped there, and the slots behind them were never
  655. /// reached: the ones whose host copy exists and only wants bringing up
  656. /// to date, and the ones whose memory went, which is what lets host
  657. /// copies go and makes room.)
  658. fn hold(&mut self, index: u32, write: u64, due: u64) {
  659. if let Some(w) = self.same(index, write) {
  660. w.due = w.due.max(due);
  661. self.held.insert(index, write);
  662. }
  663. }
  664. /// The card has room again at `frame`: the slots held back for lack of
  665. /// it are due now, as if they had never been held. Returns how many.
  666. fn room(&mut self, frame: u64) -> usize {
  667. let held = std::mem::take(&mut self.held);
  668. let mut back = 0;
  669. for (index, write) in held {
  670. if let Some(w) = self.same(index, write) {
  671. w.due = w.due.min(frame);
  672. back += 1;
  673. }
  674. }
  675. back
  676. }
  677. /// Slot `index` was uploaded with `mapped` bytes of its memory there,
  678. /// not all of it: looked at again from frame `due`.
  679. fn partly(&mut self, index: u32, write: u64, due: u64, mapped: u64) {
  680. if let Some(w) = self.same(index, write) {
  681. (w.due, w.looks, w.mapped) = (due, 0, mapped.max(1));
  682. }
  683. }
  684. /// Slot `index` was uploaded whole from memory `at` (address, bytes)
  685. /// with fingerprint `print`: looked at again from frame `due`, for a
  686. /// title that fills a texture's memory after it wrote the view (the
  687. /// `looks`-th such look; `uploaded` is the upload's frame).
  688. #[allow(clippy::too_many_arguments)]
  689. fn recheck(&mut self, index: u32, write: u64, due: u64, at: (u64, u64), print: u64, looks: u8, uploaded: u64) {
  690. if let Some(w) = self.same(index, write) {
  691. (w.due, w.looks, w.mapped) = (due, 1, 0);
  692. w.checked = (at.0, at.1, print, looks, uploaded);
  693. }
  694. }
  695. /// What [`TextureQueue::recheck`] noted of slot `index`, if it is
  696. /// waiting for such a look.
  697. fn checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> {
  698. self.slots.get(&index).map(|w| w.checked).filter(|c| c.2 != 0)
  699. }
  700. /// The memory slot `index`'s texture lies in was mapped, unmapped or
  701. /// written in `frame`: the slot is looked at from frame `due` as one
  702. /// written now, whatever was known of it (a pass at work on it does
  703. /// not take it out).
  704. fn changed(&mut self, index: u32, frame: u64, due: u64) {
  705. self.writes += 1;
  706. let write = self.writes;
  707. let due = self.slots.get(&index).map_or(due, |w| w.due.min(due));
  708. self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) });
  709. }
  710. /// Bytes of slot `index`'s memory that were mapped at its last upload
  711. /// (0: not uploaded, or all of it was).
  712. fn mapped(&self, index: u32) -> u64 {
  713. self.slots.get(&index).map_or(0, |w| w.mapped)
  714. }
  715. /// For the frame line: slots in the queue; of them due at `frame`;
  716. /// waiting for their memory (looked at, never uploaded); uploaded in
  717. /// part; and the frames the oldest due one has waited since its write.
  718. fn census(&self, frame: u64) -> [u64; 5] {
  719. let mut c = [self.slots.len() as u64, 0, 0, 0, 0];
  720. for w in self.slots.values() {
  721. if w.mapped > 0 {
  722. c[3] += 1;
  723. } else if w.looks > 0 {
  724. c[2] += 1;
  725. }
  726. if w.due <= frame {
  727. c[1] += 1;
  728. c[4] = c[4].max(frame.saturating_sub(w.written));
  729. }
  730. }
  731. c
  732. }
  733. }
  734. /// Whether `view` is of a texture the title may fill itself: a texture it
  735. /// placed in memory, or a texture object.
  736. pub(crate) fn is_texture_view(view: &View) -> bool {
  737. match view {
  738. View::Placed(false, resource, _) => resource[0] != 1,
  739. View::Shader(r, _) => crate::resource::buffer_bytes(*r as crate::object::This).is_none(),
  740. _ => false,
  741. }
  742. }
  743. /// Buffer views left null because the host would refuse them
  744. /// ([`buffer_view_ok`]), since the start.
  745. pub(crate) static REFUSED_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  746. /// Whether the host device is gone, and why (the first time it is asked
  747. /// after that): for passes that make many views, to name the one that did
  748. /// it.
  749. pub(crate) fn device_removed() -> Option<String> {
  750. let host = host()?;
  751. // SAFETY: a plain query.
  752. let reason = unsafe { host.device.GetDeviceRemovedReason() };
  753. reason.err().map(|e| e.to_string())
  754. }
  755. /// Writes of title view-heap slots with a placed texture view and with a
  756. /// view of a texture object, since the start (diagnostic counts).
  757. pub(crate) static PLACED_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  758. pub(crate) static OBJECT_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  759. /// Bytes per element of a buffer view, as the console's descriptor holds
  760. /// them for indexed reads (structured: the stride; raw: 1, the index is the
  761. /// byte; typed: the format's); `None` if `view` is not a buffer view.
  762. fn view_stride(view: &View) -> Option<u32> {
  763. let (stride, raw, format) = view_elements(view)?;
  764. Some(if stride > 0 {
  765. stride
  766. } else if raw {
  767. 1
  768. } else {
  769. crate::resource::element(format).map_or(0, |(bytes, _)| bytes as u32)
  770. })
  771. }
  772. /// A buffer view's structure stride, whether it is raw, and its format;
  773. /// `None` if `view` is not a buffer view.
  774. fn view_elements(view: &View) -> Option<(u32, bool, u32)> {
  775. const BUFFER: u32 = 1;
  776. let (words, unordered): (&[u32; 10], bool) = match view {
  777. View::Shader(_, Some(d)) if d[1] == BUFFER => (d, false),
  778. View::Unordered(_, _, Some(d)) if d[1] == BUFFER => (d, true),
  779. View::Placed(unordered, resource, d) if resource[0] == BUFFER => {
  780. (d[..10].try_into().ok()?, *unordered)
  781. }
  782. _ => return None,
  783. };
  784. // SAFETY: buffer views' union members.
  785. Some(unsafe {
  786. if unordered {
  787. let d = uav_desc(words);
  788. let b = d.Anonymous.Buffer;
  789. (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0, d.Format.0 as u32)
  790. } else {
  791. let d = srv_desc(words);
  792. let b = d.Anonymous.Buffer;
  793. (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0, d.Format.0 as u32)
  794. }
  795. })
  796. }
  797. /// Whether a buffer view that begins `offset` bytes into its host copy begins
  798. /// where no host view can: raw views begin on 16 bytes, others on a multiple
  799. /// of their elements (`stride` of a structured one, which is made raw where it
  800. /// can be, `element` of a typed one). The console's begin on any dword, and
  801. /// the title puts parameter blocks at ring positions: a raw view of 128 bytes
  802. /// at 8 (the colour table bakes'), structured ones of elements that are no
  803. /// divisor of their place (the culling's 456-byte constants). Such a view gets
  804. /// a copy of its own bytes ([`crate::shadow::exact`]). (A typed view of
  805. /// 12-byte elements at a multiple of 16 that is none of 12 is one of them: it
  806. /// was passed over, and stayed null.)
  807. fn off_elements(offset: u64, stride: u32, raw: bool, element: u64) -> bool {
  808. if raw {
  809. !offset.is_multiple_of(16)
  810. } else if stride > 0 {
  811. !offset.is_multiple_of(16) && !offset.is_multiple_of(u64::from(stride))
  812. } else {
  813. element > 0 && !offset.is_multiple_of(element)
  814. }
  815. }
  816. /// Whether `view` has a raw twin when its host slot is made ([`raw_twins`]):
  817. /// a buffer view or a constant buffer's.
  818. fn twinned(view: &View) -> bool {
  819. matches!(view, View::Constant(..)) || view_elements(view).is_some()
  820. }
  821. /// Whether views off their copy's elements get a copy of their own bytes. On by
  822. /// default; `VICTORY_VIEW_BYTES=0` leaves them null, as before.
  823. fn view_bytes() -> bool {
  824. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  825. *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_BYTES").is_none_or(|v| v != "0"))
  826. }
  827. /// The copy the buffer view of `[start, start + len)` is made on: `shadow`, the one
  828. /// its buffer has, or one of the view's own bytes ([`off_elements`]).
  829. fn view_home(
  830. shadow: std::sync::Arc<crate::shadow::Shadow>,
  831. start: u64,
  832. len: u64,
  833. (stride, raw, format): (u32, bool, u32),
  834. ) -> std::sync::Arc<crate::shadow::Shadow> {
  835. let Some(offset) = shadow.offset_in(start).map(|_| shadow.offset(start)) else {
  836. return shadow;
  837. };
  838. if !view_bytes() {
  839. return shadow;
  840. }
  841. let element = crate::resource::element(format).map_or(0, |(bytes, _)| bytes);
  842. if !off_elements(offset, stride, raw, element) {
  843. return shadow;
  844. }
  845. crate::shadow::exact(start, len).unwrap_or(shadow)
  846. }
  847. /// For device-removed reports: what the slots of the title's view heap that
  848. /// the words of user data may name hold now ([`crate::host::indirects`]).
  849. #[cfg(feature = "diagnostics")]
  850. pub(crate) fn describe_slots(words: &[u32]) -> Vec<(usize, u32, String)> {
  851. super::with_view_heap(|host| {
  852. crate::host::indirects::slots(words, host.count, 6)
  853. .into_iter()
  854. .take(24)
  855. .map(|(word, slot)| (word, slot, host.describe_slot(slot).unwrap_or_default()))
  856. .collect()
  857. })
  858. .unwrap_or_default()
  859. }
  860. /// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for
  861. /// device-removed reports: a shader indexing a heap past its end faults.
  862. static GPU_RANGES: Mutex<Vec<(u64, u64, u64, bool)>> = Mutex::new(Vec::new());
  863. /// For device-removed reports: where host GPU address `va` lies against
  864. /// the host descriptor heaps.
  865. pub(crate) fn near_heaps(va: u64) -> String {
  866. let ranges = GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner());
  867. let mut text = String::new();
  868. for &(start, bytes, step, sampler) in ranges.iter() {
  869. let kind = if sampler { "sampler" } else { "view" };
  870. let place = if va < start {
  871. format!("{:#x} below", start - va)
  872. } else if va < start + bytes {
  873. format!("inside, slot {}", (va - start) / step)
  874. } else {
  875. format!("{:#x} past its end (slot {})", va - start - bytes, (va - start) / step)
  876. };
  877. text.push_str(&format!("; {kind} heap {start:#x}+{bytes:#x}: {place}"));
  878. }
  879. text
  880. }
  881. /// The host's limit for shader-visible view heaps on resource binding
  882. /// tiers 1 and 2; tier 3 hardware may take more.
  883. const PORTABLE_VIEWS: u32 = 1_000_000;
  884. /// The size of every host view heap on a host that takes more than
  885. /// [`PORTABLE_VIEWS`] (AMD): the title's heap (a little over 1,000,000
  886. /// views in the retail game) plus [`DYNAMIC`] fits with room to spare, and
  887. /// the last slot is the null slot every view index at or past it reads.
  888. const UNCAPPED_VIEWS: u32 = 1 << 21;
  889. /// Where the raw twins of the title's slots start in a heap that has them
  890. /// ([`raw_twins`]): past every slot a title's heap and the dynamic ones take.
  891. const RAW_TWINS: u32 = 1 << 21;
  892. /// Whether view heaps keep a raw twin of every buffer view of the title's
  893. /// slots, which shaders read that pick buffers by an index they compute
  894. /// (`victory_shader::emit::raw_views` says why; `VICTORY_RAW_VIEWS=0`: they
  895. /// read the title's slots themselves, as before). Needs a host that takes
  896. /// heaps of 2^22 views.
  897. fn raw_twins() -> bool {
  898. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  899. *ON.get_or_init(|| std::env::var_os("VICTORY_RAW_VIEWS").is_none_or(|v| v != "0"))
  900. }
  901. /// Picks, once, the null slot at the end of every host view heap and tells
  902. /// the translator now (`set_view_heap_limit`) instead of when the title's
  903. /// heap is made: a shader keeps the limit it was translated with, and the
  904. /// title makes 25 pipelines (their shaders translated at once) before it
  905. /// makes its view heap. Called before a shader is translated and before a
  906. /// view heap is made.
  907. ///
  908. /// Every host clamps. A host that caps view heaps at [`PORTABLE_VIEWS`]
  909. /// (NVIDIA) hung on a view index past the heap; one that does not (AMD
  910. /// RDNA3, RX 7900 XT) took a page fault and removed the device on entering
  911. /// the world: a compute program read view slot 16,777,088 (0xffff80) of a
  912. /// heap of 1,507,328, past its end. Unclamped, that index is undefined on
  913. /// any host.
  914. pub(crate) fn probe_view_limit() {
  915. static ONCE: std::sync::Once = std::sync::Once::new();
  916. ONCE.call_once(|| {
  917. let Some(host) = host() else { return };
  918. let fits = |count: u32| {
  919. // SAFETY: plain heap creation; the heap is released at once.
  920. let made: windows::core::Result<ID3D12DescriptorHeap> = unsafe {
  921. host.device
  922. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  923. Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  924. NumDescriptors: count,
  925. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  926. NodeMask: 0,
  927. })
  928. };
  929. made.is_ok()
  930. };
  931. let twins = raw_twins() && fits(2 * RAW_TWINS);
  932. if twins {
  933. victory_shader::emit::set_raw_views(RAW_TWINS);
  934. }
  935. // (The twins lie past the null slot.)
  936. let views = if twins {
  937. RAW_TWINS
  938. } else if fits(UNCAPPED_VIEWS) {
  939. UNCAPPED_VIEWS
  940. } else {
  941. PORTABLE_VIEWS
  942. };
  943. tracing::info!(
  944. views,
  945. raw_twins = twins,
  946. "host view heaps hold {views} views; view indices are clamped to the null slot at the end from the first shader on"
  947. );
  948. victory_shader::emit::set_view_heap_limit(views - 1);
  949. });
  950. }
  951. /// Slots past the title's in a view heap, for tables a draw needs made
  952. /// afresh (constant buffers copied per draw). A list holds the slots it
  953. /// took until it is reset (its submissions have run) or released.
  954. /// 2^16 ran out in the world ("no free dynamic descriptor slots", run 11;
  955. /// upstream PR #336 takes 2^18). On a host heap capped at 1,000,000 views
  956. /// (NVIDIA) these come out of the title's slots, whose highest seen is
  957. /// about 720,000: 2^17 left 868,000 of them, and ran out in the opening
  958. /// cutscene (a frame asks for up to 16,000 tables while the frame before
  959. /// still holds its own; a draw refused its table read slots never made
  960. /// for it, and the card stopped within frames). 2^18 leaves 737,000; a
  961. /// table past them is made afresh in these slots like any other.
  962. pub(crate) const DYNAMIC: u32 = 1 << 18;
  963. /// [`DYNAMIC`] for a heap of `count` title slots whose null slot is `null`
  964. /// (0: none): up to four times as many where the host heap has the room (a
  965. /// host that takes more than [`PORTABLE_VIEWS`]; `VICTORY_DYNAMIC_SLOTS`
  966. /// sets the most). 2^18 ran out in the title's bigger places (session
  967. /// play-1125-0127: 27,000 to 35,000 tables a frame, up to 3,285 of them
  968. /// refused, with 2,639 indirect draws and dispatches).
  969. fn dynamic_slots(count: u32, null: u32) -> u32 {
  970. static MOST: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
  971. let most = *MOST.get_or_init(|| {
  972. std::env::var("VICTORY_DYNAMIC_SLOTS")
  973. .ok()
  974. .and_then(|v| v.trim().parse().ok())
  975. .unwrap_or(DYNAMIC << 2)
  976. });
  977. if null < PORTABLE_VIEWS {
  978. return DYNAMIC;
  979. }
  980. null.saturating_sub(count).min(most).max(DYNAMIC)
  981. }
  982. impl HostHeap {
  983. pub(crate) fn new(sampler: bool, count: u32) -> Option<Self> {
  984. let host = host()?;
  985. let kind = if sampler {
  986. D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER
  987. } else {
  988. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV
  989. };
  990. let make = |count: u32| -> windows::core::Result<ID3D12DescriptorHeap> {
  991. // SAFETY: plain heap creation.
  992. unsafe {
  993. host.device
  994. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  995. Type: kind,
  996. NumDescriptors: count,
  997. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  998. NodeMask: 0,
  999. })
  1000. }
  1001. };
  1002. // A view heap ends at the null slot shaders clamp view indices to
  1003. // (`probe_view_limit`), whatever the title's own count: the title's
  1004. // slots, then the dynamic ones, then null up to and with that slot.
  1005. if !sampler {
  1006. probe_view_limit();
  1007. }
  1008. let null = if sampler {
  1009. 0
  1010. } else {
  1011. victory_shader::emit::view_heap_limit()
  1012. };
  1013. let raw = if sampler { 0 } else { victory_shader::emit::raw_views() };
  1014. let extra = if sampler { 0 } else { dynamic_slots(count, null) };
  1015. let (heap, count, size) = if null == 0 {
  1016. match make(count + extra) {
  1017. Ok(heap) => (heap, count, count + extra),
  1018. Err(e) => {
  1019. tracing::warn!(error = %e, count, sampler, "no host descriptor heap");
  1020. return None;
  1021. }
  1022. }
  1023. } else {
  1024. let size = if raw == 0 { null + 1 } else { 2 * raw };
  1025. let fitted = if count + extra <= null {
  1026. count
  1027. } else {
  1028. // shortcut: descriptors past the host's limit are left out; a title that reaches
  1029. // them needs remapping. They read the null slot instead.
  1030. tracing::warn!(count, "host view heap capped at {size}; views past it read a null slot");
  1031. null - extra
  1032. };
  1033. match make(size) {
  1034. Ok(heap) => (heap, fitted, size),
  1035. Err(e) => {
  1036. tracing::warn!(error = %e, count, size, "no host view heap");
  1037. return None;
  1038. }
  1039. }
  1040. };
  1041. // SAFETY: a live heap.
  1042. let (cpu, step) = unsafe {
  1043. (
  1044. heap.GetCPUDescriptorHandleForHeapStart().ptr,
  1045. host.device.GetDescriptorHandleIncrementSize(kind),
  1046. )
  1047. };
  1048. tracing::debug!(count, sampler, "host descriptor heap");
  1049. // SAFETY: a live shader-visible heap.
  1050. let gpu = unsafe { heap.GetGPUDescriptorHandleForHeapStart().ptr };
  1051. GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((
  1052. gpu,
  1053. u64::from(size) * u64::from(step),
  1054. u64::from(step),
  1055. sampler,
  1056. ));
  1057. let strides = (!sampler)
  1058. .then(|| {
  1059. let bytes = u64::from(victory_shader::emit::SLOT_STRIDES_COUNT) * 4;
  1060. let (buffer, data) = host.upload_buffer(bytes)?;
  1061. // SAFETY: the buffer's whole mapping; a live buffer.
  1062. let gpu = unsafe {
  1063. std::ptr::write_bytes(data, 0, bytes as usize);
  1064. buffer.GetGPUVirtualAddress()
  1065. };
  1066. crate::host::name(&buffer, || "element strides by view heap slot".to_owned());
  1067. Some((buffer, gpu, data as usize))
  1068. })
  1069. .flatten();
  1070. let h = HostHeap {
  1071. heap,
  1072. cpu,
  1073. step,
  1074. count,
  1075. dynamic: extra,
  1076. sampler,
  1077. raw,
  1078. twins: (0..if raw == 0 { 0 } else { count + extra }).map(|_| std::sync::atomic::AtomicBool::new(false)).collect(),
  1079. made: Mutex::new(vec![0; count as usize]),
  1080. copied: Mutex::new(Vec::new()),
  1081. waiting: Mutex::default(),
  1082. away: Mutex::default(),
  1083. kept: Mutex::new(vec![None; (count + extra) as usize]),
  1084. next: Mutex::new((0, vec![false; extra as usize])),
  1085. free: std::sync::atomic::AtomicU32::new(extra),
  1086. too_long: std::sync::atomic::AtomicU32::new(u32::MAX),
  1087. strides,
  1088. buffers: Mutex::default(),
  1089. changed: Mutex::default(),
  1090. textures: Mutex::default(),
  1091. tabled: (0..if sampler { 0 } else { count })
  1092. .map(|_| std::sync::atomic::AtomicU32::new(0))
  1093. .collect(),
  1094. placed: {
  1095. let spans = std::sync::Arc::<Mutex<Spans>>::default();
  1096. if !sampler {
  1097. PLACED_SPANS
  1098. .lock()
  1099. .unwrap_or_else(|e| e.into_inner())
  1100. .push(std::sync::Arc::downgrade(&spans));
  1101. }
  1102. spans
  1103. },
  1104. };
  1105. // A slot never written is undefined: shaders reading one (a slot
  1106. // the title wrote in a way we do not know, or a table entry no
  1107. // used-resource entry names) read a wild address. Every slot starts
  1108. // null instead.
  1109. let started = std::time::Instant::now();
  1110. if let Err(e) = h.fill_null(kind, size) {
  1111. tracing::warn!(error = %e, "host descriptor heap not made null");
  1112. }
  1113. tracing::debug!(ms = started.elapsed().as_millis(), "host descriptor heap made null");
  1114. Some(h)
  1115. }
  1116. /// Makes the first `total` slots null: one null slot in a CPU-side heap,
  1117. /// doubled by copies to a block, the block copied over the heap.
  1118. fn fill_null(&self, kind: D3D12_DESCRIPTOR_HEAP_TYPE, total: u32) -> windows::core::Result<()> {
  1119. const BLOCK: u32 = 1 << 16;
  1120. let Some(host) = host() else { return Ok(()) };
  1121. // SAFETY: plain heap creation and copies inside live heaps.
  1122. unsafe {
  1123. let block: ID3D12DescriptorHeap =
  1124. host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  1125. Type: kind,
  1126. NumDescriptors: BLOCK,
  1127. ..Default::default()
  1128. })?;
  1129. let start = block.GetCPUDescriptorHandleForHeapStart();
  1130. let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE {
  1131. ptr: start.ptr + (i * self.step) as usize,
  1132. };
  1133. // (The twins are null buffer views.)
  1134. let ends = if self.raw == 0 { [total, total] } else { [self.raw.min(total), total] };
  1135. let mut done = 0;
  1136. for (twin, end) in ends.into_iter().enumerate() {
  1137. if done == end {
  1138. continue;
  1139. }
  1140. if self.sampler {
  1141. null_sampler(start);
  1142. } else if twin == 1 {
  1143. null_buffer_view(start);
  1144. } else {
  1145. null_view(start);
  1146. }
  1147. let mut filled = 1;
  1148. while filled < BLOCK {
  1149. let n = filled.min(BLOCK - filled);
  1150. host.device.CopyDescriptorsSimple(n, at(filled), start, kind);
  1151. filled += n;
  1152. }
  1153. while done < end {
  1154. let n = BLOCK.min(end - done);
  1155. host.device.CopyDescriptorsSimple(n, self.cpu(done), start, kind);
  1156. done += n;
  1157. }
  1158. }
  1159. }
  1160. Ok(())
  1161. }
  1162. /// A plain point sampler at slot `index`, for sampler slots without a
  1163. /// view.
  1164. fn null_sampler(&self, index: u32) {
  1165. null_sampler(self.at(index));
  1166. self.put(index);
  1167. }
  1168. }
  1169. /// A plain point sampler at `at`.
  1170. fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
  1171. let Some(host) = host() else { return };
  1172. let desc = D3D12_SAMPLER_DESC {
  1173. Filter: D3D12_FILTER_MIN_MAG_MIP_POINT,
  1174. AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  1175. AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  1176. AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  1177. MaxAnisotropy: 1,
  1178. ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER,
  1179. ..Default::default()
  1180. };
  1181. // SAFETY: a slot of a sampler heap of ours.
  1182. unsafe { host.device.CreateSampler(&desc, at) };
  1183. }
  1184. impl HostHeap {
  1185. /// `n` consecutive free dynamic slots (view heaps only), taken until
  1186. /// [`HostHeap::release`]: the first's index.
  1187. pub(crate) fn dynamic(&self, n: u32) -> Option<u32> {
  1188. if self.sampler || n == 0 || n > self.dynamic {
  1189. return None;
  1190. }
  1191. #[cfg(feature = "diagnostics")]
  1192. let started = std::time::Instant::now();
  1193. #[cfg(feature = "diagnostics")]
  1194. crate::copystat::add(crate::copystat::C::DynamicAsked, 1);
  1195. let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner());
  1196. let (next, taken) = &mut *guard;
  1197. let enough = self.free.load(std::sync::atomic::Ordering::Relaxed) >= n
  1198. && n < self.too_long.load(std::sync::atomic::Ordering::Relaxed);
  1199. let n = n as usize;
  1200. // Search from `next` on, then from the start (extending past cursor by
  1201. // n - 1 so contiguous runs crossing the cursor are not missed).
  1202. let cursor = *next as usize;
  1203. let end = self.dynamic as usize;
  1204. let second_end = cursor.saturating_add(n.saturating_sub(1)).min(end);
  1205. let starts = (cursor..end).chain(0..second_end);
  1206. let mut run = 0;
  1207. let mut found = None;
  1208. let mut last = usize::MAX;
  1209. for at in starts.take(if enough { usize::MAX } else { 0 }) {
  1210. // A run cannot wrap past the end.
  1211. if at != last.wrapping_add(1) {
  1212. run = 0;
  1213. }
  1214. last = at;
  1215. run = if taken[at] { 0 } else { run + 1 };
  1216. if run == n {
  1217. found = Some(at + 1 - n);
  1218. break;
  1219. }
  1220. }
  1221. let Some(first) = found else {
  1222. if enough {
  1223. self.too_long.fetch_min(n as u32, std::sync::atomic::Ordering::Relaxed);
  1224. }
  1225. static ONCE: std::sync::Once = std::sync::Once::new();
  1226. ONCE.call_once(|| tracing::warn!(n, "no free dynamic descriptor slots: a table is not made"));
  1227. #[cfg(feature = "diagnostics")]
  1228. {
  1229. use crate::copystat::{C, add};
  1230. add(C::DynamicRefused, 1);
  1231. add(C::DynamicNs, started.elapsed().as_nanos() as u64);
  1232. }
  1233. return None;
  1234. };
  1235. #[cfg(feature = "diagnostics")]
  1236. crate::copystat::add(crate::copystat::C::DynamicNs, started.elapsed().as_nanos() as u64);
  1237. taken[first..first + n].fill(true);
  1238. self.free.fetch_sub(n as u32, std::sync::atomic::Ordering::Relaxed);
  1239. *next = ((first + n) % end) as u32;
  1240. Some(self.count + first as u32)
  1241. }
  1242. /// The title slots this heap has host slots for; fewer than the title's
  1243. /// when the host caps its size.
  1244. pub(crate) fn count(&self) -> u32 {
  1245. self.count
  1246. }
  1247. /// The GPU address of the table of element strides by title slot (view
  1248. /// heaps).
  1249. pub(crate) fn strides_gpu(&self) -> Option<u64> {
  1250. self.strides.as_ref().map(|s| s.1)
  1251. }
  1252. /// The table's buffer, for a list to hold.
  1253. pub(crate) fn strides_buffer(&self) -> Option<&ID3D12Resource> {
  1254. self.strides.as_ref().map(|s| &s.0)
  1255. }
  1256. /// Up to `max` title slots whose texture view is due at `frame`, each
  1257. /// with its write number, in the order to serve them
  1258. /// ([`TextureQueue::due`]), and the queue's counts
  1259. /// ([`TextureQueue::census`]).
  1260. pub(crate) fn texture_slots_due(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, [u64; 5]) {
  1261. let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1262. (if max == 0 { Vec::new() } else { textures.due(frame, max) }, textures.census(frame))
  1263. }
  1264. /// Every title slot of the queue that is due at `frame`, and whether
  1265. /// it was uploaded before (in part, or whole and waiting for another
  1266. /// look): for the card accounting line
  1267. /// (`crate::resource::card_accounting`).
  1268. pub(crate) fn texture_slots_all_due(&self, frame: u64) -> Vec<(u32, bool)> {
  1269. let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1270. textures
  1271. .slots
  1272. .iter()
  1273. .filter(|(_, w)| w.due <= frame)
  1274. .map(|(&index, w)| (index, w.mapped > 0 || w.checked.2 != 0))
  1275. .collect()
  1276. }
  1277. /// The texture view of title slot `index` (as handed out with `write`)
  1278. /// was brought up to date: due again from frame `again` (uploaded with
  1279. /// that many bytes of its memory there, not all), or not until the
  1280. /// slot is written again.
  1281. pub(crate) fn texture_slot_done(&self, index: u32, write: u64, again: Option<(u64, u64)>) {
  1282. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1283. match again {
  1284. Some((frame, mapped)) => textures.partly(index, write, frame, mapped),
  1285. None => textures.done(index, write),
  1286. }
  1287. }
  1288. /// Title slot `index` was uploaded whole: see [`TextureQueue::recheck`].
  1289. #[allow(clippy::too_many_arguments)]
  1290. pub(crate) fn texture_slot_recheck(
  1291. &self,
  1292. index: u32,
  1293. write: u64,
  1294. due: u64,
  1295. at: (u64, u64),
  1296. print: u64,
  1297. looks: u8,
  1298. uploaded: u64,
  1299. ) {
  1300. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1301. textures.recheck(index, write, due, at, print, looks, uploaded);
  1302. }
  1303. /// See [`TextureQueue::checked`].
  1304. pub(crate) fn texture_slot_checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> {
  1305. self.textures.lock().unwrap_or_else(|e| e.into_inner()).checked(index)
  1306. }
  1307. /// Nothing to upload at title slot `index` now (its memory is not
  1308. /// mapped, or no more of it than before): looked at again after 1, 2,
  1309. /// 4, ... frames, at most `most`.
  1310. pub(crate) fn texture_slot_later(&self, index: u32, write: u64, frame: u64, most: u64) {
  1311. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1312. textures.later(index, write, frame, most);
  1313. }
  1314. /// See [`TextureQueue::hold`].
  1315. pub(crate) fn texture_slot_held(&self, index: u32, write: u64, due: u64) {
  1316. self.textures.lock().unwrap_or_else(|e| e.into_inner()).hold(index, write, due);
  1317. }
  1318. /// See [`TextureQueue::room`].
  1319. pub(crate) fn texture_slots_room(&self, frame: u64) -> usize {
  1320. self.textures.lock().unwrap_or_else(|e| e.into_inner()).room(frame)
  1321. }
  1322. /// Bytes of title slot `index`'s memory that were mapped when it was
  1323. /// last uploaded in part (0: not uploaded, or whole).
  1324. pub(crate) fn texture_slot_mapped(&self, index: u32) -> u64 {
  1325. self.textures.lock().unwrap_or_else(|e| e.into_inner()).mapped(index)
  1326. }
  1327. /// Takes the ranges of title memory the runtime mapped, unmapped or
  1328. /// wrote since the last call ([`remapped`]) and makes the slots whose
  1329. /// placed texture lies there due from the next frame (by when a write
  1330. /// under way has landed): memory that arrived is uploaded, memory that
  1331. /// went makes the slot null ([`HostHeap::texture_slot_gone`]), and a
  1332. /// texture streamed into the place of another of the same description
  1333. /// is uploaded although no descriptor says so. Slots tables read are
  1334. /// left to their draws. Returns how many slots it made due.
  1335. /// shortcut: the ranges are kept in one place for all heaps; the heap
  1336. /// whose pass runs first takes them (a title has one view heap).
  1337. pub(crate) fn texture_slots_remapped(&self, frame: u64) -> usize {
  1338. use std::sync::atomic::Ordering::Relaxed;
  1339. self.texture_slots_page_written(frame);
  1340. let ranges = std::mem::take(&mut *REMAPPED.lock().unwrap_or_else(|e| e.into_inner()));
  1341. if ranges.is_empty() {
  1342. return 0;
  1343. }
  1344. let mut slots: Vec<u32> = {
  1345. let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
  1346. ranges.iter().flat_map(|&(start, end)| placed.slots_in(start, end)).collect()
  1347. };
  1348. slots.sort_unstable();
  1349. slots.dedup();
  1350. slots.retain(|&slot| !self.tabled_lately(slot, frame));
  1351. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1352. for &slot in &slots {
  1353. textures.changed(slot, frame, frame + 1);
  1354. }
  1355. STALE[3].fetch_add(slots.len() as u64, Relaxed);
  1356. slots.len()
  1357. }
  1358. /// Makes the slots of the textures filled with less than was mapped
  1359. /// ([`read_short`]) due from the next frame on. Returns how many.
  1360. pub(crate) fn texture_slots_short(&self, frame: u64) -> usize {
  1361. if self.sampler {
  1362. return 0;
  1363. }
  1364. let starts = std::mem::take(&mut SHORT.lock().unwrap_or_else(|e| e.into_inner()).0);
  1365. if starts.is_empty() {
  1366. return 0;
  1367. }
  1368. let mut slots: Vec<u32> = {
  1369. let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
  1370. starts.iter().flat_map(|&start| placed.slots_at(start)).collect()
  1371. };
  1372. slots.sort_unstable();
  1373. slots.dedup();
  1374. slots.retain(|&slot| !self.tabled_lately(slot, frame));
  1375. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1376. for &slot in &slots {
  1377. textures.changed(slot, frame, frame + 1);
  1378. }
  1379. slots.len()
  1380. }
  1381. /// Takes the ranges of title memory written behind the guards' back
  1382. /// since the last call ([`page_written`]) and finds the slots whose
  1383. /// placed texture holds bytes of them ([`Spans::slots_holding`]). A
  1384. /// slot whose texture was uploaded before the write shows the bytes
  1385. /// from before: with `VICTORY_PAGE_WRITES` (`crate::watch::page_writes`,
  1386. /// bit 2) it is due again [`PAGE_WRITE_AFTER`] frames on, as memory
  1387. /// mapped under it would make it ([`HostHeap::texture_slots_remapped`]);
  1388. /// its host copy exists, so the upload needs no room on the card. A
  1389. /// slot still waiting for its first upload is left as it is: that
  1390. /// upload takes the bytes that are there by then. Slots tables read
  1391. /// are left to their draws. Counted either way; returns how many slots
  1392. /// it made due.
  1393. fn texture_slots_page_written(&self, frame: u64) -> usize {
  1394. let ranges = std::mem::take(&mut *PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()));
  1395. if ranges.is_empty() {
  1396. return 0;
  1397. }
  1398. self.slots_written_under(&ranges, frame, crate::watch::page_writes() & 2 != 0)[2]
  1399. }
  1400. /// [`HostHeap::texture_slots_page_written`] for `ranges` (start, end):
  1401. /// the slots that held bytes of them, those of them uploaded before,
  1402. /// and those made due (the latter, if `due`).
  1403. fn slots_written_under(&self, ranges: &[(u64, u64)], frame: u64, due: bool) -> [usize; 3] {
  1404. use std::sync::atomic::Ordering::Relaxed;
  1405. let mut slots: Vec<u32> = {
  1406. let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
  1407. ranges.iter().flat_map(|&(start, end)| placed.slots_holding(start, end)).collect()
  1408. };
  1409. slots.sort_unstable();
  1410. slots.dedup();
  1411. slots.retain(|&slot| !self.tabled_lately(slot, frame));
  1412. let held = slots.len();
  1413. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1414. // Uploaded before: out of the queue, or in it after an upload (in
  1415. // part, or whole and being looked at again).
  1416. slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0));
  1417. PAGE_WRITES[2].fetch_add(held as u64, Relaxed);
  1418. PAGE_WRITES[3].fetch_add(slots.len() as u64, Relaxed);
  1419. if !due {
  1420. return [held, slots.len(), 0];
  1421. }
  1422. for &slot in &slots {
  1423. textures.changed(slot, frame, frame + PAGE_WRITE_AFTER);
  1424. }
  1425. [held, slots.len(), slots.len()]
  1426. }
  1427. /// Whether host slot `index` is made from the very record the title
  1428. /// has at `handle` now. Its host texture then exists (a slot keeps what
  1429. /// it views), so bringing that texture up to date takes no memory of
  1430. /// the card.
  1431. pub(crate) fn texture_slot_made_from(&self, index: u32, handle: u64) -> bool {
  1432. if index >= self.count {
  1433. return false;
  1434. }
  1435. // SAFETY: the handle is a descriptor slot in title memory.
  1436. let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() };
  1437. let key = u64::from(generation) << 32 | u64::from(i);
  1438. if tag != VIEW_TAG {
  1439. return false;
  1440. }
  1441. // And the slot holds a host resource: a slot is also noted as made
  1442. // from a view the host could not make (`make` gave nothing, the
  1443. // slot is null and keeps nothing). The host copy of such a
  1444. // texture is held by no slot, may have been let go, and would be
  1445. // made anew here, with the card full. `made` first, then `kept`,
  1446. // as `mirror` takes them.
  1447. let made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1448. made.get(index as usize).is_some_and(|&made| made != 0 && made == key)
  1449. && self
  1450. .kept
  1451. .lock()
  1452. .unwrap_or_else(|e| e.into_inner())
  1453. .get(index as usize)
  1454. .is_some_and(Option::is_some)
  1455. }
  1456. /// Levels on demand (`crate::tiles`): makes again the host slots of the
  1457. /// placed textures whose first level with memory changed since the
  1458. /// last call ([`levels_changed`]), each from the view it was made
  1459. /// from, so that it shows the texture from that level ([`make`]). Only
  1460. /// slots that are made; a slot draws read through a table is made by
  1461. /// its draw. Returns how many it made.
  1462. /// shortcut: the starts are kept in one place for all heaps; the heap
  1463. /// whose pass runs first takes them (a title has one view heap).
  1464. /// Levels on demand (`crate::tiles`): the card has room, so the slots
  1465. /// of up to [`Self::WAITING_A_PASS`] placed textures whose upload left
  1466. /// a held level without tiles at least a second ago
  1467. /// ([`levels_waiting`]) are due again from the next frame, as memory
  1468. /// mapped under them would make them
  1469. /// ([`HostHeap::texture_slots_remapped`]): the upload then gives the
  1470. /// level its tiles. To be called only while the card has room: without
  1471. /// it the upload would give nothing again. Slots tables read are left
  1472. /// to their draws (`texture.rs` `upload` asks again for those). Returns
  1473. /// how many slots it made due.
  1474. /// shortcut: kept in one place for all heaps, as the starts below.
  1475. pub(crate) fn texture_slots_waiting(&self, frame: u64) -> usize {
  1476. if self.sampler {
  1477. return 0;
  1478. }
  1479. let starts: Vec<u64> = {
  1480. let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner());
  1481. if waiting.is_empty() {
  1482. return 0;
  1483. }
  1484. let starts: Vec<u64> = waiting
  1485. .iter()
  1486. .filter(|&(_, &since)| crate::host::long_ago(since, 1000, 2))
  1487. .map(|(&start, _)| start)
  1488. .take(Self::WAITING_A_PASS)
  1489. .collect();
  1490. for start in &starts {
  1491. waiting.remove(start);
  1492. }
  1493. starts
  1494. };
  1495. if starts.is_empty() {
  1496. return 0;
  1497. }
  1498. let mut slots: Vec<u32> = {
  1499. let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
  1500. starts.iter().flat_map(|&start| placed.slots_at(start)).collect()
  1501. };
  1502. slots.sort_unstable();
  1503. slots.dedup();
  1504. slots.retain(|&slot| !self.tabled_lately(slot, frame));
  1505. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1506. for &slot in &slots {
  1507. textures.changed(slot, frame, frame + 1);
  1508. }
  1509. crate::tiles::STATS[10].fetch_add(slots.len() as u64, std::sync::atomic::Ordering::Relaxed);
  1510. slots.len()
  1511. }
  1512. /// Textures a pass asks again for their levels
  1513. /// ([`HostHeap::texture_slots_waiting`]): the first ones given tiles
  1514. /// may take the room the others were asked for, and an upload that
  1515. /// gives nothing is a whole texture staged and copied for nothing.
  1516. const WAITING_A_PASS: usize = 128;
  1517. pub(crate) fn texture_views_remade(&self) -> usize {
  1518. if self.sampler {
  1519. return 0;
  1520. }
  1521. {
  1522. let mut after = RESHOWN_AFTER.lock().unwrap_or_else(|e| e.into_inner());
  1523. if !after.is_empty() {
  1524. let finished = crate::host::submissions().1;
  1525. let mut now = RESHOWN.lock().unwrap_or_else(|e| e.into_inner());
  1526. after.retain(|&(at, start)| {
  1527. if at <= finished {
  1528. now.push(start);
  1529. }
  1530. at > finished
  1531. });
  1532. }
  1533. }
  1534. let starts = std::mem::take(&mut *RESHOWN.lock().unwrap_or_else(|e| e.into_inner()));
  1535. if starts.is_empty() {
  1536. return 0;
  1537. }
  1538. let slots: Vec<u32> = {
  1539. let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
  1540. starts.iter().flat_map(|&start| placed.slots_at(start)).collect()
  1541. };
  1542. let made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1543. let mut remade = 0;
  1544. for slot in slots {
  1545. let Some(&key) = made.get(slot as usize) else {
  1546. continue;
  1547. };
  1548. if key == 0 {
  1549. continue;
  1550. }
  1551. let Some(view) = view_at(key as u32, (key >> 32) as u32) else {
  1552. continue;
  1553. };
  1554. if let Some(kept) = make(&view, self.at(slot)) {
  1555. self.put(slot);
  1556. self.keep(slot, kept);
  1557. remade += 1;
  1558. }
  1559. }
  1560. remade
  1561. }
  1562. /// The memory of the texture title slot `index` views is not mapped
  1563. /// (any more): a host slot made from it becomes null again, so that
  1564. /// the host copy can be let go (`crate::resource::let_go_idle`; a slot
  1565. /// keeps what it views). True if the slot was made.
  1566. ///
  1567. /// Not at the first look: a title that moves a texture in its streaming
  1568. /// memory unmaps it before it maps it again, and what was shown went
  1569. /// black for the pictures in between (session play-1125-0127: faces,
  1570. /// books, posters and sleeves for 0.3 to 2 s). Only when it is still
  1571. /// away `AWAY_MS` after it was first found away
  1572. /// (`VICTORY_TEXTURE_AWAY_MS`; 0: at once, as before).
  1573. pub(crate) fn texture_slot_gone(&self, index: u32) -> bool {
  1574. const AWAY_MS: u64 = 3000;
  1575. static WAIT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  1576. let wait = *WAIT.get_or_init(|| {
  1577. std::env::var("VICTORY_TEXTURE_AWAY_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(AWAY_MS)
  1578. });
  1579. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1580. let Some(key) = made.get(index as usize).copied().filter(|&key| key != 0) else {
  1581. return false;
  1582. };
  1583. let now = crate::host::now_ms();
  1584. {
  1585. let mut away = self.away.lock().unwrap_or_else(|e| e.into_inner());
  1586. match away.get(&index) {
  1587. Some(&(was, since)) if was == key && now.saturating_sub(since) < wait => return false,
  1588. Some(&(was, _)) if was == key => {
  1589. away.remove(&index);
  1590. }
  1591. _ if wait == 0 => {}
  1592. _ => {
  1593. away.insert(index, (key, now));
  1594. return false;
  1595. }
  1596. }
  1597. }
  1598. self.unmake(&mut made, index);
  1599. STALE[4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1600. true
  1601. }
  1602. /// Whether host slot `index` shows the placed texture the title's record
  1603. /// at `handle` views, by an earlier view of it.
  1604. pub(crate) fn texture_slot_shows_other(&self, index: u32, handle: u64) -> bool {
  1605. let key = record_key(handle);
  1606. let made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1607. let Some(&shown) = made.get(index as usize) else {
  1608. return false;
  1609. };
  1610. if key == 0 || shown == 0 || shown == key {
  1611. return false;
  1612. }
  1613. let view = |key: u64| view_at(key as u32, (key >> 32) as u32);
  1614. matches!((view(shown), view(key)), (Some(a), Some(b)) if same_placed_texture(&a, &b))
  1615. }
  1616. /// Slot `index` is made from the record at `handle` (what it is now)
  1617. /// when `list`, which holds the upload of what that view shows, has run:
  1618. /// until then it shows what it showed. (Made at once, the frames on the
  1619. /// card read the new view before its levels were filled.)
  1620. pub(crate) fn texture_slot_flip(&self, list: &crate::host::HostList, index: u32, handle: u64) {
  1621. let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle));
  1622. list.defer_host(move || {
  1623. let after = crate::host::submissions().0;
  1624. let flip = Flip { after, heap, index, handle, key };
  1625. FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip);
  1626. });
  1627. }
  1628. /// Makes the slots whose new view's upload has run
  1629. /// ([`HostHeap::texture_slot_flip`]); returns how many.
  1630. pub(crate) fn texture_slots_flip(&self) -> usize {
  1631. use std::sync::atomic::Ordering::Relaxed;
  1632. let finished = crate::host::submissions().1;
  1633. let ready: Vec<Flip> = {
  1634. let mut flips = FLIPS.lock().unwrap_or_else(|e| e.into_inner());
  1635. if flips.is_empty() {
  1636. return 0;
  1637. }
  1638. let own = std::ptr::from_ref(self) as usize;
  1639. let (ready, wait): (Vec<Flip>, Vec<Flip>) =
  1640. flips.drain(..).partition(|f| f.after <= finished && f.heap == own);
  1641. *flips = wait;
  1642. ready
  1643. };
  1644. let mut flipped = 0;
  1645. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1646. for f in ready {
  1647. let Some(shown) = made.get_mut(f.index as usize) else {
  1648. continue;
  1649. };
  1650. if *shown == f.key {
  1651. continue;
  1652. }
  1653. // Written again since, or made null: that write is in the queue.
  1654. let view = view_at(f.key as u32, (f.key >> 32) as u32);
  1655. let (true, true, Some(view)) = (f.key != 0 && record_key(f.handle) == f.key, *shown != 0, view) else {
  1656. FLIPPED[1].fetch_add(1, Relaxed);
  1657. continue;
  1658. };
  1659. if let Some(kept) = make(&view, self.at(f.index)) {
  1660. self.put(f.index);
  1661. *shown = f.key;
  1662. self.keep(f.index, kept);
  1663. flipped += 1;
  1664. }
  1665. }
  1666. FLIPPED[0].fetch_add(flipped as u64, Relaxed);
  1667. flipped
  1668. }
  1669. /// The memory of the texture title slot `index` views is there (again):
  1670. /// see [`HostHeap::texture_slot_gone`].
  1671. pub(crate) fn texture_slot_here(&self, index: u32) {
  1672. let mut away = self.away.lock().unwrap_or_else(|e| e.into_inner());
  1673. if !away.is_empty() {
  1674. away.remove(&index);
  1675. }
  1676. }
  1677. /// Makes host slot `index` null again, as it is before its view is
  1678. /// made: a null view of the kind it held.
  1679. fn unmake(&self, made: &mut [u64], index: u32) {
  1680. let Some(key) = made.get_mut(index as usize).map(std::mem::take) else {
  1681. return;
  1682. };
  1683. if key == 0 {
  1684. return;
  1685. }
  1686. match view_at(key as u32, (key >> 32) as u32) {
  1687. Some(view) => null_for(&view, self.at(index)),
  1688. None => null_view(self.at(index)),
  1689. }
  1690. self.put(index);
  1691. self.clear_twin(index);
  1692. self.keep(index, None);
  1693. }
  1694. /// Title slot `index` is a table's ([`HostHeap::tabled`]). `read`: a
  1695. /// draw read it through the table and brought what it views up to
  1696. /// date, so the slot leaves the queue of textures picked by index; the
  1697. /// caller makes the host slot in place ([`HostHeap::mirror`]), as the
  1698. /// pass would have, for a shader that picks it by index all the same.
  1699. pub(crate) fn texture_slot_tabled(&self, index: u32, read: bool) {
  1700. self.tabled_in(index, read, crate::frame::current());
  1701. }
  1702. /// [`HostHeap::texture_slot_tabled`] in frame `frame`.
  1703. fn tabled_in(&self, index: u32, read: bool, frame: u64) {
  1704. use std::sync::atomic::Ordering::Relaxed;
  1705. let Some(stamp) = self.tabled.get(index as usize) else {
  1706. return;
  1707. };
  1708. let now = (frame as u32).wrapping_add(1) & !TABLED_READ;
  1709. let old = stamp.load(Relaxed);
  1710. if !read {
  1711. if old & !TABLED_READ != now {
  1712. stamp.store(now, Relaxed);
  1713. }
  1714. return;
  1715. }
  1716. // Once per slot and frame: tables are read by every draw.
  1717. if old != now | TABLED_READ {
  1718. stamp.store(now | TABLED_READ, Relaxed);
  1719. if tabled_out() {
  1720. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1721. if textures.slots.remove(&index).is_some() {
  1722. TABLED_WRITES[1].fetch_add(1, Relaxed);
  1723. }
  1724. }
  1725. }
  1726. }
  1727. /// Whether title slot `index` was a table's within the last
  1728. /// [`TABLED_FRAMES`] frames before `frame` (never, if such slots are
  1729. /// to be queued as any other).
  1730. fn tabled_lately(&self, index: u32, frame: u64) -> bool {
  1731. let stamp = self.tabled_stamp(index) & !TABLED_READ;
  1732. let now = (frame as u32).wrapping_add(1) & !TABLED_READ;
  1733. tabled_out() && stamp != 0 && u64::from(now.wrapping_sub(stamp)) <= TABLED_FRAMES
  1734. }
  1735. /// What `tabled` holds for title slot `index`; 0: never a table's.
  1736. fn tabled_stamp(&self, index: u32) -> u32 {
  1737. self.tabled
  1738. .get(index as usize)
  1739. .map_or(0, |s| s.load(std::sync::atomic::Ordering::Relaxed))
  1740. }
  1741. /// The queue's part of a write of title slot `index` in `frame`:
  1742. /// `texture`, whether it now holds a view of a texture the title may
  1743. /// fill; `seen` as for [`HostHeap::note_buffer`].
  1744. fn queue_texture(&self, index: u32, texture: bool, seen: bool, frame: u64) {
  1745. let stamp = if tabled_out() { self.tabled_stamp(index) } else { 0 };
  1746. let now = (frame as u32).wrapping_add(1) & !TABLED_READ;
  1747. // A table's slot lately: the draw that reads it uploads its
  1748. // texture, so its write waits for that draw.
  1749. let lately = stamp != 0 && u64::from(now.wrapping_sub(stamp & !TABLED_READ)) <= TABLED_FRAMES;
  1750. // Made now by a draw of this frame that read it through a table:
  1751. // up to date.
  1752. let read_now = seen && stamp == now | TABLED_READ;
  1753. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1754. if texture && !read_now {
  1755. let due = if lately && !seen {
  1756. TABLED_WRITES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1757. frame + TABLED_GRACE
  1758. } else {
  1759. 0
  1760. };
  1761. textures.written(index, frame, due, seen);
  1762. } else {
  1763. textures.remove(index);
  1764. }
  1765. }
  1766. /// Title slot `index` lies in a table a draw reads or had made afresh:
  1767. /// what it holds is the draw's to make ([`HostHeap::copied_tabled`]).
  1768. pub(crate) fn slot_tabled(&self, index: u32) {
  1769. self.tabled_in(index, false, crate::frame::current());
  1770. }
  1771. /// The title slots that hold buffer views.
  1772. pub(crate) fn buffer_slots(&self) -> Vec<u32> {
  1773. let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
  1774. buffers.iter().copied().collect()
  1775. }
  1776. /// Of [`HostHeap::buffer_slots`], those of one of `parts` parts: every
  1777. /// slot is in the same part each time.
  1778. pub(crate) fn buffer_slots_of(&self, part: u32, parts: u32) -> Vec<u32> {
  1779. let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
  1780. buffers.iter().copied().filter(|slot| slot % parts == part).collect()
  1781. }
  1782. /// The title slots whose buffer view was written, or went, since the
  1783. /// last call.
  1784. pub(crate) fn buffer_changes(&self) -> Vec<u32> {
  1785. let mut changed = self.changed.lock().unwrap_or_else(|e| e.into_inner());
  1786. std::mem::take(&mut *changed).into_iter().collect()
  1787. }
  1788. /// Records what title slot `index` now holds for shaders that pick
  1789. /// buffers from the heap: its element stride in the table, and whether
  1790. /// it is a buffer view at all.
  1791. /// `seen`: the slot was not written now, a draw or a pass made its
  1792. /// host slot from what it held.
  1793. /// Returns the title slots whose placed texture view the write made
  1794. /// stale ([`Spans`]): out of the queue of textures already, their host
  1795. /// slots are the caller's to make null (it holds `made`).
  1796. fn note_buffer(&self, index: u32, view: Option<&View>, seen: bool) -> Vec<u32> {
  1797. if self.sampler {
  1798. return Vec::new();
  1799. }
  1800. // Measured for the texture side of the same gap (textures a shader
  1801. // picks by a computed index are neither made, if placed, nor
  1802. // uploaded): slots written with a placed texture view, and with a
  1803. // view of a texture object.
  1804. let texture = match view {
  1805. Some(View::Placed(false, resource, _)) if resource[0] != 1 => {
  1806. PLACED_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1807. true
  1808. }
  1809. Some(View::Shader(r, _)) if crate::resource::buffer_bytes(*r as crate::object::This).is_none() => {
  1810. OBJECT_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1811. true
  1812. }
  1813. _ => false,
  1814. };
  1815. self.queue_texture(index, texture, seen, crate::frame::current());
  1816. // The memory a placed texture view describes. Not for a slot
  1817. // tables read (thousands of writes a frame, each read by its
  1818. // draw): no pass looks at it, and the same texture's view in a
  1819. // slot shaders pick by index says what it says.
  1820. let placed_view = match view {
  1821. Some(View::Placed(false, resource, desc))
  1822. if resource[0] != 1 && !self.tabled_lately(index, crate::frame::current()) =>
  1823. {
  1824. // (And the level the view starts at: word 4 of a texture
  1825. // view's description, after format, dimension, mapping
  1826. // and a pad.)
  1827. let at = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  1828. let held = crate::resource::placed_bytes_from(resource, crate::resource::first_mip(desc));
  1829. Some((resource, at, desc[4], held.map_or(u64::MAX, |held| at.saturating_add(held))))
  1830. }
  1831. _ => None,
  1832. };
  1833. let stale = {
  1834. use std::sync::atomic::Ordering::Relaxed;
  1835. let mut placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
  1836. let span = placed_view.and_then(|(resource, start, first, held)| {
  1837. Some((start, start.saturating_add(placed.bytes(resource)?), first, held))
  1838. });
  1839. match span {
  1840. Some((start, end, first, held)) => {
  1841. SPANNED[0].fetch_min(start, Relaxed);
  1842. SPANNED[1].fetch_max(end, Relaxed);
  1843. placed.rule = stale_rule();
  1844. let stale = placed.note(index, start, end, !seen);
  1845. placed.shows(index, first, held);
  1846. stale
  1847. }
  1848. None => {
  1849. placed.forget(index);
  1850. Vec::new()
  1851. }
  1852. }
  1853. };
  1854. if !stale.is_empty() {
  1855. STALE[0].fetch_add(stale.len() as u64, std::sync::atomic::Ordering::Relaxed);
  1856. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1857. for &slot in &stale {
  1858. textures.remove(slot);
  1859. }
  1860. }
  1861. let stride = view.and_then(view_stride);
  1862. if let Some((_, _, data)) = &self.strides
  1863. && index < victory_shader::emit::SLOT_STRIDES_COUNT
  1864. {
  1865. // SAFETY: inside the mapping; shaders read it while we write (a
  1866. // dword, either value is one the slot had).
  1867. unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0)) };
  1868. }
  1869. let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
  1870. let was = if stride.is_some() {
  1871. buffers.insert(index);
  1872. true
  1873. } else {
  1874. buffers.remove(&index)
  1875. };
  1876. if was {
  1877. self.changed
  1878. .lock()
  1879. .unwrap_or_else(|e| e.into_inner())
  1880. .insert(index);
  1881. }
  1882. stale
  1883. }
  1884. /// Gives back `n` dynamic slots from `first` (an index [`dynamic`]
  1885. /// returned).
  1886. ///
  1887. /// [`dynamic`]: HostHeap::dynamic
  1888. pub(crate) fn release(&self, first: u32, n: u32) {
  1889. let Some(at) = first.checked_sub(self.count) else {
  1890. return;
  1891. };
  1892. let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner());
  1893. let end = (at + n).min(self.dynamic) as usize;
  1894. if let Some(slots) = guard.1.get_mut(at as usize..end) {
  1895. let given = slots.iter().filter(|taken| **taken).count() as u32;
  1896. self.free.fetch_add(given, std::sync::atomic::Ordering::Relaxed);
  1897. self.too_long.store(u32::MAX, std::sync::atomic::Ordering::Relaxed);
  1898. slots.fill(false);
  1899. }
  1900. }
  1901. /// Makes slot `index` (a dynamic one) from `view`; a null view if the
  1902. /// host cannot.
  1903. pub(crate) fn make_at(&self, index: u32, view: &View) {
  1904. let kept = make_twinned(view, self.at(index), self.twin(index));
  1905. if kept.is_none() {
  1906. null_for(view, self.at(index));
  1907. }
  1908. self.put(index);
  1909. self.twin_made(index, kept.is_some() && twinned(view));
  1910. self.keep(index, kept.flatten());
  1911. }
  1912. /// Makes slot `index` read nothing: a null view, or a plain sampler.
  1913. pub(crate) fn make_null(&self, index: u32) {
  1914. if self.sampler {
  1915. self.null_sampler(index);
  1916. } else {
  1917. null_view(self.at(index));
  1918. self.put(index);
  1919. }
  1920. self.clear_twin(index);
  1921. self.keep(index, None);
  1922. }
  1923. /// Where the raw twin of slot `index` is made.
  1924. fn twin(&self, index: u32) -> Option<D3D12_CPU_DESCRIPTOR_HANDLE> {
  1925. (index < self.twins.len() as u32).then(|| staged(self.sampler, 1).unwrap_or_else(|| self.cpu(self.raw + index)))
  1926. }
  1927. /// The raw twin of slot `index` was made by this thread ([`make_twinned`]),
  1928. /// or is a null view if it was not.
  1929. fn twin_made(&self, index: u32, made: bool) {
  1930. if !made {
  1931. return self.clear_twin(index);
  1932. }
  1933. if let Some(shown) = self.twins.get(index as usize) {
  1934. self.put_twin(index);
  1935. shown.store(true, std::sync::atomic::Ordering::Relaxed);
  1936. }
  1937. }
  1938. /// The raw twin of slot `index` is a null view again.
  1939. fn clear_twin(&self, index: u32) {
  1940. if let Some(made) = self.twins.get(index as usize)
  1941. && made.swap(false, std::sync::atomic::Ordering::Relaxed)
  1942. {
  1943. null_buffer_view(self.at(self.raw + index));
  1944. self.put(self.raw + index);
  1945. }
  1946. }
  1947. /// Slot `index` now views `resource` (or nothing of the host's).
  1948. fn keep(&self, index: u32, resource: Option<ID3D12Resource>) {
  1949. let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
  1950. if let Some(slot) = kept.get_mut(index as usize) {
  1951. use windows::core::Interface;
  1952. // The same again: nothing to retire.
  1953. if slot.as_ref().map(Interface::as_raw) == resource.as_ref().map(Interface::as_raw) {
  1954. return;
  1955. }
  1956. // A running submission may still read the old resource through
  1957. // this slot.
  1958. if let Some(old) = std::mem::replace(slot, resource) {
  1959. crate::host::retire(old);
  1960. }
  1961. }
  1962. }
  1963. /// Makes slot `index` (a dynamic one) a raw buffer view of `len` bytes
  1964. /// of `buffer` from byte `offset` (a multiple of 16): a root SRV with a
  1965. /// size, whose reads past it return zeros instead of reaching whatever
  1966. /// the host placed after the buffer.
  1967. pub(crate) fn raw_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) {
  1968. let Some(host) = host() else { return };
  1969. let elements = (len / 4).clamp(1, u64::from(u32::MAX)) as u32;
  1970. let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1971. Format: DXGI_FORMAT_R32_TYPELESS,
  1972. ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
  1973. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  1974. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1975. Buffer: D3D12_BUFFER_SRV {
  1976. FirstElement: offset / 4,
  1977. NumElements: elements,
  1978. StructureByteStride: 0,
  1979. Flags: D3D12_BUFFER_SRV_FLAG_RAW,
  1980. },
  1981. },
  1982. };
  1983. // SAFETY: a slot of our heap and a live buffer covering the range.
  1984. unsafe {
  1985. host.device
  1986. .CreateShaderResourceView(buffer, Some(&desc), self.at(index))
  1987. };
  1988. self.put(index);
  1989. // (Bound by its handle, not read by index.)
  1990. self.clear_twin(index);
  1991. self.keep(index, Some(buffer.clone()));
  1992. }
  1993. /// Makes slot `index` (a dynamic one) a raw buffer view that reads
  1994. /// zeros.
  1995. pub(crate) fn null_raw_at(&self, index: u32) {
  1996. null_buffer_view(self.at(index));
  1997. self.put(index);
  1998. self.clear_twin(index);
  1999. self.keep(index, None);
  2000. }
  2001. /// Makes slot `index` (a dynamic one) a raw unordered access view of
  2002. /// `len` bytes of `buffer` from byte `offset` (a multiple of 16): a
  2003. /// root UAV with a size, whose accesses past it do nothing instead of
  2004. /// reaching whatever the host placed after the buffer.
  2005. pub(crate) fn raw_uav_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) {
  2006. let Some(host) = host() else { return };
  2007. let elements = (len / 4).clamp(1, u64::from(u32::MAX)) as u32;
  2008. let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
  2009. Format: DXGI_FORMAT_R32_TYPELESS,
  2010. ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
  2011. Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 {
  2012. Buffer: D3D12_BUFFER_UAV {
  2013. FirstElement: offset / 4,
  2014. NumElements: elements,
  2015. StructureByteStride: 0,
  2016. CounterOffsetInBytes: 0,
  2017. Flags: D3D12_BUFFER_UAV_FLAG_RAW,
  2018. },
  2019. },
  2020. };
  2021. // SAFETY: a slot of our heap and a live buffer covering the range.
  2022. unsafe {
  2023. host.device.CreateUnorderedAccessView(
  2024. buffer,
  2025. None::<&ID3D12Resource>,
  2026. Some(&desc),
  2027. self.at(index),
  2028. )
  2029. };
  2030. self.put(index);
  2031. self.clear_twin(index);
  2032. self.keep(index, Some(buffer.clone()));
  2033. }
  2034. /// Makes slot `index` (a dynamic one) a raw unordered access view of
  2035. /// nothing: reads give zeros, writes are dropped.
  2036. pub(crate) fn null_raw_uav_at(&self, index: u32) {
  2037. let Some(host) = host() else { return };
  2038. let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
  2039. Format: DXGI_FORMAT_R32_TYPELESS,
  2040. ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
  2041. Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 {
  2042. Buffer: D3D12_BUFFER_UAV {
  2043. NumElements: 1,
  2044. Flags: D3D12_BUFFER_UAV_FLAG_RAW,
  2045. ..Default::default()
  2046. },
  2047. },
  2048. };
  2049. // SAFETY: a slot of our heap; a null resource is allowed with a desc.
  2050. unsafe {
  2051. host.device.CreateUnorderedAccessView(
  2052. None::<&ID3D12Resource>,
  2053. None::<&ID3D12Resource>,
  2054. Some(&desc),
  2055. self.at(index),
  2056. )
  2057. };
  2058. self.put(index);
  2059. self.clear_twin(index);
  2060. self.keep(index, None);
  2061. }
  2062. /// The shader-visible handle of slot `index`.
  2063. pub(crate) fn gpu_handle(&self, index: u32) -> D3D12_GPU_DESCRIPTOR_HANDLE {
  2064. // SAFETY: a live shader-visible heap.
  2065. let start = unsafe { self.heap.GetGPUDescriptorHandleForHeapStart().ptr };
  2066. D3D12_GPU_DESCRIPTOR_HANDLE {
  2067. ptr: start + u64::from(index) * u64::from(self.step),
  2068. }
  2069. }
  2070. /// Makes slot `index` (a dynamic one) a constant buffer view of host
  2071. /// memory, `size` bytes at `gpu` of `buffer`, which the slot holds.
  2072. ///
  2073. /// The list holds it too, until it is reset; the slot shows it until it
  2074. /// is made again, and a shader that picks the slot by an index it
  2075. /// computes from wrong data reads it through there. The list's scratch
  2076. /// chunks go back to the pool and are freed past its limit: session n02
  2077. /// lost the device to a page fault in the memory of three freed ones.
  2078. /// `VICTORY_SLOT_HOLDS=0`: only the list holds it, as before.
  2079. pub(crate) fn constant_at(&self, index: u32, buffer: &ID3D12Resource, gpu: u64, size: u32) {
  2080. static HOLDS: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  2081. let holds = *HOLDS.get_or_init(|| std::env::var_os("VICTORY_SLOT_HOLDS").is_none_or(|v| v != "0"));
  2082. let Some(host) = host() else { return };
  2083. let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC {
  2084. BufferLocation: gpu,
  2085. SizeInBytes: constant_bytes(size),
  2086. };
  2087. // SAFETY: a slot of our heap; the memory is the caller's.
  2088. unsafe {
  2089. host.device
  2090. .CreateConstantBufferView(Some(&desc), self.at(index))
  2091. };
  2092. self.put(index);
  2093. // A program that reads it as raw bytes reads its twin.
  2094. let twin = self.twin(index).filter(|_| desc.SizeInBytes > 0);
  2095. if let Some(twin) = twin {
  2096. // SAFETY: a live buffer that holds the range.
  2097. let first = (gpu - unsafe { buffer.GetGPUVirtualAddress() }) / 4;
  2098. let raw = D3D12_SHADER_RESOURCE_VIEW_DESC {
  2099. Format: DXGI_FORMAT_R32_TYPELESS,
  2100. ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
  2101. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  2102. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  2103. Buffer: D3D12_BUFFER_SRV {
  2104. FirstElement: first,
  2105. NumElements: desc.SizeInBytes / 4,
  2106. StructureByteStride: 0,
  2107. Flags: D3D12_BUFFER_SRV_FLAG_RAW,
  2108. },
  2109. },
  2110. };
  2111. // SAFETY: as above, and a slot of our heaps.
  2112. unsafe { host.device.CreateShaderResourceView(buffer, Some(&raw), twin) };
  2113. }
  2114. self.twin_made(index, twin.is_some());
  2115. // After the descriptor: what it showed is let go when nothing shows
  2116. // it any more.
  2117. self.keep(index, holds.then(|| buffer.clone()));
  2118. }
  2119. /// Where a descriptor for slot `index` is made, then [`HostHeap::put`]:
  2120. /// a slot of this thread's in a heap the card does not see
  2121. /// ([`staged`]), or the slot itself.
  2122. fn at(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  2123. staged(self.sampler, 0).unwrap_or_else(|| self.cpu(index))
  2124. }
  2125. /// The descriptor this thread made last ([`HostHeap::at`]) goes to slot
  2126. /// `index`.
  2127. fn put(&self, index: u32) {
  2128. self.copy_to(index, 0);
  2129. }
  2130. /// The raw twin this thread made last goes to that of slot `index`.
  2131. fn put_twin(&self, index: u32) {
  2132. if self.twin(index).is_some() {
  2133. self.copy_to(self.raw + index, 1);
  2134. }
  2135. }
  2136. fn copy_to(&self, to: u32, which: u32) {
  2137. let (Some(from), Some(host)) = (staged(self.sampler, which), host()) else {
  2138. return; // made in place
  2139. };
  2140. let kind = if self.sampler {
  2141. D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER
  2142. } else {
  2143. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV
  2144. };
  2145. // SAFETY: a slot of our heap, and one of this thread's heap slots.
  2146. unsafe { host.device.CopyDescriptorsSimple(1, self.cpu(to), from, kind) };
  2147. }
  2148. fn cpu(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  2149. D3D12_CPU_DESCRIPTOR_HANDLE {
  2150. ptr: self.cpu + index as usize * self.step as usize,
  2151. }
  2152. }
  2153. /// For a run of records of the title's heap from slot `first`, `step`
  2154. /// bytes each, on a page that changed with no call
  2155. /// (`super::sync_heaps`: the title copies records into its heap as
  2156. /// bytes): the slots whose record is not the one this last saw there.
  2157. ///
  2158. /// The page says only that something on it was written, and `mirror`
  2159. /// by itself would take every buffer or placed-texture record on it for
  2160. /// newly written each time (it leaves such a slot unmade until a draw
  2161. /// or a pass uses it): the texture queue's entry for the slot would
  2162. /// start again, and the buffer pass would look at 2,048 slots for one
  2163. /// that changed.
  2164. /// `records`: their bytes as the caller read them (through the
  2165. /// kernel, which fails on a page the title unmapped meanwhile where a
  2166. /// read in place would fault: the title unmaps heap pages too).
  2167. pub(crate) fn copied_changes(&self, first: u32, records: &[u8], step: usize, out: &mut Vec<u32>) {
  2168. let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
  2169. if copied.is_empty() {
  2170. // Nothing there: a slot never looked at that holds nothing is
  2171. // as it was.
  2172. copied.resize(self.count as usize * step, 0);
  2173. }
  2174. let at = first as usize * step;
  2175. let end = (at + records.len()).min(copied.len());
  2176. let Some(last) = copied.get_mut(at..end) else {
  2177. return;
  2178. };
  2179. let records = &records[..last.len()];
  2180. if last == records {
  2181. return;
  2182. }
  2183. for (n, (old, new)) in last.chunks_exact_mut(step).zip(records.chunks_exact(step)).enumerate() {
  2184. if old != new {
  2185. old.copy_from_slice(new);
  2186. out.push(first + n as u32);
  2187. }
  2188. }
  2189. }
  2190. /// Whether new records of draws' tables are left to the draws
  2191. /// (`VICTORY_HEAP_SYNC=all`: every new record is mirrored at once, as
  2192. /// it first was).
  2193. ///
  2194. /// The title builds each draw's tables in its heap by copying records
  2195. /// there as bytes: 60,000 to 210,000 a frame in its world (session
  2196. /// play-1125-0127), 0.9 microseconds each on the submitting thread and
  2197. /// 1.4 more in the buffer pass they were all handed to, 120 to 600 ms
  2198. /// of every frame, and the draws make what they read of them anyway.
  2199. pub(crate) fn copied_waits(&self) -> bool {
  2200. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  2201. *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SYNC").is_none_or(|v| v != "all"))
  2202. }
  2203. /// Whether a draw read title slot `index` through a table within the
  2204. /// last few frames before `frame` ([`HostHeap::tabled`]): what it holds
  2205. /// is such a draw's to make.
  2206. pub(crate) fn copied_tabled(&self, index: u32, frame: u64) -> bool {
  2207. if !self.copied_waits() {
  2208. return false;
  2209. }
  2210. let stamp = self.tabled_stamp(index) & !TABLED_READ;
  2211. let now = (frame as u32).wrapping_add(1) & !TABLED_READ;
  2212. stamp != 0 && now.wrapping_sub(stamp) & !TABLED_READ <= COPIED_FRAMES
  2213. }
  2214. /// New records the title copied into slots `slots` in `frame` wait for
  2215. /// the draw that may read them through a table.
  2216. pub(crate) fn copied_wait(&self, frame: u64, slots: Vec<u32>) {
  2217. self.waiting.lock().unwrap_or_else(|e| e.into_inner()).push_back((frame, slots));
  2218. }
  2219. /// The slots that have waited long enough at `frame`
  2220. /// ([`HostHeap::copied_wait`]), each once.
  2221. pub(crate) fn copied_before(&self, frame: u64) -> Vec<u32> {
  2222. let mut waiting = self.waiting.lock().unwrap_or_else(|e| e.into_inner());
  2223. let mut out = Vec::new();
  2224. while waiting.front().is_some_and(|(written, _)| written + COPIED_GRACE <= frame) {
  2225. out.extend(waiting.pop_front().into_iter().flat_map(|(_, slots)| slots));
  2226. }
  2227. drop(waiting);
  2228. out.sort_unstable();
  2229. out.dedup();
  2230. out
  2231. }
  2232. /// Makes host slot `index` from the record the title has at `handle`
  2233. /// if it changed since, and returns the view recorded there. Buffer
  2234. /// views are made only for draws (`for_draw`), which also copy their
  2235. /// data: a host copy of a buffer is made on first use.
  2236. pub(crate) fn mirror(&self, index: u32, handle: u64, for_draw: bool) -> Option<View> {
  2237. if index >= self.count {
  2238. // Diagnostic (NVIDIA heap cap): the highest title slot past the
  2239. // host heap seen so far.
  2240. static HIGHEST: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  2241. if HIGHEST.fetch_max(index, std::sync::atomic::Ordering::Relaxed) < index {
  2242. tracing::warn!(
  2243. index,
  2244. count = self.count,
  2245. for_draw,
  2246. "title slot past the host heap"
  2247. );
  2248. }
  2249. return None;
  2250. }
  2251. // SAFETY: the handle is a descriptor slot in title memory.
  2252. let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() };
  2253. // Generations start at 1, so a made slot's key is never 0.
  2254. let key = u64::from(generation) << 32 | u64::from(i);
  2255. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  2256. let view = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten();
  2257. let Some(view) = view else {
  2258. // Not a view of ours (never written, or of a resource the
  2259. // title released): nothing to read.
  2260. if made[index as usize] != 0 {
  2261. made[index as usize] = 0;
  2262. self.make_null(index);
  2263. let _ = self.note_buffer(index, None, false);
  2264. } else if for_draw {
  2265. // Left for later and stale since: out of the sets and the stride table.
  2266. let _ = self.note_buffer(index, None, false);
  2267. }
  2268. return None;
  2269. };
  2270. if made[index as usize] != key {
  2271. // Views of other textures in the memory this one describes
  2272. // are stale: their host slots read nothing from here on, and
  2273. // let go of the host copies they held.
  2274. for stale in self.note_buffer(index, Some(&view), for_draw) {
  2275. if stale != index {
  2276. self.unmake(&mut made, stale);
  2277. }
  2278. }
  2279. // A view of a texture object that has no host copy yet waits
  2280. // for it, as buffer views wait for a draw: the slot is made
  2281. // when the texture is first used (`super::make_waiting`), or
  2282. // here when a draw reads the slot through a table.
  2283. let waiting = if for_draw { None } else { view.waiting_texture() };
  2284. if let Some(texture) = waiting {
  2285. super::wait_for(texture, handle);
  2286. }
  2287. let later = !for_draw && (view.is_buffer() || waiting.is_some());
  2288. // Another view of the placed texture the slot shows already (a
  2289. // title that streams a texture in writes its view again with
  2290. // more mips each time some arrive): the slot goes on showing
  2291. // the old view until a draw or the texture pass makes the new
  2292. // one and uploads what it shows. Made null here, the texture
  2293. // read as nothing for as long as it waited in the queue, every
  2294. // time it got sharper.
  2295. if later
  2296. && keep_views()
  2297. && view_at(made[index as usize] as u32, (made[index as usize] >> 32) as u32)
  2298. .is_some_and(|old| same_placed_texture(&old, &view))
  2299. {
  2300. KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2301. return Some(view);
  2302. }
  2303. made[index as usize] = if later { 0 } else { key };
  2304. let kept = if later {
  2305. None
  2306. } else {
  2307. make_twinned(&view, self.at(index), self.twin(index))
  2308. };
  2309. if kept.is_none() && !self.sampler {
  2310. null_for(&view, self.at(index));
  2311. }
  2312. if kept.is_some() || !self.sampler {
  2313. self.put(index);
  2314. }
  2315. self.twin_made(index, kept.is_some() && twinned(&view));
  2316. self.keep(index, kept.flatten());
  2317. }
  2318. Some(view)
  2319. }
  2320. /// Whether slot `index` is backed by a made host descriptor (tests).
  2321. #[cfg(test)]
  2322. pub(crate) fn made(&self, index: u32) -> bool {
  2323. self.made
  2324. .lock()
  2325. .unwrap_or_else(|e| e.into_inner())
  2326. .get(index as usize)
  2327. .is_some_and(|&key| key != 0)
  2328. }
  2329. /// Whether host slot `index` shows `buffer`; `None` if it shows no
  2330. /// resource (diagnostics: a buffer view's slot must show the host copy
  2331. /// that is brought up to date for it).
  2332. #[cfg(feature = "diagnostics")]
  2333. pub(crate) fn shows(&self, index: u32, buffer: &ID3D12Resource) -> Option<bool> {
  2334. let kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
  2335. let shown = kept.get(index as usize)?.as_ref()?;
  2336. Some(windows::core::Interface::as_raw(shown) == windows::core::Interface::as_raw(buffer))
  2337. }
  2338. /// What the queue of textures picked by index knows of title slot
  2339. /// `index` at `frame`, in a few words (diagnostics).
  2340. #[cfg(feature = "diagnostics")]
  2341. pub(crate) fn texture_slot_state(&self, index: u32, frame: u64) -> String {
  2342. let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  2343. match textures.slots.get(&index) {
  2344. None => "not queued".into(),
  2345. Some(w) => format!(
  2346. "queued due={} written@{} looks={} part_mapped={} recheck={}",
  2347. if w.due <= frame { "now".to_string() } else { format!("@{}", w.due) },
  2348. w.written,
  2349. w.looks,
  2350. w.mapped,
  2351. w.checked.2 != 0
  2352. ),
  2353. }
  2354. }
  2355. /// The view host slot `index` was made from, in a few words, with the
  2356. /// title and host addresses of a buffer view (diagnostics). "null" for
  2357. /// a slot never made or left null.
  2358. #[cfg(feature = "diagnostics")]
  2359. pub(crate) fn describe_slot(&self, index: u32) -> Option<String> {
  2360. let key = *self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize)?;
  2361. if key == 0 {
  2362. return Some("null".into());
  2363. }
  2364. let view = view_at(key as u32, (key >> 32) as u32)?;
  2365. let mut text: String = format!("{view:?}").chars().take(120).collect();
  2366. if let Some((address, len)) = buffer_range(&view) {
  2367. let host = crate::shadow::find(address, len.max(1)).map(|s| s.gpu(address));
  2368. text.push_str(&format!(" title {address:#x}+{len:#x} host {host:#x?}"));
  2369. }
  2370. Some(text)
  2371. }
  2372. }
  2373. /// Slots of this thread's own in heaps the card does not see, two of views
  2374. /// and two of samplers (`which` 0 or 1): descriptors are made there and
  2375. /// copied whole into the heaps it does see. Made in place they are seen half
  2376. /// written: an RX 7900 XTX saw a texture of no size in 4 % of its reads of
  2377. /// slots whose views a thread made over and over (the driver clears the
  2378. /// descriptor and fills it step by step), and none in 8,500 million with the
  2379. /// same descriptors copied, three times as fast
  2380. /// (`indirect::tests::descriptors_written_under_readers`). Title threads and
  2381. /// our passes rewrite slots while submissions run whose shaders pick them;
  2382. /// three device losses of 2026-11-25 (play-1125-0203, n02, n03) were reads of
  2383. /// memory no view names. `VICTORY_VIEW_COPY=0`: made in place, as before.
  2384. fn staged(sampler: bool, which: u32) -> Option<D3D12_CPU_DESCRIPTOR_HANDLE> {
  2385. /// Threads at a time that have slots; more make views in place.
  2386. const THREADS: u32 = 4096;
  2387. struct Stage {
  2388. starts: [usize; 2],
  2389. steps: [usize; 2],
  2390. _heaps: [ID3D12DescriptorHeap; 2],
  2391. }
  2392. // SAFETY: descriptor heaps are free-threaded; each thread has slots of
  2393. // its own.
  2394. unsafe impl Send for Stage {}
  2395. // SAFETY: as above.
  2396. unsafe impl Sync for Stage {}
  2397. static STAGE: std::sync::OnceLock<Option<Stage>> = std::sync::OnceLock::new();
  2398. /// Places given back, and how many were ever given out.
  2399. static PLACES: Mutex<(Vec<u32>, u32)> = Mutex::new((Vec::new(), 0));
  2400. struct Place(Option<u32>);
  2401. impl Drop for Place {
  2402. fn drop(&mut self) {
  2403. if let Some(place) = self.0 {
  2404. PLACES.lock().unwrap_or_else(|e| e.into_inner()).0.push(place);
  2405. }
  2406. }
  2407. }
  2408. thread_local! {
  2409. static PLACE: Place = {
  2410. let mut places = PLACES.lock().unwrap_or_else(|e| e.into_inner());
  2411. Place(places.0.pop().or_else(|| {
  2412. (places.1 < THREADS).then(|| {
  2413. places.1 += 1;
  2414. places.1 - 1
  2415. })
  2416. }))
  2417. };
  2418. }
  2419. let stage = STAGE
  2420. .get_or_init(|| {
  2421. if std::env::var_os("VICTORY_VIEW_COPY").is_some_and(|v| v == "0") {
  2422. return None;
  2423. }
  2424. let host = host()?;
  2425. let make = |kind: D3D12_DESCRIPTOR_HEAP_TYPE| -> Option<ID3D12DescriptorHeap> {
  2426. // SAFETY: plain heap creation.
  2427. unsafe {
  2428. host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  2429. Type: kind,
  2430. NumDescriptors: 2 * THREADS,
  2431. ..Default::default()
  2432. })
  2433. }
  2434. .inspect_err(|e| tracing::warn!(error = %e, "no heap to make views in: they are made in place"))
  2435. .ok()
  2436. };
  2437. let kinds = [D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER];
  2438. let heaps = [make(kinds[0])?, make(kinds[1])?];
  2439. // SAFETY: live heaps, plain queries.
  2440. let (starts, steps) = unsafe {
  2441. (
  2442. [0, 1].map(|i: usize| heaps[i].GetCPUDescriptorHandleForHeapStart().ptr),
  2443. kinds.map(|kind| host.device.GetDescriptorHandleIncrementSize(kind) as usize),
  2444. )
  2445. };
  2446. Some(Stage { starts, steps, _heaps: heaps })
  2447. })
  2448. .as_ref()?;
  2449. // (A thread that is ending has none any more.)
  2450. let place = PLACE.try_with(|p| p.0).ok().flatten()?;
  2451. let kind = usize::from(sampler);
  2452. Some(D3D12_CPU_DESCRIPTOR_HANDLE {
  2453. ptr: stage.starts[kind] + (2 * place + which) as usize * stage.steps[kind],
  2454. })
  2455. }
  2456. /// Logs `what` the first time it happens.
  2457. macro_rules! once {
  2458. ($($arg:tt)*) => {{
  2459. static ONCE: std::sync::Once = std::sync::Once::new();
  2460. ONCE.call_once(|| tracing::warn!($($arg)*));
  2461. }};
  2462. }
  2463. /// A view description from its words, with the format as the host has it.
  2464. fn srv_desc(words: &[u32; 10]) -> D3D12_SHADER_RESOURCE_VIEW_DESC {
  2465. let mut words = *words;
  2466. words[0] = crate::resource::pc_format(words[0]);
  2467. // SAFETY: 40 bytes in the host's layout.
  2468. unsafe {
  2469. std::ptr::from_ref(&words)
  2470. .cast::<D3D12_SHADER_RESOURCE_VIEW_DESC>()
  2471. .read_unaligned()
  2472. }
  2473. }
  2474. fn uav_desc(words: &[u32; 10]) -> D3D12_UNORDERED_ACCESS_VIEW_DESC {
  2475. let mut words = *words;
  2476. words[0] = crate::resource::pc_format(words[0]);
  2477. // SAFETY: 40 bytes in the host's layout.
  2478. unsafe {
  2479. std::ptr::from_ref(&words)
  2480. .cast::<D3D12_UNORDERED_ACCESS_VIEW_DESC>()
  2481. .read_unaligned()
  2482. }
  2483. }
  2484. /// A buffer view of title memory at `address` on its host copy: the first
  2485. /// element moves by the copy's offset.
  2486. /// Bytes per element of a buffer view.
  2487. fn element_size(desc: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> u64 {
  2488. // SAFETY: a buffer view's union member.
  2489. let buffer = unsafe { desc.Anonymous.Buffer };
  2490. if buffer.StructureByteStride > 0 {
  2491. u64::from(buffer.StructureByteStride)
  2492. } else if buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0 {
  2493. 4
  2494. } else {
  2495. crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
  2496. }
  2497. }
  2498. /// The title memory a buffer shader or unordered access view reads: its
  2499. /// address and length.
  2500. pub(crate) fn buffer_range(view: &View) -> Option<(u64, u64)> {
  2501. let (base, words): (u64, &[u32; 10]) = match view {
  2502. View::Shader(r, Some(desc)) => (
  2503. crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64,
  2504. desc,
  2505. ),
  2506. View::Placed(false, resource, desc) if resource[0] == 1 => (
  2507. u64::from(desc[10]) | u64::from(desc[11]) << 32,
  2508. desc[..10].try_into().ok()?,
  2509. ),
  2510. View::Unordered(r, _, Some(desc)) => {
  2511. let base = crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64;
  2512. return unordered_range(base, desc);
  2513. }
  2514. View::Placed(true, resource, desc) if resource[0] == 1 => {
  2515. let base = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  2516. return unordered_range(base, desc[..10].try_into().ok()?);
  2517. }
  2518. _ => return None,
  2519. };
  2520. let desc = srv_desc(words);
  2521. let element = element_size(&desc);
  2522. // SAFETY: a buffer view's union member.
  2523. let buffer = unsafe { desc.Anonymous.Buffer };
  2524. Some((
  2525. base + buffer.FirstElement * element,
  2526. u64::from(buffer.NumElements) * element,
  2527. ))
  2528. }
  2529. /// The address a shader finds in a descriptor of title memory: where a
  2530. /// buffer view starts, or the ray-tracing structure of a structure's view
  2531. /// (no resource: the view's description holds the address, and the shader
  2532. /// walks the structure from there itself).
  2533. pub(crate) fn view_address(view: &View) -> Option<u64> {
  2534. const STRUCTURE: u32 = D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE.0 as u32;
  2535. match view {
  2536. View::Shader(_, Some(desc)) if desc[1] == STRUCTURE => {
  2537. Some(u64::from(desc[4]) | u64::from(desc[5]) << 32)
  2538. }
  2539. _ => buffer_range(view).map(|range| range.0),
  2540. }
  2541. }
  2542. /// The title memory the host slot of buffer view `view` is made on
  2543. /// (address, bytes): the whole buffer the view is of, which is what
  2544. /// [`make`] finds the host copy by. [`buffer_range`] is the part of it the
  2545. /// view reads.
  2546. pub(crate) fn buffer_extent(view: &View) -> Option<(u64, u64)> {
  2547. match view {
  2548. View::Shader(r, Some(_)) | View::Unordered(r, _, Some(_)) => {
  2549. let (data, len) = crate::resource::buffer_bytes(*r as crate::object::This)?;
  2550. Some((data as u64, len))
  2551. }
  2552. View::Placed(_, resource, desc) if resource[0] == 1 => Some((
  2553. u64::from(desc[10]) | u64::from(desc[11]) << 32,
  2554. u64::from(resource[4]) | u64::from(resource[5]) << 32,
  2555. )),
  2556. _ => None,
  2557. }
  2558. }
  2559. /// Whether a buffer view is brought up to date in the host copy its slot
  2560. /// shows ([`buffer_copy`]). On by default; `VICTORY_VIEW_EXTENT=0` looks the
  2561. /// copy up by the view's range alone, as before.
  2562. fn view_extent() -> bool {
  2563. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  2564. *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_EXTENT").is_none_or(|v| v != "0"))
  2565. }
  2566. /// The host copy buffer view `view` reads, and the title range (address,
  2567. /// bytes) it reads there; `None` for other views and empty ranges.
  2568. ///
  2569. /// The copy is the one the view's slot shows: [`make`] finds it by the
  2570. /// whole buffer the view is of ([`buffer_extent`]). Looked up by the range
  2571. /// the view reads, as it was, the copy is another one wherever the two
  2572. /// lookups differ: for memory outside buffer objects, a view of a part of a
  2573. /// buffer that crosses a window line (the buffer's window is two cells, the
  2574. /// part's one), and for buffer objects, a part that also lies in a smaller
  2575. /// buffer object. The slot then showed a copy nothing brought up to date,
  2576. /// and what shaders wrote through it was looked for in the other copy.
  2577. pub(crate) fn buffer_copy(view: &View) -> Option<(std::sync::Arc<crate::shadow::Shadow>, u64, u64)> {
  2578. let (address, len) = buffer_range(view)?;
  2579. if len == 0 {
  2580. return None;
  2581. }
  2582. if view_extent()
  2583. && let Some((base, width)) = buffer_extent(view)
  2584. // (The console is lax: a view may begin past its buffer's end.)
  2585. && address >= base
  2586. && address - base < width.max(1)
  2587. && let Some(shadow) = crate::shadow::find(base, width)
  2588. {
  2589. return Some((view_home(shadow, address, len, view_elements(view)?), address, len));
  2590. }
  2591. let shadow = crate::shadow::find(address, len)?;
  2592. Some((view_home(shadow, address, len, view_elements(view)?), address, len))
  2593. }
  2594. /// [`buffer_range`] of an unordered access view of memory at `base`.
  2595. fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> {
  2596. let desc = uav_desc(words);
  2597. // SAFETY: a buffer view's union member.
  2598. let buffer = unsafe { desc.Anonymous.Buffer };
  2599. let element = if buffer.StructureByteStride > 0 {
  2600. u64::from(buffer.StructureByteStride)
  2601. } else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 {
  2602. 4
  2603. } else {
  2604. crate::resource::element(desc.Format.0 as u32)?.0
  2605. };
  2606. Some((
  2607. base + buffer.FirstElement * element,
  2608. u64::from(buffer.NumElements) * element,
  2609. ))
  2610. }
  2611. /// The host resource a slot made by [`make`] views, if any.
  2612. type Kept = Option<ID3D12Resource>;
  2613. /// A structured buffer view (`first`, `count` elements of `stride` bytes,
  2614. /// `offset` bytes into its host copy) as a raw view of the same bytes:
  2615. /// its first dword and its dwords. Translated shaders read untyped buffers
  2616. /// as raw bytes at `element * stride + offset` (the stride from the
  2617. /// used-resource entry, or from the table by heap slot for a buffer picked
  2618. /// by index), and a raw read through a structured view gives zeros on
  2619. /// NVIDIA (reported upstream with PR #193; structured reads through raw
  2620. /// views were right there). So the host's view is raw whenever it can be:
  2621. /// the bytes must start on 16 (the host's raw view alignment) and be whole
  2622. /// dwords. A view that cannot stays structured.
  2623. fn raw_window(offset: u64, first: u64, count: u32, stride: u32) -> Option<(u64, u32)> {
  2624. if stride == 0 {
  2625. return None;
  2626. }
  2627. let start = first.checked_mul(u64::from(stride))?.checked_add(offset)?;
  2628. let bytes = u64::from(count) * u64::from(stride);
  2629. (start % 16 == 0 && bytes % 4 == 0)
  2630. .then(|| u32::try_from(bytes / 4).ok().map(|dwords| (start / 4, dwords)))
  2631. .flatten()
  2632. }
  2633. /// Whether the host accepts a buffer view with these fields of a buffer of
  2634. /// `width` bytes. It removes the device for one it does not (view creation
  2635. /// returns nothing), and the console is laxer: the title's heap holds
  2636. /// views past their memory's end, of no elements, of typeless formats
  2637. /// without the raw flag, with strides the host has no structured buffers
  2638. /// for. Since every buffer view of the heap is made for shaders that pick
  2639. /// them by index, one such view ended the run (2026-11-24, run 10).
  2640. fn buffer_view_ok(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bool, width: u64) -> bool {
  2641. use crate::resource::family;
  2642. let f = format.0 as u32;
  2643. let element = if raw {
  2644. // raw: R32 typeless, counted in dwords, starting on 16 bytes
  2645. if format != DXGI_FORMAT_R32_TYPELESS || stride != 0 || !first.is_multiple_of(4) {
  2646. return false;
  2647. }
  2648. 4
  2649. } else if stride > 0 {
  2650. // structured: no format, a stride the host takes
  2651. if format != DXGI_FORMAT_UNKNOWN || stride > 2048 || !stride.is_multiple_of(4) {
  2652. return false;
  2653. }
  2654. u64::from(stride)
  2655. } else {
  2656. // typed: a format with a size that is not typeless
  2657. let typeless = family(f) == f && family(f + 1) == f;
  2658. match crate::resource::element(f) {
  2659. Some((bytes, 1)) if f != 0 && !typeless && bytes > 0 => bytes,
  2660. _ => return false,
  2661. }
  2662. };
  2663. count > 0
  2664. && first
  2665. .checked_add(u64::from(count))
  2666. .and_then(|end| end.checked_mul(element))
  2667. .is_some_and(|end| end <= width)
  2668. }
  2669. /// Raw twins ([`raw_twins`]) made since the last frame line, and those of them that
  2670. /// do not begin on 16 bytes, as a raw view must ([`move_raw`]), and those of
  2671. /// these that could not be moved there (null).
  2672. pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  2673. /// Moves the raw view at `at`, a slot of our heaps the card does not see,
  2674. /// which shows `bytes` from `start` on (GPU address), `by` bytes on: for a
  2675. /// twin whose view begins between two multiples of 16, where the host makes
  2676. /// no raw view. An AMD descriptor of a raw buffer is its address (48 bits),
  2677. /// its bytes and flags; only one that says just that is changed, and only
  2678. /// where what the handle points at is the descriptor. False: not moved.
  2679. fn move_raw(at: D3D12_CPU_DESCRIPTOR_HANDLE, start: u64, bytes: u32, by: u32) -> bool {
  2680. if !by.is_multiple_of(4) || by >= bytes {
  2681. return false;
  2682. }
  2683. let mut words = [0u8; 16];
  2684. if !crate::host::read_into(at.ptr as *const u8, &mut words) {
  2685. return false;
  2686. }
  2687. let word = |i: usize| u32::from_le_bytes([words[4 * i], words[4 * i + 1], words[4 * i + 2], words[4 * i + 3]]);
  2688. let address = u64::from(word(0)) | u64::from(word(1)) << 32;
  2689. if address != start || word(2) != bytes || start >> 48 != 0 {
  2690. return false;
  2691. }
  2692. let moved = start + u64::from(by);
  2693. // SAFETY: this thread's own slot (it has slots of its own: the caller
  2694. // asks only for those), read just now.
  2695. unsafe {
  2696. let words = at.ptr as *mut u32;
  2697. words.write(moved as u32);
  2698. words.add(1).write((moved >> 32) as u32);
  2699. words.add(2).write(bytes - by);
  2700. }
  2701. true
  2702. }
  2703. /// The bytes a buffer view the host takes ([`buffer_view_ok`]) shows as a raw
  2704. /// view (first dword, dwords, and the bytes past that dword it begins: a raw
  2705. /// view begins on 16 bytes); of a buffer of `width` bytes.
  2706. fn twin_window(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bool, width: u64) -> Option<(u64, u32, u32)> {
  2707. use std::sync::atomic::Ordering::Relaxed;
  2708. TWINS[0].fetch_add(1, Relaxed);
  2709. let element = if raw {
  2710. 4
  2711. } else if stride > 0 {
  2712. u64::from(stride)
  2713. } else {
  2714. crate::resource::element(format.0 as u32).map_or(0, |(bytes, _)| bytes)
  2715. };
  2716. let (start, end) = (first * element, ((first + u64::from(count)) * element).next_multiple_of(4));
  2717. let end = end.min(width & !3);
  2718. let from = start & !15;
  2719. if end <= start {
  2720. return None;
  2721. }
  2722. let dwords = u32::try_from((end - from) / 4).ok()?;
  2723. if from != start {
  2724. TWINS[1].fetch_add(1, Relaxed);
  2725. }
  2726. Some((from / 4, dwords, (start - from) as u32))
  2727. }
  2728. fn buffer_srv(
  2729. address: u64,
  2730. len: u64,
  2731. mut desc: D3D12_SHADER_RESOURCE_VIEW_DESC,
  2732. at: D3D12_CPU_DESCRIPTOR_HANDLE,
  2733. twin: Option<D3D12_CPU_DESCRIPTOR_HANDLE>,
  2734. ) -> Option<Kept> {
  2735. let mut shadow = crate::shadow::find(address, len)?;
  2736. let mut offset = shadow.offset(address);
  2737. let unit = element_size(&desc);
  2738. // SAFETY: a buffer view's union member.
  2739. let own = unsafe { &mut desc.Anonymous.Buffer };
  2740. let start = address + own.FirstElement * unit;
  2741. let kind = (own.StructureByteStride, own.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0, desc.Format.0 as u32);
  2742. let home = view_home(shadow.clone(), start, u64::from(own.NumElements) * unit, kind);
  2743. if !std::sync::Arc::ptr_eq(&home, &shadow) {
  2744. // Its own bytes: it begins where they do.
  2745. (shadow, offset) = (home, 0);
  2746. own.FirstElement = 0;
  2747. }
  2748. // A structured view as a raw view of the same bytes (see `raw_window`).
  2749. // SAFETY: a buffer view's union member.
  2750. let structured = unsafe { desc.Anonymous.Buffer };
  2751. let window = (desc.Format == DXGI_FORMAT_UNKNOWN)
  2752. .then(|| raw_window(offset, structured.FirstElement, structured.NumElements, structured.StructureByteStride))
  2753. .flatten();
  2754. if let Some((first, count)) = window {
  2755. desc.Format = DXGI_FORMAT_R32_TYPELESS;
  2756. desc.Anonymous.Buffer = D3D12_BUFFER_SRV {
  2757. FirstElement: first,
  2758. NumElements: count,
  2759. StructureByteStride: 0,
  2760. Flags: D3D12_BUFFER_SRV_FLAG_RAW,
  2761. };
  2762. }
  2763. let element = element_size(&desc);
  2764. // SAFETY: a buffer view's union member.
  2765. let buffer = unsafe { &mut desc.Anonymous.Buffer };
  2766. if window.is_none() {
  2767. if element == 0 || offset % element != 0 {
  2768. once!(
  2769. offset,
  2770. element,
  2771. "buffer view not on an element of its host copy"
  2772. );
  2773. return None;
  2774. }
  2775. buffer.FirstElement += offset / element;
  2776. }
  2777. let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride);
  2778. let raw = buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0;
  2779. // SAFETY: a live buffer.
  2780. let width = unsafe { shadow.buffer.GetDesc() }.Width;
  2781. if !buffer_view_ok(desc.Format, first, count, stride, raw, width) {
  2782. REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2783. once!(
  2784. format = desc.Format.0,
  2785. first,
  2786. count,
  2787. stride,
  2788. raw,
  2789. width,
  2790. "buffer view the host would refuse left null"
  2791. );
  2792. return None;
  2793. }
  2794. // The console has no component mapping; one the host does not know is the default's.
  2795. if desc.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING {
  2796. desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  2797. }
  2798. let host = host()?;
  2799. // SAFETY: a live buffer and a slot of our heap.
  2800. unsafe {
  2801. host.device
  2802. .CreateShaderResourceView(&shadow.buffer, Some(&desc), at)
  2803. };
  2804. if let Some(twin) = twin {
  2805. let window = twin_window(desc.Format, first, count, stride, raw, width);
  2806. if let Some((first, count, by)) = window {
  2807. desc.Format = DXGI_FORMAT_R32_TYPELESS;
  2808. desc.Anonymous.Buffer = D3D12_BUFFER_SRV {
  2809. FirstElement: first,
  2810. NumElements: count,
  2811. StructureByteStride: 0,
  2812. Flags: D3D12_BUFFER_SRV_FLAG_RAW,
  2813. };
  2814. // SAFETY: a live buffer and a slot of our heap.
  2815. let start = unsafe {
  2816. host.device
  2817. .CreateShaderResourceView(&shadow.buffer, Some(&desc), twin);
  2818. shadow.buffer.GetGPUVirtualAddress() + first * 4
  2819. };
  2820. if by > 0 && !(staged(false, 1).is_some_and(|s| s.ptr == twin.ptr) && move_raw(twin, start, count.saturating_mul(4), by)) {
  2821. TWINS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2822. null_buffer_view(twin);
  2823. }
  2824. } else {
  2825. null_buffer_view(twin);
  2826. }
  2827. }
  2828. Some(Some(shadow.buffer.clone()))
  2829. }
  2830. /// An unordered access view of title buffer memory at `address` (`len`
  2831. /// bytes) on its host copy, as [`buffer_srv`]; false if the copy cannot be
  2832. /// written by shaders (upload memory).
  2833. /// shortcut: what shaders write stays in the host copy; title memory (and
  2834. /// so the CPU, and copies run on the CPU) does not see it.
  2835. fn buffer_uav(
  2836. address: u64,
  2837. len: u64,
  2838. mut desc: D3D12_UNORDERED_ACCESS_VIEW_DESC,
  2839. at: D3D12_CPU_DESCRIPTOR_HANDLE,
  2840. twin: Option<D3D12_CPU_DESCRIPTOR_HANDLE>,
  2841. ) -> Option<Kept> {
  2842. let mut shadow = crate::shadow::find(address, len)?;
  2843. let unit = {
  2844. // SAFETY: a buffer view's union member.
  2845. let b = unsafe { desc.Anonymous.Buffer };
  2846. if b.StructureByteStride > 0 {
  2847. u64::from(b.StructureByteStride)
  2848. } else if b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 {
  2849. 4
  2850. } else {
  2851. crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
  2852. }
  2853. };
  2854. // SAFETY: a buffer view's union member.
  2855. let own = unsafe { &mut desc.Anonymous.Buffer };
  2856. let start = address + own.FirstElement * unit;
  2857. let kind = (own.StructureByteStride, own.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0, desc.Format.0 as u32);
  2858. let home = view_home(shadow.clone(), start, u64::from(own.NumElements) * unit, kind);
  2859. let mut address = address;
  2860. if !std::sync::Arc::ptr_eq(&home, &shadow) {
  2861. // Its own bytes: it begins where they do.
  2862. (shadow, address) = (home, start);
  2863. own.FirstElement = 0;
  2864. }
  2865. // SAFETY: a live buffer.
  2866. let flags = unsafe { shadow.buffer.GetDesc() }.Flags;
  2867. if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 {
  2868. once!("unordered access to a buffer whose host copy shaders cannot write");
  2869. return None;
  2870. }
  2871. // SAFETY: a buffer view's union member.
  2872. let buffer = unsafe { &mut desc.Anonymous.Buffer };
  2873. let element = if buffer.StructureByteStride > 0 {
  2874. u64::from(buffer.StructureByteStride)
  2875. } else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 {
  2876. 4
  2877. } else {
  2878. crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
  2879. };
  2880. let offset = shadow.offset(address);
  2881. // A structured view as a raw view of the same bytes (see `raw_window`).
  2882. let window = (desc.Format == DXGI_FORMAT_UNKNOWN)
  2883. .then(|| raw_window(offset, buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride))
  2884. .flatten();
  2885. if let Some((first, count)) = window {
  2886. buffer.FirstElement = first;
  2887. buffer.NumElements = count;
  2888. buffer.StructureByteStride = 0;
  2889. buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
  2890. } else {
  2891. if element == 0 || offset % element != 0 {
  2892. once!(offset, element, "unordered buffer view not on an element of its host copy");
  2893. return None;
  2894. }
  2895. buffer.FirstElement += offset / element;
  2896. }
  2897. buffer.CounterOffsetInBytes = 0;
  2898. let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride);
  2899. let raw = buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0;
  2900. if window.is_some() {
  2901. // (Left out at first: every structured unordered access view was then
  2902. // refused by `buffer_view_ok` and left null, runs 15 and 16.)
  2903. desc.Format = DXGI_FORMAT_R32_TYPELESS;
  2904. }
  2905. // SAFETY: a live buffer.
  2906. let width = unsafe { shadow.buffer.GetDesc() }.Width;
  2907. if !buffer_view_ok(desc.Format, first, count, stride, raw, width) {
  2908. REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2909. once!(
  2910. format = desc.Format.0,
  2911. first,
  2912. count,
  2913. stride,
  2914. raw,
  2915. width,
  2916. "unordered buffer view the host would refuse left null"
  2917. );
  2918. return None;
  2919. }
  2920. let host = host()?;
  2921. // SAFETY: a live buffer and a slot of our heap.
  2922. unsafe {
  2923. host.device
  2924. .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at)
  2925. };
  2926. if let Some(twin) = twin {
  2927. let window = twin_window(desc.Format, first, count, stride, raw, width);
  2928. if let Some((first, count, by)) = window {
  2929. desc.Format = DXGI_FORMAT_R32_TYPELESS;
  2930. desc.Anonymous.Buffer = D3D12_BUFFER_UAV {
  2931. FirstElement: first,
  2932. NumElements: count,
  2933. StructureByteStride: 0,
  2934. CounterOffsetInBytes: 0,
  2935. Flags: D3D12_BUFFER_UAV_FLAG_RAW,
  2936. };
  2937. // SAFETY: a live buffer and a slot of our heap.
  2938. let start = unsafe {
  2939. host.device
  2940. .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), twin);
  2941. shadow.buffer.GetGPUVirtualAddress() + first * 4
  2942. };
  2943. if by > 0 && !(staged(false, 1).is_some_and(|s| s.ptr == twin.ptr) && move_raw(twin, start, count.saturating_mul(4), by)) {
  2944. TWINS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2945. null_buffer_view(twin);
  2946. }
  2947. } else {
  2948. null_buffer_view(twin);
  2949. }
  2950. }
  2951. Some(Some(shadow.buffer.clone()))
  2952. }
  2953. /// Whether the host can make a shader (or unordered access) view of
  2954. /// `texture` in `format` (none: the texture's own). The console allows any
  2955. /// view; the host refuses (and removes the device for) views without the
  2956. /// resource's permission, of typed depth, and in another format than a
  2957. /// typed resource's. A view of a typed texture in another format of its
  2958. /// family takes the texture's format.
  2959. /// shortcut: such a view (sRGB of UNORM, say) reads without its
  2960. /// conversion; cast with castable formats if colors come out wrong.
  2961. fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordered: bool) -> bool {
  2962. use crate::resource::{DEPTH_FORMATS, family};
  2963. // SAFETY: a live resource.
  2964. let d = unsafe { texture.GetDesc() };
  2965. let allowed = if unordered {
  2966. d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0
  2967. } else {
  2968. d.Flags.0 & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE.0 == 0
  2969. };
  2970. let own = d.Format.0 as u32;
  2971. if !allowed || DEPTH_FORMATS.iter().any(|&(typed, _)| typed == own) {
  2972. if unordered {
  2973. crate::resource::DEPTH_UNORDERED[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2974. }
  2975. once!(
  2976. unordered,
  2977. format = own,
  2978. flags = d.Flags.0,
  2979. "view the host does not allow"
  2980. );
  2981. return false;
  2982. }
  2983. // Every family has more than one format, its typeless one first.
  2984. let typeless = family(own) == own && family(own + 1) == own;
  2985. if let Some(format) = format.as_deref_mut()
  2986. && unordered
  2987. && let Some(&(_, linear)) = crate::resource::SRGB
  2988. .iter()
  2989. .find(|&&(s, _)| s == format.0 as u32)
  2990. {
  2991. format.0 = linear as i32;
  2992. }
  2993. let view = format.as_ref().map_or(0, |f| f.0 as u32);
  2994. if view == 0 {
  2995. return !typeless;
  2996. }
  2997. // A view of a target whose format the host refuses, in the title's
  2998. // format: in the stand-in the host copy has.
  2999. if view != own && crate::resource::target_format(view) == own {
  3000. if let Some(format) = format {
  3001. *format = d.Format;
  3002. }
  3003. return true;
  3004. }
  3005. if family(view) != family(own) {
  3006. once!(view, own, "view format of another family");
  3007. return false;
  3008. }
  3009. if let Some(format) = format
  3010. && !typeless
  3011. {
  3012. *format = d.Format;
  3013. }
  3014. true
  3015. }
  3016. /// The title's unordered access view of a depth texture, as a view of the
  3017. /// texture's colour twin `twin` ([`crate::resource::Twin`]): the same mip
  3018. /// and slices, in the colour format of the twin's family for a depth or
  3019. /// typeless format (R16_UNORM for 16-bit depth, R32_FLOAT for 32-bit; the
  3020. /// bits are the same). Without a description: mip 0 of every slice.
  3021. /// The twin of a stencil plane (R8) stands for the views of that plane
  3022. /// only, which become R8_UINT views of its one plane; `None` for a view of
  3023. /// the depth plane, which the twin does not stand for. The depth plane has
  3024. /// a twin of its own, viewed as a depth texture's without stencil: a view
  3025. /// in the format of the depth plane of a depth-stencil format (21, 46)
  3026. /// takes the twin's colour format too.
  3027. fn twin_uav(
  3028. twin: &ID3D12Resource,
  3029. desc: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>,
  3030. ) -> Option<D3D12_UNORDERED_ACCESS_VIEW_DESC> {
  3031. // SAFETY: a live resource.
  3032. let d = unsafe { twin.GetDesc() };
  3033. let mut desc = desc.cloned().unwrap_or_else(|| {
  3034. let mut all = D3D12_UNORDERED_ACCESS_VIEW_DESC {
  3035. ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D,
  3036. ..Default::default()
  3037. };
  3038. if d.DepthOrArraySize > 1 {
  3039. all.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
  3040. all.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV {
  3041. ArraySize: u32::from(d.DepthOrArraySize),
  3042. ..Default::default()
  3043. };
  3044. }
  3045. all
  3046. });
  3047. // A stencil plane's twin (R8 typeless, 60): the title's view is of the
  3048. // stencil plane if it names plane 1 or a stencil view format (22, 47).
  3049. if d.Format.0 == 60 {
  3050. let mut plane = 0;
  3051. match desc.ViewDimension {
  3052. D3D12_UAV_DIMENSION_TEXTURE2D => {
  3053. // SAFETY: the member the dimension names.
  3054. let mut view = unsafe { desc.Anonymous.Texture2D };
  3055. plane = std::mem::take(&mut view.PlaneSlice);
  3056. desc.Anonymous.Texture2D = view;
  3057. }
  3058. D3D12_UAV_DIMENSION_TEXTURE2DARRAY => {
  3059. // SAFETY: the member the dimension names.
  3060. let mut view = unsafe { desc.Anonymous.Texture2DArray };
  3061. plane = std::mem::take(&mut view.PlaneSlice);
  3062. desc.Anonymous.Texture2DArray = view;
  3063. }
  3064. _ => {}
  3065. }
  3066. if plane != 1 && !matches!(desc.Format.0, 22 | 47) {
  3067. return None;
  3068. }
  3069. desc.Format.0 = 62;
  3070. return Some(desc);
  3071. }
  3072. // None, typeless and depth formats (R16: 0, 53, 55; R32: 0, 39, 40),
  3073. // and those of a depth-stencil format's depth plane (19 to 21, 44 to
  3074. // 46), for the twin of such a plane.
  3075. desc.Format.0 = match (desc.Format.0, d.Format.0) {
  3076. (0 | 53 | 55 | 19..=21 | 44..=46, 53) => 56,
  3077. (0 | 39 | 40 | 19..=21 | 44..=46, 39) => 41,
  3078. (other, _) => other,
  3079. };
  3080. Some(desc)
  3081. }
  3082. /// The bytes of the host's constant buffer view for a title's of `size`:
  3083. /// whole 256s, and at most the 64 KiB a shader can index. The host removes
  3084. /// the device for a larger view, and the title's heap holds such sizes in
  3085. /// slots it does not use.
  3086. fn constant_bytes(size: u32) -> u32 {
  3087. const LARGEST: u32 = 64 << 10;
  3088. size.min(LARGEST).next_multiple_of(256)
  3089. }
  3090. /// Makes the host descriptor for `view` at `at`: the host resource it
  3091. /// views, or `None` if it cannot.
  3092. fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<Kept> {
  3093. make_twinned(view, at, None)
  3094. }
  3095. /// [`make`]; `twin`: where the raw twin of a buffer view goes
  3096. /// ([`raw_twins`]; a constant buffer's is the same view again, other views
  3097. /// have none).
  3098. fn make_twinned(
  3099. view: &View,
  3100. at: D3D12_CPU_DESCRIPTOR_HANDLE,
  3101. twin: Option<D3D12_CPU_DESCRIPTOR_HANDLE>,
  3102. ) -> Option<Kept> {
  3103. let host = host()?;
  3104. let device = &host.device;
  3105. match view {
  3106. &View::Constant(address, size) => {
  3107. let shadow = crate::shadow::find(address, u64::from(size))?;
  3108. let gpu = shadow.gpu(address);
  3109. if gpu % 256 != 0 {
  3110. once!(
  3111. address = format_args!("{address:#x}"),
  3112. "constant buffer not 256-byte aligned on the host"
  3113. );
  3114. return None;
  3115. }
  3116. let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC {
  3117. BufferLocation: gpu,
  3118. SizeInBytes: constant_bytes(size),
  3119. };
  3120. // SAFETY: slots of our heap; the range lies in the host copy.
  3121. unsafe {
  3122. device.CreateConstantBufferView(Some(&desc), at);
  3123. if let Some(twin) = twin {
  3124. device.CreateConstantBufferView(Some(&desc), twin);
  3125. }
  3126. }
  3127. Some(Some(shadow.buffer.clone()))
  3128. }
  3129. View::Shader(resource, desc) => {
  3130. let resource = *resource as crate::object::This;
  3131. if let Some(copy) = crate::resource::host_copy(resource) {
  3132. let texture = &copy.texture;
  3133. // The title's views of textures with a stencil plane, as it
  3134. // describes them (format, dimension, component mapping, a
  3135. // pad, then first level, levels, plane): each distinct one
  3136. // once. They say how its shaders read the stencil plane
  3137. // (the lighting takes each pixel's material class and its
  3138. // "inside a room" bit from it).
  3139. #[cfg(feature = "diagnostics")]
  3140. {
  3141. // SAFETY: a live resource.
  3142. let own = unsafe { texture.GetDesc() }.Format.0;
  3143. if matches!(own, 19..=22 | 44..=47) {
  3144. static SEEN: Mutex<Vec<(i32, Option<[u32; 10]>)>> = Mutex::new(Vec::new());
  3145. let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
  3146. if seen.len() < 64 && !seen.contains(&(own, *desc)) {
  3147. seen.push((own, *desc));
  3148. tracing::info!(
  3149. ?resource,
  3150. texture_format = own,
  3151. view = ?desc,
  3152. "shader view of a depth-stencil texture"
  3153. );
  3154. }
  3155. }
  3156. }
  3157. let mut desc = desc.as_ref().map(srv_desc);
  3158. if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) {
  3159. return None;
  3160. }
  3161. // Levels on demand (`crate::tiles`): a texture made level by
  3162. // level is shown from the first level that is the title's
  3163. // and has memory, if the title's view starts before it (a
  3164. // level without memory reads zeros: a black texture). The
  3165. // title's own view mostly starts there already.
  3166. if let Some(first) = crate::resource::first_shown(resource)
  3167. && first > 0
  3168. {
  3169. // SAFETY: a live resource.
  3170. let own = unsafe { texture.GetDesc() };
  3171. // The texture's own view (the title gave none): all of it.
  3172. let whole = D3D12_SHADER_RESOURCE_VIEW_DESC {
  3173. Format: own.Format,
  3174. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
  3175. Shader4ComponentMapping: 5768,
  3176. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  3177. Texture2D: D3D12_TEX2D_SRV {
  3178. MostDetailedMip: 0,
  3179. MipLevels: u32::MAX,
  3180. PlaneSlice: 0,
  3181. ResourceMinLODClamp: 0.0,
  3182. },
  3183. },
  3184. };
  3185. crate::tiles::show_from(desc.get_or_insert(whole), first, u32::from(own.MipLevels));
  3186. }
  3187. if copy.base > 0
  3188. && let Some(desc) = &mut desc
  3189. {
  3190. from_base(desc, copy.base);
  3191. }
  3192. // SAFETY: a live texture and a slot of our heap.
  3193. unsafe {
  3194. device.CreateShaderResourceView(
  3195. texture,
  3196. desc.as_ref().map(std::ptr::from_ref),
  3197. at,
  3198. )
  3199. };
  3200. Some(Some(texture.clone()))
  3201. } else if let (Some((data, len)), Some(desc)) =
  3202. (crate::resource::buffer_bytes(resource), desc)
  3203. {
  3204. buffer_srv(data as u64, len, srv_desc(desc), at, twin)
  3205. } else {
  3206. None
  3207. }
  3208. }
  3209. View::Unordered(resource, _counter, desc) => {
  3210. let resource = *resource as crate::object::This;
  3211. let Some(texture) = crate::resource::host_resource(resource) else {
  3212. return match (crate::resource::buffer_bytes(resource), desc) {
  3213. (Some((data, len)), Some(desc)) => {
  3214. buffer_uav(data as u64, len, uav_desc(desc), at, twin)
  3215. }
  3216. _ => None,
  3217. };
  3218. };
  3219. // The first such views of depth textures are logged as the
  3220. // title describes them (format, dimension, then mip, slices and
  3221. // plane): they say which planes shaders write, and as what.
  3222. if crate::resource::depth_and_unordered(resource) {
  3223. static LOGGED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  3224. if LOGGED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 512 {
  3225. tracing::info!(
  3226. ?resource,
  3227. view = ?desc,
  3228. "unordered access view of a depth texture"
  3229. );
  3230. }
  3231. }
  3232. let mut desc = desc.as_ref().map(uav_desc);
  3233. // A depth texture's unordered access is its colour twin's: the
  3234. // host gives a depth texture none.
  3235. let twin = crate::resource::twin_resource(resource)
  3236. .and_then(|twin| Some((twin, twin_uav(twin, desc.as_ref())?)))
  3237. // A view of the depth plane of a texture with a stencil
  3238. // plane: of that plane's own twin.
  3239. .or_else(|| {
  3240. let twin = crate::resource::twin_plane_resource(resource)?;
  3241. Some((twin, twin_uav(twin, desc.as_ref())?))
  3242. });
  3243. let texture = match twin {
  3244. Some((twin, view)) => {
  3245. desc = Some(view);
  3246. twin
  3247. }
  3248. None => texture,
  3249. };
  3250. if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) {
  3251. return None;
  3252. }
  3253. // SAFETY: a live texture and a slot of our heap.
  3254. unsafe {
  3255. device.CreateUnorderedAccessView(
  3256. texture,
  3257. None::<&ID3D12Resource>,
  3258. desc.as_ref().map(std::ptr::from_ref),
  3259. at,
  3260. )
  3261. };
  3262. Some(Some(texture.clone()))
  3263. }
  3264. View::Sampler(words) => {
  3265. // SAFETY: 13 words in the host's layout.
  3266. let desc = unsafe {
  3267. std::ptr::from_ref(words)
  3268. .cast::<D3D12_SAMPLER_DESC>()
  3269. .read_unaligned()
  3270. };
  3271. // SAFETY: a slot of our sampler heap.
  3272. unsafe { device.CreateSampler(&desc, at) };
  3273. Some(None)
  3274. }
  3275. View::ConsoleSampler(words) => {
  3276. let desc = crate::sampler::console(words);
  3277. // SAFETY: a slot of our sampler heap.
  3278. unsafe { device.CreateSampler(&desc, at) };
  3279. Some(None)
  3280. }
  3281. View::Placed(unordered, resource, desc) => {
  3282. if let Some(view) = placed_texture(view) {
  3283. return make(&view, at);
  3284. }
  3285. const BUFFER: u32 = 1;
  3286. if resource[0] != BUFFER {
  3287. // shortcut: unordered access to a texture the title placed
  3288. // itself is not mirrored; give it a resource as shader
  3289. // views of such textures get when a dispatch writes one.
  3290. // Each texture is said once (the first 64), with how many times
  3291. // such a view was asked for so far: what shaders write through
  3292. // them is lost.
  3293. static SAID: Mutex<std::collections::BTreeSet<u64>> = Mutex::new(std::collections::BTreeSet::new());
  3294. static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  3295. let times = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
  3296. let at = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  3297. let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
  3298. if (said.len() < 64 && said.insert(at)) || times.is_power_of_two() {
  3299. tracing::warn!(
  3300. address = format_args!("{at:#x}"),
  3301. times,
  3302. "placed unordered texture view not mirrored (null: writes through it are lost): resource {resource:?}, view {:?}",
  3303. &desc[..10]
  3304. );
  3305. }
  3306. return None;
  3307. }
  3308. // The resource description's width, after the alignment.
  3309. let len = u64::from(resource[4]) | u64::from(resource[5]) << 32;
  3310. let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  3311. let words: &[u32; 10] = desc[..10].try_into().unwrap_or(&[0; 10]);
  3312. // An empty title buffer: nothing to view, and no host copy to
  3313. // look for (#70: such views were in flight at device removals).
  3314. if len == 0 {
  3315. return None;
  3316. }
  3317. if *unordered {
  3318. buffer_uav(address, len, uav_desc(words), at, twin)
  3319. } else {
  3320. buffer_srv(address, len, srv_desc(words), at, twin)
  3321. }
  3322. }
  3323. }
  3324. }
  3325. /// The view `desc` of a texture, of a host copy of its levels from `base`
  3326. /// on (`crate::resource::held_only`). What it shows of larger ones, if any,
  3327. /// is left out.
  3328. fn from_base(desc: &mut D3D12_SHADER_RESOURCE_VIEW_DESC, base: u32) {
  3329. if desc.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D {
  3330. return;
  3331. }
  3332. // SAFETY: the member its dimension says.
  3333. let t = unsafe { &mut desc.Anonymous.Texture2D };
  3334. let lost = base.saturating_sub(t.MostDetailedMip);
  3335. t.MostDetailedMip = t.MostDetailedMip.saturating_sub(base);
  3336. if t.MipLevels != u32::MAX {
  3337. t.MipLevels = t.MipLevels.saturating_sub(lost).max(1);
  3338. }
  3339. t.ResourceMinLODClamp = (t.ResourceMinLODClamp - base as f32).max(0.0);
  3340. }
  3341. /// Writes of a slot with another view of the placed texture it showed,
  3342. /// since the start: the slot kept showing the old view.
  3343. pub(crate) static KEPT_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  3344. /// Whether a slot written with another view of the placed texture it
  3345. /// shows keeps showing the old one until the new is made;
  3346. /// `VICTORY_KEEP_VIEWS=0` makes it null at once, as before.
  3347. fn keep_views() -> bool {
  3348. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  3349. *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_VIEWS").is_none_or(|v| v != "0"))
  3350. }
  3351. /// Whether both are shader views of one texture the title placed in
  3352. /// memory: the same address and the same resource description, whatever
  3353. /// part of it each shows.
  3354. fn same_placed_texture(a: &View, b: &View) -> bool {
  3355. match (a, b) {
  3356. (View::Placed(false, resource, desc), View::Placed(false, other, other_desc)) => {
  3357. // (Words 1 and 13 are the filler of the description's layout, not
  3358. // part of what a texture is: `crate::resource::texture_at`.)
  3359. let same = |from: usize, to: usize| resource[from..to] == other[from..to];
  3360. resource[0] != 1 && resource[0] == other[0] && same(2, 13) && desc[10..12] == other_desc[10..12]
  3361. }
  3362. _ => false,
  3363. }
  3364. }
  3365. /// A shader view of a texture the title placed in memory itself, as a view
  3366. /// of the resource made for that memory (on first use).
  3367. pub(crate) fn placed_texture(view: &View) -> Option<View> {
  3368. const BUFFER: u32 = 1;
  3369. let View::Placed(false, resource, desc) = view else {
  3370. return None;
  3371. };
  3372. if resource[0] == BUFFER {
  3373. return None;
  3374. }
  3375. let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  3376. let texture = crate::resource::texture_at(address, resource)?;
  3377. crate::resource::want_level(texture, crate::resource::first_mip(desc));
  3378. Some(View::Shader(texture as usize, desc[..10].try_into().ok()))
  3379. }
  3380. /// A null view of the kind `view` is, for a slot whose view the host
  3381. /// cannot make: unordered access (to a buffer or a 2D texture) or a shader
  3382. /// view. Writes to it are dropped, reads give zeros.
  3383. fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) {
  3384. let Some(host) = host() else { return };
  3385. let is_buffer = |r: &usize| crate::resource::buffer_bytes(*r as crate::object::This).is_some();
  3386. // Unordered views: whether a buffer, and the title's view dimension.
  3387. let (buffer, dimension) = match view {
  3388. View::Unordered(r, _, desc) => (
  3389. is_buffer(r) || desc.is_some_and(|d| d[1] == 1),
  3390. desc.map(|d| d[1]),
  3391. ),
  3392. View::Placed(true, resource, desc) => (resource[0] == 1, Some(desc[1])),
  3393. // Shader views of buffers read nothing through a null buffer view:
  3394. // a null 2D view where the shader expects a buffer is a mismatch
  3395. // the hardware does not survive in general (GPU-based validation
  3396. // reports it).
  3397. View::Shader(r, desc) if is_buffer(r) || desc.is_some_and(|d| d[1] == 1) => {
  3398. return null_buffer_view(at);
  3399. }
  3400. View::Placed(false, resource, _) if resource[0] == 1 => return null_buffer_view(at),
  3401. // Textures: a null view of the title's dimension (1D, arrays, 3D,
  3402. // cubes), not always 2D.
  3403. View::Shader(_, Some(desc)) => return null_like(desc, at),
  3404. View::Placed(false, _, desc) => {
  3405. return null_like(desc[..10].try_into().unwrap_or(&[0; 10]), at);
  3406. }
  3407. View::Constant(..) => {
  3408. let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC::default();
  3409. // SAFETY: a slot of our heap; a zero location makes a null view.
  3410. return unsafe { host.device.CreateConstantBufferView(Some(&desc), at) };
  3411. }
  3412. _ => return null_view(at),
  3413. };
  3414. let desc = if buffer {
  3415. D3D12_UNORDERED_ACCESS_VIEW_DESC {
  3416. Format: DXGI_FORMAT_R32_UINT,
  3417. ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
  3418. ..Default::default()
  3419. }
  3420. } else {
  3421. null_uav_desc(dimension)
  3422. };
  3423. // SAFETY: a slot of our heap; a null resource is allowed with a desc.
  3424. unsafe {
  3425. host.device.CreateUnorderedAccessView(
  3426. None::<&ID3D12Resource>,
  3427. None::<&ID3D12Resource>,
  3428. Some(&desc),
  3429. at,
  3430. )
  3431. };
  3432. }
  3433. /// A null texture UAV of the title's view dimension (1D, 1D or 2D arrays,
  3434. /// 3D), 2D if it names none: a 2D null view where the shader writes a 3D
  3435. /// texture is a mismatch GPU-based validation reports (the world's wind
  3436. /// field, CS_CopyWindFieldBeforeUpdateWithSmooth, 2026-11-24).
  3437. fn null_uav_desc(dimension: Option<u32>) -> D3D12_UNORDERED_ACCESS_VIEW_DESC {
  3438. let mut desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
  3439. Format: DXGI_FORMAT_R32_UINT,
  3440. ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D,
  3441. ..Default::default()
  3442. };
  3443. match dimension.map(|d| D3D12_UAV_DIMENSION(d as i32)) {
  3444. Some(D3D12_UAV_DIMENSION_TEXTURE1D) => {
  3445. desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D;
  3446. }
  3447. Some(D3D12_UAV_DIMENSION_TEXTURE1DARRAY) => {
  3448. desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY;
  3449. desc.Anonymous.Texture1DArray = D3D12_TEX1D_ARRAY_UAV {
  3450. ArraySize: 1,
  3451. ..Default::default()
  3452. };
  3453. }
  3454. Some(D3D12_UAV_DIMENSION_TEXTURE2DARRAY) => {
  3455. desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
  3456. desc.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV {
  3457. ArraySize: 1,
  3458. ..Default::default()
  3459. };
  3460. }
  3461. Some(D3D12_UAV_DIMENSION_TEXTURE3D) => {
  3462. desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D;
  3463. desc.Anonymous.Texture3D = D3D12_TEX3D_UAV {
  3464. WSize: u32::MAX,
  3465. ..Default::default()
  3466. };
  3467. }
  3468. _ => {}
  3469. }
  3470. desc
  3471. }
  3472. /// A buffer view that reads zeros (raw, as translated shaders mostly read
  3473. /// buffers).
  3474. fn null_buffer_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
  3475. let Some(host) = host() else { return };
  3476. let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
  3477. Format: DXGI_FORMAT_R32_TYPELESS,
  3478. ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
  3479. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  3480. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  3481. Buffer: D3D12_BUFFER_SRV {
  3482. NumElements: 1,
  3483. Flags: D3D12_BUFFER_SRV_FLAG_RAW,
  3484. ..Default::default()
  3485. },
  3486. },
  3487. };
  3488. // SAFETY: a slot of our heap; a null resource is allowed with a desc.
  3489. unsafe {
  3490. host.device
  3491. .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at)
  3492. };
  3493. }
  3494. /// A texture view that reads zeros with the dimension (and mip and array
  3495. /// counts) of the title's description `words`; 2D if it names none.
  3496. fn null_like(words: &[u32; 10], at: D3D12_CPU_DESCRIPTOR_HANDLE) {
  3497. const TEXTURES: std::ops::RangeInclusive<u32> = 2..=10;
  3498. if !TEXTURES.contains(&words[1]) {
  3499. return null_view(at);
  3500. }
  3501. let Some(host) = host() else { return };
  3502. // One mip, one slice or cube, plane 0: fields a null view still checks.
  3503. let mut w = [0u32; 10];
  3504. w[1] = words[1];
  3505. match words[1] {
  3506. 6 => {}
  3507. 7 => w[5] = 1,
  3508. 3 | 5 | 10 => (w[5], w[7]) = (1, 1),
  3509. _ => w[5] = 1,
  3510. }
  3511. let mut desc = srv_desc(&w);
  3512. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  3513. desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  3514. // SAFETY: a slot of our heap; a null resource is allowed with a desc.
  3515. unsafe {
  3516. host.device
  3517. .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at)
  3518. };
  3519. }
  3520. /// A view that reads zeros, for slots whose view the host cannot make.
  3521. /// shortcut: slots with no view at all (kind unknown) get this null 2D
  3522. /// view; null buffer views there did not stop the world's low-address
  3523. /// page faults (2026-11-24, run w10), so they are not the cause.
  3524. fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
  3525. let Some(host) = host() else { return };
  3526. let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
  3527. Format: DXGI_FORMAT_R8G8B8A8_UNORM,
  3528. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
  3529. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  3530. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  3531. Texture2D: D3D12_TEX2D_SRV {
  3532. MipLevels: 1,
  3533. ..Default::default()
  3534. },
  3535. },
  3536. };
  3537. // SAFETY: a slot of our heap; a null resource is allowed with a desc.
  3538. unsafe {
  3539. host.device
  3540. .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at)
  3541. };
  3542. }
  3543. #[cfg(test)]
  3544. mod tests {
  3545. use super::*;
  3546. /// A view of a host copy that begins at a later level shows the same
  3547. /// levels of it.
  3548. #[test]
  3549. fn views_count_from_the_first_level_of_the_host_copy() {
  3550. let view = |first, levels, clamp| {
  3551. let mut desc = srv_desc(&[98, 4, 5768, 0, first, levels, 0, 0, 0, 0]);
  3552. desc.Anonymous.Texture2D.ResourceMinLODClamp = clamp;
  3553. from_base(&mut desc, 3);
  3554. // SAFETY: the member its dimension says.
  3555. let t = unsafe { desc.Anonymous.Texture2D };
  3556. (t.MostDetailedMip, t.MipLevels, t.ResourceMinLODClamp)
  3557. };
  3558. assert_eq!(view(3, 4, 0.0), (0, 4, 0.0));
  3559. assert_eq!(view(5, u32::MAX, 5.5), (2, u32::MAX, 2.5));
  3560. // (Two levels the copy has not.)
  3561. assert_eq!(view(1, 4, 0.0), (0, 2, 0.0));
  3562. }
  3563. /// Memory past the levels a slot's view shows is not its texture's.
  3564. #[test]
  3565. fn a_view_of_smaller_levels_is_not_told_of_memory_past_them() {
  3566. let mut spans = Spans::default();
  3567. spans.note(1, 0x10000, 0x50000, true);
  3568. spans.shows(1, 3, 0x12000);
  3569. spans.note(2, 0x10000, 0x50000, true);
  3570. spans.shows(2, 0, 0x50000);
  3571. assert_eq!(spans.slots_holding(0x11000, 0x11800), vec![1, 2]);
  3572. assert_eq!(spans.slots_holding(0x20000, 0x21000), vec![2]);
  3573. assert_eq!(spans.slots_in(0x20000, 0x21000), vec![2]);
  3574. spans.forget(2);
  3575. assert!(spans.slots_in(0x20000, 0x21000).is_empty());
  3576. assert_eq!(spans.slots_in(0x0, 0x10001), vec![1]);
  3577. }
  3578. /// A texture filled with less than was mapped is looked at again, but
  3579. /// not for ever: memory that is shown and cannot be read ends it, and a
  3580. /// filling that got everything starts the count anew.
  3581. #[test]
  3582. fn a_short_filling_is_looked_at_again_a_few_times() {
  3583. // An address no other test names.
  3584. let start = 0x7fee_1234_0000u64;
  3585. let pending = || super::SHORT.lock().unwrap().0.remove(&start);
  3586. for _ in 0..super::SHORT_IN_A_ROW {
  3587. super::read_short(start);
  3588. assert!(pending());
  3589. }
  3590. super::read_short(start);
  3591. assert!(!pending());
  3592. super::read_all(start);
  3593. super::read_short(start);
  3594. assert!(pending());
  3595. super::read_all(start);
  3596. }
  3597. /// A null texture UAV keeps the title's dimension (3D for the world's
  3598. /// wind field), and is 2D when the title names none.
  3599. #[test]
  3600. fn null_uavs_keep_the_titles_dimension() {
  3601. let d = null_uav_desc(Some(8));
  3602. assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE3D);
  3603. // SAFETY: the member the dimension names.
  3604. assert_eq!(unsafe { d.Anonymous.Texture3D.WSize }, u32::MAX);
  3605. let d = null_uav_desc(Some(5));
  3606. assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE2DARRAY);
  3607. // SAFETY: the member the dimension names.
  3608. assert_eq!(unsafe { d.Anonymous.Texture2DArray.ArraySize }, 1);
  3609. let dimension = |d| null_uav_desc(d).ViewDimension;
  3610. assert_eq!(dimension(Some(2)), D3D12_UAV_DIMENSION_TEXTURE1D);
  3611. assert_eq!(dimension(Some(4)), D3D12_UAV_DIMENSION_TEXTURE2D);
  3612. assert_eq!(dimension(None), D3D12_UAV_DIMENSION_TEXTURE2D);
  3613. // Multisampled UAVs need a cap; they stay 2D.
  3614. assert_eq!(dimension(Some(6)), D3D12_UAV_DIMENSION_TEXTURE2D);
  3615. }
  3616. /// What the texture code asks of the spans (levels on demand): where
  3617. /// the next texture starts inside a span, the lowest level a view of a
  3618. /// texture shows, and a texture's slots.
  3619. #[test]
  3620. fn spans_say_the_next_start_and_the_lowest_level_viewed() {
  3621. let mut spans = Spans::default();
  3622. // A 512x512 texture of 0x56000 bytes viewed from levels 3 and 1,
  3623. // and the next one 0x6000 after it (run 188).
  3624. spans.note(1, 0x1_0000, 0x1_0000 + 0x5_6000, true);
  3625. spans.shows(1, 3, u64::MAX);
  3626. spans.note(2, 0x1_0000, 0x1_0000 + 0x5_6000, true);
  3627. spans.shows(2, 1, u64::MAX);
  3628. spans.note(3, 0x1_6000, 0x1_6000 + 0x5_6000, true);
  3629. assert_eq!(spans.next_start(0x1_0000, 0x1_0000 + 0x5_6000), Some(0x1_6000));
  3630. assert_eq!(spans.next_start(0x1_6000, 0x1_6000 + 0x5_6000), None);
  3631. assert_eq!(spans.first_viewed(0x1_0000), Some(1));
  3632. assert_eq!(spans.first_viewed(0x1_6000), None);
  3633. assert_eq!(spans.slots_at(0x1_0000), vec![1, 2]);
  3634. // The view from level 1 goes: the texture is viewed from level 3.
  3635. spans.forget(2);
  3636. assert_eq!(spans.first_viewed(0x1_0000), Some(3));
  3637. }
  3638. /// Views of one placed texture are told from views of others by the
  3639. /// address and the resource description, not by what they show.
  3640. #[test]
  3641. fn views_of_one_placed_texture_are_told_by_address_and_description() {
  3642. let texture = [3, 0, 0, 0, 512, 0, 512, 0x8_0001, 98, 1, 0, 0x105, 0, 0];
  3643. let view = |resource: [u32; 14], first_mip: u32, address: u32| {
  3644. let mut desc = [0u32; 16];
  3645. (desc[0], desc[1], desc[4], desc[5], desc[10], desc[11]) = (98, 4, first_mip, 8 - first_mip, address, 0xb);
  3646. View::Placed(false, resource, desc)
  3647. };
  3648. let low = view(texture, 3, 0x1000_0000);
  3649. // more mips of the same texture
  3650. assert!(same_placed_texture(&low, &view(texture, 0, 0x1000_0000)));
  3651. // another address, another description, a buffer, an unordered view
  3652. assert!(!same_placed_texture(&low, &view(texture, 3, 0x2000_0000)));
  3653. let mut wider = texture;
  3654. wider[4] = 1024;
  3655. assert!(!same_placed_texture(&low, &view(wider, 3, 0x1000_0000)));
  3656. let mut buffer = texture;
  3657. buffer[0] = 1;
  3658. assert!(!same_placed_texture(&view(buffer, 3, 0x1000_0000), &view(buffer, 3, 0x1000_0000)));
  3659. let View::Placed(_, resource, desc) = low.clone() else { unreachable!() };
  3660. assert!(!same_placed_texture(&low, &View::Placed(true, resource, desc)));
  3661. assert!(!same_placed_texture(&low, &View::Shader(0, None)));
  3662. }
  3663. /// A constant buffer view larger than the host takes is cut to what it
  3664. /// takes: the device, which such a view removes, stays.
  3665. #[test]
  3666. fn an_oversized_constant_buffer_view_leaves_the_device_alive() {
  3667. let Some(host) = host() else {
  3668. return; // no host GPU
  3669. };
  3670. let Some(heap) = HostHeap::new(false, 4) else {
  3671. return;
  3672. };
  3673. // SAFETY: a plain device query.
  3674. let alive = || unsafe { host.device.GetDeviceRemovedReason() }.is_ok();
  3675. // Made first: an allocation that fails on a removed device must not
  3676. // end the test early.
  3677. let (buffer, _) = host.upload_buffer(1 << 20).expect("an upload buffer");
  3678. let memory = vec![0u8; 2 << 20];
  3679. let at = (memory.as_ptr() as u64).next_multiple_of(64 << 10);
  3680. for size in [969_472u32, 896_256] {
  3681. assert!(make(&View::Constant(at, size), heap.cpu(0)).is_some());
  3682. assert!(alive(), "a view of {size} bytes");
  3683. }
  3684. // SAFETY: a live upload buffer.
  3685. heap.constant_at(1, &buffer, unsafe { buffer.GetGPUVirtualAddress() }, 969_472);
  3686. assert!(alive(), "a view of the list's own memory");
  3687. assert_eq!(constant_bytes(480), 512);
  3688. assert_eq!(constant_bytes(64 << 10), 64 << 10);
  3689. assert_eq!(constant_bytes(u32::MAX), 64 << 10);
  3690. }
  3691. /// A null 3D UAV made on the real device leaves it alive.
  3692. #[test]
  3693. fn null_3d_uav_is_accepted_by_the_device() {
  3694. let Some(host) = host() else {
  3695. return; // no host GPU
  3696. };
  3697. let Some(heap) = HostHeap::new(false, 4) else {
  3698. return;
  3699. };
  3700. let view = View::Unordered(0, 0, Some([28, 8, 0, 0, 0, 0, 0, 0, 0, 0]));
  3701. null_for(&view, heap.cpu(0));
  3702. // SAFETY: a plain device query.
  3703. assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok());
  3704. }
  3705. /// Dynamic slots stay taken until given back, and runs do not wrap.
  3706. #[test]
  3707. fn a_structured_view_made_raw_passes_the_host_check() {
  3708. // 100 elements of 20 bytes from element 8, in a copy that starts 32
  3709. // bytes before the view's memory: bytes 192..2192.
  3710. let (first, count) = raw_window(32, 8, 100, 20).unwrap();
  3711. assert_eq!((first, count), (48, 500));
  3712. assert!(buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 4096));
  3713. // the format a raw view must name; the structured one's is refused
  3714. assert!(!buffer_view_ok(DXGI_FORMAT_UNKNOWN, first, count, 0, true, 4096));
  3715. // past the buffer, not on 16 bytes, no elements
  3716. assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 2000));
  3717. assert!(raw_window(4, 0, 100, 20).is_none());
  3718. assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, 0, 0, 0, true, 4096));
  3719. // a structured view the host takes as it is
  3720. assert!(buffer_view_ok(DXGI_FORMAT_UNKNOWN, 1, 10, 12, false, 4096));
  3721. }
  3722. /// The raw twin of a view shows the same bytes: typed and structured ones
  3723. /// that begin on 16 bytes, whole dwords, none past the buffer.
  3724. #[test]
  3725. fn raw_twins_show_the_views_bytes() {
  3726. let (u16s, u32s, none) = (DXGI_FORMAT(57), DXGI_FORMAT(42), DXGI_FORMAT_UNKNOWN);
  3727. assert_eq!(twin_window(u32s, 4, 10, 0, false, 4096), Some((4, 10, 0)));
  3728. assert_eq!(twin_window(u16s, 8, 7, 0, false, 4096), Some((4, 4, 0)));
  3729. // the last dword would reach past the buffer
  3730. assert_eq!(twin_window(u16s, 8, 7, 0, false, 30), Some((4, 3, 0)));
  3731. assert_eq!(twin_window(none, 2, 3, 24, false, 4096), Some((12, 18, 0)));
  3732. assert_eq!(twin_window(DXGI_FORMAT_R32_TYPELESS, 8, 5, 0, true, 4096), Some((8, 5, 0)));
  3733. // where no raw view begins: from the 16 bytes below
  3734. assert_eq!(twin_window(none, 1, 3, 24, false, 4096), Some((4, 20, 8)));
  3735. assert_eq!(twin_window(u32s, 1, 10, 0, false, 4096), Some((0, 11, 4)));
  3736. assert_eq!(twin_window(u32s, 1, 10, 0, false, 4), None);
  3737. }
  3738. /// What a slot is made as is made beside the heap and copied in whole: the
  3739. /// slot's descriptor is the one the view has, and each thread makes its
  3740. /// own.
  3741. #[test]
  3742. fn views_are_made_beside_the_heap_and_copied_in() {
  3743. let Some(host) = host() else {
  3744. return; // no host GPU here
  3745. };
  3746. let Some(heap) = HostHeap::new(false, 4) else {
  3747. return;
  3748. };
  3749. let (Some(a), Some(b)) = (staged(false, 0), staged(false, 1)) else {
  3750. return;
  3751. };
  3752. assert_ne!(a.ptr, b.ptr);
  3753. assert_ne!(Some(a.ptr), std::thread::spawn(|| staged(false, 0).map(|h| h.ptr)).join().unwrap());
  3754. let (buffer, _) = host.shared_buffer(1 << 16).unwrap();
  3755. let index = heap.dynamic(1).unwrap();
  3756. let bytes = |at: D3D12_CPU_DESCRIPTOR_HANDLE| {
  3757. let mut bytes = [0u8; 32];
  3758. crate::host::read_into(at.ptr as *const u8, &mut bytes).then_some(bytes)
  3759. };
  3760. heap.raw_at(index, &buffer, 64, 1024);
  3761. let (slot, beside) = (bytes(heap.cpu(index)), bytes(staged(false, 0).unwrap()));
  3762. assert_eq!(slot, beside, "copied as it was made");
  3763. heap.null_raw_at(index);
  3764. assert_ne!(bytes(heap.cpu(index)), slot, "another view since");
  3765. // SAFETY: a plain query.
  3766. assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok());
  3767. }
  3768. /// A raw view moved on by some dwords says so in its descriptor, on a
  3769. /// card whose descriptors are what we take them for; on another nothing
  3770. /// is changed.
  3771. #[test]
  3772. fn a_raw_view_is_moved_only_where_its_descriptor_says_where_it_is() {
  3773. let (Some(host), Some(at)) = (host(), staged(false, 1)) else {
  3774. return; // no host GPU here
  3775. };
  3776. let (buffer, _) = host.shared_buffer(1 << 16).unwrap();
  3777. let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
  3778. Format: DXGI_FORMAT_R32_TYPELESS,
  3779. ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
  3780. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  3781. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  3782. Buffer: D3D12_BUFFER_SRV {
  3783. FirstElement: 8,
  3784. NumElements: 100,
  3785. StructureByteStride: 0,
  3786. Flags: D3D12_BUFFER_SRV_FLAG_RAW,
  3787. },
  3788. },
  3789. };
  3790. // SAFETY: this thread's slot, a live buffer.
  3791. let start = unsafe {
  3792. host.device.CreateShaderResourceView(&buffer, Some(&desc), at);
  3793. buffer.GetGPUVirtualAddress() + 32
  3794. };
  3795. let words = || {
  3796. let mut bytes = [0u8; 32];
  3797. assert!(crate::host::read_into(at.ptr as *const u8, &mut bytes));
  3798. bytes
  3799. };
  3800. let before = words();
  3801. assert!(!move_raw(at, start + 16, 400, 8), "another address");
  3802. assert!(!move_raw(at, start, 404, 8), "another size");
  3803. assert!(!move_raw(at, start, 400, 2), "not a dword");
  3804. assert_eq!(words(), before);
  3805. if move_raw(at, start, 400, 8) {
  3806. let moved = words();
  3807. assert_eq!(moved[..8], (start + 8).to_le_bytes());
  3808. assert_eq!(moved[8..12], 392u32.to_le_bytes());
  3809. assert_eq!(moved[12..], before[12..]);
  3810. } else {
  3811. assert_eq!(words(), before);
  3812. }
  3813. }
  3814. /// Views that begin where no host view can: raw ones off 16 bytes,
  3815. /// structured ones off their elements (and off 16 bytes, where they are
  3816. /// made raw), typed ones off theirs.
  3817. #[test]
  3818. fn views_off_their_elements_are_told() {
  3819. // the colour table bakes' parameter block: raw, 8 bytes into its window
  3820. assert!(off_elements(8, 0, true, 4));
  3821. assert!(!off_elements(0, 0, true, 4));
  3822. assert!(!off_elements(48, 0, true, 4));
  3823. // 456-byte elements: at one of them, on 16 bytes, at neither
  3824. assert!(!off_elements(456, 456, false, 0));
  3825. assert!(!off_elements(32, 456, false, 0));
  3826. assert!(off_elements(100, 456, false, 0));
  3827. // A typed view of 12-byte elements on 16 bytes and not on an element.
  3828. assert!(off_elements(23_702_896, 0, false, 12));
  3829. assert!(!off_elements(48, 0, false, 12));
  3830. assert!(!off_elements(12, 0, false, 4));
  3831. assert!(off_elements(12, 0, false, 8));
  3832. }
  3833. /// Such a view is made on a copy of its own bytes, and that copy is the one
  3834. /// brought up to date for it; another's is its buffer's.
  3835. #[test]
  3836. fn views_off_their_elements_get_a_copy_of_their_bytes() {
  3837. let Some(host) = host() else {
  3838. return; // no host GPU here
  3839. };
  3840. let memory = vec![0u64; 1 << 13];
  3841. let start = (memory.as_ptr() as u64).next_multiple_of(4096);
  3842. // SAFETY: a plain CPU-side heap of one view.
  3843. let cpu: ID3D12DescriptorHeap = unsafe {
  3844. host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  3845. Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  3846. NumDescriptors: 1,
  3847. ..Default::default()
  3848. })
  3849. }
  3850. .unwrap();
  3851. // SAFETY: a live heap.
  3852. let at = unsafe { cpu.GetCPUDescriptorHandleForHeapStart() };
  3853. // Memory placed at `address`, seen as the title passes it: raw, 32
  3854. // dwords, or four 456-byte elements.
  3855. let view = |address: u64, raw: bool| {
  3856. let resource: [u32; 14] = [1, 0, 0, 0, 4 * 456, 0, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0];
  3857. let mut desc = [0u32; 16];
  3858. let words = if raw {
  3859. [39, 1, 5768, 0, 0, 0, 32, 0, 1, 0]
  3860. } else {
  3861. [0, 1, 5768, 0, 0, 0, 4, 456, 0, 0]
  3862. };
  3863. desc[..10].copy_from_slice(&words);
  3864. (desc[10], desc[11]) = (address as u32, (address >> 32) as u32);
  3865. View::Placed(false, resource, desc)
  3866. };
  3867. let width = |v: &View| {
  3868. let made = make(v, at).expect("a view").expect("a buffer");
  3869. // SAFETY: a live buffer.
  3870. unsafe { made.GetDesc() }.Width
  3871. };
  3872. for (off, raw, len) in [(8, true, 128u64), (8, false, 4 * 456)] {
  3873. let v = view(start + off, raw);
  3874. assert_eq!(width(&v), len.next_multiple_of(256));
  3875. let (copy, address, bytes) = buffer_copy(&v).unwrap();
  3876. assert_eq!((copy.span(), address, bytes), ((start + off, len), start + off, len));
  3877. }
  3878. for (off, raw) in [(16, true), (32, false)] {
  3879. let v = view(start + off, raw);
  3880. let (copy, ..) = buffer_copy(&v).unwrap();
  3881. assert_ne!(copy.span().0, start + off, "its buffer's copy");
  3882. // SAFETY: a live buffer.
  3883. assert_eq!(width(&v), unsafe { copy.buffer.GetDesc() }.Width);
  3884. }
  3885. }
  3886. /// The queue of textures picked by index serves the slots looked at
  3887. /// before first, then the newest write and the oldest in turns; a
  3888. /// slot whose memory is not there is looked at again after
  3889. /// 1, 2, 4 frames up to the limit; and what the pass reports about a
  3890. /// slot written again meanwhile is dropped.
  3891. #[test]
  3892. fn the_texture_queue_serves_the_newest_writes_first() {
  3893. let mut q = TextureQueue::default();
  3894. // Slots 10..18 written in frames 1..9, slot 5 last.
  3895. for i in 0..8u32 {
  3896. q.written(10 + i, u64::from(i) + 1, 0, false);
  3897. }
  3898. q.written(5, 9, 0, false);
  3899. let order: Vec<u32> = q.due(9, 100).into_iter().map(|d| d.0).collect();
  3900. // newest, oldest, newest, oldest, and so on
  3901. assert_eq!(order, [5, 10, 17, 11, 16, 12, 15, 13, 14]);
  3902. assert_eq!(q.due(9, 2).len(), 2);
  3903. assert_eq!(q.census(9), [9, 9, 0, 0, 8]);
  3904. // Slot 17's memory is not mapped: again next frame, then in 2, 4, 4.
  3905. let write = |q: &TextureQueue, index: u32| q.due(u64::MAX, 100).iter().find(|d| d.0 == index).unwrap().1;
  3906. let w17 = write(&q, 17);
  3907. let mut frame = 9;
  3908. for wait in [1, 2, 4, 4] {
  3909. q.later(17, w17, frame, 4);
  3910. assert!(!q.due(frame + wait - 1, 100).iter().any(|d| d.0 == 17));
  3911. frame += wait;
  3912. // Due again, and ahead of every slot never looked at.
  3913. assert_eq!(q.due(frame, 100)[0].0, 17);
  3914. }
  3915. assert_eq!(q.census(9)[2], 1);
  3916. q.done(17, w17);
  3917. assert!(!q.due(u64::MAX, 100).iter().any(|d| d.0 == 17));
  3918. // Uploaded with part of its memory there: kept, with what was there.
  3919. let w16 = write(&q, 16);
  3920. q.partly(16, w16, 12, 4096);
  3921. assert_eq!(q.mapped(16), 4096);
  3922. assert_eq!(q.due(12, 100)[0].0, 16);
  3923. // The title writes slot 16 again while the pass works on it: what
  3924. // the pass then says about the old write changes nothing.
  3925. q.written(16, 13, 0, false);
  3926. q.done(16, w16);
  3927. q.later(16, w16, 13, 4);
  3928. assert_eq!(q.mapped(16), 0);
  3929. assert_eq!(q.due(13, 100)[0].0, 16);
  3930. // A draw that makes the host slot (`seen`) keeps what the queue knows,
  3931. let w15 = write(&q, 15);
  3932. q.partly(15, w15, 20, 8192);
  3933. q.written(15, 14, 0, true);
  3934. assert_eq!(q.mapped(15), 8192);
  3935. // and queues a slot the queue did not hold.
  3936. q.written(99, 14, 0, true);
  3937. assert!(q.due(14, 100).iter().any(|d| d.0 == 99));
  3938. // A write due later (a table's slot) is not handed out before.
  3939. q.written(98, 14, 16, false);
  3940. assert!(!q.due(15, 100).iter().any(|d| d.0 == 98));
  3941. assert!(q.due(16, 100).iter().any(|d| d.0 == 98));
  3942. }
  3943. /// Slots held back for lack of room on the card are not handed out
  3944. /// until their frame, keep their place, are not counted as waiting
  3945. /// for their memory, and all come back at once when the card has room;
  3946. /// a slot written again meanwhile is the title's new write.
  3947. #[test]
  3948. fn slots_held_for_lack_of_room_come_back_when_there_is_room() {
  3949. let mut q = TextureQueue::default();
  3950. for i in 0..4u32 {
  3951. q.written(20 + i, 1, 0, false);
  3952. }
  3953. let due = q.due(1, 100);
  3954. assert_eq!(due.len(), 4);
  3955. // The card is full: slots 20 and 21 are held back until frame 101.
  3956. for &(index, write) in due.iter().filter(|d| d.0 < 22) {
  3957. q.hold(index, write, 101);
  3958. }
  3959. let now: Vec<u32> = q.due(2, 100).into_iter().map(|d| d.0).collect();
  3960. assert!(!now.contains(&20) && !now.contains(&21));
  3961. assert!(now.contains(&22) && now.contains(&23));
  3962. assert_eq!(q.census(2)[2], 0, "held slots do not wait for their memory");
  3963. // Due again at their frame, in the order they had.
  3964. assert_eq!(q.due(101, 100), due);
  3965. // Slot 21 is written again while held: due as written.
  3966. q.written(21, 3, 0, false);
  3967. assert!(q.due(3, 100).iter().any(|d| d.0 == 21));
  3968. // Room again at frame 5: slot 20 is due at once, and only it was
  3969. // still held as it was.
  3970. assert_eq!(q.room(5), 1);
  3971. assert!(q.due(5, 100).iter().any(|d| d.0 == 20));
  3972. assert_eq!(q.room(6), 0);
  3973. }
  3974. /// Textures of which only the smallest levels are held, packed into
  3975. /// one another's address range (the three of run 188: 0x2c000 bytes
  3976. /// each at full size, their starts 0x2000 and 0x4000 apart): writing
  3977. /// any of them, in any order and again, leaves the others.
  3978. #[test]
  3979. fn packed_neighbours_stay() {
  3980. let mut spans = Spans::default();
  3981. assert_eq!(spans.rule, Rule::Start);
  3982. let at = 0xb_86bf_8000u64;
  3983. let (a, b, c) = (at, at + 0x2000, at + 0x6000);
  3984. assert!(spans.note(105_998, a, a + 0x2c000, true).is_empty());
  3985. assert!(spans.note(106_004, b, b + 0x2c000, true).is_empty());
  3986. assert!(spans.note(108_521, c, c + 0x2c000, true).is_empty());
  3987. // The first written again (as a title does when levels arrive),
  3988. // from another slot too: its span reaches over the other two.
  3989. assert!(spans.note(7, a, a + 0x2c000, true).is_empty());
  3990. assert!(spans.note(106_004, b, b + 0x2c000, true).is_empty());
  3991. let mut all = spans.slots_in(0, u64::MAX);
  3992. all.sort_unstable();
  3993. assert_eq!(all, [7, 105_998, 106_004, 108_521]);
  3994. // A draw makes a slot of the second texture: it is one of them.
  3995. assert!(spans.note(9, b, b + 0x2c000, false).is_empty());
  3996. assert_eq!(spans.by_slot.get(&9), Some(&b));
  3997. }
  3998. /// A texture written where another starts replaces it: at the same
  3999. /// address with another length, or inside the block of its smallest
  4000. /// levels. The packed neighbours of the one replaced stay.
  4001. #[test]
  4002. fn a_texture_written_at_the_start_of_another_replaces_it() {
  4003. let mut spans = Spans::default();
  4004. let at = 0x7_0000_0000u64;
  4005. assert!(spans.note(1, at, at + 0x2c000, true).is_empty());
  4006. assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty());
  4007. // Another length from the same start: slot 1 is stale, slot 2 not.
  4008. assert_eq!(spans.note(3, at, at + 0xb000, true), [1]);
  4009. // A start inside the first 4 KiB of slot 3's texture: stale too.
  4010. assert_eq!(spans.note(4, at + 0x800, at + 0x1800, true), [3]);
  4011. // And the other way: a texture that starts just before one.
  4012. assert_eq!(spans.note(5, at + 0x1800, at + 0x4800, true), [2]);
  4013. let mut left = spans.slots_in(0, u64::MAX);
  4014. left.sort_unstable();
  4015. assert_eq!(left, [4, 5]);
  4016. // Exactly 4 KiB apart: both there.
  4017. assert!(spans.note(6, at + 0x2800, at + 0x3800, true).is_empty());
  4018. // A draw's view that clashes is left out, and nothing is stale.
  4019. assert!(spans.note(8, at + 0x900, at + 0x2900, false).is_empty());
  4020. assert_eq!(spans.by_slot.get(&8), None);
  4021. assert_eq!(spans.by_slot.len(), 3);
  4022. }
  4023. /// A slot written with another texture leaves its old span; the same
  4024. /// view written again changes nothing.
  4025. #[test]
  4026. fn a_slot_rewritten_moves_to_its_new_span() {
  4027. let mut spans = Spans::default();
  4028. assert!(spans.note(1, 0x10000, 0x3c000, true).is_empty());
  4029. assert!(spans.note(2, 0x12000, 0x3e000, true).is_empty());
  4030. assert!(spans.note(1, 0x10000, 0x3c000, true).is_empty());
  4031. assert_eq!(spans.slots_in(0x10000, 0x10001), [1]);
  4032. // Slot 1 now views a texture far away.
  4033. assert!(spans.note(1, 0x90000, 0x91000, true).is_empty());
  4034. assert_eq!(spans.slots_in(0x10000, 0x10001), [] as [u32; 0]);
  4035. assert_eq!(spans.slots_in(0x12000, 0x12001), [2]);
  4036. assert_eq!(spans.slots_in(0x90000, 0x90001), [1]);
  4037. spans.forget(1);
  4038. spans.forget(2);
  4039. assert!(spans.by_start.is_empty() && spans.by_slot.is_empty());
  4040. }
  4041. /// Memory the runtime maps, unmaps or writes names the textures that
  4042. /// are there: among packed neighbours the one whose held levels the
  4043. /// range lies in (it ends where the next one starts), and the ones
  4044. /// that start inside the range.
  4045. #[test]
  4046. fn memory_changed_under_packed_neighbours_names_the_ones_there() {
  4047. let mut spans = Spans::default();
  4048. let at = 0x7_0000_0000u64;
  4049. assert!(spans.note(1, at, at + 0x2c000, true).is_empty());
  4050. assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty());
  4051. assert!(spans.note(3, at + 0x6000, at + 0x32000, true).is_empty());
  4052. // Inside the first one's held levels.
  4053. assert_eq!(spans.slots_in(at + 0x1000, at + 0x2000), [1]);
  4054. // Inside the second's: not the first, which ends where it starts.
  4055. assert_eq!(spans.slots_in(at + 0x3000, at + 0x4000), [2]);
  4056. // Past the last start: the last one.
  4057. assert_eq!(spans.slots_in(at + 0x20000, at + 0x21000), [3]);
  4058. // A range over all of them.
  4059. assert_eq!(spans.slots_in(at, at + 0x8000), [1, 2, 3]);
  4060. // Past the end of all: none.
  4061. assert_eq!(spans.slots_in(at + 0x32000, at + 0x33000), [] as [u32; 0]);
  4062. }
  4063. /// A write names the textures that hold its bytes: the one that
  4064. /// starts where the write starts, not the neighbour before it, whose
  4065. /// held levels end there.
  4066. #[test]
  4067. fn a_write_at_the_start_of_a_packed_texture_names_it_alone() {
  4068. let mut spans = Spans::default();
  4069. let at = 0x7_0000_0000u64;
  4070. assert!(spans.note(1, at, at + 0x2c000, true).is_empty());
  4071. assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty());
  4072. assert!(spans.note(3, at + 0x6000, at + 0x32000, true).is_empty());
  4073. // A request that fills the second texture's held levels.
  4074. assert_eq!(spans.slots_in(at + 0x2000, at + 0x6000), [1, 2]);
  4075. assert_eq!(spans.slots_holding(at + 0x2000, at + 0x6000), [2]);
  4076. // From inside the first one's held levels on: both.
  4077. assert_eq!(spans.slots_holding(at + 0x1000, at + 0x3000), [1, 2]);
  4078. // A whole 64 KiB page: every texture that starts in it.
  4079. assert_eq!(spans.slots_holding(at, at + 0x10000), [1, 2, 3]);
  4080. // Past the last start, the last one; past all, or no bytes, none.
  4081. assert_eq!(spans.slots_holding(at + 0x20000, at + 0x21000), [3]);
  4082. assert_eq!(spans.slots_holding(at + 0x32000, at + 0x33000), [] as [u32; 0]);
  4083. assert_eq!(spans.slots_holding(at + 0x2000, at + 0x2000), [] as [u32; 0]);
  4084. }
  4085. /// A write behind the guards' back under a placed texture: a slot
  4086. /// waiting for its first upload is left alone, one uploaded before is
  4087. /// counted, and made due two frames on when that is asked for. (The
  4088. /// ranges are handed over here, not through the list all heaps share.)
  4089. #[test]
  4090. fn a_page_write_makes_an_uploaded_texture_slot_due_when_asked() {
  4091. let Some(heap) = HostHeap::new(false, 8) else {
  4092. return; // no host GPU
  4093. };
  4094. let slots = |at: u64| -> Vec<u32> { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() };
  4095. // 64x64 BC7, one mip, at an address no test and no title uses.
  4096. let at = 0x7fed_0000_0000u64;
  4097. let mut desc = [0u32; 16];
  4098. (desc[10], desc[11]) = (at as u32, (at >> 32) as u32);
  4099. let view = View::Placed(false, [3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc);
  4100. assert!(heap.note_buffer(1, Some(&view), false).is_empty());
  4101. let written = [(at, at + 0x1000)];
  4102. // Waiting for its first upload: held, not uploaded, nothing done.
  4103. assert_eq!(heap.slots_written_under(&written, 50, true), [1, 0, 0]);
  4104. let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0];
  4105. assert_eq!(queued, 1);
  4106. heap.texture_slot_done(1, write, None);
  4107. assert_eq!(slots(u64::MAX), []);
  4108. // Uploaded and out of the queue. Memory elsewhere: nothing.
  4109. assert_eq!(heap.slots_written_under(&[(at + 0x10_0000, at + 0x10_1000)], 60, true), [0, 0, 0]);
  4110. // Under it, counted only: it stays out of the queue.
  4111. assert_eq!(heap.slots_written_under(&written, 60, false), [1, 1, 0]);
  4112. assert_eq!(slots(u64::MAX), []);
  4113. // Under it, asked for: due two frames on, not before.
  4114. assert_eq!(heap.slots_written_under(&written, 60, true), [1, 1, 1]);
  4115. assert_eq!(slots(61), []);
  4116. assert_eq!(slots(62), [1]);
  4117. }
  4118. /// `VICTORY_STALE_TEXTURES=0`: nothing is ever stale, and a view that
  4119. /// overlaps others is left out of the spans, as before.
  4120. #[test]
  4121. fn never_stale_leaves_overlapping_views_out() {
  4122. let mut spans = Spans { rule: Rule::Never, ..Default::default() };
  4123. assert!(spans.note(1, 0x1000, 0x3000, true).is_empty());
  4124. assert!(spans.note(2, 0x2000, 0x4000, true).is_empty());
  4125. assert!(spans.note(3, 0x1000, 0x2000, true).is_empty());
  4126. assert_eq!(spans.slots_in(0, u64::MAX), [1]);
  4127. }
  4128. /// The rule until run 188 (`VICTORY_STALE_TEXTURES=overlap`): a view
  4129. /// written over memory that older views describe otherwise makes
  4130. /// those stale; views of the same span are one texture's.
  4131. #[test]
  4132. fn a_newer_view_of_other_memory_makes_the_older_stale() {
  4133. let mut spans = Spans { rule: Rule::Overlap, ..Default::default() };
  4134. // Three textures side by side, the first in two slots.
  4135. assert!(spans.note(1, 0x1000, 0x3000, true).is_empty());
  4136. assert!(spans.note(2, 0x1000, 0x3000, true).is_empty());
  4137. assert!(spans.note(3, 0x3000, 0x4000, true).is_empty());
  4138. assert!(spans.note(4, 0x8000, 0x9000, true).is_empty());
  4139. // The same slot written with the same span again: nothing changes.
  4140. assert!(spans.note(2, 0x1000, 0x3000, true).is_empty());
  4141. assert_eq!(spans.slots_in(0x2000, 0x3800), [1, 2, 3]);
  4142. assert_eq!(spans.slots_in(0x4000, 0x8000), [] as [u32; 0]);
  4143. // A draw makes a slot whose view overlaps them: left out, nothing stale.
  4144. assert!(spans.note(9, 0x2000, 0x3800, false).is_empty());
  4145. assert_eq!(spans.slots_in(0x2000, 0x3800), [1, 2, 3]);
  4146. // The title writes a texture over the end of the first and all of
  4147. // the second: their three slots are stale.
  4148. let mut stale = spans.note(5, 0x2000, 0x4000, true);
  4149. stale.sort_unstable();
  4150. assert_eq!(stale, [1, 2, 3]);
  4151. assert_eq!(spans.slots_in(0, u64::MAX), [5, 4]);
  4152. // Another start in the same memory: stale in turn. Another length
  4153. // from the same start too.
  4154. assert_eq!(spans.note(6, 0x2800, 0x3000, true), [5]);
  4155. assert_eq!(spans.note(7, 0x2800, 0x2c00, true), [6]);
  4156. // A slot that moves to another texture leaves its span behind.
  4157. assert!(spans.note(7, 0x8000, 0x9000, true).is_empty());
  4158. assert_eq!(spans.slots_in(0x2800, 0x2c00), [] as [u32; 0]);
  4159. assert_eq!(spans.slots_in(0x8000, 0x8001), [4, 7]);
  4160. spans.forget(4);
  4161. spans.forget(7);
  4162. assert!(spans.by_start.is_empty() && spans.by_slot.is_empty());
  4163. }
  4164. /// Memory the runtime maps under a slot's texture makes the slot due
  4165. /// again from the next frame; a stale slot leaves the queue.
  4166. #[test]
  4167. fn remapped_memory_makes_its_texture_slots_due() {
  4168. let Some(heap) = HostHeap::new(false, 8) else {
  4169. return; // no host GPU
  4170. };
  4171. let slots = |at: u64| -> Vec<u32> { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() };
  4172. // 64x64 BC7, one mip, at an address no test and no title uses.
  4173. let at = 0x7fee_0000_0000u64;
  4174. let view = |address: u64, width: u32| {
  4175. let mut desc = [0u32; 16];
  4176. (desc[10], desc[11]) = (address as u32, (address >> 32) as u32);
  4177. View::Placed(false, [3, 0, 0, 0, width, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc)
  4178. };
  4179. let len = crate::resource::placed_bytes(&[3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0]).unwrap();
  4180. assert!(heap.note_buffer(1, Some(&view(at, 64)), false).is_empty());
  4181. let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0];
  4182. assert_eq!(queued, 1);
  4183. heap.texture_slot_done(1, write, None);
  4184. assert_eq!(slots(u64::MAX), []);
  4185. // Memory elsewhere: nothing. Under the texture: due from the next frame.
  4186. remapped((at + 2 * len) as usize, 0x1000);
  4187. remapped(at as usize, 0x1000);
  4188. assert_eq!(heap.texture_slots_remapped(50), 1);
  4189. assert_eq!(slots(50), []);
  4190. assert_eq!(slots(51), [1]);
  4191. // A wider texture written at the same address: slot 1 is stale.
  4192. assert_eq!(heap.note_buffer(2, Some(&view(at, 128)), false), [1]);
  4193. assert_eq!(slots(u64::MAX), [2]);
  4194. }
  4195. /// A slot a draw read through a table leaves the queue; the title's
  4196. /// next write of it waits for its draw, and is due after the grace
  4197. /// frames if none reads it.
  4198. #[test]
  4199. fn slots_read_through_tables_leave_the_texture_queue() {
  4200. let Some(heap) = HostHeap::new(false, 8) else {
  4201. return; // no host GPU
  4202. };
  4203. let frame = 100;
  4204. let slots = |at: u64| -> Vec<u32> { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() };
  4205. let texture = View::Placed(false, [3, 0, 0, 0, 4, 0, 4, 0x1_0001, 28, 1, 0, 0x105, 0, 0], [0; 16]);
  4206. assert!(is_texture_view(&texture));
  4207. heap.queue_texture(2, true, false, frame);
  4208. heap.queue_texture(3, true, false, frame);
  4209. assert_eq!(slots(frame), [3, 2]);
  4210. heap.tabled_in(3, true, frame);
  4211. assert_eq!(slots(frame), [2]);
  4212. // Made in place by the draw that read it: still out.
  4213. heap.queue_texture(3, true, true, frame);
  4214. assert_eq!(slots(frame), [2]);
  4215. // Written again in the next frame: due once the grace frames have
  4216. // passed without a draw that reads it.
  4217. heap.queue_texture(3, true, false, frame + 1);
  4218. assert_eq!(slots(frame + TABLED_GRACE), [2]);
  4219. assert_eq!(slots(frame + 1 + TABLED_GRACE), [3, 2]);
  4220. // The draw comes after all: out again.
  4221. heap.tabled_in(3, true, frame + 1);
  4222. assert_eq!(slots(u64::MAX), [2]);
  4223. // A slot of a table no draw read stays queued; its next write waits.
  4224. heap.tabled_in(2, false, frame + 1);
  4225. assert_eq!(slots(frame + 1), [2]);
  4226. heap.queue_texture(2, true, false, frame + 2);
  4227. assert_eq!(slots(frame + 2), []);
  4228. // Long after the last table, a write is due at once.
  4229. heap.queue_texture(2, true, false, frame + 3 + TABLED_FRAMES);
  4230. assert_eq!(slots(frame + 3 + TABLED_FRAMES), [2]);
  4231. }
  4232. #[test]
  4233. fn dynamic_slots_are_held_until_released() {
  4234. let Some(heap) = HostHeap::new(false, 4) else {
  4235. return; // no host GPU
  4236. };
  4237. let a = heap.dynamic(heap.dynamic - 100).unwrap();
  4238. let b = heap.dynamic(60).unwrap();
  4239. assert_eq!((a, b), (4, 4 + heap.dynamic - 100));
  4240. // 40 left at the end: 50 do not fit until something is given back.
  4241. assert_eq!(heap.dynamic(50), None);
  4242. heap.release(a, 50);
  4243. assert_eq!(heap.dynamic(50), Some(4));
  4244. assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40));
  4245. }
  4246. #[test]
  4247. fn dynamic_search_can_find_a_run_across_the_cursor() {
  4248. let Some(heap) = HostHeap::new(false, 4) else {
  4249. eprintln!("no host descriptor heap; skipped");
  4250. return;
  4251. };
  4252. let first = heap.dynamic(1).unwrap();
  4253. let left = heap.dynamic(2).unwrap();
  4254. let right = heap.dynamic(2).unwrap();
  4255. let rest = heap.dynamic(heap.dynamic - 5).unwrap();
  4256. assert_eq!((first, left, right, rest), (4, 5, 7, 9));
  4257. // Reallocating the left half puts the cursor back in the middle.
  4258. heap.release(left, 2);
  4259. assert_eq!(heap.dynamic(2), Some(left));
  4260. heap.release(left, 2);
  4261. heap.release(right, 2);
  4262. assert_eq!(heap.dynamic(4), Some(left));
  4263. assert_eq!(heap.dynamic(1), None);
  4264. // A free slot at each physical end does not form a two-slot range.
  4265. heap.release(first, 1);
  4266. let last = first + heap.dynamic - 1;
  4267. heap.release(last, 1);
  4268. assert_eq!(heap.dynamic(2), None);
  4269. }
  4270. }