indirect.rs 124 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835
  1. //! Indirect execution's arguments, bounded before the GPU reads them. The
  2. //! title's own compute passes write most of them; a pass we drop or
  3. //! translate wrongly leaves whatever the memory held, and a draw of four
  4. //! billion vertices or a dispatch past the host's limits runs until the
  5. //! host resets the display driver. So active records are copied and clamped
  6. //! on the GPU into a device-local scratch buffer, just before execution, by a
  7. //! compute shader of ours (HLSL compiled by the system's compiler; a 5.1
  8. //! shader with its root signature inside), leaving the title's argument and
  9. //! count buffers untouched.
  10. //!
  11. //! The scratch buffer is left readable as indirect arguments after a clamp
  12. //! and stays so until the next clamp into it, which moves it straight back
  13. //! to unordered access; it goes back to the common state once, when the
  14. //! list closes. The executions that read it record no barrier of their
  15. //! own, so draws that read records clamped together (`crate::draw`'s
  16. //! windows) follow each other with nothing between them. Before, each
  17. //! execution was followed by a move of the scratch buffer back to the
  18. //! common state, which drivers may treat as a full wait.
  19. //!
  20. //! The executions of one record without a count buffer (all the title's)
  21. //! are clamped in batches ([`batch`], `VICTORY_INDIRECT_BATCH`): the rest of
  22. //! this is for the others.
  23. //!
  24. //! When a count buffer is given, threads at or past `min(max, count)` return
  25. //! immediately without charging the list's budget or reading uninitialized
  26. //! tail slots. Each list has a budget (2^27 vertex instances or threads,
  27. //! groups counted as 64 threads, mesh groups as 128): active records past it
  28. //! run empty, saturating without 32-bit wraparound so a list of thousands of
  29. //! garbage records cannot run for seconds either.
  30. //!
  31. //! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535
  32. //! groups per dimension, in x 2^20 ([`widest`]), and 2^20 per dispatch, one-dimensional mesh
  33. //! dispatches, the budget) cut legitimate work beyond them; raise them if
  34. //! the title needs more.
  35. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  36. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  37. use windows::Win32::Graphics::Direct3D12::*;
  38. use windows::core::s;
  39. use crate::host::{HostList, host, transition};
  40. pub(crate) mod batch;
  41. const SOURCE: &str = r#"
  42. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)"
  43. cbuffer Record : register(b0) {
  44. uint kind;
  45. uint stride;
  46. uint records;
  47. uint args_offset;
  48. // Bit 0: a count buffer bounds the records. Bit 1: the records are a
  49. // window clamped ahead of their draws: one that asks for more than can
  50. // run is left empty and costs nothing.
  51. uint has_count;
  52. uint count_offset;
  53. };
  54. ByteAddressBuffer src_args : register(t0);
  55. ByteAddressBuffer count_buf : register(t1);
  56. RWByteAddressBuffer dst_args : register(u0);
  57. // The list's work so far (vertex instances, threads): past the budget,
  58. // records run empty.
  59. RWByteAddressBuffer budget : register(u1);
  60. static const uint BUDGET = 1u << 27;
  61. // Groups of one dispatch; more run empty.
  62. static const uint GROUPS = 1u << 20;
  63. // Each group charges the budget once: the costs of its records go here,
  64. // one thread charges their sum, saturating as each record would in lane
  65. // order, and every thread then reads whether its own record fitted. A
  66. // compare and swap per record, 64 threads racing for one word, cost a
  67. // round for each record of a window, and in memory the CPU maps (where the
  68. // budget was, and is with VICTORY_INDIRECT_CARD_BUDGET=0) every atomic
  69. // crosses the bus on a card of its own.
  70. groupshared uint costs[64];
  71. groupshared uint fits[64];
  72. groupshared uint largest_asked;
  73. groupshared uint all_asked;
  74. [RootSignature(RS)]
  75. [numthreads(64, 1, 1)]
  76. void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
  77. uint eff_count = records;
  78. bool ahead = (has_count & 2u) != 0;
  79. if ((has_count & 1u) != 0) {
  80. eff_count = min(eff_count, count_buf.Load(count_offset));
  81. }
  82. // Threads past the records take part in the group's charge (cost 0)
  83. // and store nothing.
  84. bool active = id.x < eff_count;
  85. uint src_at = args_offset + id.x * stride;
  86. uint dst_at = id.x * stride;
  87. uint cost = 0;
  88. uint asked = 0;
  89. uint2 draw_counts = uint2(0, 0);
  90. uint3 groups = uint3(0, 0, 0);
  91. if (gi == 0) {
  92. largest_asked = 0;
  93. all_asked = 0;
  94. }
  95. if (active && kind <= 1) {
  96. // Draws: vertex or index count, then instances.
  97. uint2 want = src_args.Load2(src_at);
  98. if (ahead && (want.x > (1u << 24) || want.y > (1u << 24))) {
  99. want = uint2(0, 0);
  100. }
  101. uint count = min(want.x, 1u << 24);
  102. uint instances = min(want.y, (1u << 26) / max(count, 1u));
  103. cost = count * instances;
  104. draw_counts = uint2(count, instances);
  105. } else if (active && kind == 2) {
  106. uint3 g = src_args.Load3(src_at);
  107. // Up to WIDEST groups in x run as asked (`widest`).
  108. g = min(g, uint3(g.x <= WIDEST ? WIDEST : 65535u, 65535u, 65535u));
  109. // x * y fits 32 bits where it is looked at; the whole count may not.
  110. if ((g.y != 0 && g.x > GROUPS / g.y) || (g.z != 0 && g.x * g.y > GROUPS / g.z)) {
  111. g = uint3(0, 0, 0);
  112. }
  113. cost = g.x * g.y * g.z * 64u;
  114. groups = g;
  115. } else if (active) {
  116. // Mesh dispatches: the console's are one-dimensional.
  117. uint3 g = src_args.Load3(src_at);
  118. // Ahead of its draw, a record over the most a dispatch runs is a
  119. // slot the title has not filled (the title leaves all
  120. // ones there): empty, and not counted below either.
  121. if (ahead && g.x > 65535u) {
  122. g = uint3(0, 0, 0);
  123. }
  124. asked = g.x;
  125. g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u));
  126. cost = g.x * g.y * g.z * 128u;
  127. groups = g;
  128. }
  129. costs[gi] = cost;
  130. GroupMemoryBarrierWithGroupSync();
  131. if (active && kind > 2) {
  132. // Diagnostics, in the budget buffer's next words (below): the
  133. // largest group count a mesh record asked for, and the groups
  134. // asked in all.
  135. uint was;
  136. InterlockedMax(largest_asked, asked, was);
  137. InterlockedAdd(all_asked, min(asked, 1u << 24), was);
  138. }
  139. // The group's own records: none for a group past a count buffer's
  140. // count (an execution may ask for thousands and count a few), which
  141. // touches the budget not at all, as its threads did not before.
  142. uint first = id.x - gi;
  143. uint n = eff_count > first ? min(64u, eff_count - first) : 0u;
  144. if (gi == 0 && n > 0) {
  145. // What the records charge, from `before` on, in lane order: a
  146. // record that does not fit whole runs empty and takes the rest.
  147. // Only the group's own records are walked (one, clamped alone).
  148. uint before;
  149. budget.InterlockedOr(0, 0, before);
  150. [allow_uav_condition]
  151. while (before < BUDGET) {
  152. uint next = before;
  153. for (uint j = 0; j < n; j++) {
  154. uint c = costs[j];
  155. if (c > 0 && next < BUDGET) {
  156. next = (BUDGET - next <= c) ? BUDGET : (next + c);
  157. }
  158. }
  159. if (next == before) break;
  160. uint prev;
  161. budget.InterlockedCompareExchange(0, before, next, prev);
  162. if (prev == before) break;
  163. before = prev;
  164. }
  165. uint at = before;
  166. for (uint k = 0; k < n; k++) {
  167. uint c = costs[k];
  168. uint fit = 1;
  169. if (c > 0) {
  170. fit = (at < BUDGET && BUDGET - at >= c) ? 1u : 0u;
  171. at = (at >= BUDGET || BUDGET - at <= c) ? BUDGET : (at + c);
  172. }
  173. fits[k] = fit;
  174. }
  175. }
  176. GroupMemoryBarrierWithGroupSync();
  177. if (gi == 0 && kind > 2 && n > 0) {
  178. uint was;
  179. budget.InterlockedMax(4, largest_asked, was);
  180. budget.InterlockedAdd(8, all_asked, was);
  181. }
  182. if (!active) {
  183. return;
  184. }
  185. bool over = fits[gi] == 0;
  186. if (kind <= 1) {
  187. if (over) {
  188. draw_counts = uint2(0, 0);
  189. }
  190. dst_args.Store2(dst_at, draw_counts);
  191. for (uint off = 8; off < stride; off += 4) {
  192. dst_args.Store(dst_at + off, src_args.Load(src_at + off));
  193. }
  194. } else {
  195. if (over) {
  196. groups = uint3(0, 0, 0);
  197. }
  198. dst_args.Store3(dst_at, groups);
  199. for (uint off = 12; off < stride; off += 4) {
  200. dst_args.Store(dst_at + off, src_args.Load(src_at + off));
  201. }
  202. }
  203. }
  204. "#;
  205. struct Clamp {
  206. root: ID3D12RootSignature,
  207. pso: ID3D12PipelineState,
  208. }
  209. // SAFETY: D3D12 objects are free-threaded.
  210. unsafe impl Send for Clamp {}
  211. // SAFETY: as above.
  212. unsafe impl Sync for Clamp {}
  213. fn clamp() -> Option<&'static Clamp> {
  214. static CLAMP: std::sync::OnceLock<Option<Clamp>> = std::sync::OnceLock::new();
  215. CLAMP
  216. .get_or_init(|| match make() {
  217. Ok(c) => Some(c),
  218. Err(e) => {
  219. tracing::warn!(error = %e, "no argument clamp: indirect execution dropped");
  220. None
  221. }
  222. })
  223. .as_ref()
  224. }
  225. fn make() -> windows::core::Result<Clamp> {
  226. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  227. make_for(device)
  228. }
  229. fn make_for(device: &ID3D12Device) -> windows::core::Result<Clamp> {
  230. make_from(device, SOURCE)
  231. }
  232. /// The most groups in x that an indirect dispatch runs as the title asks:
  233. /// 65,535 is the most D3D12 names for a dispatch, 2^20 ([`SOURCE`]'s GROUPS)
  234. /// what is bounded here anyway (`VICTORY_INDIRECT_WIDE=0`: 65,535; a record
  235. /// that asks for more still runs 65,535).
  236. ///
  237. /// The title's tile lists are dispatches of one group per tile, and two of
  238. /// them are classes of the picture's 8x4 tiles, 115,200 in all at
  239. /// 2560x1440: in a captured frame 67,440 and 47,760 (the program
  240. /// 2dc364df5d3278b8 and 940c2635dc1312f4). Cut to 65,535 the first list lost
  241. /// its last 1,905 tiles, the lowest of the picture. The console runs what it
  242. /// is asked (its dispatch counts are 32 bits), and so does an AMD card, whose
  243. /// dispatch packets and group numbers are the same; D3D12 does not look at
  244. /// indirect counts. Other cards stay at 65,535.
  245. fn widest(amd: bool) -> u32 {
  246. let on = std::env::var_os("VICTORY_INDIRECT_WIDE").is_none_or(|v| v != "0");
  247. if amd && on { 1 << 20 } else { 65_535 }
  248. }
  249. /// Whether `device` is an AMD card's.
  250. fn amd(device: &ID3D12Device) -> bool {
  251. use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIAdapter1, IDXGIFactory4};
  252. // SAFETY: plain queries.
  253. unsafe {
  254. CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  255. .and_then(|f| f.EnumAdapterByLuid::<IDXGIAdapter1>(device.GetAdapterLuid()))
  256. .and_then(|a| a.GetDesc1())
  257. .is_ok_and(|d| d.VendorId == 0x1002)
  258. }
  259. }
  260. /// The clamp compiled from `source` (ours, or in the benchmark the one it
  261. /// replaced).
  262. fn make_from(device: &ID3D12Device, source: &str) -> windows::core::Result<Clamp> {
  263. #[cfg(feature = "diagnostics")]
  264. let batched = source == batch::SOURCE;
  265. let source = &format!("#define WIDEST {}u\n{source}", widest(amd(device)));
  266. let mut code: Option<ID3DBlob> = None;
  267. let mut errors: Option<ID3DBlob> = None;
  268. // SAFETY: the source and names live through the call; out pointers ours.
  269. let compiled = unsafe {
  270. D3DCompile(
  271. source.as_ptr().cast(),
  272. source.len(),
  273. s!("clamp"),
  274. None,
  275. None,
  276. s!("main"),
  277. s!("cs_5_1"),
  278. 0,
  279. 0,
  280. &mut code,
  281. Some(&mut errors),
  282. )
  283. };
  284. if let Err(e) = compiled {
  285. if let Some(errors) = errors {
  286. // SAFETY: the blob's own bytes.
  287. let text = unsafe {
  288. std::slice::from_raw_parts(
  289. errors.GetBufferPointer().cast::<u8>(),
  290. errors.GetBufferSize(),
  291. )
  292. };
  293. tracing::warn!("argument clamp: {}", String::from_utf8_lossy(text));
  294. }
  295. return Err(e);
  296. }
  297. let code = code.ok_or_else(windows::core::Error::empty)?;
  298. // SAFETY: the blob's own bytes; the root signature is inside the shader.
  299. unsafe {
  300. let bytes =
  301. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  302. let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?;
  303. let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  304. pRootSignature: std::mem::transmute_copy(&root),
  305. CS: D3D12_SHADER_BYTECODE {
  306. pShaderBytecode: bytes.as_ptr().cast(),
  307. BytecodeLength: bytes.len(),
  308. },
  309. ..Default::default()
  310. })?;
  311. #[cfg(feature = "diagnostics")]
  312. crate::host::name(&pso, || crate::replay::play::CLAMP.into());
  313. Ok(Clamp { root, pso })
  314. }
  315. }
  316. /// Minimum record byte stride for a supported PC indirect argument `kind`.
  317. fn min_stride(kind: u32) -> Option<u32> {
  318. match kind {
  319. 0 => Some(16),
  320. 1 => Some(20),
  321. 2 | 10 => Some(12),
  322. _ => None,
  323. }
  324. }
  325. /// Validates record alignment and returns the scratch byte size `stride * records`.
  326. fn validate_layout(
  327. (kind, stride, records): (u32, u32, u32),
  328. src_offset: u64,
  329. count_offset: Option<u64>,
  330. ) -> Option<u64> {
  331. let min = min_stride(kind)?;
  332. if stride < min || !stride.is_multiple_of(4) || !src_offset.is_multiple_of(4) {
  333. return None;
  334. }
  335. if count_offset.is_some_and(|off| !off.is_multiple_of(4)) {
  336. return None;
  337. }
  338. let bytes = u64::from(stride).checked_mul(u64::from(records))?;
  339. (bytes <= u64::from(u32::MAX)).then_some(bytes)
  340. }
  341. /// Records, in `list`, the non-destructive clamp of up to `records` records of
  342. /// `kind` (PC argument numbering) `stride` bytes apart from `src` (and bounded
  343. /// by the 32-bit count in `count` when given) into a device-local scratch
  344. /// buffer, at offset `0`. The scratch buffer is left in `INDIRECT_ARGUMENT`
  345. /// until the next clamp into it: executions read it with no barrier of
  346. /// their own. Replaces the list's compute root signature and pipeline
  347. /// (callers bind theirs after). `None` if the clamp or alignment is not
  348. /// available.
  349. pub(crate) fn bound(
  350. list: &HostList,
  351. src: (&ID3D12Resource, u64),
  352. count: Option<(&ID3D12Resource, u64)>,
  353. spec: (u32, u32, u32),
  354. ) -> Option<ID3D12Resource> {
  355. let bytes = validate_layout(spec, src.1, count.map(|(_, off)| off))?;
  356. let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?);
  357. clamp_into(list, c, &dst, budget, src, count, spec, false).then_some(dst)
  358. }
  359. /// [`bound`] for a window of records clamped ahead of the draws that will
  360. /// read them (`crate::draw`'s windows; no count buffer). The records past
  361. /// the ones the title filled are whatever the buffer holds, and each
  362. /// record clamped charges the list's budget when it is clamped: a slot of
  363. /// all ones, clamped to the most a mesh dispatch runs (65,535 groups),
  364. /// charged a sixteenth of the budget, so sixteen of them emptied every
  365. /// draw of the list after them (run 93: "the largest group count asked for
  366. /// 4294967295", 43 to 153 such records a frame). Here a record that asks
  367. /// for more than can run is left empty and charges nothing; a record
  368. /// clamped alone is clamped and charged as before.
  369. pub(crate) fn bound_ahead(
  370. list: &HostList,
  371. src: (&ID3D12Resource, u64),
  372. spec: (u32, u32, u32),
  373. ) -> Option<ID3D12Resource> {
  374. let bytes = validate_layout(spec, src.1, None)?;
  375. let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?);
  376. clamp_into(list, c, &dst, budget, src, None, spec, true).then_some(dst)
  377. }
  378. /// [`record_clamp_as`] into `list`'s scratch buffer `dst`, from the state
  379. /// the list left it in; afterwards the list knows it is readable as
  380. /// indirect arguments.
  381. #[allow(clippy::too_many_arguments)]
  382. fn clamp_into(
  383. list: &HostList,
  384. c: &Clamp,
  385. dst: &ID3D12Resource,
  386. budget: u64,
  387. src: (&ID3D12Resource, u64),
  388. count: Option<(&ID3D12Resource, u64)>,
  389. spec: (u32, u32, u32),
  390. ahead: bool,
  391. ) -> bool {
  392. let before = list.indirect_state(dst);
  393. let recorded = record_clamp_as(c, &list.list, (dst, before), budget, src, count, spec, ahead);
  394. if recorded {
  395. list.indirect_readable(dst);
  396. }
  397. recorded
  398. }
  399. /// Records the clamp into `dst`, which is in state `before` (common, or
  400. /// indirect arguments after an earlier clamp into it), and leaves `dst` in
  401. /// `INDIRECT_ARGUMENT`. `ahead`: the records are a window clamped ahead of
  402. /// their draws ([`bound_ahead`]). False, with nothing recorded, if the
  403. /// layout or the addresses do not fit the clamp.
  404. #[allow(clippy::too_many_arguments)]
  405. fn record_clamp_as(
  406. c: &Clamp,
  407. l: &ID3D12GraphicsCommandList,
  408. (dst, before): (&ID3D12Resource, D3D12_RESOURCE_STATES),
  409. budget: u64,
  410. (src, src_offset): (&ID3D12Resource, u64),
  411. count: Option<(&ID3D12Resource, u64)>,
  412. (kind, stride, records): (u32, u32, u32),
  413. ahead: bool,
  414. ) -> bool {
  415. let Some(bytes) = validate_layout(
  416. (kind, stride, records),
  417. src_offset,
  418. count.map(|(_, off)| off),
  419. ) else {
  420. return false;
  421. };
  422. // SAFETY: live D3D12 buffer resources.
  423. let (src_base, dst_gpu) = unsafe { (src.GetGPUVirtualAddress(), dst.GetGPUVirtualAddress()) };
  424. if !src_base.is_multiple_of(4) || !dst_gpu.is_multiple_of(4) || !budget.is_multiple_of(4) {
  425. return false;
  426. }
  427. let (src_gpu, args_offset) = match src_offset
  428. .checked_add(bytes)
  429. .filter(|&end| end <= u64::from(u32::MAX))
  430. {
  431. Some(_) => (src_base, src_offset as u32),
  432. None => {
  433. let Some(rebased) = src_base.checked_add(src_offset) else {
  434. return false;
  435. };
  436. (rebased, 0)
  437. }
  438. };
  439. let (count_gpu, has_count, count_offset) = match count {
  440. Some((buf, off)) => {
  441. // SAFETY: a live D3D12 buffer resource.
  442. let base = unsafe { buf.GetGPUVirtualAddress() };
  443. if !base.is_multiple_of(4) {
  444. return false;
  445. }
  446. match off.checked_add(4).filter(|&end| end <= u64::from(u32::MAX)) {
  447. Some(_) => (base, 1u32, off as u32),
  448. None => {
  449. let Some(rebased) = base.checked_add(off) else {
  450. return false;
  451. };
  452. (rebased, 1u32, 0u32)
  453. }
  454. }
  455. }
  456. None => (src_gpu, 0u32, 0u32),
  457. };
  458. let constants = [kind, stride, records, args_offset, has_count | (u32::from(ahead) << 1), count_offset];
  459. // SAFETY: an open list; our root signature and pipeline; live source,
  460. // count, scratch destination, and budget buffers. `src` and `count` stay
  461. // in `COMMON` / `GENERIC_READ` via implicit buffer promotion while `dst`
  462. // transitions `before -> UNORDERED_ACCESS -> INDIRECT_ARGUMENT`. Moving
  463. // it out of `INDIRECT_ARGUMENT` orders this clamp's writes after every
  464. // earlier execution's reads of the scratch buffer; nothing else writes it.
  465. // Diagnostics: counted; `VICTORY_BARRIER_TEST=indirect` leaves the two
  466. // waits for every earlier shader write out (the state changes stay).
  467. #[cfg(feature = "diagnostics")]
  468. crate::copystat::add(crate::copystat::C::IndirectBounded, 1);
  469. #[cfg(feature = "diagnostics")]
  470. let waits = crate::copystat::barrier_test() & 2 == 0;
  471. #[cfg(not(feature = "diagnostics"))]
  472. let waits = true;
  473. let first = [
  474. uav_barrier(),
  475. transition(dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
  476. ];
  477. let second = [
  478. uav_barrier(),
  479. transition(
  480. dst,
  481. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  482. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  483. ),
  484. ];
  485. let skip = usize::from(!waits);
  486. unsafe {
  487. // Earlier shader writes (the title's argument and count passes) first.
  488. l.ResourceBarrier(&first[skip..]);
  489. if records > 0 {
  490. l.SetComputeRootSignature(&c.root);
  491. l.SetPipelineState(&c.pso);
  492. l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  493. l.SetComputeRootShaderResourceView(1, src_gpu);
  494. l.SetComputeRootShaderResourceView(2, count_gpu);
  495. l.SetComputeRootUnorderedAccessView(3, dst_gpu);
  496. l.SetComputeRootUnorderedAccessView(4, budget);
  497. l.Dispatch(records.div_ceil(64), 1, 1);
  498. }
  499. l.ResourceBarrier(&second[skip..]);
  500. }
  501. true
  502. }
  503. /// The batched clamp's pipeline ([`batch`]).
  504. fn batch_clamp() -> Option<&'static Clamp> {
  505. static CLAMP: std::sync::OnceLock<Option<Clamp>> = std::sync::OnceLock::new();
  506. CLAMP
  507. .get_or_init(|| {
  508. let made = host().ok_or_else(windows::core::Error::empty).and_then(|h| make_from(&h.device, batch::SOURCE));
  509. match made {
  510. Ok(c) => Some(c),
  511. Err(e) => {
  512. tracing::warn!(error = %e, "no batched argument clamp: records are clamped one at a time");
  513. None
  514. }
  515. }
  516. })
  517. .as_ref()
  518. }
  519. /// Opens a batch in `list` ([`batch`]): a pass that clamps the records of
  520. /// the executions recorded after it, of `source` (a host copy's number and
  521. /// buffer) and of the `recent` ones after it. The table to add them to,
  522. /// and the scratch buffer its places are in. Replaces the list's compute
  523. /// root signature and pipeline (callers bind theirs after). `None` if the
  524. /// clamp is not available.
  525. pub(crate) fn open_batch(
  526. list: &HostList,
  527. source: (u64, &ID3D12Resource),
  528. recent: &[(u64, ID3D12Resource)],
  529. ) -> Option<(batch::Table, ID3D12Resource)> {
  530. let c = batch_clamp()?;
  531. let budget = list.budget()?;
  532. let (jobs, at) = list.scratch(batch::TABLE)?;
  533. let (dst, base, before) = list.batch_place()?;
  534. let gpu = |b: &ID3D12Resource| {
  535. // SAFETY: a live buffer.
  536. Some(unsafe { b.GetGPUVirtualAddress() }).filter(|at| at.is_multiple_of(4))
  537. };
  538. // A source there is none of is the first again, which no job names.
  539. let mut ids = [0u64; batch::SOURCES];
  540. let mut sources = [gpu(source.1)?; batch::SOURCES];
  541. ids[0] = source.0;
  542. let others = recent.iter().filter(|r| r.0 != source.0).take(batch::SOURCES - 1);
  543. for (i, (id, buffer)) in others.enumerate() {
  544. if let Some(at) = gpu(buffer) {
  545. // Bound, and read only if a job names it: kept alive like the
  546. // copies draws read (`Shadow::refresh`).
  547. list.keep(buffer);
  548. (ids[i + 1], sources[i + 1]) = (*id, at);
  549. }
  550. }
  551. #[cfg(feature = "diagnostics")]
  552. crate::copystat::add(crate::copystat::C::IndirectBounded, 1);
  553. batch::record(c, &list.list, (&dst, before), budget, sources, jobs);
  554. // SAFETY: the list's own upload memory of that many bytes, 256-byte
  555. // aligned, until it is reset.
  556. Some((unsafe { batch::Table::new(at, base, ids) }, dst))
  557. }
  558. /// The batched clamp's root signature and pipeline on `device`, for the
  559. /// replayer.
  560. #[cfg(feature = "diagnostics")]
  561. pub(crate) fn batch_for(device: &ID3D12Device) -> windows::core::Result<(ID3D12RootSignature, ID3D12PipelineState)> {
  562. make_from(device, batch::SOURCE).map(|c| (c.root, c.pso))
  563. }
  564. fn uav_barrier() -> D3D12_RESOURCE_BARRIER {
  565. D3D12_RESOURCE_BARRIER {
  566. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  567. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  568. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  569. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  570. pResource: std::mem::ManuallyDrop::new(None),
  571. }),
  572. },
  573. }
  574. }
  575. #[cfg(test)]
  576. pub(crate) mod tests {
  577. use super::*;
  578. use windows::Win32::Foundation::HANDLE;
  579. use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
  580. use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC;
  581. use windows::Win32::Graphics::Dxgi::*;
  582. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  583. use windows::core::Interface;
  584. const WORKER_CS: &str = r#"
  585. #define RS "UAV(u0)"
  586. RWByteAddressBuffer hits : register(u0);
  587. [RootSignature(RS)]
  588. [numthreads(1, 1, 1)]
  589. void main() {
  590. uint prev;
  591. hits.InterlockedAdd(0, 1, prev);
  592. }
  593. "#;
  594. struct WarpHarness {
  595. device: ID3D12Device,
  596. queue: ID3D12CommandQueue,
  597. allocator: ID3D12CommandAllocator,
  598. list: ID3D12GraphicsCommandList,
  599. fence: ID3D12Fence,
  600. submitted: u64,
  601. event: HANDLE,
  602. clamp: Clamp,
  603. worker: Clamp,
  604. /// Last, so given up last.
  605. _turn: std::sync::MutexGuard<'static, ()>,
  606. }
  607. /// The software adapter is one test's at a time. Two tests that compile
  608. /// and run shaders on it at once (it is one device for the process) make
  609. /// `d3d10warp.dll` (10.0.26100) crash now and then: access violations in
  610. /// its own shader compiler, on its own worker threads, in 12% of runs of
  611. /// all tests and 3% of runs of these alone on two threads; none in 100
  612. /// runs one after the other.
  613. pub(crate) fn warp_turn() -> std::sync::MutexGuard<'static, ()> {
  614. static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(());
  615. TURN.lock().unwrap_or_else(|e| e.into_inner())
  616. }
  617. impl WarpHarness {
  618. fn new() -> Option<Self> {
  619. Self::on(true)
  620. }
  621. /// On the software adapter, or the first one (for measurements).
  622. fn on(software: bool) -> Option<Self> {
  623. let turn = warp_turn();
  624. // SAFETY: plain DXGI query and D3D12 test harness setup.
  625. unsafe {
  626. let factory: IDXGIFactory4 =
  627. CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?;
  628. let adapter: IDXGIAdapter = if software {
  629. factory.EnumWarpAdapter().ok()?
  630. } else {
  631. factory.EnumAdapters(0).ok()?
  632. };
  633. let desc = adapter.cast::<IDXGIAdapter1>().ok()?.GetDesc1().ok()?;
  634. if software != (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0) {
  635. return None;
  636. }
  637. let mut device: Option<ID3D12Device> = None;
  638. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?;
  639. let device = device?;
  640. let queue: ID3D12CommandQueue = device
  641. .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  642. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  643. ..Default::default()
  644. })
  645. .ok()?;
  646. let allocator: ID3D12CommandAllocator = device
  647. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)
  648. .ok()?;
  649. let list: ID3D12GraphicsCommandList = device
  650. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)
  651. .ok()?;
  652. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  653. let event = CreateEventW(None, false, false, None).ok()?;
  654. let clamp = make_for(&device).expect("clamp shader must compile on WARP");
  655. let worker = compile_cs(&device, WORKER_CS).expect("worker shader must compile");
  656. Some(Self {
  657. device,
  658. queue,
  659. allocator,
  660. list,
  661. fence,
  662. submitted: 0,
  663. event,
  664. clamp,
  665. worker,
  666. _turn: turn,
  667. })
  668. }
  669. }
  670. /// CPU-mapped L0 write-back buffer matching `Shadow`'s heap type.
  671. fn shared_buffer(&self, size: u64) -> (ID3D12Resource, *mut u8, u64) {
  672. let heap = D3D12_HEAP_PROPERTIES {
  673. Type: D3D12_HEAP_TYPE_CUSTOM,
  674. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  675. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  676. ..Default::default()
  677. };
  678. let desc = D3D12_RESOURCE_DESC {
  679. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  680. Width: size.max(4),
  681. Height: 1,
  682. DepthOrArraySize: 1,
  683. MipLevels: 1,
  684. SampleDesc: DXGI_SAMPLE_DESC {
  685. Count: 1,
  686. Quality: 0,
  687. },
  688. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  689. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  690. ..Default::default()
  691. };
  692. let mut buffer: Option<ID3D12Resource> = None;
  693. let mut data = std::ptr::null_mut();
  694. // SAFETY: plain buffer creation and persistent CPU mapping.
  695. unsafe {
  696. self.device
  697. .CreateCommittedResource(
  698. &heap,
  699. D3D12_HEAP_FLAG_NONE,
  700. &desc,
  701. D3D12_RESOURCE_STATE_COMMON,
  702. None,
  703. &mut buffer,
  704. )
  705. .unwrap();
  706. let buffer = buffer.unwrap();
  707. buffer.Map(0, None, Some(&mut data)).unwrap();
  708. let gpu = buffer.GetGPUVirtualAddress();
  709. (buffer, data.cast(), gpu)
  710. }
  711. }
  712. /// Device-local `DEFAULT`-heap UAV scratch buffer.
  713. fn default_uav(&self, size: u64) -> ID3D12Resource {
  714. let heap = D3D12_HEAP_PROPERTIES {
  715. Type: D3D12_HEAP_TYPE_DEFAULT,
  716. ..Default::default()
  717. };
  718. let desc = D3D12_RESOURCE_DESC {
  719. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  720. Width: size.max(64 << 10),
  721. Height: 1,
  722. DepthOrArraySize: 1,
  723. MipLevels: 1,
  724. SampleDesc: DXGI_SAMPLE_DESC {
  725. Count: 1,
  726. Quality: 0,
  727. },
  728. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  729. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  730. ..Default::default()
  731. };
  732. let mut buffer: Option<ID3D12Resource> = None;
  733. // SAFETY: plain device-local buffer creation.
  734. unsafe {
  735. self.device
  736. .CreateCommittedResource(
  737. &heap,
  738. D3D12_HEAP_FLAG_NONE,
  739. &desc,
  740. D3D12_RESOURCE_STATE_COMMON,
  741. None,
  742. &mut buffer,
  743. )
  744. .unwrap();
  745. }
  746. buffer.unwrap()
  747. }
  748. fn signature(&self, kind: u32, stride: u32) -> ID3D12CommandSignature {
  749. let arg = D3D12_INDIRECT_ARGUMENT_DESC {
  750. Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32),
  751. ..Default::default()
  752. };
  753. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  754. ByteStride: stride,
  755. NumArgumentDescs: 1,
  756. pArgumentDescs: &arg,
  757. NodeMask: 0,
  758. };
  759. let mut sig: Option<ID3D12CommandSignature> = None;
  760. // SAFETY: valid single-argument command signature description.
  761. unsafe {
  762. self.device
  763. .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig)
  764. .unwrap();
  765. }
  766. sig.unwrap()
  767. }
  768. fn submit_and_wait(&mut self) {
  769. self.submitted += 1;
  770. // SAFETY: closing, executing, waiting on fence, and resetting our list.
  771. unsafe {
  772. self.list.Close().unwrap();
  773. let cmd: ID3D12CommandList = self.list.cast().unwrap();
  774. self.queue.ExecuteCommandLists(&[Some(cmd)]);
  775. self.queue.Signal(&self.fence, self.submitted).unwrap();
  776. self.fence
  777. .SetEventOnCompletion(self.submitted, self.event)
  778. .unwrap();
  779. WaitForSingleObject(self.event, INFINITE);
  780. self.allocator.Reset().unwrap();
  781. self.list.Reset(&self.allocator, None).unwrap();
  782. }
  783. }
  784. }
  785. fn compile_cs(device: &ID3D12Device, source: &str) -> windows::core::Result<Clamp> {
  786. let mut code: Option<ID3DBlob> = None;
  787. // SAFETY: source and entry names outlive `D3DCompile`.
  788. unsafe {
  789. D3DCompile(
  790. source.as_ptr().cast(),
  791. source.len(),
  792. s!("worker"),
  793. None,
  794. None,
  795. s!("main"),
  796. s!("cs_5_1"),
  797. 0,
  798. 0,
  799. &mut code,
  800. None,
  801. )?;
  802. let code = code.unwrap();
  803. let bytes = std::slice::from_raw_parts(
  804. code.GetBufferPointer().cast::<u8>(),
  805. code.GetBufferSize(),
  806. );
  807. let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?;
  808. let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  809. pRootSignature: std::mem::transmute_copy(&root),
  810. CS: D3D12_SHADER_BYTECODE {
  811. pShaderBytecode: bytes.as_ptr().cast(),
  812. BytecodeLength: bytes.len(),
  813. },
  814. ..Default::default()
  815. })?;
  816. Ok(Clamp { root, pso })
  817. }
  818. }
  819. /// The compare of copies in the card's memory (`crate::host`), on the
  820. /// software adapter. Told 1 it flags the pieces whose bytes are not
  821. /// what was hashed last and leaves the hashes: a piece a shader changed
  822. /// and a later one changed back then looks untouched, which is right
  823. /// only if the piece was fetched after both. Told 2 (submissions sent
  824. /// ahead with the relay, whose pieces are fetched flight by flight) it
  825. /// stores the hash it made: each compare flags what changed since the
  826. /// compare before it, also a change back.
  827. #[test]
  828. fn warp_card_compare_stores_the_hash_it_made_when_told() {
  829. let Some(mut warp) = WarpHarness::new() else {
  830. return;
  831. };
  832. let compare = compile_cs(&warp.device, crate::host::CARD_COMPARE).expect("the card compare must compile on WARP");
  833. const PIECE: usize = 64 << 10;
  834. const PIECES: u32 = 3;
  835. let size = PIECE * PIECES as usize;
  836. let (_now, now_ptr, now_gpu) = warp.shared_buffer(size as u64);
  837. let (_hashes, _, hashes_gpu) = warp.shared_buffer(16 * u64::from(PIECES));
  838. let (_differs, differs_ptr, differs_gpu) = warp.shared_buffer(64);
  839. let content: Vec<u8> = (0..size).map(|i| (i * 31 + i / 251) as u8).collect();
  840. // SAFETY: the mapping holds `size` bytes.
  841. unsafe { std::ptr::copy_nonoverlapping(content.as_ptr(), now_ptr, size) };
  842. // One pass over the three pieces; what it left in `differs` (7s
  843. // where it stored nothing).
  844. let run = |warp: &mut WarpHarness, mode: u32| -> [u32; 3] {
  845. // SAFETY: our open list, live buffers, the compare's own root
  846. // signature; the mappings hold what is read and written.
  847. unsafe {
  848. for piece in 0..PIECES as usize {
  849. differs_ptr.cast::<u32>().add(piece).write_volatile(7);
  850. }
  851. warp.list.SetComputeRootSignature(&compare.root);
  852. warp.list.SetPipelineState(&compare.pso);
  853. let constants = [0u32, 0, size as u32, PIECES, 0, mode];
  854. warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  855. warp.list.SetComputeRootShaderResourceView(1, now_gpu);
  856. warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu);
  857. warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu);
  858. warp.list.Dispatch(PIECES, 1, 1);
  859. }
  860. warp.submit_and_wait();
  861. // SAFETY: as above.
  862. let found = [0, 1, 2].map(|piece| unsafe { differs_ptr.cast::<u32>().add(piece).read_volatile() });
  863. if mode == 0 {
  864. return found;
  865. }
  866. // Above the flag, the hash: as `host::torn` makes it of the bytes.
  867. for (piece, d) in found.iter().enumerate() {
  868. // SAFETY: inside the mapping, which the card has read.
  869. let bytes = unsafe { std::slice::from_raw_parts(now_ptr.add(piece * PIECE).cast_const(), PIECE) };
  870. assert_eq!(d >> 1, crate::host::piece_hash(bytes), "piece {piece}");
  871. }
  872. found.map(|d| d & 1)
  873. };
  874. let at = PIECE + 1234;
  875. // SAFETY (each): inside the mapping.
  876. let set = |value: u8| unsafe { now_ptr.add(at).write_volatile(value) };
  877. // 0: the hashes are stored, nothing is flagged.
  878. assert_eq!(run(&mut warp, 0), [7, 7, 7]);
  879. assert_eq!(run(&mut warp, 1), [0, 0, 0]);
  880. // A change in the second piece: flagged, and with 1 flagged again
  881. // (the hash stays the old one).
  882. set(content[at] ^ 0x40);
  883. assert_eq!(run(&mut warp, 1), [0, 1, 0]);
  884. assert_eq!(run(&mut warp, 1), [0, 1, 0]);
  885. // Changed back: with 1 the piece looks untouched.
  886. set(content[at]);
  887. assert_eq!(run(&mut warp, 1), [0, 0, 0]);
  888. // With 2 the change is flagged once, and the hash is the new one.
  889. set(content[at] ^ 0x40);
  890. assert_eq!(run(&mut warp, 2), [0, 1, 0]);
  891. assert_eq!(run(&mut warp, 2), [0, 0, 0]);
  892. // Changed back: flagged, where 1 saw nothing.
  893. set(content[at]);
  894. assert_eq!(run(&mut warp, 2), [0, 1, 0]);
  895. assert_eq!(run(&mut warp, 2), [0, 0, 0]);
  896. }
  897. /// What the passes over copies in the card's memory cost on the card
  898. /// (ignored: a measurement): rounds of a few passes of some pieces and a
  899. /// wait, as a frame has them. `VICTORY_BENCH_CS=<file>` times another
  900. /// source of the shader.
  901. #[test]
  902. #[ignore]
  903. fn card_compare_costs() {
  904. let Some(mut gpu) = WarpHarness::on(false) else {
  905. return;
  906. };
  907. let other = std::env::var("VICTORY_BENCH_CS").ok().map(|f| std::fs::read_to_string(f).unwrap());
  908. let source: &'static str = other.map_or(crate::host::CARD_COMPARE, |s| Box::leak(s.into_boxed_str()));
  909. let walked_alone = source.contains("SV_DispatchThreadID");
  910. let compare = compile_cs(&gpu.device, source).expect("the compare must compile");
  911. let now = gpu.default_uav(256 << 20);
  912. let hashes = gpu.default_uav(64 << 10);
  913. let differs = gpu.default_uav(64 << 10);
  914. for (rounds, passes, pieces) in [(80u32, 5u32, 1u32), (80, 5, 5), (80, 5, 64), (80, 5, 500), (1, 1, 4000)] {
  915. let mut best = f64::MAX;
  916. for _ in 0..6 {
  917. // SAFETY: our open list, live buffers, the compare's own
  918. // root signature; the pieces lie in the buffers.
  919. unsafe {
  920. gpu.list.SetComputeRootSignature(&compare.root);
  921. gpu.list.SetPipelineState(&compare.pso);
  922. gpu.list.SetComputeRootShaderResourceView(1, now.GetGPUVirtualAddress());
  923. gpu.list.SetComputeRootUnorderedAccessView(2, hashes.GetGPUVirtualAddress());
  924. gpu.list.SetComputeRootUnorderedAccessView(3, differs.GetGPUVirtualAddress());
  925. for _ in 0..rounds {
  926. for pass in 0..passes {
  927. let first = if pieces * passes < 4096 { pass * pieces } else { 0 };
  928. let constants = [first, 0u32, 256 << 20, pieces, 0, 1];
  929. gpu.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  930. gpu.list.Dispatch(if walked_alone { pieces.div_ceil(64) } else { pieces }, 1, 1);
  931. }
  932. gpu.list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
  933. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  934. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  935. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  936. pResource: std::mem::ManuallyDrop::new(None),
  937. }),
  938. },
  939. ..Default::default()
  940. }]);
  941. }
  942. }
  943. let t = std::time::Instant::now();
  944. gpu.submit_and_wait();
  945. best = best.min(t.elapsed().as_secs_f64() * 1e3);
  946. }
  947. let mb = f64::from(rounds * passes * pieces) / 16.0;
  948. println!("{rounds} rounds of {passes} passes of {pieces} pieces: {best:.2} ms ({mb:.0} MB, {:.0} GB/s)", mb / best / 1.024);
  949. }
  950. }
  951. /// The clamp compiles with the system's compiler and the host takes it.
  952. #[test]
  953. fn argument_clamp_builds() {
  954. if super::host().is_none() {
  955. return; // no host GPU here
  956. }
  957. assert!(super::clamp().is_some());
  958. }
  959. #[test]
  960. fn rejects_unaligned_or_undersized_layouts() {
  961. assert_eq!(validate_layout((0, 16, 4), 0, None), Some(64));
  962. assert_eq!(validate_layout((1, 20, 4), 64, Some(128)), Some(80));
  963. assert_eq!(validate_layout((2, 12, 0), 0, Some(0)), Some(0));
  964. assert_eq!(validate_layout((10, 16, 2), 8, None), Some(32));
  965. // Undersized strides for each kind.
  966. assert_eq!(validate_layout((0, 12, 1), 0, None), None);
  967. assert_eq!(validate_layout((1, 16, 1), 0, None), None);
  968. assert_eq!(validate_layout((2, 8, 1), 0, None), None);
  969. assert_eq!(validate_layout((10, 8, 1), 0, None), None);
  970. // Unknown kind.
  971. assert_eq!(validate_layout((3, 16, 1), 0, None), None);
  972. // Unaligned stride, source offset, or count offset.
  973. assert_eq!(validate_layout((0, 18, 1), 0, None), None);
  974. assert_eq!(validate_layout((0, 16, 1), 2, None), None);
  975. assert_eq!(validate_layout((0, 16, 1), 0, Some(6)), None);
  976. // Total byte size exceeding 32-bit ByteAddressBuffer indexing.
  977. assert_eq!(validate_layout((1, 20, u32::MAX), 0, None), None);
  978. }
  979. /// WARP D3D12 execution test proving:
  980. /// (a) `countBuffer` with a small count (`3`) and `4,093` garbage tail slots
  981. /// (`max = 4096`) does NOT blow `BUDGET` or zero valid dispatches in
  982. /// this or subsequent `ExecuteIndirect` calls in the same list,
  983. /// (b) `src_args` (and `count_buf`) are NOT mutated in-place, and
  984. /// (c) full `stride` bytes (`stride = 24` > `12`) are copied for active
  985. /// records into `dst_args` at offset `0`.
  986. #[test]
  987. fn warp_count_buffer_ignores_garbage_tail_and_preserves_source() {
  988. let Some(mut warp) = WarpHarness::new() else {
  989. return;
  990. };
  991. const KIND_DISPATCH: u32 = 2;
  992. const STRIDE: u32 = 24; // 6 dwords: 3 dispatch group counts + 3 extra payload dwords
  993. const MAX: u32 = 4096;
  994. const ARGS_OFFSET: usize = 64; // non-zero offset with sentinel prefix
  995. const COUNT_OFFSET_1: usize = 128;
  996. const COUNT_OFFSET_2: usize = 192;
  997. let src_bytes = ARGS_OFFSET + (STRIDE as usize) * (MAX as usize) + 64;
  998. let (src_buf, src_ptr, _) = warp.shared_buffer(src_bytes as u64);
  999. let (count_buf, count_ptr, _) = warp.shared_buffer(512);
  1000. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  1001. let (_hits_buf, hits_ptr, hits_gpu) = warp.shared_buffer(256);
  1002. let (readback_buf, readback_ptr, _) = warp.shared_buffer((STRIDE * 8) as u64);
  1003. let dst_buf = warp.default_uav(u64::from(STRIDE) * u64::from(MAX));
  1004. let sig = warp.signature(KIND_DISPATCH, STRIDE);
  1005. // Fill the entire source buffer with non-zero sentinel bytes, then
  1006. // populate 3 valid records at `ARGS_OFFSET` and 4,093 huge garbage
  1007. // records in `3..MAX` that would exhaust `BUDGET` ~2,000x over if read.
  1008. let mut initial_src = vec![0xA5u8; src_bytes];
  1009. let write_record = |buf: &mut [u8], idx: usize, words: [u32; 6]| {
  1010. let base = ARGS_OFFSET + idx * (STRIDE as usize);
  1011. for (w, val) in words.into_iter().enumerate() {
  1012. buf[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes());
  1013. }
  1014. };
  1015. write_record(
  1016. &mut initial_src,
  1017. 0,
  1018. [3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666],
  1019. );
  1020. write_record(
  1021. &mut initial_src,
  1022. 1,
  1023. [5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC],
  1024. );
  1025. // Record 2 exceeds what any card runs in X -> clamped to (65535, 1, 1).
  1026. write_record(
  1027. &mut initial_src,
  1028. 2,
  1029. [(1 << 20) + 1, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567],
  1030. );
  1031. for slot in 3..MAX as usize {
  1032. // Each garbage slot would clamp to 65535 * 16 * 1 = 1,048,560 groups
  1033. // (`cost = 67,107,840 ~= BUDGET / 2`), exhausting `BUDGET` immediately!
  1034. write_record(
  1035. &mut initial_src,
  1036. slot,
  1037. [0xFFFF_FFFF, 16, 1, 0xDEAD_BEEF, 0xBAD0_C0DE, slot as u32],
  1038. );
  1039. }
  1040. // Second indirect call's source records (at offset 0 of a second buffer,
  1041. // or later in `count_buf`): put 2 active records + garbage tail in a
  1042. // second range to run back-to-back in the SAME command list.
  1043. let mut initial_count = vec![0x5Au8; 512];
  1044. initial_count[COUNT_OFFSET_1..COUNT_OFFSET_1 + 4].copy_from_slice(&3u32.to_le_bytes());
  1045. initial_count[COUNT_OFFSET_2..COUNT_OFFSET_2 + 4].copy_from_slice(&2u32.to_le_bytes());
  1046. // SAFETY: buffers are mapped with exact capacities above.
  1047. unsafe {
  1048. std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, src_bytes);
  1049. std::ptr::copy_nonoverlapping(initial_count.as_ptr(), count_ptr, 512);
  1050. (budget_ptr as *mut u32).write_volatile(0);
  1051. (hits_ptr as *mut u32).write_volatile(0);
  1052. std::ptr::write_bytes(readback_ptr, 0, (STRIDE * 8) as usize);
  1053. }
  1054. // Record Call #1 (`eff_count = 3` out of `MAX = 4096`), copy the first
  1055. // 5 records of `dst_buf` out for inspection, then record Call #2
  1056. // (`eff_count = 2` out of `MAX = 4096`) reusing `dst_buf` in the same list!
  1057. assert!(record_clamp_as(
  1058. &warp.clamp,
  1059. &warp.list,
  1060. (&dst_buf, D3D12_RESOURCE_STATE_COMMON),
  1061. budget_gpu,
  1062. (&src_buf, ARGS_OFFSET as u64),
  1063. Some((&count_buf, COUNT_OFFSET_1 as u64)),
  1064. (KIND_DISPATCH, STRIDE, MAX),
  1065. false,
  1066. ));
  1067. // SAFETY: open command list, valid worker PSO/root and buffers.
  1068. unsafe {
  1069. warp.list.SetComputeRootSignature(&warp.worker.root);
  1070. warp.list.SetPipelineState(&warp.worker.pso);
  1071. warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  1072. warp.list.ExecuteIndirect(
  1073. &sig,
  1074. MAX,
  1075. &dst_buf,
  1076. 0,
  1077. Some(&count_buf),
  1078. COUNT_OFFSET_1 as u64,
  1079. );
  1080. }
  1081. // Snapshot `dst_buf` after Call #1 (copy 5 * STRIDE bytes, then leave
  1082. // `dst_buf` readable as arguments again, as the clamp left it).
  1083. // SAFETY: open command list; the clamp left `dst_buf` in `INDIRECT_ARGUMENT`.
  1084. unsafe {
  1085. warp.list.ResourceBarrier(&[transition(
  1086. &dst_buf,
  1087. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  1088. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1089. )]);
  1090. warp.list
  1091. .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, u64::from(STRIDE * 5));
  1092. warp.list.ResourceBarrier(&[transition(
  1093. &dst_buf,
  1094. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1095. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  1096. )]);
  1097. }
  1098. // Call #2 in the SAME command list (`eff_count = 2` -> records 0 and 1:
  1099. // 6 + 5 = 11 groups). Would run empty if Call #1's tail blew `BUDGET`!
  1100. // The scratch buffer goes straight from arguments back to unordered
  1101. // access.
  1102. assert!(record_clamp_as(
  1103. &warp.clamp,
  1104. &warp.list,
  1105. (&dst_buf, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT),
  1106. budget_gpu,
  1107. (&src_buf, ARGS_OFFSET as u64),
  1108. Some((&count_buf, COUNT_OFFSET_2 as u64)),
  1109. (KIND_DISPATCH, STRIDE, MAX),
  1110. false,
  1111. ));
  1112. // SAFETY: open command list, valid worker PSO/root and buffers.
  1113. unsafe {
  1114. warp.list.SetComputeRootSignature(&warp.worker.root);
  1115. warp.list.SetPipelineState(&warp.worker.pso);
  1116. warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  1117. warp.list.ExecuteIndirect(
  1118. &sig,
  1119. MAX,
  1120. &dst_buf,
  1121. 0,
  1122. Some(&count_buf),
  1123. COUNT_OFFSET_2 as u64,
  1124. );
  1125. }
  1126. warp.submit_and_wait();
  1127. // SAFETY: GPU execution finished; read mapped host results.
  1128. let (hits, spent, after_src, after_count, clamped_words) = unsafe {
  1129. let hits = (hits_ptr as *const u32).read_volatile();
  1130. let spent = (budget_ptr as *const u32).read_volatile();
  1131. let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), src_bytes).to_vec();
  1132. let after_count = std::slice::from_raw_parts(count_ptr.cast_const(), 512).to_vec();
  1133. let words = std::slice::from_raw_parts(
  1134. readback_ptr.cast::<u32>().cast_const(),
  1135. (STRIDE as usize / 4) * 5,
  1136. )
  1137. .to_vec();
  1138. (hits, spent, after_src, after_count, words)
  1139. };
  1140. // Call #1: (3*2*1) + (5*1*1) + (65535*1*1) = 65,546 groups.
  1141. // Call #2: (3*2*1) + (5*1*1) = 11 groups.
  1142. let expected_groups = (6 + 5 + 65_535) + (6 + 5);
  1143. assert_eq!(
  1144. hits, expected_groups,
  1145. "valid indirect dispatches must all execute"
  1146. );
  1147. assert_eq!(
  1148. spent,
  1149. expected_groups * 64,
  1150. "budget must reflect only active records below countBuffer"
  1151. );
  1152. assert_eq!(
  1153. after_src, initial_src,
  1154. "src_args must never be mutated in-place"
  1155. );
  1156. assert_eq!(
  1157. after_count, initial_count,
  1158. "count_buf must never be mutated"
  1159. );
  1160. // Check `dst_args` records 0..3: clamped group counts + preserved extra stride words.
  1161. assert_eq!(
  1162. &clamped_words[0..6],
  1163. &[3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666]
  1164. );
  1165. assert_eq!(
  1166. &clamped_words[6..12],
  1167. &[5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC]
  1168. );
  1169. assert_eq!(
  1170. &clamped_words[12..18],
  1171. &[65_535, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567]
  1172. );
  1173. // Inactive slot 3 was never copied from `src_args`.
  1174. assert_ne!(clamped_words[21], 0xDEAD_BEEF);
  1175. }
  1176. /// WARP D3D12 test proving `BUDGET` saturates without 32-bit unsigned
  1177. /// wraparound across >64 huge indexed-draw records (`count = None`), while
  1178. /// preserving `StartIndexLocation`, `BaseVertexLocation`,
  1179. /// `StartInstanceLocation`, and custom stride padding, and leaving
  1180. /// `src_args` untouched.
  1181. /// A window of mesh records clamped ahead: the filled ones come out as
  1182. /// they are and are charged, the slots of all ones come out empty and
  1183. /// charge nothing; clamped as single records the same slots are clamped
  1184. /// to the most and spend the budget.
  1185. #[test]
  1186. fn warp_window_leaves_unfilled_slots_empty_and_uncharged() {
  1187. let Some(mut warp) = WarpHarness::new() else {
  1188. return;
  1189. };
  1190. const KIND_MESH: u32 = 10;
  1191. const STRIDE: u32 = 32;
  1192. const RECORDS: u32 = 16;
  1193. let filled = [5u32, 0, 519];
  1194. let total = (STRIDE * RECORDS) as usize;
  1195. let mut src = vec![0xffu8; total];
  1196. for (i, groups) in filled.into_iter().enumerate() {
  1197. let words = [groups, 1, 1, 0xAB00 + i as u32];
  1198. for (w, word) in words.into_iter().enumerate() {
  1199. let at = i * STRIDE as usize + w * 4;
  1200. src[at..at + 4].copy_from_slice(&word.to_le_bytes());
  1201. }
  1202. }
  1203. for ahead in [true, false] {
  1204. let (src_buf, src_ptr, _) = warp.shared_buffer(total as u64);
  1205. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  1206. let (readback_buf, readback_ptr, _) = warp.shared_buffer(total as u64);
  1207. let dst_buf = warp.default_uav(total as u64);
  1208. // SAFETY: mapped buffers of these sizes.
  1209. unsafe {
  1210. std::ptr::copy_nonoverlapping(src.as_ptr(), src_ptr, total);
  1211. std::ptr::write_bytes(budget_ptr, 0, 256);
  1212. std::ptr::write_bytes(readback_ptr, 0, total);
  1213. }
  1214. assert!(record_clamp_as(
  1215. &warp.clamp,
  1216. &warp.list,
  1217. (&dst_buf, D3D12_RESOURCE_STATE_COMMON),
  1218. budget_gpu,
  1219. (&src_buf, 0),
  1220. None,
  1221. (KIND_MESH, STRIDE, RECORDS),
  1222. ahead,
  1223. ));
  1224. // SAFETY: an open list; the scratch buffer, which the clamp left
  1225. // readable as arguments, is copied for the check.
  1226. unsafe {
  1227. warp.list.ResourceBarrier(&[transition(
  1228. &dst_buf,
  1229. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  1230. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1231. )]);
  1232. warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64);
  1233. }
  1234. warp.submit_and_wait();
  1235. // SAFETY: the work is done; mapped buffers.
  1236. let (spent, largest, out) = unsafe {
  1237. (
  1238. (budget_ptr as *const u32).read_volatile(),
  1239. (budget_ptr as *const u32).add(1).read_volatile(),
  1240. std::slice::from_raw_parts(readback_ptr.cast::<u32>().cast_const(), total / 4).to_vec(),
  1241. )
  1242. };
  1243. for (i, groups) in filled.into_iter().enumerate() {
  1244. let rec = &out[i * 8..i * 8 + 4];
  1245. assert_eq!(rec, [groups, u32::from(groups > 0).max(1).min(1), 1, 0xAB00 + i as u32], "filled record {i}, ahead {ahead}");
  1246. }
  1247. let charged_filled = (5 + 519) * 128;
  1248. if ahead {
  1249. for i in filled.len()..RECORDS as usize {
  1250. assert_eq!(out[i * 8..i * 8 + 3], [0, 0, 0], "unfilled slot {i} must come out empty");
  1251. assert_eq!(out[i * 8 + 3], u32::MAX, "the words after the record are copied as they are");
  1252. }
  1253. assert_eq!(spent, charged_filled, "unfilled slots charge nothing");
  1254. assert_eq!(largest, 519, "and are not counted as asked for");
  1255. } else {
  1256. // Thirteen slots at 65,535 groups: sixteen would be all of it.
  1257. assert_eq!(spent, charged_filled + 13 * 65535 * 128, "clamped one by one, each slot is charged the most");
  1258. assert_eq!(largest, u32::MAX);
  1259. }
  1260. }
  1261. }
  1262. #[test]
  1263. fn warp_budget_saturates_without_wraparound_and_preserves_draw_fields() {
  1264. let Some(mut warp) = WarpHarness::new() else {
  1265. return;
  1266. };
  1267. const KIND_INDEXED: u32 = 1;
  1268. const STRIDE: u32 = 24; // 5 indexed-draw words + 1 trailing custom word
  1269. const RECORDS: u32 = 128; // 2 waves of 64: old InterlockedAdd wrapped 2^32 at 64!
  1270. const BUDGET_CAP: u32 = 1 << 27;
  1271. let total_bytes = (STRIDE * RECORDS) as usize;
  1272. let (src_buf, src_ptr, _) = warp.shared_buffer(total_bytes as u64);
  1273. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  1274. let (readback_buf, readback_ptr, _) = warp.shared_buffer(total_bytes as u64);
  1275. let dst_buf = warp.default_uav(total_bytes as u64);
  1276. let mut initial_src = vec![0u8; total_bytes];
  1277. for i in 0..RECORDS as usize {
  1278. let words: [u32; 6] = [
  1279. u32::MAX, // IndexCount -> clamps to 1 << 24
  1280. u32::MAX, // InstanceCount -> clamps to 4 (cost = 1 << 26)
  1281. 1000 + i as u32, // StartIndexLocation
  1282. (-200i32 + i as i32) as u32, // BaseVertexLocation
  1283. 5000 + i as u32, // StartInstanceLocation
  1284. 0xCAFE_0000 | (i as u32), // Extra stride word
  1285. ];
  1286. let base = i * (STRIDE as usize);
  1287. for (w, val) in words.into_iter().enumerate() {
  1288. initial_src[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes());
  1289. }
  1290. }
  1291. // SAFETY: mapped buffers have sufficient capacity.
  1292. unsafe {
  1293. std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, total_bytes);
  1294. (budget_ptr as *mut u32).write_volatile(0);
  1295. std::ptr::write_bytes(readback_ptr, 0, total_bytes);
  1296. }
  1297. assert!(record_clamp_as(
  1298. &warp.clamp,
  1299. &warp.list,
  1300. (&dst_buf, D3D12_RESOURCE_STATE_COMMON),
  1301. budget_gpu,
  1302. (&src_buf, 0),
  1303. None,
  1304. (KIND_INDEXED, STRIDE, RECORDS),
  1305. false,
  1306. ));
  1307. // SAFETY: open command list; copy clamped scratch buffer (left
  1308. // readable as arguments) for verification.
  1309. unsafe {
  1310. warp.list.ResourceBarrier(&[transition(
  1311. &dst_buf,
  1312. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  1313. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1314. )]);
  1315. warp.list
  1316. .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total_bytes as u64);
  1317. }
  1318. warp.submit_and_wait();
  1319. // SAFETY: GPU work completed.
  1320. let (spent, after_src, out_words) = unsafe {
  1321. let spent = (budget_ptr as *const u32).read_volatile();
  1322. let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), total_bytes).to_vec();
  1323. let out_words = std::slice::from_raw_parts(
  1324. readback_ptr.cast::<u32>().cast_const(),
  1325. total_bytes / 4,
  1326. )
  1327. .to_vec();
  1328. (spent, after_src, out_words)
  1329. };
  1330. assert_eq!(
  1331. spent, BUDGET_CAP,
  1332. "budget must saturate at BUDGET without wrapping"
  1333. );
  1334. assert_eq!(after_src, initial_src, "src_args must remain untouched");
  1335. let mut kept = 0usize;
  1336. let mut zeroed = 0usize;
  1337. for i in 0..RECORDS as usize {
  1338. let rec = &out_words[i * 6..(i + 1) * 6];
  1339. if rec[0] == (1 << 24) && rec[1] == 4 {
  1340. kept += 1;
  1341. } else {
  1342. assert_eq!((rec[0], rec[1]), (0, 0), "excess draw must be zeroed");
  1343. zeroed += 1;
  1344. }
  1345. assert_eq!(rec[2], 1000 + i as u32);
  1346. assert_eq!(rec[3], (-200i32 + i as i32) as u32);
  1347. assert_eq!(rec[4], 5000 + i as u32);
  1348. assert_eq!(rec[5], 0xCAFE_0000 | (i as u32));
  1349. }
  1350. assert_eq!((kept, zeroed), (2, (RECORDS as usize) - 2));
  1351. }
  1352. /// Exercises `HostList::indirect_scratch`, `bound`, the scratch buffer's
  1353. /// tracked state, `Host::execute`, and `HostList::reset` end-to-end on
  1354. /// the host device.
  1355. #[test]
  1356. fn host_list_reuses_and_grows_scratch_across_submissions() {
  1357. let Some(host) = super::host() else {
  1358. return;
  1359. };
  1360. // What earlier tests left in the debug layer's queue, if it is on.
  1361. let _ = host.log_messages();
  1362. let Ok(list) = host.new_list() else {
  1363. return;
  1364. };
  1365. let Some((src_buf, src_ptr)) = host.shared_buffer(256 << 10) else {
  1366. return;
  1367. };
  1368. let Some((count_buf, count_ptr)) = host.shared_buffer(256) else {
  1369. return;
  1370. };
  1371. // SAFETY: mapped host buffers.
  1372. unsafe {
  1373. std::ptr::write_bytes(src_ptr, 0x7F, 256 << 10);
  1374. (count_ptr as *mut u32).write_volatile(2);
  1375. }
  1376. let args = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
  1377. // First two calls fit inside the initial 64 KiB scratch buffer and
  1378. // must reuse the exact same `ID3D12Resource`, which stays readable
  1379. // as arguments between them.
  1380. let b1 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (0, 16, 64)).unwrap();
  1381. assert_eq!(
  1382. list.indirect_state(&b1),
  1383. args,
  1384. "a clamp leaves the scratch readable as arguments"
  1385. );
  1386. let b2 = bound(&list, (&src_buf, 64), Some((&count_buf, 0)), (1, 20, 128)).unwrap();
  1387. assert_eq!(
  1388. b1.as_raw(),
  1389. b2.as_raw(),
  1390. "scratch buffer within capacity must be reused"
  1391. );
  1392. assert_eq!(list.indirect_state(&b2), args);
  1393. // A call needing >64 KiB grows the scratch buffer mid-list while keeping
  1394. // `b1` alive until reset. The new buffer starts out common.
  1395. let grown = list.indirect_scratch(5000 * 20).unwrap();
  1396. assert_eq!(
  1397. list.indirect_state(&grown),
  1398. D3D12_RESOURCE_STATE_COMMON,
  1399. "a new scratch buffer is common"
  1400. );
  1401. let b3 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 5000)).unwrap();
  1402. assert_eq!(b3.as_raw(), grown.as_raw());
  1403. assert_ne!(
  1404. b3.as_raw(),
  1405. b1.as_raw(),
  1406. "larger request must grow scratch buffer"
  1407. );
  1408. assert_eq!(list.indirect_state(&b3), args);
  1409. assert_eq!(
  1410. list.indirect_state(&b1),
  1411. D3D12_RESOURCE_STATE_COMMON,
  1412. "the replaced buffer went back to common"
  1413. );
  1414. list.close();
  1415. // With the debug layer on (`VICTORY_D3D12_DEBUG=1`, diagnostics):
  1416. // every barrier recorded named the state the buffer was in. Read
  1417. // before the submission, which moves the messages to the log.
  1418. assert_eq!(host.log_messages(), None, "the debug layer found an error");
  1419. host.execute(&[&list]);
  1420. list.reset();
  1421. // After reset, requests up to the grown high-water mark reuse `b3` with
  1422. // zero new allocations; the buffer decayed to common when the
  1423. // submission ran.
  1424. assert_eq!(
  1425. list.indirect_state(&b3),
  1426. D3D12_RESOURCE_STATE_COMMON,
  1427. "a reset list starts with a common scratch buffer"
  1428. );
  1429. let b4 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 4096)).unwrap();
  1430. assert_eq!(
  1431. b4.as_raw(),
  1432. b3.as_raw(),
  1433. "grown scratch buffer must persist across reset"
  1434. );
  1435. assert_eq!(list.indirect_state(&b4), args);
  1436. list.close();
  1437. assert_eq!(host.log_messages(), None, "the debug layer found an error");
  1438. host.execute(&[&list]);
  1439. list.reset();
  1440. }
  1441. /// A group charges its records in lane order: with 300 left of the
  1442. /// budget, the first draw (100) fits, the second (250) does not and
  1443. /// takes the rest, and the ones after it run empty. (Racing for the
  1444. /// word record by record, which of them fitted was up to the GPU.)
  1445. #[test]
  1446. fn warp_a_group_charges_its_records_in_lane_order() {
  1447. let Some(mut warp) = WarpHarness::new() else {
  1448. return;
  1449. };
  1450. const KIND_DRAW: u32 = 0;
  1451. const STRIDE: u32 = 16;
  1452. const BUDGET_CAP: u32 = 1 << 27;
  1453. let counts = [100u32, 250, 50, 100];
  1454. let total = counts.len() * STRIDE as usize;
  1455. let (src_buf, src_ptr, _) = warp.shared_buffer(total as u64);
  1456. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  1457. let (readback_buf, readback_ptr, _) = warp.shared_buffer(total as u64);
  1458. let dst_buf = warp.default_uav(total as u64);
  1459. // SAFETY: mapped buffers of these sizes.
  1460. unsafe {
  1461. for (i, &count) in counts.iter().enumerate() {
  1462. let words = [count, 1, 7, 9];
  1463. std::ptr::copy_nonoverlapping(
  1464. words.as_ptr().cast::<u8>(),
  1465. src_ptr.add(i * STRIDE as usize),
  1466. 16,
  1467. );
  1468. }
  1469. std::ptr::write_bytes(budget_ptr, 0, 256);
  1470. (budget_ptr as *mut u32).write_volatile(BUDGET_CAP - 300);
  1471. }
  1472. assert!(record_clamp_as(
  1473. &warp.clamp,
  1474. &warp.list,
  1475. (&dst_buf, D3D12_RESOURCE_STATE_COMMON),
  1476. budget_gpu,
  1477. (&src_buf, 0),
  1478. None,
  1479. (KIND_DRAW, STRIDE, counts.len() as u32),
  1480. false,
  1481. ));
  1482. // SAFETY: an open list; the clamped records are copied for the check.
  1483. unsafe {
  1484. warp.list.ResourceBarrier(&[transition(
  1485. &dst_buf,
  1486. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  1487. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1488. )]);
  1489. warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64);
  1490. }
  1491. warp.submit_and_wait();
  1492. // SAFETY: the work is done; mapped buffers.
  1493. let (spent, out) = unsafe {
  1494. (
  1495. (budget_ptr as *const u32).read_volatile(),
  1496. std::slice::from_raw_parts(readback_ptr.cast::<u32>().cast_const(), total / 4)
  1497. .to_vec(),
  1498. )
  1499. };
  1500. assert_eq!(out[0..4], [100, 1, 7, 9], "the first record fits");
  1501. for i in 1..counts.len() {
  1502. assert_eq!(out[i * 4..i * 4 + 4], [0, 0, 7, 9], "record {i} runs empty");
  1503. }
  1504. assert_eq!(spent, BUDGET_CAP, "the record that did not fit took the rest");
  1505. }
  1506. /// The list's budget starts empty at each submission, wherever it
  1507. /// lives (the card's copy is zeroed in the list): a recording whose
  1508. /// clamps spend all of it is followed, after the reset, by one whose
  1509. /// small record still runs.
  1510. #[test]
  1511. fn host_list_budget_starts_empty_at_each_submission() {
  1512. let Some(host) = super::host() else {
  1513. return;
  1514. };
  1515. let Ok(list) = host.new_list() else {
  1516. return;
  1517. };
  1518. let _ = host.log_messages();
  1519. let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile");
  1520. const KIND_DISPATCH: u32 = 2;
  1521. const STRIDE: u32 = 12;
  1522. let signature = {
  1523. let arg = D3D12_INDIRECT_ARGUMENT_DESC {
  1524. Type: D3D12_INDIRECT_ARGUMENT_TYPE(KIND_DISPATCH as i32),
  1525. ..Default::default()
  1526. };
  1527. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  1528. ByteStride: STRIDE,
  1529. NumArgumentDescs: 1,
  1530. pArgumentDescs: &arg,
  1531. NodeMask: 0,
  1532. };
  1533. let mut sig: Option<ID3D12CommandSignature> = None;
  1534. // SAFETY: a valid single-argument command signature description.
  1535. unsafe {
  1536. host.device
  1537. .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig)
  1538. .unwrap();
  1539. }
  1540. sig.unwrap()
  1541. };
  1542. // Three records of 65,535 x 16 groups: about half the budget each.
  1543. let Some((big, big_ptr)) = host.shared_buffer(3 * u64::from(STRIDE)) else {
  1544. return;
  1545. };
  1546. let Some((small, small_ptr)) = host.shared_buffer(u64::from(STRIDE)) else {
  1547. return;
  1548. };
  1549. let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else {
  1550. return;
  1551. };
  1552. // SAFETY: mapped buffers of these sizes; nothing runs yet.
  1553. unsafe {
  1554. for i in 0..3 {
  1555. let words = [65535u32, 16, 1];
  1556. std::ptr::copy_nonoverlapping(
  1557. words.as_ptr().cast::<u8>(),
  1558. big_ptr.add(i * STRIDE as usize),
  1559. 12,
  1560. );
  1561. }
  1562. std::ptr::copy_nonoverlapping([1u32, 1, 1].as_ptr().cast::<u8>(), small_ptr, 12);
  1563. std::ptr::write_bytes(hits_ptr, 0, 256);
  1564. }
  1565. // SAFETY: a live buffer.
  1566. let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() };
  1567. for round in 0..2 {
  1568. // Spends the budget (clamped, not executed), then one group.
  1569. bound(&list, (&big, 0), None, (KIND_DISPATCH, STRIDE, 3)).unwrap();
  1570. let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap();
  1571. // SAFETY: an open list; the worker's root signature and
  1572. // pipeline; buffers the test holds until the list has run.
  1573. unsafe {
  1574. list.list.SetComputeRootSignature(&worker.root);
  1575. list.list.SetPipelineState(&worker.pso);
  1576. list.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  1577. list.list.ExecuteIndirect(&signature, 1, &scratch, 0, None, 0);
  1578. }
  1579. list.close();
  1580. assert_eq!(host.log_messages(), None, "the debug layer found an error");
  1581. host.execute(&[&list]);
  1582. list.reset();
  1583. // SAFETY: the list has run; a mapped buffer.
  1584. let hits = unsafe { (hits_ptr as *const u32).read_volatile() };
  1585. // The small record comes after the big ones spent the budget:
  1586. // it runs empty, in every round alike (none carries over).
  1587. assert_eq!(hits, 0, "round {round}: the spent budget empties the record after it");
  1588. }
  1589. // A recording with only the small record: the budget is empty
  1590. // again, so it runs.
  1591. let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap();
  1592. // SAFETY: as above.
  1593. unsafe {
  1594. list.list.SetComputeRootSignature(&worker.root);
  1595. list.list.SetPipelineState(&worker.pso);
  1596. list.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  1597. list.list.ExecuteIndirect(&signature, 1, &scratch, 0, None, 0);
  1598. }
  1599. list.close();
  1600. assert_eq!(host.log_messages(), None, "the debug layer found an error");
  1601. host.execute(&[&list]);
  1602. list.reset();
  1603. // SAFETY: the list has run; a mapped buffer.
  1604. let hits = unsafe { (hits_ptr as *const u32).read_volatile() };
  1605. assert_eq!(hits, 1, "the budget starts empty at the next submission");
  1606. }
  1607. /// Records the dispatch records `groups` (three words each, `step`
  1608. /// bytes apart, the rest of each record ones) into a fresh mapped
  1609. /// buffer of `warp`'s device.
  1610. fn dispatch_records(warp: &WarpHarness, groups: &[u32], step: u32) -> ID3D12Resource {
  1611. let total = groups.len() * step as usize;
  1612. let (buffer, ptr, _) = warp.shared_buffer(total as u64);
  1613. let mut bytes = vec![0xffu8; total];
  1614. for (i, &g) in groups.iter().enumerate() {
  1615. for (w, word) in [g, 1, 1].into_iter().enumerate() {
  1616. let at = i * step as usize + w * 4;
  1617. bytes[at..at + 4].copy_from_slice(&word.to_le_bytes());
  1618. }
  1619. }
  1620. // SAFETY: the mapping holds `total` bytes.
  1621. unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, total) };
  1622. buffer
  1623. }
  1624. /// Two windows in one list, as `crate::draw` records them: each clamps
  1625. /// its records ahead, then one execution per record reads the scratch
  1626. /// buffer with no barrier between them; the second clamp moves the
  1627. /// scratch buffer straight from arguments back to unordered access.
  1628. /// Every record runs once, with the group count it asked for.
  1629. #[test]
  1630. fn warp_window_executions_read_their_records_with_no_barrier_between() {
  1631. let Some(mut warp) = WarpHarness::new() else {
  1632. return;
  1633. };
  1634. const KIND_DISPATCH: u32 = 2;
  1635. // The title names 12 bytes and keeps its records 32 apart.
  1636. const STRIDE: u32 = 12;
  1637. const STEP: u32 = 32;
  1638. let windows: [&[u32]; 2] = [&[1, 2, 3, 4], &[10, 11, 12, 13]];
  1639. let sources: Vec<ID3D12Resource> =
  1640. windows.iter().map(|g| dispatch_records(&warp, g, STEP)).collect();
  1641. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  1642. let (_hits_buf, hits_ptr, hits_gpu) = warp.shared_buffer(256);
  1643. let dst_buf = warp.default_uav(u64::from(STEP) * 4);
  1644. let sig = warp.signature(KIND_DISPATCH, STRIDE);
  1645. // SAFETY: mapped buffers of these sizes.
  1646. unsafe {
  1647. std::ptr::write_bytes(budget_ptr, 0, 256);
  1648. std::ptr::write_bytes(hits_ptr, 0, 256);
  1649. }
  1650. let mut state = D3D12_RESOURCE_STATE_COMMON;
  1651. for (groups, src) in windows.iter().zip(&sources) {
  1652. assert!(record_clamp_as(
  1653. &warp.clamp,
  1654. &warp.list,
  1655. (&dst_buf, state),
  1656. budget_gpu,
  1657. (src, 0),
  1658. None,
  1659. (KIND_DISPATCH, STEP, groups.len() as u32),
  1660. true,
  1661. ));
  1662. state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
  1663. // SAFETY: an open list; the worker's root signature and
  1664. // pipeline; the scratch buffer is readable as arguments.
  1665. unsafe {
  1666. warp.list.SetComputeRootSignature(&warp.worker.root);
  1667. warp.list.SetPipelineState(&warp.worker.pso);
  1668. warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  1669. for i in 0..groups.len() as u64 {
  1670. warp.list.ExecuteIndirect(&sig, 1, &dst_buf, i * u64::from(STEP), None, 0);
  1671. }
  1672. }
  1673. }
  1674. warp.submit_and_wait();
  1675. // SAFETY: the work is done; mapped buffers.
  1676. let (hits, spent) = unsafe {
  1677. (
  1678. (hits_ptr as *const u32).read_volatile(),
  1679. (budget_ptr as *const u32).read_volatile(),
  1680. )
  1681. };
  1682. let expected: u32 = windows.iter().flat_map(|g| g.iter()).sum();
  1683. assert_eq!(hits, expected, "every record of both windows runs once");
  1684. assert_eq!(spent, expected * 64, "and is charged what it asked for");
  1685. }
  1686. /// The windows of `warp_window_executions_read_their_records_with_no_barrier_between`
  1687. /// through a host list (`bound_ahead`, the list's tracked scratch state,
  1688. /// `Host::execute`), twice: on the first recording the scratch buffer
  1689. /// starts common, on the second (after the reset) it starts common
  1690. /// again. With the debug layer on (`VICTORY_D3D12_DEBUG=1` in a
  1691. /// diagnostics build) no barrier names a state the buffer is not in.
  1692. #[test]
  1693. fn host_list_window_executions_need_no_barrier_of_their_own() {
  1694. let Some(host) = super::host() else {
  1695. return;
  1696. };
  1697. // What earlier tests left in the debug layer's queue, if it is on.
  1698. let _ = host.log_messages();
  1699. let Ok(list) = host.new_list() else {
  1700. return;
  1701. };
  1702. let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile");
  1703. const KIND_DISPATCH: u32 = 2;
  1704. const STRIDE: u32 = 12;
  1705. const STEP: u32 = 32;
  1706. let signature = {
  1707. let arg = D3D12_INDIRECT_ARGUMENT_DESC {
  1708. Type: D3D12_INDIRECT_ARGUMENT_TYPE(KIND_DISPATCH as i32),
  1709. ..Default::default()
  1710. };
  1711. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  1712. ByteStride: STRIDE,
  1713. NumArgumentDescs: 1,
  1714. pArgumentDescs: &arg,
  1715. NodeMask: 0,
  1716. };
  1717. let mut sig: Option<ID3D12CommandSignature> = None;
  1718. // SAFETY: a valid single-argument command signature description.
  1719. unsafe {
  1720. host.device
  1721. .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig)
  1722. .unwrap();
  1723. }
  1724. sig.unwrap()
  1725. };
  1726. let windows: [&[u32]; 2] = [&[1, 2, 3, 4], &[10, 11, 12, 13]];
  1727. let mut sources = Vec::new();
  1728. for groups in windows {
  1729. let total = groups.len() * STEP as usize;
  1730. let Some((buffer, ptr)) = host.shared_buffer(total as u64) else {
  1731. return;
  1732. };
  1733. let mut bytes = vec![0xffu8; total];
  1734. for (i, &g) in groups.iter().enumerate() {
  1735. for (w, word) in [g, 1, 1].into_iter().enumerate() {
  1736. let at = i * STEP as usize + w * 4;
  1737. bytes[at..at + 4].copy_from_slice(&word.to_le_bytes());
  1738. }
  1739. }
  1740. // SAFETY: the mapping holds `total` bytes.
  1741. unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, total) };
  1742. sources.push(buffer);
  1743. }
  1744. let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else {
  1745. return;
  1746. };
  1747. let expected: u32 = windows.iter().flat_map(|g| g.iter()).sum();
  1748. // SAFETY: a live buffer.
  1749. let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() };
  1750. for _ in 0..2 {
  1751. // SAFETY: the mapping holds 256 bytes; nothing runs.
  1752. unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) };
  1753. for (groups, src) in windows.iter().zip(&sources) {
  1754. let spec = (KIND_DISPATCH, STEP, groups.len() as u32);
  1755. let scratch = bound_ahead(&list, (src, 0), spec).unwrap();
  1756. assert_eq!(list.indirect_state(&scratch), D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
  1757. // SAFETY: an open list; the worker's root signature and
  1758. // pipeline; buffers the test holds until the list has run.
  1759. unsafe {
  1760. list.list.SetComputeRootSignature(&worker.root);
  1761. list.list.SetPipelineState(&worker.pso);
  1762. list.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  1763. for i in 0..groups.len() as u64 {
  1764. let at = i * u64::from(STEP);
  1765. list.list.ExecuteIndirect(&signature, 1, &scratch, at, None, 0);
  1766. }
  1767. }
  1768. }
  1769. list.close();
  1770. // With the debug layer on: nothing it objects to was recorded.
  1771. // Read before the submission, which moves the messages to the log.
  1772. assert_eq!(host.log_messages(), None, "the debug layer found an error");
  1773. host.execute(&[&list]);
  1774. list.reset();
  1775. // SAFETY: the list has run; a mapped buffer.
  1776. let hits = unsafe { (hits_ptr as *const u32).read_volatile() };
  1777. assert_eq!(hits, expected, "every record of both windows runs once");
  1778. }
  1779. }
  1780. /// A command signature of one argument of `kind` on `device`.
  1781. fn one_argument(device: &ID3D12Device, kind: u32, stride: u32) -> ID3D12CommandSignature {
  1782. let arg = D3D12_INDIRECT_ARGUMENT_DESC {
  1783. Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32),
  1784. ..Default::default()
  1785. };
  1786. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  1787. ByteStride: stride,
  1788. NumArgumentDescs: 1,
  1789. pArgumentDescs: &arg,
  1790. NodeMask: 0,
  1791. };
  1792. let mut sig: Option<ID3D12CommandSignature> = None;
  1793. // SAFETY: a valid single-argument command signature description.
  1794. unsafe {
  1795. device.CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig).unwrap();
  1796. }
  1797. sig.unwrap()
  1798. }
  1799. /// An AMD card runs every group of an indirect dispatch of more than
  1800. /// 65,535, each under its own number: the title's tile lists
  1801. /// ([`widest`]), clamped one by one and in a batch. Others are not asked.
  1802. #[test]
  1803. fn card_runs_wide_indirect_dispatches() {
  1804. const CS: &str = r#"
  1805. #define RS "UAV(u0)"
  1806. RWByteAddressBuffer seen : register(u0);
  1807. [RootSignature(RS)]
  1808. [numthreads(1, 1, 1)]
  1809. void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) {
  1810. uint was;
  1811. seen.InterlockedAdd(0, 1, was);
  1812. seen.InterlockedMax(4, group.x, was);
  1813. seen.InterlockedMax(8, thread.x, was);
  1814. seen.InterlockedAdd(16 + group.x * 4, 1, was);
  1815. }
  1816. "#;
  1817. let Some(mut gpu) = WarpHarness::on(false) else {
  1818. return;
  1819. };
  1820. if !amd(&gpu.device) || widest(true) == 65_535 {
  1821. return;
  1822. }
  1823. let worker = compile_cs(&gpu.device, CS).expect("the worker must compile");
  1824. let pass = make_from(&gpu.device, batch::SOURCE).expect("the batched clamp must compile");
  1825. let sig = gpu.signature(2, 12);
  1826. for asked in [67_440u32, 115_200, 1 << 20, (1 << 20) + 1] {
  1827. let runs = if asked > 1 << 20 { 65_535 } else { asked };
  1828. for batched in [false, true] {
  1829. let (src, src_ptr, src_gpu) = gpu.shared_buffer(1024);
  1830. let (_budget, budget_ptr, budget_gpu) = gpu.shared_buffer(256);
  1831. let (_table, table_ptr, table_gpu) = gpu.shared_buffer(batch::TABLE);
  1832. let size = 16 + (4 << 20) + 16;
  1833. let seen = gpu.default_uav(size);
  1834. let (back, back_ptr, _) = gpu.shared_buffer(size);
  1835. let dst = gpu.default_uav(64 << 10);
  1836. // SAFETY: mapped buffers, which nothing reads yet; an open
  1837. // list and live buffers.
  1838. unsafe {
  1839. std::ptr::write_bytes(budget_ptr, 0, 256);
  1840. for (w, word) in [asked, 1, 1].into_iter().enumerate() {
  1841. src_ptr.cast::<u32>().add(w).write_volatile(word);
  1842. }
  1843. if batched {
  1844. batch::record(&pass, &gpu.list, (&dst, D3D12_RESOURCE_STATE_COMMON), budget_gpu, [src_gpu; 4], table_gpu);
  1845. assert_eq!(batch::Table::new(table_ptr, 0, [1, 0, 0, 0]).place(1, 0, 2), Some(0));
  1846. } else {
  1847. let to = (&dst, D3D12_RESOURCE_STATE_COMMON);
  1848. assert!(record_clamp_as(&gpu.clamp, &gpu.list, to, budget_gpu, (&src, 0), None, (2, 12, 1), false));
  1849. }
  1850. gpu.list.SetComputeRootSignature(&worker.root);
  1851. gpu.list.SetPipelineState(&worker.pso);
  1852. gpu.list.SetComputeRootUnorderedAccessView(0, seen.GetGPUVirtualAddress());
  1853. gpu.list.ExecuteIndirect(&sig, 1, &dst, 0, None, 0);
  1854. gpu.list.ResourceBarrier(&[uav_barrier()]);
  1855. gpu.list.ResourceBarrier(&[transition(&seen, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
  1856. gpu.list.CopyBufferRegion(&back, 0, &seen, 0, size);
  1857. }
  1858. gpu.submit_and_wait();
  1859. // SAFETY: the list has run; mapped words.
  1860. let word = |i: usize| unsafe { back_ptr.cast::<u32>().add(i).read_volatile() };
  1861. assert_eq!([word(0), word(1), word(2)], [runs, runs - 1, runs - 1], "asked for {asked}, batched {batched}");
  1862. let wrong = (0..runs as usize).find(|&g| word(4 + g) != 1);
  1863. assert_eq!((wrong, word(4 + runs as usize)), (None, 0), "every group once, asked for {asked}");
  1864. }
  1865. }
  1866. }
  1867. /// What a batch's table says of records added to it: one job per
  1868. /// record, charged for every execution that reads it, and none for what
  1869. /// the pass cannot read.
  1870. #[test]
  1871. fn batch_tables() {
  1872. use batch::{JOBS, SLOT, TABLE, TIMES, Table, job};
  1873. let mut memory = vec![0xffff_ffffu32; TABLE as usize / 4 + 1];
  1874. // SAFETY: the vector holds the table and outlives its use.
  1875. let mut t = unsafe { Table::new(memory.as_mut_ptr().cast(), 4096, [7, 9, 0, 0]) };
  1876. assert_eq!(t.place(7, 64, 10), Some(4096));
  1877. assert_eq!(t.place(9, 64, 10), Some(4096 + u64::from(SLOT)));
  1878. assert_eq!(t.place(7, 64, 2), Some(4096 + 2 * u64::from(SLOT)), "another kind is another record");
  1879. // The same record again: the same place, charged twice.
  1880. assert_eq!(t.place(9, 64, 10), Some(4096 + u64::from(SLOT)));
  1881. assert_eq!(&memory[..4], [3, 0xffff_ffff, 0xffff_ffff, 0xffff_ffff]);
  1882. assert_eq!(memory[4..8], [job(0, 10, 1), 64, 4096, 0]);
  1883. assert_eq!(memory[8..12], [job(1, 10, 2), 64, 4096 + SLOT, 0]);
  1884. assert_eq!(job(1, 10, 2), 1 | 10 << 4 | 3 << 8 | 2 << 16);
  1885. // Not a copy of the pass, not on 4 bytes, past 32 bits, not a kind.
  1886. for (id, offset, kind) in [(8, 64, 10), (7, 66, 10), (7, 1 << 32, 10), (7, u64::from(u32::MAX) & !3, 10), (7, 64, 3)] {
  1887. assert_eq!(t.place(id, offset, kind), None);
  1888. }
  1889. // Read more often than one job may be charged for: another job.
  1890. for _ in 1..TIMES {
  1891. assert_eq!(t.place(7, 64, 10), Some(4096));
  1892. }
  1893. assert_eq!(t.place(7, 64, 10), Some(4096 + 3 * u64::from(SLOT)));
  1894. assert_eq!(t.place(7, 64, 10), Some(4096 + 3 * u64::from(SLOT)));
  1895. for i in 4..u64::from(JOBS) {
  1896. assert_eq!(t.place(7, 1024 + 16 * i, 0), Some(4096 + i * u64::from(SLOT)));
  1897. }
  1898. assert_eq!(t.place(7, 1024, 1), None, "full");
  1899. assert_eq!(t.place(7, 1024 + 16 * 5, 0), Some(4096 + 5 * u64::from(SLOT)));
  1900. assert_eq!((memory[0], memory[TABLE as usize / 4]), (JOBS, 0xffff_ffff));
  1901. }
  1902. /// A batch clamps records exactly as the clamp of one execution does, of
  1903. /// any kind, sensible or not; they are added to its table after the pass
  1904. /// was recorded; it charges each as often as it is read.
  1905. #[test]
  1906. fn warp_batch_clamps_as_the_clamp_of_one_does() {
  1907. let Some(mut warp) = WarpHarness::new() else {
  1908. return;
  1909. };
  1910. let pass = make_from(&warp.device, batch::SOURCE).expect("the batched clamp must compile on WARP");
  1911. let kinds = [0u32, 1, 2, 10];
  1912. let values = [0u32, 1, 3, 100, 65_535, 65_536, 1 << 20, 1 << 24, (1 << 26) + 1, u32::MAX];
  1913. // Every kind with many records, in two sources.
  1914. let mut records: Vec<(u32, [u32; 5])> = Vec::new();
  1915. for kind in kinds {
  1916. for (i, a) in values.into_iter().enumerate() {
  1917. for (k, b) in values.into_iter().enumerate() {
  1918. records.push((kind, [a, b, values[(i * 3 + k) % 4], 77, 0xABCD]));
  1919. }
  1920. }
  1921. }
  1922. // In passes of so few that the budget holds whatever one asks for,
  1923. // and one pass of them all, which it does not.
  1924. let (src, src_ptr, src_gpu) = warp.shared_buffer(64 << 10);
  1925. let (_other, other_ptr, other_gpu) = warp.shared_buffer(64 << 10);
  1926. for (i, (_, words)) in records.iter().enumerate() {
  1927. for (w, word) in words.iter().enumerate() {
  1928. // SAFETY: 400 records of 32 bytes in 64 KiB.
  1929. unsafe {
  1930. src_ptr.cast::<u32>().add(i * 8 + w).write_volatile(*word);
  1931. other_ptr.cast::<u32>().add(i * 8 + w).write_volatile(*word);
  1932. }
  1933. }
  1934. }
  1935. let (_budget, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  1936. let (back, back_ptr, _) = warp.shared_buffer(64 << 10);
  1937. let dst = warp.default_uav(64 << 10);
  1938. let (_table, table_ptr, table_gpu) = warp.shared_buffer(batch::TABLE);
  1939. for (i, (kind, _)) in records.iter().enumerate().step_by(3) {
  1940. let offset = i as u64 * 32;
  1941. let words = batch::words(*kind).unwrap();
  1942. let stride = words * 4;
  1943. let read = |p: *mut u8| -> Vec<u32> {
  1944. // SAFETY: the mapping holds more.
  1945. (0..words as usize).map(|w| unsafe { p.cast::<u32>().add(w).read_volatile() }).collect()
  1946. };
  1947. let mut seen = Vec::new();
  1948. for batched in [false, true] {
  1949. // SAFETY: mapped buffers; nothing runs.
  1950. unsafe { std::ptr::write_bytes(budget_ptr, 0, 256) };
  1951. if batched {
  1952. batch::record(&pass, &warp.list, (&dst, D3D12_RESOURCE_STATE_COMMON), budget_gpu, [src_gpu, other_gpu, src_gpu, src_gpu], table_gpu);
  1953. // SAFETY: the mapped table; the list has not run.
  1954. let mut table = unsafe { batch::Table::new(table_ptr, 0, [1, 2, 0, 0]) };
  1955. assert_eq!(table.place(1 + i as u64 % 2, offset, *kind), Some(0));
  1956. } else {
  1957. assert!(record_clamp_as(
  1958. &warp.clamp,
  1959. &warp.list,
  1960. (&dst, D3D12_RESOURCE_STATE_COMMON),
  1961. budget_gpu,
  1962. (&src, offset),
  1963. None,
  1964. (*kind, stride, 1),
  1965. false,
  1966. ));
  1967. }
  1968. // SAFETY: an open list; the records are readable as arguments.
  1969. unsafe {
  1970. warp.list.ResourceBarrier(&[transition(&dst, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
  1971. warp.list.CopyBufferRegion(&back, 0, &dst, 0, u64::from(stride));
  1972. warp.list.ResourceBarrier(&[transition(&dst, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]);
  1973. }
  1974. warp.submit_and_wait();
  1975. // SAFETY: the list has run; mapped words.
  1976. let budget: Vec<u32> = (0..3).map(|k| unsafe { budget_ptr.cast::<u32>().add(k).read_volatile() }).collect();
  1977. seen.push((read(back_ptr), budget));
  1978. }
  1979. // (A mesh record that asks for nothing notes nothing.)
  1980. assert_eq!(seen[0], seen[1], "record {i} of kind {kind}: {:?}", records[i].1);
  1981. }
  1982. }
  1983. /// Records past the list's budget come out empty, and one read by many
  1984. /// executions is charged for each.
  1985. #[test]
  1986. fn warp_batch_charges_every_execution() {
  1987. let Some(mut warp) = WarpHarness::new() else {
  1988. return;
  1989. };
  1990. let pass = make_from(&warp.device, batch::SOURCE).expect("the batched clamp must compile on WARP");
  1991. const BUDGET: u32 = 1 << 27;
  1992. // 2^26 vertices each, as much as a draw is let run: two fill it.
  1993. for (times, records, filled) in [(1u32, 3u64, 2usize), (2, 1, 1), (1, 1, 1), (3, 1, 0)] {
  1994. let (_src, src_ptr, src_gpu) = warp.shared_buffer(64 << 10);
  1995. let (_budget, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  1996. let (back, back_ptr, _) = warp.shared_buffer(1024);
  1997. let (_table, table_ptr, table_gpu) = warp.shared_buffer(batch::TABLE);
  1998. let dst = warp.default_uav(64 << 10);
  1999. batch::record(&pass, &warp.list, (&dst, D3D12_RESOURCE_STATE_COMMON), budget_gpu, [src_gpu; 4], table_gpu);
  2000. // SAFETY: mapped buffers, which the list has not read yet.
  2001. let mut table = unsafe {
  2002. std::ptr::write_bytes(budget_ptr, 0, 256);
  2003. for r in 0..records {
  2004. for (w, word) in [1u32 << 24, 4, 5, 6].into_iter().enumerate() {
  2005. src_ptr.cast::<u32>().add(r as usize * 4 + w).write_volatile(word);
  2006. }
  2007. }
  2008. batch::Table::new(table_ptr, 0, [1, 0, 0, 0])
  2009. };
  2010. for _ in 0..times {
  2011. for r in 0..records {
  2012. assert_eq!(table.place(1, r * 16, 0), Some(r * u64::from(batch::SLOT)));
  2013. }
  2014. }
  2015. // SAFETY: an open list; the records are readable as arguments.
  2016. unsafe {
  2017. warp.list.ResourceBarrier(&[transition(&dst, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
  2018. warp.list.CopyBufferRegion(&back, 0, &dst, 0, 256);
  2019. }
  2020. warp.submit_and_wait();
  2021. // SAFETY: the list has run; mapped words.
  2022. let (spent, out): (u32, Vec<u32>) = unsafe {
  2023. (
  2024. budget_ptr.cast::<u32>().read_volatile(),
  2025. (0..records as usize).map(|r| back_ptr.cast::<u32>().add(r * batch::SLOT as usize / 4).read_volatile()).collect(),
  2026. )
  2027. };
  2028. assert_eq!(out.iter().filter(|&&v| v == 1 << 24).count(), filled, "{times} times {records}: {out:?}");
  2029. assert!(out.iter().all(|&v| v == 0 || v == 1 << 24));
  2030. assert_eq!(spent, BUDGET.min((1 << 26) * times * records as u32));
  2031. }
  2032. }
  2033. /// Two batches through a host list, twice (the second recording finds
  2034. /// the scratch buffer as the first one's end left it): executions with
  2035. /// nothing between them read what they asked for, of two source buffers,
  2036. /// the second batch while the first one's places are still read. With
  2037. /// the debug layer on no barrier names a state the buffer is not in.
  2038. #[test]
  2039. fn host_list_batches() {
  2040. let Some(host) = super::host() else {
  2041. return;
  2042. };
  2043. let _ = host.log_messages();
  2044. let Ok(list) = host.new_list() else {
  2045. return;
  2046. };
  2047. let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile");
  2048. let signature = one_argument(&host.device, 2, 12);
  2049. let mut sources = Vec::new();
  2050. for first in [1u32, 100] {
  2051. let Some((buffer, ptr)) = host.shared_buffer(1024) else {
  2052. return;
  2053. };
  2054. for i in 0..16u32 {
  2055. for (w, word) in [first + i, 1, 1].into_iter().enumerate() {
  2056. // SAFETY: inside the mapping.
  2057. unsafe { ptr.cast::<u32>().add(i as usize * 8 + w).write_volatile(word) };
  2058. }
  2059. }
  2060. sources.push(buffer);
  2061. }
  2062. let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else {
  2063. return;
  2064. };
  2065. // SAFETY: a live buffer.
  2066. let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() };
  2067. for _ in 0..2 {
  2068. // SAFETY: the mapping holds 256 bytes; nothing runs.
  2069. unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) };
  2070. let mut expected = 0;
  2071. // More batches than one scratch buffer holds.
  2072. for k in 0..12u32 {
  2073. let (mut table, scratch) =
  2074. open_batch(&list, (1, &sources[0]), &[(1, sources[0].clone()), (2, sources[1].clone())]).unwrap();
  2075. // SAFETY: an open list; the worker's root signature and
  2076. // pipeline; buffers the test holds until the list has run.
  2077. unsafe {
  2078. list.list.SetComputeRootSignature(&worker.root);
  2079. list.list.SetPipelineState(&worker.pso);
  2080. list.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  2081. }
  2082. for (id, record) in [(1u64, 3 + k % 4), (2, 5), (1, 0), (2, 5)] {
  2083. let at = table.place(id, u64::from(record) * 32, 2).unwrap();
  2084. // SAFETY: as above.
  2085. unsafe { list.list.ExecuteIndirect(&signature, 1, &scratch, at, None, 0) };
  2086. expected += record + if id == 1 { 1 } else { 100 };
  2087. }
  2088. }
  2089. list.close();
  2090. assert_eq!(host.log_messages(), None, "the debug layer found an error");
  2091. host.execute(&[&list]);
  2092. list.reset();
  2093. // SAFETY: the list has run; a mapped buffer.
  2094. let hits = unsafe { (hits_ptr as *const u32).read_volatile() };
  2095. assert_eq!(hits, expected, "every execution runs what it asked for");
  2096. }
  2097. }
  2098. /// What clamps of a frame cost on the card one by one and in batches
  2099. /// (ignored: a measurement): 2,355 executions of an empty dispatch, in
  2100. /// 49 lists' worth of runs, as in the captured frame.
  2101. #[test]
  2102. #[ignore]
  2103. fn batch_costs() {
  2104. let Some(mut gpu) = WarpHarness::on(false) else {
  2105. return;
  2106. };
  2107. const EXECUTIONS: u32 = 2355;
  2108. let pass = make_from(&gpu.device, batch::SOURCE).expect("the batched clamp must compile");
  2109. let sig = gpu.signature(2, 12);
  2110. let groups: Vec<u32> = vec![1; 2048];
  2111. let src = dispatch_records(&gpu, &groups, 32);
  2112. // SAFETY: a live buffer.
  2113. let src_gpu = unsafe { src.GetGPUVirtualAddress() };
  2114. let budget = gpu.default_uav(256);
  2115. let hits = gpu.default_uav(256);
  2116. // SAFETY: live buffers.
  2117. let (budget_gpu, hits_gpu) = unsafe { (budget.GetGPUVirtualAddress(), hits.GetGPUVirtualAddress()) };
  2118. let (_tables, tables_ptr, tables_gpu) = gpu.shared_buffer(batch::TABLE * 2400);
  2119. let dst = gpu.default_uav(4 << 20);
  2120. for run in [0u32, 2355 / 49, 5, 1] {
  2121. let mut best = f64::MAX;
  2122. for _ in 0..6 {
  2123. let mut state = D3D12_RESOURCE_STATE_COMMON;
  2124. let mut table = batch::Table::default();
  2125. for i in 0..EXECUTIONS {
  2126. if run == 0 {
  2127. assert!(record_clamp_as(&gpu.clamp, &gpu.list, (&dst, state), budget_gpu, (&src, u64::from(i % 2048) * 32), None, (2, 12, 1), false));
  2128. } else if i % run == 0 {
  2129. let k = u64::from(i / run) * batch::TABLE;
  2130. batch::record(&pass, &gpu.list, (&dst, state), budget_gpu, [src_gpu; 4], tables_gpu + k);
  2131. // SAFETY: the mapped table; the list has not run.
  2132. table = unsafe { batch::Table::new(tables_ptr.add(k as usize), 0, [1, 0, 0, 0]) };
  2133. }
  2134. state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
  2135. let at = if run == 0 { 0 } else { table.place(1, u64::from(i % 2048) * 32, 2).unwrap() };
  2136. // SAFETY: an open list; live buffers.
  2137. unsafe {
  2138. if run == 0 || i % run == 0 {
  2139. gpu.list.SetComputeRootSignature(&gpu.worker.root);
  2140. gpu.list.SetPipelineState(&gpu.worker.pso);
  2141. gpu.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  2142. }
  2143. gpu.list.ExecuteIndirect(&sig, 1, &dst, at, None, 0);
  2144. }
  2145. }
  2146. let t = std::time::Instant::now();
  2147. gpu.submit_and_wait();
  2148. best = best.min(t.elapsed().as_secs_f64() * 1e3);
  2149. }
  2150. let what = if run == 0 { "each clamped on its own".to_owned() } else { format!("a batch every {run}") };
  2151. println!("{EXECUTIONS} indirect dispatches, {what}: {best:.2} ms");
  2152. }
  2153. }
  2154. }
  2155. /// The benchmark of the clamp and its barriers (ignored by default).
  2156. #[cfg(test)]
  2157. mod bench;
  2158. /// What one small draw costs this card, bare and with one thing changed
  2159. /// between every two draws: a measurement, not a check (it asserts only
  2160. /// that the card answered). The timing run of the lit scene (run 187) has
  2161. /// some 11,000 small commands a frame at 5 to 16 microseconds each, and no
  2162. /// log says whether that is what we put around a command or what the card
  2163. /// takes for one. Each variant here is 10,000 one-triangle draws into a
  2164. /// 2560x1440 target, timed on the card by one pair of timestamps around
  2165. /// the whole batch (not one per command, which would time the stamps).
  2166. ///
  2167. /// Run by name, no game needed:
  2168. /// `cargo test -p victory-gpu --release -- --ignored bare_command_cost --nocapture`
  2169. #[cfg(test)]
  2170. mod bare_cost {
  2171. use windows::Win32::Foundation::{HANDLE, RECT};
  2172. use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY};
  2173. use windows::Win32::Graphics::Direct3D12::*;
  2174. use windows::Win32::Graphics::Dxgi::Common::*;
  2175. use windows::Win32::Graphics::Dxgi::*;
  2176. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  2177. use windows::core::{Interface, s};
  2178. use crate::host::{compile, transition};
  2179. /// Draws in a batch.
  2180. const DRAWS: u32 = 10_000;
  2181. const WIDTH: u32 = 2560;
  2182. const HEIGHT: u32 = 1440;
  2183. /// One small triangle in the middle of the target (about 180 pixels),
  2184. /// and two pixel programs that read one texel of a texture through a
  2185. /// table, so that the view heap set is in use.
  2186. const DRAW: &str = r#"
  2187. #define RS "DescriptorTable(SRV(t0))"
  2188. Texture2D<float4> image : register(t0);
  2189. [RootSignature(RS)]
  2190. float4 corner(uint i : SV_VertexID) : SV_Position {
  2191. float2 p = float2((i << 1) & 2, i & 2);
  2192. return float4(p * 0.02 - 0.01, 0.5, 1.0);
  2193. }
  2194. [RootSignature(RS)]
  2195. float4 first(float4 at : SV_Position) : SV_Target {
  2196. return image.Load(int3(0, 0, 0));
  2197. }
  2198. [RootSignature(RS)]
  2199. float4 second(float4 at : SV_Position) : SV_Target {
  2200. return 1.0 - image.Load(int3(0, 0, 0));
  2201. }
  2202. "#;
  2203. /// A compute pass of next to nothing, as our clamp of an indirect
  2204. /// record is: one group of one thread that writes one word.
  2205. const WORK: &str = r#"
  2206. #define RS "UAV(u0)"
  2207. RWByteAddressBuffer words : register(u0);
  2208. [RootSignature(RS)]
  2209. [numthreads(1, 1, 1)]
  2210. void work() {
  2211. words.Store(0, words.Load(0) + 1);
  2212. }
  2213. "#;
  2214. /// What changes between every two draws of a batch.
  2215. #[derive(Clone, Copy, PartialEq)]
  2216. enum Between {
  2217. /// Nothing.
  2218. Nothing,
  2219. /// The pipeline: two alternate.
  2220. Pipeline,
  2221. /// A second texture goes from target to shader read and back.
  2222. BarrierPair,
  2223. /// The depth texture bound for testing goes from write to read or
  2224. /// back.
  2225. DepthMove,
  2226. /// The pair of descriptor heaps: two pairs alternate.
  2227. Heaps,
  2228. /// The colour target: two alternate.
  2229. Targets,
  2230. /// A compute pass of ours of one group, and the pipeline back.
  2231. Compute,
  2232. /// The same between two waits for every earlier shader write, as
  2233. /// the clamp records them.
  2234. ComputeWithWaits,
  2235. }
  2236. struct Rig {
  2237. queue: ID3D12CommandQueue,
  2238. allocator: ID3D12CommandAllocator,
  2239. list: ID3D12GraphicsCommandList,
  2240. fence: ID3D12Fence,
  2241. submitted: u64,
  2242. event: HANDLE,
  2243. root: ID3D12RootSignature,
  2244. pipelines: [ID3D12PipelineState; 2],
  2245. work_root: ID3D12RootSignature,
  2246. work: ID3D12PipelineState,
  2247. words: ID3D12Resource,
  2248. other: ID3D12Resource,
  2249. depth: ID3D12Resource,
  2250. /// Kept alive: the views below name them.
  2251. _kept: Vec<ID3D12Resource>,
  2252. _target_heaps: [ID3D12DescriptorHeap; 2],
  2253. heap_pairs: [[Option<ID3D12DescriptorHeap>; 2]; 2],
  2254. tables: [D3D12_GPU_DESCRIPTOR_HANDLE; 2],
  2255. targets: [D3D12_CPU_DESCRIPTOR_HANDLE; 2],
  2256. depth_written: D3D12_CPU_DESCRIPTOR_HANDLE,
  2257. depth_tested: D3D12_CPU_DESCRIPTOR_HANDLE,
  2258. stamps: ID3D12QueryHeap,
  2259. back: ID3D12Resource,
  2260. card: String,
  2261. }
  2262. fn texture(
  2263. device: &ID3D12Device,
  2264. (width, height): (u32, u32),
  2265. format: DXGI_FORMAT,
  2266. flags: D3D12_RESOURCE_FLAGS,
  2267. state: D3D12_RESOURCE_STATES,
  2268. ) -> ID3D12Resource {
  2269. let heap = D3D12_HEAP_PROPERTIES {
  2270. Type: D3D12_HEAP_TYPE_DEFAULT,
  2271. ..Default::default()
  2272. };
  2273. let desc = D3D12_RESOURCE_DESC {
  2274. Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  2275. Width: u64::from(width),
  2276. Height: height,
  2277. DepthOrArraySize: 1,
  2278. MipLevels: 1,
  2279. Format: format,
  2280. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  2281. Flags: flags,
  2282. ..Default::default()
  2283. };
  2284. let mut out: Option<ID3D12Resource> = None;
  2285. // SAFETY: plain texture creation.
  2286. unsafe {
  2287. device
  2288. .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out)
  2289. .unwrap();
  2290. }
  2291. out.unwrap()
  2292. }
  2293. fn buffer(
  2294. device: &ID3D12Device,
  2295. size: u64,
  2296. kind: D3D12_HEAP_TYPE,
  2297. flags: D3D12_RESOURCE_FLAGS,
  2298. state: D3D12_RESOURCE_STATES,
  2299. ) -> ID3D12Resource {
  2300. let heap = D3D12_HEAP_PROPERTIES {
  2301. Type: kind,
  2302. ..Default::default()
  2303. };
  2304. let desc = D3D12_RESOURCE_DESC {
  2305. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  2306. Width: size,
  2307. Height: 1,
  2308. DepthOrArraySize: 1,
  2309. MipLevels: 1,
  2310. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  2311. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  2312. Flags: flags,
  2313. ..Default::default()
  2314. };
  2315. let mut out: Option<ID3D12Resource> = None;
  2316. // SAFETY: plain buffer creation.
  2317. unsafe {
  2318. device
  2319. .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out)
  2320. .unwrap();
  2321. }
  2322. out.unwrap()
  2323. }
  2324. fn heap(device: &ID3D12Device, kind: D3D12_DESCRIPTOR_HEAP_TYPE, count: u32, visible: bool) -> ID3D12DescriptorHeap {
  2325. let flags = if visible {
  2326. D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE
  2327. } else {
  2328. D3D12_DESCRIPTOR_HEAP_FLAG_NONE
  2329. };
  2330. // SAFETY: plain heap creation.
  2331. unsafe {
  2332. device
  2333. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  2334. Type: kind,
  2335. NumDescriptors: count,
  2336. Flags: flags,
  2337. NodeMask: 0,
  2338. })
  2339. .unwrap()
  2340. }
  2341. }
  2342. fn pipeline(device: &ID3D12Device, root: &ID3D12RootSignature, vs: &[u8], ps: &[u8]) -> ID3D12PipelineState {
  2343. let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
  2344. pShaderBytecode: bytes.as_ptr().cast(),
  2345. BytecodeLength: bytes.len(),
  2346. };
  2347. let mut blend = D3D12_BLEND_DESC::default();
  2348. blend.RenderTarget[0].RenderTargetWriteMask = 0xf;
  2349. let mut formats = [DXGI_FORMAT(0); 8];
  2350. formats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
  2351. // SAFETY: the description points at live data and never releases
  2352. // its pointer to the root signature.
  2353. unsafe {
  2354. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  2355. pRootSignature: std::mem::transmute_copy(root),
  2356. VS: code(vs),
  2357. PS: code(ps),
  2358. BlendState: blend,
  2359. SampleMask: u32::MAX,
  2360. RasterizerState: D3D12_RASTERIZER_DESC {
  2361. FillMode: D3D12_FILL_MODE_SOLID,
  2362. CullMode: D3D12_CULL_MODE_NONE,
  2363. DepthClipEnable: true.into(),
  2364. ..Default::default()
  2365. },
  2366. // Depth is tested and never written, so the texture may be
  2367. // in the write state or in the read state under one view.
  2368. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  2369. DepthEnable: true.into(),
  2370. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO,
  2371. DepthFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL,
  2372. ..Default::default()
  2373. },
  2374. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  2375. NumRenderTargets: 1,
  2376. RTVFormats: formats,
  2377. DSVFormat: DXGI_FORMAT_D32_FLOAT,
  2378. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  2379. ..Default::default()
  2380. };
  2381. device.CreateGraphicsPipelineState(&desc).unwrap()
  2382. }
  2383. }
  2384. impl Rig {
  2385. /// The default adapter, as the layer takes it; `None` without one
  2386. /// or on a software adapter.
  2387. fn new() -> Option<Self> {
  2388. let vs = compile(DRAW, s!("corner"), s!("vs_5_1")).ok()?;
  2389. let ps = [
  2390. compile(DRAW, s!("first"), s!("ps_5_1")).ok()?,
  2391. compile(DRAW, s!("second"), s!("ps_5_1")).ok()?,
  2392. ];
  2393. let cs = compile(WORK, s!("work"), s!("cs_5_1")).ok()?;
  2394. // SAFETY: plain object creation on a device of our own; the
  2395. // views are made in heaps that live as long as the rig.
  2396. unsafe {
  2397. let mut device: Option<ID3D12Device> = None;
  2398. D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?;
  2399. let device = device?;
  2400. let desc = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  2401. .and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid()))
  2402. .ok()?
  2403. .cast::<IDXGIAdapter1>()
  2404. .ok()?
  2405. .GetDesc1()
  2406. .ok()?;
  2407. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 {
  2408. return None;
  2409. }
  2410. let card = String::from_utf16_lossy(&desc.Description)
  2411. .trim_end_matches('\0')
  2412. .to_owned();
  2413. let queue: ID3D12CommandQueue = device
  2414. .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  2415. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  2416. ..Default::default()
  2417. })
  2418. .ok()?;
  2419. let allocator: ID3D12CommandAllocator =
  2420. device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?;
  2421. let list: ID3D12GraphicsCommandList = device
  2422. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)
  2423. .ok()?;
  2424. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  2425. let event = CreateEventW(None, false, false, None).ok()?;
  2426. let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs[..]).ok()?;
  2427. let pipelines = [
  2428. pipeline(&device, &root, &vs, &ps[0]),
  2429. pipeline(&device, &root, &vs, &ps[1]),
  2430. ];
  2431. let work_root: ID3D12RootSignature = device.CreateRootSignature(0, &cs[..]).ok()?;
  2432. let work: ID3D12PipelineState = device
  2433. .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  2434. pRootSignature: std::mem::transmute_copy(&work_root),
  2435. CS: D3D12_SHADER_BYTECODE {
  2436. pShaderBytecode: cs.as_ptr().cast(),
  2437. BytecodeLength: cs.len(),
  2438. },
  2439. ..Default::default()
  2440. })
  2441. .ok()?;
  2442. let size = (WIDTH, HEIGHT);
  2443. let colour = |state| texture(&device, size, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, state);
  2444. let target = [
  2445. colour(D3D12_RESOURCE_STATE_RENDER_TARGET),
  2446. colour(D3D12_RESOURCE_STATE_RENDER_TARGET),
  2447. ];
  2448. let other = colour(D3D12_RESOURCE_STATE_RENDER_TARGET);
  2449. let depth = texture(
  2450. &device,
  2451. size,
  2452. DXGI_FORMAT_D32_FLOAT,
  2453. D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL,
  2454. D3D12_RESOURCE_STATE_DEPTH_WRITE,
  2455. );
  2456. let image = texture(
  2457. &device,
  2458. (4, 4),
  2459. DXGI_FORMAT_R8G8B8A8_UNORM,
  2460. D3D12_RESOURCE_FLAG_NONE,
  2461. D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
  2462. );
  2463. let words = buffer(
  2464. &device,
  2465. 64 << 10,
  2466. D3D12_HEAP_TYPE_DEFAULT,
  2467. D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  2468. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  2469. );
  2470. let back = buffer(
  2471. &device,
  2472. 16,
  2473. D3D12_HEAP_TYPE_READBACK,
  2474. D3D12_RESOURCE_FLAG_NONE,
  2475. D3D12_RESOURCE_STATE_COPY_DEST,
  2476. );
  2477. let mut stamps: Option<ID3D12QueryHeap> = None;
  2478. device
  2479. .CreateQueryHeap(
  2480. &D3D12_QUERY_HEAP_DESC {
  2481. Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP,
  2482. Count: 2,
  2483. NodeMask: 0,
  2484. },
  2485. &mut stamps,
  2486. )
  2487. .ok()?;
  2488. let stamps = stamps?;
  2489. // Target and depth views.
  2490. let rtvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, false);
  2491. let rtv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize;
  2492. let mut targets = [rtvs.GetCPUDescriptorHandleForHeapStart(); 2];
  2493. targets[1].ptr += rtv_step;
  2494. device.CreateRenderTargetView(&target[0], None, targets[0]);
  2495. device.CreateRenderTargetView(&target[1], None, targets[1]);
  2496. let dsvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2, false);
  2497. let dsv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize;
  2498. let depth_written = dsvs.GetCPUDescriptorHandleForHeapStart();
  2499. let mut depth_tested = depth_written;
  2500. depth_tested.ptr += dsv_step;
  2501. device.CreateDepthStencilView(&depth, None, depth_written);
  2502. let tested = D3D12_DEPTH_STENCIL_VIEW_DESC {
  2503. Format: DXGI_FORMAT_D32_FLOAT,
  2504. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D,
  2505. Flags: D3D12_DSV_FLAG_READ_ONLY_DEPTH,
  2506. ..Default::default()
  2507. };
  2508. device.CreateDepthStencilView(&depth, Some(&tested), depth_tested);
  2509. // Two pairs of shader-visible heaps: views (one view of the
  2510. // small texture each) and samplers (none used).
  2511. let view_heaps = [
  2512. heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true),
  2513. heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true),
  2514. ];
  2515. let sampler_heaps = [
  2516. heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true),
  2517. heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true),
  2518. ];
  2519. for views in &view_heaps {
  2520. device.CreateShaderResourceView(&image, None, views.GetCPUDescriptorHandleForHeapStart());
  2521. }
  2522. let tables = [
  2523. view_heaps[0].GetGPUDescriptorHandleForHeapStart(),
  2524. view_heaps[1].GetGPUDescriptorHandleForHeapStart(),
  2525. ];
  2526. let heap_pairs = [
  2527. [Some(view_heaps[0].clone()), Some(sampler_heaps[0].clone())],
  2528. [Some(view_heaps[1].clone()), Some(sampler_heaps[1].clone())],
  2529. ];
  2530. // The first list: both targets and the depth texture cleared.
  2531. list.ClearRenderTargetView(targets[0], &[0.0; 4], None);
  2532. list.ClearRenderTargetView(targets[1], &[0.0; 4], None);
  2533. list.ClearDepthStencilView(depth_written, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None);
  2534. let [first_target, second_target] = target;
  2535. let mut rig = Rig {
  2536. queue,
  2537. allocator,
  2538. list,
  2539. fence,
  2540. submitted: 0,
  2541. event,
  2542. root,
  2543. pipelines,
  2544. work_root,
  2545. work,
  2546. words,
  2547. other,
  2548. depth,
  2549. _kept: vec![first_target, second_target, image],
  2550. _target_heaps: [rtvs, dsvs],
  2551. heap_pairs,
  2552. tables,
  2553. targets,
  2554. depth_written,
  2555. depth_tested,
  2556. stamps,
  2557. back,
  2558. card,
  2559. };
  2560. rig.finish();
  2561. Some(rig)
  2562. }
  2563. }
  2564. /// Closes the open list, runs it, waits for the card and opens the
  2565. /// list again.
  2566. fn finish(&mut self) {
  2567. self.submitted += 1;
  2568. // SAFETY: our list, queue and fence; the allocator is reset
  2569. // only after the card finished everything recorded from it.
  2570. unsafe {
  2571. self.list.Close().unwrap();
  2572. let run: ID3D12CommandList = self.list.cast().unwrap();
  2573. self.queue.ExecuteCommandLists(&[Some(run)]);
  2574. self.queue.Signal(&self.fence, self.submitted).unwrap();
  2575. self.fence.SetEventOnCompletion(self.submitted, self.event).unwrap();
  2576. WaitForSingleObject(self.event, INFINITE);
  2577. self.allocator.Reset().unwrap();
  2578. self.list.Reset(&self.allocator, None).unwrap();
  2579. }
  2580. }
  2581. /// What every list starts with: a new list has nothing set.
  2582. fn begin(&self) {
  2583. let l = &self.list;
  2584. // SAFETY: an open list and live objects and views.
  2585. unsafe {
  2586. l.SetDescriptorHeaps(&self.heap_pairs[0]);
  2587. l.SetGraphicsRootSignature(&self.root);
  2588. l.SetPipelineState(&self.pipelines[0]);
  2589. l.SetGraphicsRootDescriptorTable(0, self.tables[0]);
  2590. l.OMSetRenderTargets(1, Some(&self.targets[0]), false, Some(&self.depth_tested));
  2591. l.RSSetViewports(&[D3D12_VIEWPORT {
  2592. TopLeftX: 0.0,
  2593. TopLeftY: 0.0,
  2594. Width: WIDTH as f32,
  2595. Height: HEIGHT as f32,
  2596. MinDepth: 0.0,
  2597. MaxDepth: 1.0,
  2598. }]);
  2599. l.RSSetScissorRects(&[RECT {
  2600. left: 0,
  2601. top: 0,
  2602. right: WIDTH as i32,
  2603. bottom: HEIGHT as i32,
  2604. }]);
  2605. // A triangle list.
  2606. l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(4));
  2607. }
  2608. }
  2609. /// One batch of [`DRAWS`] draws in `lists` lists run one by one,
  2610. /// with `between` recorded before every draw: the microseconds a
  2611. /// draw took on the card, and the milliseconds recording took.
  2612. fn batch(&mut self, between: Between, lists: u32) -> (f64, f64) {
  2613. let (target, read, written, tested) = (
  2614. D3D12_RESOURCE_STATE_RENDER_TARGET,
  2615. D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
  2616. D3D12_RESOURCE_STATE_DEPTH_WRITE,
  2617. D3D12_RESOURCE_STATE_DEPTH_READ,
  2618. );
  2619. let started = std::time::Instant::now();
  2620. let mut drawn = 0u32;
  2621. for part in 0..lists {
  2622. let l = &self.list;
  2623. // SAFETY: an open list; our query heap; live objects.
  2624. unsafe {
  2625. if part == 0 {
  2626. l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0);
  2627. }
  2628. }
  2629. self.begin();
  2630. // SAFETY: an open list with everything set; live objects.
  2631. // Every state moved is moved back within the batch (the
  2632. // draws of a list are an even number).
  2633. unsafe {
  2634. for _ in 0..DRAWS / lists {
  2635. let odd = (drawn % 2) as usize;
  2636. match between {
  2637. Between::Nothing => {}
  2638. Between::Pipeline => l.SetPipelineState(&self.pipelines[odd]),
  2639. Between::BarrierPair => {
  2640. l.ResourceBarrier(&[transition(&self.other, target, read)]);
  2641. l.ResourceBarrier(&[transition(&self.other, read, target)]);
  2642. }
  2643. Between::DepthMove => {
  2644. let (from, to) = if odd == 0 { (written, tested) } else { (tested, written) };
  2645. l.ResourceBarrier(&[transition(&self.depth, from, to)]);
  2646. }
  2647. Between::Heaps => {
  2648. l.SetDescriptorHeaps(&self.heap_pairs[odd]);
  2649. l.SetGraphicsRootDescriptorTable(0, self.tables[odd]);
  2650. }
  2651. Between::Targets => {
  2652. l.OMSetRenderTargets(1, Some(&self.targets[odd]), false, Some(&self.depth_tested));
  2653. }
  2654. Between::Compute | Between::ComputeWithWaits => {
  2655. let waits = between == Between::ComputeWithWaits;
  2656. if waits {
  2657. l.ResourceBarrier(&[super::uav_barrier()]);
  2658. }
  2659. l.SetComputeRootSignature(&self.work_root);
  2660. l.SetPipelineState(&self.work);
  2661. l.SetComputeRootUnorderedAccessView(0, self.words.GetGPUVirtualAddress());
  2662. l.Dispatch(1, 1, 1);
  2663. if waits {
  2664. l.ResourceBarrier(&[super::uav_barrier()]);
  2665. }
  2666. l.SetPipelineState(&self.pipelines[0]);
  2667. }
  2668. }
  2669. l.DrawInstanced(3, 1, 0, 0);
  2670. drawn += 1;
  2671. }
  2672. if part + 1 < lists {
  2673. // The next list of the batch: this one is sent on
  2674. // its own and the list is opened again at once
  2675. // (the allocator is not reset before the card is
  2676. // done with all of them).
  2677. l.Close().unwrap();
  2678. let run: ID3D12CommandList = l.cast().unwrap();
  2679. self.queue.ExecuteCommandLists(&[Some(run)]);
  2680. l.Reset(&self.allocator, None).unwrap();
  2681. } else {
  2682. l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1);
  2683. l.ResolveQueryData(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &self.back, 0);
  2684. }
  2685. }
  2686. }
  2687. let recording = started.elapsed().as_secs_f64() * 1e3;
  2688. self.finish();
  2689. let mut data = std::ptr::null_mut();
  2690. let range = D3D12_RANGE { Begin: 0, End: 16 };
  2691. // SAFETY: a read-back buffer the finished list resolved two
  2692. // timestamps into.
  2693. let ticks = unsafe {
  2694. self.back.Map(0, Some(&range), Some(&mut data)).unwrap();
  2695. let stamps = std::slice::from_raw_parts(data.cast::<u64>(), 2).to_vec();
  2696. self.back.Unmap(0, None);
  2697. stamps[1].saturating_sub(stamps[0])
  2698. };
  2699. // SAFETY: a plain query of our queue.
  2700. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1).max(1);
  2701. (ticks as f64 * 1e6 / frequency as f64 / f64::from(drawn.max(1)), recording)
  2702. }
  2703. }
  2704. #[test]
  2705. #[ignore = "a measurement on the card: run it by name with --ignored --nocapture"]
  2706. fn bare_command_cost() {
  2707. let Some(mut rig) = Rig::new() else {
  2708. eprintln!("no hardware adapter, or our shaders did not compile; skipped");
  2709. return;
  2710. };
  2711. eprintln!("bare command cost on {}: {DRAWS} one-triangle draws into {WIDTH}x{HEIGHT}, three batches each", rig.card);
  2712. // The first batch pays for whatever the driver does at first use.
  2713. rig.batch(Between::Nothing, 1);
  2714. let variants = [
  2715. ("(a) nothing changes between draws", Between::Nothing, 1),
  2716. ("(b) another pipeline every draw", Between::Pipeline, 1),
  2717. ("(c) a barrier pair on a second texture every draw", Between::BarrierPair, 1),
  2718. ("(d) the tested depth texture moved between write and read every draw", Between::DepthMove, 1),
  2719. ("(e) another pair of descriptor heaps every draw", Between::Heaps, 1),
  2720. ("(f) another colour target every draw", Between::Targets, 1),
  2721. ("(g) nothing changes, in 100 lists run one by one", Between::Nothing, 100),
  2722. ("(h) a compute pass of ours of one group before every draw", Between::Compute, 1),
  2723. ("(i) the same pass between two waits for earlier shader writes", Between::ComputeWithWaits, 1),
  2724. ];
  2725. let mut least = Vec::new();
  2726. for (name, between, lists) in variants {
  2727. let mut runs: Vec<(f64, f64)> = (0..3).map(|_| rig.batch(between, lists)).collect();
  2728. runs.sort_by(|a, b| a.0.total_cmp(&b.0));
  2729. eprintln!(
  2730. "{name}: {:.2} microseconds a draw on the card (the three: {:.2}, {:.2}, {:.2}); recording took {:.1} ms",
  2731. runs[0].0, runs[0].0, runs[1].0, runs[2].0, runs[0].1
  2732. );
  2733. least.push(runs[0].0);
  2734. }
  2735. assert!(least.iter().all(|us| us.is_finite() && *us > 0.0), "the card gave no time for a batch");
  2736. }
  2737. }