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