GrContext.h revision a0b40280a49a8a43af7929ead3b3489951c58501
1/*
2 * Copyright 2010 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 GrContext_DEFINED
9#define GrContext_DEFINED
10
11#include "GrClipData.h"
12#include "GrColor.h"
13#include "GrPaint.h"
14#include "GrPathRendererChain.h"
15#include "GrPoint.h"
16#include "GrRenderTarget.h"
17#include "GrTexture.h"
18#include "SkMatrix.h"
19#include "SkTypes.h"
20
21class GrAARectRenderer;
22class GrAutoScratchTexture;
23class GrDrawState;
24class GrDrawTarget;
25class GrEffect;
26class GrFontCache;
27class GrGpu;
28class GrIndexBuffer;
29class GrIndexBufferAllocPool;
30class GrInOrderDrawBuffer;
31class GrOvalRenderer;
32class GrPathRenderer;
33class GrResourceEntry;
34class GrResourceCache;
35class GrStencilBuffer;
36class GrTestTarget;
37class GrTextureParams;
38class GrVertexBuffer;
39class GrVertexBufferAllocPool;
40class GrSoftwarePathRenderer;
41class SkStrokeRec;
42
43class SK_API GrContext : public SkRefCnt {
44public:
45    SK_DECLARE_INST_COUNT(GrContext)
46
47    /**
48     * Creates a GrContext for a backend context.
49     */
50    static GrContext* Create(GrBackend, GrBackendContext);
51
52    /**
53     * Returns the number of GrContext instances for the current thread.
54     */
55    static int GetThreadInstanceCount();
56
57    virtual ~GrContext();
58
59    /**
60     * The GrContext normally assumes that no outsider is setting state
61     * within the underlying 3D API's context/device/whatever. This call informs
62     * the context that the state was modified and it should resend. Shouldn't
63     * be called frequently for good performance.
64     * The flag bits, state, is dpendent on which backend is used by the
65     * context, either GL or D3D (possible in future).
66     */
67    void resetContext(uint32_t state = kAll_GrBackendState);
68
69    /**
70     * Callback function to allow classes to cleanup on GrContext destruction.
71     * The 'info' field is filled in with the 'info' passed to addCleanUp.
72     */
73    typedef void (*PFCleanUpFunc)(const GrContext* context, void* info);
74
75    /**
76     * Add a function to be called from within GrContext's destructor.
77     * This gives classes a chance to free resources held on a per context basis.
78     * The 'info' parameter will be stored and passed to the callback function.
79     */
80    void addCleanUp(PFCleanUpFunc cleanUp, void* info) {
81        CleanUpData* entry = fCleanUpData.push();
82
83        entry->fFunc = cleanUp;
84        entry->fInfo = info;
85    }
86
87    /**
88     * Abandons all GPU resources, assumes 3D API state is unknown. Call this
89     * if you have lost the associated GPU context, and thus internal texture,
90     * buffer, etc. references/IDs are now invalid. Should be called even when
91     * GrContext is no longer going to be used for two reasons:
92     *  1) ~GrContext will not try to free the objects in the 3D API.
93     *  2) If you've created GrResources that outlive the GrContext they will
94     *     be marked as invalid (GrResource::isValid()) and won't attempt to
95     *     free their underlying resource in the 3D API.
96     * Content drawn since the last GrContext::flush() may be lost.
97     */
98    void contextLost();
99
100    /**
101     * Similar to contextLost, but makes no attempt to reset state.
102     * Use this method when GrContext destruction is pending, but
103     * the graphics context is destroyed first.
104     */
105    void contextDestroyed();
106
107    /**
108     * Frees GPU created by the context. Can be called to reduce GPU memory
109     * pressure.
110     */
111    void freeGpuResources();
112
113    /**
114     * Returns the number of bytes of GPU memory hosted by the texture cache.
115     */
116    size_t getGpuTextureCacheBytes() const;
117
118    ///////////////////////////////////////////////////////////////////////////
119    // Textures
120
121    /**
122     * Creates a new entry, based on the specified key and texture and returns it. The caller owns a
123     * ref on the returned texture which must be balanced by a call to unref.
124     *
125     * @param params    The texture params used to draw a texture may help determine
126     *                  the cache entry used. (e.g. different versions may exist
127     *                  for different wrap modes on GPUs with limited NPOT
128     *                  texture support). NULL implies clamp wrap modes.
129     * @param desc      Description of the texture properties.
130     * @param cacheID Cache-specific properties (e.g., texture gen ID)
131     * @param srcData   Pointer to the pixel values.
132     * @param rowBytes  The number of bytes between rows of the texture. Zero
133     *                  implies tightly packed rows.
134     */
135    GrTexture* createTexture(const GrTextureParams* params,
136                             const GrTextureDesc& desc,
137                             const GrCacheID& cacheID,
138                             void* srcData, size_t rowBytes);
139
140    /**
141     * Search for an entry based on key and dimensions. If found, ref it and return it. The return
142     * value will be NULL if not found. The caller must balance with a call to unref.
143     *
144     *  @param desc     Description of the texture properties.
145     *  @param cacheID Cache-specific properties (e.g., texture gen ID)
146     *  @param params   The texture params used to draw a texture may help determine
147     *                  the cache entry used. (e.g. different versions may exist
148     *                  for different wrap modes on GPUs with limited NPOT
149     *                  texture support). NULL implies clamp wrap modes.
150     */
151    GrTexture* findAndRefTexture(const GrTextureDesc& desc,
152                                 const GrCacheID& cacheID,
153                                 const GrTextureParams* params);
154    /**
155     * Determines whether a texture is in the cache. If the texture is found it
156     * will not be locked or returned. This call does not affect the priority of
157     * the texture for deletion.
158     */
159    bool isTextureInCache(const GrTextureDesc& desc,
160                          const GrCacheID& cacheID,
161                          const GrTextureParams* params) const;
162
163    /**
164     * Enum that determines how closely a returned scratch texture must match
165     * a provided GrTextureDesc.
166     */
167    enum ScratchTexMatch {
168        /**
169         * Finds a texture that exactly matches the descriptor.
170         */
171        kExact_ScratchTexMatch,
172        /**
173         * Finds a texture that approximately matches the descriptor. Will be
174         * at least as large in width and height as desc specifies. If desc
175         * specifies that texture is a render target then result will be a
176         * render target. If desc specifies a render target and doesn't set the
177         * no stencil flag then result will have a stencil. Format and aa level
178         * will always match.
179         */
180        kApprox_ScratchTexMatch
181    };
182
183    /**
184     * Returns a texture matching the desc. It's contents are unknown. Subsequent
185     * requests with the same descriptor are not guaranteed to return the same
186     * texture. The same texture is guaranteed not be returned again until it is
187     * unlocked. Call must be balanced with an unlockTexture() call. The caller
188     * owns a ref on the returned texture and must balance with a call to unref.
189     *
190     * Textures created by createAndLockTexture() hide the complications of
191     * tiling non-power-of-two textures on APIs that don't support this (e.g.
192     * unextended GLES2). Tiling a NPOT texture created by lockScratchTexture on
193     * such an API will create gaps in the tiling pattern. This includes clamp
194     * mode. (This may be addressed in a future update.)
195     */
196    GrTexture* lockAndRefScratchTexture(const GrTextureDesc&, ScratchTexMatch match);
197
198    /**
199     *  When done with an entry, call unlockScratchTexture(entry) on it, which returns
200     *  it to the cache, where it may be purged. This does not unref the texture.
201     */
202    void unlockScratchTexture(GrTexture* texture);
203
204    /**
205     * This method should be called whenever a GrTexture is unreffed or
206     * switched from exclusive to non-exclusive. This
207     * gives the resource cache a chance to discard unneeded textures.
208     * Note: this entry point will be removed once totally ref-driven
209     * cache maintenance is implemented
210     */
211    void purgeCache();
212
213    /**
214     * Creates a texture that is outside the cache. Does not count against
215     * cache's budget.
216     */
217    GrTexture* createUncachedTexture(const GrTextureDesc& desc,
218                                     void* srcData,
219                                     size_t rowBytes);
220
221    /**
222     * Returns true if the specified use of an indexed texture is supported.
223     * Support may depend upon whether the texture params indicate that the
224     * texture will be tiled. Passing NULL for the texture params indicates
225     * clamp mode.
226     */
227    bool supportsIndex8PixelConfig(const GrTextureParams*,
228                                   int width,
229                                   int height) const;
230
231    /**
232     *  Return the current texture cache limits.
233     *
234     *  @param maxTextures If non-null, returns maximum number of textures that
235     *                     can be held in the cache.
236     *  @param maxTextureBytes If non-null, returns maximum number of bytes of
237     *                         texture memory that can be held in the cache.
238     */
239    void getTextureCacheLimits(int* maxTextures, size_t* maxTextureBytes) const;
240
241    /**
242     *  Specify the texture cache limits. If the current cache exceeds either
243     *  of these, it will be purged (LRU) to keep the cache within these limits.
244     *
245     *  @param maxTextures The maximum number of textures that can be held in
246     *                     the cache.
247     *  @param maxTextureBytes The maximum number of bytes of texture memory
248     *                         that can be held in the cache.
249     */
250    void setTextureCacheLimits(int maxTextures, size_t maxTextureBytes);
251
252    /**
253     *  Return the max width or height of a texture supported by the current GPU.
254     */
255    int getMaxTextureSize() const;
256
257    /**
258     *  Temporarily override the true max texture size. Note: an override
259     *  larger then the true max texture size will have no effect.
260     *  This entry point is mainly meant for testing texture size dependent
261     *  features and is only available if defined outside of Skia (see
262     *  bleed GM.
263     */
264    void setMaxTextureSizeOverride(int maxTextureSizeOverride);
265
266    ///////////////////////////////////////////////////////////////////////////
267    // Render targets
268
269    /**
270     * Sets the render target.
271     * @param target    the render target to set.
272     */
273    void setRenderTarget(GrRenderTarget* target) {
274        fRenderTarget.reset(SkSafeRef(target));
275    }
276
277    /**
278     * Gets the current render target.
279     * @return the currently bound render target.
280     */
281    const GrRenderTarget* getRenderTarget() const { return fRenderTarget.get(); }
282    GrRenderTarget* getRenderTarget() { return fRenderTarget.get(); }
283
284    GrAARectRenderer* getAARectRenderer() { return fAARectRenderer; }
285
286    /**
287     * Can the provided configuration act as a color render target?
288     */
289    bool isConfigRenderable(GrPixelConfig config) const;
290
291    /**
292     * Return the max width or height of a render target supported by the
293     * current GPU.
294     */
295    int getMaxRenderTargetSize() const;
296
297    /**
298     * Returns the max sample count for a render target. It will be 0 if MSAA
299     * is not supported.
300     */
301    int getMaxSampleCount() const;
302
303    ///////////////////////////////////////////////////////////////////////////
304    // Backend Surfaces
305
306    /**
307     * Wraps an existing texture with a GrTexture object.
308     *
309     * OpenGL: if the object is a texture Gr may change its GL texture params
310     *         when it is drawn.
311     *
312     * @param  desc     description of the object to create.
313     *
314     * @return GrTexture object or NULL on failure.
315     */
316    GrTexture* wrapBackendTexture(const GrBackendTextureDesc& desc);
317
318    /**
319     * Wraps an existing render target with a GrRenderTarget object. It is
320     * similar to wrapBackendTexture but can be used to draw into surfaces
321     * that are not also textures (e.g. FBO 0 in OpenGL, or an MSAA buffer that
322     * the client will resolve to a texture).
323     *
324     * @param  desc     description of the object to create.
325     *
326     * @return GrTexture object or NULL on failure.
327     */
328     GrRenderTarget* wrapBackendRenderTarget(const GrBackendRenderTargetDesc& desc);
329
330    ///////////////////////////////////////////////////////////////////////////
331    // Matrix state
332
333    /**
334     * Gets the current transformation matrix.
335     * @return the current matrix.
336     */
337    const SkMatrix& getMatrix() const { return fViewMatrix; }
338
339    /**
340     * Sets the transformation matrix.
341     * @param m the matrix to set.
342     */
343    void setMatrix(const SkMatrix& m) { fViewMatrix = m; }
344
345    /**
346     * Sets the current transformation matrix to identity.
347     */
348    void setIdentityMatrix() { fViewMatrix.reset(); }
349
350    /**
351     * Concats the current matrix. The passed matrix is applied before the
352     * current matrix.
353     * @param m the matrix to concat.
354     */
355    void concatMatrix(const SkMatrix& m) { fViewMatrix.preConcat(m); }
356
357
358    ///////////////////////////////////////////////////////////////////////////
359    // Clip state
360    /**
361     * Gets the current clip.
362     * @return the current clip.
363     */
364    const GrClipData* getClip() const { return fClip; }
365
366    /**
367     * Sets the clip.
368     * @param clipData  the clip to set.
369     */
370    void setClip(const GrClipData* clipData) { fClip = clipData; }
371
372    ///////////////////////////////////////////////////////////////////////////
373    // Draws
374
375    /**
376     * Clear the entire or rect of the render target, ignoring any clips.
377     * @param rect  the rect to clear or the whole thing if rect is NULL.
378     * @param color the color to clear to.
379     * @param target if non-NULL, the render target to clear otherwise clear
380     *               the current render target
381     */
382    void clear(const SkIRect* rect, GrColor color,
383               GrRenderTarget* target = NULL);
384
385    /**
386     *  Draw everywhere (respecting the clip) with the paint.
387     */
388    void drawPaint(const GrPaint& paint);
389
390    /**
391     *  Draw the rect using a paint.
392     *  @param paint        describes how to color pixels.
393     *  @param strokeWidth  If strokeWidth < 0, then the rect is filled, else
394     *                      the rect is mitered stroked based on strokeWidth. If
395     *                      strokeWidth == 0, then the stroke is always a single
396     *                      pixel thick.
397     *  @param matrix       Optional matrix applied to the rect. Applied before
398     *                      context's matrix or the paint's matrix.
399     *  The rects coords are used to access the paint (through texture matrix)
400     */
401    void drawRect(const GrPaint& paint,
402                  const SkRect&,
403                  SkScalar strokeWidth = -1,
404                  const SkMatrix* matrix = NULL);
405
406    /**
407     * Maps a rect of local coordinates onto the a rect of destination
408     * coordinates. Each rect can optionally be transformed. The localRect
409     * is stretched over the dstRect. The dstRect is transformed by the
410     * context's matrix. Additional optional matrices for both rects can be
411     * provided by parameters.
412     *
413     * @param paint         describes how to color pixels.
414     * @param dstRect       the destination rect to draw.
415     * @param localRect     rect of local coordinates to be mapped onto dstRect
416     * @param dstMatrix     Optional matrix to transform dstRect. Applied before context's matrix.
417     * @param localMatrix   Optional matrix to transform localRect.
418     */
419    void drawRectToRect(const GrPaint& paint,
420                        const SkRect& dstRect,
421                        const SkRect& localRect,
422                        const SkMatrix* dstMatrix = NULL,
423                        const SkMatrix* localMatrix = NULL);
424
425    /**
426     *  Draw a roundrect using a paint.
427     *
428     *  @param paint        describes how to color pixels.
429     *  @param rrect        the roundrect to draw
430     *  @param stroke       the stroke information (width, join, cap)
431     */
432    void drawRRect(const GrPaint& paint,
433                   const SkRRect& rrect,
434                   const SkStrokeRec& stroke);
435
436    /**
437     * Draws a path.
438     *
439     * @param paint         describes how to color pixels.
440     * @param path          the path to draw
441     * @param stroke        the stroke information (width, join, cap)
442     */
443    void drawPath(const GrPaint& paint, const SkPath& path, const SkStrokeRec& stroke);
444
445    /**
446     * Draws vertices with a paint.
447     *
448     * @param   paint           describes how to color pixels.
449     * @param   primitiveType   primitives type to draw.
450     * @param   vertexCount     number of vertices.
451     * @param   positions       array of vertex positions, required.
452     * @param   texCoords       optional array of texture coordinates used
453     *                          to access the paint.
454     * @param   colors          optional array of per-vertex colors, supercedes
455     *                          the paint's color field.
456     * @param   indices         optional array of indices. If NULL vertices
457     *                          are drawn non-indexed.
458     * @param   indexCount      if indices is non-null then this is the
459     *                          number of indices.
460     */
461    void drawVertices(const GrPaint& paint,
462                      GrPrimitiveType primitiveType,
463                      int vertexCount,
464                      const GrPoint positions[],
465                      const GrPoint texs[],
466                      const GrColor colors[],
467                      const uint16_t indices[],
468                      int indexCount);
469
470    /**
471     * Draws an oval.
472     *
473     * @param paint         describes how to color pixels.
474     * @param oval          the bounding rect of the oval.
475     * @param stroke        the stroke information (width, style)
476     */
477    void drawOval(const GrPaint& paint,
478                  const SkRect& oval,
479                  const SkStrokeRec& stroke);
480
481    ///////////////////////////////////////////////////////////////////////////
482    // Misc.
483
484    /**
485     * Flags that affect flush() behavior.
486     */
487    enum FlushBits {
488        /**
489         * A client may reach a point where it has partially rendered a frame
490         * through a GrContext that it knows the user will never see. This flag
491         * causes the flush to skip submission of deferred content to the 3D API
492         * during the flush.
493         */
494        kDiscard_FlushBit                    = 0x2,
495    };
496
497    /**
498     * Call to ensure all drawing to the context has been issued to the
499     * underlying 3D API.
500     * @param flagsBitfield     flags that control the flushing behavior. See
501     *                          FlushBits.
502     */
503    void flush(int flagsBitfield = 0);
504
505   /**
506    * These flags can be used with the read/write pixels functions below.
507    */
508    enum PixelOpsFlags {
509        /** The GrContext will not be flushed. This means that the read or write may occur before
510            previous draws have executed. */
511        kDontFlush_PixelOpsFlag = 0x1,
512        /** The src for write or dst read is unpremultiplied. This is only respected if both the
513            config src and dst configs are an RGBA/BGRA 8888 format. */
514        kUnpremul_PixelOpsFlag  = 0x2,
515    };
516
517    /**
518     * Reads a rectangle of pixels from a render target.
519     * @param target        the render target to read from. NULL means the current render target.
520     * @param left          left edge of the rectangle to read (inclusive)
521     * @param top           top edge of the rectangle to read (inclusive)
522     * @param width         width of rectangle to read in pixels.
523     * @param height        height of rectangle to read in pixels.
524     * @param config        the pixel config of the destination buffer
525     * @param buffer        memory to read the rectangle into.
526     * @param rowBytes      number of bytes bewtween consecutive rows. Zero means rows are tightly
527     *                      packed.
528     * @param pixelOpsFlags see PixelOpsFlags enum above.
529     *
530     * @return true if the read succeeded, false if not. The read can fail because of an unsupported
531     *         pixel config or because no render target is currently set and NULL was passed for
532     *         target.
533     */
534    bool readRenderTargetPixels(GrRenderTarget* target,
535                                int left, int top, int width, int height,
536                                GrPixelConfig config, void* buffer,
537                                size_t rowBytes = 0,
538                                uint32_t pixelOpsFlags = 0);
539
540    /**
541     * Copy the src pixels [buffer, row bytes, pixel config] into a render target at the specified
542     * rectangle.
543     * @param target        the render target to write into. NULL means the current render target.
544     * @param left          left edge of the rectangle to write (inclusive)
545     * @param top           top edge of the rectangle to write (inclusive)
546     * @param width         width of rectangle to write in pixels.
547     * @param height        height of rectangle to write in pixels.
548     * @param config        the pixel config of the source buffer
549     * @param buffer        memory to read the rectangle from.
550     * @param rowBytes      number of bytes between consecutive rows. Zero means rows are tightly
551     *                      packed.
552     * @param pixelOpsFlags see PixelOpsFlags enum above.
553     *
554     * @return true if the write succeeded, false if not. The write can fail because of an
555     *         unsupported combination of target and pixel configs.
556     */
557    bool writeRenderTargetPixels(GrRenderTarget* target,
558                                 int left, int top, int width, int height,
559                                 GrPixelConfig config, const void* buffer,
560                                 size_t rowBytes = 0,
561                                 uint32_t pixelOpsFlags = 0);
562
563    /**
564     * Reads a rectangle of pixels from a texture.
565     * @param texture       the texture to read from.
566     * @param left          left edge of the rectangle to read (inclusive)
567     * @param top           top edge of the rectangle to read (inclusive)
568     * @param width         width of rectangle to read in pixels.
569     * @param height        height of rectangle to read in pixels.
570     * @param config        the pixel config of the destination buffer
571     * @param buffer        memory to read the rectangle into.
572     * @param rowBytes      number of bytes between consecutive rows. Zero means rows are tightly
573     *                      packed.
574     * @param pixelOpsFlags see PixelOpsFlags enum above.
575     *
576     * @return true if the read succeeded, false if not. The read can fail because of an unsupported
577     *         pixel config.
578     */
579    bool readTexturePixels(GrTexture* texture,
580                           int left, int top, int width, int height,
581                           GrPixelConfig config, void* buffer,
582                           size_t rowBytes = 0,
583                           uint32_t pixelOpsFlags = 0);
584
585    /**
586     * Writes a rectangle of pixels to a texture.
587     * @param texture       the render target to read from.
588     * @param left          left edge of the rectangle to write (inclusive)
589     * @param top           top edge of the rectangle to write (inclusive)
590     * @param width         width of rectangle to write in pixels.
591     * @param height        height of rectangle to write in pixels.
592     * @param config        the pixel config of the source buffer
593     * @param buffer        memory to read pixels from
594     * @param rowBytes      number of bytes between consecutive rows. Zero
595     *                      means rows are tightly packed.
596     * @param pixelOpsFlags see PixelOpsFlags enum above.
597     * @return true if the write succeeded, false if not. The write can fail because of an
598     *         unsupported combination of texture and pixel configs.
599     */
600    bool writeTexturePixels(GrTexture* texture,
601                            int left, int top, int width, int height,
602                            GrPixelConfig config, const void* buffer,
603                            size_t rowBytes,
604                            uint32_t pixelOpsFlags = 0);
605
606
607    /**
608     * Copies a rectangle of texels from src to dst. The size of dst is the size of the rectangle
609     * copied and topLeft is the position of the rect in src. The rectangle is clipped to src's
610     * bounds.
611     * @param src           the texture to copy from.
612     * @param dst           the render target to copy to.
613     * @param topLeft       the point in src that will be copied to the top-left of dst. If NULL,
614     *                      (0, 0) will be used.
615     */
616    void copyTexture(GrTexture* src, GrRenderTarget* dst, const SkIPoint* topLeft = NULL);
617
618    /**
619     * Resolves a render target that has MSAA. The intermediate MSAA buffer is
620     * down-sampled to the associated GrTexture (accessible via
621     * GrRenderTarget::asTexture()). Any pending draws to the render target will
622     * be executed before the resolve.
623     *
624     * This is only necessary when a client wants to access the object directly
625     * using the backend API directly. GrContext will detect when it must
626     * perform a resolve to a GrTexture used as the source of a draw or before
627     * reading pixels back from a GrTexture or GrRenderTarget.
628     */
629    void resolveRenderTarget(GrRenderTarget* target);
630
631    ///////////////////////////////////////////////////////////////////////////
632    // Helpers
633
634    class AutoRenderTarget : public ::SkNoncopyable {
635    public:
636        AutoRenderTarget(GrContext* context, GrRenderTarget* target) {
637            fPrevTarget = context->getRenderTarget();
638            SkSafeRef(fPrevTarget);
639            context->setRenderTarget(target);
640            fContext = context;
641        }
642        AutoRenderTarget(GrContext* context) {
643            fPrevTarget = context->getRenderTarget();
644            SkSafeRef(fPrevTarget);
645            fContext = context;
646        }
647        ~AutoRenderTarget() {
648            if (NULL != fContext) {
649                fContext->setRenderTarget(fPrevTarget);
650            }
651            SkSafeUnref(fPrevTarget);
652        }
653    private:
654        GrContext*      fContext;
655        GrRenderTarget* fPrevTarget;
656    };
657
658    /**
659     * Save/restore the view-matrix in the context. It can optionally adjust a paint to account
660     * for a coordinate system change. Here is an example of how the paint param can be used:
661     *
662     * A GrPaint is setup with GrEffects. The stages will have access to the pre-matrix source
663     * geometry positions when the draw is executed. Later on a decision is made to transform the
664     * geometry to device space on the CPU. The effects now need to know that the space in which
665     * the geometry will be specified has changed.
666     *
667     * Note that when restore is called (or in the destructor) the context's matrix will be
668     * restored. However, the paint will not be restored. The caller must make a copy of the
669     * paint if necessary. Hint: use SkTCopyOnFirstWrite if the AutoMatrix is conditionally
670     * initialized.
671     */
672    class AutoMatrix : public ::SkNoncopyable {
673    public:
674        AutoMatrix() : fContext(NULL) {}
675
676        ~AutoMatrix() { this->restore(); }
677
678        /**
679         * Initializes by pre-concat'ing the context's current matrix with the preConcat param.
680         */
681        void setPreConcat(GrContext* context, const SkMatrix& preConcat, GrPaint* paint = NULL) {
682            SkASSERT(NULL != context);
683
684            this->restore();
685
686            fContext = context;
687            fMatrix = context->getMatrix();
688            this->preConcat(preConcat, paint);
689        }
690
691        /**
692         * Sets the context's matrix to identity. Returns false if the inverse matrix is required to
693         * update a paint but the matrix cannot be inverted.
694         */
695        bool setIdentity(GrContext* context, GrPaint* paint = NULL) {
696            SkASSERT(NULL != context);
697
698            this->restore();
699
700            if (NULL != paint) {
701                if (!paint->localCoordChangeInverse(context->getMatrix())) {
702                    return false;
703                }
704            }
705            fMatrix = context->getMatrix();
706            fContext = context;
707            context->setIdentityMatrix();
708            return true;
709        }
710
711        /**
712         * Replaces the context's matrix with a new matrix. Returns false if the inverse matrix is
713         * required to update a paint but the matrix cannot be inverted.
714         */
715        bool set(GrContext* context, const SkMatrix& newMatrix, GrPaint* paint = NULL) {
716            if (NULL != paint) {
717                if (!this->setIdentity(context, paint)) {
718                    return false;
719                }
720                this->preConcat(newMatrix, paint);
721            } else {
722                this->restore();
723                fContext = context;
724                fMatrix = context->getMatrix();
725                context->setMatrix(newMatrix);
726            }
727            return true;
728        }
729
730        /**
731         * If this has been initialized then the context's matrix will be further updated by
732         * pre-concat'ing the preConcat param. The matrix that will be restored remains unchanged.
733         * The paint is assumed to be relative to the context's matrix at the time this call is
734         * made, not the matrix at the time AutoMatrix was first initialized. In other words, this
735         * performs an incremental update of the paint.
736         */
737        void preConcat(const SkMatrix& preConcat, GrPaint* paint = NULL) {
738            if (NULL != paint) {
739                paint->localCoordChange(preConcat);
740            }
741            fContext->concatMatrix(preConcat);
742        }
743
744        /**
745         * Returns false if never initialized or the inverse matrix was required to update a paint
746         * but the matrix could not be inverted.
747         */
748        bool succeeded() const { return NULL != fContext; }
749
750        /**
751         * If this has been initialized then the context's original matrix is restored.
752         */
753        void restore() {
754            if (NULL != fContext) {
755                fContext->setMatrix(fMatrix);
756                fContext = NULL;
757            }
758        }
759
760    private:
761        GrContext*  fContext;
762        SkMatrix    fMatrix;
763    };
764
765    class AutoClip : public ::SkNoncopyable {
766    public:
767        // This enum exists to require a caller of the constructor to acknowledge that the clip will
768        // initially be wide open. It also could be extended if there are other desirable initial
769        // clip states.
770        enum InitialClip {
771            kWideOpen_InitialClip,
772        };
773
774        AutoClip(GrContext* context, InitialClip initialState)
775        : fContext(context) {
776            SkASSERT(kWideOpen_InitialClip == initialState);
777            fNewClipData.fClipStack = &fNewClipStack;
778
779            fOldClip = context->getClip();
780            context->setClip(&fNewClipData);
781        }
782
783        AutoClip(GrContext* context, const SkRect& newClipRect)
784        : fContext(context)
785        , fNewClipStack(newClipRect) {
786            fNewClipData.fClipStack = &fNewClipStack;
787
788            fOldClip = fContext->getClip();
789            fContext->setClip(&fNewClipData);
790        }
791
792        ~AutoClip() {
793            if (NULL != fContext) {
794                fContext->setClip(fOldClip);
795            }
796        }
797    private:
798        GrContext*        fContext;
799        const GrClipData* fOldClip;
800
801        SkClipStack       fNewClipStack;
802        GrClipData        fNewClipData;
803    };
804
805    class AutoWideOpenIdentityDraw {
806    public:
807        AutoWideOpenIdentityDraw(GrContext* ctx, GrRenderTarget* rt)
808            : fAutoClip(ctx, AutoClip::kWideOpen_InitialClip)
809            , fAutoRT(ctx, rt) {
810            fAutoMatrix.setIdentity(ctx);
811            // should never fail with no paint param.
812            SkASSERT(fAutoMatrix.succeeded());
813        }
814
815    private:
816        AutoClip fAutoClip;
817        AutoRenderTarget fAutoRT;
818        AutoMatrix fAutoMatrix;
819    };
820
821    ///////////////////////////////////////////////////////////////////////////
822    // Functions intended for internal use only.
823    GrGpu* getGpu() { return fGpu; }
824    const GrGpu* getGpu() const { return fGpu; }
825    GrFontCache* getFontCache() { return fFontCache; }
826    GrDrawTarget* getTextTarget();
827    const GrIndexBuffer* getQuadIndexBuffer() const;
828
829    // Called by tests that draw directly to the context via GrDrawTarget
830    void getTestTarget(GrTestTarget*);
831
832    /**
833     * Stencil buffers add themselves to the cache using addStencilBuffer. findStencilBuffer is
834     * called to check the cache for a SB that matches an RT's criteria.
835     */
836    void addStencilBuffer(GrStencilBuffer* sb);
837    GrStencilBuffer* findStencilBuffer(int width, int height, int sampleCnt);
838
839    GrPathRenderer* getPathRenderer(
840                    const SkPath& path,
841                    const SkStrokeRec& stroke,
842                    const GrDrawTarget* target,
843                    bool allowSW,
844                    GrPathRendererChain::DrawType drawType = GrPathRendererChain::kColor_DrawType,
845                    GrPathRendererChain::StencilSupport* stencilSupport = NULL);
846
847
848#if GR_CACHE_STATS
849    void printCacheStats() const;
850#endif
851
852private:
853    // Used to indicate whether a draw should be performed immediately or queued in fDrawBuffer.
854    enum BufferedDraw {
855        kYes_BufferedDraw,
856        kNo_BufferedDraw,
857    };
858    BufferedDraw fLastDrawWasBuffered;
859
860    GrGpu*                          fGpu;
861    SkMatrix                        fViewMatrix;
862    SkAutoTUnref<GrRenderTarget>    fRenderTarget;
863    const GrClipData*               fClip;  // TODO: make this ref counted
864    GrDrawState*                    fDrawState;
865
866    GrResourceCache*                fTextureCache;
867    GrFontCache*                    fFontCache;
868
869    GrPathRendererChain*            fPathRendererChain;
870    GrSoftwarePathRenderer*         fSoftwarePathRenderer;
871
872    GrVertexBufferAllocPool*        fDrawBufferVBAllocPool;
873    GrIndexBufferAllocPool*         fDrawBufferIBAllocPool;
874    GrInOrderDrawBuffer*            fDrawBuffer;
875
876    GrAARectRenderer*               fAARectRenderer;
877    GrOvalRenderer*                 fOvalRenderer;
878
879    bool                            fDidTestPMConversions;
880    int                             fPMToUPMConversion;
881    int                             fUPMToPMConversion;
882
883    struct CleanUpData {
884        PFCleanUpFunc fFunc;
885        void*         fInfo;
886    };
887
888    SkTDArray<CleanUpData>          fCleanUpData;
889
890    int                             fMaxTextureSizeOverride;
891
892    GrContext(); // init must be called after the constructor.
893    bool init(GrBackend, GrBackendContext);
894
895    void setupDrawBuffer();
896
897    class AutoRestoreEffects;
898    /// Sets the paint and returns the target to draw into. The paint can be NULL in which case the
899    /// draw state is left unmodified.
900    GrDrawTarget* prepareToDraw(const GrPaint*, BufferedDraw, AutoRestoreEffects*);
901
902    void internalDrawPath(GrDrawTarget* target, bool useAA, const SkPath& path,
903                          const SkStrokeRec& stroke);
904
905    GrTexture* createResizedTexture(const GrTextureDesc& desc,
906                                    const GrCacheID& cacheID,
907                                    void* srcData,
908                                    size_t rowBytes,
909                                    bool filter);
910
911    // Needed so GrTexture's returnToCache helper function can call
912    // addExistingTextureToCache
913    friend class GrTexture;
914
915    // Add an existing texture to the texture cache. This is intended solely
916    // for use with textures released from an GrAutoScratchTexture.
917    void addExistingTextureToCache(GrTexture* texture);
918
919    /**
920     * These functions create premul <-> unpremul effects if it is possible to generate a pair
921     * of effects that make a readToUPM->writeToPM->readToUPM cycle invariant. Otherwise, they
922     * return NULL.
923     */
924    const GrEffectRef* createPMToUPMEffect(GrTexture* texture,
925                                           bool swapRAndB,
926                                           const SkMatrix& matrix);
927    const GrEffectRef* createUPMToPMEffect(GrTexture* texture,
928                                           bool swapRAndB,
929                                           const SkMatrix& matrix);
930
931    /**
932     *  This callback allows the resource cache to callback into the GrContext
933     *  when the cache is still overbudget after a purge.
934     */
935    static bool OverbudgetCB(void* data);
936
937    typedef SkRefCnt INHERITED;
938};
939
940/**
941 * Gets and locks a scratch texture from a descriptor using either exact or approximate criteria.
942 * Unlocks texture in the destructor.
943 */
944class GrAutoScratchTexture : public ::SkNoncopyable {
945public:
946    GrAutoScratchTexture()
947        : fContext(NULL)
948        , fTexture(NULL) {
949    }
950
951    GrAutoScratchTexture(GrContext* context,
952                         const GrTextureDesc& desc,
953                         GrContext::ScratchTexMatch match = GrContext::kApprox_ScratchTexMatch)
954      : fContext(NULL)
955      , fTexture(NULL) {
956      this->set(context, desc, match);
957    }
958
959    ~GrAutoScratchTexture() {
960        this->reset();
961    }
962
963    void reset() {
964        if (NULL != fContext && NULL != fTexture) {
965            fContext->unlockScratchTexture(fTexture);
966            fTexture->unref();
967            fTexture = NULL;
968        }
969    }
970
971    /*
972     * When detaching a texture we do not unlock it in the texture cache but
973     * we do set the returnToCache flag. In this way the texture remains
974     * "locked" in the texture cache until it is freed and recycled in
975     * GrTexture::internal_dispose. In reality, the texture has been removed
976     * from the cache (because this is in AutoScratchTexture) and by not
977     * calling unlockScratchTexture we simply don't re-add it. It will be
978     * reattached in GrTexture::internal_dispose.
979     *
980     * Note that the caller is assumed to accept and manage the ref to the
981     * returned texture.
982     */
983    GrTexture* detach() {
984        if (NULL == fTexture) {
985            return NULL;
986        }
987        GrTexture* texture = fTexture;
988        fTexture = NULL;
989
990        // This GrAutoScratchTexture has a ref from lockAndRefScratchTexture, which we give up now.
991        // The cache also has a ref which we are lending to the caller of detach(). When the caller
992        // lets go of the ref and the ref count goes to 0 internal_dispose will see this flag is
993        // set and re-ref the texture, thereby restoring the cache's ref.
994        SkASSERT(texture->getRefCnt() > 1);
995        texture->setFlag((GrTextureFlags) GrTexture::kReturnToCache_FlagBit);
996        texture->unref();
997        SkASSERT(NULL != texture->getCacheEntry());
998
999        return texture;
1000    }
1001
1002    GrTexture* set(GrContext* context,
1003                   const GrTextureDesc& desc,
1004                   GrContext::ScratchTexMatch match = GrContext::kApprox_ScratchTexMatch) {
1005        this->reset();
1006
1007        fContext = context;
1008        if (NULL != fContext) {
1009            fTexture = fContext->lockAndRefScratchTexture(desc, match);
1010            if (NULL == fTexture) {
1011                fContext = NULL;
1012            }
1013            return fTexture;
1014        } else {
1015            return NULL;
1016        }
1017    }
1018
1019    GrTexture* texture() { return fTexture; }
1020
1021private:
1022    GrContext*                    fContext;
1023    GrTexture*                    fTexture;
1024};
1025
1026#endif
1027