RenderNode.cpp revision 590b8d3601a518f6c3e00a28e88add36142bde22
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#define ATRACE_TAG ATRACE_TAG_VIEW
18#define LOG_TAG "OpenGLRenderer"
19
20#include "RenderNode.h"
21
22#include <algorithm>
23#include <string>
24
25#include <SkCanvas.h>
26#include <algorithm>
27
28#include <utils/Trace.h>
29
30#include "DamageAccumulator.h"
31#include "Debug.h"
32#include "DisplayListOp.h"
33#include "DisplayListLogBuffer.h"
34#include "LayerRenderer.h"
35#include "OpenGLRenderer.h"
36#include "utils/MathUtils.h"
37
38namespace android {
39namespace uirenderer {
40
41void RenderNode::outputLogBuffer(int fd) {
42    DisplayListLogBuffer& logBuffer = DisplayListLogBuffer::getInstance();
43    if (logBuffer.isEmpty()) {
44        return;
45    }
46
47    FILE *file = fdopen(fd, "a");
48
49    fprintf(file, "\nRecent DisplayList operations\n");
50    logBuffer.outputCommands(file);
51
52    String8 cachesLog;
53    Caches::getInstance().dumpMemoryUsage(cachesLog);
54    fprintf(file, "\nCaches:\n%s", cachesLog.string());
55    fprintf(file, "\n");
56
57    fflush(file);
58}
59
60RenderNode::RenderNode()
61        : mDirtyPropertyFields(0)
62        , mNeedsDisplayListDataSync(false)
63        , mDisplayListData(0)
64        , mStagingDisplayListData(0)
65        , mAnimatorManager(*this)
66        , mLayer(0)
67        , mParentCount(0) {
68}
69
70RenderNode::~RenderNode() {
71    deleteDisplayListData();
72    delete mStagingDisplayListData;
73    LayerRenderer::destroyLayerDeferred(mLayer);
74}
75
76void RenderNode::setStagingDisplayList(DisplayListData* data) {
77    mNeedsDisplayListDataSync = true;
78    delete mStagingDisplayListData;
79    mStagingDisplayListData = data;
80    if (mStagingDisplayListData) {
81        Caches::getInstance().registerFunctors(mStagingDisplayListData->functors.size());
82    }
83}
84
85/**
86 * This function is a simplified version of replay(), where we simply retrieve and log the
87 * display list. This function should remain in sync with the replay() function.
88 */
89void RenderNode::output(uint32_t level) {
90    ALOGD("%*sStart display list (%p, %s, render=%d)", (level - 1) * 2, "", this,
91            getName(), isRenderable());
92    ALOGD("%*s%s %d", level * 2, "", "Save",
93            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
94
95    properties().debugOutputProperties(level);
96    int flags = DisplayListOp::kOpLogFlag_Recurse;
97    for (unsigned int i = 0; i < mDisplayListData->displayListOps.size(); i++) {
98        mDisplayListData->displayListOps[i]->output(level, flags);
99    }
100
101    ALOGD("%*sDone (%p, %s)", (level - 1) * 2, "", this, getName());
102}
103
104int RenderNode::getDebugSize() {
105    int size = sizeof(RenderNode);
106    if (mStagingDisplayListData) {
107        size += mStagingDisplayListData->allocator.usedSize();
108    }
109    if (mDisplayListData && mDisplayListData != mStagingDisplayListData) {
110        size += mDisplayListData->allocator.usedSize();
111    }
112    return size;
113}
114
115void RenderNode::prepareTree(TreeInfo& info) {
116    ATRACE_CALL();
117
118    prepareTreeImpl(info);
119}
120
121void RenderNode::addAnimator(const sp<BaseRenderNodeAnimator>& animator) {
122    mAnimatorManager.addAnimator(animator);
123}
124
125void RenderNode::damageSelf(TreeInfo& info) {
126    if (isRenderable()) {
127        if (properties().getClipDamageToBounds()) {
128            info.damageAccumulator->dirty(0, 0, properties().getWidth(), properties().getHeight());
129        } else {
130            // Hope this is big enough?
131            // TODO: Get this from the display list ops or something
132            info.damageAccumulator->dirty(INT_MIN, INT_MIN, INT_MAX, INT_MAX);
133        }
134    }
135}
136
137void RenderNode::prepareLayer(TreeInfo& info) {
138    LayerType layerType = properties().layerProperties().type();
139    if (CC_UNLIKELY(layerType == kLayerTypeRenderLayer)) {
140        // We push a null transform here as we don't care what the existing dirty
141        // area is, only what our display list dirty is as well as our children's
142        // dirty area
143        info.damageAccumulator->pushNullTransform();
144    }
145}
146
147void RenderNode::pushLayerUpdate(TreeInfo& info) {
148    LayerType layerType = properties().layerProperties().type();
149    // If we are not a layer OR we cannot be rendered (eg, view was detached)
150    // we need to destroy any Layers we may have had previously
151    if (CC_LIKELY(layerType != kLayerTypeRenderLayer) || CC_UNLIKELY(!isRenderable())) {
152        if (layerType == kLayerTypeRenderLayer) {
153            info.damageAccumulator->popTransform();
154        }
155        if (CC_UNLIKELY(mLayer)) {
156            LayerRenderer::destroyLayer(mLayer);
157            mLayer = NULL;
158        }
159        return;
160    }
161
162    if (!mLayer) {
163        mLayer = LayerRenderer::createRenderLayer(info.renderState, getWidth(), getHeight());
164        applyLayerPropertiesToLayer(info);
165        damageSelf(info);
166    } else if (mLayer->layer.getWidth() != getWidth() || mLayer->layer.getHeight() != getHeight()) {
167        if (!LayerRenderer::resizeLayer(mLayer, getWidth(), getHeight())) {
168            LayerRenderer::destroyLayer(mLayer);
169            mLayer = 0;
170        }
171        damageSelf(info);
172    }
173
174    SkRect dirty;
175    info.damageAccumulator->peekAtDirty(&dirty);
176    info.damageAccumulator->popTransform();
177
178    if (!mLayer) {
179        if (info.errorHandler) {
180            std::string msg = "Unable to create layer for ";
181            msg += getName();
182            info.errorHandler->onError(msg);
183        }
184        return;
185    }
186
187    if (!dirty.isEmpty()) {
188        mLayer->updateDeferred(this, dirty.fLeft, dirty.fTop, dirty.fRight, dirty.fBottom);
189    }
190    // This is not inside the above if because we may have called
191    // updateDeferred on a previous prepare pass that didn't have a renderer
192    if (info.renderer && mLayer->deferredUpdateScheduled) {
193        info.renderer->pushLayerUpdate(mLayer);
194    }
195}
196
197void RenderNode::prepareTreeImpl(TreeInfo& info) {
198    info.damageAccumulator->pushTransform(this);
199
200    if (info.mode == TreeInfo::MODE_FULL) {
201        pushStagingPropertiesChanges(info);
202    }
203    mAnimatorManager.animate(info);
204    prepareLayer(info);
205    if (info.mode == TreeInfo::MODE_FULL) {
206        pushStagingDisplayListChanges(info);
207    }
208    prepareSubTree(info, mDisplayListData);
209    pushLayerUpdate(info);
210
211    info.damageAccumulator->popTransform();
212}
213
214void RenderNode::pushStagingPropertiesChanges(TreeInfo& info) {
215    // Push the animators first so that setupStartValueIfNecessary() is called
216    // before properties() is trampled by stagingProperties(), as they are
217    // required by some animators.
218    mAnimatorManager.pushStaging(info);
219    if (mDirtyPropertyFields) {
220        mDirtyPropertyFields = 0;
221        damageSelf(info);
222        info.damageAccumulator->popTransform();
223        mProperties = mStagingProperties;
224        applyLayerPropertiesToLayer(info);
225        // We could try to be clever and only re-damage if the matrix changed.
226        // However, we don't need to worry about that. The cost of over-damaging
227        // here is only going to be a single additional map rect of this node
228        // plus a rect join(). The parent's transform (and up) will only be
229        // performed once.
230        info.damageAccumulator->pushTransform(this);
231        damageSelf(info);
232    }
233}
234
235void RenderNode::applyLayerPropertiesToLayer(TreeInfo& info) {
236    if (CC_LIKELY(!mLayer)) return;
237
238    const LayerProperties& props = properties().layerProperties();
239    mLayer->setAlpha(props.alpha(), props.xferMode());
240    mLayer->setColorFilter(props.colorFilter());
241    mLayer->setBlend(props.needsBlending());
242}
243
244void RenderNode::pushStagingDisplayListChanges(TreeInfo& info) {
245    if (mNeedsDisplayListDataSync) {
246        mNeedsDisplayListDataSync = false;
247        // Make sure we inc first so that we don't fluctuate between 0 and 1,
248        // which would thrash the layer cache
249        if (mStagingDisplayListData) {
250            for (size_t i = 0; i < mStagingDisplayListData->children().size(); i++) {
251                mStagingDisplayListData->children()[i]->mRenderNode->incParentRefCount();
252            }
253        }
254        deleteDisplayListData();
255        mDisplayListData = mStagingDisplayListData;
256        mStagingDisplayListData = NULL;
257        if (mDisplayListData) {
258            for (size_t i = 0; i < mDisplayListData->functors.size(); i++) {
259                (*mDisplayListData->functors[i])(DrawGlInfo::kModeSync, NULL);
260            }
261        }
262        damageSelf(info);
263    }
264}
265
266void RenderNode::deleteDisplayListData() {
267    if (mDisplayListData) {
268        for (size_t i = 0; i < mDisplayListData->children().size(); i++) {
269            mDisplayListData->children()[i]->mRenderNode->decParentRefCount();
270        }
271    }
272    delete mDisplayListData;
273    mDisplayListData = NULL;
274}
275
276void RenderNode::prepareSubTree(TreeInfo& info, DisplayListData* subtree) {
277    if (subtree) {
278        TextureCache& cache = Caches::getInstance().textureCache;
279        info.out.hasFunctors |= subtree->functors.size();
280        // TODO: Fix ownedBitmapResources to not require disabling prepareTextures
281        // and thus falling out of async drawing path.
282        if (subtree->ownedBitmapResources.size()) {
283            info.prepareTextures = false;
284        }
285        for (size_t i = 0; info.prepareTextures && i < subtree->bitmapResources.size(); i++) {
286            info.prepareTextures = cache.prefetchAndMarkInUse(subtree->bitmapResources[i]);
287        }
288        for (size_t i = 0; i < subtree->children().size(); i++) {
289            DrawRenderNodeOp* op = subtree->children()[i];
290            RenderNode* childNode = op->mRenderNode;
291            info.damageAccumulator->pushTransform(&op->mTransformFromParent);
292            childNode->prepareTreeImpl(info);
293            info.damageAccumulator->popTransform();
294        }
295    }
296}
297
298void RenderNode::destroyHardwareResources() {
299    if (mLayer) {
300        LayerRenderer::destroyLayer(mLayer);
301        mLayer = NULL;
302    }
303    if (mDisplayListData) {
304        for (size_t i = 0; i < mDisplayListData->children().size(); i++) {
305            mDisplayListData->children()[i]->mRenderNode->destroyHardwareResources();
306        }
307        if (mNeedsDisplayListDataSync) {
308            // Next prepare tree we are going to push a new display list, so we can
309            // drop our current one now
310            deleteDisplayListData();
311        }
312    }
313}
314
315void RenderNode::decParentRefCount() {
316    LOG_ALWAYS_FATAL_IF(!mParentCount, "already 0!");
317    mParentCount--;
318    if (!mParentCount) {
319        // If a child of ours is being attached to our parent then this will incorrectly
320        // destroy its hardware resources. However, this situation is highly unlikely
321        // and the failure is "just" that the layer is re-created, so this should
322        // be safe enough
323        destroyHardwareResources();
324    }
325}
326
327/*
328 * For property operations, we pass a savecount of 0, since the operations aren't part of the
329 * displaylist, and thus don't have to compensate for the record-time/playback-time discrepancy in
330 * base saveCount (i.e., how RestoreToCount uses saveCount + properties().getCount())
331 */
332#define PROPERTY_SAVECOUNT 0
333
334template <class T>
335void RenderNode::setViewProperties(OpenGLRenderer& renderer, T& handler) {
336#if DEBUG_DISPLAY_LIST
337    properties().debugOutputProperties(handler.level() + 1);
338#endif
339    if (properties().getLeft() != 0 || properties().getTop() != 0) {
340        renderer.translate(properties().getLeft(), properties().getTop());
341    }
342    if (properties().getStaticMatrix()) {
343        renderer.concatMatrix(*properties().getStaticMatrix());
344    } else if (properties().getAnimationMatrix()) {
345        renderer.concatMatrix(*properties().getAnimationMatrix());
346    }
347    if (properties().hasTransformMatrix()) {
348        if (properties().isTransformTranslateOnly()) {
349            renderer.translate(properties().getTranslationX(), properties().getTranslationY());
350        } else {
351            renderer.concatMatrix(*properties().getTransformMatrix());
352        }
353    }
354    const bool isLayer = properties().layerProperties().type() != kLayerTypeNone;
355    int clipFlags = properties().getClippingFlags();
356    if (properties().getAlpha() < 1) {
357        if (isLayer) {
358            clipFlags &= ~CLIP_TO_BOUNDS; // bounds clipping done by layer
359
360            renderer.setOverrideLayerAlpha(properties().getAlpha());
361        } else if (!properties().getHasOverlappingRendering()) {
362            renderer.scaleAlpha(properties().getAlpha());
363        } else {
364            Rect layerBounds(0, 0, getWidth(), getHeight());
365            int saveFlags = SkCanvas::kHasAlphaLayer_SaveFlag;
366            if (clipFlags) {
367                saveFlags |= SkCanvas::kClipToLayer_SaveFlag;
368                properties().getClippingRectForFlags(clipFlags, &layerBounds);
369                clipFlags = 0; // all clipping done by saveLayer
370            }
371
372            SaveLayerOp* op = new (handler.allocator()) SaveLayerOp(
373                    layerBounds.left, layerBounds.top, layerBounds.right, layerBounds.bottom,
374                    properties().getAlpha() * 255, saveFlags);
375            handler(op, PROPERTY_SAVECOUNT, properties().getClipToBounds());
376        }
377    }
378    if (clipFlags) {
379        Rect clipRect;
380        properties().getClippingRectForFlags(clipFlags, &clipRect);
381        ClipRectOp* op = new (handler.allocator()) ClipRectOp(
382                clipRect.left, clipRect.top, clipRect.right, clipRect.bottom,
383                SkRegion::kIntersect_Op);
384        handler(op, PROPERTY_SAVECOUNT, properties().getClipToBounds());
385    }
386
387    if (CC_UNLIKELY(properties().hasClippingPath())) {
388        ClipPathOp* op = new (handler.allocator()) ClipPathOp(
389                properties().getClippingPath(), properties().getClippingPathOp());
390        handler(op, PROPERTY_SAVECOUNT, properties().getClipToBounds());
391    }
392}
393
394/**
395 * Apply property-based transformations to input matrix
396 *
397 * If true3dTransform is set to true, the transform applied to the input matrix will use true 4x4
398 * matrix computation instead of the Skia 3x3 matrix + camera hackery.
399 */
400void RenderNode::applyViewPropertyTransforms(mat4& matrix, bool true3dTransform) {
401    if (properties().getLeft() != 0 || properties().getTop() != 0) {
402        matrix.translate(properties().getLeft(), properties().getTop());
403    }
404    if (properties().getStaticMatrix()) {
405        mat4 stat(*properties().getStaticMatrix());
406        matrix.multiply(stat);
407    } else if (properties().getAnimationMatrix()) {
408        mat4 anim(*properties().getAnimationMatrix());
409        matrix.multiply(anim);
410    }
411
412    bool applyTranslationZ = true3dTransform && !MathUtils::isZero(properties().getZ());
413    if (properties().hasTransformMatrix() || applyTranslationZ) {
414        if (properties().isTransformTranslateOnly()) {
415            matrix.translate(properties().getTranslationX(), properties().getTranslationY(),
416                    true3dTransform ? properties().getZ() : 0.0f);
417        } else {
418            if (!true3dTransform) {
419                matrix.multiply(*properties().getTransformMatrix());
420            } else {
421                mat4 true3dMat;
422                true3dMat.loadTranslate(
423                        properties().getPivotX() + properties().getTranslationX(),
424                        properties().getPivotY() + properties().getTranslationY(),
425                        properties().getZ());
426                true3dMat.rotate(properties().getRotationX(), 1, 0, 0);
427                true3dMat.rotate(properties().getRotationY(), 0, 1, 0);
428                true3dMat.rotate(properties().getRotation(), 0, 0, 1);
429                true3dMat.scale(properties().getScaleX(), properties().getScaleY(), 1);
430                true3dMat.translate(-properties().getPivotX(), -properties().getPivotY());
431
432                matrix.multiply(true3dMat);
433            }
434        }
435    }
436}
437
438/**
439 * Organizes the DisplayList hierarchy to prepare for background projection reordering.
440 *
441 * This should be called before a call to defer() or drawDisplayList()
442 *
443 * Each DisplayList that serves as a 3d root builds its list of composited children,
444 * which are flagged to not draw in the standard draw loop.
445 */
446void RenderNode::computeOrdering() {
447    ATRACE_CALL();
448    mProjectedNodes.clear();
449
450    // TODO: create temporary DDLOp and call computeOrderingImpl on top DisplayList so that
451    // transform properties are applied correctly to top level children
452    if (mDisplayListData == NULL) return;
453    for (unsigned int i = 0; i < mDisplayListData->children().size(); i++) {
454        DrawRenderNodeOp* childOp = mDisplayListData->children()[i];
455        childOp->mRenderNode->computeOrderingImpl(childOp,
456                properties().getOutline().getPath(), &mProjectedNodes, &mat4::identity());
457    }
458}
459
460void RenderNode::computeOrderingImpl(
461        DrawRenderNodeOp* opState,
462        const SkPath* outlineOfProjectionSurface,
463        Vector<DrawRenderNodeOp*>* compositedChildrenOfProjectionSurface,
464        const mat4* transformFromProjectionSurface) {
465    mProjectedNodes.clear();
466    if (mDisplayListData == NULL || mDisplayListData->isEmpty()) return;
467
468    // TODO: should avoid this calculation in most cases
469    // TODO: just calculate single matrix, down to all leaf composited elements
470    Matrix4 localTransformFromProjectionSurface(*transformFromProjectionSurface);
471    localTransformFromProjectionSurface.multiply(opState->mTransformFromParent);
472
473    if (properties().getProjectBackwards()) {
474        // composited projectee, flag for out of order draw, save matrix, and store in proj surface
475        opState->mSkipInOrderDraw = true;
476        opState->mTransformFromCompositingAncestor.load(localTransformFromProjectionSurface);
477        compositedChildrenOfProjectionSurface->add(opState);
478    } else {
479        // standard in order draw
480        opState->mSkipInOrderDraw = false;
481    }
482
483    if (mDisplayListData->children().size() > 0) {
484        const bool isProjectionReceiver = mDisplayListData->projectionReceiveIndex >= 0;
485        bool haveAppliedPropertiesToProjection = false;
486        for (unsigned int i = 0; i < mDisplayListData->children().size(); i++) {
487            DrawRenderNodeOp* childOp = mDisplayListData->children()[i];
488            RenderNode* child = childOp->mRenderNode;
489
490            const SkPath* projectionOutline = NULL;
491            Vector<DrawRenderNodeOp*>* projectionChildren = NULL;
492            const mat4* projectionTransform = NULL;
493            if (isProjectionReceiver && !child->properties().getProjectBackwards()) {
494                // if receiving projections, collect projecting descendent
495
496                // Note that if a direct descendent is projecting backwards, we pass it's
497                // grandparent projection collection, since it shouldn't project onto it's
498                // parent, where it will already be drawing.
499                projectionOutline = properties().getOutline().getPath();
500                projectionChildren = &mProjectedNodes;
501                projectionTransform = &mat4::identity();
502            } else {
503                if (!haveAppliedPropertiesToProjection) {
504                    applyViewPropertyTransforms(localTransformFromProjectionSurface);
505                    haveAppliedPropertiesToProjection = true;
506                }
507                projectionOutline = outlineOfProjectionSurface;
508                projectionChildren = compositedChildrenOfProjectionSurface;
509                projectionTransform = &localTransformFromProjectionSurface;
510            }
511            child->computeOrderingImpl(childOp,
512                    projectionOutline, projectionChildren, projectionTransform);
513        }
514    }
515}
516
517class DeferOperationHandler {
518public:
519    DeferOperationHandler(DeferStateStruct& deferStruct, int level)
520        : mDeferStruct(deferStruct), mLevel(level) {}
521    inline void operator()(DisplayListOp* operation, int saveCount, bool clipToBounds) {
522        operation->defer(mDeferStruct, saveCount, mLevel, clipToBounds);
523    }
524    inline LinearAllocator& allocator() { return *(mDeferStruct.mAllocator); }
525    inline void startMark(const char* name) {} // do nothing
526    inline void endMark() {}
527    inline int level() { return mLevel; }
528    inline int replayFlags() { return mDeferStruct.mReplayFlags; }
529
530private:
531    DeferStateStruct& mDeferStruct;
532    const int mLevel;
533};
534
535void RenderNode::defer(DeferStateStruct& deferStruct, const int level) {
536    DeferOperationHandler handler(deferStruct, level);
537    issueOperations<DeferOperationHandler>(deferStruct.mRenderer, handler);
538}
539
540class ReplayOperationHandler {
541public:
542    ReplayOperationHandler(ReplayStateStruct& replayStruct, int level)
543        : mReplayStruct(replayStruct), mLevel(level) {}
544    inline void operator()(DisplayListOp* operation, int saveCount, bool clipToBounds) {
545#if DEBUG_DISPLAY_LIST_OPS_AS_EVENTS
546        mReplayStruct.mRenderer.eventMark(operation->name());
547#endif
548        operation->replay(mReplayStruct, saveCount, mLevel, clipToBounds);
549    }
550    inline LinearAllocator& allocator() { return *(mReplayStruct.mAllocator); }
551    inline void startMark(const char* name) {
552        mReplayStruct.mRenderer.startMark(name);
553    }
554    inline void endMark() {
555        mReplayStruct.mRenderer.endMark();
556    }
557    inline int level() { return mLevel; }
558    inline int replayFlags() { return mReplayStruct.mReplayFlags; }
559
560private:
561    ReplayStateStruct& mReplayStruct;
562    const int mLevel;
563};
564
565void RenderNode::replay(ReplayStateStruct& replayStruct, const int level) {
566    ReplayOperationHandler handler(replayStruct, level);
567    issueOperations<ReplayOperationHandler>(replayStruct.mRenderer, handler);
568}
569
570void RenderNode::buildZSortedChildList(Vector<ZDrawRenderNodeOpPair>& zTranslatedNodes) {
571    if (mDisplayListData == NULL || mDisplayListData->children().size() == 0) return;
572
573    for (unsigned int i = 0; i < mDisplayListData->children().size(); i++) {
574        DrawRenderNodeOp* childOp = mDisplayListData->children()[i];
575        RenderNode* child = childOp->mRenderNode;
576        float childZ = child->properties().getZ();
577
578        if (!MathUtils::isZero(childZ)) {
579            zTranslatedNodes.add(ZDrawRenderNodeOpPair(childZ, childOp));
580            childOp->mSkipInOrderDraw = true;
581        } else if (!child->properties().getProjectBackwards()) {
582            // regular, in order drawing DisplayList
583            childOp->mSkipInOrderDraw = false;
584        }
585    }
586
587    // Z sort 3d children (stable-ness makes z compare fall back to standard drawing order)
588    std::stable_sort(zTranslatedNodes.begin(), zTranslatedNodes.end());
589}
590
591template <class T>
592void RenderNode::issueDrawShadowOperation(const Matrix4& transformFromParent, T& handler) {
593    if (properties().getAlpha() <= 0.0f || !properties().getOutline().getPath()) return;
594
595    mat4 shadowMatrixXY(transformFromParent);
596    applyViewPropertyTransforms(shadowMatrixXY);
597
598    // Z matrix needs actual 3d transformation, so mapped z values will be correct
599    mat4 shadowMatrixZ(transformFromParent);
600    applyViewPropertyTransforms(shadowMatrixZ, true);
601
602    const SkPath* outlinePath = properties().getOutline().getPath();
603    const RevealClip& revealClip = properties().getRevealClip();
604    const SkPath* revealClipPath = revealClip.hasConvexClip()
605            ?  revealClip.getPath() : NULL; // only pass the reveal clip's path if it's convex
606
607    if (revealClipPath && revealClipPath->isEmpty()) return;
608
609    /**
610     * The drawing area of the caster is always the same as the its perimeter (which
611     * the shadow system uses) *except* in the inverse clip case. Inform the shadow
612     * system that the caster's drawing area (as opposed to its perimeter) has been
613     * clipped, so that it knows the caster can't be opaque.
614     */
615    bool casterUnclipped = !revealClip.willClip() || revealClip.hasConvexClip();
616
617    DisplayListOp* shadowOp  = new (handler.allocator()) DrawShadowOp(
618            shadowMatrixXY, shadowMatrixZ,
619            properties().getAlpha(), casterUnclipped,
620            outlinePath, revealClipPath);
621    handler(shadowOp, PROPERTY_SAVECOUNT, properties().getClipToBounds());
622}
623
624template <class T>
625int RenderNode::issueOperationsOfNegZChildren(
626        const Vector<ZDrawRenderNodeOpPair>& zTranslatedNodes,
627        OpenGLRenderer& renderer, T& handler) {
628    if (zTranslatedNodes.isEmpty()) return -1;
629
630    // create a save around the body of the ViewGroup's draw method, so that
631    // matrix/clip methods don't affect composited children
632    int shadowSaveCount = renderer.getSaveCount();
633    handler(new (handler.allocator()) SaveOp(SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag),
634            PROPERTY_SAVECOUNT, properties().getClipToBounds());
635
636    issueOperationsOf3dChildren(zTranslatedNodes, kNegativeZChildren, renderer, handler);
637    return shadowSaveCount;
638}
639
640template <class T>
641void RenderNode::issueOperationsOfPosZChildren(int shadowRestoreTo,
642        const Vector<ZDrawRenderNodeOpPair>& zTranslatedNodes,
643        OpenGLRenderer& renderer, T& handler) {
644    if (zTranslatedNodes.isEmpty()) return;
645
646    LOG_ALWAYS_FATAL_IF(shadowRestoreTo < 0, "invalid save to restore to");
647    handler(new (handler.allocator()) RestoreToCountOp(shadowRestoreTo),
648            PROPERTY_SAVECOUNT, properties().getClipToBounds());
649    renderer.setOverrideLayerAlpha(1.0f);
650
651    issueOperationsOf3dChildren(zTranslatedNodes, kPositiveZChildren, renderer, handler);
652}
653
654#define SHADOW_DELTA 0.1f
655
656template <class T>
657void RenderNode::issueOperationsOf3dChildren(const Vector<ZDrawRenderNodeOpPair>& zTranslatedNodes,
658        ChildrenSelectMode mode, OpenGLRenderer& renderer, T& handler) {
659    const int size = zTranslatedNodes.size();
660    if (size == 0
661            || (mode == kNegativeZChildren && zTranslatedNodes[0].key > 0.0f)
662            || (mode == kPositiveZChildren && zTranslatedNodes[size - 1].key < 0.0f)) {
663        // no 3d children to draw
664        return;
665    }
666
667    /**
668     * Draw shadows and (potential) casters mostly in order, but allow the shadows of casters
669     * with very similar Z heights to draw together.
670     *
671     * This way, if Views A & B have the same Z height and are both casting shadows, the shadows are
672     * underneath both, and neither's shadow is drawn on top of the other.
673     */
674    const size_t nonNegativeIndex = findNonNegativeIndex(zTranslatedNodes);
675    size_t drawIndex, shadowIndex, endIndex;
676    if (mode == kNegativeZChildren) {
677        drawIndex = 0;
678        endIndex = nonNegativeIndex;
679        shadowIndex = endIndex; // draw no shadows
680    } else {
681        drawIndex = nonNegativeIndex;
682        endIndex = size;
683        shadowIndex = drawIndex; // potentially draw shadow for each pos Z child
684    }
685
686    DISPLAY_LIST_LOGD("%*s%d %s 3d children:", (handler.level() + 1) * 2, "",
687            endIndex - drawIndex, mode == kNegativeZChildren ? "negative" : "positive");
688
689    float lastCasterZ = 0.0f;
690    while (shadowIndex < endIndex || drawIndex < endIndex) {
691        if (shadowIndex < endIndex) {
692            DrawRenderNodeOp* casterOp = zTranslatedNodes[shadowIndex].value;
693            RenderNode* caster = casterOp->mRenderNode;
694            const float casterZ = zTranslatedNodes[shadowIndex].key;
695            // attempt to render the shadow if the caster about to be drawn is its caster,
696            // OR if its caster's Z value is similar to the previous potential caster
697            if (shadowIndex == drawIndex || casterZ - lastCasterZ < SHADOW_DELTA) {
698                caster->issueDrawShadowOperation(casterOp->mTransformFromParent, handler);
699
700                lastCasterZ = casterZ; // must do this even if current caster not casting a shadow
701                shadowIndex++;
702                continue;
703            }
704        }
705
706        // only the actual child DL draw needs to be in save/restore,
707        // since it modifies the renderer's matrix
708        int restoreTo = renderer.save(SkCanvas::kMatrix_SaveFlag);
709
710        DrawRenderNodeOp* childOp = zTranslatedNodes[drawIndex].value;
711        RenderNode* child = childOp->mRenderNode;
712
713        renderer.concatMatrix(childOp->mTransformFromParent);
714        childOp->mSkipInOrderDraw = false; // this is horrible, I'm so sorry everyone
715        handler(childOp, renderer.getSaveCount() - 1, properties().getClipToBounds());
716        childOp->mSkipInOrderDraw = true;
717
718        renderer.restoreToCount(restoreTo);
719        drawIndex++;
720    }
721}
722
723template <class T>
724void RenderNode::issueOperationsOfProjectedChildren(OpenGLRenderer& renderer, T& handler) {
725    DISPLAY_LIST_LOGD("%*s%d projected children:", (handler.level() + 1) * 2, "", mProjectedNodes.size());
726    const SkPath* projectionReceiverOutline = properties().getOutline().getPath();
727    int restoreTo = renderer.getSaveCount();
728
729    // If the projection reciever has an outline, we mask each of the projected rendernodes to it
730    // Either with clipRect, or special saveLayer masking
731    LinearAllocator& alloc = handler.allocator();
732    if (projectionReceiverOutline != NULL) {
733        const SkRect& outlineBounds = projectionReceiverOutline->getBounds();
734        if (projectionReceiverOutline->isRect(NULL)) {
735            // mask to the rect outline simply with clipRect
736            handler(new (alloc) SaveOp(SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag),
737                    PROPERTY_SAVECOUNT, properties().getClipToBounds());
738            ClipRectOp* clipOp = new (alloc) ClipRectOp(
739                    outlineBounds.left(), outlineBounds.top(),
740                    outlineBounds.right(), outlineBounds.bottom(), SkRegion::kIntersect_Op);
741            handler(clipOp, PROPERTY_SAVECOUNT, properties().getClipToBounds());
742        } else {
743            // wrap the projected RenderNodes with a SaveLayer that will mask to the outline
744            SaveLayerOp* op = new (alloc) SaveLayerOp(
745                    outlineBounds.left(), outlineBounds.top(),
746                    outlineBounds.right(), outlineBounds.bottom(),
747                    255, SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag | SkCanvas::kARGB_ClipLayer_SaveFlag);
748            op->setMask(projectionReceiverOutline);
749            handler(op, PROPERTY_SAVECOUNT, properties().getClipToBounds());
750
751            /* TODO: add optimizations here to take advantage of placement/size of projected
752             * children (which may shrink saveLayer area significantly). This is dependent on
753             * passing actual drawing/dirtying bounds of projected content down to native.
754             */
755        }
756    }
757
758    // draw projected nodes
759    for (size_t i = 0; i < mProjectedNodes.size(); i++) {
760        DrawRenderNodeOp* childOp = mProjectedNodes[i];
761
762        // matrix save, concat, and restore can be done safely without allocating operations
763        int restoreTo = renderer.save(SkCanvas::kMatrix_SaveFlag);
764        renderer.concatMatrix(childOp->mTransformFromCompositingAncestor);
765        childOp->mSkipInOrderDraw = false; // this is horrible, I'm so sorry everyone
766        handler(childOp, renderer.getSaveCount() - 1, properties().getClipToBounds());
767        childOp->mSkipInOrderDraw = true;
768        renderer.restoreToCount(restoreTo);
769    }
770
771    if (projectionReceiverOutline != NULL) {
772        handler(new (alloc) RestoreToCountOp(restoreTo),
773                PROPERTY_SAVECOUNT, properties().getClipToBounds());
774    }
775}
776
777/**
778 * This function serves both defer and replay modes, and will organize the displayList's component
779 * operations for a single frame:
780 *
781 * Every 'simple' state operation that affects just the matrix and alpha (or other factors of
782 * DeferredDisplayState) may be issued directly to the renderer, but complex operations (with custom
783 * defer logic) and operations in displayListOps are issued through the 'handler' which handles the
784 * defer vs replay logic, per operation
785 */
786template <class T>
787void RenderNode::issueOperations(OpenGLRenderer& renderer, T& handler) {
788    const int level = handler.level();
789    if (mDisplayListData->isEmpty()) {
790        DISPLAY_LIST_LOGD("%*sEmpty display list (%p, %s)", level * 2, "", this, getName());
791        return;
792    }
793
794    const bool drawLayer = (mLayer && (&renderer != mLayer->renderer));
795    // If we are updating the contents of mLayer, we don't want to apply any of
796    // the RenderNode's properties to this issueOperations pass. Those will all
797    // be applied when the layer is drawn, aka when this is true.
798    const bool useViewProperties = (!mLayer || drawLayer);
799    if (useViewProperties) {
800        const Outline& outline = properties().getOutline();
801        if (properties().getAlpha() <= 0 || (outline.getShouldClip() && outline.isEmpty())) {
802            DISPLAY_LIST_LOGD("%*sRejected display list (%p, %s)", level * 2, "", this, getName());
803            return;
804        }
805    }
806
807    handler.startMark(getName());
808
809#if DEBUG_DISPLAY_LIST
810    const Rect& clipRect = renderer.getLocalClipBounds();
811    DISPLAY_LIST_LOGD("%*sStart display list (%p, %s), localClipBounds: %.0f, %.0f, %.0f, %.0f",
812            level * 2, "", this, getName(),
813            clipRect.left, clipRect.top, clipRect.right, clipRect.bottom);
814#endif
815
816    LinearAllocator& alloc = handler.allocator();
817    int restoreTo = renderer.getSaveCount();
818    handler(new (alloc) SaveOp(SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag),
819            PROPERTY_SAVECOUNT, properties().getClipToBounds());
820
821    DISPLAY_LIST_LOGD("%*sSave %d %d", (level + 1) * 2, "",
822            SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag, restoreTo);
823
824    if (useViewProperties) {
825        setViewProperties<T>(renderer, handler);
826    }
827
828    bool quickRejected = properties().getClipToBounds()
829            && renderer.quickRejectConservative(0, 0, properties().getWidth(), properties().getHeight());
830    if (!quickRejected) {
831        if (mProperties.getOutline().willClip()) {
832            renderer.setClippingOutline(alloc, &(mProperties.getOutline()));
833        }
834
835        if (drawLayer) {
836            handler(new (alloc) DrawLayerOp(mLayer, 0, 0),
837                    renderer.getSaveCount() - 1, properties().getClipToBounds());
838        } else {
839            Vector<ZDrawRenderNodeOpPair> zTranslatedNodes;
840            buildZSortedChildList(zTranslatedNodes);
841
842            // for 3d root, draw children with negative z values
843            int shadowRestoreTo = issueOperationsOfNegZChildren(zTranslatedNodes, renderer, handler);
844
845            DisplayListLogBuffer& logBuffer = DisplayListLogBuffer::getInstance();
846            const int saveCountOffset = renderer.getSaveCount() - 1;
847            const int projectionReceiveIndex = mDisplayListData->projectionReceiveIndex;
848            const int size = static_cast<int>(mDisplayListData->displayListOps.size());
849            for (int i = 0; i < size; i++) {
850                DisplayListOp *op = mDisplayListData->displayListOps[i];
851
852#if DEBUG_DISPLAY_LIST
853                op->output(level + 1);
854#endif
855                logBuffer.writeCommand(level, op->name());
856                handler(op, saveCountOffset, properties().getClipToBounds());
857
858                if (CC_UNLIKELY(i == projectionReceiveIndex && mProjectedNodes.size() > 0)) {
859                    issueOperationsOfProjectedChildren(renderer, handler);
860                }
861            }
862
863            // for 3d root, draw children with positive z values
864            issueOperationsOfPosZChildren(shadowRestoreTo, zTranslatedNodes, renderer, handler);
865        }
866    }
867
868    DISPLAY_LIST_LOGD("%*sRestoreToCount %d", (level + 1) * 2, "", restoreTo);
869    handler(new (alloc) RestoreToCountOp(restoreTo),
870            PROPERTY_SAVECOUNT, properties().getClipToBounds());
871    renderer.setOverrideLayerAlpha(1.0f);
872
873    DISPLAY_LIST_LOGD("%*sDone (%p, %s)", level * 2, "", this, getName());
874    handler.endMark();
875}
876
877} /* namespace uirenderer */
878} /* namespace android */
879