code:
/*
    Copyright 2010 Google Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

#ifndef GrDrawTarget_DEFINED
#define GrDrawTarget_DEFINED

#include "GrMatrix.h"
#include "GrColor.h"
#include "GrRefCnt.h"
#include "GrSamplerState.h"
#include "GrClip.h"
#include "GrTexture.h"
#include "GrStencil.h"

#include "SkXfermode.h"

class GrTexture;
class GrClipIterator;
class GrVertexBuffer;
class GrIndexBuffer;

class GrDrawTarget : public GrRefCnt {
public:
    /**
     * Number of texture stages. Each stage takes as input a color and
     * 2D texture coordinates. The color input to the first enabled stage is the
     * per-vertex color or the constant color (setColor/setAlpha) if there are
     * no per-vertex colors. For subsequent stages the input color is the output
     * color from the previous enabled stage. The output color of each stage is
     * the input color modulated with the result of a texture lookup. Texture
     * lookups are specified by a texture a sampler (setSamplerState). Texture
     * coordinates for each stage come from the vertices based on a
     * GrVertexLayout bitfield. The output fragment color is the output color of
     * the last enabled stage. The presence or absence of texture coordinates
     * for each stage in the vertex layout indicates whether a stage is enabled
     * or not.
     */
    enum {
        kNumStages = 3,
        kMaxTexCoords = kNumStages
    };

    /**
     * The absolute maximum number of edges that may be specified for
     * a single draw call when performing edge antialiasing.  This is used for
     * the size of several static buffers, so implementations of getMaxEdges()
     * (below) should clamp to this value.
     */
    enum {
        kMaxEdges = 32
    };

    /**
     *  Bitfield used to indicate which stages are in use.
     */
    typedef int StageBitfield;
    GR_STATIC_ASSERT(sizeof(StageBitfield)*8 >= kNumStages);

    /**
     *  Flags that affect rendering. Controlled using enable/disableState(). All
     *  default to disabled.
     */
    enum StateBits {
        kDither_StateBit        = 0x01, //<! Perform color dithering
        kAntialias_StateBit     = 0x02, //<! Perform anti-aliasing. The render-
                                        //   target must support some form of AA
                                        //   (msaa, coverage sampling, etc). For
                                        //   GrGpu-created rendertarget/textures
                                        //   this is controlled by parameters
                                        //   passed to createTexture.
        kClip_StateBit          = 0x04, //<! Controls whether drawing is clipped
                                        //   against the region specified by
                                        //   setClip.
        kNoColorWrites_StateBit = 0x08, //<! If set it disables writing colors.
                                        //   Useful while performing stencil
                                        //   ops.
        kEdgeAAConcave_StateBit =  0x10,//<! If set, edge AA will test edge
                                        //   pairs for convexity while
                                        //   rasterizing.  Set this if the
                                        //   source polygon is non-convex.

        // subclass may use additional bits internally
        kDummyStateBit,
        kLastPublicStateBit = kDummyStateBit-1
    };

    enum DrawFace {
        kBoth_DrawFace,
        kCCW_DrawFace,
        kCW_DrawFace,
    };

    /**
     * The DrawTarget may reserve some of the high bits of the stencil. The draw
     * target will automatically trim reference and mask values so that the
     * client doesn't overwrite these bits.
     * The number of bits available is relative to the currently set render
      *target.
     * @return the number of bits usable by the draw target client.
     */
    int getUsableStencilBits() const {
        int bits = fCurrDrawState.fRenderTarget->stencilBits();
        if (bits) {
            return bits - 1;
        } else {
            return 0;
        }
    }

    /**
     * Sets the stencil settings to use for the next draw.
     * Changing the clip has the side-effect of possibly zeroing
     * out the client settable stencil bits. So multipass algorithms
     * using stencil should not change the clip between passes.
     * @param settings  the stencil settings to use.
     */
    void setStencil(const GrStencilSettings& settings) {
        fCurrDrawState.fStencilSettings = settings;
    }

    /**
     * Shortcut to disable stencil testing and ops.
     */
    void disableStencil() {
        fCurrDrawState.fStencilSettings.setDisabled();
    }

    class Edge {
      public:
        Edge() {}
        Edge(float x, float y, float z) : fX(x), fY(y), fZ(z) {}
        GrPoint intersect(const Edge& other) {
            return GrPoint::Make(
                (fY * other.fZ - other.fY * fZ) /
                  (fX * other.fY - other.fX * fY),
                (fX * other.fZ - other.fX * fZ) /
                  (other.fX * fY - fX * other.fY));
        }
        float fX, fY, fZ;
    };

protected:

    struct DrState {
        DrState() {
            // make sure any pad is zero for memcmp
            // all DrState members should default to something
            // valid by the memset
            memset(this, 0, sizeof(DrState));

            // memset exceptions
            fColorFilterXfermode = SkXfermode::kDstIn_Mode;
            fFirstCoverageStage = kNumStages;

            // pedantic assertion that our ptrs will
            // be NULL (0 ptr is mem addr 0)
            GrAssert((intptr_t)(void*)NULL == 0LL);

            // default stencil setting should be disabled
            GrAssert(fStencilSettings.isDisabled());
            fFirstCoverageStage = kNumStages;
        }
        uint32_t                fFlagBits;
        GrBlendCoeff            fSrcBlend;
        GrBlendCoeff            fDstBlend;
        GrColor                 fBlendConstant;
        GrTexture*              fTextures[kNumStages];
        GrSamplerState          fSamplerStates[kNumStages];
        int                     fFirstCoverageStage;
        GrRenderTarget*         fRenderTarget;
        GrColor                 fColor;
        DrawFace                fDrawFace;
        GrColor                 fColorFilterColor;
        SkXfermode::Mode        fColorFilterXfermode;

        GrStencilSettings       fStencilSettings;
        GrMatrix                fViewMatrix;
        Edge                    fEdgeAAEdges[kMaxEdges];
        int                     fEdgeAANumEdges;
        bool operator ==(const DrState& s) const {
            return 0 == memcmp(this, &s, sizeof(DrState));
        }
        bool operator !=(const DrState& s) const { return !(*this == s); }
    };

