draw.rs 168 KB

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