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