Debian Codegraph @

src/gpu/graphite/vk/VulkanCommandBuffer.cpp

raw
1 /*
2 * Copyright 2022 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "src/gpu/graphite/vk/VulkanCommandBuffer.h"
9
10 #include "include/gpu/MutableTextureState.h"
11 #include "include/gpu/graphite/BackendSemaphore.h"
12 #include "include/gpu/graphite/vk/VulkanGraphiteTypes.h"
13 #include "include/gpu/vk/VulkanMutableTextureState.h"
14 #include "include/private/base/SkTArray.h"
15 #include "src/gpu/DataUtils.h"
16 #include "src/gpu/graphite/ContextUtils.h"
17 #include "src/gpu/graphite/DescriptorData.h"
18 #include "src/gpu/graphite/Log.h"
19 #include "src/gpu/graphite/PipelineData.h"
20 #include "src/gpu/graphite/RenderPassDesc.h"
21 #include "src/gpu/graphite/Surface_Graphite.h"
22 #include "src/gpu/graphite/TextureProxy.h"
23 #include "src/gpu/graphite/UniformManager.h"
24 #include "src/gpu/graphite/vk/VulkanBuffer.h"
25 #include "src/gpu/graphite/vk/VulkanCaps.h"
26 #include "src/gpu/graphite/vk/VulkanDescriptorSet.h"
27 #include "src/gpu/graphite/vk/VulkanFramebuffer.h"
28 #include "src/gpu/graphite/vk/VulkanGraphiteUtils.h"
29 #include "src/gpu/graphite/vk/VulkanRenderPass.h"
30 #include "src/gpu/graphite/vk/VulkanSampler.h"
31 #include "src/gpu/graphite/vk/VulkanSharedContext.h"
32 #include "src/gpu/graphite/vk/VulkanTexture.h"
33 #include "src/gpu/vk/VulkanUtilsPriv.h"
34
35 using namespace skia_private;
36
37 namespace skgpu::graphite {
38
39 class VulkanDescriptorSet;
40
41 std::unique_ptr<VulkanCommandBuffer> VulkanCommandBuffer::Make(
42 const VulkanSharedContext* sharedContext,
43 VulkanResourceProvider* resourceProvider,
44 Protected isProtected) {
45 // Create VkCommandPool
46 VkCommandPoolCreateFlags cmdPoolCreateFlags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
47 if (isProtected == Protected::kYes) {
48 cmdPoolCreateFlags |= VK_COMMAND_POOL_CREATE_PROTECTED_BIT;
49 }
50
51 const VkCommandPoolCreateInfo cmdPoolInfo = {
52 VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType
53 nullptr, // pNext
54 cmdPoolCreateFlags, // CmdPoolCreateFlags
55 sharedContext->queueIndex(), // queueFamilyIndex
56 };
57 VkResult result;
58 VkCommandPool pool;
59 VULKAN_CALL_RESULT(sharedContext,
60 result,
61 CreateCommandPool(sharedContext->device(), &cmdPoolInfo, nullptr, &pool));
62 if (result != VK_SUCCESS) {
63 return nullptr;
64 }
65
66 const VkCommandBufferAllocateInfo cmdInfo = {
67 VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType
68 nullptr, // pNext
69 pool, // commandPool
70 VK_COMMAND_BUFFER_LEVEL_PRIMARY, // level
71 1 // bufferCount
72 };
73
74 VkCommandBuffer primaryCmdBuffer;
75 VULKAN_CALL_RESULT(
76 sharedContext,
77 result,
78 AllocateCommandBuffers(sharedContext->device(), &cmdInfo, &primaryCmdBuffer));
79 if (result != VK_SUCCESS) {
80 VULKAN_CALL(sharedContext->interface(),
81 DestroyCommandPool(sharedContext->device(), pool, nullptr));
82 return nullptr;
83 }
84
85 return std::unique_ptr<VulkanCommandBuffer>(new VulkanCommandBuffer(pool,
86 primaryCmdBuffer,
87 sharedContext,
88 resourceProvider,
89 isProtected));
90 }
91
92 VulkanCommandBuffer::VulkanCommandBuffer(VkCommandPool pool,
93 VkCommandBuffer primaryCommandBuffer,
94 const VulkanSharedContext* sharedContext,
95 VulkanResourceProvider* resourceProvider,
96 Protected isProtected)
97 : CommandBuffer(isProtected)
98 , fPool(pool)
99 , fPrimaryCommandBuffer(primaryCommandBuffer)
100 , fSharedContext(sharedContext)
101 , fResourceProvider(resourceProvider) {
102 // When making a new command buffer, we automatically begin the command buffer
103 this->begin();
104 }
105
106 VulkanCommandBuffer::~VulkanCommandBuffer() {
107 if (fActive) {
108 // Need to end command buffer before deleting it
109 VULKAN_CALL(fSharedContext->interface(), EndCommandBuffer(fPrimaryCommandBuffer));
110 fActive = false;
111 }
112
113 if (VK_NULL_HANDLE != fSubmitFence) {
114 VULKAN_CALL(fSharedContext->interface(),
115 DestroyFence(fSharedContext->device(), fSubmitFence, nullptr));
116 }
117 // This should delete any command buffers as well.
118 VULKAN_CALL(fSharedContext->interface(),
119 DestroyCommandPool(fSharedContext->device(), fPool, nullptr));
120 }
121
122 void VulkanCommandBuffer::onResetCommandBuffer() {
123 SkASSERT(!fActive);
124 VULKAN_CALL_ERRCHECK(fSharedContext, ResetCommandPool(fSharedContext->device(), fPool, 0));
125 fActiveGraphicsPipeline = nullptr;
126 fBindUniformBuffers = true;
127 fBoundIndirectBuffer = VK_NULL_HANDLE;
128 fBoundIndirectBufferOffset = 0;
129 fTargetTexture = nullptr;
130 fTextureSamplerDescSetToBind = VK_NULL_HANDLE;
131 fNumTextureSamplers = 0;
132 fUniformBuffersToBind.fill({});
133 for (int i = 0; i < 4; ++i) {
134 fCachedBlendConstant[i] = -1.0;
135 }
136 }
137
138 bool VulkanCommandBuffer::setNewCommandBufferResources() {
139 this->begin();
140 return true;
141 }
142
143 void VulkanCommandBuffer::begin() {
144 SkASSERT(!fActive);
145 VkCommandBufferBeginInfo cmdBufferBeginInfo = {};
146 cmdBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
147 cmdBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
148
149 VULKAN_CALL_ERRCHECK(fSharedContext,
150 BeginCommandBuffer(fPrimaryCommandBuffer, &cmdBufferBeginInfo));
151 fActive = true;
152
153 // Set all the dynamic state that Graphite never changes once at the beginning of the command
154 // buffer. The following state are constants in Graphite:
155 //
156 // * lineWidth
157 // * depthBiasEnable, depthBiasConstantFactor, depthBiasClamp, depthBiasSlopeFactor
158 // * min/maxDepthBounds, depthBoundsTestEnable
159 // * primitiveRestartEnable
160 // * cullMode
161 // * frontFace
162 // * rasterizerDiscardEnable
163
164 if (fSharedContext->caps()->useBasicDynamicState()) {
165 VULKAN_CALL(fSharedContext->interface(),
166 CmdSetLineWidth(fPrimaryCommandBuffer,
167 /*lineWidth=*/1.0));
168 VULKAN_CALL(fSharedContext->interface(),
169 CmdSetDepthBias(fPrimaryCommandBuffer,
170 /*depthBiasConstantFactor=*/0.0f,
171 /*depthBiasClamp=*/0.0f,
172 /*depthBiasSlopeFactor=*/0.0f));
173 VULKAN_CALL(fSharedContext->interface(),
174 CmdSetDepthBounds(fPrimaryCommandBuffer,
175 /*minDepthBounds=*/0.0f,
176 /*maxDepthBounds=*/1.0f));
177 VULKAN_CALL(fSharedContext->interface(),
178 CmdSetDepthBoundsTestEnable(fPrimaryCommandBuffer,
179 /*depthBoundsTestEnable=*/VK_FALSE));
180 VULKAN_CALL(fSharedContext->interface(),
181 CmdSetDepthBiasEnable(fPrimaryCommandBuffer,
182 /*depthBiasEnable=*/VK_FALSE));
183 VULKAN_CALL(fSharedContext->interface(),
184 CmdSetPrimitiveRestartEnable(fPrimaryCommandBuffer,
185 /*primitiveRestartEnable=*/VK_FALSE));
186 VULKAN_CALL(fSharedContext->interface(),
187 CmdSetCullMode(fPrimaryCommandBuffer,
188 /*cullMode=*/VK_CULL_MODE_NONE));
189 VULKAN_CALL(fSharedContext->interface(),
190 CmdSetFrontFace(fPrimaryCommandBuffer,
191 /*frontFace=*/VK_FRONT_FACE_COUNTER_CLOCKWISE));
192 VULKAN_CALL(fSharedContext->interface(),
193 CmdSetRasterizerDiscardEnable(fPrimaryCommandBuffer,
194 /*rasterizerDiscardEnable=*/VK_FALSE));
195 }
196 }
197
198 void VulkanCommandBuffer::end() {
199 SkASSERT(fActive);
200 SkASSERT(!fActiveRenderPass);
201
202 this->submitPipelineBarriers();
203
204 VULKAN_CALL_ERRCHECK(fSharedContext, EndCommandBuffer(fPrimaryCommandBuffer));
205
206 fActive = false;
207 }
208
209 void VulkanCommandBuffer::addWaitSemaphores(size_t numWaitSemaphores,
210 const BackendSemaphore* waitSemaphores) {
211 if (!waitSemaphores) {
212 SkASSERT(numWaitSemaphores == 0);
213 return;
214 }
215
216 for (size_t i = 0; i < numWaitSemaphores; ++i) {
217 auto& semaphore = waitSemaphores[i];
218 if (semaphore.isValid() && semaphore.backend() == BackendApi::kVulkan) {
219 fWaitSemaphores.push_back(BackendSemaphores::GetVkSemaphore(semaphore));
220 }
221 }
222 }
223
224 void VulkanCommandBuffer::addSignalSemaphores(size_t numSignalSemaphores,
225 const BackendSemaphore* signalSemaphores) {
226 if (!signalSemaphores) {
227 SkASSERT(numSignalSemaphores == 0);
228 return;
229 }
230
231 for (size_t i = 0; i < numSignalSemaphores; ++i) {
232 auto& semaphore = signalSemaphores[i];
233 if (semaphore.isValid() && semaphore.backend() == BackendApi::kVulkan) {
234 fSignalSemaphores.push_back(BackendSemaphores::GetVkSemaphore(semaphore));
235 }
236 }
237 }
238
239 void VulkanCommandBuffer::prepareSurfaceForStateUpdate(SkSurface* targetSurface,
240 const MutableTextureState* newState) {
241 TextureProxy* textureProxy = static_cast<Surface*>(targetSurface)->backingTextureProxy();
242 VulkanTexture* texture = static_cast<VulkanTexture*>(textureProxy->texture());
243
244 // Even though internally we use this helper for getting src access flags and stages they
245 // can also be used for general dst flags since we don't know exactly what the client
246 // plans on using the image for.
247 VkImageLayout newLayout = skgpu::MutableTextureStates::GetVkImageLayout(newState);
248 if (newLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
249 newLayout = texture->currentLayout();
250 }
251 VkPipelineStageFlags dstStage = VulkanTexture::LayoutToPipelineSrcStageFlags(newLayout);
252 VkAccessFlags dstAccess = VulkanTexture::LayoutToSrcAccessMask(newLayout);
253
254 uint32_t currentQueueFamilyIndex = texture->currentQueueFamilyIndex();
255 uint32_t newQueueFamilyIndex = skgpu::MutableTextureStates::GetVkQueueFamilyIndex(newState);
256 auto isSpecialQueue = [](uint32_t queueFamilyIndex) {
257 return queueFamilyIndex == VK_QUEUE_FAMILY_EXTERNAL ||
258 queueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT;
259 };
260 if (isSpecialQueue(currentQueueFamilyIndex) && isSpecialQueue(newQueueFamilyIndex)) {
261 // It is illegal to have both the new and old queue be special queue families (i.e. external
262 // or foreign).
263 return;
264 }
265
266 this->trackCommandBufferResource(sk_ref_sp(texture));
267
268 texture->setImageLayoutAndQueueIndex(this,
269 newLayout,
270 dstAccess,
271 dstStage,
272 newQueueFamilyIndex);
273 }
274
275 // Requests a sampler. Dynamic samplers live in the global cache, requiring no tracking, but
276 // immutable samplers are created on the current graphics pipeline, and may outlive it, requiring
277 // further tracking.
278 const Sampler* VulkanCommandBuffer::getSampler(
279 const DrawPassCommands::BindTexturesAndSamplers* command, int32_t index) {
280 auto desc = command->fSamplers[index];
281 if (desc.isImmutable()) {
282 const VulkanSampler* immutableSampler = fActiveGraphicsPipeline->immutableSampler(index);
283 if (immutableSampler) {
284 this->trackCommandBufferResource(sk_ref_sp<Sampler>(immutableSampler));
285 }
286 return immutableSampler;
287 } else {
288 return fSharedContext->globalCache()->getDynamicSampler(desc);
289 }
290 }
291
292 static VkResult submit_to_queue(const VulkanSharedContext* sharedContext,
293 VkQueue queue,
294 VkFence fence,
295 uint32_t waitCount,
296 const VkSemaphore* waitSemaphores,
297 const VkPipelineStageFlags* waitStages,
298 uint32_t commandBufferCount,
299 const VkCommandBuffer* commandBuffers,
300 uint32_t signalCount,
301 const VkSemaphore* signalSemaphores,
302 Protected protectedContext,
303 MarkFrameBoundary markFrameBoundary,
304 uint64_t frameID) {
305 VkSubmitInfo submitInfo = {};
306 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
307
308 VkProtectedSubmitInfo protectedSubmitInfo = {};
309 if (protectedContext == Protected::kYes) {
310 protectedSubmitInfo.sType = VK_STRUCTURE_TYPE_PROTECTED_SUBMIT_INFO;
311 protectedSubmitInfo.protectedSubmit = VK_TRUE;
312
313 AddToPNextChain(&submitInfo, &protectedSubmitInfo);
314 }
315
316
317 VkFrameBoundaryEXT frameBoundary;
318 if (markFrameBoundary == MarkFrameBoundary::kYes &&
319 sharedContext->vulkanCaps().supportsFrameBoundary()) {
320 memset(&frameBoundary, 0, sizeof(VkFrameBoundaryEXT));
321 frameBoundary.sType = VK_STRUCTURE_TYPE_FRAME_BOUNDARY_EXT;
322 frameBoundary.flags = VK_FRAME_BOUNDARY_FRAME_END_BIT_EXT;
323 frameBoundary.frameID = frameID;
324
325 AddToPNextChain(&submitInfo, &frameBoundary);
326 }
327
328 submitInfo.waitSemaphoreCount = waitCount;
329 submitInfo.pWaitSemaphores = waitSemaphores;
330 submitInfo.pWaitDstStageMask = waitStages;
331 submitInfo.commandBufferCount = commandBufferCount;
332 submitInfo.pCommandBuffers = commandBuffers;
333 submitInfo.signalSemaphoreCount = signalCount;
334 submitInfo.pSignalSemaphores = signalSemaphores;
335
336 VkResult result;
337 VULKAN_CALL_RESULT(sharedContext, result, QueueSubmit(queue, 1, &submitInfo, fence));
338 return result;
339 }
340
341 bool VulkanCommandBuffer::submit(VkQueue queue, const SubmitInfo& submitInfo) {
342 this->end();
343
344 auto device = fSharedContext->device();
345 VkResult err;
346
347 if (fSubmitFence == VK_NULL_HANDLE) {
348 VkFenceCreateInfo fenceInfo = {};
349 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
350 VULKAN_CALL_RESULT(
351 fSharedContext, err, CreateFence(device, &fenceInfo, nullptr, &fSubmitFence));
352 if (err) {
353 fSubmitFence = VK_NULL_HANDLE;
354 return false;
355 }
356 } else {
357 // This cannot return DEVICE_LOST so we assert we succeeded.
358 VULKAN_CALL_RESULT(fSharedContext, err, ResetFences(device, 1, &fSubmitFence));
359 SkASSERT(err == VK_SUCCESS);
360 }
361
362 SkASSERT(fSubmitFence != VK_NULL_HANDLE);
363 int waitCount = fWaitSemaphores.size();
364 TArray<VkPipelineStageFlags> vkWaitStages(waitCount);
365 for (int i = 0; i < waitCount; ++i) {
366 vkWaitStages.push_back(VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
367 VK_PIPELINE_STAGE_TRANSFER_BIT);
368 }
369
370 VkResult submitResult = submit_to_queue(fSharedContext,
371 queue,
372 fSubmitFence,
373 waitCount,
374 fWaitSemaphores.data(),
375 vkWaitStages.data(),
376 /*commandBufferCount*/ 1,
377 &fPrimaryCommandBuffer,
378 fSignalSemaphores.size(),
379 fSignalSemaphores.data(),
380 this->isProtected(),
381 submitInfo.fMarkBoundary,
382 submitInfo.fFrameID);
383 fWaitSemaphores.clear();
384 fSignalSemaphores.clear();
385 if (submitResult != VK_SUCCESS) {
386 // If we failed to submit because of a device lost, we still need to wait for the fence to
387 // signal before deleting. However, there is an ARM bug (b/359822580) where the driver early
388 // outs on the fence wait if in a device lost state and thus we can't wait on it. Instead,
389 // we just wait on the queue to finish. We're already in a state that's going to cause us to
390 // restart the whole device, so waiting on the queue shouldn't have any performance impact.
391 if (submitResult == VK_ERROR_DEVICE_LOST) {
392 VULKAN_CALL(fSharedContext->interface(), QueueWaitIdle(queue));
393 } else {
394 SkASSERT(submitResult == VK_ERROR_OUT_OF_HOST_MEMORY ||
395 submitResult == VK_ERROR_OUT_OF_DEVICE_MEMORY);
396 }
397
398 VULKAN_CALL(fSharedContext->interface(), DestroyFence(device, fSubmitFence, nullptr));
399 fSubmitFence = VK_NULL_HANDLE;
400 return false;
401 }
402 return true;
403 }
404
405 bool VulkanCommandBuffer::isFinished() {
406 SkASSERT(!fActive);
407 if (VK_NULL_HANDLE == fSubmitFence) {
408 return true;
409 }
410
411 VkResult err;
412 VULKAN_CALL_RESULT_NOCHECK(fSharedContext->interface(), err,
413 GetFenceStatus(fSharedContext->device(), fSubmitFence));
414 switch (err) {
415 case VK_SUCCESS:
416 case VK_ERROR_DEVICE_LOST:
417 return true;
418
419 case VK_NOT_READY:
420 return false;
421
422 default:
423 SKGPU_LOG_F("Error calling vkGetFenceStatus. Error: %d", err);
424 SK_ABORT("Got an invalid fence status");
425 return false;
426 }
427 }
428
429 void VulkanCommandBuffer::waitUntilFinished() {
430 if (fSubmitFence == VK_NULL_HANDLE) {
431 return;
432 }
433 VULKAN_CALL_ERRCHECK(fSharedContext,
434 WaitForFences(fSharedContext->device(),
435 1,
436 &fSubmitFence,
437 /*waitAll=*/true,
438 /*timeout=*/UINT64_MAX));
439 }
440
441 void VulkanCommandBuffer::pushConstants(const PushConstantInfo& pushConstantInfo,
442 VkPipelineLayout compatibleLayout) {
443 // size must be within limits. Vulkan spec dictates each device supports at least 128 bytes
444 SkASSERT(pushConstantInfo.fSize < 128);
445 // offset and size must be a multiple of 4
446 SkASSERT(!SkToBool(pushConstantInfo.fOffset & 0x3));
447 SkASSERT(!SkToBool(pushConstantInfo.fSize & 0x3));
448
449 VULKAN_CALL(fSharedContext->interface(),
450 CmdPushConstants(fPrimaryCommandBuffer,
451 compatibleLayout,
452 pushConstantInfo.fShaderStageFlagBits,
453 pushConstantInfo.fOffset,
454 pushConstantInfo.fSize,
455 pushConstantInfo.fValues));
456 }
457
458 bool VulkanCommandBuffer::onAddRenderPass(const RenderPassDesc& rpDesc,
459 SkIRect renderPassBounds,
460 const Texture* colorTexture,
461 const Texture* resolveTexture,
462 const Texture* depthStencilTexture,
463 SkIPoint resolveOffset,
464 SkIRect viewport,
465 const DrawPassList& drawPasses) {
466 SkASSERT(resolveOffset.isZero());
467 for (const auto& drawPass : drawPasses) {
468 // Our current implementation of setting texture image layouts does not allow layout changes
469 // once we have already begun a render pass, so prior to any other commands, set the layout
470 // of all sampled textures from the drawpass so they can be sampled from the shader.
471 for (const sk_sp<TextureProxy>& textureProxy : drawPass->sampledTextures()) {
472 VulkanTexture* vulkanTexture = const_cast<VulkanTexture*>(
473 static_cast<const VulkanTexture*>(
474 textureProxy->texture()));
475 vulkanTexture->setImageLayout(this,
476 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
477 VK_ACCESS_SHADER_READ_BIT,
478 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
479 }
480 }
481 if (fDstCopy.first) {
482 VulkanTexture* vulkanTexture =
483 const_cast<VulkanTexture*>(static_cast<const VulkanTexture*>(fDstCopy.first));
484 vulkanTexture->setImageLayout(this,
485 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
486 VK_ACCESS_SHADER_READ_BIT,
487 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
488 }
489 this->setViewport(viewport);
490
491 if (!this->beginRenderPass(
492 rpDesc, renderPassBounds, colorTexture, resolveTexture, depthStencilTexture)) {
493 return false;
494 }
495
496 // After loading msaa from resolve (if needed), perform any updates that only need to occur
497 // once per renderpass.
498 this->performOncePerRPUpdates(
499 viewport, rpDesc.fDstReadStrategy == DstReadStrategy::kReadFromInput);
500
501 for (const auto& drawPass : drawPasses) {
502 if (!this->addDrawPass(drawPass.get())) SK_UNLIKELY {
503 this->endRenderPass();
504 return false;
505 }
506 }
507
508 this->endRenderPass();
509 return true;
510 }
511
512 void VulkanCommandBuffer::performOncePerRPUpdates(SkIRect viewport, bool bindDstAsInputAttachment) {
513 // Updating push constant values and - if any draw within the RP reads from the dst as an
514 // input attachment - binding the dst texture as an input attachment only need to occur once per
515 // RP. This is because intrinsic constant vlues (dst copy bounds and rtAdjust) and the render
516 // target do not change throughout the course of a RenderPass. Even if no pipeline is bound yet,
517 // we can use a compatible mock pipeline layout to perform these operations.
518
519 // TODO(b/374997389): Somehow convey & enforce Layout::kStd430 for push constants.
520 UniformManager intrinsicValues{Layout::kStd140};
521 CollectIntrinsicUniforms(fSharedContext->caps(), viewport, fDstReadBounds, &intrinsicValues);
522 SkSpan<const char> bytes = intrinsicValues.finish();
523 SkASSERT(bytes.size_bytes() == VulkanResourceProvider::kIntrinsicConstantSize);
524
525 PushConstantInfo pushConstantInfo;
526 pushConstantInfo.fOffset = 0;
527 pushConstantInfo.fSize = VulkanResourceProvider::kIntrinsicConstantSize;
528 pushConstantInfo.fShaderStageFlagBits = VulkanResourceProvider::kIntrinsicConstantStageFlags;
529 pushConstantInfo.fValues = bytes.data();
530 this->pushConstants(pushConstantInfo, fResourceProvider->mockPipelineLayout());
531
532 if (bindDstAsInputAttachment) {
533 this->updateAndBindInputAttachment(*fTargetTexture,
534 VulkanGraphicsPipeline::kDstAsInputDescSetIndex,
535 fResourceProvider->mockPipelineLayout());
536 }
537 }
538
539 bool VulkanCommandBuffer::updateAndBindInputAttachment(const VulkanTexture& texture,
540 const int setIdx,
541 VkPipelineLayout piplineLayout) {
542 // Fetch a descriptor set that contains one input attachment (we do not support using more than
543 // one per set at this time).
544 STArray<1, DescriptorData> inputDesc = {VulkanGraphicsPipeline::kInputAttachmentDescriptor};
545 sk_sp<VulkanDescriptorSet> set = fResourceProvider->findOrCreateDescriptorSet(
546 {&inputDesc.front(), (size_t)inputDesc.size()});
547 if (!set) {
548 return false;
549 }
550
551 // Update and write to the descriptor given the provided texture, binding it afterwards.
552 VkDescriptorImageInfo textureInfo = {};
553 textureInfo.sampler = VK_NULL_HANDLE;
554 textureInfo.imageView =
555 texture.getImageView(VulkanImageView::Usage::kAttachment)->imageView();
556 // Even though the image is in the VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, the subpass
557 // is configured to implicitly use VK_IMAGE_LAYOUT_GENERAL in VkAttachmentReference::layout as
558 // part of VkSubpassDescription.
559 textureInfo.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
560
561 VkWriteDescriptorSet writeInfo = {};
562 writeInfo.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
563 writeInfo.dstSet = *set->descriptorSet();
564 writeInfo.dstBinding = 0;
565 writeInfo.dstArrayElement = 0;
566 writeInfo.descriptorCount = 1;
567 writeInfo.descriptorType = DsTypeEnumToVkDs(DescriptorType::kInputAttachment);
568 writeInfo.pImageInfo = &textureInfo;
569
570 VULKAN_CALL(fSharedContext->interface(),
571 UpdateDescriptorSets(fSharedContext->device(),
572 /*descriptorWriteCount=*/1,
573 &writeInfo,
574 /*descriptorCopyCount=*/0,
575 /*pDescriptorCopies=*/nullptr));
576
577 VULKAN_CALL(fSharedContext->interface(),
578 CmdBindDescriptorSets(fPrimaryCommandBuffer,
579 VK_PIPELINE_BIND_POINT_GRAPHICS,
580 piplineLayout,
581 setIdx,
582 /*setCount=*/1,
583 set->descriptorSet(),
584 /*dynamicOffsetCount=*/0,
585 /*dynamicOffsets=*/nullptr));
586
587 this->trackCommandBufferResource(std::move(set));
588 return true;
589 }
590
591 bool VulkanCommandBuffer::loadMSAAFromResolve(const RenderPassDesc& rpDesc,
592 VulkanTexture& resolveTexture,
593 SkISize dstDimensions,
594 const SkIRect nativeDrawBounds) {
595 sk_sp<VulkanGraphicsPipeline> loadPipeline =
596 fResourceProvider->findOrCreateLoadMSAAPipeline(rpDesc);
597 if (!loadPipeline) {
598 SKGPU_LOG_E("Unable to create pipeline to load resolve texture into MSAA attachment");
599 return false;
600 }
601
602 // Update and bind uniform descriptor set
603 int w = nativeDrawBounds.width();
604 int h = nativeDrawBounds.height();
605
606 // dst rect edges in NDC (-1 to 1)
607 int dw = dstDimensions.width();
608 int dh = dstDimensions.height();
609 float dx0 = 2.f * nativeDrawBounds.fLeft / dw - 1.f;
610 float dx1 = 2.f * (nativeDrawBounds.fLeft + w) / dw - 1.f;
611 float dy0 = 2.f * nativeDrawBounds.fTop / dh - 1.f;
612 float dy1 = 2.f * (nativeDrawBounds.fTop + h) / dh - 1.f;
613 float uniData[] = {dx1 - dx0, dy1 - dy0, dx0, dy0}; // posXform
614 SkASSERT(sizeof(uniData) == VulkanResourceProvider::kLoadMSAAPushConstantSize);
615
616 this->bindGraphicsPipeline(loadPipeline.get());
617
618 PushConstantInfo loadMsaaPushConstantInfo;
619 loadMsaaPushConstantInfo.fOffset = 0;
620 loadMsaaPushConstantInfo.fSize = VulkanResourceProvider::kLoadMSAAPushConstantSize;
621 loadMsaaPushConstantInfo.fShaderStageFlagBits =
622 VulkanResourceProvider::kLoadMSAAPushConstantStageFlags;
623 loadMsaaPushConstantInfo.fValues = uniData;
624 this->pushConstants(loadMsaaPushConstantInfo, loadPipeline->layout());
625
626 // Make sure we do not attempt to bind uniform or texture/sampler descriptors because we do
627 // not use them for loading MSAA from resolve.
628 fBindUniformBuffers = false;
629 fBindTextureSamplers = false;
630
631 this->setScissor(SkIRect::MakeXYWH(0, 0, dstDimensions.width(), dstDimensions.height()));
632
633 if (!this->updateAndBindInputAttachment(
634 resolveTexture,
635 VulkanGraphicsPipeline::kLoadMsaaFromResolveInputDescSetIndex,
636 fActiveGraphicsPipeline->layout())) {
637 SKGPU_LOG_E("Unable to update and bind an input attachment descriptor for loading MSAA "
638 "from resolve");
639 return false;
640 }
641
642 this->draw(PrimitiveType::kTriangleStrip, /*baseVertex=*/0, /*vertexCount=*/4);
643
644 // After loading the resolve attachment, proceed to the next subpass.
645 this->nextSubpass();
646 // While transitioning to the next subpass, the layout of the resolve texture gets changed
647 // internally to accommodate its usage within the following subpass. Thus, we need to update
648 // our tracking of the layout to match the new/final layout. We do not need to use a general
649 // layout because we do not expect to later treat the resolve texture as a dst to read from.
650 resolveTexture.updateImageLayout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
651
652 // After using a distinct descriptor set layout for loading MSAA from resolve, we will need to
653 // (re-)bind any descriptor sets.
654 fBindUniformBuffers = true;
655 fBindTextureSamplers = true;
656 return true;
657 }
658
659 namespace {
660 // Helpers for determining + updating texture layouts.
661 void assign_color_texture_layout(VulkanCommandBuffer* cmdBuf,
662 VulkanTexture* colorTexture,
663 bool rpReadsDstAsInput) {
664 VkAccessFlags access =
665 VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
666 VkPipelineStageFlags stageFlags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
667 VkImageLayout layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
668
669 // If any draws within a render pass read from the dst color texture as an input attachment,
670 // we must add additional pipeline stage + access flags.
671 if (rpReadsDstAsInput) {
672 stageFlags |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
673 access |= VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
674 }
675
676 colorTexture->setImageLayout(cmdBuf, layout, access, stageFlags);
677 }
678
679 void assign_resolve_texture_layout(VulkanCommandBuffer* cmdBuf,
680 VulkanTexture* resolveTexture,
681 bool loadMSAAFromResolve) {
682 VkPipelineStageFlags stageFlags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
683 VkAccessFlags access = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT;
684 // The resolve image uses the color attachment layout. If loadMSAAFromResolve is true, the
685 // additional subpass will set the appropriate layout in VkAttachmentReference::layout, and
686 // layout transitions are performed automatically between subpasses.
687 VkImageLayout layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
688
689 // If loading MSAA from resolve, then the resolve texture is used in the first subpass
690 // as an input attachment and is referenced within the fragment shader. Add to the access and
691 // pipeline stage flags accordingly.
692 if (loadMSAAFromResolve) {
693 access |= VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
694 stageFlags |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
695 } else {
696 // Otherwise, add write access.
697 access |= VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
698 }
699
700 resolveTexture->setImageLayout(cmdBuf, layout, access, stageFlags);
701 }
702
703 void setup_texture_layouts(VulkanCommandBuffer* cmdBuf,
704 VulkanTexture* colorTexture,
705 VulkanTexture* resolveTexture,
706 VulkanTexture* depthStencilTexture,
707 bool loadMSAAFromResolve,
708 bool rpReadsDstAsInput) {
709 if (colorTexture) {
710 assign_color_texture_layout(cmdBuf, colorTexture, rpReadsDstAsInput);
711 if (resolveTexture) {
712 // rpReadsDstAsInput does not matter here given that we do not anticipate reading
713 // from the resolve texture as a dst input attachment.
714 assign_resolve_texture_layout(cmdBuf, resolveTexture, loadMSAAFromResolve);
715 }
716 }
717
718 if (depthStencilTexture) {
719 depthStencilTexture->setImageLayout(cmdBuf,
720 VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
721 VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
722 VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
723 VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT);
724 }
725 }
726
727 static constexpr int kMaxNumAttachments = 3;
728 void gather_clear_values(const RenderPassDesc& rpDesc,
729 STArray<kMaxNumAttachments, VkClearValue>* clearValues) {
730 // NOTE: This must stay in sync with the attachment order defined in VulkanRenderPass.cpp, in
731 // populate_attachment_refs().
732 if (rpDesc.fColorAttachment.fFormat != TextureFormat::kUnsupported) {
733 VkClearValue& colorAttachmentClear = clearValues->push_back();
734 colorAttachmentClear.color = {{rpDesc.fClearColor[0],
735 rpDesc.fClearColor[1],
736 rpDesc.fClearColor[2],
737 rpDesc.fClearColor[3]}};
738 }
739 // The resolve attachment (if defined) should never be cleared, but add a value to keep the
740 // attachment indices in sync.
741 if (rpDesc.fColorResolveAttachment.fFormat != TextureFormat::kUnsupported) {
742 SkASSERT(rpDesc.fColorResolveAttachment.fLoadOp != LoadOp::kClear);
743 clearValues->push_back({});
744 }
745
746 // Vulkan takes the clear depth and clear stencil regardless of whether or not the DS attachment
747 // only has a single aspect or both.
748 if (rpDesc.fDepthStencilAttachment.fFormat != TextureFormat::kUnsupported) {
749 VkClearValue& depthStencilAttachmentClear = clearValues->push_back();
750 depthStencilAttachmentClear.depthStencil = {rpDesc.fClearDepth, rpDesc.fClearStencil};
751 }
752 }
753
754 // The RenderArea bounds we pass into BeginRenderPass must have a start x value that is a multiple
755 // of the granularity. The width must also be a multiple of the granularity or equal to the width
756 // of the entire attachment. Similar requirements apply to the y and height components.
757 VkRect2D get_render_area(const SkIRect& srcBounds,
758 const VkExtent2D& granularity,
759 int maxWidth,
760 int maxHeight) {
761 SkIRect dstBounds;
762 // Adjust Width
763 if (granularity.width == 0 || granularity.width == 1) {
764 dstBounds.fLeft = srcBounds.fLeft;
765 dstBounds.fRight = srcBounds.fRight;
766 } else {
767 // Start with the right side of rect so we know if we end up going past the maxWidth.
768 int rightAdj = srcBounds.fRight % granularity.width;
769 if (rightAdj != 0) {
770 rightAdj = granularity.width - rightAdj;
771 }
772 dstBounds.fRight = srcBounds.fRight + rightAdj;
773 if (dstBounds.fRight > maxWidth) {
774 dstBounds.fRight = maxWidth;
775 dstBounds.fLeft = 0;
776 } else {
777 dstBounds.fLeft = srcBounds.fLeft - srcBounds.fLeft % granularity.width;
778 }
779 }
780
781 if (granularity.height == 0 || granularity.height == 1) {
782 dstBounds.fTop = srcBounds.fTop;
783 dstBounds.fBottom = srcBounds.fBottom;
784 } else {
785 // Start with the bottom side of rect so we know if we end up going past the maxHeight.
786 int bottomAdj = srcBounds.fBottom % granularity.height;
787 if (bottomAdj != 0) {
788 bottomAdj = granularity.height - bottomAdj;
789 }
790 dstBounds.fBottom = srcBounds.fBottom + bottomAdj;
791 if (dstBounds.fBottom > maxHeight) {
792 dstBounds.fBottom = maxHeight;
793 dstBounds.fTop = 0;
794 } else {
795 dstBounds.fTop = srcBounds.fTop - srcBounds.fTop % granularity.height;
796 }
797 }
798
799 VkRect2D renderArea;
800 renderArea.offset = { dstBounds.fLeft , dstBounds.fTop };
801 renderArea.extent = { (uint32_t)dstBounds.width(), (uint32_t)dstBounds.height() };
802 return renderArea;
803 }
804
805 void populate_write_info(VulkanDescriptorSet* set,
806 TArray<VkDescriptorImageInfo>& descriptorImageInfos,
807 TArray<VkWriteDescriptorSet>& writeDescriptorSets,
808 const VulkanTexture* texture,
809 const VulkanSampler* sampler,
810 int32_t binding) {
811 SkASSERT(set);
812 VkDescriptorImageInfo& textureInfo = descriptorImageInfos.push_back();
813 textureInfo = {};
814 textureInfo.sampler = sampler ? sampler->vkSampler() : VK_NULL_HANDLE;
815 textureInfo.imageView =
816 texture->getImageView(VulkanImageView::Usage::kShaderInput)->imageView();
817 textureInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
818
819 VkWriteDescriptorSet& writeInfo = writeDescriptorSets.push_back();
820 writeInfo = {};
821 writeInfo.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
822 writeInfo.dstSet = *set->descriptorSet();
823 writeInfo.dstBinding = binding;
824 writeInfo.dstArrayElement = 0;
825 writeInfo.descriptorCount = 1;
826 writeInfo.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
827 writeInfo.pImageInfo = &textureInfo;
828 }
829 } // anonymous namespace
830
831 bool VulkanCommandBuffer::beginRenderPass(const RenderPassDesc& rpDesc,
832 SkIRect renderPassBounds,
833 const Texture* colorTexture,
834 const Texture* resolveTexture,
835 const Texture* depthStencilTexture) {
836 // Validate attachment descs and textures
837 SkDEBUGCODE(const auto& colorInfo = rpDesc.fColorAttachment;)
838 SkDEBUGCODE(const auto& resolveInfo = rpDesc.fColorResolveAttachment;)
839 SkDEBUGCODE(const auto& depthStencilInfo = rpDesc.fDepthStencilAttachment;)
840 SkASSERT(colorTexture ? colorInfo.isCompatible(colorTexture->textureInfo())
841 : colorInfo.fFormat == TextureFormat::kUnsupported);
842 SkASSERT(resolveTexture ? resolveInfo.isCompatible(resolveTexture->textureInfo())
843 : resolveInfo.fFormat == TextureFormat::kUnsupported);
844 SkASSERT(depthStencilTexture ? depthStencilInfo.isCompatible(depthStencilTexture->textureInfo())
845 : depthStencilInfo.fFormat == TextureFormat::kUnsupported);
846
847 fTargetTexture =
848 const_cast<VulkanTexture*>(static_cast<const VulkanTexture*>(colorTexture));
849 VulkanTexture* vulkanResolveTexture =
850 const_cast<VulkanTexture*>(static_cast<const VulkanTexture*>(resolveTexture));
851 VulkanTexture* vulkanDepthStencilTexture =
852 const_cast<VulkanTexture*>(static_cast<const VulkanTexture*>(depthStencilTexture));
853
854 // Determine if we need to load MSAA from resolve, and if so, make certain that key conditions
855 // are met before proceeding.
856 const bool loadMSAAFromResolve = RenderPassDescWillLoadMSAAFromResolve(rpDesc);
857 if (loadMSAAFromResolve && (!vulkanResolveTexture || !fTargetTexture ||
858 !vulkanResolveTexture->supportsInputAttachmentUsage())) {
859 SKGPU_LOG_E("Cannot begin render pass. In order to load MSAA from resolve, the color "
860 "attachment must have input attachment usage and both the color and resolve "
861 "attachments must be valid.");
862 return false;
863 }
864
865 // Before beginning a renderpass, set all textures to the appropriate image layout. Whether a RP
866 // must support reading from the dst as an input attachment affects some layout selections.
867 setup_texture_layouts(
868 this,
869 fTargetTexture,
870 vulkanResolveTexture,
871 vulkanDepthStencilTexture,
872 loadMSAAFromResolve,
873 /*rpReadsDstAsInput=*/rpDesc.fDstReadStrategy == DstReadStrategy::kReadFromInput);
874
875 // Gather clear values needed for RenderPassBeginInfo. Indexed by attachment number.
876 STArray<kMaxNumAttachments, VkClearValue> clearValues;
877 gather_clear_values(rpDesc, &clearValues);
878
879 sk_sp<VulkanRenderPass> vulkanRenderPass =
880 fResourceProvider->findOrCreateRenderPass(rpDesc, /*compatibleOnly=*/false);
881 if (!vulkanRenderPass) {
882 SKGPU_LOG_W("Could not create Vulkan RenderPass");
883 return false;
884 }
885 this->submitPipelineBarriers();
886 this->trackCommandBufferResource(vulkanRenderPass);
887
888 int frameBufferWidth = 0;
889 int frameBufferHeight = 0;
890 if (colorTexture) {
891 frameBufferWidth = colorTexture->dimensions().width();
892 frameBufferHeight = colorTexture->dimensions().height();
893 } else if (depthStencilTexture) {
894 frameBufferWidth = depthStencilTexture->dimensions().width();
895 frameBufferHeight = depthStencilTexture->dimensions().height();
896 }
897 sk_sp<VulkanFramebuffer> framebuffer =
898 fResourceProvider->findOrCreateFramebuffer(fSharedContext,
899 fTargetTexture,
900 vulkanResolveTexture,
901 vulkanDepthStencilTexture,
902 rpDesc,
903 *vulkanRenderPass,
904 frameBufferWidth,
905 frameBufferHeight);
906 if (!framebuffer) {
907 SKGPU_LOG_W("Could not find or create Vulkan Framebuffer");
908 return false;
909 }
910
911 bool useFullBounds = loadMSAAFromResolve &&
912 fSharedContext->vulkanCaps().mustLoadFullImageForMSAA();
913
914 VkRect2D renderArea = get_render_area(useFullBounds ? SkIRect::MakeWH(frameBufferWidth,
915 frameBufferHeight)
916 : renderPassBounds,
917 vulkanRenderPass->granularity(),
918 frameBufferWidth,
919 frameBufferHeight);
920
921 VkRenderPassBeginInfo beginInfo = {};
922 beginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
923 beginInfo.renderPass = vulkanRenderPass->renderPass();
924 beginInfo.framebuffer = framebuffer->framebuffer();
925 beginInfo.renderArea = renderArea;
926 beginInfo.clearValueCount = clearValues.size();
927 beginInfo.pClearValues = clearValues.begin();
928
929 // Submit pipeline barriers to ensure any image layout transitions are recorded prior to
930 // beginning the render pass.
931 this->submitPipelineBarriers();
932 // TODO: If we add support for secondary command buffers, dynamically determine subpass contents
933 VULKAN_CALL(fSharedContext->interface(),
934 CmdBeginRenderPass(fPrimaryCommandBuffer,
935 &beginInfo,
936 VK_SUBPASS_CONTENTS_INLINE));
937 fActiveRenderPass = true;
938
939 SkIRect nativeBounds = SkIRect::MakeXYWH(renderArea.offset.x,
940 renderArea.offset.y,
941 renderArea.extent.width,
942 renderArea.extent.height);
943
944 if (loadMSAAFromResolve && !this->loadMSAAFromResolve(rpDesc,
945 *vulkanResolveTexture,
946 fTargetTexture->dimensions(),
947 nativeBounds)) {
948 SKGPU_LOG_E("Failed to load MSAA from resolve");
949 this->endRenderPass();
950 return false;
951 }
952
953 // Once we have an active render pass, the command buffer should hold on to a frame buffer ref.
954 this->trackCommandBufferResource(std::move(framebuffer));
955 return true;
956 }
957
958 void VulkanCommandBuffer::endRenderPass() {
959 SkASSERT(fActive);
960 VULKAN_CALL(fSharedContext->interface(), CmdEndRenderPass(fPrimaryCommandBuffer));
961 fActiveRenderPass = false;
962 fTargetTexture = nullptr;
963 }
964
965 bool VulkanCommandBuffer::addDrawPass(DrawPass* drawPass) {
966 // If there is gradient data to bind, it must be done prior to draws.
967 if (drawPass->floatStorageManager()->hasData()) {
968 this->recordBufferBindingInfo(drawPass->floatStorageManager()->getBufferInfo(),
969 UniformSlot::kGradient);
970 }
971
972 if (!drawPass->addResourceRefs(fResourceProvider, this)) SK_UNLIKELY {
973 return false;
974 }
975
976 for (auto [type, cmdPtr] : drawPass->commands()) {
977 switch (type) {
978 case DrawPassCommands::Type::kBindGraphicsPipeline: {
979 auto bgp = static_cast<DrawPassCommands::BindGraphicsPipeline*>(cmdPtr);
980 this->bindGraphicsPipeline(drawPass->getPipeline(bgp->fPipelineIndex));
981 break;
982 }
983 case DrawPassCommands::Type::kSetBlendConstants: {
984 auto sbc = static_cast<DrawPassCommands::SetBlendConstants*>(cmdPtr);
985 this->setBlendConstants(sbc->fBlendConstants);
986 break;
987 }
988 case DrawPassCommands::Type::kBindUniformBuffer: {
989 auto bub = static_cast<DrawPassCommands::BindUniformBuffer*>(cmdPtr);
990 this->recordBufferBindingInfo(bub->fInfo, bub->fSlot);
991 break;
992 }
993 case DrawPassCommands::Type::kBindStaticDataBuffer: {
994 auto bdb = static_cast<DrawPassCommands::BindStaticDataBuffer*>(cmdPtr);
995 this->bindInputBuffer(bdb->fStaticData.fBuffer, bdb->fStaticData.fOffset,
996 VulkanGraphicsPipeline::kStaticDataBufferIndex);
997 break;
998 }
999 case DrawPassCommands::Type::kBindAppendDataBuffer: {
1000 auto bdb = static_cast<DrawPassCommands::BindAppendDataBuffer*>(cmdPtr);
1001 this->bindInputBuffer(bdb->fAppendData.fBuffer, bdb->fAppendData.fOffset,
1002 VulkanGraphicsPipeline::kAppendDataBufferIndex);
1003 break;
1004 }
1005 case DrawPassCommands::Type::kBindIndexBuffer: {
1006 auto bdb = static_cast<DrawPassCommands::BindIndexBuffer*>(cmdPtr);
1007 this->bindIndexBuffer(
1008 bdb->fIndices.fBuffer, bdb->fIndices.fOffset);
1009 break;
1010 }
1011 case DrawPassCommands::Type::kBindIndirectBuffer: {
1012 auto bdb = static_cast<DrawPassCommands::BindIndirectBuffer*>(cmdPtr);
1013 this->bindIndirectBuffer(
1014 bdb->fIndirect.fBuffer, bdb->fIndirect.fOffset);
1015 break;
1016 }
1017 case DrawPassCommands::Type::kBindTexturesAndSamplers: {
1018 auto bts = static_cast<DrawPassCommands::BindTexturesAndSamplers*>(cmdPtr);
1019 this->recordTextureAndSamplerDescSet(drawPass, bts);
1020 break;
1021 }
1022 case DrawPassCommands::Type::kSetScissor: {
1023 auto ss = static_cast<DrawPassCommands::SetScissor*>(cmdPtr);
1024 this->setScissor(ss->fScissor);
1025 break;
1026 }
1027 case DrawPassCommands::Type::kDraw: {
1028 auto draw = static_cast<DrawPassCommands::Draw*>(cmdPtr);
1029 this->draw(draw->fType, draw->fBaseVertex, draw->fVertexCount);
1030 break;
1031 }
1032 case DrawPassCommands::Type::kDrawIndexed: {
1033 auto draw = static_cast<DrawPassCommands::DrawIndexed*>(cmdPtr);
1034 this->drawIndexed(
1035 draw->fType, draw->fBaseIndex, draw->fIndexCount, draw->fBaseVertex);
1036 break;
1037 }
1038 case DrawPassCommands::Type::kDrawInstanced: {
1039 auto draw = static_cast<DrawPassCommands::DrawInstanced*>(cmdPtr);
1040 this->drawInstanced(draw->fType,
1041 draw->fBaseVertex,
1042 draw->fVertexCount,
1043 draw->fBaseInstance,
1044 draw->fInstanceCount);
1045 break;
1046 }
1047 case DrawPassCommands::Type::kDrawIndexedInstanced: {
1048 auto draw = static_cast<DrawPassCommands::DrawIndexedInstanced*>(cmdPtr);
1049 this->drawIndexedInstanced(draw->fType,
1050 draw->fBaseIndex,
1051 draw->fIndexCount,
1052 draw->fBaseVertex,
1053 draw->fBaseInstance,
1054 draw->fInstanceCount);
1055 break;
1056 }
1057 case DrawPassCommands::Type::kDrawIndirect: {
1058 auto draw = static_cast<DrawPassCommands::DrawIndirect*>(cmdPtr);
1059 this->drawIndirect(draw->fType);
1060 break;
1061 }
1062 case DrawPassCommands::Type::kDrawIndexedIndirect: {
1063 auto draw = static_cast<DrawPassCommands::DrawIndexedIndirect*>(cmdPtr);
1064 this->drawIndexedIndirect(draw->fType);
1065 break;
1066 }
1067 case DrawPassCommands::Type::kAddBarrier: {
1068 auto barrierCmd = static_cast<DrawPassCommands::AddBarrier*>(cmdPtr);
1069 this->addBarrier(barrierCmd->fType);
1070 break;
1071 }
1072 }
1073 }
1074
1075 return true;
1076 }
1077
1078 void VulkanCommandBuffer::bindGraphicsPipeline(const GraphicsPipeline* graphicsPipeline) {
1079 SkASSERT(fActiveRenderPass);
1080 // TODO(b/414645289): Once the front-end is made aware of dynamic state, it could recognize when
1081 // only dynamic state has changed. In that case, since the pipeline doesn't change, this call
1082 // can be avoided. The logic after this would then have to move to another place; for example
1083 // setting dynamic states should move to a separate VulkanCommandBuffer call.
1084 const auto* previousGraphicsPipeline = fActiveGraphicsPipeline;
1085 fActiveGraphicsPipeline = static_cast<const VulkanGraphicsPipeline*>(graphicsPipeline);
1086 VULKAN_CALL(fSharedContext->interface(), CmdBindPipeline(fPrimaryCommandBuffer,
1087 VK_PIPELINE_BIND_POINT_GRAPHICS,
1088 fActiveGraphicsPipeline->pipeline()));
1089 // TODO(b/293924877): Compare pipeline layouts. If 2 pipelines have the same pipeline layout,
1090 // then descriptor sets do not need to be re-bound. For now, simply force a re-binding of
1091 // descriptor sets with any new bindGraphicsPipeline DrawPassCommand.
1092 fBindUniformBuffers = true;
1093
1094 fActiveGraphicsPipeline->updateDynamicState(
1095 fSharedContext, fPrimaryCommandBuffer, previousGraphicsPipeline);
1096 }
1097
1098 void VulkanCommandBuffer::setBlendConstants(std::array<float, 4> blendConstants) {
1099 SkASSERT(fActive);
1100 if (fCachedBlendConstant != blendConstants) {
1101 VULKAN_CALL(fSharedContext->interface(),
1102 CmdSetBlendConstants(fPrimaryCommandBuffer, blendConstants.data()));
1103 fCachedBlendConstant = blendConstants;
1104 }
1105 }
1106
1107 void VulkanCommandBuffer::addBarrier(BarrierType type) {
1108 SkASSERT(fTargetTexture);
1109
1110 VkPipelineStageFlags dstStage;
1111 VkAccessFlags dstAccess;
1112 if (type == BarrierType::kAdvancedNoncoherentBlend) {
1113 dstStage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1114 dstAccess = VK_ACCESS_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT;
1115 } else {
1116 // If input reads are coherent, no barrier is needed
1117 if (fSharedContext->vulkanCaps().isInputAttachmentReadCoherent()) {
1118 return;
1119 }
1120
1121 SkASSERT(type == BarrierType::kReadDstFromInput);
1122 dstStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
1123 dstAccess = VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
1124 }
1125 VkImageMemoryBarrier imageMemoryBarrier = {
1126 VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
1127 /*pNext=*/nullptr,
1128 /*srcAccessMask=*/VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1129 dstAccess,
1130 /*oldLayout=*/VK_IMAGE_LAYOUT_GENERAL,
1131 /*newLayout=*/VK_IMAGE_LAYOUT_GENERAL,
1132 /*srcQueueFamilyIndex=*/VK_QUEUE_FAMILY_IGNORED,
1133 /*dstQueueFamilyIndex=*/VK_QUEUE_FAMILY_IGNORED,
1134 fTargetTexture->vkImage(),
1135 /*subresourceRange=*/{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }};
1136 this->addImageMemoryBarrier(fTargetTexture,
1137 VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
1138 dstStage,
1139 /*byRegion=*/true,
1140 &imageMemoryBarrier);
1141 }
1142
1143 void VulkanCommandBuffer::recordBufferBindingInfo(const BindBufferInfo& info, UniformSlot slot) {
1144 unsigned int bufferIndex = 0;
1145 switch (slot) {
1146 case UniformSlot::kCombinedUniforms:
1147 bufferIndex = VulkanGraphicsPipeline::kCombinedUniformIndex;
1148 break;
1149 case UniformSlot::kGradient:
1150 bufferIndex = VulkanGraphicsPipeline::kGradientBufferIndex;
1151 break;
1152 default:
1153 SkASSERT(false);
1154 }
1155
1156 fUniformBuffersToBind[bufferIndex] = info;
1157 fBindUniformBuffers = true;
1158 }
1159
1160 void VulkanCommandBuffer::syncDescriptorSets() {
1161 if (fBindUniformBuffers) {
1162 this->bindUniformBuffers();
1163 // Changes to descriptor sets in lower slot numbers disrupt later set bindings. Currently,
1164 // the descriptor set which houses uniform buffers is at a lower slot than the texture /
1165 // sampler set, so rebinding uniform buffers necessitates re-binding any texture/samplers.
1166 fBindTextureSamplers = true;
1167 }
1168 if (fBindTextureSamplers) {
1169 this->bindTextureSamplers();
1170 }
1171 }
1172
1173 void VulkanCommandBuffer::bindUniformBuffers() {
1174 fBindUniformBuffers = false;
1175
1176 // Define a container with size reserved for up to kNumUniformBuffers descriptors. Only add
1177 // DescriptorData for uniforms that actually are used and need to be bound.
1178 STArray<VulkanGraphicsPipeline::kNumUniformBuffers, DescriptorData> descriptors;
1179
1180 // Up to kNumUniformBuffers can be used and require rebinding depending upon render pass info.
1181 DescriptorType uniformBufferType =
1182 fSharedContext->caps()->storageBufferSupport() ? DescriptorType::kStorageBuffer
1183 : DescriptorType::kUniformBuffer;
1184 if (fActiveGraphicsPipeline->hasCombinedUniforms() &&
1185 fUniformBuffersToBind[VulkanGraphicsPipeline::kCombinedUniformIndex].fBuffer) {
1186 descriptors.push_back({
1187 uniformBufferType,
1188 /*count=*/1,
1189 VulkanGraphicsPipeline::kCombinedUniformIndex,
1190 PipelineStageFlags::kVertexShader | PipelineStageFlags::kFragmentShader });
1191 }
1192
1193 if (fActiveGraphicsPipeline->hasGradientBuffer() &&
1194 fUniformBuffersToBind[VulkanGraphicsPipeline::kGradientBufferIndex].fBuffer) {
1195 SkASSERT(fSharedContext->caps()->gradientBufferSupport() &&
1196 fSharedContext->caps()->storageBufferSupport());
1197 descriptors.push_back({ DescriptorType::kStorageBuffer, /*count=*/1,
1198 VulkanGraphicsPipeline::kGradientBufferIndex,
1199 PipelineStageFlags::kFragmentShader });
1200 }
1201
1202 // If no uniforms are used, we can go ahead and return since no descriptors need to be bound.
1203 if (descriptors.empty()) {
1204 return;
1205 }
1206
1207 skia_private::AutoSTMalloc<VulkanGraphicsPipeline::kNumUniformBuffers, uint32_t>
1208 dynamicOffsets(descriptors.size());
1209 for (int i = 0; i < descriptors.size(); i++) {
1210 int descriptorBindingIndex = descriptors[i].fBindingIndex;
1211 SkASSERT(static_cast<unsigned long>(descriptorBindingIndex) < fUniformBuffersToBind.size());
1212 const auto& bindInfo = fUniformBuffersToBind[descriptorBindingIndex];
1213 #ifdef SK_DEBUG
1214 if (descriptors[i].fPipelineStageFlags & PipelineStageFlags::kVertexShader) {
1215 SkASSERT(bindInfo.fBuffer->isProtected() == Protected::kNo);
1216 }
1217 #endif
1218 dynamicOffsets[i] = bindInfo.fOffset;
1219 }
1220
1221 sk_sp<VulkanDescriptorSet> descSet = fResourceProvider->findOrCreateUniformBuffersDescriptorSet(
1222 descriptors, fUniformBuffersToBind);
1223 if (!descSet) {
1224 SKGPU_LOG_E("Unable to find or create uniform descriptor set");
1225 return;
1226 }
1227
1228 VULKAN_CALL(fSharedContext->interface(),
1229 CmdBindDescriptorSets(fPrimaryCommandBuffer,
1230 VK_PIPELINE_BIND_POINT_GRAPHICS,
1231 fActiveGraphicsPipeline->layout(),
1232 VulkanGraphicsPipeline::kUniformBufferDescSetIndex,
1233 /*setCount=*/1,
1234 descSet->descriptorSet(),
1235 descriptors.size(),
1236 dynamicOffsets.get()));
1237 this->trackCommandBufferResource(std::move(descSet));
1238 }
1239
1240 void VulkanCommandBuffer::bindInputBuffer(const Buffer* inputBuffer, VkDeviceSize offset,
1241 uint32_t binding) {
1242 if (inputBuffer) {
1243 SkASSERT(inputBuffer->isProtected() == Protected::kNo);
1244 VkBuffer vkBuffer = static_cast<const VulkanBuffer*>(inputBuffer)->vkBuffer();
1245 SkASSERT(vkBuffer != VK_NULL_HANDLE);
1246 VULKAN_CALL(fSharedContext->interface(), CmdBindVertexBuffers(fPrimaryCommandBuffer,
1247 binding,
1248 /*bindingCount=*/1,
1249 &vkBuffer,
1250 &offset));
1251 }
1252 }
1253
1254 void VulkanCommandBuffer::bindIndexBuffer(const Buffer* indexBuffer, size_t offset) {
1255 if (indexBuffer) {
1256 SkASSERT(indexBuffer->isProtected() == Protected::kNo);
1257 VkBuffer vkBuffer = static_cast<const VulkanBuffer*>(indexBuffer)->vkBuffer();
1258 SkASSERT(vkBuffer != VK_NULL_HANDLE);
1259 VULKAN_CALL(fSharedContext->interface(), CmdBindIndexBuffer(fPrimaryCommandBuffer,
1260 vkBuffer,
1261 offset,
1262 VK_INDEX_TYPE_UINT16));
1263 }
1264 }
1265
1266 void VulkanCommandBuffer::bindIndirectBuffer(const Buffer* indirectBuffer, size_t offset) {
1267 // Indirect buffers are not bound via the command buffer, but specified in the draw cmd.
1268 if (indirectBuffer) {
1269 SkASSERT(indirectBuffer->isProtected() == Protected::kNo);
1270 fBoundIndirectBuffer = static_cast<const VulkanBuffer*>(indirectBuffer)->vkBuffer();
1271 fBoundIndirectBufferOffset = offset;
1272 } else {
1273 fBoundIndirectBuffer = VK_NULL_HANDLE;
1274 fBoundIndirectBufferOffset = 0;
1275 }
1276 }
1277
1278 void VulkanCommandBuffer::recordTextureAndSamplerDescSet(
1279 const DrawPass* drawPass, const DrawPassCommands::BindTexturesAndSamplers* command) {
1280 SkASSERT(SkToBool(drawPass) == SkToBool(command));
1281 SkASSERT(fActiveGraphicsPipeline);
1282 auto resetTextureAndSamplerState = [&]() {
1283 fNumTextureSamplers = 0;
1284 fTextureSamplerDescSetToBind = VK_NULL_HANDLE;
1285 fBindTextureSamplers = false;
1286 };
1287
1288 bool hasDstCopy = fActiveGraphicsPipeline->dstReadStrategy() == DstReadStrategy::kTextureCopy;
1289 int numTexSamplers = (command ? command->fNumTexSamplers : 0) + hasDstCopy;
1290 if (numTexSamplers == 0) {
1291 resetTextureAndSamplerState();
1292 return;
1293 }
1294
1295 sk_sp<VulkanDescriptorSet> set;
1296 const VulkanTexture* singleTexture = nullptr;
1297 sk_sp<Sampler> singleSampler = nullptr;
1298 if (numTexSamplers == 1) {
1299 SkASSERT(hasDstCopy || command);
1300 singleTexture = static_cast<const VulkanTexture*>(
1301 hasDstCopy ? fDstCopy.first : command->fTextures[0]->texture());
1302 singleSampler = sk_ref_sp<Sampler>(hasDstCopy ? fDstCopy.second : getSampler(command, 0));
1303 SkASSERT(singleTexture && singleSampler);
1304 set = singleTexture->getCachedSingleTextureDescriptorSet(singleSampler.get());
1305 }
1306
1307 if (!set) {
1308 TArray<DescriptorData> descriptors(numTexSamplers);
1309 if (command) {
1310 for (int i = 0; i < command->fNumTexSamplers; i++) {
1311 // Embed immutable samplers into the descriptor set directly, which are held on the
1312 // active graphics pipeline and can be indexed directly with `i`.
1313 const Sampler* immutableSampler = fActiveGraphicsPipeline->immutableSampler(i);
1314 SkASSERT(SkToBool(immutableSampler) == command->fSamplers[i].isImmutable());
1315 descriptors.push_back({DescriptorType::kCombinedTextureSampler,
1316 /*count=*/1,
1317 /*bindingIdx=*/i,
1318 PipelineStageFlags::kFragmentShader,
1319 immutableSampler});
1320 }
1321 }
1322 // If required the dst copy texture+sampler is the last one in the descriptor set
1323 if (hasDstCopy) {
1324 descriptors.push_back({DescriptorType::kCombinedTextureSampler,
1325 /*count=*/1,
1326 /*bindingIdx=*/numTexSamplers - 1,
1327 PipelineStageFlags::kFragmentShader,
1328 /*immutableSampler=*/nullptr});
1329 }
1330 SkASSERT(descriptors.size() == numTexSamplers);
1331 // Query resource provider to obtain a descriptor set for the texture/samplers
1332 set = fResourceProvider->findOrCreateDescriptorSet(
1333 {&descriptors.front(), (size_t)descriptors.size()});
1334 if (!set) {
1335 SKGPU_LOG_E("Unable to find or create descriptor set");
1336 resetTextureAndSamplerState();
1337 return;
1338 }
1339
1340 TArray<VkWriteDescriptorSet> writeDescriptorSets(numTexSamplers);
1341 TArray<VkDescriptorImageInfo> descriptorImageInfos(numTexSamplers);
1342 if (command) {
1343 for (int i = 0; i < command->fNumTexSamplers; ++i) {
1344 auto texture = static_cast<const VulkanTexture*>(command->fTextures[i]->texture());
1345 // TODO(b/294198324): Investigate the root cause for null texture or samplers on
1346 // Ubuntu QuadP400 GPU
1347 if (!texture) {
1348 SKGPU_LOG_E("Invalid texture in BindTexturesAndSamplers command.");
1349 resetTextureAndSamplerState();
1350 return;
1351 }
1352
1353 if (command->fSamplers[i].isImmutable()) {
1354 populate_write_info(set.get(), descriptorImageInfos, writeDescriptorSets,
1355 texture, /*sampler=*/nullptr, i);
1356 } else {
1357 auto sampler = static_cast<const VulkanSampler*>(
1358 fSharedContext->globalCache()->getDynamicSampler(
1359 command->fSamplers[i]));
1360 // b/294198324, see above
1361 if (!sampler) {
1362 SKGPU_LOG_E("Invalid dynamic sampler.");
1363 resetTextureAndSamplerState();
1364 return;
1365 }
1366 populate_write_info(set.get(), descriptorImageInfos, writeDescriptorSets,
1367 texture, sampler, i);
1368 }
1369 }
1370 }
1371
1372 if (fActiveGraphicsPipeline->dstReadStrategy() == DstReadStrategy::kTextureCopy) {
1373 auto texture = static_cast<const VulkanTexture*>(fDstCopy.first);
1374 auto sampler = static_cast<const VulkanSampler*>(fDstCopy.second);
1375 // b/294198324, see above
1376 if (!texture || !sampler) {
1377 SKGPU_LOG_E("Invalid texture or sampler for dst-copy path.");
1378 resetTextureAndSamplerState();
1379 return;
1380 }
1381 populate_write_info(set.get(), descriptorImageInfos, writeDescriptorSets,
1382 texture, sampler, numTexSamplers - 1);
1383 }
1384
1385 SkASSERT(writeDescriptorSets.size() == numTexSamplers);
1386 VULKAN_CALL(fSharedContext->interface(),
1387 UpdateDescriptorSets(fSharedContext->device(),
1388 writeDescriptorSets.size(),
1389 writeDescriptorSets.begin(),
1390 /*descriptorCopyCount=*/0,
1391 /*pDescriptorCopies=*/nullptr));
1392
1393 if (numTexSamplers == 1) {
1394 SkASSERT(singleTexture && singleSampler);
1395 singleTexture->addCachedSingleTextureDescriptorSet(set, singleSampler);
1396 }
1397 }
1398
1399 // Store the updated descriptor set to be actually bound later on. This avoids binding and
1400 // potentially having to re-bind in cases where earlier descriptor sets change while going
1401 // through drawpass commands.
1402 fTextureSamplerDescSetToBind = *set->descriptorSet();
1403 fBindTextureSamplers = true;
1404 fNumTextureSamplers = numTexSamplers;
1405 this->trackCommandBufferResource(std::move(set));
1406 }
1407
1408 void VulkanCommandBuffer::bindTextureSamplers() {
1409 fBindTextureSamplers = false;
1410 if (fTextureSamplerDescSetToBind != VK_NULL_HANDLE &&
1411 fActiveGraphicsPipeline->numFragTexturesAndSamplers() == fNumTextureSamplers) {
1412 VULKAN_CALL(fSharedContext->interface(),
1413 CmdBindDescriptorSets(fPrimaryCommandBuffer,
1414 VK_PIPELINE_BIND_POINT_GRAPHICS,
1415 fActiveGraphicsPipeline->layout(),
1416 VulkanGraphicsPipeline::kTextureBindDescSetIndex,
1417 /*setCount=*/1,
1418 &fTextureSamplerDescSetToBind,
1419 /*dynamicOffsetCount=*/0,
1420 /*dynamicOffsets=*/nullptr));
1421 }
1422 }
1423
1424 void VulkanCommandBuffer::setScissor(const Scissor& scissor) {
1425 this->setScissor(scissor.getRect(fReplayTranslation, fRenderPassBounds));
1426 }
1427
1428 void VulkanCommandBuffer::setScissor(const SkIRect& rect) {
1429 VkRect2D scissor = {
1430 {rect.x(), rect.y()},
1431 {static_cast<unsigned int>(rect.width()), static_cast<unsigned int>(rect.height())}};
1432 VULKAN_CALL(fSharedContext->interface(),
1433 CmdSetScissor(fPrimaryCommandBuffer,
1434 /*firstScissor=*/0,
1435 /*scissorCount=*/1,
1436 &scissor));
1437 }
1438
1439 void VulkanCommandBuffer::draw(PrimitiveType,
1440 unsigned int baseVertex,
1441 unsigned int vertexCount) {
1442 SkASSERT(fActiveRenderPass);
1443 this->syncDescriptorSets();
1444 // TODO: set primitive type via dynamic state if available
1445 VULKAN_CALL(fSharedContext->interface(),
1446 CmdDraw(fPrimaryCommandBuffer,
1447 vertexCount,
1448 /*instanceCount=*/1,
1449 baseVertex,
1450 /*firstInstance=*/0));
1451 }
1452
1453 void VulkanCommandBuffer::drawIndexed(PrimitiveType,
1454 unsigned int baseIndex,
1455 unsigned int indexCount,
1456 unsigned int baseVertex) {
1457 SkASSERT(fActiveRenderPass);
1458 this->syncDescriptorSets();
1459 // TODO: set primitive type via dynamic state if available
1460 VULKAN_CALL(fSharedContext->interface(),
1461 CmdDrawIndexed(fPrimaryCommandBuffer,
1462 indexCount,
1463 /*instanceCount=*/1,
1464 baseIndex,
1465 baseVertex,
1466 /*firstInstance=*/0));
1467 }
1468
1469 void VulkanCommandBuffer::drawInstanced(PrimitiveType,
1470 unsigned int baseVertex,
1471 unsigned int vertexCount,
1472 unsigned int baseInstance,
1473 unsigned int instanceCount) {
1474 SkASSERT(fActiveRenderPass);
1475 this->syncDescriptorSets();
1476 // TODO: set primitive type via dynamic state if available
1477 VULKAN_CALL(fSharedContext->interface(),
1478 CmdDraw(fPrimaryCommandBuffer,
1479 vertexCount,
1480 instanceCount,
1481 baseVertex,
1482 baseInstance));
1483 }
1484
1485 void VulkanCommandBuffer::drawIndexedInstanced(PrimitiveType,
1486 unsigned int baseIndex,
1487 unsigned int indexCount,
1488 unsigned int baseVertex,
1489 unsigned int baseInstance,
1490 unsigned int instanceCount) {
1491 SkASSERT(fActiveRenderPass);
1492 this->syncDescriptorSets();
1493 // TODO: set primitive type via dynamic state if available
1494 VULKAN_CALL(fSharedContext->interface(),
1495 CmdDrawIndexed(fPrimaryCommandBuffer,
1496 indexCount,
1497 instanceCount,
1498 baseIndex,
1499 baseVertex,
1500 baseInstance));
1501 }
1502
1503 void VulkanCommandBuffer::drawIndirect(PrimitiveType) {
1504 SkASSERT(fActiveRenderPass);
1505 this->syncDescriptorSets();
1506 // TODO: set primitive type via dynamic state if available
1507 // Currently we can only support doing one indirect draw operation at a time,
1508 // so stride is irrelevant.
1509 VULKAN_CALL(fSharedContext->interface(),
1510 CmdDrawIndirect(fPrimaryCommandBuffer,
1511 fBoundIndirectBuffer,
1512 fBoundIndirectBufferOffset,
1513 /*drawCount=*/1,
1514 /*stride=*/0));
1515 }
1516
1517 void VulkanCommandBuffer::drawIndexedIndirect(PrimitiveType) {
1518 SkASSERT(fActiveRenderPass);
1519 this->syncDescriptorSets();
1520 // TODO: set primitive type via dynamic state if available
1521 // Currently we can only support doing one indirect draw operation at a time,
1522 // so stride is irrelevant.
1523 VULKAN_CALL(fSharedContext->interface(),
1524 CmdDrawIndexedIndirect(fPrimaryCommandBuffer,
1525 fBoundIndirectBuffer,
1526 fBoundIndirectBufferOffset,
1527 /*drawCount=*/1,
1528 /*stride=*/0));
1529 }
1530
1531 bool VulkanCommandBuffer::onAddComputePass(DispatchGroupSpan) { return false; }
1532
1533 bool VulkanCommandBuffer::onCopyBufferToBuffer(const Buffer* srcBuffer,
1534 size_t srcOffset,
1535 const Buffer* dstBuffer,
1536 size_t dstOffset,
1537 size_t size) {
1538 auto vkSrcBuffer = static_cast<const VulkanBuffer*>(srcBuffer);
1539 auto vkDstBuffer = static_cast<const VulkanBuffer*>(dstBuffer);
1540
1541 SkASSERT(vkSrcBuffer->bufferUsageFlags() & VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
1542 SkASSERT(vkDstBuffer->bufferUsageFlags() & VK_BUFFER_USAGE_TRANSFER_DST_BIT);
1543
1544 vkSrcBuffer->setBufferAccess(this, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
1545 vkDstBuffer->setBufferAccess(
1546 this, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
1547
1548 VkBufferCopy region = {};
1549 region.srcOffset = srcOffset;
1550 region.dstOffset = dstOffset;
1551 region.size = size;
1552
1553 this->submitPipelineBarriers();
1554
1555 VULKAN_CALL(fSharedContext->interface(),
1556 CmdCopyBuffer(fPrimaryCommandBuffer,
1557 vkSrcBuffer->vkBuffer(),
1558 vkDstBuffer->vkBuffer(),
1559 /*regionCount=*/1,
1560 &region));
1561
1562 // TODO (b/394121386): We don't currently have a list of tracked buffers that are used on a
1563 // RenderPass in order to put in any needed barriers (like we do for textures). If we did have
1564 // one, then we would add the needed barriers for the buffers at the start of a render pass.
1565 // Until we have such a system, we need to do some hackyness here to put in a barrier with the
1566 // assumption that the buffer will be read after this write from the copy. The only buffer types
1567 // we allow to be used as the dst of a transfer are vertex and index buffers. So we check the
1568 // buffers usages for either of those and then set the corresponding access flag.
1569 VkAccessFlags dstAccess = 0;
1570 VkPipelineStageFlags dstStageMask = 0;
1571 VkBufferUsageFlags bufferUsageFlags = vkDstBuffer->bufferUsageFlags();
1572 if (bufferUsageFlags & VK_BUFFER_USAGE_VERTEX_BUFFER_BIT) {
1573 dstAccess = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
1574 dstStageMask = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
1575 } else if (bufferUsageFlags & VK_BUFFER_USAGE_INDEX_BUFFER_BIT) {
1576 dstAccess = VK_ACCESS_INDEX_READ_BIT;
1577 dstStageMask = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
1578 } else if (vkDstBuffer->bufferUsedForCpuRead()) {
1579 dstAccess = VK_ACCESS_HOST_READ_BIT;
1580 dstStageMask = VK_PIPELINE_STAGE_HOST_BIT;
1581 } else {
1582 SkDEBUGFAIL("Unhandled type of buffer to buffer copy\n");
1583 return false;
1584 }
1585 SkASSERT(dstAccess);
1586 vkDstBuffer->setBufferAccess(this, dstAccess, dstStageMask);
1587
1588 return true;
1589 }
1590
1591 bool VulkanCommandBuffer::onCopyTextureToBuffer(const Texture* texture,
1592 SkIRect srcRect,
1593 const Buffer* buffer,
1594 size_t bufferOffset,
1595 size_t bufferRowBytes) {
1596 const VulkanTexture* srcTexture = static_cast<const VulkanTexture*>(texture);
1597 auto dstBuffer = static_cast<const VulkanBuffer*>(buffer);
1598 SkASSERT(dstBuffer->bufferUsageFlags() & VK_BUFFER_USAGE_TRANSFER_DST_BIT);
1599
1600 size_t bytesPerBlock = VkFormatBytesPerBlock(srcTexture->vulkanTextureInfo().fFormat);
1601
1602 // Set up copy region
1603 VkBufferImageCopy region = {};
1604 region.bufferOffset = bufferOffset;
1605 // Vulkan expects bufferRowLength in texels, not bytes.
1606 region.bufferRowLength = (uint32_t)(bufferRowBytes/bytesPerBlock);
1607 region.bufferImageHeight = 0; // Tightly packed
1608 region.imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, /*mipLevel=*/0, 0, 1 };
1609 region.imageOffset = { srcRect.left(), srcRect.top(), /*z=*/0 };
1610 region.imageExtent = { (uint32_t)srcRect.width(), (uint32_t)srcRect.height(), /*depth=*/1 };
1611
1612 // Enable editing of the source texture so we can change its layout so it can be copied from.
1613 const_cast<VulkanTexture*>(srcTexture)->setImageLayout(this,
1614 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1615 VK_ACCESS_TRANSFER_READ_BIT,
1616 VK_PIPELINE_STAGE_TRANSFER_BIT);
1617 // Set current access mask for buffer
1618 const_cast<VulkanBuffer*>(dstBuffer)->setBufferAccess(this,
1619 VK_ACCESS_TRANSFER_WRITE_BIT,
1620 VK_PIPELINE_STAGE_TRANSFER_BIT);
1621
1622 this->submitPipelineBarriers();
1623
1624 VULKAN_CALL(fSharedContext->interface(),
1625 CmdCopyImageToBuffer(fPrimaryCommandBuffer,
1626 srcTexture->vkImage(),
1627 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1628 dstBuffer->vkBuffer(),
1629 /*regionCount=*/1,
1630 &region));
1631 return true;
1632 }
1633
1634 bool VulkanCommandBuffer::onCopyBufferToTexture(const Buffer* buffer,
1635 const Texture* texture,
1636 const BufferTextureCopyData* copyData,
1637 int count) {
1638 auto srcBuffer = static_cast<const VulkanBuffer*>(buffer);
1639 SkASSERT(srcBuffer->bufferUsageFlags() & VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
1640 const VulkanTexture* dstTexture = static_cast<const VulkanTexture*>(texture);
1641
1642 TextureFormat format = TextureInfoPriv::ViewFormat(dstTexture->textureInfo());
1643 size_t bytesPerBlock = TextureFormatBytesPerBlock(format);
1644 SkISize oneBlockDims = CompressedDimensions(TextureFormatCompressionType(format), {1, 1});
1645
1646 // Set up copy regions.
1647 TArray<VkBufferImageCopy> regions(count);
1648 for (int i = 0; i < count; ++i) {
1649 VkBufferImageCopy& region = regions.push_back();
1650 region = {};
1651 region.bufferOffset = copyData[i].fBufferOffset;
1652 // copyData provides row length in bytes, but Vulkan expects bufferRowLength in texels.
1653 // For compressed this is the number of logical pixels not the number of blocks.
1654 region.bufferRowLength =
1655 (uint32_t)((copyData[i].fBufferRowBytes/bytesPerBlock) * oneBlockDims.fWidth);
1656 region.bufferImageHeight = 0; // Tightly packed
1657 region.imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, copyData[i].fMipLevel, 0, 1 };
1658 region.imageOffset = { copyData[i].fRect.left(),
1659 copyData[i].fRect.top(),
1660 /*z=*/0 };
1661 region.imageExtent = { (uint32_t)copyData[i].fRect.width(),
1662 (uint32_t)copyData[i].fRect.height(),
1663 /*depth=*/1 };
1664 }
1665
1666 // Enable editing of the destination texture so we can change its layout so it can be copied to.
1667 const_cast<VulkanTexture*>(dstTexture)->setImageLayout(this,
1668 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1669 VK_ACCESS_TRANSFER_WRITE_BIT,
1670 VK_PIPELINE_STAGE_TRANSFER_BIT);
1671
1672 this->submitPipelineBarriers();
1673
1674 VULKAN_CALL(fSharedContext->interface(),
1675 CmdCopyBufferToImage(fPrimaryCommandBuffer,
1676 srcBuffer->vkBuffer(),
1677 dstTexture->vkImage(),
1678 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1679 regions.size(),
1680 regions.begin()));
1681 return true;
1682 }
1683
1684 bool VulkanCommandBuffer::onCopyTextureToTexture(const Texture* src,
1685 SkIRect srcRect,
1686 const Texture* dst,
1687 SkIPoint dstPoint,
1688 int mipLevel) {
1689 const VulkanTexture* srcTexture = static_cast<const VulkanTexture*>(src);
1690 const VulkanTexture* dstTexture = static_cast<const VulkanTexture*>(dst);
1691
1692 VkImageCopy copyRegion = {};
1693 copyRegion.srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 };
1694 copyRegion.srcOffset = { srcRect.fLeft, srcRect.fTop, 0 };
1695 copyRegion.dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, (uint32_t)mipLevel, 0, 1 };
1696 copyRegion.dstOffset = { dstPoint.fX, dstPoint.fY, 0 };
1697 copyRegion.extent = { (uint32_t)srcRect.width(), (uint32_t)srcRect.height(), 1 };
1698
1699 // Enable editing of the src texture so we can change its layout so it can be copied from.
1700 const_cast<VulkanTexture*>(srcTexture)->setImageLayout(this,
1701 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1702 VK_ACCESS_TRANSFER_READ_BIT,
1703 VK_PIPELINE_STAGE_TRANSFER_BIT);
1704 // Enable editing of the destination texture so we can change its layout so it can be copied to.
1705 const_cast<VulkanTexture*>(dstTexture)->setImageLayout(this,
1706 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1707 VK_ACCESS_TRANSFER_WRITE_BIT,
1708 VK_PIPELINE_STAGE_TRANSFER_BIT);
1709
1710 this->submitPipelineBarriers();
1711
1712 VULKAN_CALL(fSharedContext->interface(),
1713 CmdCopyImage(fPrimaryCommandBuffer,
1714 srcTexture->vkImage(),
1715 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1716 dstTexture->vkImage(),
1717 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1718 /*regionCount=*/1,
1719 &copyRegion));
1720
1721 return true;
1722 }
1723
1724 bool VulkanCommandBuffer::onSynchronizeBufferToCpu(const Buffer* buffer, bool* outDidResultInWork) {
1725 static_cast<const VulkanBuffer*>(buffer)->setBufferAccess(this,
1726 VK_ACCESS_HOST_READ_BIT,
1727 VK_PIPELINE_STAGE_HOST_BIT);
1728
1729 *outDidResultInWork = true;
1730 return true;
1731 }
1732
1733 bool VulkanCommandBuffer::onClearBuffer(const Buffer*, size_t offset, size_t size) {
1734 return false;
1735 }
1736
1737 void VulkanCommandBuffer::addBufferMemoryBarrier(const Resource* resource,
1738 VkPipelineStageFlags srcStageMask,
1739 VkPipelineStageFlags dstStageMask,
1740 VkBufferMemoryBarrier* barrier) {
1741 SkASSERT(resource);
1742 this->pipelineBarrier(resource,
1743 srcStageMask,
1744 dstStageMask,
1745 /*byRegion=*/false,
1746 kBufferMemory_BarrierType,
1747 barrier);
1748 }
1749
1750 void VulkanCommandBuffer::addBufferMemoryBarrier(VkPipelineStageFlags srcStageMask,
1751 VkPipelineStageFlags dstStageMask,
1752 VkBufferMemoryBarrier* barrier) {
1753 // We don't pass in a resource here to the command buffer. The command buffer only is using it
1754 // to hold a ref, but every place where we add a buffer memory barrier we are doing some other
1755 // command with the buffer on the command buffer. Thus those other commands will already cause
1756 // the command buffer to be holding a ref to the buffer.
1757 this->pipelineBarrier(/*resource=*/nullptr,
1758 srcStageMask,
1759 dstStageMask,
1760 /*byRegion=*/false,
1761 kBufferMemory_BarrierType,
1762 barrier);
1763 }
1764
1765 void VulkanCommandBuffer::addImageMemoryBarrier(const Resource* resource,
1766 VkPipelineStageFlags srcStageMask,
1767 VkPipelineStageFlags dstStageMask,
1768 bool byRegion,
1769 VkImageMemoryBarrier* barrier) {
1770 SkASSERT(resource);
1771 this->pipelineBarrier(resource,
1772 srcStageMask,
1773 dstStageMask,
1774 byRegion,
1775 kImageMemory_BarrierType,
1776 barrier);
1777 }
1778
1779 void VulkanCommandBuffer::pipelineBarrier(const Resource* resource,
1780 VkPipelineStageFlags srcStageMask,
1781 VkPipelineStageFlags dstStageMask,
1782 bool byRegion,
1783 PipelineBarrierType barrierType,
1784 void* barrier) {
1785 // TODO: Do we need to handle wrapped command buffers?
1786 // SkASSERT(!this->isWrapped());
1787 SkASSERT(fActive);
1788 #ifdef SK_DEBUG
1789 // For images we can have barriers inside of render passes but they require us to add more
1790 // support in subpasses which need self dependencies to have barriers inside them. Also, we can
1791 // never have buffer barriers inside of a render pass. For now we will just assert that we are
1792 // not in a render pass.
1793 bool isValidSubpassBarrier = false;
1794 if (barrierType == kImageMemory_BarrierType) {
1795 VkImageMemoryBarrier* imgBarrier = static_cast<VkImageMemoryBarrier*>(barrier);
1796 isValidSubpassBarrier = (imgBarrier->newLayout == imgBarrier->oldLayout) &&
1797 (imgBarrier->srcQueueFamilyIndex == VK_QUEUE_FAMILY_IGNORED) &&
1798 (imgBarrier->dstQueueFamilyIndex == VK_QUEUE_FAMILY_IGNORED) &&
1799 byRegion;
1800 }
1801 SkASSERT(!fActiveRenderPass || isValidSubpassBarrier);
1802 #endif
1803
1804 if (barrierType == kBufferMemory_BarrierType) {
1805 const VkBufferMemoryBarrier* barrierPtr = static_cast<VkBufferMemoryBarrier*>(barrier);
1806 fBufferBarriers.push_back(*barrierPtr);
1807 } else {
1808 SkASSERT(barrierType == kImageMemory_BarrierType);
1809 const VkImageMemoryBarrier* barrierPtr = static_cast<VkImageMemoryBarrier*>(barrier);
1810 // We need to check if we are adding a pipeline barrier that covers part of the same
1811 // subresource range as a barrier that is already in current batch. If it does, then we must
1812 // submit the first batch because the vulkan spec does not define a specific ordering for
1813 // barriers submitted in the same batch.
1814 // TODO: Look if we can gain anything by merging barriers together instead of submitting
1815 // the old ones.
1816 for (int i = 0; i < fImageBarriers.size(); ++i) {
1817 VkImageMemoryBarrier& currentBarrier = fImageBarriers[i];
1818 if (barrierPtr->image == currentBarrier.image) {
1819 const VkImageSubresourceRange newRange = barrierPtr->subresourceRange;
1820 const VkImageSubresourceRange oldRange = currentBarrier.subresourceRange;
1821 SkASSERT(newRange.aspectMask == oldRange.aspectMask);
1822 SkASSERT(newRange.baseArrayLayer == oldRange.baseArrayLayer);
1823 SkASSERT(newRange.layerCount == oldRange.layerCount);
1824 uint32_t newStart = newRange.baseMipLevel;
1825 uint32_t newEnd = newRange.baseMipLevel + newRange.levelCount - 1;
1826 uint32_t oldStart = oldRange.baseMipLevel;
1827 uint32_t oldEnd = oldRange.baseMipLevel + oldRange.levelCount - 1;
1828 if (std::max(newStart, oldStart) <= std::min(newEnd, oldEnd)) {
1829 this->submitPipelineBarriers();
1830 break;
1831 }
1832 }
1833 }
1834 fImageBarriers.push_back(*barrierPtr);
1835 }
1836 fBarriersByRegion |= byRegion;
1837 fSrcStageMask = fSrcStageMask | srcStageMask;
1838 fDstStageMask = fDstStageMask | dstStageMask;
1839
1840 if (fActiveRenderPass) {
1841 this->submitPipelineBarriers(true);
1842 }
1843 }
1844
1845 void VulkanCommandBuffer::submitPipelineBarriers(bool forSelfDependency) {
1846 SkASSERT(fActive);
1847
1848 // TODO: Do we need to handle SecondaryCommandBuffers as well?
1849
1850 // Currently we never submit a pipeline barrier without at least one buffer or image barrier.
1851 if (!fBufferBarriers.empty() || !fImageBarriers.empty()) {
1852 // For images we can have barriers inside of render passes but they require us to add more
1853 // support in subpasses which need self dependencies to have barriers inside them. Also, we
1854 // can never have buffer barriers inside of a render pass. For now we will just assert that
1855 // we are not in a render pass.
1856 SkASSERT(!fActiveRenderPass || forSelfDependency);
1857 // TODO: Do we need to handle wrapped CommandBuffers?
1858 // SkASSERT(!this->isWrapped());
1859 SkASSERT(fSrcStageMask && fDstStageMask);
1860
1861 VkDependencyFlags dependencyFlags = fBarriersByRegion ? VK_DEPENDENCY_BY_REGION_BIT : 0;
1862 VULKAN_CALL(fSharedContext->interface(),
1863 CmdPipelineBarrier(fPrimaryCommandBuffer, fSrcStageMask, fDstStageMask,
1864 dependencyFlags,
1865 /*memoryBarrierCount=*/0, /*pMemoryBarrier=*/nullptr,
1866 fBufferBarriers.size(), fBufferBarriers.begin(),
1867 fImageBarriers.size(), fImageBarriers.begin()));
1868 fBufferBarriers.clear();
1869 fImageBarriers.clear();
1870 fBarriersByRegion = false;
1871 fSrcStageMask = 0;
1872 fDstStageMask = 0;
1873 }
1874 SkASSERT(fBufferBarriers.empty());
1875 SkASSERT(fImageBarriers.empty());
1876 SkASSERT(!fBarriersByRegion);
1877 SkASSERT(!fSrcStageMask);
1878 SkASSERT(!fDstStageMask);
1879 }
1880
1881 void VulkanCommandBuffer::nextSubpass() {
1882 // TODO: Use VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS if we add secondary cmd buffers
1883 VULKAN_CALL(fSharedContext->interface(),
1884 CmdNextSubpass(fPrimaryCommandBuffer, VK_SUBPASS_CONTENTS_INLINE));
1885 }
1886
1887 void VulkanCommandBuffer::setViewport(SkIRect viewport) {
1888 VkViewport vkViewport = {
1889 (float) viewport.fLeft,
1890 (float) viewport.fTop,
1891 (float) viewport.width(),
1892 (float) viewport.height(),
1893 0.0f, // minDepth
1894 1.0f, // maxDepth
1895 };
1896 VULKAN_CALL(fSharedContext->interface(),
1897 CmdSetViewport(fPrimaryCommandBuffer,
1898 /*firstViewport=*/0,
1899 /*viewportCount=*/1,
1900 &vkViewport));
1901 }
1902
1903 } // namespace skgpu::graphite