1 /*
2  * Copyright 2015 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 "include/gpu/GrBackendSurface.h"
9 #include "include/gpu/vk/GrVkBackendContext.h"
10 #include "include/gpu/vk/GrVkExtensions.h"
11 #include "src/gpu/GrRenderTarget.h"
12 #include "src/gpu/GrRenderTargetProxy.h"
13 #include "src/gpu/GrShaderCaps.h"
14 #include "src/gpu/GrUtil.h"
15 #include "src/gpu/SkGr.h"
16 #include "src/gpu/vk/GrVkCaps.h"
17 #include "src/gpu/vk/GrVkInterface.h"
18 #include "src/gpu/vk/GrVkTexture.h"
19 #include "src/gpu/vk/GrVkUniformHandler.h"
20 #include "src/gpu/vk/GrVkUtil.h"
21 
22 #ifdef SK_BUILD_FOR_ANDROID
23 #include <sys/system_properties.h>
24 #endif
25 
GrVkCaps(const GrContextOptions & contextOptions,const GrVkInterface * vkInterface,VkPhysicalDevice physDev,const VkPhysicalDeviceFeatures2 & features,uint32_t instanceVersion,uint32_t physicalDeviceVersion,const GrVkExtensions & extensions,GrProtected isProtected)26 GrVkCaps::GrVkCaps(const GrContextOptions& contextOptions, const GrVkInterface* vkInterface,
27                    VkPhysicalDevice physDev, const VkPhysicalDeviceFeatures2& features,
28                    uint32_t instanceVersion, uint32_t physicalDeviceVersion,
29                    const GrVkExtensions& extensions, GrProtected isProtected)
30         : INHERITED(contextOptions) {
31     /**************************************************************************
32      * GrCaps fields
33      **************************************************************************/
34     fMipMapSupport = true;   // always available in Vulkan
35     fNPOTTextureTileSupport = true;  // always available in Vulkan
36     fReuseScratchTextures = true; //TODO: figure this out
37     fGpuTracingSupport = false; //TODO: figure this out
38     fOversizedStencilSupport = false; //TODO: figure this out
39     fInstanceAttribSupport = true;
40 
41     fSemaphoreSupport = true;   // always available in Vulkan
42     fFenceSyncSupport = true;   // always available in Vulkan
43     fCrossContextTextureSupport = true;
44     fHalfFloatVertexAttributeSupport = true;
45 
46     // We always copy in/out of a transfer buffer so it's trivial to support row bytes.
47     fReadPixelsRowBytesSupport = true;
48     fWritePixelsRowBytesSupport = true;
49 
50     fTransferBufferSupport = true;
51 
52     fMaxRenderTargetSize = 4096; // minimum required by spec
53     fMaxTextureSize = 4096; // minimum required by spec
54 
55     fDynamicStateArrayGeometryProcessorTextureSupport = true;
56 
57     fShaderCaps.reset(new GrShaderCaps(contextOptions));
58 
59     this->init(contextOptions, vkInterface, physDev, features, physicalDeviceVersion, extensions,
60                isProtected);
61 }
62 
63 namespace {
64 /**
65  * This comes from section 37.1.6 of the Vulkan spec. Format is
66  * (<bits>|<tag>)_<block_size>_<texels_per_block>.
67  */
68 enum class FormatCompatibilityClass {
69     k8_1_1,
70     k16_2_1,
71     k24_3_1,
72     k32_4_1,
73     k64_8_1,
74     kETC2_RGB_8_16,
75 };
76 }  // anonymous namespace
77 
format_compatibility_class(VkFormat format)78 static FormatCompatibilityClass format_compatibility_class(VkFormat format) {
79     switch (format) {
80         case VK_FORMAT_B8G8R8A8_UNORM:
81         case VK_FORMAT_R8G8B8A8_UNORM:
82         case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
83         case VK_FORMAT_R8G8B8A8_SRGB:
84         case VK_FORMAT_R16G16_UNORM:
85         case VK_FORMAT_R16G16_SFLOAT:
86             return FormatCompatibilityClass::k32_4_1;
87 
88         case VK_FORMAT_R8_UNORM:
89             return FormatCompatibilityClass::k8_1_1;
90 
91         case VK_FORMAT_R5G6B5_UNORM_PACK16:
92         case VK_FORMAT_R16_SFLOAT:
93         case VK_FORMAT_R8G8_UNORM:
94         case VK_FORMAT_B4G4R4A4_UNORM_PACK16:
95         case VK_FORMAT_R4G4B4A4_UNORM_PACK16:
96         case VK_FORMAT_R16_UNORM:
97             return FormatCompatibilityClass::k16_2_1;
98 
99         case VK_FORMAT_R16G16B16A16_SFLOAT:
100         case VK_FORMAT_R16G16B16A16_UNORM:
101             return FormatCompatibilityClass::k64_8_1;
102 
103         case VK_FORMAT_R8G8B8_UNORM:
104             return FormatCompatibilityClass::k24_3_1;
105 
106         case VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK:
107             return FormatCompatibilityClass::kETC2_RGB_8_16;
108 
109         default:
110             SK_ABORT("Unsupported VkFormat");
111     }
112 }
113 
canCopyImage(VkFormat dstFormat,int dstSampleCnt,bool dstHasYcbcr,VkFormat srcFormat,int srcSampleCnt,bool srcHasYcbcr) const114 bool GrVkCaps::canCopyImage(VkFormat dstFormat, int dstSampleCnt, bool dstHasYcbcr,
115                             VkFormat srcFormat, int srcSampleCnt, bool srcHasYcbcr) const {
116     if ((dstSampleCnt > 1 || srcSampleCnt > 1) && dstSampleCnt != srcSampleCnt) {
117         return false;
118     }
119 
120     if (dstHasYcbcr || srcHasYcbcr) {
121         return false;
122     }
123 
124     // We require that all Vulkan GrSurfaces have been created with transfer_dst and transfer_src
125     // as image usage flags.
126     return format_compatibility_class(srcFormat) == format_compatibility_class(dstFormat);
127 }
128 
canCopyAsBlit(VkFormat dstFormat,int dstSampleCnt,bool dstIsLinear,bool dstHasYcbcr,VkFormat srcFormat,int srcSampleCnt,bool srcIsLinear,bool srcHasYcbcr) const129 bool GrVkCaps::canCopyAsBlit(VkFormat dstFormat, int dstSampleCnt, bool dstIsLinear,
130                              bool dstHasYcbcr, VkFormat srcFormat, int srcSampleCnt,
131                              bool srcIsLinear, bool srcHasYcbcr) const {
132     // We require that all vulkan GrSurfaces have been created with transfer_dst and transfer_src
133     // as image usage flags.
134     if (!this->formatCanBeDstofBlit(dstFormat, dstIsLinear) ||
135         !this->formatCanBeSrcofBlit(srcFormat, srcIsLinear)) {
136         return false;
137     }
138 
139     // We cannot blit images that are multisampled. Will need to figure out if we can blit the
140     // resolved msaa though.
141     if (dstSampleCnt > 1 || srcSampleCnt > 1) {
142         return false;
143     }
144 
145     if (dstHasYcbcr || srcHasYcbcr) {
146         return false;
147     }
148 
149     return true;
150 }
151 
canCopyAsResolve(VkFormat dstFormat,int dstSampleCnt,bool dstHasYcbcr,VkFormat srcFormat,int srcSampleCnt,bool srcHasYcbcr) const152 bool GrVkCaps::canCopyAsResolve(VkFormat dstFormat, int dstSampleCnt, bool dstHasYcbcr,
153                                 VkFormat srcFormat, int srcSampleCnt, bool srcHasYcbcr) const {
154     // The src surface must be multisampled.
155     if (srcSampleCnt <= 1) {
156         return false;
157     }
158 
159     // The dst must not be multisampled.
160     if (dstSampleCnt > 1) {
161         return false;
162     }
163 
164     // Surfaces must have the same format.
165     if (srcFormat != dstFormat) {
166         return false;
167     }
168 
169     if (dstHasYcbcr || srcHasYcbcr) {
170         return false;
171     }
172 
173     return true;
174 }
175 
onCanCopySurface(const GrSurfaceProxy * dst,const GrSurfaceProxy * src,const SkIRect & srcRect,const SkIPoint & dstPoint) const176 bool GrVkCaps::onCanCopySurface(const GrSurfaceProxy* dst, const GrSurfaceProxy* src,
177                                 const SkIRect& srcRect, const SkIPoint& dstPoint) const {
178     if (src->isProtected() && !dst->isProtected()) {
179         return false;
180     }
181 
182     // TODO: Figure out a way to track if we've wrapped a linear texture in a proxy (e.g.
183     // PromiseImage which won't get instantiated right away. Does this need a similar thing like the
184     // tracking of external or rectangle textures in GL? For now we don't create linear textures
185     // internally, and I don't believe anyone is wrapping them.
186     bool srcIsLinear = false;
187     bool dstIsLinear = false;
188 
189     int dstSampleCnt = 0;
190     int srcSampleCnt = 0;
191     if (const GrRenderTargetProxy* rtProxy = dst->asRenderTargetProxy()) {
192         // Copying to or from render targets that wrap a secondary command buffer is not allowed
193         // since they would require us to know the VkImage, which we don't have, as well as need us
194         // to stop and start the VkRenderPass which we don't have access to.
195         if (rtProxy->wrapsVkSecondaryCB()) {
196             return false;
197         }
198         dstSampleCnt = rtProxy->numSamples();
199     }
200     if (const GrRenderTargetProxy* rtProxy = src->asRenderTargetProxy()) {
201         // Copying to or from render targets that wrap a secondary command buffer is not allowed
202         // since they would require us to know the VkImage, which we don't have, as well as need us
203         // to stop and start the VkRenderPass which we don't have access to.
204         if (rtProxy->wrapsVkSecondaryCB()) {
205             return false;
206         }
207         srcSampleCnt = rtProxy->numSamples();
208     }
209     SkASSERT((dstSampleCnt > 0) == SkToBool(dst->asRenderTargetProxy()));
210     SkASSERT((srcSampleCnt > 0) == SkToBool(src->asRenderTargetProxy()));
211 
212     bool dstHasYcbcr = false;
213     if (auto ycbcr = dst->backendFormat().getVkYcbcrConversionInfo()) {
214         if (ycbcr->isValid()) {
215             dstHasYcbcr = true;
216         }
217     }
218 
219     bool srcHasYcbcr = false;
220     if (auto ycbcr = src->backendFormat().getVkYcbcrConversionInfo()) {
221         if (ycbcr->isValid()) {
222             srcHasYcbcr = true;
223         }
224     }
225 
226     VkFormat dstFormat, srcFormat;
227     SkAssertResult(dst->backendFormat().asVkFormat(&dstFormat));
228     SkAssertResult(src->backendFormat().asVkFormat(&srcFormat));
229 
230     return this->canCopyImage(dstFormat, dstSampleCnt, dstHasYcbcr,
231                               srcFormat, srcSampleCnt, srcHasYcbcr) ||
232            this->canCopyAsBlit(dstFormat, dstSampleCnt, dstIsLinear, dstHasYcbcr,
233                                srcFormat, srcSampleCnt, srcIsLinear, srcHasYcbcr) ||
234            this->canCopyAsResolve(dstFormat, dstSampleCnt, dstHasYcbcr,
235                                   srcFormat, srcSampleCnt, srcHasYcbcr);
236 }
237 
get_extension_feature_struct(const VkPhysicalDeviceFeatures2 & features,VkStructureType type)238 template<typename T> T* get_extension_feature_struct(const VkPhysicalDeviceFeatures2& features,
239                                                      VkStructureType type) {
240     // All Vulkan structs that could be part of the features chain will start with the
241     // structure type followed by the pNext pointer. We cast to the CommonVulkanHeader
242     // so we can get access to the pNext for the next struct.
243     struct CommonVulkanHeader {
244         VkStructureType sType;
245         void*           pNext;
246     };
247 
248     void* pNext = features.pNext;
249     while (pNext) {
250         CommonVulkanHeader* header = static_cast<CommonVulkanHeader*>(pNext);
251         if (header->sType == type) {
252             return static_cast<T*>(pNext);
253         }
254         pNext = header->pNext;
255     }
256     return nullptr;
257 }
258 
init(const GrContextOptions & contextOptions,const GrVkInterface * vkInterface,VkPhysicalDevice physDev,const VkPhysicalDeviceFeatures2 & features,uint32_t physicalDeviceVersion,const GrVkExtensions & extensions,GrProtected isProtected)259 void GrVkCaps::init(const GrContextOptions& contextOptions, const GrVkInterface* vkInterface,
260                     VkPhysicalDevice physDev, const VkPhysicalDeviceFeatures2& features,
261                     uint32_t physicalDeviceVersion, const GrVkExtensions& extensions,
262                     GrProtected isProtected) {
263     VkPhysicalDeviceProperties properties;
264     GR_VK_CALL(vkInterface, GetPhysicalDeviceProperties(physDev, &properties));
265 
266     VkPhysicalDeviceMemoryProperties memoryProperties;
267     GR_VK_CALL(vkInterface, GetPhysicalDeviceMemoryProperties(physDev, &memoryProperties));
268 
269     SkASSERT(physicalDeviceVersion <= properties.apiVersion);
270 
271     if (extensions.hasExtension(VK_KHR_SWAPCHAIN_EXTENSION_NAME, 1)) {
272         fSupportsSwapchain = true;
273     }
274 
275     if (physicalDeviceVersion >= VK_MAKE_VERSION(1, 1, 0) ||
276         extensions.hasExtension(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, 1)) {
277         fSupportsPhysicalDeviceProperties2 = true;
278     }
279 
280     if (physicalDeviceVersion >= VK_MAKE_VERSION(1, 1, 0) ||
281         extensions.hasExtension(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME, 1)) {
282         fSupportsMemoryRequirements2 = true;
283     }
284 
285     if (physicalDeviceVersion >= VK_MAKE_VERSION(1, 1, 0) ||
286         extensions.hasExtension(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME, 1)) {
287         fSupportsBindMemory2 = true;
288     }
289 
290     if (physicalDeviceVersion >= VK_MAKE_VERSION(1, 1, 0) ||
291         extensions.hasExtension(VK_KHR_MAINTENANCE1_EXTENSION_NAME, 1)) {
292         fSupportsMaintenance1 = true;
293     }
294 
295     if (physicalDeviceVersion >= VK_MAKE_VERSION(1, 1, 0) ||
296         extensions.hasExtension(VK_KHR_MAINTENANCE2_EXTENSION_NAME, 1)) {
297         fSupportsMaintenance2 = true;
298     }
299 
300     if (physicalDeviceVersion >= VK_MAKE_VERSION(1, 1, 0) ||
301         extensions.hasExtension(VK_KHR_MAINTENANCE3_EXTENSION_NAME, 1)) {
302         fSupportsMaintenance3 = true;
303     }
304 
305     if (physicalDeviceVersion >= VK_MAKE_VERSION(1, 1, 0) ||
306         (extensions.hasExtension(VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME, 1) &&
307          this->supportsMemoryRequirements2())) {
308         fSupportsDedicatedAllocation = true;
309     }
310 
311     if (physicalDeviceVersion >= VK_MAKE_VERSION(1, 1, 0) ||
312         (extensions.hasExtension(VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME, 1) &&
313          this->supportsPhysicalDeviceProperties2() &&
314          extensions.hasExtension(VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME, 1) &&
315          this->supportsDedicatedAllocation())) {
316         fSupportsExternalMemory = true;
317     }
318 
319 #ifdef SK_BUILD_FOR_ANDROID
320     // Currently Adreno devices are not supporting the QUEUE_FAMILY_FOREIGN_EXTENSION, so until they
321     // do we don't explicitly require it here even the spec says it is required.
322     if (extensions.hasExtension(
323             VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME, 2) &&
324        /* extensions.hasExtension(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME, 1) &&*/
325         this->supportsExternalMemory() &&
326         this->supportsBindMemory2()) {
327         fSupportsAndroidHWBExternalMemory = true;
328         fSupportsAHardwareBufferImages = true;
329     }
330 #endif
331 
332     auto ycbcrFeatures =
333             get_extension_feature_struct<VkPhysicalDeviceSamplerYcbcrConversionFeatures>(
334                     features, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES);
335     if (ycbcrFeatures && ycbcrFeatures->samplerYcbcrConversion &&
336         (physicalDeviceVersion >= VK_MAKE_VERSION(1, 1, 0) ||
337          (extensions.hasExtension(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME, 1) &&
338           this->supportsMaintenance1() && this->supportsBindMemory2() &&
339           this->supportsMemoryRequirements2() && this->supportsPhysicalDeviceProperties2()))) {
340         fSupportsYcbcrConversion = true;
341     }
342 
343     // We always push back the default GrVkYcbcrConversionInfo so that the case of no conversion
344     // will return a key of 0.
345     fYcbcrInfos.push_back(GrVkYcbcrConversionInfo());
346 
347     if ((isProtected == GrProtected::kYes) &&
348         (physicalDeviceVersion >= VK_MAKE_VERSION(1, 1, 0))) {
349         fSupportsProtectedMemory = true;
350         fAvoidUpdateBuffers = true;
351         fShouldAlwaysUseDedicatedImageMemory = true;
352     }
353 
354     this->initGrCaps(vkInterface, physDev, properties, memoryProperties, features, extensions);
355     this->initShaderCaps(properties, features);
356 
357     if (kQualcomm_VkVendor == properties.vendorID) {
358         // A "clear" load for the CCPR atlas runs faster on QC than a "discard" load followed by a
359         // scissored clear.
360         // On NVIDIA and Intel, the discard load followed by clear is faster.
361         // TODO: Evaluate on ARM, Imagination, and ATI.
362         fPreferFullscreenClears = true;
363     }
364 
365     if (kQualcomm_VkVendor == properties.vendorID || kARM_VkVendor == properties.vendorID) {
366         // On Qualcomm and ARM mapping a gpu buffer and doing both reads and writes to it is slow.
367         // Thus for index and vertex buffers we will force to use a cpu side buffer and then copy
368         // the whole buffer up to the gpu.
369         fBufferMapThreshold = SK_MaxS32;
370     }
371 
372     if (kQualcomm_VkVendor == properties.vendorID) {
373         // On Qualcomm it looks like using vkCmdUpdateBuffer is slower than using a transfer buffer
374         // even for small sizes.
375         fAvoidUpdateBuffers = true;
376     }
377 
378     if (kARM_VkVendor == properties.vendorID) {
379         // ARM seems to do better with more fine triangles as opposed to using the sample mask.
380         // (At least in our current round rect op.)
381         fPreferTrianglesOverSampleMask = true;
382     }
383 
384     this->initFormatTable(vkInterface, physDev, properties);
385     this->initStencilFormat(vkInterface, physDev);
386 
387     if (!contextOptions.fDisableDriverCorrectnessWorkarounds) {
388         this->applyDriverCorrectnessWorkarounds(properties);
389     }
390 
391     this->applyOptionsOverrides(contextOptions);
392     fShaderCaps->applyOptionsOverrides(contextOptions);
393 }
394 
applyDriverCorrectnessWorkarounds(const VkPhysicalDeviceProperties & properties)395 void GrVkCaps::applyDriverCorrectnessWorkarounds(const VkPhysicalDeviceProperties& properties) {
396     if (kQualcomm_VkVendor == properties.vendorID) {
397         fMustDoCopiesFromOrigin = true;
398         // Transfer doesn't support this workaround.
399         fTransferBufferSupport = false;
400     }
401 
402 #if defined(SK_BUILD_FOR_WIN)
403     if (kNvidia_VkVendor == properties.vendorID || kIntel_VkVendor == properties.vendorID) {
404         fMustSleepOnTearDown = true;
405     }
406 #elif defined(SK_BUILD_FOR_ANDROID)
407     if (kImagination_VkVendor == properties.vendorID) {
408         fMustSleepOnTearDown = true;
409     }
410 #endif
411 
412 #if defined(SK_BUILD_FOR_ANDROID)
413     // Protected memory features have problems in Android P and earlier.
414     if (fSupportsProtectedMemory && (kQualcomm_VkVendor == properties.vendorID)) {
415         char androidAPIVersion[PROP_VALUE_MAX];
416         int strLength = __system_property_get("ro.build.version.sdk", androidAPIVersion);
417         if (strLength == 0 || atoi(androidAPIVersion) <= 28) {
418             fSupportsProtectedMemory = false;
419         }
420     }
421 #endif
422 
423     // On Mali galaxy s7 we see lots of rendering issues when we suballocate VkImages.
424     if (kARM_VkVendor == properties.vendorID) {
425         fShouldAlwaysUseDedicatedImageMemory = true;
426     }
427 
428     // On Mali galaxy s7 and s9 we see lots of rendering issues with image filters dropping out when
429     // using only primary command buffers.
430     if (kARM_VkVendor == properties.vendorID) {
431         fPreferPrimaryOverSecondaryCommandBuffers = false;
432     }
433 
434     // On various devices, when calling vkCmdClearAttachments on a primary command buffer, it
435     // corrupts the bound buffers on the command buffer. As a workaround we invalidate our knowledge
436     // of bound buffers so that we will rebind them on the next draw.
437     if (kQualcomm_VkVendor == properties.vendorID || kAMD_VkVendor == properties.vendorID) {
438         fMustInvalidatePrimaryCmdBufferStateAfterClearAttachments = true;
439     }
440 
441     ////////////////////////////////////////////////////////////////////////////
442     // GrCaps workarounds
443     ////////////////////////////////////////////////////////////////////////////
444 
445     if (kARM_VkVendor == properties.vendorID) {
446         fInstanceAttribSupport = false;
447         fAvoidWritePixelsFastPath = true; // bugs.skia.org/8064
448     }
449 
450     // AMD advertises support for MAX_UINT vertex input attributes, but in reality only supports 32.
451     if (kAMD_VkVendor == properties.vendorID) {
452         fMaxVertexAttributes = SkTMin(fMaxVertexAttributes, 32);
453     }
454 
455     ////////////////////////////////////////////////////////////////////////////
456     // GrShaderCaps workarounds
457     ////////////////////////////////////////////////////////////////////////////
458 
459     if (kImagination_VkVendor == properties.vendorID) {
460         fShaderCaps->fAtan2ImplementedAsAtanYOverX = true;
461     }
462 }
463 
get_max_sample_count(VkSampleCountFlags flags)464 int get_max_sample_count(VkSampleCountFlags flags) {
465     SkASSERT(flags & VK_SAMPLE_COUNT_1_BIT);
466     if (!(flags & VK_SAMPLE_COUNT_2_BIT)) {
467         return 0;
468     }
469     if (!(flags & VK_SAMPLE_COUNT_4_BIT)) {
470         return 2;
471     }
472     if (!(flags & VK_SAMPLE_COUNT_8_BIT)) {
473         return 4;
474     }
475     if (!(flags & VK_SAMPLE_COUNT_16_BIT)) {
476         return 8;
477     }
478     if (!(flags & VK_SAMPLE_COUNT_32_BIT)) {
479         return 16;
480     }
481     if (!(flags & VK_SAMPLE_COUNT_64_BIT)) {
482         return 32;
483     }
484     return 64;
485 }
486 
initGrCaps(const GrVkInterface * vkInterface,VkPhysicalDevice physDev,const VkPhysicalDeviceProperties & properties,const VkPhysicalDeviceMemoryProperties & memoryProperties,const VkPhysicalDeviceFeatures2 & features,const GrVkExtensions & extensions)487 void GrVkCaps::initGrCaps(const GrVkInterface* vkInterface,
488                           VkPhysicalDevice physDev,
489                           const VkPhysicalDeviceProperties& properties,
490                           const VkPhysicalDeviceMemoryProperties& memoryProperties,
491                           const VkPhysicalDeviceFeatures2& features,
492                           const GrVkExtensions& extensions) {
493     // So GPUs, like AMD, are reporting MAX_INT support vertex attributes. In general, there is no
494     // need for us ever to support that amount, and it makes tests which tests all the vertex
495     // attribs timeout looping over that many. For now, we'll cap this at 64 max and can raise it if
496     // we ever find that need.
497     static const uint32_t kMaxVertexAttributes = 64;
498     fMaxVertexAttributes = SkTMin(properties.limits.maxVertexInputAttributes, kMaxVertexAttributes);
499 
500     // We could actually query and get a max size for each config, however maxImageDimension2D will
501     // give the minimum max size across all configs. So for simplicity we will use that for now.
502     fMaxRenderTargetSize = SkTMin(properties.limits.maxImageDimension2D, (uint32_t)INT_MAX);
503     fMaxTextureSize = SkTMin(properties.limits.maxImageDimension2D, (uint32_t)INT_MAX);
504     if (fDriverBugWorkarounds.max_texture_size_limit_4096) {
505         fMaxTextureSize = SkTMin(fMaxTextureSize, 4096);
506     }
507     // Our render targets are always created with textures as the color
508     // attachment, hence this min:
509     fMaxRenderTargetSize = SkTMin(fMaxTextureSize, fMaxRenderTargetSize);
510 
511     // TODO: check if RT's larger than 4k incur a performance cost on ARM.
512     fMaxPreferredRenderTargetSize = fMaxRenderTargetSize;
513 
514     // Assuming since we will always map in the end to upload the data we might as well just map
515     // from the get go. There is no hard data to suggest this is faster or slower.
516     fBufferMapThreshold = 0;
517 
518     fMapBufferFlags = kCanMap_MapFlag | kSubset_MapFlag | kAsyncRead_MapFlag;
519 
520     fOversizedStencilSupport = true;
521 
522     if (extensions.hasExtension(VK_EXT_BLEND_OPERATION_ADVANCED_EXTENSION_NAME, 2) &&
523         this->supportsPhysicalDeviceProperties2()) {
524 
525         VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT blendProps;
526         blendProps.sType =
527                 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BLEND_OPERATION_ADVANCED_PROPERTIES_EXT;
528         blendProps.pNext = nullptr;
529 
530         VkPhysicalDeviceProperties2 props;
531         props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
532         props.pNext = &blendProps;
533 
534         GR_VK_CALL(vkInterface, GetPhysicalDeviceProperties2(physDev, &props));
535 
536         if (blendProps.advancedBlendAllOperations == VK_TRUE) {
537             fShaderCaps->fAdvBlendEqInteraction = GrShaderCaps::kAutomatic_AdvBlendEqInteraction;
538 
539             auto blendFeatures =
540                 get_extension_feature_struct<VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT>(
541                     features,
542                     VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BLEND_OPERATION_ADVANCED_FEATURES_EXT);
543             if (blendFeatures && blendFeatures->advancedBlendCoherentOperations == VK_TRUE) {
544                 fBlendEquationSupport = kAdvancedCoherent_BlendEquationSupport;
545             } else {
546                 // TODO: Currently non coherent blends are not supported in our vulkan backend. They
547                 // require us to support self dependencies in our render passes.
548                 // fBlendEquationSupport = kAdvanced_BlendEquationSupport;
549             }
550         }
551     }
552 }
553 
initShaderCaps(const VkPhysicalDeviceProperties & properties,const VkPhysicalDeviceFeatures2 & features)554 void GrVkCaps::initShaderCaps(const VkPhysicalDeviceProperties& properties,
555                               const VkPhysicalDeviceFeatures2& features) {
556     GrShaderCaps* shaderCaps = fShaderCaps.get();
557     shaderCaps->fVersionDeclString = "#version 330\n";
558 
559     // Vulkan is based off ES 3.0 so the following should all be supported
560     shaderCaps->fUsesPrecisionModifiers = true;
561     shaderCaps->fFlatInterpolationSupport = true;
562     // Flat interpolation appears to be slow on Qualcomm GPUs. This was tested in GL and is assumed
563     // to be true with Vulkan as well.
564     shaderCaps->fPreferFlatInterpolation = kQualcomm_VkVendor != properties.vendorID;
565 
566     // GrShaderCaps
567 
568     shaderCaps->fShaderDerivativeSupport = true;
569 
570     // FIXME: http://skbug.com/7733: Disable geometry shaders until Intel/Radeon GMs draw correctly.
571     // shaderCaps->fGeometryShaderSupport =
572     //         shaderCaps->fGSInvocationsSupport = features.features.geometryShader;
573 
574     shaderCaps->fDualSourceBlendingSupport = features.features.dualSrcBlend;
575 
576     shaderCaps->fIntegerSupport = true;
577     shaderCaps->fVertexIDSupport = true;
578     shaderCaps->fFPManipulationSupport = true;
579 
580     // Assume the minimum precisions mandated by the SPIR-V spec.
581     shaderCaps->fFloatIs32Bits = true;
582     shaderCaps->fHalfIs32Bits = false;
583 
584     shaderCaps->fMaxFragmentSamplers = SkTMin(
585                                        SkTMin(properties.limits.maxPerStageDescriptorSampledImages,
586                                               properties.limits.maxPerStageDescriptorSamplers),
587                                               (uint32_t)INT_MAX);
588 }
589 
stencil_format_supported(const GrVkInterface * interface,VkPhysicalDevice physDev,VkFormat format)590 bool stencil_format_supported(const GrVkInterface* interface,
591                               VkPhysicalDevice physDev,
592                               VkFormat format) {
593     VkFormatProperties props;
594     memset(&props, 0, sizeof(VkFormatProperties));
595     GR_VK_CALL(interface, GetPhysicalDeviceFormatProperties(physDev, format, &props));
596     return SkToBool(VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT & props.optimalTilingFeatures);
597 }
598 
initStencilFormat(const GrVkInterface * interface,VkPhysicalDevice physDev)599 void GrVkCaps::initStencilFormat(const GrVkInterface* interface, VkPhysicalDevice physDev) {
600     // List of legal stencil formats (though perhaps not supported on
601     // the particular gpu/driver) from most preferred to least. We are guaranteed to have either
602     // VK_FORMAT_D24_UNORM_S8_UINT or VK_FORMAT_D32_SFLOAT_S8_UINT. VK_FORMAT_D32_SFLOAT_S8_UINT
603     // can optionally have 24 unused bits at the end so we assume the total bits is 64.
604     static const StencilFormat
605                   // internal Format             stencil bits      total bits        packed?
606         gS8    = { VK_FORMAT_S8_UINT,            8,                 8,               false },
607         gD24S8 = { VK_FORMAT_D24_UNORM_S8_UINT,  8,                32,               true },
608         gD32S8 = { VK_FORMAT_D32_SFLOAT_S8_UINT, 8,                64,               true };
609 
610     if (stencil_format_supported(interface, physDev, VK_FORMAT_S8_UINT)) {
611         fPreferredStencilFormat = gS8;
612     } else if (stencil_format_supported(interface, physDev, VK_FORMAT_D24_UNORM_S8_UINT)) {
613         fPreferredStencilFormat = gD24S8;
614     } else {
615         SkASSERT(stencil_format_supported(interface, physDev, VK_FORMAT_D32_SFLOAT_S8_UINT));
616         fPreferredStencilFormat = gD32S8;
617     }
618 }
619 
format_is_srgb(VkFormat format)620 static bool format_is_srgb(VkFormat format) {
621     SkASSERT(GrVkFormatIsSupported(format));
622 
623     switch (format) {
624         case VK_FORMAT_R8G8B8A8_SRGB:
625             return true;
626         default:
627             return false;
628     }
629 }
630 
631 // These are all the valid VkFormats that we support in Skia. They are roughly ordered from most
632 // frequently used to least to improve look up times in arrays.
633 static constexpr VkFormat kVkFormats[] = {
634     VK_FORMAT_R8G8B8A8_UNORM,
635     VK_FORMAT_R8_UNORM,
636     VK_FORMAT_B8G8R8A8_UNORM,
637     VK_FORMAT_R5G6B5_UNORM_PACK16,
638     VK_FORMAT_R16G16B16A16_SFLOAT,
639     VK_FORMAT_R16_SFLOAT,
640     VK_FORMAT_R8G8B8_UNORM,
641     VK_FORMAT_R8G8_UNORM,
642     VK_FORMAT_A2B10G10R10_UNORM_PACK32,
643     VK_FORMAT_B4G4R4A4_UNORM_PACK16,
644     VK_FORMAT_R4G4B4A4_UNORM_PACK16,
645     VK_FORMAT_R8G8B8A8_SRGB,
646     VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK,
647     VK_FORMAT_R16_UNORM,
648     VK_FORMAT_R16G16_UNORM,
649     VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM,
650     VK_FORMAT_G8_B8R8_2PLANE_420_UNORM,
651     VK_FORMAT_R16G16B16A16_UNORM,
652     VK_FORMAT_R16G16_SFLOAT,
653 };
654 
setColorType(GrColorType colorType,std::initializer_list<VkFormat> formats)655 void GrVkCaps::setColorType(GrColorType colorType, std::initializer_list<VkFormat> formats) {
656 #ifdef SK_DEBUG
657     for (size_t i = 0; i < kNumVkFormats; ++i) {
658         const auto& formatInfo = fFormatTable[i];
659         for (int j = 0; j < formatInfo.fColorTypeInfoCount; ++j) {
660             const auto& ctInfo = formatInfo.fColorTypeInfos[j];
661             if (ctInfo.fColorType == colorType &&
662                 !SkToBool(ctInfo.fFlags & ColorTypeInfo::kWrappedOnly_Flag)) {
663                 bool found = false;
664                 for (auto it = formats.begin(); it != formats.end(); ++it) {
665                     if (kVkFormats[i] == *it) {
666                         found = true;
667                     }
668                 }
669                 SkASSERT(found);
670             }
671         }
672     }
673 #endif
674     int idx = static_cast<int>(colorType);
675     for (auto it = formats.begin(); it != formats.end(); ++it) {
676         const auto& info = this->getFormatInfo(*it);
677         for (int i = 0; i < info.fColorTypeInfoCount; ++i) {
678             if (info.fColorTypeInfos[i].fColorType == colorType) {
679                 fColorTypeToFormatTable[idx] = *it;
680                 return;
681             }
682         }
683     }
684 }
685 
getFormatInfo(VkFormat format) const686 const GrVkCaps::FormatInfo& GrVkCaps::getFormatInfo(VkFormat format) const {
687     GrVkCaps* nonConstThis = const_cast<GrVkCaps*>(this);
688     return nonConstThis->getFormatInfo(format);
689 }
690 
getFormatInfo(VkFormat format)691 GrVkCaps::FormatInfo& GrVkCaps::getFormatInfo(VkFormat format) {
692     static_assert(SK_ARRAY_COUNT(kVkFormats) == GrVkCaps::kNumVkFormats,
693                   "Size of VkFormats array must match static value in header");
694     for (size_t i = 0; i < SK_ARRAY_COUNT(kVkFormats); ++i) {
695         if (kVkFormats[i] == format) {
696             return fFormatTable[i];
697         }
698     }
699     static FormatInfo kInvalidFormat;
700     return kInvalidFormat;
701 }
702 
initFormatTable(const GrVkInterface * interface,VkPhysicalDevice physDev,const VkPhysicalDeviceProperties & properties)703 void GrVkCaps::initFormatTable(const GrVkInterface* interface, VkPhysicalDevice physDev,
704                                const VkPhysicalDeviceProperties& properties) {
705     static_assert(SK_ARRAY_COUNT(kVkFormats) == GrVkCaps::kNumVkFormats,
706                   "Size of VkFormats array must match static value in header");
707 
708     std::fill_n(fColorTypeToFormatTable, kGrColorTypeCnt, VK_FORMAT_UNDEFINED);
709 
710     // Go through all the formats and init their support surface and data GrColorTypes.
711     // Format: VK_FORMAT_R8G8B8A8_UNORM
712     {
713         constexpr VkFormat format = VK_FORMAT_R8G8B8A8_UNORM;
714         auto& info = this->getFormatInfo(format);
715         info.init(interface, physDev, properties, format);
716         info.fBytesPerPixel = 4;
717         if (SkToBool(info.fOptimalFlags & FormatInfo::kTexturable_Flag)) {
718             info.fColorTypeInfoCount = 2;
719             info.fColorTypeInfos.reset(new ColorTypeInfo[info.fColorTypeInfoCount]());
720             int ctIdx = 0;
721             // Format: VK_FORMAT_R8G8B8A8_UNORM, Surface: kRGBA_8888
722             {
723                 constexpr GrColorType ct = GrColorType::kRGBA_8888;
724                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
725                 ctInfo.fColorType = ct;
726                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
727             }
728             // Format: VK_FORMAT_R8G8B8A8_UNORM, Surface: kRGB_888x
729             {
730                 constexpr GrColorType ct = GrColorType::kRGB_888x;
731                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
732                 ctInfo.fColorType = ct;
733                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag;
734                 ctInfo.fTextureSwizzle = GrSwizzle::RGB1();
735             }
736         }
737     }
738 
739     // Format: VK_FORMAT_R8_UNORM
740     {
741         constexpr VkFormat format = VK_FORMAT_R8_UNORM;
742         auto& info = this->getFormatInfo(format);
743         info.init(interface, physDev, properties, format);
744         info.fBytesPerPixel = 1;
745         if (SkToBool(info.fOptimalFlags & FormatInfo::kTexturable_Flag)) {
746             info.fColorTypeInfoCount = 2;
747             info.fColorTypeInfos.reset(new ColorTypeInfo[info.fColorTypeInfoCount]());
748             int ctIdx = 0;
749             // Format: VK_FORMAT_R8_UNORM, Surface: kAlpha_8
750             {
751                 constexpr GrColorType ct = GrColorType::kAlpha_8;
752                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
753                 ctInfo.fColorType = ct;
754                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
755                 ctInfo.fTextureSwizzle = GrSwizzle::RRRR();
756                 ctInfo.fOutputSwizzle = GrSwizzle::AAAA();
757             }
758             // Format: VK_FORMAT_R8_UNORM, Surface: kGray_8
759             {
760                 constexpr GrColorType ct = GrColorType::kGray_8;
761                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
762                 ctInfo.fColorType = ct;
763                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag;
764                 ctInfo.fTextureSwizzle = GrSwizzle("rrr1");
765             }
766         }
767     }
768     // Format: VK_FORMAT_B8G8R8A8_UNORM
769     {
770         constexpr VkFormat format = VK_FORMAT_B8G8R8A8_UNORM;
771         auto& info = this->getFormatInfo(format);
772         info.init(interface, physDev, properties, format);
773         info.fBytesPerPixel = 4;
774         if (SkToBool(info.fOptimalFlags & FormatInfo::kTexturable_Flag)) {
775             info.fColorTypeInfoCount = 1;
776             info.fColorTypeInfos.reset(new ColorTypeInfo[info.fColorTypeInfoCount]());
777             int ctIdx = 0;
778             // Format: VK_FORMAT_B8G8R8A8_UNORM, Surface: kBGRA_8888
779             {
780                 constexpr GrColorType ct = GrColorType::kBGRA_8888;
781                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
782                 ctInfo.fColorType = ct;
783                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
784             }
785         }
786     }
787     // Format: VK_FORMAT_R5G6B5_UNORM_PACK16
788     {
789         constexpr VkFormat format = VK_FORMAT_R5G6B5_UNORM_PACK16;
790         auto& info = this->getFormatInfo(format);
791         info.init(interface, physDev, properties, format);
792         info.fBytesPerPixel = 2;
793         if (SkToBool(info.fOptimalFlags & FormatInfo::kTexturable_Flag)) {
794             info.fColorTypeInfoCount = 1;
795             info.fColorTypeInfos.reset(new ColorTypeInfo[info.fColorTypeInfoCount]());
796             int ctIdx = 0;
797             // Format: VK_FORMAT_R5G6B5_UNORM_PACK16, Surface: kBGR_565
798             {
799                 constexpr GrColorType ct = GrColorType::kBGR_565;
800                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
801                 ctInfo.fColorType = ct;
802                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
803             }
804         }
805     }
806     // Format: VK_FORMAT_R16G16B16A16_SFLOAT
807     {
808         constexpr VkFormat format = VK_FORMAT_R16G16B16A16_SFLOAT;
809         auto& info = this->getFormatInfo(format);
810         info.init(interface, physDev, properties, format);
811         info.fBytesPerPixel = 8;
812         if (SkToBool(info.fOptimalFlags & FormatInfo::kTexturable_Flag)) {
813             info.fColorTypeInfoCount = 2;
814             info.fColorTypeInfos.reset(new ColorTypeInfo[info.fColorTypeInfoCount]());
815             int ctIdx = 0;
816             // Format: VK_FORMAT_R16G16B16A16_SFLOAT, Surface: GrColorType::kRGBA_F16
817             {
818                 constexpr GrColorType ct = GrColorType::kRGBA_F16;
819                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
820                 ctInfo.fColorType = ct;
821                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
822             }
823             // Format: VK_FORMAT_R16G16B16A16_SFLOAT, Surface: GrColorType::kRGBA_F16_Clamped
824             {
825                 constexpr GrColorType ct = GrColorType::kRGBA_F16_Clamped;
826                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
827                 ctInfo.fColorType = ct;
828                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
829             }
830         }
831     }
832     // Format: VK_FORMAT_R16_SFLOAT
833     {
834         constexpr VkFormat format = VK_FORMAT_R16_SFLOAT;
835         auto& info = this->getFormatInfo(format);
836         info.init(interface, physDev, properties, format);
837         info.fBytesPerPixel = 2;
838         if (SkToBool(info.fOptimalFlags & FormatInfo::kTexturable_Flag)) {
839             info.fColorTypeInfoCount = 1;
840             info.fColorTypeInfos.reset(new ColorTypeInfo[info.fColorTypeInfoCount]());
841             int ctIdx = 0;
842             // Format: VK_FORMAT_R16_SFLOAT, Surface: kAlpha_F16
843             {
844                 constexpr GrColorType ct = GrColorType::kAlpha_F16;
845                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
846                 ctInfo.fColorType = ct;
847                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
848                 ctInfo.fTextureSwizzle = GrSwizzle::RRRR();
849                 ctInfo.fOutputSwizzle = GrSwizzle::AAAA();
850             }
851         }
852     }
853     // Format: VK_FORMAT_R8G8B8_UNORM
854     {
855         constexpr VkFormat format = VK_FORMAT_R8G8B8_UNORM;
856         auto& info = this->getFormatInfo(format);
857         info.init(interface, physDev, properties, format);
858         info.fBytesPerPixel = 3;
859         if (SkToBool(info.fOptimalFlags & FormatInfo::kTexturable_Flag)) {
860             info.fColorTypeInfoCount = 1;
861             info.fColorTypeInfos.reset(new ColorTypeInfo[info.fColorTypeInfoCount]());
862             int ctIdx = 0;
863             // Format: VK_FORMAT_R8G8B8_UNORM, Surface: kRGB_888x
864             {
865                 constexpr GrColorType ct = GrColorType::kRGB_888x;
866                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
867                 ctInfo.fColorType = ct;
868                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
869             }
870         }
871     }
872     // Format: VK_FORMAT_R8G8_UNORM
873     {
874         constexpr VkFormat format = VK_FORMAT_R8G8_UNORM;
875         auto& info = this->getFormatInfo(format);
876         info.init(interface, physDev, properties, format);
877         info.fBytesPerPixel = 2;
878         if (SkToBool(info.fOptimalFlags & FormatInfo::kTexturable_Flag)) {
879             info.fColorTypeInfoCount = 1;
880             info.fColorTypeInfos.reset(new ColorTypeInfo[info.fColorTypeInfoCount]());
881             int ctIdx = 0;
882             // Format: VK_FORMAT_R8G8_UNORM, Surface: kRG_88
883             {
884                 constexpr GrColorType ct = GrColorType::kRG_88;
885                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
886                 ctInfo.fColorType = ct;
887                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
888             }
889         }
890     }
891     // Format: VK_FORMAT_A2B10G10R10_UNORM_PACK32
892     {
893         constexpr VkFormat format = VK_FORMAT_A2B10G10R10_UNORM_PACK32;
894         auto& info = this->getFormatInfo(format);
895         info.init(interface, physDev, properties, format);
896         info.fBytesPerPixel = 4;
897         if (SkToBool(info.fOptimalFlags & FormatInfo::kTexturable_Flag)) {
898             info.fColorTypeInfoCount = 1;
899             info.fColorTypeInfos.reset(new ColorTypeInfo[info.fColorTypeInfoCount]());
900             int ctIdx = 0;
901             // Format: VK_FORMAT_A2B10G10R10_UNORM_PACK32, Surface: kRGBA_1010102
902             {
903                 constexpr GrColorType ct = GrColorType::kRGBA_1010102;
904                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
905                 ctInfo.fColorType = ct;
906                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
907             }
908         }
909     }
910     // Format: VK_FORMAT_B4G4R4A4_UNORM_PACK16
911     {
912         constexpr VkFormat format = VK_FORMAT_B4G4R4A4_UNORM_PACK16;
913         auto& info = this->getFormatInfo(format);
914         info.init(interface, physDev, properties, format);
915         info.fBytesPerPixel = 2;
916         if (SkToBool(info.fOptimalFlags & FormatInfo::kTexturable_Flag)) {
917             info.fColorTypeInfoCount = 1;
918             info.fColorTypeInfos.reset(new ColorTypeInfo[info.fColorTypeInfoCount]());
919             int ctIdx = 0;
920             // Format: VK_FORMAT_B4G4R4A4_UNORM_PACK16, Surface: kABGR_4444
921             {
922                 constexpr GrColorType ct = GrColorType::kABGR_4444;
923                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
924                 ctInfo.fColorType = ct;
925                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
926                 ctInfo.fTextureSwizzle = GrSwizzle::BGRA();
927                 ctInfo.fOutputSwizzle = GrSwizzle::BGRA();
928             }
929         }
930     }
931     // Format: VK_FORMAT_R4G4B4A4_UNORM_PACK16
932     {
933         constexpr VkFormat format = VK_FORMAT_R4G4B4A4_UNORM_PACK16;
934         auto& info = this->getFormatInfo(format);
935         info.init(interface, physDev, properties, format);
936         info.fBytesPerPixel = 2;
937         if (SkToBool(info.fOptimalFlags & FormatInfo::kTexturable_Flag)) {
938             info.fColorTypeInfoCount = 1;
939             info.fColorTypeInfos.reset(new ColorTypeInfo[info.fColorTypeInfoCount]());
940             int ctIdx = 0;
941             // Format: VK_FORMAT_R4G4B4A4_UNORM_PACK16, Surface: kABGR_4444
942             {
943                 constexpr GrColorType ct = GrColorType::kABGR_4444;
944                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
945                 ctInfo.fColorType = ct;
946                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
947             }
948         }
949     }
950     // Format: VK_FORMAT_R8G8B8A8_SRGB
951     {
952         constexpr VkFormat format = VK_FORMAT_R8G8B8A8_SRGB;
953         auto& info = this->getFormatInfo(format);
954         info.init(interface, physDev, properties, format);
955         info.fBytesPerPixel = 4;
956         if (SkToBool(info.fOptimalFlags & FormatInfo::kTexturable_Flag)) {
957             info.fColorTypeInfoCount = 1;
958             info.fColorTypeInfos.reset(new ColorTypeInfo[info.fColorTypeInfoCount]());
959             int ctIdx = 0;
960             // Format: VK_FORMAT_R8G8B8A8_SRGB, Surface: kRGBA_8888_SRGB
961             {
962                 constexpr GrColorType ct = GrColorType::kRGBA_8888_SRGB;
963                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
964                 ctInfo.fColorType = ct;
965                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
966             }
967         }
968     }
969     // Format: VK_FORMAT_R16_UNORM
970     {
971         constexpr VkFormat format = VK_FORMAT_R16_UNORM;
972         auto& info = this->getFormatInfo(format);
973         info.init(interface, physDev, properties, format);
974         info.fBytesPerPixel = 2;
975         if (SkToBool(info.fOptimalFlags & FormatInfo::kTexturable_Flag)) {
976             info.fColorTypeInfoCount = 1;
977             info.fColorTypeInfos.reset(new ColorTypeInfo[info.fColorTypeInfoCount]());
978             int ctIdx = 0;
979             // Format: VK_FORMAT_R16_UNORM, Surface: kAlpha_16
980             {
981                 constexpr GrColorType ct = GrColorType::kAlpha_16;
982                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
983                 ctInfo.fColorType = ct;
984                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
985                 ctInfo.fTextureSwizzle = GrSwizzle::RRRR();
986                 ctInfo.fOutputSwizzle = GrSwizzle::AAAA();
987             }
988         }
989     }
990     // Format: VK_FORMAT_R16G16_UNORM
991     {
992         constexpr VkFormat format = VK_FORMAT_R16G16_UNORM;
993         auto& info = this->getFormatInfo(format);
994         info.init(interface, physDev, properties, format);
995         info.fBytesPerPixel = 4;
996         if (SkToBool(info.fOptimalFlags & FormatInfo::kTexturable_Flag)) {
997             info.fColorTypeInfoCount = 1;
998             info.fColorTypeInfos.reset(new ColorTypeInfo[info.fColorTypeInfoCount]());
999             int ctIdx = 0;
1000             // Format: VK_FORMAT_R16G16_UNORM, Surface: kRG_1616
1001             {
1002                 constexpr GrColorType ct = GrColorType::kRG_1616;
1003                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
1004                 ctInfo.fColorType = ct;
1005                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
1006             }
1007         }
1008     }
1009     // Format: VK_FORMAT_R16G16B16A16_UNORM
1010     {
1011         constexpr VkFormat format = VK_FORMAT_R16G16B16A16_UNORM;
1012         auto& info = this->getFormatInfo(format);
1013         info.init(interface, physDev, properties, format);
1014         info.fBytesPerPixel = 8;
1015         if (SkToBool(info.fOptimalFlags & FormatInfo::kTexturable_Flag)) {
1016             info.fColorTypeInfoCount = 1;
1017             info.fColorTypeInfos.reset(new ColorTypeInfo[info.fColorTypeInfoCount]());
1018             int ctIdx = 0;
1019             // Format: VK_FORMAT_R16G16B16A16_UNORM, Surface: kRGBA_16161616
1020             {
1021                 constexpr GrColorType ct = GrColorType::kRGBA_16161616;
1022                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
1023                 ctInfo.fColorType = ct;
1024                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
1025             }
1026         }
1027     }
1028     // Format: VK_FORMAT_R16G16_SFLOAT
1029     {
1030         constexpr VkFormat format = VK_FORMAT_R16G16_SFLOAT;
1031         auto& info = this->getFormatInfo(format);
1032         info.init(interface, physDev, properties, format);
1033         info.fBytesPerPixel = 4;
1034         if (SkToBool(info.fOptimalFlags & FormatInfo::kTexturable_Flag)) {
1035             info.fColorTypeInfoCount = 1;
1036             info.fColorTypeInfos.reset(new ColorTypeInfo[info.fColorTypeInfoCount]());
1037             int ctIdx = 0;
1038             // Format: VK_FORMAT_R16G16_SFLOAT, Surface: kRG_F16
1039             {
1040                 constexpr GrColorType ct = GrColorType::kRG_F16;
1041                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
1042                 ctInfo.fColorType = ct;
1043                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
1044             }
1045         }
1046     }
1047     // Format: VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM
1048     {
1049         constexpr VkFormat format = VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM;
1050         auto& info = this->getFormatInfo(format);
1051         // Currently we are just over estimating this value to be used in gpu size calculations even
1052         // though the actually size is probably less. We should instead treat planar formats similar
1053         // to compressed textures that go through their own special query for calculating size.
1054         info.fBytesPerPixel = 3;
1055         if (fSupportsYcbcrConversion) {
1056             info.init(interface, physDev, properties, format);
1057         }
1058         if (SkToBool(info.fOptimalFlags & FormatInfo::kTexturable_Flag)) {
1059             info.fColorTypeInfoCount = 1;
1060             info.fColorTypeInfos.reset(new ColorTypeInfo[info.fColorTypeInfoCount]());
1061             int ctIdx = 0;
1062             // Format: VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM, Surface: kRGB_888x
1063             {
1064                 constexpr GrColorType ct = GrColorType::kRGB_888x;
1065                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
1066                 ctInfo.fColorType = ct;
1067                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kWrappedOnly_Flag;
1068             }
1069         }
1070     }
1071     // Format: VK_FORMAT_G8_B8R8_2PLANE_420_UNORM
1072     {
1073         constexpr VkFormat format = VK_FORMAT_G8_B8R8_2PLANE_420_UNORM;
1074         auto& info = this->getFormatInfo(format);
1075         // Currently we are just over estimating this value to be used in gpu size calculations even
1076         // though the actually size is probably less. We should instead treat planar formats similar
1077         // to compressed textures that go through their own special query for calculating size.
1078         info.fBytesPerPixel = 3;
1079         if (fSupportsYcbcrConversion) {
1080             info.init(interface, physDev, properties, format);
1081         }
1082         if (SkToBool(info.fOptimalFlags & FormatInfo::kTexturable_Flag)) {
1083             info.fColorTypeInfoCount = 1;
1084             info.fColorTypeInfos.reset(new ColorTypeInfo[info.fColorTypeInfoCount]());
1085             int ctIdx = 0;
1086             // Format: VK_FORMAT_G8_B8R8_2PLANE_420_UNORM, Surface: kRGB_888x
1087             {
1088                 constexpr GrColorType ct = GrColorType::kRGB_888x;
1089                 auto& ctInfo = info.fColorTypeInfos[ctIdx++];
1090                 ctInfo.fColorType = ct;
1091                 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kWrappedOnly_Flag;
1092             }
1093         }
1094     }
1095     // Format: VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK
1096     {
1097         constexpr VkFormat format = VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK;
1098         auto& info = this->getFormatInfo(format);
1099         info.init(interface, physDev, properties, format);
1100         info.fBytesPerPixel = 0;
1101         // No supported GrColorTypes.
1102     }
1103 
1104     ////////////////////////////////////////////////////////////////////////////
1105     // Map GrColorTypes (used for creating GrSurfaces) to VkFormats. The order in which the formats
1106     // are passed into the setColorType function indicates the priority in selecting which format
1107     // we use for a given GrcolorType.
1108 
1109     this->setColorType(GrColorType::kAlpha_8,          { VK_FORMAT_R8_UNORM });
1110     this->setColorType(GrColorType::kBGR_565,          { VK_FORMAT_R5G6B5_UNORM_PACK16 });
1111     this->setColorType(GrColorType::kABGR_4444,        { VK_FORMAT_R4G4B4A4_UNORM_PACK16,
1112                                                          VK_FORMAT_B4G4R4A4_UNORM_PACK16 });
1113     this->setColorType(GrColorType::kRGBA_8888,        { VK_FORMAT_R8G8B8A8_UNORM });
1114     this->setColorType(GrColorType::kRGBA_8888_SRGB,   { VK_FORMAT_R8G8B8A8_SRGB });
1115     this->setColorType(GrColorType::kRGB_888x,         { VK_FORMAT_R8G8B8_UNORM,
1116                                                          VK_FORMAT_R8G8B8A8_UNORM });
1117     this->setColorType(GrColorType::kRG_88,            { VK_FORMAT_R8G8_UNORM });
1118     this->setColorType(GrColorType::kBGRA_8888,        { VK_FORMAT_B8G8R8A8_UNORM });
1119     this->setColorType(GrColorType::kRGBA_1010102,     { VK_FORMAT_A2B10G10R10_UNORM_PACK32 });
1120     this->setColorType(GrColorType::kGray_8,           { VK_FORMAT_R8_UNORM });
1121     this->setColorType(GrColorType::kAlpha_F16,        { VK_FORMAT_R16_SFLOAT });
1122     this->setColorType(GrColorType::kRGBA_F16,         { VK_FORMAT_R16G16B16A16_SFLOAT });
1123     this->setColorType(GrColorType::kRGBA_F16_Clamped, { VK_FORMAT_R16G16B16A16_SFLOAT });
1124     this->setColorType(GrColorType::kAlpha_16,         { VK_FORMAT_R16_UNORM });
1125     this->setColorType(GrColorType::kRG_1616,          { VK_FORMAT_R16G16_UNORM });
1126     this->setColorType(GrColorType::kRGBA_16161616,    { VK_FORMAT_R16G16B16A16_UNORM });
1127     this->setColorType(GrColorType::kRG_F16,           { VK_FORMAT_R16G16_SFLOAT });
1128 }
1129 
InitFormatFlags(VkFormatFeatureFlags vkFlags,uint16_t * flags)1130 void GrVkCaps::FormatInfo::InitFormatFlags(VkFormatFeatureFlags vkFlags, uint16_t* flags) {
1131     if (SkToBool(VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT & vkFlags) &&
1132         SkToBool(VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT & vkFlags)) {
1133         *flags = *flags | kTexturable_Flag;
1134 
1135         // Ganesh assumes that all renderable surfaces are also texturable
1136         if (SkToBool(VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT & vkFlags)) {
1137             *flags = *flags | kRenderable_Flag;
1138         }
1139     }
1140 
1141     if (SkToBool(VK_FORMAT_FEATURE_BLIT_SRC_BIT & vkFlags)) {
1142         *flags = *flags | kBlitSrc_Flag;
1143     }
1144 
1145     if (SkToBool(VK_FORMAT_FEATURE_BLIT_DST_BIT & vkFlags)) {
1146         *flags = *flags | kBlitDst_Flag;
1147     }
1148 }
1149 
initSampleCounts(const GrVkInterface * interface,VkPhysicalDevice physDev,const VkPhysicalDeviceProperties & physProps,VkFormat format)1150 void GrVkCaps::FormatInfo::initSampleCounts(const GrVkInterface* interface,
1151                                             VkPhysicalDevice physDev,
1152                                             const VkPhysicalDeviceProperties& physProps,
1153                                             VkFormat format) {
1154     VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
1155                               VK_IMAGE_USAGE_TRANSFER_DST_BIT |
1156                               VK_IMAGE_USAGE_SAMPLED_BIT |
1157                               VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
1158     VkImageFormatProperties properties;
1159     GR_VK_CALL(interface, GetPhysicalDeviceImageFormatProperties(physDev,
1160                                                                  format,
1161                                                                  VK_IMAGE_TYPE_2D,
1162                                                                  VK_IMAGE_TILING_OPTIMAL,
1163                                                                  usage,
1164                                                                  0,  // createFlags
1165                                                                  &properties));
1166     VkSampleCountFlags flags = properties.sampleCounts;
1167     if (flags & VK_SAMPLE_COUNT_1_BIT) {
1168         fColorSampleCounts.push_back(1);
1169     }
1170     if (kImagination_VkVendor == physProps.vendorID) {
1171         // MSAA does not work on imagination
1172         return;
1173     }
1174     if (kIntel_VkVendor == physProps.vendorID) {
1175         // MSAA doesn't work well on Intel GPUs chromium:527565, chromium:983926
1176         return;
1177     }
1178     if (flags & VK_SAMPLE_COUNT_2_BIT) {
1179         fColorSampleCounts.push_back(2);
1180     }
1181     if (flags & VK_SAMPLE_COUNT_4_BIT) {
1182         fColorSampleCounts.push_back(4);
1183     }
1184     if (flags & VK_SAMPLE_COUNT_8_BIT) {
1185         fColorSampleCounts.push_back(8);
1186     }
1187     if (flags & VK_SAMPLE_COUNT_16_BIT) {
1188         fColorSampleCounts.push_back(16);
1189     }
1190     if (flags & VK_SAMPLE_COUNT_32_BIT) {
1191         fColorSampleCounts.push_back(32);
1192     }
1193     if (flags & VK_SAMPLE_COUNT_64_BIT) {
1194         fColorSampleCounts.push_back(64);
1195     }
1196 }
1197 
init(const GrVkInterface * interface,VkPhysicalDevice physDev,const VkPhysicalDeviceProperties & properties,VkFormat format)1198 void GrVkCaps::FormatInfo::init(const GrVkInterface* interface,
1199                                 VkPhysicalDevice physDev,
1200                                 const VkPhysicalDeviceProperties& properties,
1201                                 VkFormat format) {
1202     VkFormatProperties props;
1203     memset(&props, 0, sizeof(VkFormatProperties));
1204     GR_VK_CALL(interface, GetPhysicalDeviceFormatProperties(physDev, format, &props));
1205     InitFormatFlags(props.linearTilingFeatures, &fLinearFlags);
1206     InitFormatFlags(props.optimalTilingFeatures, &fOptimalFlags);
1207     if (fOptimalFlags & kRenderable_Flag) {
1208         this->initSampleCounts(interface, physDev, properties, format);
1209     }
1210 }
1211 
1212 // For many checks in caps, we need to know whether the GrBackendFormat is external or not. If it is
1213 // external the VkFormat will be VK_NULL_HANDLE which is not handled by our various format
1214 // capability checks.
backend_format_is_external(const GrBackendFormat & format)1215 static bool backend_format_is_external(const GrBackendFormat& format) {
1216     const GrVkYcbcrConversionInfo* ycbcrInfo = format.getVkYcbcrConversionInfo();
1217     SkASSERT(ycbcrInfo);
1218 
1219     // All external formats have a valid ycbcrInfo used for sampling and a non zero external format.
1220     if (ycbcrInfo->isValid() && ycbcrInfo->fExternalFormat != 0) {
1221 #ifdef SK_DEBUG
1222         VkFormat vkFormat;
1223         SkAssertResult(format.asVkFormat(&vkFormat));
1224         SkASSERT(vkFormat == VK_NULL_HANDLE);
1225 #endif
1226         return true;
1227     }
1228     return false;
1229 }
1230 
isFormatSRGB(const GrBackendFormat & format) const1231 bool GrVkCaps::isFormatSRGB(const GrBackendFormat& format) const {
1232     VkFormat vkFormat;
1233     if (!format.asVkFormat(&vkFormat)) {
1234         return false;
1235     }
1236     if (backend_format_is_external(format)) {
1237         return false;
1238     }
1239 
1240     return format_is_srgb(vkFormat);
1241 }
1242 
isFormatCompressed(const GrBackendFormat & format,SkImage::CompressionType * compressionType) const1243 bool GrVkCaps::isFormatCompressed(const GrBackendFormat& format,
1244                                   SkImage::CompressionType* compressionType) const {
1245     VkFormat vkFormat;
1246     if (!format.asVkFormat(&vkFormat)) {
1247         return false;
1248     }
1249     SkImage::CompressionType dummyType;
1250     SkImage::CompressionType* compressionTypePtr = compressionType ? compressionType : &dummyType;
1251 
1252     switch (vkFormat) {
1253         case VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK:
1254             // ETC2 uses the same compression layout as ETC1
1255             *compressionTypePtr = SkImage::kETC1_CompressionType;
1256             return true;
1257         default:
1258             return false;
1259     }
1260 }
1261 
isFormatTexturableAndUploadable(GrColorType ct,const GrBackendFormat & format) const1262 bool GrVkCaps::isFormatTexturableAndUploadable(GrColorType ct,
1263                                                const GrBackendFormat& format) const {
1264     VkFormat vkFormat;
1265     if (!format.asVkFormat(&vkFormat)) {
1266         return false;
1267     }
1268 
1269     uint32_t ctFlags = this->getFormatInfo(vkFormat).colorTypeFlags(ct);
1270     return this->isVkFormatTexturable(vkFormat) &&
1271            SkToBool(ctFlags & ColorTypeInfo::kUploadData_Flag);
1272 }
1273 
isFormatTexturable(const GrBackendFormat & format) const1274 bool GrVkCaps::isFormatTexturable(const GrBackendFormat& format) const {
1275     VkFormat vkFormat;
1276     if (!format.asVkFormat(&vkFormat)) {
1277         return false;
1278     }
1279     if (backend_format_is_external(format)) {
1280         // We can always texture from an external format (assuming we have the ycbcr conversion
1281         // info which we require to be passed in).
1282         return true;
1283     }
1284     return this->isVkFormatTexturable(vkFormat);
1285 }
1286 
isVkFormatTexturable(VkFormat format) const1287 bool GrVkCaps::isVkFormatTexturable(VkFormat format) const {
1288     const FormatInfo& info = this->getFormatInfo(format);
1289     return SkToBool(FormatInfo::kTexturable_Flag & info.fOptimalFlags);
1290 }
1291 
isFormatAsColorTypeRenderable(GrColorType ct,const GrBackendFormat & format,int sampleCount) const1292 bool GrVkCaps::isFormatAsColorTypeRenderable(GrColorType ct, const GrBackendFormat& format,
1293                                              int sampleCount) const {
1294     if (!this->isFormatRenderable(format, sampleCount)) {
1295         return false;
1296     }
1297     VkFormat vkFormat;
1298     if (!format.asVkFormat(&vkFormat)) {
1299         return false;
1300     }
1301     const auto& info = this->getFormatInfo(vkFormat);
1302     if (!SkToBool(info.colorTypeFlags(ct) & ColorTypeInfo::kRenderable_Flag)) {
1303         return false;
1304     }
1305     return true;
1306 }
1307 
isFormatRenderable(const GrBackendFormat & format,int sampleCount) const1308 bool GrVkCaps::isFormatRenderable(const GrBackendFormat& format, int sampleCount) const {
1309     VkFormat vkFormat;
1310     if (!format.asVkFormat(&vkFormat)) {
1311         return false;
1312     }
1313     return this->isFormatRenderable(vkFormat, sampleCount);
1314 }
1315 
isFormatRenderable(VkFormat format,int sampleCount) const1316 bool GrVkCaps::isFormatRenderable(VkFormat format, int sampleCount) const {
1317     return sampleCount <= this->maxRenderTargetSampleCount(format);
1318 }
1319 
getRenderTargetSampleCount(int requestedCount,const GrBackendFormat & format) const1320 int GrVkCaps::getRenderTargetSampleCount(int requestedCount,
1321                                          const GrBackendFormat& format) const {
1322     VkFormat vkFormat;
1323     if (!format.asVkFormat(&vkFormat)) {
1324         return 0;
1325     }
1326 
1327     return this->getRenderTargetSampleCount(requestedCount, vkFormat);
1328 }
1329 
getRenderTargetSampleCount(int requestedCount,VkFormat format) const1330 int GrVkCaps::getRenderTargetSampleCount(int requestedCount, VkFormat format) const {
1331     requestedCount = SkTMax(1, requestedCount);
1332 
1333     const FormatInfo& info = this->getFormatInfo(format);
1334 
1335     int count = info.fColorSampleCounts.count();
1336 
1337     if (!count) {
1338         return 0;
1339     }
1340 
1341     if (1 == requestedCount) {
1342         SkASSERT(info.fColorSampleCounts.count() && info.fColorSampleCounts[0] == 1);
1343         return 1;
1344     }
1345 
1346     for (int i = 0; i < count; ++i) {
1347         if (info.fColorSampleCounts[i] >= requestedCount) {
1348             return info.fColorSampleCounts[i];
1349         }
1350     }
1351     return 0;
1352 }
1353 
maxRenderTargetSampleCount(const GrBackendFormat & format) const1354 int GrVkCaps::maxRenderTargetSampleCount(const GrBackendFormat& format) const {
1355     VkFormat vkFormat;
1356     if (!format.asVkFormat(&vkFormat)) {
1357         return 0;
1358     }
1359     return this->maxRenderTargetSampleCount(vkFormat);
1360 }
1361 
maxRenderTargetSampleCount(VkFormat format) const1362 int GrVkCaps::maxRenderTargetSampleCount(VkFormat format) const {
1363     const FormatInfo& info = this->getFormatInfo(format);
1364 
1365     const auto& table = info.fColorSampleCounts;
1366     if (!table.count()) {
1367         return 0;
1368     }
1369     return table[table.count() - 1];
1370 }
1371 
bytesPerPixel(const GrBackendFormat & format) const1372 size_t GrVkCaps::bytesPerPixel(const GrBackendFormat& format) const {
1373     VkFormat vkFormat;
1374     if (!format.asVkFormat(&vkFormat)) {
1375         return 0;
1376     }
1377     return this->bytesPerPixel(vkFormat);
1378 }
1379 
bytesPerPixel(VkFormat format) const1380 size_t GrVkCaps::bytesPerPixel(VkFormat format) const {
1381     return this->getFormatInfo(format).fBytesPerPixel;
1382 }
1383 
align_to_4(size_t v)1384 static inline size_t align_to_4(size_t v) {
1385     switch (v & 0b11) {
1386         // v is already a multiple of 4.
1387         case 0:     return v;
1388         // v is a multiple of 2 but not 4.
1389         case 2:     return 2 * v;
1390         // v is not a multiple of 2.
1391         default:    return 4 * v;
1392     }
1393 }
1394 
supportedWritePixelsColorType(GrColorType surfaceColorType,const GrBackendFormat & surfaceFormat,GrColorType srcColorType) const1395 GrCaps::SupportedWrite GrVkCaps::supportedWritePixelsColorType(GrColorType surfaceColorType,
1396                                                                const GrBackendFormat& surfaceFormat,
1397                                                                GrColorType srcColorType) const {
1398     VkFormat vkFormat;
1399     if (!surfaceFormat.asVkFormat(&vkFormat)) {
1400         return {GrColorType::kUnknown, 0};
1401     }
1402 
1403     // We don't support the ability to upload to external formats or formats that require a ycbcr
1404     // sampler. In general these types of formats are only used for sampling in a shader.
1405     if (backend_format_is_external(surfaceFormat) || GrVkFormatNeedsYcbcrSampler(vkFormat)) {
1406         return {GrColorType::kUnknown, 0};
1407     }
1408 
1409     // The VkBufferImageCopy bufferOffset field must be both a multiple of 4 and of a single texel.
1410     size_t offsetAlignment = align_to_4(this->bytesPerPixel(vkFormat));
1411 
1412     const auto& info = this->getFormatInfo(vkFormat);
1413     for (int i = 0; i < info.fColorTypeInfoCount; ++i) {
1414         const auto& ctInfo = info.fColorTypeInfos[i];
1415         if (ctInfo.fColorType == surfaceColorType) {
1416             return {surfaceColorType, offsetAlignment};
1417         }
1418     }
1419     return {GrColorType::kUnknown, 0};
1420 }
1421 
surfaceSupportsReadPixels(const GrSurface * surface) const1422 GrCaps::SurfaceReadPixelsSupport GrVkCaps::surfaceSupportsReadPixels(
1423         const GrSurface* surface) const {
1424     if (surface->isProtected()) {
1425         return SurfaceReadPixelsSupport::kUnsupported;
1426     }
1427     if (auto tex = static_cast<const GrVkTexture*>(surface->asTexture())) {
1428         // We can't directly read from a VkImage that has a ycbcr sampler.
1429         if (tex->ycbcrConversionInfo().isValid()) {
1430             return SurfaceReadPixelsSupport::kCopyToTexture2D;
1431         }
1432         // We can't directly read from a compressed format
1433         SkImage::CompressionType compressionType;
1434         if (GrVkFormatToCompressionType(tex->imageFormat(), &compressionType)) {
1435             return SurfaceReadPixelsSupport::kCopyToTexture2D;
1436         }
1437     }
1438     return SurfaceReadPixelsSupport::kSupported;
1439 }
1440 
onSurfaceSupportsWritePixels(const GrSurface * surface) const1441 bool GrVkCaps::onSurfaceSupportsWritePixels(const GrSurface* surface) const {
1442     if (auto rt = surface->asRenderTarget()) {
1443         return rt->numSamples() <= 1 && SkToBool(surface->asTexture());
1444     }
1445     // We can't write to a texture that has a ycbcr sampler.
1446     if (auto tex = static_cast<const GrVkTexture*>(surface->asTexture())) {
1447         // We can't directly read from a VkImage that has a ycbcr sampler.
1448         if (tex->ycbcrConversionInfo().isValid()) {
1449             return false;
1450         }
1451     }
1452     return true;
1453 }
1454 
onAreColorTypeAndFormatCompatible(GrColorType ct,const GrBackendFormat & format) const1455 bool GrVkCaps::onAreColorTypeAndFormatCompatible(GrColorType ct,
1456                                                  const GrBackendFormat& format) const {
1457     VkFormat vkFormat;
1458     if (!format.asVkFormat(&vkFormat)) {
1459         return false;
1460     }
1461     const GrVkYcbcrConversionInfo* ycbcrInfo = format.getVkYcbcrConversionInfo();
1462     SkASSERT(ycbcrInfo);
1463 
1464     if (ycbcrInfo->isValid() && !GrVkFormatNeedsYcbcrSampler(vkFormat)) {
1465         // Format may be undefined for external images, which are required to have YCbCr conversion.
1466         if (VK_FORMAT_UNDEFINED == vkFormat && ycbcrInfo->fExternalFormat != 0) {
1467             return true;
1468         }
1469         return false;
1470     }
1471 
1472     const auto& info = this->getFormatInfo(vkFormat);
1473     for (int i = 0; i < info.fColorTypeInfoCount; ++i) {
1474         if (info.fColorTypeInfos[i].fColorType == ct) {
1475             return true;
1476         }
1477     }
1478     return false;
1479 }
1480 
validate_image_info(VkFormat format,GrColorType ct,bool hasYcbcrConversion)1481 static GrPixelConfig validate_image_info(VkFormat format, GrColorType ct, bool hasYcbcrConversion) {
1482     if (hasYcbcrConversion) {
1483         if (GrVkFormatNeedsYcbcrSampler(format)) {
1484             return kRGB_888X_GrPixelConfig;
1485         }
1486 
1487         // Format may be undefined for external images, which are required to have YCbCr conversion.
1488         if (VK_FORMAT_UNDEFINED == format) {
1489             // We don't actually care what the color type or config are since we won't use those
1490             // values for external textures. However, for read pixels we will draw to a non ycbcr
1491             // texture of this config so we set RGBA here for that.
1492             return kRGBA_8888_GrPixelConfig;
1493         }
1494 
1495         return kUnknown_GrPixelConfig;
1496     }
1497 
1498     if (VK_FORMAT_UNDEFINED == format) {
1499         return kUnknown_GrPixelConfig;
1500     }
1501 
1502     switch (ct) {
1503         case GrColorType::kUnknown:
1504             break;
1505         case GrColorType::kAlpha_8:
1506             if (VK_FORMAT_R8_UNORM == format) {
1507                 return kAlpha_8_as_Red_GrPixelConfig;
1508             }
1509             break;
1510         case GrColorType::kBGR_565:
1511             if (VK_FORMAT_R5G6B5_UNORM_PACK16 == format) {
1512                 return kRGB_565_GrPixelConfig;
1513             }
1514             break;
1515         case GrColorType::kABGR_4444:
1516             if (VK_FORMAT_B4G4R4A4_UNORM_PACK16 == format ||
1517                 VK_FORMAT_R4G4B4A4_UNORM_PACK16 == format) {
1518                 return kRGBA_4444_GrPixelConfig;
1519             }
1520             break;
1521         case GrColorType::kRGBA_8888:
1522             if (VK_FORMAT_R8G8B8A8_UNORM == format) {
1523                 return kRGBA_8888_GrPixelConfig;
1524             }
1525             break;
1526         case GrColorType::kRGBA_8888_SRGB:
1527             if (VK_FORMAT_R8G8B8A8_SRGB == format) {
1528                 return kSRGBA_8888_GrPixelConfig;
1529             }
1530             break;
1531         case GrColorType::kRGB_888x:
1532             if (VK_FORMAT_R8G8B8_UNORM == format) {
1533                 return kRGB_888_GrPixelConfig;
1534             } else if (VK_FORMAT_R8G8B8A8_UNORM == format) {
1535                 return kRGB_888X_GrPixelConfig;
1536             } else if (VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK == format) {
1537                 return kRGB_ETC1_GrPixelConfig;
1538             }
1539             break;
1540         case GrColorType::kRG_88:
1541             if (VK_FORMAT_R8G8_UNORM == format) {
1542                 return kRG_88_GrPixelConfig;
1543             }
1544             break;
1545         case GrColorType::kBGRA_8888:
1546             if (VK_FORMAT_B8G8R8A8_UNORM == format) {
1547                 return kBGRA_8888_GrPixelConfig;
1548             }
1549             break;
1550         case GrColorType::kRGBA_1010102:
1551             if (VK_FORMAT_A2B10G10R10_UNORM_PACK32 == format) {
1552                 return kRGBA_1010102_GrPixelConfig;
1553             }
1554             break;
1555         case GrColorType::kGray_8:
1556             if (VK_FORMAT_R8_UNORM == format) {
1557                 return kGray_8_as_Red_GrPixelConfig;
1558             }
1559             break;
1560         case GrColorType::kAlpha_F16:
1561             if (VK_FORMAT_R16_SFLOAT == format) {
1562                 return kAlpha_half_as_Red_GrPixelConfig;
1563             }
1564             break;
1565         case GrColorType::kRGBA_F16:
1566             if (VK_FORMAT_R16G16B16A16_SFLOAT == format) {
1567                 return kRGBA_half_GrPixelConfig;
1568             }
1569             break;
1570         case GrColorType::kRGBA_F16_Clamped:
1571             if (VK_FORMAT_R16G16B16A16_SFLOAT == format) {
1572                 return kRGBA_half_Clamped_GrPixelConfig;
1573             }
1574             break;
1575         case GrColorType::kAlpha_16:
1576             if (VK_FORMAT_R16_UNORM == format) {
1577                 return kAlpha_16_GrPixelConfig;
1578             }
1579             break;
1580         case GrColorType::kRG_1616:
1581             if (VK_FORMAT_R16G16_UNORM == format) {
1582                 return kRG_1616_GrPixelConfig;
1583             }
1584             break;
1585         case GrColorType::kRGBA_16161616:
1586             if (VK_FORMAT_R16G16B16A16_UNORM == format) {
1587                 return kRGBA_16161616_GrPixelConfig;
1588             }
1589             break;
1590         case GrColorType::kRG_F16:
1591             if (VK_FORMAT_R16G16_SFLOAT == format) {
1592                 return kRG_half_GrPixelConfig;
1593             }
1594             break;
1595         // These have no equivalent:
1596         case GrColorType::kRGBA_F32:
1597         case GrColorType::kAlpha_8xxx:
1598         case GrColorType::kAlpha_F32xxx:
1599         case GrColorType::kGray_8xxx:
1600             break;
1601     }
1602 
1603     return kUnknown_GrPixelConfig;
1604 }
1605 
onGetConfigFromBackendFormat(const GrBackendFormat & format,GrColorType ct) const1606 GrPixelConfig GrVkCaps::onGetConfigFromBackendFormat(const GrBackendFormat& format,
1607                                                      GrColorType ct) const {
1608     VkFormat vkFormat;
1609     if (!format.asVkFormat(&vkFormat)) {
1610         return kUnknown_GrPixelConfig;
1611     }
1612     const GrVkYcbcrConversionInfo* ycbcrInfo = format.getVkYcbcrConversionInfo();
1613     SkASSERT(ycbcrInfo);
1614     return validate_image_info(vkFormat, ct, ycbcrInfo->isValid());
1615 }
1616 
getYUVAColorTypeFromBackendFormat(const GrBackendFormat & format,bool isAlphaChannel) const1617 GrColorType GrVkCaps::getYUVAColorTypeFromBackendFormat(const GrBackendFormat& format,
1618                                                         bool isAlphaChannel) const {
1619     VkFormat vkFormat;
1620     if (!format.asVkFormat(&vkFormat)) {
1621         return GrColorType::kUnknown;
1622     }
1623 
1624     switch (vkFormat) {
1625         case VK_FORMAT_R8_UNORM:                 return isAlphaChannel ? GrColorType::kAlpha_8
1626                                                                        : GrColorType::kGray_8;
1627         case VK_FORMAT_R8G8B8A8_UNORM:           return GrColorType::kRGBA_8888;
1628         case VK_FORMAT_R8G8B8_UNORM:             return GrColorType::kRGB_888x;
1629         case VK_FORMAT_R8G8_UNORM:               return GrColorType::kRG_88;
1630         case VK_FORMAT_B8G8R8A8_UNORM:           return GrColorType::kBGRA_8888;
1631         case VK_FORMAT_A2B10G10R10_UNORM_PACK32: return GrColorType::kRGBA_1010102;
1632         case VK_FORMAT_R16_UNORM:                return GrColorType::kAlpha_16;
1633         case VK_FORMAT_R16_SFLOAT:               return GrColorType::kAlpha_F16;
1634         case VK_FORMAT_R16G16_UNORM:             return GrColorType::kRG_1616;
1635         case VK_FORMAT_R16G16B16A16_UNORM:       return GrColorType::kRGBA_16161616;
1636         case VK_FORMAT_R16G16_SFLOAT:            return GrColorType::kRG_F16;
1637         default:                                 return GrColorType::kUnknown;
1638     }
1639 
1640     SkUNREACHABLE;
1641 }
1642 
onGetDefaultBackendFormat(GrColorType ct,GrRenderable renderable) const1643 GrBackendFormat GrVkCaps::onGetDefaultBackendFormat(GrColorType ct,
1644                                                     GrRenderable renderable) const {
1645     VkFormat format = this->getFormatFromColorType(ct);
1646     if (format == VK_FORMAT_UNDEFINED) {
1647         return GrBackendFormat();
1648     }
1649     return GrBackendFormat::MakeVk(format);
1650 }
1651 
getBackendFormatFromCompressionType(SkImage::CompressionType compressionType) const1652 GrBackendFormat GrVkCaps::getBackendFormatFromCompressionType(
1653         SkImage::CompressionType compressionType) const {
1654     switch (compressionType) {
1655         case SkImage::kETC1_CompressionType:
1656             return GrBackendFormat::MakeVk(VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK);
1657     }
1658     SK_ABORT("Invalid compression type");
1659 }
1660 
getTextureSwizzle(const GrBackendFormat & format,GrColorType colorType) const1661 GrSwizzle GrVkCaps::getTextureSwizzle(const GrBackendFormat& format, GrColorType colorType) const {
1662     VkFormat vkFormat;
1663     SkAssertResult(format.asVkFormat(&vkFormat));
1664     const auto& info = this->getFormatInfo(vkFormat);
1665     for (int i = 0; i < info.fColorTypeInfoCount; ++i) {
1666         const auto& ctInfo = info.fColorTypeInfos[i];
1667         if (ctInfo.fColorType == colorType) {
1668             return ctInfo.fTextureSwizzle;
1669         }
1670     }
1671     return GrSwizzle::RGBA();
1672 }
1673 
getOutputSwizzle(const GrBackendFormat & format,GrColorType colorType) const1674 GrSwizzle GrVkCaps::getOutputSwizzle(const GrBackendFormat& format, GrColorType colorType) const {
1675     VkFormat vkFormat;
1676     SkAssertResult(format.asVkFormat(&vkFormat));
1677     const auto& info = this->getFormatInfo(vkFormat);
1678     for (int i = 0; i < info.fColorTypeInfoCount; ++i) {
1679         const auto& ctInfo = info.fColorTypeInfos[i];
1680         if (ctInfo.fColorType == colorType) {
1681             return ctInfo.fOutputSwizzle;
1682         }
1683     }
1684     return GrSwizzle::RGBA();
1685 }
1686 
onSupportedReadPixelsColorType(GrColorType srcColorType,const GrBackendFormat & srcBackendFormat,GrColorType dstColorType) const1687 GrCaps::SupportedRead GrVkCaps::onSupportedReadPixelsColorType(
1688         GrColorType srcColorType, const GrBackendFormat& srcBackendFormat,
1689         GrColorType dstColorType) const {
1690     VkFormat vkFormat;
1691     if (!srcBackendFormat.asVkFormat(&vkFormat)) {
1692         return {GrColorType::kUnknown, 0};
1693     }
1694 
1695     if (GrVkFormatNeedsYcbcrSampler(vkFormat)) {
1696         return {GrColorType::kUnknown, 0};
1697     }
1698 
1699     // The VkBufferImageCopy bufferOffset field must be both a multiple of 4 and of a single texel.
1700     size_t offsetAlignment = align_to_4(this->bytesPerPixel(vkFormat));
1701 
1702     const auto& info = this->getFormatInfo(vkFormat);
1703     for (int i = 0; i < info.fColorTypeInfoCount; ++i) {
1704         const auto& ctInfo = info.fColorTypeInfos[i];
1705         if (ctInfo.fColorType == srcColorType) {
1706             return {srcColorType, offsetAlignment};
1707         }
1708     }
1709     return {GrColorType::kUnknown, 0};
1710 }
1711 
getFragmentUniformBinding() const1712 int GrVkCaps::getFragmentUniformBinding() const {
1713     return GrVkUniformHandler::kUniformBinding;
1714 }
1715 
getFragmentUniformSet() const1716 int GrVkCaps::getFragmentUniformSet() const {
1717     return GrVkUniformHandler::kUniformBufferDescSet;
1718 }
1719 
1720 #if GR_TEST_UTILS
getTestingCombinations() const1721 std::vector<GrCaps::TestFormatColorTypeCombination> GrVkCaps::getTestingCombinations() const {
1722     std::vector<GrCaps::TestFormatColorTypeCombination> combos = {
1723         { GrColorType::kAlpha_8,          GrBackendFormat::MakeVk(VK_FORMAT_R8_UNORM)             },
1724         { GrColorType::kBGR_565,          GrBackendFormat::MakeVk(VK_FORMAT_R5G6B5_UNORM_PACK16)  },
1725         { GrColorType::kABGR_4444,        GrBackendFormat::MakeVk(VK_FORMAT_R4G4B4A4_UNORM_PACK16)},
1726         { GrColorType::kABGR_4444,        GrBackendFormat::MakeVk(VK_FORMAT_B4G4R4A4_UNORM_PACK16)},
1727         { GrColorType::kRGBA_8888,        GrBackendFormat::MakeVk(VK_FORMAT_R8G8B8A8_UNORM)       },
1728         { GrColorType::kRGBA_8888_SRGB,   GrBackendFormat::MakeVk(VK_FORMAT_R8G8B8A8_SRGB)        },
1729         { GrColorType::kRGB_888x,         GrBackendFormat::MakeVk(VK_FORMAT_R8G8B8A8_UNORM)       },
1730         { GrColorType::kRGB_888x,         GrBackendFormat::MakeVk(VK_FORMAT_R8G8B8_UNORM)         },
1731         { GrColorType::kRGB_888x,         GrBackendFormat::MakeVk(VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK)},
1732         { GrColorType::kRG_88,            GrBackendFormat::MakeVk(VK_FORMAT_R8G8_UNORM)           },
1733         { GrColorType::kBGRA_8888,        GrBackendFormat::MakeVk(VK_FORMAT_B8G8R8A8_UNORM)       },
1734         { GrColorType::kRGBA_1010102,     GrBackendFormat::MakeVk(VK_FORMAT_A2B10G10R10_UNORM_PACK32)},
1735         { GrColorType::kGray_8,           GrBackendFormat::MakeVk(VK_FORMAT_R8_UNORM)             },
1736         { GrColorType::kAlpha_F16,        GrBackendFormat::MakeVk(VK_FORMAT_R16_SFLOAT)           },
1737         { GrColorType::kRGBA_F16,         GrBackendFormat::MakeVk(VK_FORMAT_R16G16B16A16_SFLOAT)  },
1738         { GrColorType::kRGBA_F16_Clamped, GrBackendFormat::MakeVk(VK_FORMAT_R16G16B16A16_SFLOAT)  },
1739         { GrColorType::kAlpha_16,         GrBackendFormat::MakeVk(VK_FORMAT_R16_UNORM)            },
1740         { GrColorType::kRG_1616,          GrBackendFormat::MakeVk(VK_FORMAT_R16G16_UNORM)         },
1741         { GrColorType::kRGBA_16161616,    GrBackendFormat::MakeVk(VK_FORMAT_R16G16B16A16_UNORM)   },
1742         { GrColorType::kRG_F16,           GrBackendFormat::MakeVk(VK_FORMAT_R16G16_SFLOAT)        },
1743     };
1744 
1745     return combos;
1746 }
1747 #endif
1748