OpenGLRenderer.cpp revision e3c26851dc315b730ea0fe5ef35bb1db81f6d675
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    glDisable(GL_DITHER);
129    glViewport(0, 0, width, height);
130    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
131
132    mWidth = width;
133    mHeight = height;
134
135    mFirstSnapshot->height = height;
136    mFirstSnapshot->viewport.set(0, 0, width, height);
137
138    mDirtyClip = false;
139}
140
141void OpenGLRenderer::prepare(bool opaque) {
142    prepareDirty(0.0f, 0.0f, mWidth, mHeight, opaque);
143}
144
145void OpenGLRenderer::prepareDirty(float left, float top, float right, float bottom, bool opaque) {
146    mCaches.clearGarbage();
147
148    mSnapshot = new Snapshot(mFirstSnapshot,
149            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
150    mSnapshot->fbo = getTargetFbo();
151
152    mSaveCount = 1;
153
154    glViewport(0, 0, mWidth, mHeight);
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            layer->getWidth() == (uint32_t) rect.getWidth() &&
650            layer->getHeight() == (uint32_t) rect.getHeight()) {
651        const float x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f);
652        const float y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f);
653
654        layer->setFilter(GL_NEAREST, GL_NEAREST);
655        setupDrawModelView(x, y, x + rect.getWidth(), y + rect.getHeight(), true);
656    } else {
657        layer->setFilter(GL_LINEAR, GL_LINEAR);
658        setupDrawModelView(rect.left, rect.top, rect.right, rect.bottom);
659    }
660    setupDrawTextureTransformUniforms(layer->getTexTransform());
661    setupDrawMesh(&mMeshVertices[0].position[0], &mMeshVertices[0].texture[0]);
662
663    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
664
665    finishDrawTexture();
666}
667
668void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
669    if (!layer->isTextureLayer()) {
670        const Rect& texCoords = layer->texCoords;
671        resetDrawTextureTexCoords(texCoords.left, texCoords.top,
672                texCoords.right, texCoords.bottom);
673
674        float x = rect.left;
675        float y = rect.top;
676        bool simpleTransform = mSnapshot->transform->isPureTranslate() &&
677                layer->getWidth() == (uint32_t) rect.getWidth() &&
678                layer->getHeight() == (uint32_t) rect.getHeight();
679
680        if (simpleTransform) {
681            // When we're swapping, the layer is already in screen coordinates
682            if (!swap) {
683                x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f);
684                y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f);
685            }
686
687            layer->setFilter(GL_NEAREST, GL_NEAREST, true);
688        } else {
689            layer->setFilter(GL_LINEAR, GL_LINEAR, true);
690        }
691
692        drawTextureMesh(x, y, x + rect.getWidth(), y + rect.getHeight(),
693                layer->getTexture(), layer->getAlpha() / 255.0f,
694                layer->getMode(), layer->isBlend(),
695                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
696                GL_TRIANGLE_STRIP, gMeshCount, swap, swap || simpleTransform);
697
698        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
699    } else {
700        resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f);
701        drawTextureLayer(layer, rect);
702        resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
703    }
704}
705
706void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
707#if RENDER_LAYERS_AS_REGIONS
708    if (layer->region.isRect()) {
709        layer->setRegionAsRect();
710
711        composeLayerRect(layer, layer->regionRect);
712
713        layer->region.clear();
714        return;
715    }
716
717    if (!layer->region.isEmpty()) {
718        size_t count;
719        const android::Rect* rects = layer->region.getArray(&count);
720
721        const float alpha = layer->getAlpha() / 255.0f;
722        const float texX = 1.0f / float(layer->getWidth());
723        const float texY = 1.0f / float(layer->getHeight());
724        const float height = rect.getHeight();
725
726        TextureVertex* mesh = mCaches.getRegionMesh();
727        GLsizei numQuads = 0;
728
729        setupDraw();
730        setupDrawWithTexture();
731        setupDrawColor(alpha, alpha, alpha, alpha);
732        setupDrawColorFilter();
733        setupDrawBlending(layer->isBlend() || alpha < 1.0f, layer->getMode(), false);
734        setupDrawProgram();
735        setupDrawDirtyRegionsDisabled();
736        setupDrawPureColorUniforms();
737        setupDrawColorFilterUniforms();
738        setupDrawTexture(layer->getTexture());
739        if (mSnapshot->transform->isPureTranslate()) {
740            const float x = (int) floorf(rect.left + mSnapshot->transform->getTranslateX() + 0.5f);
741            const float y = (int) floorf(rect.top + mSnapshot->transform->getTranslateY() + 0.5f);
742
743            layer->setFilter(GL_NEAREST, GL_NEAREST);
744            setupDrawModelViewTranslate(x, y, x + rect.getWidth(), y + rect.getHeight(), true);
745        } else {
746            layer->setFilter(GL_LINEAR, GL_LINEAR);
747            setupDrawModelViewTranslate(rect.left, rect.top, rect.right, rect.bottom);
748        }
749        setupDrawMesh(&mesh[0].position[0], &mesh[0].texture[0]);
750
751        for (size_t i = 0; i < count; i++) {
752            const android::Rect* r = &rects[i];
753
754            const float u1 = r->left * texX;
755            const float v1 = (height - r->top) * texY;
756            const float u2 = r->right * texX;
757            const float v2 = (height - r->bottom) * texY;
758
759            // TODO: Reject quads outside of the clip
760            TextureVertex::set(mesh++, r->left, r->top, u1, v1);
761            TextureVertex::set(mesh++, r->right, r->top, u2, v1);
762            TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
763            TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
764
765            numQuads++;
766
767            if (numQuads >= REGION_MESH_QUAD_COUNT) {
768                glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
769                numQuads = 0;
770                mesh = mCaches.getRegionMesh();
771            }
772        }
773
774        if (numQuads > 0) {
775            glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
776        }
777
778        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
779        finishDrawTexture();
780
781#if DEBUG_LAYERS_AS_REGIONS
782        drawRegionRects(layer->region);
783#endif
784
785        layer->region.clear();
786    }
787#else
788    composeLayerRect(layer, rect);
789#endif
790}
791
792void OpenGLRenderer::drawRegionRects(const Region& region) {
793#if DEBUG_LAYERS_AS_REGIONS
794    size_t count;
795    const android::Rect* rects = region.getArray(&count);
796
797    uint32_t colors[] = {
798            0x7fff0000, 0x7f00ff00,
799            0x7f0000ff, 0x7fff00ff,
800    };
801
802    int offset = 0;
803    int32_t top = rects[0].top;
804
805    for (size_t i = 0; i < count; i++) {
806        if (top != rects[i].top) {
807            offset ^= 0x2;
808            top = rects[i].top;
809        }
810
811        Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
812        drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)],
813                SkXfermode::kSrcOver_Mode);
814    }
815#endif
816}
817
818void OpenGLRenderer::dirtyLayer(const float left, const float top,
819        const float right, const float bottom, const mat4 transform) {
820#if RENDER_LAYERS_AS_REGIONS
821    if (hasLayer()) {
822        Rect bounds(left, top, right, bottom);
823        transform.mapRect(bounds);
824        dirtyLayerUnchecked(bounds, getRegion());
825    }
826#endif
827}
828
829void OpenGLRenderer::dirtyLayer(const float left, const float top,
830        const float right, const float bottom) {
831#if RENDER_LAYERS_AS_REGIONS
832    if (hasLayer()) {
833        Rect bounds(left, top, right, bottom);
834        dirtyLayerUnchecked(bounds, getRegion());
835    }
836#endif
837}
838
839void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
840#if RENDER_LAYERS_AS_REGIONS
841    if (bounds.intersect(*mSnapshot->clipRect)) {
842        bounds.snapToPixelBoundaries();
843        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
844        if (!dirty.isEmpty()) {
845            region->orSelf(dirty);
846        }
847    }
848#endif
849}
850
851void OpenGLRenderer::clearLayerRegions() {
852    const size_t count = mLayers.size();
853    if (count == 0) return;
854
855    if (!mSnapshot->isIgnored()) {
856        // Doing several glScissor/glClear here can negatively impact
857        // GPUs with a tiler architecture, instead we draw quads with
858        // the Clear blending mode
859
860        // The list contains bounds that have already been clipped
861        // against their initial clip rect, and the current clip
862        // is likely different so we need to disable clipping here
863        glDisable(GL_SCISSOR_TEST);
864
865        Vertex mesh[count * 6];
866        Vertex* vertex = mesh;
867
868        for (uint32_t i = 0; i < count; i++) {
869            Rect* bounds = mLayers.itemAt(i);
870
871            Vertex::set(vertex++, bounds->left, bounds->bottom);
872            Vertex::set(vertex++, bounds->left, bounds->top);
873            Vertex::set(vertex++, bounds->right, bounds->top);
874            Vertex::set(vertex++, bounds->left, bounds->bottom);
875            Vertex::set(vertex++, bounds->right, bounds->top);
876            Vertex::set(vertex++, bounds->right, bounds->bottom);
877
878            delete bounds;
879        }
880
881        setupDraw(false);
882        setupDrawColor(0.0f, 0.0f, 0.0f, 1.0f);
883        setupDrawBlending(true, SkXfermode::kClear_Mode);
884        setupDrawProgram();
885        setupDrawPureColorUniforms();
886        setupDrawModelViewTranslate(0.0f, 0.0f, 0.0f, 0.0f, true);
887
888        mCaches.unbindMeshBuffer();
889        glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
890                gVertexStride, &mesh[0].position[0]);
891        glDrawArrays(GL_TRIANGLES, 0, count * 6);
892
893        glEnable(GL_SCISSOR_TEST);
894    } else {
895        for (uint32_t i = 0; i < count; i++) {
896            delete mLayers.itemAt(i);
897        }
898    }
899
900    mLayers.clear();
901}
902
903///////////////////////////////////////////////////////////////////////////////
904// Transforms
905///////////////////////////////////////////////////////////////////////////////
906
907void OpenGLRenderer::translate(float dx, float dy) {
908    mSnapshot->transform->translate(dx, dy, 0.0f);
909}
910
911void OpenGLRenderer::rotate(float degrees) {
912    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
913}
914
915void OpenGLRenderer::scale(float sx, float sy) {
916    mSnapshot->transform->scale(sx, sy, 1.0f);
917}
918
919void OpenGLRenderer::skew(float sx, float sy) {
920    mSnapshot->transform->skew(sx, sy);
921}
922
923void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
924    mSnapshot->transform->load(*matrix);
925}
926
927const float* OpenGLRenderer::getMatrix() const {
928    if (mSnapshot->fbo != 0) {
929        return &mSnapshot->transform->data[0];
930    }
931    return &mIdentity.data[0];
932}
933
934void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
935    mSnapshot->transform->copyTo(*matrix);
936}
937
938void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
939    SkMatrix transform;
940    mSnapshot->transform->copyTo(transform);
941    transform.preConcat(*matrix);
942    mSnapshot->transform->load(transform);
943}
944
945///////////////////////////////////////////////////////////////////////////////
946// Clipping
947///////////////////////////////////////////////////////////////////////////////
948
949void OpenGLRenderer::setScissorFromClip() {
950    Rect clip(*mSnapshot->clipRect);
951    clip.snapToPixelBoundaries();
952    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
953    mDirtyClip = false;
954}
955
956const Rect& OpenGLRenderer::getClipBounds() {
957    return mSnapshot->getLocalClip();
958}
959
960bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
961    if (mSnapshot->isIgnored()) {
962        return true;
963    }
964
965    Rect r(left, top, right, bottom);
966    mSnapshot->transform->mapRect(r);
967    r.snapToPixelBoundaries();
968
969    Rect clipRect(*mSnapshot->clipRect);
970    clipRect.snapToPixelBoundaries();
971
972    return !clipRect.intersects(r);
973}
974
975bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
976    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
977    if (clipped) {
978        dirtyClip();
979    }
980    return !mSnapshot->clipRect->isEmpty();
981}
982
983///////////////////////////////////////////////////////////////////////////////
984// Drawing commands
985///////////////////////////////////////////////////////////////////////////////
986
987void OpenGLRenderer::setupDraw(bool clear) {
988    if (clear) clearLayerRegions();
989    if (mDirtyClip) {
990        setScissorFromClip();
991    }
992    mDescription.reset();
993    mSetShaderColor = false;
994    mColorSet = false;
995    mColorA = mColorR = mColorG = mColorB = 0.0f;
996    mTextureUnit = 0;
997    mTrackDirtyRegions = true;
998    mTexCoordsSlot = -1;
999}
1000
1001void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
1002    mDescription.hasTexture = true;
1003    mDescription.hasAlpha8Texture = isAlpha8;
1004}
1005
1006void OpenGLRenderer::setupDrawWithExternalTexture() {
1007    mDescription.hasExternalTexture = true;
1008}
1009
1010void OpenGLRenderer::setupDrawAALine() {
1011    mDescription.isAA = true;
1012}
1013
1014void OpenGLRenderer::setupDrawPoint(float pointSize) {
1015    mDescription.isPoint = true;
1016    mDescription.pointSize = pointSize;
1017}
1018
1019void OpenGLRenderer::setupDrawColor(int color) {
1020    setupDrawColor(color, (color >> 24) & 0xFF);
1021}
1022
1023void OpenGLRenderer::setupDrawColor(int color, int alpha) {
1024    mColorA = alpha / 255.0f;
1025    // Second divide of a by 255 is an optimization, allowing us to simply multiply
1026    // the rgb values by a instead of also dividing by 255
1027    const float a = mColorA / 255.0f;
1028    mColorR = a * ((color >> 16) & 0xFF);
1029    mColorG = a * ((color >>  8) & 0xFF);
1030    mColorB = a * ((color      ) & 0xFF);
1031    mColorSet = true;
1032    mSetShaderColor = mDescription.setColor(mColorR, mColorG, mColorB, mColorA);
1033}
1034
1035void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
1036    mColorA = alpha / 255.0f;
1037    // Double-divide of a by 255 is an optimization, allowing us to simply multiply
1038    // the rgb values by a instead of also dividing by 255
1039    const float a = mColorA / 255.0f;
1040    mColorR = a * ((color >> 16) & 0xFF);
1041    mColorG = a * ((color >>  8) & 0xFF);
1042    mColorB = a * ((color      ) & 0xFF);
1043    mColorSet = true;
1044    mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA);
1045}
1046
1047void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
1048    mColorA = a;
1049    mColorR = r;
1050    mColorG = g;
1051    mColorB = b;
1052    mColorSet = true;
1053    mSetShaderColor = mDescription.setColor(r, g, b, a);
1054}
1055
1056void OpenGLRenderer::setupDrawAlpha8Color(float r, float g, float b, float a) {
1057    mColorA = a;
1058    mColorR = r;
1059    mColorG = g;
1060    mColorB = b;
1061    mColorSet = true;
1062    mSetShaderColor = mDescription.setAlpha8Color(r, g, b, a);
1063}
1064
1065void OpenGLRenderer::setupDrawShader() {
1066    if (mShader) {
1067        mShader->describe(mDescription, mCaches.extensions);
1068    }
1069}
1070
1071void OpenGLRenderer::setupDrawColorFilter() {
1072    if (mColorFilter) {
1073        mColorFilter->describe(mDescription, mCaches.extensions);
1074    }
1075}
1076
1077void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) {
1078    if (mColorSet && mode == SkXfermode::kClear_Mode) {
1079        mColorA = 1.0f;
1080        mColorR = mColorG = mColorB = 0.0f;
1081        mSetShaderColor = mDescription.modulate = true;
1082    }
1083}
1084
1085void OpenGLRenderer::setupDrawBlending(SkXfermode::Mode mode, bool swapSrcDst) {
1086    // When the blending mode is kClear_Mode, we need to use a modulate color
1087    // argb=1,0,0,0
1088    accountForClear(mode);
1089    chooseBlending((mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
1090            mDescription, swapSrcDst);
1091}
1092
1093void OpenGLRenderer::setupDrawBlending(bool blend, SkXfermode::Mode mode, bool swapSrcDst) {
1094    // When the blending mode is kClear_Mode, we need to use a modulate color
1095    // argb=1,0,0,0
1096    accountForClear(mode);
1097    chooseBlending(blend || (mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
1098            mDescription, swapSrcDst);
1099}
1100
1101void OpenGLRenderer::setupDrawProgram() {
1102    useProgram(mCaches.programCache.get(mDescription));
1103}
1104
1105void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
1106    mTrackDirtyRegions = false;
1107}
1108
1109void OpenGLRenderer::setupDrawModelViewTranslate(float left, float top, float right, float bottom,
1110        bool ignoreTransform) {
1111    mModelView.loadTranslate(left, top, 0.0f);
1112    if (!ignoreTransform) {
1113        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1114        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1115    } else {
1116        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
1117        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom);
1118    }
1119}
1120
1121void OpenGLRenderer::setupDrawModelViewIdentity(bool offset) {
1122    mCaches.currentProgram->set(mOrthoMatrix, mIdentity, *mSnapshot->transform, offset);
1123}
1124
1125void OpenGLRenderer::setupDrawModelView(float left, float top, float right, float bottom,
1126        bool ignoreTransform, bool ignoreModelView) {
1127    if (!ignoreModelView) {
1128        mModelView.loadTranslate(left, top, 0.0f);
1129        mModelView.scale(right - left, bottom - top, 1.0f);
1130    } else {
1131        mModelView.loadIdentity();
1132    }
1133    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
1134    if (!ignoreTransform) {
1135        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1136        if (mTrackDirtyRegions && dirty) {
1137            dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1138        }
1139    } else {
1140        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
1141        if (mTrackDirtyRegions && dirty) dirtyLayer(left, top, right, bottom);
1142    }
1143}
1144
1145void OpenGLRenderer::setupDrawPointUniforms() {
1146    int slot = mCaches.currentProgram->getUniform("pointSize");
1147    glUniform1f(slot, mDescription.pointSize);
1148}
1149
1150void OpenGLRenderer::setupDrawColorUniforms() {
1151    if (mColorSet || (mShader && mSetShaderColor)) {
1152        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1153    }
1154}
1155
1156void OpenGLRenderer::setupDrawPureColorUniforms() {
1157    if (mSetShaderColor) {
1158        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1159    }
1160}
1161
1162void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) {
1163    if (mShader) {
1164        if (ignoreTransform) {
1165            mModelView.loadInverse(*mSnapshot->transform);
1166        }
1167        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &mTextureUnit);
1168    }
1169}
1170
1171void OpenGLRenderer::setupDrawShaderIdentityUniforms() {
1172    if (mShader) {
1173        mShader->setupProgram(mCaches.currentProgram, mIdentity, *mSnapshot, &mTextureUnit);
1174    }
1175}
1176
1177void OpenGLRenderer::setupDrawColorFilterUniforms() {
1178    if (mColorFilter) {
1179        mColorFilter->setupProgram(mCaches.currentProgram);
1180    }
1181}
1182
1183void OpenGLRenderer::setupDrawSimpleMesh() {
1184    mCaches.bindMeshBuffer();
1185    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1186            gMeshStride, 0);
1187}
1188
1189void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1190    bindTexture(texture);
1191    glUniform1i(mCaches.currentProgram->getUniform("sampler"), mTextureUnit++);
1192
1193    mTexCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1194    glEnableVertexAttribArray(mTexCoordsSlot);
1195}
1196
1197void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) {
1198    bindExternalTexture(texture);
1199    glUniform1i(mCaches.currentProgram->getUniform("sampler"), mTextureUnit++);
1200
1201    mTexCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1202    glEnableVertexAttribArray(mTexCoordsSlot);
1203}
1204
1205void OpenGLRenderer::setupDrawTextureTransform() {
1206    mDescription.hasTextureTransform = true;
1207}
1208
1209void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) {
1210    glUniformMatrix4fv(mCaches.currentProgram->getUniform("mainTextureTransform"), 1,
1211            GL_FALSE, &transform.data[0]);
1212}
1213
1214void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
1215    if (!vertices) {
1216        mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1217    } else {
1218        mCaches.unbindMeshBuffer();
1219    }
1220    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1221            gMeshStride, vertices);
1222    if (mTexCoordsSlot >= 0) {
1223        glVertexAttribPointer(mTexCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1224    }
1225}
1226
1227void OpenGLRenderer::setupDrawVertices(GLvoid* vertices) {
1228    mCaches.unbindMeshBuffer();
1229    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1230            gVertexStride, vertices);
1231}
1232
1233/**
1234 * Sets up the shader to draw an AA line. We draw AA lines with quads, where there is an
1235 * outer boundary that fades out to 0. The variables set in the shader define the proportion of
1236 * the width and length of the primitive occupied by the AA region. The vtxWidth and vtxLength
1237 * attributes (one per vertex) are values from zero to one that tells the fragment
1238 * shader where the fragment is in relation to the line width/length overall; these values are
1239 * then used to compute the proper color, based on whether the fragment lies in the fading AA
1240 * region of the line.
1241 * Note that we only pass down the width values in this setup function. The length coordinates
1242 * are set up for each individual segment.
1243 */
1244void OpenGLRenderer::setupDrawAALine(GLvoid* vertices, GLvoid* widthCoords,
1245        GLvoid* lengthCoords, float boundaryWidthProportion) {
1246    mCaches.unbindMeshBuffer();
1247    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1248            gAAVertexStride, vertices);
1249    int widthSlot = mCaches.currentProgram->getAttrib("vtxWidth");
1250    glEnableVertexAttribArray(widthSlot);
1251    glVertexAttribPointer(widthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, widthCoords);
1252    int lengthSlot = mCaches.currentProgram->getAttrib("vtxLength");
1253    glEnableVertexAttribArray(lengthSlot);
1254    glVertexAttribPointer(lengthSlot, 1, GL_FLOAT, GL_FALSE, gAAVertexStride, lengthCoords);
1255    int boundaryWidthSlot = mCaches.currentProgram->getUniform("boundaryWidth");
1256    glUniform1f(boundaryWidthSlot, boundaryWidthProportion);
1257    // Setting the inverse value saves computations per-fragment in the shader
1258    int inverseBoundaryWidthSlot = mCaches.currentProgram->getUniform("inverseBoundaryWidth");
1259    glUniform1f(inverseBoundaryWidthSlot, (1 / boundaryWidthProportion));
1260}
1261
1262void OpenGLRenderer::finishDrawTexture() {
1263    glDisableVertexAttribArray(mTexCoordsSlot);
1264}
1265
1266///////////////////////////////////////////////////////////////////////////////
1267// Drawing
1268///////////////////////////////////////////////////////////////////////////////
1269
1270bool OpenGLRenderer::drawDisplayList(DisplayList* displayList, uint32_t width, uint32_t height,
1271        Rect& dirty, uint32_t level) {
1272    if (quickReject(0.0f, 0.0f, width, height)) {
1273        return false;
1274    }
1275
1276    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1277    // will be performed by the display list itself
1278    if (displayList) {
1279        return displayList->replay(*this, dirty, level);
1280    }
1281
1282    return false;
1283}
1284
1285void OpenGLRenderer::outputDisplayList(DisplayList* displayList, uint32_t level) {
1286    if (displayList) {
1287        displayList->output(*this, level);
1288    }
1289}
1290
1291void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, SkPaint* paint) {
1292    int alpha;
1293    SkXfermode::Mode mode;
1294    getAlphaAndMode(paint, &alpha, &mode);
1295
1296    float x = left;
1297    float y = top;
1298
1299    GLenum filter = GL_LINEAR;
1300    bool ignoreTransform = false;
1301    if (mSnapshot->transform->isPureTranslate()) {
1302        x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1303        y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1304        ignoreTransform = true;
1305        filter = GL_NEAREST;
1306    }
1307
1308    setupDraw();
1309    setupDrawWithTexture(true);
1310    if (paint) {
1311        setupDrawAlpha8Color(paint->getColor(), alpha);
1312    }
1313    setupDrawColorFilter();
1314    setupDrawShader();
1315    setupDrawBlending(true, mode);
1316    setupDrawProgram();
1317    setupDrawModelView(x, y, x + texture->width, y + texture->height, ignoreTransform);
1318
1319    setupDrawTexture(texture->id);
1320    texture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1321    texture->setFilter(filter, filter);
1322
1323    setupDrawPureColorUniforms();
1324    setupDrawColorFilterUniforms();
1325    setupDrawShaderUniforms();
1326    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
1327
1328    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1329
1330    finishDrawTexture();
1331}
1332
1333void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
1334    const float right = left + bitmap->width();
1335    const float bottom = top + bitmap->height();
1336
1337    if (quickReject(left, top, right, bottom)) {
1338        return;
1339    }
1340
1341    glActiveTexture(gTextureUnits[0]);
1342    Texture* texture = mCaches.textureCache.get(bitmap);
1343    if (!texture) return;
1344    const AutoTexture autoCleanup(texture);
1345
1346    if (bitmap->getConfig() == SkBitmap::kA8_Config) {
1347        drawAlphaBitmap(texture, left, top, paint);
1348    } else {
1349        drawTextureRect(left, top, right, bottom, texture, paint);
1350    }
1351}
1352
1353void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
1354    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
1355    const mat4 transform(*matrix);
1356    transform.mapRect(r);
1357
1358    if (quickReject(r.left, r.top, r.right, r.bottom)) {
1359        return;
1360    }
1361
1362    glActiveTexture(gTextureUnits[0]);
1363    Texture* texture = mCaches.textureCache.get(bitmap);
1364    if (!texture) return;
1365    const AutoTexture autoCleanup(texture);
1366
1367    // This could be done in a cheaper way, all we need is pass the matrix
1368    // to the vertex shader. The save/restore is a bit overkill.
1369    save(SkCanvas::kMatrix_SaveFlag);
1370    concatMatrix(matrix);
1371    drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
1372    restore();
1373}
1374
1375void OpenGLRenderer::drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight,
1376        float* vertices, int* colors, SkPaint* paint) {
1377    // TODO: Do a quickReject
1378    if (!vertices || mSnapshot->isIgnored()) {
1379        return;
1380    }
1381
1382    glActiveTexture(gTextureUnits[0]);
1383    Texture* texture = mCaches.textureCache.get(bitmap);
1384    if (!texture) return;
1385    const AutoTexture autoCleanup(texture);
1386
1387    texture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, true);
1388    texture->setFilter(GL_LINEAR, GL_LINEAR, true);
1389
1390    int alpha;
1391    SkXfermode::Mode mode;
1392    getAlphaAndMode(paint, &alpha, &mode);
1393
1394    const uint32_t count = meshWidth * meshHeight * 6;
1395
1396    float left = FLT_MAX;
1397    float top = FLT_MAX;
1398    float right = FLT_MIN;
1399    float bottom = FLT_MIN;
1400
1401#if RENDER_LAYERS_AS_REGIONS
1402    bool hasActiveLayer = hasLayer();
1403#else
1404    bool hasActiveLayer = false;
1405#endif
1406
1407    // TODO: Support the colors array
1408    TextureVertex mesh[count];
1409    TextureVertex* vertex = mesh;
1410    for (int32_t y = 0; y < meshHeight; y++) {
1411        for (int32_t x = 0; x < meshWidth; x++) {
1412            uint32_t i = (y * (meshWidth + 1) + x) * 2;
1413
1414            float u1 = float(x) / meshWidth;
1415            float u2 = float(x + 1) / meshWidth;
1416            float v1 = float(y) / meshHeight;
1417            float v2 = float(y + 1) / meshHeight;
1418
1419            int ax = i + (meshWidth + 1) * 2;
1420            int ay = ax + 1;
1421            int bx = i;
1422            int by = bx + 1;
1423            int cx = i + 2;
1424            int cy = cx + 1;
1425            int dx = i + (meshWidth + 1) * 2 + 2;
1426            int dy = dx + 1;
1427
1428            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1429            TextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1);
1430            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1431
1432            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1433            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1434            TextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2);
1435
1436#if RENDER_LAYERS_AS_REGIONS
1437            if (hasActiveLayer) {
1438                // TODO: This could be optimized to avoid unnecessary ops
1439                left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
1440                top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
1441                right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
1442                bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
1443            }
1444#endif
1445        }
1446    }
1447
1448#if RENDER_LAYERS_AS_REGIONS
1449    if (hasActiveLayer) {
1450        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1451    }
1452#endif
1453
1454    drawTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, alpha / 255.0f,
1455            mode, texture->blend, &mesh[0].position[0], &mesh[0].texture[0],
1456            GL_TRIANGLES, count, false, false, 0, false, false);
1457}
1458
1459void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
1460         float srcLeft, float srcTop, float srcRight, float srcBottom,
1461         float dstLeft, float dstTop, float dstRight, float dstBottom,
1462         SkPaint* paint) {
1463    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
1464        return;
1465    }
1466
1467    glActiveTexture(gTextureUnits[0]);
1468    Texture* texture = mCaches.textureCache.get(bitmap);
1469    if (!texture) return;
1470    const AutoTexture autoCleanup(texture);
1471    texture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, true);
1472
1473    const float width = texture->width;
1474    const float height = texture->height;
1475
1476    const float u1 = (srcLeft + 0.5f) / width;
1477    const float v1 = (srcTop + 0.5f)  / height;
1478    const float u2 = (srcRight - 0.5f) / width;
1479    const float v2 = (srcBottom - 0.5f) / height;
1480
1481    mCaches.unbindMeshBuffer();
1482    resetDrawTextureTexCoords(u1, v1, u2, v2);
1483
1484    int alpha;
1485    SkXfermode::Mode mode;
1486    getAlphaAndMode(paint, &alpha, &mode);
1487
1488    if (mSnapshot->transform->isPureTranslate()) {
1489        const float x = (int) floorf(dstLeft + mSnapshot->transform->getTranslateX() + 0.5f);
1490        const float y = (int) floorf(dstTop + mSnapshot->transform->getTranslateY() + 0.5f);
1491
1492        texture->setFilter(GL_NEAREST, GL_NEAREST, true);
1493        drawTextureMesh(x, y, x + (dstRight - dstLeft), y + (dstBottom - dstTop),
1494                texture->id, alpha / 255.0f, mode, texture->blend,
1495                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1496                GL_TRIANGLE_STRIP, gMeshCount, false, true);
1497    } else {
1498        texture->setFilter(GL_LINEAR, GL_LINEAR, true);
1499        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, texture->id, alpha / 255.0f,
1500                mode, texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1501                GL_TRIANGLE_STRIP, gMeshCount);
1502    }
1503
1504    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1505}
1506
1507void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
1508        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
1509        float left, float top, float right, float bottom, SkPaint* paint) {
1510    if (quickReject(left, top, right, bottom)) {
1511        return;
1512    }
1513
1514    glActiveTexture(gTextureUnits[0]);
1515    Texture* texture = mCaches.textureCache.get(bitmap);
1516    if (!texture) return;
1517    const AutoTexture autoCleanup(texture);
1518    texture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, true);
1519    texture->setFilter(GL_LINEAR, GL_LINEAR, true);
1520
1521    int alpha;
1522    SkXfermode::Mode mode;
1523    getAlphaAndMode(paint, &alpha, &mode);
1524
1525    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
1526            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
1527
1528    if (mesh && mesh->verticesCount > 0) {
1529        const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1530#if RENDER_LAYERS_AS_REGIONS
1531        // Mark the current layer dirty where we are going to draw the patch
1532        if (hasLayer() && mesh->hasEmptyQuads) {
1533            const float offsetX = left + mSnapshot->transform->getTranslateX();
1534            const float offsetY = top + mSnapshot->transform->getTranslateY();
1535            const size_t count = mesh->quads.size();
1536            for (size_t i = 0; i < count; i++) {
1537                const Rect& bounds = mesh->quads.itemAt(i);
1538                if (pureTranslate) {
1539                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
1540                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
1541                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
1542                } else {
1543                    dirtyLayer(left + bounds.left, top + bounds.top,
1544                            left + bounds.right, top + bounds.bottom, *mSnapshot->transform);
1545                }
1546            }
1547        }
1548#endif
1549
1550        if (pureTranslate) {
1551            const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1552            const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1553
1554            drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f,
1555                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1556                    GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer,
1557                    true, !mesh->hasEmptyQuads);
1558        } else {
1559            drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f,
1560                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1561                    GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer,
1562                    true, !mesh->hasEmptyQuads);
1563        }
1564    }
1565}
1566
1567/**
1568 * This function uses a similar approach to that of AA lines in the drawLines() function.
1569 * We expand the rectangle by a half pixel in screen space on all sides, and use a fragment
1570 * shader to compute the translucency of the color, determined by whether a given pixel is
1571 * within that boundary region and how far into the region it is.
1572 */
1573void OpenGLRenderer::drawAARect(float left, float top, float right, float bottom,
1574        int color, SkXfermode::Mode mode) {
1575    float inverseScaleX = 1.0f;
1576    float inverseScaleY = 1.0f;
1577    // The quad that we use needs to account for scaling.
1578    if (!mSnapshot->transform->isPureTranslate()) {
1579        Matrix4 *mat = mSnapshot->transform;
1580        float m00 = mat->data[Matrix4::kScaleX];
1581        float m01 = mat->data[Matrix4::kSkewY];
1582        float m02 = mat->data[2];
1583        float m10 = mat->data[Matrix4::kSkewX];
1584        float m11 = mat->data[Matrix4::kScaleX];
1585        float m12 = mat->data[6];
1586        float scaleX = sqrt(m00 * m00 + m01 * m01);
1587        float scaleY = sqrt(m10 * m10 + m11 * m11);
1588        inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0;
1589        inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0;
1590    }
1591
1592    setupDraw();
1593    setupDrawAALine();
1594    setupDrawColor(color);
1595    setupDrawColorFilter();
1596    setupDrawShader();
1597    setupDrawBlending(true, mode);
1598    setupDrawProgram();
1599    setupDrawModelViewIdentity(true);
1600    setupDrawColorUniforms();
1601    setupDrawColorFilterUniforms();
1602    setupDrawShaderIdentityUniforms();
1603
1604    AAVertex rects[4];
1605    AAVertex* aaVertices = &rects[0];
1606    void* widthCoords = ((GLbyte*) aaVertices) + gVertexAAWidthOffset;
1607    void* lengthCoords = ((GLbyte*) aaVertices) + gVertexAALengthOffset;
1608
1609    float boundarySizeX = .5 * inverseScaleX;
1610    float boundarySizeY = .5 * inverseScaleY;
1611
1612    // Adjust the rect by the AA boundary padding
1613    left -= boundarySizeX;
1614    right += boundarySizeX;
1615    top -= boundarySizeY;
1616    bottom += boundarySizeY;
1617
1618    float width = right - left;
1619    float height = bottom - top;
1620
1621    float boundaryWidthProportion = (width != 0) ? (2 * boundarySizeX) / width : 0;
1622    float boundaryHeightProportion = (height != 0) ? (2 * boundarySizeY) / height : 0;
1623    setupDrawAALine((void*) aaVertices, widthCoords, lengthCoords, boundaryWidthProportion);
1624    int boundaryLengthSlot = mCaches.currentProgram->getUniform("boundaryLength");
1625    int inverseBoundaryLengthSlot = mCaches.currentProgram->getUniform("inverseBoundaryLength");
1626    glUniform1f(boundaryLengthSlot, boundaryHeightProportion);
1627    glUniform1f(inverseBoundaryLengthSlot, (1 / boundaryHeightProportion));
1628
1629    if (!quickReject(left, top, right, bottom)) {
1630        AAVertex::set(aaVertices++, left, bottom, 1, 1);
1631        AAVertex::set(aaVertices++, left, top, 1, 0);
1632        AAVertex::set(aaVertices++, right, bottom, 0, 1);
1633        AAVertex::set(aaVertices++, right, top, 0, 0);
1634        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1635        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1636    }
1637}
1638
1639/**
1640 * We draw lines as quads (tristrips). Using GL_LINES can be difficult because the rasterization
1641 * rules for those lines produces some unexpected results, and may vary between hardware devices.
1642 * The basics of lines-as-quads is easy; we simply find the normal to the line and position the
1643 * corners of the quads on either side of each line endpoint, separated by the strokeWidth
1644 * of the line. Hairlines are more involved because we need to account for transform scaling
1645 * to end up with a one-pixel-wide line in screen space..
1646 * Anti-aliased lines add another factor to the approach. We use a specialized fragment shader
1647 * in combination with values that we calculate and pass down in this method. The basic approach
1648 * is that the quad we create contains both the core line area plus a bounding area in which
1649 * the translucent/AA pixels are drawn. The values we calculate tell the shader what
1650 * proportion of the width and the length of a given segment is represented by the boundary
1651 * region. The quad ends up being exactly .5 pixel larger in all directions than the non-AA quad.
1652 * The bounding region is actually 1 pixel wide on all sides (half pixel on the outside, half pixel
1653 * on the inside). This ends up giving the result we want, with pixels that are completely
1654 * 'inside' the line area being filled opaquely and the other pixels being filled according to
1655 * how far into the boundary region they are, which is determined by shader interpolation.
1656 */
1657void OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
1658    if (mSnapshot->isIgnored()) return;
1659
1660    const bool isAA = paint->isAntiAlias();
1661    // We use half the stroke width here because we're going to position the quad
1662    // corner vertices half of the width away from the line endpoints
1663    float halfStrokeWidth = paint->getStrokeWidth() * 0.5f;
1664    // A stroke width of 0 has a special meaning in Skia:
1665    // it draws a line 1 px wide regardless of current transform
1666    bool isHairLine = paint->getStrokeWidth() == 0.0f;
1667    float inverseScaleX = 1.0f;
1668    float inverseScaleY = 1.0f;
1669    bool scaled = false;
1670    int alpha;
1671    SkXfermode::Mode mode;
1672    int generatedVerticesCount = 0;
1673    int verticesCount = count;
1674    if (count > 4) {
1675        // Polyline: account for extra vertices needed for continuous tri-strip
1676        verticesCount += (count - 4);
1677    }
1678
1679    if (isHairLine || isAA) {
1680        // The quad that we use for AA and hairlines needs to account for scaling. For hairlines
1681        // the line on the screen should always be one pixel wide regardless of scale. For
1682        // AA lines, we only want one pixel of translucent boundary around the quad.
1683        if (!mSnapshot->transform->isPureTranslate()) {
1684            Matrix4 *mat = mSnapshot->transform;
1685            float m00 = mat->data[Matrix4::kScaleX];
1686            float m01 = mat->data[Matrix4::kSkewY];
1687            float m02 = mat->data[2];
1688            float m10 = mat->data[Matrix4::kSkewX];
1689            float m11 = mat->data[Matrix4::kScaleX];
1690            float m12 = mat->data[6];
1691            float scaleX = sqrt(m00*m00 + m01*m01);
1692            float scaleY = sqrt(m10*m10 + m11*m11);
1693            inverseScaleX = (scaleX != 0) ? (inverseScaleX / scaleX) : 0;
1694            inverseScaleY = (scaleY != 0) ? (inverseScaleY / scaleY) : 0;
1695            if (inverseScaleX != 1.0f || inverseScaleY != 1.0f) {
1696                scaled = true;
1697            }
1698        }
1699    }
1700
1701    getAlphaAndMode(paint, &alpha, &mode);
1702    setupDraw();
1703    if (isAA) {
1704        setupDrawAALine();
1705    }
1706    setupDrawColor(paint->getColor(), alpha);
1707    setupDrawColorFilter();
1708    setupDrawShader();
1709    if (isAA) {
1710        setupDrawBlending(true, mode);
1711    } else {
1712        setupDrawBlending(mode);
1713    }
1714    setupDrawProgram();
1715    setupDrawModelViewIdentity(true);
1716    setupDrawColorUniforms();
1717    setupDrawColorFilterUniforms();
1718    setupDrawShaderIdentityUniforms();
1719
1720    if (isHairLine) {
1721        // Set a real stroke width to be used in quad construction
1722        halfStrokeWidth = isAA? 1 : .5;
1723    } else if (isAA && !scaled) {
1724        // Expand boundary to enable AA calculations on the quad border
1725        halfStrokeWidth += .5f;
1726    }
1727    Vertex lines[verticesCount];
1728    Vertex* vertices = &lines[0];
1729    AAVertex wLines[verticesCount];
1730    AAVertex* aaVertices = &wLines[0];
1731    if (!isAA) {
1732        setupDrawVertices(vertices);
1733    } else {
1734        void* widthCoords = ((GLbyte*) aaVertices) + gVertexAAWidthOffset;
1735        void* lengthCoords = ((GLbyte*) aaVertices) + gVertexAALengthOffset;
1736        // innerProportion is the ratio of the inner (non-AA) part of the line to the total
1737        // AA stroke width (the base stroke width expanded by a half pixel on either side).
1738        // This value is used in the fragment shader to determine how to fill fragments.
1739        // We will need to calculate the actual width proportion on each segment for
1740        // scaled non-hairlines, since the boundary proportion may differ per-axis when scaled.
1741        float boundaryWidthProportion = 1 / (2 * halfStrokeWidth);
1742        setupDrawAALine((void*) aaVertices, widthCoords, lengthCoords, boundaryWidthProportion);
1743    }
1744
1745    AAVertex* prevAAVertex = NULL;
1746    Vertex* prevVertex = NULL;
1747
1748    int boundaryLengthSlot = -1;
1749    int inverseBoundaryLengthSlot = -1;
1750    int boundaryWidthSlot = -1;
1751    int inverseBoundaryWidthSlot = -1;
1752    for (int i = 0; i < count; i += 4) {
1753        // a = start point, b = end point
1754        vec2 a(points[i], points[i + 1]);
1755        vec2 b(points[i + 2], points[i + 3]);
1756        float length = 0;
1757        float boundaryLengthProportion = 0;
1758        float boundaryWidthProportion = 0;
1759
1760        // Find the normal to the line
1761        vec2 n = (b - a).copyNormalized() * halfStrokeWidth;
1762        if (isHairLine) {
1763            if (isAA) {
1764                float wideningFactor;
1765                if (fabs(n.x) >= fabs(n.y)) {
1766                    wideningFactor = fabs(1.0f / n.x);
1767                } else {
1768                    wideningFactor = fabs(1.0f / n.y);
1769                }
1770                n *= wideningFactor;
1771            }
1772            if (scaled) {
1773                n.x *= inverseScaleX;
1774                n.y *= inverseScaleY;
1775            }
1776        } else if (scaled) {
1777            // Extend n by .5 pixel on each side, post-transform
1778            vec2 extendedN = n.copyNormalized();
1779            extendedN /= 2;
1780            extendedN.x *= inverseScaleX;
1781            extendedN.y *= inverseScaleY;
1782            float extendedNLength = extendedN.length();
1783            // We need to set this value on the shader prior to drawing
1784            boundaryWidthProportion = extendedNLength / (halfStrokeWidth + extendedNLength);
1785            n += extendedN;
1786        }
1787        float x = n.x;
1788        n.x = -n.y;
1789        n.y = x;
1790
1791        // aa lines expand the endpoint vertices to encompass the AA boundary
1792        if (isAA) {
1793            vec2 abVector = (b - a);
1794            length = abVector.length();
1795            abVector.normalize();
1796            if (scaled) {
1797                abVector.x *= inverseScaleX;
1798                abVector.y *= inverseScaleY;
1799                float abLength = abVector.length();
1800                boundaryLengthProportion = abLength / (length + abLength);
1801            } else {
1802                boundaryLengthProportion = .5 / (length + 1);
1803            }
1804            abVector /= 2;
1805            a -= abVector;
1806            b += abVector;
1807        }
1808
1809        // Four corners of the rectangle defining a thick line
1810        vec2 p1 = a - n;
1811        vec2 p2 = a + n;
1812        vec2 p3 = b + n;
1813        vec2 p4 = b - n;
1814
1815
1816        const float left = fmin(p1.x, fmin(p2.x, fmin(p3.x, p4.x)));
1817        const float right = fmax(p1.x, fmax(p2.x, fmax(p3.x, p4.x)));
1818        const float top = fmin(p1.y, fmin(p2.y, fmin(p3.y, p4.y)));
1819        const float bottom = fmax(p1.y, fmax(p2.y, fmax(p3.y, p4.y)));
1820
1821        if (!quickReject(left, top, right, bottom)) {
1822            if (!isAA) {
1823                if (prevVertex != NULL) {
1824                    // Issue two repeat vertices to create degenerate triangles to bridge
1825                    // between the previous line and the new one. This is necessary because
1826                    // we are creating a single triangle_strip which will contain
1827                    // potentially discontinuous line segments.
1828                    Vertex::set(vertices++, prevVertex->position[0], prevVertex->position[1]);
1829                    Vertex::set(vertices++, p1.x, p1.y);
1830                    generatedVerticesCount += 2;
1831                }
1832                Vertex::set(vertices++, p1.x, p1.y);
1833                Vertex::set(vertices++, p2.x, p2.y);
1834                Vertex::set(vertices++, p4.x, p4.y);
1835                Vertex::set(vertices++, p3.x, p3.y);
1836                prevVertex = vertices - 1;
1837                generatedVerticesCount += 4;
1838            } else {
1839                if (!isHairLine && scaled) {
1840                    // Must set width proportions per-segment for scaled non-hairlines to use the
1841                    // correct AA boundary dimensions
1842                    if (boundaryWidthSlot < 0) {
1843                        boundaryWidthSlot =
1844                                mCaches.currentProgram->getUniform("boundaryWidth");
1845                        inverseBoundaryWidthSlot =
1846                                mCaches.currentProgram->getUniform("inverseBoundaryWidth");
1847                    }
1848                    glUniform1f(boundaryWidthSlot, boundaryWidthProportion);
1849                    glUniform1f(inverseBoundaryWidthSlot, (1 / boundaryWidthProportion));
1850                }
1851                if (boundaryLengthSlot < 0) {
1852                    boundaryLengthSlot = mCaches.currentProgram->getUniform("boundaryLength");
1853                    inverseBoundaryLengthSlot =
1854                            mCaches.currentProgram->getUniform("inverseBoundaryLength");
1855                }
1856                glUniform1f(boundaryLengthSlot, boundaryLengthProportion);
1857                glUniform1f(inverseBoundaryLengthSlot, (1 / boundaryLengthProportion));
1858
1859                if (prevAAVertex != NULL) {
1860                    // Issue two repeat vertices to create degenerate triangles to bridge
1861                    // between the previous line and the new one. This is necessary because
1862                    // we are creating a single triangle_strip which will contain
1863                    // potentially discontinuous line segments.
1864                    AAVertex::set(aaVertices++,prevAAVertex->position[0],
1865                            prevAAVertex->position[1], prevAAVertex->width, prevAAVertex->length);
1866                    AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1);
1867                    generatedVerticesCount += 2;
1868                }
1869                AAVertex::set(aaVertices++, p4.x, p4.y, 1, 1);
1870                AAVertex::set(aaVertices++, p1.x, p1.y, 1, 0);
1871                AAVertex::set(aaVertices++, p3.x, p3.y, 0, 1);
1872                AAVertex::set(aaVertices++, p2.x, p2.y, 0, 0);
1873                prevAAVertex = aaVertices - 1;
1874                generatedVerticesCount += 4;
1875            }
1876            dirtyLayer(a.x == b.x ? left - 1 : left, a.y == b.y ? top - 1 : top,
1877                    a.x == b.x ? right: right, a.y == b.y ? bottom: bottom,
1878                    *mSnapshot->transform);
1879        }
1880    }
1881    if (generatedVerticesCount > 0) {
1882       glDrawArrays(GL_TRIANGLE_STRIP, 0, generatedVerticesCount);
1883    }
1884}
1885
1886void OpenGLRenderer::drawPoints(float* points, int count, SkPaint* paint) {
1887    if (mSnapshot->isIgnored()) return;
1888
1889    // TODO: The paint's cap style defines whether the points are square or circular
1890    // TODO: Handle AA for round points
1891
1892    // A stroke width of 0 has a special meaning in Skia:
1893    // it draws an unscaled 1px point
1894    float strokeWidth = paint->getStrokeWidth();
1895    const bool isHairLine = paint->getStrokeWidth() == 0.0f;
1896    if (isHairLine) {
1897        // Now that we know it's hairline, we can set the effective width, to be used later
1898        strokeWidth = 1.0f;
1899    }
1900    const float halfWidth = strokeWidth / 2;
1901    int alpha;
1902    SkXfermode::Mode mode;
1903    getAlphaAndMode(paint, &alpha, &mode);
1904
1905    int verticesCount = count >> 1;
1906    int generatedVerticesCount = 0;
1907
1908    TextureVertex pointsData[verticesCount];
1909    TextureVertex* vertex = &pointsData[0];
1910
1911    setupDraw();
1912    setupDrawPoint(strokeWidth);
1913    setupDrawColor(paint->getColor(), alpha);
1914    setupDrawColorFilter();
1915    setupDrawShader();
1916    setupDrawBlending(mode);
1917    setupDrawProgram();
1918    setupDrawModelViewIdentity(true);
1919    setupDrawColorUniforms();
1920    setupDrawColorFilterUniforms();
1921    setupDrawPointUniforms();
1922    setupDrawShaderIdentityUniforms();
1923    setupDrawMesh(vertex);
1924
1925    for (int i = 0; i < count; i += 2) {
1926        TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f);
1927        generatedVerticesCount++;
1928        float left = points[i] - halfWidth;
1929        float right = points[i] + halfWidth;
1930        float top = points[i + 1] - halfWidth;
1931        float bottom = points [i + 1] + halfWidth;
1932        dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1933    }
1934
1935    glDrawArrays(GL_POINTS, 0, generatedVerticesCount);
1936}
1937
1938void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
1939    // No need to check against the clip, we fill the clip region
1940    if (mSnapshot->isIgnored()) return;
1941
1942    Rect& clip(*mSnapshot->clipRect);
1943    clip.snapToPixelBoundaries();
1944
1945    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
1946}
1947
1948void OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture, SkPaint* paint) {
1949    if (!texture) return;
1950    const AutoTexture autoCleanup(texture);
1951
1952    const float x = left + texture->left - texture->offset;
1953    const float y = top + texture->top - texture->offset;
1954
1955    drawPathTexture(texture, x, y, paint);
1956}
1957
1958void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
1959        float rx, float ry, SkPaint* paint) {
1960    if (mSnapshot->isIgnored()) return;
1961
1962    glActiveTexture(gTextureUnits[0]);
1963    const PathTexture* texture = mCaches.roundRectShapeCache.getRoundRect(
1964            right - left, bottom - top, rx, ry, paint);
1965    drawShape(left, top, texture, paint);
1966}
1967
1968void OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* paint) {
1969    if (mSnapshot->isIgnored()) return;
1970
1971    glActiveTexture(gTextureUnits[0]);
1972    const PathTexture* texture = mCaches.circleShapeCache.getCircle(radius, paint);
1973    drawShape(x - radius, y - radius, texture, paint);
1974}
1975
1976void OpenGLRenderer::drawOval(float left, float top, float right, float bottom, SkPaint* paint) {
1977    if (mSnapshot->isIgnored()) return;
1978
1979    glActiveTexture(gTextureUnits[0]);
1980    const PathTexture* texture = mCaches.ovalShapeCache.getOval(right - left, bottom - top, paint);
1981    drawShape(left, top, texture, paint);
1982}
1983
1984void OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
1985        float startAngle, float sweepAngle, bool useCenter, SkPaint* paint) {
1986    if (mSnapshot->isIgnored()) return;
1987
1988    if (fabs(sweepAngle) >= 360.0f) {
1989        drawOval(left, top, right, bottom, paint);
1990        return;
1991    }
1992
1993    glActiveTexture(gTextureUnits[0]);
1994    const PathTexture* texture = mCaches.arcShapeCache.getArc(right - left, bottom - top,
1995            startAngle, sweepAngle, useCenter, paint);
1996    drawShape(left, top, texture, paint);
1997}
1998
1999void OpenGLRenderer::drawRectAsShape(float left, float top, float right, float bottom,
2000        SkPaint* paint) {
2001    if (mSnapshot->isIgnored()) return;
2002
2003    glActiveTexture(gTextureUnits[0]);
2004    const PathTexture* texture = mCaches.rectShapeCache.getRect(right - left, bottom - top, paint);
2005    drawShape(left, top, texture, paint);
2006}
2007
2008void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
2009    if (p->getStyle() != SkPaint::kFill_Style) {
2010        drawRectAsShape(left, top, right, bottom, p);
2011        return;
2012    }
2013
2014    if (quickReject(left, top, right, bottom)) {
2015        return;
2016    }
2017
2018    SkXfermode::Mode mode;
2019    if (!mCaches.extensions.hasFramebufferFetch()) {
2020        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
2021        if (!isMode) {
2022            // Assume SRC_OVER
2023            mode = SkXfermode::kSrcOver_Mode;
2024        }
2025    } else {
2026        mode = getXfermode(p->getXfermode());
2027    }
2028
2029    int color = p->getColor();
2030    if (p->isAntiAlias() && !mSnapshot->transform->isSimple()) {
2031        drawAARect(left, top, right, bottom, color, mode);
2032    } else {
2033        drawColorRect(left, top, right, bottom, color, mode);
2034    }
2035}
2036
2037void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
2038        float x, float y, SkPaint* paint) {
2039    if (text == NULL || count == 0) {
2040        return;
2041    }
2042    if (mSnapshot->isIgnored()) return;
2043
2044    // TODO: We should probably make a copy of the paint instead of modifying
2045    //       it; modifying the paint will change its generationID the first
2046    //       time, which might impact caches. More investigation needed to
2047    //       see if it matters.
2048    //       If we make a copy, then drawTextDecorations() should *not* make
2049    //       its own copy as it does right now.
2050    paint->setAntiAlias(true);
2051#if RENDER_TEXT_AS_GLYPHS
2052    paint->setTextEncoding(SkPaint::kGlyphID_TextEncoding);
2053#endif
2054
2055    float length = -1.0f;
2056    switch (paint->getTextAlign()) {
2057        case SkPaint::kCenter_Align:
2058            length = paint->measureText(text, bytesCount);
2059            x -= length / 2.0f;
2060            break;
2061        case SkPaint::kRight_Align:
2062            length = paint->measureText(text, bytesCount);
2063            x -= length;
2064            break;
2065        default:
2066            break;
2067    }
2068
2069    const float oldX = x;
2070    const float oldY = y;
2071    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
2072    if (pureTranslate) {
2073        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2074        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2075    }
2076
2077    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
2078    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
2079            paint->getTextSize());
2080
2081    int alpha;
2082    SkXfermode::Mode mode;
2083    getAlphaAndMode(paint, &alpha, &mode);
2084
2085    if (mHasShadow) {
2086        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
2087        const ShadowTexture* shadow = mCaches.dropShadowCache.get(
2088                paint, text, bytesCount, count, mShadowRadius);
2089        const AutoTexture autoCleanup(shadow);
2090
2091        const float sx = oldX - shadow->left + mShadowDx;
2092        const float sy = oldY - shadow->top + mShadowDy;
2093
2094        const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
2095        int shadowColor = mShadowColor;
2096        if (mShader) {
2097            shadowColor = 0xffffffff;
2098        }
2099
2100        glActiveTexture(gTextureUnits[0]);
2101        setupDraw();
2102        setupDrawWithTexture(true);
2103        setupDrawAlpha8Color(shadowColor, shadowAlpha < 255 ? shadowAlpha : alpha);
2104        setupDrawColorFilter();
2105        setupDrawShader();
2106        setupDrawBlending(true, mode);
2107        setupDrawProgram();
2108        setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height);
2109        setupDrawTexture(shadow->id);
2110        setupDrawPureColorUniforms();
2111        setupDrawColorFilterUniforms();
2112        setupDrawShaderUniforms();
2113        setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2114
2115        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2116
2117        finishDrawTexture();
2118    }
2119
2120    if (paint->getAlpha() == 0 && paint->getXfermode() == NULL) {
2121        return;
2122    }
2123
2124    // Pick the appropriate texture filtering
2125    bool linearFilter = mSnapshot->transform->changesBounds();
2126    if (pureTranslate && !linearFilter) {
2127        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2128    }
2129
2130    glActiveTexture(gTextureUnits[0]);
2131    setupDraw();
2132    setupDrawDirtyRegionsDisabled();
2133    setupDrawWithTexture(true);
2134    setupDrawAlpha8Color(paint->getColor(), alpha);
2135    setupDrawColorFilter();
2136    setupDrawShader();
2137    setupDrawBlending(true, mode);
2138    setupDrawProgram();
2139    setupDrawModelView(x, y, x, y, pureTranslate, true);
2140    setupDrawTexture(fontRenderer.getTexture(linearFilter));
2141    setupDrawPureColorUniforms();
2142    setupDrawColorFilterUniforms();
2143    setupDrawShaderUniforms(pureTranslate);
2144
2145    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
2146    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2147
2148#if RENDER_LAYERS_AS_REGIONS
2149    bool hasActiveLayer = hasLayer();
2150#else
2151    bool hasActiveLayer = false;
2152#endif
2153    mCaches.unbindMeshBuffer();
2154
2155    // Tell font renderer the locations of position and texture coord
2156    // attributes so it can bind its data properly
2157    int positionSlot = mCaches.currentProgram->position;
2158    fontRenderer.setAttributeBindingSlots(positionSlot, mTexCoordsSlot);
2159    if (fontRenderer.renderText(paint, clip, text, 0, bytesCount, count, x, y,
2160            hasActiveLayer ? &bounds : NULL)) {
2161#if RENDER_LAYERS_AS_REGIONS
2162        if (hasActiveLayer) {
2163            if (!pureTranslate) {
2164                mSnapshot->transform->mapRect(bounds);
2165            }
2166            dirtyLayerUnchecked(bounds, getRegion());
2167        }
2168#endif
2169    }
2170
2171    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
2172    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
2173
2174    drawTextDecorations(text, bytesCount, length, oldX, oldY, paint);
2175}
2176
2177void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
2178    if (mSnapshot->isIgnored()) return;
2179
2180    glActiveTexture(gTextureUnits[0]);
2181
2182    const PathTexture* texture = mCaches.pathCache.get(path, paint);
2183    if (!texture) return;
2184    const AutoTexture autoCleanup(texture);
2185
2186    const float x = texture->left - texture->offset;
2187    const float y = texture->top - texture->offset;
2188
2189    drawPathTexture(texture, x, y, paint);
2190}
2191
2192void OpenGLRenderer::drawLayer(Layer* layer, float x, float y, SkPaint* paint) {
2193    if (!layer || quickReject(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight())) {
2194        return;
2195    }
2196
2197    glActiveTexture(gTextureUnits[0]);
2198
2199    int alpha;
2200    SkXfermode::Mode mode;
2201    getAlphaAndMode(paint, &alpha, &mode);
2202
2203    layer->setAlpha(alpha, mode);
2204
2205#if RENDER_LAYERS_AS_REGIONS
2206    if (!layer->region.isEmpty()) {
2207        if (layer->region.isRect()) {
2208            composeLayerRect(layer, layer->regionRect);
2209        } else if (layer->mesh) {
2210            const float a = alpha / 255.0f;
2211            const Rect& rect = layer->layer;
2212
2213            setupDraw();
2214            setupDrawWithTexture();
2215            setupDrawColor(a, a, a, a);
2216            setupDrawColorFilter();
2217            setupDrawBlending(layer->isBlend() || a < 1.0f, layer->getMode(), false);
2218            setupDrawProgram();
2219            setupDrawPureColorUniforms();
2220            setupDrawColorFilterUniforms();
2221            setupDrawTexture(layer->getTexture());
2222            if (mSnapshot->transform->isPureTranslate()) {
2223                x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
2224                y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
2225
2226                layer->setFilter(GL_NEAREST, GL_NEAREST);
2227                setupDrawModelViewTranslate(x, y,
2228                        x + layer->layer.getWidth(), y + layer->layer.getHeight(), true);
2229            } else {
2230                layer->setFilter(GL_LINEAR, GL_LINEAR);
2231                setupDrawModelViewTranslate(x, y,
2232                        x + layer->layer.getWidth(), y + layer->layer.getHeight());
2233            }
2234            setupDrawMesh(&layer->mesh[0].position[0], &layer->mesh[0].texture[0]);
2235
2236            glDrawElements(GL_TRIANGLES, layer->meshElementCount,
2237                    GL_UNSIGNED_SHORT, layer->meshIndices);
2238
2239            finishDrawTexture();
2240
2241#if DEBUG_LAYERS_AS_REGIONS
2242            drawRegionRects(layer->region);
2243#endif
2244        }
2245    }
2246#else
2247    const Rect r(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight());
2248    composeLayerRect(layer, r);
2249#endif
2250}
2251
2252///////////////////////////////////////////////////////////////////////////////
2253// Shaders
2254///////////////////////////////////////////////////////////////////////////////
2255
2256void OpenGLRenderer::resetShader() {
2257    mShader = NULL;
2258}
2259
2260void OpenGLRenderer::setupShader(SkiaShader* shader) {
2261    mShader = shader;
2262    if (mShader) {
2263        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
2264    }
2265}
2266
2267///////////////////////////////////////////////////////////////////////////////
2268// Color filters
2269///////////////////////////////////////////////////////////////////////////////
2270
2271void OpenGLRenderer::resetColorFilter() {
2272    mColorFilter = NULL;
2273}
2274
2275void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
2276    mColorFilter = filter;
2277}
2278
2279///////////////////////////////////////////////////////////////////////////////
2280// Drop shadow
2281///////////////////////////////////////////////////////////////////////////////
2282
2283void OpenGLRenderer::resetShadow() {
2284    mHasShadow = false;
2285}
2286
2287void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
2288    mHasShadow = true;
2289    mShadowRadius = radius;
2290    mShadowDx = dx;
2291    mShadowDy = dy;
2292    mShadowColor = color;
2293}
2294
2295///////////////////////////////////////////////////////////////////////////////
2296// Drawing implementation
2297///////////////////////////////////////////////////////////////////////////////
2298
2299void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
2300        float x, float y, SkPaint* paint) {
2301    if (quickReject(x, y, x + texture->width, y + texture->height)) {
2302        return;
2303    }
2304
2305    int alpha;
2306    SkXfermode::Mode mode;
2307    getAlphaAndMode(paint, &alpha, &mode);
2308
2309    setupDraw();
2310    setupDrawWithTexture(true);
2311    setupDrawAlpha8Color(paint->getColor(), alpha);
2312    setupDrawColorFilter();
2313    setupDrawShader();
2314    setupDrawBlending(true, mode);
2315    setupDrawProgram();
2316    setupDrawModelView(x, y, x + texture->width, y + texture->height);
2317    setupDrawTexture(texture->id);
2318    setupDrawPureColorUniforms();
2319    setupDrawColorFilterUniforms();
2320    setupDrawShaderUniforms();
2321    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2322
2323    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2324
2325    finishDrawTexture();
2326}
2327
2328// Same values used by Skia
2329#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
2330#define kStdUnderline_Offset    (1.0f / 9.0f)
2331#define kStdUnderline_Thickness (1.0f / 18.0f)
2332
2333void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
2334        float x, float y, SkPaint* paint) {
2335    // Handle underline and strike-through
2336    uint32_t flags = paint->getFlags();
2337    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
2338        SkPaint paintCopy(*paint);
2339        float underlineWidth = length;
2340        // If length is > 0.0f, we already measured the text for the text alignment
2341        if (length <= 0.0f) {
2342            underlineWidth = paintCopy.measureText(text, bytesCount);
2343        }
2344
2345        float offsetX = 0;
2346        switch (paintCopy.getTextAlign()) {
2347            case SkPaint::kCenter_Align:
2348                offsetX = underlineWidth * 0.5f;
2349                break;
2350            case SkPaint::kRight_Align:
2351                offsetX = underlineWidth;
2352                break;
2353            default:
2354                break;
2355        }
2356
2357        if (underlineWidth > 0.0f) {
2358            const float textSize = paintCopy.getTextSize();
2359            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
2360
2361            const float left = x - offsetX;
2362            float top = 0.0f;
2363
2364            int linesCount = 0;
2365            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
2366            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
2367
2368            const int pointsCount = 4 * linesCount;
2369            float points[pointsCount];
2370            int currentPoint = 0;
2371
2372            if (flags & SkPaint::kUnderlineText_Flag) {
2373                top = y + textSize * kStdUnderline_Offset;
2374                points[currentPoint++] = left;
2375                points[currentPoint++] = top;
2376                points[currentPoint++] = left + underlineWidth;
2377                points[currentPoint++] = top;
2378            }
2379
2380            if (flags & SkPaint::kStrikeThruText_Flag) {
2381                top = y + textSize * kStdStrikeThru_Offset;
2382                points[currentPoint++] = left;
2383                points[currentPoint++] = top;
2384                points[currentPoint++] = left + underlineWidth;
2385                points[currentPoint++] = top;
2386            }
2387
2388            paintCopy.setStrokeWidth(strokeWidth);
2389
2390            drawLines(&points[0], pointsCount, &paintCopy);
2391        }
2392    }
2393}
2394
2395void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
2396        int color, SkXfermode::Mode mode, bool ignoreTransform) {
2397    // If a shader is set, preserve only the alpha
2398    if (mShader) {
2399        color |= 0x00ffffff;
2400    }
2401
2402    setupDraw();
2403    setupDrawColor(color);
2404    setupDrawShader();
2405    setupDrawColorFilter();
2406    setupDrawBlending(mode);
2407    setupDrawProgram();
2408    setupDrawModelView(left, top, right, bottom, ignoreTransform);
2409    setupDrawColorUniforms();
2410    setupDrawShaderUniforms(ignoreTransform);
2411    setupDrawColorFilterUniforms();
2412    setupDrawSimpleMesh();
2413
2414    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2415}
2416
2417void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
2418        Texture* texture, SkPaint* paint) {
2419    int alpha;
2420    SkXfermode::Mode mode;
2421    getAlphaAndMode(paint, &alpha, &mode);
2422
2423    texture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, true);
2424
2425    if (mSnapshot->transform->isPureTranslate()) {
2426        const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
2427        const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
2428
2429        texture->setFilter(GL_NEAREST, GL_NEAREST, true);
2430        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
2431                alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL,
2432                (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true);
2433    } else {
2434        texture->setFilter(GL_LINEAR, GL_LINEAR, true);
2435        drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
2436                texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
2437                GL_TRIANGLE_STRIP, gMeshCount);
2438    }
2439}
2440
2441void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
2442        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
2443    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
2444            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
2445}
2446
2447void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
2448        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
2449        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
2450        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
2451
2452    setupDraw();
2453    setupDrawWithTexture();
2454    setupDrawColor(alpha, alpha, alpha, alpha);
2455    setupDrawColorFilter();
2456    setupDrawBlending(blend, mode, swapSrcDst);
2457    setupDrawProgram();
2458    if (!dirty) {
2459        setupDrawDirtyRegionsDisabled();
2460    }
2461    if (!ignoreScale) {
2462        setupDrawModelView(left, top, right, bottom, ignoreTransform);
2463    } else {
2464        setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
2465    }
2466    setupDrawPureColorUniforms();
2467    setupDrawColorFilterUniforms();
2468    setupDrawTexture(texture);
2469    setupDrawMesh(vertices, texCoords, vbo);
2470
2471    glDrawArrays(drawMode, 0, elementsCount);
2472
2473    finishDrawTexture();
2474}
2475
2476void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
2477        ProgramDescription& description, bool swapSrcDst) {
2478    blend = blend || mode != SkXfermode::kSrcOver_Mode;
2479    if (blend) {
2480        if (mode < SkXfermode::kPlus_Mode) {
2481            if (!mCaches.blend) {
2482                glEnable(GL_BLEND);
2483            }
2484
2485            GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
2486            GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
2487
2488            if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
2489                glBlendFunc(sourceMode, destMode);
2490                mCaches.lastSrcMode = sourceMode;
2491                mCaches.lastDstMode = destMode;
2492            }
2493        } else {
2494            // These blend modes are not supported by OpenGL directly and have
2495            // to be implemented using shaders. Since the shader will perform
2496            // the blending, turn blending off here
2497            if (mCaches.extensions.hasFramebufferFetch()) {
2498                description.framebufferMode = mode;
2499                description.swapSrcDst = swapSrcDst;
2500            }
2501
2502            if (mCaches.blend) {
2503                glDisable(GL_BLEND);
2504            }
2505            blend = false;
2506        }
2507    } else if (mCaches.blend) {
2508        glDisable(GL_BLEND);
2509    }
2510    mCaches.blend = blend;
2511}
2512
2513bool OpenGLRenderer::useProgram(Program* program) {
2514    if (!program->isInUse()) {
2515        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
2516        program->use();
2517        mCaches.currentProgram = program;
2518        return false;
2519    }
2520    return true;
2521}
2522
2523void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
2524    TextureVertex* v = &mMeshVertices[0];
2525    TextureVertex::setUV(v++, u1, v1);
2526    TextureVertex::setUV(v++, u2, v1);
2527    TextureVertex::setUV(v++, u1, v2);
2528    TextureVertex::setUV(v++, u2, v2);
2529}
2530
2531void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
2532    if (paint) {
2533        if (!mCaches.extensions.hasFramebufferFetch()) {
2534            const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
2535            if (!isMode) {
2536                // Assume SRC_OVER
2537                *mode = SkXfermode::kSrcOver_Mode;
2538            }
2539        } else {
2540            *mode = getXfermode(paint->getXfermode());
2541        }
2542
2543        // Skia draws using the color's alpha channel if < 255
2544        // Otherwise, it uses the paint's alpha
2545        int color = paint->getColor();
2546        *alpha = (color >> 24) & 0xFF;
2547        if (*alpha == 255) {
2548            *alpha = paint->getAlpha();
2549        }
2550    } else {
2551        *mode = SkXfermode::kSrcOver_Mode;
2552        *alpha = 255;
2553    }
2554}
2555
2556SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
2557    SkXfermode::Mode resultMode;
2558    if (!SkXfermode::AsMode(mode, &resultMode)) {
2559        resultMode = SkXfermode::kSrcOver_Mode;
2560    }
2561    return resultMode;
2562}
2563
2564}; // namespace uirenderer
2565}; // namespace android
2566