blob: 2b9074499c2a7448d467366cf33f9b9993581310 [file] [log] [blame]
Derek Sollenberger0e3cba32016-11-09 11:58:36 -05001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "VulkanManager.h"
18
19#include "DeviceInfo.h"
Greg Danielcd558522016-11-17 13:31:40 -050020#include "Properties.h"
Derek Sollenberger0e3cba32016-11-09 11:58:36 -050021#include "RenderThread.h"
Greg Daniel45ec62b2017-01-04 14:27:00 -050022#include "renderstate/RenderState.h"
Derek Sollenberger0e3cba32016-11-09 11:58:36 -050023
24#include <GrContext.h>
25#include <GrTypes.h>
26#include <vk/GrVkTypes.h>
27
28namespace android {
29namespace uirenderer {
30namespace renderthread {
31
32#define GET_PROC(F) m ## F = (PFN_vk ## F) vkGetInstanceProcAddr(instance, "vk" #F)
33#define GET_DEV_PROC(F) m ## F = (PFN_vk ## F) vkGetDeviceProcAddr(device, "vk" #F)
34
35VulkanManager::VulkanManager(RenderThread& thread) : mRenderThread(thread) {
36}
37
38void VulkanManager::destroy() {
39 if (!hasVkContext()) return;
40
Greg Daniel45ec62b2017-01-04 14:27:00 -050041 mRenderThread.renderState().onVkContextDestroyed();
42 mRenderThread.setGrContext(nullptr);
43
Derek Sollenberger0e3cba32016-11-09 11:58:36 -050044 if (VK_NULL_HANDLE != mCommandPool) {
45 mDestroyCommandPool(mBackendContext->fDevice, mCommandPool, nullptr);
46 mCommandPool = VK_NULL_HANDLE;
47 }
Greg Daniel45ec62b2017-01-04 14:27:00 -050048 mBackendContext.reset();
Derek Sollenberger0e3cba32016-11-09 11:58:36 -050049}
50
51void VulkanManager::initialize() {
52 if (hasVkContext()) { return; }
53
54 auto canPresent = [](VkInstance, VkPhysicalDevice, uint32_t) { return true; };
55
56 mBackendContext.reset(GrVkBackendContext::Create(&mPresentQueueIndex, canPresent));
57
58 // Get all the addresses of needed vulkan functions
59 VkInstance instance = mBackendContext->fInstance;
60 VkDevice device = mBackendContext->fDevice;
61 GET_PROC(CreateAndroidSurfaceKHR);
62 GET_PROC(DestroySurfaceKHR);
63 GET_PROC(GetPhysicalDeviceSurfaceSupportKHR);
64 GET_PROC(GetPhysicalDeviceSurfaceCapabilitiesKHR);
65 GET_PROC(GetPhysicalDeviceSurfaceFormatsKHR);
66 GET_PROC(GetPhysicalDeviceSurfacePresentModesKHR);
67 GET_DEV_PROC(CreateSwapchainKHR);
68 GET_DEV_PROC(DestroySwapchainKHR);
69 GET_DEV_PROC(GetSwapchainImagesKHR);
70 GET_DEV_PROC(AcquireNextImageKHR);
71 GET_DEV_PROC(QueuePresentKHR);
72 GET_DEV_PROC(CreateCommandPool);
73 GET_DEV_PROC(DestroyCommandPool);
74 GET_DEV_PROC(AllocateCommandBuffers);
75 GET_DEV_PROC(FreeCommandBuffers);
76 GET_DEV_PROC(ResetCommandBuffer);
77 GET_DEV_PROC(BeginCommandBuffer);
78 GET_DEV_PROC(EndCommandBuffer);
79 GET_DEV_PROC(CmdPipelineBarrier);
80 GET_DEV_PROC(GetDeviceQueue);
81 GET_DEV_PROC(QueueSubmit);
82 GET_DEV_PROC(QueueWaitIdle);
83 GET_DEV_PROC(DeviceWaitIdle);
84 GET_DEV_PROC(CreateSemaphore);
85 GET_DEV_PROC(DestroySemaphore);
86 GET_DEV_PROC(CreateFence);
87 GET_DEV_PROC(DestroyFence);
88 GET_DEV_PROC(WaitForFences);
89 GET_DEV_PROC(ResetFences);
90
91 // create the command pool for the command buffers
92 if (VK_NULL_HANDLE == mCommandPool) {
93 VkCommandPoolCreateInfo commandPoolInfo;
94 memset(&commandPoolInfo, 0, sizeof(VkCommandPoolCreateInfo));
95 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
96 // this needs to be on the render queue
97 commandPoolInfo.queueFamilyIndex = mBackendContext->fGraphicsQueueIndex;
98 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
99 SkDEBUGCODE(VkResult res =) mCreateCommandPool(mBackendContext->fDevice,
100 &commandPoolInfo, nullptr, &mCommandPool);
101 SkASSERT(VK_SUCCESS == res);
102 }
103
104 mGetDeviceQueue(mBackendContext->fDevice, mPresentQueueIndex, 0, &mPresentQueue);
105
106 mRenderThread.setGrContext(GrContext::Create(kVulkan_GrBackend,
107 (GrBackendContext) mBackendContext.get()));
108 DeviceInfo::initialize(mRenderThread.getGrContext()->caps()->maxRenderTargetSize());
Greg Danielcd558522016-11-17 13:31:40 -0500109
110 if (Properties::enablePartialUpdates && Properties::useBufferAge) {
111 mSwapBehavior = SwapBehavior::BufferAge;
112 }
Greg Daniel45ec62b2017-01-04 14:27:00 -0500113
114 mRenderThread.renderState().onVkContextCreated();
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500115}
116
117// Returns the next BackbufferInfo to use for the next draw. The function will make sure all
118// previous uses have finished before returning.
119VulkanSurface::BackbufferInfo* VulkanManager::getAvailableBackbuffer(VulkanSurface* surface) {
120 SkASSERT(surface->mBackbuffers);
121
122 ++surface->mCurrentBackbufferIndex;
123 if (surface->mCurrentBackbufferIndex > surface->mImageCount) {
124 surface->mCurrentBackbufferIndex = 0;
125 }
126
127 VulkanSurface::BackbufferInfo* backbuffer = surface->mBackbuffers +
128 surface->mCurrentBackbufferIndex;
129
130 // Before we reuse a backbuffer, make sure its fences have all signaled so that we can safely
131 // reuse its commands buffers.
132 VkResult res = mWaitForFences(mBackendContext->fDevice, 2, backbuffer->mUsageFences,
133 true, UINT64_MAX);
134 if (res != VK_SUCCESS) {
135 return nullptr;
136 }
137
138 return backbuffer;
139}
140
141
142SkSurface* VulkanManager::getBackbufferSurface(VulkanSurface* surface) {
143 VulkanSurface::BackbufferInfo* backbuffer = getAvailableBackbuffer(surface);
144 SkASSERT(backbuffer);
145
146 VkResult res;
147
148 res = mResetFences(mBackendContext->fDevice, 2, backbuffer->mUsageFences);
149 SkASSERT(VK_SUCCESS == res);
150
151 // The acquire will signal the attached mAcquireSemaphore. We use this to know the image has
152 // finished presenting and that it is safe to begin sending new commands to the returned image.
153 res = mAcquireNextImageKHR(mBackendContext->fDevice, surface->mSwapchain, UINT64_MAX,
154 backbuffer->mAcquireSemaphore, VK_NULL_HANDLE, &backbuffer->mImageIndex);
155
156 if (VK_ERROR_SURFACE_LOST_KHR == res) {
157 // need to figure out how to create a new vkSurface without the platformData*
158 // maybe use attach somehow? but need a Window
159 return nullptr;
160 }
161 if (VK_ERROR_OUT_OF_DATE_KHR == res) {
162 // tear swapchain down and try again
163 if (!createSwapchain(surface)) {
164 return nullptr;
165 }
Greg Daniel45ec62b2017-01-04 14:27:00 -0500166 backbuffer = getAvailableBackbuffer(surface);
167 res = mResetFences(mBackendContext->fDevice, 2, backbuffer->mUsageFences);
168 SkASSERT(VK_SUCCESS == res);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500169
170 // acquire the image
171 res = mAcquireNextImageKHR(mBackendContext->fDevice, surface->mSwapchain, UINT64_MAX,
172 backbuffer->mAcquireSemaphore, VK_NULL_HANDLE, &backbuffer->mImageIndex);
173
174 if (VK_SUCCESS != res) {
175 return nullptr;
176 }
177 }
178
179 // set up layout transfer from initial to color attachment
Greg Danielcd558522016-11-17 13:31:40 -0500180 VkImageLayout layout = surface->mImageInfos[backbuffer->mImageIndex].mImageLayout;
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500181 SkASSERT(VK_IMAGE_LAYOUT_UNDEFINED == layout || VK_IMAGE_LAYOUT_PRESENT_SRC_KHR == layout);
182 VkPipelineStageFlags srcStageMask = (VK_IMAGE_LAYOUT_UNDEFINED == layout) ?
183 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT :
184 VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
185 VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
186 VkAccessFlags srcAccessMask = (VK_IMAGE_LAYOUT_UNDEFINED == layout) ?
187 0 : VK_ACCESS_MEMORY_READ_BIT;
188 VkAccessFlags dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
189
190 VkImageMemoryBarrier imageMemoryBarrier = {
191 VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // sType
192 NULL, // pNext
193 srcAccessMask, // outputMask
194 dstAccessMask, // inputMask
195 layout, // oldLayout
196 VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // newLayout
197 mPresentQueueIndex, // srcQueueFamilyIndex
198 mBackendContext->fGraphicsQueueIndex, // dstQueueFamilyIndex
199 surface->mImages[backbuffer->mImageIndex], // image
200 { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 } // subresourceRange
201 };
202 mResetCommandBuffer(backbuffer->mTransitionCmdBuffers[0], 0);
203
204 VkCommandBufferBeginInfo info;
205 memset(&info, 0, sizeof(VkCommandBufferBeginInfo));
206 info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
207 info.flags = 0;
208 mBeginCommandBuffer(backbuffer->mTransitionCmdBuffers[0], &info);
209
210 mCmdPipelineBarrier(backbuffer->mTransitionCmdBuffers[0], srcStageMask, dstStageMask, 0,
211 0, nullptr, 0, nullptr, 1, &imageMemoryBarrier);
212
213 mEndCommandBuffer(backbuffer->mTransitionCmdBuffers[0]);
214
215 VkPipelineStageFlags waitDstStageFlags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
216 // insert the layout transfer into the queue and wait on the acquire
217 VkSubmitInfo submitInfo;
218 memset(&submitInfo, 0, sizeof(VkSubmitInfo));
219 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
220 submitInfo.waitSemaphoreCount = 1;
221 // Wait to make sure aquire semaphore set above has signaled.
222 submitInfo.pWaitSemaphores = &backbuffer->mAcquireSemaphore;
223 submitInfo.pWaitDstStageMask = &waitDstStageFlags;
224 submitInfo.commandBufferCount = 1;
225 submitInfo.pCommandBuffers = &backbuffer->mTransitionCmdBuffers[0];
226 submitInfo.signalSemaphoreCount = 0;
227
228 // Attach first fence to submission here so we can track when the command buffer finishes.
229 mQueueSubmit(mBackendContext->fQueue, 1, &submitInfo, backbuffer->mUsageFences[0]);
230
231 // We need to notify Skia that we changed the layout of the wrapped VkImage
232 GrVkImageInfo* imageInfo;
Greg Danielcd558522016-11-17 13:31:40 -0500233 sk_sp<SkSurface> skSurface = surface->mImageInfos[backbuffer->mImageIndex].mSurface;
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500234 skSurface->getRenderTargetHandle((GrBackendObject*)&imageInfo,
235 SkSurface::kFlushRead_BackendHandleAccess);
236 imageInfo->updateImageLayout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
237
238 surface->mBackbuffer = std::move(skSurface);
239 return surface->mBackbuffer.get();
240}
241
242void VulkanManager::destroyBuffers(VulkanSurface* surface) {
243 if (surface->mBackbuffers) {
244 for (uint32_t i = 0; i < surface->mImageCount + 1; ++i) {
245 mWaitForFences(mBackendContext->fDevice, 2, surface->mBackbuffers[i].mUsageFences, true,
246 UINT64_MAX);
247 surface->mBackbuffers[i].mImageIndex = -1;
248 mDestroySemaphore(mBackendContext->fDevice, surface->mBackbuffers[i].mAcquireSemaphore,
249 nullptr);
250 mDestroySemaphore(mBackendContext->fDevice, surface->mBackbuffers[i].mRenderSemaphore,
251 nullptr);
252 mFreeCommandBuffers(mBackendContext->fDevice, mCommandPool, 2,
253 surface->mBackbuffers[i].mTransitionCmdBuffers);
254 mDestroyFence(mBackendContext->fDevice, surface->mBackbuffers[i].mUsageFences[0], 0);
255 mDestroyFence(mBackendContext->fDevice, surface->mBackbuffers[i].mUsageFences[1], 0);
256 }
257 }
258
259 delete[] surface->mBackbuffers;
260 surface->mBackbuffers = nullptr;
Greg Danielcd558522016-11-17 13:31:40 -0500261 delete[] surface->mImageInfos;
262 surface->mImageInfos = nullptr;
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500263 delete[] surface->mImages;
264 surface->mImages = nullptr;
265}
266
267void VulkanManager::destroySurface(VulkanSurface* surface) {
268 // Make sure all submit commands have finished before starting to destroy objects.
269 if (VK_NULL_HANDLE != mPresentQueue) {
270 mQueueWaitIdle(mPresentQueue);
271 }
272 mDeviceWaitIdle(mBackendContext->fDevice);
273
274 destroyBuffers(surface);
275
276 if (VK_NULL_HANDLE != surface->mSwapchain) {
277 mDestroySwapchainKHR(mBackendContext->fDevice, surface->mSwapchain, nullptr);
278 surface->mSwapchain = VK_NULL_HANDLE;
279 }
280
281 if (VK_NULL_HANDLE != surface->mVkSurface) {
282 mDestroySurfaceKHR(mBackendContext->fInstance, surface->mVkSurface, nullptr);
283 surface->mVkSurface = VK_NULL_HANDLE;
284 }
285 delete surface;
286}
287
288void VulkanManager::createBuffers(VulkanSurface* surface, VkFormat format, VkExtent2D extent) {
289 mGetSwapchainImagesKHR(mBackendContext->fDevice, surface->mSwapchain, &surface->mImageCount,
290 nullptr);
291 SkASSERT(surface->mImageCount);
292 surface->mImages = new VkImage[surface->mImageCount];
293 mGetSwapchainImagesKHR(mBackendContext->fDevice, surface->mSwapchain,
294 &surface->mImageCount, surface->mImages);
295
296 SkSurfaceProps props(0, kUnknown_SkPixelGeometry);
297
298 bool wantSRGB = VK_FORMAT_R8G8B8A8_SRGB == format;
299 GrPixelConfig config = wantSRGB ? kSRGBA_8888_GrPixelConfig : kRGBA_8888_GrPixelConfig;
300
301 // set up initial image layouts and create surfaces
Greg Danielcd558522016-11-17 13:31:40 -0500302 surface->mImageInfos = new VulkanSurface::ImageInfo[surface->mImageCount];
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500303 for (uint32_t i = 0; i < surface->mImageCount; ++i) {
304 GrBackendRenderTargetDesc desc;
305 GrVkImageInfo info;
306 info.fImage = surface->mImages[i];
307 info.fAlloc = { VK_NULL_HANDLE, 0, 0, 0 };
308 info.fImageLayout = VK_IMAGE_LAYOUT_UNDEFINED;
309 info.fImageTiling = VK_IMAGE_TILING_OPTIMAL;
310 info.fFormat = format;
311 info.fLevelCount = 1;
312
313 desc.fWidth = extent.width;
314 desc.fHeight = extent.height;
315 desc.fConfig = config;
316 desc.fOrigin = kTopLeft_GrSurfaceOrigin;
317 desc.fSampleCnt = 0;
318 desc.fStencilBits = 0;
319 desc.fRenderTargetHandle = (GrBackendObject) &info;
320
Greg Danielcd558522016-11-17 13:31:40 -0500321 VulkanSurface::ImageInfo& imageInfo = surface->mImageInfos[i];
322 imageInfo.mSurface = SkSurface::MakeFromBackendRenderTarget(mRenderThread.getGrContext(),
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500323 desc, &props);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500324 }
325
326 SkASSERT(mCommandPool != VK_NULL_HANDLE);
327
328 // set up the backbuffers
329 VkSemaphoreCreateInfo semaphoreInfo;
330 memset(&semaphoreInfo, 0, sizeof(VkSemaphoreCreateInfo));
331 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
332 semaphoreInfo.pNext = nullptr;
333 semaphoreInfo.flags = 0;
334 VkCommandBufferAllocateInfo commandBuffersInfo;
335 memset(&commandBuffersInfo, 0, sizeof(VkCommandBufferAllocateInfo));
336 commandBuffersInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
337 commandBuffersInfo.pNext = nullptr;
338 commandBuffersInfo.commandPool = mCommandPool;
339 commandBuffersInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
340 commandBuffersInfo.commandBufferCount = 2;
341 VkFenceCreateInfo fenceInfo;
342 memset(&fenceInfo, 0, sizeof(VkFenceCreateInfo));
343 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
344 fenceInfo.pNext = nullptr;
345 fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
346
347 // we create one additional backbuffer structure here, because we want to
348 // give the command buffers they contain a chance to finish before we cycle back
349 surface->mBackbuffers = new VulkanSurface::BackbufferInfo[surface->mImageCount + 1];
350 for (uint32_t i = 0; i < surface->mImageCount + 1; ++i) {
351 SkDEBUGCODE(VkResult res);
352 surface->mBackbuffers[i].mImageIndex = -1;
353 SkDEBUGCODE(res = ) mCreateSemaphore(mBackendContext->fDevice, &semaphoreInfo, nullptr,
354 &surface->mBackbuffers[i].mAcquireSemaphore);
355 SkDEBUGCODE(res = ) mCreateSemaphore(mBackendContext->fDevice, &semaphoreInfo, nullptr,
356 &surface->mBackbuffers[i].mRenderSemaphore);
357 SkDEBUGCODE(res = ) mAllocateCommandBuffers(mBackendContext->fDevice, &commandBuffersInfo,
358 surface->mBackbuffers[i].mTransitionCmdBuffers);
359 SkDEBUGCODE(res = ) mCreateFence(mBackendContext->fDevice, &fenceInfo, nullptr,
360 &surface->mBackbuffers[i].mUsageFences[0]);
361 SkDEBUGCODE(res = ) mCreateFence(mBackendContext->fDevice, &fenceInfo, nullptr,
362 &surface->mBackbuffers[i].mUsageFences[1]);
363 SkASSERT(VK_SUCCESS == res);
364 }
365 surface->mCurrentBackbufferIndex = surface->mImageCount;
366}
367
368bool VulkanManager::createSwapchain(VulkanSurface* surface) {
369 // check for capabilities
370 VkSurfaceCapabilitiesKHR caps;
371 VkResult res = mGetPhysicalDeviceSurfaceCapabilitiesKHR(mBackendContext->fPhysicalDevice,
372 surface->mVkSurface, &caps);
373 if (VK_SUCCESS != res) {
374 return false;
375 }
376
377 uint32_t surfaceFormatCount;
378 res = mGetPhysicalDeviceSurfaceFormatsKHR(mBackendContext->fPhysicalDevice, surface->mVkSurface,
379 &surfaceFormatCount, nullptr);
380 if (VK_SUCCESS != res) {
381 return false;
382 }
383
384 SkAutoMalloc surfaceFormatAlloc(surfaceFormatCount * sizeof(VkSurfaceFormatKHR));
385 VkSurfaceFormatKHR* surfaceFormats = (VkSurfaceFormatKHR*)surfaceFormatAlloc.get();
386 res = mGetPhysicalDeviceSurfaceFormatsKHR(mBackendContext->fPhysicalDevice, surface->mVkSurface,
387 &surfaceFormatCount, surfaceFormats);
388 if (VK_SUCCESS != res) {
389 return false;
390 }
391
392 uint32_t presentModeCount;
393 res = mGetPhysicalDeviceSurfacePresentModesKHR(mBackendContext->fPhysicalDevice,
394 surface->mVkSurface, &presentModeCount, nullptr);
395 if (VK_SUCCESS != res) {
396 return false;
397 }
398
399 SkAutoMalloc presentModeAlloc(presentModeCount * sizeof(VkPresentModeKHR));
400 VkPresentModeKHR* presentModes = (VkPresentModeKHR*)presentModeAlloc.get();
401 res = mGetPhysicalDeviceSurfacePresentModesKHR(mBackendContext->fPhysicalDevice,
402 surface->mVkSurface, &presentModeCount, presentModes);
403 if (VK_SUCCESS != res) {
404 return false;
405 }
406
407 VkExtent2D extent = caps.currentExtent;
408 // clamp width; to handle currentExtent of -1 and protect us from broken hints
409 if (extent.width < caps.minImageExtent.width) {
410 extent.width = caps.minImageExtent.width;
411 }
412 SkASSERT(extent.width <= caps.maxImageExtent.width);
413 // clamp height
414 if (extent.height < caps.minImageExtent.height) {
415 extent.height = caps.minImageExtent.height;
416 }
417 SkASSERT(extent.height <= caps.maxImageExtent.height);
418
419 uint32_t imageCount = caps.minImageCount + 2;
420 if (caps.maxImageCount > 0 && imageCount > caps.maxImageCount) {
421 // Application must settle for fewer images than desired:
422 imageCount = caps.maxImageCount;
423 }
424
425 // Currently Skia requires the images to be color attchments and support all transfer
426 // operations.
427 VkImageUsageFlags usageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
428 VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
429 VK_IMAGE_USAGE_TRANSFER_DST_BIT;
430 SkASSERT((caps.supportedUsageFlags & usageFlags) == usageFlags);
431 SkASSERT(caps.supportedTransforms & caps.currentTransform);
432 SkASSERT(caps.supportedCompositeAlpha & (VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR |
433 VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR));
434 VkCompositeAlphaFlagBitsKHR composite_alpha =
435 (caps.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR) ?
436 VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR :
437 VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
438
439 // Pick our surface format. For now, just make sure it matches our sRGB request:
440 VkFormat surfaceFormat = VK_FORMAT_UNDEFINED;
441 VkColorSpaceKHR colorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
442
443 bool wantSRGB = false;
444#ifdef ANDROID_ENABLE_LINEAR_BLENDING
445 wantSRGB = true;
446#endif
447 for (uint32_t i = 0; i < surfaceFormatCount; ++i) {
448 // We are assuming we can get either R8G8B8A8_UNORM or R8G8B8A8_SRGB
449 VkFormat desiredFormat = wantSRGB ? VK_FORMAT_R8G8B8A8_SRGB : VK_FORMAT_R8G8B8A8_UNORM;
450 if (desiredFormat == surfaceFormats[i].format) {
451 surfaceFormat = surfaceFormats[i].format;
452 colorSpace = surfaceFormats[i].colorSpace;
453 }
454 }
455
456 if (VK_FORMAT_UNDEFINED == surfaceFormat) {
457 return false;
458 }
459
460 // If mailbox mode is available, use it, as it is the lowest-latency non-
461 // tearing mode. If not, fall back to FIFO which is always available.
462 VkPresentModeKHR mode = VK_PRESENT_MODE_FIFO_KHR;
463 for (uint32_t i = 0; i < presentModeCount; ++i) {
464 // use mailbox
465 if (VK_PRESENT_MODE_MAILBOX_KHR == presentModes[i]) {
466 mode = presentModes[i];
467 break;
468 }
469 }
470
471 VkSwapchainCreateInfoKHR swapchainCreateInfo;
472 memset(&swapchainCreateInfo, 0, sizeof(VkSwapchainCreateInfoKHR));
473 swapchainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
474 swapchainCreateInfo.surface = surface->mVkSurface;
475 swapchainCreateInfo.minImageCount = imageCount;
476 swapchainCreateInfo.imageFormat = surfaceFormat;
477 swapchainCreateInfo.imageColorSpace = colorSpace;
478 swapchainCreateInfo.imageExtent = extent;
479 swapchainCreateInfo.imageArrayLayers = 1;
480 swapchainCreateInfo.imageUsage = usageFlags;
481
482 uint32_t queueFamilies[] = { mBackendContext->fGraphicsQueueIndex, mPresentQueueIndex };
483 if (mBackendContext->fGraphicsQueueIndex != mPresentQueueIndex) {
484 swapchainCreateInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
485 swapchainCreateInfo.queueFamilyIndexCount = 2;
486 swapchainCreateInfo.pQueueFamilyIndices = queueFamilies;
487 } else {
488 swapchainCreateInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
489 swapchainCreateInfo.queueFamilyIndexCount = 0;
490 swapchainCreateInfo.pQueueFamilyIndices = nullptr;
491 }
492
493 swapchainCreateInfo.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
494 swapchainCreateInfo.compositeAlpha = composite_alpha;
495 swapchainCreateInfo.presentMode = mode;
496 swapchainCreateInfo.clipped = true;
497 swapchainCreateInfo.oldSwapchain = surface->mSwapchain;
498
499 res = mCreateSwapchainKHR(mBackendContext->fDevice, &swapchainCreateInfo, nullptr,
500 &surface->mSwapchain);
501 if (VK_SUCCESS != res) {
502 return false;
503 }
504
505 // destroy the old swapchain
506 if (swapchainCreateInfo.oldSwapchain != VK_NULL_HANDLE) {
507 mDeviceWaitIdle(mBackendContext->fDevice);
508
509 destroyBuffers(surface);
510
511 mDestroySwapchainKHR(mBackendContext->fDevice, swapchainCreateInfo.oldSwapchain, nullptr);
512 }
513
514 createBuffers(surface, surfaceFormat, extent);
515
516 return true;
517}
518
519
520VulkanSurface* VulkanManager::createSurface(ANativeWindow* window) {
521 initialize();
522
523 if (!window) {
524 return nullptr;
525 }
526
527 VulkanSurface* surface = new VulkanSurface();
528
529 VkAndroidSurfaceCreateInfoKHR surfaceCreateInfo;
530 memset(&surfaceCreateInfo, 0, sizeof(VkAndroidSurfaceCreateInfoKHR));
531 surfaceCreateInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR;
532 surfaceCreateInfo.pNext = nullptr;
533 surfaceCreateInfo.flags = 0;
534 surfaceCreateInfo.window = window;
535
536 VkResult res = mCreateAndroidSurfaceKHR(mBackendContext->fInstance, &surfaceCreateInfo,
537 nullptr, &surface->mVkSurface);
538 if (VK_SUCCESS != res) {
539 delete surface;
540 return nullptr;
541 }
542
543SkDEBUGCODE(
544 VkBool32 supported;
545 res = mGetPhysicalDeviceSurfaceSupportKHR(mBackendContext->fPhysicalDevice,
546 mPresentQueueIndex, surface->mVkSurface, &supported);
547 // All physical devices and queue families on Android must be capable of presentation with any
548 // native window.
549 SkASSERT(VK_SUCCESS == res && supported);
550);
551
552 if (!createSwapchain(surface)) {
553 destroySurface(surface);
554 return nullptr;
555 }
556
557 return surface;
558}
559
560// Helper to know which src stage flags we need to set when transitioning to the present layout
561static VkPipelineStageFlags layoutToPipelineStageFlags(const VkImageLayout layout) {
562 if (VK_IMAGE_LAYOUT_GENERAL == layout) {
563 return VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
564 } else if (VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL == layout ||
565 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL == layout) {
566 return VK_PIPELINE_STAGE_TRANSFER_BIT;
567 } else if (VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL == layout ||
568 VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL == layout ||
569 VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL == layout ||
570 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL == layout) {
571 return VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT;
572 } else if (VK_IMAGE_LAYOUT_PREINITIALIZED == layout) {
573 return VK_PIPELINE_STAGE_HOST_BIT;
574 }
575
576 SkASSERT(VK_IMAGE_LAYOUT_UNDEFINED == layout);
577 return VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
578}
579
580// Helper to know which src access mask we need to set when transitioning to the present layout
581static VkAccessFlags layoutToSrcAccessMask(const VkImageLayout layout) {
582 VkAccessFlags flags = 0;
583 if (VK_IMAGE_LAYOUT_GENERAL == layout) {
584 flags = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
585 VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
586 VK_ACCESS_TRANSFER_WRITE_BIT |
587 VK_ACCESS_TRANSFER_READ_BIT |
588 VK_ACCESS_SHADER_READ_BIT |
589 VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_HOST_READ_BIT;
590 } else if (VK_IMAGE_LAYOUT_PREINITIALIZED == layout) {
591 flags = VK_ACCESS_HOST_WRITE_BIT;
592 } else if (VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL == layout) {
593 flags = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
594 } else if (VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL == layout) {
595 flags = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
596 } else if (VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL == layout) {
597 flags = VK_ACCESS_TRANSFER_WRITE_BIT;
598 } else if (VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL == layout) {
599 flags = VK_ACCESS_TRANSFER_READ_BIT;
600 } else if (VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL == layout) {
601 flags = VK_ACCESS_SHADER_READ_BIT;
602 }
603 return flags;
604}
605
606void VulkanManager::swapBuffers(VulkanSurface* surface) {
607 VulkanSurface::BackbufferInfo* backbuffer = surface->mBackbuffers +
608 surface->mCurrentBackbufferIndex;
609 GrVkImageInfo* imageInfo;
Greg Danielcd558522016-11-17 13:31:40 -0500610 SkSurface* skSurface = surface->mImageInfos[backbuffer->mImageIndex].mSurface.get();
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500611 skSurface->getRenderTargetHandle((GrBackendObject*)&imageInfo,
612 SkSurface::kFlushRead_BackendHandleAccess);
613 // Check to make sure we never change the actually wrapped image
614 SkASSERT(imageInfo->fImage == surface->mImages[backbuffer->mImageIndex]);
615
616 // We need to transition the image to VK_IMAGE_LAYOUT_PRESENT_SRC_KHR and make sure that all
617 // previous work is complete for before presenting. So we first add the necessary barrier here.
618 VkImageLayout layout = imageInfo->fImageLayout;
619 VkPipelineStageFlags srcStageMask = layoutToPipelineStageFlags(layout);
620 VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
621 VkAccessFlags srcAccessMask = layoutToSrcAccessMask(layout);
622 VkAccessFlags dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
623
624 VkImageMemoryBarrier imageMemoryBarrier = {
625 VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // sType
626 NULL, // pNext
627 srcAccessMask, // outputMask
628 dstAccessMask, // inputMask
629 layout, // oldLayout
630 VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, // newLayout
631 mBackendContext->fGraphicsQueueIndex, // srcQueueFamilyIndex
632 mPresentQueueIndex, // dstQueueFamilyIndex
633 surface->mImages[backbuffer->mImageIndex], // image
634 { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 } // subresourceRange
635 };
636
637 mResetCommandBuffer(backbuffer->mTransitionCmdBuffers[1], 0);
638 VkCommandBufferBeginInfo info;
639 memset(&info, 0, sizeof(VkCommandBufferBeginInfo));
640 info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
641 info.flags = 0;
642 mBeginCommandBuffer(backbuffer->mTransitionCmdBuffers[1], &info);
643 mCmdPipelineBarrier(backbuffer->mTransitionCmdBuffers[1], srcStageMask, dstStageMask, 0,
644 0, nullptr, 0, nullptr, 1, &imageMemoryBarrier);
645 mEndCommandBuffer(backbuffer->mTransitionCmdBuffers[1]);
646
Greg Danielcd558522016-11-17 13:31:40 -0500647 surface->mImageInfos[backbuffer->mImageIndex].mImageLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500648
649 // insert the layout transfer into the queue and wait on the acquire
650 VkSubmitInfo submitInfo;
651 memset(&submitInfo, 0, sizeof(VkSubmitInfo));
652 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
653 submitInfo.waitSemaphoreCount = 0;
654 submitInfo.pWaitDstStageMask = 0;
655 submitInfo.commandBufferCount = 1;
656 submitInfo.pCommandBuffers = &backbuffer->mTransitionCmdBuffers[1];
657 submitInfo.signalSemaphoreCount = 1;
658 // When this command buffer finishes we will signal this semaphore so that we know it is now
659 // safe to present the image to the screen.
660 submitInfo.pSignalSemaphores = &backbuffer->mRenderSemaphore;
661
662 // Attach second fence to submission here so we can track when the command buffer finishes.
663 mQueueSubmit(mBackendContext->fQueue, 1, &submitInfo, backbuffer->mUsageFences[1]);
664
665 // Submit present operation to present queue. We use a semaphore here to make sure all rendering
666 // to the image is complete and that the layout has been change to present on the graphics
667 // queue.
668 const VkPresentInfoKHR presentInfo =
669 {
670 VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, // sType
671 NULL, // pNext
672 1, // waitSemaphoreCount
673 &backbuffer->mRenderSemaphore, // pWaitSemaphores
674 1, // swapchainCount
675 &surface->mSwapchain, // pSwapchains
676 &backbuffer->mImageIndex, // pImageIndices
677 NULL // pResults
678 };
679
680 mQueuePresentKHR(mPresentQueue, &presentInfo);
681
682 surface->mBackbuffer.reset();
Greg Danielcd558522016-11-17 13:31:40 -0500683 surface->mImageInfos[backbuffer->mImageIndex].mLastUsed = surface->mCurrentTime;
684 surface->mImageInfos[backbuffer->mImageIndex].mInvalid = false;
685 surface->mCurrentTime++;
686}
687
688int VulkanManager::getAge(VulkanSurface* surface) {
689 VulkanSurface::BackbufferInfo* backbuffer = surface->mBackbuffers +
690 surface->mCurrentBackbufferIndex;
691 if (mSwapBehavior == SwapBehavior::Discard
692 || surface->mImageInfos[backbuffer->mImageIndex].mInvalid) {
693 return 0;
694 }
695 uint16_t lastUsed = surface->mImageInfos[backbuffer->mImageIndex].mLastUsed;
696 return surface->mCurrentTime - lastUsed;
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500697}
698
699} /* namespace renderthread */
700} /* namespace uirenderer */
701} /* namespace android */