OpenGLRenderer.cpp revision 031888744e24b5c7243ac99ec98b78aff5db1c78
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#include "OpenGLRenderer.h"
18
19#include "DeferredDisplayList.h"
20#include "DisplayListRenderer.h"
21#include "Fence.h"
22#include "GammaFontRenderer.h"
23#include "Glop.h"
24#include "GlopBuilder.h"
25#include "Patch.h"
26#include "PathTessellator.h"
27#include "Properties.h"
28#include "RenderNode.h"
29#include "renderstate/MeshState.h"
30#include "renderstate/RenderState.h"
31#include "ShadowTessellator.h"
32#include "SkiaShader.h"
33#include "Vector.h"
34#include "VertexBuffer.h"
35#include "utils/GLUtils.h"
36#include "utils/PaintUtils.h"
37#include "utils/TraceUtils.h"
38
39#include <stdlib.h>
40#include <stdint.h>
41#include <sys/types.h>
42
43#include <SkCanvas.h>
44#include <SkColor.h>
45#include <SkShader.h>
46#include <SkTypeface.h>
47
48#include <utils/Log.h>
49#include <utils/StopWatch.h>
50
51#include <private/hwui/DrawGlInfo.h>
52
53#include <ui/Rect.h>
54
55#if DEBUG_DETAILED_EVENTS
56    #define EVENT_LOGD(...) eventMarkDEBUG(__VA_ARGS__)
57#else
58    #define EVENT_LOGD(...)
59#endif
60
61namespace android {
62namespace uirenderer {
63
64static GLenum getFilter(const SkPaint* paint) {
65    if (!paint || paint->getFilterLevel() != SkPaint::kNone_FilterLevel) {
66        return GL_LINEAR;
67    }
68    return GL_NEAREST;
69}
70
71///////////////////////////////////////////////////////////////////////////////
72// Globals
73///////////////////////////////////////////////////////////////////////////////
74
75
76///////////////////////////////////////////////////////////////////////////////
77// Functions
78///////////////////////////////////////////////////////////////////////////////
79
80template<typename T>
81static inline T min(T a, T b) {
82    return a < b ? a : b;
83}
84
85///////////////////////////////////////////////////////////////////////////////
86// Constructors/destructor
87///////////////////////////////////////////////////////////////////////////////
88
89OpenGLRenderer::OpenGLRenderer(RenderState& renderState)
90        : mState(*this)
91        , mCaches(Caches::getInstance())
92        , mExtensions(Extensions::getInstance())
93        , mRenderState(renderState)
94        , mFrameStarted(false)
95        , mScissorOptimizationDisabled(false)
96        , mSuppressTiling(false)
97        , mFirstFrameAfterResize(true)
98        , mDirty(false)
99        , mLightCenter((Vector3){FLT_MIN, FLT_MIN, FLT_MIN})
100        , mLightRadius(FLT_MIN)
101        , mAmbientShadowAlpha(0)
102        , mSpotShadowAlpha(0) {
103    // *set* draw modifiers to be 0
104    memset(&mDrawModifiers, 0, sizeof(mDrawModifiers));
105    mDrawModifiers.mOverrideLayerAlpha = 1.0f;
106
107    memcpy(mMeshVertices, kUnitQuadVertices, sizeof(kUnitQuadVertices));
108}
109
110OpenGLRenderer::~OpenGLRenderer() {
111    // The context has already been destroyed at this point, do not call
112    // GL APIs. All GL state should be kept in Caches.h
113}
114
115void OpenGLRenderer::initProperties() {
116    char property[PROPERTY_VALUE_MAX];
117    if (property_get(PROPERTY_DISABLE_SCISSOR_OPTIMIZATION, property, "false")) {
118        mScissorOptimizationDisabled = !strcasecmp(property, "true");
119        INIT_LOGD("  Scissor optimization %s",
120                mScissorOptimizationDisabled ? "disabled" : "enabled");
121    } else {
122        INIT_LOGD("  Scissor optimization enabled");
123    }
124}
125
126void OpenGLRenderer::initLight(const Vector3& lightCenter, float lightRadius,
127        uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) {
128    mLightCenter = lightCenter;
129    mLightRadius = lightRadius;
130    mAmbientShadowAlpha = ambientShadowAlpha;
131    mSpotShadowAlpha = spotShadowAlpha;
132}
133
134///////////////////////////////////////////////////////////////////////////////
135// Setup
136///////////////////////////////////////////////////////////////////////////////
137
138void OpenGLRenderer::onViewportInitialized() {
139    glDisable(GL_DITHER);
140    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
141    mFirstFrameAfterResize = true;
142}
143
144void OpenGLRenderer::setupFrameState(float left, float top,
145        float right, float bottom, bool opaque) {
146    mCaches.clearGarbage();
147    mState.initializeSaveStack(left, top, right, bottom, mLightCenter);
148    mOpaque = opaque;
149    mTilingClip.set(left, top, right, bottom);
150}
151
152void OpenGLRenderer::startFrame() {
153    if (mFrameStarted) return;
154    mFrameStarted = true;
155
156    mState.setDirtyClip(true);
157
158    discardFramebuffer(mTilingClip.left, mTilingClip.top, mTilingClip.right, mTilingClip.bottom);
159
160    mRenderState.setViewport(mState.getWidth(), mState.getHeight());
161
162    // Functors break the tiling extension in pretty spectacular ways
163    // This ensures we don't use tiling when a functor is going to be
164    // invoked during the frame
165    mSuppressTiling = mCaches.hasRegisteredFunctors()
166            || mFirstFrameAfterResize;
167    mFirstFrameAfterResize = false;
168
169    startTilingCurrentClip(true);
170
171    debugOverdraw(true, true);
172
173    clear(mTilingClip.left, mTilingClip.top,
174            mTilingClip.right, mTilingClip.bottom, mOpaque);
175}
176
177void OpenGLRenderer::prepareDirty(float left, float top,
178        float right, float bottom, bool opaque) {
179
180    setupFrameState(left, top, right, bottom, opaque);
181
182    // Layer renderers will start the frame immediately
183    // The framebuffer renderer will first defer the display list
184    // for each layer and wait until the first drawing command
185    // to start the frame
186    if (currentSnapshot()->fbo == 0) {
187        mRenderState.blend().syncEnabled();
188        updateLayers();
189    } else {
190        startFrame();
191    }
192}
193
194void OpenGLRenderer::discardFramebuffer(float left, float top, float right, float bottom) {
195    // If we know that we are going to redraw the entire framebuffer,
196    // perform a discard to let the driver know we don't need to preserve
197    // the back buffer for this frame.
198    if (mExtensions.hasDiscardFramebuffer() &&
199            left <= 0.0f && top <= 0.0f && right >= mState.getWidth() && bottom >= mState.getHeight()) {
200        const bool isFbo = onGetTargetFbo() == 0;
201        const GLenum attachments[] = {
202                isFbo ? (const GLenum) GL_COLOR_EXT : (const GLenum) GL_COLOR_ATTACHMENT0,
203                isFbo ? (const GLenum) GL_STENCIL_EXT : (const GLenum) GL_STENCIL_ATTACHMENT };
204        glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments);
205    }
206}
207
208void OpenGLRenderer::clear(float left, float top, float right, float bottom, bool opaque) {
209    if (!opaque) {
210        mRenderState.scissor().setEnabled(true);
211        mRenderState.scissor().set(left, getViewportHeight() - bottom, right - left, bottom - top);
212        glClear(GL_COLOR_BUFFER_BIT);
213        mDirty = true;
214        return;
215    }
216
217    mRenderState.scissor().reset();
218}
219
220void OpenGLRenderer::startTilingCurrentClip(bool opaque, bool expand) {
221    if (!mSuppressTiling) {
222        const Snapshot* snapshot = currentSnapshot();
223
224        const Rect* clip = &mTilingClip;
225        if (snapshot->flags & Snapshot::kFlagFboTarget) {
226            clip = &(snapshot->layer->clipRect);
227        }
228
229        startTiling(*clip, getViewportHeight(), opaque, expand);
230    }
231}
232
233void OpenGLRenderer::startTiling(const Rect& clip, int windowHeight, bool opaque, bool expand) {
234    if (!mSuppressTiling) {
235        if(expand) {
236            // Expand the startTiling region by 1
237            int leftNotZero = (clip.left > 0) ? 1 : 0;
238            int topNotZero = (windowHeight - clip.bottom > 0) ? 1 : 0;
239
240            mCaches.startTiling(
241                clip.left - leftNotZero,
242                windowHeight - clip.bottom - topNotZero,
243                clip.right - clip.left + leftNotZero + 1,
244                clip.bottom - clip.top + topNotZero + 1,
245                opaque);
246        } else {
247            mCaches.startTiling(clip.left, windowHeight - clip.bottom,
248                clip.right - clip.left, clip.bottom - clip.top, opaque);
249        }
250    }
251}
252
253void OpenGLRenderer::endTiling() {
254    if (!mSuppressTiling) mCaches.endTiling();
255}
256
257bool OpenGLRenderer::finish() {
258    renderOverdraw();
259    endTiling();
260    mTempPaths.clear();
261
262    // When finish() is invoked on FBO 0 we've reached the end
263    // of the current frame
264    if (onGetTargetFbo() == 0) {
265        mCaches.pathCache.trim();
266        mCaches.tessellationCache.trim();
267    }
268
269    if (!suppressErrorChecks()) {
270#if DEBUG_OPENGL
271        GLUtils::dumpGLErrors();
272#endif
273
274#if DEBUG_MEMORY_USAGE
275        mCaches.dumpMemoryUsage();
276#else
277        if (mCaches.getDebugLevel() & kDebugMemory) {
278            mCaches.dumpMemoryUsage();
279        }
280#endif
281    }
282
283    mFrameStarted = false;
284
285    return reportAndClearDirty();
286}
287
288void OpenGLRenderer::resumeAfterLayer() {
289    mRenderState.setViewport(getViewportWidth(), getViewportHeight());
290    mRenderState.bindFramebuffer(currentSnapshot()->fbo);
291    debugOverdraw(true, false);
292
293    mRenderState.scissor().reset();
294    dirtyClip();
295}
296
297void OpenGLRenderer::callDrawGLFunction(Functor* functor, Rect& dirty) {
298    if (mState.currentlyIgnored()) return;
299
300    Rect clip(mState.currentClipRect());
301    clip.snapToPixelBoundaries();
302
303    // Since we don't know what the functor will draw, let's dirty
304    // the entire clip region
305    if (hasLayer()) {
306        dirtyLayerUnchecked(clip, getRegion());
307    }
308
309    DrawGlInfo info;
310    info.clipLeft = clip.left;
311    info.clipTop = clip.top;
312    info.clipRight = clip.right;
313    info.clipBottom = clip.bottom;
314    info.isLayer = hasLayer();
315    info.width = getViewportWidth();
316    info.height = getViewportHeight();
317    currentTransform()->copyTo(&info.transform[0]);
318
319    bool prevDirtyClip = mState.getDirtyClip();
320    // setup GL state for functor
321    if (mState.getDirtyClip()) {
322        setStencilFromClip(); // can issue draws, so must precede enableScissor()/interrupt()
323    }
324    if (mRenderState.scissor().setEnabled(true) || prevDirtyClip) {
325        setScissorFromClip();
326    }
327
328    mRenderState.invokeFunctor(functor, DrawGlInfo::kModeDraw, &info);
329    // Scissor may have been modified, reset dirty clip
330    dirtyClip();
331
332    mDirty = true;
333}
334
335///////////////////////////////////////////////////////////////////////////////
336// Debug
337///////////////////////////////////////////////////////////////////////////////
338
339void OpenGLRenderer::eventMarkDEBUG(const char* fmt, ...) const {
340#if DEBUG_DETAILED_EVENTS
341    const int BUFFER_SIZE = 256;
342    va_list ap;
343    char buf[BUFFER_SIZE];
344
345    va_start(ap, fmt);
346    vsnprintf(buf, BUFFER_SIZE, fmt, ap);
347    va_end(ap);
348
349    eventMark(buf);
350#endif
351}
352
353
354void OpenGLRenderer::eventMark(const char* name) const {
355    mCaches.eventMark(0, name);
356}
357
358void OpenGLRenderer::startMark(const char* name) const {
359    mCaches.startMark(0, name);
360}
361
362void OpenGLRenderer::endMark() const {
363    mCaches.endMark();
364}
365
366void OpenGLRenderer::debugOverdraw(bool enable, bool clear) {
367    mRenderState.debugOverdraw(enable, clear);
368}
369
370void OpenGLRenderer::renderOverdraw() {
371    if (mCaches.debugOverdraw && onGetTargetFbo() == 0) {
372        const Rect* clip = &mTilingClip;
373
374        mRenderState.scissor().setEnabled(true);
375        mRenderState.scissor().set(clip->left,
376                mState.firstSnapshot()->getViewportHeight() - clip->bottom,
377                clip->right - clip->left,
378                clip->bottom - clip->top);
379
380        // 1x overdraw
381        mRenderState.stencil().enableDebugTest(2);
382        drawColor(mCaches.getOverdrawColor(1), SkXfermode::kSrcOver_Mode);
383
384        // 2x overdraw
385        mRenderState.stencil().enableDebugTest(3);
386        drawColor(mCaches.getOverdrawColor(2), SkXfermode::kSrcOver_Mode);
387
388        // 3x overdraw
389        mRenderState.stencil().enableDebugTest(4);
390        drawColor(mCaches.getOverdrawColor(3), SkXfermode::kSrcOver_Mode);
391
392        // 4x overdraw and higher
393        mRenderState.stencil().enableDebugTest(4, true);
394        drawColor(mCaches.getOverdrawColor(4), SkXfermode::kSrcOver_Mode);
395
396        mRenderState.stencil().disable();
397    }
398}
399
400///////////////////////////////////////////////////////////////////////////////
401// Layers
402///////////////////////////////////////////////////////////////////////////////
403
404bool OpenGLRenderer::updateLayer(Layer* layer, bool inFrame) {
405    if (layer->deferredUpdateScheduled && layer->renderer
406            && layer->renderNode.get() && layer->renderNode->isRenderable()) {
407
408        if (inFrame) {
409            endTiling();
410            debugOverdraw(false, false);
411        }
412
413        if (CC_UNLIKELY(inFrame || mCaches.drawDeferDisabled)) {
414            layer->render(*this);
415        } else {
416            layer->defer(*this);
417        }
418
419        if (inFrame) {
420            resumeAfterLayer();
421            startTilingCurrentClip();
422        }
423
424        layer->debugDrawUpdate = mCaches.debugLayersUpdates;
425        layer->hasDrawnSinceUpdate = false;
426
427        return true;
428    }
429
430    return false;
431}
432
433void OpenGLRenderer::updateLayers() {
434    // If draw deferring is enabled this method will simply defer
435    // the display list of each individual layer. The layers remain
436    // in the layer updates list which will be cleared by flushLayers().
437    int count = mLayerUpdates.size();
438    if (count > 0) {
439        if (CC_UNLIKELY(mCaches.drawDeferDisabled)) {
440            startMark("Layer Updates");
441        } else {
442            startMark("Defer Layer Updates");
443        }
444
445        // Note: it is very important to update the layers in order
446        for (int i = 0; i < count; i++) {
447            Layer* layer = mLayerUpdates.itemAt(i).get();
448            updateLayer(layer, false);
449        }
450
451        if (CC_UNLIKELY(mCaches.drawDeferDisabled)) {
452            mLayerUpdates.clear();
453            mRenderState.bindFramebuffer(onGetTargetFbo());
454        }
455        endMark();
456    }
457}
458
459void OpenGLRenderer::flushLayers() {
460    int count = mLayerUpdates.size();
461    if (count > 0) {
462        startMark("Apply Layer Updates");
463
464        // Note: it is very important to update the layers in order
465        for (int i = 0; i < count; i++) {
466            mLayerUpdates.itemAt(i)->flush();
467        }
468
469        mLayerUpdates.clear();
470        mRenderState.bindFramebuffer(onGetTargetFbo());
471
472        endMark();
473    }
474}
475
476void OpenGLRenderer::pushLayerUpdate(Layer* layer) {
477    if (layer) {
478        // Make sure we don't introduce duplicates.
479        // SortedVector would do this automatically but we need to respect
480        // the insertion order. The linear search is not an issue since
481        // this list is usually very short (typically one item, at most a few)
482        for (int i = mLayerUpdates.size() - 1; i >= 0; i--) {
483            if (mLayerUpdates.itemAt(i) == layer) {
484                return;
485            }
486        }
487        mLayerUpdates.push_back(layer);
488    }
489}
490
491void OpenGLRenderer::cancelLayerUpdate(Layer* layer) {
492    if (layer) {
493        for (int i = mLayerUpdates.size() - 1; i >= 0; i--) {
494            if (mLayerUpdates.itemAt(i) == layer) {
495                mLayerUpdates.removeAt(i);
496                break;
497            }
498        }
499    }
500}
501
502void OpenGLRenderer::flushLayerUpdates() {
503    ATRACE_NAME("Update HW Layers");
504    mRenderState.blend().syncEnabled();
505    updateLayers();
506    flushLayers();
507    // Wait for all the layer updates to be executed
508    AutoFence fence;
509}
510
511void OpenGLRenderer::markLayersAsBuildLayers() {
512    for (size_t i = 0; i < mLayerUpdates.size(); i++) {
513        mLayerUpdates[i]->wasBuildLayered = true;
514    }
515}
516
517///////////////////////////////////////////////////////////////////////////////
518// State management
519///////////////////////////////////////////////////////////////////////////////
520
521void OpenGLRenderer::onSnapshotRestored(const Snapshot& removed, const Snapshot& restored) {
522    bool restoreViewport = removed.flags & Snapshot::kFlagIsFboLayer;
523    bool restoreClip = removed.flags & Snapshot::kFlagClipSet;
524    bool restoreLayer = removed.flags & Snapshot::kFlagIsLayer;
525
526    if (restoreViewport) {
527        mRenderState.setViewport(getViewportWidth(), getViewportHeight());
528    }
529
530    if (restoreClip) {
531        dirtyClip();
532    }
533
534    if (restoreLayer) {
535        endMark(); // Savelayer
536        ATRACE_END(); // SaveLayer
537        startMark("ComposeLayer");
538        composeLayer(removed, restored);
539        endMark();
540    }
541}
542
543///////////////////////////////////////////////////////////////////////////////
544// Layers
545///////////////////////////////////////////////////////////////////////////////
546
547int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
548        const SkPaint* paint, int flags, const SkPath* convexMask) {
549    // force matrix/clip isolation for layer
550    flags |= SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag;
551
552    const int count = mState.saveSnapshot(flags);
553
554    if (!mState.currentlyIgnored()) {
555        createLayer(left, top, right, bottom, paint, flags, convexMask);
556    }
557
558    return count;
559}
560
561void OpenGLRenderer::calculateLayerBoundsAndClip(Rect& bounds, Rect& clip, bool fboLayer) {
562    const Rect untransformedBounds(bounds);
563
564    currentTransform()->mapRect(bounds);
565
566    // Layers only make sense if they are in the framebuffer's bounds
567    if (bounds.intersect(mState.currentClipRect())) {
568        // We cannot work with sub-pixels in this case
569        bounds.snapToPixelBoundaries();
570
571        // When the layer is not an FBO, we may use glCopyTexImage so we
572        // need to make sure the layer does not extend outside the bounds
573        // of the framebuffer
574        const Snapshot& previous = *(currentSnapshot()->previous);
575        Rect previousViewport(0, 0, previous.getViewportWidth(), previous.getViewportHeight());
576        if (!bounds.intersect(previousViewport)) {
577            bounds.setEmpty();
578        } else if (fboLayer) {
579            clip.set(bounds);
580            mat4 inverse;
581            inverse.loadInverse(*currentTransform());
582            inverse.mapRect(clip);
583            clip.snapToPixelBoundaries();
584            if (clip.intersect(untransformedBounds)) {
585                clip.translate(-untransformedBounds.left, -untransformedBounds.top);
586                bounds.set(untransformedBounds);
587            } else {
588                clip.setEmpty();
589            }
590        }
591    } else {
592        bounds.setEmpty();
593    }
594}
595
596void OpenGLRenderer::updateSnapshotIgnoreForLayer(const Rect& bounds, const Rect& clip,
597        bool fboLayer, int alpha) {
598    if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize ||
599            bounds.getHeight() > mCaches.maxTextureSize ||
600            (fboLayer && clip.isEmpty())) {
601        writableSnapshot()->empty = fboLayer;
602    } else {
603        writableSnapshot()->invisible = writableSnapshot()->invisible || (alpha <= 0 && fboLayer);
604    }
605}
606
607int OpenGLRenderer::saveLayerDeferred(float left, float top, float right, float bottom,
608        const SkPaint* paint, int flags) {
609    const int count = mState.saveSnapshot(flags);
610
611    if (!mState.currentlyIgnored() && (flags & SkCanvas::kClipToLayer_SaveFlag)) {
612        // initialize the snapshot as though it almost represents an FBO layer so deferred draw
613        // operations will be able to store and restore the current clip and transform info, and
614        // quick rejection will be correct (for display lists)
615
616        Rect bounds(left, top, right, bottom);
617        Rect clip;
618        calculateLayerBoundsAndClip(bounds, clip, true);
619        updateSnapshotIgnoreForLayer(bounds, clip, true, getAlphaDirect(paint));
620
621        if (!mState.currentlyIgnored()) {
622            writableSnapshot()->resetTransform(-bounds.left, -bounds.top, 0.0f);
623            writableSnapshot()->resetClip(clip.left, clip.top, clip.right, clip.bottom);
624            writableSnapshot()->initializeViewport(bounds.getWidth(), bounds.getHeight());
625            writableSnapshot()->roundRectClipState = nullptr;
626        }
627    }
628
629    return count;
630}
631
632/**
633 * Layers are viewed by Skia are slightly different than layers in image editing
634 * programs (for instance.) When a layer is created, previously created layers
635 * and the frame buffer still receive every drawing command. For instance, if a
636 * layer is created and a shape intersecting the bounds of the layers and the
637 * framebuffer is draw, the shape will be drawn on both (unless the layer was
638 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
639 *
640 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
641 * texture. Unfortunately, this is inefficient as it requires every primitive to
642 * be drawn n + 1 times, where n is the number of active layers. In practice this
643 * means, for every primitive:
644 *   - Switch active frame buffer
645 *   - Change viewport, clip and projection matrix
646 *   - Issue the drawing
647 *
648 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
649 * To avoid this, layers are implemented in a different way here, at least in the
650 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
651 * is set. When this flag is set we can redirect all drawing operations into a
652 * single FBO.
653 *
654 * This implementation relies on the frame buffer being at least RGBA 8888. When
655 * a layer is created, only a texture is created, not an FBO. The content of the
656 * frame buffer contained within the layer's bounds is copied into this texture
657 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
658 * buffer and drawing continues as normal. This technique therefore treats the
659 * frame buffer as a scratch buffer for the layers.
660 *
661 * To compose the layers back onto the frame buffer, each layer texture
662 * (containing the original frame buffer data) is drawn as a simple quad over
663 * the frame buffer. The trick is that the quad is set as the composition
664 * destination in the blending equation, and the frame buffer becomes the source
665 * of the composition.
666 *
667 * Drawing layers with an alpha value requires an extra step before composition.
668 * An empty quad is drawn over the layer's region in the frame buffer. This quad
669 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
670 * quad is used to multiply the colors in the frame buffer. This is achieved by
671 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
672 * GL_ZERO, GL_SRC_ALPHA.
673 *
674 * Because glCopyTexImage2D() can be slow, an alternative implementation might
675 * be use to draw a single clipped layer. The implementation described above
676 * is correct in every case.
677 *
678 * (1) The frame buffer is actually not cleared right away. To allow the GPU
679 *     to potentially optimize series of calls to glCopyTexImage2D, the frame
680 *     buffer is left untouched until the first drawing operation. Only when
681 *     something actually gets drawn are the layers regions cleared.
682 */
683bool OpenGLRenderer::createLayer(float left, float top, float right, float bottom,
684        const SkPaint* paint, int flags, const SkPath* convexMask) {
685    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
686    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
687
688    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
689
690    // Window coordinates of the layer
691    Rect clip;
692    Rect bounds(left, top, right, bottom);
693    calculateLayerBoundsAndClip(bounds, clip, fboLayer);
694    updateSnapshotIgnoreForLayer(bounds, clip, fboLayer, getAlphaDirect(paint));
695
696    // Bail out if we won't draw in this snapshot
697    if (mState.currentlyIgnored()) {
698        return false;
699    }
700
701    mCaches.textureState().activateTexture(0);
702    Layer* layer = mCaches.layerCache.get(mRenderState, bounds.getWidth(), bounds.getHeight());
703    if (!layer) {
704        return false;
705    }
706
707    layer->setPaint(paint);
708    layer->layer.set(bounds);
709    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->getHeight()),
710            bounds.getWidth() / float(layer->getWidth()), 0.0f);
711
712    layer->setBlend(true);
713    layer->setDirty(false);
714    layer->setConvexMask(convexMask); // note: the mask must be cleared before returning to the cache
715
716    // Save the layer in the snapshot
717    writableSnapshot()->flags |= Snapshot::kFlagIsLayer;
718    writableSnapshot()->layer = layer;
719
720    ATRACE_FORMAT_BEGIN("%ssaveLayer %ux%u",
721            fboLayer ? "" : "unclipped ",
722            layer->getWidth(), layer->getHeight());
723    startMark("SaveLayer");
724    if (fboLayer) {
725        return createFboLayer(layer, bounds, clip);
726    } else {
727        // Copy the framebuffer into the layer
728        layer->bindTexture();
729        if (!bounds.isEmpty()) {
730            if (layer->isEmpty()) {
731                // Workaround for some GL drivers. When reading pixels lying outside
732                // of the window we should get undefined values for those pixels.
733                // Unfortunately some drivers will turn the entire target texture black
734                // when reading outside of the window.
735                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->getWidth(), layer->getHeight(),
736                        0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
737                layer->setEmpty(false);
738            }
739
740            glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0,
741                    bounds.left, getViewportHeight() - bounds.bottom,
742                    bounds.getWidth(), bounds.getHeight());
743
744            // Enqueue the buffer coordinates to clear the corresponding region later
745            mLayers.push_back(Rect(bounds));
746        }
747    }
748
749    return true;
750}
751
752bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, Rect& clip) {
753    layer->clipRect.set(clip);
754    layer->setFbo(mCaches.fboCache.get());
755
756    writableSnapshot()->region = &writableSnapshot()->layer->region;
757    writableSnapshot()->flags |= Snapshot::kFlagFboTarget | Snapshot::kFlagIsFboLayer;
758    writableSnapshot()->fbo = layer->getFbo();
759    writableSnapshot()->resetTransform(-bounds.left, -bounds.top, 0.0f);
760    writableSnapshot()->resetClip(clip.left, clip.top, clip.right, clip.bottom);
761    writableSnapshot()->initializeViewport(bounds.getWidth(), bounds.getHeight());
762    writableSnapshot()->roundRectClipState = nullptr;
763
764    endTiling();
765    debugOverdraw(false, false);
766    // Bind texture to FBO
767    mRenderState.bindFramebuffer(layer->getFbo());
768    layer->bindTexture();
769
770    // Initialize the texture if needed
771    if (layer->isEmpty()) {
772        layer->allocateTexture();
773        layer->setEmpty(false);
774    }
775
776    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
777            layer->getTexture(), 0);
778
779    // Expand the startTiling region by 1
780    startTilingCurrentClip(true, true);
781
782    // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
783    mRenderState.scissor().setEnabled(true);
784    mRenderState.scissor().set(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
785            clip.getWidth() + 2.0f, clip.getHeight() + 2.0f);
786    glClear(GL_COLOR_BUFFER_BIT);
787
788    dirtyClip();
789
790    // Change the ortho projection
791    mRenderState.setViewport(bounds.getWidth(), bounds.getHeight());
792    return true;
793}
794
795/**
796 * Read the documentation of createLayer() before doing anything in this method.
797 */
798void OpenGLRenderer::composeLayer(const Snapshot& removed, const Snapshot& restored) {
799    if (!removed.layer) {
800        ALOGE("Attempting to compose a layer that does not exist");
801        return;
802    }
803
804    Layer* layer = removed.layer;
805    const Rect& rect = layer->layer;
806    const bool fboLayer = removed.flags & Snapshot::kFlagIsFboLayer;
807
808    bool clipRequired = false;
809    mState.calculateQuickRejectForScissor(rect.left, rect.top, rect.right, rect.bottom,
810            &clipRequired, nullptr, false); // safely ignore return, should never be rejected
811    mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired);
812
813    if (fboLayer) {
814        endTiling();
815
816        // Detach the texture from the FBO
817        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
818
819        layer->removeFbo(false);
820
821        // Unbind current FBO and restore previous one
822        mRenderState.bindFramebuffer(restored.fbo);
823        debugOverdraw(true, false);
824
825        startTilingCurrentClip();
826    }
827
828    if (!fboLayer && layer->getAlpha() < 255) {
829        SkPaint layerPaint;
830        layerPaint.setAlpha(layer->getAlpha());
831        layerPaint.setXfermodeMode(SkXfermode::kDstIn_Mode);
832        layerPaint.setColorFilter(layer->getColorFilter());
833
834        drawColorRect(rect.left, rect.top, rect.right, rect.bottom, &layerPaint, true);
835        // Required below, composeLayerRect() will divide by 255
836        layer->setAlpha(255);
837    }
838
839    mRenderState.meshState().unbindMeshBuffer();
840
841    mCaches.textureState().activateTexture(0);
842
843    // When the layer is stored in an FBO, we can save a bit of fillrate by
844    // drawing only the dirty region
845    if (fboLayer) {
846        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *restored.transform);
847        composeLayerRegion(layer, rect);
848    } else if (!rect.isEmpty()) {
849        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
850
851        save(0);
852        // the layer contains screen buffer content that shouldn't be alpha modulated
853        // (and any necessary alpha modulation was handled drawing into the layer)
854        writableSnapshot()->alpha = 1.0f;
855        composeLayerRect(layer, rect, true);
856        restore();
857    }
858
859    dirtyClip();
860
861    // Failing to add the layer to the cache should happen only if the layer is too large
862    layer->setConvexMask(nullptr);
863    if (!mCaches.layerCache.put(layer)) {
864        LAYER_LOGD("Deleting layer");
865        layer->decStrong(nullptr);
866    }
867}
868
869void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) {
870    float alpha = getLayerAlpha(layer);
871
872    setupDraw();
873    if (layer->getRenderTarget() == GL_TEXTURE_2D) {
874        setupDrawWithTexture();
875    } else {
876        setupDrawWithExternalTexture();
877    }
878    setupDrawTextureTransform();
879    setupDrawColor(alpha, alpha, alpha, alpha);
880    setupDrawColorFilter(layer->getColorFilter());
881    setupDrawBlending(layer);
882    setupDrawProgram();
883    setupDrawPureColorUniforms();
884    setupDrawColorFilterUniforms(layer->getColorFilter());
885    if (layer->getRenderTarget() == GL_TEXTURE_2D) {
886        setupDrawTexture(layer->getTexture());
887    } else {
888        setupDrawExternalTexture(layer->getTexture());
889    }
890    if (currentTransform()->isPureTranslate() &&
891            !layer->getForceFilter() &&
892            layer->getWidth() == (uint32_t) rect.getWidth() &&
893            layer->getHeight() == (uint32_t) rect.getHeight()) {
894        const float x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f);
895        const float y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f);
896
897        layer->setFilter(GL_NEAREST);
898        setupDrawModelView(kModelViewMode_TranslateAndScale, false,
899                x, y, x + rect.getWidth(), y + rect.getHeight(), true);
900    } else {
901        layer->setFilter(GL_LINEAR);
902        setupDrawModelView(kModelViewMode_TranslateAndScale, false,
903                rect.left, rect.top, rect.right, rect.bottom);
904    }
905    setupDrawTextureTransformUniforms(layer->getTexTransform());
906    setupDrawMesh(&mMeshVertices[0].x, &mMeshVertices[0].u);
907
908    glDrawArrays(GL_TRIANGLE_STRIP, 0, kMeshCount);
909}
910
911void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
912    if (layer->isTextureLayer()) {
913        EVENT_LOGD("composeTextureLayerRect");
914        resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f);
915        drawTextureLayer(layer, rect);
916        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
917    } else {
918        EVENT_LOGD("composeHardwareLayerRect");
919        const Rect& texCoords = layer->texCoords;
920        resetDrawTextureTexCoords(texCoords.left, texCoords.top,
921                texCoords.right, texCoords.bottom);
922
923        float x = rect.left;
924        float y = rect.top;
925        bool simpleTransform = currentTransform()->isPureTranslate() &&
926                layer->getWidth() == (uint32_t) rect.getWidth() &&
927                layer->getHeight() == (uint32_t) rect.getHeight();
928
929        if (simpleTransform) {
930            // When we're swapping, the layer is already in screen coordinates
931            if (!swap) {
932                x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f);
933                y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f);
934            }
935
936            layer->setFilter(GL_NEAREST, true);
937        } else {
938            layer->setFilter(GL_LINEAR, true);
939        }
940
941        SkPaint layerPaint;
942        layerPaint.setAlpha(getLayerAlpha(layer) * 255);
943        layerPaint.setXfermodeMode(layer->getMode());
944        layerPaint.setColorFilter(layer->getColorFilter());
945
946        bool blend = layer->isBlend() || getLayerAlpha(layer) < 1.0f;
947        drawTextureMesh(x, y, x + rect.getWidth(), y + rect.getHeight(),
948                layer->getTexture(), &layerPaint, blend,
949                &mMeshVertices[0].x, &mMeshVertices[0].u,
950                GL_TRIANGLE_STRIP, kMeshCount, swap, swap || simpleTransform);
951
952        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
953    }
954}
955
956/**
957 * Issues the command X, and if we're composing a save layer to the fbo or drawing a newly updated
958 * hardware layer with overdraw debug on, draws again to the stencil only, so that these draw
959 * operations are correctly counted twice for overdraw. NOTE: assumes composeLayerRegion only used
960 * by saveLayer's restore
961 */
962#define DRAW_DOUBLE_STENCIL_IF(COND, DRAW_COMMAND) {                               \
963        DRAW_COMMAND;                                                              \
964        if (CC_UNLIKELY(mCaches.debugOverdraw && onGetTargetFbo() == 0 && COND)) { \
965            glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);                   \
966            DRAW_COMMAND;                                                          \
967            glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);                       \
968        }                                                                          \
969    }
970
971#define DRAW_DOUBLE_STENCIL(DRAW_COMMAND) DRAW_DOUBLE_STENCIL_IF(true, DRAW_COMMAND)
972
973// This class is purely for inspection. It inherits from SkShader, but Skia does not know how to
974// use it. The OpenGLRenderer will look at it to find its Layer and whether it is opaque.
975class LayerShader : public SkShader {
976public:
977    LayerShader(Layer* layer, const SkMatrix* localMatrix)
978    : INHERITED(localMatrix)
979    , mLayer(layer) {
980    }
981
982    virtual bool asACustomShader(void** data) const override {
983        if (data) {
984            *data = static_cast<void*>(mLayer);
985        }
986        return true;
987    }
988
989    virtual bool isOpaque() const override {
990        return !mLayer->isBlend();
991    }
992
993protected:
994    virtual void shadeSpan(int x, int y, SkPMColor[], int count) {
995        LOG_ALWAYS_FATAL("LayerShader should never be drawn with raster backend.");
996    }
997
998    virtual void flatten(SkWriteBuffer&) const override {
999        LOG_ALWAYS_FATAL("LayerShader should never be flattened.");
1000    }
1001
1002    virtual Factory getFactory() const override {
1003        LOG_ALWAYS_FATAL("LayerShader should never be created from a stream.");
1004        return nullptr;
1005    }
1006private:
1007    // Unowned.
1008    Layer* mLayer;
1009    typedef SkShader INHERITED;
1010};
1011
1012void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
1013    if (CC_UNLIKELY(layer->region.isEmpty())) return; // nothing to draw
1014
1015    if (layer->getConvexMask()) {
1016        save(SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag);
1017
1018        // clip to the area of the layer the mask can be larger
1019        clipRect(rect.left, rect.top, rect.right, rect.bottom, SkRegion::kIntersect_Op);
1020
1021        SkPaint paint;
1022        paint.setAntiAlias(true);
1023        paint.setColor(SkColorSetARGB(int(getLayerAlpha(layer) * 255), 0, 0, 0));
1024
1025        // create LayerShader to map SaveLayer content into subsequent draw
1026        SkMatrix shaderMatrix;
1027        shaderMatrix.setTranslate(rect.left, rect.bottom);
1028        shaderMatrix.preScale(1, -1);
1029        LayerShader layerShader(layer, &shaderMatrix);
1030        paint.setShader(&layerShader);
1031
1032        // Since the drawing primitive is defined in local drawing space,
1033        // we don't need to modify the draw matrix
1034        const SkPath* maskPath = layer->getConvexMask();
1035        DRAW_DOUBLE_STENCIL(drawConvexPath(*maskPath, &paint));
1036
1037        paint.setShader(nullptr);
1038        restore();
1039
1040        return;
1041    }
1042
1043    if (layer->region.isRect()) {
1044        layer->setRegionAsRect();
1045
1046        DRAW_DOUBLE_STENCIL(composeLayerRect(layer, layer->regionRect));
1047
1048        layer->region.clear();
1049        return;
1050    }
1051
1052    EVENT_LOGD("composeLayerRegion");
1053    // standard Region based draw
1054    size_t count;
1055    const android::Rect* rects;
1056    Region safeRegion;
1057    if (CC_LIKELY(hasRectToRectTransform())) {
1058        rects = layer->region.getArray(&count);
1059    } else {
1060        safeRegion = Region::createTJunctionFreeRegion(layer->region);
1061        rects = safeRegion.getArray(&count);
1062    }
1063
1064    const float alpha = getLayerAlpha(layer);
1065    const float texX = 1.0f / float(layer->getWidth());
1066    const float texY = 1.0f / float(layer->getHeight());
1067    const float height = rect.getHeight();
1068
1069    setupDraw();
1070
1071    // We must get (and therefore bind) the region mesh buffer
1072    // after we setup drawing in case we need to mess with the
1073    // stencil buffer in setupDraw()
1074    TextureVertex* mesh = mCaches.getRegionMesh();
1075    uint32_t numQuads = 0;
1076
1077    setupDrawWithTexture();
1078    setupDrawColor(alpha, alpha, alpha, alpha);
1079    setupDrawColorFilter(layer->getColorFilter());
1080    setupDrawBlending(layer);
1081    setupDrawProgram();
1082    setupDrawDirtyRegionsDisabled();
1083    setupDrawPureColorUniforms();
1084    setupDrawColorFilterUniforms(layer->getColorFilter());
1085    setupDrawTexture(layer->getTexture());
1086    if (currentTransform()->isPureTranslate()) {
1087        const float x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f);
1088        const float y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f);
1089
1090        layer->setFilter(GL_NEAREST);
1091        setupDrawModelView(kModelViewMode_Translate, false,
1092                x, y, x + rect.getWidth(), y + rect.getHeight(), true);
1093    } else {
1094        layer->setFilter(GL_LINEAR);
1095        setupDrawModelView(kModelViewMode_Translate, false,
1096                rect.left, rect.top, rect.right, rect.bottom);
1097    }
1098    setupDrawMeshIndices(&mesh[0].x, &mesh[0].u);
1099
1100    for (size_t i = 0; i < count; i++) {
1101        const android::Rect* r = &rects[i];
1102
1103        const float u1 = r->left * texX;
1104        const float v1 = (height - r->top) * texY;
1105        const float u2 = r->right * texX;
1106        const float v2 = (height - r->bottom) * texY;
1107
1108        // TODO: Reject quads outside of the clip
1109        TextureVertex::set(mesh++, r->left, r->top, u1, v1);
1110        TextureVertex::set(mesh++, r->right, r->top, u2, v1);
1111        TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
1112        TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
1113
1114        numQuads++;
1115
1116        if (numQuads >= kMaxNumberOfQuads) {
1117            DRAW_DOUBLE_STENCIL(glDrawElements(GL_TRIANGLES, numQuads * 6,
1118                    GL_UNSIGNED_SHORT, nullptr));
1119            numQuads = 0;
1120            mesh = mCaches.getRegionMesh();
1121        }
1122    }
1123
1124    if (numQuads > 0) {
1125        DRAW_DOUBLE_STENCIL(glDrawElements(GL_TRIANGLES, numQuads * 6,
1126                GL_UNSIGNED_SHORT, nullptr));
1127    }
1128
1129#if DEBUG_LAYERS_AS_REGIONS
1130    drawRegionRectsDebug(layer->region);
1131#endif
1132
1133    layer->region.clear();
1134}
1135
1136#if DEBUG_LAYERS_AS_REGIONS
1137void OpenGLRenderer::drawRegionRectsDebug(const Region& region) {
1138    size_t count;
1139    const android::Rect* rects = region.getArray(&count);
1140
1141    uint32_t colors[] = {
1142            0x7fff0000, 0x7f00ff00,
1143            0x7f0000ff, 0x7fff00ff,
1144    };
1145
1146    int offset = 0;
1147    int32_t top = rects[0].top;
1148
1149    for (size_t i = 0; i < count; i++) {
1150        if (top != rects[i].top) {
1151            offset ^= 0x2;
1152            top = rects[i].top;
1153        }
1154
1155        SkPaint paint;
1156        paint.setColor(colors[offset + (i & 0x1)]);
1157        Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
1158        drawColorRect(r.left, r.top, r.right, r.bottom, paint);
1159    }
1160}
1161#endif
1162
1163void OpenGLRenderer::drawRegionRects(const SkRegion& region, const SkPaint& paint, bool dirty) {
1164    Vector<float> rects;
1165
1166    SkRegion::Iterator it(region);
1167    while (!it.done()) {
1168        const SkIRect& r = it.rect();
1169        rects.push(r.fLeft);
1170        rects.push(r.fTop);
1171        rects.push(r.fRight);
1172        rects.push(r.fBottom);
1173        it.next();
1174    }
1175
1176    drawColorRects(rects.array(), rects.size(), &paint, true, dirty, false);
1177}
1178
1179void OpenGLRenderer::dirtyLayer(const float left, const float top,
1180        const float right, const float bottom, const mat4 transform) {
1181    if (hasLayer()) {
1182        Rect bounds(left, top, right, bottom);
1183        transform.mapRect(bounds);
1184        dirtyLayerUnchecked(bounds, getRegion());
1185    }
1186}
1187
1188void OpenGLRenderer::dirtyLayer(const float left, const float top,
1189        const float right, const float bottom) {
1190    if (hasLayer()) {
1191        Rect bounds(left, top, right, bottom);
1192        dirtyLayerUnchecked(bounds, getRegion());
1193    }
1194}
1195
1196void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
1197    if (bounds.intersect(mState.currentClipRect())) {
1198        bounds.snapToPixelBoundaries();
1199        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
1200        if (!dirty.isEmpty()) {
1201            region->orSelf(dirty);
1202        }
1203    }
1204}
1205
1206void OpenGLRenderer::issueIndexedQuadDraw(Vertex* mesh, GLsizei quadsCount) {
1207    GLsizei elementsCount = quadsCount * 6;
1208    while (elementsCount > 0) {
1209        GLsizei drawCount = min(elementsCount, (GLsizei) kMaxNumberOfQuads * 6);
1210
1211        setupDrawIndexedVertices(&mesh[0].x);
1212        glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_SHORT, nullptr);
1213
1214        elementsCount -= drawCount;
1215        // Though there are 4 vertices in a quad, we use 6 indices per
1216        // quad to draw with GL_TRIANGLES
1217        mesh += (drawCount / 6) * 4;
1218    }
1219}
1220
1221void OpenGLRenderer::clearLayerRegions() {
1222    const size_t count = mLayers.size();
1223    if (count == 0) return;
1224
1225    if (!mState.currentlyIgnored()) {
1226        EVENT_LOGD("clearLayerRegions");
1227        // Doing several glScissor/glClear here can negatively impact
1228        // GPUs with a tiler architecture, instead we draw quads with
1229        // the Clear blending mode
1230
1231        // The list contains bounds that have already been clipped
1232        // against their initial clip rect, and the current clip
1233        // is likely different so we need to disable clipping here
1234        bool scissorChanged = mRenderState.scissor().setEnabled(false);
1235
1236        Vertex mesh[count * 4];
1237        Vertex* vertex = mesh;
1238
1239        for (uint32_t i = 0; i < count; i++) {
1240            const Rect& bounds = mLayers[i];
1241
1242            Vertex::set(vertex++, bounds.left, bounds.top);
1243            Vertex::set(vertex++, bounds.right, bounds.top);
1244            Vertex::set(vertex++, bounds.left, bounds.bottom);
1245            Vertex::set(vertex++, bounds.right, bounds.bottom);
1246        }
1247        // We must clear the list of dirty rects before we
1248        // call setupDraw() to prevent stencil setup to do
1249        // the same thing again
1250        mLayers.clear();
1251
1252        SkPaint clearPaint;
1253        clearPaint.setXfermodeMode(SkXfermode::kClear_Mode);
1254
1255        setupDraw(false);
1256        setupDrawColor(0.0f, 0.0f, 0.0f, 1.0f);
1257        setupDrawBlending(&clearPaint, true);
1258        setupDrawProgram();
1259        setupDrawPureColorUniforms();
1260        setupDrawModelView(kModelViewMode_Translate, false,
1261                0.0f, 0.0f, 0.0f, 0.0f, true);
1262
1263        issueIndexedQuadDraw(&mesh[0], count);
1264
1265        if (scissorChanged) mRenderState.scissor().setEnabled(true);
1266    } else {
1267        mLayers.clear();
1268    }
1269}
1270
1271///////////////////////////////////////////////////////////////////////////////
1272// State Deferral
1273///////////////////////////////////////////////////////////////////////////////
1274
1275bool OpenGLRenderer::storeDisplayState(DeferredDisplayState& state, int stateDeferFlags) {
1276    const Rect& currentClip = mState.currentClipRect();
1277    const mat4* currentMatrix = currentTransform();
1278
1279    if (stateDeferFlags & kStateDeferFlag_Draw) {
1280        // state has bounds initialized in local coordinates
1281        if (!state.mBounds.isEmpty()) {
1282            currentMatrix->mapRect(state.mBounds);
1283            Rect clippedBounds(state.mBounds);
1284            // NOTE: if we ever want to use this clipping info to drive whether the scissor
1285            // is used, it should more closely duplicate the quickReject logic (in how it uses
1286            // snapToPixelBoundaries)
1287
1288            if (!clippedBounds.intersect(currentClip)) {
1289                // quick rejected
1290                return true;
1291            }
1292
1293            state.mClipSideFlags = kClipSide_None;
1294            if (!currentClip.contains(state.mBounds)) {
1295                int& flags = state.mClipSideFlags;
1296                // op partially clipped, so record which sides are clipped for clip-aware merging
1297                if (currentClip.left > state.mBounds.left) flags |= kClipSide_Left;
1298                if (currentClip.top > state.mBounds.top) flags |= kClipSide_Top;
1299                if (currentClip.right < state.mBounds.right) flags |= kClipSide_Right;
1300                if (currentClip.bottom < state.mBounds.bottom) flags |= kClipSide_Bottom;
1301            }
1302            state.mBounds.set(clippedBounds);
1303        } else {
1304            // Empty bounds implies size unknown. Label op as conservatively clipped to disable
1305            // overdraw avoidance (since we don't know what it overlaps)
1306            state.mClipSideFlags = kClipSide_ConservativeFull;
1307            state.mBounds.set(currentClip);
1308        }
1309    }
1310
1311    state.mClipValid = (stateDeferFlags & kStateDeferFlag_Clip);
1312    if (state.mClipValid) {
1313        state.mClip.set(currentClip);
1314    }
1315
1316    // Transform, drawModifiers, and alpha always deferred, since they are used by state operations
1317    // (Note: saveLayer/restore use colorFilter and alpha, so we just save restore everything)
1318    state.mMatrix.load(*currentMatrix);
1319    state.mDrawModifiers = mDrawModifiers;
1320    state.mAlpha = currentSnapshot()->alpha;
1321
1322    // always store/restore, since it's just a pointer
1323    state.mRoundRectClipState = currentSnapshot()->roundRectClipState;
1324    return false;
1325}
1326
1327void OpenGLRenderer::restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore) {
1328    setMatrix(state.mMatrix);
1329    writableSnapshot()->alpha = state.mAlpha;
1330    mDrawModifiers = state.mDrawModifiers;
1331    writableSnapshot()->roundRectClipState = state.mRoundRectClipState;
1332
1333    if (state.mClipValid && !skipClipRestore) {
1334        writableSnapshot()->setClip(state.mClip.left, state.mClip.top,
1335                state.mClip.right, state.mClip.bottom);
1336        dirtyClip();
1337    }
1338}
1339
1340/**
1341 * Merged multidraw (such as in drawText and drawBitmaps rely on the fact that no clipping is done
1342 * in the draw path. Instead, clipping is done ahead of time - either as a single clip rect (when at
1343 * least one op is clipped), or disabled entirely (because no merged op is clipped)
1344 *
1345 * This method should be called when restoreDisplayState() won't be restoring the clip
1346 */
1347void OpenGLRenderer::setupMergedMultiDraw(const Rect* clipRect) {
1348    if (clipRect != nullptr) {
1349        writableSnapshot()->setClip(clipRect->left, clipRect->top, clipRect->right, clipRect->bottom);
1350    } else {
1351        writableSnapshot()->setClip(0, 0, mState.getWidth(), mState.getHeight());
1352    }
1353    dirtyClip();
1354    bool enableScissor = (clipRect != nullptr) || mScissorOptimizationDisabled;
1355    mRenderState.scissor().setEnabled(enableScissor);
1356}
1357
1358///////////////////////////////////////////////////////////////////////////////
1359// Clipping
1360///////////////////////////////////////////////////////////////////////////////
1361
1362void OpenGLRenderer::setScissorFromClip() {
1363    Rect clip(mState.currentClipRect());
1364    clip.snapToPixelBoundaries();
1365
1366    if (mRenderState.scissor().set(clip.left, getViewportHeight() - clip.bottom,
1367            clip.getWidth(), clip.getHeight())) {
1368        mState.setDirtyClip(false);
1369    }
1370}
1371
1372void OpenGLRenderer::ensureStencilBuffer() {
1373    // Thanks to the mismatch between EGL and OpenGL ES FBO we
1374    // cannot attach a stencil buffer to fbo0 dynamically. Let's
1375    // just hope we have one when hasLayer() returns false.
1376    if (hasLayer()) {
1377        attachStencilBufferToLayer(currentSnapshot()->layer);
1378    }
1379}
1380
1381void OpenGLRenderer::attachStencilBufferToLayer(Layer* layer) {
1382    // The layer's FBO is already bound when we reach this stage
1383    if (!layer->getStencilRenderBuffer()) {
1384        // GL_QCOM_tiled_rendering doesn't like it if a renderbuffer
1385        // is attached after we initiated tiling. We must turn it off,
1386        // attach the new render buffer then turn tiling back on
1387        endTiling();
1388
1389        RenderBuffer* buffer = mCaches.renderBufferCache.get(
1390                Stencil::getSmallestStencilFormat(), layer->getWidth(), layer->getHeight());
1391        layer->setStencilRenderBuffer(buffer);
1392
1393        startTiling(layer->clipRect, layer->layer.getHeight());
1394    }
1395}
1396
1397static void handlePoint(std::vector<Vertex>& rectangleVertices, const Matrix4& transform,
1398        float x, float y) {
1399    Vertex v;
1400    v.x = x;
1401    v.y = y;
1402    transform.mapPoint(v.x, v.y);
1403    rectangleVertices.push_back(v);
1404}
1405
1406static void handlePointNoTransform(std::vector<Vertex>& rectangleVertices, float x, float y) {
1407    Vertex v;
1408    v.x = x;
1409    v.y = y;
1410    rectangleVertices.push_back(v);
1411}
1412
1413void OpenGLRenderer::drawRectangleList(const RectangleList& rectangleList) {
1414    int count = rectangleList.getTransformedRectanglesCount();
1415    std::vector<Vertex> rectangleVertices(count * 4);
1416    Rect scissorBox = rectangleList.calculateBounds();
1417    scissorBox.snapToPixelBoundaries();
1418    for (int i = 0; i < count; ++i) {
1419        const TransformedRectangle& tr(rectangleList.getTransformedRectangle(i));
1420        const Matrix4& transform = tr.getTransform();
1421        Rect bounds = tr.getBounds();
1422        if (transform.rectToRect()) {
1423            transform.mapRect(bounds);
1424            if (!bounds.intersect(scissorBox)) {
1425                bounds.setEmpty();
1426            } else {
1427                handlePointNoTransform(rectangleVertices, bounds.left, bounds.top);
1428                handlePointNoTransform(rectangleVertices, bounds.right, bounds.top);
1429                handlePointNoTransform(rectangleVertices, bounds.left, bounds.bottom);
1430                handlePointNoTransform(rectangleVertices, bounds.right, bounds.bottom);
1431            }
1432        } else {
1433            handlePoint(rectangleVertices, transform, bounds.left, bounds.top);
1434            handlePoint(rectangleVertices, transform, bounds.right, bounds.top);
1435            handlePoint(rectangleVertices, transform, bounds.left, bounds.bottom);
1436            handlePoint(rectangleVertices, transform, bounds.right, bounds.bottom);
1437        }
1438    }
1439
1440    mRenderState.scissor().set(scissorBox.left, getViewportHeight() - scissorBox.bottom,
1441            scissorBox.getWidth(), scissorBox.getHeight());
1442
1443    const SkPaint* paint = nullptr;
1444    setupDraw();
1445    setupDrawNoTexture();
1446    setupDrawColor(0, 0xff * currentSnapshot()->alpha);
1447    setupDrawShader(getShader(paint));
1448    setupDrawColorFilter(getColorFilter(paint));
1449    setupDrawBlending(paint);
1450    setupDrawProgram();
1451    setupDrawDirtyRegionsDisabled();
1452    setupDrawModelView(kModelViewMode_Translate, false,
1453            0.0f, 0.0f, 0.0f, 0.0f, true);
1454    setupDrawColorUniforms(getShader(paint));
1455    setupDrawShaderUniforms(getShader(paint));
1456    setupDrawColorFilterUniforms(getColorFilter(paint));
1457
1458    issueIndexedQuadDraw(&rectangleVertices[0], rectangleVertices.size() / 4);
1459}
1460
1461void OpenGLRenderer::setStencilFromClip() {
1462    if (!mCaches.debugOverdraw) {
1463        if (!currentSnapshot()->clipIsSimple()) {
1464            int incrementThreshold;
1465            EVENT_LOGD("setStencilFromClip - enabling");
1466
1467            // NOTE: The order here is important, we must set dirtyClip to false
1468            //       before any draw call to avoid calling back into this method
1469            mState.setDirtyClip(false);
1470
1471            ensureStencilBuffer();
1472
1473            const ClipArea& clipArea = currentSnapshot()->getClipArea();
1474
1475            bool isRectangleList = clipArea.isRectangleList();
1476            if (isRectangleList) {
1477                incrementThreshold = clipArea.getRectangleList().getTransformedRectanglesCount();
1478            } else {
1479                incrementThreshold = 0;
1480            }
1481
1482            mRenderState.stencil().enableWrite(incrementThreshold);
1483
1484            // Clean and update the stencil, but first make sure we restrict drawing
1485            // to the region's bounds
1486            bool resetScissor = mRenderState.scissor().setEnabled(true);
1487            if (resetScissor) {
1488                // The scissor was not set so we now need to update it
1489                setScissorFromClip();
1490            }
1491
1492            mRenderState.stencil().clear();
1493
1494            // stash and disable the outline clip state, since stencil doesn't account for outline
1495            bool storedSkipOutlineClip = mSkipOutlineClip;
1496            mSkipOutlineClip = true;
1497
1498            SkPaint paint;
1499            paint.setColor(SK_ColorBLACK);
1500            paint.setXfermodeMode(SkXfermode::kSrc_Mode);
1501
1502            if (isRectangleList) {
1503                drawRectangleList(clipArea.getRectangleList());
1504            } else {
1505                // NOTE: We could use the region contour path to generate a smaller mesh
1506                //       Since we are using the stencil we could use the red book path
1507                //       drawing technique. It might increase bandwidth usage though.
1508
1509                // The last parameter is important: we are not drawing in the color buffer
1510                // so we don't want to dirty the current layer, if any
1511                drawRegionRects(clipArea.getClipRegion(), paint, false);
1512            }
1513            if (resetScissor) mRenderState.scissor().setEnabled(false);
1514            mSkipOutlineClip = storedSkipOutlineClip;
1515
1516            mRenderState.stencil().enableTest(incrementThreshold);
1517
1518            // Draw the region used to generate the stencil if the appropriate debug
1519            // mode is enabled
1520            // TODO: Implement for rectangle list clip areas
1521            if (mCaches.debugStencilClip == Caches::kStencilShowRegion &&
1522                    !clipArea.isRectangleList()) {
1523                paint.setColor(0x7f0000ff);
1524                paint.setXfermodeMode(SkXfermode::kSrcOver_Mode);
1525                drawRegionRects(currentSnapshot()->getClipRegion(), paint);
1526            }
1527        } else {
1528            EVENT_LOGD("setStencilFromClip - disabling");
1529            mRenderState.stencil().disable();
1530        }
1531    }
1532}
1533
1534/**
1535 * Returns false and sets scissor enable based upon bounds if drawing won't be clipped out.
1536 *
1537 * @param paint if not null, the bounds will be expanded to account for stroke depending on paint
1538 *         style, and tessellated AA ramp
1539 */
1540bool OpenGLRenderer::quickRejectSetupScissor(float left, float top, float right, float bottom,
1541        const SkPaint* paint) {
1542    bool snapOut = paint && paint->isAntiAlias();
1543
1544    if (paint && paint->getStyle() != SkPaint::kFill_Style) {
1545        float outset = paint->getStrokeWidth() * 0.5f;
1546        left -= outset;
1547        top -= outset;
1548        right += outset;
1549        bottom += outset;
1550    }
1551
1552    bool clipRequired = false;
1553    bool roundRectClipRequired = false;
1554    if (mState.calculateQuickRejectForScissor(left, top, right, bottom,
1555            &clipRequired, &roundRectClipRequired, snapOut)) {
1556        return true;
1557    }
1558
1559    // not quick rejected, so enable the scissor if clipRequired
1560    mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired);
1561    mSkipOutlineClip = !roundRectClipRequired;
1562    return false;
1563}
1564
1565void OpenGLRenderer::debugClip() {
1566#if DEBUG_CLIP_REGIONS
1567    if (!currentSnapshot()->clipRegion->isEmpty()) {
1568        SkPaint paint;
1569        paint.setColor(0x7f00ff00);
1570        drawRegionRects(*(currentSnapshot()->clipRegion, paint);
1571
1572    }
1573#endif
1574}
1575
1576///////////////////////////////////////////////////////////////////////////////
1577// Drawing commands
1578///////////////////////////////////////////////////////////////////////////////
1579
1580void OpenGLRenderer::setupDraw(bool clearLayer) {
1581    // TODO: It would be best if we could do this before quickRejectSetupScissor()
1582    //       changes the scissor test state
1583    if (clearLayer) clearLayerRegions();
1584    // Make sure setScissor & setStencil happen at the beginning of
1585    // this method
1586    if (mState.getDirtyClip()) {
1587        if (mRenderState.scissor().isEnabled()) {
1588            setScissorFromClip();
1589        }
1590
1591        setStencilFromClip();
1592    }
1593
1594    mDescription.reset();
1595
1596    mSetShaderColor = false;
1597    mColorSet = false;
1598    mColorA = mColorR = mColorG = mColorB = 0.0f;
1599    mTextureUnit = 0;
1600    mTrackDirtyRegions = true;
1601
1602    // Enable debug highlight when what we're about to draw is tested against
1603    // the stencil buffer and if stencil highlight debugging is on
1604    mDescription.hasDebugHighlight = !mCaches.debugOverdraw &&
1605            mCaches.debugStencilClip == Caches::kStencilShowHighlight &&
1606            mRenderState.stencil().isTestEnabled();
1607}
1608
1609void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
1610    mDescription.hasTexture = true;
1611    mDescription.hasAlpha8Texture = isAlpha8;
1612}
1613
1614void OpenGLRenderer::setupDrawWithTextureAndColor(bool isAlpha8) {
1615    mDescription.hasTexture = true;
1616    mDescription.hasColors = true;
1617    mDescription.hasAlpha8Texture = isAlpha8;
1618}
1619
1620void OpenGLRenderer::setupDrawWithExternalTexture() {
1621    mDescription.hasExternalTexture = true;
1622}
1623
1624void OpenGLRenderer::setupDrawNoTexture() {
1625    mRenderState.meshState().disableTexCoordsVertexArray();
1626}
1627
1628void OpenGLRenderer::setupDrawVertexAlpha(bool useShadowAlphaInterp) {
1629    mDescription.hasVertexAlpha = true;
1630    mDescription.useShadowAlphaInterp = useShadowAlphaInterp;
1631}
1632
1633void OpenGLRenderer::setupDrawColor(int color, int alpha) {
1634    mColorA = alpha / 255.0f;
1635    mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f;
1636    mColorG = mColorA * ((color >>  8) & 0xFF) / 255.0f;
1637    mColorB = mColorA * ((color      ) & 0xFF) / 255.0f;
1638    mColorSet = true;
1639    mSetShaderColor = mDescription.setColorModulate(mColorA);
1640}
1641
1642void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
1643    mColorA = alpha / 255.0f;
1644    mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f;
1645    mColorG = mColorA * ((color >>  8) & 0xFF) / 255.0f;
1646    mColorB = mColorA * ((color      ) & 0xFF) / 255.0f;
1647    mColorSet = true;
1648    mSetShaderColor = mDescription.setAlpha8ColorModulate(mColorR, mColorG, mColorB, mColorA);
1649}
1650
1651void OpenGLRenderer::setupDrawTextGamma(const SkPaint* paint) {
1652    mCaches.fontRenderer->describe(mDescription, paint);
1653}
1654
1655void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
1656    mColorA = a;
1657    mColorR = r;
1658    mColorG = g;
1659    mColorB = b;
1660    mColorSet = true;
1661    mSetShaderColor = mDescription.setColorModulate(a);
1662}
1663
1664void OpenGLRenderer::setupDrawShader(const SkShader* shader) {
1665    if (shader != nullptr) {
1666        SkiaShader::describe(&mCaches, mDescription, mExtensions, *shader);
1667    }
1668}
1669
1670void OpenGLRenderer::setupDrawColorFilter(const SkColorFilter* filter) {
1671    if (filter == nullptr) {
1672        return;
1673    }
1674
1675    SkXfermode::Mode mode;
1676    if (filter->asColorMode(nullptr, &mode)) {
1677        mDescription.colorOp = ProgramDescription::kColorBlend;
1678        mDescription.colorMode = mode;
1679    } else if (filter->asColorMatrix(nullptr)) {
1680        mDescription.colorOp = ProgramDescription::kColorMatrix;
1681    }
1682}
1683
1684void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) {
1685    if (mColorSet && mode == SkXfermode::kClear_Mode) {
1686        mColorA = 1.0f;
1687        mColorR = mColorG = mColorB = 0.0f;
1688        mSetShaderColor = mDescription.modulate = true;
1689    }
1690}
1691
1692void OpenGLRenderer::setupDrawBlending(const Layer* layer, bool swapSrcDst) {
1693    SkXfermode::Mode mode = layer->getMode();
1694    // When the blending mode is kClear_Mode, we need to use a modulate color
1695    // argb=1,0,0,0
1696    accountForClear(mode);
1697    // TODO: check shader blending, once we have shader drawing support for layers.
1698    bool blend = layer->isBlend()
1699            || getLayerAlpha(layer) < 1.0f
1700            || (mColorSet && mColorA < 1.0f)
1701            || PaintUtils::isBlendedColorFilter(layer->getColorFilter());
1702    chooseBlending(blend, mode, mDescription, swapSrcDst);
1703}
1704
1705void OpenGLRenderer::setupDrawBlending(const SkPaint* paint, bool blend, bool swapSrcDst) {
1706    SkXfermode::Mode mode = getXfermodeDirect(paint);
1707    // When the blending mode is kClear_Mode, we need to use a modulate color
1708    // argb=1,0,0,0
1709    accountForClear(mode);
1710    blend |= (mColorSet && mColorA < 1.0f)
1711            || (getShader(paint) && !getShader(paint)->isOpaque())
1712            || PaintUtils::isBlendedColorFilter(getColorFilter(paint));
1713    chooseBlending(blend, mode, mDescription, swapSrcDst);
1714}
1715
1716void OpenGLRenderer::setupDrawProgram() {
1717    mCaches.setProgram(mDescription);
1718    if (mDescription.hasRoundRectClip) {
1719        // TODO: avoid doing this repeatedly, stashing state pointer in program
1720        const RoundRectClipState* state = writableSnapshot()->roundRectClipState;
1721        const Rect& innerRect = state->innerRect;
1722        glUniform4f(mCaches.program().getUniform("roundRectInnerRectLTRB"),
1723                innerRect.left, innerRect.top,
1724                innerRect.right, innerRect.bottom);
1725        glUniformMatrix4fv(mCaches.program().getUniform("roundRectInvTransform"),
1726                1, GL_FALSE, &state->matrix.data[0]);
1727
1728        // add half pixel to round out integer rect space to cover pixel centers
1729        float roundedOutRadius = state->radius + 0.5f;
1730        glUniform1f(mCaches.program().getUniform("roundRectRadius"),
1731                roundedOutRadius);
1732    }
1733}
1734
1735void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
1736    mTrackDirtyRegions = false;
1737}
1738
1739void OpenGLRenderer::setupDrawModelView(ModelViewMode mode, bool offset,
1740        float left, float top, float right, float bottom, bool ignoreTransform) {
1741    mModelViewMatrix.loadTranslate(left, top, 0.0f);
1742    if (mode == kModelViewMode_TranslateAndScale) {
1743        mModelViewMatrix.scale(right - left, bottom - top, 1.0f);
1744    }
1745
1746    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
1747    const Matrix4& transformMatrix = ignoreTransform ? Matrix4::identity() : *currentTransform();
1748
1749    mCaches.program().set(currentSnapshot()->getOrthoMatrix(),
1750            mModelViewMatrix, transformMatrix, offset);
1751    if (dirty && mTrackDirtyRegions) {
1752        if (!ignoreTransform) {
1753            dirtyLayer(left, top, right, bottom, *currentTransform());
1754        } else {
1755            dirtyLayer(left, top, right, bottom);
1756        }
1757    }
1758}
1759
1760void OpenGLRenderer::setupDrawColorUniforms(bool hasShader) {
1761    if ((mColorSet && !hasShader) || (hasShader && mSetShaderColor)) {
1762        mCaches.program().setColor(mColorR, mColorG, mColorB, mColorA);
1763    }
1764}
1765
1766void OpenGLRenderer::setupDrawPureColorUniforms() {
1767    if (mSetShaderColor) {
1768        mCaches.program().setColor(mColorR, mColorG, mColorB, mColorA);
1769    }
1770}
1771
1772void OpenGLRenderer::setupDrawShaderUniforms(const SkShader* shader, bool ignoreTransform) {
1773    if (shader == nullptr) {
1774        return;
1775    }
1776
1777    if (ignoreTransform) {
1778        // if ignoreTransform=true was passed to setupDrawModelView, undo currentTransform()
1779        // because it was built into modelView / the geometry, and the description needs to
1780        // compensate.
1781        mat4 modelViewWithoutTransform;
1782        modelViewWithoutTransform.loadInverse(*currentTransform());
1783        modelViewWithoutTransform.multiply(mModelViewMatrix);
1784        mModelViewMatrix.load(modelViewWithoutTransform);
1785    }
1786
1787    SkiaShader::setupProgram(&mCaches, mModelViewMatrix, &mTextureUnit, mExtensions, *shader);
1788}
1789
1790void OpenGLRenderer::setupDrawColorFilterUniforms(const SkColorFilter* filter) {
1791    if (nullptr == filter) {
1792        return;
1793    }
1794
1795    SkColor color;
1796    SkXfermode::Mode mode;
1797    if (filter->asColorMode(&color, &mode)) {
1798        const int alpha = SkColorGetA(color);
1799        const GLfloat a = alpha / 255.0f;
1800        const GLfloat r = a * SkColorGetR(color) / 255.0f;
1801        const GLfloat g = a * SkColorGetG(color) / 255.0f;
1802        const GLfloat b = a * SkColorGetB(color) / 255.0f;
1803        glUniform4f(mCaches.program().getUniform("colorBlend"), r, g, b, a);
1804        return;
1805    }
1806
1807    SkScalar srcColorMatrix[20];
1808    if (filter->asColorMatrix(srcColorMatrix)) {
1809
1810        float colorMatrix[16];
1811        memcpy(colorMatrix, srcColorMatrix, 4 * sizeof(float));
1812        memcpy(&colorMatrix[4], &srcColorMatrix[5], 4 * sizeof(float));
1813        memcpy(&colorMatrix[8], &srcColorMatrix[10], 4 * sizeof(float));
1814        memcpy(&colorMatrix[12], &srcColorMatrix[15], 4 * sizeof(float));
1815
1816        // Skia uses the range [0..255] for the addition vector, but we need
1817        // the [0..1] range to apply the vector in GLSL
1818        float colorVector[4];
1819        colorVector[0] = srcColorMatrix[4] / 255.0f;
1820        colorVector[1] = srcColorMatrix[9] / 255.0f;
1821        colorVector[2] = srcColorMatrix[14] / 255.0f;
1822        colorVector[3] = srcColorMatrix[19] / 255.0f;
1823
1824        glUniformMatrix4fv(mCaches.program().getUniform("colorMatrix"), 1,
1825                GL_FALSE, colorMatrix);
1826        glUniform4fv(mCaches.program().getUniform("colorMatrixVector"), 1, colorVector);
1827        return;
1828    }
1829
1830    // it is an error if we ever get here
1831}
1832
1833void OpenGLRenderer::setupDrawTextGammaUniforms() {
1834    mCaches.fontRenderer->setupProgram(mDescription, mCaches.program());
1835}
1836
1837void OpenGLRenderer::setupDrawSimpleMesh() {
1838    bool force = mRenderState.meshState().bindMeshBuffer();
1839    mRenderState.meshState().bindPositionVertexPointer(force, nullptr);
1840    mRenderState.meshState().unbindIndicesBuffer();
1841}
1842
1843void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1844    if (texture) mCaches.textureState().bindTexture(texture);
1845    mTextureUnit++;
1846    mRenderState.meshState().enableTexCoordsVertexArray();
1847}
1848
1849void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) {
1850    mCaches.textureState().bindTexture(GL_TEXTURE_EXTERNAL_OES, texture);
1851    mTextureUnit++;
1852    mRenderState.meshState().enableTexCoordsVertexArray();
1853}
1854
1855void OpenGLRenderer::setupDrawTextureTransform() {
1856    mDescription.hasTextureTransform = true;
1857}
1858
1859void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) {
1860    glUniformMatrix4fv(mCaches.program().getUniform("mainTextureTransform"), 1,
1861            GL_FALSE, &transform.data[0]);
1862}
1863
1864void OpenGLRenderer::setupDrawMesh(const GLvoid* vertices,
1865        const GLvoid* texCoords, GLuint vbo) {
1866    bool force = false;
1867    if (!vertices || vbo) {
1868        force = mRenderState.meshState().bindMeshBuffer(vbo);
1869    } else {
1870        force = mRenderState.meshState().unbindMeshBuffer();
1871    }
1872
1873    mRenderState.meshState().bindPositionVertexPointer(force, vertices);
1874    if (mCaches.program().texCoords >= 0) {
1875        mRenderState.meshState().bindTexCoordsVertexPointer(force, texCoords);
1876    }
1877
1878    mRenderState.meshState().unbindIndicesBuffer();
1879}
1880
1881void OpenGLRenderer::setupDrawMesh(const GLvoid* vertices,
1882        const GLvoid* texCoords, const GLvoid* colors) {
1883    bool force = mRenderState.meshState().unbindMeshBuffer();
1884    GLsizei stride = sizeof(ColorTextureVertex);
1885
1886    mRenderState.meshState().bindPositionVertexPointer(force, vertices, stride);
1887    if (mCaches.program().texCoords >= 0) {
1888        mRenderState.meshState().bindTexCoordsVertexPointer(force, texCoords, stride);
1889    }
1890    int slot = mCaches.program().getAttrib("colors");
1891    if (slot >= 0) {
1892        glEnableVertexAttribArray(slot);
1893        glVertexAttribPointer(slot, 4, GL_FLOAT, GL_FALSE, stride, colors);
1894    }
1895
1896    mRenderState.meshState().unbindIndicesBuffer();
1897}
1898
1899void OpenGLRenderer::setupDrawMeshIndices(const GLvoid* vertices,
1900        const GLvoid* texCoords, GLuint vbo) {
1901    bool force = false;
1902    // If vbo is != 0 we want to treat the vertices parameter as an offset inside
1903    // a VBO. However, if vertices is set to NULL and vbo == 0 then we want to
1904    // use the default VBO found in RenderState
1905    if (!vertices || vbo) {
1906        force = mRenderState.meshState().bindMeshBuffer(vbo);
1907    } else {
1908        force = mRenderState.meshState().unbindMeshBuffer();
1909    }
1910    mRenderState.meshState().bindQuadIndicesBuffer();
1911
1912    mRenderState.meshState().bindPositionVertexPointer(force, vertices);
1913    if (mCaches.program().texCoords >= 0) {
1914        mRenderState.meshState().bindTexCoordsVertexPointer(force, texCoords);
1915    }
1916}
1917
1918void OpenGLRenderer::setupDrawIndexedVertices(GLvoid* vertices) {
1919    bool force = mRenderState.meshState().unbindMeshBuffer();
1920    mRenderState.meshState().bindQuadIndicesBuffer();
1921    mRenderState.meshState().bindPositionVertexPointer(force, vertices, kVertexStride);
1922}
1923
1924///////////////////////////////////////////////////////////////////////////////
1925// Drawing
1926///////////////////////////////////////////////////////////////////////////////
1927
1928void OpenGLRenderer::drawRenderNode(RenderNode* renderNode, Rect& dirty, int32_t replayFlags) {
1929    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1930    // will be performed by the display list itself
1931    if (renderNode && renderNode->isRenderable()) {
1932        // compute 3d ordering
1933        renderNode->computeOrdering();
1934        if (CC_UNLIKELY(mCaches.drawDeferDisabled)) {
1935            startFrame();
1936            ReplayStateStruct replayStruct(*this, dirty, replayFlags);
1937            renderNode->replay(replayStruct, 0);
1938            return;
1939        }
1940
1941        // Don't avoid overdraw when visualizing, since that makes it harder to
1942        // debug where it's coming from, and when the problem occurs.
1943        bool avoidOverdraw = !mCaches.debugOverdraw;
1944        DeferredDisplayList deferredList(mState.currentClipRect(), avoidOverdraw);
1945        DeferStateStruct deferStruct(deferredList, *this, replayFlags);
1946        renderNode->defer(deferStruct, 0);
1947
1948        flushLayers();
1949        startFrame();
1950
1951        deferredList.flush(*this, dirty);
1952    } else {
1953        // Even if there is no drawing command(Ex: invisible),
1954        // it still needs startFrame to clear buffer and start tiling.
1955        startFrame();
1956    }
1957}
1958
1959void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top,
1960        const SkPaint* paint) {
1961    float x = left;
1962    float y = top;
1963
1964    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1965
1966    bool ignoreTransform = false;
1967    if (currentTransform()->isPureTranslate()) {
1968        x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f);
1969        y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f);
1970        ignoreTransform = true;
1971
1972        texture->setFilter(GL_NEAREST, true);
1973    } else {
1974        texture->setFilter(getFilter(paint), true);
1975    }
1976
1977    // No need to check for a UV mapper on the texture object, only ARGB_8888
1978    // bitmaps get packed in the atlas
1979    drawAlpha8TextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
1980            paint, (GLvoid*) nullptr, (GLvoid*) kMeshTextureOffset,
1981            GL_TRIANGLE_STRIP, kMeshCount, ignoreTransform);
1982}
1983
1984/**
1985 * Important note: this method is intended to draw batches of bitmaps and
1986 * will not set the scissor enable or dirty the current layer, if any.
1987 * The caller is responsible for properly dirtying the current layer.
1988 */
1989void OpenGLRenderer::drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
1990        int bitmapCount, TextureVertex* vertices, bool pureTranslate,
1991        const Rect& bounds, const SkPaint* paint) {
1992    mCaches.textureState().activateTexture(0);
1993    Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
1994    if (!texture) return;
1995
1996    const AutoTexture autoCleanup(texture);
1997
1998    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1999    texture->setFilter(pureTranslate ? GL_NEAREST : getFilter(paint), true);
2000
2001    const float x = (int) floorf(bounds.left + 0.5f);
2002    const float y = (int) floorf(bounds.top + 0.5f);
2003    if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) {
2004        drawAlpha8TextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(),
2005                texture->id, paint, &vertices[0].x, &vertices[0].u,
2006                GL_TRIANGLES, bitmapCount * 6, true,
2007                kModelViewMode_Translate, false);
2008    } else {
2009        drawTextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(),
2010                texture->id, paint, texture->blend, &vertices[0].x, &vertices[0].u,
2011                GL_TRIANGLES, bitmapCount * 6, false, true, 0,
2012                kModelViewMode_Translate, false);
2013    }
2014
2015    mDirty = true;
2016}
2017
2018void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, const SkPaint* paint) {
2019    if (quickRejectSetupScissor(0, 0, bitmap->width(), bitmap->height())) {
2020        return;
2021    }
2022
2023    mCaches.textureState().activateTexture(0);
2024    Texture* texture = getTexture(bitmap);
2025    if (!texture) return;
2026    const AutoTexture autoCleanup(texture);
2027
2028    if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) {
2029        drawAlphaBitmap(texture, 0, 0, paint);
2030    } else {
2031        drawTextureRect(0, 0, bitmap->width(), bitmap->height(), texture, paint);
2032    }
2033
2034    mDirty = true;
2035}
2036
2037void OpenGLRenderer::drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight,
2038        const float* vertices, const int* colors, const SkPaint* paint) {
2039    if (!vertices || mState.currentlyIgnored()) {
2040        return;
2041    }
2042
2043    // TODO: use quickReject on bounds from vertices
2044    mRenderState.scissor().setEnabled(true);
2045
2046    float left = FLT_MAX;
2047    float top = FLT_MAX;
2048    float right = FLT_MIN;
2049    float bottom = FLT_MIN;
2050
2051    const uint32_t count = meshWidth * meshHeight * 6;
2052
2053    std::unique_ptr<ColorTextureVertex[]> mesh(new ColorTextureVertex[count]);
2054    ColorTextureVertex* vertex = &mesh[0];
2055
2056    std::unique_ptr<int[]> tempColors;
2057    if (!colors) {
2058        uint32_t colorsCount = (meshWidth + 1) * (meshHeight + 1);
2059        tempColors.reset(new int[colorsCount]);
2060        memset(tempColors.get(), 0xff, colorsCount * sizeof(int));
2061        colors = tempColors.get();
2062    }
2063
2064    mCaches.textureState().activateTexture(0);
2065    Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap);
2066    const UvMapper& mapper(getMapper(texture));
2067
2068    for (int32_t y = 0; y < meshHeight; y++) {
2069        for (int32_t x = 0; x < meshWidth; x++) {
2070            uint32_t i = (y * (meshWidth + 1) + x) * 2;
2071
2072            float u1 = float(x) / meshWidth;
2073            float u2 = float(x + 1) / meshWidth;
2074            float v1 = float(y) / meshHeight;
2075            float v2 = float(y + 1) / meshHeight;
2076
2077            mapper.map(u1, v1, u2, v2);
2078
2079            int ax = i + (meshWidth + 1) * 2;
2080            int ay = ax + 1;
2081            int bx = i;
2082            int by = bx + 1;
2083            int cx = i + 2;
2084            int cy = cx + 1;
2085            int dx = i + (meshWidth + 1) * 2 + 2;
2086            int dy = dx + 1;
2087
2088            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
2089            ColorTextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2, colors[ax / 2]);
2090            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
2091
2092            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
2093            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
2094            ColorTextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1, colors[cx / 2]);
2095
2096            left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
2097            top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
2098            right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
2099            bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
2100        }
2101    }
2102
2103    if (quickRejectSetupScissor(left, top, right, bottom)) {
2104        return;
2105    }
2106
2107    if (!texture) {
2108        texture = mCaches.textureCache.get(bitmap);
2109        if (!texture) {
2110            return;
2111        }
2112    }
2113    const AutoTexture autoCleanup(texture);
2114
2115    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2116    texture->setFilter(getFilter(paint), true);
2117
2118    int alpha;
2119    SkXfermode::Mode mode;
2120    getAlphaAndMode(paint, &alpha, &mode);
2121
2122    float a = alpha / 255.0f;
2123
2124    if (hasLayer()) {
2125        dirtyLayer(left, top, right, bottom, *currentTransform());
2126    }
2127
2128    setupDraw();
2129    setupDrawWithTextureAndColor();
2130    setupDrawColor(a, a, a, a);
2131    setupDrawColorFilter(getColorFilter(paint));
2132    setupDrawBlending(paint, true);
2133    setupDrawProgram();
2134    setupDrawDirtyRegionsDisabled();
2135    setupDrawModelView(kModelViewMode_TranslateAndScale, false, 0.0f, 0.0f, 1.0f, 1.0f);
2136    setupDrawTexture(texture->id);
2137    setupDrawPureColorUniforms();
2138    setupDrawColorFilterUniforms(getColorFilter(paint));
2139    setupDrawMesh(&mesh[0].x, &mesh[0].u, &mesh[0].r);
2140
2141    glDrawArrays(GL_TRIANGLES, 0, count);
2142
2143    int slot = mCaches.program().getAttrib("colors");
2144    if (slot >= 0) {
2145        glDisableVertexAttribArray(slot);
2146    }
2147
2148    mDirty = true;
2149}
2150
2151void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap,
2152         float srcLeft, float srcTop, float srcRight, float srcBottom,
2153         float dstLeft, float dstTop, float dstRight, float dstBottom,
2154         const SkPaint* paint) {
2155    if (quickRejectSetupScissor(dstLeft, dstTop, dstRight, dstBottom)) {
2156        return;
2157    }
2158
2159    mCaches.textureState().activateTexture(0);
2160    Texture* texture = getTexture(bitmap);
2161    if (!texture) return;
2162    const AutoTexture autoCleanup(texture);
2163
2164    const float width = texture->width;
2165    const float height = texture->height;
2166
2167    float u1 = fmax(0.0f, srcLeft / width);
2168    float v1 = fmax(0.0f, srcTop / height);
2169    float u2 = fmin(1.0f, srcRight / width);
2170    float v2 = fmin(1.0f, srcBottom / height);
2171
2172    getMapper(texture).map(u1, v1, u2, v2);
2173
2174    mRenderState.meshState().unbindMeshBuffer();
2175    resetDrawTextureTexCoords(u1, v1, u2, v2);
2176
2177    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2178
2179    float scaleX = (dstRight - dstLeft) / (srcRight - srcLeft);
2180    float scaleY = (dstBottom - dstTop) / (srcBottom - srcTop);
2181
2182    bool scaled = scaleX != 1.0f || scaleY != 1.0f;
2183    // Apply a scale transform on the canvas only when a shader is in use
2184    // Skia handles the ratio between the dst and src rects as a scale factor
2185    // when a shader is set
2186    bool useScaleTransform = getShader(paint) && scaled;
2187    bool ignoreTransform = false;
2188
2189    if (CC_LIKELY(currentTransform()->isPureTranslate() && !useScaleTransform)) {
2190        float x = (int) floorf(dstLeft + currentTransform()->getTranslateX() + 0.5f);
2191        float y = (int) floorf(dstTop + currentTransform()->getTranslateY() + 0.5f);
2192
2193        dstRight = x + (dstRight - dstLeft);
2194        dstBottom = y + (dstBottom - dstTop);
2195
2196        dstLeft = x;
2197        dstTop = y;
2198
2199        texture->setFilter(scaled ? getFilter(paint) : GL_NEAREST, true);
2200        ignoreTransform = true;
2201    } else {
2202        texture->setFilter(getFilter(paint), true);
2203    }
2204
2205    if (CC_UNLIKELY(useScaleTransform)) {
2206        save(SkCanvas::kMatrix_SaveFlag);
2207        translate(dstLeft, dstTop);
2208        scale(scaleX, scaleY);
2209
2210        dstLeft = 0.0f;
2211        dstTop = 0.0f;
2212
2213        dstRight = srcRight - srcLeft;
2214        dstBottom = srcBottom - srcTop;
2215    }
2216
2217    if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) {
2218        drawAlpha8TextureMesh(dstLeft, dstTop, dstRight, dstBottom,
2219                texture->id, paint,
2220                &mMeshVertices[0].x, &mMeshVertices[0].u,
2221                GL_TRIANGLE_STRIP, kMeshCount, ignoreTransform);
2222    } else {
2223        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom,
2224                texture->id, paint, texture->blend,
2225                &mMeshVertices[0].x, &mMeshVertices[0].u,
2226                GL_TRIANGLE_STRIP, kMeshCount, false, ignoreTransform);
2227    }
2228
2229    if (CC_UNLIKELY(useScaleTransform)) {
2230        restore();
2231    }
2232
2233    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
2234
2235    mDirty = true;
2236}
2237
2238void OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Res_png_9patch* patch,
2239        float left, float top, float right, float bottom, const SkPaint* paint) {
2240    if (quickRejectSetupScissor(left, top, right, bottom)) {
2241        return;
2242    }
2243
2244    AssetAtlas::Entry* entry = mRenderState.assetAtlas().getEntry(bitmap);
2245    const Patch* mesh = mCaches.patchCache.get(entry, bitmap->width(), bitmap->height(),
2246            right - left, bottom - top, patch);
2247
2248    drawPatch(bitmap, mesh, entry, left, top, right, bottom, paint);
2249}
2250
2251void OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Patch* mesh,
2252        AssetAtlas::Entry* entry, float left, float top, float right, float bottom,
2253        const SkPaint* paint) {
2254    if (quickRejectSetupScissor(left, top, right, bottom)) {
2255        return;
2256    }
2257
2258    if (CC_LIKELY(mesh && mesh->verticesCount > 0)) {
2259        mCaches.textureState().activateTexture(0);
2260        Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
2261        if (!texture) return;
2262        const AutoTexture autoCleanup(texture);
2263
2264        texture->setWrap(GL_CLAMP_TO_EDGE, true);
2265        texture->setFilter(GL_LINEAR, true);
2266
2267        const bool pureTranslate = currentTransform()->isPureTranslate();
2268        // Mark the current layer dirty where we are going to draw the patch
2269        if (hasLayer() && mesh->hasEmptyQuads) {
2270            const float offsetX = left + currentTransform()->getTranslateX();
2271            const float offsetY = top + currentTransform()->getTranslateY();
2272            const size_t count = mesh->quads.size();
2273            for (size_t i = 0; i < count; i++) {
2274                const Rect& bounds = mesh->quads.itemAt(i);
2275                if (CC_LIKELY(pureTranslate)) {
2276                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
2277                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
2278                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
2279                } else {
2280                    dirtyLayer(left + bounds.left, top + bounds.top,
2281                            left + bounds.right, top + bounds.bottom, *currentTransform());
2282                }
2283            }
2284        }
2285
2286        bool ignoreTransform = false;
2287        if (CC_LIKELY(pureTranslate)) {
2288            const float x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f);
2289            const float y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f);
2290
2291            right = x + right - left;
2292            bottom = y + bottom - top;
2293            left = x;
2294            top = y;
2295            ignoreTransform = true;
2296        }
2297        drawIndexedTextureMesh(left, top, right, bottom, texture->id, paint,
2298                texture->blend, (GLvoid*) mesh->offset, (GLvoid*) mesh->textureOffset,
2299                GL_TRIANGLES, mesh->indexCount, false, ignoreTransform,
2300                mCaches.patchCache.getMeshBuffer(), kModelViewMode_Translate, !mesh->hasEmptyQuads);
2301    }
2302
2303    mDirty = true;
2304}
2305
2306/**
2307 * Important note: this method is intended to draw batches of 9-patch objects and
2308 * will not set the scissor enable or dirty the current layer, if any.
2309 * The caller is responsible for properly dirtying the current layer.
2310 */
2311void OpenGLRenderer::drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
2312        TextureVertex* vertices, uint32_t indexCount, const SkPaint* paint) {
2313    mCaches.textureState().activateTexture(0);
2314    Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
2315    if (!texture) return;
2316    const AutoTexture autoCleanup(texture);
2317
2318    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2319    texture->setFilter(GL_LINEAR, true);
2320
2321    drawIndexedTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, paint,
2322            texture->blend, &vertices[0].x, &vertices[0].u,
2323            GL_TRIANGLES, indexCount, false, true, 0, kModelViewMode_Translate, false);
2324
2325    mDirty = true;
2326}
2327
2328void OpenGLRenderer::drawVertexBuffer(float translateX, float translateY,
2329        const VertexBuffer& vertexBuffer, const SkPaint* paint, int displayFlags) {
2330    // not missing call to quickReject/dirtyLayer, always done at a higher level
2331    if (!vertexBuffer.getVertexCount()) {
2332        // no vertices to draw
2333        return;
2334    }
2335
2336    Rect bounds(vertexBuffer.getBounds());
2337    bounds.translate(translateX, translateY);
2338    dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom, *currentTransform());
2339
2340    int color = paint->getColor();
2341    bool isAA = paint->isAntiAlias();
2342
2343    setupDraw();
2344    setupDrawNoTexture();
2345    if (isAA) setupDrawVertexAlpha((displayFlags & kVertexBuffer_ShadowInterp));
2346    setupDrawColor(color, ((color >> 24) & 0xFF) * writableSnapshot()->alpha);
2347    setupDrawColorFilter(getColorFilter(paint));
2348    setupDrawShader(getShader(paint));
2349    setupDrawBlending(paint, isAA);
2350    setupDrawProgram();
2351    setupDrawModelView(kModelViewMode_Translate, (displayFlags & kVertexBuffer_Offset),
2352            translateX, translateY, 0, 0);
2353    setupDrawColorUniforms(getShader(paint));
2354    setupDrawColorFilterUniforms(getColorFilter(paint));
2355    setupDrawShaderUniforms(getShader(paint));
2356
2357    const void* vertices = vertexBuffer.getBuffer();
2358    mRenderState.meshState().unbindMeshBuffer();
2359    mRenderState.meshState().bindPositionVertexPointer(true, vertices,
2360            isAA ? kAlphaVertexStride : kVertexStride);
2361    mRenderState.meshState().resetTexCoordsVertexPointer();
2362
2363    int alphaSlot = -1;
2364    if (isAA) {
2365        void* alphaCoords = ((GLbyte*) vertices) + kVertexAlphaOffset;
2366        alphaSlot = mCaches.program().getAttrib("vtxAlpha");
2367        // TODO: avoid enable/disable in back to back uses of the alpha attribute
2368        glEnableVertexAttribArray(alphaSlot);
2369        glVertexAttribPointer(alphaSlot, 1, GL_FLOAT, GL_FALSE, kAlphaVertexStride, alphaCoords);
2370    }
2371
2372    const VertexBuffer::Mode mode = vertexBuffer.getMode();
2373    if (mode == VertexBuffer::kStandard) {
2374        mRenderState.meshState().unbindIndicesBuffer();
2375        glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexBuffer.getVertexCount());
2376    } else if (mode == VertexBuffer::kOnePolyRingShadow) {
2377        mRenderState.meshState().bindShadowIndicesBuffer();
2378        glDrawElements(GL_TRIANGLE_STRIP, ONE_POLY_RING_SHADOW_INDEX_COUNT,
2379                GL_UNSIGNED_SHORT, nullptr);
2380    } else if (mode == VertexBuffer::kTwoPolyRingShadow) {
2381        mRenderState.meshState().bindShadowIndicesBuffer();
2382        glDrawElements(GL_TRIANGLE_STRIP, TWO_POLY_RING_SHADOW_INDEX_COUNT,
2383                GL_UNSIGNED_SHORT, nullptr);
2384    } else if (mode == VertexBuffer::kIndices) {
2385        mRenderState.meshState().unbindIndicesBuffer();
2386        glDrawElements(GL_TRIANGLE_STRIP, vertexBuffer.getIndexCount(),
2387                GL_UNSIGNED_SHORT, vertexBuffer.getIndices());
2388    }
2389
2390    if (isAA) {
2391        glDisableVertexAttribArray(alphaSlot);
2392    }
2393
2394    mDirty = true;
2395}
2396
2397/**
2398 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to
2399 * that of AA lines in the drawLines() function.  We expand the convex path by a half pixel in
2400 * screen space in all directions. However, instead of using a fragment shader to compute the
2401 * translucency of the color from its position, we simply use a varying parameter to define how far
2402 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used.
2403 *
2404 * Doesn't yet support joins, caps, or path effects.
2405 */
2406void OpenGLRenderer::drawConvexPath(const SkPath& path, const SkPaint* paint) {
2407    VertexBuffer vertexBuffer;
2408    // TODO: try clipping large paths to viewport
2409    PathTessellator::tessellatePath(path, paint, *currentTransform(), vertexBuffer);
2410    drawVertexBuffer(vertexBuffer, paint);
2411}
2412
2413/**
2414 * We create tristrips for the lines much like shape stroke tessellation, using a per-vertex alpha
2415 * and additional geometry for defining an alpha slope perimeter.
2416 *
2417 * Using GL_LINES can be difficult because the rasterization rules for those lines produces some
2418 * unexpected results, and may vary between hardware devices. Previously we used a varying-base
2419 * in-shader alpha region, but found it to be taxing on some GPUs.
2420 *
2421 * TODO: try using a fixed input buffer for non-capped lines as in text rendering. this may reduce
2422 * memory transfer by removing need for degenerate vertices.
2423 */
2424void OpenGLRenderer::drawLines(const float* points, int count, const SkPaint* paint) {
2425    if (mState.currentlyIgnored() || count < 4) return;
2426
2427    count &= ~0x3; // round down to nearest four
2428
2429    VertexBuffer buffer;
2430    PathTessellator::tessellateLines(points, count, paint, *currentTransform(), buffer);
2431    const Rect& bounds = buffer.getBounds();
2432
2433    if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) {
2434        return;
2435    }
2436
2437    int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset;
2438    drawVertexBuffer(buffer, paint, displayFlags);
2439}
2440
2441void OpenGLRenderer::drawPoints(const float* points, int count, const SkPaint* paint) {
2442    if (mState.currentlyIgnored() || count < 2) return;
2443
2444    count &= ~0x1; // round down to nearest two
2445
2446    VertexBuffer buffer;
2447    PathTessellator::tessellatePoints(points, count, paint, *currentTransform(), buffer);
2448
2449    const Rect& bounds = buffer.getBounds();
2450    if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) {
2451        return;
2452    }
2453
2454    int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset;
2455    drawVertexBuffer(buffer, paint, displayFlags);
2456
2457    mDirty = true;
2458}
2459
2460void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
2461    // No need to check against the clip, we fill the clip region
2462    if (mState.currentlyIgnored()) return;
2463
2464    Rect clip(mState.currentClipRect());
2465    clip.snapToPixelBoundaries();
2466
2467    SkPaint paint;
2468    paint.setColor(color);
2469    paint.setXfermodeMode(mode);
2470
2471    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, &paint, true);
2472
2473    mDirty = true;
2474}
2475
2476void OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture,
2477        const SkPaint* paint) {
2478    if (!texture) return;
2479    const AutoTexture autoCleanup(texture);
2480
2481    const float x = left + texture->left - texture->offset;
2482    const float y = top + texture->top - texture->offset;
2483
2484    drawPathTexture(texture, x, y, paint);
2485
2486    mDirty = true;
2487}
2488
2489void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
2490        float rx, float ry, const SkPaint* p) {
2491    if (mState.currentlyIgnored()
2492            || quickRejectSetupScissor(left, top, right, bottom, p)
2493            || PaintUtils::paintWillNotDraw(*p)) {
2494        return;
2495    }
2496
2497    if (p->getPathEffect() != nullptr) {
2498        mCaches.textureState().activateTexture(0);
2499        const PathTexture* texture = mCaches.pathCache.getRoundRect(
2500                right - left, bottom - top, rx, ry, p);
2501        drawShape(left, top, texture, p);
2502    } else {
2503        const VertexBuffer* vertexBuffer = mCaches.tessellationCache.getRoundRect(
2504                *currentTransform(), *p, right - left, bottom - top, rx, ry);
2505        drawVertexBuffer(left, top, *vertexBuffer, p);
2506    }
2507}
2508
2509void OpenGLRenderer::drawCircle(float x, float y, float radius, const SkPaint* p) {
2510    if (mState.currentlyIgnored()
2511            || quickRejectSetupScissor(x - radius, y - radius, x + radius, y + radius, p)
2512            || PaintUtils::paintWillNotDraw(*p)) {
2513        return;
2514    }
2515    if (p->getPathEffect() != nullptr) {
2516        mCaches.textureState().activateTexture(0);
2517        const PathTexture* texture = mCaches.pathCache.getCircle(radius, p);
2518        drawShape(x - radius, y - radius, texture, p);
2519    } else {
2520        SkPath path;
2521        if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2522            path.addCircle(x, y, radius + p->getStrokeWidth() / 2);
2523        } else {
2524            path.addCircle(x, y, radius);
2525        }
2526        drawConvexPath(path, p);
2527    }
2528}
2529
2530void OpenGLRenderer::drawOval(float left, float top, float right, float bottom,
2531        const SkPaint* p) {
2532    if (mState.currentlyIgnored()
2533            || quickRejectSetupScissor(left, top, right, bottom, p)
2534            || PaintUtils::paintWillNotDraw(*p)) {
2535        return;
2536    }
2537
2538    if (p->getPathEffect() != nullptr) {
2539        mCaches.textureState().activateTexture(0);
2540        const PathTexture* texture = mCaches.pathCache.getOval(right - left, bottom - top, p);
2541        drawShape(left, top, texture, p);
2542    } else {
2543        SkPath path;
2544        SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2545        if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2546            rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2547        }
2548        path.addOval(rect);
2549        drawConvexPath(path, p);
2550    }
2551}
2552
2553void OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
2554        float startAngle, float sweepAngle, bool useCenter, const SkPaint* p) {
2555    if (mState.currentlyIgnored()
2556            || quickRejectSetupScissor(left, top, right, bottom, p)
2557            || PaintUtils::paintWillNotDraw(*p)) {
2558        return;
2559    }
2560
2561    // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180)
2562    if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != nullptr || useCenter) {
2563        mCaches.textureState().activateTexture(0);
2564        const PathTexture* texture = mCaches.pathCache.getArc(right - left, bottom - top,
2565                startAngle, sweepAngle, useCenter, p);
2566        drawShape(left, top, texture, p);
2567        return;
2568    }
2569    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2570    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2571        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2572    }
2573
2574    SkPath path;
2575    if (useCenter) {
2576        path.moveTo(rect.centerX(), rect.centerY());
2577    }
2578    path.arcTo(rect, startAngle, sweepAngle, !useCenter);
2579    if (useCenter) {
2580        path.close();
2581    }
2582    drawConvexPath(path, p);
2583}
2584
2585// See SkPaintDefaults.h
2586#define SkPaintDefaults_MiterLimit SkIntToScalar(4)
2587
2588void OpenGLRenderer::drawRect(float left, float top, float right, float bottom,
2589        const SkPaint* p) {
2590    if (mState.currentlyIgnored()
2591            || quickRejectSetupScissor(left, top, right, bottom, p)
2592            || PaintUtils::paintWillNotDraw(*p)) {
2593        return;
2594    }
2595
2596    if (p->getStyle() != SkPaint::kFill_Style) {
2597        // only fill style is supported by drawConvexPath, since others have to handle joins
2598        if (p->getPathEffect() != nullptr || p->getStrokeJoin() != SkPaint::kMiter_Join ||
2599                p->getStrokeMiter() != SkPaintDefaults_MiterLimit) {
2600            mCaches.textureState().activateTexture(0);
2601            const PathTexture* texture =
2602                    mCaches.pathCache.getRect(right - left, bottom - top, p);
2603            drawShape(left, top, texture, p);
2604        } else {
2605            SkPath path;
2606            SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2607            if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2608                rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2609            }
2610            path.addRect(rect);
2611            drawConvexPath(path, p);
2612        }
2613    } else {
2614        if (p->isAntiAlias() && !currentTransform()->isSimple()) {
2615            SkPath path;
2616            path.addRect(left, top, right, bottom);
2617            drawConvexPath(path, p);
2618        } else {
2619            drawColorRect(left, top, right, bottom, p);
2620
2621            mDirty = true;
2622        }
2623    }
2624}
2625
2626void OpenGLRenderer::drawTextShadow(const SkPaint* paint, const char* text,
2627        int bytesCount, int count, const float* positions,
2628        FontRenderer& fontRenderer, int alpha, float x, float y) {
2629    mCaches.textureState().activateTexture(0);
2630
2631    TextShadow textShadow;
2632    if (!getTextShadow(paint, &textShadow)) {
2633        LOG_ALWAYS_FATAL("failed to query shadow attributes");
2634    }
2635
2636    // NOTE: The drop shadow will not perform gamma correction
2637    //       if shader-based correction is enabled
2638    mCaches.dropShadowCache.setFontRenderer(fontRenderer);
2639    const ShadowTexture* shadow = mCaches.dropShadowCache.get(
2640            paint, text, bytesCount, count, textShadow.radius, positions);
2641    // If the drop shadow exceeds the max texture size or couldn't be
2642    // allocated, skip drawing
2643    if (!shadow) return;
2644    const AutoTexture autoCleanup(shadow);
2645
2646    const float sx = x - shadow->left + textShadow.dx;
2647    const float sy = y - shadow->top + textShadow.dy;
2648
2649    const int shadowAlpha = ((textShadow.color >> 24) & 0xFF) * writableSnapshot()->alpha;
2650    if (getShader(paint)) {
2651        textShadow.color = SK_ColorWHITE;
2652    }
2653
2654    setupDraw();
2655    setupDrawWithTexture(true);
2656    setupDrawAlpha8Color(textShadow.color, shadowAlpha < 255 ? shadowAlpha : alpha);
2657    setupDrawColorFilter(getColorFilter(paint));
2658    setupDrawShader(getShader(paint));
2659    setupDrawBlending(paint, true);
2660    setupDrawProgram();
2661    setupDrawModelView(kModelViewMode_TranslateAndScale, false,
2662            sx, sy, sx + shadow->width, sy + shadow->height);
2663    setupDrawTexture(shadow->id);
2664    setupDrawPureColorUniforms();
2665    setupDrawColorFilterUniforms(getColorFilter(paint));
2666    setupDrawShaderUniforms(getShader(paint));
2667    setupDrawMesh(nullptr, (GLvoid*) kMeshTextureOffset);
2668
2669    glDrawArrays(GL_TRIANGLE_STRIP, 0, kMeshCount);
2670}
2671
2672bool OpenGLRenderer::canSkipText(const SkPaint* paint) const {
2673    float alpha = (hasTextShadow(paint) ? 1.0f : paint->getAlpha()) * currentSnapshot()->alpha;
2674    return MathUtils::isZero(alpha)
2675            && PaintUtils::getXfermode(paint->getXfermode()) == SkXfermode::kSrcOver_Mode;
2676}
2677
2678void OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count,
2679        const float* positions, const SkPaint* paint) {
2680    if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint)) {
2681        return;
2682    }
2683
2684    // NOTE: Skia does not support perspective transform on drawPosText yet
2685    if (!currentTransform()->isSimple()) {
2686        return;
2687    }
2688
2689    mRenderState.scissor().setEnabled(true);
2690
2691    float x = 0.0f;
2692    float y = 0.0f;
2693    const bool pureTranslate = currentTransform()->isPureTranslate();
2694    if (pureTranslate) {
2695        x = (int) floorf(x + currentTransform()->getTranslateX() + 0.5f);
2696        y = (int) floorf(y + currentTransform()->getTranslateY() + 0.5f);
2697    }
2698
2699    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2700    fontRenderer.setFont(paint, SkMatrix::I());
2701
2702    int alpha;
2703    SkXfermode::Mode mode;
2704    getAlphaAndMode(paint, &alpha, &mode);
2705
2706    if (CC_UNLIKELY(hasTextShadow(paint))) {
2707        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2708                alpha, 0.0f, 0.0f);
2709    }
2710
2711    // Pick the appropriate texture filtering
2712    bool linearFilter = currentTransform()->changesBounds();
2713    if (pureTranslate && !linearFilter) {
2714        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2715    }
2716    fontRenderer.setTextureFiltering(linearFilter);
2717
2718    const Rect& clip(pureTranslate ? writableSnapshot()->getClipRect() : writableSnapshot()->getLocalClip());
2719    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2720
2721    const bool hasActiveLayer = hasLayer();
2722
2723    TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint);
2724    if (fontRenderer.renderPosText(paint, &clip, text, 0, bytesCount, count, x, y,
2725            positions, hasActiveLayer ? &bounds : nullptr, &functor)) {
2726        if (hasActiveLayer) {
2727            if (!pureTranslate) {
2728                currentTransform()->mapRect(bounds);
2729            }
2730            dirtyLayerUnchecked(bounds, getRegion());
2731        }
2732    }
2733
2734    mDirty = true;
2735}
2736
2737bool OpenGLRenderer::findBestFontTransform(const mat4& transform, SkMatrix* outMatrix) const {
2738    if (CC_LIKELY(transform.isPureTranslate())) {
2739        outMatrix->setIdentity();
2740        return false;
2741    } else if (CC_UNLIKELY(transform.isPerspective())) {
2742        outMatrix->setIdentity();
2743        return true;
2744    }
2745
2746    /**
2747     * Input is a non-perspective, scaling transform. Generate a scale-only transform,
2748     * with values rounded to the nearest int.
2749     */
2750    float sx, sy;
2751    transform.decomposeScale(sx, sy);
2752    outMatrix->setScale(
2753            roundf(fmaxf(1.0f, sx)),
2754            roundf(fmaxf(1.0f, sy)));
2755    return true;
2756}
2757
2758int OpenGLRenderer::getSaveCount() const {
2759    return mState.getSaveCount();
2760}
2761
2762int OpenGLRenderer::save(int flags) {
2763    return mState.save(flags);
2764}
2765
2766void OpenGLRenderer::restore() {
2767    return mState.restore();
2768}
2769
2770void OpenGLRenderer::restoreToCount(int saveCount) {
2771    return mState.restoreToCount(saveCount);
2772}
2773
2774void OpenGLRenderer::translate(float dx, float dy, float dz) {
2775    return mState.translate(dx, dy, dz);
2776}
2777
2778void OpenGLRenderer::rotate(float degrees) {
2779    return mState.rotate(degrees);
2780}
2781
2782void OpenGLRenderer::scale(float sx, float sy) {
2783    return mState.scale(sx, sy);
2784}
2785
2786void OpenGLRenderer::skew(float sx, float sy) {
2787    return mState.skew(sx, sy);
2788}
2789
2790void OpenGLRenderer::setMatrix(const Matrix4& matrix) {
2791    mState.setMatrix(matrix);
2792}
2793
2794void OpenGLRenderer::concatMatrix(const Matrix4& matrix) {
2795    mState.concatMatrix(matrix);
2796}
2797
2798bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
2799    return mState.clipRect(left, top, right, bottom, op);
2800}
2801
2802bool OpenGLRenderer::clipPath(const SkPath* path, SkRegion::Op op) {
2803    return mState.clipPath(path, op);
2804}
2805
2806bool OpenGLRenderer::clipRegion(const SkRegion* region, SkRegion::Op op) {
2807    return mState.clipRegion(region, op);
2808}
2809
2810void OpenGLRenderer::setClippingOutline(LinearAllocator& allocator, const Outline* outline) {
2811    mState.setClippingOutline(allocator, outline);
2812}
2813
2814void OpenGLRenderer::setClippingRoundRect(LinearAllocator& allocator,
2815        const Rect& rect, float radius, bool highPriority) {
2816    mState.setClippingRoundRect(allocator, rect, radius, highPriority);
2817}
2818
2819void OpenGLRenderer::drawText(const char* text, int bytesCount, int count, float x, float y,
2820        const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds,
2821        DrawOpMode drawOpMode) {
2822
2823    if (drawOpMode == kDrawOpMode_Immediate) {
2824        // The checks for corner-case ignorable text and quick rejection is only done for immediate
2825        // drawing as ops from DeferredDisplayList are already filtered for these
2826        if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint) ||
2827                quickRejectSetupScissor(bounds)) {
2828            return;
2829        }
2830    }
2831
2832    const float oldX = x;
2833    const float oldY = y;
2834
2835    const mat4& transform = *currentTransform();
2836    const bool pureTranslate = transform.isPureTranslate();
2837
2838    if (CC_LIKELY(pureTranslate)) {
2839        x = (int) floorf(x + transform.getTranslateX() + 0.5f);
2840        y = (int) floorf(y + transform.getTranslateY() + 0.5f);
2841    }
2842
2843    int alpha;
2844    SkXfermode::Mode mode;
2845    getAlphaAndMode(paint, &alpha, &mode);
2846
2847    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2848
2849    if (CC_UNLIKELY(hasTextShadow(paint))) {
2850        fontRenderer.setFont(paint, SkMatrix::I());
2851        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2852                alpha, oldX, oldY);
2853    }
2854
2855    const bool hasActiveLayer = hasLayer();
2856
2857    // We only pass a partial transform to the font renderer. That partial
2858    // matrix defines how glyphs are rasterized. Typically we want glyphs
2859    // to be rasterized at their final size on screen, which means the partial
2860    // matrix needs to take the scale factor into account.
2861    // When a partial matrix is used to transform glyphs during rasterization,
2862    // the mesh is generated with the inverse transform (in the case of scale,
2863    // the mesh is generated at 1.0 / scale for instance.) This allows us to
2864    // apply the full transform matrix at draw time in the vertex shader.
2865    // Applying the full matrix in the shader is the easiest way to handle
2866    // rotation and perspective and allows us to always generated quads in the
2867    // font renderer which greatly simplifies the code, clipping in particular.
2868    SkMatrix fontTransform;
2869    bool linearFilter = findBestFontTransform(transform, &fontTransform)
2870            || fabs(y - (int) y) > 0.0f
2871            || fabs(x - (int) x) > 0.0f;
2872    fontRenderer.setFont(paint, fontTransform);
2873    fontRenderer.setTextureFiltering(linearFilter);
2874
2875    // TODO: Implement better clipping for scaled/rotated text
2876    const Rect* clip = !pureTranslate ? nullptr : &mState.currentClipRect();
2877    Rect layerBounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2878
2879    bool status;
2880    TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint);
2881
2882    // don't call issuedrawcommand, do it at end of batch
2883    bool forceFinish = (drawOpMode != kDrawOpMode_Defer);
2884    if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) {
2885        SkPaint paintCopy(*paint);
2886        paintCopy.setTextAlign(SkPaint::kLeft_Align);
2887        status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y,
2888                positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish);
2889    } else {
2890        status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2891                positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish);
2892    }
2893
2894    if ((status || drawOpMode != kDrawOpMode_Immediate) && hasActiveLayer) {
2895        if (!pureTranslate) {
2896            transform.mapRect(layerBounds);
2897        }
2898        dirtyLayerUnchecked(layerBounds, getRegion());
2899    }
2900
2901    drawTextDecorations(totalAdvance, oldX, oldY, paint);
2902
2903    mDirty = true;
2904}
2905
2906void OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count,
2907        const SkPath* path, float hOffset, float vOffset, const SkPaint* paint) {
2908    if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint)) {
2909        return;
2910    }
2911
2912    // TODO: avoid scissor by calculating maximum bounds using path bounds + font metrics
2913    mRenderState.scissor().setEnabled(true);
2914
2915    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2916    fontRenderer.setFont(paint, SkMatrix::I());
2917    fontRenderer.setTextureFiltering(true);
2918
2919    int alpha;
2920    SkXfermode::Mode mode;
2921    getAlphaAndMode(paint, &alpha, &mode);
2922    TextSetupFunctor functor(this, 0.0f, 0.0f, false, alpha, mode, paint);
2923
2924    const Rect* clip = &writableSnapshot()->getLocalClip();
2925    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2926
2927    const bool hasActiveLayer = hasLayer();
2928
2929    if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path,
2930            hOffset, vOffset, hasActiveLayer ? &bounds : nullptr, &functor)) {
2931        if (hasActiveLayer) {
2932            currentTransform()->mapRect(bounds);
2933            dirtyLayerUnchecked(bounds, getRegion());
2934        }
2935    }
2936
2937    mDirty = true;
2938}
2939
2940void OpenGLRenderer::drawPath(const SkPath* path, const SkPaint* paint) {
2941    if (mState.currentlyIgnored()) return;
2942
2943    mCaches.textureState().activateTexture(0);
2944
2945    const PathTexture* texture = mCaches.pathCache.get(path, paint);
2946    if (!texture) return;
2947    const AutoTexture autoCleanup(texture);
2948
2949    const float x = texture->left - texture->offset;
2950    const float y = texture->top - texture->offset;
2951
2952    drawPathTexture(texture, x, y, paint);
2953    mDirty = true;
2954}
2955
2956void OpenGLRenderer::drawLayer(Layer* layer, float x, float y) {
2957    if (!layer) {
2958        return;
2959    }
2960
2961    mat4* transform = nullptr;
2962    if (layer->isTextureLayer()) {
2963        transform = &layer->getTransform();
2964        if (!transform->isIdentity()) {
2965            save(SkCanvas::kMatrix_SaveFlag);
2966            concatMatrix(*transform);
2967        }
2968    }
2969
2970    bool clipRequired = false;
2971    const bool rejected = mState.calculateQuickRejectForScissor(
2972            x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(),
2973            &clipRequired, nullptr, false);
2974
2975    if (rejected) {
2976        if (transform && !transform->isIdentity()) {
2977            restore();
2978        }
2979        return;
2980    }
2981
2982    EVENT_LOGD("drawLayer," RECT_STRING ", clipRequired %d", x, y,
2983            x + layer->layer.getWidth(), y + layer->layer.getHeight(), clipRequired);
2984
2985    updateLayer(layer, true);
2986
2987    mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired);
2988    mCaches.textureState().activateTexture(0);
2989
2990    if (CC_LIKELY(!layer->region.isEmpty())) {
2991        if (layer->region.isRect()) {
2992            DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate,
2993                    composeLayerRect(layer, layer->regionRect));
2994        } else if (layer->mesh) {
2995
2996            const float a = getLayerAlpha(layer);
2997            setupDraw();
2998            setupDrawWithTexture();
2999            setupDrawColor(a, a, a, a);
3000            setupDrawColorFilter(layer->getColorFilter());
3001            setupDrawBlending(layer);
3002            setupDrawProgram();
3003            setupDrawPureColorUniforms();
3004            setupDrawColorFilterUniforms(layer->getColorFilter());
3005            setupDrawTexture(layer->getTexture());
3006            if (CC_LIKELY(currentTransform()->isPureTranslate())) {
3007                int tx = (int) floorf(x + currentTransform()->getTranslateX() + 0.5f);
3008                int ty = (int) floorf(y + currentTransform()->getTranslateY() + 0.5f);
3009
3010                layer->setFilter(GL_NEAREST);
3011                setupDrawModelView(kModelViewMode_Translate, false, tx, ty,
3012                        tx + layer->layer.getWidth(), ty + layer->layer.getHeight(), true);
3013            } else {
3014                layer->setFilter(GL_LINEAR);
3015                setupDrawModelView(kModelViewMode_Translate, false, x, y,
3016                        x + layer->layer.getWidth(), y + layer->layer.getHeight());
3017            }
3018
3019            TextureVertex* mesh = &layer->mesh[0];
3020            GLsizei elementsCount = layer->meshElementCount;
3021
3022            while (elementsCount > 0) {
3023                GLsizei drawCount = min(elementsCount, (GLsizei) kMaxNumberOfQuads * 6);
3024
3025                setupDrawMeshIndices(&mesh[0].x, &mesh[0].u);
3026                DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate,
3027                        glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_SHORT, nullptr));
3028
3029                elementsCount -= drawCount;
3030                // Though there are 4 vertices in a quad, we use 6 indices per
3031                // quad to draw with GL_TRIANGLES
3032                mesh += (drawCount / 6) * 4;
3033            }
3034
3035#if DEBUG_LAYERS_AS_REGIONS
3036            drawRegionRectsDebug(layer->region);
3037#endif
3038        }
3039
3040        if (layer->debugDrawUpdate) {
3041            layer->debugDrawUpdate = false;
3042
3043            SkPaint paint;
3044            paint.setColor(0x7f00ff00);
3045            drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(), &paint);
3046        }
3047    }
3048    layer->hasDrawnSinceUpdate = true;
3049
3050    if (transform && !transform->isIdentity()) {
3051        restore();
3052    }
3053
3054    mDirty = true;
3055}
3056
3057///////////////////////////////////////////////////////////////////////////////
3058// Draw filters
3059///////////////////////////////////////////////////////////////////////////////
3060void OpenGLRenderer::setDrawFilter(SkDrawFilter* filter) {
3061    // We should never get here since we apply the draw filter when stashing
3062    // the paints in the DisplayList.
3063    LOG_ALWAYS_FATAL("OpenGLRenderer does not directly support DrawFilters");
3064}
3065
3066///////////////////////////////////////////////////////////////////////////////
3067// Drawing implementation
3068///////////////////////////////////////////////////////////////////////////////
3069
3070Texture* OpenGLRenderer::getTexture(const SkBitmap* bitmap) {
3071    Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap);
3072    if (!texture) {
3073        return mCaches.textureCache.get(bitmap);
3074    }
3075    return texture;
3076}
3077
3078void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
3079        float x, float y, const SkPaint* paint) {
3080    if (quickRejectSetupScissor(x, y, x + texture->width, y + texture->height)) {
3081        return;
3082    }
3083
3084    int alpha;
3085    SkXfermode::Mode mode;
3086    getAlphaAndMode(paint, &alpha, &mode);
3087
3088    setupDraw();
3089    setupDrawWithTexture(true);
3090    setupDrawAlpha8Color(paint->getColor(), alpha);
3091    setupDrawColorFilter(getColorFilter(paint));
3092    setupDrawShader(getShader(paint));
3093    setupDrawBlending(paint, true);
3094    setupDrawProgram();
3095    setupDrawModelView(kModelViewMode_TranslateAndScale, false,
3096            x, y, x + texture->width, y + texture->height);
3097    setupDrawTexture(texture->id);
3098    setupDrawPureColorUniforms();
3099    setupDrawColorFilterUniforms(getColorFilter(paint));
3100    setupDrawShaderUniforms(getShader(paint));
3101    setupDrawMesh(nullptr, (GLvoid*) kMeshTextureOffset);
3102
3103    glDrawArrays(GL_TRIANGLE_STRIP, 0, kMeshCount);
3104}
3105
3106// Same values used by Skia
3107#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
3108#define kStdUnderline_Offset    (1.0f / 9.0f)
3109#define kStdUnderline_Thickness (1.0f / 18.0f)
3110
3111void OpenGLRenderer::drawTextDecorations(float underlineWidth, float x, float y,
3112        const SkPaint* paint) {
3113    // Handle underline and strike-through
3114    uint32_t flags = paint->getFlags();
3115    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
3116        SkPaint paintCopy(*paint);
3117
3118        if (CC_LIKELY(underlineWidth > 0.0f)) {
3119            const float textSize = paintCopy.getTextSize();
3120            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
3121
3122            const float left = x;
3123            float top = 0.0f;
3124
3125            int linesCount = 0;
3126            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
3127            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
3128
3129            const int pointsCount = 4 * linesCount;
3130            float points[pointsCount];
3131            int currentPoint = 0;
3132
3133            if (flags & SkPaint::kUnderlineText_Flag) {
3134                top = y + textSize * kStdUnderline_Offset;
3135                points[currentPoint++] = left;
3136                points[currentPoint++] = top;
3137                points[currentPoint++] = left + underlineWidth;
3138                points[currentPoint++] = top;
3139            }
3140
3141            if (flags & SkPaint::kStrikeThruText_Flag) {
3142                top = y + textSize * kStdStrikeThru_Offset;
3143                points[currentPoint++] = left;
3144                points[currentPoint++] = top;
3145                points[currentPoint++] = left + underlineWidth;
3146                points[currentPoint++] = top;
3147            }
3148
3149            paintCopy.setStrokeWidth(strokeWidth);
3150
3151            drawLines(&points[0], pointsCount, &paintCopy);
3152        }
3153    }
3154}
3155
3156void OpenGLRenderer::drawRects(const float* rects, int count, const SkPaint* paint) {
3157    if (mState.currentlyIgnored()) {
3158        return;
3159    }
3160
3161    drawColorRects(rects, count, paint, false, true, true);
3162}
3163
3164void OpenGLRenderer::drawShadow(float casterAlpha,
3165        const VertexBuffer* ambientShadowVertexBuffer, const VertexBuffer* spotShadowVertexBuffer) {
3166    if (mState.currentlyIgnored()) return;
3167
3168    // TODO: use quickRejectWithScissor. For now, always force enable scissor.
3169    mRenderState.scissor().setEnabled(true);
3170
3171    SkPaint paint;
3172    paint.setAntiAlias(true); // want to use AlphaVertex
3173
3174    // The caller has made sure casterAlpha > 0.
3175    float ambientShadowAlpha = mAmbientShadowAlpha;
3176    if (CC_UNLIKELY(mCaches.propertyAmbientShadowStrength >= 0)) {
3177        ambientShadowAlpha = mCaches.propertyAmbientShadowStrength;
3178    }
3179    if (ambientShadowVertexBuffer && ambientShadowAlpha > 0) {
3180        paint.setARGB(casterAlpha * ambientShadowAlpha, 0, 0, 0);
3181        drawVertexBuffer(*ambientShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp);
3182    }
3183
3184    float spotShadowAlpha = mSpotShadowAlpha;
3185    if (CC_UNLIKELY(mCaches.propertySpotShadowStrength >= 0)) {
3186        spotShadowAlpha = mCaches.propertySpotShadowStrength;
3187    }
3188    if (spotShadowVertexBuffer && spotShadowAlpha > 0) {
3189        paint.setARGB(casterAlpha * spotShadowAlpha, 0, 0, 0);
3190        drawVertexBuffer(*spotShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp);
3191    }
3192
3193    mDirty=true;
3194}
3195
3196void OpenGLRenderer::drawColorRects(const float* rects, int count, const SkPaint* paint,
3197        bool ignoreTransform, bool dirty, bool clip) {
3198    if (count == 0) {
3199        return;
3200    }
3201
3202    int color = paint->getColor();
3203    // If a shader is set, preserve only the alpha
3204    if (getShader(paint)) {
3205        color |= 0x00ffffff;
3206    }
3207
3208    float left = FLT_MAX;
3209    float top = FLT_MAX;
3210    float right = FLT_MIN;
3211    float bottom = FLT_MIN;
3212
3213    Vertex mesh[count];
3214    Vertex* vertex = mesh;
3215
3216    for (int index = 0; index < count; index += 4) {
3217        float l = rects[index + 0];
3218        float t = rects[index + 1];
3219        float r = rects[index + 2];
3220        float b = rects[index + 3];
3221
3222        Vertex::set(vertex++, l, t);
3223        Vertex::set(vertex++, r, t);
3224        Vertex::set(vertex++, l, b);
3225        Vertex::set(vertex++, r, b);
3226
3227        left = fminf(left, l);
3228        top = fminf(top, t);
3229        right = fmaxf(right, r);
3230        bottom = fmaxf(bottom, b);
3231    }
3232
3233    if (clip && quickRejectSetupScissor(left, top, right, bottom)) {
3234        return;
3235    }
3236
3237    setupDraw();
3238    setupDrawNoTexture();
3239    setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha);
3240    setupDrawShader(getShader(paint));
3241    setupDrawColorFilter(getColorFilter(paint));
3242    setupDrawBlending(paint);
3243    setupDrawProgram();
3244    setupDrawDirtyRegionsDisabled();
3245    setupDrawModelView(kModelViewMode_Translate, false,
3246            0.0f, 0.0f, 0.0f, 0.0f, ignoreTransform);
3247    setupDrawColorUniforms(getShader(paint));
3248    setupDrawShaderUniforms(getShader(paint));
3249    setupDrawColorFilterUniforms(getColorFilter(paint));
3250
3251    if (dirty && hasLayer()) {
3252        dirtyLayer(left, top, right, bottom, *currentTransform());
3253    }
3254
3255    issueIndexedQuadDraw(&mesh[0], count / 4);
3256
3257    mDirty = true;
3258}
3259
3260void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
3261        const SkPaint* paint, bool ignoreTransform) {
3262    int color = paint->getColor();
3263    // If a shader is set, preserve only the alpha
3264    if (getShader(paint)) {
3265        color |= 0x00ffffff;
3266    }
3267
3268    setupDraw();
3269    setupDrawNoTexture();
3270    setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha);
3271    setupDrawShader(getShader(paint));
3272    setupDrawColorFilter(getColorFilter(paint));
3273    setupDrawBlending(paint);
3274    setupDrawProgram();
3275    setupDrawModelView(kModelViewMode_TranslateAndScale, false,
3276            left, top, right, bottom, ignoreTransform);
3277    setupDrawColorUniforms(getShader(paint));
3278    setupDrawShaderUniforms(getShader(paint), ignoreTransform);
3279    setupDrawColorFilterUniforms(getColorFilter(paint));
3280    setupDrawSimpleMesh();
3281
3282    glDrawArrays(GL_TRIANGLE_STRIP, 0, kMeshCount);
3283}
3284
3285void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
3286        Texture* texture, const SkPaint* paint) {
3287    texture->setWrap(GL_CLAMP_TO_EDGE, true);
3288
3289    GLvoid* vertices = (GLvoid*) nullptr;
3290    GLvoid* texCoords = (GLvoid*) kMeshTextureOffset;
3291
3292    if (texture->uvMapper) {
3293        vertices = &mMeshVertices[0].x;
3294        texCoords = &mMeshVertices[0].u;
3295
3296        Rect uvs(0.0f, 0.0f, 1.0f, 1.0f);
3297        texture->uvMapper->map(uvs);
3298
3299        resetDrawTextureTexCoords(uvs.left, uvs.top, uvs.right, uvs.bottom);
3300    }
3301
3302    if (CC_LIKELY(currentTransform()->isPureTranslate())) {
3303        const float x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f);
3304        const float y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f);
3305
3306        texture->setFilter(GL_NEAREST, true);
3307        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
3308                paint, texture->blend, vertices, texCoords,
3309                GL_TRIANGLE_STRIP, kMeshCount, false, true);
3310    } else {
3311        texture->setFilter(getFilter(paint), true);
3312        drawTextureMesh(left, top, right, bottom, texture->id, paint,
3313                texture->blend, vertices, texCoords, GL_TRIANGLE_STRIP, kMeshCount);
3314    }
3315
3316    if (texture->uvMapper) {
3317        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
3318    }
3319}
3320
3321void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
3322        GLuint texture, const SkPaint* paint, bool blend,
3323        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3324        bool swapSrcDst, bool ignoreTransform, GLuint vbo,
3325        ModelViewMode modelViewMode, bool dirty) {
3326
3327    int a;
3328    SkXfermode::Mode mode;
3329    getAlphaAndMode(paint, &a, &mode);
3330    const float alpha = a / 255.0f;
3331
3332    setupDraw();
3333    setupDrawWithTexture();
3334    setupDrawColor(alpha, alpha, alpha, alpha);
3335    setupDrawColorFilter(getColorFilter(paint));
3336    setupDrawBlending(paint, blend, swapSrcDst);
3337    setupDrawProgram();
3338    if (!dirty) setupDrawDirtyRegionsDisabled();
3339    setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform);
3340    setupDrawTexture(texture);
3341    setupDrawPureColorUniforms();
3342    setupDrawColorFilterUniforms(getColorFilter(paint));
3343    setupDrawMesh(vertices, texCoords, vbo);
3344
3345    glDrawArrays(drawMode, 0, elementsCount);
3346}
3347
3348void OpenGLRenderer::drawIndexedTextureMesh(float left, float top, float right, float bottom,
3349        GLuint texture, const SkPaint* paint, bool blend,
3350        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3351        bool swapSrcDst, bool ignoreTransform, GLuint vbo,
3352        ModelViewMode modelViewMode, bool dirty) {
3353
3354    int a;
3355    SkXfermode::Mode mode;
3356    getAlphaAndMode(paint, &a, &mode);
3357    const float alpha = a / 255.0f;
3358
3359    setupDraw();
3360    setupDrawWithTexture();
3361    setupDrawColor(alpha, alpha, alpha, alpha);
3362    setupDrawColorFilter(getColorFilter(paint));
3363    setupDrawBlending(paint, blend, swapSrcDst);
3364    setupDrawProgram();
3365    if (!dirty) setupDrawDirtyRegionsDisabled();
3366    setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform);
3367    setupDrawTexture(texture);
3368    setupDrawPureColorUniforms();
3369    setupDrawColorFilterUniforms(getColorFilter(paint));
3370    setupDrawMeshIndices(vertices, texCoords, vbo);
3371
3372    glDrawElements(drawMode, elementsCount, GL_UNSIGNED_SHORT, nullptr);
3373}
3374
3375void OpenGLRenderer::drawAlpha8TextureMesh(float left, float top, float right, float bottom,
3376        GLuint texture, const SkPaint* paint,
3377        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3378        bool ignoreTransform, ModelViewMode modelViewMode, bool dirty) {
3379
3380    int color = paint != nullptr ? paint->getColor() : 0;
3381    int alpha;
3382    SkXfermode::Mode mode;
3383    getAlphaAndMode(paint, &alpha, &mode);
3384
3385    setupDraw();
3386    setupDrawWithTexture(true);
3387    if (paint != nullptr) {
3388        setupDrawAlpha8Color(color, alpha);
3389    }
3390    setupDrawColorFilter(getColorFilter(paint));
3391    setupDrawShader(getShader(paint));
3392    setupDrawBlending(paint, true);
3393    setupDrawProgram();
3394    if (!dirty) setupDrawDirtyRegionsDisabled();
3395    setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform);
3396    setupDrawTexture(texture);
3397    setupDrawPureColorUniforms();
3398    setupDrawColorFilterUniforms(getColorFilter(paint));
3399    setupDrawShaderUniforms(getShader(paint), ignoreTransform);
3400    setupDrawMesh(vertices, texCoords);
3401
3402    glDrawArrays(drawMode, 0, elementsCount);
3403}
3404
3405void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
3406        ProgramDescription& description, bool swapSrcDst) {
3407
3408    if (writableSnapshot()->roundRectClipState != nullptr /*&& !mSkipOutlineClip*/) {
3409        blend = true;
3410        mDescription.hasRoundRectClip = true;
3411    }
3412    mSkipOutlineClip = true;
3413
3414    blend = blend || mode != SkXfermode::kSrcOver_Mode;
3415
3416    if (blend) {
3417        // These blend modes are not supported by OpenGL directly and have
3418        // to be implemented using shaders. Since the shader will perform
3419        // the blending, turn blending off here
3420        // If the blend mode cannot be implemented using shaders, fall
3421        // back to the default SrcOver blend mode instead
3422        if (CC_UNLIKELY(mode > SkXfermode::kScreen_Mode)) {
3423            if (CC_UNLIKELY(mExtensions.hasFramebufferFetch())) {
3424                description.framebufferMode = mode;
3425                description.swapSrcDst = swapSrcDst;
3426
3427                mRenderState.blend().disable();
3428                return;
3429            } else {
3430                mode = SkXfermode::kSrcOver_Mode;
3431            }
3432        }
3433        mRenderState.blend().enable(mode, swapSrcDst);
3434    } else {
3435        mRenderState.blend().disable();
3436    }
3437}
3438
3439void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
3440    TextureVertex* v = &mMeshVertices[0];
3441    TextureVertex::setUV(v++, u1, v1);
3442    TextureVertex::setUV(v++, u2, v1);
3443    TextureVertex::setUV(v++, u1, v2);
3444    TextureVertex::setUV(v++, u2, v2);
3445}
3446
3447void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha,
3448        SkXfermode::Mode* mode) const {
3449    getAlphaAndModeDirect(paint, alpha,  mode);
3450    if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) {
3451        // if drawing a layer, ignore the paint's alpha
3452        *alpha = mDrawModifiers.mOverrideLayerAlpha * 255;
3453    }
3454    *alpha *= currentSnapshot()->alpha;
3455}
3456
3457float OpenGLRenderer::getLayerAlpha(const Layer* layer) const {
3458    float alpha;
3459    if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) {
3460        alpha = mDrawModifiers.mOverrideLayerAlpha;
3461    } else {
3462        alpha = layer->getAlpha() / 255.0f;
3463    }
3464    return alpha * currentSnapshot()->alpha;
3465}
3466
3467}; // namespace uirenderer
3468}; // namespace android
3469