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