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