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