RenderNode.cpp revision eecff56fed5dd5206acfbc5007b4912081b36d3b
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#include "RenderNode.h" 18 19#include "DamageAccumulator.h" 20#include "Debug.h" 21#if HWUI_NEW_OPS 22#include "RecordedOp.h" 23#include "BakedOpRenderer.h" 24#endif 25#include "DisplayListOp.h" 26#include "LayerRenderer.h" 27#include "OpenGLRenderer.h" 28#include "TreeInfo.h" 29#include "utils/MathUtils.h" 30#include "utils/TraceUtils.h" 31#include "renderthread/CanvasContext.h" 32 33#include "protos/hwui.pb.h" 34#include "protos/ProtoHelpers.h" 35 36#include <algorithm> 37#include <sstream> 38#include <string> 39 40namespace android { 41namespace uirenderer { 42 43void RenderNode::debugDumpLayers(const char* prefix) { 44#if HWUI_NEW_OPS 45 LOG_ALWAYS_FATAL("TODO: dump layer"); 46#else 47 if (mLayer) { 48 ALOGD("%sNode %p (%s) has layer %p (fbo = %u, wasBuildLayered = %s)", 49 prefix, this, getName(), mLayer, mLayer->getFbo(), 50 mLayer->wasBuildLayered ? "true" : "false"); 51 } 52#endif 53 if (mDisplayList) { 54 for (auto&& child : mDisplayList->getChildren()) { 55 child->renderNode->debugDumpLayers(prefix); 56 } 57 } 58} 59 60RenderNode::RenderNode() 61 : mDirtyPropertyFields(0) 62 , mNeedsDisplayListSync(false) 63 , mDisplayList(nullptr) 64 , mStagingDisplayList(nullptr) 65 , mAnimatorManager(*this) 66 , mParentCount(0) { 67} 68 69RenderNode::~RenderNode() { 70 deleteDisplayList(); 71 delete mStagingDisplayList; 72#if HWUI_NEW_OPS 73 LOG_ALWAYS_FATAL_IF(mLayer, "layer missed detachment!"); 74#else 75 if (mLayer) { 76 ALOGW("Memory Warning: Layer %p missed its detachment, held on to for far too long!", mLayer); 77 mLayer->postDecStrong(); 78 mLayer = nullptr; 79 } 80#endif 81} 82 83void RenderNode::setStagingDisplayList(DisplayList* displayList) { 84 mNeedsDisplayListSync = true; 85 delete mStagingDisplayList; 86 mStagingDisplayList = displayList; 87 // If mParentCount == 0 we are the sole reference to this RenderNode, 88 // so immediately free the old display list 89 if (!mParentCount && !mStagingDisplayList) { 90 deleteDisplayList(); 91 } 92} 93 94/** 95 * This function is a simplified version of replay(), where we simply retrieve and log the 96 * display list. This function should remain in sync with the replay() function. 97 */ 98void RenderNode::output(uint32_t level) { 99 ALOGD("%*sStart display list (%p, %s%s%s%s%s%s)", (level - 1) * 2, "", this, 100 getName(), 101 (MathUtils::isZero(properties().getAlpha()) ? ", zero alpha" : ""), 102 (properties().hasShadow() ? ", casting shadow" : ""), 103 (isRenderable() ? "" : ", empty"), 104 (properties().getProjectBackwards() ? ", projected" : ""), 105 (mLayer != nullptr ? ", on HW Layer" : "")); 106 ALOGD("%*s%s %d", level * 2, "", "Save", SaveFlags::MatrixClip); 107 108 properties().debugOutputProperties(level); 109 110 if (mDisplayList) { 111#if HWUI_NEW_OPS 112 LOG_ALWAYS_FATAL("op dumping unsupported"); 113#else 114 // TODO: consider printing the chunk boundaries here 115 for (auto&& op : mDisplayList->getOps()) { 116 op->output(level, DisplayListOp::kOpLogFlag_Recurse); 117 } 118#endif 119 } 120 121 ALOGD("%*sDone (%p, %s)", (level - 1) * 2, "", this, getName()); 122} 123 124void RenderNode::copyTo(proto::RenderNode *pnode) { 125 pnode->set_id(static_cast<uint64_t>( 126 reinterpret_cast<uintptr_t>(this))); 127 pnode->set_name(mName.string(), mName.length()); 128 129 proto::RenderProperties* pprops = pnode->mutable_properties(); 130 pprops->set_left(properties().getLeft()); 131 pprops->set_top(properties().getTop()); 132 pprops->set_right(properties().getRight()); 133 pprops->set_bottom(properties().getBottom()); 134 pprops->set_clip_flags(properties().getClippingFlags()); 135 pprops->set_alpha(properties().getAlpha()); 136 pprops->set_translation_x(properties().getTranslationX()); 137 pprops->set_translation_y(properties().getTranslationY()); 138 pprops->set_translation_z(properties().getTranslationZ()); 139 pprops->set_elevation(properties().getElevation()); 140 pprops->set_rotation(properties().getRotation()); 141 pprops->set_rotation_x(properties().getRotationX()); 142 pprops->set_rotation_y(properties().getRotationY()); 143 pprops->set_scale_x(properties().getScaleX()); 144 pprops->set_scale_y(properties().getScaleY()); 145 pprops->set_pivot_x(properties().getPivotX()); 146 pprops->set_pivot_y(properties().getPivotY()); 147 pprops->set_has_overlapping_rendering(properties().getHasOverlappingRendering()); 148 pprops->set_pivot_explicitly_set(properties().isPivotExplicitlySet()); 149 pprops->set_project_backwards(properties().getProjectBackwards()); 150 pprops->set_projection_receiver(properties().isProjectionReceiver()); 151 set(pprops->mutable_clip_bounds(), properties().getClipBounds()); 152 153 const Outline& outline = properties().getOutline(); 154 if (outline.getType() != Outline::Type::None) { 155 proto::Outline* poutline = pprops->mutable_outline(); 156 poutline->clear_path(); 157 if (outline.getType() == Outline::Type::Empty) { 158 poutline->set_type(proto::Outline_Type_Empty); 159 } else if (outline.getType() == Outline::Type::ConvexPath) { 160 poutline->set_type(proto::Outline_Type_ConvexPath); 161 if (const SkPath* path = outline.getPath()) { 162 set(poutline->mutable_path(), *path); 163 } 164 } else if (outline.getType() == Outline::Type::RoundRect) { 165 poutline->set_type(proto::Outline_Type_RoundRect); 166 } else { 167 ALOGW("Uknown outline type! %d", static_cast<int>(outline.getType())); 168 poutline->set_type(proto::Outline_Type_None); 169 } 170 poutline->set_should_clip(outline.getShouldClip()); 171 poutline->set_alpha(outline.getAlpha()); 172 poutline->set_radius(outline.getRadius()); 173 set(poutline->mutable_bounds(), outline.getBounds()); 174 } else { 175 pprops->clear_outline(); 176 } 177 178 const RevealClip& revealClip = properties().getRevealClip(); 179 if (revealClip.willClip()) { 180 proto::RevealClip* prevealClip = pprops->mutable_reveal_clip(); 181 prevealClip->set_x(revealClip.getX()); 182 prevealClip->set_y(revealClip.getY()); 183 prevealClip->set_radius(revealClip.getRadius()); 184 } else { 185 pprops->clear_reveal_clip(); 186 } 187 188 pnode->clear_children(); 189 if (mDisplayList) { 190 for (auto&& child : mDisplayList->getChildren()) { 191 child->renderNode->copyTo(pnode->add_children()); 192 } 193 } 194} 195 196int RenderNode::getDebugSize() { 197 int size = sizeof(RenderNode); 198 if (mStagingDisplayList) { 199 size += mStagingDisplayList->getUsedSize(); 200 } 201 if (mDisplayList && mDisplayList != mStagingDisplayList) { 202 size += mDisplayList->getUsedSize(); 203 } 204 return size; 205} 206 207void RenderNode::prepareTree(TreeInfo& info) { 208 ATRACE_CALL(); 209 LOG_ALWAYS_FATAL_IF(!info.damageAccumulator, "DamageAccumulator missing"); 210 211 // Functors don't correctly handle stencil usage of overdraw debugging - shove 'em in a layer. 212 bool functorsNeedLayer = Properties::debugOverdraw; 213 214 prepareTreeImpl(info, functorsNeedLayer); 215} 216 217void RenderNode::addAnimator(const sp<BaseRenderNodeAnimator>& animator) { 218 mAnimatorManager.addAnimator(animator); 219} 220 221void RenderNode::damageSelf(TreeInfo& info) { 222 if (isRenderable()) { 223 if (properties().getClipDamageToBounds()) { 224 info.damageAccumulator->dirty(0, 0, properties().getWidth(), properties().getHeight()); 225 } else { 226 // Hope this is big enough? 227 // TODO: Get this from the display list ops or something 228 info.damageAccumulator->dirty(DIRTY_MIN, DIRTY_MIN, DIRTY_MAX, DIRTY_MAX); 229 } 230 } 231} 232 233void RenderNode::prepareLayer(TreeInfo& info, uint32_t dirtyMask) { 234 LayerType layerType = properties().effectiveLayerType(); 235 if (CC_UNLIKELY(layerType == LayerType::RenderLayer)) { 236 // Damage applied so far needs to affect our parent, but does not require 237 // the layer to be updated. So we pop/push here to clear out the current 238 // damage and get a clean state for display list or children updates to 239 // affect, which will require the layer to be updated 240 info.damageAccumulator->popTransform(); 241 info.damageAccumulator->pushTransform(this); 242 if (dirtyMask & DISPLAY_LIST) { 243 damageSelf(info); 244 } 245 } 246} 247 248static layer_t* createLayer(RenderState& renderState, uint32_t width, uint32_t height) { 249#if HWUI_NEW_OPS 250 return renderState.layerPool().get(renderState, width, height); 251#else 252 return LayerRenderer::createRenderLayer(renderState, width, height); 253#endif 254} 255 256static void destroyLayer(layer_t* layer) { 257#if HWUI_NEW_OPS 258 RenderState& renderState = layer->renderState; 259 renderState.layerPool().putOrDelete(layer); 260#else 261 LayerRenderer::destroyLayer(layer); 262#endif 263} 264 265static bool layerMatchesWidthAndHeight(layer_t* layer, int width, int height) { 266#if HWUI_NEW_OPS 267 return layer->viewportWidth == (uint32_t) width && layer->viewportHeight == (uint32_t)height; 268#else 269 return layer->layer.getWidth() == width && layer->layer.getHeight() == height; 270#endif 271} 272 273void RenderNode::pushLayerUpdate(TreeInfo& info) { 274 LayerType layerType = properties().effectiveLayerType(); 275 // If we are not a layer OR we cannot be rendered (eg, view was detached) 276 // we need to destroy any Layers we may have had previously 277 if (CC_LIKELY(layerType != LayerType::RenderLayer) || CC_UNLIKELY(!isRenderable())) { 278 if (CC_UNLIKELY(mLayer)) { 279 destroyLayer(mLayer); 280 mLayer = nullptr; 281 } 282 return; 283 } 284 285 bool transformUpdateNeeded = false; 286 if (!mLayer) { 287 mLayer = createLayer(info.canvasContext.getRenderState(), getWidth(), getHeight()); 288#if !HWUI_NEW_OPS 289 applyLayerPropertiesToLayer(info); 290#endif 291 damageSelf(info); 292 transformUpdateNeeded = true; 293 } else if (!layerMatchesWidthAndHeight(mLayer, getWidth(), getHeight())) { 294#if HWUI_NEW_OPS 295 RenderState& renderState = mLayer->renderState; 296 if (properties().fitsOnLayer()) { 297 mLayer = renderState.layerPool().resize(mLayer, getWidth(), getHeight()); 298 } else { 299#else 300 if (!LayerRenderer::resizeLayer(mLayer, getWidth(), getHeight())) { 301#endif 302 destroyLayer(mLayer); 303 mLayer = nullptr; 304 } 305 damageSelf(info); 306 transformUpdateNeeded = true; 307 } 308 309 SkRect dirty; 310 info.damageAccumulator->peekAtDirty(&dirty); 311 312 if (!mLayer) { 313 Caches::getInstance().dumpMemoryUsage(); 314 if (info.errorHandler) { 315 std::ostringstream err; 316 err << "Unable to create layer for " << getName(); 317 const int maxTextureSize = Caches::getInstance().maxTextureSize; 318 if (getWidth() > maxTextureSize || getHeight() > maxTextureSize) { 319 err << ", size " << getWidth() << "x" << getHeight() 320 << " exceeds max size " << maxTextureSize; 321 } else { 322 err << ", see logcat for more info"; 323 } 324 info.errorHandler->onError(err.str()); 325 } 326 return; 327 } 328 329 if (transformUpdateNeeded && mLayer) { 330 // update the transform in window of the layer to reset its origin wrt light source position 331 Matrix4 windowTransform; 332 info.damageAccumulator->computeCurrentTransform(&windowTransform); 333 mLayer->setWindowTransform(windowTransform); 334 } 335 336#if HWUI_NEW_OPS 337 info.layerUpdateQueue->enqueueLayerWithDamage(this, dirty); 338#else 339 if (dirty.intersect(0, 0, getWidth(), getHeight())) { 340 dirty.roundOut(&dirty); 341 mLayer->updateDeferred(this, dirty.fLeft, dirty.fTop, dirty.fRight, dirty.fBottom); 342 } 343 // This is not inside the above if because we may have called 344 // updateDeferred on a previous prepare pass that didn't have a renderer 345 if (info.renderer && mLayer->deferredUpdateScheduled) { 346 info.renderer->pushLayerUpdate(mLayer); 347 } 348#endif 349 350 // There might be prefetched layers that need to be accounted for. 351 // That might be us, so tell CanvasContext that this layer is in the 352 // tree and should not be destroyed. 353 info.canvasContext.markLayerInUse(this); 354} 355 356/** 357 * Traverse down the the draw tree to prepare for a frame. 358 * 359 * MODE_FULL = UI Thread-driven (thus properties must be synced), otherwise RT driven 360 * 361 * While traversing down the tree, functorsNeedLayer flag is set to true if anything that uses the 362 * stencil buffer may be needed. Views that use a functor to draw will be forced onto a layer. 363 */ 364void RenderNode::prepareTreeImpl(TreeInfo& info, bool functorsNeedLayer) { 365 info.damageAccumulator->pushTransform(this); 366 367 if (info.mode == TreeInfo::MODE_FULL) { 368 pushStagingPropertiesChanges(info); 369 } 370 uint32_t animatorDirtyMask = 0; 371 if (CC_LIKELY(info.runAnimations)) { 372 animatorDirtyMask = mAnimatorManager.animate(info); 373 } 374 375 bool willHaveFunctor = false; 376 if (info.mode == TreeInfo::MODE_FULL && mStagingDisplayList) { 377 willHaveFunctor = !mStagingDisplayList->getFunctors().empty(); 378 } else if (mDisplayList) { 379 willHaveFunctor = !mDisplayList->getFunctors().empty(); 380 } 381 bool childFunctorsNeedLayer = mProperties.prepareForFunctorPresence( 382 willHaveFunctor, functorsNeedLayer); 383 384 prepareLayer(info, animatorDirtyMask); 385 if (info.mode == TreeInfo::MODE_FULL) { 386 pushStagingDisplayListChanges(info); 387 } 388 prepareSubTree(info, childFunctorsNeedLayer, mDisplayList); 389 pushLayerUpdate(info); 390 391 info.damageAccumulator->popTransform(); 392} 393 394void RenderNode::syncProperties() { 395 mProperties = mStagingProperties; 396} 397 398void RenderNode::pushStagingPropertiesChanges(TreeInfo& info) { 399 // Push the animators first so that setupStartValueIfNecessary() is called 400 // before properties() is trampled by stagingProperties(), as they are 401 // required by some animators. 402 if (CC_LIKELY(info.runAnimations)) { 403 mAnimatorManager.pushStaging(); 404 } 405 if (mDirtyPropertyFields) { 406 mDirtyPropertyFields = 0; 407 damageSelf(info); 408 info.damageAccumulator->popTransform(); 409 syncProperties(); 410#if !HWUI_NEW_OPS 411 applyLayerPropertiesToLayer(info); 412#endif 413 // We could try to be clever and only re-damage if the matrix changed. 414 // However, we don't need to worry about that. The cost of over-damaging 415 // here is only going to be a single additional map rect of this node 416 // plus a rect join(). The parent's transform (and up) will only be 417 // performed once. 418 info.damageAccumulator->pushTransform(this); 419 damageSelf(info); 420 } 421} 422 423#if !HWUI_NEW_OPS 424void RenderNode::applyLayerPropertiesToLayer(TreeInfo& info) { 425 if (CC_LIKELY(!mLayer)) return; 426 427 const LayerProperties& props = properties().layerProperties(); 428 mLayer->setAlpha(props.alpha(), props.xferMode()); 429 mLayer->setColorFilter(props.colorFilter()); 430 mLayer->setBlend(props.needsBlending()); 431} 432#endif 433 434void RenderNode::syncDisplayList() { 435 // Make sure we inc first so that we don't fluctuate between 0 and 1, 436 // which would thrash the layer cache 437 if (mStagingDisplayList) { 438 for (auto&& child : mStagingDisplayList->getChildren()) { 439 child->renderNode->incParentRefCount(); 440 } 441 } 442 deleteDisplayList(); 443 mDisplayList = mStagingDisplayList; 444 mStagingDisplayList = nullptr; 445 if (mDisplayList) { 446 for (size_t i = 0; i < mDisplayList->getFunctors().size(); i++) { 447 (*mDisplayList->getFunctors()[i])(DrawGlInfo::kModeSync, nullptr); 448 } 449 } 450} 451 452void RenderNode::pushStagingDisplayListChanges(TreeInfo& info) { 453 if (mNeedsDisplayListSync) { 454 mNeedsDisplayListSync = false; 455 // Damage with the old display list first then the new one to catch any 456 // changes in isRenderable or, in the future, bounds 457 damageSelf(info); 458 syncDisplayList(); 459 damageSelf(info); 460 } 461} 462 463void RenderNode::deleteDisplayList() { 464 if (mDisplayList) { 465 for (auto&& child : mDisplayList->getChildren()) { 466 child->renderNode->decParentRefCount(); 467 } 468 } 469 delete mDisplayList; 470 mDisplayList = nullptr; 471} 472 473void RenderNode::prepareSubTree(TreeInfo& info, bool functorsNeedLayer, DisplayList* subtree) { 474 if (subtree) { 475 TextureCache& cache = Caches::getInstance().textureCache; 476 info.out.hasFunctors |= subtree->getFunctors().size(); 477 for (auto&& bitmapResource : subtree->getBitmapResources()) { 478 void* ownerToken = &info.canvasContext; 479 info.prepareTextures = cache.prefetchAndMarkInUse(ownerToken, bitmapResource); 480 } 481 for (auto&& op : subtree->getChildren()) { 482 RenderNode* childNode = op->renderNode; 483#if HWUI_NEW_OPS 484 info.damageAccumulator->pushTransform(&op->localMatrix); 485 bool childFunctorsNeedLayer = functorsNeedLayer; // TODO! || op->mRecordedWithPotentialStencilClip; 486#else 487 info.damageAccumulator->pushTransform(&op->localMatrix); 488 bool childFunctorsNeedLayer = functorsNeedLayer 489 // Recorded with non-rect clip, or canvas-rotated by parent 490 || op->mRecordedWithPotentialStencilClip; 491#endif 492 childNode->prepareTreeImpl(info, childFunctorsNeedLayer); 493 info.damageAccumulator->popTransform(); 494 } 495 } 496} 497 498void RenderNode::destroyHardwareResources() { 499 if (mLayer) { 500 destroyLayer(mLayer); 501 mLayer = nullptr; 502 } 503 if (mDisplayList) { 504 for (auto&& child : mDisplayList->getChildren()) { 505 child->renderNode->destroyHardwareResources(); 506 } 507 if (mNeedsDisplayListSync) { 508 // Next prepare tree we are going to push a new display list, so we can 509 // drop our current one now 510 deleteDisplayList(); 511 } 512 } 513} 514 515void RenderNode::decParentRefCount() { 516 LOG_ALWAYS_FATAL_IF(!mParentCount, "already 0!"); 517 mParentCount--; 518 if (!mParentCount) { 519 // If a child of ours is being attached to our parent then this will incorrectly 520 // destroy its hardware resources. However, this situation is highly unlikely 521 // and the failure is "just" that the layer is re-created, so this should 522 // be safe enough 523 destroyHardwareResources(); 524 } 525} 526 527/* 528 * For property operations, we pass a savecount of 0, since the operations aren't part of the 529 * displaylist, and thus don't have to compensate for the record-time/playback-time discrepancy in 530 * base saveCount (i.e., how RestoreToCount uses saveCount + properties().getCount()) 531 */ 532#define PROPERTY_SAVECOUNT 0 533 534template <class T> 535void RenderNode::setViewProperties(OpenGLRenderer& renderer, T& handler) { 536#if DEBUG_DISPLAY_LIST 537 properties().debugOutputProperties(handler.level() + 1); 538#endif 539 if (properties().getLeft() != 0 || properties().getTop() != 0) { 540 renderer.translate(properties().getLeft(), properties().getTop()); 541 } 542 if (properties().getStaticMatrix()) { 543 renderer.concatMatrix(*properties().getStaticMatrix()); 544 } else if (properties().getAnimationMatrix()) { 545 renderer.concatMatrix(*properties().getAnimationMatrix()); 546 } 547 if (properties().hasTransformMatrix()) { 548 if (properties().isTransformTranslateOnly()) { 549 renderer.translate(properties().getTranslationX(), properties().getTranslationY()); 550 } else { 551 renderer.concatMatrix(*properties().getTransformMatrix()); 552 } 553 } 554 const bool isLayer = properties().effectiveLayerType() != LayerType::None; 555 int clipFlags = properties().getClippingFlags(); 556 if (properties().getAlpha() < 1) { 557 if (isLayer) { 558 clipFlags &= ~CLIP_TO_BOUNDS; // bounds clipping done by layer 559 } 560 if (CC_LIKELY(isLayer || !properties().getHasOverlappingRendering())) { 561 // simply scale rendering content's alpha 562 renderer.scaleAlpha(properties().getAlpha()); 563 } else { 564 // savelayer needed to create an offscreen buffer 565 Rect layerBounds(0, 0, getWidth(), getHeight()); 566 if (clipFlags) { 567 properties().getClippingRectForFlags(clipFlags, &layerBounds); 568 clipFlags = 0; // all clipping done by savelayer 569 } 570 SaveLayerOp* op = new (handler.allocator()) SaveLayerOp( 571 layerBounds.left, layerBounds.top, 572 layerBounds.right, layerBounds.bottom, 573 (int) (properties().getAlpha() * 255), 574 SaveFlags::HasAlphaLayer | SaveFlags::ClipToLayer); 575 handler(op, PROPERTY_SAVECOUNT, properties().getClipToBounds()); 576 } 577 578 if (CC_UNLIKELY(ATRACE_ENABLED() && properties().promotedToLayer())) { 579 // pretend alpha always causes savelayer to warn about 580 // performance problem affecting old versions 581 ATRACE_FORMAT("%s alpha caused saveLayer %dx%d", getName(), 582 static_cast<int>(getWidth()), 583 static_cast<int>(getHeight())); 584 } 585 } 586 if (clipFlags) { 587 Rect clipRect; 588 properties().getClippingRectForFlags(clipFlags, &clipRect); 589 ClipRectOp* op = new (handler.allocator()) ClipRectOp( 590 clipRect.left, clipRect.top, clipRect.right, clipRect.bottom, 591 SkRegion::kIntersect_Op); 592 handler(op, PROPERTY_SAVECOUNT, properties().getClipToBounds()); 593 } 594 595 // TODO: support nesting round rect clips 596 if (mProperties.getRevealClip().willClip()) { 597 Rect bounds; 598 mProperties.getRevealClip().getBounds(&bounds); 599 renderer.setClippingRoundRect(handler.allocator(), bounds, mProperties.getRevealClip().getRadius()); 600 } else if (mProperties.getOutline().willClip()) { 601 renderer.setClippingOutline(handler.allocator(), &(mProperties.getOutline())); 602 } 603} 604 605/** 606 * Apply property-based transformations to input matrix 607 * 608 * If true3dTransform is set to true, the transform applied to the input matrix will use true 4x4 609 * matrix computation instead of the Skia 3x3 matrix + camera hackery. 610 */ 611void RenderNode::applyViewPropertyTransforms(mat4& matrix, bool true3dTransform) const { 612 if (properties().getLeft() != 0 || properties().getTop() != 0) { 613 matrix.translate(properties().getLeft(), properties().getTop()); 614 } 615 if (properties().getStaticMatrix()) { 616 mat4 stat(*properties().getStaticMatrix()); 617 matrix.multiply(stat); 618 } else if (properties().getAnimationMatrix()) { 619 mat4 anim(*properties().getAnimationMatrix()); 620 matrix.multiply(anim); 621 } 622 623 bool applyTranslationZ = true3dTransform && !MathUtils::isZero(properties().getZ()); 624 if (properties().hasTransformMatrix() || applyTranslationZ) { 625 if (properties().isTransformTranslateOnly()) { 626 matrix.translate(properties().getTranslationX(), properties().getTranslationY(), 627 true3dTransform ? properties().getZ() : 0.0f); 628 } else { 629 if (!true3dTransform) { 630 matrix.multiply(*properties().getTransformMatrix()); 631 } else { 632 mat4 true3dMat; 633 true3dMat.loadTranslate( 634 properties().getPivotX() + properties().getTranslationX(), 635 properties().getPivotY() + properties().getTranslationY(), 636 properties().getZ()); 637 true3dMat.rotate(properties().getRotationX(), 1, 0, 0); 638 true3dMat.rotate(properties().getRotationY(), 0, 1, 0); 639 true3dMat.rotate(properties().getRotation(), 0, 0, 1); 640 true3dMat.scale(properties().getScaleX(), properties().getScaleY(), 1); 641 true3dMat.translate(-properties().getPivotX(), -properties().getPivotY()); 642 643 matrix.multiply(true3dMat); 644 } 645 } 646 } 647} 648 649/** 650 * Organizes the DisplayList hierarchy to prepare for background projection reordering. 651 * 652 * This should be called before a call to defer() or drawDisplayList() 653 * 654 * Each DisplayList that serves as a 3d root builds its list of composited children, 655 * which are flagged to not draw in the standard draw loop. 656 */ 657void RenderNode::computeOrdering() { 658 ATRACE_CALL(); 659 mProjectedNodes.clear(); 660 661 // TODO: create temporary DDLOp and call computeOrderingImpl on top DisplayList so that 662 // transform properties are applied correctly to top level children 663 if (mDisplayList == nullptr) return; 664 for (unsigned int i = 0; i < mDisplayList->getChildren().size(); i++) { 665 renderNodeOp_t* childOp = mDisplayList->getChildren()[i]; 666 childOp->renderNode->computeOrderingImpl(childOp, &mProjectedNodes, &mat4::identity()); 667 } 668} 669 670void RenderNode::computeOrderingImpl( 671 renderNodeOp_t* opState, 672 std::vector<renderNodeOp_t*>* compositedChildrenOfProjectionSurface, 673 const mat4* transformFromProjectionSurface) { 674 mProjectedNodes.clear(); 675 if (mDisplayList == nullptr || mDisplayList->isEmpty()) return; 676 677 // TODO: should avoid this calculation in most cases 678 // TODO: just calculate single matrix, down to all leaf composited elements 679 Matrix4 localTransformFromProjectionSurface(*transformFromProjectionSurface); 680 localTransformFromProjectionSurface.multiply(opState->localMatrix); 681 682 if (properties().getProjectBackwards()) { 683 // composited projectee, flag for out of order draw, save matrix, and store in proj surface 684 opState->skipInOrderDraw = true; 685 opState->transformFromCompositingAncestor = localTransformFromProjectionSurface; 686 compositedChildrenOfProjectionSurface->push_back(opState); 687 } else { 688 // standard in order draw 689 opState->skipInOrderDraw = false; 690 } 691 692 if (mDisplayList->getChildren().size() > 0) { 693 const bool isProjectionReceiver = mDisplayList->projectionReceiveIndex >= 0; 694 bool haveAppliedPropertiesToProjection = false; 695 for (unsigned int i = 0; i < mDisplayList->getChildren().size(); i++) { 696 renderNodeOp_t* childOp = mDisplayList->getChildren()[i]; 697 RenderNode* child = childOp->renderNode; 698 699 std::vector<renderNodeOp_t*>* projectionChildren = nullptr; 700 const mat4* projectionTransform = nullptr; 701 if (isProjectionReceiver && !child->properties().getProjectBackwards()) { 702 // if receiving projections, collect projecting descendant 703 704 // Note that if a direct descendant is projecting backwards, we pass its 705 // grandparent projection collection, since it shouldn't project onto its 706 // parent, where it will already be drawing. 707 projectionChildren = &mProjectedNodes; 708 projectionTransform = &mat4::identity(); 709 } else { 710 if (!haveAppliedPropertiesToProjection) { 711 applyViewPropertyTransforms(localTransformFromProjectionSurface); 712 haveAppliedPropertiesToProjection = true; 713 } 714 projectionChildren = compositedChildrenOfProjectionSurface; 715 projectionTransform = &localTransformFromProjectionSurface; 716 } 717 child->computeOrderingImpl(childOp, projectionChildren, projectionTransform); 718 } 719 } 720} 721 722class DeferOperationHandler { 723public: 724 DeferOperationHandler(DeferStateStruct& deferStruct, int level) 725 : mDeferStruct(deferStruct), mLevel(level) {} 726 inline void operator()(DisplayListOp* operation, int saveCount, bool clipToBounds) { 727 operation->defer(mDeferStruct, saveCount, mLevel, clipToBounds); 728 } 729 inline LinearAllocator& allocator() { return *(mDeferStruct.mAllocator); } 730 inline void startMark(const char* name) {} // do nothing 731 inline void endMark() {} 732 inline int level() { return mLevel; } 733 inline int replayFlags() { return mDeferStruct.mReplayFlags; } 734 inline SkPath* allocPathForFrame() { return mDeferStruct.allocPathForFrame(); } 735 736private: 737 DeferStateStruct& mDeferStruct; 738 const int mLevel; 739}; 740 741void RenderNode::defer(DeferStateStruct& deferStruct, const int level) { 742 DeferOperationHandler handler(deferStruct, level); 743 issueOperations<DeferOperationHandler>(deferStruct.mRenderer, handler); 744} 745 746class ReplayOperationHandler { 747public: 748 ReplayOperationHandler(ReplayStateStruct& replayStruct, int level) 749 : mReplayStruct(replayStruct), mLevel(level) {} 750 inline void operator()(DisplayListOp* operation, int saveCount, bool clipToBounds) { 751#if DEBUG_DISPLAY_LIST_OPS_AS_EVENTS 752 mReplayStruct.mRenderer.eventMark(operation->name()); 753#endif 754 operation->replay(mReplayStruct, saveCount, mLevel, clipToBounds); 755 } 756 inline LinearAllocator& allocator() { return *(mReplayStruct.mAllocator); } 757 inline void startMark(const char* name) { 758 mReplayStruct.mRenderer.startMark(name); 759 } 760 inline void endMark() { 761 mReplayStruct.mRenderer.endMark(); 762 } 763 inline int level() { return mLevel; } 764 inline int replayFlags() { return mReplayStruct.mReplayFlags; } 765 inline SkPath* allocPathForFrame() { return mReplayStruct.allocPathForFrame(); } 766 767private: 768 ReplayStateStruct& mReplayStruct; 769 const int mLevel; 770}; 771 772void RenderNode::replay(ReplayStateStruct& replayStruct, const int level) { 773 ReplayOperationHandler handler(replayStruct, level); 774 issueOperations<ReplayOperationHandler>(replayStruct.mRenderer, handler); 775} 776 777void RenderNode::buildZSortedChildList(const DisplayList::Chunk& chunk, 778 std::vector<ZDrawRenderNodeOpPair>& zTranslatedNodes) { 779#if !HWUI_NEW_OPS 780 if (chunk.beginChildIndex == chunk.endChildIndex) return; 781 782 for (unsigned int i = chunk.beginChildIndex; i < chunk.endChildIndex; i++) { 783 DrawRenderNodeOp* childOp = mDisplayList->getChildren()[i]; 784 RenderNode* child = childOp->renderNode; 785 float childZ = child->properties().getZ(); 786 787 if (!MathUtils::isZero(childZ) && chunk.reorderChildren) { 788 zTranslatedNodes.push_back(ZDrawRenderNodeOpPair(childZ, childOp)); 789 childOp->skipInOrderDraw = true; 790 } else if (!child->properties().getProjectBackwards()) { 791 // regular, in order drawing DisplayList 792 childOp->skipInOrderDraw = false; 793 } 794 } 795 796 // Z sort any 3d children (stable-ness makes z compare fall back to standard drawing order) 797 std::stable_sort(zTranslatedNodes.begin(), zTranslatedNodes.end()); 798#endif 799} 800 801template <class T> 802void RenderNode::issueDrawShadowOperation(const Matrix4& transformFromParent, T& handler) { 803 if (properties().getAlpha() <= 0.0f 804 || properties().getOutline().getAlpha() <= 0.0f 805 || !properties().getOutline().getPath() 806 || properties().getScaleX() == 0 807 || properties().getScaleY() == 0) { 808 // no shadow to draw 809 return; 810 } 811 812 mat4 shadowMatrixXY(transformFromParent); 813 applyViewPropertyTransforms(shadowMatrixXY); 814 815 // Z matrix needs actual 3d transformation, so mapped z values will be correct 816 mat4 shadowMatrixZ(transformFromParent); 817 applyViewPropertyTransforms(shadowMatrixZ, true); 818 819 const SkPath* casterOutlinePath = properties().getOutline().getPath(); 820 const SkPath* revealClipPath = properties().getRevealClip().getPath(); 821 if (revealClipPath && revealClipPath->isEmpty()) return; 822 823 float casterAlpha = properties().getAlpha() * properties().getOutline().getAlpha(); 824 825 826 // holds temporary SkPath to store the result of intersections 827 SkPath* frameAllocatedPath = nullptr; 828 const SkPath* outlinePath = casterOutlinePath; 829 830 // intersect the outline with the reveal clip, if present 831 if (revealClipPath) { 832 frameAllocatedPath = handler.allocPathForFrame(); 833 834 Op(*outlinePath, *revealClipPath, kIntersect_SkPathOp, frameAllocatedPath); 835 outlinePath = frameAllocatedPath; 836 } 837 838 // intersect the outline with the clipBounds, if present 839 if (properties().getClippingFlags() & CLIP_TO_CLIP_BOUNDS) { 840 if (!frameAllocatedPath) { 841 frameAllocatedPath = handler.allocPathForFrame(); 842 } 843 844 Rect clipBounds; 845 properties().getClippingRectForFlags(CLIP_TO_CLIP_BOUNDS, &clipBounds); 846 SkPath clipBoundsPath; 847 clipBoundsPath.addRect(clipBounds.left, clipBounds.top, 848 clipBounds.right, clipBounds.bottom); 849 850 Op(*outlinePath, clipBoundsPath, kIntersect_SkPathOp, frameAllocatedPath); 851 outlinePath = frameAllocatedPath; 852 } 853 854 DisplayListOp* shadowOp = new (handler.allocator()) DrawShadowOp( 855 shadowMatrixXY, shadowMatrixZ, casterAlpha, outlinePath); 856 handler(shadowOp, PROPERTY_SAVECOUNT, properties().getClipToBounds()); 857} 858 859#define SHADOW_DELTA 0.1f 860 861template <class T> 862void RenderNode::issueOperationsOf3dChildren(ChildrenSelectMode mode, 863 const Matrix4& initialTransform, const std::vector<ZDrawRenderNodeOpPair>& zTranslatedNodes, 864 OpenGLRenderer& renderer, T& handler) { 865 const int size = zTranslatedNodes.size(); 866 if (size == 0 867 || (mode == ChildrenSelectMode::NegativeZChildren && zTranslatedNodes[0].key > 0.0f) 868 || (mode == ChildrenSelectMode::PositiveZChildren && zTranslatedNodes[size - 1].key < 0.0f)) { 869 // no 3d children to draw 870 return; 871 } 872 873 // Apply the base transform of the parent of the 3d children. This isolates 874 // 3d children of the current chunk from transformations made in previous chunks. 875 int rootRestoreTo = renderer.save(SaveFlags::Matrix); 876 renderer.setGlobalMatrix(initialTransform); 877 878 /** 879 * Draw shadows and (potential) casters mostly in order, but allow the shadows of casters 880 * with very similar Z heights to draw together. 881 * 882 * This way, if Views A & B have the same Z height and are both casting shadows, the shadows are 883 * underneath both, and neither's shadow is drawn on top of the other. 884 */ 885 const size_t nonNegativeIndex = findNonNegativeIndex(zTranslatedNodes); 886 size_t drawIndex, shadowIndex, endIndex; 887 if (mode == ChildrenSelectMode::NegativeZChildren) { 888 drawIndex = 0; 889 endIndex = nonNegativeIndex; 890 shadowIndex = endIndex; // draw no shadows 891 } else { 892 drawIndex = nonNegativeIndex; 893 endIndex = size; 894 shadowIndex = drawIndex; // potentially draw shadow for each pos Z child 895 } 896 897 DISPLAY_LIST_LOGD("%*s%d %s 3d children:", (handler.level() + 1) * 2, "", 898 endIndex - drawIndex, mode == kNegativeZChildren ? "negative" : "positive"); 899 900 float lastCasterZ = 0.0f; 901 while (shadowIndex < endIndex || drawIndex < endIndex) { 902 if (shadowIndex < endIndex) { 903 DrawRenderNodeOp* casterOp = zTranslatedNodes[shadowIndex].value; 904 RenderNode* caster = casterOp->renderNode; 905 const float casterZ = zTranslatedNodes[shadowIndex].key; 906 // attempt to render the shadow if the caster about to be drawn is its caster, 907 // OR if its caster's Z value is similar to the previous potential caster 908 if (shadowIndex == drawIndex || casterZ - lastCasterZ < SHADOW_DELTA) { 909 caster->issueDrawShadowOperation(casterOp->localMatrix, handler); 910 911 lastCasterZ = casterZ; // must do this even if current caster not casting a shadow 912 shadowIndex++; 913 continue; 914 } 915 } 916 917 // only the actual child DL draw needs to be in save/restore, 918 // since it modifies the renderer's matrix 919 int restoreTo = renderer.save(SaveFlags::Matrix); 920 921 DrawRenderNodeOp* childOp = zTranslatedNodes[drawIndex].value; 922 923 renderer.concatMatrix(childOp->localMatrix); 924 childOp->skipInOrderDraw = false; // this is horrible, I'm so sorry everyone 925 handler(childOp, renderer.getSaveCount() - 1, properties().getClipToBounds()); 926 childOp->skipInOrderDraw = true; 927 928 renderer.restoreToCount(restoreTo); 929 drawIndex++; 930 } 931 renderer.restoreToCount(rootRestoreTo); 932} 933 934template <class T> 935void RenderNode::issueOperationsOfProjectedChildren(OpenGLRenderer& renderer, T& handler) { 936 DISPLAY_LIST_LOGD("%*s%d projected children:", (handler.level() + 1) * 2, "", mProjectedNodes.size()); 937 const SkPath* projectionReceiverOutline = properties().getOutline().getPath(); 938 int restoreTo = renderer.getSaveCount(); 939 940 LinearAllocator& alloc = handler.allocator(); 941 handler(new (alloc) SaveOp(SaveFlags::MatrixClip), 942 PROPERTY_SAVECOUNT, properties().getClipToBounds()); 943 944 // Transform renderer to match background we're projecting onto 945 // (by offsetting canvas by translationX/Y of background rendernode, since only those are set) 946 const DisplayListOp* op = 947#if HWUI_NEW_OPS 948 nullptr; 949 LOG_ALWAYS_FATAL("unsupported"); 950#else 951 (mDisplayList->getOps()[mDisplayList->projectionReceiveIndex]); 952#endif 953 const DrawRenderNodeOp* backgroundOp = reinterpret_cast<const DrawRenderNodeOp*>(op); 954 const RenderProperties& backgroundProps = backgroundOp->renderNode->properties(); 955 renderer.translate(backgroundProps.getTranslationX(), backgroundProps.getTranslationY()); 956 957 // If the projection receiver has an outline, we mask projected content to it 958 // (which we know, apriori, are all tessellated paths) 959 renderer.setProjectionPathMask(alloc, projectionReceiverOutline); 960 961 // draw projected nodes 962 for (size_t i = 0; i < mProjectedNodes.size(); i++) { 963 renderNodeOp_t* childOp = mProjectedNodes[i]; 964 965 // matrix save, concat, and restore can be done safely without allocating operations 966 int restoreTo = renderer.save(SaveFlags::Matrix); 967 renderer.concatMatrix(childOp->transformFromCompositingAncestor); 968 childOp->skipInOrderDraw = false; // this is horrible, I'm so sorry everyone 969 handler(childOp, renderer.getSaveCount() - 1, properties().getClipToBounds()); 970 childOp->skipInOrderDraw = true; 971 renderer.restoreToCount(restoreTo); 972 } 973 974 handler(new (alloc) RestoreToCountOp(restoreTo), 975 PROPERTY_SAVECOUNT, properties().getClipToBounds()); 976} 977 978/** 979 * This function serves both defer and replay modes, and will organize the displayList's component 980 * operations for a single frame: 981 * 982 * Every 'simple' state operation that affects just the matrix and alpha (or other factors of 983 * DeferredDisplayState) may be issued directly to the renderer, but complex operations (with custom 984 * defer logic) and operations in displayListOps are issued through the 'handler' which handles the 985 * defer vs replay logic, per operation 986 */ 987template <class T> 988void RenderNode::issueOperations(OpenGLRenderer& renderer, T& handler) { 989 if (mDisplayList->isEmpty()) { 990 DISPLAY_LIST_LOGD("%*sEmpty display list (%p, %s)", handler.level() * 2, "", 991 this, getName()); 992 return; 993 } 994 995#if HWUI_NEW_OPS 996 const bool drawLayer = false; 997#else 998 const bool drawLayer = (mLayer && (&renderer != mLayer->renderer.get())); 999#endif 1000 // If we are updating the contents of mLayer, we don't want to apply any of 1001 // the RenderNode's properties to this issueOperations pass. Those will all 1002 // be applied when the layer is drawn, aka when this is true. 1003 const bool useViewProperties = (!mLayer || drawLayer); 1004 if (useViewProperties) { 1005 const Outline& outline = properties().getOutline(); 1006 if (properties().getAlpha() <= 0 1007 || (outline.getShouldClip() && outline.isEmpty()) 1008 || properties().getScaleX() == 0 1009 || properties().getScaleY() == 0) { 1010 DISPLAY_LIST_LOGD("%*sRejected display list (%p, %s)", handler.level() * 2, "", 1011 this, getName()); 1012 return; 1013 } 1014 } 1015 1016 handler.startMark(getName()); 1017 1018#if DEBUG_DISPLAY_LIST 1019 const Rect& clipRect = renderer.getLocalClipBounds(); 1020 DISPLAY_LIST_LOGD("%*sStart display list (%p, %s), localClipBounds: %.0f, %.0f, %.0f, %.0f", 1021 handler.level() * 2, "", this, getName(), 1022 clipRect.left, clipRect.top, clipRect.right, clipRect.bottom); 1023#endif 1024 1025 LinearAllocator& alloc = handler.allocator(); 1026 int restoreTo = renderer.getSaveCount(); 1027 handler(new (alloc) SaveOp(SaveFlags::MatrixClip), 1028 PROPERTY_SAVECOUNT, properties().getClipToBounds()); 1029 1030 DISPLAY_LIST_LOGD("%*sSave %d %d", (handler.level() + 1) * 2, "", 1031 SaveFlags::MatrixClip, restoreTo); 1032 1033 if (useViewProperties) { 1034 setViewProperties<T>(renderer, handler); 1035 } 1036 1037#if HWUI_NEW_OPS 1038 LOG_ALWAYS_FATAL("legacy op traversal not supported"); 1039#else 1040 bool quickRejected = properties().getClipToBounds() 1041 && renderer.quickRejectConservative(0, 0, properties().getWidth(), properties().getHeight()); 1042 if (!quickRejected) { 1043 Matrix4 initialTransform(*(renderer.currentTransform())); 1044 renderer.setBaseTransform(initialTransform); 1045 1046 if (drawLayer) { 1047 handler(new (alloc) DrawLayerOp(mLayer), 1048 renderer.getSaveCount() - 1, properties().getClipToBounds()); 1049 } else { 1050 const int saveCountOffset = renderer.getSaveCount() - 1; 1051 const int projectionReceiveIndex = mDisplayList->projectionReceiveIndex; 1052 for (size_t chunkIndex = 0; chunkIndex < mDisplayList->getChunks().size(); chunkIndex++) { 1053 const DisplayList::Chunk& chunk = mDisplayList->getChunks()[chunkIndex]; 1054 1055 std::vector<ZDrawRenderNodeOpPair> zTranslatedNodes; 1056 buildZSortedChildList(chunk, zTranslatedNodes); 1057 1058 issueOperationsOf3dChildren(ChildrenSelectMode::NegativeZChildren, 1059 initialTransform, zTranslatedNodes, renderer, handler); 1060 1061 for (size_t opIndex = chunk.beginOpIndex; opIndex < chunk.endOpIndex; opIndex++) { 1062 DisplayListOp *op = mDisplayList->getOps()[opIndex]; 1063#if DEBUG_DISPLAY_LIST 1064 op->output(handler.level() + 1); 1065#endif 1066 handler(op, saveCountOffset, properties().getClipToBounds()); 1067 1068 if (CC_UNLIKELY(!mProjectedNodes.empty() && projectionReceiveIndex >= 0 && 1069 opIndex == static_cast<size_t>(projectionReceiveIndex))) { 1070 issueOperationsOfProjectedChildren(renderer, handler); 1071 } 1072 } 1073 1074 issueOperationsOf3dChildren(ChildrenSelectMode::PositiveZChildren, 1075 initialTransform, zTranslatedNodes, renderer, handler); 1076 } 1077 } 1078 } 1079#endif 1080 1081 DISPLAY_LIST_LOGD("%*sRestoreToCount %d", (handler.level() + 1) * 2, "", restoreTo); 1082 handler(new (alloc) RestoreToCountOp(restoreTo), 1083 PROPERTY_SAVECOUNT, properties().getClipToBounds()); 1084 1085 DISPLAY_LIST_LOGD("%*sDone (%p, %s)", handler.level() * 2, "", this, getName()); 1086 handler.endMark(); 1087} 1088 1089} /* namespace uirenderer */ 1090} /* namespace android */ 1091