• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2014 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 GrResourceKey_DEFINED
9 #define GrResourceKey_DEFINED
10 
11 #include "include/core/SkData.h"
12 #include "include/core/SkString.h"
13 #include "include/gpu/GrTypes.h"
14 #include "include/private/SkOnce.h"
15 #include "include/private/SkTemplates.h"
16 #include "include/private/SkTo.h"
17 
18 #include <new>
19 
20 uint32_t GrResourceKeyHash(const uint32_t* data, size_t size);
21 
22 /**
23  * Base class for all GrGpuResource cache keys. There are two types of cache keys. Refer to the
24  * comments for each key type below.
25  */
26 class GrResourceKey {
27 public:
hash()28     uint32_t hash() const {
29         this->validate();
30         return fKey[kHash_MetaDataIdx];
31     }
32 
size()33     size_t size() const {
34         this->validate();
35         SkASSERT(this->isValid());
36         return this->internalSize();
37     }
38 
39 protected:
40     static const uint32_t kInvalidDomain = 0;
41 
GrResourceKey()42     GrResourceKey() { this->reset(); }
43 
44     /** Reset to an invalid key. */
reset()45     void reset() {
46         fKey.reset(kMetaDataCnt);
47         fKey[kHash_MetaDataIdx] = 0;
48         fKey[kDomainAndSize_MetaDataIdx] = kInvalidDomain;
49     }
50 
51     bool operator==(const GrResourceKey& that) const {
52         return this->hash() == that.hash() && 0 == memcmp(&fKey[kHash_MetaDataIdx + 1],
53                                                           &that.fKey[kHash_MetaDataIdx + 1],
54                                                           this->internalSize() - sizeof(uint32_t));
55     }
56 
57     GrResourceKey& operator=(const GrResourceKey& that) {
58         if (this != &that) {
59             if (!that.isValid()) {
60                 this->reset();
61             } else {
62                 size_t bytes = that.size();
63                 SkASSERT(SkIsAlign4(bytes));
64                 fKey.reset(SkToInt(bytes / sizeof(uint32_t)));
65                 memcpy(fKey.get(), that.fKey.get(), bytes);
66                 this->validate();
67             }
68         }
69         return *this;
70     }
71 
isValid()72     bool isValid() const { return kInvalidDomain != this->domain(); }
73 
domain()74     uint32_t domain() const { return fKey[kDomainAndSize_MetaDataIdx] & 0xffff; }
75 
76     /** size of the key data, excluding meta-data (hash, domain, etc).  */
dataSize()77     size_t dataSize() const { return this->size() - 4 * kMetaDataCnt; }
78 
79     /** ptr to the key data, excluding meta-data (hash, domain, etc).  */
data()80     const uint32_t* data() const {
81         this->validate();
82         return &fKey[kMetaDataCnt];
83     }
84 
85 #ifdef SK_DEBUG
dump()86     void dump() const {
87         if (!this->isValid()) {
88             SkDebugf("Invalid Key\n");
89         } else {
90             SkDebugf("hash: %d ", this->hash());
91             SkDebugf("domain: %d ", this->domain());
92             SkDebugf("size: %dB ", this->internalSize());
93             for (size_t i = 0; i < this->internalSize(); ++i) {
94                 SkDebugf("%d ", fKey[SkTo<int>(i)]);
95             }
96             SkDebugf("\n");
97         }
98     }
99 #endif
100 
101     /** Used to initialize a key. */
102     class Builder {
103     public:
Builder(GrResourceKey * key,uint32_t domain,int data32Count)104         Builder(GrResourceKey* key, uint32_t domain, int data32Count) : fKey(key) {
105             SkASSERT(data32Count >= 0);
106             SkASSERT(domain != kInvalidDomain);
107             key->fKey.reset(kMetaDataCnt + data32Count);
108             int size = (data32Count + kMetaDataCnt) * sizeof(uint32_t);
109             SkASSERT(SkToU16(size) == size);
110             SkASSERT(SkToU16(domain) == domain);
111             key->fKey[kDomainAndSize_MetaDataIdx] = domain | (size << 16);
112         }
113 
~Builder()114         ~Builder() { this->finish(); }
115 
finish()116         void finish() {
117             if (nullptr == fKey) {
118                 return;
119             }
120             uint32_t* hash = &fKey->fKey[kHash_MetaDataIdx];
121             *hash = GrResourceKeyHash(hash + 1, fKey->internalSize() - sizeof(uint32_t));
122             fKey->validate();
123             fKey = nullptr;
124         }
125 
126         uint32_t& operator[](int dataIdx) {
127             SkASSERT(fKey);
128             SkDEBUGCODE(size_t dataCount = fKey->internalSize() / sizeof(uint32_t) - kMetaDataCnt;)
129             SkASSERT(SkToU32(dataIdx) < dataCount);
130             return fKey->fKey[kMetaDataCnt + dataIdx];
131         }
132 
133     private:
134         GrResourceKey* fKey;
135     };
136 
137 private:
138     enum MetaDataIdx {
139         kHash_MetaDataIdx,
140         // The key domain and size are packed into a single uint32_t.
141         kDomainAndSize_MetaDataIdx,
142 
143         kLastMetaDataIdx = kDomainAndSize_MetaDataIdx
144     };
145     static const uint32_t kMetaDataCnt = kLastMetaDataIdx + 1;
146 
internalSize()147     size_t internalSize() const { return fKey[kDomainAndSize_MetaDataIdx] >> 16; }
148 
validate()149     void validate() const {
150         SkASSERT(this->isValid());
151         SkASSERT(fKey[kHash_MetaDataIdx] ==
152                  GrResourceKeyHash(&fKey[kHash_MetaDataIdx] + 1,
153                                    this->internalSize() - sizeof(uint32_t)));
154         SkASSERT(SkIsAlign4(this->internalSize()));
155     }
156 
157     friend class TestResource;  // For unit test to access kMetaDataCnt.
158 
159     // bmp textures require 5 uint32_t values.
160     SkAutoSTMalloc<kMetaDataCnt + 5, uint32_t> fKey;
161 };
162 
163 /**
164  * A key used for scratch resources. There are three important rules about scratch keys:
165  *        * Multiple resources can share the same scratch key. Therefore resources assigned the same
166  *          scratch key should be interchangeable with respect to the code that uses them.
167  *        * A resource can have at most one scratch key and it is set at resource creation by the
168  *          resource itself.
169  *        * When a scratch resource is ref'ed it will not be returned from the
170  *          cache for a subsequent cache request until all refs are released. This facilitates using
171  *          a scratch key for multiple render-to-texture scenarios. An example is a separable blur:
172  *
173  *  GrTexture* texture[2];
174  *  texture[0] = get_scratch_texture(scratchKey);
175  *  texture[1] = get_scratch_texture(scratchKey); // texture[0] is already owned so we will get a
176  *                                                // different one for texture[1]
177  *  draw_mask(texture[0], path);        // draws path mask to texture[0]
178  *  blur_x(texture[0], texture[1]);     // blurs texture[0] in y and stores result in texture[1]
179  *  blur_y(texture[1], texture[0]);     // blurs texture[1] in y and stores result in texture[0]
180  *  texture[1]->unref();  // texture 1 can now be recycled for the next request with scratchKey
181  *  consume_blur(texture[0]);
182  *  texture[0]->unref();  // texture 0 can now be recycled for the next request with scratchKey
183  */
184 class GrScratchKey : public GrResourceKey {
185 private:
186     typedef GrResourceKey INHERITED;
187 
188 public:
189     /** Uniquely identifies the type of resource that is cached as scratch. */
190     typedef uint32_t ResourceType;
191 
192     /** Generate a unique ResourceType. */
193     static ResourceType GenerateResourceType();
194 
195     /** Creates an invalid scratch key. It must be initialized using a Builder object before use. */
GrScratchKey()196     GrScratchKey() {}
197 
GrScratchKey(const GrScratchKey & that)198     GrScratchKey(const GrScratchKey& that) { *this = that; }
199 
200     /** reset() returns the key to the invalid state. */
201     using INHERITED::reset;
202 
203     using INHERITED::isValid;
204 
resourceType()205     ResourceType resourceType() const { return this->domain(); }
206 
207     GrScratchKey& operator=(const GrScratchKey& that) {
208         this->INHERITED::operator=(that);
209         return *this;
210     }
211 
212     bool operator==(const GrScratchKey& that) const { return this->INHERITED::operator==(that); }
213     bool operator!=(const GrScratchKey& that) const { return !(*this == that); }
214 
215     class Builder : public INHERITED::Builder {
216     public:
Builder(GrScratchKey * key,ResourceType type,int data32Count)217         Builder(GrScratchKey* key, ResourceType type, int data32Count)
218                 : INHERITED::Builder(key, type, data32Count) {}
219     };
220 };
221 
222 /**
223  * A key that allows for exclusive use of a resource for a use case (AKA "domain"). There are three
224  * rules governing the use of unique keys:
225  *        * Only one resource can have a given unique key at a time. Hence, "unique".
226  *        * A resource can have at most one unique key at a time.
227  *        * Unlike scratch keys, multiple requests for a unique key will return the same
228  *          resource even if the resource already has refs.
229  * This key type allows a code path to create cached resources for which it is the exclusive user.
230  * The code path creates a domain which it sets on its keys. This guarantees that there are no
231  * cross-domain collisions.
232  *
233  * Unique keys preempt scratch keys. While a resource has a unique key it is inaccessible via its
234  * scratch key. It can become scratch again if the unique key is removed.
235  */
236 class GrUniqueKey : public GrResourceKey {
237 private:
238     typedef GrResourceKey INHERITED;
239 
240 public:
241     typedef uint32_t Domain;
242     /** Generate a Domain for unique keys. */
243     static Domain GenerateDomain();
244 
245     /** Creates an invalid unique key. It must be initialized using a Builder object before use. */
GrUniqueKey()246     GrUniqueKey() : fTag(nullptr) {}
247 
GrUniqueKey(const GrUniqueKey & that)248     GrUniqueKey(const GrUniqueKey& that) { *this = that; }
249 
250     /** reset() returns the key to the invalid state. */
251     using INHERITED::reset;
252 
253     using INHERITED::isValid;
254 
255     GrUniqueKey& operator=(const GrUniqueKey& that) {
256         this->INHERITED::operator=(that);
257         this->setCustomData(sk_ref_sp(that.getCustomData()));
258         fTag = that.fTag;
259         return *this;
260     }
261 
262     bool operator==(const GrUniqueKey& that) const { return this->INHERITED::operator==(that); }
263     bool operator!=(const GrUniqueKey& that) const { return !(*this == that); }
264 
setCustomData(sk_sp<SkData> data)265     void setCustomData(sk_sp<SkData> data) { fData = std::move(data); }
getCustomData()266     SkData* getCustomData() const { return fData.get(); }
267 
tag()268     const char* tag() const { return fTag; }
269 
270 #ifdef SK_DEBUG
dump(const char * label)271     void dump(const char* label) const {
272         SkDebugf("%s tag: %s\n", label, fTag ? fTag : "None");
273         this->INHERITED::dump();
274     }
275 #endif
276 
277     class Builder : public INHERITED::Builder {
278     public:
279         Builder(GrUniqueKey* key, Domain type, int data32Count, const char* tag = nullptr)
Builder(key,type,data32Count)280                 : INHERITED::Builder(key, type, data32Count) {
281             key->fTag = tag;
282         }
283 
284         /** Used to build a key that wraps another key and adds additional data. */
285         Builder(GrUniqueKey* key, const GrUniqueKey& innerKey, Domain domain, int extraData32Cnt,
286                 const char* tag = nullptr)
287                 : INHERITED::Builder(key, domain, Data32CntForInnerKey(innerKey) + extraData32Cnt) {
288             SkASSERT(&innerKey != key);
289             // add the inner key to the end of the key so that op[] can be indexed normally.
290             uint32_t* innerKeyData = &this->operator[](extraData32Cnt);
291             const uint32_t* srcData = innerKey.data();
292             (*innerKeyData++) = innerKey.domain();
293             memcpy(innerKeyData, srcData, innerKey.dataSize());
294             key->fTag = tag;
295         }
296 
297     private:
Data32CntForInnerKey(const GrUniqueKey & innerKey)298         static int Data32CntForInnerKey(const GrUniqueKey& innerKey) {
299             // key data + domain
300             return SkToInt((innerKey.dataSize() >> 2) + 1);
301         }
302     };
303 
304 private:
305     sk_sp<SkData> fData;
306     const char* fTag;
307 };
308 
309 /**
310  * It is common to need a frequently reused GrUniqueKey where the only requirement is that the key
311  * is unique. These macros create such a key in a thread safe manner so the key can be truly global
312  * and only constructed once.
313  */
314 
315 /** Place outside of function/class definitions. */
316 #define GR_DECLARE_STATIC_UNIQUE_KEY(name) static SkOnce name##_once
317 
318 /** Place inside function where the key is used. */
319 #define GR_DEFINE_STATIC_UNIQUE_KEY(name)                         \
320     static SkAlignedSTStorage<1, GrUniqueKey> name##_storage;     \
321     name##_once(gr_init_static_unique_key_once, &name##_storage); \
322     static const GrUniqueKey& name = *reinterpret_cast<GrUniqueKey*>(name##_storage.get())
323 
gr_init_static_unique_key_once(SkAlignedSTStorage<1,GrUniqueKey> * keyStorage)324 static inline void gr_init_static_unique_key_once(SkAlignedSTStorage<1, GrUniqueKey>* keyStorage) {
325     GrUniqueKey* key = new (keyStorage->get()) GrUniqueKey;
326     GrUniqueKey::Builder builder(key, GrUniqueKey::GenerateDomain(), 0);
327 }
328 
329 // The cache listens for these messages to purge junk resources proactively.
330 class GrUniqueKeyInvalidatedMessage {
331 public:
332     GrUniqueKeyInvalidatedMessage() = default;
GrUniqueKeyInvalidatedMessage(const GrUniqueKey & key,uint32_t contextUniqueID)333     GrUniqueKeyInvalidatedMessage(const GrUniqueKey& key, uint32_t contextUniqueID)
334             : fKey(key), fContextID(contextUniqueID) {
335         SkASSERT(SK_InvalidUniqueID != contextUniqueID);
336     }
337 
338     GrUniqueKeyInvalidatedMessage(const GrUniqueKeyInvalidatedMessage&) = default;
339 
340     GrUniqueKeyInvalidatedMessage& operator=(const GrUniqueKeyInvalidatedMessage&) = default;
341 
key()342     const GrUniqueKey& key() const { return fKey; }
contextID()343     uint32_t contextID() const { return fContextID; }
344 
345 private:
346     GrUniqueKey fKey;
347     uint32_t fContextID = SK_InvalidUniqueID;
348 };
349 
SkShouldPostMessageToBus(const GrUniqueKeyInvalidatedMessage & msg,uint32_t msgBusUniqueID)350 static inline bool SkShouldPostMessageToBus(const GrUniqueKeyInvalidatedMessage& msg,
351                                             uint32_t msgBusUniqueID) {
352     return msg.contextID() == msgBusUniqueID;
353 }
354 
355 #endif
356