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