draw.rs 162 KB

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