OpenGLRenderer.cpp revision 8ba548f81d1ab5f1750cbf86098c4a14e0b8bead
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 <utils/Log.h>
26
27#include "OpenGLRenderer.h"
28
29namespace android {
30namespace uirenderer {
31
32///////////////////////////////////////////////////////////////////////////////
33// Defines
34///////////////////////////////////////////////////////////////////////////////
35
36#define MAX_TEXTURE_COUNT 128
37
38#define SV(x, y) { { x, y } }
39#define FV(x, y, u, v) { { x, y }, { u, v } }
40
41///////////////////////////////////////////////////////////////////////////////
42// Globals
43///////////////////////////////////////////////////////////////////////////////
44
45static const SimpleVertex gDrawColorVertices[] = {
46        SV(0.0f, 0.0f),
47        SV(1.0f, 0.0f),
48        SV(0.0f, 1.0f),
49        SV(1.0f, 1.0f)
50};
51static const GLsizei gDrawColorVertexStride = sizeof(SimpleVertex);
52static const GLsizei gDrawColorVertexCount = 4;
53
54// This array is never used directly but used as a memcpy source in the
55// OpenGLRenderer constructor
56static const TextureVertex gDrawTextureVertices[] = {
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 gDrawTextureVertexStride = sizeof(TextureVertex);
63static const GLsizei gDrawTextureVertexCount = 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
82///////////////////////////////////////////////////////////////////////////////
83// Constructors/destructor
84///////////////////////////////////////////////////////////////////////////////
85
86OpenGLRenderer::OpenGLRenderer(): mTextureCache(MAX_TEXTURE_COUNT) {
87    LOGD("Create OpenGLRenderer");
88
89    mDrawColorShader = new DrawColorProgram;
90    mDrawTextureShader = new DrawTextureProgram;
91
92    memcpy(mDrawTextureVertices, gDrawTextureVertices, sizeof(gDrawTextureVertices));
93}
94
95OpenGLRenderer::~OpenGLRenderer() {
96    LOGD("Destroy OpenGLRenderer");
97
98    mTextureCache.clear();
99}
100
101///////////////////////////////////////////////////////////////////////////////
102// Setup
103///////////////////////////////////////////////////////////////////////////////
104
105void OpenGLRenderer::setViewport(int width, int height) {
106    glViewport(0, 0, width, height);
107
108    mat4 ortho;
109    ortho.loadOrtho(0, width, height, 0, -1, 1);
110    ortho.copyTo(mOrthoMatrix);
111
112    mWidth = width;
113    mHeight = height;
114}
115
116void OpenGLRenderer::prepare() {
117    mSnapshot = &mFirstSnapshot;
118    mSaveCount = 0;
119
120    glDisable(GL_SCISSOR_TEST);
121
122    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
123    glClear(GL_COLOR_BUFFER_BIT);
124
125    glEnable(GL_SCISSOR_TEST);
126    glScissor(0, 0, mWidth, mHeight);
127
128    mSnapshot->clipRect.set(0.0f, 0.0f, mWidth, mHeight);
129}
130
131///////////////////////////////////////////////////////////////////////////////
132// State management
133///////////////////////////////////////////////////////////////////////////////
134
135int OpenGLRenderer::getSaveCount() const {
136    return mSaveCount;
137}
138
139int OpenGLRenderer::save(int flags) {
140    return saveSnapshot();
141}
142
143void OpenGLRenderer::restore() {
144    if (mSaveCount == 0) return;
145
146    if (restoreSnapshot()) {
147        setScissorFromClip();
148    }
149}
150
151void OpenGLRenderer::restoreToCount(int saveCount) {
152    if (saveCount <= 0 || saveCount > mSaveCount) return;
153
154    bool restoreClip = false;
155
156    while (mSaveCount != saveCount - 1) {
157        restoreClip |= restoreSnapshot();
158    }
159
160    if (restoreClip) {
161        setScissorFromClip();
162    }
163}
164
165int OpenGLRenderer::saveSnapshot() {
166    mSnapshot = new Snapshot(mSnapshot);
167    return ++mSaveCount;
168}
169
170bool OpenGLRenderer::restoreSnapshot() {
171    bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
172    bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
173
174    sp<Snapshot> current = mSnapshot;
175    sp<Snapshot> previous = mSnapshot->previous;
176
177    if (restoreLayer) {
178        composeLayer(current, previous);
179    }
180
181    mSnapshot = previous;
182    mSaveCount--;
183
184    return restoreClip;
185}
186
187void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
188    // Unbind current FBO and restore previous one
189    // Most of the time, previous->fbo will be 0 to bind the default buffer
190    glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
191
192    // Restore the clip from the previous snapshot
193    const Rect& clip = previous->getMappedClip();
194    glScissor(clip.left, mHeight - clip.bottom, clip.getWidth(), clip.getHeight());
195
196    // Compute the correct texture coordinates for the FBO texture
197    // The texture is currently as big as the window but drawn with
198    // a quad of the appropriate size
199    const Rect& layer = current->layer;
200    Rect texCoords(current->layer);
201    mSnapshot->transform.mapRect(texCoords);
202
203    const float u1 = texCoords.left / float(mWidth);
204    const float v1 = (mHeight - texCoords.top) / float(mHeight);
205    const float u2 = texCoords.right / float(mWidth);
206    const float v2 = (mHeight - texCoords.bottom) / float(mHeight);
207
208    resetDrawTextureTexCoords(u1, v1, u2, v2);
209
210    drawTextureRect(layer.left, layer.top, layer.right, layer.bottom,
211            current->texture, current->alpha, current->mode, true, true);
212
213    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
214
215    glDeleteFramebuffers(1, &current->fbo);
216    glDeleteTextures(1, &current->texture);
217}
218
219///////////////////////////////////////////////////////////////////////////////
220// Layers
221///////////////////////////////////////////////////////////////////////////////
222
223int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
224        const SkPaint* p, int flags) {
225    int count = saveSnapshot();
226
227    int alpha = 255;
228    SkXfermode::Mode mode;
229
230    if (p) {
231        alpha = p->getAlpha();
232        const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
233        if (!isMode) {
234            // Assume SRC_OVER
235            mode = SkXfermode::kSrcOver_Mode;
236        }
237    } else {
238        mode = SkXfermode::kSrcOver_Mode;
239    }
240
241    createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags);
242
243    return count;
244}
245
246int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom,
247        int alpha, int flags) {
248    int count = saveSnapshot();
249    createLayer(mSnapshot, left, top, right, bottom, alpha, SkXfermode::kSrcOver_Mode, flags);
250    return count;
251}
252
253bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top,
254        float right, float bottom, int alpha, SkXfermode::Mode mode,int flags) {
255    // Generate the FBO and attach the texture
256    glGenFramebuffers(1, &snapshot->fbo);
257    glBindFramebuffer(GL_FRAMEBUFFER, snapshot->fbo);
258
259    // Generate the texture in which the FBO will draw
260    glGenTextures(1, &snapshot->texture);
261    glBindTexture(GL_TEXTURE_2D, snapshot->texture);
262
263    // The FBO will not be scaled, so we can use lower quality filtering
264    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
265    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
266
267    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
268    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
269
270    // TODO VERY IMPORTANT: Fix TextView to not call saveLayer() all the time
271    // TODO ***** IMPORTANT *****
272    // Creating a texture-backed FBO works only if the texture is the same size
273    // as the original rendering buffer (in this case, mWidth and mHeight.)
274    // This is expensive and wasteful and must be fixed.
275    // TODO Additionally we should use an FBO cache
276
277    const GLsizei width = mWidth; //right - left;
278    const GLsizei height = mHeight; //bottom - right;
279
280    const GLint format = (flags & SkCanvas::kHasAlphaLayer_SaveFlag) ? GL_RGBA : GL_RGB;
281    glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, NULL);
282    glBindTexture(GL_TEXTURE_2D, 0);
283
284    // Bind texture to FBO
285    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
286            snapshot->texture, 0);
287
288    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
289    if (status != GL_FRAMEBUFFER_COMPLETE) {
290        LOGD("Framebuffer incomplete %d", status);
291
292        glDeleteFramebuffers(1, &snapshot->fbo);
293        glDeleteTextures(1, &snapshot->texture);
294
295        return false;
296    }
297
298    snapshot->flags |= Snapshot::kFlagIsLayer;
299    snapshot->mode = mode;
300    snapshot->alpha = alpha / 255.0f;
301    snapshot->layer.set(left, top, right, bottom);
302
303    return true;
304}
305
306///////////////////////////////////////////////////////////////////////////////
307// Transforms
308///////////////////////////////////////////////////////////////////////////////
309
310void OpenGLRenderer::translate(float dx, float dy) {
311    mSnapshot->transform.translate(dx, dy, 0.0f);
312    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
313}
314
315void OpenGLRenderer::rotate(float degrees) {
316    mSnapshot->transform.rotate(degrees, 0.0f, 0.0f, 1.0f);
317    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
318}
319
320void OpenGLRenderer::scale(float sx, float sy) {
321    mSnapshot->transform.scale(sx, sy, 1.0f);
322    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
323}
324
325void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
326    mSnapshot->transform.load(*matrix);
327    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
328}
329
330void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
331    mSnapshot->transform.copyTo(*matrix);
332}
333
334void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
335    mat4 m(*matrix);
336    mSnapshot->transform.multiply(m);
337    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
338}
339
340///////////////////////////////////////////////////////////////////////////////
341// Clipping
342///////////////////////////////////////////////////////////////////////////////
343
344void OpenGLRenderer::setScissorFromClip() {
345    const Rect& clip = mSnapshot->getMappedClip();
346    glScissor(clip.left, mHeight - clip.bottom, clip.getWidth(), clip.getHeight());
347}
348
349const Rect& OpenGLRenderer::getClipBounds() {
350    return mSnapshot->clipRect;
351}
352
353bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
354    /*
355     * The documentation of quickReject() indicates that the specified rect
356     * is transformed before being compared to the clip rect. However, the
357     * clip rect is not stored transformed in the snapshot and can thus be
358     * compared directly
359     *
360     * The following code can be used instead to performed a mapped comparison:
361     *
362     *     mSnapshot->transform.mapRect(r);
363     *     const Rect& clip = mSnapshot->getMappedClip();
364     *     return !clip.intersects(r);
365     */
366    Rect r(left, top, right, bottom);
367    return !mSnapshot->clipRect.intersects(r);
368}
369
370bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom) {
371    bool clipped = mSnapshot->clipRect.intersect(left, top, right, bottom);
372    if (clipped) {
373        mSnapshot->flags |= Snapshot::kFlagClipSet;
374        setScissorFromClip();
375    }
376    return clipped;
377}
378
379///////////////////////////////////////////////////////////////////////////////
380// Drawing
381///////////////////////////////////////////////////////////////////////////////
382
383void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, const SkPaint* paint) {
384    Texture* texture = mTextureCache.get(bitmap);
385
386    int alpha;
387    SkXfermode::Mode mode;
388    getAlphaAndMode(paint, &alpha, &mode);
389
390    drawTextureRect(left, top, left + texture->width, top + texture->height, texture->id,
391            alpha / 255.0f, mode, texture->blend, true);
392}
393
394void OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
395         float srcLeft, float srcTop, float srcRight, float srcBottom,
396         float dstLeft, float dstTop, float dstRight, float dstBottom,
397         const SkMatrix* matrix, const SkPaint* paint) {
398    Texture* texture = mTextureCache.get(bitmap);
399
400    int alpha;
401    SkXfermode::Mode mode;
402    getAlphaAndMode(paint, &alpha, &mode);
403
404    const float width = texture->width;
405    const float height = texture->height;
406
407    const float u1 = srcLeft / width;
408    const float v1 = srcTop / height;
409    const float u2 = srcRight / width;
410    const float v2 = srcBottom / height;
411
412    resetDrawTextureTexCoords(u1, v1, u2, v2);
413
414    // TODO: implement Matrix
415
416    drawTextureRect(dstLeft, dstTop, dstRight, dstBottom, texture->id,
417            alpha / 255.0f, mode, texture->blend, true);
418
419    resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
420}
421
422void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
423    const Rect& clip = mSnapshot->clipRect;
424    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode);
425}
426
427void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, const SkPaint* p) {
428    SkXfermode::Mode mode;
429
430    const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
431    if (!isMode) {
432        // Assume SRC_OVER
433        mode = SkXfermode::kSrcOver_Mode;
434    }
435
436    // Skia draws using the color's alpha channel if < 255
437    // Otherwise, it uses the paint's alpha
438    int color = p->getColor();
439    if (((color >> 24) & 0xFF) == 255) {
440        color |= p->getAlpha() << 24;
441    }
442
443    drawColorRect(left, top, right, bottom, color, mode);
444}
445
446void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
447        int color, SkXfermode::Mode mode) {
448    const int alpha = (color >> 24) & 0xFF;
449    const bool blend = alpha < 255 || mode != SkXfermode::kSrcOver_Mode;
450
451    const GLfloat a = alpha                  / 255.0f;
452    const GLfloat r = ((color >> 16) & 0xFF) / 255.0f;
453    const GLfloat g = ((color >>  8) & 0xFF) / 255.0f;
454    const GLfloat b = ((color      ) & 0xFF) / 255.0f;
455
456    if (blend) {
457        glEnable(GL_BLEND);
458        glBlendFunc(gBlends[mode].src, gBlends[mode].dst);
459    }
460
461    mModelView.loadTranslate(left, top, 0.0f);
462    mModelView.scale(right - left, bottom - top, 1.0f);
463
464    mDrawColorShader->use(&mOrthoMatrix[0], &mModelView.data[0], &mSnapshot->transform.data[0]);
465
466    const GLvoid* p = &gDrawColorVertices[0].position[0];
467
468    glEnableVertexAttribArray(mDrawColorShader->position);
469    glVertexAttribPointer(mDrawColorShader->position, 2, GL_FLOAT, GL_FALSE,
470            gDrawColorVertexStride, p);
471    glVertexAttrib4f(mDrawColorShader->color, r, g, b, a);
472
473    glDrawArrays(GL_TRIANGLE_STRIP, 0, gDrawColorVertexCount);
474
475    glDisableVertexAttribArray(mDrawColorShader->position);
476
477    if (blend) {
478        glDisable(GL_BLEND);
479    }
480}
481
482void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
483        GLuint texture, float alpha, SkXfermode::Mode mode, bool blend, bool isPremultiplied) {
484    mModelView.loadTranslate(left, top, 0.0f);
485    mModelView.scale(right - left, bottom - top, 1.0f);
486
487    mDrawTextureShader->use(&mOrthoMatrix[0], &mModelView.data[0], &mSnapshot->transform.data[0]);
488
489    if (blend || alpha < 1.0f || mode != SkXfermode::kSrcOver_Mode) {
490        GLenum sourceMode = gBlends[mode].src;
491        if (!isPremultiplied && sourceMode == GL_ONE) {
492            sourceMode = GL_SRC_ALPHA;
493        }
494
495        glEnable(GL_BLEND);
496        glBlendFunc(sourceMode, gBlends[mode].dst);
497    }
498
499    glBindTexture(GL_TEXTURE_2D, texture);
500
501    // TODO handle tiling and filtering here
502
503    glActiveTexture(GL_TEXTURE0);
504    glUniform1i(mDrawTextureShader->sampler, 0);
505
506    const GLvoid* p = &mDrawTextureVertices[0].position[0];
507    const GLvoid* t = &mDrawTextureVertices[0].texture[0];
508
509    glEnableVertexAttribArray(mDrawTextureShader->position);
510    glVertexAttribPointer(mDrawTextureShader->position, 2, GL_FLOAT, GL_FALSE,
511            gDrawTextureVertexStride, p);
512
513    glEnableVertexAttribArray(mDrawTextureShader->texCoords);
514    glVertexAttribPointer(mDrawTextureShader->texCoords, 2, GL_FLOAT, GL_FALSE,
515            gDrawTextureVertexStride, t);
516
517    glVertexAttrib4f(mDrawTextureShader->color, 1.0f, 1.0f, 1.0f, alpha);
518
519    glDrawArrays(GL_TRIANGLE_STRIP, 0, gDrawTextureVertexCount);
520
521    glDisableVertexAttribArray(mDrawTextureShader->position);
522    glDisableVertexAttribArray(mDrawTextureShader->texCoords);
523
524    glBindTexture(GL_TEXTURE_2D, 0);
525    glDisable(GL_BLEND);
526}
527
528void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
529    mDrawTextureVertices[0].texture[0] = u1;
530    mDrawTextureVertices[0].texture[1] = v1;
531    mDrawTextureVertices[1].texture[0] = u2;
532    mDrawTextureVertices[1].texture[1] = v1;
533    mDrawTextureVertices[2].texture[0] = u1;
534    mDrawTextureVertices[2].texture[1] = v2;
535    mDrawTextureVertices[3].texture[0] = u2;
536    mDrawTextureVertices[3].texture[1] = v2;
537}
538
539void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
540    if (paint) {
541        const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode);
542        if (!isMode) {
543            // Assume SRC_OVER
544            *mode = SkXfermode::kSrcOver_Mode;
545        }
546
547        // Skia draws using the color's alpha channel if < 255
548        // Otherwise, it uses the paint's alpha
549        int color = paint->getColor();
550        *alpha = (color >> 24) & 0xFF;
551        if (*alpha == 255) {
552            *alpha = paint->getAlpha();
553        }
554    } else {
555        *mode = SkXfermode::kSrcOver_Mode;
556        *alpha = 255;
557    }
558}
559
560}; // namespace uirenderer
561}; // namespace android
562