Home | History | Annotate | Download | only in gpu
      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 "GrDrawOpAtlas.h"
      9 
     10 #include "GrContext.h"
     11 #include "GrOpFlushState.h"
     12 #include "GrRectanizer.h"
     13 #include "GrResourceProvider.h"
     14 #include "GrTexture.h"
     15 #include "GrTracing.h"
     16 
     17 std::unique_ptr<GrDrawOpAtlas> GrDrawOpAtlas::Make(GrContext* ctx, GrPixelConfig config,
     18                                                    int width, int height,
     19                                                    int numPlotsX, int numPlotsY,
     20                                                    GrDrawOpAtlas::EvictionFunc func,
     21                                                    void* data) {
     22     GrSurfaceDesc desc;
     23     desc.fFlags = kNone_GrSurfaceFlags;
     24     desc.fWidth = width;
     25     desc.fHeight = height;
     26     desc.fConfig = config;
     27 
     28     // We don't want to flush the context so we claim we're in the middle of flushing so as to
     29     // guarantee we do not recieve a texture with pending IO
     30     // TODO: Determine how to avoid having to do this. (https://bug.skia.org/4156)
     31     static const uint32_t kFlags = GrResourceProvider::kNoPendingIO_Flag;
     32     sk_sp<GrTexture> texture(ctx->resourceProvider()->createApproxTexture(desc, kFlags));
     33     if (!texture) {
     34         return nullptr;
     35     }
     36 
     37     // MDB TODO: for now, wrap an instantiated texture. Having the deferred instantiation
     38     // possess the correct properties (e.g., no pendingIO) should fall out of the system but
     39     // should receive special attention.
     40     // Note: When switching over to the deferred proxy, use the kExact flag to create
     41     // the atlas and assert that the width & height are powers of 2.
     42     sk_sp<GrTextureProxy> proxy = GrSurfaceProxy::MakeWrapped(std::move(texture));
     43     if (!proxy) {
     44         return nullptr;
     45     }
     46 
     47     std::unique_ptr<GrDrawOpAtlas> atlas(
     48             new GrDrawOpAtlas(ctx, std::move(proxy), numPlotsX, numPlotsY));
     49     atlas->registerEvictionCallback(func, data);
     50     return atlas;
     51 }
     52 
     53 
     54 ////////////////////////////////////////////////////////////////////////////////
     55 
     56 GrDrawOpAtlas::Plot::Plot(int index, uint64_t genID, int offX, int offY, int width, int height,
     57                           GrPixelConfig config)
     58         : fLastUpload(GrDrawOpUploadToken::AlreadyFlushedToken())
     59         , fLastUse(GrDrawOpUploadToken::AlreadyFlushedToken())
     60         , fIndex(index)
     61         , fGenID(genID)
     62         , fID(CreateId(fIndex, fGenID))
     63         , fData(nullptr)
     64         , fWidth(width)
     65         , fHeight(height)
     66         , fX(offX)
     67         , fY(offY)
     68         , fRects(nullptr)
     69         , fOffset(SkIPoint16::Make(fX * fWidth, fY * fHeight))
     70         , fConfig(config)
     71         , fBytesPerPixel(GrBytesPerPixel(config))
     72 #ifdef SK_DEBUG
     73         , fDirty(false)
     74 #endif
     75 {
     76     fDirtyRect.setEmpty();
     77 }
     78 
     79 GrDrawOpAtlas::Plot::~Plot() {
     80     sk_free(fData);
     81     delete fRects;
     82 }
     83 
     84 bool GrDrawOpAtlas::Plot::addSubImage(int width, int height, const void* image, SkIPoint16* loc) {
     85     SkASSERT(width <= fWidth && height <= fHeight);
     86 
     87     if (!fRects) {
     88         fRects = GrRectanizer::Factory(fWidth, fHeight);
     89     }
     90 
     91     if (!fRects->addRect(width, height, loc)) {
     92         return false;
     93     }
     94 
     95     if (!fData) {
     96         fData = reinterpret_cast<unsigned char*>(sk_calloc_throw(fBytesPerPixel * fWidth *
     97                                                                  fHeight));
     98     }
     99     size_t rowBytes = width * fBytesPerPixel;
    100     const unsigned char* imagePtr = (const unsigned char*)image;
    101     // point ourselves at the right starting spot
    102     unsigned char* dataPtr = fData;
    103     dataPtr += fBytesPerPixel * fWidth * loc->fY;
    104     dataPtr += fBytesPerPixel * loc->fX;
    105     // copy into the data buffer, swizzling as we go if this is ARGB data
    106     if (4 == fBytesPerPixel && kSkia8888_GrPixelConfig == kBGRA_8888_GrPixelConfig) {
    107         for (int i = 0; i < height; ++i) {
    108             SkOpts::RGBA_to_BGRA(reinterpret_cast<uint32_t*>(dataPtr), imagePtr, width);
    109             dataPtr += fBytesPerPixel * fWidth;
    110             imagePtr += rowBytes;
    111         }
    112     } else {
    113         for (int i = 0; i < height; ++i) {
    114             memcpy(dataPtr, imagePtr, rowBytes);
    115             dataPtr += fBytesPerPixel * fWidth;
    116             imagePtr += rowBytes;
    117         }
    118     }
    119 
    120     fDirtyRect.join(loc->fX, loc->fY, loc->fX + width, loc->fY + height);
    121 
    122     loc->fX += fOffset.fX;
    123     loc->fY += fOffset.fY;
    124     SkDEBUGCODE(fDirty = true;)
    125 
    126     return true;
    127 }
    128 
    129 void GrDrawOpAtlas::Plot::uploadToTexture(GrDrawOp::WritePixelsFn& writePixels,
    130                                           GrTexture* texture) {
    131     // We should only be issuing uploads if we are in fact dirty
    132     SkASSERT(fDirty && fData && texture);
    133     TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("skia.gpu"), "GrDrawOpAtlas::Plot::uploadToTexture");
    134     size_t rowBytes = fBytesPerPixel * fWidth;
    135     const unsigned char* dataPtr = fData;
    136     dataPtr += rowBytes * fDirtyRect.fTop;
    137     dataPtr += fBytesPerPixel * fDirtyRect.fLeft;
    138     writePixels(texture, fOffset.fX + fDirtyRect.fLeft, fOffset.fY + fDirtyRect.fTop,
    139                 fDirtyRect.width(), fDirtyRect.height(), fConfig, dataPtr, rowBytes);
    140     fDirtyRect.setEmpty();
    141     SkDEBUGCODE(fDirty = false;)
    142 }
    143 
    144 void GrDrawOpAtlas::Plot::resetRects() {
    145     if (fRects) {
    146         fRects->reset();
    147     }
    148 
    149     fGenID++;
    150     fID = CreateId(fIndex, fGenID);
    151 
    152     // zero out the plot
    153     if (fData) {
    154         sk_bzero(fData, fBytesPerPixel * fWidth * fHeight);
    155     }
    156 
    157     fDirtyRect.setEmpty();
    158     SkDEBUGCODE(fDirty = false;)
    159 }
    160 
    161 ///////////////////////////////////////////////////////////////////////////////
    162 
    163 GrDrawOpAtlas::GrDrawOpAtlas(GrContext* context, sk_sp<GrTextureProxy> proxy,
    164                              int numPlotsX, int numPlotsY)
    165         : fContext(context)
    166         , fProxy(std::move(proxy))
    167         , fAtlasGeneration(kInvalidAtlasGeneration + 1) {
    168     fPlotWidth = fProxy->width() / numPlotsX;
    169     fPlotHeight = fProxy->height() / numPlotsY;
    170     SkASSERT(numPlotsX * numPlotsY <= BulkUseTokenUpdater::kMaxPlots);
    171     SkASSERT(fPlotWidth * numPlotsX == fProxy->width());
    172     SkASSERT(fPlotHeight * numPlotsY == fProxy->height());
    173 
    174     SkDEBUGCODE(fNumPlots = numPlotsX * numPlotsY;)
    175 
    176     // set up allocated plots
    177     fPlotArray.reset(new sk_sp<Plot>[ numPlotsX * numPlotsY ]);
    178 
    179     sk_sp<Plot>* currPlot = fPlotArray.get();
    180     for (int y = numPlotsY - 1, r = 0; y >= 0; --y, ++r) {
    181         for (int x = numPlotsX - 1, c = 0; x >= 0; --x, ++c) {
    182             uint32_t index = r * numPlotsX + c;
    183             currPlot->reset(
    184                     new Plot(index, 1, x, y, fPlotWidth, fPlotHeight, fProxy->config()));
    185 
    186             // build LRU list
    187             fPlotList.addToHead(currPlot->get());
    188             ++currPlot;
    189         }
    190     }
    191 }
    192 
    193 void GrDrawOpAtlas::processEviction(AtlasID id) {
    194     for (int i = 0; i < fEvictionCallbacks.count(); i++) {
    195         (*fEvictionCallbacks[i].fFunc)(id, fEvictionCallbacks[i].fData);
    196     }
    197 }
    198 
    199 inline bool GrDrawOpAtlas::updatePlot(GrDrawOp::Target* target, AtlasID* id, Plot* plot) {
    200     this->makeMRU(plot);
    201 
    202     // If our most recent upload has already occurred then we have to insert a new
    203     // upload. Otherwise, we already have a scheduled upload that hasn't yet ocurred.
    204     // This new update will piggy back on that previously scheduled update.
    205     if (target->hasDrawBeenFlushed(plot->lastUploadToken())) {
    206         // With c+14 we could move sk_sp into lamba to only ref once.
    207         sk_sp<Plot> plotsp(SkRef(plot));
    208 
    209         // MDB TODO: this is currently fine since the atlas' proxy is always pre-instantiated.
    210         // Once it is deferred more care must be taken upon instantiation failure.
    211         if (!fProxy->instantiate(fContext->resourceProvider())) {
    212             return false;
    213         }
    214         GrTexture* texture = fProxy->priv().peekTexture();
    215 
    216         GrDrawOpUploadToken lastUploadToken = target->addAsapUpload(
    217             [plotsp, texture] (GrDrawOp::WritePixelsFn& writePixels) {
    218                 plotsp->uploadToTexture(writePixels, texture);
    219             }
    220         );
    221         plot->setLastUploadToken(lastUploadToken);
    222     }
    223     *id = plot->id();
    224     return true;
    225 }
    226 
    227 bool GrDrawOpAtlas::addToAtlas(AtlasID* id, GrDrawOp::Target* target, int width, int height,
    228                                const void* image, SkIPoint16* loc) {
    229     // We should already have a texture, TODO clean this up
    230     SkASSERT(fProxy);
    231     if (width > fPlotWidth || height > fPlotHeight) {
    232         return false;
    233     }
    234 
    235     // now look through all allocated plots for one we can share, in Most Recently Refed order
    236     PlotList::Iter plotIter;
    237     plotIter.init(fPlotList, PlotList::Iter::kHead_IterStart);
    238     Plot* plot;
    239     while ((plot = plotIter.get())) {
    240         SkASSERT(GrBytesPerPixel(fProxy->config()) == plot->bpp());
    241         if (plot->addSubImage(width, height, image, loc)) {
    242             return this->updatePlot(target, id, plot);
    243         }
    244         plotIter.next();
    245     }
    246 
    247     // If the above fails, then see if the least recently refed plot has already been flushed to the
    248     // gpu
    249     plot = fPlotList.tail();
    250     SkASSERT(plot);
    251     if (target->hasDrawBeenFlushed(plot->lastUseToken())) {
    252         this->processEviction(plot->id());
    253         plot->resetRects();
    254         SkASSERT(GrBytesPerPixel(fProxy->config()) == plot->bpp());
    255         SkDEBUGCODE(bool verify = )plot->addSubImage(width, height, image, loc);
    256         SkASSERT(verify);
    257         if (!this->updatePlot(target, id, plot)) {
    258             return false;
    259         }
    260 
    261         fAtlasGeneration++;
    262         return true;
    263     }
    264 
    265     // If this plot has been used in a draw that is currently being prepared by an op, then we have
    266     // to fail. This gives the op a chance to enqueue the draw, and call back into this function.
    267     // When that draw is enqueued, the draw token advances, and the subsequent call will continue
    268     // past this branch and prepare an inline upload that will occur after the enqueued draw which
    269     // references the plot's pre-upload content.
    270     if (plot->lastUseToken() == target->nextDrawToken()) {
    271         return false;
    272     }
    273 
    274     this->processEviction(plot->id());
    275     fPlotList.remove(plot);
    276     sk_sp<Plot>& newPlot = fPlotArray[plot->index()];
    277     newPlot.reset(plot->clone());
    278 
    279     fPlotList.addToHead(newPlot.get());
    280     SkASSERT(GrBytesPerPixel(fProxy->config()) == newPlot->bpp());
    281     SkDEBUGCODE(bool verify = )newPlot->addSubImage(width, height, image, loc);
    282     SkASSERT(verify);
    283 
    284     // Note that this plot will be uploaded inline with the draws whereas the
    285     // one it displaced most likely was uploaded asap.
    286     // With c+14 we could move sk_sp into lambda to only ref once.
    287     sk_sp<Plot> plotsp(SkRef(newPlot.get()));
    288     // MDB TODO: this is currently fine since the atlas' proxy is always pre-instantiated.
    289     // Once it is deferred more care must be taken upon instantiation failure.
    290     if (!fProxy->instantiate(fContext->resourceProvider())) {
    291         return false;
    292     }
    293     GrTexture* texture = fProxy->priv().peekTexture();
    294 
    295     GrDrawOpUploadToken lastUploadToken = target->addInlineUpload(
    296         [plotsp, texture] (GrDrawOp::WritePixelsFn& writePixels) {
    297             plotsp->uploadToTexture(writePixels, texture);
    298         }
    299     );
    300     newPlot->setLastUploadToken(lastUploadToken);
    301 
    302     *id = newPlot->id();
    303 
    304     fAtlasGeneration++;
    305     return true;
    306 }
    307