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