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 #ifndef GrDrawOpAtlas_DEFINED 9 #define GrDrawOpAtlas_DEFINED 10 11 #include <cmath> 12 #include <vector> 13 14 #include "include/gpu/GrBackendSurface.h" 15 #include "src/core/SkIPoint16.h" 16 #include "src/gpu/AtlasTypes.h" 17 #include "src/gpu/RectanizerSkyline.h" 18 #include "src/gpu/ganesh/GrDeferredUpload.h" 19 #include "src/gpu/ganesh/GrSurfaceProxyView.h" 20 21 class GrOnFlushResourceProvider; 22 class GrProxyProvider; 23 class GrResourceProvider; 24 class GrTextureProxy; 25 26 /** 27 * This class manages one or more atlas textures on behalf of GrDrawOps. The draw ops that use the 28 * atlas perform texture uploads when preparing their draws during flush. The class provides 29 * facilities for using GrDrawOpUploadToken to detect data hazards. Op's uploads are performed in 30 * "ASAP" mode until it is impossible to add data without overwriting texels read by draws that 31 * have not yet executed on the gpu. At that point, the atlas will attempt to allocate a new 32 * atlas texture (or "page") of the same size, up to a maximum number of textures, and upload 33 * to that texture. If that's not possible, the uploads are performed "inline" between draws. If a 34 * single draw would use enough subimage space to overflow the atlas texture then the atlas will 35 * fail to add a subimage. This gives the op the chance to end the draw and begin a new one. 36 * Additional uploads will then succeed in inline mode. 37 * 38 * When the atlas has multiple pages, new uploads are prioritized to the lower index pages, i.e., 39 * it will try to upload to page 0 before page 1 or 2. To keep the atlas from continually using 40 * excess space, periodic garbage collection is needed to shift data from the higher index pages to 41 * the lower ones, and then eventually remove any pages that are no longer in use. "In use" is 42 * determined by using the GrDrawUploadToken system: After a flush each subarea of the page 43 * is checked to see whether it was used in that flush. If less than a quarter of the plots have 44 * been used recently (within kPlotRecentlyUsedCount iterations) and there are available 45 * plots in lower index pages, the higher index page will be deactivated, and its glyphs will 46 * gradually migrate to other pages via the usual upload system. 47 * 48 * Garbage collection is initiated by the GrDrawOpAtlas's client via the compact() method. One 49 * solution is to make the client a subclass of GrOnFlushCallbackObject, register it with the 50 * GrContext via addOnFlushCallbackObject(), and the client's postFlush() method calls compact() 51 * and passes in the given GrDrawUploadToken. 52 */ 53 class GrDrawOpAtlas { 54 public: 55 /** Is the atlas allowed to use more than one texture? */ 56 enum class AllowMultitexturing : bool { kNo, kYes }; 57 58 /** 59 * Returns a GrDrawOpAtlas. This function can be called anywhere, but the returned atlas 60 * should only be used inside of GrMeshDrawOp::onPrepareDraws. 61 * @param proxyProvider Used to create the atlas's texture proxies. 62 * @param format Backend format for the atlas's textures. 63 * Should be compatible with ct. 64 * @param ct The colorType which this atlas will store. 65 * @param bpp Size in bytes of each pixel. 66 * @param width Width in pixels of the atlas. 67 * @param height Height in pixels of the atlas. 68 * @param plotWidth The width of each plot. width/plotWidth should be an integer. 69 * @param plotWidth The height of each plot. height/plotHeight should be an integer. 70 * @param generationCounter A pointer to the context's generation counter. 71 * @param allowMultitexturing Can the atlas use more than one texture. 72 * @param evictor A pointer to an eviction callback class. 73 * @param label A label for the atlas texture. 74 * 75 * @return An initialized DrawAtlas, or nullptr if creation fails. 76 */ 77 static std::unique_ptr<GrDrawOpAtlas> Make(GrProxyProvider* proxyProvider, 78 const GrBackendFormat& format, 79 SkColorType ct, size_t bpp, 80 int width, int height, 81 int plotWidth, int plotHeight, 82 skgpu::AtlasGenerationCounter* generationCounter, 83 AllowMultitexturing allowMultitexturing, 84 skgpu::PlotEvictionCallback* evictor, 85 std::string_view label); 86 87 /** 88 * Adds a width x height subimage to the atlas. Upon success it returns 'kSucceeded' and returns 89 * the ID and the subimage's coordinates in the backing texture. 'kTryAgain' is returned if 90 * the subimage cannot fit in the atlas without overwriting texels that will be read in the 91 * current draw. This indicates that the op should end its current draw and begin another 92 * before adding more data. Upon success, an upload of the provided image data will have 93 * been added to the GrDrawOp::Target, in "asap" mode if possible, otherwise in "inline" mode. 94 * Successive uploads in either mode may be consolidated. 95 * 'kError' will be returned when some unrecoverable error was encountered while trying to 96 * add the subimage. In this case the op being created should be discarded. 97 * 98 * NOTE: When the GrDrawOp prepares a draw that reads from the atlas, it must immediately call 99 * 'setLastUseToken' with the currentToken from the GrDrawOp::Target, otherwise the next call to 100 * addToAtlas might cause the previous data to be overwritten before it has been read. 101 */ 102 103 enum class ErrorCode { 104 kError, 105 kSucceeded, 106 kTryAgain 107 }; 108 109 ErrorCode addToAtlas(GrResourceProvider*, GrDeferredUploadTarget*, 110 int width, int height, const void* image, skgpu::AtlasLocator*); 111 getViews()112 const GrSurfaceProxyView* getViews() const { return fViews; } 113 atlasGeneration()114 uint64_t atlasGeneration() const { return fAtlasGeneration; } 115 hasID(const skgpu::PlotLocator & plotLocator)116 bool hasID(const skgpu::PlotLocator& plotLocator) { 117 if (!plotLocator.isValid()) { 118 return false; 119 } 120 121 uint32_t plot = plotLocator.plotIndex(); 122 uint32_t page = plotLocator.pageIndex(); 123 uint64_t plotGeneration = fPages[page].fPlotArray[plot]->genID(); 124 uint64_t locatorGeneration = plotLocator.genID(); 125 return plot < fNumPlots && page < fNumActivePages && plotGeneration == locatorGeneration; 126 } 127 128 /** To ensure the atlas does not evict a given entry, the client must set the last use token. */ setLastUseToken(const skgpu::AtlasLocator & atlasLocator,skgpu::AtlasToken token)129 void setLastUseToken(const skgpu::AtlasLocator& atlasLocator, skgpu::AtlasToken token) { 130 SkASSERT(this->hasID(atlasLocator.plotLocator())); 131 uint32_t plotIdx = atlasLocator.plotIndex(); 132 SkASSERT(plotIdx < fNumPlots); 133 uint32_t pageIdx = atlasLocator.pageIndex(); 134 SkASSERT(pageIdx < fNumActivePages); 135 skgpu::Plot* plot = fPages[pageIdx].fPlotArray[plotIdx].get(); 136 this->makeMRU(plot, pageIdx); 137 plot->setLastUseToken(token); 138 } 139 numActivePages()140 uint32_t numActivePages() { return fNumActivePages; } 141 setLastUseTokenBulk(const skgpu::BulkUsePlotUpdater & updater,skgpu::AtlasToken token)142 void setLastUseTokenBulk(const skgpu::BulkUsePlotUpdater& updater, 143 skgpu::AtlasToken token) { 144 int count = updater.count(); 145 for (int i = 0; i < count; i++) { 146 const skgpu::BulkUsePlotUpdater::PlotData& pd = updater.plotData(i); 147 // it's possible we've added a plot to the updater and subsequently the plot's page 148 // was deleted -- so we check to prevent a crash 149 if (pd.fPageIndex < fNumActivePages) { 150 skgpu::Plot* plot = fPages[pd.fPageIndex].fPlotArray[pd.fPlotIndex].get(); 151 this->makeMRU(plot, pd.fPageIndex); 152 plot->setLastUseToken(token); 153 } 154 } 155 } 156 157 void compact(skgpu::AtlasToken startTokenForNextFlush); 158 159 void instantiate(GrOnFlushResourceProvider*); 160 maxPages()161 uint32_t maxPages() const { 162 return fMaxPages; 163 } 164 165 int numAllocated_TestingOnly() const; 166 void setMaxPages_TestingOnly(uint32_t maxPages); 167 168 private: 169 GrDrawOpAtlas(GrProxyProvider*, const GrBackendFormat& format, SkColorType, size_t bpp, 170 int width, int height, int plotWidth, int plotHeight, 171 skgpu::AtlasGenerationCounter* generationCounter, 172 AllowMultitexturing allowMultitexturing, std::string_view label); 173 174 inline bool updatePlot(GrDeferredUploadTarget*, skgpu::AtlasLocator*, skgpu::Plot*); 175 makeMRU(skgpu::Plot * plot,int pageIdx)176 inline void makeMRU(skgpu::Plot* plot, int pageIdx) { 177 if (fPages[pageIdx].fPlotList.head() == plot) { 178 return; 179 } 180 181 fPages[pageIdx].fPlotList.remove(plot); 182 fPages[pageIdx].fPlotList.addToHead(plot); 183 184 // No MRU update for pages -- since we will always try to add from 185 // the front and remove from the back there is no need for MRU. 186 } 187 188 bool uploadToPage(unsigned int pageIdx, GrDeferredUploadTarget*, int width, int height, 189 const void* image, skgpu::AtlasLocator*); 190 191 void uploadPlotToTexture(GrDeferredTextureUploadWritePixelsFn& writePixels, 192 GrTextureProxy* proxy, 193 skgpu::Plot* plot); 194 195 bool createPages(GrProxyProvider*, skgpu::AtlasGenerationCounter*); 196 bool activateNewPage(GrResourceProvider*); 197 void deactivateLastPage(); 198 199 void processEviction(skgpu::PlotLocator); processEvictionAndResetRects(skgpu::Plot * plot)200 inline void processEvictionAndResetRects(skgpu::Plot* plot) { 201 this->processEviction(plot->plotLocator()); 202 plot->resetRects(); 203 } 204 205 GrBackendFormat fFormat; 206 SkColorType fColorType; 207 size_t fBytesPerPixel; 208 int fTextureWidth; 209 int fTextureHeight; 210 int fPlotWidth; 211 int fPlotHeight; 212 unsigned int fNumPlots; 213 const std::string fLabel; 214 215 // A counter to track the atlas eviction state for Glyphs. Each Glyph has a PlotLocator 216 // which contains its current generation. When the atlas evicts a plot, it increases 217 // the generation counter. If a Glyph's generation is less than the atlas's 218 // generation, then it knows it's been evicted and is either free to be deleted or 219 // re-added to the atlas if necessary. 220 skgpu::AtlasGenerationCounter* const fGenerationCounter; 221 uint64_t fAtlasGeneration; 222 223 // nextFlushToken() value at the end of the previous flush 224 skgpu::AtlasToken fPrevFlushToken; 225 226 // the number of flushes since this atlas has been last used 227 int fFlushesSinceLastUse; 228 229 std::vector<skgpu::PlotEvictionCallback*> fEvictionCallbacks; 230 231 struct Page { 232 // allocated array of Plots 233 std::unique_ptr<sk_sp<skgpu::Plot>[]> fPlotArray; 234 // LRU list of Plots (MRU at head - LRU at tail) 235 skgpu::PlotList fPlotList; 236 }; 237 // proxies kept separate to make it easier to pass them up to client 238 GrSurfaceProxyView fViews[skgpu::PlotLocator::kMaxMultitexturePages]; 239 Page fPages[skgpu::PlotLocator::kMaxMultitexturePages]; 240 uint32_t fMaxPages; 241 242 uint32_t fNumActivePages; 243 244 SkDEBUGCODE(void validate(const skgpu::AtlasLocator& atlasLocator) const;) 245 }; 246 247 // There are three atlases (A8, 565, ARGB) that are kept in relation with one another. In 248 // general, because A8 is the most frequently used mask format its dimensions are 2x the 565 and 249 // ARGB dimensions, with the constraint that an atlas size will always contain at least one plot. 250 // Since the ARGB atlas takes the most space, its dimensions are used to size the other two atlases. 251 class GrDrawOpAtlasConfig { 252 public: 253 // The capabilities of the GPU define maxTextureSize. The client provides maxBytes, and this 254 // represents the largest they want a single atlas texture to be. Due to multitexturing, we 255 // may expand temporarily to use more space as needed. 256 GrDrawOpAtlasConfig(int maxTextureSize, size_t maxBytes); 257 258 // For testing only - make minimum sized atlases -- a single plot for ARGB, four for A8 GrDrawOpAtlasConfig()259 GrDrawOpAtlasConfig() : GrDrawOpAtlasConfig(kMaxAtlasDim, 0) {} 260 261 SkISize atlasDimensions(skgpu::MaskFormat type) const; 262 SkISize plotDimensions(skgpu::MaskFormat type) const; 263 264 private: 265 // On some systems texture coordinates are represented using half-precision floating point 266 // with 11 significant bits, which limits the largest atlas dimensions to 2048x2048. 267 // For simplicity we'll use this constraint for all of our atlas textures. 268 // This can be revisited later if we need larger atlases. 269 inline static constexpr int kMaxAtlasDim = 2048; 270 271 SkISize fARGBDimensions; 272 int fMaxTextureSize; 273 }; 274 275 #endif 276