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