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