RenderNode.cpp revision 07c056d627be315796d53bf07f8e06f449d92668
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 "RenderNode.h"
18
19#include "DamageAccumulator.h"
20#include "Debug.h"
21#if HWUI_NEW_OPS
22#include "BakedOpRenderer.h"
23#include "RecordedOp.h"
24#include "OpDumper.h"
25#endif
26#include "DisplayListOp.h"
27#include "LayerRenderer.h"
28#include "OpenGLRenderer.h"
29#include "TreeInfo.h"
30#include "utils/MathUtils.h"
31#include "utils/TraceUtils.h"
32#include "renderthread/CanvasContext.h"
33
34#include "protos/hwui.pb.h"
35#include "protos/ProtoHelpers.h"
36
37#include <algorithm>
38#include <sstream>
39#include <string>
40
41namespace android {
42namespace uirenderer {
43
44void RenderNode::debugDumpLayers(const char* prefix) {
45#if HWUI_NEW_OPS
46    LOG_ALWAYS_FATAL("TODO: dump layer");
47#else
48    if (mLayer) {
49        ALOGD("%sNode %p (%s) has layer %p (fbo = %u, wasBuildLayered = %s)",
50                prefix, this, getName(), mLayer, mLayer->getFbo(),
51                mLayer->wasBuildLayered ? "true" : "false");
52    }
53#endif
54    if (mDisplayList) {
55        for (auto&& child : mDisplayList->getChildren()) {
56            child->renderNode->debugDumpLayers(prefix);
57        }
58    }
59}
60
61RenderNode::RenderNode()
62        : mDirtyPropertyFields(0)
63        , mNeedsDisplayListSync(false)
64        , mDisplayList(nullptr)
65        , mStagingDisplayList(nullptr)
66        , mAnimatorManager(*this)
67        , mParentCount(0) {
68}
69
70RenderNode::~RenderNode() {
71    deleteDisplayList(nullptr);
72    delete mStagingDisplayList;
73#if HWUI_NEW_OPS
74    LOG_ALWAYS_FATAL_IF(mLayer, "layer missed detachment!");
75#else
76    if (mLayer) {
77        ALOGW("Memory Warning: Layer %p missed its detachment, held on to for far too long!", mLayer);
78        mLayer->postDecStrong();
79        mLayer = nullptr;
80    }
81#endif
82}
83
84void RenderNode::setStagingDisplayList(DisplayList* displayList, TreeObserver* observer) {
85    mNeedsDisplayListSync = true;
86    delete mStagingDisplayList;
87    mStagingDisplayList = displayList;
88    // If mParentCount == 0 we are the sole reference to this RenderNode,
89    // so immediately free the old display list
90    if (!mParentCount && !mStagingDisplayList) {
91        deleteDisplayList(observer);
92    }
93}
94
95/**
96 * This function is a simplified version of replay(), where we simply retrieve and log the
97 * display list. This function should remain in sync with the replay() function.
98 */
99#if HWUI_NEW_OPS
100void RenderNode::output(uint32_t level, const char* label) {
101    ALOGD("%s (%s %p%s%s%s%s%s)",
102            label,
103            getName(),
104            this,
105            (MathUtils::isZero(properties().getAlpha()) ? ", zero alpha" : ""),
106            (properties().hasShadow() ? ", casting shadow" : ""),
107            (isRenderable() ? "" : ", empty"),
108            (properties().getProjectBackwards() ? ", projected" : ""),
109            (mLayer != nullptr ? ", on HW Layer" : ""));
110    properties().debugOutputProperties(level + 1);
111
112    if (mDisplayList) {
113        for (auto&& op : mDisplayList->getOps()) {
114            std::stringstream strout;
115            OpDumper::dump(*op, strout, level + 1);
116            if (op->opId == RecordedOpId::RenderNodeOp) {
117                auto rnOp = reinterpret_cast<const RenderNodeOp*>(op);
118                rnOp->renderNode->output(level + 1, strout.str().c_str());
119            } else {
120                ALOGD("%s", strout.str().c_str());
121            }
122        }
123    }
124    ALOGD("%*s/RenderNode(%s %p)", level * 2, "", getName(), this);
125}
126#else
127void RenderNode::output(uint32_t level) {
128    ALOGD("%*sStart display list (%p, %s%s%s%s%s%s)", (level - 1) * 2, "", this,
129            getName(),
130            (MathUtils::isZero(properties().getAlpha()) ? ", zero alpha" : ""),
131            (properties().hasShadow() ? ", casting shadow" : ""),
132            (isRenderable() ? "" : ", empty"),
133            (properties().getProjectBackwards() ? ", projected" : ""),
134            (mLayer != nullptr ? ", on HW Layer" : ""));
135    ALOGD("%*s%s %d", level * 2, "", "Save", SaveFlags::MatrixClip);
136    properties().debugOutputProperties(level);
137    if (mDisplayList) {
138        // TODO: consider printing the chunk boundaries here
139        for (auto&& op : mDisplayList->getOps()) {
140            op->output(level, DisplayListOp::kOpLogFlag_Recurse);
141        }
142    }
143    ALOGD("%*sDone (%p, %s)", (level - 1) * 2, "", this, getName());
144    }
145#endif
146
147void RenderNode::copyTo(proto::RenderNode *pnode) {
148    pnode->set_id(static_cast<uint64_t>(
149            reinterpret_cast<uintptr_t>(this)));
150    pnode->set_name(mName.string(), mName.length());
151
152    proto::RenderProperties* pprops = pnode->mutable_properties();
153    pprops->set_left(properties().getLeft());
154    pprops->set_top(properties().getTop());
155    pprops->set_right(properties().getRight());
156    pprops->set_bottom(properties().getBottom());
157    pprops->set_clip_flags(properties().getClippingFlags());
158    pprops->set_alpha(properties().getAlpha());
159    pprops->set_translation_x(properties().getTranslationX());
160    pprops->set_translation_y(properties().getTranslationY());
161    pprops->set_translation_z(properties().getTranslationZ());
162    pprops->set_elevation(properties().getElevation());
163    pprops->set_rotation(properties().getRotation());
164    pprops->set_rotation_x(properties().getRotationX());
165    pprops->set_rotation_y(properties().getRotationY());
166    pprops->set_scale_x(properties().getScaleX());
167    pprops->set_scale_y(properties().getScaleY());
168    pprops->set_pivot_x(properties().getPivotX());
169    pprops->set_pivot_y(properties().getPivotY());
170    pprops->set_has_overlapping_rendering(properties().getHasOverlappingRendering());
171    pprops->set_pivot_explicitly_set(properties().isPivotExplicitlySet());
172    pprops->set_project_backwards(properties().getProjectBackwards());
173    pprops->set_projection_receiver(properties().isProjectionReceiver());
174    set(pprops->mutable_clip_bounds(), properties().getClipBounds());
175
176    const Outline& outline = properties().getOutline();
177    if (outline.getType() != Outline::Type::None) {
178        proto::Outline* poutline = pprops->mutable_outline();
179        poutline->clear_path();
180        if (outline.getType() == Outline::Type::Empty) {
181            poutline->set_type(proto::Outline_Type_Empty);
182        } else if (outline.getType() == Outline::Type::ConvexPath) {
183            poutline->set_type(proto::Outline_Type_ConvexPath);
184            if (const SkPath* path = outline.getPath()) {
185                set(poutline->mutable_path(), *path);
186            }
187        } else if (outline.getType() == Outline::Type::RoundRect) {
188            poutline->set_type(proto::Outline_Type_RoundRect);
189        } else {
190            ALOGW("Uknown outline type! %d", static_cast<int>(outline.getType()));
191            poutline->set_type(proto::Outline_Type_None);
192        }
193        poutline->set_should_clip(outline.getShouldClip());
194        poutline->set_alpha(outline.getAlpha());
195        poutline->set_radius(outline.getRadius());
196        set(poutline->mutable_bounds(), outline.getBounds());
197    } else {
198        pprops->clear_outline();
199    }
200
201    const RevealClip& revealClip = properties().getRevealClip();
202    if (revealClip.willClip()) {
203        proto::RevealClip* prevealClip = pprops->mutable_reveal_clip();
204        prevealClip->set_x(revealClip.getX());
205        prevealClip->set_y(revealClip.getY());
206        prevealClip->set_radius(revealClip.getRadius());
207    } else {
208        pprops->clear_reveal_clip();
209    }
210
211    pnode->clear_children();
212    if (mDisplayList) {
213        for (auto&& child : mDisplayList->getChildren()) {
214            child->renderNode->copyTo(pnode->add_children());
215        }
216    }
217}
218
219int RenderNode::getDebugSize() {
220    int size = sizeof(RenderNode);
221    if (mStagingDisplayList) {
222        size += mStagingDisplayList->getUsedSize();
223    }
224    if (mDisplayList && mDisplayList != mStagingDisplayList) {
225        size += mDisplayList->getUsedSize();
226    }
227    return size;
228}
229
230void RenderNode::prepareTree(TreeInfo& info) {
231    ATRACE_CALL();
232    LOG_ALWAYS_FATAL_IF(!info.damageAccumulator, "DamageAccumulator missing");
233
234    // Functors don't correctly handle stencil usage of overdraw debugging - shove 'em in a layer.
235    bool functorsNeedLayer = Properties::debugOverdraw;
236
237    prepareTreeImpl(info, functorsNeedLayer);
238}
239
240void RenderNode::addAnimator(const sp<BaseRenderNodeAnimator>& animator) {
241    mAnimatorManager.addAnimator(animator);
242}
243
244void RenderNode::removeAnimator(const sp<BaseRenderNodeAnimator>& animator) {
245    mAnimatorManager.removeAnimator(animator);
246}
247
248void RenderNode::damageSelf(TreeInfo& info) {
249    if (isRenderable()) {
250        if (properties().getClipDamageToBounds()) {
251            info.damageAccumulator->dirty(0, 0, properties().getWidth(), properties().getHeight());
252        } else {
253            // Hope this is big enough?
254            // TODO: Get this from the display list ops or something
255            info.damageAccumulator->dirty(DIRTY_MIN, DIRTY_MIN, DIRTY_MAX, DIRTY_MAX);
256        }
257    }
258}
259
260void RenderNode::prepareLayer(TreeInfo& info, uint32_t dirtyMask) {
261    LayerType layerType = properties().effectiveLayerType();
262    if (CC_UNLIKELY(layerType == LayerType::RenderLayer)) {
263        // Damage applied so far needs to affect our parent, but does not require
264        // the layer to be updated. So we pop/push here to clear out the current
265        // damage and get a clean state for display list or children updates to
266        // affect, which will require the layer to be updated
267        info.damageAccumulator->popTransform();
268        info.damageAccumulator->pushTransform(this);
269        if (dirtyMask & DISPLAY_LIST) {
270            damageSelf(info);
271        }
272    }
273}
274
275static layer_t* createLayer(RenderState& renderState, uint32_t width, uint32_t height) {
276#if HWUI_NEW_OPS
277    return renderState.layerPool().get(renderState, width, height);
278#else
279    return LayerRenderer::createRenderLayer(renderState, width, height);
280#endif
281}
282
283static void destroyLayer(layer_t* layer) {
284#if HWUI_NEW_OPS
285    RenderState& renderState = layer->renderState;
286    renderState.layerPool().putOrDelete(layer);
287#else
288    LayerRenderer::destroyLayer(layer);
289#endif
290}
291
292static bool layerMatchesWidthAndHeight(layer_t* layer, int width, int height) {
293#if HWUI_NEW_OPS
294    return layer->viewportWidth == (uint32_t) width && layer->viewportHeight == (uint32_t)height;
295#else
296    return layer->layer.getWidth() == width && layer->layer.getHeight() == height;
297#endif
298}
299
300void RenderNode::pushLayerUpdate(TreeInfo& info) {
301    LayerType layerType = properties().effectiveLayerType();
302    // If we are not a layer OR we cannot be rendered (eg, view was detached)
303    // we need to destroy any Layers we may have had previously
304    if (CC_LIKELY(layerType != LayerType::RenderLayer) || CC_UNLIKELY(!isRenderable())) {
305        if (CC_UNLIKELY(mLayer)) {
306            destroyLayer(mLayer);
307            mLayer = nullptr;
308        }
309        return;
310    }
311
312    bool transformUpdateNeeded = false;
313    if (!mLayer) {
314        mLayer = createLayer(info.canvasContext.getRenderState(), getWidth(), getHeight());
315#if !HWUI_NEW_OPS
316        applyLayerPropertiesToLayer(info);
317#endif
318        damageSelf(info);
319        transformUpdateNeeded = true;
320    } else if (!layerMatchesWidthAndHeight(mLayer, getWidth(), getHeight())) {
321#if HWUI_NEW_OPS
322        // TODO: remove now irrelevant, currently enqueued damage (respecting damage ordering)
323        // Or, ideally, maintain damage between frames on node/layer so ordering is always correct
324        RenderState& renderState = mLayer->renderState;
325        if (properties().fitsOnLayer()) {
326            mLayer = renderState.layerPool().resize(mLayer, getWidth(), getHeight());
327        } else {
328#else
329        if (!LayerRenderer::resizeLayer(mLayer, getWidth(), getHeight())) {
330#endif
331            destroyLayer(mLayer);
332            mLayer = nullptr;
333        }
334        damageSelf(info);
335        transformUpdateNeeded = true;
336    }
337
338    SkRect dirty;
339    info.damageAccumulator->peekAtDirty(&dirty);
340
341    if (!mLayer) {
342        Caches::getInstance().dumpMemoryUsage();
343        if (info.errorHandler) {
344            std::ostringstream err;
345            err << "Unable to create layer for " << getName();
346            const int maxTextureSize = Caches::getInstance().maxTextureSize;
347            if (getWidth() > maxTextureSize || getHeight() > maxTextureSize) {
348                err << ", size " << getWidth() << "x" << getHeight()
349                        << " exceeds max size " << maxTextureSize;
350            } else {
351                err << ", see logcat for more info";
352            }
353            info.errorHandler->onError(err.str());
354        }
355        return;
356    }
357
358    if (transformUpdateNeeded && mLayer) {
359        // update the transform in window of the layer to reset its origin wrt light source position
360        Matrix4 windowTransform;
361        info.damageAccumulator->computeCurrentTransform(&windowTransform);
362        mLayer->setWindowTransform(windowTransform);
363    }
364
365#if HWUI_NEW_OPS
366    info.layerUpdateQueue->enqueueLayerWithDamage(this, dirty);
367#else
368    if (dirty.intersect(0, 0, getWidth(), getHeight())) {
369        dirty.roundOut(&dirty);
370        mLayer->updateDeferred(this, dirty.fLeft, dirty.fTop, dirty.fRight, dirty.fBottom);
371    }
372    // This is not inside the above if because we may have called
373    // updateDeferred on a previous prepare pass that didn't have a renderer
374    if (info.renderer && mLayer->deferredUpdateScheduled) {
375        info.renderer->pushLayerUpdate(mLayer);
376    }
377#endif
378
379    // There might be prefetched layers that need to be accounted for.
380    // That might be us, so tell CanvasContext that this layer is in the
381    // tree and should not be destroyed.
382    info.canvasContext.markLayerInUse(this);
383}
384
385/**
386 * Traverse down the the draw tree to prepare for a frame.
387 *
388 * MODE_FULL = UI Thread-driven (thus properties must be synced), otherwise RT driven
389 *
390 * While traversing down the tree, functorsNeedLayer flag is set to true if anything that uses the
391 * stencil buffer may be needed. Views that use a functor to draw will be forced onto a layer.
392 */
393void RenderNode::prepareTreeImpl(TreeInfo& info, bool functorsNeedLayer) {
394    info.damageAccumulator->pushTransform(this);
395
396    if (info.mode == TreeInfo::MODE_FULL) {
397        pushStagingPropertiesChanges(info);
398    }
399    uint32_t animatorDirtyMask = 0;
400    if (CC_LIKELY(info.runAnimations)) {
401        animatorDirtyMask = mAnimatorManager.animate(info);
402    }
403
404    bool willHaveFunctor = false;
405    if (info.mode == TreeInfo::MODE_FULL && mStagingDisplayList) {
406        willHaveFunctor = !mStagingDisplayList->getFunctors().empty();
407    } else if (mDisplayList) {
408        willHaveFunctor = !mDisplayList->getFunctors().empty();
409    }
410    bool childFunctorsNeedLayer = mProperties.prepareForFunctorPresence(
411            willHaveFunctor, functorsNeedLayer);
412
413    if (CC_UNLIKELY(mPositionListener.get())) {
414        mPositionListener->onPositionUpdated(*this, info);
415    }
416
417    prepareLayer(info, animatorDirtyMask);
418    if (info.mode == TreeInfo::MODE_FULL) {
419        pushStagingDisplayListChanges(info);
420    }
421    prepareSubTree(info, childFunctorsNeedLayer, mDisplayList);
422    pushLayerUpdate(info);
423
424    if (mDisplayList) {
425        for (auto& vectorDrawable : mDisplayList->getVectorDrawables()) {
426            // If any vector drawable in the display list needs update, damage the node.
427            if (vectorDrawable->isDirty()) {
428                damageSelf(info);
429            }
430            vectorDrawable->setPropertyChangeWillBeConsumed(true);
431        }
432    }
433
434    info.damageAccumulator->popTransform();
435}
436
437void RenderNode::syncProperties() {
438    mProperties = mStagingProperties;
439}
440
441void RenderNode::pushStagingPropertiesChanges(TreeInfo& info) {
442    // Push the animators first so that setupStartValueIfNecessary() is called
443    // before properties() is trampled by stagingProperties(), as they are
444    // required by some animators.
445    if (CC_LIKELY(info.runAnimations)) {
446        mAnimatorManager.pushStaging();
447    }
448    if (mDirtyPropertyFields) {
449        mDirtyPropertyFields = 0;
450        damageSelf(info);
451        info.damageAccumulator->popTransform();
452        syncProperties();
453#if !HWUI_NEW_OPS
454        applyLayerPropertiesToLayer(info);
455#endif
456        // We could try to be clever and only re-damage if the matrix changed.
457        // However, we don't need to worry about that. The cost of over-damaging
458        // here is only going to be a single additional map rect of this node
459        // plus a rect join(). The parent's transform (and up) will only be
460        // performed once.
461        info.damageAccumulator->pushTransform(this);
462        damageSelf(info);
463    }
464}
465
466#if !HWUI_NEW_OPS
467void RenderNode::applyLayerPropertiesToLayer(TreeInfo& info) {
468    if (CC_LIKELY(!mLayer)) return;
469
470    const LayerProperties& props = properties().layerProperties();
471    mLayer->setAlpha(props.alpha(), props.xferMode());
472    mLayer->setColorFilter(props.colorFilter());
473    mLayer->setBlend(props.needsBlending());
474}
475#endif
476
477void RenderNode::syncDisplayList(TreeObserver* observer) {
478    // Make sure we inc first so that we don't fluctuate between 0 and 1,
479    // which would thrash the layer cache
480    if (mStagingDisplayList) {
481        for (auto&& child : mStagingDisplayList->getChildren()) {
482            child->renderNode->incParentRefCount();
483        }
484    }
485    deleteDisplayList(observer);
486    mDisplayList = mStagingDisplayList;
487    mStagingDisplayList = nullptr;
488    if (mDisplayList) {
489        for (auto& iter : mDisplayList->getFunctors()) {
490            (*iter.functor)(DrawGlInfo::kModeSync, nullptr);
491        }
492        for (auto& vectorDrawable : mDisplayList->getVectorDrawables()) {
493            vectorDrawable->syncProperties();
494        }
495    }
496}
497
498void RenderNode::pushStagingDisplayListChanges(TreeInfo& info) {
499    if (mNeedsDisplayListSync) {
500        mNeedsDisplayListSync = false;
501        // Damage with the old display list first then the new one to catch any
502        // changes in isRenderable or, in the future, bounds
503        damageSelf(info);
504        syncDisplayList(info.observer);
505        damageSelf(info);
506    }
507}
508
509void RenderNode::deleteDisplayList(TreeObserver* observer) {
510    if (mDisplayList) {
511        for (auto&& child : mDisplayList->getChildren()) {
512            child->renderNode->decParentRefCount(observer);
513        }
514    }
515    delete mDisplayList;
516    mDisplayList = nullptr;
517}
518
519void RenderNode::prepareSubTree(TreeInfo& info, bool functorsNeedLayer, DisplayList* subtree) {
520    if (subtree) {
521        TextureCache& cache = Caches::getInstance().textureCache;
522        info.out.hasFunctors |= subtree->getFunctors().size();
523        for (auto&& bitmapResource : subtree->getBitmapResources()) {
524            void* ownerToken = &info.canvasContext;
525            info.prepareTextures = cache.prefetchAndMarkInUse(ownerToken, bitmapResource);
526        }
527        for (auto&& op : subtree->getChildren()) {
528            RenderNode* childNode = op->renderNode;
529#if HWUI_NEW_OPS
530            info.damageAccumulator->pushTransform(&op->localMatrix);
531            bool childFunctorsNeedLayer = functorsNeedLayer; // TODO! || op->mRecordedWithPotentialStencilClip;
532#else
533            info.damageAccumulator->pushTransform(&op->localMatrix);
534            bool childFunctorsNeedLayer = functorsNeedLayer
535                    // Recorded with non-rect clip, or canvas-rotated by parent
536                    || op->mRecordedWithPotentialStencilClip;
537#endif
538            childNode->prepareTreeImpl(info, childFunctorsNeedLayer);
539            info.damageAccumulator->popTransform();
540        }
541    }
542}
543
544void RenderNode::destroyHardwareResources(TreeObserver* observer) {
545    if (mLayer) {
546        destroyLayer(mLayer);
547        mLayer = nullptr;
548    }
549    if (mDisplayList) {
550        for (auto&& child : mDisplayList->getChildren()) {
551            child->renderNode->destroyHardwareResources(observer);
552        }
553        if (mNeedsDisplayListSync) {
554            // Next prepare tree we are going to push a new display list, so we can
555            // drop our current one now
556            deleteDisplayList(observer);
557        }
558    }
559}
560
561void RenderNode::decParentRefCount(TreeObserver* observer) {
562    LOG_ALWAYS_FATAL_IF(!mParentCount, "already 0!");
563    mParentCount--;
564    if (!mParentCount) {
565        if (observer) {
566            observer->onMaybeRemovedFromTree(this);
567        }
568        // If a child of ours is being attached to our parent then this will incorrectly
569        // destroy its hardware resources. However, this situation is highly unlikely
570        // and the failure is "just" that the layer is re-created, so this should
571        // be safe enough
572        destroyHardwareResources(observer);
573    }
574}
575
576/*
577 * For property operations, we pass a savecount of 0, since the operations aren't part of the
578 * displaylist, and thus don't have to compensate for the record-time/playback-time discrepancy in
579 * base saveCount (i.e., how RestoreToCount uses saveCount + properties().getCount())
580 */
581#define PROPERTY_SAVECOUNT 0
582
583template <class T>
584void RenderNode::setViewProperties(OpenGLRenderer& renderer, T& handler) {
585#if DEBUG_DISPLAY_LIST
586    properties().debugOutputProperties(handler.level() + 1);
587#endif
588    if (properties().getLeft() != 0 || properties().getTop() != 0) {
589        renderer.translate(properties().getLeft(), properties().getTop());
590    }
591    if (properties().getStaticMatrix()) {
592        renderer.concatMatrix(*properties().getStaticMatrix());
593    } else if (properties().getAnimationMatrix()) {
594        renderer.concatMatrix(*properties().getAnimationMatrix());
595    }
596    if (properties().hasTransformMatrix()) {
597        if (properties().isTransformTranslateOnly()) {
598            renderer.translate(properties().getTranslationX(), properties().getTranslationY());
599        } else {
600            renderer.concatMatrix(*properties().getTransformMatrix());
601        }
602    }
603    const bool isLayer = properties().effectiveLayerType() != LayerType::None;
604    int clipFlags = properties().getClippingFlags();
605    if (properties().getAlpha() < 1) {
606        if (isLayer) {
607            clipFlags &= ~CLIP_TO_BOUNDS; // bounds clipping done by layer
608        }
609        if (CC_LIKELY(isLayer || !properties().getHasOverlappingRendering())) {
610            // simply scale rendering content's alpha
611            renderer.scaleAlpha(properties().getAlpha());
612        } else {
613            // savelayer needed to create an offscreen buffer
614            Rect layerBounds(0, 0, getWidth(), getHeight());
615            if (clipFlags) {
616                properties().getClippingRectForFlags(clipFlags, &layerBounds);
617                clipFlags = 0; // all clipping done by savelayer
618            }
619            SaveLayerOp* op = new (handler.allocator()) SaveLayerOp(
620                    layerBounds.left, layerBounds.top,
621                    layerBounds.right, layerBounds.bottom,
622                    (int) (properties().getAlpha() * 255),
623                    SaveFlags::HasAlphaLayer | SaveFlags::ClipToLayer);
624            handler(op, PROPERTY_SAVECOUNT, properties().getClipToBounds());
625        }
626
627        if (CC_UNLIKELY(ATRACE_ENABLED() && properties().promotedToLayer())) {
628            // pretend alpha always causes savelayer to warn about
629            // performance problem affecting old versions
630            ATRACE_FORMAT("%s alpha caused saveLayer %dx%d", getName(),
631                    static_cast<int>(getWidth()),
632                    static_cast<int>(getHeight()));
633        }
634    }
635    if (clipFlags) {
636        Rect clipRect;
637        properties().getClippingRectForFlags(clipFlags, &clipRect);
638        ClipRectOp* op = new (handler.allocator()) ClipRectOp(
639                clipRect.left, clipRect.top, clipRect.right, clipRect.bottom,
640                SkRegion::kIntersect_Op);
641        handler(op, PROPERTY_SAVECOUNT, properties().getClipToBounds());
642    }
643
644    // TODO: support nesting round rect clips
645    if (mProperties.getRevealClip().willClip()) {
646        Rect bounds;
647        mProperties.getRevealClip().getBounds(&bounds);
648        renderer.setClippingRoundRect(handler.allocator(), bounds, mProperties.getRevealClip().getRadius());
649    } else if (mProperties.getOutline().willClip()) {
650        renderer.setClippingOutline(handler.allocator(), &(mProperties.getOutline()));
651    }
652}
653
654/**
655 * Apply property-based transformations to input matrix
656 *
657 * If true3dTransform is set to true, the transform applied to the input matrix will use true 4x4
658 * matrix computation instead of the Skia 3x3 matrix + camera hackery.
659 */
660void RenderNode::applyViewPropertyTransforms(mat4& matrix, bool true3dTransform) const {
661    if (properties().getLeft() != 0 || properties().getTop() != 0) {
662        matrix.translate(properties().getLeft(), properties().getTop());
663    }
664    if (properties().getStaticMatrix()) {
665        mat4 stat(*properties().getStaticMatrix());
666        matrix.multiply(stat);
667    } else if (properties().getAnimationMatrix()) {
668        mat4 anim(*properties().getAnimationMatrix());
669        matrix.multiply(anim);
670    }
671
672    bool applyTranslationZ = true3dTransform && !MathUtils::isZero(properties().getZ());
673    if (properties().hasTransformMatrix() || applyTranslationZ) {
674        if (properties().isTransformTranslateOnly()) {
675            matrix.translate(properties().getTranslationX(), properties().getTranslationY(),
676                    true3dTransform ? properties().getZ() : 0.0f);
677        } else {
678            if (!true3dTransform) {
679                matrix.multiply(*properties().getTransformMatrix());
680            } else {
681                mat4 true3dMat;
682                true3dMat.loadTranslate(
683                        properties().getPivotX() + properties().getTranslationX(),
684                        properties().getPivotY() + properties().getTranslationY(),
685                        properties().getZ());
686                true3dMat.rotate(properties().getRotationX(), 1, 0, 0);
687                true3dMat.rotate(properties().getRotationY(), 0, 1, 0);
688                true3dMat.rotate(properties().getRotation(), 0, 0, 1);
689                true3dMat.scale(properties().getScaleX(), properties().getScaleY(), 1);
690                true3dMat.translate(-properties().getPivotX(), -properties().getPivotY());
691
692                matrix.multiply(true3dMat);
693            }
694        }
695    }
696}
697
698/**
699 * Organizes the DisplayList hierarchy to prepare for background projection reordering.
700 *
701 * This should be called before a call to defer() or drawDisplayList()
702 *
703 * Each DisplayList that serves as a 3d root builds its list of composited children,
704 * which are flagged to not draw in the standard draw loop.
705 */
706void RenderNode::computeOrdering() {
707    ATRACE_CALL();
708    mProjectedNodes.clear();
709
710    // TODO: create temporary DDLOp and call computeOrderingImpl on top DisplayList so that
711    // transform properties are applied correctly to top level children
712    if (mDisplayList == nullptr) return;
713    for (unsigned int i = 0; i < mDisplayList->getChildren().size(); i++) {
714        renderNodeOp_t* childOp = mDisplayList->getChildren()[i];
715        childOp->renderNode->computeOrderingImpl(childOp, &mProjectedNodes, &mat4::identity());
716    }
717}
718
719void RenderNode::computeOrderingImpl(
720        renderNodeOp_t* opState,
721        std::vector<renderNodeOp_t*>* compositedChildrenOfProjectionSurface,
722        const mat4* transformFromProjectionSurface) {
723    mProjectedNodes.clear();
724    if (mDisplayList == nullptr || mDisplayList->isEmpty()) return;
725
726    // TODO: should avoid this calculation in most cases
727    // TODO: just calculate single matrix, down to all leaf composited elements
728    Matrix4 localTransformFromProjectionSurface(*transformFromProjectionSurface);
729    localTransformFromProjectionSurface.multiply(opState->localMatrix);
730
731    if (properties().getProjectBackwards()) {
732        // composited projectee, flag for out of order draw, save matrix, and store in proj surface
733        opState->skipInOrderDraw = true;
734        opState->transformFromCompositingAncestor = localTransformFromProjectionSurface;
735        compositedChildrenOfProjectionSurface->push_back(opState);
736    } else {
737        // standard in order draw
738        opState->skipInOrderDraw = false;
739    }
740
741    if (mDisplayList->getChildren().size() > 0) {
742        const bool isProjectionReceiver = mDisplayList->projectionReceiveIndex >= 0;
743        bool haveAppliedPropertiesToProjection = false;
744        for (unsigned int i = 0; i < mDisplayList->getChildren().size(); i++) {
745            renderNodeOp_t* childOp = mDisplayList->getChildren()[i];
746            RenderNode* child = childOp->renderNode;
747
748            std::vector<renderNodeOp_t*>* projectionChildren = nullptr;
749            const mat4* projectionTransform = nullptr;
750            if (isProjectionReceiver && !child->properties().getProjectBackwards()) {
751                // if receiving projections, collect projecting descendant
752
753                // Note that if a direct descendant is projecting backwards, we pass its
754                // grandparent projection collection, since it shouldn't project onto its
755                // parent, where it will already be drawing.
756                projectionChildren = &mProjectedNodes;
757                projectionTransform = &mat4::identity();
758            } else {
759                if (!haveAppliedPropertiesToProjection) {
760                    applyViewPropertyTransforms(localTransformFromProjectionSurface);
761                    haveAppliedPropertiesToProjection = true;
762                }
763                projectionChildren = compositedChildrenOfProjectionSurface;
764                projectionTransform = &localTransformFromProjectionSurface;
765            }
766            child->computeOrderingImpl(childOp, projectionChildren, projectionTransform);
767        }
768    }
769}
770
771class DeferOperationHandler {
772public:
773    DeferOperationHandler(DeferStateStruct& deferStruct, int level)
774        : mDeferStruct(deferStruct), mLevel(level) {}
775    inline void operator()(DisplayListOp* operation, int saveCount, bool clipToBounds) {
776        operation->defer(mDeferStruct, saveCount, mLevel, clipToBounds);
777    }
778    inline LinearAllocator& allocator() { return *(mDeferStruct.mAllocator); }
779    inline void startMark(const char* name) {} // do nothing
780    inline void endMark() {}
781    inline int level() { return mLevel; }
782    inline int replayFlags() { return mDeferStruct.mReplayFlags; }
783    inline SkPath* allocPathForFrame() { return mDeferStruct.allocPathForFrame(); }
784
785private:
786    DeferStateStruct& mDeferStruct;
787    const int mLevel;
788};
789
790void RenderNode::defer(DeferStateStruct& deferStruct, const int level) {
791    DeferOperationHandler handler(deferStruct, level);
792    issueOperations<DeferOperationHandler>(deferStruct.mRenderer, handler);
793}
794
795class ReplayOperationHandler {
796public:
797    ReplayOperationHandler(ReplayStateStruct& replayStruct, int level)
798        : mReplayStruct(replayStruct), mLevel(level) {}
799    inline void operator()(DisplayListOp* operation, int saveCount, bool clipToBounds) {
800#if DEBUG_DISPLAY_LIST_OPS_AS_EVENTS
801        mReplayStruct.mRenderer.eventMark(operation->name());
802#endif
803        operation->replay(mReplayStruct, saveCount, mLevel, clipToBounds);
804    }
805    inline LinearAllocator& allocator() { return *(mReplayStruct.mAllocator); }
806    inline void startMark(const char* name) {
807        mReplayStruct.mRenderer.startMark(name);
808    }
809    inline void endMark() {
810        mReplayStruct.mRenderer.endMark();
811    }
812    inline int level() { return mLevel; }
813    inline int replayFlags() { return mReplayStruct.mReplayFlags; }
814    inline SkPath* allocPathForFrame() { return mReplayStruct.allocPathForFrame(); }
815
816private:
817    ReplayStateStruct& mReplayStruct;
818    const int mLevel;
819};
820
821void RenderNode::replay(ReplayStateStruct& replayStruct, const int level) {
822    ReplayOperationHandler handler(replayStruct, level);
823    issueOperations<ReplayOperationHandler>(replayStruct.mRenderer, handler);
824}
825
826void RenderNode::buildZSortedChildList(const DisplayList::Chunk& chunk,
827        std::vector<ZDrawRenderNodeOpPair>& zTranslatedNodes) {
828#if !HWUI_NEW_OPS
829    if (chunk.beginChildIndex == chunk.endChildIndex) return;
830
831    for (unsigned int i = chunk.beginChildIndex; i < chunk.endChildIndex; i++) {
832        DrawRenderNodeOp* childOp = mDisplayList->getChildren()[i];
833        RenderNode* child = childOp->renderNode;
834        float childZ = child->properties().getZ();
835
836        if (!MathUtils::isZero(childZ) && chunk.reorderChildren) {
837            zTranslatedNodes.push_back(ZDrawRenderNodeOpPair(childZ, childOp));
838            childOp->skipInOrderDraw = true;
839        } else if (!child->properties().getProjectBackwards()) {
840            // regular, in order drawing DisplayList
841            childOp->skipInOrderDraw = false;
842        }
843    }
844
845    // Z sort any 3d children (stable-ness makes z compare fall back to standard drawing order)
846    std::stable_sort(zTranslatedNodes.begin(), zTranslatedNodes.end());
847#endif
848}
849
850template <class T>
851void RenderNode::issueDrawShadowOperation(const Matrix4& transformFromParent, T& handler) {
852    if (properties().getAlpha() <= 0.0f
853            || properties().getOutline().getAlpha() <= 0.0f
854            || !properties().getOutline().getPath()
855            || properties().getScaleX() == 0
856            || properties().getScaleY() == 0) {
857        // no shadow to draw
858        return;
859    }
860
861    mat4 shadowMatrixXY(transformFromParent);
862    applyViewPropertyTransforms(shadowMatrixXY);
863
864    // Z matrix needs actual 3d transformation, so mapped z values will be correct
865    mat4 shadowMatrixZ(transformFromParent);
866    applyViewPropertyTransforms(shadowMatrixZ, true);
867
868    const SkPath* casterOutlinePath = properties().getOutline().getPath();
869    const SkPath* revealClipPath = properties().getRevealClip().getPath();
870    if (revealClipPath && revealClipPath->isEmpty()) return;
871
872    float casterAlpha = properties().getAlpha() * properties().getOutline().getAlpha();
873
874
875    // holds temporary SkPath to store the result of intersections
876    SkPath* frameAllocatedPath = nullptr;
877    const SkPath* outlinePath = casterOutlinePath;
878
879    // intersect the outline with the reveal clip, if present
880    if (revealClipPath) {
881        frameAllocatedPath = handler.allocPathForFrame();
882
883        Op(*outlinePath, *revealClipPath, kIntersect_SkPathOp, frameAllocatedPath);
884        outlinePath = frameAllocatedPath;
885    }
886
887    // intersect the outline with the clipBounds, if present
888    if (properties().getClippingFlags() & CLIP_TO_CLIP_BOUNDS) {
889        if (!frameAllocatedPath) {
890            frameAllocatedPath = handler.allocPathForFrame();
891        }
892
893        Rect clipBounds;
894        properties().getClippingRectForFlags(CLIP_TO_CLIP_BOUNDS, &clipBounds);
895        SkPath clipBoundsPath;
896        clipBoundsPath.addRect(clipBounds.left, clipBounds.top,
897                clipBounds.right, clipBounds.bottom);
898
899        Op(*outlinePath, clipBoundsPath, kIntersect_SkPathOp, frameAllocatedPath);
900        outlinePath = frameAllocatedPath;
901    }
902
903    DisplayListOp* shadowOp  = new (handler.allocator()) DrawShadowOp(
904            shadowMatrixXY, shadowMatrixZ, casterAlpha, outlinePath);
905    handler(shadowOp, PROPERTY_SAVECOUNT, properties().getClipToBounds());
906}
907
908#define SHADOW_DELTA 0.1f
909
910template <class T>
911void RenderNode::issueOperationsOf3dChildren(ChildrenSelectMode mode,
912        const Matrix4& initialTransform, const std::vector<ZDrawRenderNodeOpPair>& zTranslatedNodes,
913        OpenGLRenderer& renderer, T& handler) {
914    const int size = zTranslatedNodes.size();
915    if (size == 0
916            || (mode == ChildrenSelectMode::NegativeZChildren && zTranslatedNodes[0].key > 0.0f)
917            || (mode == ChildrenSelectMode::PositiveZChildren && zTranslatedNodes[size - 1].key < 0.0f)) {
918        // no 3d children to draw
919        return;
920    }
921
922    // Apply the base transform of the parent of the 3d children. This isolates
923    // 3d children of the current chunk from transformations made in previous chunks.
924    int rootRestoreTo = renderer.save(SaveFlags::Matrix);
925    renderer.setGlobalMatrix(initialTransform);
926
927    /**
928     * Draw shadows and (potential) casters mostly in order, but allow the shadows of casters
929     * with very similar Z heights to draw together.
930     *
931     * This way, if Views A & B have the same Z height and are both casting shadows, the shadows are
932     * underneath both, and neither's shadow is drawn on top of the other.
933     */
934    const size_t nonNegativeIndex = findNonNegativeIndex(zTranslatedNodes);
935    size_t drawIndex, shadowIndex, endIndex;
936    if (mode == ChildrenSelectMode::NegativeZChildren) {
937        drawIndex = 0;
938        endIndex = nonNegativeIndex;
939        shadowIndex = endIndex; // draw no shadows
940    } else {
941        drawIndex = nonNegativeIndex;
942        endIndex = size;
943        shadowIndex = drawIndex; // potentially draw shadow for each pos Z child
944    }
945
946    DISPLAY_LIST_LOGD("%*s%d %s 3d children:", (handler.level() + 1) * 2, "",
947            endIndex - drawIndex, mode == kNegativeZChildren ? "negative" : "positive");
948
949    float lastCasterZ = 0.0f;
950    while (shadowIndex < endIndex || drawIndex < endIndex) {
951        if (shadowIndex < endIndex) {
952            DrawRenderNodeOp* casterOp = zTranslatedNodes[shadowIndex].value;
953            RenderNode* caster = casterOp->renderNode;
954            const float casterZ = zTranslatedNodes[shadowIndex].key;
955            // attempt to render the shadow if the caster about to be drawn is its caster,
956            // OR if its caster's Z value is similar to the previous potential caster
957            if (shadowIndex == drawIndex || casterZ - lastCasterZ < SHADOW_DELTA) {
958                caster->issueDrawShadowOperation(casterOp->localMatrix, handler);
959
960                lastCasterZ = casterZ; // must do this even if current caster not casting a shadow
961                shadowIndex++;
962                continue;
963            }
964        }
965
966        // only the actual child DL draw needs to be in save/restore,
967        // since it modifies the renderer's matrix
968        int restoreTo = renderer.save(SaveFlags::Matrix);
969
970        DrawRenderNodeOp* childOp = zTranslatedNodes[drawIndex].value;
971
972        renderer.concatMatrix(childOp->localMatrix);
973        childOp->skipInOrderDraw = false; // this is horrible, I'm so sorry everyone
974        handler(childOp, renderer.getSaveCount() - 1, properties().getClipToBounds());
975        childOp->skipInOrderDraw = true;
976
977        renderer.restoreToCount(restoreTo);
978        drawIndex++;
979    }
980    renderer.restoreToCount(rootRestoreTo);
981}
982
983template <class T>
984void RenderNode::issueOperationsOfProjectedChildren(OpenGLRenderer& renderer, T& handler) {
985    DISPLAY_LIST_LOGD("%*s%d projected children:", (handler.level() + 1) * 2, "", mProjectedNodes.size());
986    const SkPath* projectionReceiverOutline = properties().getOutline().getPath();
987    int restoreTo = renderer.getSaveCount();
988
989    LinearAllocator& alloc = handler.allocator();
990    handler(new (alloc) SaveOp(SaveFlags::MatrixClip),
991            PROPERTY_SAVECOUNT, properties().getClipToBounds());
992
993    // Transform renderer to match background we're projecting onto
994    // (by offsetting canvas by translationX/Y of background rendernode, since only those are set)
995    const DisplayListOp* op =
996#if HWUI_NEW_OPS
997            nullptr;
998    LOG_ALWAYS_FATAL("unsupported");
999#else
1000            (mDisplayList->getOps()[mDisplayList->projectionReceiveIndex]);
1001#endif
1002    const DrawRenderNodeOp* backgroundOp = reinterpret_cast<const DrawRenderNodeOp*>(op);
1003    const RenderProperties& backgroundProps = backgroundOp->renderNode->properties();
1004    renderer.translate(backgroundProps.getTranslationX(), backgroundProps.getTranslationY());
1005
1006    // If the projection receiver has an outline, we mask projected content to it
1007    // (which we know, apriori, are all tessellated paths)
1008    renderer.setProjectionPathMask(alloc, projectionReceiverOutline);
1009
1010    // draw projected nodes
1011    for (size_t i = 0; i < mProjectedNodes.size(); i++) {
1012        renderNodeOp_t* childOp = mProjectedNodes[i];
1013
1014        // matrix save, concat, and restore can be done safely without allocating operations
1015        int restoreTo = renderer.save(SaveFlags::Matrix);
1016        renderer.concatMatrix(childOp->transformFromCompositingAncestor);
1017        childOp->skipInOrderDraw = false; // this is horrible, I'm so sorry everyone
1018        handler(childOp, renderer.getSaveCount() - 1, properties().getClipToBounds());
1019        childOp->skipInOrderDraw = true;
1020        renderer.restoreToCount(restoreTo);
1021    }
1022
1023    handler(new (alloc) RestoreToCountOp(restoreTo),
1024            PROPERTY_SAVECOUNT, properties().getClipToBounds());
1025}
1026
1027/**
1028 * This function serves both defer and replay modes, and will organize the displayList's component
1029 * operations for a single frame:
1030 *
1031 * Every 'simple' state operation that affects just the matrix and alpha (or other factors of
1032 * DeferredDisplayState) may be issued directly to the renderer, but complex operations (with custom
1033 * defer logic) and operations in displayListOps are issued through the 'handler' which handles the
1034 * defer vs replay logic, per operation
1035 */
1036template <class T>
1037void RenderNode::issueOperations(OpenGLRenderer& renderer, T& handler) {
1038    if (mDisplayList->isEmpty()) {
1039        DISPLAY_LIST_LOGD("%*sEmpty display list (%p, %s)", handler.level() * 2, "",
1040                this, getName());
1041        return;
1042    }
1043
1044#if HWUI_NEW_OPS
1045    const bool drawLayer = false;
1046#else
1047    const bool drawLayer = (mLayer && (&renderer != mLayer->renderer.get()));
1048#endif
1049    // If we are updating the contents of mLayer, we don't want to apply any of
1050    // the RenderNode's properties to this issueOperations pass. Those will all
1051    // be applied when the layer is drawn, aka when this is true.
1052    const bool useViewProperties = (!mLayer || drawLayer);
1053    if (useViewProperties) {
1054        const Outline& outline = properties().getOutline();
1055        if (properties().getAlpha() <= 0
1056                || (outline.getShouldClip() && outline.isEmpty())
1057                || properties().getScaleX() == 0
1058                || properties().getScaleY() == 0) {
1059            DISPLAY_LIST_LOGD("%*sRejected display list (%p, %s)", handler.level() * 2, "",
1060                    this, getName());
1061            return;
1062        }
1063    }
1064
1065    handler.startMark(getName());
1066
1067#if DEBUG_DISPLAY_LIST
1068    const Rect& clipRect = renderer.getLocalClipBounds();
1069    DISPLAY_LIST_LOGD("%*sStart display list (%p, %s), localClipBounds: %.0f, %.0f, %.0f, %.0f",
1070            handler.level() * 2, "", this, getName(),
1071            clipRect.left, clipRect.top, clipRect.right, clipRect.bottom);
1072#endif
1073
1074    LinearAllocator& alloc = handler.allocator();
1075    int restoreTo = renderer.getSaveCount();
1076    handler(new (alloc) SaveOp(SaveFlags::MatrixClip),
1077            PROPERTY_SAVECOUNT, properties().getClipToBounds());
1078
1079    DISPLAY_LIST_LOGD("%*sSave %d %d", (handler.level() + 1) * 2, "",
1080            SaveFlags::MatrixClip, restoreTo);
1081
1082    if (useViewProperties) {
1083        setViewProperties<T>(renderer, handler);
1084    }
1085
1086#if HWUI_NEW_OPS
1087    LOG_ALWAYS_FATAL("legacy op traversal not supported");
1088#else
1089    bool quickRejected = properties().getClipToBounds()
1090            && renderer.quickRejectConservative(0, 0, properties().getWidth(), properties().getHeight());
1091    if (!quickRejected) {
1092        Matrix4 initialTransform(*(renderer.currentTransform()));
1093        renderer.setBaseTransform(initialTransform);
1094
1095        if (drawLayer) {
1096            handler(new (alloc) DrawLayerOp(mLayer),
1097                    renderer.getSaveCount() - 1, properties().getClipToBounds());
1098        } else {
1099            const int saveCountOffset = renderer.getSaveCount() - 1;
1100            const int projectionReceiveIndex = mDisplayList->projectionReceiveIndex;
1101            for (size_t chunkIndex = 0; chunkIndex < mDisplayList->getChunks().size(); chunkIndex++) {
1102                const DisplayList::Chunk& chunk = mDisplayList->getChunks()[chunkIndex];
1103
1104                std::vector<ZDrawRenderNodeOpPair> zTranslatedNodes;
1105                buildZSortedChildList(chunk, zTranslatedNodes);
1106
1107                issueOperationsOf3dChildren(ChildrenSelectMode::NegativeZChildren,
1108                        initialTransform, zTranslatedNodes, renderer, handler);
1109
1110                for (size_t opIndex = chunk.beginOpIndex; opIndex < chunk.endOpIndex; opIndex++) {
1111                    DisplayListOp *op = mDisplayList->getOps()[opIndex];
1112#if DEBUG_DISPLAY_LIST
1113                    op->output(handler.level() + 1);
1114#endif
1115                    handler(op, saveCountOffset, properties().getClipToBounds());
1116
1117                    if (CC_UNLIKELY(!mProjectedNodes.empty() && projectionReceiveIndex >= 0 &&
1118                        opIndex == static_cast<size_t>(projectionReceiveIndex))) {
1119                        issueOperationsOfProjectedChildren(renderer, handler);
1120                    }
1121                }
1122
1123                issueOperationsOf3dChildren(ChildrenSelectMode::PositiveZChildren,
1124                        initialTransform, zTranslatedNodes, renderer, handler);
1125            }
1126        }
1127    }
1128#endif
1129
1130    DISPLAY_LIST_LOGD("%*sRestoreToCount %d", (handler.level() + 1) * 2, "", restoreTo);
1131    handler(new (alloc) RestoreToCountOp(restoreTo),
1132            PROPERTY_SAVECOUNT, properties().getClipToBounds());
1133
1134    DISPLAY_LIST_LOGD("%*sDone (%p, %s)", handler.level() * 2, "", this, getName());
1135    handler.endMark();
1136}
1137
1138} /* namespace uirenderer */
1139} /* namespace android */
1140