indirect.rs 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817
  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. //! When a count buffer is given, threads at or past `min(max, count)` return
  12. //! immediately without charging the list's budget or reading uninitialized
  13. //! tail slots. Each list has a budget (2^27 vertex instances or threads,
  14. //! groups counted as 64 threads, mesh groups as 128): active records past it
  15. //! run empty, saturating without 32-bit wraparound so a list of thousands of
  16. //! garbage records cannot run for seconds either.
  17. //!
  18. //! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535
  19. //! groups per dimension and 2^20 per dispatch, one-dimensional mesh
  20. //! dispatches, the budget) cut legitimate work beyond them; raise them if
  21. //! the title needs more.
  22. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  23. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  24. use windows::Win32::Graphics::Direct3D12::*;
  25. use windows::core::s;
  26. use crate::host::{HostList, host, transition};
  27. const SOURCE: &str = r#"
  28. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)"
  29. cbuffer Record : register(b0) {
  30. uint kind;
  31. uint stride;
  32. uint records;
  33. uint args_offset;
  34. // Bit 0: a count buffer bounds the records. Bit 1: the records are a
  35. // window clamped ahead of their draws: one that asks for more than can
  36. // run is left empty and costs nothing.
  37. uint has_count;
  38. uint count_offset;
  39. };
  40. ByteAddressBuffer src_args : register(t0);
  41. ByteAddressBuffer count_buf : register(t1);
  42. RWByteAddressBuffer dst_args : register(u0);
  43. // The list's work so far (vertex instances, threads): past the budget,
  44. // records run empty.
  45. RWByteAddressBuffer budget : register(u1);
  46. static const uint BUDGET = 1u << 27;
  47. // Groups of one dispatch; more run empty.
  48. static const uint GROUPS = 1u << 20;
  49. [RootSignature(RS)]
  50. [numthreads(64, 1, 1)]
  51. void main(uint3 id : SV_DispatchThreadID) {
  52. uint eff_count = records;
  53. bool ahead = (has_count & 2u) != 0;
  54. if ((has_count & 1u) != 0) {
  55. eff_count = min(eff_count, count_buf.Load(count_offset));
  56. }
  57. if (id.x >= eff_count) return;
  58. uint src_at = args_offset + id.x * stride;
  59. uint dst_at = id.x * stride;
  60. uint cost;
  61. uint2 draw_counts = uint2(0, 0);
  62. uint3 groups = uint3(0, 0, 0);
  63. if (kind <= 1) {
  64. // Draws: vertex or index count, then instances.
  65. uint2 asked = src_args.Load2(src_at);
  66. if (ahead && (asked.x > (1u << 24) || asked.y > (1u << 24))) {
  67. asked = uint2(0, 0);
  68. }
  69. uint count = min(asked.x, 1u << 24);
  70. uint instances = min(asked.y, (1u << 26) / max(count, 1u));
  71. cost = count * instances;
  72. draw_counts = uint2(count, instances);
  73. } else if (kind == 2) {
  74. uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u));
  75. // x * y fits 32 bits; the whole count may not.
  76. if (g.z != 0 && g.x * g.y > GROUPS / g.z) {
  77. g = uint3(0, 0, 0);
  78. }
  79. cost = g.x * g.y * g.z * 64u;
  80. groups = g;
  81. } else {
  82. // Mesh dispatches: the console's are one-dimensional.
  83. uint3 g = src_args.Load3(src_at);
  84. // Ahead of its draw, a record over the most a dispatch runs is a
  85. // slot the title has not filled (the title leaves all
  86. // ones there): empty, and not counted below either.
  87. if (ahead && g.x > 65535u) {
  88. g = uint3(0, 0, 0);
  89. }
  90. // Diagnostics, in the budget buffer's next words: the largest
  91. // group count a mesh record asked for, and the groups asked in all.
  92. uint was;
  93. budget.InterlockedMax(4, g.x, was);
  94. budget.InterlockedAdd(8, min(g.x, 1u << 24), was);
  95. g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u));
  96. cost = g.x * g.y * g.z * 128u;
  97. groups = g;
  98. }
  99. bool over = false;
  100. if (cost > 0) {
  101. uint before;
  102. budget.InterlockedOr(0, 0, before);
  103. [allow_uav_condition]
  104. while (before < BUDGET) {
  105. uint next = (BUDGET - before <= cost) ? BUDGET : (before + cost);
  106. uint prev;
  107. budget.InterlockedCompareExchange(0, before, next, prev);
  108. if (prev == before) break;
  109. before = prev;
  110. }
  111. over = before >= BUDGET || BUDGET - before < cost;
  112. }
  113. if (kind <= 1) {
  114. if (over) {
  115. draw_counts = uint2(0, 0);
  116. }
  117. dst_args.Store2(dst_at, draw_counts);
  118. for (uint off = 8; off < stride; off += 4) {
  119. dst_args.Store(dst_at + off, src_args.Load(src_at + off));
  120. }
  121. } else {
  122. if (over) {
  123. groups = uint3(0, 0, 0);
  124. }
  125. dst_args.Store3(dst_at, groups);
  126. for (uint off = 12; off < stride; off += 4) {
  127. dst_args.Store(dst_at + off, src_args.Load(src_at + off));
  128. }
  129. }
  130. }
  131. "#;
  132. struct Clamp {
  133. root: ID3D12RootSignature,
  134. pso: ID3D12PipelineState,
  135. }
  136. // SAFETY: D3D12 objects are free-threaded.
  137. unsafe impl Send for Clamp {}
  138. // SAFETY: as above.
  139. unsafe impl Sync for Clamp {}
  140. fn clamp() -> Option<&'static Clamp> {
  141. static CLAMP: std::sync::OnceLock<Option<Clamp>> = std::sync::OnceLock::new();
  142. CLAMP
  143. .get_or_init(|| match make() {
  144. Ok(c) => Some(c),
  145. Err(e) => {
  146. tracing::warn!(error = %e, "no argument clamp: indirect execution dropped");
  147. None
  148. }
  149. })
  150. .as_ref()
  151. }
  152. fn make() -> windows::core::Result<Clamp> {
  153. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  154. make_for(device)
  155. }
  156. fn make_for(device: &ID3D12Device) -> windows::core::Result<Clamp> {
  157. let mut code: Option<ID3DBlob> = None;
  158. let mut errors: Option<ID3DBlob> = None;
  159. // SAFETY: the source and names live through the call; out pointers ours.
  160. let compiled = unsafe {
  161. D3DCompile(
  162. SOURCE.as_ptr().cast(),
  163. SOURCE.len(),
  164. s!("clamp"),
  165. None,
  166. None,
  167. s!("main"),
  168. s!("cs_5_1"),
  169. 0,
  170. 0,
  171. &mut code,
  172. Some(&mut errors),
  173. )
  174. };
  175. if let Err(e) = compiled {
  176. if let Some(errors) = errors {
  177. // SAFETY: the blob's own bytes.
  178. let text = unsafe {
  179. std::slice::from_raw_parts(
  180. errors.GetBufferPointer().cast::<u8>(),
  181. errors.GetBufferSize(),
  182. )
  183. };
  184. tracing::warn!("argument clamp: {}", String::from_utf8_lossy(text));
  185. }
  186. return Err(e);
  187. }
  188. let code = code.ok_or_else(windows::core::Error::empty)?;
  189. // SAFETY: the blob's own bytes; the root signature is inside the shader.
  190. unsafe {
  191. let bytes =
  192. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  193. let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?;
  194. let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  195. pRootSignature: std::mem::transmute_copy(&root),
  196. CS: D3D12_SHADER_BYTECODE {
  197. pShaderBytecode: bytes.as_ptr().cast(),
  198. BytecodeLength: bytes.len(),
  199. },
  200. ..Default::default()
  201. })?;
  202. Ok(Clamp { root, pso })
  203. }
  204. }
  205. /// Minimum record byte stride for a supported PC indirect argument `kind`.
  206. fn min_stride(kind: u32) -> Option<u32> {
  207. match kind {
  208. 0 => Some(16),
  209. 1 => Some(20),
  210. 2 | 10 => Some(12),
  211. _ => None,
  212. }
  213. }
  214. /// Validates record alignment and returns the scratch byte size `stride * records`.
  215. fn validate_layout(
  216. (kind, stride, records): (u32, u32, u32),
  217. src_offset: u64,
  218. count_offset: Option<u64>,
  219. ) -> Option<u64> {
  220. let min = min_stride(kind)?;
  221. if stride < min || !stride.is_multiple_of(4) || !src_offset.is_multiple_of(4) {
  222. return None;
  223. }
  224. if count_offset.is_some_and(|off| !off.is_multiple_of(4)) {
  225. return None;
  226. }
  227. let bytes = u64::from(stride).checked_mul(u64::from(records))?;
  228. (bytes <= u64::from(u32::MAX)).then_some(bytes)
  229. }
  230. /// Records, in `list`, the non-destructive clamp of up to `records` records of
  231. /// `kind` (PC argument numbering) `stride` bytes apart from `src` (and bounded
  232. /// by the 32-bit count in `count` when given) into a device-local scratch
  233. /// buffer, leaving that scratch buffer in `INDIRECT_ARGUMENT` at offset `0`.
  234. /// Replaces the list's compute root signature and pipeline (callers bind
  235. /// theirs after). `None` if the clamp or alignment is not available.
  236. pub(crate) fn bound(
  237. list: &HostList,
  238. src: (&ID3D12Resource, u64),
  239. count: Option<(&ID3D12Resource, u64)>,
  240. spec: (u32, u32, u32),
  241. ) -> Option<ID3D12Resource> {
  242. let bytes = validate_layout(spec, src.1, count.map(|(_, off)| off))?;
  243. let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?);
  244. record_clamp(c, &list.list, &dst, budget, src, count, spec).then_some(dst)
  245. }
  246. /// [`bound`] for a window of records clamped ahead of the draws that will
  247. /// read them (`crate::draw`'s windows; no count buffer). The records past
  248. /// the ones the title filled are whatever the buffer holds, and each
  249. /// record clamped charges the list's budget when it is clamped: a slot of
  250. /// all ones, clamped to the most a mesh dispatch runs (65,535 groups),
  251. /// charged a sixteenth of the budget, so sixteen of them emptied every
  252. /// draw of the list after them (run 93: "the largest group count asked for
  253. /// 4294967295", 43 to 153 such records a frame). Here a record that asks
  254. /// for more than can run is left empty and charges nothing; a record
  255. /// clamped alone is clamped and charged as before.
  256. pub(crate) fn bound_ahead(
  257. list: &HostList,
  258. src: (&ID3D12Resource, u64),
  259. spec: (u32, u32, u32),
  260. ) -> Option<ID3D12Resource> {
  261. let bytes = validate_layout(spec, src.1, None)?;
  262. let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?);
  263. record_clamp_as(c, &list.list, &dst, budget, src, None, spec, true).then_some(dst)
  264. }
  265. fn record_clamp(
  266. c: &Clamp,
  267. l: &ID3D12GraphicsCommandList,
  268. dst: &ID3D12Resource,
  269. budget: u64,
  270. src: (&ID3D12Resource, u64),
  271. count: Option<(&ID3D12Resource, u64)>,
  272. spec: (u32, u32, u32),
  273. ) -> bool {
  274. record_clamp_as(c, l, dst, budget, src, count, spec, false)
  275. }
  276. /// [`record_clamp`]; `ahead`: the records are a window clamped ahead of
  277. /// their draws ([`bound_ahead`]).
  278. #[allow(clippy::too_many_arguments)]
  279. fn record_clamp_as(
  280. c: &Clamp,
  281. l: &ID3D12GraphicsCommandList,
  282. dst: &ID3D12Resource,
  283. budget: u64,
  284. (src, src_offset): (&ID3D12Resource, u64),
  285. count: Option<(&ID3D12Resource, u64)>,
  286. (kind, stride, records): (u32, u32, u32),
  287. ahead: bool,
  288. ) -> bool {
  289. let Some(bytes) = validate_layout(
  290. (kind, stride, records),
  291. src_offset,
  292. count.map(|(_, off)| off),
  293. ) else {
  294. return false;
  295. };
  296. // SAFETY: live D3D12 buffer resources.
  297. let (src_base, dst_gpu) = unsafe { (src.GetGPUVirtualAddress(), dst.GetGPUVirtualAddress()) };
  298. if !src_base.is_multiple_of(4) || !dst_gpu.is_multiple_of(4) || !budget.is_multiple_of(4) {
  299. return false;
  300. }
  301. let (src_gpu, args_offset) = match src_offset
  302. .checked_add(bytes)
  303. .filter(|&end| end <= u64::from(u32::MAX))
  304. {
  305. Some(_) => (src_base, src_offset as u32),
  306. None => {
  307. let Some(rebased) = src_base.checked_add(src_offset) else {
  308. return false;
  309. };
  310. (rebased, 0)
  311. }
  312. };
  313. let (count_gpu, has_count, count_offset) = match count {
  314. Some((buf, off)) => {
  315. // SAFETY: a live D3D12 buffer resource.
  316. let base = unsafe { buf.GetGPUVirtualAddress() };
  317. if !base.is_multiple_of(4) {
  318. return false;
  319. }
  320. match off.checked_add(4).filter(|&end| end <= u64::from(u32::MAX)) {
  321. Some(_) => (base, 1u32, off as u32),
  322. None => {
  323. let Some(rebased) = base.checked_add(off) else {
  324. return false;
  325. };
  326. (rebased, 1u32, 0u32)
  327. }
  328. }
  329. }
  330. None => (src_gpu, 0u32, 0u32),
  331. };
  332. let constants = [kind, stride, records, args_offset, has_count | (u32::from(ahead) << 1), count_offset];
  333. // SAFETY: an open list; our root signature and pipeline; live source,
  334. // count, scratch destination, and budget buffers. `src` and `count` stay
  335. // in `COMMON` / `GENERIC_READ` via implicit buffer promotion while `dst`
  336. // transitions `COMMON -> UNORDERED_ACCESS -> INDIRECT_ARGUMENT`.
  337. // Diagnostics: counted; `VICTORY_BARRIER_TEST=indirect` leaves the two
  338. // waits for every earlier shader write out (the state changes stay).
  339. #[cfg(feature = "diagnostics")]
  340. crate::copystat::add(crate::copystat::C::IndirectBounded, 1);
  341. #[cfg(feature = "diagnostics")]
  342. let waits = crate::copystat::barrier_test() & 2 == 0;
  343. #[cfg(not(feature = "diagnostics"))]
  344. let waits = true;
  345. let first = [
  346. uav_barrier(),
  347. transition(
  348. dst,
  349. D3D12_RESOURCE_STATE_COMMON,
  350. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  351. ),
  352. ];
  353. let second = [
  354. uav_barrier(),
  355. transition(
  356. dst,
  357. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  358. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  359. ),
  360. ];
  361. let skip = usize::from(!waits);
  362. unsafe {
  363. // Earlier shader writes (the title's argument and count passes) first.
  364. l.ResourceBarrier(&first[skip..]);
  365. if records > 0 {
  366. l.SetComputeRootSignature(&c.root);
  367. l.SetPipelineState(&c.pso);
  368. l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  369. l.SetComputeRootShaderResourceView(1, src_gpu);
  370. l.SetComputeRootShaderResourceView(2, count_gpu);
  371. l.SetComputeRootUnorderedAccessView(3, dst_gpu);
  372. l.SetComputeRootUnorderedAccessView(4, budget);
  373. l.Dispatch(records.div_ceil(64), 1, 1);
  374. }
  375. l.ResourceBarrier(&second[skip..]);
  376. }
  377. true
  378. }
  379. /// After indirect execution (or if preparation failed after [`bound`]):
  380. /// returns the scratch buffer to the common state for the next call.
  381. pub(crate) fn done(list: &HostList, scratch: &ID3D12Resource) {
  382. done_on(&list.list, scratch);
  383. }
  384. fn done_on(list: &ID3D12GraphicsCommandList, scratch: &ID3D12Resource) {
  385. // SAFETY: an open list and a live scratch buffer in INDIRECT_ARGUMENT.
  386. unsafe {
  387. list.ResourceBarrier(&[transition(
  388. scratch,
  389. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  390. D3D12_RESOURCE_STATE_COMMON,
  391. )])
  392. };
  393. }
  394. fn uav_barrier() -> D3D12_RESOURCE_BARRIER {
  395. D3D12_RESOURCE_BARRIER {
  396. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  397. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  398. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  399. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  400. pResource: std::mem::ManuallyDrop::new(None),
  401. }),
  402. },
  403. }
  404. }
  405. #[cfg(test)]
  406. mod tests {
  407. use super::*;
  408. use windows::Win32::Foundation::HANDLE;
  409. use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
  410. use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC;
  411. use windows::Win32::Graphics::Dxgi::*;
  412. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  413. use windows::core::Interface;
  414. const WORKER_CS: &str = r#"
  415. #define RS "UAV(u0)"
  416. RWByteAddressBuffer hits : register(u0);
  417. [RootSignature(RS)]
  418. [numthreads(1, 1, 1)]
  419. void main() {
  420. uint prev;
  421. hits.InterlockedAdd(0, 1, prev);
  422. }
  423. "#;
  424. struct WarpHarness {
  425. device: ID3D12Device,
  426. queue: ID3D12CommandQueue,
  427. allocator: ID3D12CommandAllocator,
  428. list: ID3D12GraphicsCommandList,
  429. fence: ID3D12Fence,
  430. submitted: u64,
  431. event: HANDLE,
  432. clamp: Clamp,
  433. worker: Clamp,
  434. }
  435. impl WarpHarness {
  436. fn new() -> Option<Self> {
  437. // SAFETY: plain DXGI WARP query and D3D12 test harness setup.
  438. unsafe {
  439. let factory: IDXGIFactory4 =
  440. CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?;
  441. let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?;
  442. let desc = adapter.cast::<IDXGIAdapter1>().ok()?.GetDesc1().ok()?;
  443. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
  444. return None;
  445. }
  446. let mut device: Option<ID3D12Device> = None;
  447. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?;
  448. let device = device?;
  449. let queue: ID3D12CommandQueue = device
  450. .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  451. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  452. ..Default::default()
  453. })
  454. .ok()?;
  455. let allocator: ID3D12CommandAllocator = device
  456. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)
  457. .ok()?;
  458. let list: ID3D12GraphicsCommandList = device
  459. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)
  460. .ok()?;
  461. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  462. let event = CreateEventW(None, false, false, None).ok()?;
  463. let clamp = make_for(&device).expect("clamp shader must compile on WARP");
  464. let worker = compile_cs(&device, WORKER_CS).expect("worker shader must compile");
  465. Some(Self {
  466. device,
  467. queue,
  468. allocator,
  469. list,
  470. fence,
  471. submitted: 0,
  472. event,
  473. clamp,
  474. worker,
  475. })
  476. }
  477. }
  478. /// CPU-mapped L0 write-back buffer matching `Shadow`'s heap type.
  479. fn shared_buffer(&self, size: u64) -> (ID3D12Resource, *mut u8, u64) {
  480. let heap = D3D12_HEAP_PROPERTIES {
  481. Type: D3D12_HEAP_TYPE_CUSTOM,
  482. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  483. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  484. ..Default::default()
  485. };
  486. let desc = D3D12_RESOURCE_DESC {
  487. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  488. Width: size.max(4),
  489. Height: 1,
  490. DepthOrArraySize: 1,
  491. MipLevels: 1,
  492. SampleDesc: DXGI_SAMPLE_DESC {
  493. Count: 1,
  494. Quality: 0,
  495. },
  496. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  497. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  498. ..Default::default()
  499. };
  500. let mut buffer: Option<ID3D12Resource> = None;
  501. let mut data = std::ptr::null_mut();
  502. // SAFETY: plain buffer creation and persistent CPU mapping.
  503. unsafe {
  504. self.device
  505. .CreateCommittedResource(
  506. &heap,
  507. D3D12_HEAP_FLAG_NONE,
  508. &desc,
  509. D3D12_RESOURCE_STATE_COMMON,
  510. None,
  511. &mut buffer,
  512. )
  513. .unwrap();
  514. let buffer = buffer.unwrap();
  515. buffer.Map(0, None, Some(&mut data)).unwrap();
  516. let gpu = buffer.GetGPUVirtualAddress();
  517. (buffer, data.cast(), gpu)
  518. }
  519. }
  520. /// Device-local `DEFAULT`-heap UAV scratch buffer.
  521. fn default_uav(&self, size: u64) -> ID3D12Resource {
  522. let heap = D3D12_HEAP_PROPERTIES {
  523. Type: D3D12_HEAP_TYPE_DEFAULT,
  524. ..Default::default()
  525. };
  526. let desc = D3D12_RESOURCE_DESC {
  527. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  528. Width: size.max(64 << 10),
  529. Height: 1,
  530. DepthOrArraySize: 1,
  531. MipLevels: 1,
  532. SampleDesc: DXGI_SAMPLE_DESC {
  533. Count: 1,
  534. Quality: 0,
  535. },
  536. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  537. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  538. ..Default::default()
  539. };
  540. let mut buffer: Option<ID3D12Resource> = None;
  541. // SAFETY: plain device-local buffer creation.
  542. unsafe {
  543. self.device
  544. .CreateCommittedResource(
  545. &heap,
  546. D3D12_HEAP_FLAG_NONE,
  547. &desc,
  548. D3D12_RESOURCE_STATE_COMMON,
  549. None,
  550. &mut buffer,
  551. )
  552. .unwrap();
  553. }
  554. buffer.unwrap()
  555. }
  556. fn signature(&self, kind: u32, stride: u32) -> ID3D12CommandSignature {
  557. let arg = D3D12_INDIRECT_ARGUMENT_DESC {
  558. Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32),
  559. ..Default::default()
  560. };
  561. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  562. ByteStride: stride,
  563. NumArgumentDescs: 1,
  564. pArgumentDescs: &arg,
  565. NodeMask: 0,
  566. };
  567. let mut sig: Option<ID3D12CommandSignature> = None;
  568. // SAFETY: valid single-argument command signature description.
  569. unsafe {
  570. self.device
  571. .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig)
  572. .unwrap();
  573. }
  574. sig.unwrap()
  575. }
  576. fn submit_and_wait(&mut self) {
  577. self.submitted += 1;
  578. // SAFETY: closing, executing, waiting on fence, and resetting our list.
  579. unsafe {
  580. self.list.Close().unwrap();
  581. let cmd: ID3D12CommandList = self.list.cast().unwrap();
  582. self.queue.ExecuteCommandLists(&[Some(cmd)]);
  583. self.queue.Signal(&self.fence, self.submitted).unwrap();
  584. self.fence
  585. .SetEventOnCompletion(self.submitted, self.event)
  586. .unwrap();
  587. WaitForSingleObject(self.event, INFINITE);
  588. self.allocator.Reset().unwrap();
  589. self.list.Reset(&self.allocator, None).unwrap();
  590. }
  591. }
  592. }
  593. fn compile_cs(device: &ID3D12Device, source: &str) -> windows::core::Result<Clamp> {
  594. let mut code: Option<ID3DBlob> = None;
  595. // SAFETY: source and entry names outlive `D3DCompile`.
  596. unsafe {
  597. D3DCompile(
  598. source.as_ptr().cast(),
  599. source.len(),
  600. s!("worker"),
  601. None,
  602. None,
  603. s!("main"),
  604. s!("cs_5_1"),
  605. 0,
  606. 0,
  607. &mut code,
  608. None,
  609. )?;
  610. let code = code.unwrap();
  611. let bytes = std::slice::from_raw_parts(
  612. code.GetBufferPointer().cast::<u8>(),
  613. code.GetBufferSize(),
  614. );
  615. let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?;
  616. let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  617. pRootSignature: std::mem::transmute_copy(&root),
  618. CS: D3D12_SHADER_BYTECODE {
  619. pShaderBytecode: bytes.as_ptr().cast(),
  620. BytecodeLength: bytes.len(),
  621. },
  622. ..Default::default()
  623. })?;
  624. Ok(Clamp { root, pso })
  625. }
  626. }
  627. /// The compare of copies in the card's memory (`crate::host`), on the
  628. /// software adapter. Told 1 it flags the pieces whose bytes are not
  629. /// what was hashed last and leaves the hashes: a piece a shader changed
  630. /// and a later one changed back then looks untouched, which is right
  631. /// only if the piece was fetched after both. Told 2 (submissions sent
  632. /// ahead with the relay, whose pieces are fetched flight by flight) it
  633. /// stores the hash it made: each compare flags what changed since the
  634. /// compare before it, also a change back.
  635. #[test]
  636. fn warp_card_compare_stores_the_hash_it_made_when_told() {
  637. let Some(mut warp) = WarpHarness::new() else {
  638. return;
  639. };
  640. let compare = compile_cs(&warp.device, crate::host::CARD_COMPARE).expect("the card compare must compile on WARP");
  641. const PIECE: usize = 64 << 10;
  642. const PIECES: u32 = 3;
  643. let size = PIECE * PIECES as usize;
  644. let (_now, now_ptr, now_gpu) = warp.shared_buffer(size as u64);
  645. let (_hashes, _, hashes_gpu) = warp.shared_buffer(16 * u64::from(PIECES));
  646. let (_differs, differs_ptr, differs_gpu) = warp.shared_buffer(64);
  647. let content: Vec<u8> = (0..size).map(|i| (i * 31 + i / 251) as u8).collect();
  648. // SAFETY: the mapping holds `size` bytes.
  649. unsafe { std::ptr::copy_nonoverlapping(content.as_ptr(), now_ptr, size) };
  650. // One pass over the three pieces; what it left in `differs` (7s
  651. // where it stored nothing).
  652. let run = |warp: &mut WarpHarness, mode: u32| -> [u32; 3] {
  653. // SAFETY: our open list, live buffers, the compare's own root
  654. // signature; the mappings hold what is read and written.
  655. unsafe {
  656. for piece in 0..PIECES as usize {
  657. differs_ptr.cast::<u32>().add(piece).write_volatile(7);
  658. }
  659. warp.list.SetComputeRootSignature(&compare.root);
  660. warp.list.SetPipelineState(&compare.pso);
  661. let constants = [0u32, 0, size as u32, PIECES, 0, mode];
  662. warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  663. warp.list.SetComputeRootShaderResourceView(1, now_gpu);
  664. warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu);
  665. warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu);
  666. warp.list.Dispatch(PIECES.div_ceil(64), 1, 1);
  667. }
  668. warp.submit_and_wait();
  669. // SAFETY: as above.
  670. [0, 1, 2].map(|piece| unsafe { differs_ptr.cast::<u32>().add(piece).read_volatile() })
  671. };
  672. let at = PIECE + 1234;
  673. // SAFETY (each): inside the mapping.
  674. let set = |value: u8| unsafe { now_ptr.add(at).write_volatile(value) };
  675. // 0: the hashes are stored, nothing is flagged.
  676. assert_eq!(run(&mut warp, 0), [7, 7, 7]);
  677. assert_eq!(run(&mut warp, 1), [0, 0, 0]);
  678. // A change in the second piece: flagged, and with 1 flagged again
  679. // (the hash stays the old one).
  680. set(content[at] ^ 0x40);
  681. assert_eq!(run(&mut warp, 1), [0, 1, 0]);
  682. assert_eq!(run(&mut warp, 1), [0, 1, 0]);
  683. // Changed back: with 1 the piece looks untouched.
  684. set(content[at]);
  685. assert_eq!(run(&mut warp, 1), [0, 0, 0]);
  686. // With 2 the change is flagged once, and the hash is the new one.
  687. set(content[at] ^ 0x40);
  688. assert_eq!(run(&mut warp, 2), [0, 1, 0]);
  689. assert_eq!(run(&mut warp, 2), [0, 0, 0]);
  690. // Changed back: flagged, where 1 saw nothing.
  691. set(content[at]);
  692. assert_eq!(run(&mut warp, 2), [0, 1, 0]);
  693. assert_eq!(run(&mut warp, 2), [0, 0, 0]);
  694. }
  695. /// The clamp compiles with the system's compiler and the host takes it.
  696. #[test]
  697. fn argument_clamp_builds() {
  698. if super::host().is_none() {
  699. return; // no host GPU here
  700. }
  701. assert!(super::clamp().is_some());
  702. }
  703. #[test]
  704. fn rejects_unaligned_or_undersized_layouts() {
  705. assert_eq!(validate_layout((0, 16, 4), 0, None), Some(64));
  706. assert_eq!(validate_layout((1, 20, 4), 64, Some(128)), Some(80));
  707. assert_eq!(validate_layout((2, 12, 0), 0, Some(0)), Some(0));
  708. assert_eq!(validate_layout((10, 16, 2), 8, None), Some(32));
  709. // Undersized strides for each kind.
  710. assert_eq!(validate_layout((0, 12, 1), 0, None), None);
  711. assert_eq!(validate_layout((1, 16, 1), 0, None), None);
  712. assert_eq!(validate_layout((2, 8, 1), 0, None), None);
  713. assert_eq!(validate_layout((10, 8, 1), 0, None), None);
  714. // Unknown kind.
  715. assert_eq!(validate_layout((3, 16, 1), 0, None), None);
  716. // Unaligned stride, source offset, or count offset.
  717. assert_eq!(validate_layout((0, 18, 1), 0, None), None);
  718. assert_eq!(validate_layout((0, 16, 1), 2, None), None);
  719. assert_eq!(validate_layout((0, 16, 1), 0, Some(6)), None);
  720. // Total byte size exceeding 32-bit ByteAddressBuffer indexing.
  721. assert_eq!(validate_layout((1, 20, u32::MAX), 0, None), None);
  722. }
  723. /// WARP D3D12 execution test proving:
  724. /// (a) `countBuffer` with a small count (`3`) and `4,093` garbage tail slots
  725. /// (`max = 4096`) does NOT blow `BUDGET` or zero valid dispatches in
  726. /// this or subsequent `ExecuteIndirect` calls in the same list,
  727. /// (b) `src_args` (and `count_buf`) are NOT mutated in-place, and
  728. /// (c) full `stride` bytes (`stride = 24` > `12`) are copied for active
  729. /// records into `dst_args` at offset `0`.
  730. #[test]
  731. fn warp_count_buffer_ignores_garbage_tail_and_preserves_source() {
  732. let Some(mut warp) = WarpHarness::new() else {
  733. return;
  734. };
  735. const KIND_DISPATCH: u32 = 2;
  736. const STRIDE: u32 = 24; // 6 dwords: 3 dispatch group counts + 3 extra payload dwords
  737. const MAX: u32 = 4096;
  738. const ARGS_OFFSET: usize = 64; // non-zero offset with sentinel prefix
  739. const COUNT_OFFSET_1: usize = 128;
  740. const COUNT_OFFSET_2: usize = 192;
  741. let src_bytes = ARGS_OFFSET + (STRIDE as usize) * (MAX as usize) + 64;
  742. let (src_buf, src_ptr, _) = warp.shared_buffer(src_bytes as u64);
  743. let (count_buf, count_ptr, _) = warp.shared_buffer(512);
  744. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  745. let (_hits_buf, hits_ptr, hits_gpu) = warp.shared_buffer(256);
  746. let (readback_buf, readback_ptr, _) = warp.shared_buffer((STRIDE * 8) as u64);
  747. let dst_buf = warp.default_uav(u64::from(STRIDE) * u64::from(MAX));
  748. let sig = warp.signature(KIND_DISPATCH, STRIDE);
  749. // Fill the entire source buffer with non-zero sentinel bytes, then
  750. // populate 3 valid records at `ARGS_OFFSET` and 4,093 huge garbage
  751. // records in `3..MAX` that would exhaust `BUDGET` ~2,000x over if read.
  752. let mut initial_src = vec![0xA5u8; src_bytes];
  753. let write_record = |buf: &mut [u8], idx: usize, words: [u32; 6]| {
  754. let base = ARGS_OFFSET + idx * (STRIDE as usize);
  755. for (w, val) in words.into_iter().enumerate() {
  756. buf[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes());
  757. }
  758. };
  759. write_record(
  760. &mut initial_src,
  761. 0,
  762. [3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666],
  763. );
  764. write_record(
  765. &mut initial_src,
  766. 1,
  767. [5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC],
  768. );
  769. // Record 2 exceeds 65,535 in X -> clamped to (65535, 1, 1).
  770. write_record(
  771. &mut initial_src,
  772. 2,
  773. [100_000, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567],
  774. );
  775. for slot in 3..MAX as usize {
  776. // Each garbage slot would clamp to 65535 * 16 * 1 = 1,048,560 groups
  777. // (`cost = 67,107,840 ~= BUDGET / 2`), exhausting `BUDGET` immediately!
  778. write_record(
  779. &mut initial_src,
  780. slot,
  781. [0xFFFF_FFFF, 16, 1, 0xDEAD_BEEF, 0xBAD0_C0DE, slot as u32],
  782. );
  783. }
  784. // Second indirect call's source records (at offset 0 of a second buffer,
  785. // or later in `count_buf`): put 2 active records + garbage tail in a
  786. // second range to run back-to-back in the SAME command list.
  787. let mut initial_count = vec![0x5Au8; 512];
  788. initial_count[COUNT_OFFSET_1..COUNT_OFFSET_1 + 4].copy_from_slice(&3u32.to_le_bytes());
  789. initial_count[COUNT_OFFSET_2..COUNT_OFFSET_2 + 4].copy_from_slice(&2u32.to_le_bytes());
  790. // SAFETY: buffers are mapped with exact capacities above.
  791. unsafe {
  792. std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, src_bytes);
  793. std::ptr::copy_nonoverlapping(initial_count.as_ptr(), count_ptr, 512);
  794. (budget_ptr as *mut u32).write_volatile(0);
  795. (hits_ptr as *mut u32).write_volatile(0);
  796. std::ptr::write_bytes(readback_ptr, 0, (STRIDE * 8) as usize);
  797. }
  798. // Record Call #1 (`eff_count = 3` out of `MAX = 4096`), copy the first
  799. // 5 records of `dst_buf` out for inspection, then record Call #2
  800. // (`eff_count = 2` out of `MAX = 4096`) reusing `dst_buf` in the same list!
  801. assert!(record_clamp(
  802. &warp.clamp,
  803. &warp.list,
  804. &dst_buf,
  805. budget_gpu,
  806. (&src_buf, ARGS_OFFSET as u64),
  807. Some((&count_buf, COUNT_OFFSET_1 as u64)),
  808. (KIND_DISPATCH, STRIDE, MAX),
  809. ));
  810. // SAFETY: open command list, valid worker PSO/root and buffers.
  811. unsafe {
  812. warp.list.SetComputeRootSignature(&warp.worker.root);
  813. warp.list.SetPipelineState(&warp.worker.pso);
  814. warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  815. warp.list.ExecuteIndirect(
  816. &sig,
  817. MAX,
  818. &dst_buf,
  819. 0,
  820. Some(&count_buf),
  821. COUNT_OFFSET_1 as u64,
  822. );
  823. }
  824. done_on(&warp.list, &dst_buf);
  825. // Snapshot `dst_buf` after Call #1 (from `COMMON`, copy 5 * STRIDE bytes,
  826. // then return `dst_buf` to `COMMON` before Call #2).
  827. // SAFETY: open command list; `dst_buf` returned to `COMMON` by `done_on`.
  828. unsafe {
  829. warp.list.ResourceBarrier(&[transition(
  830. &dst_buf,
  831. D3D12_RESOURCE_STATE_COMMON,
  832. D3D12_RESOURCE_STATE_COPY_SOURCE,
  833. )]);
  834. warp.list
  835. .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, u64::from(STRIDE * 5));
  836. warp.list.ResourceBarrier(&[transition(
  837. &dst_buf,
  838. D3D12_RESOURCE_STATE_COPY_SOURCE,
  839. D3D12_RESOURCE_STATE_COMMON,
  840. )]);
  841. }
  842. // Call #2 in the SAME command list (`eff_count = 2` -> records 0 and 1:
  843. // 6 + 5 = 11 groups). Would run empty if Call #1's tail blew `BUDGET`!
  844. assert!(record_clamp(
  845. &warp.clamp,
  846. &warp.list,
  847. &dst_buf,
  848. budget_gpu,
  849. (&src_buf, ARGS_OFFSET as u64),
  850. Some((&count_buf, COUNT_OFFSET_2 as u64)),
  851. (KIND_DISPATCH, STRIDE, MAX),
  852. ));
  853. // SAFETY: open command list, valid worker PSO/root and buffers.
  854. unsafe {
  855. warp.list.SetComputeRootSignature(&warp.worker.root);
  856. warp.list.SetPipelineState(&warp.worker.pso);
  857. warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  858. warp.list.ExecuteIndirect(
  859. &sig,
  860. MAX,
  861. &dst_buf,
  862. 0,
  863. Some(&count_buf),
  864. COUNT_OFFSET_2 as u64,
  865. );
  866. }
  867. done_on(&warp.list, &dst_buf);
  868. warp.submit_and_wait();
  869. // SAFETY: GPU execution finished; read mapped host results.
  870. let (hits, spent, after_src, after_count, clamped_words) = unsafe {
  871. let hits = (hits_ptr as *const u32).read_volatile();
  872. let spent = (budget_ptr as *const u32).read_volatile();
  873. let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), src_bytes).to_vec();
  874. let after_count = std::slice::from_raw_parts(count_ptr.cast_const(), 512).to_vec();
  875. let words = std::slice::from_raw_parts(
  876. readback_ptr.cast::<u32>().cast_const(),
  877. (STRIDE as usize / 4) * 5,
  878. )
  879. .to_vec();
  880. (hits, spent, after_src, after_count, words)
  881. };
  882. // Call #1: (3*2*1) + (5*1*1) + (65535*1*1) = 65,546 groups.
  883. // Call #2: (3*2*1) + (5*1*1) = 11 groups.
  884. let expected_groups = (6 + 5 + 65_535) + (6 + 5);
  885. assert_eq!(
  886. hits, expected_groups,
  887. "valid indirect dispatches must all execute"
  888. );
  889. assert_eq!(
  890. spent,
  891. expected_groups * 64,
  892. "budget must reflect only active records below countBuffer"
  893. );
  894. assert_eq!(
  895. after_src, initial_src,
  896. "src_args must never be mutated in-place"
  897. );
  898. assert_eq!(
  899. after_count, initial_count,
  900. "count_buf must never be mutated"
  901. );
  902. // Check `dst_args` records 0..3: clamped group counts + preserved extra stride words.
  903. assert_eq!(
  904. &clamped_words[0..6],
  905. &[3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666]
  906. );
  907. assert_eq!(
  908. &clamped_words[6..12],
  909. &[5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC]
  910. );
  911. assert_eq!(
  912. &clamped_words[12..18],
  913. &[65_535, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567]
  914. );
  915. // Inactive slot 3 was never copied from `src_args`.
  916. assert_ne!(clamped_words[21], 0xDEAD_BEEF);
  917. }
  918. /// WARP D3D12 test proving `BUDGET` saturates without 32-bit unsigned
  919. /// wraparound across >64 huge indexed-draw records (`count = None`), while
  920. /// preserving `StartIndexLocation`, `BaseVertexLocation`,
  921. /// `StartInstanceLocation`, and custom stride padding, and leaving
  922. /// `src_args` untouched.
  923. /// A window of mesh records clamped ahead: the filled ones come out as
  924. /// they are and are charged, the slots of all ones come out empty and
  925. /// charge nothing; clamped as single records the same slots are clamped
  926. /// to the most and spend the budget.
  927. #[test]
  928. fn warp_window_leaves_unfilled_slots_empty_and_uncharged() {
  929. let Some(mut warp) = WarpHarness::new() else {
  930. return;
  931. };
  932. const KIND_MESH: u32 = 10;
  933. const STRIDE: u32 = 32;
  934. const RECORDS: u32 = 16;
  935. let filled = [5u32, 0, 519];
  936. let total = (STRIDE * RECORDS) as usize;
  937. let mut src = vec![0xffu8; total];
  938. for (i, groups) in filled.into_iter().enumerate() {
  939. let words = [groups, 1, 1, 0xAB00 + i as u32];
  940. for (w, word) in words.into_iter().enumerate() {
  941. let at = i * STRIDE as usize + w * 4;
  942. src[at..at + 4].copy_from_slice(&word.to_le_bytes());
  943. }
  944. }
  945. for ahead in [true, false] {
  946. let (src_buf, src_ptr, _) = warp.shared_buffer(total as u64);
  947. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  948. let (readback_buf, readback_ptr, _) = warp.shared_buffer(total as u64);
  949. let dst_buf = warp.default_uav(total as u64);
  950. // SAFETY: mapped buffers of these sizes.
  951. unsafe {
  952. std::ptr::copy_nonoverlapping(src.as_ptr(), src_ptr, total);
  953. std::ptr::write_bytes(budget_ptr, 0, 256);
  954. std::ptr::write_bytes(readback_ptr, 0, total);
  955. }
  956. assert!(record_clamp_as(
  957. &warp.clamp,
  958. &warp.list,
  959. &dst_buf,
  960. budget_gpu,
  961. (&src_buf, 0),
  962. None,
  963. (KIND_MESH, STRIDE, RECORDS),
  964. ahead,
  965. ));
  966. done_on(&warp.list, &dst_buf);
  967. // SAFETY: an open list; the scratch buffer is copied for the check.
  968. unsafe {
  969. warp.list.ResourceBarrier(&[transition(
  970. &dst_buf,
  971. D3D12_RESOURCE_STATE_COMMON,
  972. D3D12_RESOURCE_STATE_COPY_SOURCE,
  973. )]);
  974. warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64);
  975. warp.list.ResourceBarrier(&[transition(
  976. &dst_buf,
  977. D3D12_RESOURCE_STATE_COPY_SOURCE,
  978. D3D12_RESOURCE_STATE_COMMON,
  979. )]);
  980. }
  981. warp.submit_and_wait();
  982. // SAFETY: the work is done; mapped buffers.
  983. let (spent, largest, out) = unsafe {
  984. (
  985. (budget_ptr as *const u32).read_volatile(),
  986. (budget_ptr as *const u32).add(1).read_volatile(),
  987. std::slice::from_raw_parts(readback_ptr.cast::<u32>().cast_const(), total / 4).to_vec(),
  988. )
  989. };
  990. for (i, groups) in filled.into_iter().enumerate() {
  991. let rec = &out[i * 8..i * 8 + 4];
  992. assert_eq!(rec, [groups, u32::from(groups > 0).max(1).min(1), 1, 0xAB00 + i as u32], "filled record {i}, ahead {ahead}");
  993. }
  994. let charged_filled = (5 + 519) * 128;
  995. if ahead {
  996. for i in filled.len()..RECORDS as usize {
  997. assert_eq!(out[i * 8..i * 8 + 3], [0, 0, 0], "unfilled slot {i} must come out empty");
  998. assert_eq!(out[i * 8 + 3], u32::MAX, "the words after the record are copied as they are");
  999. }
  1000. assert_eq!(spent, charged_filled, "unfilled slots charge nothing");
  1001. assert_eq!(largest, 519, "and are not counted as asked for");
  1002. } else {
  1003. // Thirteen slots at 65,535 groups: sixteen would be all of it.
  1004. assert_eq!(spent, charged_filled + 13 * 65535 * 128, "clamped one by one, each slot is charged the most");
  1005. assert_eq!(largest, u32::MAX);
  1006. }
  1007. }
  1008. }
  1009. #[test]
  1010. fn warp_budget_saturates_without_wraparound_and_preserves_draw_fields() {
  1011. let Some(mut warp) = WarpHarness::new() else {
  1012. return;
  1013. };
  1014. const KIND_INDEXED: u32 = 1;
  1015. const STRIDE: u32 = 24; // 5 indexed-draw words + 1 trailing custom word
  1016. const RECORDS: u32 = 128; // 2 waves of 64: old InterlockedAdd wrapped 2^32 at 64!
  1017. const BUDGET_CAP: u32 = 1 << 27;
  1018. let total_bytes = (STRIDE * RECORDS) as usize;
  1019. let (src_buf, src_ptr, _) = warp.shared_buffer(total_bytes as u64);
  1020. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  1021. let (readback_buf, readback_ptr, _) = warp.shared_buffer(total_bytes as u64);
  1022. let dst_buf = warp.default_uav(total_bytes as u64);
  1023. let mut initial_src = vec![0u8; total_bytes];
  1024. for i in 0..RECORDS as usize {
  1025. let words: [u32; 6] = [
  1026. u32::MAX, // IndexCount -> clamps to 1 << 24
  1027. u32::MAX, // InstanceCount -> clamps to 4 (cost = 1 << 26)
  1028. 1000 + i as u32, // StartIndexLocation
  1029. (-200i32 + i as i32) as u32, // BaseVertexLocation
  1030. 5000 + i as u32, // StartInstanceLocation
  1031. 0xCAFE_0000 | (i as u32), // Extra stride word
  1032. ];
  1033. let base = i * (STRIDE as usize);
  1034. for (w, val) in words.into_iter().enumerate() {
  1035. initial_src[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes());
  1036. }
  1037. }
  1038. // SAFETY: mapped buffers have sufficient capacity.
  1039. unsafe {
  1040. std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, total_bytes);
  1041. (budget_ptr as *mut u32).write_volatile(0);
  1042. std::ptr::write_bytes(readback_ptr, 0, total_bytes);
  1043. }
  1044. assert!(record_clamp(
  1045. &warp.clamp,
  1046. &warp.list,
  1047. &dst_buf,
  1048. budget_gpu,
  1049. (&src_buf, 0),
  1050. None,
  1051. (KIND_INDEXED, STRIDE, RECORDS),
  1052. ));
  1053. done_on(&warp.list, &dst_buf);
  1054. // SAFETY: open command list; copy clamped scratch buffer for verification.
  1055. unsafe {
  1056. warp.list.ResourceBarrier(&[transition(
  1057. &dst_buf,
  1058. D3D12_RESOURCE_STATE_COMMON,
  1059. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1060. )]);
  1061. warp.list
  1062. .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total_bytes as u64);
  1063. warp.list.ResourceBarrier(&[transition(
  1064. &dst_buf,
  1065. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1066. D3D12_RESOURCE_STATE_COMMON,
  1067. )]);
  1068. }
  1069. warp.submit_and_wait();
  1070. // SAFETY: GPU work completed.
  1071. let (spent, after_src, out_words) = unsafe {
  1072. let spent = (budget_ptr as *const u32).read_volatile();
  1073. let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), total_bytes).to_vec();
  1074. let out_words = std::slice::from_raw_parts(
  1075. readback_ptr.cast::<u32>().cast_const(),
  1076. total_bytes / 4,
  1077. )
  1078. .to_vec();
  1079. (spent, after_src, out_words)
  1080. };
  1081. assert_eq!(
  1082. spent, BUDGET_CAP,
  1083. "budget must saturate at BUDGET without wrapping"
  1084. );
  1085. assert_eq!(after_src, initial_src, "src_args must remain untouched");
  1086. let mut kept = 0usize;
  1087. let mut zeroed = 0usize;
  1088. for i in 0..RECORDS as usize {
  1089. let rec = &out_words[i * 6..(i + 1) * 6];
  1090. if rec[0] == (1 << 24) && rec[1] == 4 {
  1091. kept += 1;
  1092. } else {
  1093. assert_eq!((rec[0], rec[1]), (0, 0), "excess draw must be zeroed");
  1094. zeroed += 1;
  1095. }
  1096. assert_eq!(rec[2], 1000 + i as u32);
  1097. assert_eq!(rec[3], (-200i32 + i as i32) as u32);
  1098. assert_eq!(rec[4], 5000 + i as u32);
  1099. assert_eq!(rec[5], 0xCAFE_0000 | (i as u32));
  1100. }
  1101. assert_eq!((kept, zeroed), (2, (RECORDS as usize) - 2));
  1102. }
  1103. /// Exercises `HostList::indirect_scratch`, `bound`, `done`, `Host::execute`,
  1104. /// and `HostList::reset` end-to-end on the host device.
  1105. #[test]
  1106. fn host_list_reuses_and_grows_scratch_across_submissions() {
  1107. let Some(host) = super::host() else {
  1108. return;
  1109. };
  1110. let Ok(list) = host.new_list() else {
  1111. return;
  1112. };
  1113. let Some((src_buf, src_ptr)) = host.shared_buffer(256 << 10) else {
  1114. return;
  1115. };
  1116. let Some((count_buf, count_ptr)) = host.shared_buffer(256) else {
  1117. return;
  1118. };
  1119. // SAFETY: mapped host buffers.
  1120. unsafe {
  1121. std::ptr::write_bytes(src_ptr, 0x7F, 256 << 10);
  1122. (count_ptr as *mut u32).write_volatile(2);
  1123. }
  1124. // First two calls fit inside the initial 64 KiB scratch buffer and
  1125. // must reuse the exact same `ID3D12Resource`.
  1126. let b1 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (0, 16, 64)).unwrap();
  1127. done(&list, &b1);
  1128. let b2 = bound(&list, (&src_buf, 64), Some((&count_buf, 0)), (1, 20, 128)).unwrap();
  1129. done(&list, &b2);
  1130. assert_eq!(
  1131. b1.as_raw(),
  1132. b2.as_raw(),
  1133. "scratch buffer within capacity must be reused"
  1134. );
  1135. // A call needing >64 KiB grows the scratch buffer mid-list while keeping
  1136. // `b1` alive until reset.
  1137. let b3 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 5000)).unwrap();
  1138. done(&list, &b3);
  1139. assert_ne!(
  1140. b3.as_raw(),
  1141. b1.as_raw(),
  1142. "larger request must grow scratch buffer"
  1143. );
  1144. list.close();
  1145. host.execute(&[&list]);
  1146. list.reset();
  1147. // After reset, requests up to the grown high-water mark reuse `b3` with
  1148. // zero new allocations.
  1149. let b4 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 4096)).unwrap();
  1150. done(&list, &b4);
  1151. assert_eq!(
  1152. b4.as_raw(),
  1153. b3.as_raw(),
  1154. "grown scratch buffer must persist across reset"
  1155. );
  1156. list.close();
  1157. host.execute(&[&list]);
  1158. list.reset();
  1159. }
  1160. }
  1161. /// What one small draw costs this card, bare and with one thing changed
  1162. /// between every two draws: a measurement, not a check (it asserts only
  1163. /// that the card answered). The timing run of the lit scene (run 187) has
  1164. /// some 11,000 small commands a frame at 5 to 16 microseconds each, and no
  1165. /// log says whether that is what we put around a command or what the card
  1166. /// takes for one. Each variant here is 10,000 one-triangle draws into a
  1167. /// 2560x1440 target, timed on the card by one pair of timestamps around
  1168. /// the whole batch (not one per command, which would time the stamps).
  1169. ///
  1170. /// Run by name, no game needed:
  1171. /// `cargo test -p victory-gpu --release -- --ignored bare_command_cost --nocapture`
  1172. #[cfg(test)]
  1173. mod bare_cost {
  1174. use windows::Win32::Foundation::{HANDLE, RECT};
  1175. use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY};
  1176. use windows::Win32::Graphics::Direct3D12::*;
  1177. use windows::Win32::Graphics::Dxgi::Common::*;
  1178. use windows::Win32::Graphics::Dxgi::*;
  1179. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  1180. use windows::core::{Interface, s};
  1181. use crate::host::{compile, transition};
  1182. /// Draws in a batch.
  1183. const DRAWS: u32 = 10_000;
  1184. const WIDTH: u32 = 2560;
  1185. const HEIGHT: u32 = 1440;
  1186. /// One small triangle in the middle of the target (about 180 pixels),
  1187. /// and two pixel programs that read one texel of a texture through a
  1188. /// table, so that the view heap set is in use.
  1189. const DRAW: &str = r#"
  1190. #define RS "DescriptorTable(SRV(t0))"
  1191. Texture2D<float4> image : register(t0);
  1192. [RootSignature(RS)]
  1193. float4 corner(uint i : SV_VertexID) : SV_Position {
  1194. float2 p = float2((i << 1) & 2, i & 2);
  1195. return float4(p * 0.02 - 0.01, 0.5, 1.0);
  1196. }
  1197. [RootSignature(RS)]
  1198. float4 first(float4 at : SV_Position) : SV_Target {
  1199. return image.Load(int3(0, 0, 0));
  1200. }
  1201. [RootSignature(RS)]
  1202. float4 second(float4 at : SV_Position) : SV_Target {
  1203. return 1.0 - image.Load(int3(0, 0, 0));
  1204. }
  1205. "#;
  1206. /// A compute pass of next to nothing, as our clamp of an indirect
  1207. /// record is: one group of one thread that writes one word.
  1208. const WORK: &str = r#"
  1209. #define RS "UAV(u0)"
  1210. RWByteAddressBuffer words : register(u0);
  1211. [RootSignature(RS)]
  1212. [numthreads(1, 1, 1)]
  1213. void work() {
  1214. words.Store(0, words.Load(0) + 1);
  1215. }
  1216. "#;
  1217. /// What changes between every two draws of a batch.
  1218. #[derive(Clone, Copy, PartialEq)]
  1219. enum Between {
  1220. /// Nothing.
  1221. Nothing,
  1222. /// The pipeline: two alternate.
  1223. Pipeline,
  1224. /// A second texture goes from target to shader read and back.
  1225. BarrierPair,
  1226. /// The depth texture bound for testing goes from write to read or
  1227. /// back.
  1228. DepthMove,
  1229. /// The pair of descriptor heaps: two pairs alternate.
  1230. Heaps,
  1231. /// The colour target: two alternate.
  1232. Targets,
  1233. /// A compute pass of ours of one group, and the pipeline back.
  1234. Compute,
  1235. /// The same between two waits for every earlier shader write, as
  1236. /// the clamp records them.
  1237. ComputeWithWaits,
  1238. }
  1239. struct Rig {
  1240. queue: ID3D12CommandQueue,
  1241. allocator: ID3D12CommandAllocator,
  1242. list: ID3D12GraphicsCommandList,
  1243. fence: ID3D12Fence,
  1244. submitted: u64,
  1245. event: HANDLE,
  1246. root: ID3D12RootSignature,
  1247. pipelines: [ID3D12PipelineState; 2],
  1248. work_root: ID3D12RootSignature,
  1249. work: ID3D12PipelineState,
  1250. words: ID3D12Resource,
  1251. other: ID3D12Resource,
  1252. depth: ID3D12Resource,
  1253. /// Kept alive: the views below name them.
  1254. _kept: Vec<ID3D12Resource>,
  1255. _target_heaps: [ID3D12DescriptorHeap; 2],
  1256. heap_pairs: [[Option<ID3D12DescriptorHeap>; 2]; 2],
  1257. tables: [D3D12_GPU_DESCRIPTOR_HANDLE; 2],
  1258. targets: [D3D12_CPU_DESCRIPTOR_HANDLE; 2],
  1259. depth_written: D3D12_CPU_DESCRIPTOR_HANDLE,
  1260. depth_tested: D3D12_CPU_DESCRIPTOR_HANDLE,
  1261. stamps: ID3D12QueryHeap,
  1262. back: ID3D12Resource,
  1263. card: String,
  1264. }
  1265. fn texture(
  1266. device: &ID3D12Device,
  1267. (width, height): (u32, u32),
  1268. format: DXGI_FORMAT,
  1269. flags: D3D12_RESOURCE_FLAGS,
  1270. state: D3D12_RESOURCE_STATES,
  1271. ) -> ID3D12Resource {
  1272. let heap = D3D12_HEAP_PROPERTIES {
  1273. Type: D3D12_HEAP_TYPE_DEFAULT,
  1274. ..Default::default()
  1275. };
  1276. let desc = D3D12_RESOURCE_DESC {
  1277. Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  1278. Width: u64::from(width),
  1279. Height: height,
  1280. DepthOrArraySize: 1,
  1281. MipLevels: 1,
  1282. Format: format,
  1283. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  1284. Flags: flags,
  1285. ..Default::default()
  1286. };
  1287. let mut out: Option<ID3D12Resource> = None;
  1288. // SAFETY: plain texture creation.
  1289. unsafe {
  1290. device
  1291. .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out)
  1292. .unwrap();
  1293. }
  1294. out.unwrap()
  1295. }
  1296. fn buffer(
  1297. device: &ID3D12Device,
  1298. size: u64,
  1299. kind: D3D12_HEAP_TYPE,
  1300. flags: D3D12_RESOURCE_FLAGS,
  1301. state: D3D12_RESOURCE_STATES,
  1302. ) -> ID3D12Resource {
  1303. let heap = D3D12_HEAP_PROPERTIES {
  1304. Type: kind,
  1305. ..Default::default()
  1306. };
  1307. let desc = D3D12_RESOURCE_DESC {
  1308. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  1309. Width: size,
  1310. Height: 1,
  1311. DepthOrArraySize: 1,
  1312. MipLevels: 1,
  1313. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  1314. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  1315. Flags: flags,
  1316. ..Default::default()
  1317. };
  1318. let mut out: Option<ID3D12Resource> = None;
  1319. // SAFETY: plain buffer creation.
  1320. unsafe {
  1321. device
  1322. .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out)
  1323. .unwrap();
  1324. }
  1325. out.unwrap()
  1326. }
  1327. fn heap(device: &ID3D12Device, kind: D3D12_DESCRIPTOR_HEAP_TYPE, count: u32, visible: bool) -> ID3D12DescriptorHeap {
  1328. let flags = if visible {
  1329. D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE
  1330. } else {
  1331. D3D12_DESCRIPTOR_HEAP_FLAG_NONE
  1332. };
  1333. // SAFETY: plain heap creation.
  1334. unsafe {
  1335. device
  1336. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  1337. Type: kind,
  1338. NumDescriptors: count,
  1339. Flags: flags,
  1340. NodeMask: 0,
  1341. })
  1342. .unwrap()
  1343. }
  1344. }
  1345. fn pipeline(device: &ID3D12Device, root: &ID3D12RootSignature, vs: &[u8], ps: &[u8]) -> ID3D12PipelineState {
  1346. let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
  1347. pShaderBytecode: bytes.as_ptr().cast(),
  1348. BytecodeLength: bytes.len(),
  1349. };
  1350. let mut blend = D3D12_BLEND_DESC::default();
  1351. blend.RenderTarget[0].RenderTargetWriteMask = 0xf;
  1352. let mut formats = [DXGI_FORMAT(0); 8];
  1353. formats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
  1354. // SAFETY: the description points at live data and never releases
  1355. // its pointer to the root signature.
  1356. unsafe {
  1357. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  1358. pRootSignature: std::mem::transmute_copy(root),
  1359. VS: code(vs),
  1360. PS: code(ps),
  1361. BlendState: blend,
  1362. SampleMask: u32::MAX,
  1363. RasterizerState: D3D12_RASTERIZER_DESC {
  1364. FillMode: D3D12_FILL_MODE_SOLID,
  1365. CullMode: D3D12_CULL_MODE_NONE,
  1366. DepthClipEnable: true.into(),
  1367. ..Default::default()
  1368. },
  1369. // Depth is tested and never written, so the texture may be
  1370. // in the write state or in the read state under one view.
  1371. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  1372. DepthEnable: true.into(),
  1373. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO,
  1374. DepthFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL,
  1375. ..Default::default()
  1376. },
  1377. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  1378. NumRenderTargets: 1,
  1379. RTVFormats: formats,
  1380. DSVFormat: DXGI_FORMAT_D32_FLOAT,
  1381. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  1382. ..Default::default()
  1383. };
  1384. device.CreateGraphicsPipelineState(&desc).unwrap()
  1385. }
  1386. }
  1387. impl Rig {
  1388. /// The default adapter, as the layer takes it; `None` without one
  1389. /// or on a software adapter.
  1390. fn new() -> Option<Self> {
  1391. let vs = compile(DRAW, s!("corner"), s!("vs_5_1")).ok()?;
  1392. let ps = [
  1393. compile(DRAW, s!("first"), s!("ps_5_1")).ok()?,
  1394. compile(DRAW, s!("second"), s!("ps_5_1")).ok()?,
  1395. ];
  1396. let cs = compile(WORK, s!("work"), s!("cs_5_1")).ok()?;
  1397. // SAFETY: plain object creation on a device of our own; the
  1398. // views are made in heaps that live as long as the rig.
  1399. unsafe {
  1400. let mut device: Option<ID3D12Device> = None;
  1401. D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?;
  1402. let device = device?;
  1403. let desc = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  1404. .and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid()))
  1405. .ok()?
  1406. .cast::<IDXGIAdapter1>()
  1407. .ok()?
  1408. .GetDesc1()
  1409. .ok()?;
  1410. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 {
  1411. return None;
  1412. }
  1413. let card = String::from_utf16_lossy(&desc.Description)
  1414. .trim_end_matches('\0')
  1415. .to_owned();
  1416. let queue: ID3D12CommandQueue = device
  1417. .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  1418. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  1419. ..Default::default()
  1420. })
  1421. .ok()?;
  1422. let allocator: ID3D12CommandAllocator =
  1423. device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?;
  1424. let list: ID3D12GraphicsCommandList = device
  1425. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)
  1426. .ok()?;
  1427. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  1428. let event = CreateEventW(None, false, false, None).ok()?;
  1429. let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs[..]).ok()?;
  1430. let pipelines = [
  1431. pipeline(&device, &root, &vs, &ps[0]),
  1432. pipeline(&device, &root, &vs, &ps[1]),
  1433. ];
  1434. let work_root: ID3D12RootSignature = device.CreateRootSignature(0, &cs[..]).ok()?;
  1435. let work: ID3D12PipelineState = device
  1436. .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  1437. pRootSignature: std::mem::transmute_copy(&work_root),
  1438. CS: D3D12_SHADER_BYTECODE {
  1439. pShaderBytecode: cs.as_ptr().cast(),
  1440. BytecodeLength: cs.len(),
  1441. },
  1442. ..Default::default()
  1443. })
  1444. .ok()?;
  1445. let size = (WIDTH, HEIGHT);
  1446. let colour = |state| texture(&device, size, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, state);
  1447. let target = [
  1448. colour(D3D12_RESOURCE_STATE_RENDER_TARGET),
  1449. colour(D3D12_RESOURCE_STATE_RENDER_TARGET),
  1450. ];
  1451. let other = colour(D3D12_RESOURCE_STATE_RENDER_TARGET);
  1452. let depth = texture(
  1453. &device,
  1454. size,
  1455. DXGI_FORMAT_D32_FLOAT,
  1456. D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL,
  1457. D3D12_RESOURCE_STATE_DEPTH_WRITE,
  1458. );
  1459. let image = texture(
  1460. &device,
  1461. (4, 4),
  1462. DXGI_FORMAT_R8G8B8A8_UNORM,
  1463. D3D12_RESOURCE_FLAG_NONE,
  1464. D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
  1465. );
  1466. let words = buffer(
  1467. &device,
  1468. 64 << 10,
  1469. D3D12_HEAP_TYPE_DEFAULT,
  1470. D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  1471. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  1472. );
  1473. let back = buffer(
  1474. &device,
  1475. 16,
  1476. D3D12_HEAP_TYPE_READBACK,
  1477. D3D12_RESOURCE_FLAG_NONE,
  1478. D3D12_RESOURCE_STATE_COPY_DEST,
  1479. );
  1480. let mut stamps: Option<ID3D12QueryHeap> = None;
  1481. device
  1482. .CreateQueryHeap(
  1483. &D3D12_QUERY_HEAP_DESC {
  1484. Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP,
  1485. Count: 2,
  1486. NodeMask: 0,
  1487. },
  1488. &mut stamps,
  1489. )
  1490. .ok()?;
  1491. let stamps = stamps?;
  1492. // Target and depth views.
  1493. let rtvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, false);
  1494. let rtv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize;
  1495. let mut targets = [rtvs.GetCPUDescriptorHandleForHeapStart(); 2];
  1496. targets[1].ptr += rtv_step;
  1497. device.CreateRenderTargetView(&target[0], None, targets[0]);
  1498. device.CreateRenderTargetView(&target[1], None, targets[1]);
  1499. let dsvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2, false);
  1500. let dsv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize;
  1501. let depth_written = dsvs.GetCPUDescriptorHandleForHeapStart();
  1502. let mut depth_tested = depth_written;
  1503. depth_tested.ptr += dsv_step;
  1504. device.CreateDepthStencilView(&depth, None, depth_written);
  1505. let tested = D3D12_DEPTH_STENCIL_VIEW_DESC {
  1506. Format: DXGI_FORMAT_D32_FLOAT,
  1507. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D,
  1508. Flags: D3D12_DSV_FLAG_READ_ONLY_DEPTH,
  1509. ..Default::default()
  1510. };
  1511. device.CreateDepthStencilView(&depth, Some(&tested), depth_tested);
  1512. // Two pairs of shader-visible heaps: views (one view of the
  1513. // small texture each) and samplers (none used).
  1514. let view_heaps = [
  1515. heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true),
  1516. heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true),
  1517. ];
  1518. let sampler_heaps = [
  1519. heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true),
  1520. heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true),
  1521. ];
  1522. for views in &view_heaps {
  1523. device.CreateShaderResourceView(&image, None, views.GetCPUDescriptorHandleForHeapStart());
  1524. }
  1525. let tables = [
  1526. view_heaps[0].GetGPUDescriptorHandleForHeapStart(),
  1527. view_heaps[1].GetGPUDescriptorHandleForHeapStart(),
  1528. ];
  1529. let heap_pairs = [
  1530. [Some(view_heaps[0].clone()), Some(sampler_heaps[0].clone())],
  1531. [Some(view_heaps[1].clone()), Some(sampler_heaps[1].clone())],
  1532. ];
  1533. // The first list: both targets and the depth texture cleared.
  1534. list.ClearRenderTargetView(targets[0], &[0.0; 4], None);
  1535. list.ClearRenderTargetView(targets[1], &[0.0; 4], None);
  1536. list.ClearDepthStencilView(depth_written, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None);
  1537. let [first_target, second_target] = target;
  1538. let mut rig = Rig {
  1539. queue,
  1540. allocator,
  1541. list,
  1542. fence,
  1543. submitted: 0,
  1544. event,
  1545. root,
  1546. pipelines,
  1547. work_root,
  1548. work,
  1549. words,
  1550. other,
  1551. depth,
  1552. _kept: vec![first_target, second_target, image],
  1553. _target_heaps: [rtvs, dsvs],
  1554. heap_pairs,
  1555. tables,
  1556. targets,
  1557. depth_written,
  1558. depth_tested,
  1559. stamps,
  1560. back,
  1561. card,
  1562. };
  1563. rig.finish();
  1564. Some(rig)
  1565. }
  1566. }
  1567. /// Closes the open list, runs it, waits for the card and opens the
  1568. /// list again.
  1569. fn finish(&mut self) {
  1570. self.submitted += 1;
  1571. // SAFETY: our list, queue and fence; the allocator is reset
  1572. // only after the card finished everything recorded from it.
  1573. unsafe {
  1574. self.list.Close().unwrap();
  1575. let run: ID3D12CommandList = self.list.cast().unwrap();
  1576. self.queue.ExecuteCommandLists(&[Some(run)]);
  1577. self.queue.Signal(&self.fence, self.submitted).unwrap();
  1578. self.fence.SetEventOnCompletion(self.submitted, self.event).unwrap();
  1579. WaitForSingleObject(self.event, INFINITE);
  1580. self.allocator.Reset().unwrap();
  1581. self.list.Reset(&self.allocator, None).unwrap();
  1582. }
  1583. }
  1584. /// What every list starts with: a new list has nothing set.
  1585. fn begin(&self) {
  1586. let l = &self.list;
  1587. // SAFETY: an open list and live objects and views.
  1588. unsafe {
  1589. l.SetDescriptorHeaps(&self.heap_pairs[0]);
  1590. l.SetGraphicsRootSignature(&self.root);
  1591. l.SetPipelineState(&self.pipelines[0]);
  1592. l.SetGraphicsRootDescriptorTable(0, self.tables[0]);
  1593. l.OMSetRenderTargets(1, Some(&self.targets[0]), false, Some(&self.depth_tested));
  1594. l.RSSetViewports(&[D3D12_VIEWPORT {
  1595. TopLeftX: 0.0,
  1596. TopLeftY: 0.0,
  1597. Width: WIDTH as f32,
  1598. Height: HEIGHT as f32,
  1599. MinDepth: 0.0,
  1600. MaxDepth: 1.0,
  1601. }]);
  1602. l.RSSetScissorRects(&[RECT {
  1603. left: 0,
  1604. top: 0,
  1605. right: WIDTH as i32,
  1606. bottom: HEIGHT as i32,
  1607. }]);
  1608. // A triangle list.
  1609. l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(4));
  1610. }
  1611. }
  1612. /// One batch of [`DRAWS`] draws in `lists` lists run one by one,
  1613. /// with `between` recorded before every draw: the microseconds a
  1614. /// draw took on the card, and the milliseconds recording took.
  1615. fn batch(&mut self, between: Between, lists: u32) -> (f64, f64) {
  1616. let (target, read, written, tested) = (
  1617. D3D12_RESOURCE_STATE_RENDER_TARGET,
  1618. D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
  1619. D3D12_RESOURCE_STATE_DEPTH_WRITE,
  1620. D3D12_RESOURCE_STATE_DEPTH_READ,
  1621. );
  1622. let started = std::time::Instant::now();
  1623. let mut drawn = 0u32;
  1624. for part in 0..lists {
  1625. let l = &self.list;
  1626. // SAFETY: an open list; our query heap; live objects.
  1627. unsafe {
  1628. if part == 0 {
  1629. l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0);
  1630. }
  1631. }
  1632. self.begin();
  1633. // SAFETY: an open list with everything set; live objects.
  1634. // Every state moved is moved back within the batch (the
  1635. // draws of a list are an even number).
  1636. unsafe {
  1637. for _ in 0..DRAWS / lists {
  1638. let odd = (drawn % 2) as usize;
  1639. match between {
  1640. Between::Nothing => {}
  1641. Between::Pipeline => l.SetPipelineState(&self.pipelines[odd]),
  1642. Between::BarrierPair => {
  1643. l.ResourceBarrier(&[transition(&self.other, target, read)]);
  1644. l.ResourceBarrier(&[transition(&self.other, read, target)]);
  1645. }
  1646. Between::DepthMove => {
  1647. let (from, to) = if odd == 0 { (written, tested) } else { (tested, written) };
  1648. l.ResourceBarrier(&[transition(&self.depth, from, to)]);
  1649. }
  1650. Between::Heaps => {
  1651. l.SetDescriptorHeaps(&self.heap_pairs[odd]);
  1652. l.SetGraphicsRootDescriptorTable(0, self.tables[odd]);
  1653. }
  1654. Between::Targets => {
  1655. l.OMSetRenderTargets(1, Some(&self.targets[odd]), false, Some(&self.depth_tested));
  1656. }
  1657. Between::Compute | Between::ComputeWithWaits => {
  1658. let waits = between == Between::ComputeWithWaits;
  1659. if waits {
  1660. l.ResourceBarrier(&[super::uav_barrier()]);
  1661. }
  1662. l.SetComputeRootSignature(&self.work_root);
  1663. l.SetPipelineState(&self.work);
  1664. l.SetComputeRootUnorderedAccessView(0, self.words.GetGPUVirtualAddress());
  1665. l.Dispatch(1, 1, 1);
  1666. if waits {
  1667. l.ResourceBarrier(&[super::uav_barrier()]);
  1668. }
  1669. l.SetPipelineState(&self.pipelines[0]);
  1670. }
  1671. }
  1672. l.DrawInstanced(3, 1, 0, 0);
  1673. drawn += 1;
  1674. }
  1675. if part + 1 < lists {
  1676. // The next list of the batch: this one is sent on
  1677. // its own and the list is opened again at once
  1678. // (the allocator is not reset before the card is
  1679. // done with all of them).
  1680. l.Close().unwrap();
  1681. let run: ID3D12CommandList = l.cast().unwrap();
  1682. self.queue.ExecuteCommandLists(&[Some(run)]);
  1683. l.Reset(&self.allocator, None).unwrap();
  1684. } else {
  1685. l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1);
  1686. l.ResolveQueryData(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &self.back, 0);
  1687. }
  1688. }
  1689. }
  1690. let recording = started.elapsed().as_secs_f64() * 1e3;
  1691. self.finish();
  1692. let mut data = std::ptr::null_mut();
  1693. let range = D3D12_RANGE { Begin: 0, End: 16 };
  1694. // SAFETY: a read-back buffer the finished list resolved two
  1695. // timestamps into.
  1696. let ticks = unsafe {
  1697. self.back.Map(0, Some(&range), Some(&mut data)).unwrap();
  1698. let stamps = std::slice::from_raw_parts(data.cast::<u64>(), 2).to_vec();
  1699. self.back.Unmap(0, None);
  1700. stamps[1].saturating_sub(stamps[0])
  1701. };
  1702. // SAFETY: a plain query of our queue.
  1703. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1).max(1);
  1704. (ticks as f64 * 1e6 / frequency as f64 / f64::from(drawn.max(1)), recording)
  1705. }
  1706. }
  1707. #[test]
  1708. #[ignore = "a measurement on the card: run it by name with --ignored --nocapture"]
  1709. fn bare_command_cost() {
  1710. let Some(mut rig) = Rig::new() else {
  1711. eprintln!("no hardware adapter, or our shaders did not compile; skipped");
  1712. return;
  1713. };
  1714. eprintln!("bare command cost on {}: {DRAWS} one-triangle draws into {WIDTH}x{HEIGHT}, three batches each", rig.card);
  1715. // The first batch pays for whatever the driver does at first use.
  1716. rig.batch(Between::Nothing, 1);
  1717. let variants = [
  1718. ("(a) nothing changes between draws", Between::Nothing, 1),
  1719. ("(b) another pipeline every draw", Between::Pipeline, 1),
  1720. ("(c) a barrier pair on a second texture every draw", Between::BarrierPair, 1),
  1721. ("(d) the tested depth texture moved between write and read every draw", Between::DepthMove, 1),
  1722. ("(e) another pair of descriptor heaps every draw", Between::Heaps, 1),
  1723. ("(f) another colour target every draw", Between::Targets, 1),
  1724. ("(g) nothing changes, in 100 lists run one by one", Between::Nothing, 100),
  1725. ("(h) a compute pass of ours of one group before every draw", Between::Compute, 1),
  1726. ("(i) the same pass between two waits for earlier shader writes", Between::ComputeWithWaits, 1),
  1727. ];
  1728. let mut least = Vec::new();
  1729. for (name, between, lists) in variants {
  1730. let mut runs: Vec<(f64, f64)> = (0..3).map(|_| rig.batch(between, lists)).collect();
  1731. runs.sort_by(|a, b| a.0.total_cmp(&b.0));
  1732. eprintln!(
  1733. "{name}: {:.2} microseconds a draw on the card (the three: {:.2}, {:.2}, {:.2}); recording took {:.1} ms",
  1734. runs[0].0, runs[0].0, runs[1].0, runs[2].0, runs[0].1
  1735. );
  1736. least.push(runs[0].0);
  1737. }
  1738. assert!(least.iter().all(|us| us.is_finite() && *us > 0.0), "the card gave no time for a batch");
  1739. }
  1740. }