indirect.rs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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 every record is clamped on the GPU,
  6. //! just before its execution, by a compute shader of ours (HLSL compiled by
  7. //! the system's compiler; a 5.1 shader with its root signature inside).
  8. //!
  9. //! Each list also has a budget (2^28 vertex instances or threads, mesh
  10. //! groups counted as 128): records past it run empty, so a list of
  11. //! thousands of garbage records cannot run for seconds either.
  12. //!
  13. //! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535
  14. //! groups per dimension, one-dimensional mesh dispatches, the budget) cut
  15. //! legitimate work beyond them; raise them if the title needs more.
  16. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  17. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  18. use windows::Win32::Graphics::Direct3D12::*;
  19. use windows::core::s;
  20. use crate::host::{HostList, host, transition};
  21. const SOURCE: &str = r#"
  22. #define RS "RootConstants(num32BitConstants=4, b0), UAV(u0), UAV(u1)"
  23. cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint unused; };
  24. RWByteAddressBuffer args : register(u0);
  25. // The list's work so far (vertex instances, threads): past the budget,
  26. // records run empty.
  27. RWByteAddressBuffer budget : register(u1);
  28. static const uint BUDGET = 1u << 28;
  29. [RootSignature(RS)]
  30. [numthreads(64, 1, 1)]
  31. void main(uint3 id : SV_DispatchThreadID) {
  32. if (id.x >= records) return;
  33. uint at = id.x * stride;
  34. uint cost;
  35. if (kind <= 1) {
  36. // Draws: vertex or index count, then instances.
  37. uint count = min(args.Load(at), 1u << 24);
  38. uint instances = min(args.Load(at + 4), (1u << 26) / max(count, 1u));
  39. cost = count * instances;
  40. args.Store2(at, uint2(count, instances));
  41. } else if (kind == 2) {
  42. uint3 g = min(args.Load3(at), uint3(65535, 65535, 65535));
  43. cost = min(g.x * g.y * g.z, 1u << 20) * 64;
  44. args.Store3(at, g);
  45. } else {
  46. // Mesh dispatches: the console's are one-dimensional.
  47. uint3 g = args.Load3(at);
  48. g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u));
  49. cost = g.x * g.y * g.z * 128;
  50. args.Store3(at, g);
  51. }
  52. uint before;
  53. budget.InterlockedAdd(0, cost, before);
  54. if (before >= BUDGET || before + cost > BUDGET) {
  55. // Draws keep their layout with no vertices; groups become zero.
  56. args.Store(at, 0);
  57. }
  58. }
  59. "#;
  60. struct Clamp {
  61. root: ID3D12RootSignature,
  62. pso: ID3D12PipelineState,
  63. }
  64. // SAFETY: D3D12 objects are free-threaded.
  65. unsafe impl Send for Clamp {}
  66. // SAFETY: as above.
  67. unsafe impl Sync for Clamp {}
  68. fn clamp() -> Option<&'static Clamp> {
  69. static CLAMP: std::sync::OnceLock<Option<Clamp>> = std::sync::OnceLock::new();
  70. CLAMP
  71. .get_or_init(|| match make() {
  72. Ok(c) => Some(c),
  73. Err(e) => {
  74. tracing::warn!(error = %e, "no argument clamp: indirect execution dropped");
  75. None
  76. }
  77. })
  78. .as_ref()
  79. }
  80. fn make() -> windows::core::Result<Clamp> {
  81. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  82. let mut code: Option<ID3DBlob> = None;
  83. let mut errors: Option<ID3DBlob> = None;
  84. // SAFETY: the source and names live through the call; out pointers ours.
  85. let compiled = unsafe {
  86. D3DCompile(
  87. SOURCE.as_ptr().cast(),
  88. SOURCE.len(),
  89. s!("clamp"),
  90. None,
  91. None,
  92. s!("main"),
  93. s!("cs_5_1"),
  94. 0,
  95. 0,
  96. &mut code,
  97. Some(&mut errors),
  98. )
  99. };
  100. if let Err(e) = compiled {
  101. if let Some(errors) = errors {
  102. // SAFETY: the blob's own bytes.
  103. let text = unsafe {
  104. std::slice::from_raw_parts(errors.GetBufferPointer().cast::<u8>(), errors.GetBufferSize())
  105. };
  106. tracing::warn!("argument clamp: {}", String::from_utf8_lossy(text));
  107. }
  108. return Err(e);
  109. }
  110. let code = code.ok_or_else(windows::core::Error::empty)?;
  111. // SAFETY: the blob's own bytes; the root signature is inside the shader.
  112. unsafe {
  113. let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  114. let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?;
  115. let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  116. pRootSignature: std::mem::transmute_copy(&root),
  117. CS: D3D12_SHADER_BYTECODE {
  118. pShaderBytecode: bytes.as_ptr().cast(),
  119. BytecodeLength: bytes.len(),
  120. },
  121. ..Default::default()
  122. })?;
  123. Ok(Clamp { root, pso })
  124. }
  125. }
  126. /// Records, in `list`, the clamp of `records` records of `kind` (PC
  127. /// argument numbering) `stride` bytes apart at host address `gpu` in
  128. /// `buffer`, and leaves the buffer ready to be read as arguments. Replaces
  129. /// the list's compute root signature and pipeline (callers bind theirs
  130. /// after). False if the clamp is not available.
  131. pub(crate) fn bound(
  132. list: &HostList,
  133. buffer: &ID3D12Resource,
  134. gpu: u64,
  135. (kind, stride, records): (u32, u32, u32),
  136. ) -> bool {
  137. let (Some(c), Some(budget)) = (clamp(), list.budget()) else {
  138. return false;
  139. };
  140. if !gpu.is_multiple_of(4) || !stride.is_multiple_of(4) {
  141. return false;
  142. }
  143. let l = &list.list;
  144. let constants = [kind, stride, records, 0];
  145. // SAFETY: an open list; our root signature, pipeline and a live buffer
  146. // the caller's list holds.
  147. unsafe {
  148. // Earlier shader writes (the title's argument passes) first.
  149. l.ResourceBarrier(&[uav_barrier()]);
  150. l.SetComputeRootSignature(&c.root);
  151. l.SetPipelineState(&c.pso);
  152. l.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0);
  153. l.SetComputeRootUnorderedAccessView(1, gpu);
  154. l.SetComputeRootUnorderedAccessView(2, budget);
  155. l.Dispatch(records.div_ceil(64), 1, 1);
  156. l.ResourceBarrier(&[
  157. uav_barrier(),
  158. transition(
  159. buffer,
  160. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  161. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  162. ),
  163. ]);
  164. }
  165. true
  166. }
  167. /// After the execution: the buffer back to unordered access, where the
  168. /// title's passes keep using it.
  169. pub(crate) fn done(list: &HostList, buffer: &ID3D12Resource) {
  170. // SAFETY: an open list and a live buffer.
  171. unsafe {
  172. list.list.ResourceBarrier(&[transition(
  173. buffer,
  174. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  175. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  176. )])
  177. };
  178. }
  179. fn uav_barrier() -> D3D12_RESOURCE_BARRIER {
  180. D3D12_RESOURCE_BARRIER {
  181. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  182. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  183. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  184. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }),
  185. },
  186. }
  187. }
  188. #[cfg(test)]
  189. mod tests {
  190. /// The clamp compiles with the system's compiler and the host takes it.
  191. #[test]
  192. fn argument_clamp_builds() {
  193. if super::host().is_none() {
  194. return; // no host GPU here
  195. }
  196. assert!(super::clamp().is_some());
  197. }
  198. }