draw.rs 173 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905
  1. //! Draws on the host GPU (decision 0007, step 3). A list keeps the state
  2. //! the title sets for its draws (pipeline, descriptor heaps, root
  3. //! arguments, vertex and index buffers, targets); each draw then brings the
  4. //! host list up to date: the host pipeline and our root signature, the
  5. //! user data the translated shaders read, the host copies of the buffers
  6. //! and descriptors they read, and the states of the textures involved.
  7. //! State the host keeps across draws (viewports, scissors, blend factor,
  8. //! stencil reference, topology, targets) is set on the host list as the
  9. //! title sets it.
  10. use std::sync::atomic::{AtomicU64, Ordering};
  11. use victory_shader::resource::RootIndexedView;
  12. use victory_shader::{ResourceType, RootType, UsedResource};
  13. use crate::descriptor::View;
  14. use windows::Win32::Foundation::RECT;
  15. use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY;
  16. use windows::Win32::Graphics::Direct3D12::*;
  17. use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
  18. use windows::core::Interface;
  19. use crate::host::HostList;
  20. use crate::object::This;
  21. use crate::pipeline::host::HostPipeline;
  22. /// A root argument as the title set it.
  23. #[derive(Debug, Clone, Default)]
  24. enum Root {
  25. #[default]
  26. None,
  27. /// A descriptor table's first descriptor (an address in a heap).
  28. Table(u64),
  29. Constants(Vec<u32>),
  30. /// A root view's GPU address.
  31. View(u64),
  32. }
  33. #[repr(C)]
  34. #[derive(Debug, Clone, Copy, Default)]
  35. pub(crate) struct VertexView {
  36. address: u64,
  37. size: u32,
  38. stride: u32,
  39. }
  40. #[repr(C)]
  41. #[derive(Debug, Clone, Copy, Default)]
  42. pub(crate) struct IndexView {
  43. address: u64,
  44. size: u32,
  45. format: u32,
  46. }
  47. /// Host states of a depth target, and of a texture shaders read.
  48. const DEPTH_WRITE: u32 = 0x10;
  49. const DEPTH_READ: u32 = 0x20;
  50. const SHADER_RESOURCE: u32 = 0x40 | 0x80;
  51. thread_local! {
  52. /// While a draw is prepared (`State::bind`, then its targets' states):
  53. /// the depth target the draw only tests (0: none, or one it writes),
  54. /// and whether a view its shaders read is of that same texture.
  55. static TESTED_DEPTH: std::cell::Cell<(usize, bool)> =
  56. const { std::cell::Cell::new((0, false)) };
  57. /// While a stage's tables are walked (`State::tables`): whether that
  58. /// stage's shader can store to buffers (`Translated::stores`).
  59. static STORES: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
  60. /// While `State::early_textures` runs the texture pass: the
  61. /// milliseconds and the bytes that run may take, in place of the
  62. /// pass's own per frame.
  63. static PASS_BUDGET: std::cell::Cell<Option<(u64, u64)>> = const { std::cell::Cell::new(None) };
  64. }
  65. /// The milliseconds of every frame the pass that uploads textures picked
  66. /// by index takes before a shader that picks by index has asked for it
  67. /// (`VICTORY_EARLY_TEXTURES_MS`, 12; 0: never, as before), and the
  68. /// milliseconds it may take just before a draw of the title's decoration
  69. /// bake (`VICTORY_BAKE_TEXTURES_MS`, 1500; 0: nothing special).
  70. ///
  71. /// The pass ran only from the first world frame on, where it met some
  72. /// 24,000 slots at once and needed 60-80 frames for them. The title bakes
  73. /// its characters' skin and decorations into textures of its own while it
  74. /// loads, 159-1,165 frames before that (runs 156-174), with a pixel shader
  75. /// that picks its sources by index: whatever was not on the card then was
  76. /// baked as nothing, once, for the run. On the console a texture is there
  77. /// when its bytes are.
  78. fn early_budgets() -> (u64, u64) {
  79. static MS: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new();
  80. *MS.get_or_init(|| {
  81. let ms = |name: &str, default: u64| {
  82. std::env::var(name).ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(default)
  83. };
  84. (ms("VICTORY_EARLY_TEXTURES_MS", 12), ms("VICTORY_BAKE_TEXTURES_MS", 1500))
  85. })
  86. }
  87. /// Whether a draw of the title's bake finds the textures it picks by index
  88. /// as title memory has them at that moment (`VICTORY_BAKE_EXACT=0`: as the
  89. /// pass leaves them, as before). The pass looks at a slot whose memory was
  90. /// written or mapped a frame or two later, by when the rest of it has
  91. /// landed, and at one uploaded whole a few frames later again, for a title
  92. /// that fills memory unnoticed: a bake in between took the bytes from before
  93. /// (another texture's), and what it bakes stays: coloured specks all over
  94. /// the waitress's face for the whole diner scene (run n01), none in other
  95. /// runs. So the pass ahead of a bake takes those slots too, and its uploads
  96. /// wait for title memory that is being remapped (`crate::texture` `BAKING`).
  97. fn bake_exact() -> bool {
  98. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  99. *ON.get_or_init(|| std::env::var_os("VICTORY_BAKE_EXACT").is_none_or(|v| v != "0"))
  100. }
  101. /// Whether a texture found changed with nothing to tell of it is looked at
  102. /// again in the next frame (`VICTORY_RECHECK_SOON=0`: after four, as
  103. /// before).
  104. fn recheck_soon() -> bool {
  105. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  106. *ON.get_or_init(|| std::env::var_os("VICTORY_RECHECK_SOON").is_none_or(|v| v != "0"))
  107. }
  108. /// Frames ahead the pass before a bake takes slots from that are due only
  109. /// then ([`bake_exact`]): those of notices (1 and 2), and the first looks
  110. /// again ([`RECHECK_FRAMES`]).
  111. const BAKE_AHEAD: u64 = 12;
  112. /// The pixel shaders of the title's decoration bake (the title:
  113. /// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the
  114. /// frame listings print it. They draw into a 256x256 corner of 2048x2048
  115. /// targets and name no texture in a table.
  116. const BAKE_PIXEL_SHADERS: [&str; 4] =
  117. ["c0a7fe77b1862e10", "0d1575a396dfe513", "b7cfd8dda91ebb6b", "280967ad158cee0b"];
  118. /// Since the start: early runs of the texture pass, and those of them
  119. /// made for a bake draw.
  120. pub(crate) static EARLY_TEXTURE_PASSES: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)];
  121. /// Whether a buffer range a shader names through an unordered access view
  122. /// is given to shaders as written (snapshot before the submission, compare
  123. /// and write back after) only if that shader's code can store to buffers.
  124. /// The title binds buffers its shaders only read through such views, and
  125. /// every range declared costs a snapshot and a compare of its bytes: 3.97
  126. /// GB a frame in 31 submissions, 0.49 s of snapshots and 0.28 s of
  127. /// comparing (run 28). On by default; `VICTORY_WRITE_SKIP=0` declares
  128. /// every such range, as before.
  129. fn write_skip() -> bool {
  130. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  131. *ON.get_or_init(|| std::env::var_os("VICTORY_WRITE_SKIP").is_none_or(|v| v != "0"))
  132. }
  133. /// A run of indirect records clamped in one pass ([`windows`]): the host
  134. /// copy they came from (its number), their kind and stride, the offset of
  135. /// the first in that copy, how many, and the list's scratch buffer that
  136. /// holds them clamped, record `i` at `i * step`.
  137. #[derive(Clone)]
  138. struct Window {
  139. copy: u64,
  140. kind: u32,
  141. stride: u32,
  142. /// How far apart the records are in the copy, and in the scratch
  143. /// buffer: what the title walks them by ([`windows`]).
  144. step: u32,
  145. base: u64,
  146. records: u32,
  147. scratch: ID3D12Resource,
  148. }
  149. /// The most records clamped in one pass ([`windows`]).
  150. const WINDOW_MOST: u64 = 64;
  151. /// Whether indirect draws that read record after record of one argument
  152. /// buffer are clamped a window at a time (`VICTORY_INDIRECT_WINDOW=1`; off
  153. /// by default).
  154. ///
  155. /// The title issues its mesh draws one record per call, each from the next
  156. /// slot of the same argument buffer: 3,460 a frame in gameplay, and before
  157. /// each our clamp ran as a compute dispatch of its own between two waits,
  158. /// so the card went from drawing to compute and back for every record. In
  159. /// the timing run of the lit scene (run 79) a shadow draw of next to
  160. /// nothing cost 14-16 microseconds, 4,126 records a frame.
  161. ///
  162. /// With the switch, when a draw asks for a record a short step after the
  163. /// one drawn before, the clamp takes that record and the ones that step
  164. /// apart after it (16, then twice as many each time, [`WINDOW_MOST`] at
  165. /// most, never past the buffer) into
  166. /// the list's scratch buffer in one pass, and the draws that follow read
  167. /// their record there with no pass of ours and no barrier (the scratch
  168. /// buffer stays readable as arguments until the next clamp), until one of
  169. /// these: a compute
  170. /// dispatch, a direct draw, an indirect call with a count buffer or more
  171. /// than one record, a draw whose shaders can store to buffers, a record
  172. /// outside the window, another host list.
  173. ///
  174. /// The step is the one the title is seen to take, not the stride its
  175. /// command signature names: it draws one record a call, for which the
  176. /// stride means nothing, and the title names 12 bytes (the three
  177. /// words of a mesh dispatch) for records it keeps 32 bytes apart (2,173 of
  178. /// a frame's 3,349 mesh records in run 87's listed frame; 283 are 16
  179. /// apart, which ends a window). Walked by the named stride the window
  180. /// never opened: run 87, with the switch, still clamped 5,068 records a
  181. /// frame one at a time.
  182. ///
  183. /// What it costs the guard against garbage records: nothing against a
  184. /// hang (every record is bounded as before and charged to the list's
  185. /// budget as before), but the budget is charged when a window is clamped,
  186. /// so also for records of the window's tail that are never drawn. Those
  187. /// hold garbage in this title (slots of all ones: run 93 spent lists'
  188. /// budgets on them and emptied the draws after), so in a window a record
  189. /// that asks for more than can run is left empty and charges nothing
  190. /// (`crate::indirect::bound_ahead`); a tail record that looks real is
  191. /// charged what it asks, a few thousand of 2^27. And arguments the title's CPU side changes are seen as
  192. /// before, at the next submission.
  193. fn windows() -> bool {
  194. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  195. *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_WINDOW").is_some_and(|v| v == "1"))
  196. }
  197. /// Whether indirect executions of one record are clamped in batches
  198. /// (`crate::indirect::batch`; `VICTORY_INDIRECT_BATCH=0`: each on its own,
  199. /// or in windows ([`windows`])).
  200. ///
  201. /// A frame of gameplay has 4,809 indirect executions (a capture: 3,523 mesh
  202. /// draws, 948 dispatches, 338 draws), and with the windows still 2,355
  203. /// clamps: each a dispatch between two full waits, with the scratch buffer
  204. /// moved twice. The replayed frame's 84.6 ms are 75.3 ms with the clamps in
  205. /// 133 passes, and 77.7 ms in the 980 of this.
  206. ///
  207. /// A batch is opened by the first execution after a point where arguments
  208. /// may have changed, and all executions up to the next such point read
  209. /// theirs from it, each exactly the record it asks for (windows guess which
  210. /// are next, and clamp what they do not know). Arguments in buffers change
  211. /// by dispatches and by draws whose shaders store to buffers; those end the
  212. /// batch, so the record an execution reads is clamped after all that was
  213. /// recorded before it, and the pass waits for all of it, exactly as the
  214. /// clamp of its own did. Between two executions of a batch is no wait of
  215. /// ours: there is nothing between them to wait for but draws that store to
  216. /// no buffer.
  217. ///
  218. /// `VICTORY_INDIRECT_BATCH=2`: a dispatch does not end the batch before the
  219. /// title waits for it (a barrier, or a pipeline sync) or draws: what a
  220. /// dispatch writes is not there for a later command without a wait, and
  221. /// dispatches the title runs side by side (its tile classes, up to 92 at a
  222. /// time) are not held up by waits of ours. Off: whether the title has ways
  223. /// to wait that do not pass through its lists' methods is not known.
  224. fn batches() -> u8 {
  225. static ON: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
  226. *ON.get_or_init(|| match std::env::var("VICTORY_INDIRECT_BATCH").as_deref() {
  227. Ok("0") => 0,
  228. Ok("2") => 2,
  229. _ => 1,
  230. })
  231. }
  232. /// The records clamped by the pass opened last ([`batches`]).
  233. struct Batch {
  234. table: crate::indirect::batch::Table,
  235. scratch: ID3D12Resource,
  236. /// Dispatches since, which may have written arguments
  237. /// (`VICTORY_INDIRECT_BATCH=2`).
  238. wrote: bool,
  239. }
  240. /// The host copies arguments were read from last: what a batch opens with,
  241. /// as the executions after the first may read theirs from another one.
  242. static ARGUMENT_COPIES: std::sync::Mutex<Vec<std::sync::Weak<crate::shadow::Shadow>>> = std::sync::Mutex::new(Vec::new());
  243. /// [`ARGUMENT_COPIES`] that live, and `first` put in front of them.
  244. fn argument_copies(first: &std::sync::Arc<crate::shadow::Shadow>) -> Vec<(u64, ID3D12Resource)> {
  245. let mut copies = ARGUMENT_COPIES.lock().unwrap_or_else(|e| e.into_inner());
  246. let live: Vec<_> = copies.iter().filter_map(std::sync::Weak::upgrade).filter(|s| s.id() != first.id()).collect();
  247. *copies = std::iter::once(first)
  248. .chain(&live)
  249. .take(crate::indirect::batch::SOURCES)
  250. .map(std::sync::Arc::downgrade)
  251. .collect();
  252. live.iter().map(|s| (s.id(), s.buffer.clone())).collect()
  253. }
  254. /// What one title list has set, and what its host list was last given.
  255. #[derive(Default)]
  256. pub(crate) struct State {
  257. pipeline: usize,
  258. /// View heap, sampler heap.
  259. heaps: [usize; 2],
  260. graphics: Vec<Root>,
  261. compute: Vec<Root>,
  262. vertex: [VertexView; 32],
  263. index: IndexView,
  264. /// Bound render target and depth resources, for their host states.
  265. targets: Vec<usize>,
  266. depth: usize,
  267. /// The host state the bound depth view needs ([`depth_state`]).
  268. depth_state: u32,
  269. /// The title's primitive topology (the host's may differ).
  270. topology: u32,
  271. /// What the title set that goes straight onto the host list, kept for
  272. /// the host list that continues this one after a cut ([`State::replay`]):
  273. /// whether a topology was set, the render target and depth handles, the
  274. /// viewports, the scissors, the blend factor and the stencil reference.
  275. topology_set: bool,
  276. target_handles: Vec<u64>,
  277. depth_handle: u64,
  278. targets_set: bool,
  279. viewports: Vec<D3D12_VIEWPORT>,
  280. scissors: Vec<RECT>,
  281. blend: Option<[f32; 4]>,
  282. stencil: Option<u32>,
  283. depth_bounds: Option<[f32; 2]>,
  284. /// The indirect records clamped last, if later draws may still read
  285. /// them ([`windows`]).
  286. window: Option<Window>,
  287. /// The records clamped in a batch, if later executions may still read
  288. /// them ([`batches`]).
  289. batch: Option<Batch>,
  290. /// The user data bound last, of the last stage that has some (for the
  291. /// report of a removed device, `crate::host::indirects`).
  292. #[cfg(feature = "diagnostics")]
  293. user: Vec<u32>,
  294. /// What the host list has: pipeline, root signature, heaps.
  295. host_pipeline: usize,
  296. /// Graphics, compute.
  297. host_roots: [usize; 2],
  298. host_heaps: [usize; 2],
  299. /// Tables made afresh in this list: (table, slot count, contents) → first
  300. /// dynamic slot.
  301. fresh_tables: std::collections::HashMap<(u64, u32, u64), u32>,
  302. /// The dynamic slots the list holds: title heap, first, count; given
  303. /// back when the list has run, is reset or released.
  304. dynamic: Vec<(usize, u32, u32)>,
  305. /// Root SRVs bound as one-view tables in this list: (title heap, title
  306. /// address; 0 for none) → dynamic slot, and the host copy the slot
  307. /// shows: later draws of the list bring that one up to date, whatever
  308. /// copy the address would find by then (`shadow.rs` `tails`).
  309. root_srv_slots: std::collections::HashMap<(usize, u64), RootSlot>,
  310. /// Root UAVs bound as one-view tables in this list, likewise.
  311. root_uav_slots: std::collections::HashMap<(usize, u64), RootSlot>,
  312. /// The list ran and its dynamic slots were given back.
  313. tables_gone: bool,
  314. }
  315. impl Drop for State {
  316. fn drop(&mut self) {
  317. for &(heap, first, n) in &self.dynamic {
  318. crate::descriptor::release_dynamic(heap, first, n);
  319. }
  320. }
  321. }
  322. impl State {
  323. /// The list's submission has run (submissions are waited for): the
  324. /// dynamic slots its tables were made in are given back, not kept
  325. /// until the title resets the list. A frame of the opening cutscene
  326. /// asks for 12,500 tables; held until the resets they ran the 131,072
  327. /// slots out, and up to 4,900 draws a frame went without their tables.
  328. /// shortcut: a list the title runs a second time without a reset then
  329. /// reads slots others may have taken (logged once).
  330. pub(crate) fn tables_done(&mut self) {
  331. if self.tables_gone && self.dynamic.is_empty() {
  332. return;
  333. }
  334. if self.tables_gone {
  335. static ONCE: std::sync::Once = std::sync::Once::new();
  336. ONCE.call_once(|| tracing::warn!("a list ran again after its descriptor tables were given back"));
  337. }
  338. for (heap, first, n) in self.dynamic.drain(..) {
  339. crate::descriptor::release_dynamic(heap, first, n);
  340. }
  341. self.fresh_tables.clear();
  342. self.root_srv_slots.clear();
  343. self.root_uav_slots.clear();
  344. self.tables_gone = true;
  345. }
  346. }
  347. /// An experiment on the title's scissor rectangles (`VICTORY_SCISSOR_TEST=full`):
  348. /// they are all widened to the whole target. The title's room at
  349. /// the start of the prologue lost its walls in five runs of seven, and in
  350. /// those runs the player's body and the world outside were cut by one
  351. /// rectangle around the window (run 85, frame 2046): one run with this on
  352. /// says whether the walls are drawn and cut away by such a rectangle, or
  353. /// not drawn at all. Off by default: a rectangle the title sets is part of
  354. /// its picture.
  355. fn scissor_test() -> bool {
  356. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  357. *ON.get_or_init(|| std::env::var("VICTORY_SCISSOR_TEST").as_deref() == Ok("full"))
  358. }
  359. /// An experiment on mesh draws (`VICTORY_MESH_TEST`): 1 for `skip` (none
  360. /// is issued), 2 for `scissor` (each runs its shaders but rasterises one
  361. /// pixel), 0 otherwise. It tells a card hung by a mesh shader from one hung
  362. /// by what the shader's triangles cover.
  363. fn mesh_test() -> u8 {
  364. static ON: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
  365. *ON.get_or_init(|| match std::env::var("VICTORY_MESH_TEST").as_deref() {
  366. Ok("skip") => 1,
  367. Ok("scissor") => 2,
  368. _ => 0,
  369. })
  370. }
  371. /// `VICTORY_MESH_TEST=keep:<hex digits>[:<hex digits>]`: only the mesh
  372. /// draws whose mesh shader's hash ends in one of the first digits (and
  373. /// whose digit before it is one of the second, if given) are issued: a
  374. /// search for the shaders that stop the card.
  375. fn mesh_kept(pipeline: usize) -> bool {
  376. static KEEP: std::sync::OnceLock<Option<(String, String)>> = std::sync::OnceLock::new();
  377. let Some((last, before)) = KEEP.get_or_init(|| {
  378. let value = std::env::var("VICTORY_MESH_TEST").ok()?;
  379. let mut parts = value.strip_prefix("keep:")?.split(':');
  380. Some((parts.next()?.to_owned(), parts.next().unwrap_or("").to_owned()))
  381. }) else {
  382. return true;
  383. };
  384. let Some(p) = crate::pipeline::host_pipeline(pipeline as This) else {
  385. return true;
  386. };
  387. let Some(at) = p.name.find("mesh ") else {
  388. return true;
  389. };
  390. let hash = p.name[at + 5..].as_bytes();
  391. if hash.len() < 16 {
  392. return true;
  393. }
  394. last.as_bytes().contains(&hash[15]) && (before.is_empty() || before.as_bytes().contains(&hash[14]))
  395. }
  396. /// Draws recorded on the host GPU since the last frame line.
  397. static DRAWN: AtomicU64 = AtomicU64::new(0);
  398. /// Draws run on the host so far.
  399. pub(crate) fn drawn() -> u64 {
  400. DRAWN.load(Ordering::Relaxed)
  401. }
  402. /// The draws traced since the last present (diagnostics builds, with
  403. /// debug logging for this module): logged when the frame comes out black.
  404. #[cfg(feature = "diagnostics")]
  405. static FRAME: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
  406. /// The draws traced since the last call.
  407. #[cfg(feature = "diagnostics")]
  408. pub(crate) fn take_frame() -> Vec<String> {
  409. std::mem::take(&mut *FRAME.lock().unwrap_or_else(|e| e.into_inner()))
  410. }
  411. /// Draws, mesh dispatches and dispatches recorded but not run on the host
  412. /// (no host pipeline) since the last call.
  413. pub(crate) fn take_dropped() -> u64 {
  414. DROPPED.swap(0, Ordering::Relaxed)
  415. }
  416. /// A root SRV's dynamic slot in a list, and the host copy it shows.
  417. type RootSlot = (u32, Option<std::sync::Arc<crate::shadow::Shadow>>);
  418. /// Buffer views of the heap whose slot showed another host buffer than
  419. /// the copy the pass brought up to date for them, since the start
  420. /// (diagnostics; for the memory line). It stays 0 while the pass and the
  421. /// slots agree; with `VICTORY_VIEW_EXTENT=0` it counts the views that were
  422. /// read stale.
  423. #[cfg(feature = "diagnostics")]
  424. pub(crate) static HEAP_VIEWS_ELSEWHERE: AtomicU64 = AtomicU64::new(0);
  425. /// Passes over the view heap's buffer views for shaders that pick them by
  426. /// index ([`State::heap_buffers`]), and the microseconds they took.
  427. pub(crate) static HEAP_BUFFER_PASSES: AtomicU64 = AtomicU64::new(0);
  428. pub(crate) static HEAP_BUFFER_MICROS: AtomicU64 = AtomicU64::new(0);
  429. /// Of the passes, nanoseconds since the last frame line: looking at slots,
  430. /// the spans and refreshes of their copies, the texture side.
  431. #[cfg(feature = "diagnostics")]
  432. pub(crate) static HEAP_SPLIT: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
  433. /// Passes after which every buffer slot of the heap was looked at again.
  434. const HEAP_ROUND: u64 = 16;
  435. /// Whether the slots looked at again for no write are a part of them at
  436. /// every pass, each slot at every sixteenth (`VICTORY_HEAP_SPREAD=0`: all of
  437. /// them at every sixteenth pass, as before).
  438. ///
  439. /// All at once was some 115 ms on a thread that records the frame, every
  440. /// sixteenth frame (72,000 slots; run record-1: 11 ms a pass in the lines
  441. /// without such a pass, 22 in those of ten frames with one). A slot is
  442. /// looked at as often as before.
  443. fn heap_spread() -> bool {
  444. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  445. *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SPREAD").is_none_or(|v| v != "0"))
  446. }
  447. /// The host copy and range the buffer view of each of a heap's slots reads
  448. /// ([`State::heap_buffers`]), by slot.
  449. #[derive(Default)]
  450. struct HeapRanges<T>(Vec<Option<(T, u64, u64)>>);
  451. impl<T> HeapRanges<T> {
  452. fn set(&mut self, slot: u32, range: Option<(T, u64, u64)>) {
  453. let slot = slot as usize;
  454. if range.is_none() && slot >= self.0.len() {
  455. return;
  456. }
  457. if slot >= self.0.len() {
  458. self.0.resize_with(slot + 1, || None);
  459. }
  460. self.0[slot] = range;
  461. }
  462. /// Forgets the slots of one of `parts` parts
  463. /// (`HostHeap::buffer_slots_of`).
  464. fn forget_part(&mut self, part: u32, parts: u32) {
  465. self.0.iter_mut().skip(part as usize).step_by(parts as usize).for_each(|r| *r = None);
  466. }
  467. fn ranges(&self) -> impl Iterator<Item = &(T, u64, u64)> {
  468. self.0.iter().flatten()
  469. }
  470. }
  471. #[cfg(test)]
  472. mod heap_range_tests {
  473. use super::{HEAP_ROUND, HeapRanges};
  474. /// Round by round every slot is looked at again once, whatever was
  475. /// written between, and what a slot holds is what was found last.
  476. #[test]
  477. fn every_slot_is_looked_at_again_in_a_round() {
  478. const SLOTS: u32 = 1000;
  479. let mut ranges = HeapRanges(Vec::new());
  480. ranges.set(7, None);
  481. assert_eq!(ranges.ranges().count(), 0);
  482. for slot in (0..SLOTS).step_by(3) {
  483. ranges.set(slot, Some(((), 0, 1)));
  484. }
  485. let parts = HEAP_ROUND as u32;
  486. for pass in 1..=HEAP_ROUND {
  487. let part = (pass % HEAP_ROUND) as u32;
  488. ranges.forget_part(part, parts);
  489. for slot in (0..SLOTS).step_by(3).filter(|slot| slot % parts == part) {
  490. assert!(ranges.0[slot as usize].is_none(), "slot {slot} not forgotten");
  491. ranges.set(slot, Some(((), pass, pass)));
  492. }
  493. assert_eq!(ranges.ranges().count(), SLOTS.div_ceil(3) as usize);
  494. }
  495. assert!(ranges.ranges().all(|r| r.1 != 0), "a slot not looked at in a round");
  496. ranges.set(3, None);
  497. assert_eq!(ranges.ranges().count(), SLOTS.div_ceil(3) as usize - 1);
  498. }
  499. /// The spans of 4,400 copies from the ranges of 72,000 slots, as a pass
  500. /// makes them, by slot and from the table they were in. Run with
  501. /// `--ignored --nocapture`.
  502. #[test]
  503. #[ignore]
  504. fn spans_of_a_pass() {
  505. use std::collections::HashMap;
  506. use std::sync::Arc;
  507. let copies: Vec<Arc<u64>> = (0..4400).map(Arc::new).collect();
  508. let (mut table, mut slots) = (HashMap::new(), HeapRanges(Vec::new()));
  509. for slot in 0..72_000u32 {
  510. let copy = &copies[slot as usize * 7919 % 4400];
  511. table.insert(slot, (copy.clone(), u64::from(slot), u64::from(slot) + 64));
  512. slots.set(slot, Some((copy.clone(), u64::from(slot), u64::from(slot) + 64)));
  513. }
  514. fn join<S: std::hash::BuildHasher + Default>(ranges: &mut dyn Iterator<Item = &(Arc<u64>, u64, u64)>) -> usize {
  515. let mut spans: HashMap<usize, (Arc<u64>, u64, u64), S> = HashMap::default();
  516. for (copy, from, to) in ranges {
  517. let span = spans.entry(Arc::as_ptr(copy) as usize).or_insert_with(|| (copy.clone(), *from, *to));
  518. span.1 = span.1.min(*from);
  519. span.2 = span.2.max(*to);
  520. }
  521. spans.len()
  522. }
  523. let best = |f: &mut dyn FnMut() -> usize| {
  524. (0..30)
  525. .map(|_| {
  526. let t = std::time::Instant::now();
  527. assert_eq!(f(), 4400);
  528. t.elapsed().as_secs_f64() * 1e3
  529. })
  530. .fold(f64::MAX, f64::min)
  531. };
  532. println!(
  533. "{:.2} ms from the table, {:.2} ms by slot",
  534. best(&mut || join::<std::hash::RandomState>(&mut table.values())),
  535. best(&mut || join::<std::hash::BuildHasherDefault<crate::host::AddressHash>>(&mut slots.ranges())),
  536. );
  537. }
  538. }
  539. /// Textures brought up to date for shaders that pick them by index
  540. /// ([`State::heap_textures`]), the bytes of their memory, and the slots
  541. /// still waiting.
  542. pub(crate) static HEAP_TEXTURES: AtomicU64 = AtomicU64::new(0);
  543. pub(crate) static HEAP_TEXTURE_BYTES: AtomicU64 = AtomicU64::new(0);
  544. pub(crate) static HEAP_TEXTURES_WAITING: AtomicU64 = AtomicU64::new(0);
  545. /// Passes that made no texture because the card had no room
  546. /// (`crate::resource::room`), for the memory line.
  547. pub(crate) static HEAP_TEXTURES_FULL: AtomicU64 = AtomicU64::new(0);
  548. /// Frames after a whole upload of a texture picked by index at which its
  549. /// memory is looked at again, each counted from the look before.
  550. const RECHECK_FRAMES: [u64; 5] = [4, 12, 40, 120, 400];
  551. /// Looks at uploaded textures picked by index that found the memory as it
  552. /// was, and that found it changed (uploaded again), since the start.
  553. pub(crate) static HEAP_TEXTURES_RECHECKED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)];
  554. /// Uploads of textures already on the card made while it had no room for
  555. /// new ones, since the start.
  556. pub(crate) static HEAP_TEXTURES_REUPLOADED_FULL: AtomicU64 = AtomicU64::new(0);
  557. /// Whether a pass over the textures picked by index on a full card holds
  558. /// back the slots that need a new host copy (`VICTORY_FULL_CARD_PASS=0`:
  559. /// no, as before: they stay due, each pass looks at the same ones again
  560. /// and stops at the 257th). Held back, such a slot is looked at again
  561. /// after about four seconds or as soon as the card has room, and the pass
  562. /// goes on to the slots behind it: the ones whose host copy exists and
  563. /// only wants bringing up to date, and the ones whose memory went (letting
  564. /// their host copies go is what makes room). What is uploaded while the
  565. /// card has room is the same either way.
  566. fn full_card_pass() -> bool {
  567. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  568. *ON.get_or_init(|| std::env::var_os("VICTORY_FULL_CARD_PASS").is_none_or(|v| v != "0"))
  569. }
  570. /// Whether a texture that has its host copy is still brought up to date
  571. /// while the card has no room for new ones (`VICTORY_REUPLOAD_WHEN_FULL=0`:
  572. /// no).
  573. fn reupload_when_full() -> bool {
  574. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  575. *ON.get_or_init(|| std::env::var_os("VICTORY_REUPLOAD_WHEN_FULL").is_none_or(|v| v != "0"))
  576. }
  577. /// Whether textures picked by index are looked at again after their upload
  578. /// (`VICTORY_HEAP_RECHECK=0`: no).
  579. fn heap_recheck() -> bool {
  580. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  581. *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_RECHECK").is_none_or(|v| v != "0"))
  582. }
  583. /// Times a placed texture's slot was passed over because its memory is not
  584. /// mapped.
  585. pub(crate) static HEAP_TEXTURES_SAME: AtomicU64 = AtomicU64::new(0);
  586. pub(crate) static HEAP_TEXTURES_AWAY: AtomicU64 = AtomicU64::new(0);
  587. /// Slots the pass found up to date already: their texture is uploaded by
  588. /// the draws that read it through a table (it has a staging buffer).
  589. pub(crate) static HEAP_TEXTURES_TABLED: AtomicU64 = AtomicU64::new(0);
  590. /// The queue of textures picked by index at the last pass
  591. /// (`TextureQueue::census`): slots in it, due, waiting for their memory,
  592. /// uploaded in part, and the frames the oldest due one has waited.
  593. pub(crate) static HEAP_TEXTURES_QUEUE: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5];
  594. /// Since the start: looks at a slot uploaded in part that found no more of
  595. /// its memory mapped; uploads of textures not all mapped; and of those,
  596. /// the ones whose first page was not there (asked by the first page alone,
  597. /// as before, they counted as not there at all).
  598. pub(crate) static HEAP_TEXTURES_PARTLY: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
  599. static DROPPED: AtomicU64 = AtomicU64::new(0);
  600. /// Marks the last traced draw as not run on the host.
  601. #[cfg(feature = "diagnostics")]
  602. fn dropped(pipeline: usize) {
  603. crate::pipeline::note_drop(pipeline as This);
  604. if let Some(last) = FRAME.lock().unwrap_or_else(|e| e.into_inner()).last_mut() {
  605. last.push_str(" DROPPED");
  606. }
  607. }
  608. /// Dispatches run on the host so far.
  609. static DISPATCHED: AtomicU64 = AtomicU64::new(0);
  610. pub(crate) fn dispatched() -> u64 {
  611. DISPATCHED.load(Ordering::Relaxed)
  612. }
  613. /// The host address of a root view: its buffer's host copy, or for a
  614. /// constant buffer not 256-byte aligned there (the console needs 16) a
  615. /// copy in upload memory.
  616. /// shortcut: a root view has no size; constant buffers are taken as 64 KiB
  617. /// (cut at their buffer's end), other views as all that is left of their
  618. /// buffer. (They were taken as 1 MiB: 1,452 of the 2,021 mesh vertex
  619. /// streams of a cutscene frame reach further, and what lay past the first
  620. /// megabyte was never brought up to date - meshes without bodies, exploded
  621. /// triangles. `VICTORY_ROOT_VIEW_MB` sets a limit again.)
  622. fn root_view(list: &HostList, address: u64, srv: bool) -> Option<u64> {
  623. static LIMIT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  624. let limit = *LIMIT.get_or_init(|| {
  625. std::env::var("VICTORY_ROOT_VIEW_MB")
  626. .ok()
  627. .and_then(|v| v.parse::<u64>().ok())
  628. .map_or(u64::MAX, |mb| mb << 20)
  629. });
  630. let shadow = crate::shadow::find(address, 1)?;
  631. let len = shadow
  632. .left(address)
  633. .min(if srv { limit } else { 1 << 16 });
  634. let gpu = shadow.gpu(address);
  635. if srv || gpu % 256 == 0 {
  636. shadow.refresh(list, address, len);
  637. return Some(gpu);
  638. }
  639. let (gpu, to) = list.scratch(len)?;
  640. list.defer_fill(to, address as *const u8, len as usize);
  641. Some(gpu)
  642. }
  643. macro_rules! once {
  644. ($($arg:tt)*) => {{
  645. static ONCE: std::sync::Once = std::sync::Once::new();
  646. ONCE.call_once(|| tracing::warn!($($arg)*));
  647. }};
  648. }
  649. fn set(roots: &mut Vec<Root>, slot: u32, root: Root) {
  650. let slot = slot as usize;
  651. if roots.len() <= slot {
  652. roots.resize(slot + 1, Root::None);
  653. }
  654. roots[slot] = root;
  655. }
  656. impl State {
  657. pub(crate) fn reset(&mut self, pipeline: This) {
  658. *self = State::default();
  659. self.pipeline = pipeline as usize;
  660. }
  661. /// The title's topology; console-only ones become host lists (see
  662. /// [`crate::primitive`]).
  663. pub(crate) fn set_topology(&mut self, list: &HostList, topology: u32) {
  664. self.topology = topology;
  665. self.topology_set = true;
  666. let host = match topology {
  667. RECTANGLES => 4,
  668. TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => {
  669. once!(topology, "console topology drawn as a triangle list");
  670. 4
  671. }
  672. t => t,
  673. };
  674. // SAFETY: an open list.
  675. unsafe {
  676. list.list
  677. .IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(host as i32))
  678. };
  679. }
  680. pub(crate) fn set_pipeline(&mut self, pipeline: This) {
  681. self.pipeline = pipeline as usize;
  682. }
  683. pub(crate) fn set_heaps(&mut self, heaps: &[This]) {
  684. self.heaps = [0; 2];
  685. for &h in heaps {
  686. if !h.is_null() {
  687. let samplers = crate::descriptor::heap(h).samplers();
  688. self.heaps[usize::from(samplers)] = h as usize;
  689. }
  690. }
  691. }
  692. fn roots(&mut self, compute: bool) -> &mut Vec<Root> {
  693. if compute {
  694. &mut self.compute
  695. } else {
  696. &mut self.graphics
  697. }
  698. }
  699. pub(crate) fn set_table(&mut self, compute: bool, slot: u32, handle: u64) {
  700. set(self.roots(compute), slot, Root::Table(handle));
  701. }
  702. pub(crate) fn set_view(&mut self, compute: bool, slot: u32, address: u64) {
  703. set(self.roots(compute), slot, Root::View(address));
  704. }
  705. pub(crate) fn set_constants(&mut self, compute: bool, slot: u32, values: &[u32], offset: u32) {
  706. let roots = self.roots(compute);
  707. let s = slot as usize;
  708. if !matches!(roots.get(s), Some(Root::Constants(_))) {
  709. set(roots, slot, Root::Constants(Vec::new()));
  710. }
  711. if let Root::Constants(c) = &mut roots[s] {
  712. let end = offset as usize + values.len();
  713. if c.len() < end {
  714. c.resize(end, 0);
  715. }
  716. c[offset as usize..end].copy_from_slice(values);
  717. }
  718. }
  719. pub(crate) fn set_vertex_buffers(&mut self, start: u32, views: &[VertexView]) {
  720. for (i, v) in views.iter().enumerate() {
  721. if let Some(slot) = self.vertex.get_mut(start as usize + i) {
  722. *slot = *v;
  723. }
  724. }
  725. }
  726. pub(crate) fn clear_vertex_buffers(&mut self, start: u32, count: u32) {
  727. for slot in self.vertex.iter_mut().skip(start as usize).take(count as usize) {
  728. *slot = VertexView::default();
  729. }
  730. }
  731. pub(crate) fn set_index_buffer(&mut self, view: Option<&IndexView>) {
  732. self.index = view.copied().unwrap_or_default();
  733. }
  734. /// Render targets and depth, set on the host list at once.
  735. pub(crate) fn set_targets(&mut self, list: &HostList, handles: &[u64], depth: u64) {
  736. let Some(host) = crate::host::host() else {
  737. return;
  738. };
  739. self.target_handles.clear();
  740. self.target_handles.extend_from_slice(handles);
  741. self.depth_handle = depth;
  742. self.targets_set = true;
  743. self.targets.clear();
  744. let mut rtvs = Vec::new();
  745. for &h in handles {
  746. let Some(record) = crate::descriptor::rtv_record(h) else {
  747. once!(
  748. handle = format_args!("{h:#x}"),
  749. "render target without a recorded view"
  750. );
  751. continue;
  752. };
  753. let Some(texture) = crate::resource::host_resource(record.resource) else {
  754. // A typed null view (or a target without a host copy) still
  755. // takes its slot: left out, the next live target would move
  756. // into it and the pixel shader's outputs reach the wrong
  757. // targets.
  758. // shortcut: a view without a description or a format has no
  759. // null view to stand for it and is left out, as before.
  760. let null = record
  761. .desc()
  762. .filter(|d| d.Format.0 != 0 && d.ViewDimension.0 != 0);
  763. if let Some(desc) = null {
  764. rtvs.push(host.rtv(None, Some(&desc)));
  765. }
  766. continue;
  767. };
  768. self.targets.push(record.resource as usize);
  769. #[cfg(feature = "diagnostics")]
  770. crate::capture::note_target(record.resource);
  771. rtvs.push(host.rtv(Some(texture), record.desc().as_ref()));
  772. }
  773. self.depth = 0;
  774. self.depth_state = DEPTH_WRITE;
  775. let dsv = crate::descriptor::dsv_record(depth).and_then(|record| {
  776. let texture = crate::resource::host_resource(record.resource)?;
  777. self.depth = record.resource as usize;
  778. self.depth_state = depth_state(texture, record.depth_desc().as_ref());
  779. if crate::resource::depth_and_unordered(record.resource) {
  780. crate::resource::DEPTH_UNORDERED[1].fetch_add(1, Ordering::Relaxed);
  781. }
  782. #[cfg(feature = "diagnostics")]
  783. crate::capture::note_target(record.resource);
  784. Some(host.dsv(texture, record.depth_desc().as_ref()))
  785. });
  786. // SAFETY: an open list; the views were just made.
  787. unsafe {
  788. list.list.OMSetRenderTargets(
  789. rtvs.len() as u32,
  790. (!rtvs.is_empty()).then_some(rtvs.as_ptr()),
  791. false,
  792. dsv.as_ref().map(std::ptr::from_ref),
  793. )
  794. };
  795. }
  796. /// Viewports, scissors, the blend factor and the stencil reference: set
  797. /// on the host list at once, and kept for [`State::replay`].
  798. pub(crate) fn set_viewports(&mut self, list: &HostList, viewports: &[D3D12_VIEWPORT]) {
  799. self.viewports.clear();
  800. self.viewports.extend_from_slice(viewports);
  801. crate::draw::viewports(list, viewports);
  802. }
  803. pub(crate) fn set_scissors(&mut self, list: &HostList, rects: &[RECT]) {
  804. self.scissors.clear();
  805. self.scissors.extend_from_slice(rects);
  806. if scissor_test() {
  807. // The experiment: every rectangle the title sets is widened to
  808. // the largest target there is, so nothing is cut by one. What
  809. // the listing shows (`op_text`) stays the title's own.
  810. let full = RECT {
  811. left: 0,
  812. top: 0,
  813. right: 16384,
  814. bottom: 16384,
  815. };
  816. crate::draw::scissors(list, &vec![full; rects.len()]);
  817. return;
  818. }
  819. crate::draw::scissors(list, rects);
  820. }
  821. pub(crate) fn set_blend_factor(&mut self, list: &HostList, factor: Option<&[f32; 4]>) {
  822. self.blend = factor.copied();
  823. crate::draw::blend_factor(list, factor);
  824. }
  825. pub(crate) fn set_stencil_ref(&mut self, list: &HostList, reference: u32) {
  826. self.stencil = Some(reference);
  827. crate::draw::stencil_ref(list, reference);
  828. }
  829. pub(crate) fn set_depth_bounds(&mut self, list: &HostList, min: f32, max: f32) {
  830. self.depth_bounds = Some([min, max]);
  831. crate::draw::depth_bounds(list, min, max);
  832. }
  833. /// `list` is a new host list that continues the title's list (it was
  834. /// cut at a wait for a memory value, `crate::list::cut`): a new host
  835. /// list has nothing set, so what the title set so far is set again.
  836. /// The pipeline, the root signatures and the heaps are set by the next
  837. /// draw or dispatch (`bind`, which is told here that the host list has
  838. /// none); root arguments, vertex and index buffers are set by every
  839. /// draw anyway. The dynamic descriptor slots and the tables made in
  840. /// them stay: the parts before the cut have not run yet, and they are
  841. /// given back when the title's list is reset.
  842. /// shortcut: the render target views are made again from the handles'
  843. /// descriptors as they are now, not as they were when the title set
  844. /// the targets (a descriptor rewritten in between names another view).
  845. pub(crate) fn replay(&mut self, list: &HostList) {
  846. self.host_pipeline = 0;
  847. self.host_roots = [0; 2];
  848. self.host_heaps = [0; 2];
  849. if self.topology_set {
  850. self.set_topology(list, self.topology);
  851. }
  852. if self.targets_set {
  853. let handles = std::mem::take(&mut self.target_handles);
  854. self.set_targets(list, &handles, self.depth_handle);
  855. }
  856. if !self.viewports.is_empty() {
  857. crate::draw::viewports(list, &self.viewports);
  858. }
  859. if !self.scissors.is_empty() {
  860. let rects = std::mem::take(&mut self.scissors);
  861. self.set_scissors(list, &rects);
  862. }
  863. if let Some(factor) = self.blend {
  864. crate::draw::blend_factor(list, Some(&factor));
  865. }
  866. if let Some(reference) = self.stencil {
  867. crate::draw::stencil_ref(list, reference);
  868. }
  869. if let Some([min, max]) = self.depth_bounds {
  870. crate::draw::depth_bounds(list, min, max);
  871. }
  872. }
  873. /// The user-data value of a root argument, as translated shaders read
  874. /// it: a table's byte offset in its heap, a constant's value.
  875. fn user_value(&self, compute: bool, slot: u8, root: RootType, dword: u32) -> u32 {
  876. match (self.roots_ref(compute).get(usize::from(slot)), root) {
  877. (Some(Root::Table(handle)), RootType::Table) => match self.heap_of(*handle) {
  878. Some(heap) => (handle - heap.start) as u32,
  879. None => {
  880. once!(
  881. handle = format_args!("{handle:#x}"),
  882. "descriptor table outside the bound heaps"
  883. );
  884. 0
  885. }
  886. },
  887. (Some(Root::Constants(c)), RootType::Constants) => {
  888. c.get(dword as usize).copied().unwrap_or(0)
  889. }
  890. // The host's own ([`Self::host_word`]): no root argument.
  891. (_, RootType::Other(_)) => 0,
  892. _ => {
  893. once!(
  894. slot,
  895. ?root,
  896. "a shader reads a root argument the title did not set"
  897. );
  898. 0
  899. }
  900. }
  901. }
  902. /// A user-data dword the host computes for a translated shader
  903. /// (`victory_shader::emit::USER_MEMORY_BASE`, `USER_VIEW_ADDRESS`).
  904. fn host_word(
  905. &self,
  906. compute: bool,
  907. kind: u32,
  908. slot: u8,
  909. dword: u32,
  910. memory: Option<&crate::memory::Ready>,
  911. ) -> u32 {
  912. use victory_shader::emit::{USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS};
  913. if kind == USER_MEMORY_BASE {
  914. return memory.map_or(0, |m| m.base);
  915. }
  916. if kind == USER_VIEW_BIAS {
  917. // The view begins on 16 bytes of the copy the address finds
  918. // (`root_uav`, `root_srv_table`).
  919. // shortcut: found again here, not taken from the list's slot.
  920. return match self.roots_ref(compute).get(usize::from(slot)) {
  921. Some(&Root::View(address)) => crate::shadow::find(address, 1).map_or(0, |s| {
  922. // SAFETY: a live buffer.
  923. let base = unsafe { s.buffer.GetGPUVirtualAddress() };
  924. ((s.gpu(address) - base) & 15) as u32
  925. }),
  926. _ => 0,
  927. };
  928. }
  929. if kind != USER_VIEW_ADDRESS && kind != USER_VIEW_ADDRESS + 1 {
  930. once!(kind, "a shader reads a host value this build does not know");
  931. return 0;
  932. }
  933. let address = self.view_address(compute, slot, dword);
  934. if address == 0 {
  935. // The first few say what lies there instead.
  936. static SAID: AtomicU64 = AtomicU64::new(0);
  937. if SAID.fetch_add(1, Ordering::Relaxed) < 8 {
  938. let view = match self.roots_ref(compute).get(usize::from(slot)) {
  939. Some(&Root::Table(table)) => crate::descriptor::view(table + u64::from(dword) * 4),
  940. _ => None,
  941. };
  942. tracing::warn!(slot, dword, ?view, "a shader takes the address of a buffer view that is not there: it reads 0");
  943. }
  944. }
  945. if kind == USER_VIEW_ADDRESS {
  946. address as u32
  947. } else {
  948. (address >> 32) as u32
  949. }
  950. }
  951. /// The title address the view at dword `dword` of the table in root
  952. /// slot `slot` starts at, 0 without one.
  953. fn view_address(&self, compute: bool, slot: u8, dword: u32) -> u64 {
  954. match self.roots_ref(compute).get(usize::from(slot)) {
  955. Some(&Root::Table(table)) => crate::descriptor::view(table + u64::from(dword) * 4)
  956. .and_then(|view| crate::descriptor::host::view_address(&view))
  957. .unwrap_or(0),
  958. _ => 0,
  959. }
  960. }
  961. /// For a shader that reads title memory by address
  962. /// ([`crate::memory`]): its directory, fault notes and view slots,
  963. /// with the pages made ready of the root views the list has set and of
  964. /// the views whose addresses it takes (`t`: the ray-tracing structures
  965. /// it walks).
  966. fn memory_ready(
  967. &self,
  968. list: &HostList,
  969. t: &crate::pipeline::Translated,
  970. compute: bool,
  971. writes: bool,
  972. ) -> Option<crate::memory::Ready> {
  973. let heap = match self.heaps[0] {
  974. 0 => None,
  975. h => crate::descriptor::heap(h as This).host(),
  976. }?;
  977. let (mut addresses, mut constants) = (Vec::new(), Vec::new());
  978. for root in self.roots_ref(compute) {
  979. match root {
  980. Root::View(address) => addresses.push(*address),
  981. Root::Constants(values) => constants.extend_from_slice(values),
  982. _ => {}
  983. }
  984. }
  985. for u in &t.host.user_data {
  986. if u.root == RootType::Other(victory_shader::emit::USER_VIEW_ADDRESS) {
  987. addresses.push(self.view_address(compute, u.slot, u.dword));
  988. }
  989. }
  990. crate::memory::ready(list, heap, &addresses, &constants, writes)
  991. }
  992. /// The bound heap holding `handle`.
  993. fn heap_of(&self, handle: u64) -> Option<&'static crate::descriptor::Heap> {
  994. self.heaps
  995. .iter()
  996. .filter(|&&h| h != 0)
  997. .map(|&h| crate::descriptor::heap(h as This))
  998. .find(|h| h.index(handle).is_some())
  999. }
  1000. /// Brings the host list up to date for a draw; false if the draw cannot
  1001. /// run on the host.
  1002. fn prepare(&mut self, list: &HostList, indexed: bool) -> bool {
  1003. self.prepare_for(list, indexed, false)
  1004. }
  1005. /// As [`State::prepare`], for draws (`mesh` false) or mesh dispatches.
  1006. fn prepare_for(&mut self, list: &HostList, indexed: bool, mesh: bool) -> bool {
  1007. #[cfg(feature = "diagnostics")]
  1008. if crate::pipeline::is_skipped(self.pipeline as This) {
  1009. return false;
  1010. }
  1011. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  1012. return false;
  1013. };
  1014. if p.compute || p.mesh != mesh {
  1015. once!(mesh, "a draw or mesh dispatch with another kind of pipeline");
  1016. return false;
  1017. }
  1018. if p.rects && self.topology != RECTANGLES {
  1019. // Its geometry stage would turn each triangle into a rectangle.
  1020. once!("a rectangle pipeline drawn with another topology");
  1021. }
  1022. if !self.bind(list, p, false) {
  1023. return false;
  1024. }
  1025. let l = &list.list;
  1026. // Vertex buffers the input layout reads.
  1027. let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32];
  1028. let mut count = 0;
  1029. for (slot, (view, &v)) in views.iter_mut().zip(&self.vertex).enumerate() {
  1030. if p.slots & 1 << slot == 0 {
  1031. continue;
  1032. }
  1033. count = slot + 1;
  1034. if v.address == 0 || v.size == 0 {
  1035. continue;
  1036. }
  1037. let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else {
  1038. continue;
  1039. };
  1040. shadow.refresh(list, v.address, u64::from(v.size));
  1041. *view = D3D12_VERTEX_BUFFER_VIEW {
  1042. BufferLocation: shadow.gpu(v.address),
  1043. SizeInBytes: v.size,
  1044. StrideInBytes: v.stride,
  1045. };
  1046. }
  1047. // SAFETY: an open list; the views name live host buffers.
  1048. unsafe {
  1049. if count > 0 {
  1050. l.IASetVertexBuffers(0, Some(&views[..count]));
  1051. }
  1052. }
  1053. if indexed {
  1054. let v = self.index;
  1055. let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else {
  1056. return false;
  1057. };
  1058. shadow.refresh(list, v.address, u64::from(v.size));
  1059. let view = D3D12_INDEX_BUFFER_VIEW {
  1060. BufferLocation: shadow.gpu(v.address),
  1061. SizeInBytes: v.size,
  1062. Format: DXGI_FORMAT(v.format as i32),
  1063. };
  1064. // SAFETY: an open list; the view names a live host buffer.
  1065. unsafe { l.IASetIndexBuffer(Some(&view)) };
  1066. }
  1067. const RENDER_TARGET: u32 = 0x4;
  1068. for &t in &self.targets {
  1069. crate::list::ensure_state(list, t as This, RENDER_TARGET);
  1070. }
  1071. if self.depth != 0 {
  1072. // A depth texture shaders also write: what they wrote, first.
  1073. list.twin_use(self.depth as This, false, true);
  1074. // A view that writes neither plane keeps the texture readable:
  1075. // the depth read state, together with the shader read states
  1076. // if this draw's shaders read the same texture (the write state
  1077. // put it out of the state those views need, and a move to it
  1078. // and back for every such draw).
  1079. let state = if self.depth_state == DEPTH_READ {
  1080. let (tested, read) = TESTED_DEPTH.get();
  1081. if read && tested == self.depth {
  1082. DEPTH_READ | SHADER_RESOURCE
  1083. } else {
  1084. DEPTH_READ
  1085. }
  1086. } else {
  1087. DEPTH_WRITE
  1088. };
  1089. crate::list::ensure_state(list, self.depth as This, state);
  1090. }
  1091. true
  1092. }
  1093. /// A descriptor a shader reads through a table: its host slot made if
  1094. /// it changed, constant data copied, textures made readable.
  1095. /// What draws and dispatches share: heaps, our root signature, the
  1096. /// pipeline, and per stage the user data, root views and the
  1097. /// descriptors its tables hold.
  1098. /// False if the draw or dispatch must not run: a root SRV it reads
  1099. /// could not be given a view.
  1100. pub(crate) fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool {
  1101. let l = &list.list;
  1102. // Textures picked by index, before anything asks for them.
  1103. self.early_textures(list, p, compute);
  1104. if crate::host::walls_trace() {
  1105. self.walls_census(p, compute);
  1106. }
  1107. // Heaps first: a root signature with directly indexed heaps must be
  1108. // set after them.
  1109. if self.host_heaps != self.heaps {
  1110. let heaps: Vec<Option<ID3D12DescriptorHeap>> = self
  1111. .heaps
  1112. .iter()
  1113. .filter(|&&h| h != 0)
  1114. .filter_map(|&h| crate::descriptor::heap(h as This).host())
  1115. .map(|h| Some(h.heap.clone()))
  1116. .collect();
  1117. heaps.iter().flatten().for_each(|h| list.keep(h));
  1118. // SAFETY: an open list and shader-visible heaps.
  1119. unsafe { l.SetDescriptorHeaps(&heaps) };
  1120. self.host_heaps = self.heaps;
  1121. self.host_roots = [0; 2];
  1122. }
  1123. // The depth target a draw only tests, for the views of it that the
  1124. // draw's shaders read (`readable`).
  1125. let tested = if !compute && self.depth_state == DEPTH_READ {
  1126. self.depth
  1127. } else {
  1128. 0
  1129. };
  1130. TESTED_DEPTH.set((tested, false));
  1131. let root = p.root.as_raw() as usize;
  1132. if self.host_roots[usize::from(compute)] != root {
  1133. // SAFETY: an open list and a live root signature.
  1134. unsafe {
  1135. if compute {
  1136. l.SetComputeRootSignature(&p.root);
  1137. } else {
  1138. l.SetGraphicsRootSignature(&p.root);
  1139. }
  1140. }
  1141. self.host_roots[usize::from(compute)] = root;
  1142. }
  1143. // By host object: a title pipeline released and another made at its
  1144. // address is another host pipeline (the list keeps the old one).
  1145. if self.host_pipeline != p.pso.as_raw() as usize {
  1146. // SAFETY: an open list and a live pipeline.
  1147. unsafe { l.SetPipelineState(&p.pso) };
  1148. self.host_pipeline = p.pso.as_raw() as usize;
  1149. list.used_pipeline(&p.name);
  1150. // The title may release the pipeline before it submits the list.
  1151. list.keep(&p.pso);
  1152. list.keep(&p.root);
  1153. }
  1154. for stage in &p.stages {
  1155. let t = stage.translated();
  1156. STORES.set(t.stores);
  1157. if t.stores && crate::picked::on() && crate::picked::picks(&stage.shader, &t.picks) {
  1158. crate::picked::runs_in(list);
  1159. }
  1160. let made = self.tables(list, &t.used, &t.host.root_indexed_views, compute);
  1161. STORES.set(true);
  1162. if made.iter().any(|m| m.1 == u32::MAX) {
  1163. once!("a draw whose descriptor table found no free slots is dropped");
  1164. return false;
  1165. }
  1166. // What the shader stores through root views and raw addresses is
  1167. // copied back into title memory afterwards.
  1168. let writes = (t.stores || !write_skip())
  1169. && !crate::pipeline::builder_quarantined(self.pipeline as This);
  1170. // Title memory by address: what the shader finds it by.
  1171. let memory = if t.host.root_srvs.contains(&victory_shader::emit::SLOT_MEMORY) {
  1172. // Only through a store by address: what it stores through
  1173. // views is declared with them.
  1174. let writes = writes && t.stores_by_address;
  1175. let Some(ready) = self.memory_ready(list, &t, compute, writes) else {
  1176. once!("a shader that reads title memory by address without a view heap to hold its views: the draw is dropped");
  1177. return false;
  1178. };
  1179. Some(ready)
  1180. } else {
  1181. None
  1182. };
  1183. if let Some((param, dwords)) = stage.user_data {
  1184. let mut values = vec![0u32; dwords as usize];
  1185. for u in &t.host.user_data {
  1186. if let RootType::Other(kind) = u.root {
  1187. values[u.index as usize] =
  1188. self.host_word(compute, kind, u.slot, u.dword, memory.as_ref());
  1189. continue;
  1190. }
  1191. let fresh = made
  1192. .iter()
  1193. .find(|m| m.0 == u.slot && u.root == RootType::Table);
  1194. values[u.index as usize] = match fresh {
  1195. Some(&(_, offset)) => offset,
  1196. None => self.user_value(compute, u.slot, u.root, u.dword),
  1197. };
  1198. }
  1199. #[cfg(feature = "diagnostics")]
  1200. {
  1201. self.user.clear();
  1202. self.user.extend_from_slice(&values);
  1203. }
  1204. // SAFETY: an open list; `values` covers the parameter.
  1205. unsafe {
  1206. if compute {
  1207. l.SetComputeRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0);
  1208. } else {
  1209. l.SetGraphicsRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0);
  1210. }
  1211. }
  1212. }
  1213. for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] {
  1214. for &(slot, param) in views {
  1215. if srv && slot == victory_shader::emit::SLOT_MEMORY {
  1216. // Ours: the directory of title memory by address.
  1217. if let Some(m) = &memory {
  1218. // SAFETY: an open list; the directory lives as
  1219. // long as the process and the list holds it.
  1220. unsafe {
  1221. if compute {
  1222. l.SetComputeRootShaderResourceView(param, m.directory);
  1223. } else {
  1224. l.SetGraphicsRootShaderResourceView(param, m.directory);
  1225. }
  1226. }
  1227. }
  1228. continue;
  1229. }
  1230. if srv && slot == victory_shader::emit::SLOT_STRIDES {
  1231. // Ours, not the title's: the shader picks buffers
  1232. // from the view heap by an index it computes.
  1233. match self.heap_buffers(list) {
  1234. // SAFETY: an open list; the table lives as long
  1235. // as the heap the list holds.
  1236. Some(gpu) => unsafe {
  1237. if compute {
  1238. l.SetComputeRootShaderResourceView(param, gpu);
  1239. } else {
  1240. l.SetGraphicsRootShaderResourceView(param, gpu);
  1241. }
  1242. },
  1243. None => once!("a shader picks buffers from a view heap that is not set"),
  1244. }
  1245. continue;
  1246. }
  1247. let tabled = srv && crate::pipeline::host::bounded_root_srvs();
  1248. let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot))
  1249. else {
  1250. once!(slot, "a shader reads a root view the title did not set");
  1251. // A table left unset is undefined: a null view.
  1252. if tabled && !self.root_srv_table(list, None, param, compute, false) {
  1253. return false;
  1254. }
  1255. continue;
  1256. };
  1257. // The shader adds the bytes a raw view begins early by.
  1258. let biased = srv
  1259. && t.host.user_data.iter().any(|u| {
  1260. u.slot == slot
  1261. && u.root == RootType::Other(victory_shader::emit::USER_VIEW_BIAS)
  1262. });
  1263. if tabled {
  1264. if !self.root_srv_table(list, Some(address), param, compute, biased) {
  1265. return false;
  1266. }
  1267. continue;
  1268. }
  1269. let Some(mut gpu) = root_view(list, address, srv) else {
  1270. continue;
  1271. };
  1272. if biased {
  1273. gpu -= u64::from(self.host_word(
  1274. compute,
  1275. victory_shader::emit::USER_VIEW_BIAS,
  1276. slot,
  1277. 0,
  1278. None,
  1279. ));
  1280. }
  1281. // SAFETY: an open list; the address is in live memory.
  1282. unsafe {
  1283. match (compute, srv) {
  1284. (false, false) => l.SetGraphicsRootConstantBufferView(param, gpu),
  1285. (false, true) => l.SetGraphicsRootShaderResourceView(param, gpu),
  1286. (true, false) => l.SetComputeRootConstantBufferView(param, gpu),
  1287. (true, true) => l.SetComputeRootShaderResourceView(param, gpu),
  1288. }
  1289. }
  1290. }
  1291. }
  1292. for &(slot, param) in &stage.root_uavs {
  1293. if slot == victory_shader::emit::SLOT_FAULTS {
  1294. // Ours: where shaders note the pages they found empty.
  1295. if let Some(m) = &memory {
  1296. // SAFETY: an open list; the buffer lives as long as
  1297. // the process and the list holds it.
  1298. unsafe {
  1299. if compute {
  1300. l.SetComputeRootUnorderedAccessView(param, m.faults);
  1301. } else {
  1302. l.SetGraphicsRootUnorderedAccessView(param, m.faults);
  1303. }
  1304. }
  1305. }
  1306. continue;
  1307. }
  1308. let address = match self.roots_ref(compute).get(usize::from(slot)) {
  1309. Some(&Root::View(address)) => Some(address),
  1310. _ => {
  1311. once!(slot, "a shader writes through a root view the title did not set");
  1312. None
  1313. }
  1314. };
  1315. if !self.root_uav(list, address, param, compute, writes) {
  1316. return false;
  1317. }
  1318. }
  1319. }
  1320. // Depth textures it writes through unordered access: their colour
  1321. // twins hold what they lack from here on.
  1322. list.twins_written();
  1323. true
  1324. }
  1325. /// Binds a root UAV: a raw unordered access view of the title buffer's
  1326. /// host copy from `address` on, as a one-view table (a null view
  1327. /// without an address, without a host copy shaders can write, or at an
  1328. /// address not on 16 bytes), or as a root descriptor with
  1329. /// `VICTORY_ROOT_SRV_DIRECT=1` (the dispatch is dropped then if there
  1330. /// is nothing to bind). With `writes`, what the shader stored is copied
  1331. /// back into title memory when the list has run. False if the draw
  1332. /// must be dropped.
  1333. /// shortcut: a root view has no size: the view, the refresh and the
  1334. /// copy back cover all that is left of the title's buffer
  1335. /// (`VICTORY_ROOT_UAV_MB` sets a limit for all three).
  1336. fn root_uav(
  1337. &mut self,
  1338. list: &HostList,
  1339. address: Option<u64>,
  1340. param: u32,
  1341. compute: bool,
  1342. writes: bool,
  1343. ) -> bool {
  1344. const UNORDERED: i32 = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0;
  1345. static LIMIT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  1346. let limit = *LIMIT.get_or_init(|| {
  1347. std::env::var("VICTORY_ROOT_UAV_MB")
  1348. .ok()
  1349. .and_then(|v| v.parse::<u64>().ok())
  1350. .map_or(u64::MAX, |mb| mb << 20)
  1351. });
  1352. let find = |a: u64| {
  1353. let s = crate::shadow::find(a, 1)?;
  1354. // SAFETY: a live buffer.
  1355. let flags = unsafe { s.buffer.GetDesc() }.Flags;
  1356. if flags.0 & UNORDERED == 0 {
  1357. once!("a root UAV of a buffer whose host copy shaders cannot write");
  1358. return None;
  1359. }
  1360. Some(s)
  1361. };
  1362. let ready = |a: u64, s: &std::sync::Arc<crate::shadow::Shadow>| {
  1363. let len = s.left(a).min(limit);
  1364. s.refresh(list, a, len);
  1365. if writes {
  1366. #[cfg(feature = "diagnostics")]
  1367. crate::host::wide_write(a, len, self.pipeline);
  1368. s.gpu_writes(list, a, len);
  1369. }
  1370. };
  1371. if !crate::pipeline::host::bounded_root_srvs() {
  1372. let Some((a, s)) = address.and_then(|a| Some((a, find(a)?))) else {
  1373. once!("a root UAV with nothing to bind: the draw is dropped");
  1374. return false;
  1375. };
  1376. ready(a, &s);
  1377. // From the 16 bytes below: the shader adds the rest.
  1378. // SAFETY: a live buffer.
  1379. let base = unsafe { s.buffer.GetGPUVirtualAddress() };
  1380. let gpu = base + ((s.gpu(a) - base) & !15);
  1381. // SAFETY: an open list; the address is in a live buffer.
  1382. unsafe {
  1383. if compute {
  1384. list.list.SetComputeRootUnorderedAccessView(param, gpu);
  1385. } else {
  1386. list.list.SetGraphicsRootUnorderedAccessView(param, gpu);
  1387. }
  1388. }
  1389. return true;
  1390. }
  1391. let heap = match self.heaps[0] {
  1392. 0 => None,
  1393. h => Some(crate::descriptor::heap(h as This)),
  1394. };
  1395. let Some((heap, host)) = heap.and_then(|h| Some((h, h.host()?))) else {
  1396. once!("a root UAV without a bound view heap: the draw is dropped");
  1397. return false;
  1398. };
  1399. let key = (std::ptr::from_ref(heap) as usize, address.unwrap_or(0));
  1400. let (index, shadow) = match self.root_uav_slots.get(&key) {
  1401. Some((index, shadow)) => (*index, address.zip(shadow.clone())),
  1402. None => {
  1403. let shadow = address.and_then(|a| find(a).map(|s| (a, s)));
  1404. let Some(index) = host.dynamic(1) else {
  1405. return false;
  1406. };
  1407. self.dynamic.push((key.0, index, 1));
  1408. if let Some((a, s)) = &shadow {
  1409. // SAFETY: a live buffer.
  1410. let base = unsafe { s.buffer.GetGPUVirtualAddress() };
  1411. let offset = s.gpu(*a) - base;
  1412. // Raw views start on 16 bytes: from the 16 bytes
  1413. // below, and the shader adds the rest to its offsets
  1414. // (`victory_shader::emit::USER_VIEW_BIAS`). (An address
  1415. // not on 16 bytes got a null view at first: the
  1416. // builder's counters are at such addresses.)
  1417. let bias = offset & 15;
  1418. host.raw_uav_at(index, &s.buffer, offset - bias, s.left(*a).min(limit) + bias);
  1419. }
  1420. if shadow.is_none() {
  1421. host.null_raw_uav_at(index);
  1422. }
  1423. self.root_uav_slots
  1424. .insert(key, (index, shadow.as_ref().map(|(_, s)| s.clone())));
  1425. (index, shadow)
  1426. }
  1427. };
  1428. if let Some((a, s)) = &shadow {
  1429. ready(*a, s);
  1430. }
  1431. let handle = host.gpu_handle(index);
  1432. // SAFETY: an open list; the slot is in the bound view heap.
  1433. unsafe {
  1434. if compute {
  1435. list.list.SetComputeRootDescriptorTable(param, handle);
  1436. } else {
  1437. list.list.SetGraphicsRootDescriptorTable(param, handle);
  1438. }
  1439. }
  1440. true
  1441. }
  1442. /// Binds a root SRV as a one-view table
  1443. /// ([`crate::pipeline::host::bounded_root_srvs`]): a raw view of the
  1444. /// title buffer's host copy from `address` to the copy's end, or a null
  1445. /// view (no address, no host copy, or an address not on 16 bytes). One
  1446. /// dynamic slot per address per list, given back with the list's
  1447. /// others. False if no slot could be had or no view heap is bound.
  1448. fn root_srv_table(
  1449. &mut self,
  1450. list: &HostList,
  1451. address: Option<u64>,
  1452. param: u32,
  1453. compute: bool,
  1454. biased: bool,
  1455. ) -> bool {
  1456. let heap = match self.heaps[0] {
  1457. 0 => None,
  1458. h => Some(crate::descriptor::heap(h as This)),
  1459. };
  1460. let Some((heap, host)) = heap.and_then(|h| Some((h, h.host()?))) else {
  1461. once!("a root SRV without a bound view heap: the draw is dropped");
  1462. return false;
  1463. };
  1464. // A view that begins early is another view than one that does not
  1465. // (title addresses stay below bit 63).
  1466. let key = (
  1467. std::ptr::from_ref(heap) as usize,
  1468. address.unwrap_or(0) | u64::from(biased) << 63,
  1469. );
  1470. let (index, shadow) = match self.root_srv_slots.get(&key) {
  1471. Some((index, shadow)) => (*index, address.zip(shadow.clone())),
  1472. None => {
  1473. let shadow = address.and_then(|a| crate::shadow::find(a, 1).map(|s| (a, s)));
  1474. let Some(index) = host.dynamic(1) else {
  1475. return false;
  1476. };
  1477. self.dynamic.push((key.0, index, 1));
  1478. self.root_srv_slots
  1479. .insert(key, (index, shadow.as_ref().map(|(_, s)| s.clone())));
  1480. match &shadow {
  1481. Some((a, s)) => {
  1482. // SAFETY: a live buffer.
  1483. let base = unsafe { s.buffer.GetGPUVirtualAddress() };
  1484. let offset = s.gpu(*a) - base;
  1485. if biased {
  1486. // From the 16 bytes below; the shader adds the
  1487. // rest (`victory_shader::emit::USER_VIEW_BIAS`).
  1488. let bias = offset & 15;
  1489. host.raw_at(index, &s.buffer, offset - bias, s.left(*a) + bias);
  1490. } else if offset.is_multiple_of(16) {
  1491. host.raw_at(index, &s.buffer, offset, s.left(*a));
  1492. } else {
  1493. // Raw views start on 16 bytes; one from the
  1494. // aligned start would shift every read.
  1495. once!(
  1496. address = format_args!("{a:#x}"),
  1497. "a root SRV not on 16 bytes reads zeros"
  1498. );
  1499. host.null_raw_at(index);
  1500. }
  1501. }
  1502. None => host.null_raw_at(index),
  1503. }
  1504. (index, shadow)
  1505. }
  1506. };
  1507. // As for root descriptors (`root_view`): all that is left of the
  1508. // buffer is brought up to date. The first 1 MiB only left what lay
  1509. // past it stale (most mesh vertex streams reach further).
  1510. if let Some((a, s)) = &shadow {
  1511. s.refresh(list, *a, s.left(*a));
  1512. }
  1513. let handle = host.gpu_handle(index);
  1514. // SAFETY: an open list; the slot is in the bound view heap.
  1515. unsafe {
  1516. if compute {
  1517. list.list.SetComputeRootDescriptorTable(param, handle);
  1518. } else {
  1519. list.list.SetGraphicsRootDescriptorTable(param, handle);
  1520. }
  1521. }
  1522. true
  1523. }
  1524. /// For a shader that picks buffers from the view heap by an index it
  1525. /// computes (SM 6.6 dynamic resources): the GPU address of the heap's
  1526. /// table of element strides, with every buffer view of the heap given
  1527. /// its host slot and its memory brought up to date when `list` is
  1528. /// submitted. Tables tell us which views a draw reads; nothing tells
  1529. /// us which of the heap's a computed index names, so all of them are
  1530. /// made ready, once per list.
  1531. /// shortcut: the buffers are read, not written: what such a shader
  1532. /// writes through a picked unordered access view stays in the host
  1533. /// copy. A list refreshes them where it first runs such a shader;
  1534. /// title writes recorded later in the same list are not seen.
  1535. fn heap_buffers(&self, list: &HostList) -> Option<u64> {
  1536. let heap = self
  1537. .heaps
  1538. .iter()
  1539. .filter(|&&h| h != 0)
  1540. .map(|&h| crate::descriptor::heap(h as This))
  1541. .find(|h| !h.samplers())?;
  1542. let host = heap.host()?;
  1543. let gpu = host.strides_gpu()?;
  1544. // One key per list, as textures have: no title resource is there.
  1545. const ONCE: usize = usize::MAX - 0x5e;
  1546. if !list.first_use(ONCE) {
  1547. return Some(gpu);
  1548. }
  1549. // The list may outlive the title's heap object, which owns the table.
  1550. if let Some(buffer) = host.strides_buffer() {
  1551. list.keep(buffer);
  1552. }
  1553. // The pass itself once per frame: per list it ran up to 51 times a
  1554. // frame over 81,000 views and 4,100 host copies, 18 s of every
  1555. // frame (2026-11-24, run 11).
  1556. // shortcut: what the title writes into such buffers between lists
  1557. // of one frame is seen a frame late.
  1558. static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
  1559. let frame = crate::frame::current();
  1560. if FRAME.swap(frame, Ordering::Relaxed) == frame {
  1561. return Some(gpu);
  1562. }
  1563. let started = std::time::Instant::now();
  1564. // Per host heap: the host copy and range each slot's buffer view
  1565. // reads, kept from pass to pass. Only the slots written since the
  1566. // last pass are looked at again (83,000 slots a pass otherwise, 0.1 s
  1567. // at best); all of them every 16 passes, because a view of a
  1568. // released resource goes stale without a write, and a slot written
  1569. // before its memory had a host copy is only made then.
  1570. type Ranges = HeapRanges<std::sync::Arc<crate::shadow::Shadow>>;
  1571. static RANGES: std::sync::Mutex<Option<std::collections::HashMap<usize, (u64, Ranges)>>> =
  1572. std::sync::Mutex::new(None);
  1573. let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner());
  1574. let (passes, ranges) = kept
  1575. .get_or_insert_with(Default::default)
  1576. .entry(std::ptr::from_ref(host) as usize)
  1577. .or_insert_with(|| (0, HeapRanges(Vec::new())));
  1578. let changed = host.buffer_changes();
  1579. let all = *passes == 0 || (*passes % HEAP_ROUND == 0 && !heap_spread());
  1580. let slots = if all {
  1581. ranges.0.clear();
  1582. host.buffer_slots()
  1583. } else if heap_spread() {
  1584. // The written ones, and this pass's part of the others.
  1585. let (part, parts) = ((*passes % HEAP_ROUND) as u32, HEAP_ROUND as u32);
  1586. ranges.forget_part(part, parts);
  1587. let mut slots = host.buffer_slots_of(part, parts);
  1588. slots.extend(changed);
  1589. slots
  1590. } else {
  1591. changed
  1592. };
  1593. *passes += 1;
  1594. // Whether the device was there before the pass: a view that removes
  1595. // it is named below.
  1596. static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  1597. let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none();
  1598. let mut unordered = Vec::new();
  1599. for (n, &index) in slots.iter().enumerate() {
  1600. ranges.set(index, None);
  1601. // A draw's table's: the draw brings what it reads up to date.
  1602. if host.copied_tabled(index, frame) {
  1603. continue;
  1604. }
  1605. let Some(handle) = heap.handle(index) else {
  1606. continue;
  1607. };
  1608. let Some(view) = host.mirror(index, handle, true) else {
  1609. continue;
  1610. };
  1611. // Every 64 views while the device lives (a cheap query).
  1612. if alive
  1613. && n % 64 == 63
  1614. && let Some(why) = crate::descriptor::host::device_removed()
  1615. {
  1616. alive = false;
  1617. GONE.store(true, Ordering::Relaxed);
  1618. let last: Vec<String> = slots[n - 63..=n]
  1619. .iter()
  1620. .filter_map(|&i| crate::descriptor::view(heap.handle(i)?).map(|v| format!("{i}: {v:?}")))
  1621. .map(|s| s.chars().take(200).collect())
  1622. .collect();
  1623. tracing::error!(why, slot = index, "the host device went while buffer views of the heap were made; one of: {last:#?}");
  1624. crate::host::log_removal_context();
  1625. }
  1626. // The copy the slot shows (`buffer_copy`), not the one the
  1627. // view's range alone would find.
  1628. let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(&view) else {
  1629. continue;
  1630. };
  1631. #[cfg(feature = "diagnostics")]
  1632. if host.shows(index, &shadow.buffer) == Some(false) {
  1633. HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed);
  1634. }
  1635. if crate::picked::on() && view_kind(&view) == Some(ResourceType::Uav) {
  1636. unordered.push((shadow.clone(), address, address + len));
  1637. }
  1638. ranges.set(index, Some((shadow, address, address + len)));
  1639. }
  1640. if crate::picked::on() {
  1641. crate::picked::shown(unordered, all);
  1642. }
  1643. #[cfg(feature = "diagnostics")]
  1644. let looked = std::time::Instant::now();
  1645. // Per host copy, the span its picked views cover.
  1646. let mut spans: crate::host::ByCopy<(std::sync::Arc<crate::shadow::Shadow>, u64, u64)> = Default::default();
  1647. let mut views = 0u32;
  1648. for (shadow, from, to) in ranges.ranges() {
  1649. views += 1;
  1650. let key = std::sync::Arc::as_ptr(shadow) as usize;
  1651. let span = spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to));
  1652. span.1 = span.1.min(*from);
  1653. span.2 = span.2.max(*to);
  1654. }
  1655. drop(kept);
  1656. let bytes: u64 = spans.values().map(|s| s.2 - s.1).sum();
  1657. // Memory that is not write-watched is copied whole by every refresh.
  1658. // It was once refreshed only every 120 frames (unmapped pages read
  1659. // one by one cost 14 GB a frame in run 11, before they were
  1660. // remembered): streamed geometry then drew from stale buffers, and
  1661. // the garbage ended runs (the card stopped answering 14-90 frames
  1662. // into the opening cutscene; with every frame it ran on). The pass
  1663. // costs some 30 ms a frame this way.
  1664. static WHOLE: std::sync::Mutex<Option<std::collections::HashMap<usize, u64>>> = std::sync::Mutex::new(None);
  1665. let mut whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner());
  1666. let whole = whole.get_or_insert_with(Default::default);
  1667. for (shadow, from, to) in spans.values() {
  1668. if shadow.unwatched() {
  1669. // By the copy's number: a copy made where one let go was
  1670. // (`shadow::let_go_idle`) has never been refreshed.
  1671. let key = shadow.id() as usize;
  1672. // `VICTORY_UNWATCHED_FRAMES` sets the interval (1: every frame).
  1673. static EVERY: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  1674. let every = *EVERY.get_or_init(|| {
  1675. std::env::var("VICTORY_UNWATCHED_FRAMES")
  1676. .ok()
  1677. .and_then(|v| v.parse().ok())
  1678. .unwrap_or(1)
  1679. });
  1680. match whole.get(&key) {
  1681. Some(&last) if frame < last + every => continue,
  1682. _ => {
  1683. whole.insert(key, frame);
  1684. }
  1685. }
  1686. }
  1687. shadow.refresh(list, *from, to - from);
  1688. }
  1689. #[cfg(feature = "diagnostics")]
  1690. let refreshed = std::time::Instant::now();
  1691. crate::watch::look_at_holes();
  1692. self.heap_textures(list, heap, host);
  1693. #[cfg(feature = "diagnostics")]
  1694. for (sum, time) in HEAP_SPLIT.iter().zip([looked - started, refreshed - looked, refreshed.elapsed()]) {
  1695. sum.fetch_add(time.as_nanos() as u64, Ordering::Relaxed);
  1696. }
  1697. HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed);
  1698. HEAP_BUFFER_MICROS.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  1699. static LOGGED: AtomicU64 = AtomicU64::new(0);
  1700. // The first pass and every growth of the set by half.
  1701. let seen = LOGGED.load(Ordering::Relaxed);
  1702. if u64::from(views) > seen + seen / 2 {
  1703. LOGGED.store(u64::from(views), Ordering::Relaxed);
  1704. tracing::info!(
  1705. slots = slots.len(),
  1706. views,
  1707. copies = spans.len(),
  1708. mb = bytes >> 20,
  1709. ms = started.elapsed().as_millis(),
  1710. "buffer views of the heap made ready for shaders that pick them by index"
  1711. );
  1712. }
  1713. Some(gpu)
  1714. }
  1715. /// Runs the pass that uploads textures picked by index
  1716. /// ([`State::heap_textures`]) where nothing has asked for it yet
  1717. /// ([`early_budgets`]): once a frame for a few milliseconds, at the
  1718. /// frame's first draw with a view heap set, and with a larger budget
  1719. /// of its own before every draw whose pixel shader is one of the
  1720. /// title's bake programs. The uploads are recorded into `list` ahead
  1721. /// of the draw being bound, as the world's pass records them.
  1722. fn early_textures(&self, list: &HostList, p: &HostPipeline, compute: bool) {
  1723. let (early_ms, bake_ms) = early_budgets();
  1724. if compute || (early_ms == 0 && bake_ms == 0) {
  1725. return;
  1726. }
  1727. let bake = bake_ms > 0
  1728. && p.stages.iter().any(|s| BAKE_PIXEL_SHADERS.contains(&s.shader.hash.as_str()));
  1729. static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
  1730. // The milliseconds this frame's bake draws have taken so far: a
  1731. // frame has several, and together they get `bake_ms`.
  1732. static BAKED_MS: AtomicU64 = AtomicU64::new(0);
  1733. let frame = crate::frame::current();
  1734. let first = FRAME.swap(frame, Ordering::Relaxed) != frame;
  1735. if first {
  1736. BAKED_MS.store(0, Ordering::Relaxed);
  1737. }
  1738. let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed));
  1739. let budget = if bake && left > 0 {
  1740. // What a bake may read must be there now: up to 2 GiB.
  1741. (left, 2 << 30)
  1742. } else if first && early_ms > 0 {
  1743. (early_ms, 64 << 20)
  1744. } else {
  1745. return;
  1746. };
  1747. let Some(heap) = self
  1748. .heaps
  1749. .iter()
  1750. .filter(|&&h| h != 0)
  1751. .map(|&h| crate::descriptor::heap(h as This))
  1752. .find(|h| !h.samplers())
  1753. else {
  1754. return;
  1755. };
  1756. let Some(host) = heap.host() else {
  1757. return;
  1758. };
  1759. let bake = bake && left > 0;
  1760. let n = EARLY_TEXTURE_PASSES[usize::from(bake)].fetch_add(1, Ordering::Relaxed) + 1;
  1761. if bake && n.is_power_of_two() {
  1762. let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed));
  1763. tracing::info!(
  1764. frame,
  1765. bakes = n,
  1766. queued_at_the_last_pass = slots,
  1767. due_at_the_last_pass = due,
  1768. uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed),
  1769. "a draw of the title's decoration bake: textures picked by index are uploaded first (VICTORY_BAKE_TEXTURES_MS=0: not)"
  1770. );
  1771. }
  1772. let began = std::time::Instant::now();
  1773. PASS_BUDGET.set(Some(budget));
  1774. crate::texture::BAKING.set(bake && bake_exact());
  1775. self.heap_textures(list, heap, host);
  1776. crate::texture::BAKING.set(false);
  1777. PASS_BUDGET.set(None);
  1778. if bake {
  1779. BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed);
  1780. }
  1781. }
  1782. /// The queue's side of the card accounting line
  1783. /// (`crate::resource::card_accounting`, which says what the line
  1784. /// holds): the slots that are due, by what their texture has on the
  1785. /// card. Off unless `VICTORY_CARD_ACCOUNTING=1`; then at the first pass
  1786. /// that finds the card without room, and every five seconds after it.
  1787. /// Nothing is made, uploaded or counted as used here. For 18,000 due
  1788. /// slots: 18,000 looks at a title slot and at the texture it views, a
  1789. /// lock each, some milliseconds of the thread that records the frame.
  1790. fn card_accounting(
  1791. heap: &crate::descriptor::Heap,
  1792. host: &crate::descriptor::host::HostHeap,
  1793. frame: u64,
  1794. room: bool,
  1795. ) {
  1796. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1797. if !*ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ACCOUNTING").is_some_and(|v| v == "1")) {
  1798. return;
  1799. }
  1800. // When the next line is due (0: none yet, the card has had room).
  1801. static NEXT: AtomicU64 = AtomicU64::new(0);
  1802. let now = crate::host::now_ms().max(1);
  1803. let next = NEXT.load(Ordering::Relaxed);
  1804. // (With levels on demand the card may never be without room: the
  1805. // lines then start with the first texture made that way.)
  1806. let by_level = crate::tiles::STATS[4].load(Ordering::Relaxed) > 0;
  1807. let due_now = if next == 0 { !room || by_level } else { now >= next };
  1808. if !due_now || NEXT.compare_exchange(next, now + 5000, Ordering::Relaxed, Ordering::Relaxed).is_err() {
  1809. return;
  1810. }
  1811. // Due slots; of them uploaded before; of them viewing nothing the
  1812. // title fills; and the textures (each once) whose host copy is
  1813. // alive, with their bytes on the card.
  1814. let mut due = [0u64; 5];
  1815. // Textures (each once) that never had a host copy, and ones whose
  1816. // host copy was let go: where their memory is, and its bytes.
  1817. let (mut never, mut gone) = (Vec::new(), Vec::new());
  1818. let mut seen = std::collections::BTreeSet::new();
  1819. for (index, uploaded) in host.texture_slots_all_due(frame) {
  1820. due[0] += 1;
  1821. due[1] += u64::from(uploaded);
  1822. let state = match heap.handle(index).and_then(crate::descriptor::view) {
  1823. Some(View::Placed(false, resource, desc)) if resource[0] != 1 => {
  1824. let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  1825. match crate::resource::placed_known(address, &resource) {
  1826. Some(texture) => crate::resource::copy_state(texture),
  1827. // No title texture was made for it: the pass never
  1828. // got as far as making one.
  1829. None => Some((0, crate::resource::placed_bytes(&resource).unwrap_or(0), address)),
  1830. }
  1831. }
  1832. Some(View::Shader(object, _)) if crate::resource::title_fills(object as This) => {
  1833. crate::resource::copy_state(object as This)
  1834. }
  1835. _ => None,
  1836. };
  1837. let Some((state, bytes, memory)) = state else {
  1838. due[2] += 1;
  1839. continue;
  1840. };
  1841. if !seen.insert(memory) {
  1842. continue;
  1843. }
  1844. match state {
  1845. 2 => {
  1846. due[3] += 1;
  1847. due[4] += bytes;
  1848. }
  1849. 1 => gone.push((memory, bytes)),
  1850. _ => never.push((memory, bytes)),
  1851. }
  1852. }
  1853. crate::resource::card_accounting(room, due, never, gone);
  1854. }
  1855. /// The texture side of [`State::heap_buffers`]: textures the title fills
  1856. /// itself (streamed pages, layout-library copies) whose views sit in the
  1857. /// view heap are created (placed textures have no host texture until
  1858. /// something reads them) and uploaded, as a table read would do, for
  1859. /// shaders that pick them by a computed index. Within a budget of bytes
  1860. /// per frame and in all; the rest waits for later lists and frames.
  1861. /// The most recently written slots first (`TextureQueue::due`); slots
  1862. /// draws read through tables are not in the queue.
  1863. /// shortcut: uploaded once, and again only when the title rewrites the
  1864. /// slot. A placed texture not all mapped yet is uploaded with what is
  1865. /// there and looked at again (1, 2, 4, ... frames later, at most about
  1866. /// a second): uploaded again when more of it is mapped. Pages mapped
  1867. /// in place of others, and contents changed with no descriptor write,
  1868. /// are missed (hook the page-mapping events for those).
  1869. /// `VICTORY_HEAP_TEXTURES=0` turns it off.
  1870. fn heap_textures(
  1871. &self,
  1872. list: &HostList,
  1873. heap: &crate::descriptor::Heap,
  1874. host: &crate::descriptor::host::HostHeap,
  1875. ) {
  1876. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1877. if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_TEXTURES").is_none_or(|v| v != "0")) {
  1878. return;
  1879. }
  1880. let memory = crate::host::host().and_then(|h| h.video_memory());
  1881. // `VICTORY_TEXTURE_STAGE_MB` sets it: a backlog of tens of thousands of
  1882. // textures (a scene's first minutes) then drains in fewer frames.
  1883. static PER_FRAME_MB: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
  1884. let asked = *PER_FRAME_MB.get_or_init(|| {
  1885. std::env::var("VICTORY_TEXTURE_STAGE_MB").ok().and_then(|v| v.trim().parse::<u64>().ok())
  1886. });
  1887. let per_frame = match asked {
  1888. Some(mb) => mb << 20,
  1889. None => staging_budget_per_frame(memory.map(|[budget, ..]| budget)),
  1890. };
  1891. static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
  1892. static SPENT: AtomicU64 = AtomicU64::new(0);
  1893. let frame = crate::frame::current();
  1894. if FRAME.swap(frame, Ordering::Relaxed) != frame {
  1895. SPENT.store(0, Ordering::Relaxed);
  1896. }
  1897. // No more of them are made while the card has no room
  1898. // (`resource::room`): by what is alive now, not by what was ever
  1899. // staged (4 GB in all, after which later textures stayed empty for
  1900. // the run). The ones nothing names any more are let go, which
  1901. // makes room again: so the slots are still looked at (the pass
  1902. // returned here, and a slot whose texture had been streamed out
  1903. // kept its host copy for as long as the card was full).
  1904. let mut room = crate::resource::room(memory);
  1905. // Bytes uploaded by this pass since the card was last asked
  1906. // whether it has room: asked again every 32 MiB (a pass may upload
  1907. // 192 MB and more, and one asking a pass let the queue run some
  1908. // 400 MB past its line while the world loaded: run 193).
  1909. let mut since_asked = 0u64;
  1910. if !room {
  1911. HEAP_TEXTURES_FULL.fetch_add(1, Ordering::Relaxed);
  1912. once!("textures picked by index: the card has no room for more; they wait");
  1913. }
  1914. let mut refused = 0;
  1915. // Room again: the slots held back while the card was full are due
  1916. // now (`full_card_pass`).
  1917. if room {
  1918. host.texture_slots_room(frame);
  1919. }
  1920. // Slots whose texture's memory the runtime mapped, unmapped or
  1921. // wrote since the last pass are due again.
  1922. host.texture_slots_remapped(frame);
  1923. host.texture_slots_short(frame);
  1924. // The slots of textures whose first level with memory (levels on
  1925. // demand), or whose host copy for one with more levels, changed since
  1926. // the last pass are made again from it; those whose new view's upload
  1927. // has run are made from that.
  1928. host.texture_views_remade();
  1929. host.texture_slots_flip();
  1930. // And with room, the textures whose upload left a held level
  1931. // without the card's memory are uploaded again.
  1932. if room {
  1933. host.texture_slots_waiting(frame);
  1934. }
  1935. let baking = crate::texture::BAKING.get();
  1936. let (mut due, census) = host.texture_slots_due(frame, if baking { 1 << 16 } else { 4096 });
  1937. // (Those that are due later after all that are due.)
  1938. let on_time = due.len();
  1939. if baking {
  1940. let known: std::collections::HashSet<u32> = due.iter().map(|&(index, _)| index).collect();
  1941. let (ahead, _) = host.texture_slots_due(frame + BAKE_AHEAD, 1 << 16);
  1942. due.extend(ahead.into_iter().filter(|(index, _)| !known.contains(index)));
  1943. }
  1944. HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed);
  1945. for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) {
  1946. count.store(now, Ordering::Relaxed);
  1947. }
  1948. // Where the card's memory is, and what the due slots would need
  1949. // (`VICTORY_CARD_ACCOUNTING=1`; a line when the card first has no
  1950. // room, and every five seconds after it).
  1951. Self::card_accounting(heap, host, frame, room);
  1952. // The frames in about four seconds, between 16 and 256: how long a
  1953. // slot with nothing to upload waits at most for its next look. In
  1954. // frames alone it was 120: four minutes at the opening cutscene's
  1955. // half a frame per second, while the title streams by the clock.
  1956. // (About a second before the runtime told of the memory it maps:
  1957. // the looks are now only for what that does not tell.)
  1958. static PASSED: AtomicU64 = AtomicU64::new(0);
  1959. let now = crate::host::now_ms();
  1960. let took = now.saturating_sub(PASSED.swap(now, Ordering::Relaxed)).max(1);
  1961. let most = (4000 / took).clamp(16, 256);
  1962. // What a table entry of a texture a shader samples says.
  1963. let sampled = UsedResource {
  1964. kind: ResourceType::Srv,
  1965. root: RootType::Table,
  1966. table_offset_dwords: 0,
  1967. lower_bound: 0,
  1968. stride: 0,
  1969. dwords: 8,
  1970. user_data: 0,
  1971. slot: 0,
  1972. };
  1973. // Also within a time per pass: the pass runs on a thread that
  1974. // records the frame, and making and staging 192 MB of textures took
  1975. // 1.6-2.2 s of each of the world's first twenty frames (run 20).
  1976. // The rest waits for the next frames, as it does past the bytes.
  1977. static SPAN_MS: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  1978. let span = std::time::Duration::from_millis(*SPAN_MS.get_or_init(|| {
  1979. std::env::var("VICTORY_TEXTURE_STAGE_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(250)
  1980. }));
  1981. // A backlog (a scene's first minutes: 22,000 slots due, 2-3 minutes of black
  1982. // surfaces at 192 MB a frame) gets three times the bytes and the time until it
  1983. // drains; `VICTORY_TEXTURE_CATCHUP=0` keeps the plain budget.
  1984. static CATCHUP: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1985. let catchup = *CATCHUP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_CATCHUP").is_none_or(|v| v != "0"));
  1986. let (per_frame, span) = if catchup && on_time >= 1024 { (per_frame * 3, span * 3) } else { (per_frame, span) };
  1987. // A run made early (`State::early_textures`) has a budget of its
  1988. // own: its bytes on top of what the frame has spent so far.
  1989. // (Not `most`: that is the longest wait between looks, used below.)
  1990. let (span, bytes_at_most) = match PASS_BUDGET.get() {
  1991. Some((ms, bytes)) => {
  1992. (std::time::Duration::from_millis(ms), SPENT.load(Ordering::Relaxed).saturating_add(bytes))
  1993. }
  1994. None => (span, per_frame),
  1995. };
  1996. let began = std::time::Instant::now();
  1997. for (index, write) in due {
  1998. if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span {
  1999. break;
  2000. }
  2001. // A placed texture whose memory is not mapped (not streamed in
  2002. // yet, or streamed out again: the heap keeps tens of thousands
  2003. // of such views) gets no host texture; looked at again soon (a
  2004. // title writes a texture's view before its pages are mapped,
  2005. // and the pass runs early in a frame). One of which some is
  2006. // mapped (a texture streaming in: its smaller mips lie at the
  2007. // start of its memory and arrive first) is uploaded with what
  2008. // is there, and again when more is. (It was uploaded again
  2009. // every 120 frames, changed or not; and asked by its first
  2010. // page alone, one whose first page is the one missing counted
  2011. // as not there.)
  2012. // A slot uploaded whole is looked at again a few times
  2013. // (`RECHECK_FRAMES`): the title writes a texture's view, and
  2014. // may fill the texture's memory itself only afterwards, with
  2015. // no descriptor write and nothing from the runtime to tell of
  2016. // it. The host copy then kept what the memory held at the
  2017. // first look for the rest of the run. The look reads 48 KiB;
  2018. // only a changed texture is uploaded again.
  2019. // `VICTORY_HEAP_RECHECK=0`: uploaded once, as before.
  2020. // One found changed by such a look is looked at in the next frame
  2021. // again: the textures left that change unnoticed are ones the
  2022. // title paints all the time through another view of their pages
  2023. // (all their blocks are shown at other addresses too), and each
  2024. // was shown four frames late, over and over.
  2025. let mut again_in = RECHECK_FRAMES[0];
  2026. if let Some((at, len, print, looks, uploaded)) = host.texture_slot_checked(index) {
  2027. if crate::texture::fingerprint(at, len) == print {
  2028. HEAP_TEXTURES_RECHECKED[0].fetch_add(1, Ordering::Relaxed);
  2029. match RECHECK_FRAMES.get(usize::from(looks) + 1) {
  2030. Some(wait) => {
  2031. host.texture_slot_recheck(index, write, frame + wait, (at, len), print, looks + 1, uploaded)
  2032. }
  2033. None => host.texture_slot_done(index, write, None),
  2034. }
  2035. continue;
  2036. }
  2037. if recheck_soon() {
  2038. again_in = 1;
  2039. }
  2040. let n = HEAP_TEXTURES_RECHECKED[1].fetch_add(1, Ordering::Relaxed);
  2041. if n < 200 || n.is_multiple_of(1000) {
  2042. // Whether its pages are the title's at other addresses
  2043. // too: what is written there is told of there alone.
  2044. let elsewhere = crate::inplace::shown_elsewhere(at as usize & !0xffff, (at + len) as usize);
  2045. let first = heap.handle(index).and_then(crate::descriptor::view).map_or(0, |view| match view {
  2046. View::Placed(false, _, desc) => crate::resource::first_mip(&desc),
  2047. _ => 0,
  2048. });
  2049. tracing::warn!(
  2050. first_level = first,
  2051. blocks_shown_elsewhere = elsewhere.len(),
  2052. slot = index,
  2053. address = format_args!("{at:#x}"),
  2054. bytes = len,
  2055. frames_after_upload = frame.saturating_sub(uploaded),
  2056. looks,
  2057. changed = n + 1,
  2058. "a texture picked by index changed after its upload with nothing to tell of it: uploaded again"
  2059. );
  2060. }
  2061. }
  2062. let mut partly = None;
  2063. if let Some(View::Placed(false, resource, desc)) = heap.handle(index).and_then(crate::descriptor::view) {
  2064. let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  2065. let first = crate::resource::first_mip(&desc);
  2066. let len = crate::resource::placed_bytes_from(&resource, first).unwrap_or(1);
  2067. let mapped = crate::texture::mapped_bytes(address as *const u8, len as usize);
  2068. if mapped == 0 {
  2069. HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed);
  2070. // Streamed out: what the slot showed is let go.
  2071. host.texture_slot_gone(index);
  2072. host.texture_slot_later(index, write, frame, most);
  2073. continue;
  2074. }
  2075. host.texture_slot_here(index);
  2076. if mapped < len {
  2077. if mapped <= host.texture_slot_mapped(index) {
  2078. HEAP_TEXTURES_PARTLY[0].fetch_add(1, Ordering::Relaxed);
  2079. host.texture_slot_later(index, write, frame, most);
  2080. continue;
  2081. }
  2082. if !crate::texture::committed(address as *const u8, 1) {
  2083. HEAP_TEXTURES_PARTLY[2].fetch_add(1, Ordering::Relaxed);
  2084. }
  2085. partly = Some(mapped);
  2086. }
  2087. }
  2088. // A texture object the host renders to or writes holds the
  2089. // host's own contents: nothing to bring up to date, and this
  2090. // pass is no use of it (its host copy is made when something
  2091. // uses it, and its slots then: `descriptor::make_waiting`).
  2092. if let Some(View::Shader(object, _)) = heap.handle(index).and_then(crate::descriptor::view)
  2093. && crate::resource::buffer_bytes(object as This).is_none()
  2094. && !crate::resource::title_fills(object as This)
  2095. {
  2096. host.texture_slot_done(index, write, None);
  2097. continue;
  2098. }
  2099. // From here on a host texture is made: not without room. The
  2100. // slot stays due.
  2101. // Not so a slot already made from this very view: its host
  2102. // texture exists, and uploading it again takes none of the
  2103. // card's memory. It was refused all the same, so a texture the
  2104. // title filled after its first upload kept its empty host copy
  2105. // from the moment the card reached the line, which is the first
  2106. // world frame in eight launches of nine: the same slots were
  2107. // found changed again at every pass and never uploaded (run
  2108. // 179: 33,000 such findings), and the main character's face
  2109. // had its colour only in the launches that entered the world
  2110. // under the line. `VICTORY_REUPLOAD_WHEN_FULL=0`: refused, as
  2111. // before.
  2112. if !room {
  2113. let has_its_texture = reupload_when_full()
  2114. && heap.handle(index).is_some_and(|handle| host.texture_slot_made_from(index, handle));
  2115. if !has_its_texture {
  2116. refused += 1;
  2117. if full_card_pass() {
  2118. // Held back for the frames of about four seconds
  2119. // (`most`), or until the card has room; the pass
  2120. // goes on, within a count that bounds one pass.
  2121. host.texture_slot_held(index, write, frame + most);
  2122. if refused > 1024 {
  2123. break;
  2124. }
  2125. } else if refused > 256 {
  2126. break;
  2127. }
  2128. continue;
  2129. }
  2130. let n = HEAP_TEXTURES_REUPLOADED_FULL.fetch_add(1, Ordering::Relaxed) + 1;
  2131. if n == 1 || n.is_multiple_of(500) {
  2132. tracing::info!(
  2133. so_far = n,
  2134. slot = index,
  2135. "a texture already on the card is brought up to date although the card has no room for new ones"
  2136. );
  2137. }
  2138. }
  2139. // A slot that shows the texture by an earlier view of it (one
  2140. // from another level) goes on doing so until the upload of what
  2141. // the new one shows has run.
  2142. let shows_other = !baking
  2143. && crate::resource::held_only()
  2144. && heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle));
  2145. let view = heap.handle(index).and_then(|handle| {
  2146. if shows_other { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) }
  2147. });
  2148. let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture);
  2149. let resource = match placed.as_ref().or(view.as_ref()) {
  2150. Some(&View::Shader(resource, _)) => resource as This,
  2151. _ => {
  2152. host.texture_slot_done(index, write, None);
  2153. continue;
  2154. }
  2155. };
  2156. let title_fills = crate::resource::host_resource(resource).is_some_and(crate::texture::title_written);
  2157. if !title_fills {
  2158. // a render target, a depth or unordered access texture: the host's own
  2159. host.texture_slot_done(index, write, None);
  2160. continue;
  2161. }
  2162. // A texture that has a staging buffer now is one draws read
  2163. // through a table: they upload it, and check it at every
  2164. // submission that samples it.
  2165. let tabled = crate::texture::is_staged(resource);
  2166. // The host copy holds these very bytes: nothing to upload.
  2167. let first = match (&placed, &view) {
  2168. (Some(_), Some(View::Placed(_, _, desc))) => crate::resource::first_mip(desc),
  2169. _ => 0,
  2170. };
  2171. let same = !tabled && crate::texture::unchanged(resource, first);
  2172. if same {
  2173. HEAP_TEXTURES_SAME.fetch_add(1, Ordering::Relaxed);
  2174. if shows_other && let Some(handle) = heap.handle(index) {
  2175. let _ = host.mirror(index, handle, true);
  2176. }
  2177. let again = partly.map(|mapped| (frame + 1, mapped));
  2178. let memory = if again.is_none() && heap_recheck() { crate::texture::title_span(resource, first) } else { None };
  2179. match memory {
  2180. Some((at, len)) => {
  2181. let print = crate::texture::fingerprint(at, len);
  2182. host.texture_slot_recheck(index, write, frame + again_in, (at, len), print, 0, frame);
  2183. }
  2184. None => host.texture_slot_done(index, write, again),
  2185. }
  2186. continue;
  2187. }
  2188. if let Some(view) = &view {
  2189. readable(list, sampled.kind, view);
  2190. }
  2191. if shows_other && let Some(handle) = heap.handle(index) {
  2192. host.texture_slot_flip(list, index, handle);
  2193. }
  2194. // A texture view the host refuses removes the device: name it.
  2195. static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  2196. if !GONE.load(Ordering::Relaxed)
  2197. && let Some(why) = crate::descriptor::host::device_removed()
  2198. {
  2199. GONE.store(true, Ordering::Relaxed);
  2200. let text: String = format!("{view:?}").chars().take(300).collect();
  2201. tracing::error!(why, slot = index, "the host device went while textures picked by index were made ready; last: {text}");
  2202. crate::host::log_removal_context();
  2203. return;
  2204. }
  2205. let (bytes, whole) = crate::texture::staged(resource).unwrap_or((0, true));
  2206. // Not all of it there: looked at again next frame, and from
  2207. // then on as a slot with nothing new (a placed texture: until
  2208. // more of it is mapped; a texture object at an address the
  2209. // title mapped: again in 120 frames, as before).
  2210. let again = match partly {
  2211. Some(mapped) => Some((frame + 1, mapped)),
  2212. None => (!whole).then_some((frame + 120, 0)),
  2213. };
  2214. if again.is_some() {
  2215. HEAP_TEXTURES_PARTLY[1].fetch_add(1, Ordering::Relaxed);
  2216. }
  2217. if tabled {
  2218. // Nothing was staged here, so nothing is counted or spent,
  2219. // and the staging buffer stays: taking it away made the
  2220. // next draw that reads the texture through a table stage,
  2221. // detile and upload all of it once more.
  2222. HEAP_TEXTURES_TABLED.fetch_add(1, Ordering::Relaxed);
  2223. host.texture_slot_done(index, write, again);
  2224. continue;
  2225. }
  2226. // Uploaded: the list holds the staging buffer until it has run;
  2227. // a table read, or the next look at a texture not all mapped
  2228. // yet, makes it anew. (Kept for those until now: every partly
  2229. // streamed texture of the heap held a staging buffer of its full
  2230. // size for good.)
  2231. let memory = if again.is_none() && heap_recheck() {
  2232. crate::texture::staged_memory(resource)
  2233. } else {
  2234. None
  2235. };
  2236. crate::texture::unstage(resource);
  2237. SPENT.fetch_add(bytes, Ordering::Relaxed);
  2238. since_asked += bytes;
  2239. if room && since_asked >= 32 << 20 {
  2240. since_asked = 0;
  2241. room = crate::resource::room(crate::host::host().and_then(|h| h.video_memory()));
  2242. }
  2243. HEAP_TEXTURE_BYTES.fetch_add(bytes, Ordering::Relaxed);
  2244. HEAP_TEXTURES.fetch_add(1, Ordering::Relaxed);
  2245. match memory {
  2246. // Whole and uploaded: looked at again (see above).
  2247. Some((at, len)) => {
  2248. let print = crate::texture::fingerprint(at, len);
  2249. host.texture_slot_recheck(index, write, frame + again_in, (at, len), print, 0, frame);
  2250. }
  2251. None => host.texture_slot_done(index, write, again),
  2252. }
  2253. }
  2254. }
  2255. /// For the frame listing, after a dropped dispatch's line: its group
  2256. /// counts and the compute root arguments it was recorded with (root
  2257. /// constants as hex dwords, root views with the title buffer they
  2258. /// point into). A program that does not translate has no bindings to
  2259. /// list; these say which memory it would have read and written (the
  2260. /// ray-tracing structure builder passes its buffers this way).
  2261. #[cfg(feature = "diagnostics")]
  2262. fn list_dropped_roots(&self, groups: [u32; 3]) {
  2263. crate::capture::op(0, || {
  2264. use std::fmt::Write;
  2265. let [x, y, z] = groups;
  2266. let mut text = format!(" its roots ({x}x{y}x{z}):");
  2267. for (slot, root) in self.compute.iter().enumerate() {
  2268. match root {
  2269. Root::None => {}
  2270. Root::Table(a) => {
  2271. let _ = write!(text, " {slot}=table {a:#x}");
  2272. }
  2273. Root::Constants(v) => {
  2274. let _ = write!(text, " {slot}=constants {:x?}", &v[..v.len().min(48)]);
  2275. }
  2276. Root::View(a) => {
  2277. let _ = write!(text, " {slot}=view {a:#x}");
  2278. match crate::shadow::extent(*a) {
  2279. Some((start, len)) => {
  2280. let _ = write!(text, " in buffer {start:#x}+{len:#x}");
  2281. }
  2282. None => text.push_str(" in no buffer"),
  2283. }
  2284. }
  2285. }
  2286. }
  2287. text
  2288. });
  2289. }
  2290. /// Runs a dispatch on the host.
  2291. pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) {
  2292. // It may write the arguments a window holds clamped.
  2293. self.window = None;
  2294. #[cfg(feature = "diagnostics")]
  2295. if crate::pipeline::is_skipped(self.pipeline as This) {
  2296. DROPPED.fetch_add(1, Ordering::Relaxed);
  2297. crate::pipeline::note_drop(self.pipeline as This);
  2298. return;
  2299. }
  2300. // The ray-tracing structure builder's stages run all or none.
  2301. if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() {
  2302. DROPPED.fetch_add(1, Ordering::Relaxed);
  2303. #[cfg(feature = "diagnostics")]
  2304. {
  2305. crate::pipeline::note_why("a stage of the ray-tracing structure builder, which is off".to_owned());
  2306. self.list_dropped_roots([x, y, z]);
  2307. }
  2308. return;
  2309. }
  2310. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  2311. once!(
  2312. pipeline = format_args!("{:#x}", self.pipeline),
  2313. "a dispatch without a host pipeline dropped"
  2314. );
  2315. DROPPED.fetch_add(1, Ordering::Relaxed);
  2316. #[cfg(feature = "diagnostics")]
  2317. {
  2318. crate::pipeline::note_drop(self.pipeline as This);
  2319. self.list_dropped_roots([x, y, z]);
  2320. }
  2321. return;
  2322. };
  2323. if !p.compute {
  2324. once!("a dispatch with a graphics pipeline");
  2325. return;
  2326. }
  2327. if !self.bind(list, p, true) {
  2328. DROPPED.fetch_add(1, Ordering::Relaxed);
  2329. // A stage of the structure builder that cannot be bound is a
  2330. // dropped stage: the others stop too.
  2331. if crate::pipeline::is_builder(self.pipeline as This) {
  2332. crate::pipeline::builder_off("one of its dispatches could not be bound");
  2333. }
  2334. return;
  2335. }
  2336. #[cfg(feature = "diagnostics")]
  2337. list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true));
  2338. // SAFETY: an open list with everything set.
  2339. unsafe { list.list.Dispatch(x, y, z) };
  2340. self.buffers_written();
  2341. DISPATCHED.fetch_add(1, Ordering::Relaxed);
  2342. }
  2343. /// What a draw or dispatch runs, for the device-removed report
  2344. /// (diagnostics): the pipeline, then per stage the user data it gets
  2345. /// (with the view at that heap index, if one is), the host addresses
  2346. /// of its root views and the views its tables name.
  2347. #[cfg(feature = "diagnostics")]
  2348. fn op_text(&self, kind: String, compute: bool) -> String {
  2349. use std::fmt::Write;
  2350. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  2351. return kind;
  2352. };
  2353. let mut text = format!("{kind} {}", p.name);
  2354. // What it draws into (a dispatch writes through its views below).
  2355. if !compute {
  2356. let described = |t: usize| {
  2357. crate::resource::host_made(t as This).map(|r| {
  2358. // SAFETY: a live resource.
  2359. let d = unsafe { r.GetDesc() };
  2360. format!("{t:#x} {}x{} f{}", d.Width, d.Height, d.Format.0)
  2361. })
  2362. };
  2363. let targets: Vec<String> = self.targets.iter().filter_map(|&t| described(t)).collect();
  2364. let _ = write!(text, " targets {targets:?} depth {:?} state [{}]", described(self.depth), p.state);
  2365. // The title's scissor and viewport at this draw (the first of
  2366. // each): the title draws what it sees through a
  2367. // portal (a window, from inside a room) under the portal's
  2368. // rectangle, and the listing did not say which draws those are.
  2369. if let Some(r) = self.scissors.first() {
  2370. let _ = write!(text, " scissor [{} {} {} {}]", r.left, r.top, r.right, r.bottom);
  2371. }
  2372. if let Some(v) = self.viewports.first() {
  2373. let _ = write!(
  2374. text,
  2375. " viewport [{} {} {} {} depth {}..{}]",
  2376. v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth
  2377. );
  2378. }
  2379. }
  2380. let views = (self.heaps[0] != 0)
  2381. .then(|| crate::descriptor::heap(self.heaps[0] as This).host())
  2382. .flatten();
  2383. for stage in &p.stages {
  2384. let t = stage.translated();
  2385. let _ = write!(text, " | {}:", stage.shader.hash);
  2386. for u in &t.host.user_data {
  2387. let v = match u.root {
  2388. RootType::Other(kind) => self.host_word(compute, kind, u.slot, u.dword, None),
  2389. _ => self.user_value(compute, u.slot, u.root, u.dword),
  2390. };
  2391. let _ = write!(text, " u{}={v:#x}", u.index);
  2392. let index = if u.root == RootType::Table { v / 32 } else { v };
  2393. if let Some(slot) = views.and_then(|h| h.describe_slot(index)) {
  2394. let _ = write!(text, " [heap {index}: {slot}]");
  2395. }
  2396. }
  2397. for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs).chain(&stage.root_uavs) {
  2398. if let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) {
  2399. let host = crate::shadow::find(*address, 1)
  2400. .map(|s| (s.gpu(*address), s.left(*address)));
  2401. let _ = write!(text, " root{slot}={address:#x} host {host:#x?}");
  2402. }
  2403. }
  2404. }
  2405. let _ = write!(text, " tables {:?}", self.reads(compute));
  2406. if !compute && !list_slots().is_empty() {
  2407. text.push_str(&self.slots_text());
  2408. }
  2409. text
  2410. }
  2411. /// For the frame listing, after a draw whose shader `VICTORY_LIST_SLOTS`
  2412. /// names: the heap slots it will pick textures from by index, and what
  2413. /// the title and the host hold there (one `~slot` line each), with the
  2414. /// words they were read from (`~raw` lines, to decode offline what is
  2415. /// not decoded here).
  2416. ///
  2417. /// Where the slots are, for the title's character shaders
  2418. /// (`PS_DeferredPedTexturedNC`, from their native code): in the small
  2419. /// buffers and constants of the draw's own table (every word of those
  2420. /// that names a texture view gets a line); in the material record, at
  2421. /// the byte offset the draw's constants (table 1, dword 56) hold at
  2422. /// 0x1c, of the buffer at table 0, dword 160; and in the record at the
  2423. /// byte offset the second root constant holds of the buffer at table 0,
  2424. /// dword 688. A word that is a small number by chance and names a
  2425. /// texture gets a line too.
  2426. #[cfg(feature = "diagnostics")]
  2427. fn slots_text(&self) -> String {
  2428. use std::fmt::Write;
  2429. const MATERIALS: u32 = 160;
  2430. const GLOBAL: u32 = 688;
  2431. const DRAW_CONSTANTS: u32 = 56;
  2432. let wanted = list_slots();
  2433. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  2434. return String::new();
  2435. };
  2436. let Some(stage) = p.stages.iter().find(|s| wanted.iter().any(|w| s.shader.hash.starts_with(w.as_str())))
  2437. else {
  2438. return String::new();
  2439. };
  2440. let Some(heap) = self
  2441. .heaps
  2442. .iter()
  2443. .filter(|&&h| h != 0)
  2444. .map(|&h| crate::descriptor::heap(h as This))
  2445. .find(|h| !h.samplers())
  2446. else {
  2447. return String::new();
  2448. };
  2449. let t = stage.translated();
  2450. let mut text = String::new();
  2451. let entry = |slot: u8, dwords: u32| -> Option<View> {
  2452. let Some(Root::Table(table)) = self.roots_ref(false).get(usize::from(slot)) else {
  2453. return None;
  2454. };
  2455. crate::descriptor::view(table + u64::from(dwords) * 4)
  2456. };
  2457. let mut material = None;
  2458. for u in t.used.iter().filter(|u| u.root == RootType::Table && u.kind != ResourceType::Sampler) {
  2459. let label = format!("s{}+{}", u.slot, u.table_offset_dwords);
  2460. let Some(view) = entry(u.slot, u.table_offset_dwords) else {
  2461. let _ = write!(text, "\n ~table {label} no view");
  2462. continue;
  2463. };
  2464. let range = match &view {
  2465. View::Constant(address, size) => Some((*address, u64::from(*size))),
  2466. other => crate::descriptor::host::buffer_range(other),
  2467. };
  2468. match range {
  2469. // A small buffer or constants: its words.
  2470. Some((address, len)) if len <= 2048 => {
  2471. Self::slot_words(&mut text, heap, &label, address, len as usize);
  2472. if u.slot == 1 && u.table_offset_dwords == DRAW_CONSTANTS && len >= 0x20 {
  2473. let mut word = [0u8; 4];
  2474. if crate::host::read_into((address + 0x1c) as *const u8, &mut word) {
  2475. material = Some(u32::from_le_bytes(word));
  2476. }
  2477. }
  2478. }
  2479. Some(_) => {}
  2480. // A texture read through the table: the title slot it sits in.
  2481. None => {
  2482. let Some(Root::Table(table)) = self.roots_ref(false).get(usize::from(u.slot)) else {
  2483. continue;
  2484. };
  2485. match heap.index(table + u64::from(u.table_offset_dwords) * 4) {
  2486. Some(index) => text.push_str(&Self::slot_line(heap, &format!("table:{label}"), 0, index)),
  2487. None => {
  2488. let _ = write!(text, "\n ~table {label} title=[{}]", view_state(Some(&view)));
  2489. }
  2490. }
  2491. }
  2492. }
  2493. }
  2494. let uses = |slot: u8, dwords: u32| {
  2495. t.used.iter().any(|u| u.root == RootType::Table && u.slot == slot && u.table_offset_dwords == dwords)
  2496. };
  2497. if let Some(at) = material
  2498. && uses(0, MATERIALS)
  2499. && let Some((base, len)) = entry(0, MATERIALS).as_ref().and_then(crate::descriptor::host::buffer_range)
  2500. {
  2501. let at = u64::from(at);
  2502. let _ = write!(text, "\n ~material record at {at:#x} of the buffer at {base:#x} bytes {len}");
  2503. if at + 64 <= len {
  2504. Self::slot_words(&mut text, heap, "M", base + at, 64);
  2505. }
  2506. if at + 1936 + 512 <= len {
  2507. Self::slot_words(&mut text, heap, "M+1936", base + at + 1936, 512);
  2508. }
  2509. }
  2510. if uses(0, GLOBAL)
  2511. && let Some(slot) = t.used.iter().find(|u| u.root == RootType::Constants).map(|u| u.slot)
  2512. && let Some(Root::Constants(words)) = self.roots_ref(false).get(usize::from(slot))
  2513. && let Some(&at) = words.get(1)
  2514. && let Some((base, len)) = entry(0, GLOBAL).as_ref().and_then(crate::descriptor::host::buffer_range)
  2515. {
  2516. let at = u64::from(at);
  2517. let _ = write!(text, "\n ~root constants {words:08x?}: record at {at:#x} of the buffer at {base:#x} bytes {len}");
  2518. if at + 64 <= len {
  2519. Self::slot_words(&mut text, heap, "G", base + at, 64);
  2520. }
  2521. }
  2522. text
  2523. }
  2524. /// Up to 512 bytes of title memory at `address` as hex words (a `~raw`
  2525. /// line), and a `~slot` line for every word of them that names a
  2526. /// texture view in `heap`.
  2527. #[cfg(feature = "diagnostics")]
  2528. fn slot_words(text: &mut String, heap: &crate::descriptor::Heap, label: &str, address: u64, len: usize) {
  2529. use std::fmt::Write;
  2530. let mut bytes = vec![0u8; len.min(512) & !3];
  2531. if bytes.is_empty() || !crate::host::read_into(address as *const u8, &mut bytes) {
  2532. let _ = write!(text, "\n ~raw {label} at {address:#x} bytes {len}: unreadable");
  2533. return;
  2534. }
  2535. let words: Vec<u32> =
  2536. bytes.chunks_exact(4).map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])).collect();
  2537. let _ = write!(text, "\n ~raw {label} at {address:#x} bytes {len}:");
  2538. for w in &words {
  2539. let _ = write!(text, " {w:08x}");
  2540. }
  2541. for (i, &index) in words.iter().enumerate() {
  2542. let names = index != 0
  2543. && heap
  2544. .handle(index)
  2545. .and_then(crate::descriptor::view)
  2546. .as_ref()
  2547. .is_some_and(crate::descriptor::host::is_texture_view);
  2548. if names {
  2549. text.push_str(&Self::slot_line(heap, label, i * 4, index));
  2550. }
  2551. }
  2552. }
  2553. /// One `~slot` line: where the slot number was read (`from`, byte
  2554. /// `at`), what the title's heap holds in slot `index` with the state
  2555. /// of that texture ([`view_state`]), what the host slot was made from,
  2556. /// and what the queue of textures picked by index knows of it.
  2557. #[cfg(feature = "diagnostics")]
  2558. fn slot_line(heap: &crate::descriptor::Heap, from: &str, at: usize, index: u32) -> String {
  2559. let title = heap.handle(index).and_then(crate::descriptor::view);
  2560. let host: String = heap
  2561. .host()
  2562. .and_then(|h| h.describe_slot(index))
  2563. .unwrap_or_else(|| "none".into())
  2564. .chars()
  2565. .take(90)
  2566. .collect();
  2567. let queue = match heap.host() {
  2568. Some(h) => h.texture_slot_state(index, crate::frame::current()),
  2569. None => "no host heap".into(),
  2570. };
  2571. format!(
  2572. "\n ~slot from={from}+{at:#x} slot={index} title=[{}] host=[{host}] queue=[{queue}]",
  2573. view_state(title.as_ref())
  2574. )
  2575. }
  2576. /// A mesh draw under `VICTORY_MESH_TEST=scissor` rasterises one pixel:
  2577. /// the scissors before it (`on`), the title's after it.
  2578. fn mesh_scissor(&self, list: &HostList, on: bool) {
  2579. if mesh_test() != 2 {
  2580. return;
  2581. }
  2582. if on {
  2583. let one = RECT { left: 0, top: 0, right: 1, bottom: 1 };
  2584. crate::draw::scissors(list, &vec![one; self.scissors.len().max(1)]);
  2585. } else if !self.scissors.is_empty() {
  2586. crate::draw::scissors(list, &self.scissors);
  2587. }
  2588. }
  2589. /// Runs a mesh dispatch of `x` groups on the host (the title's mesh
  2590. /// programs are one-dimensional).
  2591. pub(crate) fn dispatch_mesh(&mut self, list: &HostList, x: u32) {
  2592. self.window = None;
  2593. #[cfg(feature = "diagnostics")]
  2594. self.trace("mesh", x, 0);
  2595. let ran = mesh_test() != 1
  2596. && mesh_kept(self.pipeline)
  2597. && self.prepare_for(list, false, true)
  2598. && match list.list.cast::<ID3D12GraphicsCommandList6>() {
  2599. Ok(l6) => {
  2600. #[cfg(feature = "diagnostics")]
  2601. list.note_op(|| self.op_text(format!("mesh {x}"), false));
  2602. self.mesh_scissor(list, true);
  2603. // SAFETY: an open list with everything set.
  2604. unsafe { l6.DispatchMesh(x, 1, 1) };
  2605. self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
  2606. self.mesh_scissor(list, false);
  2607. DRAWN.fetch_add(1, Ordering::Relaxed);
  2608. true
  2609. }
  2610. Err(_) => false,
  2611. };
  2612. if !ran {
  2613. DROPPED.fetch_add(1, Ordering::Relaxed);
  2614. #[cfg(feature = "diagnostics")]
  2615. dropped(self.pipeline);
  2616. }
  2617. }
  2618. /// The walls trace (`crate::host::walls_trace`): one log line per
  2619. /// frame with the draws of its main pass (four or more colour targets)
  2620. /// by scissor rectangle, and how often each of the title's culling
  2621. /// programs was dispatched. The title clips what it draws
  2622. /// through a window or door to that opening's rectangle while it holds
  2623. /// the camera to be in a room (run 182, frame 1529: 1,386 draws under
  2624. /// `531 0 1789 1337`); in a launch without the room's walls the same
  2625. /// shot has no such rectangle (run 187, frame 1414). The line shows
  2626. /// the frame in which that changes.
  2627. fn walls_census(&self, p: &HostPipeline, compute: bool) {
  2628. const CULL: [(&str, &str); 9] = [
  2629. ("55679a0547649d0b", "tree"),
  2630. ("89d08e561897d4e5", "tree_imposter"),
  2631. ("9209777e8face9dd", "grass"),
  2632. ("17af15c4015cb4b6", "prop"),
  2633. ("fdd56d97a806bcca", "prop_nocull"),
  2634. ("42f717f1b4d18e94", "simple"),
  2635. ("1c4b3c0547e3e6fa", "slod"),
  2636. ("9146291b38ea9ce1", "meshlet_args"),
  2637. ("42683eebec081520", "depth_pyramid_cpu_occlusion"),
  2638. ];
  2639. type Census = (u64, std::collections::BTreeMap<[i32; 4], u32>, [u32; 9]);
  2640. static CENSUS: std::sync::Mutex<Census> =
  2641. std::sync::Mutex::new((u64::MAX, std::collections::BTreeMap::new(), [0; 9]));
  2642. let frame = crate::frame::current();
  2643. let mut census = CENSUS.lock().unwrap_or_else(|e| e.into_inner());
  2644. if census.0 != frame {
  2645. let draws: u32 = census.1.values().sum();
  2646. if draws > 0 {
  2647. let mut rects: Vec<([i32; 4], u32)> = census.1.iter().map(|(r, n)| (*r, *n)).collect();
  2648. rects.sort_unstable_by(|a, b| b.1.cmp(&a.1));
  2649. let scissors: Vec<String> = rects
  2650. .iter()
  2651. .take(5)
  2652. .map(|(r, n)| format!("{} {} {} {} x{n}", r[0], r[1], r[2], r[3]))
  2653. .collect();
  2654. let counts = census.2;
  2655. let culling: Vec<String> = CULL
  2656. .iter()
  2657. .zip(counts)
  2658. .filter(|(_, n)| *n > 0)
  2659. .map(|(c, n)| format!("{}={n}", c.1))
  2660. .collect();
  2661. tracing::info!(
  2662. frame = census.0,
  2663. main_pass_draws = draws,
  2664. rectangles = rects.len(),
  2665. scissors = ?scissors,
  2666. culling = ?culling,
  2667. "walls trace: the frame's main pass by scissor rectangle, and its culling dispatches"
  2668. );
  2669. }
  2670. census.0 = frame;
  2671. census.1.clear();
  2672. census.2 = [0; 9];
  2673. }
  2674. if compute {
  2675. for (i, c) in CULL.iter().enumerate() {
  2676. if p.stages.iter().any(|s| s.shader.hash.as_str() == c.0) {
  2677. census.2[i] += 1;
  2678. }
  2679. }
  2680. } else if self.targets.iter().filter(|&&t| t != 0).count() >= 4 {
  2681. let r = self.scissors.first().map_or([0; 4], |r| [r.left, r.top, r.right, r.bottom]);
  2682. *census.1.entry(r).or_insert(0) += 1;
  2683. }
  2684. }
  2685. fn roots_ref(&self, compute: bool) -> &Vec<Root> {
  2686. if compute {
  2687. &self.compute
  2688. } else {
  2689. &self.graphics
  2690. }
  2691. }
  2692. fn table_entry(&self, list: &HostList, u: &UsedResource, compute: bool) {
  2693. let Some(Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else {
  2694. return;
  2695. };
  2696. let handle = table + u64::from(u.table_offset_dwords) * 4;
  2697. let Some(heap) = self.heap_of(handle) else {
  2698. return;
  2699. };
  2700. let (Some(host), Some(index)) = (heap.host(), heap.index(handle)) else {
  2701. return;
  2702. };
  2703. if let Some(view) = host.mirror(index, handle, true) {
  2704. readable(list, u.kind, &view);
  2705. // Up to date by this draw: not the texture pass's to make.
  2706. if crate::descriptor::host::is_texture_view(&view) {
  2707. host.texture_slot_tabled(index, true);
  2708. } else {
  2709. host.slot_tabled(index);
  2710. }
  2711. }
  2712. }
  2713. /// The descriptors a shader reads through tables. Tables holding a
  2714. /// constant buffer are made afresh for the draw in dynamic slots, with
  2715. /// the constant data copied to upload memory when the list is
  2716. /// submitted: the host wants constant buffers 256-byte aligned, the
  2717. /// console only 16. Returns those tables' new byte offsets by root
  2718. /// parameter; the other tables' slots are made from the title's.
  2719. ///
  2720. /// Within a list, the same table holding the same descriptors is made
  2721. /// once: its constant data is copied at submission either way, and the
  2722. /// big tables the world binds would otherwise take hundreds of slots per
  2723. /// draw, wrapping the dynamic slots onto lists not yet submitted.
  2724. pub(crate) fn tables(
  2725. &mut self,
  2726. list: &HostList,
  2727. used: &[UsedResource],
  2728. indexed: &[RootIndexedView],
  2729. compute: bool,
  2730. ) -> Vec<(u8, u32)> {
  2731. let tables = |u: &&UsedResource| u.root == RootType::Table;
  2732. let mut fresh: Vec<u8> = used
  2733. .iter()
  2734. .filter(tables)
  2735. .filter(|u| u.kind == ResourceType::Cbv)
  2736. .map(|u| u.slot)
  2737. .collect();
  2738. // Tables reaching past a host heap smaller than the title's (the
  2739. // host's limit, 1,000,000 views on NVIDIA) are made afresh too: the
  2740. // title's slots there have no host slot of their own.
  2741. for u in used.iter().filter(tables) {
  2742. if fresh.contains(&u.slot) {
  2743. continue;
  2744. }
  2745. let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else {
  2746. continue;
  2747. };
  2748. let end = table + u64::from(u.table_offset_dwords) * 4;
  2749. let Some(heap) = self.heap_of(table) else {
  2750. continue;
  2751. };
  2752. let (Some(host), Some(index)) = (heap.host(), heap.index(end)) else {
  2753. continue;
  2754. };
  2755. if index >= host.count() {
  2756. fresh.push(u.slot);
  2757. }
  2758. }
  2759. fresh.sort_unstable();
  2760. fresh.dedup();
  2761. for u in used.iter().filter(tables) {
  2762. if !fresh.contains(&u.slot) {
  2763. self.table_entry(list, u, compute);
  2764. }
  2765. }
  2766. let mut made = Vec::new();
  2767. for slot in fresh {
  2768. let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else {
  2769. continue;
  2770. };
  2771. let entries: Vec<&UsedResource> = used
  2772. .iter()
  2773. .filter(tables)
  2774. .filter(|u| u.slot == slot)
  2775. .collect();
  2776. let Some(heap) = self.heap_of(table) else {
  2777. continue;
  2778. };
  2779. if heap.samplers() || (table - heap.start) % 32 != 0 {
  2780. continue;
  2781. }
  2782. let Some(host) = heap.host() else {
  2783. continue;
  2784. };
  2785. let mut selected: Vec<u32> = indexed
  2786. .iter()
  2787. .filter(|index| index.table_slot == slot)
  2788. .map(|index| {
  2789. let constant = self.user_value(
  2790. compute,
  2791. index.constant_slot,
  2792. RootType::Constants,
  2793. index.constant_dword,
  2794. );
  2795. // The shader adds i32 byte offsets and shifts by 5.
  2796. index.byte_offset.wrapping_add(constant << index.shift) / 32
  2797. })
  2798. .collect();
  2799. selected.sort_unstable();
  2800. selected.dedup();
  2801. let n = entries
  2802. .iter()
  2803. .map(|u| u.table_offset_dwords / 8)
  2804. .chain(selected.last().copied())
  2805. .max()
  2806. .unwrap_or(0)
  2807. + 1;
  2808. let last = table.checked_add(u64::from(n - 1) * 32);
  2809. if n > crate::descriptor::host::DYNAMIC
  2810. || last.and_then(|handle| heap.index(handle)).is_none()
  2811. {
  2812. once!(slot, n, "fresh descriptor table exceeds the available span");
  2813. continue;
  2814. }
  2815. // The table and what its entries hold (record words).
  2816. let key = {
  2817. use std::hash::{Hash, Hasher};
  2818. let mut h = std::collections::hash_map::DefaultHasher::new();
  2819. for k in 0..n {
  2820. let at = table + u64::from(k) * 32;
  2821. // SAFETY: a descriptor slot in title memory.
  2822. unsafe { (at as *const [u32; 3]).read_unaligned() }.hash(&mut h);
  2823. }
  2824. (table, n, h.finish())
  2825. };
  2826. if let Some(&first) = self.fresh_tables.get(&key) {
  2827. for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) {
  2828. let handle = table + u64::from(u.table_offset_dwords) * 4;
  2829. if let Some(view) = crate::descriptor::view(handle) {
  2830. readable(list, u.kind, &view);
  2831. }
  2832. }
  2833. for k in selected {
  2834. if entries.iter().any(|u| u.table_offset_dwords / 8 == k) {
  2835. continue;
  2836. }
  2837. let handle = table + u64::from(k) * 32;
  2838. if let Some(view) = crate::descriptor::view(handle)
  2839. && let Some(kind) = view_kind(&view)
  2840. {
  2841. readable(list, kind, &view);
  2842. }
  2843. }
  2844. made.push((slot, first * 32));
  2845. continue;
  2846. }
  2847. let Some(first) = host.dynamic(n) else {
  2848. // No room: the draw must not run with the title's own
  2849. // offsets (slots never made for it); `bind` drops it.
  2850. made.push((slot, u32::MAX));
  2851. continue;
  2852. };
  2853. self.fresh_tables.insert(key, first);
  2854. self.dynamic
  2855. .push((std::ptr::from_ref(heap) as usize, first, n));
  2856. // The title's own slots of this table: what the draw reads of
  2857. // them it brings up to date here, in the dynamic slots.
  2858. let title_first = heap.index(table).filter(|first| first + n <= host.count());
  2859. // They are such a table's, whatever they hold. (Of a big one,
  2860. // which may lie over slots shaders pick by index, only the ones
  2861. // the shader names.)
  2862. if let Some(title) = title_first {
  2863. for k in (0..n).filter(|&k| n <= 64 || entries.iter().any(|u| u.table_offset_dwords / 8 == k)) {
  2864. host.slot_tabled(title + k);
  2865. }
  2866. }
  2867. // The whole range: a shader may index past the entries its
  2868. // used-resource list names (descriptor arrays).
  2869. for k in 0..n {
  2870. let index = first + k;
  2871. let used = entries.iter().find(|u| u.table_offset_dwords / 8 == k);
  2872. match crate::descriptor::view(table + u64::from(k) * 32) {
  2873. Some(View::Constant(address, size)) => {
  2874. let Some((buffer, gpu, to)) = list.scratch_held(u64::from(size)) else {
  2875. host.make_null(index);
  2876. continue;
  2877. };
  2878. let slot = (std::ptr::from_ref(heap) as usize, index);
  2879. list.defer_constants(to, address as *const u8, size as usize, slot);
  2880. host.constant_at(index, &buffer, gpu, size);
  2881. }
  2882. Some(view) => {
  2883. host.make_at(index, &view);
  2884. let kind = used.map(|u| u.kind).or_else(|| {
  2885. selected.binary_search(&k).ok().and_then(|_| view_kind(&view))
  2886. });
  2887. if let Some(kind) = kind {
  2888. readable(list, kind, &view);
  2889. }
  2890. // The title's slot is a table's: out of the queue
  2891. // of textures picked by index if the draw read it
  2892. // (its texture is up to date now), and made in
  2893. // place as the texture pass would have made it,
  2894. // for a shader that picks it by index all the same.
  2895. if let Some(title) = title_first
  2896. && crate::descriptor::host::is_texture_view(&view)
  2897. {
  2898. host.texture_slot_tabled(title + k, kind.is_some());
  2899. if kind.is_some() {
  2900. host.mirror(title + k, table + u64::from(k) * 32, true);
  2901. }
  2902. }
  2903. }
  2904. None => {
  2905. host.make_null(index);
  2906. if used.is_some() {
  2907. once!(slot, "a table entry without a view");
  2908. }
  2909. }
  2910. }
  2911. }
  2912. made.push((slot, first * 32));
  2913. }
  2914. made
  2915. }
  2916. /// The first draws, at debug level: what they bind and read
  2917. /// (diagnostics builds).
  2918. #[cfg(feature = "diagnostics")]
  2919. fn trace(&self, kind: &str, count: u32, first: u32) {
  2920. static TRACED: AtomicU64 = AtomicU64::new(0);
  2921. if !tracing::enabled!(tracing::Level::DEBUG) {
  2922. return;
  2923. }
  2924. let listed = crate::capture::listed(crate::queue::presented() + 1);
  2925. let logged = listed || TRACED.fetch_add(1, Ordering::Relaxed) < 64;
  2926. let targets: Vec<String> = self
  2927. .targets
  2928. .iter()
  2929. .filter_map(|&t| crate::resource::host_made(t as This))
  2930. .map(|t| {
  2931. // SAFETY: a live resource.
  2932. let d = unsafe { t.GetDesc() };
  2933. format!("{}x{} f{}", d.Width, d.Height, d.Format.0)
  2934. })
  2935. .collect();
  2936. let v = self.vertex[0];
  2937. let line = format!(
  2938. "{kind} {count} from {first} topology {} pipeline {:#x} targets {targets:?} vb {:#x}+{} stride {} reads {:?}",
  2939. self.topology,
  2940. self.pipeline,
  2941. v.address,
  2942. v.size,
  2943. v.stride,
  2944. self.reads(false)
  2945. );
  2946. if logged {
  2947. tracing::debug!("draw {line}");
  2948. }
  2949. let mut frame = FRAME.lock().unwrap_or_else(|e| e.into_inner());
  2950. if frame.len() < 256 {
  2951. frame.push(line);
  2952. }
  2953. }
  2954. /// What a draw's shaders read, one line per used resource (diagnostics
  2955. /// builds).
  2956. #[cfg(feature = "diagnostics")]
  2957. fn reads(&self, compute: bool) -> Vec<String> {
  2958. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  2959. return vec!["no host pipeline".into()];
  2960. };
  2961. let mut out = Vec::new();
  2962. for stage in &p.stages {
  2963. let t = stage.translated();
  2964. for u in &t.used {
  2965. let what = match (u.root, self.roots_ref(compute).get(usize::from(u.slot))) {
  2966. (RootType::Table, Some(Root::Table(table))) => {
  2967. let handle = table + u64::from(u.table_offset_dwords) * 4;
  2968. describe(crate::descriptor::view(handle).as_ref())
  2969. }
  2970. (root, _) => format!("{root:?}"),
  2971. };
  2972. out.push(format!(
  2973. "{} {:?} s{}+{}: {what}",
  2974. stage.shader.hash, u.kind, u.slot, u.table_offset_dwords
  2975. ));
  2976. }
  2977. }
  2978. out
  2979. }
  2980. pub(crate) fn draw(
  2981. &mut self,
  2982. list: &HostList,
  2983. vertices: u32,
  2984. instances: u32,
  2985. first: u32,
  2986. first_instance: u32,
  2987. ) {
  2988. self.window = None;
  2989. #[cfg(feature = "diagnostics")]
  2990. self.trace("draw", vertices, first);
  2991. let ready = self.prepare(list, false);
  2992. // A pipeline with the rectangle geometry stage draws the title's
  2993. // vertices as they are; any other gets its rectangles expanded.
  2994. let rects = self.topology == RECTANGLES && !self.completes_rects();
  2995. let ran = ready && (!rects || self.rectangles(list, vertices, first));
  2996. if ran {
  2997. // Rectangles were expanded into their own vertex buffers.
  2998. let (count, from) = if rects {
  2999. (vertices / 3 * 6, 0)
  3000. } else {
  3001. (vertices, first)
  3002. };
  3003. #[cfg(feature = "diagnostics")]
  3004. list.note_op(|| self.op_text(format!("draw {count}x{instances}"), false));
  3005. // SAFETY: an open list with everything set.
  3006. unsafe {
  3007. list.list
  3008. .DrawInstanced(count, instances, from, first_instance)
  3009. };
  3010. self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
  3011. DRAWN.fetch_add(1, Ordering::Relaxed);
  3012. }
  3013. if !ran {
  3014. DROPPED.fetch_add(1, Ordering::Relaxed);
  3015. #[cfg(feature = "diagnostics")]
  3016. dropped(self.pipeline);
  3017. }
  3018. }
  3019. /// Whether the bound pipeline completes rectangles itself, in the
  3020. /// geometry stage rectangle pipelines get (`HostPipeline::rects`).
  3021. fn completes_rects(&self) -> bool {
  3022. crate::pipeline::host_pipeline(self.pipeline as This).is_some_and(|p| p.rects)
  3023. }
  3024. /// Binds vertex buffers holding the rectangles of vertices `first..first
  3025. /// + count` as triangles, made when the list is submitted.
  3026. fn rectangles(&self, list: &HostList, count: u32, first: u32) -> bool {
  3027. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  3028. return false;
  3029. };
  3030. let rects = u64::from(count / 3);
  3031. for slot in 0..32 {
  3032. let elements: Vec<(u32, u32)> = p
  3033. .inputs
  3034. .iter()
  3035. .filter(|e| e.slot == slot && !e.per_instance)
  3036. .map(|e| (e.offset, e.format))
  3037. .collect();
  3038. if elements.is_empty() {
  3039. continue;
  3040. }
  3041. let v = self.vertex[slot as usize];
  3042. let stride = u64::from(v.stride);
  3043. let from = v.address + u64::from(first) * stride;
  3044. if v.address == 0
  3045. || stride == 0
  3046. || u64::from(first + count) * stride > u64::from(v.size)
  3047. || crate::shadow::find(from, rects * 3 * stride).is_none()
  3048. {
  3049. once!(slot, "rectangle vertices outside their buffer");
  3050. return false;
  3051. }
  3052. let Some((gpu, to)) = list.scratch(rects * 6 * stride) else {
  3053. return false;
  3054. };
  3055. let (from, to, stride) = (from as usize, to as usize, stride as usize);
  3056. let n = rects as usize;
  3057. list.defer_host_read(from, n * 3 * stride, move || {
  3058. // The vertices are read in place, at submission: no change
  3059. // of mapping under the read (see
  3060. // `crate::watch::title_memory_reading`).
  3061. let _mapped = crate::watch::title_memory_reading();
  3062. // SAFETY: the vertices lie in a title buffer (checked when
  3063. // recorded) and the scratch memory is the list's.
  3064. let (src, dst) = unsafe {
  3065. (
  3066. std::slice::from_raw_parts(from as *const u8, n * 3 * stride),
  3067. std::slice::from_raw_parts_mut(to as *mut u8, n * 6 * stride),
  3068. )
  3069. };
  3070. crate::primitive::expand_rects(src, dst, stride, &elements);
  3071. });
  3072. let view = D3D12_VERTEX_BUFFER_VIEW {
  3073. BufferLocation: gpu,
  3074. SizeInBytes: (rects * 6 * stride as u64) as u32,
  3075. StrideInBytes: v.stride,
  3076. };
  3077. // SAFETY: an open list; the view names live scratch memory.
  3078. unsafe { list.list.IASetVertexBuffers(slot, Some(&[view])) };
  3079. }
  3080. true
  3081. }
  3082. pub(crate) fn draw_indexed(
  3083. &mut self,
  3084. list: &HostList,
  3085. indices: u32,
  3086. instances: u32,
  3087. first: u32,
  3088. base: i32,
  3089. first_instance: u32,
  3090. ) {
  3091. self.window = None;
  3092. #[cfg(feature = "diagnostics")]
  3093. self.trace("indexed", indices, first);
  3094. // Indexed rectangles are drawn by the rectangle geometry stage
  3095. // alone (nothing expands them on the CPU).
  3096. let lost = self.topology == RECTANGLES && !self.completes_rects();
  3097. if lost {
  3098. once!("indexed rectangles not drawn");
  3099. }
  3100. let ran = !lost && self.prepare(list, true);
  3101. if ran {
  3102. #[cfg(feature = "diagnostics")]
  3103. list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false));
  3104. // SAFETY: an open list with everything set.
  3105. unsafe {
  3106. list.list
  3107. .DrawIndexedInstanced(indices, instances, first, base, first_instance)
  3108. };
  3109. self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
  3110. DRAWN.fetch_add(1, Ordering::Relaxed);
  3111. }
  3112. if !ran {
  3113. DROPPED.fetch_add(1, Ordering::Relaxed);
  3114. #[cfg(feature = "diagnostics")]
  3115. dropped(self.pipeline);
  3116. }
  3117. }
  3118. }
  3119. impl State {
  3120. /// Shaders that can write buffers were recorded: arguments may be others
  3121. /// from here on.
  3122. fn buffers_written(&mut self) {
  3123. match &mut self.batch {
  3124. Some(batch) if batches() == 2 => batch.wrote = true,
  3125. batch => *batch = None,
  3126. }
  3127. }
  3128. /// A draw with the pipeline `p` was recorded (as [`State::buffers_written`]
  3129. /// if its shaders can store to buffers).
  3130. fn drew(&mut self, p: Option<&HostPipeline>) {
  3131. if p.is_none_or(|p| p.stages.iter().any(|stage| stage.translated().stores)) {
  3132. self.batch = None;
  3133. }
  3134. }
  3135. /// A buffer was copied to: what was clamped of it ahead is clamped anew.
  3136. pub(crate) fn copied(&mut self) {
  3137. self.window = None;
  3138. self.batch = None;
  3139. }
  3140. /// The title waits for earlier work (a barrier or a pipeline sync).
  3141. pub(crate) fn synced(&mut self) {
  3142. if self.batch.as_ref().is_some_and(|b| b.wrote) {
  3143. self.batch = None;
  3144. }
  3145. }
  3146. /// Where the clamped record of `kind` at `arguments` of the copy `args`
  3147. /// is, from the open batch or a new one ([`batches`]). `None` if it
  3148. /// cannot be clamped in one.
  3149. fn batched(
  3150. &mut self,
  3151. list: &HostList,
  3152. args: &std::sync::Arc<crate::shadow::Shadow>,
  3153. arguments: u64,
  3154. kind: u32,
  3155. ) -> Option<(ID3D12Resource, u64)> {
  3156. const BATCH_USE: usize = usize::MAX - 0x78;
  3157. const DISPATCH: u32 = 2;
  3158. // Another host list, or this one after its reset ([`windows`]).
  3159. if list.first_use(BATCH_USE) {
  3160. self.batch = None;
  3161. }
  3162. // A draw after dispatches waits for them.
  3163. if kind != DISPATCH {
  3164. self.synced();
  3165. }
  3166. let (id, offset) = (args.id(), args.offset(arguments));
  3167. if let Some(b) = &mut self.batch
  3168. && let Some(at) = b.table.place(id, offset, kind)
  3169. {
  3170. return Some((b.scratch.clone(), at));
  3171. }
  3172. self.batch = None;
  3173. let (mut table, scratch) = crate::indirect::open_batch(list, (id, &args.buffer), &argument_copies(args))?;
  3174. self.host_pipeline = 0;
  3175. self.host_roots[1] = 0;
  3176. let at = table.place(id, offset, kind)?;
  3177. self.batch = Some(Batch { table, scratch: scratch.clone(), wrote: false });
  3178. Some((scratch, at))
  3179. }
  3180. /// Indirect execution of a one-argument signature of `kind` (PC
  3181. /// numbering: 0 draw, 1 indexed draw, 2 dispatch, 10 mesh dispatch) with
  3182. /// records `stride` bytes apart at title address `arguments`, and the
  3183. /// record count at `count` if the title gives one: the GPU reads them
  3184. /// from the buffer's host copy, where earlier dispatches may have
  3185. /// written them. False if it cannot run on the host.
  3186. pub(crate) fn execute_indirect(
  3187. &mut self,
  3188. list: &HostList,
  3189. (kind, stride, max): (u32, u32, u32),
  3190. arguments: u64,
  3191. count: Option<u64>,
  3192. ) -> bool {
  3193. // Skip before the argument clamp can mutate the indirect buffer.
  3194. #[cfg(feature = "diagnostics")]
  3195. if crate::pipeline::is_skipped(self.pipeline as This) {
  3196. crate::pipeline::note_drop(self.pipeline as This);
  3197. return false;
  3198. }
  3199. if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() {
  3200. return false;
  3201. }
  3202. const DRAW: u32 = 0;
  3203. const INDEXED: u32 = 1;
  3204. const DISPATCH: u32 = 2;
  3205. const MESH: u32 = 10;
  3206. #[cfg(feature = "diagnostics")]
  3207. let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}"));
  3208. #[cfg(not(feature = "diagnostics"))]
  3209. let why = |_: &str| {};
  3210. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  3211. #[cfg(feature = "diagnostics")]
  3212. crate::pipeline::note_drop(self.pipeline as This);
  3213. return false;
  3214. };
  3215. // Indirect rectangles (the title's tiled lighting, 256
  3216. // indirect draws a frame, makes their corners from the vertex
  3217. // number) are completed by the pipeline's geometry stage: the
  3218. // arguments stay the title's, three vertices a rectangle. They
  3219. // cannot be expanded on the CPU, which does not know their count.
  3220. // shortcut: in a pipeline without that stage, a rectangle with no
  3221. // per-vertex inputs is drawn as its first triangle (three vertices,
  3222. // half of it), and one with vertex buffers is not drawn.
  3223. let made_rects = !p.rects
  3224. && kind == DRAW
  3225. && self.topology == RECTANGLES
  3226. && !p.inputs.iter().any(|e| !e.per_instance);
  3227. if made_rects {
  3228. once!("indirect rectangles without vertex inputs drawn as their first triangle");
  3229. }
  3230. let matches_kind = match kind {
  3231. DRAW | INDEXED => {
  3232. (self.topology != RECTANGLES || made_rects || p.rects) && !p.compute && !p.mesh
  3233. }
  3234. MESH => !p.compute && p.mesh,
  3235. DISPATCH => p.compute,
  3236. _ => false,
  3237. };
  3238. if !matches_kind {
  3239. why(&format!(
  3240. "pipeline mismatch (compute {}, mesh {}, topology {})",
  3241. p.compute, p.mesh, self.topology
  3242. ));
  3243. return false;
  3244. }
  3245. let len = u64::from(stride) * u64::from(max.max(1));
  3246. let Some(args) = crate::shadow::find_any(arguments, len) else {
  3247. why("arguments outside title buffers");
  3248. return false;
  3249. };
  3250. let counter = match count {
  3251. Some(at) => match crate::shadow::find_any(at, 4) {
  3252. Some(s) => Some((s, at)),
  3253. None => {
  3254. why("count outside title buffers");
  3255. return false;
  3256. }
  3257. },
  3258. None => None,
  3259. };
  3260. let Some(signature) = matches!(kind, DRAW | INDEXED | DISPATCH | MESH)
  3261. .then(|| host_signature(kind, stride))
  3262. .flatten()
  3263. else {
  3264. why("no host signature");
  3265. return false;
  3266. };
  3267. if kind == MESH && (mesh_test() == 1 || !mesh_kept(self.pipeline)) {
  3268. why("mesh draws are switched off (VICTORY_MESH_TEST=skip)");
  3269. return false;
  3270. }
  3271. // One record without a count: clamped in a batch (`batches`).
  3272. let batch = if batches() > 0 && max == 1 && count.is_none() {
  3273. args.refresh(list, arguments, len);
  3274. self.batched(list, &args, arguments, kind)
  3275. } else {
  3276. None
  3277. };
  3278. if batch.is_some() {
  3279. self.window = None;
  3280. }
  3281. // A window of records clamped in one pass (`windows`): for single
  3282. // records without a count buffer, drawn by shaders that store to no
  3283. // buffer. Anything else ends the window: it uses the scratch buffer
  3284. // or may write the arguments.
  3285. const WINDOW_USE: usize = usize::MAX - 0x77;
  3286. let offset = args.offset(arguments);
  3287. let windowed = windows()
  3288. && kind != DISPATCH
  3289. && max == 1
  3290. && count.is_none()
  3291. && !p.stages.iter().any(|stage| stage.translated().stores);
  3292. // Another host list (a new one after a cut, or this one after its
  3293. // reset) has another scratch buffer, or this one's with old bytes.
  3294. if !windowed || list.first_use(WINDOW_USE) {
  3295. self.window = None;
  3296. }
  3297. let same = |w: &Window| w.copy == args.id() && w.kind == kind && w.stride == stride;
  3298. let hit = self
  3299. .window
  3300. .as_ref()
  3301. .filter(|w| same(w) && offset >= w.base)
  3302. .filter(|w| (offset - w.base) % u64::from(w.step) == 0 && (offset - w.base) / u64::from(w.step) < u64::from(w.records))
  3303. .map(|w| (w.scratch.clone(), offset - w.base));
  3304. let (bounded, at) = match batch.or(hit) {
  3305. Some(hit) => hit,
  3306. None => {
  3307. // A record a short step after the last window's last one
  3308. // (the same step as that window's, if it had one): the
  3309. // title walks the buffer, so the ones that step apart
  3310. // after it are clamped with it.
  3311. let (step, records) = match &self.window {
  3312. Some(w) if windowed && same(w) => {
  3313. let last = w.base + u64::from(w.records - 1) * u64::from(w.step);
  3314. let step = offset.saturating_sub(last);
  3315. let walks = step >= u64::from(stride)
  3316. && step <= 256
  3317. && step % 4 == 0
  3318. && (w.records == 1 || step == u64::from(w.step));
  3319. if walks {
  3320. let fit = (args.left(arguments) / step).min(WINDOW_MOST) as u32;
  3321. (step as u32, (if w.records == 1 { 16 } else { w.records * 2 }).min(fit).max(1))
  3322. } else {
  3323. (stride, max)
  3324. }
  3325. }
  3326. _ => (stride, max),
  3327. };
  3328. args.refresh(list, arguments, len.max(u64::from(step) * u64::from(records)));
  3329. if let Some((s, at)) = &counter {
  3330. s.refresh(list, *at, 4);
  3331. }
  3332. // Bounded first: the clamp binds a compute pipeline of its
  3333. // own and copies clamped active records into a scratch
  3334. // buffer at offset 0.
  3335. let count_arg = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at)));
  3336. // More than the record asked for: a window clamped ahead,
  3337. // whose unfilled slots must not spend the list's budget.
  3338. let bounded = if windowed && records > 1 {
  3339. crate::indirect::bound_ahead(list, (&args.buffer, offset), (kind, step, records))
  3340. } else {
  3341. crate::indirect::bound(list, (&args.buffer, offset), count_arg, (kind, step, records))
  3342. };
  3343. let Some(bounded) = bounded else {
  3344. self.window = None;
  3345. why("not bounded (no clamp, or arguments not 4-byte aligned)");
  3346. return false;
  3347. };
  3348. self.host_pipeline = 0;
  3349. self.host_roots[1] = 0;
  3350. self.window = windowed.then(|| Window {
  3351. copy: args.id(),
  3352. kind,
  3353. stride,
  3354. step,
  3355. base: offset,
  3356. records,
  3357. scratch: bounded.clone(),
  3358. });
  3359. (bounded, 0)
  3360. }
  3361. };
  3362. let ran = match kind {
  3363. DRAW | INDEXED => self.prepare(list, kind == INDEXED),
  3364. MESH => self.prepare_for(list, false, true),
  3365. DISPATCH => self.bind(list, p, true),
  3366. _ => false,
  3367. };
  3368. if !ran {
  3369. why("prepare failed");
  3370. return false;
  3371. }
  3372. #[cfg(feature = "diagnostics")]
  3373. list.note_op(|| {
  3374. self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH)
  3375. });
  3376. #[cfg(feature = "diagnostics")]
  3377. list.ran_indirect(p.pso.as_raw() as usize, &p.name, kind, max, &self.user);
  3378. if kind == MESH {
  3379. self.mesh_scissor(list, true);
  3380. }
  3381. // SAFETY: an open list with everything set; the scratch buffer and
  3382. // host copies are kept alive by the list, and the signature is cached.
  3383. unsafe {
  3384. list.list.ExecuteIndirect(
  3385. &signature,
  3386. max,
  3387. &bounded,
  3388. at,
  3389. counter.as_ref().map(|(s, _)| &s.buffer),
  3390. counter.as_ref().map_or(0, |(s, at)| s.offset(*at)),
  3391. )
  3392. };
  3393. if kind == MESH {
  3394. self.mesh_scissor(list, false);
  3395. }
  3396. if kind == DISPATCH {
  3397. self.buffers_written();
  3398. } else {
  3399. self.drew(Some(p));
  3400. }
  3401. // The scratch buffer stays readable as arguments: the next draw of
  3402. // the window reads it with no barrier, and the next clamp moves it
  3403. // back (`crate::indirect`).
  3404. if kind == DISPATCH {
  3405. DISPATCHED.fetch_add(1, Ordering::Relaxed);
  3406. } else {
  3407. DRAWN.fetch_add(1, Ordering::Relaxed);
  3408. }
  3409. true
  3410. }
  3411. }
  3412. /// The host command signature for one argument of `kind` with records
  3413. /// `stride` bytes apart (no root arguments, so no root signature), made
  3414. /// once.
  3415. fn host_signature(kind: u32, stride: u32) -> Option<ID3D12CommandSignature> {
  3416. static MADE: std::sync::Mutex<Vec<((u32, u32), ID3D12CommandSignature)>> =
  3417. std::sync::Mutex::new(Vec::new());
  3418. let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
  3419. if let Some((_, s)) = made.iter().find(|(k, _)| *k == (kind, stride)) {
  3420. return Some(s.clone());
  3421. }
  3422. let argument = D3D12_INDIRECT_ARGUMENT_DESC {
  3423. Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32),
  3424. ..Default::default()
  3425. };
  3426. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  3427. ByteStride: stride,
  3428. NumArgumentDescs: 1,
  3429. pArgumentDescs: &argument,
  3430. NodeMask: 0,
  3431. };
  3432. let mut signature: Option<ID3D12CommandSignature> = None;
  3433. // SAFETY: a description of one argument; no root arguments.
  3434. let result = unsafe {
  3435. crate::host::host()?.device.CreateCommandSignature(
  3436. &desc,
  3437. None::<&ID3D12RootSignature>,
  3438. &mut signature,
  3439. )
  3440. };
  3441. if let Err(e) = result {
  3442. once!(error = %e, kind, stride, "host command signature refused");
  3443. return None;
  3444. }
  3445. let signature = signature?;
  3446. made.push(((kind, stride), signature.clone()));
  3447. Some(signature)
  3448. }
  3449. /// Gets what a shader reads or writes through a view ready: buffer data
  3450. /// copied, textures moved to the state they need.
  3451. fn view_kind(view: &View) -> Option<ResourceType> {
  3452. match view {
  3453. View::Shader(..) | View::Placed(false, ..) => Some(ResourceType::Srv),
  3454. View::Unordered(..) | View::Placed(true, ..) => Some(ResourceType::Uav),
  3455. _ => None,
  3456. }
  3457. }
  3458. /// The host state a depth view needs of its texture: the read state if the
  3459. /// view writes no plane the format has (the title's read-only flags), else
  3460. /// the write state.
  3461. /// shortcut: whole textures have one state, so a view that writes one of
  3462. /// two planes counts as writing.
  3463. fn depth_state(texture: &ID3D12Resource, desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>) -> u32 {
  3464. // D16_UNORM and D32_FLOAT: depth formats without a stencil plane.
  3465. const ONE_PLANE: [i32; 2] = [55, 40];
  3466. let Some(desc) = desc else {
  3467. return DEPTH_WRITE;
  3468. };
  3469. let format = if desc.Format.0 == 0 {
  3470. // SAFETY: a live texture; a view without a format has its own.
  3471. unsafe { texture.GetDesc() }.Format.0
  3472. } else {
  3473. desc.Format.0
  3474. };
  3475. let mut needed = D3D12_DSV_FLAG_READ_ONLY_DEPTH.0;
  3476. if !ONE_PLANE.contains(&format) {
  3477. needed |= D3D12_DSV_FLAG_READ_ONLY_STENCIL.0;
  3478. }
  3479. if desc.Flags.0 & needed == needed {
  3480. DEPTH_READ
  3481. } else {
  3482. DEPTH_WRITE
  3483. }
  3484. }
  3485. fn readable(list: &HostList, kind: ResourceType, view: &View) {
  3486. const UNORDERED_ACCESS: u32 = 0x8;
  3487. let placed = crate::descriptor::host::placed_texture(view);
  3488. let view = placed.as_ref().unwrap_or(view);
  3489. // Buffer views read title memory: their range is copied at submission;
  3490. // what shaders write through unordered access goes back to it after.
  3491. if let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(view) {
  3492. shadow.refresh(list, address, len);
  3493. if kind == ResourceType::Uav {
  3494. // A shader that cannot store to buffers leaves the range as
  3495. // the title has it: nothing to find afterwards.
  3496. if STORES.get() || !write_skip() {
  3497. #[cfg(feature = "diagnostics")]
  3498. crate::host::wide_write(address, len, 0);
  3499. shadow.gpu_writes(list, address, len);
  3500. } else {
  3501. #[cfg(feature = "diagnostics")]
  3502. {
  3503. crate::copystat::add(crate::copystat::C::GpuWritesLeftOut, 1);
  3504. crate::copystat::add(crate::copystat::C::GpuWritesLeftOutBytes, len);
  3505. }
  3506. }
  3507. }
  3508. }
  3509. match (view, kind) {
  3510. (View::Shader(resource, _), ResourceType::Srv) => {
  3511. // A view the title placed, in another format, in the memory of
  3512. // a texture the host writes: that texture's texels, copied on
  3513. // the host (title memory does not have them).
  3514. let aliased = crate::resource::alias_of(*resource as This)
  3515. .is_some_and(|source| crate::texture::alias(list, *resource as This, source));
  3516. if !aliased
  3517. && let Some(t) = crate::resource::host_resource(*resource as This)
  3518. && crate::texture::title_written(t)
  3519. {
  3520. // Of a texture the title placed, the levels the view shows.
  3521. let first = match (&placed, view) {
  3522. (Some(_), View::Shader(_, Some(desc))) => crate::resource::first_mip(desc),
  3523. _ => 0,
  3524. };
  3525. crate::texture::upload_from(list, *resource as This, first);
  3526. }
  3527. // A depth texture shaders also write: what they wrote, first.
  3528. list.twin_use(*resource as This, false, false);
  3529. // The depth target the draw only tests is read in both ways at
  3530. // once: both read states, which its preparation asks for too.
  3531. let (tested, _) = TESTED_DEPTH.get();
  3532. let state = if tested != 0 && tested == *resource {
  3533. TESTED_DEPTH.set((tested, true));
  3534. DEPTH_READ | SHADER_RESOURCE
  3535. } else {
  3536. SHADER_RESOURCE
  3537. };
  3538. crate::list::ensure_state(list, *resource as This, state);
  3539. #[cfg(feature = "diagnostics")]
  3540. if let Some(t) = crate::resource::host_resource(*resource as This) {
  3541. // SAFETY: a live resource.
  3542. let d = unsafe { t.GetDesc() };
  3543. if d.Flags.0 & 7 == 0 {
  3544. tracing::debug!(
  3545. resource = format_args!("{resource:#x}"),
  3546. ?d,
  3547. "a shader reads a texture the title fills"
  3548. );
  3549. }
  3550. }
  3551. }
  3552. (View::Unordered(resource, _, _), ResourceType::Uav) => {
  3553. #[cfg(feature = "diagnostics")]
  3554. crate::capture::note_target(*resource as This);
  3555. // Unordered access to a depth texture is its colour twin's.
  3556. if !list.twin_use(*resource as This, true, true) {
  3557. crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS);
  3558. }
  3559. }
  3560. _ => {}
  3561. }
  3562. }
  3563. /// The pixel shaders whose draws get their slots listed
  3564. /// ([`State::slots_text`]): `VICTORY_LIST_SLOTS`, hash prefixes separated
  3565. /// by commas. None by default.
  3566. #[cfg(feature = "diagnostics")]
  3567. fn list_slots() -> &'static [String] {
  3568. static LIST: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
  3569. LIST.get_or_init(|| {
  3570. std::env::var("VICTORY_LIST_SLOTS")
  3571. .unwrap_or_default()
  3572. .split(',')
  3573. .map(|s| s.trim().to_ascii_lowercase())
  3574. .filter(|s| !s.is_empty())
  3575. .collect()
  3576. })
  3577. }
  3578. /// A fingerprint of the 4 KiB of title memory at `at` (FNV-1a, 64 bits; of
  3579. /// 4 KiB of zeros it is always the same value, which `slots.py` knows), or
  3580. /// "unreadable".
  3581. #[cfg(feature = "diagnostics")]
  3582. fn print_4k(at: u64) -> String {
  3583. let mut bytes = [0u8; 4096];
  3584. if at == 0 || !crate::host::read_into(at as *const u8, &mut bytes) {
  3585. return "unreadable".into();
  3586. }
  3587. let mut hash = 0xcbf2_9ce4_8422_2325_u64;
  3588. for b in bytes {
  3589. hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
  3590. }
  3591. format!("{hash:016x}")
  3592. }
  3593. /// The `bytes` of title memory at `at`: how many are mapped, and the
  3594. /// fingerprints of the first and the last 4 KiB (a texture's smallest
  3595. /// levels lie first, its largest last).
  3596. #[cfg(feature = "diagnostics")]
  3597. fn memory_state(at: u64, bytes: u64) -> String {
  3598. let mapped = crate::texture::mapped_bytes(at as *const u8, bytes as usize);
  3599. let last = at + bytes.saturating_sub(4096);
  3600. format!("memory={at:#x} mapped={mapped}/{bytes} first4k={} last4k={}", print_4k(at), print_4k(last))
  3601. }
  3602. /// Title texture `this` for the frame listing: its size, whether it has a
  3603. /// host copy (not made here), its staging buffer's state, whether the host
  3604. /// copied into it, and its memory ([`memory_state`]).
  3605. #[cfg(feature = "diagnostics")]
  3606. fn texture_state(this: This) -> String {
  3607. let Some((at, desc)) = crate::resource::texture_memory(this) else {
  3608. return "not a texture".into();
  3609. };
  3610. // SAFETY: 56 bytes in the description's layout.
  3611. let words = unsafe { std::ptr::from_ref(&desc).cast::<[u32; 14]>().read_unaligned() };
  3612. let bytes = crate::resource::placed_bytes(&words).unwrap_or(0);
  3613. let staged = match crate::texture::staged_state(this) {
  3614. Some((uploaded, dirty)) => format!("staged=yes uploaded={uploaded} dirty={dirty}"),
  3615. None => "staged=no".into(),
  3616. };
  3617. format!(
  3618. "{}x{} f{} levels={} host_copy={} {staged} host_written={} title_fills={} {}",
  3619. u64::from(words[4]) | u64::from(words[5]) << 32,
  3620. words[6],
  3621. words[8],
  3622. words[7] >> 16,
  3623. crate::resource::host_made(this).is_some(),
  3624. crate::texture::host_wrote(this as usize),
  3625. crate::resource::title_fills(this),
  3626. memory_state(at as u64, bytes)
  3627. )
  3628. }
  3629. /// A view of the title's heap for the frame listing: a texture with its
  3630. /// state ([`texture_state`]; a placed one that has no resource yet with
  3631. /// its memory alone), anything else in a few words.
  3632. #[cfg(feature = "diagnostics")]
  3633. fn view_state(view: Option<&View>) -> String {
  3634. match view {
  3635. None => "no view".into(),
  3636. Some(View::Placed(false, r, d)) if r[0] != 1 => {
  3637. let address = u64::from(d[10]) | u64::from(d[11]) << 32;
  3638. let state = match crate::resource::texture_at_made(address, r) {
  3639. Some(this) => texture_state(this),
  3640. None => format!(
  3641. "{}x{} f{} levels={} resource=none {}",
  3642. u64::from(r[4]) | u64::from(r[5]) << 32,
  3643. r[6],
  3644. r[8],
  3645. r[7] >> 16,
  3646. memory_state(address, crate::resource::placed_bytes(r).unwrap_or(0))
  3647. ),
  3648. };
  3649. // (Last, so that readers of the older lines still find
  3650. // theirs: the level the view starts at, and how many it shows.)
  3651. format!("placed texture view_format={} {state} view_levels={}+{}", d[0], d[4], d[5] as i32)
  3652. }
  3653. Some(View::Shader(r, d)) if crate::resource::texture_memory(*r as This).is_some() => {
  3654. format!(
  3655. "texture object {r:#x} view_format={} {} view_levels={}",
  3656. d.as_ref().map_or(0, |d| d[0]),
  3657. texture_state(*r as This),
  3658. d.as_ref().map_or("all".to_owned(), |d| format!("{}+{}", d[4], d[5] as i32))
  3659. )
  3660. }
  3661. Some(v) => format!("{v:?}").chars().take(80).collect(),
  3662. }
  3663. }
  3664. /// A view in a few words (diagnostics builds).
  3665. #[cfg(feature = "diagnostics")]
  3666. fn describe(view: Option<&View>) -> String {
  3667. let texture = |r: This| {
  3668. crate::resource::host_made(r).map(|t| {
  3669. // SAFETY: a live resource.
  3670. let d = unsafe { t.GetDesc() };
  3671. format!("{}x{} f{} flags {:#x} of {r:?}", d.Width, d.Height, d.Format.0, d.Flags.0)
  3672. })
  3673. };
  3674. match view {
  3675. None => "no view".into(),
  3676. Some(v @ View::Shader(r, _)) => texture(*r as This)
  3677. .unwrap_or_else(|| format!("buffer {:?}", crate::descriptor::host::buffer_range(v))),
  3678. Some(v @ View::Unordered(r, ..)) => match texture(*r as This) {
  3679. Some(t) => format!("uav texture {t}"),
  3680. None => format!(
  3681. "uav resource {r:#x} buffer {:?}",
  3682. crate::descriptor::host::buffer_range(v)
  3683. ),
  3684. },
  3685. Some(View::Placed(u, r, d)) => format!(
  3686. "placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}",
  3687. r[0],
  3688. u64::from(r[4]) | u64::from(r[5]) << 32,
  3689. r[6],
  3690. r[8],
  3691. r[11],
  3692. u64::from(d[10]) | u64::from(d[11]) << 32
  3693. ),
  3694. // The first four values, as a colour rectangle's constants are.
  3695. Some(View::Constant(address, size))
  3696. if *size >= 16 && crate::texture::committed(*address as *const u8, 16) =>
  3697. {
  3698. // SAFETY: 16 committed bytes of title memory.
  3699. let v = unsafe { (*address as *const [f32; 4]).read_unaligned() };
  3700. format!("Constant({address:#x}, {size}) {v:?}")
  3701. }
  3702. Some(v) => format!("{v:?}").chars().take(60).collect(),
  3703. }
  3704. }
  3705. /// The console's own primitive topologies.
  3706. const TRIANGLE_FAN: u32 = 6;
  3707. const RECTANGLES: u32 = 17;
  3708. const LINE_LOOP: u32 = 18;
  3709. const QUADS: u32 = 19;
  3710. const QUAD_STRIP: u32 = 20;
  3711. /// Fixed-function state, straight onto the host list.
  3712. pub(crate) fn viewports(list: &HostList, viewports: &[D3D12_VIEWPORT]) {
  3713. // SAFETY: an open list.
  3714. unsafe { list.list.RSSetViewports(viewports) };
  3715. }
  3716. pub(crate) fn scissors(list: &HostList, rects: &[RECT]) {
  3717. // SAFETY: an open list.
  3718. unsafe { list.list.RSSetScissorRects(rects) };
  3719. }
  3720. pub(crate) fn blend_factor(list: &HostList, factor: Option<&[f32; 4]>) {
  3721. // SAFETY: an open list.
  3722. unsafe { list.list.OMSetBlendFactor(factor) };
  3723. }
  3724. pub(crate) fn stencil_ref(list: &HostList, reference: u32) {
  3725. #[cfg(feature = "diagnostics")]
  3726. crate::capture::op(std::ptr::from_ref(list) as usize, || format!("STENCIL REF {reference:#x}"));
  3727. // SAFETY: an open list.
  3728. unsafe { list.list.OMSetStencilRef(reference) };
  3729. }
  3730. pub(crate) fn depth_bounds(list: &HostList, min: f32, max: f32) {
  3731. #[cfg(feature = "diagnostics")]
  3732. crate::capture::op(std::ptr::from_ref(list) as usize, || {
  3733. format!("DEPTH BOUNDS {min}..{max}")
  3734. });
  3735. if crate::host::host().is_some_and(|h| h.depth_bounds())
  3736. && let Ok(l1) = list.list.cast::<ID3D12GraphicsCommandList1>()
  3737. {
  3738. // SAFETY: an open list on a device that supports depth bounds.
  3739. unsafe { l1.OMSetDepthBounds(min, max) };
  3740. }
  3741. }
  3742. /// Per-frame texture staging byte budget scaled from the adapter's local VRAM
  3743. /// budget (`None` keeps the 192 MiB 12 GiB baseline).
  3744. fn staging_budget_per_frame(vram_budget: Option<u64>) -> u64 {
  3745. const GIB: u64 = 1 << 30;
  3746. const MIB: u64 = 1 << 20;
  3747. match vram_budget {
  3748. Some(budget) if budget <= 6 * GIB => 96 * MIB,
  3749. Some(budget) if budget >= 20 * GIB => 384 * MIB,
  3750. Some(budget) if budget > 12 * GIB => 256 * MIB,
  3751. _ => 192 * MIB,
  3752. }
  3753. }
  3754. #[cfg(test)]
  3755. mod tests {
  3756. use super::staging_budget_per_frame;
  3757. #[test]
  3758. fn staging_budget_scales_with_vram_budget() {
  3759. const GIB: u64 = 1 << 30;
  3760. const MIB: u64 = 1 << 20;
  3761. assert_eq!(staging_budget_per_frame(None), 192 * MIB);
  3762. assert_eq!(staging_budget_per_frame(Some(4 * GIB)), 96 * MIB);
  3763. assert_eq!(staging_budget_per_frame(Some(6 * GIB)), 96 * MIB);
  3764. assert_eq!(staging_budget_per_frame(Some(8 * GIB)), 192 * MIB);
  3765. assert_eq!(staging_budget_per_frame(Some(12 * GIB)), 192 * MIB);
  3766. assert_eq!(staging_budget_per_frame(Some(13 * GIB)), 256 * MIB);
  3767. assert_eq!(staging_budget_per_frame(Some(14 * GIB)), 256 * MIB);
  3768. assert_eq!(staging_budget_per_frame(Some(16 * GIB)), 256 * MIB);
  3769. assert_eq!(staging_budget_per_frame(Some(20 * GIB)), 384 * MIB);
  3770. assert_eq!(staging_budget_per_frame(Some(24 * GIB)), 384 * MIB);
  3771. assert_eq!(staging_budget_per_frame(Some(32 * GIB)), 384 * MIB);
  3772. }
  3773. }