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