1 /*
2  * Copyright 2015 Google Inc.
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 #ifndef GrResourceProvider_DEFINED
9 #define GrResourceProvider_DEFINED
10 
11 #include "GrBuffer.h"
12 #include "GrContextOptions.h"
13 #include "GrPathRange.h"
14 #include "GrResourceCache.h"
15 #include "SkImageInfoPriv.h"
16 #include "SkScalerContext.h"
17 
18 class GrBackendRenderTarget;
19 class GrBackendSemaphore;
20 class GrBackendTexture;
21 class GrGpu;
22 class GrPath;
23 class GrRenderTarget;
24 class GrResourceProviderPriv;
25 class GrSemaphore;
26 class GrSingleOwner;
27 class GrStencilAttachment;
28 class GrTexture;
29 
30 class GrStyle;
31 class SkDescriptor;
32 class SkPath;
33 class SkTypeface;
34 
35 /**
36  * A factory for arbitrary resource types. This class is intended for use within the Gr code base.
37  *
38  * Some members force callers to make a flags (pendingIO) decision. This can be relaxed once
39  * https://bug.skia.org/4156 is fixed.
40  */
41 class GrResourceProvider {
42 public:
43     GrResourceProvider(GrGpu*, GrResourceCache*, GrSingleOwner*,
44                        GrContextOptions::Enable explicitlyAllocateGPUResources);
45 
46     /**
47      * Finds a resource in the cache, based on the specified key. Prior to calling this, the caller
48      * must be sure that if a resource of exists in the cache with the given unique key then it is
49      * of type T.
50      */
51     template <typename T>
findByUniqueKey(const GrUniqueKey & key)52     sk_sp<T> findByUniqueKey(const GrUniqueKey& key) {
53         return sk_sp<T>(static_cast<T*>(this->findResourceByUniqueKey(key).release()));
54     }
55 
56     ///////////////////////////////////////////////////////////////////////////
57     // Textures
58 
59     /**
60      * Finds a texture that approximately matches the descriptor. Will be at least as large in width
61      * and height as desc specifies. If desc specifies that the texture should be a render target
62      * then result will be a render target. Format and sample count will always match the request.
63      * The contents of the texture are undefined.
64      */
65     sk_sp<GrTexture> createApproxTexture(const GrSurfaceDesc&, uint32_t flags);
66 
67     /** Create an exact fit texture with no initial data to upload.
68      */
69     sk_sp<GrTexture> createTexture(const GrSurfaceDesc&, SkBudgeted, uint32_t flags = 0);
70 
71     sk_sp<GrTexture> createTexture(const GrSurfaceDesc&, SkBudgeted,
72                                    const GrMipLevel texels[], int mipLevelCount,
73                                    SkDestinationSurfaceColorMode mipColorMode);
74 
75     // Create a potentially loose fit texture with the provided data
76     sk_sp<GrTexture> createTexture(const GrSurfaceDesc&, SkBudgeted, SkBackingFit,
77                                    const GrMipLevel&);
78 
79     ///////////////////////////////////////////////////////////////////////////
80     // Wrapped Backend Surfaces
81 
82     /**
83      * Wraps an existing texture with a GrTexture object.
84      *
85      * OpenGL: if the object is a texture Gr may change its GL texture params
86      *         when it is drawn.
87      *
88      * @return GrTexture object or NULL on failure.
89      */
90     sk_sp<GrTexture> wrapBackendTexture(const GrBackendTexture& tex,
91                                         GrWrapOwnership = kBorrow_GrWrapOwnership);
92 
93     /**
94      * This makes the backend texture be renderable. If sampleCnt is > 1 and the underlying API
95      * uses separate MSAA render buffers then a MSAA render buffer is created that resolves
96      * to the texture.
97      */
98     sk_sp<GrTexture> wrapRenderableBackendTexture(const GrBackendTexture& tex,
99                                                   int sampleCnt,
100                                                   GrWrapOwnership = kBorrow_GrWrapOwnership);
101 
102     /**
103      * Wraps an existing render target with a GrRenderTarget object. It is
104      * similar to wrapBackendTexture but can be used to draw into surfaces
105      * that are not also textures (e.g. FBO 0 in OpenGL, or an MSAA buffer that
106      * the client will resolve to a texture). Currently wrapped render targets
107      * always use the kBorrow_GrWrapOwnership semantics.
108      *
109      * @return GrRenderTarget object or NULL on failure.
110      */
111     sk_sp<GrRenderTarget> wrapBackendRenderTarget(const GrBackendRenderTarget&);
112 
113     static const uint32_t kMinScratchTextureSize;
114 
115     /**
116      * Either finds and refs, or creates a static buffer with the given parameters and contents.
117      *
118      * @param intendedType    hint to the graphics subsystem about what the buffer will be used for.
119      * @param size            minimum size of buffer to return.
120      * @param data            optional data with which to initialize the buffer.
121      * @param key             Key to be assigned to the buffer.
122      *
123      * @return The buffer if successful, otherwise nullptr.
124      */
125     sk_sp<const GrBuffer> findOrMakeStaticBuffer(GrBufferType intendedType, size_t size,
126                                                  const void* data, const GrUniqueKey& key);
127 
128     /**
129      * Either finds and refs, or creates an index buffer with a repeating pattern for drawing
130      * contiguous vertices of a repeated mesh. If the return is non-null, the caller owns a ref on
131      * the returned GrBuffer.
132      *
133      * @param pattern     the pattern of indices to repeat
134      * @param patternSize size in bytes of the pattern
135      * @param reps        number of times to repeat the pattern
136      * @param vertCount   number of vertices the pattern references
137      * @param key         Key to be assigned to the index buffer.
138      *
139      * @return The index buffer if successful, otherwise nullptr.
140      */
findOrCreatePatternedIndexBuffer(const uint16_t * pattern,int patternSize,int reps,int vertCount,const GrUniqueKey & key)141     sk_sp<const GrBuffer> findOrCreatePatternedIndexBuffer(const uint16_t* pattern,
142                                                            int patternSize,
143                                                            int reps,
144                                                            int vertCount,
145                                                            const GrUniqueKey& key) {
146         if (auto buffer = this->findByUniqueKey<GrBuffer>(key)) {
147             return buffer;
148         }
149         return this->createPatternedIndexBuffer(pattern, patternSize, reps, vertCount, key);
150     }
151 
152     /**
153      * Returns an index buffer that can be used to render quads.
154      * Six indices per quad: 0, 1, 2, 2, 1, 3, etc.
155      * The max number of quads is the buffer's index capacity divided by 6.
156      * Draw with GrPrimitiveType::kTriangles
157      * @ return the quad index buffer
158      */
refQuadIndexBuffer()159     sk_sp<const GrBuffer> refQuadIndexBuffer() {
160         if (auto buffer = this->findByUniqueKey<const GrBuffer>(fQuadIndexBufferKey)) {
161             return buffer;
162         }
163         return this->createQuadIndexBuffer();
164     }
165 
166     static int QuadCountOfQuadBuffer();
167 
168     /**
169      * Factories for GrPath and GrPathRange objects. It's an error to call these if path rendering
170      * is not supported.
171      */
172     sk_sp<GrPath> createPath(const SkPath&, const GrStyle&);
173     sk_sp<GrPathRange> createPathRange(GrPathRange::PathGenerator*, const GrStyle&);
174     sk_sp<GrPathRange> createGlyphs(const SkTypeface*, const SkScalerContextEffects&,
175                                     const SkDescriptor*, const GrStyle&);
176 
177     /** These flags govern which scratch resources we are allowed to return */
178     enum Flags {
179         /** If the caller intends to do direct reads/writes to/from the CPU then this flag must be
180          *  set when accessing resources during a GrOpList flush. This includes the execution of
181          *  GrOp objects. The reason is that these memory operations are done immediately and
182          *  will occur out of order WRT the operations being flushed.
183          *  Make this automatic: https://bug.skia.org/4156
184          */
185         kNoPendingIO_Flag     = 0x1,
186 
187         /** Normally the caps may indicate a preference for client-side buffers. Set this flag when
188          *  creating a buffer to guarantee it resides in GPU memory.
189          */
190         kRequireGpuMemory_Flag = 0x2,
191     };
192 
193     /**
194      * Returns a buffer.
195      *
196      * @param size            minimum size of buffer to return.
197      * @param intendedType    hint to the graphics subsystem about what the buffer will be used for.
198      * @param GrAccessPattern hint to the graphics subsystem about how the data will be accessed.
199      * @param flags           see Flags enum.
200      * @param data            optional data with which to initialize the buffer.
201      *
202      * @return the buffer if successful, otherwise nullptr.
203      */
204     GrBuffer* createBuffer(size_t size, GrBufferType intendedType, GrAccessPattern, uint32_t flags,
205                            const void* data = nullptr);
206 
207 
208     /**
209      * If passed in render target already has a stencil buffer, return true. Otherwise attempt to
210      * attach one and return true on success.
211      */
212     bool attachStencilAttachment(GrRenderTarget* rt);
213 
214      /**
215       * Wraps an existing texture with a GrRenderTarget object. This is useful when the provided
216       * texture has a format that cannot be textured from by Skia, but we want to raster to it.
217       *
218       * The texture is wrapped as borrowed. The texture object will not be freed once the
219       * render target is destroyed.
220       *
221       * @return GrRenderTarget object or NULL on failure.
222       */
223      sk_sp<GrRenderTarget> wrapBackendTextureAsRenderTarget(const GrBackendTexture&,
224                                                             int sampleCnt);
225 
226     /**
227      * Assigns a unique key to a resource. If the key is associated with another resource that
228      * association is removed and replaced by this resource.
229      */
230     void assignUniqueKeyToResource(const GrUniqueKey&, GrGpuResource*);
231 
232     sk_sp<GrSemaphore> SK_WARN_UNUSED_RESULT makeSemaphore(bool isOwned = true);
233 
234     enum class SemaphoreWrapType {
235         kWillSignal,
236         kWillWait,
237     };
238 
239     sk_sp<GrSemaphore> wrapBackendSemaphore(const GrBackendSemaphore&,
240                                             SemaphoreWrapType wrapType,
241                                             GrWrapOwnership = kBorrow_GrWrapOwnership);
242 
243     // Takes the GrSemaphore and sets the ownership of the semaphore to the GrGpu object used by
244     // this class. This call is only used when passing a GrSemaphore from one context to another.
245     void takeOwnershipOfSemaphore(sk_sp<GrSemaphore>);
246     // Takes the GrSemaphore and resets the ownership of the semaphore so that it is not owned by
247     // any GrGpu. A follow up call to takeOwnershipofSemaphore must be made so that the underlying
248     // semaphore can be deleted. This call is only used when passing a GrSemaphore from one context
249     // to another.
250     void releaseOwnershipOfSemaphore(sk_sp<GrSemaphore>);
251 
abandon()252     void abandon() {
253         fCache = nullptr;
254         fGpu = nullptr;
255     }
256 
caps()257     const GrCaps* caps() const { return fCaps.get(); }
overBudget()258     bool overBudget() const { return fCache->overBudget(); }
259 
260     inline GrResourceProviderPriv priv();
261     inline const GrResourceProviderPriv priv() const;
262 
explicitlyAllocateGPUResources()263     bool explicitlyAllocateGPUResources() const { return fExplicitlyAllocateGPUResources; }
264 
265     bool testingOnly_setExplicitlyAllocateGPUResources(bool newValue);
266 
267 private:
268     sk_sp<GrGpuResource> findResourceByUniqueKey(const GrUniqueKey&);
269 
270     // Attempts to find a resource in the cache that exactly matches the GrSurfaceDesc. Failing that
271     // it returns null. If non-null, the resulting texture is always budgeted.
272     sk_sp<GrTexture> refScratchTexture(const GrSurfaceDesc&, uint32_t scratchTextureFlags);
273 
274     /*
275      * Try to find an existing scratch texture that exactly matches 'desc'. If successful
276      * update the budgeting accordingly.
277      */
278     sk_sp<GrTexture> getExactScratch(const GrSurfaceDesc&, SkBudgeted, uint32_t flags);
279 
cache()280     GrResourceCache* cache() { return fCache; }
cache()281     const GrResourceCache* cache() const { return fCache; }
282 
283     friend class GrResourceProviderPriv;
284 
285     // Method made available via GrResourceProviderPriv
gpu()286     GrGpu* gpu() { return fGpu; }
gpu()287     const GrGpu* gpu() const { return fGpu; }
288 
isAbandoned()289     bool isAbandoned() const {
290         SkASSERT(SkToBool(fGpu) == SkToBool(fCache));
291         return !SkToBool(fCache);
292     }
293 
294     sk_sp<const GrBuffer> createPatternedIndexBuffer(const uint16_t* pattern,
295                                                      int patternSize,
296                                                      int reps,
297                                                      int vertCount,
298                                                      const GrUniqueKey& key);
299 
300     sk_sp<const GrBuffer> createQuadIndexBuffer();
301 
302     GrResourceCache*    fCache;
303     GrGpu*              fGpu;
304     sk_sp<const GrCaps> fCaps;
305     GrUniqueKey         fQuadIndexBufferKey;
306     bool                fExplicitlyAllocateGPUResources;
307 
308     // In debug builds we guard against improper thread handling
309     SkDEBUGCODE(mutable GrSingleOwner* fSingleOwner;)
310 };
311 
312 #endif
313