OpenGLRenderer.cpp revision ce0537b80087a6225273040a987414b1dd081aa0
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, 1.0f),
58        FV(1.0f, 0.0f, 1.0f, 1.0f),
59        FV(0.0f, 1.0f, 0.0f, 0.0f),
60        FV(1.0f, 1.0f, 1.0f, 0.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, v1);
209
210    drawTextureRect(layer.left, layer.top, layer.right, layer.bottom,
211            current->texture, current->alpha, current->mode, true);
212
213    resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.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    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
267    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
268
269    // TODO ***** IMPORTANT *****
270    // Creating a texture-backed FBO works only if the texture is the same size
271    // as the original rendering buffer (in this case, mWidth and mHeight.)
272    // This is expensive and wasteful and must be fixed.
273    // TODO Additionally we should use an FBO cache
274
275    const GLsizei width = mWidth; //right - left;
276    const GLsizei height = mHeight; //bottom - right;
277
278    const GLint format = (flags & SkCanvas::kHasAlphaLayer_SaveFlag) ? GL_RGBA : GL_RGB;
279    glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, NULL);
280    glBindTexture(GL_TEXTURE_2D, 0);
281
282    // Bind texture to FBO
283    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
284            snapshot->texture, 0);
285
286    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
287    if (status != GL_FRAMEBUFFER_COMPLETE) {
288        LOGD("Framebuffer incomplete %d", status);
289
290        glDeleteFramebuffers(1, &snapshot->fbo);
291        glDeleteTextures(1, &snapshot->texture);
292
293        return false;
294    }
295
296    snapshot->flags |= Snapshot::kFlagIsLayer;
297    snapshot->mode = mode;
298    snapshot->alpha = alpha / 255.0f;
299    snapshot->layer.set(left, top, right, bottom);
300
301    return true;
302}
303
304///////////////////////////////////////////////////////////////////////////////
305// Transforms
306///////////////////////////////////////////////////////////////////////////////
307
308void OpenGLRenderer::translate(float dx, float dy) {
309    mSnapshot->transform.translate(dx, dy, 0.0f);
310    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
311}
312
313void OpenGLRenderer::rotate(float degrees) {
314    mSnapshot->transform.rotate(degrees, 0.0f, 0.0f, 1.0f);
315    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
316}
317
318void OpenGLRenderer::scale(float sx, float sy) {
319    mSnapshot->transform.scale(sx, sy, 1.0f);
320    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
321}
322
323void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
324    mSnapshot->transform.load(*matrix);
325    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
326}
327
328void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
329    mSnapshot->transform.copyTo(*matrix);
330}
331
332void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
333    mat4 m(*matrix);
334    mSnapshot->transform.multiply(m);
335    mSnapshot->flags |= Snapshot::kFlagDirtyTransform;
336}
337
338///////////////////////////////////////////////////////////////////////////////
339// Clipping
340///////////////////////////////////////////////////////////////////////////////
341
342void OpenGLRenderer::setScissorFromClip() {
343    const Rect& clip = mSnapshot->getMappedClip();
344    glScissor(clip.left, mHeight - clip.bottom, clip.getWidth(), clip.getHeight());
345}
346
347const Rect& OpenGLRenderer::getClipBounds() {
348    return mSnapshot->clipRect;
349}
350
351bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
352    /*
353     * The documentation of quickReject() indicates that the specified rect
354     * is transformed before being compared to the clip rect. However, the
355     * clip rect is not stored transformed in the snapshot and can thus be
356     * compared directly
357     *
358     * The following code can be used instead to performed a mapped comparison:
359     *
360     *     mSnapshot->transform.mapRect(r);
361     *     const Rect& clip = mSnapshot->getMappedClip();
362     *     return !clip.intersects(r);
363     */
364    Rect r(left, top, right, bottom);
365    return !mSnapshot->clipRect.intersects(r);
366}
367
368bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom) {
369    bool clipped = mSnapshot->clipRect.intersect(left, top, right, bottom);
370    if (clipped) {
371        mSnapshot->flags |= Snapshot::kFlagClipSet;
372        setScissorFromClip();
373    }
374    return clipped;
375}
376
377///////////////////////////////////////////////////////////////////////////////
378// Drawing
379///////////////////////////////////////////////////////////////////////////////
380
381void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, float left, float top, const SkPaint* paint) {
382    LOGD("Drawing bitmap!");
383}
384
385void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
386    const Rect& clip = mSnapshot->clipRect;
387    drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode);
388}
389
390void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, const SkPaint* p) {
391    SkXfermode::Mode mode;
392
393    const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode);
394    if (!isMode) {
395        // Assume SRC_OVER
396        mode = SkXfermode::kSrcOver_Mode;
397    }
398
399    // Skia draws using the color's alpha channel if < 255
400    // Otherwise, it uses the paint's alpha
401    int color = p->getColor();
402    if (((color >> 24) & 0xFF) == 255) {
403        color |= p->getAlpha() << 24;
404    }
405
406    drawColorRect(left, top, right, bottom, color, mode);
407}
408
409void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
410        int color, SkXfermode::Mode mode) {
411    const int alpha = (color >> 24) & 0xFF;
412    const bool blend = alpha < 255 || mode != SkXfermode::kSrcOver_Mode;
413
414    const GLfloat a = alpha                  / 255.0f;
415    const GLfloat r = ((color >> 16) & 0xFF) / 255.0f;
416    const GLfloat g = ((color >>  8) & 0xFF) / 255.0f;
417    const GLfloat b = ((color      ) & 0xFF) / 255.0f;
418
419    if (blend) {
420        glEnable(GL_BLEND);
421        glBlendFunc(gBlends[mode].src, gBlends[mode].dst);
422    }
423
424    mModelView.loadTranslate(left, top, 0.0f);
425    mModelView.scale(right - left, bottom - top, 1.0f);
426
427    mDrawColorShader->use(&mOrthoMatrix[0], &mModelView.data[0], &mSnapshot->transform.data[0]);
428
429    const GLvoid* p = &gDrawColorVertices[0].position[0];
430
431    glEnableVertexAttribArray(mDrawColorShader->position);
432    glVertexAttribPointer(mDrawColorShader->position, 2, GL_FLOAT, GL_FALSE,
433            gDrawColorVertexStride, p);
434    glVertexAttrib4f(mDrawColorShader->color, r, g, b, a);
435
436    glDrawArrays(GL_TRIANGLE_STRIP, 0, gDrawColorVertexCount);
437
438    glDisableVertexAttribArray(mDrawColorShader->position);
439
440    if (blend) {
441        glDisable(GL_BLEND);
442    }
443}
444
445void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
446        GLuint texture, float alpha, SkXfermode::Mode mode, bool isPremultiplied) {
447    mModelView.loadTranslate(left, top, 0.0f);
448    mModelView.scale(right - left, bottom - top, 1.0f);
449
450    mDrawTextureShader->use(&mOrthoMatrix[0], &mModelView.data[0], &mSnapshot->transform.data[0]);
451
452    GLenum sourceMode = gBlends[mode].src;
453    if (!isPremultiplied && sourceMode == GL_ONE) {
454        sourceMode = GL_SRC_ALPHA;
455    }
456
457    // TODO: Try to disable blending when the texture is opaque and alpha == 1.0f
458    glEnable(GL_BLEND);
459    glBlendFunc(sourceMode, gBlends[mode].dst);
460
461    glBindTexture(GL_TEXTURE_2D, texture);
462
463    glActiveTexture(GL_TEXTURE0);
464    glUniform1i(mDrawTextureShader->sampler, 0);
465
466    const GLvoid* p = &mDrawTextureVertices[0].position[0];
467    const GLvoid* t = &mDrawTextureVertices[0].texture[0];
468
469    glEnableVertexAttribArray(mDrawTextureShader->position);
470    glVertexAttribPointer(mDrawTextureShader->position, 2, GL_FLOAT, GL_FALSE,
471            gDrawTextureVertexStride, p);
472
473    glEnableVertexAttribArray(mDrawTextureShader->texCoords);
474    glVertexAttribPointer(mDrawTextureShader->texCoords, 2, GL_FLOAT, GL_FALSE,
475            gDrawTextureVertexStride, t);
476
477    glVertexAttrib4f(mDrawTextureShader->color, 1.0f, 1.0f, 1.0f, alpha);
478
479    glDrawArrays(GL_TRIANGLE_STRIP, 0, gDrawTextureVertexCount);
480
481    glDisableVertexAttribArray(mDrawTextureShader->position);
482    glDisableVertexAttribArray(mDrawTextureShader->texCoords);
483
484    glBindTexture(GL_TEXTURE_2D, 0);
485    glDisable(GL_BLEND);
486}
487
488void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
489    mDrawTextureVertices[0].texture[0] = u1;
490    mDrawTextureVertices[0].texture[1] = v2;
491    mDrawTextureVertices[1].texture[0] = u2;
492    mDrawTextureVertices[1].texture[1] = v2;
493    mDrawTextureVertices[2].texture[0] = u1;
494    mDrawTextureVertices[2].texture[1] = v1;
495    mDrawTextureVertices[3].texture[0] = u2;
496    mDrawTextureVertices[3].texture[1] = v1;
497}
498
499}; // namespace uirenderer
500}; // namespace android
501