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