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