public:
    ///////////////////////////////////////////////////////////////////////////

    GrDrawTarget();
    virtual ~GrDrawTarget();

    /**
     * Sets the current clip to the region specified by clip. All draws will be
     * clipped against this clip if kClip_StateBit is enabled.
     *
     * Setting the clip may (or may not) zero out the client's stencil bits.
     *
     * @param description of the clipping region
     */
    void setClip(const GrClip& clip);

    /**
     * Gets the current clip.
     *
     * @return the clip.
     */
    const GrClip& getClip() const;

    /**
     * Sets the texture used at the next drawing call
     *
     * @param stage The texture stage for which the texture will be set
     *
     * @param texture The texture to set. Can be NULL though there is no advantage
     * to settings a NULL texture if doing non-textured drawing
     */
    void setTexture(int stage, GrTexture* texture);

    /**
     * Retrieves the currently set texture.
     *
     * @return    The currently set texture. The return value will be NULL if no
     *            texture has been set, NULL was most recently passed to
     *            setTexture, or the last setTexture was destroyed.
     */
    const GrTexture* getTexture(int stage) const;
    GrTexture* getTexture(int stage);

    /**
     * Sets the rendertarget used at the next drawing call
     *
     * @param target  The render target to set.
     */
    void setRenderTarget(GrRenderTarget* target);

    /**
     * Retrieves the currently set rendertarget.
     *
     * @return    The currently set render target.
     */
    const GrRenderTarget* getRenderTarget() const;
    GrRenderTarget* getRenderTarget();

    /**
     * Sets the sampler state for a stage used in subsequent draws.
     *
     * The sampler state determines how texture coordinates are
     * intepretted and used to sample the texture.
     *
     * @param stage           the stage of the sampler to set
     * @param samplerState    Specifies the sampler state.
     */
    void setSamplerState(int stage, const GrSamplerState& samplerState);

    /**
     * Concats the matrix of a stage's sampler.
     *
     * @param stage   the stage of the sampler to set
     * @param matrix  the matrix to concat
     */
    void preConcatSamplerMatrix(int stage, const GrMatrix& matrix)  {
        GrAssert(stage >= 0 && stage < kNumStages);
        fCurrDrawState.fSamplerStates[stage].preConcatMatrix(matrix);
    }

    /**
     * Shortcut for preConcatSamplerMatrix on all stages in mask with same
     * matrix
     */
    void preConcatSamplerMatrices(int stageMask, const GrMatrix& matrix) {
        for (int i = 0; i < kNumStages; ++i) {
            if ((1 << i) & stageMask) {
                this->preConcatSamplerMatrix(i, matrix);
            }
        }
    }

    /**
     * Gets the matrix of a stage's sampler
     *
     * @param stage     the stage to of sampler to get
     * @return the sampler state's matrix
     */
    const GrMatrix& getSamplerMatrix(int stage) const {
        return fCurrDrawState.fSamplerStates[stage].getMatrix();
    }

    /**
     * Sets the matrix of a stage's sampler
     *
     * @param stage     the stage of sampler set
     * @param matrix    the matrix to set
     */
    void setSamplerMatrix(int stage, const GrMatrix& matrix) {
        fCurrDrawState.fSamplerStates[stage].setMatrix(matrix);
    }

    /**
     * Sets the matrix applied to veretx positions.
     *
     * In the post-view-matrix space the rectangle [0,w]x[0,h]
     * fully covers the render target. (w and h are the width and height of the
     * the rendertarget.)
     *
     * @param m the matrix used to transform the vertex positions.
     */
    void setViewMatrix(const GrMatrix& m);

    /**
     *  Multiplies the current view matrix by a matrix
     *
     *  After this call V' = V*m where V is the old view matrix,
     *  m is the parameter to this function, and V' is the new view matrix.
     *  (We consider positions to be column vectors so position vector p is
     *  transformed by matrix X as p' = X*p.)
     *
     *  @param m the matrix used to modify the view matrix.
     */
    void preConcatViewMatrix(const GrMatrix& m);

    /**
     *  Multiplies the current view matrix by a matrix
     *
     *  After this call V' = m*V where V is the old view matrix,
     *  m is the parameter to this function, and V' is the new view matrix.
     *  (We consider positions to be column vectors so position vector p is
     *  transformed by matrix X as p' = X*p.)
     *
     *  @param m the matrix used to modify the view matrix.
     */
    void postConcatViewMatrix(const GrMatrix& m);

    /**
     * Retrieves the current view matrix
     * @return the current view matrix.
     */
    const GrMatrix& getViewMatrix() const;

    /**
     *  Retrieves the inverse of the current view matrix.
     *
     *  If the current view matrix is invertible, return true, and if matrix
     *  is non-null, copy the inverse into it. If the current view matrix is
     *  non-invertible, return false and ignore the matrix parameter.
     *
     * @param matrix if not null, will receive a copy of the current inverse.
     */
    bool getViewInverse(GrMatrix* matrix) const;

    /**
     *  Sets color for next draw to a premultiplied-alpha color.
     *
     *  @param the color to set.
     */
    void setColor(GrColor);

    /**
     * Add a color filter that can be represented by a color and a mode.
     */
    void setColorFilter(GrColor, SkXfermode::Mode);

    /**
     *  Sets the color to be used for the next draw to be
     *  (r,g,b,a) = (alpha, alpha, alpha, alpha).
     *
     *  @param alpha The alpha value to set as the color.
     */
    void setAlpha(uint8_t alpha);

    /**
     * Controls whether clockwise, counterclockwise, or both faces are drawn.
     * @param face  the face(s) to draw.
     */
    void setDrawFace(DrawFace face) { fCurrDrawState.fDrawFace = face; }

    /**
     * A common pattern is to compute a color with the initial stages and then
     * modulate that color by a coverage value in later stage(s) (AA, mask-
     * filters, glyph mask, etc). Color-filters, xfermodes, etc should be
     * computed based on the pre-coverage-modulated color. The division of
     * stages between color-computing and coverage-computing is specified by
     * this method. Initially this is kNumStages (all stages are color-
     * computing).
     */
    void setFirstCoverageStage(int firstCoverageStage) {
        fCurrDrawState.fFirstCoverageStage = firstCoverageStage;
    }

    /**
     * Gets the index of the first coverage-computing stage.
     */
    int getFirstCoverageStage() const {
        return fCurrDrawState.fFirstCoverageStage;
    }

    /**
     * Gets whether the target is drawing clockwise, counterclockwise,
     * or both faces.
     * @return the current draw face(s).
     */
    DrawFace getDrawFace() const { return fCurrDrawState.fDrawFace; }

    /**
     * Enable render state settings.
     *
     * @param flags   bitfield of StateBits specifing the states to enable
     */
    void enableState(uint32_t stateBits);

    /**
     * Disable render state settings.
     *
     * @param flags   bitfield of StateBits specifing the states to disable
     */
    void disableState(uint32_t stateBits);

    bool isDitherState() const {
        return 0 != (fCurrDrawState.fFlagBits & kDither_StateBit);
    }

    bool isAntialiasState() const {
        return 0 != (fCurrDrawState.fFlagBits & kAntialias_StateBit);
    }

    bool isClipState() const {
        return 0 != (fCurrDrawState.fFlagBits & kClip_StateBit);
    }

    bool isColorWriteDisabled() const {
        return 0 != (fCurrDrawState.fFlagBits & kNoColorWrites_StateBit);
    }

    /**
     * Sets the blending function coeffecients.
     *
     * The blend function will be:
     *    D' = sat(S*srcCoef + D*dstCoef)
     *
     *   where D is the existing destination color, S is the incoming source
     *   color, and D' is the new destination color that will be written. sat()
     *   is the saturation function.
     *
     * @param srcCoef coeffecient applied to the src color.
     * @param dstCoef coeffecient applied to the dst color.
     */
    void setBlendFunc(GrBlendCoeff srcCoeff, GrBlendCoeff dstCoeff);

    /**
     * Sets the blending function constant referenced by the following blending
     * coeffecients:
     *      kConstC_BlendCoeff
     *      kIConstC_BlendCoeff
     *      kConstA_BlendCoeff
     *      kIConstA_BlendCoeff
     *
     * @param constant the constant to set
     */
    void setBlendConstant(GrColor constant) { fCurrDrawState.fBlendConstant = constant; }

    /**
     * Retrieves the last value set by setBlendConstant()
     * @return the blending constant value
     */
    GrColor getBlendConstant() const { return fCurrDrawState.fBlendConstant; }

    /**
     * Used to save and restore the GrGpu's drawing state
     */
    struct SavedDrawState {
    private:
        DrState fState;
        friend class GrDrawTarget;
    };

    /**
     * Saves the current draw state. The state can be restored at a later time
     * with restoreDrawState.
     *
     * See also AutoStateRestore class.
     *
     * @param   state will hold the state after the function returns.
     */
    void saveCurrentDrawState(SavedDrawState* state) const;

    /**
     * Restores previously saved draw state. The client guarantees that state
     * was previously passed to saveCurrentDrawState and that the rendertarget
     * and texture set at save are still valid.
     *
     * See also AutoStateRestore class.
     *
     * @param   state the previously saved state to restore.
     */
    void restoreDrawState(const SavedDrawState& state);

    /**
     * Copies the draw state from another target to this target.
     *
     * @param srcTarget     draw target used as src of the draw state.
     */
    void copyDrawState(const GrDrawTarget& srcTarget);

    /**
     * The format of vertices is represented as a bitfield of flags.
     * Flags that indicate the layout of vertex data. Vertices always contain
     * positions and may also contain up to kMaxTexCoords sets of 2D texture
     * coordinates and per-vertex colors. Each stage can use any of the texture
     * coordinates as its input texture coordinates or it may use the positions.
     *
     * If no texture coordinates are specified for a stage then the stage is
     * disabled.
     *
     * Only one type of texture coord can be specified per stage. For
     * example StageTexCoordVertexLayoutBit(0, 2) and
     * StagePosAsTexCoordVertexLayoutBit(0) cannot both be specified.
     *
     * The order in memory is always (position, texture coord 0, ..., color)
     * with any unused fields omitted. Note that this means that if only texture
     * coordinates 1 is referenced then there is no texture coordinates 0 and
     * the order would be (position, texture coordinate 1[, color]).
     */

    /**
     * Generates a bit indicating that a texture stage uses texture coordinates
     *
     * @param stage       the stage that will use texture coordinates.
     * @param texCoordIdx the index of the texture coordinates to use
     *
     * @return the bit to add to a GrVertexLayout bitfield.
     */
    static int StageTexCoordVertexLayoutBit(int stage, int texCoordIdx) {
        GrAssert(stage < kNumStages);
        GrAssert(texCoordIdx < kMaxTexCoords);
        return 1 << (stage + (texCoordIdx * kNumStages));
    }

    /**
     * Determines if blend is effectively disabled.
     *
     * @return true if blend can be disabled without changing the rendering
     *  result given the current state including the vertex layout specified
     *  with the vertex source.
     */
    bool canDisableBlend() const;

    /**
     * Sets the edge data required for edge antialiasing.
     *
     * @param edges       3 * 6 float values, representing the edge
     *                    equations in Ax + By + C form
     */
     void setEdgeAAData(const Edge* edges, int numEdges);

private:
    static const int TEX_COORD_BIT_CNT = kNumStages*kMaxTexCoords;
public:
    /**
     * Generates a bit indicating that a texture stage uses the position
     * as its texture coordinate.
     *
     * @param stage       the stage that will use position as texture
     *                    coordinates.
     *
     * @return the bit to add to a GrVertexLayout bitfield.
     */
    static int StagePosAsTexCoordVertexLayoutBit(int stage) {
        GrAssert(stage < kNumStages);
        return (1 << (TEX_COORD_BIT_CNT + stage));
    }
private:
    static const int STAGE_BIT_CNT = TEX_COORD_BIT_CNT + kNumStages;

