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