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