public:

    /**
     * Additional Bits that can be specified in GrVertexLayout.
     */
    enum VertexLayoutBits {

        kColor_VertexLayoutBit              = 1 << (STAGE_BIT_CNT + 0),
                                                //<! vertices have colors
        kTextFormat_VertexLayoutBit         = 1 << (STAGE_BIT_CNT + 1),
                                                //<! use text vertices. (Pos
                                                //   and tex coords may be
                                                //   a different type for
                                                //   text [GrGpuTextVertex vs
                                                //   GrPoint].)
        // for below assert
        kDummyVertexLayoutBit,
        kHighVertexLayoutBit = kDummyVertexLayoutBit - 1
    };
    // make sure we haven't exceeded the number of bits in GrVertexLayout.
    GR_STATIC_ASSERT(kHighVertexLayoutBit < ((uint64_t)1 << 8*sizeof(GrVertexLayout)));

    /**
     * There are three methods for specifying geometry (vertices and optionally
     * indices) to the draw target. When indexed drawing the indices and vertices
     * can use a different method. Once geometry is specified it can be used for
     * multiple drawIndexed and drawNonIndexed calls.
     *
     * Sometimes it is necessary to perform a draw while upstack code has
     * already specified geometry that it isn't finished with. There are push
     * pop methods
     *
     * 1. Provide a cpu array (set*SourceToArray). This is useful when the
     *    caller's client has already provided vertex data in a format
     *    the time compatible with a GrVertexLayout. The array must contain the
     *    data at set*SourceToArray is called. The source stays in effect for
     *    drawIndexed & drawNonIndexed calls until set*SourceToArray is called
     *    again or one of the other two paths is chosen.
     *
     * 2. Reserve. This is most useful when the caller has data it must
     *    transform before drawing and is not long-lived. The caller requests
     *    that the draw target make room for some amount of vertex and/or index
     *    data. The target provides ptrs to hold the vertex and/or index data.
     *
     *    The data is writable up until the next drawIndexed, drawNonIndexed,
     *    or pushGeometrySource At this point the data is frozen and the ptrs
     *    are no longer valid.
     *
     * 3. Vertex and Index Buffers. This is most useful for geometry that will
     *    is long-lived. SetVertexSourceToBuffer and SetIndexSourceToBuffer are
     *    used to set the buffer and subsequent drawIndexed and drawNonIndexed
     *    calls use this source until another source is set.
     */

    /**
     * Reserves space for vertices. Draw target will use reserved vertices at
     * at the next draw.
     *
     * If succeeds:
     *          if vertexCount > 0, *vertices will be the array
     *          of vertices to be filled by caller. The next draw will read
     *          these vertices.
     *
     * If a client does not already have a vertex buffer then this is the
     * preferred way to allocate vertex data. It allows the subclass of
     * GrDrawTarget to decide whether to put data in buffers, to group vertex
     * data that uses the same state (e.g. for deferred rendering), etc.
     *
     * After the next draw or pushGeometrySource the vertices ptr is no longer
     * valid and the geometry data cannot be further modified. The contents
     * that were put in the reserved space can be drawn by multiple draws,
     * however.
     *
     * @param vertexLayout the format of vertices (ignored if vertexCount == 0).
     * @param vertexCount  the number of vertices to reserve space for. Can be 0.
     * @param vertices     will point to reserved vertex space if vertexCount is
     *                     non-zero. Illegal to pass NULL if vertexCount > 0.
     *
     * @return  true if succeeded in allocating space for the vertices and false
     *               if not.
     */
    bool reserveVertexSpace(GrVertexLayout vertexLayout,
                            int vertexCount,
                            void** vertices);
    /**
     * Reserves space for indices. Draw target will use the reserved indices at
     * the next indexed draw.
     *
     * If succeeds:
     *          if indexCount > 0, *indices will be the array
     *          of indices to be filled by caller. The next draw will read
     *          these indices.
     *
     * If a client does not already have a index buffer then this is the
     * preferred way to allocate index data. It allows the subclass of
     * GrDrawTarget to decide whether to put data in buffers, to group index
     * data that uses the same state (e.g. for deferred rendering), etc.
     *
     * After the next indexed draw or pushGeometrySource the indices ptr is no
     * longer valid and the geometry data cannot be further modified. The
     * contents that were put in the reserved space can be drawn by multiple
     * draws, however.
     *
     * @param indexCount   the number of indices to reserve space for. Can be 0.
     * @param indices      will point to reserved index space if indexCount is
     *                     non-zero. Illegal to pass NULL if indexCount > 0.
     */

    bool reserveIndexSpace(int indexCount, void** indices);
    /**
     * Provides hints to caller about the number of vertices and indices
     * that can be allocated cheaply. This can be useful if caller is reserving
     * space but doesn't know exactly how much geometry is needed.
     *
     * Also may hint whether the draw target should be flushed first. This is
     * useful for deferred targets.
     *
     * @param vertexLayout layout of vertices caller would like to reserve
     * @param vertexCount  in: hint about how many vertices the caller would
     *                     like to allocate.
     *                     out: a hint about the number of vertices that can be
     *                     allocated cheaply. Negative means no hint.
     *                     Ignored if NULL.
     * @param indexCount   in: hint about how many indices the caller would
     *                     like to allocate.
     *                     out: a hint about the number of indices that can be
     *                     allocated cheaply. Negative means no hint.
     *                     Ignored if NULL.
     *
     * @return  true if target should be flushed based on the input values.
     */
    virtual bool geometryHints(GrVertexLayout vertexLayout,
                               int* vertexCount,
                               int* indexCount) const;

    /**
     * Sets source of vertex data for the next draw. Array must contain
     * the vertex data when this is called.
     *
     * @param array         cpu array containing vertex data.
     * @param size          size of the vertex data.
     * @param vertexCount   the number of vertices in the array.
     */
    void setVertexSourceToArray(GrVertexLayout vertexLayout,
                                const void* vertexArray,
                                int vertexCount);

    /**
     * Sets source of index data for the next indexed draw. Array must contain
     * the indices when this is called.
     *
     * @param array         cpu array containing index data.
     * @param indexCount    the number of indices in the array.
     */
    void setIndexSourceToArray(const void* indexArray, int indexCount);

    /**
     * Sets source of vertex data for the next draw. Data does not have to be
     * in the buffer until drawIndexed or drawNonIndexed.
     *
     * @param buffer        vertex buffer containing vertex data. Must be
     *                      unlocked before draw call.
     * @param vertexLayout  layout of the vertex data in the buffer.
     */
    void setVertexSourceToBuffer(GrVertexLayout vertexLayout,
                                 const GrVertexBuffer* buffer);

    /**
     * Sets source of index data for the next indexed draw. Data does not have
     * to be in the buffer until drawIndexed or drawNonIndexed.
     *
     * @param buffer index buffer containing indices. Must be unlocked
     *               before indexed draw call.
     */
    void setIndexSourceToBuffer(const GrIndexBuffer* buffer);

    /**
     * Resets vertex source. Drawing from reset vertices is illegal. Set vertex
     * source to reserved, array, or buffer before next draw. May be able to free
     * up temporary storage allocated by setVertexSourceToArray or
     * reserveVertexSpace.
     */
    void resetVertexSource();

    /**
     * Resets index source. Indexed Drawing from reset indices is illegal. Set
     * index source to reserved, array, or buffer before next indexed draw. May
     * be able to free up temporary storage allocated by setIndexSourceToArray
     * or reserveIndexSpace.
     */
    void resetIndexSource();

    /**
     * Pushes and resets the vertex/index sources. Any reserved vertex / index
     * data is finalized (i.e. cannot be updated after the matching pop but can
     * be drawn from). Must be balanced by a pop.
     */
    void pushGeometrySource();

    /**
     * Pops the vertex / index sources from the matching push.
     */
    void popGeometrySource();

    /**
     * Draws indexed geometry using the current state and current vertex / index
     * sources.
     *
     * @param type         The type of primitives to draw.
     * @param startVertex  the vertex in the vertex array/buffer corresponding
     *                     to index 0
     * @param startIndex   first index to read from index src.
     * @param vertexCount  one greater than the max index.
     * @param indexCount   the number of index elements to read. The index count
     *                     is effectively trimmed to the last completely
     *                     specified primitive.
     */
    void drawIndexed(GrPrimitiveType type,
                     int startVertex,
                     int startIndex,
                     int vertexCount,
                     int indexCount);

    /**
     * Draws non-indexed geometry using the current state and current vertex
     * sources.
     *
     * @param type         The type of primitives to draw.
     * @param startVertex  the vertex in the vertex array/buffer corresponding
     *                     to index 0
     * @param vertexCount  one greater than the max index.
     */
    void drawNonIndexed(GrPrimitiveType type,
                        int startVertex,
                        int vertexCount);

    /**
     * Helper function for drawing rects. This does not use the current index
     * and vertex sources. After returning, the vertex and index sources may
     * have changed. They should be reestablished before the next drawIndexed
     * or drawNonIndexed. This cannot be called between reserving and releasing
     * geometry. The GrDrawTarget subclass may be able to perform additional
     * optimizations if drawRect is used rather than drawIndexed or
     * drawNonIndexed.
     * @param rect      the rect to draw
     * @param matrix    optional matrix applied to rect (before viewMatrix)
     * @param stageEnableBitfield bitmask indicating which stages are enabled.
     *                            Bit i indicates whether stage i is enabled.
     * @param srcRects  specifies rects for stages enabled by stageEnableMask.
     *                  if stageEnableMask bit i is 1, srcRects is not NULL,
     *                  and srcRects[i] is not NULL, then srcRects[i] will be
     *                  used as coordinates for stage i. Otherwise, if stage i
     *                  is enabled then rect is used as the coordinates.
     * @param srcMatrices   optional matrices applied to srcRects. If
     *                      srcRect[i] is non-NULL and srcMatrices[i] is
     *                      non-NULL then srcRect[i] will be transformed by
     *                      srcMatrix[i]. srcMatrices can be NULL when no
     *                      srcMatrices are desired.
     */
    virtual void drawRect(const GrRect& rect,
                          const GrMatrix* matrix,
                          StageBitfield stageEnableBitfield,
                          const GrRect* srcRects[],
                          const GrMatrix* srcMatrices[]);

    /**
     * Helper for drawRect when the caller doesn't need separate src rects or
     * matrices.
     */
    void drawSimpleRect(const GrRect& rect,
                        const GrMatrix* matrix,
                        StageBitfield stageEnableBitfield) {
         drawRect(rect, matrix, stageEnableBitfield, NULL, NULL);
    }

    /**
     * Clear the render target. Ignores the clip and all other draw state
     * (blend mode, stages, etc). Clears the whole thing if rect is NULL,
     * otherwise just the rect.
     */
    virtual void clear(const GrIRect* rect, GrColor color) = 0;

    /**
     * Returns the maximum number of edges that may be specified in a single
     * draw call when performing edge antialiasing.  This is usually limited
     * by the number of fragment uniforms which may be uploaded.  Must be a
     * minimum of six, since a triangle's vertices each belong to two boundary
     * edges which may be distinct.
     */
    virtual int getMaxEdges() const { return 6; }

    ////////////////////////////////////////////////////////////////////////////

    class AutoStateRestore : ::GrNoncopyable {
    public:
        AutoStateRestore();
        AutoStateRestore(GrDrawTarget* target);
        ~AutoStateRestore();

        /**
         * if this object is already saving state for param target then
         * this does nothing. Otherise, it restores previously saved state on
         * previous target (if any) and saves current state on param target.
         */
        void set(GrDrawTarget* target);

    private:
        GrDrawTarget*       fDrawTarget;
        SavedDrawState      fDrawState;
    };

    ////////////////////////////////////////////////////////////////////////////

    class AutoViewMatrixRestore : ::GrNoncopyable {
    public:
        AutoViewMatrixRestore() {
            fDrawTarget = NULL;
        }

        AutoViewMatrixRestore(GrDrawTarget* target)
            : fDrawTarget(target), fMatrix(fDrawTarget->getViewMatrix()) {
            GrAssert(NULL != target);
        }

        void set(GrDrawTarget* target) {
            GrAssert(NULL != target);
            if (NULL != fDrawTarget) {
                fDrawTarget->setViewMatrix(fMatrix);
            }
            fDrawTarget = target;
            fMatrix = target->getViewMatrix();
        }

        ~AutoViewMatrixRestore() {
            if (NULL != fDrawTarget) {
                fDrawTarget->setViewMatrix(fMatrix);
            }
        }

    private:
        GrDrawTarget*       fDrawTarget;
        GrMatrix            fMatrix;
    };

    ////////////////////////////////////////////////////////////////////////////

    /**
     * Sets the view matrix to I and preconcats all stage matrices enabled in
     * mask by the view inverse. Destructor undoes these changes.
     */
    class AutoDeviceCoordDraw : ::GrNoncopyable {
    public:
        AutoDeviceCoordDraw(GrDrawTarget* target, int stageMask);
        ~AutoDeviceCoordDraw();
    private:
        GrDrawTarget*       fDrawTarget;
        GrMatrix            fViewMatrix;
        GrMatrix            fSamplerMatrices[kNumStages];
        int                 fStageMask;
    };

    ////////////////////////////////////////////////////////////////////////////

    class AutoReleaseGeometry : ::GrNoncopyable {
    public:
        AutoReleaseGeometry(GrDrawTarget*  target,
                            GrVertexLayout vertexLayout,
                            int            vertexCount,
                            int            indexCount);
        AutoReleaseGeometry();
        ~AutoReleaseGeometry();
        bool set(GrDrawTarget*  target,
                 GrVertexLayout vertexLayout,
                 int            vertexCount,
                 int            indexCount);
        bool succeeded() const { return NULL != fTarget; }
        void* vertices() const { return fVertices; }
        void* indices() const { return fIndices; }
        GrPoint* positions() const {
            return static_cast<GrPoint*>(fVertices);
        }

    private:
        void reset();

        GrDrawTarget* fTarget;
        void*         fVertices;
        void*         fIndices;
    };

    ////////////////////////////////////////////////////////////////////////////

    class AutoClipRestore : ::GrNoncopyable {
    public:
        AutoClipRestore(GrDrawTarget* target) {
            fTarget = target;
            fClip = fTarget->getClip();
        }

        ~AutoClipRestore() {
            fTarget->setClip(fClip);
        }
    private:
        GrDrawTarget* fTarget;
        GrClip        fClip;
    };

    ////////////////////////////////////////////////////////////////////////////

    class AutoGeometryPush : ::GrNoncopyable {
    public:
        AutoGeometryPush(GrDrawTarget* target) {
            GrAssert(NULL != target);
            fTarget = target;
            target->pushGeometrySource();
        }
        ~AutoGeometryPush() {
            fTarget->popGeometrySource();
        }
    private:
        GrDrawTarget* fTarget;
    };

    ////////////////////////////////////////////////////////////////////////////
    // Helpers for picking apart vertex layouts

    /**
     * Helper function to compute the size of a vertex from a vertex layout
     * @return size of a single vertex.
     */
    static size_t VertexSize(GrVertexLayout vertexLayout);

    /**
     * Helper function for determining the index of texture coordinates that
     * is input for a texture stage. Note that a stage may instead use positions
     * as texture coordinates, in which case the result of the function is
     * indistinguishable from the case when the stage is disabled.
     *
     * @param stage         the stage to query
     * @param vertexLayout  layout to query
     *
     * @return the texture coordinate index or -1 if the stage doesn't use
     *         separate (non-position) texture coordinates.
     */
    static int VertexTexCoordsForStage(int stage, GrVertexLayout vertexLayout);

    /**
     * Helper function to compute the offset of texture coordinates in a vertex
     * @return offset of texture coordinates in vertex layout or -1 if the
     *         layout has no texture coordinates. Will be 0 if positions are
     *         used as texture coordinates for the stage.
     */
    static int VertexStageCoordOffset(int stage, GrVertexLayout vertexLayout);

    /**
     * Helper function to compute the offset of the color in a vertex
     * @return offset of color in vertex layout or -1 if the
     *         layout has no color.
     */
    static int VertexColorOffset(GrVertexLayout vertexLayout);

    /**
     * Helper function to determine if vertex layout contains explicit texture
     * coordinates of some index.
     *
     * @param coordIndex    the tex coord index to query
     * @param vertexLayout  layout to query
     *
     * @return true if vertex specifies texture coordinates for the index,
     *              false otherwise.
     */
    static bool VertexUsesTexCoordIdx(int coordIndex,
                                      GrVertexLayout vertexLayout);

    /**
     * Helper function to determine if vertex layout contains either explicit or
     * implicit texture coordinates for a stage.
     *
     * @param stage         the stage to query
     * @param vertexLayout  layout to query
     *
     * @return true if vertex specifies texture coordinates for the stage,
     *              false otherwise.
     */
    static bool VertexUsesStage(int stage, GrVertexLayout vertexLayout);

    /**
     * Helper function to compute the size of each vertex and the offsets of
     * texture coordinates and color. Determines tex coord offsets by tex coord
     * index rather than by stage. (Each stage can be mapped to any t.c. index
     * by StageTexCoordVertexLayoutBit.)
     *
     * @param vertexLayout          the layout to query
     * @param texCoordOffsetsByIdx  after return it is the offset of each
     *                              tex coord index in the vertex or -1 if
     *                              index isn't used.
     * @return size of a single vertex
     */
    static int VertexSizeAndOffsetsByIdx(GrVertexLayout vertexLayout,
                                         int texCoordOffsetsByIdx[kMaxTexCoords],
                                         int *colorOffset);

    /**
     * Helper function to compute the size of each vertex and the offsets of
     * texture coordinates and color. Determines tex coord offsets by stage
     * rather than by index. (Each stage can be mapped to any t.c. index
     * by StageTexCoordVertexLayoutBit.) If a stage uses positions for
     * tex coords then that stage's offset will be 0 (positions are always at 0).
     *
     * @param vertexLayout              the layout to query
     * @param texCoordOffsetsByStage    after return it is the offset of each
     *                                  tex coord index in the vertex or -1 if
     *                                  index isn't used.
     * @return size of a single vertex
     */
    static int VertexSizeAndOffsetsByStage(GrVertexLayout vertexLayout,
                                           int texCoordOffsetsByStage[kNumStages],
                                           int *colorOffset);

    /**
     * Accessing positions, texture coords, or colors, of a vertex within an
     * array is a hassle involving casts and simple math. These helpers exist
     * to keep GrDrawTarget clients' code a bit nicer looking.
     */

    /**
     * Gets a pointer to a GrPoint of a vertex's position or texture
     * coordinate.
     * @param vertices      the vetex array
     * @param vertexIndex   the index of the vertex in the array
     * @param vertexSize    the size of each vertex in the array
     * @param offset        the offset in bytes of the vertex component.
     *                      Defaults to zero (corresponding to vertex position)
     * @return pointer to the vertex component as a GrPoint
     */
    static GrPoint* GetVertexPoint(void* vertices,
                                   int vertexIndex,
                                   int vertexSize,
                                   int offset = 0) {
        intptr_t start = GrTCast<intptr_t>(vertices);
        return GrTCast<GrPoint*>(start + offset +
                                 vertexIndex * vertexSize);
    }
    static const GrPoint* GetVertexPoint(const void* vertices,
                                         int vertexIndex,
                                         int vertexSize,
                                         int offset = 0) {
        intptr_t start = GrTCast<intptr_t>(vertices);
        return GrTCast<const GrPoint*>(start + offset +
                                       vertexIndex * vertexSize);
    }

    /**
     * Gets a pointer to a GrColor inside a vertex within a vertex array.
     * @param vertices      the vetex array
     * @param vertexIndex   the index of the vertex in the array
     * @param vertexSize    the size of each vertex in the array
     * @param offset        the offset in bytes of the vertex color
     * @return pointer to the vertex component as a GrColor
     */
    static GrColor* GetVertexColor(void* vertices,
                                   int vertexIndex,
                                   int vertexSize,
                                   int offset) {
        intptr_t start = GrTCast<intptr_t>(vertices);
        return GrTCast<GrColor*>(start + offset +
                                 vertexIndex * vertexSize);
    }
    static const GrColor* GetVertexColor(const void* vertices,
                                         int vertexIndex,
                                         int vertexSize,
                                         int offset) {
        const intptr_t start = GrTCast<intptr_t>(vertices);
        return GrTCast<const GrColor*>(start + offset +
                                       vertexIndex * vertexSize);
    }

    static void VertexLayoutUnitTest();

