OpenGLRenderer.cpp revision 8d2959ddffcdee8b0c2f6387f2e2772c6df474ae
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 <ui/Rect.h>
30
31#include "OpenGLRenderer.h"
32#include "DisplayListRenderer.h"
33#include "Vector.h"
34
35namespace android {
36namespace uirenderer {
37
38///////////////////////////////////////////////////////////////////////////////
39// Defines
40///////////////////////////////////////////////////////////////////////////////
41
42#define RAD_TO_DEG (180.0f / 3.14159265f)
43#define MIN_ANGLE 0.001f
44
45// TODO: This should be set in properties
46#define ALPHA_THRESHOLD (0x7f / PANEL_BIT_DEPTH)
47
48///////////////////////////////////////////////////////////////////////////////
49// Globals
50///////////////////////////////////////////////////////////////////////////////
51
52/**
53 * Structure mapping Skia xfermodes to OpenGL blending factors.
54 */
55struct Blender {
56    SkXfermode::Mode mode;
57    GLenum src;
58    GLenum dst;
59}; // struct Blender
60
61// In this array, the index of each Blender equals the value of the first
62// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
63static const Blender gBlends[] = {
64    { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
65    { SkXfermode::kSrc_Mode,     GL_ONE,                  GL_ZERO },
66    { SkXfermode::kDst_Mode,     GL_ZERO,                 GL_ONE },
67    { SkXfermode::kSrcOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
68    { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
69    { SkXfermode::kSrcIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
70    { SkXfermode::kDstIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
71    { SkXfermode::kSrcOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
72    { SkXfermode::kDstOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
73    { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
74    { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
75    { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
76};
77
78// This array contains the swapped version of each SkXfermode. For instance
79// this array's SrcOver blending mode is actually DstOver. You can refer to
80// createLayer() for more information on the purpose of this array.
81static const Blender gBlendsSwap[] = {
82    { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
83    { SkXfermode::kSrc_Mode,     GL_ZERO,                 GL_ONE },
84    { SkXfermode::kDst_Mode,     GL_ONE,                  GL_ZERO },
85    { SkXfermode::kSrcOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
86    { SkXfermode::kDstOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
87    { SkXfermode::kSrcIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
88    { SkXfermode::kDstIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
89    { SkXfermode::kSrcOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
90    { SkXfermode::kDstOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
91    { SkXfermode::kSrcATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
92    { SkXfermode::kDstATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
93    { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
94};
95
96static const GLenum gTextureUnits[] = {
97    GL_TEXTURE0,
98    GL_TEXTURE1,
99    GL_TEXTURE2
100};
101
102///////////////////////////////////////////////////////////////////////////////
103// Constructors/destructor
104///////////////////////////////////////////////////////////////////////////////
105
106OpenGLRenderer::OpenGLRenderer(): mCaches(Caches::getInstance()) {
107    mShader = NULL;
108    mColorFilter = NULL;
109    mHasShadow = false;
110
111    memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices));
112
113    mFirstSnapshot = new Snapshot;
114}
115
116OpenGLRenderer::~OpenGLRenderer() {
117    // The context has already been destroyed at this point, do not call
118    // GL APIs. All GL state should be kept in Caches.h
119}
120
121///////////////////////////////////////////////////////////////////////////////
122// Setup
123///////////////////////////////////////////////////////////////////////////////
124
125void OpenGLRenderer::setViewport(int width, int height) {
126    glViewport(0, 0, width, height);
127    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
128
129    mWidth = width;
130    mHeight = height;
131
132    mFirstSnapshot->height = height;
133    mFirstSnapshot->viewport.set(0, 0, width, height);
134
135    mDirtyClip = false;
136}
137
138void OpenGLRenderer::prepare(bool opaque) {
139    prepareDirty(0.0f, 0.0f, mWidth, mHeight, opaque);
140}
141
142void OpenGLRenderer::prepareDirty(float left, float top, float right, float bottom, bool opaque) {
143    mCaches.clearGarbage();
144
145    mSnapshot = new Snapshot(mFirstSnapshot,
146            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
147    mSaveCount = 1;
148
149    glViewport(0, 0, mWidth, mHeight);
150
151    glDisable(GL_DITHER);
152
153    glEnable(GL_SCISSOR_TEST);
154    glScissor(left, mSnapshot->height - bottom, right - left, bottom - top);
155    mSnapshot->setClip(left, top, right, bottom);
156
157    if (!opaque) {
158        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
159        glClear(GL_COLOR_BUFFER_BIT);
160    }
161}
162
163void OpenGLRenderer::finish() {
164#if DEBUG_OPENGL
165    GLenum status = GL_NO_ERROR;
166    while ((status = glGetError()) != GL_NO_ERROR) {
167        LOGD("GL error from OpenGLRenderer: 0x%x", status);
168        switch (status) {
169            case GL_OUT_OF_MEMORY:
170                LOGE("  OpenGLRenderer is out of memory!");
171                break;
172        }
173    }
174#endif
175#if DEBUG_MEMORY_USAGE
176    mCaches.dumpMemoryUsage();
177#else
178    if (mCaches.getDebugLevel() & kDebugMemory) {
179        mCaches.dumpMemoryUsage();
180    }
181#endif
182}
183
184void OpenGLRenderer::interrupt() {
185    if (mCaches.currentProgram) {
186        if (mCaches.currentProgram->isInUse()) {
187            mCaches.currentProgram->remove();
188            mCaches.currentProgram = NULL;
189        }
190    }
191    mCaches.unbindMeshBuffer();
192}
193
194void OpenGLRenderer::acquireContext() {
195    interrupt();
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
215void OpenGLRenderer::releaseContext() {
216    resume();
217}
218
219bool OpenGLRenderer::callDrawGLFunction(Functor *functor) {
220    interrupt();
221    status_t result = (*functor)();
222    resume();
223    return (result == 0) ? false : true;
224}
225
226///////////////////////////////////////////////////////////////////////////////
227// State management
228///////////////////////////////////////////////////////////////////////////////
229
230int OpenGLRenderer::getSaveCount() const {
231    return mSaveCount;
232}
233
234int OpenGLRenderer::save(int flags) {
235    return saveSnapshot(flags);
236}
237
238void OpenGLRenderer::restore() {
239    if (mSaveCount > 1) {
240        restoreSnapshot();
241    }
242}
243
244void OpenGLRenderer::restoreToCount(int saveCount) {
245    if (saveCount < 1) saveCount = 1;
246
247    while (mSaveCount > saveCount) {
248        restoreSnapshot();
249    }
250}
251
252int OpenGLRenderer::saveSnapshot(int flags) {
253    mSnapshot = new Snapshot(mSnapshot, flags);
254    return mSaveCount++;
255}
256
257bool OpenGLRenderer::restoreSnapshot() {
258    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
259    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
260    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
261
262    sp<Snapshot> current = mSnapshot;
263    sp<Snapshot> previous = mSnapshot->previous;
264
265    if (restoreOrtho) {
266        Rect& r = previous->viewport;
267        glViewport(r.left, r.top, r.right, r.bottom);
268        mOrthoMatrix.load(current->orthoMatrix);
269    }
270
271    mSaveCount--;
272    mSnapshot = previous;
273
274    if (restoreClip) {
275        dirtyClip();
276    }
277
278    if (restoreLayer) {
279        composeLayer(current, previous);
280    }
281
282    return restoreClip;
283}
284
285///////////////////////////////////////////////////////////////////////////////
286// Layers
287///////////////////////////////////////////////////////////////////////////////
288
289int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
290        SkPaint* p, int flags) {
291    const GLuint previousFbo = mSnapshot->fbo;
292    const int count = saveSnapshot(flags);
293
294    if (!mSnapshot->isIgnored()) {
295        int alpha = 255;
296        SkXfermode::Mode mode;
297
298        if (p) {
299            alpha = p->getAlpha();
300            if (!mCaches.extensions.hasFramebufferFetch()) {
301                const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
302                if (!isMode) {
303                    // Assume SRC_OVER
304                    mode = SkXfermode::kSrcOver_Mode;
305                }
306            } else {
307                mode = getXfermode(p->getXfermode());
308            }
309        } else {
310            mode = SkXfermode::kSrcOver_Mode;
311        }
312
313        createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags, previousFbo);
314    }
315
316    return count;
317}
318
319int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
320        int alpha, int flags) {
321    if (alpha >= 255 - ALPHA_THRESHOLD) {
322        return saveLayer(left, top, right, bottom, NULL, flags);
323    } else {
324        SkPaint paint;
325        paint.setAlpha(alpha);
326        return saveLayer(left, top, right, bottom, &paint, flags);
327    }
328}
329
330/**
331 * Layers are viewed by Skia are slightly different than layers in image editing
332 * programs (for instance.) When a layer is created, previously created layers
333 * and the frame buffer still receive every drawing command. For instance, if a
334 * layer is created and a shape intersecting the bounds of the layers and the
335 * framebuffer is draw, the shape will be drawn on both (unless the layer was
336 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
337 *
338 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
339 * texture. Unfortunately, this is inefficient as it requires every primitive to
340 * be drawn n + 1 times, where n is the number of active layers. In practice this
341 * means, for every primitive:
342 *   - Switch active frame buffer
343 *   - Change viewport, clip and projection matrix
344 *   - Issue the drawing
345 *
346 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
347 * To avoid this, layers are implemented in a different way here, at least in the
348 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
349 * is set. When this flag is set we can redirect all drawing operations into a
350 * single FBO.
351 *
352 * This implementation relies on the frame buffer being at least RGBA 8888. When
353 * a layer is created, only a texture is created, not an FBO. The content of the
354 * frame buffer contained within the layer's bounds is copied into this texture
355 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
356 * buffer and drawing continues as normal. This technique therefore treats the
357 * frame buffer as a scratch buffer for the layers.
358 *
359 * To compose the layers back onto the frame buffer, each layer texture
360 * (containing the original frame buffer data) is drawn as a simple quad over
361 * the frame buffer. The trick is that the quad is set as the composition
362 * destination in the blending equation, and the frame buffer becomes the source
363 * of the composition.
364 *
365 * Drawing layers with an alpha value requires an extra step before composition.
366 * An empty quad is drawn over the layer's region in the frame buffer. This quad
367 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
368 * quad is used to multiply the colors in the frame buffer. This is achieved by
369 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
370 * GL_ZERO, GL_SRC_ALPHA.
371 *
372 * Because glCopyTexImage2D() can be slow, an alternative implementation might
373 * be use to draw a single clipped layer. The implementation described above
374 * is correct in every case.
375 *
376 * (1) The frame buffer is actually not cleared right away. To allow the GPU
377 *     to potentially optimize series of calls to glCopyTexImage2D, the frame
378 *     buffer is left untouched until the first drawing operation. Only when
379 *     something actually gets drawn are the layers regions cleared.
380 */
381bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
382        float right, float bottom, int alpha, SkXfermode::Mode mode,
383        int flags, GLuint previousFbo) {
384    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
385    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
386
387    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
388
389    // Window coordinates of the layer
390    Rect bounds(left, top, right, bottom);
391    if (fboLayer) {
392        // Clear the previous layer regions before we change the viewport
393        clearLayerRegions();
394    } else {
395        mSnapshot->transform->mapRect(bounds);
396
397        // Layers only make sense if they are in the framebuffer's bounds
398        bounds.intersect(*snapshot->clipRect);
399
400        // We cannot work with sub-pixels in this case
401        bounds.snapToPixelBoundaries();
402
403        // When the layer is not an FBO, we may use glCopyTexImage so we
404        // need to make sure the layer does not extend outside the bounds
405        // of the framebuffer
406        bounds.intersect(snapshot->previous->viewport);
407    }
408
409    if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize ||
410            bounds.getHeight() > mCaches.maxTextureSize) {
411        snapshot->empty = fboLayer;
412    } else {
413        snapshot->invisible = snapshot->invisible || (alpha <= ALPHA_THRESHOLD && fboLayer);
414    }
415
416    // Bail out if we won't draw in this snapshot
417    if (snapshot->invisible || snapshot->empty) {
418        return false;
419    }
420
421    glActiveTexture(gTextureUnits[0]);
422    Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight());
423    if (!layer) {
424        return false;
425    }
426
427    layer->mode = mode;
428    layer->alpha = alpha;
429    layer->layer.set(bounds);
430    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->height),
431            bounds.getWidth() / float(layer->width), 0.0f);
432    layer->colorFilter = mColorFilter;
433
434    // Save the layer in the snapshot
435    snapshot->flags |= Snapshot::kFlagIsLayer;
436    snapshot->layer = layer;
437
438    if (fboLayer) {
439        return createFboLayer(layer, bounds, snapshot, previousFbo);
440    } else {
441        // Copy the framebuffer into the layer
442        glBindTexture(GL_TEXTURE_2D, layer->texture);
443        if (!bounds.isEmpty()) {
444            if (layer->empty) {
445                glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.left,
446                        snapshot->height - bounds.bottom, layer->width, layer->height, 0);
447                layer->empty = false;
448            } else {
449                glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left,
450                        snapshot->height - bounds.bottom, bounds.getWidth(), bounds.getHeight());
451            }
452            // Enqueue the buffer coordinates to clear the corresponding region later
453            mLayers.push(new Rect(bounds));
454        }
455    }
456
457    return true;
458}
459
460bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, sp<Snapshot> snapshot,
461        GLuint previousFbo) {
462    layer->fbo = mCaches.fboCache.get();
463
464#if RENDER_LAYERS_AS_REGIONS
465    snapshot->region = &snapshot->layer->region;
466    snapshot->flags |= Snapshot::kFlagFboTarget;
467#endif
468
469    Rect clip(bounds);
470    snapshot->transform->mapRect(clip);
471    clip.intersect(*snapshot->clipRect);
472    clip.snapToPixelBoundaries();
473    clip.intersect(snapshot->previous->viewport);
474
475    mat4 inverse;
476    inverse.loadInverse(*mSnapshot->transform);
477
478    inverse.mapRect(clip);
479    clip.snapToPixelBoundaries();
480    clip.intersect(bounds);
481    clip.translate(-bounds.left, -bounds.top);
482
483    snapshot->flags |= Snapshot::kFlagIsFboLayer;
484    snapshot->fbo = layer->fbo;
485    snapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
486    snapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom);
487    snapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
488    snapshot->height = bounds.getHeight();
489    snapshot->flags |= Snapshot::kFlagDirtyOrtho;
490    snapshot->orthoMatrix.load(mOrthoMatrix);
491
492    // Bind texture to FBO
493    glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo);
494    glBindTexture(GL_TEXTURE_2D, layer->texture);
495
496    // Initialize the texture if needed
497    if (layer->empty) {
498        layer->empty = false;
499        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->width, layer->height, 0,
500                GL_RGBA, GL_UNSIGNED_BYTE, NULL);
501    }
502
503    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
504            layer->texture, 0);
505
506#if DEBUG_LAYERS_AS_REGIONS
507    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
508    if (status != GL_FRAMEBUFFER_COMPLETE) {
509        LOGE("Framebuffer incomplete (GL error code 0x%x)", status);
510
511        glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
512        glDeleteTextures(1, &layer->texture);
513        mCaches.fboCache.put(layer->fbo);
514
515        delete layer;
516
517        return false;
518    }
519#endif
520
521    // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
522    glScissor(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
523            clip.getWidth() + 2.0f, clip.getHeight() + 2.0f);
524    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
525    glClear(GL_COLOR_BUFFER_BIT);
526
527    dirtyClip();
528
529    // Change the ortho projection
530    glViewport(0, 0, bounds.getWidth(), bounds.getHeight());
531    mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f);
532
533    return true;
534}
535
536/**
537 * Read the documentation of createLayer() before doing anything in this method.
538 */
539void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
540    if (!current->layer) {
541        LOGE("Attempting to compose a layer that does not exist");
542        return;
543    }
544
545    const bool fboLayer = current->flags & Snapshot::kFlagIsFboLayer;
546
547    if (fboLayer) {
548        // Unbind current FBO and restore previous one
549        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
550    }
551
552    Layer* layer = current->layer;
553    const Rect& rect = layer->layer;
554
555    if (!fboLayer && layer->alpha < 255) {
556        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
557                layer->alpha << 24, SkXfermode::kDstIn_Mode, true);
558        // Required below, composeLayerRect() will divide by 255
559        layer->alpha = 255;
560    }
561
562    mCaches.unbindMeshBuffer();
563
564    glActiveTexture(gTextureUnits[0]);
565
566    // When the layer is stored in an FBO, we can save a bit of fillrate by
567    // drawing only the dirty region
568    if (fboLayer) {
569        dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *previous->transform);
570        if (layer->colorFilter) {
571            setupColorFilter(layer->colorFilter);
572        }
573        composeLayerRegion(layer, rect);
574        if (layer->colorFilter) {
575            resetColorFilter();
576        }
577    } else {
578        if (!rect.isEmpty()) {
579            dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
580            composeLayerRect(layer, rect, true);
581        }
582    }
583
584    if (fboLayer) {
585        // Detach the texture from the FBO
586        glBindFramebuffer(GL_FRAMEBUFFER, current->fbo);
587        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
588        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
589
590        // Put the FBO name back in the cache, if it doesn't fit, it will be destroyed
591        mCaches.fboCache.put(current->fbo);
592    }
593
594    dirtyClip();
595
596    // Failing to add the layer to the cache should happen only if the layer is too large
597    if (!mCaches.layerCache.put(layer)) {
598        LAYER_LOGD("Deleting layer");
599        glDeleteTextures(1, &layer->texture);
600        delete layer;
601    }
602}
603
604void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
605    const Rect& texCoords = layer->texCoords;
606    resetDrawTextureTexCoords(texCoords.left, texCoords.top, texCoords.right, texCoords.bottom);
607
608    drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture,
609            layer->alpha / 255.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0],
610            &mMeshVertices[0].texture[0], GL_TRIANGLE_STRIP, gMeshCount, swap, swap);
611
612    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
613}
614
615void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
616#if RENDER_LAYERS_AS_REGIONS
617    if (layer->region.isRect()) {
618        composeLayerRect(layer, rect);
619        layer->region.clear();
620        return;
621    }
622
623    if (!layer->region.isEmpty()) {
624        size_t count;
625        const android::Rect* rects = layer->region.getArray(&count);
626
627        const float alpha = layer->alpha / 255.0f;
628        const float texX = 1.0f / float(layer->width);
629        const float texY = 1.0f / float(layer->height);
630        const float height = rect.getHeight();
631
632        TextureVertex* mesh = mCaches.getRegionMesh();
633        GLsizei numQuads = 0;
634
635        setupDraw();
636        setupDrawWithTexture();
637        setupDrawColor(alpha, alpha, alpha, alpha);
638        setupDrawColorFilter();
639        setupDrawBlending(layer->blend || layer->alpha < 255, layer->mode, false);
640        setupDrawProgram();
641        setupDrawDirtyRegionsDisabled();
642        setupDrawPureColorUniforms();
643        setupDrawColorFilterUniforms();
644        setupDrawTexture(layer->texture);
645        setupDrawModelViewTranslate(rect.left, rect.top, rect.right, rect.bottom);
646        setupDrawMesh(&mesh[0].position[0], &mesh[0].texture[0]);
647
648        for (size_t i = 0; i < count; i++) {
649            const android::Rect* r = &rects[i];
650
651            const float u1 = r->left * texX;
652            const float v1 = (height - r->top) * texY;
653            const float u2 = r->right * texX;
654            const float v2 = (height - r->bottom) * texY;
655
656            // TODO: Reject quads outside of the clip
657            TextureVertex::set(mesh++, r->left, r->top, u1, v1);
658            TextureVertex::set(mesh++, r->right, r->top, u2, v1);
659            TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
660            TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
661
662            numQuads++;
663
664            if (numQuads >= REGION_MESH_QUAD_COUNT) {
665                glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
666                numQuads = 0;
667                mesh = mCaches.getRegionMesh();
668            }
669        }
670
671        if (numQuads > 0) {
672            glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL);
673        }
674
675        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
676        finishDrawTexture();
677
678#if DEBUG_LAYERS_AS_REGIONS
679        uint32_t colors[] = {
680                0x7fff0000, 0x7f00ff00,
681                0x7f0000ff, 0x7fff00ff,
682        };
683
684        int offset = 0;
685        int32_t top = rects[0].top;
686        int i = 0;
687
688        for (size_t i = 0; i < count; i++) {
689            if (top != rects[i].top) {
690                offset ^= 0x2;
691                top = rects[i].top;
692            }
693
694            Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
695            drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)],
696                    SkXfermode::kSrcOver_Mode);
697        }
698#endif
699
700        layer->region.clear();
701    }
702#else
703    composeLayerRect(layer, rect);
704#endif
705}
706
707void OpenGLRenderer::dirtyLayer(const float left, const float top,
708        const float right, const float bottom, const mat4 transform) {
709#if RENDER_LAYERS_AS_REGIONS
710    if (hasLayer()) {
711        Rect bounds(left, top, right, bottom);
712        transform.mapRect(bounds);
713        dirtyLayerUnchecked(bounds, getRegion());
714    }
715#endif
716}
717
718void OpenGLRenderer::dirtyLayer(const float left, const float top,
719        const float right, const float bottom) {
720#if RENDER_LAYERS_AS_REGIONS
721    if (hasLayer()) {
722        Rect bounds(left, top, right, bottom);
723        dirtyLayerUnchecked(bounds, getRegion());
724    }
725#endif
726}
727
728void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
729#if RENDER_LAYERS_AS_REGIONS
730    if (bounds.intersect(*mSnapshot->clipRect)) {
731        bounds.snapToPixelBoundaries();
732        android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
733        if (!dirty.isEmpty()) {
734            region->orSelf(dirty);
735        }
736    }
737#endif
738}
739
740void OpenGLRenderer::clearLayerRegions() {
741    if (mLayers.size() == 0 || mSnapshot->isIgnored()) return;
742
743    Rect clipRect(*mSnapshot->clipRect);
744    clipRect.snapToPixelBoundaries();
745
746    for (uint32_t i = 0; i < mLayers.size(); i++) {
747        Rect* bounds = mLayers.itemAt(i);
748        if (clipRect.intersects(*bounds)) {
749            // Clear the framebuffer where the layer will draw
750            glScissor(bounds->left, mSnapshot->height - bounds->bottom,
751                    bounds->getWidth(), bounds->getHeight());
752            glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
753            glClear(GL_COLOR_BUFFER_BIT);
754
755            // Restore the clip
756            dirtyClip();
757        }
758
759        delete bounds;
760    }
761
762    mLayers.clear();
763}
764
765///////////////////////////////////////////////////////////////////////////////
766// Transforms
767///////////////////////////////////////////////////////////////////////////////
768
769void OpenGLRenderer::translate(float dx, float dy) {
770    mSnapshot->transform->translate(dx, dy, 0.0f);
771}
772
773void OpenGLRenderer::rotate(float degrees) {
774    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
775}
776
777void OpenGLRenderer::scale(float sx, float sy) {
778    mSnapshot->transform->scale(sx, sy, 1.0f);
779}
780
781void OpenGLRenderer::skew(float sx, float sy) {
782    mSnapshot->transform->skew(sx, sy);
783}
784
785void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
786    mSnapshot->transform->load(*matrix);
787}
788
789const float* OpenGLRenderer::getMatrix() const {
790    if (mSnapshot->fbo != 0) {
791        return &mSnapshot->transform->data[0];
792    }
793    return &mIdentity.data[0];
794}
795
796void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
797    mSnapshot->transform->copyTo(*matrix);
798}
799
800void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
801    SkMatrix transform;
802    mSnapshot->transform->copyTo(transform);
803    transform.preConcat(*matrix);
804    mSnapshot->transform->load(transform);
805}
806
807///////////////////////////////////////////////////////////////////////////////
808// Clipping
809///////////////////////////////////////////////////////////////////////////////
810
811void OpenGLRenderer::setScissorFromClip() {
812    Rect clip(*mSnapshot->clipRect);
813    clip.snapToPixelBoundaries();
814    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
815    mDirtyClip = false;
816}
817
818const Rect& OpenGLRenderer::getClipBounds() {
819    return mSnapshot->getLocalClip();
820}
821
822bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
823    if (mSnapshot->isIgnored()) {
824        return true;
825    }
826
827    Rect r(left, top, right, bottom);
828    mSnapshot->transform->mapRect(r);
829    r.snapToPixelBoundaries();
830
831    Rect clipRect(*mSnapshot->clipRect);
832    clipRect.snapToPixelBoundaries();
833
834    return !clipRect.intersects(r);
835}
836
837bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
838    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
839    if (clipped) {
840        dirtyClip();
841    }
842    return !mSnapshot->clipRect->isEmpty();
843}
844
845///////////////////////////////////////////////////////////////////////////////
846// Drawing commands
847///////////////////////////////////////////////////////////////////////////////
848
849void OpenGLRenderer::setupDraw() {
850    clearLayerRegions();
851    if (mDirtyClip) {
852        setScissorFromClip();
853    }
854    mDescription.reset();
855    mSetShaderColor = false;
856    mColorSet = false;
857    mColorA = mColorR = mColorG = mColorB = 0.0f;
858    mTextureUnit = 0;
859    mTrackDirtyRegions = true;
860    mTexCoordsSlot = -1;
861}
862
863void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
864    mDescription.hasTexture = true;
865    mDescription.hasAlpha8Texture = isAlpha8;
866}
867
868void OpenGLRenderer::setupDrawColor(int color) {
869    setupDrawColor(color, (color >> 24) & 0xFF);
870}
871
872void OpenGLRenderer::setupDrawColor(int color, int alpha) {
873    mColorA = alpha / 255.0f;
874    const float a = mColorA / 255.0f;
875    mColorR = a * ((color >> 16) & 0xFF);
876    mColorG = a * ((color >>  8) & 0xFF);
877    mColorB = a * ((color      ) & 0xFF);
878    mColorSet = true;
879    mSetShaderColor = mDescription.setColor(mColorR, mColorG, mColorB, mColorA);
880}
881
882void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
883    mColorA = alpha / 255.0f;
884    const float a = mColorA / 255.0f;
885    mColorR = a * ((color >> 16) & 0xFF);
886    mColorG = a * ((color >>  8) & 0xFF);
887    mColorB = a * ((color      ) & 0xFF);
888    mColorSet = true;
889    mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA);
890}
891
892void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
893    mColorA = a;
894    mColorR = r;
895    mColorG = g;
896    mColorB = b;
897    mColorSet = true;
898    mSetShaderColor = mDescription.setColor(r, g, b, a);
899}
900
901void OpenGLRenderer::setupDrawAlpha8Color(float r, float g, float b, float a) {
902    mColorA = a;
903    mColorR = r;
904    mColorG = g;
905    mColorB = b;
906    mColorSet = true;
907    mSetShaderColor = mDescription.setAlpha8Color(r, g, b, a);
908}
909
910void OpenGLRenderer::setupDrawShader() {
911    if (mShader) {
912        mShader->describe(mDescription, mCaches.extensions);
913    }
914}
915
916void OpenGLRenderer::setupDrawColorFilter() {
917    if (mColorFilter) {
918        mColorFilter->describe(mDescription, mCaches.extensions);
919    }
920}
921
922void OpenGLRenderer::setupDrawBlending(SkXfermode::Mode mode, bool swapSrcDst) {
923    chooseBlending((mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
924            mDescription, swapSrcDst);
925}
926
927void OpenGLRenderer::setupDrawBlending(bool blend, SkXfermode::Mode mode, bool swapSrcDst) {
928    chooseBlending(blend || (mColorSet && mColorA < 1.0f) || (mShader && mShader->blend()), mode,
929            mDescription, swapSrcDst);
930}
931
932void OpenGLRenderer::setupDrawProgram() {
933    useProgram(mCaches.programCache.get(mDescription));
934}
935
936void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
937    mTrackDirtyRegions = false;
938}
939
940void OpenGLRenderer::setupDrawModelViewTranslate(float left, float top, float right, float bottom,
941        bool ignoreTransform) {
942    mModelView.loadTranslate(left, top, 0.0f);
943    if (!ignoreTransform) {
944        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
945        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
946    } else {
947        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
948        if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom);
949    }
950}
951
952void OpenGLRenderer::setupDrawModelViewIdentity() {
953    mCaches.currentProgram->set(mOrthoMatrix, mIdentity, *mSnapshot->transform);
954}
955
956void OpenGLRenderer::setupDrawModelView(float left, float top, float right, float bottom,
957        bool ignoreTransform, bool ignoreModelView) {
958    if (!ignoreModelView) {
959        mModelView.loadTranslate(left, top, 0.0f);
960        mModelView.scale(right - left, bottom - top, 1.0f);
961    } else {
962        mModelView.loadIdentity();
963    }
964    bool dirty = right - left > 0.0f && bottom - top > 0.0f;
965    if (!ignoreTransform) {
966        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
967        if (mTrackDirtyRegions && dirty) {
968            dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
969        }
970    } else {
971        mCaches.currentProgram->set(mOrthoMatrix, mModelView, mIdentity);
972        if (mTrackDirtyRegions && dirty) dirtyLayer(left, top, right, bottom);
973    }
974}
975
976void OpenGLRenderer::setupDrawColorUniforms() {
977    if (mColorSet || (mShader && mSetShaderColor)) {
978        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
979    }
980}
981
982void OpenGLRenderer::setupDrawPureColorUniforms() {
983    if (mSetShaderColor) {
984        mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
985    }
986}
987
988void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) {
989    if (mShader) {
990        if (ignoreTransform) {
991            mModelView.loadInverse(*mSnapshot->transform);
992        }
993        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &mTextureUnit);
994    }
995}
996
997void OpenGLRenderer::setupDrawShaderIdentityUniforms() {
998    if (mShader) {
999        mShader->setupProgram(mCaches.currentProgram, mIdentity, *mSnapshot, &mTextureUnit);
1000    }
1001}
1002
1003void OpenGLRenderer::setupDrawColorFilterUniforms() {
1004    if (mColorFilter) {
1005        mColorFilter->setupProgram(mCaches.currentProgram);
1006    }
1007}
1008
1009void OpenGLRenderer::setupDrawSimpleMesh() {
1010    mCaches.bindMeshBuffer();
1011    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1012            gMeshStride, 0);
1013}
1014
1015void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1016    bindTexture(texture);
1017    glUniform1i(mCaches.currentProgram->getUniform("sampler"), mTextureUnit++);
1018
1019    mTexCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1020    glEnableVertexAttribArray(mTexCoordsSlot);
1021}
1022
1023void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
1024    if (!vertices) {
1025        mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1026    } else {
1027        mCaches.unbindMeshBuffer();
1028    }
1029    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1030            gMeshStride, vertices);
1031    if (mTexCoordsSlot > 0) {
1032        glVertexAttribPointer(mTexCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1033    }
1034}
1035
1036void OpenGLRenderer::finishDrawTexture() {
1037    glDisableVertexAttribArray(mTexCoordsSlot);
1038}
1039
1040///////////////////////////////////////////////////////////////////////////////
1041// Drawing
1042///////////////////////////////////////////////////////////////////////////////
1043
1044bool OpenGLRenderer::drawDisplayList(DisplayList* displayList, uint32_t level) {
1045    // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1046    // will be performed by the display list itself
1047    if (displayList) {
1048        return displayList->replay(*this, level);
1049    }
1050    return false;
1051}
1052
1053void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
1054    const float right = left + bitmap->width();
1055    const float bottom = top + bitmap->height();
1056
1057    if (quickReject(left, top, right, bottom)) {
1058        return;
1059    }
1060
1061    glActiveTexture(gTextureUnits[0]);
1062    Texture* texture = mCaches.textureCache.get(bitmap);
1063    if (!texture) return;
1064    const AutoTexture autoCleanup(texture);
1065
1066    drawTextureRect(left, top, right, bottom, texture, paint);
1067}
1068
1069void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
1070    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
1071    const mat4 transform(*matrix);
1072    transform.mapRect(r);
1073
1074    if (quickReject(r.left, r.top, r.right, r.bottom)) {
1075        return;
1076    }
1077
1078    glActiveTexture(gTextureUnits[0]);
1079    Texture* texture = mCaches.textureCache.get(bitmap);
1080    if (!texture) return;
1081    const AutoTexture autoCleanup(texture);
1082
1083    // This could be done in a cheaper way, all we need is pass the matrix
1084    // to the vertex shader. The save/restore is a bit overkill.
1085    save(SkCanvas::kMatrix_SaveFlag);
1086    concatMatrix(matrix);
1087    drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
1088    restore();
1089}
1090
1091void OpenGLRenderer::drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight,
1092        float* vertices, int* colors, SkPaint* paint) {
1093    // TODO: Do a quickReject
1094    if (!vertices || mSnapshot->isIgnored()) {
1095        return;
1096    }
1097
1098    glActiveTexture(gTextureUnits[0]);
1099    Texture* texture = mCaches.textureCache.get(bitmap);
1100    if (!texture) return;
1101    const AutoTexture autoCleanup(texture);
1102    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1103
1104    int alpha;
1105    SkXfermode::Mode mode;
1106    getAlphaAndMode(paint, &alpha, &mode);
1107
1108    const uint32_t count = meshWidth * meshHeight * 6;
1109
1110    // TODO: Support the colors array
1111    TextureVertex mesh[count];
1112    TextureVertex* vertex = mesh;
1113    for (int32_t y = 0; y < meshHeight; y++) {
1114        for (int32_t x = 0; x < meshWidth; x++) {
1115            uint32_t i = (y * (meshWidth + 1) + x) * 2;
1116
1117            float u1 = float(x) / meshWidth;
1118            float u2 = float(x + 1) / meshWidth;
1119            float v1 = float(y) / meshHeight;
1120            float v2 = float(y + 1) / meshHeight;
1121
1122            int ax = i + (meshWidth + 1) * 2;
1123            int ay = ax + 1;
1124            int bx = i;
1125            int by = bx + 1;
1126            int cx = i + 2;
1127            int cy = cx + 1;
1128            int dx = i + (meshWidth + 1) * 2 + 2;
1129            int dy = dx + 1;
1130
1131            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1132            TextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1);
1133            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1134
1135            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
1136            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
1137            TextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2);
1138        }
1139    }
1140
1141    drawTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, alpha / 255.0f,
1142            mode, texture->blend, &mesh[0].position[0], &mesh[0].texture[0],
1143            GL_TRIANGLES, count);
1144}
1145
1146void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
1147         float srcLeft, float srcTop, float srcRight, float srcBottom,
1148         float dstLeft, float dstTop, float dstRight, float dstBottom,
1149         SkPaint* paint) {
1150    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
1151        return;
1152    }
1153
1154    glActiveTexture(gTextureUnits[0]);
1155    Texture* texture = mCaches.textureCache.get(bitmap);
1156    if (!texture) return;
1157    const AutoTexture autoCleanup(texture);
1158    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1159
1160    const float width = texture->width;
1161    const float height = texture->height;
1162
1163    const float u1 = srcLeft / width;
1164    const float v1 = srcTop / height;
1165    const float u2 = srcRight / width;
1166    const float v2 = srcBottom / height;
1167
1168    mCaches.unbindMeshBuffer();
1169    resetDrawTextureTexCoords(u1, v1, u2, v2);
1170
1171    int alpha;
1172    SkXfermode::Mode mode;
1173    getAlphaAndMode(paint, &alpha, &mode);
1174
1175    if (mSnapshot->transform->isPureTranslate()) {
1176        const float x = (int) floorf(dstLeft + mSnapshot->transform->getTranslateX() + 0.5f);
1177        const float y = (int) floorf(dstTop + mSnapshot->transform->getTranslateY() + 0.5f);
1178
1179        drawTextureMesh(x, y, x + (dstRight - dstLeft), y + (dstBottom - dstTop),
1180                texture->id, alpha / 255.0f, mode, texture->blend,
1181                &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1182                GL_TRIANGLE_STRIP, gMeshCount, false, true);
1183    } else {
1184        drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, texture->id, alpha / 255.0f,
1185                mode, texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1186                GL_TRIANGLE_STRIP, gMeshCount);
1187    }
1188
1189    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1190}
1191
1192void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
1193        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
1194        float left, float top, float right, float bottom, SkPaint* paint) {
1195    if (quickReject(left, top, right, bottom)) {
1196        return;
1197    }
1198
1199    glActiveTexture(gTextureUnits[0]);
1200    Texture* texture = mCaches.textureCache.get(bitmap);
1201    if (!texture) return;
1202    const AutoTexture autoCleanup(texture);
1203    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1204
1205    int alpha;
1206    SkXfermode::Mode mode;
1207    getAlphaAndMode(paint, &alpha, &mode);
1208
1209    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
1210            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
1211
1212    if (mesh && mesh->verticesCount > 0) {
1213        const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1214#if RENDER_LAYERS_AS_REGIONS
1215        // Mark the current layer dirty where we are going to draw the patch
1216        if (hasLayer() && mesh->hasEmptyQuads) {
1217            const size_t count = mesh->quads.size();
1218            for (size_t i = 0; i < count; i++) {
1219                const Rect& bounds = mesh->quads.itemAt(i);
1220                if (pureTranslate) {
1221                    const float x = (int) floorf(bounds.left + 0.5f);
1222                    const float y = (int) floorf(bounds.top + 0.5f);
1223                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight(),
1224                            *mSnapshot->transform);
1225                } else {
1226                    dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom,
1227                            *mSnapshot->transform);
1228                }
1229            }
1230        }
1231#endif
1232
1233        if (pureTranslate) {
1234            const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1235            const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1236
1237            drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f,
1238                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1239                    GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer,
1240                    true, !mesh->hasEmptyQuads);
1241        } else {
1242            drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f,
1243                    mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
1244                    GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer,
1245                    true, !mesh->hasEmptyQuads);
1246        }
1247    }
1248}
1249
1250void OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
1251    if (mSnapshot->isIgnored()) return;
1252
1253    const bool isAA = paint->isAntiAlias();
1254    const float strokeWidth = paint->getStrokeWidth() * 0.5f;
1255    // A stroke width of 0 has a special meaningin Skia:
1256    // it draws an unscaled 1px wide line
1257    const bool isHairLine = paint->getStrokeWidth() == 0.0f;
1258
1259    int alpha;
1260    SkXfermode::Mode mode;
1261    getAlphaAndMode(paint, &alpha, &mode);
1262
1263    int verticesCount = count >> 2;
1264    int generatedVerticesCount = 0;
1265    if (!isHairLine) {
1266        // TODO: AA needs more vertices
1267        verticesCount *= 6;
1268    } else {
1269        // TODO: AA will be different
1270        verticesCount *= 2;
1271    }
1272
1273    TextureVertex lines[verticesCount];
1274    TextureVertex* vertex = &lines[0];
1275
1276    setupDraw();
1277    setupDrawColor(paint->getColor(), alpha);
1278    setupDrawColorFilter();
1279    setupDrawShader();
1280    setupDrawBlending(mode);
1281    setupDrawProgram();
1282    setupDrawModelViewIdentity();
1283    setupDrawColorUniforms();
1284    setupDrawColorFilterUniforms();
1285    setupDrawShaderIdentityUniforms();
1286    setupDrawMesh(vertex);
1287
1288    if (!isHairLine) {
1289        // TODO: Handle the AA case
1290        for (int i = 0; i < count; i += 4) {
1291            // a = start point, b = end point
1292            vec2 a(points[i], points[i + 1]);
1293            vec2 b(points[i + 2], points[i + 3]);
1294
1295            // Bias to snap to the same pixels as Skia
1296            a += 0.375;
1297            b += 0.375;
1298
1299            // Find the normal to the line
1300            vec2 n = (b - a).copyNormalized() * strokeWidth;
1301            float x = n.x;
1302            n.x = -n.y;
1303            n.y = x;
1304
1305            // Four corners of the rectangle defining a thick line
1306            vec2 p1 = a - n;
1307            vec2 p2 = a + n;
1308            vec2 p3 = b + n;
1309            vec2 p4 = b - n;
1310
1311            const float left = fmin(p1.x, fmin(p2.x, fmin(p3.x, p4.x)));
1312            const float right = fmax(p1.x, fmax(p2.x, fmax(p3.x, p4.x)));
1313            const float top = fmin(p1.y, fmin(p2.y, fmin(p3.y, p4.y)));
1314            const float bottom = fmax(p1.y, fmax(p2.y, fmax(p3.y, p4.y)));
1315
1316            if (!quickReject(left, top, right, bottom)) {
1317                // Draw the line as 2 triangles, could be optimized
1318                // by using only 4 vertices and the correct indices
1319                // Also we should probably used non textured vertices
1320                // when line AA is disabled to save on bandwidth
1321                TextureVertex::set(vertex++, p1.x, p1.y, 0.0f, 0.0f);
1322                TextureVertex::set(vertex++, p2.x, p2.y, 0.0f, 0.0f);
1323                TextureVertex::set(vertex++, p3.x, p3.y, 0.0f, 0.0f);
1324                TextureVertex::set(vertex++, p1.x, p1.y, 0.0f, 0.0f);
1325                TextureVertex::set(vertex++, p3.x, p3.y, 0.0f, 0.0f);
1326                TextureVertex::set(vertex++, p4.x, p4.y, 0.0f, 0.0f);
1327
1328                generatedVerticesCount += 6;
1329
1330                dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1331            }
1332        }
1333
1334        if (generatedVerticesCount > 0) {
1335            // GL_LINE does not give the result we want to match Skia
1336            glDrawArrays(GL_TRIANGLES, 0, generatedVerticesCount);
1337        }
1338    } else {
1339        // TODO: Handle the AA case
1340        for (int i = 0; i < count; i += 4) {
1341            const float left = fmin(points[i], points[i + 1]);
1342            const float right = fmax(points[i], points[i + 1]);
1343            const float top = fmin(points[i + 2], points[i + 3]);
1344            const float bottom = fmax(points[i + 2], points[i + 3]);
1345
1346            if (!quickReject(left, top, right, bottom)) {
1347                TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f);
1348                TextureVertex::set(vertex++, points[i + 2], points[i + 3], 0.0f, 0.0f);
1349
1350                generatedVerticesCount += 2;
1351
1352                dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
1353            }
1354        }
1355
1356        if (generatedVerticesCount > 0) {
1357            glLineWidth(1.0f);
1358            glDrawArrays(GL_LINES, 0, generatedVerticesCount);
1359        }
1360    }
1361}
1362
1363void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
1364    // No need to check against the clip, we fill the clip region
1365    if (mSnapshot->isIgnored()) return;
1366
1367    Rect& clip(*mSnapshot->clipRect);
1368    clip.snapToPixelBoundaries();
1369
1370    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
1371}
1372
1373void OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture, SkPaint* paint) {
1374    if (!texture) return;
1375    const AutoTexture autoCleanup(texture);
1376
1377    const float x = left + texture->left - texture->offset;
1378    const float y = top + texture->top - texture->offset;
1379
1380    drawPathTexture(texture, x, y, paint);
1381}
1382
1383void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
1384        float rx, float ry, SkPaint* paint) {
1385    if (mSnapshot->isIgnored()) return;
1386
1387    glActiveTexture(gTextureUnits[0]);
1388    const PathTexture* texture = mCaches.roundRectShapeCache.getRoundRect(
1389            right - left, bottom - top, rx, ry, paint);
1390    drawShape(left, top, texture, paint);
1391}
1392
1393void OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* paint) {
1394    if (mSnapshot->isIgnored()) return;
1395
1396    glActiveTexture(gTextureUnits[0]);
1397    const PathTexture* texture = mCaches.circleShapeCache.getCircle(radius, paint);
1398    drawShape(x - radius, y - radius, texture, paint);
1399}
1400
1401void OpenGLRenderer::drawOval(float left, float top, float right, float bottom, SkPaint* paint) {
1402    if (mSnapshot->isIgnored()) return;
1403
1404    glActiveTexture(gTextureUnits[0]);
1405    const PathTexture* texture = mCaches.ovalShapeCache.getOval(right - left, bottom - top, paint);
1406    drawShape(left, top, texture, paint);
1407}
1408
1409void OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
1410        float startAngle, float sweepAngle, bool useCenter, SkPaint* paint) {
1411    if (mSnapshot->isIgnored()) return;
1412
1413    if (fabs(sweepAngle) >= 360.0f) {
1414        drawOval(left, top, right, bottom, paint);
1415        return;
1416    }
1417
1418    glActiveTexture(gTextureUnits[0]);
1419    const PathTexture* texture = mCaches.arcShapeCache.getArc(right - left, bottom - top,
1420            startAngle, sweepAngle, useCenter, paint);
1421    drawShape(left, top, texture, paint);
1422}
1423
1424void OpenGLRenderer::drawRectAsShape(float left, float top, float right, float bottom,
1425        SkPaint* paint) {
1426    if (mSnapshot->isIgnored()) return;
1427
1428    glActiveTexture(gTextureUnits[0]);
1429    const PathTexture* texture = mCaches.rectShapeCache.getRect(right - left, bottom - top, paint);
1430    drawShape(left, top, texture, paint);
1431}
1432
1433void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
1434    if (p->getStyle() != SkPaint::kFill_Style) {
1435        drawRectAsShape(left, top, right, bottom, p);
1436        return;
1437    }
1438
1439    if (quickReject(left, top, right, bottom)) {
1440        return;
1441    }
1442
1443    SkXfermode::Mode mode;
1444    if (!mCaches.extensions.hasFramebufferFetch()) {
1445        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
1446        if (!isMode) {
1447            // Assume SRC_OVER
1448            mode = SkXfermode::kSrcOver_Mode;
1449        }
1450    } else {
1451        mode = getXfermode(p->getXfermode());
1452    }
1453
1454    // Skia draws using the color's alpha channel if < 255
1455    // Otherwise, it uses the paint's alpha
1456    int color = p->getColor();
1457    if (((color >> 24) & 0xff) == 255) {
1458        color |= p->getAlpha() << 24;
1459    }
1460
1461    drawColorRect(left, top, right, bottom, color, mode);
1462}
1463
1464void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
1465        float x, float y, SkPaint* paint) {
1466    if (text == NULL || count == 0) {
1467        return;
1468    }
1469    if (mSnapshot->isIgnored()) return;
1470
1471    paint->setAntiAlias(true);
1472
1473    float length = -1.0f;
1474    switch (paint->getTextAlign()) {
1475        case SkPaint::kCenter_Align:
1476            length = paint->measureText(text, bytesCount);
1477            x -= length / 2.0f;
1478            break;
1479        case SkPaint::kRight_Align:
1480            length = paint->measureText(text, bytesCount);
1481            x -= length;
1482            break;
1483        default:
1484            break;
1485    }
1486
1487    // TODO: Handle paint->getTextScaleX()
1488    const float oldX = x;
1489    const float oldY = y;
1490    const bool pureTranslate = mSnapshot->transform->isPureTranslate();
1491    if (pureTranslate) {
1492        x = (int) floorf(x + mSnapshot->transform->getTranslateX() + 0.5f);
1493        y = (int) floorf(y + mSnapshot->transform->getTranslateY() + 0.5f);
1494    }
1495
1496    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
1497    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
1498            paint->getTextSize());
1499
1500    int alpha;
1501    SkXfermode::Mode mode;
1502    getAlphaAndMode(paint, &alpha, &mode);
1503
1504    if (mHasShadow) {
1505        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
1506        const ShadowTexture* shadow = mCaches.dropShadowCache.get(paint, text, bytesCount,
1507                count, mShadowRadius);
1508        const AutoTexture autoCleanup(shadow);
1509
1510        const float sx = x - shadow->left + mShadowDx;
1511        const float sy = y - shadow->top + mShadowDy;
1512
1513        const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
1514
1515        glActiveTexture(gTextureUnits[0]);
1516        setupDraw();
1517        setupDrawWithTexture(true);
1518        setupDrawAlpha8Color(mShadowColor, shadowAlpha < 255 ? shadowAlpha : alpha);
1519        setupDrawBlending(true, mode);
1520        setupDrawProgram();
1521        setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height, pureTranslate);
1522        setupDrawTexture(shadow->id);
1523        setupDrawPureColorUniforms();
1524        setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
1525
1526        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1527        finishDrawTexture();
1528    }
1529
1530    if (paint->getAlpha() == 0 && paint->getXfermode() == NULL) {
1531        return;
1532    }
1533
1534    // Pick the appropriate texture filtering
1535    bool linearFilter = mSnapshot->transform->changesBounds();
1536    if (pureTranslate && !linearFilter) {
1537        linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
1538    }
1539
1540    glActiveTexture(gTextureUnits[0]);
1541    setupDraw();
1542    setupDrawDirtyRegionsDisabled();
1543    setupDrawWithTexture(true);
1544    setupDrawAlpha8Color(paint->getColor(), alpha);
1545    setupDrawColorFilter();
1546    setupDrawShader();
1547    setupDrawBlending(true, mode);
1548    setupDrawProgram();
1549    setupDrawModelView(x, y, x, y, pureTranslate, true);
1550    setupDrawTexture(fontRenderer.getTexture(linearFilter));
1551    setupDrawPureColorUniforms();
1552    setupDrawColorFilterUniforms();
1553    setupDrawShaderUniforms(pureTranslate);
1554
1555    const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
1556    Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
1557
1558#if RENDER_LAYERS_AS_REGIONS
1559    bool hasActiveLayer = hasLayer();
1560#else
1561    bool hasActiveLayer = false;
1562#endif
1563
1564    mCaches.unbindMeshBuffer();
1565    if (fontRenderer.renderText(paint, clip, text, 0, bytesCount, count, x, y,
1566            hasActiveLayer ? &bounds : NULL)) {
1567#if RENDER_LAYERS_AS_REGIONS
1568        if (hasActiveLayer) {
1569            if (!pureTranslate) {
1570                mSnapshot->transform->mapRect(bounds);
1571            }
1572            dirtyLayerUnchecked(bounds, getRegion());
1573        }
1574#endif
1575    }
1576
1577    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1578    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
1579
1580    drawTextDecorations(text, bytesCount, length, oldX, oldY, paint);
1581}
1582
1583void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
1584    if (mSnapshot->isIgnored()) return;
1585
1586    glActiveTexture(gTextureUnits[0]);
1587
1588    const PathTexture* texture = mCaches.pathCache.get(path, paint);
1589    if (!texture) return;
1590    const AutoTexture autoCleanup(texture);
1591
1592    const float x = texture->left - texture->offset;
1593    const float y = texture->top - texture->offset;
1594
1595    drawPathTexture(texture, x, y, paint);
1596}
1597
1598void OpenGLRenderer::drawLayer(Layer* layer, float x, float y, SkPaint* paint) {
1599    if (!layer || quickReject(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight())) {
1600        return;
1601    }
1602
1603    glActiveTexture(gTextureUnits[0]);
1604
1605    int alpha;
1606    SkXfermode::Mode mode;
1607    getAlphaAndMode(paint, &alpha, &mode);
1608
1609    layer->alpha = alpha;
1610    layer->mode = mode;
1611
1612#if RENDER_LAYERS_AS_REGIONS
1613    if (!layer->region.isEmpty()) {
1614        if (layer->region.isRect()) {
1615            const Rect r(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight());
1616            composeLayerRect(layer, r);
1617        } else if (layer->mesh) {
1618            const float a = alpha / 255.0f;
1619            const Rect& rect = layer->layer;
1620
1621            setupDraw();
1622            setupDrawWithTexture();
1623            setupDrawColor(a, a, a, a);
1624            setupDrawColorFilter();
1625            setupDrawBlending(layer->blend || layer->alpha < 255, layer->mode, false);
1626            setupDrawProgram();
1627            setupDrawDirtyRegionsDisabled();
1628            setupDrawPureColorUniforms();
1629            setupDrawColorFilterUniforms();
1630            setupDrawTexture(layer->texture);
1631            setupDrawModelViewTranslate(rect.left, rect.top, rect.right, rect.bottom);
1632            setupDrawMesh(&layer->mesh[0].position[0], &layer->mesh[0].texture[0]);
1633
1634            glDrawElements(GL_TRIANGLES, layer->meshElementCount,
1635                    GL_UNSIGNED_SHORT, layer->meshIndices);
1636
1637            finishDrawTexture();
1638        }
1639    }
1640#else
1641    const Rect r(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight());
1642    composeLayerRect(layer, r);
1643#endif
1644}
1645
1646///////////////////////////////////////////////////////////////////////////////
1647// Shaders
1648///////////////////////////////////////////////////////////////////////////////
1649
1650void OpenGLRenderer::resetShader() {
1651    mShader = NULL;
1652}
1653
1654void OpenGLRenderer::setupShader(SkiaShader* shader) {
1655    mShader = shader;
1656    if (mShader) {
1657        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
1658    }
1659}
1660
1661///////////////////////////////////////////////////////////////////////////////
1662// Color filters
1663///////////////////////////////////////////////////////////////////////////////
1664
1665void OpenGLRenderer::resetColorFilter() {
1666    mColorFilter = NULL;
1667}
1668
1669void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
1670    mColorFilter = filter;
1671}
1672
1673///////////////////////////////////////////////////////////////////////////////
1674// Drop shadow
1675///////////////////////////////////////////////////////////////////////////////
1676
1677void OpenGLRenderer::resetShadow() {
1678    mHasShadow = false;
1679}
1680
1681void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
1682    mHasShadow = true;
1683    mShadowRadius = radius;
1684    mShadowDx = dx;
1685    mShadowDy = dy;
1686    mShadowColor = color;
1687}
1688
1689///////////////////////////////////////////////////////////////////////////////
1690// Drawing implementation
1691///////////////////////////////////////////////////////////////////////////////
1692
1693void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
1694        float x, float y, SkPaint* paint) {
1695    if (quickReject(x, y, x + texture->width, y + texture->height)) {
1696        return;
1697    }
1698
1699    int alpha;
1700    SkXfermode::Mode mode;
1701    getAlphaAndMode(paint, &alpha, &mode);
1702
1703    setupDraw();
1704    setupDrawWithTexture(true);
1705    setupDrawAlpha8Color(paint->getColor(), alpha);
1706    setupDrawColorFilter();
1707    setupDrawShader();
1708    setupDrawBlending(true, mode);
1709    setupDrawProgram();
1710    setupDrawModelView(x, y, x + texture->width, y + texture->height);
1711    setupDrawTexture(texture->id);
1712    setupDrawPureColorUniforms();
1713    setupDrawColorFilterUniforms();
1714    setupDrawShaderUniforms();
1715    setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
1716
1717    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1718
1719    finishDrawTexture();
1720}
1721
1722// Same values used by Skia
1723#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
1724#define kStdUnderline_Offset    (1.0f / 9.0f)
1725#define kStdUnderline_Thickness (1.0f / 18.0f)
1726
1727void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
1728        float x, float y, SkPaint* paint) {
1729    // Handle underline and strike-through
1730    uint32_t flags = paint->getFlags();
1731    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
1732        float underlineWidth = length;
1733        // If length is > 0.0f, we already measured the text for the text alignment
1734        if (length <= 0.0f) {
1735            underlineWidth = paint->measureText(text, bytesCount);
1736        }
1737
1738        float offsetX = 0;
1739        switch (paint->getTextAlign()) {
1740            case SkPaint::kCenter_Align:
1741                offsetX = underlineWidth * 0.5f;
1742                break;
1743            case SkPaint::kRight_Align:
1744                offsetX = underlineWidth;
1745                break;
1746            default:
1747                break;
1748        }
1749
1750        if (underlineWidth > 0.0f) {
1751            const float textSize = paint->getTextSize();
1752            // TODO: Support stroke width < 1.0f when we have AA lines
1753            const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
1754
1755            const float left = x - offsetX;
1756            float top = 0.0f;
1757
1758            int linesCount = 0;
1759            if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
1760            if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
1761
1762            const int pointsCount = 4 * linesCount;
1763            float points[pointsCount];
1764            int currentPoint = 0;
1765
1766            if (flags & SkPaint::kUnderlineText_Flag) {
1767                top = y + textSize * kStdUnderline_Offset;
1768                points[currentPoint++] = left;
1769                points[currentPoint++] = top;
1770                points[currentPoint++] = left + underlineWidth;
1771                points[currentPoint++] = top;
1772            }
1773
1774            if (flags & SkPaint::kStrikeThruText_Flag) {
1775                top = y + textSize * kStdStrikeThru_Offset;
1776                points[currentPoint++] = left;
1777                points[currentPoint++] = top;
1778                points[currentPoint++] = left + underlineWidth;
1779                points[currentPoint++] = top;
1780            }
1781
1782            SkPaint linesPaint(*paint);
1783            linesPaint.setStrokeWidth(strokeWidth);
1784
1785            drawLines(&points[0], pointsCount, &linesPaint);
1786        }
1787    }
1788}
1789
1790void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
1791        int color, SkXfermode::Mode mode, bool ignoreTransform) {
1792    // If a shader is set, preserve only the alpha
1793    if (mShader) {
1794        color |= 0x00ffffff;
1795    }
1796
1797    setupDraw();
1798    setupDrawColor(color);
1799    setupDrawShader();
1800    setupDrawColorFilter();
1801    setupDrawBlending(mode);
1802    setupDrawProgram();
1803    setupDrawModelView(left, top, right, bottom, ignoreTransform);
1804    setupDrawColorUniforms();
1805    setupDrawShaderUniforms(ignoreTransform);
1806    setupDrawColorFilterUniforms();
1807    setupDrawSimpleMesh();
1808
1809    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1810}
1811
1812void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1813        Texture* texture, SkPaint* paint) {
1814    int alpha;
1815    SkXfermode::Mode mode;
1816    getAlphaAndMode(paint, &alpha, &mode);
1817
1818    setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
1819
1820    if (mSnapshot->transform->isPureTranslate()) {
1821        const float x = (int) floorf(left + mSnapshot->transform->getTranslateX() + 0.5f);
1822        const float y = (int) floorf(top + mSnapshot->transform->getTranslateY() + 0.5f);
1823
1824        drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
1825                alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL,
1826                (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true);
1827    } else {
1828        drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
1829                texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
1830                GL_TRIANGLE_STRIP, gMeshCount);
1831    }
1832}
1833
1834void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1835        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
1836    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
1837            (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
1838}
1839
1840void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
1841        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
1842        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
1843        bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
1844
1845    setupDraw();
1846    setupDrawWithTexture();
1847    setupDrawColor(alpha, alpha, alpha, alpha);
1848    setupDrawColorFilter();
1849    setupDrawBlending(blend, mode, swapSrcDst);
1850    setupDrawProgram();
1851    if (!dirty) {
1852        setupDrawDirtyRegionsDisabled();
1853    }
1854    if (!ignoreScale) {
1855        setupDrawModelView(left, top, right, bottom, ignoreTransform);
1856    } else {
1857        setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
1858    }
1859    setupDrawPureColorUniforms();
1860    setupDrawColorFilterUniforms();
1861    setupDrawTexture(texture);
1862    setupDrawMesh(vertices, texCoords, vbo);
1863
1864    glDrawArrays(drawMode, 0, elementsCount);
1865
1866    finishDrawTexture();
1867}
1868
1869void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
1870        ProgramDescription& description, bool swapSrcDst) {
1871    blend = blend || mode != SkXfermode::kSrcOver_Mode;
1872    if (blend) {
1873        if (mode < SkXfermode::kPlus_Mode) {
1874            if (!mCaches.blend) {
1875                glEnable(GL_BLEND);
1876            }
1877
1878            GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
1879            GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
1880
1881            if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
1882                glBlendFunc(sourceMode, destMode);
1883                mCaches.lastSrcMode = sourceMode;
1884                mCaches.lastDstMode = destMode;
1885            }
1886        } else {
1887            // These blend modes are not supported by OpenGL directly and have
1888            // to be implemented using shaders. Since the shader will perform
1889            // the blending, turn blending off here
1890            if (mCaches.extensions.hasFramebufferFetch()) {
1891                description.framebufferMode = mode;
1892                description.swapSrcDst = swapSrcDst;
1893            }
1894
1895            if (mCaches.blend) {
1896                glDisable(GL_BLEND);
1897            }
1898            blend = false;
1899        }
1900    } else if (mCaches.blend) {
1901        glDisable(GL_BLEND);
1902    }
1903    mCaches.blend = blend;
1904}
1905
1906bool OpenGLRenderer::useProgram(Program* program) {
1907    if (!program->isInUse()) {
1908        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
1909        program->use();
1910        mCaches.currentProgram = program;
1911        return false;
1912    }
1913    return true;
1914}
1915
1916void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
1917    TextureVertex* v = &mMeshVertices[0];
1918    TextureVertex::setUV(v++, u1, v1);
1919    TextureVertex::setUV(v++, u2, v1);
1920    TextureVertex::setUV(v++, u1, v2);
1921    TextureVertex::setUV(v++, u2, v2);
1922}
1923
1924void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
1925    if (paint) {
1926        if (!mCaches.extensions.hasFramebufferFetch()) {
1927            const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
1928            if (!isMode) {
1929                // Assume SRC_OVER
1930                *mode = SkXfermode::kSrcOver_Mode;
1931            }
1932        } else {
1933            *mode = getXfermode(paint->getXfermode());
1934        }
1935
1936        // Skia draws using the color's alpha channel if < 255
1937        // Otherwise, it uses the paint's alpha
1938        int color = paint->getColor();
1939        *alpha = (color >> 24) & 0xFF;
1940        if (*alpha == 255) {
1941            *alpha = paint->getAlpha();
1942        }
1943    } else {
1944        *mode = SkXfermode::kSrcOver_Mode;
1945        *alpha = 255;
1946    }
1947}
1948
1949SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
1950    if (mode == NULL) {
1951        return SkXfermode::kSrcOver_Mode;
1952    }
1953    return mode->fMode;
1954}
1955
1956void OpenGLRenderer::setTextureWrapModes(Texture* texture, GLenum wrapS, GLenum wrapT) {
1957    bool bound = false;
1958    if (wrapS != texture->wrapS) {
1959        glBindTexture(GL_TEXTURE_2D, texture->id);
1960        bound = true;
1961        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
1962        texture->wrapS = wrapS;
1963    }
1964    if (wrapT != texture->wrapT) {
1965        if (!bound) {
1966            glBindTexture(GL_TEXTURE_2D, texture->id);
1967        }
1968        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
1969        texture->wrapT = wrapT;
1970    }
1971}
1972
1973}; // namespace uirenderer
1974}; // namespace android
1975