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