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