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 "CanvasState.h"
21 #include "Debug.h"
22 #include "Extensions.h"
23 #include "Matrix.h"
24 #include "Program.h"
25 #include "Rect.h"
26 #include "Snapshot.h"
27 #include "UvMapper.h"
28 #include "Vertex.h"
29 #include "Caches.h"
30 #include "utils/PaintUtils.h"
31 
32 #include <GLES2/gl2.h>
33 #include <GLES2/gl2ext.h>
34 
35 #include <SkBitmap.h>
36 #include <SkCanvas.h>
37 #include <SkColorFilter.h>
38 #include <SkMatrix.h>
39 #include <SkPaint.h>
40 #include <SkRegion.h>
41 #include <SkXfermode.h>
42 
43 #include <utils/Blur.h>
44 #include <utils/Functor.h>
45 #include <utils/RefBase.h>
46 #include <utils/SortedVector.h>
47 #include <utils/Vector.h>
48 
49 #include <cutils/compiler.h>
50 
51 #include <androidfw/ResourceTypes.h>
52 
53 class SkShader;
54 
55 namespace android {
56 namespace uirenderer {
57 
58 enum class DrawOpMode {
59     kImmediate,
60     kDefer,
61     kFlush
62 };
63 
64 class DeferredDisplayState;
65 struct Glop;
66 class RenderState;
67 class RenderNode;
68 class TextDrawFunctor;
69 class VertexBuffer;
70 
71 enum StateDeferFlags {
72     kStateDeferFlag_Draw = 0x1,
73     kStateDeferFlag_Clip = 0x2
74 };
75 
76 enum ClipSideFlags {
77     kClipSide_None = 0x0,
78     kClipSide_Left = 0x1,
79     kClipSide_Top = 0x2,
80     kClipSide_Right = 0x4,
81     kClipSide_Bottom = 0x8,
82     kClipSide_Full = 0xF,
83     kClipSide_ConservativeFull = 0x1F
84 };
85 
86 enum VertexBufferDisplayFlags {
87     kVertexBuffer_Offset = 0x1,
88     kVertexBuffer_ShadowInterp = 0x2,
89 };
90 
91 /**
92  * Defines additional transformation that should be applied by the model view matrix, beyond that of
93  * the currentTransform()
94  */
95 enum ModelViewMode {
96     /**
97      * Used when the model view should simply translate geometry passed to the shader. The resulting
98      * matrix will be a simple translation.
99      */
100     kModelViewMode_Translate = 0,
101 
102     /**
103      * Used when the model view should translate and scale geometry. The resulting matrix will be a
104      * translation + scale. This is frequently used together with VBO 0, the (0,0,1,1) rect.
105      */
106     kModelViewMode_TranslateAndScale = 1,
107 };
108 
109 ///////////////////////////////////////////////////////////////////////////////
110 // Renderer
111 ///////////////////////////////////////////////////////////////////////////////
112 /**
113  * OpenGL Renderer implementation.
114  */
115 class OpenGLRenderer : public CanvasStateClient {
116 public:
117     OpenGLRenderer(RenderState& renderState);
118     virtual ~OpenGLRenderer();
119 
120     /**
121      * Sets the dimension of the underlying drawing surface. This method must
122      * be called at least once every time the drawing surface changes size.
123      *
124      * @param width The width in pixels of the underlysing surface
125      * @param height The height in pixels of the underlysing surface
126      */
setViewport(int width,int height)127     void setViewport(int width, int height) { mState.setViewport(width, height); }
128 
129     void initProperties();
130     void initLight(float lightRadius, uint8_t ambientShadowAlpha,
131             uint8_t spotShadowAlpha);
132     void setLightCenter(const Vector3& lightCenter);
133 
134     /*
135      * Prepares the renderer to draw a frame. This method must be invoked
136      * at the beginning of each frame. Only the specified rectangle of the
137      * frame is assumed to be dirty. A clip will automatically be set to
138      * the specified rectangle.
139      *
140      * @param opaque If true, the target surface is considered opaque
141      *               and will not be cleared. If false, the target surface
142      *               will be cleared
143      */
144     virtual void prepareDirty(float left, float top, float right, float bottom,
145             bool opaque);
146 
147     /**
148      * Prepares the renderer to draw a frame. This method must be invoked
149      * at the beginning of each frame. When this method is invoked, the
150      * entire drawing surface is assumed to be redrawn.
151      *
152      * @param opaque If true, the target surface is considered opaque
153      *               and will not be cleared. If false, the target surface
154      *               will be cleared
155      */
prepare(bool opaque)156     void prepare(bool opaque) {
157         prepareDirty(0.0f, 0.0f, mState.getWidth(), mState.getHeight(), opaque);
158     }
159 
160     /**
161      * Indicates the end of a frame. This method must be invoked whenever
162      * the caller is done rendering a frame.
163      * Returns true if any drawing was done during the frame (the output
164      * has changed / is "dirty" and should be displayed to the user).
165      */
166     virtual bool finish();
167 
168     void callDrawGLFunction(Functor* functor, Rect& dirty);
169 
170     void pushLayerUpdate(Layer* layer);
171     void cancelLayerUpdate(Layer* layer);
172     void flushLayerUpdates();
173     void markLayersAsBuildLayers();
174 
saveLayer(float left,float top,float right,float bottom,const SkPaint * paint,int flags)175     virtual int saveLayer(float left, float top, float right, float bottom,
176             const SkPaint* paint, int flags) {
177         return saveLayer(left, top, right, bottom, paint, flags, nullptr);
178     }
179 
180     // Specialized saveLayer implementation, which will pass the convexMask to an FBO layer, if
181     // created, which will in turn clip to that mask when drawn back/restored.
182     int saveLayer(float left, float top, float right, float bottom,
183             const SkPaint* paint, int flags, const SkPath* convexMask);
184 
185     int saveLayerDeferred(float left, float top, float right, float bottom,
186             const SkPaint* paint, int flags);
187 
188     void drawRenderNode(RenderNode* displayList, Rect& dirty, int32_t replayFlags = 1);
189     void drawLayer(Layer* layer, float x, float y);
190     void drawBitmap(const SkBitmap* bitmap, const SkPaint* paint);
191     void drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry, int bitmapCount,
192             TextureVertex* vertices, bool pureTranslate, const Rect& bounds, const SkPaint* paint);
193     void drawBitmap(const SkBitmap* bitmap, Rect src, Rect dst,
194             const SkPaint* paint);
195     void drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight,
196             const float* vertices, const int* colors, const SkPaint* paint);
197     void drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
198             TextureVertex* vertices, uint32_t indexCount, const SkPaint* paint);
199     void drawPatch(const SkBitmap* bitmap, const Patch* mesh, AssetAtlas::Entry* entry,
200             float left, float top, float right, float bottom, const SkPaint* paint);
201     void drawColor(int color, SkXfermode::Mode mode);
202     void drawRect(float left, float top, float right, float bottom,
203             const SkPaint* paint);
204     void drawRoundRect(float left, float top, float right, float bottom,
205             float rx, float ry, const SkPaint* paint);
206     void drawCircle(float x, float y, float radius, const SkPaint* paint);
207     void drawOval(float left, float top, float right, float bottom,
208             const SkPaint* paint);
209     void drawArc(float left, float top, float right, float bottom,
210             float startAngle, float sweepAngle, bool useCenter, const SkPaint* paint);
211     void drawPath(const SkPath* path, const SkPaint* paint);
212     void drawLines(const float* points, int count, const SkPaint* paint);
213     void drawPoints(const float* points, int count, const SkPaint* paint);
214     void drawTextOnPath(const char* text, int bytesCount, int count, const SkPath* path,
215             float hOffset, float vOffset, const SkPaint* paint);
216     void drawPosText(const char* text, int bytesCount, int count,
217             const float* positions, const SkPaint* paint);
218     void drawText(const char* text, int bytesCount, int count, float x, float y,
219             const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds,
220             DrawOpMode drawOpMode = DrawOpMode::kImmediate);
221     void drawRects(const float* rects, int count, const SkPaint* paint);
222 
223     void drawShadow(float casterAlpha,
224             const VertexBuffer* ambientShadowVertexBuffer,
225             const VertexBuffer* spotShadowVertexBuffer);
226 
227     void setDrawFilter(SkDrawFilter* filter);
228 
229     /**
230      * Store the current display state (most importantly, the current clip and transform), and
231      * additionally map the state's bounds from local to window coordinates.
232      *
233      * Returns true if quick-rejected
234      */
235     bool storeDisplayState(DeferredDisplayState& state, int stateDeferFlags);
236     void restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore = false);
237     void setupMergedMultiDraw(const Rect* clipRect);
238 
isCurrentTransformSimple()239     bool isCurrentTransformSimple() {
240         return currentTransform()->isSimple();
241     }
242 
getCaches()243     Caches& getCaches() {
244         return mCaches;
245     }
246 
renderState()247     RenderState& renderState() {
248         return mRenderState;
249     }
250 
getViewportWidth()251     int getViewportWidth() { return mState.getViewportWidth(); }
getViewportHeight()252     int getViewportHeight() { return mState.getViewportHeight(); }
253 
254     /**
255      * Scales the alpha on the current snapshot. This alpha value will be modulated
256      * with other alpha values when drawing primitives.
257      */
scaleAlpha(float alpha)258     void scaleAlpha(float alpha) { mState.scaleAlpha(alpha); }
259 
260     /**
261      * Inserts a named event marker in the stream of GL commands.
262      */
263     void eventMark(const char* name) const;
264 
265     /**
266      * Inserts a formatted event marker in the stream of GL commands.
267      */
268     void eventMarkDEBUG(const char *fmt, ...) const;
269 
270     /**
271      * Inserts a named group marker in the stream of GL commands. This marker
272      * can be used by tools to group commands into logical groups. A call to
273      * this method must always be followed later on by a call to endMark().
274      */
275     void startMark(const char* name) const;
276 
277     /**
278      * Closes the last group marker opened by startMark().
279      */
280     void endMark() const;
281 
282     /**
283      * Gets the alpha and xfermode out of a paint object. If the paint is null
284      * alpha will be 255 and the xfermode will be SRC_OVER. This method does
285      * not multiply the paint's alpha by the current snapshot's alpha, and does
286      * not replace the alpha with the overrideLayerAlpha
287      *
288      * @param paint The paint to extract values from
289      * @param alpha Where to store the resulting alpha
290      * @param mode Where to store the resulting xfermode
291      */
getAlphaAndModeDirect(const SkPaint * paint,int * alpha,SkXfermode::Mode * mode)292     static inline void getAlphaAndModeDirect(const SkPaint* paint, int* alpha,
293             SkXfermode::Mode* mode) {
294         *mode = getXfermodeDirect(paint);
295         *alpha = getAlphaDirect(paint);
296     }
297 
getXfermodeDirect(const SkPaint * paint)298     static inline SkXfermode::Mode getXfermodeDirect(const SkPaint* paint) {
299         if (!paint) return SkXfermode::kSrcOver_Mode;
300         return PaintUtils::getXfermode(paint->getXfermode());
301     }
302 
getAlphaDirect(const SkPaint * paint)303     static inline int getAlphaDirect(const SkPaint* paint) {
304         if (!paint) return 255;
305         return paint->getAlpha();
306     }
307 
308     struct TextShadow {
309         SkScalar radius;
310         float dx;
311         float dy;
312         SkColor color;
313     };
314 
getTextShadow(const SkPaint * paint,TextShadow * textShadow)315     static inline bool getTextShadow(const SkPaint* paint, TextShadow* textShadow) {
316         SkDrawLooper::BlurShadowRec blur;
317         if (paint && paint->getLooper() && paint->getLooper()->asABlurShadow(&blur)) {
318             if (textShadow) {
319                 textShadow->radius = Blur::convertSigmaToRadius(blur.fSigma);
320                 textShadow->dx = blur.fOffset.fX;
321                 textShadow->dy = blur.fOffset.fY;
322                 textShadow->color = blur.fColor;
323             }
324             return true;
325         }
326         return false;
327     }
328 
hasTextShadow(const SkPaint * paint)329     static inline bool hasTextShadow(const SkPaint* paint) {
330         return getTextShadow(paint, nullptr);
331     }
332 
333     /**
334      * Build the best transform to use to rasterize text given a full
335      * transform matrix, and whether filteration is needed.
336      *
337      * Returns whether filtration is needed
338      */
339     bool findBestFontTransform(const mat4& transform, SkMatrix* outMatrix) const;
340 
341 #if DEBUG_MERGE_BEHAVIOR
drawScreenSpaceColorRect(float left,float top,float right,float bottom,int color)342     void drawScreenSpaceColorRect(float left, float top, float right, float bottom, int color) {
343         mCaches.setScissorEnabled(false);
344 
345         // should only be called outside of other draw ops, so stencil can only be in test state
346         bool stencilWasEnabled = mCaches.stencil.isTestEnabled();
347         mCaches.stencil.disable();
348 
349         drawColorRect(left, top, right, bottom, color, SkXfermode::kSrcOver_Mode, true);
350 
351         if (stencilWasEnabled) mCaches.stencil.enableTest();
352         mDirty = true;
353     }
354 #endif
355 
getLightCenter()356     const Vector3& getLightCenter() const { return mState.currentLightCenter(); }
getLightRadius()357     float getLightRadius() const { return mLightRadius; }
getAmbientShadowAlpha()358     uint8_t getAmbientShadowAlpha() const { return mAmbientShadowAlpha; }
getSpotShadowAlpha()359     uint8_t getSpotShadowAlpha() const { return mSpotShadowAlpha; }
360 
361     ///////////////////////////////////////////////////////////////////
362     /// State manipulation
363 
364     int getSaveCount() const;
365     int save(int flags);
366     void restore();
367     void restoreToCount(int saveCount);
368 
getMatrix(SkMatrix * outMatrix)369     void getMatrix(SkMatrix* outMatrix) const { mState.getMatrix(outMatrix); }
setMatrix(const SkMatrix & matrix)370     void setMatrix(const SkMatrix& matrix) { mState.setMatrix(matrix); }
371     void setLocalMatrix(const SkMatrix& matrix);
concatMatrix(const SkMatrix & matrix)372     void concatMatrix(const SkMatrix& matrix) { mState.concatMatrix(matrix); }
373 
374     void translate(float dx, float dy, float dz = 0.0f);
375     void rotate(float degrees);
376     void scale(float sx, float sy);
377     void skew(float sx, float sy);
378 
379     void setMatrix(const Matrix4& matrix); // internal only convenience method
380     void concatMatrix(const Matrix4& matrix); // internal only convenience method
381 
getLocalClipBounds()382     const Rect& getLocalClipBounds() const { return mState.getLocalClipBounds(); }
getRenderTargetClipBounds()383     const Rect& getRenderTargetClipBounds() const { return mState.getRenderTargetClipBounds(); }
quickRejectConservative(float left,float top,float right,float bottom)384     bool quickRejectConservative(float left, float top,
385             float right, float bottom) const {
386         return mState.quickRejectConservative(left, top, right, bottom);
387     }
388 
389     bool clipRect(float left, float top,
390             float right, float bottom, SkRegion::Op op);
391     bool clipPath(const SkPath* path, SkRegion::Op op);
392     bool clipRegion(const SkRegion* region, SkRegion::Op op);
393 
394     /**
395      * Does not support different clipping Ops (that is, every call to setClippingOutline is
396      * effectively using SkRegion::kReplaceOp)
397      *
398      * The clipping outline is independent from the regular clip.
399      */
400     void setClippingOutline(LinearAllocator& allocator, const Outline* outline);
401     void setClippingRoundRect(LinearAllocator& allocator,
402             const Rect& rect, float radius, bool highPriority = true);
403     void setProjectionPathMask(LinearAllocator& allocator, const SkPath* path);
404 
hasRectToRectTransform()405     inline bool hasRectToRectTransform() const { return mState.hasRectToRectTransform(); }
currentTransform()406     inline const mat4* currentTransform() const { return mState.currentTransform(); }
407 
408     ///////////////////////////////////////////////////////////////////
409     /// CanvasStateClient interface
410 
411     virtual void onViewportInitialized() override;
412     virtual void onSnapshotRestored(const Snapshot& removed, const Snapshot& restored) override;
getTargetFbo()413     virtual GLuint getTargetFbo() const override { return 0; }
414 
allocPathForFrame()415     SkPath* allocPathForFrame() {
416         std::unique_ptr<SkPath> path(new SkPath());
417         SkPath* returnPath = path.get();
418         mTempPaths.push_back(std::move(path));
419         return returnPath;
420     }
421 
setBaseTransform(const Matrix4 & matrix)422     void setBaseTransform(const Matrix4& matrix) { mBaseTransform = matrix; }
423 
424 protected:
425     /**
426      * Perform the setup specific to a frame. This method does not
427      * issue any OpenGL commands.
428      */
429     void setupFrameState(float left, float top, float right, float bottom, bool opaque);
430 
431     /**
432      * Indicates the start of rendering. This method will setup the
433      * initial OpenGL state (viewport, clearing the buffer, etc.)
434      */
435     void startFrame();
436 
437     /**
438      * Clears the underlying surface if needed.
439      */
440     virtual void clear(float left, float top, float right, float bottom, bool opaque);
441 
442     /**
443      * Call this method after updating a layer during a drawing pass.
444      */
445     void resumeAfterLayer();
446 
447     /**
448      * This method is called whenever a stencil buffer is required. Subclasses
449      * should override this method and call attachStencilBufferToLayer() on the
450      * appropriate layer(s).
451      */
452     virtual void ensureStencilBuffer();
453 
454     /**
455      * Obtains a stencil render buffer (allocating it if necessary) and
456      * attaches it to the specified layer.
457      */
458     void attachStencilBufferToLayer(Layer* layer);
459 
460     /**
461      * Draw a rectangle list. Currently only used for the the stencil buffer so that the stencil
462      * will have a value of 'n' in every unclipped pixel, where 'n' is the number of rectangles
463      * in the list.
464      */
465     void drawRectangleList(const RectangleList& rectangleList);
466 
467     bool quickRejectSetupScissor(float left, float top, float right, float bottom,
468             const SkPaint* paint = nullptr);
469     bool quickRejectSetupScissor(const Rect& bounds, const SkPaint* paint = nullptr) {
470         return quickRejectSetupScissor(bounds.left, bounds.top,
471                 bounds.right, bounds.bottom, paint);
472     }
473 
474     /**
475      * Compose the layer defined in the current snapshot with the layer
476      * defined by the previous snapshot.
477      *
478      * The current snapshot *must* be a layer (flag kFlagIsLayer set.)
479      *
480      * @param curent The current snapshot containing the layer to compose
481      * @param previous The previous snapshot to compose the current layer with
482      */
483     virtual void composeLayer(const Snapshot& current, const Snapshot& previous);
484 
485     /**
486      * Marks the specified region as dirty at the specified bounds.
487      */
488     void dirtyLayerUnchecked(Rect& bounds, Region* region);
489 
490     /**
491      * Returns the region of the current layer.
492      */
getRegion()493     virtual Region* getRegion() const {
494         return mState.currentRegion();
495     }
496 
497     /**
498      * Indicates whether rendering is currently targeted at a layer.
499      */
hasLayer()500     virtual bool hasLayer() const {
501         return (mState.currentFlags() & Snapshot::kFlagFboTarget) && mState.currentRegion();
502     }
503 
504     /**
505      * Renders the specified layer as a textured quad.
506      *
507      * @param layer The layer to render
508      * @param rect The bounds of the layer
509      */
510     void drawTextureLayer(Layer* layer, const Rect& rect);
511 
512     /**
513      * Gets the alpha and xfermode out of a paint object. If the paint is null
514      * alpha will be 255 and the xfermode will be SRC_OVER. Accounts for snapshot alpha.
515      *
516      * @param paint The paint to extract values from
517      * @param alpha Where to store the resulting alpha
518      * @param mode Where to store the resulting xfermode
519      */
520     inline void getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) const;
521 
522     /**
523      * Gets the alpha from a layer, accounting for snapshot alpha
524      *
525      * @param layer The layer from which the alpha is extracted
526      */
527     inline float getLayerAlpha(const Layer* layer) const;
528 
529     /**
530      * Set to true to suppress error checks at the end of a frame.
531      */
suppressErrorChecks()532     virtual bool suppressErrorChecks() const {
533         return false;
534     }
535 
536     CanvasState mState;
537     Caches& mCaches;
538     RenderState& mRenderState;
539 
540 private:
541     enum class GlopRenderType {
542         Standard,
543         Multi,
544         LayerClear
545     };
546 
547     void renderGlop(const Glop& glop, GlopRenderType type = GlopRenderType::Standard);
548 
549     /**
550      * Discards the content of the framebuffer if supported by the driver.
551      * This method should be called at the beginning of a frame to optimize
552      * rendering on some tiler architectures.
553      */
554     void discardFramebuffer(float left, float top, float right, float bottom);
555 
556     /**
557      * Tells the GPU what part of the screen is about to be redrawn.
558      * This method will use the current layer space clip rect.
559      * This method needs to be invoked every time getTargetFbo() is
560      * bound again.
561      */
562     void startTilingCurrentClip(bool opaque = false, bool expand = false);
563 
564     /**
565      * Tells the GPU what part of the screen is about to be redrawn.
566      * This method needs to be invoked every time getTargetFbo() is
567      * bound again.
568      */
569     void startTiling(const Rect& clip, int windowHeight, bool opaque = false, bool expand = false);
570 
571     /**
572      * Tells the GPU that we are done drawing the frame or that we
573      * are switching to another render target.
574      */
575     void endTiling();
576 
577     /**
578      * Sets the clipping rectangle using glScissor. The clip is defined by
579      * the current snapshot's clipRect member.
580      */
581     void setScissorFromClip();
582 
583     /**
584      * Sets the clipping region using the stencil buffer. The clip region
585      * is defined by the current snapshot's clipRegion member.
586      */
587     void setStencilFromClip();
588 
589     /**
590      * Given the local bounds of the layer, calculates ...
591      */
592     void calculateLayerBoundsAndClip(Rect& bounds, Rect& clip, bool fboLayer);
593 
594     /**
595      * Given the local bounds + clip of the layer, updates current snapshot's empty/invisible
596      */
597     void updateSnapshotIgnoreForLayer(const Rect& bounds, const Rect& clip,
598             bool fboLayer, int alpha);
599 
600     /**
601      * Creates a new layer stored in the specified snapshot.
602      *
603      * @param snapshot The snapshot associated with the new layer
604      * @param left The left coordinate of the layer
605      * @param top The top coordinate of the layer
606      * @param right The right coordinate of the layer
607      * @param bottom The bottom coordinate of the layer
608      * @param alpha The translucency of the layer
609      * @param mode The blending mode of the layer
610      * @param flags The layer save flags
611      * @param mask A mask to use when drawing the layer back, may be empty
612      *
613      * @return True if the layer was successfully created, false otherwise
614      */
615     bool createLayer(float left, float top, float right, float bottom,
616             const SkPaint* paint, int flags, const SkPath* convexMask);
617 
618     /**
619      * Creates a new layer stored in the specified snapshot as an FBO.
620      *
621      * @param layer The layer to store as an FBO
622      * @param snapshot The snapshot associated with the new layer
623      * @param bounds The bounds of the layer
624      */
625     bool createFboLayer(Layer* layer, Rect& bounds, Rect& clip);
626 
627     /**
628      * Compose the specified layer as a region.
629      *
630      * @param layer The layer to compose
631      * @param rect The layer's bounds
632      */
633     void composeLayerRegion(Layer* layer, const Rect& rect);
634 
635     /**
636      * Restores the content in layer to the screen, swapping the blend mode,
637      * specifically used in the restore() of a saveLayerAlpha().
638      *
639      * This allows e.g. a layer that would have been drawn on top of existing content (with SrcOver)
640      * to be drawn underneath.
641      *
642      * This will always ignore the canvas transform.
643      */
644     void composeLayerRectSwapped(Layer* layer, const Rect& rect);
645 
646     /**
647      * Draws the content in layer to the screen.
648      */
649     void composeLayerRect(Layer* layer, const Rect& rect);
650 
651     /**
652      * Clears all the regions corresponding to the current list of layers.
653      * This method MUST be invoked before any drawing operation.
654      */
655     void clearLayerRegions();
656 
657     /**
658      * Mark the layer as dirty at the specified coordinates. The coordinates
659      * are transformed with the supplied matrix.
660      */
661     void dirtyLayer(const float left, const float top,
662             const float right, const float bottom, const Matrix4& transform);
663 
664     /**
665      * Mark the layer as dirty at the specified coordinates.
666      */
667     void dirtyLayer(const float left, const float top,
668             const float right, const float bottom);
669 
670     /**
671      * Draws a colored rectangle with the specified color. The specified coordinates
672      * are transformed by the current snapshot's transform matrix unless specified
673      * otherwise.
674      *
675      * @param left The left coordinate of the rectangle
676      * @param top The top coordinate of the rectangle
677      * @param right The right coordinate of the rectangle
678      * @param bottom The bottom coordinate of the rectangle
679      * @param paint The paint containing the color, blending mode, etc.
680      * @param ignoreTransform True if the current transform should be ignored
681      */
682     void drawColorRect(float left, float top, float right, float bottom,
683             const SkPaint* paint, bool ignoreTransform = false);
684 
685     /**
686      * Draws a series of colored rectangles with the specified color. The specified
687      * coordinates are transformed by the current snapshot's transform matrix unless
688      * specified otherwise.
689      *
690      * @param rects A list of rectangles, 4 floats (left, top, right, bottom)
691      *              per rectangle
692      * @param paint The paint containing the color, blending mode, etc.
693      * @param ignoreTransform True if the current transform should be ignored
694      * @param dirty True if calling this method should dirty the current layer
695      * @param clip True if the rects should be clipped, false otherwise
696      */
697     void drawColorRects(const float* rects, int count, const SkPaint* paint,
698             bool ignoreTransform = false, bool dirty = true, bool clip = true);
699 
700     /**
701      * Draws the shape represented by the specified path texture.
702      * This method invokes drawPathTexture() but takes into account
703      * the extra left/top offset and the texture offset to correctly
704      * position the final shape.
705      *
706      * @param left The left coordinate of the shape to render
707      * @param top The top coordinate of the shape to render
708      * @param texture The texture reprsenting the shape
709      * @param paint The paint to draw the shape with
710      */
711     void drawShape(float left, float top, PathTexture* texture, const SkPaint* paint);
712 
713     /**
714      * Renders a strip of polygons with the specified paint, used for tessellated geometry.
715      *
716      * @param vertexBuffer The VertexBuffer to be drawn
717      * @param paint The paint to render with
718      * @param flags flags with which to draw
719      */
720     void drawVertexBuffer(float translateX, float translateY, const VertexBuffer& vertexBuffer,
721             const SkPaint* paint, int flags = 0);
722 
723     /**
724      * Convenience for translating method
725      */
726     void drawVertexBuffer(const VertexBuffer& vertexBuffer,
727             const SkPaint* paint, int flags = 0) {
728         drawVertexBuffer(0.0f, 0.0f, vertexBuffer, paint, flags);
729     }
730 
731     /**
732      * Renders the convex hull defined by the specified path as a strip of polygons.
733      *
734      * @param path The hull of the path to draw
735      * @param paint The paint to render with
736      */
737     void drawConvexPath(const SkPath& path, const SkPaint* paint);
738 
739     /**
740      * Draws text underline and strike-through if needed.
741      *
742      * @param text The text to decor
743      * @param bytesCount The number of bytes in the text
744      * @param totalAdvance The total advance in pixels, defines underline/strikethrough length
745      * @param x The x coordinate where the text will be drawn
746      * @param y The y coordinate where the text will be drawn
747      * @param paint The paint to draw the text with
748      */
749     void drawTextDecorations(float totalAdvance, float x, float y, const SkPaint* paint);
750 
751    /**
752      * Draws shadow layer on text (with optional positions).
753      *
754      * @param paint The paint to draw the shadow with
755      * @param text The text to draw
756      * @param bytesCount The number of bytes in the text
757      * @param count The number of glyphs in the text
758      * @param positions The x, y positions of individual glyphs (or NULL)
759      * @param fontRenderer The font renderer object
760      * @param alpha The alpha value for drawing the shadow
761      * @param x The x coordinate where the shadow will be drawn
762      * @param y The y coordinate where the shadow will be drawn
763      */
764     void drawTextShadow(const SkPaint* paint, const char* text, int bytesCount, int count,
765             const float* positions, FontRenderer& fontRenderer, int alpha,
766             float x, float y);
767 
768     /**
769      * Draws a path texture. Path textures are alpha8 bitmaps that need special
770      * compositing to apply colors/filters/etc.
771      *
772      * @param texture The texture to render
773      * @param x The x coordinate where the texture will be drawn
774      * @param y The y coordinate where the texture will be drawn
775      * @param paint The paint to draw the texture with
776      */
777      void drawPathTexture(PathTexture* texture, float x, float y, const SkPaint* paint);
778 
779     /**
780      * Resets the texture coordinates stored in mMeshVertices. Setting the values
781      * back to default is achieved by calling:
782      *
783      * resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
784      *
785      * @param u1 The left coordinate of the texture
786      * @param v1 The bottom coordinate of the texture
787      * @param u2 The right coordinate of the texture
788      * @param v2 The top coordinate of the texture
789      */
790     void resetDrawTextureTexCoords(float u1, float v1, float u2, float v2);
791 
792     /**
793      * Returns true if the specified paint will draw invisible text.
794      */
795     bool canSkipText(const SkPaint* paint) const;
796 
797     bool updateLayer(Layer* layer, bool inFrame);
798     void updateLayers();
799     void flushLayers();
800 
801 #if DEBUG_LAYERS_AS_REGIONS
802     /**
803      * Renders the specified region as a series of rectangles. This method
804      * is used for debugging only.
805      */
806     void drawRegionRectsDebug(const Region& region);
807 #endif
808 
809     /**
810      * Renders the specified region as a series of rectangles. The region
811      * must be in screen-space coordinates.
812      */
813     void drawRegionRects(const SkRegion& region, const SkPaint& paint, bool dirty = false);
814 
815     /**
816      * Draws the current clip region if any. Only when DEBUG_CLIP_REGIONS
817      * is turned on.
818      */
819     void debugClip();
820 
821     void debugOverdraw(bool enable, bool clear);
822     void renderOverdraw();
823     void countOverdraw();
824 
825     /**
826      * Should be invoked every time the glScissor is modified.
827      */
dirtyClip()828     inline void dirtyClip() { mState.setDirtyClip(true); }
829 
getMapper(const Texture * texture)830     inline const UvMapper& getMapper(const Texture* texture) {
831         return texture && texture->uvMapper ? *texture->uvMapper : mUvMapper;
832     }
833 
834     /**
835      * Returns a texture object for the specified bitmap. The texture can
836      * come from the texture cache or an atlas. If this method returns
837      * NULL, the texture could not be found and/or allocated.
838      */
839     Texture* getTexture(const SkBitmap* bitmap);
840 
reportAndClearDirty()841     bool reportAndClearDirty() { bool ret = mDirty; mDirty = false; return ret; }
writableSnapshot()842     inline Snapshot* writableSnapshot() { return mState.writableSnapshot(); }
currentSnapshot()843     inline const Snapshot* currentSnapshot() const { return mState.currentSnapshot(); }
844 
845     // State used to define the clipping region
846     Rect mTilingClip;
847     // Is the target render surface opaque
848     bool mOpaque;
849     // Is a frame currently being rendered
850     bool mFrameStarted;
851 
852     // Default UV mapper
853     const UvMapper mUvMapper;
854 
855     // List of rectangles to clear after saveLayer() is invoked
856     std::vector<Rect> mLayers;
857     // List of layers to update at the beginning of a frame
858     Vector< sp<Layer> > mLayerUpdates;
859 
860     // See PROPERTY_DISABLE_SCISSOR_OPTIMIZATION in
861     // Properties.h
862     bool mScissorOptimizationDisabled;
863 
864     // No-ops start/endTiling when set
865     bool mSuppressTiling;
866     bool mFirstFrameAfterResize;
867 
868     bool mSkipOutlineClip;
869 
870     // True if anything has been drawn since the last call to
871     // reportAndClearDirty()
872     bool mDirty;
873 
874     // Lighting + shadows
875     Vector3 mLightCenter;
876     float mLightRadius;
877     uint8_t mAmbientShadowAlpha;
878     uint8_t mSpotShadowAlpha;
879 
880     // Paths kept alive for the duration of the frame
881     std::vector<std::unique_ptr<SkPath>> mTempPaths;
882 
883     /**
884      * Initial transform for a rendering pass; transform from global device
885      * coordinates to the current RenderNode's drawing content coordinates,
886      * with the RenderNode's RenderProperty transforms already applied.
887      * Calling setMatrix(mBaseTransform) will result in drawing at the origin
888      * of the DisplayList's recorded surface prior to any Canvas
889      * transformation.
890      */
891     Matrix4 mBaseTransform;
892 
893     friend class Layer;
894     friend class TextDrawFunctor;
895     friend class DrawBitmapOp;
896     friend class DrawPatchOp;
897 
898 }; // class OpenGLRenderer
899 
900 }; // namespace uirenderer
901 }; // namespace android
902 
903 #endif // ANDROID_HWUI_OPENGL_RENDERER_H
904