Debian Codegraph @

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