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