draw.rs 163 KB

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