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