OpenGLRenderer.h revision 54be1cdf3d63095512120fa7ced5c16e462abffa
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/Functor.h>
31#include <utils/RefBase.h>
32#include <utils/Vector.h>
33
34#include "Debug.h"
35#include "Extensions.h"
36#include "Matrix.h"
37#include "Program.h"
38#include "Rect.h"
39#include "Snapshot.h"
40#include "Vertex.h"
41#include "SkiaShader.h"
42#include "SkiaColorFilter.h"
43#include "Caches.h"
44
45namespace android {
46namespace uirenderer {
47
48///////////////////////////////////////////////////////////////////////////////
49// Renderer
50///////////////////////////////////////////////////////////////////////////////
51
52class DisplayList;
53
54/**
55 * OpenGL renderer used to draw accelerated 2D graphics. The API is a
56 * simplified version of Skia's Canvas API.
57 */
58class OpenGLRenderer {
59public:
60    OpenGLRenderer();
61    virtual ~OpenGLRenderer();
62
63    virtual void setViewport(int width, int height);
64
65    void prepare(bool opaque);
66    virtual void prepareDirty(float left, float top, float right, float bottom, bool opaque);
67    virtual void finish();
68
69    // These two calls must not be recorded in display lists
70    virtual void interrupt();
71    virtual void resume();
72
73    virtual bool callDrawGLFunction(Functor *functor, Rect& dirty);
74
75    int getSaveCount() const;
76    virtual int save(int flags);
77    virtual void restore();
78    virtual void restoreToCount(int saveCount);
79
80    virtual int saveLayer(float left, float top, float right, float bottom,
81            SkPaint* p, int flags);
82    virtual int saveLayerAlpha(float left, float top, float right, float bottom,
83            int alpha, int flags);
84
85    virtual void translate(float dx, float dy);
86    virtual void rotate(float degrees);
87    virtual void scale(float sx, float sy);
88    virtual void skew(float sx, float sy);
89
90    const float* getMatrix() const;
91    void getMatrix(SkMatrix* matrix);
92    virtual void setMatrix(SkMatrix* matrix);
93    virtual void concatMatrix(SkMatrix* matrix);
94
95    const Rect& getClipBounds();
96    bool quickReject(float left, float top, float right, float bottom);
97    virtual bool clipRect(float left, float top, float right, float bottom, SkRegion::Op op);
98
99    virtual bool drawDisplayList(DisplayList* displayList, uint32_t width, uint32_t height,
100            Rect& dirty, uint32_t level = 0);
101    virtual void outputDisplayList(DisplayList* displayList, uint32_t level = 0);
102    virtual void drawLayer(Layer* layer, float x, float y, SkPaint* paint);
103    virtual void drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint);
104    virtual void drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint);
105    virtual void drawBitmap(SkBitmap* bitmap, float srcLeft, float srcTop,
106            float srcRight, float srcBottom, float dstLeft, float dstTop,
107            float dstRight, float dstBottom, SkPaint* paint);
108    virtual void drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight,
109            float* vertices, int* colors, SkPaint* paint);
110    virtual void drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
111            const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
112            float left, float top, float right, float bottom, SkPaint* paint);
113    virtual void drawColor(int color, SkXfermode::Mode mode);
114    virtual void drawRect(float left, float top, float right, float bottom, SkPaint* paint);
115    virtual void drawRoundRect(float left, float top, float right, float bottom,
116            float rx, float ry, SkPaint* paint);
117    virtual void drawCircle(float x, float y, float radius, SkPaint* paint);
118    virtual void drawOval(float left, float top, float right, float bottom, SkPaint* paint);
119    virtual void drawArc(float left, float top, float right, float bottom,
120            float startAngle, float sweepAngle, bool useCenter, SkPaint* paint);
121    virtual void drawPath(SkPath* path, SkPaint* paint);
122    virtual void drawLines(float* points, int count, SkPaint* paint);
123    virtual void drawPoints(float* points, int count, SkPaint* paint);
124    virtual void drawText(const char* text, int bytesCount, int count, float x, float y,
125            SkPaint* paint);
126
127    virtual void resetShader();
128    virtual void setupShader(SkiaShader* shader);
129
130    virtual void resetColorFilter();
131    virtual void setupColorFilter(SkiaColorFilter* filter);
132
133    virtual void resetShadow();
134    virtual void setupShadow(float radius, float dx, float dy, int color);
135
136protected:
137    /**
138     * Compose the layer defined in the current snapshot with the layer
139     * defined by the previous snapshot.
140     *
141     * The current snapshot *must* be a layer (flag kFlagIsLayer set.)
142     *
143     * @param curent The current snapshot containing the layer to compose
144     * @param previous The previous snapshot to compose the current layer with
145     */
146    virtual void composeLayer(sp<Snapshot> current, sp<Snapshot> previous);
147
148    /**
149     * Marks the specified region as dirty at the specified bounds.
150     */
151    void dirtyLayerUnchecked(Rect& bounds, Region* region);
152
153    /**
154     * Returns the current snapshot.
155     */
156    sp<Snapshot> getSnapshot() {
157        return mSnapshot;
158    }
159
160    /**
161     * Returns the region of the current layer.
162     */
163    virtual Region* getRegion() {
164        return mSnapshot->region;
165    }
166
167    /**
168     * Indicates whether rendering is currently targeted at a layer.
169     */
170    virtual bool hasLayer() {
171        return (mSnapshot->flags & Snapshot::kFlagFboTarget) && mSnapshot->region;
172    }
173
174    /**
175     * Returns the name of the FBO this renderer is rendering into.
176     */
177    virtual GLint getTargetFbo() {
178        return 0;
179    }
180
181private:
182    /**
183     * Saves the current state of the renderer as a new snapshot.
184     * The new snapshot is saved in mSnapshot and the previous snapshot
185     * is linked from mSnapshot->previous.
186     *
187     * @param flags The save flags; see SkCanvas for more information
188     *
189     * @return The new save count. This value can be passed to #restoreToCount()
190     */
191    int saveSnapshot(int flags);
192
193    /**
194     * Restores the current snapshot; mSnapshot becomes mSnapshot->previous.
195     *
196     * @return True if the clip was modified.
197     */
198    bool restoreSnapshot();
199
200    /**
201     * Sets the clipping rectangle using glScissor. The clip is defined by
202     * the current snapshot's clipRect member.
203     */
204    void setScissorFromClip();
205
206    /**
207     * Creates a new layer stored in the specified snapshot.
208     *
209     * @param snapshot The snapshot associated with the new layer
210     * @param left The left coordinate of the layer
211     * @param top The top coordinate of the layer
212     * @param right The right coordinate of the layer
213     * @param bottom The bottom coordinate of the layer
214     * @param alpha The translucency of the layer
215     * @param mode The blending mode of the layer
216     * @param flags The layer save flags
217     * @param previousFbo The name of the current framebuffer
218     *
219     * @return True if the layer was successfully created, false otherwise
220     */
221    bool createLayer(sp<Snapshot> snapshot, float left, float top, float right, float bottom,
222            int alpha, SkXfermode::Mode mode, int flags, GLuint previousFbo);
223
224    /**
225     * Creates a new layer stored in the specified snapshot as an FBO.
226     *
227     * @param layer The layer to store as an FBO
228     * @param snapshot The snapshot associated with the new layer
229     * @param bounds The bounds of the layer
230     * @param previousFbo The name of the current framebuffer
231     */
232    bool createFboLayer(Layer* layer, Rect& bounds, sp<Snapshot> snapshot,
233            GLuint previousFbo);
234
235    /**
236     * Compose the specified layer as a region.
237     *
238     * @param layer The layer to compose
239     * @param rect The layer's bounds
240     */
241    void composeLayerRegion(Layer* layer, const Rect& rect);
242
243    /**
244     * Compose the specified layer as a simple rectangle.
245     *
246     * @param layer The layer to compose
247     * @param rect The layer's bounds
248     * @param swap If true, the source and destination are swapped
249     */
250    void composeLayerRect(Layer* layer, const Rect& rect, bool swap = false);
251
252    /**
253     * Clears all the regions corresponding to the current list of layers.
254     * This method MUST be invoked before any drawing operation.
255     */
256    void clearLayerRegions();
257
258    /**
259     * Renders the specified layer as a textured quad.
260     *
261     * @param layer The layer to render
262     * @param rect The bounds of the layer
263     */
264    void drawTextureLayer(Layer* layer, const Rect& rect);
265
266    /**
267     * Mark the layer as dirty at the specified coordinates. The coordinates
268     * are transformed with the supplied matrix.
269     */
270    void dirtyLayer(const float left, const float top,
271            const float right, const float bottom, const mat4 transform);
272
273    /**
274     * Mark the layer as dirty at the specified coordinates.
275     */
276    void dirtyLayer(const float left, const float top,
277            const float right, const float bottom);
278
279    /**
280     * Draws a colored rectangle with the specified color. The specified coordinates
281     * are transformed by the current snapshot's transform matrix.
282     *
283     * @param left The left coordinate of the rectangle
284     * @param top The top coordinate of the rectangle
285     * @param right The right coordinate of the rectangle
286     * @param bottom The bottom coordinate of the rectangle
287     * @param color The rectangle's ARGB color, defined as a packed 32 bits word
288     * @param mode The Skia xfermode to use
289     * @param ignoreTransform True if the current transform should be ignored
290     * @param ignoreBlending True if the blending is set by the caller
291     */
292    void drawColorRect(float left, float top, float right, float bottom,
293            int color, SkXfermode::Mode mode, bool ignoreTransform = false);
294
295    /**
296     * Draws the shape represented by the specified path texture.
297     * This method invokes drawPathTexture() but takes into account
298     * the extra left/top offset and the texture offset to correctly
299     * position the final shape.
300     *
301     * @param left The left coordinate of the shape to render
302     * @param top The top coordinate of the shape to render
303     * @param texture The texture reprsenting the shape
304     * @param paint The paint to draw the shape with
305     */
306    void drawShape(float left, float top, const PathTexture* texture, SkPaint* paint);
307
308    /**
309     * Renders the rect defined by the specified bounds as a shape.
310     * This will render the rect using a path texture, which is used to render
311     * rects with stroke effects.
312     *
313     * @param left The left coordinate of the rect to draw
314     * @param top The top coordinate of the rect to draw
315     * @param right The right coordinate of the rect to draw
316     * @param bottom The bottom coordinate of the rect to draw
317     * @param p The paint to draw the rect with
318     */
319    void drawRectAsShape(float left, float top, float right, float bottom, SkPaint* p);
320
321    /**
322     * Draws the specified texture as an alpha bitmap. Alpha bitmaps obey
323     * different compositing rules.
324     *
325     * @param texture The texture to draw with
326     * @param left The x coordinate of the bitmap
327     * @param top The y coordinate of the bitmap
328     * @param paint The paint to render with
329     */
330    void drawAlphaBitmap(Texture* texture, float left, float top, SkPaint* paint);
331
332    /**
333     * Renders the rect defined by the specified bounds as an anti-aliased rect.
334     *
335     * @param left The left coordinate of the rect to draw
336     * @param top The top coordinate of the rect to draw
337     * @param right The right coordinate of the rect to draw
338     * @param bottom The bottom coordinate of the rect to draw
339     * @param color The color of the rect
340     * @param mode The blending mode to draw the rect
341     */
342    void drawAARect(float left, float top, float right, float bottom,
343            int color, SkXfermode::Mode mode);
344
345    /**
346     * Draws a textured rectangle with the specified texture. The specified coordinates
347     * are transformed by the current snapshot's transform matrix.
348     *
349     * @param left The left coordinate of the rectangle
350     * @param top The top coordinate of the rectangle
351     * @param right The right coordinate of the rectangle
352     * @param bottom The bottom coordinate of the rectangle
353     * @param texture The texture name to map onto the rectangle
354     * @param alpha An additional translucency parameter, between 0.0f and 1.0f
355     * @param mode The blending mode
356     * @param blend True if the texture contains an alpha channel
357     */
358    void drawTextureRect(float left, float top, float right, float bottom, GLuint texture,
359            float alpha, SkXfermode::Mode mode, bool blend);
360
361    /**
362     * Draws a textured rectangle with the specified texture. The specified coordinates
363     * are transformed by the current snapshot's transform matrix.
364     *
365     * @param left The left coordinate of the rectangle
366     * @param top The top coordinate of the rectangle
367     * @param right The right coordinate of the rectangle
368     * @param bottom The bottom coordinate of the rectangle
369     * @param texture The texture to use
370     * @param paint The paint containing the alpha, blending mode, etc.
371     */
372    void drawTextureRect(float left, float top, float right, float bottom,
373            Texture* texture, SkPaint* paint);
374
375    /**
376     * Draws a textured mesh with the specified texture. If the indices are omitted,
377     * the mesh is drawn as a simple quad. The mesh pointers become offsets when a
378     * VBO is bound.
379     *
380     * @param left The left coordinate of the rectangle
381     * @param top The top coordinate of the rectangle
382     * @param right The right coordinate of the rectangle
383     * @param bottom The bottom coordinate of the rectangle
384     * @param texture The texture name to map onto the rectangle
385     * @param alpha An additional translucency parameter, between 0.0f and 1.0f
386     * @param mode The blending mode
387     * @param blend True if the texture contains an alpha channel
388     * @param vertices The vertices that define the mesh
389     * @param texCoords The texture coordinates of each vertex
390     * @param elementsCount The number of elements in the mesh, required by indices
391     * @param swapSrcDst Whether or not the src and dst blending operations should be swapped
392     * @param ignoreTransform True if the current transform should be ignored
393     * @param vbo The VBO used to draw the mesh
394     * @param ignoreScale True if the model view matrix should not be scaled
395     * @param dirty True if calling this method should dirty the current layer
396     */
397    void drawTextureMesh(float left, float top, float right, float bottom, GLuint texture,
398            float alpha, SkXfermode::Mode mode, bool blend,
399            GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
400            bool swapSrcDst = false, bool ignoreTransform = false, GLuint vbo = 0,
401            bool ignoreScale = false, bool dirty = true);
402
403    /**
404     * Draws text underline and strike-through if needed.
405     *
406     * @param text The text to decor
407     * @param bytesCount The number of bytes in the text
408     * @param length The length in pixels of the text, can be <= 0.0f to force a measurement
409     * @param x The x coordinate where the text will be drawn
410     * @param y The y coordinate where the text will be drawn
411     * @param paint The paint to draw the text with
412     */
413    void drawTextDecorations(const char* text, int bytesCount, float length,
414            float x, float y, SkPaint* paint);
415
416    /**
417     * Draws a path texture. Path textures are alpha8 bitmaps that need special
418     * compositing to apply colors/filters/etc.
419     *
420     * @param texture The texture to render
421     * @param x The x coordinate where the texture will be drawn
422     * @param y The y coordinate where the texture will be drawn
423     * @param paint The paint to draw the texture with
424     */
425    void drawPathTexture(const PathTexture* texture, float x, float y, SkPaint* paint);
426
427    /**
428     * Resets the texture coordinates stored in mMeshVertices. Setting the values
429     * back to default is achieved by calling:
430     *
431     * resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
432     *
433     * @param u1 The left coordinate of the texture
434     * @param v1 The bottom coordinate of the texture
435     * @param u2 The right coordinate of the texture
436     * @param v2 The top coordinate of the texture
437     */
438    void resetDrawTextureTexCoords(float u1, float v1, float u2, float v2);
439
440    /**
441     * Gets the alpha and xfermode out of a paint object. If the paint is null
442     * alpha will be 255 and the xfermode will be SRC_OVER.
443     *
444     * @param paint The paint to extract values from
445     * @param alpha Where to store the resulting alpha
446     * @param mode Where to store the resulting xfermode
447     */
448    inline void getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode);
449
450    /**
451     * Binds the specified texture. The texture unit must have been selected
452     * prior to calling this method.
453     */
454    inline void bindTexture(GLuint texture) {
455        glBindTexture(GL_TEXTURE_2D, texture);
456    }
457
458    /**
459     * Binds the specified EGLImage texture. The texture unit must have been selected
460     * prior to calling this method.
461     */
462    inline void bindExternalTexture(GLuint texture) {
463        glBindTexture(GL_TEXTURE_EXTERNAL_OES, texture);
464    }
465
466    /**
467     * Sets the wrap modes for the specified texture. The wrap modes are modified
468     * only when needed.
469     */
470    inline void setTextureWrapModes(Texture* texture, GLenum wrapS, GLenum wrapT);
471
472    /**
473     * Enable or disable blending as necessary. This function sets the appropriate
474     * blend function based on the specified xfermode.
475     */
476    inline void chooseBlending(bool blend, SkXfermode::Mode mode, ProgramDescription& description,
477            bool swapSrcDst = false);
478
479    /**
480     * Safely retrieves the mode from the specified xfermode. If the specified
481     * xfermode is null, the mode is assumed to be SkXfermode::kSrcOver_Mode.
482     */
483    inline SkXfermode::Mode getXfermode(SkXfermode* mode);
484
485    /**
486     * Use the specified program with the current GL context. If the program is already
487     * in use, it will not be bound again. If it is not in use, the current program is
488     * marked unused and the specified program becomes used and becomes the new
489     * current program.
490     *
491     * @param program The program to use
492     *
493     * @return true If the specified program was already in use, false otherwise.
494     */
495    inline bool useProgram(Program* program);
496
497    /**
498     * Invoked before any drawing operation. This sets required state.
499     */
500    void setupDraw(bool clear = true);
501    /**
502     * Various methods to setup OpenGL rendering.
503     */
504    void setupDrawWithTexture(bool isAlpha8 = false);
505    void setupDrawWithExternalTexture();
506    void setupDrawAALine();
507    void setupDrawPoint(float pointSize);
508    void setupDrawColor(int color);
509    void setupDrawColor(int color, int alpha);
510    void setupDrawColor(float r, float g, float b, float a);
511    void setupDrawAlpha8Color(int color, int alpha);
512    void setupDrawAlpha8Color(float r, float g, float b, float a);
513    void setupDrawShader();
514    void setupDrawColorFilter();
515    void setupDrawBlending(SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode,
516            bool swapSrcDst = false);
517    void setupDrawBlending(bool blend = true, SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode,
518            bool swapSrcDst = false);
519    void setupDrawProgram();
520    void setupDrawDirtyRegionsDisabled();
521    void setupDrawModelViewIdentity(bool offset = false);
522    void setupDrawModelView(float left, float top, float right, float bottom,
523            bool ignoreTransform = false, bool ignoreModelView = false);
524    void setupDrawModelViewTranslate(float left, float top, float right, float bottom,
525            bool ignoreTransform = false);
526    void setupDrawPointUniforms();
527    void setupDrawColorUniforms();
528    void setupDrawPureColorUniforms();
529    void setupDrawShaderIdentityUniforms();
530    void setupDrawShaderUniforms(bool ignoreTransform = false);
531    void setupDrawColorFilterUniforms();
532    void setupDrawSimpleMesh();
533    void setupDrawTexture(GLuint texture);
534    void setupDrawExternalTexture(GLuint texture);
535    void setupDrawTextureTransform();
536    void setupDrawTextureTransformUniforms(mat4& transform);
537    void setupDrawMesh(GLvoid* vertices, GLvoid* texCoords = NULL, GLuint vbo = 0);
538    void setupDrawVertices(GLvoid* vertices);
539    void setupDrawAALine(GLvoid* vertices, GLvoid* distanceCoords, GLvoid* lengthCoords,
540            float strokeWidth);
541    void finishDrawTexture();
542    void accountForClear(SkXfermode::Mode mode);
543
544    void drawRegionRects(const Region& region);
545
546    /**
547     * Should be invoked every time the glScissor is modified.
548     */
549    inline void dirtyClip() {
550        mDirtyClip = true;
551    }
552
553    // Dimensions of the drawing surface
554    int mWidth, mHeight;
555
556    // Matrix used for ortho projection in shaders
557    mat4 mOrthoMatrix;
558
559    // Model-view matrix used to position/size objects
560    mat4 mModelView;
561
562    // Number of saved states
563    int mSaveCount;
564    // Base state
565    sp<Snapshot> mFirstSnapshot;
566    // Current state
567    sp<Snapshot> mSnapshot;
568
569    // Shaders
570    SkiaShader* mShader;
571
572    // Color filters
573    SkiaColorFilter* mColorFilter;
574
575    // Used to draw textured quads
576    TextureVertex mMeshVertices[4];
577
578    // Drop shadow
579    bool mHasShadow;
580    float mShadowRadius;
581    float mShadowDx;
582    float mShadowDy;
583    int mShadowColor;
584
585    // Various caches
586    Caches& mCaches;
587
588    // List of rectagnles to clear after saveLayer() is invoked
589    Vector<Rect*> mLayers;
590
591    // Indentity matrix
592    const mat4 mIdentity;
593
594    // Indicates whether the clip must be restored
595    bool mDirtyClip;
596
597    // The following fields are used to setup drawing
598    // Used to describe the shaders to generate
599    ProgramDescription mDescription;
600    // Color description
601    bool mColorSet;
602    float mColorA, mColorR, mColorG, mColorB;
603    // Indicates that the shader should get a color
604    bool mSetShaderColor;
605    // Current texture unit
606    GLuint mTextureUnit;
607    // Track dirty regions, true by default
608    bool mTrackDirtyRegions;
609    // Texture coordinates slot
610    int mTexCoordsSlot;
611
612    friend class DisplayListRenderer;
613
614}; // class OpenGLRenderer
615
616}; // namespace uirenderer
617}; // namespace android
618
619#endif // ANDROID_HWUI_OPENGL_RENDERER_H
620