FrameBuilder.cpp revision 7fc1b0349bc2ac8c880120dc5611f703faa7f06f
1/* 2 * Copyright (C) 2016 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 "FrameBuilder.h" 18 19#include "Canvas.h" 20#include "LayerUpdateQueue.h" 21#include "RenderNode.h" 22#include "renderstate/OffscreenBufferPool.h" 23#include "utils/FatVector.h" 24#include "utils/PaintUtils.h" 25#include "utils/TraceUtils.h" 26 27#include <SkPathOps.h> 28#include <utils/TypeHelpers.h> 29 30namespace android { 31namespace uirenderer { 32 33FrameBuilder::FrameBuilder(const LayerUpdateQueue& layers, const SkRect& clip, 34 uint32_t viewportWidth, uint32_t viewportHeight, 35 const std::vector< sp<RenderNode> >& nodes, const Vector3& lightCenter) 36 : FrameBuilder(layers, clip, viewportWidth, viewportHeight, nodes, lightCenter, 37 Rect(0, 0, 0, 0)) { 38} 39 40 41FrameBuilder::FrameBuilder(const LayerUpdateQueue& layers, const SkRect& clip, 42 uint32_t viewportWidth, uint32_t viewportHeight, 43 const std::vector< sp<RenderNode> >& nodes, const Vector3& lightCenter, 44 const Rect &contentDrawBounds) 45 : mCanvasState(*this) { 46 ATRACE_NAME("prepare drawing commands"); 47 48 mLayerBuilders.reserve(layers.entries().size()); 49 mLayerStack.reserve(layers.entries().size()); 50 51 // Prepare to defer Fbo0 52 auto fbo0 = mAllocator.create<LayerBuilder>(viewportWidth, viewportHeight, Rect(clip)); 53 mLayerBuilders.push_back(fbo0); 54 mLayerStack.push_back(0); 55 mCanvasState.initializeSaveStack(viewportWidth, viewportHeight, 56 clip.fLeft, clip.fTop, clip.fRight, clip.fBottom, 57 lightCenter); 58 59 // Render all layers to be updated, in order. Defer in reverse order, so that they'll be 60 // updated in the order they're passed in (mLayerBuilders are issued to Renderer in reverse) 61 for (int i = layers.entries().size() - 1; i >= 0; i--) { 62 RenderNode* layerNode = layers.entries()[i].renderNode; 63 // only schedule repaint if node still on layer - possible it may have been 64 // removed during a dropped frame, but layers may still remain scheduled so 65 // as not to lose info on what portion is damaged 66 if (CC_LIKELY(layerNode->getLayer() != nullptr)) { 67 const Rect& layerDamage = layers.entries()[i].damage; 68 layerNode->computeOrdering(); 69 70 // map current light center into RenderNode's coordinate space 71 Vector3 lightCenter = mCanvasState.currentSnapshot()->getRelativeLightCenter(); 72 layerNode->getLayer()->inverseTransformInWindow.mapPoint3d(lightCenter); 73 74 saveForLayer(layerNode->getWidth(), layerNode->getHeight(), 0, 0, 75 layerDamage, lightCenter, nullptr, layerNode); 76 77 if (layerNode->getDisplayList()) { 78 deferNodeOps(*layerNode); 79 } 80 restoreForLayer(); 81 } 82 } 83 84 // It there are multiple render nodes, they are laid out as follows: 85 // #0 - backdrop (content + caption) 86 // #1 - content (positioned at (0,0) and clipped to - its bounds mContentDrawBounds) 87 // #2 - additional overlay nodes 88 // Usually the backdrop cannot be seen since it will be entirely covered by the content. While 89 // resizing however it might become partially visible. The following render loop will crop the 90 // backdrop against the content and draw the remaining part of it. It will then draw the content 91 // cropped to the backdrop (since that indicates a shrinking of the window). 92 // 93 // Additional nodes will be drawn on top with no particular clipping semantics. 94 95 // The bounds of the backdrop against which the content should be clipped. 96 Rect backdropBounds = contentDrawBounds; 97 // Usually the contents bounds should be mContentDrawBounds - however - we will 98 // move it towards the fixed edge to give it a more stable appearance (for the moment). 99 // If there is no content bounds we ignore the layering as stated above and start with 2. 100 int layer = (contentDrawBounds.isEmpty() || nodes.size() == 1) ? 2 : 0; 101 102 for (const sp<RenderNode>& node : nodes) { 103 if (node->nothingToDraw()) continue; 104 node->computeOrdering(); 105 int count = mCanvasState.save(SaveFlags::MatrixClip); 106 107 if (layer == 0) { 108 const RenderProperties& properties = node->properties(); 109 Rect targetBounds(properties.getLeft(), properties.getTop(), 110 properties.getRight(), properties.getBottom()); 111 // Move the content bounds towards the fixed corner of the backdrop. 112 const int x = targetBounds.left; 113 const int y = targetBounds.top; 114 // Remember the intersection of the target bounds and the intersection bounds against 115 // which we have to crop the content. 116 backdropBounds.set(x, y, x + backdropBounds.getWidth(), y + backdropBounds.getHeight()); 117 backdropBounds.doIntersect(targetBounds); 118 } else if (layer == 1) { 119 // We shift and clip the content to match its final location in the window. 120 const float left = contentDrawBounds.left; 121 const float top = contentDrawBounds.top; 122 const float dx = backdropBounds.left - left; 123 const float dy = backdropBounds.top - top; 124 const float width = backdropBounds.getWidth(); 125 const float height = backdropBounds.getHeight(); 126 mCanvasState.translate(dx, dy); 127 // It gets cropped against the bounds of the backdrop to stay inside. 128 mCanvasState.clipRect(left, top, left + width, top + height, SkRegion::kIntersect_Op); 129 } 130 131 deferNodePropsAndOps(*node); 132 mCanvasState.restoreToCount(count); 133 layer++; 134 } 135} 136 137void FrameBuilder::onViewportInitialized() {} 138 139void FrameBuilder::onSnapshotRestored(const Snapshot& removed, const Snapshot& restored) {} 140 141void FrameBuilder::deferNodePropsAndOps(RenderNode& node) { 142 const RenderProperties& properties = node.properties(); 143 const Outline& outline = properties.getOutline(); 144 if (properties.getAlpha() <= 0 145 || (outline.getShouldClip() && outline.isEmpty()) 146 || properties.getScaleX() == 0 147 || properties.getScaleY() == 0) { 148 return; // rejected 149 } 150 151 if (properties.getLeft() != 0 || properties.getTop() != 0) { 152 mCanvasState.translate(properties.getLeft(), properties.getTop()); 153 } 154 if (properties.getStaticMatrix()) { 155 mCanvasState.concatMatrix(*properties.getStaticMatrix()); 156 } else if (properties.getAnimationMatrix()) { 157 mCanvasState.concatMatrix(*properties.getAnimationMatrix()); 158 } 159 if (properties.hasTransformMatrix()) { 160 if (properties.isTransformTranslateOnly()) { 161 mCanvasState.translate(properties.getTranslationX(), properties.getTranslationY()); 162 } else { 163 mCanvasState.concatMatrix(*properties.getTransformMatrix()); 164 } 165 } 166 167 const int width = properties.getWidth(); 168 const int height = properties.getHeight(); 169 170 Rect saveLayerBounds; // will be set to non-empty if saveLayer needed 171 const bool isLayer = properties.effectiveLayerType() != LayerType::None; 172 int clipFlags = properties.getClippingFlags(); 173 if (properties.getAlpha() < 1) { 174 if (isLayer) { 175 clipFlags &= ~CLIP_TO_BOUNDS; // bounds clipping done by layer 176 } 177 if (CC_LIKELY(isLayer || !properties.getHasOverlappingRendering())) { 178 // simply scale rendering content's alpha 179 mCanvasState.scaleAlpha(properties.getAlpha()); 180 } else { 181 // schedule saveLayer by initializing saveLayerBounds 182 saveLayerBounds.set(0, 0, width, height); 183 if (clipFlags) { 184 properties.getClippingRectForFlags(clipFlags, &saveLayerBounds); 185 clipFlags = 0; // all clipping done by savelayer 186 } 187 } 188 189 if (CC_UNLIKELY(ATRACE_ENABLED() && properties.promotedToLayer())) { 190 // pretend alpha always causes savelayer to warn about 191 // performance problem affecting old versions 192 ATRACE_FORMAT("%s alpha caused saveLayer %dx%d", node.getName(), width, height); 193 } 194 } 195 if (clipFlags) { 196 Rect clipRect; 197 properties.getClippingRectForFlags(clipFlags, &clipRect); 198 mCanvasState.clipRect(clipRect.left, clipRect.top, clipRect.right, clipRect.bottom, 199 SkRegion::kIntersect_Op); 200 } 201 202 if (properties.getRevealClip().willClip()) { 203 Rect bounds; 204 properties.getRevealClip().getBounds(&bounds); 205 mCanvasState.setClippingRoundRect(mAllocator, 206 bounds, properties.getRevealClip().getRadius()); 207 } else if (properties.getOutline().willClip()) { 208 mCanvasState.setClippingOutline(mAllocator, &(properties.getOutline())); 209 } 210 211 bool quickRejected = properties.getClipToBounds() 212 && mCanvasState.quickRejectConservative(0, 0, width, height); 213 if (!quickRejected) { 214 // not rejected, so defer render as either Layer, or direct (possibly wrapped in saveLayer) 215 if (node.getLayer()) { 216 // HW layer 217 LayerOp* drawLayerOp = new (mAllocator) LayerOp(node); 218 BakedOpState* bakedOpState = tryBakeOpState(*drawLayerOp); 219 if (bakedOpState) { 220 // Node's layer already deferred, schedule it to render into parent layer 221 currentLayer().deferUnmergeableOp(mAllocator, bakedOpState, OpBatchType::Bitmap); 222 } 223 } else if (CC_UNLIKELY(!saveLayerBounds.isEmpty())) { 224 // draw DisplayList contents within temporary, since persisted layer could not be used. 225 // (temp layers are clipped to viewport, since they don't persist offscreen content) 226 SkPaint saveLayerPaint; 227 saveLayerPaint.setAlpha(properties.getAlpha()); 228 deferBeginLayerOp(*new (mAllocator) BeginLayerOp( 229 saveLayerBounds, 230 Matrix4::identity(), 231 nullptr, // no record-time clip - need only respect defer-time one 232 &saveLayerPaint)); 233 deferNodeOps(node); 234 deferEndLayerOp(*new (mAllocator) EndLayerOp()); 235 } else { 236 deferNodeOps(node); 237 } 238 } 239} 240 241typedef key_value_pair_t<float, const RenderNodeOp*> ZRenderNodeOpPair; 242 243template <typename V> 244static void buildZSortedChildList(V* zTranslatedNodes, 245 const DisplayList& displayList, const DisplayList::Chunk& chunk) { 246 if (chunk.beginChildIndex == chunk.endChildIndex) return; 247 248 for (size_t i = chunk.beginChildIndex; i < chunk.endChildIndex; i++) { 249 RenderNodeOp* childOp = displayList.getChildren()[i]; 250 RenderNode* child = childOp->renderNode; 251 float childZ = child->properties().getZ(); 252 253 if (!MathUtils::isZero(childZ) && chunk.reorderChildren) { 254 zTranslatedNodes->push_back(ZRenderNodeOpPair(childZ, childOp)); 255 childOp->skipInOrderDraw = true; 256 } else if (!child->properties().getProjectBackwards()) { 257 // regular, in order drawing DisplayList 258 childOp->skipInOrderDraw = false; 259 } 260 } 261 262 // Z sort any 3d children (stable-ness makes z compare fall back to standard drawing order) 263 std::stable_sort(zTranslatedNodes->begin(), zTranslatedNodes->end()); 264} 265 266template <typename V> 267static size_t findNonNegativeIndex(const V& zTranslatedNodes) { 268 for (size_t i = 0; i < zTranslatedNodes.size(); i++) { 269 if (zTranslatedNodes[i].key >= 0.0f) return i; 270 } 271 return zTranslatedNodes.size(); 272} 273 274template <typename V> 275void FrameBuilder::defer3dChildren(ChildrenSelectMode mode, const V& zTranslatedNodes) { 276 const int size = zTranslatedNodes.size(); 277 if (size == 0 278 || (mode == ChildrenSelectMode::Negative&& zTranslatedNodes[0].key > 0.0f) 279 || (mode == ChildrenSelectMode::Positive && zTranslatedNodes[size - 1].key < 0.0f)) { 280 // no 3d children to draw 281 return; 282 } 283 284 /** 285 * Draw shadows and (potential) casters mostly in order, but allow the shadows of casters 286 * with very similar Z heights to draw together. 287 * 288 * This way, if Views A & B have the same Z height and are both casting shadows, the shadows are 289 * underneath both, and neither's shadow is drawn on top of the other. 290 */ 291 const size_t nonNegativeIndex = findNonNegativeIndex(zTranslatedNodes); 292 size_t drawIndex, shadowIndex, endIndex; 293 if (mode == ChildrenSelectMode::Negative) { 294 drawIndex = 0; 295 endIndex = nonNegativeIndex; 296 shadowIndex = endIndex; // draw no shadows 297 } else { 298 drawIndex = nonNegativeIndex; 299 endIndex = size; 300 shadowIndex = drawIndex; // potentially draw shadow for each pos Z child 301 } 302 303 float lastCasterZ = 0.0f; 304 while (shadowIndex < endIndex || drawIndex < endIndex) { 305 if (shadowIndex < endIndex) { 306 const RenderNodeOp* casterNodeOp = zTranslatedNodes[shadowIndex].value; 307 const float casterZ = zTranslatedNodes[shadowIndex].key; 308 // attempt to render the shadow if the caster about to be drawn is its caster, 309 // OR if its caster's Z value is similar to the previous potential caster 310 if (shadowIndex == drawIndex || casterZ - lastCasterZ < 0.1f) { 311 deferShadow(*casterNodeOp); 312 313 lastCasterZ = casterZ; // must do this even if current caster not casting a shadow 314 shadowIndex++; 315 continue; 316 } 317 } 318 319 const RenderNodeOp* childOp = zTranslatedNodes[drawIndex].value; 320 deferRenderNodeOpImpl(*childOp); 321 drawIndex++; 322 } 323} 324 325void FrameBuilder::deferShadow(const RenderNodeOp& casterNodeOp) { 326 auto& node = *casterNodeOp.renderNode; 327 auto& properties = node.properties(); 328 329 if (properties.getAlpha() <= 0.0f 330 || properties.getOutline().getAlpha() <= 0.0f 331 || !properties.getOutline().getPath() 332 || properties.getScaleX() == 0 333 || properties.getScaleY() == 0) { 334 // no shadow to draw 335 return; 336 } 337 338 const SkPath* casterOutlinePath = properties.getOutline().getPath(); 339 const SkPath* revealClipPath = properties.getRevealClip().getPath(); 340 if (revealClipPath && revealClipPath->isEmpty()) return; 341 342 float casterAlpha = properties.getAlpha() * properties.getOutline().getAlpha(); 343 344 // holds temporary SkPath to store the result of intersections 345 SkPath* frameAllocatedPath = nullptr; 346 const SkPath* casterPath = casterOutlinePath; 347 348 // intersect the shadow-casting path with the reveal, if present 349 if (revealClipPath) { 350 frameAllocatedPath = createFrameAllocatedPath(); 351 352 Op(*casterPath, *revealClipPath, kIntersect_SkPathOp, frameAllocatedPath); 353 casterPath = frameAllocatedPath; 354 } 355 356 // intersect the shadow-casting path with the clipBounds, if present 357 if (properties.getClippingFlags() & CLIP_TO_CLIP_BOUNDS) { 358 if (!frameAllocatedPath) { 359 frameAllocatedPath = createFrameAllocatedPath(); 360 } 361 Rect clipBounds; 362 properties.getClippingRectForFlags(CLIP_TO_CLIP_BOUNDS, &clipBounds); 363 SkPath clipBoundsPath; 364 clipBoundsPath.addRect(clipBounds.left, clipBounds.top, 365 clipBounds.right, clipBounds.bottom); 366 367 Op(*casterPath, clipBoundsPath, kIntersect_SkPathOp, frameAllocatedPath); 368 casterPath = frameAllocatedPath; 369 } 370 371 ShadowOp* shadowOp = new (mAllocator) ShadowOp(casterNodeOp, casterAlpha, casterPath, 372 mCanvasState.getLocalClipBounds(), 373 mCanvasState.currentSnapshot()->getRelativeLightCenter()); 374 BakedOpState* bakedOpState = BakedOpState::tryShadowOpConstruct( 375 mAllocator, *mCanvasState.writableSnapshot(), shadowOp); 376 if (CC_LIKELY(bakedOpState)) { 377 currentLayer().deferUnmergeableOp(mAllocator, bakedOpState, OpBatchType::Shadow); 378 } 379} 380 381void FrameBuilder::deferProjectedChildren(const RenderNode& renderNode) { 382 const SkPath* projectionReceiverOutline = renderNode.properties().getOutline().getPath(); 383 int count = mCanvasState.save(SaveFlags::MatrixClip); 384 385 // can't be null, since DL=null node rejection happens before deferNodePropsAndOps 386 const DisplayList& displayList = *(renderNode.getDisplayList()); 387 388 const RecordedOp* op = (displayList.getOps()[displayList.projectionReceiveIndex]); 389 const RenderNodeOp* backgroundOp = static_cast<const RenderNodeOp*>(op); 390 const RenderProperties& backgroundProps = backgroundOp->renderNode->properties(); 391 392 // Transform renderer to match background we're projecting onto 393 // (by offsetting canvas by translationX/Y of background rendernode, since only those are set) 394 mCanvasState.translate(backgroundProps.getTranslationX(), backgroundProps.getTranslationY()); 395 396 // If the projection receiver has an outline, we mask projected content to it 397 // (which we know, apriori, are all tessellated paths) 398 mCanvasState.setProjectionPathMask(mAllocator, projectionReceiverOutline); 399 400 // draw projected nodes 401 for (size_t i = 0; i < renderNode.mProjectedNodes.size(); i++) { 402 RenderNodeOp* childOp = renderNode.mProjectedNodes[i]; 403 404 int restoreTo = mCanvasState.save(SaveFlags::Matrix); 405 mCanvasState.concatMatrix(childOp->transformFromCompositingAncestor); 406 deferRenderNodeOpImpl(*childOp); 407 mCanvasState.restoreToCount(restoreTo); 408 } 409 410 mCanvasState.restoreToCount(count); 411} 412 413/** 414 * Used to define a list of lambdas referencing private FrameBuilder::onXX::defer() methods. 415 * 416 * This allows opIds embedded in the RecordedOps to be used for dispatching to these lambdas. 417 * E.g. a BitmapOp op then would be dispatched to FrameBuilder::onBitmapOp(const BitmapOp&) 418 */ 419#define OP_RECEIVER(Type) \ 420 [](FrameBuilder& frameBuilder, const RecordedOp& op) { frameBuilder.defer##Type(static_cast<const Type&>(op)); }, 421void FrameBuilder::deferNodeOps(const RenderNode& renderNode) { 422 typedef void (*OpDispatcher) (FrameBuilder& frameBuilder, const RecordedOp& op); 423 static OpDispatcher receivers[] = BUILD_DEFERRABLE_OP_LUT(OP_RECEIVER); 424 425 // can't be null, since DL=null node rejection happens before deferNodePropsAndOps 426 const DisplayList& displayList = *(renderNode.getDisplayList()); 427 for (const DisplayList::Chunk& chunk : displayList.getChunks()) { 428 FatVector<ZRenderNodeOpPair, 16> zTranslatedNodes; 429 buildZSortedChildList(&zTranslatedNodes, displayList, chunk); 430 431 defer3dChildren(ChildrenSelectMode::Negative, zTranslatedNodes); 432 for (size_t opIndex = chunk.beginOpIndex; opIndex < chunk.endOpIndex; opIndex++) { 433 const RecordedOp* op = displayList.getOps()[opIndex]; 434 receivers[op->opId](*this, *op); 435 436 if (CC_UNLIKELY(!renderNode.mProjectedNodes.empty() 437 && displayList.projectionReceiveIndex >= 0 438 && static_cast<int>(opIndex) == displayList.projectionReceiveIndex)) { 439 deferProjectedChildren(renderNode); 440 } 441 } 442 defer3dChildren(ChildrenSelectMode::Positive, zTranslatedNodes); 443 } 444} 445 446void FrameBuilder::deferRenderNodeOpImpl(const RenderNodeOp& op) { 447 if (op.renderNode->nothingToDraw()) return; 448 int count = mCanvasState.save(SaveFlags::MatrixClip); 449 450 // apply state from RecordedOp (clip first, since op's clip is transformed by current matrix) 451 mCanvasState.writableSnapshot()->mutateClipArea().applyClip(op.localClip, 452 *mCanvasState.currentSnapshot()->transform); 453 mCanvasState.concatMatrix(op.localMatrix); 454 455 // then apply state from node properties, and defer ops 456 deferNodePropsAndOps(*op.renderNode); 457 458 mCanvasState.restoreToCount(count); 459} 460 461void FrameBuilder::deferRenderNodeOp(const RenderNodeOp& op) { 462 if (!op.skipInOrderDraw) { 463 deferRenderNodeOpImpl(op); 464 } 465} 466 467/** 468 * Defers an unmergeable, strokeable op, accounting correctly 469 * for paint's style on the bounds being computed. 470 */ 471void FrameBuilder::deferStrokeableOp(const RecordedOp& op, batchid_t batchId, 472 BakedOpState::StrokeBehavior strokeBehavior) { 473 // Note: here we account for stroke when baking the op 474 BakedOpState* bakedState = BakedOpState::tryStrokeableOpConstruct( 475 mAllocator, *mCanvasState.writableSnapshot(), op, strokeBehavior); 476 if (!bakedState) return; // quick rejected 477 currentLayer().deferUnmergeableOp(mAllocator, bakedState, batchId); 478} 479 480/** 481 * Returns batch id for tessellatable shapes, based on paint. Checks to see if path effect/AA will 482 * be used, since they trigger significantly different rendering paths. 483 * 484 * Note: not used for lines/points, since they don't currently support path effects. 485 */ 486static batchid_t tessBatchId(const RecordedOp& op) { 487 const SkPaint& paint = *(op.paint); 488 return paint.getPathEffect() 489 ? OpBatchType::AlphaMaskTexture 490 : (paint.isAntiAlias() ? OpBatchType::AlphaVertices : OpBatchType::Vertices); 491} 492 493void FrameBuilder::deferArcOp(const ArcOp& op) { 494 deferStrokeableOp(op, tessBatchId(op)); 495} 496 497static bool hasMergeableClip(const BakedOpState& state) { 498 return state.computedState.clipState 499 || state.computedState.clipState->mode == ClipMode::Rectangle; 500} 501 502void FrameBuilder::deferBitmapOp(const BitmapOp& op) { 503 BakedOpState* bakedState = tryBakeOpState(op); 504 if (!bakedState) return; // quick rejected 505 506 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Bitmap); 507 508 // TODO: Fix this ( b/26569206 ) 509/* 510 // Don't merge non-simply transformed or neg scale ops, SET_TEXTURE doesn't handle rotation 511 // Don't merge A8 bitmaps - the paint's color isn't compared by mergeId, or in 512 // MergingDrawBatch::canMergeWith() 513 if (bakedState->computedState.transform.isSimple() 514 && bakedState->computedState.transform.positiveScale() 515 && PaintUtils::getXfermodeDirect(op.paint) == SkXfermode::kSrcOver_Mode 516 && op.bitmap->colorType() != kAlpha_8_SkColorType 517 && hasMergeableClip(*bakedState)) { 518 mergeid_t mergeId = reinterpret_cast<mergeid_t>(op.bitmap->getGenerationID()); 519 // TODO: AssetAtlas in mergeId 520 currentLayer().deferMergeableOp(mAllocator, bakedState, OpBatchType::Bitmap, mergeId); 521 } else { 522 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Bitmap); 523 } 524*/ 525} 526 527void FrameBuilder::deferBitmapMeshOp(const BitmapMeshOp& op) { 528 BakedOpState* bakedState = tryBakeOpState(op); 529 if (!bakedState) return; // quick rejected 530 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Bitmap); 531} 532 533void FrameBuilder::deferBitmapRectOp(const BitmapRectOp& op) { 534 BakedOpState* bakedState = tryBakeOpState(op); 535 if (!bakedState) return; // quick rejected 536 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Bitmap); 537} 538 539void FrameBuilder::deferCirclePropsOp(const CirclePropsOp& op) { 540 // allocate a temporary oval op (with mAllocator, so it persists until render), so the 541 // renderer doesn't have to handle the RoundRectPropsOp type, and so state baking is simple. 542 float x = *(op.x); 543 float y = *(op.y); 544 float radius = *(op.radius); 545 Rect unmappedBounds(x - radius, y - radius, x + radius, y + radius); 546 const OvalOp* resolvedOp = new (mAllocator) OvalOp( 547 unmappedBounds, 548 op.localMatrix, 549 op.localClip, 550 op.paint); 551 deferOvalOp(*resolvedOp); 552} 553 554void FrameBuilder::deferFunctorOp(const FunctorOp& op) { 555 BakedOpState* bakedState = tryBakeOpState(op); 556 if (!bakedState) return; // quick rejected 557 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Functor); 558} 559 560void FrameBuilder::deferLinesOp(const LinesOp& op) { 561 batchid_t batch = op.paint->isAntiAlias() ? OpBatchType::AlphaVertices : OpBatchType::Vertices; 562 deferStrokeableOp(op, batch, BakedOpState::StrokeBehavior::Forced); 563} 564 565void FrameBuilder::deferOvalOp(const OvalOp& op) { 566 deferStrokeableOp(op, tessBatchId(op)); 567} 568 569void FrameBuilder::deferPatchOp(const PatchOp& op) { 570 BakedOpState* bakedState = tryBakeOpState(op); 571 if (!bakedState) return; // quick rejected 572 573 if (bakedState->computedState.transform.isPureTranslate() 574 && PaintUtils::getXfermodeDirect(op.paint) == SkXfermode::kSrcOver_Mode 575 && hasMergeableClip(*bakedState)) { 576 mergeid_t mergeId = reinterpret_cast<mergeid_t>(op.bitmap->getGenerationID()); 577 // TODO: AssetAtlas in mergeId 578 579 // Only use the MergedPatch batchId when merged, so Bitmap+Patch don't try to merge together 580 currentLayer().deferMergeableOp(mAllocator, bakedState, OpBatchType::MergedPatch, mergeId); 581 } else { 582 // Use Bitmap batchId since Bitmap+Patch use same shader 583 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Bitmap); 584 } 585} 586 587void FrameBuilder::deferPathOp(const PathOp& op) { 588 deferStrokeableOp(op, OpBatchType::Bitmap); 589} 590 591void FrameBuilder::deferPointsOp(const PointsOp& op) { 592 batchid_t batch = op.paint->isAntiAlias() ? OpBatchType::AlphaVertices : OpBatchType::Vertices; 593 deferStrokeableOp(op, batch, BakedOpState::StrokeBehavior::Forced); 594} 595 596void FrameBuilder::deferRectOp(const RectOp& op) { 597 deferStrokeableOp(op, tessBatchId(op)); 598} 599 600void FrameBuilder::deferRoundRectOp(const RoundRectOp& op) { 601 deferStrokeableOp(op, tessBatchId(op)); 602} 603 604void FrameBuilder::deferRoundRectPropsOp(const RoundRectPropsOp& op) { 605 // allocate a temporary round rect op (with mAllocator, so it persists until render), so the 606 // renderer doesn't have to handle the RoundRectPropsOp type, and so state baking is simple. 607 const RoundRectOp* resolvedOp = new (mAllocator) RoundRectOp( 608 Rect(*(op.left), *(op.top), *(op.right), *(op.bottom)), 609 op.localMatrix, 610 op.localClip, 611 op.paint, *op.rx, *op.ry); 612 deferRoundRectOp(*resolvedOp); 613} 614 615void FrameBuilder::deferSimpleRectsOp(const SimpleRectsOp& op) { 616 BakedOpState* bakedState = tryBakeOpState(op); 617 if (!bakedState) return; // quick rejected 618 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Vertices); 619} 620 621static batchid_t textBatchId(const SkPaint& paint) { 622 // TODO: better handling of shader (since we won't care about color then) 623 return paint.getColor() == SK_ColorBLACK ? OpBatchType::Text : OpBatchType::ColorText; 624} 625 626void FrameBuilder::deferTextOp(const TextOp& op) { 627 BakedOpState* bakedState = tryBakeOpState(op); 628 if (!bakedState) return; // quick rejected 629 630 batchid_t batchId = textBatchId(*(op.paint)); 631 if (bakedState->computedState.transform.isPureTranslate() 632 && PaintUtils::getXfermodeDirect(op.paint) == SkXfermode::kSrcOver_Mode 633 && hasMergeableClip(*bakedState)) { 634 mergeid_t mergeId = reinterpret_cast<mergeid_t>(op.paint->getColor()); 635 currentLayer().deferMergeableOp(mAllocator, bakedState, batchId, mergeId); 636 } else { 637 currentLayer().deferUnmergeableOp(mAllocator, bakedState, batchId); 638 } 639} 640 641void FrameBuilder::deferTextOnPathOp(const TextOnPathOp& op) { 642 BakedOpState* bakedState = tryBakeOpState(op); 643 if (!bakedState) return; // quick rejected 644 currentLayer().deferUnmergeableOp(mAllocator, bakedState, textBatchId(*(op.paint))); 645} 646 647void FrameBuilder::deferTextureLayerOp(const TextureLayerOp& op) { 648 BakedOpState* bakedState = tryBakeOpState(op); 649 if (!bakedState) return; // quick rejected 650 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::TextureLayer); 651} 652 653void FrameBuilder::saveForLayer(uint32_t layerWidth, uint32_t layerHeight, 654 float contentTranslateX, float contentTranslateY, 655 const Rect& repaintRect, 656 const Vector3& lightCenter, 657 const BeginLayerOp* beginLayerOp, RenderNode* renderNode) { 658 mCanvasState.save(SaveFlags::MatrixClip); 659 mCanvasState.writableSnapshot()->initializeViewport(layerWidth, layerHeight); 660 mCanvasState.writableSnapshot()->roundRectClipState = nullptr; 661 mCanvasState.writableSnapshot()->setRelativeLightCenter(lightCenter); 662 mCanvasState.writableSnapshot()->transform->loadTranslate( 663 contentTranslateX, contentTranslateY, 0); 664 mCanvasState.writableSnapshot()->setClip( 665 repaintRect.left, repaintRect.top, repaintRect.right, repaintRect.bottom); 666 667 // create a new layer repaint, and push its index on the stack 668 mLayerStack.push_back(mLayerBuilders.size()); 669 auto newFbo = mAllocator.create<LayerBuilder>(layerWidth, layerHeight, 670 repaintRect, beginLayerOp, renderNode); 671 mLayerBuilders.push_back(newFbo); 672} 673 674void FrameBuilder::restoreForLayer() { 675 // restore canvas, and pop finished layer off of the stack 676 mCanvasState.restore(); 677 mLayerStack.pop_back(); 678} 679 680// TODO: defer time rejection (when bounds become empty) + tests 681// Option - just skip layers with no bounds at playback + defer? 682void FrameBuilder::deferBeginLayerOp(const BeginLayerOp& op) { 683 uint32_t layerWidth = (uint32_t) op.unmappedBounds.getWidth(); 684 uint32_t layerHeight = (uint32_t) op.unmappedBounds.getHeight(); 685 686 auto previous = mCanvasState.currentSnapshot(); 687 Vector3 lightCenter = previous->getRelativeLightCenter(); 688 689 // Combine all transforms used to present saveLayer content: 690 // parent content transform * canvas transform * bounds offset 691 Matrix4 contentTransform(*(previous->transform)); 692 contentTransform.multiply(op.localMatrix); 693 contentTransform.translate(op.unmappedBounds.left, op.unmappedBounds.top); 694 695 Matrix4 inverseContentTransform; 696 inverseContentTransform.loadInverse(contentTransform); 697 698 // map the light center into layer-relative space 699 inverseContentTransform.mapPoint3d(lightCenter); 700 701 // Clip bounds of temporary layer to parent's clip rect, so: 702 Rect saveLayerBounds(layerWidth, layerHeight); 703 // 1) transform Rect(width, height) into parent's space 704 // note: left/top offsets put in contentTransform above 705 contentTransform.mapRect(saveLayerBounds); 706 // 2) intersect with parent's clip 707 saveLayerBounds.doIntersect(previous->getRenderTargetClip()); 708 // 3) and transform back 709 inverseContentTransform.mapRect(saveLayerBounds); 710 saveLayerBounds.doIntersect(Rect(layerWidth, layerHeight)); 711 saveLayerBounds.roundOut(); 712 713 // if bounds are reduced, will clip the layer's area by reducing required bounds... 714 layerWidth = saveLayerBounds.getWidth(); 715 layerHeight = saveLayerBounds.getHeight(); 716 // ...and shifting drawing content to account for left/top side clipping 717 float contentTranslateX = -saveLayerBounds.left; 718 float contentTranslateY = -saveLayerBounds.top; 719 720 saveForLayer(layerWidth, layerHeight, 721 contentTranslateX, contentTranslateY, 722 Rect(layerWidth, layerHeight), 723 lightCenter, 724 &op, nullptr); 725} 726 727void FrameBuilder::deferEndLayerOp(const EndLayerOp& /* ignored */) { 728 const BeginLayerOp& beginLayerOp = *currentLayer().beginLayerOp; 729 int finishedLayerIndex = mLayerStack.back(); 730 731 restoreForLayer(); 732 733 // record the draw operation into the previous layer's list of draw commands 734 // uses state from the associated beginLayerOp, since it has all the state needed for drawing 735 LayerOp* drawLayerOp = new (mAllocator) LayerOp( 736 beginLayerOp.unmappedBounds, 737 beginLayerOp.localMatrix, 738 beginLayerOp.localClip, 739 beginLayerOp.paint, 740 &(mLayerBuilders[finishedLayerIndex]->offscreenBuffer)); 741 BakedOpState* bakedOpState = tryBakeOpState(*drawLayerOp); 742 743 if (bakedOpState) { 744 // Layer will be drawn into parent layer (which is now current, since we popped mLayerStack) 745 currentLayer().deferUnmergeableOp(mAllocator, bakedOpState, OpBatchType::Bitmap); 746 } else { 747 // Layer won't be drawn - delete its drawing batches to prevent it from doing any work 748 // TODO: need to prevent any render work from being done 749 // - create layerop earlier for reject purposes? 750 mLayerBuilders[finishedLayerIndex]->clear(); 751 return; 752 } 753} 754 755void FrameBuilder::deferBeginUnclippedLayerOp(const BeginUnclippedLayerOp& op) { 756 Matrix4 boundsTransform(*(mCanvasState.currentSnapshot()->transform)); 757 boundsTransform.multiply(op.localMatrix); 758 759 Rect dstRect(op.unmappedBounds); 760 boundsTransform.mapRect(dstRect); 761 dstRect.doIntersect(mCanvasState.currentSnapshot()->getRenderTargetClip()); 762 763 // Allocate a holding position for the layer object (copyTo will produce, copyFrom will consume) 764 OffscreenBuffer** layerHandle = mAllocator.create<OffscreenBuffer*>(nullptr); 765 766 /** 767 * First, defer an operation to copy out the content from the rendertarget into a layer. 768 */ 769 auto copyToOp = new (mAllocator) CopyToLayerOp(op, layerHandle); 770 BakedOpState* bakedState = BakedOpState::directConstruct(mAllocator, 771 &(currentLayer().viewportClip), dstRect, *copyToOp); 772 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::CopyToLayer); 773 774 /** 775 * Defer a clear rect, so that clears from multiple unclipped layers can be drawn 776 * both 1) simultaneously, and 2) as long after the copyToLayer executes as possible 777 */ 778 currentLayer().deferLayerClear(dstRect); 779 780 /** 781 * And stash an operation to copy that layer back under the rendertarget until 782 * a balanced EndUnclippedLayerOp is seen 783 */ 784 auto copyFromOp = new (mAllocator) CopyFromLayerOp(op, layerHandle); 785 bakedState = BakedOpState::directConstruct(mAllocator, 786 &(currentLayer().viewportClip), dstRect, *copyFromOp); 787 currentLayer().activeUnclippedSaveLayers.push_back(bakedState); 788} 789 790void FrameBuilder::deferEndUnclippedLayerOp(const EndUnclippedLayerOp& /* ignored */) { 791 LOG_ALWAYS_FATAL_IF(currentLayer().activeUnclippedSaveLayers.empty(), "no layer to end!"); 792 793 BakedOpState* copyFromLayerOp = currentLayer().activeUnclippedSaveLayers.back(); 794 currentLayer().deferUnmergeableOp(mAllocator, copyFromLayerOp, OpBatchType::CopyFromLayer); 795 currentLayer().activeUnclippedSaveLayers.pop_back(); 796} 797 798} // namespace uirenderer 799} // namespace android 800