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