• 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/ganesh/GrDrawOpAtlas.h"
9 
10 #include <memory>
11 
12 #include "include/private/base/SkTPin.h"
13 #include "src/core/SkOpts.h"
14 #include "src/gpu/ganesh/GrBackendUtils.h"
15 #include "src/gpu/ganesh/GrCaps.h"
16 #include "src/gpu/ganesh/GrOnFlushResourceProvider.h"
17 #include "src/gpu/ganesh/GrOpFlushState.h"
18 #include "src/gpu/ganesh/GrProxyProvider.h"
19 #include "src/gpu/ganesh/GrResourceProvider.h"
20 #include "src/gpu/ganesh/GrResourceProviderPriv.h"
21 #include "src/gpu/ganesh/GrSurfaceProxyPriv.h"
22 #include "src/gpu/ganesh/GrTexture.h"
23 #include "src/gpu/ganesh/GrTracing.h"
24 
25 using AtlasLocator = skgpu::AtlasLocator;
26 using AtlasToken = skgpu::AtlasToken;
27 using EvictionCallback = skgpu::PlotEvictionCallback;
28 using GenerationCounter = skgpu::AtlasGenerationCounter;
29 using MaskFormat = skgpu::MaskFormat;
30 using Plot = skgpu::Plot;
31 using PlotList = skgpu::PlotList;
32 using PlotLocator = skgpu::PlotLocator;
33 
34 #if defined(DUMP_ATLAS_DATA)
35 static const constexpr bool kDumpAtlasData = true;
36 #else
37 static const constexpr bool kDumpAtlasData = false;
38 #endif
39 
40 #ifdef SK_DEBUG
validate(const AtlasLocator & atlasLocator) const41 void GrDrawOpAtlas::validate(const AtlasLocator& atlasLocator) const {
42     // Verify that the plotIndex stored in the PlotLocator is consistent with the glyph rectangle
43     int numPlotsX = fTextureWidth / fPlotWidth;
44     int numPlotsY = fTextureHeight / fPlotHeight;
45 
46     int plotIndex = atlasLocator.plotIndex();
47     auto topLeft = atlasLocator.topLeft();
48     int plotX = topLeft.x() / fPlotWidth;
49     int plotY = topLeft.y() / fPlotHeight;
50     SkASSERT(plotIndex == (numPlotsY - plotY - 1) * numPlotsX + (numPlotsX - plotX - 1));
51 }
52 #endif
53 
54 // When proxy allocation is deferred until flush time the proxies acting as atlases require
55 // special handling. This is because the usage that can be determined from the ops themselves
56 // isn't sufficient. Independent of the ops there will be ASAP and inline uploads to the
57 // atlases. Extending the usage interval of any op that uses an atlas to the start of the
58 // flush (as is done for proxies that are used for sw-generated masks) also won't work because
59 // the atlas persists even beyond the last use in an op - for a given flush. Given this, atlases
60 // must explicitly manage the lifetime of their backing proxies via the onFlushCallback system
61 // (which calls this method).
instantiate(GrOnFlushResourceProvider * onFlushResourceProvider)62 void GrDrawOpAtlas::instantiate(GrOnFlushResourceProvider* onFlushResourceProvider) {
63     for (uint32_t i = 0; i < fNumActivePages; ++i) {
64         // All the atlas pages are now instantiated at flush time in the activeNewPage method.
65         SkASSERT(fViews[i].proxy() && fViews[i].proxy()->isInstantiated());
66     }
67 }
68 
Make(GrProxyProvider * proxyProvider,const GrBackendFormat & format,SkColorType colorType,size_t bpp,int width,int height,int plotWidth,int plotHeight,GenerationCounter * generationCounter,AllowMultitexturing allowMultitexturing,EvictionCallback * evictor,std::string_view label)69 std::unique_ptr<GrDrawOpAtlas> GrDrawOpAtlas::Make(GrProxyProvider* proxyProvider,
70                                                    const GrBackendFormat& format,
71                                                    SkColorType colorType, size_t bpp, int width,
72                                                    int height, int plotWidth, int plotHeight,
73                                                    GenerationCounter* generationCounter,
74                                                    AllowMultitexturing allowMultitexturing,
75                                                    EvictionCallback* evictor,
76                                                    std::string_view label) {
77     if (!format.isValid()) {
78         return nullptr;
79     }
80 
81     std::unique_ptr<GrDrawOpAtlas> atlas(new GrDrawOpAtlas(proxyProvider, format, colorType, bpp,
82                                                            width, height, plotWidth, plotHeight,
83                                                            generationCounter,
84                                                            allowMultitexturing, label));
85     if (!atlas->getViews()[0].proxy()) {
86         return nullptr;
87     }
88 
89     if (evictor != nullptr) {
90         atlas->fEvictionCallbacks.emplace_back(evictor);
91     }
92     return atlas;
93 }
94 
95 ///////////////////////////////////////////////////////////////////////////////
96 
GrDrawOpAtlas(GrProxyProvider * proxyProvider,const GrBackendFormat & format,SkColorType colorType,size_t bpp,int width,int height,int plotWidth,int plotHeight,GenerationCounter * generationCounter,AllowMultitexturing allowMultitexturing,std::string_view label)97 GrDrawOpAtlas::GrDrawOpAtlas(GrProxyProvider* proxyProvider, const GrBackendFormat& format,
98                              SkColorType colorType, size_t bpp, int width, int height,
99                              int plotWidth, int plotHeight, GenerationCounter* generationCounter,
100                              AllowMultitexturing allowMultitexturing, std::string_view label)
101         : fFormat(format)
102         , fColorType(colorType)
103         , fBytesPerPixel(bpp)
104         , fTextureWidth(width)
105         , fTextureHeight(height)
106         , fPlotWidth(plotWidth)
107         , fPlotHeight(plotHeight)
108         , fLabel(label)
109         , fGenerationCounter(generationCounter)
110         , fAtlasGeneration(fGenerationCounter->next())
111         , fPrevFlushToken(AtlasToken::InvalidToken())
112         , fFlushesSinceLastUse(0)
113         , fMaxPages(AllowMultitexturing::kYes == allowMultitexturing ?
114                             PlotLocator::kMaxMultitexturePages : 1)
115         , fNumActivePages(0) {
116     int numPlotsX = width/plotWidth;
117     int numPlotsY = height/plotHeight;
118     SkASSERT(numPlotsX * numPlotsY <= PlotLocator::kMaxPlots);
119     SkASSERT(fPlotWidth * numPlotsX == fTextureWidth);
120     SkASSERT(fPlotHeight * numPlotsY == fTextureHeight);
121 
122     fNumPlots = numPlotsX * numPlotsY;
123 
124     this->createPages(proxyProvider, generationCounter);
125 }
126 
processEviction(PlotLocator plotLocator)127 inline void GrDrawOpAtlas::processEviction(PlotLocator plotLocator) {
128     for (EvictionCallback* evictor : fEvictionCallbacks) {
129         evictor->evict(plotLocator);
130     }
131 
132     fAtlasGeneration = fGenerationCounter->next();
133 }
134 
uploadPlotToTexture(GrDeferredTextureUploadWritePixelsFn & writePixels,GrTextureProxy * proxy,Plot * plot)135 void GrDrawOpAtlas::uploadPlotToTexture(GrDeferredTextureUploadWritePixelsFn& writePixels,
136                                         GrTextureProxy* proxy,
137                                         Plot* plot) {
138     SkASSERT(proxy && proxy->peekTexture());
139     TRACE_EVENT0("skia.gpu", TRACE_FUNC);
140 
141     const void* dataPtr;
142     SkIRect rect;
143     std::tie(dataPtr, rect) = plot->prepareForUpload(/*useCachedUploads=*/false);
144 
145     writePixels(proxy,
146                 rect,
147                 SkColorTypeToGrColorType(fColorType),
148                 dataPtr,
149                 fBytesPerPixel*fPlotWidth);
150 }
151 
updatePlot(GrDeferredUploadTarget * target,AtlasLocator * atlasLocator,Plot * plot)152 inline bool GrDrawOpAtlas::updatePlot(GrDeferredUploadTarget* target,
153                                       AtlasLocator* atlasLocator, Plot* plot) {
154     int pageIdx = plot->pageIndex();
155     this->makeMRU(plot, pageIdx);
156 
157     // If our most recent upload has already occurred then we have to insert a new
158     // upload. Otherwise, we already have a scheduled upload that hasn't yet ocurred.
159     // This new update will piggy back on that previously scheduled update.
160     if (plot->lastUploadToken() < target->tokenTracker()->nextFlushToken()) {
161         // With c+14 we could move sk_sp into lamba to only ref once.
162         sk_sp<Plot> plotsp(SkRef(plot));
163 
164         GrTextureProxy* proxy = fViews[pageIdx].asTextureProxy();
165         SkASSERT(proxy && proxy->isInstantiated());  // This is occurring at flush time
166 
167         AtlasToken lastUploadToken = target->addASAPUpload(
168                 [this, plotsp, proxy](GrDeferredTextureUploadWritePixelsFn& writePixels) {
169                     this->uploadPlotToTexture(writePixels, proxy, plotsp.get());
170                 });
171         plot->setLastUploadToken(lastUploadToken);
172     }
173     atlasLocator->updatePlotLocator(plot->plotLocator());
174     SkDEBUGCODE(this->validate(*atlasLocator);)
175     return true;
176 }
177 
uploadToPage(unsigned int pageIdx,GrDeferredUploadTarget * target,int width,int height,const void * image,AtlasLocator * atlasLocator)178 bool GrDrawOpAtlas::uploadToPage(unsigned int pageIdx, GrDeferredUploadTarget* target, int width,
179                                  int height, const void* image, AtlasLocator* atlasLocator) {
180     SkASSERT(fViews[pageIdx].proxy() && fViews[pageIdx].proxy()->isInstantiated());
181 
182     // look through all allocated plots for one we can share, in Most Recently Refed order
183     PlotList::Iter plotIter;
184     plotIter.init(fPages[pageIdx].fPlotList, PlotList::Iter::kHead_IterStart);
185 
186     for (Plot* plot = plotIter.get(); plot; plot = plotIter.next()) {
187         SkASSERT(GrBackendFormatBytesPerPixel(fViews[pageIdx].proxy()->backendFormat()) ==
188                  plot->bpp());
189 
190         if (plot->addSubImage(width, height, image, atlasLocator)) {
191             return this->updatePlot(target, atlasLocator, plot);
192         }
193     }
194 
195     return false;
196 }
197 
198 // Number of atlas-related flushes beyond which we consider a plot to no longer be in use.
199 //
200 // This value is somewhat arbitrary -- the idea is to keep it low enough that
201 // a page with unused plots will get removed reasonably quickly, but allow it
202 // to hang around for a bit in case it's needed. The assumption is that flushes
203 // are rare; i.e., we are not continually refreshing the frame.
204 static constexpr auto kPlotRecentlyUsedCount = 32;
205 static constexpr auto kAtlasRecentlyUsedCount = 128;
206 
addToAtlas(GrResourceProvider * resourceProvider,GrDeferredUploadTarget * target,int width,int height,const void * image,AtlasLocator * atlasLocator)207 GrDrawOpAtlas::ErrorCode GrDrawOpAtlas::addToAtlas(GrResourceProvider* resourceProvider,
208                                                    GrDeferredUploadTarget* target,
209                                                    int width, int height, const void* image,
210                                                    AtlasLocator* atlasLocator) {
211     if (width > fPlotWidth || height > fPlotHeight) {
212         return ErrorCode::kError;
213     }
214 
215     // Look through each page to see if we can upload without having to flush
216     // We prioritize this upload to the first pages, not the most recently used, to make it easier
217     // to remove unused pages in reverse page order.
218     for (unsigned int pageIdx = 0; pageIdx < fNumActivePages; ++pageIdx) {
219         if (this->uploadToPage(pageIdx, target, width, height, image, atlasLocator)) {
220             return ErrorCode::kSucceeded;
221         }
222     }
223 
224     // If the above fails, then see if the least recently used plot per page has already been
225     // flushed to the gpu if we're at max page allocation, or if the plot has aged out otherwise.
226     // We wait until we've grown to the full number of pages to begin evicting already flushed
227     // plots so that we can maximize the opportunity for reuse.
228     // As before we prioritize this upload to the first pages, not the most recently used.
229     if (fNumActivePages == this->maxPages()) {
230         for (unsigned int pageIdx = 0; pageIdx < fNumActivePages; ++pageIdx) {
231             Plot* plot = fPages[pageIdx].fPlotList.tail();
232             SkASSERT(plot);
233             if (plot->lastUseToken() < target->tokenTracker()->nextFlushToken()) {
234                 this->processEvictionAndResetRects(plot);
235                 SkASSERT(GrBackendFormatBytesPerPixel(fViews[pageIdx].proxy()->backendFormat()) ==
236                          plot->bpp());
237                 SkDEBUGCODE(bool verify = )plot->addSubImage(width, height, image, atlasLocator);
238                 SkASSERT(verify);
239                 if (!this->updatePlot(target, atlasLocator, plot)) {
240                     return ErrorCode::kError;
241                 }
242                 return ErrorCode::kSucceeded;
243             }
244         }
245     } else {
246         // If we haven't activated all the available pages, try to create a new one and add to it
247         if (!this->activateNewPage(resourceProvider)) {
248             return ErrorCode::kError;
249         }
250 
251         if (this->uploadToPage(fNumActivePages-1, target, width, height, image, atlasLocator)) {
252             return ErrorCode::kSucceeded;
253         } else {
254             // If we fail to upload to a newly activated page then something has gone terribly
255             // wrong - return an error
256             return ErrorCode::kError;
257         }
258     }
259 
260     if (!fNumActivePages) {
261         return ErrorCode::kError;
262     }
263 
264     // Try to find a plot that we can perform an inline upload to.
265     // We prioritize this upload in reverse order of pages to counterbalance the order above.
266     Plot* plot = nullptr;
267     for (int pageIdx = ((int)fNumActivePages)-1; pageIdx >= 0; --pageIdx) {
268         Plot* currentPlot = fPages[pageIdx].fPlotList.tail();
269         if (currentPlot->lastUseToken() != target->tokenTracker()->nextDrawToken()) {
270             plot = currentPlot;
271             break;
272         }
273     }
274 
275     // If we can't find a plot that is not used in a draw currently being prepared by an op, then
276     // we have to fail. This gives the op a chance to enqueue the draw, and call back into this
277     // function. When that draw is enqueued, the draw token advances, and the subsequent call will
278     // continue past this branch and prepare an inline upload that will occur after the enqueued
279     // draw which references the plot's pre-upload content.
280     if (!plot) {
281         return ErrorCode::kTryAgain;
282     }
283 
284     this->processEviction(plot->plotLocator());
285     int pageIdx = plot->pageIndex();
286     fPages[pageIdx].fPlotList.remove(plot);
287     sk_sp<Plot>& newPlot = fPages[pageIdx].fPlotArray[plot->plotIndex()];
288     newPlot = plot->clone();
289 
290     fPages[pageIdx].fPlotList.addToHead(newPlot.get());
291     SkASSERT(GrBackendFormatBytesPerPixel(fViews[pageIdx].proxy()->backendFormat()) ==
292              newPlot->bpp());
293     SkDEBUGCODE(bool verify = )newPlot->addSubImage(width, height, image, atlasLocator);
294     SkASSERT(verify);
295 
296     // Note that this plot will be uploaded inline with the draws whereas the
297     // one it displaced most likely was uploaded ASAP.
298     // With c++14 we could move sk_sp into lambda to only ref once.
299     sk_sp<Plot> plotsp(SkRef(newPlot.get()));
300 
301     GrTextureProxy* proxy = fViews[pageIdx].asTextureProxy();
302     SkASSERT(proxy && proxy->isInstantiated());
303 
304     AtlasToken lastUploadToken = target->addInlineUpload(
305             [this, plotsp, proxy](GrDeferredTextureUploadWritePixelsFn& writePixels) {
306                 this->uploadPlotToTexture(writePixels, proxy, plotsp.get());
307             });
308     newPlot->setLastUploadToken(lastUploadToken);
309 
310     atlasLocator->updatePlotLocator(newPlot->plotLocator());
311     SkDEBUGCODE(this->validate(*atlasLocator);)
312 
313     return ErrorCode::kSucceeded;
314 }
315 
compact(AtlasToken startTokenForNextFlush)316 void GrDrawOpAtlas::compact(AtlasToken startTokenForNextFlush) {
317     if (fNumActivePages < 1) {
318         fPrevFlushToken = startTokenForNextFlush;
319         return;
320     }
321 
322     // For all plots, reset number of flushes since used if used this frame.
323     PlotList::Iter plotIter;
324     bool atlasUsedThisFlush = false;
325     for (uint32_t pageIndex = 0; pageIndex < fNumActivePages; ++pageIndex) {
326         plotIter.init(fPages[pageIndex].fPlotList, PlotList::Iter::kHead_IterStart);
327         while (Plot* plot = plotIter.get()) {
328             // Reset number of flushes since used
329             if (plot->lastUseToken().inInterval(fPrevFlushToken, startTokenForNextFlush)) {
330                 plot->resetFlushesSinceLastUsed();
331                 atlasUsedThisFlush = true;
332             }
333 
334             plotIter.next();
335         }
336     }
337 
338     if (atlasUsedThisFlush) {
339         fFlushesSinceLastUse = 0;
340     } else {
341         ++fFlushesSinceLastUse;
342     }
343 
344     // We only try to compact if the atlas was used in the recently completed flush or
345     // hasn't been used in a long time.
346     // This is to handle the case where a lot of text or path rendering has occurred but then just
347     // a blinking cursor is drawn.
348     if (atlasUsedThisFlush || fFlushesSinceLastUse > kAtlasRecentlyUsedCount) {
349         SkTArray<Plot*> availablePlots;
350         uint32_t lastPageIndex = fNumActivePages - 1;
351 
352         // For all plots but the last one, update number of flushes since used, and check to see
353         // if there are any in the first pages that the last page can safely upload to.
354         for (uint32_t pageIndex = 0; pageIndex < lastPageIndex; ++pageIndex) {
355             if constexpr (kDumpAtlasData) {
356                 SkDebugf("page %d: ", pageIndex);
357             }
358 
359             plotIter.init(fPages[pageIndex].fPlotList, PlotList::Iter::kHead_IterStart);
360             while (Plot* plot = plotIter.get()) {
361                 // Update number of flushes since plot was last used
362                 // We only increment the 'sinceLastUsed' count for flushes where the atlas was used
363                 // to avoid deleting everything when we return to text drawing in the blinking
364                 // cursor case
365                 if (!plot->lastUseToken().inInterval(fPrevFlushToken, startTokenForNextFlush)) {
366                     plot->incFlushesSinceLastUsed();
367                 }
368 
369                 if constexpr (kDumpAtlasData) {
370                     SkDebugf("%d ", plot->flushesSinceLastUsed());
371                 }
372 
373                 // Count plots we can potentially upload to in all pages except the last one
374                 // (the potential compactee).
375                 if (plot->flushesSinceLastUsed() > kPlotRecentlyUsedCount) {
376                     availablePlots.push_back() = plot;
377                 }
378 
379                 plotIter.next();
380             }
381 
382             if constexpr (kDumpAtlasData) {
383                 SkDebugf("\n");
384             }
385         }
386 
387         // Count recently used plots in the last page and evict any that are no longer in use.
388         // Since we prioritize uploading to the first pages, this will eventually
389         // clear out usage of this page unless we have a large need.
390         plotIter.init(fPages[lastPageIndex].fPlotList, PlotList::Iter::kHead_IterStart);
391         unsigned int usedPlots = 0;
392         if constexpr (kDumpAtlasData) {
393             SkDebugf("page %d: ", lastPageIndex);
394         }
395 
396         while (Plot* plot = plotIter.get()) {
397             // Update number of flushes since plot was last used
398             if (!plot->lastUseToken().inInterval(fPrevFlushToken, startTokenForNextFlush)) {
399                 plot->incFlushesSinceLastUsed();
400             }
401 
402             if constexpr (kDumpAtlasData) {
403                 SkDebugf("%d ", plot->flushesSinceLastUsed());
404             }
405 
406             // If this plot was used recently
407             if (plot->flushesSinceLastUsed() <= kPlotRecentlyUsedCount) {
408                 usedPlots++;
409             } else if (plot->lastUseToken() != AtlasToken::InvalidToken()) {
410                 // otherwise if aged out just evict it.
411                 this->processEvictionAndResetRects(plot);
412             }
413             plotIter.next();
414         }
415 
416         if constexpr (kDumpAtlasData) {
417             SkDebugf("\n");
418         }
419 
420         // If recently used plots in the last page are using less than a quarter of the page, try
421         // to evict them if there's available space in earlier pages. Since we prioritize uploading
422         // to the first pages, this will eventually clear out usage of this page unless we have a
423         // large need.
424         if (availablePlots.size() && usedPlots && usedPlots <= fNumPlots / 4) {
425             plotIter.init(fPages[lastPageIndex].fPlotList, PlotList::Iter::kHead_IterStart);
426             while (Plot* plot = plotIter.get()) {
427                 // If this plot was used recently
428                 if (plot->flushesSinceLastUsed() <= kPlotRecentlyUsedCount) {
429                     // See if there's room in an earlier page and if so evict.
430                     // We need to be somewhat harsh here so that a handful of plots that are
431                     // consistently in use don't end up locking the page in memory.
432                     if (availablePlots.size() > 0) {
433                         this->processEvictionAndResetRects(plot);
434                         this->processEvictionAndResetRects(availablePlots.back());
435                         availablePlots.pop_back();
436                         --usedPlots;
437                     }
438                     if (!usedPlots || !availablePlots.size()) {
439                         break;
440                     }
441                 }
442                 plotIter.next();
443             }
444         }
445 
446         // If none of the plots in the last page have been used recently, delete it.
447         if (!usedPlots) {
448             if constexpr (kDumpAtlasData) {
449                 SkDebugf("delete %d\n", fNumActivePages-1);
450             }
451 
452             this->deactivateLastPage();
453             fFlushesSinceLastUse = 0;
454         }
455     }
456 
457     fPrevFlushToken = startTokenForNextFlush;
458 }
459 
createPages(GrProxyProvider * proxyProvider,GenerationCounter * generationCounter)460 bool GrDrawOpAtlas::createPages(
461         GrProxyProvider* proxyProvider, GenerationCounter* generationCounter) {
462     SkASSERT(SkIsPow2(fTextureWidth) && SkIsPow2(fTextureHeight));
463 
464     SkISize dims = {fTextureWidth, fTextureHeight};
465 
466     int numPlotsX = fTextureWidth/fPlotWidth;
467     int numPlotsY = fTextureHeight/fPlotHeight;
468 
469     GrColorType grColorType = SkColorTypeToGrColorType(fColorType);
470 
471     for (uint32_t i = 0; i < this->maxPages(); ++i) {
472         skgpu::Swizzle swizzle = proxyProvider->caps()->getReadSwizzle(fFormat, grColorType);
473         if (GrColorTypeIsAlphaOnly(grColorType)) {
474             swizzle = skgpu::Swizzle::Concat(swizzle, skgpu::Swizzle("aaaa"));
475         }
476         sk_sp<GrSurfaceProxy> proxy = proxyProvider->createProxy(fFormat,
477                                                                  dims,
478                                                                  GrRenderable::kNo,
479                                                                  1,
480                                                                  GrMipmapped::kNo,
481                                                                  SkBackingFit::kExact,
482                                                                  skgpu::Budgeted::kYes,
483                                                                  GrProtected::kNo,
484                                                                  fLabel,
485                                                                  GrInternalSurfaceFlags::kNone,
486                                                                  GrSurfaceProxy::UseAllocator::kNo);
487         if (!proxy) {
488             return false;
489         }
490         fViews[i] = GrSurfaceProxyView(std::move(proxy), kTopLeft_GrSurfaceOrigin, swizzle);
491 
492         // set up allocated plots
493         fPages[i].fPlotArray = std::make_unique<sk_sp<Plot>[]>(numPlotsX * numPlotsY);
494 
495         sk_sp<Plot>* currPlot = fPages[i].fPlotArray.get();
496         for (int y = numPlotsY - 1, r = 0; y >= 0; --y, ++r) {
497             for (int x = numPlotsX - 1, c = 0; x >= 0; --x, ++c) {
498                 uint32_t plotIndex = r * numPlotsX + c;
499                 currPlot->reset(new Plot(
500                     i, plotIndex, generationCounter, x, y, fPlotWidth, fPlotHeight, fColorType,
501                     fBytesPerPixel));
502 
503                 // build LRU list
504                 fPages[i].fPlotList.addToHead(currPlot->get());
505                 ++currPlot;
506             }
507         }
508 
509     }
510 
511     return true;
512 }
513 
activateNewPage(GrResourceProvider * resourceProvider)514 bool GrDrawOpAtlas::activateNewPage(GrResourceProvider* resourceProvider) {
515     SkASSERT(fNumActivePages < this->maxPages());
516 
517     if (!fViews[fNumActivePages].proxy()->instantiate(resourceProvider)) {
518         return false;
519     }
520 
521     if constexpr (kDumpAtlasData) {
522         SkDebugf("activated page#: %d\n", fNumActivePages);
523     }
524 
525     ++fNumActivePages;
526     return true;
527 }
528 
deactivateLastPage()529 inline void GrDrawOpAtlas::deactivateLastPage() {
530     SkASSERT(fNumActivePages);
531 
532     uint32_t lastPageIndex = fNumActivePages - 1;
533 
534     int numPlotsX = fTextureWidth/fPlotWidth;
535     int numPlotsY = fTextureHeight/fPlotHeight;
536 
537     fPages[lastPageIndex].fPlotList.reset();
538     for (int r = 0; r < numPlotsY; ++r) {
539         for (int c = 0; c < numPlotsX; ++c) {
540             uint32_t plotIndex = r * numPlotsX + c;
541 
542             Plot* currPlot = fPages[lastPageIndex].fPlotArray[plotIndex].get();
543             currPlot->resetRects();
544             currPlot->resetFlushesSinceLastUsed();
545 
546             // rebuild the LRU list
547             SkDEBUGCODE(currPlot->resetListPtrs());
548             fPages[lastPageIndex].fPlotList.addToHead(currPlot);
549         }
550     }
551 
552     // remove ref to the backing texture
553     fViews[lastPageIndex].proxy()->deinstantiate();
554     --fNumActivePages;
555 }
556 
GrDrawOpAtlasConfig(int maxTextureSize,size_t maxBytes)557 GrDrawOpAtlasConfig::GrDrawOpAtlasConfig(int maxTextureSize, size_t maxBytes) {
558     static const SkISize kARGBDimensions[] = {
559         {256, 256},   // maxBytes < 2^19
560         {512, 256},   // 2^19 <= maxBytes < 2^20
561         {512, 512},   // 2^20 <= maxBytes < 2^21
562         {1024, 512},  // 2^21 <= maxBytes < 2^22
563         {1024, 1024}, // 2^22 <= maxBytes < 2^23
564         {2048, 1024}, // 2^23 <= maxBytes
565     };
566 
567     // Index 0 corresponds to maxBytes of 2^18, so start by dividing it by that
568     maxBytes >>= 18;
569     // Take the floor of the log to get the index
570     int index = maxBytes > 0
571         ? SkTPin<int>(SkPrevLog2(maxBytes), 0, std::size(kARGBDimensions) - 1)
572         : 0;
573 
574     SkASSERT(kARGBDimensions[index].width() <= kMaxAtlasDim);
575     SkASSERT(kARGBDimensions[index].height() <= kMaxAtlasDim);
576     fARGBDimensions.set(std::min<int>(kARGBDimensions[index].width(), maxTextureSize),
577                         std::min<int>(kARGBDimensions[index].height(), maxTextureSize));
578     fMaxTextureSize = std::min<int>(maxTextureSize, kMaxAtlasDim);
579 }
580 
atlasDimensions(MaskFormat type) const581 SkISize GrDrawOpAtlasConfig::atlasDimensions(MaskFormat type) const {
582     if (MaskFormat::kA8 == type) {
583         // A8 is always 2x the ARGB dimensions, clamped to the max allowed texture size
584         return { std::min<int>(2 * fARGBDimensions.width(), fMaxTextureSize),
585                  std::min<int>(2 * fARGBDimensions.height(), fMaxTextureSize) };
586     } else {
587         return fARGBDimensions;
588     }
589 }
590 
plotDimensions(MaskFormat type) const591 SkISize GrDrawOpAtlasConfig::plotDimensions(MaskFormat type) const {
592     if (MaskFormat::kA8 == type) {
593         SkISize atlasDimensions = this->atlasDimensions(type);
594         // For A8 we want to grow the plots at larger texture sizes to accept more of the
595         // larger SDF glyphs. Since the largest SDF glyph can be 170x170 with padding, this
596         // allows us to pack 3 in a 512x256 plot, or 9 in a 512x512 plot.
597 
598         // This will give us 512x256 plots for 2048x1024, 512x512 plots for 2048x2048,
599         // and 256x256 plots otherwise.
600         int plotWidth = atlasDimensions.width() >= 2048 ? 512 : 256;
601         int plotHeight = atlasDimensions.height() >= 2048 ? 512 : 256;
602 
603         return { plotWidth, plotHeight };
604     } else {
605         // ARGB and LCD always use 256x256 plots -- this has been shown to be faster
606         return { 256, 256 };
607     }
608 }
609