Debian Codegraph @

tools/window/GraphiteNativeVulkanWindowContext.cpp

raw
1 /*
2 * Copyright 2023 Google Inc.
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 "tools/window/GraphiteNativeVulkanWindowContext.h"
9
10 #include "include/core/SkSurface.h"
11 #include "include/gpu/MutableTextureState.h"
12 #include "include/gpu/graphite/BackendSemaphore.h"
13 #include "include/gpu/graphite/BackendTexture.h"
14 #include "include/gpu/graphite/Context.h"
15 #include "include/gpu/graphite/ContextOptions.h"
16 #include "include/gpu/graphite/GraphiteTypes.h"
17 #include "include/gpu/graphite/Recorder.h"
18 #include "include/gpu/graphite/Surface.h"
19 #include "include/gpu/graphite/TextureInfo.h"
20 #include "include/gpu/graphite/vk/VulkanGraphiteContext.h"
21 #include "include/gpu/graphite/vk/VulkanGraphiteTypes.h"
22 #include "include/gpu/vk/VulkanExtensions.h"
23 #include "include/gpu/vk/VulkanMutableTextureState.h"
24 #include "include/gpu/vk/VulkanTypes.h"
25 #include "src/base/SkAutoMalloc.h"
26 #include "src/gpu/graphite/ContextOptionsPriv.h"
27 #include "src/gpu/graphite/Log.h"
28 #include "src/gpu/graphite/TextureFormat.h"
29 #include "src/gpu/graphite/vk/VulkanGraphiteUtils.h"
30 #include "src/gpu/vk/VulkanInterface.h"
31 #include "src/gpu/vk/vulkanmemoryallocator/VulkanAMDMemoryAllocator.h"
32 #include "tools/graphite/GraphiteToolUtils.h"
33
34 #include <algorithm>
35
36 #ifdef VK_USE_PLATFORM_WIN32_KHR
37 // windows wants to define this as CreateSemaphoreA or CreateSemaphoreW
38 #undef CreateSemaphore
39 #endif
40
41 #define GET_PROC(F) f##F = (PFN_vk##F)backendContext.fGetProc("vk" #F, fInstance, VK_NULL_HANDLE)
42 #define GET_DEV_PROC(F) f##F = (PFN_vk##F)backendContext.fGetProc("vk" #F, VK_NULL_HANDLE, fDevice)
43
44 namespace skwindow::internal {
45
46 GraphiteVulkanWindowContext::GraphiteVulkanWindowContext(
47 std::unique_ptr<const DisplayParams> params,
48 CreateVkSurfaceFn createVkSurface,
49 CanPresentFn canPresent,
50 PFN_vkGetInstanceProcAddr instProc)
51 : WindowContext(std::move(params))
52 , fDeviceSurface(VK_NULL_HANDLE)
53 , fSwapchain(VK_NULL_HANDLE)
54 , fCreateVkSurfaceFn(std::move(createVkSurface))
55 , fCanPresentFn(std::move(canPresent)) {
56 fGetInstanceProcAddr = instProc;
57 this->initializeContext();
58 }
59
60 void GraphiteVulkanWindowContext::initializeContext() {
61 SkASSERT(!fGraphiteContext && !fGraphiteRecorder);
62 // Any config code here (particularly for msaa)?
63
64 PFN_vkGetInstanceProcAddr getInstanceProc = fGetInstanceProcAddr;
65 skgpu::VulkanBackendContext backendContext;
66 skgpu::VulkanExtensions extensions;
67 sk_gpu_test::TestVkFeatures features;
68 if (!sk_gpu_test::CreateVkBackendContext(getInstanceProc,
69 &backendContext,
70 &extensions,
71 &features,
72 &fDebugMessenger,
73 &fPresentQueueIndex,
74 fCanPresentFn,
75 fDisplayParams->createProtectedNativeBackend())) {
76 return;
77 }
78
79 if (!extensions.hasExtension(VK_KHR_SURFACE_EXTENSION_NAME, 25) ||
80 !extensions.hasExtension(VK_KHR_SWAPCHAIN_EXTENSION_NAME, 68)) {
81 return;
82 }
83
84 fInstance = backendContext.fInstance;
85 fPhysicalDevice = backendContext.fPhysicalDevice;
86 fDevice = backendContext.fDevice;
87 fGraphicsQueueIndex = backendContext.fGraphicsQueueIndex;
88 fGraphicsQueue = backendContext.fQueue;
89
90 PFN_vkGetPhysicalDeviceProperties localGetPhysicalDeviceProperties =
91 reinterpret_cast<PFN_vkGetPhysicalDeviceProperties>(backendContext.fGetProc(
92 "vkGetPhysicalDeviceProperties", backendContext.fInstance, VK_NULL_HANDLE));
93 if (!localGetPhysicalDeviceProperties) {
94 return;
95 }
96 VkPhysicalDeviceProperties physDeviceProperties;
97 localGetPhysicalDeviceProperties(backendContext.fPhysicalDevice, &physDeviceProperties);
98 uint32_t physDevVersion = physDeviceProperties.apiVersion;
99
100 fInterface.reset(new skgpu::VulkanInterface(backendContext.fGetProc,
101 fInstance,
102 fDevice,
103 backendContext.fMaxAPIVersion,
104 physDevVersion,
105 &extensions));
106
107 GET_PROC(DestroyInstance);
108 if (fDebugMessenger != VK_NULL_HANDLE) {
109 GET_PROC(DestroyDebugUtilsMessengerEXT);
110 }
111 GET_PROC(DestroySurfaceKHR);
112 GET_PROC(GetPhysicalDeviceSurfaceSupportKHR);
113 GET_PROC(GetPhysicalDeviceSurfaceCapabilitiesKHR);
114 GET_PROC(GetPhysicalDeviceSurfaceFormatsKHR);
115 GET_PROC(GetPhysicalDeviceSurfacePresentModesKHR);
116 GET_DEV_PROC(DeviceWaitIdle);
117 GET_DEV_PROC(QueueWaitIdle);
118 GET_DEV_PROC(DestroyDevice);
119 GET_DEV_PROC(CreateSwapchainKHR);
120 GET_DEV_PROC(DestroySwapchainKHR);
121 GET_DEV_PROC(GetSwapchainImagesKHR);
122 GET_DEV_PROC(AcquireNextImageKHR);
123 GET_DEV_PROC(QueuePresentKHR);
124 GET_DEV_PROC(GetDeviceQueue);
125
126 skgpu::graphite::ContextOptions contextOptions;
127 skgpu::graphite::ContextOptionsPriv contextOptionsPriv;
128 // Needed to make synchronous readPixels work
129 contextOptionsPriv.fStoreContextRefInRecorder = true;
130 contextOptions.fOptionsPriv = &contextOptionsPriv;
131 fGraphiteContext = skgpu::graphite::ContextFactory::MakeVulkan(backendContext, contextOptions);
132 fGraphiteRecorder = fGraphiteContext->makeRecorder(ToolUtils::CreateTestingRecorderOptions());
133
134 fDeviceSurface = fCreateVkSurfaceFn(fInstance);
135 if (VK_NULL_HANDLE == fDeviceSurface) {
136 this->destroyContext();
137 return;
138 }
139
140 VkBool32 supported;
141 VkResult res = fGetPhysicalDeviceSurfaceSupportKHR(
142 fPhysicalDevice, fPresentQueueIndex, fDeviceSurface, &supported);
143 if (VK_SUCCESS != res) {
144 this->destroyContext();
145 return;
146 }
147
148 if (!this->createSwapchain(-1, -1)) {
149 this->destroyContext();
150 return;
151 }
152
153 fGetDeviceQueue(fDevice, fPresentQueueIndex, /*queueIndex=*/0, &fPresentQueue);
154 }
155
156 bool GraphiteVulkanWindowContext::createSwapchain(int width, int height) {
157 // Check surface capabilities
158 VkSurfaceCapabilitiesKHR caps;
159 VkResult res = fGetPhysicalDeviceSurfaceCapabilitiesKHR(fPhysicalDevice, fDeviceSurface, &caps);
160 if (VK_SUCCESS != res) {
161 return false;
162 }
163
164 uint32_t surfaceFormatCount;
165 res = fGetPhysicalDeviceSurfaceFormatsKHR(
166 fPhysicalDevice, fDeviceSurface, &surfaceFormatCount, nullptr);
167 if (VK_SUCCESS != res) {
168 return false;
169 }
170
171 SkAutoMalloc surfaceFormatAlloc(surfaceFormatCount * sizeof(VkSurfaceFormatKHR));
172 VkSurfaceFormatKHR* surfaceFormats = (VkSurfaceFormatKHR*)surfaceFormatAlloc.get();
173 res = fGetPhysicalDeviceSurfaceFormatsKHR(
174 fPhysicalDevice, fDeviceSurface, &surfaceFormatCount, surfaceFormats);
175 if (VK_SUCCESS != res) {
176 return false;
177 }
178
179 uint32_t presentModeCount;
180 res = fGetPhysicalDeviceSurfacePresentModesKHR(
181 fPhysicalDevice, fDeviceSurface, &presentModeCount, nullptr);
182 if (VK_SUCCESS != res) {
183 return false;
184 }
185
186 SkAutoMalloc presentModeAlloc(presentModeCount * sizeof(VkPresentModeKHR));
187 VkPresentModeKHR* presentModes = (VkPresentModeKHR*)presentModeAlloc.get();
188 res = fGetPhysicalDeviceSurfacePresentModesKHR(
189 fPhysicalDevice, fDeviceSurface, &presentModeCount, presentModes);
190 if (VK_SUCCESS != res) {
191 return false;
192 }
193
194 VkExtent2D extent = caps.currentExtent;
195 // Use the hints for width + height
196 if (extent.width == (uint32_t)-1) {
197 extent.width = width;
198 extent.height = height;
199 }
200 // Clamp the values to protect from broken hints
201 if (extent.width < caps.minImageExtent.width) {
202 extent.width = caps.minImageExtent.width;
203 } else if (extent.width > caps.maxImageExtent.width) {
204 extent.width = caps.maxImageExtent.width;
205 }
206 if (extent.height < caps.minImageExtent.height) {
207 extent.height = caps.minImageExtent.height;
208 } else if (extent.height > caps.maxImageExtent.height) {
209 extent.height = caps.maxImageExtent.height;
210 }
211 fWidth = (int)extent.width;
212 fHeight = (int)extent.height;
213
214 uint32_t imageCount = caps.minImageCount + 2;
215 if (caps.maxImageCount > 0 && imageCount > caps.maxImageCount) {
216 // Application must settle for fewer images than desired:
217 imageCount = caps.maxImageCount;
218 }
219
220 VkImageUsageFlags usageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
221 VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
222 VK_IMAGE_USAGE_TRANSFER_DST_BIT;
223 SkASSERT((caps.supportedUsageFlags & usageFlags) == usageFlags);
224 if (caps.supportedUsageFlags & VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) {
225 usageFlags |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
226 }
227 if (caps.supportedUsageFlags & VK_IMAGE_USAGE_SAMPLED_BIT) {
228 usageFlags |= VK_IMAGE_USAGE_SAMPLED_BIT;
229 }
230 SkASSERT(caps.supportedTransforms & caps.currentTransform);
231 SkASSERT(caps.supportedCompositeAlpha &
232 (VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR | VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR));
233 VkCompositeAlphaFlagBitsKHR composite_alpha =
234 (caps.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR)
235 ? VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR
236 : VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
237
238 // Pick our surface format.
239 VkFormat surfaceFormat = VK_FORMAT_UNDEFINED;
240 VkColorSpaceKHR colorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
241 for (uint32_t i = 0; i < surfaceFormatCount; ++i) {
242 VkFormat localFormat = surfaceFormats[i].format;
243 skgpu::graphite::TextureFormat format =
244 skgpu::graphite::VkFormatToTextureFormat(localFormat);
245 // Skip unsupported and HW sRGB formats. We can technically render to the sRGB formats
246 // but it requires the SkColorSpace to have a linear gamut. Viewer needs to be able to
247 // set the dst color space for legacy color management and various other modes, so we
248 // skip those formats here for compatibility.
249 if (format != skgpu::graphite::TextureFormat::kUnsupported &&
250 format != skgpu::graphite::TextureFormat::kRGBA8_sRGB &&
251 format != skgpu::graphite::TextureFormat::kBGRA8_sRGB) {
252 surfaceFormat = localFormat;
253 colorSpace = surfaceFormats[i].colorSpace;
254 break;
255 }
256 }
257 fSampleCount = std::max(1, fDisplayParams->msaaSampleCount());
258 fStencilBits = 8;
259
260 if (VK_FORMAT_UNDEFINED == surfaceFormat) {
261 return false;
262 }
263
264 // If mailbox mode is available, use it, as it is the lowest-latency non-tearing mode. If not,
265 // fall back to FIFO which is always available.
266 VkPresentModeKHR mode = VK_PRESENT_MODE_FIFO_KHR;
267 bool hasImmediate = false;
268 for (uint32_t i = 0; i < presentModeCount; ++i) {
269 // use mailbox
270 if (VK_PRESENT_MODE_MAILBOX_KHR == presentModes[i]) {
271 mode = VK_PRESENT_MODE_MAILBOX_KHR;
272 }
273 if (VK_PRESENT_MODE_IMMEDIATE_KHR == presentModes[i]) {
274 hasImmediate = true;
275 }
276 }
277 if (fDisplayParams->disableVsync() && hasImmediate) {
278 mode = VK_PRESENT_MODE_IMMEDIATE_KHR;
279 }
280
281 VkSwapchainCreateInfoKHR swapchainCreateInfo;
282 memset(&swapchainCreateInfo, 0, sizeof(VkSwapchainCreateInfoKHR));
283 swapchainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
284 swapchainCreateInfo.flags = fDisplayParams->createProtectedNativeBackend()
285 ? VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR
286 : 0;
287 swapchainCreateInfo.surface = fDeviceSurface;
288 swapchainCreateInfo.minImageCount = imageCount;
289 swapchainCreateInfo.imageFormat = surfaceFormat;
290 swapchainCreateInfo.imageColorSpace = colorSpace;
291 swapchainCreateInfo.imageExtent = extent;
292 swapchainCreateInfo.imageArrayLayers = 1;
293 swapchainCreateInfo.imageUsage = usageFlags;
294
295 uint32_t queueFamilies[] = {fGraphicsQueueIndex, fPresentQueueIndex};
296 if (fGraphicsQueueIndex != fPresentQueueIndex) {
297 swapchainCreateInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
298 swapchainCreateInfo.queueFamilyIndexCount = 2;
299 swapchainCreateInfo.pQueueFamilyIndices = queueFamilies;
300 } else {
301 swapchainCreateInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
302 swapchainCreateInfo.queueFamilyIndexCount = 0;
303 swapchainCreateInfo.pQueueFamilyIndices = nullptr;
304 }
305
306 swapchainCreateInfo.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
307 swapchainCreateInfo.compositeAlpha = composite_alpha;
308 swapchainCreateInfo.presentMode = mode;
309 swapchainCreateInfo.clipped = true;
310 swapchainCreateInfo.oldSwapchain = fSwapchain;
311
312 res = fCreateSwapchainKHR(fDevice, &swapchainCreateInfo, nullptr, &fSwapchain);
313 if (VK_SUCCESS != res) {
314 return false;
315 }
316
317 // Destroy the old swapchain
318 if (swapchainCreateInfo.oldSwapchain != VK_NULL_HANDLE) {
319 fDeviceWaitIdle(fDevice);
320 this->resetSwapchainImages();
321 fDestroySwapchainKHR(fDevice, swapchainCreateInfo.oldSwapchain, nullptr);
322 swapchainCreateInfo.oldSwapchain = VK_NULL_HANDLE;
323 }
324 // If buffer creation fails, destroy the swapchain.
325 if (!this->populateSwapchainImages(swapchainCreateInfo.imageFormat,
326 usageFlags,
327 swapchainCreateInfo.imageSharingMode)) {
328 fDeviceWaitIdle(fDevice);
329 this->resetSwapchainImages();
330 fDestroySwapchainKHR(fDevice, swapchainCreateInfo.oldSwapchain, nullptr);
331 swapchainCreateInfo.oldSwapchain = VK_NULL_HANDLE;
332 return false;
333 }
334
335 return true;
336 }
337
338 bool GraphiteVulkanWindowContext::populateSwapchainImages(VkFormat format,
339 VkImageUsageFlags usageFlags,
340 VkSharingMode sharingMode) {
341 // Determine number of swapchain images
342 uint32_t swapchainImgCount;
343 fGetSwapchainImagesKHR(fDevice, fSwapchain, &swapchainImgCount, /*pSwapchainImages*/nullptr);
344 SkASSERT(swapchainImgCount);
345
346 // Define an array of VkImages and query the driver to populate it.
347 skia_private::AutoTArray<VkImage> vkImages((size_t)swapchainImgCount);
348 std::fill_n(vkImages.get(), swapchainImgCount, VK_NULL_HANDLE);
349 fGetSwapchainImagesKHR(fDevice, fSwapchain, &swapchainImgCount, vkImages.get());
350
351 // Populate all swapchain image representations
352 fImages = skia_private::AutoTArray<SwapchainImage>((size_t)swapchainImgCount);
353 VkResult result;
354 for (uint32_t i = 0; i < swapchainImgCount; ++i) {
355 // Make sure we were provided a valid VkImage handle
356 SkASSERT(vkImages[i] != VK_NULL_HANDLE);
357 fImages[i].fVkImage = vkImages[i];
358
359 // Create the semaphore that will be signaled once the image done being rendered
360 static const VkSemaphoreCreateInfo submitSemInfo =
361 {VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, /*pNext=*/nullptr, /*flags=*/0};
362 VULKAN_CALL_RESULT_NOCHECK(fInterface,
363 result,
364 CreateSemaphore(fDevice,
365 &submitSemInfo,
366 /*pAllocator=*/nullptr,
367 &fImages[i].fRenderCompletionSemaphore));
368
369 // Create a Surface associated with each image for presentation
370 skgpu::graphite::VulkanTextureInfo info;
371 info.fImageTiling = VK_IMAGE_TILING_OPTIMAL;
372 info.fFormat = format;
373 info.fImageUsageFlags = usageFlags;
374 info.fSharingMode = sharingMode;
375 info.fFlags =
376 fDisplayParams->createProtectedNativeBackend() ? VK_IMAGE_CREATE_PROTECTED_BIT : 0;
377 auto backendTex = skgpu::graphite::BackendTextures::MakeVulkan(this->dimensions(),
378 info,
379 VK_IMAGE_LAYOUT_UNDEFINED,
380 fPresentQueueIndex,
381 fImages[i].fVkImage,
382 skgpu::VulkanAlloc());
383 fImages[i].fSurface = SkSurfaces::WrapBackendTexture(this->graphiteRecorder(),
384 backendTex,
385 fDisplayParams->colorSpace(),
386 &fDisplayParams->surfaceProps());
387 if (!fImages[i].fSurface) {
388 SKGPU_LOG_W("Failed to create Surface for swapchain image");
389 // Clean up any previously-created semaphores before returning false to indicate failure
390 this->resetSwapchainImages();
391 return false;
392 }
393 }
394 return true;
395 }
396
397 GraphiteVulkanWindowContext::~GraphiteVulkanWindowContext() { this->destroyContext(); }
398
399 void GraphiteVulkanWindowContext::destroyContext() {
400 if (this->isValid()) {
401 if (fPresentQueue != VK_NULL_HANDLE) {
402 fQueueWaitIdle(fPresentQueue);
403 }
404 fDeviceWaitIdle(fDevice);
405
406 if (fAcquireSemaphore != VK_NULL_HANDLE) {
407 VULKAN_CALL(fInterface,
408 DestroySemaphore(fDevice, fAcquireSemaphore, /*pAllocator=*/nullptr));
409 fAcquireSemaphore = VK_NULL_HANDLE;
410 }
411
412 this->resetSwapchainImages();
413
414 if (fSwapchain != VK_NULL_HANDLE) {
415 fDestroySwapchainKHR(fDevice, fSwapchain, /*pAllocator=*/nullptr);
416 fSwapchain = VK_NULL_HANDLE;
417 }
418
419 if (fDeviceSurface != VK_NULL_HANDLE) {
420 fDestroySurfaceKHR(fInstance, fDeviceSurface, /*pAllocator=*/nullptr);
421 fDeviceSurface = VK_NULL_HANDLE;
422 }
423 }
424
425 if (fGraphiteContext) {
426 fGraphiteRecorder.reset();
427 fGraphiteContext.reset();
428 }
429 fInterface.reset();
430
431 if (fDevice != VK_NULL_HANDLE) {
432 fDestroyDevice(fDevice, /*pAllocator=*/nullptr);
433 fDevice = VK_NULL_HANDLE;
434 }
435
436 #ifdef SK_ENABLE_VK_LAYERS
437 if (fDebugMessenger != VK_NULL_HANDLE) {
438 fDestroyDebugUtilsMessengerEXT(fInstance, fDebugMessenger, /*pAllocator=*/nullptr);
439 }
440 #endif
441
442 fPhysicalDevice = VK_NULL_HANDLE;
443
444 if (fInstance != VK_NULL_HANDLE) {
445 fDestroyInstance(fInstance, /*pAllocator=*/nullptr);
446 fInstance = VK_NULL_HANDLE;
447 }
448 }
449
450 bool GraphiteVulkanWindowContext::submitToGpu() {
451 if (!fGraphiteContext) {
452 SKGPU_LOG_W("Cannot have null graphite context when submitting work to the GPU for "
453 "presentation.");
454 return false;
455 }
456 SkASSERT(fGraphiteRecorder);
457
458 std::unique_ptr<skgpu::graphite::Recording> recording = fGraphiteRecorder->snap();
459 if (!recording) {
460 SKGPU_LOG_W("Failed to snap recording for submitting work to the GPU for presentation. "
461 "Will not submit the present operation to the present queue.");
462 return false;
463 }
464
465 skgpu::graphite::InsertRecordingInfo info;
466 info.fRecording = recording.get();
467
468 // Set up surface for layout transition
469 info.fTargetSurface = fImages[fCurrentImageIndex].fSurface.get();
470 skgpu::MutableTextureState presentState = skgpu::MutableTextureStates::MakeVulkan(
471 VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, fPresentQueueIndex);
472 info.fTargetTextureState = &presentState;
473
474 // Populate InsertRecordingInfo semaphores by wrapping VkSemaphores in graphite representation.
475 // The recorder should wait upon image acquisition prior to submitting work to the GPU:
476 SkASSERT(fAcquireSemaphore != VK_NULL_HANDLE);
477 info.fNumWaitSemaphores = 1;
478 skgpu::graphite::BackendSemaphore backendAcquireSemaphore =
479 skgpu::graphite::BackendSemaphores::MakeVulkan(fAcquireSemaphore);
480 info.fWaitSemaphores = &backendAcquireSemaphore;
481 // The recorder should signal render completion for its associated image so we know when we
482 // can submit the image to the presentation queue:
483 info.fNumSignalSemaphores = 1;
484 skgpu::graphite::BackendSemaphore backendRenderSemaphore =
485 skgpu::graphite::BackendSemaphores::MakeVulkan(
486 fImages[fCurrentImageIndex].fRenderCompletionSemaphore);
487 info.fSignalSemaphores = &backendRenderSemaphore;
488
489 // Insert finishedProc to delete the wait semaphore when done. The signal semaphore used for
490 // rendering completion is handled by resetSwapchainImages().
491 struct FinishContext {
492 sk_sp<const skgpu::VulkanInterface> fInterface;
493 VkDevice fDevice;
494 VkSemaphore fWaitSemaphore;
495 };
496 auto* finishContext = new FinishContext{fInterface, fDevice, fAcquireSemaphore};
497 skgpu::graphite::GpuFinishedProc finishCallback = [](skgpu::graphite::GpuFinishedContext c,
498 skgpu::CallbackResult status) {
499 // Regardless of the status, we need to destroy the waitSemaphore
500 if (status != skgpu::CallbackResult::kSuccess) {
501 SKGPU_LOG_W("Recording insertion failed.");
502 }
503 const auto* context = reinterpret_cast<const FinishContext*>(c);
504 VULKAN_CALL(context->fInterface, DestroySemaphore(context->fDevice,
505 context->fWaitSemaphore,
506 /*pAllocator=*/nullptr));
507 };
508 info.fFinishedContext = finishContext;
509 info.fFinishedProc = finishCallback;
510
511 fGraphiteContext->insertRecording(info);
512 fGraphiteContext->submit(skgpu::graphite::SyncToCpu::kNo);
513 fAcquireSemaphore = {}; // FinishCallback will destroy this
514 return true;
515 }
516
517 void GraphiteVulkanWindowContext::resetSwapchainImages() {
518 if (fImages.empty()) {
519 return;
520 }
521
522 // Clean up the image's semaphores
523 for (size_t i = 0; i < fImages.size(); i++) {
524 if (fImages[i].fRenderCompletionSemaphore != VK_NULL_HANDLE) {
525 VULKAN_CALL(fInterface, DestroySemaphore(fDevice,
526 fImages[i].fRenderCompletionSemaphore,
527 /*pAllocator=*/nullptr));
528 }
529 }
530
531 fImages.reset();
532 }
533
534 sk_sp<SkSurface> GraphiteVulkanWindowContext::getBackbufferSurface() {
535 // Create a new, unsignaled semaphore to be signaled upon swapchain image acquisition.
536 static const VkSemaphoreCreateInfo acquireSemInfo =
537 { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, /*pNext=*/nullptr, /*flags=*/0 };
538 VkResult result;
539 VULKAN_CALL_RESULT_NOCHECK(fInterface, result, CreateSemaphore(fDevice,
540 &acquireSemInfo,
541 /*pAllocator=*/nullptr,
542 &fAcquireSemaphore));
543 SkASSERT(fAcquireSemaphore != VK_NULL_HANDLE);
544
545 // Acquire the next available presentable image's index.
546 VkResult res = fAcquireNextImageKHR(fDevice,
547 fSwapchain,
548 /*timeout=*/UINT64_MAX,
549 fAcquireSemaphore,
550 /*VkFence=*/VK_NULL_HANDLE,
551 &fCurrentImageIndex);
552 if (VK_ERROR_SURFACE_LOST_KHR == res) {
553 // TODO: Recreate fDeviceSurface using fCreateVkSurfaceFn, and then rebuild the swapchain
554 VULKAN_CALL(fInterface,
555 DestroySemaphore(fDevice, fAcquireSemaphore, /*pAllocator=*/nullptr));
556 return nullptr;
557 }
558 if (VK_ERROR_OUT_OF_DATE_KHR == res) {
559 SKGPU_LOG_W("Failed to acquire next image for swapchain. Tearing down and trying again.");
560 if (!this->createSwapchain(-1, -1)) {
561 VULKAN_CALL(fInterface,
562 DestroySemaphore(fDevice, fAcquireSemaphore, /*pAllocator=*/nullptr));
563 return nullptr;
564 }
565
566 res = fAcquireNextImageKHR(fDevice,
567 fSwapchain,
568 UINT64_MAX,
569 fAcquireSemaphore,
570 /*VkFence=*/VK_NULL_HANDLE,
571 &fCurrentImageIndex);
572 if (VK_SUCCESS != res) {
573 VULKAN_CALL(fInterface,
574 DestroySemaphore(fDevice, fAcquireSemaphore, /*pAllocator=*/nullptr));
575 return nullptr;
576 }
577 }
578
579 // Return the SkSurface associated with the current backbuffer's image.
580 SkSurface* surface = fImages[fCurrentImageIndex].fSurface.get();
581 return sk_ref_sp(surface);
582 }
583
584 void GraphiteVulkanWindowContext::onSwapBuffers() {
585 // Submit the GPU work associated with the current backbuffer. If submission fails, exit early.
586 if (!this->submitToGpu()) {
587 return;
588 }
589
590 // Submit present operation to present queue
591 auto renderCompletionSemaphore = &fImages[fCurrentImageIndex].fRenderCompletionSemaphore;
592 const VkPresentInfoKHR presentInfo = {VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, // sType
593 nullptr, // pNext
594 1, // waitSemaphoreCount
595 renderCompletionSemaphore, // pWaitSemaphores
596 1, // swapchainCount
597 &fSwapchain, // pSwapchains
598 &fCurrentImageIndex, // pImageIndices
599 nullptr}; // pResults
600 fQueuePresentKHR(fPresentQueue, &presentInfo);
601 }
602
603 } // namespace skwindow::internal