Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / third_party / skia / src / gpu / GrLayerCache.h
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 GrLayerCache_DEFINED
9 #define GrLayerCache_DEFINED
10
11 #include "GrAtlas.h"
12 #include "GrPictureUtils.h"
13 #include "GrRect.h"
14
15 #include "SkChecksum.h"
16 #include "SkMessageBus.h"
17 #include "SkTDynamicHash.h"
18
19 class SkPicture;
20
21 // Set to 0 to disable caching of hoisted layers
22 #define GR_CACHE_HOISTED_LAYERS 0
23
24 // The layer cache listens for these messages to purge picture-related resources.
25 struct GrPictureDeletedMessage {
26     uint32_t pictureID;
27 };
28
29 // GrPictureInfo stores the atlas plots used by a single picture. A single 
30 // plot may be used to store layers from multiple pictures.
31 struct GrPictureInfo {
32 public:
33     static const int kNumPlots = 4;
34
35     // for SkTDynamicHash - just use the pictureID as the hash key
36     static const uint32_t& GetKey(const GrPictureInfo& pictInfo) { return pictInfo.fPictureID; }
37     static uint32_t Hash(const uint32_t& key) { return SkChecksum::Mix(key); }
38
39     // GrPictureInfo proper
40     GrPictureInfo(uint32_t pictureID) : fPictureID(pictureID) { 
41 #if !GR_CACHE_HOISTED_LAYERS
42         memset(fPlotUses, 0, sizeof(fPlotUses)); 
43 #endif
44     }
45
46 #if !GR_CACHE_HOISTED_LAYERS
47     void incPlotUsage(int plotID) {
48         SkASSERT(plotID < kNumPlots);
49         fPlotUses[plotID]++;
50     }
51
52     void decPlotUsage(int plotID) {
53         SkASSERT(plotID < kNumPlots);
54         SkASSERT(fPlotUses[plotID] > 0);
55         fPlotUses[plotID]--;
56     }
57
58     int plotUsage(int plotID) const { 
59         SkASSERT(plotID < kNumPlots);
60         return fPlotUses[plotID];
61     }
62 #endif
63
64     const uint32_t fPictureID;
65     GrAtlas::ClientPlotUsage  fPlotUsage;
66
67 #if !GR_CACHE_HOISTED_LAYERS
68 private:
69     int fPlotUses[kNumPlots];
70 #endif
71 };
72
73 // GrCachedLayer encapsulates the caching information for a single saveLayer.
74 //
75 // Atlased layers get a ref to the backing GrTexture while non-atlased layers
76 // get a ref to the GrTexture in which they reside. In both cases 'fRect' 
77 // contains the layer's extent in its texture.
78 // Atlased layers also get a pointer to the plot in which they reside.
79 // For non-atlased layers, the lock field just corresponds to locking in
80 // the resource cache. For atlased layers, it implements an additional level
81 // of locking to allow atlased layers to be reused multiple times.
82 struct GrCachedLayer {
83 public:
84     // For SkTDynamicHash
85     struct Key {
86         Key(uint32_t pictureID, int start, const SkIRect& bounds, const SkMatrix& ctm)
87         : fPictureID(pictureID)
88         , fStart(start)
89         , fBounds(bounds)
90         , fCTM(ctm) {
91             fCTM.getType(); // force initialization of type so hashes match
92
93             // Key needs to be tightly packed.
94             GR_STATIC_ASSERT(sizeof(Key) == sizeof(uint32_t) +      // picture ID
95                                             sizeof(int) +           // start index
96                                             4 * sizeof(uint32_t) +  // bounds
97                                             9 * sizeof(SkScalar) + sizeof(uint32_t)); // matrix
98         }
99
100         bool operator==(const Key& other) const {
101             return fPictureID == other.fPictureID &&
102                    fStart == other.fStart &&
103                    fBounds == other.fBounds &&
104                    fCTM.cheapEqualTo(other.fCTM);
105         }
106
107         uint32_t pictureID() const { return fPictureID; }
108         int start() const { return fStart; }
109         const SkIRect& bound() const { return fBounds; }
110
111     private:
112         // ID of the picture of which this layer is a part
113         const uint32_t fPictureID;
114         // The the index of the saveLayer command in the picture
115         const int      fStart;
116         // The bounds of the layer. The TL corner is its offset.
117         const SkIRect  fBounds;
118         // The 2x2 portion of the CTM applied to this layer in the picture
119         SkMatrix       fCTM;
120     };
121
122     static const Key& GetKey(const GrCachedLayer& layer) { return layer.fKey; }
123     static uint32_t Hash(const Key& key) { 
124         return SkChecksum::Murmur3(reinterpret_cast<const uint32_t*>(&key), sizeof(Key));
125     }
126
127     // GrCachedLayer proper
128     GrCachedLayer(uint32_t pictureID, int start, int stop,
129                   const SkIRect& bounds, const SkMatrix& ctm,
130                   const SkPaint* paint)
131         : fKey(pictureID, start, bounds, ctm)
132         , fStop(stop)
133         , fPaint(paint ? SkNEW_ARGS(SkPaint, (*paint)) : NULL)
134         , fTexture(NULL)
135         , fRect(GrIRect16::MakeEmpty())
136         , fPlot(NULL)
137         , fUses(0)
138         , fLocked(false) {
139         SkASSERT(SK_InvalidGenID != pictureID && start >= 0 && stop >= 0);
140     }
141
142     ~GrCachedLayer() {
143         SkSafeUnref(fTexture);
144         SkDELETE(fPaint);
145     }
146
147     uint32_t pictureID() const { return fKey.pictureID(); }
148     int start() const { return fKey.start(); }
149     const SkIRect& bound() const { return fKey.bound(); }
150
151     int stop() const { return fStop; }
152     void setTexture(GrTexture* texture, const GrIRect16& rect) {
153         SkRefCnt_SafeAssign(fTexture, texture);
154         fRect = rect;
155     }
156     GrTexture* texture() { return fTexture; }
157     const SkPaint* paint() const { return fPaint; }
158     const GrIRect16& rect() const { return fRect; }
159
160     void setPlot(GrPlot* plot) {
161         SkASSERT(NULL == plot || NULL == fPlot);
162         fPlot = plot;
163     }
164     GrPlot* plot() { return fPlot; }
165
166     bool isAtlased() const { return SkToBool(fPlot); }
167
168     void setLocked(bool locked) { fLocked = locked; }
169     bool locked() const { return fLocked; }
170
171     SkDEBUGCODE(const GrPlot* plot() const { return fPlot; })
172     SkDEBUGCODE(void validate(const GrTexture* backingTexture) const;)
173
174 private:
175     const Key       fKey;
176
177     // The final "restore" operation index of the cached layer
178     const int       fStop;
179
180     // The paint used when dropping the layer down into the owning canvas.
181     // Can be NULL. This class makes a copy for itself.
182     const SkPaint*  fPaint;
183
184     // fTexture is a ref on the atlasing texture for atlased layers and a
185     // ref on a GrTexture for non-atlased textures.
186     GrTexture*      fTexture;
187
188     // For both atlased and non-atlased layers 'fRect' contains the  bound of
189     // the layer in whichever texture it resides. It is empty when 'fTexture'
190     // is NULL.
191     GrIRect16       fRect;
192
193     // For atlased layers, fPlot stores the atlas plot in which the layer rests.
194     // It is always NULL for non-atlased layers.
195     GrPlot*         fPlot;
196
197     // The number of actively hoisted layers using this cached image (e.g.,
198     // extant GrHoistedLayers pointing at this object). This object will
199     // be unlocked when the use count reaches 0.
200     int             fUses;
201
202     // For non-atlased layers 'fLocked' should always match "fTexture".
203     // (i.e., if there is a texture it is locked).
204     // For atlased layers, 'fLocked' is true if the layer is in a plot and
205     // actively required for rendering. If the layer is in a plot but not
206     // actively required for rendering, then 'fLocked' is false. If the
207     // layer isn't in a plot then is can never be locked.
208     bool            fLocked;
209
210     void addUse()     { ++fUses; }
211     void removeUse()  { SkASSERT(fUses > 0); --fUses; }
212     int uses() const { return fUses; }
213
214     friend class GrLayerCache;  // for access to usage methods
215     friend class TestingAccess; // for testing
216 };
217
218 // The GrLayerCache caches pre-computed saveLayers for later rendering.
219 // Non-atlased layers are stored in their own GrTexture while the atlased
220 // layers share a single GrTexture.
221 // Unlike the GrFontCache, the GrTexture atlas only has one GrAtlas (for 8888)
222 // and one GrPlot (for the entire atlas). As such, the GrLayerCache
223 // roughly combines the functionality of the GrFontCache and GrTextStrike
224 // classes.
225 class GrLayerCache {
226 public:
227     GrLayerCache(GrContext*);
228     ~GrLayerCache();
229
230     // As a cache, the GrLayerCache can be ordered to free up all its cached
231     // elements by the GrContext
232     void freeAll();
233
234     GrCachedLayer* findLayer(uint32_t pictureID, int start, 
235                              const SkIRect& bounds, const SkMatrix& ctm);
236     GrCachedLayer* findLayerOrCreate(uint32_t pictureID,
237                                      int start, int stop, 
238                                      const SkIRect& bounds,
239                                      const SkMatrix& ctm,
240                                      const SkPaint* paint);
241
242     // Attempt to place 'layer' in the atlas. Return true on success; false on failure.
243     // When true is returned, 'needsRendering' will indicate if the layer must be (re)drawn.
244     // Additionally, the GPU resources will be locked.
245     bool tryToAtlas(GrCachedLayer* layer, const GrSurfaceDesc& desc, bool* needsRendering);
246
247     // Attempt to lock the GPU resources required for a layer. Return true on success;
248     // false on failure. When true is returned 'needsRendering' will indicate if the
249     // layer must be (re)drawn.
250     // Note that atlased layers should already have been locked and rendered so only
251     // free floating layers will have 'needsRendering' set.
252     // Currently, this path always uses a new scratch texture for non-Atlased layers
253     // and (thus) doesn't cache anything. This can yield a lot of re-rendering.
254     // TODO: allow rediscovery of free-floating layers that are still in the resource cache.
255     bool lock(GrCachedLayer* layer, const GrSurfaceDesc& desc, bool* needsRendering);
256
257     // addUse is just here to keep the API symmetric
258     void addUse(GrCachedLayer* layer) { layer->addUse(); }
259     void removeUse(GrCachedLayer* layer) {
260         layer->removeUse();
261         if (layer->uses() == 0) {
262             // If no one cares about the layer allow it to be recycled.
263             this->unlock(layer);
264         }
265     }
266
267     // Setup to be notified when 'picture' is deleted
268     void trackPicture(const SkPicture* picture);
269
270     // Cleanup after any SkPicture deletions
271     void processDeletedPictures();
272
273     SkDEBUGCODE(void validate() const;)
274
275 #ifdef SK_DEVELOPER
276     void writeLayersToDisk(const SkString& dirName);
277 #endif
278
279     static bool PlausiblyAtlasable(int width, int height) {
280         return width <= kPlotWidth && height <= kPlotHeight;
281     }
282
283 #if !GR_CACHE_HOISTED_LAYERS
284     void purgeAll();
285 #endif
286
287 private:
288     static const int kAtlasTextureWidth = 1024;
289     static const int kAtlasTextureHeight = 1024;
290
291     static const int kNumPlotsX = 2;
292     static const int kNumPlotsY = 2;
293
294     static const int kPlotWidth = kAtlasTextureWidth / kNumPlotsX;
295     static const int kPlotHeight = kAtlasTextureHeight / kNumPlotsY;
296
297     GrContext*                fContext;  // pointer back to owning context
298     SkAutoTDelete<GrAtlas>    fAtlas;    // TODO: could lazily allocate
299
300     // We cache this information here (rather then, say, on the owning picture)
301     // because we want to be able to clean it up as needed (e.g., if a picture
302     // is leaked and never cleans itself up we still want to be able to 
303     // remove the GrPictureInfo once its layers are purged from all the atlas
304     // plots).
305     SkTDynamicHash<GrPictureInfo, uint32_t> fPictureHash;
306
307     SkTDynamicHash<GrCachedLayer, GrCachedLayer::Key> fLayerHash;
308
309     SkMessageBus<GrPictureDeletedMessage>::Inbox fPictDeletionInbox;
310
311     SkAutoTUnref<SkPicture::DeletionListener> fDeletionListener;
312
313     // This implements a plot-centric locking mechanism (since the atlas
314     // backing texture is always locked). Each layer that is locked (i.e.,
315     // needed for the current rendering) in a plot increments the plot lock
316     // count for that plot. Similarly, once a rendering is complete all the
317     // layers used in it decrement the lock count for the used plots.
318     // Plots with a 0 lock count are open for recycling/purging.
319     int fPlotLocks[kNumPlotsX * kNumPlotsY];
320
321     // Inform the cache that layer's cached image is not currently required
322     void unlock(GrCachedLayer* layer);
323
324     void initAtlas();
325     GrCachedLayer* createLayer(uint32_t pictureID, int start, int stop, 
326                                const SkIRect& bounds, const SkMatrix& ctm, 
327                                const SkPaint* paint);
328
329     // Remove all the layers (and unlock any resources) associated with 'pictureID'
330     void purge(uint32_t pictureID);
331
332     void purgePlot(GrPlot* plot);
333
334     // Try to find a purgeable plot and clear it out. Return true if a plot
335     // was purged; false otherwise.
336     bool purgePlot();
337
338     void incPlotLock(int plotIdx) { ++fPlotLocks[plotIdx]; }
339     void decPlotLock(int plotIdx) {
340         SkASSERT(fPlotLocks[plotIdx] > 0);
341         --fPlotLocks[plotIdx];
342     }
343
344     // for testing
345     friend class TestingAccess;
346     int numLayers() const { return fLayerHash.count(); }
347 };
348
349 #endif