• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2021 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/ResourceProvider.h"
9 
10 #include "include/core/SkSamplingOptions.h"
11 #include "include/core/SkTileMode.h"
12 #include "include/gpu/graphite/BackendTexture.h"
13 #include "src/core/SkTraceEvent.h"
14 #include "src/gpu/graphite/Buffer.h"
15 #include "src/gpu/graphite/Caps.h"
16 #include "src/gpu/graphite/CommandBuffer.h"
17 #include "src/gpu/graphite/ComputePipeline.h"
18 #include "src/gpu/graphite/ContextPriv.h"
19 #include "src/gpu/graphite/ContextUtils.h"
20 #include "src/gpu/graphite/GlobalCache.h"
21 #include "src/gpu/graphite/GraphicsPipeline.h"
22 #include "src/gpu/graphite/GraphicsPipelineDesc.h"
23 #include "src/gpu/graphite/Log.h"
24 #include "src/gpu/graphite/RenderPassDesc.h"
25 #include "src/gpu/graphite/RendererProvider.h"
26 #include "src/gpu/graphite/ResourceCache.h"
27 #include "src/gpu/graphite/Sampler.h"
28 #include "src/gpu/graphite/SharedContext.h"
29 #include "src/gpu/graphite/Texture.h"
30 #include "src/sksl/SkSLCompiler.h"
31 
32 namespace skgpu::graphite {
33 
34 // This is only used when tracing is enabled at compile time.
to_str(const SharedContext * ctx,const GraphicsPipelineDesc & gpDesc,const RenderPassDesc & rpDesc)35 [[maybe_unused]] static std::string to_str(const SharedContext* ctx,
36                                            const GraphicsPipelineDesc& gpDesc,
37                                            const RenderPassDesc& rpDesc) {
38     const ShaderCodeDictionary* dict = ctx->shaderCodeDictionary();
39     const RenderStep* step = ctx->rendererProvider()->lookup(gpDesc.renderStepID());
40     return GetPipelineLabel(dict, rpDesc, step, gpDesc.paintParamsID());
41 }
42 
ResourceProvider(SharedContext * sharedContext,SingleOwner * singleOwner,uint32_t recorderID,size_t resourceBudget)43 ResourceProvider::ResourceProvider(SharedContext* sharedContext,\
44                                    SingleOwner* singleOwner,
45                                    uint32_t recorderID,
46                                    size_t resourceBudget)
47         : fSharedContext(sharedContext)
48         , fResourceCache(ResourceCache::Make(singleOwner, recorderID, resourceBudget)) {}
49 
~ResourceProvider()50 ResourceProvider::~ResourceProvider() {
51     fResourceCache->shutdown();
52 }
53 
findOrCreateGraphicsPipeline(const RuntimeEffectDictionary * runtimeDict,const GraphicsPipelineDesc & pipelineDesc,const RenderPassDesc & renderPassDesc,SkEnumBitMask<PipelineCreationFlags> pipelineCreationFlags)54 sk_sp<GraphicsPipeline> ResourceProvider::findOrCreateGraphicsPipeline(
55         const RuntimeEffectDictionary* runtimeDict,
56         const GraphicsPipelineDesc& pipelineDesc,
57         const RenderPassDesc& renderPassDesc,
58         SkEnumBitMask<PipelineCreationFlags> pipelineCreationFlags) {
59 
60     auto globalCache = fSharedContext->globalCache();
61     UniqueKey pipelineKey = fSharedContext->caps()->makeGraphicsPipelineKey(pipelineDesc,
62                                                                             renderPassDesc);
63 
64     uint32_t compilationID = 0;
65     sk_sp<GraphicsPipeline> pipeline = globalCache->findGraphicsPipeline(pipelineKey,
66                                                                          pipelineCreationFlags,
67                                                                          &compilationID);
68     if (!pipeline) {
69         // Haven't encountered this pipeline, so create a new one. Since pipelines are shared
70         // across Recorders, we could theoretically create equivalent pipelines on different
71         // threads. If this happens, GlobalCache returns the first-through-gate pipeline and we
72         // discard the redundant pipeline. While this is wasted effort in the rare event of a race,
73         // it allows pipeline creation to be performed without locking the global cache.
74         // NOTE: The parameters to TRACE_EVENT are only evaluated inside an if-block when the
75         // category is enabled.
76         TRACE_EVENT1_ALWAYS(
77                 "skia.shaders", "createGraphicsPipeline", "desc",
78                 TRACE_STR_COPY(to_str(fSharedContext, pipelineDesc, renderPassDesc).c_str()));
79 
80 #if defined(SK_PIPELINE_LIFETIME_LOGGING)
81         bool forPrecompile =
82                 SkToBool(pipelineCreationFlags & PipelineCreationFlags::kForPrecompilation);
83 
84         static const char* kNames[2] = { "BeginBuildN", "BeginBuildP" };
85         TRACE_EVENT_INSTANT2("skia.gpu",
86                              TRACE_STR_STATIC(kNames[forPrecompile]),
87                              TRACE_EVENT_SCOPE_THREAD,
88                              "key", pipelineKey.hash(),
89                              "compilationID", compilationID);
90 #endif
91 
92         pipeline = this->createGraphicsPipeline(runtimeDict, pipelineKey,
93                                                 pipelineDesc, renderPassDesc,
94                                                 pipelineCreationFlags,
95                                                 compilationID);
96         if (pipeline) {
97             // TODO: Should we store a null pipeline if we failed to create one so that subsequent
98             // usage immediately sees that the pipeline cannot be created, vs. retrying every time?
99             pipeline = globalCache->addGraphicsPipeline(pipelineKey, std::move(pipeline));
100         }
101     }
102     return pipeline;
103 }
104 
findOrCreateComputePipeline(const ComputePipelineDesc & pipelineDesc)105 sk_sp<ComputePipeline> ResourceProvider::findOrCreateComputePipeline(
106         const ComputePipelineDesc& pipelineDesc) {
107     auto globalCache = fSharedContext->globalCache();
108     UniqueKey pipelineKey = fSharedContext->caps()->makeComputePipelineKey(pipelineDesc);
109     sk_sp<ComputePipeline> pipeline = globalCache->findComputePipeline(pipelineKey);
110     if (!pipeline) {
111         pipeline = this->createComputePipeline(pipelineDesc);
112         if (pipeline) {
113             pipeline = globalCache->addComputePipeline(pipelineKey, std::move(pipeline));
114         }
115     }
116     return pipeline;
117 }
118 
119 ////////////////////////////////////////////////////////////////////////////////////////////////
120 
findOrCreateScratchTexture(SkISize dimensions,const TextureInfo & info,std::string_view label,skgpu::Budgeted budgeted)121 sk_sp<Texture> ResourceProvider::findOrCreateScratchTexture(SkISize dimensions,
122                                                             const TextureInfo& info,
123                                                             std::string_view label,
124                                                             skgpu::Budgeted budgeted) {
125     SkASSERT(info.isValid());
126 
127     static const ResourceType kType = GraphiteResourceKey::GenerateResourceType();
128 
129     GraphiteResourceKey key;
130     // Scratch textures are not shareable
131     fSharedContext->caps()->buildKeyForTexture(dimensions, info, kType, Shareable::kNo, &key);
132 
133     return this->findOrCreateTextureWithKey(dimensions,
134                                             info,
135                                             key,
136                                             std::move(label),
137                                             budgeted);
138 }
139 
findOrCreateDepthStencilAttachment(SkISize dimensions,const TextureInfo & info)140 sk_sp<Texture> ResourceProvider::findOrCreateDepthStencilAttachment(SkISize dimensions,
141                                                                     const TextureInfo& info) {
142     SkASSERT(info.isValid());
143 
144     static const ResourceType kType = GraphiteResourceKey::GenerateResourceType();
145 
146     GraphiteResourceKey key;
147     // We always make depth and stencil attachments shareable. Between any render pass the values
148     // are reset. Thus it is safe to be used by multiple different render passes without worry of
149     // stomping on each other's data.
150     fSharedContext->caps()->buildKeyForTexture(dimensions, info, kType, Shareable::kYes, &key);
151 
152     return this->findOrCreateTextureWithKey(dimensions,
153                                             info,
154                                             key,
155                                             "DepthStencilAttachment",
156                                             skgpu::Budgeted::kYes);
157 }
158 
findOrCreateDiscardableMSAAAttachment(SkISize dimensions,const TextureInfo & info)159 sk_sp<Texture> ResourceProvider::findOrCreateDiscardableMSAAAttachment(SkISize dimensions,
160                                                                        const TextureInfo& info) {
161     SkASSERT(info.isValid());
162 
163     static const ResourceType kType = GraphiteResourceKey::GenerateResourceType();
164 
165     GraphiteResourceKey key;
166     // We always make discardable msaa attachments shareable. Between any render pass we discard
167     // the values of the MSAA texture. Thus it is safe to be used by multiple different render
168     // passes without worry of stomping on each other's data. It is the callings code's
169     // responsibility to populate the discardable MSAA texture with data at the start of the
170     // render pass.
171     fSharedContext->caps()->buildKeyForTexture(dimensions, info, kType, Shareable::kYes, &key);
172 
173     return this->findOrCreateTextureWithKey(dimensions,
174                                             info,
175                                             key,
176                                             "DiscardableMSAAAttachment",
177                                             skgpu::Budgeted::kYes);
178 }
179 
findOrCreateTextureWithKey(SkISize dimensions,const TextureInfo & info,const GraphiteResourceKey & key,std::string_view label,skgpu::Budgeted budgeted)180 sk_sp<Texture> ResourceProvider::findOrCreateTextureWithKey(SkISize dimensions,
181                                                             const TextureInfo& info,
182                                                             const GraphiteResourceKey& key,
183                                                             std::string_view label,
184                                                             skgpu::Budgeted budgeted) {
185     // If the resource is shareable it should be budgeted since it shouldn't be backing any client
186     // owned object.
187     SkASSERT(key.shareable() == Shareable::kNo || budgeted == skgpu::Budgeted::kYes);
188 
189     if (Resource* resource = fResourceCache->findAndRefResource(key, budgeted)) {
190         resource->setLabel(std::move(label));
191         return sk_sp<Texture>(static_cast<Texture*>(resource));
192     }
193 
194     auto tex = this->createTexture(dimensions, info, budgeted);
195     if (!tex) {
196         return nullptr;
197     }
198 
199     tex->setKey(key);
200     tex->setLabel(std::move(label));
201     fResourceCache->insertResource(tex.get());
202 
203     return tex;
204 }
205 
createWrappedTexture(const BackendTexture & backendTexture,std::string_view label)206 sk_sp<Texture> ResourceProvider::createWrappedTexture(const BackendTexture& backendTexture,
207                                                       std::string_view label) {
208     sk_sp<Texture> texture = this->onCreateWrappedTexture(backendTexture);
209     if (texture) {
210         texture->setLabel(std::move(label));
211     }
212     return texture;
213 }
214 
findOrCreateCompatibleSampler(const SamplerDesc & samplerDesc)215 sk_sp<Sampler> ResourceProvider::findOrCreateCompatibleSampler(const SamplerDesc& samplerDesc) {
216     GraphiteResourceKey key = fSharedContext->caps()->makeSamplerKey(samplerDesc);
217 
218     if (Resource* resource = fResourceCache->findAndRefResource(key, skgpu::Budgeted::kYes)) {
219         return sk_sp<Sampler>(static_cast<Sampler*>(resource));
220     }
221 
222     sk_sp<Sampler> sampler = this->createSampler(samplerDesc);
223     if (!sampler) {
224         return nullptr;
225     }
226 
227     sampler->setKey(key);
228     fResourceCache->insertResource(sampler.get());
229     return sampler;
230 }
231 
findOrCreateBuffer(size_t size,BufferType type,AccessPattern accessPattern,std::string_view label)232 sk_sp<Buffer> ResourceProvider::findOrCreateBuffer(size_t size,
233                                                    BufferType type,
234                                                    AccessPattern accessPattern,
235                                                    std::string_view label) {
236     static const ResourceType kType = GraphiteResourceKey::GenerateResourceType();
237 
238     GraphiteResourceKey key;
239     {
240         // For the key we need ((sizeof(size_t) + (sizeof(uint32_t) - 1)) / (sizeof(uint32_t))
241         // uint32_t's for the size and one uint32_t for the rest.
242         static_assert(sizeof(uint32_t) == 4);
243         static const int kSizeKeyNum32DataCnt = (sizeof(size_t) + 3) / 4;
244         static const int kKeyNum32DataCnt =  kSizeKeyNum32DataCnt + 1;
245 
246         SkASSERT(static_cast<uint32_t>(type) < (1u << 4));
247         SkASSERT(static_cast<uint32_t>(accessPattern) < (1u << 1));
248 
249         GraphiteResourceKey::Builder builder(&key, kType, kKeyNum32DataCnt, Shareable::kNo);
250         builder[0] = (static_cast<uint32_t>(type) << 0) |
251                      (static_cast<uint32_t>(accessPattern) << 4);
252         size_t szKey = size;
253         for (int i = 0; i < kSizeKeyNum32DataCnt; ++i) {
254             builder[i + 1] = (uint32_t) szKey;
255 
256             // If size_t is 4 bytes, we cannot do a shift of 32 or else we get a warning/error that
257             // shift amount is >= width of the type.
258             if constexpr(kSizeKeyNum32DataCnt > 1) {
259                 szKey = szKey >> 32;
260             }
261         }
262     }
263 
264     skgpu::Budgeted budgeted = skgpu::Budgeted::kYes;
265     if (Resource* resource = fResourceCache->findAndRefResource(key, budgeted)) {
266         resource->setLabel(std::move(label));
267         return sk_sp<Buffer>(static_cast<Buffer*>(resource));
268     }
269     auto buffer = this->createBuffer(size, type, accessPattern);
270     if (!buffer) {
271         return nullptr;
272     }
273 
274     buffer->setKey(key);
275     buffer->setLabel(std::move(label));
276     fResourceCache->insertResource(buffer.get());
277     return buffer;
278 }
279 
280 namespace {
dimensions_are_valid(const int maxTextureSize,const SkISize & dimensions)281 bool dimensions_are_valid(const int maxTextureSize, const SkISize& dimensions) {
282     if (dimensions.isEmpty() ||
283         dimensions.width()  > maxTextureSize ||
284         dimensions.height() > maxTextureSize) {
285         SKGPU_LOG_W("Call to createBackendTexture has requested dimensions (%d, %d) larger than the"
286                     " supported gpu max texture size: %d. Or the dimensions are empty.",
287                     dimensions.fWidth, dimensions.fHeight, maxTextureSize);
288         return false;
289     }
290     return true;
291 }
292 }
293 
createBackendTexture(SkISize dimensions,const TextureInfo & info)294 BackendTexture ResourceProvider::createBackendTexture(SkISize dimensions, const TextureInfo& info) {
295     if (!dimensions_are_valid(fSharedContext->caps()->maxTextureSize(), dimensions)) {
296         return {};
297     }
298     return this->onCreateBackendTexture(dimensions, info);
299 }
300 
301 #ifdef SK_BUILD_FOR_ANDROID
createBackendTexture(AHardwareBuffer * hardwareBuffer,bool isRenderable,bool isProtectedContent,SkISize dimensions,bool fromAndroidWindow) const302 BackendTexture ResourceProvider::createBackendTexture(AHardwareBuffer* hardwareBuffer,
303                                                       bool isRenderable,
304                                                       bool isProtectedContent,
305                                                       SkISize dimensions,
306                                                       bool fromAndroidWindow) const {
307     if (!dimensions_are_valid(fSharedContext->caps()->maxTextureSize(), dimensions)) {
308         return {};
309     }
310     return this->onCreateBackendTexture(hardwareBuffer,
311                                         isRenderable,
312                                         isProtectedContent,
313                                         dimensions,
314                                         fromAndroidWindow);
315 }
316 
onCreateBackendTexture(AHardwareBuffer *,bool isRenderable,bool isProtectedContent,SkISize dimensions,bool fromAndroidWindow) const317 BackendTexture ResourceProvider::onCreateBackendTexture(AHardwareBuffer*,
318                                                         bool isRenderable,
319                                                         bool isProtectedContent,
320                                                         SkISize dimensions,
321                                                         bool fromAndroidWindow) const {
322     return {};
323 }
324 #endif
325 
deleteBackendTexture(const BackendTexture & texture)326 void ResourceProvider::deleteBackendTexture(const BackendTexture& texture) {
327     this->onDeleteBackendTexture(texture);
328 }
329 
freeGpuResources()330 void ResourceProvider::freeGpuResources() {
331     this->onFreeGpuResources();
332 
333     // TODO: Are there Resources that are ref'd by the ResourceProvider or its subclasses that need
334     // be released? If we ever find that we're holding things directly on the ResourceProviders we
335     // call down into the subclasses to allow them to release things.
336 
337     fResourceCache->purgeResources();
338 }
339 
purgeResourcesNotUsedSince(StdSteadyClock::time_point purgeTime)340 void ResourceProvider::purgeResourcesNotUsedSince(StdSteadyClock::time_point purgeTime) {
341     this->onPurgeResourcesNotUsedSince(purgeTime);
342     fResourceCache->purgeResourcesNotUsedSince(purgeTime);
343 }
344 
345 }  // namespace skgpu::graphite
346