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