Debian Codegraph @

src/gpu/graphite/dawn/DawnGraphicsPipeline.cpp

raw ◀ ▶
1 Debian patch touch this file
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/DawnGraphicsPipeline.h"
9
10 #include "include/gpu/graphite/TextureInfo.h"
11 #include "include/gpu/graphite/dawn/DawnGraphiteTypes.h"
12 #include "include/private/base/SkTemplates.h"
•13 #include "include/private/base/SkTArray.h"
14 #include "src/base/SkTBlockList.h"
15 #include "src/core/SkTraceEvent.h"
16 #include "src/gpu/SkSLToBackend.h"
17 #include "src/gpu/Swizzle.h"
18 #include "src/gpu/graphite/Attribute.h"
19 #include "src/gpu/graphite/ContextUtils.h"
20 #include "src/gpu/graphite/GraphicsPipelineDesc.h"
21 #include "src/gpu/graphite/Log.h"
22 #include "src/gpu/graphite/RenderPassDesc.h"
23 #include "src/gpu/graphite/RendererProvider.h"
24 #include "src/gpu/graphite/ShaderInfo.h"
25 #include "src/gpu/graphite/TextureInfoPriv.h"
26 #include "src/gpu/graphite/ThreadSafeResourceProvider.h"
27 #include "src/gpu/graphite/UniformManager.h"
28 #include "src/gpu/graphite/dawn/DawnCaps.h"
29 #include "src/gpu/graphite/dawn/DawnErrorChecker.h"
30 #include "src/gpu/graphite/dawn/DawnGraphiteUtils.h"
31 #include "src/gpu/graphite/dawn/DawnResourceProvider.h"
32 #include "src/gpu/graphite/dawn/DawnSampler.h"
33 #include "src/gpu/graphite/dawn/DawnSharedContext.h"
34 #include "src/sksl/SkSLProgramSettings.h"
35 #include "src/sksl/SkSLUtil.h"
36 #include "src/sksl/ir/SkSLProgram.h"
37
38 #include <atomic>
•39
40 using namespace skia_private;
41
42 namespace skgpu::graphite {
43
44 namespace {
45
46 inline wgpu::VertexFormat attribute_type_to_dawn(VertexAttribType type) {
47 switch (type) {
48 case VertexAttribType::kFloat:
49 return wgpu::VertexFormat::Float32;
50 case VertexAttribType::kFloat2:
51 return wgpu::VertexFormat::Float32x2;
52 case VertexAttribType::kFloat3:
53 return wgpu::VertexFormat::Float32x3;
54 case VertexAttribType::kFloat4:
55 return wgpu::VertexFormat::Float32x4;
56 case VertexAttribType::kHalf2:
57 return wgpu::VertexFormat::Float16x2;
58 case VertexAttribType::kHalf4:
59 return wgpu::VertexFormat::Float16x4;
60 case VertexAttribType::kInt2:
61 return wgpu::VertexFormat::Sint32x2;
62 case VertexAttribType::kInt3:
63 return wgpu::VertexFormat::Sint32x3;
64 case VertexAttribType::kInt4:
65 return wgpu::VertexFormat::Sint32x4;
66 case VertexAttribType::kUInt2:
67 return wgpu::VertexFormat::Uint32x2;
68 case VertexAttribType::kByte2:
69 return wgpu::VertexFormat::Sint8x2;
70 case VertexAttribType::kByte4:
71 return wgpu::VertexFormat::Sint8x4;
72 case VertexAttribType::kUByte2:
73 return wgpu::VertexFormat::Uint8x2;
74 case VertexAttribType::kUByte4:
75 return wgpu::VertexFormat::Uint8x4;
76 case VertexAttribType::kUByte4_norm:
77 return wgpu::VertexFormat::Unorm8x4;
78 case VertexAttribType::kShort2:
79 return wgpu::VertexFormat::Sint16x2;
80 case VertexAttribType::kShort4:
81 return wgpu::VertexFormat::Sint16x4;
82 case VertexAttribType::kUShort2:
83 return wgpu::VertexFormat::Uint16x2;
84 case VertexAttribType::kUShort2_norm:
85 return wgpu::VertexFormat::Unorm16x2;
86 case VertexAttribType::kInt:
87 return wgpu::VertexFormat::Sint32;
88 case VertexAttribType::kUInt:
89 return wgpu::VertexFormat::Uint32;
90 case VertexAttribType::kUShort4_norm:
91 return wgpu::VertexFormat::Unorm16x4;
92 case VertexAttribType::kHalf:
93 case VertexAttribType::kByte:
94 case VertexAttribType::kUByte:
95 case VertexAttribType::kUByte_norm:
96 case VertexAttribType::kUShort_norm:
97 // Not supported.
98 break;
99 }
100 SkUNREACHABLE;
101 }
102
103 wgpu::CompareFunction compare_op_to_dawn(CompareOp op) {
104 switch (op) {
105 case CompareOp::kAlways:
106 return wgpu::CompareFunction::Always;
107 case CompareOp::kNever:
108 return wgpu::CompareFunction::Never;
109 case CompareOp::kGreater:
110 return wgpu::CompareFunction::Greater;
111 case CompareOp::kGEqual:
112 return wgpu::CompareFunction::GreaterEqual;
113 case CompareOp::kLess:
114 return wgpu::CompareFunction::Less;
115 case CompareOp::kLEqual:
116 return wgpu::CompareFunction::LessEqual;
117 case CompareOp::kEqual:
118 return wgpu::CompareFunction::Equal;
119 case CompareOp::kNotEqual:
120 return wgpu::CompareFunction::NotEqual;
121 }
122 SkUNREACHABLE;
123 }
124
125 wgpu::StencilOperation stencil_op_to_dawn(StencilOp op) {
126 switch (op) {
127 case StencilOp::kKeep:
128 return wgpu::StencilOperation::Keep;
129 case StencilOp::kZero:
130 return wgpu::StencilOperation::Zero;
131 case StencilOp::kReplace:
132 return wgpu::StencilOperation::Replace;
133 case StencilOp::kInvert:
134 return wgpu::StencilOperation::Invert;
135 case StencilOp::kIncWrap:
136 return wgpu::StencilOperation::IncrementWrap;
137 case StencilOp::kDecWrap:
138 return wgpu::StencilOperation::DecrementWrap;
139 case StencilOp::kIncClamp:
140 return wgpu::StencilOperation::IncrementClamp;
141 case StencilOp::kDecClamp:
142 return wgpu::StencilOperation::DecrementClamp;
143 }
144 SkUNREACHABLE;
145 }
146
147 wgpu::StencilFaceState stencil_face_to_dawn(DepthStencilSettings::Face face) {
148 wgpu::StencilFaceState state;
149 state.compare = compare_op_to_dawn(face.fCompareOp);
150 state.failOp = stencil_op_to_dawn(face.fStencilFailOp);
151 state.depthFailOp = stencil_op_to_dawn(face.fDepthFailOp);
152 state.passOp = stencil_op_to_dawn(face.fDepthStencilPassOp);
153 return state;
154 }
155
156 size_t create_vertex_attributes(SkSpan<const Attribute> attrs,
157 int shaderLocationOffset,
•158 TArray<wgpu::VertexAttribute>* out) {
159 SkASSERT(out && out->empty());
160 out->resize(attrs.size());
161 size_t vertexAttributeOffset = 0;
162 int attributeIndex = 0;
163 for (const auto& attr : attrs) {
164 wgpu::VertexAttribute& vertexAttribute = (*out)[attributeIndex];
165 vertexAttribute.format = attribute_type_to_dawn(attr.cpuType());
166 vertexAttribute.offset = vertexAttributeOffset;
167 vertexAttribute.shaderLocation = shaderLocationOffset + attributeIndex;
168 vertexAttributeOffset += attr.sizeAlign4();
169 attributeIndex++;
170 }
171 return vertexAttributeOffset;
172 }
173
174 // TODO: share this w/ Ganesh dawn backend?
175 static wgpu::BlendFactor blend_coeff_to_dawn_blend(const DawnCaps& caps, skgpu::BlendCoeff coeff) {
176 #if defined(__EMSCRIPTEN__)
177 #define VALUE_IF_DSB_OR_ZERO(VALUE) wgpu::BlendFactor::Zero
178 #else
179 #define VALUE_IF_DSB_OR_ZERO(VALUE) \
180 ((caps.shaderCaps()->fDualSourceBlendingSupport) ? (VALUE) : wgpu::BlendFactor::Zero)
181 #endif
182 switch (coeff) {
183 case skgpu::BlendCoeff::kZero:
184 return wgpu::BlendFactor::Zero;
185 case skgpu::BlendCoeff::kOne:
186 return wgpu::BlendFactor::One;
187 case skgpu::BlendCoeff::kSC:
188 return wgpu::BlendFactor::Src;
189 case skgpu::BlendCoeff::kISC:
190 return wgpu::BlendFactor::OneMinusSrc;
191 case skgpu::BlendCoeff::kDC:
192 return wgpu::BlendFactor::Dst;
193 case skgpu::BlendCoeff::kIDC:
194 return wgpu::BlendFactor::OneMinusDst;
195 case skgpu::BlendCoeff::kSA:
196 return wgpu::BlendFactor::SrcAlpha;
197 case skgpu::BlendCoeff::kISA:
198 return wgpu::BlendFactor::OneMinusSrcAlpha;
199 case skgpu::BlendCoeff::kDA:
200 return wgpu::BlendFactor::DstAlpha;
201 case skgpu::BlendCoeff::kIDA:
202 return wgpu::BlendFactor::OneMinusDstAlpha;
203 case skgpu::BlendCoeff::kConstC:
204 return wgpu::BlendFactor::Constant;
205 case skgpu::BlendCoeff::kIConstC:
206 return wgpu::BlendFactor::OneMinusConstant;
207 case skgpu::BlendCoeff::kS2C:
208 return VALUE_IF_DSB_OR_ZERO(wgpu::BlendFactor::Src1);
209 case skgpu::BlendCoeff::kIS2C:
210 return VALUE_IF_DSB_OR_ZERO(wgpu::BlendFactor::OneMinusSrc1);
211 case skgpu::BlendCoeff::kS2A:
212 return VALUE_IF_DSB_OR_ZERO(wgpu::BlendFactor::Src1Alpha);
213 case skgpu::BlendCoeff::kIS2A:
214 return VALUE_IF_DSB_OR_ZERO(wgpu::BlendFactor::OneMinusSrc1Alpha);
215 case skgpu::BlendCoeff::kIllegal:
216 return wgpu::BlendFactor::Zero;
217 }
218 SkUNREACHABLE;
219 #undef VALUE_IF_DSB_OR_ZERO
220 }
221
222 static wgpu::BlendFactor blend_coeff_to_dawn_blend_for_alpha(const DawnCaps& caps,
223 skgpu::BlendCoeff coeff) {
224 switch (coeff) {
225 // Force all srcColor used in alpha slot to alpha version.
226 case skgpu::BlendCoeff::kSC:
227 return wgpu::BlendFactor::SrcAlpha;
228 case skgpu::BlendCoeff::kISC:
229 return wgpu::BlendFactor::OneMinusSrcAlpha;
230 case skgpu::BlendCoeff::kDC:
231 return wgpu::BlendFactor::DstAlpha;
232 case skgpu::BlendCoeff::kIDC:
233 return wgpu::BlendFactor::OneMinusDstAlpha;
234 default:
235 return blend_coeff_to_dawn_blend(caps, coeff);
236 }
237 }
238
239 // TODO: share this w/ Ganesh Metal backend?
240 static wgpu::BlendOperation blend_equation_to_dawn_blend_op(skgpu::BlendEquation equation) {
241 static const wgpu::BlendOperation gTable[] = {
242 wgpu::BlendOperation::Add, // skgpu::BlendEquation::kAdd
243 wgpu::BlendOperation::Subtract, // skgpu::BlendEquation::kSubtract
244 wgpu::BlendOperation::ReverseSubtract, // skgpu::BlendEquation::kReverseSubtract
245 };
246 static_assert(std::size(gTable) == (int)skgpu::BlendEquation::kFirstAdvanced);
247 static_assert(0 == (int)skgpu::BlendEquation::kAdd);
248 static_assert(1 == (int)skgpu::BlendEquation::kSubtract);
249 static_assert(2 == (int)skgpu::BlendEquation::kReverseSubtract);
250
251 SkASSERT((unsigned)equation < skgpu::kBlendEquationCnt);
252 return gTable[(int)equation];
253 }
254
255 struct AsyncPipelineCreationBase {
256 AsyncPipelineCreationBase(const UniqueKey& key) : fKey(key) {}
257
258 wgpu::RenderPipeline fRenderPipeline;
259 std::atomic<bool> fFinished = false;
260 UniqueKey fKey; // for logging the wait to resolve a Pipeline future in dawnRenderPipeline
261 #if SK_HISTOGRAMS_ENABLED
262 // We need these three for the Graphite.PipelineCreationTimes.* histograms (cf.
263 // log_pipeline_creation)
264 skgpu::StdSteadyClock::time_point fStartTime;
265 bool fFromPrecompile;
266 bool fAsynchronous = false;
267 #endif
268 };
269
270 void log_pipeline_creation(const AsyncPipelineCreationBase* apcb) {
271 #if SK_HISTOGRAMS_ENABLED
272 [[maybe_unused]] static constexpr int kBucketCount = 100;
273 [[maybe_unused]] static constexpr int kOneSecInUS = 1000000;
274
275 SkASSERT(apcb->fFinished);
276
277 if (!apcb->fRenderPipeline) {
278 // A null fRenderPipeline means Pipeline creation failed
279 return; // TODO: log failures to their own UMA stat
280 }
281
282 [[maybe_unused]] auto micros_since = [](skgpu::StdSteadyClock::time_point start) {
283 skgpu::StdSteadyClock::duration elapsed = skgpu::StdSteadyClock::now() - start;
284 return std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
285 };
286
287 if (apcb->fFromPrecompile) {
288 SkASSERT(!apcb->fAsynchronous); // precompile is done synchronously on a thread
289 SK_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES(
290 "Graphite.PipelineCreationTimes.Precompile",
291 micros_since(apcb->fStartTime),
292 /* minUSec= */ 1,
293 /* maxUSec= */ kOneSecInUS,
294 kBucketCount);
295 } else if (apcb->fAsynchronous) {
296 SK_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES(
297 "Graphite.PipelineCreationTimes.Asynchronous",
298 micros_since(apcb->fStartTime),
299 /* minUSec= */ 1,
300 /* maxUSec= */ kOneSecInUS,
301 kBucketCount);
302 } else {
303 SK_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES(
304 "Graphite.PipelineCreationTimes.Synchronous",
305 micros_since(apcb->fStartTime),
306 /* minUSec= */ 1,
307 /* maxUSec= */ kOneSecInUS,
308 kBucketCount);
309 }
310 #endif // SK_HISTOGRAMS_ENABLED
311 }
312
313 } // anonymous namespace
314
315 #if defined(__EMSCRIPTEN__)
316 // For wasm, we don't use async compilation.
317 struct DawnGraphicsPipeline::AsyncPipelineCreation : public AsyncPipelineCreationBase {
318 AsyncPipelineCreation(const UniqueKey& key) : AsyncPipelineCreationBase(key) {}
319 };
320 #else
321 struct DawnGraphicsPipeline::AsyncPipelineCreation : public AsyncPipelineCreationBase {
322 AsyncPipelineCreation(const UniqueKey& key) : AsyncPipelineCreationBase(key) {}
323
324 wgpu::Future fFuture;
325 };
326 #endif
327
328 // static
329 sk_sp<DawnGraphicsPipeline> DawnGraphicsPipeline::Make(
330 const DawnSharedContext* sharedContext,
331 const RuntimeEffectDictionary* runtimeDict,
332 const UniqueKey& pipelineKey,
333 const GraphicsPipelineDesc& pipelineDesc,
334 const RenderPassDesc& renderPassDesc,
335 SkEnumBitMask<PipelineCreationFlags> pipelineCreationFlags,
336 uint32_t compilationID) {
337 const DawnCaps& caps = *static_cast<const DawnCaps*>(sharedContext->caps());
338 const auto& device = sharedContext->device();
339
340 SkSL::Program::Interface vsInterface, fsInterface;
341
342 SkSL::ProgramSettings settings;
343 settings.fSharpenTextures = true;
344 settings.fForceNoRTFlip = true;
345 // TODO(michaelludwig): Set this to false when "shader-f16" is available.
346 settings.fForceHighPrecision = true;
347
348 ShaderErrorHandler* errorHandler = caps.shaderErrorHandler();
349
350 const RenderStep* step = sharedContext->rendererProvider()->lookup(pipelineDesc.renderStepID());
351
352 SkSL::NativeShader vsCode, fsCode;
353 wgpu::ShaderModule fsModule, vsModule;
354
355 // Some steps just render depth buffer but not color buffer, so the fragment
356 // shader is null.
357 UniquePaintParamsID paintID = pipelineDesc.paintParamsID();
358
359 skia_private::TArray<SamplerDesc>* samplerDescArrPtr = nullptr;
360 #if !defined(__EMSCRIPTEN__)
361 skia_private::TArray<SamplerDesc> samplerDescArr {};
362 samplerDescArrPtr = &samplerDescArr;
363 #endif
364
365 std::unique_ptr<ShaderInfo> shaderInfo =
366 ShaderInfo::Make(&caps,
367 sharedContext->shaderCodeDictionary(),
368 runtimeDict,
369 renderPassDesc,
370 step,
371 paintID,
372 samplerDescArrPtr);
373
374 const std::string& fsSkSL = shaderInfo->fragmentSkSL();
375 const BlendInfo& blendInfo = shaderInfo->blendInfo();
376 const int numTexturesAndSamplers = shaderInfo->numFragmentTexturesAndSamplers();
377
378 const bool hasFragmentSkSL = !fsSkSL.empty();
379 if (hasFragmentSkSL) {
380 if (!skgpu::SkSLToWGSL(caps.shaderCaps(),
381 fsSkSL,
382 SkSL::ProgramKind::kGraphiteFragment,
383 settings,
384 &fsCode,
385 &fsInterface,
386 errorHandler)) {
387 return {};
388 }
389 if (!DawnCompileWGSLShaderModule(sharedContext, shaderInfo->fsLabel().c_str(), fsCode,
390 &fsModule, errorHandler)) {
391 return {};
392 }
393 }
394
395 const std::string& vsSkSL = shaderInfo->vertexSkSL();
396 if (!skgpu::SkSLToWGSL(caps.shaderCaps(),
397 vsSkSL,
398 SkSL::ProgramKind::kGraphiteVertex,
399 settings,
400 &vsCode,
401 &vsInterface,
402 errorHandler)) {
403 return {};
404 }
405 if (!DawnCompileWGSLShaderModule(sharedContext, shaderInfo->vsLabel().c_str(), vsCode,
406 &vsModule, errorHandler)) {
407 return {};
408 }
409
410 wgpu::RenderPipelineDescriptor descriptor;
411 // Always set the label for pipelines, dawn may need it for tracing.
412 descriptor.label = shaderInfo->pipelineLabel().c_str();
413
414 // Fragment state
415 skgpu::BlendEquation equation = blendInfo.fEquation;
416 skgpu::BlendCoeff srcCoeff = blendInfo.fSrcBlend;
417 skgpu::BlendCoeff dstCoeff = blendInfo.fDstBlend;
418 bool blendOn = !skgpu::BlendShouldDisable(equation, srcCoeff, dstCoeff);
419
420 wgpu::BlendState blend;
421 if (blendOn) {
422 blend.color.operation = blend_equation_to_dawn_blend_op(equation);
423 blend.color.srcFactor = blend_coeff_to_dawn_blend(caps, srcCoeff);
424 blend.color.dstFactor = blend_coeff_to_dawn_blend(caps, dstCoeff);
425 blend.alpha.operation = blend_equation_to_dawn_blend_op(equation);
426 blend.alpha.srcFactor = blend_coeff_to_dawn_blend_for_alpha(caps, srcCoeff);
427 blend.alpha.dstFactor = blend_coeff_to_dawn_blend_for_alpha(caps, dstCoeff);
428 }
429
430 wgpu::ColorTargetState colorTarget;
431 colorTarget.format = TextureFormatToDawnFormat(renderPassDesc.fColorAttachment.fFormat);
432 colorTarget.blend = blendOn ? &blend : nullptr;
433 colorTarget.writeMask = blendInfo.fWritesColor && hasFragmentSkSL ? wgpu::ColorWriteMask::All
434 : wgpu::ColorWriteMask::None;
435
436 #if !defined(__EMSCRIPTEN__)
437 const bool loadMsaaFromResolve =
438 renderPassDesc.fColorResolveAttachment.fFormat != TextureFormat::kUnsupported &&
439 renderPassDesc.fColorResolveAttachment.fLoadOp == LoadOp::kLoad;
440 // Special case: a render pass loading resolve texture requires additional settings for the
441 // pipeline to make it compatible.
442 wgpu::ColorTargetStateExpandResolveTextureDawn pipelineMSAALoadResolveTextureDesc;
443 if (loadMsaaFromResolve && sharedContext->dawnCaps()->loadOpAffectsMSAAPipelines()) {
444 SkASSERT(device.HasFeature(wgpu::FeatureName::DawnLoadResolveTexture));
445 colorTarget.nextInChain = &pipelineMSAALoadResolveTextureDesc;
446 pipelineMSAALoadResolveTextureDesc.enabled = true;
447 }
448 #endif
449
450 wgpu::FragmentState fragment;
451 // Dawn doesn't allow having a color attachment but without fragment shader, so have to use a
452 // noop fragment shader, if fragment shader is null.
453 fragment.module = hasFragmentSkSL ? std::move(fsModule) : sharedContext->noopFragment();
454 fragment.entryPoint = "main";
455 fragment.constantCount = 0;
456 fragment.constants = nullptr;
457 fragment.targetCount = 1;
458 fragment.targets = &colorTarget;
459 descriptor.fragment = &fragment;
460
461 // Depth stencil state
462 const auto& depthStencilSettings = step->depthStencilSettings();
463 SkASSERT(depthStencilSettings.fDepthTestEnabled ||
464 depthStencilSettings.fDepthCompareOp == CompareOp::kAlways);
465 TextureFormat dsFormat = renderPassDesc.fDepthStencilAttachment.fFormat;
466 wgpu::DepthStencilState depthStencil;
467 if (dsFormat != TextureFormat::kUnsupported) {
468 SkASSERT(TextureFormatIsDepthOrStencil(dsFormat));
469 depthStencil.format = TextureFormatToDawnFormat(dsFormat);
470 if (depthStencilSettings.fDepthTestEnabled) {
471 depthStencil.depthWriteEnabled = depthStencilSettings.fDepthWriteEnabled;
472 }
473 depthStencil.depthCompare = compare_op_to_dawn(depthStencilSettings.fDepthCompareOp);
474
475 // Dawn validation fails if the stencil state is non-default and the
476 // format doesn't have the stencil aspect.
477 if (TextureFormatHasStencil(dsFormat) && depthStencilSettings.fStencilTestEnabled) {
478 depthStencil.stencilFront = stencil_face_to_dawn(depthStencilSettings.fFrontStencil);
479 depthStencil.stencilBack = stencil_face_to_dawn(depthStencilSettings.fBackStencil);
480 depthStencil.stencilReadMask = depthStencilSettings.fFrontStencil.fReadMask;
481 depthStencil.stencilWriteMask = depthStencilSettings.fFrontStencil.fWriteMask;
482 }
483
484 descriptor.depthStencil = &depthStencil;
485 }
486
487 // Determine the BindGroupLayouts that will be used to make up the pipeline layout.
488 BindGroupLayouts groupLayouts;
489 // If immutable samplers are used with this pipeline, they must be included in the pipeline
490 // layout and passed in to the pipline constructor for lifetime management.
491 skia_private::TArray<sk_sp<DawnSampler>> immutableSamplers;
492 {
493 groupLayouts[0] = sharedContext->getUniformBuffersBindGroupLayout();
494 if (!groupLayouts[0]) {
495 return {};
496 }
497
498 bool hasFragmentSamplers = hasFragmentSkSL && numTexturesAndSamplers > 0;
499 if (hasFragmentSamplers) {
500 // Check if we can optimize for the common case of a single texture + 1 dynamic sampler
501 if (numTexturesAndSamplers == 2 &&
502 !(samplerDescArrPtr && samplerDescArrPtr->at(0).isImmutable())) {
503 groupLayouts[1] = sharedContext->getSingleTextureSamplerBindGroupLayout();
504 } else {
•505 TArray<wgpu::BindGroupLayoutEntry> entries;
506 entries.reset(numTexturesAndSamplers);
507
508 #if !defined(__EMSCRIPTEN__)
509 // Static sampler layouts are passed into Dawn by address and therefore must stay
510 // alive until the BindGroupLayoutDescriptor is created. So, store them outside of
•511 // the loop that iterates over each BindGroupLayoutEntry. Use a TBlockList so that
512 // any append StaticSamplerBindingLayouts have a stable address in case we have to
513 // grow the collection.
514 SkTBlockList<wgpu::StaticSamplerBindingLayout, 1> staticSamplerLayouts;
515
516 // Note that the number of samplers is equivalent to numTexturesAndSamplers / 2. So,
517 // a sampler's index within any container that only pertains to sampler information
518 // (as in, excludes textures) is equivalent to 1/2 of that sampler's binding index
519 // within the BindGroupLayout. Assert that we have analyzed the appropriate number
520 // of samplers by equating samplerDescArr size to sampler quantity.
521 SkASSERT(samplerDescArrPtr && samplerDescArr.size() == numTexturesAndSamplers / 2);
522 immutableSamplers.reset(samplerDescArr.size());
523 #endif
524
525 for (int i = 0; i < numTexturesAndSamplers;) {
526 entries[i].binding = i;
527 entries[i].visibility = wgpu::ShaderStage::Fragment;
528 #if !defined(__EMSCRIPTEN__)
529 // Index of sampler information = 1/2 of cumulative texture and sampler index.
530 // If we have a non-default-initialized SamplerDesc at that index,
531 // fetch an immutable sampler that matches that description to include in the
532 // pipeline layout.
533 const SamplerDesc& samplerDesc = samplerDescArr.at(i/2);
534 if (samplerDesc.isImmutable()) {
535 DawnThreadSafeResourceProvider* resourceProvider =
536 sharedContext->threadSafeResourceProvider();
537 sk_sp<Sampler> immutableSampler =
538 resourceProvider->findOrCreateCompatibleSampler(samplerDesc);
539 if (!immutableSampler) {
540 SKGPU_LOG_E("Failed to find/create immutable sampler for pipeline");
541 return {};
542 }
543 sk_sp<DawnSampler> dawnImmutableSampler = sk_ref_sp<DawnSampler>(
544 static_cast<DawnSampler*>(immutableSampler.get()));
545 SkASSERT(dawnImmutableSampler);
546
547 wgpu::StaticSamplerBindingLayout& immutableSamplerBinding =
548 staticSamplerLayouts.emplace_back();
549 immutableSamplerBinding.sampler = dawnImmutableSampler->dawnSampler();
550 // Static samplers sample from the subsequent texture in the BindGroupLayout
551 immutableSamplerBinding.sampledTextureBinding = i + 1;
552
553 immutableSamplers[i/2] = std::move(dawnImmutableSampler);
554 entries[i].nextInChain = &immutableSamplerBinding;
555 } else {
556 #endif
557 entries[i].sampler.type = wgpu::SamplerBindingType::Filtering;
558 #if !defined(__EMSCRIPTEN__)
559 }
560 #endif
561 ++i;
562
563 entries[i].binding = i;
564 entries[i].visibility = wgpu::ShaderStage::Fragment;
565 entries[i].texture.sampleType = wgpu::TextureSampleType::Float;
566 entries[i].texture.viewDimension = wgpu::TextureViewDimension::e2D;
567 entries[i].texture.multisampled = false;
568 ++i;
569 }
570
571 wgpu::BindGroupLayoutDescriptor groupLayoutDesc;
572 if (sharedContext->caps()->setBackendLabels()) {
573 groupLayoutDesc.label = shaderInfo->vsLabel().c_str();
574 }
575 groupLayoutDesc.entryCount = entries.size();
576 groupLayoutDesc.entries = entries.data();
577 groupLayouts[1] = device.CreateBindGroupLayout(&groupLayoutDesc);
578 }
579 if (!groupLayouts[1]) {
580 return {};
581 }
582 }
583
584 wgpu::PipelineLayoutDescriptor layoutDesc;
585 if (sharedContext->caps()->setBackendLabels()) {
586 layoutDesc.label = shaderInfo->fsLabel().c_str();
587 }
588 layoutDesc.bindGroupLayoutCount =
589 hasFragmentSamplers ? groupLayouts.size() : groupLayouts.size() - 1;
590 layoutDesc.bindGroupLayouts = groupLayouts.data();
591 #if !defined(__EMSCRIPTEN__)
592 if (sharedContext->caps()
593 ->resourceBindingRequirements()
594 .fUsePushConstantsForIntrinsicConstants) {
595 layoutDesc.immediateSize = kIntrinsicUniformSize;
596 }
597 #endif
598 auto layout = device.CreatePipelineLayout(&layoutDesc);
599 if (!layout) {
600 return {};
601 }
602 descriptor.layout = std::move(layout);
603 }
604
605 // Vertex state
606 std::array<wgpu::VertexBufferLayout, kNumVertexBuffers> vertexBufferLayouts;
607 // Static data buffer layout
•608 TArray<wgpu::VertexAttribute> staticDataAttributes;
609 {
610 auto arrayStride = create_vertex_attributes(step->staticAttributes(),
611 0,
612 &staticDataAttributes);
613 auto& layout = vertexBufferLayouts[kStaticDataBufferIndex];
614 if (arrayStride) {
615 layout.arrayStride = arrayStride;
616 layout.stepMode = wgpu::VertexStepMode::Vertex;
617 layout.attributeCount = staticDataAttributes.size();
618 layout.attributes = staticDataAttributes.data();
619 } else {
620 layout.arrayStride = 0;
621 #if defined(__EMSCRIPTEN__)
622 layout.stepMode = wgpu::VertexStepMode::VertexBufferNotUsed;
623 #else
624 layout.stepMode = wgpu::VertexStepMode::Undefined;
625 #endif
626 layout.attributeCount = 0;
627 layout.attributes = nullptr;
628 }
629 }
630
631 // Append data buffer layout
•632 TArray<wgpu::VertexAttribute> appendDataAttributes;
633 {
634 // Note: the shaderLocationOffset in this function call needs to be the staticAttributeSize
635 auto arrayStride = create_vertex_attributes(step->appendAttributes(),
636 step->staticAttributes().size(),
637 &appendDataAttributes);
638 auto& layout = vertexBufferLayouts[kAppendDataBufferIndex];
639 if (arrayStride) {
640 layout.arrayStride = arrayStride;
641 layout.stepMode = step->appendsVertices() ? wgpu::VertexStepMode::Vertex :
642 wgpu::VertexStepMode::Instance;
643 layout.attributeCount = appendDataAttributes.size();
644 layout.attributes = appendDataAttributes.data();
645 } else {
646 layout.arrayStride = 0;
647 #if defined(__EMSCRIPTEN__)
648 layout.stepMode = wgpu::VertexStepMode::VertexBufferNotUsed;
649 #else
650 layout.stepMode = wgpu::VertexStepMode::Undefined;
651 #endif
652 layout.attributeCount = 0;
653 layout.attributes = nullptr;
654 }
655 }
656
657 auto& vertex = descriptor.vertex;
658 vertex.module = std::move(vsModule);
659 vertex.entryPoint = "main";
660 vertex.constantCount = 0;
661 vertex.constants = nullptr;
662 vertex.bufferCount = vertexBufferLayouts.size();
663 vertex.buffers = vertexBufferLayouts.data();
664
665 // Other state
666 descriptor.primitive.frontFace = wgpu::FrontFace::CCW;
667 descriptor.primitive.cullMode = wgpu::CullMode::None;
668 switch (step->primitiveType()) {
669 case PrimitiveType::kTriangles:
670 descriptor.primitive.topology = wgpu::PrimitiveTopology::TriangleList;
671 break;
672 case PrimitiveType::kTriangleStrip:
673 descriptor.primitive.topology = wgpu::PrimitiveTopology::TriangleStrip;
674 descriptor.primitive.stripIndexFormat = wgpu::IndexFormat::Uint16;
675 break;
676 case PrimitiveType::kPoints:
677 descriptor.primitive.topology = wgpu::PrimitiveTopology::PointList;
678 break;
679 }
680
681 // Multisampled state
682 descriptor.multisample.count = (uint8_t) renderPassDesc.fSampleCount;
683 descriptor.multisample.mask = 0xFFFFFFFF;
684 descriptor.multisample.alphaToCoverageEnabled = false;
685
686 const bool forPrecompilation =
687 SkToBool(pipelineCreationFlags & PipelineCreationFlags::kForPrecompilation);
688 // For Dawn, we want Precompilation to happen synchronously
689 const bool useAsync = caps.useAsyncPipelineCreation() && !forPrecompilation;
690
691 auto asyncCreation = std::make_unique<AsyncPipelineCreation>(pipelineKey);
692 #if SK_HISTOGRAMS_ENABLED
693 asyncCreation->fStartTime = skgpu::StdSteadyClock::now();
694 asyncCreation->fFromPrecompile = forPrecompilation;
695 asyncCreation->fAsynchronous = useAsync;
696 #endif
697
698 if (useAsync) {
699 #if defined(__EMSCRIPTEN__)
700 // We shouldn't use CreateRenderPipelineAsync in wasm.
701 SKGPU_LOG_F("CreateRenderPipelineAsync shouldn't be used in WASM");
702 #else
703 asyncCreation->fFuture = device.CreateRenderPipelineAsync(
704 &descriptor,
705 wgpu::CallbackMode::WaitAnyOnly,
706 [asyncCreationPtr = asyncCreation.get()](wgpu::CreatePipelineAsyncStatus status,
707 wgpu::RenderPipeline pipeline,
708 wgpu::StringView message) {
709 if (status != wgpu::CreatePipelineAsyncStatus::Success) {
710 SKGPU_LOG_E("Failed to create render pipeline (%d): %.*s",
711 static_cast<int>(status),
712 static_cast<int>(message.length),
713 message.data);
714 // invalidate AsyncPipelineCreation pointer to signal that this pipeline has
715 // failed.
716 asyncCreationPtr->fRenderPipeline = nullptr;
717 } else {
718 asyncCreationPtr->fRenderPipeline = std::move(pipeline);
719 }
720
721 asyncCreationPtr->fFinished = true;
722
723 log_pipeline_creation(asyncCreationPtr);
724 });
725 #endif
726 } else {
727 std::optional<DawnErrorChecker> errorChecker;
728 if (sharedContext->dawnCaps()->allowScopedErrorChecks()) {
729 errorChecker.emplace(sharedContext);
730 }
731 asyncCreation->fRenderPipeline = device.CreateRenderPipeline(&descriptor);
732 asyncCreation->fFinished = true;
733
734 if (errorChecker.has_value() && errorChecker->popErrorScopes() != DawnErrorType::kNoError) {
735 asyncCreation->fRenderPipeline = nullptr;
736 }
737
738 // Fail ASAP for synchronous pipeline creation so it affects the Recording snap instead of
739 // being detected later at insertRecording().
740 if (!asyncCreation->fRenderPipeline) {
741 return nullptr;
742 }
743
744 log_pipeline_creation(asyncCreation.get());
745 }
746
747 PipelineInfo pipelineInfo{ *shaderInfo, pipelineCreationFlags,
748 pipelineKey.hash(), compilationID };
749 #if defined(GPU_TEST_UTILS)
750 pipelineInfo.fNativeVertexShader = std::move(vsCode.fText);
751 pipelineInfo.fNativeFragmentShader = std::move(fsCode.fText);
752 #endif
753
754 return sk_sp<DawnGraphicsPipeline>(
755 new DawnGraphicsPipeline(sharedContext,
756 pipelineInfo,
757 shaderInfo->pipelineLabel(),
758 std::move(asyncCreation),
759 std::move(groupLayouts),
760 step->primitiveType(),
761 depthStencilSettings.fStencilReferenceValue,
762 std::move(immutableSamplers)));
763 }
764
765 DawnGraphicsPipeline::DawnGraphicsPipeline(
766 const skgpu::graphite::SharedContext* sharedContext,
767 const PipelineInfo& pipelineInfo,
768 std::string_view pipelineLabel,
769 std::unique_ptr<AsyncPipelineCreation> asyncCreationInfo,
770 BindGroupLayouts groupLayouts,
771 PrimitiveType primitiveType,
772 uint32_t refValue,
773 skia_private::TArray<sk_sp<DawnSampler>> immutableSamplers)
774 : GraphicsPipeline(sharedContext, pipelineInfo, pipelineLabel)
775 , fAsyncPipelineCreation(std::move(asyncCreationInfo))
776 , fGroupLayouts(std::move(groupLayouts))
777 , fPrimitiveType(primitiveType)
778 , fStencilReferenceValue(refValue)
779 , fImmutableSamplers(std::move(immutableSamplers)) {}
780
781 DawnGraphicsPipeline::~DawnGraphicsPipeline() {
782 this->freeGpuData();
783 }
784
785 void DawnGraphicsPipeline::freeGpuData() {
786 // Wait for async creation to finish before we can destroy this object.
787 (void)this->dawnRenderPipeline();
788 fAsyncPipelineCreation = nullptr;
789 }
790
791 bool DawnGraphicsPipeline::didAsyncCompilationFail() const {
792 return fAsyncPipelineCreation &&
793 fAsyncPipelineCreation->fFinished &&
794 !fAsyncPipelineCreation->fRenderPipeline;
795 }
796
797 const wgpu::RenderPipeline& DawnGraphicsPipeline::dawnRenderPipeline() const {
798 if (!fAsyncPipelineCreation) {
799 static const wgpu::RenderPipeline kNullPipeline = nullptr;
800 return kNullPipeline;
801 }
802 if (fAsyncPipelineCreation->fFinished) {
803 return fAsyncPipelineCreation->fRenderPipeline;
804 }
805 #if defined(__EMSCRIPTEN__)
806 // We shouldn't use CreateRenderPipelineAsync in wasm.
807 SKGPU_LOG_F("CreateRenderPipelineAsync shouldn't be used in WASM");
808 #else
809
810 #if defined(SK_PIPELINE_LIFETIME_LOGGING)
811 TRACE_EVENT_INSTANT2("skia.gpu",
812 TRACE_STR_STATIC("WaitBeginN"),
813 TRACE_EVENT_SCOPE_THREAD,
814 "key", fAsyncPipelineCreation->fKey.hash(),
815 "compilationID", this->getPipelineInfo().fCompilationID);
816 #endif
817
818 wgpu::FutureWaitInfo waitInfo{};
819 waitInfo.future = fAsyncPipelineCreation->fFuture;
820 const auto& instance = static_cast<const DawnSharedContext*>(sharedContext())->instance();
821
822 [[maybe_unused]] auto status =
823 instance.WaitAny(1, &waitInfo, /*timeoutNS=*/std::numeric_limits<uint64_t>::max());
824 SkASSERT(status == wgpu::WaitStatus::Success);
825 SkASSERT(waitInfo.completed);
826
827 #if defined(SK_PIPELINE_LIFETIME_LOGGING)
828 TRACE_EVENT_INSTANT2("skia.gpu",
829 TRACE_STR_STATIC("WaitEndN"),
830 TRACE_EVENT_SCOPE_THREAD,
831 "key", fAsyncPipelineCreation->fKey.hash(),
832 "compilationID", this->getPipelineInfo().fCompilationID);
833 #endif
834
835 #endif
836
837 return fAsyncPipelineCreation->fRenderPipeline;
838 }
839
840 } // namespace skgpu::graphite