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