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