LayerRenderer.cpp revision 06e7fe5a70409d2050b2b3e1286500f5223099da
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#define ATRACE_TAG ATRACE_TAG_VIEW
19
20#include <ui/Rect.h>
21
22#include <private/hwui/DrawGlInfo.h>
23
24#include "RenderState.h"
25#include "LayerCache.h"
26#include "LayerRenderer.h"
27#include "Matrix.h"
28#include "Properties.h"
29#include "Rect.h"
30#include "utils/TraceUtils.h"
31
32namespace android {
33namespace uirenderer {
34
35///////////////////////////////////////////////////////////////////////////////
36// Rendering
37///////////////////////////////////////////////////////////////////////////////
38
39LayerRenderer::LayerRenderer(RenderState& renderState, Layer* layer)
40        : OpenGLRenderer(renderState)
41        , mLayer(layer) {
42}
43
44LayerRenderer::~LayerRenderer() {
45}
46
47void LayerRenderer::prepareDirty(float left, float top, float right, float bottom,
48        bool opaque) {
49    LAYER_RENDERER_LOGD("Rendering into layer, fbo = %d", mLayer->getFbo());
50
51    renderState().bindFramebuffer(mLayer->getFbo());
52
53    const float width = mLayer->layer.getWidth();
54    const float height = mLayer->layer.getHeight();
55
56    Rect dirty(left, top, right, bottom);
57    if (dirty.isEmpty() || (dirty.left <= 0 && dirty.top <= 0 &&
58            dirty.right >= width && dirty.bottom >= height)) {
59        mLayer->region.clear();
60        dirty.set(0.0f, 0.0f, width, height);
61    } else {
62        dirty.intersect(0.0f, 0.0f, width, height);
63        android::Rect r(dirty.left, dirty.top, dirty.right, dirty.bottom);
64        mLayer->region.subtractSelf(r);
65    }
66    mLayer->clipRect.set(dirty);
67
68    OpenGLRenderer::prepareDirty(dirty.left, dirty.top, dirty.right, dirty.bottom, opaque);
69}
70
71void LayerRenderer::clear(float left, float top, float right, float bottom, bool opaque) {
72    if (mLayer->isDirty()) {
73        getCaches().disableScissor();
74        glClear(GL_COLOR_BUFFER_BIT);
75
76        getCaches().resetScissor();
77        mLayer->setDirty(false);
78    } else {
79        OpenGLRenderer::clear(left, top, right, bottom, opaque);
80    }
81}
82
83bool LayerRenderer::finish() {
84    bool retval = OpenGLRenderer::finish();
85
86    generateMesh();
87
88    LAYER_RENDERER_LOGD("Finished rendering into layer, fbo = %d", mLayer->getFbo());
89
90    // No need to unbind our FBO, this will be taken care of by the caller
91    // who will invoke OpenGLRenderer::resume()
92    return retval;
93}
94
95GLuint LayerRenderer::onGetTargetFbo() 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 (mState.currentFlags() & 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(RenderState& renderState, uint32_t width, uint32_t height) {
188    ATRACE_FORMAT("Allocate %ux%u HW Layer", width, height);
189    LAYER_RENDERER_LOGD("Requesting new render layer %dx%d", width, height);
190
191    Caches& caches = Caches::getInstance();
192    GLuint fbo = caches.fboCache.get();
193    if (!fbo) {
194        ALOGW("Could not obtain an FBO");
195        return NULL;
196    }
197
198    caches.activeTexture(0);
199    Layer* layer = caches.layerCache.get(renderState, width, height);
200    if (!layer) {
201        ALOGW("Could not obtain a layer");
202        return NULL;
203    }
204
205    // We first obtain a layer before comparing against the max texture size
206    // because layers are not allocated at the exact desired size. They are
207    // always created slighly larger to improve recycling
208    const uint32_t maxTextureSize = caches.maxTextureSize;
209    if (layer->getWidth() > maxTextureSize || layer->getHeight() > maxTextureSize) {
210        ALOGW("Layer exceeds max. dimensions supported by the GPU (%dx%d, max=%dx%d)",
211                width, height, maxTextureSize, maxTextureSize);
212
213        // Creating a new layer always increment its refcount by 1, this allows
214        // us to destroy the layer object if one was created for us
215        layer->decStrong(0);
216
217        return NULL;
218    }
219
220    layer->setFbo(fbo);
221    layer->layer.set(0.0f, 0.0f, width, height);
222    layer->texCoords.set(0.0f, height / float(layer->getHeight()),
223            width / float(layer->getWidth()), 0.0f);
224    layer->setAlpha(255, SkXfermode::kSrcOver_Mode);
225    layer->setColorFilter(NULL);
226    layer->setDirty(true);
227    layer->region.clear();
228
229    GLuint previousFbo = renderState.getFramebuffer();
230
231    renderState.bindFramebuffer(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            renderState.bindFramebuffer(previousFbo);
243            layer->decStrong(0);
244            return NULL;
245        }
246    }
247
248    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
249            layer->getTexture(), 0);
250
251    renderState.bindFramebuffer(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(RenderState& renderState) {
273    LAYER_RENDERER_LOGD("Creating new texture layer");
274
275    Layer* layer = new Layer(Layer::kType_Texture, renderState, 0, 0);
276    layer->setCacheable(false);
277    layer->setEmpty(true);
278    layer->setFbo(0);
279    layer->setAlpha(255, SkXfermode::kSrcOver_Mode);
280    layer->layer.set(0.0f, 0.0f, 0.0f, 0.0f);
281    layer->texCoords.set(0.0f, 1.0f, 1.0f, 0.0f);
282    layer->region.clear();
283    layer->setRenderTarget(GL_NONE); // see ::updateTextureLayer()
284
285    Caches::getInstance().activeTexture(0);
286    layer->generateTexture();
287
288    return layer;
289}
290
291void LayerRenderer::updateTextureLayer(Layer* layer, uint32_t width, uint32_t height,
292        bool isOpaque, bool forceFilter, GLenum renderTarget, float* textureTransform) {
293    if (layer) {
294        layer->setBlend(!isOpaque);
295        layer->setForceFilter(forceFilter);
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(textureTransform);
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        ATRACE_FORMAT("Destroy %ux%u HW Layer", layer->getWidth(), layer->getHeight());
314        LAYER_RENDERER_LOGD("Recycling layer, %dx%d fbo = %d",
315                layer->getWidth(), layer->getHeight(), layer->getFbo());
316
317        if (!Caches::getInstance().layerCache.put(layer)) {
318            LAYER_RENDERER_LOGD("  Destroyed!");
319            layer->decStrong(0);
320        } else {
321            LAYER_RENDERER_LOGD("  Cached!");
322#if DEBUG_LAYER_RENDERER
323            Caches::getInstance().layerCache.dump();
324#endif
325            layer->removeFbo();
326            layer->region.clear();
327        }
328    }
329}
330
331void LayerRenderer::flushLayer(RenderState& renderState, Layer* layer) {
332#ifdef GL_EXT_discard_framebuffer
333    if (!layer) return;
334
335    GLuint fbo = layer->getFbo();
336    if (fbo) {
337        // If possible, discard any enqueud operations on deferred
338        // rendering architectures
339        if (Extensions::getInstance().hasDiscardFramebuffer()) {
340            GLuint previousFbo = renderState.getFramebuffer();
341            if (fbo != previousFbo) {
342                renderState.bindFramebuffer(fbo);
343            }
344
345            const GLenum attachments[] = { GL_COLOR_ATTACHMENT0 };
346            glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments);
347
348            if (fbo != previousFbo) {
349                renderState.bindFramebuffer(previousFbo);
350            }
351        }
352    }
353#endif
354}
355
356bool LayerRenderer::copyLayer(RenderState& renderState, Layer* layer, SkBitmap* bitmap) {
357    Caches& caches = Caches::getInstance();
358    if (layer && bitmap->width() <= caches.maxTextureSize &&
359            bitmap->height() <= caches.maxTextureSize) {
360
361        GLuint fbo = caches.fboCache.get();
362        if (!fbo) {
363            ALOGW("Could not obtain an FBO");
364            return false;
365        }
366
367        SkAutoLockPixels alp(*bitmap);
368
369        GLuint texture;
370        GLuint previousFbo;
371        GLsizei previousViewportWidth;
372        GLsizei previousViewportHeight;
373
374        GLenum format;
375        GLenum type;
376
377        GLenum error = GL_NO_ERROR;
378        bool status = false;
379
380        switch (bitmap->colorType()) {
381            case kAlpha_8_SkColorType:
382                format = GL_ALPHA;
383                type = GL_UNSIGNED_BYTE;
384                break;
385            case kRGB_565_SkColorType:
386                format = GL_RGB;
387                type = GL_UNSIGNED_SHORT_5_6_5;
388                break;
389            case kARGB_4444_SkColorType:
390                format = GL_RGBA;
391                type = GL_UNSIGNED_SHORT_4_4_4_4;
392                break;
393            case kN32_SkColorType:
394            default:
395                format = GL_RGBA;
396                type = GL_UNSIGNED_BYTE;
397                break;
398        }
399
400        float alpha = layer->getAlpha();
401        SkXfermode::Mode mode = layer->getMode();
402        GLuint previousLayerFbo = layer->getFbo();
403
404        layer->setAlpha(255, SkXfermode::kSrc_Mode);
405        layer->setFbo(fbo);
406
407        previousFbo = renderState.getFramebuffer();
408        renderState.getViewport(&previousViewportWidth, &previousViewportHeight);
409        renderState.bindFramebuffer(fbo);
410
411        glGenTextures(1, &texture);
412        if ((error = glGetError()) != GL_NO_ERROR) goto error;
413
414        caches.activeTexture(0);
415        caches.bindTexture(texture);
416
417        glPixelStorei(GL_PACK_ALIGNMENT, bitmap->bytesPerPixel());
418
419        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
420        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
421
422        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
423        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
424
425        glTexImage2D(GL_TEXTURE_2D, 0, format, bitmap->width(), bitmap->height(),
426                0, format, type, NULL);
427        if ((error = glGetError()) != GL_NO_ERROR) goto error;
428
429        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
430                GL_TEXTURE_2D, texture, 0);
431        if ((error = glGetError()) != GL_NO_ERROR) goto error;
432
433        {
434            LayerRenderer renderer(renderState, layer);
435            renderer.setViewport(bitmap->width(), bitmap->height());
436            renderer.OpenGLRenderer::prepareDirty(0.0f, 0.0f,
437                    bitmap->width(), bitmap->height(), !layer->isBlend());
438
439            caches.disableScissor();
440            renderer.translate(0.0f, bitmap->height());
441            renderer.scale(1.0f, -1.0f);
442
443            mat4 texTransform(layer->getTexTransform());
444
445            mat4 invert;
446            invert.translate(0.0f, 1.0f);
447            invert.scale(1.0f, -1.0f, 1.0f);
448            layer->getTexTransform().multiply(invert);
449
450            if ((error = glGetError()) != GL_NO_ERROR) goto error;
451
452            {
453                Rect bounds;
454                bounds.set(0.0f, 0.0f, bitmap->width(), bitmap->height());
455                renderer.drawTextureLayer(layer, bounds);
456
457                glReadPixels(0, 0, bitmap->width(), bitmap->height(), format,
458                        type, bitmap->getPixels());
459
460                if ((error = glGetError()) != GL_NO_ERROR) goto error;
461            }
462
463            layer->getTexTransform().load(texTransform);
464            status = true;
465        }
466
467error:
468#if DEBUG_OPENGL
469        if (error != GL_NO_ERROR) {
470            ALOGD("GL error while copying layer into bitmap = 0x%x", error);
471        }
472#endif
473
474        renderState.bindFramebuffer(previousFbo);
475        layer->setAlpha(alpha, mode);
476        layer->setFbo(previousLayerFbo);
477        caches.deleteTexture(texture);
478        caches.fboCache.put(fbo);
479        renderState.setViewport(previousViewportWidth, previousViewportHeight);
480
481        return status;
482    }
483    return false;
484}
485
486}; // namespace uirenderer
487}; // namespace android
488