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
95GLint 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 (getSnapshot()->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::createLayer(uint32_t width, uint32_t height, bool isOpaque) {
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->setBlend(!isOpaque);
225    layer->setColorFilter(NULL);
226    layer->setDirty(true);
227    layer->region.clear();
228
229    GLuint previousFbo;
230    glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*) &previousFbo);
231
232    glBindFramebuffer(GL_FRAMEBUFFER, layer->getFbo());
233    layer->bindTexture();
234
235    // Initialize the texture if needed
236    if (layer->isEmpty()) {
237        layer->setEmpty(false);
238        layer->allocateTexture();
239
240        // This should only happen if we run out of memory
241        if (glGetError() != GL_NO_ERROR) {
242            ALOGE("Could not allocate texture for layer (fbo=%d %dx%d)", fbo, width, height);
243            glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
244            caches.resourceCache.decrementRefcount(layer);
245            return NULL;
246        }
247    }
248
249    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
250            layer->getTexture(), 0);
251
252    glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
253
254    return layer;
255}
256
257bool LayerRenderer::resizeLayer(Layer* layer, uint32_t width, uint32_t height) {
258    if (layer) {
259        LAYER_RENDERER_LOGD("Resizing layer fbo = %d to %dx%d", layer->getFbo(), width, height);
260
261        if (layer->resize(width, height)) {
262            layer->layer.set(0.0f, 0.0f, width, height);
263            layer->texCoords.set(0.0f, height / float(layer->getHeight()),
264                    width / float(layer->getWidth()), 0.0f);
265        } else {
266            return false;
267        }
268    }
269
270    return true;
271}
272
273Layer* LayerRenderer::createTextureLayer(bool isOpaque) {
274    LAYER_RENDERER_LOGD("Creating new texture layer");
275
276    Layer* layer = new Layer(0, 0);
277    layer->setCacheable(false);
278    layer->setTextureLayer(true);
279    layer->setBlend(!isOpaque);
280    layer->setEmpty(true);
281    layer->setFbo(0);
282    layer->setAlpha(255, SkXfermode::kSrcOver_Mode);
283    layer->layer.set(0.0f, 0.0f, 0.0f, 0.0f);
284    layer->texCoords.set(0.0f, 1.0f, 1.0f, 0.0f);
285    layer->region.clear();
286    layer->setRenderTarget(GL_NONE); // see ::updateTextureLayer()
287
288    Caches::getInstance().activeTexture(0);
289    layer->generateTexture();
290
291    return layer;
292}
293
294void LayerRenderer::updateTextureLayer(Layer* layer, uint32_t width, uint32_t height,
295        bool isOpaque, GLenum renderTarget, float* transform) {
296    if (layer) {
297        layer->setBlend(!isOpaque);
298        layer->setSize(width, height);
299        layer->layer.set(0.0f, 0.0f, width, height);
300        layer->region.set(width, height);
301        layer->regionRect.set(0.0f, 0.0f, width, height);
302        layer->getTexTransform().load(transform);
303
304        if (renderTarget != layer->getRenderTarget()) {
305            layer->setRenderTarget(renderTarget);
306            layer->bindTexture();
307            layer->setFilter(GL_NEAREST, false, true);
308            layer->setWrap(GL_CLAMP_TO_EDGE, false, true);
309        }
310    }
311}
312
313void LayerRenderer::destroyLayer(Layer* layer) {
314    if (layer) {
315        LAYER_RENDERER_LOGD("Recycling layer, %dx%d fbo = %d",
316                layer->getWidth(), layer->getHeight(), layer->getFbo());
317
318        if (!Caches::getInstance().layerCache.put(layer)) {
319            LAYER_RENDERER_LOGD("  Destroyed!");
320            Caches::getInstance().resourceCache.decrementRefcount(layer);
321        } else {
322            LAYER_RENDERER_LOGD("  Cached!");
323#if DEBUG_LAYER_RENDERER
324            Caches::getInstance().layerCache.dump();
325#endif
326            layer->removeFbo();
327            layer->region.clear();
328        }
329    }
330}
331
332void LayerRenderer::destroyLayerDeferred(Layer* layer) {
333    if (layer) {
334        LAYER_RENDERER_LOGD("Deferring layer destruction, fbo = %d", layer->getFbo());
335
336        Caches::getInstance().deleteLayerDeferred(layer);
337    }
338}
339
340void LayerRenderer::flushLayer(Layer* layer) {
341#ifdef GL_EXT_discard_framebuffer
342    GLuint fbo = layer->getFbo();
343    if (layer && fbo) {
344        // If possible, discard any enqueud operations on deferred
345        // rendering architectures
346        if (Extensions::getInstance().hasDiscardFramebuffer()) {
347            GLuint previousFbo;
348            glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*) &previousFbo);
349            if (fbo != previousFbo) glBindFramebuffer(GL_FRAMEBUFFER, fbo);
350
351            const GLenum attachments[] = { GL_COLOR_ATTACHMENT0 };
352            glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments);
353
354            if (fbo != previousFbo) glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
355        }
356    }
357#endif
358}
359
360bool LayerRenderer::copyLayer(Layer* layer, SkBitmap* bitmap) {
361    Caches& caches = Caches::getInstance();
362    if (layer && bitmap->width() <= caches.maxTextureSize &&
363            bitmap->height() <= caches.maxTextureSize) {
364
365        GLuint fbo = caches.fboCache.get();
366        if (!fbo) {
367            ALOGW("Could not obtain an FBO");
368            return false;
369        }
370
371        SkAutoLockPixels alp(*bitmap);
372
373        GLuint texture;
374        GLuint previousFbo;
375        GLuint previousViewport[4];
376
377        GLenum format;
378        GLenum type;
379
380        GLenum error = GL_NO_ERROR;
381        bool status = false;
382
383        switch (bitmap->config()) {
384            case SkBitmap::kA8_Config:
385                format = GL_ALPHA;
386                type = GL_UNSIGNED_BYTE;
387                break;
388            case SkBitmap::kRGB_565_Config:
389                format = GL_RGB;
390                type = GL_UNSIGNED_SHORT_5_6_5;
391                break;
392            case SkBitmap::kARGB_4444_Config:
393                format = GL_RGBA;
394                type = GL_UNSIGNED_SHORT_4_4_4_4;
395                break;
396            case SkBitmap::kARGB_8888_Config:
397            default:
398                format = GL_RGBA;
399                type = GL_UNSIGNED_BYTE;
400                break;
401        }
402
403        float alpha = layer->getAlpha();
404        SkXfermode::Mode mode = layer->getMode();
405        GLuint previousLayerFbo = layer->getFbo();
406
407        layer->setAlpha(255, SkXfermode::kSrc_Mode);
408        layer->setFbo(fbo);
409
410        glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*) &previousFbo);
411        glGetIntegerv(GL_VIEWPORT, (GLint*) &previousViewport);
412        glBindFramebuffer(GL_FRAMEBUFFER, fbo);
413
414        glGenTextures(1, &texture);
415        if ((error = glGetError()) != GL_NO_ERROR) goto error;
416
417        caches.activeTexture(0);
418        caches.bindTexture(texture);
419
420        glPixelStorei(GL_PACK_ALIGNMENT, bitmap->bytesPerPixel());
421
422        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
423        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
424
425        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
426        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
427
428        glTexImage2D(GL_TEXTURE_2D, 0, format, bitmap->width(), bitmap->height(),
429                0, format, type, NULL);
430        if ((error = glGetError()) != GL_NO_ERROR) goto error;
431
432        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
433                GL_TEXTURE_2D, texture, 0);
434        if ((error = glGetError()) != GL_NO_ERROR) goto error;
435
436        {
437            LayerRenderer renderer(layer);
438            renderer.setViewport(bitmap->width(), bitmap->height());
439            renderer.OpenGLRenderer::prepareDirty(0.0f, 0.0f,
440                    bitmap->width(), bitmap->height(), !layer->isBlend());
441
442            caches.disableScissor();
443            renderer.translate(0.0f, bitmap->height());
444            renderer.scale(1.0f, -1.0f);
445
446            mat4 texTransform(layer->getTexTransform());
447
448            mat4 invert;
449            invert.translate(0.0f, 1.0f);
450            invert.scale(1.0f, -1.0f, 1.0f);
451            layer->getTexTransform().multiply(invert);
452
453            if ((error = glGetError()) != GL_NO_ERROR) goto error;
454
455            {
456                Rect bounds;
457                bounds.set(0.0f, 0.0f, bitmap->width(), bitmap->height());
458                renderer.drawTextureLayer(layer, bounds);
459
460                glReadPixels(0, 0, bitmap->width(), bitmap->height(), format,
461                        type, bitmap->getPixels());
462
463                if ((error = glGetError()) != GL_NO_ERROR) goto error;
464            }
465
466            layer->getTexTransform().load(texTransform);
467            status = true;
468        }
469
470error:
471#if DEBUG_OPENGL
472        if (error != GL_NO_ERROR) {
473            ALOGD("GL error while copying layer into bitmap = 0x%x", error);
474        }
475#endif
476
477        glBindFramebuffer(GL_FRAMEBUFFER, previousFbo);
478        layer->setAlpha(alpha, mode);
479        layer->setFbo(previousLayerFbo);
480        caches.deleteTexture(texture);
481        caches.fboCache.put(fbo);
482        glViewport(previousViewport[0], previousViewport[1],
483                previousViewport[2], previousViewport[3]);
484
485        return status;
486    }
487    return false;
488}
489
490}; // namespace uirenderer
491}; // namespace android
492