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