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