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