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