OpenGLRenderer.h revision 23d307c8d88f4a3849163b9e5b7cd11d0d4f372c
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 RenderState;
61class RenderNode;
62class TextSetupFunctor;
63class VertexBuffer;
64
65struct DrawModifiers {
66    DrawModifiers() {
67        reset();
68    }
69
70    void reset() {
71        memset(this, 0, sizeof(DrawModifiers));
72    }
73
74    float mOverrideLayerAlpha;
75
76    // Draw filters
77    bool mHasDrawFilter;
78    int mPaintFilterClearBits;
79    int mPaintFilterSetBits;
80};
81
82enum StateDeferFlags {
83    kStateDeferFlag_Draw = 0x1,
84    kStateDeferFlag_Clip = 0x2
85};
86
87enum ClipSideFlags {
88    kClipSide_None = 0x0,
89    kClipSide_Left = 0x1,
90    kClipSide_Top = 0x2,
91    kClipSide_Right = 0x4,
92    kClipSide_Bottom = 0x8,
93    kClipSide_Full = 0xF,
94    kClipSide_ConservativeFull = 0x1F
95};
96
97enum VertexBufferDisplayFlags {
98    kVertexBuffer_Offset = 0x1,
99    kVertexBuffer_ShadowInterp = 0x2,
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
120///////////////////////////////////////////////////////////////////////////////
121// Renderer
122///////////////////////////////////////////////////////////////////////////////
123/**
124 * OpenGL Renderer implementation.
125 */
126class OpenGLRenderer : public StatefulBaseRenderer {
127public:
128    OpenGLRenderer(RenderState& renderState);
129    virtual ~OpenGLRenderer();
130
131    void initProperties();
132    void initLight(const Vector3& lightCenter, float lightRadius,
133            uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha);
134
135    virtual void onViewportInitialized();
136    virtual status_t prepareDirty(float left, float top, float right, float bottom, bool opaque);
137    virtual void finish();
138
139    virtual status_t callDrawGLFunction(Functor* functor, Rect& dirty);
140
141    void pushLayerUpdate(Layer* layer);
142    void cancelLayerUpdate(Layer* layer);
143    void clearLayerUpdates();
144    void flushLayerUpdates();
145    void markLayersAsBuildLayers();
146
147    virtual int saveLayer(float left, float top, float right, float bottom,
148            const SkPaint* paint, int flags) {
149        return saveLayer(left, top, right, bottom, paint, flags, NULL);
150    }
151
152    // Specialized saveLayer implementation, which will pass the convexMask to an FBO layer, if
153    // created, which will in turn clip to that mask when drawn back/restored.
154    int saveLayer(float left, float top, float right, float bottom,
155            const SkPaint* paint, int flags, const SkPath* convexMask);
156
157    int saveLayerDeferred(float left, float top, float right, float bottom,
158            const SkPaint* paint, int flags);
159
160    virtual status_t drawRenderNode(RenderNode* displayList, Rect& dirty, int32_t replayFlags = 1);
161    virtual status_t drawLayer(Layer* layer, float x, float y);
162    virtual status_t drawBitmap(const SkBitmap* bitmap, const SkPaint* paint);
163    status_t drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry, int bitmapCount,
164            TextureVertex* vertices, bool pureTranslate, const Rect& bounds, const SkPaint* paint);
165    virtual status_t drawBitmap(const SkBitmap* bitmap, float srcLeft, float srcTop,
166            float srcRight, float srcBottom, float dstLeft, float dstTop,
167            float dstRight, float dstBottom, const SkPaint* paint);
168    virtual status_t drawBitmapData(const SkBitmap* bitmap, const SkPaint* paint);
169    virtual status_t drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight,
170            const float* vertices, const int* colors, const SkPaint* paint);
171    status_t drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
172            TextureVertex* vertices, uint32_t indexCount, const SkPaint* paint);
173    virtual status_t drawPatch(const SkBitmap* bitmap, const Res_png_9patch* patch,
174            float left, float top, float right, float bottom, const SkPaint* paint);
175    status_t drawPatch(const SkBitmap* bitmap, const Patch* mesh, AssetAtlas::Entry* entry,
176            float left, float top, float right, float bottom, const SkPaint* paint);
177    virtual status_t drawColor(int color, SkXfermode::Mode mode);
178    virtual status_t drawRect(float left, float top, float right, float bottom,
179            const SkPaint* paint);
180    virtual status_t drawRoundRect(float left, float top, float right, float bottom,
181            float rx, float ry, const SkPaint* paint);
182    virtual status_t drawCircle(float x, float y, float radius, const SkPaint* paint);
183    virtual status_t drawOval(float left, float top, float right, float bottom,
184            const SkPaint* paint);
185    virtual status_t drawArc(float left, float top, float right, float bottom,
186            float startAngle, float sweepAngle, bool useCenter, const SkPaint* paint);
187    virtual status_t drawPath(const SkPath* path, const SkPaint* paint);
188    virtual status_t drawLines(const float* points, int count, const SkPaint* paint);
189    virtual status_t drawPoints(const float* points, int count, const SkPaint* paint);
190    virtual status_t drawTextOnPath(const char* text, int bytesCount, int count, const SkPath* path,
191            float hOffset, float vOffset, const SkPaint* paint);
192    virtual status_t drawPosText(const char* text, int bytesCount, int count,
193            const float* positions, const SkPaint* paint);
194    virtual status_t drawText(const char* text, int bytesCount, int count, float x, float y,
195            const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds,
196            DrawOpMode drawOpMode = kDrawOpMode_Immediate);
197    virtual status_t drawRects(const float* rects, int count, const SkPaint* paint);
198
199    status_t drawShadow(float casterAlpha,
200            const VertexBuffer* ambientShadowVertexBuffer, const VertexBuffer* spotShadowVertexBuffer);
201
202    virtual void resetPaintFilter();
203    virtual void setupPaintFilter(int clearBits, int setBits);
204
205    // If this value is set to < 1.0, it overrides alpha set on layer (see drawBitmap, drawLayer)
206    void setOverrideLayerAlpha(float alpha) { mDrawModifiers.mOverrideLayerAlpha = alpha; }
207
208    const SkPaint* filterPaint(const SkPaint* paint);
209
210    /**
211     * Store the current display state (most importantly, the current clip and transform), and
212     * additionally map the state's bounds from local to window coordinates.
213     *
214     * Returns true if quick-rejected
215     */
216    bool storeDisplayState(DeferredDisplayState& state, int stateDeferFlags);
217    void restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore = false);
218    void setupMergedMultiDraw(const Rect* clipRect);
219
220    const DrawModifiers& getDrawModifiers() { return mDrawModifiers; }
221    void setDrawModifiers(const DrawModifiers& drawModifiers) { mDrawModifiers = drawModifiers; }
222
223    bool isCurrentTransformSimple() {
224        return currentTransform()->isSimple();
225    }
226
227    Caches& getCaches() {
228        return mCaches;
229    }
230
231    // simple rect clip
232    bool isCurrentClipSimple() {
233        return mSnapshot->clipRegion->isEmpty();
234    }
235
236    int getViewportWidth() { return currentSnapshot()->getViewportWidth(); }
237    int getViewportHeight() { return currentSnapshot()->getViewportHeight(); }
238
239    /**
240     * Scales the alpha on the current snapshot. This alpha value will be modulated
241     * with other alpha values when drawing primitives.
242     */
243    void scaleAlpha(float alpha) {
244        mSnapshot->alpha *= alpha;
245    }
246
247    /**
248     * Inserts a named event marker in the stream of GL commands.
249     */
250    void eventMark(const char* name) const;
251
252    /**
253     * Inserts a formatted event marker in the stream of GL commands.
254     */
255    void eventMarkDEBUG(const char *fmt, ...) const;
256
257    /**
258     * Inserts a named group marker in the stream of GL commands. This marker
259     * can be used by tools to group commands into logical groups. A call to
260     * this method must always be followed later on by a call to endMark().
261     */
262    void startMark(const char* name) const;
263
264    /**
265     * Closes the last group marker opened by startMark().
266     */
267    void endMark() const;
268
269    /**
270     * Gets the alpha and xfermode out of a paint object. If the paint is null
271     * alpha will be 255 and the xfermode will be SRC_OVER. This method does
272     * not multiply the paint's alpha by the current snapshot's alpha, and does
273     * not replace the alpha with the overrideLayerAlpha
274     *
275     * @param paint The paint to extract values from
276     * @param alpha Where to store the resulting alpha
277     * @param mode Where to store the resulting xfermode
278     */
279    static inline void getAlphaAndModeDirect(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
280        *mode = getXfermodeDirect(paint);
281        *alpha = getAlphaDirect(paint);
282    }
283
284    static inline SkXfermode::Mode getXfermodeDirect(const SkPaint* paint) {
285        if (!paint) return SkXfermode::kSrcOver_Mode;
286        return getXfermode(paint->getXfermode());
287    }
288
289    static inline int getAlphaDirect(const SkPaint* paint) {
290        if (!paint) return 255;
291        return paint->getAlpha();
292    }
293
294    struct TextShadow {
295        SkScalar radius;
296        float dx;
297        float dy;
298        SkColor color;
299    };
300
301    static inline bool getTextShadow(const SkPaint* paint, TextShadow* textShadow) {
302        SkDrawLooper::BlurShadowRec blur;
303        if (paint && paint->getLooper() && paint->getLooper()->asABlurShadow(&blur)) {
304            if (textShadow) {
305                textShadow->radius = Blur::convertSigmaToRadius(blur.fSigma);
306                textShadow->dx = blur.fOffset.fX;
307                textShadow->dy = blur.fOffset.fY;
308                textShadow->color = blur.fColor;
309            }
310            return true;
311        }
312        return false;
313    }
314
315    static inline bool hasTextShadow(const SkPaint* paint) {
316        return getTextShadow(paint, NULL);
317    }
318
319    /**
320     * Build the best transform to use to rasterize text given a full
321     * transform matrix, and whether filteration is needed.
322     *
323     * Returns whether filtration is needed
324     */
325    bool findBestFontTransform(const mat4& transform, SkMatrix* outMatrix) const;
326
327#if DEBUG_MERGE_BEHAVIOR
328    void drawScreenSpaceColorRect(float left, float top, float right, float bottom, int color) {
329        mCaches.setScissorEnabled(false);
330
331        // should only be called outside of other draw ops, so stencil can only be in test state
332        bool stencilWasEnabled = mCaches.stencil.isTestEnabled();
333        mCaches.stencil.disable();
334
335        drawColorRect(left, top, right, bottom, color, SkXfermode::kSrcOver_Mode, true);
336
337        if (stencilWasEnabled) mCaches.stencil.enableTest();
338    }
339#endif
340
341    const Vector3& getLightCenter() const { return currentSnapshot()->getRelativeLightCenter(); }
342    float getLightRadius() const { return mLightRadius; }
343    uint8_t getAmbientShadowAlpha() const { return mAmbientShadowAlpha; }
344    uint8_t getSpotShadowAlpha() const { return mSpotShadowAlpha; }
345
346protected:
347    /**
348     * Perform the setup specific to a frame. This method does not
349     * issue any OpenGL commands.
350     */
351    void setupFrameState(float left, float top, float right, float bottom, bool opaque);
352
353    /**
354     * Indicates the start of rendering. This method will setup the
355     * initial OpenGL state (viewport, clearing the buffer, etc.)
356     */
357    status_t startFrame();
358
359    /**
360     * Clears the underlying surface if needed.
361     */
362    virtual status_t clear(float left, float top, float right, float bottom, bool opaque);
363
364    /**
365     * Call this method after updating a layer during a drawing pass.
366     */
367    void resumeAfterLayer();
368
369    /**
370     * This method is called whenever a stencil buffer is required. Subclasses
371     * should override this method and call attachStencilBufferToLayer() on the
372     * appropriate layer(s).
373     */
374    virtual void ensureStencilBuffer();
375
376    /**
377     * Obtains a stencil render buffer (allocating it if necessary) and
378     * attaches it to the specified layer.
379     */
380    void attachStencilBufferToLayer(Layer* layer);
381
382    bool quickRejectSetupScissor(float left, float top, float right, float bottom,
383            const SkPaint* paint = NULL);
384    bool quickRejectSetupScissor(const Rect& bounds, const SkPaint* paint = NULL) {
385        return quickRejectSetupScissor(bounds.left, bounds.top,
386                bounds.right, bounds.bottom, paint);
387    }
388
389    /**
390     * Compose the layer defined in the current snapshot with the layer
391     * defined by the previous snapshot.
392     *
393     * The current snapshot *must* be a layer (flag kFlagIsLayer set.)
394     *
395     * @param curent The current snapshot containing the layer to compose
396     * @param previous The previous snapshot to compose the current layer with
397     */
398    virtual void composeLayer(const Snapshot& current, const Snapshot& previous);
399
400    /**
401     * Marks the specified region as dirty at the specified bounds.
402     */
403    void dirtyLayerUnchecked(Rect& bounds, Region* region);
404
405    /**
406     * Returns the region of the current layer.
407     */
408    virtual Region* getRegion() const {
409        return mSnapshot->region;
410    }
411
412    /**
413     * Indicates whether rendering is currently targeted at a layer.
414     */
415    virtual bool hasLayer() const {
416        return (mSnapshot->flags & Snapshot::kFlagFboTarget) && mSnapshot->region;
417    }
418
419    /**
420     * Returns the name of the FBO this renderer is rendering into.
421     */
422    virtual GLuint getTargetFbo() const {
423        return 0;
424    }
425
426    /**
427     * Renders the specified layer as a textured quad.
428     *
429     * @param layer The layer to render
430     * @param rect The bounds of the layer
431     */
432    void drawTextureLayer(Layer* layer, const Rect& rect);
433
434    /**
435     * Gets the alpha and xfermode out of a paint object. If the paint is null
436     * alpha will be 255 and the xfermode will be SRC_OVER. Accounts for both
437     * snapshot alpha, and overrideLayerAlpha
438     *
439     * @param paint The paint to extract values from
440     * @param alpha Where to store the resulting alpha
441     * @param mode Where to store the resulting xfermode
442     */
443    inline void getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) const;
444
445    /**
446     * Gets the alpha from a layer, accounting for snapshot alpha and overrideLayerAlpha
447     *
448     * @param layer The layer from which the alpha is extracted
449     */
450    inline float getLayerAlpha(const Layer* layer) const;
451
452    /**
453     * Safely retrieves the ColorFilter from the given Paint. If the paint is
454     * null then null is returned.
455     */
456    static inline SkColorFilter* getColorFilter(const SkPaint* paint) {
457        return paint ? paint->getColorFilter() : NULL;
458    }
459
460    /**
461     * Safely retrieves the Shader from the given Paint. If the paint is
462     * null then null is returned.
463     */
464    static inline const SkShader* getShader(const SkPaint* paint) {
465        return paint ? paint->getShader() : NULL;
466    }
467
468    /**
469     * Set to true to suppress error checks at the end of a frame.
470     */
471    virtual bool suppressErrorChecks() const {
472        return false;
473    }
474
475    inline RenderState& renderState() { return mRenderState; }
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, bool expand = 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, bool expand = 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 flags flags with which to draw
660     */
661    status_t drawVertexBuffer(float translateX, float translateY, const VertexBuffer& vertexBuffer,
662            const SkPaint* paint, int flags = 0);
663
664    /**
665     * Convenience for translating method
666     */
667    status_t drawVertexBuffer(const VertexBuffer& vertexBuffer,
668            const SkPaint* paint, int flags = 0) {
669        return drawVertexBuffer(0.0f, 0.0f, vertexBuffer, paint, flags);
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 setupDrawVertexAlpha(bool useShadowAlphaInterp);
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    RenderState& mRenderState;
981
982    // List of rectangles to clear after saveLayer() is invoked
983    Vector<Rect*> mLayers;
984    // List of layers to update at the beginning of a frame
985    Vector<Layer*> mLayerUpdates;
986
987    // The following fields are used to setup drawing
988    // Used to describe the shaders to generate
989    ProgramDescription mDescription;
990    // Color description
991    bool mColorSet;
992    float mColorA, mColorR, mColorG, mColorB;
993    // Indicates that the shader should get a color
994    bool mSetShaderColor;
995    // Current texture unit
996    GLuint mTextureUnit;
997    // Track dirty regions, true by default
998    bool mTrackDirtyRegions;
999    // Indicate whether we are drawing an opaque frame
1000    bool mOpaqueFrame;
1001
1002    // See PROPERTY_DISABLE_SCISSOR_OPTIMIZATION in
1003    // Properties.h
1004    bool mScissorOptimizationDisabled;
1005
1006    // No-ops start/endTiling when set
1007    bool mSuppressTiling;
1008    bool mFirstFrameAfterResize;
1009
1010    bool mSkipOutlineClip;
1011
1012    // Lighting + shadows
1013    Vector3 mLightCenter;
1014    float mLightRadius;
1015    uint8_t mAmbientShadowAlpha;
1016    uint8_t mSpotShadowAlpha;
1017
1018    friend class Layer;
1019    friend class TextSetupFunctor;
1020    friend class DrawBitmapOp;
1021    friend class DrawPatchOp;
1022
1023}; // class OpenGLRenderer
1024
1025}; // namespace uirenderer
1026}; // namespace android
1027
1028#endif // ANDROID_HWUI_OPENGL_RENDERER_H
1029