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