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