OpenGLRenderer.cpp revision 8d4aeb7111afac0c3c7e56d4ad5d92f9cfce2ffd
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 = mCaches.renderBufferCache.get(
1277                Stencil::getSmallestStencilFormat(), layer->getWidth(), layer->getHeight());
1278        layer->setStencilRenderBuffer(buffer);
1279
1280        startTiling(layer->clipRect, layer->layer.getHeight());
1281    }
1282}
1283
1284void OpenGLRenderer::setStencilFromClip() {
1285    if (!mCaches.debugOverdraw) {
1286        if (!mSnapshot->clipRegion->isEmpty()) {
1287            // NOTE: The order here is important, we must set dirtyClip to false
1288            //       before any draw call to avoid calling back into this method
1289            mDirtyClip = false;
1290
1291            ensureStencilBuffer();
1292
1293            mCaches.stencil.enableWrite();
1294
1295            // Clear the stencil but first make sure we restrict drawing
1296            // to the region's bounds
1297            bool resetScissor = mCaches.enableScissor();
1298            if (resetScissor) {
1299                // The scissor was not set so we now need to update it
1300                setScissorFromClip();
1301            }
1302            mCaches.stencil.clear();
1303            if (resetScissor) mCaches.disableScissor();
1304
1305            // NOTE: We could use the region contour path to generate a smaller mesh
1306            //       Since we are using the stencil we could use the red book path
1307            //       drawing technique. It might increase bandwidth usage though.
1308
1309            // The last parameter is important: we are not drawing in the color buffer
1310            // so we don't want to dirty the current layer, if any
1311            drawRegionRects(*mSnapshot->clipRegion, 0xff000000, SkXfermode::kSrc_Mode, false);
1312
1313            mCaches.stencil.enableTest();
1314        } else {
1315            mCaches.stencil.disable();
1316        }
1317    }
1318}
1319
1320const Rect& OpenGLRenderer::getClipBounds() {
1321    return mSnapshot->getLocalClip();
1322}
1323
1324bool OpenGLRenderer::quickRejectNoScissor(float left, float top, float right, float bottom) {
1325    if (mSnapshot->isIgnored()) {
1326        return true;
1327    }
1328
1329    Rect r(left, top, right, bottom);
1330    mSnapshot->transform->mapRect(r);
1331    r.snapToPixelBoundaries();
1332
1333    Rect clipRect(*mSnapshot->clipRect);
1334    clipRect.snapToPixelBoundaries();
1335
1336    return !clipRect.intersects(r);
1337}
1338
1339bool OpenGLRenderer::quickRejectNoScissor(float left, float top, float right, float bottom,
1340        Rect& transformed, Rect& clip) {
1341    if (mSnapshot->isIgnored()) {
1342        return true;
1343    }
1344
1345    transformed.set(left, top, right, bottom);
1346    mSnapshot->transform->mapRect(transformed);
1347    transformed.snapToPixelBoundaries();
1348
1349    clip.set(*mSnapshot->clipRect);
1350    clip.snapToPixelBoundaries();
1351
1352    return !clip.intersects(transformed);
1353}
1354
1355bool OpenGLRenderer::quickRejectPreStroke(float left, float top, float right, float bottom,
1356        SkPaint* paint) {
1357    if (paint->getStyle() != SkPaint::kFill_Style) {
1358        float outset = paint->getStrokeWidth() * 0.5f;
1359        return quickReject(left - outset, top - outset, right + outset, bottom + outset);
1360    } else {
1361        return quickReject(left, top, right, bottom);
1362    }
1363}
1364
1365bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
1366    if (mSnapshot->isIgnored() || bottom <= top || right <= left) {
1367        return true;
1368    }
1369
1370    Rect r(left, top, right, bottom);
1371    mSnapshot->transform->mapRect(r);
1372    r.snapToPixelBoundaries();
1373
1374    Rect clipRect(*mSnapshot->clipRect);
1375    clipRect.snapToPixelBoundaries();
1376
1377    bool rejected = !clipRect.intersects(r);
1378    if (!isDeferred() && !rejected) {
1379        mCaches.setScissorEnabled(mScissorOptimizationDisabled || !clipRect.contains(r));
1380    }
1381
1382    return rejected;
1383}
1384
1385void OpenGLRenderer::debugClip() {
1386#if DEBUG_CLIP_REGIONS
1387    if (!isDeferred() && !mSnapshot->clipRegion->isEmpty()) {
1388        drawRegionRects(*mSnapshot->clipRegion, 0x7f00ff00, SkXfermode::kSrcOver_Mode);
1389    }
1390#endif
1391}
1392
1393bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
1394    if (CC_LIKELY(mSnapshot->transform->rectToRect())) {
1395        bool clipped = mSnapshot->clip(left, top, right, bottom, op);
1396        if (clipped) {
1397            dirtyClip();
1398        }
1399        return !mSnapshot->clipRect->isEmpty();
1400    }
1401
1402    SkPath path;
1403    path.addRect(left, top, right, bottom);
1404
1405    return clipPath(&path, op);
1406}
1407
1408bool OpenGLRenderer::clipPath(SkPath* path, SkRegion::Op op) {
1409    SkMatrix transform;
1410    mSnapshot->transform->copyTo(transform);
1411
1412    SkPath transformed;
1413    path->transform(transform, &transformed);
1414
1415    SkRegion clip;
1416    if (!mSnapshot->clipRegion->isEmpty()) {
1417        clip.setRegion(*mSnapshot->clipRegion);
1418    } else {
1419        Rect* bounds = mSnapshot->clipRect;
1420        clip.setRect(bounds->left, bounds->top, bounds->right, bounds->bottom);
1421    }
1422
1423    SkRegion region;
1424    region.setPath(transformed, clip);
1425
1426    bool clipped = mSnapshot->clipRegionTransformed(region, op);
1427    if (clipped) {
1428        dirtyClip();
1429    }
1430    return !mSnapshot->clipRect->isEmpty();
1431}
1432
1433bool OpenGLRenderer::clipRegion(SkRegion* region, SkRegion::Op op) {
1434    bool clipped = mSnapshot->clipRegionTransformed(*region, op);
1435    if (clipped) {
1436        dirtyClip();
1437    }
1438    return !mSnapshot->clipRect->isEmpty();
1439}
1440
1441Rect* OpenGLRenderer::getClipRect() {
1442    return mSnapshot->clipRect;
1443}
1444
1445///////////////////////////////////////////////////////////////////////////////
1446// Drawing commands
1447///////////////////////////////////////////////////////////////////////////////
1448
1449void OpenGLRenderer::setupDraw(bool clear) {
1450    // TODO: It would be best if we could do this before quickReject()
1451    //       changes the scissor test state
1452    if (clear) clearLayerRegions();
1453    // Make sure setScissor & setStencil happen at the beginning of
1454    // this method
1455    if (mDirtyClip) {
1456        setScissorFromClip();
1457        setStencilFromClip();
1458    }
1459    mDescription.reset();
1460    mSetShaderColor = false;
1461    mColorSet = false;
1462    mColorA = mColorR = mColorG = mColorB = 0.0f;
1463    mTextureUnit = 0;
1464    mTrackDirtyRegions = true;
1465}
1466
1467void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
1468    mDescription.hasTexture = true;
1469    mDescription.hasAlpha8Texture = isAlpha8;
1470}
1471
1472void OpenGLRenderer::setupDrawWithExternalTexture() {
1473    mDescription.hasExternalTexture = true;
1474}
1475
1476void OpenGLRenderer::setupDrawNoTexture() {
1477    mCaches.disbaleTexCoordsVertexArray();
1478}
1479
1480void OpenGLRenderer::setupDrawAA() {
1481    mDescription.isAA = true;
1482}
1483
1484void OpenGLRenderer::setupDrawPoint(float pointSize) {
1485    mDescription.isPoint = true;
1486    mDescription.pointSize = pointSize;
1487}
1488
1489void OpenGLRenderer::setupDrawColor(int color, int alpha) {
1490    mColorA = alpha / 255.0f;
1491    mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f;
1492    mColorG = mColorA * ((color >>  8) & 0xFF) / 255.0f;
1493    mColorB = mColorA * ((color      ) & 0xFF) / 255.0f;
1494    mColorSet = true;
1495    mSetShaderColor = mDescription.setColor(mColorR, mColorG, mColorB, mColorA);
1496}
1497
1498void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
1499    mColorA = alpha / 255.0f;
1500    mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f;
1501    mColorG = mColorA * ((color >>  8) & 0xFF) / 255.0f;
1502    mColorB = mColorA * ((color      ) & 0xFF) / 255.0f;
1503    mColorSet = true;
1504    mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA);
1505}
1506
1507void OpenGLRenderer::setupDrawTextGamma(const SkPaint* paint) {
1508    mCaches.fontRenderer->describe(mDescription, paint);
1509}
1510
1511void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
1512    mColorA = a;
1513    mColorR = r;
1514    mColorG = g;
1515    mColorB = b;
1516    mColorSet = true;
1517    mSetShaderColor = mDescription.setColor(r, g, b, a);
1518}
1519
1520void OpenGLRenderer::setupDrawShader() {
1521    if (mShader) {
1522        mShader->describe(mDescription, mExtensions);
1523    }
1524}
1525
1526void OpenGLRenderer::setupDrawColorFilter() {
1527    if (mColorFilter) {
1528        mColorFilter->describe(mDescription, mExtensions);
1529    }
1530}
1531
1532void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) {
1533    if (mColorSet && mode == SkXfermode::kClear_Mode) {
1534        mColorA = 1.0f;
1535        mColorR = mColorG = mColorB = 0.0f;
1536        mSetShaderColor = mDescription.modulate = true;
1537    }
1538}
1539
1540void OpenGLRenderer::setupDrawBlending(SkXfermode::Mode mode, bool swapSrcDst) {
1541    // When the blending mode is kClear_Mode, we need to use a modulate color
1542    // argb=1,0,0,0
1543    accountForClear(mode);
1544    chooseBlending((mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
1545            mDescription, swapSrcDst);
1546}
1547
1548void OpenGLRenderer::setupDrawBlending(bool blend, SkXfermode::Mode mode, bool swapSrcDst) {
1549    // When the blending mode is kClear_Mode, we need to use a modulate color
1550    // argb=1,0,0,0
1551    accountForClear(mode);
1552    chooseBlending(blend || (mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()) ||
1553            (mColorFilter && mColorFilter->blend()), mode, mDescription, swapSrcDst);
1554}
1555
1556void OpenGLRenderer::setupDrawProgram() {
1557    useProgram(mCaches.programCache.get(mDescription));
1558}
1559
1560void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
1561    mTrackDirtyRegions = false;
1562}
1563
1564void OpenGLRenderer::setupDrawModelViewTranslate(float left, float top, float right, float bottom,
1565        bool ignoreTransform) {
1566    mModelView.loadTranslate(left, top, 0.0f);
1567    if (!ignoreTransform) {
1568        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1569        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1570    } else {
1571        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
1572        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom);
1573    }
1574}
1575
1576void OpenGLRenderer::setupDrawModelViewIdentity(bool offset) {
1577    mCaches.currentProgram->set(mOrthoMatrix, mIdentity, *mSnapshot->transform, offset);
1578}
1579
1580void OpenGLRenderer::setupDrawModelView(float left, float top, float right, float bottom,
1581        bool ignoreTransform, bool ignoreModelView) {
1582    if (!ignoreModelView) {
1583        mModelView.loadTranslate(left, top, 0.0f);
1584        mModelView.scale(right - left, bottom - top, 1.0f);
1585    } else {
1586        mModelView.loadIdentity();
1587    }
1588    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
1589    if (!ignoreTransform) {
1590        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1591        if (mTrackDirtyRegions && dirty) {
1592            dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1593        }
1594    } else {
1595        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
1596        if (mTrackDirtyRegions && dirty) dirtyLayer(left, top, right, bottom);
1597    }
1598}
1599
1600void OpenGLRenderer::setupDrawPointUniforms() {
1601    int slot = mCaches.currentProgram->getUniform("pointSize");
1602    glUniform1f(slot, mDescription.pointSize);
1603}
1604
1605void OpenGLRenderer::setupDrawColorUniforms() {
1606    if ((mColorSet && !mShader) || (mShader && mSetShaderColor)) {
1607        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1608    }
1609}
1610
1611void OpenGLRenderer::setupDrawPureColorUniforms() {
1612    if (mSetShaderColor) {
1613        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1614    }
1615}
1616
1617void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) {
1618    if (mShader) {
1619        if (ignoreTransform) {
1620            mModelView.loadInverse(*mSnapshot->transform);
1621        }
1622        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &mTextureUnit);
1623    }
1624}
1625
1626void OpenGLRenderer::setupDrawShaderIdentityUniforms() {
1627    if (mShader) {
1628        mShader->setupProgram(mCaches.currentProgram, mIdentity, *mSnapshot, &mTextureUnit);
1629    }
1630}
1631
1632void OpenGLRenderer::setupDrawColorFilterUniforms() {
1633    if (mColorFilter) {
1634        mColorFilter->setupProgram(mCaches.currentProgram);
1635    }
1636}
1637
1638void OpenGLRenderer::setupDrawTextGammaUniforms() {
1639    mCaches.fontRenderer->setupProgram(mDescription, mCaches.currentProgram);
1640}
1641
1642void OpenGLRenderer::setupDrawSimpleMesh() {
1643    bool force = mCaches.bindMeshBuffer();
1644    mCaches.bindPositionVertexPointer(force, 0);
1645    mCaches.unbindIndicesBuffer();
1646}
1647
1648void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1649    bindTexture(texture);
1650    mTextureUnit++;
1651    mCaches.enableTexCoordsVertexArray();
1652}
1653
1654void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) {
1655    bindExternalTexture(texture);
1656    mTextureUnit++;
1657    mCaches.enableTexCoordsVertexArray();
1658}
1659
1660void OpenGLRenderer::setupDrawTextureTransform() {
1661    mDescription.hasTextureTransform = true;
1662}
1663
1664void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) {
1665    glUniformMatrix4fv(mCaches.currentProgram->getUniform("mainTextureTransform"), 1,
1666            GL_FALSE, &transform.data[0]);
1667}
1668
1669void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
1670    bool force = false;
1671    if (!vertices) {
1672        force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1673    } else {
1674        force = mCaches.unbindMeshBuffer();
1675    }
1676
1677    mCaches.bindPositionVertexPointer(force, vertices);
1678    if (mCaches.currentProgram->texCoords >= 0) {
1679        mCaches.bindTexCoordsVertexPointer(force, texCoords);
1680    }
1681
1682    mCaches.unbindIndicesBuffer();
1683}
1684
1685void OpenGLRenderer::setupDrawMeshIndices(GLvoid* vertices, GLvoid* texCoords) {
1686    bool force = mCaches.unbindMeshBuffer();
1687    mCaches.bindPositionVertexPointer(force, vertices);
1688    if (mCaches.currentProgram->texCoords >= 0) {
1689        mCaches.bindTexCoordsVertexPointer(force, texCoords);
1690    }
1691}
1692
1693void OpenGLRenderer::setupDrawVertices(GLvoid* vertices) {
1694    bool force = mCaches.unbindMeshBuffer();
1695    mCaches.bindPositionVertexPointer(force, vertices, gVertexStride);
1696    mCaches.unbindIndicesBuffer();
1697}
1698
1699void OpenGLRenderer::finishDrawTexture() {
1700}
1701
1702///////////////////////////////////////////////////////////////////////////////
1703// Drawing
1704///////////////////////////////////////////////////////////////////////////////
1705
1706status_t OpenGLRenderer::drawDisplayList(DisplayList* displayList,
1707        Rect& dirty, int32_t flags, uint32_t level) {
1708
1709    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1710    // will be performed by the display list itself
1711    if (displayList && displayList->isRenderable()) {
1712        return displayList->replay(*this, dirty, flags, level);
1713    }
1714
1715    return DrawGlInfo::kStatusDone;
1716}
1717
1718void OpenGLRenderer::outputDisplayList(DisplayList* displayList, uint32_t level) {
1719    if (displayList) {
1720        displayList->output(level);
1721    }
1722}
1723
1724void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, SkPaint* paint) {
1725    int alpha;
1726    SkXfermode::Mode mode;
1727    getAlphaAndMode(paint, &alpha, &mode);
1728
1729    int color = paint != NULL ? paint->getColor() : 0;
1730
1731    float x = left;
1732    float y = top;
1733
1734    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1735
1736    bool ignoreTransform = false;
1737    if (mSnapshot->transform->isPureTranslate()) {
1738        x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1739        y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1740        ignoreTransform = true;
1741
1742        texture->setFilter(GL_NEAREST, true);
1743    } else {
1744        texture->setFilter(FILTER(paint), true);
1745    }
1746
1747    drawAlpha8TextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
1748            paint != NULL, color, alpha, mode, (GLvoid*) NULL,
1749            (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform);
1750}
1751
1752status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
1753    const float right = left + bitmap->width();
1754    const float bottom = top + bitmap->height();
1755
1756    if (quickReject(left, top, right, bottom)) {
1757        return DrawGlInfo::kStatusDone;
1758    }
1759
1760    mCaches.activeTexture(0);
1761    Texture* texture = mCaches.textureCache.get(bitmap);
1762    if (!texture) return DrawGlInfo::kStatusDone;
1763    const AutoTexture autoCleanup(texture);
1764
1765    if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
1766        drawAlphaBitmap(texture, left, top, paint);
1767    } else {
1768        drawTextureRect(left, top, right, bottom, texture, paint);
1769    }
1770
1771    return DrawGlInfo::kStatusDrew;
1772}
1773
1774status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
1775    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
1776    const mat4 transform(*matrix);
1777    transform.mapRect(r);
1778
1779    if (quickReject(r.left, r.top, r.right, r.bottom)) {
1780        return DrawGlInfo::kStatusDone;
1781    }
1782
1783    mCaches.activeTexture(0);
1784    Texture* texture = mCaches.textureCache.get(bitmap);
1785    if (!texture) return DrawGlInfo::kStatusDone;
1786    const AutoTexture autoCleanup(texture);
1787
1788    // This could be done in a cheaper way, all we need is pass the matrix
1789    // to the vertex shader. The save/restore is a bit overkill.
1790    save(SkCanvas::kMatrix_SaveFlag);
1791    concatMatrix(matrix);
1792    if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
1793        drawAlphaBitmap(texture, 0.0f, 0.0f, paint);
1794    } else {
1795        drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
1796    }
1797    restore();
1798
1799    return DrawGlInfo::kStatusDrew;
1800}
1801
1802status_t OpenGLRenderer::drawBitmapData(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
1803    const float right = left + bitmap->width();
1804    const float bottom = top + bitmap->height();
1805
1806    if (quickReject(left, top, right, bottom)) {
1807        return DrawGlInfo::kStatusDone;
1808    }
1809
1810    mCaches.activeTexture(0);
1811    Texture* texture = mCaches.textureCache.getTransient(bitmap);
1812    const AutoTexture autoCleanup(texture);
1813
1814    if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
1815        drawAlphaBitmap(texture, left, top, paint);
1816    } else {
1817        drawTextureRect(left, top, right, bottom, texture, paint);
1818    }
1819
1820    return DrawGlInfo::kStatusDrew;
1821}
1822
1823status_t OpenGLRenderer::drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight,
1824        float* vertices, int* colors, SkPaint* paint) {
1825    if (!vertices || mSnapshot->isIgnored()) {
1826        return DrawGlInfo::kStatusDone;
1827    }
1828
1829    float left = FLT_MAX;
1830    float top = FLT_MAX;
1831    float right = FLT_MIN;
1832    float bottom = FLT_MIN;
1833
1834    const uint32_t count = meshWidth * meshHeight * 6;
1835
1836    // TODO: Support the colors array
1837    TextureVertex mesh[count];
1838    TextureVertex* vertex = mesh;
1839
1840    for (int32_t y = 0; y < meshHeight; y++) {
1841        for (int32_t x = 0; x < meshWidth; x++) {
1842            uint32_t i = (y * (meshWidth + 1) + x) * 2;
1843
1844            float u1 = float(x) / meshWidth;
1845            float u2 = float(x + 1) / meshWidth;
1846            float v1 = float(y) / meshHeight;
1847            float v2 = float(y + 1) / meshHeight;
1848
1849            int ax = i + (meshWidth + 1) * 2;
1850            int ay = ax + 1;
1851            int bx = i;
1852            int by = bx + 1;
1853            int cx = i + 2;
1854            int cy = cx + 1;
1855            int dx = i + (meshWidth + 1) * 2 + 2;
1856            int dy = dx + 1;
1857
1858            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1859            TextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1);
1860            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1861
1862            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1863            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1864            TextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2);
1865
1866            left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
1867            top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
1868            right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
1869            bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
1870        }
1871    }
1872
1873    if (quickReject(left, top, right, bottom)) {
1874        return DrawGlInfo::kStatusDone;
1875    }
1876
1877    mCaches.activeTexture(0);
1878    Texture* texture = mCaches.textureCache.get(bitmap);
1879    if (!texture) return DrawGlInfo::kStatusDone;
1880    const AutoTexture autoCleanup(texture);
1881
1882    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1883    texture->setFilter(FILTER(paint), true);
1884
1885    int alpha;
1886    SkXfermode::Mode mode;
1887    getAlphaAndMode(paint, &alpha, &mode);
1888
1889    if (hasLayer()) {
1890        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1891    }
1892
1893    drawTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, alpha / 255.0f,
1894            mode, texture->blend, &mesh[0].position[0], &mesh[0].texture[0],
1895            GL_TRIANGLES, count, false, false, 0, false, false);
1896
1897    return DrawGlInfo::kStatusDrew;
1898}
1899
1900status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
1901         float srcLeft, float srcTop, float srcRight, float srcBottom,
1902         float dstLeft, float dstTop, float dstRight, float dstBottom,
1903         SkPaint* paint) {
1904    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
1905        return DrawGlInfo::kStatusDone;
1906    }
1907
1908    mCaches.activeTexture(0);
1909    Texture* texture = mCaches.textureCache.get(bitmap);
1910    if (!texture) return DrawGlInfo::kStatusDone;
1911    const AutoTexture autoCleanup(texture);
1912
1913    const float width = texture->width;
1914    const float height = texture->height;
1915
1916    const float u1 = fmax(0.0f, srcLeft / width);
1917    const float v1 = fmax(0.0f, srcTop / height);
1918    const float u2 = fmin(1.0f, srcRight / width);
1919    const float v2 = fmin(1.0f, srcBottom / height);
1920
1921    mCaches.unbindMeshBuffer();
1922    resetDrawTextureTexCoords(u1, v1, u2, v2);
1923
1924    int alpha;
1925    SkXfermode::Mode mode;
1926    getAlphaAndMode(paint, &alpha, &mode);
1927
1928    texture->setWrap(GL_CLAMP_TO_EDGE, true);
1929
1930    float scaleX = (dstRight - dstLeft) / (srcRight - srcLeft);
1931    float scaleY = (dstBottom - dstTop) / (srcBottom - srcTop);
1932
1933    bool scaled = scaleX != 1.0f || scaleY != 1.0f;
1934    // Apply a scale transform on the canvas only when a shader is in use
1935    // Skia handles the ratio between the dst and src rects as a scale factor
1936    // when a shader is set
1937    bool useScaleTransform = mShader && scaled;
1938    bool ignoreTransform = false;
1939
1940    if (CC_LIKELY(mSnapshot->transform->isPureTranslate() && !useScaleTransform)) {
1941        float x = (int) floorf(dstLeft + mSnapshot->transform->getTranslateX() + 0.5f);
1942        float y = (int) floorf(dstTop + mSnapshot->transform->getTranslateY() + 0.5f);
1943
1944        dstRight = x + (dstRight - dstLeft);
1945        dstBottom = y + (dstBottom - dstTop);
1946
1947        dstLeft = x;
1948        dstTop = y;
1949
1950        texture->setFilter(scaled ? FILTER(paint) : GL_NEAREST, true);
1951        ignoreTransform = true;
1952    } else {
1953        texture->setFilter(FILTER(paint), true);
1954    }
1955
1956    if (CC_UNLIKELY(useScaleTransform)) {
1957        save(SkCanvas::kMatrix_SaveFlag);
1958        translate(dstLeft, dstTop);
1959        scale(scaleX, scaleY);
1960
1961        dstLeft = 0.0f;
1962        dstTop = 0.0f;
1963
1964        dstRight = srcRight - srcLeft;
1965        dstBottom = srcBottom - srcTop;
1966    }
1967
1968    if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
1969        int color = paint ? paint->getColor() : 0;
1970        drawAlpha8TextureMesh(dstLeft, dstTop, dstRight, dstBottom,
1971                texture->id, paint != NULL, color, alpha, mode,
1972                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1973                GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform);
1974    } else {
1975        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom,
1976                texture->id, alpha / 255.0f, mode, texture->blend,
1977                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1978                GL_TRIANGLE_STRIP, gMeshCount, false, ignoreTransform);
1979    }
1980
1981    if (CC_UNLIKELY(useScaleTransform)) {
1982        restore();
1983    }
1984
1985    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1986
1987    return DrawGlInfo::kStatusDrew;
1988}
1989
1990status_t OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
1991        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
1992        float left, float top, float right, float bottom, SkPaint* paint) {
1993    int alpha;
1994    SkXfermode::Mode mode;
1995    getAlphaAndModeDirect(paint, &alpha, &mode);
1996
1997    return drawPatch(bitmap, xDivs, yDivs, colors, width, height, numColors,
1998            left, top, right, bottom, alpha, mode);
1999}
2000
2001status_t OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
2002        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
2003        float left, float top, float right, float bottom, int alpha, SkXfermode::Mode mode) {
2004    if (quickReject(left, top, right, bottom)) {
2005        return DrawGlInfo::kStatusDone;
2006    }
2007
2008    alpha *= mSnapshot->alpha;
2009
2010    mCaches.activeTexture(0);
2011    Texture* texture = mCaches.textureCache.get(bitmap);
2012    if (!texture) return DrawGlInfo::kStatusDone;
2013    const AutoTexture autoCleanup(texture);
2014    texture->setWrap(GL_CLAMP_TO_EDGE, true);
2015    texture->setFilter(GL_LINEAR, true);
2016
2017    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
2018            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
2019
2020    if (CC_LIKELY(mesh && mesh->verticesCount > 0)) {
2021        const bool pureTranslate = mSnapshot->transform->isPureTranslate();
2022        // Mark the current layer dirty where we are going to draw the patch
2023        if (hasLayer() && mesh->hasEmptyQuads) {
2024            const float offsetX = left + mSnapshot->transform->getTranslateX();
2025            const float offsetY = top + mSnapshot->transform->getTranslateY();
2026            const size_t count = mesh->quads.size();
2027            for (size_t i = 0; i < count; i++) {
2028                const Rect& bounds = mesh->quads.itemAt(i);
2029                if (CC_LIKELY(pureTranslate)) {
2030                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
2031                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
2032                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
2033                } else {
2034                    dirtyLayer(left + bounds.left, top + bounds.top,
2035                            left + bounds.right, top + bounds.bottom, *mSnapshot->transform);
2036                }
2037            }
2038        }
2039
2040        if (CC_LIKELY(pureTranslate)) {
2041            const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
2042            const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
2043
2044            drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f,
2045                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
2046                    GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer,
2047                    true, !mesh->hasEmptyQuads);
2048        } else {
2049            drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f,
2050                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
2051                    GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer,
2052                    true, !mesh->hasEmptyQuads);
2053        }
2054    }
2055
2056    return DrawGlInfo::kStatusDrew;
2057}
2058
2059status_t OpenGLRenderer::drawVertexBuffer(const VertexBuffer& vertexBuffer, SkPaint* paint,
2060        bool useOffset) {
2061    if (!vertexBuffer.getSize()) {
2062        // no vertices to draw
2063        return DrawGlInfo::kStatusDone;
2064    }
2065
2066    int color = paint->getColor();
2067    SkXfermode::Mode mode = getXfermode(paint->getXfermode());
2068    bool isAA = paint->isAntiAlias();
2069
2070    setupDraw();
2071    setupDrawNoTexture();
2072    if (isAA) setupDrawAA();
2073    setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
2074    setupDrawColorFilter();
2075    setupDrawShader();
2076    setupDrawBlending(isAA, mode);
2077    setupDrawProgram();
2078    setupDrawModelViewIdentity(useOffset);
2079    setupDrawColorUniforms();
2080    setupDrawColorFilterUniforms();
2081    setupDrawShaderIdentityUniforms();
2082
2083    void* vertices = vertexBuffer.getBuffer();
2084    bool force = mCaches.unbindMeshBuffer();
2085    mCaches.bindPositionVertexPointer(true, vertices, isAA ? gAlphaVertexStride : gVertexStride);
2086    mCaches.resetTexCoordsVertexPointer();
2087    mCaches.unbindIndicesBuffer();
2088
2089    int alphaSlot = -1;
2090    if (isAA) {
2091        void* alphaCoords = ((GLbyte*) vertices) + gVertexAlphaOffset;
2092        alphaSlot = mCaches.currentProgram->getAttrib("vtxAlpha");
2093
2094        // TODO: avoid enable/disable in back to back uses of the alpha attribute
2095        glEnableVertexAttribArray(alphaSlot);
2096        glVertexAttribPointer(alphaSlot, 1, GL_FLOAT, GL_FALSE, gAlphaVertexStride, alphaCoords);
2097    }
2098
2099    glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexBuffer.getSize());
2100
2101    if (isAA) {
2102        glDisableVertexAttribArray(alphaSlot);
2103    }
2104
2105    return DrawGlInfo::kStatusDrew;
2106}
2107
2108/**
2109 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to
2110 * that of AA lines in the drawLines() function.  We expand the convex path by a half pixel in
2111 * screen space in all directions. However, instead of using a fragment shader to compute the
2112 * translucency of the color from its position, we simply use a varying parameter to define how far
2113 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used.
2114 *
2115 * Doesn't yet support joins, caps, or path effects.
2116 */
2117status_t OpenGLRenderer::drawConvexPath(const SkPath& path, SkPaint* paint) {
2118    VertexBuffer vertexBuffer;
2119    // TODO: try clipping large paths to viewport
2120    PathTessellator::tessellatePath(path, paint, mSnapshot->transform, vertexBuffer);
2121
2122    SkRect bounds = path.getBounds();
2123    PathTessellator::expandBoundsForStroke(bounds, paint, false);
2124    dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, *mSnapshot->transform);
2125
2126    return drawVertexBuffer(vertexBuffer, paint);
2127}
2128
2129/**
2130 * We create tristrips for the lines much like shape stroke tessellation, using a per-vertex alpha
2131 * and additional geometry for defining an alpha slope perimeter.
2132 *
2133 * Using GL_LINES can be difficult because the rasterization rules for those lines produces some
2134 * unexpected results, and may vary between hardware devices. Previously we used a varying-base
2135 * in-shader alpha region, but found it to be taxing on some GPUs.
2136 *
2137 * TODO: try using a fixed input buffer for non-capped lines as in text rendering. this may reduce
2138 * memory transfer by removing need for degenerate vertices.
2139 */
2140status_t OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
2141    if (mSnapshot->isIgnored() || count < 4) return DrawGlInfo::kStatusDone;
2142
2143    count &= ~0x3; // round down to nearest four
2144
2145    VertexBuffer buffer;
2146    SkRect bounds;
2147    PathTessellator::tessellateLines(points, count, paint, mSnapshot->transform, bounds, buffer);
2148
2149    if (quickReject(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom)) {
2150        return DrawGlInfo::kStatusDone;
2151    }
2152
2153    dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, *mSnapshot->transform);
2154
2155    bool useOffset = !paint->isAntiAlias();
2156    return drawVertexBuffer(buffer, paint, useOffset);
2157}
2158
2159status_t OpenGLRenderer::drawPoints(float* points, int count, SkPaint* paint) {
2160    if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
2161
2162    // TODO: The paint's cap style defines whether the points are square or circular
2163    // TODO: Handle AA for round points
2164
2165    // A stroke width of 0 has a special meaning in Skia:
2166    // it draws an unscaled 1px point
2167    float strokeWidth = paint->getStrokeWidth();
2168    const bool isHairLine = paint->getStrokeWidth() == 0.0f;
2169    if (isHairLine) {
2170        // Now that we know it's hairline, we can set the effective width, to be used later
2171        strokeWidth = 1.0f;
2172    }
2173    const float halfWidth = strokeWidth / 2;
2174
2175    int alpha;
2176    SkXfermode::Mode mode;
2177    getAlphaAndMode(paint, &alpha, &mode);
2178
2179    int verticesCount = count >> 1;
2180    int generatedVerticesCount = 0;
2181
2182    TextureVertex pointsData[verticesCount];
2183    TextureVertex* vertex = &pointsData[0];
2184
2185    // TODO: We should optimize this method to not generate vertices for points
2186    // that lie outside of the clip.
2187    mCaches.enableScissor();
2188
2189    setupDraw();
2190    setupDrawNoTexture();
2191    setupDrawPoint(strokeWidth);
2192    setupDrawColor(paint->getColor(), alpha);
2193    setupDrawColorFilter();
2194    setupDrawShader();
2195    setupDrawBlending(mode);
2196    setupDrawProgram();
2197    setupDrawModelViewIdentity(true);
2198    setupDrawColorUniforms();
2199    setupDrawColorFilterUniforms();
2200    setupDrawPointUniforms();
2201    setupDrawShaderIdentityUniforms();
2202    setupDrawMesh(vertex);
2203
2204    for (int i = 0; i < count; i += 2) {
2205        TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f);
2206        generatedVerticesCount++;
2207
2208        float left = points[i] - halfWidth;
2209        float right = points[i] + halfWidth;
2210        float top = points[i + 1] - halfWidth;
2211        float bottom = points [i + 1] + halfWidth;
2212
2213        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
2214    }
2215
2216    glDrawArrays(GL_POINTS, 0, generatedVerticesCount);
2217
2218    return DrawGlInfo::kStatusDrew;
2219}
2220
2221status_t OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
2222    // No need to check against the clip, we fill the clip region
2223    if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
2224
2225    Rect& clip(*mSnapshot->clipRect);
2226    clip.snapToPixelBoundaries();
2227
2228    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
2229
2230    return DrawGlInfo::kStatusDrew;
2231}
2232
2233status_t OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture,
2234        SkPaint* paint) {
2235    if (!texture) return DrawGlInfo::kStatusDone;
2236    const AutoTexture autoCleanup(texture);
2237
2238    const float x = left + texture->left - texture->offset;
2239    const float y = top + texture->top - texture->offset;
2240
2241    drawPathTexture(texture, x, y, paint);
2242
2243    return DrawGlInfo::kStatusDrew;
2244}
2245
2246status_t OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
2247        float rx, float ry, SkPaint* p) {
2248    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) {
2249        return DrawGlInfo::kStatusDone;
2250    }
2251
2252    if (p->getPathEffect() != 0) {
2253        mCaches.activeTexture(0);
2254        const PathTexture* texture = mCaches.roundRectShapeCache.getRoundRect(
2255                right - left, bottom - top, rx, ry, p);
2256        return drawShape(left, top, texture, p);
2257    }
2258
2259    SkPath path;
2260    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2261    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2262        float outset = p->getStrokeWidth() / 2;
2263        rect.outset(outset, outset);
2264        rx += outset;
2265        ry += outset;
2266    }
2267    path.addRoundRect(rect, rx, ry);
2268    return drawConvexPath(path, p);
2269}
2270
2271status_t OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* p) {
2272    if (mSnapshot->isIgnored() || quickRejectPreStroke(x - radius, y - radius,
2273            x + radius, y + radius, p)) {
2274        return DrawGlInfo::kStatusDone;
2275    }
2276    if (p->getPathEffect() != 0) {
2277        mCaches.activeTexture(0);
2278        const PathTexture* texture = mCaches.circleShapeCache.getCircle(radius, p);
2279        return drawShape(x - radius, y - radius, texture, p);
2280    }
2281
2282    SkPath path;
2283    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2284        path.addCircle(x, y, radius + p->getStrokeWidth() / 2);
2285    } else {
2286        path.addCircle(x, y, radius);
2287    }
2288    return drawConvexPath(path, p);
2289}
2290
2291status_t OpenGLRenderer::drawOval(float left, float top, float right, float bottom,
2292        SkPaint* p) {
2293    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) {
2294        return DrawGlInfo::kStatusDone;
2295    }
2296
2297    if (p->getPathEffect() != 0) {
2298        mCaches.activeTexture(0);
2299        const PathTexture* texture = mCaches.ovalShapeCache.getOval(right - left, bottom - top, p);
2300        return drawShape(left, top, texture, p);
2301    }
2302
2303    SkPath path;
2304    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2305    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2306        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2307    }
2308    path.addOval(rect);
2309    return drawConvexPath(path, p);
2310}
2311
2312status_t OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
2313        float startAngle, float sweepAngle, bool useCenter, SkPaint* p) {
2314    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) {
2315        return DrawGlInfo::kStatusDone;
2316    }
2317
2318    if (fabs(sweepAngle) >= 360.0f) {
2319        return drawOval(left, top, right, bottom, p);
2320    }
2321
2322    // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180)
2323    if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != 0 || useCenter) {
2324        mCaches.activeTexture(0);
2325        const PathTexture* texture = mCaches.arcShapeCache.getArc(right - left, bottom - top,
2326                startAngle, sweepAngle, useCenter, p);
2327        return drawShape(left, top, texture, p);
2328    }
2329
2330    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2331    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2332        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2333    }
2334
2335    SkPath path;
2336    if (useCenter) {
2337        path.moveTo(rect.centerX(), rect.centerY());
2338    }
2339    path.arcTo(rect, startAngle, sweepAngle, !useCenter);
2340    if (useCenter) {
2341        path.close();
2342    }
2343    return drawConvexPath(path, p);
2344}
2345
2346// See SkPaintDefaults.h
2347#define SkPaintDefaults_MiterLimit SkIntToScalar(4)
2348
2349status_t OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
2350    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) {
2351        return DrawGlInfo::kStatusDone;
2352    }
2353
2354    if (p->getStyle() != SkPaint::kFill_Style) {
2355        // only fill style is supported by drawConvexPath, since others have to handle joins
2356        if (p->getPathEffect() != 0 || p->getStrokeJoin() != SkPaint::kMiter_Join ||
2357                p->getStrokeMiter() != SkPaintDefaults_MiterLimit) {
2358            mCaches.activeTexture(0);
2359            const PathTexture* texture =
2360                    mCaches.rectShapeCache.getRect(right - left, bottom - top, p);
2361            return drawShape(left, top, texture, p);
2362        }
2363
2364        SkPath path;
2365        SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2366        if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2367            rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2368        }
2369        path.addRect(rect);
2370        return drawConvexPath(path, p);
2371    }
2372
2373    if (p->isAntiAlias() && !mSnapshot->transform->isSimple()) {
2374        SkPath path;
2375        path.addRect(left, top, right, bottom);
2376        return drawConvexPath(path, p);
2377    } else {
2378        drawColorRect(left, top, right, bottom, p->getColor(), getXfermode(p->getXfermode()));
2379        return DrawGlInfo::kStatusDrew;
2380    }
2381}
2382
2383void OpenGLRenderer::drawTextShadow(SkPaint* paint, const char* text, int bytesCount, int count,
2384        const float* positions, FontRenderer& fontRenderer, int alpha, SkXfermode::Mode mode,
2385        float x, float y) {
2386    mCaches.activeTexture(0);
2387
2388    // NOTE: The drop shadow will not perform gamma correction
2389    //       if shader-based correction is enabled
2390    mCaches.dropShadowCache.setFontRenderer(fontRenderer);
2391    const ShadowTexture* shadow = mCaches.dropShadowCache.get(
2392            paint, text, bytesCount, count, mShadowRadius, positions);
2393    const AutoTexture autoCleanup(shadow);
2394
2395    const float sx = x - shadow->left + mShadowDx;
2396    const float sy = y - shadow->top + mShadowDy;
2397
2398    const int shadowAlpha = ((mShadowColor >> 24) & 0xFF) * mSnapshot->alpha;
2399    int shadowColor = mShadowColor;
2400    if (mShader) {
2401        shadowColor = 0xffffffff;
2402    }
2403
2404    setupDraw();
2405    setupDrawWithTexture(true);
2406    setupDrawAlpha8Color(shadowColor, shadowAlpha < 255 ? shadowAlpha : alpha);
2407    setupDrawColorFilter();
2408    setupDrawShader();
2409    setupDrawBlending(true, mode);
2410    setupDrawProgram();
2411    setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height);
2412    setupDrawTexture(shadow->id);
2413    setupDrawPureColorUniforms();
2414    setupDrawColorFilterUniforms();
2415    setupDrawShaderUniforms();
2416    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2417
2418    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2419}
2420
2421status_t OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count,
2422        const float* positions, SkPaint* paint) {
2423    if (text == NULL || count == 0 || mSnapshot->isIgnored() ||
2424            (paint->getAlpha() * mSnapshot->alpha == 0 && paint->getXfermode() == NULL)) {
2425        return DrawGlInfo::kStatusDone;
2426    }
2427
2428    // NOTE: Skia does not support perspective transform on drawPosText yet
2429    if (!mSnapshot->transform->isSimple()) {
2430        return DrawGlInfo::kStatusDone;
2431    }
2432
2433    float x = 0.0f;
2434    float y = 0.0f;
2435    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
2436    if (pureTranslate) {
2437        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2438        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2439    }
2440
2441    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2442    fontRenderer.setFont(paint, *mSnapshot->transform);
2443
2444    int alpha;
2445    SkXfermode::Mode mode;
2446    getAlphaAndMode(paint, &alpha, &mode);
2447
2448    if (CC_UNLIKELY(mHasShadow)) {
2449        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2450                alpha, mode, 0.0f, 0.0f);
2451    }
2452
2453    // Pick the appropriate texture filtering
2454    bool linearFilter = mSnapshot->transform->changesBounds();
2455    if (pureTranslate && !linearFilter) {
2456        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2457    }
2458
2459    mCaches.activeTexture(0);
2460    setupDraw();
2461    setupDrawTextGamma(paint);
2462    setupDrawDirtyRegionsDisabled();
2463    setupDrawWithTexture(true);
2464    setupDrawAlpha8Color(paint->getColor(), alpha);
2465    setupDrawColorFilter();
2466    setupDrawShader();
2467    setupDrawBlending(true, mode);
2468    setupDrawProgram();
2469    setupDrawModelView(x, y, x, y, pureTranslate, true);
2470    setupDrawTexture(fontRenderer.getTexture(linearFilter));
2471    setupDrawPureColorUniforms();
2472    setupDrawColorFilterUniforms();
2473    setupDrawShaderUniforms(pureTranslate);
2474    setupDrawTextGammaUniforms();
2475
2476    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
2477    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2478
2479    const bool hasActiveLayer = hasLayer();
2480
2481    if (fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2482            positions, hasActiveLayer ? &bounds : NULL)) {
2483        if (hasActiveLayer) {
2484            if (!pureTranslate) {
2485                mSnapshot->transform->mapRect(bounds);
2486            }
2487            dirtyLayerUnchecked(bounds, getRegion());
2488        }
2489    }
2490
2491    return DrawGlInfo::kStatusDrew;
2492}
2493
2494status_t OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
2495        float x, float y, const float* positions, SkPaint* paint, float length) {
2496    if (text == NULL || count == 0 || mSnapshot->isIgnored() ||
2497            (paint->getAlpha() * mSnapshot->alpha == 0 && paint->getXfermode() == NULL)) {
2498        return DrawGlInfo::kStatusDone;
2499    }
2500
2501    if (length < 0.0f) length = paint->measureText(text, bytesCount);
2502    switch (paint->getTextAlign()) {
2503        case SkPaint::kCenter_Align:
2504            x -= length / 2.0f;
2505            break;
2506        case SkPaint::kRight_Align:
2507            x -= length;
2508            break;
2509        default:
2510            break;
2511    }
2512
2513    SkPaint::FontMetrics metrics;
2514    paint->getFontMetrics(&metrics, 0.0f);
2515    if (quickReject(x, y + metrics.fTop, x + length, y + metrics.fBottom)) {
2516        return DrawGlInfo::kStatusDone;
2517    }
2518
2519#if DEBUG_GLYPHS
2520    ALOGD("OpenGLRenderer drawText() with FontID=%d",
2521            SkTypeface::UniqueID(paint->getTypeface()));
2522#endif
2523
2524    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2525    fontRenderer.setFont(paint, *mSnapshot->transform);
2526
2527    const float oldX = x;
2528    const float oldY = y;
2529    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
2530    if (CC_LIKELY(pureTranslate)) {
2531        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2532        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2533    }
2534
2535    int alpha;
2536    SkXfermode::Mode mode;
2537    getAlphaAndMode(paint, &alpha, &mode);
2538
2539    if (CC_UNLIKELY(mHasShadow)) {
2540        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer, alpha, mode,
2541                oldX, oldY);
2542    }
2543
2544    // Pick the appropriate texture filtering
2545    bool linearFilter = mSnapshot->transform->changesBounds();
2546    if (pureTranslate && !linearFilter) {
2547        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2548    }
2549
2550    // The font renderer will always use texture unit 0
2551    mCaches.activeTexture(0);
2552    setupDraw();
2553    setupDrawTextGamma(paint);
2554    setupDrawDirtyRegionsDisabled();
2555    setupDrawWithTexture(true);
2556    setupDrawAlpha8Color(paint->getColor(), alpha);
2557    setupDrawColorFilter();
2558    setupDrawShader();
2559    setupDrawBlending(true, mode);
2560    setupDrawProgram();
2561    setupDrawModelView(x, y, x, y, pureTranslate, true);
2562    // See comment above; the font renderer must use texture unit 0
2563    // assert(mTextureUnit == 0)
2564    setupDrawTexture(fontRenderer.getTexture(linearFilter));
2565    setupDrawPureColorUniforms();
2566    setupDrawColorFilterUniforms();
2567    setupDrawShaderUniforms(pureTranslate);
2568    setupDrawTextGammaUniforms();
2569
2570    const Rect* clip = pureTranslate ? mSnapshot->clipRect :
2571            (mSnapshot->hasPerspectiveTransform() ? NULL : &mSnapshot->getLocalClip());
2572    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2573
2574    const bool hasActiveLayer = hasLayer();
2575
2576    bool status;
2577    if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) {
2578        SkPaint paintCopy(*paint);
2579        paintCopy.setTextAlign(SkPaint::kLeft_Align);
2580        status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y,
2581                positions, hasActiveLayer ? &bounds : NULL);
2582    } else {
2583        status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2584                positions, hasActiveLayer ? &bounds : NULL);
2585    }
2586
2587    if (status && hasActiveLayer) {
2588        if (!pureTranslate) {
2589            mSnapshot->transform->mapRect(bounds);
2590        }
2591        dirtyLayerUnchecked(bounds, getRegion());
2592    }
2593
2594    drawTextDecorations(text, bytesCount, length, oldX, oldY, paint);
2595
2596    return DrawGlInfo::kStatusDrew;
2597}
2598
2599status_t OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count, SkPath* path,
2600        float hOffset, float vOffset, SkPaint* paint) {
2601    if (text == NULL || count == 0 || mSnapshot->isIgnored() ||
2602            (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) {
2603        return DrawGlInfo::kStatusDone;
2604    }
2605
2606    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2607    fontRenderer.setFont(paint, *mSnapshot->transform);
2608
2609    int alpha;
2610    SkXfermode::Mode mode;
2611    getAlphaAndMode(paint, &alpha, &mode);
2612
2613    mCaches.activeTexture(0);
2614    setupDraw();
2615    setupDrawTextGamma(paint);
2616    setupDrawDirtyRegionsDisabled();
2617    setupDrawWithTexture(true);
2618    setupDrawAlpha8Color(paint->getColor(), alpha);
2619    setupDrawColorFilter();
2620    setupDrawShader();
2621    setupDrawBlending(true, mode);
2622    setupDrawProgram();
2623    setupDrawModelView(0.0f, 0.0f, 0.0f, 0.0f, false, true);
2624    setupDrawTexture(fontRenderer.getTexture(true));
2625    setupDrawPureColorUniforms();
2626    setupDrawColorFilterUniforms();
2627    setupDrawShaderUniforms(false);
2628    setupDrawTextGammaUniforms();
2629
2630    const Rect* clip = &mSnapshot->getLocalClip();
2631    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2632
2633    const bool hasActiveLayer = hasLayer();
2634
2635    if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path,
2636            hOffset, vOffset, hasActiveLayer ? &bounds : NULL)) {
2637        if (hasActiveLayer) {
2638            mSnapshot->transform->mapRect(bounds);
2639            dirtyLayerUnchecked(bounds, getRegion());
2640        }
2641    }
2642
2643    return DrawGlInfo::kStatusDrew;
2644}
2645
2646status_t OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
2647    if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
2648
2649    mCaches.activeTexture(0);
2650
2651    const PathTexture* texture = mCaches.pathCache.get(path, paint);
2652    if (!texture) return DrawGlInfo::kStatusDone;
2653    const AutoTexture autoCleanup(texture);
2654
2655    const float x = texture->left - texture->offset;
2656    const float y = texture->top - texture->offset;
2657
2658    drawPathTexture(texture, x, y, paint);
2659
2660    return DrawGlInfo::kStatusDrew;
2661}
2662
2663status_t OpenGLRenderer::drawLayer(Layer* layer, float x, float y, SkPaint* paint) {
2664    if (!layer) {
2665        return DrawGlInfo::kStatusDone;
2666    }
2667
2668    mat4* transform = NULL;
2669    if (layer->isTextureLayer()) {
2670        transform = &layer->getTransform();
2671        if (!transform->isIdentity()) {
2672            save(0);
2673            mSnapshot->transform->multiply(*transform);
2674        }
2675    }
2676
2677    Rect transformed;
2678    Rect clip;
2679    const bool rejected = quickRejectNoScissor(x, y,
2680            x + layer->layer.getWidth(), y + layer->layer.getHeight(), transformed, clip);
2681
2682    if (rejected) {
2683        if (transform && !transform->isIdentity()) {
2684            restore();
2685        }
2686        return DrawGlInfo::kStatusDone;
2687    }
2688
2689    updateLayer(layer, true);
2690
2691    mCaches.setScissorEnabled(mScissorOptimizationDisabled || !clip.contains(transformed));
2692    mCaches.activeTexture(0);
2693
2694    if (CC_LIKELY(!layer->region.isEmpty())) {
2695        SkiaColorFilter* oldFilter = mColorFilter;
2696        mColorFilter = layer->getColorFilter();
2697
2698        if (layer->region.isRect()) {
2699            composeLayerRect(layer, layer->regionRect);
2700        } else if (layer->mesh) {
2701            const float a = layer->getAlpha() / 255.0f;
2702            setupDraw();
2703            setupDrawWithTexture();
2704            setupDrawColor(a, a, a, a);
2705            setupDrawColorFilter();
2706            setupDrawBlending(layer->isBlend() || a < 1.0f, layer->getMode(), false);
2707            setupDrawProgram();
2708            setupDrawPureColorUniforms();
2709            setupDrawColorFilterUniforms();
2710            setupDrawTexture(layer->getTexture());
2711            if (CC_LIKELY(mSnapshot->transform->isPureTranslate())) {
2712                int tx = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2713                int ty = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2714
2715                layer->setFilter(GL_NEAREST);
2716                setupDrawModelViewTranslate(tx, ty,
2717                        tx + layer->layer.getWidth(), ty + layer->layer.getHeight(), true);
2718            } else {
2719                layer->setFilter(GL_LINEAR);
2720                setupDrawModelViewTranslate(x, y,
2721                        x + layer->layer.getWidth(), y + layer->layer.getHeight());
2722            }
2723            setupDrawMesh(&layer->mesh[0].position[0], &layer->mesh[0].texture[0]);
2724
2725            glDrawElements(GL_TRIANGLES, layer->meshElementCount,
2726                    GL_UNSIGNED_SHORT, layer->meshIndices);
2727
2728            finishDrawTexture();
2729
2730#if DEBUG_LAYERS_AS_REGIONS
2731            drawRegionRects(layer->region);
2732#endif
2733        }
2734
2735        mColorFilter = oldFilter;
2736
2737        if (layer->debugDrawUpdate) {
2738            layer->debugDrawUpdate = false;
2739            drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(),
2740                    0x7f00ff00, SkXfermode::kSrcOver_Mode);
2741        }
2742    }
2743
2744    if (transform && !transform->isIdentity()) {
2745        restore();
2746    }
2747
2748    return DrawGlInfo::kStatusDrew;
2749}
2750
2751///////////////////////////////////////////////////////////////////////////////
2752// Shaders
2753///////////////////////////////////////////////////////////////////////////////
2754
2755void OpenGLRenderer::resetShader() {
2756    mShader = NULL;
2757}
2758
2759void OpenGLRenderer::setupShader(SkiaShader* shader) {
2760    mShader = shader;
2761    if (mShader) {
2762        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
2763    }
2764}
2765
2766///////////////////////////////////////////////////////////////////////////////
2767// Color filters
2768///////////////////////////////////////////////////////////////////////////////
2769
2770void OpenGLRenderer::resetColorFilter() {
2771    mColorFilter = NULL;
2772}
2773
2774void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
2775    mColorFilter = filter;
2776}
2777
2778///////////////////////////////////////////////////////////////////////////////
2779// Drop shadow
2780///////////////////////////////////////////////////////////////////////////////
2781
2782void OpenGLRenderer::resetShadow() {
2783    mHasShadow = false;
2784}
2785
2786void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
2787    mHasShadow = true;
2788    mShadowRadius = radius;
2789    mShadowDx = dx;
2790    mShadowDy = dy;
2791    mShadowColor = color;
2792}
2793
2794///////////////////////////////////////////////////////////////////////////////
2795// Draw filters
2796///////////////////////////////////////////////////////////////////////////////
2797
2798void OpenGLRenderer::resetPaintFilter() {
2799    mHasDrawFilter = false;
2800}
2801
2802void OpenGLRenderer::setupPaintFilter(int clearBits, int setBits) {
2803    mHasDrawFilter = true;
2804    mPaintFilterClearBits = clearBits & SkPaint::kAllFlags;
2805    mPaintFilterSetBits = setBits & SkPaint::kAllFlags;
2806}
2807
2808SkPaint* OpenGLRenderer::filterPaint(SkPaint* paint) {
2809    if (CC_LIKELY(!mHasDrawFilter || !paint)) return paint;
2810
2811    uint32_t flags = paint->getFlags();
2812
2813    mFilteredPaint = *paint;
2814    mFilteredPaint.setFlags((flags & ~mPaintFilterClearBits) | mPaintFilterSetBits);
2815
2816    return &mFilteredPaint;
2817}
2818
2819///////////////////////////////////////////////////////////////////////////////
2820// Drawing implementation
2821///////////////////////////////////////////////////////////////////////////////
2822
2823void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
2824        float x, float y, SkPaint* paint) {
2825    if (quickReject(x, y, x + texture->width, y + texture->height)) {
2826        return;
2827    }
2828
2829    int alpha;
2830    SkXfermode::Mode mode;
2831    getAlphaAndMode(paint, &alpha, &mode);
2832
2833    setupDraw();
2834    setupDrawWithTexture(true);
2835    setupDrawAlpha8Color(paint->getColor(), alpha);
2836    setupDrawColorFilter();
2837    setupDrawShader();
2838    setupDrawBlending(true, mode);
2839    setupDrawProgram();
2840    setupDrawModelView(x, y, x + texture->width, y + texture->height);
2841    setupDrawTexture(texture->id);
2842    setupDrawPureColorUniforms();
2843    setupDrawColorFilterUniforms();
2844    setupDrawShaderUniforms();
2845    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2846
2847    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2848
2849    finishDrawTexture();
2850}
2851
2852// Same values used by Skia
2853#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
2854#define kStdUnderline_Offset    (1.0f / 9.0f)
2855#define kStdUnderline_Thickness (1.0f / 18.0f)
2856
2857void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
2858        float x, float y, SkPaint* paint) {
2859    // Handle underline and strike-through
2860    uint32_t flags = paint->getFlags();
2861    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
2862        SkPaint paintCopy(*paint);
2863        float underlineWidth = length;
2864        // If length is > 0.0f, we already measured the text for the text alignment
2865        if (length <= 0.0f) {
2866            underlineWidth = paintCopy.measureText(text, bytesCount);
2867        }
2868
2869        if (CC_LIKELY(underlineWidth > 0.0f)) {
2870            const float textSize = paintCopy.getTextSize();
2871            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
2872
2873            const float left = x;
2874            float top = 0.0f;
2875
2876            int linesCount = 0;
2877            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
2878            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
2879
2880            const int pointsCount = 4 * linesCount;
2881            float points[pointsCount];
2882            int currentPoint = 0;
2883
2884            if (flags & SkPaint::kUnderlineText_Flag) {
2885                top = y + textSize * kStdUnderline_Offset;
2886                points[currentPoint++] = left;
2887                points[currentPoint++] = top;
2888                points[currentPoint++] = left + underlineWidth;
2889                points[currentPoint++] = top;
2890            }
2891
2892            if (flags & SkPaint::kStrikeThruText_Flag) {
2893                top = y + textSize * kStdStrikeThru_Offset;
2894                points[currentPoint++] = left;
2895                points[currentPoint++] = top;
2896                points[currentPoint++] = left + underlineWidth;
2897                points[currentPoint++] = top;
2898            }
2899
2900            paintCopy.setStrokeWidth(strokeWidth);
2901
2902            drawLines(&points[0], pointsCount, &paintCopy);
2903        }
2904    }
2905}
2906
2907status_t OpenGLRenderer::drawRects(const float* rects, int count, SkPaint* paint) {
2908    if (mSnapshot->isIgnored()) {
2909        return DrawGlInfo::kStatusDone;
2910    }
2911
2912    int color = paint->getColor();
2913    // If a shader is set, preserve only the alpha
2914    if (mShader) {
2915        color |= 0x00ffffff;
2916    }
2917    SkXfermode::Mode mode = getXfermode(paint->getXfermode());
2918
2919    return drawColorRects(rects, count, color, mode);
2920}
2921
2922status_t OpenGLRenderer::drawColorRects(const float* rects, int count, int color,
2923        SkXfermode::Mode mode, bool ignoreTransform, bool dirty, bool clip) {
2924
2925    float left = FLT_MAX;
2926    float top = FLT_MAX;
2927    float right = FLT_MIN;
2928    float bottom = FLT_MIN;
2929
2930    int vertexCount = 0;
2931    Vertex mesh[count * 6];
2932    Vertex* vertex = mesh;
2933
2934    for (int index = 0; index < count; index += 4) {
2935        float l = rects[index + 0];
2936        float t = rects[index + 1];
2937        float r = rects[index + 2];
2938        float b = rects[index + 3];
2939
2940        if (ignoreTransform || !quickRejectNoScissor(left, top, right, bottom)) {
2941            Vertex::set(vertex++, l, b);
2942            Vertex::set(vertex++, l, t);
2943            Vertex::set(vertex++, r, t);
2944            Vertex::set(vertex++, l, b);
2945            Vertex::set(vertex++, r, t);
2946            Vertex::set(vertex++, r, b);
2947
2948            vertexCount += 6;
2949
2950            left = fminf(left, l);
2951            top = fminf(top, t);
2952            right = fmaxf(right, r);
2953            bottom = fmaxf(bottom, b);
2954        }
2955    }
2956
2957    if (count == 0 || (clip && quickReject(left, top, right, bottom))) {
2958        return DrawGlInfo::kStatusDone;
2959    }
2960
2961    setupDraw();
2962    setupDrawNoTexture();
2963    setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
2964    setupDrawShader();
2965    setupDrawColorFilter();
2966    setupDrawBlending(mode);
2967    setupDrawProgram();
2968    setupDrawDirtyRegionsDisabled();
2969    setupDrawModelView(0.0f, 0.0f, 1.0f, 1.0f, ignoreTransform, true);
2970    setupDrawColorUniforms();
2971    setupDrawShaderUniforms();
2972    setupDrawColorFilterUniforms();
2973    setupDrawVertices((GLvoid*) &mesh[0].position[0]);
2974
2975    if (dirty && hasLayer()) {
2976        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
2977    }
2978
2979    glDrawArrays(GL_TRIANGLES, 0, vertexCount);
2980
2981    return DrawGlInfo::kStatusDrew;
2982}
2983
2984void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
2985        int color, SkXfermode::Mode mode, bool ignoreTransform) {
2986    // If a shader is set, preserve only the alpha
2987    if (mShader) {
2988        color |= 0x00ffffff;
2989    }
2990
2991    setupDraw();
2992    setupDrawNoTexture();
2993    setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
2994    setupDrawShader();
2995    setupDrawColorFilter();
2996    setupDrawBlending(mode);
2997    setupDrawProgram();
2998    setupDrawModelView(left, top, right, bottom, ignoreTransform);
2999    setupDrawColorUniforms();
3000    setupDrawShaderUniforms(ignoreTransform);
3001    setupDrawColorFilterUniforms();
3002    setupDrawSimpleMesh();
3003
3004    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
3005}
3006
3007void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
3008        Texture* texture, SkPaint* paint) {
3009    int alpha;
3010    SkXfermode::Mode mode;
3011    getAlphaAndMode(paint, &alpha, &mode);
3012
3013    texture->setWrap(GL_CLAMP_TO_EDGE, true);
3014
3015    if (CC_LIKELY(mSnapshot->transform->isPureTranslate())) {
3016        const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
3017        const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
3018
3019        texture->setFilter(GL_NEAREST, true);
3020        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
3021                alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL,
3022                (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true);
3023    } else {
3024        texture->setFilter(FILTER(paint), true);
3025        drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
3026                texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
3027                GL_TRIANGLE_STRIP, gMeshCount);
3028    }
3029}
3030
3031void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
3032        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
3033    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
3034            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
3035}
3036
3037void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
3038        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
3039        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3040        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
3041
3042    setupDraw();
3043    setupDrawWithTexture();
3044    setupDrawColor(alpha, alpha, alpha, alpha);
3045    setupDrawColorFilter();
3046    setupDrawBlending(blend, mode, swapSrcDst);
3047    setupDrawProgram();
3048    if (!dirty) setupDrawDirtyRegionsDisabled();
3049    if (!ignoreScale) {
3050        setupDrawModelView(left, top, right, bottom, ignoreTransform);
3051    } else {
3052        setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
3053    }
3054    setupDrawTexture(texture);
3055    setupDrawPureColorUniforms();
3056    setupDrawColorFilterUniforms();
3057    setupDrawMesh(vertices, texCoords, vbo);
3058
3059    glDrawArrays(drawMode, 0, elementsCount);
3060
3061    finishDrawTexture();
3062}
3063
3064void OpenGLRenderer::drawAlpha8TextureMesh(float left, float top, float right, float bottom,
3065        GLuint texture, bool hasColor, int color, int alpha, SkXfermode::Mode mode,
3066        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3067        bool ignoreTransform, bool dirty) {
3068
3069    setupDraw();
3070    setupDrawWithTexture(true);
3071    if (hasColor) {
3072        setupDrawAlpha8Color(color, alpha);
3073    }
3074    setupDrawColorFilter();
3075    setupDrawShader();
3076    setupDrawBlending(true, mode);
3077    setupDrawProgram();
3078    if (!dirty) setupDrawDirtyRegionsDisabled();
3079    setupDrawModelView(left, top, right, bottom, ignoreTransform);
3080    setupDrawTexture(texture);
3081    setupDrawPureColorUniforms();
3082    setupDrawColorFilterUniforms();
3083    setupDrawShaderUniforms();
3084    setupDrawMesh(vertices, texCoords);
3085
3086    glDrawArrays(drawMode, 0, elementsCount);
3087
3088    finishDrawTexture();
3089}
3090
3091void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
3092        ProgramDescription& description, bool swapSrcDst) {
3093    blend = blend || mode != SkXfermode::kSrcOver_Mode;
3094
3095    if (blend) {
3096        // These blend modes are not supported by OpenGL directly and have
3097        // to be implemented using shaders. Since the shader will perform
3098        // the blending, turn blending off here
3099        // If the blend mode cannot be implemented using shaders, fall
3100        // back to the default SrcOver blend mode instead
3101        if (CC_UNLIKELY(mode > SkXfermode::kScreen_Mode)) {
3102            if (CC_UNLIKELY(mExtensions.hasFramebufferFetch())) {
3103                description.framebufferMode = mode;
3104                description.swapSrcDst = swapSrcDst;
3105
3106                if (mCaches.blend) {
3107                    glDisable(GL_BLEND);
3108                    mCaches.blend = false;
3109                }
3110
3111                return;
3112            } else {
3113                mode = SkXfermode::kSrcOver_Mode;
3114            }
3115        }
3116
3117        if (!mCaches.blend) {
3118            glEnable(GL_BLEND);
3119        }
3120
3121        GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
3122        GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
3123
3124        if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
3125            glBlendFunc(sourceMode, destMode);
3126            mCaches.lastSrcMode = sourceMode;
3127            mCaches.lastDstMode = destMode;
3128        }
3129    } else if (mCaches.blend) {
3130        glDisable(GL_BLEND);
3131    }
3132    mCaches.blend = blend;
3133}
3134
3135bool OpenGLRenderer::useProgram(Program* program) {
3136    if (!program->isInUse()) {
3137        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
3138        program->use();
3139        mCaches.currentProgram = program;
3140        return false;
3141    }
3142    return true;
3143}
3144
3145void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
3146    TextureVertex* v = &mMeshVertices[0];
3147    TextureVertex::setUV(v++, u1, v1);
3148    TextureVertex::setUV(v++, u2, v1);
3149    TextureVertex::setUV(v++, u1, v2);
3150    TextureVertex::setUV(v++, u2, v2);
3151}
3152
3153void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
3154    getAlphaAndModeDirect(paint, alpha,  mode);
3155    *alpha *= mSnapshot->alpha;
3156}
3157
3158}; // namespace uirenderer
3159}; // namespace android
3160