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