GrGpu.h revision ec00d94199fad7723b5987b86c1abef8ddafe2d8
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 "GrPipelineBuilder.h"
12#include "GrProgramDesc.h"
13#include "GrStencil.h"
14#include "GrXferProcessor.h"
15#include "SkPath.h"
16
17class GrBatchTracker;
18class GrContext;
19class GrGLContext;
20class GrIndexBuffer;
21class GrNonInstancedVertices;
22class GrPath;
23class GrPathRange;
24class GrPathRenderer;
25class GrPathRendererChain;
26class GrPathRendering;
27class GrPipeline;
28class GrPrimitiveProcessor;
29class GrRenderTarget;
30class GrStencilAttachment;
31class GrSurface;
32class GrTexture;
33class GrVertexBuffer;
34class GrVertices;
35
36class GrGpu : public SkRefCnt {
37public:
38    /**
39     * Create an instance of GrGpu that matches the specified backend. If the requested backend is
40     * not supported (at compile-time or run-time) this returns nullptr. The context will not be
41     * fully constructed and should not be used by GrGpu until after this function returns.
42     */
43    static GrGpu* Create(GrBackend, GrBackendContext, const GrContextOptions&, GrContext* context);
44
45    ////////////////////////////////////////////////////////////////////////////
46
47    GrGpu(GrContext* context);
48    ~GrGpu() override;
49
50    GrContext* getContext() { return fContext; }
51    const GrContext* getContext() const { return fContext; }
52
53    /**
54     * Gets the capabilities of the draw target.
55     */
56    const GrCaps* caps() const { return fCaps.get(); }
57
58    GrPathRendering* pathRendering() { return fPathRendering.get();  }
59
60    // Called by GrContext when the underlying backend context has been destroyed.
61    // GrGpu should use this to ensure that no backend API calls will be made from
62    // here onward, including in its destructor. Subclasses should call
63    // INHERITED::contextAbandoned() if they override this.
64    virtual void contextAbandoned();
65
66    /**
67     * The GrGpu object normally assumes that no outsider is setting state
68     * within the underlying 3D API's context/device/whatever. This call informs
69     * the GrGpu that the state was modified and it shouldn't make assumptions
70     * about the state.
71     */
72    void markContextDirty(uint32_t state = kAll_GrBackendState) { fResetBits |= state; }
73
74    /**
75     * Creates a texture object. If kRenderTarget_GrSurfaceFlag the texture can
76     * be used as a render target by calling GrTexture::asRenderTarget(). Not all
77     * pixel configs can be used as render targets. Support for configs as textures
78     * or render targets can be checked using GrCaps.
79     *
80     * @param desc        describes the texture to be created.
81     * @param budgeted    does this texture count against the resource cache budget?
82     * @param srcData     texel data to load texture. Begins with full-size
83     *                    palette data for paletted textures. For compressed
84     *                    formats it contains the compressed pixel data. Otherwise,
85     *                    it contains width*height texels. If nullptr texture data
86     *                    is uninitialized.
87     * @param rowBytes    the number of bytes between consecutive rows. Zero
88     *                    means rows are tightly packed. This field is ignored
89     *                    for compressed formats.
90     *
91     * @return    The texture object if successful, otherwise nullptr.
92     */
93    GrTexture* createTexture(const GrSurfaceDesc& desc, bool budgeted,
94                             const void* srcData, size_t rowBytes);
95
96    /**
97     * Implements GrContext::wrapBackendTexture
98     */
99    GrTexture* wrapBackendTexture(const GrBackendTextureDesc&, GrWrapOwnership);
100
101    /**
102     * Implements GrContext::wrapBackendTexture
103     */
104    GrRenderTarget* wrapBackendRenderTarget(const GrBackendRenderTargetDesc&, GrWrapOwnership);
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::map() or
112     *                GrVertexBuffer::updateData().
113     *
114     * @return    The vertex buffer if successful, otherwise nullptr.
115     */
116    GrVertexBuffer* createVertexBuffer(size_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::map() or
124     *                GrIndexBuffer::updateData().
125     *
126     * @return The index buffer if successful, otherwise nullptr.
127     */
128    GrIndexBuffer* createIndexBuffer(size_t size, bool dynamic);
129
130    /**
131     * Resolves MSAA.
132     */
133    void resolveRenderTarget(GrRenderTarget* target);
134
135    /** Info struct returned by getReadPixelsInfo about performing intermediate draws before
136        reading pixels for performance or correctness. */
137    struct ReadPixelTempDrawInfo {
138        /** If the GrGpu is requesting that the caller do a draw to an intermediate surface then
139            this is descriptor for the temp surface. The draw should always be a rect with
140            dst 0,0,w,h. */
141        GrSurfaceDesc   fTempSurfaceDesc;
142        /** Indicates whether there is a performance advantage to using an exact match texture
143            (in terms of width and height) for the intermediate texture instead of approximate. */
144        bool            fUseExactScratch;
145        /** The caller should swap the R and B channel in the temp draw and then instead of reading
146            the desired config back it should read GrPixelConfigSwapRAndB(readConfig). The swap
147            during the draw and the swap at readback time cancel and the client gets the correct
148            data. The swapped read back is either faster for or required by the underlying backend
149            3D API. */
150        bool            fSwapRAndB;
151    };
152    /** Describes why an intermediate draw must/should be performed before readPixels. */
153    enum DrawPreference {
154        /** On input means that the caller would proceed without draw if the GrGpu doesn't request
155            one.
156            On output means that the GrGpu is not requesting a draw. */
157        kNoDraw_DrawPreference,
158        /** Means that the client would prefer a draw for performance of the readback but
159            can satisfy a straight readPixels call on the inputs without an intermediate draw.
160            getReadPixelsInfo will never set the draw preference to this value but may leave
161            it set. */
162        kCallerPrefersDraw_DrawPreference,
163        /** On output means that GrGpu would prefer a draw for performance of the readback but
164            can satisfy a straight readPixels call on the inputs without an intermediate draw. The
165            caller of getReadPixelsInfo should never specify this on intput. */
166        kGpuPrefersDraw_DrawPreference,
167        /** On input means that the caller requires a draw to do a transformation and there is no
168            CPU fallback.
169            On output means that GrGpu can only satisfy the readPixels request if the intermediate
170            draw is performed.
171          */
172        kRequireDraw_DrawPreference
173    };
174
175    /**
176     * Used to negotiate whether and how an intermediate draw should or must be performed before
177     * a readPixels call. If this returns false then GrGpu could not deduce an intermediate draw
178     * that would allow a successful readPixels call. The passed width, height, and rowBytes,
179     * must be non-zero and already reflect clipping to the src bounds.
180     */
181    bool getReadPixelsInfo(GrSurface* srcSurface, int readWidth, int readHeight, size_t rowBytes,
182                           GrPixelConfig readConfig, DrawPreference*, ReadPixelTempDrawInfo*);
183
184    /** Info struct returned by getWritePixelsInfo about performing an intermediate draw in order
185        to write pixels to a GrSurface for either performance or correctness reasons. */
186    struct WritePixelTempDrawInfo {
187        /** If the GrGpu is requesting that the caller upload to an intermediate surface and draw
188            that to the dst then this is the descriptor for the intermediate surface. The caller
189            should upload the pixels such that the upper left pixel of the upload rect is at 0,0 in
190            the intermediate surface.*/
191        GrSurfaceDesc   fTempSurfaceDesc;
192        /** If set, fTempSurfaceDesc's config will be a R/B swap of the src pixel config. The caller
193            should upload the pixels as is such that R and B will be swapped in the intermediate
194            surface. When the intermediate is drawn to the dst the shader should swap R/B again
195            such that the correct swizzle results in the dst. This is done to work around either
196            performance or API restrictions in the backend 3D API implementation. */
197        bool            fSwapRAndB;
198    };
199
200    /**
201     * Used to negotiate whether and how an intermediate surface should be used to write pixels to
202     * a GrSurface. If this returns false then GrGpu could not deduce an intermediate draw
203     * that would allow a successful transfer of the src pixels to the dst. The passed width,
204     * height, and rowBytes, must be non-zero and already reflect clipping to the dst bounds.
205     */
206    bool getWritePixelsInfo(GrSurface* dstSurface, int width, int height, size_t rowBytes,
207                            GrPixelConfig srcConfig, DrawPreference*, WritePixelTempDrawInfo*);
208
209    /**
210     * Reads a rectangle of pixels from a render target.
211     *
212     * @param surface       The surface to read from
213     * @param left          left edge of the rectangle to read (inclusive)
214     * @param top           top edge of the rectangle to read (inclusive)
215     * @param width         width of rectangle to read in pixels.
216     * @param height        height of rectangle to read in pixels.
217     * @param config        the pixel config of the destination buffer
218     * @param buffer        memory to read the rectangle into.
219     * @param rowBytes      the number of bytes between consecutive rows. Zero
220     *                      means rows are tightly packed.
221     * @param invertY       buffer should be populated bottom-to-top as opposed
222     *                      to top-to-bottom (skia's usual order)
223     *
224     * @return true if the read succeeded, false if not. The read can fail
225     *              because of a unsupported pixel config or because no render
226     *              target is currently set.
227     */
228    bool readPixels(GrSurface* surface,
229                    int left, int top, int width, int height,
230                    GrPixelConfig config, void* buffer, size_t rowBytes);
231
232    /**
233     * Updates the pixels in a rectangle of a surface.
234     *
235     * @param surface       The surface to write to.
236     * @param left          left edge of the rectangle to write (inclusive)
237     * @param top           top edge of the rectangle to write (inclusive)
238     * @param width         width of rectangle to write in pixels.
239     * @param height        height of rectangle to write in pixels.
240     * @param config        the pixel config of the source buffer
241     * @param buffer        memory to read pixels from
242     * @param rowBytes      number of bytes between consecutive rows. Zero
243     *                      means rows are tightly packed.
244     */
245    bool writePixels(GrSurface* surface,
246                     int left, int top, int width, int height,
247                     GrPixelConfig config, const void* buffer,
248                     size_t rowBytes);
249
250    /**
251     * Clear the passed in render target. Ignores the draw state and clip.
252     */
253    void clear(const SkIRect& rect, GrColor color, GrRenderTarget* renderTarget);
254
255
256    void clearStencilClip(const SkIRect& rect, bool insideClip, GrRenderTarget* renderTarget);
257
258    /**
259     * Discards the contents render target. nullptr indicates that the current render target should
260     * be discarded.
261     **/
262    virtual void discard(GrRenderTarget* = nullptr) = 0;
263
264    /**
265     * This is can be called before allocating a texture to be a dst for copySurface. It will
266     * populate the origin, config, and flags fields of the desc such that copySurface can
267     * efficiently succeed. It should only succeed if it can allow copySurface to perform a copy
268     * that would be more effecient than drawing the src to a dst render target.
269     */
270    virtual bool initCopySurfaceDstDesc(const GrSurface* src, GrSurfaceDesc* desc) const = 0;
271
272    // After the client interacts directly with the 3D context state the GrGpu
273    // must resync its internal state and assumptions about 3D context state.
274    // Each time this occurs the GrGpu bumps a timestamp.
275    // state of the 3D context
276    // At 10 resets / frame and 60fps a 64bit timestamp will overflow in about
277    // a billion years.
278    typedef uint64_t ResetTimestamp;
279
280    // This timestamp is always older than the current timestamp
281    static const ResetTimestamp kExpiredTimestamp = 0;
282    // Returns a timestamp based on the number of times the context was reset.
283    // This timestamp can be used to lazily detect when cached 3D context state
284    // is dirty.
285    ResetTimestamp getResetTimestamp() const { return fResetTimestamp; }
286
287    virtual void buildProgramDesc(GrProgramDesc*,
288                                  const GrPrimitiveProcessor&,
289                                  const GrPipeline&) const = 0;
290
291    // Called to perform a surface to surface copy. Fallbacks to issuing a draw from the src to dst
292    // take place at the GrDrawTarget level and this function implement faster copy paths. The rect
293    // and point are pre-clipped. The src rect and implied dst rect are guaranteed to be within the
294    // src/dst bounds and non-empty.
295    bool copySurface(GrSurface* dst,
296                     GrSurface* src,
297                     const SkIRect& srcRect,
298                     const SkIPoint& dstPoint);
299
300    struct DrawArgs {
301        DrawArgs(const GrPrimitiveProcessor* primProc,
302                 const GrPipeline* pipeline,
303                 const GrProgramDesc* desc)
304            : fPrimitiveProcessor(primProc)
305            , fPipeline(pipeline)
306            , fDesc(desc) {
307            SkASSERT(primProc && pipeline && desc);
308        }
309        const GrPrimitiveProcessor* fPrimitiveProcessor;
310        const GrPipeline* fPipeline;
311        const GrProgramDesc* fDesc;
312    };
313
314    void draw(const DrawArgs&, const GrVertices&);
315
316    ///////////////////////////////////////////////////////////////////////////
317    // Debugging and Stats
318
319    class Stats {
320    public:
321#if GR_GPU_STATS
322        Stats() { this->reset(); }
323
324        void reset() {
325            fRenderTargetBinds = 0;
326            fShaderCompilations = 0;
327            fTextureCreates = 0;
328            fTextureUploads = 0;
329            fStencilAttachmentCreates = 0;
330            fNumDraws = 0;
331        }
332
333        int renderTargetBinds() const { return fRenderTargetBinds; }
334        void incRenderTargetBinds() { fRenderTargetBinds++; }
335        int shaderCompilations() const { return fShaderCompilations; }
336        void incShaderCompilations() { fShaderCompilations++; }
337        int textureCreates() const { return fTextureCreates; }
338        void incTextureCreates() { fTextureCreates++; }
339        int textureUploads() const { return fTextureUploads; }
340        void incTextureUploads() { fTextureUploads++; }
341        void incStencilAttachmentCreates() { fStencilAttachmentCreates++; }
342        void incNumDraws() { fNumDraws++; }
343        void dump(SkString*);
344
345    private:
346        int fRenderTargetBinds;
347        int fShaderCompilations;
348        int fTextureCreates;
349        int fTextureUploads;
350        int fStencilAttachmentCreates;
351        int fNumDraws;
352#else
353        void dump(SkString*) {};
354        void incRenderTargetBinds() {}
355        void incShaderCompilations() {}
356        void incTextureCreates() {}
357        void incTextureUploads() {}
358        void incStencilAttachmentCreates() {}
359        void incNumDraws() {}
360#endif
361    };
362
363    Stats* stats() { return &fStats; }
364
365    // creation and deletion of raw texture for testing
366    // only to be used in GPU-specific tests
367    virtual GrBackendObject createTestingOnlyBackendTexture(void* pixels, int w, int h,
368                                                            GrPixelConfig config) const = 0;
369    virtual bool isTestingOnlyBackendTexture(GrBackendObject id) const = 0;
370    virtual void deleteTestingOnlyBackendTexture(GrBackendObject id) const = 0;
371
372    // width and height may be larger than rt (if underlying API allows it).
373    // Returns nullptr if compatible sb could not be created, otherwise the caller owns the ref on
374    // the GrStencilAttachment.
375    virtual GrStencilAttachment* createStencilAttachmentForRenderTarget(const GrRenderTarget*,
376                                                                        int width,
377                                                                        int height) = 0;
378    // clears target's entire stencil buffer to 0
379    virtual void clearStencil(GrRenderTarget* target) = 0;
380
381    // This is only to be used in GL-specific tests.
382    virtual const GrGLContext* glContextForTesting() const { return nullptr; }
383
384protected:
385    // Functions used to map clip-respecting stencil tests into normal
386    // stencil funcs supported by GPUs.
387    static GrStencilFunc ConvertStencilFunc(bool stencilInClip,
388                                            GrStencilFunc func);
389    static void ConvertStencilFuncAndMask(GrStencilFunc func,
390                                          bool clipInStencil,
391                                          unsigned int clipBit,
392                                          unsigned int userBits,
393                                          unsigned int* ref,
394                                          unsigned int* mask);
395
396    static void ElevateDrawPreference(GrGpu::DrawPreference* preference,
397                                      GrGpu::DrawPreference elevation) {
398        GR_STATIC_ASSERT(GrGpu::kCallerPrefersDraw_DrawPreference > GrGpu::kNoDraw_DrawPreference);
399        GR_STATIC_ASSERT(GrGpu::kGpuPrefersDraw_DrawPreference >
400                         GrGpu::kCallerPrefersDraw_DrawPreference);
401        GR_STATIC_ASSERT(GrGpu::kRequireDraw_DrawPreference >
402                         GrGpu::kGpuPrefersDraw_DrawPreference);
403        *preference = SkTMax(*preference, elevation);
404    }
405
406    Stats                                   fStats;
407    SkAutoTDelete<GrPathRendering>          fPathRendering;
408    // Subclass must initialize this in its constructor.
409    SkAutoTUnref<const GrCaps>    fCaps;
410
411private:
412    // called when the 3D context state is unknown. Subclass should emit any
413    // assumed 3D context state and dirty any state cache.
414    virtual void onResetContext(uint32_t resetBits) = 0;
415
416    // Called before certain draws in order to guarantee coherent results from dst reads.
417    virtual void xferBarrier(GrRenderTarget*, GrXferBarrierType) = 0;
418
419    // overridden by backend-specific derived class to create objects.
420    // Texture size and sample size will have already been validated in base class before
421    // onCreateTexture/CompressedTexture are called.
422    virtual GrTexture* onCreateTexture(const GrSurfaceDesc& desc,
423                                       GrGpuResource::LifeCycle lifeCycle,
424                                       const void* srcData, size_t rowBytes) = 0;
425    virtual GrTexture* onCreateCompressedTexture(const GrSurfaceDesc& desc,
426                                                 GrGpuResource::LifeCycle lifeCycle,
427                                                 const void* srcData) = 0;
428    virtual GrTexture* onWrapBackendTexture(const GrBackendTextureDesc&, GrWrapOwnership) = 0;
429    virtual GrRenderTarget* onWrapBackendRenderTarget(const GrBackendRenderTargetDesc&,
430                                                      GrWrapOwnership) = 0;
431    virtual GrVertexBuffer* onCreateVertexBuffer(size_t size, bool dynamic) = 0;
432    virtual GrIndexBuffer* onCreateIndexBuffer(size_t size, bool dynamic) = 0;
433
434    // overridden by backend-specific derived class to perform the clear.
435    virtual void onClear(GrRenderTarget*, const SkIRect& rect, GrColor color) = 0;
436
437
438    // Overridden by backend specific classes to perform a clear of the stencil clip bits.  This is
439    // ONLY used by the the clip target
440    virtual void onClearStencilClip(GrRenderTarget*, const SkIRect& rect, bool insideClip) = 0;
441
442    // overridden by backend-specific derived class to perform the draw call.
443    virtual void onDraw(const DrawArgs&, const GrNonInstancedVertices&) = 0;
444
445    virtual bool onGetReadPixelsInfo(GrSurface* srcSurface, int readWidth, int readHeight,
446                                     size_t rowBytes, GrPixelConfig readConfig, DrawPreference*,
447                                     ReadPixelTempDrawInfo*) = 0;
448    virtual bool onGetWritePixelsInfo(GrSurface* dstSurface, int width, int height, size_t rowBytes,
449                                      GrPixelConfig srcConfig, DrawPreference*,
450                                      WritePixelTempDrawInfo*) = 0;
451
452    // overridden by backend-specific derived class to perform the surface read
453    virtual bool onReadPixels(GrSurface*,
454                              int left, int top,
455                              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 surface write
461    virtual bool onWritePixels(GrSurface*,
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    // overridden by backend specific derived class to perform the copy surface
470    virtual bool onCopySurface(GrSurface* dst,
471                               GrSurface* src,
472                               const SkIRect& srcRect,
473                               const SkIPoint& dstPoint) = 0;
474
475    void resetContext() {
476        this->onResetContext(fResetBits);
477        fResetBits = 0;
478        ++fResetTimestamp;
479    }
480
481    void handleDirtyContext() {
482        if (fResetBits) {
483            this->resetContext();
484        }
485    }
486
487    ResetTimestamp                                                      fResetTimestamp;
488    uint32_t                                                            fResetBits;
489    // The context owns us, not vice-versa, so this ptr is not ref'ed by Gpu.
490    GrContext*                                                          fContext;
491
492    friend class GrPathRendering;
493    typedef SkRefCnt INHERITED;
494};
495
496#endif
497