3
0

AttachmentReadback.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <Atom/RPI.Public/Buffer/BufferSystemInterface.h>
  9. #include <Atom/RPI.Public/Buffer/Buffer.h>
  10. #include <Atom/RPI.Public/Image/AttachmentImage.h>
  11. #include <Atom/RPI.Public/Image/ImageSystemInterface.h>
  12. #include <Atom/RPI.Public/Pass/AttachmentReadback.h>
  13. #include <Atom/RPI.Public/RPIUtils.h>
  14. #include <Atom/RPI.Reflect/Buffer/BufferAssetCreator.h>
  15. #include <Atom/RHI/CommandList.h>
  16. #include <Atom/RHI/Factory.h>
  17. #include <Atom/RHI/Fence.h>
  18. #include <Atom/RHI/FrameGraphExecuteContext.h>
  19. #include <Atom/RHI/FrameScheduler.h>
  20. #include <Atom/RHI/RHISystemInterface.h>
  21. #include <Atom/RHI/RHIUtils.h>
  22. #include <Atom/RHI/ScopeProducerFunction.h>
  23. #include <AzCore/Serialization/Json/JsonUtils.h>
  24. #include <AzCore/std/smart_ptr/make_shared.h>
  25. namespace AZ
  26. {
  27. namespace RPI
  28. {
  29. // Helper class to build scope producer with functions
  30. class ScopeProducerFunction final
  31. : public RHI::ScopeProducer
  32. {
  33. public:
  34. AZ_CLASS_ALLOCATOR(ScopeProducerFunction, SystemAllocator);
  35. using PrepareFunction = AZStd::function<void(RHI::FrameGraphInterface)>;
  36. using CompileFunction = AZStd::function<void(const RHI::FrameGraphCompileContext&)>;
  37. using ExecuteFunction = AZStd::function<void(const RHI::FrameGraphExecuteContext&)>;
  38. ScopeProducerFunction(
  39. const RHI::ScopeId& scopeId,
  40. PrepareFunction prepareFunction,
  41. CompileFunction compileFunction,
  42. ExecuteFunction executeFunction)
  43. : ScopeProducer(scopeId)
  44. , m_prepareFunction{ AZStd::move(prepareFunction) }
  45. , m_compileFunction{ AZStd::move(compileFunction) }
  46. , m_executeFunction{ AZStd::move(executeFunction) }
  47. {}
  48. private:
  49. //////////////////////////////////////////////////////////////////////////
  50. // ScopeProducer overrides
  51. void SetupFrameGraphDependencies(RHI::FrameGraphInterface builder) override
  52. {
  53. m_prepareFunction(builder);
  54. }
  55. void CompileResources(const RHI::FrameGraphCompileContext& context) override
  56. {
  57. m_compileFunction(context);
  58. }
  59. void BuildCommandList(const RHI::FrameGraphExecuteContext& context) override
  60. {
  61. m_executeFunction(context);
  62. }
  63. //////////////////////////////////////////////////////////////////////////
  64. PrepareFunction m_prepareFunction;
  65. CompileFunction m_compileFunction;
  66. ExecuteFunction m_executeFunction;
  67. };
  68. // Find a format for formats with two planars (DepthStencil) based on its ImageView's aspect flag
  69. RHI::Format FindFormatForAspect(RHI::Format format, RHI::ImageAspect imageAspect)
  70. {
  71. RHI::ImageAspectFlags imageAspectFlags = RHI::GetImageAspectFlags(format);
  72. // only need to convert is the source contains two aspects
  73. if (imageAspectFlags == RHI::ImageAspectFlags::DepthStencil)
  74. {
  75. switch (imageAspect)
  76. {
  77. case RHI::ImageAspect::Stencil:
  78. return RHI::Format::R8_UINT;
  79. case RHI::ImageAspect::Depth:
  80. {
  81. switch (format)
  82. {
  83. case RHI::Format::D32_FLOAT_S8X24_UINT:
  84. return RHI::Format::R32_FLOAT;
  85. case RHI::Format::D24_UNORM_S8_UINT:
  86. return RHI::Format::R32_UINT;
  87. case RHI::Format::D16_UNORM_S8_UINT:
  88. return RHI::Format::R16_UNORM;
  89. default:
  90. AZ_Assert(false, "Unknown DepthStencil format. Please update this function");
  91. return RHI::Format::R32_FLOAT;
  92. }
  93. }
  94. }
  95. }
  96. return format;
  97. }
  98. AttachmentReadback::AttachmentReadback(const RHI::ScopeId& scopeId)
  99. {
  100. for(uint32_t i = 0; i < RHI::Limits::Device::FrameCountMax; i++)
  101. {
  102. m_isReadbackComplete.push_back(false);
  103. }
  104. // Create fence
  105. RHI::Ptr<RHI::Device> device = RHI::RHISystemInterface::Get()->GetDevice();
  106. m_fence = RHI::Factory::Get().CreateFence();
  107. AZ_Assert(m_fence != nullptr, "AttachmentReadback failed to create a fence");
  108. [[maybe_unused]] RHI::ResultCode result = m_fence->Init(*device, RHI::FenceState::Reset);
  109. AZ_Assert(result == RHI::ResultCode::Success, "AttachmentReadback failed to init fence");
  110. // Load shader and srg
  111. constexpr const char* ShaderPath = "shaders/decomposemsimage.azshader";
  112. m_decomposeShader = LoadCriticalShader(ShaderPath);
  113. if (m_decomposeShader == nullptr)
  114. {
  115. AZ_Error("PassSystem", false, "[AttachmentReadback]: Failed to load shader '%s'!", ShaderPath);
  116. return;
  117. }
  118. // Load SRG
  119. const auto srgLayout = m_decomposeShader->FindShaderResourceGroupLayout(SrgBindingSlot::Object);
  120. if (srgLayout)
  121. {
  122. m_decomposeSrg = ShaderResourceGroup::Create(m_decomposeShader->GetAsset(), m_decomposeShader->GetSupervariantIndex(), srgLayout->GetName());
  123. if (!m_decomposeSrg)
  124. {
  125. AZ_Error("PassSystem", false, "Failed to create SRG from shader asset '%s'", ShaderPath);
  126. return;
  127. }
  128. }
  129. RHI::PipelineStateDescriptorForDispatch pipelineStateDescriptor;
  130. const auto& shaderVariant = m_decomposeShader->GetVariant(RPI::ShaderAsset::RootShaderVariantStableId);
  131. shaderVariant.ConfigurePipelineState(pipelineStateDescriptor);
  132. m_dispatchItem.m_pipelineState = m_decomposeShader->AcquirePipelineState(pipelineStateDescriptor);
  133. m_dispatchItem.m_shaderResourceGroupCount = 1;
  134. m_dispatchItem.m_shaderResourceGroups[0] = m_decomposeSrg->GetRHIShaderResourceGroup();
  135. // find srg input indexes
  136. m_decomposeInputImageIndex = m_decomposeSrg->FindShaderInputImageIndex(Name("m_msImage"));
  137. m_decomposeOutputImageIndex = m_decomposeSrg->FindShaderInputImageIndex(Name("m_outputImage"));
  138. // build scope producer for copying
  139. m_copyScopeProducer = AZStd::make_shared<ScopeProducerFunction>(
  140. scopeId,
  141. AZStd::bind(&AttachmentReadback::CopyPrepare, this, AZStd::placeholders::_1),
  142. AZStd::bind(&AttachmentReadback::CopyCompile, this, AZStd::placeholders::_1),
  143. AZStd::bind(&AttachmentReadback::CopyExecute, this, AZStd::placeholders::_1)
  144. );
  145. m_state = ReadbackState::Idle;
  146. }
  147. AttachmentReadback::~AttachmentReadback()
  148. {
  149. Reset();
  150. m_fence = nullptr;
  151. }
  152. bool AttachmentReadback::ReadPassAttachment(const PassAttachment* attachment, const AZ::Name& readbackName, const RHI::ImageSubresourceRange* mipsRange)
  153. {
  154. if (AZ::RHI::IsNullRHI())
  155. {
  156. return false;
  157. }
  158. if (!IsReady())
  159. {
  160. AZ_Assert(false, "AttachmentsReadbackGroup is not ready to readback attachments.");
  161. return false;
  162. }
  163. Reset();
  164. if (!attachment || (attachment->GetAttachmentType() != RHI::AttachmentType::Buffer && attachment->GetAttachmentType() != RHI::AttachmentType::Image))
  165. {
  166. AZ_Assert(false, "ReadPassAttachment: attachment is not a buffer or an image");
  167. return false;
  168. }
  169. m_state = ReadbackState::AttachmentSet;
  170. m_attachmentId = attachment->GetAttachmentId();
  171. m_attachmentType = attachment->GetAttachmentType();
  172. m_readbackName = readbackName;
  173. if (m_readbackName.IsEmpty())
  174. {
  175. m_readbackName = AZStd::string::format("%s_RB", m_attachmentId.GetCStr());
  176. }
  177. m_copyAttachmentId = m_attachmentId;
  178. // Get some attachment information
  179. if (m_attachmentType == RHI::AttachmentType::Buffer)
  180. {
  181. if (attachment->m_importedResource)
  182. {
  183. Buffer* buffer = static_cast<Buffer*>(attachment->m_importedResource.get());
  184. m_bufferAttachmentByteSize = buffer->GetBufferSize();
  185. }
  186. else
  187. {
  188. m_bufferAttachmentByteSize = attachment->m_descriptor.m_buffer.m_byteCount;
  189. }
  190. m_readbackItems.push_back({});
  191. auto& item = m_readbackItems.back();
  192. item.m_readbackBufferArray.resize(RHI::Limits::Device::FrameCountMax, nullptr);
  193. }
  194. else
  195. {
  196. if (attachment->m_importedResource)
  197. {
  198. AttachmentImage* attImage = static_cast<AttachmentImage*>(attachment->m_importedResource.get());
  199. m_imageDescriptor = attImage->GetRHIImage()->GetDescriptor();
  200. }
  201. else
  202. {
  203. m_imageDescriptor = attachment->m_descriptor.m_image;
  204. }
  205. m_imageMipsRange = (mipsRange != nullptr)
  206. ? *mipsRange
  207. : RHI::ImageSubresourceRange(0, 0, 0, 0);
  208. for (uint32_t mipIndex = m_imageMipsRange.m_mipSliceMin; mipIndex <= m_imageMipsRange.m_mipSliceMax; mipIndex++)
  209. {
  210. m_readbackItems.push_back({});
  211. auto& mipItem = m_readbackItems.back();
  212. mipItem.m_readbackBufferArray.resize(RHI::Limits::Device::FrameCountMax, nullptr);
  213. }
  214. // Add decompose scope to convert multi-sampled images to image array
  215. if (m_imageDescriptor.m_multisampleState.m_samples > 1)
  216. {
  217. m_copyAttachmentId = RHI::AttachmentId(AZStd::string::format("%s_Decomposed", m_attachmentId.GetCStr()));
  218. m_decomposeScopeProducer = AZStd::make_shared<ScopeProducerFunction>(
  219. m_copyAttachmentId,
  220. AZStd::bind(&AttachmentReadback::DecomposePrepare, this, AZStd::placeholders::_1),
  221. AZStd::bind(&AttachmentReadback::DecomposeCompile, this, AZStd::placeholders::_1),
  222. AZStd::bind(&AttachmentReadback::DecomposeExecute, this, AZStd::placeholders::_1)
  223. );
  224. }
  225. }
  226. return true;
  227. }
  228. void AttachmentReadback::DecomposePrepare(RHI::FrameGraphInterface frameGraph)
  229. {
  230. RHI::ImageScopeAttachmentDescriptor inputDesc{ m_attachmentId };
  231. inputDesc.m_imageViewDescriptor.m_aspectFlags = RHI::CheckBitsAny(RHI::GetImageAspectFlags(m_imageDescriptor.m_format), RHI::ImageAspectFlags::Depth)?
  232. RHI::ImageAspectFlags::Depth:RHI::ImageAspectFlags::Color;
  233. frameGraph.UseAttachment(inputDesc, RHI::ScopeAttachmentAccess::Read, RHI::ScopeAttachmentUsage::Shader);
  234. RHI::ImageScopeAttachmentDescriptor outputDesc{ m_copyAttachmentId };
  235. frameGraph.UseAttachment(outputDesc, RHI::ScopeAttachmentAccess::Write, RHI::ScopeAttachmentUsage::Shader);
  236. }
  237. void AttachmentReadback::DecomposeCompile(const RHI::FrameGraphCompileContext& context)
  238. {
  239. // prepare compute shader which to convert multi-sample texture to texture array
  240. RHI::DispatchDirect dispatchArgs;
  241. dispatchArgs.m_totalNumberOfThreadsX = m_imageDescriptor.m_size.m_width;
  242. dispatchArgs.m_totalNumberOfThreadsY = m_imageDescriptor.m_size.m_height;
  243. dispatchArgs.m_totalNumberOfThreadsZ = m_imageDescriptor.m_arraySize;
  244. dispatchArgs.m_threadsPerGroupX = 16; // these numbers are matching numthreads in shader file
  245. dispatchArgs.m_threadsPerGroupY = 16;
  246. dispatchArgs.m_threadsPerGroupZ = 1;
  247. m_dispatchItem.m_arguments = dispatchArgs;
  248. const RHI::ImageView* imageView = context.GetImageView(m_attachmentId);
  249. m_decomposeSrg->SetImageView(m_decomposeInputImageIndex, imageView);
  250. imageView = context.GetImageView(m_copyAttachmentId);
  251. m_decomposeSrg->SetImageView(m_decomposeOutputImageIndex, imageView);
  252. m_decomposeSrg->Compile();
  253. }
  254. void AttachmentReadback::DecomposeExecute(const RHI::FrameGraphExecuteContext& context)
  255. {
  256. context.GetCommandList()->Submit(m_dispatchItem);
  257. }
  258. void AttachmentReadback::CopyPrepare(RHI::FrameGraphInterface frameGraph)
  259. {
  260. if (m_attachmentType == RHI::AttachmentType::Buffer)
  261. {
  262. RHI::BufferScopeAttachmentDescriptor descriptor{ m_copyAttachmentId };
  263. descriptor.m_bufferViewDescriptor = RHI::BufferViewDescriptor::CreateRaw(0, aznumeric_cast<uint32_t>(m_bufferAttachmentByteSize));
  264. frameGraph.UseCopyAttachment(descriptor, RHI::ScopeAttachmentAccess::Read);
  265. }
  266. else if (m_attachmentType == RHI::AttachmentType::Image)
  267. {
  268. RHI::ImageScopeAttachmentDescriptor descriptor{ m_copyAttachmentId };
  269. frameGraph.UseCopyAttachment(descriptor, RHI::ScopeAttachmentAccess::Read);
  270. }
  271. frameGraph.SetEstimatedItemCount(static_cast<uint32_t>(m_readbackItems.size()));
  272. frameGraph.SignalFence(*m_fence);
  273. // CPU has already consumed the GPU buffer. We can clear it now.
  274. // We don't do this in the Async callback as the callback can get signaled by the GPU at anytime.
  275. // We were seeing an issue where during the buffer cleanup there was a chance to hit the assert
  276. // related to disconnecting a bus during a dispatch on a lockless Bus.
  277. // The fix is to clear the buffer outside of the callback.
  278. for (int32_t i = 0; i < RHI::Limits::Device::FrameCountMax; i++)
  279. {
  280. if (m_isReadbackComplete[i])
  281. {
  282. m_isReadbackComplete[i] = false;
  283. for (auto& readbackItem : m_readbackItems)
  284. {
  285. readbackItem.m_readbackBufferArray[i] = nullptr;
  286. }
  287. }
  288. }
  289. // Loop the triple buffer index and cache the current index to the callback.
  290. m_readbackBufferCurrentIndex = (m_readbackBufferCurrentIndex + 1) % RHI::Limits::Device::FrameCountMax;
  291. uint32_t readbackBufferCurrentIndex = m_readbackBufferCurrentIndex;
  292. m_fence->WaitOnCpuAsync([this, readbackBufferCurrentIndex]()
  293. {
  294. if (m_state == ReadbackState::Reading)
  295. {
  296. if (CopyBufferData(readbackBufferCurrentIndex))
  297. {
  298. m_state = ReadbackState::Success;
  299. }
  300. else
  301. {
  302. m_state = ReadbackState::Failed;
  303. }
  304. }
  305. if (m_callback)
  306. {
  307. m_callback(GetReadbackResult());
  308. }
  309. Reset();
  310. }
  311. );
  312. }
  313. void AttachmentReadback::CopyCompile(const RHI::FrameGraphCompileContext& context)
  314. {
  315. if (m_attachmentType == RHI::AttachmentType::Buffer)
  316. {
  317. const AZ::RHI::Buffer* buffer = context.GetBuffer(m_copyAttachmentId);
  318. RPI::CommonBufferDescriptor desc;
  319. desc.m_poolType = RPI::CommonBufferPoolType::ReadBack;
  320. desc.m_bufferName = m_readbackName.GetStringView();
  321. desc.m_byteCount = buffer->GetDescriptor().m_byteCount;
  322. m_readbackItems[0].m_readbackBufferArray[m_readbackBufferCurrentIndex] = BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc);
  323. // copy buffer
  324. RHI::CopyBufferDescriptor copyBuffer;
  325. copyBuffer.m_sourceBuffer = buffer;
  326. copyBuffer.m_destinationBuffer = m_readbackItems[0].m_readbackBufferArray[m_readbackBufferCurrentIndex]->GetRHIBuffer();
  327. copyBuffer.m_size = aznumeric_cast<uint32_t>(desc.m_byteCount);
  328. m_readbackItems[0].m_copyItem = copyBuffer;
  329. }
  330. else if (m_attachmentType == RHI::AttachmentType::Image)
  331. {
  332. // copy image to a read back buffer since only a buffer can be accessed by the host.
  333. const AZ::RHI::Image* image = context.GetImage(m_copyAttachmentId);
  334. if (!image)
  335. {
  336. AZ_Warning("AttachmentReadback", false, "Failed to find attachment image %s for copy to buffer", m_copyAttachmentId.GetCStr());
  337. return;
  338. }
  339. m_imageDescriptor = image->GetDescriptor();
  340. for (uint16_t itemIdx = 0; itemIdx < static_cast<uint16_t>(m_readbackItems.size()); itemIdx++)
  341. {
  342. auto& readbackItem = m_readbackItems[itemIdx];
  343. // [GFX TODO] [ATOM-14140] [Pass Tree] Add the ability to output all the array subresources and planars
  344. // only array 0, and one aspect (planar) at this moment.
  345. // Note: Mip Levels and Texture3D images are supported.
  346. const uint16_t mipSlice = m_imageMipsRange.m_mipSliceMin + itemIdx;
  347. RHI::ImageSubresourceRange range(mipSlice, mipSlice, 0, 0);
  348. range.m_aspectFlags = RHI::ImageAspectFlags::Color;
  349. // setup aspect
  350. RHI::ImageAspect imageAspect = RHI::ImageAspect::Color;
  351. RHI::ImageAspectFlags imageAspectFlags = RHI::GetImageAspectFlags(m_imageDescriptor.m_format);
  352. if (RHI::CheckBitsAll(imageAspectFlags, RHI::ImageAspectFlags::Depth))
  353. {
  354. imageAspect = RHI::ImageAspect::Depth;
  355. range.m_aspectFlags = RHI::ImageAspectFlags::Depth;
  356. }
  357. AZStd::vector<RHI::ImageSubresourceLayout> imageSubresourceLayouts;
  358. imageSubresourceLayouts.resize_no_construct(m_imageDescriptor.m_mipLevels);
  359. size_t totalSizeInBytes = 0;
  360. image->GetSubresourceLayouts(range, imageSubresourceLayouts.data(), &totalSizeInBytes);
  361. AZ::u64 byteCount = totalSizeInBytes;
  362. RPI::CommonBufferDescriptor desc;
  363. desc.m_poolType = RPI::CommonBufferPoolType::ReadBack;
  364. desc.m_bufferName = m_readbackName.GetStringView();
  365. desc.m_byteCount = byteCount;
  366. readbackItem.m_readbackBufferArray[m_readbackBufferCurrentIndex] = BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc);
  367. // Use the aspect format as output format, this format is also used as copy destination's format
  368. m_imageDescriptor.m_format = FindFormatForAspect(m_imageDescriptor.m_format, imageAspect);
  369. // copy descriptor for copying image to buffer
  370. RHI::CopyImageToBufferDescriptor copyImageToBuffer;
  371. copyImageToBuffer.m_sourceImage = image;
  372. copyImageToBuffer.m_sourceSize = imageSubresourceLayouts[mipSlice].m_size;
  373. copyImageToBuffer.m_sourceSubresource = RHI::ImageSubresource(mipSlice, 0 /*arraySlice*/, imageAspect);
  374. copyImageToBuffer.m_destinationOffset = 0;
  375. copyImageToBuffer.m_destinationBytesPerRow = imageSubresourceLayouts[mipSlice].m_bytesPerRow;
  376. copyImageToBuffer.m_destinationBytesPerImage = imageSubresourceLayouts[mipSlice].m_bytesPerImage;
  377. copyImageToBuffer.m_destinationBuffer = readbackItem.m_readbackBufferArray[m_readbackBufferCurrentIndex]->GetRHIBuffer();
  378. copyImageToBuffer.m_destinationFormat = m_imageDescriptor.m_format;
  379. readbackItem.m_mipInfo.m_slice = mipSlice;
  380. readbackItem.m_mipInfo.m_size = imageSubresourceLayouts[mipSlice].m_size;
  381. readbackItem.m_copyItem = copyImageToBuffer;
  382. }
  383. }
  384. }
  385. void AttachmentReadback::CopyExecute(const RHI::FrameGraphExecuteContext& context)
  386. {
  387. for (const auto& readbackItem : m_readbackItems)
  388. {
  389. if (readbackItem.m_readbackBufferArray[m_readbackBufferCurrentIndex])
  390. {
  391. context.GetCommandList()->Submit(readbackItem.m_copyItem);
  392. }
  393. }
  394. }
  395. void AttachmentReadback::Reset()
  396. {
  397. m_attachmentId = RHI::AttachmentId{};
  398. m_readbackItems.clear();
  399. m_state = ReadbackState::Idle;
  400. m_readbackName = AZ::Name{};
  401. m_copyAttachmentId = RHI::AttachmentId{};
  402. m_decomposeScopeProducer = nullptr;
  403. if (m_decomposeSrg)
  404. {
  405. m_decomposeSrg->SetImageView(m_decomposeInputImageIndex, nullptr);
  406. m_decomposeSrg->SetImageView(m_decomposeOutputImageIndex, nullptr);
  407. }
  408. if (m_fence)
  409. {
  410. m_fence->Reset();
  411. }
  412. }
  413. AttachmentReadback::ReadbackState AttachmentReadback::GetReadbackState()
  414. {
  415. return m_state;
  416. }
  417. void AttachmentReadback::SetCallback(CallbackFunction callback)
  418. {
  419. m_callback = callback;
  420. }
  421. void AttachmentReadback::SetUserIdentifier(uint32_t userIdentifier)
  422. {
  423. m_userIdentifier = userIdentifier;
  424. }
  425. void AttachmentReadback::FrameBegin(Pass::FramePrepareParams params)
  426. {
  427. if (m_state == AttachmentReadback::ReadbackState::AttachmentSet)
  428. {
  429. // Need decompose
  430. if (m_decomposeScopeProducer)
  431. {
  432. // Create transient image array to save decompose result
  433. RHI::TransientImageDescriptor descriptor;
  434. descriptor.m_attachmentId = m_copyAttachmentId;
  435. auto format = m_imageDescriptor.m_format;
  436. // We can only use one planar for none render target shader output. Set to output Depth aspect only
  437. if (RHI::GetImageAspectFlags(format) == RHI::ImageAspectFlags::DepthStencil)
  438. {
  439. format = FindFormatForAspect(format, RHI::ImageAspect::Depth);
  440. }
  441. descriptor.m_imageDescriptor = RHI::ImageDescriptor::Create2DArray(RHI::ImageBindFlags::ShaderReadWrite,
  442. m_imageDescriptor.m_size.m_width, m_imageDescriptor.m_size.m_height,
  443. m_imageDescriptor.m_multisampleState.m_samples, // Use sample count as array size
  444. format);
  445. params.m_frameGraphBuilder->GetAttachmentDatabase().CreateTransientImage(descriptor);
  446. params.m_frameGraphBuilder->ImportScopeProducer(*m_decomposeScopeProducer.get());
  447. }
  448. // Import copy producer
  449. params.m_frameGraphBuilder->ImportScopeProducer(*m_copyScopeProducer.get());
  450. m_state = AttachmentReadback::ReadbackState::Reading;
  451. }
  452. }
  453. bool AttachmentReadback::IsFinished() const
  454. {
  455. return m_state == ReadbackState::Success || m_state == ReadbackState::Failed;
  456. }
  457. bool AttachmentReadback::IsReady() const
  458. {
  459. return !(m_state == ReadbackState::Reading || m_state == ReadbackState::Uninitialized);
  460. }
  461. AttachmentReadback::ReadbackResult AttachmentReadback::GetReadbackResult() const
  462. {
  463. ReadbackResult result;
  464. result.m_state = m_state;
  465. result.m_attachmentType = m_attachmentType;
  466. result.m_dataBuffer = m_readbackItems[0].m_dataBuffer;
  467. result.m_name = m_readbackName;
  468. result.m_userIdentifier = m_userIdentifier;
  469. result.m_imageDescriptor = m_imageDescriptor;
  470. result.m_imageDescriptor.m_arraySize = 1;
  471. if (m_attachmentType == RHI::AttachmentType::Image)
  472. {
  473. result.m_mipDataBuffers.reserve(m_readbackItems.size());
  474. for (const auto& readbackItem : m_readbackItems)
  475. {
  476. result.m_mipDataBuffers.push_back({});
  477. auto& mipDataBuffer = result.m_mipDataBuffers.back();
  478. mipDataBuffer.m_mipBuffer = readbackItem.m_dataBuffer;
  479. mipDataBuffer.m_mipInfo = readbackItem.m_mipInfo;
  480. }
  481. }
  482. return result;
  483. }
  484. bool AttachmentReadback::CopyBufferData(uint32_t readbackBufferIndex)
  485. {
  486. for (auto& readbackItem : m_readbackItems)
  487. {
  488. Data::Instance<Buffer> readbackBufferCurrent = readbackItem.m_readbackBufferArray[readbackBufferIndex];
  489. if (!readbackBufferCurrent)
  490. {
  491. return false;
  492. }
  493. auto bufferSize = readbackBufferCurrent->GetBufferSize();
  494. readbackItem.m_dataBuffer = AZStd::make_shared<AZStd::vector<uint8_t>>();
  495. void* buf = readbackBufferCurrent->Map(bufferSize, 0);
  496. if (buf)
  497. {
  498. if (m_attachmentType == RHI::AttachmentType::Buffer)
  499. {
  500. readbackItem.m_dataBuffer->resize_no_construct(bufferSize);
  501. memcpy(readbackItem.m_dataBuffer->data(), buf, bufferSize);
  502. }
  503. else if (m_attachmentType == RHI::AttachmentType::Image)
  504. {
  505. RHI::Size mipSize = readbackItem.m_mipInfo.m_size;
  506. RHI::ImageSubresourceLayout imageLayout = RHI::GetImageSubresourceLayout(mipSize,
  507. m_imageDescriptor.m_format);
  508. auto rowCount = imageLayout.m_rowCount;
  509. auto byteCount = imageLayout.m_bytesPerImage;
  510. if (m_imageDescriptor.m_dimension == AZ::RHI::ImageDimension::Image3D)
  511. {
  512. byteCount *= mipSize.m_depth;
  513. rowCount *= mipSize.m_depth;
  514. }
  515. readbackItem.m_dataBuffer->resize_no_construct(byteCount);
  516. const uint8_t* const sourceBegin = static_cast<uint8_t*>(buf);
  517. uint8_t* const destBegin = readbackItem.m_dataBuffer->data();
  518. // The source image WAS the destination when the copy item transferred data from GPU to CPU
  519. // this explains why the name srcBytesPerRow for these memcpy operations.
  520. const auto srcBytesPerRow = readbackItem.m_copyItem.m_imageToBuffer.m_destinationBytesPerRow;
  521. for (uint32_t row = 0; row < rowCount; ++row)
  522. {
  523. void* dest = destBegin + row * imageLayout.m_bytesPerRow;
  524. const void* source = sourceBegin + row * srcBytesPerRow;
  525. memcpy(dest, source, imageLayout.m_bytesPerRow);
  526. }
  527. }
  528. readbackBufferCurrent->Unmap();
  529. m_isReadbackComplete[readbackBufferIndex] = true;
  530. }
  531. else
  532. {
  533. return false;
  534. }
  535. }
  536. return true;
  537. }
  538. } // namespace RPI
  539. } // namespace AZ