Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / third_party / skia / src / gpu / GrDrawState.h
1 /*
2  * Copyright 2011 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7
8 #ifndef GrDrawState_DEFINED
9 #define GrDrawState_DEFINED
10
11
12 #include "GrBlend.h"
13 #include "GrDrawTargetCaps.h"
14 #include "GrGeometryProcessor.h"
15 #include "GrGpuResourceRef.h"
16 #include "GrProcessorStage.h"
17 #include "GrRenderTarget.h"
18 #include "GrStencil.h"
19 #include "SkMatrix.h"
20 #include "effects/GrSimpleTextureEffect.h"
21
22 class GrDrawTargetCaps;
23 class GrOptDrawState;
24 class GrPaint;
25 class GrTexture;
26
27 class GrDrawState : public SkRefCnt {
28 public:
29     SK_DECLARE_INST_COUNT(GrDrawState)
30
31     GrDrawState() : fCachedOptState(NULL) {
32         SkDEBUGCODE(fBlockEffectRemovalCnt = 0;)
33         this->reset();
34     }
35
36     GrDrawState(const SkMatrix& initialViewMatrix) : fCachedOptState(NULL) {
37         SkDEBUGCODE(fBlockEffectRemovalCnt = 0;)
38         this->reset(initialViewMatrix);
39     }
40
41     /**
42      * Copies another draw state.
43      **/
44     GrDrawState(const GrDrawState& state) : INHERITED(), fCachedOptState(NULL) {
45         SkDEBUGCODE(fBlockEffectRemovalCnt = 0;)
46         *this = state;
47     }
48
49     /**
50      * Copies another draw state with a preconcat to the view matrix.
51      **/
52     GrDrawState(const GrDrawState& state, const SkMatrix& preConcatMatrix);
53
54     virtual ~GrDrawState();
55
56     /**
57      * Resets to the default state. GrProcessors will be removed from all stages.
58      */
59     void reset() { this->onReset(NULL); }
60
61     void reset(const SkMatrix& initialViewMatrix) { this->onReset(&initialViewMatrix); }
62
63     /**
64      * Initializes the GrDrawState based on a GrPaint, view matrix and render target. Note that
65      * GrDrawState encompasses more than GrPaint. Aspects of GrDrawState that have no GrPaint
66      * equivalents are set to default values with the exception of vertex attribute state which
67      * is unmodified by this function and clipping which will be enabled.
68      */
69     void setFromPaint(const GrPaint& , const SkMatrix& viewMatrix, GrRenderTarget*);
70
71     ///////////////////////////////////////////////////////////////////////////
72     /// @name Vertex Attributes
73     ////
74
75     enum {
76         kMaxVertexAttribCnt = kLast_GrVertexAttribBinding + 4,
77     };
78
79     const GrVertexAttrib* getVertexAttribs() const { return fVAPtr; }
80     int getVertexAttribCount() const { return fVACount; }
81
82     size_t getVertexStride() const { return fVAStride; }
83
84     bool hasLocalCoordAttribute() const {
85         return -1 != fFixedFunctionVertexAttribIndices[kLocalCoord_GrVertexAttribBinding];
86     }
87     bool hasColorVertexAttribute() const {
88         return -1 != fFixedFunctionVertexAttribIndices[kColor_GrVertexAttribBinding];
89     }
90     bool hasCoverageVertexAttribute() const {
91         return -1 != fFixedFunctionVertexAttribIndices[kCoverage_GrVertexAttribBinding];
92     }
93
94     const int* getFixedFunctionVertexAttribIndices() const {
95         return fFixedFunctionVertexAttribIndices;
96     }
97
98     bool validateVertexAttribs() const;
99
100    /**
101      * The format of vertices is represented as an array of GrVertexAttribs, with each representing
102      * the type of the attribute, its offset, and semantic binding (see GrVertexAttrib in
103      * GrTypesPriv.h).
104      *
105      * The mapping of attributes with kEffect bindings to GrProcessor inputs is specified when
106      * setEffect is called.
107      */
108
109     /**
110      *  Sets vertex attributes for next draw. The object driving the templatization
111      *  should be a global GrVertexAttrib array that is never changed.
112      *
113      *  @param count      the number of attributes being set, limited to kMaxVertexAttribCnt.
114      *  @param stride     the number of bytes between successive vertex data.
115      */
116     template <const GrVertexAttrib A[]> void setVertexAttribs(int count, size_t stride) {
117         this->internalSetVertexAttribs(A, count, stride);
118     }
119
120     /**
121      *  Sets default vertex attributes for next draw. The default is a single attribute:
122      *  {kVec2f_GrVertexAttribType, 0, kPosition_GrVertexAttribType}
123      */
124     void setDefaultVertexAttribs();
125
126     /**
127      * Helper to save/restore vertex attribs
128      */
129      class AutoVertexAttribRestore {
130      public:
131          AutoVertexAttribRestore(GrDrawState* drawState);
132
133          ~AutoVertexAttribRestore() { fDrawState->internalSetVertexAttribs(fVAPtr, fVACount,
134                                                                            fVAStride); }
135
136      private:
137          GrDrawState*          fDrawState;
138          const GrVertexAttrib* fVAPtr;
139          int                   fVACount;
140          size_t                fVAStride;
141      };
142
143     /// @}
144
145     /**
146      * Depending on features available in the underlying 3D API and the color blend mode requested
147      * it may or may not be possible to correctly blend with fractional pixel coverage generated by
148      * the fragment shader.
149      *
150      * This function considers the current draw state and the draw target's capabilities to
151      * determine whether coverage can be handled correctly. This function assumes that the caller
152      * intends to specify fractional pixel coverage (via setCoverage(), through a coverage vertex
153      * attribute, or a coverage effect) but may not have specified it yet.
154      */
155     bool couldApplyCoverage(const GrDrawTargetCaps& caps) const;
156
157     /**
158      * Determines whether the output coverage is guaranteed to be one for all pixels hit by a draw.
159      */
160     bool hasSolidCoverage() const;
161
162     /// @}
163
164     ///////////////////////////////////////////////////////////////////////////
165     /// @name Color
166     ////
167
168     GrColor getColor() const { return fColor; }
169
170     /**
171      *  Sets color for next draw to a premultiplied-alpha color.
172      *
173      *  @param color    the color to set.
174      */
175     void setColor(GrColor color) {
176         if (color != fColor) {
177             fColor = color;
178             this->invalidateOptState();
179         }
180     }
181
182     /**
183      *  Sets the color to be used for the next draw to be
184      *  (r,g,b,a) = (alpha, alpha, alpha, alpha).
185      *
186      *  @param alpha The alpha value to set as the color.
187      */
188     void setAlpha(uint8_t a) { this->setColor((a << 24) | (a << 16) | (a << 8) | a); }
189
190     /// @}
191
192     ///////////////////////////////////////////////////////////////////////////
193     /// @name Coverage
194     ////
195
196     uint8_t getCoverage() const { return fCoverage; }
197
198     GrColor getCoverageColor() const {
199         return GrColorPackRGBA(fCoverage, fCoverage, fCoverage, fCoverage);
200     }
201
202     /**
203      * Sets a constant fractional coverage to be applied to the draw. The
204      * initial value (after construction or reset()) is 0xff. The constant
205      * coverage is ignored when per-vertex coverage is provided.
206      */
207     void setCoverage(uint8_t coverage) {
208         if (coverage != fCoverage) {
209             fCoverage = coverage;
210             this->invalidateOptState();
211         }
212     }
213
214     /// @}
215
216     /**
217      * The geometry processor is the sole element of the skia pipeline which can use the vertex,
218      * geometry, and tesselation shaders.  The GP may also compute a coverage in its fragment shader
219      * but is never put in the color processing pipeline.
220      */
221
222     const GrGeometryProcessor* setGeometryProcessor(const GrGeometryProcessor* geometryProcessor) {
223         SkASSERT(geometryProcessor);
224         SkASSERT(!this->hasGeometryProcessor());
225         fGeometryProcessor.reset(SkRef(geometryProcessor));
226         this->invalidateOptState();
227         return geometryProcessor;
228     }
229
230     ///////////////////////////////////////////////////////////////////////////
231     /// @name Effect Stages
232     /// Each stage hosts a GrProcessor. The effect produces an output color or coverage in the
233     /// fragment shader. Its inputs are the output from the previous stage as well as some variables
234     /// available to it in the fragment and vertex shader (e.g. the vertex position, the dst color,
235     /// the fragment position, local coordinates).
236     ///
237     /// The stages are divided into two sets, color-computing and coverage-computing. The final
238     /// color stage produces the final pixel color. The coverage-computing stages function exactly
239     /// as the color-computing but the output of the final coverage stage is treated as a fractional
240     /// pixel coverage rather than as input to the src/dst color blend step.
241     ///
242     /// The input color to the first color-stage is either the constant color or interpolated
243     /// per-vertex colors. The input to the first coverage stage is either a constant coverage
244     /// (usually full-coverage) or interpolated per-vertex coverage.
245     ///
246     /// See the documentation of kCoverageDrawing_StateBit for information about disabling the
247     /// the color / coverage distinction.
248     ////
249
250     int numColorStages() const { return fColorStages.count(); }
251     int numCoverageStages() const { return fCoverageStages.count(); }
252     int numTotalStages() const {
253          return this->numColorStages() + this->numCoverageStages() +
254                  (this->hasGeometryProcessor() ? 1 : 0);
255     }
256
257     bool hasGeometryProcessor() const { return SkToBool(fGeometryProcessor.get()); }
258     const GrGeometryProcessor* getGeometryProcessor() const { return fGeometryProcessor.get(); }
259     const GrFragmentStage& getColorStage(int idx) const { return fColorStages[idx]; }
260     const GrFragmentStage& getCoverageStage(int idx) const { return fCoverageStages[idx]; }
261
262     /**
263      * Checks whether any of the effects will read the dst pixel color.
264      */
265     bool willEffectReadDstColor() const;
266
267     const GrFragmentProcessor* addColorProcessor(const GrFragmentProcessor* effect) {
268         SkASSERT(effect);
269         SkNEW_APPEND_TO_TARRAY(&fColorStages, GrFragmentStage, (effect));
270         this->invalidateOptState();
271         return effect;
272     }
273
274     const GrFragmentProcessor* addCoverageProcessor(const GrFragmentProcessor* effect) {
275         SkASSERT(effect);
276         SkNEW_APPEND_TO_TARRAY(&fCoverageStages, GrFragmentStage, (effect));
277         this->invalidateOptState();
278         return effect;
279     }
280
281     /**
282      * Creates a GrSimpleTextureEffect that uses local coords as texture coordinates.
283      */
284     void addColorTextureProcessor(GrTexture* texture, const SkMatrix& matrix) {
285         this->addColorProcessor(GrSimpleTextureEffect::Create(texture, matrix))->unref();
286     }
287
288     void addCoverageTextureProcessor(GrTexture* texture, const SkMatrix& matrix) {
289         this->addCoverageProcessor(GrSimpleTextureEffect::Create(texture, matrix))->unref();
290     }
291
292     void addColorTextureProcessor(GrTexture* texture,
293                                   const SkMatrix& matrix,
294                                   const GrTextureParams& params) {
295         this->addColorProcessor(GrSimpleTextureEffect::Create(texture, matrix, params))->unref();
296     }
297
298     void addCoverageTextureProcessor(GrTexture* texture,
299                                      const SkMatrix& matrix,
300                                      const GrTextureParams& params) {
301         this->addCoverageProcessor(GrSimpleTextureEffect::Create(texture, matrix, params))->unref();
302     }
303
304     /**
305      * When this object is destroyed it will remove any color/coverage effects from the draw state
306      * that were added after its constructor.
307      *
308      * This class has strange behavior around geometry processor. If there is a GP on the draw state
309      * it will assert that the GP is not modified until after the destructor of the ARE. If the
310      * draw state has a NULL GP when the ARE is constructed then it will reset it to null in the
311      * destructor.
312      *
313      * TODO: We'd prefer for the ARE to just save and restore the GP. However, this would add
314      * significant complexity to the multi-ref architecture for deferred drawing. Once GrDrawState
315      * and GrOptDrawState are fully separated then GrDrawState will never be in the deferred
316      * execution state and GrOptDrawState always will be (and will be immutable and therefore
317      * unable to have an ARE). At this point we can restore sanity and have the ARE save and restore
318      * the GP.
319      */
320     class AutoRestoreEffects : public ::SkNoncopyable {
321     public:
322         AutoRestoreEffects() 
323             : fDrawState(NULL)
324             , fOriginalGPID(SK_InvalidUniqueID)
325             , fColorEffectCnt(0)
326             , fCoverageEffectCnt(0) {}
327
328         AutoRestoreEffects(GrDrawState* ds)
329             : fDrawState(NULL)
330             , fOriginalGPID(SK_InvalidUniqueID)
331             , fColorEffectCnt(0)
332             , fCoverageEffectCnt(0) {
333             this->set(ds);
334         }
335
336         ~AutoRestoreEffects() { this->set(NULL); }
337
338         void set(GrDrawState* ds);
339
340         bool isSet() const { return SkToBool(fDrawState); }
341
342     private:
343         GrDrawState*    fDrawState;
344         uint32_t        fOriginalGPID;
345         int             fColorEffectCnt;
346         int             fCoverageEffectCnt;
347     };
348
349     /**
350      * AutoRestoreStencil
351      *
352      * This simple struct saves and restores the stencil settings
353      */
354     class AutoRestoreStencil : public ::SkNoncopyable {
355     public:
356         AutoRestoreStencil() : fDrawState(NULL) {}
357
358         AutoRestoreStencil(GrDrawState* ds) : fDrawState(NULL) { this->set(ds); }
359
360         ~AutoRestoreStencil() { this->set(NULL); }
361
362         void set(GrDrawState* ds) {
363             if (fDrawState) {
364                 fDrawState->setStencil(fStencilSettings);
365             }
366             fDrawState = ds;
367             if (ds) {
368                 fStencilSettings = ds->getStencil();
369             }
370         }
371
372         bool isSet() const { return SkToBool(fDrawState); }
373
374     private:
375         GrDrawState*       fDrawState;
376         GrStencilSettings  fStencilSettings;
377     };
378
379     /// @}
380
381     ///////////////////////////////////////////////////////////////////////////
382     /// @name Blending
383     ////
384
385     GrBlendCoeff getSrcBlendCoeff() const { return fSrcBlend; }
386     GrBlendCoeff getDstBlendCoeff() const { return fDstBlend; }
387
388     /**
389      * Retrieves the last value set by setBlendConstant()
390      * @return the blending constant value
391      */
392     GrColor getBlendConstant() const { return fBlendConstant; }
393
394     /**
395      * Determines whether multiplying the computed per-pixel color by the pixel's fractional
396      * coverage before the blend will give the correct final destination color. In general it
397      * will not as coverage is applied after blending.
398      */
399     bool canTweakAlphaForCoverage() const;
400
401     /**
402      * Sets the blending function coefficients.
403      *
404      * The blend function will be:
405      *    D' = sat(S*srcCoef + D*dstCoef)
406      *
407      *   where D is the existing destination color, S is the incoming source
408      *   color, and D' is the new destination color that will be written. sat()
409      *   is the saturation function.
410      *
411      * @param srcCoef coefficient applied to the src color.
412      * @param dstCoef coefficient applied to the dst color.
413      */
414     void setBlendFunc(GrBlendCoeff srcCoeff, GrBlendCoeff dstCoeff) {
415         if (srcCoeff != fSrcBlend || dstCoeff != fDstBlend) {
416             fSrcBlend = srcCoeff;
417             fDstBlend = dstCoeff;
418             this->invalidateOptState();
419         }
420     #ifdef SK_DEBUG
421         if (GrBlendCoeffRefsDst(dstCoeff)) {
422             SkDebugf("Unexpected dst blend coeff. Won't work correctly with coverage stages.\n");
423         }
424         if (GrBlendCoeffRefsSrc(srcCoeff)) {
425             SkDebugf("Unexpected src blend coeff. Won't work correctly with coverage stages.\n");
426         }
427     #endif
428     }
429
430     /**
431      * Sets the blending function constant referenced by the following blending
432      * coefficients:
433      *      kConstC_GrBlendCoeff
434      *      kIConstC_GrBlendCoeff
435      *      kConstA_GrBlendCoeff
436      *      kIConstA_GrBlendCoeff
437      *
438      * @param constant the constant to set
439      */
440     void setBlendConstant(GrColor constant) {
441         if (constant != fBlendConstant) {
442             fBlendConstant = constant;
443             this->invalidateOptState();
444         }
445     }
446
447     /// @}
448
449     ///////////////////////////////////////////////////////////////////////////
450     /// @name View Matrix
451     ////
452
453     /**
454      * Retrieves the current view matrix
455      * @return the current view matrix.
456      */
457     const SkMatrix& getViewMatrix() const { return fViewMatrix; }
458
459     /**
460      *  Retrieves the inverse of the current view matrix.
461      *
462      *  If the current view matrix is invertible, return true, and if matrix
463      *  is non-null, copy the inverse into it. If the current view matrix is
464      *  non-invertible, return false and ignore the matrix parameter.
465      *
466      * @param matrix if not null, will receive a copy of the current inverse.
467      */
468     bool getViewInverse(SkMatrix* matrix) const {
469         SkMatrix inverse;
470         if (fViewMatrix.invert(&inverse)) {
471             if (matrix) {
472                 *matrix = inverse;
473             }
474             return true;
475         }
476         return false;
477     }
478
479     /**
480      * Sets the view matrix to identity and updates any installed effects to compensate for the
481      * coord system change.
482      */
483     bool setIdentityViewMatrix();
484
485     ////////////////////////////////////////////////////////////////////////////
486
487     /**
488      * Preconcats the current view matrix and restores the previous view matrix in the destructor.
489      * Effect matrices are automatically adjusted to compensate and adjusted back in the destructor.
490      */
491     class AutoViewMatrixRestore : public ::SkNoncopyable {
492     public:
493         AutoViewMatrixRestore() : fDrawState(NULL) {}
494
495         AutoViewMatrixRestore(GrDrawState* ds, const SkMatrix& preconcatMatrix) {
496             fDrawState = NULL;
497             this->set(ds, preconcatMatrix);
498         }
499
500         ~AutoViewMatrixRestore() { this->restore(); }
501
502         /**
503          * Can be called prior to destructor to restore the original matrix.
504          */
505         void restore();
506
507         void set(GrDrawState* drawState, const SkMatrix& preconcatMatrix);
508
509         /** Sets the draw state's matrix to identity. This can fail because the current view matrix
510             is not invertible. */
511         bool setIdentity(GrDrawState* drawState);
512
513     private:
514         void doEffectCoordChanges(const SkMatrix& coordChangeMatrix);
515
516         GrDrawState*                                           fDrawState;
517         SkMatrix                                               fViewMatrix;
518         int                                                    fNumColorStages;
519         SkAutoSTArray<8, GrFragmentStage::SavedCoordChange>    fSavedCoordChanges;
520     };
521
522     /// @}
523
524     ///////////////////////////////////////////////////////////////////////////
525     /// @name Render Target
526     ////
527
528     /**
529      * Retrieves the currently set render-target.
530      *
531      * @return    The currently set render target.
532      */
533     GrRenderTarget* getRenderTarget() const { return fRenderTarget.get(); }
534
535     /**
536      * Sets the render-target used at the next drawing call
537      *
538      * @param target  The render target to set.
539      */
540     void setRenderTarget(GrRenderTarget* target) {
541         fRenderTarget.set(SkSafeRef(target), kWrite_GrIOType);
542         this->invalidateOptState();
543     }
544
545     /// @}
546
547     ///////////////////////////////////////////////////////////////////////////
548     /// @name Stencil
549     ////
550
551     const GrStencilSettings& getStencil() const { return fStencilSettings; }
552
553     /**
554      * Sets the stencil settings to use for the next draw.
555      * Changing the clip has the side-effect of possibly zeroing
556      * out the client settable stencil bits. So multipass algorithms
557      * using stencil should not change the clip between passes.
558      * @param settings  the stencil settings to use.
559      */
560     void setStencil(const GrStencilSettings& settings) {
561         if (settings != fStencilSettings) {
562             fStencilSettings = settings;
563             this->invalidateOptState();
564         }
565     }
566
567     /**
568      * Shortcut to disable stencil testing and ops.
569      */
570     void disableStencil() {
571         if (!fStencilSettings.isDisabled()) {
572             fStencilSettings.setDisabled();
573             this->invalidateOptState();
574         }
575     }
576
577     GrStencilSettings* stencil() { return &fStencilSettings; }
578
579     /// @}
580
581     ///////////////////////////////////////////////////////////////////////////
582     /// @name State Flags
583     ////
584
585     /**
586      *  Flags that affect rendering. Controlled using enable/disableState(). All
587      *  default to disabled.
588      */
589     enum StateBits {
590         /**
591          * Perform dithering. TODO: Re-evaluate whether we need this bit
592          */
593         kDither_StateBit        = 0x01,
594         /**
595          * Perform HW anti-aliasing. This means either HW FSAA, if supported by the render target,
596          * or smooth-line rendering if a line primitive is drawn and line smoothing is supported by
597          * the 3D API.
598          */
599         kHWAntialias_StateBit   = 0x02,
600         /**
601          * Draws will respect the clip, otherwise the clip is ignored.
602          */
603         kClip_StateBit          = 0x04,
604         /**
605          * Disables writing to the color buffer. Useful when performing stencil
606          * operations.
607          */
608         kNoColorWrites_StateBit = 0x08,
609
610         /**
611          * Usually coverage is applied after color blending. The color is blended using the coeffs
612          * specified by setBlendFunc(). The blended color is then combined with dst using coeffs
613          * of src_coverage, 1-src_coverage. Sometimes we are explicitly drawing a coverage mask. In
614          * this case there is no distinction between coverage and color and the caller needs direct
615          * control over the blend coeffs. When set, there will be a single blend step controlled by
616          * setBlendFunc() which will use coverage*color as the src color.
617          */
618          kCoverageDrawing_StateBit = 0x10,
619          kLast_StateBit = kCoverageDrawing_StateBit,
620     };
621
622     uint32_t getFlagBits() const { return fFlagBits; }
623
624     bool isStateFlagEnabled(uint32_t stateBit) const { return 0 != (stateBit & fFlagBits); }
625
626     bool isClipState() const { return 0 != (fFlagBits & kClip_StateBit); }
627     bool isColorWriteDisabled() const { return 0 != (fFlagBits & kNoColorWrites_StateBit); }
628     bool isCoverageDrawing() const { return 0 != (fFlagBits & kCoverageDrawing_StateBit); }
629
630     void resetStateFlags() {
631         if (0 != fFlagBits) {
632             fFlagBits = 0;
633             this->invalidateOptState();
634         }
635     }
636
637     /**
638      * Enable render state settings.
639      *
640      * @param stateBits bitfield of StateBits specifying the states to enable
641      */
642     void enableState(uint32_t stateBits) {
643         if (stateBits & ~fFlagBits) {
644             fFlagBits |= stateBits;
645             this->invalidateOptState();
646         }
647     }
648
649     /**
650      * Disable render state settings.
651      *
652      * @param stateBits bitfield of StateBits specifying the states to disable
653      */
654     void disableState(uint32_t stateBits) {
655         if (stateBits & fFlagBits) {
656             fFlagBits &= ~(stateBits);
657             this->invalidateOptState();
658         }
659     }
660
661     /**
662      * Enable or disable stateBits based on a boolean.
663      *
664      * @param stateBits bitfield of StateBits to enable or disable
665      * @param enable    if true enable stateBits, otherwise disable
666      */
667     void setState(uint32_t stateBits, bool enable) {
668         if (enable) {
669             this->enableState(stateBits);
670         } else {
671             this->disableState(stateBits);
672         }
673     }
674
675     /// @}
676
677     ///////////////////////////////////////////////////////////////////////////
678     /// @name Face Culling
679     ////
680
681     enum DrawFace {
682         kInvalid_DrawFace = -1,
683
684         kBoth_DrawFace,
685         kCCW_DrawFace,
686         kCW_DrawFace,
687     };
688
689     /**
690      * Gets whether the target is drawing clockwise, counterclockwise,
691      * or both faces.
692      * @return the current draw face(s).
693      */
694     DrawFace getDrawFace() const { return fDrawFace; }
695
696     /**
697      * Controls whether clockwise, counterclockwise, or both faces are drawn.
698      * @param face  the face(s) to draw.
699      */
700     void setDrawFace(DrawFace face) {
701         SkASSERT(kInvalid_DrawFace != face);
702         fDrawFace = face;
703     }
704
705     /// @}
706
707     ///////////////////////////////////////////////////////////////////////////
708     /// @name Hints
709     /// Hints that when provided can enable optimizations.
710     ////
711
712     enum Hints {
713         kVertexColorsAreOpaque_Hint = 0x1,
714         kLast_Hint = kVertexColorsAreOpaque_Hint
715     };
716
717     void setHint(Hints hint, bool value) { fHints = value ? (fHints | hint) : (fHints & ~hint); }
718
719     bool vertexColorsAreOpaque() const { return kVertexColorsAreOpaque_Hint & fHints; }
720
721     /// @}
722
723     ///////////////////////////////////////////////////////////////////////////
724
725     /** Return type for CombineIfPossible. */
726     enum CombinedState {
727         /** The GrDrawStates cannot be combined. */
728         kIncompatible_CombinedState,
729         /** Either draw state can be used in place of the other. */
730         kAOrB_CombinedState,
731         /** Use the first draw state. */
732         kA_CombinedState,
733         /** Use the second draw state. */
734         kB_CombinedState,
735     };
736
737     /** This function determines whether the GrDrawStates used for two draws can be combined into
738         a single GrDrawState. This is used to avoid storing redundant GrDrawStates and to determine
739         if draws can be batched. The return value indicates whether combining is possible and, if
740         so, which of the two inputs should be used. */
741     static CombinedState CombineIfPossible(const GrDrawState& a, const GrDrawState& b,
742                                            const GrDrawTargetCaps& caps);
743
744     GrDrawState& operator= (const GrDrawState& that);
745
746 private:
747     /**
748      * Converts refs on GrGpuResources owned directly or indirectly by this GrDrawState into
749      * pending reads and writes. This should be called when a GrDrawState is recorded into
750      * a GrDrawTarget for later execution. Subclasses of GrDrawState may add setters. However,
751      * once this call has been made the GrDrawState is immutable. It is also no longer copyable.
752      * In the future this conversion will automatically happen when converting a GrDrawState into
753      * an optimized draw state.
754      */
755     void convertToPendingExec();
756
757     friend class GrDrawTarget;
758
759     bool isEqual(const GrDrawState& that) const;
760
761     /**
762      * Optimizations for blending / coverage to that can be applied based on the current state.
763      */
764     enum BlendOptFlags {
765         /**
766          * No optimization
767          */
768         kNone_BlendOpt                  = 0,
769         /**
770          * Don't draw at all
771          */
772         kSkipDraw_BlendOptFlag          = 0x1,
773         /**
774          * The coverage value does not have to be computed separately from alpha, the the output
775          * color can be the modulation of the two.
776          */
777         kCoverageAsAlpha_BlendOptFlag   = 0x2,
778         /**
779          * Instead of emitting a src color, emit coverage in the alpha channel and r,g,b are
780          * "don't cares".
781          */
782         kEmitCoverage_BlendOptFlag      = 0x4,
783         /**
784          * Emit transparent black instead of the src color, no need to compute coverage.
785          */
786         kEmitTransBlack_BlendOptFlag    = 0x8,
787     };
788     GR_DECL_BITFIELD_OPS_FRIENDS(BlendOptFlags);
789
790     /**
791      * Determines what optimizations can be applied based on the blend. The coefficients may have
792      * to be tweaked in order for the optimization to work. srcCoeff and dstCoeff are optional
793      * params that receive the tweaked coefficients. Normally the function looks at the current
794      * state to see if coverage is enabled. By setting forceCoverage the caller can speculatively
795      * determine the blend optimizations that would be used if there was partial pixel coverage.
796      *
797      * Subclasses of GrDrawTarget that actually draw (as opposed to those that just buffer for
798      * playback) must call this function and respect the flags that replace the output color.
799      *
800      * If the cached BlendOptFlags does not have the invalidate bit set, then getBlendOpts will
801      * simply returned the cached flags and coefficients. Otherwise it will calculate the values. 
802      */
803     BlendOptFlags getBlendOpts(bool forceCoverage = false,
804                                GrBlendCoeff* srcCoeff = NULL,
805                                GrBlendCoeff* dstCoeff = NULL) const;
806
807     /**
808      * Determines whether src alpha is guaranteed to be one for all src pixels
809      */
810     bool srcAlphaWillBeOne() const;
811
812     void invalidateOptState() const;
813
814     void onReset(const SkMatrix* initialViewMatrix);
815
816     // Some of the auto restore objects assume that no effects are removed during their lifetime.
817     // This is used to assert that this condition holds.
818     SkDEBUGCODE(int fBlockEffectRemovalCnt;)
819
820     void internalSetVertexAttribs(const GrVertexAttrib attribs[], int count, size_t stride);
821
822     typedef GrTGpuResourceRef<GrRenderTarget> ProgramRenderTarget;
823     // These fields are roughly sorted by decreasing likelihood of being different in op==
824     ProgramRenderTarget                 fRenderTarget;
825     GrColor                             fColor;
826     SkMatrix                            fViewMatrix;
827     GrColor                             fBlendConstant;
828     uint32_t                            fFlagBits;
829     const GrVertexAttrib*               fVAPtr;
830     int                                 fVACount;
831     size_t                              fVAStride;
832     GrStencilSettings                   fStencilSettings;
833     uint8_t                             fCoverage;
834     DrawFace                            fDrawFace;
835     GrBlendCoeff                        fSrcBlend;
836     GrBlendCoeff                        fDstBlend;
837
838     typedef SkSTArray<4, GrFragmentStage> FragmentStageArray;
839     typedef GrProgramElementRef<const GrGeometryProcessor> ProgramGeometryProcessor;
840     ProgramGeometryProcessor            fGeometryProcessor;
841     FragmentStageArray                  fColorStages;
842     FragmentStageArray                  fCoverageStages;
843
844     uint32_t                            fHints;
845
846     // This is simply a different representation of info in fVertexAttribs and thus does
847     // not need to be compared in op==.
848     int fFixedFunctionVertexAttribIndices[kGrFixedFunctionVertexAttribBindingCnt];
849
850     mutable GrOptDrawState* fCachedOptState;
851     mutable uint32_t fCachedCapsID;
852
853     friend class GrOptDrawState;
854
855     typedef SkRefCnt INHERITED;
856 };
857
858 GR_MAKE_BITFIELD_OPS(GrDrawState::BlendOptFlags);
859
860 #endif