OpenGLRenderer.cpp revision d27977d1a91d5a6b3cc9fa7664ac7e835e7bd895
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
25#include <cutils/properties.h>
26#include <utils/Log.h>
27
28#include "OpenGLRenderer.h"
29
30namespace android {
31namespace uirenderer {
32
33///////////////////////////////////////////////////////////////////////////////
34// Defines
35///////////////////////////////////////////////////////////////////////////////
36
37// These properties are defined in mega-bytes
38#define PROPERTY_TEXTURE_CACHE_SIZE "ro.hwui.texture_cache_size"
39#define PROPERTY_LAYER_CACHE_SIZE "ro.hwui.layer_cache_size"
40
41#define DEFAULT_TEXTURE_CACHE_SIZE 20
42#define DEFAULT_LAYER_CACHE_SIZE 10
43#define DEFAULT_PATCH_CACHE_SIZE 100
44
45// Converts a number of mega-bytes into bytes
46#define MB(s) s * 1024 * 1024
47
48// Generates simple and textured vertices
49#define SV(x, y) { { x, y } }
50#define FV(x, y, u, v) { { x, y }, { u, v } }
51
52///////////////////////////////////////////////////////////////////////////////
53// Globals
54///////////////////////////////////////////////////////////////////////////////
55
56static const SimpleVertex gDrawColorVertices[] = {
57        SV(0.0f, 0.0f),
58        SV(1.0f, 0.0f),
59        SV(0.0f, 1.0f),
60        SV(1.0f, 1.0f)
61};
62static const GLsizei gDrawColorVertexStride = sizeof(SimpleVertex);
63static const GLsizei gDrawColorVertexCount = 4;
64
65// This array is never used directly but used as a memcpy source in the
66// OpenGLRenderer constructor
67static const TextureVertex gDrawTextureVertices[] = {
68        FV(0.0f, 0.0f, 0.0f, 0.0f),
69        FV(1.0f, 0.0f, 1.0f, 0.0f),
70        FV(0.0f, 1.0f, 0.0f, 1.0f),
71        FV(1.0f, 1.0f, 1.0f, 1.0f)
72};
73static const GLsizei gDrawTextureVertexStride = sizeof(TextureVertex);
74static const GLsizei gDrawTextureVertexCount = 4;
75
76// In this array, the index of each Blender equals the value of the first
77// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
78static const Blender gBlends[] = {
79        { SkXfermode::kClear_Mode,   GL_ZERO,                 GL_ZERO },
80        { SkXfermode::kSrc_Mode,     GL_ONE,                  GL_ZERO },
81        { SkXfermode::kDst_Mode,     GL_ZERO,                 GL_ONE },
82        { SkXfermode::kSrcOver_Mode, GL_ONE,                  GL_ONE_MINUS_SRC_ALPHA },
83        { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_ONE },
84        { SkXfermode::kSrcIn_Mode,   GL_DST_ALPHA,            GL_ZERO },
85        { SkXfermode::kDstIn_Mode,   GL_ZERO,                 GL_SRC_ALPHA },
86        { SkXfermode::kSrcOut_Mode,  GL_ONE_MINUS_DST_ALPHA,  GL_ZERO },
87        { SkXfermode::kDstOut_Mode,  GL_ZERO,                 GL_ONE_MINUS_SRC_ALPHA },
88        { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA,            GL_ONE_MINUS_SRC_ALPHA },
89        { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA,  GL_SRC_ALPHA },
90        { SkXfermode::kXor_Mode,     GL_ONE_MINUS_DST_ALPHA,  GL_ONE_MINUS_SRC_ALPHA }
91};
92
93static const GLint gTileModes[] = {
94        GL_CLAMP_TO_EDGE,   // == SkShader::kClamp_TileMode
95        GL_REPEAT,          // == SkShader::kRepeat_Mode
96        GL_MIRRORED_REPEAT  // == SkShader::kMirror_TileMode
97};
98
99///////////////////////////////////////////////////////////////////////////////
100// Constructors/destructor
101///////////////////////////////////////////////////////////////////////////////
102
103OpenGLRenderer::OpenGLRenderer():
104        mBlend(false), mLastSrcMode(GL_ZERO), mLastDstMode(GL_ZERO),
105        mTextureCache(MB(DEFAULT_TEXTURE_CACHE_SIZE)),
106        mLayerCache(MB(DEFAULT_LAYER_CACHE_SIZE)),
107        mPatchCache(DEFAULT_PATCH_CACHE_SIZE) {
108    LOGD("Create OpenGLRenderer");
109
110    char property[PROPERTY_VALUE_MAX];
111    if (property_get(PROPERTY_TEXTURE_CACHE_SIZE, property, NULL) > 0) {
112        LOGD("  Setting texture cache size to %sMB", property);
113        mTextureCache.setMaxSize(MB(atoi(property)));
114    } else {
115        LOGD("  Using default texture cache size of %dMB", DEFAULT_TEXTURE_CACHE_SIZE);
116    }
117
118    if (property_get(PROPERTY_LAYER_CACHE_SIZE, property, NULL) > 0) {
119        LOGD("  Setting layer cache size to %sMB", property);
120        mLayerCache.setMaxSize(MB(atoi(property)));
121    } else {
122        LOGD("  Using default layer cache size of %dMB", DEFAULT_LAYER_CACHE_SIZE);
123    }
124
125    mDrawColorProgram = new DrawColorProgram;
126    mDrawTextureProgram = new DrawTextureProgram;
127    mCurrentProgram = mDrawTextureProgram;
128
129    mShader = kShaderNone;
130    mShaderTileX = SkShader::kClamp_TileMode;
131    mShaderTileY = SkShader::kClamp_TileMode;
132    mShaderMatrix = NULL;
133    mShaderBitmap = NULL;
134
135    memcpy(mDrawTextureVertices, gDrawTextureVertices, sizeof(gDrawTextureVertices));
136}
137
138OpenGLRenderer::~OpenGLRenderer() {
139    LOGD("Destroy OpenGLRenderer");
140
141    mTextureCache.clear();
142    mLayerCache.clear();
143    mPatchCache.clear();
144}
145
146///////////////////////////////////////////////////////////////////////////////
147// Setup
148///////////////////////////////////////////////////////////////////////////////
149
150void OpenGLRenderer::setViewport(int width, int height) {
151    glViewport(0, 0, width, height);
152
153    mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
154
155    mWidth = width;
156    mHeight = height;
157    mFirstSnapshot.height = height;
158}
159
160void OpenGLRenderer::prepare() {
161    mSnapshot = &mFirstSnapshot;
162    mSaveCount = 0;
163
164    glDisable(GL_SCISSOR_TEST);
165
166    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
167    glClear(GL_COLOR_BUFFER_BIT);
168
169    glEnable(GL_SCISSOR_TEST);
170    glScissor(0, 0, mWidth, mHeight);
171
172    mSnapshot->clipRect.set(0.0f, 0.0f, mWidth, mHeight);
173}
174
175///////////////////////////////////////////////////////////////////////////////
176// State management
177///////////////////////////////////////////////////////////////////////////////
178
179int OpenGLRenderer::getSaveCount() const {
180    return mSaveCount;
181}
182
183int OpenGLRenderer::save(int flags) {
184    return saveSnapshot();
185}
186
187void OpenGLRenderer::restore() {
188    if (mSaveCount == 0) return;
189
190    if (restoreSnapshot()) {
191        setScissorFromClip();
192    }
193}
194
195void OpenGLRenderer::restoreToCount(int saveCount) {
196    if (saveCount <= 0 || saveCount > mSaveCount) return;
197
198    bool restoreClip = false;
199
200    while (mSaveCount != saveCount - 1) {
201        restoreClip |= restoreSnapshot();
202    }
203
204    if (restoreClip) {
205        setScissorFromClip();
206    }
207}
208
209int OpenGLRenderer::saveSnapshot() {
210    mSnapshot = new Snapshot(mSnapshot);
211    return ++mSaveCount;
212}
213
214bool OpenGLRenderer::restoreSnapshot() {
215    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
216    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
217    bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
218
219    sp<Snapshot> current = mSnapshot;
220    sp<Snapshot> previous = mSnapshot->previous;
221
222    if (restoreOrtho) {
223        mOrthoMatrix.load(current->orthoMatrix);
224    }
225
226    if (restoreLayer) {
227        composeLayer(current, previous);
228    }
229
230    mSnapshot = previous;
231    mSaveCount--;
232
233    return restoreClip;
234}
235
236void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
237    if (!current->layer) {
238        LOGE("Attempting to compose a layer that does not exist");
239        return;
240    }
241
242    // Unbind current FBO and restore previous one
243    // Most of the time, previous->fbo will be 0 to bind the default buffer
244    glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
245
246    // Restore the clip from the previous snapshot
247    const Rect& clip = previous->getMappedClip();
248    glScissor(clip.left, mHeight - clip.bottom, clip.getWidth(), clip.getHeight());
249
250    Layer* layer = current->layer;
251
252    // Compute the correct texture coordinates for the FBO texture
253    // The texture is currently as big as the window but drawn with
254    // a quad of the appropriate size
255    const Rect& rect = layer->layer;
256
257    drawTextureRect(rect.left, rect.top, rect.right, rect.bottom,
258            layer->texture, layer->alpha, layer->mode, layer->blend);
259
260    LayerSize size(rect.getWidth(), rect.getHeight());
261    // Failing to add the layer to the cache should happen only if the
262    // layer is too large
263    if (!mLayerCache.put(size, layer)) {
264        LAYER_LOGD("Deleting layer");
265
266        glDeleteFramebuffers(1, &layer->fbo);
267        glDeleteTextures(1, &layer->texture);
268
269        delete layer;
270    }
271}
272
273///////////////////////////////////////////////////////////////////////////////
274// Layers
275///////////////////////////////////////////////////////////////////////////////
276
277int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
278        const SkPaint* p, int flags) {
279    int count = saveSnapshot();
280
281    int alpha = 255;
282    SkXfermode::Mode mode;
283
284    if (p) {
285        alpha = p->getAlpha();
286        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
287        if (!isMode) {
288            // Assume SRC_OVER
289            mode = SkXfermode::kSrcOver_Mode;
290        }
291    } else {
292        mode = SkXfermode::kSrcOver_Mode;
293    }
294
295    createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags);
296
297    return count;
298}
299
300int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
301        int alpha, int flags) {
302    int count = saveSnapshot();
303    createLayer(mSnapshot, left, top, right, bottom, alpha, SkXfermode::kSrcOver_Mode, flags);
304    return count;
305}
306
307bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
308        float right, float bottom, int alpha, SkXfermode::Mode mode,int flags) {
309
310    LAYER_LOGD("Requesting layer %fx%f", right - left, bottom - top);
311    LAYER_LOGD("Layer cache size = %d", mLayerCache.getSize());
312
313    GLuint previousFbo = snapshot->previous.get() ? snapshot->previous->fbo : 0;
314    LayerSize size(right - left, bottom - top);
315
316    Layer* layer = mLayerCache.get(size, previousFbo);
317    if (!layer) {
318        return false;
319    }
320
321    glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo);
322
323    // Clear the FBO
324    glDisable(GL_SCISSOR_TEST);
325    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
326    glClear(GL_COLOR_BUFFER_BIT);
327    glEnable(GL_SCISSOR_TEST);
328
329    // Save the layer in the snapshot
330    snapshot->flags |= Snapshot::kFlagIsLayer;
331    layer->mode = mode;
332    layer->alpha = alpha / 255.0f;
333    layer->layer.set(left, top, right, bottom);
334
335    snapshot->layer = layer;
336    snapshot->fbo = layer->fbo;
337
338    // Creates a new snapshot to draw into the FBO
339    saveSnapshot();
340    // TODO: This doesn't preserve other transformations (check Skia first)
341    mSnapshot->transform.loadTranslate(-left, -top, 0.0f);
342    mSnapshot->setClip(left, top, right, bottom);
343    mSnapshot->height = bottom - top;
344    setScissorFromClip();
345
346    mSnapshot->flags = Snapshot::kFlagDirtyTransform | Snapshot::kFlagDirtyOrtho |
347            Snapshot::kFlagClipSet;
348    mSnapshot->orthoMatrix.load(mOrthoMatrix);
349
350    // Change the ortho projection
351    mOrthoMatrix.loadOrtho(0.0f, right - left, bottom - top, 0.0f, 0.0f, 1.0f);
352
353    return true;
354}
355
356///////////////////////////////////////////////////////////////////////////////
357// Transforms
358///////////////////////////////////////////////////////////////////////////////
359
360void OpenGLRenderer::translate(float dx, float dy) {
361    mSnapshot->transform.translate(dx, dy, 0.0f);
362    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
363}
364
365void OpenGLRenderer::rotate(float degrees) {
366    mSnapshot->transform.rotate(degrees, 0.0f, 0.0f, 1.0f);
367    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
368}
369
370void OpenGLRenderer::scale(float sx, float sy) {
371    mSnapshot->transform.scale(sx, sy, 1.0f);
372    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
373}
374
375void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
376    mSnapshot->transform.load(*matrix);
377    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
378}
379
380void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
381    mSnapshot->transform.copyTo(*matrix);
382}
383
384void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
385    mat4 m(*matrix);
386    mSnapshot->transform.multiply(m);
387    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
388}
389
390///////////////////////////////////////////////////////////////////////////////
391// Clipping
392///////////////////////////////////////////////////////////////////////////////
393
394void OpenGLRenderer::setScissorFromClip() {
395    const Rect& clip = mSnapshot->getMappedClip();
396    glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight());
397}
398
399const Rect& OpenGLRenderer::getClipBounds() {
400    return mSnapshot->clipRect;
401}
402
403bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
404    /*
405     * The documentation of quickReject() indicates that the specified rect
406     * is transformed before being compared to the clip rect. However, the
407     * clip rect is not stored transformed in the snapshot and can thus be
408     * compared directly
409     *
410     * The following code can be used instead to performed a mapped comparison:
411     *
412     *     mSnapshot->transform.mapRect(r);
413     *     const Rect& clip = mSnapshot->getMappedClip();
414     *     return !clip.intersects(r);
415     */
416    Rect r(left, top, right, bottom);
417    return !mSnapshot->clipRect.intersects(r);
418}
419
420bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom) {
421    bool clipped = mSnapshot->clip(left, top, right, bottom);
422    if (clipped) {
423        mSnapshot->flags |= Snapshot::kFlagClipSet;
424        setScissorFromClip();
425    }
426    return clipped;
427}
428
429///////////////////////////////////////////////////////////////////////////////
430// Drawing
431///////////////////////////////////////////////////////////////////////////////
432
433void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, const SkPaint* paint) {
434    const float right = left + bitmap->width();
435    const float bottom = top + bitmap->height();
436
437    if (quickReject(left, top, right, bottom)) {
438        return;
439    }
440
441    const Texture* texture = mTextureCache.get(bitmap);
442    drawTextureRect(left, top, right, bottom, texture, paint);
443}
444
445void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, const SkMatrix* matrix, const SkPaint* paint) {
446    Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
447    const mat4 transform(*matrix);
448    transform.mapRect(r);
449
450    if (quickReject(r.left, r.top, r.right, r.bottom)) {
451        return;
452    }
453
454    const Texture* texture = mTextureCache.get(bitmap);
455    drawTextureRect(r.left, r.top, r.right, r.bottom, texture, paint);
456}
457
458void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
459         float srcLeft, float srcTop, float srcRight, float srcBottom,
460         float dstLeft, float dstTop, float dstRight, float dstBottom,
461         const SkPaint* paint) {
462    if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
463        return;
464    }
465
466    const Texture* texture = mTextureCache.get(bitmap);
467
468    const float width = texture->width;
469    const float height = texture->height;
470
471    const float u1 = srcLeft / width;
472    const float v1 = srcTop / height;
473    const float u2 = srcRight / width;
474    const float v2 = srcBottom / height;
475
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->getMappedClip();
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
534///////////////////////////////////////////////////////////////////////////////
535// Shaders
536///////////////////////////////////////////////////////////////////////////////
537
538void OpenGLRenderer::resetShader() {
539    mShader = OpenGLRenderer::kShaderNone;
540    mShaderBlend = false;
541    mShaderTileX = SkShader::kClamp_TileMode;
542    mShaderTileY = SkShader::kClamp_TileMode;
543}
544
545void OpenGLRenderer::setupBitmapShader(SkBitmap* bitmap, SkShader::TileMode tileX,
546        SkShader::TileMode tileY, SkMatrix* matrix, bool hasAlpha) {
547    mShader = kShaderBitmap;
548    mShaderBlend = hasAlpha;
549    mShaderBitmap = bitmap;
550    mShaderTileX = tileX;
551    mShaderTileY = tileY;
552    mShaderMatrix = matrix;
553}
554
555///////////////////////////////////////////////////////////////////////////////
556// Drawing implementation
557///////////////////////////////////////////////////////////////////////////////
558
559void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
560        int color, SkXfermode::Mode mode, bool ignoreTransform) {
561    // If a shader is set, preserve only the alpha
562    if (mShader != kShaderNone) {
563        color |= 0x00ffffff;
564    }
565
566    // Render using pre-multiplied alpha
567    const int alpha = (color >> 24) & 0xFF;
568    const GLfloat a = alpha / 255.0f;
569    const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f;
570    const GLfloat g = a * ((color >>  8) & 0xFF) / 255.0f;
571    const GLfloat b = a * ((color      ) & 0xFF) / 255.0f;
572
573    switch (mShader) {
574        case kShaderBitmap:
575            drawBitmapShader(left, top, right, bottom, a, mode);
576            return;
577        default:
578            break;
579    }
580
581    // Pre-multiplication happens when setting the shader color
582    chooseBlending(alpha < 255 || mShaderBlend, mode);
583
584    mModelView.loadTranslate(left, top, 0.0f);
585    mModelView.scale(right - left, bottom - top, 1.0f);
586
587    // TODO: Pick the program matching the current shader
588    sp<DrawColorProgram> program = mDrawColorProgram;
589    if (!useProgram(program)) {
590        const GLvoid* p = &gDrawColorVertices[0].position[0];
591        glVertexAttribPointer(program->position, 2, GL_FLOAT, GL_FALSE,
592                gDrawColorVertexStride, p);
593    }
594
595    if (!ignoreTransform) {
596        program->set(mOrthoMatrix, mModelView, mSnapshot->transform);
597    } else {
598        mat4 identity;
599        program->set(mOrthoMatrix, mModelView, identity);
600    }
601
602    glUniform4f(program->color, r, g, b, a);
603
604    glDrawArrays(GL_TRIANGLE_STRIP, 0, gDrawColorVertexCount);
605}
606
607void OpenGLRenderer::drawBitmapShader(float left, float top, float right, float bottom,
608        float alpha, SkXfermode::Mode mode) {
609    const Texture* texture = mTextureCache.get(mShaderBitmap);
610
611    const float width = texture->width;
612    const float height = texture->height;
613
614    // This could be done in the vertex shader but we have only 4 vertices
615    float u1 = 0.0f;
616    float v1 = 0.0f;
617    float u2 = right - left;
618    float v2 = bottom - top;
619
620    if (mShaderMatrix) {
621        SkMatrix inverse;
622        mShaderMatrix->invert(&inverse);
623        mat4 m(inverse);
624        Rect r(u1, v1, u2, v2);
625        m.mapRect(r);
626
627        u1 = r.left;
628        u2 = r.right;
629        v1 = r.top;
630        v2 = r.bottom;
631    }
632
633    u1 /= width;
634    u2 /= width;
635    v1 /= height;
636    v2 /= height;
637
638    resetDrawTextureTexCoords(u1, v1, u2, v2);
639
640    drawTextureMesh(left, top, right, bottom, texture->id, alpha, mode, texture->blend,
641            &mDrawTextureVertices[0].position[0], &mDrawTextureVertices[0].texture[0], NULL);
642
643    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
644}
645
646void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
647        const Texture* texture, const SkPaint* paint) {
648    int alpha;
649    SkXfermode::Mode mode;
650    getAlphaAndMode(paint, &alpha, &mode);
651
652    drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode, texture->blend,
653            &mDrawTextureVertices[0].position[0], &mDrawTextureVertices[0].texture[0], NULL);
654}
655
656void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
657        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
658    drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
659            &mDrawTextureVertices[0].position[0], &mDrawTextureVertices[0].texture[0], NULL);
660}
661
662void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
663        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
664        GLvoid* vertices, GLvoid* texCoords, GLvoid* indices, GLsizei elementsCount) {
665    mModelView.loadTranslate(left, top, 0.0f);
666    mModelView.scale(right - left, bottom - top, 1.0f);
667
668    useProgram(mDrawTextureProgram);
669    mDrawTextureProgram->set(mOrthoMatrix, mModelView, mSnapshot->transform);
670
671    chooseBlending(blend || alpha < 1.0f, mode);
672
673    // TODO: Only bind/set parameters when needed
674    glBindTexture(GL_TEXTURE_2D, texture);
675    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, gTileModes[mShaderTileX]);
676    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, gTileModes[mShaderTileY]);
677
678    // Always premultiplied
679    glUniform4f(mDrawTextureProgram->color, alpha, alpha, alpha, alpha);
680
681    glVertexAttribPointer(mDrawTextureProgram->position, 2, GL_FLOAT, GL_FALSE,
682            gDrawTextureVertexStride, vertices);
683    glVertexAttribPointer(mDrawTextureProgram->texCoords, 2, GL_FLOAT, GL_FALSE,
684            gDrawTextureVertexStride, texCoords);
685
686    if (!indices) {
687        glDrawArrays(GL_TRIANGLE_STRIP, 0, gDrawTextureVertexCount);
688    } else {
689        glDrawElements(GL_TRIANGLES, elementsCount, GL_UNSIGNED_SHORT, indices);
690    }
691
692    glBindTexture(GL_TEXTURE_2D, 0);
693}
694
695void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode, bool isPremultiplied) {
696    // In theory we should not blend if the mode is Src, but it's rare enough
697    // that it's not worth it
698    blend = blend || mode != SkXfermode::kSrcOver_Mode;
699    if (blend) {
700        if (!mBlend) {
701            glEnable(GL_BLEND);
702        }
703
704        GLenum sourceMode = gBlends[mode].src;
705        GLenum destMode = gBlends[mode].dst;
706        if (!isPremultiplied && sourceMode == GL_ONE) {
707            sourceMode = GL_SRC_ALPHA;
708        }
709
710        if (sourceMode != mLastSrcMode || destMode != mLastDstMode) {
711            glBlendFunc(sourceMode, destMode);
712            mLastSrcMode = sourceMode;
713            mLastDstMode = destMode;
714        }
715    } else if (mBlend) {
716        glDisable(GL_BLEND);
717    }
718    mBlend = blend;
719}
720
721bool OpenGLRenderer::useProgram(const sp<Program>& program) {
722    if (!program->isInUse()) {
723        mCurrentProgram->remove();
724        program->use();
725        mCurrentProgram = program;
726        return false;
727    }
728    return true;
729}
730
731void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
732    TextureVertex* v = &mDrawTextureVertices[0];
733    TextureVertex::setUV(v++, u1, v1);
734    TextureVertex::setUV(v++, u2, v1);
735    TextureVertex::setUV(v++, u1, v2);
736    TextureVertex::setUV(v++, u2, v2);
737}
738
739void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
740    if (paint) {
741        const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
742        if (!isMode) {
743            // Assume SRC_OVER
744            *mode = SkXfermode::kSrcOver_Mode;
745        }
746
747        // Skia draws using the color's alpha channel if < 255
748        // Otherwise, it uses the paint's alpha
749        int color = paint->getColor();
750        *alpha = (color >> 24) & 0xFF;
751        if (*alpha == 255) {
752            *alpha = paint->getAlpha();
753        }
754    } else {
755        *mode = SkXfermode::kSrcOver_Mode;
756        *alpha = 255;
757    }
758}
759
760}; // namespace uirenderer
761}; // namespace android
762