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