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