Debian Codegraph @

src/gpu/graphite/dawn/DawnResourceProvider.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/DawnResourceProvider.h"
9
10 #include "include/core/SkString.h"
11 #include "include/gpu/graphite/BackendTexture.h"
12 #include "include/gpu/graphite/TextureInfo.h"
13 #include "include/gpu/graphite/dawn/DawnGraphiteTypes.h"
14 #include "include/private/base/SingleOwner.h"
15 #include "include/private/base/SkAlign.h"
16 #include "src/gpu/graphite/ComputePipeline.h"
17 #include "src/gpu/graphite/RenderPassDesc.h"
18 #include "src/gpu/graphite/dawn/DawnBuffer.h"
19 #include "src/gpu/graphite/dawn/DawnCommandBuffer.h"
20 #include "src/gpu/graphite/dawn/DawnComputePipeline.h"
21 #include "src/gpu/graphite/dawn/DawnErrorChecker.h"
22 #include "src/gpu/graphite/dawn/DawnGraphicsPipeline.h"
23 #include "src/gpu/graphite/dawn/DawnGraphiteUtils.h"
24 #include "src/gpu/graphite/dawn/DawnSampler.h"
25 #include "src/gpu/graphite/dawn/DawnSharedContext.h"
26 #include "src/gpu/graphite/dawn/DawnTexture.h"
27 #include "src/sksl/SkSLCompiler.h"
28
29 namespace skgpu::graphite {
30
31 namespace {
32
33 constexpr uint32_t kBufferBindingSizeAlignment = 16;
34 constexpr int kMaxNumberOfCachedTextureBindGroups = 4096;
35
36 wgpu::ShaderModule create_shader_module(const wgpu::Device& device, const char* source) {
37 #if defined(__EMSCRIPTEN__)
38 wgpu::ShaderModuleWGSLDescriptor wgslDesc;
39 #else
40 wgpu::ShaderSourceWGSL wgslDesc;
41 #endif
42 wgslDesc.code = source;
43 wgpu::ShaderModuleDescriptor descriptor;
44 descriptor.nextInChain = &wgslDesc;
45 return device.CreateShaderModule(&descriptor);
46 }
47
48 wgpu::RenderPipeline create_blit_render_pipeline(const DawnSharedContext* sharedContext,
49 const char* label,
50 wgpu::ShaderModule shaderModule,
51 const char* vsEntryPoint,
52 const char* fsEntryPoint,
53 wgpu::TextureFormat renderPassColorFormat,
54 wgpu::TextureFormat renderPassDepthStencilFormat,
55 SampleCount sampleCount) {
56 wgpu::RenderPipelineDescriptor descriptor;
57 descriptor.label = label;
58 descriptor.layout = nullptr;
59
60 wgpu::ColorTargetState colorTarget;
61 colorTarget.format = renderPassColorFormat;
62 colorTarget.blend = nullptr;
63 colorTarget.writeMask = wgpu::ColorWriteMask::All;
64
65 wgpu::DepthStencilState depthStencil;
66 if (renderPassDepthStencilFormat != wgpu::TextureFormat::Undefined) {
67 depthStencil.format = renderPassDepthStencilFormat;
68 depthStencil.depthWriteEnabled = false;
69 depthStencil.depthCompare = wgpu::CompareFunction::Always;
70
71 descriptor.depthStencil = &depthStencil;
72 }
73
74 wgpu::FragmentState fragment;
75 fragment.module = shaderModule;
76 fragment.entryPoint = fsEntryPoint;
77 fragment.constantCount = 0;
78 fragment.constants = nullptr;
79 fragment.targetCount = 1;
80 fragment.targets = &colorTarget;
81 descriptor.fragment = &fragment;
82
83 descriptor.vertex.module = shaderModule;
84 descriptor.vertex.entryPoint = vsEntryPoint;
85 descriptor.vertex.constantCount = 0;
86 descriptor.vertex.constants = nullptr;
87 descriptor.vertex.bufferCount = 0;
88 descriptor.vertex.buffers = nullptr;
89
90 descriptor.primitive.frontFace = wgpu::FrontFace::CCW;
91 descriptor.primitive.cullMode = wgpu::CullMode::None;
92 descriptor.primitive.topology = wgpu::PrimitiveTopology::TriangleStrip;
93 descriptor.primitive.stripIndexFormat = wgpu::IndexFormat::Undefined;
94
95 descriptor.multisample.count = (uint8_t) sampleCount;
96 descriptor.multisample.mask = 0xFFFFFFFF;
97 descriptor.multisample.alphaToCoverageEnabled = false;
98
99 std::optional<DawnErrorChecker> errorChecker;
100 if (sharedContext->dawnCaps()->allowScopedErrorChecks()) {
101 errorChecker.emplace(sharedContext);
102 }
103 auto pipeline = sharedContext->device().CreateRenderPipeline(&descriptor);
104 if (errorChecker.has_value() && errorChecker->popErrorScopes() != DawnErrorType::kNoError) {
105 return nullptr;
106 }
107
108 return pipeline;
109 }
110
111 template <size_t NumEntries>
112 using BindGroupKey = typename DawnResourceProvider::BindGroupKey<NumEntries>;
113 using UniformBindGroupKey = BindGroupKey<DawnResourceProvider::kNumUniformEntries>;
114
115 BindGroupKey<1> make_texture_bind_group_key(const DawnSampler* sampler,
116 const DawnTexture* texture) {
117 BindGroupKey<1> uniqueKey;
118 {
119 BindGroupKey<1>::Builder builder(&uniqueKey);
120
121 builder[0] = sampler->uniqueID().asUInt();
122 builder[1] = texture->uniqueID().asUInt();
123
124 builder.finish();
125 }
126
127 return uniqueKey;
128 }
129 } // namespace
130
131
132 // Wraps a Dawn buffer, and tracks the intrinsic blocks residing in this buffer.
133 class DawnResourceProvider::IntrinsicBuffer final {
134 public:
135 static constexpr int kNumSlots = 8;
136
137 IntrinsicBuffer(sk_sp<DawnBuffer> dawnBuffer) : fDawnBuffer(std::move(dawnBuffer)) {}
138 ~IntrinsicBuffer() = default;
139
140 sk_sp<DawnBuffer> buffer() const { return fDawnBuffer; }
141
142 // Track that 'intrinsicValues' is stored in the buffer at the 'offset'.
143 void trackIntrinsic(UniformDataBlock intrinsicValues, uint32_t offset) {
144 fCachedIntrinsicValues.set(UniformDataBlock::Make(intrinsicValues, &fUniformData), offset);
145 }
146
147 // Find the offset of 'intrinsicValues' in the buffer. If not found, return nullptr.
148 uint32_t* findIntrinsic(UniformDataBlock intrinsicValues) const {
149 return fCachedIntrinsicValues.find(intrinsicValues);
150 }
151
152 int slotsUsed() const { return fCachedIntrinsicValues.count(); }
153
154 void updateAccessTime() {
155 fLastAccess = skgpu::StdSteadyClock::now();
156 }
157 skgpu::StdSteadyClock::time_point lastAccessTime() const {
158 return fLastAccess;
159 }
160
161 private:
162 skia_private::THashMap<UniformDataBlock, uint32_t, UniformDataBlock::Hash>
163 fCachedIntrinsicValues;
164 SkArenaAlloc fUniformData{0};
165
166 sk_sp<DawnBuffer> fDawnBuffer;
167 skgpu::StdSteadyClock::time_point fLastAccess;
168
169 SK_DECLARE_INTERNAL_LLIST_INTERFACE(IntrinsicBuffer);
170 };
171
172 // DawnResourceProvider::IntrinsicConstantsManager
173 // ----------------------------------------------------------------------------
174
175 /**
176 * Since Dawn does not currently provide push constants, this helper class manages rotating through
177 * buffers and writing each new occurrence of a set of intrinsic uniforms into the current buffer.
178 */
179 class DawnResourceProvider::IntrinsicConstantsManager {
180 public:
181 explicit IntrinsicConstantsManager(DawnResourceProvider* resourceProvider)
182 : fResourceProvider(resourceProvider) {}
183
184 ~IntrinsicConstantsManager() {
185 auto alwaysTrue = [](IntrinsicBuffer* buffer) { return true; };
186 this->purgeBuffersIf(alwaysTrue);
187
188 SkASSERT(fIntrinsicBuffersLRU.isEmpty());
189 }
190
191 // Find or create a bind buffer info for the given intrinsic values used in the given command
192 // buffer.
193 BindBufferInfo add(DawnCommandBuffer* cb, UniformDataBlock intrinsicValues);
194
195 void purgeResourcesNotUsedSince(StdSteadyClock::time_point purgeTime) {
196 auto bufferNotUsedSince = [purgeTime, this](IntrinsicBuffer* buffer) {
197 // We always keep the current buffer as it is likely to be used again soon.
198 return buffer != fCurrentBuffer && buffer->lastAccessTime() < purgeTime;
199 };
200 this->purgeBuffersIf(bufferNotUsedSince);
201 }
202
203 void freeGpuResources() { this->purgeResourcesNotUsedSince(skgpu::StdSteadyClock::now()); }
204
205 private:
206 // The max number of intrinsic buffers to keep around in the cache.
207 static constexpr uint32_t kMaxNumBuffers = 16;
208
209 // Traverse the intrinsic buffers and purge the ones that match the 'pred'.
210 template<typename T> void purgeBuffersIf(T pred);
211
212 DawnResourceProvider* const fResourceProvider;
213 // The current buffer being filled up, as well as the how much of it has been written to.
214 IntrinsicBuffer* fCurrentBuffer = nullptr;
215
216 // All cached intrinsic buffers, in LRU order.
217 SkTInternalLList<IntrinsicBuffer> fIntrinsicBuffersLRU;
218 // The number of intrinsic buffers currently in the cache.
219 uint32_t fNumBuffers = 0;
220 };
221
222 // Find or create a bind buffer info for the given intrinsic values used in the given command
223 // buffer.
224 BindBufferInfo DawnResourceProvider::IntrinsicConstantsManager::add(
225 DawnCommandBuffer* cb, UniformDataBlock intrinsicValues) {
226 using Iter = SkTInternalLList<IntrinsicBuffer>::Iter;
227 Iter iter;
228 auto* curr = iter.init(fIntrinsicBuffersLRU, Iter::kHead_IterStart);
229 uint32_t* offset = nullptr;
230 // Find the buffer that contains the given intrinsic values.
231 while (curr != nullptr) {
232 offset = curr->findIntrinsic(intrinsicValues);
233 if (offset != nullptr) {
234 break;
235 }
236 curr = iter.next();
237 }
238 // If we found the buffer, we can return the bind buffer info directly.
239 if (curr != nullptr && offset != nullptr) {
240 // Move the buffer to the head of the LRU list.
241 fIntrinsicBuffersLRU.remove(curr);
242 fIntrinsicBuffersLRU.addToHead(curr);
243 // Track the dawn buffer's usage by the command buffer.
244 cb->trackResource(curr->buffer());
245 curr->updateAccessTime();
246 return {curr->buffer().get(), *offset, SkTo<uint32_t>(intrinsicValues.size())};
247 }
248
249 // TODO: https://b.corp.google.com/issues/259267703
250 // Make updating intrinsic constants faster. Metal has setVertexBytes method to quickly send
251 // intrinsic constants to vertex shader without any buffer. But Dawn doesn't have similar
252 // capability. So we have to use WriteBuffer(), and this method is not allowed to be called when
253 // there is an active render pass.
254 SkASSERT(!cb->hasActivePassEncoder());
255
256 const Caps* caps = fResourceProvider->dawnSharedContext()->caps();
257 const uint32_t stride =
258 SkAlignTo(intrinsicValues.size(), caps->requiredUniformBufferAlignment());
259 // In any one of the following cases, we need to create a new buffer:
260 // (1) There is no current buffer.
261 // (2) The current buffer is full.
262 if (!fCurrentBuffer || fCurrentBuffer->slotsUsed() == IntrinsicBuffer::kNumSlots) {
263 // We can just replace the current buffer; any prior buffer was already tracked in the LRU
264 // list and the intrinsic constants were written directly to the Dawn queue.
265 DawnResourceProvider* resourceProvider = fResourceProvider;
266 auto dawnBuffer =
267 resourceProvider->findOrCreateDawnBuffer(stride * IntrinsicBuffer::kNumSlots,
268 BufferType::kUniform,
269 AccessPattern::kGpuOnly,
270 "IntrinsicConstantBuffer");
271 if (!dawnBuffer) {
272 // If we failed to create a GPU buffer to hold the intrinsic uniforms, we will fail the
273 // Recording being inserted, so return an empty bind info.
274 return {};
275 }
276
277 fCurrentBuffer = new IntrinsicBuffer(dawnBuffer);
278 fIntrinsicBuffersLRU.addToHead(fCurrentBuffer);
279 fNumBuffers++;
280 // If we have too many buffers, remove the least used one.
281 if (fNumBuffers > kMaxNumBuffers) {
282 auto* tail = fIntrinsicBuffersLRU.tail();
283 fIntrinsicBuffersLRU.remove(tail);
284 delete tail;
285 fNumBuffers--;
286 }
287 }
288
289 SkASSERT(fCurrentBuffer && fCurrentBuffer->slotsUsed() < IntrinsicBuffer::kNumSlots);
290 uint32_t newOffset = (fCurrentBuffer->slotsUsed()) * stride;
291 fResourceProvider->dawnSharedContext()->queue().WriteBuffer(
292 fCurrentBuffer->buffer()->dawnBuffer(),
293 newOffset,
294 intrinsicValues.data(),
295 intrinsicValues.size());
296
297 // Track the intrinsic values in the buffer.
298 fCurrentBuffer->trackIntrinsic(intrinsicValues, newOffset);
299
300 cb->trackResource(fCurrentBuffer->buffer());
301 fCurrentBuffer->updateAccessTime();
302
303 return {fCurrentBuffer->buffer().get(), newOffset, SkTo<uint32_t>(intrinsicValues.size())};
304 }
305
306 template <typename T> void DawnResourceProvider::IntrinsicConstantsManager::purgeBuffersIf(T pred) {
307 using Iter = SkTInternalLList<IntrinsicBuffer>::Iter;
308 Iter iter;
309 auto* curr = iter.init(fIntrinsicBuffersLRU, Iter::kHead_IterStart);
310 while (curr != nullptr) {
311 auto* next = iter.next();
312 if (pred(curr)) {
313 fIntrinsicBuffersLRU.remove(curr);
314 fNumBuffers--;
315 delete curr;
316 }
317 curr = next;
318 }
319 }
320
321 // DawnResourceProvider::IntrinsicConstantsManager
322 // ----------------------------------------------------------------------------
323
324 // DawnResourceProvider::BlitWithDrawEncoder
325 DawnResourceProvider::BlitWithDrawEncoder::BlitWithDrawEncoder(wgpu::RenderPipeline pipeline,
326 bool srcIsMSAA)
327 : fPipeline(std::move(pipeline)), fSrcIsMSAA(srcIsMSAA) {}
328
329 void DawnResourceProvider::BlitWithDrawEncoder::EncodeBlit(
330 const wgpu::Device& device,
331 const wgpu::RenderPassEncoder& renderEncoder,
332 const wgpu::TextureView& srcTextureView,
333 const SkIPoint& srcOffset,
334 const SkIRect& dstBounds) {
335 SkASSERT(fPipeline);
336 renderEncoder.SetPipeline(fPipeline);
337
338 // TODO(b/260368758): cache single texture's bind group creation.
339 wgpu::BindGroupEntry entry;
340 entry.binding = fSrcIsMSAA ? 1 : 0;
341 entry.textureView = srcTextureView;
342
343 wgpu::BindGroupDescriptor desc;
344 desc.layout = fPipeline.GetBindGroupLayout(0);
345 desc.entryCount = 1;
346 desc.entries = &entry;
347
348 auto bindGroup = device.CreateBindGroup(&desc);
349
350 renderEncoder.SetBindGroup(0, bindGroup);
351
352 renderEncoder.SetScissorRect(
353 dstBounds.left(), dstBounds.top(), dstBounds.width(), dstBounds.height());
354 renderEncoder.SetViewport(
355 dstBounds.left(), dstBounds.top(), dstBounds.width(), dstBounds.height(), 0, 1);
356
357 // In fragment shader, the sampling coords are calculated as:
358 // - x = fragPosition.x - dstX + srcX = fragPosition.x - (dxtX - srcX)
359 // - y = fragPosition.y - dstY + srcX = fragPosition.y - (dxtY - srcY)
360 int32_t deltaX = dstBounds.left() - srcOffset.x();
361 int32_t deltaY = dstBounds.top() - srcOffset.y();
362 // Since texture's sizes are never larger than 16 bits, we can encode the offsets's (x, y)
363 // in one single 32 bits instance index value. In future, once push constants are implemented in
364 // Dawn, we should use them instead.
365 SkASSERT(std::abs(deltaX) < std::numeric_limits<int16_t>::max());
366 SkASSERT(std::abs(deltaY) < std::numeric_limits<int16_t>::max());
367 int32_t baseInstance = (deltaX & 0xffff) | (deltaY << 16);
368
369 renderEncoder.Draw(/*vertexCount=*/3,
370 /*instanceCount=*/ 1,
371 /*firstVertex=*/0,
372 /*firstInstance=*/baseInstance);
373 }
374
375 // ----------------------------------------------------------------------------
376 DawnResourceProvider::DawnResourceProvider(SharedContext* sharedContext,
377 SingleOwner* singleOwner,
378 uint32_t recorderID,
379 size_t resourceBudget)
380 : ResourceProvider(sharedContext, singleOwner, recorderID, resourceBudget)
381 , fSingleTextureSamplerBindGroups(kMaxNumberOfCachedTextureBindGroups)
382 , fSingleOwner(singleOwner) {
383 fIntrinsicConstantsManager = std::make_unique<IntrinsicConstantsManager>(this);
384
385 // Only used for debug asserts so this avoids compile errors.
386 (void)fSingleOwner;
387 }
388
389 DawnResourceProvider::~DawnResourceProvider() = default;
390
391 DawnResourceProvider::BlitWithDrawEncoder DawnResourceProvider::findOrCreateBlitWithDrawEncoder(
392 const RenderPassDesc& renderPassDesc, SampleCount srcSampleCount) {
393 // Currently Dawn only supports k1 and k4. So we can optimize the pipeline key by specifying
394 // whether the source has MSAA or not.
395 SkASSERT(srcSampleCount == SampleCount::k1 || srcSampleCount == SampleCount::k4);
396 const bool srcIsMSAA = srcSampleCount > SampleCount::k1;
397 const uint32_t pipelineKey = this->dawnSharedContext()->dawnCaps()->getRenderPassDescKeyForPipeline(
398 renderPassDesc, srcIsMSAA);
399 wgpu::RenderPipeline pipeline = fBlitWithDrawPipelines[pipelineKey];
400 if (!pipeline) {
401 // Since texture's sizes are never larger than 16 bits, we can encode the offsets's (x, y)
402 // in one single 32 bits instance index value.
403 static constexpr char kShaderSrc[] =
404 "struct VertexOutput {"
405 "@builtin(position) position: vec4f,"
406 "@location(1) @interpolate(flat, either) srcOffset: vec2i,"
407 "};"
408 "var<private> fullscreenTriPositions : array<vec2<f32>, 3> = array<vec2<f32>, 3>("
409 "vec2(-1.0, -1.0), vec2(-1.0, 3.0), vec2(3.0, -1.0));"
410
411 "@vertex "
412 "fn VS(@builtin(vertex_index) vertexIndex : u32,"
413 "@builtin(instance_index) instanceIndex : u32)"
414 "-> VertexOutput {"
415 "var out: VertexOutput;"
416 "out.position = vec4(fullscreenTriPositions[vertexIndex], 1.0, 1.0);"
417 "var srcOffset = vec2u("
418 "bitcast<u32>(instanceIndex & 0xffff),"
419 "bitcast<u32>(instanceIndex >> 16)"
420 ");"
421
422 // Sign extending from 16 bits to 32 bits
423 "let hasSignBit = (srcOffset & vec2u(0x8000)) != vec2u(0u);"
424 "srcOffset = select(srcOffset, srcOffset | vec2u(0xffff0000), hasSignBit);"
425
426 "out.srcOffset = bitcast<vec2i>(srcOffset);"
427
428 "return out;"
429 "}"
430
431 "fn getSamplingCoords(input: VertexOutput) -> vec2i {"
432 "var coords : vec2<i32> = vec2<i32>(i32(input.position.x), i32(input.position.y));"
433 "return coords - input.srcOffset;"
434 "}"
435
436 "@group(0) @binding(0) var colorMap: texture_2d<f32>;"
437 "@fragment "
438 "fn SampleFS(input: VertexOutput) -> @location(0) vec4<f32> {"
439 "let coords = getSamplingCoords(input);"
440 "return textureLoad(colorMap, coords, 0);"
441 "}"
442
443 "@group(0) @binding(1) var msColorMap: texture_multisampled_2d<f32>;"
444 "@fragment\n"
445 "fn SampleMSAAFS(input: VertexOutput) -> @location(0) vec4<f32> {"
446 "let coords = getSamplingCoords(input);"
447 "const sampleCount = %u;"
448 "var sum = vec4f(0.0);"
449 "for (var i: u32 = 0; i < sampleCount; i = i + 1) {"
450 "sum += textureLoad(msColorMap, coords, i);"
451 "}"
452 "return sum * (1.0 / f32(sampleCount));"
453 "}";
454
455 auto shaderModule = create_shader_module(
456 dawnSharedContext()->device(),
457 SkStringPrintf(kShaderSrc, (unsigned) srcSampleCount).c_str());
458
459 pipeline = create_blit_render_pipeline(
460 dawnSharedContext(),
461 /*label=*/"BlitWithDraw",
462 std::move(shaderModule),
463 "VS",
464 srcIsMSAA ? "SampleMSAAFS": "SampleFS",
465 /*renderPassColorFormat=*/
466 TextureFormatToDawnFormat(renderPassDesc.fColorAttachment.fFormat),
467 /*renderPassDepthStencilFormat=*/
468 TextureFormatToDawnFormat(renderPassDesc.fDepthStencilAttachment.fFormat),
469 renderPassDesc.fColorAttachment.fSampleCount);
470
471 if (pipeline) {
472 fBlitWithDrawPipelines.set(pipelineKey, pipeline);
473 }
474 }
475
476 return BlitWithDrawEncoder(std::move(pipeline), srcIsMSAA);
477 }
478
479 sk_sp<Texture> DawnResourceProvider::onCreateWrappedTexture(const BackendTexture& texture) {
480 // Convert to smart pointers. wgpu::Texture* constructor will increment the ref count.
481 wgpu::Texture dawnTexture = BackendTextures::GetDawnTexturePtr(texture);
482 wgpu::TextureView dawnTextureView = BackendTextures::GetDawnTextureViewPtr(texture);
483 SkASSERT(!dawnTexture || !dawnTextureView);
484
485 if (!dawnTexture && !dawnTextureView) {
486 return {};
487 }
488
489 if (dawnTexture) {
490 return DawnTexture::MakeWrapped(this->dawnSharedContext(),
491 texture.dimensions(),
492 texture.info(),
493 std::move(dawnTexture));
494 } else {
495 return DawnTexture::MakeWrapped(this->dawnSharedContext(),
496 texture.dimensions(),
497 texture.info(),
498 std::move(dawnTextureView));
499 }
500 }
501
502 sk_sp<DawnTexture> DawnResourceProvider::findOrCreateDiscardableMSAALoadTexture(
503 SkISize dimensions, const TextureInfo& msaaInfo) {
504 SkASSERT(msaaInfo.isValid());
505
506 // Derive the load texture's info from MSAA texture's info.
507 DawnTextureInfo dawnMsaaLoadTextureInfo = TextureInfoPriv::Get<DawnTextureInfo>(msaaInfo);
508 dawnMsaaLoadTextureInfo.fSampleCount = SampleCount::k1;
509 dawnMsaaLoadTextureInfo.fUsage |= wgpu::TextureUsage::TextureBinding;
510
511 #if !defined(__EMSCRIPTEN__)
512 // MSAA texture can be transient attachment (memoryless) but the load texture cannot be.
513 // This is because the load texture will need to have its content retained between two passes
514 // loading:
515 // - first pass: the resolve texture is blitted to the load texture.
516 // - 2nd pass: the actual render pass is started and the load texture is blitted to the MSAA
517 // texture.
518 dawnMsaaLoadTextureInfo.fUsage &= (~wgpu::TextureUsage::TransientAttachment);
519 #endif
520
521 auto texture = this->findOrCreateShareableTexture(
522 dimensions,
523 TextureInfos::MakeDawn(dawnMsaaLoadTextureInfo),
524 "DiscardableLoadMSAATexture");
525
526 return sk_sp<DawnTexture>(static_cast<DawnTexture*>(texture.release()));
527 }
528
529 sk_sp<ComputePipeline> DawnResourceProvider::createComputePipeline(
530 const ComputePipelineDesc& desc) {
531 return DawnComputePipeline::Make(this->dawnSharedContext(), desc);
532 }
533
534 sk_sp<Texture> DawnResourceProvider::createTexture(SkISize dimensions, const TextureInfo& info) {
535 return DawnTexture::Make(this->dawnSharedContext(), dimensions, info);
536 }
537
538 sk_sp<Buffer> DawnResourceProvider::createBuffer(size_t size,
539 BufferType type,
540 AccessPattern accessPattern) {
541 return DawnBuffer::Make(this->dawnSharedContext(), size, type, accessPattern);
542 }
543
544 sk_sp<Sampler> DawnResourceProvider::createSampler(const SamplerDesc& samplerDesc) {
545 return DawnSampler::Make(this->dawnSharedContext(), samplerDesc);
546 }
547
548 BackendTexture DawnResourceProvider::onCreateBackendTexture(SkISize dimensions,
549 const TextureInfo& info) {
550 wgpu::Texture texture = DawnTexture::MakeDawnTexture(this->dawnSharedContext(),
551 dimensions,
552 info);
553 if (!texture) {
554 return {};
555 }
556
557 return BackendTextures::MakeDawn(texture.MoveToCHandle());
558 }
559
560 void DawnResourceProvider::onDeleteBackendTexture(const BackendTexture& texture) {
561 SkASSERT(texture.isValid());
562 SkASSERT(texture.backend() == BackendApi::kDawn);
563
564 // Automatically release the pointers in wgpu::TextureView & wgpu::Texture's dtor.
565 // Acquire() won't increment the ref count.
566 wgpu::TextureView::Acquire(BackendTextures::GetDawnTextureViewPtr(texture));
567 // We need to explicitly call Destroy() here since since that is the recommended way to delete
568 // a Dawn texture predictably versus just dropping a ref and relying on garbage collection.
569 //
570 // Additionally this helps to work around an issue where Skia may have cached a BindGroup that
571 // references the underlying texture. Skia currently doesn't destroy BindGroups when its use of
572 // the texture goes away, thus a ref to the texture remains on the BindGroup and memory is never
573 // cleared up unless we call Destroy() here.
574 wgpu::Texture::Acquire(BackendTextures::GetDawnTexturePtr(texture)).Destroy();
575 }
576
577 DawnSharedContext* DawnResourceProvider::dawnSharedContext() const {
578 return static_cast<DawnSharedContext*>(fSharedContext);
579 }
580
581 sk_sp<DawnBuffer> DawnResourceProvider::findOrCreateDawnBuffer(size_t size,
582 BufferType type,
583 AccessPattern accessPattern,
584 std::string_view label) {
585 sk_sp<Buffer> buffer = this->findOrCreateNonShareableBuffer(size, type, accessPattern, label);
586 DawnBuffer* ptr = static_cast<DawnBuffer*>(buffer.release());
587 return sk_sp<DawnBuffer>(ptr);
588 }
589
590 const wgpu::Buffer& DawnResourceProvider::getOrCreateNullBuffer() {
591 if (!fNullBuffer) {
592 wgpu::BufferDescriptor desc;
593 if (fSharedContext->caps()->setBackendLabels()) {
594 desc.label = "UnusedBufferSlot";
595 }
596 desc.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::Uniform |
597 wgpu::BufferUsage::Storage;
598 desc.size = kBufferBindingSizeAlignment;
599 desc.mappedAtCreation = false;
600
601 fNullBuffer = this->dawnSharedContext()->device().CreateBuffer(&desc);
602 SkASSERT(fNullBuffer);
603 }
604
605 return fNullBuffer;
606 }
607
•608 wgpu::BindGroup DawnResourceProvider::findOrCreateSingleUniformBindGroup(
609 const BindBufferInfo& bufferInfo) {
610 SKGPU_ASSERT_SINGLE_OWNER(fSingleOwner)
•611 // We should only hit the single-uniform case if push constant usage is supported for intrinsic
612 // constants.
613 SkASSERT(this->dawnSharedContext()->dawnCaps()->
614 resourceBindingRequirements().fUsePushConstantsForIntrinsicConstants);
615
616 auto buffer = static_cast<const DawnBuffer*>(bufferInfo.fBuffer);
617
618 if (auto cachedBindGroup = buffer->getCachedSingleBufferBindGroup(bufferInfo.fSize)) {
619 return *cachedBindGroup;
620 }
621
622 // We should be able to assume that if we only have one uniform that it is the combined uniform
623 // buffer. Construct a list of bind group entries to represent the single combined uniform
624 // buffer case.
625 wgpu::BindGroupEntry intrinsicConstantNullEntry;
626 intrinsicConstantNullEntry.binding = DawnGraphicsPipeline::kIntrinsicUniformBufferIndex;
627 intrinsicConstantNullEntry.buffer = this->getOrCreateNullBuffer();
628
629 wgpu::BindGroupEntry combinedUniformEntry;
630 combinedUniformEntry.binding = DawnGraphicsPipeline::kCombinedUniformIndex;
631 combinedUniformEntry.offset = 0; // Use dynamic offsets; ignore bufferInfo.fOffset
632 combinedUniformEntry.buffer = buffer->dawnBuffer();
633 combinedUniformEntry.size = SkAlignTo(bufferInfo.fSize, kBufferBindingSizeAlignment);
634
635 wgpu::BindGroupEntry gradientBufferNullEntry;
636 gradientBufferNullEntry.binding = DawnGraphicsPipeline::kGradientBufferIndex;
637 gradientBufferNullEntry.buffer = this->getOrCreateNullBuffer();
638
639 std::array<wgpu::BindGroupEntry, kNumUniformEntries> entries = {
640 intrinsicConstantNullEntry,
641 combinedUniformEntry,
642 gradientBufferNullEntry
643 };
644
•645 wgpu::BindGroup bindGroup = this->createBindGroup(
646 entries, this->dawnSharedContext()->getUniformBuffersBindGroupLayout());
647
•648 buffer->addCachedSingleBufferBindGroup(bindGroup, bufferInfo.fSize);
649
•650 return bindGroup;
651 }
652
•653
654 const wgpu::BindGroup& DawnResourceProvider::findOrCreateSingleTextureSamplerBindGroup(
655 const DawnSampler* sampler, const DawnTexture* texture) {
656 SKGPU_ASSERT_SINGLE_OWNER(fSingleOwner)
657
658 auto key = make_texture_bind_group_key(sampler, texture);
659 auto* existingBindGroup = fSingleTextureSamplerBindGroups.find(key);
660 if (existingBindGroup) {
661 // cache hit.
662 return *existingBindGroup;
663 }
664
665 std::array<wgpu::BindGroupEntry, 2> entries;
666
667 entries[0].binding = 0;
668 entries[0].sampler = sampler->dawnSampler();
669 entries[1].binding = 1;
670 entries[1].textureView = texture->sampleTextureView();
671
672 wgpu::BindGroupDescriptor desc;
673 desc.layout = this->dawnSharedContext()->getSingleTextureSamplerBindGroupLayout();
674 desc.entryCount = entries.size();
675 desc.entries = entries.data();
676
677 const auto& device = this->dawnSharedContext()->device();
678 auto bindGroup = device.CreateBindGroup(&desc);
679
680 return *fSingleTextureSamplerBindGroups.insert(key, bindGroup);
681 }
682
683 void DawnResourceProvider::onFreeGpuResources() {
684 SKGPU_ASSERT_SINGLE_OWNER(fSingleOwner)
685
686 fIntrinsicConstantsManager->freeGpuResources();
687 // The wgpu::Textures and wgpu::Buffers held by the BindGroups should be explicitly destroyed
688 // when the DawnTexture and DawnBuffer is destroyed, but removing the bind groups themselves
689 // helps reduce CPU memory periodically.
690 fSingleTextureSamplerBindGroups.reset();
691 }
692
693 void DawnResourceProvider::onPurgeResourcesNotUsedSince(StdSteadyClock::time_point purgeTime) {
694 fIntrinsicConstantsManager->purgeResourcesNotUsedSince(purgeTime);
695 }
696
697 BindBufferInfo DawnResourceProvider::findOrCreateIntrinsicBindBufferInfo(
698 DawnCommandBuffer* cb, UniformDataBlock intrinsicValues) {
699 return fIntrinsicConstantsManager->add(cb, intrinsicValues);
700 }
701
702 DawnThreadSafeResourceProvider::DawnThreadSafeResourceProvider(
703 std::unique_ptr<ResourceProvider> resourceProvider)
704 : ThreadSafeResourceProvider(std::move(resourceProvider)) {}
705
706 } // namespace skgpu::graphite