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