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