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