draw.rs 197 KB

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