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