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