LayerRenderer.cpp revision e49d7ec36132f33b7c9e2c044ab9dd3585aa3747
1/*
2 * Copyright (C) 2011 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 <ui/Rect.h>
20
21#include "LayerCache.h"
22#include "LayerRenderer.h"
23#include "Matrix.h"
24#include "Properties.h"
25#include "Rect.h"
26
27namespace android {
28namespace uirenderer {
29
30///////////////////////////////////////////////////////////////////////////////
31// Rendering
32///////////////////////////////////////////////////////////////////////////////
33
34LayerRenderer::LayerRenderer(Layer* layer): mLayer(layer) {
35}
36
37LayerRenderer::~LayerRenderer() {
38}
39
40int LayerRenderer::prepareDirty(float left, float top, float right, float bottom, bool opaque) {
41    LAYER_RENDERER_LOGD("Rendering into layer, fbo = %d", mLayer->getFbo());
42
43    glBindFramebuffer(GL_FRAMEBUFFER, mLayer->getFbo());
44
45    const float width = mLayer->layer.getWidth();
46    const float height = mLayer->layer.getHeight();
47
48    Rect dirty(left, top, right, bottom);
49    if (dirty.isEmpty() || (dirty.left <= 0 && dirty.top <= 0 &&
50            dirty.right >= width && dirty.bottom >= height)) {
51        mLayer->region.clear();
52        dirty.set(0.0f, 0.0f, width, height);
53    } else {
54        dirty.intersect(0.0f, 0.0f, width, height);
55        android::Rect r(dirty.left, dirty.top, dirty.right, dirty.bottom);
56        mLayer->region.subtractSelf(r);
57    }
58
59    return OpenGLRenderer::prepareDirty(dirty.left, dirty.top, dirty.right, dirty.bottom, opaque);
60}
61
62void LayerRenderer::finish() {
63    OpenGLRenderer::finish();
64
65    generateMesh();
66
67    LAYER_RENDERER_LOGD("Finished rendering into layer, fbo = %d", mLayer->getFbo());
68
69    // No need to unbind our FBO, this will be taken care of by the caller
70    // who will invoke OpenGLRenderer::resume()
71}
72
73GLint LayerRenderer::getTargetFbo() {
74    return mLayer->getFbo();
75}
76
77///////////////////////////////////////////////////////////////////////////////
78// Dirty region tracking
79///////////////////////////////////////////////////////////////////////////////
80
81bool LayerRenderer::hasLayer() {
82    return true;
83}
84
85Region* LayerRenderer::getRegion() {
86    if (getSnapshot()->flags & Snapshot::kFlagFboTarget) {
87        return OpenGLRenderer::getRegion();
88    }
89    return &mLayer->region;
90}
91
92// TODO: This implementation is flawed and can generate T-junctions
93//       in the mesh, which will in turn produce cracks when the
94//       mesh is rotated/skewed. The easiest way to fix this would
95//       be, for each row, to add new vertices shared with the previous
96//       row when the two rows share an edge.
97//       In practice, T-junctions do not appear often so this has yet
98//       to be fixed.
99void LayerRenderer::generateMesh() {
100    if (mLayer->region.isRect() || mLayer->region.isEmpty()) {
101        if (mLayer->mesh) {
102            delete mLayer->mesh;
103            delete mLayer->meshIndices;
104
105            mLayer->mesh = NULL;
106            mLayer->meshIndices = NULL;
107            mLayer->meshElementCount = 0;
108        }
109
110        mLayer->setRegionAsRect();
111        return;
112    }
113
114    size_t count;
115    const android::Rect* rects = mLayer->region.getArray(&count);
116
117    GLsizei elementCount = count * 6;
118
119    if (mLayer->mesh && mLayer->meshElementCount < elementCount) {
120        delete mLayer->mesh;
121        delete mLayer->meshIndices;
122
123        mLayer->mesh = NULL;
124        mLayer->meshIndices = NULL;
125    }
126
127    bool rebuildIndices = false;
128    if (!mLayer->mesh) {
129        mLayer->mesh = new TextureVertex[count * 4];
130        mLayer->meshIndices = new uint16_t[elementCount];
131        rebuildIndices = true;
132    }
133    mLayer->meshElementCount = elementCount;
134
135    const float texX = 1.0f / float(mLayer->getWidth());
136    const float texY = 1.0f / float(mLayer->getHeight());
137    const float height = mLayer->layer.getHeight();
138
139    TextureVertex* mesh = mLayer->mesh;
140    uint16_t* indices = mLayer->meshIndices;
141
142    for (size_t i = 0; i < count; i++) {
143        const android::Rect* r = &rects[i];
144
145        const float u1 = r->left * texX;
146        const float v1 = (height - r->top) * texY;
147        const float u2 = r->right * texX;
148        const float v2 = (height - r->bottom) * texY;
149
150        TextureVertex::set(mesh++, r->left, r->top, u1, v1);
151        TextureVertex::set(mesh++, r->right, r->top, u2, v1);
152        TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
153        TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
154
155        if (rebuildIndices) {
156            uint16_t quad = i * 4;
157            int index = i * 6;
158            indices[index    ] = quad;       // top-left
159            indices[index + 1] = quad + 1;   // top-right
160            indices[index + 2] = quad + 2;   // bottom-left
161            indices[index + 3] = quad + 2;   // bottom-left
162            indices[index + 4] = quad + 1;   // top-right
163            indices[index + 5] = quad + 3;   // bottom-right
164        }
165    }
166}
167
168///////////////////////////////////////////////////////////////////////////////
169// Layers management
170///////////////////////////////////////////////////////////////////////////////
171
172Layer* LayerRenderer::createLayer(uint32_t width, uint32_t height, bool isOpaque) {
173    LAYER_RENDERER_LOGD("Requesting new render layer %dx%d", width, height);
174
175    Caches& caches = Caches::getInstance();
176    GLuint fbo = caches.fboCache.get();
177    if (!fbo) {
178        ALOGW("Could not obtain an FBO");
179        return NULL;
180    }
181
182    caches.activeTexture(0);
183    Layer* layer = caches.layerCache.get(width, height);
184    if (!layer) {
185        ALOGW("Could not obtain a layer");
186        return NULL;
187    }
188
189    layer->setFbo(fbo);
190    layer->layer.set(0.0f, 0.0f, width, height);
191    layer->texCoords.set(0.0f, height / float(layer->getHeight()),
192            width / float(layer->getWidth()), 0.0f);
193    layer->setAlpha(255, SkXfermode::kSrcOver_Mode);
194    layer->setBlend(!isOpaque);
195    layer->setColorFilter(NULL);
196    layer->region.clear();
197
198    GLuint previousFbo;
199    glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*) &previousFbo);
200
201    glBindFramebuffer(GL_FRAMEBUFFER, layer->getFbo());
202    layer->bindTexture();
203
204    // Initialize the texture if needed
205    if (layer->isEmpty()) {
206        layer->setEmpty(false);
207        layer->allocateTexture(GL_RGBA, GL_UNSIGNED_BYTE);
208
209        if (glGetError() != GL_NO_ERROR) {
210            ALOGD("Could not allocate texture for layer (fbo=%d %dx%d)",
211                    fbo, width, height);
212
213            glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
214            caches.fboCache.put(fbo);
215
216            layer->deleteTexture();
217            delete layer;
218
219            return NULL;
220        }
221    }
222
223    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
224            layer->getTexture(), 0);
225
226    caches.disableScissor();
227    glClear(GL_COLOR_BUFFER_BIT);
228
229    glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
230
231    return layer;
232}
233
234bool LayerRenderer::resizeLayer(Layer* layer, uint32_t width, uint32_t height) {
235    if (layer) {
236        LAYER_RENDERER_LOGD("Resizing layer fbo = %d to %dx%d", layer->getFbo(), width, height);
237
238        if (Caches::getInstance().layerCache.resize(layer, width, height)) {
239            layer->layer.set(0.0f, 0.0f, width, height);
240            layer->texCoords.set(0.0f, height / float(layer->getHeight()),
241                    width / float(layer->getWidth()), 0.0f);
242        } else {
243            layer->deleteTexture();
244            delete layer;
245            return false;
246        }
247    }
248
249    return true;
250}
251
252Layer* LayerRenderer::createTextureLayer(bool isOpaque) {
253    LAYER_RENDERER_LOGD("Creating new texture layer");
254
255    Layer* layer = new Layer(0, 0);
256    layer->setCacheable(false);
257    layer->setTextureLayer(true);
258    layer->setBlend(!isOpaque);
259    layer->setEmpty(true);
260    layer->setFbo(0);
261    layer->setAlpha(255, SkXfermode::kSrcOver_Mode);
262    layer->layer.set(0.0f, 0.0f, 0.0f, 0.0f);
263    layer->texCoords.set(0.0f, 1.0f, 1.0f, 0.0f);
264    layer->region.clear();
265    layer->setRenderTarget(GL_NONE); // see ::updateTextureLayer()
266
267    Caches::getInstance().activeTexture(0);
268    layer->generateTexture();
269
270    return layer;
271}
272
273void LayerRenderer::updateTextureLayer(Layer* layer, uint32_t width, uint32_t height,
274        bool isOpaque, GLenum renderTarget, float* transform) {
275    if (layer) {
276        layer->setBlend(!isOpaque);
277        layer->setSize(width, height);
278        layer->layer.set(0.0f, 0.0f, width, height);
279        layer->region.set(width, height);
280        layer->regionRect.set(0.0f, 0.0f, width, height);
281        layer->getTexTransform().load(transform);
282
283        if (renderTarget != layer->getRenderTarget()) {
284            layer->setRenderTarget(renderTarget);
285            layer->bindTexture();
286            layer->setFilter(GL_NEAREST, false, true);
287            layer->setWrap(GL_CLAMP_TO_EDGE, false, true);
288        }
289    }
290}
291
292void LayerRenderer::destroyLayer(Layer* layer) {
293    if (layer) {
294        LAYER_RENDERER_LOGD("Recycling layer, %dx%d fbo = %d",
295                layer->getWidth(), layer->getHeight(), layer->getFbo());
296
297        GLuint fbo = layer->getFbo();
298        if (fbo) {
299            flushLayer(layer);
300            Caches::getInstance().fboCache.put(fbo);
301            layer->setFbo(0);
302        }
303
304        if (!Caches::getInstance().layerCache.put(layer)) {
305            LAYER_RENDERER_LOGD("  Destroyed!");
306            layer->deleteTexture();
307            delete layer;
308        } else {
309            LAYER_RENDERER_LOGD("  Cached!");
310#if DEBUG_LAYER_RENDERER
311            Caches::getInstance().layerCache.dump();
312#endif
313            layer->region.clear();
314        }
315    }
316}
317
318void LayerRenderer::destroyLayerDeferred(Layer* layer) {
319    if (layer) {
320        LAYER_RENDERER_LOGD("Deferring layer destruction, fbo = %d", layer->getFbo());
321
322        Caches::getInstance().deleteLayerDeferred(layer);
323    }
324}
325
326void LayerRenderer::flushLayer(Layer* layer) {
327#ifdef GL_EXT_discard_framebuffer
328    GLuint fbo = layer->getFbo();
329    if (layer && fbo) {
330        // If possible, discard any enqueud operations on deferred
331        // rendering architectures
332        if (Caches::getInstance().extensions.hasDiscardFramebuffer()) {
333            GLuint previousFbo;
334            glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*) &previousFbo);
335
336            GLenum attachments = GL_COLOR_ATTACHMENT0;
337            if (fbo != previousFbo) glBindFramebuffer(GL_FRAMEBUFFER, fbo);
338            glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, &attachments);
339
340            if (fbo != previousFbo) glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
341        }
342    }
343#endif
344}
345
346bool LayerRenderer::copyLayer(Layer* layer, SkBitmap* bitmap) {
347    Caches& caches = Caches::getInstance();
348    if (layer && layer->isTextureLayer() && bitmap->width() <= caches.maxTextureSize &&
349            bitmap->height() <= caches.maxTextureSize) {
350
351        GLuint fbo = caches.fboCache.get();
352        if (!fbo) {
353            ALOGW("Could not obtain an FBO");
354            return false;
355        }
356
357        SkAutoLockPixels alp(*bitmap);
358
359        GLuint texture;
360        GLuint previousFbo;
361
362        GLenum format;
363        GLenum type;
364
365        GLenum error = GL_NO_ERROR;
366        bool status = false;
367
368        switch (bitmap->config()) {
369            case SkBitmap::kA8_Config:
370                format = GL_ALPHA;
371                type = GL_UNSIGNED_BYTE;
372                break;
373            case SkBitmap::kRGB_565_Config:
374                format = GL_RGB;
375                type = GL_UNSIGNED_SHORT_5_6_5;
376                break;
377            case SkBitmap::kARGB_4444_Config:
378                format = GL_RGBA;
379                type = GL_UNSIGNED_SHORT_4_4_4_4;
380                break;
381            case SkBitmap::kARGB_8888_Config:
382            default:
383                format = GL_RGBA;
384                type = GL_UNSIGNED_BYTE;
385                break;
386        }
387
388        float alpha = layer->getAlpha();
389        SkXfermode::Mode mode = layer->getMode();
390
391        layer->setAlpha(255, SkXfermode::kSrc_Mode);
392        layer->setFbo(fbo);
393
394        glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*) &previousFbo);
395        glBindFramebuffer(GL_FRAMEBUFFER, fbo);
396
397        glGenTextures(1, &texture);
398        if ((error = glGetError()) != GL_NO_ERROR) goto error;
399
400        caches.activeTexture(0);
401        glBindTexture(GL_TEXTURE_2D, texture);
402
403        glPixelStorei(GL_PACK_ALIGNMENT, bitmap->bytesPerPixel());
404
405        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
406        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
407
408        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
409        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
410
411        glTexImage2D(GL_TEXTURE_2D, 0, format, bitmap->width(), bitmap->height(),
412                0, format, type, NULL);
413        if ((error = glGetError()) != GL_NO_ERROR) goto error;
414
415        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
416                GL_TEXTURE_2D, texture, 0);
417        if ((error = glGetError()) != GL_NO_ERROR) goto error;
418
419        {
420            LayerRenderer renderer(layer);
421            renderer.setViewport(bitmap->width(), bitmap->height());
422            renderer.OpenGLRenderer::prepareDirty(0.0f, 0.0f,
423                    bitmap->width(), bitmap->height(), !layer->isBlend());
424
425            caches.disableScissor();
426            renderer.translate(0.0f, bitmap->height());
427            renderer.scale(1.0f, -1.0f);
428
429            mat4 texTransform(layer->getTexTransform());
430
431            mat4 invert;
432            invert.translate(0.0f, 1.0f, 0.0f);
433            invert.scale(1.0f, -1.0f, 1.0f);
434            layer->getTexTransform().multiply(invert);
435
436            if ((error = glGetError()) != GL_NO_ERROR) goto error;
437
438            {
439                Rect bounds;
440                bounds.set(0.0f, 0.0f, bitmap->width(), bitmap->height());
441                renderer.drawTextureLayer(layer, bounds);
442
443                glReadPixels(0, 0, bitmap->width(), bitmap->height(), format,
444                        type, bitmap->getPixels());
445
446                if ((error = glGetError()) != GL_NO_ERROR) goto error;
447            }
448
449            layer->getTexTransform().load(texTransform);
450            status = true;
451        }
452
453error:
454#if DEBUG_OPENGL
455        if (error != GL_NO_ERROR) {
456            ALOGD("GL error while copying layer into bitmap = 0x%x", error);
457        }
458#endif
459
460        glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
461        layer->setAlpha(alpha, mode);
462        layer->setFbo(0);
463        glDeleteTextures(1, &texture);
464        caches.fboCache.put(fbo);
465
466        return status;
467    }
468    return false;
469}
470
471}; // namespace uirenderer
472}; // namespace android
473