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