Debian Codegraph @

src/gpu/graphite/dawn/DawnCaps.cpp

raw
1 /*
2 * Copyright 2022 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "src/gpu/graphite/dawn/DawnCaps.h"
9
10 #include <algorithm>
11 #include <string>
12
13 #include "include/core/SkTextureCompressionType.h"
14 #include "include/gpu/graphite/ContextOptions.h"
15 #include "include/gpu/graphite/TextureInfo.h"
16 #include "include/gpu/graphite/dawn/DawnBackendContext.h"
17 #include "include/gpu/graphite/dawn/DawnGraphiteTypes.h"
18 #include "src/gpu/SwizzlePriv.h"
19 #include "src/gpu/graphite/ComputePipelineDesc.h"
20 #include "src/gpu/graphite/GraphicsPipelineDesc.h"
21 #include "src/gpu/graphite/GraphiteResourceKey.h"
22 #include "src/gpu/graphite/RenderPassDesc.h"
23 #include "src/gpu/graphite/RendererProvider.h"
24 #include "src/gpu/graphite/ResourceTypes.h"
25 #include "src/gpu/graphite/TextureInfoPriv.h"
26 #include "src/gpu/graphite/UniformManager.h"
27 #include "src/gpu/graphite/dawn/DawnGraphicsPipeline.h"
28 #include "src/gpu/graphite/dawn/DawnGraphiteUtils.h"
29 #include "src/sksl/SkSLUtil.h"
30
31 #if defined(__EMSCRIPTEN__)
32 #include <emscripten/version.h>
33 #endif
34
35 namespace {
36
37 skgpu::UniqueKey::Domain get_pipeline_domain() {
38 static const skgpu::UniqueKey::Domain kDawnGraphicsPipelineDomain =
39 skgpu::UniqueKey::GenerateDomain();
40
41 return kDawnGraphicsPipelineDomain;
42 }
43
44 // These are all the valid wgpu::TextureFormat that we currently support in Skia.
45 // They are roughly ordered from most frequently used to least to improve lookup times in arrays.
46 static constexpr wgpu::TextureFormat kFormats[] = {
47 wgpu::TextureFormat::RGBA8Unorm,
48 wgpu::TextureFormat::R8Unorm,
49 #if !defined(__EMSCRIPTEN__)
50 wgpu::TextureFormat::R16Unorm,
51 #endif
52 wgpu::TextureFormat::BGRA8Unorm,
53 wgpu::TextureFormat::RGBA16Float,
54 wgpu::TextureFormat::R16Float,
55 wgpu::TextureFormat::RG8Unorm,
56 #if !defined(__EMSCRIPTEN__)
57 wgpu::TextureFormat::RG16Unorm,
58 #endif
59 wgpu::TextureFormat::RGB10A2Unorm,
60 wgpu::TextureFormat::RG16Float,
61
62 wgpu::TextureFormat::Stencil8,
63 wgpu::TextureFormat::Depth16Unorm,
64 wgpu::TextureFormat::Depth32Float,
65 wgpu::TextureFormat::Depth24PlusStencil8,
66
67 wgpu::TextureFormat::BC1RGBAUnorm,
68 wgpu::TextureFormat::ETC2RGB8Unorm,
69
70 #if !defined(__EMSCRIPTEN__)
71 wgpu::TextureFormat::External,
72 #endif
73 };
74
75 #if !defined(__EMSCRIPTEN__)
76 bool IsMultiplanarFormat(wgpu::TextureFormat format) {
77 switch (format) {
78 case wgpu::TextureFormat::R8BG8Biplanar420Unorm:
79 case wgpu::TextureFormat::R10X6BG10X6Biplanar420Unorm:
80 case wgpu::TextureFormat::R8BG8A8Triplanar420Unorm:
81 return true;
82 default:
83 return false;
84 }
85 }
86 #endif
87 } // anonymous namespace
88
89 namespace skgpu::graphite {
90
91 DawnCaps::DawnCaps(const DawnBackendContext& backendContext, const ContextOptions& options)
92 : Caps() {
93 this->initCaps(backendContext, options);
94 this->initShaderCaps(backendContext.fDevice);
95 this->initFormatTable(backendContext.fDevice);
96 this->finishInitialization(options);
97 }
98
99 DawnCaps::~DawnCaps() = default;
100
101 bool DawnCaps::isTexturableIgnoreSampleCount(const TextureInfo& info) const {
102 auto overrideDawnInfo = TextureInfoPriv::Get<DawnTextureInfo>(info);
103 overrideDawnInfo.fSampleCount = SampleCount::k1;
104 TextureInfo overrideInfo = TextureInfos::MakeDawn(overrideDawnInfo);
105 return this->isTexturable(overrideInfo);
106 }
107
108 bool DawnCaps::onIsTexturable(const TextureInfo& info) const {
109 if (!info.isValid()) {
110 return false;
111 }
112
113 const auto& dawnInfo = TextureInfoPriv::Get<DawnTextureInfo>(info);
114
115 if (!(dawnInfo.fUsage & wgpu::TextureUsage::TextureBinding)) {
116 return false;
117 }
118
119 #if !defined(__EMSCRIPTEN__)
120 switch (dawnInfo.fFormat) {
121 case wgpu::TextureFormat::R8BG8Biplanar420Unorm: {
122 if (dawnInfo.fAspect == wgpu::TextureAspect::Plane0Only &&
123 dawnInfo.getViewFormat() != wgpu::TextureFormat::R8Unorm) {
124 return false;
125 }
126 if (dawnInfo.fAspect == wgpu::TextureAspect::Plane1Only &&
127 dawnInfo.getViewFormat() != wgpu::TextureFormat::RG8Unorm) {
128 return false;
129 }
130 break;
131 }
132 case wgpu::TextureFormat::R10X6BG10X6Biplanar420Unorm: {
133 if (dawnInfo.fAspect == wgpu::TextureAspect::Plane0Only &&
134 dawnInfo.getViewFormat() != wgpu::TextureFormat::R16Unorm) {
135 return false;
136 }
137 if (dawnInfo.fAspect == wgpu::TextureAspect::Plane1Only &&
138 dawnInfo.getViewFormat() != wgpu::TextureFormat::RG16Unorm) {
139 return false;
140 }
141 break;
142 }
143 case wgpu::TextureFormat::R8BG8A8Triplanar420Unorm: {
144 if (dawnInfo.fAspect == wgpu::TextureAspect::Plane0Only &&
145 dawnInfo.getViewFormat() != wgpu::TextureFormat::R8Unorm) {
146 return false;
147 }
148 if (dawnInfo.fAspect == wgpu::TextureAspect::Plane1Only &&
149 dawnInfo.getViewFormat() != wgpu::TextureFormat::RG8Unorm) {
150 return false;
151 }
152 if (dawnInfo.fAspect == wgpu::TextureAspect::Plane2Only &&
153 dawnInfo.getViewFormat() != wgpu::TextureFormat::R8Unorm) {
154 return false;
155 }
156 break;
157 }
158 default:
159 break;
160 }
161 #endif
162
163 const FormatInfo& formatInfo = this->getFormatInfo(dawnInfo.getViewFormat());
164 return SkToBool(FormatInfo::kTexturable_Flag & formatInfo.fFlags);
165 }
166
167 bool DawnCaps::isRenderable(const TextureInfo& info) const {
168 if (!info.isValid()) {
169 return false;
170 }
171 TextureFormat format = TextureInfoPriv::ViewFormat(info);
172 const auto& dawnInfo = TextureInfoPriv::Get<DawnTextureInfo>(info);
173 return (dawnInfo.fUsage & wgpu::TextureUsage::RenderAttachment) &&
174 this->isSampleCountSupported(format, info.sampleCount());
175 }
176
177 bool DawnCaps::isStorage(const TextureInfo& info) const {
178 if (!info.isValid()) {
179 return false;
180 }
181 const auto& dawnInfo = TextureInfoPriv::Get<DawnTextureInfo>(info);
182 if (!(dawnInfo.fUsage & wgpu::TextureUsage::StorageBinding)) {
183 return false;
184 }
185 const FormatInfo& formatInfo = this->getFormatInfo(dawnInfo.getViewFormat());
186 return info.sampleCount() == SampleCount::k1 &&
187 SkToBool(FormatInfo::kStorage_Flag & formatInfo.fFlags);
188 }
189
190 bool DawnCaps::isSampleCountSupported(TextureFormat format,
191 SampleCount requestedSampleCount) const {
192 const FormatInfo& formatInfo = this->getFormatInfo(TextureFormatToDawnFormat(format));
193 if (!SkToBool(formatInfo.fFlags & FormatInfo::kRenderable_Flag)) {
194 return 0;
195 }
196 if (SkToBool(formatInfo.fFlags & FormatInfo::kMSAA_Flag)) {
197 // WebGPU only supports a sample count of 1 or 4.
198 return requestedSampleCount == SampleCount::k1 || requestedSampleCount == SampleCount::k4;
199 } else {
200 return requestedSampleCount == SampleCount::k1;
201 }
202 }
203
204 TextureFormat DawnCaps::getDepthStencilFormat(SkEnumBitMask<DepthStencilFlags> mask) const {
205 if (mask == DepthStencilFlags::kDepth) {
206 // If needed for workarounds or performance, Depth32Float is also available but requires 2x
207 // the amount of memory.
208 return TextureFormat::kD16;
209 } else if (mask == DepthStencilFlags::kStencil) {
210 return TextureFormat::kS8;
211 } else if (mask == DepthStencilFlags::kDepthStencil) {
212 // For WebGPU, this maps to kDepth24PlusStencil8, which might end up choosing the equivalent
213 // of D32F_S8 under the hood.
214 return TextureFormat::kD24_S8;
215 }
216 return TextureFormat::kUnsupported;
217 }
218
219 TextureInfo DawnCaps::getDefaultAttachmentTextureInfo(AttachmentDesc desc,
220 Protected,
221 Discardable discardable) const {
222 if (!this->isSampleCountSupported(desc.fFormat, desc.fSampleCount)) {
223 return {};
224 }
225
226 DawnTextureInfo info;
227 info.fSampleCount = desc.fSampleCount;
228 info.fMipmapped = Mipmapped::kNo;
229 info.fFormat = TextureFormatToDawnFormat(desc.fFormat);
230 info.fUsage = wgpu::TextureUsage::RenderAttachment;
231
232 if (fSupportedTransientAttachmentUsage != wgpu::TextureUsage::None &&
233 discardable == Discardable::kYes) {
234 info.fUsage |= fSupportedTransientAttachmentUsage;
235 }
236 if (fEmulateLoadStoreResolve && !TextureFormatIsDepthOrStencil(desc.fFormat)) {
237 // When emulating the store, the color attachment is sampled into the resolve.
238 info.fUsage |= wgpu::TextureUsage::TextureBinding;
239 }
240
241 return TextureInfos::MakeDawn(info);
242 }
243
244 TextureInfo DawnCaps::getDefaultSampledTextureInfo(SkColorType colorType,
245 Mipmapped mipmapped,
246 Protected,
247 Renderable renderable) const {
248 wgpu::TextureUsage usage = wgpu::TextureUsage::TextureBinding |
249 wgpu::TextureUsage::CopyDst |
250 wgpu::TextureUsage::CopySrc;
251 if (renderable == Renderable::kYes) {
252 usage |= wgpu::TextureUsage::RenderAttachment;
253 }
254
255 wgpu::TextureFormat format = this->getFormatFromColorType(colorType);
256 if (format == wgpu::TextureFormat::Undefined) {
257 return {};
258 }
259
260 DawnTextureInfo info;
261 info.fSampleCount = SampleCount::k1;
262 info.fMipmapped = mipmapped;
263 info.fFormat = format;
264 info.fViewFormat = format;
265 info.fUsage = usage;
266
267 return TextureInfos::MakeDawn(info);
268 }
269
270 TextureInfo DawnCaps::getTextureInfoForSampledCopy(const TextureInfo& textureInfo,
271 Mipmapped mipmapped) const {
272 DawnTextureInfo info;
273 info.fSampleCount = SampleCount::k1;
274 info.fMipmapped = mipmapped;
275 info.fFormat = TextureInfoPriv::Get<DawnTextureInfo>(textureInfo).getViewFormat();
276 info.fUsage = wgpu::TextureUsage::TextureBinding | wgpu::TextureUsage::CopyDst |
277 wgpu::TextureUsage::CopySrc;
278
279 return TextureInfos::MakeDawn(info);
280 }
281
282 namespace {
283 wgpu::TextureFormat format_from_compression(SkTextureCompressionType compression) {
284 switch (compression) {
285 case SkTextureCompressionType::kETC2_RGB8_UNORM:
286 return wgpu::TextureFormat::ETC2RGB8Unorm;
287 case SkTextureCompressionType::kBC1_RGBA8_UNORM:
288 return wgpu::TextureFormat::BC1RGBAUnorm;
289 default:
290 return wgpu::TextureFormat::Undefined;
291 }
292 }
293 }
294
295 TextureInfo DawnCaps::getDefaultCompressedTextureInfo(SkTextureCompressionType compression,
296 Mipmapped mipmapped,
297 Protected) const {
298 wgpu::TextureUsage usage = wgpu::TextureUsage::TextureBinding |
299 wgpu::TextureUsage::CopyDst |
300 wgpu::TextureUsage::CopySrc;
301
302 wgpu::TextureFormat format = format_from_compression(compression);
303 if (format == wgpu::TextureFormat::Undefined) {
304 return {};
305 }
306
307 DawnTextureInfo info;
308 info.fSampleCount = SampleCount::k1;
309 info.fMipmapped = mipmapped;
310 info.fFormat = format;
311 info.fViewFormat = format;
312 info.fUsage = usage;
313
314 return TextureInfos::MakeDawn(info);
315 }
316
317 TextureInfo DawnCaps::getDefaultStorageTextureInfo(SkColorType colorType) const {
318 wgpu::TextureFormat format = this->getFormatFromColorType(colorType);
319 if (format == wgpu::TextureFormat::Undefined) {
320 SkDebugf("colorType=%d is not supported\n", static_cast<int>(colorType));
321 return {};
322 }
323
324 const FormatInfo& formatInfo = this->getFormatInfo(format);
325 if (!SkToBool(FormatInfo::kStorage_Flag & formatInfo.fFlags)) {
326 return {};
327 }
328
329 wgpu::TextureUsage usage = wgpu::TextureUsage::StorageBinding |
330 wgpu::TextureUsage::TextureBinding |
331 wgpu::TextureUsage::CopySrc;
332 DawnTextureInfo info;
333 info.fSampleCount = SampleCount::k1;
334 info.fMipmapped = Mipmapped::kNo;
335 info.fFormat = format;
336 info.fViewFormat = format;
337 info.fUsage = usage;
338
339 return TextureInfos::MakeDawn(info);
340 }
341
342 SkISize DawnCaps::getDepthAttachmentDimensions(const TextureInfo& textureInfo,
343 const SkISize colorAttachmentDimensions) const {
344 #if !defined(__EMSCRIPTEN__)
345 // For multiplanar textures, texture->textureInfo() uses the format of planes instead of
346 // textures (R8, R8G8, vs R8BG8Biplanar420Unorm), so we have to query texture format from
347 // wgpu::Texture object, and then use it reconstruct the full dimensions.
348 const auto& dawnInfo = TextureInfoPriv::Get<DawnTextureInfo>(textureInfo);
349 wgpu::TextureFormat format = dawnInfo.fFormat;
350 if (IsMultiplanarFormat(format) && dawnInfo.fAspect == wgpu::TextureAspect::Plane1Only) {
351 // Dawn requires depth attachment to match the size of Y plane (texture size).
352 return SkISize::Make(colorAttachmentDimensions.width() * 2,
353 colorAttachmentDimensions.height() * 2);
354 }
355 #endif
356
357 return colorAttachmentDimensions;
358 }
359
360 SkSpan<const Caps::ColorTypeInfo> DawnCaps::getColorTypeInfos(
361 const TextureInfo& textureInfo) const {
362 auto dawnFormat = TextureInfoPriv::Get<DawnTextureInfo>(textureInfo).getViewFormat();
363 if (dawnFormat == wgpu::TextureFormat::Undefined) {
364 SkASSERT(false);
365 return {};
366 }
367
368 const FormatInfo& formatInfo = this->getFormatInfo(dawnFormat);
369 return {formatInfo.fColorTypeInfos.get(), formatInfo.fColorTypeInfoCount};
370 }
371
372 bool DawnCaps::supportsWritePixels(const TextureInfo& textureInfo) const {
373 const auto& dawnInfo = TextureInfoPriv::Get<DawnTextureInfo>(textureInfo);
374 return dawnInfo.fUsage & wgpu::TextureUsage::CopyDst;
375 }
376
377 bool DawnCaps::supportsReadPixels(const TextureInfo& textureInfo) const {
378 const auto& dawnInfo = TextureInfoPriv::Get<DawnTextureInfo>(textureInfo);
379 return dawnInfo.fUsage & wgpu::TextureUsage::CopySrc;
380 }
381
382 void DawnCaps::initCaps(const DawnBackendContext& backendContext, const ContextOptions& options) {
383 // GetAdapter() is not available in WASM and there's no way to get AdapterInfo off of
384 // the WGPUDevice directly.
385 #if !defined(__EMSCRIPTEN__)
386 wgpu::AdapterInfo info;
387 backendContext.fDevice.GetAdapter().GetInfo(&info);
388
389 #if defined(GPU_TEST_UTILS)
390 this->setDeviceName(std::string(info.device));
391 #endif
392 #endif // defined(__EMSCRIPTEN__)
393
394 #if defined(__EMSCRIPTEN__)
395 wgpu::SupportedLimits supportedLimits;
396 // TODO(crbug.com/42241199): Update to use wgpu::Status when webgpu.h in Emscripten is updated.
397 [[maybe_unused]] bool limitsSucceeded = backendContext.fDevice.GetLimits(&supportedLimits);
398 SkASSERT(limitsSucceeded);
399 wgpu::Limits& limits = supportedLimits.limits;
400 #else
401 wgpu::CompatibilityModeLimits compatLimits;
402 wgpu::Limits limits{.nextInChain = &compatLimits};
403 wgpu::DawnTexelCopyBufferRowAlignmentLimits alignmentLimits{};
404 if (backendContext.fDevice.HasFeature(wgpu::FeatureName::DawnTexelCopyBufferRowAlignment)) {
405 compatLimits.nextInChain = &alignmentLimits;
406 }
407 [[maybe_unused]] wgpu::Status status = backendContext.fDevice.GetLimits(&limits);
408 SkASSERT(status == wgpu::Status::Success);
409 #endif // defined(__EMSCRIPTEN__)
410
411 fMaxTextureSize = limits.maxTextureDimension2D;
412
413 fRequiredTransferBufferAlignment = 4;
414 fRequiredUniformBufferAlignment = limits.minUniformBufferOffsetAlignment;
415 fRequiredStorageBufferAlignment = limits.minStorageBufferOffsetAlignment;
416
417 fMaxVaryings = limits.maxInterStageShaderVariables;
418
419 // Dawn requires 256 bytes per row alignment for buffer texture copies.
420 fTextureDataRowBytesAlignment = 256;
421 #if !defined(__EMSCRIPTEN__)
422 // If the device supports the DawnTexelCopyBufferRowAlignment feature, the alignment can be
423 // queried from its limits.
424 if (backendContext.fDevice.HasFeature(wgpu::FeatureName::DawnTexelCopyBufferRowAlignment)) {
425 fTextureDataRowBytesAlignment = alignmentLimits.minTexelCopyBufferRowAlignment;
426 }
427 #endif
428
429 fResourceBindingReqs.fBackendApi = BackendApi::kDawn;
430 fResourceBindingReqs.fUniformBufferLayout = Layout::kStd140;
431 // The WGSL generator assumes tightly packed std430 layout for SSBOs which is also the default
432 // for all types outside the uniform address space in WGSL.
433 fResourceBindingReqs.fStorageBufferLayout = Layout::kStd430;
434 fResourceBindingReqs.fSeparateTextureAndSamplerBinding = true;
435
436 #if !defined(__EMSCRIPTEN__)
437 // We need 32 bytes push constant for 2 vectors worth of intrinsic data.
438 fResourceBindingReqs.fUsePushConstantsForIntrinsicConstants =
439 limits.maxImmediateSize >= DawnGraphicsPipeline::kIntrinsicUniformSize;
440 #endif
441
442 fResourceBindingReqs.fUniformsSetIdx = DawnGraphicsPipeline::kUniformBufferBindGroupIndex;
443 fResourceBindingReqs.fTextureSamplerSetIdx = DawnGraphicsPipeline::kTextureBindGroupIndex;
444
445 fResourceBindingReqs.fIntrinsicBufferBinding =
446 DawnGraphicsPipeline::kIntrinsicUniformBufferIndex;
447 fResourceBindingReqs.fCombinedUniformBufferBinding =
448 DawnGraphicsPipeline::kCombinedUniformIndex;
449 fResourceBindingReqs.fGradientBufferBinding = DawnGraphicsPipeline::kGradientBufferIndex;
450
451 #if !defined(__EMSCRIPTEN__)
452 // We need at least 4 SSBOs for intrinsic, render step, paint & gradient buffers.
453 // TODO(b/418235681): Enable SSBOs after fixing performance regressions for Dawn/Vulkan.
454 fStorageBufferSupport = info.backendType != wgpu::BackendType::OpenGL &&
455 info.backendType != wgpu::BackendType::OpenGLES &&
456 info.backendType != wgpu::BackendType::Vulkan &&
457 compatLimits.maxStorageBuffersInVertexStage >= 4 &&
458 compatLimits.maxStorageBuffersInFragmentStage >= 4;
459 #else
460 // WASM doesn't provide a way to query the backend, so can't tell if we are on a backend that
461 // needs to have SSBOs disabled. Pessimistically assume we could be. Once the above conditions
462 // go away in Dawn-native, then we can assume SSBOs are always supported in pure WebGPU too.
463 fStorageBufferSupport = false;
464 #endif
465
466 fDrawBufferCanBeMapped = false;
467
468 fComputeSupport = true;
469
470 // TODO: support clamp to border.
471 fClampToBorderSupport = false;
472
473 #if defined(GPU_TEST_UTILS)
474 fDrawBufferCanBeMappedForReadback = false;
475 #endif
476
477 #if defined(__EMSCRIPTEN__)
478 // For wasm, we use async map.
479 fBufferMapsAreAsync = true;
480 #else
481 // For Dawn native, we use direct mapping.
482 fBufferMapsAreAsync = false;
483 fDrawBufferCanBeMapped =
484 backendContext.fDevice.HasFeature(wgpu::FeatureName::BufferMapExtendedUsages);
485
486 fMSAARenderToSingleSampledSupport =
487 backendContext.fDevice.HasFeature(wgpu::FeatureName::MSAARenderToSingleSampled);
488
489 if (backendContext.fDevice.HasFeature(wgpu::FeatureName::TransientAttachments)) {
490 fSupportedTransientAttachmentUsage = wgpu::TextureUsage::TransientAttachment;
491 }
492 #endif
493
494 #if !defined(__EMSCRIPTEN__)
495 if (backendContext.fDevice.HasFeature(wgpu::FeatureName::DawnLoadResolveTexture)) {
496 fSupportedResolveTextureLoadOp = wgpu::LoadOp::ExpandResolveTexture;
497 fSupportsPartialLoadResolve =
498 backendContext.fDevice.HasFeature(wgpu::FeatureName::DawnPartialLoadResolveTexture);
499 fDifferentResolveAttachmentSizeSupport = fSupportsPartialLoadResolve;
500 }
501 #endif
502
503 if (!fSupportsPartialLoadResolve &&
504 fSupportedTransientAttachmentUsage == wgpu::TextureUsage::None) {
505 // If the device doesn't support partial resolve nor transient attachments, we will emulate
506 // load/resolve using separate render passes. This helps reuse MSAA textures better to
507 // reduce memory usage.
508 fEmulateLoadStoreResolve = true;
509 fDifferentResolveAttachmentSizeSupport = true;
510
511 // On hardware that doesn't support transient attachments or partial resolve, we
512 // force-disable the ExpandResolveTexture loadOp. This is done because, under emulation,
513 // ExpandResolveTexture isn't used, and fully disabling it prevents the precompilation API
514 // from generating duplicate pipeline permutations (one for load resolve texture, one for
515 // others).
516 fSupportedResolveTextureLoadOp = std::nullopt;
517 }
518
519 if (backendContext.fDevice.HasFeature(wgpu::FeatureName::TimestampQuery)) {
520 // Native Dawn has an API for writing timestamps on command buffers. WebGPU only supports
521 // begin and end timestamps on render and compute passes.
522 #if !defined(__EMSCRIPTEN__)
523 // TODO(b/42240559): On Apple silicon, the timer queries don't have the correct dependencies
524 // to measure all the encoders that the start/end commands encapsulate in the commandbuffer.
525 // We would prefer to keep this API as it lets us measure our texture uploads. If either
526 // this is fixed in Dawn, we can unconditionally take this approach for dawn-native; or
527 // the WebGPU API can hopefully be extended to capture blit passes.
528 fSupportsCommandBufferTimestamps = info.backendType != wgpu::BackendType::Metal;
529 #endif
530
531 // The emscripten C/C++ interface before 3.1.48 for timestamp query writes on render and
532 // compute passes is different than on current emsdk. The older API isn't correctly
533 // translated to the current JS WebGPU API in emsdk. So we require 3.1.48+.
534 #if !defined(__EMSCRIPTEN__) \
535 || (__EMSCRIPTEN_major__ > 3) \
536 || (__EMSCRIPTEN_major__ == 3 && __EMSCRIPTEN_minor__ > 1) \
537 || (__EMSCRIPTEN_major__ == 3 && __EMSCRIPTEN_minor__ == 1 && __EMSCRIPTEN_tiny__ >= 48)
538 fSupportedGpuStats |= GpuStatsFlags::kElapsedTime;
539 #endif
540 }
541
542 if (!backendContext.fTick) {
543 fAllowCpuSync = false;
544 // This seems paradoxical. However, if we use the async pipeline creation methods (e.g
545 // Device::CreateRenderPipelineAsync) then we may have to synchronize before a submit that
546 // uses the pipeline. If we use the methods that look synchronous (e.g.
547 // Device::CreateRenderPipeline) they actually operate asynchronously on WebGPU but the
548 // browser becomes responsible for synchronizing when we call submit.
549 fUseAsyncPipelineCreation = false;
550
551 // The implementation busy waits after popping.
552 fAllowScopedErrorChecks = false;
553 }
554
555 fFullCompressedUploadSizeMustAlignToBlockDims = true;
556 }
557
558 void DawnCaps::initShaderCaps(const wgpu::Device& device) {
559 SkSL::ShaderCaps* shaderCaps = fShaderCaps.get();
560
561 // WGSL does not support infinities regardless of hardware support. There are discussions around
562 // enabling it using an extension in the future.
563 shaderCaps->fInfinitySupport = false;
564
565 // WGSL supports shader derivatives in the fragment shader
566 shaderCaps->fShaderDerivativeSupport = true;
567
568 #if !defined(__EMSCRIPTEN__)
569 if (device.HasFeature(wgpu::FeatureName::DualSourceBlending)) {
570 shaderCaps->fDualSourceBlendingSupport = true;
571 }
572 if (device.HasFeature(wgpu::FeatureName::FramebufferFetch)) {
573 shaderCaps->fFBFetchSupport = true;
574 }
575 #endif
576 }
577
578 void DawnCaps::initFormatTable(const wgpu::Device& device) {
579 // NOTE: wgpu::TextureFormat's naming convention orders channels from least significant to most,
580 // matching the data address ordering of a little endian system.
581 FormatInfo* info;
582 // Format: RGBA8Unorm
583 {
584 info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::RGBA8Unorm)];
585 info->fFlags = FormatInfo::kAllFlags;
586 info->fColorTypeInfoCount = 2;
587 info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
588 int ctIdx = 0;
589 // Format: RGBA8Unorm, Surface: kRGBA_8888
590 {
591 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
592 ctInfo.fColorType = kRGBA_8888_SkColorType;
593 ctInfo.fTransferColorType = kRGBA_8888_SkColorType;
594 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
595 }
596 // Format: RGBA8Unorm, Surface: kRGB_888x
597 {
598 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
599 ctInfo.fColorType = kRGB_888x_SkColorType;
600 ctInfo.fTransferColorType = kRGB_888x_SkColorType;
601 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag;
602 ctInfo.fReadSwizzle = skgpu::Swizzle::RGB1();
603 }
604 }
605
606 // Format: R8Unorm
607 {
608 info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::R8Unorm)];
609 info->fFlags = FormatInfo::kAllFlags;
610 if (!device.HasFeature(wgpu::FeatureName::TextureFormatsTier1)) {
611 info->fFlags &= ~FormatInfo::kStorage_Flag;
612 }
613 info->fColorTypeInfoCount = 3;
614 info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
615 int ctIdx = 0;
616 // Format: R8Unorm, Surface: kAlpha_8
617 {
618 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
619 ctInfo.fColorType = kAlpha_8_SkColorType;
620 ctInfo.fTransferColorType = kAlpha_8_SkColorType;
621 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
622 ctInfo.fReadSwizzle = skgpu::Swizzle("000r");
623 ctInfo.fWriteSwizzle = skgpu::Swizzle("a000");
624 }
625 // Format: R8Unorm, Surface: kR8_unorm
626 {
627 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
628 ctInfo.fColorType = kR8_unorm_SkColorType;
629 ctInfo.fTransferColorType = kR8_unorm_SkColorType;
630 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
631 }
632 // Format: R8Unorm, Surface: kGray_8
633 {
634 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
635 ctInfo.fColorType = kGray_8_SkColorType;
636 ctInfo.fTransferColorType = kGray_8_SkColorType;
637 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag;
638 ctInfo.fReadSwizzle = skgpu::Swizzle("rrr1");
639 }
640 }
641
642 #if !defined(__EMSCRIPTEN__)
643 const bool supportUnorm16 = device.HasFeature(wgpu::FeatureName::Unorm16TextureFormats);
644 // TODO(crbug.com/dawn/1856): Support storage binding for compute shader in Dawn.
645 // Format: R16Unorm
646 {
647 info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::R16Unorm)];
648 if (supportUnorm16) {
649 info->fFlags = FormatInfo::kAllFlags & ~FormatInfo::kStorage_Flag;
650 info->fColorTypeInfoCount = 2;
651 info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
652 int ctIdx = 0;
653 // Format: R16Unorm, Surface: kA16_unorm
654 {
655 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
656 ctInfo.fColorType = kA16_unorm_SkColorType;
657 ctInfo.fTransferColorType = kA16_unorm_SkColorType;
658 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
659 ctInfo.fReadSwizzle = skgpu::Swizzle("000r");
660 ctInfo.fWriteSwizzle = skgpu::Swizzle("a000");
661 }
662 // Format: R16Unorm, Surface: kR16_unorm
663 {
664 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
665 ctInfo.fColorType = kR16_unorm_SkColorType;
666 ctInfo.fTransferColorType = kR16_unorm_SkColorType;
667 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
668 }
669 }
670 }
671 #endif
672
673 // Format: BGRA8Unorm
674 {
675 info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::BGRA8Unorm)];
676 info->fFlags = FormatInfo::kAllFlags;
677 info->fColorTypeInfoCount = 2;
678 info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
679 int ctIdx = 0;
680 // Format: BGRA8Unorm, Surface: kBGRA_8888
681 {
682 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
683 ctInfo.fColorType = kBGRA_8888_SkColorType;
684 ctInfo.fTransferColorType = kBGRA_8888_SkColorType;
685 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
686 }
687 // Format: BGRA8Unorm, Surface: kRGB_888x
688 {
689 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
690 ctInfo.fColorType = kRGB_888x_SkColorType;
691 // There is no kBGR_888x color type, so report that the data is BGRA and rely on
692 // SkConvertPixels to force alpha to opaque when kRGB_888x is either the src or dst type
693 ctInfo.fTransferColorType = kBGRA_8888_SkColorType;
694 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag;
695 }
696 }
697
698 // Format: RGBA16Float
699 {
700 info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::RGBA16Float)];
701 info->fFlags = FormatInfo::kAllFlags;
702 info->fColorTypeInfoCount = 2;
703 info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
704 int ctIdx = 0;
705 // Format: RGBA16Float, Surface: RGBA_F16
706 {
707 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
708 ctInfo.fColorType = kRGBA_F16_SkColorType;
709 ctInfo.fTransferColorType = kRGBA_F16_SkColorType;
710 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
711 }
712 // Format: RGBA16Float, Surface: RGB_F16F16F16x
713 {
714 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
715 ctInfo.fColorType = kRGB_F16F16F16x_SkColorType;
716 ctInfo.fTransferColorType = kRGB_F16F16F16x_SkColorType;
717 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag;
718 ctInfo.fReadSwizzle = skgpu::Swizzle::RGB1();
719 }
720 }
721
722 // Format: R16Float
723 {
724 info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::R16Float)];
725 info->fFlags = FormatInfo::kAllFlags;
726 info->fColorTypeInfoCount = 1;
727 info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
728 int ctIdx = 0;
729 // Format: R16Float, Surface: kA16_float
730 {
731 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
732 ctInfo.fColorType = kA16_float_SkColorType;
733 ctInfo.fTransferColorType = kA16_float_SkColorType;
734 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
735 ctInfo.fReadSwizzle = skgpu::Swizzle("000r");
736 ctInfo.fWriteSwizzle = skgpu::Swizzle("a000");
737 }
738 }
739
740 // TODO(crbug.com/dawn/1856): Support storage binding for compute shader in Dawn.
741 // Format: RG8Unorm
742 {
743 info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::RG8Unorm)];
744 info->fFlags = FormatInfo::kAllFlags;
745 info->fColorTypeInfoCount = 1;
746 info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
747 int ctIdx = 0;
748 // Format: RG8Unorm, Surface: kR8G8_unorm
749 {
750 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
751 ctInfo.fColorType = kR8G8_unorm_SkColorType;
752 ctInfo.fTransferColorType = kR8G8_unorm_SkColorType;
753 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
754 }
755 }
756
757 #if !defined(__EMSCRIPTEN__)
758 // TODO(crbug.com/dawn/1856): Support storage binding for compute shader in Dawn.
759 // Format: RG16Unorm
760 {
761 info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::RG16Unorm)];
762 if (supportUnorm16) {
763 info->fFlags = FormatInfo::kAllFlags;
764 info->fColorTypeInfoCount = 1;
765 info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
766 int ctIdx = 0;
767 // Format: RG16Unorm, Surface: kR16G16_unorm
768 {
769 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
770 ctInfo.fColorType = kR16G16_unorm_SkColorType;
771 ctInfo.fTransferColorType = kR16G16_unorm_SkColorType;
772 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
773 }
774 }
775 }
776 #endif
777
778 // Format: RGB10A2Unorm
779 {
780 info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::RGB10A2Unorm)];
781 info->fFlags = FormatInfo::kAllFlags;
782 info->fColorTypeInfoCount = 2;
783 info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
784 int ctIdx = 0;
785 // Format: RGB10A2Unorm, Surface: kRGBA_1010102
786 {
787 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
788 ctInfo.fColorType = kRGBA_1010102_SkColorType;
789 ctInfo.fTransferColorType = kRGBA_1010102_SkColorType;
790 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
791 }
792 // Format: RGB10A2Unorm, Surface: kRGB_101010x
793 {
794 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
795 ctInfo.fColorType = kRGB_101010x_SkColorType;
796 ctInfo.fTransferColorType = kRGB_101010x_SkColorType;
797 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag;
798 ctInfo.fReadSwizzle = skgpu::Swizzle::RGB1();
799 }
800 }
801
802 // Format: RG16Float
803 {
804 info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::RG16Float)];
805 info->fFlags = FormatInfo::kAllFlags;
806 info->fColorTypeInfoCount = 1;
807 info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
808 int ctIdx = 0;
809 // Format: RG16Float, Surface: kR16G16_float
810 {
811 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
812 ctInfo.fColorType = kR16G16_float_SkColorType;
813 ctInfo.fTransferColorType = kR16G16_float_SkColorType;
814 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag | ColorTypeInfo::kRenderable_Flag;
815 }
816 }
817
818 // Format: ETC2RGB8Unorm
819 {
820 if (device.HasFeature(wgpu::FeatureName::TextureCompressionETC2)) {
821 info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::ETC2RGB8Unorm)];
822 info->fFlags = FormatInfo::kTexturable_Flag;
823 info->fColorTypeInfoCount = 1;
824 info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
825 int ctIdx = 0;
826 // Format: ETC2RGB8Unorm, Surface: kRGB_888x
827 {
828 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
829 ctInfo.fColorType = kRGB_888x_SkColorType;
830 ctInfo.fTransferColorType = kRGB_888x_SkColorType;
831 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag;
832 }
833 }
834 }
835
836 // Format: BC1RGBAUnorm
837 {
838 if (device.HasFeature(wgpu::FeatureName::TextureCompressionBC)) {
839 info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::BC1RGBAUnorm)];
840 info->fFlags = FormatInfo::kTexturable_Flag;
841 info->fColorTypeInfoCount = 1;
842 info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
843 int ctIdx = 0;
844 // Format: BC1RGBAUnorm, Surface: kRGBA_8888
845 {
846 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
847 ctInfo.fColorType = kRGBA_8888_SkColorType;
848 ctInfo.fTransferColorType = kRGBA_8888_SkColorType;
849 ctInfo.fFlags = ColorTypeInfo::kUploadData_Flag;
850 }
851 }
852 }
853
854 /*
855 * Non-color formats (renderable but with no color type)
856 */
857
858 // Format: Stencil8
859 {
860 info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::Stencil8)];
861 info->fFlags = FormatInfo::kMSAA_Flag | FormatInfo::kRenderable_Flag;
862 info->fColorTypeInfoCount = 0;
863 }
864
865 // Format: Depth16UNorm
866 {
867 info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::Depth16Unorm)];
868 info->fFlags = FormatInfo::kMSAA_Flag | FormatInfo::kRenderable_Flag;
869 info->fColorTypeInfoCount = 0;
870 }
871
872 // Format: Depth32Float
873 {
874 info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::Depth32Float)];
875 info->fFlags = FormatInfo::kMSAA_Flag | FormatInfo::kRenderable_Flag;
876 info->fColorTypeInfoCount = 0;
877 }
878
879 // Format: Depth24PlusStencil8
880 {
881 info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::Depth24PlusStencil8)];
882 info->fFlags = FormatInfo::kMSAA_Flag | FormatInfo::kRenderable_Flag;
883 info->fColorTypeInfoCount = 0;
884 }
885
886 #if !defined(__EMSCRIPTEN__)
887 // Format: External
888 {
889 info = &fFormatTable[GetFormatIndex(wgpu::TextureFormat::External)];
890 info->fFlags = FormatInfo::kTexturable_Flag;
891 info->fColorTypeInfoCount = 2;
892 info->fColorTypeInfos = std::make_unique<ColorTypeInfo[]>(info->fColorTypeInfoCount);
893 int ctIdx = 0;
894 // Format: External, Surface: kRGBA_8888
895 {
896 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
897 ctInfo.fColorType = kRGBA_8888_SkColorType;
898 }
899 // Format: External, Surface: kRGB_888x
900 {
901 auto& ctInfo = info->fColorTypeInfos[ctIdx++];
902 ctInfo.fColorType = kRGB_888x_SkColorType;
903 }
904 }
905 #endif
906
907 ////////////////////////////////////////////////////////////////////////////
908 // Map SkColorTypes (used for creating SkSurfaces) to wgpu::TextureFormat.
909 // The order in which the formats are passed into the setColorType function
910 // indicates the priority in selecting which format we use for a given
911 // SkColorType.
912
913 std::fill_n(fColorTypeToFormatTable, kSkColorTypeCnt, wgpu::TextureFormat::Undefined);
914
915 this->setColorType(kAlpha_8_SkColorType, { wgpu::TextureFormat::R8Unorm });
916 this->setColorType(kRGBA_8888_SkColorType, { wgpu::TextureFormat::RGBA8Unorm });
917 this->setColorType(kRGB_888x_SkColorType, { wgpu::TextureFormat::RGBA8Unorm,
918 wgpu::TextureFormat::BGRA8Unorm });
919 this->setColorType(kBGRA_8888_SkColorType, { wgpu::TextureFormat::BGRA8Unorm });
920 this->setColorType(kGray_8_SkColorType, { wgpu::TextureFormat::R8Unorm });
921 this->setColorType(kR8_unorm_SkColorType, { wgpu::TextureFormat::R8Unorm });
922 this->setColorType(kRGBA_F16_SkColorType, { wgpu::TextureFormat::RGBA16Float });
923 this->setColorType(kRGB_F16F16F16x_SkColorType, { wgpu::TextureFormat::RGBA16Float });
924 this->setColorType(kA16_float_SkColorType, { wgpu::TextureFormat::R16Float });
925 this->setColorType(kR8G8_unorm_SkColorType, { wgpu::TextureFormat::RG8Unorm });
926 this->setColorType(kRGBA_1010102_SkColorType, { wgpu::TextureFormat::RGB10A2Unorm });
927 this->setColorType(kRGB_101010x_SkColorType, { wgpu::TextureFormat::RGB10A2Unorm });
928 this->setColorType(kR16G16_float_SkColorType, { wgpu::TextureFormat::RG16Float });
929
930 #if !defined(__EMSCRIPTEN__)
931 this->setColorType(kA16_unorm_SkColorType, { wgpu::TextureFormat::R16Unorm });
932 this->setColorType(kR16_unorm_SkColorType, { wgpu::TextureFormat::R16Unorm });
933 this->setColorType(kR16G16_unorm_SkColorType, { wgpu::TextureFormat::RG16Unorm });
934 #endif
935 }
936
937 // static
938 size_t DawnCaps::GetFormatIndex(wgpu::TextureFormat format) {
939 for (size_t i = 0; i < std::size(kFormats); ++i) {
940 if (format == kFormats[i]) {
941 return i;
942 }
943 }
944 SkDEBUGFAILF("Unsupported wgpu::TextureFormat: 0x%08X\n", static_cast<uint32_t>(format));
945 return 0;
946 }
947
948 void DawnCaps::setColorType(SkColorType colorType,
949 std::initializer_list<wgpu::TextureFormat> formats) {
950 static_assert(std::size(kFormats) <= kFormatCount,
951 "Size is not compatible for DawnCaps::fFormatTable and kFormats");
952 int idx = static_cast<int>(colorType);
953 for (auto it = formats.begin(); it != formats.end(); ++it) {
954 const auto& info = this->getFormatInfo(*it);
955 for (int i = 0; i < info.fColorTypeInfoCount; ++i) {
956 if (info.fColorTypeInfos[i].fColorType == colorType) {
957 fColorTypeToFormatTable[idx] = *it;
958 return;
959 }
960 }
961 }
962 }
963
964 // TextureFormat is backed by a uint8_t, so 8 bits are always sufficient (including using
965 // kUnsupported) to represent an unused attachment. To make room for the load-from-resolve bit, we
966 // reduce the uint8_t of fSampleCount to 3 bits with the SampleToKey function (x2 attachments)
967 static constexpr int kFormatBits = 8; // x2 attachments (color & depthStencil formats)
968 static constexpr int kResolveBits = 1;
969
970 static_assert(2*(kFormatBits + kNumSampleKeyBits) + kResolveBits <= 32);
971 static_assert(kTextureFormatCount < 1 << kFormatBits);
972
973 static constexpr int kDepthStencilNumSamplesOffset = /*loadResolveOffset=0 + */ kResolveBits;
974 static constexpr int kDepthStencilFormatOffset = kDepthStencilNumSamplesOffset + kNumSampleKeyBits;
975 static constexpr int kColorNumSamplesOffset = kDepthStencilFormatOffset + kFormatBits;
976 static constexpr int kColorFormatOffset = kColorNumSamplesOffset + kNumSampleKeyBits;
977 static constexpr int kAdditionalFlagOffset = kColorFormatOffset + kFormatBits;
978 static_assert(kAdditionalFlagOffset <= 31);
979
980 static constexpr uint32_t kFormatMask = (1 << kFormatBits) - 1;
981 static constexpr uint32_t kNumSamplesMask = (1 << kNumSampleKeyBits) - 1;
982 static constexpr uint32_t kResolveMask = (1 << kResolveBits) - 1;
983
984 uint32_t DawnCaps::getRenderPassDescKeyForPipeline(const RenderPassDesc& renderPassDesc,
985 bool additionalFlag) const {
986 // The color attachment should be valid; the depth-stencil attachment may not be if it's not
987 // being used. The full resolve attachment (if present) does not need to be included.
988 const auto& color = renderPassDesc.fColorAttachment;
989 const auto& depthStencil = renderPassDesc.fDepthStencilAttachment;
990 SkASSERT(color.fFormat != TextureFormat::kUnsupported);
991
992 // Note: if Dawn supports ExpandResolveTexture load op and the render pass uses it to load the
993 // resolve texture, a render pipeline will need to be created with
994 // wgpu::ColorTargetStateExpandResolveTextureDawn chained struct in order to be compatible.
995 // Hence a render pipeline created for a render pass using ExpandResolveTexture load op will be
996 // different from the one created for a render pass not using that load op. So we need to
997 // include a bit flag to differentiate the two kinds of pipelines.
998 const bool shouldIncludeLoadResolveAttachmentBit = this->loadOpAffectsMSAAPipelines();
999 uint32_t loadResolveAttachmentKey = 0;
1000 if (shouldIncludeLoadResolveAttachmentBit &&
1001 renderPassDesc.fColorResolveAttachment.fFormat != TextureFormat::kUnsupported &&
1002 renderPassDesc.fColorResolveAttachment.fLoadOp == LoadOp::kLoad) {
1003 loadResolveAttachmentKey = 1;
1004 }
1005
1006 SkASSERT(SamplesToKey(color.fSampleCount) < (1 << kNumSampleKeyBits));
1007 SkASSERT(SamplesToKey(depthStencil.fSampleCount) < (1 << kNumSampleKeyBits));
1008 SkASSERT(loadResolveAttachmentKey < (1 << kResolveBits));
1009 uint32_t additionalFlagKey = additionalFlag ? 1 : 0;
1010
1011 return (additionalFlagKey << kAdditionalFlagOffset) |
1012 (static_cast<uint32_t>(color.fFormat) << kColorFormatOffset) |
1013 (SamplesToKey(color.fSampleCount) << kColorNumSamplesOffset) |
1014 (static_cast<uint32_t>(depthStencil.fFormat) << kDepthStencilFormatOffset) |
1015 (SamplesToKey(depthStencil.fSampleCount) << kDepthStencilNumSamplesOffset) |
1016 loadResolveAttachmentKey;
1017 }
1018
1019 static constexpr uint16_t kDawnGraphicsPipelineKeyData32Count = 4;
1020
1021 UniqueKey DawnCaps::makeGraphicsPipelineKey(const GraphicsPipelineDesc& pipelineDesc,
1022 const RenderPassDesc& renderPassDesc) const {
1023 UniqueKey pipelineKey;
1024 {
1025 // 4 uint32_t's (render step id, paint id, uint32 RenderPassDesc, uint16 write swizzle key)
1026 UniqueKey::Builder builder(&pipelineKey, get_pipeline_domain(),
1027 kDawnGraphicsPipelineKeyData32Count, "DawnGraphicsPipeline");
1028 // Add GraphicsPipelineDesc key.
1029 builder[0] = static_cast<uint32_t>(pipelineDesc.renderStepID());
1030 builder[1] = pipelineDesc.paintParamsID().asUInt();
1031
1032 // Add RenderPassDesc key and write swizzle (which is separate from the RenderPassDescKey
1033 // because it is applied in the program writing to the target, and is not actually part of
1034 // the underlying GPU render pass config).
1035 builder[2] = this->getRenderPassDescKeyForPipeline(renderPassDesc);
1036 builder[3] = renderPassDesc.fWriteSwizzle.asKey();
1037 builder.finish();
1038 }
1039
1040 return pipelineKey;
1041 }
1042
1043 bool DawnCaps::extractGraphicsDescs(const UniqueKey& key,
1044 GraphicsPipelineDesc* pipelineDesc,
1045 RenderPassDesc* renderPassDesc,
1046 const RendererProvider* rendererProvider) const {
1047 SkASSERT(key.domain() == get_pipeline_domain());
1048 SkASSERT(key.dataSize() == 4 * kDawnGraphicsPipelineKeyData32Count);
1049
1050 const uint32_t* rawKeyData = key.data();
1051
1052 SkASSERT(RenderStep::IsValidRenderStepID(rawKeyData[0]));
1053 RenderStep::RenderStepID renderStepID = static_cast<RenderStep::RenderStepID>(rawKeyData[0]);
1054
1055 *pipelineDesc = GraphicsPipelineDesc(renderStepID, UniquePaintParamsID(rawKeyData[1]));
1056
1057 const uint32_t rpDescBits = rawKeyData[2];
1058 TextureFormat colorFormat =
1059 static_cast<TextureFormat>((rpDescBits >> kColorFormatOffset) & kFormatMask);
1060 SampleCount colorSamples =
1061 KeyToSamples((rpDescBits >> kColorNumSamplesOffset) & kNumSamplesMask);
1062
1063 TextureFormat depthStencilFormat =
1064 static_cast<TextureFormat>((rpDescBits >> kDepthStencilFormatOffset) & kFormatMask);
1065 SampleCount depthStencilSamples =
1066 KeyToSamples((rpDescBits >> kDepthStencilNumSamplesOffset) & kNumSamplesMask);
1067
1068 const bool loadFromResolve = (rpDescBits & kResolveMask) != 0;
1069 // This bit should only be set if Dawn supports ExpandResolveTexture load op
1070 SkASSERT(!loadFromResolve || this->loadOpAffectsMSAAPipelines());
1071
1072 // Recreate the RenderPassDesc, assuming that if there is MSAA on the color attachment that
1073 // a resolve attachment is also required. The resolve attachment's load op will match the key.
1074 SkASSERT(colorSamples == depthStencilSamples ||
1075 depthStencilFormat == TextureFormat::kUnsupported);
1076 *renderPassDesc = {};
1077 renderPassDesc->fColorAttachment = {colorFormat,
1078 LoadOp::kClear,
1079 StoreOp::kStore,
1080 colorSamples};
1081 renderPassDesc->fDepthStencilAttachment = {depthStencilFormat,
1082 LoadOp::kClear,
1083 StoreOp::kDiscard,
1084 depthStencilSamples};
1085 if (colorSamples > SampleCount::k1) {
1086 renderPassDesc->fColorResolveAttachment = {colorFormat,
1087 loadFromResolve ? LoadOp::kLoad : LoadOp::kClear,
1088 StoreOp::kStore,
1089 SampleCount::k1};
1090 renderPassDesc->fColorAttachment.fStoreOp = StoreOp::kDiscard;
1091 }
1092
1093 renderPassDesc->fSampleCount = colorSamples;
1094 renderPassDesc->fWriteSwizzle = SwizzleCtorAccessor::Make(rawKeyData[3]);
1095 renderPassDesc->fDstReadStrategy = this->getDstReadStrategy();
1096
1097 return true;
1098 }
1099
1100 UniqueKey DawnCaps::makeComputePipelineKey(const ComputePipelineDesc& pipelineDesc) const {
1101 UniqueKey pipelineKey;
1102 {
1103 static const skgpu::UniqueKey::Domain kComputePipelineDomain = UniqueKey::GenerateDomain();
1104 // The key is made up of a single uint32_t corresponding to the compute step ID.
1105 UniqueKey::Builder builder(&pipelineKey, kComputePipelineDomain, 1, "ComputePipeline");
1106 builder[0] = pipelineDesc.computeStep()->uniqueID();
1107
1108 // TODO(b/240615224): The local work group size should factor into the key here since it is
1109 // specified in the shader text on Dawn/SPIR-V. This is not a problem right now since
1110 // ComputeSteps don't vary their workgroup size dynamically.
1111
1112 builder.finish();
1113 }
1114 return pipelineKey;
1115 }
1116
1117 ImmutableSamplerInfo DawnCaps::getImmutableSamplerInfo(const TextureInfo& textureInfo) const {
1118 #if !defined(__EMSCRIPTEN__)
1119 const wgpu::YCbCrVkDescriptor& ycbcrConversionInfo =
1120 TextureInfoPriv::Get<DawnTextureInfo>(textureInfo).fYcbcrVkDescriptor;
1121
1122 if (DawnDescriptorIsValid(ycbcrConversionInfo)) {
1123 return DawnDescriptorToImmutableSamplerInfo(ycbcrConversionInfo);
1124 }
1125 #endif
1126
1127 // If the YCbCr conversion for is invalid, then return a default ImmutableSamplerInfo struct.
1128 return {};
1129 }
1130
1131 #if !defined(__EMSCRIPTEN__)
1132 static constexpr const char* filter_mode_to_str(wgpu::FilterMode mode) {
1133 switch (mode) {
1134 case wgpu::FilterMode::Undefined: return "undefined";
1135 case wgpu::FilterMode::Nearest: return "nearest";
1136 case wgpu::FilterMode::Linear: return "linear";
1137 }
1138 SkUNREACHABLE;
1139 }
1140
1141 static constexpr const char* model_to_str(uint32_t c) {
1142 switch (c) {
1143 case 0 /* VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY */: return "RGB-I";
1144 case 1 /* VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY */: return "YCbCr-I";
1145 case 2 /* VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709 */: return "709";
1146 case 3 /* VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_601 */: return "601";
1147 case 4 /* VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020 */: return "2020";
1148 default: return "unknown";
1149 }
1150 SkUNREACHABLE;
1151 }
1152
1153 static constexpr const char* range_to_str(uint32_t r) {
1154 switch (r) {
1155 case 0 /* VK_SAMPLER_YCBCR_RANGE_ITU_FULL */: return "full";
1156 case 1 /* VK_SAMPLER_YCBCR_RANGE_ITU_NARROW */: return "narrow";
1157 default: return "unknown";
1158 }
1159 SkUNREACHABLE;
1160 }
1161
1162 static constexpr char swizzle_to_str(uint32_t c, char identityAnswer) {
1163 switch (c) {
1164 case 0 /* VK_COMPONENT_SWIZZLE_IDENTITY */: return identityAnswer;
1165 case 1 /* VK_COMPONENT_SWIZZLE_ZERO */: return '0';
1166 case 2 /* VK_COMPONENT_SWIZZLE_ONE */: return '1';
1167 case 3 /* VK_COMPONENT_SWIZZLE_R */: return 'r';
1168 case 4 /* VK_COMPONENT_SWIZZLE_G */: return 'g';
1169 case 5 /* VK_COMPONENT_SWIZZLE_B */: return 'b';
1170 case 6 /* VK_COMPONENT_SWIZZLE_A */: return 'a';
1171 default: return '?';
1172 }
1173 SkUNREACHABLE;
1174 }
1175 #endif
1176
1177 std::string DawnCaps::toString(const ImmutableSamplerInfo& immutableSamplerInfo) const {
1178 #if defined(__EMSCRIPTEN__)
1179 return "";
1180 #else
1181 const wgpu::YCbCrVkDescriptor info =
1182 DawnDescriptorFromImmutableSamplerInfo(immutableSamplerInfo);
1183 if (!DawnDescriptorIsValid(info)) {
1184 return "";
1185 }
1186
1187 std::string result;
1188
1189 if (info.vkFormat == 0) {
1190 result += 'x';
1191 result += std::to_string(info.externalFormat);
1192 } else {
1193 result += std::to_string(info.vkFormat);
1194 }
1195
1196 result += " ";
1197 result += model_to_str(info.vkYCbCrModel);
1198 result += "+";
1199 result += range_to_str(info.vkYCbCrRange);
1200 result += info.vkXChromaOffset ? " mid" : " cos"; // midpoint or cosited-even
1201 result += info.vkYChromaOffset ? " mid " : " cos "; // midpoint or cosited-even
1202 result += filter_mode_to_str(info.vkChromaFilter);
1203 result += info.forceExplicitReconstruction ? " T " : " F ";
1204 result += swizzle_to_str(info.vkComponentSwizzleRed, 'r');
1205 result += swizzle_to_str(info.vkComponentSwizzleGreen, 'g');
1206 result += swizzle_to_str(info.vkComponentSwizzleBlue, 'b');
1207 result += swizzle_to_str(info.vkComponentSwizzleAlpha, 'a');
1208 return result;
1209 #endif
1210 }
1211
1212 void DawnCaps::buildKeyForTexture(SkISize dimensions,
1213 const TextureInfo& info,
1214 ResourceType type,
1215 GraphiteResourceKey* key) const {
1216 const auto& dawnInfo = TextureInfoPriv::Get<DawnTextureInfo>(info);
1217
1218 SkASSERT(!dimensions.isEmpty());
1219
1220 SkASSERT(dawnInfo.getViewFormat() != wgpu::TextureFormat::Undefined);
1221 // FIXME we can reduce this by packing format into samplesKey and then we're back down to 5 ints
1222 // we could go further if we said textures were likely to be under 65kx65kf...
1223 uint32_t formatKey = static_cast<uint32_t>(dawnInfo.getViewFormat());
1224
1225 uint32_t samplesKey = SamplesToKey(info.sampleCount());
1226 // We don't have to key the number of mip levels because it is inherit in the combination of
1227 // isMipped and dimensions.
1228 bool isMipped = info.mipmapped() == Mipmapped::kYes;
1229
1230 // Confirm all the below parts of the key can fit in a single uint32_t. The sum of the shift
1231 // amounts in the asserts must be less than or equal to 32.
1232 SkASSERT(samplesKey < (1u << 3)); // sample key is first 3 bits
1233 SkASSERT(static_cast<uint32_t>(isMipped) < (1u << 1)); // isMapped is 4th bit
1234 SkASSERT(static_cast<uint32_t>(dawnInfo.fUsage) < (1u << 28)); // usage is remaining 28 bits
1235
1236 // We need two uint32_ts for dimensions, 1 for format, and 1 for the rest of the key;
1237 uint16_t num32DataCnt = 2 + 1 + 1;
1238 bool hasYcbcrInfo = false;
1239 #if !defined(__EMSCRIPTEN__)
1240 // If we are using ycbcr texture/sampling, more key information is needed.
1241 if ((hasYcbcrInfo = DawnDescriptorIsValid(dawnInfo.fYcbcrVkDescriptor))) {
1242 num32DataCnt += 3; // non-format flags and 64-bit format
1243 }
1244 #endif
1245 GraphiteResourceKey::Builder builder(key, type, num32DataCnt);
1246
1247 builder[0] = dimensions.width();
1248 builder[1] = dimensions.height();
1249 builder[2] = formatKey;
1250 builder[3] = (samplesKey << 0) |
1251 (static_cast<uint32_t>(isMipped) << 3) |
1252 (static_cast<uint32_t>(dawnInfo.fUsage) << 4);
1253
1254 #if !defined(__EMSCRIPTEN__)
1255 if (hasYcbcrInfo) {
1256 ImmutableSamplerInfo packedInfo =
1257 DawnDescriptorToImmutableSamplerInfo(dawnInfo.fYcbcrVkDescriptor);
1258 builder[4] = packedInfo.fNonFormatYcbcrConversionInfo;
1259 // Even though we already have formatKey appended to the texture key, we still need to add
1260 // fYcbcrVkDescriptor's vkFormat or externalFormat. The latter two are distinct from
1261 // dawnSpec's wgpu::TextureFormat.
1262 builder[5] = (uint32_t) packedInfo.fFormat;
1263 builder[6] = (uint32_t) (packedInfo.fFormat >> 32);
1264 }
1265 #endif
1266 }
1267
1268 } // namespace skgpu::graphite