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