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