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