OpenGLRenderer.cpp revision 7564c716bbee6a4825ae747797068d0e7c370c0d
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    mDirtyClip = true;
197
198    updateLayers();
199
200    discardFramebuffer(left, top, right, bottom);
201
202    syncState();
203
204    // Functors break the tiling extension in pretty spectacular ways
205    // This ensures we don't use tiling when a functor is going to be
206    // invoked during the frame
207    mSuppressTiling = mCaches.hasRegisteredFunctors();
208
209    mTilingSnapshot = mSnapshot;
210    startTiling(mTilingSnapshot, 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 = mTilingSnapshot->clipRect;
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 = mTilingSnapshot->clipRect;
484
485        mCaches.enableScissor();
486        mCaches.setScissor(clip->left, mTilingSnapshot->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    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        return DrawGlInfo::kStatusDone;
2416    }
2417
2418    if (p->getPathEffect() != 0) {
2419        mCaches.activeTexture(0);
2420        const PathTexture* texture = mCaches.pathCache.getRoundRect(
2421                right - left, bottom - top, rx, ry, p);
2422        return drawShape(left, top, texture, p);
2423    }
2424
2425    SkPath path;
2426    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2427    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2428        float outset = p->getStrokeWidth() / 2;
2429        rect.outset(outset, outset);
2430        rx += outset;
2431        ry += outset;
2432    }
2433    path.addRoundRect(rect, rx, ry);
2434    return drawConvexPath(path, p);
2435}
2436
2437status_t OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* p) {
2438    if (mSnapshot->isIgnored() || quickRejectPreStroke(x - radius, y - radius,
2439            x + radius, y + radius, p)) {
2440        return DrawGlInfo::kStatusDone;
2441    }
2442    if (p->getPathEffect() != 0) {
2443        mCaches.activeTexture(0);
2444        const PathTexture* texture = mCaches.pathCache.getCircle(radius, p);
2445        return drawShape(x - radius, y - radius, texture, p);
2446    }
2447
2448    SkPath path;
2449    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2450        path.addCircle(x, y, radius + p->getStrokeWidth() / 2);
2451    } else {
2452        path.addCircle(x, y, radius);
2453    }
2454    return drawConvexPath(path, p);
2455}
2456
2457status_t OpenGLRenderer::drawOval(float left, float top, float right, float bottom,
2458        SkPaint* p) {
2459    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) {
2460        return DrawGlInfo::kStatusDone;
2461    }
2462
2463    if (p->getPathEffect() != 0) {
2464        mCaches.activeTexture(0);
2465        const PathTexture* texture = mCaches.pathCache.getOval(right - left, bottom - top, p);
2466        return drawShape(left, top, texture, p);
2467    }
2468
2469    SkPath path;
2470    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2471    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2472        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2473    }
2474    path.addOval(rect);
2475    return drawConvexPath(path, p);
2476}
2477
2478status_t OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
2479        float startAngle, float sweepAngle, bool useCenter, SkPaint* p) {
2480    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) {
2481        return DrawGlInfo::kStatusDone;
2482    }
2483
2484    if (fabs(sweepAngle) >= 360.0f) {
2485        return drawOval(left, top, right, bottom, p);
2486    }
2487
2488    // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180)
2489    if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != 0 || useCenter) {
2490        mCaches.activeTexture(0);
2491        const PathTexture* texture = mCaches.pathCache.getArc(right - left, bottom - top,
2492                startAngle, sweepAngle, useCenter, p);
2493        return drawShape(left, top, texture, p);
2494    }
2495
2496    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2497    if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2498        rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2499    }
2500
2501    SkPath path;
2502    if (useCenter) {
2503        path.moveTo(rect.centerX(), rect.centerY());
2504    }
2505    path.arcTo(rect, startAngle, sweepAngle, !useCenter);
2506    if (useCenter) {
2507        path.close();
2508    }
2509    return drawConvexPath(path, p);
2510}
2511
2512// See SkPaintDefaults.h
2513#define SkPaintDefaults_MiterLimit SkIntToScalar(4)
2514
2515status_t OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
2516    if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p)) {
2517        return DrawGlInfo::kStatusDone;
2518    }
2519
2520    if (p->getStyle() != SkPaint::kFill_Style) {
2521        // only fill style is supported by drawConvexPath, since others have to handle joins
2522        if (p->getPathEffect() != 0 || p->getStrokeJoin() != SkPaint::kMiter_Join ||
2523                p->getStrokeMiter() != SkPaintDefaults_MiterLimit) {
2524            mCaches.activeTexture(0);
2525            const PathTexture* texture =
2526                    mCaches.pathCache.getRect(right - left, bottom - top, p);
2527            return drawShape(left, top, texture, p);
2528        }
2529
2530        SkPath path;
2531        SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2532        if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2533            rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2534        }
2535        path.addRect(rect);
2536        return drawConvexPath(path, p);
2537    }
2538
2539    if (p->isAntiAlias() && !currentTransform().isSimple()) {
2540        SkPath path;
2541        path.addRect(left, top, right, bottom);
2542        return drawConvexPath(path, p);
2543    } else {
2544        drawColorRect(left, top, right, bottom, p->getColor(), getXfermode(p->getXfermode()));
2545        return DrawGlInfo::kStatusDrew;
2546    }
2547}
2548
2549void OpenGLRenderer::drawTextShadow(SkPaint* paint, const char* text, int bytesCount, int count,
2550        const float* positions, FontRenderer& fontRenderer, int alpha, SkXfermode::Mode mode,
2551        float x, float y) {
2552    mCaches.activeTexture(0);
2553
2554    // NOTE: The drop shadow will not perform gamma correction
2555    //       if shader-based correction is enabled
2556    mCaches.dropShadowCache.setFontRenderer(fontRenderer);
2557    const ShadowTexture* shadow = mCaches.dropShadowCache.get(
2558            paint, text, bytesCount, count, mDrawModifiers.mShadowRadius, positions);
2559    const AutoTexture autoCleanup(shadow);
2560
2561    const float sx = x - shadow->left + mDrawModifiers.mShadowDx;
2562    const float sy = y - shadow->top + mDrawModifiers.mShadowDy;
2563
2564    const int shadowAlpha = ((mDrawModifiers.mShadowColor >> 24) & 0xFF) * mSnapshot->alpha;
2565    int shadowColor = mDrawModifiers.mShadowColor;
2566    if (mDrawModifiers.mShader) {
2567        shadowColor = 0xffffffff;
2568    }
2569
2570    setupDraw();
2571    setupDrawWithTexture(true);
2572    setupDrawAlpha8Color(shadowColor, shadowAlpha < 255 ? shadowAlpha : alpha);
2573    setupDrawColorFilter();
2574    setupDrawShader();
2575    setupDrawBlending(true, mode);
2576    setupDrawProgram();
2577    setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height);
2578    setupDrawTexture(shadow->id);
2579    setupDrawPureColorUniforms();
2580    setupDrawColorFilterUniforms();
2581    setupDrawShaderUniforms();
2582    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2583
2584    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2585}
2586
2587bool OpenGLRenderer::canSkipText(const SkPaint* paint) const {
2588    float alpha = (mDrawModifiers.mHasShadow ? 1.0f : paint->getAlpha()) * mSnapshot->alpha;
2589    return alpha == 0.0f && getXfermode(paint->getXfermode()) == SkXfermode::kSrcOver_Mode;
2590}
2591
2592status_t OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count,
2593        const float* positions, SkPaint* paint) {
2594    if (text == NULL || count == 0 || mSnapshot->isIgnored() || canSkipText(paint)) {
2595        return DrawGlInfo::kStatusDone;
2596    }
2597
2598    // NOTE: Skia does not support perspective transform on drawPosText yet
2599    if (!currentTransform().isSimple()) {
2600        return DrawGlInfo::kStatusDone;
2601    }
2602
2603    float x = 0.0f;
2604    float y = 0.0f;
2605    const bool pureTranslate = currentTransform().isPureTranslate();
2606    if (pureTranslate) {
2607        x = (int) floorf(x + currentTransform().getTranslateX() + 0.5f);
2608        y = (int) floorf(y + currentTransform().getTranslateY() + 0.5f);
2609    }
2610
2611    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2612    fontRenderer.setFont(paint, mat4::identity());
2613
2614    int alpha;
2615    SkXfermode::Mode mode;
2616    getAlphaAndMode(paint, &alpha, &mode);
2617
2618    if (CC_UNLIKELY(mDrawModifiers.mHasShadow)) {
2619        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2620                alpha, mode, 0.0f, 0.0f);
2621    }
2622
2623    // Pick the appropriate texture filtering
2624    bool linearFilter = currentTransform().changesBounds();
2625    if (pureTranslate && !linearFilter) {
2626        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2627    }
2628
2629    mCaches.activeTexture(0);
2630    setupDraw();
2631    setupDrawTextGamma(paint);
2632    setupDrawDirtyRegionsDisabled();
2633    setupDrawWithTexture(true);
2634    setupDrawAlpha8Color(paint->getColor(), alpha);
2635    setupDrawColorFilter();
2636    setupDrawShader();
2637    setupDrawBlending(true, mode);
2638    setupDrawProgram();
2639    setupDrawModelView(x, y, x, y, pureTranslate, true);
2640    setupDrawTexture(fontRenderer.getTexture(linearFilter));
2641    setupDrawPureColorUniforms();
2642    setupDrawColorFilterUniforms();
2643    setupDrawShaderUniforms(pureTranslate);
2644    setupDrawTextGammaUniforms();
2645
2646    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
2647    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2648
2649    const bool hasActiveLayer = hasLayer();
2650
2651    if (fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2652            positions, hasActiveLayer ? &bounds : NULL)) {
2653        if (hasActiveLayer) {
2654            if (!pureTranslate) {
2655                currentTransform().mapRect(bounds);
2656            }
2657            dirtyLayerUnchecked(bounds, getRegion());
2658        }
2659    }
2660
2661    return DrawGlInfo::kStatusDrew;
2662}
2663
2664mat4 OpenGLRenderer::findBestFontTransform(const mat4& transform) const {
2665    mat4 fontTransform;
2666    if (CC_LIKELY(transform.isPureTranslate())) {
2667        fontTransform = mat4::identity();
2668    } else {
2669        if (CC_UNLIKELY(transform.isPerspective())) {
2670            fontTransform = mat4::identity();
2671        } else {
2672            float sx, sy;
2673            currentTransform().decomposeScale(sx, sy);
2674            fontTransform.loadScale(sx, sy, 1.0f);
2675        }
2676    }
2677    return fontTransform;
2678}
2679
2680status_t OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
2681        float x, float y, const float* positions, SkPaint* paint, float length) {
2682    if (text == NULL || count == 0 || mSnapshot->isIgnored() || canSkipText(paint)) {
2683        return DrawGlInfo::kStatusDone;
2684    }
2685
2686    if (length < 0.0f) length = paint->measureText(text, bytesCount);
2687    switch (paint->getTextAlign()) {
2688        case SkPaint::kCenter_Align:
2689            x -= length / 2.0f;
2690            break;
2691        case SkPaint::kRight_Align:
2692            x -= length;
2693            break;
2694        default:
2695            break;
2696    }
2697
2698    SkPaint::FontMetrics metrics;
2699    paint->getFontMetrics(&metrics, 0.0f);
2700    if (quickReject(x, y + metrics.fTop, x + length, y + metrics.fBottom)) {
2701        return DrawGlInfo::kStatusDone;
2702    }
2703
2704    const float oldX = x;
2705    const float oldY = y;
2706
2707    const mat4& transform = currentTransform();
2708    const bool pureTranslate = transform.isPureTranslate();
2709
2710    if (CC_LIKELY(pureTranslate)) {
2711        x = (int) floorf(x + transform.getTranslateX() + 0.5f);
2712        y = (int) floorf(y + transform.getTranslateY() + 0.5f);
2713    }
2714
2715    int alpha;
2716    SkXfermode::Mode mode;
2717    getAlphaAndMode(paint, &alpha, &mode);
2718
2719    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2720
2721    if (CC_UNLIKELY(mDrawModifiers.mHasShadow)) {
2722        fontRenderer.setFont(paint, mat4::identity());
2723        drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2724                alpha, mode, oldX, oldY);
2725    }
2726
2727    const bool hasActiveLayer = hasLayer();
2728
2729    // We only pass a partial transform to the font renderer. That partial
2730    // matrix defines how glyphs are rasterized. Typically we want glyphs
2731    // to be rasterized at their final size on screen, which means the partial
2732    // matrix needs to take the scale factor into account.
2733    // When a partial matrix is used to transform glyphs during rasterization,
2734    // the mesh is generated with the inverse transform (in the case of scale,
2735    // the mesh is generated at 1.0 / scale for instance.) This allows us to
2736    // apply the full transform matrix at draw time in the vertex shader.
2737    // Applying the full matrix in the shader is the easiest way to handle
2738    // rotation and perspective and allows us to always generated quads in the
2739    // font renderer which greatly simplifies the code, clipping in particular.
2740    mat4 fontTransform = findBestFontTransform(transform);
2741    fontRenderer.setFont(paint, fontTransform);
2742
2743    // Pick the appropriate texture filtering
2744    bool linearFilter = !pureTranslate || fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2745
2746    // The font renderer will always use texture unit 0
2747    mCaches.activeTexture(0);
2748    setupDraw();
2749    setupDrawTextGamma(paint);
2750    setupDrawDirtyRegionsDisabled();
2751    setupDrawWithTexture(true);
2752    setupDrawAlpha8Color(paint->getColor(), alpha);
2753    setupDrawColorFilter();
2754    setupDrawShader();
2755    setupDrawBlending(true, mode);
2756    setupDrawProgram();
2757    setupDrawModelView(x, y, x, y, pureTranslate, true);
2758    // See comment above; the font renderer must use texture unit 0
2759    // assert(mTextureUnit == 0)
2760    setupDrawTexture(fontRenderer.getTexture(linearFilter));
2761    setupDrawPureColorUniforms();
2762    setupDrawColorFilterUniforms();
2763    setupDrawShaderUniforms(pureTranslate);
2764    setupDrawTextGammaUniforms();
2765
2766    // TODO: Implement better clipping for scaled/rotated text
2767    const Rect* clip = !pureTranslate ? NULL : mSnapshot->clipRect;
2768    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2769
2770    bool status;
2771    if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) {
2772        SkPaint paintCopy(*paint);
2773        paintCopy.setTextAlign(SkPaint::kLeft_Align);
2774        status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y,
2775                positions, hasActiveLayer ? &bounds : NULL);
2776    } else {
2777        status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2778                positions, hasActiveLayer ? &bounds : NULL);
2779    }
2780
2781    if (status && hasActiveLayer) {
2782        if (!pureTranslate) {
2783            transform.mapRect(bounds);
2784        }
2785        dirtyLayerUnchecked(bounds, getRegion());
2786    }
2787
2788    drawTextDecorations(text, bytesCount, length, oldX, oldY, paint);
2789
2790    return DrawGlInfo::kStatusDrew;
2791}
2792
2793status_t OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count, SkPath* path,
2794        float hOffset, float vOffset, SkPaint* paint) {
2795    if (text == NULL || count == 0 || mSnapshot->isIgnored() || canSkipText(paint)) {
2796        return DrawGlInfo::kStatusDone;
2797    }
2798
2799    FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2800    fontRenderer.setFont(paint, mat4::identity());
2801
2802    int alpha;
2803    SkXfermode::Mode mode;
2804    getAlphaAndMode(paint, &alpha, &mode);
2805
2806    mCaches.activeTexture(0);
2807    setupDraw();
2808    setupDrawTextGamma(paint);
2809    setupDrawDirtyRegionsDisabled();
2810    setupDrawWithTexture(true);
2811    setupDrawAlpha8Color(paint->getColor(), alpha);
2812    setupDrawColorFilter();
2813    setupDrawShader();
2814    setupDrawBlending(true, mode);
2815    setupDrawProgram();
2816    setupDrawModelView(0.0f, 0.0f, 0.0f, 0.0f, false, true);
2817    setupDrawTexture(fontRenderer.getTexture(true));
2818    setupDrawPureColorUniforms();
2819    setupDrawColorFilterUniforms();
2820    setupDrawShaderUniforms(false);
2821    setupDrawTextGammaUniforms();
2822
2823    const Rect* clip = &mSnapshot->getLocalClip();
2824    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2825
2826    const bool hasActiveLayer = hasLayer();
2827
2828    if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path,
2829            hOffset, vOffset, hasActiveLayer ? &bounds : NULL)) {
2830        if (hasActiveLayer) {
2831            currentTransform().mapRect(bounds);
2832            dirtyLayerUnchecked(bounds, getRegion());
2833        }
2834    }
2835
2836    return DrawGlInfo::kStatusDrew;
2837}
2838
2839status_t OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
2840    if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
2841
2842    mCaches.activeTexture(0);
2843
2844    const PathTexture* texture = mCaches.pathCache.get(path, paint);
2845    if (!texture) return DrawGlInfo::kStatusDone;
2846    const AutoTexture autoCleanup(texture);
2847
2848    const float x = texture->left - texture->offset;
2849    const float y = texture->top - texture->offset;
2850
2851    drawPathTexture(texture, x, y, paint);
2852
2853    return DrawGlInfo::kStatusDrew;
2854}
2855
2856status_t OpenGLRenderer::drawLayer(Layer* layer, float x, float y) {
2857    if (!layer) {
2858        return DrawGlInfo::kStatusDone;
2859    }
2860
2861    mat4* transform = NULL;
2862    if (layer->isTextureLayer()) {
2863        transform = &layer->getTransform();
2864        if (!transform->isIdentity()) {
2865            save(0);
2866            currentTransform().multiply(*transform);
2867        }
2868    }
2869
2870    Rect transformed;
2871    Rect clip;
2872    const bool rejected = quickRejectNoScissor(x, y,
2873            x + layer->layer.getWidth(), y + layer->layer.getHeight(), transformed, clip);
2874
2875    if (rejected) {
2876        if (transform && !transform->isIdentity()) {
2877            restore();
2878        }
2879        return DrawGlInfo::kStatusDone;
2880    }
2881
2882    updateLayer(layer, true);
2883
2884    mCaches.setScissorEnabled(mScissorOptimizationDisabled || !clip.contains(transformed));
2885    mCaches.activeTexture(0);
2886
2887    if (CC_LIKELY(!layer->region.isEmpty())) {
2888        SkiaColorFilter* oldFilter = mDrawModifiers.mColorFilter;
2889        mDrawModifiers.mColorFilter = layer->getColorFilter();
2890
2891        if (layer->region.isRect()) {
2892            composeLayerRect(layer, layer->regionRect);
2893        } else if (layer->mesh) {
2894            const float a = layer->getAlpha() / 255.0f * mSnapshot->alpha;
2895            setupDraw();
2896            setupDrawWithTexture();
2897            setupDrawColor(a, a, a, a);
2898            setupDrawColorFilter();
2899            setupDrawBlending(layer->isBlend() || a < 1.0f, layer->getMode(), false);
2900            setupDrawProgram();
2901            setupDrawPureColorUniforms();
2902            setupDrawColorFilterUniforms();
2903            setupDrawTexture(layer->getTexture());
2904            if (CC_LIKELY(currentTransform().isPureTranslate())) {
2905                int tx = (int) floorf(x + currentTransform().getTranslateX() + 0.5f);
2906                int ty = (int) floorf(y + currentTransform().getTranslateY() + 0.5f);
2907
2908                layer->setFilter(GL_NEAREST);
2909                setupDrawModelViewTranslate(tx, ty,
2910                        tx + layer->layer.getWidth(), ty + layer->layer.getHeight(), true);
2911            } else {
2912                layer->setFilter(GL_LINEAR);
2913                setupDrawModelViewTranslate(x, y,
2914                        x + layer->layer.getWidth(), y + layer->layer.getHeight());
2915            }
2916            setupDrawMesh(&layer->mesh[0].position[0], &layer->mesh[0].texture[0]);
2917
2918            glDrawElements(GL_TRIANGLES, layer->meshElementCount,
2919                    GL_UNSIGNED_SHORT, layer->meshIndices);
2920
2921            finishDrawTexture();
2922
2923#if DEBUG_LAYERS_AS_REGIONS
2924            drawRegionRects(layer->region);
2925#endif
2926        }
2927
2928        mDrawModifiers.mColorFilter = oldFilter;
2929
2930        if (layer->debugDrawUpdate) {
2931            layer->debugDrawUpdate = false;
2932            drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(),
2933                    0x7f00ff00, SkXfermode::kSrcOver_Mode);
2934        }
2935    }
2936
2937    if (transform && !transform->isIdentity()) {
2938        restore();
2939    }
2940
2941    return DrawGlInfo::kStatusDrew;
2942}
2943
2944///////////////////////////////////////////////////////////////////////////////
2945// Shaders
2946///////////////////////////////////////////////////////////////////////////////
2947
2948void OpenGLRenderer::resetShader() {
2949    mDrawModifiers.mShader = NULL;
2950}
2951
2952void OpenGLRenderer::setupShader(SkiaShader* shader) {
2953    mDrawModifiers.mShader = shader;
2954    if (mDrawModifiers.mShader) {
2955        mDrawModifiers.mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
2956    }
2957}
2958
2959///////////////////////////////////////////////////////////////////////////////
2960// Color filters
2961///////////////////////////////////////////////////////////////////////////////
2962
2963void OpenGLRenderer::resetColorFilter() {
2964    mDrawModifiers.mColorFilter = NULL;
2965}
2966
2967void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
2968    mDrawModifiers.mColorFilter = filter;
2969}
2970
2971///////////////////////////////////////////////////////////////////////////////
2972// Drop shadow
2973///////////////////////////////////////////////////////////////////////////////
2974
2975void OpenGLRenderer::resetShadow() {
2976    mDrawModifiers.mHasShadow = false;
2977}
2978
2979void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
2980    mDrawModifiers.mHasShadow = true;
2981    mDrawModifiers.mShadowRadius = radius;
2982    mDrawModifiers.mShadowDx = dx;
2983    mDrawModifiers.mShadowDy = dy;
2984    mDrawModifiers.mShadowColor = color;
2985}
2986
2987///////////////////////////////////////////////////////////////////////////////
2988// Draw filters
2989///////////////////////////////////////////////////////////////////////////////
2990
2991void OpenGLRenderer::resetPaintFilter() {
2992    mDrawModifiers.mHasDrawFilter = false;
2993}
2994
2995void OpenGLRenderer::setupPaintFilter(int clearBits, int setBits) {
2996    mDrawModifiers.mHasDrawFilter = true;
2997    mDrawModifiers.mPaintFilterClearBits = clearBits & SkPaint::kAllFlags;
2998    mDrawModifiers.mPaintFilterSetBits = setBits & SkPaint::kAllFlags;
2999}
3000
3001SkPaint* OpenGLRenderer::filterPaint(SkPaint* paint) {
3002    if (CC_LIKELY(!mDrawModifiers.mHasDrawFilter || !paint)) {
3003        return paint;
3004    }
3005
3006    uint32_t flags = paint->getFlags();
3007
3008    mFilteredPaint = *paint;
3009    mFilteredPaint.setFlags((flags & ~mDrawModifiers.mPaintFilterClearBits) |
3010            mDrawModifiers.mPaintFilterSetBits);
3011
3012    return &mFilteredPaint;
3013}
3014
3015///////////////////////////////////////////////////////////////////////////////
3016// Drawing implementation
3017///////////////////////////////////////////////////////////////////////////////
3018
3019void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
3020        float x, float y, SkPaint* paint) {
3021    if (quickReject(x, y, x + texture->width, y + texture->height)) {
3022        return;
3023    }
3024
3025    int alpha;
3026    SkXfermode::Mode mode;
3027    getAlphaAndMode(paint, &alpha, &mode);
3028
3029    setupDraw();
3030    setupDrawWithTexture(true);
3031    setupDrawAlpha8Color(paint->getColor(), alpha);
3032    setupDrawColorFilter();
3033    setupDrawShader();
3034    setupDrawBlending(true, mode);
3035    setupDrawProgram();
3036    setupDrawModelView(x, y, x + texture->width, y + texture->height);
3037    setupDrawTexture(texture->id);
3038    setupDrawPureColorUniforms();
3039    setupDrawColorFilterUniforms();
3040    setupDrawShaderUniforms();
3041    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
3042
3043    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
3044
3045    finishDrawTexture();
3046}
3047
3048// Same values used by Skia
3049#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
3050#define kStdUnderline_Offset    (1.0f / 9.0f)
3051#define kStdUnderline_Thickness (1.0f / 18.0f)
3052
3053void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
3054        float x, float y, SkPaint* paint) {
3055    // Handle underline and strike-through
3056    uint32_t flags = paint->getFlags();
3057    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
3058        SkPaint paintCopy(*paint);
3059        float underlineWidth = length;
3060        // If length is > 0.0f, we already measured the text for the text alignment
3061        if (length <= 0.0f) {
3062            underlineWidth = paintCopy.measureText(text, bytesCount);
3063        }
3064
3065        if (CC_LIKELY(underlineWidth > 0.0f)) {
3066            const float textSize = paintCopy.getTextSize();
3067            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
3068
3069            const float left = x;
3070            float top = 0.0f;
3071
3072            int linesCount = 0;
3073            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
3074            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
3075
3076            const int pointsCount = 4 * linesCount;
3077            float points[pointsCount];
3078            int currentPoint = 0;
3079
3080            if (flags & SkPaint::kUnderlineText_Flag) {
3081                top = y + textSize * kStdUnderline_Offset;
3082                points[currentPoint++] = left;
3083                points[currentPoint++] = top;
3084                points[currentPoint++] = left + underlineWidth;
3085                points[currentPoint++] = top;
3086            }
3087
3088            if (flags & SkPaint::kStrikeThruText_Flag) {
3089                top = y + textSize * kStdStrikeThru_Offset;
3090                points[currentPoint++] = left;
3091                points[currentPoint++] = top;
3092                points[currentPoint++] = left + underlineWidth;
3093                points[currentPoint++] = top;
3094            }
3095
3096            paintCopy.setStrokeWidth(strokeWidth);
3097
3098            drawLines(&points[0], pointsCount, &paintCopy);
3099        }
3100    }
3101}
3102
3103status_t OpenGLRenderer::drawRects(const float* rects, int count, SkPaint* paint) {
3104    if (mSnapshot->isIgnored()) {
3105        return DrawGlInfo::kStatusDone;
3106    }
3107
3108    int color = paint->getColor();
3109    // If a shader is set, preserve only the alpha
3110    if (mDrawModifiers.mShader) {
3111        color |= 0x00ffffff;
3112    }
3113    SkXfermode::Mode mode = getXfermode(paint->getXfermode());
3114
3115    return drawColorRects(rects, count, color, mode);
3116}
3117
3118status_t OpenGLRenderer::drawColorRects(const float* rects, int count, int color,
3119        SkXfermode::Mode mode, bool ignoreTransform, bool dirty, bool clip) {
3120    if (count == 0) {
3121        return DrawGlInfo::kStatusDone;
3122    }
3123
3124    float left = FLT_MAX;
3125    float top = FLT_MAX;
3126    float right = FLT_MIN;
3127    float bottom = FLT_MIN;
3128
3129    int vertexCount = 0;
3130    Vertex mesh[count * 6];
3131    Vertex* vertex = mesh;
3132
3133    for (int index = 0; index < count; index += 4) {
3134        float l = rects[index + 0];
3135        float t = rects[index + 1];
3136        float r = rects[index + 2];
3137        float b = rects[index + 3];
3138
3139        Vertex::set(vertex++, l, b);
3140        Vertex::set(vertex++, l, t);
3141        Vertex::set(vertex++, r, t);
3142        Vertex::set(vertex++, l, b);
3143        Vertex::set(vertex++, r, t);
3144        Vertex::set(vertex++, r, b);
3145
3146        vertexCount += 6;
3147
3148        left = fminf(left, l);
3149        top = fminf(top, t);
3150        right = fmaxf(right, r);
3151        bottom = fmaxf(bottom, b);
3152    }
3153
3154    if (clip && quickReject(left, top, right, bottom)) {
3155        return DrawGlInfo::kStatusDone;
3156    }
3157
3158    setupDraw();
3159    setupDrawNoTexture();
3160    setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
3161    setupDrawShader();
3162    setupDrawColorFilter();
3163    setupDrawBlending(mode);
3164    setupDrawProgram();
3165    setupDrawDirtyRegionsDisabled();
3166    setupDrawModelView(0.0f, 0.0f, 1.0f, 1.0f, ignoreTransform, true);
3167    setupDrawColorUniforms();
3168    setupDrawShaderUniforms();
3169    setupDrawColorFilterUniforms();
3170    setupDrawVertices((GLvoid*) &mesh[0].position[0]);
3171
3172    if (dirty && hasLayer()) {
3173        dirtyLayer(left, top, right, bottom, currentTransform());
3174    }
3175
3176    glDrawArrays(GL_TRIANGLES, 0, vertexCount);
3177
3178    return DrawGlInfo::kStatusDrew;
3179}
3180
3181void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
3182        int color, SkXfermode::Mode mode, bool ignoreTransform) {
3183    // If a shader is set, preserve only the alpha
3184    if (mDrawModifiers.mShader) {
3185        color |= 0x00ffffff;
3186    }
3187
3188    setupDraw();
3189    setupDrawNoTexture();
3190    setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
3191    setupDrawShader();
3192    setupDrawColorFilter();
3193    setupDrawBlending(mode);
3194    setupDrawProgram();
3195    setupDrawModelView(left, top, right, bottom, ignoreTransform);
3196    setupDrawColorUniforms();
3197    setupDrawShaderUniforms(ignoreTransform);
3198    setupDrawColorFilterUniforms();
3199    setupDrawSimpleMesh();
3200
3201    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
3202}
3203
3204void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
3205        Texture* texture, SkPaint* paint) {
3206    int alpha;
3207    SkXfermode::Mode mode;
3208    getAlphaAndMode(paint, &alpha, &mode);
3209
3210    texture->setWrap(GL_CLAMP_TO_EDGE, true);
3211
3212    if (CC_LIKELY(currentTransform().isPureTranslate())) {
3213        const float x = (int) floorf(left + currentTransform().getTranslateX() + 0.5f);
3214        const float y = (int) floorf(top + currentTransform().getTranslateY() + 0.5f);
3215
3216        texture->setFilter(GL_NEAREST, true);
3217        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
3218                alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL,
3219                (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true);
3220    } else {
3221        texture->setFilter(FILTER(paint), true);
3222        drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
3223                texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
3224                GL_TRIANGLE_STRIP, gMeshCount);
3225    }
3226}
3227
3228void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
3229        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
3230    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
3231            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
3232}
3233
3234void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
3235        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
3236        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3237        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
3238
3239    setupDraw();
3240    setupDrawWithTexture();
3241    setupDrawColor(alpha, alpha, alpha, alpha);
3242    setupDrawColorFilter();
3243    setupDrawBlending(blend, mode, swapSrcDst);
3244    setupDrawProgram();
3245    if (!dirty) setupDrawDirtyRegionsDisabled();
3246    if (!ignoreScale) {
3247        setupDrawModelView(left, top, right, bottom, ignoreTransform);
3248    } else {
3249        setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
3250    }
3251    setupDrawTexture(texture);
3252    setupDrawPureColorUniforms();
3253    setupDrawColorFilterUniforms();
3254    setupDrawMesh(vertices, texCoords, vbo);
3255
3256    glDrawArrays(drawMode, 0, elementsCount);
3257
3258    finishDrawTexture();
3259}
3260
3261void OpenGLRenderer::drawAlpha8TextureMesh(float left, float top, float right, float bottom,
3262        GLuint texture, bool hasColor, int color, int alpha, SkXfermode::Mode mode,
3263        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3264        bool ignoreTransform, bool dirty) {
3265
3266    setupDraw();
3267    setupDrawWithTexture(true);
3268    if (hasColor) {
3269        setupDrawAlpha8Color(color, alpha);
3270    }
3271    setupDrawColorFilter();
3272    setupDrawShader();
3273    setupDrawBlending(true, mode);
3274    setupDrawProgram();
3275    if (!dirty) setupDrawDirtyRegionsDisabled();
3276    setupDrawModelView(left, top, right, bottom, ignoreTransform);
3277    setupDrawTexture(texture);
3278    setupDrawPureColorUniforms();
3279    setupDrawColorFilterUniforms();
3280    setupDrawShaderUniforms();
3281    setupDrawMesh(vertices, texCoords);
3282
3283    glDrawArrays(drawMode, 0, elementsCount);
3284
3285    finishDrawTexture();
3286}
3287
3288void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
3289        ProgramDescription& description, bool swapSrcDst) {
3290    blend = blend || mode != SkXfermode::kSrcOver_Mode;
3291
3292    if (blend) {
3293        // These blend modes are not supported by OpenGL directly and have
3294        // to be implemented using shaders. Since the shader will perform
3295        // the blending, turn blending off here
3296        // If the blend mode cannot be implemented using shaders, fall
3297        // back to the default SrcOver blend mode instead
3298        if (CC_UNLIKELY(mode > SkXfermode::kScreen_Mode)) {
3299            if (CC_UNLIKELY(mExtensions.hasFramebufferFetch())) {
3300                description.framebufferMode = mode;
3301                description.swapSrcDst = swapSrcDst;
3302
3303                if (mCaches.blend) {
3304                    glDisable(GL_BLEND);
3305                    mCaches.blend = false;
3306                }
3307
3308                return;
3309            } else {
3310                mode = SkXfermode::kSrcOver_Mode;
3311            }
3312        }
3313
3314        if (!mCaches.blend) {
3315            glEnable(GL_BLEND);
3316        }
3317
3318        GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
3319        GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
3320
3321        if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
3322            glBlendFunc(sourceMode, destMode);
3323            mCaches.lastSrcMode = sourceMode;
3324            mCaches.lastDstMode = destMode;
3325        }
3326    } else if (mCaches.blend) {
3327        glDisable(GL_BLEND);
3328    }
3329    mCaches.blend = blend;
3330}
3331
3332bool OpenGLRenderer::useProgram(Program* program) {
3333    if (!program->isInUse()) {
3334        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
3335        program->use();
3336        mCaches.currentProgram = program;
3337        return false;
3338    }
3339    return true;
3340}
3341
3342void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
3343    TextureVertex* v = &mMeshVertices[0];
3344    TextureVertex::setUV(v++, u1, v1);
3345    TextureVertex::setUV(v++, u2, v1);
3346    TextureVertex::setUV(v++, u1, v2);
3347    TextureVertex::setUV(v++, u2, v2);
3348}
3349
3350void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
3351    getAlphaAndModeDirect(paint, alpha,  mode);
3352    *alpha *= mSnapshot->alpha;
3353}
3354
3355}; // namespace uirenderer
3356}; // namespace android
3357