Home | History | Annotate | Download | only in gpu
      1 
      2 /*
      3  * Copyright 2011 Google Inc.
      4  *
      5  * Use of this source code is governed by a BSD-style license that can be
      6  * found in the LICENSE file.
      7  */
      8 
      9 
     10 #ifndef GrGpu_DEFINED
     11 #define GrGpu_DEFINED
     12 
     13 #include "GrDrawTarget.h"
     14 #include "GrRect.h"
     15 #include "GrRefCnt.h"
     16 #include "GrClipMaskManager.h"
     17 
     18 #include "SkPath.h"
     19 
     20 class GrContext;
     21 class GrIndexBufferAllocPool;
     22 class GrPath;
     23 class GrPathRenderer;
     24 class GrPathRendererChain;
     25 class GrResource;
     26 class GrStencilBuffer;
     27 class GrVertexBufferAllocPool;
     28 
     29 class GrGpu : public GrDrawTarget {
     30 
     31 public:
     32 
     33     /**
     34      * Additional blend coefficients for dual source blending, not exposed
     35      * through GrPaint/GrContext.
     36      */
     37     enum ExtendedBlendCoeffs {
     38         // source 2 refers to second output color when
     39         // using dual source blending.
     40         kS2C_GrBlendCoeff = kPublicGrBlendCoeffCount,
     41         kIS2C_GrBlendCoeff,
     42         kS2A_GrBlendCoeff,
     43         kIS2A_GrBlendCoeff,
     44 
     45         kTotalGrBlendCoeffCount
     46     };
     47 
     48     /**
     49      * Create an instance of GrGpu that matches the specified backend. If the requested backend is
     50      * not supported (at compile-time or run-time) this returns NULL.
     51      */
     52     static GrGpu* Create(GrBackend, GrBackendContext);
     53 
     54     ////////////////////////////////////////////////////////////////////////////
     55 
     56     GrGpu();
     57     virtual ~GrGpu();
     58 
     59     // The GrContext sets itself as the owner of this Gpu object
     60     void setContext(GrContext* context) {
     61         GrAssert(NULL == fContext);
     62         fContext = context;
     63         fClipMaskManager.setContext(context);
     64     }
     65     GrContext* getContext() { return fContext; }
     66     const GrContext* getContext() const { return fContext; }
     67 
     68     /**
     69      * The GrGpu object normally assumes that no outsider is setting state
     70      * within the underlying 3D API's context/device/whatever. This call informs
     71      * the GrGpu that the state was modified and it shouldn't make assumptions
     72      * about the state.
     73      */
     74     void markContextDirty() { fContextIsDirty = true; }
     75 
     76     void unimpl(const char[]);
     77 
     78     /**
     79      * Creates a texture object. If desc width or height is not a power of
     80      * two but underlying API requires a power of two texture then srcData
     81      * will be embedded in a power of two texture. The extra width and height
     82      * is filled as though srcData were rendered clamped into the texture.
     83      *
     84      * If kRenderTarget_TextureFlag is specified the GrRenderTarget is
     85      * accessible via GrTexture::asRenderTarget(). The texture will hold a ref
     86      * on the render target until its releaseRenderTarget() is called or it is
     87      * destroyed.
     88      *
     89      * @param desc        describes the texture to be created.
     90      * @param srcData     texel data to load texture. Begins with full-size
     91      *                    palette data for paletted textures. Contains width*
     92      *                    height texels. If NULL texture data is uninitialized.
     93      *
     94      * @return    The texture object if successful, otherwise NULL.
     95      */
     96     GrTexture* createTexture(const GrTextureDesc& desc,
     97                              const void* srcData, size_t rowBytes);
     98 
     99     /**
    100      * Implements GrContext::wrapBackendTexture
    101      */
    102     GrTexture* wrapBackendTexture(const GrBackendTextureDesc&);
    103 
    104     /**
    105      * Implements GrContext::wrapBackendTexture
    106      */
    107     GrRenderTarget* wrapBackendRenderTarget(const GrBackendRenderTargetDesc&);
    108 
    109     /**
    110      * Creates a vertex buffer.
    111      *
    112      * @param size    size in bytes of the vertex buffer
    113      * @param dynamic hints whether the data will be frequently changed
    114      *                by either GrVertexBuffer::lock or
    115      *                GrVertexBuffer::updateData.
    116      *
    117      * @return    The vertex buffer if successful, otherwise NULL.
    118      */
    119     GrVertexBuffer* createVertexBuffer(uint32_t size, bool dynamic);
    120 
    121     /**
    122      * Creates an index buffer.
    123      *
    124      * @param size    size in bytes of the index buffer
    125      * @param dynamic hints whether the data will be frequently changed
    126      *                by either GrIndexBuffer::lock or
    127      *                GrIndexBuffer::updateData.
    128      *
    129      * @return The index buffer if successful, otherwise NULL.
    130      */
    131     GrIndexBuffer* createIndexBuffer(uint32_t size, bool dynamic);
    132 
    133     /**
    134      * Creates a path object that can be stenciled using stencilPath(). It is
    135      * only legal to call this if the caps report support for path stenciling.
    136      */
    137     GrPath* createPath(const SkPath& path);
    138 
    139     /**
    140      * Returns an index buffer that can be used to render quads.
    141      * Six indices per quad: 0, 1, 2, 0, 2, 3, etc.
    142      * The max number of quads can be queried using GrIndexBuffer::maxQuads().
    143      * Draw with kTriangles_GrPrimitiveType
    144      * @ return the quad index buffer
    145      */
    146     const GrIndexBuffer* getQuadIndexBuffer() const;
    147 
    148     /**
    149      * Returns a vertex buffer with four position-only vertices [(0,0), (1,0),
    150      * (1,1), (0,1)].
    151      * @ return unit square vertex buffer
    152      */
    153     const GrVertexBuffer* getUnitSquareVertexBuffer() const;
    154 
    155     /**
    156      * Resolves MSAA.
    157      */
    158     void resolveRenderTarget(GrRenderTarget* target);
    159 
    160     /**
    161      * Ensures that the current render target is actually set in the
    162      * underlying 3D API. Used when client wants to use 3D API to directly
    163      * render to the RT.
    164      */
    165     void forceRenderTargetFlush();
    166 
    167     /**
    168      * readPixels with some configs may be slow. Given a desired config this
    169      * function returns a fast-path config. The returned config must have the
    170      * same components and component sizes. The caller is free to ignore the
    171      * result and call readPixels with the original config.
    172      */
    173     virtual GrPixelConfig preferredReadPixelsConfig(GrPixelConfig config)
    174                                                                         const {
    175         return config;
    176     }
    177 
    178     /**
    179      * Same as above but applies to writeTexturePixels
    180      */
    181     virtual GrPixelConfig preferredWritePixelsConfig(GrPixelConfig config)
    182                                                                         const {
    183         return config;
    184     }
    185 
    186     /**
    187      * OpenGL's readPixels returns the result bottom-to-top while the skia
    188      * API is top-to-bottom. Thus we have to do a y-axis flip. The obvious
    189      * solution is to have the subclass do the flip using either the CPU or GPU.
    190      * However, the caller (GrContext) may have transformations to apply and can
    191      * simply fold in the y-flip for free. On the other hand, the subclass may
    192      * be able to do it for free itself. For example, the subclass may have to
    193      * do memcpys to handle rowBytes that aren't tight. It could do the y-flip
    194      * concurrently.
    195      *
    196      * This function returns true if a y-flip is required to put the pixels in
    197      * top-to-bottom order and the subclass cannot do it for free.
    198      *
    199      * See read pixels for the params
    200      * @return true if calling readPixels with the same set of params will
    201      *              produce bottom-to-top data
    202      */
    203      virtual bool readPixelsWillPayForYFlip(GrRenderTarget* renderTarget,
    204                                             int left, int top,
    205                                             int width, int height,
    206                                             GrPixelConfig config,
    207                                             size_t rowBytes) const = 0;
    208      /**
    209       * This should return true if reading a NxM rectangle of pixels from a
    210       * render target is faster if the target has dimensons N and M and the read
    211       * rectangle has its top-left at 0,0.
    212       */
    213      virtual bool fullReadPixelsIsFasterThanPartial() const { return false; };
    214 
    215     /**
    216      * Reads a rectangle of pixels from a render target.
    217      *
    218      * @param renderTarget  the render target to read from. NULL means the
    219      *                      current render target.
    220      * @param left          left edge of the rectangle to read (inclusive)
    221      * @param top           top edge of the rectangle to read (inclusive)
    222      * @param width         width of rectangle to read in pixels.
    223      * @param height        height of rectangle to read in pixels.
    224      * @param config        the pixel config of the destination buffer
    225      * @param buffer        memory to read the rectangle into.
    226      * @param rowBytes      the number of bytes between consecutive rows. Zero
    227      *                      means rows are tightly packed.
    228      * @param invertY       buffer should be populated bottom-to-top as opposed
    229      *                      to top-to-bottom (skia's usual order)
    230      *
    231      * @return true if the read succeeded, false if not. The read can fail
    232      *              because of a unsupported pixel config or because no render
    233      *              target is currently set.
    234      */
    235     bool readPixels(GrRenderTarget* renderTarget,
    236                     int left, int top, int width, int height,
    237                     GrPixelConfig config, void* buffer, size_t rowBytes,
    238                     bool invertY);
    239 
    240     /**
    241      * Updates the pixels in a rectangle of a texture.
    242      *
    243      * @param left          left edge of the rectangle to write (inclusive)
    244      * @param top           top edge of the rectangle to write (inclusive)
    245      * @param width         width of rectangle to write in pixels.
    246      * @param height        height of rectangle to write in pixels.
    247      * @param config        the pixel config of the source buffer
    248      * @param buffer        memory to read pixels from
    249      * @param rowBytes      number of bytes between consecutive rows. Zero
    250      *                      means rows are tightly packed.
    251      */
    252     void writeTexturePixels(GrTexture* texture,
    253                             int left, int top, int width, int height,
    254                             GrPixelConfig config, const void* buffer,
    255                             size_t rowBytes);
    256 
    257     /**
    258      * Called to tell Gpu object that all GrResources have been lost and should
    259      * be abandoned. Overrides must call INHERITED::abandonResources().
    260      */
    261     virtual void abandonResources();
    262 
    263     /**
    264      * Called to tell Gpu object to release all GrResources. Overrides must call
    265      * INHERITED::releaseResources().
    266      */
    267     void releaseResources();
    268 
    269     /**
    270      * Add resource to list of resources. Should only be called by GrResource.
    271      * @param resource  the resource to add.
    272      */
    273     void insertResource(GrResource* resource);
    274 
    275     /**
    276      * Remove resource from list of resources. Should only be called by
    277      * GrResource.
    278      * @param resource  the resource to remove.
    279      */
    280     void removeResource(GrResource* resource);
    281 
    282     // GrDrawTarget overrides
    283     virtual void clear(const GrIRect* rect,
    284                        GrColor color,
    285                        GrRenderTarget* renderTarget = NULL) SK_OVERRIDE;
    286 
    287     virtual void purgeResources() SK_OVERRIDE {
    288         // The clip mask manager can rebuild all its clip masks so just
    289         // get rid of them all.
    290         fClipMaskManager.releaseResources();
    291     }
    292 
    293     // After the client interacts directly with the 3D context state the GrGpu
    294     // must resync its internal state and assumptions about 3D context state.
    295     // Each time this occurs the GrGpu bumps a timestamp.
    296     // state of the 3D context
    297     // At 10 resets / frame and 60fps a 64bit timestamp will overflow in about
    298     // a billion years.
    299     typedef uint64_t ResetTimestamp;
    300 
    301     // This timestamp is always older than the current timestamp
    302     static const ResetTimestamp kExpiredTimestamp = 0;
    303     // Returns a timestamp based on the number of times the context was reset.
    304     // This timestamp can be used to lazily detect when cached 3D context state
    305     // is dirty.
    306     ResetTimestamp getResetTimestamp() const {
    307         return fResetTimestamp;
    308     }
    309 
    310     /**
    311      * Can the provided configuration act as a color render target?
    312      */
    313     bool isConfigRenderable(GrPixelConfig config) const {
    314         GrAssert(kGrPixelConfigCount > config);
    315         return fConfigRenderSupport[config];
    316     }
    317 
    318     /**
    319      * These methods are called by the clip manager's setupClipping function
    320      * which (called as part of GrGpu's implementation of onDraw and
    321      * onStencilPath member functions.) The GrGpu subclass should flush the
    322      * stencil state to the 3D API in its implementation of flushGraphicsState.
    323      */
    324     void enableScissor(const GrIRect& rect) {
    325         fScissorState.fEnabled = true;
    326         fScissorState.fRect = rect;
    327     }
    328     void disableScissor() { fScissorState.fEnabled = false; }
    329 
    330     /**
    331      * Like the scissor methods above this is called by setupClipping and
    332      * should be flushed by the GrGpu subclass in flushGraphicsState. These
    333      * stencil settings should be used in place of those on the GrDrawState.
    334      * They have been adjusted to account for any interactions between the
    335      * GrDrawState's stencil settings and stencil clipping.
    336      */
    337     void setStencilSettings(const GrStencilSettings& settings) {
    338         fStencilSettings = settings;
    339     }
    340     void disableStencil() { fStencilSettings.setDisabled(); }
    341 
    342     // GrGpu subclass sets clip bit in the stencil buffer. The subclass is
    343     // free to clear the remaining bits to zero if masked clears are more
    344     // expensive than clearing all bits.
    345     virtual void clearStencilClip(const GrIRect& rect, bool insideClip) = 0;
    346 
    347     enum PrivateDrawStateStateBits {
    348         kFirstBit = (GrDrawState::kLastPublicStateBit << 1),
    349 
    350         kModifyStencilClip_StateBit = kFirstBit, // allows draws to modify
    351                                                  // stencil bits used for
    352                                                  // clipping.
    353     };
    354 
    355 protected:
    356     enum DrawType {
    357         kDrawPoints_DrawType,
    358         kDrawLines_DrawType,
    359         kDrawTriangles_DrawType,
    360         kStencilPath_DrawType,
    361     };
    362 
    363     DrawType PrimTypeToDrawType(GrPrimitiveType type) {
    364         switch (type) {
    365             case kTriangles_GrPrimitiveType:
    366             case kTriangleStrip_GrPrimitiveType:
    367             case kTriangleFan_GrPrimitiveType:
    368                 return kDrawTriangles_DrawType;
    369             case kPoints_GrPrimitiveType:
    370                 return kDrawPoints_DrawType;
    371             case kLines_GrPrimitiveType:
    372             case kLineStrip_GrPrimitiveType:
    373                 return kDrawLines_DrawType;
    374             default:
    375                 GrCrash("Unexpected primitive type");
    376                 return kDrawTriangles_DrawType;
    377         }
    378     }
    379 
    380     // prepares clip flushes gpu state before a draw
    381     bool setupClipAndFlushState(DrawType);
    382 
    383     // Functions used to map clip-respecting stencil tests into normal
    384     // stencil funcs supported by GPUs.
    385     static GrStencilFunc ConvertStencilFunc(bool stencilInClip,
    386                                             GrStencilFunc func);
    387     static void ConvertStencilFuncAndMask(GrStencilFunc func,
    388                                           bool clipInStencil,
    389                                           unsigned int clipBit,
    390                                           unsigned int userBits,
    391                                           unsigned int* ref,
    392                                           unsigned int* mask);
    393 
    394     GrClipMaskManager           fClipMaskManager;
    395 
    396     struct GeometryPoolState {
    397         const GrVertexBuffer* fPoolVertexBuffer;
    398         int                   fPoolStartVertex;
    399 
    400         const GrIndexBuffer*  fPoolIndexBuffer;
    401         int                   fPoolStartIndex;
    402     };
    403     const GeometryPoolState& getGeomPoolState() {
    404         return fGeomPoolStateStack.back();
    405     }
    406 
    407     // The state of the scissor is controlled by the clip manager
    408     struct ScissorState {
    409         bool    fEnabled;
    410         GrIRect fRect;
    411     } fScissorState;
    412 
    413     // The final stencil settings to use as determined by the clip manager.
    414     GrStencilSettings fStencilSettings;
    415 
    416     // Derived classes need access to this so they can fill it out in their
    417     // constructors
    418     bool    fConfigRenderSupport[kGrPixelConfigCount];
    419 
    420     // Helpers for setting up geometry state
    421     void finalizeReservedVertices();
    422     void finalizeReservedIndices();
    423 
    424 private:
    425     // GrDrawTarget overrides
    426     virtual bool onReserveVertexSpace(size_t vSize, int vertexCount, void** vertices) SK_OVERRIDE;
    427     virtual bool onReserveIndexSpace(int indexCount, void** indices) SK_OVERRIDE;
    428     virtual void releaseReservedVertexSpace() SK_OVERRIDE;
    429     virtual void releaseReservedIndexSpace() SK_OVERRIDE;
    430     virtual void onSetVertexSourceToArray(const void* vertexArray, int vertexCount) SK_OVERRIDE;
    431     virtual void onSetIndexSourceToArray(const void* indexArray, int indexCount) SK_OVERRIDE;
    432     virtual void releaseVertexArray() SK_OVERRIDE;
    433     virtual void releaseIndexArray() SK_OVERRIDE;
    434     virtual void geometrySourceWillPush() SK_OVERRIDE;
    435     virtual void geometrySourceWillPop(const GeometrySrcState& restoredState) SK_OVERRIDE;
    436 
    437 
    438     // called when the 3D context state is unknown. Subclass should emit any
    439     // assumed 3D context state and dirty any state cache.
    440     virtual void onResetContext() = 0;
    441 
    442     // overridden by backend-specific derived class to create objects.
    443     virtual GrTexture* onCreateTexture(const GrTextureDesc& desc,
    444                                        const void* srcData,
    445                                        size_t rowBytes) = 0;
    446     virtual GrTexture* onWrapBackendTexture(const GrBackendTextureDesc&) = 0;
    447     virtual GrRenderTarget* onWrapBackendRenderTarget(const GrBackendRenderTargetDesc&) = 0;
    448     virtual GrVertexBuffer* onCreateVertexBuffer(uint32_t size, bool dynamic) = 0;
    449     virtual GrIndexBuffer* onCreateIndexBuffer(uint32_t size, bool dynamic) = 0;
    450     virtual GrPath* onCreatePath(const SkPath& path) = 0;
    451 
    452     // overridden by backend-specific derived class to perform the clear and
    453     // clearRect. NULL rect means clear whole target.
    454     virtual void onClear(const GrIRect* rect, GrColor color) = 0;
    455 
    456     // overridden by backend-specific derived class to perform the draw call.
    457     virtual void onGpuDraw(const DrawInfo&) = 0;
    458     // when GrDrawTarget::stencilPath is called the draw state's current stencil
    459     // settings are ignored. Instead the GrGpu decides the stencil rules
    460     // necessary to stencil the path. These are still subject to filtering by
    461     // the clip mask manager.
    462     virtual void setStencilPathSettings(const GrPath&,
    463                                         SkPath::FillType,
    464                                         GrStencilSettings* settings) = 0;
    465     // overridden by backend-specific derived class to perform the path stenciling.
    466     virtual void onGpuStencilPath(const GrPath*, SkPath::FillType) = 0;
    467 
    468     // overridden by backend-specific derived class to perform flush
    469     virtual void onForceRenderTargetFlush() = 0;
    470 
    471     // overridden by backend-specific derived class to perform the read pixels.
    472     virtual bool onReadPixels(GrRenderTarget* target,
    473                               int left, int top, int width, int height,
    474                               GrPixelConfig,
    475                               void* buffer,
    476                               size_t rowBytes,
    477                               bool invertY) = 0;
    478 
    479     // overridden by backend-specific derived class to perform the texture update
    480     virtual void onWriteTexturePixels(GrTexture* texture,
    481                                       int left, int top, int width, int height,
    482                                       GrPixelConfig config, const void* buffer,
    483                                       size_t rowBytes) = 0;
    484 
    485     // overridden by backend-specific derived class to perform the resolve
    486     virtual void onResolveRenderTarget(GrRenderTarget* target) = 0;
    487 
    488     // width and height may be larger than rt (if underlying API allows it).
    489     // Should attach the SB to the RT. Returns false if compatible sb could
    490     // not be created.
    491     virtual bool createStencilBufferForRenderTarget(GrRenderTarget*, int width, int height) = 0;
    492 
    493     // attaches an existing SB to an existing RT.
    494     virtual bool attachStencilBufferToRenderTarget(GrStencilBuffer*, GrRenderTarget*) = 0;
    495 
    496     // The GrGpu typically records the clients requested state and then flushes
    497     // deltas from previous state at draw time. This function does the
    498     // backend-specific flush of the state
    499     // returns false if current state is unsupported.
    500     virtual bool flushGraphicsState(DrawType) = 0;
    501 
    502     // clears the entire stencil buffer to 0
    503     virtual void clearStencil() = 0;
    504 
    505     // Given a rt, find or create a stencil buffer and attach it
    506     bool attachStencilBufferToRenderTarget(GrRenderTarget* target);
    507 
    508     // GrDrawTarget overrides
    509     virtual void onDraw(const DrawInfo&) SK_OVERRIDE;
    510     virtual void onStencilPath(const GrPath* path, const SkStrokeRec& stroke,
    511                                SkPath::FillType) SK_OVERRIDE;
    512 
    513     // readies the pools to provide vertex/index data.
    514     void prepareVertexPool();
    515     void prepareIndexPool();
    516 
    517     void resetContext() {
    518         // We call this because the client may have messed with the
    519         // stencil buffer. Perhaps we should detect whether it is a
    520         // internally created stencil buffer and if so skip the invalidate.
    521         fClipMaskManager.invalidateStencilMask();
    522         this->onResetContext();
    523         ++fResetTimestamp;
    524     }
    525 
    526     void handleDirtyContext() {
    527         if (fContextIsDirty) {
    528             this->resetContext();
    529             fContextIsDirty = false;
    530         }
    531     }
    532 
    533     enum {
    534         kPreallocGeomPoolStateStackCnt = 4,
    535     };
    536     typedef SkTInternalLList<GrResource> ResourceList;
    537     SkSTArray<kPreallocGeomPoolStateStackCnt, GeometryPoolState, true>  fGeomPoolStateStack;
    538     GrContext*                                                          fContext; // not reffed
    539     ResetTimestamp                                                      fResetTimestamp;
    540     GrVertexBufferAllocPool*                                            fVertexPool;
    541     GrIndexBufferAllocPool*                                             fIndexPool;
    542     // counts number of uses of vertex/index pool in the geometry stack
    543     int                                                                 fVertexPoolUseCnt;
    544     int                                                                 fIndexPoolUseCnt;
    545     // these are mutable so they can be created on-demand
    546     mutable GrVertexBuffer*                                             fUnitSquareVertexBuffer;
    547     mutable GrIndexBuffer*                                              fQuadIndexBuffer;
    548     bool                                                                fContextIsDirty;
    549     ResourceList                                                        fResourceList;
    550 
    551     typedef GrDrawTarget INHERITED;
    552 };
    553 
    554 #endif
    555