GrGpu.h revision b0bd4f64a6827dda6f4ec48e4746b0f0b72a975f
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 "GrClipMaskManager.h"
13#include "GrPathRendering.h"
14#include "SkPath.h"
15
16class GrContext;
17class GrIndexBufferAllocPool;
18class GrPath;
19class GrPathRange;
20class GrPathRenderer;
21class GrPathRendererChain;
22class GrStencilBuffer;
23class GrVertexBufferAllocPool;
24
25class GrGpu : public GrDrawTarget {
26public:
27
28    /**
29     * Additional blend coefficients for dual source blending, not exposed
30     * through GrPaint/GrContext.
31     */
32    enum ExtendedBlendCoeffs {
33        // source 2 refers to second output color when
34        // using dual source blending.
35        kS2C_GrBlendCoeff = kPublicGrBlendCoeffCount,
36        kIS2C_GrBlendCoeff,
37        kS2A_GrBlendCoeff,
38        kIS2A_GrBlendCoeff,
39
40        kTotalGrBlendCoeffCount
41    };
42
43    /**
44     * Create an instance of GrGpu that matches the specified backend. If the requested backend is
45     * not supported (at compile-time or run-time) this returns NULL. The context will not be
46     * fully constructed and should not be used by GrGpu until after this function returns.
47     */
48    static GrGpu* Create(GrBackend, GrBackendContext, GrContext* context);
49
50    ////////////////////////////////////////////////////////////////////////////
51
52    GrGpu(GrContext* context);
53    virtual ~GrGpu();
54
55    GrContext* getContext() { return this->INHERITED::getContext(); }
56    const GrContext* getContext() const { return this->INHERITED::getContext(); }
57
58    GrPathRendering* pathRendering() {
59        return fPathRendering.get();
60    }
61
62    // Called by GrContext when the underlying backend context has been destroyed.
63    // GrGpu should use this to ensure that no backend API calls will be made from
64    // here onward, including in its destructor. Subclasses should call
65    // INHERITED::contextAbandonded() if they override this.
66    virtual void contextAbandonded();
67
68    /**
69     * The GrGpu object normally assumes that no outsider is setting state
70     * within the underlying 3D API's context/device/whatever. This call informs
71     * the GrGpu that the state was modified and it shouldn't make assumptions
72     * about the state.
73     */
74    void markContextDirty(uint32_t state = kAll_GrBackendState) {
75        fResetBits |= state;
76    }
77
78    void unimpl(const char[]);
79
80    /**
81     * Creates a texture object. If desc width or height is not a power of
82     * two but underlying API requires a power of two texture then srcData
83     * will be embedded in a power of two texture. The extra width and height
84     * is filled as though srcData were rendered clamped into the texture.
85     * The exception is when using compressed data formats. In this case, the
86     * desc width and height must be a multiple of the compressed format block
87     * size otherwise this function returns NULL. Similarly, if the underlying
88     * API requires a power of two texture and the source width and height are not
89     * a power of two, then this function returns NULL.
90     *
91     * If kRenderTarget_TextureFlag is specified the GrRenderTarget is
92     * accessible via GrTexture::asRenderTarget(). The texture will hold a ref
93     * on the render target until the texture is destroyed. Compressed textures
94     * cannot have the kRenderTarget_TextureFlag set.
95     *
96     * @param desc        describes the texture to be created.
97     * @param srcData     texel data to load texture. Begins with full-size
98     *                    palette data for paletted textures. For compressed
99     *                    formats it contains the compressed pixel data. Otherwise,
100     *                    it contains width*height texels. If NULL texture data
101     *                    is uninitialized.
102     * @param rowBytes    the number of bytes between consecutive rows. Zero
103     *                    means rows are tightly packed. This field is ignored
104     *                    for compressed formats.
105     *
106     * @return    The texture object if successful, otherwise NULL.
107     */
108    GrTexture* createTexture(const GrTextureDesc& desc,
109                             const void* srcData, size_t rowBytes);
110
111    /**
112     * Implements GrContext::wrapBackendTexture
113     */
114    GrTexture* wrapBackendTexture(const GrBackendTextureDesc&);
115
116    /**
117     * Implements GrContext::wrapBackendTexture
118     */
119    GrRenderTarget* wrapBackendRenderTarget(const GrBackendRenderTargetDesc&);
120
121    /**
122     * Creates a vertex buffer.
123     *
124     * @param size    size in bytes of the vertex buffer
125     * @param dynamic hints whether the data will be frequently changed
126     *                by either GrVertexBuffer::map() or
127     *                GrVertexBuffer::updateData().
128     *
129     * @return    The vertex buffer if successful, otherwise NULL.
130     */
131    GrVertexBuffer* createVertexBuffer(size_t size, bool dynamic);
132
133    /**
134     * Creates an index buffer.
135     *
136     * @param size    size in bytes of the index buffer
137     * @param dynamic hints whether the data will be frequently changed
138     *                by either GrIndexBuffer::map() or
139     *                GrIndexBuffer::updateData().
140     *
141     * @return The index buffer if successful, otherwise NULL.
142     */
143    GrIndexBuffer* createIndexBuffer(size_t size, bool dynamic);
144
145    /**
146     * Creates a path object that can be stenciled using stencilPath(). It is
147     * only legal to call this if the caps report support for path stenciling.
148     */
149    GrPath* createPath(const SkPath& path, const SkStrokeRec& stroke);
150
151    /**
152     * Creates a path range object that can be used to draw multiple paths via
153     * drawPaths(). It is only legal to call this if the caps report support for
154     * path rendering.
155     */
156    GrPathRange* createPathRange(size_t size, const SkStrokeRec&);
157
158    /**
159     * Returns an index buffer that can be used to render quads.
160     * Six indices per quad: 0, 1, 2, 0, 2, 3, etc.
161     * The max number of quads can be queried using GrIndexBuffer::maxQuads().
162     * Draw with kTriangles_GrPrimitiveType
163     * @ return the quad index buffer
164     */
165    const GrIndexBuffer* getQuadIndexBuffer() const;
166
167    /**
168     * Resolves MSAA.
169     */
170    void resolveRenderTarget(GrRenderTarget* target);
171
172    /**
173     * Gets a preferred 8888 config to use for writing/reading pixel data to/from a surface with
174     * config surfaceConfig. The returned config must have at least as many bits per channel as the
175     * readConfig or writeConfig param.
176     */
177    virtual GrPixelConfig preferredReadPixelsConfig(GrPixelConfig readConfig,
178                                                    GrPixelConfig surfaceConfig) const {
179        return readConfig;
180    }
181    virtual GrPixelConfig preferredWritePixelsConfig(GrPixelConfig writeConfig,
182                                                     GrPixelConfig surfaceConfig) const {
183        return writeConfig;
184    }
185
186    /**
187     * Called before uploading writing pixels to a GrTexture when the src pixel config doesn't
188     * match the texture's config.
189     */
190    virtual bool canWriteTexturePixels(const GrTexture*, GrPixelConfig srcConfig) const = 0;
191
192    /**
193     * OpenGL's readPixels returns the result bottom-to-top while the skia
194     * API is top-to-bottom. Thus we have to do a y-axis flip. The obvious
195     * solution is to have the subclass do the flip using either the CPU or GPU.
196     * However, the caller (GrContext) may have transformations to apply and can
197     * simply fold in the y-flip for free. On the other hand, the subclass may
198     * be able to do it for free itself. For example, the subclass may have to
199     * do memcpys to handle rowBytes that aren't tight. It could do the y-flip
200     * concurrently.
201     *
202     * This function returns true if a y-flip is required to put the pixels in
203     * top-to-bottom order and the subclass cannot do it for free.
204     *
205     * See read pixels for the params
206     * @return true if calling readPixels with the same set of params will
207     *              produce bottom-to-top data
208     */
209     virtual bool readPixelsWillPayForYFlip(GrRenderTarget* renderTarget,
210                                            int left, int top,
211                                            int width, int height,
212                                            GrPixelConfig config,
213                                            size_t rowBytes) const = 0;
214     /**
215      * This should return true if reading a NxM rectangle of pixels from a
216      * render target is faster if the target has dimensons N and M and the read
217      * rectangle has its top-left at 0,0.
218      */
219     virtual bool fullReadPixelsIsFasterThanPartial() const { return false; };
220
221    /**
222     * Reads a rectangle of pixels from a render target.
223     *
224     * @param renderTarget  the render target to read from. NULL means the
225     *                      current render target.
226     * @param left          left edge of the rectangle to read (inclusive)
227     * @param top           top edge of the rectangle to read (inclusive)
228     * @param width         width of rectangle to read in pixels.
229     * @param height        height of rectangle to read in pixels.
230     * @param config        the pixel config of the destination buffer
231     * @param buffer        memory to read the rectangle into.
232     * @param rowBytes      the number of bytes between consecutive rows. Zero
233     *                      means rows are tightly packed.
234     * @param invertY       buffer should be populated bottom-to-top as opposed
235     *                      to top-to-bottom (skia's usual order)
236     *
237     * @return true if the read succeeded, false if not. The read can fail
238     *              because of a unsupported pixel config or because no render
239     *              target is currently set.
240     */
241    bool readPixels(GrRenderTarget* renderTarget,
242                    int left, int top, int width, int height,
243                    GrPixelConfig config, void* buffer, size_t rowBytes);
244
245    /**
246     * Updates the pixels in a rectangle of a texture.
247     *
248     * @param left          left edge of the rectangle to write (inclusive)
249     * @param top           top edge of the rectangle to write (inclusive)
250     * @param width         width of rectangle to write in pixels.
251     * @param height        height of rectangle to write in pixels.
252     * @param config        the pixel config of the source buffer
253     * @param buffer        memory to read pixels from
254     * @param rowBytes      number of bytes between consecutive rows. Zero
255     *                      means rows are tightly packed.
256     */
257    bool writeTexturePixels(GrTexture* texture,
258                            int left, int top, int width, int height,
259                            GrPixelConfig config, const void* buffer,
260                            size_t rowBytes);
261
262    // GrDrawTarget overrides
263    virtual void clear(const SkIRect* rect,
264                       GrColor color,
265                       bool canIgnoreRect,
266                       GrRenderTarget* renderTarget = NULL) SK_OVERRIDE;
267
268    virtual void purgeResources() SK_OVERRIDE {
269        // The clip mask manager can rebuild all its clip masks so just
270        // get rid of them all.
271        fClipMaskManager.purgeResources();
272    }
273
274    // After the client interacts directly with the 3D context state the GrGpu
275    // must resync its internal state and assumptions about 3D context state.
276    // Each time this occurs the GrGpu bumps a timestamp.
277    // state of the 3D context
278    // At 10 resets / frame and 60fps a 64bit timestamp will overflow in about
279    // a billion years.
280    typedef uint64_t ResetTimestamp;
281
282    // This timestamp is always older than the current timestamp
283    static const ResetTimestamp kExpiredTimestamp = 0;
284    // Returns a timestamp based on the number of times the context was reset.
285    // This timestamp can be used to lazily detect when cached 3D context state
286    // is dirty.
287    ResetTimestamp getResetTimestamp() const {
288        return fResetTimestamp;
289    }
290
291    /**
292     * These methods are called by the clip manager's setupClipping function
293     * which (called as part of GrGpu's implementation of onDraw and
294     * onStencilPath member functions.) The GrGpu subclass should flush the
295     * stencil state to the 3D API in its implementation of flushGraphicsState.
296     */
297    void enableScissor(const SkIRect& rect) {
298        fScissorState.fEnabled = true;
299        fScissorState.fRect = rect;
300    }
301    void disableScissor() { fScissorState.fEnabled = false; }
302
303    /**
304     * Like the scissor methods above this is called by setupClipping and
305     * should be flushed by the GrGpu subclass in flushGraphicsState. These
306     * stencil settings should be used in place of those on the GrDrawState.
307     * They have been adjusted to account for any interactions between the
308     * GrDrawState's stencil settings and stencil clipping.
309     */
310    void setStencilSettings(const GrStencilSettings& settings) {
311        fStencilSettings = settings;
312    }
313    void disableStencil() { fStencilSettings.setDisabled(); }
314
315    // GrGpu subclass sets clip bit in the stencil buffer. The subclass is
316    // free to clear the remaining bits to zero if masked clears are more
317    // expensive than clearing all bits.
318    virtual void clearStencilClip(GrRenderTarget*, const SkIRect& rect, bool insideClip) = 0;
319
320    enum PrivateDrawStateStateBits {
321        kFirstBit = (GrDrawState::kLastPublicStateBit << 1),
322
323        kModifyStencilClip_StateBit = kFirstBit, // allows draws to modify
324                                                 // stencil bits used for
325                                                 // clipping.
326    };
327
328    void getPathStencilSettingsForFillType(SkPath::FillType fill, GrStencilSettings* outStencilSettings);
329
330    enum DrawType {
331        kDrawPoints_DrawType,
332        kDrawLines_DrawType,
333        kDrawTriangles_DrawType,
334        kStencilPath_DrawType,
335        kDrawPath_DrawType,
336        kDrawPaths_DrawType,
337    };
338
339    static bool IsPathRenderingDrawType(DrawType type) {
340        return kDrawPath_DrawType == type || kDrawPaths_DrawType == type;
341    }
342
343protected:
344    DrawType PrimTypeToDrawType(GrPrimitiveType type) {
345        switch (type) {
346            case kTriangles_GrPrimitiveType:
347            case kTriangleStrip_GrPrimitiveType:
348            case kTriangleFan_GrPrimitiveType:
349                return kDrawTriangles_DrawType;
350            case kPoints_GrPrimitiveType:
351                return kDrawPoints_DrawType;
352            case kLines_GrPrimitiveType:
353            case kLineStrip_GrPrimitiveType:
354                return kDrawLines_DrawType;
355            default:
356                SkFAIL("Unexpected primitive type");
357                return kDrawTriangles_DrawType;
358        }
359    }
360
361    // prepares clip flushes gpu state before a draw
362    bool setupClipAndFlushState(DrawType,
363                                const GrDeviceCoordTexture* dstCopy,
364                                GrDrawState::AutoRestoreEffects* are,
365                                const SkRect* devBounds);
366
367    // Functions used to map clip-respecting stencil tests into normal
368    // stencil funcs supported by GPUs.
369    static GrStencilFunc ConvertStencilFunc(bool stencilInClip,
370                                            GrStencilFunc func);
371    static void ConvertStencilFuncAndMask(GrStencilFunc func,
372                                          bool clipInStencil,
373                                          unsigned int clipBit,
374                                          unsigned int userBits,
375                                          unsigned int* ref,
376                                          unsigned int* mask);
377
378    GrClipMaskManager           fClipMaskManager;
379
380    struct GeometryPoolState {
381        const GrVertexBuffer* fPoolVertexBuffer;
382        int                   fPoolStartVertex;
383
384        const GrIndexBuffer*  fPoolIndexBuffer;
385        int                   fPoolStartIndex;
386    };
387    const GeometryPoolState& getGeomPoolState() {
388        return fGeomPoolStateStack.back();
389    }
390
391    // The state of the scissor is controlled by the clip manager
392    struct ScissorState {
393        bool    fEnabled;
394        SkIRect fRect;
395    } fScissorState;
396
397    // The final stencil settings to use as determined by the clip manager.
398    GrStencilSettings fStencilSettings;
399
400    // Helpers for setting up geometry state
401    void finalizeReservedVertices();
402    void finalizeReservedIndices();
403
404    SkAutoTDelete<GrPathRendering> fPathRendering;
405
406private:
407    // GrDrawTarget overrides
408    virtual bool onReserveVertexSpace(size_t vertexSize, int vertexCount, void** vertices) SK_OVERRIDE;
409    virtual bool onReserveIndexSpace(int indexCount, void** indices) SK_OVERRIDE;
410    virtual void releaseReservedVertexSpace() SK_OVERRIDE;
411    virtual void releaseReservedIndexSpace() SK_OVERRIDE;
412    virtual void onSetVertexSourceToArray(const void* vertexArray, int vertexCount) SK_OVERRIDE;
413    virtual void onSetIndexSourceToArray(const void* indexArray, int indexCount) SK_OVERRIDE;
414    virtual void releaseVertexArray() SK_OVERRIDE;
415    virtual void releaseIndexArray() SK_OVERRIDE;
416    virtual void geometrySourceWillPush() SK_OVERRIDE;
417    virtual void geometrySourceWillPop(const GeometrySrcState& restoredState) SK_OVERRIDE;
418
419
420    // called when the 3D context state is unknown. Subclass should emit any
421    // assumed 3D context state and dirty any state cache.
422    virtual void onResetContext(uint32_t resetBits) = 0;
423
424    // overridden by backend-specific derived class to create objects.
425    virtual GrTexture* onCreateTexture(const GrTextureDesc& desc,
426                                       const void* srcData,
427                                       size_t rowBytes) = 0;
428    virtual GrTexture* onCreateCompressedTexture(const GrTextureDesc& desc,
429                                                 const void* srcData) = 0;
430    virtual GrTexture* onWrapBackendTexture(const GrBackendTextureDesc&) = 0;
431    virtual GrRenderTarget* onWrapBackendRenderTarget(const GrBackendRenderTargetDesc&) = 0;
432    virtual GrVertexBuffer* onCreateVertexBuffer(size_t size, bool dynamic) = 0;
433    virtual GrIndexBuffer* onCreateIndexBuffer(size_t size, bool dynamic) = 0;
434
435    // overridden by backend-specific derived class to perform the clear and
436    // clearRect. NULL rect means clear whole target. If canIgnoreRect is
437    // true, it is okay to perform a full clear instead of a partial clear
438    virtual void onClear(GrRenderTarget*, const SkIRect* rect, GrColor color,
439                         bool canIgnoreRect) = 0;
440
441    // overridden by backend-specific derived class to perform the draw call.
442    virtual void onGpuDraw(const DrawInfo&) = 0;
443
444    // overridden by backend-specific derived class to perform the read pixels.
445    virtual bool onReadPixels(GrRenderTarget* target,
446                              int left, int top, int width, int height,
447                              GrPixelConfig,
448                              void* buffer,
449                              size_t rowBytes) = 0;
450
451    // overridden by backend-specific derived class to perform the texture update
452    virtual bool onWriteTexturePixels(GrTexture* texture,
453                                      int left, int top, int width, int height,
454                                      GrPixelConfig config, const void* buffer,
455                                      size_t rowBytes) = 0;
456
457    // overridden by backend-specific derived class to perform the resolve
458    virtual void onResolveRenderTarget(GrRenderTarget* target) = 0;
459
460    // width and height may be larger than rt (if underlying API allows it).
461    // Should attach the SB to the RT. Returns false if compatible sb could
462    // not be created.
463    virtual bool createStencilBufferForRenderTarget(GrRenderTarget*, int width, int height) = 0;
464
465    // attaches an existing SB to an existing RT.
466    virtual bool attachStencilBufferToRenderTarget(GrStencilBuffer*, GrRenderTarget*) = 0;
467
468    // The GrGpu typically records the clients requested state and then flushes
469    // deltas from previous state at draw time. This function does the
470    // backend-specific flush of the state.
471    // returns false if current state is unsupported.
472    virtual bool flushGraphicsState(DrawType, const GrDeviceCoordTexture* dstCopy) = 0;
473
474    // clears target's entire stencil buffer to 0
475    virtual void clearStencil(GrRenderTarget* target) = 0;
476
477    // Given a rt, find or create a stencil buffer and attach it
478    bool attachStencilBufferToRenderTarget(GrRenderTarget* target);
479
480    // GrDrawTarget overrides
481    virtual void onDraw(const DrawInfo&) SK_OVERRIDE;
482    virtual void onStencilPath(const GrPath*, SkPath::FillType) SK_OVERRIDE;
483    virtual void onDrawPath(const GrPath*, SkPath::FillType,
484                            const GrDeviceCoordTexture* dstCopy) SK_OVERRIDE;
485    virtual void onDrawPaths(const GrPathRange*,
486                             const uint32_t indices[], int count,
487                             const float transforms[], PathTransformType,
488                             SkPath::FillType, const GrDeviceCoordTexture*) SK_OVERRIDE;
489
490    // readies the pools to provide vertex/index data.
491    void prepareVertexPool();
492    void prepareIndexPool();
493
494    void resetContext() {
495        // We call this because the client may have messed with the
496        // stencil buffer. Perhaps we should detect whether it is a
497        // internally created stencil buffer and if so skip the invalidate.
498        fClipMaskManager.invalidateStencilMask();
499        this->onResetContext(fResetBits);
500        fResetBits = 0;
501        ++fResetTimestamp;
502    }
503
504    void handleDirtyContext() {
505        if (fResetBits) {
506            this->resetContext();
507        }
508    }
509
510    enum {
511        kPreallocGeomPoolStateStackCnt = 4,
512    };
513    SkSTArray<kPreallocGeomPoolStateStackCnt, GeometryPoolState, true>  fGeomPoolStateStack;
514    ResetTimestamp                                                      fResetTimestamp;
515    uint32_t                                                            fResetBits;
516    GrVertexBufferAllocPool*                                            fVertexPool;
517    GrIndexBufferAllocPool*                                             fIndexPool;
518    // counts number of uses of vertex/index pool in the geometry stack
519    int                                                                 fVertexPoolUseCnt;
520    int                                                                 fIndexPoolUseCnt;
521    // these are mutable so they can be created on-demand
522    mutable GrIndexBuffer*                                              fQuadIndexBuffer;
523
524    typedef GrDrawTarget INHERITED;
525};
526
527#endif
528