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