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 #include "LayerCache.h"
18 #include "LayerRenderer.h"
19 #include "Matrix.h"
20 #include "Properties.h"
21 #include "Rect.h"
22 #include "renderstate/RenderState.h"
23 #include "utils/GLUtils.h"
24 #include "utils/TraceUtils.h"
25 
26 #include <ui/Rect.h>
27 
28 #include <private/hwui/DrawGlInfo.h>
29 
30 
31 namespace android {
32 namespace uirenderer {
33 
34 ///////////////////////////////////////////////////////////////////////////////
35 // Rendering
36 ///////////////////////////////////////////////////////////////////////////////
37 
LayerRenderer(RenderState & renderState,Layer * layer)38 LayerRenderer::LayerRenderer(RenderState& renderState, Layer* layer)
39         : OpenGLRenderer(renderState)
40         , mLayer(layer) {
41 }
42 
~LayerRenderer()43 LayerRenderer::~LayerRenderer() {
44 }
45 
prepareDirty(int viewportWidth,int viewportHeight,float left,float top,float right,float bottom,bool opaque)46 void LayerRenderer::prepareDirty(int viewportWidth, int viewportHeight,
47         float left, float top, float right, float bottom, bool opaque) {
48     LAYER_RENDERER_LOGD("Rendering into layer, fbo = %d", mLayer->getFbo());
49 
50     mRenderState.bindFramebuffer(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.doIntersect(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     OpenGLRenderer::prepareDirty(viewportWidth, viewportHeight,
68             dirty.left, dirty.top, dirty.right, dirty.bottom, opaque);
69 }
70 
clear(float left,float top,float right,float bottom,bool opaque)71 void LayerRenderer::clear(float left, float top, float right, float bottom, bool opaque) {
72     if (mLayer->isDirty()) {
73         mRenderState.scissor().setEnabled(false);
74         glClear(GL_COLOR_BUFFER_BIT);
75 
76         mRenderState.scissor().reset();
77         mLayer->setDirty(false);
78     } else {
79         OpenGLRenderer::clear(left, top, right, bottom, opaque);
80     }
81 }
82 
finish()83 bool 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 
getTargetFbo() const95 GLuint LayerRenderer::getTargetFbo() const {
96     return mLayer->getFbo();
97 }
98 
suppressErrorChecks() const99 bool LayerRenderer::suppressErrorChecks() const {
100     return true;
101 }
102 
103 ///////////////////////////////////////////////////////////////////////////////
104 // Layer support
105 ///////////////////////////////////////////////////////////////////////////////
106 
hasLayer() const107 bool LayerRenderer::hasLayer() const {
108     return true;
109 }
110 
ensureStencilBuffer()111 void LayerRenderer::ensureStencilBuffer() {
112     attachStencilBufferToLayer(mLayer);
113 }
114 
115 ///////////////////////////////////////////////////////////////////////////////
116 // Dirty region tracking
117 ///////////////////////////////////////////////////////////////////////////////
118 
getRegion() const119 Region* 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.
generateMesh()129 void LayerRenderer::generateMesh() {
130     if (mLayer->region.isRect() || mLayer->region.isEmpty()) {
131         if (mLayer->mesh) {
132             delete[] mLayer->mesh;
133             mLayer->mesh = nullptr;
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 = nullptr;
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 
createRenderLayer(RenderState & renderState,uint32_t width,uint32_t height)187 Layer* 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 = renderState.createFramebuffer();
193     if (!fbo) {
194         ALOGW("Could not obtain an FBO");
195         return nullptr;
196     }
197 
198     caches.textureState().activateTexture(0);
199     Layer* layer = caches.layerCache.get(renderState, width, height);
200     if (!layer) {
201         ALOGW("Could not obtain a layer");
202         return nullptr;
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 slightly 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(nullptr);
216 
217         return nullptr;
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(nullptr);
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 (CC_UNLIKELY(GLUtils::dumpGLErrors())) {
241             LOG_ALWAYS_FATAL("Could not allocate texture for layer (fbo=%d %dx%d)",
242                     fbo, width, height);
243             renderState.bindFramebuffer(previousFbo);
244             layer->decStrong(nullptr);
245             return nullptr;
246         }
247     }
248 
249     glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
250             layer->getTextureId(), 0);
251 
252     renderState.bindFramebuffer(previousFbo);
253 
254     return layer;
255 }
256 
resizeLayer(Layer * layer,uint32_t width,uint32_t height)257 bool 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 
createTextureLayer(RenderState & renderState)273 Layer* LayerRenderer::createTextureLayer(RenderState& renderState) {
274     LAYER_RENDERER_LOGD("Creating new texture layer");
275 
276     Layer* layer = new Layer(Layer::Type::Texture, renderState, 0, 0);
277     layer->setCacheable(false);
278     layer->layer.set(0.0f, 0.0f, 0.0f, 0.0f);
279     layer->texCoords.set(0.0f, 1.0f, 1.0f, 0.0f);
280     layer->region.clear();
281     layer->setRenderTarget(GL_NONE); // see ::updateTextureLayer()
282 
283     Caches::getInstance().textureState().activateTexture(0);
284     layer->generateTexture();
285 
286     return layer;
287 }
288 
updateTextureLayer(Layer * layer,uint32_t width,uint32_t height,bool isOpaque,bool forceFilter,GLenum renderTarget,const float * textureTransform)289 void LayerRenderer::updateTextureLayer(Layer* layer, uint32_t width, uint32_t height,
290         bool isOpaque, bool forceFilter, GLenum renderTarget, const float* textureTransform) {
291     if (layer) {
292         layer->setBlend(!isOpaque);
293         layer->setForceFilter(forceFilter);
294         layer->setSize(width, height);
295         layer->layer.set(0.0f, 0.0f, width, height);
296         layer->region.set(width, height);
297         layer->regionRect.set(0.0f, 0.0f, width, height);
298         layer->getTexTransform().load(textureTransform);
299 
300         if (renderTarget != layer->getRenderTarget()) {
301             layer->setRenderTarget(renderTarget);
302             layer->bindTexture();
303             layer->setFilter(GL_NEAREST, false, true);
304             layer->setWrap(GL_CLAMP_TO_EDGE, false, true);
305         }
306     }
307 }
308 
destroyLayer(Layer * layer)309 void LayerRenderer::destroyLayer(Layer* layer) {
310     if (layer) {
311         ATRACE_FORMAT("Destroy %ux%u HW Layer", layer->getWidth(), layer->getHeight());
312         LAYER_RENDERER_LOGD("Recycling layer, %dx%d fbo = %d",
313                 layer->getWidth(), layer->getHeight(), layer->getFbo());
314 
315         if (!Caches::getInstance().layerCache.put(layer)) {
316             LAYER_RENDERER_LOGD("  Destroyed!");
317             layer->decStrong(nullptr);
318         } else {
319             LAYER_RENDERER_LOGD("  Cached!");
320 #if DEBUG_LAYER_RENDERER
321             Caches::getInstance().layerCache.dump();
322 #endif
323             layer->removeFbo();
324             layer->region.clear();
325         }
326     }
327 }
328 
flushLayer(RenderState & renderState,Layer * layer)329 void LayerRenderer::flushLayer(RenderState& renderState, Layer* layer) {
330 #ifdef GL_EXT_discard_framebuffer
331     if (!layer) return;
332 
333     GLuint fbo = layer->getFbo();
334     if (fbo) {
335         // If possible, discard any enqueud operations on deferred
336         // rendering architectures
337         if (Caches::getInstance().extensions().hasDiscardFramebuffer()) {
338             GLuint previousFbo = renderState.getFramebuffer();
339             if (fbo != previousFbo) {
340                 renderState.bindFramebuffer(fbo);
341             }
342 
343             const GLenum attachments[] = { GL_COLOR_ATTACHMENT0 };
344             glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments);
345 
346             if (fbo != previousFbo) {
347                 renderState.bindFramebuffer(previousFbo);
348             }
349         }
350     }
351 #endif
352 }
353 
copyLayer(RenderState & renderState,Layer * layer,SkBitmap * bitmap)354 bool LayerRenderer::copyLayer(RenderState& renderState, Layer* layer, SkBitmap* bitmap) {
355     Caches& caches = Caches::getInstance();
356     if (layer && layer->isRenderable()
357             && bitmap->width() <= caches.maxTextureSize
358             && bitmap->height() <= caches.maxTextureSize) {
359 
360         GLuint fbo = renderState.createFramebuffer();
361         if (!fbo) {
362             ALOGW("Could not obtain an FBO");
363             return false;
364         }
365 
366         SkAutoLockPixels alp(*bitmap);
367 
368         GLuint texture;
369         GLuint previousFbo;
370         GLsizei previousViewportWidth;
371         GLsizei previousViewportHeight;
372 
373         GLenum format;
374         GLenum type;
375 
376         bool status = false;
377 
378         switch (bitmap->colorType()) {
379             case kAlpha_8_SkColorType:
380                 format = GL_ALPHA;
381                 type = GL_UNSIGNED_BYTE;
382                 break;
383             case kRGB_565_SkColorType:
384                 format = GL_RGB;
385                 type = GL_UNSIGNED_SHORT_5_6_5;
386                 break;
387             case kARGB_4444_SkColorType:
388                 format = GL_RGBA;
389                 type = GL_UNSIGNED_SHORT_4_4_4_4;
390                 break;
391             case kN32_SkColorType:
392             default:
393                 format = GL_RGBA;
394                 type = GL_UNSIGNED_BYTE;
395                 break;
396         }
397 
398         float alpha = layer->getAlpha();
399         SkXfermode::Mode mode = layer->getMode();
400         GLuint previousLayerFbo = layer->getFbo();
401 
402         layer->setAlpha(255, SkXfermode::kSrc_Mode);
403         layer->setFbo(fbo);
404 
405         previousFbo = renderState.getFramebuffer();
406         renderState.getViewport(&previousViewportWidth, &previousViewportHeight);
407         renderState.bindFramebuffer(fbo);
408 
409         glGenTextures(1, &texture);
410 
411         caches.textureState().activateTexture(0);
412         caches.textureState().bindTexture(texture);
413 
414         glPixelStorei(GL_PACK_ALIGNMENT, bitmap->bytesPerPixel());
415 
416         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
417         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
418 
419         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
420         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
421 
422         glTexImage2D(GL_TEXTURE_2D, 0, format, bitmap->width(), bitmap->height(),
423                 0, format, type, nullptr);
424 
425         glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
426                 GL_TEXTURE_2D, texture, 0);
427 
428         {
429             LayerRenderer renderer(renderState, layer);
430             renderer.OpenGLRenderer::prepareDirty(bitmap->width(), bitmap->height(),
431                     0.0f, 0.0f, bitmap->width(), bitmap->height(), !layer->isBlend());
432 
433             renderState.scissor().setEnabled(false);
434             renderer.translate(0.0f, bitmap->height());
435             renderer.scale(1.0f, -1.0f);
436 
437             {
438                 Rect bounds;
439                 bounds.set(0.0f, 0.0f, bitmap->width(), bitmap->height());
440                 renderer.drawTextureLayer(layer, bounds);
441 
442                 glReadPixels(0, 0, bitmap->width(), bitmap->height(), format,
443                         type, bitmap->getPixels());
444 
445             }
446 
447             status = true;
448         }
449 
450         renderState.bindFramebuffer(previousFbo);
451         layer->setAlpha(alpha, mode);
452         layer->setFbo(previousLayerFbo);
453         caches.textureState().deleteTexture(texture);
454         renderState.deleteFramebuffer(fbo);
455         renderState.setViewport(previousViewportWidth, previousViewportHeight);
456 
457         GL_CHECKPOINT(MODERATE);
458 
459         return status;
460     }
461     return false;
462 }
463 
464 }; // namespace uirenderer
465 }; // namespace android
466