Debian Codegraph @

src/gpu/graphite/dawn/DawnCommandBuffer.cpp

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
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/DawnCommandBuffer.h"
9
10 #include "include/gpu/graphite/TextureInfo.h"
11 #include "src/gpu/graphite/ContextUtils.h"
12 #include "src/gpu/graphite/Log.h"
13 #include "src/gpu/graphite/RenderPassDesc.h"
14 #include "src/gpu/graphite/TextureProxy.h"
15 #include "src/gpu/graphite/UniformManager.h"
16 #include "src/gpu/graphite/compute/DispatchGroup.h"
17 #include "src/gpu/graphite/dawn/DawnBuffer.h"
18 #include "src/gpu/graphite/dawn/DawnCaps.h"
19 #include "src/gpu/graphite/dawn/DawnComputePipeline.h"
20 #include "src/gpu/graphite/dawn/DawnGraphicsPipeline.h"
21 #include "src/gpu/graphite/dawn/DawnGraphiteUtils.h"
22 #include "src/gpu/graphite/dawn/DawnQueueManager.h"
23 #include "src/gpu/graphite/dawn/DawnSampler.h"
24 #include "src/gpu/graphite/dawn/DawnSharedContext.h"
25 #include "src/gpu/graphite/dawn/DawnTexture.h"
26
27 #if defined(__EMSCRIPTEN__)
28 #include <emscripten/version.h>
29
30 namespace wgpu {
31 using TexelCopyBufferInfo = ImageCopyBuffer;
32 using TexelCopyTextureInfo = ImageCopyTexture;
33 } // namespace wgpu
34 #endif
35
36 namespace skgpu::graphite {
37
38 // On emsdk before 3.1.48 the API for RenderPass and ComputePass timestamps was different
39 // and does not map to current webgpu. We check this in DawnCaps but we also must avoid
40 // naming the types from the new API because they aren't defined.
41 #if defined(__EMSCRIPTEN__) \
42 && ((__EMSCRIPTEN_major__ < 3) \
43 || (__EMSCRIPTEN_major__ == 3 && __EMSCRIPTEN_minor__ < 1) \
44 || (__EMSCRIPTEN_major__ == 3 && __EMSCRIPTEN_minor__ == 1 && __EMSCRIPTEN_tiny__ < 48))
45 #define WGPU_TIMESTAMP_WRITES_DEFINED 0
46 #else
47 #define WGPU_TIMESTAMP_WRITES_DEFINED 1
48 #endif
49
50 // DawnCommandBuffer
51 // ----------------------------------------------------------------------------
52 std::unique_ptr<DawnCommandBuffer> DawnCommandBuffer::Make(const DawnSharedContext* sharedContext,
53 DawnResourceProvider* resourceProvider) {
54 std::unique_ptr<DawnCommandBuffer> cmdBuffer(
55 new DawnCommandBuffer(sharedContext, resourceProvider));
56 if (!cmdBuffer->setNewCommandBufferResources()) {
57 return {};
58 }
59 return cmdBuffer;
60 }
61
62 DawnCommandBuffer::DawnCommandBuffer(const DawnSharedContext* sharedContext,
63 DawnResourceProvider* resourceProvider)
64 : CommandBuffer(Protected::kNo) // Dawn doesn't support protected memory
65 , fSharedContext(sharedContext)
66 , fResourceProvider(resourceProvider) {}
67
68 DawnCommandBuffer::~DawnCommandBuffer() {}
69
70 bool DawnCommandBuffer::startTimerQuery() {
71 wgpu::QuerySet querySet = std::move(fTimestampQuerySet);
72
73 auto buffer = fResourceProvider->findOrCreateDawnBuffer(2 * sizeof(uint64_t),
74 BufferType::kQuery,
75 AccessPattern::kHostVisible,
76 "TimerQuery");
77 if (!buffer) {
78 SKGPU_LOG_W("Failed to create buffer for resolving results, timer query will "
79 "not be reported.");
80 return false;
81 }
82 sk_sp<DawnBuffer> xferBuffer;
83 if (!fSharedContext->caps()->drawBufferCanBeMapped()) {
84 xferBuffer = fResourceProvider->findOrCreateDawnBuffer(2 * sizeof(uint64_t),
85 BufferType::kXferGpuToCpu,
86 AccessPattern::kHostVisible,
87 "TimerQueryXfer");
88 if (!xferBuffer) {
89 SKGPU_LOG_W("Failed to create buffer for transferring timestamp results, timer "
90 "query will not be reported.");
91 return false;
92 }
93 }
94 if (!querySet) {
95 wgpu::QuerySetDescriptor descriptor;
96 descriptor.count = 2;
97 descriptor.label = "Command Buffer Timer Query";
98 descriptor.type = wgpu::QueryType::Timestamp;
99 descriptor.nextInChain = nullptr;
100 querySet = fSharedContext->device().CreateQuerySet(&descriptor);
101 if (!querySet) {
102 SKGPU_LOG_W("Failed to create query set, timer query will not be reported.");
103 return false;
104 }
105 }
106
107 fTimestampQuerySet = std::move(querySet);
108 fTimestampQueryBuffer = std::move(buffer);
109 fTimestampQueryXferBuffer = std::move(xferBuffer);
110
111 if (fSharedContext->dawnCaps()->supportsCommandBufferTimestamps()) {
112 // In native Dawn we use the writeTimeStamp method on CommandBuffer to bracket
113 // the whole command buffer.
114 fCommandEncoder.WriteTimestamp(fTimestampQuerySet, 0);
115 } else {
116 // On WebGPU the best we can do is add timestamps to each render/compute pass as we record
117 // them. Since we don't know a priori how many passes there will be we write a begin
118 // timestamp on the first pass and an end on every pass, overwriting the second query in the
119 // set.
120 fWroteFirstPassTimestamps = false;
121 }
122
123 return true;
124 }
125
126 void DawnCommandBuffer::endTimerQuery() {
127 SkASSERT(fTimestampQuerySet);
128 SkASSERT(fTimestampQueryBuffer);
129 if (fSharedContext->dawnCaps()->supportsCommandBufferTimestamps()) {
130 fCommandEncoder.WriteTimestamp(fTimestampQuerySet, 1);
131 } else if (!fWroteFirstPassTimestamps) {
132 // If we didn't have any passes then we can't report anything.
133 fTimestampQueryBuffer = nullptr;
134 fTimestampQueryXferBuffer = nullptr;
135 return;
136 }
137 // This resolve covers both timestamp code paths (command encoder and render/compute pass).
138 fCommandEncoder.ResolveQuerySet(
139 fTimestampQuerySet, 0, 2, fTimestampQueryBuffer->dawnBuffer(), 0);
140 if (fTimestampQueryXferBuffer) {
141 SkASSERT(fTimestampQueryBuffer->size() == fTimestampQueryBuffer->size());
142 fCommandEncoder.CopyBufferToBuffer(fTimestampQueryBuffer->dawnBuffer(),
143 /*sourceOffset=*/0,
144 fTimestampQueryXferBuffer->dawnBuffer(),
145 /*destinationOffset=*/0,
146 /*size=*/fTimestampQueryBuffer->size());
147 fTimestampQueryBuffer.reset();
148 }
149 if (fSharedContext->caps()->bufferMapsAreAsync()) {
150 sk_sp<Buffer> buffer =
151 fTimestampQueryXferBuffer ? fTimestampQueryXferBuffer : fTimestampQueryBuffer;
152 this->addBuffersToAsyncMapOnSubmit({&buffer, 1});
153 }
154 }
155
156 std::optional<GpuStats> DawnCommandBuffer::gpuStats() {
157 auto& buffer = fTimestampQueryXferBuffer ? fTimestampQueryXferBuffer : fTimestampQueryBuffer;
158 if (!buffer) {
159 return {};
160 }
161 if (fSharedContext->caps()->bufferMapsAreAsync()) {
162 if (!buffer->isMapped()) {
163 return {};
164 }
165 }
166 uint64_t* results = static_cast<uint64_t*>(buffer->map());
167 if (!results) {
168 SKGPU_LOG_W("Failed to get timer query results because buffer couldn't be mapped.");
169 return {};
170 }
171 if (results[1] < results[0]) {
172 return {};
173 }
174 GpuStats stats;
175 stats.elapsedTime = results[1] - results[0];
176 return stats;
177 }
178
179 wgpu::CommandBuffer DawnCommandBuffer::finishEncoding() {
180 SkASSERT(fCommandEncoder);
181 wgpu::CommandBuffer cmdBuffer = fCommandEncoder.Finish();
182
183 fCommandEncoder = nullptr;
184
185 return cmdBuffer;
186 }
187
188 void DawnCommandBuffer::onResetCommandBuffer() {
189 fActiveGraphicsPipeline = nullptr;
190 fActiveRenderPassEncoder = nullptr;
191 fActiveComputePassEncoder = nullptr;
192 fCommandEncoder = nullptr;
193
194 for (auto& bufferSlot : fBoundUniforms) {
195 bufferSlot = {};
196 }
197 fBoundUniformBuffersDirty = true;
198 if (fTimestampQueryBuffer && fTimestampQueryBuffer->isUnmappable()) {
199 fTimestampQueryBuffer->unmap();
200 }
201 if (fTimestampQueryXferBuffer && fTimestampQueryXferBuffer->isUnmappable()) {
202 fTimestampQueryXferBuffer->unmap();
203 }
204 fTimestampQueryBuffer = {};
205 fTimestampQueryXferBuffer = {};
206 fWroteFirstPassTimestamps = false;
207 }
208
209 bool DawnCommandBuffer::setNewCommandBufferResources() {
210 SkASSERT(!fCommandEncoder);
211 fCommandEncoder = fSharedContext->device().CreateCommandEncoder();
212 SkASSERT(fCommandEncoder);
213
214 return true;
215 }
216
217 // Requests a sampler. Dynamic samplers live in the global cache, requiring no tracking, but
218 // immutable samplers are created on the current graphics pipeline, and may outlive it, requiring
219 // further tracking.
220 const DawnSampler* DawnCommandBuffer::getSampler(
221 const DrawPassCommands::BindTexturesAndSamplers& command, int32_t index) {
222 auto desc = command.fSamplers[index];
223 if (desc.isImmutable()) {
224 const DawnSampler* immutableSampler = fActiveGraphicsPipeline->immutableSampler(index);
225 if (immutableSampler) {
226 this->trackCommandBufferResource(sk_ref_sp<Sampler>(immutableSampler));
227 }
228 return immutableSampler;
229 } else {
230 // Use the shared Sampler held in the global cache
231 return static_cast<const DawnSampler*>(
232 fSharedContext->globalCache()->getDynamicSampler(desc));
233 }
234 }
235
236 bool DawnCommandBuffer::onAddRenderPass(const RenderPassDesc& renderPassDesc,
237 SkIRect renderPassBounds,
238 const Texture* colorTexture,
239 const Texture* resolveTexture,
240 const Texture* depthStencilTexture,
241 SkIPoint resolveOffset,
242 SkIRect viewport,
243 const DrawPassList& drawPasses) {
244 // `viewport` has already been translated by the replay translation by the base CommandBuffer
245 if (!SkIRect::Intersects(viewport, fRenderPassBounds)) SK_UNLIKELY {
246 // The entire pass is offscreen
247 return true;
248 }
249
250
251 UniformManager intrinsicValues{Layout::kStd140};
252 CollectIntrinsicUniforms(fSharedContext->caps(), viewport, fDstReadBounds, &intrinsicValues);
253 const auto uniformData = UniformDataBlock::Wrap(&intrinsicValues);
254 const bool usePushConstant = fSharedContext->dawnCaps()
255 ->resourceBindingRequirements()
256 .fUsePushConstantsForIntrinsicConstants;
257
258 // If push constant is not supported, update the intrinsic constant buffer before starting a
259 // render pass.
260 if (!usePushConstant && !this->updateIntrinsicUniformsAsUBO(uniformData)) SK_UNLIKELY {
261 return false;
262 }
263
264 if (!this->beginRenderPass(renderPassDesc,
265 resolveOffset,
266 renderPassBounds,
267 colorTexture,
268 resolveTexture,
269 depthStencilTexture)) SK_UNLIKELY {
270 return false;
271 }
272
273 // If push constant is supported, update the intrinsic constants after starting a render pass.
274 if (usePushConstant && !this->updateIntrinsicUniformsAsPushConstant(uniformData)) SK_UNLIKELY {
275 return false;
276 }
277
278 this->setViewport(viewport);
279
280 for (const auto& drawPass : drawPasses) {
281 if (!this->addDrawPass(drawPass.get())) SK_UNLIKELY {
282 this->endRenderPass();
283 return false;
284 }
285 }
286
287 return this->endRenderPass();
288 }
289
290 bool DawnCommandBuffer::onAddComputePass(DispatchGroupSpan groups) {
291 this->beginComputePass();
292 for (const auto& group : groups) {
293 group->addResourceRefs(this);
294 for (const auto& dispatch : group->dispatches()) {
295 this->bindComputePipeline(group->getPipeline(dispatch.fPipelineIndex));
296 this->bindDispatchResources(*group, dispatch);
297 if (const WorkgroupSize* globalSize =
298 std::get_if<WorkgroupSize>(&dispatch.fGlobalSizeOrIndirect)) {
299 this->dispatchWorkgroups(*globalSize);
300 } else {
301 SkASSERT(std::holds_alternative<BindBufferInfo>(dispatch.fGlobalSizeOrIndirect));
302 const BindBufferInfo& indirect =
303 *std::get_if<BindBufferInfo>(&dispatch.fGlobalSizeOrIndirect);
304 this->dispatchWorkgroupsIndirect(indirect.fBuffer, indirect.fOffset);
305 }
306 }
307 }
308 this->endComputePass();
309 return true;
310 }
311
312 bool DawnCommandBuffer::beginRenderPass(const RenderPassDesc& renderPassDesc,
313 const SkIPoint& resolveOffset,
314 SkIRect renderPassBounds,
315 const Texture* colorTexture,
316 const Texture* resolveTexture,
317 const Texture* depthStencilTexture) {
318 SkASSERT(!fActiveRenderPassEncoder);
319 SkASSERT(!fActiveComputePassEncoder);
320
321 constexpr static wgpu::LoadOp wgpuLoadActionMap[]{
322 wgpu::LoadOp::Load,
323 wgpu::LoadOp::Clear,
324 wgpu::LoadOp::Clear // Don't care
325 };
326 static_assert((int)LoadOp::kLoad == 0);
327 static_assert((int)LoadOp::kClear == 1);
328 static_assert((int)LoadOp::kDiscard == 2);
329 static_assert(std::size(wgpuLoadActionMap) == kLoadOpCount);
330
331 constexpr static wgpu::StoreOp wgpuStoreActionMap[]{wgpu::StoreOp::Store,
332 wgpu::StoreOp::Discard};
333 static_assert((int)StoreOp::kStore == 0);
334 static_assert((int)StoreOp::kDiscard == 1);
335 static_assert(std::size(wgpuStoreActionMap) == kStoreOpCount);
336
337 wgpu::RenderPassDescriptor wgpuRenderPass = {};
338 wgpu::RenderPassColorAttachment wgpuColorAttachment;
339 wgpu::RenderPassDepthStencilAttachment wgpuDepthStencilAttachment;
340
341 // Set up color attachment.
342 #if !defined(__EMSCRIPTEN__)
343 wgpu::DawnRenderPassSampleCount mssaRenderToSingleSampledDesc;
344 wgpu::RenderPassDescriptorResolveRect wgpuPartialRect = {};
345 #endif
346
347 #if WGPU_TIMESTAMP_WRITES_DEFINED
348 #if defined(__EMSCRIPTEN__)
349 wgpu::RenderPassTimestampWrites wgpuTimestampWrites;
350 #else
351 wgpu::PassTimestampWrites wgpuTimestampWrites;
352 #endif
353 if (!fSharedContext->dawnCaps()->supportsCommandBufferTimestamps() && fTimestampQueryBuffer) {
354 SkASSERT(fTimestampQuerySet);
355 wgpuTimestampWrites.querySet = fTimestampQuerySet;
356 if (!fWroteFirstPassTimestamps) {
357 wgpuTimestampWrites.beginningOfPassWriteIndex = 0;
358 fWroteFirstPassTimestamps = true;
359 }
360 wgpuTimestampWrites.endOfPassWriteIndex = 1;
361 wgpuRenderPass.timestampWrites = &wgpuTimestampWrites;
362 }
363 #else
364 SkASSERT(!fTimestampQueryBuffer);
365 #endif
366
367 // Validate attachment descs and textures
368 const auto& colorInfo = renderPassDesc.fColorAttachment;
369 const auto& resolveInfo = renderPassDesc.fColorResolveAttachment;
370 const auto& depthStencilInfo = renderPassDesc.fDepthStencilAttachment;
371 SkASSERT(colorTexture ? colorInfo.isCompatible(colorTexture->textureInfo())
372 : colorInfo.fFormat == TextureFormat::kUnsupported);
373 SkASSERT(resolveTexture ? resolveInfo.isCompatible(resolveTexture->textureInfo())
374 : resolveInfo.fFormat == TextureFormat::kUnsupported);
375 SkASSERT(depthStencilTexture ? depthStencilInfo.isCompatible(depthStencilTexture->textureInfo())
376 : depthStencilInfo.fFormat == TextureFormat::kUnsupported);
377
378 // Set up color attachment
379 bool emulateLoadStoreResolveTexture = false;
380 if (colorTexture) {
381 wgpuRenderPass.colorAttachments = &wgpuColorAttachment;
382 wgpuRenderPass.colorAttachmentCount = 1;
383
384 const auto* dawnColorTexture = static_cast<const DawnTexture*>(colorTexture);
385 SkASSERT(dawnColorTexture->renderTextureView());
386 wgpuColorAttachment.view = dawnColorTexture->renderTextureView();
387
388 const std::array<float, 4>& clearColor = renderPassDesc.fClearColor;
389 wgpuColorAttachment.clearValue = {
390 clearColor[0], clearColor[1], clearColor[2], clearColor[3]};
391 wgpuColorAttachment.loadOp = wgpuLoadActionMap[static_cast<int>(colorInfo.fLoadOp)];
392 wgpuColorAttachment.storeOp = wgpuStoreActionMap[static_cast<int>(colorInfo.fStoreOp)];
393
394 // Set up resolve attachment
395 if (resolveTexture) {
396 SkASSERT(resolveInfo.fStoreOp == StoreOp::kStore);
397
398 const auto* dawnResolveTexture = static_cast<const DawnTexture*>(resolveTexture);
399 SkASSERT(dawnResolveTexture->renderTextureView());
400 wgpuColorAttachment.resolveTarget = dawnResolveTexture->renderTextureView();
401
402 // Inclusion of a resolve texture implies the client wants to finish the
403 // renderpass with a resolve.
404 SkASSERT(wgpuColorAttachment.storeOp == wgpu::StoreOp::Discard);
405 // But it also means we might have to load the resolve texture into the MSAA color attachment
406
407 if (fSharedContext->dawnCaps()->emulateLoadStoreResolve()) {
408 emulateLoadStoreResolveTexture = true;
409 } else if (resolveInfo.fLoadOp == LoadOp::kLoad) {
410 std::optional<wgpu::LoadOp> resolveLoadOp =
411 fSharedContext->dawnCaps()->resolveTextureLoadOp();
412 if (resolveLoadOp.has_value()) {
413 wgpuColorAttachment.loadOp = *resolveLoadOp;
414 } else {
415 // No Dawn built-in support, we need to manually load the resolve texture.
416 emulateLoadStoreResolveTexture = true;
417 }
418 }
419
420 if (!emulateLoadStoreResolveTexture) {
421 #if !defined(__EMSCRIPTEN__)
422 if (fSharedContext->dawnCaps()->supportsPartialLoadResolve()) {
423 SkIRect msaaArea = renderPassBounds;
424 SkAssertResult(msaaArea.intersect(SkIRect::MakeSize(
425 colorTexture->dimensions())));
426 wgpuPartialRect.colorOffsetX = msaaArea.x();
427 wgpuPartialRect.colorOffsetY = msaaArea.y();
428
429 SkIRect resolveArea = renderPassBounds;
430 resolveArea.offset(resolveOffset);
431 SkAssertResult(resolveArea.intersect(SkIRect::MakeSize(
432 resolveTexture->dimensions())));
433 wgpuPartialRect.resolveOffsetX = resolveArea.x();
434 wgpuPartialRect.resolveOffsetY = resolveArea.y();
435 wgpuPartialRect.width = resolveArea.width();
436 wgpuPartialRect.height = resolveArea.height();
437 wgpuRenderPass.nextInChain = &wgpuPartialRect;
438 } else
439 #endif
440 {
441 SkASSERT(resolveOffset.isZero());
442 }
443 }
444
445 // TODO: If the color resolve texture is read-only we can use a private (vs. memoryless)
446 // msaa attachment that's coupled to the framebuffer and the StoreAndMultisampleResolve
447 // action instead of loading as a draw.
448 } else {
449 [[maybe_unused]] bool isMSAAToSingleSampled =
450 renderPassDesc.fSampleCount > SampleCount::k1 &&
451 colorTexture->sampleCount() == SampleCount::k1;
452 #if defined(__EMSCRIPTEN__)
453 SkASSERT(!isMSAAToSingleSampled);
454 #else
455 if (isMSAAToSingleSampled) {
456 // If render pass is multi sampled but the color attachment is single sampled, we
457 // need to activate multisampled render to single sampled feature for this render
458 // pass.
459 SkASSERT(fSharedContext->device().HasFeature(
460 wgpu::FeatureName::MSAARenderToSingleSampled));
461
462 wgpuRenderPass.nextInChain = &mssaRenderToSingleSampledDesc;
463 mssaRenderToSingleSampledDesc.sampleCount = (uint8_t)renderPassDesc.fSampleCount;
464 }
465 #endif
466 }
467 }
468
469 // Set up stencil/depth attachment
470 if (depthStencilTexture) {
471 const auto* dawnDepthStencilTexture = static_cast<const DawnTexture*>(depthStencilTexture);
472
473 SkASSERT(dawnDepthStencilTexture->renderTextureView());
474 wgpuDepthStencilAttachment.view = dawnDepthStencilTexture->renderTextureView();
475
476 if (TextureFormatHasDepth(depthStencilInfo.fFormat)) {
477 wgpuDepthStencilAttachment.depthClearValue = renderPassDesc.fClearDepth;
478 wgpuDepthStencilAttachment.depthLoadOp =
479 wgpuLoadActionMap[static_cast<int>(depthStencilInfo.fLoadOp)];
480 wgpuDepthStencilAttachment.depthStoreOp =
481 wgpuStoreActionMap[static_cast<int>(depthStencilInfo.fStoreOp)];
482 }
483
484 if (TextureFormatHasStencil(depthStencilInfo.fFormat)) {
485 wgpuDepthStencilAttachment.stencilClearValue = renderPassDesc.fClearStencil;
486 wgpuDepthStencilAttachment.stencilLoadOp =
487 wgpuLoadActionMap[static_cast<int>(depthStencilInfo.fLoadOp)];
488 wgpuDepthStencilAttachment.stencilStoreOp =
489 wgpuStoreActionMap[static_cast<int>(depthStencilInfo.fStoreOp)];
490 }
491
492 wgpuRenderPass.depthStencilAttachment = &wgpuDepthStencilAttachment;
493 }
494
495 if (emulateLoadStoreResolveTexture) {
496 if (!this->emulateLoadMSAAFromResolveAndBeginRenderPassEncoder(
497 renderPassDesc,
498 wgpuRenderPass,
499 resolveOffset,
500 renderPassBounds,
501 static_cast<const DawnTexture*>(colorTexture),
502 static_cast<const DawnTexture*>(resolveTexture))) {
503 return false;
504 }
505 }
506 else {
507 fActiveRenderPassEncoder = fCommandEncoder.BeginRenderPass(&wgpuRenderPass);
508 }
509
510 return true;
511 }
512
513 bool DawnCommandBuffer::emulateLoadMSAAFromResolveAndBeginRenderPassEncoder(
514 const RenderPassDesc& intendedRenderPassDesc,
515 const wgpu::RenderPassDescriptor& intendedDawnRenderPassDesc,
516 const SkIPoint& resolveOffset,
517 const SkIRect& renderPassBounds,
518 const DawnTexture* msaaTexture,
519 const DawnTexture* resolveTexture) {
520 SkASSERT(!fActiveRenderPassEncoder);
521
522 const bool loadResolve =
523 intendedRenderPassDesc.fColorResolveAttachment.fLoadOp == LoadOp::kLoad;
524
525 // Override the render pass to exclude the resolve texture. We will emulate the loading &
526 // resolve via blit. The resovle step will be done separately after endRenderPass()
527 RenderPassDesc renderPassWithoutResolveDesc = intendedRenderPassDesc;
528 renderPassWithoutResolveDesc.fColorResolveAttachment = {};
529
530 wgpu::RenderPassColorAttachment dawnColorAttachmentWithoutResolve =
531 intendedDawnRenderPassDesc.colorAttachments[0];
532 dawnColorAttachmentWithoutResolve.resolveTarget = nullptr;
533 dawnColorAttachmentWithoutResolve.storeOp = wgpu::StoreOp::Store;
534
535 if (loadResolve) {
536 // If we intend to load the resolve texture, then override the loadOp of the MSAA attachment
537 // to Load instead of Clear.
538 // This path is intended to be used when the device doesn't support transient attachments.
539 // Which most likely means it is a non-tiled GPU. On non-tiled GPUs, load is a no-op so it
540 // should be faster than clearing the whole MSAA attachment. Note: Dawn doesn't have any
541 // DontCare loadOp.
542 dawnColorAttachmentWithoutResolve.loadOp = wgpu::LoadOp::Load;
543 }
544
545 wgpu::RenderPassDescriptor dawnRenderPassDescWithoutResolve = intendedDawnRenderPassDesc;
546 dawnRenderPassDescWithoutResolve.colorAttachments = &dawnColorAttachmentWithoutResolve;
547 dawnRenderPassDescWithoutResolve.colorAttachmentCount = 1;
548
549 auto renderPassEncoder = fCommandEncoder.BeginRenderPass(&dawnRenderPassDescWithoutResolve);
550
551 SkIRect msaaArea = renderPassBounds;
552 msaaArea.intersect(SkIRect::MakeSize(msaaTexture->dimensions()));
553 SkIRect resolveArea = renderPassBounds;
554 resolveArea.offset(resolveOffset);
555 resolveArea.intersect(SkIRect::MakeSize(resolveTexture->dimensions()));
556
557 if (loadResolve) {
558 // Blit from the resolve texture to the MSAA texture
559 if (!this->doBlitWithDraw(renderPassEncoder,
560 renderPassWithoutResolveDesc,
561 /*srcTextureView=*/resolveTexture->renderTextureView(),
562 /*srcSampleCount=*/SampleCount::k1,
563 /*srcOffset=*/resolveArea.topLeft(),
564 /*dstBounds=*/msaaArea)) {
565 renderPassEncoder.End();
566 return false;
567 }
568 }
569
570 fActiveRenderPassEncoder = renderPassEncoder;
571
572 fResolveStepEmulationInfo = {msaaTexture, resolveTexture, msaaArea.topLeft(), resolveArea};
573
574 return true;
575 }
576
577 bool DawnCommandBuffer::doBlitWithDraw(const wgpu::RenderPassEncoder& renderEncoder,
578 const RenderPassDesc& frontendRenderPassDescKey,
579 const wgpu::TextureView& srcTextureView,
580 SampleCount srcSampleCount,
581 const SkIPoint& srcOffset,
582 const SkIRect& dstBounds) {
583 DawnResourceProvider::BlitWithDrawEncoder blit =
584 fResourceProvider->findOrCreateBlitWithDrawEncoder(frontendRenderPassDescKey,
585 srcSampleCount);
586 if (!blit) {
587 SKGPU_LOG_E("Unable to create pipeline to blit with draw");
588 return false;
589 }
590
591 SkASSERT(renderEncoder);
592
593 blit.EncodeBlit(fSharedContext->device(), renderEncoder, srcTextureView, srcOffset, dstBounds);
594
595 return true;
596 }
597
598 bool DawnCommandBuffer::endRenderPass() {
599 SkASSERT(fActiveRenderPassEncoder);
600 fActiveRenderPassEncoder.End();
601 fActiveRenderPassEncoder = nullptr;
602
603 // Return early if no resolve step's emulation is needed.
604 if (!fResolveStepEmulationInfo.has_value()) {
605 return true;
606 }
607
608 // Creating an intermediate render pass to copy from the MSAA texture -> resolve texture.
609 RenderPassDesc intermediateRenderPassDesc = {};
610 intermediateRenderPassDesc.fColorAttachment = {
611 TextureInfoPriv::ViewFormat(fResolveStepEmulationInfo->fResolveTexture->textureInfo()),
612 LoadOp::kLoad,
613 StoreOp::kStore,
614 SampleCount::k1 };
615
616 wgpu::RenderPassColorAttachment dawnIntermediateColorAttachment;
617 dawnIntermediateColorAttachment.loadOp = wgpu::LoadOp::Load;
618 dawnIntermediateColorAttachment.storeOp = wgpu::StoreOp::Store;
619 dawnIntermediateColorAttachment.view =
620 fResolveStepEmulationInfo->fResolveTexture->renderTextureView();
621
622 wgpu::RenderPassDescriptor dawnIntermediateRenderPassDesc;
623 dawnIntermediateRenderPassDesc.colorAttachmentCount = 1;
624 dawnIntermediateRenderPassDesc.colorAttachments = &dawnIntermediateColorAttachment;
625
626 auto renderPassEncoder = fCommandEncoder.BeginRenderPass(&dawnIntermediateRenderPassDesc);
627
628 bool blitSucceeded = this->doBlitWithDraw(
629 renderPassEncoder,
630 intermediateRenderPassDesc,
631 /*srcTextureView=*/fResolveStepEmulationInfo->fMSAATexture->renderTextureView(),
632 /*srcSampleCount=*/fResolveStepEmulationInfo->fMSAATexture->textureInfo().sampleCount(),
633 /*srcOffset=*/fResolveStepEmulationInfo->fMSAAAOffset,
634 /*dstBounds=*/fResolveStepEmulationInfo->fResolveArea);
635
636 renderPassEncoder.End();
637
638 fResolveStepEmulationInfo.reset();
639
640 return blitSucceeded;
641 }
642
643 bool DawnCommandBuffer::addDrawPass(DrawPass* drawPass) {
644 // If there is gradient data to bind, it must be done prior to draws.
645 if (drawPass->floatStorageManager()->hasData()) {
646 this->bindUniformBuffer(drawPass->floatStorageManager()->getBufferInfo(),
647 UniformSlot::kGradient);
648 }
649
650 if (!drawPass->addResourceRefs(fResourceProvider, this)) SK_UNLIKELY {
651 return false;
652 }
653
654 for (auto [type, cmdPtr] : drawPass->commands()) {
655 switch (type) {
656 case DrawPassCommands::Type::kBindGraphicsPipeline: {
657 auto bgp = static_cast<DrawPassCommands::BindGraphicsPipeline*>(cmdPtr);
658 if (!this->bindGraphicsPipeline(drawPass->getPipeline(bgp->fPipelineIndex)))
659 SK_UNLIKELY { return false; }
660 break;
661 }
662 case DrawPassCommands::Type::kSetBlendConstants: {
663 auto sbc = static_cast<DrawPassCommands::SetBlendConstants*>(cmdPtr);
664 this->setBlendConstants(sbc->fBlendConstants);
665 break;
666 }
667 case DrawPassCommands::Type::kBindUniformBuffer: {
668 auto bub = static_cast<DrawPassCommands::BindUniformBuffer*>(cmdPtr);
669 this->bindUniformBuffer(bub->fInfo, bub->fSlot);
670 break;
671 }
672 case DrawPassCommands::Type::kBindStaticDataBuffer: {
673 auto bdb = static_cast<DrawPassCommands::BindStaticDataBuffer*>(cmdPtr);
674 this->bindInputBuffer(bdb->fStaticData.fBuffer, bdb->fStaticData.fOffset,
675 DawnGraphicsPipeline::kStaticDataBufferIndex);
676 break;
677 }
678 case DrawPassCommands::Type::kBindAppendDataBuffer: {
679 auto bdb = static_cast<DrawPassCommands::BindAppendDataBuffer*>(cmdPtr);
680 this->bindInputBuffer(bdb->fAppendData.fBuffer, bdb->fAppendData.fOffset,
681 DawnGraphicsPipeline::kAppendDataBufferIndex);
682 break;
683 }
684 case DrawPassCommands::Type::kBindIndexBuffer: {
685 auto bdb = static_cast<DrawPassCommands::BindIndexBuffer*>(cmdPtr);
686 this->bindIndexBuffer(
687 bdb->fIndices.fBuffer, bdb->fIndices.fOffset);
688 break;
689 }
690 case DrawPassCommands::Type::kBindIndirectBuffer: {
691 auto bdb = static_cast<DrawPassCommands::BindIndirectBuffer*>(cmdPtr);
692 this->bindIndirectBuffer(
693 bdb->fIndirect.fBuffer, bdb->fIndirect.fOffset);
694 break;
695 }
696 case DrawPassCommands::Type::kBindTexturesAndSamplers: {
697 auto bts = static_cast<DrawPassCommands::BindTexturesAndSamplers*>(cmdPtr);
698 this->bindTextureAndSamplers(*drawPass, *bts);
699 break;
700 }
701 case DrawPassCommands::Type::kSetScissor: {
702 auto ss = static_cast<DrawPassCommands::SetScissor*>(cmdPtr);
703 this->setScissor(ss->fScissor);
704 break;
705 }
706 case DrawPassCommands::Type::kDraw: {
707 auto draw = static_cast<DrawPassCommands::Draw*>(cmdPtr);
708 this->draw(draw->fType, draw->fBaseVertex, draw->fVertexCount);
709 break;
710 }
711 case DrawPassCommands::Type::kDrawIndexed: {
712 auto draw = static_cast<DrawPassCommands::DrawIndexed*>(cmdPtr);
713 this->drawIndexed(
714 draw->fType, draw->fBaseIndex, draw->fIndexCount, draw->fBaseVertex);
715 break;
716 }
717 case DrawPassCommands::Type::kDrawInstanced: {
718 auto draw = static_cast<DrawPassCommands::DrawInstanced*>(cmdPtr);
719 this->drawInstanced(draw->fType,
720 draw->fBaseVertex,
721 draw->fVertexCount,
722 draw->fBaseInstance,
723 draw->fInstanceCount);
724 break;
725 }
726 case DrawPassCommands::Type::kDrawIndexedInstanced: {
727 auto draw = static_cast<DrawPassCommands::DrawIndexedInstanced*>(cmdPtr);
728 this->drawIndexedInstanced(draw->fType,
729 draw->fBaseIndex,
730 draw->fIndexCount,
731 draw->fBaseVertex,
732 draw->fBaseInstance,
733 draw->fInstanceCount);
734 break;
735 }
736 case DrawPassCommands::Type::kDrawIndirect: {
737 auto draw = static_cast<DrawPassCommands::DrawIndirect*>(cmdPtr);
738 this->drawIndirect(draw->fType);
739 break;
740 }
741 case DrawPassCommands::Type::kDrawIndexedIndirect: {
742 auto draw = static_cast<DrawPassCommands::DrawIndexedIndirect*>(cmdPtr);
743 this->drawIndexedIndirect(draw->fType);
744 break;
745 }
746 case DrawPassCommands::Type::kAddBarrier: {
747 SKGPU_LOG_E("DawnCommandBuffer does not support the addition of barriers.");
748 break;
749 }
750 }
751 }
752
753 return true;
754 }
755
756 bool DawnCommandBuffer::bindGraphicsPipeline(const GraphicsPipeline* graphicsPipeline) {
757 SkASSERT(fActiveRenderPassEncoder);
758
759 auto* dawnGraphicsPipeline = static_cast<const DawnGraphicsPipeline*>(graphicsPipeline);
760 auto& wgpuPipeline = dawnGraphicsPipeline->dawnRenderPipeline();
761 if (!wgpuPipeline) SK_UNLIKELY {
762 return false;
763 }
764 fActiveGraphicsPipeline = dawnGraphicsPipeline;
765 fActiveRenderPassEncoder.SetPipeline(wgpuPipeline);
766 fBoundUniformBuffersDirty = true;
767
768 if (fActiveGraphicsPipeline->dstReadStrategy() == DstReadStrategy::kTextureCopy &&
769 fActiveGraphicsPipeline->numFragTexturesAndSamplers() == 2) {
770 // The pipeline has a single paired texture+sampler and uses texture copies for dst reads.
771 // This situation comes about when the program requires complex blending but otherwise
772 // is not referencing any images. Since there are no other images in play, the DrawPass
773 // will not have a BindTexturesAndSamplers command that we can tack the dstCopy on to.
774 // Instead we need to set the texture BindGroup ASAP to just the dstCopy.
775 // TODO(b/366254117): Once we standardize on a pipeline layout across all backends, the dst
776 // copy texture may not go in a group with the regular textures, in which case this binding
777 // can hopefully happen in a single place (e.g. here or at the start of the renderpass and
778 // not also every other time the textures are changed).
779 const auto* texture = static_cast<const DawnTexture*>(fDstCopy.first);
780 const auto* sampler = static_cast<const DawnSampler*>(fDstCopy.second);
781 wgpu::BindGroup bindGroup =
782 fResourceProvider->findOrCreateSingleTextureSamplerBindGroup(sampler, texture);
783 fActiveRenderPassEncoder.SetBindGroup(
784 DawnGraphicsPipeline::kTextureBindGroupIndex, bindGroup);
785 }
786
787 return true;
788 }
789
790 void DawnCommandBuffer::bindUniformBuffer(const BindBufferInfo& info, UniformSlot slot) {
791 SkASSERT(fActiveRenderPassEncoder);
792
793 unsigned int bufferIndex;
794 switch (slot) {
795 case UniformSlot::kCombinedUniforms:
796 bufferIndex = DawnGraphicsPipeline::kCombinedUniformIndex;
797 break;
798 case UniformSlot::kGradient:
799 bufferIndex = DawnGraphicsPipeline::kGradientBufferIndex;
800 break;
801 }
802
803 fBoundUniforms[bufferIndex] = info;
804 fBoundUniformBuffersDirty = true;
805 }
806
807 void DawnCommandBuffer::bindInputBuffer(const Buffer* buffer, size_t offset,
808 uint32_t bindingIndex) {
809 SkASSERT(fActiveRenderPassEncoder);
810 if (buffer) {
811 auto dawnBuffer = static_cast<const DawnBuffer*>(buffer)->dawnBuffer();
812 fActiveRenderPassEncoder.SetVertexBuffer(bindingIndex, dawnBuffer, offset);
813 }
814 }
815
816 void DawnCommandBuffer::bindIndexBuffer(const Buffer* indexBuffer, size_t offset) {
817 SkASSERT(fActiveRenderPassEncoder);
818 if (indexBuffer) {
819 auto dawnBuffer = static_cast<const DawnBuffer*>(indexBuffer)->dawnBuffer();
820 fActiveRenderPassEncoder.SetIndexBuffer(
821 dawnBuffer, wgpu::IndexFormat::Uint16, offset);
822 }
823 }
824
825 void DawnCommandBuffer::bindIndirectBuffer(const Buffer* indirectBuffer, size_t offset) {
826 if (indirectBuffer) {
827 fCurrentIndirectBuffer = static_cast<const DawnBuffer*>(indirectBuffer)->dawnBuffer();
828 fCurrentIndirectBufferOffset = offset;
829 } else {
830 fCurrentIndirectBuffer = nullptr;
831 fCurrentIndirectBufferOffset = 0;
832 }
833 }
834
835 void DawnCommandBuffer::bindTextureAndSamplers(
836 const DrawPass& drawPass, const DrawPassCommands::BindTexturesAndSamplers& command) {
837 SkASSERT(fActiveRenderPassEncoder);
838 SkASSERT(fActiveGraphicsPipeline);
839
840 // When there's an active graphics pipeline with a texture-copy dstread requirement, add one
841 // to account for the intrinsic dstCopy texture we bind here.
842 // NOTE: This is in units of pairs of textures and samplers, whereas the value reported by
843 // the current pipeline is in net bindings (textures + samplers).
844 int numTexturesAndSamplers = command.fNumTexSamplers;
845 if (fActiveGraphicsPipeline->dstReadStrategy() == DstReadStrategy::kTextureCopy) {
846 numTexturesAndSamplers++;
847 }
848 SkASSERT(fActiveGraphicsPipeline->numFragTexturesAndSamplers() == 2*numTexturesAndSamplers);
849
850 // If possible, it's ideal to optimize for the common case of using a single texture with one
851 // dynamic sampler. When using only one sampler, determine whether it is static or dynamic.
852 bool usingSingleStaticSampler = false;
853 #if !defined(__EMSCRIPTEN__)
854 if (command.fNumTexSamplers == 1) {
855 const wgpu::YCbCrVkDescriptor& ycbcrDesc =
856 TextureInfoPriv::Get<DawnTextureInfo>(
857 command.fTextures[0]->texture()->textureInfo())
858 .fYcbcrVkDescriptor;
859 usingSingleStaticSampler = DawnDescriptorIsValid(ycbcrDesc);
860 }
861 #endif
862
863 wgpu::BindGroup bindGroup;
864 // Optimize for single texture with dynamic sampling.
865 if (numTexturesAndSamplers == 1 && !usingSingleStaticSampler) {
866 SkASSERT(fActiveGraphicsPipeline->numFragTexturesAndSamplers() == 2);
867 SkASSERT(fActiveGraphicsPipeline->dstReadStrategy() != DstReadStrategy::kTextureCopy);
868
869 const auto* texture = static_cast<const DawnTexture*>(command.fTextures[0]->texture());
870 const auto* sampler = this->getSampler(command, 0);
871 bindGroup = fResourceProvider->findOrCreateSingleTextureSamplerBindGroup(sampler, texture);
872 } else {
873 std::vector<wgpu::BindGroupEntry> entries;
874
875 for (int i = 0; i < command.fNumTexSamplers; ++i) {
876 const auto* texture = static_cast<const DawnTexture*>(command.fTextures[i]->texture());
877 const auto* sampler = this->getSampler(command, i);
878 auto& wgpuTextureView = texture->sampleTextureView();
879 auto& wgpuSampler = sampler->dawnSampler();
880
881 #if !defined(__EMSCRIPTEN__)
882 // Assuming shader generator assigns binding slot to sampler then texture,
883 // then the next sampler and texture, and so on, we need to use
884 // 2 * i as base binding index of the sampler and texture.
885 // TODO: https://b.corp.google.com/issues/259457090:
886 // Better configurable way of assigning samplers and textures' bindings.
887 const wgpu::YCbCrVkDescriptor& ycbcrDesc =
888 texture->dawnTextureInfo().fYcbcrVkDescriptor;
889
890 // Only add a sampler as a bind group entry if it's a regular dynamic sampler. A valid
891 // YCbCrVkDescriptor indicates the usage of a static sampler, which should not be
892 // included here. They should already be fully specified in the bind group layout.
893 if (!DawnDescriptorIsValid(ycbcrDesc)) {
894 #endif
895 wgpu::BindGroupEntry samplerEntry;
896 samplerEntry.binding = 2 * i;
897 samplerEntry.sampler = wgpuSampler;
898 entries.push_back(samplerEntry);
899 #if !defined(__EMSCRIPTEN__)
900 }
901 #endif
902 wgpu::BindGroupEntry textureEntry;
903 textureEntry.binding = 2 * i + 1;
904 textureEntry.textureView = wgpuTextureView;
905 entries.push_back(textureEntry);
906 }
907
908 if (fActiveGraphicsPipeline->dstReadStrategy() == DstReadStrategy::kTextureCopy) {
909 // Append the dstCopy sampler and texture as the very last two bind group entries
910 wgpu::BindGroupEntry samplerEntry;
911 samplerEntry.binding = 2*numTexturesAndSamplers - 2;
912 samplerEntry.sampler = static_cast<const DawnSampler*>(fDstCopy.second)->dawnSampler();
913 entries.push_back(samplerEntry);
914
915 wgpu::BindGroupEntry textureEntry;
916 textureEntry.binding = 2*numTexturesAndSamplers - 1;
917 textureEntry.textureView =
918 static_cast<const DawnTexture*>(fDstCopy.first)->sampleTextureView();
919 entries.push_back(textureEntry);
920 }
921
922 wgpu::BindGroupDescriptor desc;
923 const auto& groupLayouts = fActiveGraphicsPipeline->dawnGroupLayouts();
924 desc.layout = groupLayouts[DawnGraphicsPipeline::kTextureBindGroupIndex];
925 desc.entryCount = entries.size();
926 desc.entries = entries.data();
927
928 bindGroup = fSharedContext->device().CreateBindGroup(&desc);
929 }
930
931 fActiveRenderPassEncoder.SetBindGroup(DawnGraphicsPipeline::kTextureBindGroupIndex, bindGroup);
932 }
933
934 void DawnCommandBuffer::syncUniformBuffers() {
935 static constexpr int kNumBuffers = DawnGraphicsPipeline::kNumUniformBuffers;
936
937 if (fBoundUniformBuffersDirty) {
938 fBoundUniformBuffersDirty = false;
939
940 std::array<uint32_t, kNumBuffers> dynamicOffsets;
941 std::array<std::pair<const DawnBuffer*, uint32_t>, kNumBuffers> boundBuffersAndSizes;
942
943 std::array<bool, kNumBuffers> enabled = {
944 !fSharedContext->dawnCaps()
945 ->resourceBindingRequirements()
946 .fUsePushConstantsForIntrinsicConstants, // intrinsic uniforms
947 fActiveGraphicsPipeline->hasCombinedUniforms(), // paint AND renderstep uniforms!
948 fActiveGraphicsPipeline->hasGradientBuffer(), // gradient SSBO
949 };
950
951 for (int i = 0; i < kNumBuffers; ++i) {
952 if (enabled[i] && fBoundUniforms[i]) {
953 boundBuffersAndSizes[i].first =
954 static_cast<const DawnBuffer*>(fBoundUniforms[i].fBuffer);
955 boundBuffersAndSizes[i].second = fBoundUniforms[i].fSize;
956 dynamicOffsets[i] = fBoundUniforms[i].fOffset;
957 } else {
958 // Unused or null binding
959 boundBuffersAndSizes[i].first = nullptr;
960 dynamicOffsets[i] = 0;
961 }
962 }
963
964 auto bindGroup =
965 fResourceProvider->findOrCreateUniformBuffersBindGroup(boundBuffersAndSizes);
966
967 fActiveRenderPassEncoder.SetBindGroup(DawnGraphicsPipeline::kUniformBufferBindGroupIndex,
968 bindGroup,
969 dynamicOffsets.size(),
970 dynamicOffsets.data());
971 }
972 }
973
974 void DawnCommandBuffer::setScissor(const Scissor& scissor) {
975 SkASSERT(fActiveRenderPassEncoder);
976 SkIRect rect = scissor.getRect(fReplayTranslation, fRenderPassBounds);
977 fActiveRenderPassEncoder.SetScissorRect(rect.x(), rect.y(), rect.width(), rect.height());
978 }
979
980 bool DawnCommandBuffer::updateIntrinsicUniformsAsUBO(UniformDataBlock uniformData) {
981 BindBufferInfo binding =
982 fResourceProvider->findOrCreateIntrinsicBindBufferInfo(this, uniformData);
983
984 if (!binding) {
985 return false;
986 } else if (binding == fBoundUniforms[DawnGraphicsPipeline::kIntrinsicUniformBufferIndex]) {
987 return true; // no binding change needed
988 }
989
990 fBoundUniforms[DawnGraphicsPipeline::kIntrinsicUniformBufferIndex] = binding;
991 fBoundUniformBuffersDirty = true;
992 return true;
993 }
994
995 bool DawnCommandBuffer::updateIntrinsicUniformsAsPushConstant(UniformDataBlock uniformData) {
996 #if !defined(__EMSCRIPTEN__)
997 SkASSERT(fActiveRenderPassEncoder);
998 SkASSERT(uniformData.size() <= DawnGraphicsPipeline::kIntrinsicUniformSize);
999 fActiveRenderPassEncoder.SetImmediates(0, uniformData.data(), uniformData.size());
1000 return true;
1001 #else
1002 SkASSERT(false); // No push constant support in WASM yet
1003 return false;
1004 #endif
1005 }
1006
1007 void DawnCommandBuffer::setViewport(SkIRect viewport) {
1008 SkASSERT(fActiveRenderPassEncoder);
1009 fActiveRenderPassEncoder.SetViewport(
1010 viewport.x(), viewport.y(), viewport.width(), viewport.height(), 0, 1);
1011 }
1012
1013 void DawnCommandBuffer::setBlendConstants(std::array<float, 4> blendConstants) {
1014 SkASSERT(fActiveRenderPassEncoder);
1015 wgpu::Color blendConst = {
1016 blendConstants[0], blendConstants[1], blendConstants[2], blendConstants[3]};
1017 fActiveRenderPassEncoder.SetBlendConstant(&blendConst);
1018 }
1019
1020 void DawnCommandBuffer::draw(PrimitiveType type,
1021 unsigned int baseVertex,
1022 unsigned int vertexCount) {
1023 SkASSERT(fActiveRenderPassEncoder);
1024 SkASSERT(fActiveGraphicsPipeline->primitiveType() == type);
1025
1026 this->syncUniformBuffers();
1027
1028 fActiveRenderPassEncoder.Draw(vertexCount, /*instanceCount=*/1, baseVertex);
1029 }
1030
1031 void DawnCommandBuffer::drawIndexed(PrimitiveType type,
1032 unsigned int baseIndex,
1033 unsigned int indexCount,
1034 unsigned int baseVertex) {
1035 SkASSERT(fActiveRenderPassEncoder);
1036 SkASSERT(fActiveGraphicsPipeline->primitiveType() == type);
1037
1038 this->syncUniformBuffers();
1039
1040 fActiveRenderPassEncoder.DrawIndexed(indexCount, /*instanceCount=*/1, baseIndex, baseVertex);
1041 }
1042
1043 void DawnCommandBuffer::drawInstanced(PrimitiveType type,
1044 unsigned int baseVertex,
1045 unsigned int vertexCount,
1046 unsigned int baseInstance,
1047 unsigned int instanceCount) {
1048 SkASSERT(fActiveRenderPassEncoder);
1049 SkASSERT(fActiveGraphicsPipeline->primitiveType() == type);
1050
1051 this->syncUniformBuffers();
1052
1053 fActiveRenderPassEncoder.Draw(vertexCount, instanceCount, baseVertex, baseInstance);
1054 }
1055
1056 void DawnCommandBuffer::drawIndexedInstanced(PrimitiveType type,
1057 unsigned int baseIndex,
1058 unsigned int indexCount,
1059 unsigned int baseVertex,
1060 unsigned int baseInstance,
1061 unsigned int instanceCount) {
1062 SkASSERT(fActiveRenderPassEncoder);
1063 SkASSERT(fActiveGraphicsPipeline->primitiveType() == type);
1064
1065 this->syncUniformBuffers();
1066
1067 fActiveRenderPassEncoder.DrawIndexed(
1068 indexCount, instanceCount, baseIndex, baseVertex, baseInstance);
1069 }
1070
1071 void DawnCommandBuffer::drawIndirect(PrimitiveType type) {
1072 SkASSERT(fActiveRenderPassEncoder);
1073 SkASSERT(fActiveGraphicsPipeline->primitiveType() == type);
1074 SkASSERT(fCurrentIndirectBuffer);
1075
1076 this->syncUniformBuffers();
1077
1078 fActiveRenderPassEncoder.DrawIndirect(fCurrentIndirectBuffer, fCurrentIndirectBufferOffset);
1079 }
1080
1081 void DawnCommandBuffer::drawIndexedIndirect(PrimitiveType type) {
1082 SkASSERT(fActiveRenderPassEncoder);
1083 SkASSERT(fActiveGraphicsPipeline->primitiveType() == type);
1084 SkASSERT(fCurrentIndirectBuffer);
1085
1086 this->syncUniformBuffers();
1087
1088 fActiveRenderPassEncoder.DrawIndexedIndirect(fCurrentIndirectBuffer,
1089 fCurrentIndirectBufferOffset);
1090 }
1091
1092 void DawnCommandBuffer::beginComputePass() {
1093 SkASSERT(!fActiveRenderPassEncoder);
1094 SkASSERT(!fActiveComputePassEncoder);
1095 wgpu::ComputePassDescriptor wgpuComputePassDescriptor = {};
1096 #if WGPU_TIMESTAMP_WRITES_DEFINED
1097 #if defined(__EMSCRIPTEN__)
1098 wgpu::ComputePassTimestampWrites wgpuTimestampWrites;
1099 #else
1100 wgpu::PassTimestampWrites wgpuTimestampWrites;
1101 #endif
1102 if (!fSharedContext->dawnCaps()->supportsCommandBufferTimestamps() && fTimestampQueryBuffer) {
1103 SkASSERT(fTimestampQuerySet);
1104 wgpuTimestampWrites.querySet = fTimestampQuerySet;
1105 if (!fWroteFirstPassTimestamps) {
1106 wgpuTimestampWrites.beginningOfPassWriteIndex = 0;
1107 fWroteFirstPassTimestamps = true;
1108 }
1109 wgpuTimestampWrites.endOfPassWriteIndex = 1;
1110 wgpuComputePassDescriptor.timestampWrites = &wgpuTimestampWrites;
1111 }
1112 #else
1113 SkASSERT(!fTimestampQueryBuffer);
1114 #endif
1115 fActiveComputePassEncoder = fCommandEncoder.BeginComputePass(&wgpuComputePassDescriptor);
1116 }
1117
1118 void DawnCommandBuffer::bindComputePipeline(const ComputePipeline* computePipeline) {
1119 SkASSERT(fActiveComputePassEncoder);
1120
1121 fActiveComputePipeline = static_cast<const DawnComputePipeline*>(computePipeline);
1122 fActiveComputePassEncoder.SetPipeline(fActiveComputePipeline->dawnComputePipeline());
1123 }
1124
1125 void DawnCommandBuffer::bindDispatchResources(const DispatchGroup& group,
1126 const DispatchGroup::Dispatch& dispatch) {
1127 SkASSERT(fActiveComputePassEncoder);
1128 SkASSERT(fActiveComputePipeline);
1129
1130 // Bind all pipeline resources to a single new bind group at index 0.
1131 // NOTE: Caching the bind groups here might be beneficial based on the layout and the bound
1132 // resources (though it's questionable how often a bind group will end up getting reused since
1133 // the bound objects change often).
1134 skia_private::TArray<wgpu::BindGroupEntry> entries;
1135 entries.reserve(dispatch.fBindings.size());
1136
1137 for (const ResourceBinding& binding : dispatch.fBindings) {
1138 wgpu::BindGroupEntry& entry = entries.push_back();
1139 entry.binding = binding.fIndex;
1140 if (const BindBufferInfo* buffer = std::get_if<BindBufferInfo>(&binding.fResource)) {
1141 entry.buffer = static_cast<const DawnBuffer*>(buffer->fBuffer)->dawnBuffer();
1142 entry.offset = buffer->fOffset;
1143 entry.size = buffer->fSize;
1144 } else if (const TextureIndex* texIdx = std::get_if<TextureIndex>(&binding.fResource)) {
1145 const DawnTexture* texture =
1146 static_cast<const DawnTexture*>(group.getTexture(texIdx->fValue));
1147 SkASSERT(texture);
1148 entry.textureView = texture->sampleTextureView();
1149 } else if (const SamplerIndex* samplerIdx = std::get_if<SamplerIndex>(&binding.fResource)) {
1150 const DawnSampler* sampler =
1151 static_cast<const DawnSampler*>(group.getSampler(samplerIdx->fValue));
1152 entry.sampler = sampler->dawnSampler();
1153 } else {
1154 SK_ABORT("unsupported dispatch resource type");
1155 }
1156 }
1157
1158 wgpu::BindGroupDescriptor desc;
1159 desc.layout = fActiveComputePipeline->dawnGroupLayout();
1160 desc.entryCount = entries.size();
1161 desc.entries = entries.data();
1162
1163 auto bindGroup = fSharedContext->device().CreateBindGroup(&desc);
1164 fActiveComputePassEncoder.SetBindGroup(0, bindGroup);
1165 }
1166
1167 void DawnCommandBuffer::dispatchWorkgroups(const WorkgroupSize& globalSize) {
1168 SkASSERT(fActiveComputePassEncoder);
1169 SkASSERT(fActiveComputePipeline);
1170
1171 fActiveComputePassEncoder.DispatchWorkgroups(
1172 globalSize.fWidth, globalSize.fHeight, globalSize.fDepth);
1173 }
1174
1175 void DawnCommandBuffer::dispatchWorkgroupsIndirect(const Buffer* indirectBuffer,
1176 size_t indirectBufferOffset) {
1177 SkASSERT(fActiveComputePassEncoder);
1178 SkASSERT(fActiveComputePipeline);
1179
1180 auto& wgpuIndirectBuffer = static_cast<const DawnBuffer*>(indirectBuffer)->dawnBuffer();
1181 fActiveComputePassEncoder.DispatchWorkgroupsIndirect(wgpuIndirectBuffer, indirectBufferOffset);
1182 }
1183
1184 void DawnCommandBuffer::endComputePass() {
1185 SkASSERT(fActiveComputePassEncoder);
1186 fActiveComputePassEncoder.End();
1187 fActiveComputePassEncoder = nullptr;
1188 }
1189
1190 bool DawnCommandBuffer::onCopyBufferToBuffer(const Buffer* srcBuffer,
1191 size_t srcOffset,
1192 const Buffer* dstBuffer,
1193 size_t dstOffset,
1194 size_t size) {
1195 SkASSERT(!fActiveRenderPassEncoder);
1196 SkASSERT(!fActiveComputePassEncoder);
1197
1198 auto& wgpuBufferSrc = static_cast<const DawnBuffer*>(srcBuffer)->dawnBuffer();
1199 auto& wgpuBufferDst = static_cast<const DawnBuffer*>(dstBuffer)->dawnBuffer();
1200
1201 fCommandEncoder.CopyBufferToBuffer(wgpuBufferSrc, srcOffset, wgpuBufferDst, dstOffset, size);
1202 return true;
1203 }
1204
1205 bool DawnCommandBuffer::onCopyTextureToBuffer(const Texture* texture,
1206 SkIRect srcRect,
1207 const Buffer* buffer,
1208 size_t bufferOffset,
1209 size_t bufferRowBytes) {
1210 SkASSERT(!fActiveRenderPassEncoder);
1211 SkASSERT(!fActiveComputePassEncoder);
1212
1213 const auto* wgpuTexture = static_cast<const DawnTexture*>(texture);
1214 auto& wgpuBuffer = static_cast<const DawnBuffer*>(buffer)->dawnBuffer();
1215
1216 wgpu::TexelCopyTextureInfo src;
1217 src.texture = wgpuTexture->dawnTexture();
1218 src.origin.x = srcRect.x();
1219 src.origin.y = srcRect.y();
1220 src.aspect = wgpuTexture->dawnTextureInfo().fAspect;
1221
1222 wgpu::TexelCopyBufferInfo dst;
1223 dst.buffer = wgpuBuffer;
1224 dst.layout.offset = bufferOffset;
1225 dst.layout.bytesPerRow = bufferRowBytes;
1226
1227 wgpu::Extent3D copySize = {
1228 static_cast<uint32_t>(srcRect.width()), static_cast<uint32_t>(srcRect.height()), 1};
1229 fCommandEncoder.CopyTextureToBuffer(&src, &dst, &copySize);
1230
1231 return true;
1232 }
1233
1234 bool DawnCommandBuffer::onCopyBufferToTexture(const Buffer* buffer,
1235 const Texture* texture,
1236 const BufferTextureCopyData* copyData,
1237 int count) {
1238 SkASSERT(!fActiveRenderPassEncoder);
1239 SkASSERT(!fActiveComputePassEncoder);
1240
1241 auto& wgpuTexture = static_cast<const DawnTexture*>(texture)->dawnTexture();
1242 auto& wgpuBuffer = static_cast<const DawnBuffer*>(buffer)->dawnBuffer();
1243
1244 wgpu::TexelCopyBufferInfo src;
1245 src.buffer = wgpuBuffer;
1246
1247 wgpu::TexelCopyTextureInfo dst;
1248 dst.texture = wgpuTexture;
1249
1250 for (int i = 0; i < count; ++i) {
1251 src.layout.offset = copyData[i].fBufferOffset;
1252 src.layout.bytesPerRow = copyData[i].fBufferRowBytes;
1253
1254 dst.origin.x = copyData[i].fRect.x();
1255 dst.origin.y = copyData[i].fRect.y();
1256 dst.mipLevel = copyData[i].fMipLevel;
1257
1258 wgpu::Extent3D copySize = {static_cast<uint32_t>(copyData[i].fRect.width()),
1259 static_cast<uint32_t>(copyData[i].fRect.height()),
1260 1};
1261 fCommandEncoder.CopyBufferToTexture(&src, &dst, &copySize);
1262 }
1263
1264 return true;
1265 }
1266
1267 bool DawnCommandBuffer::onCopyTextureToTexture(const Texture* src,
1268 SkIRect srcRect,
1269 const Texture* dst,
1270 SkIPoint dstPoint,
1271 int mipLevel) {
1272 SkASSERT(!fActiveRenderPassEncoder);
1273 SkASSERT(!fActiveComputePassEncoder);
1274
1275 auto& wgpuTextureSrc = static_cast<const DawnTexture*>(src)->dawnTexture();
1276 auto& wgpuTextureDst = static_cast<const DawnTexture*>(dst)->dawnTexture();
1277
1278 wgpu::TexelCopyTextureInfo srcArgs;
1279 srcArgs.texture = wgpuTextureSrc;
1280 srcArgs.origin.x = srcRect.fLeft;
1281 srcArgs.origin.y = srcRect.fTop;
1282
1283 wgpu::TexelCopyTextureInfo dstArgs;
1284 dstArgs.texture = wgpuTextureDst;
1285 dstArgs.origin.x = dstPoint.fX;
1286 dstArgs.origin.y = dstPoint.fY;
1287 dstArgs.mipLevel = mipLevel;
1288
1289 wgpu::Extent3D copySize = {
1290 static_cast<uint32_t>(srcRect.width()), static_cast<uint32_t>(srcRect.height()), 1};
1291
1292 fCommandEncoder.CopyTextureToTexture(&srcArgs, &dstArgs, &copySize);
1293
1294 return true;
1295 }
1296
1297 bool DawnCommandBuffer::onSynchronizeBufferToCpu(const Buffer* buffer, bool* outDidResultInWork) {
1298 return true;
1299 }
1300
1301 bool DawnCommandBuffer::onClearBuffer(const Buffer* buffer, size_t offset, size_t size) {
1302 SkASSERT(!fActiveRenderPassEncoder);
1303 SkASSERT(!fActiveComputePassEncoder);
1304
1305 auto& wgpuBuffer = static_cast<const DawnBuffer*>(buffer)->dawnBuffer();
1306 fCommandEncoder.ClearBuffer(wgpuBuffer, offset, size);
1307
1308 return true;
1309 }
1310
1311 } // namespace skgpu::graphite