GrContext.h revision f9bc796e0dbd31674c22b34761913ee6e8fdd66a
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 "GrCaps.h"
12#include "GrClip.h"
13#include "GrColor.h"
14#include "GrPaint.h"
15#include "GrRenderTarget.h"
16#include "GrTextureProvider.h"
17#include "SkMatrix.h"
18#include "SkPathEffect.h"
19#include "SkTypes.h"
20#include "../private/GrSingleOwner.h"
21#include "../private/SkMutex.h"
22
23struct GrBatchAtlasConfig;
24class GrBatchFontCache;
25struct GrContextOptions;
26class GrDrawingManager;
27class GrDrawContext;
28class GrDrawTarget;
29class GrFragmentProcessor;
30class GrGpu;
31class GrIndexBuffer;
32class GrLayerCache;
33class GrOvalRenderer;
34class GrPath;
35class GrPipelineBuilder;
36class GrResourceEntry;
37class GrResourceCache;
38class GrResourceProvider;
39class GrTestTarget;
40class GrTextBlobCache;
41class GrTextContext;
42class GrTextureParams;
43class GrVertexBuffer;
44class GrStrokeInfo;
45class SkTraceMemoryDump;
46
47class SK_API GrContext : public SkRefCnt {
48public:
49    /**
50     * Creates a GrContext for a backend context.
51     */
52    static GrContext* Create(GrBackend, GrBackendContext, const GrContextOptions& options);
53    static GrContext* Create(GrBackend, GrBackendContext);
54
55    /**
56     * Only defined in test apps.
57     */
58    static GrContext* CreateMockContext();
59
60    virtual ~GrContext();
61
62    /**
63     * The GrContext normally assumes that no outsider is setting state
64     * within the underlying 3D API's context/device/whatever. This call informs
65     * the context that the state was modified and it should resend. Shouldn't
66     * be called frequently for good performance.
67     * The flag bits, state, is dpendent on which backend is used by the
68     * context, either GL or D3D (possible in future).
69     */
70    void resetContext(uint32_t state = kAll_GrBackendState);
71
72    /**
73     * Callback function to allow classes to cleanup on GrContext destruction.
74     * The 'info' field is filled in with the 'info' passed to addCleanUp.
75     */
76    typedef void (*PFCleanUpFunc)(const GrContext* context, void* info);
77
78    /**
79     * Add a function to be called from within GrContext's destructor.
80     * This gives classes a chance to free resources held on a per context basis.
81     * The 'info' parameter will be stored and passed to the callback function.
82     */
83    void addCleanUp(PFCleanUpFunc cleanUp, void* info) {
84        CleanUpData* entry = fCleanUpData.push();
85
86        entry->fFunc = cleanUp;
87        entry->fInfo = info;
88    }
89
90    /**
91     * Abandons all GPU resources and assumes the underlying backend 3D API
92     * context is not longer usable. Call this if you have lost the associated
93     * GPU context, and thus internal texture, buffer, etc. references/IDs are
94     * now invalid. Should be called even when GrContext is no longer going to
95     * be used for two reasons:
96     *  1) ~GrContext will not try to free the objects in the 3D API.
97     *  2) Any GrGpuResources created by this GrContext that outlive
98     *     will be marked as invalid (GrGpuResource::wasDestroyed()) and
99     *     when they're destroyed no 3D API calls will be made.
100     * Content drawn since the last GrContext::flush() may be lost. After this
101     * function is called the only valid action on the GrContext or
102     * GrGpuResources it created is to destroy them.
103     */
104    void abandonContext();
105
106    ///////////////////////////////////////////////////////////////////////////
107    // Resource Cache
108
109    /**
110     *  Return the current GPU resource cache limits.
111     *
112     *  @param maxResources If non-null, returns maximum number of resources that
113     *                      can be held in the cache.
114     *  @param maxResourceBytes If non-null, returns maximum number of bytes of
115     *                          video memory that can be held in the cache.
116     */
117    void getResourceCacheLimits(int* maxResources, size_t* maxResourceBytes) const;
118
119    /**
120     *  Gets the current GPU resource cache usage.
121     *
122     *  @param resourceCount If non-null, returns the number of resources that are held in the
123     *                       cache.
124     *  @param maxResourceBytes If non-null, returns the total number of bytes of video memory held
125     *                          in the cache.
126     */
127    void getResourceCacheUsage(int* resourceCount, size_t* resourceBytes) const;
128
129    /**
130     *  Specify the GPU resource cache limits. If the current cache exceeds either
131     *  of these, it will be purged (LRU) to keep the cache within these limits.
132     *
133     *  @param maxResources The maximum number of resources that can be held in
134     *                      the cache.
135     *  @param maxResourceBytes The maximum number of bytes of video memory
136     *                          that can be held in the cache.
137     */
138    void setResourceCacheLimits(int maxResources, size_t maxResourceBytes);
139
140    GrTextureProvider* textureProvider() { return fTextureProvider; }
141    const GrTextureProvider* textureProvider() const { return fTextureProvider; }
142
143    /**
144     * Frees GPU created by the context. Can be called to reduce GPU memory
145     * pressure.
146     */
147    void freeGpuResources();
148
149    /**
150     * Purge all the unlocked resources from the cache.
151     * This entry point is mainly meant for timing texture uploads
152     * and is not defined in normal builds of Skia.
153     */
154    void purgeAllUnlockedResources();
155
156    /** Access the context capabilities */
157    const GrCaps* caps() const { return fCaps; }
158
159    /**
160     * Returns the recommended sample count for a render target when using this
161     * context.
162     *
163     * @param  config the configuration of the render target.
164     * @param  dpi the display density in dots per inch.
165     *
166     * @return sample count that should be perform well and have good enough
167     *         rendering quality for the display. Alternatively returns 0 if
168     *         MSAA is not supported or recommended to be used by default.
169     */
170    int getRecommendedSampleCount(GrPixelConfig config, SkScalar dpi) const;
171
172    /**
173     * Returns a helper object to orchestrate draws.
174     * Callers assume the creation ref of the drawContext
175     * NULL will be returned if the context has been abandoned.
176     *
177     * @param  rt           the render target receiving the draws
178     * @param  surfaceProps the surface properties (mainly defines text drawing)
179     *
180     * @return a draw context
181     */
182    GrDrawContext* drawContext(GrRenderTarget* rt, const SkSurfaceProps* surfaceProps = NULL);
183
184    ///////////////////////////////////////////////////////////////////////////
185    // Misc.
186
187    /**
188     * Flags that affect flush() behavior.
189     */
190    enum FlushBits {
191        /**
192         * A client may reach a point where it has partially rendered a frame
193         * through a GrContext that it knows the user will never see. This flag
194         * causes the flush to skip submission of deferred content to the 3D API
195         * during the flush.
196         */
197        kDiscard_FlushBit                    = 0x2,
198    };
199
200    /**
201     * Call to ensure all drawing to the context has been issued to the
202     * underlying 3D API.
203     * @param flagsBitfield     flags that control the flushing behavior. See
204     *                          FlushBits.
205     */
206    void flush(int flagsBitfield = 0);
207
208    void flushIfNecessary() {
209        if (fFlushToReduceCacheSize || this->caps()->immediateFlush()) {
210            this->flush();
211        }
212    }
213
214   /**
215    * These flags can be used with the read/write pixels functions below.
216    */
217    enum PixelOpsFlags {
218        /** The GrContext will not be flushed before the surface read or write. This means that
219            the read or write may occur before previous draws have executed. */
220        kDontFlush_PixelOpsFlag = 0x1,
221        /** Any surface writes should be flushed to the backend 3D API after the surface operation
222            is complete */
223        kFlushWrites_PixelOp = 0x2,
224        /** The src for write or dst read is unpremultiplied. This is only respected if both the
225            config src and dst configs are an RGBA/BGRA 8888 format. */
226        kUnpremul_PixelOpsFlag  = 0x4,
227    };
228
229    /**
230     * Reads a rectangle of pixels from a surface.
231     * @param surface       the surface to read from.
232     * @param left          left edge of the rectangle to read (inclusive)
233     * @param top           top edge of the rectangle to read (inclusive)
234     * @param width         width of rectangle to read in pixels.
235     * @param height        height of rectangle to read in pixels.
236     * @param config        the pixel config of the destination buffer
237     * @param buffer        memory to read the rectangle into.
238     * @param rowBytes      number of bytes bewtween consecutive rows. Zero means rows are tightly
239     *                      packed.
240     * @param pixelOpsFlags see PixelOpsFlags enum above.
241     *
242     * @return true if the read succeeded, false if not. The read can fail because of an unsupported
243     *         pixel configs
244     */
245    bool readSurfacePixels(GrSurface* surface,
246                           int left, int top, int width, int height,
247                           GrPixelConfig config, void* buffer,
248                           size_t rowBytes = 0,
249                           uint32_t pixelOpsFlags = 0);
250
251    /**
252     * Writes a rectangle of pixels to a surface.
253     * @param surface       the surface to write to.
254     * @param left          left edge of the rectangle to write (inclusive)
255     * @param top           top edge of the rectangle to write (inclusive)
256     * @param width         width of rectangle to write in pixels.
257     * @param height        height of rectangle to write in pixels.
258     * @param config        the pixel config of the source buffer
259     * @param buffer        memory to read pixels from
260     * @param rowBytes      number of bytes between consecutive rows. Zero
261     *                      means rows are tightly packed.
262     * @param pixelOpsFlags see PixelOpsFlags enum above.
263     * @return true if the write succeeded, false if not. The write can fail because of an
264     *         unsupported combination of surface and src configs.
265     */
266    bool writeSurfacePixels(GrSurface* surface,
267                            int left, int top, int width, int height,
268                            GrPixelConfig config, const void* buffer,
269                            size_t rowBytes,
270                            uint32_t pixelOpsFlags = 0);
271
272    /**
273     * Copies a rectangle of texels from src to dst.
274     * bounds.
275     * @param dst           the surface to copy to.
276     * @param src           the surface to copy from.
277     * @param srcRect       the rectangle of the src that should be copied.
278     * @param dstPoint      the translation applied when writing the srcRect's pixels to the dst.
279     * @param pixelOpsFlags see PixelOpsFlags enum above. (kUnpremul_PixelOpsFlag is not allowed).
280     */
281    void copySurface(GrSurface* dst,
282                     GrSurface* src,
283                     const SkIRect& srcRect,
284                     const SkIPoint& dstPoint,
285                     uint32_t pixelOpsFlags = 0);
286
287    /** Helper that copies the whole surface but fails when the two surfaces are not identically
288        sized. */
289    bool copySurface(GrSurface* dst, GrSurface* src) {
290        if (NULL == dst || NULL == src || dst->width() != src->width() ||
291            dst->height() != src->height()) {
292            return false;
293        }
294        this->copySurface(dst, src, SkIRect::MakeWH(dst->width(), dst->height()),
295                          SkIPoint::Make(0,0));
296        return true;
297    }
298
299    /**
300     * After this returns any pending writes to the surface will have been issued to the backend 3D API.
301     */
302    void flushSurfaceWrites(GrSurface* surface);
303
304    /**
305     * Finalizes all pending reads and writes to the surface and also performs an MSAA resolve
306     * if necessary.
307     *
308     * It is not necessary to call this before reading the render target via Skia/GrContext.
309     * GrContext will detect when it must perform a resolve before reading pixels back from the
310     * surface or using it as a texture.
311     */
312    void prepareSurfaceForExternalIO(GrSurface*);
313
314    /**
315     * An ID associated with this context, guaranteed to be unique.
316     */
317    uint32_t uniqueID() { return fUniqueID; }
318
319    ///////////////////////////////////////////////////////////////////////////
320    // Functions intended for internal use only.
321    GrGpu* getGpu() { return fGpu; }
322    const GrGpu* getGpu() const { return fGpu; }
323    GrBatchFontCache* getBatchFontCache() { return fBatchFontCache; }
324    GrLayerCache* getLayerCache() { return fLayerCache.get(); }
325    GrTextBlobCache* getTextBlobCache() { return fTextBlobCache; }
326    bool abandoned() const;
327    GrResourceProvider* resourceProvider() { return fResourceProvider; }
328    const GrResourceProvider* resourceProvider() const { return fResourceProvider; }
329    GrResourceCache* getResourceCache() { return fResourceCache; }
330
331    // Called by tests that draw directly to the context via GrDrawTarget
332    void getTestTarget(GrTestTarget*, GrRenderTarget* rt);
333
334    /** Reset GPU stats */
335    void resetGpuStats() const ;
336
337    /** Prints cache stats to the string if GR_CACHE_STATS == 1. */
338    void dumpCacheStats(SkString*) const;
339    void dumpCacheStatsKeyValuePairs(SkTArray<SkString>* keys, SkTArray<double>* values) const;
340    void printCacheStats() const;
341
342    /** Prints GPU stats to the string if GR_GPU_STATS == 1. */
343    void dumpGpuStats(SkString*) const;
344    void dumpGpuStatsKeyValuePairs(SkTArray<SkString>* keys, SkTArray<double>* values) const;
345    void printGpuStats() const;
346
347    /** Specify the TextBlob cache limit. If the current cache exceeds this limit it will purge.
348        this is for testing only */
349    void setTextBlobCacheLimit_ForTesting(size_t bytes);
350
351    /** Specify the sizes of the GrAtlasTextContext atlases.  The configs pointer below should be
352        to an array of 3 entries */
353    void setTextContextAtlasSizes_ForTesting(const GrBatchAtlasConfig* configs);
354
355    /** Enumerates all cached GPU resources and dumps their memory to traceMemoryDump. */
356    void dumpMemoryStatistics(SkTraceMemoryDump* traceMemoryDump) const;
357
358    /** Get pointer to atlas texture for given mask format */
359    GrTexture* getFontAtlasTexture(GrMaskFormat format);
360
361private:
362    GrGpu*                          fGpu;
363    const GrCaps*                   fCaps;
364    GrResourceCache*                fResourceCache;
365    // this union exists because the inheritance of GrTextureProvider->GrResourceProvider
366    // is in a private header.
367    union {
368        GrResourceProvider*         fResourceProvider;
369        GrTextureProvider*          fTextureProvider;
370    };
371
372    GrBatchFontCache*               fBatchFontCache;
373    SkAutoTDelete<GrLayerCache>     fLayerCache;
374    SkAutoTDelete<GrTextBlobCache>  fTextBlobCache;
375
376    // Set by OverbudgetCB() to request that GrContext flush before exiting a draw.
377    bool                            fFlushToReduceCacheSize;
378    bool                            fDidTestPMConversions;
379    int                             fPMToUPMConversion;
380    int                             fUPMToPMConversion;
381    // The sw backend may call GrContext::readSurfacePixels on multiple threads
382    // We may transfer the responsibilty for using a mutex to the sw backend
383    // when there are fewer code paths that lead to a readSurfacePixels call
384    // from the sw backend. readSurfacePixels is reentrant in one case - when performing
385    // the PM conversions test. To handle this we do the PM conversions test outside
386    // of fReadPixelsMutex and use a separate mutex to guard it. When it re-enters
387    // readSurfacePixels it will grab fReadPixelsMutex and release it before the outer
388    // readSurfacePixels proceeds to grab it.
389    // TODO: Stop pretending to make GrContext thread-safe for sw rasterization and provide
390    // a mechanism to make a SkPicture safe for multithreaded sw rasterization.
391    SkMutex                         fReadPixelsMutex;
392    SkMutex                         fTestPMConversionsMutex;
393
394    // In debug builds we guard against improper thread handling
395    // This guard is passed to the GrDrawingManager and, from there to all the
396    // GrDrawContexts.  It is also passed to the GrTextureProvider and SkGpuDevice.
397    mutable GrSingleOwner fSingleOwner;
398
399    struct CleanUpData {
400        PFCleanUpFunc fFunc;
401        void*         fInfo;
402    };
403
404    SkTDArray<CleanUpData>          fCleanUpData;
405
406    const uint32_t                  fUniqueID;
407
408    SkAutoTDelete<GrDrawingManager> fDrawingManager;
409
410    // TODO: have the CMM use drawContexts and rm this friending
411    friend class GrClipMaskManager; // the CMM is friended just so it can call 'drawingManager'
412    friend class GrDrawingManager;  // for access to drawingManager for ProgramUnitTest
413    GrDrawingManager* drawingManager() { return fDrawingManager; }
414
415    GrContext(); // init must be called after the constructor.
416    bool init(GrBackend, GrBackendContext, const GrContextOptions& options);
417
418    void initMockContext();
419    void initCommon(const GrContextOptions&);
420
421    /**
422     * These functions create premul <-> unpremul effects if it is possible to generate a pair
423     * of effects that make a readToUPM->writeToPM->readToUPM cycle invariant. Otherwise, they
424     * return NULL.
425     */
426    const GrFragmentProcessor* createPMToUPMEffect(GrTexture*, bool swapRAndB,
427                                                   const SkMatrix&) const;
428    const GrFragmentProcessor* createUPMToPMEffect(GrTexture*, bool swapRAndB,
429                                                   const SkMatrix&) const;
430    /** Called before either of the above two functions to determine the appropriate fragment
431        processors for conversions. This must be called by readSurfacePixels before a mutex is
432        taken, since testingvPM conversions itself will call readSurfacePixels */
433    void testPMConversionsIfNecessary(uint32_t flags);
434    /** Returns true if we've already determined that createPMtoUPMEffect and createUPMToPMEffect
435        will fail. In such cases fall back to SW conversion. */
436    bool didFailPMUPMConversionTest() const;
437
438    /**
439     *  This callback allows the resource cache to callback into the GrContext
440     *  when the cache is still over budget after a purge.
441     */
442    static void OverBudgetCB(void* data);
443
444    /**
445     * A callback similar to the above for use by the TextBlobCache
446     * TODO move textblob draw calls below context so we can use the call above.
447     */
448    static void TextBlobCacheOverBudgetCB(void* data);
449
450    typedef SkRefCnt INHERITED;
451};
452
453#endif
454