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)
305            || CC_UNLIKELY(!isRenderable())
306            || CC_UNLIKELY(properties().getWidth() == 0)
307            || CC_UNLIKELY(properties().getHeight() == 0)) {
308        if (CC_UNLIKELY(mLayer)) {
309            destroyLayer(mLayer);
310            mLayer = nullptr;
311        }
312        return;
313    }
314
315    bool transformUpdateNeeded = false;
316    if (!mLayer) {
317        mLayer = createLayer(info.canvasContext.getRenderState(), getWidth(), getHeight());
318#if !HWUI_NEW_OPS
319        applyLayerPropertiesToLayer(info);
320#endif
321        damageSelf(info);
322        transformUpdateNeeded = true;
323    } else if (!layerMatchesWidthAndHeight(mLayer, getWidth(), getHeight())) {
324#if HWUI_NEW_OPS
325        // TODO: remove now irrelevant, currently enqueued damage (respecting damage ordering)
326        // Or, ideally, maintain damage between frames on node/layer so ordering is always correct
327        RenderState& renderState = mLayer->renderState;
328        if (properties().fitsOnLayer()) {
329            mLayer = renderState.layerPool().resize(mLayer, getWidth(), getHeight());
330        } else {
331#else
332        if (!LayerRenderer::resizeLayer(mLayer, getWidth(), getHeight())) {
333#endif
334            destroyLayer(mLayer);
335            mLayer = nullptr;
336        }
337        damageSelf(info);
338        transformUpdateNeeded = true;
339    }
340
341    SkRect dirty;
342    info.damageAccumulator->peekAtDirty(&dirty);
343
344    if (!mLayer) {
345        Caches::getInstance().dumpMemoryUsage();
346        if (info.errorHandler) {
347            std::ostringstream err;
348            err << "Unable to create layer for " << getName();
349            const int maxTextureSize = Caches::getInstance().maxTextureSize;
350            if (getWidth() > maxTextureSize || getHeight() > maxTextureSize) {
351                err << ", size " << getWidth() << "x" << getHeight()
352                        << " exceeds max size " << maxTextureSize;
353            } else {
354                err << ", see logcat for more info";
355            }
356            info.errorHandler->onError(err.str());
357        }
358        return;
359    }
360
361    if (transformUpdateNeeded && mLayer) {
362        // update the transform in window of the layer to reset its origin wrt light source position
363        Matrix4 windowTransform;
364        info.damageAccumulator->computeCurrentTransform(&windowTransform);
365        mLayer->setWindowTransform(windowTransform);
366    }
367
368#if HWUI_NEW_OPS
369    info.layerUpdateQueue->enqueueLayerWithDamage(this, dirty);
370#else
371    if (dirty.intersect(0, 0, getWidth(), getHeight())) {
372        dirty.roundOut(&dirty);
373        mLayer->updateDeferred(this, dirty.fLeft, dirty.fTop, dirty.fRight, dirty.fBottom);
374    }
375    // This is not inside the above if because we may have called
376    // updateDeferred on a previous prepare pass that didn't have a renderer
377    if (info.renderer && mLayer->deferredUpdateScheduled) {
378        info.renderer->pushLayerUpdate(mLayer);
379    }
380#endif
381
382    // There might be prefetched layers that need to be accounted for.
383    // That might be us, so tell CanvasContext that this layer is in the
384    // tree and should not be destroyed.
385    info.canvasContext.markLayerInUse(this);
386}
387
388/**
389 * Traverse down the the draw tree to prepare for a frame.
390 *
391 * MODE_FULL = UI Thread-driven (thus properties must be synced), otherwise RT driven
392 *
393 * While traversing down the tree, functorsNeedLayer flag is set to true if anything that uses the
394 * stencil buffer may be needed. Views that use a functor to draw will be forced onto a layer.
395 */
396void RenderNode::prepareTreeImpl(TreeInfo& info, bool functorsNeedLayer) {
397    info.damageAccumulator->pushTransform(this);
398
399    if (info.mode == TreeInfo::MODE_FULL) {
400        pushStagingPropertiesChanges(info);
401    }
402    uint32_t animatorDirtyMask = 0;
403    if (CC_LIKELY(info.runAnimations)) {
404        animatorDirtyMask = mAnimatorManager.animate(info);
405    }
406
407    bool willHaveFunctor = false;
408    if (info.mode == TreeInfo::MODE_FULL && mStagingDisplayList) {
409        willHaveFunctor = !mStagingDisplayList->getFunctors().empty();
410    } else if (mDisplayList) {
411        willHaveFunctor = !mDisplayList->getFunctors().empty();
412    }
413    bool childFunctorsNeedLayer = mProperties.prepareForFunctorPresence(
414            willHaveFunctor, functorsNeedLayer);
415
416    if (CC_UNLIKELY(mPositionListener.get())) {
417        mPositionListener->onPositionUpdated(*this, info);
418    }
419
420    prepareLayer(info, animatorDirtyMask);
421    if (info.mode == TreeInfo::MODE_FULL) {
422        pushStagingDisplayListChanges(info);
423    }
424    prepareSubTree(info, childFunctorsNeedLayer, mDisplayList);
425    pushLayerUpdate(info);
426
427    info.damageAccumulator->popTransform();
428}
429
430void RenderNode::syncProperties() {
431    mProperties = mStagingProperties;
432}
433
434void RenderNode::pushStagingPropertiesChanges(TreeInfo& info) {
435    // Push the animators first so that setupStartValueIfNecessary() is called
436    // before properties() is trampled by stagingProperties(), as they are
437    // required by some animators.
438    if (CC_LIKELY(info.runAnimations)) {
439        mAnimatorManager.pushStaging();
440    }
441    if (mDirtyPropertyFields) {
442        mDirtyPropertyFields = 0;
443        damageSelf(info);
444        info.damageAccumulator->popTransform();
445        syncProperties();
446#if !HWUI_NEW_OPS
447        applyLayerPropertiesToLayer(info);
448#endif
449        // We could try to be clever and only re-damage if the matrix changed.
450        // However, we don't need to worry about that. The cost of over-damaging
451        // here is only going to be a single additional map rect of this node
452        // plus a rect join(). The parent's transform (and up) will only be
453        // performed once.
454        info.damageAccumulator->pushTransform(this);
455        damageSelf(info);
456    }
457}
458
459#if !HWUI_NEW_OPS
460void RenderNode::applyLayerPropertiesToLayer(TreeInfo& info) {
461    if (CC_LIKELY(!mLayer)) return;
462
463    const LayerProperties& props = properties().layerProperties();
464    mLayer->setAlpha(props.alpha(), props.xferMode());
465    mLayer->setColorFilter(props.colorFilter());
466    mLayer->setBlend(props.needsBlending());
467}
468#endif
469
470void RenderNode::syncDisplayList(TreeInfo* info) {
471    // Make sure we inc first so that we don't fluctuate between 0 and 1,
472    // which would thrash the layer cache
473    if (mStagingDisplayList) {
474        for (auto&& child : mStagingDisplayList->getChildren()) {
475            child->renderNode->incParentRefCount();
476        }
477    }
478    deleteDisplayList(info ? info->observer : nullptr, info);
479    mDisplayList = mStagingDisplayList;
480    mStagingDisplayList = nullptr;
481    if (mDisplayList) {
482        for (auto& iter : mDisplayList->getFunctors()) {
483            (*iter.functor)(DrawGlInfo::kModeSync, nullptr);
484        }
485        for (size_t i = 0; i < mDisplayList->getPushStagingFunctors().size(); i++) {
486            (*mDisplayList->getPushStagingFunctors()[i])();
487        }
488    }
489}
490
491void RenderNode::pushStagingDisplayListChanges(TreeInfo& info) {
492    if (mNeedsDisplayListSync) {
493        mNeedsDisplayListSync = false;
494        // Damage with the old display list first then the new one to catch any
495        // changes in isRenderable or, in the future, bounds
496        damageSelf(info);
497        syncDisplayList(&info);
498        damageSelf(info);
499    }
500}
501
502void RenderNode::deleteDisplayList(TreeObserver* observer, TreeInfo* info) {
503    if (mDisplayList) {
504        for (auto&& child : mDisplayList->getChildren()) {
505            child->renderNode->decParentRefCount(observer, info);
506        }
507    }
508    delete mDisplayList;
509    mDisplayList = nullptr;
510}
511
512void RenderNode::prepareSubTree(TreeInfo& info, bool functorsNeedLayer, DisplayList* subtree) {
513    if (subtree) {
514        TextureCache& cache = Caches::getInstance().textureCache;
515        info.out.hasFunctors |= subtree->getFunctors().size();
516        for (auto&& bitmapResource : subtree->getBitmapResources()) {
517            void* ownerToken = &info.canvasContext;
518            info.prepareTextures = cache.prefetchAndMarkInUse(ownerToken, bitmapResource);
519        }
520        for (auto&& op : subtree->getChildren()) {
521            RenderNode* childNode = op->renderNode;
522#if HWUI_NEW_OPS
523            info.damageAccumulator->pushTransform(&op->localMatrix);
524            bool childFunctorsNeedLayer = functorsNeedLayer; // TODO! || op->mRecordedWithPotentialStencilClip;
525#else
526            info.damageAccumulator->pushTransform(&op->localMatrix);
527            bool childFunctorsNeedLayer = functorsNeedLayer
528                    // Recorded with non-rect clip, or canvas-rotated by parent
529                    || op->mRecordedWithPotentialStencilClip;
530#endif
531            childNode->prepareTreeImpl(info, childFunctorsNeedLayer);
532            info.damageAccumulator->popTransform();
533        }
534    }
535}
536
537void RenderNode::destroyHardwareResources(TreeObserver* observer, TreeInfo* info) {
538    if (mLayer) {
539        destroyLayer(mLayer);
540        mLayer = nullptr;
541    }
542    if (mDisplayList) {
543        for (auto&& child : mDisplayList->getChildren()) {
544            child->renderNode->destroyHardwareResources(observer, info);
545        }
546        if (mNeedsDisplayListSync) {
547            // Next prepare tree we are going to push a new display list, so we can
548            // drop our current one now
549            deleteDisplayList(observer, info);
550        }
551    }
552}
553
554void RenderNode::decParentRefCount(TreeObserver* observer, TreeInfo* info) {
555    LOG_ALWAYS_FATAL_IF(!mParentCount, "already 0!");
556    mParentCount--;
557    if (!mParentCount) {
558        if (observer) {
559            observer->onMaybeRemovedFromTree(this);
560        }
561        if (CC_UNLIKELY(mPositionListener.get())) {
562            mPositionListener->onPositionLost(*this, info);
563        }
564        // If a child of ours is being attached to our parent then this will incorrectly
565        // destroy its hardware resources. However, this situation is highly unlikely
566        // and the failure is "just" that the layer is re-created, so this should
567        // be safe enough
568        destroyHardwareResources(observer, info);
569    }
570}
571
572/*
573 * For property operations, we pass a savecount of 0, since the operations aren't part of the
574 * displaylist, and thus don't have to compensate for the record-time/playback-time discrepancy in
575 * base saveCount (i.e., how RestoreToCount uses saveCount + properties().getCount())
576 */
577#define PROPERTY_SAVECOUNT 0
578
579template <class T>
580void RenderNode::setViewProperties(OpenGLRenderer& renderer, T& handler) {
581#if DEBUG_DISPLAY_LIST
582    properties().debugOutputProperties(handler.level() + 1);
583#endif
584    if (properties().getLeft() != 0 || properties().getTop() != 0) {
585        renderer.translate(properties().getLeft(), properties().getTop());
586    }
587    if (properties().getStaticMatrix()) {
588        renderer.concatMatrix(*properties().getStaticMatrix());
589    } else if (properties().getAnimationMatrix()) {
590        renderer.concatMatrix(*properties().getAnimationMatrix());
591    }
592    if (properties().hasTransformMatrix()) {
593        if (properties().isTransformTranslateOnly()) {
594            renderer.translate(properties().getTranslationX(), properties().getTranslationY());
595        } else {
596            renderer.concatMatrix(*properties().getTransformMatrix());
597        }
598    }
599    const bool isLayer = properties().effectiveLayerType() != LayerType::None;
600    int clipFlags = properties().getClippingFlags();
601    if (properties().getAlpha() < 1) {
602        if (isLayer) {
603            clipFlags &= ~CLIP_TO_BOUNDS; // bounds clipping done by layer
604        }
605        if (CC_LIKELY(isLayer || !properties().getHasOverlappingRendering())) {
606            // simply scale rendering content's alpha
607            renderer.scaleAlpha(properties().getAlpha());
608        } else {
609            // savelayer needed to create an offscreen buffer
610            Rect layerBounds(0, 0, getWidth(), getHeight());
611            if (clipFlags) {
612                properties().getClippingRectForFlags(clipFlags, &layerBounds);
613                clipFlags = 0; // all clipping done by savelayer
614            }
615            SaveLayerOp* op = new (handler.allocator()) SaveLayerOp(
616                    layerBounds.left, layerBounds.top,
617                    layerBounds.right, layerBounds.bottom,
618                    (int) (properties().getAlpha() * 255),
619                    SaveFlags::HasAlphaLayer | SaveFlags::ClipToLayer);
620            handler(op, PROPERTY_SAVECOUNT, properties().getClipToBounds());
621        }
622
623        if (CC_UNLIKELY(ATRACE_ENABLED() && properties().promotedToLayer())) {
624            // pretend alpha always causes savelayer to warn about
625            // performance problem affecting old versions
626            ATRACE_FORMAT("%s alpha caused saveLayer %dx%d", getName(),
627                    static_cast<int>(getWidth()),
628                    static_cast<int>(getHeight()));
629        }
630    }
631    if (clipFlags) {
632        Rect clipRect;
633        properties().getClippingRectForFlags(clipFlags, &clipRect);
634        ClipRectOp* op = new (handler.allocator()) ClipRectOp(
635                clipRect.left, clipRect.top, clipRect.right, clipRect.bottom,
636                SkRegion::kIntersect_Op);
637        handler(op, PROPERTY_SAVECOUNT, properties().getClipToBounds());
638    }
639
640    // TODO: support nesting round rect clips
641    if (mProperties.getRevealClip().willClip()) {
642        Rect bounds;
643        mProperties.getRevealClip().getBounds(&bounds);
644        renderer.setClippingRoundRect(handler.allocator(), bounds, mProperties.getRevealClip().getRadius());
645    } else if (mProperties.getOutline().willClip()) {
646        renderer.setClippingOutline(handler.allocator(), &(mProperties.getOutline()));
647    }
648}
649
650/**
651 * Apply property-based transformations to input matrix
652 *
653 * If true3dTransform is set to true, the transform applied to the input matrix will use true 4x4
654 * matrix computation instead of the Skia 3x3 matrix + camera hackery.
655 */
656void RenderNode::applyViewPropertyTransforms(mat4& matrix, bool true3dTransform) const {
657    if (properties().getLeft() != 0 || properties().getTop() != 0) {
658        matrix.translate(properties().getLeft(), properties().getTop());
659    }
660    if (properties().getStaticMatrix()) {
661        mat4 stat(*properties().getStaticMatrix());
662        matrix.multiply(stat);
663    } else if (properties().getAnimationMatrix()) {
664        mat4 anim(*properties().getAnimationMatrix());
665        matrix.multiply(anim);
666    }
667
668    bool applyTranslationZ = true3dTransform && !MathUtils::isZero(properties().getZ());
669    if (properties().hasTransformMatrix() || applyTranslationZ) {
670        if (properties().isTransformTranslateOnly()) {
671            matrix.translate(properties().getTranslationX(), properties().getTranslationY(),
672                    true3dTransform ? properties().getZ() : 0.0f);
673        } else {
674            if (!true3dTransform) {
675                matrix.multiply(*properties().getTransformMatrix());
676            } else {
677                mat4 true3dMat;
678                true3dMat.loadTranslate(
679                        properties().getPivotX() + properties().getTranslationX(),
680                        properties().getPivotY() + properties().getTranslationY(),
681                        properties().getZ());
682                true3dMat.rotate(properties().getRotationX(), 1, 0, 0);
683                true3dMat.rotate(properties().getRotationY(), 0, 1, 0);
684                true3dMat.rotate(properties().getRotation(), 0, 0, 1);
685                true3dMat.scale(properties().getScaleX(), properties().getScaleY(), 1);
686                true3dMat.translate(-properties().getPivotX(), -properties().getPivotY());
687
688                matrix.multiply(true3dMat);
689            }
690        }
691    }
692}
693
694/**
695 * Organizes the DisplayList hierarchy to prepare for background projection reordering.
696 *
697 * This should be called before a call to defer() or drawDisplayList()
698 *
699 * Each DisplayList that serves as a 3d root builds its list of composited children,
700 * which are flagged to not draw in the standard draw loop.
701 */
702void RenderNode::computeOrdering() {
703    ATRACE_CALL();
704    mProjectedNodes.clear();
705
706    // TODO: create temporary DDLOp and call computeOrderingImpl on top DisplayList so that
707    // transform properties are applied correctly to top level children
708    if (mDisplayList == nullptr) return;
709    for (unsigned int i = 0; i < mDisplayList->getChildren().size(); i++) {
710        renderNodeOp_t* childOp = mDisplayList->getChildren()[i];
711        childOp->renderNode->computeOrderingImpl(childOp, &mProjectedNodes, &mat4::identity());
712    }
713}
714
715void RenderNode::computeOrderingImpl(
716        renderNodeOp_t* opState,
717        std::vector<renderNodeOp_t*>* compositedChildrenOfProjectionSurface,
718        const mat4* transformFromProjectionSurface) {
719    mProjectedNodes.clear();
720    if (mDisplayList == nullptr || mDisplayList->isEmpty()) return;
721
722    // TODO: should avoid this calculation in most cases
723    // TODO: just calculate single matrix, down to all leaf composited elements
724    Matrix4 localTransformFromProjectionSurface(*transformFromProjectionSurface);
725    localTransformFromProjectionSurface.multiply(opState->localMatrix);
726
727    if (properties().getProjectBackwards()) {
728        // composited projectee, flag for out of order draw, save matrix, and store in proj surface
729        opState->skipInOrderDraw = true;
730        opState->transformFromCompositingAncestor = localTransformFromProjectionSurface;
731        compositedChildrenOfProjectionSurface->push_back(opState);
732    } else {
733        // standard in order draw
734        opState->skipInOrderDraw = false;
735    }
736
737    if (mDisplayList->getChildren().size() > 0) {
738        const bool isProjectionReceiver = mDisplayList->projectionReceiveIndex >= 0;
739        bool haveAppliedPropertiesToProjection = false;
740        for (unsigned int i = 0; i < mDisplayList->getChildren().size(); i++) {
741            renderNodeOp_t* childOp = mDisplayList->getChildren()[i];
742            RenderNode* child = childOp->renderNode;
743
744            std::vector<renderNodeOp_t*>* projectionChildren = nullptr;
745            const mat4* projectionTransform = nullptr;
746            if (isProjectionReceiver && !child->properties().getProjectBackwards()) {
747                // if receiving projections, collect projecting descendant
748
749                // Note that if a direct descendant is projecting backwards, we pass its
750                // grandparent projection collection, since it shouldn't project onto its
751                // parent, where it will already be drawing.
752                projectionChildren = &mProjectedNodes;
753                projectionTransform = &mat4::identity();
754            } else {
755                if (!haveAppliedPropertiesToProjection) {
756                    applyViewPropertyTransforms(localTransformFromProjectionSurface);
757                    haveAppliedPropertiesToProjection = true;
758                }
759                projectionChildren = compositedChildrenOfProjectionSurface;
760                projectionTransform = &localTransformFromProjectionSurface;
761            }
762            child->computeOrderingImpl(childOp, projectionChildren, projectionTransform);
763        }
764    }
765}
766
767class DeferOperationHandler {
768public:
769    DeferOperationHandler(DeferStateStruct& deferStruct, int level)
770        : mDeferStruct(deferStruct), mLevel(level) {}
771    inline void operator()(DisplayListOp* operation, int saveCount, bool clipToBounds) {
772        operation->defer(mDeferStruct, saveCount, mLevel, clipToBounds);
773    }
774    inline LinearAllocator& allocator() { return *(mDeferStruct.mAllocator); }
775    inline void startMark(const char* name) {} // do nothing
776    inline void endMark() {}
777    inline int level() { return mLevel; }
778    inline int replayFlags() { return mDeferStruct.mReplayFlags; }
779    inline SkPath* allocPathForFrame() { return mDeferStruct.allocPathForFrame(); }
780
781private:
782    DeferStateStruct& mDeferStruct;
783    const int mLevel;
784};
785
786void RenderNode::defer(DeferStateStruct& deferStruct, const int level) {
787    DeferOperationHandler handler(deferStruct, level);
788    issueOperations<DeferOperationHandler>(deferStruct.mRenderer, handler);
789}
790
791class ReplayOperationHandler {
792public:
793    ReplayOperationHandler(ReplayStateStruct& replayStruct, int level)
794        : mReplayStruct(replayStruct), mLevel(level) {}
795    inline void operator()(DisplayListOp* operation, int saveCount, bool clipToBounds) {
796#if DEBUG_DISPLAY_LIST_OPS_AS_EVENTS
797        mReplayStruct.mRenderer.eventMark(operation->name());
798#endif
799        operation->replay(mReplayStruct, saveCount, mLevel, clipToBounds);
800    }
801    inline LinearAllocator& allocator() { return *(mReplayStruct.mAllocator); }
802    inline void startMark(const char* name) {
803        mReplayStruct.mRenderer.startMark(name);
804    }
805    inline void endMark() {
806        mReplayStruct.mRenderer.endMark();
807    }
808    inline int level() { return mLevel; }
809    inline int replayFlags() { return mReplayStruct.mReplayFlags; }
810    inline SkPath* allocPathForFrame() { return mReplayStruct.allocPathForFrame(); }
811
812private:
813    ReplayStateStruct& mReplayStruct;
814    const int mLevel;
815};
816
817void RenderNode::replay(ReplayStateStruct& replayStruct, const int level) {
818    ReplayOperationHandler handler(replayStruct, level);
819    issueOperations<ReplayOperationHandler>(replayStruct.mRenderer, handler);
820}
821
822void RenderNode::buildZSortedChildList(const DisplayList::Chunk& chunk,
823        std::vector<ZDrawRenderNodeOpPair>& zTranslatedNodes) {
824#if !HWUI_NEW_OPS
825    if (chunk.beginChildIndex == chunk.endChildIndex) return;
826
827    for (unsigned int i = chunk.beginChildIndex; i < chunk.endChildIndex; i++) {
828        DrawRenderNodeOp* childOp = mDisplayList->getChildren()[i];
829        RenderNode* child = childOp->renderNode;
830        float childZ = child->properties().getZ();
831
832        if (!MathUtils::isZero(childZ) && chunk.reorderChildren) {
833            zTranslatedNodes.push_back(ZDrawRenderNodeOpPair(childZ, childOp));
834            childOp->skipInOrderDraw = true;
835        } else if (!child->properties().getProjectBackwards()) {
836            // regular, in order drawing DisplayList
837            childOp->skipInOrderDraw = false;
838        }
839    }
840
841    // Z sort any 3d children (stable-ness makes z compare fall back to standard drawing order)
842    std::stable_sort(zTranslatedNodes.begin(), zTranslatedNodes.end());
843#endif
844}
845
846template <class T>
847void RenderNode::issueDrawShadowOperation(const Matrix4& transformFromParent, T& handler) {
848    if (properties().getAlpha() <= 0.0f
849            || properties().getOutline().getAlpha() <= 0.0f
850            || !properties().getOutline().getPath()
851            || properties().getScaleX() == 0
852            || properties().getScaleY() == 0) {
853        // no shadow to draw
854        return;
855    }
856
857    mat4 shadowMatrixXY(transformFromParent);
858    applyViewPropertyTransforms(shadowMatrixXY);
859
860    // Z matrix needs actual 3d transformation, so mapped z values will be correct
861    mat4 shadowMatrixZ(transformFromParent);
862    applyViewPropertyTransforms(shadowMatrixZ, true);
863
864    const SkPath* casterOutlinePath = properties().getOutline().getPath();
865    const SkPath* revealClipPath = properties().getRevealClip().getPath();
866    if (revealClipPath && revealClipPath->isEmpty()) return;
867
868    float casterAlpha = properties().getAlpha() * properties().getOutline().getAlpha();
869
870
871    // holds temporary SkPath to store the result of intersections
872    SkPath* frameAllocatedPath = nullptr;
873    const SkPath* outlinePath = casterOutlinePath;
874
875    // intersect the outline with the reveal clip, if present
876    if (revealClipPath) {
877        frameAllocatedPath = handler.allocPathForFrame();
878
879        Op(*outlinePath, *revealClipPath, kIntersect_SkPathOp, frameAllocatedPath);
880        outlinePath = frameAllocatedPath;
881    }
882
883    // intersect the outline with the clipBounds, if present
884    if (properties().getClippingFlags() & CLIP_TO_CLIP_BOUNDS) {
885        if (!frameAllocatedPath) {
886            frameAllocatedPath = handler.allocPathForFrame();
887        }
888
889        Rect clipBounds;
890        properties().getClippingRectForFlags(CLIP_TO_CLIP_BOUNDS, &clipBounds);
891        SkPath clipBoundsPath;
892        clipBoundsPath.addRect(clipBounds.left, clipBounds.top,
893                clipBounds.right, clipBounds.bottom);
894
895        Op(*outlinePath, clipBoundsPath, kIntersect_SkPathOp, frameAllocatedPath);
896        outlinePath = frameAllocatedPath;
897    }
898
899    DisplayListOp* shadowOp  = new (handler.allocator()) DrawShadowOp(
900            shadowMatrixXY, shadowMatrixZ, casterAlpha, outlinePath);
901    handler(shadowOp, PROPERTY_SAVECOUNT, properties().getClipToBounds());
902}
903
904#define SHADOW_DELTA 0.1f
905
906template <class T>
907void RenderNode::issueOperationsOf3dChildren(ChildrenSelectMode mode,
908        const Matrix4& initialTransform, const std::vector<ZDrawRenderNodeOpPair>& zTranslatedNodes,
909        OpenGLRenderer& renderer, T& handler) {
910    const int size = zTranslatedNodes.size();
911    if (size == 0
912            || (mode == ChildrenSelectMode::NegativeZChildren && zTranslatedNodes[0].key > 0.0f)
913            || (mode == ChildrenSelectMode::PositiveZChildren && zTranslatedNodes[size - 1].key < 0.0f)) {
914        // no 3d children to draw
915        return;
916    }
917
918    // Apply the base transform of the parent of the 3d children. This isolates
919    // 3d children of the current chunk from transformations made in previous chunks.
920    int rootRestoreTo = renderer.save(SaveFlags::Matrix);
921    renderer.setGlobalMatrix(initialTransform);
922
923    /**
924     * Draw shadows and (potential) casters mostly in order, but allow the shadows of casters
925     * with very similar Z heights to draw together.
926     *
927     * This way, if Views A & B have the same Z height and are both casting shadows, the shadows are
928     * underneath both, and neither's shadow is drawn on top of the other.
929     */
930    const size_t nonNegativeIndex = findNonNegativeIndex(zTranslatedNodes);
931    size_t drawIndex, shadowIndex, endIndex;
932    if (mode == ChildrenSelectMode::NegativeZChildren) {
933        drawIndex = 0;
934        endIndex = nonNegativeIndex;
935        shadowIndex = endIndex; // draw no shadows
936    } else {
937        drawIndex = nonNegativeIndex;
938        endIndex = size;
939        shadowIndex = drawIndex; // potentially draw shadow for each pos Z child
940    }
941
942    DISPLAY_LIST_LOGD("%*s%d %s 3d children:", (handler.level() + 1) * 2, "",
943            endIndex - drawIndex, mode == kNegativeZChildren ? "negative" : "positive");
944
945    float lastCasterZ = 0.0f;
946    while (shadowIndex < endIndex || drawIndex < endIndex) {
947        if (shadowIndex < endIndex) {
948            DrawRenderNodeOp* casterOp = zTranslatedNodes[shadowIndex].value;
949            RenderNode* caster = casterOp->renderNode;
950            const float casterZ = zTranslatedNodes[shadowIndex].key;
951            // attempt to render the shadow if the caster about to be drawn is its caster,
952            // OR if its caster's Z value is similar to the previous potential caster
953            if (shadowIndex == drawIndex || casterZ - lastCasterZ < SHADOW_DELTA) {
954                caster->issueDrawShadowOperation(casterOp->localMatrix, handler);
955
956                lastCasterZ = casterZ; // must do this even if current caster not casting a shadow
957                shadowIndex++;
958                continue;
959            }
960        }
961
962        // only the actual child DL draw needs to be in save/restore,
963        // since it modifies the renderer's matrix
964        int restoreTo = renderer.save(SaveFlags::Matrix);
965
966        DrawRenderNodeOp* childOp = zTranslatedNodes[drawIndex].value;
967
968        renderer.concatMatrix(childOp->localMatrix);
969        childOp->skipInOrderDraw = false; // this is horrible, I'm so sorry everyone
970        handler(childOp, renderer.getSaveCount() - 1, properties().getClipToBounds());
971        childOp->skipInOrderDraw = true;
972
973        renderer.restoreToCount(restoreTo);
974        drawIndex++;
975    }
976    renderer.restoreToCount(rootRestoreTo);
977}
978
979template <class T>
980void RenderNode::issueOperationsOfProjectedChildren(OpenGLRenderer& renderer, T& handler) {
981    DISPLAY_LIST_LOGD("%*s%d projected children:", (handler.level() + 1) * 2, "", mProjectedNodes.size());
982    const SkPath* projectionReceiverOutline = properties().getOutline().getPath();
983    int restoreTo = renderer.getSaveCount();
984
985    LinearAllocator& alloc = handler.allocator();
986    handler(new (alloc) SaveOp(SaveFlags::MatrixClip),
987            PROPERTY_SAVECOUNT, properties().getClipToBounds());
988
989    // Transform renderer to match background we're projecting onto
990    // (by offsetting canvas by translationX/Y of background rendernode, since only those are set)
991    const DisplayListOp* op =
992#if HWUI_NEW_OPS
993            nullptr;
994    LOG_ALWAYS_FATAL("unsupported");
995#else
996            (mDisplayList->getOps()[mDisplayList->projectionReceiveIndex]);
997#endif
998    const DrawRenderNodeOp* backgroundOp = reinterpret_cast<const DrawRenderNodeOp*>(op);
999    const RenderProperties& backgroundProps = backgroundOp->renderNode->properties();
1000    renderer.translate(backgroundProps.getTranslationX(), backgroundProps.getTranslationY());
1001
1002    // If the projection receiver has an outline, we mask projected content to it
1003    // (which we know, apriori, are all tessellated paths)
1004    renderer.setProjectionPathMask(alloc, projectionReceiverOutline);
1005
1006    // draw projected nodes
1007    for (size_t i = 0; i < mProjectedNodes.size(); i++) {
1008        renderNodeOp_t* childOp = mProjectedNodes[i];
1009
1010        // matrix save, concat, and restore can be done safely without allocating operations
1011        int restoreTo = renderer.save(SaveFlags::Matrix);
1012        renderer.concatMatrix(childOp->transformFromCompositingAncestor);
1013        childOp->skipInOrderDraw = false; // this is horrible, I'm so sorry everyone
1014        handler(childOp, renderer.getSaveCount() - 1, properties().getClipToBounds());
1015        childOp->skipInOrderDraw = true;
1016        renderer.restoreToCount(restoreTo);
1017    }
1018
1019    handler(new (alloc) RestoreToCountOp(restoreTo),
1020            PROPERTY_SAVECOUNT, properties().getClipToBounds());
1021}
1022
1023/**
1024 * This function serves both defer and replay modes, and will organize the displayList's component
1025 * operations for a single frame:
1026 *
1027 * Every 'simple' state operation that affects just the matrix and alpha (or other factors of
1028 * DeferredDisplayState) may be issued directly to the renderer, but complex operations (with custom
1029 * defer logic) and operations in displayListOps are issued through the 'handler' which handles the
1030 * defer vs replay logic, per operation
1031 */
1032template <class T>
1033void RenderNode::issueOperations(OpenGLRenderer& renderer, T& handler) {
1034    if (mDisplayList->isEmpty()) {
1035        DISPLAY_LIST_LOGD("%*sEmpty display list (%p, %s)", handler.level() * 2, "",
1036                this, getName());
1037        return;
1038    }
1039
1040#if HWUI_NEW_OPS
1041    const bool drawLayer = false;
1042#else
1043    const bool drawLayer = (mLayer && (&renderer != mLayer->renderer.get()));
1044#endif
1045    // If we are updating the contents of mLayer, we don't want to apply any of
1046    // the RenderNode's properties to this issueOperations pass. Those will all
1047    // be applied when the layer is drawn, aka when this is true.
1048    const bool useViewProperties = (!mLayer || drawLayer);
1049    if (useViewProperties) {
1050        const Outline& outline = properties().getOutline();
1051        if (properties().getAlpha() <= 0
1052                || (outline.getShouldClip() && outline.isEmpty())
1053                || properties().getScaleX() == 0
1054                || properties().getScaleY() == 0) {
1055            DISPLAY_LIST_LOGD("%*sRejected display list (%p, %s)", handler.level() * 2, "",
1056                    this, getName());
1057            return;
1058        }
1059    }
1060
1061    handler.startMark(getName());
1062
1063#if DEBUG_DISPLAY_LIST
1064    const Rect& clipRect = renderer.getLocalClipBounds();
1065    DISPLAY_LIST_LOGD("%*sStart display list (%p, %s), localClipBounds: %.0f, %.0f, %.0f, %.0f",
1066            handler.level() * 2, "", this, getName(),
1067            clipRect.left, clipRect.top, clipRect.right, clipRect.bottom);
1068#endif
1069
1070    LinearAllocator& alloc = handler.allocator();
1071    int restoreTo = renderer.getSaveCount();
1072    handler(new (alloc) SaveOp(SaveFlags::MatrixClip),
1073            PROPERTY_SAVECOUNT, properties().getClipToBounds());
1074
1075    DISPLAY_LIST_LOGD("%*sSave %d %d", (handler.level() + 1) * 2, "",
1076            SaveFlags::MatrixClip, restoreTo);
1077
1078    if (useViewProperties) {
1079        setViewProperties<T>(renderer, handler);
1080    }
1081
1082#if HWUI_NEW_OPS
1083    LOG_ALWAYS_FATAL("legacy op traversal not supported");
1084#else
1085    bool quickRejected = properties().getClipToBounds()
1086            && renderer.quickRejectConservative(0, 0, properties().getWidth(), properties().getHeight());
1087    if (!quickRejected) {
1088        Matrix4 initialTransform(*(renderer.currentTransform()));
1089        renderer.setBaseTransform(initialTransform);
1090
1091        if (drawLayer) {
1092            handler(new (alloc) DrawLayerOp(mLayer),
1093                    renderer.getSaveCount() - 1, properties().getClipToBounds());
1094        } else {
1095            const int saveCountOffset = renderer.getSaveCount() - 1;
1096            const int projectionReceiveIndex = mDisplayList->projectionReceiveIndex;
1097            for (size_t chunkIndex = 0; chunkIndex < mDisplayList->getChunks().size(); chunkIndex++) {
1098                const DisplayList::Chunk& chunk = mDisplayList->getChunks()[chunkIndex];
1099
1100                std::vector<ZDrawRenderNodeOpPair> zTranslatedNodes;
1101                buildZSortedChildList(chunk, zTranslatedNodes);
1102
1103                issueOperationsOf3dChildren(ChildrenSelectMode::NegativeZChildren,
1104                        initialTransform, zTranslatedNodes, renderer, handler);
1105
1106                for (size_t opIndex = chunk.beginOpIndex; opIndex < chunk.endOpIndex; opIndex++) {
1107                    DisplayListOp *op = mDisplayList->getOps()[opIndex];
1108#if DEBUG_DISPLAY_LIST
1109                    op->output(handler.level() + 1);
1110#endif
1111                    handler(op, saveCountOffset, properties().getClipToBounds());
1112
1113                    if (CC_UNLIKELY(!mProjectedNodes.empty() && projectionReceiveIndex >= 0 &&
1114                        opIndex == static_cast<size_t>(projectionReceiveIndex))) {
1115                        issueOperationsOfProjectedChildren(renderer, handler);
1116                    }
1117                }
1118
1119                issueOperationsOf3dChildren(ChildrenSelectMode::PositiveZChildren,
1120                        initialTransform, zTranslatedNodes, renderer, handler);
1121            }
1122        }
1123    }
1124#endif
1125
1126    DISPLAY_LIST_LOGD("%*sRestoreToCount %d", (handler.level() + 1) * 2, "", restoreTo);
1127    handler(new (alloc) RestoreToCountOp(restoreTo),
1128            PROPERTY_SAVECOUNT, properties().getClipToBounds());
1129
1130    DISPLAY_LIST_LOGD("%*sDone (%p, %s)", handler.level() * 2, "", this, getName());
1131    handler.endMark();
1132}
1133
1134} /* namespace uirenderer */
1135} /* namespace android */
1136