GrContext.h revision d0423587ac56ae84d3f1eb796d5c1e2dfba9646e
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 "GrRenderTarget.h"
16#include "GrTexture.h"
17#include "SkMatrix.h"
18#include "SkPathEffect.h"
19#include "SkTypes.h"
20
21class GrAARectRenderer;
22class GrDrawTarget;
23class GrFontCache;
24class GrFragmentProcessor;
25class GrGpu;
26class GrGpuTraceMarker;
27class GrIndexBuffer;
28class GrIndexBufferAllocPool;
29class GrInOrderDrawBuffer;
30class GrLayerCache;
31class GrOvalRenderer;
32class GrPath;
33class GrPathRenderer;
34class GrPipelineBuilder;
35class GrResourceEntry;
36class GrResourceCache2;
37class GrTestTarget;
38class GrTextContext;
39class GrTextureParams;
40class GrVertexBuffer;
41class GrVertexBufferAllocPool;
42class GrStrokeInfo;
43class GrSoftwarePathRenderer;
44class SkStrokeRec;
45
46class SK_API GrContext : public SkRefCnt {
47public:
48    SK_DECLARE_INST_COUNT(GrContext)
49
50    struct Options {
51        Options() : fDrawPathToCompressedTexture(false) { }
52
53        // EXPERIMENTAL
54        // May be removed in the future, or may become standard depending
55        // on the outcomes of a variety of internal tests.
56        bool fDrawPathToCompressedTexture;
57    };
58
59    /**
60     * Creates a GrContext for a backend context.
61     */
62    static GrContext* Create(GrBackend, GrBackendContext, const Options* opts = NULL);
63
64    /**
65     * Only defined in test apps.
66     */
67    static GrContext* CreateMockContext();
68
69    virtual ~GrContext();
70
71    /**
72     * The GrContext normally assumes that no outsider is setting state
73     * within the underlying 3D API's context/device/whatever. This call informs
74     * the context that the state was modified and it should resend. Shouldn't
75     * be called frequently for good performance.
76     * The flag bits, state, is dpendent on which backend is used by the
77     * context, either GL or D3D (possible in future).
78     */
79    void resetContext(uint32_t state = kAll_GrBackendState);
80
81    /**
82     * Callback function to allow classes to cleanup on GrContext destruction.
83     * The 'info' field is filled in with the 'info' passed to addCleanUp.
84     */
85    typedef void (*PFCleanUpFunc)(const GrContext* context, void* info);
86
87    /**
88     * Add a function to be called from within GrContext's destructor.
89     * This gives classes a chance to free resources held on a per context basis.
90     * The 'info' parameter will be stored and passed to the callback function.
91     */
92    void addCleanUp(PFCleanUpFunc cleanUp, void* info) {
93        CleanUpData* entry = fCleanUpData.push();
94
95        entry->fFunc = cleanUp;
96        entry->fInfo = info;
97    }
98
99    /**
100     * Abandons all GPU resources and assumes the underlying backend 3D API
101     * context is not longer usable. Call this if you have lost the associated
102     * GPU context, and thus internal texture, buffer, etc. references/IDs are
103     * now invalid. Should be called even when GrContext is no longer going to
104     * be used for two reasons:
105     *  1) ~GrContext will not try to free the objects in the 3D API.
106     *  2) Any GrGpuResources created by this GrContext that outlive
107     *     will be marked as invalid (GrGpuResource::wasDestroyed()) and
108     *     when they're destroyed no 3D API calls will be made.
109     * Content drawn since the last GrContext::flush() may be lost. After this
110     * function is called the only valid action on the GrContext or
111     * GrGpuResources it created is to destroy them.
112     */
113    void abandonContext();
114    void contextDestroyed() { this->abandonContext(); }  //  legacy alias
115
116    ///////////////////////////////////////////////////////////////////////////
117    // Resource Cache
118
119    /**
120     *  Return the current GPU resource cache limits.
121     *
122     *  @param maxResources If non-null, returns maximum number of resources that
123     *                      can be held in the cache.
124     *  @param maxResourceBytes If non-null, returns maximum number of bytes of
125     *                          video memory that can be held in the cache.
126     */
127    void getResourceCacheLimits(int* maxResources, size_t* maxResourceBytes) const;
128
129    /**
130     *  Gets the current GPU resource cache usage.
131     *
132     *  @param resourceCount If non-null, returns the number of resources that are held in the
133     *                       cache.
134     *  @param maxResourceBytes If non-null, returns the total number of bytes of video memory held
135     *                          in the cache.
136     */
137    void getResourceCacheUsage(int* resourceCount, size_t* resourceBytes) const;
138
139    /**
140     *  Specify the GPU resource cache limits. If the current cache exceeds either
141     *  of these, it will be purged (LRU) to keep the cache within these limits.
142     *
143     *  @param maxResources The maximum number of resources that can be held in
144     *                      the cache.
145     *  @param maxResourceBytes The maximum number of bytes of video memory
146     *                          that can be held in the cache.
147     */
148    void setResourceCacheLimits(int maxResources, size_t maxResourceBytes);
149
150    /**
151     * Frees GPU created by the context. Can be called to reduce GPU memory
152     * pressure.
153     */
154    void freeGpuResources();
155
156    /**
157     * This method should be called whenever a GrResource is unreffed or
158     * switched from exclusive to non-exclusive. This
159     * gives the resource cache a chance to discard unneeded resources.
160     * Note: this entry point will be removed once totally ref-driven
161     * cache maintenance is implemented.
162     */
163    void purgeCache();
164
165    /**
166     * Purge all the unlocked resources from the cache.
167     * This entry point is mainly meant for timing texture uploads
168     * and is not defined in normal builds of Skia.
169     */
170    void purgeAllUnlockedResources();
171
172    /** Sets a content key on the resource. The resource must not already have a content key and
173     *  the key must not already be in use for this to succeed.
174     */
175    bool addResourceToCache(const GrContentKey&, GrGpuResource*);
176
177    /**
178     * Finds a resource in the cache, based on the specified key. This is intended for use in
179     * conjunction with addResourceToCache(). The return value will be NULL if not found. The
180     * caller must balance with a call to unref().
181     */
182    GrGpuResource* findAndRefCachedResource(const GrContentKey&);
183
184    /** Helper for casting resource to a texture. Caller must be sure that the resource cached
185        with the key is either NULL or a texture and not another resource type. */
186    GrTexture* findAndRefCachedTexture(const GrContentKey& key) {
187        GrGpuResource* resource = this->findAndRefCachedResource(key);
188        if (resource) {
189            GrTexture* texture = static_cast<GrSurface*>(resource)->asTexture();
190            SkASSERT(texture);
191            return texture;
192        }
193        return NULL;
194    }
195
196    /**
197     * Determines whether a resource is in the cache. If the resource is found it
198     * will not be locked or returned. This call does not affect the priority of
199     * the resource for deletion.
200     */
201    bool isResourceInCache(const GrContentKey& key) const;
202
203    /**
204     * Creates a new text rendering context that is optimal for the
205     * render target and the context. Caller assumes the ownership
206     * of the returned object. The returned object must be deleted
207     * before the context is destroyed.
208     */
209    GrTextContext* createTextContext(GrRenderTarget*,
210                                     const SkDeviceProperties&,
211                                     bool enableDistanceFieldFonts);
212
213    ///////////////////////////////////////////////////////////////////////////
214    // Textures
215
216    /**
217     * Creates a new texture in the resource cache and returns it. The caller owns a
218     * ref on the returned texture which must be balanced by a call to unref.
219     *
220     * @param desc      Description of the texture properties.
221     * @param budgeted  Does the texture count against the resource cache budget?
222     * @param srcData   Pointer to the pixel values (optional).
223     * @param rowBytes  The number of bytes between rows of the texture. Zero
224     *                  implies tightly packed rows. For compressed pixel configs, this
225     *                  field is ignored.
226     */
227    GrTexture* createTexture(const GrSurfaceDesc& desc, bool budgeted, const void* srcData,
228                             size_t rowBytes);
229
230    GrTexture* createTexture(const GrSurfaceDesc& desc, bool budgeted) {
231        return this->createTexture(desc, budgeted, NULL, 0);
232    }
233
234    /**
235     * DEPRECATED: use createTexture().
236     */
237    GrTexture* createUncachedTexture(const GrSurfaceDesc& desc, void* srcData, size_t rowBytes) {
238        return this->createTexture(desc, false, srcData, rowBytes);
239    }
240
241    /**
242     * Enum that determines how closely a returned scratch texture must match
243     * a provided GrSurfaceDesc. TODO: Remove this. createTexture() should be used
244     * for exact match and refScratchTexture() should be replaced with createApproxTexture().
245     */
246    enum ScratchTexMatch {
247        /**
248         * Finds a texture that exactly matches the descriptor.
249         */
250        kExact_ScratchTexMatch,
251        /**
252         * Finds a texture that approximately matches the descriptor. Will be
253         * at least as large in width and height as desc specifies. If desc
254         * specifies that texture is a render target then result will be a
255         * render target. If desc specifies a render target and doesn't set the
256         * no stencil flag then result will have a stencil. Format and aa level
257         * will always match.
258         */
259        kApprox_ScratchTexMatch
260    };
261
262    /**
263     * Returns a texture matching the desc. It's contents are unknown. The caller
264     * owns a ref on the returned texture and must balance with a call to unref.
265     * It is guaranteed that the same texture will not be returned in subsequent
266     * calls until all refs to the texture are dropped.
267     *
268     * Textures created by createTexture() hide the complications of
269     * tiling non-power-of-two textures on APIs that don't support this (e.g.
270     * unextended GLES2). NPOT scratch textures are not tilable on such APIs.
271     *
272     * internalFlag is a temporary workaround until changes in the internal
273     * architecture are complete. Use the default value.
274     *
275     * TODO: Once internal flag can be removed, this should be replaced with
276     * createApproxTexture() and exact textures should be created with
277     * createTexture().
278     */
279    GrTexture* refScratchTexture(const GrSurfaceDesc&, ScratchTexMatch match,
280                                 bool internalFlag = false);
281
282    /**
283     * Can the provided configuration act as a texture?
284     */
285    bool isConfigTexturable(GrPixelConfig) const;
286
287    /**
288     * Can non-power-of-two textures be used with tile modes other than clamp?
289     */
290    bool npotTextureTileSupport() const;
291
292    /**
293     *  Return the max width or height of a texture supported by the current GPU.
294     */
295    int getMaxTextureSize() const;
296
297    /**
298     *  Temporarily override the true max texture size. Note: an override
299     *  larger then the true max texture size will have no effect.
300     *  This entry point is mainly meant for testing texture size dependent
301     *  features and is only available if defined outside of Skia (see
302     *  bleed GM.
303     */
304    void setMaxTextureSizeOverride(int maxTextureSizeOverride);
305
306    ///////////////////////////////////////////////////////////////////////////
307    // Render targets
308
309    /**
310     * Sets the render target.
311     * @param target    the render target to set.
312     */
313    void setRenderTarget(GrRenderTarget* target) {
314        fRenderTarget.reset(SkSafeRef(target));
315    }
316
317    /**
318     * Gets the current render target.
319     * @return the currently bound render target.
320     */
321    const GrRenderTarget* getRenderTarget() const { return fRenderTarget.get(); }
322    GrRenderTarget* getRenderTarget() { return fRenderTarget.get(); }
323
324    /**
325     * Can the provided configuration act as a color render target?
326     */
327    bool isConfigRenderable(GrPixelConfig config, bool withMSAA) const;
328
329    /**
330     * Return the max width or height of a render target supported by the
331     * current GPU.
332     */
333    int getMaxRenderTargetSize() const;
334
335    /**
336     * Returns the max sample count for a render target. It will be 0 if MSAA
337     * is not supported.
338     */
339    int getMaxSampleCount() const;
340
341    /**
342     * Returns the recommended sample count for a render target when using this
343     * context.
344     *
345     * @param  config the configuration of the render target.
346     * @param  dpi the display density in dots per inch.
347     *
348     * @return sample count that should be perform well and have good enough
349     *         rendering quality for the display. Alternatively returns 0 if
350     *         MSAA is not supported or recommended to be used by default.
351     */
352    int getRecommendedSampleCount(GrPixelConfig config, SkScalar dpi) const;
353
354    ///////////////////////////////////////////////////////////////////////////
355    // Backend Surfaces
356
357    /**
358     * Wraps an existing texture with a GrTexture object.
359     *
360     * OpenGL: if the object is a texture Gr may change its GL texture params
361     *         when it is drawn.
362     *
363     * @param  desc     description of the object to create.
364     *
365     * @return GrTexture object or NULL on failure.
366     */
367    GrTexture* wrapBackendTexture(const GrBackendTextureDesc& desc);
368
369    /**
370     * Wraps an existing render target with a GrRenderTarget object. It is
371     * similar to wrapBackendTexture but can be used to draw into surfaces
372     * that are not also textures (e.g. FBO 0 in OpenGL, or an MSAA buffer that
373     * the client will resolve to a texture).
374     *
375     * @param  desc     description of the object to create.
376     *
377     * @return GrTexture object or NULL on failure.
378     */
379     GrRenderTarget* wrapBackendRenderTarget(const GrBackendRenderTargetDesc& desc);
380
381    ///////////////////////////////////////////////////////////////////////////
382    // Clip state
383    /**
384     * Gets the current clip.
385     * @return the current clip.
386     */
387    const GrClipData* getClip() const { return fClip; }
388
389    /**
390     * Sets the clip.
391     * @param clipData  the clip to set.
392     */
393    void setClip(const GrClipData* clipData) { fClip = clipData; }
394
395    ///////////////////////////////////////////////////////////////////////////
396    // Draws
397
398    /**
399     * Clear the entire or rect of the render target, ignoring any clips.
400     * @param rect  the rect to clear or the whole thing if rect is NULL.
401     * @param color the color to clear to.
402     * @param canIgnoreRect allows partial clears to be converted to whole
403     *                      clears on platforms for which that is cheap
404     * @param target The render target to clear.
405     */
406    void clear(const SkIRect* rect, GrColor color, bool canIgnoreRect, GrRenderTarget* target);
407
408    /**
409     *  Draw everywhere (respecting the clip) with the paint.
410     */
411    void drawPaint(const GrPaint&, const SkMatrix& viewMatrix);
412
413    /**
414     *  Draw the rect using a paint.
415     *  @param paint        describes how to color pixels.
416     *  @param viewMatrix   transformation matrix
417     *  @param strokeInfo   the stroke information (width, join, cap), and.
418     *                      the dash information (intervals, count, phase).
419     *                      If strokeInfo == NULL, then the rect is filled.
420     *                      Otherwise, if stroke width == 0, then the stroke
421     *                      is always a single pixel thick, else the rect is
422     *                      mitered/beveled stroked based on stroke width.
423     *  The rects coords are used to access the paint (through texture matrix)
424     */
425    void drawRect(const GrPaint& paint,
426                  const SkMatrix& viewMatrix,
427                  const SkRect&,
428                  const GrStrokeInfo* strokeInfo = NULL);
429
430    /**
431     * Maps a rectangle of shader coordinates to a rectangle and draws that rectangle
432     *
433     * @param paint         describes how to color pixels.
434     * @param viewMatrix    transformation matrix which applies to rectToDraw
435     * @param rectToDraw    the rectangle to draw
436     * @param localRect     the rectangle of shader coordinates applied to rectToDraw
437     * @param localMatrix   an optional matrix to transform the shader coordinates before applying
438     *                      to rectToDraw
439     */
440    void drawNonAARectToRect(const GrPaint& paint,
441                             const SkMatrix& viewMatrix,
442                             const SkRect& rectToDraw,
443                             const SkRect& localRect,
444                             const SkMatrix* localMatrix = NULL);
445
446    /**
447     * Draws a non-AA rect with paint and a localMatrix
448     */
449    void drawNonAARectWithLocalMatrix(const GrPaint& paint,
450                                      const SkMatrix& viewMatrix,
451                                      const SkRect& rect,
452                                      const SkMatrix& localMatrix) {
453        this->drawNonAARectToRect(paint, viewMatrix, rect, rect, &localMatrix);
454    }
455
456    /**
457     *  Draw a roundrect using a paint.
458     *
459     *  @param paint        describes how to color pixels.
460     *  @param viewMatrix   transformation matrix
461     *  @param rrect        the roundrect to draw
462     *  @param strokeInfo   the stroke information (width, join, cap) and
463     *                      the dash information (intervals, count, phase).
464     */
465    void drawRRect(const GrPaint&, const SkMatrix& viewMatrix, const SkRRect& rrect,
466                   const GrStrokeInfo&);
467
468    /**
469     *  Shortcut for drawing an SkPath consisting of nested rrects using a paint.
470     *  Does not support stroking. The result is undefined if outer does not contain
471     *  inner.
472     *
473     *  @param paint        describes how to color pixels.
474     *  @param viewMatrix   transformation matrix
475     *  @param outer        the outer roundrect
476     *  @param inner        the inner roundrect
477     */
478    void drawDRRect(const GrPaint&, const SkMatrix& viewMatrix, const SkRRect& outer,
479                    const SkRRect& inner);
480
481
482    /**
483     * Draws a path.
484     *
485     * @param paint         describes how to color pixels.
486     * @param viewMatrix    transformation matrix
487     * @param path          the path to draw
488     * @param strokeInfo    the stroke information (width, join, cap) and
489     *                      the dash information (intervals, count, phase).
490     */
491    void drawPath(const GrPaint&, const SkMatrix& viewMatrix, const SkPath&, const GrStrokeInfo&);
492
493    /**
494     * Draws vertices with a paint.
495     *
496     * @param   paint           describes how to color pixels.
497     * @param   viewMatrix      transformation matrix
498     * @param   primitiveType   primitives type to draw.
499     * @param   vertexCount     number of vertices.
500     * @param   positions       array of vertex positions, required.
501     * @param   texCoords       optional array of texture coordinates used
502     *                          to access the paint.
503     * @param   colors          optional array of per-vertex colors, supercedes
504     *                          the paint's color field.
505     * @param   indices         optional array of indices. If NULL vertices
506     *                          are drawn non-indexed.
507     * @param   indexCount      if indices is non-null then this is the
508     *                          number of indices.
509     */
510    void drawVertices(const GrPaint& paint,
511                      const SkMatrix& viewMatrix,
512                      GrPrimitiveType primitiveType,
513                      int vertexCount,
514                      const SkPoint positions[],
515                      const SkPoint texs[],
516                      const GrColor colors[],
517                      const uint16_t indices[],
518                      int indexCount);
519
520    /**
521     * Draws an oval.
522     *
523     * @param paint         describes how to color pixels.
524     * @param viewMatrix    transformation matrix
525     * @param oval          the bounding rect of the oval.
526     * @param strokeInfo    the stroke information (width, join, cap) and
527     *                      the dash information (intervals, count, phase).
528     */
529    void drawOval(const GrPaint& paint,
530                  const SkMatrix& viewMatrix,
531                  const SkRect& oval,
532                  const GrStrokeInfo& strokeInfo);
533
534    ///////////////////////////////////////////////////////////////////////////
535    // Misc.
536
537    /**
538     * Flags that affect flush() behavior.
539     */
540    enum FlushBits {
541        /**
542         * A client may reach a point where it has partially rendered a frame
543         * through a GrContext that it knows the user will never see. This flag
544         * causes the flush to skip submission of deferred content to the 3D API
545         * during the flush.
546         */
547        kDiscard_FlushBit                    = 0x2,
548    };
549
550    /**
551     * Call to ensure all drawing to the context has been issued to the
552     * underlying 3D API.
553     * @param flagsBitfield     flags that control the flushing behavior. See
554     *                          FlushBits.
555     */
556    void flush(int flagsBitfield = 0);
557
558   /**
559    * These flags can be used with the read/write pixels functions below.
560    */
561    enum PixelOpsFlags {
562        /** The GrContext will not be flushed before the surface read or write. This means that
563            the read or write may occur before previous draws have executed. */
564        kDontFlush_PixelOpsFlag = 0x1,
565        /** Any surface writes should be flushed to the backend 3D API after the surface operation
566            is complete */
567        kFlushWrites_PixelOp = 0x2,
568        /** The src for write or dst read is unpremultiplied. This is only respected if both the
569            config src and dst configs are an RGBA/BGRA 8888 format. */
570        kUnpremul_PixelOpsFlag  = 0x4,
571    };
572
573    /**
574     * Reads a rectangle of pixels from a render target.
575     * @param target        the render target to read from.
576     * @param left          left edge of the rectangle to read (inclusive)
577     * @param top           top edge of the rectangle to read (inclusive)
578     * @param width         width of rectangle to read in pixels.
579     * @param height        height of rectangle to read in pixels.
580     * @param config        the pixel config of the destination buffer
581     * @param buffer        memory to read the rectangle into.
582     * @param rowBytes      number of bytes bewtween consecutive rows. Zero means rows are tightly
583     *                      packed.
584     * @param pixelOpsFlags see PixelOpsFlags enum above.
585     *
586     * @return true if the read succeeded, false if not. The read can fail because of an unsupported
587     *         pixel config or because no render target is currently set and NULL was passed for
588     *         target.
589     */
590    bool readRenderTargetPixels(GrRenderTarget* target,
591                                int left, int top, int width, int height,
592                                GrPixelConfig config, void* buffer,
593                                size_t rowBytes = 0,
594                                uint32_t pixelOpsFlags = 0);
595
596    /**
597     * Writes a rectangle of pixels to a surface.
598     * @param surface       the surface to write to.
599     * @param left          left edge of the rectangle to write (inclusive)
600     * @param top           top edge of the rectangle to write (inclusive)
601     * @param width         width of rectangle to write in pixels.
602     * @param height        height of rectangle to write in pixels.
603     * @param config        the pixel config of the source buffer
604     * @param buffer        memory to read pixels from
605     * @param rowBytes      number of bytes between consecutive rows. Zero
606     *                      means rows are tightly packed.
607     * @param pixelOpsFlags see PixelOpsFlags enum above.
608     * @return true if the write succeeded, false if not. The write can fail because of an
609     *         unsupported combination of surface and src configs.
610     */
611    bool writeSurfacePixels(GrSurface* surface,
612                            int left, int top, int width, int height,
613                            GrPixelConfig config, const void* buffer,
614                            size_t rowBytes,
615                            uint32_t pixelOpsFlags = 0);
616
617    /**
618     * Copies a rectangle of texels from src to dst.
619     * bounds.
620     * @param dst           the surface to copy to.
621     * @param src           the surface to copy from.
622     * @param srcRect       the rectangle of the src that should be copied.
623     * @param dstPoint      the translation applied when writing the srcRect's pixels to the dst.
624     * @param pixelOpsFlags see PixelOpsFlags enum above. (kUnpremul_PixelOpsFlag is not allowed).
625     */
626    void copySurface(GrSurface* dst,
627                     GrSurface* src,
628                     const SkIRect& srcRect,
629                     const SkIPoint& dstPoint,
630                     uint32_t pixelOpsFlags = 0);
631
632    /** Helper that copies the whole surface but fails when the two surfaces are not identically
633        sized. */
634    bool copySurface(GrSurface* dst, GrSurface* src) {
635        if (NULL == dst || NULL == src || dst->width() != src->width() ||
636            dst->height() != src->height()) {
637            return false;
638        }
639        this->copySurface(dst, src, SkIRect::MakeWH(dst->width(), dst->height()),
640                          SkIPoint::Make(0,0));
641        return true;
642    }
643
644    /**
645     * After this returns any pending writes to the surface will have been issued to the backend 3D API.
646     */
647    void flushSurfaceWrites(GrSurface* surface);
648
649    /**
650     * Equivalent to flushSurfaceWrites but also performs MSAA resolve if necessary. This call is
651     * used to make the surface contents available to be read in the backend 3D API, usually for a
652     * compositing step external to Skia.
653     *
654     * It is not necessary to call this before reading the render target via Skia/GrContext.
655     * GrContext will detect when it must perform a resolve before reading pixels back from the
656     * surface or using it as a texture.
657     */
658    void prepareSurfaceForExternalRead(GrSurface*);
659
660    /**
661     * Provides a perfomance hint that the render target's contents are allowed
662     * to become undefined.
663     */
664    void discardRenderTarget(GrRenderTarget*);
665
666#ifdef SK_DEVELOPER
667    void dumpFontCache() const;
668#endif
669
670    ///////////////////////////////////////////////////////////////////////////
671    // Helpers
672
673    class AutoRenderTarget : public ::SkNoncopyable {
674    public:
675        AutoRenderTarget(GrContext* context, GrRenderTarget* target) {
676            fPrevTarget = context->getRenderTarget();
677            SkSafeRef(fPrevTarget);
678            context->setRenderTarget(target);
679            fContext = context;
680        }
681        AutoRenderTarget(GrContext* context) {
682            fPrevTarget = context->getRenderTarget();
683            SkSafeRef(fPrevTarget);
684            fContext = context;
685        }
686        ~AutoRenderTarget() {
687            if (fContext) {
688                fContext->setRenderTarget(fPrevTarget);
689            }
690            SkSafeUnref(fPrevTarget);
691        }
692    private:
693        GrContext*      fContext;
694        GrRenderTarget* fPrevTarget;
695    };
696
697    class AutoClip : public ::SkNoncopyable {
698    public:
699        // This enum exists to require a caller of the constructor to acknowledge that the clip will
700        // initially be wide open. It also could be extended if there are other desirable initial
701        // clip states.
702        enum InitialClip {
703            kWideOpen_InitialClip,
704        };
705
706        AutoClip(GrContext* context, InitialClip SkDEBUGCODE(initialState))
707        : fContext(context) {
708            SkASSERT(kWideOpen_InitialClip == initialState);
709            fNewClipData.fClipStack.reset(SkRef(&fNewClipStack));
710
711            fOldClip = context->getClip();
712            context->setClip(&fNewClipData);
713        }
714
715        AutoClip(GrContext* context, const SkRect& newClipRect)
716        : fContext(context)
717        , fNewClipStack(newClipRect) {
718            fNewClipData.fClipStack.reset(SkRef(&fNewClipStack));
719
720            fOldClip = fContext->getClip();
721            fContext->setClip(&fNewClipData);
722        }
723
724        ~AutoClip() {
725            if (fContext) {
726                fContext->setClip(fOldClip);
727            }
728        }
729    private:
730        GrContext*        fContext;
731        const GrClipData* fOldClip;
732
733        SkClipStack       fNewClipStack;
734        GrClipData        fNewClipData;
735    };
736
737    class AutoWideOpenIdentityDraw {
738    public:
739        AutoWideOpenIdentityDraw(GrContext* ctx, GrRenderTarget* rt)
740            : fAutoClip(ctx, AutoClip::kWideOpen_InitialClip)
741            , fAutoRT(ctx, rt) {
742        }
743
744    private:
745        AutoClip fAutoClip;
746        AutoRenderTarget fAutoRT;
747    };
748
749    ///////////////////////////////////////////////////////////////////////////
750    // Functions intended for internal use only.
751    GrGpu* getGpu() { return fGpu; }
752    const GrGpu* getGpu() const { return fGpu; }
753    GrFontCache* getFontCache() { return fFontCache; }
754    GrLayerCache* getLayerCache() { return fLayerCache.get(); }
755    GrDrawTarget* getTextTarget();
756    const GrIndexBuffer* getQuadIndexBuffer() const;
757    GrAARectRenderer* getAARectRenderer() { return fAARectRenderer; }
758    GrResourceCache2* getResourceCache2() { return fResourceCache2; }
759
760    // Called by tests that draw directly to the context via GrDrawTarget
761    void getTestTarget(GrTestTarget*);
762
763    void addGpuTraceMarker(const GrGpuTraceMarker* marker);
764    void removeGpuTraceMarker(const GrGpuTraceMarker* marker);
765
766    GrPathRenderer* getPathRenderer(
767                    const GrDrawTarget* target,
768                    const GrPipelineBuilder*,
769                    const SkMatrix& viewMatrix,
770                    const SkPath& path,
771                    const SkStrokeRec& stroke,
772                    bool allowSW,
773                    GrPathRendererChain::DrawType drawType = GrPathRendererChain::kColor_DrawType,
774                    GrPathRendererChain::StencilSupport* stencilSupport = NULL);
775
776    /**
777     *  This returns a copy of the the GrContext::Options that was passed to the
778     *  constructor of this class.
779     */
780    const Options& getOptions() const { return fOptions; }
781
782    /** Prints cache stats to the string if GR_CACHE_STATS == 1. */
783    void dumpCacheStats(SkString*) const;
784    void printCacheStats() const;
785
786    /** Prints GPU stats to the string if GR_GPU_STATS == 1. */
787    void dumpGpuStats(SkString*) const;
788    void printGpuStats() const;
789
790private:
791    GrGpu*                          fGpu;
792    SkAutoTUnref<GrRenderTarget>    fRenderTarget;
793    const GrClipData*               fClip;  // TODO: make this ref counted
794
795    GrResourceCache2*               fResourceCache2;
796    GrFontCache*                    fFontCache;
797    SkAutoTDelete<GrLayerCache>     fLayerCache;
798
799    GrPathRendererChain*            fPathRendererChain;
800    GrSoftwarePathRenderer*         fSoftwarePathRenderer;
801
802    GrVertexBufferAllocPool*        fDrawBufferVBAllocPool;
803    GrIndexBufferAllocPool*         fDrawBufferIBAllocPool;
804    GrInOrderDrawBuffer*            fDrawBuffer;
805
806    // Set by OverbudgetCB() to request that GrContext flush before exiting a draw.
807    bool                            fFlushToReduceCacheSize;
808    GrAARectRenderer*               fAARectRenderer;
809    GrOvalRenderer*                 fOvalRenderer;
810
811    bool                            fDidTestPMConversions;
812    int                             fPMToUPMConversion;
813    int                             fUPMToPMConversion;
814
815    struct CleanUpData {
816        PFCleanUpFunc fFunc;
817        void*         fInfo;
818    };
819
820    SkTDArray<CleanUpData>          fCleanUpData;
821
822    int                             fMaxTextureSizeOverride;
823
824    const Options                   fOptions;
825
826    GrContext(const Options&); // init must be called after the constructor.
827    bool init(GrBackend, GrBackendContext);
828    void initMockContext();
829    void initCommon();
830
831    void setupDrawBuffer();
832
833    class AutoCheckFlush;
834    // Sets the paint and returns the target to draw into.  This function is overloaded to either
835    // take a GrDrawState, GrPaint, and AutoCheckFlush, or JUST an AutoCheckFlush
836    GrDrawTarget* prepareToDraw(GrPipelineBuilder*, const GrPaint* paint, const AutoCheckFlush*);
837
838    void internalDrawPath(GrDrawTarget*,
839                          GrPipelineBuilder*,
840                          const SkMatrix& viewMatrix,
841                          GrColor,
842                          bool useAA,
843                          const SkPath&,
844                          const GrStrokeInfo&);
845
846    GrTexture* internalRefScratchTexture(const GrSurfaceDesc&, uint32_t flags);
847
848    /**
849     * These functions create premul <-> unpremul effects if it is possible to generate a pair
850     * of effects that make a readToUPM->writeToPM->readToUPM cycle invariant. Otherwise, they
851     * return NULL.
852     */
853    const GrFragmentProcessor* createPMToUPMEffect(GrTexture*, bool swapRAndB, const SkMatrix&);
854    const GrFragmentProcessor* createUPMToPMEffect(GrTexture*, bool swapRAndB, const SkMatrix&);
855
856    /**
857     *  This callback allows the resource cache to callback into the GrContext
858     *  when the cache is still over budget after a purge.
859     */
860    static void OverBudgetCB(void* data);
861
862    typedef SkRefCnt INHERITED;
863};
864
865#endif
866