Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "precompiled.h"
19 :
20 : #include "DeviceCommandContext.h"
21 :
22 : #include "graphics/Color.h"
23 : #include "lib/debug.h"
24 : #include "ps/CLogger.h"
25 : #include "ps/ConfigDB.h"
26 : #include "ps/containers/StaticVector.h"
27 : #include "renderer/backend/Format.h"
28 : #include "renderer/backend/IBuffer.h"
29 : #include "renderer/backend/IFramebuffer.h"
30 : #include "renderer/backend/IShaderProgram.h"
31 : #include "renderer/backend/ITexture.h"
32 : #include "renderer/backend/PipelineState.h"
33 : #include "renderer/backend/Sampler.h"
34 : #include "renderer/backend/vulkan/Buffer.h"
35 : #include "renderer/backend/vulkan/DescriptorManager.h"
36 : #include "renderer/backend/vulkan/Device.h"
37 : #include "renderer/backend/vulkan/DeviceSelection.h"
38 : #include "renderer/backend/vulkan/Framebuffer.h"
39 : #include "renderer/backend/vulkan/Mapping.h"
40 : #include "renderer/backend/vulkan/PipelineState.h"
41 : #include "renderer/backend/vulkan/RingCommandContext.h"
42 : #include "renderer/backend/vulkan/ShaderProgram.h"
43 : #include "renderer/backend/vulkan/SwapChain.h"
44 : #include "renderer/backend/vulkan/Texture.h"
45 : #include "renderer/backend/vulkan/Utilities.h"
46 :
47 : #include <algorithm>
48 : #include <bit>
49 : #include <cstddef>
50 : #include <cstring>
51 : #include <iterator>
52 : #include <tuple>
53 : #include <utility>
54 :
55 : namespace Renderer
56 : {
57 :
58 : namespace Backend
59 : {
60 :
61 : namespace Vulkan
62 : {
63 :
64 : namespace
65 : {
66 :
67 : constexpr uint32_t UNIFORM_BUFFER_INITIAL_SIZE = 1024 * 1024;
68 : constexpr uint32_t FRAME_INPLACE_BUFFER_INITIAL_SIZE = 128 * 1024;
69 :
70 : struct SBaseImageState
71 : {
72 : VkImageLayout layout = VK_IMAGE_LAYOUT_UNDEFINED;
73 : VkAccessFlags accessMask = 0;
74 : VkPipelineStageFlags stageMask = 0;
75 : };
76 :
77 0 : SBaseImageState GetBaseImageState(CTexture* texture)
78 : {
79 0 : if (texture->GetUsage() & ITexture::Usage::SAMPLED)
80 : {
81 0 : return {
82 : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
83 : VK_ACCESS_SHADER_READ_BIT,
84 0 : VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT};
85 : }
86 0 : else if (texture->GetUsage() & ITexture::Usage::COLOR_ATTACHMENT)
87 : {
88 0 : return {
89 : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
90 : VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
91 0 : VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT};
92 : }
93 0 : else if (texture->GetUsage() & ITexture::Usage::DEPTH_STENCIL_ATTACHMENT)
94 : {
95 0 : return {
96 : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
97 : VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
98 0 : VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT};
99 : }
100 : // The only TRANSFER_DST usage means we can do only readbacks.
101 0 : else if (texture->GetUsage() == ITexture::Usage::TRANSFER_DST)
102 : {
103 0 : return {
104 : VK_IMAGE_LAYOUT_GENERAL,
105 : VK_ACCESS_HOST_READ_BIT,
106 0 : VK_PIPELINE_STAGE_HOST_BIT};
107 : }
108 0 : return {};
109 : }
110 :
111 : class ScopedImageLayoutTransition
112 : {
113 : public:
114 0 : ScopedImageLayoutTransition(
115 : CRingCommandContext& commandContext, const std::span<CTexture* const> textures,
116 : const VkImageLayout layout, const VkAccessFlags accessMask, const VkPipelineStageFlags stageMask)
117 0 : : m_CommandContext(commandContext), m_Textures(textures), m_Layout(layout),
118 0 : m_AccessMask(accessMask), m_StageMask(stageMask)
119 : {
120 0 : for (CTexture* const texture : m_Textures)
121 : {
122 0 : const auto state = GetBaseImageState(texture);
123 :
124 0 : VkImageLayout oldLayout = state.layout;
125 0 : if (!texture->IsInitialized())
126 0 : oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
127 :
128 0 : Utilities::SetTextureLayout(
129 0 : m_CommandContext.GetCommandBuffer(), texture,
130 0 : oldLayout, m_Layout,
131 0 : state.accessMask, m_AccessMask, state.stageMask, m_StageMask);
132 : }
133 0 : }
134 :
135 0 : ~ScopedImageLayoutTransition()
136 : {
137 0 : for (CTexture* const texture : m_Textures)
138 : {
139 0 : const auto state = GetBaseImageState(texture);
140 :
141 0 : Utilities::SetTextureLayout(
142 0 : m_CommandContext.GetCommandBuffer(), texture,
143 0 : m_Layout, state.layout,
144 0 : m_AccessMask, state.accessMask, m_StageMask, state.stageMask);
145 : }
146 0 : }
147 :
148 : private:
149 : CRingCommandContext& m_CommandContext;
150 : const std::span<CTexture* const> m_Textures;
151 : const VkImageLayout m_Layout = VK_IMAGE_LAYOUT_UNDEFINED;
152 : const VkAccessFlags m_AccessMask = 0;
153 : const VkPipelineStageFlags m_StageMask = 0;
154 : };
155 :
156 : template<typename TransferOp>
157 0 : void TransferForEachFramebufferAttachmentPair(
158 : CRingCommandContext& commandContext,
159 : CFramebuffer* sourceFramebuffer, CFramebuffer* destinationFramebuffer,
160 : TransferOp transferOp)
161 : {
162 : const auto& sourceColorAttachments =
163 0 : sourceFramebuffer->GetColorAttachments();
164 : const auto& destinationColorAttachments =
165 0 : destinationFramebuffer->GetColorAttachments();
166 0 : ENSURE(sourceColorAttachments.size() == destinationColorAttachments.size());
167 :
168 0 : for (CTexture* sourceColorAttachment : sourceColorAttachments)
169 0 : ENSURE(sourceColorAttachment->GetUsage() & ITexture::Usage::TRANSFER_SRC);
170 0 : for (CTexture* destinationColorAttachment : destinationColorAttachments)
171 0 : ENSURE(destinationColorAttachment->GetUsage() & ITexture::Usage::TRANSFER_DST);
172 :
173 : // TODO: combine barriers, reduce duplication, add depth.
174 0 : ScopedImageLayoutTransition scopedColorAttachmentsTransition{
175 : commandContext,
176 : {sourceColorAttachments.begin(), sourceColorAttachments.end()},
177 : VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
178 : VK_ACCESS_TRANSFER_READ_BIT,
179 : VK_PIPELINE_STAGE_TRANSFER_BIT};
180 0 : ScopedImageLayoutTransition destinationColorAttachmentsTransition{
181 : commandContext,
182 : {destinationColorAttachments.begin(), destinationColorAttachments.end()},
183 : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
184 : VK_ACCESS_TRANSFER_WRITE_BIT,
185 : VK_PIPELINE_STAGE_TRANSFER_BIT};
186 :
187 0 : for (CFramebuffer::ColorAttachments::size_type index = 0; index < destinationColorAttachments.size(); ++index)
188 : {
189 0 : CTexture* sourceColorAttachment = sourceColorAttachments[index];
190 0 : CTexture* destinationColorAttachment = destinationColorAttachments[index];
191 :
192 0 : transferOp(commandContext.GetCommandBuffer(), sourceColorAttachment, destinationColorAttachment);
193 : }
194 :
195 0 : if (sourceFramebuffer->GetDepthStencilAttachment() && destinationFramebuffer->GetDepthStencilAttachment())
196 : {
197 0 : transferOp(
198 : commandContext.GetCommandBuffer(),
199 : sourceFramebuffer->GetDepthStencilAttachment(),
200 : destinationFramebuffer->GetDepthStencilAttachment());
201 : }
202 0 : }
203 :
204 : } // anonymous namespace
205 :
206 : // A helper class to store consequent uploads to avoid many copy functions.
207 : // We use a buffer in the device memory and NUMBER_OF_FRAMES_IN_FLIGHT
208 : // times bigger buffer in the host memory.
209 : class CDeviceCommandContext::CUploadRing
210 : {
211 : public:
212 : CUploadRing(
213 : CDevice* device, const IBuffer::Type type, const uint32_t initialCapacity);
214 :
215 0 : CBuffer* GetBuffer() { return m_Buffer.get(); }
216 :
217 : uint32_t ScheduleUpload(
218 : VkCommandBuffer commandBuffer, const std::span<const std::byte> data,
219 : const uint32_t alignment);
220 :
221 : void ExecuteUploads(VkCommandBuffer commandBuffer);
222 :
223 : private:
224 : void ResizeIfNeeded(
225 : VkCommandBuffer commandBuffer, const uint32_t dataSize);
226 :
227 : CDevice* m_Device = nullptr;
228 : IBuffer::Type m_Type = IBuffer::Type::VERTEX;
229 : uint32_t m_Capacity = 0;
230 : uint32_t m_BlockIndex = 0, m_BlockOffset = 0;
231 : std::unique_ptr<CBuffer> m_Buffer, m_StagingBuffer;
232 : std::byte* m_StagingBufferMappedData = nullptr;
233 : };
234 :
235 0 : CDeviceCommandContext::CUploadRing::CUploadRing(
236 0 : CDevice* device, const IBuffer::Type type, const uint32_t initialCapacity)
237 0 : : m_Device(device), m_Type(type)
238 : {
239 0 : ResizeIfNeeded(VK_NULL_HANDLE, initialCapacity);
240 0 : }
241 :
242 0 : void CDeviceCommandContext::CUploadRing::ResizeIfNeeded(
243 : VkCommandBuffer commandBuffer, const uint32_t dataSize)
244 : {
245 : // We need to pad the data size for uniforms because we use dynamic offsets
246 : // with a fixed range.
247 0 : const uint32_t paddedDataSize{
248 0 : m_Type == IBuffer::Type::UNIFORM ? std::bit_ceil(dataSize) : dataSize};
249 0 : const bool resizeNeeded = !m_Buffer || m_BlockOffset + paddedDataSize > m_Capacity;
250 : if (!resizeNeeded)
251 : return;
252 :
253 0 : if (m_Buffer && m_BlockOffset > 0)
254 : {
255 0 : ENSURE(commandBuffer != VK_NULL_HANDLE);
256 0 : ExecuteUploads(commandBuffer);
257 : }
258 :
259 0 : m_Capacity = std::max(m_Capacity * 2, std::bit_ceil(dataSize));
260 :
261 0 : m_Buffer = m_Device->CreateCBuffer(
262 0 : "UploadRingBuffer", m_Type, m_Capacity, IBuffer::Usage::DYNAMIC | IBuffer::Usage::TRANSFER_DST);
263 0 : m_StagingBuffer = m_Device->CreateCBuffer(
264 0 : "UploadRingStagingBuffer", IBuffer::Type::UPLOAD, NUMBER_OF_FRAMES_IN_FLIGHT * m_Capacity, IBuffer::Usage::DYNAMIC | IBuffer::Usage::TRANSFER_SRC);
265 0 : ENSURE(m_Buffer && m_StagingBuffer);
266 0 : m_StagingBufferMappedData = static_cast<std::byte*>(m_StagingBuffer->GetMappedData());
267 0 : ENSURE(m_StagingBufferMappedData);
268 :
269 0 : m_BlockIndex = 0;
270 0 : m_BlockOffset = 0;
271 : }
272 :
273 0 : uint32_t CDeviceCommandContext::CUploadRing::ScheduleUpload(
274 : VkCommandBuffer commandBuffer, const std::span<const std::byte> data,
275 : const uint32_t alignment)
276 : {
277 0 : ENSURE(data.size() > 0);
278 0 : ENSURE(std::has_single_bit(alignment));
279 :
280 0 : m_BlockOffset = (m_BlockOffset + alignment - 1) & ~(alignment - 1);
281 :
282 0 : ResizeIfNeeded(commandBuffer, data.size());
283 :
284 0 : const uint32_t destination = m_BlockIndex * m_Capacity + m_BlockOffset;
285 0 : const uint32_t offset = m_BlockOffset;
286 0 : m_BlockOffset += data.size();
287 0 : std::memcpy(m_StagingBufferMappedData + destination, data.data(), data.size());
288 0 : return offset;
289 : }
290 :
291 0 : void CDeviceCommandContext::CUploadRing::ExecuteUploads(
292 : VkCommandBuffer commandBuffer)
293 : {
294 0 : if (m_BlockOffset == 0)
295 0 : return;
296 :
297 0 : const VkPipelineStageFlags stageMask =
298 0 : m_Type == IBuffer::Type::UNIFORM
299 0 : ? VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT
300 : : VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
301 :
302 0 : Utilities::SubmitBufferMemoryBarrier(
303 : commandBuffer, m_Buffer.get(), 0, VK_WHOLE_SIZE,
304 : VK_ACCESS_MEMORY_READ_BIT, VK_ACCESS_TRANSFER_WRITE_BIT,
305 : stageMask, VK_PIPELINE_STAGE_TRANSFER_BIT);
306 :
307 0 : VkBufferCopy region{};
308 0 : region.srcOffset = m_BlockIndex * m_Capacity;
309 0 : region.dstOffset = 0;
310 0 : region.size = m_BlockOffset;
311 :
312 0 : vkCmdCopyBuffer(
313 : commandBuffer,
314 : m_StagingBuffer->GetVkBuffer(), m_Buffer->GetVkBuffer(),
315 : 1, ®ion);
316 :
317 0 : Utilities::SubmitBufferMemoryBarrier(
318 : commandBuffer, m_Buffer.get(), 0, VK_WHOLE_SIZE,
319 : VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_MEMORY_READ_BIT,
320 : VK_PIPELINE_STAGE_TRANSFER_BIT, stageMask);
321 :
322 0 : m_BlockIndex = (m_BlockIndex + 1) % NUMBER_OF_FRAMES_IN_FLIGHT;
323 0 : m_BlockOffset = 0;
324 : }
325 :
326 : // static
327 0 : std::unique_ptr<IDeviceCommandContext> CDeviceCommandContext::Create(CDevice* device)
328 : {
329 0 : std::unique_ptr<CDeviceCommandContext> deviceCommandContext(new CDeviceCommandContext());
330 0 : deviceCommandContext->m_Device = device;
331 0 : deviceCommandContext->m_DebugScopedLabels = device->GetCapabilities().debugScopedLabels;
332 0 : deviceCommandContext->m_PrependCommandContext =
333 0 : device->CreateRingCommandContext(NUMBER_OF_FRAMES_IN_FLIGHT);
334 0 : ENSURE(deviceCommandContext->m_PrependCommandContext);
335 0 : deviceCommandContext->m_CommandContext =
336 0 : device->CreateRingCommandContext(NUMBER_OF_FRAMES_IN_FLIGHT);
337 0 : ENSURE(deviceCommandContext->m_CommandContext);
338 :
339 0 : deviceCommandContext->m_VertexUploadRing = std::make_unique<CUploadRing>(
340 0 : device, IBuffer::Type::VERTEX, FRAME_INPLACE_BUFFER_INITIAL_SIZE);
341 0 : deviceCommandContext->m_IndexUploadRing = std::make_unique<CUploadRing>(
342 0 : device, IBuffer::Type::INDEX, FRAME_INPLACE_BUFFER_INITIAL_SIZE);
343 0 : deviceCommandContext->m_UniformUploadRing = std::make_unique<CUploadRing>(
344 0 : device, IBuffer::Type::UNIFORM, UNIFORM_BUFFER_INITIAL_SIZE);
345 :
346 0 : deviceCommandContext->m_DebugBarrierAfterFramebufferPass = g_ConfigDB.Get(
347 : "renderer.backend.vulkan.debugbarrierafterframebufferpass",
348 0 : deviceCommandContext->m_DebugBarrierAfterFramebufferPass);
349 :
350 0 : return deviceCommandContext;
351 0 : }
352 :
353 0 : CDeviceCommandContext::CDeviceCommandContext() = default;
354 :
355 0 : CDeviceCommandContext::~CDeviceCommandContext()
356 : {
357 0 : VkDevice device = m_Device->GetVkDevice();
358 :
359 0 : vkDeviceWaitIdle(device);
360 :
361 0 : if (m_UniformDescriptorPool != VK_NULL_HANDLE)
362 0 : vkDestroyDescriptorPool(device, m_UniformDescriptorPool, nullptr);
363 0 : }
364 :
365 0 : IDevice* CDeviceCommandContext::GetDevice()
366 : {
367 0 : return m_Device;
368 : }
369 :
370 0 : void CDeviceCommandContext::SetGraphicsPipelineState(
371 : IGraphicsPipelineState* pipelineState)
372 : {
373 0 : ENSURE(pipelineState);
374 0 : if (m_GraphicsPipelineState && m_GraphicsPipelineState->GetUID() == pipelineState->As<CGraphicsPipelineState>()->GetUID())
375 : return;
376 0 : m_GraphicsPipelineState = pipelineState->As<CGraphicsPipelineState>();
377 :
378 0 : CShaderProgram* shaderProgram = m_GraphicsPipelineState->GetShaderProgram()->As<CShaderProgram>();
379 0 : if (m_ShaderProgram != shaderProgram)
380 : {
381 0 : if (m_ShaderProgram)
382 0 : m_ShaderProgram->Unbind();
383 0 : m_ShaderProgram = shaderProgram;
384 : }
385 0 : m_IsPipelineStateDirty = true;
386 : }
387 :
388 0 : void CDeviceCommandContext::SetComputePipelineState(
389 : IComputePipelineState* pipelineState)
390 : {
391 0 : ENSURE(pipelineState);
392 0 : if (m_ComputePipelineState && m_ComputePipelineState->GetUID() == pipelineState->As<CComputePipelineState>()->GetUID())
393 : return;
394 0 : m_ComputePipelineState = pipelineState->As<CComputePipelineState>();
395 :
396 0 : CShaderProgram* shaderProgram = m_ComputePipelineState->GetShaderProgram()->As<CShaderProgram>();
397 0 : if (m_ShaderProgram != shaderProgram)
398 : {
399 0 : if (m_ShaderProgram)
400 0 : m_ShaderProgram->Unbind();
401 0 : m_ShaderProgram = shaderProgram;
402 : }
403 0 : m_IsPipelineStateDirty = true;
404 : }
405 :
406 0 : void CDeviceCommandContext::BlitFramebuffer(
407 : IFramebuffer* sourceFramebuffer, IFramebuffer* destinationFramebuffer,
408 : const Rect& sourceRegion, const Rect& destinationRegion,
409 : const Sampler::Filter filter)
410 : {
411 0 : ENSURE(!m_InsideFramebufferPass);
412 0 : ENSURE(sourceRegion.x >= 0 && sourceRegion.x + sourceRegion.width <= static_cast<int32_t>(sourceFramebuffer->GetWidth()));
413 0 : ENSURE(sourceRegion.y >= 0 && sourceRegion.y + sourceRegion.height <= static_cast<int32_t>(sourceFramebuffer->GetHeight()));
414 0 : ENSURE(destinationRegion.x >= 0 && destinationRegion.x + destinationRegion.width <= static_cast<int32_t>(destinationFramebuffer->GetWidth()));
415 0 : ENSURE(destinationRegion.y >= 0 && destinationRegion.y + destinationRegion.height <= static_cast<int32_t>(destinationFramebuffer->GetHeight()));
416 :
417 0 : TransferForEachFramebufferAttachmentPair(
418 0 : *m_CommandContext,
419 : sourceFramebuffer->As<CFramebuffer>(), destinationFramebuffer->As<CFramebuffer>(),
420 0 : [&sourceRegion, &destinationRegion, filter](
421 0 : VkCommandBuffer commandBuffer, CTexture* sourceColorAttachment, CTexture* destinationColorAttachment)
422 : {
423 : // TODO: we need to check for VK_FORMAT_FEATURE_BLIT_*_BIT for used formats.
424 :
425 0 : const bool isDepth = IsDepthFormat(sourceColorAttachment->GetFormat());
426 0 : const VkImageAspectFlags aspectMask = isDepth ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT;
427 :
428 0 : VkImageBlit region{};
429 : // Currently (0, 0) is the left-bottom corner (legacy from GL), so
430 : // we need to adjust the regions.
431 0 : const uint32_t sourceHeight = sourceColorAttachment->GetHeight();
432 0 : const uint32_t destinationHeight = destinationColorAttachment->GetHeight();
433 0 : region.srcOffsets[0].x = sourceRegion.x;
434 0 : region.srcOffsets[0].y = sourceHeight - sourceRegion.y - sourceRegion.height;
435 0 : region.dstOffsets[0].x = destinationRegion.x;
436 0 : region.dstOffsets[0].y = destinationHeight - destinationRegion.y - destinationRegion.height;
437 0 : region.srcOffsets[1].x = sourceRegion.x + sourceRegion.width;
438 0 : region.srcOffsets[1].y = sourceHeight - sourceRegion.y;
439 0 : region.srcOffsets[1].z = 1;
440 0 : region.dstOffsets[1].x = destinationRegion.x + destinationRegion.width;
441 0 : region.dstOffsets[1].y = destinationHeight - destinationRegion.y;
442 0 : region.dstOffsets[1].z = 1;
443 0 : region.srcSubresource.aspectMask = aspectMask;
444 0 : region.srcSubresource.mipLevel = 0;
445 0 : region.srcSubresource.baseArrayLayer = 0;
446 0 : region.srcSubresource.layerCount = 1;
447 0 : region.dstSubresource.aspectMask = aspectMask;
448 0 : region.dstSubresource.mipLevel = 0;
449 0 : region.dstSubresource.baseArrayLayer = 0;
450 0 : region.dstSubresource.layerCount = 1;
451 :
452 0 : vkCmdBlitImage(
453 : commandBuffer,
454 : sourceColorAttachment->GetImage(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
455 : destinationColorAttachment->GetImage(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
456 : 1, ®ion, filter == Sampler::Filter::LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST);
457 0 : });
458 0 : }
459 :
460 0 : void CDeviceCommandContext::ResolveFramebuffer(
461 : IFramebuffer* sourceFramebuffer, IFramebuffer* destinationFramebuffer)
462 : {
463 0 : ENSURE(!m_InsideFramebufferPass);
464 0 : ENSURE(sourceFramebuffer->As<CFramebuffer>()->GetSampleCount() > 1);
465 0 : ENSURE(destinationFramebuffer->As<CFramebuffer>()->GetSampleCount() == 1);
466 0 : ENSURE(sourceFramebuffer->As<CFramebuffer>()->GetWidth() == destinationFramebuffer->As<CFramebuffer>()->GetWidth());
467 0 : ENSURE(sourceFramebuffer->As<CFramebuffer>()->GetHeight() == destinationFramebuffer->As<CFramebuffer>()->GetHeight());
468 :
469 0 : TransferForEachFramebufferAttachmentPair(
470 0 : *m_CommandContext,
471 : sourceFramebuffer->As<CFramebuffer>(), destinationFramebuffer->As<CFramebuffer>(),
472 0 : [](VkCommandBuffer commandBuffer, CTexture* sourceColorAttachment, CTexture* destinationColorAttachment)
473 : {
474 0 : ENSURE(sourceColorAttachment->GetFormat() == destinationColorAttachment->GetFormat());
475 0 : ENSURE(!IsDepthFormat(sourceColorAttachment->GetFormat()));
476 0 : const VkImageAspectFlags aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
477 :
478 0 : VkImageResolve region{};
479 0 : region.extent.width = sourceColorAttachment->GetWidth();
480 0 : region.extent.height = sourceColorAttachment->GetHeight();
481 0 : region.extent.depth = 1;
482 0 : region.srcSubresource.aspectMask = aspectMask;
483 0 : region.srcSubresource.mipLevel = 0;
484 0 : region.srcSubresource.baseArrayLayer = 0;
485 0 : region.srcSubresource.layerCount = 1;
486 0 : region.dstSubresource.aspectMask = aspectMask;
487 0 : region.dstSubresource.mipLevel = 0;
488 0 : region.dstSubresource.baseArrayLayer = 0;
489 0 : region.dstSubresource.layerCount = 1;
490 :
491 0 : vkCmdResolveImage(
492 : commandBuffer,
493 : sourceColorAttachment->GetImage(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
494 : destinationColorAttachment->GetImage(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
495 : 1, ®ion);
496 0 : });
497 0 : }
498 :
499 0 : void CDeviceCommandContext::ClearFramebuffer(const bool color, const bool depth, const bool stencil)
500 : {
501 0 : ENSURE(m_InsideFramebufferPass);
502 0 : ENSURE(m_Framebuffer);
503 0 : PS::StaticVector<VkClearAttachment, 4> clearAttachments;
504 0 : if (color)
505 : {
506 0 : ENSURE(!m_Framebuffer->GetColorAttachments().empty());
507 0 : for (size_t index = 0; index < m_Framebuffer->GetColorAttachments().size(); ++index)
508 : {
509 0 : VkClearAttachment clearAttachment{};
510 0 : clearAttachment.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
511 0 : const CColor& clearColor = m_Framebuffer->GetClearColor();
512 0 : clearAttachment.clearValue.color.float32[0] = clearColor.r;
513 0 : clearAttachment.clearValue.color.float32[1] = clearColor.g;
514 0 : clearAttachment.clearValue.color.float32[2] = clearColor.b;
515 0 : clearAttachment.clearValue.color.float32[3] = clearColor.a;
516 0 : clearAttachment.colorAttachment = index;
517 0 : clearAttachments.emplace_back(std::move(clearAttachment));
518 : }
519 : }
520 0 : if (depth || stencil)
521 : {
522 0 : ENSURE(m_Framebuffer->GetDepthStencilAttachment());
523 0 : if (stencil)
524 : {
525 0 : const Format depthStencilFormat =
526 0 : m_Framebuffer->GetDepthStencilAttachment()->GetFormat();
527 0 : ENSURE(depthStencilFormat == Format::D24_UNORM_S8_UINT ||
528 : depthStencilFormat == Format::D32_SFLOAT_S8_UINT);
529 : }
530 0 : VkClearAttachment clearAttachment{};
531 0 : if (depth)
532 0 : clearAttachment.aspectMask |= VK_IMAGE_ASPECT_DEPTH_BIT;
533 0 : if (stencil)
534 0 : clearAttachment.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
535 0 : clearAttachment.clearValue.depthStencil.depth = 1.0f;
536 0 : clearAttachment.clearValue.depthStencil.stencil = 0;
537 0 : clearAttachments.emplace_back(std::move(clearAttachment));
538 : }
539 0 : VkClearRect clearRect{};
540 0 : clearRect.layerCount = 1;
541 0 : clearRect.rect.offset.x = 0;
542 0 : clearRect.rect.offset.y = 0;
543 0 : clearRect.rect.extent.width = m_Framebuffer->GetWidth();
544 0 : clearRect.rect.extent.height = m_Framebuffer->GetHeight();
545 0 : vkCmdClearAttachments(
546 : m_CommandContext->GetCommandBuffer(),
547 0 : clearAttachments.size(), clearAttachments.data(),
548 : 1, &clearRect);
549 0 : }
550 :
551 0 : void CDeviceCommandContext::BeginFramebufferPass(IFramebuffer* framebuffer)
552 : {
553 0 : ENSURE(!m_InsideFramebufferPass);
554 0 : ENSURE(!m_InsideComputePass);
555 0 : ENSURE(framebuffer);
556 0 : m_IsPipelineStateDirty = true;
557 0 : m_Framebuffer = framebuffer->As<CFramebuffer>();
558 0 : m_GraphicsPipelineState = nullptr;
559 0 : m_VertexInputLayout = nullptr;
560 :
561 0 : SetScissors(0, nullptr);
562 :
563 0 : for (CTexture* colorAttachment : m_Framebuffer->GetColorAttachments())
564 : {
565 0 : if (!(colorAttachment->GetUsage() & ITexture::Usage::SAMPLED) && colorAttachment->IsInitialized())
566 0 : continue;
567 0 : VkImageLayout oldLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
568 0 : if (!colorAttachment->IsInitialized())
569 0 : oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
570 0 : Utilities::SetTextureLayout(
571 : m_CommandContext->GetCommandBuffer(), colorAttachment,
572 : oldLayout,
573 : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
574 : VK_ACCESS_SHADER_READ_BIT,
575 : VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
576 : VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT);
577 : }
578 :
579 0 : CTexture* depthStencilAttachment = m_Framebuffer->GetDepthStencilAttachment();
580 0 : if (depthStencilAttachment && ((depthStencilAttachment->GetUsage() & ITexture::Usage::SAMPLED) || !depthStencilAttachment->IsInitialized()))
581 : {
582 0 : VkImageLayout oldLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
583 0 : if (!depthStencilAttachment->IsInitialized())
584 0 : oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
585 0 : Utilities::SetTextureLayout(
586 : m_CommandContext->GetCommandBuffer(), depthStencilAttachment, oldLayout,
587 : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
588 : VK_ACCESS_SHADER_READ_BIT,
589 : VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
590 : VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
591 : VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT);
592 : }
593 :
594 0 : m_InsideFramebufferPass = true;
595 :
596 0 : VkRenderPassBeginInfo renderPassBeginInfo{};
597 0 : renderPassBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
598 0 : renderPassBeginInfo.renderPass = m_Framebuffer->GetRenderPass();
599 0 : renderPassBeginInfo.framebuffer = m_Framebuffer->GetFramebuffer();
600 0 : renderPassBeginInfo.renderArea.offset = { 0, 0 };
601 0 : renderPassBeginInfo.renderArea.extent = { m_Framebuffer->GetWidth(), m_Framebuffer->GetHeight() };
602 :
603 0 : PS::StaticVector<VkClearValue, 4> clearValues;
604 0 : const bool needsClearValues =
605 0 : m_Framebuffer->GetColorAttachmentLoadOp() == AttachmentLoadOp::CLEAR ||
606 0 : (m_Framebuffer->GetDepthStencilAttachment() &&
607 0 : m_Framebuffer->GetDepthStencilAttachmentLoadOp() == AttachmentLoadOp::CLEAR);
608 0 : if (needsClearValues)
609 : {
610 0 : const CFramebuffer::ColorAttachments& colorAttachments{m_Framebuffer->GetColorAttachments()};
611 0 : std::for_each(colorAttachments.begin(), colorAttachments.end(), [&](CTexture*)
612 : {
613 0 : const CColor& clearColor = m_Framebuffer->GetClearColor();
614 : // The four array elements of the clear color map to R, G, B, and A
615 : // components of image formats, in order.
616 0 : clearValues.emplace_back();
617 0 : clearValues.back().color.float32[0] = clearColor.r;
618 0 : clearValues.back().color.float32[1] = clearColor.g;
619 0 : clearValues.back().color.float32[2] = clearColor.b;
620 0 : clearValues.back().color.float32[3] = clearColor.a;
621 0 : });
622 0 : if (m_Framebuffer->GetDepthStencilAttachment())
623 : {
624 0 : clearValues.emplace_back();
625 0 : clearValues.back().depthStencil.depth = 1.0f;
626 0 : clearValues.back().depthStencil.stencil = 0;
627 : }
628 0 : renderPassBeginInfo.clearValueCount = clearValues.size();
629 0 : renderPassBeginInfo.pClearValues = clearValues.data();
630 : }
631 :
632 0 : vkCmdBeginRenderPass(m_CommandContext->GetCommandBuffer(), &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
633 0 : }
634 :
635 0 : void CDeviceCommandContext::EndFramebufferPass()
636 : {
637 0 : ENSURE(m_InsideFramebufferPass);
638 0 : vkCmdEndRenderPass(m_CommandContext->GetCommandBuffer());
639 :
640 0 : m_InsideFramebufferPass = false;
641 0 : m_BoundIndexBuffer = nullptr;
642 :
643 0 : ENSURE(m_Framebuffer);
644 0 : for (CTexture* colorAttachment : m_Framebuffer->GetColorAttachments())
645 : {
646 0 : if (!(colorAttachment->GetUsage() & ITexture::Usage::SAMPLED))
647 0 : continue;
648 0 : Utilities::SetTextureLayout(
649 : m_CommandContext->GetCommandBuffer(), colorAttachment,
650 : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
651 : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
652 : VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
653 : VK_ACCESS_SHADER_READ_BIT,
654 : VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
655 : }
656 :
657 0 : CTexture* depthStencilAttachment = m_Framebuffer->GetDepthStencilAttachment();
658 0 : if (depthStencilAttachment && (depthStencilAttachment->GetUsage() & ITexture::Usage::SAMPLED))
659 : {
660 0 : Utilities::SetTextureLayout(
661 : m_CommandContext->GetCommandBuffer(), depthStencilAttachment,
662 : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
663 : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
664 : VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
665 : VK_ACCESS_SHADER_READ_BIT,
666 : VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
667 : VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
668 : }
669 :
670 0 : m_LastBoundPipeline = VK_NULL_HANDLE;
671 0 : if (m_ShaderProgram)
672 0 : m_ShaderProgram->Unbind();
673 0 : m_ShaderProgram = nullptr;
674 0 : m_GraphicsPipelineState = nullptr;
675 :
676 0 : if (m_DebugBarrierAfterFramebufferPass)
677 0 : Utilities::SubmitDebugSyncMemoryBarrier(m_CommandContext->GetCommandBuffer());
678 0 : }
679 :
680 0 : void CDeviceCommandContext::ReadbackFramebufferSync(
681 : ISwapChain& swapChain, const uint32_t x, const uint32_t y,
682 : const uint32_t width, const uint32_t height,
683 : void* data)
684 : {
685 0 : CSwapChain* queuedSwapChain{(&swapChain)->As<CSwapChain>()};
686 0 : ENSURE(queuedSwapChain->IsValid());
687 0 : CTexture* texture{queuedSwapChain->GetCurrentBackbufferTexture()};
688 0 : if (!texture)
689 : {
690 0 : LOGERROR("Vulkan: backbuffer is unavailable.");
691 0 : return;
692 : }
693 0 : if (!(texture->GetUsage() & ITexture::Usage::TRANSFER_SRC))
694 : {
695 0 : LOGERROR("Vulkan: backbuffer doesn't support readback.");
696 0 : return;
697 : }
698 0 : m_QueuedReadbacks.emplace_back(x, y, width, height, data);
699 0 : ENSURE(!m_QueuedReadbackSwapChain || m_QueuedReadbackSwapChain == queuedSwapChain);
700 0 : m_QueuedReadbackSwapChain = queuedSwapChain;
701 : }
702 :
703 0 : void CDeviceCommandContext::UploadTexture(ITexture* texture, const Format dataFormat,
704 : const void* data, const size_t dataSize,
705 : const uint32_t level, const uint32_t layer)
706 : {
707 0 : (m_InsideFramebufferPass ? m_PrependCommandContext : m_CommandContext)->ScheduleUpload(
708 : texture->As<CTexture>(), dataFormat, data, dataSize, level, layer);
709 0 : }
710 :
711 0 : void CDeviceCommandContext::UploadTextureRegion(ITexture* texture, const Format dataFormat,
712 : const void* data, const size_t dataSize,
713 : const uint32_t xOffset, const uint32_t yOffset,
714 : const uint32_t width, const uint32_t height,
715 : const uint32_t level, const uint32_t layer)
716 : {
717 0 : (m_InsideFramebufferPass ? m_PrependCommandContext : m_CommandContext)->ScheduleUpload(
718 : texture->As<CTexture>(), dataFormat, data, dataSize, xOffset, yOffset, width, height, level, layer);
719 0 : }
720 :
721 0 : void CDeviceCommandContext::UploadBuffer(IBuffer* buffer, const void* data, const uint32_t dataSize)
722 : {
723 0 : ENSURE(!m_InsideFramebufferPass);
724 0 : m_CommandContext->ScheduleUpload(
725 : buffer->As<CBuffer>(), data, 0, dataSize);
726 0 : }
727 :
728 0 : void CDeviceCommandContext::UploadBuffer(IBuffer* buffer, const UploadBufferFunction& uploadFunction)
729 : {
730 0 : ENSURE(!m_InsideFramebufferPass);
731 0 : m_CommandContext->ScheduleUpload(
732 : buffer->As<CBuffer>(), 0, buffer->As<CBuffer>()->GetSize(), uploadFunction);
733 0 : }
734 :
735 0 : void CDeviceCommandContext::UploadBufferRegion(
736 : IBuffer* buffer, const void* data, const uint32_t dataOffset, const uint32_t dataSize)
737 : {
738 0 : ENSURE(!m_InsideFramebufferPass);
739 0 : m_CommandContext->ScheduleUpload(
740 : buffer->As<CBuffer>(), data, dataOffset, dataSize);
741 0 : }
742 :
743 0 : void CDeviceCommandContext::UploadBufferRegion(
744 : IBuffer* buffer, const uint32_t dataOffset, const uint32_t dataSize,
745 : const UploadBufferFunction& uploadFunction)
746 : {
747 0 : m_CommandContext->ScheduleUpload(
748 : buffer->As<CBuffer>(), dataOffset, dataSize, uploadFunction);
749 0 : }
750 :
751 0 : void CDeviceCommandContext::SetScissors(const uint32_t scissorCount, const Rect* scissors)
752 : {
753 0 : ENSURE(m_Framebuffer);
754 0 : ENSURE(scissorCount <= 1);
755 0 : VkRect2D scissor{};
756 0 : if (scissorCount == 1)
757 : {
758 : // the x and y members of offset member of any element of pScissors must be
759 : // greater than or equal to 0.
760 0 : int32_t x = scissors[0].x;
761 0 : int32_t y = m_Framebuffer->GetHeight() - scissors[0].y - scissors[0].height;
762 0 : int32_t width = scissors[0].width;
763 0 : int32_t height = scissors[0].height;
764 0 : if (x < 0)
765 : {
766 0 : width = std::max(0, width + x);
767 0 : x = 0;
768 : }
769 0 : if (y < 0)
770 : {
771 0 : height = std::max(0, height + y);
772 0 : y = 0;
773 : }
774 0 : scissor.offset.x = x;
775 0 : scissor.offset.y = y;
776 0 : scissor.extent.width = width;
777 0 : scissor.extent.height = height;
778 : }
779 : else
780 : {
781 0 : scissor.extent.width = m_Framebuffer->GetWidth();
782 0 : scissor.extent.height = m_Framebuffer->GetHeight();
783 : }
784 0 : vkCmdSetScissor(m_CommandContext->GetCommandBuffer(), 0, 1, &scissor);
785 0 : }
786 :
787 0 : void CDeviceCommandContext::SetViewports(const uint32_t viewportCount, const Rect* viewports)
788 : {
789 0 : ENSURE(m_Framebuffer);
790 0 : ENSURE(viewportCount == 1);
791 :
792 0 : VkViewport viewport{};
793 0 : viewport.minDepth = 0.0f;
794 0 : viewport.maxDepth = 1.0f;
795 0 : viewport.x = static_cast<float>(viewports[0].x);
796 0 : viewport.y = static_cast<float>(static_cast<int32_t>(m_Framebuffer->GetHeight()) - viewports[0].y - viewports[0].height);
797 0 : viewport.width = static_cast<float>(viewports[0].width);
798 0 : viewport.height = static_cast<float>(viewports[0].height);
799 :
800 0 : vkCmdSetViewport(m_CommandContext->GetCommandBuffer(), 0, 1, &viewport);
801 0 : }
802 :
803 0 : void CDeviceCommandContext::SetVertexInputLayout(
804 : IVertexInputLayout* vertexInputLayout)
805 : {
806 0 : ENSURE(vertexInputLayout);
807 0 : if (m_VertexInputLayout != vertexInputLayout->As<CVertexInputLayout>())
808 : {
809 0 : m_IsPipelineStateDirty = true;
810 0 : m_VertexInputLayout = vertexInputLayout->As<CVertexInputLayout>();
811 : }
812 0 : }
813 :
814 0 : void CDeviceCommandContext::SetVertexBuffer(
815 : const uint32_t bindingSlot, IBuffer* buffer, const uint32_t offset)
816 : {
817 0 : BindVertexBuffer(bindingSlot, buffer->As<CBuffer>(), offset);
818 0 : }
819 :
820 0 : void CDeviceCommandContext::SetVertexBufferData(
821 : const uint32_t bindingSlot, const void* data, const uint32_t dataSize)
822 : {
823 : // TODO: check vertex buffer alignment.
824 0 : const uint32_t ALIGNMENT = 32;
825 :
826 0 : const uint32_t offset = m_VertexUploadRing->ScheduleUpload(
827 : m_PrependCommandContext->GetCommandBuffer(),
828 : std::span<const std::byte>{static_cast<const std::byte*>(data), dataSize}, ALIGNMENT);
829 0 : BindVertexBuffer(bindingSlot, m_VertexUploadRing->GetBuffer(), offset);
830 0 : }
831 :
832 0 : void CDeviceCommandContext::SetIndexBuffer(IBuffer* buffer)
833 : {
834 0 : BindIndexBuffer(buffer->As<CBuffer>(), 0);
835 0 : }
836 :
837 0 : void CDeviceCommandContext::SetIndexBufferData(
838 : const void* data, const uint32_t dataSize)
839 : {
840 : // TODO: check index buffer alignment.
841 0 : const uint32_t ALIGNMENT = 32;
842 :
843 0 : const uint32_t offset = m_IndexUploadRing->ScheduleUpload(
844 : m_PrependCommandContext->GetCommandBuffer(),
845 : std::span<const std::byte>{static_cast<const std::byte*>(data), dataSize}, ALIGNMENT);
846 0 : BindIndexBuffer(m_IndexUploadRing->GetBuffer(), offset);
847 0 : }
848 :
849 0 : void CDeviceCommandContext::BeginPass()
850 : {
851 0 : ENSURE(m_InsideFramebufferPass);
852 0 : m_InsidePass = true;
853 0 : }
854 :
855 0 : void CDeviceCommandContext::EndPass()
856 : {
857 0 : ENSURE(m_InsidePass);
858 0 : m_InsidePass = false;
859 0 : }
860 :
861 0 : void CDeviceCommandContext::Draw(const uint32_t firstVertex, const uint32_t vertexCount)
862 : {
863 0 : PreDraw();
864 0 : vkCmdDraw(m_CommandContext->GetCommandBuffer(), vertexCount, 1, firstVertex, 0);
865 0 : }
866 :
867 0 : void CDeviceCommandContext::DrawIndexed(
868 : const uint32_t firstIndex, const uint32_t indexCount, const int32_t vertexOffset)
869 : {
870 0 : ENSURE(vertexOffset == 0);
871 0 : PreDraw();
872 0 : vkCmdDrawIndexed(m_CommandContext->GetCommandBuffer(), indexCount, 1, firstIndex, 0, 0);
873 0 : }
874 :
875 0 : void CDeviceCommandContext::DrawInstanced(
876 : const uint32_t firstVertex, const uint32_t vertexCount,
877 : const uint32_t firstInstance, const uint32_t instanceCount)
878 : {
879 0 : PreDraw();
880 0 : vkCmdDraw(
881 : m_CommandContext->GetCommandBuffer(), vertexCount, instanceCount, firstVertex, firstInstance);
882 0 : }
883 :
884 0 : void CDeviceCommandContext::DrawIndexedInstanced(
885 : const uint32_t firstIndex, const uint32_t indexCount,
886 : const uint32_t firstInstance, const uint32_t instanceCount,
887 : const int32_t vertexOffset)
888 : {
889 0 : PreDraw();
890 0 : vkCmdDrawIndexed(
891 : m_CommandContext->GetCommandBuffer(), indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
892 0 : }
893 :
894 0 : void CDeviceCommandContext::DrawIndexedInRange(
895 : const uint32_t firstIndex, const uint32_t indexCount,
896 : const uint32_t /*start*/, const uint32_t /*end*/)
897 : {
898 0 : DrawIndexed(firstIndex, indexCount, 0);
899 0 : }
900 :
901 0 : void CDeviceCommandContext::BeginComputePass()
902 : {
903 0 : ENSURE(!m_InsideFramebufferPass);
904 0 : ENSURE(!m_InsideComputePass);
905 0 : m_InsideComputePass = true;
906 0 : }
907 :
908 0 : void CDeviceCommandContext::EndComputePass()
909 : {
910 0 : if (m_ShaderProgram)
911 : {
912 0 : m_ShaderProgram->Unbind();
913 0 : m_ShaderProgram = nullptr;
914 : }
915 0 : m_LastBoundPipeline = VK_NULL_HANDLE;
916 0 : m_ComputePipelineState = nullptr;
917 :
918 0 : ENSURE(m_InsideComputePass);
919 0 : m_InsideComputePass = false;
920 0 : }
921 :
922 0 : void CDeviceCommandContext::Dispatch(
923 : const uint32_t groupCountX,
924 : const uint32_t groupCountY,
925 : const uint32_t groupCountZ)
926 : {
927 0 : ENSURE(m_InsideComputePass);
928 0 : ApplyPipelineStateIfDirty();
929 0 : m_ShaderProgram->PreDispatch(*m_CommandContext);
930 0 : UpdateOutdatedConstants();
931 0 : vkCmdDispatch(
932 : m_CommandContext->GetCommandBuffer(), groupCountX, groupCountY, groupCountZ);
933 0 : m_ShaderProgram->PostDispatch(*m_CommandContext);
934 0 : }
935 :
936 0 : void CDeviceCommandContext::InsertMemoryBarrier(
937 : const uint32_t srcStageMask, const uint32_t dstStageMask,
938 : const uint32_t srcAccessMask, const uint32_t dstAccessMask)
939 : {
940 0 : ENSURE(!m_InsideFramebufferPass);
941 0 : Utilities::SubmitMemoryBarrier(
942 : m_CommandContext->GetCommandBuffer(),
943 : Mapping::FromAccessMask(srcAccessMask), Mapping::FromAccessMask(dstAccessMask),
944 : Mapping::FromPipelineStageMask(srcStageMask), Mapping::FromPipelineStageMask(dstStageMask));
945 0 : }
946 :
947 0 : void CDeviceCommandContext::SetTexture(const int32_t bindingSlot, ITexture* texture)
948 : {
949 0 : if (bindingSlot < 0)
950 0 : return;
951 :
952 0 : ENSURE(m_InsidePass || m_InsideComputePass);
953 0 : ENSURE(texture);
954 0 : CTexture* textureToBind = texture->As<CTexture>();
955 0 : ENSURE(textureToBind->GetUsage() & ITexture::Usage::SAMPLED);
956 :
957 0 : if (!m_Device->GetDescriptorManager().UseDescriptorIndexing() && m_InsidePass)
958 : {
959 : // We can't bind textures which are used as attachments.
960 0 : const auto& colorAttachments = m_Framebuffer->GetColorAttachments();
961 0 : ENSURE(std::find(
962 : colorAttachments.begin(), colorAttachments.end(), textureToBind) == colorAttachments.end());
963 0 : ENSURE(m_Framebuffer->GetDepthStencilAttachment() != textureToBind);
964 :
965 0 : ENSURE(textureToBind->IsInitialized());
966 : }
967 :
968 0 : m_ShaderProgram->SetTexture(bindingSlot, textureToBind);
969 : }
970 :
971 0 : void CDeviceCommandContext::SetStorageTexture(const int32_t bindingSlot, ITexture* texture)
972 : {
973 0 : ENSURE(m_InsidePass || m_InsideComputePass);
974 0 : ENSURE(texture);
975 0 : CTexture* textureToBind = texture->As<CTexture>();
976 0 : ENSURE(textureToBind->GetUsage() & ITexture::Usage::STORAGE);
977 0 : m_ShaderProgram->SetStorageTexture(bindingSlot, textureToBind);
978 0 : }
979 :
980 0 : void CDeviceCommandContext::SetStorageBuffer(const int32_t bindingSlot, IBuffer* buffer)
981 : {
982 0 : ENSURE(m_InsidePass || m_InsideComputePass);
983 0 : ENSURE(buffer);
984 0 : CBuffer* bufferToBind = buffer->As<CBuffer>();
985 0 : ENSURE(bufferToBind->GetType() == IBuffer::Type::VERTEX || bufferToBind->GetType() == IBuffer::Type::INDEX);
986 0 : ENSURE(bufferToBind->GetUsage() & IBuffer::Usage::STORAGE);
987 0 : m_ShaderProgram->SetStorageBuffer(bindingSlot, bufferToBind);
988 0 : }
989 :
990 0 : void CDeviceCommandContext::SetUniform(
991 : const int32_t bindingSlot,
992 : const float value)
993 : {
994 0 : ENSURE(m_InsidePass || m_InsideComputePass);
995 0 : m_ShaderProgram->SetUniform(bindingSlot, value);
996 0 : }
997 :
998 0 : void CDeviceCommandContext::SetUniform(
999 : const int32_t bindingSlot,
1000 : const float valueX, const float valueY)
1001 : {
1002 0 : ENSURE(m_InsidePass || m_InsideComputePass);
1003 0 : m_ShaderProgram->SetUniform(bindingSlot, valueX, valueY);
1004 0 : }
1005 :
1006 0 : void CDeviceCommandContext::SetUniform(
1007 : const int32_t bindingSlot,
1008 : const float valueX, const float valueY,
1009 : const float valueZ)
1010 : {
1011 0 : ENSURE(m_InsidePass || m_InsideComputePass);
1012 0 : m_ShaderProgram->SetUniform(bindingSlot, valueX, valueY, valueZ);
1013 0 : }
1014 :
1015 0 : void CDeviceCommandContext::SetUniform(
1016 : const int32_t bindingSlot,
1017 : const float valueX, const float valueY,
1018 : const float valueZ, const float valueW)
1019 : {
1020 0 : ENSURE(m_InsidePass || m_InsideComputePass);
1021 0 : m_ShaderProgram->SetUniform(bindingSlot, valueX, valueY, valueZ, valueW);
1022 0 : }
1023 :
1024 0 : void CDeviceCommandContext::SetUniform(
1025 : const int32_t bindingSlot, std::span<const float> values)
1026 : {
1027 0 : ENSURE(m_InsidePass || m_InsideComputePass);
1028 0 : m_ShaderProgram->SetUniform(bindingSlot, values);
1029 0 : }
1030 :
1031 0 : void CDeviceCommandContext::InsertTimestampQuery(const uint32_t handle, const bool isScopeBegin)
1032 : {
1033 0 : ENSURE(!m_InsideFramebufferPass);
1034 0 : m_Device->InsertTimestampQuery(m_CommandContext->GetCommandBuffer(), handle, isScopeBegin);
1035 0 : }
1036 :
1037 0 : void CDeviceCommandContext::BeginScopedLabel(const char* name)
1038 : {
1039 0 : if (!m_DebugScopedLabels)
1040 0 : return;
1041 0 : VkDebugUtilsLabelEXT label{};
1042 0 : label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
1043 0 : label.pLabelName = name;
1044 0 : vkCmdBeginDebugUtilsLabelEXT(m_CommandContext->GetCommandBuffer(), &label);
1045 : }
1046 :
1047 0 : void CDeviceCommandContext::EndScopedLabel()
1048 : {
1049 0 : if (!m_DebugScopedLabels)
1050 : return;
1051 0 : vkCmdEndDebugUtilsLabelEXT(m_CommandContext->GetCommandBuffer());
1052 : }
1053 :
1054 0 : void CDeviceCommandContext::Flush()
1055 : {
1056 0 : ENSURE(!m_InsideFramebufferPass);
1057 : // TODO: fix unsafe copying when overlaping flushes/frames.
1058 :
1059 0 : m_VertexUploadRing->ExecuteUploads(m_PrependCommandContext->GetCommandBuffer());
1060 0 : m_IndexUploadRing->ExecuteUploads(m_PrependCommandContext->GetCommandBuffer());
1061 0 : m_UniformUploadRing->ExecuteUploads(m_PrependCommandContext->GetCommandBuffer());
1062 :
1063 0 : m_IsPipelineStateDirty = true;
1064 :
1065 0 : CTexture* backbufferReadbackTexture{
1066 0 : !m_QueuedReadbacks.empty() && m_QueuedReadbackSwapChain && m_QueuedReadbackSwapChain->IsValid()
1067 0 : ? m_QueuedReadbackSwapChain->GetOrCreateBackbufferReadbackTexture()
1068 0 : : nullptr};
1069 0 : const bool needsReadback = backbufferReadbackTexture;
1070 0 : if (needsReadback)
1071 : {
1072 0 : CTexture* backbufferTexture{m_QueuedReadbackSwapChain->GetCurrentBackbufferTexture()};
1073 :
1074 0 : {
1075 : // We assume that the readback texture is in linear tiling.
1076 0 : ScopedImageLayoutTransition scopedBackbufferTransition{
1077 0 : *m_CommandContext,
1078 : {&backbufferTexture, 1},
1079 : VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1080 : VK_ACCESS_TRANSFER_READ_BIT,
1081 0 : VK_PIPELINE_STAGE_TRANSFER_BIT};
1082 0 : ScopedImageLayoutTransition scopedReadbackBackbufferTransition{
1083 0 : *m_CommandContext,
1084 : {&backbufferReadbackTexture, 1},
1085 : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1086 : VK_ACCESS_TRANSFER_WRITE_BIT,
1087 0 : VK_PIPELINE_STAGE_TRANSFER_BIT};
1088 0 : VkImageCopy region{};
1089 0 : region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1090 0 : region.srcSubresource.layerCount = 1;
1091 0 : region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1092 0 : region.dstSubresource.layerCount = 1;
1093 0 : region.extent.width = backbufferTexture->GetWidth();
1094 0 : region.extent.height = backbufferTexture->GetHeight();
1095 0 : region.extent.depth = 1;
1096 0 : vkCmdCopyImage(
1097 : m_CommandContext->GetCommandBuffer(),
1098 : backbufferTexture->GetImage(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1099 : backbufferReadbackTexture->GetImage(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1100 : 1, ®ion);
1101 0 : }
1102 :
1103 0 : Utilities::SubmitMemoryBarrier(
1104 : m_CommandContext->GetCommandBuffer(),
1105 : VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT,
1106 : VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT);
1107 :
1108 0 : m_PrependCommandContext->Flush();
1109 0 : m_CommandContext->FlushAndWait();
1110 :
1111 0 : VkImageSubresource subresource{};
1112 0 : subresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1113 0 : VkSubresourceLayout subresourceLayout{};
1114 0 : vkGetImageSubresourceLayout(
1115 0 : m_Device->GetVkDevice(), backbufferReadbackTexture->GetImage(), &subresource, &subresourceLayout);
1116 :
1117 0 : void* mappedData = backbufferReadbackTexture->GetMappedData();
1118 0 : ENSURE(mappedData);
1119 0 : const uint32_t height = backbufferReadbackTexture->GetHeight();
1120 0 : const auto [redOffset, greenOffset, blueOffset] = backbufferReadbackTexture->GetFormat() == Format::B8G8R8A8_UNORM
1121 0 : ? std::make_tuple(2, 1, 0) : std::make_tuple(0, 1, 2);
1122 0 : for (const QueuedReadback& queuedReackback : m_QueuedReadbacks)
1123 : {
1124 0 : const std::byte* data = static_cast<const std::byte*>(mappedData);
1125 : // Currently the backbuffer (0, 0) is the left-bottom corner (legacy from GL).
1126 0 : data += subresourceLayout.offset + subresourceLayout.rowPitch * (height - queuedReackback.height - queuedReackback.y);
1127 0 : for (uint32_t y = 0; y < queuedReackback.height; ++y)
1128 : {
1129 : const std::byte* row = data;
1130 0 : for (uint32_t x = 0; x < queuedReackback.width; ++x)
1131 : {
1132 0 : const uint32_t sourceIndex = (queuedReackback.x + x) * 4;
1133 0 : const uint32_t destinationIndex = ((queuedReackback.height - y - 1) * queuedReackback.width + x) * 3;
1134 0 : std::byte* destinationPixelData = static_cast<std::byte*>(queuedReackback.data) + destinationIndex;
1135 0 : destinationPixelData[0] = row[sourceIndex + redOffset];
1136 0 : destinationPixelData[1] = row[sourceIndex + greenOffset];
1137 0 : destinationPixelData[2] = row[sourceIndex + blueOffset];
1138 : }
1139 0 : data += subresourceLayout.rowPitch;
1140 : }
1141 : }
1142 : }
1143 : else
1144 : {
1145 0 : m_PrependCommandContext->Flush();
1146 0 : m_CommandContext->Flush();
1147 : }
1148 :
1149 0 : m_QueuedReadbacks.clear();
1150 0 : m_QueuedReadbackSwapChain = nullptr;
1151 0 : }
1152 :
1153 0 : void CDeviceCommandContext::PreDraw()
1154 : {
1155 0 : ENSURE(m_InsidePass);
1156 0 : ApplyPipelineStateIfDirty();
1157 0 : m_ShaderProgram->PreDraw(*m_CommandContext);
1158 0 : UpdateOutdatedConstants();
1159 0 : }
1160 :
1161 0 : void CDeviceCommandContext::UpdateOutdatedConstants()
1162 : {
1163 0 : if (m_ShaderProgram->IsMaterialConstantsDataOutdated())
1164 : {
1165 0 : const VkDeviceSize alignment =
1166 0 : std::max(static_cast<VkDeviceSize>(16), m_Device->GetChoosenPhysicalDevice().properties.limits.minUniformBufferOffsetAlignment);
1167 0 : const uint32_t offset = m_UniformUploadRing->ScheduleUpload(
1168 : m_PrependCommandContext->GetCommandBuffer(),
1169 : std::span<const std::byte>{
1170 0 : m_ShaderProgram->GetMaterialConstantsData(),
1171 0 : m_ShaderProgram->GetMaterialConstantsDataSize()}, alignment);
1172 0 : m_ShaderProgram->UpdateMaterialConstantsData();
1173 :
1174 0 : const VkDescriptorSet uniformDescriptorSet{GetUniformDescriptorSet(
1175 0 : m_UniformUploadRing->GetBuffer(), m_ShaderProgram->GetMaterialConstantsDataSize())};
1176 : // TODO: maybe move inside shader program to reduce the # of bind calls.
1177 0 : vkCmdBindDescriptorSets(
1178 0 : m_CommandContext->GetCommandBuffer(), m_ShaderProgram->GetPipelineBindPoint(),
1179 0 : m_ShaderProgram->GetPipelineLayout(), m_Device->GetDescriptorManager().GetUniformSet(),
1180 : 1, &uniformDescriptorSet, 1, &offset);
1181 : }
1182 0 : }
1183 :
1184 0 : void CDeviceCommandContext::ApplyPipelineStateIfDirty()
1185 : {
1186 0 : if (!m_IsPipelineStateDirty)
1187 : return;
1188 0 : m_IsPipelineStateDirty = false;
1189 :
1190 0 : ENSURE(m_GraphicsPipelineState || m_ComputePipelineState);
1191 0 : if (m_GraphicsPipelineState)
1192 : {
1193 0 : ENSURE(m_VertexInputLayout);
1194 0 : ENSURE(m_Framebuffer);
1195 : }
1196 :
1197 0 : VkPipeline pipeline{m_GraphicsPipelineState
1198 0 : ? m_GraphicsPipelineState->GetOrCreatePipeline(m_VertexInputLayout, m_Framebuffer)
1199 0 : : m_ComputePipelineState->GetPipeline()};
1200 0 : ENSURE(pipeline != VK_NULL_HANDLE);
1201 :
1202 0 : if (m_LastBoundPipeline != pipeline)
1203 : {
1204 0 : m_LastBoundPipeline = pipeline;
1205 0 : vkCmdBindPipeline(m_CommandContext->GetCommandBuffer(), m_ShaderProgram->GetPipelineBindPoint(), pipeline);
1206 :
1207 0 : m_ShaderProgram->Bind();
1208 :
1209 0 : if (m_Device->GetDescriptorManager().UseDescriptorIndexing())
1210 : {
1211 0 : vkCmdBindDescriptorSets(
1212 0 : m_CommandContext->GetCommandBuffer(), m_ShaderProgram->GetPipelineBindPoint(),
1213 0 : m_ShaderProgram->GetPipelineLayout(), 0,
1214 0 : 1, &m_Device->GetDescriptorManager().GetDescriptorIndexingSet(), 0, nullptr);
1215 : }
1216 : }
1217 : }
1218 :
1219 0 : void CDeviceCommandContext::BindVertexBuffer(
1220 : const uint32_t bindingSlot, CBuffer* buffer, uint32_t offset)
1221 : {
1222 0 : VkBuffer vertexBuffers[] = { buffer->GetVkBuffer() };
1223 0 : VkDeviceSize offsets[] = { offset };
1224 0 : vkCmdBindVertexBuffers(
1225 : m_CommandContext->GetCommandBuffer(), bindingSlot, std::size(vertexBuffers), vertexBuffers, offsets);
1226 0 : }
1227 :
1228 0 : void CDeviceCommandContext::BindIndexBuffer(CBuffer* buffer, uint32_t offset)
1229 : {
1230 0 : if (buffer == m_BoundIndexBuffer && offset == m_BoundIndexBufferOffset)
1231 : return;
1232 0 : m_BoundIndexBuffer = buffer;
1233 0 : m_BoundIndexBufferOffset = offset;
1234 0 : vkCmdBindIndexBuffer(
1235 : m_CommandContext->GetCommandBuffer(), buffer->GetVkBuffer(), offset, VK_INDEX_TYPE_UINT16);
1236 : }
1237 :
1238 0 : VkDescriptorSet CDeviceCommandContext::GetUniformDescriptorSet(
1239 : CBuffer* uniformBuffer, const uint32_t dataSize)
1240 : {
1241 0 : ENSURE(uniformBuffer);
1242 :
1243 0 : if (m_UniformBufferUID == INVALID_DEVICE_OBJECT_UID || m_UniformBufferUID != uniformBuffer->GetUID())
1244 : {
1245 0 : if (m_UniformDescriptorPool != VK_NULL_HANDLE)
1246 : {
1247 0 : m_Device->ScheduleObjectToDestroy(
1248 0 : VK_OBJECT_TYPE_DESCRIPTOR_POOL, m_UniformDescriptorPool, VK_NULL_HANDLE);
1249 0 : m_UniformDescriptorPool = VK_NULL_HANDLE;
1250 : }
1251 :
1252 0 : m_UniformBufferUID = uniformBuffer->GetUID();
1253 0 : m_UniformDescriptorSets.clear();
1254 :
1255 0 : constexpr uint32_t initialSize{16};
1256 0 : const uint32_t maxUniformBufferRange{m_Device->GetChoosenPhysicalDevice().properties.limits.maxUniformBufferRange};
1257 0 : const uint32_t maxSize{std::min(uniformBuffer->GetSize(), 65536u)};
1258 :
1259 0 : uint32_t maxSets{0};
1260 0 : for (uint32_t size{initialSize}; size <= maxUniformBufferRange && size <= maxSize; size *= 2)
1261 0 : ++maxSets;
1262 :
1263 0 : VkDescriptorPoolSize descriptorPoolSize{};
1264 0 : descriptorPoolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
1265 0 : descriptorPoolSize.descriptorCount = maxSets;
1266 :
1267 0 : VkDescriptorPoolCreateInfo descriptorPoolCreateInfo{};
1268 0 : descriptorPoolCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
1269 0 : descriptorPoolCreateInfo.poolSizeCount = 1;
1270 0 : descriptorPoolCreateInfo.pPoolSizes = &descriptorPoolSize;
1271 0 : descriptorPoolCreateInfo.maxSets = maxSets;
1272 0 : ENSURE_VK_SUCCESS(vkCreateDescriptorPool(
1273 : m_Device->GetVkDevice(), &descriptorPoolCreateInfo, nullptr, &m_UniformDescriptorPool));
1274 :
1275 0 : PS::StaticVector<VkDescriptorBufferInfo, 16> descriptorBufferInfos;
1276 0 : PS::StaticVector<VkWriteDescriptorSet, 16> writeDescriptorSets;
1277 0 : for (uint32_t size{initialSize}; size <= maxUniformBufferRange && size <= maxSize; size *= 2)
1278 : {
1279 0 : VkDescriptorSetAllocateInfo descriptorSetAllocateInfo{};
1280 0 : descriptorSetAllocateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
1281 0 : descriptorSetAllocateInfo.descriptorPool = m_UniformDescriptorPool;
1282 0 : descriptorSetAllocateInfo.descriptorSetCount = 1;
1283 0 : descriptorSetAllocateInfo.pSetLayouts = &m_Device->GetDescriptorManager().GetUniformDescriptorSetLayout();
1284 :
1285 0 : VkDescriptorSet descriptorSet{VK_NULL_HANDLE};
1286 0 : ENSURE_VK_SUCCESS(vkAllocateDescriptorSets(
1287 : m_Device->GetVkDevice(), &descriptorSetAllocateInfo, &descriptorSet));
1288 :
1289 0 : m_UniformDescriptorSets.emplace_back(descriptorSet, size);
1290 0 : descriptorBufferInfos.emplace_back(uniformBuffer->GetVkBuffer(), 0u, size);
1291 :
1292 0 : VkWriteDescriptorSet writeDescriptorSet{};
1293 0 : writeDescriptorSet.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
1294 0 : writeDescriptorSet.dstSet = descriptorSet;
1295 0 : writeDescriptorSet.dstBinding = 0;
1296 0 : writeDescriptorSet.dstArrayElement = 0;
1297 0 : writeDescriptorSet.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
1298 0 : writeDescriptorSet.descriptorCount = 1;
1299 0 : writeDescriptorSet.pBufferInfo = &descriptorBufferInfos.back();
1300 0 : writeDescriptorSets.emplace_back(writeDescriptorSet);
1301 : }
1302 :
1303 0 : vkUpdateDescriptorSets(
1304 0 : m_Device->GetVkDevice(), writeDescriptorSets.size(), writeDescriptorSets.data(), 0, nullptr);
1305 : }
1306 :
1307 0 : VkDescriptorSet descriptorSet{VK_NULL_HANDLE};
1308 0 : for (const UniformDescriptorSet& uniformDescriptorSet : m_UniformDescriptorSets)
1309 0 : if (uniformDescriptorSet.size >= dataSize)
1310 : {
1311 0 : descriptorSet = uniformDescriptorSet.descriptorSet;
1312 0 : break;
1313 : }
1314 0 : return descriptorSet;
1315 : }
1316 :
1317 : } // namespace Vulkan
1318 :
1319 : } // namespace Backend
1320 :
1321 : } // namespace Renderer
|