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