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