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