CommandBufferImpl.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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. #include <AnKi/Gr/Vulkan/CommandBufferImpl.h>
  6. #include <AnKi/Gr/GrManager.h>
  7. #include <AnKi/Gr/Vulkan/GrManagerImpl.h>
  8. #include <AnKi/Gr/Framebuffer.h>
  9. #include <AnKi/Gr/Vulkan/GrUpscalerImpl.h>
  10. #include <AnKi/Gr/Vulkan/AccelerationStructureImpl.h>
  11. #include <AnKi/Gr/Vulkan/FramebufferImpl.h>
  12. #if ANKI_DLSS
  13. # include <ThirdParty/DlssSdk/sdk/include/nvsdk_ngx.h>
  14. # include <ThirdParty/DlssSdk/sdk/include/nvsdk_ngx_helpers.h>
  15. # include <ThirdParty/DlssSdk/sdk/include/nvsdk_ngx_vk.h>
  16. # include <ThirdParty/DlssSdk/sdk/include/nvsdk_ngx_helpers_vk.h>
  17. #endif
  18. #include <algorithm>
  19. namespace anki {
  20. CommandBufferImpl::~CommandBufferImpl()
  21. {
  22. if(m_empty)
  23. {
  24. ANKI_VK_LOGW("Command buffer was empty");
  25. }
  26. if(!m_finalized)
  27. {
  28. ANKI_VK_LOGW("Command buffer was not flushed");
  29. }
  30. #if ANKI_EXTRA_CHECKS
  31. ANKI_ASSERT(m_debugMarkersPushed == 0);
  32. #endif
  33. }
  34. Error CommandBufferImpl::init(const CommandBufferInitInfo& init)
  35. {
  36. m_tid = Thread::getCurrentThreadId();
  37. m_flags = init.m_flags;
  38. ANKI_CHECK(getGrManagerImpl().getCommandBufferFactory().newCommandBuffer(m_tid, m_flags, m_microCmdb));
  39. m_handle = m_microCmdb->getHandle();
  40. m_pool = &m_microCmdb->getFastMemoryPool();
  41. // Store some of the init info for later
  42. if(!!(m_flags & CommandBufferFlag::kSecondLevel))
  43. {
  44. m_activeFb = init.m_framebuffer;
  45. m_colorAttachmentUsages = init.m_colorAttachmentUsages;
  46. m_depthStencilAttachmentUsage = init.m_depthStencilAttachmentUsage;
  47. m_state.beginRenderPass(static_cast<FramebufferImpl*>(m_activeFb));
  48. m_microCmdb->pushObjectRef(m_activeFb);
  49. }
  50. for(DescriptorSetState& state : m_dsetState)
  51. {
  52. state.init(m_pool);
  53. }
  54. m_state.setVrsCapable(getGrManagerImpl().getDeviceCapabilities().m_vrs);
  55. m_debugMarkers = !!(getGrManagerImpl().getExtensions() & VulkanExtensions::kEXT_debug_utils);
  56. return Error::kNone;
  57. }
  58. void CommandBufferImpl::beginRecording()
  59. {
  60. // Do the begin
  61. VkCommandBufferInheritanceInfo inheritance = {};
  62. inheritance.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO;
  63. VkCommandBufferBeginInfo begin = {};
  64. begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  65. begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  66. begin.pInheritanceInfo = &inheritance;
  67. if(!!(m_flags & CommandBufferFlag::kSecondLevel))
  68. {
  69. FramebufferImpl& impl = static_cast<FramebufferImpl&>(*m_activeFb);
  70. // Calc the layouts
  71. Array<VkImageLayout, kMaxColorRenderTargets> colAttLayouts;
  72. for(U i = 0; i < impl.getColorAttachmentCount(); ++i)
  73. {
  74. const TextureViewImpl& view = static_cast<const TextureViewImpl&>(*impl.getColorAttachment(i));
  75. colAttLayouts[i] = view.getTextureImpl().computeLayout(m_colorAttachmentUsages[i], 0);
  76. }
  77. VkImageLayout dsAttLayout = VK_IMAGE_LAYOUT_MAX_ENUM;
  78. if(impl.hasDepthStencil())
  79. {
  80. const TextureViewImpl& view = static_cast<const TextureViewImpl&>(*impl.getDepthStencilAttachment());
  81. dsAttLayout = view.getTextureImpl().computeLayout(m_depthStencilAttachmentUsage, 0);
  82. }
  83. VkImageLayout sriAttachmentLayout = VK_IMAGE_LAYOUT_MAX_ENUM;
  84. if(impl.hasSri())
  85. {
  86. // Technically it's possible for SRI to be in other layout. Don't bother though
  87. sriAttachmentLayout = VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR;
  88. }
  89. inheritance.renderPass = impl.getRenderPassHandle(colAttLayouts, dsAttLayout, sriAttachmentLayout);
  90. inheritance.subpass = 0;
  91. inheritance.framebuffer = impl.getFramebufferHandle();
  92. begin.flags |= VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT;
  93. }
  94. vkBeginCommandBuffer(m_handle, &begin);
  95. // Stats
  96. if(!!(getGrManagerImpl().getExtensions() & VulkanExtensions::kKHR_pipeline_executable_properties))
  97. {
  98. m_state.setEnablePipelineStatistics(true);
  99. }
  100. }
  101. void CommandBufferImpl::beginRenderPassInternal(Framebuffer* fb, const Array<TextureUsageBit, kMaxColorRenderTargets>& colorAttachmentUsages,
  102. TextureUsageBit depthStencilAttachmentUsage, U32 minx, U32 miny, U32 width, U32 height)
  103. {
  104. commandCommon();
  105. ANKI_ASSERT(!insideRenderPass());
  106. m_rpCommandCount = 0;
  107. m_activeFb = fb;
  108. FramebufferImpl& fbimpl = static_cast<FramebufferImpl&>(*fb);
  109. U32 fbWidth, fbHeight;
  110. fbimpl.getAttachmentsSize(fbWidth, fbHeight);
  111. m_fbSize[0] = fbWidth;
  112. m_fbSize[1] = fbHeight;
  113. ANKI_ASSERT(minx < fbWidth && miny < fbHeight);
  114. const U32 maxx = min<U32>(minx + width, fbWidth);
  115. const U32 maxy = min<U32>(miny + height, fbHeight);
  116. width = maxx - minx;
  117. height = maxy - miny;
  118. ANKI_ASSERT(minx + width <= fbWidth && miny + height <= fbHeight);
  119. m_renderArea[0] = minx;
  120. m_renderArea[1] = miny;
  121. m_renderArea[2] = width;
  122. m_renderArea[3] = height;
  123. m_colorAttachmentUsages = colorAttachmentUsages;
  124. m_depthStencilAttachmentUsage = depthStencilAttachmentUsage;
  125. m_microCmdb->pushObjectRef(fb);
  126. m_subpassContents = VK_SUBPASS_CONTENTS_MAX_ENUM;
  127. // Re-set the viewport and scissor because sometimes they are set clamped
  128. m_viewportDirty = true;
  129. m_scissorDirty = true;
  130. }
  131. void CommandBufferImpl::beginRenderPassInternal()
  132. {
  133. FramebufferImpl& impl = static_cast<FramebufferImpl&>(*m_activeFb);
  134. m_state.beginRenderPass(&impl);
  135. VkRenderPassBeginInfo bi = {};
  136. bi.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  137. bi.clearValueCount = impl.getAttachmentCount();
  138. bi.pClearValues = impl.getClearValues();
  139. bi.framebuffer = impl.getFramebufferHandle();
  140. // Calc the layouts
  141. Array<VkImageLayout, kMaxColorRenderTargets> colAttLayouts;
  142. for(U i = 0; i < impl.getColorAttachmentCount(); ++i)
  143. {
  144. const TextureViewImpl& view = static_cast<const TextureViewImpl&>(*impl.getColorAttachment(i));
  145. colAttLayouts[i] = view.getTextureImpl().computeLayout(m_colorAttachmentUsages[i], 0);
  146. }
  147. VkImageLayout dsAttLayout = VK_IMAGE_LAYOUT_MAX_ENUM;
  148. if(impl.hasDepthStencil())
  149. {
  150. const TextureViewImpl& view = static_cast<const TextureViewImpl&>(*impl.getDepthStencilAttachment());
  151. dsAttLayout = view.getTextureImpl().computeLayout(m_depthStencilAttachmentUsage, 0);
  152. }
  153. VkImageLayout sriAttachmentLayout = VK_IMAGE_LAYOUT_MAX_ENUM;
  154. if(impl.hasSri())
  155. {
  156. // Technically it's possible for SRI to be in other layout. Don't bother though
  157. sriAttachmentLayout = VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR;
  158. }
  159. bi.renderPass = impl.getRenderPassHandle(colAttLayouts, dsAttLayout, sriAttachmentLayout);
  160. const Bool flipvp = flipViewport();
  161. bi.renderArea.offset.x = m_renderArea[0];
  162. if(flipvp)
  163. {
  164. ANKI_ASSERT(m_renderArea[3] <= m_fbSize[1]);
  165. }
  166. bi.renderArea.offset.y = (flipvp) ? m_fbSize[1] - (m_renderArea[1] + m_renderArea[3]) : m_renderArea[1];
  167. bi.renderArea.extent.width = m_renderArea[2];
  168. bi.renderArea.extent.height = m_renderArea[3];
  169. #if !ANKI_PLATFORM_MOBILE
  170. // nVidia SRI cache workaround
  171. if(impl.hasSri())
  172. {
  173. VkMemoryBarrier memBarrier = {};
  174. memBarrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
  175. memBarrier.dstAccessMask = VK_ACCESS_FRAGMENT_SHADING_RATE_ATTACHMENT_READ_BIT_KHR;
  176. const VkPipelineStageFlags srcStages = VK_PIPELINE_STAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR;
  177. const VkPipelineStageFlags dstStages = VK_PIPELINE_STAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR;
  178. vkCmdPipelineBarrier(m_handle, srcStages, dstStages, 0, 1, &memBarrier, 0, nullptr, 0, nullptr);
  179. }
  180. #endif
  181. VkSubpassBeginInfo subpassBeginInfo = {};
  182. subpassBeginInfo.sType = VK_STRUCTURE_TYPE_SUBPASS_BEGIN_INFO;
  183. subpassBeginInfo.contents = m_subpassContents;
  184. vkCmdBeginRenderPass2KHR(m_handle, &bi, &subpassBeginInfo);
  185. m_renderedToDefaultFb = m_renderedToDefaultFb || impl.hasPresentableTexture();
  186. }
  187. void CommandBufferImpl::endRenderPassInternal()
  188. {
  189. commandCommon();
  190. ANKI_ASSERT(insideRenderPass());
  191. if(m_rpCommandCount == 0)
  192. {
  193. // Empty pass
  194. m_subpassContents = VK_SUBPASS_CONTENTS_INLINE;
  195. beginRenderPassInternal();
  196. }
  197. VkSubpassEndInfo subpassEndInfo = {};
  198. subpassEndInfo.sType = VK_STRUCTURE_TYPE_SUBPASS_END_INFO;
  199. vkCmdEndRenderPass2KHR(m_handle, &subpassEndInfo);
  200. m_activeFb = nullptr;
  201. m_state.endRenderPass();
  202. // After pushing second level command buffers the state is undefined. Reset the tracker and rebind the dynamic state
  203. if(m_subpassContents == VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS)
  204. {
  205. m_state.reset();
  206. rebindDynamicState();
  207. }
  208. }
  209. void CommandBufferImpl::endRecording()
  210. {
  211. commandCommon();
  212. ANKI_ASSERT(!m_finalized);
  213. ANKI_ASSERT(!m_empty);
  214. ANKI_VK_CHECKF(vkEndCommandBuffer(m_handle));
  215. m_finalized = true;
  216. #if ANKI_EXTRA_CHECKS
  217. static Atomic<U32> messagePrintCount(0);
  218. constexpr U32 MAX_PRINT_COUNT = 10;
  219. CString message;
  220. if(!!(m_flags & CommandBufferFlag::kSmallBatch))
  221. {
  222. if(m_commandCount > kCommandBufferSmallBatchMaxCommands * 4)
  223. {
  224. message = "Command buffer has too many commands%s: %u";
  225. }
  226. }
  227. else
  228. {
  229. if(m_commandCount <= kCommandBufferSmallBatchMaxCommands / 4)
  230. {
  231. message = "Command buffer has too few commands%s: %u";
  232. }
  233. }
  234. if(!message.isEmpty())
  235. {
  236. const U32 count = messagePrintCount.fetchAdd(1) + 1;
  237. if(count < MAX_PRINT_COUNT)
  238. {
  239. ANKI_VK_LOGW(message.cstr(), "", m_commandCount);
  240. }
  241. else if(count == MAX_PRINT_COUNT)
  242. {
  243. ANKI_VK_LOGW(message.cstr(), " (will ignore further warnings)", m_commandCount);
  244. }
  245. }
  246. #endif
  247. }
  248. void CommandBufferImpl::generateMipmaps2dInternal(TextureView* texView)
  249. {
  250. commandCommon();
  251. const TextureViewImpl& view = static_cast<const TextureViewImpl&>(*texView);
  252. const TextureImpl& tex = view.getTextureImpl();
  253. ANKI_ASSERT(tex.getTextureType() != TextureType::k3D && "Not for 3D");
  254. ANKI_ASSERT(tex.isSubresourceGoodForMipmapGeneration(view.getSubresource()));
  255. const U32 blitCount = tex.getMipmapCount() - 1u;
  256. if(blitCount == 0)
  257. {
  258. // Nothing to be done, flush the previous commands though because you may batch (and sort) things you shouldn't
  259. return;
  260. }
  261. const DepthStencilAspectBit aspect = view.getSubresource().m_depthStencilAspect;
  262. const U32 face = view.getSubresource().m_firstFace;
  263. const U32 layer = view.getSubresource().m_firstLayer;
  264. for(U32 i = 0; i < blitCount; ++i)
  265. {
  266. // Transition source
  267. // OPT: Combine the 2 barriers
  268. if(i > 0)
  269. {
  270. VkImageSubresourceRange range;
  271. tex.computeVkImageSubresourceRange(TextureSubresourceInfo(TextureSurfaceInfo(i, 0, face, layer), aspect), range);
  272. setImageBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
  273. VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, tex.m_imageHandle,
  274. range);
  275. }
  276. // Transition destination
  277. {
  278. VkImageSubresourceRange range;
  279. tex.computeVkImageSubresourceRange(TextureSubresourceInfo(TextureSurfaceInfo(i + 1, 0, face, layer), aspect), range);
  280. setImageBarrier(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, VK_IMAGE_LAYOUT_UNDEFINED, VK_PIPELINE_STAGE_TRANSFER_BIT,
  281. VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, tex.m_imageHandle, range);
  282. }
  283. // Setup the blit struct
  284. I32 srcWidth = tex.getWidth() >> i;
  285. I32 srcHeight = tex.getHeight() >> i;
  286. I32 dstWidth = tex.getWidth() >> (i + 1);
  287. I32 dstHeight = tex.getHeight() >> (i + 1);
  288. ANKI_ASSERT(srcWidth > 0 && srcHeight > 0 && dstWidth > 0 && dstHeight > 0);
  289. U32 vkLayer = 0;
  290. switch(tex.getTextureType())
  291. {
  292. case TextureType::k2D:
  293. case TextureType::k2DArray:
  294. break;
  295. case TextureType::kCube:
  296. vkLayer = face;
  297. break;
  298. case TextureType::kCubeArray:
  299. vkLayer = layer * 6 + face;
  300. break;
  301. default:
  302. ANKI_ASSERT(0);
  303. break;
  304. }
  305. VkImageBlit blit;
  306. blit.srcSubresource.aspectMask = convertImageAspect(aspect);
  307. blit.srcSubresource.baseArrayLayer = vkLayer;
  308. blit.srcSubresource.layerCount = 1;
  309. blit.srcSubresource.mipLevel = i;
  310. blit.srcOffsets[0] = {0, 0, 0};
  311. blit.srcOffsets[1] = {srcWidth, srcHeight, 1};
  312. blit.dstSubresource.aspectMask = convertImageAspect(aspect);
  313. blit.dstSubresource.baseArrayLayer = vkLayer;
  314. blit.dstSubresource.layerCount = 1;
  315. blit.dstSubresource.mipLevel = i + 1;
  316. blit.dstOffsets[0] = {0, 0, 0};
  317. blit.dstOffsets[1] = {dstWidth, dstHeight, 1};
  318. vkCmdBlitImage(m_handle, tex.m_imageHandle, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, tex.m_imageHandle, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1,
  319. &blit, (!!aspect) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR);
  320. }
  321. }
  322. void CommandBufferImpl::copyBufferToTextureViewInternal(Buffer* buff, PtrSize offset, [[maybe_unused]] PtrSize range, TextureView* texView)
  323. {
  324. commandCommon();
  325. const TextureViewImpl& view = static_cast<const TextureViewImpl&>(*texView);
  326. const TextureImpl& tex = view.getTextureImpl();
  327. ANKI_ASSERT(tex.usageValid(TextureUsageBit::kTransferDestination));
  328. ANKI_ASSERT(tex.isSubresourceGoodForCopyFromBuffer(view.getSubresource()));
  329. const VkImageLayout layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  330. const Bool is3D = tex.getTextureType() == TextureType::k3D;
  331. const VkImageAspectFlags aspect = convertImageAspect(view.getSubresource().m_depthStencilAspect);
  332. const TextureSurfaceInfo surf(view.getSubresource().m_firstMipmap, view.getSubresource().m_firstFace, 0, view.getSubresource().m_firstLayer);
  333. const TextureVolumeInfo vol(view.getSubresource().m_firstMipmap);
  334. // Compute the sizes of the mip
  335. const U32 width = tex.getWidth() >> surf.m_level;
  336. const U32 height = tex.getHeight() >> surf.m_level;
  337. ANKI_ASSERT(width && height);
  338. const U32 depth = (is3D) ? (tex.getDepth() >> surf.m_level) : 1u;
  339. if(!is3D)
  340. {
  341. ANKI_ASSERT(range == computeSurfaceSize(width, height, tex.getFormat()));
  342. }
  343. else
  344. {
  345. ANKI_ASSERT(range == computeVolumeSize(width, height, depth, tex.getFormat()));
  346. }
  347. // Copy
  348. VkBufferImageCopy region;
  349. region.imageSubresource.aspectMask = aspect;
  350. region.imageSubresource.baseArrayLayer = (is3D) ? tex.computeVkArrayLayer(vol) : tex.computeVkArrayLayer(surf);
  351. region.imageSubresource.layerCount = 1;
  352. region.imageSubresource.mipLevel = surf.m_level;
  353. region.imageOffset = {0, 0, 0};
  354. region.imageExtent.width = width;
  355. region.imageExtent.height = height;
  356. region.imageExtent.depth = depth;
  357. region.bufferOffset = offset;
  358. region.bufferImageHeight = 0;
  359. region.bufferRowLength = 0;
  360. vkCmdCopyBufferToImage(m_handle, static_cast<const BufferImpl&>(*buff).getHandle(), tex.m_imageHandle, layout, 1, &region);
  361. }
  362. void CommandBufferImpl::rebindDynamicState()
  363. {
  364. m_viewportDirty = true;
  365. m_lastViewport = {};
  366. m_scissorDirty = true;
  367. m_lastScissor = {};
  368. m_vrsRateDirty = true;
  369. m_vrsRate = VrsRate::k1x1;
  370. // Rebind the stencil compare mask
  371. if(m_stencilCompareMasks[0] == m_stencilCompareMasks[1])
  372. {
  373. vkCmdSetStencilCompareMask(m_handle, VK_STENCIL_FACE_FRONT_BIT | VK_STENCIL_FACE_BACK_BIT, m_stencilCompareMasks[0]);
  374. }
  375. else
  376. {
  377. vkCmdSetStencilCompareMask(m_handle, VK_STENCIL_FACE_FRONT_BIT, m_stencilCompareMasks[0]);
  378. vkCmdSetStencilCompareMask(m_handle, VK_STENCIL_FACE_BACK_BIT, m_stencilCompareMasks[1]);
  379. }
  380. // Rebind the stencil write mask
  381. if(m_stencilWriteMasks[0] == m_stencilWriteMasks[1])
  382. {
  383. vkCmdSetStencilWriteMask(m_handle, VK_STENCIL_FACE_FRONT_BIT | VK_STENCIL_FACE_BACK_BIT, m_stencilWriteMasks[0]);
  384. }
  385. else
  386. {
  387. vkCmdSetStencilWriteMask(m_handle, VK_STENCIL_FACE_FRONT_BIT, m_stencilWriteMasks[0]);
  388. vkCmdSetStencilWriteMask(m_handle, VK_STENCIL_FACE_BACK_BIT, m_stencilWriteMasks[1]);
  389. }
  390. // Rebind the stencil reference
  391. if(m_stencilReferenceMasks[0] == m_stencilReferenceMasks[1])
  392. {
  393. vkCmdSetStencilReference(m_handle, VK_STENCIL_FACE_FRONT_BIT | VK_STENCIL_FACE_BACK_BIT, m_stencilReferenceMasks[0]);
  394. }
  395. else
  396. {
  397. vkCmdSetStencilReference(m_handle, VK_STENCIL_FACE_FRONT_BIT, m_stencilReferenceMasks[0]);
  398. vkCmdSetStencilReference(m_handle, VK_STENCIL_FACE_BACK_BIT, m_stencilReferenceMasks[1]);
  399. }
  400. }
  401. void CommandBufferImpl::buildAccelerationStructureInternal(AccelerationStructure* as)
  402. {
  403. commandCommon();
  404. // Get objects
  405. const AccelerationStructureImpl& asImpl = static_cast<AccelerationStructureImpl&>(*as);
  406. // Create the scrach buffer
  407. BufferInitInfo bufferInit;
  408. bufferInit.m_usage = PrivateBufferUsageBit::kAccelerationStructureBuildScratch;
  409. bufferInit.m_size = asImpl.getBuildScratchBufferSize();
  410. BufferPtr scratchBuff = getGrManagerImpl().newBuffer(bufferInit);
  411. // Create the build info
  412. VkAccelerationStructureBuildGeometryInfoKHR buildInfo;
  413. VkAccelerationStructureBuildRangeInfoKHR rangeInfo;
  414. asImpl.generateBuildInfo(scratchBuff->getGpuAddress(), buildInfo, rangeInfo);
  415. // Do the command
  416. Array<const VkAccelerationStructureBuildRangeInfoKHR*, 1> pRangeInfos = {&rangeInfo};
  417. vkCmdBuildAccelerationStructuresKHR(m_handle, 1, &buildInfo, &pRangeInfos[0]);
  418. // Push refs
  419. m_microCmdb->pushObjectRef(as);
  420. }
  421. #if ANKI_DLSS
  422. /// Utility function to get the NGX's resource structure for a texture
  423. /// @param[in] tex the texture to generate the NVSDK_NGX_Resource_VK from
  424. static NVSDK_NGX_Resource_VK getNGXResourceFromAnkiTexture(const TextureViewImpl& view)
  425. {
  426. const TextureImpl& tex = view.getTextureImpl();
  427. const VkImageView imageView = view.getHandle();
  428. const VkFormat format = tex.m_vkFormat;
  429. const VkImage image = tex.m_imageHandle;
  430. const VkImageSubresourceRange subresourceRange = view.getVkImageSubresourceRange();
  431. const Bool isUAV = !!(tex.m_vkUsageFlags & VK_IMAGE_USAGE_STORAGE_BIT);
  432. // TODO Not sure if I should pass the width,height of the image or the view
  433. return NVSDK_NGX_Create_ImageView_Resource_VK(imageView, image, subresourceRange, format, tex.getWidth(), tex.getHeight(), isUAV);
  434. }
  435. #endif
  436. void CommandBufferImpl::upscaleInternal(GrUpscaler* upscaler, TextureView* inColor, TextureView* outUpscaledColor, TextureView* motionVectors,
  437. TextureView* depth, TextureView* exposure, const Bool resetAccumulation, const Vec2& jitterOffset,
  438. const Vec2& motionVectorsScale)
  439. {
  440. #if ANKI_DLSS
  441. ANKI_ASSERT(getGrManagerImpl().getDeviceCapabilities().m_dlss);
  442. ANKI_ASSERT(upscaler->getUpscalerType() == GrUpscalerType::kDlss2);
  443. commandCommon();
  444. const GrUpscalerImpl& upscalerImpl = static_cast<const GrUpscalerImpl&>(*upscaler);
  445. const TextureViewImpl& srcViewImpl = static_cast<const TextureViewImpl&>(*inColor);
  446. const TextureViewImpl& dstViewImpl = static_cast<const TextureViewImpl&>(*outUpscaledColor);
  447. const TextureViewImpl& mvViewImpl = static_cast<const TextureViewImpl&>(*motionVectors);
  448. const TextureViewImpl& depthViewImpl = static_cast<const TextureViewImpl&>(*depth);
  449. const TextureViewImpl& exposureViewImpl = static_cast<const TextureViewImpl&>(*exposure);
  450. NVSDK_NGX_Resource_VK srcResVk = getNGXResourceFromAnkiTexture(srcViewImpl);
  451. NVSDK_NGX_Resource_VK dstResVk = getNGXResourceFromAnkiTexture(dstViewImpl);
  452. NVSDK_NGX_Resource_VK mvResVk = getNGXResourceFromAnkiTexture(mvViewImpl);
  453. NVSDK_NGX_Resource_VK depthResVk = getNGXResourceFromAnkiTexture(depthViewImpl);
  454. NVSDK_NGX_Resource_VK exposureResVk = getNGXResourceFromAnkiTexture(exposureViewImpl);
  455. const U32 mipLevel = srcViewImpl.getSubresource().m_firstMipmap;
  456. const NVSDK_NGX_Coordinates renderingOffset = {0, 0};
  457. const NVSDK_NGX_Dimensions renderingSize = {srcViewImpl.getTextureImpl().getWidth() >> mipLevel,
  458. srcViewImpl.getTextureImpl().getHeight() >> mipLevel};
  459. NVSDK_NGX_VK_DLSS_Eval_Params vkDlssEvalParams;
  460. memset(&vkDlssEvalParams, 0, sizeof(vkDlssEvalParams));
  461. vkDlssEvalParams.Feature.pInColor = &srcResVk;
  462. vkDlssEvalParams.Feature.pInOutput = &dstResVk;
  463. vkDlssEvalParams.pInDepth = &depthResVk;
  464. vkDlssEvalParams.pInMotionVectors = &mvResVk;
  465. vkDlssEvalParams.pInExposureTexture = &exposureResVk;
  466. vkDlssEvalParams.InJitterOffsetX = jitterOffset.x();
  467. vkDlssEvalParams.InJitterOffsetY = jitterOffset.y();
  468. vkDlssEvalParams.InReset = resetAccumulation;
  469. vkDlssEvalParams.InMVScaleX = motionVectorsScale.x();
  470. vkDlssEvalParams.InMVScaleY = motionVectorsScale.y();
  471. vkDlssEvalParams.InColorSubrectBase = renderingOffset;
  472. vkDlssEvalParams.InDepthSubrectBase = renderingOffset;
  473. vkDlssEvalParams.InTranslucencySubrectBase = renderingOffset;
  474. vkDlssEvalParams.InMVSubrectBase = renderingOffset;
  475. vkDlssEvalParams.InRenderSubrectDimensions = renderingSize;
  476. NVSDK_NGX_Parameter* dlssParameters = &upscalerImpl.getParameters();
  477. NVSDK_NGX_Handle* dlssFeature = &upscalerImpl.getFeature();
  478. const NVSDK_NGX_Result result = NGX_VULKAN_EVALUATE_DLSS_EXT(m_handle, dlssFeature, dlssParameters, &vkDlssEvalParams);
  479. if(NVSDK_NGX_FAILED(result))
  480. {
  481. ANKI_VK_LOGF("Failed to NVSDK_NGX_VULKAN_EvaluateFeature for DLSS, code = 0x%08x, info: %ls", result, GetNGXResultAsString(result));
  482. }
  483. #else
  484. ANKI_ASSERT(0 && "Not supported");
  485. (void)upscaler;
  486. (void)inColor;
  487. (void)outUpscaledColor;
  488. (void)motionVectors;
  489. (void)depth;
  490. (void)exposure;
  491. (void)resetAccumulation;
  492. (void)jitterOffset;
  493. (void)motionVectorsScale;
  494. #endif
  495. }
  496. void CommandBufferImpl::setPipelineBarrierInternal(ConstWeakArray<TextureBarrierInfo> textures, ConstWeakArray<BufferBarrierInfo> buffers,
  497. ConstWeakArray<AccelerationStructureBarrierInfo> accelerationStructures)
  498. {
  499. commandCommon();
  500. DynamicArray<VkImageMemoryBarrier, MemoryPoolPtrWrapper<StackMemoryPool>> imageBarriers(m_pool);
  501. DynamicArray<VkBufferMemoryBarrier, MemoryPoolPtrWrapper<StackMemoryPool>> bufferBarriers(m_pool);
  502. DynamicArray<VkMemoryBarrier, MemoryPoolPtrWrapper<StackMemoryPool>> genericBarriers(m_pool);
  503. VkPipelineStageFlags srcStageMask = 0;
  504. VkPipelineStageFlags dstStageMask = 0;
  505. for(const TextureBarrierInfo& barrier : textures)
  506. {
  507. ANKI_ASSERT(barrier.m_texture);
  508. const TextureImpl& impl = static_cast<const TextureImpl&>(*barrier.m_texture);
  509. const TextureUsageBit nextUsage = barrier.m_nextUsage;
  510. const TextureUsageBit prevUsage = barrier.m_previousUsage;
  511. TextureSubresourceInfo subresource = barrier.m_subresource;
  512. ANKI_ASSERT(impl.usageValid(prevUsage));
  513. ANKI_ASSERT(impl.usageValid(nextUsage));
  514. ANKI_ASSERT(((nextUsage & TextureUsageBit::kGenerateMipmaps) == TextureUsageBit::kGenerateMipmaps
  515. || (nextUsage & TextureUsageBit::kGenerateMipmaps) == TextureUsageBit::kNone)
  516. && "GENERATE_MIPMAPS should be alone");
  517. ANKI_ASSERT(impl.isSubresourceValid(subresource));
  518. if(subresource.m_firstMipmap > 0 && nextUsage == TextureUsageBit::kGenerateMipmaps) [[unlikely]]
  519. {
  520. // This transition happens inside CommandBufferImpl::generateMipmapsX. No need to do something
  521. continue;
  522. }
  523. if(nextUsage == TextureUsageBit::kGenerateMipmaps) [[unlikely]]
  524. {
  525. // The transition of the non zero mip levels happens inside CommandBufferImpl::generateMipmapsX so limit the
  526. // subresource
  527. ANKI_ASSERT(subresource.m_firstMipmap == 0 && subresource.m_mipmapCount == 1);
  528. }
  529. VkImageMemoryBarrier& inf = *imageBarriers.emplaceBack();
  530. inf = {};
  531. inf.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  532. inf.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  533. inf.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  534. inf.image = impl.m_imageHandle;
  535. impl.computeVkImageSubresourceRange(subresource, inf.subresourceRange);
  536. VkPipelineStageFlags srcStage;
  537. VkPipelineStageFlags dstStage;
  538. impl.computeBarrierInfo(prevUsage, nextUsage, inf.subresourceRange.baseMipLevel, srcStage, inf.srcAccessMask, dstStage, inf.dstAccessMask);
  539. inf.oldLayout = impl.computeLayout(prevUsage, inf.subresourceRange.baseMipLevel);
  540. inf.newLayout = impl.computeLayout(nextUsage, inf.subresourceRange.baseMipLevel);
  541. srcStageMask |= srcStage;
  542. dstStageMask |= dstStage;
  543. }
  544. for(const BufferBarrierInfo& barrier : buffers)
  545. {
  546. ANKI_ASSERT(barrier.m_buffer);
  547. const BufferImpl& impl = static_cast<const BufferImpl&>(*barrier.m_buffer);
  548. const BufferUsageBit prevUsage = barrier.m_previousUsage;
  549. const BufferUsageBit nextUsage = barrier.m_nextUsage;
  550. VkBufferMemoryBarrier& inf = *bufferBarriers.emplaceBack();
  551. inf = {};
  552. inf.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
  553. inf.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  554. inf.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  555. inf.buffer = impl.getHandle();
  556. ANKI_ASSERT(barrier.m_offset < impl.getSize());
  557. inf.offset = barrier.m_offset;
  558. if(barrier.m_range == kMaxPtrSize)
  559. {
  560. inf.size = VK_WHOLE_SIZE;
  561. }
  562. else
  563. {
  564. ANKI_ASSERT(barrier.m_range > 0);
  565. ANKI_ASSERT(barrier.m_offset + barrier.m_range <= impl.getSize());
  566. inf.size = barrier.m_range;
  567. }
  568. VkPipelineStageFlags srcStage;
  569. VkPipelineStageFlags dstStage;
  570. impl.computeBarrierInfo(prevUsage, nextUsage, srcStage, inf.srcAccessMask, dstStage, inf.dstAccessMask);
  571. srcStageMask |= srcStage;
  572. dstStageMask |= dstStage;
  573. }
  574. for(const AccelerationStructureBarrierInfo& barrier : accelerationStructures)
  575. {
  576. ANKI_ASSERT(barrier.m_as);
  577. VkMemoryBarrier& inf = *genericBarriers.emplaceBack();
  578. inf = {};
  579. inf.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
  580. VkPipelineStageFlags srcStage;
  581. VkPipelineStageFlags dstStage;
  582. AccelerationStructureImpl::computeBarrierInfo(barrier.m_previousUsage, barrier.m_nextUsage, srcStage, inf.srcAccessMask, dstStage,
  583. inf.dstAccessMask);
  584. srcStageMask |= srcStage;
  585. dstStageMask |= dstStage;
  586. m_microCmdb->pushObjectRef(barrier.m_as);
  587. }
  588. vkCmdPipelineBarrier(m_handle, srcStageMask, dstStageMask, 0, genericBarriers.getSize(),
  589. (genericBarriers.getSize()) ? &genericBarriers[0] : nullptr, bufferBarriers.getSize(),
  590. (bufferBarriers.getSize()) ? &bufferBarriers[0] : nullptr, imageBarriers.getSize(),
  591. (imageBarriers.getSize()) ? &imageBarriers[0] : nullptr);
  592. ANKI_TRACE_INC_COUNTER(VkBarrier, 1);
  593. }
  594. } // end namespace anki