GrDrawTarget.h revision 8d67c0711b52226db59158a0cfce09f35badd96a
1
2/*
3 * Copyright 2010 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
11#ifndef GrDrawTarget_DEFINED
12#define GrDrawTarget_DEFINED
13
14#include "GrClipData.h"
15#include "GrDrawState.h"
16#include "GrIndexBuffer.h"
17#include "SkMatrix.h"
18#include "GrRefCnt.h"
19#include "GrTemplates.h"
20
21#include "SkClipStack.h"
22#include "SkPath.h"
23#include "SkTLazy.h"
24#include "SkTArray.h"
25#include "SkXfermode.h"
26
27class GrClipData;
28class GrPath;
29class GrVertexBuffer;
30
31class SkStroke;
32
33class GrDrawTarget : public GrRefCnt {
34protected:
35    /** This helper class allows GrDrawTarget subclasses to set the caps values without having to be
36        made a friend of GrDrawTarget::Caps. */
37    class CapsInternals {
38    public:
39        bool f8BitPaletteSupport        : 1;
40        bool fNPOTTextureTileSupport    : 1;
41        bool fTwoSidedStencilSupport    : 1;
42        bool fStencilWrapOpsSupport     : 1;
43        bool fHWAALineSupport           : 1;
44        bool fShaderDerivativeSupport   : 1;
45        bool fGeometryShaderSupport     : 1;
46        bool fFSAASupport               : 1;
47        bool fDualSourceBlendingSupport : 1;
48        bool fBufferLockSupport         : 1;
49        bool fPathStencilingSupport     : 1;
50        int fMaxRenderTargetSize;
51        int fMaxTextureSize;
52    };
53
54public:
55    SK_DECLARE_INST_COUNT(GrDrawTarget)
56
57    /**
58     * Represents the draw target capabilities.
59     */
60    class Caps {
61    public:
62        Caps() { memset(this, 0, sizeof(Caps)); }
63        Caps(const Caps& c) { *this = c; }
64        Caps& operator= (const Caps& c) {
65            memcpy(this, &c, sizeof(Caps));
66            return *this;
67        }
68        void print() const;
69
70        bool eightBitPaletteSupport() const { return fInternals.f8BitPaletteSupport; }
71        bool npotTextureTileSupport() const { return fInternals.fNPOTTextureTileSupport; }
72        bool twoSidedStencilSupport() const { return fInternals.fTwoSidedStencilSupport; }
73        bool stencilWrapOpsSupport() const { return  fInternals.fStencilWrapOpsSupport; }
74        bool hwAALineSupport() const { return fInternals.fHWAALineSupport; }
75        bool shaderDerivativeSupport() const { return fInternals.fShaderDerivativeSupport; }
76        bool geometryShaderSupport() const { return fInternals.fGeometryShaderSupport; }
77        bool fsaaSupport() const { return fInternals.fFSAASupport; }
78        bool dualSourceBlendingSupport() const { return fInternals.fDualSourceBlendingSupport; }
79        bool bufferLockSupport() const { return fInternals.fBufferLockSupport; }
80        bool pathStencilingSupport() const { return fInternals.fPathStencilingSupport; }
81
82        int maxRenderTargetSize() const { return fInternals.fMaxRenderTargetSize; }
83        int maxTextureSize() const { return fInternals.fMaxTextureSize; }
84    private:
85        CapsInternals fInternals;
86        friend class GrDrawTarget; // to set values of fInternals
87    };
88
89    ///////////////////////////////////////////////////////////////////////////
90
91    GrDrawTarget();
92    virtual ~GrDrawTarget();
93
94    /**
95     * Gets the capabilities of the draw target.
96     */
97    const Caps& getCaps() const { return fCaps; }
98
99    /**
100     * Sets the current clip to the region specified by clip. All draws will be
101     * clipped against this clip if kClip_StateBit is enabled.
102     *
103     * Setting the clip may (or may not) zero out the client's stencil bits.
104     *
105     * @param description of the clipping region
106     */
107    void setClip(const GrClipData* clip);
108
109    /**
110     * Gets the current clip.
111     *
112     * @return the clip.
113     */
114    const GrClipData* getClip() const;
115
116    /**
117     * Sets the draw state object for the draw target. Note that this does not
118     * make a copy. The GrDrawTarget will take a reference to passed object.
119     * Passing NULL will cause the GrDrawTarget to use its own internal draw
120     * state object rather than an externally provided one.
121     */
122    void setDrawState(GrDrawState*  drawState);
123
124    /**
125     * Read-only access to the GrDrawTarget's current draw state.
126     */
127    const GrDrawState& getDrawState() const { return *fDrawState; }
128
129    /**
130     * Read-write access to the GrDrawTarget's current draw state. Note that
131     * this doesn't ref.
132     */
133    GrDrawState* drawState() { return fDrawState; }
134
135    /**
136     * Color alpha and coverage are two inputs to the drawing pipeline. For some
137     * blend modes it is safe to fold the coverage into constant or per-vertex
138     * color alpha value. For other blend modes they must be handled separately.
139     * Depending on features available in the underlying 3D API this may or may
140     * not be possible.
141     *
142     * This function considers the current draw state and the draw target's
143     * capabilities to determine whether coverage can be handled correctly. The
144     * following assumptions are made:
145     *    1. The caller intends to somehow specify coverage. This can be
146     *       specified either by enabling a coverage stage on the GrDrawState or
147     *       via the vertex layout.
148     *    2. Other than enabling coverage stages, the current configuration of
149     *       the target's GrDrawState is as it will be at draw time.
150     *    3. If a vertex source has not yet been specified then all stages with
151     *       non-NULL textures will be referenced by the vertex layout.
152     */
153    bool canApplyCoverage() const;
154
155    /**
156     * Determines whether incorporating partial pixel coverage into the constant
157     * color specified by setColor or per-vertex colors will give the right
158     * blending result. If a vertex source has not yet been specified then
159     * the function assumes that all stages with non-NULL textures will be
160     * referenced by the vertex layout.
161     */
162    bool canTweakAlphaForCoverage() const;
163
164    /**
165     * Given the current draw state and hw support, will HW AA lines be used
166     * (if line primitive type is drawn)? If a vertex source has not yet been
167     * specified then  the function assumes that all stages with non-NULL
168     * textures will be referenced by the vertex layout.
169     */
170    bool willUseHWAALines() const;
171
172    /**
173     * The format of vertices is represented as a bitfield of flags.
174     * Flags that indicate the layout of vertex data. Vertices always contain
175     * positions and may also contain up to GrDrawState::kMaxTexCoords sets
176     * of 2D texture coordinates, per-vertex colors, and per-vertex coverage.
177     * Each stage can
178     * use any of the texture coordinates as its input texture coordinates or it
179     * may use the positions as texture coordinates.
180     *
181     * If no texture coordinates are specified for a stage then the stage is
182     * disabled.
183     *
184     * Only one type of texture coord can be specified per stage. For
185     * example StageTexCoordVertexLayoutBit(0, 2) and
186     * StagePosAsTexCoordVertexLayoutBit(0) cannot both be specified.
187     *
188     * The order in memory is always (position, texture coord 0, ..., color,
189     * coverage) with any unused fields omitted. Note that this means that if
190     * only texture coordinates 1 is referenced then there is no texture
191     * coordinates 0 and the order would be (position, texture coordinate 1
192     * [, color][, coverage]).
193     */
194
195    /**
196     * Generates a bit indicating that a texture stage uses texture coordinates
197     *
198     * @param stageIdx    the stage that will use texture coordinates.
199     * @param texCoordIdx the index of the texture coordinates to use
200     *
201     * @return the bit to add to a GrVertexLayout bitfield.
202     */
203    static int StageTexCoordVertexLayoutBit(int stageIdx, int texCoordIdx) {
204        GrAssert(stageIdx < GrDrawState::kNumStages);
205        GrAssert(texCoordIdx < GrDrawState::kMaxTexCoords);
206        return 1 << (stageIdx + (texCoordIdx * GrDrawState::kNumStages));
207    }
208
209    static bool StageUsesTexCoords(GrVertexLayout layout, int stageIdx);
210
211private:
212    // non-stage bits start at this index.
213    static const int STAGE_BIT_CNT = GrDrawState::kNumStages *
214                                     GrDrawState::kMaxTexCoords;
215public:
216
217    /**
218     * Additional Bits that can be specified in GrVertexLayout.
219     */
220    enum VertexLayoutBits {
221        /* vertices have colors (GrColor) */
222        kColor_VertexLayoutBit              = 1 << (STAGE_BIT_CNT + 0),
223        /* vertices have coverage (GrColor)
224         */
225        kCoverage_VertexLayoutBit           = 1 << (STAGE_BIT_CNT + 1),
226        /* Use text vertices. (Pos and tex coords may be a different type for
227         * text [GrGpuTextVertex vs GrPoint].)
228         */
229        kTextFormat_VertexLayoutBit         = 1 << (STAGE_BIT_CNT + 2),
230
231        /* Each vertex specificies an edge. Distance to the edge is used to
232         * compute a coverage. See GrDrawState::setVertexEdgeType().
233         */
234        kEdge_VertexLayoutBit               = 1 << (STAGE_BIT_CNT + 3),
235        // for below assert
236        kDummyVertexLayoutBit,
237        kHighVertexLayoutBit = kDummyVertexLayoutBit - 1
238    };
239    // make sure we haven't exceeded the number of bits in GrVertexLayout.
240    GR_STATIC_ASSERT(kHighVertexLayoutBit < ((uint64_t)1 << 8*sizeof(GrVertexLayout)));
241
242    /**
243     * There are three types of "sources" of geometry (vertices and indices) for
244     * draw calls made on the target. When performing an indexed draw, the
245     * indices and vertices can use different source types. Once a source is
246     * specified it can be used for multiple draws. However, the time at which
247     * the geometry data is no longer editable depends on the source type.
248     *
249     * Sometimes it is necessary to perform a draw while upstack code has
250     * already specified geometry that it isn't finished with. So there are push
251     * and pop methods. This allows the client to push the sources, draw
252     * something using alternate sources, and then pop to restore the original
253     * sources.
254     *
255     * Aside from pushes and pops, a source remains valid until another source
256     * is set or resetVertexSource / resetIndexSource is called. Drawing from
257     * a reset source is an error.
258     *
259     * The three types of sources are:
260     *
261     * 1. A cpu array (set*SourceToArray). This is useful when the caller
262     *    already provided vertex data in a format compatible with a
263     *    GrVertexLayout. The data in the array is consumed at the time that
264     *    set*SourceToArray is called and subsequent edits to the array will not
265     *    be reflected in draws.
266     *
267     * 2. Reserve. This is most useful when the caller has data it must
268     *    transform before drawing and is not long-lived. The caller requests
269     *    that the draw target make room for some amount of vertex and/or index
270     *    data. The target provides ptrs to hold the vertex and/or index data.
271     *
272     *    The data is writable up until the next drawIndexed, drawNonIndexed,
273     *    drawIndexedInstances, or pushGeometrySource. At this point the data is
274     *    frozen and the ptrs are no longer valid.
275     *
276     *    Where the space is allocated and how it is uploaded to the GPU is
277     *    subclass-dependent.
278     *
279     * 3. Vertex and Index Buffers. This is most useful for geometry that will
280     *    is long-lived. When the data in the buffer is consumed depends on the
281     *    GrDrawTarget subclass. For deferred subclasses the caller has to
282     *    guarantee that the data is still available in the buffers at playback.
283     *    (TODO: Make this more automatic as we have done for read/write pixels)
284     */
285
286    /**
287     * Reserves space for vertices and/or indices. Zero can be specifed as
288     * either the vertex or index count if the caller desires to only reserve
289     * space for only indices or only vertices. If zero is specifed for
290     * vertexCount then the vertex source will be unmodified and likewise for
291     * indexCount.
292     *
293     * If the function returns true then the reserve suceeded and the vertices
294     * and indices pointers will point to the space created.
295     *
296     * If the target cannot make space for the request then this function will
297     * return false. If vertexCount was non-zero then upon failure the vertex
298     * source is reset and likewise for indexCount.
299     *
300     * The pointers to the space allocated for vertices and indices remain valid
301     * until a drawIndexed, drawNonIndexed, drawIndexedInstances, or push/
302     * popGeomtrySource is called. At that point logically a snapshot of the
303     * data is made and the pointers are invalid.
304     *
305     * @param vertexLayout the format of vertices (ignored if vertexCount == 0).
306     * @param vertexCount  the number of vertices to reserve space for. Can be
307     *                     0.
308     * @param indexCount   the number of indices to reserve space for. Can be 0.
309     * @param vertices     will point to reserved vertex space if vertexCount is
310     *                     non-zero. Illegal to pass NULL if vertexCount > 0.
311     * @param indices      will point to reserved index space if indexCount is
312     *                     non-zero. Illegal to pass NULL if indexCount > 0.
313     */
314     bool reserveVertexAndIndexSpace(GrVertexLayout vertexLayout,
315                                     int vertexCount,
316                                     int indexCount,
317                                     void** vertices,
318                                     void** indices);
319
320    /**
321     * Provides hints to caller about the number of vertices and indices
322     * that can be allocated cheaply. This can be useful if caller is reserving
323     * space but doesn't know exactly how much geometry is needed.
324     *
325     * Also may hint whether the draw target should be flushed first. This is
326     * useful for deferred targets.
327     *
328     * @param vertexLayout layout of vertices caller would like to reserve
329     * @param vertexCount  in: hint about how many vertices the caller would
330     *                     like to allocate.
331     *                     out: a hint about the number of vertices that can be
332     *                     allocated cheaply. Negative means no hint.
333     *                     Ignored if NULL.
334     * @param indexCount   in: hint about how many indices the caller would
335     *                     like to allocate.
336     *                     out: a hint about the number of indices that can be
337     *                     allocated cheaply. Negative means no hint.
338     *                     Ignored if NULL.
339     *
340     * @return  true if target should be flushed based on the input values.
341     */
342    virtual bool geometryHints(GrVertexLayout vertexLayout,
343                               int* vertexCount,
344                               int* indexCount) const;
345
346    /**
347     * Sets source of vertex data for the next draw. Array must contain
348     * the vertex data when this is called.
349     *
350     * @param array         cpu array containing vertex data.
351     * @param size          size of the vertex data.
352     * @param vertexCount   the number of vertices in the array.
353     */
354    void setVertexSourceToArray(GrVertexLayout vertexLayout,
355                                const void* vertexArray,
356                                int vertexCount);
357
358    /**
359     * Sets source of index data for the next indexed draw. Array must contain
360     * the indices when this is called.
361     *
362     * @param array         cpu array containing index data.
363     * @param indexCount    the number of indices in the array.
364     */
365    void setIndexSourceToArray(const void* indexArray, int indexCount);
366
367    /**
368     * Sets source of vertex data for the next draw. Data does not have to be
369     * in the buffer until drawIndexed, drawNonIndexed, or drawIndexedInstances.
370     *
371     * @param buffer        vertex buffer containing vertex data. Must be
372     *                      unlocked before draw call.
373     * @param vertexLayout  layout of the vertex data in the buffer.
374     */
375    void setVertexSourceToBuffer(GrVertexLayout vertexLayout,
376                                 const GrVertexBuffer* buffer);
377
378    /**
379     * Sets source of index data for the next indexed draw. Data does not have
380     * to be in the buffer until drawIndexed.
381     *
382     * @param buffer index buffer containing indices. Must be unlocked
383     *               before indexed draw call.
384     */
385    void setIndexSourceToBuffer(const GrIndexBuffer* buffer);
386
387    /**
388     * Resets vertex source. Drawing from reset vertices is illegal. Set vertex
389     * source to reserved, array, or buffer before next draw. May be able to free
390     * up temporary storage allocated by setVertexSourceToArray or
391     * reserveVertexSpace.
392     */
393    void resetVertexSource();
394
395    /**
396     * Resets index source. Indexed Drawing from reset indices is illegal. Set
397     * index source to reserved, array, or buffer before next indexed draw. May
398     * be able to free up temporary storage allocated by setIndexSourceToArray
399     * or reserveIndexSpace.
400     */
401    void resetIndexSource();
402
403    /**
404     * Query to find out if the vertex or index source is reserved.
405     */
406    bool hasReservedVerticesOrIndices() const {
407        return kReserved_GeometrySrcType == this->getGeomSrc().fVertexSrc ||
408        kReserved_GeometrySrcType == this->getGeomSrc().fIndexSrc;
409    }
410
411    /**
412     * Pushes and resets the vertex/index sources. Any reserved vertex / index
413     * data is finalized (i.e. cannot be updated after the matching pop but can
414     * be drawn from). Must be balanced by a pop.
415     */
416    void pushGeometrySource();
417
418    /**
419     * Pops the vertex / index sources from the matching push.
420     */
421    void popGeometrySource();
422
423    /**
424     * Draws indexed geometry using the current state and current vertex / index
425     * sources.
426     *
427     * @param type         The type of primitives to draw.
428     * @param startVertex  the vertex in the vertex array/buffer corresponding
429     *                     to index 0
430     * @param startIndex   first index to read from index src.
431     * @param vertexCount  one greater than the max index.
432     * @param indexCount   the number of index elements to read. The index count
433     *                     is effectively trimmed to the last completely
434     *                     specified primitive.
435     */
436    void drawIndexed(GrPrimitiveType type,
437                     int startVertex,
438                     int startIndex,
439                     int vertexCount,
440                     int indexCount);
441
442    /**
443     * Draws non-indexed geometry using the current state and current vertex
444     * sources.
445     *
446     * @param type         The type of primitives to draw.
447     * @param startVertex  the vertex in the vertex array/buffer corresponding
448     *                     to index 0
449     * @param vertexCount  one greater than the max index.
450     */
451    void drawNonIndexed(GrPrimitiveType type,
452                        int startVertex,
453                        int vertexCount);
454
455    /**
456     * Draws path into the stencil buffer. The fill must be either even/odd or
457     * winding (not inverse or hairline). It will respect the HW antialias flag
458     * on the draw state (if possible in the 3D API).
459     */
460    void stencilPath(const GrPath*, const SkStroke& stroke, SkPath::FillType fill);
461
462    /**
463     * Helper function for drawing rects. This does not use the current index
464     * and vertex sources. After returning, the vertex and index sources may
465     * have changed. They should be reestablished before the next drawIndexed
466     * or drawNonIndexed. This cannot be called between reserving and releasing
467     * geometry. The GrDrawTarget subclass may be able to perform additional
468     * optimizations if drawRect is used rather than drawIndexed or
469     * drawNonIndexed.
470     * @param rect      the rect to draw
471     * @param matrix    optional matrix applied to rect (before viewMatrix)
472     * @param srcRects  specifies rects for stages enabled by stageEnableMask.
473     *                  if stageEnableMask bit i is 1, srcRects is not NULL,
474     *                  and srcRects[i] is not NULL, then srcRects[i] will be
475     *                  used as coordinates for stage i. Otherwise, if stage i
476     *                  is enabled then rect is used as the coordinates.
477     * @param srcMatrices   optional matrices applied to srcRects. If
478     *                      srcRect[i] is non-NULL and srcMatrices[i] is
479     *                      non-NULL then srcRect[i] will be transformed by
480     *                      srcMatrix[i]. srcMatrices can be NULL when no
481     *                      srcMatrices are desired.
482     */
483    virtual void drawRect(const GrRect& rect,
484                          const SkMatrix* matrix,
485                          const GrRect* srcRects[],
486                          const SkMatrix* srcMatrices[]);
487    /**
488     * Helper for drawRect when the caller doesn't need separate src rects or
489     * matrices.
490     */
491    void drawSimpleRect(const GrRect& rect, const SkMatrix* matrix = NULL) {
492        drawRect(rect, matrix, NULL, NULL);
493    }
494    void drawSimpleRect(const GrIRect& irect, const SkMatrix* matrix = NULL) {
495        SkRect rect = SkRect::MakeFromIRect(irect);
496        this->drawRect(rect, matrix, NULL, NULL);
497    }
498
499
500    /**
501     * This call is used to draw multiple instances of some geometry with a
502     * given number of vertices (V) and indices (I) per-instance. The indices in
503     * the index source must have the form i[k+I] == i[k] + V. Also, all indices
504     * i[kI] ... i[(k+1)I-1] must be elements of the range kV ... (k+1)V-1. As a
505     * concrete example, the following index buffer for drawing a series of
506     * quads each as two triangles each satisfies these conditions with V=4 and
507     * I=6:
508     *      (0,1,2,0,2,3, 4,5,6,4,6,7, 8,9,10,8,10,11, ...)
509     *
510     * The call assumes that the pattern of indices fills the entire index
511     * source. The size of the index buffer limits the number of instances that
512     * can be drawn by the GPU in a single draw. However, the caller may specify
513     * any (positive) number for instanceCount and if necessary multiple GPU
514     * draws will be issued. Morever, when drawIndexedInstances is called
515     * multiple times it may be possible for GrDrawTarget to group them into a
516     * single GPU draw.
517     *
518     * @param type          the type of primitives to draw
519     * @param instanceCount the number of instances to draw. Each instance
520     *                      consists of verticesPerInstance vertices indexed by
521     *                      indicesPerInstance indices drawn as the primitive
522     *                      type specified by type.
523     * @param verticesPerInstance   The number of vertices in each instance (V
524     *                              in the above description).
525     * @param indicesPerInstance    The number of indices in each instance (I
526     *                              in the above description).
527     */
528    virtual void drawIndexedInstances(GrPrimitiveType type,
529                                      int instanceCount,
530                                      int verticesPerInstance,
531                                      int indicesPerInstance);
532
533    /**
534     * Clear the current render target if one isn't passed in. Ignores the
535     * clip and all other draw state (blend mode, stages, etc). Clears the
536     * whole thing if rect is NULL, otherwise just the rect.
537     */
538    virtual void clear(const GrIRect* rect,
539                       GrColor color,
540                       GrRenderTarget* renderTarget = NULL) = 0;
541
542    /**
543     * Release any resources that are cached but not currently in use. This
544     * is intended to give an application some recourse when resources are low.
545     */
546    virtual void purgeResources() {};
547
548    ////////////////////////////////////////////////////////////////////////////
549
550    /**
551     * See AutoStateRestore below.
552     */
553    enum ASRInit {
554        kPreserve_ASRInit,
555        kReset_ASRInit
556    };
557
558    /**
559     * Saves off the current state and restores it in the destructor. It will
560     * install a new GrDrawState object on the target (setDrawState) and restore
561     * the previous one in the destructor. The caller should call drawState() to
562     * get the new draw state after the ASR is installed.
563     *
564     * GrDrawState* state = target->drawState();
565     * AutoStateRestore asr(target, GrDrawTarget::kReset_ASRInit).
566     * state->setRenderTarget(rt); // state refers to the GrDrawState set on
567     *                             // target before asr was initialized.
568     *                             // Therefore, rt is set on the GrDrawState
569     *                             // that will be restored after asr's
570     *                             // destructor rather than target's current
571     *                             // GrDrawState.
572     */
573    class AutoStateRestore : ::GrNoncopyable {
574    public:
575        /**
576         * Default ASR will have no effect unless set() is subsequently called.
577         */
578        AutoStateRestore();
579
580        /**
581         * Saves the state on target. The state will be restored when the ASR
582         * is destroyed. If this constructor is used do not call set().
583         *
584         * @param init  Should the newly installed GrDrawState be a copy of the
585         *              previous state or a default-initialized GrDrawState.
586         */
587        AutoStateRestore(GrDrawTarget* target, ASRInit init);
588
589        ~AutoStateRestore();
590
591        /**
592         * Saves the state on target. The state will be restored when the ASR
593         * is destroyed. This should only be called once per ASR object and only
594         * when the default constructor was used. For nested saves use multiple
595         * ASR objects.
596         *
597         * @param init  Should the newly installed GrDrawState be a copy of the
598         *              previous state or a default-initialized GrDrawState.
599         */
600        void set(GrDrawTarget* target, ASRInit init);
601
602    private:
603        GrDrawTarget*        fDrawTarget;
604        SkTLazy<GrDrawState> fTempState;
605        GrDrawState*         fSavedState;
606    };
607
608    ////////////////////////////////////////////////////////////////////////////
609
610    class AutoReleaseGeometry : ::GrNoncopyable {
611    public:
612        AutoReleaseGeometry(GrDrawTarget*  target,
613                            GrVertexLayout vertexLayout,
614                            int            vertexCount,
615                            int            indexCount);
616        AutoReleaseGeometry();
617        ~AutoReleaseGeometry();
618        bool set(GrDrawTarget*  target,
619                 GrVertexLayout vertexLayout,
620                 int            vertexCount,
621                 int            indexCount);
622        bool succeeded() const { return NULL != fTarget; }
623        void* vertices() const { GrAssert(this->succeeded()); return fVertices; }
624        void* indices() const { GrAssert(this->succeeded()); return fIndices; }
625        GrPoint* positions() const {
626            return static_cast<GrPoint*>(this->vertices());
627        }
628
629    private:
630        void reset();
631
632        GrDrawTarget* fTarget;
633        void*         fVertices;
634        void*         fIndices;
635    };
636
637    ////////////////////////////////////////////////////////////////////////////
638
639    class AutoClipRestore : ::GrNoncopyable {
640    public:
641        AutoClipRestore(GrDrawTarget* target) {
642            fTarget = target;
643            fClip = fTarget->getClip();
644        }
645
646        AutoClipRestore(GrDrawTarget* target, const SkIRect& newClip);
647
648        ~AutoClipRestore() {
649            fTarget->setClip(fClip);
650        }
651    private:
652        GrDrawTarget*           fTarget;
653        const GrClipData*       fClip;
654        SkTLazy<SkClipStack>    fStack;
655        GrClipData              fReplacementClip;
656    };
657
658    ////////////////////////////////////////////////////////////////////////////
659
660    class AutoGeometryPush : ::GrNoncopyable {
661    public:
662        AutoGeometryPush(GrDrawTarget* target) {
663            GrAssert(NULL != target);
664            fTarget = target;
665            target->pushGeometrySource();
666        }
667        ~AutoGeometryPush() {
668            fTarget->popGeometrySource();
669        }
670    private:
671        GrDrawTarget* fTarget;
672    };
673
674    ////////////////////////////////////////////////////////////////////////////
675    // Helpers for picking apart vertex layouts
676
677    /**
678     * Helper function to compute the size of a vertex from a vertex layout
679     * @return size of a single vertex.
680     */
681    static size_t VertexSize(GrVertexLayout vertexLayout);
682
683    /**
684     * Helper function for determining the index of texture coordinates that
685     * is input for a texture stage. Note that a stage may instead use positions
686     * as texture coordinates, in which case the result of the function is
687     * indistinguishable from the case when the stage is disabled.
688     *
689     * @param stageIdx      the stage to query
690     * @param vertexLayout  layout to query
691     *
692     * @return the texture coordinate index or -1 if the stage doesn't use
693     *         separate (non-position) texture coordinates.
694     */
695    static int VertexTexCoordsForStage(int stageIdx, GrVertexLayout vertexLayout);
696
697    /**
698     * Helper function to compute the offset of texture coordinates in a vertex
699     * @return offset of texture coordinates in vertex layout or -1 if the
700     *         layout has no texture coordinates. Will be 0 if positions are
701     *         used as texture coordinates for the stage.
702     */
703    static int VertexStageCoordOffset(int stageIdx, GrVertexLayout vertexLayout);
704
705    /**
706     * Helper function to compute the offset of the color in a vertex
707     * @return offset of color in vertex layout or -1 if the
708     *         layout has no color.
709     */
710    static int VertexColorOffset(GrVertexLayout vertexLayout);
711
712    /**
713     * Helper function to compute the offset of the coverage in a vertex
714     * @return offset of coverage in vertex layout or -1 if the
715     *         layout has no coverage.
716     */
717    static int VertexCoverageOffset(GrVertexLayout vertexLayout);
718
719     /**
720      * Helper function to compute the offset of the edge pts in a vertex
721      * @return offset of edge in vertex layout or -1 if the
722      *         layout has no edge.
723      */
724     static int VertexEdgeOffset(GrVertexLayout vertexLayout);
725
726    /**
727     * Helper function to determine if vertex layout contains explicit texture
728     * coordinates of some index.
729     *
730     * @param coordIndex    the tex coord index to query
731     * @param vertexLayout  layout to query
732     *
733     * @return true if vertex specifies texture coordinates for the index,
734     *              false otherwise.
735     */
736    static bool VertexUsesTexCoordIdx(int coordIndex,
737                                      GrVertexLayout vertexLayout);
738
739    /**
740     * Helper function to compute the size of each vertex and the offsets of
741     * texture coordinates and color. Determines tex coord offsets by tex coord
742     * index rather than by stage. (Each stage can be mapped to any t.c. index
743     * by StageTexCoordVertexLayoutBit.)
744     *
745     * @param vertexLayout          the layout to query
746     * @param texCoordOffsetsByIdx  after return it is the offset of each
747     *                              tex coord index in the vertex or -1 if
748     *                              index isn't used. (optional)
749     * @param colorOffset           after return it is the offset of the
750     *                              color field in each vertex, or -1 if
751     *                              there aren't per-vertex colors. (optional)
752     * @param coverageOffset        after return it is the offset of the
753     *                              coverage field in each vertex, or -1 if
754     *                              there aren't per-vertex coeverages.
755     *                              (optional)
756     * @param edgeOffset            after return it is the offset of the
757     *                              edge eq field in each vertex, or -1 if
758     *                              there aren't per-vertex edge equations.
759     *                              (optional)
760     * @return size of a single vertex
761     */
762    static int VertexSizeAndOffsetsByIdx(GrVertexLayout vertexLayout,
763                   int texCoordOffsetsByIdx[GrDrawState::kMaxTexCoords],
764                   int *colorOffset,
765                   int *coverageOffset,
766                   int* edgeOffset);
767
768    /**
769     * Helper function to compute the size of each vertex and the offsets of
770     * texture coordinates and color. Determines tex coord offsets by stage
771     * rather than by index. (Each stage can be mapped to any t.c. index
772     * by StageTexCoordVertexLayoutBit.) If a stage uses positions for
773     * tex coords then that stage's offset will be 0 (positions are always at 0).
774     *
775     * @param vertexLayout              the layout to query
776     * @param texCoordOffsetsByStage    after return it is the offset of each
777     *                                  tex coord index in the vertex or -1 if
778     *                                  index isn't used. (optional)
779     * @param colorOffset               after return it is the offset of the
780     *                                  color field in each vertex, or -1 if
781     *                                  there aren't per-vertex colors.
782     *                                  (optional)
783     * @param coverageOffset            after return it is the offset of the
784     *                                  coverage field in each vertex, or -1 if
785     *                                  there aren't per-vertex coeverages.
786     *                                  (optional)
787     * @param edgeOffset                after return it is the offset of the
788     *                                  edge eq field in each vertex, or -1 if
789     *                                  there aren't per-vertex edge equations.
790     *                                  (optional)
791     * @return size of a single vertex
792     */
793    static int VertexSizeAndOffsetsByStage(GrVertexLayout vertexLayout,
794                   int texCoordOffsetsByStage[GrDrawState::kNumStages],
795                   int* colorOffset,
796                   int* coverageOffset,
797                   int* edgeOffset);
798
799    /**
800     * Accessing positions, texture coords, or colors, of a vertex within an
801     * array is a hassle involving casts and simple math. These helpers exist
802     * to keep GrDrawTarget clients' code a bit nicer looking.
803     */
804
805    /**
806     * Gets a pointer to a GrPoint of a vertex's position or texture
807     * coordinate.
808     * @param vertices      the vetex array
809     * @param vertexIndex   the index of the vertex in the array
810     * @param vertexSize    the size of each vertex in the array
811     * @param offset        the offset in bytes of the vertex component.
812     *                      Defaults to zero (corresponding to vertex position)
813     * @return pointer to the vertex component as a GrPoint
814     */
815    static GrPoint* GetVertexPoint(void* vertices,
816                                   int vertexIndex,
817                                   int vertexSize,
818                                   int offset = 0) {
819        intptr_t start = GrTCast<intptr_t>(vertices);
820        return GrTCast<GrPoint*>(start + offset +
821                                 vertexIndex * vertexSize);
822    }
823    static const GrPoint* GetVertexPoint(const void* vertices,
824                                         int vertexIndex,
825                                         int vertexSize,
826                                         int offset = 0) {
827        intptr_t start = GrTCast<intptr_t>(vertices);
828        return GrTCast<const GrPoint*>(start + offset +
829                                       vertexIndex * vertexSize);
830    }
831
832    /**
833     * Gets a pointer to a GrColor inside a vertex within a vertex array.
834     * @param vertices      the vetex array
835     * @param vertexIndex   the index of the vertex in the array
836     * @param vertexSize    the size of each vertex in the array
837     * @param offset        the offset in bytes of the vertex color
838     * @return pointer to the vertex component as a GrColor
839     */
840    static GrColor* GetVertexColor(void* vertices,
841                                   int vertexIndex,
842                                   int vertexSize,
843                                   int offset) {
844        intptr_t start = GrTCast<intptr_t>(vertices);
845        return GrTCast<GrColor*>(start + offset +
846                                 vertexIndex * vertexSize);
847    }
848    static const GrColor* GetVertexColor(const void* vertices,
849                                         int vertexIndex,
850                                         int vertexSize,
851                                         int offset) {
852        const intptr_t start = GrTCast<intptr_t>(vertices);
853        return GrTCast<const GrColor*>(start + offset +
854                                       vertexIndex * vertexSize);
855    }
856
857    static void VertexLayoutUnitTest();
858
859protected:
860
861    /**
862     * Optimizations for blending / coverage to be applied based on the current
863     * state.
864     * Subclasses that actually draw (as opposed to those that just buffer for
865     * playback) must implement the flags that replace the output color.
866     */
867    enum BlendOptFlags {
868        /**
869         * No optimization
870         */
871        kNone_BlendOpt = 0,
872        /**
873         * Don't draw at all
874         */
875        kSkipDraw_BlendOptFlag = 0x2,
876        /**
877         * Emit the src color, disable HW blending (replace dst with src)
878         */
879        kDisableBlend_BlendOptFlag = 0x4,
880        /**
881         * The coverage value does not have to be computed separately from
882         * alpha, the the output color can be the modulation of the two.
883         */
884        kCoverageAsAlpha_BlendOptFlag = 0x1,
885        /**
886         * Instead of emitting a src color, emit coverage in the alpha channel
887         * and r,g,b are "don't cares".
888         */
889        kEmitCoverage_BlendOptFlag = 0x10,
890        /**
891         * Emit transparent black instead of the src color, no need to compute
892         * coverage.
893         */
894        kEmitTransBlack_BlendOptFlag = 0x8,
895    };
896    GR_DECL_BITFIELD_OPS_FRIENDS(BlendOptFlags);
897
898    /**
899     * Determines what optimizations can be applied based on the blend. The coefficients may have
900     * to be tweaked in order for the optimization to work. srcCoeff and dstCoeff are optional
901     * params that receive the tweaked coefficients. Normally the function looks at the current
902     * state to see if coverage is enabled. By setting forceCoverage the caller can speculatively
903     * determine the blend optimizations that would be used if there was partial pixel coverage.
904     */
905    BlendOptFlags getBlendOpts(bool forceCoverage = false,
906                               GrBlendCoeff* srcCoeff = NULL,
907                               GrBlendCoeff* dstCoeff = NULL) const;
908
909    // determine if src alpha is guaranteed to be one for all src pixels
910    bool srcAlphaWillBeOne(GrVertexLayout vertexLayout) const;
911
912    enum GeometrySrcType {
913        kNone_GeometrySrcType,     //<! src has not been specified
914        kReserved_GeometrySrcType, //<! src was set using reserve*Space
915        kArray_GeometrySrcType,    //<! src was set using set*SourceToArray
916        kBuffer_GeometrySrcType    //<! src was set using set*SourceToBuffer
917    };
918
919    struct GeometrySrcState {
920        GeometrySrcType         fVertexSrc;
921        union {
922            // valid if src type is buffer
923            const GrVertexBuffer*   fVertexBuffer;
924            // valid if src type is reserved or array
925            int                     fVertexCount;
926        };
927
928        GeometrySrcType         fIndexSrc;
929        union {
930            // valid if src type is buffer
931            const GrIndexBuffer*    fIndexBuffer;
932            // valid if src type is reserved or array
933            int                     fIndexCount;
934        };
935
936        GrVertexLayout          fVertexLayout;
937    };
938
939    int indexCountInCurrentSource() const {
940        const GeometrySrcState& src = this->getGeomSrc();
941        switch (src.fIndexSrc) {
942            case kNone_GeometrySrcType:
943                return 0;
944            case kReserved_GeometrySrcType:
945            case kArray_GeometrySrcType:
946                return src.fIndexCount;
947            case kBuffer_GeometrySrcType:
948                return src.fIndexBuffer->sizeInBytes() / sizeof(uint16_t);
949            default:
950                GrCrash("Unexpected Index Source.");
951                return 0;
952        }
953    }
954
955    bool isStageEnabled(int stageIdx) const {
956        return this->getDrawState().isStageEnabled(stageIdx);
957    }
958
959    // A sublcass can optionally overload this function to be notified before
960    // vertex and index space is reserved.
961    virtual void willReserveVertexAndIndexSpace(GrVertexLayout vertexLayout,
962                                                int vertexCount,
963                                                int indexCount) {}
964
965
966    // implemented by subclass to allocate space for reserved geom
967    virtual bool onReserveVertexSpace(GrVertexLayout vertexLayout,
968                                      int vertexCount,
969                                      void** vertices) = 0;
970    virtual bool onReserveIndexSpace(int indexCount, void** indices) = 0;
971    // implemented by subclass to handle release of reserved geom space
972    virtual void releaseReservedVertexSpace() = 0;
973    virtual void releaseReservedIndexSpace() = 0;
974    // subclass must consume array contents when set
975    virtual void onSetVertexSourceToArray(const void* vertexArray,
976                                          int vertexCount) = 0;
977    virtual void onSetIndexSourceToArray(const void* indexArray,
978                                         int indexCount) = 0;
979    // subclass is notified that geom source will be set away from an array
980    virtual void releaseVertexArray() = 0;
981    virtual void releaseIndexArray() = 0;
982    // subclass overrides to be notified just before geo src state
983    // is pushed/popped.
984    virtual void geometrySourceWillPush() = 0;
985    virtual void geometrySourceWillPop(const GeometrySrcState& restoredState) = 0;
986    // subclass called to perform drawing
987    virtual void onDrawIndexed(GrPrimitiveType type,
988                               int startVertex,
989                               int startIndex,
990                               int vertexCount,
991                               int indexCount) = 0;
992    virtual void onDrawNonIndexed(GrPrimitiveType type,
993                                  int startVertex,
994                                  int vertexCount) = 0;
995    virtual void onStencilPath(const GrPath*, const SkStroke& stroke, SkPath::FillType fill) = 0;
996
997    // subclass overrides to be notified when clip is set. Must call
998    // INHERITED::clipwillBeSet
999    virtual void clipWillBeSet(const GrClipData* clipData) {}
1000
1001    // Helpers for drawRect, protected so subclasses that override drawRect
1002    // can use them.
1003    static GrVertexLayout GetRectVertexLayout(const GrRect* srcRects[]);
1004
1005    static void SetRectVertices(const GrRect& rect,
1006                                const SkMatrix* matrix,
1007                                const GrRect* srcRects[],
1008                                const SkMatrix* srcMatrices[],
1009                                GrColor color,
1010                                GrVertexLayout layout,
1011                                void* vertices);
1012
1013    // accessors for derived classes
1014    const GeometrySrcState& getGeomSrc() const {
1015        return fGeoSrcStateStack.back();
1016    }
1017    // it is prefereable to call this rather than getGeomSrc()->fVertexLayout
1018    // because of the assert.
1019    GrVertexLayout getVertexLayout() const {
1020        // the vertex layout is only valid if a vertex source has been
1021        // specified.
1022        GrAssert(this->getGeomSrc().fVertexSrc != kNone_GeometrySrcType);
1023        return this->getGeomSrc().fVertexLayout;
1024    }
1025
1026    // allows derived class to set the caps
1027    CapsInternals* capsInternals() { return &fCaps.fInternals; }
1028
1029    const GrClipData* fClip;
1030
1031    GrDrawState* fDrawState;
1032    GrDrawState fDefaultDrawState;
1033
1034    Caps fCaps;
1035
1036    // subclasses must call this in their destructors to ensure all vertex
1037    // and index sources have been released (including those held by
1038    // pushGeometrySource())
1039    void releaseGeometry();
1040
1041private:
1042    // helpers for reserving vertex and index space.
1043    bool reserveVertexSpace(GrVertexLayout vertexLayout,
1044                            int vertexCount,
1045                            void** vertices);
1046    bool reserveIndexSpace(int indexCount, void** indices);
1047
1048    // called by drawIndexed and drawNonIndexed. Use a negative indexCount to
1049    // indicate non-indexed drawing.
1050    bool checkDraw(GrPrimitiveType type, int startVertex,
1051                   int startIndex, int vertexCount,
1052                   int indexCount) const;
1053    // called when setting a new vert/idx source to unref prev vb/ib
1054    void releasePreviousVertexSource();
1055    void releasePreviousIndexSource();
1056
1057    enum {
1058        kPreallocGeoSrcStateStackCnt = 4,
1059    };
1060    SkSTArray<kPreallocGeoSrcStateStackCnt,
1061              GeometrySrcState, true>           fGeoSrcStateStack;
1062
1063    typedef GrRefCnt INHERITED;
1064};
1065
1066GR_MAKE_BITFIELD_OPS(GrDrawTarget::BlendOptFlags);
1067
1068#endif
1069