OpenGLRenderer.cpp revision 8411f336c786379c5a03106e9ed3bc8622b579a5
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    // Layers only make sense if they are in the framebuffer's bounds
293    bounds.intersect(*mSnapshot->clipRect);
294    if (bounds.isEmpty()) return;
295
296    LayerSize size(bounds.getWidth(), bounds.getHeight());
297    Layer* layer = mCaches.layerCache.get(size);
298    if (!layer) {
299        return false;
300    }
301
302    layer->mode = mode;
303    layer->alpha = alpha;
304    layer->layer.set(bounds);
305
306    // Save the layer in the snapshot
307    snapshot->flags |= Snapshot::kFlagIsLayer;
308    snapshot->layer = layer;
309
310    // Copy the framebuffer into the layer
311    glBindTexture(GL_TEXTURE_2D, layer->texture);
312    glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.left, mHeight - bounds.bottom,
313            bounds.getWidth(), bounds.getHeight(), 0);
314
315    if (flags & SkCanvas::kClipToLayer_SaveFlag) {
316        if (mSnapshot->clipTransformed(bounds)) setScissorFromClip();
317    }
318
319    // Enqueue the buffer coordinates to clear the corresponding region later
320    mLayers.push(new Rect(bounds));
321
322    return true;
323}
324
325void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
326    if (!current->layer) {
327        LOGE("Attempting to compose a layer that does not exist");
328        return;
329    }
330
331    // Restore the clip from the previous snapshot
332    const Rect& clip = *previous->clipRect;
333    glScissor(clip.left, mHeight - clip.bottom, clip.getWidth(), clip.getHeight());
334
335    Layer* layer = current->layer;
336    const Rect& rect = layer->layer;
337
338    if (layer->alpha < 255) {
339        glEnable(GL_BLEND);
340        glBlendFuncSeparate(GL_ZERO, GL_SRC_ALPHA, GL_DST_ALPHA, GL_ZERO);
341
342        drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
343                layer->alpha << 24, SkXfermode::kSrcOver_Mode, true, true);
344
345        glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode);
346        if (!mCaches.blend) {
347            glDisable(GL_BLEND);
348        }
349    }
350
351    // Layers are already drawn with a top-left origin, don't flip the texture
352    resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f);
353
354    drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture,
355            1.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0],
356            &mMeshVertices[0].texture[0], NULL, 0, true, true);
357
358    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
359
360    LayerSize size(rect.getWidth(), rect.getHeight());
361    // Failing to add the layer to the cache should happen only if the
362    // layer is too large
363    if (!mCaches.layerCache.put(size, layer)) {
364        LAYER_LOGD("Deleting layer");
365
366        glDeleteTextures(1, &layer->texture);
367
368        delete layer;
369    }
370}
371
372void OpenGLRenderer::clearLayerRegions() {
373    if (mLayers.size() == 0) return;
374
375    for (uint32_t i = 0; i < mLayers.size(); i++) {
376        Rect* bounds = mLayers.itemAt(i);
377
378        // Clear the framebuffer where the layer will draw
379        glScissor(bounds->left, mHeight - bounds->bottom,
380                bounds->getWidth(), bounds->getHeight());
381        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
382        glClear(GL_COLOR_BUFFER_BIT);
383
384        delete bounds;
385    }
386    mLayers.clear();
387
388    // Restore the clip
389    setScissorFromClip();
390}
391
392///////////////////////////////////////////////////////////////////////////////
393// Transforms
394///////////////////////////////////////////////////////////////////////////////
395
396void OpenGLRenderer::translate(float dx, float dy) {
397    mSnapshot->transform->translate(dx, dy, 0.0f);
398}
399
400void OpenGLRenderer::rotate(float degrees) {
401    mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f);
402}
403
404void OpenGLRenderer::scale(float sx, float sy) {
405    mSnapshot->transform->scale(sx, sy, 1.0f);
406}
407
408void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
409    mSnapshot->transform->load(*matrix);
410}
411
412void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
413    mSnapshot->transform->copyTo(*matrix);
414}
415
416void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
417    mat4 m(*matrix);
418    mSnapshot->transform->multiply(m);
419}
420
421///////////////////////////////////////////////////////////////////////////////
422// Clipping
423///////////////////////////////////////////////////////////////////////////////
424
425void OpenGLRenderer::setScissorFromClip() {
426    const Rect& clip = *mSnapshot->clipRect;
427    glScissor(clip.left, mHeight - clip.bottom, clip.getWidth(), clip.getHeight());
428}
429
430const Rect& OpenGLRenderer::getClipBounds() {
431    return mSnapshot->getLocalClip();
432}
433
434bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
435    Rect r(left, top, right, bottom);
436    mSnapshot->transform->mapRect(r);
437    return !mSnapshot->clipRect->intersects(r);
438}
439
440bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
441    bool clipped = mSnapshot->clip(left, top, right, bottom, op);
442    if (clipped) {
443        setScissorFromClip();
444    }
445    return !mSnapshot->clipRect->isEmpty();
446}
447
448///////////////////////////////////////////////////////////////////////////////
449// Drawing
450///////////////////////////////////////////////////////////////////////////////
451
452void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, const SkPaint* paint) {
453    const float right = left + bitmap->width();
454    const float bottom = top + bitmap->height();
455
456    if (quickReject(left, top, right, bottom)) {
457        return;
458    }
459
460    glActiveTexture(GL_TEXTURE0);
461    const Texture* texture = mCaches.textureCache.get(bitmap);
462    if (!texture) return;
463    const AutoTexture autoCleanup(texture);
464
465    drawTextureRect(left, top, right, bottom, texture, paint);
466}
467
468void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, const SkMatrix* matrix, const SkPaint* paint) {
469    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
470    const mat4 transform(*matrix);
471    transform.mapRect(r);
472
473    if (quickReject(r.left, r.top, r.right, r.bottom)) {
474        return;
475    }
476
477    glActiveTexture(GL_TEXTURE0);
478    const Texture* texture = mCaches.textureCache.get(bitmap);
479    if (!texture) return;
480    const AutoTexture autoCleanup(texture);
481
482    drawTextureRect(r.left, r.top, r.right, r.bottom, texture, paint);
483}
484
485void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
486         float srcLeft, float srcTop, float srcRight, float srcBottom,
487         float dstLeft, float dstTop, float dstRight, float dstBottom,
488         const SkPaint* paint) {
489    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
490        return;
491    }
492
493    glActiveTexture(GL_TEXTURE0);
494    const Texture* texture = mCaches.textureCache.get(bitmap);
495    if (!texture) return;
496    const AutoTexture autoCleanup(texture);
497
498    const float width = texture->width;
499    const float height = texture->height;
500
501    const float u1 = srcLeft / width;
502    const float v1 = srcTop / height;
503    const float u2 = srcRight / width;
504    const float v2 = srcBottom / height;
505
506    resetDrawTextureTexCoords(u1, v1, u2, v2);
507
508    drawTextureRect(dstLeft, dstTop, dstRight, dstBottom, texture, paint);
509
510    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
511}
512
513void OpenGLRenderer::drawPatch(SkBitmap* bitmap, Res_png_9patch* patch,
514        float left, float top, float right, float bottom, const SkPaint* paint) {
515    if (quickReject(left, top, right, bottom)) {
516        return;
517    }
518
519    glActiveTexture(GL_TEXTURE0);
520    const Texture* texture = mCaches.textureCache.get(bitmap);
521    if (!texture) return;
522    const AutoTexture autoCleanup(texture);
523
524    int alpha;
525    SkXfermode::Mode mode;
526    getAlphaAndMode(paint, &alpha, &mode);
527
528    Patch* mesh = mCaches.patchCache.get(patch);
529    mesh->updateVertices(bitmap, left, top, right, bottom,
530            &patch->xDivs[0], &patch->yDivs[0], patch->numXDivs, patch->numYDivs);
531    mesh->dump();
532
533    // Specify right and bottom as +1.0f from left/top to prevent scaling since the
534    // patch mesh already defines the final size
535    drawTextureMesh(left, top, left + 1.0f, top + 1.0f, texture->id, alpha / 255.0f,
536            mode, texture->blend, &mesh->vertices[0].position[0],
537            &mesh->vertices[0].texture[0], mesh->indices, mesh->indicesCount);
538}
539
540void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
541    const Rect& clip = *mSnapshot->clipRect;
542    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
543}
544
545void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, const SkPaint* p) {
546    if (quickReject(left, top, right, bottom)) {
547        return;
548    }
549
550    SkXfermode::Mode mode;
551    if (!mExtensions.hasFramebufferFetch()) {
552        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
553        if (!isMode) {
554            // Assume SRC_OVER
555            mode = SkXfermode::kSrcOver_Mode;
556        }
557    } else {
558        mode = getXfermode(p->getXfermode());
559    }
560
561    // Skia draws using the color's alpha channel if < 255
562    // Otherwise, it uses the paint's alpha
563    int color = p->getColor();
564    if (((color >> 24) & 0xff) == 255) {
565        color |= p->getAlpha() << 24;
566    }
567
568    drawColorRect(left, top, right, bottom, color, mode);
569}
570
571void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
572        float x, float y, SkPaint* paint) {
573    if (text == NULL || count == 0 || (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) {
574        return;
575    }
576    paint->setAntiAlias(true);
577
578    float length = -1.0f;
579    switch (paint->getTextAlign()) {
580        case SkPaint::kCenter_Align:
581            length = paint->measureText(text, bytesCount);
582            x -= length / 2.0f;
583            break;
584        case SkPaint::kRight_Align:
585            length = paint->measureText(text, bytesCount);
586            x -= length;
587            break;
588        default:
589            break;
590    }
591
592    int alpha;
593    SkXfermode::Mode mode;
594    getAlphaAndMode(paint, &alpha, &mode);
595
596    uint32_t color = paint->getColor();
597    const GLfloat a = alpha / 255.0f;
598    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
599    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
600    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
601
602    FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint);
603    fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()),
604            paint->getTextSize());
605    if (mHasShadow) {
606        glActiveTexture(gTextureUnits[0]);
607        mCaches.dropShadowCache.setFontRenderer(fontRenderer);
608        const ShadowTexture* shadow = mCaches.dropShadowCache.get(paint, text, bytesCount,
609                count, mShadowRadius);
610        const AutoTexture autoCleanup(shadow);
611
612        setupShadow(shadow, x, y, mode, a);
613
614        // Draw the mesh
615        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
616        glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
617    }
618
619    GLuint textureUnit = 0;
620    glActiveTexture(gTextureUnits[textureUnit]);
621
622    setupTextureAlpha8(fontRenderer.getTexture(), 0, 0, textureUnit, x, y, r, g, b, a,
623            mode, false, true);
624
625    const Rect& clip = mSnapshot->getLocalClip();
626    clearLayerRegions();
627    fontRenderer.renderText(paint, &clip, text, 0, bytesCount, count, x, y);
628
629    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
630    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
631
632    drawTextDecorations(text, bytesCount, length, x, y, paint);
633}
634
635void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
636    GLuint textureUnit = 0;
637    glActiveTexture(gTextureUnits[textureUnit]);
638
639    const PathTexture* texture = mCaches.pathCache.get(path, paint);
640    if (!texture) return;
641    const AutoTexture autoCleanup(texture);
642
643    const float x = texture->left - texture->offset;
644    const float y = texture->top - texture->offset;
645
646    if (quickReject(x, y, x + texture->width, y + texture->height)) {
647        return;
648    }
649
650    int alpha;
651    SkXfermode::Mode mode;
652    getAlphaAndMode(paint, &alpha, &mode);
653
654    uint32_t color = paint->getColor();
655    const GLfloat a = alpha / 255.0f;
656    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
657    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
658    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
659
660    setupTextureAlpha8(texture, textureUnit, x, y, r, g, b, a, mode, true, true);
661
662    clearLayerRegions();
663
664    // Draw the mesh
665    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
666    glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords"));
667}
668
669///////////////////////////////////////////////////////////////////////////////
670// Shaders
671///////////////////////////////////////////////////////////////////////////////
672
673void OpenGLRenderer::resetShader() {
674    mShader = NULL;
675}
676
677void OpenGLRenderer::setupShader(SkiaShader* shader) {
678    mShader = shader;
679    if (mShader) {
680        mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
681    }
682}
683
684///////////////////////////////////////////////////////////////////////////////
685// Color filters
686///////////////////////////////////////////////////////////////////////////////
687
688void OpenGLRenderer::resetColorFilter() {
689    mColorFilter = NULL;
690}
691
692void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
693    mColorFilter = filter;
694}
695
696///////////////////////////////////////////////////////////////////////////////
697// Drop shadow
698///////////////////////////////////////////////////////////////////////////////
699
700void OpenGLRenderer::resetShadow() {
701    mHasShadow = false;
702}
703
704void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
705    mHasShadow = true;
706    mShadowRadius = radius;
707    mShadowDx = dx;
708    mShadowDy = dy;
709    mShadowColor = color;
710}
711
712///////////////////////////////////////////////////////////////////////////////
713// Drawing implementation
714///////////////////////////////////////////////////////////////////////////////
715
716void OpenGLRenderer::setupShadow(const ShadowTexture* texture, float x, float y,
717        SkXfermode::Mode mode, float alpha) {
718    const float sx = x - texture->left + mShadowDx;
719    const float sy = y - texture->top + mShadowDy;
720
721    const int shadowAlpha = ((mShadowColor >> 24) & 0xFF);
722    const GLfloat a = shadowAlpha < 255 ? shadowAlpha / 255.0f : alpha;
723    const GLfloat r = a * ((mShadowColor >> 16) & 0xFF) / 255.0f;
724    const GLfloat g = a * ((mShadowColor >>  8) & 0xFF) / 255.0f;
725    const GLfloat b = a * ((mShadowColor      ) & 0xFF) / 255.0f;
726
727    GLuint textureUnit = 0;
728    setupTextureAlpha8(texture, textureUnit, sx, sy, r, g, b, a, mode, true, false);
729}
730
731void OpenGLRenderer::setupTextureAlpha8(const Texture* texture, GLuint& textureUnit,
732        float x, float y, float r, float g, float b, float a, SkXfermode::Mode mode,
733        bool transforms, bool applyFilters) {
734    setupTextureAlpha8(texture->id, texture->width, texture->height, textureUnit,
735            x, y, r, g, b, a, mode, transforms, applyFilters);
736}
737
738void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height,
739        GLuint& textureUnit, float x, float y, float r, float g, float b, float a,
740        SkXfermode::Mode mode, bool transforms, bool applyFilters) {
741     // Describe the required shaders
742     ProgramDescription description;
743     description.hasTexture = true;
744     description.hasAlpha8Texture = true;
745
746     if (applyFilters) {
747         if (mShader) {
748             mShader->describe(description, mExtensions);
749         }
750         if (mColorFilter) {
751             mColorFilter->describe(description, mExtensions);
752         }
753     }
754
755     // Setup the blending mode
756     chooseBlending(true, mode, description);
757
758     // Build and use the appropriate shader
759     useProgram(mCaches.programCache.get(description));
760
761     bindTexture(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, textureUnit);
762     glUniform1i(mCaches.currentProgram->getUniform("sampler"), textureUnit);
763
764     int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
765     glEnableVertexAttribArray(texCoordsSlot);
766
767     // Setup attributes
768     glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
769             gMeshStride, &mMeshVertices[0].position[0]);
770     glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE,
771             gMeshStride, &mMeshVertices[0].texture[0]);
772
773     // Setup uniforms
774     if (transforms) {
775         mModelView.loadTranslate(x, y, 0.0f);
776         mModelView.scale(width, height, 1.0f);
777     } else {
778         mModelView.loadIdentity();
779     }
780     mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
781     glUniform4f(mCaches.currentProgram->color, r, g, b, a);
782
783     textureUnit++;
784     if (applyFilters) {
785         // Setup attributes and uniforms required by the shaders
786         if (mShader) {
787             mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit);
788         }
789         if (mColorFilter) {
790             mColorFilter->setupProgram(mCaches.currentProgram);
791         }
792     }
793}
794
795// Same values used by Skia
796#define kStdStrikeThru_Offset   (-6.0f / 21.0f)
797#define kStdUnderline_Offset    (1.0f / 9.0f)
798#define kStdUnderline_Thickness (1.0f / 18.0f)
799
800void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
801        float x, float y, SkPaint* paint) {
802    // Handle underline and strike-through
803    uint32_t flags = paint->getFlags();
804    if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
805        float underlineWidth = length;
806        // If length is > 0.0f, we already measured the text for the text alignment
807        if (length <= 0.0f) {
808            underlineWidth = paint->measureText(text, bytesCount);
809        }
810
811        float offsetX = 0;
812        switch (paint->getTextAlign()) {
813            case SkPaint::kCenter_Align:
814                offsetX = underlineWidth * 0.5f;
815                break;
816            case SkPaint::kRight_Align:
817                offsetX = underlineWidth;
818                break;
819            default:
820                break;
821        }
822
823        if (underlineWidth > 0.0f) {
824            float textSize = paint->getTextSize();
825            float height = textSize * kStdUnderline_Thickness;
826
827            float left = x - offsetX;
828            float top = 0.0f;
829            float right = left + underlineWidth;
830            float bottom = 0.0f;
831
832            if (flags & SkPaint::kUnderlineText_Flag) {
833                top = y + textSize * kStdUnderline_Offset;
834                bottom = top + height;
835                drawRect(left, top, right, bottom, paint);
836            }
837
838            if (flags & SkPaint::kStrikeThruText_Flag) {
839                top = y + textSize * kStdStrikeThru_Offset;
840                bottom = top + height;
841                drawRect(left, top, right, bottom, paint);
842            }
843        }
844    }
845}
846
847void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
848        int color, SkXfermode::Mode mode, bool ignoreTransform, bool ignoreBlending) {
849    clearLayerRegions();
850
851    // If a shader is set, preserve only the alpha
852    if (mShader) {
853        color |= 0x00ffffff;
854    }
855
856    // Render using pre-multiplied alpha
857    const int alpha = (color >> 24) & 0xFF;
858    const GLfloat a = alpha / 255.0f;
859    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
860    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
861    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
862
863    GLuint textureUnit = 0;
864
865    // Describe the required shaders
866    ProgramDescription description;
867    if (mShader) {
868        mShader->describe(description, mExtensions);
869    }
870    if (mColorFilter) {
871        mColorFilter->describe(description, mExtensions);
872    }
873
874    if (!ignoreBlending) {
875        // Setup the blending mode
876        chooseBlending(alpha < 255 || (mShader && mShader->blend()), mode, description);
877    }
878
879    // Build and use the appropriate shader
880    useProgram(mCaches.programCache.get(description));
881
882    // Setup attributes
883    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
884            gMeshStride, &mMeshVertices[0].position[0]);
885
886    // Setup uniforms
887    mModelView.loadTranslate(left, top, 0.0f);
888    mModelView.scale(right - left, bottom - top, 1.0f);
889    if (!ignoreTransform) {
890        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
891    } else {
892        mat4 identity;
893        mCaches.currentProgram->set(mOrthoMatrix, mModelView, identity);
894    }
895    glUniform4f(mCaches.currentProgram->color, r, g, b, a);
896
897    // Setup attributes and uniforms required by the shaders
898    if (mShader) {
899        mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit);
900    }
901    if (mColorFilter) {
902        mColorFilter->setupProgram(mCaches.currentProgram);
903    }
904
905    // Draw the mesh
906    glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
907}
908
909void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
910        const Texture* texture, const SkPaint* paint) {
911    int alpha;
912    SkXfermode::Mode mode;
913    getAlphaAndMode(paint, &alpha, &mode);
914
915    drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode, texture->blend,
916            &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], NULL);
917}
918
919void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
920        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
921    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
922            &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], NULL);
923}
924
925void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
926        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
927        GLvoid* vertices, GLvoid* texCoords, GLvoid* indices, GLsizei elementsCount,
928        bool swapSrcDst, bool ignoreTransform) {
929    clearLayerRegions();
930
931    ProgramDescription description;
932    description.hasTexture = true;
933    if (mColorFilter) {
934        mColorFilter->describe(description, mExtensions);
935    }
936
937    mModelView.loadTranslate(left, top, 0.0f);
938    mModelView.scale(right - left, bottom - top, 1.0f);
939
940    chooseBlending(blend || alpha < 1.0f, mode, description, swapSrcDst);
941
942    useProgram(mCaches.programCache.get(description));
943    if (!ignoreTransform) {
944        mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
945    } else {
946        mat4 m;
947        mCaches.currentProgram->set(mOrthoMatrix, mModelView, m);
948    }
949
950    // Texture
951    bindTexture(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, 0);
952    glUniform1i(mCaches.currentProgram->getUniform("sampler"), 0);
953
954    // Always premultiplied
955    glUniform4f(mCaches.currentProgram->color, alpha, alpha, alpha, alpha);
956
957    // Mesh
958    int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
959    glEnableVertexAttribArray(texCoordsSlot);
960    glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
961            gMeshStride, vertices);
962    glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords);
963
964    // Color filter
965    if (mColorFilter) {
966        mColorFilter->setupProgram(mCaches.currentProgram);
967    }
968
969    if (!indices) {
970        glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
971    } else {
972        glDrawElements(GL_TRIANGLES, elementsCount, GL_UNSIGNED_SHORT, indices);
973    }
974    glDisableVertexAttribArray(texCoordsSlot);
975}
976
977void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
978        ProgramDescription& description, bool swapSrcDst) {
979    blend = blend || mode != SkXfermode::kSrcOver_Mode;
980    if (blend) {
981        if (mode < SkXfermode::kPlus_Mode) {
982            if (!mCaches.blend) {
983                glEnable(GL_BLEND);
984            }
985
986            GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
987            GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
988
989            if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
990                glBlendFunc(sourceMode, destMode);
991                mCaches.lastSrcMode = sourceMode;
992                mCaches.lastDstMode = destMode;
993            }
994        } else {
995            // These blend modes are not supported by OpenGL directly and have
996            // to be implemented using shaders. Since the shader will perform
997            // the blending, turn blending off here
998            if (mExtensions.hasFramebufferFetch()) {
999                description.framebufferMode = mode;
1000                description.swapSrcDst = swapSrcDst;
1001            }
1002
1003            if (mCaches.blend) {
1004                glDisable(GL_BLEND);
1005            }
1006            blend = false;
1007        }
1008    } else if (mCaches.blend) {
1009        glDisable(GL_BLEND);
1010    }
1011    mCaches.blend = blend;
1012}
1013
1014bool OpenGLRenderer::useProgram(Program* program) {
1015    if (!program->isInUse()) {
1016        if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
1017        program->use();
1018        mCaches.currentProgram = program;
1019        return false;
1020    }
1021    return true;
1022}
1023
1024void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
1025    TextureVertex* v = &mMeshVertices[0];
1026    TextureVertex::setUV(v++, u1, v1);
1027    TextureVertex::setUV(v++, u2, v1);
1028    TextureVertex::setUV(v++, u1, v2);
1029    TextureVertex::setUV(v++, u2, v2);
1030}
1031
1032void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
1033    if (paint) {
1034        if (!mExtensions.hasFramebufferFetch()) {
1035            const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
1036            if (!isMode) {
1037                // Assume SRC_OVER
1038                *mode = SkXfermode::kSrcOver_Mode;
1039            }
1040        } else {
1041            *mode = getXfermode(paint->getXfermode());
1042        }
1043
1044        // Skia draws using the color's alpha channel if < 255
1045        // Otherwise, it uses the paint's alpha
1046        int color = paint->getColor();
1047        *alpha = (color >> 24) & 0xFF;
1048        if (*alpha == 255) {
1049            *alpha = paint->getAlpha();
1050        }
1051    } else {
1052        *mode = SkXfermode::kSrcOver_Mode;
1053        *alpha = 255;
1054    }
1055}
1056
1057SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) {
1058    if (mode == NULL) {
1059        return SkXfermode::kSrcOver_Mode;
1060    }
1061    return mode->fMode;
1062}
1063
1064void OpenGLRenderer::bindTexture(GLuint texture, GLenum wrapS, GLenum wrapT, GLuint textureUnit) {
1065    glActiveTexture(gTextureUnits[textureUnit]);
1066    glBindTexture(GL_TEXTURE_2D, texture);
1067    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
1068    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
1069}
1070
1071}; // namespace uirenderer
1072}; // namespace android
1073