protected:

    enum GeometrySrcType {
        kNone_GeometrySrcType,     //<! src has not been specified
        kReserved_GeometrySrcType, //<! src was set using reserve*Space
        kArray_GeometrySrcType,    //<! src was set using set*SourceToArray
        kBuffer_GeometrySrcType    //<! src was set using set*SourceToBuffer
    };

    struct GeometrySrcState {
        GeometrySrcType         fVertexSrc;
        union {
            // valid if src type is buffer
            const GrVertexBuffer*   fVertexBuffer;
            // valid if src type is reserved or array
            int                     fVertexCount;
        };

        GeometrySrcType         fIndexSrc;
        union {
            // valid if src type is buffer
            const GrIndexBuffer*    fIndexBuffer;
            // valid if src type is reserved or array
            int                     fIndexCount;
        };

        GrVertexLayout          fVertexLayout;
    };

    // given a vertex layout and a draw state, will a stage be used?
    static bool StageWillBeUsed(int stage, GrVertexLayout layout,
                         const DrState& state) {
        return NULL != state.fTextures[stage] && VertexUsesStage(stage, layout);
    }

    bool isStageEnabled(int stage) const {
        return StageWillBeUsed(stage, this->getGeomSrc().fVertexLayout,
                               fCurrDrawState);
    }

    // Helpers for GrDrawTarget subclasses that won't have private access to
    // SavedDrawState but need to peek at the state values.
    static DrState& accessSavedDrawState(SavedDrawState& sds)
                                                        { return sds.fState; }
    static const DrState& accessSavedDrawState(const SavedDrawState& sds)
                                                        { return sds.fState; }

    // implemented by subclass to allocate space for reserved geom
    virtual bool onReserveVertexSpace(GrVertexLayout vertexLayout,
                                      int vertexCount,
                                      void** vertices) = 0;
    virtual bool onReserveIndexSpace(int indexCount, void** indices) = 0;
    // implemented by subclass to handle release of reserved geom space
    virtual void releaseReservedVertexSpace() = 0;
    virtual void releaseReservedIndexSpace() = 0;
    // subclass must consume array contents when set
    virtual void onSetVertexSourceToArray(const void* vertexArray,
                                          int vertexCount) = 0;
    virtual void onSetIndexSourceToArray(const void* indexArray,
                                         int indexCount) = 0;
    // subclass is notified that geom source will be set away from an array
    virtual void releaseVertexArray() = 0;
    virtual void releaseIndexArray() = 0;
    // subclass overrides to be notified just before geo src state
    // is pushed/popped.
    virtual void geometrySourceWillPush() = 0;
    virtual void geometrySourceWillPop(const GeometrySrcState& restoredState) = 0;
    // subclass called to perform drawing
    virtual void onDrawIndexed(GrPrimitiveType type,
                               int startVertex,
                               int startIndex,
                               int vertexCount,
                               int indexCount) = 0;
    virtual void onDrawNonIndexed(GrPrimitiveType type,
                                  int startVertex,
                                  int vertexCount) = 0;
    // subclass overrides to be notified when clip is set.
    virtual void clipWillBeSet(const GrClip& clip) = 0;

    // Helpers for drawRect, protected so subclasses that override drawRect
    // can use them.
    static GrVertexLayout GetRectVertexLayout(StageBitfield stageEnableBitfield,
                                              const GrRect* srcRects[]);

    static void SetRectVertices(const GrRect& rect,
                                const GrMatrix* matrix,
                                const GrRect* srcRects[],
                                const GrMatrix* srcMatrices[],
                                GrVertexLayout layout,
                                void* vertices);

    // accessor for derived classes
    const GeometrySrcState& getGeomSrc() const {
        return fGeoSrcStateStack.back();
    }

    GrClip fClip;

    DrState fCurrDrawState;

private:
    // called when setting a new vert/idx source to unref prev vb/ib
    void releasePreviousVertexSource();
    void releasePreviousIndexSource();

    enum {
        kPreallocGeoSrcStateStackCnt = 4,
    };
    GrAlignedSTStorage<kPreallocGeoSrcStateStackCnt,
                        GeometrySrcState>
                                     fGeoSrcStateStackStorage;
    GrTArray<GeometrySrcState, true> fGeoSrcStateStack;

};

#endif


code:
/*
    Copyright 2010 Google Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

#ifndef GrFontScaler_DEFINED
#define GrFontScaler_DEFINED

#include "GrGlyph.h"
#include "GrKey.h"

class SkPath;

/**
 *  This is a virtual base class which Gr's interface to the host platform's
 *  font scaler.
 *
 *  The client is responsible for subclassing, and instantiating this. The
 *  instance is create for a specific font+size+matrix.
 */
class GrFontScaler : public GrRefCnt {
public:
    virtual const GrKey* getKey() = 0;
    virtual GrMaskFormat getMaskFormat() = 0;
    virtual bool getPackedGlyphBounds(GrGlyph::PackedID, GrIRect* bounds) = 0;
    virtual bool getPackedGlyphImage(GrGlyph::PackedID, int width, int height,
                                     int rowBytes, void* image) = 0;
    virtual bool getGlyphPath(uint16_t glyphID, SkPath*) = 0;
};

#endif

license: mit


code:
/*
    Copyright 2011 Google Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

#ifndef GrGLConfig_DEFINED
#define GrGLConfig_DEFINED

#include "GrTypes.h"
#include "GrGLDefines.h"

/**
 * Optional GL config file.
 */
#ifdef GR_GL_CUSTOM_SETUP_HEADER
    #include GR_GL_CUSTOM_SETUP_HEADER
#endif

#if !defined(GR_GL_FUNCTION_TYPE)
    #define GR_GL_FUNCTION_TYPE
#endif

