OpenGLRenderer.cpp revision 4bb942083a0d4db746adf95349108dd8ef842e32
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 "OpenGLRenderer.h"
30
31namespace android {
32namespace uirenderer {
33
34///////////////////////////////////////////////////////////////////////////////
35// Defines
36///////////////////////////////////////////////////////////////////////////////
37
38#define REQUIRED_TEXTURE_UNITS_COUNT 3
39
40// Generates simple and textured vertices
41#define FV(x, y, u, v) { { x, y }, { u, v } }
42
43#define RAD_TO_DEG (180.0f / 3.14159265f)
44#define MIN_ANGLE 0.001f
45
46// TODO: This should be set in properties
47#define ALPHA_THRESHOLD (0x7f / PANEL_BIT_DEPTH)
48
49///////////////////////////////////////////////////////////////////////////////
50// Globals
51///////////////////////////////////////////////////////////////////////////////
52
53// This array is never used directly but used as a memcpy source in the
54// OpenGLRenderer constructor
55static const TextureVertex gMeshVertices[] = {
56        FV(0.0f, 0.0f, 0.0f, 0.0f),
57        FV(1.0f, 0.0f, 1.0f, 0.0f),
58        FV(0.0f, 1.0f, 0.0f, 1.0f),
59        FV(1.0f, 1.0f, 1.0f, 1.0f)
60};
61static const GLsizei gMeshStride = sizeof(TextureVertex);
62static const GLsizei gMeshCount = 4;
63
64/**
65 * Structure mapping Skia xfermodes to OpenGL blending factors.
66 */
67struct Blender {
68    SkXfermode::Mode mode;
69    GLenum src;
70    GLenum dst;
71}; // struct Blender
72
73// In this array, the index of each Blender equals the value of the first
74// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
75static const Blender gBlends[] = {
76        { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
77        { SkXfermode::kSrc_Mode,     GL_ONE,                  GL_ZERO },
78        { SkXfermode::kDst_Mode,     GL_ZERO,                 GL_ONE },
79        { SkXfermode::kSrcOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
80        { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
81        { SkXfermode::kSrcIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
82        { SkXfermode::kDstIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
83        { SkXfermode::kSrcOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
84        { SkXfermode::kDstOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
85        { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
86        { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
87        { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
88};
89
90// This array contains the swapped version of each SkXfermode. For instance
91// this array's SrcOver blending mode is actually DstOver. You can refer to
92// createLayer() for more information on the purpose of this array.
93static const Blender gBlendsSwap[] = {
94        { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
95        { SkXfermode::kSrc_Mode,     GL_ZERO,                 GL_ONE },
96        { SkXfermode::kDst_Mode,     GL_ONE,                  GL_ZERO },
97        { SkXfermode::kSrcOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
98        { SkXfermode::kDstOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
99        { SkXfermode::kSrcIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
100        { SkXfermode::kDstIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
101        { SkXfermode::kSrcOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
102        { SkXfermode::kDstOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
103        { SkXfermode::kSrcATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
104        { SkXfermode::kDstATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
105        { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
106};
107
108static const GLenum gTextureUnits[] = {
109        GL_TEXTURE0,
110        GL_TEXTURE1,
111        GL_TEXTURE2
112};
113
114///////////////////////////////////////////////////////////////////////////////
115// Constructors/destructor
116///////////////////////////////////////////////////////////////////////////////
117
118OpenGLRenderer::OpenGLRenderer(): mCaches(Caches::getInstance()) {
119    mShader = NULL;
120    mColorFilter = NULL;
121    mHasShadow = false;
122
123    memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices));
124
125    mFirstSnapshot = new Snapshot;
126
127    GLint maxTextureUnits;
128    glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxTextureUnits);
129    if (maxTextureUnits < REQUIRED_TEXTURE_UNITS_COUNT) {
130        LOGW("At least %d texture units are required!", REQUIRED_TEXTURE_UNITS_COUNT);
131    }
132
133    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
134}
135
136OpenGLRenderer::~OpenGLRenderer() {
137    // The context has already been destroyed at this point, do not call
138    // GL APIs. All GL state should be kept in Caches.h
139}
140
141///////////////////////////////////////////////////////////////////////////////
142// Setup
143///////////////////////////////////////////////////////////////////////////////
144
145void OpenGLRenderer::setViewport(int width, int height) {
146    glViewport(0, 0, width, height);
147    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
148
149    mWidth = width;
150    mHeight = height;
151
152    mFirstSnapshot->height = height;
153    mFirstSnapshot->viewport.set(0, 0, width, height);
154}
155
156void OpenGLRenderer::prepare(bool opaque) {
157    mSnapshot = new Snapshot(mFirstSnapshot,
158            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
159    mSaveCount = 1;
160
161    glViewport(0, 0, mWidth, mHeight);
162
163    glDisable(GL_DITHER);
164    glDisable(GL_SCISSOR_TEST);
165
166    if (!opaque) {
167        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
168        glClear(GL_COLOR_BUFFER_BIT);
169    }
170
171    glEnable(GL_SCISSOR_TEST);
172    glScissor(0, 0, mWidth, mHeight);
173
174    mSnapshot->setClip(0.0f, 0.0f, mWidth, mHeight);
175}
176
177void OpenGLRenderer::finish() {
178#if DEBUG_OPENGL
179    GLenum status = GL_NO_ERROR;
180    while ((status = glGetError()) != GL_NO_ERROR) {
181        LOGD("GL error from OpenGLRenderer: 0x%x", status);
182    }
183#endif
184}
185
186void OpenGLRenderer::acquireContext() {
187    if (mCaches.currentProgram) {
188        if (mCaches.currentProgram->isInUse()) {
189            mCaches.currentProgram->remove();
190            mCaches.currentProgram = NULL;
191        }
192    }
193}
194
195void OpenGLRenderer::releaseContext() {
196    glViewport(0, 0, mSnapshot->viewport.getWidth(), mSnapshot->viewport.getHeight());
197
198    glEnable(GL_SCISSOR_TEST);
199    setScissorFromClip();
200
201    glDisable(GL_DITHER);
202
203    glBindFramebuffer(GL_FRAMEBUFFER, 0);
204
205    if (mCaches.blend) {
206        glEnable(GL_BLEND);
207        glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode);
208        glBlendEquation(GL_FUNC_ADD);
209    } else {
210        glDisable(GL_BLEND);
211    }
212}
213
214///////////////////////////////////////////////////////////////////////////////
215// State management
216///////////////////////////////////////////////////////////////////////////////
217
218int OpenGLRenderer::getSaveCount() const {
219    return mSaveCount;
220}
221
222int OpenGLRenderer::save(int flags) {
223    return saveSnapshot(flags);
224}
225
226void OpenGLRenderer::restore() {
227    if (mSaveCount > 1) {
228        restoreSnapshot();
229    }
230}
231
232void OpenGLRenderer::restoreToCount(int saveCount) {
233    if (saveCount < 1) saveCount = 1;
234
235    while (mSaveCount > saveCount) {
236        restoreSnapshot();
237    }
238}
239
240int OpenGLRenderer::saveSnapshot(int flags) {
241    mSnapshot = new Snapshot(mSnapshot, flags);
242    return mSaveCount++;
243}
244
245bool OpenGLRenderer::restoreSnapshot() {
246    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
247    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
248    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
249
250    sp<Snapshot> current = mSnapshot;
251    sp<Snapshot> previous = mSnapshot->previous;
252
253    if (restoreOrtho) {
254        Rect& r = previous->viewport;
255        glViewport(r.left, r.top, r.right, r.bottom);
256        mOrthoMatrix.load(current->orthoMatrix);
257    }
258
259    mSaveCount--;
260    mSnapshot = previous;
261
262    if (restoreLayer) {
263        composeLayer(current, previous);
264    }
265
266    if (restoreClip) {
267        setScissorFromClip();
268    }
269
270    return restoreClip;
271}
272
273///////////////////////////////////////////////////////////////////////////////
274// Layers
275///////////////////////////////////////////////////////////////////////////////
276
277int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
278        const SkPaint* p, int flags) {
279    const GLuint previousFbo = mSnapshot->fbo;
280    const int count = saveSnapshot(flags);
281
282    int alpha = 255;
283    SkXfermode::Mode mode;
284
285    if (p) {
286        alpha = p->getAlpha();
287        if (!mExtensions.hasFramebufferFetch()) {
288            const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
289            if (!isMode) {
290                // Assume SRC_OVER
291                mode = SkXfermode::kSrcOver_Mode;
292            }
293        } else {
294            mode = getXfermode(p->getXfermode());
295        }
296    } else {
297        mode = SkXfermode::kSrcOver_Mode;
298    }
299
300    if (!mSnapshot->previous->invisible) {
301        createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags, previousFbo);
302    }
303
304    return count;
305}
306
307int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
308        int alpha, int flags) {
309    if (alpha == 0xff) {
310        return saveLayer(left, top, right, bottom, NULL, flags);
311    } else {
312        SkPaint paint;
313        paint.setAlpha(alpha);
314        return saveLayer(left, top, right, bottom, &paint, flags);
315    }
316}
317
318/**
319 * Layers are viewed by Skia are slightly different than layers in image editing
320 * programs (for instance.) When a layer is created, previously created layers
321 * and the frame buffer still receive every drawing command. For instance, if a
322 * layer is created and a shape intersecting the bounds of the layers and the
323 * framebuffer is draw, the shape will be drawn on both (unless the layer was
324 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
325 *
326 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
327 * texture. Unfortunately, this is inefficient as it requires every primitive to
328 * be drawn n + 1 times, where n is the number of active layers. In practice this
329 * means, for every primitive:
330 *   - Switch active frame buffer
331 *   - Change viewport, clip and projection matrix
332 *   - Issue the drawing
333 *
334 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
335 * To avoid this, layers are implemented in a different way here, at least in the
336 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
337 * is set. When this flag is set we can redirect all drawing operations into a
338 * single FBO.
339 *
340 * This implementation relies on the frame buffer being at least RGBA 8888. When
341 * a layer is created, only a texture is created, not an FBO. The content of the
342 * frame buffer contained within the layer's bounds is copied into this texture
343 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
344 * buffer and drawing continues as normal. This technique therefore treats the
345 * frame buffer as a scratch buffer for the layers.
346 *
347 * To compose the layers back onto the frame buffer, each layer texture
348 * (containing the original frame buffer data) is drawn as a simple quad over
349 * the frame buffer. The trick is that the quad is set as the composition
350 * destination in the blending equation, and the frame buffer becomes the source
351 * of the composition.
352 *
353 * Drawing layers with an alpha value requires an extra step before composition.
354 * An empty quad is drawn over the layer's region in the frame buffer. This quad
355 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
356 * quad is used to multiply the colors in the frame buffer. This is achieved by
357 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
358 * GL_ZERO, GL_SRC_ALPHA.
359 *
360 * Because glCopyTexImage2D() can be slow, an alternative implementation might
361 * be use to draw a single clipped layer. The implementation described above
362 * is correct in every case.
363 *
364 * (1) The frame buffer is actually not cleared right away. To allow the GPU
365 *     to potentially optimize series of calls to glCopyTexImage2D, the frame
366 *     buffer is left untouched until the first drawing operation. Only when
367 *     something actually gets drawn are the layers regions cleared.
368 */
369bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
370        float right, float bottom, int alpha, SkXfermode::Mode mode,
371        int flags, GLuint previousFbo) {
372    LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
373    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
374
375    const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
376
377    // Window coordinates of the layer
378    Rect bounds(left, top, right, bottom);
379    if (!fboLayer) {
380        mSnapshot->transform->mapRect(bounds);
381        // Layers only make sense if they are in the framebuffer's bounds
382        bounds.intersect(*mSnapshot->clipRect);
383        bounds.snapToPixelBoundaries();
384    }
385
386    if (bounds.isEmpty() || bounds.getWidth() > mMaxTextureSize ||
387            bounds.getHeight() > mMaxTextureSize) {
388        snapshot->invisible = true;
389    } else {
390        // TODO: Should take the mode into account
391        snapshot->invisible = snapshot->previous->invisible || alpha <= ALPHA_THRESHOLD;
392    }
393
394    // Bail out if we won't draw in this snapshot
395    if (snapshot->invisible) {
396        return false;
397    }
398
399    glActiveTexture(GL_TEXTURE0);
400
401    Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight());
402    if (!layer) {
403        return false;
404    }
405
406    layer->mode = mode;
407    layer->alpha = alpha;
408    layer->layer.set(bounds);
409    layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->height),
410            bounds.getWidth() / float(layer->width), 0.0f);
411
412    // Save the layer in the snapshot
413    snapshot->flags |= Snapshot::kFlagIsLayer;
414    snapshot->layer = layer;
415
416    if (fboLayer) {
417        layer->fbo = mCaches.fboCache.get();
418
419        snapshot->flags |= Snapshot::kFlagIsFboLayer;
420        snapshot->fbo = layer->fbo;
421        snapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
422        snapshot->resetClip(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
423        snapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
424        snapshot->height = bounds.getHeight();
425        snapshot->flags |= Snapshot::kFlagDirtyOrtho;
426        snapshot->orthoMatrix.load(mOrthoMatrix);
427
428        setScissorFromClip();
429
430        // Bind texture to FBO
431        glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo);
432        glBindTexture(GL_TEXTURE_2D, layer->texture);
433
434        // Initialize the texture if needed
435        if (layer->empty) {
436            layer->empty = false;
437            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->width, layer->height, 0,
438                    GL_RGBA, GL_UNSIGNED_BYTE, NULL);
439        }
440
441        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
442                layer->texture, 0);
443
444        GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
445        if (status != GL_FRAMEBUFFER_COMPLETE) {
446            LOGE("Framebuffer incomplete (GL error code 0x%x)", status);
447
448            glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
449            glDeleteTextures(1, &layer->texture);
450            mCaches.fboCache.put(layer->fbo);
451
452            delete layer;
453
454            return false;
455        }
456
457        // Clear the FBO
458        glDisable(GL_SCISSOR_TEST);
459        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
460        glClear(GL_COLOR_BUFFER_BIT);
461        glEnable(GL_SCISSOR_TEST);
462
463        // Change the ortho projection
464        glViewport(0, 0, bounds.getWidth(), bounds.getHeight());
465        mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f);
466    } else {
467        // Copy the framebuffer into the layer
468        glBindTexture(GL_TEXTURE_2D, layer->texture);
469
470         if (layer->empty) {
471             glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.left, mHeight - bounds.bottom,
472                     layer->width, layer->height, 0);
473             layer->empty = false;
474         } else {
475             glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left, mHeight - bounds.bottom,
476                     bounds.getWidth(), bounds.getHeight());
477          }
478
479        // Enqueue the buffer coordinates to clear the corresponding region later
480        mLayers.push(new Rect(bounds));
481    }
482
483    return true;
484}
485
486/**
487 * Read the documentation of createLayer() before doing anything in this method.
488 */
489void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
490    if (!current->layer) {
491        LOGE("Attempting to compose a layer that does not exist");
492        return;
493    }
494
495    const bool fboLayer = current->flags & SkCanvas::kClipToLayer_SaveFlag;
496
497    if (fboLayer) {
498        // Unbind current FBO and restore previous one
499        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
500    }
501
502    // Restore the clip from the previous snapshot
503    const Rect& clip = *previous->clipRect;
504    glScissor(clip.left, previous->height - clip.bottom, clip.getWidth(), clip.getHeight());
505
506    Layer* layer = current->layer;
507    const Rect& rect = layer->layer;
508
509    if (!fboLayer && layer->alpha < 255) {
510        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
511                layer->alpha << 24, SkXfermode::kDstIn_Mode, true);
512    }
513
514    const Rect& texCoords = layer->texCoords;
515    resetDrawTextureTexCoords(texCoords.left, texCoords.top, texCoords.right, texCoords.bottom);
516
517    if (fboLayer) {
518        drawTextureRect(rect.left, rect.top, rect.right, rect.bottom,
519                layer->texture, layer->alpha / 255.0f, layer->mode, layer->blend);
520    } else {
521        drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture,
522                1.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0],
523                &mMeshVertices[0].texture[0], GL_TRIANGLE_STRIP, gMeshCount, true, true);
524    }
525
526    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
527
528    if (fboLayer) {
529        // Detach the texture from the FBO
530        glBindFramebuffer(GL_FRAMEBUFFER, current->fbo);
531        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
532        glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
533
534        // Put the FBO name back in the cache, if it doesn't fit, it will be destroyed
535        mCaches.fboCache.put(current->fbo);
536    }
537
538    // Failing to add the layer to the cache should happen only if the layer is too large
539    if (!mCaches.layerCache.put(layer)) {
540        LAYER_LOGD("Deleting layer");
541        glDeleteTextures(1, &layer->texture);
542        delete layer;
543    }
544}
545
546void OpenGLRenderer::clearLayerRegions() {
547    if (mLayers.size() == 0 || mSnapshot->invisible) return;
548
549    for (uint32_t i = 0; i < mLayers.size(); i++) {
550        Rect* bounds = mLayers.itemAt(i);
551
552        // Clear the framebuffer where the layer will draw
553        glScissor(bounds->left, mHeight - bounds->bottom,
554                bounds->getWidth(), bounds->getHeight());
555        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
556        glClear(GL_COLOR_BUFFER_BIT);
557
558        delete bounds;
559    }
560    mLayers.clear();
561
562    // Restore the clip
563    setScissorFromClip();
564}
565
566///////////////////////////////////////////////////////////////////////////////
567// Transforms
568///////////////////////////////////////////////////////////////////////////////
569
570void OpenGLRenderer::translate(float dx, float dy) {
571    mSnapshot->transform->translate(dx, dy, 0.0f);
572}
573
574void OpenGLRenderer::rotate(float degrees) {
575    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
576}
577
578void OpenGLRenderer::scale(float sx, float sy) {
579    mSnapshot->transform->scale(sx, sy, 1.0f);
580}
581
582void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
583    mSnapshot->transform->load(*matrix);
584}
585
586void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
587    mSnapshot->transform->copyTo(*matrix);
588}
589
590void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
591    mat4 m(*matrix);
592    mSnapshot->transform->multiply(m);
593}
594
595///////////////////////////////////////////////////////////////////////////////
596// Clipping
597///////////////////////////////////////////////////////////////////////////////
598
599void OpenGLRenderer::setScissorFromClip() {
600    const Rect& clip = *mSnapshot->clipRect;
601    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
602}
603
604const Rect& OpenGLRenderer::getClipBounds() {
605    return mSnapshot->getLocalClip();
606}
607
608bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
609    if (mSnapshot->invisible) {
610        return true;
611    }
612
613    Rect r(left, top, right, bottom);
614    mSnapshot->transform->mapRect(r);
615    return !mSnapshot->clipRect->intersects(r);
616}
617
618bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
619    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
620    if (clipped) {
621        setScissorFromClip();
622    }
623    return !mSnapshot->clipRect->isEmpty();
624}
625
626///////////////////////////////////////////////////////////////////////////////
627// Drawing
628///////////////////////////////////////////////////////////////////////////////
629
630void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, const SkPaint* paint) {
631    const float right = left + bitmap->width();
632    const float bottom = top + bitmap->height();
633
634    if (quickReject(left, top, right, bottom)) {
635        return;
636    }
637
638    glActiveTexture(GL_TEXTURE0);
639    const Texture* texture = mCaches.textureCache.get(bitmap);
640    if (!texture) return;
641    const AutoTexture autoCleanup(texture);
642
643    drawTextureRect(left, top, right, bottom, texture, paint);
644}
645
646void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, const SkMatrix* matrix, const SkPaint* paint) {
647    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
648    const mat4 transform(*matrix);
649    transform.mapRect(r);
650
651    if (quickReject(r.left, r.top, r.right, r.bottom)) {
652        return;
653    }
654
655    glActiveTexture(GL_TEXTURE0);
656    const Texture* texture = mCaches.textureCache.get(bitmap);
657    if (!texture) return;
658    const AutoTexture autoCleanup(texture);
659
660    drawTextureRect(r.left, r.top, r.right, r.bottom, texture, paint);
661}
662
663void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
664         float srcLeft, float srcTop, float srcRight, float srcBottom,
665         float dstLeft, float dstTop, float dstRight, float dstBottom,
666         const SkPaint* paint) {
667    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
668        return;
669    }
670
671    glActiveTexture(GL_TEXTURE0);
672    const Texture* texture = mCaches.textureCache.get(bitmap);
673    if (!texture) return;
674    const AutoTexture autoCleanup(texture);
675
676    const float width = texture->width;
677    const float height = texture->height;
678
679    const float u1 = srcLeft / width;
680    const float v1 = srcTop / height;
681    const float u2 = srcRight / width;
682    const float v2 = srcBottom / height;
683
684    resetDrawTextureTexCoords(u1, v1, u2, v2);
685
686    drawTextureRect(dstLeft, dstTop, dstRight, dstBottom, texture, paint);
687
688    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
689}
690
691void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
692        const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
693        float left, float top, float right, float bottom, const SkPaint* paint) {
694    if (quickReject(left, top, right, bottom)) {
695        return;
696    }
697
698    glActiveTexture(GL_TEXTURE0);
699    const Texture* texture = mCaches.textureCache.get(bitmap);
700    if (!texture) return;
701    const AutoTexture autoCleanup(texture);
702
703    int alpha;
704    SkXfermode::Mode mode;
705    getAlphaAndMode(paint, &alpha, &mode);
706
707    const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
708            right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
709
710    // Specify right and bottom as +1.0f from left/top to prevent scaling since the
711    // patch mesh already defines the final size
712    drawTextureMesh(left, top, left + 1.0f, top + 1.0f, texture->id, alpha / 255.0f,
713            mode, texture->blend, &mesh->vertices[0].position[0],
714            &mesh->vertices[0].texture[0], GL_TRIANGLES, mesh->verticesCount);
715}
716
717void OpenGLRenderer::drawLines(float* points, int count, const SkPaint* paint) {
718    if (mSnapshot->invisible) return;
719
720    int alpha;
721    SkXfermode::Mode mode;
722    getAlphaAndMode(paint, &alpha, &mode);
723
724    uint32_t color = paint->getColor();
725    const GLfloat a = alpha / 255.0f;
726    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
727    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
728    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
729
730    const bool isAA = paint->isAntiAlias();
731    if (isAA) {
732        GLuint textureUnit = 0;
733        setupTextureAlpha8(mCaches.line.getTexture(), 0, 0, textureUnit, 0.0f, 0.0f, r, g, b, a,
734                mode, false, true, mCaches.line.getVertices(), mCaches.line.getTexCoords());
735    } else {
736        setupColorRect(0.0f, 0.0f, 1.0f, 1.0f, r, g, b, a, mode, false);
737    }
738
739    const float strokeWidth = paint->getStrokeWidth();
740    const GLsizei elementsCount = isAA ? mCaches.line.getElementsCount() : gMeshCount;
741    const GLenum drawMode = isAA ? GL_TRIANGLES : GL_TRIANGLE_STRIP;
742
743    for (int i = 0; i < count; i += 4) {
744        float tx = 0.0f;
745        float ty = 0.0f;
746
747        if (isAA) {
748            mCaches.line.update(points[i], points[i + 1], points[i + 2], points[i + 3],
749                    strokeWidth, tx, ty);
750        } else {
751            ty = strokeWidth <= 1.0f ? 0.0f : -strokeWidth * 0.5f;
752        }
753
754        const float dx = points[i + 2] - points[i];
755        const float dy = points[i + 3] - points[i + 1];
756        const float mag = sqrtf(dx * dx + dy * dy);
757        const float angle = acos(dx / mag);
758
759        mModelView.loadTranslate(points[i], points[i + 1], 0.0f);
760        if (angle > MIN_ANGLE || angle < -MIN_ANGLE) {
761            mModelView.rotate(angle * RAD_TO_DEG, 0.0f, 0.0f, 1.0f);
762        }
763        mModelView.translate(tx, ty, 0.0f);
764        if (!isAA) {
765            float length = mCaches.line.getLength(points[i], points[i + 1],
766                    points[i + 2], points[i + 3]);
767            mModelView.scale(length, strokeWidth, 1.0f);
768        }
769        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
770
771        if (mShader) {
772            mShader->updateTransforms(mCaches.currentProgram, mModelView, *mSnapshot);
773        }
774
775        glDrawArrays(drawMode, 0, elementsCount);
776    }
777
778    if (isAA) {
779        glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
780    }
781}
782
783void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
784    const Rect& clip = *mSnapshot->clipRect;
785    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
786}
787
788void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, const SkPaint* p) {
789    if (quickReject(left, top, right, bottom)) {
790        return;
791    }
792
793    SkXfermode::Mode mode;
794    if (!mExtensions.hasFramebufferFetch()) {
795        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
796        if (!isMode) {
797            // Assume SRC_OVER
798            mode = SkXfermode::kSrcOver_Mode;
799        }
800    } else {
801        mode = getXfermode(p->getXfermode());
802    }
803
804    // Skia draws using the color's alpha channel if < 255
805    // Otherwise, it uses the paint's alpha
806    int color = p->getColor();
807    if (((color >> 24) & 0xff) == 255) {
808        color |= p->getAlpha() << 24;
809    }
810
811    drawColorRect(left, top, right, bottom, color, mode);
812}
813
814void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
815        float x, float y, SkPaint* paint) {
816    if (text == NULL || count == 0 || (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) {
817        return;
818    }
819    if (mSnapshot->invisible) return;
820
821    paint->setAntiAlias(true);
822
823    float length = -1.0f;
824    switch (paint->getTextAlign()) {
825        case SkPaint::kCenter_Align:
826            length = paint->measureText(text, bytesCount);
827            x -= length / 2.0f;
828            break;
829        case SkPaint::kRight_Align:
830            length = paint->measureText(text, bytesCount);
831            x -= length;
832            break;
833        default:
834            break;
835    }
836
837    int alpha;
838    SkXfermode::Mode mode;
839    getAlphaAndMode(paint, &alpha, &mode);
840
841    uint32_t color = paint->getColor();
842    const GLfloat a = alpha / 255.0f;
843    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
844    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
845    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
846
847    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
848    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
849            paint->getTextSize());
850
851    if (mHasShadow) {
852        glActiveTexture(gTextureUnits[0]);
853        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
854        const ShadowTexture* shadow = mCaches.dropShadowCache.get(paint, text, bytesCount,
855                count, mShadowRadius);
856        const AutoTexture autoCleanup(shadow);
857
858        setupShadow(shadow, x, y, mode, a);
859
860        // Draw the mesh
861        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
862        glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
863    }
864
865    GLuint textureUnit = 0;
866    glActiveTexture(gTextureUnits[textureUnit]);
867
868    // Assume that the modelView matrix does not force scales, rotates, etc.
869    const bool linearFilter = mSnapshot->transform->changesBounds();
870    setupTextureAlpha8(fontRenderer.getTexture(linearFilter), 0, 0, textureUnit,
871            x, y, r, g, b, a, mode, false, true);
872
873    const Rect& clip = mSnapshot->getLocalClip();
874    clearLayerRegions();
875    fontRenderer.renderText(paint, &clip, text, 0, bytesCount, count, x, y);
876
877    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
878    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
879
880    drawTextDecorations(text, bytesCount, length, x, y, paint);
881}
882
883void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
884    if (mSnapshot->invisible) return;
885
886    GLuint textureUnit = 0;
887    glActiveTexture(gTextureUnits[textureUnit]);
888
889    const PathTexture* texture = mCaches.pathCache.get(path, paint);
890    if (!texture) return;
891    const AutoTexture autoCleanup(texture);
892
893    const float x = texture->left - texture->offset;
894    const float y = texture->top - texture->offset;
895
896    if (quickReject(x, y, x + texture->width, y + texture->height)) {
897        return;
898    }
899
900    int alpha;
901    SkXfermode::Mode mode;
902    getAlphaAndMode(paint, &alpha, &mode);
903
904    uint32_t color = paint->getColor();
905    const GLfloat a = alpha / 255.0f;
906    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
907    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
908    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
909
910    setupTextureAlpha8(texture, textureUnit, x, y, r, g, b, a, mode, true, true);
911
912    clearLayerRegions();
913
914    // Draw the mesh
915    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
916    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
917}
918
919///////////////////////////////////////////////////////////////////////////////
920// Shaders
921///////////////////////////////////////////////////////////////////////////////
922
923void OpenGLRenderer::resetShader() {
924    mShader = NULL;
925}
926
927void OpenGLRenderer::setupShader(SkiaShader* shader) {
928    mShader = shader;
929    if (mShader) {
930        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
931    }
932}
933
934///////////////////////////////////////////////////////////////////////////////
935// Color filters
936///////////////////////////////////////////////////////////////////////////////
937
938void OpenGLRenderer::resetColorFilter() {
939    mColorFilter = NULL;
940}
941
942void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
943    mColorFilter = filter;
944}
945
946///////////////////////////////////////////////////////////////////////////////
947// Drop shadow
948///////////////////////////////////////////////////////////////////////////////
949
950void OpenGLRenderer::resetShadow() {
951    mHasShadow = false;
952}
953
954void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
955    mHasShadow = true;
956    mShadowRadius = radius;
957    mShadowDx = dx;
958    mShadowDy = dy;
959    mShadowColor = color;
960}
961
962///////////////////////////////////////////////////////////////////////////////
963// Drawing implementation
964///////////////////////////////////////////////////////////////////////////////
965
966void OpenGLRenderer::setupShadow(const ShadowTexture* texture, float x, float y,
967        SkXfermode::Mode mode, float alpha) {
968    const float sx = x - texture->left + mShadowDx;
969    const float sy = y - texture->top + mShadowDy;
970
971    const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
972    const GLfloat a = shadowAlpha < 255 ? shadowAlpha / 255.0f : alpha;
973    const GLfloat r = a * ((mShadowColor >> 16) & 0xFF) / 255.0f;
974    const GLfloat g = a * ((mShadowColor >>  8) & 0xFF) / 255.0f;
975    const GLfloat b = a * ((mShadowColor      ) & 0xFF) / 255.0f;
976
977    GLuint textureUnit = 0;
978    setupTextureAlpha8(texture, textureUnit, sx, sy, r, g, b, a, mode, true, false);
979}
980
981void OpenGLRenderer::setupTextureAlpha8(const Texture* texture, GLuint& textureUnit,
982        float x, float y, float r, float g, float b, float a, SkXfermode::Mode mode,
983        bool transforms, bool applyFilters) {
984    setupTextureAlpha8(texture->id, texture->width, texture->height, textureUnit,
985            x, y, r, g, b, a, mode, transforms, applyFilters,
986            &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0]);
987}
988
989void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height,
990        GLuint& textureUnit, float x, float y, float r, float g, float b, float a,
991        SkXfermode::Mode mode, bool transforms, bool applyFilters) {
992    setupTextureAlpha8(texture, width, height, textureUnit,
993            x, y, r, g, b, a, mode, transforms, applyFilters,
994            &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0]);
995}
996
997void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height,
998        GLuint& textureUnit, float x, float y, float r, float g, float b, float a,
999        SkXfermode::Mode mode, bool transforms, bool applyFilters,
1000        GLvoid* vertices, GLvoid* texCoords) {
1001     // Describe the required shaders
1002     ProgramDescription description;
1003     description.hasTexture = true;
1004     description.hasAlpha8Texture = true;
1005     const bool setColor = description.setAlpha8Color(r, g, b, a);
1006
1007     if (applyFilters) {
1008         if (mShader) {
1009             mShader->describe(description, mExtensions);
1010         }
1011         if (mColorFilter) {
1012             mColorFilter->describe(description, mExtensions);
1013         }
1014     }
1015
1016     // Setup the blending mode
1017     chooseBlending(true, mode, description);
1018
1019     // Build and use the appropriate shader
1020     useProgram(mCaches.programCache.get(description));
1021
1022     bindTexture(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, textureUnit);
1023     glUniform1i(mCaches.currentProgram->getUniform("sampler"), textureUnit);
1024
1025     int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1026     glEnableVertexAttribArray(texCoordsSlot);
1027
1028     // Setup attributes
1029     glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1030             gMeshStride, vertices);
1031     glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE,
1032             gMeshStride, texCoords);
1033
1034     // Setup uniforms
1035     if (transforms) {
1036         mModelView.loadTranslate(x, y, 0.0f);
1037         mModelView.scale(width, height, 1.0f);
1038     } else {
1039         mModelView.loadIdentity();
1040     }
1041     mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1042     if (setColor) {
1043         mCaches.currentProgram->setColor(r, g, b, a);
1044     }
1045
1046     textureUnit++;
1047     if (applyFilters) {
1048         // Setup attributes and uniforms required by the shaders
1049         if (mShader) {
1050             mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit);
1051         }
1052         if (mColorFilter) {
1053             mColorFilter->setupProgram(mCaches.currentProgram);
1054         }
1055     }
1056}
1057
1058// Same values used by Skia
1059#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
1060#define kStdUnderline_Offset    (1.0f / 9.0f)
1061#define kStdUnderline_Thickness (1.0f / 18.0f)
1062
1063void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
1064        float x, float y, SkPaint* paint) {
1065    // Handle underline and strike-through
1066    uint32_t flags = paint->getFlags();
1067    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
1068        float underlineWidth = length;
1069        // If length is > 0.0f, we already measured the text for the text alignment
1070        if (length <= 0.0f) {
1071            underlineWidth = paint->measureText(text, bytesCount);
1072        }
1073
1074        float offsetX = 0;
1075        switch (paint->getTextAlign()) {
1076            case SkPaint::kCenter_Align:
1077                offsetX = underlineWidth * 0.5f;
1078                break;
1079            case SkPaint::kRight_Align:
1080                offsetX = underlineWidth;
1081                break;
1082            default:
1083                break;
1084        }
1085
1086        if (underlineWidth > 0.0f) {
1087            const float textSize = paint->getTextSize();
1088            const float strokeWidth = textSize * kStdUnderline_Thickness;
1089
1090            const float left = x - offsetX;
1091            float top = 0.0f;
1092
1093            const int pointsCount = 4 * (flags & SkPaint::kStrikeThruText_Flag ? 2 : 1);
1094            float points[pointsCount];
1095            int currentPoint = 0;
1096
1097            if (flags & SkPaint::kUnderlineText_Flag) {
1098                top = y + textSize * kStdUnderline_Offset;
1099                points[currentPoint++] = left;
1100                points[currentPoint++] = top;
1101                points[currentPoint++] = left + underlineWidth;
1102                points[currentPoint++] = top;
1103            }
1104
1105            if (flags & SkPaint::kStrikeThruText_Flag) {
1106                top = y + textSize * kStdStrikeThru_Offset;
1107                points[currentPoint++] = left;
1108                points[currentPoint++] = top;
1109                points[currentPoint++] = left + underlineWidth;
1110                points[currentPoint++] = top;
1111            }
1112
1113            SkPaint linesPaint(*paint);
1114            linesPaint.setStrokeWidth(strokeWidth);
1115
1116            drawLines(&points[0], pointsCount, &linesPaint);
1117        }
1118    }
1119}
1120
1121void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
1122        int color, SkXfermode::Mode mode, bool ignoreTransform) {
1123    clearLayerRegions();
1124
1125    // If a shader is set, preserve only the alpha
1126    if (mShader) {
1127        color |= 0x00ffffff;
1128    }
1129
1130    // Render using pre-multiplied alpha
1131    const int alpha = (color >> 24) & 0xFF;
1132    const GLfloat a = alpha / 255.0f;
1133    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
1134    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
1135    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
1136
1137    setupColorRect(left, top, right, bottom, r, g, b, a, mode, ignoreTransform);
1138
1139    // Draw the mesh
1140    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1141}
1142
1143void OpenGLRenderer::setupColorRect(float left, float top, float right, float bottom,
1144        float r, float g, float b, float a, SkXfermode::Mode mode, bool ignoreTransform) {
1145    GLuint textureUnit = 0;
1146
1147    // Describe the required shaders
1148    ProgramDescription description;
1149    const bool setColor = description.setColor(r, g, b, a);
1150
1151    if (mShader) {
1152        mShader->describe(description, mExtensions);
1153    }
1154    if (mColorFilter) {
1155        mColorFilter->describe(description, mExtensions);
1156    }
1157
1158    // Setup the blending mode
1159    chooseBlending(a < 1.0f || (mShader && mShader->blend()), mode, description);
1160
1161    // Build and use the appropriate shader
1162    useProgram(mCaches.programCache.get(description));
1163
1164    // Setup attributes
1165    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1166            gMeshStride, &mMeshVertices[0].position[0]);
1167
1168    // Setup uniforms
1169    mModelView.loadTranslate(left, top, 0.0f);
1170    mModelView.scale(right - left, bottom - top, 1.0f);
1171    if (!ignoreTransform) {
1172        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1173    } else {
1174        mat4 identity;
1175        mCaches.currentProgram->set(mOrthoMatrix, mModelView, identity);
1176    }
1177    mCaches.currentProgram->setColor(r, g, b, a);
1178
1179    // Setup attributes and uniforms required by the shaders
1180    if (mShader) {
1181        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit);
1182    }
1183    if (mColorFilter) {
1184        mColorFilter->setupProgram(mCaches.currentProgram);
1185    }
1186}
1187
1188void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1189        const Texture* texture, const SkPaint* paint) {
1190    int alpha;
1191    SkXfermode::Mode mode;
1192    getAlphaAndMode(paint, &alpha, &mode);
1193
1194    drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
1195            texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1196            GL_TRIANGLE_STRIP, gMeshCount);
1197}
1198
1199void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
1200        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
1201    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
1202            &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1203            GL_TRIANGLE_STRIP, gMeshCount);
1204}
1205
1206void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
1207        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
1208        GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
1209        bool swapSrcDst, bool ignoreTransform) {
1210    clearLayerRegions();
1211
1212    ProgramDescription description;
1213    description.hasTexture = true;
1214    const bool setColor = description.setColor(alpha, alpha, alpha, alpha);
1215    if (mColorFilter) {
1216        mColorFilter->describe(description, mExtensions);
1217    }
1218
1219    mModelView.loadTranslate(left, top, 0.0f);
1220    mModelView.scale(right - left, bottom - top, 1.0f);
1221
1222    chooseBlending(blend || alpha < 1.0f, mode, description, swapSrcDst);
1223
1224    useProgram(mCaches.programCache.get(description));
1225    if (!ignoreTransform) {
1226        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
1227    } else {
1228        mat4 m;
1229        mCaches.currentProgram->set(mOrthoMatrix, mModelView, m);
1230    }
1231
1232    // Texture
1233    bindTexture(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, 0);
1234    glUniform1i(mCaches.currentProgram->getUniform("sampler"), 0);
1235
1236    // Always premultiplied
1237    if (setColor) {
1238        mCaches.currentProgram->setColor(alpha, alpha, alpha, alpha);
1239    }
1240
1241    // Mesh
1242    int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
1243    glEnableVertexAttribArray(texCoordsSlot);
1244    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
1245            gMeshStride, vertices);
1246    glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
1247
1248    // Color filter
1249    if (mColorFilter) {
1250        mColorFilter->setupProgram(mCaches.currentProgram);
1251    }
1252
1253    glDrawArrays(drawMode, 0, elementsCount);
1254    glDisableVertexAttribArray(texCoordsSlot);
1255}
1256
1257void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
1258        ProgramDescription& description, bool swapSrcDst) {
1259    blend = blend || mode != SkXfermode::kSrcOver_Mode;
1260    if (blend) {
1261        if (mode < SkXfermode::kPlus_Mode) {
1262            if (!mCaches.blend) {
1263                glEnable(GL_BLEND);
1264            }
1265
1266            GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
1267            GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
1268
1269            if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
1270                glBlendFunc(sourceMode, destMode);
1271                mCaches.lastSrcMode = sourceMode;
1272                mCaches.lastDstMode = destMode;
1273            }
1274        } else {
1275            // These blend modes are not supported by OpenGL directly and have
1276            // to be implemented using shaders. Since the shader will perform
1277            // the blending, turn blending off here
1278            if (mExtensions.hasFramebufferFetch()) {
1279                description.framebufferMode = mode;
1280                description.swapSrcDst = swapSrcDst;
1281            }
1282
1283            if (mCaches.blend) {
1284                glDisable(GL_BLEND);
1285            }
1286            blend = false;
1287        }
1288    } else if (mCaches.blend) {
1289        glDisable(GL_BLEND);
1290    }
1291    mCaches.blend = blend;
1292}
1293
1294bool OpenGLRenderer::useProgram(Program* program) {
1295    if (!program->isInUse()) {
1296        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
1297        program->use();
1298        mCaches.currentProgram = program;
1299        return false;
1300    }
1301    return true;
1302}
1303
1304void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
1305    TextureVertex* v = &mMeshVertices[0];
1306    TextureVertex::setUV(v++, u1, v1);
1307    TextureVertex::setUV(v++, u2, v1);
1308    TextureVertex::setUV(v++, u1, v2);
1309    TextureVertex::setUV(v++, u2, v2);
1310}
1311
1312void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
1313    if (paint) {
1314        if (!mExtensions.hasFramebufferFetch()) {
1315            const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
1316            if (!isMode) {
1317                // Assume SRC_OVER
1318                *mode = SkXfermode::kSrcOver_Mode;
1319            }
1320        } else {
1321            *mode = getXfermode(paint->getXfermode());
1322        }
1323
1324        // Skia draws using the color's alpha channel if < 255
1325        // Otherwise, it uses the paint's alpha
1326        int color = paint->getColor();
1327        *alpha = (color >> 24) & 0xFF;
1328        if (*alpha == 255) {
1329            *alpha = paint->getAlpha();
1330        }
1331    } else {
1332        *mode = SkXfermode::kSrcOver_Mode;
1333        *alpha = 255;
1334    }
1335}
1336
1337SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
1338    if (mode == NULL) {
1339        return SkXfermode::kSrcOver_Mode;
1340    }
1341    return mode->fMode;
1342}
1343
1344void OpenGLRenderer::bindTexture(GLuint texture, GLenum wrapS, GLenum wrapT, GLuint textureUnit) {
1345    glActiveTexture(gTextureUnits[textureUnit]);
1346    glBindTexture(GL_TEXTURE_2D, texture);
1347    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
1348    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
1349}
1350
1351}; // namespace uirenderer
1352}; // namespace android
1353