cc: use property trees instead of CDP on the main thread
[chromium-blink-merge.git] / cc / trees / layer_tree_host_common.cc
blob49bc13d95da3cfd13dbc086f9af9d35e03ac07fd
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(current_target->num_unclipped_descendants() == 0 ||
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 CalculateVisibleContentRect(
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->content_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,
407 gfx::Rect(layer->content_bounds()),
408 layer_rect_in_target_space,
409 layer->draw_transform());
412 static inline bool TransformToParentIsKnown(LayerImpl* layer) { return true; }
414 static inline bool TransformToParentIsKnown(Layer* layer) {
415 return !layer->TransformIsAnimating();
418 static inline bool TransformToScreenIsKnown(LayerImpl* layer) { return true; }
420 static inline bool TransformToScreenIsKnown(Layer* layer) {
421 return !layer->screen_space_transform_is_animating();
424 template <typename LayerType>
425 static bool LayerShouldBeSkipped(LayerType* layer, bool layer_is_drawn) {
426 // Layers can be skipped if any of these conditions are met.
427 // - is not drawn due to it or one of its ancestors being hidden (or having
428 // no copy requests).
429 // - does not draw content.
430 // - is transparent.
431 // - has empty bounds
432 // - the layer is not double-sided, but its back face is visible.
434 // Some additional conditions need to be computed at a later point after the
435 // recursion is finished.
436 // - the intersection of render_surface content and layer clip_rect is empty
437 // - the visible_content_rect is empty
439 // Note, if the layer should not have been drawn due to being fully
440 // transparent, we would have skipped the entire subtree and never made it
441 // into this function, so it is safe to omit this check here.
443 if (!layer_is_drawn)
444 return true;
446 if (!layer->DrawsContent() || layer->bounds().IsEmpty())
447 return true;
449 LayerType* backface_test_layer = layer;
450 if (layer->use_parent_backface_visibility()) {
451 DCHECK(layer->parent());
452 DCHECK(!layer->parent()->use_parent_backface_visibility());
453 backface_test_layer = layer->parent();
456 // The layer should not be drawn if (1) it is not double-sided and (2) the
457 // back of the layer is known to be facing the screen.
458 if (!backface_test_layer->double_sided() &&
459 TransformToScreenIsKnown(backface_test_layer) &&
460 IsLayerBackFaceVisible(backface_test_layer))
461 return true;
463 return false;
466 template <typename LayerType>
467 static bool HasInvertibleOrAnimatedTransform(LayerType* layer) {
468 return layer->transform_is_invertible() || layer->TransformIsAnimating();
471 static inline bool SubtreeShouldBeSkipped(LayerImpl* layer,
472 bool layer_is_drawn) {
473 // If the layer transform is not invertible, it should not be drawn.
474 // TODO(ajuma): Correctly process subtrees with singular transform for the
475 // case where we may animate to a non-singular transform and wish to
476 // pre-raster.
477 if (!HasInvertibleOrAnimatedTransform(layer))
478 return true;
480 // When we need to do a readback/copy of a layer's output, we can not skip
481 // it or any of its ancestors.
482 if (layer->draw_properties().layer_or_descendant_has_copy_request)
483 return false;
485 // We cannot skip the the subtree if a descendant has a wheel or touch handler
486 // or the hit testing code will break (it requires fresh transforms, etc).
487 if (layer->draw_properties().layer_or_descendant_has_input_handler)
488 return false;
490 // If the layer is not drawn, then skip it and its subtree.
491 if (!layer_is_drawn)
492 return true;
494 // If layer is on the pending tree and opacity is being animated then
495 // this subtree can't be skipped as we need to create, prioritize and
496 // include tiles for this layer when deciding if tree can be activated.
497 if (layer->layer_tree_impl()->IsPendingTree() && layer->OpacityIsAnimating())
498 return false;
500 // The opacity of a layer always applies to its children (either implicitly
501 // via a render surface or explicitly if the parent preserves 3D), so the
502 // entire subtree can be skipped if this layer is fully transparent.
503 return !layer->opacity();
506 static inline bool SubtreeShouldBeSkipped(Layer* layer, bool layer_is_drawn) {
507 // If the layer transform is not invertible, it should not be drawn.
508 if (!layer->transform_is_invertible() && !layer->TransformIsAnimating())
509 return true;
511 // When we need to do a readback/copy of a layer's output, we can not skip
512 // it or any of its ancestors.
513 if (layer->draw_properties().layer_or_descendant_has_copy_request)
514 return false;
516 // We cannot skip the the subtree if a descendant has a wheel or touch handler
517 // or the hit testing code will break (it requires fresh transforms, etc).
518 if (layer->draw_properties().layer_or_descendant_has_input_handler)
519 return false;
521 // If the layer is not drawn, then skip it and its subtree.
522 if (!layer_is_drawn)
523 return true;
525 // If the opacity is being animated then the opacity on the main thread is
526 // unreliable (since the impl thread may be using a different opacity), so it
527 // should not be trusted.
528 // In particular, it should not cause the subtree to be skipped.
529 // Similarly, for layers that might animate opacity using an impl-only
530 // animation, their subtree should also not be skipped.
531 return !layer->opacity() && !layer->OpacityIsAnimating() &&
532 !layer->OpacityCanAnimateOnImplThread();
535 static inline void SavePaintPropertiesLayer(LayerImpl* layer) {}
537 static inline void SavePaintPropertiesLayer(Layer* layer) {
538 layer->SavePaintProperties();
540 if (layer->mask_layer())
541 layer->mask_layer()->SavePaintProperties();
542 if (layer->replica_layer() && layer->replica_layer()->mask_layer())
543 layer->replica_layer()->mask_layer()->SavePaintProperties();
546 static bool SubtreeShouldRenderToSeparateSurface(
547 Layer* layer,
548 bool axis_aligned_with_respect_to_parent) {
550 // A layer and its descendants should render onto a new RenderSurfaceImpl if
551 // any of these rules hold:
554 // The root layer owns a render surface, but it never acts as a contributing
555 // surface to another render target. Compositor features that are applied via
556 // a contributing surface can not be applied to the root layer. In order to
557 // use these effects, another child of the root would need to be introduced
558 // in order to act as a contributing surface to the root layer's surface.
559 bool is_root = IsRootLayer(layer);
561 // If the layer uses a mask.
562 if (layer->mask_layer()) {
563 DCHECK(!is_root);
564 return true;
567 // If the layer has a reflection.
568 if (layer->replica_layer()) {
569 DCHECK(!is_root);
570 return true;
573 // If the layer uses a CSS filter.
574 if (!layer->filters().IsEmpty() || !layer->background_filters().IsEmpty()) {
575 DCHECK(!is_root);
576 return true;
579 // If the layer will use a CSS filter. In this case, the animation
580 // will start and add a filter to this layer, so it needs a surface.
581 if (layer->FilterIsAnimating()) {
582 DCHECK(!is_root);
583 return true;
586 int num_descendants_that_draw_content =
587 layer->NumDescendantsThatDrawContent();
589 // If the layer flattens its subtree, but it is treated as a 3D object by its
590 // parent (i.e. parent participates in a 3D rendering context).
591 if (LayerIsInExisting3DRenderingContext(layer) &&
592 layer->should_flatten_transform() &&
593 num_descendants_that_draw_content > 0) {
594 TRACE_EVENT_INSTANT0(
595 "cc",
596 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface flattening",
597 TRACE_EVENT_SCOPE_THREAD);
598 DCHECK(!is_root);
599 return true;
602 // If the layer has blending.
603 // TODO(rosca): this is temporary, until blending is implemented for other
604 // types of quads than RenderPassDrawQuad. Layers having descendants that draw
605 // content will still create a separate rendering surface.
606 if (!layer->uses_default_blend_mode()) {
607 TRACE_EVENT_INSTANT0(
608 "cc",
609 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface blending",
610 TRACE_EVENT_SCOPE_THREAD);
611 DCHECK(!is_root);
612 return true;
615 // If the layer clips its descendants but it is not axis-aligned with respect
616 // to its parent.
617 bool layer_clips_external_content =
618 LayerClipsSubtree(layer) || layer->HasDelegatedContent();
619 if (layer_clips_external_content && !axis_aligned_with_respect_to_parent &&
620 num_descendants_that_draw_content > 0) {
621 TRACE_EVENT_INSTANT0(
622 "cc",
623 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface clipping",
624 TRACE_EVENT_SCOPE_THREAD);
625 DCHECK(!is_root);
626 return true;
629 // If the layer has some translucency and does not have a preserves-3d
630 // transform style. This condition only needs a render surface if two or more
631 // layers in the subtree overlap. But checking layer overlaps is unnecessarily
632 // costly so instead we conservatively create a surface whenever at least two
633 // layers draw content for this subtree.
634 bool at_least_two_layers_in_subtree_draw_content =
635 num_descendants_that_draw_content > 0 &&
636 (layer->DrawsContent() || num_descendants_that_draw_content > 1);
638 if (layer->opacity() != 1.f && layer->should_flatten_transform() &&
639 at_least_two_layers_in_subtree_draw_content) {
640 TRACE_EVENT_INSTANT0(
641 "cc",
642 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface opacity",
643 TRACE_EVENT_SCOPE_THREAD);
644 DCHECK(!is_root);
645 return true;
648 // The root layer should always have a render_surface.
649 if (is_root)
650 return true;
653 // These are allowed on the root surface, as they don't require the surface to
654 // be used as a contributing surface in order to apply correctly.
657 // If the layer has isolation.
658 // TODO(rosca): to be optimized - create separate rendering surface only when
659 // the blending descendants might have access to the content behind this layer
660 // (layer has transparent background or descendants overflow).
661 // https://code.google.com/p/chromium/issues/detail?id=301738
662 if (layer->is_root_for_isolated_group()) {
663 TRACE_EVENT_INSTANT0(
664 "cc",
665 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface isolation",
666 TRACE_EVENT_SCOPE_THREAD);
667 return true;
670 // If we force it.
671 if (layer->force_render_surface())
672 return true;
674 // If we'll make a copy of the layer's contents.
675 if (layer->HasCopyRequest())
676 return true;
678 return false;
681 // This function returns a translation matrix that can be applied on a vector
682 // that's in the layer's target surface coordinate, while the position offset is
683 // specified in some ancestor layer's coordinate.
684 template <typename LayerType>
685 gfx::Transform ComputeSizeDeltaCompensation(
686 LayerType* layer,
687 LayerType* container,
688 const gfx::Vector2dF& position_offset) {
689 gfx::Transform result_transform;
691 // To apply a translate in the container's layer space,
692 // the following steps need to be done:
693 // Step 1a. transform from target surface space to the container's target
694 // surface space
695 // Step 1b. transform from container's target surface space to the
696 // container's layer space
697 // Step 2. apply the compensation
698 // Step 3. transform back to target surface space
700 gfx::Transform target_surface_space_to_container_layer_space;
701 // Calculate step 1a
702 LayerType* container_target_surface = container->render_target();
703 for (LayerType* current_target_surface = NextTargetSurface(layer);
704 current_target_surface &&
705 current_target_surface != container_target_surface;
706 current_target_surface = NextTargetSurface(current_target_surface)) {
707 // Note: Concat is used here to convert the result coordinate space from
708 // current render surface to the next render surface.
709 target_surface_space_to_container_layer_space.ConcatTransform(
710 current_target_surface->render_surface()->draw_transform());
712 // Calculate step 1b
713 gfx::Transform container_layer_space_to_container_target_surface_space =
714 container->draw_transform();
715 container_layer_space_to_container_target_surface_space.Scale(
716 container->contents_scale_x(), container->contents_scale_y());
718 gfx::Transform container_target_surface_space_to_container_layer_space;
719 if (container_layer_space_to_container_target_surface_space.GetInverse(
720 &container_target_surface_space_to_container_layer_space)) {
721 // Note: Again, Concat is used to conver the result coordinate space from
722 // the container render surface to the container layer.
723 target_surface_space_to_container_layer_space.ConcatTransform(
724 container_target_surface_space_to_container_layer_space);
727 // Apply step 3
728 gfx::Transform container_layer_space_to_target_surface_space;
729 if (target_surface_space_to_container_layer_space.GetInverse(
730 &container_layer_space_to_target_surface_space)) {
731 result_transform.PreconcatTransform(
732 container_layer_space_to_target_surface_space);
733 } else {
734 // TODO(shawnsingh): A non-invertible matrix could still make meaningful
735 // projection. For example ScaleZ(0) is non-invertible but the layer is
736 // still visible.
737 return gfx::Transform();
740 // Apply step 2
741 result_transform.Translate(position_offset.x(), position_offset.y());
743 // Apply step 1
744 result_transform.PreconcatTransform(
745 target_surface_space_to_container_layer_space);
747 return result_transform;
750 template <typename LayerType>
751 void ApplyPositionAdjustment(
752 LayerType* layer,
753 LayerType* container,
754 const gfx::Transform& scroll_compensation,
755 gfx::Transform* combined_transform) {
756 if (!layer->position_constraint().is_fixed_position())
757 return;
759 // Special case: this layer is a composited fixed-position layer; we need to
760 // explicitly compensate for all ancestors' nonzero scroll_deltas to keep
761 // this layer fixed correctly.
762 // Note carefully: this is Concat, not Preconcat
763 // (current_scroll_compensation * combined_transform).
764 combined_transform->ConcatTransform(scroll_compensation);
766 // For right-edge or bottom-edge anchored fixed position layers,
767 // the layer should relocate itself if the container changes its size.
768 bool fixed_to_right_edge =
769 layer->position_constraint().is_fixed_to_right_edge();
770 bool fixed_to_bottom_edge =
771 layer->position_constraint().is_fixed_to_bottom_edge();
772 gfx::Vector2dF position_offset = container->FixedContainerSizeDelta();
773 position_offset.set_x(fixed_to_right_edge ? position_offset.x() : 0);
774 position_offset.set_y(fixed_to_bottom_edge ? position_offset.y() : 0);
775 if (position_offset.IsZero())
776 return;
778 // Note: Again, this is Concat. The compensation matrix will be applied on
779 // the vector in target surface space.
780 combined_transform->ConcatTransform(
781 ComputeSizeDeltaCompensation(layer, container, position_offset));
784 template <typename LayerType>
785 gfx::Transform ComputeScrollCompensationForThisLayer(
786 LayerType* scrolling_layer,
787 const gfx::Transform& parent_matrix,
788 const gfx::Vector2dF& scroll_delta) {
789 // For every layer that has non-zero scroll_delta, we have to compute a
790 // transform that can undo the scroll_delta translation. In particular, we
791 // want this matrix to premultiply a fixed-position layer's parent_matrix, so
792 // we design this transform in three steps as follows. The steps described
793 // here apply from right-to-left, so Step 1 would be the right-most matrix:
795 // Step 1. transform from target surface space to the exact space where
796 // scroll_delta is actually applied.
797 // -- this is inverse of parent_matrix
798 // Step 2. undo the scroll_delta
799 // -- this is just a translation by scroll_delta.
800 // Step 3. transform back to target surface space.
801 // -- this transform is the parent_matrix
803 // These steps create a matrix that both start and end in target surface
804 // space. So this matrix can pre-multiply any fixed-position layer's
805 // draw_transform to undo the scroll_deltas -- as long as that fixed position
806 // layer is fixed onto the same render_target as this scrolling_layer.
809 gfx::Transform scroll_compensation_for_this_layer = parent_matrix; // Step 3
810 scroll_compensation_for_this_layer.Translate(
811 scroll_delta.x(),
812 scroll_delta.y()); // Step 2
814 gfx::Transform inverse_parent_matrix(gfx::Transform::kSkipInitialization);
815 if (!parent_matrix.GetInverse(&inverse_parent_matrix)) {
816 // TODO(shawnsingh): Either we need to handle uninvertible transforms
817 // here, or DCHECK that the transform is invertible.
819 scroll_compensation_for_this_layer.PreconcatTransform(
820 inverse_parent_matrix); // Step 1
821 return scroll_compensation_for_this_layer;
824 template <typename LayerType>
825 gfx::Transform ComputeScrollCompensationMatrixForChildren(
826 LayerType* layer,
827 const gfx::Transform& parent_matrix,
828 const gfx::Transform& current_scroll_compensation_matrix,
829 const gfx::Vector2dF& scroll_delta) {
830 // "Total scroll compensation" is the transform needed to cancel out all
831 // scroll_delta translations that occurred since the nearest container layer,
832 // even if there are render_surfaces in-between.
834 // There are some edge cases to be aware of, that are not explicit in the
835 // code:
836 // - A layer that is both a fixed-position and container should not be its
837 // own container, instead, that means it is fixed to an ancestor, and is a
838 // container for any fixed-position descendants.
839 // - A layer that is a fixed-position container and has a render_surface
840 // should behave the same as a container without a render_surface, the
841 // render_surface is irrelevant in that case.
842 // - A layer that does not have an explicit container is simply fixed to the
843 // viewport. (i.e. the root render_surface.)
844 // - If the fixed-position layer has its own render_surface, then the
845 // render_surface is the one who gets fixed.
847 // This function needs to be called AFTER layers create their own
848 // render_surfaces.
851 // Scroll compensation restarts from identity under two possible conditions:
852 // - the current layer is a container for fixed-position descendants
853 // - the current layer is fixed-position itself, so any fixed-position
854 // descendants are positioned with respect to this layer. Thus, any
855 // fixed position descendants only need to compensate for scrollDeltas
856 // that occur below this layer.
857 bool current_layer_resets_scroll_compensation_for_descendants =
858 layer->IsContainerForFixedPositionLayers() ||
859 layer->position_constraint().is_fixed_position();
861 // Avoid the overheads (including stack allocation and matrix
862 // initialization/copy) if we know that the scroll compensation doesn't need
863 // to be reset or adjusted.
864 if (!current_layer_resets_scroll_compensation_for_descendants &&
865 scroll_delta.IsZero() && !layer->render_surface())
866 return current_scroll_compensation_matrix;
868 // Start as identity matrix.
869 gfx::Transform next_scroll_compensation_matrix;
871 // If this layer does not reset scroll compensation, then it inherits the
872 // existing scroll compensations.
873 if (!current_layer_resets_scroll_compensation_for_descendants)
874 next_scroll_compensation_matrix = current_scroll_compensation_matrix;
876 // If the current layer has a non-zero scroll_delta, then we should compute
877 // its local scroll compensation and accumulate it to the
878 // next_scroll_compensation_matrix.
879 if (!scroll_delta.IsZero()) {
880 gfx::Transform scroll_compensation_for_this_layer =
881 ComputeScrollCompensationForThisLayer(
882 layer, parent_matrix, scroll_delta);
883 next_scroll_compensation_matrix.PreconcatTransform(
884 scroll_compensation_for_this_layer);
887 // If the layer created its own render_surface, we have to adjust
888 // next_scroll_compensation_matrix. The adjustment allows us to continue
889 // using the scroll compensation on the next surface.
890 // Step 1 (right-most in the math): transform from the new surface to the
891 // original ancestor surface
892 // Step 2: apply the scroll compensation
893 // Step 3: transform back to the new surface.
894 if (layer->render_surface() &&
895 !next_scroll_compensation_matrix.IsIdentity()) {
896 gfx::Transform inverse_surface_draw_transform(
897 gfx::Transform::kSkipInitialization);
898 if (!layer->render_surface()->draw_transform().GetInverse(
899 &inverse_surface_draw_transform)) {
900 // TODO(shawnsingh): Either we need to handle uninvertible transforms
901 // here, or DCHECK that the transform is invertible.
903 next_scroll_compensation_matrix =
904 inverse_surface_draw_transform * next_scroll_compensation_matrix *
905 layer->render_surface()->draw_transform();
908 return next_scroll_compensation_matrix;
911 template <typename LayerType>
912 static inline void UpdateLayerScaleDrawProperties(
913 LayerType* layer,
914 float ideal_contents_scale,
915 float maximum_animation_contents_scale,
916 float starting_animation_contents_scale,
917 float page_scale_factor,
918 float device_scale_factor) {
919 layer->draw_properties().ideal_contents_scale = ideal_contents_scale;
920 layer->draw_properties().maximum_animation_contents_scale =
921 maximum_animation_contents_scale;
922 layer->draw_properties().starting_animation_contents_scale =
923 starting_animation_contents_scale;
924 layer->draw_properties().page_scale_factor = page_scale_factor;
925 layer->draw_properties().device_scale_factor = device_scale_factor;
928 static inline void CalculateContentsScale(LayerImpl* layer,
929 float contents_scale) {
930 // LayerImpl has all of its content scales and bounds pushed from the Main
931 // thread during commit and just uses those values as-is.
934 static inline void CalculateContentsScale(Layer* layer, float contents_scale) {
935 layer->CalculateContentsScale(contents_scale,
936 &layer->draw_properties().contents_scale_x,
937 &layer->draw_properties().contents_scale_y,
938 &layer->draw_properties().content_bounds);
940 Layer* mask_layer = layer->mask_layer();
941 if (mask_layer) {
942 mask_layer->CalculateContentsScale(
943 contents_scale,
944 &mask_layer->draw_properties().contents_scale_x,
945 &mask_layer->draw_properties().contents_scale_y,
946 &mask_layer->draw_properties().content_bounds);
949 Layer* replica_mask_layer =
950 layer->replica_layer() ? layer->replica_layer()->mask_layer() : NULL;
951 if (replica_mask_layer) {
952 replica_mask_layer->CalculateContentsScale(
953 contents_scale,
954 &replica_mask_layer->draw_properties().contents_scale_x,
955 &replica_mask_layer->draw_properties().contents_scale_y,
956 &replica_mask_layer->draw_properties().content_bounds);
960 static inline void UpdateLayerContentsScale(
961 LayerImpl* layer,
962 bool can_adjust_raster_scale,
963 float ideal_contents_scale,
964 float device_scale_factor,
965 float page_scale_factor,
966 bool animating_transform_to_screen) {
967 CalculateContentsScale(layer, ideal_contents_scale);
970 static inline void UpdateLayerContentsScale(
971 Layer* layer,
972 bool can_adjust_raster_scale,
973 float ideal_contents_scale,
974 float device_scale_factor,
975 float page_scale_factor,
976 bool animating_transform_to_screen) {
977 if (can_adjust_raster_scale) {
978 float ideal_raster_scale =
979 ideal_contents_scale / (device_scale_factor * page_scale_factor);
981 bool need_to_set_raster_scale = layer->raster_scale_is_unknown();
983 // If we've previously saved a raster_scale but the ideal changes, things
984 // are unpredictable and we should just use 1.
985 if (!need_to_set_raster_scale && layer->raster_scale() != 1.f &&
986 ideal_raster_scale != layer->raster_scale()) {
987 ideal_raster_scale = 1.f;
988 need_to_set_raster_scale = true;
991 if (need_to_set_raster_scale) {
992 bool use_and_save_ideal_scale =
993 ideal_raster_scale >= 1.f && !animating_transform_to_screen;
994 if (use_and_save_ideal_scale)
995 layer->set_raster_scale(ideal_raster_scale);
999 float raster_scale = 1.f;
1000 if (!layer->raster_scale_is_unknown())
1001 raster_scale = layer->raster_scale();
1003 gfx::Size old_content_bounds = layer->content_bounds();
1004 float old_contents_scale_x = layer->contents_scale_x();
1005 float old_contents_scale_y = layer->contents_scale_y();
1007 float contents_scale = raster_scale * device_scale_factor * page_scale_factor;
1008 CalculateContentsScale(layer, contents_scale);
1010 if (layer->content_bounds() != old_content_bounds ||
1011 layer->contents_scale_x() != old_contents_scale_x ||
1012 layer->contents_scale_y() != old_contents_scale_y)
1013 layer->SetNeedsPushProperties();
1016 static inline void CalculateAnimationContentsScale(
1017 Layer* layer,
1018 bool ancestor_is_animating_scale,
1019 float ancestor_maximum_animation_contents_scale,
1020 const gfx::Transform& parent_transform,
1021 const gfx::Transform& combined_transform,
1022 bool* combined_is_animating_scale,
1023 float* combined_maximum_animation_contents_scale,
1024 float* combined_starting_animation_contents_scale) {
1025 *combined_is_animating_scale = false;
1026 *combined_maximum_animation_contents_scale = 0.f;
1027 *combined_starting_animation_contents_scale = 0.f;
1030 static inline void CalculateAnimationContentsScale(
1031 LayerImpl* layer,
1032 bool ancestor_is_animating_scale,
1033 float ancestor_maximum_animation_contents_scale,
1034 const gfx::Transform& ancestor_transform,
1035 const gfx::Transform& combined_transform,
1036 bool* combined_is_animating_scale,
1037 float* combined_maximum_animation_contents_scale,
1038 float* combined_starting_animation_contents_scale) {
1039 if (ancestor_is_animating_scale &&
1040 ancestor_maximum_animation_contents_scale == 0.f) {
1041 // We've already failed to compute a maximum animated scale at an
1042 // ancestor, so we'll continue to fail.
1043 *combined_maximum_animation_contents_scale = 0.f;
1044 *combined_starting_animation_contents_scale = 0.f;
1045 *combined_is_animating_scale = true;
1046 return;
1049 if (!combined_transform.IsScaleOrTranslation()) {
1050 // Computing maximum animated scale in the presence of
1051 // non-scale/translation transforms isn't supported.
1052 *combined_maximum_animation_contents_scale = 0.f;
1053 *combined_starting_animation_contents_scale = 0.f;
1054 *combined_is_animating_scale = true;
1055 return;
1058 // We currently only support computing maximum scale for combinations of
1059 // scales and translations. We treat all non-translations as potentially
1060 // affecting scale. Animations that include non-translation/scale components
1061 // will cause the computation of MaximumScale below to fail.
1062 bool layer_is_animating_scale =
1063 !layer->layer_animation_controller()->HasOnlyTranslationTransforms();
1065 if (!layer_is_animating_scale && !ancestor_is_animating_scale) {
1066 *combined_maximum_animation_contents_scale = 0.f;
1067 *combined_starting_animation_contents_scale = 0.f;
1068 *combined_is_animating_scale = false;
1069 return;
1072 // We don't attempt to accumulate animation scale from multiple nodes,
1073 // because of the risk of significant overestimation. For example, one node
1074 // may be increasing scale from 1 to 10 at the same time as a descendant is
1075 // decreasing scale from 10 to 1. Naively combining these scales would produce
1076 // a scale of 100.
1077 if (layer_is_animating_scale && ancestor_is_animating_scale) {
1078 *combined_maximum_animation_contents_scale = 0.f;
1079 *combined_starting_animation_contents_scale = 0.f;
1080 *combined_is_animating_scale = true;
1081 return;
1084 // At this point, we know either the layer or an ancestor, but not both,
1085 // is animating scale.
1086 *combined_is_animating_scale = true;
1087 if (!layer_is_animating_scale) {
1088 gfx::Vector2dF layer_transform_scales =
1089 MathUtil::ComputeTransform2dScaleComponents(layer->transform(), 0.f);
1090 *combined_maximum_animation_contents_scale =
1091 ancestor_maximum_animation_contents_scale *
1092 std::max(layer_transform_scales.x(), layer_transform_scales.y());
1093 *combined_starting_animation_contents_scale =
1094 *combined_maximum_animation_contents_scale;
1095 return;
1098 float layer_maximum_animated_scale = 0.f;
1099 float layer_start_animated_scale = 0.f;
1100 if (!layer->layer_animation_controller()->MaximumTargetScale(
1101 &layer_maximum_animated_scale)) {
1102 *combined_maximum_animation_contents_scale = 0.f;
1103 return;
1105 if (!layer->layer_animation_controller()->AnimationStartScale(
1106 &layer_start_animated_scale)) {
1107 *combined_starting_animation_contents_scale = 0.f;
1108 return;
1111 gfx::Vector2dF ancestor_transform_scales =
1112 MathUtil::ComputeTransform2dScaleComponents(ancestor_transform, 0.f);
1113 float max_scale_xy =
1114 std::max(ancestor_transform_scales.x(), ancestor_transform_scales.y());
1115 *combined_maximum_animation_contents_scale =
1116 layer_maximum_animated_scale * max_scale_xy;
1117 *combined_starting_animation_contents_scale =
1118 layer_start_animated_scale * max_scale_xy;
1121 template <typename LayerTypePtr>
1122 static inline void MarkLayerWithRenderSurfaceLayerListId(
1123 LayerTypePtr layer,
1124 int current_render_surface_layer_list_id) {
1125 layer->draw_properties().last_drawn_render_surface_layer_list_id =
1126 current_render_surface_layer_list_id;
1127 layer->draw_properties().layer_or_descendant_is_drawn =
1128 !!current_render_surface_layer_list_id;
1131 template <typename LayerTypePtr>
1132 static inline void MarkMasksWithRenderSurfaceLayerListId(
1133 LayerTypePtr layer,
1134 int current_render_surface_layer_list_id) {
1135 if (layer->mask_layer()) {
1136 MarkLayerWithRenderSurfaceLayerListId(layer->mask_layer(),
1137 current_render_surface_layer_list_id);
1139 if (layer->replica_layer() && layer->replica_layer()->mask_layer()) {
1140 MarkLayerWithRenderSurfaceLayerListId(layer->replica_layer()->mask_layer(),
1141 current_render_surface_layer_list_id);
1145 template <typename LayerListType>
1146 static inline void MarkLayerListWithRenderSurfaceLayerListId(
1147 LayerListType* layer_list,
1148 int current_render_surface_layer_list_id) {
1149 for (typename LayerListType::iterator it = layer_list->begin();
1150 it != layer_list->end();
1151 ++it) {
1152 MarkLayerWithRenderSurfaceLayerListId(*it,
1153 current_render_surface_layer_list_id);
1154 MarkMasksWithRenderSurfaceLayerListId(*it,
1155 current_render_surface_layer_list_id);
1159 template <typename LayerType>
1160 static inline void RemoveSurfaceForEarlyExit(
1161 LayerType* layer_to_remove,
1162 typename LayerType::RenderSurfaceListType* render_surface_layer_list) {
1163 DCHECK(layer_to_remove->render_surface());
1164 // Technically, we know that the layer we want to remove should be
1165 // at the back of the render_surface_layer_list. However, we have had
1166 // bugs before that added unnecessary layers here
1167 // (https://bugs.webkit.org/show_bug.cgi?id=74147), but that causes
1168 // things to crash. So here we proactively remove any additional
1169 // layers from the end of the list.
1170 while (render_surface_layer_list->back() != layer_to_remove) {
1171 MarkLayerListWithRenderSurfaceLayerListId(
1172 &render_surface_layer_list->back()->render_surface()->layer_list(), 0);
1173 MarkLayerWithRenderSurfaceLayerListId(render_surface_layer_list->back(), 0);
1175 render_surface_layer_list->back()->ClearRenderSurfaceLayerList();
1176 render_surface_layer_list->pop_back();
1178 DCHECK_EQ(render_surface_layer_list->back(), layer_to_remove);
1179 MarkLayerListWithRenderSurfaceLayerListId(
1180 &layer_to_remove->render_surface()->layer_list(), 0);
1181 MarkLayerWithRenderSurfaceLayerListId(layer_to_remove, 0);
1182 render_surface_layer_list->pop_back();
1183 layer_to_remove->ClearRenderSurfaceLayerList();
1186 struct PreCalculateMetaInformationRecursiveData {
1187 int num_unclipped_descendants;
1188 int num_layer_or_descendants_with_copy_request;
1189 int num_layer_or_descendants_with_input_handler;
1191 PreCalculateMetaInformationRecursiveData()
1192 : num_unclipped_descendants(0),
1193 num_layer_or_descendants_with_copy_request(0),
1194 num_layer_or_descendants_with_input_handler(0) {}
1196 void Merge(const PreCalculateMetaInformationRecursiveData& data) {
1197 num_layer_or_descendants_with_copy_request +=
1198 data.num_layer_or_descendants_with_copy_request;
1199 num_layer_or_descendants_with_input_handler +=
1200 data.num_layer_or_descendants_with_input_handler;
1201 num_unclipped_descendants += data.num_unclipped_descendants;
1205 static void ValidateRenderSurface(LayerImpl* layer) {
1206 // This test verifies that there are no cases where a LayerImpl needs
1207 // a render surface, but doesn't have one.
1208 if (layer->render_surface())
1209 return;
1211 DCHECK(layer->filters().IsEmpty()) << "layer: " << layer->id();
1212 DCHECK(layer->background_filters().IsEmpty()) << "layer: " << layer->id();
1213 DCHECK(!layer->mask_layer()) << "layer: " << layer->id();
1214 DCHECK(!layer->replica_layer()) << "layer: " << layer->id();
1215 DCHECK(!IsRootLayer(layer)) << "layer: " << layer->id();
1216 DCHECK(!layer->is_root_for_isolated_group()) << "layer: " << layer->id();
1217 DCHECK(!layer->HasCopyRequest()) << "layer: " << layer->id();
1220 static void ValidateRenderSurface(Layer* layer) {
1223 static void ResetDrawProperties(Layer* layer) {
1224 layer->draw_properties().sorted_for_recursion = false;
1225 layer->draw_properties().has_child_with_a_scroll_parent = false;
1226 layer->draw_properties().layer_or_descendant_is_drawn = false;
1227 layer->draw_properties().visited = false;
1228 if (!HasInvertibleOrAnimatedTransform(layer)) {
1229 // Layers with singular transforms should not be drawn, the whole subtree
1230 // can be skipped.
1231 return;
1234 for (size_t i = 0; i < layer->children().size(); ++i) {
1235 Layer* child_layer = layer->child_at(i);
1236 if (child_layer->scroll_parent())
1237 layer->draw_properties().has_child_with_a_scroll_parent = true;
1238 ResetDrawProperties(child_layer);
1242 static void ResetDrawProperties(LayerImpl* layer) {
1245 static bool IsMetaInformationRecomputationNeeded(Layer* layer) {
1246 return layer->layer_tree_host()->needs_meta_info_recomputation();
1249 // Recursively walks the layer tree(if needed) to compute any information
1250 // that is needed before doing the main recursion.
1251 static void PreCalculateMetaInformationInternal(
1252 Layer* layer,
1253 PreCalculateMetaInformationRecursiveData* recursive_data) {
1254 ValidateRenderSurface(layer);
1255 if (!HasInvertibleOrAnimatedTransform(layer)) {
1256 // Layers with singular transforms should not be drawn, the whole subtree
1257 // can be skipped.
1258 return;
1261 if (!IsMetaInformationRecomputationNeeded(layer)) {
1262 DCHECK(IsRootLayer(layer));
1263 return;
1266 if (layer->clip_parent())
1267 recursive_data->num_unclipped_descendants++;
1269 for (size_t i = 0; i < layer->children().size(); ++i) {
1270 Layer* child_layer = layer->child_at(i);
1272 PreCalculateMetaInformationRecursiveData data_for_child;
1273 PreCalculateMetaInformationInternal(child_layer, &data_for_child);
1275 recursive_data->Merge(data_for_child);
1278 if (layer->clip_children()) {
1279 int num_clip_children = layer->clip_children()->size();
1280 DCHECK_GE(recursive_data->num_unclipped_descendants, num_clip_children);
1281 recursive_data->num_unclipped_descendants -= num_clip_children;
1284 if (layer->HasCopyRequest())
1285 recursive_data->num_layer_or_descendants_with_copy_request++;
1287 if (!layer->touch_event_handler_region().IsEmpty() ||
1288 layer->have_wheel_event_handlers())
1289 recursive_data->num_layer_or_descendants_with_input_handler++;
1291 layer->draw_properties().num_unclipped_descendants =
1292 recursive_data->num_unclipped_descendants;
1293 layer->draw_properties().layer_or_descendant_has_copy_request =
1294 (recursive_data->num_layer_or_descendants_with_copy_request != 0);
1295 layer->draw_properties().layer_or_descendant_has_input_handler =
1296 (recursive_data->num_layer_or_descendants_with_input_handler != 0);
1297 layer->set_num_layer_or_descandant_with_copy_request(
1298 recursive_data->num_layer_or_descendants_with_copy_request);
1299 layer->set_num_layer_or_descandant_with_input_handler(
1300 recursive_data->num_layer_or_descendants_with_input_handler);
1302 if (IsRootLayer(layer))
1303 layer->layer_tree_host()->SetNeedsMetaInfoRecomputation(false);
1306 static void PreCalculateMetaInformationInternal(
1307 LayerImpl* layer,
1308 PreCalculateMetaInformationRecursiveData* recursive_data) {
1309 ValidateRenderSurface(layer);
1311 layer->draw_properties().sorted_for_recursion = false;
1312 layer->draw_properties().has_child_with_a_scroll_parent = false;
1313 layer->draw_properties().layer_or_descendant_is_drawn = false;
1314 layer->draw_properties().visited = false;
1316 if (!HasInvertibleOrAnimatedTransform(layer)) {
1317 // Layers with singular transforms should not be drawn, the whole subtree
1318 // can be skipped.
1319 return;
1322 if (layer->clip_parent())
1323 recursive_data->num_unclipped_descendants++;
1325 for (size_t i = 0; i < layer->children().size(); ++i) {
1326 LayerImpl* child_layer = layer->child_at(i);
1328 PreCalculateMetaInformationRecursiveData data_for_child;
1329 PreCalculateMetaInformationInternal(child_layer, &data_for_child);
1331 if (child_layer->scroll_parent())
1332 layer->draw_properties().has_child_with_a_scroll_parent = true;
1333 recursive_data->Merge(data_for_child);
1336 if (layer->clip_children()) {
1337 int num_clip_children = layer->clip_children()->size();
1338 DCHECK_GE(recursive_data->num_unclipped_descendants, num_clip_children);
1339 recursive_data->num_unclipped_descendants -= num_clip_children;
1342 if (layer->HasCopyRequest())
1343 recursive_data->num_layer_or_descendants_with_copy_request++;
1345 if (!layer->touch_event_handler_region().IsEmpty() ||
1346 layer->have_wheel_event_handlers())
1347 recursive_data->num_layer_or_descendants_with_input_handler++;
1349 layer->draw_properties().num_unclipped_descendants =
1350 recursive_data->num_unclipped_descendants;
1351 layer->draw_properties().layer_or_descendant_has_copy_request =
1352 (recursive_data->num_layer_or_descendants_with_copy_request != 0);
1353 layer->draw_properties().layer_or_descendant_has_input_handler =
1354 (recursive_data->num_layer_or_descendants_with_input_handler != 0);
1357 void LayerTreeHostCommon::PreCalculateMetaInformation(Layer* root_layer) {
1358 PreCalculateMetaInformationRecursiveData recursive_data;
1359 PreCalculateMetaInformationInternal(root_layer, &recursive_data);
1362 template <typename LayerType>
1363 struct SubtreeGlobals {
1364 int max_texture_size;
1365 float device_scale_factor;
1366 float page_scale_factor;
1367 const LayerType* page_scale_application_layer;
1368 gfx::Vector2dF elastic_overscroll;
1369 const LayerType* elastic_overscroll_application_layer;
1370 bool can_adjust_raster_scales;
1371 bool can_render_to_separate_surface;
1372 bool layers_always_allowed_lcd_text;
1375 template<typename LayerType>
1376 struct DataForRecursion {
1377 // The accumulated sequence of transforms a layer will use to determine its
1378 // own draw transform.
1379 gfx::Transform parent_matrix;
1381 // The accumulated sequence of transforms a layer will use to determine its
1382 // own screen-space transform.
1383 gfx::Transform full_hierarchy_matrix;
1385 // The transform that removes all scrolling that may have occurred between a
1386 // fixed-position layer and its container, so that the layer actually does
1387 // remain fixed.
1388 gfx::Transform scroll_compensation_matrix;
1390 // The ancestor that would be the container for any fixed-position / sticky
1391 // layers.
1392 LayerType* fixed_container;
1394 // This is the normal clip rect that is propagated from parent to child.
1395 gfx::Rect clip_rect_in_target_space;
1397 // When the layer's children want to compute their visible content rect, they
1398 // want to know what their target surface's clip rect will be. BUT - they
1399 // want to know this clip rect represented in their own target space. This
1400 // requires inverse-projecting the surface's clip rect from the surface's
1401 // render target space down to the surface's own space. Instead of computing
1402 // this value redundantly for each child layer, it is computed only once
1403 // while dealing with the parent layer, and then this precomputed value is
1404 // passed down the recursion to the children that actually use it.
1405 gfx::Rect clip_rect_of_target_surface_in_target_space;
1407 // The maximum amount by which this layer will be scaled during the lifetime
1408 // of currently running animations.
1409 float maximum_animation_contents_scale;
1411 bool ancestor_is_animating_scale;
1412 bool ancestor_clips_subtree;
1413 typename LayerType::RenderSurfaceType*
1414 nearest_occlusion_immune_ancestor_surface;
1415 bool in_subtree_of_page_scale_application_layer;
1416 bool subtree_can_use_lcd_text;
1417 bool subtree_is_visible_from_ancestor;
1420 template <typename LayerType>
1421 static LayerType* GetChildContainingLayer(const LayerType& parent,
1422 LayerType* layer) {
1423 for (LayerType* ancestor = layer; ancestor; ancestor = ancestor->parent()) {
1424 if (ancestor->parent() == &parent)
1425 return ancestor;
1427 NOTREACHED();
1428 return 0;
1431 template <typename LayerType>
1432 static void AddScrollParentChain(std::vector<LayerType*>* out,
1433 const LayerType& parent,
1434 LayerType* layer) {
1435 // At a high level, this function walks up the chain of scroll parents
1436 // recursively, and once we reach the end of the chain, we add the child
1437 // of |parent| containing each scroll ancestor as we unwind. The result is
1438 // an ordering of parent's children that ensures that scroll parents are
1439 // visited before their descendants.
1440 // Take for example this layer tree:
1442 // + stacking_context
1443 // + scroll_child (1)
1444 // + scroll_parent_graphics_layer (*)
1445 // | + scroll_parent_scrolling_layer
1446 // | + scroll_parent_scrolling_content_layer (2)
1447 // + scroll_grandparent_graphics_layer (**)
1448 // + scroll_grandparent_scrolling_layer
1449 // + scroll_grandparent_scrolling_content_layer (3)
1451 // The scroll child is (1), its scroll parent is (2) and its scroll
1452 // grandparent is (3). Note, this doesn't mean that (2)'s scroll parent is
1453 // (3), it means that (*)'s scroll parent is (3). We don't want our list to
1454 // look like [ (3), (2), (1) ], even though that does have the ancestor chain
1455 // in the right order. Instead, we want [ (**), (*), (1) ]. That is, only want
1456 // (1)'s siblings in the list, but we want them to appear in such an order
1457 // that the scroll ancestors get visited in the correct order.
1459 // So our first task at this step of the recursion is to determine the layer
1460 // that we will potentionally add to the list. That is, the child of parent
1461 // containing |layer|.
1462 LayerType* child = GetChildContainingLayer(parent, layer);
1463 if (child->draw_properties().sorted_for_recursion)
1464 return;
1466 if (LayerType* scroll_parent = child->scroll_parent())
1467 AddScrollParentChain(out, parent, scroll_parent);
1469 out->push_back(child);
1470 child->draw_properties().sorted_for_recursion = true;
1473 template <typename LayerType>
1474 static bool SortChildrenForRecursion(std::vector<LayerType*>* out,
1475 const LayerType& parent) {
1476 out->reserve(parent.children().size());
1477 bool order_changed = false;
1478 for (size_t i = 0; i < parent.children().size(); ++i) {
1479 LayerType* current =
1480 LayerTreeHostCommon::get_layer_as_raw_ptr(parent.children(), i);
1482 if (current->draw_properties().sorted_for_recursion) {
1483 order_changed = true;
1484 continue;
1487 AddScrollParentChain(out, parent, current);
1490 DCHECK_EQ(parent.children().size(), out->size());
1491 return order_changed;
1494 template <typename LayerType>
1495 static void GetNewDescendantsStartIndexAndCount(LayerType* layer,
1496 size_t* start_index,
1497 size_t* count) {
1498 *start_index = layer->draw_properties().index_of_first_descendants_addition;
1499 *count = layer->draw_properties().num_descendants_added;
1502 template <typename LayerType>
1503 static void GetNewRenderSurfacesStartIndexAndCount(LayerType* layer,
1504 size_t* start_index,
1505 size_t* count) {
1506 *start_index = layer->draw_properties()
1507 .index_of_first_render_surface_layer_list_addition;
1508 *count = layer->draw_properties().num_render_surfaces_added;
1511 // We need to extract a list from the the two flavors of RenderSurfaceListType
1512 // for use in the sorting function below.
1513 static LayerList* GetLayerListForSorting(RenderSurfaceLayerList* rsll) {
1514 return &rsll->AsLayerList();
1517 static LayerImplList* GetLayerListForSorting(LayerImplList* layer_list) {
1518 return layer_list;
1521 static inline gfx::Vector2d BoundsDelta(Layer* layer) {
1522 return gfx::Vector2d();
1525 static inline gfx::Vector2d BoundsDelta(LayerImpl* layer) {
1526 return gfx::ToCeiledVector2d(layer->bounds_delta());
1529 template <typename LayerType, typename GetIndexAndCountType>
1530 static void SortLayerListContributions(
1531 const LayerType& parent,
1532 typename LayerType::LayerListType* unsorted,
1533 size_t start_index_for_all_contributions,
1534 GetIndexAndCountType get_index_and_count) {
1535 typename LayerType::LayerListType buffer;
1536 for (size_t i = 0; i < parent.children().size(); ++i) {
1537 LayerType* child =
1538 LayerTreeHostCommon::get_layer_as_raw_ptr(parent.children(), i);
1540 size_t start_index = 0;
1541 size_t count = 0;
1542 get_index_and_count(child, &start_index, &count);
1543 for (size_t j = start_index; j < start_index + count; ++j)
1544 buffer.push_back(unsorted->at(j));
1547 DCHECK_EQ(buffer.size(),
1548 unsorted->size() - start_index_for_all_contributions);
1550 for (size_t i = 0; i < buffer.size(); ++i)
1551 (*unsorted)[i + start_index_for_all_contributions] = buffer[i];
1554 // Recursively walks the layer tree starting at the given node and computes all
1555 // the necessary transformations, clip rects, render surfaces, etc.
1556 template <typename LayerType>
1557 static void CalculateDrawPropertiesInternal(
1558 LayerType* layer,
1559 const SubtreeGlobals<LayerType>& globals,
1560 const DataForRecursion<LayerType>& data_from_ancestor,
1561 typename LayerType::RenderSurfaceListType* render_surface_layer_list,
1562 typename LayerType::LayerListType* layer_list,
1563 std::vector<AccumulatedSurfaceState<LayerType>>* accumulated_surface_state,
1564 int current_render_surface_layer_list_id) {
1565 // This function computes the new matrix transformations recursively for this
1566 // layer and all its descendants. It also computes the appropriate render
1567 // surfaces.
1568 // Some important points to remember:
1570 // 0. Here, transforms are notated in Matrix x Vector order, and in words we
1571 // describe what the transform does from left to right.
1573 // 1. In our terminology, the "layer origin" refers to the top-left corner of
1574 // a layer, and the positive Y-axis points downwards. This interpretation is
1575 // valid because the orthographic projection applied at draw time flips the Y
1576 // axis appropriately.
1578 // 2. The anchor point, when given as a PointF object, is specified in "unit
1579 // layer space", where the bounds of the layer map to [0, 1]. However, as a
1580 // Transform object, the transform to the anchor point is specified in "layer
1581 // space", where the bounds of the layer map to [bounds.width(),
1582 // bounds.height()].
1584 // 3. Definition of various transforms used:
1585 // M[parent] is the parent matrix, with respect to the nearest render
1586 // surface, passed down recursively.
1588 // M[root] is the full hierarchy, with respect to the root, passed down
1589 // recursively.
1591 // Tr[origin] is the translation matrix from the parent's origin to
1592 // this layer's origin.
1594 // Tr[origin2anchor] is the translation from the layer's origin to its
1595 // anchor point
1597 // Tr[origin2center] is the translation from the layer's origin to its
1598 // center
1600 // M[layer] is the layer's matrix (applied at the anchor point)
1602 // S[layer2content] is the ratio of a layer's content_bounds() to its
1603 // Bounds().
1605 // Some composite transforms can help in understanding the sequence of
1606 // transforms:
1607 // composite_layer_transform = Tr[origin2anchor] * M[layer] *
1608 // Tr[origin2anchor].inverse()
1610 // 4. When a layer (or render surface) is drawn, it is drawn into a "target
1611 // render surface". Therefore the draw transform does not necessarily
1612 // transform from screen space to local layer space. Instead, the draw
1613 // transform is the transform between the "target render surface space" and
1614 // local layer space. Note that render surfaces, except for the root, also
1615 // draw themselves into a different target render surface, and so their draw
1616 // transform and origin transforms are also described with respect to the
1617 // target.
1619 // Using these definitions, then:
1621 // The draw transform for the layer is:
1622 // M[draw] = M[parent] * Tr[origin] * composite_layer_transform *
1623 // S[layer2content] = M[parent] * Tr[layer->position() + anchor] *
1624 // M[layer] * Tr[anchor2origin] * S[layer2content]
1626 // Interpreting the math left-to-right, this transforms from the
1627 // layer's render surface to the origin of the layer in content space.
1629 // The screen space transform is:
1630 // M[screenspace] = M[root] * Tr[origin] * composite_layer_transform *
1631 // S[layer2content]
1632 // = M[root] * Tr[layer->position() + anchor] * M[layer]
1633 // * Tr[anchor2origin] * S[layer2content]
1635 // Interpreting the math left-to-right, this transforms from the root
1636 // render surface's content space to the origin of the layer in content
1637 // space.
1639 // The transform hierarchy that is passed on to children (i.e. the child's
1640 // parent_matrix) is:
1641 // M[parent]_for_child = M[parent] * Tr[origin] *
1642 // composite_layer_transform
1643 // = M[parent] * Tr[layer->position() + anchor] *
1644 // M[layer] * Tr[anchor2origin]
1646 // and a similar matrix for the full hierarchy with respect to the
1647 // root.
1649 // Finally, note that the final matrix used by the shader for the layer is P *
1650 // M[draw] * S . This final product is computed in drawTexturedQuad(), where:
1651 // P is the projection matrix
1652 // S is the scale adjustment (to scale up a canonical quad to the
1653 // layer's size)
1655 // When a render surface has a replica layer, that layer's transform is used
1656 // to draw a second copy of the surface. gfx::Transforms named here are
1657 // relative to the surface, unless they specify they are relative to the
1658 // replica layer.
1660 // We will denote a scale by device scale S[deviceScale]
1662 // The render surface draw transform to its target surface origin is:
1663 // M[surfaceDraw] = M[owningLayer->Draw]
1665 // The render surface origin transform to its the root (screen space) origin
1666 // is:
1667 // M[surface2root] = M[owningLayer->screenspace] *
1668 // S[deviceScale].inverse()
1670 // The replica draw transform to its target surface origin is:
1671 // M[replicaDraw] = S[deviceScale] * M[surfaceDraw] *
1672 // Tr[replica->position() + replica->anchor()] * Tr[replica] *
1673 // Tr[origin2anchor].inverse() * S[contents_scale].inverse()
1675 // The replica draw transform to the root (screen space) origin is:
1676 // M[replica2root] = M[surface2root] * Tr[replica->position()] *
1677 // Tr[replica] * Tr[origin2anchor].inverse()
1680 // It makes no sense to have a non-unit page_scale_factor without specifying
1681 // which layer roots the subtree the scale is applied to.
1682 DCHECK(globals.page_scale_application_layer ||
1683 (globals.page_scale_factor == 1.f));
1685 CHECK(!layer->draw_properties().visited);
1686 layer->draw_properties().visited = true;
1688 DataForRecursion<LayerType> data_for_children;
1689 typename LayerType::RenderSurfaceType*
1690 nearest_occlusion_immune_ancestor_surface =
1691 data_from_ancestor.nearest_occlusion_immune_ancestor_surface;
1692 data_for_children.in_subtree_of_page_scale_application_layer =
1693 data_from_ancestor.in_subtree_of_page_scale_application_layer;
1694 data_for_children.subtree_can_use_lcd_text =
1695 data_from_ancestor.subtree_can_use_lcd_text;
1697 // Layers that are marked as hidden will hide themselves and their subtree.
1698 // Exception: Layers with copy requests, whether hidden or not, must be drawn
1699 // anyway. In this case, we will inform their subtree they are visible to get
1700 // the right results.
1701 const bool layer_is_visible =
1702 data_from_ancestor.subtree_is_visible_from_ancestor &&
1703 !layer->hide_layer_and_subtree();
1704 const bool layer_is_drawn = layer_is_visible || layer->HasCopyRequest();
1706 // The root layer cannot skip CalcDrawProperties.
1707 if (!IsRootLayer(layer) && SubtreeShouldBeSkipped(layer, layer_is_drawn)) {
1708 if (layer->render_surface())
1709 layer->ClearRenderSurfaceLayerList();
1710 layer->draw_properties().render_target = nullptr;
1711 return;
1714 // We need to circumvent the normal recursive flow of information for clip
1715 // children (they don't inherit their direct ancestor's clip information).
1716 // This is unfortunate, and would be unnecessary if we were to formally
1717 // separate the clipping hierarchy from the layer hierarchy.
1718 bool ancestor_clips_subtree = data_from_ancestor.ancestor_clips_subtree;
1719 gfx::Rect ancestor_clip_rect_in_target_space =
1720 data_from_ancestor.clip_rect_in_target_space;
1722 // Update our clipping state. If we have a clip parent we will need to pull
1723 // from the clip state cache rather than using the clip state passed from our
1724 // immediate ancestor.
1725 UpdateClipRectsForClipChild<LayerType>(
1726 layer, &ancestor_clip_rect_in_target_space, &ancestor_clips_subtree);
1728 // As this function proceeds, these are the properties for the current
1729 // layer that actually get computed. To avoid unnecessary copies
1730 // (particularly for matrices), we do computations directly on these values
1731 // when possible.
1732 DrawProperties<LayerType>& layer_draw_properties = layer->draw_properties();
1734 gfx::Rect clip_rect_in_target_space;
1735 bool layer_or_ancestor_clips_descendants = false;
1737 // This value is cached on the stack so that we don't have to inverse-project
1738 // the surface's clip rect redundantly for every layer. This value is the
1739 // same as the target surface's clip rect, except that instead of being
1740 // described in the target surface's target's space, it is described in the
1741 // current render target's space.
1742 gfx::Rect clip_rect_of_target_surface_in_target_space;
1744 float accumulated_draw_opacity = layer->opacity();
1745 bool animating_opacity_to_target = layer->OpacityIsAnimating();
1746 bool animating_opacity_to_screen = animating_opacity_to_target;
1747 if (layer->parent()) {
1748 accumulated_draw_opacity *= layer->parent()->draw_opacity();
1749 animating_opacity_to_target |= layer->parent()->draw_opacity_is_animating();
1750 animating_opacity_to_screen |=
1751 layer->parent()->screen_space_opacity_is_animating();
1754 bool animating_transform_to_target = layer->TransformIsAnimating();
1755 bool animating_transform_to_screen = animating_transform_to_target;
1756 if (layer->parent()) {
1757 animating_transform_to_target |=
1758 layer->parent()->draw_transform_is_animating();
1759 animating_transform_to_screen |=
1760 layer->parent()->screen_space_transform_is_animating();
1762 gfx::Point3F transform_origin = layer->transform_origin();
1763 gfx::ScrollOffset scroll_offset = GetEffectiveCurrentScrollOffset(layer);
1764 gfx::PointF position =
1765 layer->position() - ScrollOffsetToVector2dF(scroll_offset);
1766 gfx::Transform combined_transform = data_from_ancestor.parent_matrix;
1767 if (!layer->transform().IsIdentity()) {
1768 // LT = Tr[origin] * Tr[origin2transformOrigin]
1769 combined_transform.Translate3d(position.x() + transform_origin.x(),
1770 position.y() + transform_origin.y(),
1771 transform_origin.z());
1772 // LT = Tr[origin] * Tr[origin2origin] * M[layer]
1773 combined_transform.PreconcatTransform(layer->transform());
1774 // LT = Tr[origin] * Tr[origin2origin] * M[layer] *
1775 // Tr[transformOrigin2origin]
1776 combined_transform.Translate3d(
1777 -transform_origin.x(), -transform_origin.y(), -transform_origin.z());
1778 } else {
1779 combined_transform.Translate(position.x(), position.y());
1782 gfx::Vector2dF effective_scroll_delta = GetEffectiveScrollDelta(layer);
1783 if (!animating_transform_to_target && layer->scrollable() &&
1784 combined_transform.IsScaleOrTranslation()) {
1785 // Align the scrollable layer's position to screen space pixels to avoid
1786 // blurriness. To avoid side-effects, do this only if the transform is
1787 // simple.
1788 gfx::Vector2dF previous_translation = combined_transform.To2dTranslation();
1789 combined_transform.RoundTranslationComponents();
1790 gfx::Vector2dF current_translation = combined_transform.To2dTranslation();
1792 // This rounding changes the scroll delta, and so must be included
1793 // in the scroll compensation matrix. The scaling converts from physical
1794 // coordinates to the scroll delta's CSS coordinates (using the parent
1795 // matrix instead of combined transform since scrolling is applied before
1796 // the layer's transform). For example, if we have a total scale factor of
1797 // 3.0, then 1 physical pixel is only 1/3 of a CSS pixel.
1798 gfx::Vector2dF parent_scales = MathUtil::ComputeTransform2dScaleComponents(
1799 data_from_ancestor.parent_matrix, 1.f);
1800 effective_scroll_delta -=
1801 gfx::ScaleVector2d(current_translation - previous_translation,
1802 1.f / parent_scales.x(),
1803 1.f / parent_scales.y());
1806 // Apply adjustment from position constraints.
1807 ApplyPositionAdjustment(layer, data_from_ancestor.fixed_container,
1808 data_from_ancestor.scroll_compensation_matrix, &combined_transform);
1810 bool combined_is_animating_scale = false;
1811 float combined_maximum_animation_contents_scale = 0.f;
1812 float combined_starting_animation_contents_scale = 0.f;
1813 if (globals.can_adjust_raster_scales) {
1814 CalculateAnimationContentsScale(
1815 layer, data_from_ancestor.ancestor_is_animating_scale,
1816 data_from_ancestor.maximum_animation_contents_scale,
1817 data_from_ancestor.parent_matrix, combined_transform,
1818 &combined_is_animating_scale,
1819 &combined_maximum_animation_contents_scale,
1820 &combined_starting_animation_contents_scale);
1822 data_for_children.ancestor_is_animating_scale = combined_is_animating_scale;
1823 data_for_children.maximum_animation_contents_scale =
1824 combined_maximum_animation_contents_scale;
1826 // Compute the 2d scale components of the transform hierarchy up to the target
1827 // surface. From there, we can decide on a contents scale for the layer.
1828 float layer_scale_factors = globals.device_scale_factor;
1829 if (data_from_ancestor.in_subtree_of_page_scale_application_layer)
1830 layer_scale_factors *= globals.page_scale_factor;
1831 gfx::Vector2dF combined_transform_scales =
1832 MathUtil::ComputeTransform2dScaleComponents(
1833 combined_transform,
1834 layer_scale_factors);
1836 float ideal_contents_scale =
1837 globals.can_adjust_raster_scales
1838 ? std::max(combined_transform_scales.x(),
1839 combined_transform_scales.y())
1840 : layer_scale_factors;
1841 UpdateLayerContentsScale(
1842 layer,
1843 globals.can_adjust_raster_scales,
1844 ideal_contents_scale,
1845 globals.device_scale_factor,
1846 data_from_ancestor.in_subtree_of_page_scale_application_layer
1847 ? globals.page_scale_factor
1848 : 1.f,
1849 animating_transform_to_screen);
1851 UpdateLayerScaleDrawProperties(
1852 layer, ideal_contents_scale, combined_maximum_animation_contents_scale,
1853 combined_starting_animation_contents_scale,
1854 data_from_ancestor.in_subtree_of_page_scale_application_layer
1855 ? globals.page_scale_factor
1856 : 1.f,
1857 globals.device_scale_factor);
1859 LayerType* mask_layer = layer->mask_layer();
1860 if (mask_layer) {
1861 UpdateLayerScaleDrawProperties(
1862 mask_layer, ideal_contents_scale,
1863 combined_maximum_animation_contents_scale,
1864 combined_starting_animation_contents_scale,
1865 data_from_ancestor.in_subtree_of_page_scale_application_layer
1866 ? globals.page_scale_factor
1867 : 1.f,
1868 globals.device_scale_factor);
1871 LayerType* replica_mask_layer =
1872 layer->replica_layer() ? layer->replica_layer()->mask_layer() : NULL;
1873 if (replica_mask_layer) {
1874 UpdateLayerScaleDrawProperties(
1875 replica_mask_layer, ideal_contents_scale,
1876 combined_maximum_animation_contents_scale,
1877 combined_starting_animation_contents_scale,
1878 data_from_ancestor.in_subtree_of_page_scale_application_layer
1879 ? globals.page_scale_factor
1880 : 1.f,
1881 globals.device_scale_factor);
1884 // The draw_transform that gets computed below is effectively the layer's
1885 // draw_transform, unless the layer itself creates a render_surface. In that
1886 // case, the render_surface re-parents the transforms.
1887 layer_draw_properties.target_space_transform = combined_transform;
1888 // M[draw] = M[parent] * LT * S[layer2content]
1889 layer_draw_properties.target_space_transform.Scale(
1890 SK_MScalar1 / layer->contents_scale_x(),
1891 SK_MScalar1 / layer->contents_scale_y());
1893 // The layer's screen_space_transform represents the transform between root
1894 // layer's "screen space" and local content space.
1895 layer_draw_properties.screen_space_transform =
1896 data_from_ancestor.full_hierarchy_matrix;
1897 layer_draw_properties.screen_space_transform.PreconcatTransform
1898 (layer_draw_properties.target_space_transform);
1900 // Adjusting text AA method during animation may cause repaints, which in-turn
1901 // causes jank.
1902 bool adjust_text_aa =
1903 !animating_opacity_to_screen && !animating_transform_to_screen;
1904 bool layer_can_use_lcd_text = true;
1905 bool subtree_can_use_lcd_text = true;
1906 if (!globals.layers_always_allowed_lcd_text) {
1907 // To avoid color fringing, LCD text should only be used on opaque layers
1908 // with just integral translation.
1909 subtree_can_use_lcd_text = data_from_ancestor.subtree_can_use_lcd_text &&
1910 accumulated_draw_opacity == 1.f &&
1911 layer_draw_properties.target_space_transform
1912 .IsIdentityOrIntegerTranslation();
1913 // Also disable LCD text locally for non-opaque content.
1914 layer_can_use_lcd_text = subtree_can_use_lcd_text &&
1915 layer->contents_opaque();
1918 // full_hierarchy_matrix is the matrix that transforms objects between screen
1919 // space (except projection matrix) and the most recent RenderSurfaceImpl's
1920 // space. next_hierarchy_matrix will only change if this layer uses a new
1921 // RenderSurfaceImpl, otherwise remains the same.
1922 data_for_children.full_hierarchy_matrix =
1923 data_from_ancestor.full_hierarchy_matrix;
1925 bool render_to_separate_surface =
1926 IsRootLayer(layer) ||
1927 (globals.can_render_to_separate_surface && layer->render_surface());
1929 if (render_to_separate_surface) {
1930 DCHECK(layer->render_surface());
1931 // Check back-face visibility before continuing with this surface and its
1932 // subtree
1933 if (!layer->double_sided() && TransformToParentIsKnown(layer) &&
1934 IsSurfaceBackFaceVisible(layer, combined_transform)) {
1935 layer->ClearRenderSurfaceLayerList();
1936 layer->draw_properties().render_target = nullptr;
1937 return;
1940 typename LayerType::RenderSurfaceType* render_surface =
1941 layer->render_surface();
1942 layer->ClearRenderSurfaceLayerList();
1944 layer_draw_properties.render_target = layer;
1945 if (IsRootLayer(layer)) {
1946 // The root layer's render surface size is predetermined and so the root
1947 // layer can't directly support non-identity transforms. It should just
1948 // forward top-level transforms to the rest of the tree.
1949 data_for_children.parent_matrix = combined_transform;
1951 // The root surface does not contribute to any other surface, it has no
1952 // target.
1953 layer->render_surface()->set_contributes_to_drawn_surface(false);
1954 } else {
1955 // The owning layer's draw transform has a scale from content to layer
1956 // space which we do not want; so here we use the combined_transform
1957 // instead of the draw_transform. However, we do need to add a different
1958 // scale factor that accounts for the surface's pixel dimensions.
1959 // Remove the combined_transform scale from the draw transform.
1960 gfx::Transform draw_transform = combined_transform;
1961 draw_transform.Scale(1.0 / combined_transform_scales.x(),
1962 1.0 / combined_transform_scales.y());
1963 render_surface->SetDrawTransform(draw_transform);
1965 // The owning layer's transform was re-parented by the surface, so the
1966 // layer's new draw_transform only needs to scale the layer to surface
1967 // space.
1968 layer_draw_properties.target_space_transform.MakeIdentity();
1969 layer_draw_properties.target_space_transform.Scale(
1970 combined_transform_scales.x() / layer->contents_scale_x(),
1971 combined_transform_scales.y() / layer->contents_scale_y());
1973 // Inside the surface's subtree, we scale everything to the owning layer's
1974 // scale. The sublayer matrix transforms layer rects into target surface
1975 // content space. Conceptually, all layers in the subtree inherit the
1976 // scale at the point of the render surface in the transform hierarchy,
1977 // but we apply it explicitly to the owning layer and the remainder of the
1978 // subtree independently.
1979 DCHECK(data_for_children.parent_matrix.IsIdentity());
1980 data_for_children.parent_matrix.Scale(combined_transform_scales.x(),
1981 combined_transform_scales.y());
1983 // Even if the |layer_is_drawn|, it only contributes to a drawn surface
1984 // when the |layer_is_visible|.
1985 layer->render_surface()->set_contributes_to_drawn_surface(
1986 layer_is_visible);
1989 // The opacity value is moved from the layer to its surface, so that the
1990 // entire subtree properly inherits opacity.
1991 render_surface->SetDrawOpacity(accumulated_draw_opacity);
1992 render_surface->SetDrawOpacityIsAnimating(animating_opacity_to_target);
1993 animating_opacity_to_target = false;
1994 layer_draw_properties.opacity = 1.f;
1995 layer_draw_properties.blend_mode = SkXfermode::kSrcOver_Mode;
1996 layer_draw_properties.opacity_is_animating = animating_opacity_to_target;
1997 layer_draw_properties.screen_space_opacity_is_animating =
1998 animating_opacity_to_screen;
2000 render_surface->SetTargetSurfaceTransformsAreAnimating(
2001 animating_transform_to_target);
2002 render_surface->SetScreenSpaceTransformsAreAnimating(
2003 animating_transform_to_screen);
2004 animating_transform_to_target = false;
2005 layer_draw_properties.target_space_transform_is_animating =
2006 animating_transform_to_target;
2007 layer_draw_properties.screen_space_transform_is_animating =
2008 animating_transform_to_screen;
2010 // Update the aggregate hierarchy matrix to include the transform of the
2011 // newly created RenderSurfaceImpl.
2012 data_for_children.full_hierarchy_matrix.PreconcatTransform(
2013 render_surface->draw_transform());
2015 // A render surface inherently acts as a flattening point for the content of
2016 // its descendants.
2017 data_for_children.full_hierarchy_matrix.FlattenTo2d();
2019 if (layer->mask_layer()) {
2020 DrawProperties<LayerType>& mask_layer_draw_properties =
2021 layer->mask_layer()->draw_properties();
2022 mask_layer_draw_properties.render_target = layer;
2023 mask_layer_draw_properties.visible_content_rect =
2024 gfx::Rect(layer->content_bounds());
2027 if (layer->replica_layer() && layer->replica_layer()->mask_layer()) {
2028 DrawProperties<LayerType>& replica_mask_draw_properties =
2029 layer->replica_layer()->mask_layer()->draw_properties();
2030 replica_mask_draw_properties.render_target = layer;
2031 replica_mask_draw_properties.visible_content_rect =
2032 gfx::Rect(layer->content_bounds());
2035 // Ignore occlusion from outside the surface when surface contents need to
2036 // be fully drawn. Layers with copy-request need to be complete.
2037 // We could be smarter about layers with replica and exclude regions
2038 // where both layer and the replica are occluded, but this seems like an
2039 // overkill. The same is true for layers with filters that move pixels.
2040 // TODO(senorblanco): make this smarter for the SkImageFilter case (check
2041 // for pixel-moving filters)
2042 if (layer->HasCopyRequest() ||
2043 layer->has_replica() ||
2044 layer->filters().HasReferenceFilter() ||
2045 layer->filters().HasFilterThatMovesPixels()) {
2046 nearest_occlusion_immune_ancestor_surface = render_surface;
2048 render_surface->SetNearestOcclusionImmuneAncestor(
2049 nearest_occlusion_immune_ancestor_surface);
2051 layer_or_ancestor_clips_descendants = false;
2052 bool subtree_is_clipped_by_surface_bounds = false;
2053 if (ancestor_clips_subtree) {
2054 // It may be the layer or the surface doing the clipping of the subtree,
2055 // but in either case, we'll be clipping to the projected clip rect of our
2056 // ancestor.
2057 gfx::Transform inverse_surface_draw_transform(
2058 gfx::Transform::kSkipInitialization);
2059 if (!render_surface->draw_transform().GetInverse(
2060 &inverse_surface_draw_transform)) {
2061 // TODO(shawnsingh): Either we need to handle uninvertible transforms
2062 // here, or DCHECK that the transform is invertible.
2065 gfx::Rect surface_clip_rect_in_target_space = gfx::IntersectRects(
2066 data_from_ancestor.clip_rect_of_target_surface_in_target_space,
2067 ancestor_clip_rect_in_target_space);
2068 gfx::Rect projected_surface_rect = MathUtil::ProjectEnclosingClippedRect(
2069 inverse_surface_draw_transform, surface_clip_rect_in_target_space);
2071 if (layer_draw_properties.num_unclipped_descendants > 0) {
2072 // If we have unclipped descendants, we cannot count on the render
2073 // surface's bounds clipping our subtree: the unclipped descendants
2074 // could cause us to expand our bounds. In this case, we must rely on
2075 // layer clipping for correctess. NB: since we can only encounter
2076 // translations between a clip child and its clip parent, clipping is
2077 // guaranteed to be exact in this case.
2078 layer_or_ancestor_clips_descendants = true;
2079 clip_rect_in_target_space = projected_surface_rect;
2080 } else {
2081 // The new render_surface here will correctly clip the entire subtree.
2082 // So, we do not need to continue propagating the clipping state further
2083 // down the tree. This way, we can avoid transforming clip rects from
2084 // ancestor target surface space to current target surface space that
2085 // could cause more w < 0 headaches. The render surface clip rect is
2086 // expressed in the space where this surface draws, i.e. the same space
2087 // as clip_rect_from_ancestor_in_ancestor_target_space.
2088 render_surface->SetClipRect(ancestor_clip_rect_in_target_space);
2089 clip_rect_of_target_surface_in_target_space = projected_surface_rect;
2090 subtree_is_clipped_by_surface_bounds = true;
2094 DCHECK(layer->render_surface());
2095 DCHECK(!layer->parent() || layer->parent()->render_target() ==
2096 accumulated_surface_state->back().render_target);
2098 accumulated_surface_state->push_back(
2099 AccumulatedSurfaceState<LayerType>(layer));
2101 render_surface->SetIsClipped(subtree_is_clipped_by_surface_bounds);
2102 if (!subtree_is_clipped_by_surface_bounds) {
2103 render_surface->SetClipRect(gfx::Rect());
2104 clip_rect_of_target_surface_in_target_space =
2105 data_from_ancestor.clip_rect_of_target_surface_in_target_space;
2108 // If the new render surface is drawn translucent or with a non-integral
2109 // translation then the subtree that gets drawn on this render surface
2110 // cannot use LCD text.
2111 data_for_children.subtree_can_use_lcd_text = subtree_can_use_lcd_text;
2113 render_surface_layer_list->push_back(layer);
2114 } else {
2115 DCHECK(layer->parent());
2117 // Note: layer_draw_properties.target_space_transform is computed above,
2118 // before this if-else statement.
2119 layer_draw_properties.target_space_transform_is_animating =
2120 animating_transform_to_target;
2121 layer_draw_properties.screen_space_transform_is_animating =
2122 animating_transform_to_screen;
2123 layer_draw_properties.opacity = accumulated_draw_opacity;
2124 layer_draw_properties.blend_mode = layer->blend_mode();
2125 layer_draw_properties.opacity_is_animating = animating_opacity_to_target;
2126 layer_draw_properties.screen_space_opacity_is_animating =
2127 animating_opacity_to_screen;
2128 data_for_children.parent_matrix = combined_transform;
2130 // Layers without render_surfaces directly inherit the ancestor's clip
2131 // status.
2132 layer_or_ancestor_clips_descendants = ancestor_clips_subtree;
2133 if (ancestor_clips_subtree) {
2134 clip_rect_in_target_space =
2135 ancestor_clip_rect_in_target_space;
2138 // The surface's cached clip rect value propagates regardless of what
2139 // clipping goes on between layers here.
2140 clip_rect_of_target_surface_in_target_space =
2141 data_from_ancestor.clip_rect_of_target_surface_in_target_space;
2143 // Layers that are not their own render_target will render into the target
2144 // of their nearest ancestor.
2145 layer_draw_properties.render_target = layer->parent()->render_target();
2148 if (adjust_text_aa)
2149 layer_draw_properties.can_use_lcd_text = layer_can_use_lcd_text;
2151 gfx::Size content_size_affected_by_delta(layer->content_bounds());
2153 // Non-zero BoundsDelta imply the contents_scale of 1.0
2154 // because BoundsDela is only set on Android where
2155 // ContentScalingLayer is never used.
2156 DCHECK_IMPLIES(!BoundsDelta(layer).IsZero(),
2157 (layer->contents_scale_x() == 1.0 &&
2158 layer->contents_scale_y() == 1.0));
2160 // Thus we can omit contents scale in the following calculation.
2161 gfx::Vector2d bounds_delta = BoundsDelta(layer);
2162 content_size_affected_by_delta.Enlarge(bounds_delta.x(), bounds_delta.y());
2164 gfx::Rect rect_in_target_space = MathUtil::MapEnclosingClippedRect(
2165 layer->draw_transform(),
2166 gfx::Rect(content_size_affected_by_delta));
2168 if (LayerClipsSubtree(layer)) {
2169 layer_or_ancestor_clips_descendants = true;
2170 if (ancestor_clips_subtree && !render_to_separate_surface) {
2171 // A layer without render surface shares the same target as its ancestor.
2172 clip_rect_in_target_space =
2173 ancestor_clip_rect_in_target_space;
2174 clip_rect_in_target_space.Intersect(rect_in_target_space);
2175 } else {
2176 clip_rect_in_target_space = rect_in_target_space;
2180 // Tell the layer the rect that it's clipped by. In theory we could use a
2181 // tighter clip rect here (drawable_content_rect), but that actually does not
2182 // reduce how much would be drawn, and instead it would create unnecessary
2183 // changes to scissor state affecting GPU performance. Our clip information
2184 // is used in the recursion below, so we must set it beforehand.
2185 layer_draw_properties.is_clipped = layer_or_ancestor_clips_descendants;
2186 if (layer_or_ancestor_clips_descendants) {
2187 layer_draw_properties.clip_rect = clip_rect_in_target_space;
2188 } else {
2189 // Initialize the clip rect to a safe value that will not clip the
2190 // layer, just in case clipping is still accidentally used.
2191 layer_draw_properties.clip_rect = rect_in_target_space;
2194 typename LayerType::LayerListType& descendants =
2195 (render_to_separate_surface ? layer->render_surface()->layer_list()
2196 : *layer_list);
2198 // Any layers that are appended after this point are in the layer's subtree
2199 // and should be included in the sorting process.
2200 size_t sorting_start_index = descendants.size();
2202 if (!LayerShouldBeSkipped(layer, layer_is_drawn)) {
2203 MarkLayerWithRenderSurfaceLayerListId(layer,
2204 current_render_surface_layer_list_id);
2205 descendants.push_back(layer);
2208 // Any layers that are appended after this point may need to be sorted if we
2209 // visit the children out of order.
2210 size_t render_surface_layer_list_child_sorting_start_index =
2211 render_surface_layer_list->size();
2212 size_t layer_list_child_sorting_start_index = descendants.size();
2214 if (!layer->children().empty()) {
2215 if (layer == globals.page_scale_application_layer) {
2216 data_for_children.parent_matrix.Scale(
2217 globals.page_scale_factor,
2218 globals.page_scale_factor);
2219 data_for_children.in_subtree_of_page_scale_application_layer = true;
2221 if (layer == globals.elastic_overscroll_application_layer) {
2222 data_for_children.parent_matrix.Translate(
2223 -globals.elastic_overscroll.x(), -globals.elastic_overscroll.y());
2226 // Flatten to 2D if the layer doesn't preserve 3D.
2227 if (layer->should_flatten_transform())
2228 data_for_children.parent_matrix.FlattenTo2d();
2230 data_for_children.scroll_compensation_matrix =
2231 ComputeScrollCompensationMatrixForChildren(
2232 layer,
2233 data_from_ancestor.parent_matrix,
2234 data_from_ancestor.scroll_compensation_matrix,
2235 effective_scroll_delta);
2236 data_for_children.fixed_container =
2237 layer->IsContainerForFixedPositionLayers() ?
2238 layer : data_from_ancestor.fixed_container;
2240 data_for_children.clip_rect_in_target_space = clip_rect_in_target_space;
2241 data_for_children.clip_rect_of_target_surface_in_target_space =
2242 clip_rect_of_target_surface_in_target_space;
2243 data_for_children.ancestor_clips_subtree =
2244 layer_or_ancestor_clips_descendants;
2245 data_for_children.nearest_occlusion_immune_ancestor_surface =
2246 nearest_occlusion_immune_ancestor_surface;
2247 data_for_children.subtree_is_visible_from_ancestor = layer_is_drawn;
2250 std::vector<LayerType*> sorted_children;
2251 bool child_order_changed = false;
2252 if (layer_draw_properties.has_child_with_a_scroll_parent)
2253 child_order_changed = SortChildrenForRecursion(&sorted_children, *layer);
2255 for (size_t i = 0; i < layer->children().size(); ++i) {
2256 // If one of layer's children has a scroll parent, then we may have to
2257 // visit the children out of order. The new order is stored in
2258 // sorted_children. Otherwise, we'll grab the child directly from the
2259 // layer's list of children.
2260 LayerType* child =
2261 layer_draw_properties.has_child_with_a_scroll_parent
2262 ? sorted_children[i]
2263 : LayerTreeHostCommon::get_layer_as_raw_ptr(layer->children(), i);
2265 child->draw_properties().index_of_first_descendants_addition =
2266 descendants.size();
2267 child->draw_properties().index_of_first_render_surface_layer_list_addition =
2268 render_surface_layer_list->size();
2270 CalculateDrawPropertiesInternal<LayerType>(
2271 child,
2272 globals,
2273 data_for_children,
2274 render_surface_layer_list,
2275 &descendants,
2276 accumulated_surface_state,
2277 current_render_surface_layer_list_id);
2278 // If the child is its own render target, then it has a render surface.
2279 if (child->render_target() == child &&
2280 !child->render_surface()->layer_list().empty() &&
2281 !child->render_surface()->content_rect().IsEmpty()) {
2282 // This child will contribute its render surface, which means
2283 // we need to mark just the mask layer (and replica mask layer)
2284 // with the id.
2285 MarkMasksWithRenderSurfaceLayerListId(
2286 child, current_render_surface_layer_list_id);
2287 descendants.push_back(child);
2290 child->draw_properties().num_descendants_added =
2291 descendants.size() -
2292 child->draw_properties().index_of_first_descendants_addition;
2293 child->draw_properties().num_render_surfaces_added =
2294 render_surface_layer_list->size() -
2295 child->draw_properties()
2296 .index_of_first_render_surface_layer_list_addition;
2297 layer_draw_properties.layer_or_descendant_is_drawn |=
2298 child->draw_properties().layer_or_descendant_is_drawn;
2301 // Add the unsorted layer list contributions, if necessary.
2302 if (child_order_changed) {
2303 SortLayerListContributions(
2304 *layer,
2305 GetLayerListForSorting(render_surface_layer_list),
2306 render_surface_layer_list_child_sorting_start_index,
2307 &GetNewRenderSurfacesStartIndexAndCount<LayerType>);
2309 SortLayerListContributions(
2310 *layer,
2311 &descendants,
2312 layer_list_child_sorting_start_index,
2313 &GetNewDescendantsStartIndexAndCount<LayerType>);
2316 // Compute the total drawable_content_rect for this subtree (the rect is in
2317 // target surface space).
2318 gfx::Rect local_drawable_content_rect_of_subtree =
2319 accumulated_surface_state->back().drawable_content_rect;
2320 if (render_to_separate_surface) {
2321 DCHECK(accumulated_surface_state->back().render_target == layer);
2322 accumulated_surface_state->pop_back();
2325 if (render_to_separate_surface && !IsRootLayer(layer) &&
2326 layer->render_surface()->layer_list().empty()) {
2327 RemoveSurfaceForEarlyExit(layer, render_surface_layer_list);
2328 return;
2331 // Compute the layer's drawable content rect (the rect is in target surface
2332 // space).
2333 layer_draw_properties.drawable_content_rect = rect_in_target_space;
2334 if (layer_or_ancestor_clips_descendants) {
2335 layer_draw_properties.drawable_content_rect.Intersect(
2336 clip_rect_in_target_space);
2338 if (layer->DrawsContent()) {
2339 local_drawable_content_rect_of_subtree.Union(
2340 layer_draw_properties.drawable_content_rect);
2343 // Compute the layer's visible content rect (the rect is in content space).
2344 layer_draw_properties.visible_content_rect = CalculateVisibleContentRect(
2345 layer, clip_rect_of_target_surface_in_target_space, rect_in_target_space);
2347 // Compute the remaining properties for the render surface, if the layer has
2348 // one.
2349 if (IsRootLayer(layer)) {
2350 // The root layer's surface's content_rect is always the entire viewport.
2351 DCHECK(render_to_separate_surface);
2352 layer->render_surface()->SetContentRect(
2353 ancestor_clip_rect_in_target_space);
2354 } else if (render_to_separate_surface) {
2355 typename LayerType::RenderSurfaceType* render_surface =
2356 layer->render_surface();
2357 gfx::Rect clipped_content_rect = local_drawable_content_rect_of_subtree;
2359 // Don't clip if the layer is reflected as the reflection shouldn't be
2360 // clipped. If the layer is animating, then the surface's transform to
2361 // its target is not known on the main thread, and we should not use it
2362 // to clip.
2363 if (!layer->replica_layer() && TransformToParentIsKnown(layer)) {
2364 // Note, it is correct to use data_from_ancestor.ancestor_clips_subtree
2365 // here, because we are looking at this layer's render_surface, not the
2366 // layer itself.
2367 if (render_surface->is_clipped() && !clipped_content_rect.IsEmpty()) {
2368 gfx::Rect surface_clip_rect = LayerTreeHostCommon::CalculateVisibleRect(
2369 render_surface->clip_rect(),
2370 clipped_content_rect,
2371 render_surface->draw_transform());
2372 clipped_content_rect.Intersect(surface_clip_rect);
2376 // The RenderSurfaceImpl backing texture cannot exceed the maximum supported
2377 // texture size.
2378 clipped_content_rect.set_width(
2379 std::min(clipped_content_rect.width(), globals.max_texture_size));
2380 clipped_content_rect.set_height(
2381 std::min(clipped_content_rect.height(), globals.max_texture_size));
2383 if (clipped_content_rect.IsEmpty()) {
2384 RemoveSurfaceForEarlyExit(layer, render_surface_layer_list);
2385 return;
2388 // Layers having a non-default blend mode will blend with the content
2389 // inside its parent's render target. This render target should be
2390 // either root_for_isolated_group, or the root of the layer tree.
2391 // Otherwise, this layer will use an incomplete backdrop, limited to its
2392 // render target and the blending result will be incorrect.
2393 DCHECK(layer->uses_default_blend_mode() || IsRootLayer(layer) ||
2394 !layer->parent()->render_target() ||
2395 IsRootLayer(layer->parent()->render_target()) ||
2396 layer->parent()->render_target()->is_root_for_isolated_group());
2398 render_surface->SetContentRect(clipped_content_rect);
2400 // The owning layer's screen_space_transform has a scale from content to
2401 // layer space which we need to undo and replace with a scale from the
2402 // surface's subtree into layer space.
2403 gfx::Transform screen_space_transform = layer->screen_space_transform();
2404 screen_space_transform.Scale(
2405 layer->contents_scale_x() / combined_transform_scales.x(),
2406 layer->contents_scale_y() / combined_transform_scales.y());
2407 render_surface->SetScreenSpaceTransform(screen_space_transform);
2409 if (layer->replica_layer()) {
2410 gfx::Transform surface_origin_to_replica_origin_transform;
2411 surface_origin_to_replica_origin_transform.Scale(
2412 combined_transform_scales.x(), combined_transform_scales.y());
2413 surface_origin_to_replica_origin_transform.Translate(
2414 layer->replica_layer()->position().x() +
2415 layer->replica_layer()->transform_origin().x(),
2416 layer->replica_layer()->position().y() +
2417 layer->replica_layer()->transform_origin().y());
2418 surface_origin_to_replica_origin_transform.PreconcatTransform(
2419 layer->replica_layer()->transform());
2420 surface_origin_to_replica_origin_transform.Translate(
2421 -layer->replica_layer()->transform_origin().x(),
2422 -layer->replica_layer()->transform_origin().y());
2423 surface_origin_to_replica_origin_transform.Scale(
2424 1.0 / combined_transform_scales.x(),
2425 1.0 / combined_transform_scales.y());
2427 // Compute the replica's "originTransform" that maps from the replica's
2428 // origin space to the target surface origin space.
2429 gfx::Transform replica_origin_transform =
2430 layer->render_surface()->draw_transform() *
2431 surface_origin_to_replica_origin_transform;
2432 render_surface->SetReplicaDrawTransform(replica_origin_transform);
2434 // Compute the replica's "screen_space_transform" that maps from the
2435 // replica's origin space to the screen's origin space.
2436 gfx::Transform replica_screen_space_transform =
2437 layer->render_surface()->screen_space_transform() *
2438 surface_origin_to_replica_origin_transform;
2439 render_surface->SetReplicaScreenSpaceTransform(
2440 replica_screen_space_transform);
2444 SavePaintPropertiesLayer(layer);
2446 // If neither this layer nor any of its children were added, early out.
2447 if (sorting_start_index == descendants.size()) {
2448 DCHECK(!render_to_separate_surface || IsRootLayer(layer));
2449 return;
2452 UpdateAccumulatedSurfaceState<LayerType>(
2453 layer, local_drawable_content_rect_of_subtree, accumulated_surface_state);
2455 if (layer->HasContributingDelegatedRenderPasses()) {
2456 layer->render_target()->render_surface()->
2457 AddContributingDelegatedRenderPassLayer(layer);
2459 } // NOLINT(readability/fn_size)
2461 template <typename LayerType, typename RenderSurfaceLayerListType>
2462 static void ProcessCalcDrawPropsInputs(
2463 const LayerTreeHostCommon::CalcDrawPropsInputs<LayerType,
2464 RenderSurfaceLayerListType>&
2465 inputs,
2466 SubtreeGlobals<LayerType>* globals,
2467 DataForRecursion<LayerType>* data_for_recursion) {
2468 DCHECK(inputs.root_layer);
2469 DCHECK(IsRootLayer(inputs.root_layer));
2470 DCHECK(inputs.render_surface_layer_list);
2472 gfx::Transform identity_matrix;
2474 // The root layer's render_surface should receive the device viewport as the
2475 // initial clip rect.
2476 gfx::Rect device_viewport_rect(inputs.device_viewport_size);
2478 gfx::Vector2dF device_transform_scale_components =
2479 MathUtil::ComputeTransform2dScaleComponents(inputs.device_transform, 1.f);
2480 // Not handling the rare case of different x and y device scale.
2481 float device_transform_scale =
2482 std::max(device_transform_scale_components.x(),
2483 device_transform_scale_components.y());
2485 gfx::Transform scaled_device_transform = inputs.device_transform;
2486 scaled_device_transform.Scale(inputs.device_scale_factor,
2487 inputs.device_scale_factor);
2489 globals->max_texture_size = inputs.max_texture_size;
2490 globals->device_scale_factor =
2491 inputs.device_scale_factor * device_transform_scale;
2492 globals->page_scale_factor = inputs.page_scale_factor;
2493 globals->page_scale_application_layer = inputs.page_scale_application_layer;
2494 globals->elastic_overscroll = inputs.elastic_overscroll;
2495 globals->elastic_overscroll_application_layer =
2496 inputs.elastic_overscroll_application_layer;
2497 globals->can_render_to_separate_surface =
2498 inputs.can_render_to_separate_surface;
2499 globals->can_adjust_raster_scales = inputs.can_adjust_raster_scales;
2500 globals->layers_always_allowed_lcd_text =
2501 inputs.layers_always_allowed_lcd_text;
2503 data_for_recursion->parent_matrix = scaled_device_transform;
2504 data_for_recursion->full_hierarchy_matrix = identity_matrix;
2505 data_for_recursion->scroll_compensation_matrix = identity_matrix;
2506 data_for_recursion->fixed_container = inputs.root_layer;
2507 data_for_recursion->clip_rect_in_target_space = device_viewport_rect;
2508 data_for_recursion->clip_rect_of_target_surface_in_target_space =
2509 device_viewport_rect;
2510 data_for_recursion->maximum_animation_contents_scale = 0.f;
2511 data_for_recursion->ancestor_is_animating_scale = false;
2512 data_for_recursion->ancestor_clips_subtree = true;
2513 data_for_recursion->nearest_occlusion_immune_ancestor_surface = NULL;
2514 data_for_recursion->in_subtree_of_page_scale_application_layer = false;
2515 data_for_recursion->subtree_can_use_lcd_text = inputs.can_use_lcd_text;
2516 data_for_recursion->subtree_is_visible_from_ancestor = true;
2519 void LayerTreeHostCommon::UpdateRenderSurface(
2520 Layer* layer,
2521 bool can_render_to_separate_surface,
2522 gfx::Transform* transform,
2523 bool* draw_transform_is_axis_aligned) {
2524 bool preserves_2d_axis_alignment =
2525 transform->Preserves2dAxisAlignment() && *draw_transform_is_axis_aligned;
2526 if (IsRootLayer(layer) || (can_render_to_separate_surface &&
2527 SubtreeShouldRenderToSeparateSurface(
2528 layer, preserves_2d_axis_alignment))) {
2529 // We reset the transform here so that any axis-changing transforms
2530 // will now be relative to this RenderSurface.
2531 transform->MakeIdentity();
2532 *draw_transform_is_axis_aligned = true;
2533 if (!layer->render_surface()) {
2534 layer->CreateRenderSurface();
2536 layer->SetHasRenderSurface(true);
2537 return;
2539 layer->SetHasRenderSurface(false);
2540 if (layer->render_surface())
2541 layer->ClearRenderSurface();
2544 void LayerTreeHostCommon::UpdateRenderSurfaces(
2545 Layer* layer,
2546 bool can_render_to_separate_surface,
2547 const gfx::Transform& parent_transform,
2548 bool draw_transform_is_axis_aligned) {
2549 gfx::Transform transform_for_children = layer->transform();
2550 transform_for_children *= parent_transform;
2551 draw_transform_is_axis_aligned &= layer->AnimationsPreserveAxisAlignment();
2552 UpdateRenderSurface(layer, can_render_to_separate_surface,
2553 &transform_for_children, &draw_transform_is_axis_aligned);
2555 for (size_t i = 0; i < layer->children().size(); ++i) {
2556 UpdateRenderSurfaces(layer->children()[i].get(),
2557 can_render_to_separate_surface, transform_for_children,
2558 draw_transform_is_axis_aligned);
2562 static bool ApproximatelyEqual(const gfx::Rect& r1, const gfx::Rect& r2) {
2563 // TODO(vollick): This tolerance should be lower: crbug.com/471786
2564 static const int tolerance = 3;
2566 if (r1.IsEmpty())
2567 return std::min(r2.width(), r2.height()) < tolerance;
2569 if (r2.IsEmpty())
2570 return std::min(r1.width(), r1.height()) < tolerance;
2572 return std::abs(r1.x() - r2.x()) <= tolerance &&
2573 std::abs(r1.y() - r2.y()) <= tolerance &&
2574 std::abs(r1.right() - r2.right()) <= tolerance &&
2575 std::abs(r1.bottom() - r2.bottom()) <= tolerance;
2578 static bool ApproximatelyEqual(const gfx::Transform& a,
2579 const gfx::Transform& b) {
2580 static const float component_tolerance = 0.1f;
2582 // We may have a larger discrepancy in the scroll components due to snapping
2583 // (floating point error might round the other way).
2584 static const float translation_tolerance = 1.f;
2586 for (int row = 0; row < 4; row++) {
2587 for (int col = 0; col < 4; col++) {
2588 const float delta =
2589 std::abs(a.matrix().get(row, col) - b.matrix().get(row, col));
2590 const float tolerance =
2591 col == 3 && row < 3 ? translation_tolerance : component_tolerance;
2592 if (delta > tolerance)
2593 return false;
2597 return true;
2600 void VerifyPropertyTreeValues(
2601 LayerTreeHostCommon::CalcDrawPropsMainInputs* inputs) {
2602 LayerIterator<Layer> it, end;
2603 for (it = LayerIterator<Layer>::Begin(inputs->render_surface_layer_list),
2604 end = LayerIterator<Layer>::End(inputs->render_surface_layer_list);
2605 it != end; ++it) {
2606 Layer* current_layer = *it;
2607 if (!it.represents_itself() || !current_layer->DrawsContent())
2608 continue;
2610 const bool visible_rects_match =
2611 ApproximatelyEqual(current_layer->visible_content_rect(),
2612 current_layer->visible_rect_from_property_trees());
2613 CHECK(visible_rects_match)
2614 << "expected: " << current_layer->visible_content_rect().ToString()
2615 << " actual: "
2616 << current_layer->visible_rect_from_property_trees().ToString();
2618 const bool draw_transforms_match = ApproximatelyEqual(
2619 current_layer->draw_transform(),
2620 DrawTransformFromPropertyTrees(current_layer,
2621 inputs->property_trees->transform_tree));
2622 CHECK(draw_transforms_match)
2623 << "expected: " << current_layer->draw_transform().ToString()
2624 << " actual: "
2625 << DrawTransformFromPropertyTrees(
2626 current_layer, inputs->property_trees->transform_tree)
2627 .ToString();
2629 const bool draw_opacities_match =
2630 current_layer->draw_opacity() ==
2631 DrawOpacityFromPropertyTrees(current_layer,
2632 inputs->property_trees->opacity_tree);
2633 CHECK(draw_opacities_match)
2634 << "expected: " << current_layer->draw_opacity() << " actual: "
2635 << DrawOpacityFromPropertyTrees(current_layer,
2636 inputs->property_trees->opacity_tree);
2640 void VerifyPropertyTreeValues(
2641 LayerTreeHostCommon::CalcDrawPropsImplInputs* inputs) {
2642 // TODO(enne): need to synchronize compositor thread changes
2643 // for animation and scrolling to the property trees before these
2644 // can be correct.
2647 enum PropertyTreeOption {
2648 BUILD_PROPERTY_TREES_IF_NEEDED,
2649 DONT_BUILD_PROPERTY_TREES
2652 template <typename LayerType, typename RenderSurfaceLayerListType>
2653 void CalculateDrawPropertiesAndVerify(LayerTreeHostCommon::CalcDrawPropsInputs<
2654 LayerType,
2655 RenderSurfaceLayerListType>* inputs,
2656 PropertyTreeOption property_tree_option) {
2657 typename LayerType::LayerListType dummy_layer_list;
2658 SubtreeGlobals<LayerType> globals;
2659 DataForRecursion<LayerType> data_for_recursion;
2661 ProcessCalcDrawPropsInputs(*inputs, &globals, &data_for_recursion);
2662 PreCalculateMetaInformationRecursiveData recursive_data;
2663 PreCalculateMetaInformationInternal(inputs->root_layer, &recursive_data);
2665 const bool should_measure_property_tree_performance =
2666 inputs->verify_property_trees &&
2667 (property_tree_option == BUILD_PROPERTY_TREES_IF_NEEDED);
2669 if (should_measure_property_tree_performance) {
2670 TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2671 "LayerTreeHostCommon::CalculateDrawProperties");
2673 ResetDrawProperties(inputs->root_layer);
2675 std::vector<AccumulatedSurfaceState<LayerType>> accumulated_surface_state;
2676 CalculateDrawPropertiesInternal<LayerType>(
2677 inputs->root_layer, globals, data_for_recursion,
2678 inputs->render_surface_layer_list, &dummy_layer_list,
2679 &accumulated_surface_state, inputs->current_render_surface_layer_list_id);
2681 if (should_measure_property_tree_performance) {
2682 TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2683 "LayerTreeHostCommon::CalculateDrawProperties");
2686 if (inputs->verify_property_trees) {
2687 typename LayerType::LayerListType update_layer_list;
2689 // For testing purposes, sometimes property trees need to be built on the
2690 // compositor thread, so this can't just switch on Layer vs LayerImpl,
2691 // even though in practice only the main thread builds property trees.
2692 switch (property_tree_option) {
2693 case BUILD_PROPERTY_TREES_IF_NEEDED: {
2694 // The translation from layer to property trees is an intermediate
2695 // state. We will eventually get these data passed directly to the
2696 // compositor.
2697 if (should_measure_property_tree_performance) {
2698 TRACE_EVENT_BEGIN0(
2699 TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2700 "LayerTreeHostCommon::ComputeVisibleRectsWithPropertyTrees");
2703 BuildPropertyTreesAndComputeVisibleRects(
2704 inputs->root_layer, inputs->page_scale_application_layer,
2705 inputs->page_scale_factor, inputs->device_scale_factor,
2706 gfx::Rect(inputs->device_viewport_size), inputs->device_transform,
2707 inputs->property_trees, &update_layer_list);
2709 if (should_measure_property_tree_performance) {
2710 TRACE_EVENT_END0(
2711 TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2712 "LayerTreeHostCommon::ComputeVisibleRectsWithPropertyTrees");
2715 break;
2717 case DONT_BUILD_PROPERTY_TREES: {
2718 TRACE_EVENT0(
2719 TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2720 "LayerTreeHostCommon::ComputeJustVisibleRectsWithPropertyTrees");
2721 ComputeVisibleRectsUsingPropertyTrees(
2722 inputs->root_layer, inputs->property_trees, &update_layer_list);
2723 break;
2727 VerifyPropertyTreeValues(inputs);
2730 // The dummy layer list should not have been used.
2731 DCHECK_EQ(0u, dummy_layer_list.size());
2732 // A root layer render_surface should always exist after
2733 // CalculateDrawProperties.
2734 DCHECK(inputs->root_layer->render_surface());
2737 void LayerTreeHostCommon::CalculateDrawProperties(
2738 CalcDrawPropsMainInputs* inputs) {
2739 UpdateRenderSurfaces(inputs->root_layer,
2740 inputs->can_render_to_separate_surface, gfx::Transform(),
2741 false);
2742 CalculateDrawPropertiesAndVerify(inputs, BUILD_PROPERTY_TREES_IF_NEEDED);
2745 void LayerTreeHostCommon::CalculateDrawProperties(
2746 CalcDrawPropsImplInputs* inputs) {
2747 CalculateDrawPropertiesAndVerify(inputs, DONT_BUILD_PROPERTY_TREES);
2750 void LayerTreeHostCommon::CalculateDrawProperties(
2751 CalcDrawPropsImplInputsForTesting* inputs) {
2752 CalculateDrawPropertiesAndVerify(inputs, BUILD_PROPERTY_TREES_IF_NEEDED);
2755 PropertyTrees* GetPropertyTrees(Layer* layer,
2756 PropertyTrees* trees_from_inputs) {
2757 return layer->layer_tree_host()->property_trees();
2760 PropertyTrees* GetPropertyTrees(LayerImpl* layer,
2761 PropertyTrees* trees_from_inputs) {
2762 return trees_from_inputs;
2765 } // namespace cc