Draw Opacity of Render Surface from Property Trees
[chromium-blink-merge.git] / cc / trees / layer_tree_host_common.cc
blob037969a78fa330ad1d8113345158e86ab9fddb7b
1 // 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.
5 #include "cc/trees/layer_tree_host_common.h"
7 #include <algorithm>
9 #include "base/trace_event/trace_event.h"
10 #include "cc/base/math_util.h"
11 #include "cc/layers/heads_up_display_layer_impl.h"
12 #include "cc/layers/layer.h"
13 #include "cc/layers/layer_impl.h"
14 #include "cc/layers/layer_iterator.h"
15 #include "cc/layers/render_surface.h"
16 #include "cc/layers/render_surface_impl.h"
17 #include "cc/trees/draw_property_utils.h"
18 #include "cc/trees/layer_tree_host.h"
19 #include "cc/trees/layer_tree_impl.h"
20 #include "ui/gfx/geometry/rect_conversions.h"
21 #include "ui/gfx/geometry/vector2d_conversions.h"
22 #include "ui/gfx/transform.h"
23 #include "ui/gfx/transform_util.h"
25 namespace cc {
27 ScrollAndScaleSet::ScrollAndScaleSet()
28 : page_scale_delta(1.f), top_controls_delta(0.f) {
31 ScrollAndScaleSet::~ScrollAndScaleSet() {}
33 template <typename LayerType>
34 static gfx::Vector2dF GetEffectiveScrollDelta(LayerType* layer) {
35 // Layer's scroll offset can have an integer part and fractional part.
36 // Due to Blink's limitation, it only counter-scrolls the position-fixed
37 // layer using the integer part of Layer's scroll offset.
38 // CC scrolls the layer using the full scroll offset, so we have to
39 // add the ScrollCompensationAdjustment (fractional part of the scroll
40 // offset) to the effective scroll delta which is used to counter-scroll
41 // the position-fixed layer.
42 gfx::Vector2dF scroll_delta =
43 layer->ScrollDelta() + layer->ScrollCompensationAdjustment();
44 // The scroll parent's scroll delta is the amount we've scrolled on the
45 // compositor thread since the commit for this layer tree's source frame.
46 // we last reported to the main thread. I.e., it's the discrepancy between
47 // a scroll parent's scroll delta and offset, so we must add it here.
48 if (layer->scroll_parent())
49 scroll_delta += layer->scroll_parent()->ScrollDelta() +
50 layer->ScrollCompensationAdjustment();
51 return scroll_delta;
54 template <typename LayerType>
55 static gfx::ScrollOffset GetEffectiveCurrentScrollOffset(LayerType* layer) {
56 gfx::ScrollOffset offset = layer->CurrentScrollOffset();
57 // The scroll parent's total scroll offset (scroll offset + scroll delta)
58 // can't be used because its scroll offset has already been applied to the
59 // scroll children's positions by the main thread layer positioning code.
60 if (layer->scroll_parent())
61 offset += gfx::ScrollOffset(layer->scroll_parent()->ScrollDelta());
62 return offset;
65 inline gfx::Rect CalculateVisibleRectWithCachedLayerRect(
66 const gfx::Rect& target_surface_rect,
67 const gfx::Rect& layer_bound_rect,
68 const gfx::Rect& layer_rect_in_target_space,
69 const gfx::Transform& transform) {
70 if (layer_rect_in_target_space.IsEmpty())
71 return gfx::Rect();
73 // Is this layer fully contained within the target surface?
74 if (target_surface_rect.Contains(layer_rect_in_target_space))
75 return layer_bound_rect;
77 // If the layer doesn't fill up the entire surface, then find the part of
78 // the surface rect where the layer could be visible. This avoids trying to
79 // project surface rect points that are behind the projection point.
80 gfx::Rect minimal_surface_rect = target_surface_rect;
81 minimal_surface_rect.Intersect(layer_rect_in_target_space);
83 if (minimal_surface_rect.IsEmpty())
84 return gfx::Rect();
86 // Project the corners of the target surface rect into the layer space.
87 // This bounding rectangle may be larger than it needs to be (being
88 // axis-aligned), but is a reasonable filter on the space to consider.
89 // Non-invertible transforms will create an empty rect here.
91 gfx::Transform surface_to_layer(gfx::Transform::kSkipInitialization);
92 if (!transform.GetInverse(&surface_to_layer)) {
93 // Because we cannot use the surface bounds to determine what portion of
94 // the layer is visible, we must conservatively assume the full layer is
95 // visible.
96 return layer_bound_rect;
99 gfx::Rect layer_rect = MathUtil::ProjectEnclosingClippedRect(
100 surface_to_layer, minimal_surface_rect);
101 layer_rect.Intersect(layer_bound_rect);
102 return layer_rect;
105 gfx::Rect LayerTreeHostCommon::CalculateVisibleRect(
106 const gfx::Rect& target_surface_rect,
107 const gfx::Rect& layer_bound_rect,
108 const gfx::Transform& transform) {
109 gfx::Rect layer_in_surface_space =
110 MathUtil::MapEnclosingClippedRect(transform, layer_bound_rect);
111 return CalculateVisibleRectWithCachedLayerRect(
112 target_surface_rect, layer_bound_rect, layer_in_surface_space, transform);
115 template <typename LayerType>
116 static LayerType* NextTargetSurface(LayerType* layer) {
117 return layer->parent() ? layer->parent()->render_target() : 0;
120 // Given two layers, this function finds their respective render targets and,
121 // computes a change of basis translation. It does this by accumulating the
122 // translation components of the draw transforms of each target between the
123 // ancestor and descendant. These transforms must be 2D translations, and this
124 // requirement is enforced at every step.
125 template <typename LayerType>
126 static gfx::Vector2dF ComputeChangeOfBasisTranslation(
127 const LayerType& ancestor_layer,
128 const LayerType& descendant_layer) {
129 DCHECK(descendant_layer.HasAncestor(&ancestor_layer));
130 const LayerType* descendant_target = descendant_layer.render_target();
131 DCHECK(descendant_target);
132 const LayerType* ancestor_target = ancestor_layer.render_target();
133 DCHECK(ancestor_target);
135 gfx::Vector2dF translation;
136 for (const LayerType* target = descendant_target; target != ancestor_target;
137 target = NextTargetSurface(target)) {
138 const gfx::Transform& trans = target->render_surface()->draw_transform();
139 // Ensure that this translation is truly 2d.
140 DCHECK(trans.IsIdentityOrTranslation());
141 DCHECK_EQ(0.f, trans.matrix().get(2, 3));
142 translation += trans.To2dTranslation();
145 return translation;
148 enum TranslateRectDirection {
149 TRANSLATE_RECT_DIRECTION_TO_ANCESTOR,
150 TRANSLATE_RECT_DIRECTION_TO_DESCENDANT
153 template <typename LayerType>
154 static gfx::Rect TranslateRectToTargetSpace(const LayerType& ancestor_layer,
155 const LayerType& descendant_layer,
156 const gfx::Rect& rect,
157 TranslateRectDirection direction) {
158 gfx::Vector2dF translation = ComputeChangeOfBasisTranslation<LayerType>(
159 ancestor_layer, descendant_layer);
160 if (direction == TRANSLATE_RECT_DIRECTION_TO_DESCENDANT)
161 translation.Scale(-1.f);
162 return gfx::ToEnclosingRect(
163 gfx::RectF(rect.origin() + translation, rect.size()));
166 // Attempts to update the clip rects for the given layer. If the layer has a
167 // clip_parent, it may not inherit its immediate ancestor's clip.
168 template <typename LayerType>
169 static void UpdateClipRectsForClipChild(
170 const LayerType* layer,
171 gfx::Rect* clip_rect_in_parent_target_space,
172 bool* subtree_should_be_clipped) {
173 // If the layer has no clip_parent, or the ancestor is the same as its actual
174 // parent, then we don't need special clip rects. Bail now and leave the out
175 // parameters untouched.
176 const LayerType* clip_parent = layer->scroll_parent();
178 if (!clip_parent)
179 clip_parent = layer->clip_parent();
181 if (!clip_parent || clip_parent == layer->parent())
182 return;
184 // The root layer is never a clip child.
185 DCHECK(layer->parent());
187 // Grab the cached values.
188 *clip_rect_in_parent_target_space = clip_parent->clip_rect();
189 *subtree_should_be_clipped = clip_parent->is_clipped();
191 // We may have to project the clip rect into our parent's target space. Note,
192 // it must be our parent's target space, not ours. For one, we haven't
193 // computed our transforms, so we couldn't put it in our space yet even if we
194 // wanted to. But more importantly, this matches the expectations of
195 // CalculateDrawPropertiesInternal. If we, say, create a render surface, these
196 // clip rects will want to be in its target space, not ours.
197 if (clip_parent == layer->clip_parent()) {
198 *clip_rect_in_parent_target_space = TranslateRectToTargetSpace<LayerType>(
199 *clip_parent, *layer->parent(), *clip_rect_in_parent_target_space,
200 TRANSLATE_RECT_DIRECTION_TO_DESCENDANT);
201 } else {
202 // If we're being clipped by our scroll parent, we must translate through
203 // our common ancestor. This happens to be our parent, so it is sufficent to
204 // translate from our clip parent's space to the space of its ancestor (our
205 // parent).
206 *clip_rect_in_parent_target_space = TranslateRectToTargetSpace<LayerType>(
207 *layer->parent(), *clip_parent, *clip_rect_in_parent_target_space,
208 TRANSLATE_RECT_DIRECTION_TO_ANCESTOR);
212 // We collect an accumulated drawable content rect per render surface.
213 // Typically, a layer will contribute to only one surface, the surface
214 // associated with its render target. Clip children, however, may affect
215 // several surfaces since there may be several surfaces between the clip child
216 // and its parent.
218 // NB: we accumulate the layer's *clipped* drawable content rect.
219 template <typename LayerType>
220 struct AccumulatedSurfaceState {
221 explicit AccumulatedSurfaceState(LayerType* render_target)
222 : render_target(render_target) {}
224 // The accumulated drawable content rect for the surface associated with the
225 // given |render_target|.
226 gfx::Rect drawable_content_rect;
228 // The target owning the surface. (We hang onto the target rather than the
229 // surface so that we can DCHECK that the surface's draw transform is simply
230 // a translation when |render_target| reports that it has no unclipped
231 // descendants).
232 LayerType* render_target;
235 template <typename LayerType>
236 void UpdateAccumulatedSurfaceState(
237 LayerType* layer,
238 const gfx::Rect& drawable_content_rect,
239 std::vector<AccumulatedSurfaceState<LayerType>>*
240 accumulated_surface_state) {
241 if (IsRootLayer(layer))
242 return;
244 // We will apply our drawable content rect to the accumulated rects for all
245 // surfaces between us and |render_target| (inclusive). This is either our
246 // clip parent's target if we are a clip child, or else simply our parent's
247 // target. We use our parent's target because we're either the owner of a
248 // render surface and we'll want to add our rect to our *surface's* target, or
249 // we're not and our target is the same as our parent's. In both cases, the
250 // parent's target gives us what we want.
251 LayerType* render_target = layer->clip_parent()
252 ? layer->clip_parent()->render_target()
253 : layer->parent()->render_target();
255 // If the layer owns a surface, then the content rect is in the wrong space.
256 // Instead, we will use the surface's DrawableContentRect which is in target
257 // space as required.
258 gfx::Rect target_rect = drawable_content_rect;
259 if (layer->render_surface()) {
260 target_rect =
261 gfx::ToEnclosedRect(layer->render_surface()->DrawableContentRect());
264 if (render_target->is_clipped()) {
265 gfx::Rect clip_rect = render_target->clip_rect();
266 // If the layer has a clip parent, the clip rect may be in the wrong space,
267 // so we'll need to transform it before it is applied.
268 if (layer->clip_parent()) {
269 clip_rect = TranslateRectToTargetSpace<LayerType>(
270 *layer->clip_parent(), *layer, clip_rect,
271 TRANSLATE_RECT_DIRECTION_TO_DESCENDANT);
273 target_rect.Intersect(clip_rect);
276 // We must have at least one entry in the vector for the root.
277 DCHECK_LT(0ul, accumulated_surface_state->size());
279 typedef typename std::vector<AccumulatedSurfaceState<LayerType>>
280 AccumulatedSurfaceStateVector;
281 typedef typename AccumulatedSurfaceStateVector::reverse_iterator
282 AccumulatedSurfaceStateIterator;
283 AccumulatedSurfaceStateIterator current_state =
284 accumulated_surface_state->rbegin();
286 // Add this rect to the accumulated content rect for all surfaces until we
287 // reach the target surface.
288 bool found_render_target = false;
289 for (; current_state != accumulated_surface_state->rend(); ++current_state) {
290 current_state->drawable_content_rect.Union(target_rect);
292 // If we've reached |render_target| our work is done and we can bail.
293 if (current_state->render_target == render_target) {
294 found_render_target = true;
295 break;
298 // Transform rect from the current target's space to the next.
299 LayerType* current_target = current_state->render_target;
300 DCHECK(current_target->render_surface());
301 const gfx::Transform& current_draw_transform =
302 current_target->render_surface()->draw_transform();
304 // If we have unclipped descendants, the draw transform is a translation.
305 DCHECK_IMPLIES(current_target->num_unclipped_descendants(),
306 current_draw_transform.IsIdentityOrTranslation());
308 target_rect = gfx::ToEnclosingRect(
309 MathUtil::MapClippedRect(current_draw_transform, target_rect));
312 // It is an error to not reach |render_target|. If this happens, it means that
313 // either the clip parent is not an ancestor of the clip child or the surface
314 // state vector is empty, both of which should be impossible.
315 DCHECK(found_render_target);
318 template <typename LayerType> static inline bool IsRootLayer(LayerType* layer) {
319 return !layer->parent();
322 template <typename LayerType>
323 static inline bool LayerIsInExisting3DRenderingContext(LayerType* layer) {
324 return layer->Is3dSorted() && layer->parent() &&
325 layer->parent()->Is3dSorted() &&
326 (layer->parent()->sorting_context_id() == layer->sorting_context_id());
329 template <typename LayerType>
330 static bool IsRootLayerOfNewRenderingContext(LayerType* layer) {
331 if (layer->parent())
332 return !layer->parent()->Is3dSorted() && layer->Is3dSorted();
334 return layer->Is3dSorted();
337 template <typename LayerType>
338 static bool IsLayerBackFaceVisible(LayerType* layer) {
339 // The current W3C spec on CSS transforms says that backface visibility should
340 // be determined differently depending on whether the layer is in a "3d
341 // rendering context" or not. For Chromium code, we can determine whether we
342 // are in a 3d rendering context by checking if the parent preserves 3d.
344 if (LayerIsInExisting3DRenderingContext(layer))
345 return layer->draw_transform().IsBackFaceVisible();
347 // In this case, either the layer establishes a new 3d rendering context, or
348 // is not in a 3d rendering context at all.
349 return layer->transform().IsBackFaceVisible();
352 template <typename LayerType>
353 static bool IsSurfaceBackFaceVisible(LayerType* layer,
354 const gfx::Transform& draw_transform) {
355 if (LayerIsInExisting3DRenderingContext(layer))
356 return draw_transform.IsBackFaceVisible();
358 if (IsRootLayerOfNewRenderingContext(layer))
359 return layer->transform().IsBackFaceVisible();
361 // If the render_surface is not part of a new or existing rendering context,
362 // then the layers that contribute to this surface will decide back-face
363 // visibility for themselves.
364 return false;
367 template <typename LayerType>
368 static inline bool LayerClipsSubtree(LayerType* layer) {
369 return layer->masks_to_bounds() || layer->mask_layer();
372 template <typename LayerType>
373 static gfx::Rect CalculateVisibleLayerRect(
374 LayerType* layer,
375 const gfx::Rect& clip_rect_of_target_surface_in_target_space,
376 const gfx::Rect& layer_rect_in_target_space) {
377 DCHECK(layer->render_target());
379 // Nothing is visible if the layer bounds are empty.
380 if (!layer->DrawsContent() || layer->bounds().IsEmpty() ||
381 layer->drawable_content_rect().IsEmpty())
382 return gfx::Rect();
384 // Compute visible bounds in target surface space.
385 gfx::Rect visible_rect_in_target_surface_space =
386 layer->drawable_content_rect();
388 if (layer->render_target()->render_surface()->is_clipped()) {
389 // The |layer| L has a target T which owns a surface Ts. The surface Ts
390 // has a target TsT.
392 // In this case the target surface Ts does clip the layer L that contributes
393 // to it. So, we have to convert the clip rect of Ts from the target space
394 // of Ts (that is the space of TsT), to the current render target's space
395 // (that is the space of T). This conversion is done outside this function
396 // so that it can be cached instead of computing it redundantly for every
397 // layer.
398 visible_rect_in_target_surface_space.Intersect(
399 clip_rect_of_target_surface_in_target_space);
402 if (visible_rect_in_target_surface_space.IsEmpty())
403 return gfx::Rect();
405 return CalculateVisibleRectWithCachedLayerRect(
406 visible_rect_in_target_surface_space, gfx::Rect(layer->bounds()),
407 layer_rect_in_target_space, layer->draw_transform());
410 static inline bool TransformToParentIsKnown(LayerImpl* layer) { return true; }
412 static inline bool TransformToParentIsKnown(Layer* layer) {
413 return !layer->HasPotentiallyRunningTransformAnimation();
416 static bool LayerShouldBeSkipped(LayerImpl* layer, bool layer_is_drawn) {
417 // Layers can be skipped if any of these conditions are met.
418 // - is not drawn due to it or one of its ancestors being hidden (or having
419 // no copy requests).
420 // - does not draw content.
421 // - is transparent.
422 // - has empty bounds
423 // - the layer is not double-sided, but its back face is visible.
425 // Some additional conditions need to be computed at a later point after the
426 // recursion is finished.
427 // - the intersection of render_surface content and layer clip_rect is empty
428 // - the visible_layer_rect is empty
430 // Note, if the layer should not have been drawn due to being fully
431 // transparent, we would have skipped the entire subtree and never made it
432 // into this function, so it is safe to omit this check here.
434 if (!layer_is_drawn)
435 return true;
437 if (!layer->DrawsContent() || layer->bounds().IsEmpty())
438 return true;
440 LayerImpl* backface_test_layer = layer;
441 if (layer->use_parent_backface_visibility()) {
442 DCHECK(layer->parent());
443 DCHECK(!layer->parent()->use_parent_backface_visibility());
444 backface_test_layer = layer->parent();
447 // The layer should not be drawn if (1) it is not double-sided and (2) the
448 // back of the layer is known to be facing the screen.
449 if (!backface_test_layer->double_sided() &&
450 IsLayerBackFaceVisible(backface_test_layer))
451 return true;
453 return false;
456 template <typename LayerType>
457 static bool HasInvertibleOrAnimatedTransform(LayerType* layer) {
458 return layer->transform_is_invertible() ||
459 layer->HasPotentiallyRunningTransformAnimation();
462 static inline bool SubtreeShouldBeSkipped(LayerImpl* layer,
463 bool layer_is_drawn) {
464 // If the layer transform is not invertible, it should not be drawn.
465 // TODO(ajuma): Correctly process subtrees with singular transform for the
466 // case where we may animate to a non-singular transform and wish to
467 // pre-raster.
468 if (!HasInvertibleOrAnimatedTransform(layer))
469 return true;
471 // When we need to do a readback/copy of a layer's output, we can not skip
472 // it or any of its ancestors.
473 if (layer->draw_properties().layer_or_descendant_has_copy_request)
474 return false;
476 // We cannot skip the the subtree if a descendant has a wheel or touch handler
477 // or the hit testing code will break (it requires fresh transforms, etc).
478 if (layer->draw_properties().layer_or_descendant_has_input_handler)
479 return false;
481 // If the layer is not drawn, then skip it and its subtree.
482 if (!layer_is_drawn)
483 return true;
485 // If layer is on the pending tree and opacity is being animated then
486 // this subtree can't be skipped as we need to create, prioritize and
487 // include tiles for this layer when deciding if tree can be activated.
488 if (layer->layer_tree_impl()->IsPendingTree() &&
489 layer->HasPotentiallyRunningOpacityAnimation())
490 return false;
492 // The opacity of a layer always applies to its children (either implicitly
493 // via a render surface or explicitly if the parent preserves 3D), so the
494 // entire subtree can be skipped if this layer is fully transparent.
495 return !layer->opacity();
498 static inline bool SubtreeShouldBeSkipped(Layer* layer, bool layer_is_drawn) {
499 // If the layer transform is not invertible, it should not be drawn.
500 if (!layer->transform_is_invertible() &&
501 !layer->HasPotentiallyRunningTransformAnimation())
502 return true;
504 // When we need to do a readback/copy of a layer's output, we can not skip
505 // it or any of its ancestors.
506 if (layer->draw_properties().layer_or_descendant_has_copy_request)
507 return false;
509 // We cannot skip the the subtree if a descendant has a wheel or touch handler
510 // or the hit testing code will break (it requires fresh transforms, etc).
511 if (layer->draw_properties().layer_or_descendant_has_input_handler)
512 return false;
514 // If the layer is not drawn, then skip it and its subtree.
515 if (!layer_is_drawn)
516 return true;
518 // If the opacity is being animated then the opacity on the main thread is
519 // unreliable (since the impl thread may be using a different opacity), so it
520 // should not be trusted.
521 // In particular, it should not cause the subtree to be skipped.
522 // Similarly, for layers that might animate opacity using an impl-only
523 // animation, their subtree should also not be skipped.
524 return !layer->opacity() && !layer->HasPotentiallyRunningOpacityAnimation() &&
525 !layer->OpacityCanAnimateOnImplThread();
528 static inline void SavePaintPropertiesLayer(LayerImpl* layer) {}
530 static inline void SavePaintPropertiesLayer(Layer* layer) {
531 layer->SavePaintProperties();
533 if (layer->mask_layer())
534 layer->mask_layer()->SavePaintProperties();
535 if (layer->replica_layer() && layer->replica_layer()->mask_layer())
536 layer->replica_layer()->mask_layer()->SavePaintProperties();
539 static bool SubtreeShouldRenderToSeparateSurface(
540 Layer* layer,
541 bool axis_aligned_with_respect_to_parent) {
543 // A layer and its descendants should render onto a new RenderSurfaceImpl if
544 // any of these rules hold:
547 // The root layer owns a render surface, but it never acts as a contributing
548 // surface to another render target. Compositor features that are applied via
549 // a contributing surface can not be applied to the root layer. In order to
550 // use these effects, another child of the root would need to be introduced
551 // in order to act as a contributing surface to the root layer's surface.
552 bool is_root = IsRootLayer(layer);
554 // If the layer uses a mask.
555 if (layer->mask_layer()) {
556 DCHECK(!is_root);
557 return true;
560 // If the layer has a reflection.
561 if (layer->replica_layer()) {
562 DCHECK(!is_root);
563 return true;
566 // If the layer uses a CSS filter.
567 if (!layer->filters().IsEmpty() || !layer->background_filters().IsEmpty()) {
568 DCHECK(!is_root);
569 return true;
572 // If the layer will use a CSS filter. In this case, the animation
573 // will start and add a filter to this layer, so it needs a surface.
574 if (layer->HasPotentiallyRunningFilterAnimation()) {
575 DCHECK(!is_root);
576 return true;
579 int num_descendants_that_draw_content =
580 layer->NumDescendantsThatDrawContent();
582 // If the layer flattens its subtree, but it is treated as a 3D object by its
583 // parent (i.e. parent participates in a 3D rendering context).
584 if (LayerIsInExisting3DRenderingContext(layer) &&
585 layer->should_flatten_transform() &&
586 num_descendants_that_draw_content > 0) {
587 TRACE_EVENT_INSTANT0(
588 "cc",
589 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface flattening",
590 TRACE_EVENT_SCOPE_THREAD);
591 DCHECK(!is_root);
592 return true;
595 // If the layer has blending.
596 // TODO(rosca): this is temporary, until blending is implemented for other
597 // types of quads than RenderPassDrawQuad. Layers having descendants that draw
598 // content will still create a separate rendering surface.
599 if (!layer->uses_default_blend_mode()) {
600 TRACE_EVENT_INSTANT0(
601 "cc",
602 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface blending",
603 TRACE_EVENT_SCOPE_THREAD);
604 DCHECK(!is_root);
605 return true;
608 // If the layer clips its descendants but it is not axis-aligned with respect
609 // to its parent.
610 bool layer_clips_external_content =
611 LayerClipsSubtree(layer) || layer->HasDelegatedContent();
612 if (layer_clips_external_content && !axis_aligned_with_respect_to_parent &&
613 num_descendants_that_draw_content > 0) {
614 TRACE_EVENT_INSTANT0(
615 "cc",
616 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface clipping",
617 TRACE_EVENT_SCOPE_THREAD);
618 DCHECK(!is_root);
619 return true;
622 // If the layer has some translucency and does not have a preserves-3d
623 // transform style. This condition only needs a render surface if two or more
624 // layers in the subtree overlap. But checking layer overlaps is unnecessarily
625 // costly so instead we conservatively create a surface whenever at least two
626 // layers draw content for this subtree.
627 bool at_least_two_layers_in_subtree_draw_content =
628 num_descendants_that_draw_content > 0 &&
629 (layer->DrawsContent() || num_descendants_that_draw_content > 1);
631 if (layer->opacity() != 1.f && layer->should_flatten_transform() &&
632 at_least_two_layers_in_subtree_draw_content) {
633 TRACE_EVENT_INSTANT0(
634 "cc",
635 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface opacity",
636 TRACE_EVENT_SCOPE_THREAD);
637 DCHECK(!is_root);
638 return true;
641 // The root layer should always have a render_surface.
642 if (is_root)
643 return true;
646 // These are allowed on the root surface, as they don't require the surface to
647 // be used as a contributing surface in order to apply correctly.
650 // If the layer has isolation.
651 // TODO(rosca): to be optimized - create separate rendering surface only when
652 // the blending descendants might have access to the content behind this layer
653 // (layer has transparent background or descendants overflow).
654 // https://code.google.com/p/chromium/issues/detail?id=301738
655 if (layer->is_root_for_isolated_group()) {
656 TRACE_EVENT_INSTANT0(
657 "cc",
658 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface isolation",
659 TRACE_EVENT_SCOPE_THREAD);
660 return true;
663 // If we force it.
664 if (layer->force_render_surface())
665 return true;
667 // If we'll make a copy of the layer's contents.
668 if (layer->HasCopyRequest())
669 return true;
671 return false;
674 // This function returns a translation matrix that can be applied on a vector
675 // that's in the layer's target surface coordinate, while the position offset is
676 // specified in some ancestor layer's coordinate.
677 template <typename LayerType>
678 gfx::Transform ComputeSizeDeltaCompensation(
679 LayerType* layer,
680 LayerType* container,
681 const gfx::Vector2dF& position_offset) {
682 gfx::Transform result_transform;
684 // To apply a translate in the container's layer space,
685 // the following steps need to be done:
686 // Step 1a. transform from target surface space to the container's target
687 // surface space
688 // Step 1b. transform from container's target surface space to the
689 // container's layer space
690 // Step 2. apply the compensation
691 // Step 3. transform back to target surface space
693 gfx::Transform target_surface_space_to_container_layer_space;
694 // Calculate step 1a
695 LayerType* container_target_surface = container->render_target();
696 for (LayerType* current_target_surface = NextTargetSurface(layer);
697 current_target_surface &&
698 current_target_surface != container_target_surface;
699 current_target_surface = NextTargetSurface(current_target_surface)) {
700 // Note: Concat is used here to convert the result coordinate space from
701 // current render surface to the next render surface.
702 target_surface_space_to_container_layer_space.ConcatTransform(
703 current_target_surface->render_surface()->draw_transform());
705 // Calculate step 1b
706 gfx::Transform container_layer_space_to_container_target_surface_space =
707 container->draw_transform();
708 gfx::Transform container_target_surface_space_to_container_layer_space;
709 if (container_layer_space_to_container_target_surface_space.GetInverse(
710 &container_target_surface_space_to_container_layer_space)) {
711 // Note: Again, Concat is used to conver the result coordinate space from
712 // the container render surface to the container layer.
713 target_surface_space_to_container_layer_space.ConcatTransform(
714 container_target_surface_space_to_container_layer_space);
717 // Apply step 3
718 gfx::Transform container_layer_space_to_target_surface_space;
719 if (target_surface_space_to_container_layer_space.GetInverse(
720 &container_layer_space_to_target_surface_space)) {
721 result_transform.PreconcatTransform(
722 container_layer_space_to_target_surface_space);
723 } else {
724 // TODO(shawnsingh): A non-invertible matrix could still make meaningful
725 // projection. For example ScaleZ(0) is non-invertible but the layer is
726 // still visible.
727 return gfx::Transform();
730 // Apply step 2
731 result_transform.Translate(position_offset.x(), position_offset.y());
733 // Apply step 1
734 result_transform.PreconcatTransform(
735 target_surface_space_to_container_layer_space);
737 return result_transform;
740 template <typename LayerType>
741 void ApplyPositionAdjustment(
742 LayerType* layer,
743 LayerType* container,
744 const gfx::Transform& scroll_compensation,
745 gfx::Transform* combined_transform) {
746 if (!layer->position_constraint().is_fixed_position())
747 return;
749 // Special case: this layer is a composited fixed-position layer; we need to
750 // explicitly compensate for all ancestors' nonzero scroll_deltas to keep
751 // this layer fixed correctly.
752 // Note carefully: this is Concat, not Preconcat
753 // (current_scroll_compensation * combined_transform).
754 combined_transform->ConcatTransform(scroll_compensation);
756 // For right-edge or bottom-edge anchored fixed position layers,
757 // the layer should relocate itself if the container changes its size.
758 bool fixed_to_right_edge =
759 layer->position_constraint().is_fixed_to_right_edge();
760 bool fixed_to_bottom_edge =
761 layer->position_constraint().is_fixed_to_bottom_edge();
762 gfx::Vector2dF position_offset = container->FixedContainerSizeDelta();
763 position_offset.set_x(fixed_to_right_edge ? position_offset.x() : 0);
764 position_offset.set_y(fixed_to_bottom_edge ? position_offset.y() : 0);
765 if (position_offset.IsZero())
766 return;
768 // Note: Again, this is Concat. The compensation matrix will be applied on
769 // the vector in target surface space.
770 combined_transform->ConcatTransform(
771 ComputeSizeDeltaCompensation(layer, container, position_offset));
774 template <typename LayerType>
775 gfx::Transform ComputeScrollCompensationForThisLayer(
776 LayerType* scrolling_layer,
777 const gfx::Transform& parent_matrix,
778 const gfx::Vector2dF& scroll_delta) {
779 // For every layer that has non-zero scroll_delta, we have to compute a
780 // transform that can undo the scroll_delta translation. In particular, we
781 // want this matrix to premultiply a fixed-position layer's parent_matrix, so
782 // we design this transform in three steps as follows. The steps described
783 // here apply from right-to-left, so Step 1 would be the right-most matrix:
785 // Step 1. transform from target surface space to the exact space where
786 // scroll_delta is actually applied.
787 // -- this is inverse of parent_matrix
788 // Step 2. undo the scroll_delta
789 // -- this is just a translation by scroll_delta.
790 // Step 3. transform back to target surface space.
791 // -- this transform is the parent_matrix
793 // These steps create a matrix that both start and end in target surface
794 // space. So this matrix can pre-multiply any fixed-position layer's
795 // draw_transform to undo the scroll_deltas -- as long as that fixed position
796 // layer is fixed onto the same render_target as this scrolling_layer.
799 gfx::Transform scroll_compensation_for_this_layer = parent_matrix; // Step 3
800 scroll_compensation_for_this_layer.Translate(
801 scroll_delta.x(),
802 scroll_delta.y()); // Step 2
804 gfx::Transform inverse_parent_matrix(gfx::Transform::kSkipInitialization);
805 if (!parent_matrix.GetInverse(&inverse_parent_matrix)) {
806 // TODO(shawnsingh): Either we need to handle uninvertible transforms
807 // here, or DCHECK that the transform is invertible.
809 scroll_compensation_for_this_layer.PreconcatTransform(
810 inverse_parent_matrix); // Step 1
811 return scroll_compensation_for_this_layer;
814 template <typename LayerType>
815 gfx::Transform ComputeScrollCompensationMatrixForChildren(
816 LayerType* layer,
817 const gfx::Transform& parent_matrix,
818 const gfx::Transform& current_scroll_compensation_matrix,
819 const gfx::Vector2dF& scroll_delta) {
820 // "Total scroll compensation" is the transform needed to cancel out all
821 // scroll_delta translations that occurred since the nearest container layer,
822 // even if there are render_surfaces in-between.
824 // There are some edge cases to be aware of, that are not explicit in the
825 // code:
826 // - A layer that is both a fixed-position and container should not be its
827 // own container, instead, that means it is fixed to an ancestor, and is a
828 // container for any fixed-position descendants.
829 // - A layer that is a fixed-position container and has a render_surface
830 // should behave the same as a container without a render_surface, the
831 // render_surface is irrelevant in that case.
832 // - A layer that does not have an explicit container is simply fixed to the
833 // viewport. (i.e. the root render_surface.)
834 // - If the fixed-position layer has its own render_surface, then the
835 // render_surface is the one who gets fixed.
837 // This function needs to be called AFTER layers create their own
838 // render_surfaces.
841 // Scroll compensation restarts from identity under two possible conditions:
842 // - the current layer is a container for fixed-position descendants
843 // - the current layer is fixed-position itself, so any fixed-position
844 // descendants are positioned with respect to this layer. Thus, any
845 // fixed position descendants only need to compensate for scrollDeltas
846 // that occur below this layer.
847 bool current_layer_resets_scroll_compensation_for_descendants =
848 layer->IsContainerForFixedPositionLayers() ||
849 layer->position_constraint().is_fixed_position();
851 // Avoid the overheads (including stack allocation and matrix
852 // initialization/copy) if we know that the scroll compensation doesn't need
853 // to be reset or adjusted.
854 if (!current_layer_resets_scroll_compensation_for_descendants &&
855 scroll_delta.IsZero() && !layer->render_surface())
856 return current_scroll_compensation_matrix;
858 // Start as identity matrix.
859 gfx::Transform next_scroll_compensation_matrix;
861 // If this layer does not reset scroll compensation, then it inherits the
862 // existing scroll compensations.
863 if (!current_layer_resets_scroll_compensation_for_descendants)
864 next_scroll_compensation_matrix = current_scroll_compensation_matrix;
866 // If the current layer has a non-zero scroll_delta, then we should compute
867 // its local scroll compensation and accumulate it to the
868 // next_scroll_compensation_matrix.
869 if (!scroll_delta.IsZero()) {
870 gfx::Transform scroll_compensation_for_this_layer =
871 ComputeScrollCompensationForThisLayer(
872 layer, parent_matrix, scroll_delta);
873 next_scroll_compensation_matrix.PreconcatTransform(
874 scroll_compensation_for_this_layer);
877 // If the layer created its own render_surface, we have to adjust
878 // next_scroll_compensation_matrix. The adjustment allows us to continue
879 // using the scroll compensation on the next surface.
880 // Step 1 (right-most in the math): transform from the new surface to the
881 // original ancestor surface
882 // Step 2: apply the scroll compensation
883 // Step 3: transform back to the new surface.
884 if (layer->render_surface() &&
885 !next_scroll_compensation_matrix.IsIdentity()) {
886 gfx::Transform inverse_surface_draw_transform(
887 gfx::Transform::kSkipInitialization);
888 if (!layer->render_surface()->draw_transform().GetInverse(
889 &inverse_surface_draw_transform)) {
890 // TODO(shawnsingh): Either we need to handle uninvertible transforms
891 // here, or DCHECK that the transform is invertible.
893 next_scroll_compensation_matrix =
894 inverse_surface_draw_transform * next_scroll_compensation_matrix *
895 layer->render_surface()->draw_transform();
898 return next_scroll_compensation_matrix;
901 template <typename LayerType>
902 static inline void UpdateLayerScaleDrawProperties(
903 LayerType* layer,
904 float maximum_animation_contents_scale,
905 float starting_animation_contents_scale) {
906 layer->draw_properties().maximum_animation_contents_scale =
907 maximum_animation_contents_scale;
908 layer->draw_properties().starting_animation_contents_scale =
909 starting_animation_contents_scale;
912 static inline void CalculateAnimationContentsScale(
913 Layer* layer,
914 bool ancestor_is_animating_scale,
915 float ancestor_maximum_animation_contents_scale,
916 const gfx::Transform& parent_transform,
917 const gfx::Transform& combined_transform,
918 bool* combined_is_animating_scale,
919 float* combined_maximum_animation_contents_scale,
920 float* combined_starting_animation_contents_scale) {
921 *combined_is_animating_scale = false;
922 *combined_maximum_animation_contents_scale = 0.f;
923 *combined_starting_animation_contents_scale = 0.f;
926 static inline void CalculateAnimationContentsScale(
927 LayerImpl* layer,
928 bool ancestor_is_animating_scale,
929 float ancestor_maximum_animation_contents_scale,
930 const gfx::Transform& ancestor_transform,
931 const gfx::Transform& combined_transform,
932 bool* combined_is_animating_scale,
933 float* combined_maximum_animation_contents_scale,
934 float* combined_starting_animation_contents_scale) {
935 if (ancestor_is_animating_scale &&
936 ancestor_maximum_animation_contents_scale == 0.f) {
937 // We've already failed to compute a maximum animated scale at an
938 // ancestor, so we'll continue to fail.
939 *combined_maximum_animation_contents_scale = 0.f;
940 *combined_starting_animation_contents_scale = 0.f;
941 *combined_is_animating_scale = true;
942 return;
945 if (!combined_transform.IsScaleOrTranslation()) {
946 // Computing maximum animated scale in the presence of
947 // non-scale/translation transforms isn't supported.
948 *combined_maximum_animation_contents_scale = 0.f;
949 *combined_starting_animation_contents_scale = 0.f;
950 *combined_is_animating_scale = true;
951 return;
954 // We currently only support computing maximum scale for combinations of
955 // scales and translations. We treat all non-translations as potentially
956 // affecting scale. Animations that include non-translation/scale components
957 // will cause the computation of MaximumScale below to fail.
958 bool layer_is_animating_scale = !layer->HasOnlyTranslationTransforms();
960 if (!layer_is_animating_scale && !ancestor_is_animating_scale) {
961 *combined_maximum_animation_contents_scale = 0.f;
962 *combined_starting_animation_contents_scale = 0.f;
963 *combined_is_animating_scale = false;
964 return;
967 // We don't attempt to accumulate animation scale from multiple nodes,
968 // because of the risk of significant overestimation. For example, one node
969 // may be increasing scale from 1 to 10 at the same time as a descendant is
970 // decreasing scale from 10 to 1. Naively combining these scales would produce
971 // a scale of 100.
972 if (layer_is_animating_scale && ancestor_is_animating_scale) {
973 *combined_maximum_animation_contents_scale = 0.f;
974 *combined_starting_animation_contents_scale = 0.f;
975 *combined_is_animating_scale = true;
976 return;
979 // At this point, we know either the layer or an ancestor, but not both,
980 // is animating scale.
981 *combined_is_animating_scale = true;
982 if (!layer_is_animating_scale) {
983 gfx::Vector2dF layer_transform_scales =
984 MathUtil::ComputeTransform2dScaleComponents(layer->transform(), 0.f);
985 *combined_maximum_animation_contents_scale =
986 ancestor_maximum_animation_contents_scale *
987 std::max(layer_transform_scales.x(), layer_transform_scales.y());
988 *combined_starting_animation_contents_scale =
989 *combined_maximum_animation_contents_scale;
990 return;
993 float layer_maximum_animated_scale = 0.f;
994 float layer_start_animated_scale = 0.f;
995 if (!layer->MaximumTargetScale(&layer_maximum_animated_scale)) {
996 *combined_maximum_animation_contents_scale = 0.f;
997 return;
999 if (!layer->AnimationStartScale(&layer_start_animated_scale)) {
1000 *combined_starting_animation_contents_scale = 0.f;
1001 return;
1004 gfx::Vector2dF ancestor_transform_scales =
1005 MathUtil::ComputeTransform2dScaleComponents(ancestor_transform, 0.f);
1006 float max_scale_xy =
1007 std::max(ancestor_transform_scales.x(), ancestor_transform_scales.y());
1008 *combined_maximum_animation_contents_scale =
1009 layer_maximum_animated_scale * max_scale_xy;
1010 *combined_starting_animation_contents_scale =
1011 layer_start_animated_scale * max_scale_xy;
1014 template <typename LayerTypePtr>
1015 static inline void MarkLayerWithRenderSurfaceLayerListId(
1016 LayerTypePtr layer,
1017 int current_render_surface_layer_list_id) {
1018 layer->draw_properties().last_drawn_render_surface_layer_list_id =
1019 current_render_surface_layer_list_id;
1020 layer->set_layer_or_descendant_is_drawn(
1021 !!current_render_surface_layer_list_id);
1024 template <typename LayerTypePtr>
1025 static inline void MarkMasksWithRenderSurfaceLayerListId(
1026 LayerTypePtr layer,
1027 int current_render_surface_layer_list_id) {
1028 if (layer->mask_layer()) {
1029 MarkLayerWithRenderSurfaceLayerListId(layer->mask_layer(),
1030 current_render_surface_layer_list_id);
1032 if (layer->replica_layer() && layer->replica_layer()->mask_layer()) {
1033 MarkLayerWithRenderSurfaceLayerListId(layer->replica_layer()->mask_layer(),
1034 current_render_surface_layer_list_id);
1038 template <typename LayerListType>
1039 static inline void MarkLayerListWithRenderSurfaceLayerListId(
1040 LayerListType* layer_list,
1041 int current_render_surface_layer_list_id) {
1042 for (typename LayerListType::iterator it = layer_list->begin();
1043 it != layer_list->end();
1044 ++it) {
1045 MarkLayerWithRenderSurfaceLayerListId(*it,
1046 current_render_surface_layer_list_id);
1047 MarkMasksWithRenderSurfaceLayerListId(*it,
1048 current_render_surface_layer_list_id);
1052 static inline void RemoveSurfaceForEarlyExit(
1053 LayerImpl* layer_to_remove,
1054 LayerImplList* render_surface_layer_list) {
1055 DCHECK(layer_to_remove->render_surface());
1056 // Technically, we know that the layer we want to remove should be
1057 // at the back of the render_surface_layer_list. However, we have had
1058 // bugs before that added unnecessary layers here
1059 // (https://bugs.webkit.org/show_bug.cgi?id=74147), but that causes
1060 // things to crash. So here we proactively remove any additional
1061 // layers from the end of the list.
1062 while (render_surface_layer_list->back() != layer_to_remove) {
1063 MarkLayerListWithRenderSurfaceLayerListId(
1064 &render_surface_layer_list->back()->render_surface()->layer_list(), 0);
1065 MarkLayerWithRenderSurfaceLayerListId(render_surface_layer_list->back(), 0);
1067 render_surface_layer_list->back()->ClearRenderSurfaceLayerList();
1068 render_surface_layer_list->pop_back();
1070 DCHECK_EQ(render_surface_layer_list->back(), layer_to_remove);
1071 MarkLayerListWithRenderSurfaceLayerListId(
1072 &layer_to_remove->render_surface()->layer_list(), 0);
1073 MarkLayerWithRenderSurfaceLayerListId(layer_to_remove, 0);
1074 render_surface_layer_list->pop_back();
1075 layer_to_remove->ClearRenderSurfaceLayerList();
1078 struct PreCalculateMetaInformationRecursiveData {
1079 size_t num_unclipped_descendants;
1080 int num_layer_or_descendants_with_copy_request;
1081 int num_layer_or_descendants_with_input_handler;
1083 PreCalculateMetaInformationRecursiveData()
1084 : num_unclipped_descendants(0),
1085 num_layer_or_descendants_with_copy_request(0),
1086 num_layer_or_descendants_with_input_handler(0) {}
1088 void Merge(const PreCalculateMetaInformationRecursiveData& data) {
1089 num_layer_or_descendants_with_copy_request +=
1090 data.num_layer_or_descendants_with_copy_request;
1091 num_layer_or_descendants_with_input_handler +=
1092 data.num_layer_or_descendants_with_input_handler;
1093 num_unclipped_descendants += data.num_unclipped_descendants;
1097 static void ValidateRenderSurface(LayerImpl* layer) {
1098 // This test verifies that there are no cases where a LayerImpl needs
1099 // a render surface, but doesn't have one.
1100 if (layer->render_surface())
1101 return;
1103 DCHECK(layer->filters().IsEmpty()) << "layer: " << layer->id();
1104 DCHECK(layer->background_filters().IsEmpty()) << "layer: " << layer->id();
1105 DCHECK(!layer->mask_layer()) << "layer: " << layer->id();
1106 DCHECK(!layer->replica_layer()) << "layer: " << layer->id();
1107 DCHECK(!IsRootLayer(layer)) << "layer: " << layer->id();
1108 DCHECK(!layer->is_root_for_isolated_group()) << "layer: " << layer->id();
1109 DCHECK(!layer->HasCopyRequest()) << "layer: " << layer->id();
1112 static void ValidateRenderSurface(Layer* layer) {
1115 static bool IsMetaInformationRecomputationNeeded(Layer* layer) {
1116 return layer->layer_tree_host()->needs_meta_info_recomputation();
1119 static void UpdateMetaInformationSequenceNumber(Layer* root_layer) {
1120 root_layer->layer_tree_host()->IncrementMetaInformationSequenceNumber();
1123 static void UpdateMetaInformationSequenceNumber(LayerImpl* root_layer) {
1126 // Recursively walks the layer tree(if needed) to compute any information
1127 // that is needed before doing the main recursion.
1128 static void PreCalculateMetaInformationInternal(
1129 Layer* layer,
1130 PreCalculateMetaInformationRecursiveData* recursive_data) {
1131 ValidateRenderSurface(layer);
1133 if (!IsMetaInformationRecomputationNeeded(layer)) {
1134 DCHECK(IsRootLayer(layer));
1135 return;
1138 layer->set_sorted_for_recursion(false);
1139 layer->draw_properties().has_child_with_a_scroll_parent = false;
1140 layer->set_layer_or_descendant_is_drawn(false);
1141 layer->set_visited(false);
1143 if (!HasInvertibleOrAnimatedTransform(layer)) {
1144 // Layers with singular transforms should not be drawn, the whole subtree
1145 // can be skipped.
1146 return;
1149 if (layer->clip_parent())
1150 recursive_data->num_unclipped_descendants++;
1152 layer->set_num_children_with_scroll_parent(0);
1153 for (size_t i = 0; i < layer->children().size(); ++i) {
1154 Layer* child_layer = layer->child_at(i);
1156 PreCalculateMetaInformationRecursiveData data_for_child;
1157 PreCalculateMetaInformationInternal(child_layer, &data_for_child);
1159 if (child_layer->scroll_parent()) {
1160 layer->draw_properties().has_child_with_a_scroll_parent = true;
1161 layer->set_num_children_with_scroll_parent(
1162 layer->num_children_with_scroll_parent() + 1);
1164 recursive_data->Merge(data_for_child);
1167 if (layer->clip_children()) {
1168 size_t num_clip_children = layer->clip_children()->size();
1169 DCHECK_GE(recursive_data->num_unclipped_descendants, num_clip_children);
1170 recursive_data->num_unclipped_descendants -= num_clip_children;
1173 if (layer->HasCopyRequest())
1174 recursive_data->num_layer_or_descendants_with_copy_request++;
1176 if (!layer->touch_event_handler_region().IsEmpty() ||
1177 layer->have_wheel_event_handlers())
1178 recursive_data->num_layer_or_descendants_with_input_handler++;
1180 layer->draw_properties().num_unclipped_descendants =
1181 recursive_data->num_unclipped_descendants;
1182 layer->draw_properties().layer_or_descendant_has_copy_request =
1183 (recursive_data->num_layer_or_descendants_with_copy_request != 0);
1184 layer->draw_properties().layer_or_descendant_has_input_handler =
1185 (recursive_data->num_layer_or_descendants_with_input_handler != 0);
1186 layer->set_num_layer_or_descandant_with_copy_request(
1187 recursive_data->num_layer_or_descendants_with_copy_request);
1189 if (IsRootLayer(layer))
1190 layer->layer_tree_host()->SetNeedsMetaInfoRecomputation(false);
1193 static void PreCalculateMetaInformationInternal(
1194 LayerImpl* layer,
1195 PreCalculateMetaInformationRecursiveData* recursive_data) {
1196 ValidateRenderSurface(layer);
1198 layer->set_sorted_for_recursion(false);
1199 layer->draw_properties().has_child_with_a_scroll_parent = false;
1200 layer->set_layer_or_descendant_is_drawn(false);
1201 layer->set_visited(false);
1203 if (!HasInvertibleOrAnimatedTransform(layer)) {
1204 // Layers with singular transforms should not be drawn, the whole subtree
1205 // can be skipped.
1206 return;
1209 if (layer->clip_parent())
1210 recursive_data->num_unclipped_descendants++;
1212 for (size_t i = 0; i < layer->children().size(); ++i) {
1213 LayerImpl* child_layer = layer->child_at(i);
1215 PreCalculateMetaInformationRecursiveData data_for_child;
1216 PreCalculateMetaInformationInternal(child_layer, &data_for_child);
1218 if (child_layer->scroll_parent())
1219 layer->draw_properties().has_child_with_a_scroll_parent = true;
1220 recursive_data->Merge(data_for_child);
1223 if (layer->clip_children()) {
1224 size_t num_clip_children = layer->clip_children()->size();
1225 DCHECK_GE(recursive_data->num_unclipped_descendants, num_clip_children);
1226 recursive_data->num_unclipped_descendants -= num_clip_children;
1229 if (layer->HasCopyRequest())
1230 recursive_data->num_layer_or_descendants_with_copy_request++;
1232 if (!layer->touch_event_handler_region().IsEmpty() ||
1233 layer->have_wheel_event_handlers())
1234 recursive_data->num_layer_or_descendants_with_input_handler++;
1236 layer->draw_properties().num_unclipped_descendants =
1237 recursive_data->num_unclipped_descendants;
1238 layer->draw_properties().layer_or_descendant_has_copy_request =
1239 (recursive_data->num_layer_or_descendants_with_copy_request != 0);
1240 layer->draw_properties().layer_or_descendant_has_input_handler =
1241 (recursive_data->num_layer_or_descendants_with_input_handler != 0);
1244 void LayerTreeHostCommon::PreCalculateMetaInformation(Layer* root_layer) {
1245 PreCalculateMetaInformationRecursiveData recursive_data;
1246 PreCalculateMetaInformationInternal(root_layer, &recursive_data);
1249 void LayerTreeHostCommon::PreCalculateMetaInformationForTesting(
1250 LayerImpl* root_layer) {
1251 PreCalculateMetaInformationRecursiveData recursive_data;
1252 PreCalculateMetaInformationInternal(root_layer, &recursive_data);
1255 void LayerTreeHostCommon::PreCalculateMetaInformationForTesting(
1256 Layer* root_layer) {
1257 UpdateMetaInformationSequenceNumber(root_layer);
1258 PreCalculateMetaInformationRecursiveData recursive_data;
1259 PreCalculateMetaInformationInternal(root_layer, &recursive_data);
1262 template <typename LayerType>
1263 struct SubtreeGlobals {
1264 int max_texture_size;
1265 float device_scale_factor;
1266 float page_scale_factor;
1267 const LayerType* page_scale_layer;
1268 gfx::Vector2dF elastic_overscroll;
1269 const LayerType* elastic_overscroll_application_layer;
1270 bool can_adjust_raster_scales;
1271 bool can_render_to_separate_surface;
1272 bool layers_always_allowed_lcd_text;
1275 template<typename LayerType>
1276 struct DataForRecursion {
1277 // The accumulated sequence of transforms a layer will use to determine its
1278 // own draw transform.
1279 gfx::Transform parent_matrix;
1281 // The accumulated sequence of transforms a layer will use to determine its
1282 // own screen-space transform.
1283 gfx::Transform full_hierarchy_matrix;
1285 // The transform that removes all scrolling that may have occurred between a
1286 // fixed-position layer and its container, so that the layer actually does
1287 // remain fixed.
1288 gfx::Transform scroll_compensation_matrix;
1290 // The ancestor that would be the container for any fixed-position / sticky
1291 // layers.
1292 LayerType* fixed_container;
1294 // This is the normal clip rect that is propagated from parent to child.
1295 gfx::Rect clip_rect_in_target_space;
1297 // When the layer's children want to compute their visible content rect, they
1298 // want to know what their target surface's clip rect will be. BUT - they
1299 // want to know this clip rect represented in their own target space. This
1300 // requires inverse-projecting the surface's clip rect from the surface's
1301 // render target space down to the surface's own space. Instead of computing
1302 // this value redundantly for each child layer, it is computed only once
1303 // while dealing with the parent layer, and then this precomputed value is
1304 // passed down the recursion to the children that actually use it.
1305 gfx::Rect clip_rect_of_target_surface_in_target_space;
1307 // The maximum amount by which this layer will be scaled during the lifetime
1308 // of currently running animations.
1309 float maximum_animation_contents_scale;
1311 bool ancestor_is_animating_scale;
1312 bool ancestor_clips_subtree;
1313 typename LayerType::RenderSurfaceType*
1314 nearest_occlusion_immune_ancestor_surface;
1315 bool in_subtree_of_page_scale_layer;
1316 bool subtree_can_use_lcd_text;
1317 bool subtree_is_visible_from_ancestor;
1320 template <typename LayerType>
1321 static LayerType* GetChildContainingLayer(const LayerType& parent,
1322 LayerType* layer) {
1323 for (LayerType* ancestor = layer; ancestor; ancestor = ancestor->parent()) {
1324 if (ancestor->parent() == &parent)
1325 return ancestor;
1327 NOTREACHED();
1328 return 0;
1331 template <typename LayerType>
1332 static void AddScrollParentChain(std::vector<LayerType*>* out,
1333 const LayerType& parent,
1334 LayerType* layer) {
1335 // At a high level, this function walks up the chain of scroll parents
1336 // recursively, and once we reach the end of the chain, we add the child
1337 // of |parent| containing each scroll ancestor as we unwind. The result is
1338 // an ordering of parent's children that ensures that scroll parents are
1339 // visited before their descendants.
1340 // Take for example this layer tree:
1342 // + stacking_context
1343 // + scroll_child (1)
1344 // + scroll_parent_graphics_layer (*)
1345 // | + scroll_parent_scrolling_layer
1346 // | + scroll_parent_scrolling_content_layer (2)
1347 // + scroll_grandparent_graphics_layer (**)
1348 // + scroll_grandparent_scrolling_layer
1349 // + scroll_grandparent_scrolling_content_layer (3)
1351 // The scroll child is (1), its scroll parent is (2) and its scroll
1352 // grandparent is (3). Note, this doesn't mean that (2)'s scroll parent is
1353 // (3), it means that (*)'s scroll parent is (3). We don't want our list to
1354 // look like [ (3), (2), (1) ], even though that does have the ancestor chain
1355 // in the right order. Instead, we want [ (**), (*), (1) ]. That is, only want
1356 // (1)'s siblings in the list, but we want them to appear in such an order
1357 // that the scroll ancestors get visited in the correct order.
1359 // So our first task at this step of the recursion is to determine the layer
1360 // that we will potentionally add to the list. That is, the child of parent
1361 // containing |layer|.
1362 LayerType* child = GetChildContainingLayer(parent, layer);
1363 if (child->sorted_for_recursion())
1364 return;
1366 if (LayerType* scroll_parent = child->scroll_parent())
1367 AddScrollParentChain(out, parent, scroll_parent);
1369 out->push_back(child);
1370 bool sorted_for_recursion = true;
1371 child->set_sorted_for_recursion(sorted_for_recursion);
1374 template <typename LayerType>
1375 static bool SortChildrenForRecursion(std::vector<LayerType*>* out,
1376 const LayerType& parent) {
1377 out->reserve(parent.children().size());
1378 bool order_changed = false;
1379 for (size_t i = 0; i < parent.children().size(); ++i) {
1380 LayerType* current =
1381 LayerTreeHostCommon::get_layer_as_raw_ptr(parent.children(), i);
1383 if (current->sorted_for_recursion()) {
1384 order_changed = true;
1385 continue;
1388 AddScrollParentChain(out, parent, current);
1391 DCHECK_EQ(parent.children().size(), out->size());
1392 return order_changed;
1395 // Recursively walks the layer tree starting at the given node and computes all
1396 // the necessary transformations, clip rects, render surfaces, etc.
1397 template <typename LayerType>
1398 static void CalculateDrawPropertiesInternal(
1399 LayerType* layer,
1400 const SubtreeGlobals<LayerType>& globals,
1401 const DataForRecursion<LayerType>& data_from_ancestor,
1402 std::vector<AccumulatedSurfaceState<LayerType>>*
1403 accumulated_surface_state) {
1404 // This function computes the new matrix transformations recursively for this
1405 // layer and all its descendants. It also computes the appropriate render
1406 // surfaces.
1407 // Some important points to remember:
1409 // 0. Here, transforms are notated in Matrix x Vector order, and in words we
1410 // describe what the transform does from left to right.
1412 // 1. In our terminology, the "layer origin" refers to the top-left corner of
1413 // a layer, and the positive Y-axis points downwards. This interpretation is
1414 // valid because the orthographic projection applied at draw time flips the Y
1415 // axis appropriately.
1417 // 2. The anchor point, when given as a PointF object, is specified in "unit
1418 // layer space", where the bounds of the layer map to [0, 1]. However, as a
1419 // Transform object, the transform to the anchor point is specified in "layer
1420 // space", where the bounds of the layer map to [bounds.width(),
1421 // bounds.height()].
1423 // 3. Definition of various transforms used:
1424 // M[parent] is the parent matrix, with respect to the nearest render
1425 // surface, passed down recursively.
1427 // M[root] is the full hierarchy, with respect to the root, passed down
1428 // recursively.
1430 // Tr[origin] is the translation matrix from the parent's origin to
1431 // this layer's origin.
1433 // Tr[origin2anchor] is the translation from the layer's origin to its
1434 // anchor point
1436 // Tr[origin2center] is the translation from the layer's origin to its
1437 // center
1439 // M[layer] is the layer's matrix (applied at the anchor point)
1441 // S[layer2content] is the ratio of a layer's content_bounds() to its
1442 // Bounds().
1444 // Some composite transforms can help in understanding the sequence of
1445 // transforms:
1446 // composite_layer_transform = Tr[origin2anchor] * M[layer] *
1447 // Tr[origin2anchor].inverse()
1449 // 4. When a layer (or render surface) is drawn, it is drawn into a "target
1450 // render surface". Therefore the draw transform does not necessarily
1451 // transform from screen space to local layer space. Instead, the draw
1452 // transform is the transform between the "target render surface space" and
1453 // local layer space. Note that render surfaces, except for the root, also
1454 // draw themselves into a different target render surface, and so their draw
1455 // transform and origin transforms are also described with respect to the
1456 // target.
1458 // Using these definitions, then:
1460 // The draw transform for the layer is:
1461 // M[draw] = M[parent] * Tr[origin] * composite_layer_transform *
1462 // S[layer2content] = M[parent] * Tr[layer->position() + anchor] *
1463 // M[layer] * Tr[anchor2origin] * S[layer2content]
1465 // Interpreting the math left-to-right, this transforms from the
1466 // layer's render surface to the origin of the layer in content space.
1468 // The screen space transform is:
1469 // M[screenspace] = M[root] * Tr[origin] * composite_layer_transform *
1470 // S[layer2content]
1471 // = M[root] * Tr[layer->position() + anchor] * M[layer]
1472 // * Tr[anchor2origin] * S[layer2content]
1474 // Interpreting the math left-to-right, this transforms from the root
1475 // render surface's content space to the origin of the layer in content
1476 // space.
1478 // The transform hierarchy that is passed on to children (i.e. the child's
1479 // parent_matrix) is:
1480 // M[parent]_for_child = M[parent] * Tr[origin] *
1481 // composite_layer_transform
1482 // = M[parent] * Tr[layer->position() + anchor] *
1483 // M[layer] * Tr[anchor2origin]
1485 // and a similar matrix for the full hierarchy with respect to the
1486 // root.
1488 // Finally, note that the final matrix used by the shader for the layer is P *
1489 // M[draw] * S . This final product is computed in drawTexturedQuad(), where:
1490 // P is the projection matrix
1491 // S is the scale adjustment (to scale up a canonical quad to the
1492 // layer's size)
1494 // When a render surface has a replica layer, that layer's transform is used
1495 // to draw a second copy of the surface. gfx::Transforms named here are
1496 // relative to the surface, unless they specify they are relative to the
1497 // replica layer.
1499 // We will denote a scale by device scale S[deviceScale]
1501 // The render surface draw transform to its target surface origin is:
1502 // M[surfaceDraw] = M[owningLayer->Draw]
1504 // The render surface origin transform to its the root (screen space) origin
1505 // is:
1506 // M[surface2root] = M[owningLayer->screenspace] *
1507 // S[deviceScale].inverse()
1509 // The replica draw transform to its target surface origin is:
1510 // M[replicaDraw] = S[deviceScale] * M[surfaceDraw] *
1511 // Tr[replica->position() + replica->anchor()] * Tr[replica] *
1512 // Tr[origin2anchor].inverse() * S[contents_scale].inverse()
1514 // The replica draw transform to the root (screen space) origin is:
1515 // M[replica2root] = M[surface2root] * Tr[replica->position()] *
1516 // Tr[replica] * Tr[origin2anchor].inverse()
1519 // It makes no sense to have a non-unit page_scale_factor without specifying
1520 // which layer roots the subtree the scale is applied to.
1521 DCHECK(globals.page_scale_layer || (globals.page_scale_factor == 1.f));
1523 CHECK(!layer->visited());
1524 bool visited = true;
1525 layer->set_visited(visited);
1527 DataForRecursion<LayerType> data_for_children;
1528 typename LayerType::RenderSurfaceType*
1529 nearest_occlusion_immune_ancestor_surface =
1530 data_from_ancestor.nearest_occlusion_immune_ancestor_surface;
1531 data_for_children.in_subtree_of_page_scale_layer =
1532 data_from_ancestor.in_subtree_of_page_scale_layer;
1533 data_for_children.subtree_can_use_lcd_text =
1534 data_from_ancestor.subtree_can_use_lcd_text;
1536 // Layers that are marked as hidden will hide themselves and their subtree.
1537 // Exception: Layers with copy requests, whether hidden or not, must be drawn
1538 // anyway. In this case, we will inform their subtree they are visible to get
1539 // the right results.
1540 const bool layer_is_visible =
1541 data_from_ancestor.subtree_is_visible_from_ancestor &&
1542 !layer->hide_layer_and_subtree();
1543 const bool layer_is_drawn = layer_is_visible || layer->HasCopyRequest();
1545 // The root layer cannot skip CalcDrawProperties.
1546 if (!IsRootLayer(layer) && SubtreeShouldBeSkipped(layer, layer_is_drawn)) {
1547 return;
1550 // We need to circumvent the normal recursive flow of information for clip
1551 // children (they don't inherit their direct ancestor's clip information).
1552 // This is unfortunate, and would be unnecessary if we were to formally
1553 // separate the clipping hierarchy from the layer hierarchy.
1554 bool ancestor_clips_subtree = data_from_ancestor.ancestor_clips_subtree;
1555 gfx::Rect ancestor_clip_rect_in_target_space =
1556 data_from_ancestor.clip_rect_in_target_space;
1558 // Update our clipping state. If we have a clip parent we will need to pull
1559 // from the clip state cache rather than using the clip state passed from our
1560 // immediate ancestor.
1561 UpdateClipRectsForClipChild<LayerType>(
1562 layer, &ancestor_clip_rect_in_target_space, &ancestor_clips_subtree);
1564 // As this function proceeds, these are the properties for the current
1565 // layer that actually get computed. To avoid unnecessary copies
1566 // (particularly for matrices), we do computations directly on these values
1567 // when possible.
1568 DrawProperties<LayerType>& layer_draw_properties = layer->draw_properties();
1570 gfx::Rect clip_rect_in_target_space;
1571 bool layer_or_ancestor_clips_descendants = false;
1573 // This value is cached on the stack so that we don't have to inverse-project
1574 // the surface's clip rect redundantly for every layer. This value is the
1575 // same as the target surface's clip rect, except that instead of being
1576 // described in the target surface's target's space, it is described in the
1577 // current render target's space.
1578 gfx::Rect clip_rect_of_target_surface_in_target_space;
1580 float accumulated_draw_opacity = layer->opacity();
1581 if (layer->parent())
1582 accumulated_draw_opacity *= layer->parent()->draw_opacity();
1584 bool animating_transform_to_screen =
1585 layer->HasPotentiallyRunningTransformAnimation();
1586 if (layer->parent()) {
1587 animating_transform_to_screen |=
1588 layer->parent()->screen_space_transform_is_animating();
1590 gfx::Point3F transform_origin = layer->transform_origin();
1591 gfx::ScrollOffset scroll_offset = GetEffectiveCurrentScrollOffset(layer);
1592 gfx::PointF position =
1593 layer->position() - ScrollOffsetToVector2dF(scroll_offset);
1594 gfx::Transform combined_transform = data_from_ancestor.parent_matrix;
1595 if (!layer->transform().IsIdentity()) {
1596 // LT = Tr[origin] * Tr[origin2transformOrigin]
1597 combined_transform.Translate3d(position.x() + transform_origin.x(),
1598 position.y() + transform_origin.y(),
1599 transform_origin.z());
1600 // LT = Tr[origin] * Tr[origin2origin] * M[layer]
1601 combined_transform.PreconcatTransform(layer->transform());
1602 // LT = Tr[origin] * Tr[origin2origin] * M[layer] *
1603 // Tr[transformOrigin2origin]
1604 combined_transform.Translate3d(
1605 -transform_origin.x(), -transform_origin.y(), -transform_origin.z());
1606 } else {
1607 combined_transform.Translate(position.x(), position.y());
1610 gfx::Vector2dF effective_scroll_delta = GetEffectiveScrollDelta(layer);
1611 if (!animating_transform_to_screen && layer->scrollable() &&
1612 combined_transform.IsScaleOrTranslation()) {
1613 // Align the scrollable layer's position to screen space pixels to avoid
1614 // blurriness. To avoid side-effects, do this only if the transform is
1615 // simple.
1616 gfx::Vector2dF previous_translation = combined_transform.To2dTranslation();
1617 combined_transform.RoundTranslationComponents();
1618 gfx::Vector2dF current_translation = combined_transform.To2dTranslation();
1620 // This rounding changes the scroll delta, and so must be included
1621 // in the scroll compensation matrix. The scaling converts from physical
1622 // coordinates to the scroll delta's CSS coordinates (using the parent
1623 // matrix instead of combined transform since scrolling is applied before
1624 // the layer's transform). For example, if we have a total scale factor of
1625 // 3.0, then 1 physical pixel is only 1/3 of a CSS pixel.
1626 gfx::Vector2dF parent_scales = MathUtil::ComputeTransform2dScaleComponents(
1627 data_from_ancestor.parent_matrix, 1.f);
1628 effective_scroll_delta -=
1629 gfx::ScaleVector2d(current_translation - previous_translation,
1630 1.f / parent_scales.x(),
1631 1.f / parent_scales.y());
1634 // Apply adjustment from position constraints.
1635 ApplyPositionAdjustment(layer, data_from_ancestor.fixed_container,
1636 data_from_ancestor.scroll_compensation_matrix, &combined_transform);
1638 bool combined_is_animating_scale = false;
1639 float combined_maximum_animation_contents_scale = 0.f;
1640 float combined_starting_animation_contents_scale = 0.f;
1641 if (globals.can_adjust_raster_scales) {
1642 CalculateAnimationContentsScale(
1643 layer, data_from_ancestor.ancestor_is_animating_scale,
1644 data_from_ancestor.maximum_animation_contents_scale,
1645 data_from_ancestor.parent_matrix, combined_transform,
1646 &combined_is_animating_scale,
1647 &combined_maximum_animation_contents_scale,
1648 &combined_starting_animation_contents_scale);
1650 data_for_children.ancestor_is_animating_scale = combined_is_animating_scale;
1651 data_for_children.maximum_animation_contents_scale =
1652 combined_maximum_animation_contents_scale;
1654 // Compute the 2d scale components of the transform hierarchy up to the target
1655 // surface. From there, we can decide on a contents scale for the layer.
1656 float layer_scale_factors = globals.device_scale_factor;
1657 if (data_from_ancestor.in_subtree_of_page_scale_layer)
1658 layer_scale_factors *= globals.page_scale_factor;
1659 gfx::Vector2dF combined_transform_scales =
1660 MathUtil::ComputeTransform2dScaleComponents(
1661 combined_transform,
1662 layer_scale_factors);
1664 UpdateLayerScaleDrawProperties(layer,
1665 combined_maximum_animation_contents_scale,
1666 combined_starting_animation_contents_scale);
1668 LayerType* mask_layer = layer->mask_layer();
1669 if (mask_layer) {
1670 UpdateLayerScaleDrawProperties(mask_layer,
1671 combined_maximum_animation_contents_scale,
1672 combined_starting_animation_contents_scale);
1675 LayerType* replica_mask_layer =
1676 layer->replica_layer() ? layer->replica_layer()->mask_layer() : NULL;
1677 if (replica_mask_layer) {
1678 UpdateLayerScaleDrawProperties(replica_mask_layer,
1679 combined_maximum_animation_contents_scale,
1680 combined_starting_animation_contents_scale);
1683 if (layer == globals.page_scale_layer) {
1684 combined_transform.Scale(globals.page_scale_factor,
1685 globals.page_scale_factor);
1686 data_for_children.in_subtree_of_page_scale_layer = true;
1689 // The draw_transform that gets computed below is effectively the layer's
1690 // draw_transform, unless the layer itself creates a render_surface. In that
1691 // case, the render_surface re-parents the transforms.
1692 layer_draw_properties.target_space_transform = combined_transform;
1694 // The layer's screen_space_transform represents the transform between root
1695 // layer's "screen space" and local content space.
1696 layer_draw_properties.screen_space_transform =
1697 data_from_ancestor.full_hierarchy_matrix;
1698 layer_draw_properties.screen_space_transform.PreconcatTransform
1699 (layer_draw_properties.target_space_transform);
1701 bool layer_can_use_lcd_text = true;
1702 bool subtree_can_use_lcd_text = true;
1703 if (!globals.layers_always_allowed_lcd_text) {
1704 // To avoid color fringing, LCD text should only be used on opaque layers
1705 // with just integral translation.
1706 subtree_can_use_lcd_text = data_from_ancestor.subtree_can_use_lcd_text &&
1707 accumulated_draw_opacity == 1.f &&
1708 layer_draw_properties.target_space_transform
1709 .IsIdentityOrIntegerTranslation();
1710 // Also disable LCD text locally for non-opaque content.
1711 layer_can_use_lcd_text = subtree_can_use_lcd_text &&
1712 layer->contents_opaque();
1715 // full_hierarchy_matrix is the matrix that transforms objects between screen
1716 // space (except projection matrix) and the most recent RenderSurfaceImpl's
1717 // space. next_hierarchy_matrix will only change if this layer uses a new
1718 // RenderSurfaceImpl, otherwise remains the same.
1719 data_for_children.full_hierarchy_matrix =
1720 data_from_ancestor.full_hierarchy_matrix;
1722 bool render_to_separate_surface =
1723 IsRootLayer(layer) ||
1724 (globals.can_render_to_separate_surface && layer->render_surface());
1726 if (render_to_separate_surface) {
1727 DCHECK(layer->render_surface());
1728 // Check back-face visibility before continuing with this surface and its
1729 // subtree
1730 if (!layer->double_sided() && TransformToParentIsKnown(layer) &&
1731 IsSurfaceBackFaceVisible(layer, combined_transform)) {
1732 return;
1735 typename LayerType::RenderSurfaceType* render_surface =
1736 layer->render_surface();
1738 if (IsRootLayer(layer)) {
1739 // The root layer's render surface size is predetermined and so the root
1740 // layer can't directly support non-identity transforms. It should just
1741 // forward top-level transforms to the rest of the tree.
1742 data_for_children.parent_matrix = combined_transform;
1744 // The root surface does not contribute to any other surface, it has no
1745 // target.
1746 render_surface->set_contributes_to_drawn_surface(false);
1747 } else {
1748 // The owning layer's draw transform has a scale from content to layer
1749 // space which we do not want; so here we use the combined_transform
1750 // instead of the draw_transform. However, we do need to add a different
1751 // scale factor that accounts for the surface's pixel dimensions.
1752 // Remove the combined_transform scale from the draw transform.
1753 gfx::Transform draw_transform = combined_transform;
1754 draw_transform.Scale(1.0 / combined_transform_scales.x(),
1755 1.0 / combined_transform_scales.y());
1756 render_surface->SetDrawTransform(draw_transform);
1758 // The owning layer's transform was re-parented by the surface, so the
1759 // layer's new draw_transform only needs to scale the layer to surface
1760 // space.
1761 layer_draw_properties.target_space_transform.MakeIdentity();
1762 layer_draw_properties.target_space_transform.Scale(
1763 combined_transform_scales.x(), combined_transform_scales.y());
1765 // Inside the surface's subtree, we scale everything to the owning layer's
1766 // scale. The sublayer matrix transforms layer rects into target surface
1767 // content space. Conceptually, all layers in the subtree inherit the
1768 // scale at the point of the render surface in the transform hierarchy,
1769 // but we apply it explicitly to the owning layer and the remainder of the
1770 // subtree independently.
1771 DCHECK(data_for_children.parent_matrix.IsIdentity());
1772 data_for_children.parent_matrix.Scale(combined_transform_scales.x(),
1773 combined_transform_scales.y());
1775 // Even if the |layer_is_drawn|, it only contributes to a drawn surface
1776 // when the |layer_is_visible|.
1777 render_surface->set_contributes_to_drawn_surface(layer_is_visible);
1780 // The opacity value is moved from the layer to its surface, so that the
1781 // entire subtree properly inherits opacity.
1782 render_surface->SetDrawOpacity(accumulated_draw_opacity);
1783 layer_draw_properties.opacity = 1.f;
1784 DCHECK_EQ(layer->draw_blend_mode(), SkXfermode::kSrcOver_Mode);
1786 layer_draw_properties.screen_space_transform_is_animating =
1787 animating_transform_to_screen;
1789 // Update the aggregate hierarchy matrix to include the transform of the
1790 // newly created RenderSurfaceImpl.
1791 data_for_children.full_hierarchy_matrix.PreconcatTransform(
1792 render_surface->draw_transform());
1794 // A render surface inherently acts as a flattening point for the content of
1795 // its descendants.
1796 data_for_children.full_hierarchy_matrix.FlattenTo2d();
1798 if (layer->mask_layer()) {
1799 DrawProperties<LayerType>& mask_layer_draw_properties =
1800 layer->mask_layer()->draw_properties();
1801 mask_layer_draw_properties.visible_layer_rect =
1802 gfx::Rect(layer->bounds());
1803 // Temporarily copy the draw transform of the mask's owning layer into the
1804 // mask layer draw properties. This won't actually get used for drawing
1805 // (the render surface uses the mask texture directly), but will get used
1806 // to get the correct contents scale.
1807 // TODO(enne): do something similar for property trees.
1808 mask_layer_draw_properties.target_space_transform =
1809 layer_draw_properties.target_space_transform;
1812 if (layer->replica_layer() && layer->replica_layer()->mask_layer()) {
1813 DrawProperties<LayerType>& replica_mask_draw_properties =
1814 layer->replica_layer()->mask_layer()->draw_properties();
1815 replica_mask_draw_properties.visible_layer_rect =
1816 gfx::Rect(layer->bounds());
1817 replica_mask_draw_properties.target_space_transform =
1818 layer_draw_properties.target_space_transform;
1821 // Ignore occlusion from outside the surface when surface contents need to
1822 // be fully drawn. Layers with copy-request need to be complete.
1823 // We could be smarter about layers with replica and exclude regions
1824 // where both layer and the replica are occluded, but this seems like an
1825 // overkill. The same is true for layers with filters that move pixels.
1826 // TODO(senorblanco): make this smarter for the SkImageFilter case (check
1827 // for pixel-moving filters)
1828 if (layer->HasCopyRequest() ||
1829 layer->has_replica() ||
1830 layer->filters().HasReferenceFilter() ||
1831 layer->filters().HasFilterThatMovesPixels()) {
1832 nearest_occlusion_immune_ancestor_surface = render_surface;
1834 render_surface->SetNearestOcclusionImmuneAncestor(
1835 nearest_occlusion_immune_ancestor_surface);
1837 layer_or_ancestor_clips_descendants = false;
1838 bool subtree_is_clipped_by_surface_bounds = false;
1839 if (ancestor_clips_subtree) {
1840 // It may be the layer or the surface doing the clipping of the subtree,
1841 // but in either case, we'll be clipping to the projected clip rect of our
1842 // ancestor.
1843 gfx::Transform inverse_surface_draw_transform(
1844 gfx::Transform::kSkipInitialization);
1845 if (!render_surface->draw_transform().GetInverse(
1846 &inverse_surface_draw_transform)) {
1847 // TODO(shawnsingh): Either we need to handle uninvertible transforms
1848 // here, or DCHECK that the transform is invertible.
1851 gfx::Rect surface_clip_rect_in_target_space = gfx::IntersectRects(
1852 data_from_ancestor.clip_rect_of_target_surface_in_target_space,
1853 ancestor_clip_rect_in_target_space);
1854 gfx::Rect projected_surface_rect = MathUtil::ProjectEnclosingClippedRect(
1855 inverse_surface_draw_transform, surface_clip_rect_in_target_space);
1857 if (layer_draw_properties.num_unclipped_descendants > 0u) {
1858 // If we have unclipped descendants, we cannot count on the render
1859 // surface's bounds clipping our subtree: the unclipped descendants
1860 // could cause us to expand our bounds. In this case, we must rely on
1861 // layer clipping for correctess. NB: since we can only encounter
1862 // translations between a clip child and its clip parent, clipping is
1863 // guaranteed to be exact in this case.
1864 layer_or_ancestor_clips_descendants = true;
1865 clip_rect_in_target_space = projected_surface_rect;
1866 } else {
1867 // The new render_surface here will correctly clip the entire subtree.
1868 // So, we do not need to continue propagating the clipping state further
1869 // down the tree. This way, we can avoid transforming clip rects from
1870 // ancestor target surface space to current target surface space that
1871 // could cause more w < 0 headaches. The render surface clip rect is
1872 // expressed in the space where this surface draws, i.e. the same space
1873 // as clip_rect_from_ancestor_in_ancestor_target_space.
1874 render_surface->SetClipRect(ancestor_clip_rect_in_target_space);
1875 clip_rect_of_target_surface_in_target_space = projected_surface_rect;
1876 subtree_is_clipped_by_surface_bounds = true;
1880 DCHECK(layer->render_surface());
1881 DCHECK(!layer->parent() || layer->parent()->render_target() ==
1882 accumulated_surface_state->back().render_target);
1884 accumulated_surface_state->push_back(
1885 AccumulatedSurfaceState<LayerType>(layer));
1887 render_surface->SetIsClipped(subtree_is_clipped_by_surface_bounds);
1888 if (!subtree_is_clipped_by_surface_bounds) {
1889 render_surface->SetClipRect(gfx::Rect());
1890 clip_rect_of_target_surface_in_target_space =
1891 data_from_ancestor.clip_rect_of_target_surface_in_target_space;
1894 // If the new render surface is drawn translucent or with a non-integral
1895 // translation then the subtree that gets drawn on this render surface
1896 // cannot use LCD text.
1897 data_for_children.subtree_can_use_lcd_text = subtree_can_use_lcd_text;
1899 } else {
1900 DCHECK(layer->parent());
1902 // Note: layer_draw_properties.target_space_transform is computed above,
1903 // before this if-else statement.
1904 layer_draw_properties.screen_space_transform_is_animating =
1905 animating_transform_to_screen;
1906 layer_draw_properties.opacity = accumulated_draw_opacity;
1907 DCHECK_EQ(layer->draw_blend_mode(), layer->blend_mode());
1908 data_for_children.parent_matrix = combined_transform;
1910 // Layers without render_surfaces directly inherit the ancestor's clip
1911 // status.
1912 layer_or_ancestor_clips_descendants = ancestor_clips_subtree;
1913 if (ancestor_clips_subtree) {
1914 clip_rect_in_target_space =
1915 ancestor_clip_rect_in_target_space;
1918 // The surface's cached clip rect value propagates regardless of what
1919 // clipping goes on between layers here.
1920 clip_rect_of_target_surface_in_target_space =
1921 data_from_ancestor.clip_rect_of_target_surface_in_target_space;
1924 layer_draw_properties.can_use_lcd_text = layer_can_use_lcd_text;
1926 // The layer bounds() includes the layer's bounds_delta() which we want
1927 // for the clip rect.
1928 gfx::Rect rect_in_target_space = MathUtil::MapEnclosingClippedRect(
1929 layer->draw_transform(), gfx::Rect(layer->bounds()));
1931 if (LayerClipsSubtree(layer)) {
1932 layer_or_ancestor_clips_descendants = true;
1933 if (ancestor_clips_subtree && !render_to_separate_surface) {
1934 // A layer without render surface shares the same target as its ancestor.
1935 clip_rect_in_target_space =
1936 ancestor_clip_rect_in_target_space;
1937 clip_rect_in_target_space.Intersect(rect_in_target_space);
1938 } else {
1939 clip_rect_in_target_space = rect_in_target_space;
1943 // Tell the layer the rect that it's clipped by. In theory we could use a
1944 // tighter clip rect here (drawable_content_rect), but that actually does not
1945 // reduce how much would be drawn, and instead it would create unnecessary
1946 // changes to scissor state affecting GPU performance. Our clip information
1947 // is used in the recursion below, so we must set it beforehand.
1948 DCHECK_EQ(layer_or_ancestor_clips_descendants, layer->is_clipped());
1949 if (layer_or_ancestor_clips_descendants) {
1950 layer_draw_properties.clip_rect = clip_rect_in_target_space;
1951 } else {
1952 // Initialize the clip rect to a safe value that will not clip the
1953 // layer, just in case clipping is still accidentally used.
1954 layer_draw_properties.clip_rect = rect_in_target_space;
1957 if (!layer->children().empty()) {
1958 if (layer == globals.elastic_overscroll_application_layer) {
1959 data_for_children.parent_matrix.Translate(
1960 -globals.elastic_overscroll.x(), -globals.elastic_overscroll.y());
1963 // Flatten to 2D if the layer doesn't preserve 3D.
1964 if (layer->should_flatten_transform())
1965 data_for_children.parent_matrix.FlattenTo2d();
1967 data_for_children.scroll_compensation_matrix =
1968 ComputeScrollCompensationMatrixForChildren(
1969 layer,
1970 data_from_ancestor.parent_matrix,
1971 data_from_ancestor.scroll_compensation_matrix,
1972 effective_scroll_delta);
1973 data_for_children.fixed_container =
1974 layer->IsContainerForFixedPositionLayers() ?
1975 layer : data_from_ancestor.fixed_container;
1977 data_for_children.clip_rect_in_target_space = clip_rect_in_target_space;
1978 data_for_children.clip_rect_of_target_surface_in_target_space =
1979 clip_rect_of_target_surface_in_target_space;
1980 data_for_children.ancestor_clips_subtree =
1981 layer_or_ancestor_clips_descendants;
1982 data_for_children.nearest_occlusion_immune_ancestor_surface =
1983 nearest_occlusion_immune_ancestor_surface;
1984 data_for_children.subtree_is_visible_from_ancestor = layer_is_drawn;
1987 std::vector<LayerType*> sorted_children;
1988 if (layer_draw_properties.has_child_with_a_scroll_parent)
1989 SortChildrenForRecursion(&sorted_children, *layer);
1991 for (size_t i = 0; i < layer->children().size(); ++i) {
1992 // If one of layer's children has a scroll parent, then we may have to
1993 // visit the children out of order. The new order is stored in
1994 // sorted_children. Otherwise, we'll grab the child directly from the
1995 // layer's list of children.
1997 LayerType* child =
1998 layer_draw_properties.has_child_with_a_scroll_parent
1999 ? sorted_children[i]
2000 : LayerTreeHostCommon::get_layer_as_raw_ptr(layer->children(), i);
2002 CalculateDrawPropertiesInternal<LayerType>(
2003 child, globals, data_for_children, accumulated_surface_state);
2005 if (child->layer_or_descendant_is_drawn()) {
2006 bool layer_or_descendant_is_drawn = true;
2007 layer->set_layer_or_descendant_is_drawn(layer_or_descendant_is_drawn);
2011 // Compute the total drawable_content_rect for this subtree (the rect is in
2012 // target surface space).
2013 gfx::Rect local_drawable_content_rect_of_subtree =
2014 accumulated_surface_state->back().drawable_content_rect;
2015 if (render_to_separate_surface) {
2016 DCHECK(accumulated_surface_state->back().render_target == layer);
2017 accumulated_surface_state->pop_back();
2020 // Compute the layer's drawable content rect (the rect is in target surface
2021 // space).
2022 layer_draw_properties.drawable_content_rect = rect_in_target_space;
2023 if (layer_or_ancestor_clips_descendants) {
2024 layer_draw_properties.drawable_content_rect.Intersect(
2025 clip_rect_in_target_space);
2027 if (layer->DrawsContent()) {
2028 local_drawable_content_rect_of_subtree.Union(
2029 layer_draw_properties.drawable_content_rect);
2032 // Compute the layer's visible content rect (the rect is in content space).
2033 layer_draw_properties.visible_layer_rect = CalculateVisibleLayerRect(
2034 layer, clip_rect_of_target_surface_in_target_space, rect_in_target_space);
2036 // Compute the remaining properties for the render surface, if the layer has
2037 // one.
2038 if (IsRootLayer(layer)) {
2039 // The root layer's surface's content_rect is always the entire viewport.
2040 DCHECK(render_to_separate_surface);
2041 layer->render_surface()->SetContentRect(
2042 ancestor_clip_rect_in_target_space);
2043 } else if (render_to_separate_surface) {
2044 typename LayerType::RenderSurfaceType* render_surface =
2045 layer->render_surface();
2046 gfx::Rect clipped_content_rect = local_drawable_content_rect_of_subtree;
2048 // Don't clip if the layer is reflected as the reflection shouldn't be
2049 // clipped. If the layer is animating, then the surface's transform to
2050 // its target is not known on the main thread, and we should not use it
2051 // to clip.
2052 if (!layer->replica_layer() && TransformToParentIsKnown(layer)) {
2053 // Note, it is correct to use data_from_ancestor.ancestor_clips_subtree
2054 // here, because we are looking at this layer's render_surface, not the
2055 // layer itself.
2056 if (render_surface->is_clipped() && !clipped_content_rect.IsEmpty()) {
2057 gfx::Rect surface_clip_rect = LayerTreeHostCommon::CalculateVisibleRect(
2058 render_surface->clip_rect(),
2059 clipped_content_rect,
2060 render_surface->draw_transform());
2061 clipped_content_rect.Intersect(surface_clip_rect);
2065 // The RenderSurfaceImpl backing texture cannot exceed the maximum supported
2066 // texture size.
2067 clipped_content_rect.set_width(
2068 std::min(clipped_content_rect.width(), globals.max_texture_size));
2069 clipped_content_rect.set_height(
2070 std::min(clipped_content_rect.height(), globals.max_texture_size));
2072 // Layers having a non-default blend mode will blend with the content
2073 // inside its parent's render target. This render target should be
2074 // either root_for_isolated_group, or the root of the layer tree.
2075 // Otherwise, this layer will use an incomplete backdrop, limited to its
2076 // render target and the blending result will be incorrect.
2077 DCHECK(layer->uses_default_blend_mode() || IsRootLayer(layer) ||
2078 !layer->parent()->render_target() ||
2079 IsRootLayer(layer->parent()->render_target()) ||
2080 layer->parent()->render_target()->is_root_for_isolated_group());
2082 render_surface->SetContentRect(clipped_content_rect);
2084 if (clipped_content_rect.IsEmpty()) {
2085 return;
2088 // The owning layer's screen_space_transform has a scale from content to
2089 // layer space which we need to undo and replace with a scale from the
2090 // surface's subtree into layer space.
2091 gfx::Transform screen_space_transform = layer->screen_space_transform();
2092 screen_space_transform.Scale(1.0 / combined_transform_scales.x(),
2093 1.0 / combined_transform_scales.y());
2094 render_surface->SetScreenSpaceTransform(screen_space_transform);
2096 if (layer->replica_layer()) {
2097 gfx::Transform surface_origin_to_replica_origin_transform;
2098 surface_origin_to_replica_origin_transform.Scale(
2099 combined_transform_scales.x(), combined_transform_scales.y());
2100 surface_origin_to_replica_origin_transform.Translate(
2101 layer->replica_layer()->position().x() +
2102 layer->replica_layer()->transform_origin().x(),
2103 layer->replica_layer()->position().y() +
2104 layer->replica_layer()->transform_origin().y());
2105 surface_origin_to_replica_origin_transform.PreconcatTransform(
2106 layer->replica_layer()->transform());
2107 surface_origin_to_replica_origin_transform.Translate(
2108 -layer->replica_layer()->transform_origin().x(),
2109 -layer->replica_layer()->transform_origin().y());
2110 surface_origin_to_replica_origin_transform.Scale(
2111 1.0 / combined_transform_scales.x(),
2112 1.0 / combined_transform_scales.y());
2114 // Compute the replica's "originTransform" that maps from the replica's
2115 // origin space to the target surface origin space.
2116 gfx::Transform replica_origin_transform =
2117 layer->render_surface()->draw_transform() *
2118 surface_origin_to_replica_origin_transform;
2119 render_surface->SetReplicaDrawTransform(replica_origin_transform);
2121 // Compute the replica's "screen_space_transform" that maps from the
2122 // replica's origin space to the screen's origin space.
2123 gfx::Transform replica_screen_space_transform =
2124 layer->render_surface()->screen_space_transform() *
2125 surface_origin_to_replica_origin_transform;
2126 render_surface->SetReplicaScreenSpaceTransform(
2127 replica_screen_space_transform);
2131 SavePaintPropertiesLayer(layer);
2133 UpdateAccumulatedSurfaceState<LayerType>(
2134 layer, local_drawable_content_rect_of_subtree, accumulated_surface_state);
2135 } // NOLINT(readability/fn_size)
2137 template <typename LayerType, typename RenderSurfaceLayerListType>
2138 static void ProcessCalcDrawPropsInputs(
2139 const LayerTreeHostCommon::CalcDrawPropsInputs<LayerType,
2140 RenderSurfaceLayerListType>&
2141 inputs,
2142 SubtreeGlobals<LayerType>* globals,
2143 DataForRecursion<LayerType>* data_for_recursion) {
2144 DCHECK(inputs.root_layer);
2145 DCHECK(IsRootLayer(inputs.root_layer));
2146 DCHECK(inputs.render_surface_layer_list);
2148 gfx::Transform identity_matrix;
2150 // The root layer's render_surface should receive the device viewport as the
2151 // initial clip rect.
2152 gfx::Rect device_viewport_rect(inputs.device_viewport_size);
2154 gfx::Vector2dF device_transform_scale_components =
2155 MathUtil::ComputeTransform2dScaleComponents(inputs.device_transform, 1.f);
2156 // Not handling the rare case of different x and y device scale.
2157 float device_transform_scale =
2158 std::max(device_transform_scale_components.x(),
2159 device_transform_scale_components.y());
2161 gfx::Transform scaled_device_transform = inputs.device_transform;
2162 scaled_device_transform.Scale(inputs.device_scale_factor,
2163 inputs.device_scale_factor);
2165 globals->max_texture_size = inputs.max_texture_size;
2166 globals->device_scale_factor =
2167 inputs.device_scale_factor * device_transform_scale;
2168 globals->page_scale_factor = inputs.page_scale_factor;
2169 globals->page_scale_layer = inputs.page_scale_layer;
2170 globals->elastic_overscroll = inputs.elastic_overscroll;
2171 globals->elastic_overscroll_application_layer =
2172 inputs.elastic_overscroll_application_layer;
2173 globals->can_render_to_separate_surface =
2174 inputs.can_render_to_separate_surface;
2175 globals->can_adjust_raster_scales = inputs.can_adjust_raster_scales;
2176 globals->layers_always_allowed_lcd_text =
2177 inputs.layers_always_allowed_lcd_text;
2179 data_for_recursion->parent_matrix = scaled_device_transform;
2180 data_for_recursion->full_hierarchy_matrix = identity_matrix;
2181 data_for_recursion->scroll_compensation_matrix = identity_matrix;
2182 data_for_recursion->fixed_container = inputs.root_layer;
2183 data_for_recursion->clip_rect_in_target_space = device_viewport_rect;
2184 data_for_recursion->clip_rect_of_target_surface_in_target_space =
2185 device_viewport_rect;
2186 data_for_recursion->maximum_animation_contents_scale = 0.f;
2187 data_for_recursion->ancestor_is_animating_scale = false;
2188 data_for_recursion->ancestor_clips_subtree = true;
2189 data_for_recursion->nearest_occlusion_immune_ancestor_surface = NULL;
2190 data_for_recursion->in_subtree_of_page_scale_layer = false;
2191 data_for_recursion->subtree_can_use_lcd_text = inputs.can_use_lcd_text;
2192 data_for_recursion->subtree_is_visible_from_ancestor = true;
2195 void LayerTreeHostCommon::UpdateRenderSurface(
2196 Layer* layer,
2197 bool can_render_to_separate_surface,
2198 gfx::Transform* transform,
2199 bool* draw_transform_is_axis_aligned) {
2200 bool preserves_2d_axis_alignment =
2201 transform->Preserves2dAxisAlignment() && *draw_transform_is_axis_aligned;
2202 if (IsRootLayer(layer) || (can_render_to_separate_surface &&
2203 SubtreeShouldRenderToSeparateSurface(
2204 layer, preserves_2d_axis_alignment))) {
2205 // We reset the transform here so that any axis-changing transforms
2206 // will now be relative to this RenderSurface.
2207 transform->MakeIdentity();
2208 *draw_transform_is_axis_aligned = true;
2209 if (!layer->render_surface()) {
2210 layer->CreateRenderSurface();
2212 layer->SetHasRenderSurface(true);
2213 return;
2215 layer->SetHasRenderSurface(false);
2216 if (layer->render_surface())
2217 layer->ClearRenderSurface();
2220 void LayerTreeHostCommon::UpdateRenderSurfaces(
2221 Layer* layer,
2222 bool can_render_to_separate_surface,
2223 const gfx::Transform& parent_transform,
2224 bool draw_transform_is_axis_aligned) {
2225 gfx::Transform transform_for_children = layer->transform();
2226 transform_for_children *= parent_transform;
2227 draw_transform_is_axis_aligned &= layer->AnimationsPreserveAxisAlignment();
2228 UpdateRenderSurface(layer, can_render_to_separate_surface,
2229 &transform_for_children, &draw_transform_is_axis_aligned);
2231 for (size_t i = 0; i < layer->children().size(); ++i) {
2232 UpdateRenderSurfaces(layer->children()[i].get(),
2233 can_render_to_separate_surface, transform_for_children,
2234 draw_transform_is_axis_aligned);
2238 static bool ApproximatelyEqual(const gfx::Rect& r1, const gfx::Rect& r2) {
2239 // TODO(vollick): This tolerance should be lower: crbug.com/471786
2240 static const int tolerance = 3;
2242 if (r1.IsEmpty())
2243 return std::min(r2.width(), r2.height()) < tolerance;
2245 if (r2.IsEmpty())
2246 return std::min(r1.width(), r1.height()) < tolerance;
2248 return std::abs(r1.x() - r2.x()) <= tolerance &&
2249 std::abs(r1.y() - r2.y()) <= tolerance &&
2250 std::abs(r1.right() - r2.right()) <= tolerance &&
2251 std::abs(r1.bottom() - r2.bottom()) <= tolerance;
2254 static bool ApproximatelyEqual(const gfx::Transform& a,
2255 const gfx::Transform& b) {
2256 static const float component_tolerance = 0.1f;
2258 // We may have a larger discrepancy in the scroll components due to snapping
2259 // (floating point error might round the other way).
2260 static const float translation_tolerance = 1.f;
2262 for (int row = 0; row < 4; row++) {
2263 for (int col = 0; col < 4; col++) {
2264 const float delta =
2265 std::abs(a.matrix().get(row, col) - b.matrix().get(row, col));
2266 const float tolerance =
2267 col == 3 && row < 3 ? translation_tolerance : component_tolerance;
2268 if (delta > tolerance)
2269 return false;
2273 return true;
2276 void VerifyPropertyTreeValuesForSurface(RenderSurfaceImpl* render_surface,
2277 PropertyTrees* property_trees) {
2278 const bool render_surface_draw_transforms_match =
2279 ApproximatelyEqual(render_surface->draw_transform(),
2280 DrawTransformOfRenderSurfaceFromPropertyTrees(
2281 render_surface, property_trees->transform_tree));
2282 CHECK(render_surface_draw_transforms_match)
2283 << "expected: " << render_surface->draw_transform().ToString()
2284 << " actual: "
2285 << DrawTransformOfRenderSurfaceFromPropertyTrees(
2286 render_surface, property_trees->transform_tree)
2287 .ToString();
2289 const bool render_surface_screen_space_transform_match =
2290 ApproximatelyEqual(render_surface->screen_space_transform(),
2291 ScreenSpaceTransformOfRenderSurfaceFromPropertyTrees(
2292 render_surface, property_trees->transform_tree));
2293 CHECK(render_surface_screen_space_transform_match)
2294 << "expected: " << render_surface->screen_space_transform().ToString()
2295 << " actual: "
2296 << ScreenSpaceTransformOfRenderSurfaceFromPropertyTrees(
2297 render_surface, property_trees->transform_tree)
2298 .ToString();
2300 CHECK_EQ(render_surface->is_clipped(),
2301 RenderSurfaceIsClippedFromPropertyTrees(render_surface,
2302 property_trees->clip_tree));
2304 const bool render_surface_clip_rects_match =
2305 ApproximatelyEqual(render_surface->clip_rect(),
2306 ClipRectOfRenderSurfaceFromPropertyTrees(
2307 render_surface, property_trees->clip_tree));
2308 CHECK(render_surface_clip_rects_match)
2309 << "expected: " << render_surface->clip_rect().ToString() << " actual: "
2310 << ClipRectOfRenderSurfaceFromPropertyTrees(render_surface,
2311 property_trees->clip_tree)
2312 .ToString();
2314 CHECK_EQ(render_surface->draw_opacity(),
2315 DrawOpacityOfRenderSurfaceFromPropertyTrees(
2316 render_surface, property_trees->effect_tree));
2319 void VerifyPropertyTreeValuesForLayer(LayerImpl* current_layer,
2320 PropertyTrees* property_trees,
2321 bool layers_always_allowed_lcd_text,
2322 bool can_use_lcd_text) {
2323 const bool visible_rects_match =
2324 ApproximatelyEqual(current_layer->visible_layer_rect(),
2325 current_layer->visible_rect_from_property_trees());
2326 CHECK(visible_rects_match)
2327 << "expected: " << current_layer->visible_layer_rect().ToString()
2328 << " actual: "
2329 << current_layer->visible_rect_from_property_trees().ToString();
2331 const bool draw_transforms_match =
2332 ApproximatelyEqual(current_layer->draw_transform(),
2333 DrawTransformFromPropertyTrees(
2334 current_layer, property_trees->transform_tree));
2335 CHECK(draw_transforms_match)
2336 << "expected: " << current_layer->draw_transform().ToString()
2337 << " actual: "
2338 << DrawTransformFromPropertyTrees(
2339 current_layer, property_trees->transform_tree).ToString();
2341 const bool draw_opacities_match =
2342 current_layer->draw_opacity() ==
2343 DrawOpacityFromPropertyTrees(current_layer, property_trees->effect_tree);
2344 CHECK(draw_opacities_match)
2345 << "expected: " << current_layer->draw_opacity()
2346 << " actual: " << DrawOpacityFromPropertyTrees(
2347 current_layer, property_trees->effect_tree);
2349 const bool can_use_lcd_text_match =
2350 CanUseLcdTextFromPropertyTrees(
2351 current_layer, layers_always_allowed_lcd_text, can_use_lcd_text,
2352 property_trees) == current_layer->can_use_lcd_text();
2353 CHECK(can_use_lcd_text_match);
2355 CHECK_EQ(current_layer->screen_space_transform_is_animating(),
2356 ScreenSpaceTransformIsAnimatingFromPropertyTrees(
2357 current_layer, property_trees->transform_tree));
2359 const bool drawable_content_rects_match =
2360 ApproximatelyEqual(current_layer->drawable_content_rect(),
2361 DrawableContentRectFromPropertyTrees(
2362 current_layer, property_trees->transform_tree));
2363 CHECK(drawable_content_rects_match)
2364 << "expected: " << current_layer->drawable_content_rect().ToString()
2365 << " actual: "
2366 << DrawableContentRectFromPropertyTrees(current_layer,
2367 property_trees->transform_tree)
2368 .ToString();
2370 const bool clip_rects_match = ApproximatelyEqual(
2371 current_layer->clip_rect(),
2372 ClipRectFromPropertyTrees(current_layer, property_trees->transform_tree));
2373 CHECK(clip_rects_match) << "expected: "
2374 << current_layer->clip_rect().ToString()
2375 << " actual: "
2376 << ClipRectFromPropertyTrees(
2377 current_layer, property_trees->transform_tree)
2378 .ToString();
2381 void VerifyPropertyTreeValues(
2382 LayerTreeHostCommon::CalcDrawPropsMainInputs* inputs) {
2385 void VerifyPropertyTreeValues(
2386 LayerTreeHostCommon::CalcDrawPropsImplInputs* inputs) {
2387 LayerIterator it, end;
2388 for (it = LayerIterator::Begin(inputs->render_surface_layer_list),
2389 end = LayerIterator::End(inputs->render_surface_layer_list);
2390 it != end; ++it) {
2391 LayerImpl* current_layer = *it;
2392 if (it.represents_target_render_surface())
2393 VerifyPropertyTreeValuesForSurface(current_layer->render_surface(),
2394 inputs->property_trees);
2395 if (!it.represents_itself() || !current_layer->DrawsContent())
2396 continue;
2397 VerifyPropertyTreeValuesForLayer(current_layer, inputs->property_trees,
2398 inputs->layers_always_allowed_lcd_text,
2399 inputs->can_use_lcd_text);
2403 enum PropertyTreeOption {
2404 BUILD_PROPERTY_TREES_IF_NEEDED,
2405 DONT_BUILD_PROPERTY_TREES
2408 template <typename LayerType>
2409 void CalculateRenderTargetInternal(LayerType* layer,
2410 bool subtree_visible_from_ancestor,
2411 bool can_render_to_separate_surface) {
2412 const bool layer_is_visible =
2413 subtree_visible_from_ancestor && !layer->hide_layer_and_subtree();
2414 const bool layer_is_drawn = layer_is_visible || layer->HasCopyRequest();
2416 // The root layer cannot be skipped.
2417 if (!IsRootLayer(layer) && SubtreeShouldBeSkipped(layer, layer_is_drawn)) {
2418 layer->draw_properties().render_target = nullptr;
2419 return;
2422 bool render_to_separate_surface =
2423 IsRootLayer(layer) ||
2424 (can_render_to_separate_surface && layer->render_surface());
2426 if (render_to_separate_surface) {
2427 DCHECK(layer->render_surface());
2428 layer->draw_properties().render_target = layer;
2430 if (layer->mask_layer())
2431 layer->mask_layer()->draw_properties().render_target = layer;
2433 if (layer->replica_layer() && layer->replica_layer()->mask_layer())
2434 layer->replica_layer()->mask_layer()->draw_properties().render_target =
2435 layer;
2437 } else {
2438 DCHECK(layer->parent());
2439 layer->draw_properties().render_target = layer->parent()->render_target();
2442 for (size_t i = 0; i < layer->children().size(); ++i) {
2443 CalculateRenderTargetInternal<LayerType>(
2444 LayerTreeHostCommon::get_layer_as_raw_ptr(layer->children(), i),
2445 layer_is_drawn, can_render_to_separate_surface);
2449 void CalculateRenderSurfaceLayerListInternal(
2450 LayerImpl* layer,
2451 LayerImplList* render_surface_layer_list,
2452 LayerImplList* descendants,
2453 bool subtree_visible_from_ancestor,
2454 const bool can_render_to_separate_surface,
2455 const int current_render_surface_layer_list_id) {
2456 // This calculates top level Render Surface Layer List, and Layer List for all
2457 // Render Surfaces.
2459 // |layer| is current layer.
2461 // |render_surface_layer_list| is the top level RenderSurfaceLayerList.
2463 // |descendants| is used to determine what's in current layer's render
2464 // surface's layer list.
2466 // |subtree_visible_from_ancestor| is set during recursion to affect current
2467 // layer's subtree.
2469 // |can_render_to_separate_surface| and |current_render_surface_layer_list_id|
2470 // are settings that should stay the same during recursion.
2472 // Layers that are marked as hidden will hide themselves and their subtree.
2473 // Exception: Layers with copy requests, whether hidden or not, must be drawn
2474 // anyway. In this case, we will inform their subtree they are visible to get
2475 // the right results.
2476 const bool layer_is_visible =
2477 subtree_visible_from_ancestor && !layer->hide_layer_and_subtree();
2478 const bool layer_is_drawn = layer_is_visible || layer->HasCopyRequest();
2480 // The root layer cannot be skipped.
2481 if (!IsRootLayer(layer) && SubtreeShouldBeSkipped(layer, layer_is_drawn)) {
2482 if (layer->render_surface())
2483 layer->ClearRenderSurfaceLayerList();
2484 layer->draw_properties().render_target = nullptr;
2485 return;
2488 bool render_to_separate_surface =
2489 IsRootLayer(layer) ||
2490 (can_render_to_separate_surface && layer->render_surface());
2492 if (render_to_separate_surface) {
2493 DCHECK(layer->render_surface());
2494 if (!layer->double_sided() &&
2495 IsSurfaceBackFaceVisible(layer, layer->draw_transform())) {
2496 layer->ClearRenderSurfaceLayerList();
2497 layer->draw_properties().render_target = nullptr;
2498 return;
2501 layer->ClearRenderSurfaceLayerList();
2503 render_surface_layer_list->push_back(layer);
2505 descendants = &(layer->render_surface()->layer_list());
2508 size_t descendants_size = descendants->size();
2510 if (!LayerShouldBeSkipped(layer, layer_is_drawn)) {
2511 MarkLayerWithRenderSurfaceLayerListId(layer,
2512 current_render_surface_layer_list_id);
2513 descendants->push_back(layer);
2516 for (auto& child_layer : layer->children()) {
2517 CalculateRenderSurfaceLayerListInternal(
2518 child_layer, render_surface_layer_list, descendants, layer_is_drawn,
2519 can_render_to_separate_surface, current_render_surface_layer_list_id);
2521 // If the child is its own render target, then it has a render surface.
2522 if (child_layer->render_target() == child_layer &&
2523 !child_layer->render_surface()->layer_list().empty() &&
2524 !child_layer->render_surface()->content_rect().IsEmpty()) {
2525 // This child will contribute its render surface, which means
2526 // we need to mark just the mask layer (and replica mask layer)
2527 // with the id.
2528 MarkMasksWithRenderSurfaceLayerListId(
2529 child_layer, current_render_surface_layer_list_id);
2530 descendants->push_back(child_layer);
2533 if (child_layer->layer_or_descendant_is_drawn()) {
2534 bool layer_or_descendant_is_drawn = true;
2535 layer->set_layer_or_descendant_is_drawn(layer_or_descendant_is_drawn);
2539 if (render_to_separate_surface && !IsRootLayer(layer) &&
2540 layer->render_surface()->layer_list().empty()) {
2541 RemoveSurfaceForEarlyExit(layer, render_surface_layer_list);
2542 return;
2545 if (render_to_separate_surface && !IsRootLayer(layer) &&
2546 layer->render_surface()->content_rect().IsEmpty()) {
2547 RemoveSurfaceForEarlyExit(layer, render_surface_layer_list);
2548 return;
2551 // If neither this layer nor any of its children were added, early out.
2552 if (descendants_size == descendants->size()) {
2553 DCHECK(!render_to_separate_surface || IsRootLayer(layer));
2554 return;
2557 if (layer->HasContributingDelegatedRenderPasses()) {
2558 layer->render_target()
2559 ->render_surface()
2560 ->AddContributingDelegatedRenderPassLayer(layer);
2564 template <typename LayerType, typename RenderSurfaceLayerListType>
2565 void CalculateRenderTarget(LayerTreeHostCommon::CalcDrawPropsInputs<
2566 LayerType,
2567 RenderSurfaceLayerListType>* inputs) {
2568 // Main thread CalcDrawProps and Impl thread in general needs to calculate
2569 // render target.
2570 // TODO(weiliangc): Once main thread CDP is turned off, make this impl thread
2571 // only.
2572 CalculateRenderTargetInternal<LayerType>(
2573 inputs->root_layer, true, inputs->can_render_to_separate_surface);
2576 void CalculateRenderSurfaceLayerList(
2577 LayerTreeHostCommon::CalcDrawPropsMainInputs* inputs) {}
2579 void CalculateRenderSurfaceLayerList(
2580 LayerTreeHostCommon::CalcDrawPropsImplInputs* inputs) {
2581 const bool subtree_visible_from_ancestor = true;
2582 CalculateRenderSurfaceLayerListInternal(
2583 inputs->root_layer, inputs->render_surface_layer_list, nullptr,
2584 subtree_visible_from_ancestor, inputs->can_render_to_separate_surface,
2585 inputs->current_render_surface_layer_list_id);
2588 template <typename LayerType, typename RenderSurfaceLayerListType>
2589 void CalculateDrawPropertiesAndVerify(LayerTreeHostCommon::CalcDrawPropsInputs<
2590 LayerType,
2591 RenderSurfaceLayerListType>* inputs,
2592 PropertyTreeOption property_tree_option) {
2593 SubtreeGlobals<LayerType> globals;
2594 DataForRecursion<LayerType> data_for_recursion;
2595 inputs->render_surface_layer_list->clear();
2597 ProcessCalcDrawPropsInputs(*inputs, &globals, &data_for_recursion);
2598 UpdateMetaInformationSequenceNumber(inputs->root_layer);
2599 PreCalculateMetaInformationRecursiveData recursive_data;
2600 PreCalculateMetaInformationInternal(inputs->root_layer, &recursive_data);
2602 const bool should_measure_property_tree_performance =
2603 inputs->verify_property_trees &&
2604 (property_tree_option == BUILD_PROPERTY_TREES_IF_NEEDED);
2606 if (inputs->verify_property_trees) {
2607 typename LayerType::LayerListType update_layer_list;
2609 // For testing purposes, sometimes property trees need to be built on the
2610 // compositor thread, so this can't just switch on Layer vs LayerImpl,
2611 // even though in practice only the main thread builds property trees.
2612 switch (property_tree_option) {
2613 case BUILD_PROPERTY_TREES_IF_NEEDED: {
2614 // The translation from layer to property trees is an intermediate
2615 // state. We will eventually get these data passed directly to the
2616 // compositor.
2617 if (should_measure_property_tree_performance) {
2618 TRACE_EVENT_BEGIN0(
2619 TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2620 "LayerTreeHostCommon::ComputeVisibleRectsWithPropertyTrees");
2623 BuildPropertyTreesAndComputeVisibleRects(
2624 inputs->root_layer, inputs->page_scale_layer,
2625 inputs->inner_viewport_scroll_layer,
2626 inputs->outer_viewport_scroll_layer, inputs->page_scale_factor,
2627 inputs->device_scale_factor,
2628 gfx::Rect(inputs->device_viewport_size), inputs->device_transform,
2629 inputs->property_trees, &update_layer_list);
2631 if (should_measure_property_tree_performance) {
2632 TRACE_EVENT_END0(
2633 TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2634 "LayerTreeHostCommon::ComputeVisibleRectsWithPropertyTrees");
2637 break;
2639 case DONT_BUILD_PROPERTY_TREES: {
2640 TRACE_EVENT0(
2641 TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2642 "LayerTreeHostCommon::ComputeJustVisibleRectsWithPropertyTrees");
2643 ComputeVisibleRectsUsingPropertyTrees(
2644 inputs->root_layer, inputs->property_trees, &update_layer_list);
2645 break;
2650 if (should_measure_property_tree_performance) {
2651 TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2652 "LayerTreeHostCommon::CalculateDrawProperties");
2655 std::vector<AccumulatedSurfaceState<LayerType>> accumulated_surface_state;
2656 CalculateRenderTarget<LayerType, RenderSurfaceLayerListType>(inputs);
2657 CalculateDrawPropertiesInternal<LayerType>(inputs->root_layer, globals,
2658 data_for_recursion,
2659 &accumulated_surface_state);
2660 CalculateRenderSurfaceLayerList(inputs);
2662 if (should_measure_property_tree_performance) {
2663 TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2664 "LayerTreeHostCommon::CalculateDrawProperties");
2667 if (inputs->verify_property_trees)
2668 VerifyPropertyTreeValues(inputs);
2670 // A root layer render_surface should always exist after
2671 // CalculateDrawProperties.
2672 DCHECK(inputs->root_layer->render_surface());
2675 void LayerTreeHostCommon::CalculateDrawProperties(
2676 CalcDrawPropsMainInputs* inputs) {
2677 UpdateRenderSurfaces(inputs->root_layer,
2678 inputs->can_render_to_separate_surface, gfx::Transform(),
2679 false);
2680 CalculateDrawPropertiesAndVerify(inputs, BUILD_PROPERTY_TREES_IF_NEEDED);
2683 void LayerTreeHostCommon::CalculateDrawProperties(
2684 CalcDrawPropsImplInputs* inputs) {
2685 CalculateDrawPropertiesAndVerify(inputs, DONT_BUILD_PROPERTY_TREES);
2688 void LayerTreeHostCommon::CalculateDrawProperties(
2689 CalcDrawPropsImplInputsForTesting* inputs) {
2690 CalculateDrawPropertiesAndVerify(inputs, BUILD_PROPERTY_TREES_IF_NEEDED);
2693 PropertyTrees* GetPropertyTrees(Layer* layer) {
2694 return layer->layer_tree_host()->property_trees();
2697 PropertyTrees* GetPropertyTrees(LayerImpl* layer) {
2698 return layer->layer_tree_impl()->property_trees();
2701 } // namespace cc