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