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