/**
 * The following are optional defines that can be enabled at the compiler
 * command line, in a IDE project, in a GrUserConfig.h file, or in a GL custom
 * file (if one is in use). If a GR_GL_CUSTOM_SETUP_HEADER is used they can
 * also be placed there.
 *
 * GR_GL_LOG_CALLS: if 1 Gr can print every GL call using GrPrintf. Defaults to
 * 0. Logging can be enabled and disabled at runtime using a debugger via to
 * global gLogCallsGL. The initial value of gLogCallsGL is controlled by
 * GR_GL_LOG_CALLS_START.
 *
 * GR_GL_LOG_CALLS_START: controls the initial value of gLogCallsGL when
 * GR_GL_LOG_CALLS is 1. Defaults to 0.
 *
 * GR_GL_CHECK_ERROR: if enabled Gr can do a glGetError() after every GL call.
 * Defaults to 1 if GR_DEBUG is set, otherwise 0. When GR_GL_CHECK_ERROR is 1
 * this can be toggled in a debugger using the gCheckErrorGL global. The initial
 * value of gCheckErrorGL is controlled by by GR_GL_CHECK_ERROR_START.
 *
 * GR_GL_CHECK_ERROR_START: controls the initial value of gCheckErrorGL
 * when GR_GL_CHECK_ERROR is 1.  Defaults to 1.
 *
 * GR_GL_NO_CONSTANT_ATTRIBUTES: if this evaluates to true then the GL backend
 * will use uniforms instead of attributes in all cases when there is not
 * per-vertex data. This is important when the underlying GL implementation
 * doesn't actually support immediate style attribute values (e.g. when
 * the GL stream is converted to DX as in ANGLE on Chrome). Defaults to 0.
 *
 * GR_GL_ATTRIBUTE_MATRICES: If changing uniforms is very expensive it may be
 * faster to use vertex attributes for matrices (set via glVertexAttrib3fv).
 * Setting this build flag enables this behavior. GR_GL_NO_CONSTANT_ATTRIBUTES
 * must not be set since this uses constant attributes for the matrices.
 * Defaults to 0.
 */

#if !defined(GR_GL_LOG_CALLS)
    #define GR_GL_LOG_CALLS                 0
#endif

#if !defined(GR_GL_LOG_CALLS_START)
    #define GR_GL_LOG_CALLS_START           0
#endif

#if !defined(GR_GL_CHECK_ERROR)
    #define GR_GL_CHECK_ERROR               GR_DEBUG
#endif

#if !defined(GR_GL_CHECK_ERROR_START)
    #define GR_GL_CHECK_ERROR_START         1
#endif

#if !defined(GR_GL_NO_CONSTANT_ATTRIBUTES)
    #define GR_GL_NO_CONSTANT_ATTRIBUTES    0
#endif

#if !defined(GR_GL_ATTRIBUTE_MATRICES)
    #define GR_GL_ATTRIBUTE_MATRICES        0
#endif

#if(GR_GL_NO_CONSTANT_ATTRIBUTES) && (GR_GL_ATTRIBUTE_MATRICES)
    #error "Cannot combine GR_GL_NO_CONSTANT_ATTRIBUTES and GR_GL_ATTRIBUTE_MATRICES"
#endif

////////////////////////////////////////////////////////////////////////////////

/**
 * The following macros are used to staticlly configure the default
 * GrGLInterface, but should not be used outside of the GrGLInterface
 * scaffolding.  Undefine here to prevent accidental use.
 */
#undef GR_SUPPORT_GLDESKTOP
#undef GR_SUPPORT_GLES1
#undef GR_SUPPORT_GLES2
#undef GR_SUPPORT_GLES

////////////////////////////////////////////////////////////////////////////////

#if GR_SCALAR_IS_FIXED
    #define GrGLType   GL_FIXED
#elif GR_SCALAR_IS_FLOAT
    #define GrGLType   GR_GL_FLOAT
#else
    #error "unknown GR_SCALAR type"
#endif

#if GR_TEXT_SCALAR_IS_USHORT
    #define GrGLTextType                    GR_GL_UNSIGNED_SHORT
    #define GR_GL_TEXT_TEXTURE_NORMALIZED   1
#elif GR_TEXT_SCALAR_IS_FLOAT
    #define GrGLTextType                    GR_GL_FLOAT
    #define GR_GL_TEXT_TEXTURE_NORMALIZED   0
#elif GR_TEXT_SCALAR_IS_FIXED
    #define GrGLTextType                    GR_GL_FIXED
    #define GR_GL_TEXT_TEXTURE_NORMALIZED   0
#else
    #error "unknown GR_TEXT_SCALAR type"
#endif

// Pick a pixel config for 32bit bitmaps. Our default is GL_RGBA (except on
// Windows where we match GDI's order).
#ifndef GR_GL_32BPP_COLOR_FORMAT
    #if GR_WIN32_BUILD || GR_LINUX_BUILD || GR_QNX_BUILD
        #define GR_GL_32BPP_COLOR_FORMAT    GR_GL_BGRA
    #else
        #define GR_GL_32BPP_COLOR_FORMAT    GR_GL_RGBA
    #endif
#endif

////////////////////////////////////////////////////////////////////////////////

extern void GrGLCheckErr(const char* location, const char* call);

extern void GrGLClearErr();

#if GR_GL_CHECK_ERROR
    extern bool gCheckErrorGL;
    #define GR_GL_CHECK_ERROR_IMPL(X) if (gCheckErrorGL) GrGLCheckErr(GR_FILE_AND_LINE_STR, #X)
#else
    #define GR_GL_CHECK_ERROR_IMPL(X)
#endif

#if GR_GL_LOG_CALLS
    extern bool gLogCallsGL;
    #define GR_GL_LOG_CALLS_IMPL(X) if (gLogCallsGL) GrPrintf(GR_FILE_AND_LINE_STR "GL: " #X "\n")
#else
    #define GR_GL_LOG_CALLS_IMPL(X)
#endif

#define GR_GL(X)                 GrGLGetGLInterface()->f##X;; GR_GL_LOG_CALLS_IMPL(X); GR_GL_CHECK_ERROR_IMPL(X);
#define GR_GL_NO_ERR(X)          GrGLGetGLInterface()->f##X;; GR_GL_LOG_CALLS_IMPL(X);

#define GR_GL_SUPPORT_DESKTOP   (kDesktop_GrGLBinding == GrGLGetGLInterface()->fBindingsExported)
#define GR_GL_SUPPORT_ES1       (kES1_GrGLBinding == GrGLGetGLInterface()->fBindingsExported)
#define GR_GL_SUPPORT_ES2       (kES2_GrGLBinding == GrGLGetGLInterface()->fBindingsExported)
#define GR_GL_SUPPORT_ES        (GR_GL_SUPPORT_ES1 || GR_GL_SUPPORT_ES2)

////////////////////////////////////////////////////////////////////////////////

/**
 *  GrGLRestoreResetRowLength() will reset GL_UNPACK_ROW_LENGTH to 0. We write
 *  this wrapper, since GL_UNPACK_ROW_LENGTH is not available on all GL versions
 */
extern void GrGLRestoreResetRowLength();

////////////////////////////////////////////////////////////////////////////////

/**
 *  Some drivers want the var-int arg to be zero-initialized on input.
 */
#define GR_GL_INIT_ZERO     0
#define GR_GL_GetIntegerv(e, p)     \
    do {                            \
        *(p) = GR_GL_INIT_ZERO;     \
        GR_GL(GetIntegerv(e, p));   \
    } while (0)

////////////////////////////////////////////////////////////////////////////////

#endif


code:
#ifndef GrGLConfig_chrome_DEFINED
#define GrGLConfig_chrome_DEFINED

// chrome always assumes BGRA
#define GR_GL_32BPP_COLOR_FORMAT        GR_GL_BGRA

// glGetError() forces a sync with gpu process on chrome
#define GR_GL_CHECK_ERROR_START         0

// ANGLE creates a temp VB for vertex attributes not specified per-vertex.
#define GR_GL_NO_CONSTANT_ATTRIBUTES    GR_WIN32_BUILD

#endif


code:
/*
    Copyright 2011 Google Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

#ifndef GrGLDefines_DEFINED
#define GrGLDefines_DEFINED

// The following constants consist of the intersection of GL constants
// exported by GLES 1.0, GLES 2.0, and desktop GL required by the system.

#define GR_GL_DEPTH_BUFFER_BIT               0x00000100
#define GR_GL_STENCIL_BUFFER_BIT             0x00000400
#define GR_GL_COLOR_BUFFER_BIT               0x00004000

/* Boolean */
#define GR_GL_FALSE                          0
#define GR_GL_TRUE                           1

/* BeginMode */
#define GR_GL_POINTS                         0x0000
#define GR_GL_LINES                          0x0001
#define GR_GL_LINE_LOOP                      0x0002
#define GR_GL_LINE_STRIP                     0x0003
#define GR_GL_TRIANGLES                      0x0004
#define GR_GL_TRIANGLE_STRIP                 0x0005
#define GR_GL_TRIANGLE_FAN                   0x0006

/* AlphaFunction (not supported in ES20) */
/*      GL_NEVER */
/*      GL_LESS */
/*      GL_EQUAL */
/*      GL_LEQUAL */
/*      GL_GREATER */
/*      GL_NOTEQUAL */
/*      GL_GEQUAL */
/*      GL_ALWAYS */

/* BlendingFactorDest */
#define GR_GL_ZERO                           0
#define GR_GL_ONE                            1
#define GR_GL_SRC_COLOR                      0x0300
#define GR_GL_ONE_MINUS_SRC_COLOR            0x0301
#define GR_GL_SRC_ALPHA                      0x0302
#define GR_GL_ONE_MINUS_SRC_ALPHA            0x0303
#define GR_GL_DST_ALPHA                      0x0304
#define GR_GL_ONE_MINUS_DST_ALPHA            0x0305

/* BlendingFactorSrc */
/*      GL_ZERO */
/*      GL_ONE */
#define GR_GL_DST_COLOR                      0x0306
#define GR_GL_ONE_MINUS_DST_COLOR            0x0307
#define GR_GL_SRC_ALPHA_SATURATE             0x0308
/*      GL_SRC_ALPHA */
/*      GL_ONE_MINUS_SRC_ALPHA */
/*      GL_DST_ALPHA */
/*      GL_ONE_MINUS_DST_ALPHA */

/* ExtendedBlendFactors */
#define GR_GL_SRC1_COLOR                     0x88F9
#define GR_GL_ONE_MINUS_SRC1_COLOR           0x88FA
/*      GL_SRC1_ALPHA */
#define GR_GL_ONE_MINUS_SRC1_ALPHA           0x88FB

/* BlendEquationSeparate */
#define GR_GL_FUNC_ADD                       0x8006
#define GR_GL_BLEND_EQUATION                 0x8009
#define GR_GL_BLEND_EQUATION_RGB             0x8009    /* same as BLEND_EQUATION */
#define GR_GL_BLEND_EQUATION_ALPHA           0x883D

/* BlendSubtract */
#define GR_GL_FUNC_SUBTRACT                  0x800A
#define GR_GL_FUNC_REVERSE_SUBTRACT          0x800B

/* Separate Blend Functions */
#define GR_GL_BLEND_DST_RGB                  0x80C8
#define GR_GL_BLEND_SRC_RGB                  0x80C9
#define GR_GL_BLEND_DST_ALPHA                0x80CA
#define GR_GL_BLEND_SRC_ALPHA                0x80CB
#define GR_GL_CONSTANT_COLOR                 0x8001
#define GR_GL_ONE_MINUS_CONSTANT_COLOR       0x8002
#define GR_GL_CONSTANT_ALPHA                 0x8003
#define GR_GL_ONE_MINUS_CONSTANT_ALPHA       0x8004
#define GR_GL_BLEND_COLOR                    0x8005

