GrGpu.h revision 36c57dfb4fe9bbaca436942d5eaa75b142ba251d
1/*
2 * Copyright 2011 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 GrGpu_DEFINED
9#define GrGpu_DEFINED
10
11#include "GrDrawTarget.h"
12#include "GrPathRendering.h"
13#include "GrProgramDesc.h"
14#include "SkPath.h"
15
16class GrContext;
17class GrIndexBufferAllocPool;
18class GrPath;
19class GrPathRange;
20class GrPathRenderer;
21class GrPathRendererChain;
22class GrPipeline;
23class GrPrimitiveProcessor;
24class GrStencilBuffer;
25class GrVertexBufferAllocPool;
26
27class GrGpu : public SkRefCnt {
28public:
29
30    /**
31     * Additional blend coefficients for dual source blending, not exposed
32     * through GrPaint/GrContext.
33     */
34    enum ExtendedBlendCoeffs {
35        // source 2 refers to second output color when
36        // using dual source blending.
37        kS2C_GrBlendCoeff = kPublicGrBlendCoeffCount,
38        kIS2C_GrBlendCoeff,
39        kS2A_GrBlendCoeff,
40        kIS2A_GrBlendCoeff,
41
42        kTotalGrBlendCoeffCount
43    };
44
45    /**
46     * Create an instance of GrGpu that matches the specified backend. If the requested backend is
47     * not supported (at compile-time or run-time) this returns NULL. The context will not be
48     * fully constructed and should not be used by GrGpu until after this function returns.
49     */
50    static GrGpu* Create(GrBackend, GrBackendContext, GrContext* context);
51
52    ////////////////////////////////////////////////////////////////////////////
53
54    GrGpu(GrContext* context);
55    ~GrGpu() SK_OVERRIDE;
56
57    GrContext* getContext() { return fContext; }
58    const GrContext* getContext() const { return fContext; }
59
60    /**
61     * Gets the capabilities of the draw target.
62     */
63    const GrDrawTargetCaps* caps() const { return fCaps.get(); }
64
65    GrPathRendering* pathRendering() {
66        return fPathRendering.get();
67    }
68
69    // Called by GrContext when the underlying backend context has been destroyed.
70    // GrGpu should use this to ensure that no backend API calls will be made from
71    // here onward, including in its destructor. Subclasses should call
72    // INHERITED::contextAbandoned() if they override this.
73    virtual void contextAbandoned();
74
75    /**
76     * The GrGpu object normally assumes that no outsider is setting state
77     * within the underlying 3D API's context/device/whatever. This call informs
78     * the GrGpu that the state was modified and it shouldn't make assumptions
79     * about the state.
80     */
81    void markContextDirty(uint32_t state = kAll_GrBackendState) {
82        fResetBits |= state;
83    }
84
85    void unimpl(const char[]);
86
87    /**
88     * Creates a texture object. If kRenderTarget_GrSurfaceFlag the texture can
89     * be used as a render target by calling GrTexture::asRenderTarget(). Not all
90     * pixel configs can be used as render targets. Support for configs as textures
91     * or render targets can be checked using GrDrawTargetCaps.
92     *
93     * @param desc        describes the texture to be created.
94     * @param budgeted    does this texture count against the resource cache budget?
95     * @param srcData     texel data to load texture. Begins with full-size
96     *                    palette data for paletted textures. For compressed
97     *                    formats it contains the compressed pixel data. Otherwise,
98     *                    it contains width*height texels. If NULL texture data
99     *                    is uninitialized.
100     * @param rowBytes    the number of bytes between consecutive rows. Zero
101     *                    means rows are tightly packed. This field is ignored
102     *                    for compressed formats.
103     *
104     * @return    The texture object if successful, otherwise NULL.
105     */
106    GrTexture* createTexture(const GrSurfaceDesc& desc, bool budgeted,
107                             const void* srcData, size_t rowBytes);
108
109    /**
110     * Implements GrContext::wrapBackendTexture
111     */
112    GrTexture* wrapBackendTexture(const GrBackendTextureDesc&);
113
114    /**
115     * Implements GrContext::wrapBackendTexture
116     */
117    GrRenderTarget* wrapBackendRenderTarget(const GrBackendRenderTargetDesc&);
118
119    /**
120     * Creates a vertex buffer.
121     *
122     * @param size    size in bytes of the vertex buffer
123     * @param dynamic hints whether the data will be frequently changed
124     *                by either GrVertexBuffer::map() or
125     *                GrVertexBuffer::updateData().
126     *
127     * @return    The vertex buffer if successful, otherwise NULL.
128     */
129    GrVertexBuffer* createVertexBuffer(size_t size, bool dynamic);
130
131    /**
132     * Creates an index buffer.
133     *
134     * @param size    size in bytes of the index buffer
135     * @param dynamic hints whether the data will be frequently changed
136     *                by either GrIndexBuffer::map() or
137     *                GrIndexBuffer::updateData().
138     *
139     * @return The index buffer if successful, otherwise NULL.
140     */
141    GrIndexBuffer* createIndexBuffer(size_t size, bool dynamic);
142
143    /**
144     * Creates an index buffer for instance drawing with a specific pattern.
145     *
146     * @param pattern     the pattern to repeat
147     * @param patternSize size in bytes of the pattern
148     * @param reps        number of times to repeat the pattern
149     * @param vertCount   number of vertices the pattern references
150     * @param dynamic     hints whether the data will be frequently changed
151     *                    by either GrIndexBuffer::map() or
152     *                    GrIndexBuffer::updateData().
153     *
154     * @return The index buffer if successful, otherwise NULL.
155     */
156    GrIndexBuffer* createInstancedIndexBuffer(const uint16_t* pattern,
157                                              int patternSize,
158                                              int reps,
159                                              int vertCount,
160                                              bool isDynamic = false);
161
162    /**
163     * Returns an index buffer that can be used to render quads.
164     * Six indices per quad: 0, 1, 2, 0, 2, 3, etc.
165     * The max number of quads can be queried using GrIndexBuffer::maxQuads().
166     * Draw with kTriangles_GrPrimitiveType
167     * @ return the quad index buffer
168     */
169    const GrIndexBuffer* getQuadIndexBuffer() const;
170
171    /**
172     * Resolves MSAA.
173     */
174    void resolveRenderTarget(GrRenderTarget* target);
175
176    /**
177     * Gets a preferred 8888 config to use for writing/reading pixel data to/from a surface with
178     * config surfaceConfig. The returned config must have at least as many bits per channel as the
179     * readConfig or writeConfig param.
180     */
181    virtual GrPixelConfig preferredReadPixelsConfig(GrPixelConfig readConfig,
182                                                    GrPixelConfig surfaceConfig) const {
183        return readConfig;
184    }
185    virtual GrPixelConfig preferredWritePixelsConfig(GrPixelConfig writeConfig,
186                                                     GrPixelConfig surfaceConfig) const {
187        return writeConfig;
188    }
189
190    /**
191     * Called before uploading writing pixels to a GrTexture when the src pixel config doesn't
192     * match the texture's config.
193     */
194    virtual bool canWriteTexturePixels(const GrTexture*, GrPixelConfig srcConfig) const = 0;
195
196    /**
197     * OpenGL's readPixels returns the result bottom-to-top while the skia
198     * API is top-to-bottom. Thus we have to do a y-axis flip. The obvious
199     * solution is to have the subclass do the flip using either the CPU or GPU.
200     * However, the caller (GrContext) may have transformations to apply and can
201     * simply fold in the y-flip for free. On the other hand, the subclass may
202     * be able to do it for free itself. For example, the subclass may have to
203     * do memcpys to handle rowBytes that aren't tight. It could do the y-flip
204     * concurrently.
205     *
206     * This function returns true if a y-flip is required to put the pixels in
207     * top-to-bottom order and the subclass cannot do it for free.
208     *
209     * See read pixels for the params
210     * @return true if calling readPixels with the same set of params will
211     *              produce bottom-to-top data
212     */
213     virtual bool readPixelsWillPayForYFlip(GrRenderTarget* renderTarget,
214                                            int left, int top,
215                                            int width, int height,
216                                            GrPixelConfig config,
217                                            size_t rowBytes) const = 0;
218     /**
219      * This should return true if reading a NxM rectangle of pixels from a
220      * render target is faster if the target has dimensons N and M and the read
221      * rectangle has its top-left at 0,0.
222      */
223     virtual bool fullReadPixelsIsFasterThanPartial() const { return false; };
224
225    /**
226     * Reads a rectangle of pixels from a render target.
227     *
228     * @param renderTarget  the render target to read from. NULL means the
229     *                      current render target.
230     * @param left          left edge of the rectangle to read (inclusive)
231     * @param top           top edge of the rectangle to read (inclusive)
232     * @param width         width of rectangle to read in pixels.
233     * @param height        height of rectangle to read in pixels.
234     * @param config        the pixel config of the destination buffer
235     * @param buffer        memory to read the rectangle into.
236     * @param rowBytes      the number of bytes between consecutive rows. Zero
237     *                      means rows are tightly packed.
238     * @param invertY       buffer should be populated bottom-to-top as opposed
239     *                      to top-to-bottom (skia's usual order)
240     *
241     * @return true if the read succeeded, false if not. The read can fail
242     *              because of a unsupported pixel config or because no render
243     *              target is currently set.
244     */
245    bool readPixels(GrRenderTarget* renderTarget,
246                    int left, int top, int width, int height,
247                    GrPixelConfig config, void* buffer, size_t rowBytes);
248
249    /**
250     * Updates the pixels in a rectangle of a texture.
251     *
252     * @param left          left edge of the rectangle to write (inclusive)
253     * @param top           top edge of the rectangle to write (inclusive)
254     * @param width         width of rectangle to write in pixels.
255     * @param height        height of rectangle to write in pixels.
256     * @param config        the pixel config of the source buffer
257     * @param buffer        memory to read pixels from
258     * @param rowBytes      number of bytes between consecutive rows. Zero
259     *                      means rows are tightly packed.
260     */
261    bool writeTexturePixels(GrTexture* texture,
262                            int left, int top, int width, int height,
263                            GrPixelConfig config, const void* buffer,
264                            size_t rowBytes);
265
266    /**
267     * Clear the passed in render target. Ignores the draw state and clip. Clears the whole thing if
268     * rect is NULL, otherwise just the rect. If canIgnoreRect is set then the entire render target
269     * can be optionally cleared.
270     */
271    void clear(const SkIRect* rect, GrColor color, bool canIgnoreRect,GrRenderTarget* renderTarget);
272
273
274    void clearStencilClip(const SkIRect& rect, bool insideClip, GrRenderTarget* renderTarget);
275
276    /**
277     * Discards the contents render target. NULL indicates that the current render target should
278     * be discarded.
279     **/
280    virtual void discard(GrRenderTarget* = NULL) = 0;
281
282    /**
283     * This is can be called before allocating a texture to be a dst for copySurface. It will
284     * populate the origin, config, and flags fields of the desc such that copySurface can
285     * efficiently succeed. It should only succeed if it can allow copySurface to perform a copy
286     * that would be more effecient than drawing the src to a dst render target.
287     */
288    virtual bool initCopySurfaceDstDesc(const GrSurface* src, GrSurfaceDesc* desc) = 0;
289
290    // After the client interacts directly with the 3D context state the GrGpu
291    // must resync its internal state and assumptions about 3D context state.
292    // Each time this occurs the GrGpu bumps a timestamp.
293    // state of the 3D context
294    // At 10 resets / frame and 60fps a 64bit timestamp will overflow in about
295    // a billion years.
296    typedef uint64_t ResetTimestamp;
297
298    // This timestamp is always older than the current timestamp
299    static const ResetTimestamp kExpiredTimestamp = 0;
300    // Returns a timestamp based on the number of times the context was reset.
301    // This timestamp can be used to lazily detect when cached 3D context state
302    // is dirty.
303    ResetTimestamp getResetTimestamp() const { return fResetTimestamp; }
304
305    GrContext::GPUStats* gpuStats() { return &fGPUStats; }
306
307    virtual void buildProgramDesc(GrProgramDesc*,
308                                  const GrPrimitiveProcessor&,
309                                  const GrPipeline&,
310                                  const GrProgramDesc::DescInfo&,
311                                  const GrBatchTracker&) const = 0;
312
313    /**
314     * Called at start and end of gpu trace marking
315     * GR_CREATE_GPU_TRACE_MARKER(marker_str, target) will automatically call these at the start
316     * and end of a code block respectively
317     */
318    void addGpuTraceMarker(const GrGpuTraceMarker* marker);
319    void removeGpuTraceMarker(const GrGpuTraceMarker* marker);
320
321    /**
322     * Takes the current active set of markers and stores them for later use. Any current marker
323     * in the active set is removed from the active set and the targets remove function is called.
324     * These functions do not work as a stack so you cannot call save a second time before calling
325     * restore. Also, it is assumed that when restore is called the current active set of markers
326     * is empty. When the stored markers are added back into the active set, the targets add marker
327     * is called.
328     */
329    void saveActiveTraceMarkers();
330    void restoreActiveTraceMarkers();
331
332    // Called to determine whether a copySurface call would succeed or not. Derived
333    // classes must keep this consistent with their implementation of onCopySurface(). Fallbacks
334    // to issuing a draw from the src to dst take place at the GrDrawTarget level and this function
335    // should only return true if a faster copy path exists. The rect and point are pre-clipped. The
336    // src rect and implied dst rect are guaranteed to be within the src/dst bounds and non-empty.
337    virtual bool canCopySurface(const GrSurface* dst,
338                                const GrSurface* src,
339                                const SkIRect& srcRect,
340                                const SkIPoint& dstPoint) = 0;
341
342    // Called to perform a surface to surface copy. Fallbacks to issuing a draw from the src to dst
343    // take place at the GrDrawTarget level and this function implement faster copy paths. The rect
344    // and point are pre-clipped. The src rect and implied dst rect are guaranteed to be within the
345    // src/dst bounds and non-empty.
346    virtual bool copySurface(GrSurface* dst,
347                             GrSurface* src,
348                             const SkIRect& srcRect,
349                             const SkIPoint& dstPoint) = 0;
350
351    struct DrawArgs {
352        typedef GrDrawTarget::DrawInfo DrawInfo;
353        DrawArgs(const GrPrimitiveProcessor* primProc,
354                 const GrPipeline* pipeline,
355                 const GrProgramDesc* desc,
356                 const GrBatchTracker* batchTracker)
357            : fPrimitiveProcessor(primProc)
358            , fPipeline(pipeline)
359            , fDesc(desc)
360            , fBatchTracker(batchTracker) {
361            SkASSERT(primProc && pipeline && desc && batchTracker);
362        }
363        const GrPrimitiveProcessor* fPrimitiveProcessor;
364        const GrPipeline* fPipeline;
365        const GrProgramDesc* fDesc;
366        const GrBatchTracker* fBatchTracker;
367    };
368
369    void draw(const DrawArgs&, const GrDrawTarget::DrawInfo&);
370
371    /** None of these params are optional, pointers used just to avoid making copies. */
372    struct StencilPathState {
373        bool fUseHWAA;
374        GrRenderTarget* fRenderTarget;
375        const SkMatrix* fViewMatrix;
376        const GrStencilSettings* fStencil;
377        const GrScissorState* fScissor;
378    };
379
380    void stencilPath(const GrPath*, const StencilPathState&);
381
382    void drawPath(const DrawArgs&, const GrPath*, const GrStencilSettings&);
383    void drawPaths(const DrawArgs&,
384                   const GrPathRange*,
385                   const void* indices,
386                   GrDrawTarget::PathIndexType,
387                   const float transformValues[],
388                   GrDrawTarget::PathTransformType,
389                   int count,
390                   const GrStencilSettings&);
391
392protected:
393    // Functions used to map clip-respecting stencil tests into normal
394    // stencil funcs supported by GPUs.
395    static GrStencilFunc ConvertStencilFunc(bool stencilInClip,
396                                            GrStencilFunc func);
397    static void ConvertStencilFuncAndMask(GrStencilFunc func,
398                                          bool clipInStencil,
399                                          unsigned int clipBit,
400                                          unsigned int userBits,
401                                          unsigned int* ref,
402                                          unsigned int* mask);
403
404    const GrTraceMarkerSet& getActiveTraceMarkers() { return fActiveTraceMarkers; }
405
406    GrContext::GPUStats         fGPUStats;
407
408    SkAutoTDelete<GrPathRendering> fPathRendering;
409
410    // Subclass must initialize this in its constructor.
411    SkAutoTUnref<const GrDrawTargetCaps> fCaps;
412
413private:
414    // called when the 3D context state is unknown. Subclass should emit any
415    // assumed 3D context state and dirty any state cache.
416    virtual void onResetContext(uint32_t resetBits) = 0;
417
418    // overridden by backend-specific derived class to create objects.
419    virtual GrTexture* onCreateTexture(const GrSurfaceDesc& desc, bool budgeted,
420                                       const void* srcData, size_t rowBytes) = 0;
421    virtual GrTexture* onCreateCompressedTexture(const GrSurfaceDesc& desc, bool budgeted,
422                                                 const void* srcData) = 0;
423    virtual GrTexture* onWrapBackendTexture(const GrBackendTextureDesc&) = 0;
424    virtual GrRenderTarget* onWrapBackendRenderTarget(const GrBackendRenderTargetDesc&) = 0;
425    virtual GrVertexBuffer* onCreateVertexBuffer(size_t size, bool dynamic) = 0;
426    virtual GrIndexBuffer* onCreateIndexBuffer(size_t size, bool dynamic) = 0;
427
428    // overridden by backend-specific derived class to perform the clear.
429    virtual void onClear(GrRenderTarget*, const SkIRect* rect, GrColor color,
430                         bool canIgnoreRect) = 0;
431
432
433    // Overridden by backend specific classes to perform a clear of the stencil clip bits.  This is
434    // ONLY used by the the clip target
435    virtual void onClearStencilClip(GrRenderTarget*,
436                                    const SkIRect& rect,
437                                    bool insideClip) = 0;
438
439    // overridden by backend-specific derived class to perform the draw call.
440    virtual void onDraw(const DrawArgs&, const GrDrawTarget::DrawInfo&) = 0;
441    virtual void onStencilPath(const GrPath*, const StencilPathState&) = 0;
442
443    virtual void onDrawPath(const DrawArgs&, const GrPath*, const GrStencilSettings&) = 0;
444    virtual void onDrawPaths(const DrawArgs&,
445                             const GrPathRange*,
446                             const void* indices,
447                             GrDrawTarget::PathIndexType,
448                             const float transformValues[],
449                             GrDrawTarget::PathTransformType,
450                             int count,
451                             const GrStencilSettings&) = 0;
452
453    // overridden by backend-specific derived class to perform the read pixels.
454    virtual bool onReadPixels(GrRenderTarget* target,
455                              int left, int top, int width, int height,
456                              GrPixelConfig,
457                              void* buffer,
458                              size_t rowBytes) = 0;
459
460    // overridden by backend-specific derived class to perform the texture update
461    virtual bool onWriteTexturePixels(GrTexture* texture,
462                                      int left, int top, int width, int height,
463                                      GrPixelConfig config, const void* buffer,
464                                      size_t rowBytes) = 0;
465
466    // overridden by backend-specific derived class to perform the resolve
467    virtual void onResolveRenderTarget(GrRenderTarget* target) = 0;
468
469    // width and height may be larger than rt (if underlying API allows it).
470    // Should attach the SB to the RT. Returns false if compatible sb could
471    // not be created.
472    virtual bool createStencilBufferForRenderTarget(GrRenderTarget*, bool budgeted,
473                                                    int width, int height) = 0;
474
475    // attaches an existing SB to an existing RT.
476    virtual bool attachStencilBufferToRenderTarget(GrStencilBuffer*, GrRenderTarget*) = 0;
477
478    // clears target's entire stencil buffer to 0
479    virtual void clearStencil(GrRenderTarget* target) = 0;
480
481    // Given a rt, find or create a stencil buffer and attach it
482    bool attachStencilBufferToRenderTarget(GrRenderTarget* target, bool budgeted);
483
484    virtual void didAddGpuTraceMarker() = 0;
485    virtual void didRemoveGpuTraceMarker() = 0;
486
487    void resetContext() {
488        this->onResetContext(fResetBits);
489        fResetBits = 0;
490        ++fResetTimestamp;
491    }
492
493    void handleDirtyContext() {
494        if (fResetBits) {
495            this->resetContext();
496        }
497    }
498
499    ResetTimestamp                                                      fResetTimestamp;
500    uint32_t                                                            fResetBits;
501    // these are mutable so they can be created on-demand
502    mutable GrIndexBuffer*                                              fQuadIndexBuffer;
503    // To keep track that we always have at least as many debug marker adds as removes
504    int                                                                 fGpuTraceMarkerCount;
505    GrTraceMarkerSet                                                    fActiveTraceMarkers;
506    GrTraceMarkerSet                                                    fStoredTraceMarkers;
507    // The context owns us, not vice-versa, so this ptr is not ref'ed by Gpu.
508    GrContext*                                                          fContext;
509
510    typedef SkRefCnt INHERITED;
511};
512
513#endif
514