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