/* Buffer Objects */
#define GR_GL_ARRAY_BUFFER                   0x8892
#define GR_GL_ELEMENT_ARRAY_BUFFER           0x8893
#define GR_GL_ARRAY_BUFFER_BINDING           0x8894
#define GR_GL_ELEMENT_ARRAY_BUFFER_BINDING   0x8895

#define GR_GL_STREAM_DRAW                    0x88E0
#define GR_GL_STATIC_DRAW                    0x88E4
#define GR_GL_DYNAMIC_DRAW                   0x88E8

#define GR_GL_BUFFER_SIZE                    0x8764
#define GR_GL_BUFFER_USAGE                   0x8765

#define GR_GL_CURRENT_VERTEX_ATTRIB          0x8626

/* CullFaceMode */
#define GR_GL_FRONT                          0x0404
#define GR_GL_BACK                           0x0405
#define GR_GL_FRONT_AND_BACK                 0x0408

/* DepthFunction */
/*      GL_NEVER */
/*      GL_LESS */
/*      GL_EQUAL */
/*      GL_LEQUAL */
/*      GL_GREATER */
/*      GL_NOTEQUAL */
/*      GL_GEQUAL */
/*      GL_ALWAYS */

/* EnableCap */
#define GR_GL_TEXTURE_2D                     0x0DE1
#define GR_GL_CULL_FACE                      0x0B44
#define GR_GL_BLEND                          0x0BE2
#define GR_GL_DITHER                         0x0BD0
#define GR_GL_STENCIL_TEST                   0x0B90
#define GR_GL_DEPTH_TEST                     0x0B71
#define GR_GL_SCISSOR_TEST                   0x0C11
#define GR_GL_POLYGON_OFFSET_FILL            0x8037
#define GR_GL_SAMPLE_ALPHA_TO_COVERAGE       0x809E
#define GR_GL_SAMPLE_COVERAGE                0x80A0

/* ErrorCode */
#define GR_GL_NO_ERROR                       0
#define GR_GL_INVALID_ENUM                   0x0500
#define GR_GL_INVALID_VALUE                  0x0501
#define GR_GL_INVALID_OPERATION              0x0502
#define GR_GL_OUT_OF_MEMORY                  0x0505
#define GR_GL_CONTEXT_LOST                   0x300E  // TODO(gman): What value?

/* FrontFaceDirection */
#define GR_GL_CW                             0x0900
#define GR_GL_CCW                            0x0901

/* GetPName */
#define GR_GL_LINE_WIDTH                     0x0B21
#define GR_GL_ALIASED_POINT_SIZE_RANGE       0x846D
#define GR_GL_ALIASED_LINE_WIDTH_RANGE       0x846E
#define GR_GL_CULL_FACE_MODE                 0x0B45
#define GR_GL_FRONT_FACE                     0x0B46
#define GR_GL_DEPTH_RANGE                    0x0B70
#define GR_GL_DEPTH_WRITEMASK                0x0B72
#define GR_GL_DEPTH_CLEAR_VALUE              0x0B73
#define GR_GL_DEPTH_FUNC                     0x0B74
#define GR_GL_STENCIL_CLEAR_VALUE            0x0B91
#define GR_GL_STENCIL_FUNC                   0x0B92
#define GR_GL_STENCIL_FAIL                   0x0B94
#define GR_GL_STENCIL_PASS_DEPTH_FAIL        0x0B95
#define GR_GL_STENCIL_PASS_DEPTH_PASS        0x0B96
#define GR_GL_STENCIL_REF                    0x0B97
#define GR_GL_STENCIL_VALUE_MASK             0x0B93
#define GR_GL_STENCIL_WRITEMASK              0x0B98
#define GR_GL_STENCIL_BACK_FUNC              0x8800
#define GR_GL_STENCIL_BACK_FAIL              0x8801
#define GR_GL_STENCIL_BACK_PASS_DEPTH_FAIL   0x8802
#define GR_GL_STENCIL_BACK_PASS_DEPTH_PASS   0x8803
#define GR_GL_STENCIL_BACK_REF               0x8CA3
#define GR_GL_STENCIL_BACK_VALUE_MASK        0x8CA4
#define GR_GL_STENCIL_BACK_WRITEMASK         0x8CA5
#define GR_GL_VIEWPORT                       0x0BA2
#define GR_GL_SCISSOR_BOX                    0x0C10
/*      GL_SCISSOR_TEST */
#define GR_GL_COLOR_CLEAR_VALUE              0x0C22
#define GR_GL_COLOR_WRITEMASK                0x0C23
#define GR_GL_UNPACK_ALIGNMENT               0x0CF5
#define GR_GL_PACK_ALIGNMENT                 0x0D05
#define GR_GL_MAX_TEXTURE_SIZE               0x0D33
#define GR_GL_MAX_VIEWPORT_DIMS              0x0D3A
#define GR_GL_SUBPIXEL_BITS                  0x0D50
#define GR_GL_RED_BITS                       0x0D52
#define GR_GL_GREEN_BITS                     0x0D53
#define GR_GL_BLUE_BITS                      0x0D54
#define GR_GL_ALPHA_BITS                     0x0D55
#define GR_GL_DEPTH_BITS                     0x0D56
#define GR_GL_STENCIL_BITS                   0x0D57
#define GR_GL_POLYGON_OFFSET_UNITS           0x2A00
/*      GL_POLYGON_OFFSET_FILL */
#define GR_GL_POLYGON_OFFSET_FACTOR          0x8038
#define GR_GL_TEXTURE_BINDING_2D             0x8069
#define GR_GL_SAMPLE_BUFFERS                 0x80A8
#define GR_GL_SAMPLES                        0x80A9
#define GR_GL_SAMPLE_COVERAGE_VALUE          0x80AA
#define GR_GL_SAMPLE_COVERAGE_INVERT         0x80AB

/* GetTextureParameter */
/*      GL_TEXTURE_MAG_FILTER */
/*      GL_TEXTURE_MIN_FILTER */
/*      GL_TEXTURE_WRAP_S */
/*      GL_TEXTURE_WRAP_T */

#define GR_GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2
#define GR_GL_COMPRESSED_TEXTURE_FORMATS     0x86A3

/* HintMode */
#define GR_GL_DONT_CARE                      0x1100
#define GR_GL_FASTEST                        0x1101
#define GR_GL_NICEST                         0x1102

/* HintTarget */
#define GR_GL_GENERATE_MIPMAP_HINT            0x8192

/* DataType */
#define GR_GL_BYTE                           0x1400
#define GR_GL_UNSIGNED_BYTE                  0x1401
#define GR_GL_SHORT                          0x1402
#define GR_GL_UNSIGNED_SHORT                 0x1403
#define GR_GL_INT                            0x1404
#define GR_GL_UNSIGNED_INT                   0x1405
#define GR_GL_FLOAT                          0x1406
#define GR_GL_FIXED                          0x140C

/* Lighting */
#define GR_GL_LIGHTING                       0x0B50
#define GR_GL_LIGHT0                         0x4000
#define GR_GL_LIGHT1                         0x4001
#define GR_GL_LIGHT2                         0x4002
#define GR_GL_LIGHT3                         0x4003
#define GR_GL_LIGHT4                         0x4004
#define GR_GL_LIGHT5                         0x4005
#define GR_GL_LIGHT6                         0x4006
#define GR_GL_LIGHT7                         0x4007
#define GR_GL_SPOT_EXPONENT                  0x1205
#define GR_GL_SPOT_CUTOFF                    0x1206
#define GR_GL_CONSTANT_ATTENUATION           0x1207
#define GR_GL_LINEAR_ATTENUATION             0x1208
#define GR_GL_QUADRATIC_ATTENUATION          0x1209
#define GR_GL_AMBIENT                        0x1200
#define GR_GL_DIFFUSE                        0x1201
#define GR_GL_SPECULAR                       0x1202
#define GR_GL_SHININESS                      0x1601
#define GR_GL_EMISSION                       0x1600
#define GR_GL_POSITION                       0x1203
#define GR_GL_SPOT_DIRECTION                 0x1204
#define GR_GL_AMBIENT_AND_DIFFUSE            0x1602
#define GR_GL_COLOR_INDEXES                  0x1603
#define GR_GL_LIGHT_MODEL_TWO_SIDE           0x0B52
#define GR_GL_LIGHT_MODEL_LOCAL_VIEWER       0x0B51
#define GR_GL_LIGHT_MODEL_AMBIENT            0x0B53
#define GR_GL_FRONT_AND_BACK                 0x0408
#define GR_GL_SHADE_MODEL                    0x0B54
#define GR_GL_FLAT                           0x1D00
#define GR_GL_SMOOTH                         0x1D01
#define GR_GL_COLOR_MATERIAL                 0x0B57
#define GR_GL_COLOR_MATERIAL_FACE            0x0B55
#define GR_GL_COLOR_MATERIAL_PARAMETER       0x0B56
#define GR_GL_NORMALIZE                      0x0BA1

/* Matrix Mode */
#define GR_GL_MATRIX_MODE                    0x0BA0
#define GR_GL_MODELVIEW                      0x1700
#define GR_GL_PROJECTION                     0x1701
#define GR_GL_TEXTURE                        0x1702

/* multisample */
#define GR_GL_MULTISAMPLE                    0x809D

/* Points */
#define GR_GL_POINT_SMOOTH                   0x0B10
#define GR_GL_POINT_SIZE                     0x0B11
#define GR_GL_POINT_SIZE_GRANULARITY         0x0B13
#define GR_GL_POINT_SIZE_RANGE               0x0B12

/* Lines */
#define GR_GL_LINE_SMOOTH                    0x0B20
#define GR_GL_LINE_STIPPLE                   0x0B24
#define GR_GL_LINE_STIPPLE_PATTERN           0x0B25
#define GR_GL_LINE_STIPPLE_REPEAT            0x0B26
#define GR_GL_LINE_WIDTH                     0x0B21
#define GR_GL_LINE_WIDTH_GRANULARITY         0x0B23
#define GR_GL_LINE_WIDTH_RANGE               0x0B22

/* PixelFormat */
#define GR_GL_DEPTH_COMPONENT                0x1902
#define GR_GL_ALPHA                          0x1906
#define GR_GL_RGB                            0x1907
#define GR_GL_RGBA                           0x1908
#define GR_GL_BGRA                           0x80E1
#define GR_GL_LUMINANCE                      0x1909
#define GR_GL_LUMINANCE_ALPHA                0x190A
#define GR_GL_PALETTE8_RGBA8                 0x8B96

/* PixelType */
/*      GL_UNSIGNED_BYTE */
#define GR_GL_UNSIGNED_SHORT_4_4_4_4         0x8033
#define GR_GL_UNSIGNED_SHORT_5_5_5_1         0x8034
#define GR_GL_UNSIGNED_SHORT_5_6_5           0x8363

