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