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