/* Shaders */
#define GR_GL_FRAGMENT_SHADER                  0x8B30
#define GR_GL_VERTEX_SHADER                    0x8B31
#define GR_GL_MAX_VERTEX_ATTRIBS               0x8869
#define GR_GL_MAX_VERTEX_UNIFORM_VECTORS       0x8DFB
#define GR_GL_MAX_VARYING_VECTORS              0x8DFC
#define GR_GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D
#define GR_GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS   0x8B4C
#define GR_GL_MAX_TEXTURE_IMAGE_UNITS          0x8872
#define GR_GL_MAX_FRAGMENT_UNIFORM_VECTORS     0x8DFD
#define GR_GL_SHADER_TYPE                      0x8B4F
#define GR_GL_DELETE_STATUS                    0x8B80
#define GR_GL_LINK_STATUS                      0x8B82
#define GR_GL_VALIDATE_STATUS                  0x8B83
#define GR_GL_ATTACHED_SHADERS                 0x8B85
#define GR_GL_ACTIVE_UNIFORMS                  0x8B86
#define GR_GL_ACTIVE_UNIFORM_MAX_LENGTH        0x8B87
#define GR_GL_ACTIVE_ATTRIBUTES                0x8B89
#define GR_GL_ACTIVE_ATTRIBUTE_MAX_LENGTH      0x8B8A
#define GR_GL_SHADING_LANGUAGE_VERSION         0x8B8C
#define GR_GL_CURRENT_PROGRAM                  0x8B8D
#define GR_GL_MAX_FRAGMENT_UNIFORM_COMPONENTS  0x8B49
#define GR_GL_MAX_VERTEX_UNIFORM_COMPONENTS    0x8B4A

/* StencilFunction */
#define GR_GL_NEVER                          0x0200
#define GR_GL_LESS                           0x0201
#define GR_GL_EQUAL                          0x0202
#define GR_GL_LEQUAL                         0x0203
#define GR_GL_GREATER                        0x0204
#define GR_GL_NOTEQUAL                       0x0205
#define GR_GL_GEQUAL                         0x0206
#define GR_GL_ALWAYS                         0x0207

/* StencilOp */
/*      GL_ZERO */
#define GR_GL_KEEP                           0x1E00
#define GR_GL_REPLACE                        0x1E01
#define GR_GL_INCR                           0x1E02
#define GR_GL_DECR                           0x1E03
#define GR_GL_INVERT                         0x150A
#define GR_GL_INCR_WRAP                      0x8507
#define GR_GL_DECR_WRAP                      0x8508

/* StringName */
#define GR_GL_VENDOR                         0x1F00
#define GR_GL_RENDERER                       0x1F01
#define GR_GL_VERSION                        0x1F02
#define GR_GL_EXTENSIONS                     0x1F03

/* Pixel Mode / Transfer */
#define GR_GL_UNPACK_ROW_LENGTH            0x0CF2

/* TextureMagFilter */
#define GR_GL_NEAREST                        0x2600
#define GR_GL_LINEAR                         0x2601

/* TextureMinFilter */
/*      GL_NEAREST */
/*      GL_LINEAR */
#define GR_GL_NEAREST_MIPMAP_NEAREST         0x2700
#define GR_GL_LINEAR_MIPMAP_NEAREST          0x2701
#define GR_GL_NEAREST_MIPMAP_LINEAR          0x2702
#define GR_GL_LINEAR_MIPMAP_LINEAR           0x2703

/* TextureParameterName */
#define GR_GL_TEXTURE_MAG_FILTER             0x2800
#define GR_GL_TEXTURE_MIN_FILTER             0x2801
#define GR_GL_TEXTURE_WRAP_S                 0x2802
#define GR_GL_TEXTURE_WRAP_T                 0x2803

/* TextureTarget */
/*      GL_TEXTURE_2D */
#define GR_GL_TEXTURE                        0x1702
#define GR_GL_TEXTURE_CUBE_MAP               0x8513
#define GR_GL_TEXTURE_BINDING_CUBE_MAP       0x8514
#define GR_GL_TEXTURE_CUBE_MAP_POSITIVE_X    0x8515
#define GR_GL_TEXTURE_CUBE_MAP_NEGATIVE_X    0x8516
#define GR_GL_TEXTURE_CUBE_MAP_POSITIVE_Y    0x8517
#define GR_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y    0x8518
#define GR_GL_TEXTURE_CUBE_MAP_POSITIVE_Z    0x8519
#define GR_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z    0x851A
#define GR_GL_MAX_CUBE_MAP_TEXTURE_SIZE      0x851C

/* TextureUnit */
#define GR_GL_TEXTURE0                       0x84C0
#define GR_GL_TEXTURE1                       0x84C1
#define GR_GL_TEXTURE2                       0x84C2
#define GR_GL_TEXTURE3                       0x84C3
#define GR_GL_TEXTURE4                       0x84C4
#define GR_GL_TEXTURE5                       0x84C5
#define GR_GL_TEXTURE6                       0x84C6
#define GR_GL_TEXTURE7                       0x84C7
#define GR_GL_TEXTURE8                       0x84C8
#define GR_GL_TEXTURE9                       0x84C9
#define GR_GL_TEXTURE10                      0x84CA
#define GR_GL_TEXTURE11                      0x84CB
#define GR_GL_TEXTURE12                      0x84CC
#define GR_GL_TEXTURE13                      0x84CD
#define GR_GL_TEXTURE14                      0x84CE
#define GR_GL_TEXTURE15                      0x84CF
#define GR_GL_TEXTURE16                      0x84D0
#define GR_GL_TEXTURE17                      0x84D1
#define GR_GL_TEXTURE18                      0x84D2
#define GR_GL_TEXTURE19                      0x84D3
#define GR_GL_TEXTURE20                      0x84D4
#define GR_GL_TEXTURE21                      0x84D5
#define GR_GL_TEXTURE22                      0x84D6
#define GR_GL_TEXTURE23                      0x84D7
#define GR_GL_TEXTURE24                      0x84D8
#define GR_GL_TEXTURE25                      0x84D9
#define GR_GL_TEXTURE26                      0x84DA
#define GR_GL_TEXTURE27                      0x84DB
#define GR_GL_TEXTURE28                      0x84DC
#define GR_GL_TEXTURE29                      0x84DD
#define GR_GL_TEXTURE30                      0x84DE
#define GR_GL_TEXTURE31                      0x84DF
#define GR_GL_ACTIVE_TEXTURE                 0x84E0
#define GR_GL_MAX_TEXTURE_UNITS              0x84E2

/* TextureWrapMode */
#define GR_GL_REPEAT                         0x2901
#define GR_GL_CLAMP_TO_EDGE                  0x812F
#define GR_GL_MIRRORED_REPEAT                0x8370

/* Texture mapping */
#define GR_GL_TEXTURE_ENV                   0x2300
#define GR_GL_TEXTURE_ENV_MODE              0x2200
#define GR_GL_TEXTURE_1D                    0x0DE0
#define GR_GL_TEXTURE_2D                    0x0DE1
/*	GL_TEXTURE_WRAP_S */
/*	GL_TEXTURE_WRAP_T */
/*	GL_TEXTURE_MAG_FILTER */
/*	GL_TEXTURE_MIN_FILTER */
#define GR_GL_TEXTURE_ENV_COLOR             0x2201
#define GR_GL_TEXTURE_GEN_S                 0x0C60
#define GR_GL_TEXTURE_GEN_T                 0x0C61
#define GR_GL_TEXTURE_GEN_MODE              0x2500
#define GR_GL_TEXTURE_BORDER_COLOR          0x1004
#define GR_GL_TEXTURE_WIDTH                 0x1000
#define GR_GL_TEXTURE_HEIGHT                0x1001
#define GR_GL_TEXTURE_BORDER                0x1005
#define GR_GL_TEXTURE_COMPONENTS            0x1003
#define GR_GL_TEXTURE_RED_SIZE              0x805C
#define GR_GL_TEXTURE_GREEN_SIZE            0x805D
#define GR_GL_TEXTURE_BLUE_SIZE             0x805E
#define GR_GL_TEXTURE_ALPHA_SIZE            0x805F
#define GR_GL_TEXTURE_LUMINANCE_SIZE        0x8060
#define GR_GL_TEXTURE_INTENSITY_SIZE        0x8061
/*	GL_NEAREST_MIPMAP_NEAREST */
/*	GL_NEAREST_MIPMAP_LINEAR */
/*	GL_LINEAR_MIPMAP_NEAREST */
/*	GL_LINEAR_MIPMAP_LINEAR */
#define GR_GL_OBJECT_LINEAR                 0x2401
#define GR_GL_OBJECT_PLANE                  0x2501
#define GR_GL_EYE_LINEAR                    0x2400
#define GR_GL_EYE_PLANE                     0x2502
#define GR_GL_SPHERE_MAP                    0x2402
#define GR_GL_DECAL                         0x2101
#define GR_GL_MODULATE                      0x2100
/*	GL_NEAREST */
/*	GL_REPEAT */
#define GR_GL_CLAMP                         0x2900
#define GR_GL_S                             0x2000
#define GR_GL_T                             0x2001
#define GR_GL_R                             0x2002
#define GR_GL_Q                             0x2003
#define GR_GL_TEXTURE_GEN_R                 0x0C62
#define GR_GL_TEXTURE_GEN_Q                 0x0C63

/* texture_env_combine */
#define GR_GL_COMBINE                       0x8570
#define GR_GL_COMBINE_RGB                   0x8571
#define GR_GL_COMBINE_ALPHA                 0x8572
#define GR_GL_SOURCE0_RGB                   0x8580
#define GR_GL_SOURCE1_RGB                   0x8581
#define GR_GL_SOURCE2_RGB                   0x8582
#define GR_GL_SOURCE0_ALPHA                 0x8588
#define GR_GL_SOURCE1_ALPHA                 0x8589
#define GR_GL_SOURCE2_ALPHA                 0x858A
#define GR_GL_OPERAND0_RGB                  0x8590
#define GR_GL_OPERAND1_RGB                  0x8591
#define GR_GL_OPERAND2_RGB                  0x8592
#define GR_GL_OPERAND0_ALPHA                0x8598
#define GR_GL_OPERAND1_ALPHA                0x8599
#define GR_GL_OPERAND2_ALPHA                0x859A
#define GR_GL_RGB_SCALE                     0x8573
#define GR_GL_ADD_SIGNED                    0x8574
#define GR_GL_INTERPOLATE                   0x8575
#define GR_GL_SUBTRACT                      0x84E7
#define GR_GL_CONSTANT                      0x8576
#define GR_GL_PRIMARY_COLOR                 0x8577
#define GR_GL_PREVIOUS                      0x8578
#define GR_GL_SRC0_RGB                      0x8580
#define GR_GL_SRC1_RGB                      0x8581
#define GR_GL_SRC2_RGB                      0x8582
#define GR_GL_SRC0_ALPHA                    0x8588
#define GR_GL_SRC1_ALPHA                    0x8589
#define GR_GL_SRC2_ALPHA                    0x858A

/* Uniform Types */
#define GR_GL_FLOAT_VEC2                     0x8B50
#define GR_GL_FLOAT_VEC3                     0x8B51
#define GR_GL_FLOAT_VEC4                     0x8B52
#define GR_GL_INT_VEC2                       0x8B53
#define GR_GL_INT_VEC3                       0x8B54
#define GR_GL_INT_VEC4                       0x8B55
#define GR_GL_BOOL                           0x8B56
#define GR_GL_BOOL_VEC2                      0x8B57
#define GR_GL_BOOL_VEC3                      0x8B58
#define GR_GL_BOOL_VEC4                      0x8B59
#define GR_GL_FLOAT_MAT2                     0x8B5A
#define GR_GL_FLOAT_MAT3                     0x8B5B
#define GR_GL_FLOAT_MAT4                     0x8B5C
#define GR_GL_SAMPLER_2D                     0x8B5E
#define GR_GL_SAMPLER_CUBE                   0x8B60

