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