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