RenderNode.h revision 3afd63778e401651a7a6fd721d6d795690916ab8
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#pragma once
18
19#include <SkCamera.h>
20#include <SkMatrix.h>
21
22#include <utils/LinearAllocator.h>
23#include <utils/RefBase.h>
24#include <utils/String8.h>
25
26#include <cutils/compiler.h>
27
28#include <androidfw/ResourceTypes.h>
29
30#include "AnimatorManager.h"
31#include "Debug.h"
32#include "DisplayList.h"
33#include "Matrix.h"
34#include "RenderProperties.h"
35#include "pipeline/skia/SkiaDisplayList.h"
36#include "pipeline/skia/SkiaLayer.h"
37#include "utils/FatVector.h"
38
39#include <vector>
40
41class SkBitmap;
42class SkPaint;
43class SkPath;
44class SkRegion;
45class SkSurface;
46
47namespace android {
48namespace uirenderer {
49
50class CanvasState;
51class DisplayListOp;
52class FrameBuilder;
53class OffscreenBuffer;
54class Rect;
55class SkiaShader;
56struct RenderNodeOp;
57
58class TreeInfo;
59class TreeObserver;
60
61namespace proto {
62class RenderNode;
63}
64
65/**
66 * Primary class for storing recorded canvas commands, as well as per-View/ViewGroup display properties.
67 *
68 * Recording of canvas commands is somewhat similar to SkPicture, except the canvas-recording
69 * functionality is split between RecordingCanvas (which manages the recording), DisplayList
70 * (which holds the actual data), and RenderNode (which holds properties used for render playback).
71 *
72 * Note that DisplayList is swapped out from beneath an individual RenderNode when a view's
73 * recorded stream of canvas operations is refreshed. The RenderNode (and its properties) stay
74 * attached.
75 */
76class RenderNode : public VirtualLightRefBase {
77friend class TestUtils; // allow TestUtils to access syncDisplayList / syncProperties
78friend class FrameBuilder;
79public:
80    enum DirtyPropertyMask {
81        GENERIC         = 1 << 1,
82        TRANSLATION_X   = 1 << 2,
83        TRANSLATION_Y   = 1 << 3,
84        TRANSLATION_Z   = 1 << 4,
85        SCALE_X         = 1 << 5,
86        SCALE_Y         = 1 << 6,
87        ROTATION        = 1 << 7,
88        ROTATION_X      = 1 << 8,
89        ROTATION_Y      = 1 << 9,
90        X               = 1 << 10,
91        Y               = 1 << 11,
92        Z               = 1 << 12,
93        ALPHA           = 1 << 13,
94        DISPLAY_LIST    = 1 << 14,
95    };
96
97    ANDROID_API RenderNode();
98    ANDROID_API virtual ~RenderNode();
99
100    // See flags defined in DisplayList.java
101    enum ReplayFlag {
102        kReplayFlag_ClipChildren = 0x1
103    };
104
105    ANDROID_API void setStagingDisplayList(DisplayList* newData);
106
107    void computeOrdering();
108
109    ANDROID_API void output();
110    ANDROID_API int getDebugSize();
111    void copyTo(proto::RenderNode* node);
112
113    bool isRenderable() const {
114        return mDisplayList && !mDisplayList->isEmpty();
115    }
116
117    bool hasProjectionReceiver() const {
118        return mDisplayList && mDisplayList->projectionReceiveIndex >= 0;
119    }
120
121    const char* getName() const {
122        return mName.string();
123    }
124
125    void setName(const char* name) {
126        if (name) {
127            const char* lastPeriod = strrchr(name, '.');
128            if (lastPeriod) {
129                mName.setTo(lastPeriod + 1);
130            } else {
131                mName.setTo(name);
132            }
133        }
134    }
135
136    VirtualLightRefBase* getUserContext() const {
137        return mUserContext.get();
138    }
139
140    void setUserContext(VirtualLightRefBase* context) {
141        mUserContext = context;
142    }
143
144    bool isPropertyFieldDirty(DirtyPropertyMask field) const {
145        return mDirtyPropertyFields & field;
146    }
147
148    void setPropertyFieldsDirty(uint32_t fields) {
149        mDirtyPropertyFields |= fields;
150    }
151
152    const RenderProperties& properties() const {
153        return mProperties;
154    }
155
156    RenderProperties& animatorProperties() {
157        return mProperties;
158    }
159
160    const RenderProperties& stagingProperties() {
161        return mStagingProperties;
162    }
163
164    RenderProperties& mutateStagingProperties() {
165        return mStagingProperties;
166    }
167
168    bool isValid() {
169        return mValid;
170    }
171
172    int getWidth() const {
173        return properties().getWidth();
174    }
175
176    int getHeight() const {
177        return properties().getHeight();
178    }
179
180    ANDROID_API virtual void prepareTree(TreeInfo& info);
181    void destroyHardwareResources(TreeInfo* info = nullptr);
182    void destroyLayers();
183
184    // UI thread only!
185    ANDROID_API void addAnimator(const sp<BaseRenderNodeAnimator>& animator);
186    void removeAnimator(const sp<BaseRenderNodeAnimator>& animator);
187
188    // This can only happen during pushStaging()
189    void onAnimatorTargetChanged(BaseRenderNodeAnimator* animator) {
190        mAnimatorManager.onAnimatorTargetChanged(animator);
191    }
192
193    AnimatorManager& animators() { return mAnimatorManager; }
194
195    void applyViewPropertyTransforms(mat4& matrix, bool true3dTransform = false) const;
196
197    bool nothingToDraw() const {
198        const Outline& outline = properties().getOutline();
199        return mDisplayList == nullptr
200                || properties().getAlpha() <= 0
201                || (outline.getShouldClip() && outline.isEmpty())
202                || properties().getScaleX() == 0
203                || properties().getScaleY() == 0;
204    }
205
206    const DisplayList* getDisplayList() const {
207        return mDisplayList;
208    }
209    OffscreenBuffer* getLayer() const { return mLayer; }
210    OffscreenBuffer** getLayerHandle() { return &mLayer; } // ugh...
211    void setLayer(OffscreenBuffer* layer) { mLayer = layer; }
212
213    // Note: The position callbacks are relying on the listener using
214    // the frameNumber to appropriately batch/synchronize these transactions.
215    // There is no other filtering/batching to ensure that only the "final"
216    // state called once per frame.
217    class ANDROID_API PositionListener : public VirtualLightRefBase {
218    public:
219        virtual ~PositionListener() {}
220        // Called when the RenderNode's position changes
221        virtual void onPositionUpdated(RenderNode& node, const TreeInfo& info) = 0;
222        // Called when the RenderNode no longer has a position. As in, it's
223        // no longer being drawn.
224        // Note, tree info might be null
225        virtual void onPositionLost(RenderNode& node, const TreeInfo* info) = 0;
226    };
227
228    // Note this is not thread safe, this needs to be called
229    // before the RenderNode is used for drawing.
230    // RenderNode takes ownership of the pointer
231    ANDROID_API void setPositionListener(PositionListener* listener) {
232        mPositionListener = listener;
233    }
234
235    // This is only modified in MODE_FULL, so it can be safely accessed
236    // on the UI thread.
237    ANDROID_API bool hasParents() {
238        return mParentCount;
239    }
240
241    void onRemovedFromTree(TreeInfo* info);
242
243    // Called by CanvasContext to promote a RenderNode to be a root node
244    void makeRoot() {
245        incParentRefCount();
246    }
247
248    // Called by CanvasContext when it drops a RenderNode from being a root node
249    void clearRoot();
250
251private:
252    void computeOrderingImpl(RenderNodeOp* opState,
253            std::vector<RenderNodeOp*>* compositedChildrenOfProjectionSurface,
254            const mat4* transformFromProjectionSurface);
255
256    void syncProperties();
257    void syncDisplayList(TreeObserver& observer, TreeInfo* info);
258
259    void prepareTreeImpl(TreeObserver& observer, TreeInfo& info, bool functorsNeedLayer);
260    void pushStagingPropertiesChanges(TreeInfo& info);
261    void pushStagingDisplayListChanges(TreeObserver& observer, TreeInfo& info);
262    void prepareLayer(TreeInfo& info, uint32_t dirtyMask);
263    void pushLayerUpdate(TreeInfo& info);
264    void deleteDisplayList(TreeObserver& observer, TreeInfo* info = nullptr);
265    void damageSelf(TreeInfo& info);
266
267    void incParentRefCount() { mParentCount++; }
268    void decParentRefCount(TreeObserver& observer, TreeInfo* info = nullptr);
269    void output(std::ostream& output, uint32_t level);
270
271    String8 mName;
272    sp<VirtualLightRefBase> mUserContext;
273
274    uint32_t mDirtyPropertyFields;
275    RenderProperties mProperties;
276    RenderProperties mStagingProperties;
277
278    // Owned by UI. Set when DL is set, cleared when DL cleared or when node detached
279    // (likely by parent re-record/removal)
280    bool mValid = false;
281
282    bool mNeedsDisplayListSync;
283    // WARNING: Do not delete this directly, you must go through deleteDisplayList()!
284    DisplayList* mDisplayList;
285    DisplayList* mStagingDisplayList;
286
287    friend class AnimatorManager;
288    AnimatorManager mAnimatorManager;
289
290    // Owned by RT. Lifecycle is managed by prepareTree(), with the exception
291    // being in ~RenderNode() which may happen on any thread.
292    OffscreenBuffer* mLayer = nullptr;
293
294    /**
295     * Draw time state - these properties are only set and used during rendering
296     */
297
298    // for projection surfaces, contains a list of all children items
299    std::vector<RenderNodeOp*> mProjectedNodes;
300
301    // How many references our parent(s) have to us. Typically this should alternate
302    // between 2 and 1 (when a staging push happens we inc first then dec)
303    // When this hits 0 we are no longer in the tree, so any hardware resources
304    // (specifically Layers) should be released.
305    // This is *NOT* thread-safe, and should therefore only be tracking
306    // mDisplayList, not mStagingDisplayList.
307    uint32_t mParentCount;
308
309    sp<PositionListener> mPositionListener;
310
311// METHODS & FIELDS ONLY USED BY THE SKIA RENDERER
312public:
313    /**
314     * Detach and transfer ownership of an already allocated displayList for use
315     * in recording updated content for this renderNode
316     */
317    std::unique_ptr<skiapipeline::SkiaDisplayList> detachAvailableList() {
318        return std::move(mAvailableDisplayList);
319    }
320
321    /**
322     * Attach unused displayList to this node for potential future reuse.
323     */
324    void attachAvailableList(skiapipeline::SkiaDisplayList* skiaDisplayList) {
325        mAvailableDisplayList.reset(skiaDisplayList);
326    }
327
328    /**
329     * Returns true if an offscreen layer from any renderPipeline is attached
330     * to this node.
331     */
332    bool hasLayer() const { return mLayer || mSkiaLayer.get(); }
333
334    /**
335     * Used by the RenderPipeline to attach an offscreen surface to the RenderNode.
336     * The surface is then will be used to store the contents of a layer.
337     */
338    void setLayerSurface(sk_sp<SkSurface> layer) {
339        if (layer.get()) {
340            if (!mSkiaLayer.get()) {
341                mSkiaLayer = std::make_unique<skiapipeline::SkiaLayer>();
342            }
343            mSkiaLayer->layerSurface = std::move(layer);
344            mSkiaLayer->inverseTransformInWindow.loadIdentity();
345        } else {
346            mSkiaLayer.reset();
347        }
348    }
349
350    /**
351     * If the RenderNode is of type LayerType::RenderLayer then this method will
352     * return the an offscreen rendering surface that is used to both render into
353     * the layer and composite the layer into its parent.  If the type is not
354     * LayerType::RenderLayer then it will return a nullptr.
355     *
356     * NOTE: this function is only guaranteed to return accurate results after
357     *       prepareTree has been run for this RenderNode
358     */
359    SkSurface* getLayerSurface() const {
360        return mSkiaLayer.get() ? mSkiaLayer->layerSurface.get() : nullptr;
361    }
362
363    skiapipeline::SkiaLayer* getSkiaLayer() const {
364        return mSkiaLayer.get();
365    }
366
367private:
368    /**
369     * If this RenderNode has been used in a previous frame then the SkiaDisplayList
370     * from that frame is cached here until one of the following conditions is met:
371     *  1) The RenderNode is deleted (causing this to be deleted)
372     *  2) It is replaced with the displayList from the next completed frame
373     *  3) It is detached and used to to record a new displayList for a later frame
374     */
375    std::unique_ptr<skiapipeline::SkiaDisplayList> mAvailableDisplayList;
376
377    /**
378     * An offscreen rendering target used to contain the contents this RenderNode
379     * when it has been set to draw as a LayerType::RenderLayer.
380     */
381    std::unique_ptr<skiapipeline::SkiaLayer> mSkiaLayer;
382}; // class RenderNode
383
384class MarkAndSweepRemoved : public TreeObserver {
385PREVENT_COPY_AND_ASSIGN(MarkAndSweepRemoved);
386
387public:
388    explicit MarkAndSweepRemoved(TreeInfo* info) : mTreeInfo(info) {}
389
390    void onMaybeRemovedFromTree(RenderNode* node) override {
391        mMarked.emplace_back(node);
392    }
393
394    ~MarkAndSweepRemoved() {
395        for (auto& node : mMarked) {
396            if (!node->hasParents()) {
397                node->onRemovedFromTree(mTreeInfo);
398            }
399        }
400    }
401
402private:
403    FatVector<sp<RenderNode>, 10> mMarked;
404    TreeInfo* mTreeInfo;
405};
406
407} /* namespace uirenderer */
408} /* namespace android */
409