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