• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "src/gpu/GrDrawOpAtlas.h"
9 
10 #include "include/gpu/GrContext.h"
11 #include "include/gpu/GrTexture.h"
12 #include "src/gpu/GrContextPriv.h"
13 #include "src/gpu/GrOnFlushResourceProvider.h"
14 #include "src/gpu/GrOpFlushState.h"
15 #include "src/gpu/GrProxyProvider.h"
16 #include "src/gpu/GrRectanizer.h"
17 #include "src/gpu/GrResourceProvider.h"
18 #include "src/gpu/GrSurfaceProxyPriv.h"
19 #include "src/gpu/GrTracing.h"
20 
21 // When proxy allocation is deferred until flush time the proxies acting as atlases require
22 // special handling. This is because the usage that can be determined from the ops themselves
23 // isn't sufficient. Independent of the ops there will be ASAP and inline uploads to the
24 // atlases. Extending the usage interval of any op that uses an atlas to the start of the
25 // flush (as is done for proxies that are used for sw-generated masks) also won't work because
26 // the atlas persists even beyond the last use in an op - for a given flush. Given this, atlases
27 // must explicitly manage the lifetime of their backing proxies via the onFlushCallback system
28 // (which calls this method).
instantiate(GrOnFlushResourceProvider * onFlushResourceProvider)29 void GrDrawOpAtlas::instantiate(GrOnFlushResourceProvider* onFlushResourceProvider) {
30     for (uint32_t i = 0; i < fNumActivePages; ++i) {
31         // All the atlas pages are now instantiated at flush time in the activeNewPage method.
32         SkASSERT(fProxies[i] && fProxies[i]->isInstantiated());
33     }
34 }
35 
Make(GrProxyProvider * proxyProvider,const GrBackendFormat & format,GrColorType colorType,int width,int height,int plotWidth,int plotHeight,AllowMultitexturing allowMultitexturing,int atlasPageNum,int plotOldThreshold,GrDrawOpAtlas::EvictionFunc func,void * data)36 std::unique_ptr<GrDrawOpAtlas> GrDrawOpAtlas::Make(GrProxyProvider* proxyProvider,
37                                                    const GrBackendFormat& format,
38                                                    GrColorType colorType, int width,
39                                                    int height, int plotWidth, int plotHeight,
40                                                    AllowMultitexturing allowMultitexturing,
41                                                    int atlasPageNum,
42                                                    int plotOldThreshold,
43                                                    GrDrawOpAtlas::EvictionFunc func, void* data) {
44     if (!format.isValid()) {
45         return nullptr;
46     }
47 
48     std::unique_ptr<GrDrawOpAtlas> atlas(new GrDrawOpAtlas(proxyProvider, format, colorType, width,
49                                                            height, plotWidth, plotHeight,
50                                                            allowMultitexturing, atlasPageNum, plotOldThreshold));
51     if (!atlas->getProxies()[0]) {
52         return nullptr;
53     }
54 
55     atlas->registerEvictionCallback(func, data);
56     return atlas;
57 }
58 
59 #ifdef DUMP_ATLAS_DATA
60 static bool gDumpAtlasData = false;
61 #endif
62 
63 ////////////////////////////////////////////////////////////////////////////////
Plot(int pageIndex,int plotIndex,uint64_t genID,int offX,int offY,int width,int height,GrColorType colorType)64 GrDrawOpAtlas::Plot::Plot(int pageIndex, int plotIndex, uint64_t genID, int offX, int offY,
65                           int width, int height, GrColorType colorType)
66         : fLastUpload(GrDeferredUploadToken::AlreadyFlushedToken())
67         , fLastUse(GrDeferredUploadToken::AlreadyFlushedToken())
68         , fFlushesSinceLastUse(0)
69         , fPageIndex(pageIndex)
70         , fPlotIndex(plotIndex)
71         , fGenID(genID)
72         , fID(CreateId(fPageIndex, fPlotIndex, fGenID))
73         , fData(nullptr)
74         , fWidth(width)
75         , fHeight(height)
76         , fX(offX)
77         , fY(offY)
78         , fRects(nullptr)
79         , fOffset(SkIPoint16::Make(fX * fWidth, fY * fHeight))
80         , fColorType(colorType)
81         , fBytesPerPixel(GrColorTypeBytesPerPixel(colorType))
82 #ifdef SK_DEBUG
83         , fDirty(false)
84 #endif
85 {
86     // We expect the allocated dimensions to be a multiple of 4 bytes
87     SkASSERT(((width*fBytesPerPixel) & 0x3) == 0);
88     // The padding for faster uploads only works for 1, 2 and 4 byte texels
89     SkASSERT(fBytesPerPixel != 3 && fBytesPerPixel <= 4);
90     fDirtyRect.setEmpty();
91 }
92 
~Plot()93 GrDrawOpAtlas::Plot::~Plot() {
94     sk_free(fData);
95     delete fRects;
96 }
97 
addSubImage(int width,int height,const void * image,SkIPoint16 * loc)98 bool GrDrawOpAtlas::Plot::addSubImage(int width, int height, const void* image, SkIPoint16* loc) {
99     SkASSERT(width <= fWidth && height <= fHeight);
100 
101     if (!fRects) {
102         fRects = GrRectanizer::Factory(fWidth, fHeight);
103     }
104 
105     if (!fRects->addRect(width, height, loc)) {
106         return false;
107     }
108 
109     if (!fData) {
110         fData = reinterpret_cast<unsigned char*>(sk_calloc_throw(fBytesPerPixel * fWidth *
111                                                                  fHeight));
112     }
113     size_t rowBytes = width * fBytesPerPixel;
114     const unsigned char* imagePtr = (const unsigned char*)image;
115     // point ourselves at the right starting spot
116     unsigned char* dataPtr = fData;
117     dataPtr += fBytesPerPixel * fWidth * loc->fY;
118     dataPtr += fBytesPerPixel * loc->fX;
119     // copy into the data buffer, swizzling as we go if this is ARGB data
120     if (4 == fBytesPerPixel && kSkia8888_GrPixelConfig == kBGRA_8888_GrPixelConfig) {
121         for (int i = 0; i < height; ++i) {
122             SkOpts::RGBA_to_BGRA((uint32_t*)dataPtr, (const uint32_t*)imagePtr, width);
123             dataPtr += fBytesPerPixel * fWidth;
124             imagePtr += rowBytes;
125         }
126     } else {
127         for (int i = 0; i < height; ++i) {
128             memcpy(dataPtr, imagePtr, rowBytes);
129             dataPtr += fBytesPerPixel * fWidth;
130             imagePtr += rowBytes;
131         }
132     }
133 
134     fDirtyRect.join(loc->fX, loc->fY, loc->fX + width, loc->fY + height);
135 
136     loc->fX += fOffset.fX;
137     loc->fY += fOffset.fY;
138     SkDEBUGCODE(fDirty = true;)
139 
140     return true;
141 }
142 
uploadToTexture(GrDeferredTextureUploadWritePixelsFn & writePixels,GrTextureProxy * proxy)143 void GrDrawOpAtlas::Plot::uploadToTexture(GrDeferredTextureUploadWritePixelsFn& writePixels,
144                                           GrTextureProxy* proxy) {
145     // We should only be issuing uploads if we are in fact dirty
146     SkASSERT(fDirty && fData && proxy && proxy->peekTexture());
147     TRACE_EVENT0("skia.gpu", TRACE_FUNC);
148     size_t rowBytes = fBytesPerPixel * fWidth;
149     const unsigned char* dataPtr = fData;
150     // Clamp to 4-byte aligned boundaries
151     unsigned int clearBits = 0x3 / fBytesPerPixel;
152     fDirtyRect.fLeft &= ~clearBits;
153     fDirtyRect.fRight += clearBits;
154     fDirtyRect.fRight &= ~clearBits;
155     SkASSERT(fDirtyRect.fRight <= fWidth);
156     // Set up dataPtr
157     dataPtr += rowBytes * fDirtyRect.fTop;
158     dataPtr += fBytesPerPixel * fDirtyRect.fLeft;
159 
160     writePixels(proxy, fOffset.fX + fDirtyRect.fLeft, fOffset.fY + fDirtyRect.fTop,
161                 fDirtyRect.width(), fDirtyRect.height(), fColorType, dataPtr, rowBytes);
162     fDirtyRect.setEmpty();
163     SkDEBUGCODE(fDirty = false;)
164 }
165 
resetRects()166 void GrDrawOpAtlas::Plot::resetRects() {
167     if (fRects) {
168         fRects->reset();
169     }
170 
171     fGenID++;
172     fID = CreateId(fPageIndex, fPlotIndex, fGenID);
173     fLastUpload = GrDeferredUploadToken::AlreadyFlushedToken();
174     fLastUse = GrDeferredUploadToken::AlreadyFlushedToken();
175 
176     // zero out the plot
177     if (fData) {
178         sk_bzero(fData, fBytesPerPixel * fWidth * fHeight);
179     }
180 
181     fDirtyRect.setEmpty();
182     SkDEBUGCODE(fDirty = false;)
183 }
184 
185 ///////////////////////////////////////////////////////////////////////////////
186 
GrDrawOpAtlas(GrProxyProvider * proxyProvider,const GrBackendFormat & format,GrColorType colorType,int width,int height,int plotWidth,int plotHeight,AllowMultitexturing allowMultitexturing,int atlasPageNum,int plotOldThreshold)187 GrDrawOpAtlas::GrDrawOpAtlas(GrProxyProvider* proxyProvider, const GrBackendFormat& format,
188                              GrColorType colorType, int width, int height,
189                              int plotWidth, int plotHeight, AllowMultitexturing allowMultitexturing,
190                              int atlasPageNum, int plotOldThreshold)
191         : fFormat(format)
192         , fColorType(colorType)
193         , fTextureWidth(width)
194         , fTextureHeight(height)
195         , fPlotWidth(plotWidth)
196         , fPlotHeight(plotHeight)
197         , fAtlasGeneration(kInvalidAtlasGeneration + 1)
198         , fPrevFlushToken(GrDeferredUploadToken::AlreadyFlushedToken())
199         , fMaxPages(AllowMultitexturing::kYes == allowMultitexturing ? ((atlasPageNum > 16) ? 16 : atlasPageNum) : 1)
200         , fNumActivePages(0)
201         , fPlotOldThreshold(plotOldThreshold) {
202     int numPlotsX = width/plotWidth;
203     int numPlotsY = height/plotHeight;
204     SkASSERT(numPlotsX * numPlotsY <= GrDrawOpAtlas::kMaxPlots);
205     SkASSERT(fPlotWidth * numPlotsX == fTextureWidth);
206     SkASSERT(fPlotHeight * numPlotsY == fTextureHeight);
207 
208     fNumPlots = numPlotsX * numPlotsY;
209 
210     this->createPages(proxyProvider);
211 
212     SkDebugf("Texture[Width:%{public}d, Height:%{public}d, MaxPage:%{public}d], Plot[Width:%{public}d, Height:%{public}d, OldThreshold:%{public}d].", \
213         fTextureWidth, fTextureHeight, fMaxPages, fPlotWidth, fPlotHeight, fPlotOldThreshold);
214 }
215 
processEviction(AtlasID id)216 inline void GrDrawOpAtlas::processEviction(AtlasID id) {
217     for (int i = 0; i < fEvictionCallbacks.count(); i++) {
218         (*fEvictionCallbacks[i].fFunc)(id, fEvictionCallbacks[i].fData);
219     }
220     ++fAtlasGeneration;
221 }
222 
updatePlot(GrDeferredUploadTarget * target,AtlasID * id,Plot * plot)223 inline bool GrDrawOpAtlas::updatePlot(GrDeferredUploadTarget* target, AtlasID* id, Plot* plot) {
224     int pageIdx = GetPageIndexFromID(plot->id());
225     this->makeMRU(plot, pageIdx);
226 
227     // If our most recent upload has already occurred then we have to insert a new
228     // upload. Otherwise, we already have a scheduled upload that hasn't yet ocurred.
229     // This new update will piggy back on that previously scheduled update.
230     if (plot->lastUploadToken() < target->tokenTracker()->nextTokenToFlush()) {
231         // With c+14 we could move sk_sp into lamba to only ref once.
232         sk_sp<Plot> plotsp(SkRef(plot));
233 
234         GrTextureProxy* proxy = fProxies[pageIdx].get();
235         SkASSERT(proxy->isInstantiated());  // This is occurring at flush time
236 
237         GrDeferredUploadToken lastUploadToken = target->addASAPUpload(
238                 [plotsp, proxy](GrDeferredTextureUploadWritePixelsFn& writePixels) {
239                     plotsp->uploadToTexture(writePixels, proxy);
240                 });
241         plot->setLastUploadToken(lastUploadToken);
242     }
243     *id = plot->id();
244     return true;
245 }
246 
uploadToPage(unsigned int pageIdx,AtlasID * id,GrDeferredUploadTarget * target,int width,int height,const void * image,SkIPoint16 * loc)247 bool GrDrawOpAtlas::uploadToPage(unsigned int pageIdx, AtlasID* id, GrDeferredUploadTarget* target,
248                                  int width, int height, const void* image, SkIPoint16* loc) {
249     SkASSERT(fProxies[pageIdx] && fProxies[pageIdx]->isInstantiated());
250 
251     // look through all allocated plots for one we can share, in Most Recently Refed order
252     PlotList::Iter plotIter;
253     plotIter.init(fPages[pageIdx].fPlotList, PlotList::Iter::kHead_IterStart);
254 
255     for (Plot* plot = plotIter.get(); plot; plot = plotIter.next()) {
256         SkASSERT(GrBytesPerPixel(fProxies[pageIdx]->config()) == plot->bpp());
257 
258         if (plot->addSubImage(width, height, image, loc)) {
259             return this->updatePlot(target, id, plot);
260         }
261     }
262 
263     return false;
264 }
265 
266 // Number of atlas-related flushes beyond which we consider a plot to no longer be in use.
267 //
268 // This value is somewhat arbitrary -- the idea is to keep it low enough that
269 // a page with unused plots will get removed reasonably quickly, but allow it
270 // to hang around for a bit in case it's needed. The assumption is that flushes
271 // are rare; i.e., we are not continually refreshing the frame.
272 
273 
addToAtlas(GrResourceProvider * resourceProvider,AtlasID * id,GrDeferredUploadTarget * target,int width,int height,const void * image,SkIPoint16 * loc)274 GrDrawOpAtlas::ErrorCode GrDrawOpAtlas::addToAtlas(GrResourceProvider* resourceProvider,
275                                                    AtlasID* id, GrDeferredUploadTarget* target,
276                                                    int width, int height,
277                                                    const void* image, SkIPoint16* loc) {
278     if (width > fPlotWidth || height > fPlotHeight) {
279         return ErrorCode::kError;
280     }
281 
282     // Look through each page to see if we can upload without having to flush
283     // We prioritize this upload to the first pages, not the most recently used, to make it easier
284     // to remove unused pages in reverse page order.
285     for (unsigned int pageIdx = 0; pageIdx < fNumActivePages; ++pageIdx) {
286         if (this->uploadToPage(pageIdx, id, target, width, height, image, loc)) {
287             return ErrorCode::kSucceeded;
288         }
289     }
290 
291     // If the above fails, then see if the least recently used plot per page has already been
292     // flushed to the gpu if we're at max page allocation, or if the plot has aged out otherwise.
293     // We wait until we've grown to the full number of pages to begin evicting already flushed
294     // plots so that we can maximize the opportunity for reuse.
295     // As before we prioritize this upload to the first pages, not the most recently used.
296     if (fNumActivePages == this->maxPages()) {
297         for (unsigned int pageIdx = 0; pageIdx < fNumActivePages; ++pageIdx) {
298             Plot* plot = fPages[pageIdx].fPlotList.tail();
299             SkASSERT(plot);
300             if (plot->lastUseToken() < target->tokenTracker()->nextTokenToFlush()) {
301                 this->processEvictionAndResetRects(plot);
302                 SkASSERT(GrBytesPerPixel(fProxies[pageIdx]->config()) == plot->bpp());
303                 SkDEBUGCODE(bool verify = )plot->addSubImage(width, height, image, loc);
304                 SkASSERT(verify);
305                 if (!this->updatePlot(target, id, plot)) {
306                     return ErrorCode::kError;
307                 }
308 #ifdef SK_DEBUG_PAGE
309                 SkDebugf("----- addToAtlas overwrite page# %{public}d.", pageIdx);
310 #endif
311                 return ErrorCode::kSucceeded;
312             }
313         }
314     } else {
315         // If we haven't activated all the available pages, try to create a new one and add to it
316         if (!this->activateNewPage(resourceProvider)) {
317             return ErrorCode::kError;
318         }
319 
320         if (this->uploadToPage(fNumActivePages-1, id, target, width, height, image, loc)) {
321             return ErrorCode::kSucceeded;
322         } else {
323             // If we fail to upload to a newly activated page then something has gone terribly
324             // wrong - return an error
325             return ErrorCode::kError;
326         }
327     }
328 
329     if (!fNumActivePages) {
330         return ErrorCode::kError;
331     }
332 
333     // Try to find a plot that we can perform an inline upload to.
334     // We prioritize this upload in reverse order of pages to counterbalance the order above.
335     Plot* plot = nullptr;
336     for (int pageIdx = ((int)fNumActivePages)-1; pageIdx >= 0; --pageIdx) {
337         Plot* currentPlot = fPages[pageIdx].fPlotList.tail();
338         if (currentPlot->lastUseToken() != target->tokenTracker()->nextDrawToken()) {
339             plot = currentPlot;
340             break;
341         }
342     }
343 
344     // If we can't find a plot that is not used in a draw currently being prepared by an op, then
345     // we have to fail. This gives the op a chance to enqueue the draw, and call back into this
346     // function. When that draw is enqueued, the draw token advances, and the subsequent call will
347     // continue past this branch and prepare an inline upload that will occur after the enqueued
348     // draw which references the plot's pre-upload content.
349     if (!plot) {
350         return ErrorCode::kTryAgain;
351     }
352 
353     this->processEviction(plot->id());
354     int pageIdx = GetPageIndexFromID(plot->id());
355     fPages[pageIdx].fPlotList.remove(plot);
356     sk_sp<Plot>& newPlot = fPages[pageIdx].fPlotArray[plot->index()];
357     newPlot.reset(plot->clone());
358 
359     fPages[pageIdx].fPlotList.addToHead(newPlot.get());
360     SkASSERT(GrBytesPerPixel(fProxies[pageIdx]->config()) == newPlot->bpp());
361     SkDEBUGCODE(bool verify = )newPlot->addSubImage(width, height, image, loc);
362     SkASSERT(verify);
363 
364     // Note that this plot will be uploaded inline with the draws whereas the
365     // one it displaced most likely was uploaded ASAP.
366     // With c+14 we could move sk_sp into lambda to only ref once.
367     sk_sp<Plot> plotsp(SkRef(newPlot.get()));
368 
369     GrTextureProxy* proxy = fProxies[pageIdx].get();
370     SkASSERT(proxy->isInstantiated());
371 
372     GrDeferredUploadToken lastUploadToken = target->addInlineUpload(
373             [plotsp, proxy](GrDeferredTextureUploadWritePixelsFn& writePixels) {
374                 plotsp->uploadToTexture(writePixels, proxy);
375             });
376     newPlot->setLastUploadToken(lastUploadToken);
377 
378     *id = newPlot->id();
379 
380 #ifdef SK_DEBUG_PAGE
381     SkDebugf("----- addToAtlas addInlineUpload page# %{public}d.", pageIdx);
382 #endif
383     return ErrorCode::kSucceeded;
384 }
385 
compactRadicals(GrDeferredUploadToken startTokenForNextFlush)386 void GrDrawOpAtlas::compactRadicals(GrDeferredUploadToken startTokenForNextFlush) {
387     if (fNumActivePages <= 1) {
388         return;
389     }
390     PlotList::Iter plotIter;
391     unsigned short usedAtlasLastFlush = 0;
392     for (uint32_t pageIndex = 0; pageIndex < fNumActivePages; ++pageIndex) {
393         plotIter.init(fPages[pageIndex].fPlotList, PlotList::Iter::kHead_IterStart);
394         while (Plot* plot = plotIter.get()) {
395             if (plot->lastUseToken().inInterval(fPrevFlushToken, startTokenForNextFlush)) {
396                 usedAtlasLastFlush |= (1 << pageIndex);
397             } else if (plot->lastUploadToken() != GrDeferredUploadToken::AlreadyFlushedToken()) {
398                 this->processEvictionAndResetRects(plot);
399             }
400             plotIter.next();
401         }
402     }
403     int lastPageIndex = fNumActivePages - 1;
404     while (lastPageIndex > 0 && !(usedAtlasLastFlush & (1 << lastPageIndex))) {
405         deactivateLastPage();
406         lastPageIndex--;
407     }
408 }
409 
compact(GrDeferredUploadToken startTokenForNextFlush,bool isRadicals)410 void GrDrawOpAtlas::compact(GrDeferredUploadToken startTokenForNextFlush, bool isRadicals) {
411     if (isRadicals) {
412         compactRadicals(startTokenForNextFlush);
413     }
414     if (fNumActivePages <= 1) {
415         fPrevFlushToken = startTokenForNextFlush;
416         return;
417     }
418     int threshold = isRadicals ? 1 : fPlotOldThreshold;
419 
420     // For all plots, reset number of flushes since used if used this frame.
421     PlotList::Iter plotIter;
422     bool atlasUsedThisFlush = false;
423     for (uint32_t pageIndex = 0; pageIndex < fNumActivePages; ++pageIndex) {
424         plotIter.init(fPages[pageIndex].fPlotList, PlotList::Iter::kHead_IterStart);
425         while (Plot* plot = plotIter.get()) {
426             // Reset number of flushes since used
427             if (plot->lastUseToken().inInterval(fPrevFlushToken, startTokenForNextFlush)) {
428                 plot->resetFlushesSinceLastUsed();
429                 atlasUsedThisFlush = true;
430             }
431 
432             plotIter.next();
433         }
434     }
435 
436     // We only try to compact if the atlas was used in the recently completed flush.
437     // This is to handle the case where a lot of text or path rendering has occurred but then just
438     // a blinking cursor is drawn.
439     // TODO: consider if we should also do this if it's been a long time since the last atlas use
440     if (atlasUsedThisFlush) {
441         SkTArray<Plot*> availablePlots;
442         uint32_t lastPageIndex = fNumActivePages - 1;
443 
444         // For all plots but the last one, update number of flushes since used, and check to see
445         // if there are any in the first pages that the last page can safely upload to.
446         for (uint32_t pageIndex = 0; pageIndex < lastPageIndex; ++pageIndex) {
447 #ifdef DUMP_ATLAS_DATA
448             if (gDumpAtlasData) {
449                 SkDebugf("page %d: ", pageIndex);
450             }
451 #endif
452             plotIter.init(fPages[pageIndex].fPlotList, PlotList::Iter::kHead_IterStart);
453             while (Plot* plot = plotIter.get()) {
454                 // Update number of flushes since plot was last used
455                 // We only increment the 'sinceLastUsed' count for flushes where the atlas was used
456                 // to avoid deleting everything when we return to text drawing in the blinking
457                 // cursor case
458                 if (!plot->lastUseToken().inInterval(fPrevFlushToken, startTokenForNextFlush)) {
459                     plot->incFlushesSinceLastUsed();
460                 }
461 
462 #ifdef DUMP_ATLAS_DATA
463                 if (gDumpAtlasData) {
464                     SkDebugf("%d ", plot->flushesSinceLastUsed());
465                 }
466 #endif
467                 // Count plots we can potentially upload to in all pages except the last one
468                 // (the potential compactee).
469                 if (plot->flushesSinceLastUsed() > threshold) {
470                     availablePlots.push_back() = plot;
471                 }
472 
473                 plotIter.next();
474             }
475 #ifdef DUMP_ATLAS_DATA
476             if (gDumpAtlasData) {
477                 SkDebugf("\n");
478             }
479 #endif
480         }
481 
482         // Count recently used plots in the last page and evict any that are no longer in use.
483         // Since we prioritize uploading to the first pages, this will eventually
484         // clear out usage of this page unless we have a large need.
485         plotIter.init(fPages[lastPageIndex].fPlotList, PlotList::Iter::kHead_IterStart);
486         unsigned int usedPlots = 0;
487 #ifdef DUMP_ATLAS_DATA
488         if (gDumpAtlasData) {
489             SkDebugf("page %d: ", lastPageIndex);
490         }
491 #endif
492         while (Plot* plot = plotIter.get()) {
493             // Update number of flushes since plot was last used
494             if (!plot->lastUseToken().inInterval(fPrevFlushToken, startTokenForNextFlush)) {
495                 plot->incFlushesSinceLastUsed();
496             }
497 
498 #ifdef DUMP_ATLAS_DATA
499             if (gDumpAtlasData) {
500                 SkDebugf("%d ", plot->flushesSinceLastUsed());
501             }
502 #endif
503             // If this plot was used recently
504             if (plot->flushesSinceLastUsed() <= threshold) {
505                 usedPlots++;
506             } else if (plot->lastUseToken() != GrDeferredUploadToken::AlreadyFlushedToken()) {
507                 // otherwise if aged out just evict it.
508                 this->processEvictionAndResetRects(plot);
509             }
510             plotIter.next();
511         }
512 #ifdef DUMP_ATLAS_DATA
513         if (gDumpAtlasData) {
514             SkDebugf("\n");
515         }
516 #endif
517 
518         // If recently used plots in the last page are using less than a quarter of the page, try
519         // to evict them if there's available space in earlier pages. Since we prioritize uploading
520         // to the first pages, this will eventually clear out usage of this page unless we have a
521         // large need.
522         if (availablePlots.count() && usedPlots && usedPlots <= fNumPlots / 4) {
523             plotIter.init(fPages[lastPageIndex].fPlotList, PlotList::Iter::kHead_IterStart);
524             while (Plot* plot = plotIter.get()) {
525                 // If this plot was used recently
526                 if (plot->flushesSinceLastUsed() <= threshold) {
527                     // See if there's room in an earlier page and if so evict.
528                     // We need to be somewhat harsh here so that a handful of plots that are
529                     // consistently in use don't end up locking the page in memory.
530                     if (availablePlots.count() > 0) {
531                         this->processEvictionAndResetRects(plot);
532                         this->processEvictionAndResetRects(availablePlots.back());
533                         availablePlots.pop_back();
534                         --usedPlots;
535                     }
536                     if (!usedPlots || !availablePlots.count()) {
537                         break;
538                     }
539                 }
540                 plotIter.next();
541             }
542         }
543 
544         // If none of the plots in the last page have been used recently, delete it.
545         if (!usedPlots) {
546 #ifdef DUMP_ATLAS_DATA
547             if (gDumpAtlasData) {
548                 SkDebugf("delete %d\n", fNumPages-1);
549             }
550 #endif
551 #ifdef SK_DEBUG_PAGE
552             SkDebugf("----- availablePlots %{public}d.", availablePlots.count());
553 #endif
554             this->deactivateLastPage();
555         }
556     }
557 
558     fPrevFlushToken = startTokenForNextFlush;
559 }
560 
createPages(GrProxyProvider * proxyProvider)561 bool GrDrawOpAtlas::createPages(GrProxyProvider* proxyProvider) {
562     SkASSERT(SkIsPow2(fTextureWidth) && SkIsPow2(fTextureHeight));
563 
564     GrSurfaceDesc desc;
565     desc.fWidth = fTextureWidth;
566     desc.fHeight = fTextureHeight;
567     desc.fConfig = GrColorTypeToPixelConfig(fColorType);
568 
569     int numPlotsX = fTextureWidth/fPlotWidth;
570     int numPlotsY = fTextureHeight/fPlotHeight;
571 
572     for (uint32_t i = 0; i < this->maxPages(); ++i) {
573         fProxies[i] = proxyProvider->createProxy(fFormat, desc, GrRenderable::kNo, 1,
574                                                  kTopLeft_GrSurfaceOrigin, SkBackingFit::kExact,
575                                                  SkBudgeted::kYes, GrProtected::kNo);
576         if (!fProxies[i]) {
577             return false;
578         }
579 
580         fProxies[i]->priv().setIgnoredByResourceAllocator();
581 
582         // set up allocated plots
583         fPages[i].fPlotArray.reset(new sk_sp<Plot>[ numPlotsX * numPlotsY ]);
584 
585         sk_sp<Plot>* currPlot = fPages[i].fPlotArray.get();
586         for (int y = numPlotsY - 1, r = 0; y >= 0; --y, ++r) {
587             for (int x = numPlotsX - 1, c = 0; x >= 0; --x, ++c) {
588                 uint32_t plotIndex = r * numPlotsX + c;
589                 currPlot->reset(new Plot(i, plotIndex, 1, x, y, fPlotWidth, fPlotHeight,
590                                          fColorType));
591 
592                 // build LRU list
593                 fPages[i].fPlotList.addToHead(currPlot->get());
594                 ++currPlot;
595             }
596         }
597 
598     }
599 
600     return true;
601 }
602 
603 
activateNewPage(GrResourceProvider * resourceProvider)604 bool GrDrawOpAtlas::activateNewPage(GrResourceProvider* resourceProvider) {
605     SkASSERT(fNumActivePages < this->maxPages());
606 
607     if (!fProxies[fNumActivePages]->instantiate(resourceProvider)) {
608         return false;
609     }
610 
611 #ifdef DUMP_ATLAS_DATA
612     if (gDumpAtlasData) {
613         SkDebugf("activated page#: %d\n", fNumActivePages);
614     }
615 #endif
616 
617 #ifdef SK_DEBUG_PAGE
618     SkDebugf("----- activated page#: %{public}d.", fNumActivePages);
619 #endif
620     ++fNumActivePages;
621     return true;
622 }
623 
624 
deactivateLastPage()625 inline void GrDrawOpAtlas::deactivateLastPage() {
626     SkASSERT(fNumActivePages);
627 
628     uint32_t lastPageIndex = fNumActivePages - 1;
629 
630     int numPlotsX = fTextureWidth/fPlotWidth;
631     int numPlotsY = fTextureHeight/fPlotHeight;
632 
633     fPages[lastPageIndex].fPlotList.reset();
634     for (int r = 0; r < numPlotsY; ++r) {
635         for (int c = 0; c < numPlotsX; ++c) {
636             uint32_t plotIndex = r * numPlotsX + c;
637 
638             Plot* currPlot = fPages[lastPageIndex].fPlotArray[plotIndex].get();
639             currPlot->resetRects();
640             currPlot->resetFlushesSinceLastUsed();
641 
642             // rebuild the LRU list
643             SkDEBUGCODE(currPlot->fPrev = currPlot->fNext = nullptr);
644             SkDEBUGCODE(currPlot->fList = nullptr);
645             fPages[lastPageIndex].fPlotList.addToHead(currPlot);
646         }
647     }
648 
649     // remove ref to the backing texture
650     fProxies[lastPageIndex]->deinstantiate();
651     --fNumActivePages;
652 
653 #ifdef SK_DEBUG_PAGE
654     SkDebugf("----- deactivateLastPage %{public}d.", lastPageIndex);
655 #endif
656 }
657 
GrDrawOpAtlasConfig(int maxTextureSize,size_t maxBytes)658 GrDrawOpAtlasConfig::GrDrawOpAtlasConfig(int maxTextureSize, size_t maxBytes) {
659     static const SkISize kARGBDimensions[] = {
660         {256, 256},   // maxBytes < 2^19
661         {512, 256},   // 2^19 <= maxBytes < 2^20
662         {512, 512},   // 2^20 <= maxBytes < 2^21
663         {1024, 512},  // 2^21 <= maxBytes < 2^22
664         {1024, 1024}, // 2^22 <= maxBytes < 2^23
665         {2048, 1024}, // 2^23 <= maxBytes
666     };
667 
668     // Index 0 corresponds to maxBytes of 2^18, so start by dividing it by that
669     maxBytes >>= 18;
670     // Take the floor of the log to get the index
671     int index = maxBytes > 0
672         ? SkTPin<int>(SkPrevLog2(maxBytes), 0, SK_ARRAY_COUNT(kARGBDimensions) - 1)
673         : 0;
674 
675     SkASSERT(kARGBDimensions[index].width() <= kMaxAtlasDim);
676     SkASSERT(kARGBDimensions[index].height() <= kMaxAtlasDim);
677     fARGBDimensions.set(SkTMin<int>(kARGBDimensions[index].width(), maxTextureSize),
678                         SkTMin<int>(kARGBDimensions[index].height(), maxTextureSize));
679     fMaxTextureSize = SkTMin<int>(maxTextureSize, kMaxAtlasDim);
680 }
681 
resetAsSmallPage()682 int GrDrawOpAtlasConfig::resetAsSmallPage() {
683     size_t maxBytes = fARGBDimensions.width() * fARGBDimensions.height() * 4;
684     fARGBDimensions.set(512, 512);
685     return maxBytes / (fARGBDimensions.width() * fARGBDimensions.height());
686 }
687 
atlasDimensions(GrMaskFormat type) const688 SkISize GrDrawOpAtlasConfig::atlasDimensions(GrMaskFormat type) const {
689     if (kA8_GrMaskFormat == type) {
690         // A8 is always 2x the ARGB dimensions, clamped to the max allowed texture size
691         return { SkTMin<int>(2 * fARGBDimensions.width(), fMaxTextureSize),
692                  SkTMin<int>(2 * fARGBDimensions.height(), fMaxTextureSize) };
693     } else {
694         return fARGBDimensions;
695     }
696 }
697 
plotDimensions(GrMaskFormat type) const698 SkISize GrDrawOpAtlasConfig::plotDimensions(GrMaskFormat type) const {
699     if (kA8_GrMaskFormat == type) {
700         SkISize atlasDimensions = this->atlasDimensions(type);
701         // For A8 we want to grow the plots at larger texture sizes to accept more of the
702         // larger SDF glyphs. Since the largest SDF glyph can be 170x170 with padding, this
703         // allows us to pack 3 in a 512x256 plot, or 9 in a 512x512 plot.
704 
705         // This will give us 512x512 plots for 1024x1024, 256x256 plots for otherwise.
706         int plotWidth = atlasDimensions.width() >= 1024 ? 512 : 256;
707         int plotHeight = atlasDimensions.height() >= 1024 ? 512 : 256;
708 
709         return { plotWidth, plotHeight };
710     } else {
711         // ARGB and LCD always use 256x256 plots -- this has been shown to be faster
712         return { 256, 256 };
713     }
714 }
715 
716 constexpr int GrDrawOpAtlasConfig::kMaxAtlasDim;
717