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