CanvasContext.cpp revision dcba6725e8b9d3eba9ad7a01258d6aa974feafba
1/*
2 * Copyright (C) 2014 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 "CanvasContext"
18
19#include "CanvasContext.h"
20
21#include <private/hwui/DrawGlInfo.h>
22#include <strings.h>
23
24#include "EglManager.h"
25#include "RenderThread.h"
26#include "../Caches.h"
27#include "../DeferredLayerUpdater.h"
28#include "../RenderState.h"
29#include "../LayerRenderer.h"
30#include "../OpenGLRenderer.h"
31#include "../Stencil.h"
32
33#define TRIM_MEMORY_COMPLETE 80
34#define TRIM_MEMORY_UI_HIDDEN 20
35
36namespace android {
37namespace uirenderer {
38namespace renderthread {
39
40CanvasContext::CanvasContext(RenderThread& thread, bool translucent, RenderNode* rootRenderNode)
41        : mRenderThread(thread)
42        , mEglManager(thread.eglManager())
43        , mEglSurface(EGL_NO_SURFACE)
44        , mDirtyRegionsEnabled(false)
45        , mOpaque(!translucent)
46        , mCanvas(NULL)
47        , mHaveNewSurface(false)
48        , mRootRenderNode(rootRenderNode) {
49}
50
51CanvasContext::~CanvasContext() {
52    destroyCanvasAndSurface();
53    mRenderThread.removeFrameCallback(this);
54}
55
56void CanvasContext::destroyCanvasAndSurface() {
57    if (mCanvas) {
58        delete mCanvas;
59        mCanvas = 0;
60    }
61    setSurface(NULL);
62}
63
64void CanvasContext::setSurface(ANativeWindow* window) {
65    mNativeWindow = window;
66
67    if (mEglSurface != EGL_NO_SURFACE) {
68        mEglManager.destroySurface(mEglSurface);
69        mEglSurface = EGL_NO_SURFACE;
70    }
71
72    if (window) {
73        mEglSurface = mEglManager.createSurface(window);
74    }
75
76    if (mEglSurface != EGL_NO_SURFACE) {
77        mDirtyRegionsEnabled = mEglManager.enableDirtyRegions(mEglSurface);
78        mHaveNewSurface = true;
79        makeCurrent();
80    } else {
81        mRenderThread.removeFrameCallback(this);
82    }
83}
84
85void CanvasContext::swapBuffers() {
86    mEglManager.swapBuffers(mEglSurface);
87    mHaveNewSurface = false;
88}
89
90void CanvasContext::requireSurface() {
91    LOG_ALWAYS_FATAL_IF(mEglSurface == EGL_NO_SURFACE,
92            "requireSurface() called but no surface set!");
93    makeCurrent();
94}
95
96bool CanvasContext::initialize(ANativeWindow* window) {
97    if (mCanvas) return false;
98    setSurface(window);
99    mCanvas = new OpenGLRenderer(mRenderThread.renderState());
100    mCanvas->initProperties();
101    return true;
102}
103
104void CanvasContext::updateSurface(ANativeWindow* window) {
105    setSurface(window);
106}
107
108void CanvasContext::pauseSurface(ANativeWindow* window) {
109    // TODO: For now we just need a fence, in the future suspend any animations
110    // and such to prevent from trying to render into this surface
111}
112
113void CanvasContext::setup(int width, int height, const Vector3& lightCenter, float lightRadius) {
114    if (!mCanvas) return;
115    mCanvas->setViewport(width, height);
116    mCanvas->initializeLight(lightCenter, lightRadius);
117}
118
119void CanvasContext::setOpaque(bool opaque) {
120    mOpaque = opaque;
121}
122
123void CanvasContext::makeCurrent() {
124    // TODO: Figure out why this workaround is needed, see b/13913604
125    // In the meantime this matches the behavior of GLRenderer, so it is not a regression
126    mHaveNewSurface |= mEglManager.makeCurrent(mEglSurface);
127}
128
129void CanvasContext::processLayerUpdate(DeferredLayerUpdater* layerUpdater) {
130    bool success = layerUpdater->apply();
131    LOG_ALWAYS_FATAL_IF(!success, "Failed to update layer!");
132    if (layerUpdater->backingLayer()->deferredUpdateScheduled) {
133        mCanvas->pushLayerUpdate(layerUpdater->backingLayer());
134    }
135}
136
137void CanvasContext::prepareTree(TreeInfo& info) {
138    mRenderThread.removeFrameCallback(this);
139
140    info.frameTimeMs = mRenderThread.timeLord().frameTimeMs();
141    info.damageAccumulator = &mDamageAccumulator;
142    info.renderer = mCanvas;
143    mRootRenderNode->prepareTree(info);
144
145    int runningBehind = 0;
146    // TODO: This query is moderately expensive, investigate adding some sort
147    // of fast-path based off when we last called eglSwapBuffers() as well as
148    // last vsync time. Or something.
149    mNativeWindow->query(mNativeWindow.get(),
150            NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND, &runningBehind);
151    info.out.canDrawThisFrame = !runningBehind;
152
153    if (info.out.hasAnimations || !info.out.canDrawThisFrame) {
154        if (!info.out.requiresUiRedraw) {
155            // If animationsNeedsRedraw is set don't bother posting for an RT anim
156            // as we will just end up fighting the UI thread.
157            mRenderThread.postFrameCallback(this);
158        }
159    }
160}
161
162void CanvasContext::stopDrawing() {
163    mRenderThread.removeFrameCallback(this);
164}
165
166void CanvasContext::notifyFramePending() {
167    ATRACE_CALL();
168    mRenderThread.pushBackFrameCallback(this);
169}
170
171void CanvasContext::draw() {
172    LOG_ALWAYS_FATAL_IF(!mCanvas || mEglSurface == EGL_NO_SURFACE,
173            "drawRenderNode called on a context with no canvas or surface!");
174
175    profiler().markPlaybackStart();
176
177    SkRect dirty;
178    mDamageAccumulator.finish(&dirty);
179
180    EGLint width, height;
181    mEglManager.beginFrame(mEglSurface, &width, &height);
182    if (width != mCanvas->getViewportWidth() || height != mCanvas->getViewportHeight()) {
183        mCanvas->setViewport(width, height);
184        dirty.setEmpty();
185    } else if (!mDirtyRegionsEnabled || mHaveNewSurface) {
186        dirty.setEmpty();
187    } else {
188        profiler().unionDirty(&dirty);
189    }
190
191    status_t status;
192    if (!dirty.isEmpty()) {
193        status = mCanvas->prepareDirty(dirty.fLeft, dirty.fTop,
194                dirty.fRight, dirty.fBottom, mOpaque);
195    } else {
196        status = mCanvas->prepare(mOpaque);
197    }
198
199    Rect outBounds;
200    status |= mCanvas->drawRenderNode(mRootRenderNode.get(), outBounds);
201
202    profiler().draw(mCanvas);
203
204    mCanvas->finish();
205
206    profiler().markPlaybackEnd();
207
208    if (status & DrawGlInfo::kStatusDrew) {
209        swapBuffers();
210    }
211
212    profiler().finishFrame();
213}
214
215// Called by choreographer to do an RT-driven animation
216void CanvasContext::doFrame() {
217    if (CC_UNLIKELY(!mCanvas || mEglSurface == EGL_NO_SURFACE)) {
218        return;
219    }
220
221    ATRACE_CALL();
222
223    profiler().startFrame();
224
225    TreeInfo info(TreeInfo::MODE_RT_ONLY, mRenderThread.renderState());
226    prepareTree(info);
227    if (info.out.canDrawThisFrame) {
228        draw();
229    }
230}
231
232void CanvasContext::invokeFunctor(RenderThread& thread, Functor* functor) {
233    ATRACE_CALL();
234    DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext;
235    if (thread.eglManager().hasEglContext()) {
236        thread.eglManager().requireGlContext();
237        mode = DrawGlInfo::kModeProcess;
238    }
239
240    thread.renderState().invokeFunctor(functor, mode, NULL);
241}
242
243bool CanvasContext::copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap) {
244    requireGlContext();
245    layer->apply();
246    return LayerRenderer::copyLayer(mRenderThread.renderState(), layer->backingLayer(), bitmap);
247}
248
249void CanvasContext::destroyHardwareResources() {
250    stopDrawing();
251    if (mEglManager.hasEglContext()) {
252        requireGlContext();
253        mRootRenderNode->destroyHardwareResources();
254        Caches::getInstance().flush(Caches::kFlushMode_Layers);
255    }
256}
257
258void CanvasContext::trimMemory(RenderThread& thread, int level) {
259    // No context means nothing to free
260    if (!thread.eglManager().hasEglContext()) return;
261
262    thread.eglManager().requireGlContext();
263    if (level >= TRIM_MEMORY_COMPLETE) {
264        Caches::getInstance().flush(Caches::kFlushMode_Full);
265        thread.eglManager().destroy();
266    } else if (level >= TRIM_MEMORY_UI_HIDDEN) {
267        Caches::getInstance().flush(Caches::kFlushMode_Moderate);
268    }
269}
270
271void CanvasContext::runWithGlContext(RenderTask* task) {
272    requireGlContext();
273    task->run();
274}
275
276Layer* CanvasContext::createRenderLayer(int width, int height) {
277    requireSurface();
278    return LayerRenderer::createRenderLayer(mRenderThread.renderState(), width, height);
279}
280
281Layer* CanvasContext::createTextureLayer() {
282    requireSurface();
283    return LayerRenderer::createTextureLayer(mRenderThread.renderState());
284}
285
286void CanvasContext::requireGlContext() {
287    mEglManager.requireGlContext();
288}
289
290void CanvasContext::setTextureAtlas(RenderThread& thread,
291        const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize) {
292    thread.eglManager().setTextureAtlas(buffer, map, mapSize);
293}
294
295} /* namespace renderthread */
296} /* namespace uirenderer */
297} /* namespace android */
298