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