host.rs 197 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501
  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. /// A number that changes when a slot is written or made due anew, and
  1265. /// whether memory was noted since a pass last took the notes.
  1266. pub(crate) fn texture_news(&self) -> (u64, bool) {
  1267. let writes = self.textures.lock().unwrap_or_else(|e| e.into_inner()).writes;
  1268. let noted = |ranges: &Mutex<Vec<(u64, u64)>>| !ranges.lock().unwrap_or_else(|e| e.into_inner()).is_empty();
  1269. (writes, noted(&REMAPPED) || noted(&PAGE_WRITTEN))
  1270. }
  1271. /// Every title slot of the queue that is due at `frame`, and whether
  1272. /// it was uploaded before (in part, or whole and waiting for another
  1273. /// look): for the card accounting line
  1274. /// (`crate::resource::card_accounting`).
  1275. pub(crate) fn texture_slots_all_due(&self, frame: u64) -> Vec<(u32, bool)> {
  1276. let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1277. textures
  1278. .slots
  1279. .iter()
  1280. .filter(|(_, w)| w.due <= frame)
  1281. .map(|(&index, w)| (index, w.mapped > 0 || w.checked.2 != 0))
  1282. .collect()
  1283. }
  1284. /// The texture view of title slot `index` (as handed out with `write`)
  1285. /// was brought up to date: due again from frame `again` (uploaded with
  1286. /// that many bytes of its memory there, not all), or not until the
  1287. /// slot is written again.
  1288. pub(crate) fn texture_slot_done(&self, index: u32, write: u64, again: Option<(u64, u64)>) {
  1289. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1290. match again {
  1291. Some((frame, mapped)) => textures.partly(index, write, frame, mapped),
  1292. None => textures.done(index, write),
  1293. }
  1294. }
  1295. /// Title slot `index` was uploaded whole: see [`TextureQueue::recheck`].
  1296. #[allow(clippy::too_many_arguments)]
  1297. pub(crate) fn texture_slot_recheck(
  1298. &self,
  1299. index: u32,
  1300. write: u64,
  1301. due: u64,
  1302. at: (u64, u64),
  1303. print: u64,
  1304. looks: u8,
  1305. uploaded: u64,
  1306. ) {
  1307. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1308. textures.recheck(index, write, due, at, print, looks, uploaded);
  1309. }
  1310. /// See [`TextureQueue::checked`].
  1311. pub(crate) fn texture_slot_checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> {
  1312. self.textures.lock().unwrap_or_else(|e| e.into_inner()).checked(index)
  1313. }
  1314. /// Nothing to upload at title slot `index` now (its memory is not
  1315. /// mapped, or no more of it than before): looked at again after 1, 2,
  1316. /// 4, ... frames, at most `most`.
  1317. pub(crate) fn texture_slot_later(&self, index: u32, write: u64, frame: u64, most: u64) {
  1318. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1319. textures.later(index, write, frame, most);
  1320. }
  1321. /// See [`TextureQueue::hold`].
  1322. pub(crate) fn texture_slot_held(&self, index: u32, write: u64, due: u64) {
  1323. self.textures.lock().unwrap_or_else(|e| e.into_inner()).hold(index, write, due);
  1324. }
  1325. /// See [`TextureQueue::room`].
  1326. pub(crate) fn texture_slots_room(&self, frame: u64) -> usize {
  1327. self.textures.lock().unwrap_or_else(|e| e.into_inner()).room(frame)
  1328. }
  1329. /// Bytes of title slot `index`'s memory that were mapped when it was
  1330. /// last uploaded in part (0: not uploaded, or whole).
  1331. pub(crate) fn texture_slot_mapped(&self, index: u32) -> u64 {
  1332. self.textures.lock().unwrap_or_else(|e| e.into_inner()).mapped(index)
  1333. }
  1334. /// Takes the ranges of title memory the runtime mapped, unmapped or
  1335. /// wrote since the last call ([`remapped`]) and makes the slots whose
  1336. /// placed texture lies there due from the next frame (by when a write
  1337. /// under way has landed): memory that arrived is uploaded, memory that
  1338. /// went makes the slot null ([`HostHeap::texture_slot_gone`]), and a
  1339. /// texture streamed into the place of another of the same description
  1340. /// is uploaded although no descriptor says so. Slots tables read are
  1341. /// left to their draws. Returns how many slots it made due.
  1342. /// shortcut: the ranges are kept in one place for all heaps; the heap
  1343. /// whose pass runs first takes them (a title has one view heap).
  1344. pub(crate) fn texture_slots_remapped(&self, frame: u64) -> usize {
  1345. use std::sync::atomic::Ordering::Relaxed;
  1346. self.texture_slots_page_written(frame);
  1347. let ranges = std::mem::take(&mut *REMAPPED.lock().unwrap_or_else(|e| e.into_inner()));
  1348. if ranges.is_empty() {
  1349. return 0;
  1350. }
  1351. let mut slots: Vec<u32> = {
  1352. let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
  1353. ranges.iter().flat_map(|&(start, end)| placed.slots_in(start, end)).collect()
  1354. };
  1355. slots.sort_unstable();
  1356. slots.dedup();
  1357. slots.retain(|&slot| !self.tabled_lately(slot, frame));
  1358. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1359. for &slot in &slots {
  1360. textures.changed(slot, frame, frame + 1);
  1361. }
  1362. STALE[3].fetch_add(slots.len() as u64, Relaxed);
  1363. slots.len()
  1364. }
  1365. /// Makes the slots of the textures filled with less than was mapped
  1366. /// ([`read_short`]) due from the next frame on. Returns how many.
  1367. pub(crate) fn texture_slots_short(&self, frame: u64) -> usize {
  1368. if self.sampler {
  1369. return 0;
  1370. }
  1371. let starts = std::mem::take(&mut SHORT.lock().unwrap_or_else(|e| e.into_inner()).0);
  1372. if starts.is_empty() {
  1373. return 0;
  1374. }
  1375. let mut slots: Vec<u32> = {
  1376. let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
  1377. starts.iter().flat_map(|&start| placed.slots_at(start)).collect()
  1378. };
  1379. slots.sort_unstable();
  1380. slots.dedup();
  1381. slots.retain(|&slot| !self.tabled_lately(slot, frame));
  1382. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1383. for &slot in &slots {
  1384. textures.changed(slot, frame, frame + 1);
  1385. }
  1386. slots.len()
  1387. }
  1388. /// Takes the ranges of title memory written behind the guards' back
  1389. /// since the last call ([`page_written`]) and finds the slots whose
  1390. /// placed texture holds bytes of them ([`Spans::slots_holding`]). A
  1391. /// slot whose texture was uploaded before the write shows the bytes
  1392. /// from before: with `VICTORY_PAGE_WRITES` (`crate::watch::page_writes`,
  1393. /// bit 2) it is due again [`PAGE_WRITE_AFTER`] frames on, as memory
  1394. /// mapped under it would make it ([`HostHeap::texture_slots_remapped`]);
  1395. /// its host copy exists, so the upload needs no room on the card. A
  1396. /// slot still waiting for its first upload is left as it is: that
  1397. /// upload takes the bytes that are there by then. Slots tables read
  1398. /// are left to their draws. Counted either way; returns how many slots
  1399. /// it made due.
  1400. fn texture_slots_page_written(&self, frame: u64) -> usize {
  1401. let ranges = std::mem::take(&mut *PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()));
  1402. if ranges.is_empty() {
  1403. return 0;
  1404. }
  1405. self.slots_written_under(&ranges, frame, crate::watch::page_writes() & 2 != 0)[2]
  1406. }
  1407. /// [`HostHeap::texture_slots_page_written`] for `ranges` (start, end):
  1408. /// the slots that held bytes of them, those of them uploaded before,
  1409. /// and those made due (the latter, if `due`).
  1410. fn slots_written_under(&self, ranges: &[(u64, u64)], frame: u64, due: bool) -> [usize; 3] {
  1411. use std::sync::atomic::Ordering::Relaxed;
  1412. let mut slots: Vec<u32> = {
  1413. let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
  1414. ranges.iter().flat_map(|&(start, end)| placed.slots_holding(start, end)).collect()
  1415. };
  1416. slots.sort_unstable();
  1417. slots.dedup();
  1418. slots.retain(|&slot| !self.tabled_lately(slot, frame));
  1419. let held = slots.len();
  1420. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1421. // Uploaded before: out of the queue, or in it after an upload (in
  1422. // part, or whole and being looked at again).
  1423. slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0));
  1424. PAGE_WRITES[2].fetch_add(held as u64, Relaxed);
  1425. PAGE_WRITES[3].fetch_add(slots.len() as u64, Relaxed);
  1426. if !due {
  1427. return [held, slots.len(), 0];
  1428. }
  1429. for &slot in &slots {
  1430. textures.changed(slot, frame, frame + PAGE_WRITE_AFTER);
  1431. }
  1432. [held, slots.len(), slots.len()]
  1433. }
  1434. /// Whether host slot `index` is made from the very record the title
  1435. /// has at `handle` now. Its host texture then exists (a slot keeps what
  1436. /// it views), so bringing that texture up to date takes no memory of
  1437. /// the card.
  1438. pub(crate) fn texture_slot_made_from(&self, index: u32, handle: u64) -> bool {
  1439. if index >= self.count {
  1440. return false;
  1441. }
  1442. // SAFETY: the handle is a descriptor slot in title memory.
  1443. let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() };
  1444. let key = u64::from(generation) << 32 | u64::from(i);
  1445. if tag != VIEW_TAG {
  1446. return false;
  1447. }
  1448. // And the slot holds a host resource: a slot is also noted as made
  1449. // from a view the host could not make (`make` gave nothing, the
  1450. // slot is null and keeps nothing). The host copy of such a
  1451. // texture is held by no slot, may have been let go, and would be
  1452. // made anew here, with the card full. `made` first, then `kept`,
  1453. // as `mirror` takes them.
  1454. let made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1455. made.get(index as usize).is_some_and(|&made| made != 0 && made == key)
  1456. && self
  1457. .kept
  1458. .lock()
  1459. .unwrap_or_else(|e| e.into_inner())
  1460. .get(index as usize)
  1461. .is_some_and(Option::is_some)
  1462. }
  1463. /// Levels on demand (`crate::tiles`): makes again the host slots of the
  1464. /// placed textures whose first level with memory changed since the
  1465. /// last call ([`levels_changed`]), each from the view it was made
  1466. /// from, so that it shows the texture from that level ([`make`]). Only
  1467. /// slots that are made; a slot draws read through a table is made by
  1468. /// its draw. Returns how many it made.
  1469. /// shortcut: the starts are kept in one place for all heaps; the heap
  1470. /// whose pass runs first takes them (a title has one view heap).
  1471. /// Levels on demand (`crate::tiles`): the card has room, so the slots
  1472. /// of up to [`Self::WAITING_A_PASS`] placed textures whose upload left
  1473. /// a held level without tiles at least a second ago
  1474. /// ([`levels_waiting`]) are due again from the next frame, as memory
  1475. /// mapped under them would make them
  1476. /// ([`HostHeap::texture_slots_remapped`]): the upload then gives the
  1477. /// level its tiles. To be called only while the card has room: without
  1478. /// it the upload would give nothing again. Slots tables read are left
  1479. /// to their draws (`texture.rs` `upload` asks again for those). Returns
  1480. /// how many slots it made due.
  1481. /// shortcut: kept in one place for all heaps, as the starts below.
  1482. pub(crate) fn texture_slots_waiting(&self, frame: u64) -> usize {
  1483. if self.sampler {
  1484. return 0;
  1485. }
  1486. let starts: Vec<u64> = {
  1487. let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner());
  1488. if waiting.is_empty() {
  1489. return 0;
  1490. }
  1491. let starts: Vec<u64> = waiting
  1492. .iter()
  1493. .filter(|&(_, &since)| crate::host::long_ago(since, 1000, 2))
  1494. .map(|(&start, _)| start)
  1495. .take(Self::WAITING_A_PASS)
  1496. .collect();
  1497. for start in &starts {
  1498. waiting.remove(start);
  1499. }
  1500. starts
  1501. };
  1502. if starts.is_empty() {
  1503. return 0;
  1504. }
  1505. let mut slots: Vec<u32> = {
  1506. let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
  1507. starts.iter().flat_map(|&start| placed.slots_at(start)).collect()
  1508. };
  1509. slots.sort_unstable();
  1510. slots.dedup();
  1511. slots.retain(|&slot| !self.tabled_lately(slot, frame));
  1512. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1513. for &slot in &slots {
  1514. textures.changed(slot, frame, frame + 1);
  1515. }
  1516. crate::tiles::STATS[10].fetch_add(slots.len() as u64, std::sync::atomic::Ordering::Relaxed);
  1517. slots.len()
  1518. }
  1519. /// Textures a pass asks again for their levels
  1520. /// ([`HostHeap::texture_slots_waiting`]): the first ones given tiles
  1521. /// may take the room the others were asked for, and an upload that
  1522. /// gives nothing is a whole texture staged and copied for nothing.
  1523. const WAITING_A_PASS: usize = 128;
  1524. pub(crate) fn texture_views_remade(&self) -> usize {
  1525. if self.sampler {
  1526. return 0;
  1527. }
  1528. {
  1529. let mut after = RESHOWN_AFTER.lock().unwrap_or_else(|e| e.into_inner());
  1530. if !after.is_empty() {
  1531. let finished = crate::host::submissions().1;
  1532. let mut now = RESHOWN.lock().unwrap_or_else(|e| e.into_inner());
  1533. after.retain(|&(at, start)| {
  1534. if at <= finished {
  1535. now.push(start);
  1536. }
  1537. at > finished
  1538. });
  1539. }
  1540. }
  1541. let starts = std::mem::take(&mut *RESHOWN.lock().unwrap_or_else(|e| e.into_inner()));
  1542. if starts.is_empty() {
  1543. return 0;
  1544. }
  1545. let slots: Vec<u32> = {
  1546. let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
  1547. starts.iter().flat_map(|&start| placed.slots_at(start)).collect()
  1548. };
  1549. let made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1550. let mut remade = 0;
  1551. for slot in slots {
  1552. let Some(&key) = made.get(slot as usize) else {
  1553. continue;
  1554. };
  1555. if key == 0 {
  1556. continue;
  1557. }
  1558. let Some(view) = view_at(key as u32, (key >> 32) as u32) else {
  1559. continue;
  1560. };
  1561. if let Some(kept) = make(&view, self.at(slot)) {
  1562. self.put(slot);
  1563. self.keep(slot, kept);
  1564. remade += 1;
  1565. }
  1566. }
  1567. remade
  1568. }
  1569. /// The memory of the texture title slot `index` views is not mapped
  1570. /// (any more): a host slot made from it becomes null again, so that
  1571. /// the host copy can be let go (`crate::resource::let_go_idle`; a slot
  1572. /// keeps what it views). True if the slot was made.
  1573. ///
  1574. /// Not at the first look: a title that moves a texture in its streaming
  1575. /// memory unmaps it before it maps it again, and what was shown went
  1576. /// black for the pictures in between (session play-1125-0127: faces,
  1577. /// books, posters and sleeves for 0.3 to 2 s). Only when it is still
  1578. /// away `AWAY_MS` after it was first found away
  1579. /// (`VICTORY_TEXTURE_AWAY_MS`; 0: at once, as before).
  1580. pub(crate) fn texture_slot_gone(&self, index: u32) -> bool {
  1581. const AWAY_MS: u64 = 3000;
  1582. static WAIT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  1583. let wait = *WAIT.get_or_init(|| {
  1584. std::env::var("VICTORY_TEXTURE_AWAY_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(AWAY_MS)
  1585. });
  1586. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1587. let Some(key) = made.get(index as usize).copied().filter(|&key| key != 0) else {
  1588. return false;
  1589. };
  1590. let now = crate::host::now_ms();
  1591. {
  1592. let mut away = self.away.lock().unwrap_or_else(|e| e.into_inner());
  1593. match away.get(&index) {
  1594. Some(&(was, since)) if was == key && now.saturating_sub(since) < wait => return false,
  1595. Some(&(was, _)) if was == key => {
  1596. away.remove(&index);
  1597. }
  1598. _ if wait == 0 => {}
  1599. _ => {
  1600. away.insert(index, (key, now));
  1601. return false;
  1602. }
  1603. }
  1604. }
  1605. self.unmake(&mut made, index);
  1606. STALE[4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1607. true
  1608. }
  1609. /// Whether host slot `index` shows the placed texture the title's record
  1610. /// at `handle` views, by an earlier view of it.
  1611. pub(crate) fn texture_slot_shows_other(&self, index: u32, handle: u64) -> bool {
  1612. let key = record_key(handle);
  1613. let made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1614. let Some(&shown) = made.get(index as usize) else {
  1615. return false;
  1616. };
  1617. if key == 0 || shown == 0 || shown == key {
  1618. return false;
  1619. }
  1620. let view = |key: u64| view_at(key as u32, (key >> 32) as u32);
  1621. matches!((view(shown), view(key)), (Some(a), Some(b)) if same_placed_texture(&a, &b))
  1622. }
  1623. /// Slot `index` is made from the record at `handle` (what it is now)
  1624. /// when `list`, which holds the upload of what that view shows, has run:
  1625. /// until then it shows what it showed. (Made at once, the frames on the
  1626. /// card read the new view before its levels were filled.)
  1627. pub(crate) fn texture_slot_flip(&self, list: &crate::host::HostList, index: u32, handle: u64) {
  1628. let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle));
  1629. list.defer_host(move || {
  1630. let after = crate::host::submissions().0;
  1631. let flip = Flip { after, heap, index, handle, key };
  1632. FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip);
  1633. });
  1634. }
  1635. /// Makes the slots whose new view's upload has run
  1636. /// ([`HostHeap::texture_slot_flip`]); returns how many.
  1637. pub(crate) fn texture_slots_flip(&self) -> usize {
  1638. use std::sync::atomic::Ordering::Relaxed;
  1639. let finished = crate::host::submissions().1;
  1640. let ready: Vec<Flip> = {
  1641. let mut flips = FLIPS.lock().unwrap_or_else(|e| e.into_inner());
  1642. if flips.is_empty() {
  1643. return 0;
  1644. }
  1645. let own = std::ptr::from_ref(self) as usize;
  1646. let (ready, wait): (Vec<Flip>, Vec<Flip>) =
  1647. flips.drain(..).partition(|f| f.after <= finished && f.heap == own);
  1648. *flips = wait;
  1649. ready
  1650. };
  1651. let mut flipped = 0;
  1652. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1653. for f in ready {
  1654. let Some(shown) = made.get_mut(f.index as usize) else {
  1655. continue;
  1656. };
  1657. if *shown == f.key {
  1658. continue;
  1659. }
  1660. // Written again since, or made null: that write is in the queue.
  1661. let view = view_at(f.key as u32, (f.key >> 32) as u32);
  1662. let (true, true, Some(view)) = (f.key != 0 && record_key(f.handle) == f.key, *shown != 0, view) else {
  1663. FLIPPED[1].fetch_add(1, Relaxed);
  1664. continue;
  1665. };
  1666. if let Some(kept) = make(&view, self.at(f.index)) {
  1667. self.put(f.index);
  1668. *shown = f.key;
  1669. self.keep(f.index, kept);
  1670. flipped += 1;
  1671. }
  1672. }
  1673. FLIPPED[0].fetch_add(flipped as u64, Relaxed);
  1674. flipped
  1675. }
  1676. /// The memory of the texture title slot `index` views is there (again):
  1677. /// see [`HostHeap::texture_slot_gone`].
  1678. pub(crate) fn texture_slot_here(&self, index: u32) {
  1679. let mut away = self.away.lock().unwrap_or_else(|e| e.into_inner());
  1680. if !away.is_empty() {
  1681. away.remove(&index);
  1682. }
  1683. }
  1684. /// Makes host slot `index` null again, as it is before its view is
  1685. /// made: a null view of the kind it held.
  1686. fn unmake(&self, made: &mut [u64], index: u32) {
  1687. let Some(key) = made.get_mut(index as usize).map(std::mem::take) else {
  1688. return;
  1689. };
  1690. if key == 0 {
  1691. return;
  1692. }
  1693. match view_at(key as u32, (key >> 32) as u32) {
  1694. Some(view) => null_for(&view, self.at(index)),
  1695. None => null_view(self.at(index)),
  1696. }
  1697. self.put(index);
  1698. self.clear_twin(index);
  1699. self.keep(index, None);
  1700. }
  1701. /// Title slot `index` is a table's ([`HostHeap::tabled`]). `read`: a
  1702. /// draw read it through the table and brought what it views up to
  1703. /// date, so the slot leaves the queue of textures picked by index; the
  1704. /// caller makes the host slot in place ([`HostHeap::mirror`]), as the
  1705. /// pass would have, for a shader that picks it by index all the same.
  1706. pub(crate) fn texture_slot_tabled(&self, index: u32, read: bool) {
  1707. self.tabled_in(index, read, crate::frame::current());
  1708. }
  1709. /// [`HostHeap::texture_slot_tabled`] in frame `frame`.
  1710. fn tabled_in(&self, index: u32, read: bool, frame: u64) {
  1711. use std::sync::atomic::Ordering::Relaxed;
  1712. let Some(stamp) = self.tabled.get(index as usize) else {
  1713. return;
  1714. };
  1715. let now = (frame as u32).wrapping_add(1) & !TABLED_READ;
  1716. let old = stamp.load(Relaxed);
  1717. if !read {
  1718. if old & !TABLED_READ != now {
  1719. stamp.store(now, Relaxed);
  1720. }
  1721. return;
  1722. }
  1723. // Once per slot and frame: tables are read by every draw.
  1724. if old != now | TABLED_READ {
  1725. stamp.store(now | TABLED_READ, Relaxed);
  1726. if tabled_out() {
  1727. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1728. if textures.slots.remove(&index).is_some() {
  1729. TABLED_WRITES[1].fetch_add(1, Relaxed);
  1730. }
  1731. }
  1732. }
  1733. }
  1734. /// Whether title slot `index` was a table's within the last
  1735. /// [`TABLED_FRAMES`] frames before `frame` (never, if such slots are
  1736. /// to be queued as any other).
  1737. fn tabled_lately(&self, index: u32, frame: u64) -> bool {
  1738. let stamp = self.tabled_stamp(index) & !TABLED_READ;
  1739. let now = (frame as u32).wrapping_add(1) & !TABLED_READ;
  1740. tabled_out() && stamp != 0 && u64::from(now.wrapping_sub(stamp)) <= TABLED_FRAMES
  1741. }
  1742. /// What `tabled` holds for title slot `index`; 0: never a table's.
  1743. fn tabled_stamp(&self, index: u32) -> u32 {
  1744. self.tabled
  1745. .get(index as usize)
  1746. .map_or(0, |s| s.load(std::sync::atomic::Ordering::Relaxed))
  1747. }
  1748. /// The queue's part of a write of title slot `index` in `frame`:
  1749. /// `texture`, whether it now holds a view of a texture the title may
  1750. /// fill; `seen` as for [`HostHeap::note_buffer`].
  1751. fn queue_texture(&self, index: u32, texture: bool, seen: bool, frame: u64) {
  1752. let stamp = if tabled_out() { self.tabled_stamp(index) } else { 0 };
  1753. let now = (frame as u32).wrapping_add(1) & !TABLED_READ;
  1754. // A table's slot lately: the draw that reads it uploads its
  1755. // texture, so its write waits for that draw.
  1756. let lately = stamp != 0 && u64::from(now.wrapping_sub(stamp & !TABLED_READ)) <= TABLED_FRAMES;
  1757. // Made now by a draw of this frame that read it through a table:
  1758. // up to date.
  1759. let read_now = seen && stamp == now | TABLED_READ;
  1760. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1761. if texture && !read_now {
  1762. let due = if lately && !seen {
  1763. TABLED_WRITES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1764. frame + TABLED_GRACE
  1765. } else {
  1766. 0
  1767. };
  1768. textures.written(index, frame, due, seen);
  1769. } else {
  1770. textures.remove(index);
  1771. }
  1772. }
  1773. /// Title slot `index` lies in a table a draw reads or had made afresh:
  1774. /// what it holds is the draw's to make ([`HostHeap::copied_tabled`]).
  1775. pub(crate) fn slot_tabled(&self, index: u32) {
  1776. self.tabled_in(index, false, crate::frame::current());
  1777. }
  1778. /// The title slots that hold buffer views.
  1779. pub(crate) fn buffer_slots(&self) -> Vec<u32> {
  1780. let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
  1781. buffers.iter().copied().collect()
  1782. }
  1783. /// Of [`HostHeap::buffer_slots`], those of one of `parts` parts: every
  1784. /// slot is in the same part each time.
  1785. pub(crate) fn buffer_slots_of(&self, part: u32, parts: u32) -> Vec<u32> {
  1786. let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
  1787. buffers.iter().copied().filter(|slot| slot % parts == part).collect()
  1788. }
  1789. /// The title slots whose buffer view was written, or went, since the
  1790. /// last call.
  1791. pub(crate) fn buffer_changes(&self) -> Vec<u32> {
  1792. let mut changed = self.changed.lock().unwrap_or_else(|e| e.into_inner());
  1793. std::mem::take(&mut *changed).into_iter().collect()
  1794. }
  1795. /// Records what title slot `index` now holds for shaders that pick
  1796. /// buffers from the heap: its element stride in the table, and whether
  1797. /// it is a buffer view at all.
  1798. /// `seen`: the slot was not written now, a draw or a pass made its
  1799. /// host slot from what it held.
  1800. /// Returns the title slots whose placed texture view the write made
  1801. /// stale ([`Spans`]): out of the queue of textures already, their host
  1802. /// slots are the caller's to make null (it holds `made`).
  1803. fn note_buffer(&self, index: u32, view: Option<&View>, seen: bool) -> Vec<u32> {
  1804. if self.sampler {
  1805. return Vec::new();
  1806. }
  1807. // Measured for the texture side of the same gap (textures a shader
  1808. // picks by a computed index are neither made, if placed, nor
  1809. // uploaded): slots written with a placed texture view, and with a
  1810. // view of a texture object.
  1811. let texture = match view {
  1812. Some(View::Placed(false, resource, _)) if resource[0] != 1 => {
  1813. PLACED_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1814. true
  1815. }
  1816. Some(View::Shader(r, _)) if crate::resource::buffer_bytes(*r as crate::object::This).is_none() => {
  1817. OBJECT_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1818. true
  1819. }
  1820. _ => false,
  1821. };
  1822. self.queue_texture(index, texture, seen, crate::frame::current());
  1823. // The memory a placed texture view describes. Not for a slot
  1824. // tables read (thousands of writes a frame, each read by its
  1825. // draw): no pass looks at it, and the same texture's view in a
  1826. // slot shaders pick by index says what it says.
  1827. let placed_view = match view {
  1828. Some(View::Placed(false, resource, desc))
  1829. if resource[0] != 1 && !self.tabled_lately(index, crate::frame::current()) =>
  1830. {
  1831. // (And the level the view starts at: word 4 of a texture
  1832. // view's description, after format, dimension, mapping
  1833. // and a pad.)
  1834. let at = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  1835. let held = crate::resource::placed_bytes_from(resource, crate::resource::first_mip(desc));
  1836. Some((resource, at, desc[4], held.map_or(u64::MAX, |held| at.saturating_add(held))))
  1837. }
  1838. _ => None,
  1839. };
  1840. let stale = {
  1841. use std::sync::atomic::Ordering::Relaxed;
  1842. let mut placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
  1843. let span = placed_view.and_then(|(resource, start, first, held)| {
  1844. Some((start, start.saturating_add(placed.bytes(resource)?), first, held))
  1845. });
  1846. match span {
  1847. Some((start, end, first, held)) => {
  1848. SPANNED[0].fetch_min(start, Relaxed);
  1849. SPANNED[1].fetch_max(end, Relaxed);
  1850. placed.rule = stale_rule();
  1851. let stale = placed.note(index, start, end, !seen);
  1852. placed.shows(index, first, held);
  1853. stale
  1854. }
  1855. None => {
  1856. placed.forget(index);
  1857. Vec::new()
  1858. }
  1859. }
  1860. };
  1861. if !stale.is_empty() {
  1862. STALE[0].fetch_add(stale.len() as u64, std::sync::atomic::Ordering::Relaxed);
  1863. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1864. for &slot in &stale {
  1865. textures.remove(slot);
  1866. }
  1867. }
  1868. let stride = view.and_then(view_stride);
  1869. if let Some((_, _, data)) = &self.strides
  1870. && index < victory_shader::emit::SLOT_STRIDES_COUNT
  1871. {
  1872. // SAFETY: inside the mapping; shaders read it while we write (a
  1873. // dword, either value is one the slot had).
  1874. unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0)) };
  1875. }
  1876. let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
  1877. let was = if stride.is_some() {
  1878. buffers.insert(index);
  1879. true
  1880. } else {
  1881. buffers.remove(&index)
  1882. };
  1883. if was {
  1884. self.changed
  1885. .lock()
  1886. .unwrap_or_else(|e| e.into_inner())
  1887. .insert(index);
  1888. }
  1889. stale
  1890. }
  1891. /// Gives back `n` dynamic slots from `first` (an index [`dynamic`]
  1892. /// returned).
  1893. ///
  1894. /// [`dynamic`]: HostHeap::dynamic
  1895. pub(crate) fn release(&self, first: u32, n: u32) {
  1896. let Some(at) = first.checked_sub(self.count) else {
  1897. return;
  1898. };
  1899. let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner());
  1900. let end = (at + n).min(self.dynamic) as usize;
  1901. if let Some(slots) = guard.1.get_mut(at as usize..end) {
  1902. let given = slots.iter().filter(|taken| **taken).count() as u32;
  1903. self.free.fetch_add(given, std::sync::atomic::Ordering::Relaxed);
  1904. self.too_long.store(u32::MAX, std::sync::atomic::Ordering::Relaxed);
  1905. slots.fill(false);
  1906. }
  1907. }
  1908. /// Makes slot `index` (a dynamic one) from `view`; a null view if the
  1909. /// host cannot.
  1910. pub(crate) fn make_at(&self, index: u32, view: &View) {
  1911. let kept = make_twinned(view, self.at(index), self.twin(index));
  1912. if kept.is_none() {
  1913. null_for(view, self.at(index));
  1914. }
  1915. self.put(index);
  1916. self.twin_made(index, kept.is_some() && twinned(view));
  1917. self.keep(index, kept.flatten());
  1918. }
  1919. /// Makes slot `index` read nothing: a null view, or a plain sampler.
  1920. pub(crate) fn make_null(&self, index: u32) {
  1921. if self.sampler {
  1922. self.null_sampler(index);
  1923. } else {
  1924. null_view(self.at(index));
  1925. self.put(index);
  1926. }
  1927. self.clear_twin(index);
  1928. self.keep(index, None);
  1929. }
  1930. /// Where the raw twin of slot `index` is made.
  1931. fn twin(&self, index: u32) -> Option<D3D12_CPU_DESCRIPTOR_HANDLE> {
  1932. (index < self.twins.len() as u32).then(|| staged(self.sampler, 1).unwrap_or_else(|| self.cpu(self.raw + index)))
  1933. }
  1934. /// The raw twin of slot `index` was made by this thread ([`make_twinned`]),
  1935. /// or is a null view if it was not.
  1936. fn twin_made(&self, index: u32, made: bool) {
  1937. if !made {
  1938. return self.clear_twin(index);
  1939. }
  1940. if let Some(shown) = self.twins.get(index as usize) {
  1941. self.put_twin(index);
  1942. shown.store(true, std::sync::atomic::Ordering::Relaxed);
  1943. }
  1944. }
  1945. /// The raw twin of slot `index` is a null view again.
  1946. fn clear_twin(&self, index: u32) {
  1947. if let Some(made) = self.twins.get(index as usize)
  1948. && made.swap(false, std::sync::atomic::Ordering::Relaxed)
  1949. {
  1950. null_buffer_view(self.at(self.raw + index));
  1951. self.put(self.raw + index);
  1952. }
  1953. }
  1954. /// Slot `index` now views `resource` (or nothing of the host's).
  1955. fn keep(&self, index: u32, resource: Option<ID3D12Resource>) {
  1956. let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
  1957. if let Some(slot) = kept.get_mut(index as usize) {
  1958. use windows::core::Interface;
  1959. // The same again: nothing to retire.
  1960. if slot.as_ref().map(Interface::as_raw) == resource.as_ref().map(Interface::as_raw) {
  1961. return;
  1962. }
  1963. // A running submission may still read the old resource through
  1964. // this slot.
  1965. if let Some(old) = std::mem::replace(slot, resource) {
  1966. crate::host::retire(old);
  1967. }
  1968. }
  1969. }
  1970. /// Makes slot `index` (a dynamic one) a raw buffer view of `len` bytes
  1971. /// of `buffer` from byte `offset` (a multiple of 16): a root SRV with a
  1972. /// size, whose reads past it return zeros instead of reaching whatever
  1973. /// the host placed after the buffer.
  1974. pub(crate) fn raw_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) {
  1975. let Some(host) = host() else { return };
  1976. let elements = (len / 4).clamp(1, u64::from(u32::MAX)) as u32;
  1977. let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1978. Format: DXGI_FORMAT_R32_TYPELESS,
  1979. ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
  1980. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  1981. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1982. Buffer: D3D12_BUFFER_SRV {
  1983. FirstElement: offset / 4,
  1984. NumElements: elements,
  1985. StructureByteStride: 0,
  1986. Flags: D3D12_BUFFER_SRV_FLAG_RAW,
  1987. },
  1988. },
  1989. };
  1990. // SAFETY: a slot of our heap and a live buffer covering the range.
  1991. unsafe {
  1992. host.device
  1993. .CreateShaderResourceView(buffer, Some(&desc), self.at(index))
  1994. };
  1995. self.put(index);
  1996. // (Bound by its handle, not read by index.)
  1997. self.clear_twin(index);
  1998. self.keep(index, Some(buffer.clone()));
  1999. }
  2000. /// Makes slot `index` (a dynamic one) a raw buffer view that reads
  2001. /// zeros.
  2002. pub(crate) fn null_raw_at(&self, index: u32) {
  2003. null_buffer_view(self.at(index));
  2004. self.put(index);
  2005. self.clear_twin(index);
  2006. self.keep(index, None);
  2007. }
  2008. /// Makes slot `index` (a dynamic one) a raw unordered access view of
  2009. /// `len` bytes of `buffer` from byte `offset` (a multiple of 16): a
  2010. /// root UAV with a size, whose accesses past it do nothing instead of
  2011. /// reaching whatever the host placed after the buffer.
  2012. pub(crate) fn raw_uav_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) {
  2013. let Some(host) = host() else { return };
  2014. let elements = (len / 4).clamp(1, u64::from(u32::MAX)) as u32;
  2015. let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
  2016. Format: DXGI_FORMAT_R32_TYPELESS,
  2017. ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
  2018. Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 {
  2019. Buffer: D3D12_BUFFER_UAV {
  2020. FirstElement: offset / 4,
  2021. NumElements: elements,
  2022. StructureByteStride: 0,
  2023. CounterOffsetInBytes: 0,
  2024. Flags: D3D12_BUFFER_UAV_FLAG_RAW,
  2025. },
  2026. },
  2027. };
  2028. // SAFETY: a slot of our heap and a live buffer covering the range.
  2029. unsafe {
  2030. host.device.CreateUnorderedAccessView(
  2031. buffer,
  2032. None::<&ID3D12Resource>,
  2033. Some(&desc),
  2034. self.at(index),
  2035. )
  2036. };
  2037. self.put(index);
  2038. self.clear_twin(index);
  2039. self.keep(index, Some(buffer.clone()));
  2040. }
  2041. /// Makes slot `index` (a dynamic one) a raw unordered access view of
  2042. /// nothing: reads give zeros, writes are dropped.
  2043. pub(crate) fn null_raw_uav_at(&self, index: u32) {
  2044. let Some(host) = host() else { return };
  2045. let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
  2046. Format: DXGI_FORMAT_R32_TYPELESS,
  2047. ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
  2048. Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 {
  2049. Buffer: D3D12_BUFFER_UAV {
  2050. NumElements: 1,
  2051. Flags: D3D12_BUFFER_UAV_FLAG_RAW,
  2052. ..Default::default()
  2053. },
  2054. },
  2055. };
  2056. // SAFETY: a slot of our heap; a null resource is allowed with a desc.
  2057. unsafe {
  2058. host.device.CreateUnorderedAccessView(
  2059. None::<&ID3D12Resource>,
  2060. None::<&ID3D12Resource>,
  2061. Some(&desc),
  2062. self.at(index),
  2063. )
  2064. };
  2065. self.put(index);
  2066. self.clear_twin(index);
  2067. self.keep(index, None);
  2068. }
  2069. /// The shader-visible handle of slot `index`.
  2070. pub(crate) fn gpu_handle(&self, index: u32) -> D3D12_GPU_DESCRIPTOR_HANDLE {
  2071. // SAFETY: a live shader-visible heap.
  2072. let start = unsafe { self.heap.GetGPUDescriptorHandleForHeapStart().ptr };
  2073. D3D12_GPU_DESCRIPTOR_HANDLE {
  2074. ptr: start + u64::from(index) * u64::from(self.step),
  2075. }
  2076. }
  2077. /// Makes slot `index` (a dynamic one) a constant buffer view of host
  2078. /// memory, `size` bytes at `gpu` of `buffer`, which the slot holds.
  2079. ///
  2080. /// The list holds it too, until it is reset; the slot shows it until it
  2081. /// is made again, and a shader that picks the slot by an index it
  2082. /// computes from wrong data reads it through there. The list's scratch
  2083. /// chunks go back to the pool and are freed past its limit: session n02
  2084. /// lost the device to a page fault in the memory of three freed ones.
  2085. /// `VICTORY_SLOT_HOLDS=0`: only the list holds it, as before.
  2086. pub(crate) fn constant_at(&self, index: u32, buffer: &ID3D12Resource, gpu: u64, size: u32) {
  2087. static HOLDS: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  2088. let holds = *HOLDS.get_or_init(|| std::env::var_os("VICTORY_SLOT_HOLDS").is_none_or(|v| v != "0"));
  2089. let Some(host) = host() else { return };
  2090. let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC {
  2091. BufferLocation: gpu,
  2092. SizeInBytes: constant_bytes(size),
  2093. };
  2094. // SAFETY: a slot of our heap; the memory is the caller's.
  2095. unsafe {
  2096. host.device
  2097. .CreateConstantBufferView(Some(&desc), self.at(index))
  2098. };
  2099. self.put(index);
  2100. // A program that reads it as raw bytes reads its twin.
  2101. let twin = self.twin(index).filter(|_| desc.SizeInBytes > 0);
  2102. if let Some(twin) = twin {
  2103. // SAFETY: a live buffer that holds the range.
  2104. let first = (gpu - unsafe { buffer.GetGPUVirtualAddress() }) / 4;
  2105. let raw = D3D12_SHADER_RESOURCE_VIEW_DESC {
  2106. Format: DXGI_FORMAT_R32_TYPELESS,
  2107. ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
  2108. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  2109. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  2110. Buffer: D3D12_BUFFER_SRV {
  2111. FirstElement: first,
  2112. NumElements: desc.SizeInBytes / 4,
  2113. StructureByteStride: 0,
  2114. Flags: D3D12_BUFFER_SRV_FLAG_RAW,
  2115. },
  2116. },
  2117. };
  2118. // SAFETY: as above, and a slot of our heaps.
  2119. unsafe { host.device.CreateShaderResourceView(buffer, Some(&raw), twin) };
  2120. }
  2121. self.twin_made(index, twin.is_some());
  2122. // After the descriptor: what it showed is let go when nothing shows
  2123. // it any more.
  2124. self.keep(index, holds.then(|| buffer.clone()));
  2125. }
  2126. /// Where a descriptor for slot `index` is made, then [`HostHeap::put`]:
  2127. /// a slot of this thread's in a heap the card does not see
  2128. /// ([`staged`]), or the slot itself.
  2129. fn at(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  2130. staged(self.sampler, 0).unwrap_or_else(|| self.cpu(index))
  2131. }
  2132. /// The descriptor this thread made last ([`HostHeap::at`]) goes to slot
  2133. /// `index`.
  2134. fn put(&self, index: u32) {
  2135. self.copy_to(index, 0);
  2136. }
  2137. /// The raw twin this thread made last goes to that of slot `index`.
  2138. fn put_twin(&self, index: u32) {
  2139. if self.twin(index).is_some() {
  2140. self.copy_to(self.raw + index, 1);
  2141. }
  2142. }
  2143. fn copy_to(&self, to: u32, which: u32) {
  2144. let (Some(from), Some(host)) = (staged(self.sampler, which), host()) else {
  2145. return; // made in place
  2146. };
  2147. let kind = if self.sampler {
  2148. D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER
  2149. } else {
  2150. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV
  2151. };
  2152. // SAFETY: a slot of our heap, and one of this thread's heap slots.
  2153. unsafe { host.device.CopyDescriptorsSimple(1, self.cpu(to), from, kind) };
  2154. }
  2155. fn cpu(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  2156. D3D12_CPU_DESCRIPTOR_HANDLE {
  2157. ptr: self.cpu + index as usize * self.step as usize,
  2158. }
  2159. }
  2160. /// For a run of records of the title's heap from slot `first`, `step`
  2161. /// bytes each, on a page that changed with no call
  2162. /// (`super::sync_heaps`: the title copies records into its heap as
  2163. /// bytes): the slots whose record is not the one this last saw there.
  2164. ///
  2165. /// The page says only that something on it was written, and `mirror`
  2166. /// by itself would take every buffer or placed-texture record on it for
  2167. /// newly written each time (it leaves such a slot unmade until a draw
  2168. /// or a pass uses it): the texture queue's entry for the slot would
  2169. /// start again, and the buffer pass would look at 2,048 slots for one
  2170. /// that changed.
  2171. /// `records`: their bytes as the caller read them (through the
  2172. /// kernel, which fails on a page the title unmapped meanwhile where a
  2173. /// read in place would fault: the title unmaps heap pages too).
  2174. pub(crate) fn copied_changes(&self, first: u32, records: &[u8], step: usize, out: &mut Vec<u32>) {
  2175. let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
  2176. if copied.is_empty() {
  2177. // Nothing there: a slot never looked at that holds nothing is
  2178. // as it was.
  2179. copied.resize(self.count as usize * step, 0);
  2180. }
  2181. let at = first as usize * step;
  2182. let end = (at + records.len()).min(copied.len());
  2183. let Some(last) = copied.get_mut(at..end) else {
  2184. return;
  2185. };
  2186. let records = &records[..last.len()];
  2187. if last == records {
  2188. return;
  2189. }
  2190. for (n, (old, new)) in last.chunks_exact_mut(step).zip(records.chunks_exact(step)).enumerate() {
  2191. if old != new {
  2192. old.copy_from_slice(new);
  2193. out.push(first + n as u32);
  2194. }
  2195. }
  2196. }
  2197. /// Whether new records of draws' tables are left to the draws
  2198. /// (`VICTORY_HEAP_SYNC=all`: every new record is mirrored at once, as
  2199. /// it first was).
  2200. ///
  2201. /// The title builds each draw's tables in its heap by copying records
  2202. /// there as bytes: 60,000 to 210,000 a frame in its world (session
  2203. /// play-1125-0127), 0.9 microseconds each on the submitting thread and
  2204. /// 1.4 more in the buffer pass they were all handed to, 120 to 600 ms
  2205. /// of every frame, and the draws make what they read of them anyway.
  2206. pub(crate) fn copied_waits(&self) -> bool {
  2207. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  2208. *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SYNC").is_none_or(|v| v != "all"))
  2209. }
  2210. /// Whether a draw read title slot `index` through a table within the
  2211. /// last few frames before `frame` ([`HostHeap::tabled`]): what it holds
  2212. /// is such a draw's to make.
  2213. pub(crate) fn copied_tabled(&self, index: u32, frame: u64) -> bool {
  2214. if !self.copied_waits() {
  2215. return false;
  2216. }
  2217. let stamp = self.tabled_stamp(index) & !TABLED_READ;
  2218. let now = (frame as u32).wrapping_add(1) & !TABLED_READ;
  2219. stamp != 0 && now.wrapping_sub(stamp) & !TABLED_READ <= COPIED_FRAMES
  2220. }
  2221. /// New records the title copied into slots `slots` in `frame` wait for
  2222. /// the draw that may read them through a table.
  2223. pub(crate) fn copied_wait(&self, frame: u64, slots: Vec<u32>) {
  2224. self.waiting.lock().unwrap_or_else(|e| e.into_inner()).push_back((frame, slots));
  2225. }
  2226. /// The slots that have waited long enough at `frame`
  2227. /// ([`HostHeap::copied_wait`]), each once.
  2228. pub(crate) fn copied_before(&self, frame: u64) -> Vec<u32> {
  2229. let mut waiting = self.waiting.lock().unwrap_or_else(|e| e.into_inner());
  2230. let mut out = Vec::new();
  2231. while waiting.front().is_some_and(|(written, _)| written + COPIED_GRACE <= frame) {
  2232. out.extend(waiting.pop_front().into_iter().flat_map(|(_, slots)| slots));
  2233. }
  2234. drop(waiting);
  2235. out.sort_unstable();
  2236. out.dedup();
  2237. out
  2238. }
  2239. /// Makes host slot `index` from the record the title has at `handle`
  2240. /// if it changed since, and returns the view recorded there. Buffer
  2241. /// views are made only for draws (`for_draw`), which also copy their
  2242. /// data: a host copy of a buffer is made on first use.
  2243. pub(crate) fn mirror(&self, index: u32, handle: u64, for_draw: bool) -> Option<View> {
  2244. if index >= self.count {
  2245. // Diagnostic (NVIDIA heap cap): the highest title slot past the
  2246. // host heap seen so far.
  2247. static HIGHEST: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  2248. if HIGHEST.fetch_max(index, std::sync::atomic::Ordering::Relaxed) < index {
  2249. tracing::warn!(
  2250. index,
  2251. count = self.count,
  2252. for_draw,
  2253. "title slot past the host heap"
  2254. );
  2255. }
  2256. return None;
  2257. }
  2258. // SAFETY: the handle is a descriptor slot in title memory.
  2259. let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() };
  2260. // Generations start at 1, so a made slot's key is never 0.
  2261. let key = u64::from(generation) << 32 | u64::from(i);
  2262. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  2263. let view = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten();
  2264. let Some(view) = view else {
  2265. // Not a view of ours (never written, or of a resource the
  2266. // title released): nothing to read.
  2267. if made[index as usize] != 0 {
  2268. made[index as usize] = 0;
  2269. self.make_null(index);
  2270. let _ = self.note_buffer(index, None, false);
  2271. } else if for_draw {
  2272. // Left for later and stale since: out of the sets and the stride table.
  2273. let _ = self.note_buffer(index, None, false);
  2274. }
  2275. return None;
  2276. };
  2277. if made[index as usize] != key {
  2278. // Views of other textures in the memory this one describes
  2279. // are stale: their host slots read nothing from here on, and
  2280. // let go of the host copies they held.
  2281. for stale in self.note_buffer(index, Some(&view), for_draw) {
  2282. if stale != index {
  2283. self.unmake(&mut made, stale);
  2284. }
  2285. }
  2286. // A view of a texture object that has no host copy yet waits
  2287. // for it, as buffer views wait for a draw: the slot is made
  2288. // when the texture is first used (`super::make_waiting`), or
  2289. // here when a draw reads the slot through a table.
  2290. let waiting = if for_draw { None } else { view.waiting_texture() };
  2291. if let Some(texture) = waiting {
  2292. super::wait_for(texture, handle);
  2293. }
  2294. let later = !for_draw && (view.is_buffer() || waiting.is_some());
  2295. // Another view of the placed texture the slot shows already (a
  2296. // title that streams a texture in writes its view again with
  2297. // more mips each time some arrive): the slot goes on showing
  2298. // the old view until a draw or the texture pass makes the new
  2299. // one and uploads what it shows. Made null here, the texture
  2300. // read as nothing for as long as it waited in the queue, every
  2301. // time it got sharper.
  2302. if later
  2303. && keep_views()
  2304. && view_at(made[index as usize] as u32, (made[index as usize] >> 32) as u32)
  2305. .is_some_and(|old| same_placed_texture(&old, &view))
  2306. {
  2307. KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2308. return Some(view);
  2309. }
  2310. made[index as usize] = if later { 0 } else { key };
  2311. let kept = if later {
  2312. None
  2313. } else {
  2314. make_twinned(&view, self.at(index), self.twin(index))
  2315. };
  2316. if kept.is_none() && !self.sampler {
  2317. null_for(&view, self.at(index));
  2318. }
  2319. if kept.is_some() || !self.sampler {
  2320. self.put(index);
  2321. }
  2322. self.twin_made(index, kept.is_some() && twinned(&view));
  2323. self.keep(index, kept.flatten());
  2324. }
  2325. Some(view)
  2326. }
  2327. /// Whether slot `index` is backed by a made host descriptor (tests).
  2328. #[cfg(test)]
  2329. pub(crate) fn made(&self, index: u32) -> bool {
  2330. self.made
  2331. .lock()
  2332. .unwrap_or_else(|e| e.into_inner())
  2333. .get(index as usize)
  2334. .is_some_and(|&key| key != 0)
  2335. }
  2336. /// Whether host slot `index` shows `buffer`; `None` if it shows no
  2337. /// resource (diagnostics: a buffer view's slot must show the host copy
  2338. /// that is brought up to date for it).
  2339. #[cfg(feature = "diagnostics")]
  2340. pub(crate) fn shows(&self, index: u32, buffer: &ID3D12Resource) -> Option<bool> {
  2341. let kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
  2342. let shown = kept.get(index as usize)?.as_ref()?;
  2343. Some(windows::core::Interface::as_raw(shown) == windows::core::Interface::as_raw(buffer))
  2344. }
  2345. /// What the queue of textures picked by index knows of title slot
  2346. /// `index` at `frame`, in a few words (diagnostics).
  2347. #[cfg(feature = "diagnostics")]
  2348. pub(crate) fn texture_slot_state(&self, index: u32, frame: u64) -> String {
  2349. let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  2350. match textures.slots.get(&index) {
  2351. None => "not queued".into(),
  2352. Some(w) => format!(
  2353. "queued due={} written@{} looks={} part_mapped={} recheck={}",
  2354. if w.due <= frame { "now".to_string() } else { format!("@{}", w.due) },
  2355. w.written,
  2356. w.looks,
  2357. w.mapped,
  2358. w.checked.2 != 0
  2359. ),
  2360. }
  2361. }
  2362. /// The view host slot `index` was made from, in a few words, with the
  2363. /// title and host addresses of a buffer view (diagnostics). "null" for
  2364. /// a slot never made or left null.
  2365. #[cfg(feature = "diagnostics")]
  2366. pub(crate) fn describe_slot(&self, index: u32) -> Option<String> {
  2367. let key = *self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize)?;
  2368. if key == 0 {
  2369. return Some("null".into());
  2370. }
  2371. let view = view_at(key as u32, (key >> 32) as u32)?;
  2372. let mut text: String = format!("{view:?}").chars().take(120).collect();
  2373. if let Some((address, len)) = buffer_range(&view) {
  2374. let host = crate::shadow::find(address, len.max(1)).map(|s| s.gpu(address));
  2375. text.push_str(&format!(" title {address:#x}+{len:#x} host {host:#x?}"));
  2376. }
  2377. Some(text)
  2378. }
  2379. }
  2380. /// Slots of this thread's own in heaps the card does not see, two of views
  2381. /// and two of samplers (`which` 0 or 1): descriptors are made there and
  2382. /// copied whole into the heaps it does see. Made in place they are seen half
  2383. /// written: an RX 7900 XTX saw a texture of no size in 4 % of its reads of
  2384. /// slots whose views a thread made over and over (the driver clears the
  2385. /// descriptor and fills it step by step), and none in 8,500 million with the
  2386. /// same descriptors copied, three times as fast
  2387. /// (`indirect::tests::descriptors_written_under_readers`). Title threads and
  2388. /// our passes rewrite slots while submissions run whose shaders pick them;
  2389. /// three device losses of 2026-11-25 (play-1125-0203, n02, n03) were reads of
  2390. /// memory no view names. `VICTORY_VIEW_COPY=0`: made in place, as before.
  2391. fn staged(sampler: bool, which: u32) -> Option<D3D12_CPU_DESCRIPTOR_HANDLE> {
  2392. /// Threads at a time that have slots; more make views in place.
  2393. const THREADS: u32 = 4096;
  2394. struct Stage {
  2395. starts: [usize; 2],
  2396. steps: [usize; 2],
  2397. _heaps: [ID3D12DescriptorHeap; 2],
  2398. }
  2399. // SAFETY: descriptor heaps are free-threaded; each thread has slots of
  2400. // its own.
  2401. unsafe impl Send for Stage {}
  2402. // SAFETY: as above.
  2403. unsafe impl Sync for Stage {}
  2404. static STAGE: std::sync::OnceLock<Option<Stage>> = std::sync::OnceLock::new();
  2405. /// Places given back, and how many were ever given out.
  2406. static PLACES: Mutex<(Vec<u32>, u32)> = Mutex::new((Vec::new(), 0));
  2407. struct Place(Option<u32>);
  2408. impl Drop for Place {
  2409. fn drop(&mut self) {
  2410. if let Some(place) = self.0 {
  2411. PLACES.lock().unwrap_or_else(|e| e.into_inner()).0.push(place);
  2412. }
  2413. }
  2414. }
  2415. thread_local! {
  2416. static PLACE: Place = {
  2417. let mut places = PLACES.lock().unwrap_or_else(|e| e.into_inner());
  2418. Place(places.0.pop().or_else(|| {
  2419. (places.1 < THREADS).then(|| {
  2420. places.1 += 1;
  2421. places.1 - 1
  2422. })
  2423. }))
  2424. };
  2425. }
  2426. let stage = STAGE
  2427. .get_or_init(|| {
  2428. if std::env::var_os("VICTORY_VIEW_COPY").is_some_and(|v| v == "0") {
  2429. return None;
  2430. }
  2431. let host = host()?;
  2432. let make = |kind: D3D12_DESCRIPTOR_HEAP_TYPE| -> Option<ID3D12DescriptorHeap> {
  2433. // SAFETY: plain heap creation.
  2434. unsafe {
  2435. host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  2436. Type: kind,
  2437. NumDescriptors: 2 * THREADS,
  2438. ..Default::default()
  2439. })
  2440. }
  2441. .inspect_err(|e| tracing::warn!(error = %e, "no heap to make views in: they are made in place"))
  2442. .ok()
  2443. };
  2444. let kinds = [D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER];
  2445. let heaps = [make(kinds[0])?, make(kinds[1])?];
  2446. // SAFETY: live heaps, plain queries.
  2447. let (starts, steps) = unsafe {
  2448. (
  2449. [0, 1].map(|i: usize| heaps[i].GetCPUDescriptorHandleForHeapStart().ptr),
  2450. kinds.map(|kind| host.device.GetDescriptorHandleIncrementSize(kind) as usize),
  2451. )
  2452. };
  2453. Some(Stage { starts, steps, _heaps: heaps })
  2454. })
  2455. .as_ref()?;
  2456. // (A thread that is ending has none any more.)
  2457. let place = PLACE.try_with(|p| p.0).ok().flatten()?;
  2458. let kind = usize::from(sampler);
  2459. Some(D3D12_CPU_DESCRIPTOR_HANDLE {
  2460. ptr: stage.starts[kind] + (2 * place + which) as usize * stage.steps[kind],
  2461. })
  2462. }
  2463. /// Logs `what` the first time it happens.
  2464. macro_rules! once {
  2465. ($($arg:tt)*) => {{
  2466. static ONCE: std::sync::Once = std::sync::Once::new();
  2467. ONCE.call_once(|| tracing::warn!($($arg)*));
  2468. }};
  2469. }
  2470. /// A view description from its words, with the format as the host has it.
  2471. fn srv_desc(words: &[u32; 10]) -> D3D12_SHADER_RESOURCE_VIEW_DESC {
  2472. let mut words = *words;
  2473. words[0] = crate::resource::pc_format(words[0]);
  2474. // SAFETY: 40 bytes in the host's layout.
  2475. unsafe {
  2476. std::ptr::from_ref(&words)
  2477. .cast::<D3D12_SHADER_RESOURCE_VIEW_DESC>()
  2478. .read_unaligned()
  2479. }
  2480. }
  2481. fn uav_desc(words: &[u32; 10]) -> D3D12_UNORDERED_ACCESS_VIEW_DESC {
  2482. let mut words = *words;
  2483. words[0] = crate::resource::pc_format(words[0]);
  2484. // SAFETY: 40 bytes in the host's layout.
  2485. unsafe {
  2486. std::ptr::from_ref(&words)
  2487. .cast::<D3D12_UNORDERED_ACCESS_VIEW_DESC>()
  2488. .read_unaligned()
  2489. }
  2490. }
  2491. /// A buffer view of title memory at `address` on its host copy: the first
  2492. /// element moves by the copy's offset.
  2493. /// Bytes per element of a buffer view.
  2494. fn element_size(desc: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> u64 {
  2495. // SAFETY: a buffer view's union member.
  2496. let buffer = unsafe { desc.Anonymous.Buffer };
  2497. if buffer.StructureByteStride > 0 {
  2498. u64::from(buffer.StructureByteStride)
  2499. } else if buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0 {
  2500. 4
  2501. } else {
  2502. crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
  2503. }
  2504. }
  2505. /// The title memory a buffer shader or unordered access view reads: its
  2506. /// address and length.
  2507. pub(crate) fn buffer_range(view: &View) -> Option<(u64, u64)> {
  2508. let (base, words): (u64, &[u32; 10]) = match view {
  2509. View::Shader(r, Some(desc)) => (
  2510. crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64,
  2511. desc,
  2512. ),
  2513. View::Placed(false, resource, desc) if resource[0] == 1 => (
  2514. u64::from(desc[10]) | u64::from(desc[11]) << 32,
  2515. desc[..10].try_into().ok()?,
  2516. ),
  2517. View::Unordered(r, _, Some(desc)) => {
  2518. let base = crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64;
  2519. return unordered_range(base, desc);
  2520. }
  2521. View::Placed(true, resource, desc) if resource[0] == 1 => {
  2522. let base = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  2523. return unordered_range(base, desc[..10].try_into().ok()?);
  2524. }
  2525. _ => return None,
  2526. };
  2527. let desc = srv_desc(words);
  2528. let element = element_size(&desc);
  2529. // SAFETY: a buffer view's union member.
  2530. let buffer = unsafe { desc.Anonymous.Buffer };
  2531. Some((
  2532. base + buffer.FirstElement * element,
  2533. u64::from(buffer.NumElements) * element,
  2534. ))
  2535. }
  2536. /// The address a shader finds in a descriptor of title memory: where a
  2537. /// buffer view starts, or the ray-tracing structure of a structure's view
  2538. /// (no resource: the view's description holds the address, and the shader
  2539. /// walks the structure from there itself).
  2540. pub(crate) fn view_address(view: &View) -> Option<u64> {
  2541. const STRUCTURE: u32 = D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE.0 as u32;
  2542. match view {
  2543. View::Shader(_, Some(desc)) if desc[1] == STRUCTURE => {
  2544. Some(u64::from(desc[4]) | u64::from(desc[5]) << 32)
  2545. }
  2546. _ => buffer_range(view).map(|range| range.0),
  2547. }
  2548. }
  2549. /// The title memory the host slot of buffer view `view` is made on
  2550. /// (address, bytes): the whole buffer the view is of, which is what
  2551. /// [`make`] finds the host copy by. [`buffer_range`] is the part of it the
  2552. /// view reads.
  2553. pub(crate) fn buffer_extent(view: &View) -> Option<(u64, u64)> {
  2554. match view {
  2555. View::Shader(r, Some(_)) | View::Unordered(r, _, Some(_)) => {
  2556. let (data, len) = crate::resource::buffer_bytes(*r as crate::object::This)?;
  2557. Some((data as u64, len))
  2558. }
  2559. View::Placed(_, resource, desc) if resource[0] == 1 => Some((
  2560. u64::from(desc[10]) | u64::from(desc[11]) << 32,
  2561. u64::from(resource[4]) | u64::from(resource[5]) << 32,
  2562. )),
  2563. _ => None,
  2564. }
  2565. }
  2566. /// Whether a buffer view is brought up to date in the host copy its slot
  2567. /// shows ([`buffer_copy`]). On by default; `VICTORY_VIEW_EXTENT=0` looks the
  2568. /// copy up by the view's range alone, as before.
  2569. fn view_extent() -> bool {
  2570. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  2571. *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_EXTENT").is_none_or(|v| v != "0"))
  2572. }
  2573. /// The host copy buffer view `view` reads, and the title range (address,
  2574. /// bytes) it reads there; `None` for other views and empty ranges.
  2575. ///
  2576. /// The copy is the one the view's slot shows: [`make`] finds it by the
  2577. /// whole buffer the view is of ([`buffer_extent`]). Looked up by the range
  2578. /// the view reads, as it was, the copy is another one wherever the two
  2579. /// lookups differ: for memory outside buffer objects, a view of a part of a
  2580. /// buffer that crosses a window line (the buffer's window is two cells, the
  2581. /// part's one), and for buffer objects, a part that also lies in a smaller
  2582. /// buffer object. The slot then showed a copy nothing brought up to date,
  2583. /// and what shaders wrote through it was looked for in the other copy.
  2584. pub(crate) fn buffer_copy(view: &View) -> Option<(std::sync::Arc<crate::shadow::Shadow>, u64, u64)> {
  2585. let (address, len) = buffer_range(view)?;
  2586. if len == 0 {
  2587. return None;
  2588. }
  2589. if view_extent()
  2590. && let Some((base, width)) = buffer_extent(view)
  2591. // (The console is lax: a view may begin past its buffer's end.)
  2592. && address >= base
  2593. && address - base < width.max(1)
  2594. && let Some(shadow) = crate::shadow::find(base, width)
  2595. {
  2596. return Some((view_home(shadow, address, len, view_elements(view)?), address, len));
  2597. }
  2598. let shadow = crate::shadow::find(address, len)?;
  2599. Some((view_home(shadow, address, len, view_elements(view)?), address, len))
  2600. }
  2601. /// [`buffer_range`] of an unordered access view of memory at `base`.
  2602. fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> {
  2603. let desc = uav_desc(words);
  2604. // SAFETY: a buffer view's union member.
  2605. let buffer = unsafe { desc.Anonymous.Buffer };
  2606. let element = if buffer.StructureByteStride > 0 {
  2607. u64::from(buffer.StructureByteStride)
  2608. } else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 {
  2609. 4
  2610. } else {
  2611. crate::resource::element(desc.Format.0 as u32)?.0
  2612. };
  2613. Some((
  2614. base + buffer.FirstElement * element,
  2615. u64::from(buffer.NumElements) * element,
  2616. ))
  2617. }
  2618. /// The host resource a slot made by [`make`] views, if any.
  2619. type Kept = Option<ID3D12Resource>;
  2620. /// A structured buffer view (`first`, `count` elements of `stride` bytes,
  2621. /// `offset` bytes into its host copy) as a raw view of the same bytes:
  2622. /// its first dword and its dwords. Translated shaders read untyped buffers
  2623. /// as raw bytes at `element * stride + offset` (the stride from the
  2624. /// used-resource entry, or from the table by heap slot for a buffer picked
  2625. /// by index), and a raw read through a structured view gives zeros on
  2626. /// NVIDIA (reported upstream with PR #193; structured reads through raw
  2627. /// views were right there). So the host's view is raw whenever it can be:
  2628. /// the bytes must start on 16 (the host's raw view alignment) and be whole
  2629. /// dwords. A view that cannot stays structured.
  2630. fn raw_window(offset: u64, first: u64, count: u32, stride: u32) -> Option<(u64, u32)> {
  2631. if stride == 0 {
  2632. return None;
  2633. }
  2634. let start = first.checked_mul(u64::from(stride))?.checked_add(offset)?;
  2635. let bytes = u64::from(count) * u64::from(stride);
  2636. (start % 16 == 0 && bytes % 4 == 0)
  2637. .then(|| u32::try_from(bytes / 4).ok().map(|dwords| (start / 4, dwords)))
  2638. .flatten()
  2639. }
  2640. /// Whether the host accepts a buffer view with these fields of a buffer of
  2641. /// `width` bytes. It removes the device for one it does not (view creation
  2642. /// returns nothing), and the console is laxer: the title's heap holds
  2643. /// views past their memory's end, of no elements, of typeless formats
  2644. /// without the raw flag, with strides the host has no structured buffers
  2645. /// for. Since every buffer view of the heap is made for shaders that pick
  2646. /// them by index, one such view ended the run (2026-11-24, run 10).
  2647. fn buffer_view_ok(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bool, width: u64) -> bool {
  2648. use crate::resource::family;
  2649. let f = format.0 as u32;
  2650. let element = if raw {
  2651. // raw: R32 typeless, counted in dwords, starting on 16 bytes
  2652. if format != DXGI_FORMAT_R32_TYPELESS || stride != 0 || !first.is_multiple_of(4) {
  2653. return false;
  2654. }
  2655. 4
  2656. } else if stride > 0 {
  2657. // structured: no format, a stride the host takes
  2658. if format != DXGI_FORMAT_UNKNOWN || stride > 2048 || !stride.is_multiple_of(4) {
  2659. return false;
  2660. }
  2661. u64::from(stride)
  2662. } else {
  2663. // typed: a format with a size that is not typeless
  2664. let typeless = family(f) == f && family(f + 1) == f;
  2665. match crate::resource::element(f) {
  2666. Some((bytes, 1)) if f != 0 && !typeless && bytes > 0 => bytes,
  2667. _ => return false,
  2668. }
  2669. };
  2670. count > 0
  2671. && first
  2672. .checked_add(u64::from(count))
  2673. .and_then(|end| end.checked_mul(element))
  2674. .is_some_and(|end| end <= width)
  2675. }
  2676. /// Raw twins ([`raw_twins`]) made since the last frame line, and those of them that
  2677. /// do not begin on 16 bytes, as a raw view must ([`move_raw`]), and those of
  2678. /// these that could not be moved there (null).
  2679. pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  2680. /// Moves the raw view at `at`, a slot of our heaps the card does not see,
  2681. /// which shows `bytes` from `start` on (GPU address), `by` bytes on: for a
  2682. /// twin whose view begins between two multiples of 16, where the host makes
  2683. /// no raw view. An AMD descriptor of a raw buffer is its address (48 bits),
  2684. /// its bytes and flags; only one that says just that is changed, and only
  2685. /// where what the handle points at is the descriptor. False: not moved.
  2686. pub(crate) fn move_raw(at: D3D12_CPU_DESCRIPTOR_HANDLE, start: u64, bytes: u32, by: u32) -> bool {
  2687. // (Off dwords too, as the typed view it stands for begins there: a view
  2688. // of 16 bit values at an odd one.)
  2689. if by >= bytes {
  2690. return false;
  2691. }
  2692. let mut words = [0u8; 16];
  2693. if !crate::host::read_into(at.ptr as *const u8, &mut words) {
  2694. return false;
  2695. }
  2696. let word = |i: usize| u32::from_le_bytes([words[4 * i], words[4 * i + 1], words[4 * i + 2], words[4 * i + 3]]);
  2697. let address = u64::from(word(0)) | u64::from(word(1)) << 32;
  2698. if address != start || word(2) != bytes || start >> 48 != 0 {
  2699. return false;
  2700. }
  2701. let moved = start + u64::from(by);
  2702. // SAFETY: this thread's own slot (it has slots of its own: the caller
  2703. // asks only for those), read just now.
  2704. unsafe {
  2705. let words = at.ptr as *mut u32;
  2706. words.write(moved as u32);
  2707. words.add(1).write((moved >> 32) as u32);
  2708. words.add(2).write(bytes - by);
  2709. }
  2710. true
  2711. }
  2712. /// The bytes a buffer view the host takes ([`buffer_view_ok`]) shows as a raw
  2713. /// view (first dword, dwords, and the bytes past that dword it begins: a raw
  2714. /// view begins on 16 bytes); of a buffer of `width` bytes.
  2715. fn twin_window(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bool, width: u64) -> Option<(u64, u32, u32)> {
  2716. use std::sync::atomic::Ordering::Relaxed;
  2717. TWINS[0].fetch_add(1, Relaxed);
  2718. let element = if raw {
  2719. 4
  2720. } else if stride > 0 {
  2721. u64::from(stride)
  2722. } else {
  2723. crate::resource::element(format.0 as u32).map_or(0, |(bytes, _)| bytes)
  2724. };
  2725. let (start, end) = (first * element, ((first + u64::from(count)) * element).next_multiple_of(4));
  2726. let end = end.min(width & !3);
  2727. let from = start & !15;
  2728. if end <= start {
  2729. return None;
  2730. }
  2731. let dwords = u32::try_from((end - from) / 4).ok()?;
  2732. if from != start {
  2733. TWINS[1].fetch_add(1, Relaxed);
  2734. }
  2735. Some((from / 4, dwords, (start - from) as u32))
  2736. }
  2737. fn buffer_srv(
  2738. address: u64,
  2739. len: u64,
  2740. mut desc: D3D12_SHADER_RESOURCE_VIEW_DESC,
  2741. at: D3D12_CPU_DESCRIPTOR_HANDLE,
  2742. twin: Option<D3D12_CPU_DESCRIPTOR_HANDLE>,
  2743. ) -> Option<Kept> {
  2744. let mut shadow = crate::shadow::find(address, len)?;
  2745. let mut offset = shadow.offset(address);
  2746. let unit = element_size(&desc);
  2747. // SAFETY: a buffer view's union member.
  2748. let own = unsafe { &mut desc.Anonymous.Buffer };
  2749. let start = address + own.FirstElement * unit;
  2750. let kind = (own.StructureByteStride, own.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0, desc.Format.0 as u32);
  2751. let home = view_home(shadow.clone(), start, u64::from(own.NumElements) * unit, kind);
  2752. if !std::sync::Arc::ptr_eq(&home, &shadow) {
  2753. // Its own bytes: it begins where they do.
  2754. (shadow, offset) = (home, 0);
  2755. own.FirstElement = 0;
  2756. }
  2757. // A structured view as a raw view of the same bytes (see `raw_window`).
  2758. // SAFETY: a buffer view's union member.
  2759. let structured = unsafe { desc.Anonymous.Buffer };
  2760. let window = (desc.Format == DXGI_FORMAT_UNKNOWN)
  2761. .then(|| raw_window(offset, structured.FirstElement, structured.NumElements, structured.StructureByteStride))
  2762. .flatten();
  2763. if let Some((first, count)) = window {
  2764. desc.Format = DXGI_FORMAT_R32_TYPELESS;
  2765. desc.Anonymous.Buffer = D3D12_BUFFER_SRV {
  2766. FirstElement: first,
  2767. NumElements: count,
  2768. StructureByteStride: 0,
  2769. Flags: D3D12_BUFFER_SRV_FLAG_RAW,
  2770. };
  2771. }
  2772. let element = element_size(&desc);
  2773. // SAFETY: a buffer view's union member.
  2774. let buffer = unsafe { &mut desc.Anonymous.Buffer };
  2775. if window.is_none() {
  2776. if element == 0 || offset % element != 0 {
  2777. once!(
  2778. offset,
  2779. element,
  2780. "buffer view not on an element of its host copy"
  2781. );
  2782. return None;
  2783. }
  2784. buffer.FirstElement += offset / element;
  2785. }
  2786. let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride);
  2787. let raw = buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0;
  2788. // SAFETY: a live buffer.
  2789. let width = unsafe { shadow.buffer.GetDesc() }.Width;
  2790. if !buffer_view_ok(desc.Format, first, count, stride, raw, width) {
  2791. REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2792. once!(
  2793. format = desc.Format.0,
  2794. first,
  2795. count,
  2796. stride,
  2797. raw,
  2798. width,
  2799. "buffer view the host would refuse left null"
  2800. );
  2801. return None;
  2802. }
  2803. // The console has no component mapping; one the host does not know is the default's.
  2804. if desc.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING {
  2805. desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  2806. }
  2807. let host = host()?;
  2808. // SAFETY: a live buffer and a slot of our heap.
  2809. unsafe {
  2810. host.device
  2811. .CreateShaderResourceView(&shadow.buffer, Some(&desc), at)
  2812. };
  2813. if let Some(twin) = twin {
  2814. let window = twin_window(desc.Format, first, count, stride, raw, width);
  2815. if let Some((first, count, by)) = window {
  2816. desc.Format = DXGI_FORMAT_R32_TYPELESS;
  2817. desc.Anonymous.Buffer = D3D12_BUFFER_SRV {
  2818. FirstElement: first,
  2819. NumElements: count,
  2820. StructureByteStride: 0,
  2821. Flags: D3D12_BUFFER_SRV_FLAG_RAW,
  2822. };
  2823. // SAFETY: a live buffer and a slot of our heap.
  2824. let start = unsafe {
  2825. host.device
  2826. .CreateShaderResourceView(&shadow.buffer, Some(&desc), twin);
  2827. shadow.buffer.GetGPUVirtualAddress() + first * 4
  2828. };
  2829. if by > 0 && !(staged(false, 1).is_some_and(|s| s.ptr == twin.ptr) && move_raw(twin, start, count.saturating_mul(4), by)) {
  2830. TWINS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2831. null_buffer_view(twin);
  2832. }
  2833. } else {
  2834. null_buffer_view(twin);
  2835. }
  2836. }
  2837. Some(Some(shadow.buffer.clone()))
  2838. }
  2839. /// An unordered access view of title buffer memory at `address` (`len`
  2840. /// bytes) on its host copy, as [`buffer_srv`]; false if the copy cannot be
  2841. /// written by shaders (upload memory).
  2842. /// shortcut: what shaders write stays in the host copy; title memory (and
  2843. /// so the CPU, and copies run on the CPU) does not see it.
  2844. fn buffer_uav(
  2845. address: u64,
  2846. len: u64,
  2847. mut desc: D3D12_UNORDERED_ACCESS_VIEW_DESC,
  2848. at: D3D12_CPU_DESCRIPTOR_HANDLE,
  2849. twin: Option<D3D12_CPU_DESCRIPTOR_HANDLE>,
  2850. ) -> Option<Kept> {
  2851. let mut shadow = crate::shadow::find(address, len)?;
  2852. let unit = {
  2853. // SAFETY: a buffer view's union member.
  2854. let b = unsafe { desc.Anonymous.Buffer };
  2855. if b.StructureByteStride > 0 {
  2856. u64::from(b.StructureByteStride)
  2857. } else if b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 {
  2858. 4
  2859. } else {
  2860. crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
  2861. }
  2862. };
  2863. // SAFETY: a buffer view's union member.
  2864. let own = unsafe { &mut desc.Anonymous.Buffer };
  2865. let start = address + own.FirstElement * unit;
  2866. let kind = (own.StructureByteStride, own.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0, desc.Format.0 as u32);
  2867. let home = view_home(shadow.clone(), start, u64::from(own.NumElements) * unit, kind);
  2868. let mut address = address;
  2869. if !std::sync::Arc::ptr_eq(&home, &shadow) {
  2870. // Its own bytes: it begins where they do.
  2871. (shadow, address) = (home, start);
  2872. own.FirstElement = 0;
  2873. }
  2874. // SAFETY: a live buffer.
  2875. let flags = unsafe { shadow.buffer.GetDesc() }.Flags;
  2876. if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 {
  2877. once!("unordered access to a buffer whose host copy shaders cannot write");
  2878. return None;
  2879. }
  2880. // SAFETY: a buffer view's union member.
  2881. let buffer = unsafe { &mut desc.Anonymous.Buffer };
  2882. let element = if buffer.StructureByteStride > 0 {
  2883. u64::from(buffer.StructureByteStride)
  2884. } else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 {
  2885. 4
  2886. } else {
  2887. crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
  2888. };
  2889. let offset = shadow.offset(address);
  2890. // A structured view as a raw view of the same bytes (see `raw_window`).
  2891. let window = (desc.Format == DXGI_FORMAT_UNKNOWN)
  2892. .then(|| raw_window(offset, buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride))
  2893. .flatten();
  2894. if let Some((first, count)) = window {
  2895. buffer.FirstElement = first;
  2896. buffer.NumElements = count;
  2897. buffer.StructureByteStride = 0;
  2898. buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
  2899. } else {
  2900. if element == 0 || offset % element != 0 {
  2901. once!(offset, element, "unordered buffer view not on an element of its host copy");
  2902. return None;
  2903. }
  2904. buffer.FirstElement += offset / element;
  2905. }
  2906. buffer.CounterOffsetInBytes = 0;
  2907. let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride);
  2908. let raw = buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0;
  2909. if window.is_some() {
  2910. // (Left out at first: every structured unordered access view was then
  2911. // refused by `buffer_view_ok` and left null, runs 15 and 16.)
  2912. desc.Format = DXGI_FORMAT_R32_TYPELESS;
  2913. }
  2914. // SAFETY: a live buffer.
  2915. let width = unsafe { shadow.buffer.GetDesc() }.Width;
  2916. if !buffer_view_ok(desc.Format, first, count, stride, raw, width) {
  2917. REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2918. once!(
  2919. format = desc.Format.0,
  2920. first,
  2921. count,
  2922. stride,
  2923. raw,
  2924. width,
  2925. "unordered buffer view the host would refuse left null"
  2926. );
  2927. return None;
  2928. }
  2929. let host = host()?;
  2930. // SAFETY: a live buffer and a slot of our heap.
  2931. unsafe {
  2932. host.device
  2933. .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at)
  2934. };
  2935. if let Some(twin) = twin {
  2936. let window = twin_window(desc.Format, first, count, stride, raw, width);
  2937. if let Some((first, count, by)) = window {
  2938. desc.Format = DXGI_FORMAT_R32_TYPELESS;
  2939. desc.Anonymous.Buffer = D3D12_BUFFER_UAV {
  2940. FirstElement: first,
  2941. NumElements: count,
  2942. StructureByteStride: 0,
  2943. CounterOffsetInBytes: 0,
  2944. Flags: D3D12_BUFFER_UAV_FLAG_RAW,
  2945. };
  2946. // SAFETY: a live buffer and a slot of our heap.
  2947. let start = unsafe {
  2948. host.device
  2949. .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), twin);
  2950. shadow.buffer.GetGPUVirtualAddress() + first * 4
  2951. };
  2952. if by > 0 && !(staged(false, 1).is_some_and(|s| s.ptr == twin.ptr) && move_raw(twin, start, count.saturating_mul(4), by)) {
  2953. TWINS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2954. null_buffer_view(twin);
  2955. }
  2956. } else {
  2957. null_buffer_view(twin);
  2958. }
  2959. }
  2960. Some(Some(shadow.buffer.clone()))
  2961. }
  2962. /// Whether the host can make a shader (or unordered access) view of
  2963. /// `texture` in `format` (none: the texture's own). The console allows any
  2964. /// view; the host refuses (and removes the device for) views without the
  2965. /// resource's permission, of typed depth, and in another format than a
  2966. /// typed resource's. A view of a typed texture in another format of its
  2967. /// family takes the texture's format.
  2968. /// shortcut: such a view (sRGB of UNORM, say) reads without its
  2969. /// conversion; cast with castable formats if colors come out wrong.
  2970. fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordered: bool) -> bool {
  2971. use crate::resource::{DEPTH_FORMATS, family};
  2972. // SAFETY: a live resource.
  2973. let d = unsafe { texture.GetDesc() };
  2974. let allowed = if unordered {
  2975. d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0
  2976. } else {
  2977. d.Flags.0 & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE.0 == 0
  2978. };
  2979. let own = d.Format.0 as u32;
  2980. if !allowed || DEPTH_FORMATS.iter().any(|&(typed, _)| typed == own) {
  2981. if unordered {
  2982. crate::resource::DEPTH_UNORDERED[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2983. }
  2984. once!(
  2985. unordered,
  2986. format = own,
  2987. flags = d.Flags.0,
  2988. "view the host does not allow"
  2989. );
  2990. return false;
  2991. }
  2992. // Every family has more than one format, its typeless one first.
  2993. let typeless = family(own) == own && family(own + 1) == own;
  2994. if let Some(format) = format.as_deref_mut()
  2995. && unordered
  2996. && let Some(&(_, linear)) = crate::resource::SRGB
  2997. .iter()
  2998. .find(|&&(s, _)| s == format.0 as u32)
  2999. {
  3000. format.0 = linear as i32;
  3001. }
  3002. let view = format.as_ref().map_or(0, |f| f.0 as u32);
  3003. if view == 0 {
  3004. return !typeless;
  3005. }
  3006. // A view of a target whose format the host refuses, in the title's
  3007. // format: in the stand-in the host copy has.
  3008. if view != own && crate::resource::target_format(view) == own {
  3009. if let Some(format) = format {
  3010. *format = d.Format;
  3011. }
  3012. return true;
  3013. }
  3014. if family(view) != family(own) {
  3015. once!(view, own, "view format of another family");
  3016. return false;
  3017. }
  3018. if let Some(format) = format
  3019. && !typeless
  3020. {
  3021. *format = d.Format;
  3022. }
  3023. true
  3024. }
  3025. /// The title's unordered access view of a depth texture, as a view of the
  3026. /// texture's colour twin `twin` ([`crate::resource::Twin`]): the same mip
  3027. /// and slices, in the colour format of the twin's family for a depth or
  3028. /// typeless format (R16_UNORM for 16-bit depth, R32_FLOAT for 32-bit; the
  3029. /// bits are the same). Without a description: mip 0 of every slice.
  3030. /// The twin of a stencil plane (R8) stands for the views of that plane
  3031. /// only, which become R8_UINT views of its one plane; `None` for a view of
  3032. /// the depth plane, which the twin does not stand for. The depth plane has
  3033. /// a twin of its own, viewed as a depth texture's without stencil: a view
  3034. /// in the format of the depth plane of a depth-stencil format (21, 46)
  3035. /// takes the twin's colour format too.
  3036. fn twin_uav(
  3037. twin: &ID3D12Resource,
  3038. desc: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>,
  3039. ) -> Option<D3D12_UNORDERED_ACCESS_VIEW_DESC> {
  3040. // SAFETY: a live resource.
  3041. let d = unsafe { twin.GetDesc() };
  3042. let mut desc = desc.cloned().unwrap_or_else(|| {
  3043. let mut all = D3D12_UNORDERED_ACCESS_VIEW_DESC {
  3044. ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D,
  3045. ..Default::default()
  3046. };
  3047. if d.DepthOrArraySize > 1 {
  3048. all.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
  3049. all.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV {
  3050. ArraySize: u32::from(d.DepthOrArraySize),
  3051. ..Default::default()
  3052. };
  3053. }
  3054. all
  3055. });
  3056. // A stencil plane's twin (R8 typeless, 60): the title's view is of the
  3057. // stencil plane if it names plane 1 or a stencil view format (22, 47).
  3058. if d.Format.0 == 60 {
  3059. let mut plane = 0;
  3060. match desc.ViewDimension {
  3061. D3D12_UAV_DIMENSION_TEXTURE2D => {
  3062. // SAFETY: the member the dimension names.
  3063. let mut view = unsafe { desc.Anonymous.Texture2D };
  3064. plane = std::mem::take(&mut view.PlaneSlice);
  3065. desc.Anonymous.Texture2D = view;
  3066. }
  3067. D3D12_UAV_DIMENSION_TEXTURE2DARRAY => {
  3068. // SAFETY: the member the dimension names.
  3069. let mut view = unsafe { desc.Anonymous.Texture2DArray };
  3070. plane = std::mem::take(&mut view.PlaneSlice);
  3071. desc.Anonymous.Texture2DArray = view;
  3072. }
  3073. _ => {}
  3074. }
  3075. if plane != 1 && !matches!(desc.Format.0, 22 | 47) {
  3076. return None;
  3077. }
  3078. desc.Format.0 = 62;
  3079. return Some(desc);
  3080. }
  3081. // None, typeless and depth formats (R16: 0, 53, 55; R32: 0, 39, 40),
  3082. // and those of a depth-stencil format's depth plane (19 to 21, 44 to
  3083. // 46), for the twin of such a plane.
  3084. desc.Format.0 = match (desc.Format.0, d.Format.0) {
  3085. (0 | 53 | 55 | 19..=21 | 44..=46, 53) => 56,
  3086. (0 | 39 | 40 | 19..=21 | 44..=46, 39) => 41,
  3087. (other, _) => other,
  3088. };
  3089. Some(desc)
  3090. }
  3091. /// The bytes of the host's constant buffer view for a title's of `size`:
  3092. /// whole 256s, and at most the 64 KiB a shader can index. The host removes
  3093. /// the device for a larger view, and the title's heap holds such sizes in
  3094. /// slots it does not use.
  3095. fn constant_bytes(size: u32) -> u32 {
  3096. const LARGEST: u32 = 64 << 10;
  3097. size.min(LARGEST).next_multiple_of(256)
  3098. }
  3099. /// Makes the host descriptor for `view` at `at`: the host resource it
  3100. /// views, or `None` if it cannot.
  3101. fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<Kept> {
  3102. make_twinned(view, at, None)
  3103. }
  3104. /// [`make`]; `twin`: where the raw twin of a buffer view goes
  3105. /// ([`raw_twins`]; a constant buffer's is the same view again, other views
  3106. /// have none).
  3107. fn make_twinned(
  3108. view: &View,
  3109. at: D3D12_CPU_DESCRIPTOR_HANDLE,
  3110. twin: Option<D3D12_CPU_DESCRIPTOR_HANDLE>,
  3111. ) -> Option<Kept> {
  3112. let host = host()?;
  3113. let device = &host.device;
  3114. match view {
  3115. &View::Constant(address, size) => {
  3116. let shadow = crate::shadow::find(address, u64::from(size))?;
  3117. let gpu = shadow.gpu(address);
  3118. if gpu % 256 != 0 {
  3119. once!(
  3120. address = format_args!("{address:#x}"),
  3121. "constant buffer not 256-byte aligned on the host"
  3122. );
  3123. return None;
  3124. }
  3125. let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC {
  3126. BufferLocation: gpu,
  3127. SizeInBytes: constant_bytes(size),
  3128. };
  3129. // SAFETY: slots of our heap; the range lies in the host copy.
  3130. unsafe {
  3131. device.CreateConstantBufferView(Some(&desc), at);
  3132. if let Some(twin) = twin {
  3133. device.CreateConstantBufferView(Some(&desc), twin);
  3134. }
  3135. }
  3136. Some(Some(shadow.buffer.clone()))
  3137. }
  3138. View::Shader(resource, desc) => {
  3139. let resource = *resource as crate::object::This;
  3140. if let Some(copy) = crate::resource::host_copy(resource) {
  3141. let texture = &copy.texture;
  3142. // The title's views of textures with a stencil plane, as it
  3143. // describes them (format, dimension, component mapping, a
  3144. // pad, then first level, levels, plane): each distinct one
  3145. // once. They say how its shaders read the stencil plane
  3146. // (the lighting takes each pixel's material class and its
  3147. // "inside a room" bit from it).
  3148. #[cfg(feature = "diagnostics")]
  3149. {
  3150. // SAFETY: a live resource.
  3151. let own = unsafe { texture.GetDesc() }.Format.0;
  3152. if matches!(own, 19..=22 | 44..=47) {
  3153. static SEEN: Mutex<Vec<(i32, Option<[u32; 10]>)>> = Mutex::new(Vec::new());
  3154. let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
  3155. if seen.len() < 64 && !seen.contains(&(own, *desc)) {
  3156. seen.push((own, *desc));
  3157. tracing::info!(
  3158. ?resource,
  3159. texture_format = own,
  3160. view = ?desc,
  3161. "shader view of a depth-stencil texture"
  3162. );
  3163. }
  3164. }
  3165. }
  3166. let mut desc = desc.as_ref().map(srv_desc);
  3167. if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) {
  3168. return None;
  3169. }
  3170. // Levels on demand (`crate::tiles`): a texture made level by
  3171. // level is shown from the first level that is the title's
  3172. // and has memory, if the title's view starts before it (a
  3173. // level without memory reads zeros: a black texture). The
  3174. // title's own view mostly starts there already.
  3175. if let Some(first) = crate::resource::first_shown(resource)
  3176. && first > 0
  3177. {
  3178. // SAFETY: a live resource.
  3179. let own = unsafe { texture.GetDesc() };
  3180. // The texture's own view (the title gave none): all of it.
  3181. let whole = D3D12_SHADER_RESOURCE_VIEW_DESC {
  3182. Format: own.Format,
  3183. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
  3184. Shader4ComponentMapping: 5768,
  3185. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  3186. Texture2D: D3D12_TEX2D_SRV {
  3187. MostDetailedMip: 0,
  3188. MipLevels: u32::MAX,
  3189. PlaneSlice: 0,
  3190. ResourceMinLODClamp: 0.0,
  3191. },
  3192. },
  3193. };
  3194. crate::tiles::show_from(desc.get_or_insert(whole), first, u32::from(own.MipLevels));
  3195. }
  3196. if copy.base > 0
  3197. && let Some(desc) = &mut desc
  3198. {
  3199. from_base(desc, copy.base);
  3200. }
  3201. // SAFETY: a live texture and a slot of our heap.
  3202. unsafe {
  3203. device.CreateShaderResourceView(
  3204. texture,
  3205. desc.as_ref().map(std::ptr::from_ref),
  3206. at,
  3207. )
  3208. };
  3209. Some(Some(texture.clone()))
  3210. } else if let (Some((data, len)), Some(desc)) =
  3211. (crate::resource::buffer_bytes(resource), desc)
  3212. {
  3213. buffer_srv(data as u64, len, srv_desc(desc), at, twin)
  3214. } else {
  3215. None
  3216. }
  3217. }
  3218. View::Unordered(resource, _counter, desc) => {
  3219. let resource = *resource as crate::object::This;
  3220. let Some(texture) = crate::resource::host_resource(resource) else {
  3221. return match (crate::resource::buffer_bytes(resource), desc) {
  3222. (Some((data, len)), Some(desc)) => {
  3223. buffer_uav(data as u64, len, uav_desc(desc), at, twin)
  3224. }
  3225. _ => None,
  3226. };
  3227. };
  3228. // The first such views of depth textures are logged as the
  3229. // title describes them (format, dimension, then mip, slices and
  3230. // plane): they say which planes shaders write, and as what.
  3231. if crate::resource::depth_and_unordered(resource) {
  3232. static LOGGED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  3233. if LOGGED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 512 {
  3234. tracing::info!(
  3235. ?resource,
  3236. view = ?desc,
  3237. "unordered access view of a depth texture"
  3238. );
  3239. }
  3240. }
  3241. let mut desc = desc.as_ref().map(uav_desc);
  3242. // A depth texture's unordered access is its colour twin's: the
  3243. // host gives a depth texture none.
  3244. let twin = crate::resource::twin_resource(resource)
  3245. .and_then(|twin| Some((twin, twin_uav(twin, desc.as_ref())?)))
  3246. // A view of the depth plane of a texture with a stencil
  3247. // plane: of that plane's own twin.
  3248. .or_else(|| {
  3249. let twin = crate::resource::twin_plane_resource(resource)?;
  3250. Some((twin, twin_uav(twin, desc.as_ref())?))
  3251. });
  3252. let texture = match twin {
  3253. Some((twin, view)) => {
  3254. desc = Some(view);
  3255. twin
  3256. }
  3257. None => texture,
  3258. };
  3259. if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) {
  3260. return None;
  3261. }
  3262. // SAFETY: a live texture and a slot of our heap.
  3263. unsafe {
  3264. device.CreateUnorderedAccessView(
  3265. texture,
  3266. None::<&ID3D12Resource>,
  3267. desc.as_ref().map(std::ptr::from_ref),
  3268. at,
  3269. )
  3270. };
  3271. Some(Some(texture.clone()))
  3272. }
  3273. View::Sampler(words) => {
  3274. // SAFETY: 13 words in the host's layout.
  3275. let desc = unsafe {
  3276. std::ptr::from_ref(words)
  3277. .cast::<D3D12_SAMPLER_DESC>()
  3278. .read_unaligned()
  3279. };
  3280. // SAFETY: a slot of our sampler heap.
  3281. unsafe { device.CreateSampler(&desc, at) };
  3282. Some(None)
  3283. }
  3284. View::ConsoleSampler(words) => {
  3285. let desc = crate::sampler::console(words);
  3286. // SAFETY: a slot of our sampler heap.
  3287. unsafe { device.CreateSampler(&desc, at) };
  3288. Some(None)
  3289. }
  3290. View::Placed(unordered, resource, desc) => {
  3291. if let Some(view) = placed_texture(view) {
  3292. return make(&view, at);
  3293. }
  3294. const BUFFER: u32 = 1;
  3295. if resource[0] != BUFFER {
  3296. // shortcut: unordered access to a texture the title placed
  3297. // itself is not mirrored; give it a resource as shader
  3298. // views of such textures get when a dispatch writes one.
  3299. // Each texture is said once (the first 64), with how many times
  3300. // such a view was asked for so far: what shaders write through
  3301. // them is lost.
  3302. static SAID: Mutex<std::collections::BTreeSet<u64>> = Mutex::new(std::collections::BTreeSet::new());
  3303. static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  3304. let times = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
  3305. let at = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  3306. let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
  3307. if (said.len() < 64 && said.insert(at)) || times.is_power_of_two() {
  3308. tracing::warn!(
  3309. address = format_args!("{at:#x}"),
  3310. times,
  3311. "placed unordered texture view not mirrored (null: writes through it are lost): resource {resource:?}, view {:?}",
  3312. &desc[..10]
  3313. );
  3314. }
  3315. return None;
  3316. }
  3317. // The resource description's width, after the alignment.
  3318. let len = u64::from(resource[4]) | u64::from(resource[5]) << 32;
  3319. let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  3320. let words: &[u32; 10] = desc[..10].try_into().unwrap_or(&[0; 10]);
  3321. // An empty title buffer: nothing to view, and no host copy to
  3322. // look for (#70: such views were in flight at device removals).
  3323. if len == 0 {
  3324. return None;
  3325. }
  3326. if *unordered {
  3327. buffer_uav(address, len, uav_desc(words), at, twin)
  3328. } else {
  3329. buffer_srv(address, len, srv_desc(words), at, twin)
  3330. }
  3331. }
  3332. }
  3333. }
  3334. /// The view `desc` of a texture, of a host copy of its levels from `base`
  3335. /// on (`crate::resource::held_only`). What it shows of larger ones, if any,
  3336. /// is left out.
  3337. fn from_base(desc: &mut D3D12_SHADER_RESOURCE_VIEW_DESC, base: u32) {
  3338. if desc.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D {
  3339. return;
  3340. }
  3341. // SAFETY: the member its dimension says.
  3342. let t = unsafe { &mut desc.Anonymous.Texture2D };
  3343. let lost = base.saturating_sub(t.MostDetailedMip);
  3344. t.MostDetailedMip = t.MostDetailedMip.saturating_sub(base);
  3345. if t.MipLevels != u32::MAX {
  3346. t.MipLevels = t.MipLevels.saturating_sub(lost).max(1);
  3347. }
  3348. t.ResourceMinLODClamp = (t.ResourceMinLODClamp - base as f32).max(0.0);
  3349. }
  3350. /// Writes of a slot with another view of the placed texture it showed,
  3351. /// since the start: the slot kept showing the old view.
  3352. pub(crate) static KEPT_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  3353. /// Whether a slot written with another view of the placed texture it
  3354. /// shows keeps showing the old one until the new is made;
  3355. /// `VICTORY_KEEP_VIEWS=0` makes it null at once, as before.
  3356. fn keep_views() -> bool {
  3357. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  3358. *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_VIEWS").is_none_or(|v| v != "0"))
  3359. }
  3360. /// Whether both are shader views of one texture the title placed in
  3361. /// memory: the same address and the same resource description, whatever
  3362. /// part of it each shows.
  3363. fn same_placed_texture(a: &View, b: &View) -> bool {
  3364. match (a, b) {
  3365. (View::Placed(false, resource, desc), View::Placed(false, other, other_desc)) => {
  3366. // (Words 1 and 13 are the filler of the description's layout, not
  3367. // part of what a texture is: `crate::resource::texture_at`.)
  3368. let same = |from: usize, to: usize| resource[from..to] == other[from..to];
  3369. resource[0] != 1 && resource[0] == other[0] && same(2, 13) && desc[10..12] == other_desc[10..12]
  3370. }
  3371. _ => false,
  3372. }
  3373. }
  3374. /// A shader view of a texture the title placed in memory itself, as a view
  3375. /// of the resource made for that memory (on first use).
  3376. pub(crate) fn placed_texture(view: &View) -> Option<View> {
  3377. const BUFFER: u32 = 1;
  3378. let View::Placed(false, resource, desc) = view else {
  3379. return None;
  3380. };
  3381. if resource[0] == BUFFER {
  3382. return None;
  3383. }
  3384. let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  3385. let texture = crate::resource::texture_at(address, resource)?;
  3386. crate::resource::want_level(texture, crate::resource::first_mip(desc));
  3387. Some(View::Shader(texture as usize, desc[..10].try_into().ok()))
  3388. }
  3389. /// A null view of the kind `view` is, for a slot whose view the host
  3390. /// cannot make: unordered access (to a buffer or a 2D texture) or a shader
  3391. /// view. Writes to it are dropped, reads give zeros.
  3392. fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) {
  3393. let Some(host) = host() else { return };
  3394. let is_buffer = |r: &usize| crate::resource::buffer_bytes(*r as crate::object::This).is_some();
  3395. // Unordered views: whether a buffer, and the title's view dimension.
  3396. let (buffer, dimension) = match view {
  3397. View::Unordered(r, _, desc) => (
  3398. is_buffer(r) || desc.is_some_and(|d| d[1] == 1),
  3399. desc.map(|d| d[1]),
  3400. ),
  3401. View::Placed(true, resource, desc) => (resource[0] == 1, Some(desc[1])),
  3402. // Shader views of buffers read nothing through a null buffer view:
  3403. // a null 2D view where the shader expects a buffer is a mismatch
  3404. // the hardware does not survive in general (GPU-based validation
  3405. // reports it).
  3406. View::Shader(r, desc) if is_buffer(r) || desc.is_some_and(|d| d[1] == 1) => {
  3407. return null_buffer_view(at);
  3408. }
  3409. View::Placed(false, resource, _) if resource[0] == 1 => return null_buffer_view(at),
  3410. // Textures: a null view of the title's dimension (1D, arrays, 3D,
  3411. // cubes), not always 2D.
  3412. View::Shader(_, Some(desc)) => return null_like(desc, at),
  3413. View::Placed(false, _, desc) => {
  3414. return null_like(desc[..10].try_into().unwrap_or(&[0; 10]), at);
  3415. }
  3416. View::Constant(..) => {
  3417. let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC::default();
  3418. // SAFETY: a slot of our heap; a zero location makes a null view.
  3419. return unsafe { host.device.CreateConstantBufferView(Some(&desc), at) };
  3420. }
  3421. _ => return null_view(at),
  3422. };
  3423. let desc = if buffer {
  3424. D3D12_UNORDERED_ACCESS_VIEW_DESC {
  3425. Format: DXGI_FORMAT_R32_UINT,
  3426. ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
  3427. ..Default::default()
  3428. }
  3429. } else {
  3430. null_uav_desc(dimension)
  3431. };
  3432. // SAFETY: a slot of our heap; a null resource is allowed with a desc.
  3433. unsafe {
  3434. host.device.CreateUnorderedAccessView(
  3435. None::<&ID3D12Resource>,
  3436. None::<&ID3D12Resource>,
  3437. Some(&desc),
  3438. at,
  3439. )
  3440. };
  3441. }
  3442. /// A null texture UAV of the title's view dimension (1D, 1D or 2D arrays,
  3443. /// 3D), 2D if it names none: a 2D null view where the shader writes a 3D
  3444. /// texture is a mismatch GPU-based validation reports (the world's wind
  3445. /// field, CS_CopyWindFieldBeforeUpdateWithSmooth, 2026-11-24).
  3446. fn null_uav_desc(dimension: Option<u32>) -> D3D12_UNORDERED_ACCESS_VIEW_DESC {
  3447. let mut desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
  3448. Format: DXGI_FORMAT_R32_UINT,
  3449. ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D,
  3450. ..Default::default()
  3451. };
  3452. match dimension.map(|d| D3D12_UAV_DIMENSION(d as i32)) {
  3453. Some(D3D12_UAV_DIMENSION_TEXTURE1D) => {
  3454. desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D;
  3455. }
  3456. Some(D3D12_UAV_DIMENSION_TEXTURE1DARRAY) => {
  3457. desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY;
  3458. desc.Anonymous.Texture1DArray = D3D12_TEX1D_ARRAY_UAV {
  3459. ArraySize: 1,
  3460. ..Default::default()
  3461. };
  3462. }
  3463. Some(D3D12_UAV_DIMENSION_TEXTURE2DARRAY) => {
  3464. desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
  3465. desc.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV {
  3466. ArraySize: 1,
  3467. ..Default::default()
  3468. };
  3469. }
  3470. Some(D3D12_UAV_DIMENSION_TEXTURE3D) => {
  3471. desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D;
  3472. desc.Anonymous.Texture3D = D3D12_TEX3D_UAV {
  3473. WSize: u32::MAX,
  3474. ..Default::default()
  3475. };
  3476. }
  3477. _ => {}
  3478. }
  3479. desc
  3480. }
  3481. /// A buffer view that reads zeros (raw, as translated shaders mostly read
  3482. /// buffers).
  3483. fn null_buffer_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
  3484. let Some(host) = host() else { return };
  3485. let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
  3486. Format: DXGI_FORMAT_R32_TYPELESS,
  3487. ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
  3488. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  3489. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  3490. Buffer: D3D12_BUFFER_SRV {
  3491. NumElements: 1,
  3492. Flags: D3D12_BUFFER_SRV_FLAG_RAW,
  3493. ..Default::default()
  3494. },
  3495. },
  3496. };
  3497. // SAFETY: a slot of our heap; a null resource is allowed with a desc.
  3498. unsafe {
  3499. host.device
  3500. .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at)
  3501. };
  3502. }
  3503. /// A texture view that reads zeros with the dimension (and mip and array
  3504. /// counts) of the title's description `words`; 2D if it names none.
  3505. fn null_like(words: &[u32; 10], at: D3D12_CPU_DESCRIPTOR_HANDLE) {
  3506. const TEXTURES: std::ops::RangeInclusive<u32> = 2..=10;
  3507. if !TEXTURES.contains(&words[1]) {
  3508. return null_view(at);
  3509. }
  3510. let Some(host) = host() else { return };
  3511. // One mip, one slice or cube, plane 0: fields a null view still checks.
  3512. let mut w = [0u32; 10];
  3513. w[1] = words[1];
  3514. match words[1] {
  3515. 6 => {}
  3516. 7 => w[5] = 1,
  3517. 3 | 5 | 10 => (w[5], w[7]) = (1, 1),
  3518. _ => w[5] = 1,
  3519. }
  3520. let mut desc = srv_desc(&w);
  3521. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  3522. desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  3523. // SAFETY: a slot of our heap; a null resource is allowed with a desc.
  3524. unsafe {
  3525. host.device
  3526. .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at)
  3527. };
  3528. }
  3529. /// A view that reads zeros, for slots whose view the host cannot make.
  3530. /// shortcut: slots with no view at all (kind unknown) get this null 2D
  3531. /// view; null buffer views there did not stop the world's low-address
  3532. /// page faults (2026-11-24, run w10), so they are not the cause.
  3533. fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
  3534. let Some(host) = host() else { return };
  3535. let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
  3536. Format: DXGI_FORMAT_R8G8B8A8_UNORM,
  3537. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
  3538. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  3539. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  3540. Texture2D: D3D12_TEX2D_SRV {
  3541. MipLevels: 1,
  3542. ..Default::default()
  3543. },
  3544. },
  3545. };
  3546. // SAFETY: a slot of our heap; a null resource is allowed with a desc.
  3547. unsafe {
  3548. host.device
  3549. .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at)
  3550. };
  3551. }
  3552. #[cfg(test)]
  3553. mod tests {
  3554. use super::*;
  3555. /// A view of a host copy that begins at a later level shows the same
  3556. /// levels of it.
  3557. #[test]
  3558. fn views_count_from_the_first_level_of_the_host_copy() {
  3559. let view = |first, levels, clamp| {
  3560. let mut desc = srv_desc(&[98, 4, 5768, 0, first, levels, 0, 0, 0, 0]);
  3561. desc.Anonymous.Texture2D.ResourceMinLODClamp = clamp;
  3562. from_base(&mut desc, 3);
  3563. // SAFETY: the member its dimension says.
  3564. let t = unsafe { desc.Anonymous.Texture2D };
  3565. (t.MostDetailedMip, t.MipLevels, t.ResourceMinLODClamp)
  3566. };
  3567. assert_eq!(view(3, 4, 0.0), (0, 4, 0.0));
  3568. assert_eq!(view(5, u32::MAX, 5.5), (2, u32::MAX, 2.5));
  3569. // (Two levels the copy has not.)
  3570. assert_eq!(view(1, 4, 0.0), (0, 2, 0.0));
  3571. }
  3572. /// Memory past the levels a slot's view shows is not its texture's.
  3573. #[test]
  3574. fn a_view_of_smaller_levels_is_not_told_of_memory_past_them() {
  3575. let mut spans = Spans::default();
  3576. spans.note(1, 0x10000, 0x50000, true);
  3577. spans.shows(1, 3, 0x12000);
  3578. spans.note(2, 0x10000, 0x50000, true);
  3579. spans.shows(2, 0, 0x50000);
  3580. assert_eq!(spans.slots_holding(0x11000, 0x11800), vec![1, 2]);
  3581. assert_eq!(spans.slots_holding(0x20000, 0x21000), vec![2]);
  3582. assert_eq!(spans.slots_in(0x20000, 0x21000), vec![2]);
  3583. spans.forget(2);
  3584. assert!(spans.slots_in(0x20000, 0x21000).is_empty());
  3585. assert_eq!(spans.slots_in(0x0, 0x10001), vec![1]);
  3586. }
  3587. /// A texture filled with less than was mapped is looked at again, but
  3588. /// not for ever: memory that is shown and cannot be read ends it, and a
  3589. /// filling that got everything starts the count anew.
  3590. #[test]
  3591. fn a_short_filling_is_looked_at_again_a_few_times() {
  3592. // An address no other test names.
  3593. let start = 0x7fee_1234_0000u64;
  3594. let pending = || super::SHORT.lock().unwrap().0.remove(&start);
  3595. for _ in 0..super::SHORT_IN_A_ROW {
  3596. super::read_short(start);
  3597. assert!(pending());
  3598. }
  3599. super::read_short(start);
  3600. assert!(!pending());
  3601. super::read_all(start);
  3602. super::read_short(start);
  3603. assert!(pending());
  3604. super::read_all(start);
  3605. }
  3606. /// A null texture UAV keeps the title's dimension (3D for the world's
  3607. /// wind field), and is 2D when the title names none.
  3608. #[test]
  3609. fn null_uavs_keep_the_titles_dimension() {
  3610. let d = null_uav_desc(Some(8));
  3611. assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE3D);
  3612. // SAFETY: the member the dimension names.
  3613. assert_eq!(unsafe { d.Anonymous.Texture3D.WSize }, u32::MAX);
  3614. let d = null_uav_desc(Some(5));
  3615. assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE2DARRAY);
  3616. // SAFETY: the member the dimension names.
  3617. assert_eq!(unsafe { d.Anonymous.Texture2DArray.ArraySize }, 1);
  3618. let dimension = |d| null_uav_desc(d).ViewDimension;
  3619. assert_eq!(dimension(Some(2)), D3D12_UAV_DIMENSION_TEXTURE1D);
  3620. assert_eq!(dimension(Some(4)), D3D12_UAV_DIMENSION_TEXTURE2D);
  3621. assert_eq!(dimension(None), D3D12_UAV_DIMENSION_TEXTURE2D);
  3622. // Multisampled UAVs need a cap; they stay 2D.
  3623. assert_eq!(dimension(Some(6)), D3D12_UAV_DIMENSION_TEXTURE2D);
  3624. }
  3625. /// What the texture code asks of the spans (levels on demand): where
  3626. /// the next texture starts inside a span, the lowest level a view of a
  3627. /// texture shows, and a texture's slots.
  3628. #[test]
  3629. fn spans_say_the_next_start_and_the_lowest_level_viewed() {
  3630. let mut spans = Spans::default();
  3631. // A 512x512 texture of 0x56000 bytes viewed from levels 3 and 1,
  3632. // and the next one 0x6000 after it (run 188).
  3633. spans.note(1, 0x1_0000, 0x1_0000 + 0x5_6000, true);
  3634. spans.shows(1, 3, u64::MAX);
  3635. spans.note(2, 0x1_0000, 0x1_0000 + 0x5_6000, true);
  3636. spans.shows(2, 1, u64::MAX);
  3637. spans.note(3, 0x1_6000, 0x1_6000 + 0x5_6000, true);
  3638. assert_eq!(spans.next_start(0x1_0000, 0x1_0000 + 0x5_6000), Some(0x1_6000));
  3639. assert_eq!(spans.next_start(0x1_6000, 0x1_6000 + 0x5_6000), None);
  3640. assert_eq!(spans.first_viewed(0x1_0000), Some(1));
  3641. assert_eq!(spans.first_viewed(0x1_6000), None);
  3642. assert_eq!(spans.slots_at(0x1_0000), vec![1, 2]);
  3643. // The view from level 1 goes: the texture is viewed from level 3.
  3644. spans.forget(2);
  3645. assert_eq!(spans.first_viewed(0x1_0000), Some(3));
  3646. }
  3647. /// Views of one placed texture are told from views of others by the
  3648. /// address and the resource description, not by what they show.
  3649. #[test]
  3650. fn views_of_one_placed_texture_are_told_by_address_and_description() {
  3651. let texture = [3, 0, 0, 0, 512, 0, 512, 0x8_0001, 98, 1, 0, 0x105, 0, 0];
  3652. let view = |resource: [u32; 14], first_mip: u32, address: u32| {
  3653. let mut desc = [0u32; 16];
  3654. (desc[0], desc[1], desc[4], desc[5], desc[10], desc[11]) = (98, 4, first_mip, 8 - first_mip, address, 0xb);
  3655. View::Placed(false, resource, desc)
  3656. };
  3657. let low = view(texture, 3, 0x1000_0000);
  3658. // more mips of the same texture
  3659. assert!(same_placed_texture(&low, &view(texture, 0, 0x1000_0000)));
  3660. // another address, another description, a buffer, an unordered view
  3661. assert!(!same_placed_texture(&low, &view(texture, 3, 0x2000_0000)));
  3662. let mut wider = texture;
  3663. wider[4] = 1024;
  3664. assert!(!same_placed_texture(&low, &view(wider, 3, 0x1000_0000)));
  3665. let mut buffer = texture;
  3666. buffer[0] = 1;
  3667. assert!(!same_placed_texture(&view(buffer, 3, 0x1000_0000), &view(buffer, 3, 0x1000_0000)));
  3668. let View::Placed(_, resource, desc) = low.clone() else { unreachable!() };
  3669. assert!(!same_placed_texture(&low, &View::Placed(true, resource, desc)));
  3670. assert!(!same_placed_texture(&low, &View::Shader(0, None)));
  3671. }
  3672. /// A constant buffer view larger than the host takes is cut to what it
  3673. /// takes: the device, which such a view removes, stays.
  3674. #[test]
  3675. fn an_oversized_constant_buffer_view_leaves_the_device_alive() {
  3676. let Some(host) = host() else {
  3677. return; // no host GPU
  3678. };
  3679. let Some(heap) = HostHeap::new(false, 4) else {
  3680. return;
  3681. };
  3682. // SAFETY: a plain device query.
  3683. let alive = || unsafe { host.device.GetDeviceRemovedReason() }.is_ok();
  3684. // Made first: an allocation that fails on a removed device must not
  3685. // end the test early.
  3686. let (buffer, _) = host.upload_buffer(1 << 20).expect("an upload buffer");
  3687. let memory = vec![0u8; 2 << 20];
  3688. let at = (memory.as_ptr() as u64).next_multiple_of(64 << 10);
  3689. for size in [969_472u32, 896_256] {
  3690. assert!(make(&View::Constant(at, size), heap.cpu(0)).is_some());
  3691. assert!(alive(), "a view of {size} bytes");
  3692. }
  3693. // SAFETY: a live upload buffer.
  3694. heap.constant_at(1, &buffer, unsafe { buffer.GetGPUVirtualAddress() }, 969_472);
  3695. assert!(alive(), "a view of the list's own memory");
  3696. assert_eq!(constant_bytes(480), 512);
  3697. assert_eq!(constant_bytes(64 << 10), 64 << 10);
  3698. assert_eq!(constant_bytes(u32::MAX), 64 << 10);
  3699. }
  3700. /// A null 3D UAV made on the real device leaves it alive.
  3701. #[test]
  3702. fn null_3d_uav_is_accepted_by_the_device() {
  3703. let Some(host) = host() else {
  3704. return; // no host GPU
  3705. };
  3706. let Some(heap) = HostHeap::new(false, 4) else {
  3707. return;
  3708. };
  3709. let view = View::Unordered(0, 0, Some([28, 8, 0, 0, 0, 0, 0, 0, 0, 0]));
  3710. null_for(&view, heap.cpu(0));
  3711. // SAFETY: a plain device query.
  3712. assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok());
  3713. }
  3714. /// Dynamic slots stay taken until given back, and runs do not wrap.
  3715. #[test]
  3716. fn a_structured_view_made_raw_passes_the_host_check() {
  3717. // 100 elements of 20 bytes from element 8, in a copy that starts 32
  3718. // bytes before the view's memory: bytes 192..2192.
  3719. let (first, count) = raw_window(32, 8, 100, 20).unwrap();
  3720. assert_eq!((first, count), (48, 500));
  3721. assert!(buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 4096));
  3722. // the format a raw view must name; the structured one's is refused
  3723. assert!(!buffer_view_ok(DXGI_FORMAT_UNKNOWN, first, count, 0, true, 4096));
  3724. // past the buffer, not on 16 bytes, no elements
  3725. assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 2000));
  3726. assert!(raw_window(4, 0, 100, 20).is_none());
  3727. assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, 0, 0, 0, true, 4096));
  3728. // a structured view the host takes as it is
  3729. assert!(buffer_view_ok(DXGI_FORMAT_UNKNOWN, 1, 10, 12, false, 4096));
  3730. }
  3731. /// The raw twin of a view shows the same bytes: typed and structured ones
  3732. /// that begin on 16 bytes, whole dwords, none past the buffer.
  3733. #[test]
  3734. fn raw_twins_show_the_views_bytes() {
  3735. let (u16s, u32s, none) = (DXGI_FORMAT(57), DXGI_FORMAT(42), DXGI_FORMAT_UNKNOWN);
  3736. assert_eq!(twin_window(u32s, 4, 10, 0, false, 4096), Some((4, 10, 0)));
  3737. assert_eq!(twin_window(u16s, 8, 7, 0, false, 4096), Some((4, 4, 0)));
  3738. // the last dword would reach past the buffer
  3739. assert_eq!(twin_window(u16s, 8, 7, 0, false, 30), Some((4, 3, 0)));
  3740. assert_eq!(twin_window(none, 2, 3, 24, false, 4096), Some((12, 18, 0)));
  3741. assert_eq!(twin_window(DXGI_FORMAT_R32_TYPELESS, 8, 5, 0, true, 4096), Some((8, 5, 0)));
  3742. // where no raw view begins: from the 16 bytes below
  3743. assert_eq!(twin_window(none, 1, 3, 24, false, 4096), Some((4, 20, 8)));
  3744. assert_eq!(twin_window(u32s, 1, 10, 0, false, 4096), Some((0, 11, 4)));
  3745. assert_eq!(twin_window(u32s, 1, 10, 0, false, 4), None);
  3746. }
  3747. /// What a slot is made as is made beside the heap and copied in whole: the
  3748. /// slot's descriptor is the one the view has, and each thread makes its
  3749. /// own.
  3750. #[test]
  3751. fn views_are_made_beside_the_heap_and_copied_in() {
  3752. let Some(host) = host() else {
  3753. return; // no host GPU here
  3754. };
  3755. let Some(heap) = HostHeap::new(false, 4) else {
  3756. return;
  3757. };
  3758. let (Some(a), Some(b)) = (staged(false, 0), staged(false, 1)) else {
  3759. return;
  3760. };
  3761. assert_ne!(a.ptr, b.ptr);
  3762. assert_ne!(Some(a.ptr), std::thread::spawn(|| staged(false, 0).map(|h| h.ptr)).join().unwrap());
  3763. let (buffer, _) = host.shared_buffer(1 << 16).unwrap();
  3764. let index = heap.dynamic(1).unwrap();
  3765. let bytes = |at: D3D12_CPU_DESCRIPTOR_HANDLE| {
  3766. let mut bytes = [0u8; 32];
  3767. crate::host::read_into(at.ptr as *const u8, &mut bytes).then_some(bytes)
  3768. };
  3769. heap.raw_at(index, &buffer, 64, 1024);
  3770. let (slot, beside) = (bytes(heap.cpu(index)), bytes(staged(false, 0).unwrap()));
  3771. assert_eq!(slot, beside, "copied as it was made");
  3772. heap.null_raw_at(index);
  3773. assert_ne!(bytes(heap.cpu(index)), slot, "another view since");
  3774. // SAFETY: a plain query.
  3775. assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok());
  3776. }
  3777. /// A raw view moved on by some dwords says so in its descriptor, on a
  3778. /// card whose descriptors are what we take them for; on another nothing
  3779. /// is changed.
  3780. #[test]
  3781. fn a_raw_view_is_moved_only_where_its_descriptor_says_where_it_is() {
  3782. let (Some(host), Some(at)) = (host(), staged(false, 1)) else {
  3783. return; // no host GPU here
  3784. };
  3785. let (buffer, _) = host.shared_buffer(1 << 16).unwrap();
  3786. let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
  3787. Format: DXGI_FORMAT_R32_TYPELESS,
  3788. ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
  3789. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  3790. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  3791. Buffer: D3D12_BUFFER_SRV {
  3792. FirstElement: 8,
  3793. NumElements: 100,
  3794. StructureByteStride: 0,
  3795. Flags: D3D12_BUFFER_SRV_FLAG_RAW,
  3796. },
  3797. },
  3798. };
  3799. // SAFETY: this thread's slot, a live buffer.
  3800. let start = unsafe {
  3801. host.device.CreateShaderResourceView(&buffer, Some(&desc), at);
  3802. buffer.GetGPUVirtualAddress() + 32
  3803. };
  3804. let words = || {
  3805. let mut bytes = [0u8; 32];
  3806. assert!(crate::host::read_into(at.ptr as *const u8, &mut bytes));
  3807. bytes
  3808. };
  3809. let before = words();
  3810. assert!(!move_raw(at, start + 16, 400, 8), "another address");
  3811. assert!(!move_raw(at, start, 404, 8), "another size");
  3812. assert!(!move_raw(at, start, 400, 400), "nothing left");
  3813. assert_eq!(words(), before);
  3814. if move_raw(at, start, 400, 8) {
  3815. let moved = words();
  3816. assert_eq!(moved[..8], (start + 8).to_le_bytes());
  3817. assert_eq!(moved[8..12], 392u32.to_le_bytes());
  3818. assert_eq!(moved[12..], before[12..]);
  3819. } else {
  3820. assert_eq!(words(), before);
  3821. }
  3822. }
  3823. /// Views that begin where no host view can: raw ones off 16 bytes,
  3824. /// structured ones off their elements (and off 16 bytes, where they are
  3825. /// made raw), typed ones off theirs.
  3826. #[test]
  3827. fn views_off_their_elements_are_told() {
  3828. // the colour table bakes' parameter block: raw, 8 bytes into its window
  3829. assert!(off_elements(8, 0, true, 4));
  3830. assert!(!off_elements(0, 0, true, 4));
  3831. assert!(!off_elements(48, 0, true, 4));
  3832. // 456-byte elements: at one of them, on 16 bytes, at neither
  3833. assert!(!off_elements(456, 456, false, 0));
  3834. assert!(!off_elements(32, 456, false, 0));
  3835. assert!(off_elements(100, 456, false, 0));
  3836. // A typed view of 12-byte elements on 16 bytes and not on an element.
  3837. assert!(off_elements(23_702_896, 0, false, 12));
  3838. assert!(!off_elements(48, 0, false, 12));
  3839. assert!(!off_elements(12, 0, false, 4));
  3840. assert!(off_elements(12, 0, false, 8));
  3841. }
  3842. /// Such a view is made on a copy of its own bytes, and that copy is the one
  3843. /// brought up to date for it; another's is its buffer's.
  3844. #[test]
  3845. fn views_off_their_elements_get_a_copy_of_their_bytes() {
  3846. let Some(host) = host() else {
  3847. return; // no host GPU here
  3848. };
  3849. let memory = vec![0u64; 1 << 13];
  3850. let start = (memory.as_ptr() as u64).next_multiple_of(4096);
  3851. // SAFETY: a plain CPU-side heap of one view.
  3852. let cpu: ID3D12DescriptorHeap = unsafe {
  3853. host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  3854. Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  3855. NumDescriptors: 1,
  3856. ..Default::default()
  3857. })
  3858. }
  3859. .unwrap();
  3860. // SAFETY: a live heap.
  3861. let at = unsafe { cpu.GetCPUDescriptorHandleForHeapStart() };
  3862. // Memory placed at `address`, seen as the title passes it: raw, 32
  3863. // dwords, or four 456-byte elements.
  3864. let view = |address: u64, raw: bool| {
  3865. let resource: [u32; 14] = [1, 0, 0, 0, 4 * 456, 0, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0];
  3866. let mut desc = [0u32; 16];
  3867. let words = if raw {
  3868. [39, 1, 5768, 0, 0, 0, 32, 0, 1, 0]
  3869. } else {
  3870. [0, 1, 5768, 0, 0, 0, 4, 456, 0, 0]
  3871. };
  3872. desc[..10].copy_from_slice(&words);
  3873. (desc[10], desc[11]) = (address as u32, (address >> 32) as u32);
  3874. View::Placed(false, resource, desc)
  3875. };
  3876. let width = |v: &View| {
  3877. let made = make(v, at).expect("a view").expect("a buffer");
  3878. // SAFETY: a live buffer.
  3879. unsafe { made.GetDesc() }.Width
  3880. };
  3881. for (off, raw, len) in [(8, true, 128u64), (8, false, 4 * 456)] {
  3882. let v = view(start + off, raw);
  3883. assert_eq!(width(&v), len.next_multiple_of(256));
  3884. let (copy, address, bytes) = buffer_copy(&v).unwrap();
  3885. assert_eq!((copy.span(), address, bytes), ((start + off, len), start + off, len));
  3886. }
  3887. for (off, raw) in [(16, true), (32, false)] {
  3888. let v = view(start + off, raw);
  3889. let (copy, ..) = buffer_copy(&v).unwrap();
  3890. assert_ne!(copy.span().0, start + off, "its buffer's copy");
  3891. // SAFETY: a live buffer.
  3892. assert_eq!(width(&v), unsafe { copy.buffer.GetDesc() }.Width);
  3893. }
  3894. }
  3895. /// The queue of textures picked by index serves the slots looked at
  3896. /// before first, then the newest write and the oldest in turns; a
  3897. /// slot whose memory is not there is looked at again after
  3898. /// 1, 2, 4 frames up to the limit; and what the pass reports about a
  3899. /// slot written again meanwhile is dropped.
  3900. #[test]
  3901. fn the_texture_queue_serves_the_newest_writes_first() {
  3902. let mut q = TextureQueue::default();
  3903. // Slots 10..18 written in frames 1..9, slot 5 last.
  3904. for i in 0..8u32 {
  3905. q.written(10 + i, u64::from(i) + 1, 0, false);
  3906. }
  3907. q.written(5, 9, 0, false);
  3908. let order: Vec<u32> = q.due(9, 100).into_iter().map(|d| d.0).collect();
  3909. // newest, oldest, newest, oldest, and so on
  3910. assert_eq!(order, [5, 10, 17, 11, 16, 12, 15, 13, 14]);
  3911. assert_eq!(q.due(9, 2).len(), 2);
  3912. assert_eq!(q.census(9), [9, 9, 0, 0, 8]);
  3913. // Slot 17's memory is not mapped: again next frame, then in 2, 4, 4.
  3914. let write = |q: &TextureQueue, index: u32| q.due(u64::MAX, 100).iter().find(|d| d.0 == index).unwrap().1;
  3915. let w17 = write(&q, 17);
  3916. let mut frame = 9;
  3917. for wait in [1, 2, 4, 4] {
  3918. q.later(17, w17, frame, 4);
  3919. assert!(!q.due(frame + wait - 1, 100).iter().any(|d| d.0 == 17));
  3920. frame += wait;
  3921. // Due again, and ahead of every slot never looked at.
  3922. assert_eq!(q.due(frame, 100)[0].0, 17);
  3923. }
  3924. assert_eq!(q.census(9)[2], 1);
  3925. q.done(17, w17);
  3926. assert!(!q.due(u64::MAX, 100).iter().any(|d| d.0 == 17));
  3927. // Uploaded with part of its memory there: kept, with what was there.
  3928. let w16 = write(&q, 16);
  3929. q.partly(16, w16, 12, 4096);
  3930. assert_eq!(q.mapped(16), 4096);
  3931. assert_eq!(q.due(12, 100)[0].0, 16);
  3932. // The title writes slot 16 again while the pass works on it: what
  3933. // the pass then says about the old write changes nothing.
  3934. q.written(16, 13, 0, false);
  3935. q.done(16, w16);
  3936. q.later(16, w16, 13, 4);
  3937. assert_eq!(q.mapped(16), 0);
  3938. assert_eq!(q.due(13, 100)[0].0, 16);
  3939. // A draw that makes the host slot (`seen`) keeps what the queue knows,
  3940. let w15 = write(&q, 15);
  3941. q.partly(15, w15, 20, 8192);
  3942. q.written(15, 14, 0, true);
  3943. assert_eq!(q.mapped(15), 8192);
  3944. // and queues a slot the queue did not hold.
  3945. q.written(99, 14, 0, true);
  3946. assert!(q.due(14, 100).iter().any(|d| d.0 == 99));
  3947. // A write due later (a table's slot) is not handed out before.
  3948. q.written(98, 14, 16, false);
  3949. assert!(!q.due(15, 100).iter().any(|d| d.0 == 98));
  3950. assert!(q.due(16, 100).iter().any(|d| d.0 == 98));
  3951. }
  3952. /// Slots held back for lack of room on the card are not handed out
  3953. /// until their frame, keep their place, are not counted as waiting
  3954. /// for their memory, and all come back at once when the card has room;
  3955. /// a slot written again meanwhile is the title's new write.
  3956. #[test]
  3957. fn slots_held_for_lack_of_room_come_back_when_there_is_room() {
  3958. let mut q = TextureQueue::default();
  3959. for i in 0..4u32 {
  3960. q.written(20 + i, 1, 0, false);
  3961. }
  3962. let due = q.due(1, 100);
  3963. assert_eq!(due.len(), 4);
  3964. // The card is full: slots 20 and 21 are held back until frame 101.
  3965. for &(index, write) in due.iter().filter(|d| d.0 < 22) {
  3966. q.hold(index, write, 101);
  3967. }
  3968. let now: Vec<u32> = q.due(2, 100).into_iter().map(|d| d.0).collect();
  3969. assert!(!now.contains(&20) && !now.contains(&21));
  3970. assert!(now.contains(&22) && now.contains(&23));
  3971. assert_eq!(q.census(2)[2], 0, "held slots do not wait for their memory");
  3972. // Due again at their frame, in the order they had.
  3973. assert_eq!(q.due(101, 100), due);
  3974. // Slot 21 is written again while held: due as written.
  3975. q.written(21, 3, 0, false);
  3976. assert!(q.due(3, 100).iter().any(|d| d.0 == 21));
  3977. // Room again at frame 5: slot 20 is due at once, and only it was
  3978. // still held as it was.
  3979. assert_eq!(q.room(5), 1);
  3980. assert!(q.due(5, 100).iter().any(|d| d.0 == 20));
  3981. assert_eq!(q.room(6), 0);
  3982. }
  3983. /// Textures of which only the smallest levels are held, packed into
  3984. /// one another's address range (the three of run 188: 0x2c000 bytes
  3985. /// each at full size, their starts 0x2000 and 0x4000 apart): writing
  3986. /// any of them, in any order and again, leaves the others.
  3987. #[test]
  3988. fn packed_neighbours_stay() {
  3989. let mut spans = Spans::default();
  3990. assert_eq!(spans.rule, Rule::Start);
  3991. let at = 0xb_86bf_8000u64;
  3992. let (a, b, c) = (at, at + 0x2000, at + 0x6000);
  3993. assert!(spans.note(105_998, a, a + 0x2c000, true).is_empty());
  3994. assert!(spans.note(106_004, b, b + 0x2c000, true).is_empty());
  3995. assert!(spans.note(108_521, c, c + 0x2c000, true).is_empty());
  3996. // The first written again (as a title does when levels arrive),
  3997. // from another slot too: its span reaches over the other two.
  3998. assert!(spans.note(7, a, a + 0x2c000, true).is_empty());
  3999. assert!(spans.note(106_004, b, b + 0x2c000, true).is_empty());
  4000. let mut all = spans.slots_in(0, u64::MAX);
  4001. all.sort_unstable();
  4002. assert_eq!(all, [7, 105_998, 106_004, 108_521]);
  4003. // A draw makes a slot of the second texture: it is one of them.
  4004. assert!(spans.note(9, b, b + 0x2c000, false).is_empty());
  4005. assert_eq!(spans.by_slot.get(&9), Some(&b));
  4006. }
  4007. /// A texture written where another starts replaces it: at the same
  4008. /// address with another length, or inside the block of its smallest
  4009. /// levels. The packed neighbours of the one replaced stay.
  4010. #[test]
  4011. fn a_texture_written_at_the_start_of_another_replaces_it() {
  4012. let mut spans = Spans::default();
  4013. let at = 0x7_0000_0000u64;
  4014. assert!(spans.note(1, at, at + 0x2c000, true).is_empty());
  4015. assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty());
  4016. // Another length from the same start: slot 1 is stale, slot 2 not.
  4017. assert_eq!(spans.note(3, at, at + 0xb000, true), [1]);
  4018. // A start inside the first 4 KiB of slot 3's texture: stale too.
  4019. assert_eq!(spans.note(4, at + 0x800, at + 0x1800, true), [3]);
  4020. // And the other way: a texture that starts just before one.
  4021. assert_eq!(spans.note(5, at + 0x1800, at + 0x4800, true), [2]);
  4022. let mut left = spans.slots_in(0, u64::MAX);
  4023. left.sort_unstable();
  4024. assert_eq!(left, [4, 5]);
  4025. // Exactly 4 KiB apart: both there.
  4026. assert!(spans.note(6, at + 0x2800, at + 0x3800, true).is_empty());
  4027. // A draw's view that clashes is left out, and nothing is stale.
  4028. assert!(spans.note(8, at + 0x900, at + 0x2900, false).is_empty());
  4029. assert_eq!(spans.by_slot.get(&8), None);
  4030. assert_eq!(spans.by_slot.len(), 3);
  4031. }
  4032. /// A slot written with another texture leaves its old span; the same
  4033. /// view written again changes nothing.
  4034. #[test]
  4035. fn a_slot_rewritten_moves_to_its_new_span() {
  4036. let mut spans = Spans::default();
  4037. assert!(spans.note(1, 0x10000, 0x3c000, true).is_empty());
  4038. assert!(spans.note(2, 0x12000, 0x3e000, true).is_empty());
  4039. assert!(spans.note(1, 0x10000, 0x3c000, true).is_empty());
  4040. assert_eq!(spans.slots_in(0x10000, 0x10001), [1]);
  4041. // Slot 1 now views a texture far away.
  4042. assert!(spans.note(1, 0x90000, 0x91000, true).is_empty());
  4043. assert_eq!(spans.slots_in(0x10000, 0x10001), [] as [u32; 0]);
  4044. assert_eq!(spans.slots_in(0x12000, 0x12001), [2]);
  4045. assert_eq!(spans.slots_in(0x90000, 0x90001), [1]);
  4046. spans.forget(1);
  4047. spans.forget(2);
  4048. assert!(spans.by_start.is_empty() && spans.by_slot.is_empty());
  4049. }
  4050. /// Memory the runtime maps, unmaps or writes names the textures that
  4051. /// are there: among packed neighbours the one whose held levels the
  4052. /// range lies in (it ends where the next one starts), and the ones
  4053. /// that start inside the range.
  4054. #[test]
  4055. fn memory_changed_under_packed_neighbours_names_the_ones_there() {
  4056. let mut spans = Spans::default();
  4057. let at = 0x7_0000_0000u64;
  4058. assert!(spans.note(1, at, at + 0x2c000, true).is_empty());
  4059. assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty());
  4060. assert!(spans.note(3, at + 0x6000, at + 0x32000, true).is_empty());
  4061. // Inside the first one's held levels.
  4062. assert_eq!(spans.slots_in(at + 0x1000, at + 0x2000), [1]);
  4063. // Inside the second's: not the first, which ends where it starts.
  4064. assert_eq!(spans.slots_in(at + 0x3000, at + 0x4000), [2]);
  4065. // Past the last start: the last one.
  4066. assert_eq!(spans.slots_in(at + 0x20000, at + 0x21000), [3]);
  4067. // A range over all of them.
  4068. assert_eq!(spans.slots_in(at, at + 0x8000), [1, 2, 3]);
  4069. // Past the end of all: none.
  4070. assert_eq!(spans.slots_in(at + 0x32000, at + 0x33000), [] as [u32; 0]);
  4071. }
  4072. /// A write names the textures that hold its bytes: the one that
  4073. /// starts where the write starts, not the neighbour before it, whose
  4074. /// held levels end there.
  4075. #[test]
  4076. fn a_write_at_the_start_of_a_packed_texture_names_it_alone() {
  4077. let mut spans = Spans::default();
  4078. let at = 0x7_0000_0000u64;
  4079. assert!(spans.note(1, at, at + 0x2c000, true).is_empty());
  4080. assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty());
  4081. assert!(spans.note(3, at + 0x6000, at + 0x32000, true).is_empty());
  4082. // A request that fills the second texture's held levels.
  4083. assert_eq!(spans.slots_in(at + 0x2000, at + 0x6000), [1, 2]);
  4084. assert_eq!(spans.slots_holding(at + 0x2000, at + 0x6000), [2]);
  4085. // From inside the first one's held levels on: both.
  4086. assert_eq!(spans.slots_holding(at + 0x1000, at + 0x3000), [1, 2]);
  4087. // A whole 64 KiB page: every texture that starts in it.
  4088. assert_eq!(spans.slots_holding(at, at + 0x10000), [1, 2, 3]);
  4089. // Past the last start, the last one; past all, or no bytes, none.
  4090. assert_eq!(spans.slots_holding(at + 0x20000, at + 0x21000), [3]);
  4091. assert_eq!(spans.slots_holding(at + 0x32000, at + 0x33000), [] as [u32; 0]);
  4092. assert_eq!(spans.slots_holding(at + 0x2000, at + 0x2000), [] as [u32; 0]);
  4093. }
  4094. /// A write behind the guards' back under a placed texture: a slot
  4095. /// waiting for its first upload is left alone, one uploaded before is
  4096. /// counted, and made due two frames on when that is asked for. (The
  4097. /// ranges are handed over here, not through the list all heaps share.)
  4098. #[test]
  4099. fn a_page_write_makes_an_uploaded_texture_slot_due_when_asked() {
  4100. let Some(heap) = HostHeap::new(false, 8) else {
  4101. return; // no host GPU
  4102. };
  4103. let slots = |at: u64| -> Vec<u32> { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() };
  4104. // 64x64 BC7, one mip, at an address no test and no title uses.
  4105. let at = 0x7fed_0000_0000u64;
  4106. let mut desc = [0u32; 16];
  4107. (desc[10], desc[11]) = (at as u32, (at >> 32) as u32);
  4108. let view = View::Placed(false, [3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc);
  4109. assert!(heap.note_buffer(1, Some(&view), false).is_empty());
  4110. let written = [(at, at + 0x1000)];
  4111. // Waiting for its first upload: held, not uploaded, nothing done.
  4112. assert_eq!(heap.slots_written_under(&written, 50, true), [1, 0, 0]);
  4113. let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0];
  4114. assert_eq!(queued, 1);
  4115. heap.texture_slot_done(1, write, None);
  4116. assert_eq!(slots(u64::MAX), []);
  4117. // Uploaded and out of the queue. Memory elsewhere: nothing.
  4118. assert_eq!(heap.slots_written_under(&[(at + 0x10_0000, at + 0x10_1000)], 60, true), [0, 0, 0]);
  4119. // Under it, counted only: it stays out of the queue.
  4120. assert_eq!(heap.slots_written_under(&written, 60, false), [1, 1, 0]);
  4121. assert_eq!(slots(u64::MAX), []);
  4122. // Under it, asked for: due two frames on, not before.
  4123. assert_eq!(heap.slots_written_under(&written, 60, true), [1, 1, 1]);
  4124. assert_eq!(slots(61), []);
  4125. assert_eq!(slots(62), [1]);
  4126. }
  4127. /// `VICTORY_STALE_TEXTURES=0`: nothing is ever stale, and a view that
  4128. /// overlaps others is left out of the spans, as before.
  4129. #[test]
  4130. fn never_stale_leaves_overlapping_views_out() {
  4131. let mut spans = Spans { rule: Rule::Never, ..Default::default() };
  4132. assert!(spans.note(1, 0x1000, 0x3000, true).is_empty());
  4133. assert!(spans.note(2, 0x2000, 0x4000, true).is_empty());
  4134. assert!(spans.note(3, 0x1000, 0x2000, true).is_empty());
  4135. assert_eq!(spans.slots_in(0, u64::MAX), [1]);
  4136. }
  4137. /// The rule until run 188 (`VICTORY_STALE_TEXTURES=overlap`): a view
  4138. /// written over memory that older views describe otherwise makes
  4139. /// those stale; views of the same span are one texture's.
  4140. #[test]
  4141. fn a_newer_view_of_other_memory_makes_the_older_stale() {
  4142. let mut spans = Spans { rule: Rule::Overlap, ..Default::default() };
  4143. // Three textures side by side, the first in two slots.
  4144. assert!(spans.note(1, 0x1000, 0x3000, true).is_empty());
  4145. assert!(spans.note(2, 0x1000, 0x3000, true).is_empty());
  4146. assert!(spans.note(3, 0x3000, 0x4000, true).is_empty());
  4147. assert!(spans.note(4, 0x8000, 0x9000, true).is_empty());
  4148. // The same slot written with the same span again: nothing changes.
  4149. assert!(spans.note(2, 0x1000, 0x3000, true).is_empty());
  4150. assert_eq!(spans.slots_in(0x2000, 0x3800), [1, 2, 3]);
  4151. assert_eq!(spans.slots_in(0x4000, 0x8000), [] as [u32; 0]);
  4152. // A draw makes a slot whose view overlaps them: left out, nothing stale.
  4153. assert!(spans.note(9, 0x2000, 0x3800, false).is_empty());
  4154. assert_eq!(spans.slots_in(0x2000, 0x3800), [1, 2, 3]);
  4155. // The title writes a texture over the end of the first and all of
  4156. // the second: their three slots are stale.
  4157. let mut stale = spans.note(5, 0x2000, 0x4000, true);
  4158. stale.sort_unstable();
  4159. assert_eq!(stale, [1, 2, 3]);
  4160. assert_eq!(spans.slots_in(0, u64::MAX), [5, 4]);
  4161. // Another start in the same memory: stale in turn. Another length
  4162. // from the same start too.
  4163. assert_eq!(spans.note(6, 0x2800, 0x3000, true), [5]);
  4164. assert_eq!(spans.note(7, 0x2800, 0x2c00, true), [6]);
  4165. // A slot that moves to another texture leaves its span behind.
  4166. assert!(spans.note(7, 0x8000, 0x9000, true).is_empty());
  4167. assert_eq!(spans.slots_in(0x2800, 0x2c00), [] as [u32; 0]);
  4168. assert_eq!(spans.slots_in(0x8000, 0x8001), [4, 7]);
  4169. spans.forget(4);
  4170. spans.forget(7);
  4171. assert!(spans.by_start.is_empty() && spans.by_slot.is_empty());
  4172. }
  4173. /// Memory the runtime maps under a slot's texture makes the slot due
  4174. /// again from the next frame; a stale slot leaves the queue.
  4175. #[test]
  4176. fn remapped_memory_makes_its_texture_slots_due() {
  4177. let Some(heap) = HostHeap::new(false, 8) else {
  4178. return; // no host GPU
  4179. };
  4180. let slots = |at: u64| -> Vec<u32> { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() };
  4181. // 64x64 BC7, one mip, at an address no test and no title uses.
  4182. let at = 0x7fee_0000_0000u64;
  4183. let view = |address: u64, width: u32| {
  4184. let mut desc = [0u32; 16];
  4185. (desc[10], desc[11]) = (address as u32, (address >> 32) as u32);
  4186. View::Placed(false, [3, 0, 0, 0, width, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc)
  4187. };
  4188. let len = crate::resource::placed_bytes(&[3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0]).unwrap();
  4189. assert!(heap.note_buffer(1, Some(&view(at, 64)), false).is_empty());
  4190. let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0];
  4191. assert_eq!(queued, 1);
  4192. heap.texture_slot_done(1, write, None);
  4193. assert_eq!(slots(u64::MAX), []);
  4194. // Memory elsewhere: nothing. Under the texture: due from the next frame.
  4195. remapped((at + 2 * len) as usize, 0x1000);
  4196. remapped(at as usize, 0x1000);
  4197. assert_eq!(heap.texture_slots_remapped(50), 1);
  4198. assert_eq!(slots(50), []);
  4199. assert_eq!(slots(51), [1]);
  4200. // A wider texture written at the same address: slot 1 is stale.
  4201. assert_eq!(heap.note_buffer(2, Some(&view(at, 128)), false), [1]);
  4202. assert_eq!(slots(u64::MAX), [2]);
  4203. }
  4204. /// A slot a draw read through a table leaves the queue; the title's
  4205. /// next write of it waits for its draw, and is due after the grace
  4206. /// frames if none reads it.
  4207. #[test]
  4208. fn slots_read_through_tables_leave_the_texture_queue() {
  4209. let Some(heap) = HostHeap::new(false, 8) else {
  4210. return; // no host GPU
  4211. };
  4212. let frame = 100;
  4213. let slots = |at: u64| -> Vec<u32> { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() };
  4214. let texture = View::Placed(false, [3, 0, 0, 0, 4, 0, 4, 0x1_0001, 28, 1, 0, 0x105, 0, 0], [0; 16]);
  4215. assert!(is_texture_view(&texture));
  4216. heap.queue_texture(2, true, false, frame);
  4217. heap.queue_texture(3, true, false, frame);
  4218. assert_eq!(slots(frame), [3, 2]);
  4219. heap.tabled_in(3, true, frame);
  4220. assert_eq!(slots(frame), [2]);
  4221. // Made in place by the draw that read it: still out.
  4222. heap.queue_texture(3, true, true, frame);
  4223. assert_eq!(slots(frame), [2]);
  4224. // Written again in the next frame: due once the grace frames have
  4225. // passed without a draw that reads it.
  4226. heap.queue_texture(3, true, false, frame + 1);
  4227. assert_eq!(slots(frame + TABLED_GRACE), [2]);
  4228. assert_eq!(slots(frame + 1 + TABLED_GRACE), [3, 2]);
  4229. // The draw comes after all: out again.
  4230. heap.tabled_in(3, true, frame + 1);
  4231. assert_eq!(slots(u64::MAX), [2]);
  4232. // A slot of a table no draw read stays queued; its next write waits.
  4233. heap.tabled_in(2, false, frame + 1);
  4234. assert_eq!(slots(frame + 1), [2]);
  4235. heap.queue_texture(2, true, false, frame + 2);
  4236. assert_eq!(slots(frame + 2), []);
  4237. // Long after the last table, a write is due at once.
  4238. heap.queue_texture(2, true, false, frame + 3 + TABLED_FRAMES);
  4239. assert_eq!(slots(frame + 3 + TABLED_FRAMES), [2]);
  4240. }
  4241. #[test]
  4242. fn dynamic_slots_are_held_until_released() {
  4243. let Some(heap) = HostHeap::new(false, 4) else {
  4244. return; // no host GPU
  4245. };
  4246. let a = heap.dynamic(heap.dynamic - 100).unwrap();
  4247. let b = heap.dynamic(60).unwrap();
  4248. assert_eq!((a, b), (4, 4 + heap.dynamic - 100));
  4249. // 40 left at the end: 50 do not fit until something is given back.
  4250. assert_eq!(heap.dynamic(50), None);
  4251. heap.release(a, 50);
  4252. assert_eq!(heap.dynamic(50), Some(4));
  4253. assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40));
  4254. }
  4255. #[test]
  4256. fn dynamic_search_can_find_a_run_across_the_cursor() {
  4257. let Some(heap) = HostHeap::new(false, 4) else {
  4258. eprintln!("no host descriptor heap; skipped");
  4259. return;
  4260. };
  4261. let first = heap.dynamic(1).unwrap();
  4262. let left = heap.dynamic(2).unwrap();
  4263. let right = heap.dynamic(2).unwrap();
  4264. let rest = heap.dynamic(heap.dynamic - 5).unwrap();
  4265. assert_eq!((first, left, right, rest), (4, 5, 7, 9));
  4266. // Reallocating the left half puts the cursor back in the middle.
  4267. heap.release(left, 2);
  4268. assert_eq!(heap.dynamic(2), Some(left));
  4269. heap.release(left, 2);
  4270. heap.release(right, 2);
  4271. assert_eq!(heap.dynamic(4), Some(left));
  4272. assert_eq!(heap.dynamic(1), None);
  4273. // A free slot at each physical end does not form a two-slot range.
  4274. heap.release(first, 1);
  4275. let last = first + heap.dynamic - 1;
  4276. heap.release(last, 1);
  4277. assert_eq!(heap.dynamic(2), None);
  4278. }
  4279. }