OpenGLRenderer.h revision 0fe478ea04720a57ef3919dbc23711bc7eba517f
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_HWUI_OPENGL_RENDERER_H
18#define ANDROID_HWUI_OPENGL_RENDERER_H
19
20#include <GLES2/gl2.h>
21#include <GLES2/gl2ext.h>
22
23#include <SkBitmap.h>
24#include <SkMatrix.h>
25#include <SkPaint.h>
26#include <SkRegion.h>
27#include <SkShader.h>
28#include <SkXfermode.h>
29
30#include <utils/RefBase.h>
31#include <utils/Vector.h>
32
33#include "Extensions.h"
34#include "Matrix.h"
35#include "Program.h"
36#include "Rect.h"
37#include "Snapshot.h"
38#include "Vertex.h"
39#include "SkiaShader.h"
40#include "SkiaColorFilter.h"
41#include "Caches.h"
42
43namespace android {
44namespace uirenderer {
45
46///////////////////////////////////////////////////////////////////////////////
47// Defines
48///////////////////////////////////////////////////////////////////////////////
49
50// Debug
51#define DEBUG_OPENGL 1
52
53// If turned on, layers drawn inside FBOs are optimized with regions
54#define RENDER_LAYERS_AS_REGIONS 0
55#define DEBUG_LAYERS_AS_REGIONS 0
56
57///////////////////////////////////////////////////////////////////////////////
58// Renderer
59///////////////////////////////////////////////////////////////////////////////
60
61class DisplayList;
62
63/**
64 * OpenGL renderer used to draw accelerated 2D graphics. The API is a
65 * simplified version of Skia's Canvas API.
66 */
67class OpenGLRenderer {
68public:
69    OpenGLRenderer();
70    virtual ~OpenGLRenderer();
71
72    virtual void setViewport(int width, int height);
73
74    virtual void prepare(bool opaque);
75    virtual void finish();
76
77    virtual void acquireContext();
78    virtual void releaseContext();
79
80    int getSaveCount() const;
81    virtual int save(int flags);
82    virtual void restore();
83    virtual void restoreToCount(int saveCount);
84
85    virtual int saveLayer(float left, float top, float right, float bottom,
86            SkPaint* p, int flags);
87    virtual int saveLayerAlpha(float left, float top, float right, float bottom,
88            int alpha, int flags);
89
90    virtual void translate(float dx, float dy);
91    virtual void rotate(float degrees);
92    virtual void scale(float sx, float sy);
93
94    const float* getMatrix() const;
95    void getMatrix(SkMatrix* matrix);
96    virtual void setMatrix(SkMatrix* matrix);
97    virtual void concatMatrix(SkMatrix* matrix);
98
99    const Rect& getClipBounds();
100    bool quickReject(float left, float top, float right, float bottom);
101    virtual bool clipRect(float left, float top, float right, float bottom, SkRegion::Op op);
102
103    virtual void drawDisplayList(DisplayList* displayList);
104    virtual void drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint);
105    virtual void drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint);
106    virtual void drawBitmap(SkBitmap* bitmap, float srcLeft, float srcTop,
107            float srcRight, float srcBottom, float dstLeft, float dstTop,
108            float dstRight, float dstBottom, SkPaint* paint);
109    virtual void drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
110            const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
111            float left, float top, float right, float bottom, SkPaint* paint);
112    virtual void drawColor(int color, SkXfermode::Mode mode);
113    virtual void drawRect(float left, float top, float right, float bottom, SkPaint* paint);
114    virtual void drawPath(SkPath* path, SkPaint* paint);
115    virtual void drawLines(float* points, int count, SkPaint* paint);
116    virtual void drawText(const char* text, int bytesCount, int count, float x, float y,
117            SkPaint* paint);
118
119    virtual void resetShader();
120    virtual void setupShader(SkiaShader* shader);
121
122    virtual void resetColorFilter();
123    virtual void setupColorFilter(SkiaColorFilter* filter);
124
125    virtual void resetShadow();
126    virtual void setupShadow(float radius, float dx, float dy, int color);
127
128protected:
129    /**
130     * Compose the layer defined in the current snapshot with the layer
131     * defined by the previous snapshot.
132     *
133     * The current snapshot *must* be a layer (flag kFlagIsLayer set.)
134     *
135     * @param curent The current snapshot containing the layer to compose
136     * @param previous The previous snapshot to compose the current layer with
137     */
138    virtual void composeLayer(sp<Snapshot> current, sp<Snapshot> previous);
139
140private:
141    /**
142     * Saves the current state of the renderer as a new snapshot.
143     * The new snapshot is saved in mSnapshot and the previous snapshot
144     * is linked from mSnapshot->previous.
145     *
146     * @param flags The save flags; see SkCanvas for more information
147     *
148     * @return The new save count. This value can be passed to #restoreToCount()
149     */
150    int saveSnapshot(int flags);
151
152    /**
153     * Restores the current snapshot; mSnapshot becomes mSnapshot->previous.
154     *
155     * @return True if the clip was modified.
156     */
157    bool restoreSnapshot();
158
159    /**
160     * Sets the clipping rectangle using glScissor. The clip is defined by
161     * the current snapshot's clipRect member.
162     */
163    void setScissorFromClip();
164
165    /**
166     * Creates a new layer stored in the specified snapshot.
167     *
168     * @param snapshot The snapshot associated with the new layer
169     * @param left The left coordinate of the layer
170     * @param top The top coordinate of the layer
171     * @param right The right coordinate of the layer
172     * @param bottom The bottom coordinate of the layer
173     * @param alpha The translucency of the layer
174     * @param mode The blending mode of the layer
175     * @param flags The layer save flags
176     * @param previousFbo The name of the current framebuffer
177     *
178     * @return True if the layer was successfully created, false otherwise
179     */
180    bool createLayer(sp<Snapshot> snapshot, float left, float top, float right, float bottom,
181            int alpha, SkXfermode::Mode mode, int flags, GLuint previousFbo);
182
183    /**
184     * Creates a new layer stored in the specified snapshot as an FBO.
185     *
186     * @param layer The layer to store as an FBO
187     * @param snapshot The snapshot associated with the new layer
188     * @param bounds The bounds of the layer
189     * @param previousFbo The name of the current framebuffer
190     */
191    bool createFboLayer(Layer* layer, Rect& bounds, sp<Snapshot> snapshot,
192            GLuint previousFbo);
193
194    /**
195     * Compose the specified layer as a region.
196     *
197     * @param layer The layer to compose
198     * @param rect The layer's bounds
199     */
200    void composeLayerRegion(Layer* layer, const Rect& rect);
201
202    /**
203     * Compose the specified layer as a simple rectangle.
204     *
205     * @param layer The layer to compose
206     * @param rect The layer's bounds
207     * @param swap If true, the source and destination are swapped
208     */
209    void composeLayerRect(Layer* layer, const Rect& rect, bool swap = false);
210
211    /**
212     * Clears all the regions corresponding to the current list of layers.
213     * This method MUST be invoked before any drawing operation.
214     */
215    void clearLayerRegions();
216
217    /**
218     * Draws a colored rectangle with the specified color. The specified coordinates
219     * are transformed by the current snapshot's transform matrix.
220     *
221     * @param left The left coordinate of the rectangle
222     * @param top The top coordinate of the rectangle
223     * @param right The right coordinate of the rectangle
224     * @param bottom The bottom coordinate of the rectangle
225     * @param color The rectangle's ARGB color, defined as a packed 32 bits word
226     * @param mode The Skia xfermode to use
227     * @param ignoreTransform True if the current transform should be ignored
228     * @param ignoreBlending True if the blending is set by the caller
229     */
230    void drawColorRect(float left, float top, float right, float bottom,
231            int color, SkXfermode::Mode mode, bool ignoreTransform = false);
232
233    /**
234     * Setups shaders to draw a colored rect.
235     */
236    void setupColorRect(float left, float top, float right, float bottom,
237            float r, float g, float b, float a, SkXfermode::Mode mode,
238            bool ignoreTransform, bool ignoreMatrix = false);
239
240    /**
241     * Draws a textured rectangle with the specified texture. The specified coordinates
242     * are transformed by the current snapshot's transform matrix.
243     *
244     * @param left The left coordinate of the rectangle
245     * @param top The top coordinate of the rectangle
246     * @param right The right coordinate of the rectangle
247     * @param bottom The bottom coordinate of the rectangle
248     * @param texture The texture name to map onto the rectangle
249     * @param alpha An additional translucency parameter, between 0.0f and 1.0f
250     * @param mode The blending mode
251     * @param blend True if the texture contains an alpha channel
252     */
253    void drawTextureRect(float left, float top, float right, float bottom, GLuint texture,
254            float alpha, SkXfermode::Mode mode, bool blend);
255
256    /**
257     * Draws a textured rectangle with the specified texture. The specified coordinates
258     * are transformed by the current snapshot's transform matrix.
259     *
260     * @param left The left coordinate of the rectangle
261     * @param top The top coordinate of the rectangle
262     * @param right The right coordinate of the rectangle
263     * @param bottom The bottom coordinate of the rectangle
264     * @param texture The texture to use
265     * @param paint The paint containing the alpha, blending mode, etc.
266     */
267    void drawTextureRect(float left, float top, float right, float bottom,
268            Texture* texture, SkPaint* paint);
269
270    /**
271     * Draws a textured mesh with the specified texture. If the indices are omitted,
272     * the mesh is drawn as a simple quad. The mesh pointers become offsets when a
273     * VBO is bound.
274     *
275     * @param left The left coordinate of the rectangle
276     * @param top The top coordinate of the rectangle
277     * @param right The right coordinate of the rectangle
278     * @param bottom The bottom coordinate of the rectangle
279     * @param texture The texture name to map onto the rectangle
280     * @param alpha An additional translucency parameter, between 0.0f and 1.0f
281     * @param mode The blending mode
282     * @param blend True if the texture contains an alpha channel
283     * @param vertices The vertices that define the mesh
284     * @param texCoords The texture coordinates of each vertex
285     * @param elementsCount The number of elements in the mesh, required by indices
286     * @param swapSrcDst Whether or not the src and dst blending operations should be swapped
287     * @param ignoreTransform True if the current transform should be ignored
288     * @param vbo The VBO used to draw the mesh
289     * @param ignoreScale True if the model view matrix should not be scaled
290     * @param dirty True if calling this method should dirty the current layer
291     */
292    void drawTextureMesh(float left, float top, float right, float bottom, GLuint texture,
293            float alpha, SkXfermode::Mode mode, bool blend,
294            GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
295            bool swapSrcDst = false, bool ignoreTransform = false, GLuint vbo = 0,
296            bool ignoreScale = false, bool dirty = true);
297
298    /**
299     * Prepares the renderer to draw the specified shadow. The active texture
300     * unit must be 0 and the other units must be unbound.
301     *
302     * @param texture The shadow texture
303     * @param x The x coordinate of the shadow
304     * @param y The y coordinate of the shadow
305     * @param mode The blending mode
306     * @param alpha The alpha value
307     */
308    void setupShadow(const ShadowTexture* texture, float x, float y, SkXfermode::Mode mode,
309            float alpha);
310
311    /**
312     * Prepares the renderer to draw the specified Alpha8 texture as a rectangle.
313     *
314     * @param texture The texture to render with
315     * @param textureUnit The texture unit to use, may be modified
316     * @param x The x coordinate of the rectangle to draw
317     * @param y The y coordinate of the rectangle to draw
318     * @param r The red component of the color
319     * @param g The green component of the color
320     * @param b The blue component of the color
321     * @param a The alpha component of the color
322     * @param mode The blending mode
323     * @param transforms True if the matrix passed to the shader should be multiplied
324     *        by the model-view matrix
325     * @param applyFilters Whether or not to take color filters and
326     *        shaders into account
327     */
328    void setupTextureAlpha8(const Texture* texture, GLuint& textureUnit, float x, float y,
329            float r, float g, float b, float a, SkXfermode::Mode mode, bool transforms,
330            bool applyFilters);
331
332    /**
333     * Prepares the renderer to draw the specified Alpha8 texture as a rectangle.
334     *
335     * @param texture The texture to render with
336     * @param width The width of the texture
337     * @param height The height of the texture
338     * @param textureUnit The texture unit to use, may be modified
339     * @param x The x coordinate of the rectangle to draw
340     * @param y The y coordinate of the rectangle to draw
341     * @param r The red component of the color
342     * @param g The green component of the color
343     * @param b The blue component of the color
344     * @param a The alpha component of the color
345     * @param mode The blending mode
346     * @param transforms True if the matrix passed to the shader should be multiplied
347     *        by the model-view matrix
348     * @param applyFilters Whether or not to take color filters and
349     *        shaders into account
350     */
351    void setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height,
352            GLuint& textureUnit, float x, float y, float r, float g, float b, float a,
353            SkXfermode::Mode mode, bool transforms, bool applyFilters);
354
355    /**
356     * Same as above setupTextureAlpha8() but specifies the mesh's vertices
357     * and texCoords pointers. The pointers become offsets when a VBO is bound.
358     */
359    void setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height,
360            GLuint& textureUnit, float x, float y, float r, float g, float b, float a,
361            SkXfermode::Mode mode, bool transforms, bool applyFilters,
362            GLvoid* vertices, GLvoid* texCoords, GLuint vbo = 0);
363
364    /**
365     * Draws text underline and strike-through if needed.
366     *
367     * @param text The text to decor
368     * @param bytesCount The number of bytes in the text
369     * @param length The length in pixels of the text, can be <= 0.0f to force a measurement
370     * @param x The x coordinate where the text will be drawn
371     * @param y The y coordinate where the text will be drawn
372     * @param paint The paint to draw the text with
373     */
374    void drawTextDecorations(const char* text, int bytesCount, float length,
375            float x, float y, SkPaint* paint);
376
377    /**
378     * Resets the texture coordinates stored in mMeshVertices. Setting the values
379     * back to default is achieved by calling:
380     *
381     * resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
382     *
383     * @param u1 The left coordinate of the texture
384     * @param v1 The bottom coordinate of the texture
385     * @param u2 The right coordinate of the texture
386     * @param v2 The top coordinate of the texture
387     */
388    void resetDrawTextureTexCoords(float u1, float v1, float u2, float v2);
389
390    /**
391     * Gets the alpha and xfermode out of a paint object. If the paint is null
392     * alpha will be 255 and the xfermode will be SRC_OVER.
393     *
394     * @param paint The paint to extract values from
395     * @param alpha Where to store the resulting alpha
396     * @param mode Where to store the resulting xfermode
397     */
398    inline void getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode);
399
400    /**
401     * Binds the specified texture. The texture unit must have been selected
402     * prior to calling this method.
403     */
404    inline void bindTexture(GLuint texture) {
405        glBindTexture(GL_TEXTURE_2D, texture);
406    }
407
408    /**
409     * Sets the wrap modes for the specified texture. The wrap modes are modified
410     * only when needed.
411     */
412    inline void setTextureWrapModes(Texture* texture, GLenum wrapS, GLenum wrapT);
413
414    /**
415     * Enable or disable blending as necessary. This function sets the appropriate
416     * blend function based on the specified xfermode.
417     */
418    inline void chooseBlending(bool blend, SkXfermode::Mode mode, ProgramDescription& description,
419            bool swapSrcDst = false);
420
421    /**
422     * Safely retrieves the mode from the specified xfermode. If the specified
423     * xfermode is null, the mode is assumed to be SkXfermode::kSrcOver_Mode.
424     */
425    inline SkXfermode::Mode getXfermode(SkXfermode* mode);
426
427    /**
428     * Use the specified program with the current GL context. If the program is already
429     * in use, it will not be bound again. If it is not in use, the current program is
430     * marked unused and the specified program becomes used and becomes the new
431     * current program.
432     *
433     * @param program The program to use
434     *
435     * @return true If the specified program was already in use, false otherwise.
436     */
437    inline bool useProgram(Program* program);
438
439    /**
440     * Invoked before any drawing operation. This sets required state.
441     */
442    void setupDraw();
443
444    /**
445     * Should be invoked every time the glScissor is modified.
446     */
447    inline void dirtyClip() {
448        mDirtyClip = true;
449    }
450
451    /**
452     * Mark the layer as dirty at the specified coordinates. The coordinates
453     * are transformed with the supplied matrix.
454     */
455    void dirtyLayer(const float left, const float top, const float right, const float bottom,
456            const mat4 transform);
457
458    /**
459     * Mark the layer as dirty at the specified coordinates.
460     */
461    void dirtyLayer(const float left, const float top, const float right, const float bottom);
462
463    // Dimensions of the drawing surface
464    int mWidth, mHeight;
465
466    // Matrix used for ortho projection in shaders
467    mat4 mOrthoMatrix;
468
469    // Model-view matrix used to position/size objects
470    mat4 mModelView;
471
472    // Number of saved states
473    int mSaveCount;
474    // Base state
475    sp<Snapshot> mFirstSnapshot;
476    // Current state
477    sp<Snapshot> mSnapshot;
478
479    // Shaders
480    SkiaShader* mShader;
481
482    // Color filters
483    SkiaColorFilter* mColorFilter;
484
485    // Used to draw textured quads
486    TextureVertex mMeshVertices[4];
487
488    // Drop shadow
489    bool mHasShadow;
490    float mShadowRadius;
491    float mShadowDx;
492    float mShadowDy;
493    int mShadowColor;
494
495    // Various caches
496    Caches& mCaches;
497
498    // List of rectangles to clear due to calls to saveLayer()
499    Vector<Rect*> mLayers;
500
501    // Indentity matrix
502    const mat4 mIdentity;
503
504    // Indicates whether the clip must be restored
505    bool mDirtyClip;
506
507    friend class DisplayListRenderer;
508
509}; // class OpenGLRenderer
510
511}; // namespace uirenderer
512}; // namespace android
513
514#endif // ANDROID_HWUI_OPENGL_RENDERER_H
515