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