CommandBuffer.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. // Copyright (C) 2009-2023, 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. #include <AnKi/Math.h>
  11. namespace anki {
  12. /// @addtogroup graphics
  13. /// @{
  14. class TextureBarrierInfo
  15. {
  16. public:
  17. Texture* m_texture = nullptr;
  18. TextureUsageBit m_previousUsage = TextureUsageBit::kNone;
  19. TextureUsageBit m_nextUsage = TextureUsageBit::kNone;
  20. TextureSubresourceInfo m_subresource;
  21. };
  22. class BufferBarrierInfo
  23. {
  24. public:
  25. Buffer* m_buffer = nullptr;
  26. BufferUsageBit m_previousUsage = BufferUsageBit::kNone;
  27. BufferUsageBit m_nextUsage = BufferUsageBit::kNone;
  28. PtrSize m_offset = 0;
  29. PtrSize m_range = 0;
  30. };
  31. class AccelerationStructureBarrierInfo
  32. {
  33. public:
  34. AccelerationStructure* m_as = nullptr;
  35. AccelerationStructureUsageBit m_previousUsage = AccelerationStructureUsageBit::kNone;
  36. AccelerationStructureUsageBit m_nextUsage = AccelerationStructureUsageBit::kNone;
  37. };
  38. class CopyBufferToBufferInfo
  39. {
  40. public:
  41. PtrSize m_sourceOffset = 0;
  42. PtrSize m_destinationOffset = 0;
  43. PtrSize m_range = 0;
  44. };
  45. /// Command buffer initialization flags.
  46. enum class CommandBufferFlag : U8
  47. {
  48. kNone = 0,
  49. kSecondLevel = 1 << 0,
  50. /// It will contain a handfull of commands.
  51. kSmallBatch = 1 << 3,
  52. /// Will contain graphics, compute and transfer work.
  53. kGeneralWork = 1 << 4,
  54. /// Will contain only compute work. It binds to async compute queues.
  55. kComputeWork = 1 << 5,
  56. };
  57. ANKI_ENUM_ALLOW_NUMERIC_OPERATIONS(CommandBufferFlag)
  58. /// Command buffer init info.
  59. class CommandBufferInitInfo : public GrBaseInitInfo
  60. {
  61. public:
  62. Framebuffer* m_framebuffer = nullptr; ///< For second level command buffers.
  63. Array<TextureUsageBit, kMaxColorRenderTargets> m_colorAttachmentUsages = {};
  64. TextureUsageBit m_depthStencilAttachmentUsage = TextureUsageBit::kNone;
  65. CommandBufferFlag m_flags = CommandBufferFlag::kGeneralWork;
  66. CommandBufferInitInfo(CString name = {})
  67. : GrBaseInitInfo(name)
  68. {
  69. }
  70. };
  71. /// Command buffer.
  72. class CommandBuffer : public GrObject
  73. {
  74. ANKI_GR_OBJECT
  75. public:
  76. static constexpr GrObjectType kClassType = GrObjectType::kCommandBuffer;
  77. /// Finalize and submit if it's primary command buffer and just finalize if it's second level.
  78. /// @param[in] waitFences Optionally wait for some fences.
  79. /// @param[out] signalFence Optionaly create fence that will be signaled when the submission is done.
  80. void flush(ConstWeakArray<FencePtr> waitFences = {}, FencePtr* signalFence = nullptr);
  81. /// @name State manipulation
  82. /// @{
  83. /// Bind vertex buffer.
  84. void bindVertexBuffer(U32 binding, Buffer* buff, PtrSize offset, PtrSize stride, VertexStepRate stepRate = VertexStepRate::kVertex);
  85. /// Setup a vertex attribute.
  86. void setVertexAttribute(U32 location, U32 buffBinding, Format fmt, PtrSize relativeOffset);
  87. /// Bind index buffer.
  88. void bindIndexBuffer(Buffer* buff, PtrSize offset, IndexType type);
  89. /// Enable primitive restart.
  90. void setPrimitiveRestart(Bool enable);
  91. /// Set the viewport.
  92. void setViewport(U32 minx, U32 miny, U32 width, U32 height);
  93. /// Set the scissor rect. To disable the scissor just set a rect bigger than the viewport. By default it's disabled.
  94. void setScissor(U32 minx, U32 miny, U32 width, U32 height);
  95. /// Set fill mode.
  96. void setFillMode(FillMode mode);
  97. /// Set cull mode.
  98. /// By default it's FaceSelectionBit::BACK.
  99. void setCullMode(FaceSelectionBit mode);
  100. /// Set depth offset and units. Set zeros to both to disable it.
  101. void setPolygonOffset(F32 factor, F32 units);
  102. /// Set stencil operations. To disable stencil test put StencilOperation::KEEP to all operations.
  103. void setStencilOperations(FaceSelectionBit face, StencilOperation stencilFail, StencilOperation stencilPassDepthFail,
  104. StencilOperation stencilPassDepthPass);
  105. /// Set stencil compare operation.
  106. void setStencilCompareOperation(FaceSelectionBit face, CompareOperation comp);
  107. /// Set the stencil compare mask.
  108. void setStencilCompareMask(FaceSelectionBit face, U32 mask);
  109. /// Set the stencil write mask.
  110. void setStencilWriteMask(FaceSelectionBit face, U32 mask);
  111. /// Set the stencil reference.
  112. void setStencilReference(FaceSelectionBit face, U32 ref);
  113. /// Enable/disable depth write. To disable depth testing set depth write to false and depth compare operation to
  114. /// always.
  115. void setDepthWrite(Bool enable);
  116. /// Set depth compare operation. By default it's less.
  117. void setDepthCompareOperation(CompareOperation op);
  118. /// Enable/disable alpha to coverage.
  119. void setAlphaToCoverage(Bool enable);
  120. /// Set color channel write mask.
  121. void setColorChannelWriteMask(U32 attachment, ColorBit mask);
  122. /// Set blend factors seperate.
  123. /// By default the values of srcRgb, dstRgb, srcA and dstA are BlendFactor::ONE, BlendFactor::ZERO,
  124. /// BlendFactor::ONE, BlendFactor::ZERO respectively.
  125. void setBlendFactors(U32 attachment, BlendFactor srcRgb, BlendFactor dstRgb, BlendFactor srcA, BlendFactor dstA);
  126. /// Set blend factors.
  127. void setBlendFactors(U32 attachment, BlendFactor src, BlendFactor dst)
  128. {
  129. setBlendFactors(attachment, src, dst, src, dst);
  130. }
  131. /// Set the blend operation seperate.
  132. /// By default the values of funcRgb and funcA are BlendOperation::ADD, BlendOperation::ADD respectively.
  133. void setBlendOperation(U32 attachment, BlendOperation funcRgb, BlendOperation funcA);
  134. /// Set the blend operation.
  135. void setBlendOperation(U32 attachment, BlendOperation func)
  136. {
  137. setBlendOperation(attachment, func, func);
  138. }
  139. /// Set the rasterizatin order. By default it's RasterizationOrder::ORDERED.
  140. void setRasterizationOrder(RasterizationOrder order);
  141. /// Set the line width. By default it's undefined.
  142. void setLineWidth(F32 lineWidth);
  143. /// Bind texture and sample.
  144. /// @param set The set to bind to.
  145. /// @param binding The binding to bind to.
  146. /// @param texView The texture view to bind.
  147. /// @param sampler The sampler to override the default sampler of the tex.
  148. /// @param arrayIdx The array index if the binding is an array.
  149. void bindTextureAndSampler(U32 set, U32 binding, TextureView* texView, Sampler* sampler, U32 arrayIdx = 0);
  150. /// Bind sampler.
  151. /// @param set The set to bind to.
  152. /// @param binding The binding to bind to.
  153. /// @param sampler The sampler to override the default sampler of the tex.
  154. /// @param arrayIdx The array index if the binding is an array.
  155. void bindSampler(U32 set, U32 binding, Sampler* sampler, U32 arrayIdx = 0);
  156. /// Bind a texture.
  157. /// @param set The set to bind to.
  158. /// @param binding The binding to bind to.
  159. /// @param texView The texture view to bind.
  160. /// @param arrayIdx The array index if the binding is an array.
  161. void bindTexture(U32 set, U32 binding, TextureView* texView, U32 arrayIdx = 0);
  162. /// Bind uniform buffer.
  163. /// @param set The set to bind to.
  164. /// @param binding The binding to bind to.
  165. /// @param[in,out] buff The buffer to bind.
  166. /// @param offset The base of the binding.
  167. /// @param range The bytes to bind starting from the offset. If it's kMaxPtrSize then map from offset to the end
  168. /// of the buffer.
  169. /// @param arrayIdx The array index if the binding is an array.
  170. void bindUniformBuffer(U32 set, U32 binding, Buffer* buff, PtrSize offset, PtrSize range, U32 arrayIdx = 0);
  171. /// Bind uniform buffer.
  172. /// @param set The set to bind to.
  173. /// @param binding The binding to bind to.
  174. /// @param[in,out] buff The buffer to bind.
  175. /// @param arrayIdx The array index if the binding is an array.
  176. void bindUniformBuffer(U32 set, U32 binding, const BufferOffsetRange& buff, U32 arrayIdx = 0)
  177. {
  178. bindUniformBuffer(set, binding, buff.m_buffer, buff.m_offset, buff.m_range, arrayIdx);
  179. }
  180. /// Bind storage buffer.
  181. /// @param set The set to bind to.
  182. /// @param binding The binding to bind to.
  183. /// @param[in,out] buff The buffer to bind.
  184. /// @param offset The base of the binding.
  185. /// @param range The bytes to bind starting from the offset. If it's kMaxPtrSize then map from offset to the end
  186. /// of the buffer.
  187. /// @param arrayIdx The array index if the binding is an array.
  188. void bindStorageBuffer(U32 set, U32 binding, Buffer* buff, PtrSize offset, PtrSize range, U32 arrayIdx = 0);
  189. /// Bind storage buffer.
  190. /// @param set The set to bind to.
  191. /// @param binding The binding to bind to.
  192. /// @param[in,out] buff The buffer to bind.
  193. /// @param arrayIdx The array index if the binding is an array.
  194. void bindStorageBuffer(U32 set, U32 binding, const BufferOffsetRange& buff, U32 arrayIdx = 0)
  195. {
  196. bindStorageBuffer(set, binding, buff.m_buffer, buff.m_offset, buff.m_range, arrayIdx);
  197. }
  198. /// Bind load/store image.
  199. /// @param set The set to bind to.
  200. /// @param binding The binding to bind to.
  201. /// @param img The view to bind.
  202. /// @param arrayIdx The array index if the binding is an array.
  203. void bindImage(U32 set, U32 binding, TextureView* img, U32 arrayIdx = 0);
  204. /// Bind texture buffer.
  205. /// @param set The set to bind to.
  206. /// @param binding The binding to bind to.
  207. /// @param[in,out] buff The buffer to bind.
  208. /// @param offset The base of the binding.
  209. /// @param range The bytes to bind starting from the offset. If it's kMaxPtrSize then map from offset to the end
  210. /// of the buffer.
  211. /// @param fmt The format of the buffer.
  212. /// @param arrayIdx The array index if the binding is an array.
  213. void bindReadOnlyTextureBuffer(U32 set, U32 binding, Buffer* buff, PtrSize offset, PtrSize range, Format fmt, U32 arrayIdx = 0);
  214. /// Bind an acceleration structure.
  215. /// @param set The set to bind to.
  216. /// @param binding The binding to bind to.
  217. /// @param[in,out] as The AS to bind.
  218. /// @param arrayIdx The array index if the binding is an array.
  219. void bindAccelerationStructure(U32 set, U32 binding, AccelerationStructure* as, U32 arrayIdx = 0);
  220. /// Bind the bindless descriptor set into a slot.
  221. void bindAllBindless(U32 set);
  222. /// Set push constants.
  223. void setPushConstants(const void* data, U32 dataSize);
  224. /// Bind a program.
  225. void bindShaderProgram(ShaderProgram* prog);
  226. /// Begin renderpass.
  227. /// The minx, miny, width, height control the area that the load and store operations will happen. If the scissor is
  228. /// bigger than the render area the results are undefined.
  229. void beginRenderPass(Framebuffer* fb, const Array<TextureUsageBit, kMaxColorRenderTargets>& colorAttachmentUsages,
  230. TextureUsageBit depthStencilAttachmentUsage, U32 minx = 0, U32 miny = 0, U32 width = kMaxU32, U32 height = kMaxU32);
  231. /// End renderpass.
  232. void endRenderPass();
  233. /// Set VRS rate of the following drawcalls. By default it's 1x1.
  234. void setVrsRate(VrsRate rate);
  235. /// @}
  236. /// @name Jobs
  237. /// @{
  238. void drawIndexed(PrimitiveTopology topology, U32 count, U32 instanceCount = 1, U32 firstIndex = 0, U32 baseVertex = 0, U32 baseInstance = 0);
  239. void draw(PrimitiveTopology topology, U32 count, U32 instanceCount = 1, U32 first = 0, U32 baseInstance = 0);
  240. void drawIndexedIndirect(PrimitiveTopology topology, U32 drawCount, PtrSize offset, Buffer* indirectBuff);
  241. void drawIndirect(PrimitiveTopology topology, U32 drawCount, PtrSize offset, Buffer* indirectBuff);
  242. void drawIndexedIndirectCount(PrimitiveTopology topology, Buffer* argBuffer, PtrSize argBufferOffset, Buffer* countBuffer,
  243. PtrSize countBufferOffset, U32 maxDrawCount);
  244. void dispatchCompute(U32 groupCountX, U32 groupCountY, U32 groupCountZ);
  245. void dispatchComputeIndirect(Buffer* argBuffer, PtrSize argBufferOffset);
  246. /// Trace rays.
  247. ///
  248. /// The 1st thing in the sbtBuffer is the ray gen shader group handle:
  249. /// @code RG = RG_offset @endcode
  250. /// The RG_offset is equal to the stbBufferOffset.
  251. ///
  252. /// Then the sbtBuffer contains the miss shader group handles and their data. The indexing is as follows:
  253. /// @code M = M_offset + M_stride * R_miss @endcode
  254. /// The M_offset is equal to stbBufferOffset + GpuDeviceCapabilities::m_sbtRecordSize.
  255. /// The M_stride is equal to GpuDeviceCapabilities::m_sbtRecordSize.
  256. /// The R_miss is defined in the traceRayEXT and it's the "ray type".
  257. ///
  258. /// After the miss shaders the sbtBuffer has the hit group shader group handles and their data. The indexing is:
  259. /// @code HG = HG_offset + (HG_stride * (R_offset + R_stride * G_id + I_offset)) @endcode
  260. /// The HG_offset is equal to sbtBufferOffset + GpuDeviceCapabilities::m_sbtRecordSize * (missShaderCount + 1).
  261. /// The HG_stride is equal GpuDeviceCapabilities::m_sbtRecordSize * rayTypecount.
  262. /// The R_offset and R_stride are provided in traceRayEXT. The R_offset is the "ray type" and R_stride the number of
  263. /// ray types.
  264. /// The G_id is always 0 ATM.
  265. /// The I_offset is the AccelerationStructureInstance::m_hitgroupSbtRecordIndex.
  266. ///
  267. /// @param[in] sbtBuffer The SBT buffer.
  268. /// @param sbtBufferOffset Offset inside the sbtBuffer where SBT records start.
  269. /// @param hitGroupSbtRecordCount The number of SBT records that contain hit groups.
  270. /// @param sbtRecordSize The size of an SBT record
  271. /// @param rayTypecount The number of ray types hosted in the pipeline. See above on how it's been used.
  272. /// @param width Width.
  273. /// @param height Height.
  274. /// @param depth Depth.
  275. void traceRays(Buffer* sbtBuffer, PtrSize sbtBufferOffset, U32 sbtRecordSize, U32 hitGroupSbtRecordCount, U32 rayTypeCount, U32 width, U32 height,
  276. U32 depth);
  277. /// Generate mipmaps for non-3D textures. You have to transition all the mip levels of this face and layer to
  278. /// TextureUsageBit::kGenerateMipmaps before calling this method.
  279. /// @param texView The texture view to generate mips. It should point to a subresource that contains the whole
  280. /// mip chain and only one face and one layer.
  281. void generateMipmaps2d(TextureView* texView);
  282. /// Generate mipmaps only for 3D textures.
  283. /// @param texView The texture view to generate mips.
  284. void generateMipmaps3d(TextureView* tex);
  285. /// Blit from surface to surface.
  286. /// @param srcView The source view that points to a surface.
  287. /// @param dstView The destination view that points to a surface.
  288. void blitTextureViews(TextureView* srcView, TextureView* destView);
  289. /// Clear a single texture surface. Can be used for all textures except 3D.
  290. /// @param[in,out] texView The texture view to clear.
  291. /// @param[in] clearValue The value to clear it with.
  292. void clearTextureView(TextureView* texView, const ClearValue& clearValue);
  293. /// Copy a buffer to a texture surface or volume.
  294. /// @param buff The source buffer to copy from.
  295. /// @param offset The offset in the buffer to start reading from.
  296. /// @param range The size of the buffer to read.
  297. /// @param texView The texture view that points to a surface or volume to write to.
  298. void copyBufferToTextureView(Buffer* buff, PtrSize offset, PtrSize range, TextureView* texView);
  299. /// Fill a buffer with some value.
  300. /// @param[in,out] buff The buffer to fill.
  301. /// @param offset From where to start filling. Must be multiple of 4.
  302. /// @param size The bytes to fill. Must be multiple of 4 or kMaxPtrSize to indicate the whole buffer.
  303. /// @param value The value to fill the buffer with.
  304. void fillBuffer(Buffer* buff, PtrSize offset, PtrSize size, U32 value);
  305. /// Write the occlusion result to buffer.
  306. /// @param[in] queries The queries to write the result of.
  307. /// @param offset The offset inside the buffer to write the result.
  308. /// @param buff The buffer to update.
  309. void writeOcclusionQueriesResultToBuffer(ConstWeakArray<OcclusionQuery*> queries, PtrSize offset, Buffer* buff);
  310. /// Copy buffer to buffer.
  311. /// @param[in] src Source buffer.
  312. /// @param srcOffset Offset in the src buffer.
  313. /// @param[out] dst Destination buffer.
  314. /// @param dstOffset Offset in the destination buffer.
  315. /// @param range Size to copy.
  316. void copyBufferToBuffer(Buffer* src, PtrSize srcOffset, Buffer* dst, PtrSize dstOffset, PtrSize range)
  317. {
  318. Array<CopyBufferToBufferInfo, 1> copies = {{{srcOffset, dstOffset, range}}};
  319. copyBufferToBuffer(src, dst, copies);
  320. }
  321. /// Copy buffer to buffer.
  322. /// @param[in] src Source buffer.
  323. /// @param[out] dst Destination buffer.
  324. /// @param copies Info on the copies.
  325. void copyBufferToBuffer(Buffer* src, Buffer* dst, ConstWeakArray<CopyBufferToBufferInfo> copies);
  326. /// Build the acceleration structure.
  327. void buildAccelerationStructure(AccelerationStructure* as);
  328. /// Do upscaling by an external upscaler
  329. /// @param[in] upscaler the upscaler to use for upscaling
  330. /// @param[in] inColor Source LowRes RenderTarget.
  331. /// @param[out] outUpscaledColor Destination HighRes RenderTarget
  332. /// @param[in] motionVectors Motion Vectors
  333. /// @param[in] depth Depth attachment
  334. /// @param[in] exposure 1x1 Texture containing exposure
  335. /// @param[in] resetAccumulation Whether to clean or not any temporal history
  336. /// @param[in] jitterOffset Jittering offset that was applied during the generation of sourceTexture
  337. /// @param[in] motionVectorsScale Any scale factor that might need to be applied to the motionVectorsTexture (i.e UV
  338. /// space to Pixel space conversion)
  339. void upscale(GrUpscaler* upscaler, TextureView* inColor, TextureView* outUpscaledColor, TextureView* motionVectors, TextureView* depth,
  340. TextureView* exposure, Bool resetAccumulation, const Vec2& jitterOffset, const Vec2& motionVectorsScale);
  341. /// @}
  342. /// @name Sync
  343. /// @{
  344. void setPipelineBarrier(ConstWeakArray<TextureBarrierInfo> textures, ConstWeakArray<BufferBarrierInfo> buffers,
  345. ConstWeakArray<AccelerationStructureBarrierInfo> accelerationStructures);
  346. /// @}
  347. /// @name Other
  348. /// @{
  349. /// Reset queries before beginOcclusionQuery.
  350. void resetOcclusionQueries(ConstWeakArray<OcclusionQuery*> queries);
  351. /// Begin query.
  352. void beginOcclusionQuery(OcclusionQuery* query);
  353. /// End query.
  354. void endOcclusionQuery(OcclusionQuery* query);
  355. /// Reset timestamp queries before writeTimestamp.
  356. void resetTimestampQueries(ConstWeakArray<TimestampQuery*> queries);
  357. /// Write a timestamp.
  358. void writeTimestamp(TimestampQuery* query);
  359. /// Append second level command buffers.
  360. void pushSecondLevelCommandBuffers(ConstWeakArray<CommandBuffer*> cmdbs);
  361. Bool isEmpty() const;
  362. void pushDebugMarker(CString name, Vec3 color);
  363. void popDebugMarker();
  364. /// @}
  365. protected:
  366. /// Construct.
  367. CommandBuffer(CString name)
  368. : GrObject(kClassType, name)
  369. {
  370. }
  371. /// Destroy.
  372. ~CommandBuffer()
  373. {
  374. }
  375. private:
  376. /// Allocate and initialize a new instance.
  377. [[nodiscard]] static CommandBuffer* newInstance(const CommandBufferInitInfo& init);
  378. };
  379. /// @}
  380. } // end namespace anki