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