Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
DrawAtlas.h
Go to the documentation of this file.
1/*
2 * Copyright 2022 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#ifndef skgpu_graphite_DrawAtlas_DEFINED
9#define skgpu_graphite_DrawAtlas_DEFINED
10
11#include <cmath>
12#include <string>
13#include <string_view>
14#include <vector>
15
16#include "src/core/SkIPoint16.h"
17#include "src/core/SkTHash.h"
18#include "src/gpu/AtlasTypes.h"
19
21
22namespace skgpu::graphite {
23
24class DrawContext;
25class Recorder;
26class TextureProxy;
27
28/**
29 * TODO: the process described here is tentative, and this comment revised once locked down.
30 *
31 * This class manages one or more atlas textures on behalf of primitive draws in Device. The
32 * drawing processes that use the atlas add preceding UploadTasks when generating RenderPassTasks.
33 * The class provides facilities for using DrawTokens to detect data hazards. Plots that need
34 * uploads are tracked until it is impossible to add data without overwriting texels read by draws
35 * that have not yet been snapped to a RenderPassTask. At that point, the atlas will attempt to
36 * allocate a new atlas texture (or "page") of the same size, up to a maximum number of textures,
37 * and upload to that texture. If that's not possible, then the atlas will fail to add a subimage.
38 * This gives the Device the chance to end the current draw, snap a RenderpassTask, and begin a new
39 * one. Additional uploads will then succeed.
40 *
41 * When the atlas has multiple pages, new uploads are prioritized to the lower index pages, i.e.,
42 * it will try to upload to page 0 before page 1 or 2. To keep the atlas from continually using
43 * excess space, periodic garbage collection is needed to shift data from the higher index pages to
44 * the lower ones, and then eventually remove any pages that are no longer in use. "In use" is
45 * determined by using the AtlasToken system: After a DrawPass is snapped a subarea of the page, or
46 * "plot" is checked to see whether it was used in that DrawPass. If less than a quarter of the
47 * plots have been used recently (within kPlotRecentlyUsedCount iterations) and there are available
48 * plots in lower index pages, the higher index page will be deactivated, and its glyphs will
49 * gradually migrate to other pages via the usual upload system.
50 *
51 * Garbage collection is initiated by the DrawAtlas's client via the compact() method.
52 */
53class DrawAtlas {
54public:
55 /** Is the atlas allowed to use more than one texture? */
56 enum class AllowMultitexturing : bool { kNo, kYes };
57
58 /**
59 * Returns a DrawAtlas.
60 * @param ct The colorType which this atlas will store.
61 * @param bpp Size in bytes of each pixel.
62 * @param width Width in pixels of the atlas.
63 * @param height Height in pixels of the atlas.
64 * @param plotWidth The width of each plot. width/plotWidth should be an integer.
65 * @param plotWidth The height of each plot. height/plotHeight should be an integer.
66 * @param atlasGeneration A pointer to the context's generation counter.
67 * @param allowMultitexturing Can the atlas use more than one texture.
68 * @param evictor A pointer to an eviction callback class.
69 *
70 * @return An initialized DrawAtlas, or nullptr if creation fails.
71 */
72 static std::unique_ptr<DrawAtlas> Make(SkColorType ct, size_t bpp,
73 int width, int height,
74 int plotWidth, int plotHeight,
75 AtlasGenerationCounter* generationCounter,
76 AllowMultitexturing allowMultitexturing,
77 PlotEvictionCallback* evictor,
78 std::string_view label);
79
80 /**
81 * Adds a width x height subimage to the atlas. Upon success it returns 'kSucceeded' and returns
82 * the ID and the subimage's coordinates in the backing texture. 'kTryAgain' is returned if
83 * the subimage cannot fit in the atlas without overwriting texels that will be read in the
84 * current list of draws. This indicates that the Device should end its current draw, snap a
85 * DrawPass, and begin another before adding more data. 'kError' will be returned when some
86 * unrecoverable error was encountered while trying to add the subimage. In this case the draw
87 * being created should be discarded.
88 *
89 * This tracking does not generate UploadTasks per se. Instead, when the RenderPassTask is
90 * ready to be snapped, recordUploads() will be called by the Device and that will generate the
91 * necessary UploadTasks. If the useCachedUploads argument in recordUploads() is true, this
92 * will generate uploads for the entire area of each Plot that has changed since the last
93 * eviction. Otherwise it will only generate uploads for newly added changes.
94 *
95 * NOTE: When a draw that reads from the atlas is added to the DrawList, the client using this
96 * DrawAtlas must immediately call 'setLastUseToken' with the currentToken from the Recorder,
97 * otherwise the next call to addToAtlas might cause the previous data to be overwritten before
98 * it has been read.
99 */
100
101 enum class ErrorCode {
102 kError,
105 };
106
107 ErrorCode addToAtlas(Recorder*, int width, int height, const void* image, AtlasLocator*);
109 // Reset Pixmap to point to backing data for the AtlasLocator's Plot.
110 // Return relative location within the Plot, as indicated by the AtlasLocator.
113
114 const sk_sp<TextureProxy>* getProxies() const { return fProxies; }
115
116 uint32_t atlasID() const { return fAtlasID; }
117 uint64_t atlasGeneration() const { return fAtlasGeneration; }
118 uint32_t numActivePages() const { return fNumActivePages; }
119 unsigned int numPlots() const { return fNumPlots; }
120 SkISize plotSize() const { return {fPlotWidth, fPlotHeight}; }
121
122 bool hasID(const PlotLocator& plotLocator) {
123 if (!plotLocator.isValid()) {
124 return false;
125 }
126
127 uint32_t plot = plotLocator.plotIndex();
128 uint32_t page = plotLocator.pageIndex();
129 uint64_t plotGeneration = fPages[page].fPlotArray[plot]->genID();
130 uint64_t locatorGeneration = plotLocator.genID();
131 return plot < fNumPlots && page < fNumActivePages && plotGeneration == locatorGeneration;
132 }
133
134 /** To ensure the atlas does not evict a given entry, the client must set the last use token. */
135 void setLastUseToken(const AtlasLocator& atlasLocator, AtlasToken token) {
136 Plot* plot = this->findPlot(atlasLocator);
137 this->internalSetLastUseToken(plot, atlasLocator.pageIndex(), token);
138 }
139
141 AtlasToken token) {
142 int count = updater.count();
143 for (int i = 0; i < count; i++) {
144 const BulkUsePlotUpdater::PlotData& pd = updater.plotData(i);
145 // it's possible we've added a plot to the updater and subsequently the plot's page
146 // was deleted -- so we check to prevent a crash
147 if (pd.fPageIndex < fNumActivePages) {
148 Plot* plot = fPages[pd.fPageIndex].fPlotArray[pd.fPlotIndex].get();
149 this->internalSetLastUseToken(plot, pd.fPageIndex, token);
150 }
151 }
152 }
153
154 void compact(AtlasToken startTokenForNextFlush);
155
156 void evictAllPlots();
157
158 uint32_t maxPages() const {
159 return fMaxPages;
160 }
161
164
165private:
166 DrawAtlas(SkColorType, size_t bpp, int width, int height, int plotWidth, int plotHeight,
167 AtlasGenerationCounter* generationCounter,
168 AllowMultitexturing allowMultitexturing, std::string_view label);
169
170 bool addRectToPage(unsigned int pageIdx, int width, int height, AtlasLocator*);
171
172 void updatePlot(Plot* plot, AtlasLocator*);
173
174 inline void makeMRU(Plot* plot, int pageIdx) {
175 if (fPages[pageIdx].fPlotList.head() == plot) {
176 return;
177 }
178
179 fPages[pageIdx].fPlotList.remove(plot);
180 fPages[pageIdx].fPlotList.addToHead(plot);
181
182 // No MRU update for pages -- since we will always try to add from
183 // the front and remove from the back there is no need for MRU.
184 }
185
186 Plot* findPlot(const AtlasLocator& atlasLocator) {
187 SkASSERT(this->hasID(atlasLocator.plotLocator()));
188 uint32_t pageIdx = atlasLocator.pageIndex();
189 uint32_t plotIdx = atlasLocator.plotIndex();
190 return fPages[pageIdx].fPlotArray[plotIdx].get();
191 }
192
193 void internalSetLastUseToken(Plot* plot, uint32_t pageIdx, AtlasToken token) {
194 this->makeMRU(plot, pageIdx);
195 plot->setLastUseToken(token);
196 }
197
198 bool createPages(AtlasGenerationCounter*);
199 bool activateNewPage(Recorder*);
200 void deactivateLastPage();
201
202 void processEviction(PlotLocator);
203 inline void processEvictionAndResetRects(Plot* plot) {
204 this->processEviction(plot->plotLocator());
205 plot->resetRects();
206 }
207
208 SkColorType fColorType;
209 size_t fBytesPerPixel;
210 int fTextureWidth;
211 int fTextureHeight;
212 int fPlotWidth;
213 int fPlotHeight;
214 unsigned int fNumPlots;
215 const std::string fLabel;
216 uint32_t fAtlasID; // unique identifier for this atlas
217
218 // A counter to track the atlas eviction state for Glyphs. Each Glyph has a PlotLocator
219 // which contains its current generation. When the atlas evicts a plot, it increases
220 // the generation counter. If a Glyph's generation is less than the atlas's
221 // generation, then it knows it's been evicted and is either free to be deleted or
222 // re-added to the atlas if necessary.
223 AtlasGenerationCounter* const fGenerationCounter;
224 uint64_t fAtlasGeneration;
225
226 // nextFlushToken() value at the end of the previous DrawPass
227 // TODO: rename
228 AtlasToken fPrevFlushToken;
229
230 // the number of flushes since this atlas has been last used
231 // TODO: rename
232 int fFlushesSinceLastUse;
233
234 std::vector<PlotEvictionCallback*> fEvictionCallbacks;
235
236 struct Page {
237 // allocated array of Plots
238 std::unique_ptr<sk_sp<Plot>[]> fPlotArray;
239 // LRU list of Plots (MRU at head - LRU at tail)
240 PlotList fPlotList;
241 };
242 // proxies kept separate to make it easier to pass them up to client
245 uint32_t fMaxPages;
246
247 uint32_t fNumActivePages;
248
249 SkDEBUGCODE(void validate(const AtlasLocator& atlasLocator) const;)
250};
251
252// For text there are three atlases (A8, 565, ARGB) that are kept in relation with one another. In
253// general, because A8 is the most frequently used mask format its dimensions are 2x the 565 and
254// ARGB dimensions, with the constraint that an atlas size will always contain at least one plot.
255// Since the ARGB atlas takes the most space, its dimensions are used to size the other two atlases.
257public:
258 // The capabilities of the GPU define maxTextureSize. The client provides maxBytes, and this
259 // represents the largest they want a single atlas texture to be. Due to multitexturing, we
260 // may expand temporarily to use more space as needed.
261 DrawAtlasConfig(int maxTextureSize, size_t maxBytes);
262
265
266private:
267 // On some systems texture coordinates are represented using half-precision floating point
268 // with 11 significant bits, which limits the largest atlas dimensions to 2048x2048.
269 // For simplicity we'll use this constraint for all of our atlas textures.
270 // This can be revisited later if we need larger atlases.
271 inline static constexpr int kMaxAtlasDim = 2048;
272
273 SkISize fARGBDimensions;
274 int fMaxTextureSize;
275};
276
277} // namespace skgpu::graphite
278
279#endif
int count
#define SkASSERT(cond)
Definition SkAssert.h:116
SkColorType
Definition SkColorType.h:19
#define SkDEBUGCODE(...)
Definition SkDebug.h:23
uint32_t plotIndex() const
Definition AtlasTypes.h:305
PlotLocator plotLocator() const
Definition AtlasTypes.h:301
uint32_t pageIndex() const
Definition AtlasTypes.h:303
const PlotData & plotData(int index) const
Definition AtlasTypes.h:410
static constexpr auto kMaxMultitexturePages
Definition AtlasTypes.h:245
uint64_t genID() const
Definition AtlasTypes.h:280
uint32_t plotIndex() const
Definition AtlasTypes.h:279
bool isValid() const
Definition AtlasTypes.h:262
uint32_t pageIndex() const
Definition AtlasTypes.h:278
SkISize plotDimensions(MaskFormat type) const
SkISize atlasDimensions(MaskFormat type) const
uint32_t numActivePages() const
Definition DrawAtlas.h:118
uint32_t atlasID() const
Definition DrawAtlas.h:116
ErrorCode addRect(Recorder *, int width, int height, AtlasLocator *)
void setLastUseToken(const AtlasLocator &atlasLocator, AtlasToken token)
Definition DrawAtlas.h:135
ErrorCode addToAtlas(Recorder *, int width, int height, const void *image, AtlasLocator *)
void setMaxPages_TestingOnly(uint32_t maxPages)
bool hasID(const PlotLocator &plotLocator)
Definition DrawAtlas.h:122
uint32_t maxPages() const
Definition DrawAtlas.h:158
uint64_t atlasGeneration() const
Definition DrawAtlas.h:117
unsigned int numPlots() const
Definition DrawAtlas.h:119
void setLastUseTokenBulk(const BulkUsePlotUpdater &updater, AtlasToken token)
Definition DrawAtlas.h:140
int numAllocated_TestingOnly() const
const sk_sp< TextureProxy > * getProxies() const
Definition DrawAtlas.h:114
static std::unique_ptr< DrawAtlas > Make(SkColorType ct, size_t bpp, int width, int height, int plotWidth, int plotHeight, AtlasGenerationCounter *generationCounter, AllowMultitexturing allowMultitexturing, PlotEvictionCallback *evictor, std::string_view label)
Definition DrawAtlas.cpp:52
void compact(AtlasToken startTokenForNextFlush)
bool recordUploads(DrawContext *, Recorder *)
SkIPoint prepForRender(const AtlasLocator &, SkAutoPixmapStorage *)
SkISize plotSize() const
Definition DrawAtlas.h:120
sk_sp< SkImage > image
Definition examples.cpp:29
static void plot(SkCanvas *canvas, const char *fn, float xMin, float xMax, float yMin, float yMax, const char *label=nullptr, bool requireES3=false)
int32_t height
int32_t width