/* Vertex Arrays */
#define GR_GL_VERTEX_ATTRIB_ARRAY_ENABLED        0x8622
#define GR_GL_VERTEX_ATTRIB_ARRAY_SIZE           0x8623
#define GR_GL_VERTEX_ATTRIB_ARRAY_STRIDE         0x8624
#define GR_GL_VERTEX_ATTRIB_ARRAY_TYPE           0x8625
#define GR_GL_VERTEX_ATTRIB_ARRAY_NORMALIZED     0x886A
#define GR_GL_VERTEX_ATTRIB_ARRAY_POINTER        0x8645
#define GR_GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F
#define GR_GL_VERTEX_ARRAY                       0x8074
#define GR_GL_NORMAL_ARRAY                       0x8075
#define GR_GL_COLOR_ARRAY                        0x8076
#define GR_GL_INDEX_ARRAY                        0x8077
#define GR_GL_TEXTURE_COORD_ARRAY                0x8078
#define GR_GL_EDGE_FLAG_ARRAY                    0x8079
#define GR_GL_VERTEX_ARRAY_SIZE                  0x807A
#define GR_GL_VERTEX_ARRAY_TYPE                  0x807B
#define GR_GL_VERTEX_ARRAY_STRIDE                0x807C
#define GR_GL_NORMAL_ARRAY_TYPE                  0x807E
#define GR_GL_NORMAL_ARRAY_STRIDE                0x807F
#define GR_GL_COLOR_ARRAY_SIZE                   0x8081
#define GR_GL_COLOR_ARRAY_TYPE                   0x8082
#define GR_GL_COLOR_ARRAY_STRIDE                 0x8083
#define GR_GL_INDEX_ARRAY_TYPE                   0x8085
#define GR_GL_INDEX_ARRAY_STRIDE                 0x8086
#define GR_GL_TEXTURE_COORD_ARRAY_SIZE           0x8088
#define GR_GL_TEXTURE_COORD_ARRAY_TYPE           0x8089
#define GR_GL_TEXTURE_COORD_ARRAY_STRIDE         0x808A
#define GR_GL_EDGE_FLAG_ARRAY_STRIDE             0x808C
#define GR_GL_VERTEX_ARRAY_POINTER               0x808E
#define GR_GL_NORMAL_ARRAY_POINTER               0x808F
#define GR_GL_COLOR_ARRAY_POINTER                0x8090
#define GR_GL_INDEX_ARRAY_POINTER                0x8091
#define GR_GL_TEXTURE_COORD_ARRAY_POINTER        0x8092
#define GR_GL_EDGE_FLAG_ARRAY_POINTER            0x8093
#define GR_GL_V2F                                0x2A20
#define GR_GL_V3F                                0x2A21
#define GR_GL_C4UB_V2F                           0x2A22
#define GR_GL_C4UB_V3F                           0x2A23
#define GR_GL_C3F_V3F                            0x2A24
#define GR_GL_N3F_V3F                            0x2A25
#define GR_GL_C4F_N3F_V3F                        0x2A26
#define GR_GL_T2F_V3F                            0x2A27
#define GR_GL_T4F_V4F                            0x2A28
#define GR_GL_T2F_C4UB_V3F                       0x2A29
#define GR_GL_T2F_C3F_V3F                        0x2A2A
#define GR_GL_T2F_N3F_V3F                        0x2A2B
#define GR_GL_T2F_C4F_N3F_V3F                    0x2A2C
#define GR_GL_T4F_C4F_N3F_V4F                    0x2A2D

/* Vertex Buffer Object */
#define GR_GL_WRITE_ONLY                         0x88B9
#define GR_GL_BUFFER_MAPPED                      0x88BC
/* Read Format */
#define GR_GL_IMPLEMENTATION_COLOR_READ_TYPE   0x8B9A
#define GR_GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B

/* Shader Source */
#define GR_GL_COMPILE_STATUS                 0x8B81
#define GR_GL_INFO_LOG_LENGTH                0x8B84
#define GR_GL_SHADER_SOURCE_LENGTH           0x8B88
#define GR_GL_SHADER_COMPILER                0x8DFA

/* Shader Binary */
#define GR_GL_SHADER_BINARY_FORMATS          0x8DF8
#define GR_GL_NUM_SHADER_BINARY_FORMATS      0x8DF9

/* Shader Precision-Specified Types */
#define GR_GL_LOW_FLOAT                      0x8DF0
#define GR_GL_MEDIUM_FLOAT                   0x8DF1
#define GR_GL_HIGH_FLOAT                     0x8DF2
#define GR_GL_LOW_INT                        0x8DF3
#define GR_GL_MEDIUM_INT                     0x8DF4
#define GR_GL_HIGH_INT                       0x8DF5

/* Framebuffer Object. */
#define GR_GL_FRAMEBUFFER                    0x8D40
#define GR_GL_READ_FRAMEBUFFER               0x8CA8
#define GR_GL_DRAW_FRAMEBUFFER               0x8CA9

#define GR_GL_RENDERBUFFER                   0x8D41

#define GR_GL_RGBA4                          0x8056
#define GR_GL_RGB5_A1                        0x8057
#define GR_GL_RGB565                         0x8D62
#define GR_GL_RGBA8                          0x8058
#define GR_GL_DEPTH_COMPONENT16              0x81A5
#define GR_GL_STENCIL_INDEX                  0x1901
#define GR_GL_STENCIL_INDEX4                 0x8D47
#define GR_GL_STENCIL_INDEX8                 0x8D48
#define GR_GL_STENCIL_INDEX16                0x8D49
#define GR_GL_DEPTH_STENCIL                  0x84F9
#define GR_GL_DEPTH24_STENCIL8               0x88F0

#define GR_GL_MAX_SAMPLES                    0x8D57

#define GR_GL_RENDERBUFFER_WIDTH             0x8D42
#define GR_GL_RENDERBUFFER_HEIGHT            0x8D43
#define GR_GL_RENDERBUFFER_INTERNAL_FORMAT   0x8D44
#define GR_GL_RENDERBUFFER_RED_SIZE          0x8D50
#define GR_GL_RENDERBUFFER_GREEN_SIZE        0x8D51
#define GR_GL_RENDERBUFFER_BLUE_SIZE         0x8D52
#define GR_GL_RENDERBUFFER_ALPHA_SIZE        0x8D53
#define GR_GL_RENDERBUFFER_DEPTH_SIZE        0x8D54
#define GR_GL_RENDERBUFFER_STENCIL_SIZE      0x8D55

#define GR_GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE           0x8CD0
#define GR_GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME           0x8CD1
#define GR_GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL         0x8CD2
#define GR_GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3

#define GR_GL_COLOR_ATTACHMENT0              0x8CE0
#define GR_GL_DEPTH_ATTACHMENT               0x8D00
#define GR_GL_STENCIL_ATTACHMENT             0x8D20
#define GR_GL_DEPTH_STENCIL_ATTACHMENT       0x821A

#define GR_GL_NONE                           0

#define GR_GL_FRAMEBUFFER_COMPLETE                      0x8CD5
#define GR_GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT         0x8CD6
#define GR_GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7
#define GR_GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS         0x8CD9
#define GR_GL_FRAMEBUFFER_UNSUPPORTED                   0x8CDD

#define GR_GL_FRAMEBUFFER_BINDING            0x8CA6
#define GR_GL_RENDERBUFFER_BINDING           0x8CA7
#define GR_GL_MAX_RENDERBUFFER_SIZE          0x84E8

#define GR_GL_INVALID_FRAMEBUFFER_OPERATION  0x0506

#endif


code:
/*
    Copyright 2011 Google Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

#ifndef GrGLIRect_DEFINED
#define GrGLIRect_DEFINED

#include "GrGLInterface.h"

/**
 * Helper struct for dealing with the fact that Ganesh and GL use different
 * window coordinate systems (top-down vs bottom-up)
 */
struct GrGLIRect {
    GrGLint   fLeft;
    GrGLint   fBottom;
    GrGLsizei fWidth;
    GrGLsizei fHeight;

    void pushToGLViewport() const {
        GR_GL(Viewport(fLeft, fBottom, fWidth, fHeight));
    }

    void pushToGLScissor() const {
        GR_GL(Scissor(fLeft, fBottom, fWidth, fHeight));
    }

    void setFromGLViewport() {
        GR_STATIC_ASSERT(sizeof(GrGLIRect) == 4*sizeof(GrGLint));
        GR_GL_GetIntegerv(GR_GL_VIEWPORT, (GrGLint*) this);
    }

    // sometimes we have a GrIRect from the client that we
    // want to simultaneously make relative to GL's viewport
    // and convert from top-down to bottom-up.
    void setRelativeTo(const GrGLIRect& glRect,
                       int leftOffset,
                       int topOffset,
                       int width,
                       int height) {
        fLeft = glRect.fLeft + leftOffset;
        fWidth = width;
        fBottom = glRect.fBottom + (glRect.fHeight - topOffset - height);
        fHeight = height;

        GrAssert(fLeft >= 0);
        GrAssert(fWidth >= 0);
        GrAssert(fBottom >= 0);
        GrAssert(fHeight >= 0);
    }

    bool contains(const GrGLIRect& glRect) const {
        return fLeft <= glRect.fLeft &&
               fBottom <= glRect.fBottom &&
               fLeft + fWidth >=  glRect.fLeft + glRect.fWidth &&
               fBottom + fHeight >=  glRect.fBottom + glRect.fHeight;
    }

    void invalidate() {fLeft = fWidth = fBottom = fHeight = -1;}

    bool operator ==(const GrGLIRect& glRect) const {
        return 0 == memcmp(this, &glRect, sizeof(GrGLIRect));
    }

    bool operator !=(const GrGLIRect& glRect) const {return !(*this == glRect);}
};

#endif


code:
/*
    Copyright 2011 Google Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

#ifndef GrGLIndexBuffer_DEFINED
#define GrGLIndexBuffer_DEFINED

#include "GrIndexBuffer.h"
#include "GrGLInterface.h"

class GrGpuGL;

class GrGLIndexBuffer : public GrIndexBuffer {

public:

    virtual ~GrGLIndexBuffer() { this->release(); }

    GrGLuint bufferID() const;

    // overrides of GrIndexBuffer
    virtual void* lock();
    virtual void* lockPtr() const;
    virtual void unlock();
    virtual bool isLocked() const;
    virtual bool updateData(const void* src, size_t srcSizeInBytes);
    virtual bool updateSubData(const void* src,
                               size_t srcSizeInBytes,
                               size_t offset);
protected:
    GrGLIndexBuffer(GrGpuGL* gpu,
                    GrGLuint id,
                    size_t sizeInBytes,
                    bool dynamic);

    // overrides of GrResource
    virtual void onAbandon();
    virtual void onRelease();

private:
    void bind() const;

    GrGLuint     fBufferID;
    void*        fLockPtr;

    friend class GrGpuGL;

    typedef GrIndexBuffer INHERITED;
};

#endif