OpenGLRenderer.cpp revision 2bffd268f135df8308c9e67af110525a5c463424
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
28#include "OpenGLRenderer.h"
29
30namespace android {
31namespace uirenderer {
32
33///////////////////////////////////////////////////////////////////////////////
34// Defines
35///////////////////////////////////////////////////////////////////////////////
36
37#define REQUIRED_TEXTURE_UNITS_COUNT 3
38
39// Generates simple and textured vertices
40#define FV(x, y, u, v) { { x, y }, { u, v } }
41
42///////////////////////////////////////////////////////////////////////////////
43// Globals
44///////////////////////////////////////////////////////////////////////////////
45
46// This array is never used directly but used as a memcpy source in the
47// OpenGLRenderer constructor
48static const TextureVertex gMeshVertices[] = {
49        FV(0.0f, 0.0f, 0.0f, 0.0f),
50        FV(1.0f, 0.0f, 1.0f, 0.0f),
51        FV(0.0f, 1.0f, 0.0f, 1.0f),
52        FV(1.0f, 1.0f, 1.0f, 1.0f)
53};
54static const GLsizei gMeshStride = sizeof(TextureVertex);
55static const GLsizei gMeshCount = 4;
56
57/**
58 * Structure mapping Skia xfermodes to OpenGL blending factors.
59 */
60struct Blender {
61    SkXfermode::Mode mode;
62    GLenum src;
63    GLenum dst;
64}; // struct Blender
65
66// In this array, the index of each Blender equals the value of the first
67// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
68static const Blender gBlends[] = {
69        { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
70        { SkXfermode::kSrc_Mode,     GL_ONE,                  GL_ZERO },
71        { SkXfermode::kDst_Mode,     GL_ZERO,                 GL_ONE },
72        { SkXfermode::kSrcOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
73        { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
74        { SkXfermode::kSrcIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
75        { SkXfermode::kDstIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
76        { SkXfermode::kSrcOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
77        { SkXfermode::kDstOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
78        { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
79        { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
80        { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
81};
82
83static const Blender gBlendsSwap[] = {
84        { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
85        { SkXfermode::kSrc_Mode,     GL_ZERO,                 GL_ONE },
86        { SkXfermode::kDst_Mode,     GL_ONE,                  GL_ZERO },
87        { SkXfermode::kSrcOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
88        { SkXfermode::kDstOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
89        { SkXfermode::kSrcIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
90        { SkXfermode::kDstIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
91        { SkXfermode::kSrcOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
92        { SkXfermode::kDstOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
93        { SkXfermode::kSrcATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
94        { SkXfermode::kDstATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
95        { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
96};
97
98static const GLenum gTextureUnits[] = {
99        GL_TEXTURE0,
100        GL_TEXTURE1,
101        GL_TEXTURE2
102};
103
104///////////////////////////////////////////////////////////////////////////////
105// Constructors/destructor
106///////////////////////////////////////////////////////////////////////////////
107
108OpenGLRenderer::OpenGLRenderer(): mCaches(Caches::getInstance()) {
109    LOGD("Create OpenGLRenderer");
110
111    mShader = NULL;
112    mColorFilter = NULL;
113    mHasShadow = false;
114
115    memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices));
116
117    mFirstSnapshot = new Snapshot;
118
119    GLint maxTextureUnits;
120    glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxTextureUnits);
121    if (maxTextureUnits < REQUIRED_TEXTURE_UNITS_COUNT) {
122        LOGW("At least %d texture units are required!", REQUIRED_TEXTURE_UNITS_COUNT);
123    }
124}
125
126OpenGLRenderer::~OpenGLRenderer() {
127    LOGD("Destroy OpenGLRenderer");
128}
129
130///////////////////////////////////////////////////////////////////////////////
131// Setup
132///////////////////////////////////////////////////////////////////////////////
133
134void OpenGLRenderer::setViewport(int width, int height) {
135    glViewport(0, 0, width, height);
136    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
137
138    mWidth = width;
139    mHeight = height;
140}
141
142void OpenGLRenderer::prepare() {
143    mSnapshot = new Snapshot(mFirstSnapshot,
144            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
145    mSaveCount = 1;
146
147    glViewport(0, 0, mWidth, mHeight);
148
149    glDisable(GL_DITHER);
150    glDisable(GL_SCISSOR_TEST);
151
152    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
153    glClear(GL_COLOR_BUFFER_BIT);
154
155    glEnable(GL_SCISSOR_TEST);
156    glScissor(0, 0, mWidth, mHeight);
157
158    mSnapshot->setClip(0.0f, 0.0f, mWidth, mHeight);
159}
160
161void OpenGLRenderer::acquireContext() {
162    if (mCaches.currentProgram) {
163        if (mCaches.currentProgram->isInUse()) {
164            mCaches.currentProgram->remove();
165            mCaches.currentProgram = NULL;
166        }
167    }
168}
169
170void OpenGLRenderer::releaseContext() {
171    glViewport(0, 0, mWidth, mHeight);
172
173    glEnable(GL_SCISSOR_TEST);
174    setScissorFromClip();
175
176    glDisable(GL_DITHER);
177
178    glBindFramebuffer(GL_FRAMEBUFFER, 0);
179
180    if (mCaches.blend) {
181        glEnable(GL_BLEND);
182        glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode);
183        glBlendEquation(GL_FUNC_ADD);
184    } else {
185        glDisable(GL_BLEND);
186    }
187}
188
189///////////////////////////////////////////////////////////////////////////////
190// State management
191///////////////////////////////////////////////////////////////////////////////
192
193int OpenGLRenderer::getSaveCount() const {
194    return mSaveCount;
195}
196
197int OpenGLRenderer::save(int flags) {
198    return saveSnapshot(flags);
199}
200
201void OpenGLRenderer::restore() {
202    if (mSaveCount > 1) {
203        restoreSnapshot();
204    }
205}
206
207void OpenGLRenderer::restoreToCount(int saveCount) {
208    if (saveCount < 1) saveCount = 1;
209
210    while (mSaveCount > saveCount) {
211        restoreSnapshot();
212    }
213}
214
215int OpenGLRenderer::saveSnapshot(int flags) {
216    mSnapshot = new Snapshot(mSnapshot, flags);
217    return mSaveCount++;
218}
219
220bool OpenGLRenderer::restoreSnapshot() {
221    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
222    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
223
224    sp<Snapshot> current = mSnapshot;
225    sp<Snapshot> previous = mSnapshot->previous;
226
227    mSaveCount--;
228    mSnapshot = previous;
229
230    if (restoreLayer) {
231        composeLayer(current, previous);
232    }
233
234    if (restoreClip) {
235        setScissorFromClip();
236    }
237
238    return restoreClip;
239}
240
241///////////////////////////////////////////////////////////////////////////////
242// Layers
243///////////////////////////////////////////////////////////////////////////////
244
245int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
246        const SkPaint* p, int flags) {
247    int count = saveSnapshot(flags);
248
249    int alpha = 255;
250    SkXfermode::Mode mode;
251
252    if (p) {
253        alpha = p->getAlpha();
254        if (!mExtensions.hasFramebufferFetch()) {
255            const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
256            if (!isMode) {
257                // Assume SRC_OVER
258                mode = SkXfermode::kSrcOver_Mode;
259            }
260        } else {
261            mode = getXfermode(p->getXfermode());
262        }
263    } else {
264        mode = SkXfermode::kSrcOver_Mode;
265    }
266
267    createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags);
268
269    return count;
270}
271
272int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
273        int alpha, int flags) {
274    if (alpha == 0xff) {
275        return saveLayer(left, top, right, bottom, NULL, flags);
276    } else {
277        SkPaint paint;
278        paint.setAlpha(alpha);
279        return saveLayer(left, top, right, bottom, &paint, flags);
280    }
281}
282
283bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
284        float right, float bottom, int alpha, SkXfermode::Mode mode,int flags) {
285    LAYER_LOGD("Requesting layer %fx%f", right - left, bottom - top);
286    LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
287
288    // Window coordinates of the layer
289    Rect bounds(left, top, right, bottom);
290    mSnapshot->transform->mapRect(bounds);
291
292    LayerSize size(bounds.getWidth(), bounds.getHeight());
293
294    Layer* layer = mCaches.layerCache.get(size);
295    if (!layer) {
296        return false;
297    }
298
299    layer->mode = mode;
300    layer->alpha = alpha;
301    layer->layer.set(bounds);
302
303    // Save the layer in the snapshot
304    snapshot->flags |= Snapshot::kFlagIsLayer;
305    snapshot->layer = layer;
306
307    // Copy the framebuffer into the layer
308    glBindTexture(GL_TEXTURE_2D, layer->texture);
309    glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.left, mHeight - bounds.bottom,
310            bounds.getWidth(), bounds.getHeight(), 0);
311
312    if (flags & SkCanvas::kClipToLayer_SaveFlag) {
313        if (mSnapshot->clipTransformed(bounds)) setScissorFromClip();
314    }
315
316    // Enqueue the buffer coordinates to clear the corresponding region later
317    mLayers.push(new Rect(bounds));
318
319    return true;
320}
321
322void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
323    if (!current->layer) {
324        LOGE("Attempting to compose a layer that does not exist");
325        return;
326    }
327
328    // Restore the clip from the previous snapshot
329    const Rect& clip = *previous->clipRect;
330    glScissor(clip.left, mHeight - clip.bottom, clip.getWidth(), clip.getHeight());
331
332    Layer* layer = current->layer;
333    const Rect& rect = layer->layer;
334
335    if (layer->alpha < 255) {
336        glEnable(GL_BLEND);
337        glBlendFuncSeparate(GL_ZERO, GL_SRC_ALPHA, GL_DST_ALPHA, GL_ZERO);
338
339        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
340                layer->alpha << 24, SkXfermode::kSrcOver_Mode, true, true);
341
342        glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode);
343        if (!mCaches.blend) {
344            glDisable(GL_BLEND);
345        }
346    }
347
348    // Layers are already drawn with a top-left origin, don't flip the texture
349    resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f);
350
351    drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture,
352            1.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0],
353            &mMeshVertices[0].texture[0], NULL, 0, true, true);
354
355    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
356
357    LayerSize size(rect.getWidth(), rect.getHeight());
358    // Failing to add the layer to the cache should happen only if the
359    // layer is too large
360    if (!mCaches.layerCache.put(size, layer)) {
361        LAYER_LOGD("Deleting layer");
362
363        glDeleteTextures(1, &layer->texture);
364
365        delete layer;
366    }
367}
368
369void OpenGLRenderer::clearLayerRegions() {
370    if (mLayers.size() == 0) return;
371
372    for (uint32_t i = 0; i < mLayers.size(); i++) {
373        Rect* bounds = mLayers.itemAt(i);
374
375        // Clear the framebuffer where the layer will draw
376        glScissor(bounds->left, mHeight - bounds->bottom,
377                bounds->getWidth(), bounds->getHeight());
378        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
379        glClear(GL_COLOR_BUFFER_BIT);
380
381        delete bounds;
382    }
383    mLayers.clear();
384
385    // Restore the clip
386    setScissorFromClip();
387}
388
389///////////////////////////////////////////////////////////////////////////////
390// Transforms
391///////////////////////////////////////////////////////////////////////////////
392
393void OpenGLRenderer::translate(float dx, float dy) {
394    mSnapshot->transform->translate(dx, dy, 0.0f);
395}
396
397void OpenGLRenderer::rotate(float degrees) {
398    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
399}
400
401void OpenGLRenderer::scale(float sx, float sy) {
402    mSnapshot->transform->scale(sx, sy, 1.0f);
403}
404
405void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
406    mSnapshot->transform->load(*matrix);
407}
408
409void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
410    mSnapshot->transform->copyTo(*matrix);
411}
412
413void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
414    mat4 m(*matrix);
415    mSnapshot->transform->multiply(m);
416}
417
418///////////////////////////////////////////////////////////////////////////////
419// Clipping
420///////////////////////////////////////////////////////////////////////////////
421
422void OpenGLRenderer::setScissorFromClip() {
423    const Rect& clip = *mSnapshot->clipRect;
424    glScissor(clip.left, mHeight - clip.bottom, clip.getWidth(), clip.getHeight());
425}
426
427const Rect& OpenGLRenderer::getClipBounds() {
428    return mSnapshot->getLocalClip();
429}
430
431bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
432    Rect r(left, top, right, bottom);
433    mSnapshot->transform->mapRect(r);
434    return !mSnapshot->clipRect->intersects(r);
435}
436
437bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
438    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
439    if (clipped) {
440        setScissorFromClip();
441    }
442    return !mSnapshot->clipRect->isEmpty();
443}
444
445///////////////////////////////////////////////////////////////////////////////
446// Drawing
447///////////////////////////////////////////////////////////////////////////////
448
449void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, const SkPaint* paint) {
450    const float right = left + bitmap->width();
451    const float bottom = top + bitmap->height();
452
453    if (quickReject(left, top, right, bottom)) {
454        return;
455    }
456
457    glActiveTexture(GL_TEXTURE0);
458    const Texture* texture = mCaches.textureCache.get(bitmap);
459    if (!texture) return;
460    const AutoTexture autoCleanup(texture);
461
462    drawTextureRect(left, top, right, bottom, texture, paint);
463}
464
465void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, const SkMatrix* matrix, const SkPaint* paint) {
466    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
467    const mat4 transform(*matrix);
468    transform.mapRect(r);
469
470    if (quickReject(r.left, r.top, r.right, r.bottom)) {
471        return;
472    }
473
474    glActiveTexture(GL_TEXTURE0);
475    const Texture* texture = mCaches.textureCache.get(bitmap);
476    if (!texture) return;
477    const AutoTexture autoCleanup(texture);
478
479    drawTextureRect(r.left, r.top, r.right, r.bottom, texture, paint);
480}
481
482void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
483         float srcLeft, float srcTop, float srcRight, float srcBottom,
484         float dstLeft, float dstTop, float dstRight, float dstBottom,
485         const SkPaint* paint) {
486    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
487        return;
488    }
489
490    glActiveTexture(GL_TEXTURE0);
491    const Texture* texture = mCaches.textureCache.get(bitmap);
492    if (!texture) return;
493    const AutoTexture autoCleanup(texture);
494
495    const float width = texture->width;
496    const float height = texture->height;
497
498    const float u1 = srcLeft / width;
499    const float v1 = srcTop / height;
500    const float u2 = srcRight / width;
501    const float v2 = srcBottom / height;
502
503    resetDrawTextureTexCoords(u1, v1, u2, v2);
504
505    drawTextureRect(dstLeft, dstTop, dstRight, dstBottom, texture, paint);
506
507    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
508}
509
510void OpenGLRenderer::drawPatch(SkBitmap* bitmap, Res_png_9patch* patch,
511        float left, float top, float right, float bottom, const SkPaint* paint) {
512    if (quickReject(left, top, right, bottom)) {
513        return;
514    }
515
516    glActiveTexture(GL_TEXTURE0);
517    const Texture* texture = mCaches.textureCache.get(bitmap);
518    if (!texture) return;
519    const AutoTexture autoCleanup(texture);
520
521    int alpha;
522    SkXfermode::Mode mode;
523    getAlphaAndMode(paint, &alpha, &mode);
524
525    Patch* mesh = mCaches.patchCache.get(patch);
526    mesh->updateVertices(bitmap, left, top, right, bottom,
527            &patch->xDivs[0], &patch->yDivs[0], patch->numXDivs, patch->numYDivs);
528
529    // Specify right and bottom as +1.0f from left/top to prevent scaling since the
530    // patch mesh already defines the final size
531    drawTextureMesh(left, top, left + 1.0f, top + 1.0f, texture->id, alpha / 255.0f,
532            mode, texture->blend, &mesh->vertices[0].position[0],
533            &mesh->vertices[0].texture[0], mesh->indices, mesh->indicesCount);
534}
535
536void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
537    const Rect& clip = *mSnapshot->clipRect;
538    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
539}
540
541void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, const SkPaint* p) {
542    if (quickReject(left, top, right, bottom)) {
543        return;
544    }
545
546    SkXfermode::Mode mode;
547    if (!mExtensions.hasFramebufferFetch()) {
548        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
549        if (!isMode) {
550            // Assume SRC_OVER
551            mode = SkXfermode::kSrcOver_Mode;
552        }
553    } else {
554        mode = getXfermode(p->getXfermode());
555    }
556
557    // Skia draws using the color's alpha channel if < 255
558    // Otherwise, it uses the paint's alpha
559    int color = p->getColor();
560    if (((color >> 24) & 0xff) == 255) {
561        color |= p->getAlpha() << 24;
562    }
563
564    drawColorRect(left, top, right, bottom, color, mode);
565}
566
567void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
568        float x, float y, SkPaint* paint) {
569    if (text == NULL || count == 0 || (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) {
570        return;
571    }
572    paint->setAntiAlias(true);
573
574    float length = -1.0f;
575    switch (paint->getTextAlign()) {
576        case SkPaint::kCenter_Align:
577            length = paint->measureText(text, bytesCount);
578            x -= length / 2.0f;
579            break;
580        case SkPaint::kRight_Align:
581            length = paint->measureText(text, bytesCount);
582            x -= length;
583            break;
584        default:
585            break;
586    }
587
588    int alpha;
589    SkXfermode::Mode mode;
590    getAlphaAndMode(paint, &alpha, &mode);
591
592    uint32_t color = paint->getColor();
593    const GLfloat a = alpha / 255.0f;
594    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
595    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
596    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
597
598    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
599    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
600            paint->getTextSize());
601    if (mHasShadow) {
602        glActiveTexture(gTextureUnits[0]);
603        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
604        const ShadowTexture* shadow = mCaches.dropShadowCache.get(paint, text, bytesCount,
605                count, mShadowRadius);
606        const AutoTexture autoCleanup(shadow);
607
608        setupShadow(shadow, x, y, mode, a);
609
610        // Draw the mesh
611        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
612        glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
613    }
614
615    GLuint textureUnit = 0;
616    glActiveTexture(gTextureUnits[textureUnit]);
617
618    setupTextureAlpha8(fontRenderer.getTexture(), 0, 0, textureUnit, x, y, r, g, b, a,
619            mode, false, true);
620
621    const Rect& clip = mSnapshot->getLocalClip();
622    clearLayerRegions();
623    fontRenderer.renderText(paint, &clip, text, 0, bytesCount, count, x, y);
624
625    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
626    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
627
628    drawTextDecorations(text, bytesCount, length, x, y, paint);
629}
630
631void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
632    GLuint textureUnit = 0;
633    glActiveTexture(gTextureUnits[textureUnit]);
634
635    const PathTexture* texture = mCaches.pathCache.get(path, paint);
636    if (!texture) return;
637    const AutoTexture autoCleanup(texture);
638
639    const float x = texture->left - texture->offset;
640    const float y = texture->top - texture->offset;
641
642    if (quickReject(x, y, x + texture->width, y + texture->height)) {
643        return;
644    }
645
646    int alpha;
647    SkXfermode::Mode mode;
648    getAlphaAndMode(paint, &alpha, &mode);
649
650    uint32_t color = paint->getColor();
651    const GLfloat a = alpha / 255.0f;
652    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
653    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
654    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
655
656    setupTextureAlpha8(texture, textureUnit, x, y, r, g, b, a, mode, true, true);
657
658    clearLayerRegions();
659
660    // Draw the mesh
661    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
662    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
663}
664
665///////////////////////////////////////////////////////////////////////////////
666// Shaders
667///////////////////////////////////////////////////////////////////////////////
668
669void OpenGLRenderer::resetShader() {
670    mShader = NULL;
671}
672
673void OpenGLRenderer::setupShader(SkiaShader* shader) {
674    mShader = shader;
675    if (mShader) {
676        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
677    }
678}
679
680///////////////////////////////////////////////////////////////////////////////
681// Color filters
682///////////////////////////////////////////////////////////////////////////////
683
684void OpenGLRenderer::resetColorFilter() {
685    mColorFilter = NULL;
686}
687
688void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
689    mColorFilter = filter;
690}
691
692///////////////////////////////////////////////////////////////////////////////
693// Drop shadow
694///////////////////////////////////////////////////////////////////////////////
695
696void OpenGLRenderer::resetShadow() {
697    mHasShadow = false;
698}
699
700void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
701    mHasShadow = true;
702    mShadowRadius = radius;
703    mShadowDx = dx;
704    mShadowDy = dy;
705    mShadowColor = color;
706}
707
708///////////////////////////////////////////////////////////////////////////////
709// Drawing implementation
710///////////////////////////////////////////////////////////////////////////////
711
712void OpenGLRenderer::setupShadow(const ShadowTexture* texture, float x, float y,
713        SkXfermode::Mode mode, float alpha) {
714    const float sx = x - texture->left + mShadowDx;
715    const float sy = y - texture->top + mShadowDy;
716
717    const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
718    const GLfloat a = shadowAlpha < 255 ? shadowAlpha / 255.0f : alpha;
719    const GLfloat r = a * ((mShadowColor >> 16) & 0xFF) / 255.0f;
720    const GLfloat g = a * ((mShadowColor >>  8) & 0xFF) / 255.0f;
721    const GLfloat b = a * ((mShadowColor      ) & 0xFF) / 255.0f;
722
723    GLuint textureUnit = 0;
724    setupTextureAlpha8(texture, textureUnit, sx, sy, r, g, b, a, mode, true, false);
725}
726
727void OpenGLRenderer::setupTextureAlpha8(const Texture* texture, GLuint& textureUnit,
728        float x, float y, float r, float g, float b, float a, SkXfermode::Mode mode,
729        bool transforms, bool applyFilters) {
730    setupTextureAlpha8(texture->id, texture->width, texture->height, textureUnit,
731            x, y, r, g, b, a, mode, transforms, applyFilters);
732}
733
734void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height,
735        GLuint& textureUnit, float x, float y, float r, float g, float b, float a,
736        SkXfermode::Mode mode, bool transforms, bool applyFilters) {
737     // Describe the required shaders
738     ProgramDescription description;
739     description.hasTexture = true;
740     description.hasAlpha8Texture = true;
741
742     if (applyFilters) {
743         if (mShader) {
744             mShader->describe(description, mExtensions);
745         }
746         if (mColorFilter) {
747             mColorFilter->describe(description, mExtensions);
748         }
749     }
750
751     // Setup the blending mode
752     chooseBlending(true, mode, description);
753
754     // Build and use the appropriate shader
755     useProgram(mCaches.programCache.get(description));
756
757     bindTexture(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, textureUnit);
758     glUniform1i(mCaches.currentProgram->getUniform("sampler"), textureUnit);
759
760     int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
761     glEnableVertexAttribArray(texCoordsSlot);
762
763     // Setup attributes
764     glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
765             gMeshStride, &mMeshVertices[0].position[0]);
766     glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE,
767             gMeshStride, &mMeshVertices[0].texture[0]);
768
769     // Setup uniforms
770     if (transforms) {
771         mModelView.loadTranslate(x, y, 0.0f);
772         mModelView.scale(width, height, 1.0f);
773     } else {
774         mModelView.loadIdentity();
775     }
776     mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
777     glUniform4f(mCaches.currentProgram->color, r, g, b, a);
778
779     textureUnit++;
780     if (applyFilters) {
781         // Setup attributes and uniforms required by the shaders
782         if (mShader) {
783             mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit);
784         }
785         if (mColorFilter) {
786             mColorFilter->setupProgram(mCaches.currentProgram);
787         }
788     }
789}
790
791// Same values used by Skia
792#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
793#define kStdUnderline_Offset    (1.0f / 9.0f)
794#define kStdUnderline_Thickness (1.0f / 18.0f)
795
796void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
797        float x, float y, SkPaint* paint) {
798    // Handle underline and strike-through
799    uint32_t flags = paint->getFlags();
800    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
801        float underlineWidth = length;
802        // If length is > 0.0f, we already measured the text for the text alignment
803        if (length <= 0.0f) {
804            underlineWidth = paint->measureText(text, bytesCount);
805        }
806
807        float offsetX = 0;
808        switch (paint->getTextAlign()) {
809            case SkPaint::kCenter_Align:
810                offsetX = underlineWidth * 0.5f;
811                break;
812            case SkPaint::kRight_Align:
813                offsetX = underlineWidth;
814                break;
815            default:
816                break;
817        }
818
819        if (underlineWidth > 0.0f) {
820            float textSize = paint->getTextSize();
821            float height = textSize * kStdUnderline_Thickness;
822
823            float left = x - offsetX;
824            float top = 0.0f;
825            float right = left + underlineWidth;
826            float bottom = 0.0f;
827
828            if (flags & SkPaint::kUnderlineText_Flag) {
829                top = y + textSize * kStdUnderline_Offset;
830                bottom = top + height;
831                drawRect(left, top, right, bottom, paint);
832            }
833
834            if (flags & SkPaint::kStrikeThruText_Flag) {
835                top = y + textSize * kStdStrikeThru_Offset;
836                bottom = top + height;
837                drawRect(left, top, right, bottom, paint);
838            }
839        }
840    }
841}
842
843void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
844        int color, SkXfermode::Mode mode, bool ignoreTransform, bool ignoreBlending) {
845    clearLayerRegions();
846
847    // If a shader is set, preserve only the alpha
848    if (mShader) {
849        color |= 0x00ffffff;
850    }
851
852    // Render using pre-multiplied alpha
853    const int alpha = (color >> 24) & 0xFF;
854    const GLfloat a = alpha / 255.0f;
855    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
856    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
857    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
858
859    GLuint textureUnit = 0;
860
861    // Describe the required shaders
862    ProgramDescription description;
863    if (mShader) {
864        mShader->describe(description, mExtensions);
865    }
866    if (mColorFilter) {
867        mColorFilter->describe(description, mExtensions);
868    }
869
870    if (!ignoreBlending) {
871        // Setup the blending mode
872        chooseBlending(alpha < 255 || (mShader && mShader->blend()), mode, description);
873    }
874
875    // Build and use the appropriate shader
876    useProgram(mCaches.programCache.get(description));
877
878    // Setup attributes
879    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
880            gMeshStride, &mMeshVertices[0].position[0]);
881
882    // Setup uniforms
883    mModelView.loadTranslate(left, top, 0.0f);
884    mModelView.scale(right - left, bottom - top, 1.0f);
885    if (!ignoreTransform) {
886        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
887    } else {
888        mat4 identity;
889        mCaches.currentProgram->set(mOrthoMatrix, mModelView, identity);
890    }
891    glUniform4f(mCaches.currentProgram->color, r, g, b, a);
892
893    // Setup attributes and uniforms required by the shaders
894    if (mShader) {
895        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit);
896    }
897    if (mColorFilter) {
898        mColorFilter->setupProgram(mCaches.currentProgram);
899    }
900
901    // Draw the mesh
902    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
903}
904
905void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
906        const Texture* texture, const SkPaint* paint) {
907    int alpha;
908    SkXfermode::Mode mode;
909    getAlphaAndMode(paint, &alpha, &mode);
910
911    drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode, texture->blend,
912            &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], NULL);
913}
914
915void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
916        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
917    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
918            &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], NULL);
919}
920
921void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
922        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
923        GLvoid* vertices, GLvoid* texCoords, GLvoid* indices, GLsizei elementsCount,
924        bool swapSrcDst, bool ignoreTransform) {
925    clearLayerRegions();
926
927    ProgramDescription description;
928    description.hasTexture = true;
929    if (mColorFilter) {
930        mColorFilter->describe(description, mExtensions);
931    }
932
933    mModelView.loadTranslate(left, top, 0.0f);
934    mModelView.scale(right - left, bottom - top, 1.0f);
935
936    chooseBlending(blend || alpha < 1.0f, mode, description, swapSrcDst);
937
938    useProgram(mCaches.programCache.get(description));
939    if (!ignoreTransform) {
940        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
941    } else {
942        mat4 m;
943        mCaches.currentProgram->set(mOrthoMatrix, mModelView, m);
944    }
945
946    // Texture
947    bindTexture(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, 0);
948    glUniform1i(mCaches.currentProgram->getUniform("sampler"), 0);
949
950    // Always premultiplied
951    glUniform4f(mCaches.currentProgram->color, alpha, alpha, alpha, alpha);
952
953    // Mesh
954    int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
955    glEnableVertexAttribArray(texCoordsSlot);
956    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
957            gMeshStride, vertices);
958    glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
959
960    // Color filter
961    if (mColorFilter) {
962        mColorFilter->setupProgram(mCaches.currentProgram);
963    }
964
965    if (!indices) {
966        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
967    } else {
968        glDrawElements(GL_TRIANGLES, elementsCount, GL_UNSIGNED_SHORT, indices);
969    }
970    glDisableVertexAttribArray(texCoordsSlot);
971}
972
973void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
974        ProgramDescription& description, bool swapSrcDst) {
975    blend = blend || mode != SkXfermode::kSrcOver_Mode;
976    if (blend) {
977        if (mode < SkXfermode::kPlus_Mode) {
978            if (!mCaches.blend) {
979                glEnable(GL_BLEND);
980            }
981
982            GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
983            GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
984
985            if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
986                glBlendFunc(sourceMode, destMode);
987                mCaches.lastSrcMode = sourceMode;
988                mCaches.lastDstMode = destMode;
989            }
990        } else {
991            // These blend modes are not supported by OpenGL directly and have
992            // to be implemented using shaders. Since the shader will perform
993            // the blending, turn blending off here
994            if (mExtensions.hasFramebufferFetch()) {
995                description.framebufferMode = mode;
996                description.swapSrcDst = swapSrcDst;
997            }
998
999            if (mCaches.blend) {
1000                glDisable(GL_BLEND);
1001            }
1002            blend = false;
1003        }
1004    } else if (mCaches.blend) {
1005        glDisable(GL_BLEND);
1006    }
1007    mCaches.blend = blend;
1008}
1009
1010bool OpenGLRenderer::useProgram(Program* program) {
1011    if (!program->isInUse()) {
1012        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
1013        program->use();
1014        mCaches.currentProgram = program;
1015        return false;
1016    }
1017    return true;
1018}
1019
1020void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
1021    TextureVertex* v = &mMeshVertices[0];
1022    TextureVertex::setUV(v++, u1, v1);
1023    TextureVertex::setUV(v++, u2, v1);
1024    TextureVertex::setUV(v++, u1, v2);
1025    TextureVertex::setUV(v++, u2, v2);
1026}
1027
1028void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
1029    if (paint) {
1030        if (!mExtensions.hasFramebufferFetch()) {
1031            const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
1032            if (!isMode) {
1033                // Assume SRC_OVER
1034                *mode = SkXfermode::kSrcOver_Mode;
1035            }
1036        } else {
1037            *mode = getXfermode(paint->getXfermode());
1038        }
1039
1040        // Skia draws using the color's alpha channel if < 255
1041        // Otherwise, it uses the paint's alpha
1042        int color = paint->getColor();
1043        *alpha = (color >> 24) & 0xFF;
1044        if (*alpha == 255) {
1045            *alpha = paint->getAlpha();
1046        }
1047    } else {
1048        *mode = SkXfermode::kSrcOver_Mode;
1049        *alpha = 255;
1050    }
1051}
1052
1053SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
1054    if (mode == NULL) {
1055        return SkXfermode::kSrcOver_Mode;
1056    }
1057    return mode->fMode;
1058}
1059
1060void OpenGLRenderer::bindTexture(GLuint texture, GLenum wrapS, GLenum wrapT, GLuint textureUnit) {
1061    glActiveTexture(gTextureUnits[textureUnit]);
1062    glBindTexture(GL_TEXTURE_2D, texture);
1063    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
1064    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
1065}
1066
1067}; // namespace uirenderer
1068}; // namespace android
1069