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