Add ICU message format support
[chromium-blink-merge.git] / cc / trees / layer_tree_host_common.cc
blobbf6fbdca942413dae789d1c2d9ba5c833af9bc6d
1 // Copyright 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "cc/trees/layer_tree_host_common.h"
7 #include <algorithm>
9 #include "base/trace_event/trace_event.h"
10 #include "cc/base/math_util.h"
11 #include "cc/layers/heads_up_display_layer_impl.h"
12 #include "cc/layers/layer.h"
13 #include "cc/layers/layer_impl.h"
14 #include "cc/layers/layer_iterator.h"
15 #include "cc/layers/render_surface.h"
16 #include "cc/layers/render_surface_impl.h"
17 #include "cc/trees/draw_property_utils.h"
18 #include "cc/trees/layer_tree_host.h"
19 #include "cc/trees/layer_tree_impl.h"
20 #include "ui/gfx/geometry/rect_conversions.h"
21 #include "ui/gfx/geometry/vector2d_conversions.h"
22 #include "ui/gfx/transform.h"
23 #include "ui/gfx/transform_util.h"
25 namespace cc {
27 ScrollAndScaleSet::ScrollAndScaleSet()
28 : page_scale_delta(1.f), top_controls_delta(0.f) {
31 ScrollAndScaleSet::~ScrollAndScaleSet() {}
33 template <typename LayerType>
34 static gfx::Vector2dF GetEffectiveScrollDelta(LayerType* layer) {
35 // Layer's scroll offset can have an integer part and fractional part.
36 // Due to Blink's limitation, it only counter-scrolls the position-fixed
37 // layer using the integer part of Layer's scroll offset.
38 // CC scrolls the layer using the full scroll offset, so we have to
39 // add the ScrollCompensationAdjustment (fractional part of the scroll
40 // offset) to the effective scroll delta which is used to counter-scroll
41 // the position-fixed layer.
42 gfx::Vector2dF scroll_delta =
43 layer->ScrollDelta() + layer->ScrollCompensationAdjustment();
44 // The scroll parent's scroll delta is the amount we've scrolled on the
45 // compositor thread since the commit for this layer tree's source frame.
46 // we last reported to the main thread. I.e., it's the discrepancy between
47 // a scroll parent's scroll delta and offset, so we must add it here.
48 if (layer->scroll_parent())
49 scroll_delta += layer->scroll_parent()->ScrollDelta() +
50 layer->ScrollCompensationAdjustment();
51 return scroll_delta;
54 template <typename LayerType>
55 static gfx::ScrollOffset GetEffectiveCurrentScrollOffset(LayerType* layer) {
56 gfx::ScrollOffset offset = layer->CurrentScrollOffset();
57 // The scroll parent's total scroll offset (scroll offset + scroll delta)
58 // can't be used because its scroll offset has already been applied to the
59 // scroll children's positions by the main thread layer positioning code.
60 if (layer->scroll_parent())
61 offset += gfx::ScrollOffset(layer->scroll_parent()->ScrollDelta());
62 return offset;
65 inline gfx::Rect CalculateVisibleRectWithCachedLayerRect(
66 const gfx::Rect& target_surface_rect,
67 const gfx::Rect& layer_bound_rect,
68 const gfx::Rect& layer_rect_in_target_space,
69 const gfx::Transform& transform) {
70 if (layer_rect_in_target_space.IsEmpty())
71 return gfx::Rect();
73 // Is this layer fully contained within the target surface?
74 if (target_surface_rect.Contains(layer_rect_in_target_space))
75 return layer_bound_rect;
77 // If the layer doesn't fill up the entire surface, then find the part of
78 // the surface rect where the layer could be visible. This avoids trying to
79 // project surface rect points that are behind the projection point.
80 gfx::Rect minimal_surface_rect = target_surface_rect;
81 minimal_surface_rect.Intersect(layer_rect_in_target_space);
83 if (minimal_surface_rect.IsEmpty())
84 return gfx::Rect();
86 // Project the corners of the target surface rect into the layer space.
87 // This bounding rectangle may be larger than it needs to be (being
88 // axis-aligned), but is a reasonable filter on the space to consider.
89 // Non-invertible transforms will create an empty rect here.
91 gfx::Transform surface_to_layer(gfx::Transform::kSkipInitialization);
92 if (!transform.GetInverse(&surface_to_layer)) {
93 // Because we cannot use the surface bounds to determine what portion of
94 // the layer is visible, we must conservatively assume the full layer is
95 // visible.
96 return layer_bound_rect;
99 gfx::Rect layer_rect = MathUtil::ProjectEnclosingClippedRect(
100 surface_to_layer, minimal_surface_rect);
101 layer_rect.Intersect(layer_bound_rect);
102 return layer_rect;
105 gfx::Rect LayerTreeHostCommon::CalculateVisibleRect(
106 const gfx::Rect& target_surface_rect,
107 const gfx::Rect& layer_bound_rect,
108 const gfx::Transform& transform) {
109 gfx::Rect layer_in_surface_space =
110 MathUtil::MapEnclosingClippedRect(transform, layer_bound_rect);
111 return CalculateVisibleRectWithCachedLayerRect(
112 target_surface_rect, layer_bound_rect, layer_in_surface_space, transform);
115 template <typename LayerType>
116 static LayerType* NextTargetSurface(LayerType* layer) {
117 return layer->parent() ? layer->parent()->render_target() : 0;
120 // Given two layers, this function finds their respective render targets and,
121 // computes a change of basis translation. It does this by accumulating the
122 // translation components of the draw transforms of each target between the
123 // ancestor and descendant. These transforms must be 2D translations, and this
124 // requirement is enforced at every step.
125 template <typename LayerType>
126 static gfx::Vector2dF ComputeChangeOfBasisTranslation(
127 const LayerType& ancestor_layer,
128 const LayerType& descendant_layer) {
129 DCHECK(descendant_layer.HasAncestor(&ancestor_layer));
130 const LayerType* descendant_target = descendant_layer.render_target();
131 DCHECK(descendant_target);
132 const LayerType* ancestor_target = ancestor_layer.render_target();
133 DCHECK(ancestor_target);
135 gfx::Vector2dF translation;
136 for (const LayerType* target = descendant_target; target != ancestor_target;
137 target = NextTargetSurface(target)) {
138 const gfx::Transform& trans = target->render_surface()->draw_transform();
139 // Ensure that this translation is truly 2d.
140 DCHECK(trans.IsIdentityOrTranslation());
141 DCHECK_EQ(0.f, trans.matrix().get(2, 3));
142 translation += trans.To2dTranslation();
145 return translation;
148 enum TranslateRectDirection {
149 TRANSLATE_RECT_DIRECTION_TO_ANCESTOR,
150 TRANSLATE_RECT_DIRECTION_TO_DESCENDANT
153 template <typename LayerType>
154 static gfx::Rect TranslateRectToTargetSpace(const LayerType& ancestor_layer,
155 const LayerType& descendant_layer,
156 const gfx::Rect& rect,
157 TranslateRectDirection direction) {
158 gfx::Vector2dF translation = ComputeChangeOfBasisTranslation<LayerType>(
159 ancestor_layer, descendant_layer);
160 if (direction == TRANSLATE_RECT_DIRECTION_TO_DESCENDANT)
161 translation.Scale(-1.f);
162 return gfx::ToEnclosingRect(
163 gfx::RectF(rect.origin() + translation, rect.size()));
166 // Attempts to update the clip rects for the given layer. If the layer has a
167 // clip_parent, it may not inherit its immediate ancestor's clip.
168 template <typename LayerType>
169 static void UpdateClipRectsForClipChild(
170 const LayerType* layer,
171 gfx::Rect* clip_rect_in_parent_target_space,
172 bool* subtree_should_be_clipped) {
173 // If the layer has no clip_parent, or the ancestor is the same as its actual
174 // parent, then we don't need special clip rects. Bail now and leave the out
175 // parameters untouched.
176 const LayerType* clip_parent = layer->scroll_parent();
178 if (!clip_parent)
179 clip_parent = layer->clip_parent();
181 if (!clip_parent || clip_parent == layer->parent())
182 return;
184 // The root layer is never a clip child.
185 DCHECK(layer->parent());
187 // Grab the cached values.
188 *clip_rect_in_parent_target_space = clip_parent->clip_rect();
189 *subtree_should_be_clipped = clip_parent->is_clipped();
191 // We may have to project the clip rect into our parent's target space. Note,
192 // it must be our parent's target space, not ours. For one, we haven't
193 // computed our transforms, so we couldn't put it in our space yet even if we
194 // wanted to. But more importantly, this matches the expectations of
195 // CalculateDrawPropertiesInternal. If we, say, create a render surface, these
196 // clip rects will want to be in its target space, not ours.
197 if (clip_parent == layer->clip_parent()) {
198 *clip_rect_in_parent_target_space = TranslateRectToTargetSpace<LayerType>(
199 *clip_parent, *layer->parent(), *clip_rect_in_parent_target_space,
200 TRANSLATE_RECT_DIRECTION_TO_DESCENDANT);
201 } else {
202 // If we're being clipped by our scroll parent, we must translate through
203 // our common ancestor. This happens to be our parent, so it is sufficent to
204 // translate from our clip parent's space to the space of its ancestor (our
205 // parent).
206 *clip_rect_in_parent_target_space = TranslateRectToTargetSpace<LayerType>(
207 *layer->parent(), *clip_parent, *clip_rect_in_parent_target_space,
208 TRANSLATE_RECT_DIRECTION_TO_ANCESTOR);
212 // We collect an accumulated drawable content rect per render surface.
213 // Typically, a layer will contribute to only one surface, the surface
214 // associated with its render target. Clip children, however, may affect
215 // several surfaces since there may be several surfaces between the clip child
216 // and its parent.
218 // NB: we accumulate the layer's *clipped* drawable content rect.
219 template <typename LayerType>
220 struct AccumulatedSurfaceState {
221 explicit AccumulatedSurfaceState(LayerType* render_target)
222 : render_target(render_target) {}
224 // The accumulated drawable content rect for the surface associated with the
225 // given |render_target|.
226 gfx::Rect drawable_content_rect;
228 // The target owning the surface. (We hang onto the target rather than the
229 // surface so that we can DCHECK that the surface's draw transform is simply
230 // a translation when |render_target| reports that it has no unclipped
231 // descendants).
232 LayerType* render_target;
235 template <typename LayerType>
236 void UpdateAccumulatedSurfaceState(
237 LayerType* layer,
238 const gfx::Rect& drawable_content_rect,
239 std::vector<AccumulatedSurfaceState<LayerType>>*
240 accumulated_surface_state) {
241 if (IsRootLayer(layer))
242 return;
244 // We will apply our drawable content rect to the accumulated rects for all
245 // surfaces between us and |render_target| (inclusive). This is either our
246 // clip parent's target if we are a clip child, or else simply our parent's
247 // target. We use our parent's target because we're either the owner of a
248 // render surface and we'll want to add our rect to our *surface's* target, or
249 // we're not and our target is the same as our parent's. In both cases, the
250 // parent's target gives us what we want.
251 LayerType* render_target = layer->clip_parent()
252 ? layer->clip_parent()->render_target()
253 : layer->parent()->render_target();
255 // If the layer owns a surface, then the content rect is in the wrong space.
256 // Instead, we will use the surface's DrawableContentRect which is in target
257 // space as required.
258 gfx::Rect target_rect = drawable_content_rect;
259 if (layer->render_surface()) {
260 target_rect =
261 gfx::ToEnclosedRect(layer->render_surface()->DrawableContentRect());
264 if (render_target->is_clipped()) {
265 gfx::Rect clip_rect = render_target->clip_rect();
266 // If the layer has a clip parent, the clip rect may be in the wrong space,
267 // so we'll need to transform it before it is applied.
268 if (layer->clip_parent()) {
269 clip_rect = TranslateRectToTargetSpace<LayerType>(
270 *layer->clip_parent(), *layer, clip_rect,
271 TRANSLATE_RECT_DIRECTION_TO_DESCENDANT);
273 target_rect.Intersect(clip_rect);
276 // We must have at least one entry in the vector for the root.
277 DCHECK_LT(0ul, accumulated_surface_state->size());
279 typedef typename std::vector<AccumulatedSurfaceState<LayerType>>
280 AccumulatedSurfaceStateVector;
281 typedef typename AccumulatedSurfaceStateVector::reverse_iterator
282 AccumulatedSurfaceStateIterator;
283 AccumulatedSurfaceStateIterator current_state =
284 accumulated_surface_state->rbegin();
286 // Add this rect to the accumulated content rect for all surfaces until we
287 // reach the target surface.
288 bool found_render_target = false;
289 for (; current_state != accumulated_surface_state->rend(); ++current_state) {
290 current_state->drawable_content_rect.Union(target_rect);
292 // If we've reached |render_target| our work is done and we can bail.
293 if (current_state->render_target == render_target) {
294 found_render_target = true;
295 break;
298 // Transform rect from the current target's space to the next.
299 LayerType* current_target = current_state->render_target;
300 DCHECK(current_target->render_surface());
301 const gfx::Transform& current_draw_transform =
302 current_target->render_surface()->draw_transform();
304 // If we have unclipped descendants, the draw transform is a translation.
305 DCHECK_IMPLIES(current_target->num_unclipped_descendants(),
306 current_draw_transform.IsIdentityOrTranslation());
308 target_rect = gfx::ToEnclosingRect(
309 MathUtil::MapClippedRect(current_draw_transform, target_rect));
312 // It is an error to not reach |render_target|. If this happens, it means that
313 // either the clip parent is not an ancestor of the clip child or the surface
314 // state vector is empty, both of which should be impossible.
315 DCHECK(found_render_target);
318 template <typename LayerType> static inline bool IsRootLayer(LayerType* layer) {
319 return !layer->parent();
322 template <typename LayerType>
323 static inline bool LayerIsInExisting3DRenderingContext(LayerType* layer) {
324 return layer->Is3dSorted() && layer->parent() &&
325 layer->parent()->Is3dSorted() &&
326 (layer->parent()->sorting_context_id() == layer->sorting_context_id());
329 template <typename LayerType>
330 static bool IsRootLayerOfNewRenderingContext(LayerType* layer) {
331 if (layer->parent())
332 return !layer->parent()->Is3dSorted() && layer->Is3dSorted();
334 return layer->Is3dSorted();
337 template <typename LayerType>
338 static bool IsLayerBackFaceVisible(LayerType* layer) {
339 // The current W3C spec on CSS transforms says that backface visibility should
340 // be determined differently depending on whether the layer is in a "3d
341 // rendering context" or not. For Chromium code, we can determine whether we
342 // are in a 3d rendering context by checking if the parent preserves 3d.
344 if (LayerIsInExisting3DRenderingContext(layer))
345 return layer->draw_transform().IsBackFaceVisible();
347 // In this case, either the layer establishes a new 3d rendering context, or
348 // is not in a 3d rendering context at all.
349 return layer->transform().IsBackFaceVisible();
352 template <typename LayerType>
353 static bool IsSurfaceBackFaceVisible(LayerType* layer,
354 const gfx::Transform& draw_transform) {
355 if (LayerIsInExisting3DRenderingContext(layer))
356 return draw_transform.IsBackFaceVisible();
358 if (IsRootLayerOfNewRenderingContext(layer))
359 return layer->transform().IsBackFaceVisible();
361 // If the render_surface is not part of a new or existing rendering context,
362 // then the layers that contribute to this surface will decide back-face
363 // visibility for themselves.
364 return false;
367 template <typename LayerType>
368 static inline bool LayerClipsSubtree(LayerType* layer) {
369 return layer->masks_to_bounds() || layer->mask_layer();
372 template <typename LayerType>
373 static gfx::Rect CalculateVisibleLayerRect(
374 LayerType* layer,
375 const gfx::Rect& clip_rect_of_target_surface_in_target_space,
376 const gfx::Rect& layer_rect_in_target_space) {
377 DCHECK(layer->render_target());
379 // Nothing is visible if the layer bounds are empty.
380 if (!layer->DrawsContent() || layer->bounds().IsEmpty() ||
381 layer->drawable_content_rect().IsEmpty())
382 return gfx::Rect();
384 // Compute visible bounds in target surface space.
385 gfx::Rect visible_rect_in_target_surface_space =
386 layer->drawable_content_rect();
388 if (layer->render_target()->render_surface()->is_clipped()) {
389 // The |layer| L has a target T which owns a surface Ts. The surface Ts
390 // has a target TsT.
392 // In this case the target surface Ts does clip the layer L that contributes
393 // to it. So, we have to convert the clip rect of Ts from the target space
394 // of Ts (that is the space of TsT), to the current render target's space
395 // (that is the space of T). This conversion is done outside this function
396 // so that it can be cached instead of computing it redundantly for every
397 // layer.
398 visible_rect_in_target_surface_space.Intersect(
399 clip_rect_of_target_surface_in_target_space);
402 if (visible_rect_in_target_surface_space.IsEmpty())
403 return gfx::Rect();
405 return CalculateVisibleRectWithCachedLayerRect(
406 visible_rect_in_target_surface_space, gfx::Rect(layer->bounds()),
407 layer_rect_in_target_space, layer->draw_transform());
410 static inline bool TransformToParentIsKnown(LayerImpl* layer) { return true; }
412 static inline bool TransformToParentIsKnown(Layer* layer) {
413 return !layer->HasPotentiallyRunningTransformAnimation();
416 static inline bool TransformToScreenIsKnown(LayerImpl* layer) { return true; }
418 static inline bool TransformToScreenIsKnown(Layer* layer) {
419 return !layer->screen_space_transform_is_animating();
422 template <typename LayerType>
423 static bool LayerShouldBeSkipped(LayerType* layer, bool layer_is_drawn) {
424 // Layers can be skipped if any of these conditions are met.
425 // - is not drawn due to it or one of its ancestors being hidden (or having
426 // no copy requests).
427 // - does not draw content.
428 // - is transparent.
429 // - has empty bounds
430 // - the layer is not double-sided, but its back face is visible.
432 // Some additional conditions need to be computed at a later point after the
433 // recursion is finished.
434 // - the intersection of render_surface content and layer clip_rect is empty
435 // - the visible_layer_rect is empty
437 // Note, if the layer should not have been drawn due to being fully
438 // transparent, we would have skipped the entire subtree and never made it
439 // into this function, so it is safe to omit this check here.
441 if (!layer_is_drawn)
442 return true;
444 if (!layer->DrawsContent() || layer->bounds().IsEmpty())
445 return true;
447 LayerType* backface_test_layer = layer;
448 if (layer->use_parent_backface_visibility()) {
449 DCHECK(layer->parent());
450 DCHECK(!layer->parent()->use_parent_backface_visibility());
451 backface_test_layer = layer->parent();
454 // The layer should not be drawn if (1) it is not double-sided and (2) the
455 // back of the layer is known to be facing the screen.
456 if (!backface_test_layer->double_sided() &&
457 TransformToScreenIsKnown(backface_test_layer) &&
458 IsLayerBackFaceVisible(backface_test_layer))
459 return true;
461 return false;
464 template <typename LayerType>
465 static bool HasInvertibleOrAnimatedTransform(LayerType* layer) {
466 return layer->transform_is_invertible() ||
467 layer->HasPotentiallyRunningTransformAnimation();
470 static inline bool SubtreeShouldBeSkipped(LayerImpl* layer,
471 bool layer_is_drawn) {
472 // If the layer transform is not invertible, it should not be drawn.
473 // TODO(ajuma): Correctly process subtrees with singular transform for the
474 // case where we may animate to a non-singular transform and wish to
475 // pre-raster.
476 if (!HasInvertibleOrAnimatedTransform(layer))
477 return true;
479 // When we need to do a readback/copy of a layer's output, we can not skip
480 // it or any of its ancestors.
481 if (layer->draw_properties().layer_or_descendant_has_copy_request)
482 return false;
484 // We cannot skip the the subtree if a descendant has a wheel or touch handler
485 // or the hit testing code will break (it requires fresh transforms, etc).
486 if (layer->draw_properties().layer_or_descendant_has_input_handler)
487 return false;
489 // If the layer is not drawn, then skip it and its subtree.
490 if (!layer_is_drawn)
491 return true;
493 // If layer is on the pending tree and opacity is being animated then
494 // this subtree can't be skipped as we need to create, prioritize and
495 // include tiles for this layer when deciding if tree can be activated.
496 if (layer->layer_tree_impl()->IsPendingTree() &&
497 layer->HasPotentiallyRunningOpacityAnimation())
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() &&
509 !layer->HasPotentiallyRunningTransformAnimation())
510 return true;
512 // When we need to do a readback/copy of a layer's output, we can not skip
513 // it or any of its ancestors.
514 if (layer->draw_properties().layer_or_descendant_has_copy_request)
515 return false;
517 // We cannot skip the the subtree if a descendant has a wheel or touch handler
518 // or the hit testing code will break (it requires fresh transforms, etc).
519 if (layer->draw_properties().layer_or_descendant_has_input_handler)
520 return false;
522 // If the layer is not drawn, then skip it and its subtree.
523 if (!layer_is_drawn)
524 return true;
526 // If the opacity is being animated then the opacity on the main thread is
527 // unreliable (since the impl thread may be using a different opacity), so it
528 // should not be trusted.
529 // In particular, it should not cause the subtree to be skipped.
530 // Similarly, for layers that might animate opacity using an impl-only
531 // animation, their subtree should also not be skipped.
532 return !layer->opacity() && !layer->HasPotentiallyRunningOpacityAnimation() &&
533 !layer->OpacityCanAnimateOnImplThread();
536 static inline void SavePaintPropertiesLayer(LayerImpl* layer) {}
538 static inline void SavePaintPropertiesLayer(Layer* layer) {
539 layer->SavePaintProperties();
541 if (layer->mask_layer())
542 layer->mask_layer()->SavePaintProperties();
543 if (layer->replica_layer() && layer->replica_layer()->mask_layer())
544 layer->replica_layer()->mask_layer()->SavePaintProperties();
547 static bool SubtreeShouldRenderToSeparateSurface(
548 Layer* layer,
549 bool axis_aligned_with_respect_to_parent) {
551 // A layer and its descendants should render onto a new RenderSurfaceImpl if
552 // any of these rules hold:
555 // The root layer owns a render surface, but it never acts as a contributing
556 // surface to another render target. Compositor features that are applied via
557 // a contributing surface can not be applied to the root layer. In order to
558 // use these effects, another child of the root would need to be introduced
559 // in order to act as a contributing surface to the root layer's surface.
560 bool is_root = IsRootLayer(layer);
562 // If the layer uses a mask.
563 if (layer->mask_layer()) {
564 DCHECK(!is_root);
565 return true;
568 // If the layer has a reflection.
569 if (layer->replica_layer()) {
570 DCHECK(!is_root);
571 return true;
574 // If the layer uses a CSS filter.
575 if (!layer->filters().IsEmpty() || !layer->background_filters().IsEmpty()) {
576 DCHECK(!is_root);
577 return true;
580 // If the layer will use a CSS filter. In this case, the animation
581 // will start and add a filter to this layer, so it needs a surface.
582 if (layer->HasPotentiallyRunningFilterAnimation()) {
583 DCHECK(!is_root);
584 return true;
587 int num_descendants_that_draw_content =
588 layer->NumDescendantsThatDrawContent();
590 // If the layer flattens its subtree, but it is treated as a 3D object by its
591 // parent (i.e. parent participates in a 3D rendering context).
592 if (LayerIsInExisting3DRenderingContext(layer) &&
593 layer->should_flatten_transform() &&
594 num_descendants_that_draw_content > 0) {
595 TRACE_EVENT_INSTANT0(
596 "cc",
597 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface flattening",
598 TRACE_EVENT_SCOPE_THREAD);
599 DCHECK(!is_root);
600 return true;
603 // If the layer has blending.
604 // TODO(rosca): this is temporary, until blending is implemented for other
605 // types of quads than RenderPassDrawQuad. Layers having descendants that draw
606 // content will still create a separate rendering surface.
607 if (!layer->uses_default_blend_mode()) {
608 TRACE_EVENT_INSTANT0(
609 "cc",
610 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface blending",
611 TRACE_EVENT_SCOPE_THREAD);
612 DCHECK(!is_root);
613 return true;
616 // If the layer clips its descendants but it is not axis-aligned with respect
617 // to its parent.
618 bool layer_clips_external_content =
619 LayerClipsSubtree(layer) || layer->HasDelegatedContent();
620 if (layer_clips_external_content && !axis_aligned_with_respect_to_parent &&
621 num_descendants_that_draw_content > 0) {
622 TRACE_EVENT_INSTANT0(
623 "cc",
624 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface clipping",
625 TRACE_EVENT_SCOPE_THREAD);
626 DCHECK(!is_root);
627 return true;
630 // If the layer has some translucency and does not have a preserves-3d
631 // transform style. This condition only needs a render surface if two or more
632 // layers in the subtree overlap. But checking layer overlaps is unnecessarily
633 // costly so instead we conservatively create a surface whenever at least two
634 // layers draw content for this subtree.
635 bool at_least_two_layers_in_subtree_draw_content =
636 num_descendants_that_draw_content > 0 &&
637 (layer->DrawsContent() || num_descendants_that_draw_content > 1);
639 if (layer->opacity() != 1.f && layer->should_flatten_transform() &&
640 at_least_two_layers_in_subtree_draw_content) {
641 TRACE_EVENT_INSTANT0(
642 "cc",
643 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface opacity",
644 TRACE_EVENT_SCOPE_THREAD);
645 DCHECK(!is_root);
646 return true;
649 // The root layer should always have a render_surface.
650 if (is_root)
651 return true;
654 // These are allowed on the root surface, as they don't require the surface to
655 // be used as a contributing surface in order to apply correctly.
658 // If the layer has isolation.
659 // TODO(rosca): to be optimized - create separate rendering surface only when
660 // the blending descendants might have access to the content behind this layer
661 // (layer has transparent background or descendants overflow).
662 // https://code.google.com/p/chromium/issues/detail?id=301738
663 if (layer->is_root_for_isolated_group()) {
664 TRACE_EVENT_INSTANT0(
665 "cc",
666 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface isolation",
667 TRACE_EVENT_SCOPE_THREAD);
668 return true;
671 // If we force it.
672 if (layer->force_render_surface())
673 return true;
675 // If we'll make a copy of the layer's contents.
676 if (layer->HasCopyRequest())
677 return true;
679 return false;
682 // This function returns a translation matrix that can be applied on a vector
683 // that's in the layer's target surface coordinate, while the position offset is
684 // specified in some ancestor layer's coordinate.
685 template <typename LayerType>
686 gfx::Transform ComputeSizeDeltaCompensation(
687 LayerType* layer,
688 LayerType* container,
689 const gfx::Vector2dF& position_offset) {
690 gfx::Transform result_transform;
692 // To apply a translate in the container's layer space,
693 // the following steps need to be done:
694 // Step 1a. transform from target surface space to the container's target
695 // surface space
696 // Step 1b. transform from container's target surface space to the
697 // container's layer space
698 // Step 2. apply the compensation
699 // Step 3. transform back to target surface space
701 gfx::Transform target_surface_space_to_container_layer_space;
702 // Calculate step 1a
703 LayerType* container_target_surface = container->render_target();
704 for (LayerType* current_target_surface = NextTargetSurface(layer);
705 current_target_surface &&
706 current_target_surface != container_target_surface;
707 current_target_surface = NextTargetSurface(current_target_surface)) {
708 // Note: Concat is used here to convert the result coordinate space from
709 // current render surface to the next render surface.
710 target_surface_space_to_container_layer_space.ConcatTransform(
711 current_target_surface->render_surface()->draw_transform());
713 // Calculate step 1b
714 gfx::Transform container_layer_space_to_container_target_surface_space =
715 container->draw_transform();
716 gfx::Transform container_target_surface_space_to_container_layer_space;
717 if (container_layer_space_to_container_target_surface_space.GetInverse(
718 &container_target_surface_space_to_container_layer_space)) {
719 // Note: Again, Concat is used to conver the result coordinate space from
720 // the container render surface to the container layer.
721 target_surface_space_to_container_layer_space.ConcatTransform(
722 container_target_surface_space_to_container_layer_space);
725 // Apply step 3
726 gfx::Transform container_layer_space_to_target_surface_space;
727 if (target_surface_space_to_container_layer_space.GetInverse(
728 &container_layer_space_to_target_surface_space)) {
729 result_transform.PreconcatTransform(
730 container_layer_space_to_target_surface_space);
731 } else {
732 // TODO(shawnsingh): A non-invertible matrix could still make meaningful
733 // projection. For example ScaleZ(0) is non-invertible but the layer is
734 // still visible.
735 return gfx::Transform();
738 // Apply step 2
739 result_transform.Translate(position_offset.x(), position_offset.y());
741 // Apply step 1
742 result_transform.PreconcatTransform(
743 target_surface_space_to_container_layer_space);
745 return result_transform;
748 template <typename LayerType>
749 void ApplyPositionAdjustment(
750 LayerType* layer,
751 LayerType* container,
752 const gfx::Transform& scroll_compensation,
753 gfx::Transform* combined_transform) {
754 if (!layer->position_constraint().is_fixed_position())
755 return;
757 // Special case: this layer is a composited fixed-position layer; we need to
758 // explicitly compensate for all ancestors' nonzero scroll_deltas to keep
759 // this layer fixed correctly.
760 // Note carefully: this is Concat, not Preconcat
761 // (current_scroll_compensation * combined_transform).
762 combined_transform->ConcatTransform(scroll_compensation);
764 // For right-edge or bottom-edge anchored fixed position layers,
765 // the layer should relocate itself if the container changes its size.
766 bool fixed_to_right_edge =
767 layer->position_constraint().is_fixed_to_right_edge();
768 bool fixed_to_bottom_edge =
769 layer->position_constraint().is_fixed_to_bottom_edge();
770 gfx::Vector2dF position_offset = container->FixedContainerSizeDelta();
771 position_offset.set_x(fixed_to_right_edge ? position_offset.x() : 0);
772 position_offset.set_y(fixed_to_bottom_edge ? position_offset.y() : 0);
773 if (position_offset.IsZero())
774 return;
776 // Note: Again, this is Concat. The compensation matrix will be applied on
777 // the vector in target surface space.
778 combined_transform->ConcatTransform(
779 ComputeSizeDeltaCompensation(layer, container, position_offset));
782 template <typename LayerType>
783 gfx::Transform ComputeScrollCompensationForThisLayer(
784 LayerType* scrolling_layer,
785 const gfx::Transform& parent_matrix,
786 const gfx::Vector2dF& scroll_delta) {
787 // For every layer that has non-zero scroll_delta, we have to compute a
788 // transform that can undo the scroll_delta translation. In particular, we
789 // want this matrix to premultiply a fixed-position layer's parent_matrix, so
790 // we design this transform in three steps as follows. The steps described
791 // here apply from right-to-left, so Step 1 would be the right-most matrix:
793 // Step 1. transform from target surface space to the exact space where
794 // scroll_delta is actually applied.
795 // -- this is inverse of parent_matrix
796 // Step 2. undo the scroll_delta
797 // -- this is just a translation by scroll_delta.
798 // Step 3. transform back to target surface space.
799 // -- this transform is the parent_matrix
801 // These steps create a matrix that both start and end in target surface
802 // space. So this matrix can pre-multiply any fixed-position layer's
803 // draw_transform to undo the scroll_deltas -- as long as that fixed position
804 // layer is fixed onto the same render_target as this scrolling_layer.
807 gfx::Transform scroll_compensation_for_this_layer = parent_matrix; // Step 3
808 scroll_compensation_for_this_layer.Translate(
809 scroll_delta.x(),
810 scroll_delta.y()); // Step 2
812 gfx::Transform inverse_parent_matrix(gfx::Transform::kSkipInitialization);
813 if (!parent_matrix.GetInverse(&inverse_parent_matrix)) {
814 // TODO(shawnsingh): Either we need to handle uninvertible transforms
815 // here, or DCHECK that the transform is invertible.
817 scroll_compensation_for_this_layer.PreconcatTransform(
818 inverse_parent_matrix); // Step 1
819 return scroll_compensation_for_this_layer;
822 template <typename LayerType>
823 gfx::Transform ComputeScrollCompensationMatrixForChildren(
824 LayerType* layer,
825 const gfx::Transform& parent_matrix,
826 const gfx::Transform& current_scroll_compensation_matrix,
827 const gfx::Vector2dF& scroll_delta) {
828 // "Total scroll compensation" is the transform needed to cancel out all
829 // scroll_delta translations that occurred since the nearest container layer,
830 // even if there are render_surfaces in-between.
832 // There are some edge cases to be aware of, that are not explicit in the
833 // code:
834 // - A layer that is both a fixed-position and container should not be its
835 // own container, instead, that means it is fixed to an ancestor, and is a
836 // container for any fixed-position descendants.
837 // - A layer that is a fixed-position container and has a render_surface
838 // should behave the same as a container without a render_surface, the
839 // render_surface is irrelevant in that case.
840 // - A layer that does not have an explicit container is simply fixed to the
841 // viewport. (i.e. the root render_surface.)
842 // - If the fixed-position layer has its own render_surface, then the
843 // render_surface is the one who gets fixed.
845 // This function needs to be called AFTER layers create their own
846 // render_surfaces.
849 // Scroll compensation restarts from identity under two possible conditions:
850 // - the current layer is a container for fixed-position descendants
851 // - the current layer is fixed-position itself, so any fixed-position
852 // descendants are positioned with respect to this layer. Thus, any
853 // fixed position descendants only need to compensate for scrollDeltas
854 // that occur below this layer.
855 bool current_layer_resets_scroll_compensation_for_descendants =
856 layer->IsContainerForFixedPositionLayers() ||
857 layer->position_constraint().is_fixed_position();
859 // Avoid the overheads (including stack allocation and matrix
860 // initialization/copy) if we know that the scroll compensation doesn't need
861 // to be reset or adjusted.
862 if (!current_layer_resets_scroll_compensation_for_descendants &&
863 scroll_delta.IsZero() && !layer->render_surface())
864 return current_scroll_compensation_matrix;
866 // Start as identity matrix.
867 gfx::Transform next_scroll_compensation_matrix;
869 // If this layer does not reset scroll compensation, then it inherits the
870 // existing scroll compensations.
871 if (!current_layer_resets_scroll_compensation_for_descendants)
872 next_scroll_compensation_matrix = current_scroll_compensation_matrix;
874 // If the current layer has a non-zero scroll_delta, then we should compute
875 // its local scroll compensation and accumulate it to the
876 // next_scroll_compensation_matrix.
877 if (!scroll_delta.IsZero()) {
878 gfx::Transform scroll_compensation_for_this_layer =
879 ComputeScrollCompensationForThisLayer(
880 layer, parent_matrix, scroll_delta);
881 next_scroll_compensation_matrix.PreconcatTransform(
882 scroll_compensation_for_this_layer);
885 // If the layer created its own render_surface, we have to adjust
886 // next_scroll_compensation_matrix. The adjustment allows us to continue
887 // using the scroll compensation on the next surface.
888 // Step 1 (right-most in the math): transform from the new surface to the
889 // original ancestor surface
890 // Step 2: apply the scroll compensation
891 // Step 3: transform back to the new surface.
892 if (layer->render_surface() &&
893 !next_scroll_compensation_matrix.IsIdentity()) {
894 gfx::Transform inverse_surface_draw_transform(
895 gfx::Transform::kSkipInitialization);
896 if (!layer->render_surface()->draw_transform().GetInverse(
897 &inverse_surface_draw_transform)) {
898 // TODO(shawnsingh): Either we need to handle uninvertible transforms
899 // here, or DCHECK that the transform is invertible.
901 next_scroll_compensation_matrix =
902 inverse_surface_draw_transform * next_scroll_compensation_matrix *
903 layer->render_surface()->draw_transform();
906 return next_scroll_compensation_matrix;
909 template <typename LayerType>
910 static inline void UpdateLayerScaleDrawProperties(
911 LayerType* layer,
912 float maximum_animation_contents_scale,
913 float starting_animation_contents_scale) {
914 layer->draw_properties().maximum_animation_contents_scale =
915 maximum_animation_contents_scale;
916 layer->draw_properties().starting_animation_contents_scale =
917 starting_animation_contents_scale;
920 static inline void CalculateAnimationContentsScale(
921 Layer* layer,
922 bool ancestor_is_animating_scale,
923 float ancestor_maximum_animation_contents_scale,
924 const gfx::Transform& parent_transform,
925 const gfx::Transform& combined_transform,
926 bool* combined_is_animating_scale,
927 float* combined_maximum_animation_contents_scale,
928 float* combined_starting_animation_contents_scale) {
929 *combined_is_animating_scale = false;
930 *combined_maximum_animation_contents_scale = 0.f;
931 *combined_starting_animation_contents_scale = 0.f;
934 static inline void CalculateAnimationContentsScale(
935 LayerImpl* layer,
936 bool ancestor_is_animating_scale,
937 float ancestor_maximum_animation_contents_scale,
938 const gfx::Transform& ancestor_transform,
939 const gfx::Transform& combined_transform,
940 bool* combined_is_animating_scale,
941 float* combined_maximum_animation_contents_scale,
942 float* combined_starting_animation_contents_scale) {
943 if (ancestor_is_animating_scale &&
944 ancestor_maximum_animation_contents_scale == 0.f) {
945 // We've already failed to compute a maximum animated scale at an
946 // ancestor, so we'll continue to fail.
947 *combined_maximum_animation_contents_scale = 0.f;
948 *combined_starting_animation_contents_scale = 0.f;
949 *combined_is_animating_scale = true;
950 return;
953 if (!combined_transform.IsScaleOrTranslation()) {
954 // Computing maximum animated scale in the presence of
955 // non-scale/translation transforms isn't supported.
956 *combined_maximum_animation_contents_scale = 0.f;
957 *combined_starting_animation_contents_scale = 0.f;
958 *combined_is_animating_scale = true;
959 return;
962 // We currently only support computing maximum scale for combinations of
963 // scales and translations. We treat all non-translations as potentially
964 // affecting scale. Animations that include non-translation/scale components
965 // will cause the computation of MaximumScale below to fail.
966 bool layer_is_animating_scale = !layer->HasOnlyTranslationTransforms();
968 if (!layer_is_animating_scale && !ancestor_is_animating_scale) {
969 *combined_maximum_animation_contents_scale = 0.f;
970 *combined_starting_animation_contents_scale = 0.f;
971 *combined_is_animating_scale = false;
972 return;
975 // We don't attempt to accumulate animation scale from multiple nodes,
976 // because of the risk of significant overestimation. For example, one node
977 // may be increasing scale from 1 to 10 at the same time as a descendant is
978 // decreasing scale from 10 to 1. Naively combining these scales would produce
979 // a scale of 100.
980 if (layer_is_animating_scale && ancestor_is_animating_scale) {
981 *combined_maximum_animation_contents_scale = 0.f;
982 *combined_starting_animation_contents_scale = 0.f;
983 *combined_is_animating_scale = true;
984 return;
987 // At this point, we know either the layer or an ancestor, but not both,
988 // is animating scale.
989 *combined_is_animating_scale = true;
990 if (!layer_is_animating_scale) {
991 gfx::Vector2dF layer_transform_scales =
992 MathUtil::ComputeTransform2dScaleComponents(layer->transform(), 0.f);
993 *combined_maximum_animation_contents_scale =
994 ancestor_maximum_animation_contents_scale *
995 std::max(layer_transform_scales.x(), layer_transform_scales.y());
996 *combined_starting_animation_contents_scale =
997 *combined_maximum_animation_contents_scale;
998 return;
1001 float layer_maximum_animated_scale = 0.f;
1002 float layer_start_animated_scale = 0.f;
1003 if (!layer->MaximumTargetScale(&layer_maximum_animated_scale)) {
1004 *combined_maximum_animation_contents_scale = 0.f;
1005 return;
1007 if (!layer->AnimationStartScale(&layer_start_animated_scale)) {
1008 *combined_starting_animation_contents_scale = 0.f;
1009 return;
1012 gfx::Vector2dF ancestor_transform_scales =
1013 MathUtil::ComputeTransform2dScaleComponents(ancestor_transform, 0.f);
1014 float max_scale_xy =
1015 std::max(ancestor_transform_scales.x(), ancestor_transform_scales.y());
1016 *combined_maximum_animation_contents_scale =
1017 layer_maximum_animated_scale * max_scale_xy;
1018 *combined_starting_animation_contents_scale =
1019 layer_start_animated_scale * max_scale_xy;
1022 template <typename LayerTypePtr>
1023 static inline void MarkLayerWithRenderSurfaceLayerListId(
1024 LayerTypePtr layer,
1025 int current_render_surface_layer_list_id) {
1026 layer->draw_properties().last_drawn_render_surface_layer_list_id =
1027 current_render_surface_layer_list_id;
1028 layer->set_layer_or_descendant_is_drawn(
1029 !!current_render_surface_layer_list_id);
1032 template <typename LayerTypePtr>
1033 static inline void MarkMasksWithRenderSurfaceLayerListId(
1034 LayerTypePtr layer,
1035 int current_render_surface_layer_list_id) {
1036 if (layer->mask_layer()) {
1037 MarkLayerWithRenderSurfaceLayerListId(layer->mask_layer(),
1038 current_render_surface_layer_list_id);
1040 if (layer->replica_layer() && layer->replica_layer()->mask_layer()) {
1041 MarkLayerWithRenderSurfaceLayerListId(layer->replica_layer()->mask_layer(),
1042 current_render_surface_layer_list_id);
1046 template <typename LayerListType>
1047 static inline void MarkLayerListWithRenderSurfaceLayerListId(
1048 LayerListType* layer_list,
1049 int current_render_surface_layer_list_id) {
1050 for (typename LayerListType::iterator it = layer_list->begin();
1051 it != layer_list->end();
1052 ++it) {
1053 MarkLayerWithRenderSurfaceLayerListId(*it,
1054 current_render_surface_layer_list_id);
1055 MarkMasksWithRenderSurfaceLayerListId(*it,
1056 current_render_surface_layer_list_id);
1060 template <typename LayerType>
1061 static inline void RemoveSurfaceForEarlyExit(
1062 LayerType* layer_to_remove,
1063 typename LayerType::RenderSurfaceListType* render_surface_layer_list) {
1064 DCHECK(layer_to_remove->render_surface());
1065 // Technically, we know that the layer we want to remove should be
1066 // at the back of the render_surface_layer_list. However, we have had
1067 // bugs before that added unnecessary layers here
1068 // (https://bugs.webkit.org/show_bug.cgi?id=74147), but that causes
1069 // things to crash. So here we proactively remove any additional
1070 // layers from the end of the list.
1071 while (render_surface_layer_list->back() != layer_to_remove) {
1072 MarkLayerListWithRenderSurfaceLayerListId(
1073 &render_surface_layer_list->back()->render_surface()->layer_list(), 0);
1074 MarkLayerWithRenderSurfaceLayerListId(render_surface_layer_list->back(), 0);
1076 render_surface_layer_list->back()->ClearRenderSurfaceLayerList();
1077 render_surface_layer_list->pop_back();
1079 DCHECK_EQ(render_surface_layer_list->back(), layer_to_remove);
1080 MarkLayerListWithRenderSurfaceLayerListId(
1081 &layer_to_remove->render_surface()->layer_list(), 0);
1082 MarkLayerWithRenderSurfaceLayerListId(layer_to_remove, 0);
1083 render_surface_layer_list->pop_back();
1084 layer_to_remove->ClearRenderSurfaceLayerList();
1087 struct PreCalculateMetaInformationRecursiveData {
1088 size_t num_unclipped_descendants;
1089 int num_layer_or_descendants_with_copy_request;
1090 int num_layer_or_descendants_with_input_handler;
1092 PreCalculateMetaInformationRecursiveData()
1093 : num_unclipped_descendants(0),
1094 num_layer_or_descendants_with_copy_request(0),
1095 num_layer_or_descendants_with_input_handler(0) {}
1097 void Merge(const PreCalculateMetaInformationRecursiveData& data) {
1098 num_layer_or_descendants_with_copy_request +=
1099 data.num_layer_or_descendants_with_copy_request;
1100 num_layer_or_descendants_with_input_handler +=
1101 data.num_layer_or_descendants_with_input_handler;
1102 num_unclipped_descendants += data.num_unclipped_descendants;
1106 static void ValidateRenderSurface(LayerImpl* layer) {
1107 // This test verifies that there are no cases where a LayerImpl needs
1108 // a render surface, but doesn't have one.
1109 if (layer->render_surface())
1110 return;
1112 DCHECK(layer->filters().IsEmpty()) << "layer: " << layer->id();
1113 DCHECK(layer->background_filters().IsEmpty()) << "layer: " << layer->id();
1114 DCHECK(!layer->mask_layer()) << "layer: " << layer->id();
1115 DCHECK(!layer->replica_layer()) << "layer: " << layer->id();
1116 DCHECK(!IsRootLayer(layer)) << "layer: " << layer->id();
1117 DCHECK(!layer->is_root_for_isolated_group()) << "layer: " << layer->id();
1118 DCHECK(!layer->HasCopyRequest()) << "layer: " << layer->id();
1121 static void ValidateRenderSurface(Layer* layer) {
1124 static bool IsMetaInformationRecomputationNeeded(Layer* layer) {
1125 return layer->layer_tree_host()->needs_meta_info_recomputation();
1128 static void UpdateMetaInformationSequenceNumber(Layer* root_layer) {
1129 root_layer->layer_tree_host()->IncrementMetaInformationSequenceNumber();
1132 static void UpdateMetaInformationSequenceNumber(LayerImpl* root_layer) {
1135 // Recursively walks the layer tree(if needed) to compute any information
1136 // that is needed before doing the main recursion.
1137 static void PreCalculateMetaInformationInternal(
1138 Layer* layer,
1139 PreCalculateMetaInformationRecursiveData* recursive_data) {
1140 ValidateRenderSurface(layer);
1142 layer->set_sorted_for_recursion(false);
1143 layer->draw_properties().has_child_with_a_scroll_parent = false;
1144 layer->set_layer_or_descendant_is_drawn(false);
1145 layer->set_visited(false);
1147 if (!HasInvertibleOrAnimatedTransform(layer)) {
1148 // Layers with singular transforms should not be drawn, the whole subtree
1149 // can be skipped.
1150 return;
1153 if (!IsMetaInformationRecomputationNeeded(layer)) {
1154 DCHECK(IsRootLayer(layer));
1155 return;
1158 if (layer->clip_parent())
1159 recursive_data->num_unclipped_descendants++;
1161 layer->set_num_children_with_scroll_parent(0);
1162 for (size_t i = 0; i < layer->children().size(); ++i) {
1163 Layer* child_layer = layer->child_at(i);
1165 PreCalculateMetaInformationRecursiveData data_for_child;
1166 PreCalculateMetaInformationInternal(child_layer, &data_for_child);
1168 if (child_layer->scroll_parent()) {
1169 layer->draw_properties().has_child_with_a_scroll_parent = true;
1170 layer->set_num_children_with_scroll_parent(
1171 layer->num_children_with_scroll_parent() + 1);
1173 recursive_data->Merge(data_for_child);
1176 if (layer->clip_children()) {
1177 size_t num_clip_children = layer->clip_children()->size();
1178 DCHECK_GE(recursive_data->num_unclipped_descendants, num_clip_children);
1179 recursive_data->num_unclipped_descendants -= num_clip_children;
1182 if (layer->HasCopyRequest())
1183 recursive_data->num_layer_or_descendants_with_copy_request++;
1185 if (!layer->touch_event_handler_region().IsEmpty() ||
1186 layer->have_wheel_event_handlers())
1187 recursive_data->num_layer_or_descendants_with_input_handler++;
1189 layer->draw_properties().num_unclipped_descendants =
1190 recursive_data->num_unclipped_descendants;
1191 layer->draw_properties().layer_or_descendant_has_copy_request =
1192 (recursive_data->num_layer_or_descendants_with_copy_request != 0);
1193 layer->draw_properties().layer_or_descendant_has_input_handler =
1194 (recursive_data->num_layer_or_descendants_with_input_handler != 0);
1195 layer->set_num_layer_or_descandant_with_copy_request(
1196 recursive_data->num_layer_or_descendants_with_copy_request);
1197 layer->set_num_layer_or_descandant_with_input_handler(
1198 recursive_data->num_layer_or_descendants_with_input_handler);
1200 if (IsRootLayer(layer))
1201 layer->layer_tree_host()->SetNeedsMetaInfoRecomputation(false);
1204 static void PreCalculateMetaInformationInternal(
1205 LayerImpl* layer,
1206 PreCalculateMetaInformationRecursiveData* recursive_data) {
1207 ValidateRenderSurface(layer);
1209 layer->set_sorted_for_recursion(false);
1210 layer->draw_properties().has_child_with_a_scroll_parent = false;
1211 layer->set_layer_or_descendant_is_drawn(false);
1212 layer->set_visited(false);
1214 if (!HasInvertibleOrAnimatedTransform(layer)) {
1215 // Layers with singular transforms should not be drawn, the whole subtree
1216 // can be skipped.
1217 return;
1220 if (layer->clip_parent())
1221 recursive_data->num_unclipped_descendants++;
1223 for (size_t i = 0; i < layer->children().size(); ++i) {
1224 LayerImpl* child_layer = layer->child_at(i);
1226 PreCalculateMetaInformationRecursiveData data_for_child;
1227 PreCalculateMetaInformationInternal(child_layer, &data_for_child);
1229 if (child_layer->scroll_parent())
1230 layer->draw_properties().has_child_with_a_scroll_parent = true;
1231 recursive_data->Merge(data_for_child);
1234 if (layer->clip_children()) {
1235 size_t num_clip_children = layer->clip_children()->size();
1236 DCHECK_GE(recursive_data->num_unclipped_descendants, num_clip_children);
1237 recursive_data->num_unclipped_descendants -= num_clip_children;
1240 if (layer->HasCopyRequest())
1241 recursive_data->num_layer_or_descendants_with_copy_request++;
1243 if (!layer->touch_event_handler_region().IsEmpty() ||
1244 layer->have_wheel_event_handlers())
1245 recursive_data->num_layer_or_descendants_with_input_handler++;
1247 layer->draw_properties().num_unclipped_descendants =
1248 recursive_data->num_unclipped_descendants;
1249 layer->draw_properties().layer_or_descendant_has_copy_request =
1250 (recursive_data->num_layer_or_descendants_with_copy_request != 0);
1251 layer->draw_properties().layer_or_descendant_has_input_handler =
1252 (recursive_data->num_layer_or_descendants_with_input_handler != 0);
1255 void LayerTreeHostCommon::PreCalculateMetaInformation(Layer* root_layer) {
1256 PreCalculateMetaInformationRecursiveData recursive_data;
1257 PreCalculateMetaInformationInternal(root_layer, &recursive_data);
1260 void LayerTreeHostCommon::PreCalculateMetaInformationForTesting(
1261 LayerImpl* root_layer) {
1262 PreCalculateMetaInformationRecursiveData recursive_data;
1263 PreCalculateMetaInformationInternal(root_layer, &recursive_data);
1266 void LayerTreeHostCommon::PreCalculateMetaInformationForTesting(
1267 Layer* root_layer) {
1268 UpdateMetaInformationSequenceNumber(root_layer);
1269 PreCalculateMetaInformationRecursiveData recursive_data;
1270 PreCalculateMetaInformationInternal(root_layer, &recursive_data);
1273 template <typename LayerType>
1274 struct SubtreeGlobals {
1275 int max_texture_size;
1276 float device_scale_factor;
1277 float page_scale_factor;
1278 const LayerType* page_scale_layer;
1279 gfx::Vector2dF elastic_overscroll;
1280 const LayerType* elastic_overscroll_application_layer;
1281 bool can_adjust_raster_scales;
1282 bool can_render_to_separate_surface;
1283 bool layers_always_allowed_lcd_text;
1286 template<typename LayerType>
1287 struct DataForRecursion {
1288 // The accumulated sequence of transforms a layer will use to determine its
1289 // own draw transform.
1290 gfx::Transform parent_matrix;
1292 // The accumulated sequence of transforms a layer will use to determine its
1293 // own screen-space transform.
1294 gfx::Transform full_hierarchy_matrix;
1296 // The transform that removes all scrolling that may have occurred between a
1297 // fixed-position layer and its container, so that the layer actually does
1298 // remain fixed.
1299 gfx::Transform scroll_compensation_matrix;
1301 // The ancestor that would be the container for any fixed-position / sticky
1302 // layers.
1303 LayerType* fixed_container;
1305 // This is the normal clip rect that is propagated from parent to child.
1306 gfx::Rect clip_rect_in_target_space;
1308 // When the layer's children want to compute their visible content rect, they
1309 // want to know what their target surface's clip rect will be. BUT - they
1310 // want to know this clip rect represented in their own target space. This
1311 // requires inverse-projecting the surface's clip rect from the surface's
1312 // render target space down to the surface's own space. Instead of computing
1313 // this value redundantly for each child layer, it is computed only once
1314 // while dealing with the parent layer, and then this precomputed value is
1315 // passed down the recursion to the children that actually use it.
1316 gfx::Rect clip_rect_of_target_surface_in_target_space;
1318 // The maximum amount by which this layer will be scaled during the lifetime
1319 // of currently running animations.
1320 float maximum_animation_contents_scale;
1322 bool ancestor_is_animating_scale;
1323 bool ancestor_clips_subtree;
1324 typename LayerType::RenderSurfaceType*
1325 nearest_occlusion_immune_ancestor_surface;
1326 bool in_subtree_of_page_scale_layer;
1327 bool subtree_can_use_lcd_text;
1328 bool subtree_is_visible_from_ancestor;
1331 template <typename LayerType>
1332 static LayerType* GetChildContainingLayer(const LayerType& parent,
1333 LayerType* layer) {
1334 for (LayerType* ancestor = layer; ancestor; ancestor = ancestor->parent()) {
1335 if (ancestor->parent() == &parent)
1336 return ancestor;
1338 NOTREACHED();
1339 return 0;
1342 template <typename LayerType>
1343 static void AddScrollParentChain(std::vector<LayerType*>* out,
1344 const LayerType& parent,
1345 LayerType* layer) {
1346 // At a high level, this function walks up the chain of scroll parents
1347 // recursively, and once we reach the end of the chain, we add the child
1348 // of |parent| containing each scroll ancestor as we unwind. The result is
1349 // an ordering of parent's children that ensures that scroll parents are
1350 // visited before their descendants.
1351 // Take for example this layer tree:
1353 // + stacking_context
1354 // + scroll_child (1)
1355 // + scroll_parent_graphics_layer (*)
1356 // | + scroll_parent_scrolling_layer
1357 // | + scroll_parent_scrolling_content_layer (2)
1358 // + scroll_grandparent_graphics_layer (**)
1359 // + scroll_grandparent_scrolling_layer
1360 // + scroll_grandparent_scrolling_content_layer (3)
1362 // The scroll child is (1), its scroll parent is (2) and its scroll
1363 // grandparent is (3). Note, this doesn't mean that (2)'s scroll parent is
1364 // (3), it means that (*)'s scroll parent is (3). We don't want our list to
1365 // look like [ (3), (2), (1) ], even though that does have the ancestor chain
1366 // in the right order. Instead, we want [ (**), (*), (1) ]. That is, only want
1367 // (1)'s siblings in the list, but we want them to appear in such an order
1368 // that the scroll ancestors get visited in the correct order.
1370 // So our first task at this step of the recursion is to determine the layer
1371 // that we will potentionally add to the list. That is, the child of parent
1372 // containing |layer|.
1373 LayerType* child = GetChildContainingLayer(parent, layer);
1374 if (child->sorted_for_recursion())
1375 return;
1377 if (LayerType* scroll_parent = child->scroll_parent())
1378 AddScrollParentChain(out, parent, scroll_parent);
1380 out->push_back(child);
1381 bool sorted_for_recursion = true;
1382 child->set_sorted_for_recursion(sorted_for_recursion);
1385 template <typename LayerType>
1386 static bool SortChildrenForRecursion(std::vector<LayerType*>* out,
1387 const LayerType& parent) {
1388 out->reserve(parent.children().size());
1389 bool order_changed = false;
1390 for (size_t i = 0; i < parent.children().size(); ++i) {
1391 LayerType* current =
1392 LayerTreeHostCommon::get_layer_as_raw_ptr(parent.children(), i);
1394 if (current->sorted_for_recursion()) {
1395 order_changed = true;
1396 continue;
1399 AddScrollParentChain(out, parent, current);
1402 DCHECK_EQ(parent.children().size(), out->size());
1403 return order_changed;
1406 template <typename LayerType>
1407 static void GetNewDescendantsStartIndexAndCount(LayerType* layer,
1408 size_t* start_index,
1409 size_t* count) {
1410 *start_index = layer->draw_properties().index_of_first_descendants_addition;
1411 *count = layer->draw_properties().num_descendants_added;
1414 template <typename LayerType>
1415 static void GetNewRenderSurfacesStartIndexAndCount(LayerType* layer,
1416 size_t* start_index,
1417 size_t* count) {
1418 *start_index = layer->draw_properties()
1419 .index_of_first_render_surface_layer_list_addition;
1420 *count = layer->draw_properties().num_render_surfaces_added;
1423 // We need to extract a list from the the two flavors of RenderSurfaceListType
1424 // for use in the sorting function below.
1425 static LayerList* GetLayerListForSorting(RenderSurfaceLayerList* rsll) {
1426 return &rsll->AsLayerList();
1429 static LayerImplList* GetLayerListForSorting(LayerImplList* layer_list) {
1430 return layer_list;
1433 template <typename LayerType, typename GetIndexAndCountType>
1434 static void SortLayerListContributions(
1435 const LayerType& parent,
1436 typename LayerType::LayerListType* unsorted,
1437 size_t start_index_for_all_contributions,
1438 GetIndexAndCountType get_index_and_count) {
1439 typename LayerType::LayerListType buffer;
1440 for (size_t i = 0; i < parent.children().size(); ++i) {
1441 LayerType* child =
1442 LayerTreeHostCommon::get_layer_as_raw_ptr(parent.children(), i);
1444 size_t start_index = 0;
1445 size_t count = 0;
1446 get_index_and_count(child, &start_index, &count);
1447 for (size_t j = start_index; j < start_index + count; ++j)
1448 buffer.push_back(unsorted->at(j));
1451 DCHECK_EQ(buffer.size(),
1452 unsorted->size() - start_index_for_all_contributions);
1454 for (size_t i = 0; i < buffer.size(); ++i)
1455 (*unsorted)[i + start_index_for_all_contributions] = buffer[i];
1458 // Recursively walks the layer tree starting at the given node and computes all
1459 // the necessary transformations, clip rects, render surfaces, etc.
1460 template <typename LayerType>
1461 static void CalculateDrawPropertiesInternal(
1462 LayerType* layer,
1463 const SubtreeGlobals<LayerType>& globals,
1464 const DataForRecursion<LayerType>& data_from_ancestor,
1465 typename LayerType::RenderSurfaceListType* render_surface_layer_list,
1466 typename LayerType::LayerListType* layer_list,
1467 std::vector<AccumulatedSurfaceState<LayerType>>* accumulated_surface_state,
1468 int current_render_surface_layer_list_id) {
1469 // This function computes the new matrix transformations recursively for this
1470 // layer and all its descendants. It also computes the appropriate render
1471 // surfaces.
1472 // Some important points to remember:
1474 // 0. Here, transforms are notated in Matrix x Vector order, and in words we
1475 // describe what the transform does from left to right.
1477 // 1. In our terminology, the "layer origin" refers to the top-left corner of
1478 // a layer, and the positive Y-axis points downwards. This interpretation is
1479 // valid because the orthographic projection applied at draw time flips the Y
1480 // axis appropriately.
1482 // 2. The anchor point, when given as a PointF object, is specified in "unit
1483 // layer space", where the bounds of the layer map to [0, 1]. However, as a
1484 // Transform object, the transform to the anchor point is specified in "layer
1485 // space", where the bounds of the layer map to [bounds.width(),
1486 // bounds.height()].
1488 // 3. Definition of various transforms used:
1489 // M[parent] is the parent matrix, with respect to the nearest render
1490 // surface, passed down recursively.
1492 // M[root] is the full hierarchy, with respect to the root, passed down
1493 // recursively.
1495 // Tr[origin] is the translation matrix from the parent's origin to
1496 // this layer's origin.
1498 // Tr[origin2anchor] is the translation from the layer's origin to its
1499 // anchor point
1501 // Tr[origin2center] is the translation from the layer's origin to its
1502 // center
1504 // M[layer] is the layer's matrix (applied at the anchor point)
1506 // S[layer2content] is the ratio of a layer's content_bounds() to its
1507 // Bounds().
1509 // Some composite transforms can help in understanding the sequence of
1510 // transforms:
1511 // composite_layer_transform = Tr[origin2anchor] * M[layer] *
1512 // Tr[origin2anchor].inverse()
1514 // 4. When a layer (or render surface) is drawn, it is drawn into a "target
1515 // render surface". Therefore the draw transform does not necessarily
1516 // transform from screen space to local layer space. Instead, the draw
1517 // transform is the transform between the "target render surface space" and
1518 // local layer space. Note that render surfaces, except for the root, also
1519 // draw themselves into a different target render surface, and so their draw
1520 // transform and origin transforms are also described with respect to the
1521 // target.
1523 // Using these definitions, then:
1525 // The draw transform for the layer is:
1526 // M[draw] = M[parent] * Tr[origin] * composite_layer_transform *
1527 // S[layer2content] = M[parent] * Tr[layer->position() + anchor] *
1528 // M[layer] * Tr[anchor2origin] * S[layer2content]
1530 // Interpreting the math left-to-right, this transforms from the
1531 // layer's render surface to the origin of the layer in content space.
1533 // The screen space transform is:
1534 // M[screenspace] = M[root] * Tr[origin] * composite_layer_transform *
1535 // S[layer2content]
1536 // = M[root] * Tr[layer->position() + anchor] * M[layer]
1537 // * Tr[anchor2origin] * S[layer2content]
1539 // Interpreting the math left-to-right, this transforms from the root
1540 // render surface's content space to the origin of the layer in content
1541 // space.
1543 // The transform hierarchy that is passed on to children (i.e. the child's
1544 // parent_matrix) is:
1545 // M[parent]_for_child = M[parent] * Tr[origin] *
1546 // composite_layer_transform
1547 // = M[parent] * Tr[layer->position() + anchor] *
1548 // M[layer] * Tr[anchor2origin]
1550 // and a similar matrix for the full hierarchy with respect to the
1551 // root.
1553 // Finally, note that the final matrix used by the shader for the layer is P *
1554 // M[draw] * S . This final product is computed in drawTexturedQuad(), where:
1555 // P is the projection matrix
1556 // S is the scale adjustment (to scale up a canonical quad to the
1557 // layer's size)
1559 // When a render surface has a replica layer, that layer's transform is used
1560 // to draw a second copy of the surface. gfx::Transforms named here are
1561 // relative to the surface, unless they specify they are relative to the
1562 // replica layer.
1564 // We will denote a scale by device scale S[deviceScale]
1566 // The render surface draw transform to its target surface origin is:
1567 // M[surfaceDraw] = M[owningLayer->Draw]
1569 // The render surface origin transform to its the root (screen space) origin
1570 // is:
1571 // M[surface2root] = M[owningLayer->screenspace] *
1572 // S[deviceScale].inverse()
1574 // The replica draw transform to its target surface origin is:
1575 // M[replicaDraw] = S[deviceScale] * M[surfaceDraw] *
1576 // Tr[replica->position() + replica->anchor()] * Tr[replica] *
1577 // Tr[origin2anchor].inverse() * S[contents_scale].inverse()
1579 // The replica draw transform to the root (screen space) origin is:
1580 // M[replica2root] = M[surface2root] * Tr[replica->position()] *
1581 // Tr[replica] * Tr[origin2anchor].inverse()
1584 // It makes no sense to have a non-unit page_scale_factor without specifying
1585 // which layer roots the subtree the scale is applied to.
1586 DCHECK(globals.page_scale_layer || (globals.page_scale_factor == 1.f));
1588 CHECK(!layer->visited());
1589 bool visited = true;
1590 layer->set_visited(visited);
1592 DataForRecursion<LayerType> data_for_children;
1593 typename LayerType::RenderSurfaceType*
1594 nearest_occlusion_immune_ancestor_surface =
1595 data_from_ancestor.nearest_occlusion_immune_ancestor_surface;
1596 data_for_children.in_subtree_of_page_scale_layer =
1597 data_from_ancestor.in_subtree_of_page_scale_layer;
1598 data_for_children.subtree_can_use_lcd_text =
1599 data_from_ancestor.subtree_can_use_lcd_text;
1601 // Layers that are marked as hidden will hide themselves and their subtree.
1602 // Exception: Layers with copy requests, whether hidden or not, must be drawn
1603 // anyway. In this case, we will inform their subtree they are visible to get
1604 // the right results.
1605 const bool layer_is_visible =
1606 data_from_ancestor.subtree_is_visible_from_ancestor &&
1607 !layer->hide_layer_and_subtree();
1608 const bool layer_is_drawn = layer_is_visible || layer->HasCopyRequest();
1610 // The root layer cannot skip CalcDrawProperties.
1611 if (!IsRootLayer(layer) && SubtreeShouldBeSkipped(layer, layer_is_drawn)) {
1612 if (layer->render_surface())
1613 layer->ClearRenderSurfaceLayerList();
1614 layer->draw_properties().render_target = nullptr;
1615 return;
1618 // We need to circumvent the normal recursive flow of information for clip
1619 // children (they don't inherit their direct ancestor's clip information).
1620 // This is unfortunate, and would be unnecessary if we were to formally
1621 // separate the clipping hierarchy from the layer hierarchy.
1622 bool ancestor_clips_subtree = data_from_ancestor.ancestor_clips_subtree;
1623 gfx::Rect ancestor_clip_rect_in_target_space =
1624 data_from_ancestor.clip_rect_in_target_space;
1626 // Update our clipping state. If we have a clip parent we will need to pull
1627 // from the clip state cache rather than using the clip state passed from our
1628 // immediate ancestor.
1629 UpdateClipRectsForClipChild<LayerType>(
1630 layer, &ancestor_clip_rect_in_target_space, &ancestor_clips_subtree);
1632 // As this function proceeds, these are the properties for the current
1633 // layer that actually get computed. To avoid unnecessary copies
1634 // (particularly for matrices), we do computations directly on these values
1635 // when possible.
1636 DrawProperties<LayerType>& layer_draw_properties = layer->draw_properties();
1638 gfx::Rect clip_rect_in_target_space;
1639 bool layer_or_ancestor_clips_descendants = false;
1641 // This value is cached on the stack so that we don't have to inverse-project
1642 // the surface's clip rect redundantly for every layer. This value is the
1643 // same as the target surface's clip rect, except that instead of being
1644 // described in the target surface's target's space, it is described in the
1645 // current render target's space.
1646 gfx::Rect clip_rect_of_target_surface_in_target_space;
1648 float accumulated_draw_opacity = layer->opacity();
1649 if (layer->parent())
1650 accumulated_draw_opacity *= layer->parent()->draw_opacity();
1652 bool animating_transform_to_screen =
1653 layer->HasPotentiallyRunningTransformAnimation();
1654 if (layer->parent()) {
1655 animating_transform_to_screen |=
1656 layer->parent()->screen_space_transform_is_animating();
1658 gfx::Point3F transform_origin = layer->transform_origin();
1659 gfx::ScrollOffset scroll_offset = GetEffectiveCurrentScrollOffset(layer);
1660 gfx::PointF position =
1661 layer->position() - ScrollOffsetToVector2dF(scroll_offset);
1662 gfx::Transform combined_transform = data_from_ancestor.parent_matrix;
1663 if (!layer->transform().IsIdentity()) {
1664 // LT = Tr[origin] * Tr[origin2transformOrigin]
1665 combined_transform.Translate3d(position.x() + transform_origin.x(),
1666 position.y() + transform_origin.y(),
1667 transform_origin.z());
1668 // LT = Tr[origin] * Tr[origin2origin] * M[layer]
1669 combined_transform.PreconcatTransform(layer->transform());
1670 // LT = Tr[origin] * Tr[origin2origin] * M[layer] *
1671 // Tr[transformOrigin2origin]
1672 combined_transform.Translate3d(
1673 -transform_origin.x(), -transform_origin.y(), -transform_origin.z());
1674 } else {
1675 combined_transform.Translate(position.x(), position.y());
1678 gfx::Vector2dF effective_scroll_delta = GetEffectiveScrollDelta(layer);
1679 if (!animating_transform_to_screen && layer->scrollable() &&
1680 combined_transform.IsScaleOrTranslation()) {
1681 // Align the scrollable layer's position to screen space pixels to avoid
1682 // blurriness. To avoid side-effects, do this only if the transform is
1683 // simple.
1684 gfx::Vector2dF previous_translation = combined_transform.To2dTranslation();
1685 combined_transform.RoundTranslationComponents();
1686 gfx::Vector2dF current_translation = combined_transform.To2dTranslation();
1688 // This rounding changes the scroll delta, and so must be included
1689 // in the scroll compensation matrix. The scaling converts from physical
1690 // coordinates to the scroll delta's CSS coordinates (using the parent
1691 // matrix instead of combined transform since scrolling is applied before
1692 // the layer's transform). For example, if we have a total scale factor of
1693 // 3.0, then 1 physical pixel is only 1/3 of a CSS pixel.
1694 gfx::Vector2dF parent_scales = MathUtil::ComputeTransform2dScaleComponents(
1695 data_from_ancestor.parent_matrix, 1.f);
1696 effective_scroll_delta -=
1697 gfx::ScaleVector2d(current_translation - previous_translation,
1698 1.f / parent_scales.x(),
1699 1.f / parent_scales.y());
1702 // Apply adjustment from position constraints.
1703 ApplyPositionAdjustment(layer, data_from_ancestor.fixed_container,
1704 data_from_ancestor.scroll_compensation_matrix, &combined_transform);
1706 bool combined_is_animating_scale = false;
1707 float combined_maximum_animation_contents_scale = 0.f;
1708 float combined_starting_animation_contents_scale = 0.f;
1709 if (globals.can_adjust_raster_scales) {
1710 CalculateAnimationContentsScale(
1711 layer, data_from_ancestor.ancestor_is_animating_scale,
1712 data_from_ancestor.maximum_animation_contents_scale,
1713 data_from_ancestor.parent_matrix, combined_transform,
1714 &combined_is_animating_scale,
1715 &combined_maximum_animation_contents_scale,
1716 &combined_starting_animation_contents_scale);
1718 data_for_children.ancestor_is_animating_scale = combined_is_animating_scale;
1719 data_for_children.maximum_animation_contents_scale =
1720 combined_maximum_animation_contents_scale;
1722 // Compute the 2d scale components of the transform hierarchy up to the target
1723 // surface. From there, we can decide on a contents scale for the layer.
1724 float layer_scale_factors = globals.device_scale_factor;
1725 if (data_from_ancestor.in_subtree_of_page_scale_layer)
1726 layer_scale_factors *= globals.page_scale_factor;
1727 gfx::Vector2dF combined_transform_scales =
1728 MathUtil::ComputeTransform2dScaleComponents(
1729 combined_transform,
1730 layer_scale_factors);
1732 UpdateLayerScaleDrawProperties(layer,
1733 combined_maximum_animation_contents_scale,
1734 combined_starting_animation_contents_scale);
1736 LayerType* mask_layer = layer->mask_layer();
1737 if (mask_layer) {
1738 UpdateLayerScaleDrawProperties(mask_layer,
1739 combined_maximum_animation_contents_scale,
1740 combined_starting_animation_contents_scale);
1743 LayerType* replica_mask_layer =
1744 layer->replica_layer() ? layer->replica_layer()->mask_layer() : NULL;
1745 if (replica_mask_layer) {
1746 UpdateLayerScaleDrawProperties(replica_mask_layer,
1747 combined_maximum_animation_contents_scale,
1748 combined_starting_animation_contents_scale);
1751 if (layer == globals.page_scale_layer) {
1752 combined_transform.Scale(globals.page_scale_factor,
1753 globals.page_scale_factor);
1754 data_for_children.in_subtree_of_page_scale_layer = true;
1757 // The draw_transform that gets computed below is effectively the layer's
1758 // draw_transform, unless the layer itself creates a render_surface. In that
1759 // case, the render_surface re-parents the transforms.
1760 layer_draw_properties.target_space_transform = combined_transform;
1762 // The layer's screen_space_transform represents the transform between root
1763 // layer's "screen space" and local content space.
1764 layer_draw_properties.screen_space_transform =
1765 data_from_ancestor.full_hierarchy_matrix;
1766 layer_draw_properties.screen_space_transform.PreconcatTransform
1767 (layer_draw_properties.target_space_transform);
1769 bool layer_can_use_lcd_text = true;
1770 bool subtree_can_use_lcd_text = true;
1771 if (!globals.layers_always_allowed_lcd_text) {
1772 // To avoid color fringing, LCD text should only be used on opaque layers
1773 // with just integral translation.
1774 subtree_can_use_lcd_text = data_from_ancestor.subtree_can_use_lcd_text &&
1775 accumulated_draw_opacity == 1.f &&
1776 layer_draw_properties.target_space_transform
1777 .IsIdentityOrIntegerTranslation();
1778 // Also disable LCD text locally for non-opaque content.
1779 layer_can_use_lcd_text = subtree_can_use_lcd_text &&
1780 layer->contents_opaque();
1783 // full_hierarchy_matrix is the matrix that transforms objects between screen
1784 // space (except projection matrix) and the most recent RenderSurfaceImpl's
1785 // space. next_hierarchy_matrix will only change if this layer uses a new
1786 // RenderSurfaceImpl, otherwise remains the same.
1787 data_for_children.full_hierarchy_matrix =
1788 data_from_ancestor.full_hierarchy_matrix;
1790 bool render_to_separate_surface =
1791 IsRootLayer(layer) ||
1792 (globals.can_render_to_separate_surface && layer->render_surface());
1794 if (render_to_separate_surface) {
1795 DCHECK(layer->render_surface());
1796 // Check back-face visibility before continuing with this surface and its
1797 // subtree
1798 if (!layer->double_sided() && TransformToParentIsKnown(layer) &&
1799 IsSurfaceBackFaceVisible(layer, combined_transform)) {
1800 layer->ClearRenderSurfaceLayerList();
1801 layer->draw_properties().render_target = nullptr;
1802 return;
1805 typename LayerType::RenderSurfaceType* render_surface =
1806 layer->render_surface();
1807 layer->ClearRenderSurfaceLayerList();
1809 layer_draw_properties.render_target = layer;
1810 if (IsRootLayer(layer)) {
1811 // The root layer's render surface size is predetermined and so the root
1812 // layer can't directly support non-identity transforms. It should just
1813 // forward top-level transforms to the rest of the tree.
1814 data_for_children.parent_matrix = combined_transform;
1816 // The root surface does not contribute to any other surface, it has no
1817 // target.
1818 layer->render_surface()->set_contributes_to_drawn_surface(false);
1819 } else {
1820 // The owning layer's draw transform has a scale from content to layer
1821 // space which we do not want; so here we use the combined_transform
1822 // instead of the draw_transform. However, we do need to add a different
1823 // scale factor that accounts for the surface's pixel dimensions.
1824 // Remove the combined_transform scale from the draw transform.
1825 gfx::Transform draw_transform = combined_transform;
1826 draw_transform.Scale(1.0 / combined_transform_scales.x(),
1827 1.0 / combined_transform_scales.y());
1828 render_surface->SetDrawTransform(draw_transform);
1830 // The owning layer's transform was re-parented by the surface, so the
1831 // layer's new draw_transform only needs to scale the layer to surface
1832 // space.
1833 layer_draw_properties.target_space_transform.MakeIdentity();
1834 layer_draw_properties.target_space_transform.Scale(
1835 combined_transform_scales.x(), combined_transform_scales.y());
1837 // Inside the surface's subtree, we scale everything to the owning layer's
1838 // scale. The sublayer matrix transforms layer rects into target surface
1839 // content space. Conceptually, all layers in the subtree inherit the
1840 // scale at the point of the render surface in the transform hierarchy,
1841 // but we apply it explicitly to the owning layer and the remainder of the
1842 // subtree independently.
1843 DCHECK(data_for_children.parent_matrix.IsIdentity());
1844 data_for_children.parent_matrix.Scale(combined_transform_scales.x(),
1845 combined_transform_scales.y());
1847 // Even if the |layer_is_drawn|, it only contributes to a drawn surface
1848 // when the |layer_is_visible|.
1849 layer->render_surface()->set_contributes_to_drawn_surface(
1850 layer_is_visible);
1853 // The opacity value is moved from the layer to its surface, so that the
1854 // entire subtree properly inherits opacity.
1855 render_surface->SetDrawOpacity(accumulated_draw_opacity);
1856 layer_draw_properties.opacity = 1.f;
1857 layer_draw_properties.blend_mode = SkXfermode::kSrcOver_Mode;
1859 layer_draw_properties.screen_space_transform_is_animating =
1860 animating_transform_to_screen;
1862 // Update the aggregate hierarchy matrix to include the transform of the
1863 // newly created RenderSurfaceImpl.
1864 data_for_children.full_hierarchy_matrix.PreconcatTransform(
1865 render_surface->draw_transform());
1867 // A render surface inherently acts as a flattening point for the content of
1868 // its descendants.
1869 data_for_children.full_hierarchy_matrix.FlattenTo2d();
1871 if (layer->mask_layer()) {
1872 DrawProperties<LayerType>& mask_layer_draw_properties =
1873 layer->mask_layer()->draw_properties();
1874 mask_layer_draw_properties.render_target = layer;
1875 mask_layer_draw_properties.visible_layer_rect =
1876 gfx::Rect(layer->bounds());
1877 // Temporarily copy the draw transform of the mask's owning layer into the
1878 // mask layer draw properties. This won't actually get used for drawing
1879 // (the render surface uses the mask texture directly), but will get used
1880 // to get the correct contents scale.
1881 // TODO(enne): do something similar for property trees.
1882 mask_layer_draw_properties.target_space_transform =
1883 layer_draw_properties.target_space_transform;
1886 if (layer->replica_layer() && layer->replica_layer()->mask_layer()) {
1887 DrawProperties<LayerType>& replica_mask_draw_properties =
1888 layer->replica_layer()->mask_layer()->draw_properties();
1889 replica_mask_draw_properties.render_target = layer;
1890 replica_mask_draw_properties.visible_layer_rect =
1891 gfx::Rect(layer->bounds());
1892 replica_mask_draw_properties.target_space_transform =
1893 layer_draw_properties.target_space_transform;
1896 // Ignore occlusion from outside the surface when surface contents need to
1897 // be fully drawn. Layers with copy-request need to be complete.
1898 // We could be smarter about layers with replica and exclude regions
1899 // where both layer and the replica are occluded, but this seems like an
1900 // overkill. The same is true for layers with filters that move pixels.
1901 // TODO(senorblanco): make this smarter for the SkImageFilter case (check
1902 // for pixel-moving filters)
1903 if (layer->HasCopyRequest() ||
1904 layer->has_replica() ||
1905 layer->filters().HasReferenceFilter() ||
1906 layer->filters().HasFilterThatMovesPixels()) {
1907 nearest_occlusion_immune_ancestor_surface = render_surface;
1909 render_surface->SetNearestOcclusionImmuneAncestor(
1910 nearest_occlusion_immune_ancestor_surface);
1912 layer_or_ancestor_clips_descendants = false;
1913 bool subtree_is_clipped_by_surface_bounds = false;
1914 if (ancestor_clips_subtree) {
1915 // It may be the layer or the surface doing the clipping of the subtree,
1916 // but in either case, we'll be clipping to the projected clip rect of our
1917 // ancestor.
1918 gfx::Transform inverse_surface_draw_transform(
1919 gfx::Transform::kSkipInitialization);
1920 if (!render_surface->draw_transform().GetInverse(
1921 &inverse_surface_draw_transform)) {
1922 // TODO(shawnsingh): Either we need to handle uninvertible transforms
1923 // here, or DCHECK that the transform is invertible.
1926 gfx::Rect surface_clip_rect_in_target_space = gfx::IntersectRects(
1927 data_from_ancestor.clip_rect_of_target_surface_in_target_space,
1928 ancestor_clip_rect_in_target_space);
1929 gfx::Rect projected_surface_rect = MathUtil::ProjectEnclosingClippedRect(
1930 inverse_surface_draw_transform, surface_clip_rect_in_target_space);
1932 if (layer_draw_properties.num_unclipped_descendants > 0u) {
1933 // If we have unclipped descendants, we cannot count on the render
1934 // surface's bounds clipping our subtree: the unclipped descendants
1935 // could cause us to expand our bounds. In this case, we must rely on
1936 // layer clipping for correctess. NB: since we can only encounter
1937 // translations between a clip child and its clip parent, clipping is
1938 // guaranteed to be exact in this case.
1939 layer_or_ancestor_clips_descendants = true;
1940 clip_rect_in_target_space = projected_surface_rect;
1941 } else {
1942 // The new render_surface here will correctly clip the entire subtree.
1943 // So, we do not need to continue propagating the clipping state further
1944 // down the tree. This way, we can avoid transforming clip rects from
1945 // ancestor target surface space to current target surface space that
1946 // could cause more w < 0 headaches. The render surface clip rect is
1947 // expressed in the space where this surface draws, i.e. the same space
1948 // as clip_rect_from_ancestor_in_ancestor_target_space.
1949 render_surface->SetClipRect(ancestor_clip_rect_in_target_space);
1950 clip_rect_of_target_surface_in_target_space = projected_surface_rect;
1951 subtree_is_clipped_by_surface_bounds = true;
1955 DCHECK(layer->render_surface());
1956 DCHECK(!layer->parent() || layer->parent()->render_target() ==
1957 accumulated_surface_state->back().render_target);
1959 accumulated_surface_state->push_back(
1960 AccumulatedSurfaceState<LayerType>(layer));
1962 render_surface->SetIsClipped(subtree_is_clipped_by_surface_bounds);
1963 if (!subtree_is_clipped_by_surface_bounds) {
1964 render_surface->SetClipRect(gfx::Rect());
1965 clip_rect_of_target_surface_in_target_space =
1966 data_from_ancestor.clip_rect_of_target_surface_in_target_space;
1969 // If the new render surface is drawn translucent or with a non-integral
1970 // translation then the subtree that gets drawn on this render surface
1971 // cannot use LCD text.
1972 data_for_children.subtree_can_use_lcd_text = subtree_can_use_lcd_text;
1974 render_surface_layer_list->push_back(layer);
1975 } else {
1976 DCHECK(layer->parent());
1978 // Note: layer_draw_properties.target_space_transform is computed above,
1979 // before this if-else statement.
1980 layer_draw_properties.screen_space_transform_is_animating =
1981 animating_transform_to_screen;
1982 layer_draw_properties.opacity = accumulated_draw_opacity;
1983 layer_draw_properties.blend_mode = layer->blend_mode();
1984 data_for_children.parent_matrix = combined_transform;
1986 // Layers without render_surfaces directly inherit the ancestor's clip
1987 // status.
1988 layer_or_ancestor_clips_descendants = ancestor_clips_subtree;
1989 if (ancestor_clips_subtree) {
1990 clip_rect_in_target_space =
1991 ancestor_clip_rect_in_target_space;
1994 // The surface's cached clip rect value propagates regardless of what
1995 // clipping goes on between layers here.
1996 clip_rect_of_target_surface_in_target_space =
1997 data_from_ancestor.clip_rect_of_target_surface_in_target_space;
1999 // Layers that are not their own render_target will render into the target
2000 // of their nearest ancestor.
2001 layer_draw_properties.render_target = layer->parent()->render_target();
2004 layer_draw_properties.can_use_lcd_text = layer_can_use_lcd_text;
2006 // The layer bounds() includes the layer's bounds_delta() which we want
2007 // for the clip rect.
2008 gfx::Rect rect_in_target_space = MathUtil::MapEnclosingClippedRect(
2009 layer->draw_transform(), gfx::Rect(layer->bounds()));
2011 if (LayerClipsSubtree(layer)) {
2012 layer_or_ancestor_clips_descendants = true;
2013 if (ancestor_clips_subtree && !render_to_separate_surface) {
2014 // A layer without render surface shares the same target as its ancestor.
2015 clip_rect_in_target_space =
2016 ancestor_clip_rect_in_target_space;
2017 clip_rect_in_target_space.Intersect(rect_in_target_space);
2018 } else {
2019 clip_rect_in_target_space = rect_in_target_space;
2023 // Tell the layer the rect that it's clipped by. In theory we could use a
2024 // tighter clip rect here (drawable_content_rect), but that actually does not
2025 // reduce how much would be drawn, and instead it would create unnecessary
2026 // changes to scissor state affecting GPU performance. Our clip information
2027 // is used in the recursion below, so we must set it beforehand.
2028 DCHECK_EQ(layer_or_ancestor_clips_descendants, layer->is_clipped());
2029 if (layer_or_ancestor_clips_descendants) {
2030 layer_draw_properties.clip_rect = clip_rect_in_target_space;
2031 } else {
2032 // Initialize the clip rect to a safe value that will not clip the
2033 // layer, just in case clipping is still accidentally used.
2034 layer_draw_properties.clip_rect = rect_in_target_space;
2037 typename LayerType::LayerListType& descendants =
2038 (render_to_separate_surface ? layer->render_surface()->layer_list()
2039 : *layer_list);
2041 // Any layers that are appended after this point are in the layer's subtree
2042 // and should be included in the sorting process.
2043 size_t sorting_start_index = descendants.size();
2045 if (!LayerShouldBeSkipped(layer, layer_is_drawn)) {
2046 MarkLayerWithRenderSurfaceLayerListId(layer,
2047 current_render_surface_layer_list_id);
2048 descendants.push_back(layer);
2051 // Any layers that are appended after this point may need to be sorted if we
2052 // visit the children out of order.
2053 size_t render_surface_layer_list_child_sorting_start_index =
2054 render_surface_layer_list->size();
2055 size_t layer_list_child_sorting_start_index = descendants.size();
2057 if (!layer->children().empty()) {
2058 if (layer == globals.elastic_overscroll_application_layer) {
2059 data_for_children.parent_matrix.Translate(
2060 -globals.elastic_overscroll.x(), -globals.elastic_overscroll.y());
2063 // Flatten to 2D if the layer doesn't preserve 3D.
2064 if (layer->should_flatten_transform())
2065 data_for_children.parent_matrix.FlattenTo2d();
2067 data_for_children.scroll_compensation_matrix =
2068 ComputeScrollCompensationMatrixForChildren(
2069 layer,
2070 data_from_ancestor.parent_matrix,
2071 data_from_ancestor.scroll_compensation_matrix,
2072 effective_scroll_delta);
2073 data_for_children.fixed_container =
2074 layer->IsContainerForFixedPositionLayers() ?
2075 layer : data_from_ancestor.fixed_container;
2077 data_for_children.clip_rect_in_target_space = clip_rect_in_target_space;
2078 data_for_children.clip_rect_of_target_surface_in_target_space =
2079 clip_rect_of_target_surface_in_target_space;
2080 data_for_children.ancestor_clips_subtree =
2081 layer_or_ancestor_clips_descendants;
2082 data_for_children.nearest_occlusion_immune_ancestor_surface =
2083 nearest_occlusion_immune_ancestor_surface;
2084 data_for_children.subtree_is_visible_from_ancestor = layer_is_drawn;
2087 std::vector<LayerType*> sorted_children;
2088 bool child_order_changed = false;
2089 if (layer_draw_properties.has_child_with_a_scroll_parent)
2090 child_order_changed = SortChildrenForRecursion(&sorted_children, *layer);
2092 for (size_t i = 0; i < layer->children().size(); ++i) {
2093 // If one of layer's children has a scroll parent, then we may have to
2094 // visit the children out of order. The new order is stored in
2095 // sorted_children. Otherwise, we'll grab the child directly from the
2096 // layer's list of children.
2097 LayerType* child =
2098 layer_draw_properties.has_child_with_a_scroll_parent
2099 ? sorted_children[i]
2100 : LayerTreeHostCommon::get_layer_as_raw_ptr(layer->children(), i);
2102 child->draw_properties().index_of_first_descendants_addition =
2103 descendants.size();
2104 child->draw_properties().index_of_first_render_surface_layer_list_addition =
2105 render_surface_layer_list->size();
2107 CalculateDrawPropertiesInternal<LayerType>(
2108 child,
2109 globals,
2110 data_for_children,
2111 render_surface_layer_list,
2112 &descendants,
2113 accumulated_surface_state,
2114 current_render_surface_layer_list_id);
2115 // If the child is its own render target, then it has a render surface.
2116 if (child->render_target() == child &&
2117 !child->render_surface()->layer_list().empty() &&
2118 !child->render_surface()->content_rect().IsEmpty()) {
2119 // This child will contribute its render surface, which means
2120 // we need to mark just the mask layer (and replica mask layer)
2121 // with the id.
2122 MarkMasksWithRenderSurfaceLayerListId(
2123 child, current_render_surface_layer_list_id);
2124 descendants.push_back(child);
2127 child->draw_properties().num_descendants_added =
2128 descendants.size() -
2129 child->draw_properties().index_of_first_descendants_addition;
2130 child->draw_properties().num_render_surfaces_added =
2131 render_surface_layer_list->size() -
2132 child->draw_properties()
2133 .index_of_first_render_surface_layer_list_addition;
2135 if (child->layer_or_descendant_is_drawn()) {
2136 bool layer_or_descendant_is_drawn = true;
2137 layer->set_layer_or_descendant_is_drawn(layer_or_descendant_is_drawn);
2141 // Add the unsorted layer list contributions, if necessary.
2142 if (child_order_changed) {
2143 SortLayerListContributions(
2144 *layer,
2145 GetLayerListForSorting(render_surface_layer_list),
2146 render_surface_layer_list_child_sorting_start_index,
2147 &GetNewRenderSurfacesStartIndexAndCount<LayerType>);
2149 SortLayerListContributions(
2150 *layer,
2151 &descendants,
2152 layer_list_child_sorting_start_index,
2153 &GetNewDescendantsStartIndexAndCount<LayerType>);
2156 // Compute the total drawable_content_rect for this subtree (the rect is in
2157 // target surface space).
2158 gfx::Rect local_drawable_content_rect_of_subtree =
2159 accumulated_surface_state->back().drawable_content_rect;
2160 if (render_to_separate_surface) {
2161 DCHECK(accumulated_surface_state->back().render_target == layer);
2162 accumulated_surface_state->pop_back();
2165 if (render_to_separate_surface && !IsRootLayer(layer) &&
2166 layer->render_surface()->layer_list().empty()) {
2167 RemoveSurfaceForEarlyExit(layer, render_surface_layer_list);
2168 return;
2171 // Compute the layer's drawable content rect (the rect is in target surface
2172 // space).
2173 layer_draw_properties.drawable_content_rect = rect_in_target_space;
2174 if (layer_or_ancestor_clips_descendants) {
2175 layer_draw_properties.drawable_content_rect.Intersect(
2176 clip_rect_in_target_space);
2178 if (layer->DrawsContent()) {
2179 local_drawable_content_rect_of_subtree.Union(
2180 layer_draw_properties.drawable_content_rect);
2183 // Compute the layer's visible content rect (the rect is in content space).
2184 layer_draw_properties.visible_layer_rect = CalculateVisibleLayerRect(
2185 layer, clip_rect_of_target_surface_in_target_space, rect_in_target_space);
2187 // Compute the remaining properties for the render surface, if the layer has
2188 // one.
2189 if (IsRootLayer(layer)) {
2190 // The root layer's surface's content_rect is always the entire viewport.
2191 DCHECK(render_to_separate_surface);
2192 layer->render_surface()->SetContentRect(
2193 ancestor_clip_rect_in_target_space);
2194 } else if (render_to_separate_surface) {
2195 typename LayerType::RenderSurfaceType* render_surface =
2196 layer->render_surface();
2197 gfx::Rect clipped_content_rect = local_drawable_content_rect_of_subtree;
2199 // Don't clip if the layer is reflected as the reflection shouldn't be
2200 // clipped. If the layer is animating, then the surface's transform to
2201 // its target is not known on the main thread, and we should not use it
2202 // to clip.
2203 if (!layer->replica_layer() && TransformToParentIsKnown(layer)) {
2204 // Note, it is correct to use data_from_ancestor.ancestor_clips_subtree
2205 // here, because we are looking at this layer's render_surface, not the
2206 // layer itself.
2207 if (render_surface->is_clipped() && !clipped_content_rect.IsEmpty()) {
2208 gfx::Rect surface_clip_rect = LayerTreeHostCommon::CalculateVisibleRect(
2209 render_surface->clip_rect(),
2210 clipped_content_rect,
2211 render_surface->draw_transform());
2212 clipped_content_rect.Intersect(surface_clip_rect);
2216 // The RenderSurfaceImpl backing texture cannot exceed the maximum supported
2217 // texture size.
2218 clipped_content_rect.set_width(
2219 std::min(clipped_content_rect.width(), globals.max_texture_size));
2220 clipped_content_rect.set_height(
2221 std::min(clipped_content_rect.height(), globals.max_texture_size));
2223 if (clipped_content_rect.IsEmpty()) {
2224 RemoveSurfaceForEarlyExit(layer, render_surface_layer_list);
2225 return;
2228 // Layers having a non-default blend mode will blend with the content
2229 // inside its parent's render target. This render target should be
2230 // either root_for_isolated_group, or the root of the layer tree.
2231 // Otherwise, this layer will use an incomplete backdrop, limited to its
2232 // render target and the blending result will be incorrect.
2233 DCHECK(layer->uses_default_blend_mode() || IsRootLayer(layer) ||
2234 !layer->parent()->render_target() ||
2235 IsRootLayer(layer->parent()->render_target()) ||
2236 layer->parent()->render_target()->is_root_for_isolated_group());
2238 render_surface->SetContentRect(clipped_content_rect);
2240 // The owning layer's screen_space_transform has a scale from content to
2241 // layer space which we need to undo and replace with a scale from the
2242 // surface's subtree into layer space.
2243 gfx::Transform screen_space_transform = layer->screen_space_transform();
2244 screen_space_transform.Scale(1.0 / combined_transform_scales.x(),
2245 1.0 / combined_transform_scales.y());
2246 render_surface->SetScreenSpaceTransform(screen_space_transform);
2248 if (layer->replica_layer()) {
2249 gfx::Transform surface_origin_to_replica_origin_transform;
2250 surface_origin_to_replica_origin_transform.Scale(
2251 combined_transform_scales.x(), combined_transform_scales.y());
2252 surface_origin_to_replica_origin_transform.Translate(
2253 layer->replica_layer()->position().x() +
2254 layer->replica_layer()->transform_origin().x(),
2255 layer->replica_layer()->position().y() +
2256 layer->replica_layer()->transform_origin().y());
2257 surface_origin_to_replica_origin_transform.PreconcatTransform(
2258 layer->replica_layer()->transform());
2259 surface_origin_to_replica_origin_transform.Translate(
2260 -layer->replica_layer()->transform_origin().x(),
2261 -layer->replica_layer()->transform_origin().y());
2262 surface_origin_to_replica_origin_transform.Scale(
2263 1.0 / combined_transform_scales.x(),
2264 1.0 / combined_transform_scales.y());
2266 // Compute the replica's "originTransform" that maps from the replica's
2267 // origin space to the target surface origin space.
2268 gfx::Transform replica_origin_transform =
2269 layer->render_surface()->draw_transform() *
2270 surface_origin_to_replica_origin_transform;
2271 render_surface->SetReplicaDrawTransform(replica_origin_transform);
2273 // Compute the replica's "screen_space_transform" that maps from the
2274 // replica's origin space to the screen's origin space.
2275 gfx::Transform replica_screen_space_transform =
2276 layer->render_surface()->screen_space_transform() *
2277 surface_origin_to_replica_origin_transform;
2278 render_surface->SetReplicaScreenSpaceTransform(
2279 replica_screen_space_transform);
2283 SavePaintPropertiesLayer(layer);
2285 // If neither this layer nor any of its children were added, early out.
2286 if (sorting_start_index == descendants.size()) {
2287 DCHECK(!render_to_separate_surface || IsRootLayer(layer));
2288 return;
2291 UpdateAccumulatedSurfaceState<LayerType>(
2292 layer, local_drawable_content_rect_of_subtree, accumulated_surface_state);
2294 if (layer->HasContributingDelegatedRenderPasses()) {
2295 layer->render_target()->render_surface()->
2296 AddContributingDelegatedRenderPassLayer(layer);
2298 } // NOLINT(readability/fn_size)
2300 template <typename LayerType, typename RenderSurfaceLayerListType>
2301 static void ProcessCalcDrawPropsInputs(
2302 const LayerTreeHostCommon::CalcDrawPropsInputs<LayerType,
2303 RenderSurfaceLayerListType>&
2304 inputs,
2305 SubtreeGlobals<LayerType>* globals,
2306 DataForRecursion<LayerType>* data_for_recursion) {
2307 DCHECK(inputs.root_layer);
2308 DCHECK(IsRootLayer(inputs.root_layer));
2309 DCHECK(inputs.render_surface_layer_list);
2311 gfx::Transform identity_matrix;
2313 // The root layer's render_surface should receive the device viewport as the
2314 // initial clip rect.
2315 gfx::Rect device_viewport_rect(inputs.device_viewport_size);
2317 gfx::Vector2dF device_transform_scale_components =
2318 MathUtil::ComputeTransform2dScaleComponents(inputs.device_transform, 1.f);
2319 // Not handling the rare case of different x and y device scale.
2320 float device_transform_scale =
2321 std::max(device_transform_scale_components.x(),
2322 device_transform_scale_components.y());
2324 gfx::Transform scaled_device_transform = inputs.device_transform;
2325 scaled_device_transform.Scale(inputs.device_scale_factor,
2326 inputs.device_scale_factor);
2328 globals->max_texture_size = inputs.max_texture_size;
2329 globals->device_scale_factor =
2330 inputs.device_scale_factor * device_transform_scale;
2331 globals->page_scale_factor = inputs.page_scale_factor;
2332 globals->page_scale_layer = inputs.page_scale_layer;
2333 globals->elastic_overscroll = inputs.elastic_overscroll;
2334 globals->elastic_overscroll_application_layer =
2335 inputs.elastic_overscroll_application_layer;
2336 globals->can_render_to_separate_surface =
2337 inputs.can_render_to_separate_surface;
2338 globals->can_adjust_raster_scales = inputs.can_adjust_raster_scales;
2339 globals->layers_always_allowed_lcd_text =
2340 inputs.layers_always_allowed_lcd_text;
2342 data_for_recursion->parent_matrix = scaled_device_transform;
2343 data_for_recursion->full_hierarchy_matrix = identity_matrix;
2344 data_for_recursion->scroll_compensation_matrix = identity_matrix;
2345 data_for_recursion->fixed_container = inputs.root_layer;
2346 data_for_recursion->clip_rect_in_target_space = device_viewport_rect;
2347 data_for_recursion->clip_rect_of_target_surface_in_target_space =
2348 device_viewport_rect;
2349 data_for_recursion->maximum_animation_contents_scale = 0.f;
2350 data_for_recursion->ancestor_is_animating_scale = false;
2351 data_for_recursion->ancestor_clips_subtree = true;
2352 data_for_recursion->nearest_occlusion_immune_ancestor_surface = NULL;
2353 data_for_recursion->in_subtree_of_page_scale_layer = false;
2354 data_for_recursion->subtree_can_use_lcd_text = inputs.can_use_lcd_text;
2355 data_for_recursion->subtree_is_visible_from_ancestor = true;
2358 void LayerTreeHostCommon::UpdateRenderSurface(
2359 Layer* layer,
2360 bool can_render_to_separate_surface,
2361 gfx::Transform* transform,
2362 bool* draw_transform_is_axis_aligned) {
2363 bool preserves_2d_axis_alignment =
2364 transform->Preserves2dAxisAlignment() && *draw_transform_is_axis_aligned;
2365 if (IsRootLayer(layer) || (can_render_to_separate_surface &&
2366 SubtreeShouldRenderToSeparateSurface(
2367 layer, preserves_2d_axis_alignment))) {
2368 // We reset the transform here so that any axis-changing transforms
2369 // will now be relative to this RenderSurface.
2370 transform->MakeIdentity();
2371 *draw_transform_is_axis_aligned = true;
2372 if (!layer->render_surface()) {
2373 layer->CreateRenderSurface();
2375 layer->SetHasRenderSurface(true);
2376 return;
2378 layer->SetHasRenderSurface(false);
2379 if (layer->render_surface())
2380 layer->ClearRenderSurface();
2383 void LayerTreeHostCommon::UpdateRenderSurfaces(
2384 Layer* layer,
2385 bool can_render_to_separate_surface,
2386 const gfx::Transform& parent_transform,
2387 bool draw_transform_is_axis_aligned) {
2388 gfx::Transform transform_for_children = layer->transform();
2389 transform_for_children *= parent_transform;
2390 draw_transform_is_axis_aligned &= layer->AnimationsPreserveAxisAlignment();
2391 UpdateRenderSurface(layer, can_render_to_separate_surface,
2392 &transform_for_children, &draw_transform_is_axis_aligned);
2394 for (size_t i = 0; i < layer->children().size(); ++i) {
2395 UpdateRenderSurfaces(layer->children()[i].get(),
2396 can_render_to_separate_surface, transform_for_children,
2397 draw_transform_is_axis_aligned);
2401 static bool ApproximatelyEqual(const gfx::Rect& r1, const gfx::Rect& r2) {
2402 // TODO(vollick): This tolerance should be lower: crbug.com/471786
2403 static const int tolerance = 3;
2405 if (r1.IsEmpty())
2406 return std::min(r2.width(), r2.height()) < tolerance;
2408 if (r2.IsEmpty())
2409 return std::min(r1.width(), r1.height()) < tolerance;
2411 return std::abs(r1.x() - r2.x()) <= tolerance &&
2412 std::abs(r1.y() - r2.y()) <= tolerance &&
2413 std::abs(r1.right() - r2.right()) <= tolerance &&
2414 std::abs(r1.bottom() - r2.bottom()) <= tolerance;
2417 static bool ApproximatelyEqual(const gfx::Transform& a,
2418 const gfx::Transform& b) {
2419 static const float component_tolerance = 0.1f;
2421 // We may have a larger discrepancy in the scroll components due to snapping
2422 // (floating point error might round the other way).
2423 static const float translation_tolerance = 1.f;
2425 for (int row = 0; row < 4; row++) {
2426 for (int col = 0; col < 4; col++) {
2427 const float delta =
2428 std::abs(a.matrix().get(row, col) - b.matrix().get(row, col));
2429 const float tolerance =
2430 col == 3 && row < 3 ? translation_tolerance : component_tolerance;
2431 if (delta > tolerance)
2432 return false;
2436 return true;
2439 void VerifyPropertyTreeValuesForSurface(RenderSurfaceImpl* render_surface,
2440 PropertyTrees* property_trees) {
2441 const bool render_surface_draw_transforms_match =
2442 ApproximatelyEqual(render_surface->draw_transform(),
2443 DrawTransformOfRenderSurfaceFromPropertyTrees(
2444 render_surface, property_trees->transform_tree));
2445 CHECK(render_surface_draw_transforms_match)
2446 << "expected: " << render_surface->draw_transform().ToString()
2447 << " actual: "
2448 << DrawTransformOfRenderSurfaceFromPropertyTrees(
2449 render_surface, property_trees->transform_tree)
2450 .ToString();
2453 void VerifyPropertyTreeValuesForLayer(LayerImpl* current_layer,
2454 PropertyTrees* property_trees,
2455 bool layers_always_allowed_lcd_text,
2456 bool can_use_lcd_text) {
2457 const bool visible_rects_match =
2458 ApproximatelyEqual(current_layer->visible_layer_rect(),
2459 current_layer->visible_rect_from_property_trees());
2460 CHECK(visible_rects_match)
2461 << "expected: " << current_layer->visible_layer_rect().ToString()
2462 << " actual: "
2463 << current_layer->visible_rect_from_property_trees().ToString();
2465 const bool draw_transforms_match =
2466 ApproximatelyEqual(current_layer->draw_transform(),
2467 DrawTransformFromPropertyTrees(
2468 current_layer, property_trees->transform_tree));
2469 CHECK(draw_transforms_match)
2470 << "expected: " << current_layer->draw_transform().ToString()
2471 << " actual: "
2472 << DrawTransformFromPropertyTrees(
2473 current_layer, property_trees->transform_tree).ToString();
2475 const bool draw_opacities_match =
2476 current_layer->draw_opacity() ==
2477 DrawOpacityFromPropertyTrees(current_layer, property_trees->opacity_tree);
2478 CHECK(draw_opacities_match)
2479 << "expected: " << current_layer->draw_opacity()
2480 << " actual: " << DrawOpacityFromPropertyTrees(
2481 current_layer, property_trees->opacity_tree);
2483 const bool can_use_lcd_text_match =
2484 CanUseLcdTextFromPropertyTrees(
2485 current_layer, layers_always_allowed_lcd_text, can_use_lcd_text,
2486 property_trees) == current_layer->can_use_lcd_text();
2487 CHECK(can_use_lcd_text_match);
2489 CHECK_EQ(current_layer->screen_space_transform_is_animating(),
2490 ScreenSpaceTransformIsAnimatingFromPropertyTrees(
2491 current_layer, property_trees->transform_tree));
2494 void VerifyPropertyTreeValues(
2495 LayerTreeHostCommon::CalcDrawPropsMainInputs* inputs) {
2498 void VerifyPropertyTreeValues(
2499 LayerTreeHostCommon::CalcDrawPropsImplInputs* inputs) {
2500 LayerIterator it, end;
2501 for (it = LayerIterator::Begin(inputs->render_surface_layer_list),
2502 end = LayerIterator::End(inputs->render_surface_layer_list);
2503 it != end; ++it) {
2504 LayerImpl* current_layer = *it;
2505 if (it.represents_target_render_surface())
2506 VerifyPropertyTreeValuesForSurface(current_layer->render_surface(),
2507 inputs->property_trees);
2508 if (!it.represents_itself() || !current_layer->DrawsContent())
2509 continue;
2510 VerifyPropertyTreeValuesForLayer(current_layer, inputs->property_trees,
2511 inputs->layers_always_allowed_lcd_text,
2512 inputs->can_use_lcd_text);
2516 enum PropertyTreeOption {
2517 BUILD_PROPERTY_TREES_IF_NEEDED,
2518 DONT_BUILD_PROPERTY_TREES
2521 template <typename LayerType, typename RenderSurfaceLayerListType>
2522 void CalculateDrawPropertiesAndVerify(LayerTreeHostCommon::CalcDrawPropsInputs<
2523 LayerType,
2524 RenderSurfaceLayerListType>* inputs,
2525 PropertyTreeOption property_tree_option) {
2526 typename LayerType::LayerListType dummy_layer_list;
2527 SubtreeGlobals<LayerType> globals;
2528 DataForRecursion<LayerType> data_for_recursion;
2530 ProcessCalcDrawPropsInputs(*inputs, &globals, &data_for_recursion);
2531 UpdateMetaInformationSequenceNumber(inputs->root_layer);
2532 PreCalculateMetaInformationRecursiveData recursive_data;
2533 PreCalculateMetaInformationInternal(inputs->root_layer, &recursive_data);
2535 const bool should_measure_property_tree_performance =
2536 inputs->verify_property_trees &&
2537 (property_tree_option == BUILD_PROPERTY_TREES_IF_NEEDED);
2539 if (inputs->verify_property_trees) {
2540 typename LayerType::LayerListType update_layer_list;
2542 // For testing purposes, sometimes property trees need to be built on the
2543 // compositor thread, so this can't just switch on Layer vs LayerImpl,
2544 // even though in practice only the main thread builds property trees.
2545 switch (property_tree_option) {
2546 case BUILD_PROPERTY_TREES_IF_NEEDED: {
2547 // The translation from layer to property trees is an intermediate
2548 // state. We will eventually get these data passed directly to the
2549 // compositor.
2550 if (should_measure_property_tree_performance) {
2551 TRACE_EVENT_BEGIN0(
2552 TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2553 "LayerTreeHostCommon::ComputeVisibleRectsWithPropertyTrees");
2556 BuildPropertyTreesAndComputeVisibleRects(
2557 inputs->root_layer, inputs->page_scale_layer,
2558 inputs->inner_viewport_scroll_layer,
2559 inputs->outer_viewport_scroll_layer, inputs->page_scale_factor,
2560 inputs->device_scale_factor,
2561 gfx::Rect(inputs->device_viewport_size), inputs->device_transform,
2562 inputs->property_trees, &update_layer_list);
2564 if (should_measure_property_tree_performance) {
2565 TRACE_EVENT_END0(
2566 TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2567 "LayerTreeHostCommon::ComputeVisibleRectsWithPropertyTrees");
2570 break;
2572 case DONT_BUILD_PROPERTY_TREES: {
2573 TRACE_EVENT0(
2574 TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2575 "LayerTreeHostCommon::ComputeJustVisibleRectsWithPropertyTrees");
2576 ComputeVisibleRectsUsingPropertyTrees(
2577 inputs->root_layer, inputs->property_trees, &update_layer_list);
2578 break;
2583 if (should_measure_property_tree_performance) {
2584 TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2585 "LayerTreeHostCommon::CalculateDrawProperties");
2588 std::vector<AccumulatedSurfaceState<LayerType>> accumulated_surface_state;
2589 CalculateDrawPropertiesInternal<LayerType>(
2590 inputs->root_layer, globals, data_for_recursion,
2591 inputs->render_surface_layer_list, &dummy_layer_list,
2592 &accumulated_surface_state, inputs->current_render_surface_layer_list_id);
2594 if (should_measure_property_tree_performance) {
2595 TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2596 "LayerTreeHostCommon::CalculateDrawProperties");
2599 if (inputs->verify_property_trees)
2600 VerifyPropertyTreeValues(inputs);
2602 // The dummy layer list should not have been used.
2603 DCHECK_EQ(0u, dummy_layer_list.size());
2604 // A root layer render_surface should always exist after
2605 // CalculateDrawProperties.
2606 DCHECK(inputs->root_layer->render_surface());
2609 void LayerTreeHostCommon::CalculateDrawProperties(
2610 CalcDrawPropsMainInputs* inputs) {
2611 UpdateRenderSurfaces(inputs->root_layer,
2612 inputs->can_render_to_separate_surface, gfx::Transform(),
2613 false);
2614 CalculateDrawPropertiesAndVerify(inputs, BUILD_PROPERTY_TREES_IF_NEEDED);
2617 void LayerTreeHostCommon::CalculateDrawProperties(
2618 CalcDrawPropsImplInputs* inputs) {
2619 CalculateDrawPropertiesAndVerify(inputs, DONT_BUILD_PROPERTY_TREES);
2622 void LayerTreeHostCommon::CalculateDrawProperties(
2623 CalcDrawPropsImplInputsForTesting* inputs) {
2624 CalculateDrawPropertiesAndVerify(inputs, BUILD_PROPERTY_TREES_IF_NEEDED);
2627 PropertyTrees* GetPropertyTrees(Layer* layer) {
2628 return layer->layer_tree_host()->property_trees();
2631 PropertyTrees* GetPropertyTrees(LayerImpl* layer) {
2632 return layer->layer_tree_impl()->property_trees();
2635 } // namespace cc