Debian Codegraph @

src/gpu/graphite/DrawAtlas.h

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