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