CommandBuffer.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. // Copyright (C) 2009-2021, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #pragma once
  6. #include <AnKi/Gr/GrObject.h>
  7. #include <AnKi/Gr/Framebuffer.h>
  8. #include <AnKi/Util/Functions.h>
  9. #include <AnKi/Util/WeakArray.h>
  10. namespace anki
  11. {
  12. /// @addtogroup graphics
  13. /// @{
  14. /// The draw indirect structure for index drawing, also the parameters of a regular drawcall
  15. class DrawElementsIndirectInfo
  16. {
  17. public:
  18. U32 m_count = MAX_U32;
  19. U32 m_instanceCount = 1;
  20. U32 m_firstIndex = 0;
  21. U32 m_baseVertex = 0;
  22. U32 m_baseInstance = 0;
  23. DrawElementsIndirectInfo() = default;
  24. DrawElementsIndirectInfo(const DrawElementsIndirectInfo&) = default;
  25. DrawElementsIndirectInfo(U32 count, U32 instanceCount, U32 firstIndex, U32 baseVertex, U32 baseInstance)
  26. : m_count(count)
  27. , m_instanceCount(instanceCount)
  28. , m_firstIndex(firstIndex)
  29. , m_baseVertex(baseVertex)
  30. , m_baseInstance(baseInstance)
  31. {
  32. }
  33. Bool operator==(const DrawElementsIndirectInfo& b) const
  34. {
  35. return m_count == b.m_count && m_instanceCount == b.m_instanceCount && m_firstIndex == b.m_firstIndex
  36. && m_baseVertex == b.m_baseVertex && m_baseInstance == b.m_baseInstance;
  37. }
  38. Bool operator!=(const DrawElementsIndirectInfo& b) const
  39. {
  40. return !(operator==(b));
  41. }
  42. };
  43. /// The draw indirect structure for arrays drawing, also the parameters of a regular drawcall
  44. class DrawArraysIndirectInfo
  45. {
  46. public:
  47. U32 m_count = MAX_U32;
  48. U32 m_instanceCount = 1;
  49. U32 m_first = 0;
  50. U32 m_baseInstance = 0;
  51. DrawArraysIndirectInfo() = default;
  52. DrawArraysIndirectInfo(const DrawArraysIndirectInfo&) = default;
  53. DrawArraysIndirectInfo(U32 count, U32 instanceCount, U32 first, U32 baseInstance)
  54. : m_count(count)
  55. , m_instanceCount(instanceCount)
  56. , m_first(first)
  57. , m_baseInstance(baseInstance)
  58. {
  59. }
  60. Bool operator==(const DrawArraysIndirectInfo& b) const
  61. {
  62. return m_count == b.m_count && m_instanceCount == b.m_instanceCount && m_first == b.m_first
  63. && m_baseInstance == b.m_baseInstance;
  64. }
  65. Bool operator!=(const DrawArraysIndirectInfo& b) const
  66. {
  67. return !(operator==(b));
  68. }
  69. };
  70. /// Command buffer initialization flags.
  71. enum class CommandBufferFlag : U8
  72. {
  73. NONE = 0,
  74. SECOND_LEVEL = 1 << 0,
  75. /// It will contain a handfull of commands.
  76. SMALL_BATCH = 1 << 3,
  77. /// Will contain graphics, compute and transfer work.
  78. GENERAL_WORK = 1 << 4,
  79. /// Will contain only compute work. It binds to async compute queues.
  80. COMPUTE_WORK = 1 << 5,
  81. };
  82. ANKI_ENUM_ALLOW_NUMERIC_OPERATIONS(CommandBufferFlag)
  83. /// Command buffer init info.
  84. class CommandBufferInitInfo : public GrBaseInitInfo
  85. {
  86. public:
  87. FramebufferPtr m_framebuffer; ///< For second level command buffers.
  88. Array<TextureUsageBit, MAX_COLOR_ATTACHMENTS> m_colorAttachmentUsages{};
  89. TextureUsageBit m_depthStencilAttachmentUsage = TextureUsageBit::NONE;
  90. CommandBufferFlag m_flags = CommandBufferFlag::NONE;
  91. CommandBufferInitInfo(CString name = {})
  92. : GrBaseInitInfo(name)
  93. {
  94. }
  95. };
  96. /// Command buffer.
  97. class CommandBuffer : public GrObject
  98. {
  99. ANKI_GR_OBJECT
  100. public:
  101. static const GrObjectType CLASS_TYPE = GrObjectType::COMMAND_BUFFER;
  102. /// Finalize and submit if it's primary command buffer and just finalize if it's second level.
  103. /// @param[in] waitFences Optionally wait for some fences.
  104. /// @param[out] signalFence Optionaly create fence that will be signaled when the submission is done.
  105. void flush(ConstWeakArray<FencePtr> waitFences = {}, FencePtr* signalFence = nullptr);
  106. /// @name State manipulation
  107. /// @{
  108. /// Bind vertex buffer.
  109. void bindVertexBuffer(U32 binding, BufferPtr buff, PtrSize offset, PtrSize stride,
  110. VertexStepRate stepRate = VertexStepRate::VERTEX);
  111. /// Setup a vertex attribute.
  112. void setVertexAttribute(U32 location, U32 buffBinding, Format fmt, PtrSize relativeOffset);
  113. /// Bind index buffer.
  114. void bindIndexBuffer(BufferPtr buff, PtrSize offset, IndexType type);
  115. /// Enable primitive restart.
  116. void setPrimitiveRestart(Bool enable);
  117. /// Set the viewport.
  118. void setViewport(U32 minx, U32 miny, U32 width, U32 height);
  119. /// Set the scissor rect. To disable the scissor just set a rect bigger than the viewport. By default it's disabled.
  120. void setScissor(U32 minx, U32 miny, U32 width, U32 height);
  121. /// Set fill mode.
  122. void setFillMode(FillMode mode);
  123. /// Set cull mode.
  124. /// By default it's FaceSelectionBit::BACK.
  125. void setCullMode(FaceSelectionBit mode);
  126. /// Set depth offset and units. Set zeros to both to disable it.
  127. void setPolygonOffset(F32 factor, F32 units);
  128. /// Set stencil operations. To disable stencil test put StencilOperation::KEEP to all operations.
  129. void setStencilOperations(FaceSelectionBit face, StencilOperation stencilFail,
  130. StencilOperation stencilPassDepthFail, StencilOperation stencilPassDepthPass);
  131. /// Set stencil compare operation.
  132. void setStencilCompareOperation(FaceSelectionBit face, CompareOperation comp);
  133. /// Set the stencil compare mask.
  134. void setStencilCompareMask(FaceSelectionBit face, U32 mask);
  135. /// Set the stencil write mask.
  136. void setStencilWriteMask(FaceSelectionBit face, U32 mask);
  137. /// Set the stencil reference.
  138. void setStencilReference(FaceSelectionBit face, U32 ref);
  139. /// Enable/disable depth write. To disable depth testing set depth write to false and depth compare operation to
  140. /// always.
  141. void setDepthWrite(Bool enable);
  142. /// Set depth compare operation.
  143. void setDepthCompareOperation(CompareOperation op);
  144. /// Enable/disable alpha to coverage.
  145. void setAlphaToCoverage(Bool enable);
  146. /// Set color channel write mask.
  147. void setColorChannelWriteMask(U32 attachment, ColorBit mask);
  148. /// Set blend factors seperate.
  149. /// By default the values of srcRgb, dstRgb, srcA and dstA are BlendFactor::ONE, BlendFactor::ZERO,
  150. /// BlendFactor::ONE, BlendFactor::ZERO respectively.
  151. void setBlendFactors(U32 attachment, BlendFactor srcRgb, BlendFactor dstRgb, BlendFactor srcA, BlendFactor dstA);
  152. /// Set blend factors.
  153. void setBlendFactors(U32 attachment, BlendFactor src, BlendFactor dst)
  154. {
  155. setBlendFactors(attachment, src, dst, src, dst);
  156. }
  157. /// Set the blend operation seperate.
  158. /// By default the values of funcRgb and funcA are BlendOperation::ADD, BlendOperation::ADD respectively.
  159. void setBlendOperation(U32 attachment, BlendOperation funcRgb, BlendOperation funcA);
  160. /// Set the blend operation.
  161. void setBlendOperation(U32 attachment, BlendOperation func)
  162. {
  163. setBlendOperation(attachment, func, func);
  164. }
  165. /// Set the rasterizatin order. By default it's RasterizationOrder::ORDERED.
  166. void setRasterizationOrder(RasterizationOrder order);
  167. /// Set the line width. By default it's undefined.
  168. void setLineWidth(F32 lineWidth);
  169. /// Bind texture and sample.
  170. /// @param set The set to bind to.
  171. /// @param binding The binding to bind to.
  172. /// @param texView The texture view to bind.
  173. /// @param sampler The sampler to override the default sampler of the tex.
  174. /// @param arrayIdx The array index if the binding is an array.
  175. void bindTextureAndSampler(U32 set, U32 binding, TextureViewPtr texView, SamplerPtr sampler, U32 arrayIdx = 0);
  176. /// Bind sampler.
  177. /// @param set The set to bind to.
  178. /// @param binding The binding to bind to.
  179. /// @param sampler The sampler to override the default sampler of the tex.
  180. /// @param arrayIdx The array index if the binding is an array.
  181. void bindSampler(U32 set, U32 binding, SamplerPtr sampler, U32 arrayIdx = 0);
  182. /// Bind a texture.
  183. /// @param set The set to bind to.
  184. /// @param binding The binding to bind to.
  185. /// @param texView The texture view to bind.
  186. /// @param arrayIdx The array index if the binding is an array.
  187. void bindTexture(U32 set, U32 binding, TextureViewPtr texView, U32 arrayIdx = 0);
  188. /// Bind uniform buffer.
  189. /// @param set The set to bind to.
  190. /// @param binding The binding to bind to.
  191. /// @param[in,out] buff The buffer to bind.
  192. /// @param offset The base of the binding.
  193. /// @param range The bytes to bind starting from the offset. If it's MAX_PTR_SIZE then map from offset to the end
  194. /// of the buffer.
  195. /// @param arrayIdx The array index if the binding is an array.
  196. void bindUniformBuffer(U32 set, U32 binding, BufferPtr buff, PtrSize offset, PtrSize range, U32 arrayIdx = 0);
  197. /// Bind storage buffer.
  198. /// @param set The set to bind to.
  199. /// @param binding The binding to bind to.
  200. /// @param[in,out] buff The buffer to bind.
  201. /// @param offset The base of the binding.
  202. /// @param range The bytes to bind starting from the offset. If it's MAX_PTR_SIZE then map from offset to the end
  203. /// of the buffer.
  204. /// @param arrayIdx The array index if the binding is an array.
  205. void bindStorageBuffer(U32 set, U32 binding, BufferPtr buff, PtrSize offset, PtrSize range, U32 arrayIdx = 0);
  206. /// Bind load/store image.
  207. /// @param set The set to bind to.
  208. /// @param binding The binding to bind to.
  209. /// @param img The view to bind.
  210. /// @param arrayIdx The array index if the binding is an array.
  211. void bindImage(U32 set, U32 binding, TextureViewPtr img, U32 arrayIdx = 0);
  212. /// Bind texture buffer.
  213. /// @param set The set to bind to.
  214. /// @param binding The binding to bind to.
  215. /// @param[in,out] buff The buffer to bind.
  216. /// @param offset The base of the binding.
  217. /// @param range The bytes to bind starting from the offset. If it's MAX_PTR_SIZE then map from offset to the end
  218. /// of the buffer.
  219. /// @param fmt The format of the buffer.
  220. /// @param arrayIdx The array index if the binding is an array.
  221. void bindTextureBuffer(U32 set, U32 binding, BufferPtr buff, PtrSize offset, PtrSize range, Format fmt,
  222. U32 arrayIdx = 0);
  223. /// Bind an acceleration structure.
  224. /// @param set The set to bind to.
  225. /// @param binding The binding to bind to.
  226. /// @param[in,out] as The AS to bind.
  227. /// @param arrayIdx The array index if the binding is an array.
  228. void bindAccelerationStructure(U32 set, U32 binding, AccelerationStructurePtr as, U32 arrayIdx = 0);
  229. /// Bind the bindless descriptor set into a slot.
  230. void bindAllBindless(U32 set);
  231. /// Set push constants.
  232. void setPushConstants(const void* data, U32 dataSize);
  233. /// Bind a program.
  234. void bindShaderProgram(ShaderProgramPtr prog);
  235. /// Begin renderpass.
  236. /// The minx, miny, width, height control the area that the load and store operations will happen. If the scissor is
  237. /// bigger than the render area the results are undefined.
  238. void beginRenderPass(FramebufferPtr fb, const Array<TextureUsageBit, MAX_COLOR_ATTACHMENTS>& colorAttachmentUsages,
  239. TextureUsageBit depthStencilAttachmentUsage, U32 minx = 0, U32 miny = 0, U32 width = MAX_U32,
  240. U32 height = MAX_U32);
  241. /// End renderpass.
  242. void endRenderPass();
  243. /// @}
  244. /// @name Jobs
  245. /// @{
  246. void drawElements(PrimitiveTopology topology, U32 count, U32 instanceCount = 1, U32 firstIndex = 0,
  247. U32 baseVertex = 0, U32 baseInstance = 0);
  248. void drawArrays(PrimitiveTopology topology, U32 count, U32 instanceCount = 1, U32 first = 0, U32 baseInstance = 0);
  249. void drawElementsIndirect(PrimitiveTopology topology, U32 drawCount, PtrSize offset, BufferPtr indirectBuff);
  250. void drawArraysIndirect(PrimitiveTopology topology, U32 drawCount, PtrSize offset, BufferPtr indirectBuff);
  251. void dispatchCompute(U32 groupCountX, U32 groupCountY, U32 groupCountZ);
  252. /// Trace rays.
  253. ///
  254. /// The 1st thing in the sbtBuffer is the ray gen shader group handle:
  255. /// @code RG = RG_offset @endcode
  256. /// The RG_offset is equal to the stbBufferOffset.
  257. ///
  258. /// Then the sbtBuffer contains the miss shader group handles and their data. The indexing is as follows:
  259. /// @code M = M_offset + M_stride * R_miss @endcode
  260. /// The M_offset is equal to stbBufferOffset + GpuDeviceCapabilities::m_sbtRecordSize.
  261. /// The M_stride is equal to GpuDeviceCapabilities::m_sbtRecordSize.
  262. /// The R_miss is defined in the traceRayEXT and it's the "ray type".
  263. ///
  264. /// After the miss shaders the sbtBuffer has the hit group shader group handles and their data. The indexing is:
  265. /// @code HG = HG_offset + (HG_stride * (R_offset + R_stride * G_id + I_offset)) @endcode
  266. /// The HG_offset is equal to sbtBufferOffset + GpuDeviceCapabilities::m_sbtRecordSize * (missShaderCount + 1).
  267. /// The HG_stride is equal GpuDeviceCapabilities::m_sbtRecordSize * rayTypecount.
  268. /// The R_offset and R_stride are provided in traceRayEXT. The R_offset is the "ray type" and R_stride the number of
  269. /// ray types.
  270. /// The G_id is always 0 ATM.
  271. /// The I_offset is the AccelerationStructureInstance::m_hitgroupSbtRecordIndex.
  272. ///
  273. /// @param[in] sbtBuffer The SBT buffer.
  274. /// @param sbtBufferOffset Offset inside the sbtBuffer where SBT records start.
  275. /// @param hitGroupSbtRecordCount The number of SBT records that contain hit groups.
  276. /// @param sbtRecordSize The size of an SBT record
  277. /// @param rayTypecount The number of ray types hosted in the pipeline. See above on how it's been used.
  278. /// @param width Width.
  279. /// @param height Height.
  280. /// @param depth Depth.
  281. void traceRays(BufferPtr sbtBuffer, PtrSize sbtBufferOffset, U32 sbtRecordSize, U32 hitGroupSbtRecordCount,
  282. U32 rayTypeCount, U32 width, U32 height, U32 depth);
  283. /// Generate mipmaps for non-3D textures. You have to transition all the mip levels of this face and layer to
  284. /// TextureUsageBit::GENERATE_MIPMAPS before calling this method.
  285. /// @param texView The texture view to generate mips. It should point to a subresource that contains the whole
  286. /// mip chain and only one face and one layer.
  287. void generateMipmaps2d(TextureViewPtr texView);
  288. /// Generate mipmaps only for 3D textures.
  289. /// @param texView The texture view to generate mips.
  290. void generateMipmaps3d(TextureViewPtr tex);
  291. /// Blit from surface to surface.
  292. /// @param srcView The source view that points to a surface.
  293. /// @param dstView The destination view that points to a surface.
  294. void blitTextureViews(TextureViewPtr srcView, TextureViewPtr destView);
  295. /// Clear a single texture surface. Can be used for all textures except 3D.
  296. /// @param[in,out] texView The texture view to clear.
  297. /// @param[in] clearValue The value to clear it with.
  298. void clearTextureView(TextureViewPtr texView, const ClearValue& clearValue);
  299. /// Copy a buffer to a texture surface or volume.
  300. /// @param buff The source buffer to copy from.
  301. /// @param offset The offset in the buffer to start reading from.
  302. /// @param range The size of the buffer to read.
  303. /// @param texView The texture view that points to a surface or volume to write to.
  304. void copyBufferToTextureView(BufferPtr buff, PtrSize offset, PtrSize range, TextureViewPtr texView);
  305. /// Fill a buffer with some value.
  306. /// @param[in,out] buff The buffer to fill.
  307. /// @param offset From where to start filling. Must be multiple of 4.
  308. /// @param size The bytes to fill. Must be multiple of 4 or MAX_PTR_SIZE to indicate the whole buffer.
  309. /// @param value The value to fill the buffer with.
  310. void fillBuffer(BufferPtr buff, PtrSize offset, PtrSize size, U32 value);
  311. /// Write the occlusion result to buffer.
  312. /// @param[in] query The query to get the result from.
  313. /// @param offset The offset inside the buffer to write the result.
  314. /// @param buff The buffer to update.
  315. void writeOcclusionQueryResultToBuffer(OcclusionQueryPtr query, PtrSize offset, BufferPtr buff);
  316. /// Copy buffer to buffer.
  317. /// @param[in] src Source buffer.
  318. /// @param srcOffset Offset in the src buffer.
  319. /// @param[out] dst Destination buffer.
  320. /// @param dstOffset Offset in the destination buffer.
  321. /// @param range Size to copy.
  322. void copyBufferToBuffer(BufferPtr src, PtrSize srcOffset, BufferPtr dst, PtrSize dstOffset, PtrSize range);
  323. /// Build the acceleration structure.
  324. void buildAccelerationStructure(AccelerationStructurePtr as);
  325. /// @}
  326. /// @name Sync
  327. /// @{
  328. void setTextureBarrier(TexturePtr tex, TextureUsageBit prevUsage, TextureUsageBit nextUsage,
  329. const TextureSubresourceInfo& subresource);
  330. void setTextureSurfaceBarrier(TexturePtr tex, TextureUsageBit prevUsage, TextureUsageBit nextUsage,
  331. const TextureSurfaceInfo& surf);
  332. void setTextureVolumeBarrier(TexturePtr tex, TextureUsageBit prevUsage, TextureUsageBit nextUsage,
  333. const TextureVolumeInfo& vol);
  334. void setBufferBarrier(BufferPtr buff, BufferUsageBit prevUsage, BufferUsageBit nextUsage, PtrSize offset,
  335. PtrSize size);
  336. void setAccelerationStructureBarrier(AccelerationStructurePtr as, AccelerationStructureUsageBit prevUsage,
  337. AccelerationStructureUsageBit nextUsage);
  338. /// @}
  339. /// @name Other
  340. /// @{
  341. /// Reset query before beginOcclusionQuery.
  342. void resetOcclusionQuery(OcclusionQueryPtr query);
  343. /// Begin query.
  344. void beginOcclusionQuery(OcclusionQueryPtr query);
  345. /// End query.
  346. void endOcclusionQuery(OcclusionQueryPtr query);
  347. /// Reset timestamp query before writeTimestamp.
  348. void resetTimestampQuery(TimestampQueryPtr query);
  349. /// Write a timestamp.
  350. void writeTimestamp(TimestampQueryPtr query);
  351. /// Append a second level command buffer.
  352. void pushSecondLevelCommandBuffer(CommandBufferPtr cmdb);
  353. Bool isEmpty() const;
  354. /// The command buffer will co-own a pointer. Useful to track the lifetime of bindless resources.
  355. void addReference(GrObjectPtr ptr);
  356. /// @}
  357. protected:
  358. /// Construct.
  359. CommandBuffer(GrManager* manager, CString name)
  360. : GrObject(manager, CLASS_TYPE, name)
  361. {
  362. }
  363. /// Destroy.
  364. ~CommandBuffer()
  365. {
  366. }
  367. private:
  368. /// Allocate and initialize a new instance.
  369. static ANKI_USE_RESULT CommandBuffer* newInstance(GrManager* manager, const CommandBufferInitInfo& init);
  370. };
  371. /// @}
  372. } // end namespace anki