1 /*
2  * Copyright (C) 2015 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 "BakedOpRenderer.h"
18 
19 #include "Caches.h"
20 #include "Glop.h"
21 #include "GlopBuilder.h"
22 #include "renderstate/OffscreenBufferPool.h"
23 #include "renderstate/RenderState.h"
24 #include "utils/GLUtils.h"
25 #include "VertexBuffer.h"
26 
27 #include <algorithm>
28 
29 namespace android {
30 namespace uirenderer {
31 
startTemporaryLayer(uint32_t width,uint32_t height)32 OffscreenBuffer* BakedOpRenderer::startTemporaryLayer(uint32_t width, uint32_t height) {
33     LOG_ALWAYS_FATAL_IF(mRenderTarget.offscreenBuffer, "already has layer...");
34 
35     OffscreenBuffer* buffer = mRenderState.layerPool().get(mRenderState, width, height);
36     startRepaintLayer(buffer, Rect(width, height));
37     return buffer;
38 }
39 
recycleTemporaryLayer(OffscreenBuffer * offscreenBuffer)40 void BakedOpRenderer::recycleTemporaryLayer(OffscreenBuffer* offscreenBuffer) {
41     mRenderState.layerPool().putOrDelete(offscreenBuffer);
42 }
43 
startRepaintLayer(OffscreenBuffer * offscreenBuffer,const Rect & repaintRect)44 void BakedOpRenderer::startRepaintLayer(OffscreenBuffer* offscreenBuffer, const Rect& repaintRect) {
45     LOG_ALWAYS_FATAL_IF(mRenderTarget.offscreenBuffer, "already has layer...");
46 
47     // subtract repaintRect from region, since it will be regenerated
48     if (repaintRect.contains(0, 0,
49                 offscreenBuffer->viewportWidth, offscreenBuffer->viewportHeight)) {
50         // repaint full layer, so throw away entire region
51         offscreenBuffer->region.clear();
52     } else {
53         offscreenBuffer->region.subtractSelf(android::Rect(repaintRect.left, repaintRect.top,
54                 repaintRect.right, repaintRect.bottom));
55     }
56 
57     mRenderTarget.offscreenBuffer = offscreenBuffer;
58     mRenderTarget.offscreenBuffer->hasRenderedSinceRepaint = false;
59 
60     // create and bind framebuffer
61     mRenderTarget.frameBufferId = mRenderState.createFramebuffer();
62     mRenderState.bindFramebuffer(mRenderTarget.frameBufferId);
63 
64     // attach the texture to the FBO
65     glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
66             offscreenBuffer->texture.id(), 0);
67     GL_CHECKPOINT(LOW);
68 
69     int status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
70     LOG_ALWAYS_FATAL_IF(status != GL_FRAMEBUFFER_COMPLETE,
71             "framebuffer incomplete, status %d, textureId %d, size %dx%d",
72             status,
73             offscreenBuffer->texture.id(),
74             offscreenBuffer->texture.width(),
75             offscreenBuffer->texture.height());
76 
77     // Change the viewport & ortho projection
78     setViewport(offscreenBuffer->viewportWidth, offscreenBuffer->viewportHeight);
79 
80     clearColorBuffer(repaintRect);
81 }
82 
endLayer()83 void BakedOpRenderer::endLayer() {
84     if (mRenderTarget.stencil) {
85         // if stencil was used for clipping, detach it and return it to pool
86         glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0);
87         GL_CHECKPOINT(MODERATE);
88         mCaches.renderBufferCache.put(mRenderTarget.stencil);
89         mRenderTarget.stencil = nullptr;
90     }
91     mRenderTarget.lastStencilClip = nullptr;
92 
93     mRenderTarget.offscreenBuffer->updateMeshFromRegion();
94     mRenderTarget.offscreenBuffer = nullptr; // It's in drawLayerOp's hands now.
95 
96     // Detach the texture from the FBO
97     glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
98     GL_CHECKPOINT(LOW);
99     mRenderState.deleteFramebuffer(mRenderTarget.frameBufferId);
100     mRenderTarget.frameBufferId = 0;
101 }
102 
copyToLayer(const Rect & area)103 OffscreenBuffer* BakedOpRenderer::copyToLayer(const Rect& area) {
104     const uint32_t width = area.getWidth();
105     const uint32_t height = area.getHeight();
106     OffscreenBuffer* buffer = mRenderState.layerPool().get(mRenderState, width, height);
107     if (!area.isEmpty() && width != 0 && height != 0) {
108         mCaches.textureState().activateTexture(0);
109         mCaches.textureState().bindTexture(buffer->texture.id());
110 
111         glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0,
112                 area.left, mRenderTarget.viewportHeight - area.bottom, width, height);
113     }
114     return buffer;
115 }
116 
startFrame(uint32_t width,uint32_t height,const Rect & repaintRect)117 void BakedOpRenderer::startFrame(uint32_t width, uint32_t height, const Rect& repaintRect) {
118     LOG_ALWAYS_FATAL_IF(mRenderTarget.frameBufferId != 0, "primary framebufferId must be 0");
119     mRenderState.bindFramebuffer(0);
120     setViewport(width, height);
121 
122     if (!mOpaque) {
123         clearColorBuffer(repaintRect);
124     }
125 
126     mRenderState.debugOverdraw(true, true);
127 }
128 
endFrame(const Rect & repaintRect)129 void BakedOpRenderer::endFrame(const Rect& repaintRect) {
130     if (CC_UNLIKELY(Properties::debugOverdraw)) {
131         ClipRect overdrawClip(repaintRect);
132         Rect viewportRect(mRenderTarget.viewportWidth, mRenderTarget.viewportHeight);
133         // overdraw visualization
134         for (int i = 1; i <= 4; i++) {
135             if (i < 4) {
136                 // nth level of overdraw tests for n+1 draws per pixel
137                 mRenderState.stencil().enableDebugTest(i + 1, false);
138             } else {
139                 // 4th level tests for 4 or higher draws per pixel
140                 mRenderState.stencil().enableDebugTest(4, true);
141             }
142 
143             SkPaint paint;
144             paint.setColor(mCaches.getOverdrawColor(i));
145             Glop glop;
146             GlopBuilder(mRenderState, mCaches, &glop)
147                     .setRoundRectClipState(nullptr)
148                     .setMeshUnitQuad()
149                     .setFillPaint(paint, 1.0f)
150                     .setTransform(Matrix4::identity(), TransformFlags::None)
151                     .setModelViewMapUnitToRect(viewportRect)
152                     .build();
153             renderGlop(nullptr, &overdrawClip, glop);
154         }
155         mRenderState.stencil().disable();
156     }
157 
158     // Note: we leave FBO 0 renderable here, for post-frame-content decoration
159 }
160 
setViewport(uint32_t width,uint32_t height)161 void BakedOpRenderer::setViewport(uint32_t width, uint32_t height) {
162     mRenderTarget.viewportWidth = width;
163     mRenderTarget.viewportHeight = height;
164     mRenderTarget.orthoMatrix.loadOrtho(width, height);
165 
166     mRenderState.setViewport(width, height);
167     mRenderState.blend().syncEnabled();
168 }
169 
clearColorBuffer(const Rect & rect)170 void BakedOpRenderer::clearColorBuffer(const Rect& rect) {
171     if (rect.contains(Rect(mRenderTarget.viewportWidth, mRenderTarget.viewportHeight))) {
172         // Full viewport is being cleared - disable scissor
173         mRenderState.scissor().setEnabled(false);
174     } else {
175         // Requested rect is subset of viewport - scissor to it to avoid over-clearing
176         mRenderState.scissor().setEnabled(true);
177         mRenderState.scissor().set(rect.left, mRenderTarget.viewportHeight - rect.bottom,
178                 rect.getWidth(), rect.getHeight());
179     }
180     glClear(GL_COLOR_BUFFER_BIT);
181     if (!mRenderTarget.frameBufferId) mHasDrawn = true;
182 }
183 
getTexture(const SkBitmap * bitmap)184 Texture* BakedOpRenderer::getTexture(const SkBitmap* bitmap) {
185     Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap->pixelRef());
186     if (!texture) {
187         return mCaches.textureCache.get(bitmap);
188     }
189     return texture;
190 }
191 
drawRects(const float * rects,int count,const SkPaint * paint)192 void BakedOpRenderer::drawRects(const float* rects, int count, const SkPaint* paint) {
193     std::vector<Vertex> vertices;
194     vertices.reserve(count);
195     Vertex* vertex = vertices.data();
196 
197     for (int index = 0; index < count; index += 4) {
198         float l = rects[index + 0];
199         float t = rects[index + 1];
200         float r = rects[index + 2];
201         float b = rects[index + 3];
202 
203         Vertex::set(vertex++, l, t);
204         Vertex::set(vertex++, r, t);
205         Vertex::set(vertex++, l, b);
206         Vertex::set(vertex++, r, b);
207     }
208 
209     LOG_ALWAYS_FATAL_IF(mRenderTarget.frameBufferId != 0, "decoration only supported for FBO 0");
210     // TODO: Currently assume full FBO damage, due to FrameInfoVisualizer::unionDirty.
211     // Should should scissor/set mHasDrawn safely.
212     mRenderState.scissor().setEnabled(false);
213     mHasDrawn = true;
214     Glop glop;
215     GlopBuilder(mRenderState, mCaches, &glop)
216             .setRoundRectClipState(nullptr)
217             .setMeshIndexedQuads(vertices.data(), count / 4)
218             .setFillPaint(*paint, 1.0f)
219             .setTransform(Matrix4::identity(), TransformFlags::None)
220             .setModelViewIdentityEmptyBounds()
221             .build();
222     mRenderState.render(glop, mRenderTarget.orthoMatrix);
223 }
224 
225 // clears and re-fills stencil with provided rendertarget space quads,
226 // and then put stencil into test mode
setupStencilQuads(std::vector<Vertex> & quadVertices,int incrementThreshold)227 void BakedOpRenderer::setupStencilQuads(std::vector<Vertex>& quadVertices,
228         int incrementThreshold) {
229     mRenderState.stencil().enableWrite(incrementThreshold);
230     mRenderState.stencil().clear();
231     Glop glop;
232     GlopBuilder(mRenderState, mCaches, &glop)
233             .setRoundRectClipState(nullptr)
234             .setMeshIndexedQuads(quadVertices.data(), quadVertices.size() / 4)
235             .setFillBlack()
236             .setTransform(Matrix4::identity(), TransformFlags::None)
237             .setModelViewIdentityEmptyBounds()
238             .build();
239     mRenderState.render(glop, mRenderTarget.orthoMatrix);
240     mRenderState.stencil().enableTest(incrementThreshold);
241 }
242 
setupStencilRectList(const ClipBase * clip)243 void BakedOpRenderer::setupStencilRectList(const ClipBase* clip) {
244     LOG_ALWAYS_FATAL_IF(clip->mode != ClipMode::RectangleList, "can't rectlist clip without rectlist");
245     auto&& rectList = reinterpret_cast<const ClipRectList*>(clip)->rectList;
246     int quadCount = rectList.getTransformedRectanglesCount();
247     std::vector<Vertex> rectangleVertices;
248     rectangleVertices.reserve(quadCount * 4);
249     for (int i = 0; i < quadCount; i++) {
250         const TransformedRectangle& tr(rectList.getTransformedRectangle(i));
251         const Matrix4& transform = tr.getTransform();
252         Rect bounds = tr.getBounds();
253         if (transform.rectToRect()) {
254             // If rectToRect, can simply map bounds before storing verts
255             transform.mapRect(bounds);
256             bounds.doIntersect(clip->rect);
257             if (bounds.isEmpty()) {
258                 continue; // will be outside of scissor, skip
259             }
260         }
261 
262         rectangleVertices.push_back(Vertex{bounds.left, bounds.top});
263         rectangleVertices.push_back(Vertex{bounds.right, bounds.top});
264         rectangleVertices.push_back(Vertex{bounds.left, bounds.bottom});
265         rectangleVertices.push_back(Vertex{bounds.right, bounds.bottom});
266 
267         if (!transform.rectToRect()) {
268             // If not rectToRect, must map each point individually
269             for (auto cur = rectangleVertices.end() - 4; cur < rectangleVertices.end(); cur++) {
270                 transform.mapPoint(cur->x, cur->y);
271             }
272         }
273     }
274     setupStencilQuads(rectangleVertices, rectList.getTransformedRectanglesCount());
275 }
276 
setupStencilRegion(const ClipBase * clip)277 void BakedOpRenderer::setupStencilRegion(const ClipBase* clip) {
278     LOG_ALWAYS_FATAL_IF(clip->mode != ClipMode::Region, "can't region clip without region");
279     auto&& region = reinterpret_cast<const ClipRegion*>(clip)->region;
280 
281     std::vector<Vertex> regionVertices;
282     SkRegion::Cliperator it(region, clip->rect.toSkIRect());
283     while (!it.done()) {
284         const SkIRect& r = it.rect();
285         regionVertices.push_back(Vertex{(float)r.fLeft, (float)r.fTop});
286         regionVertices.push_back(Vertex{(float)r.fRight, (float)r.fTop});
287         regionVertices.push_back(Vertex{(float)r.fLeft, (float)r.fBottom});
288         regionVertices.push_back(Vertex{(float)r.fRight, (float)r.fBottom});
289         it.next();
290     }
291     setupStencilQuads(regionVertices, 0);
292 }
293 
prepareRender(const Rect * dirtyBounds,const ClipBase * clip)294 void BakedOpRenderer::prepareRender(const Rect* dirtyBounds, const ClipBase* clip) {
295     // Prepare scissor (done before stencil, to simplify filling stencil)
296     mRenderState.scissor().setEnabled(clip != nullptr);
297     if (clip) {
298         mRenderState.scissor().set(mRenderTarget.viewportHeight, clip->rect);
299     }
300 
301     // If stencil may be used for clipping, enable it, fill it, or disable it as appropriate
302     if (CC_LIKELY(!Properties::debugOverdraw)) {
303         // only modify stencil mode and content when it's not used for overdraw visualization
304         if (CC_UNLIKELY(clip && clip->mode != ClipMode::Rectangle)) {
305             // NOTE: this pointer check is only safe for non-rect clips,
306             // since rect clips may be created on the stack
307             if (mRenderTarget.lastStencilClip != clip) {
308                 // Stencil needed, but current stencil isn't up to date
309                 mRenderTarget.lastStencilClip = clip;
310 
311                 if (mRenderTarget.frameBufferId != 0 && !mRenderTarget.stencil) {
312                     OffscreenBuffer* layer = mRenderTarget.offscreenBuffer;
313                     mRenderTarget.stencil = mCaches.renderBufferCache.get(
314                             Stencil::getLayerStencilFormat(),
315                             layer->texture.width(), layer->texture.height());
316                     // stencil is bound + allocated - associate it with current FBO
317                     glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
318                             GL_RENDERBUFFER, mRenderTarget.stencil->getName());
319                 }
320 
321                 if (clip->mode == ClipMode::RectangleList) {
322                     setupStencilRectList(clip);
323                 } else {
324                     setupStencilRegion(clip);
325                 }
326             } else {
327                 // stencil is up to date - just need to ensure it's enabled (since an unclipped
328                 // or scissor-only clipped op may have been drawn, disabling the stencil)
329                 int incrementThreshold = 0;
330                 if (CC_LIKELY(clip->mode == ClipMode::RectangleList)) {
331                     auto&& rectList = reinterpret_cast<const ClipRectList*>(clip)->rectList;
332                     incrementThreshold = rectList.getTransformedRectanglesCount();
333                 }
334                 mRenderState.stencil().enableTest(incrementThreshold);
335             }
336         } else {
337             // either scissor or no clip, so disable stencil test
338             mRenderState.stencil().disable();
339         }
340     }
341 
342     if (dirtyBounds) {
343         // dirty offscreenbuffer if present
344         dirtyRenderTarget(*dirtyBounds);
345     }
346 }
347 
renderGlopImpl(const Rect * dirtyBounds,const ClipBase * clip,const Glop & glop)348 void BakedOpRenderer::renderGlopImpl(const Rect* dirtyBounds, const ClipBase* clip,
349         const Glop& glop) {
350     prepareRender(dirtyBounds, clip);
351     mRenderState.render(glop, mRenderTarget.orthoMatrix);
352     if (!mRenderTarget.frameBufferId) mHasDrawn = true;
353 }
354 
renderFunctor(const FunctorOp & op,const BakedOpState & state)355 void BakedOpRenderer::renderFunctor(const FunctorOp& op, const BakedOpState& state) {
356     prepareRender(&state.computedState.clippedBounds, state.computedState.getClipIfNeeded());
357 
358     DrawGlInfo info;
359     auto&& clip = state.computedState.clipRect();
360     info.clipLeft = clip.left;
361     info.clipTop = clip.top;
362     info.clipRight = clip.right;
363     info.clipBottom = clip.bottom;
364     info.isLayer = offscreenRenderTarget();
365     info.width = mRenderTarget.viewportWidth;
366     info.height = mRenderTarget.viewportHeight;
367     state.computedState.transform.copyTo(&info.transform[0]);
368 
369     mRenderState.invokeFunctor(op.functor, DrawGlInfo::kModeDraw, &info);
370 }
371 
dirtyRenderTarget(const Rect & uiDirty)372 void BakedOpRenderer::dirtyRenderTarget(const Rect& uiDirty) {
373     if (mRenderTarget.offscreenBuffer) {
374         mRenderTarget.offscreenBuffer->dirty(uiDirty);
375     }
376 }
377 
378 } // namespace uirenderer
379 } // namespace android
380