OpenGLRenderer.h revision 024433f89684e1f9cb7b15ade7c480c9346fbe4d
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 <SkCanvas.h>
25#include <SkColorFilter.h>
26#include <SkMatrix.h>
27#include <SkPaint.h>
28#include <SkRegion.h>
29#include <SkShader.h>
30#include <SkXfermode.h>
31
32#include <utils/Functor.h>
33#include <utils/RefBase.h>
34#include <utils/SortedVector.h>
35#include <utils/Vector.h>
36
37#include <cutils/compiler.h>
38
39#include <androidfw/ResourceTypes.h>
40
41#include "Debug.h"
42#include "Extensions.h"
43#include "Matrix.h"
44#include "Program.h"
45#include "Rect.h"
46#include "Renderer.h"
47#include "StatefulBaseRenderer.h"
48#include "Snapshot.h"
49#include "UvMapper.h"
50#include "Vertex.h"
51#include "Caches.h"
52
53namespace android {
54namespace uirenderer {
55
56class DeferredDisplayState;
57class RenderNode;
58class TextSetupFunctor;
59class VertexBuffer;
60class SkiaShader;
61
62struct DrawModifiers {
63    DrawModifiers() {
64        reset();
65    }
66
67    void reset() {
68        memset(this, 0, sizeof(DrawModifiers));
69    }
70
71    SkiaShader* mShader;
72    float mOverrideLayerAlpha;
73
74    // Drop shadow
75    bool mHasShadow;
76    float mShadowRadius;
77    float mShadowDx;
78    float mShadowDy;
79    int mShadowColor;
80
81    // Draw filters
82    bool mHasDrawFilter;
83    int mPaintFilterClearBits;
84    int mPaintFilterSetBits;
85};
86
87enum StateDeferFlags {
88    kStateDeferFlag_Draw = 0x1,
89    kStateDeferFlag_Clip = 0x2
90};
91
92enum ClipSideFlags {
93    kClipSide_None = 0x0,
94    kClipSide_Left = 0x1,
95    kClipSide_Top = 0x2,
96    kClipSide_Right = 0x4,
97    kClipSide_Bottom = 0x8,
98    kClipSide_Full = 0xF,
99    kClipSide_ConservativeFull = 0x1F
100};
101
102/**
103 * Defines additional transformation that should be applied by the model view matrix, beyond that of
104 * the currentTransform()
105 */
106enum ModelViewMode {
107    /**
108     * Used when the model view should simply translate geometry passed to the shader. The resulting
109     * matrix will be a simple translation.
110     */
111    kModelViewMode_Translate = 0,
112
113    /**
114     * Used when the model view should translate and scale geometry. The resulting matrix will be a
115     * translation + scale. This is frequently used together with VBO 0, the (0,0,1,1) rect.
116     */
117    kModelViewMode_TranslateAndScale = 1,
118};
119
120enum VertexBufferMode {
121    kVertexBufferMode_Standard = 0,
122    kVertexBufferMode_OnePolyRingShadow = 1,
123    kVertexBufferMode_TwoPolyRingShadow = 2
124};
125
126///////////////////////////////////////////////////////////////////////////////
127// Renderer
128///////////////////////////////////////////////////////////////////////////////
129/**
130 * OpenGL Renderer implementation.
131 */
132class OpenGLRenderer : public StatefulBaseRenderer {
133public:
134    ANDROID_API OpenGLRenderer();
135    virtual ~OpenGLRenderer();
136
137    ANDROID_API void initProperties();
138
139    virtual void setViewport(int width, int height);
140    virtual status_t prepareDirty(float left, float top, float right, float bottom, bool opaque);
141    virtual void finish();
142    virtual void interrupt();
143    virtual void resume();
144
145    ANDROID_API void setCountOverdrawEnabled(bool enabled) {
146        mCountOverdraw = enabled;
147    }
148
149    ANDROID_API float getOverdraw() {
150        return mCountOverdraw ? mOverdraw : 0.0f;
151    }
152
153    ANDROID_API status_t invokeFunctors(Rect& dirty);
154    ANDROID_API void detachFunctor(Functor* functor);
155    ANDROID_API void attachFunctor(Functor* functor);
156    virtual status_t callDrawGLFunction(Functor* functor, Rect& dirty);
157
158    ANDROID_API void pushLayerUpdate(Layer* layer);
159    ANDROID_API void cancelLayerUpdate(Layer* layer);
160    ANDROID_API void clearLayerUpdates();
161    ANDROID_API void flushLayerUpdates();
162
163    ANDROID_API virtual int saveLayer(float left, float top, float right, float bottom,
164            const SkPaint* paint, int flags);
165
166    int saveLayerDeferred(float left, float top, float right, float bottom,
167            const SkPaint* paint, int flags);
168
169    virtual status_t drawDisplayList(RenderNode* displayList, Rect& dirty, int32_t replayFlags = 1);
170    virtual status_t drawLayer(Layer* layer, float x, float y);
171    virtual status_t drawBitmap(const SkBitmap* bitmap, float left, float top,
172            const SkPaint* paint);
173    status_t drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry, int bitmapCount,
174            TextureVertex* vertices, bool pureTranslate, const Rect& bounds, const SkPaint* paint);
175    virtual status_t drawBitmap(const SkBitmap* bitmap, const SkMatrix* matrix,
176            const SkPaint* paint);
177    virtual status_t drawBitmap(const SkBitmap* bitmap, float srcLeft, float srcTop,
178            float srcRight, float srcBottom, float dstLeft, float dstTop,
179            float dstRight, float dstBottom, const SkPaint* paint);
180    virtual status_t drawBitmapData(const SkBitmap* bitmap, float left, float top,
181            const SkPaint* paint);
182    virtual status_t drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight,
183            const float* vertices, const int* colors, const SkPaint* paint);
184    status_t drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
185            TextureVertex* vertices, uint32_t indexCount, const SkPaint* paint);
186    virtual status_t drawPatch(const SkBitmap* bitmap, const Res_png_9patch* patch,
187            float left, float top, float right, float bottom, const SkPaint* paint);
188    status_t drawPatch(const SkBitmap* bitmap, const Patch* mesh, AssetAtlas::Entry* entry,
189            float left, float top, float right, float bottom, const SkPaint* paint);
190    virtual status_t drawColor(int color, SkXfermode::Mode mode);
191    virtual status_t drawRect(float left, float top, float right, float bottom,
192            const SkPaint* paint);
193    virtual status_t drawRoundRect(float left, float top, float right, float bottom,
194            float rx, float ry, const SkPaint* paint);
195    virtual status_t drawCircle(float x, float y, float radius, const SkPaint* paint);
196    virtual status_t drawOval(float left, float top, float right, float bottom,
197            const SkPaint* paint);
198    virtual status_t drawArc(float left, float top, float right, float bottom,
199            float startAngle, float sweepAngle, bool useCenter, const SkPaint* paint);
200    virtual status_t drawPath(const SkPath* path, const SkPaint* paint);
201    virtual status_t drawLines(const float* points, int count, const SkPaint* paint);
202    virtual status_t drawPoints(const float* points, int count, const SkPaint* paint);
203    virtual status_t drawTextOnPath(const char* text, int bytesCount, int count, const SkPath* path,
204            float hOffset, float vOffset, const SkPaint* paint);
205    virtual status_t drawPosText(const char* text, int bytesCount, int count,
206            const float* positions, const SkPaint* paint);
207    virtual status_t drawText(const char* text, int bytesCount, int count, float x, float y,
208            const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds,
209            DrawOpMode drawOpMode = kDrawOpMode_Immediate);
210    virtual status_t drawRects(const float* rects, int count, const SkPaint* paint);
211
212    status_t drawShadow(const mat4& casterTransformXY, const mat4& casterTransformZ,
213            float casterAlpha, bool casterUnclipped, const SkPath* casterPerimeter);
214
215    virtual void resetShader();
216    virtual void setupShader(SkiaShader* shader);
217
218    virtual void resetShadow();
219    virtual void setupShadow(float radius, float dx, float dy, int color);
220
221    virtual void resetPaintFilter();
222    virtual void setupPaintFilter(int clearBits, int setBits);
223
224    // If this value is set to < 1.0, it overrides alpha set on layer (see drawBitmap, drawLayer)
225    void setOverrideLayerAlpha(float alpha) { mDrawModifiers.mOverrideLayerAlpha = alpha; }
226
227    const SkPaint* filterPaint(const SkPaint* paint);
228
229    /**
230     * Store the current display state (most importantly, the current clip and transform), and
231     * additionally map the state's bounds from local to window coordinates.
232     *
233     * Returns true if quick-rejected
234     */
235    bool storeDisplayState(DeferredDisplayState& state, int stateDeferFlags);
236    void restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore = false);
237    void setupMergedMultiDraw(const Rect* clipRect);
238
239    const DrawModifiers& getDrawModifiers() { return mDrawModifiers; }
240    void setDrawModifiers(const DrawModifiers& drawModifiers) { mDrawModifiers = drawModifiers; }
241
242    ANDROID_API bool isCurrentTransformSimple() {
243        return currentTransform()->isSimple();
244    }
245
246    Caches& getCaches() {
247        return mCaches;
248    }
249
250    // simple rect clip
251    bool isCurrentClipSimple() {
252        return mSnapshot->clipRegion->isEmpty();
253    }
254
255    int getViewportWidth() { return currentSnapshot()->viewport.getWidth(); }
256    int getViewportHeight() { return currentSnapshot()->viewport.getHeight(); }
257
258    /**
259     * Scales the alpha on the current snapshot. This alpha value will be modulated
260     * with other alpha values when drawing primitives.
261     */
262    void scaleAlpha(float alpha) {
263        mSnapshot->alpha *= alpha;
264    }
265
266    /**
267     * Inserts a named event marker in the stream of GL commands.
268     */
269    void eventMark(const char* name) const;
270
271    /**
272     * Inserts a named group marker in the stream of GL commands. This marker
273     * can be used by tools to group commands into logical groups. A call to
274     * this method must always be followed later on by a call to endMark().
275     */
276    void startMark(const char* name) const;
277
278    /**
279     * Closes the last group marker opened by startMark().
280     */
281    void endMark() const;
282
283    /**
284     * Gets the alpha and xfermode out of a paint object. If the paint is null
285     * alpha will be 255 and the xfermode will be SRC_OVER. This method does
286     * not multiply the paint's alpha by the current snapshot's alpha, and does
287     * not replace the alpha with the overrideLayerAlpha
288     *
289     * @param paint The paint to extract values from
290     * @param alpha Where to store the resulting alpha
291     * @param mode Where to store the resulting xfermode
292     */
293    static inline void getAlphaAndModeDirect(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
294        *mode = getXfermodeDirect(paint);
295        *alpha = getAlphaDirect(paint);
296    }
297
298    static inline SkXfermode::Mode getXfermodeDirect(const SkPaint* paint) {
299        if (!paint) return SkXfermode::kSrcOver_Mode;
300        return getXfermode(paint->getXfermode());
301    }
302
303    static inline int getAlphaDirect(const SkPaint* paint) {
304        if (!paint) return 255;
305        return paint->getAlpha();
306    }
307
308    /**
309     * Return the best transform to use to rasterize text given a full
310     * transform matrix.
311     */
312    mat4 findBestFontTransform(const mat4& transform) const;
313
314#if DEBUG_MERGE_BEHAVIOR
315    void drawScreenSpaceColorRect(float left, float top, float right, float bottom, int color) {
316        mCaches.setScissorEnabled(false);
317
318        // should only be called outside of other draw ops, so stencil can only be in test state
319        bool stencilWasEnabled = mCaches.stencil.isTestEnabled();
320        mCaches.stencil.disable();
321
322        drawColorRect(left, top, right, bottom, color, SkXfermode::kSrcOver_Mode, true);
323
324        if (stencilWasEnabled) mCaches.stencil.enableTest();
325    }
326#endif
327
328protected:
329    /**
330     * Computes the projection matrix, initialize the first snapshot
331     * and stores the dimensions of the render target.
332     */
333    void initViewport(int width, int height);
334
335    /**
336     * Perform the setup specific to a frame. This method does not
337     * issue any OpenGL commands.
338     */
339    void setupFrameState(float left, float top, float right, float bottom, bool opaque);
340
341    /**
342     * Indicates the start of rendering. This method will setup the
343     * initial OpenGL state (viewport, clearing the buffer, etc.)
344     */
345    status_t startFrame();
346
347    /**
348     * Clears the underlying surface if needed.
349     */
350    virtual status_t clear(float left, float top, float right, float bottom, bool opaque);
351
352    /**
353     * Call this method after updating a layer during a drawing pass.
354     */
355    void resumeAfterLayer();
356
357    /**
358     * This method is called whenever a stencil buffer is required. Subclasses
359     * should override this method and call attachStencilBufferToLayer() on the
360     * appropriate layer(s).
361     */
362    virtual void ensureStencilBuffer();
363
364    /**
365     * Obtains a stencil render buffer (allocating it if necessary) and
366     * attaches it to the specified layer.
367     */
368    void attachStencilBufferToLayer(Layer* layer);
369
370    bool quickRejectSetupScissor(float left, float top, float right, float bottom,
371            const SkPaint* paint = NULL);
372    bool quickRejectSetupScissor(const Rect& bounds, const SkPaint* paint = NULL) {
373        return quickRejectSetupScissor(bounds.left, bounds.top,
374                bounds.right, bounds.bottom, paint);
375    }
376
377    /**
378     * Compose the layer defined in the current snapshot with the layer
379     * defined by the previous snapshot.
380     *
381     * The current snapshot *must* be a layer (flag kFlagIsLayer set.)
382     *
383     * @param curent The current snapshot containing the layer to compose
384     * @param previous The previous snapshot to compose the current layer with
385     */
386    virtual void composeLayer(const Snapshot& current, const Snapshot& previous);
387
388    /**
389     * Marks the specified region as dirty at the specified bounds.
390     */
391    void dirtyLayerUnchecked(Rect& bounds, Region* region);
392
393    /**
394     * Returns the region of the current layer.
395     */
396    virtual Region* getRegion() const {
397        return mSnapshot->region;
398    }
399
400    /**
401     * Indicates whether rendering is currently targeted at a layer.
402     */
403    virtual bool hasLayer() const {
404        return (mSnapshot->flags & Snapshot::kFlagFboTarget) && mSnapshot->region;
405    }
406
407    /**
408     * Returns the name of the FBO this renderer is rendering into.
409     */
410    virtual GLuint getTargetFbo() const {
411        return 0;
412    }
413
414    /**
415     * Renders the specified layer as a textured quad.
416     *
417     * @param layer The layer to render
418     * @param rect The bounds of the layer
419     */
420    void drawTextureLayer(Layer* layer, const Rect& rect);
421
422    /**
423     * Gets the alpha and xfermode out of a paint object. If the paint is null
424     * alpha will be 255 and the xfermode will be SRC_OVER. Accounts for both
425     * snapshot alpha, and overrideLayerAlpha
426     *
427     * @param paint The paint to extract values from
428     * @param alpha Where to store the resulting alpha
429     * @param mode Where to store the resulting xfermode
430     */
431    inline void getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) const;
432
433    /**
434     * Gets the alpha from a layer, accounting for snapshot alpha and overrideLayerAlpha
435     *
436     * @param layer The layer from which the alpha is extracted
437     */
438    inline float getLayerAlpha(const Layer* layer) const;
439
440    /**
441     * Safely retrieves the ColorFilter from the given Paint. If the paint is
442     * null then null is returned.
443     */
444    static inline SkColorFilter* getColorFilter(const SkPaint* paint) {
445        return paint ? paint->getColorFilter() : NULL;
446    }
447
448    /**
449     * Set to true to suppress error checks at the end of a frame.
450     */
451    virtual bool suppressErrorChecks() const {
452        return false;
453    }
454
455private:
456    /**
457     * Discards the content of the framebuffer if supported by the driver.
458     * This method should be called at the beginning of a frame to optimize
459     * rendering on some tiler architectures.
460     */
461    void discardFramebuffer(float left, float top, float right, float bottom);
462
463    /**
464     * Ensures the state of the renderer is the same as the state of
465     * the GL context.
466     */
467    void syncState();
468
469    /**
470     * Tells the GPU what part of the screen is about to be redrawn.
471     * This method will use the current layer space clip rect.
472     * This method needs to be invoked every time getTargetFbo() is
473     * bound again.
474     */
475    void startTilingCurrentClip(bool opaque = false);
476
477    /**
478     * Tells the GPU what part of the screen is about to be redrawn.
479     * This method needs to be invoked every time getTargetFbo() is
480     * bound again.
481     */
482    void startTiling(const Rect& clip, int windowHeight, bool opaque = false);
483
484    /**
485     * Tells the GPU that we are done drawing the frame or that we
486     * are switching to another render target.
487     */
488    void endTiling();
489
490    void onSnapshotRestored(const Snapshot& removed, const Snapshot& restored);
491
492    /**
493     * Sets the clipping rectangle using glScissor. The clip is defined by
494     * the current snapshot's clipRect member.
495     */
496    void setScissorFromClip();
497
498    /**
499     * Sets the clipping region using the stencil buffer. The clip region
500     * is defined by the current snapshot's clipRegion member.
501     */
502    void setStencilFromClip();
503
504    /**
505     * Given the local bounds of the layer, calculates ...
506     */
507    void calculateLayerBoundsAndClip(Rect& bounds, Rect& clip, bool fboLayer);
508
509    /**
510     * Given the local bounds + clip of the layer, updates current snapshot's empty/invisible
511     */
512    void updateSnapshotIgnoreForLayer(const Rect& bounds, const Rect& clip,
513            bool fboLayer, int alpha);
514
515    /**
516     * Creates a new layer stored in the specified snapshot.
517     *
518     * @param snapshot The snapshot associated with the new layer
519     * @param left The left coordinate of the layer
520     * @param top The top coordinate of the layer
521     * @param right The right coordinate of the layer
522     * @param bottom The bottom coordinate of the layer
523     * @param alpha The translucency of the layer
524     * @param mode The blending mode of the layer
525     * @param flags The layer save flags
526     *
527     * @return True if the layer was successfully created, false otherwise
528     */
529    bool createLayer(float left, float top, float right, float bottom,
530            const SkPaint* paint, int flags);
531
532    /**
533     * Creates a new layer stored in the specified snapshot as an FBO.
534     *
535     * @param layer The layer to store as an FBO
536     * @param snapshot The snapshot associated with the new layer
537     * @param bounds The bounds of the layer
538     */
539    bool createFboLayer(Layer* layer, Rect& bounds, Rect& clip);
540
541    /**
542     * Compose the specified layer as a region.
543     *
544     * @param layer The layer to compose
545     * @param rect The layer's bounds
546     */
547    void composeLayerRegion(Layer* layer, const Rect& rect);
548
549    /**
550     * Compose the specified layer as a simple rectangle.
551     *
552     * @param layer The layer to compose
553     * @param rect The layer's bounds
554     * @param swap If true, the source and destination are swapped
555     */
556    void composeLayerRect(Layer* layer, const Rect& rect, bool swap = false);
557
558    /**
559     * Clears all the regions corresponding to the current list of layers.
560     * This method MUST be invoked before any drawing operation.
561     */
562    void clearLayerRegions();
563
564    /**
565     * Mark the layer as dirty at the specified coordinates. The coordinates
566     * are transformed with the supplied matrix.
567     */
568    void dirtyLayer(const float left, const float top,
569            const float right, const float bottom, const mat4 transform);
570
571    /**
572     * Mark the layer as dirty at the specified coordinates.
573     */
574    void dirtyLayer(const float left, const float top,
575            const float right, const float bottom);
576
577    /**
578     * Draws a colored rectangle with the specified color. The specified coordinates
579     * are transformed by the current snapshot's transform matrix unless specified
580     * otherwise.
581     *
582     * @param left The left coordinate of the rectangle
583     * @param top The top coordinate of the rectangle
584     * @param right The right coordinate of the rectangle
585     * @param bottom The bottom coordinate of the rectangle
586     * @param paint The paint containing the color, blending mode, etc.
587     * @param ignoreTransform True if the current transform should be ignored
588     */
589    void drawColorRect(float left, float top, float right, float bottom,
590            const SkPaint* paint, bool ignoreTransform = false);
591
592    /**
593     * Draws a series of colored rectangles with the specified color. The specified
594     * coordinates are transformed by the current snapshot's transform matrix unless
595     * specified otherwise.
596     *
597     * @param rects A list of rectangles, 4 floats (left, top, right, bottom)
598     *              per rectangle
599     * @param paint The paint containing the color, blending mode, etc.
600     * @param ignoreTransform True if the current transform should be ignored
601     * @param dirty True if calling this method should dirty the current layer
602     * @param clip True if the rects should be clipped, false otherwise
603     */
604    status_t drawColorRects(const float* rects, int count, const SkPaint* paint,
605            bool ignoreTransform = false, bool dirty = true, bool clip = true);
606
607    /**
608     * Draws the shape represented by the specified path texture.
609     * This method invokes drawPathTexture() but takes into account
610     * the extra left/top offset and the texture offset to correctly
611     * position the final shape.
612     *
613     * @param left The left coordinate of the shape to render
614     * @param top The top coordinate of the shape to render
615     * @param texture The texture reprsenting the shape
616     * @param paint The paint to draw the shape with
617     */
618    status_t drawShape(float left, float top, const PathTexture* texture, const SkPaint* paint);
619
620    /**
621     * Draws the specified texture as an alpha bitmap. Alpha bitmaps obey
622     * different compositing rules.
623     *
624     * @param texture The texture to draw with
625     * @param left The x coordinate of the bitmap
626     * @param top The y coordinate of the bitmap
627     * @param paint The paint to render with
628     */
629    void drawAlphaBitmap(Texture* texture, float left, float top, const SkPaint* paint);
630
631    /**
632     * Renders a strip of polygons with the specified paint, used for tessellated geometry.
633     *
634     * @param vertexBuffer The VertexBuffer to be drawn
635     * @param paint The paint to render with
636     * @param useOffset Offset the vertexBuffer (used in drawing non-AA lines)
637     */
638    status_t drawVertexBuffer(VertexBufferMode mode, const VertexBuffer& vertexBuffer,
639            const SkPaint* paint, bool useOffset = false);
640
641    /**
642     * Renders the convex hull defined by the specified path as a strip of polygons.
643     *
644     * @param path The hull of the path to draw
645     * @param paint The paint to render with
646     */
647    status_t drawConvexPath(const SkPath& path, const SkPaint* paint);
648
649    /**
650     * Draws a textured rectangle with the specified texture. The specified coordinates
651     * are transformed by the current snapshot's transform matrix.
652     *
653     * @param left The left coordinate of the rectangle
654     * @param top The top coordinate of the rectangle
655     * @param right The right coordinate of the rectangle
656     * @param bottom The bottom coordinate of the rectangle
657     * @param texture The texture to use
658     * @param paint The paint containing the alpha, blending mode, etc.
659     */
660    void drawTextureRect(float left, float top, float right, float bottom,
661            Texture* texture, const SkPaint* paint);
662
663    /**
664     * Draws a textured mesh with the specified texture. If the indices are omitted,
665     * the mesh is drawn as a simple quad. The mesh pointers become offsets when a
666     * VBO is bound.
667     *
668     * @param left The left coordinate of the rectangle
669     * @param top The top coordinate of the rectangle
670     * @param right The right coordinate of the rectangle
671     * @param bottom The bottom coordinate of the rectangle
672     * @param texture The texture name to map onto the rectangle
673     * @param paint The paint containing the alpha, blending mode, colorFilter, etc.
674     * @param blend True if the texture contains an alpha channel
675     * @param vertices The vertices that define the mesh
676     * @param texCoords The texture coordinates of each vertex
677     * @param elementsCount The number of elements in the mesh, required by indices
678     * @param swapSrcDst Whether or not the src and dst blending operations should be swapped
679     * @param ignoreTransform True if the current transform should be ignored
680     * @param vbo The VBO used to draw the mesh
681     * @param modelViewMode Defines whether the model view matrix should be scaled
682     * @param dirty True if calling this method should dirty the current layer
683     */
684    void drawTextureMesh(float left, float top, float right, float bottom, GLuint texture,
685            const SkPaint* paint, bool blend,
686            GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
687            bool swapSrcDst = false, bool ignoreTransform = false, GLuint vbo = 0,
688            ModelViewMode modelViewMode = kModelViewMode_TranslateAndScale, bool dirty = true);
689
690    void drawIndexedTextureMesh(float left, float top, float right, float bottom, GLuint texture,
691            const SkPaint* paint, bool blend,
692            GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
693            bool swapSrcDst = false, bool ignoreTransform = false, GLuint vbo = 0,
694            ModelViewMode modelViewMode = kModelViewMode_TranslateAndScale, bool dirty = true);
695
696    void drawAlpha8TextureMesh(float left, float top, float right, float bottom,
697            GLuint texture, const SkPaint* paint,
698            GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
699            bool ignoreTransform, ModelViewMode modelViewMode = kModelViewMode_TranslateAndScale,
700            bool dirty = true);
701
702    /**
703     * Draws the specified list of vertices as quads using indexed GL_TRIANGLES.
704     * If the number of vertices to draw exceeds the number of indices we have
705     * pre-allocated, this method will generate several glDrawElements() calls.
706     */
707    void issueIndexedQuadDraw(Vertex* mesh, GLsizei quadsCount);
708
709    /**
710     * Draws text underline and strike-through if needed.
711     *
712     * @param text The text to decor
713     * @param bytesCount The number of bytes in the text
714     * @param totalAdvance The total advance in pixels, defines underline/strikethrough length
715     * @param x The x coordinate where the text will be drawn
716     * @param y The y coordinate where the text will be drawn
717     * @param paint The paint to draw the text with
718     */
719    void drawTextDecorations(float totalAdvance, float x, float y, const SkPaint* paint);
720
721   /**
722     * Draws shadow layer on text (with optional positions).
723     *
724     * @param paint The paint to draw the shadow with
725     * @param text The text to draw
726     * @param bytesCount The number of bytes in the text
727     * @param count The number of glyphs in the text
728     * @param positions The x, y positions of individual glyphs (or NULL)
729     * @param fontRenderer The font renderer object
730     * @param alpha The alpha value for drawing the shadow
731     * @param x The x coordinate where the shadow will be drawn
732     * @param y The y coordinate where the shadow will be drawn
733     */
734    void drawTextShadow(const SkPaint* paint, const char* text, int bytesCount, int count,
735            const float* positions, FontRenderer& fontRenderer, int alpha,
736            float x, float y);
737
738    /**
739     * Draws a path texture. Path textures are alpha8 bitmaps that need special
740     * compositing to apply colors/filters/etc.
741     *
742     * @param texture The texture to render
743     * @param x The x coordinate where the texture will be drawn
744     * @param y The y coordinate where the texture will be drawn
745     * @param paint The paint to draw the texture with
746     */
747     void drawPathTexture(const PathTexture* texture, float x, float y, const SkPaint* paint);
748
749    /**
750     * Resets the texture coordinates stored in mMeshVertices. Setting the values
751     * back to default is achieved by calling:
752     *
753     * resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
754     *
755     * @param u1 The left coordinate of the texture
756     * @param v1 The bottom coordinate of the texture
757     * @param u2 The right coordinate of the texture
758     * @param v2 The top coordinate of the texture
759     */
760    void resetDrawTextureTexCoords(float u1, float v1, float u2, float v2);
761
762    /**
763     * Returns true if the specified paint will draw invisible text.
764     */
765    bool canSkipText(const SkPaint* paint) const;
766
767    /**
768     * Binds the specified texture. The texture unit must have been selected
769     * prior to calling this method.
770     */
771    inline void bindTexture(GLuint texture) {
772        mCaches.bindTexture(texture);
773    }
774
775    /**
776     * Binds the specified EGLImage texture. The texture unit must have been selected
777     * prior to calling this method.
778     */
779    inline void bindExternalTexture(GLuint texture) {
780        mCaches.bindTexture(GL_TEXTURE_EXTERNAL_OES, texture);
781    }
782
783    /**
784     * Enable or disable blending as necessary. This function sets the appropriate
785     * blend function based on the specified xfermode.
786     */
787    inline void chooseBlending(bool blend, SkXfermode::Mode mode, ProgramDescription& description,
788            bool swapSrcDst = false);
789
790    /**
791     * Use the specified program with the current GL context. If the program is already
792     * in use, it will not be bound again. If it is not in use, the current program is
793     * marked unused and the specified program becomes used and becomes the new
794     * current program.
795     *
796     * @param program The program to use
797     *
798     * @return true If the specified program was already in use, false otherwise.
799     */
800    inline bool useProgram(Program* program);
801
802    /**
803     * Invoked before any drawing operation. This sets required state.
804     */
805    void setupDraw(bool clear = true);
806
807    /**
808     * Various methods to setup OpenGL rendering.
809     */
810    void setupDrawWithTexture(bool isAlpha8 = false);
811    void setupDrawWithTextureAndColor(bool isAlpha8 = false);
812    void setupDrawWithExternalTexture();
813    void setupDrawNoTexture();
814    void setupDrawAA();
815    void setupDrawColor(int color, int alpha);
816    void setupDrawColor(float r, float g, float b, float a);
817    void setupDrawAlpha8Color(int color, int alpha);
818    void setupDrawTextGamma(const SkPaint* paint);
819    void setupDrawShader();
820    void setupDrawColorFilter(const SkColorFilter* filter);
821    void setupDrawBlending(const Layer* layer, bool swapSrcDst = false);
822    void setupDrawBlending(const SkPaint* paint, bool blend = true, bool swapSrcDst = false);
823    void setupDrawProgram();
824    void setupDrawDirtyRegionsDisabled();
825
826    /**
827     * Setup the current program matrices based upon the nature of the geometry.
828     *
829     * @param mode If kModelViewMode_Translate, the geometry must be translated by the left and top
830     * parameters. If kModelViewMode_TranslateAndScale, the geometry that exists in the (0,0, 1,1)
831     * space must be scaled up and translated to fill the quad provided in (l,t,r,b). These
832     * transformations are stored in the modelView matrix and uploaded to the shader.
833     *
834     * @param offset Set to true if the the matrix should be fudged (translated) slightly to disambiguate
835     * geometry pixel positioning. See Vertex::GeometryFudgeFactor().
836     *
837     * @param ignoreTransform Set to true if l,t,r,b coordinates already in layer space,
838     * currentTransform() will be ignored. (e.g. when drawing clip in layer coordinates to stencil,
839     * or when simple translation has been extracted)
840     */
841    void setupDrawModelView(ModelViewMode mode, bool offset,
842            float left, float top, float right, float bottom, bool ignoreTransform = false);
843    void setupDrawColorUniforms();
844    void setupDrawPureColorUniforms();
845    void setupDrawShaderUniforms(bool ignoreTransform = false);
846    void setupDrawColorFilterUniforms(const SkColorFilter* paint);
847    void setupDrawSimpleMesh();
848    void setupDrawTexture(GLuint texture);
849    void setupDrawExternalTexture(GLuint texture);
850    void setupDrawTextureTransform();
851    void setupDrawTextureTransformUniforms(mat4& transform);
852    void setupDrawTextGammaUniforms();
853    void setupDrawMesh(const GLvoid* vertices, const GLvoid* texCoords = NULL, GLuint vbo = 0);
854    void setupDrawMesh(const GLvoid* vertices, const GLvoid* texCoords, const GLvoid* colors);
855    void setupDrawMeshIndices(const GLvoid* vertices, const GLvoid* texCoords, GLuint vbo = 0);
856    void setupDrawIndexedVertices(GLvoid* vertices);
857    void accountForClear(SkXfermode::Mode mode);
858
859    bool updateLayer(Layer* layer, bool inFrame);
860    void updateLayers();
861    void flushLayers();
862
863#if DEBUG_LAYERS_AS_REGIONS
864    /**
865     * Renders the specified region as a series of rectangles. This method
866     * is used for debugging only.
867     */
868    void drawRegionRectsDebug(const Region& region);
869#endif
870
871    /**
872     * Renders the specified region as a series of rectangles. The region
873     * must be in screen-space coordinates.
874     */
875    void drawRegionRects(const SkRegion& region, const SkPaint& paint, bool dirty = false);
876
877    /**
878     * Draws the current clip region if any. Only when DEBUG_CLIP_REGIONS
879     * is turned on.
880     */
881    void debugClip();
882
883    void debugOverdraw(bool enable, bool clear);
884    void renderOverdraw();
885    void countOverdraw();
886
887    /**
888     * Should be invoked every time the glScissor is modified.
889     */
890    inline void dirtyClip() {
891        mDirtyClip = true;
892    }
893
894    inline const UvMapper& getMapper(const Texture* texture) {
895        return texture && texture->uvMapper ? *texture->uvMapper : mUvMapper;
896    }
897
898    /**
899     * Returns a texture object for the specified bitmap. The texture can
900     * come from the texture cache or an atlas. If this method returns
901     * NULL, the texture could not be found and/or allocated.
902     */
903    Texture* getTexture(const SkBitmap* bitmap);
904
905    // Matrix used for view/projection in shaders
906    mat4 mViewProjMatrix;
907
908    /**
909     * Model-view matrix used to position/size objects
910     *
911     * Stores operation-local modifications to the draw matrix that aren't incorporated into the
912     * currentTransform().
913     *
914     * If generated with kModelViewMode_Translate, the mModelView will reflect an x/y offset,
915     * e.g. the offset in drawLayer(). If generated with kModelViewMode_TranslateAndScale,
916     * mModelView will reflect a translation and scale, e.g. the translation and scale required to
917     * make VBO 0 (a rect of (0,0,1,1)) scaled to match the x,y offset, and width/height of a
918     * bitmap.
919     *
920     * Used as input to SkiaShader transformation.
921     */
922    mat4 mModelView;
923
924    // State used to define the clipping region
925    Rect mTilingClip;
926    // Is the target render surface opaque
927    bool mOpaque;
928    // Is a frame currently being rendered
929    bool mFrameStarted;
930
931    // Used to draw textured quads
932    TextureVertex mMeshVertices[4];
933
934    // Default UV mapper
935    const UvMapper mUvMapper;
936
937    // shader, filters, and shadow
938    DrawModifiers mDrawModifiers;
939    SkPaint mFilteredPaint;
940
941    // Various caches
942    Caches& mCaches;
943    Extensions& mExtensions;
944
945    // List of rectangles to clear after saveLayer() is invoked
946    Vector<Rect*> mLayers;
947    // List of functors to invoke after a frame is drawn
948    SortedVector<Functor*> mFunctors;
949    // List of layers to update at the beginning of a frame
950    Vector<Layer*> mLayerUpdates;
951
952    // The following fields are used to setup drawing
953    // Used to describe the shaders to generate
954    ProgramDescription mDescription;
955    // Color description
956    bool mColorSet;
957    float mColorA, mColorR, mColorG, mColorB;
958    // Indicates that the shader should get a color
959    bool mSetShaderColor;
960    // Current texture unit
961    GLuint mTextureUnit;
962    // Track dirty regions, true by default
963    bool mTrackDirtyRegions;
964    // Indicate whether we are drawing an opaque frame
965    bool mOpaqueFrame;
966
967    // See PROPERTY_DISABLE_SCISSOR_OPTIMIZATION in
968    // Properties.h
969    bool mScissorOptimizationDisabled;
970
971    // No-ops start/endTiling when set
972    bool mSuppressTiling;
973
974    // If true, this renderer will setup drawing to emulate
975    // an increment stencil buffer in the color buffer
976    bool mCountOverdraw;
977    float mOverdraw;
978
979    friend class DisplayListRenderer;
980    friend class Layer;
981    friend class TextSetupFunctor;
982    friend class DrawBitmapOp;
983    friend class DrawPatchOp;
984
985}; // class OpenGLRenderer
986
987}; // namespace uirenderer
988}; // namespace android
989
990#endif // ANDROID_HWUI_OPENGL_RENDERER_H
991