blob: 6914bed3138b326d5d01a3703e2a363213454d48 [file] [log] [blame]
[email protected]94f206c12012-08-25 00:09:141// Copyright 2011 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5
6#include "config.h"
7
8#include "CCLayerTreeHostCommon.h"
9
10#include "CCLayerImpl.h"
11#include "CCLayerIterator.h"
12#include "CCLayerSorter.h"
13#include "CCMathUtil.h"
14#include "CCRenderSurface.h"
15#include "FloatQuad.h"
16#include "IntRect.h"
17#include "LayerChromium.h"
18#include "RenderSurfaceChromium.h"
19#include <public/WebTransformationMatrix.h>
20
21using WebKit::WebTransformationMatrix;
22
[email protected]9c88e562012-09-14 22:21:3023namespace cc {
[email protected]94f206c12012-08-25 00:09:1424
[email protected]493067512012-09-19 23:34:1025CCScrollAndScaleSet::CCScrollAndScaleSet()
26{
27}
28
29CCScrollAndScaleSet::~CCScrollAndScaleSet()
30{
31}
32
[email protected]94f206c12012-08-25 00:09:1433IntRect CCLayerTreeHostCommon::calculateVisibleRect(const IntRect& targetSurfaceRect, const IntRect& layerBoundRect, const WebTransformationMatrix& transform)
34{
35 // Is this layer fully contained within the target surface?
36 IntRect layerInSurfaceSpace = CCMathUtil::mapClippedRect(transform, layerBoundRect);
37 if (targetSurfaceRect.contains(layerInSurfaceSpace))
38 return layerBoundRect;
39
40 // If the layer doesn't fill up the entire surface, then find the part of
41 // the surface rect where the layer could be visible. This avoids trying to
42 // project surface rect points that are behind the projection point.
43 IntRect minimalSurfaceRect = targetSurfaceRect;
44 minimalSurfaceRect.intersect(layerInSurfaceSpace);
45
46 // Project the corners of the target surface rect into the layer space.
47 // This bounding rectangle may be larger than it needs to be (being
48 // axis-aligned), but is a reasonable filter on the space to consider.
49 // Non-invertible transforms will create an empty rect here.
50 const WebTransformationMatrix surfaceToLayer = transform.inverse();
51 IntRect layerRect = enclosingIntRect(CCMathUtil::projectClippedRect(surfaceToLayer, FloatRect(minimalSurfaceRect)));
52 layerRect.intersect(layerBoundRect);
53 return layerRect;
54}
55
56template<typename LayerType>
57static inline bool layerIsInExisting3DRenderingContext(LayerType* layer)
58{
59 // According to current W3C spec on CSS transforms, a layer is part of an established
60 // 3d rendering context if its parent has transform-style of preserves-3d.
61 return layer->parent() && layer->parent()->preserves3D();
62}
63
64template<typename LayerType>
65static bool layerIsRootOfNewRenderingContext(LayerType* layer)
66{
67 // According to current W3C spec on CSS transforms (Section 6.1), a layer is the
68 // beginning of 3d rendering context if its parent does not have transform-style:
69 // preserve-3d, but this layer itself does.
70 if (layer->parent())
71 return !layer->parent()->preserves3D() && layer->preserves3D();
72
73 return layer->preserves3D();
74}
75
76template<typename LayerType>
77static bool isLayerBackFaceVisible(LayerType* layer)
78{
79 // The current W3C spec on CSS transforms says that backface visibility should be
80 // determined differently depending on whether the layer is in a "3d rendering
81 // context" or not. For Chromium code, we can determine whether we are in a 3d
82 // rendering context by checking if the parent preserves 3d.
83
84 if (layerIsInExisting3DRenderingContext(layer))
85 return layer->drawTransform().isBackFaceVisible();
86
87 // In this case, either the layer establishes a new 3d rendering context, or is not in
88 // a 3d rendering context at all.
89 return layer->transform().isBackFaceVisible();
90}
91
92template<typename LayerType>
93static bool isSurfaceBackFaceVisible(LayerType* layer, const WebTransformationMatrix& drawTransform)
94{
95 if (layerIsInExisting3DRenderingContext(layer))
96 return drawTransform.isBackFaceVisible();
97
98 if (layerIsRootOfNewRenderingContext(layer))
99 return layer->transform().isBackFaceVisible();
100
101 // If the renderSurface is not part of a new or existing rendering context, then the
102 // layers that contribute to this surface will decide back-face visibility for themselves.
103 return false;
104}
105
106template<typename LayerType>
107static inline bool layerClipsSubtree(LayerType* layer)
108{
109 return layer->masksToBounds() || layer->maskLayer();
110}
111
112template<typename LayerType>
113static IntRect calculateVisibleContentRect(LayerType* layer)
114{
115 ASSERT(layer->renderTarget());
116
117 IntRect targetSurfaceRect = layer->renderTarget()->renderSurface()->contentRect();
118
119 targetSurfaceRect.intersect(layer->drawableContentRect());
120
121 if (targetSurfaceRect.isEmpty() || layer->contentBounds().isEmpty())
122 return IntRect();
123
124 const IntRect contentRect = IntRect(IntPoint(), layer->contentBounds());
125 IntRect visibleContentRect = CCLayerTreeHostCommon::calculateVisibleRect(targetSurfaceRect, contentRect, layer->drawTransform());
126 return visibleContentRect;
127}
128
129static bool isScaleOrTranslation(const WebTransformationMatrix& m)
130{
131 return !m.m12() && !m.m13() && !m.m14()
132 && !m.m21() && !m.m23() && !m.m24()
133 && !m.m31() && !m.m32() && !m.m43()
134 && m.m44();
135}
136
137static inline bool transformToParentIsKnown(CCLayerImpl*)
138{
139 return true;
140}
141
142static inline bool transformToParentIsKnown(LayerChromium* layer)
143{
144 return !layer->transformIsAnimating();
145}
146
147static inline bool transformToScreenIsKnown(CCLayerImpl*)
148{
149 return true;
150}
151
152static inline bool transformToScreenIsKnown(LayerChromium* layer)
153{
154 return !layer->screenSpaceTransformIsAnimating();
155}
156
157template<typename LayerType>
158static bool layerShouldBeSkipped(LayerType* layer)
159{
160 // Layers can be skipped if any of these conditions are met.
161 // - does not draw content.
162 // - is transparent
163 // - has empty bounds
164 // - the layer is not double-sided, but its back face is visible.
165 //
166 // Some additional conditions need to be computed at a later point after the recursion is finished.
167 // - the intersection of render surface content and layer clipRect is empty
168 // - the visibleContentRect is empty
169 //
170 // Note, if the layer should not have been drawn due to being fully transparent,
171 // we would have skipped the entire subtree and never made it into this function,
172 // so it is safe to omit this check here.
173
174 if (!layer->drawsContent() || layer->bounds().isEmpty())
175 return true;
176
177 LayerType* backfaceTestLayer = layer;
178 if (layer->useParentBackfaceVisibility()) {
179 ASSERT(layer->parent());
180 ASSERT(!layer->parent()->useParentBackfaceVisibility());
181 backfaceTestLayer = layer->parent();
182 }
183
184 // The layer should not be drawn if (1) it is not double-sided and (2) the back of the layer is known to be facing the screen.
185 if (!backfaceTestLayer->doubleSided() && transformToScreenIsKnown(backfaceTestLayer) && isLayerBackFaceVisible(backfaceTestLayer))
186 return true;
187
188 return false;
189}
190
191static inline bool subtreeShouldBeSkipped(CCLayerImpl* layer)
192{
193 // The opacity of a layer always applies to its children (either implicitly
194 // via a render surface or explicitly if the parent preserves 3D), so the
195 // entire subtree can be skipped if this layer is fully transparent.
196 return !layer->opacity();
197}
198
199static inline bool subtreeShouldBeSkipped(LayerChromium* layer)
200{
201 // If the opacity is being animated then the opacity on the main thread is unreliable
202 // (since the impl thread may be using a different opacity), so it should not be trusted.
203 // In particular, it should not cause the subtree to be skipped.
204 return !layer->opacity() && !layer->opacityIsAnimating();
205}
206
207template<typename LayerType>
208static bool subtreeShouldRenderToSeparateSurface(LayerType* layer, bool axisAlignedWithRespectToParent)
209{
210 // The root layer has a special render surface that is set up externally, so
211 // it shouldn't be treated as a surface in this code.
212 if (!layer->parent())
213 return false;
214
215 // Cache this value, because otherwise it walks the entire subtree several times.
216 bool descendantDrawsContent = layer->descendantDrawsContent();
217
218 //
219 // A layer and its descendants should render onto a new RenderSurface if any of these rules hold:
220 //
221
222 // If we force it.
223 if (layer->forceRenderSurface())
224 return true;
225
226 // If the layer uses a mask.
227 if (layer->maskLayer())
228 return true;
229
230 // If the layer has a reflection.
231 if (layer->replicaLayer())
232 return true;
233
234 // If the layer uses a CSS filter.
235 if (!layer->filters().isEmpty() || !layer->backgroundFilters().isEmpty())
236 return true;
237
238 // If the layer flattens its subtree (i.e. the layer doesn't preserve-3d), but it is
239 // treated as a 3D object by its parent (i.e. parent does preserve-3d).
240 if (layerIsInExisting3DRenderingContext(layer) && !layer->preserves3D() && descendantDrawsContent)
241 return true;
242
243 // If the layer clips its descendants but it is not axis-aligned with respect to its parent.
244 if (layerClipsSubtree(layer) && !axisAlignedWithRespectToParent && descendantDrawsContent)
245 return true;
246
247 // If the layer has opacity != 1 and does not have a preserves-3d transform style.
248 if (layer->opacity() != 1 && !layer->preserves3D() && descendantDrawsContent)
249 return true;
250
251 return false;
252}
253
254WebTransformationMatrix computeScrollCompensationForThisLayer(CCLayerImpl* scrollingLayer, const WebTransformationMatrix& parentMatrix)
255{
256 // For every layer that has non-zero scrollDelta, we have to compute a transform that can undo the
257 // scrollDelta translation. In particular, we want this matrix to premultiply a fixed-position layer's
258 // parentMatrix, so we design this transform in three steps as follows. The steps described here apply
259 // from right-to-left, so Step 1 would be the right-most matrix:
260 //
261 // Step 1. transform from target surface space to the exact space where scrollDelta is actually applied.
262 // -- this is inverse of the matrix in step 3
263 // Step 2. undo the scrollDelta
264 // -- this is just a translation by scrollDelta.
265 // Step 3. transform back to target surface space.
266 // -- this transform is the "partialLayerOriginTransform" = (parentMatrix * scale(layer->pageScaleDelta()));
267 //
268 // These steps create a matrix that both start and end in targetSurfaceSpace. So this matrix can
269 // pre-multiply any fixed-position layer's drawTransform to undo the scrollDeltas -- as long as
270 // that fixed position layer is fixed onto the same renderTarget as this scrollingLayer.
271 //
272
273 WebTransformationMatrix partialLayerOriginTransform = parentMatrix;
274 partialLayerOriginTransform.scale(scrollingLayer->pageScaleDelta());
275
276 WebTransformationMatrix scrollCompensationForThisLayer = partialLayerOriginTransform; // Step 3
277 scrollCompensationForThisLayer.translate(scrollingLayer->scrollDelta().width(), scrollingLayer->scrollDelta().height()); // Step 2
278 scrollCompensationForThisLayer.multiply(partialLayerOriginTransform.inverse()); // Step 1
279 return scrollCompensationForThisLayer;
280}
281
282WebTransformationMatrix computeScrollCompensationMatrixForChildren(LayerChromium* currentLayer, const WebTransformationMatrix& currentParentMatrix, const WebTransformationMatrix& currentScrollCompensation)
283{
284 // The main thread (i.e. LayerChromium) does not need to worry about scroll compensation.
285 // So we can just return an identity matrix here.
286 return WebTransformationMatrix();
287}
288
289WebTransformationMatrix computeScrollCompensationMatrixForChildren(CCLayerImpl* layer, const WebTransformationMatrix& parentMatrix, const WebTransformationMatrix& currentScrollCompensationMatrix)
290{
291 // "Total scroll compensation" is the transform needed to cancel out all scrollDelta translations that
292 // occurred since the nearest container layer, even if there are renderSurfaces in-between.
293 //
294 // There are some edge cases to be aware of, that are not explicit in the code:
295 // - A layer that is both a fixed-position and container should not be its own container, instead, that means
296 // it is fixed to an ancestor, and is a container for any fixed-position descendants.
297 // - A layer that is a fixed-position container and has a renderSurface should behave the same as a container
298 // without a renderSurface, the renderSurface is irrelevant in that case.
299 // - A layer that does not have an explicit container is simply fixed to the viewport
300 // (i.e. the root renderSurface, and it would still compensate for root layer's scrollDelta).
301 // - If the fixed-position layer has its own renderSurface, then the renderSurface is
302 // the one who gets fixed.
303 //
304 // This function needs to be called AFTER layers create their own renderSurfaces.
305 //
306
307 // Avoid the overheads (including stack allocation and matrix initialization/copy) if we know that the scroll compensation doesn't need to be reset or adjusted.
308 if (!layer->isContainerForFixedPositionLayers() && layer->scrollDelta().isZero() && !layer->renderSurface())
309 return currentScrollCompensationMatrix;
310
311 // Start as identity matrix.
312 WebTransformationMatrix nextScrollCompensationMatrix;
313
314 // If this layer is not a container, then it inherits the existing scroll compensations.
315 if (!layer->isContainerForFixedPositionLayers())
316 nextScrollCompensationMatrix = currentScrollCompensationMatrix;
317
318 // If the current layer has a non-zero scrollDelta, then we should compute its local scrollCompensation
319 // and accumulate it to the nextScrollCompensationMatrix.
320 if (!layer->scrollDelta().isZero()) {
321 WebTransformationMatrix scrollCompensationForThisLayer = computeScrollCompensationForThisLayer(layer, parentMatrix);
322 nextScrollCompensationMatrix.multiply(scrollCompensationForThisLayer);
323 }
324
325 // If the layer created its own renderSurface, we have to adjust nextScrollCompensationMatrix.
326 // The adjustment allows us to continue using the scrollCompensation on the next surface.
327 // Step 1 (right-most in the math): transform from the new surface to the original ancestor surface
328 // Step 2: apply the scroll compensation
329 // Step 3: transform back to the new surface.
330 if (layer->renderSurface() && !nextScrollCompensationMatrix.isIdentity())
331 nextScrollCompensationMatrix = layer->renderSurface()->drawTransform().inverse() * nextScrollCompensationMatrix * layer->renderSurface()->drawTransform();
332
333 return nextScrollCompensationMatrix;
334}
335
336// Should be called just before the recursive calculateDrawTransformsInternal().
337template<typename LayerType, typename LayerList>
338void setupRootLayerAndSurfaceForRecursion(LayerType* rootLayer, LayerList& renderSurfaceLayerList, const IntSize& deviceViewportSize)
339{
340 if (!rootLayer->renderSurface())
341 rootLayer->createRenderSurface();
342
343 rootLayer->renderSurface()->setContentRect(IntRect(IntPoint::zero(), deviceViewportSize));
344 rootLayer->renderSurface()->clearLayerList();
345
346 ASSERT(renderSurfaceLayerList.isEmpty());
347 renderSurfaceLayerList.append(rootLayer);
348}
349
350// Recursively walks the layer tree starting at the given node and computes all the
351// necessary transformations, clipRects, render surfaces, etc.
352template<typename LayerType, typename LayerList, typename RenderSurfaceType, typename LayerSorter>
353static void calculateDrawTransformsInternal(LayerType* layer, LayerType* rootLayer, const WebTransformationMatrix& parentMatrix,
354 const WebTransformationMatrix& fullHierarchyMatrix, const WebTransformationMatrix& currentScrollCompensationMatrix,
355 const IntRect& clipRectFromAncestor, bool ancestorClipsSubtree,
356 RenderSurfaceType* nearestAncestorThatMovesPixels, LayerList& renderSurfaceLayerList, LayerList& layerList,
357 LayerSorter* layerSorter, int maxTextureSize, float deviceScaleFactor, IntRect& drawableContentRectOfSubtree)
358{
359 // This function computes the new matrix transformations recursively for this
360 // layer and all its descendants. It also computes the appropriate render surfaces.
361 // Some important points to remember:
362 //
363 // 0. Here, transforms are notated in Matrix x Vector order, and in words we describe what
364 // the transform does from left to right.
365 //
366 // 1. In our terminology, the "layer origin" refers to the top-left corner of a layer, and the
367 // positive Y-axis points downwards. This interpretation is valid because the orthographic
368 // projection applied at draw time flips the Y axis appropriately.
369 //
370 // 2. The anchor point, when given as a FloatPoint object, is specified in "unit layer space",
371 // where the bounds of the layer map to [0, 1]. However, as a WebTransformationMatrix object,
372 // the transform to the anchor point is specified in "pixel layer space", where the bounds
373 // of the layer map to [bounds.width(), bounds.height()].
374 //
375 // 3. Definition of various transforms used:
376 // M[parent] is the parent matrix, with respect to the nearest render surface, passed down recursively.
377 // M[root] is the full hierarchy, with respect to the root, passed down recursively.
378 // Tr[origin] is the translation matrix from the parent's origin to this layer's origin.
379 // Tr[origin2anchor] is the translation from the layer's origin to its anchor point
380 // Tr[origin2center] is the translation from the layer's origin to its center
381 // M[layer] is the layer's matrix (applied at the anchor point)
382 // M[sublayer] is the layer's sublayer transform (applied at the layer's center)
383 // Tr[anchor2center] is the translation offset from the anchor point and the center of the layer
384 // S[content2layer] is the ratio of a layer's contentBounds() to its bounds().
385 //
386 // Some shortcuts and substitutions are used in the code to reduce matrix multiplications:
387 // Tr[anchor2center] = Tr[origin2anchor].inverse() * Tr[origin2center]
388 //
389 // Some composite transforms can help in understanding the sequence of transforms:
390 // compositeLayerTransform = Tr[origin2anchor] * M[layer] * Tr[origin2anchor].inverse()
391 // compositeSublayerTransform = Tr[origin2center] * M[sublayer] * Tr[origin2center].inverse()
392 //
393 // In words, the layer transform is applied about the anchor point, and the sublayer transform is
394 // applied about the center of the layer.
395 //
396 // 4. When a layer (or render surface) is drawn, it is drawn into a "target render surface". Therefore the draw
397 // transform does not necessarily transform from screen space to local layer space. Instead, the draw transform
398 // is the transform between the "target render surface space" and local layer space. Note that render surfaces,
399 // except for the root, also draw themselves into a different target render surface, and so their draw
400 // transform and origin transforms are also described with respect to the target.
401 //
402 // Using these definitions, then:
403 //
404 // The draw transform for the layer is:
405 // M[draw] = M[parent] * Tr[origin] * compositeLayerTransform * S[content2layer]
406 // = M[parent] * Tr[layer->position()] * M[layer] * Tr[anchor2origin] * S[content2layer]
407 //
408 // Interpreting the math left-to-right, this transforms from the layer's render surface to the origin of the layer in content space.
409 //
410 // The screen space transform is:
411 // M[screenspace] = M[root] * Tr[origin] * compositeLayerTransform * S[content2layer]
412 // = M[root] * Tr[layer->position()] * M[layer] * Tr[origin2anchor].inverse() * S[content2layer]
413 //
414 // Interpreting the math left-to-right, this transforms from the root render surface's content space to the local layer's origin in layer space.
415 //
416 // The transform hierarchy that is passed on to children (i.e. the child's parentMatrix) is:
417 // M[parent]_for_child = M[parent] * Tr[origin] * compositeLayerTransform * compositeSublayerTransform
418 // = M[parent] * Tr[layer->position()] * M[layer] * Tr[anchor2center] * M[sublayer] * Tr[origin2center].inverse()
419 // = M[draw] * M[sublayer] * Tr[origin2center].inverse()
420 //
421 // and a similar matrix for the full hierarchy with respect to the root.
422 //
423 // Finally, note that the final matrix used by the shader for the layer is P * M[draw] * S . This final product
424 // is computed in drawTexturedQuad(), where:
425 // P is the projection matrix
426 // S is the scale adjustment (to scale up to the layer size)
427 //
428 // When a render surface has a replica layer, that layer's transform is used to draw a second copy of the surface.
429 // Transforms named here are relative to the surface, unless they specify they are relative to the replica layer.
430 //
431 // We will denote a scale by device scale S[deviceScale]
432 //
433 // The render surface draw transform to its target surface origin is:
434 // M[surfaceDraw] = M[owningLayer->Draw]
435 //
436 // The render surface origin transform to its the root (screen space) origin is:
437 // M[surface2root] = M[owningLayer->screenspace] * S[deviceScale].inverse()
438 //
439 // The replica draw transform to its target surface origin is:
440 // M[replicaDraw] = S[deviceScale] * M[surfaceDraw] * Tr[replica->position() + replica->anchor()] * Tr[replica] * Tr[origin2anchor].inverse() * S[contentsScale].inverse()
441 //
442 // The replica draw transform to the root (screen space) origin is:
443 // M[replica2root] = M[surface2root] * Tr[replica->position()] * Tr[replica] * Tr[origin2anchor].inverse()
444 //
445
446 // If we early-exit anywhere in this function, the drawableContentRect of this subtree should be considered empty.
447 drawableContentRectOfSubtree = IntRect();
448
449 if (subtreeShouldBeSkipped(layer))
450 return;
451
452 IntRect clipRectForSubtree;
453 bool subtreeShouldBeClipped = false;
454
455 float drawOpacity = layer->opacity();
456 bool drawOpacityIsAnimating = layer->opacityIsAnimating();
457 if (layer->parent() && layer->parent()->preserves3D()) {
458 drawOpacity *= layer->parent()->drawOpacity();
459 drawOpacityIsAnimating |= layer->parent()->drawOpacityIsAnimating();
460 }
461
462 IntSize bounds = layer->bounds();
463 FloatPoint anchorPoint = layer->anchorPoint();
464 FloatPoint position = layer->position() - layer->scrollDelta();
465
466 // Offset between anchor point and the center of the quad.
467 float centerOffsetX = (0.5 - anchorPoint.x()) * bounds.width();
468 float centerOffsetY = (0.5 - anchorPoint.y()) * bounds.height();
469
470 WebTransformationMatrix layerLocalTransform;
471 // LT = S[pageScaleDelta]
472 layerLocalTransform.scale(layer->pageScaleDelta());
473 // LT = S[pageScaleDelta] * Tr[origin] * Tr[origin2anchor]
474 layerLocalTransform.translate3d(position.x() + anchorPoint.x() * bounds.width(), position.y() + anchorPoint.y() * bounds.height(), layer->anchorPointZ());
475 // LT = S[pageScaleDelta] * Tr[origin] * Tr[origin2anchor] * M[layer]
476 layerLocalTransform.multiply(layer->transform());
477 // LT = S[pageScaleDelta] * Tr[origin] * Tr[origin2anchor] * M[layer] * Tr[anchor2center]
478 layerLocalTransform.translate3d(centerOffsetX, centerOffsetY, -layer->anchorPointZ());
479
480 WebTransformationMatrix combinedTransform = parentMatrix;
481 combinedTransform.multiply(layerLocalTransform);
482
483 if (layer->fixedToContainerLayer()) {
484 // Special case: this layer is a composited fixed-position layer; we need to
485 // explicitly compensate for all ancestors' nonzero scrollDeltas to keep this layer
486 // fixed correctly.
487 combinedTransform = currentScrollCompensationMatrix * combinedTransform;
488 }
489
490 // The drawTransform that gets computed below is effectively the layer's drawTransform, unless
491 // the layer itself creates a renderSurface. In that case, the renderSurface re-parents the transforms.
492 WebTransformationMatrix drawTransform = combinedTransform;
493 // M[draw] = M[parent] * LT * Tr[anchor2center] * Tr[center2origin]
494 drawTransform.translate(-layer->bounds().width() / 2.0, -layer->bounds().height() / 2.0);
495 if (!layer->contentBounds().isEmpty() && !layer->bounds().isEmpty()) {
496 // M[draw] = M[parent] * LT * Tr[anchor2origin] * S[layer2content]
497 drawTransform.scaleNonUniform(layer->bounds().width() / static_cast<double>(layer->contentBounds().width()),
498 layer->bounds().height() / static_cast<double>(layer->contentBounds().height()));
499 }
500
501 // layerScreenSpaceTransform represents the transform between root layer's "screen space" and local content space.
502 WebTransformationMatrix layerScreenSpaceTransform = fullHierarchyMatrix;
503 if (!layer->preserves3D())
504 CCMathUtil::flattenTransformTo2d(layerScreenSpaceTransform);
505 layerScreenSpaceTransform.multiply(drawTransform);
506 layer->setScreenSpaceTransform(layerScreenSpaceTransform);
507
508 bool animatingTransformToTarget = layer->transformIsAnimating();
509 bool animatingTransformToScreen = animatingTransformToTarget;
510 if (layer->parent()) {
511 animatingTransformToTarget |= layer->parent()->drawTransformIsAnimating();
512 animatingTransformToScreen |= layer->parent()->screenSpaceTransformIsAnimating();
513 }
514
515 FloatRect contentRect(FloatPoint(), layer->contentBounds());
516
517 // fullHierarchyMatrix is the matrix that transforms objects between screen space (except projection matrix) and the most recent RenderSurface's space.
518 // nextHierarchyMatrix will only change if this layer uses a new RenderSurface, otherwise remains the same.
519 WebTransformationMatrix nextHierarchyMatrix = fullHierarchyMatrix;
520 WebTransformationMatrix sublayerMatrix;
521
522 if (subtreeShouldRenderToSeparateSurface(layer, isScaleOrTranslation(combinedTransform))) {
523 // Check back-face visibility before continuing with this surface and its subtree
524 if (!layer->doubleSided() && transformToParentIsKnown(layer) && isSurfaceBackFaceVisible(layer, combinedTransform))
525 return;
526
527 if (!layer->renderSurface())
528 layer->createRenderSurface();
529
530 RenderSurfaceType* renderSurface = layer->renderSurface();
531 renderSurface->clearLayerList();
532
533 // The origin of the new surface is the upper left corner of the layer.
534 renderSurface->setDrawTransform(drawTransform);
535 WebTransformationMatrix layerDrawTransform;
536 layerDrawTransform.scale(deviceScaleFactor);
537 if (!layer->contentBounds().isEmpty() && !layer->bounds().isEmpty()) {
538 layerDrawTransform.scaleNonUniform(layer->bounds().width() / static_cast<double>(layer->contentBounds().width()),
539 layer->bounds().height() / static_cast<double>(layer->contentBounds().height()));
540 }
541 layer->setDrawTransform(layerDrawTransform);
542
543 // The sublayer matrix transforms centered layer rects into target
544 // surface content space.
545 sublayerMatrix.makeIdentity();
546 sublayerMatrix.scale(deviceScaleFactor);
547 sublayerMatrix.translate(0.5 * bounds.width(), 0.5 * bounds.height());
548
549 // The opacity value is moved from the layer to its surface, so that the entire subtree properly inherits opacity.
550 renderSurface->setDrawOpacity(drawOpacity);
551 renderSurface->setDrawOpacityIsAnimating(drawOpacityIsAnimating);
552 layer->setDrawOpacity(1);
553 layer->setDrawOpacityIsAnimating(false);
554
555 renderSurface->setTargetSurfaceTransformsAreAnimating(animatingTransformToTarget);
556 renderSurface->setScreenSpaceTransformsAreAnimating(animatingTransformToScreen);
557 animatingTransformToTarget = false;
558 layer->setDrawTransformIsAnimating(animatingTransformToTarget);
559 layer->setScreenSpaceTransformIsAnimating(animatingTransformToScreen);
560
561 // Update the aggregate hierarchy matrix to include the transform of the
562 // newly created RenderSurface.
563 nextHierarchyMatrix.multiply(renderSurface->drawTransform());
564
565 // The new renderSurface here will correctly clip the entire subtree. So, we do
566 // not need to continue propagating the clipping state further down the tree. This
567 // way, we can avoid transforming clipRects from ancestor target surface space to
568 // current target surface space that could cause more w < 0 headaches.
569 subtreeShouldBeClipped = false;
570
571 if (layer->maskLayer())
572 layer->maskLayer()->setRenderTarget(layer);
573
574 if (layer->replicaLayer() && layer->replicaLayer()->maskLayer())
575 layer->replicaLayer()->maskLayer()->setRenderTarget(layer);
576
577 if (layer->filters().hasFilterThatMovesPixels())
578 nearestAncestorThatMovesPixels = renderSurface;
579
580 renderSurface->setNearestAncestorThatMovesPixels(nearestAncestorThatMovesPixels);
581
582 renderSurfaceLayerList.append(layer);
583 } else {
584 layer->setDrawTransform(drawTransform);
585 layer->setDrawTransformIsAnimating(animatingTransformToTarget);
586 layer->setScreenSpaceTransformIsAnimating(animatingTransformToScreen);
587 sublayerMatrix = combinedTransform;
588
589 layer->setDrawOpacity(drawOpacity);
590 layer->setDrawOpacityIsAnimating(drawOpacityIsAnimating);
591
592 if (layer != rootLayer) {
593 ASSERT(layer->parent());
594 layer->clearRenderSurface();
595
596 // Layers without renderSurfaces directly inherit the ancestor's clip status.
597 subtreeShouldBeClipped = ancestorClipsSubtree;
598 if (ancestorClipsSubtree)
599 clipRectForSubtree = clipRectFromAncestor;
600
601 // Layers that are not their own renderTarget will render into the target of their nearest ancestor.
602 layer->setRenderTarget(layer->parent()->renderTarget());
603 } else {
[email protected]23bbb412012-08-30 20:03:38604 // FIXME: This root layer special case code should eventually go away. https://bugs.webkit.org/show_bug.cgi?id=92290
[email protected]94f206c12012-08-25 00:09:14605 ASSERT(!layer->parent());
606 ASSERT(layer->renderSurface());
607 ASSERT(ancestorClipsSubtree);
608 layer->renderSurface()->setClipRect(clipRectFromAncestor);
[email protected]23bbb412012-08-30 20:03:38609 subtreeShouldBeClipped = false;
[email protected]94f206c12012-08-25 00:09:14610 }
611 }
612
613 IntRect rectInTargetSpace = enclosingIntRect(CCMathUtil::mapClippedRect(layer->drawTransform(), contentRect));
614
615 if (layerClipsSubtree(layer)) {
616 subtreeShouldBeClipped = true;
617 if (ancestorClipsSubtree && !layer->renderSurface()) {
618 clipRectForSubtree = clipRectFromAncestor;
619 clipRectForSubtree.intersect(rectInTargetSpace);
620 } else
621 clipRectForSubtree = rectInTargetSpace;
622 }
623
624 // Flatten to 2D if the layer doesn't preserve 3D.
625 if (!layer->preserves3D())
626 CCMathUtil::flattenTransformTo2d(sublayerMatrix);
627
628 // Apply the sublayer transform at the center of the layer.
629 sublayerMatrix.multiply(layer->sublayerTransform());
630
631 // The coordinate system given to children is located at the layer's origin, not the center.
632 sublayerMatrix.translate3d(-bounds.width() * 0.5, -bounds.height() * 0.5, 0);
633
634 LayerList& descendants = (layer->renderSurface() ? layer->renderSurface()->layerList() : layerList);
635
636 // Any layers that are appended after this point are in the layer's subtree and should be included in the sorting process.
637 unsigned sortingStartIndex = descendants.size();
638
639 if (!layerShouldBeSkipped(layer))
640 descendants.append(layer);
641
642 WebTransformationMatrix nextScrollCompensationMatrix = computeScrollCompensationMatrixForChildren(layer, parentMatrix, currentScrollCompensationMatrix);;
643
644 IntRect accumulatedDrawableContentRectOfChildren;
645 for (size_t i = 0; i < layer->children().size(); ++i) {
646 LayerType* child = layer->children()[i].get();
647 IntRect drawableContentRectOfChildSubtree;
648 calculateDrawTransformsInternal<LayerType, LayerList, RenderSurfaceType, LayerSorter>(child, rootLayer, sublayerMatrix, nextHierarchyMatrix, nextScrollCompensationMatrix,
649 clipRectForSubtree, subtreeShouldBeClipped, nearestAncestorThatMovesPixels,
650 renderSurfaceLayerList, descendants, layerSorter, maxTextureSize, deviceScaleFactor, drawableContentRectOfChildSubtree);
651 if (!drawableContentRectOfChildSubtree.isEmpty()) {
652 accumulatedDrawableContentRectOfChildren.unite(drawableContentRectOfChildSubtree);
653 if (child->renderSurface())
654 descendants.append(child);
655 }
656 }
657
658 // Compute the total drawableContentRect for this subtree (the rect is in targetSurface space)
659 IntRect localDrawableContentRectOfSubtree = accumulatedDrawableContentRectOfChildren;
660 if (layer->drawsContent())
661 localDrawableContentRectOfSubtree.unite(rectInTargetSpace);
662 if (subtreeShouldBeClipped)
663 localDrawableContentRectOfSubtree.intersect(clipRectForSubtree);
664
665 // Compute the layer's drawable content rect (the rect is in targetSurface space)
666 IntRect drawableContentRectOfLayer = rectInTargetSpace;
667 if (subtreeShouldBeClipped)
668 drawableContentRectOfLayer.intersect(clipRectForSubtree);
669 layer->setDrawableContentRect(drawableContentRectOfLayer);
670
671 // Compute the remaining properties for the render surface, if the layer has one.
672 if (layer->renderSurface() && layer != rootLayer) {
673 RenderSurfaceType* renderSurface = layer->renderSurface();
674 IntRect clippedContentRect = localDrawableContentRectOfSubtree;
675
676 // The render surface clipRect is expressed in the space where this surface draws, i.e. the same space as clipRectFromAncestor.
677 if (ancestorClipsSubtree)
678 renderSurface->setClipRect(clipRectFromAncestor);
679 else
680 renderSurface->setClipRect(IntRect());
681
682 // Don't clip if the layer is reflected as the reflection shouldn't be
683 // clipped. If the layer is animating, then the surface's transform to
684 // its target is not known on the main thread, and we should not use it
685 // to clip.
686 if (!layer->replicaLayer() && transformToParentIsKnown(layer)) {
687 // Note, it is correct to use ancestorClipsSubtree here, because we are looking at this layer's renderSurface, not the layer itself.
688 if (ancestorClipsSubtree && !clippedContentRect.isEmpty()) {
689 IntRect surfaceClipRect = CCLayerTreeHostCommon::calculateVisibleRect(renderSurface->clipRect(), clippedContentRect, renderSurface->drawTransform());
690 clippedContentRect.intersect(surfaceClipRect);
691 }
692 }
693
694 // The RenderSurface backing texture cannot exceed the maximum supported
695 // texture size.
696 clippedContentRect.setWidth(std::min(clippedContentRect.width(), maxTextureSize));
697 clippedContentRect.setHeight(std::min(clippedContentRect.height(), maxTextureSize));
698
699 if (clippedContentRect.isEmpty())
700 renderSurface->clearLayerList();
701
702 renderSurface->setContentRect(clippedContentRect);
703 renderSurface->setScreenSpaceTransform(layer->screenSpaceTransform());
704
705 if (layer->replicaLayer()) {
706 WebTransformationMatrix surfaceOriginToReplicaOriginTransform;
707 surfaceOriginToReplicaOriginTransform.scale(deviceScaleFactor);
708 surfaceOriginToReplicaOriginTransform.translate(layer->replicaLayer()->position().x() + layer->replicaLayer()->anchorPoint().x() * bounds.width(),
709 layer->replicaLayer()->position().y() + layer->replicaLayer()->anchorPoint().y() * bounds.height());
710 surfaceOriginToReplicaOriginTransform.multiply(layer->replicaLayer()->transform());
711 surfaceOriginToReplicaOriginTransform.translate(-layer->replicaLayer()->anchorPoint().x() * bounds.width(), -layer->replicaLayer()->anchorPoint().y() * bounds.height());
712 surfaceOriginToReplicaOriginTransform.scale(1 / deviceScaleFactor);
713
714 // Compute the replica's "originTransform" that maps from the replica's origin space to the target surface origin space.
715 WebTransformationMatrix replicaOriginTransform = layer->renderSurface()->drawTransform() * surfaceOriginToReplicaOriginTransform;
716 renderSurface->setReplicaDrawTransform(replicaOriginTransform);
717
718 // Compute the replica's "screenSpaceTransform" that maps from the replica's origin space to the screen's origin space.
719 WebTransformationMatrix replicaScreenSpaceTransform = layer->renderSurface()->screenSpaceTransform() * surfaceOriginToReplicaOriginTransform;
720 renderSurface->setReplicaScreenSpaceTransform(replicaScreenSpaceTransform);
721 }
722
723 // If a render surface has no layer list, then it and none of its children needed to get drawn.
724 if (!layer->renderSurface()->layerList().size()) {
725 // FIXME: Originally we asserted that this layer was already at the end of the
726 // list, and only needed to remove that layer. For now, we remove the
727 // entire subtree of surfaces to fix a crash bug. The root cause is
728 // https://bugs.webkit.org/show_bug.cgi?id=74147 and we should be able
729 // to put the original assert after fixing that.
730 while (renderSurfaceLayerList.last() != layer) {
731 renderSurfaceLayerList.last()->clearRenderSurface();
732 renderSurfaceLayerList.removeLast();
733 }
734 ASSERT(renderSurfaceLayerList.last() == layer);
735 renderSurfaceLayerList.removeLast();
736 layer->clearRenderSurface();
737 return;
738 }
739 }
740
741 // If neither this layer nor any of its children were added, early out.
742 if (sortingStartIndex == descendants.size())
743 return;
744
745 // If preserves-3d then sort all the descendants in 3D so that they can be
746 // drawn from back to front. If the preserves-3d property is also set on the parent then
747 // skip the sorting as the parent will sort all the descendants anyway.
748 if (descendants.size() && layer->preserves3D() && (!layer->parent() || !layer->parent()->preserves3D()))
749 sortLayers(&descendants.at(sortingStartIndex), descendants.end(), layerSorter);
750
751 if (layer->renderSurface())
752 drawableContentRectOfSubtree = enclosingIntRect(layer->renderSurface()->drawableContentRect());
753 else
754 drawableContentRectOfSubtree = localDrawableContentRectOfSubtree;
755
756 return;
757}
758
759// FIXME: Instead of using the following function to set visibility rects on a second
760// tree pass, revise calculateVisibleContentRect() so that this can be done in a single
761// pass inside calculateDrawTransformsInternal<>().
762template<typename LayerType, typename LayerList, typename RenderSurfaceType>
763static void calculateVisibleRectsInternal(const LayerList& renderSurfaceLayerList)
764{
765 // Use BackToFront since it's cheap and this isn't order-dependent.
766 typedef CCLayerIterator<LayerType, LayerList, RenderSurfaceType, CCLayerIteratorActions::BackToFront> CCLayerIteratorType;
767
768 CCLayerIteratorType end = CCLayerIteratorType::end(&renderSurfaceLayerList);
769 for (CCLayerIteratorType it = CCLayerIteratorType::begin(&renderSurfaceLayerList); it != end; ++it) {
770 if (it.representsTargetRenderSurface()) {
771 LayerType* maskLayer = it->maskLayer();
772 if (maskLayer)
773 maskLayer->setVisibleContentRect(IntRect(IntPoint(), it->contentBounds()));
774 LayerType* replicaMaskLayer = it->replicaLayer() ? it->replicaLayer()->maskLayer() : 0;
775 if (replicaMaskLayer)
776 replicaMaskLayer->setVisibleContentRect(IntRect(IntPoint(), it->contentBounds()));
777 } else if (it.representsItself()) {
778 IntRect visibleContentRect = calculateVisibleContentRect(*it);
779 it->setVisibleContentRect(visibleContentRect);
780 }
781 }
782}
783
784void CCLayerTreeHostCommon::calculateDrawTransforms(LayerChromium* rootLayer, const IntSize& deviceViewportSize, float deviceScaleFactor, int maxTextureSize, Vector<RefPtr<LayerChromium> >& renderSurfaceLayerList)
785{
786 IntRect totalDrawableContentRect;
787 WebTransformationMatrix identityMatrix;
788 WebTransformationMatrix deviceScaleTransform;
789 deviceScaleTransform.scale(deviceScaleFactor);
790
791 setupRootLayerAndSurfaceForRecursion<LayerChromium, Vector<RefPtr<LayerChromium> > >(rootLayer, renderSurfaceLayerList, deviceViewportSize);
792
[email protected]9c88e562012-09-14 22:21:30793 cc::calculateDrawTransformsInternal<LayerChromium, Vector<RefPtr<LayerChromium> >, RenderSurfaceChromium, void>(rootLayer, rootLayer, deviceScaleTransform, identityMatrix, identityMatrix,
[email protected]94f206c12012-08-25 00:09:14794 rootLayer->renderSurface()->contentRect(), true, 0, renderSurfaceLayerList,
795 rootLayer->renderSurface()->layerList(), 0, maxTextureSize, deviceScaleFactor, totalDrawableContentRect);
796}
797
798void CCLayerTreeHostCommon::calculateDrawTransforms(CCLayerImpl* rootLayer, const IntSize& deviceViewportSize, float deviceScaleFactor, CCLayerSorter* layerSorter, int maxTextureSize, Vector<CCLayerImpl*>& renderSurfaceLayerList)
799{
800 IntRect totalDrawableContentRect;
801 WebTransformationMatrix identityMatrix;
802 WebTransformationMatrix deviceScaleTransform;
803 deviceScaleTransform.scale(deviceScaleFactor);
804
805 setupRootLayerAndSurfaceForRecursion<CCLayerImpl, Vector<CCLayerImpl*> >(rootLayer, renderSurfaceLayerList, deviceViewportSize);
806
[email protected]9c88e562012-09-14 22:21:30807 cc::calculateDrawTransformsInternal<CCLayerImpl, Vector<CCLayerImpl*>, CCRenderSurface, CCLayerSorter>(rootLayer, rootLayer, deviceScaleTransform, identityMatrix, identityMatrix,
[email protected]94f206c12012-08-25 00:09:14808 rootLayer->renderSurface()->contentRect(), true, 0, renderSurfaceLayerList,
809 rootLayer->renderSurface()->layerList(), layerSorter, maxTextureSize, deviceScaleFactor, totalDrawableContentRect);
810}
811
812void CCLayerTreeHostCommon::calculateVisibleRects(Vector<RefPtr<LayerChromium> >& renderSurfaceLayerList)
813{
814 calculateVisibleRectsInternal<LayerChromium, Vector<RefPtr<LayerChromium> >, RenderSurfaceChromium>(renderSurfaceLayerList);
815}
816
817void CCLayerTreeHostCommon::calculateVisibleRects(Vector<CCLayerImpl*>& renderSurfaceLayerList)
818{
819 calculateVisibleRectsInternal<CCLayerImpl, Vector<CCLayerImpl*>, CCRenderSurface>(renderSurfaceLayerList);
820}
821
822static bool pointHitsRect(const IntPoint& viewportPoint, const WebTransformationMatrix& localSpaceToScreenSpaceTransform, FloatRect localSpaceRect)
823{
824 // If the transform is not invertible, then assume that this point doesn't hit this rect.
825 if (!localSpaceToScreenSpaceTransform.isInvertible())
826 return false;
827
828 // Transform the hit test point from screen space to the local space of the given rect.
829 bool clipped = false;
830 FloatPoint hitTestPointInLocalSpace = CCMathUtil::projectPoint(localSpaceToScreenSpaceTransform.inverse(), FloatPoint(viewportPoint), clipped);
831
832 // If projectPoint could not project to a valid value, then we assume that this point doesn't hit this rect.
833 if (clipped)
834 return false;
835
836 return localSpaceRect.contains(hitTestPointInLocalSpace);
837}
838
839static bool pointIsClippedBySurfaceOrClipRect(const IntPoint& viewportPoint, CCLayerImpl* layer)
840{
841 CCLayerImpl* currentLayer = layer;
842
843 // Walk up the layer tree and hit-test any renderSurfaces and any layer clipRects that are active.
844 while (currentLayer) {
845 if (currentLayer->renderSurface() && !pointHitsRect(viewportPoint, currentLayer->renderSurface()->screenSpaceTransform(), currentLayer->renderSurface()->contentRect()))
846 return true;
847
848 // Note that drawableContentRects are actually in targetSurface space, so the transform we
849 // have to provide is the target surface's screenSpaceTransform.
850 CCLayerImpl* renderTarget = currentLayer->renderTarget();
851 if (layerClipsSubtree(currentLayer) && !pointHitsRect(viewportPoint, renderTarget->renderSurface()->screenSpaceTransform(), currentLayer->drawableContentRect()))
852 return true;
853
854 currentLayer = currentLayer->parent();
855 }
856
857 // If we have finished walking all ancestors without having already exited, then the point is not clipped by any ancestors.
858 return false;
859}
860
861CCLayerImpl* CCLayerTreeHostCommon::findLayerThatIsHitByPoint(const IntPoint& viewportPoint, Vector<CCLayerImpl*>& renderSurfaceLayerList)
862{
863 CCLayerImpl* foundLayer = 0;
864
865 typedef CCLayerIterator<CCLayerImpl, Vector<CCLayerImpl*>, CCRenderSurface, CCLayerIteratorActions::FrontToBack> CCLayerIteratorType;
866 CCLayerIteratorType end = CCLayerIteratorType::end(&renderSurfaceLayerList);
867
868 for (CCLayerIteratorType it = CCLayerIteratorType::begin(&renderSurfaceLayerList); it != end; ++it) {
869 // We don't want to consider renderSurfaces for hit testing.
870 if (!it.representsItself())
871 continue;
872
873 CCLayerImpl* currentLayer = (*it);
874
875 FloatRect contentRect(FloatPoint::zero(), currentLayer->contentBounds());
876 if (!pointHitsRect(viewportPoint, currentLayer->screenSpaceTransform(), contentRect))
877 continue;
878
879 // At this point, we think the point does hit the layer, but we need to walk up
880 // the parents to ensure that the layer was not clipped in such a way that the
881 // hit point actually should not hit the layer.
882 if (pointIsClippedBySurfaceOrClipRect(viewportPoint, currentLayer))
883 continue;
884
885 foundLayer = currentLayer;
886 break;
887 }
888
889 // This can potentially return 0, which means the viewportPoint did not successfully hit test any layers, not even the root layer.
890 return foundLayer;
891}
892
[email protected]9c88e562012-09-14 22:21:30893} // namespace cc