Home | History | Annotate | Download | only in gpu
      1 /*
      2  * Copyright 2011 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 GrGpu_DEFINED
      9 #define GrGpu_DEFINED
     10 
     11 #include "GrCaps.h"
     12 #include "GrGpuCommandBuffer.h"
     13 #include "GrProgramDesc.h"
     14 #include "GrSwizzle.h"
     15 #include "GrAllocator.h"
     16 #include "GrTextureProducer.h"
     17 #include "GrTypes.h"
     18 #include "GrXferProcessor.h"
     19 #include "SkPath.h"
     20 #include "SkTArray.h"
     21 #include <map>
     22 
     23 class GrBackendRenderTarget;
     24 class GrBackendSemaphore;
     25 class GrBuffer;
     26 class GrContext;
     27 struct GrContextOptions;
     28 class GrGLContext;
     29 class GrMesh;
     30 class GrPath;
     31 class GrPathRange;
     32 class GrPathRenderer;
     33 class GrPathRendererChain;
     34 class GrPathRendering;
     35 class GrPipeline;
     36 class GrPrimitiveProcessor;
     37 class GrRenderTarget;
     38 class GrSemaphore;
     39 class GrStencilAttachment;
     40 class GrStencilSettings;
     41 class GrSurface;
     42 class GrTexture;
     43 class SkJSONWriter;
     44 
     45 class GrGpu : public SkRefCnt {
     46 public:
     47     /**
     48      * Create an instance of GrGpu that matches the specified backend. If the requested backend is
     49      * not supported (at compile-time or run-time) this returns nullptr. The context will not be
     50      * fully constructed and should not be used by GrGpu until after this function returns.
     51      */
     52     static sk_sp<GrGpu> Make(GrBackend, GrBackendContext, const GrContextOptions&, GrContext*);
     53 
     54     ////////////////////////////////////////////////////////////////////////////
     55 
     56     GrGpu(GrContext* context);
     57     ~GrGpu() override;
     58 
     59     GrContext* getContext() { return fContext; }
     60     const GrContext* getContext() const { return fContext; }
     61 
     62     /**
     63      * Gets the capabilities of the draw target.
     64      */
     65     const GrCaps* caps() const { return fCaps.get(); }
     66     sk_sp<const GrCaps> refCaps() const { return fCaps; }
     67 
     68     GrPathRendering* pathRendering() { return fPathRendering.get();  }
     69 
     70     enum class DisconnectType {
     71         // No cleanup should be attempted, immediately cease making backend API calls
     72         kAbandon,
     73         // Free allocated resources (not known by GrResourceCache) before returning and
     74         // ensure no backend backend 3D API calls will be made after disconnect() returns.
     75         kCleanup,
     76     };
     77 
     78     // Called by GrContext when the underlying backend context is already or will be destroyed
     79     // before GrContext.
     80     virtual void disconnect(DisconnectType);
     81 
     82     /**
     83      * The GrGpu object normally assumes that no outsider is setting state
     84      * within the underlying 3D API's context/device/whatever. This call informs
     85      * the GrGpu that the state was modified and it shouldn't make assumptions
     86      * about the state.
     87      */
     88     void markContextDirty(uint32_t state = kAll_GrBackendState) { fResetBits |= state; }
     89 
     90     /**
     91      * Creates a texture object. If kRenderTarget_GrSurfaceFlag the texture can
     92      * be used as a render target by calling GrTexture::asRenderTarget(). Not all
     93      * pixel configs can be used as render targets. Support for configs as textures
     94      * or render targets can be checked using GrCaps.
     95      *
     96      * @param desc        describes the texture to be created.
     97      * @param budgeted    does this texture count against the resource cache budget?
     98      * @param texels      array of mipmap levels containing texel data to load.
     99      *                    Each level begins with full-size palette data for paletted textures.
    100      *                    It contains width*height texels. If there is only one
    101      *                    element and it contains nullptr fPixels, texture data is
    102      *                    uninitialized.
    103      * @param mipLevelCount the number of levels in 'texels'
    104      * @return    The texture object if successful, otherwise nullptr.
    105      */
    106     sk_sp<GrTexture> createTexture(const GrSurfaceDesc&, SkBudgeted,
    107                                    const GrMipLevel texels[], int mipLevelCount);
    108 
    109     /**
    110      * Simplified createTexture() interface for when there is no initial texel data to upload.
    111      */
    112     sk_sp<GrTexture> createTexture(const GrSurfaceDesc& desc, SkBudgeted);
    113 
    114     /**
    115      * Implements GrResourceProvider::wrapBackendTexture
    116      */
    117     sk_sp<GrTexture> wrapBackendTexture(const GrBackendTexture&, GrWrapOwnership);
    118 
    119     /**
    120      * Implements GrResourceProvider::wrapRenderableBackendTexture
    121      */
    122     sk_sp<GrTexture> wrapRenderableBackendTexture(const GrBackendTexture&,
    123                                                   int sampleCnt, GrWrapOwnership);
    124 
    125     /**
    126      * Implements GrResourceProvider::wrapBackendRenderTarget
    127      */
    128     sk_sp<GrRenderTarget> wrapBackendRenderTarget(const GrBackendRenderTarget&);
    129 
    130     /**
    131      * Implements GrResourceProvider::wrapBackendTextureAsRenderTarget
    132      */
    133     sk_sp<GrRenderTarget> wrapBackendTextureAsRenderTarget(const GrBackendTexture&,
    134                                                            int sampleCnt);
    135 
    136     /**
    137      * Creates a buffer in GPU memory. For a client-side buffer use GrBuffer::CreateCPUBacked.
    138      *
    139      * @param size            size of buffer to create.
    140      * @param intendedType    hint to the graphics subsystem about what the buffer will be used for.
    141      * @param accessPattern   hint to the graphics subsystem about how the data will be accessed.
    142      * @param data            optional data with which to initialize the buffer.
    143      *
    144      * @return the buffer if successful, otherwise nullptr.
    145      */
    146     GrBuffer* createBuffer(size_t size, GrBufferType intendedType, GrAccessPattern accessPattern,
    147                            const void* data = nullptr);
    148 
    149     /**
    150      * Resolves MSAA.
    151      */
    152     void resolveRenderTarget(GrRenderTarget*, GrSurfaceOrigin);
    153 
    154     /** Info struct returned by getReadPixelsInfo about performing intermediate draws before
    155         reading pixels for performance or correctness. */
    156     struct ReadPixelTempDrawInfo {
    157         /** If the GrGpu is requesting that the caller do a draw to an intermediate surface then
    158             this is descriptor for the temp surface. The draw should always be a rect with
    159             dst 0,0,w,h. */
    160         GrSurfaceDesc   fTempSurfaceDesc;
    161         /** Indicates whether there is a performance advantage to using an exact match texture
    162             (in terms of width and height) for the intermediate texture instead of approximate. */
    163         SkBackingFit    fTempSurfaceFit;
    164         /** Swizzle to apply during the draw. This is used to compensate for either feature or
    165             performance limitations in the underlying 3D API. */
    166         GrSwizzle       fSwizzle;
    167         /** The config that should be used to read from the temp surface after the draw. This may be
    168             different than the original read config in order to compensate for swizzling. The
    169             read data will effectively be in the original read config. */
    170         GrPixelConfig   fReadConfig;
    171     };
    172 
    173     /** Describes why an intermediate draw must/should be performed before readPixels. */
    174     enum DrawPreference {
    175         /** On input means that the caller would proceed without draw if the GrGpu doesn't request
    176             one.
    177             On output means that the GrGpu is not requesting a draw. */
    178         kNoDraw_DrawPreference,
    179         /** Means that the client would prefer a draw for performance of the readback but
    180             can satisfy a straight readPixels call on the inputs without an intermediate draw.
    181             getReadPixelsInfo will never set the draw preference to this value but may leave
    182             it set. */
    183         kCallerPrefersDraw_DrawPreference,
    184         /** On output means that GrGpu would prefer a draw for performance of the readback but
    185             can satisfy a straight readPixels call on the inputs without an intermediate draw. The
    186             caller of getReadPixelsInfo should never specify this on intput. */
    187         kGpuPrefersDraw_DrawPreference,
    188         /** On input means that the caller requires a draw to do a transformation and there is no
    189             CPU fallback.
    190             On output means that GrGpu can only satisfy the readPixels request if the intermediate
    191             draw is performed.
    192           */
    193         kRequireDraw_DrawPreference
    194     };
    195 
    196     /**
    197      * Used to negotiate whether and how an intermediate draw should or must be performed before
    198      * a readPixels call. If this returns false then GrGpu could not deduce an intermediate draw
    199      * that would allow a successful readPixels call. The passed width, height, and rowBytes,
    200      * must be non-zero and already reflect clipping to the src bounds.
    201      */
    202     bool getReadPixelsInfo(GrSurface* srcSurface, GrSurfaceOrigin srcOrigin,
    203                            int readWidth, int readHeight, size_t rowBytes,
    204                            GrPixelConfig readConfig, DrawPreference*, ReadPixelTempDrawInfo*);
    205 
    206     /** Info struct returned by getWritePixelsInfo about performing an intermediate draw in order
    207         to write pixels to a GrSurface for either performance or correctness reasons. */
    208     struct WritePixelTempDrawInfo {
    209         /** If the GrGpu is requesting that the caller upload to an intermediate surface and draw
    210             that to the dst then this is the descriptor for the intermediate surface. The caller
    211             should upload the pixels such that the upper left pixel of the upload rect is at 0,0 in
    212             the intermediate surface.*/
    213         GrSurfaceDesc   fTempSurfaceDesc;
    214         /** Swizzle to apply during the draw. This is used to compensate for either feature or
    215             performance limitations in the underlying 3D API. */
    216         GrSwizzle       fSwizzle;
    217         /** The config that should be specified when uploading the *original* data to the temp
    218             surface before the draw. This may be different than the original src data config in
    219             order to compensate for swizzling that will occur when drawing. */
    220         GrPixelConfig   fWriteConfig;
    221     };
    222 
    223     /**
    224      * Used to negotiate whether and how an intermediate surface should be used to write pixels to
    225      * a GrSurface. If this returns false then GrGpu could not deduce an intermediate draw
    226      * that would allow a successful transfer of the src pixels to the dst. The passed width,
    227      * height, and rowBytes, must be non-zero and already reflect clipping to the dst bounds.
    228      */
    229     bool getWritePixelsInfo(GrSurface* dstSurface, GrSurfaceOrigin dstOrigin, int width, int height,
    230                             GrPixelConfig srcConfig, DrawPreference*, WritePixelTempDrawInfo*);
    231 
    232     /**
    233      * Reads a rectangle of pixels from a render target.
    234      *
    235      * @param surface       The surface to read from
    236      * @param left          left edge of the rectangle to read (inclusive)
    237      * @param top           top edge of the rectangle to read (inclusive)
    238      * @param width         width of rectangle to read in pixels.
    239      * @param height        height of rectangle to read in pixels.
    240      * @param config        the pixel config of the destination buffer
    241      * @param buffer        memory to read the rectangle into.
    242      * @param rowBytes      the number of bytes between consecutive rows. Zero
    243      *                      means rows are tightly packed.
    244      * @param invertY       buffer should be populated bottom-to-top as opposed
    245      *                      to top-to-bottom (skia's usual order)
    246      *
    247      * @return true if the read succeeded, false if not. The read can fail
    248      *              because of a unsupported pixel config or because no render
    249      *              target is currently set.
    250      */
    251     bool readPixels(GrSurface* surface, GrSurfaceOrigin,
    252                     int left, int top, int width, int height,
    253                     GrPixelConfig config, void* buffer, size_t rowBytes);
    254 
    255     /**
    256      * Updates the pixels in a rectangle of a surface.
    257      *
    258      * @param surface       The surface to write to.
    259      * @param left          left edge of the rectangle to write (inclusive)
    260      * @param top           top edge of the rectangle to write (inclusive)
    261      * @param width         width of rectangle to write in pixels.
    262      * @param height        height of rectangle to write in pixels.
    263      * @param config        the pixel config of the source buffer
    264      * @param texels        array of mipmap levels containing texture data
    265      * @param mipLevelCount number of levels in 'texels'
    266      */
    267     bool writePixels(GrSurface* surface, GrSurfaceOrigin origin,
    268                      int left, int top, int width, int height,
    269                      GrPixelConfig config,
    270                      const GrMipLevel texels[], int mipLevelCount);
    271 
    272     /**
    273      * This function is a shim which creates a SkTArray<GrMipLevel> of size 1.
    274      * It then calls writePixels with that SkTArray.
    275      *
    276      * @param buffer   memory to read pixels from.
    277      * @param rowBytes number of bytes between consecutive rows. Zero
    278      *                 means rows are tightly packed.
    279      */
    280     bool writePixels(GrSurface* surface, GrSurfaceOrigin origin,
    281                      int left, int top, int width, int height,
    282                      GrPixelConfig config, const void* buffer,
    283                      size_t rowBytes);
    284 
    285     /**
    286      * Updates the pixels in a rectangle of a texture using a buffer
    287      *
    288      * There are a couple of assumptions here. First, we only update the top miplevel.
    289      * And second, that any y flip needed has already been done in the buffer.
    290      *
    291      * @param texture          The texture to write to.
    292      * @param left             left edge of the rectangle to write (inclusive)
    293      * @param top              top edge of the rectangle to write (inclusive)
    294      * @param width            width of rectangle to write in pixels.
    295      * @param height           height of rectangle to write in pixels.
    296      * @param config           the pixel config of the source buffer
    297      * @param transferBuffer   GrBuffer to read pixels from (type must be "kXferCpuToGpu")
    298      * @param offset           offset from the start of the buffer
    299      * @param rowBytes         number of bytes between consecutive rows in the buffer. Zero
    300      *                         means rows are tightly packed.
    301      */
    302     bool transferPixels(GrTexture* texture,
    303                         int left, int top, int width, int height,
    304                         GrPixelConfig config, GrBuffer* transferBuffer,
    305                         size_t offset, size_t rowBytes);
    306 
    307     // After the client interacts directly with the 3D context state the GrGpu
    308     // must resync its internal state and assumptions about 3D context state.
    309     // Each time this occurs the GrGpu bumps a timestamp.
    310     // state of the 3D context
    311     // At 10 resets / frame and 60fps a 64bit timestamp will overflow in about
    312     // a billion years.
    313     typedef uint64_t ResetTimestamp;
    314 
    315     // This timestamp is always older than the current timestamp
    316     static const ResetTimestamp kExpiredTimestamp = 0;
    317     // Returns a timestamp based on the number of times the context was reset.
    318     // This timestamp can be used to lazily detect when cached 3D context state
    319     // is dirty.
    320     ResetTimestamp getResetTimestamp() const { return fResetTimestamp; }
    321 
    322     // Called to perform a surface to surface copy. Fallbacks to issuing a draw from the src to dst
    323     // take place at the GrOpList level and this function implement faster copy paths. The rect
    324     // and point are pre-clipped. The src rect and implied dst rect are guaranteed to be within the
    325     // src/dst bounds and non-empty. If canDiscardOutsideDstRect is set to true then we don't need
    326     // to preserve any data on the dst surface outside of the copy.
    327     bool copySurface(GrSurface* dst, GrSurfaceOrigin dstOrigin,
    328                      GrSurface* src, GrSurfaceOrigin srcOrigin,
    329                      const SkIRect& srcRect,
    330                      const SkIPoint& dstPoint,
    331                      bool canDiscardOutsideDstRect = false);
    332 
    333     struct MultisampleSpecs {
    334         MultisampleSpecs(uint8_t uniqueID, int effectiveSampleCnt, const SkPoint* locations)
    335             : fUniqueID(uniqueID),
    336               fEffectiveSampleCnt(effectiveSampleCnt),
    337               fSampleLocations(locations) {}
    338 
    339         // Nonzero ID that uniquely identifies these multisample specs.
    340         uint8_t          fUniqueID;
    341         // The actual number of samples the GPU will run. NOTE: this value can be greater than the
    342         // the render target's sample count.
    343         int              fEffectiveSampleCnt;
    344         // If sample locations are supported, points to the subpixel locations at which the GPU will
    345         // sample. Pixel center is at (.5, .5), and (0, 0) indicates the top left corner.
    346         const SkPoint*   fSampleLocations;
    347     };
    348 
    349     // Finds a render target's multisample specs. The pipeline is only needed in case we need to
    350     // flush the draw state prior to querying multisample info. The pipeline is not expected to
    351     // affect the multisample information itself.
    352     const MultisampleSpecs& queryMultisampleSpecs(const GrPipeline&);
    353 
    354     // Finds the multisample specs with a given unique id.
    355     const MultisampleSpecs& getMultisampleSpecs(uint8_t uniqueID) {
    356         SkASSERT(uniqueID > 0 && uniqueID < fMultisampleSpecs.count());
    357         return fMultisampleSpecs[uniqueID];
    358     }
    359 
    360     // Creates a GrGpuRTCommandBuffer which GrOpLists send draw commands to instead of directly
    361     // to the Gpu object.
    362     virtual GrGpuRTCommandBuffer* createCommandBuffer(
    363             GrRenderTarget*, GrSurfaceOrigin,
    364             const GrGpuRTCommandBuffer::LoadAndStoreInfo&,
    365             const GrGpuRTCommandBuffer::StencilLoadAndStoreInfo&) = 0;
    366 
    367     // Creates a GrGpuTextureCommandBuffer which GrOpLists send texture commands to instead of
    368     // directly to the Gpu object.
    369     virtual GrGpuTextureCommandBuffer* createCommandBuffer(GrTexture*, GrSurfaceOrigin) = 0;
    370 
    371     // Called by GrDrawingManager when flushing.
    372     // Provides a hook for post-flush actions (e.g. Vulkan command buffer submits). This will also
    373     // insert any numSemaphore semaphores on the gpu and set the backendSemaphores to match the
    374     // inserted semaphores.
    375     GrSemaphoresSubmitted finishFlush(int numSemaphores, GrBackendSemaphore backendSemaphores[]);
    376 
    377     virtual GrFence SK_WARN_UNUSED_RESULT insertFence() = 0;
    378     virtual bool waitFence(GrFence, uint64_t timeout = 1000) = 0;
    379     virtual void deleteFence(GrFence) const = 0;
    380 
    381     virtual sk_sp<GrSemaphore> SK_WARN_UNUSED_RESULT makeSemaphore(bool isOwned = true) = 0;
    382     virtual sk_sp<GrSemaphore> wrapBackendSemaphore(const GrBackendSemaphore& semaphore,
    383                                                     GrResourceProvider::SemaphoreWrapType wrapType,
    384                                                     GrWrapOwnership ownership) = 0;
    385     virtual void insertSemaphore(sk_sp<GrSemaphore> semaphore, bool flush = false) = 0;
    386     virtual void waitSemaphore(sk_sp<GrSemaphore> semaphore) = 0;
    387 
    388     /**
    389      *  Put this texture in a safe and known state for use across multiple GrContexts. Depending on
    390      *  the backend, this may return a GrSemaphore. If so, other contexts should wait on that
    391      *  semaphore before using this texture.
    392      */
    393     virtual sk_sp<GrSemaphore> prepareTextureForCrossContextUsage(GrTexture*) = 0;
    394 
    395     ///////////////////////////////////////////////////////////////////////////
    396     // Debugging and Stats
    397 
    398     class Stats {
    399     public:
    400 #if GR_GPU_STATS
    401         Stats() { this->reset(); }
    402 
    403         void reset() {
    404             fRenderTargetBinds = 0;
    405             fShaderCompilations = 0;
    406             fTextureCreates = 0;
    407             fTextureUploads = 0;
    408             fTransfersToTexture = 0;
    409             fStencilAttachmentCreates = 0;
    410             fNumDraws = 0;
    411             fNumFailedDraws = 0;
    412         }
    413 
    414         int renderTargetBinds() const { return fRenderTargetBinds; }
    415         void incRenderTargetBinds() { fRenderTargetBinds++; }
    416         int shaderCompilations() const { return fShaderCompilations; }
    417         void incShaderCompilations() { fShaderCompilations++; }
    418         int textureCreates() const { return fTextureCreates; }
    419         void incTextureCreates() { fTextureCreates++; }
    420         int textureUploads() const { return fTextureUploads; }
    421         void incTextureUploads() { fTextureUploads++; }
    422         int transfersToTexture() const { return fTransfersToTexture; }
    423         void incTransfersToTexture() { fTransfersToTexture++; }
    424         void incStencilAttachmentCreates() { fStencilAttachmentCreates++; }
    425         void incNumDraws() { fNumDraws++; }
    426         void incNumFailedDraws() { ++fNumFailedDraws; }
    427         void dump(SkString*);
    428         void dumpKeyValuePairs(SkTArray<SkString>* keys, SkTArray<double>* values);
    429         int numDraws() const { return fNumDraws; }
    430         int numFailedDraws() const { return fNumFailedDraws; }
    431     private:
    432         int fRenderTargetBinds;
    433         int fShaderCompilations;
    434         int fTextureCreates;
    435         int fTextureUploads;
    436         int fTransfersToTexture;
    437         int fStencilAttachmentCreates;
    438         int fNumDraws;
    439         int fNumFailedDraws;
    440 #else
    441         void dump(SkString*) {}
    442         void dumpKeyValuePairs(SkTArray<SkString>*, SkTArray<double>*) {}
    443         void incRenderTargetBinds() {}
    444         void incShaderCompilations() {}
    445         void incTextureCreates() {}
    446         void incTextureUploads() {}
    447         void incTransfersToTexture() {}
    448         void incStencilAttachmentCreates() {}
    449         void incNumDraws() {}
    450         void incNumFailedDraws() {}
    451 #endif
    452     };
    453 
    454     Stats* stats() { return &fStats; }
    455     void dumpJSON(SkJSONWriter*) const;
    456 
    457     /** Creates a texture directly in the backend API without wrapping it in a GrTexture. This is
    458         only to be used for testing (particularly for testing the methods that import an externally
    459         created texture into Skia. Must be matched with a call to deleteTestingOnlyTexture(). */
    460     virtual GrBackendTexture createTestingOnlyBackendTexture(
    461                                                       void* pixels, int w, int h,
    462                                                       GrPixelConfig config,
    463                                                       bool isRenderTarget,
    464                                                       GrMipMapped mipMapped) = 0;
    465     /** Check a handle represents an actual texture in the backend API that has not been freed. */
    466     virtual bool isTestingOnlyBackendTexture(const GrBackendTexture&) const = 0;
    467     /** If ownership of the backend texture has been transferred pass true for abandonTexture. This
    468         will do any necessary cleanup of the handle without freeing the texture in the backend
    469         API. */
    470     virtual void deleteTestingOnlyBackendTexture(GrBackendTexture*,
    471                                                  bool abandonTexture = false) = 0;
    472 
    473     /**
    474      * Flushes all work to the gpu and forces the GPU to wait until all the gpu work has completed.
    475      * This is for testing purposes only.
    476      */
    477     virtual void testingOnly_flushGpuAndSync() = 0;
    478 
    479     // width and height may be larger than rt (if underlying API allows it).
    480     // Returns nullptr if compatible sb could not be created, otherwise the caller owns the ref on
    481     // the GrStencilAttachment.
    482     virtual GrStencilAttachment* createStencilAttachmentForRenderTarget(const GrRenderTarget*,
    483                                                                         int width,
    484                                                                         int height) = 0;
    485     // clears target's entire stencil buffer to 0
    486     virtual void clearStencil(GrRenderTarget* target, int clearValue) = 0;
    487 
    488     // Determines whether a texture will need to be rescaled in order to be used with the
    489     // GrSamplerState. This variation is called when the caller will create a new texture using the
    490     // resource provider from a non-texture src (cpu-backed image, ...).
    491     bool isACopyNeededForTextureParams(int width, int height, const GrSamplerState&,
    492                                        GrTextureProducer::CopyParams*,
    493                                        SkScalar scaleAdjust[2]) const;
    494 
    495     // Like the above but this variation should be called when the caller is not creating the
    496     // original texture but rather was handed the original texture. It adds additional checks
    497     // relevant to original textures that were created external to Skia via
    498     // GrResourceProvider::wrap methods.
    499     bool isACopyNeededForTextureParams(GrTextureProxy* proxy, const GrSamplerState& params,
    500                                        GrTextureProducer::CopyParams* copyParams,
    501                                        SkScalar scaleAdjust[2]) const {
    502         if (this->isACopyNeededForTextureParams(proxy->width(), proxy->height(), params,
    503                                                 copyParams, scaleAdjust)) {
    504             return true;
    505         }
    506         return this->onIsACopyNeededForTextureParams(proxy, params, copyParams, scaleAdjust);
    507     }
    508 
    509     // This is only to be used in GL-specific tests.
    510     virtual const GrGLContext* glContextForTesting() const { return nullptr; }
    511 
    512     // This is only to be used by testing code
    513     virtual void resetShaderCacheForTesting() const {}
    514 
    515     void handleDirtyContext() {
    516         if (fResetBits) {
    517             this->resetContext();
    518         }
    519     }
    520 
    521 protected:
    522     static void ElevateDrawPreference(GrGpu::DrawPreference* preference,
    523                                       GrGpu::DrawPreference elevation) {
    524         GR_STATIC_ASSERT(GrGpu::kCallerPrefersDraw_DrawPreference > GrGpu::kNoDraw_DrawPreference);
    525         GR_STATIC_ASSERT(GrGpu::kGpuPrefersDraw_DrawPreference >
    526                          GrGpu::kCallerPrefersDraw_DrawPreference);
    527         GR_STATIC_ASSERT(GrGpu::kRequireDraw_DrawPreference >
    528                          GrGpu::kGpuPrefersDraw_DrawPreference);
    529         *preference = SkTMax(*preference, elevation);
    530     }
    531 
    532     // Handles cases where a surface will be updated without a call to flushRenderTarget
    533     void didWriteToSurface(GrSurface* surface, const SkIRect* bounds, uint32_t mipLevels = 1) const;
    534 
    535     Stats                            fStats;
    536     std::unique_ptr<GrPathRendering> fPathRendering;
    537     // Subclass must initialize this in its constructor.
    538     sk_sp<const GrCaps>              fCaps;
    539 
    540     typedef SkTArray<SkPoint, true> SamplePattern;
    541 
    542 private:
    543     // called when the 3D context state is unknown. Subclass should emit any
    544     // assumed 3D context state and dirty any state cache.
    545     virtual void onResetContext(uint32_t resetBits) = 0;
    546 
    547     // Called before certain draws in order to guarantee coherent results from dst reads.
    548     virtual void xferBarrier(GrRenderTarget*, GrXferBarrierType) = 0;
    549 
    550     // overridden by backend-specific derived class to create objects.
    551     // Texture size and sample size will have already been validated in base class before
    552     // onCreateTexture is called.
    553     virtual sk_sp<GrTexture> onCreateTexture(const GrSurfaceDesc&, SkBudgeted,
    554                                              const GrMipLevel texels[],
    555                                              int mipLevelCount) = 0;
    556 
    557     virtual sk_sp<GrTexture> onWrapBackendTexture(const GrBackendTexture&, GrWrapOwnership) = 0;
    558     virtual sk_sp<GrTexture> onWrapRenderableBackendTexture(const GrBackendTexture&,
    559                                                             int sampleCnt,
    560                                                             GrWrapOwnership) = 0;
    561     virtual sk_sp<GrRenderTarget> onWrapBackendRenderTarget(const GrBackendRenderTarget&) = 0;
    562     virtual sk_sp<GrRenderTarget> onWrapBackendTextureAsRenderTarget(const GrBackendTexture&,
    563                                                                      int sampleCnt) = 0;
    564     virtual GrBuffer* onCreateBuffer(size_t size, GrBufferType intendedType, GrAccessPattern,
    565                                      const void* data) = 0;
    566 
    567     virtual bool onIsACopyNeededForTextureParams(GrTextureProxy* proxy, const GrSamplerState&,
    568                                                  GrTextureProducer::CopyParams*,
    569                                                  SkScalar scaleAdjust[2]) const {
    570         return false;
    571     }
    572 
    573     virtual bool onGetReadPixelsInfo(GrSurface* srcSurface, GrSurfaceOrigin srcOrigin,
    574                                      int readWidth, int readHeight,
    575                                      size_t rowBytes, GrPixelConfig readConfig, DrawPreference*,
    576                                      ReadPixelTempDrawInfo*) = 0;
    577     virtual bool onGetWritePixelsInfo(GrSurface* dstSurface, GrSurfaceOrigin dstOrigin,
    578                                       int width, int height,
    579                                       GrPixelConfig srcConfig, DrawPreference*,
    580                                       WritePixelTempDrawInfo*) = 0;
    581 
    582     // overridden by backend-specific derived class to perform the surface read
    583     virtual bool onReadPixels(GrSurface*, GrSurfaceOrigin,
    584                               int left, int top,
    585                               int width, int height,
    586                               GrPixelConfig,
    587                               void* buffer,
    588                               size_t rowBytes) = 0;
    589 
    590     // overridden by backend-specific derived class to perform the surface write
    591     virtual bool onWritePixels(GrSurface*, GrSurfaceOrigin,
    592                                int left, int top, int width, int height,
    593                                GrPixelConfig config,
    594                                const GrMipLevel texels[], int mipLevelCount) = 0;
    595 
    596     // overridden by backend-specific derived class to perform the texture transfer
    597     virtual bool onTransferPixels(GrTexture*,
    598                                   int left, int top, int width, int height,
    599                                   GrPixelConfig config, GrBuffer* transferBuffer,
    600                                   size_t offset, size_t rowBytes) = 0;
    601 
    602     // overridden by backend-specific derived class to perform the resolve
    603     virtual void onResolveRenderTarget(GrRenderTarget* target, GrSurfaceOrigin) = 0;
    604 
    605     // overridden by backend specific derived class to perform the copy surface
    606     virtual bool onCopySurface(GrSurface* dst, GrSurfaceOrigin dstOrigin,
    607                                GrSurface* src, GrSurfaceOrigin srcOrigin,
    608                                const SkIRect& srcRect, const SkIPoint& dstPoint,
    609                                bool canDiscardOutsideDstRect) = 0;
    610 
    611     // overridden by backend specific derived class to perform the multisample queries
    612     virtual void onQueryMultisampleSpecs(GrRenderTarget*, GrSurfaceOrigin rtOrigin,
    613                                          const GrStencilSettings&,
    614                                          int* effectiveSampleCnt, SamplePattern*) = 0;
    615 
    616     virtual void onFinishFlush(bool insertedSemaphores) = 0;
    617 
    618     virtual void onDumpJSON(SkJSONWriter*) const {}
    619 
    620     void resetContext() {
    621         this->onResetContext(fResetBits);
    622         fResetBits = 0;
    623         ++fResetTimestamp;
    624     }
    625 
    626     struct SamplePatternComparator {
    627         bool operator()(const SamplePattern&, const SamplePattern&) const;
    628     };
    629 
    630     typedef std::map<SamplePattern, uint8_t, SamplePatternComparator> MultisampleSpecsIdMap;
    631 
    632     ResetTimestamp                         fResetTimestamp;
    633     uint32_t                               fResetBits;
    634     MultisampleSpecsIdMap                  fMultisampleSpecsIdMap;
    635     SkSTArray<1, MultisampleSpecs, true>   fMultisampleSpecs;
    636     // The context owns us, not vice-versa, so this ptr is not ref'ed by Gpu.
    637     GrContext*                             fContext;
    638 
    639     friend class GrPathRendering;
    640     typedef SkRefCnt INHERITED;
    641 };
    642 
    643 #endif
    644