Upstream version 11.40.277.0
[platform/framework/web/crosswalk.git] / src / cc / trees / layer_tree_host_common.cc
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.
4
5 #include "cc/trees/layer_tree_host_common.h"
6
7 #include <algorithm>
8
9 #include "base/debug/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/layer_sorter.h"
18 #include "cc/trees/layer_tree_impl.h"
19 #include "ui/gfx/geometry/rect_conversions.h"
20 #include "ui/gfx/transform.h"
21
22 namespace cc {
23
24 ScrollAndScaleSet::ScrollAndScaleSet()
25     : page_scale_delta(1.f), top_controls_delta(0.f) {
26 }
27
28 ScrollAndScaleSet::~ScrollAndScaleSet() {}
29
30 static void SortLayers(LayerList::iterator forst,
31                        LayerList::iterator end,
32                        void* layer_sorter) {
33   NOTREACHED();
34 }
35
36 static void SortLayers(LayerImplList::iterator first,
37                        LayerImplList::iterator end,
38                        LayerSorter* layer_sorter) {
39   DCHECK(layer_sorter);
40   TRACE_EVENT0("cc", "LayerTreeHostCommon::SortLayers");
41   layer_sorter->Sort(first, end);
42 }
43
44 template <typename LayerType>
45 static gfx::Vector2dF GetEffectiveScrollDelta(LayerType* layer) {
46   gfx::Vector2dF scroll_delta = layer->ScrollDelta();
47   // The scroll parent's scroll delta is the amount we've scrolled on the
48   // compositor thread since the commit for this layer tree's source frame.
49   // we last reported to the main thread. I.e., it's the discrepancy between
50   // a scroll parent's scroll delta and offset, so we must add it here.
51   if (layer->scroll_parent())
52     scroll_delta += layer->scroll_parent()->ScrollDelta();
53   return scroll_delta;
54 }
55
56 template <typename LayerType>
57 static gfx::ScrollOffset GetEffectiveTotalScrollOffset(LayerType* layer) {
58   gfx::ScrollOffset offset = layer->TotalScrollOffset();
59   // The scroll parent's total scroll offset (scroll offset + scroll delta)
60   // can't be used because its scroll offset has already been applied to the
61   // scroll children's positions by the main thread layer positioning code.
62   if (layer->scroll_parent())
63     offset += gfx::ScrollOffset(layer->scroll_parent()->ScrollDelta());
64   return offset;
65 }
66
67 inline gfx::Rect CalculateVisibleRectWithCachedLayerRect(
68     const gfx::Rect& target_surface_rect,
69     const gfx::Rect& layer_bound_rect,
70     const gfx::Rect& layer_rect_in_target_space,
71     const gfx::Transform& transform) {
72   if (layer_rect_in_target_space.IsEmpty())
73     return gfx::Rect();
74
75   // Is this layer fully contained within the target surface?
76   if (target_surface_rect.Contains(layer_rect_in_target_space))
77     return layer_bound_rect;
78
79   // If the layer doesn't fill up the entire surface, then find the part of
80   // the surface rect where the layer could be visible. This avoids trying to
81   // project surface rect points that are behind the projection point.
82   gfx::Rect minimal_surface_rect = target_surface_rect;
83   minimal_surface_rect.Intersect(layer_rect_in_target_space);
84
85   if (minimal_surface_rect.IsEmpty())
86     return gfx::Rect();
87
88   // Project the corners of the target surface rect into the layer space.
89   // This bounding rectangle may be larger than it needs to be (being
90   // axis-aligned), but is a reasonable filter on the space to consider.
91   // Non-invertible transforms will create an empty rect here.
92
93   gfx::Transform surface_to_layer(gfx::Transform::kSkipInitialization);
94   if (!transform.GetInverse(&surface_to_layer)) {
95     // Because we cannot use the surface bounds to determine what portion of
96     // the layer is visible, we must conservatively assume the full layer is
97     // visible.
98     return layer_bound_rect;
99   }
100
101   gfx::Rect layer_rect = MathUtil::ProjectEnclosingClippedRect(
102       surface_to_layer, minimal_surface_rect);
103   layer_rect.Intersect(layer_bound_rect);
104   return layer_rect;
105 }
106
107 gfx::Rect LayerTreeHostCommon::CalculateVisibleRect(
108     const gfx::Rect& target_surface_rect,
109     const gfx::Rect& layer_bound_rect,
110     const gfx::Transform& transform) {
111   gfx::Rect layer_in_surface_space =
112       MathUtil::MapEnclosingClippedRect(transform, layer_bound_rect);
113   return CalculateVisibleRectWithCachedLayerRect(
114       target_surface_rect, layer_bound_rect, layer_in_surface_space, transform);
115 }
116
117 template <typename LayerType>
118 static LayerType* NextTargetSurface(LayerType* layer) {
119   return layer->parent() ? layer->parent()->render_target() : 0;
120 }
121
122 // Given two layers, this function finds their respective render targets and,
123 // computes a change of basis translation. It does this by accumulating the
124 // translation components of the draw transforms of each target between the
125 // ancestor and descendant. These transforms must be 2D translations, and this
126 // requirement is enforced at every step.
127 template <typename LayerType>
128 static gfx::Vector2dF ComputeChangeOfBasisTranslation(
129     const LayerType& ancestor_layer,
130     const LayerType& descendant_layer) {
131   DCHECK(descendant_layer.HasAncestor(&ancestor_layer));
132   const LayerType* descendant_target = descendant_layer.render_target();
133   DCHECK(descendant_target);
134   const LayerType* ancestor_target = ancestor_layer.render_target();
135   DCHECK(ancestor_target);
136
137   gfx::Vector2dF translation;
138   for (const LayerType* target = descendant_target; target != ancestor_target;
139        target = NextTargetSurface(target)) {
140     const gfx::Transform& trans = target->render_surface()->draw_transform();
141     // Ensure that this translation is truly 2d.
142     DCHECK(trans.IsIdentityOrTranslation());
143     DCHECK_EQ(0.f, trans.matrix().get(2, 3));
144     translation += trans.To2dTranslation();
145   }
146
147   return translation;
148 }
149
150 enum TranslateRectDirection {
151   TranslateRectDirectionToAncestor,
152   TranslateRectDirectionToDescendant
153 };
154
155 template <typename LayerType>
156 static gfx::Rect TranslateRectToTargetSpace(const LayerType& ancestor_layer,
157                                             const LayerType& descendant_layer,
158                                             const gfx::Rect& rect,
159                                             TranslateRectDirection direction) {
160   gfx::Vector2dF translation = ComputeChangeOfBasisTranslation<LayerType>(
161       ancestor_layer, descendant_layer);
162   if (direction == TranslateRectDirectionToDescendant)
163     translation.Scale(-1.f);
164   return gfx::ToEnclosingRect(
165       gfx::RectF(rect.origin() + translation, rect.size()));
166 }
167
168 // Attempts to update the clip rects for the given layer. If the layer has a
169 // clip_parent, it may not inherit its immediate ancestor's clip.
170 template <typename LayerType>
171 static void UpdateClipRectsForClipChild(
172     const LayerType* layer,
173     gfx::Rect* clip_rect_in_parent_target_space,
174     bool* subtree_should_be_clipped) {
175   // If the layer has no clip_parent, or the ancestor is the same as its actual
176   // parent, then we don't need special clip rects. Bail now and leave the out
177   // parameters untouched.
178   const LayerType* clip_parent = layer->scroll_parent();
179
180   if (!clip_parent)
181     clip_parent = layer->clip_parent();
182
183   if (!clip_parent || clip_parent == layer->parent())
184     return;
185
186   // The root layer is never a clip child.
187   DCHECK(layer->parent());
188
189   // Grab the cached values.
190   *clip_rect_in_parent_target_space = clip_parent->clip_rect();
191   *subtree_should_be_clipped = clip_parent->is_clipped();
192
193   // We may have to project the clip rect into our parent's target space. Note,
194   // it must be our parent's target space, not ours. For one, we haven't
195   // computed our transforms, so we couldn't put it in our space yet even if we
196   // wanted to. But more importantly, this matches the expectations of
197   // CalculateDrawPropertiesInternal. If we, say, create a render surface, these
198   // clip rects will want to be in its target space, not ours.
199   if (clip_parent == layer->clip_parent()) {
200     *clip_rect_in_parent_target_space = TranslateRectToTargetSpace<LayerType>(
201         *clip_parent,
202         *layer->parent(),
203         *clip_rect_in_parent_target_space,
204         TranslateRectDirectionToDescendant);
205   } else {
206     // If we're being clipped by our scroll parent, we must translate through
207     // our common ancestor. This happens to be our parent, so it is sufficent to
208     // translate from our clip parent's space to the space of its ancestor (our
209     // parent).
210     *clip_rect_in_parent_target_space =
211         TranslateRectToTargetSpace<LayerType>(*layer->parent(),
212                                               *clip_parent,
213                                               *clip_rect_in_parent_target_space,
214                                               TranslateRectDirectionToAncestor);
215   }
216 }
217
218 // We collect an accumulated drawable content rect per render surface.
219 // Typically, a layer will contribute to only one surface, the surface
220 // associated with its render target. Clip children, however, may affect
221 // several surfaces since there may be several surfaces between the clip child
222 // and its parent.
223 //
224 // NB: we accumulate the layer's *clipped* drawable content rect.
225 template <typename LayerType>
226 struct AccumulatedSurfaceState {
227   explicit AccumulatedSurfaceState(LayerType* render_target)
228       : render_target(render_target) {}
229
230   // The accumulated drawable content rect for the surface associated with the
231   // given |render_target|.
232   gfx::Rect drawable_content_rect;
233
234   // The target owning the surface. (We hang onto the target rather than the
235   // surface so that we can DCHECK that the surface's draw transform is simply
236   // a translation when |render_target| reports that it has no unclipped
237   // descendants).
238   LayerType* render_target;
239 };
240
241 template <typename LayerType>
242 void UpdateAccumulatedSurfaceState(
243     LayerType* layer,
244     const gfx::Rect& drawable_content_rect,
245     std::vector<AccumulatedSurfaceState<LayerType>>*
246         accumulated_surface_state) {
247   if (IsRootLayer(layer))
248     return;
249
250   // We will apply our drawable content rect to the accumulated rects for all
251   // surfaces between us and |render_target| (inclusive). This is either our
252   // clip parent's target if we are a clip child, or else simply our parent's
253   // target. We use our parent's target because we're either the owner of a
254   // render surface and we'll want to add our rect to our *surface's* target, or
255   // we're not and our target is the same as our parent's. In both cases, the
256   // parent's target gives us what we want.
257   LayerType* render_target = layer->clip_parent()
258                                  ? layer->clip_parent()->render_target()
259                                  : layer->parent()->render_target();
260
261   // If the layer owns a surface, then the content rect is in the wrong space.
262   // Instead, we will use the surface's DrawableContentRect which is in target
263   // space as required.
264   gfx::Rect target_rect = drawable_content_rect;
265   if (layer->render_surface()) {
266     target_rect =
267         gfx::ToEnclosedRect(layer->render_surface()->DrawableContentRect());
268   }
269
270   if (render_target->is_clipped()) {
271     gfx::Rect clip_rect = render_target->clip_rect();
272     // If the layer has a clip parent, the clip rect may be in the wrong space,
273     // so we'll need to transform it before it is applied.
274     if (layer->clip_parent()) {
275       clip_rect = TranslateRectToTargetSpace<LayerType>(
276           *layer->clip_parent(),
277           *layer,
278           clip_rect,
279           TranslateRectDirectionToDescendant);
280     }
281     target_rect.Intersect(clip_rect);
282   }
283
284   // We must have at least one entry in the vector for the root.
285   DCHECK_LT(0ul, accumulated_surface_state->size());
286
287   typedef typename std::vector<AccumulatedSurfaceState<LayerType>>
288       AccumulatedSurfaceStateVector;
289   typedef typename AccumulatedSurfaceStateVector::reverse_iterator
290       AccumulatedSurfaceStateIterator;
291   AccumulatedSurfaceStateIterator current_state =
292       accumulated_surface_state->rbegin();
293
294   // Add this rect to the accumulated content rect for all surfaces until we
295   // reach the target surface.
296   bool found_render_target = false;
297   for (; current_state != accumulated_surface_state->rend(); ++current_state) {
298     current_state->drawable_content_rect.Union(target_rect);
299
300     // If we've reached |render_target| our work is done and we can bail.
301     if (current_state->render_target == render_target) {
302       found_render_target = true;
303       break;
304     }
305
306     // Transform rect from the current target's space to the next.
307     LayerType* current_target = current_state->render_target;
308     DCHECK(current_target->render_surface());
309     const gfx::Transform& current_draw_transform =
310          current_target->render_surface()->draw_transform();
311
312     // If we have unclipped descendants, the draw transform is a translation.
313     DCHECK(current_target->num_unclipped_descendants() == 0 ||
314            current_draw_transform.IsIdentityOrTranslation());
315
316     target_rect = gfx::ToEnclosingRect(
317         MathUtil::MapClippedRect(current_draw_transform, target_rect));
318   }
319
320   // It is an error to not reach |render_target|. If this happens, it means that
321   // either the clip parent is not an ancestor of the clip child or the surface
322   // state vector is empty, both of which should be impossible.
323   DCHECK(found_render_target);
324 }
325
326 template <typename LayerType> static inline bool IsRootLayer(LayerType* layer) {
327   return !layer->parent();
328 }
329
330 template <typename LayerType>
331 static inline bool LayerIsInExisting3DRenderingContext(LayerType* layer) {
332   return layer->Is3dSorted() && layer->parent() &&
333          layer->parent()->Is3dSorted();
334 }
335
336 template <typename LayerType>
337 static bool IsRootLayerOfNewRenderingContext(LayerType* layer) {
338   if (layer->parent())
339     return !layer->parent()->Is3dSorted() && layer->Is3dSorted();
340
341   return layer->Is3dSorted();
342 }
343
344 template <typename LayerType>
345 static bool IsLayerBackFaceVisible(LayerType* layer) {
346   // The current W3C spec on CSS transforms says that backface visibility should
347   // be determined differently depending on whether the layer is in a "3d
348   // rendering context" or not. For Chromium code, we can determine whether we
349   // are in a 3d rendering context by checking if the parent preserves 3d.
350
351   if (LayerIsInExisting3DRenderingContext(layer))
352     return layer->draw_transform().IsBackFaceVisible();
353
354   // In this case, either the layer establishes a new 3d rendering context, or
355   // is not in a 3d rendering context at all.
356   return layer->transform().IsBackFaceVisible();
357 }
358
359 template <typename LayerType>
360 static bool IsSurfaceBackFaceVisible(LayerType* layer,
361                                      const gfx::Transform& draw_transform) {
362   if (LayerIsInExisting3DRenderingContext(layer))
363     return draw_transform.IsBackFaceVisible();
364
365   if (IsRootLayerOfNewRenderingContext(layer))
366     return layer->transform().IsBackFaceVisible();
367
368   // If the render_surface is not part of a new or existing rendering context,
369   // then the layers that contribute to this surface will decide back-face
370   // visibility for themselves.
371   return false;
372 }
373
374 template <typename LayerType>
375 static inline bool LayerClipsSubtree(LayerType* layer) {
376   return layer->masks_to_bounds() || layer->mask_layer();
377 }
378
379 template <typename LayerType>
380 static gfx::Rect CalculateVisibleContentRect(
381     LayerType* layer,
382     const gfx::Rect& clip_rect_of_target_surface_in_target_space,
383     const gfx::Rect& layer_rect_in_target_space) {
384   DCHECK(layer->render_target());
385
386   // Nothing is visible if the layer bounds are empty.
387   if (!layer->DrawsContent() || layer->content_bounds().IsEmpty() ||
388       layer->drawable_content_rect().IsEmpty())
389     return gfx::Rect();
390
391   // Compute visible bounds in target surface space.
392   gfx::Rect visible_rect_in_target_surface_space =
393       layer->drawable_content_rect();
394
395   if (!layer->render_target()->render_surface()->clip_rect().IsEmpty()) {
396     // The |layer| L has a target T which owns a surface Ts. The surface Ts
397     // has a target TsT.
398     //
399     // In this case the target surface Ts does clip the layer L that contributes
400     // to it. So, we have to convert the clip rect of Ts from the target space
401     // of Ts (that is the space of TsT), to the current render target's space
402     // (that is the space of T). This conversion is done outside this function
403     // so that it can be cached instead of computing it redundantly for every
404     // layer.
405     visible_rect_in_target_surface_space.Intersect(
406         clip_rect_of_target_surface_in_target_space);
407   }
408
409   if (visible_rect_in_target_surface_space.IsEmpty())
410     return gfx::Rect();
411
412   return CalculateVisibleRectWithCachedLayerRect(
413       visible_rect_in_target_surface_space,
414       gfx::Rect(layer->content_bounds()),
415       layer_rect_in_target_space,
416       layer->draw_transform());
417 }
418
419 static inline bool TransformToParentIsKnown(LayerImpl* layer) { return true; }
420
421 static inline bool TransformToParentIsKnown(Layer* layer) {
422   return !layer->TransformIsAnimating();
423 }
424
425 static inline bool TransformToScreenIsKnown(LayerImpl* layer) { return true; }
426
427 static inline bool TransformToScreenIsKnown(Layer* layer) {
428   return !layer->screen_space_transform_is_animating();
429 }
430
431 template <typename LayerType>
432 static bool LayerShouldBeSkipped(LayerType* layer, bool layer_is_drawn) {
433   // Layers can be skipped if any of these conditions are met.
434   //   - is not drawn due to it or one of its ancestors being hidden (or having
435   //     no copy requests).
436   //   - does not draw content.
437   //   - is transparent.
438   //   - has empty bounds
439   //   - the layer is not double-sided, but its back face is visible.
440   //
441   // Some additional conditions need to be computed at a later point after the
442   // recursion is finished.
443   //   - the intersection of render_surface content and layer clip_rect is empty
444   //   - the visible_content_rect is empty
445   //
446   // Note, if the layer should not have been drawn due to being fully
447   // transparent, we would have skipped the entire subtree and never made it
448   // into this function, so it is safe to omit this check here.
449
450   if (!layer_is_drawn)
451     return true;
452
453   if (!layer->DrawsContent() || layer->bounds().IsEmpty())
454     return true;
455
456   LayerType* backface_test_layer = layer;
457   if (layer->use_parent_backface_visibility()) {
458     DCHECK(layer->parent());
459     DCHECK(!layer->parent()->use_parent_backface_visibility());
460     backface_test_layer = layer->parent();
461   }
462
463   // The layer should not be drawn if (1) it is not double-sided and (2) the
464   // back of the layer is known to be facing the screen.
465   if (!backface_test_layer->double_sided() &&
466       TransformToScreenIsKnown(backface_test_layer) &&
467       IsLayerBackFaceVisible(backface_test_layer))
468     return true;
469
470   return false;
471 }
472
473 template <typename LayerType>
474 static bool HasInvertibleOrAnimatedTransform(LayerType* layer) {
475   return layer->transform_is_invertible() || layer->TransformIsAnimating();
476 }
477
478 static inline bool SubtreeShouldBeSkipped(LayerImpl* layer,
479                                           bool layer_is_drawn) {
480   // If the layer transform is not invertible, it should not be drawn.
481   // TODO(ajuma): Correctly process subtrees with singular transform for the
482   // case where we may animate to a non-singular transform and wish to
483   // pre-raster.
484   if (!HasInvertibleOrAnimatedTransform(layer))
485     return true;
486
487   // When we need to do a readback/copy of a layer's output, we can not skip
488   // it or any of its ancestors.
489   if (layer->draw_properties().layer_or_descendant_has_copy_request)
490     return false;
491
492   // We cannot skip the the subtree if a descendant has a wheel or touch handler
493   // or the hit testing code will break (it requires fresh transforms, etc).
494   if (layer->draw_properties().layer_or_descendant_has_input_handler)
495     return false;
496
497   // If the layer is not drawn, then skip it and its subtree.
498   if (!layer_is_drawn)
499     return true;
500
501   // If layer is on the pending tree and opacity is being animated then
502   // this subtree can't be skipped as we need to create, prioritize and
503   // include tiles for this layer when deciding if tree can be activated.
504   if (layer->layer_tree_impl()->IsPendingTree() && layer->OpacityIsAnimating())
505     return false;
506
507   // The opacity of a layer always applies to its children (either implicitly
508   // via a render surface or explicitly if the parent preserves 3D), so the
509   // entire subtree can be skipped if this layer is fully transparent.
510   return !layer->opacity();
511 }
512
513 static inline bool SubtreeShouldBeSkipped(Layer* layer, bool layer_is_drawn) {
514   // If the layer transform is not invertible, it should not be drawn.
515   if (!layer->transform_is_invertible() && !layer->TransformIsAnimating())
516     return true;
517
518   // When we need to do a readback/copy of a layer's output, we can not skip
519   // it or any of its ancestors.
520   if (layer->draw_properties().layer_or_descendant_has_copy_request)
521     return false;
522
523   // We cannot skip the the subtree if a descendant has a wheel or touch handler
524   // or the hit testing code will break (it requires fresh transforms, etc).
525   if (layer->draw_properties().layer_or_descendant_has_input_handler)
526     return false;
527
528   // If the layer is not drawn, then skip it and its subtree.
529   if (!layer_is_drawn)
530     return true;
531
532   // If the opacity is being animated then the opacity on the main thread is
533   // unreliable (since the impl thread may be using a different opacity), so it
534   // should not be trusted.
535   // In particular, it should not cause the subtree to be skipped.
536   // Similarly, for layers that might animate opacity using an impl-only
537   // animation, their subtree should also not be skipped.
538   return !layer->opacity() && !layer->OpacityIsAnimating() &&
539          !layer->OpacityCanAnimateOnImplThread();
540 }
541
542 static inline void SavePaintPropertiesLayer(LayerImpl* layer) {}
543
544 static inline void SavePaintPropertiesLayer(Layer* layer) {
545   layer->SavePaintProperties();
546
547   if (layer->mask_layer())
548     layer->mask_layer()->SavePaintProperties();
549   if (layer->replica_layer() && layer->replica_layer()->mask_layer())
550     layer->replica_layer()->mask_layer()->SavePaintProperties();
551 }
552
553 template <typename LayerType>
554 static bool SubtreeShouldRenderToSeparateSurface(
555     LayerType* layer,
556     bool axis_aligned_with_respect_to_parent) {
557   //
558   // A layer and its descendants should render onto a new RenderSurfaceImpl if
559   // any of these rules hold:
560   //
561
562   // The root layer owns a render surface, but it never acts as a contributing
563   // surface to another render target. Compositor features that are applied via
564   // a contributing surface can not be applied to the root layer. In order to
565   // use these effects, another child of the root would need to be introduced
566   // in order to act as a contributing surface to the root layer's surface.
567   bool is_root = IsRootLayer(layer);
568
569   // If the layer uses a mask.
570   if (layer->mask_layer()) {
571     DCHECK(!is_root);
572     return true;
573   }
574
575   // If the layer has a reflection.
576   if (layer->replica_layer()) {
577     DCHECK(!is_root);
578     return true;
579   }
580
581   // If the layer uses a CSS filter.
582   if (!layer->filters().IsEmpty() || !layer->background_filters().IsEmpty()) {
583     DCHECK(!is_root);
584     return true;
585   }
586
587   int num_descendants_that_draw_content =
588       layer->NumDescendantsThatDrawContent();
589
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;
601   }
602
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;
614   }
615
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;
628   }
629
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);
638
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;
647   }
648
649   // The root layer should always have a render_surface.
650   if (is_root)
651     return true;
652
653   //
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.
656   //
657
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;
669   }
670
671   // If we force it.
672   if (layer->force_render_surface())
673     return true;
674
675   // If we'll make a copy of the layer's contents.
676   if (layer->HasCopyRequest())
677     return true;
678
679   return false;
680 }
681
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 gfx::Transform ComputeSizeDeltaCompensation(
686     LayerImpl* layer,
687     LayerImpl* container,
688     const gfx::Vector2dF& position_offset) {
689   gfx::Transform result_transform;
690
691   // To apply a translate in the container's layer space,
692   // the following steps need to be done:
693   //     Step 1a. transform from target surface space to the container's target
694   //              surface space
695   //     Step 1b. transform from container's target surface space to the
696   //              container's layer space
697   //     Step 2. apply the compensation
698   //     Step 3. transform back to target surface space
699
700   gfx::Transform target_surface_space_to_container_layer_space;
701   // Calculate step 1a
702   LayerImpl* container_target_surface = container->render_target();
703   for (LayerImpl* current_target_surface = NextTargetSurface(layer);
704       current_target_surface &&
705           current_target_surface != container_target_surface;
706       current_target_surface = NextTargetSurface(current_target_surface)) {
707     // Note: Concat is used here to convert the result coordinate space from
708     //       current render surface to the next render surface.
709     target_surface_space_to_container_layer_space.ConcatTransform(
710         current_target_surface->render_surface()->draw_transform());
711   }
712   // Calculate step 1b
713   gfx::Transform container_layer_space_to_container_target_surface_space =
714       container->draw_transform();
715   container_layer_space_to_container_target_surface_space.Scale(
716       container->contents_scale_x(), container->contents_scale_y());
717
718   gfx::Transform container_target_surface_space_to_container_layer_space;
719   if (container_layer_space_to_container_target_surface_space.GetInverse(
720       &container_target_surface_space_to_container_layer_space)) {
721     // Note: Again, Concat is used to conver the result coordinate space from
722     //       the container render surface to the container layer.
723     target_surface_space_to_container_layer_space.ConcatTransform(
724         container_target_surface_space_to_container_layer_space);
725   }
726
727   // Apply step 3
728   gfx::Transform container_layer_space_to_target_surface_space;
729   if (target_surface_space_to_container_layer_space.GetInverse(
730           &container_layer_space_to_target_surface_space)) {
731     result_transform.PreconcatTransform(
732         container_layer_space_to_target_surface_space);
733   } else {
734     // TODO(shawnsingh): A non-invertible matrix could still make meaningful
735     // projection.  For example ScaleZ(0) is non-invertible but the layer is
736     // still visible.
737     return gfx::Transform();
738   }
739
740   // Apply step 2
741   result_transform.Translate(position_offset.x(), position_offset.y());
742
743   // Apply step 1
744   result_transform.PreconcatTransform(
745       target_surface_space_to_container_layer_space);
746
747   return result_transform;
748 }
749
750 void ApplyPositionAdjustment(
751     Layer* layer,
752     Layer* container,
753     const gfx::Transform& scroll_compensation,
754     gfx::Transform* combined_transform) {}
755 void ApplyPositionAdjustment(
756     LayerImpl* layer,
757     LayerImpl* container,
758     const gfx::Transform& scroll_compensation,
759     gfx::Transform* combined_transform) {
760   if (!layer->position_constraint().is_fixed_position())
761     return;
762
763   // Special case: this layer is a composited fixed-position layer; we need to
764   // explicitly compensate for all ancestors' nonzero scroll_deltas to keep
765   // this layer fixed correctly.
766   // Note carefully: this is Concat, not Preconcat
767   // (current_scroll_compensation * combined_transform).
768   combined_transform->ConcatTransform(scroll_compensation);
769
770   // For right-edge or bottom-edge anchored fixed position layers,
771   // the layer should relocate itself if the container changes its size.
772   bool fixed_to_right_edge =
773       layer->position_constraint().is_fixed_to_right_edge();
774   bool fixed_to_bottom_edge =
775       layer->position_constraint().is_fixed_to_bottom_edge();
776   gfx::Vector2dF position_offset = container->FixedContainerSizeDelta();
777   position_offset.set_x(fixed_to_right_edge ? position_offset.x() : 0);
778   position_offset.set_y(fixed_to_bottom_edge ? position_offset.y() : 0);
779   if (position_offset.IsZero())
780     return;
781
782   // Note: Again, this is Concat. The compensation matrix will be applied on
783   //       the vector in target surface space.
784   combined_transform->ConcatTransform(
785       ComputeSizeDeltaCompensation(layer, container, position_offset));
786 }
787
788 gfx::Transform ComputeScrollCompensationForThisLayer(
789     LayerImpl* scrolling_layer,
790     const gfx::Transform& parent_matrix,
791     const gfx::Vector2dF& scroll_delta) {
792   // For every layer that has non-zero scroll_delta, we have to compute a
793   // transform that can undo the scroll_delta translation. In particular, we
794   // want this matrix to premultiply a fixed-position layer's parent_matrix, so
795   // we design this transform in three steps as follows. The steps described
796   // here apply from right-to-left, so Step 1 would be the right-most matrix:
797   //
798   //     Step 1. transform from target surface space to the exact space where
799   //           scroll_delta is actually applied.
800   //           -- this is inverse of parent_matrix
801   //     Step 2. undo the scroll_delta
802   //           -- this is just a translation by scroll_delta.
803   //     Step 3. transform back to target surface space.
804   //           -- this transform is the parent_matrix
805   //
806   // These steps create a matrix that both start and end in target surface
807   // space. So this matrix can pre-multiply any fixed-position layer's
808   // draw_transform to undo the scroll_deltas -- as long as that fixed position
809   // layer is fixed onto the same render_target as this scrolling_layer.
810   //
811
812   gfx::Transform scroll_compensation_for_this_layer = parent_matrix;  // Step 3
813   scroll_compensation_for_this_layer.Translate(
814       scroll_delta.x(),
815       scroll_delta.y());  // Step 2
816
817   gfx::Transform inverse_parent_matrix(gfx::Transform::kSkipInitialization);
818   if (!parent_matrix.GetInverse(&inverse_parent_matrix)) {
819     // TODO(shawnsingh): Either we need to handle uninvertible transforms
820     // here, or DCHECK that the transform is invertible.
821   }
822   scroll_compensation_for_this_layer.PreconcatTransform(
823       inverse_parent_matrix);  // Step 1
824   return scroll_compensation_for_this_layer;
825 }
826
827 gfx::Transform ComputeScrollCompensationMatrixForChildren(
828     Layer* current_layer,
829     const gfx::Transform& current_parent_matrix,
830     const gfx::Transform& current_scroll_compensation,
831     const gfx::Vector2dF& scroll_delta) {
832   // The main thread (i.e. Layer) does not need to worry about scroll
833   // compensation.  So we can just return an identity matrix here.
834   return gfx::Transform();
835 }
836
837 gfx::Transform ComputeScrollCompensationMatrixForChildren(
838     LayerImpl* layer,
839     const gfx::Transform& parent_matrix,
840     const gfx::Transform& current_scroll_compensation_matrix,
841     const gfx::Vector2dF& scroll_delta) {
842   // "Total scroll compensation" is the transform needed to cancel out all
843   // scroll_delta translations that occurred since the nearest container layer,
844   // even if there are render_surfaces in-between.
845   //
846   // There are some edge cases to be aware of, that are not explicit in the
847   // code:
848   //  - A layer that is both a fixed-position and container should not be its
849   //  own container, instead, that means it is fixed to an ancestor, and is a
850   //  container for any fixed-position descendants.
851   //  - A layer that is a fixed-position container and has a render_surface
852   //  should behave the same as a container without a render_surface, the
853   //  render_surface is irrelevant in that case.
854   //  - A layer that does not have an explicit container is simply fixed to the
855   //  viewport.  (i.e. the root render_surface.)
856   //  - If the fixed-position layer has its own render_surface, then the
857   //  render_surface is the one who gets fixed.
858   //
859   // This function needs to be called AFTER layers create their own
860   // render_surfaces.
861   //
862
863   // Scroll compensation restarts from identity under two possible conditions:
864   //  - the current layer is a container for fixed-position descendants
865   //  - the current layer is fixed-position itself, so any fixed-position
866   //    descendants are positioned with respect to this layer. Thus, any
867   //    fixed position descendants only need to compensate for scrollDeltas
868   //    that occur below this layer.
869   bool current_layer_resets_scroll_compensation_for_descendants =
870       layer->IsContainerForFixedPositionLayers() ||
871       layer->position_constraint().is_fixed_position();
872
873   // Avoid the overheads (including stack allocation and matrix
874   // initialization/copy) if we know that the scroll compensation doesn't need
875   // to be reset or adjusted.
876   if (!current_layer_resets_scroll_compensation_for_descendants &&
877       scroll_delta.IsZero() && !layer->render_surface())
878     return current_scroll_compensation_matrix;
879
880   // Start as identity matrix.
881   gfx::Transform next_scroll_compensation_matrix;
882
883   // If this layer does not reset scroll compensation, then it inherits the
884   // existing scroll compensations.
885   if (!current_layer_resets_scroll_compensation_for_descendants)
886     next_scroll_compensation_matrix = current_scroll_compensation_matrix;
887
888   // If the current layer has a non-zero scroll_delta, then we should compute
889   // its local scroll compensation and accumulate it to the
890   // next_scroll_compensation_matrix.
891   if (!scroll_delta.IsZero()) {
892     gfx::Transform scroll_compensation_for_this_layer =
893         ComputeScrollCompensationForThisLayer(
894             layer, parent_matrix, scroll_delta);
895     next_scroll_compensation_matrix.PreconcatTransform(
896         scroll_compensation_for_this_layer);
897   }
898
899   // If the layer created its own render_surface, we have to adjust
900   // next_scroll_compensation_matrix.  The adjustment allows us to continue
901   // using the scroll compensation on the next surface.
902   //  Step 1 (right-most in the math): transform from the new surface to the
903   //  original ancestor surface
904   //  Step 2: apply the scroll compensation
905   //  Step 3: transform back to the new surface.
906   if (layer->render_surface() &&
907       !next_scroll_compensation_matrix.IsIdentity()) {
908     gfx::Transform inverse_surface_draw_transform(
909         gfx::Transform::kSkipInitialization);
910     if (!layer->render_surface()->draw_transform().GetInverse(
911             &inverse_surface_draw_transform)) {
912       // TODO(shawnsingh): Either we need to handle uninvertible transforms
913       // here, or DCHECK that the transform is invertible.
914     }
915     next_scroll_compensation_matrix =
916         inverse_surface_draw_transform * next_scroll_compensation_matrix *
917         layer->render_surface()->draw_transform();
918   }
919
920   return next_scroll_compensation_matrix;
921 }
922
923 template <typename LayerType>
924 static inline void UpdateLayerScaleDrawProperties(
925     LayerType* layer,
926     float ideal_contents_scale,
927     float maximum_animation_contents_scale,
928     float page_scale_factor,
929     float device_scale_factor) {
930   layer->draw_properties().ideal_contents_scale = ideal_contents_scale;
931   layer->draw_properties().maximum_animation_contents_scale =
932       maximum_animation_contents_scale;
933   layer->draw_properties().page_scale_factor = page_scale_factor;
934   layer->draw_properties().device_scale_factor = device_scale_factor;
935 }
936
937 static inline void CalculateContentsScale(LayerImpl* layer,
938                                           float contents_scale) {
939   // LayerImpl has all of its content scales and bounds pushed from the Main
940   // thread during commit and just uses those values as-is.
941 }
942
943 static inline void CalculateContentsScale(Layer* layer, float contents_scale) {
944   layer->CalculateContentsScale(contents_scale,
945                                 &layer->draw_properties().contents_scale_x,
946                                 &layer->draw_properties().contents_scale_y,
947                                 &layer->draw_properties().content_bounds);
948
949   Layer* mask_layer = layer->mask_layer();
950   if (mask_layer) {
951     mask_layer->CalculateContentsScale(
952         contents_scale,
953         &mask_layer->draw_properties().contents_scale_x,
954         &mask_layer->draw_properties().contents_scale_y,
955         &mask_layer->draw_properties().content_bounds);
956   }
957
958   Layer* replica_mask_layer =
959       layer->replica_layer() ? layer->replica_layer()->mask_layer() : NULL;
960   if (replica_mask_layer) {
961     replica_mask_layer->CalculateContentsScale(
962         contents_scale,
963         &replica_mask_layer->draw_properties().contents_scale_x,
964         &replica_mask_layer->draw_properties().contents_scale_y,
965         &replica_mask_layer->draw_properties().content_bounds);
966   }
967 }
968
969 static inline void UpdateLayerContentsScale(
970     LayerImpl* layer,
971     bool can_adjust_raster_scale,
972     float ideal_contents_scale,
973     float device_scale_factor,
974     float page_scale_factor,
975     bool animating_transform_to_screen) {
976   CalculateContentsScale(layer, ideal_contents_scale);
977 }
978
979 static inline void UpdateLayerContentsScale(
980     Layer* layer,
981     bool can_adjust_raster_scale,
982     float ideal_contents_scale,
983     float device_scale_factor,
984     float page_scale_factor,
985     bool animating_transform_to_screen) {
986   if (can_adjust_raster_scale) {
987     float ideal_raster_scale =
988         ideal_contents_scale / (device_scale_factor * page_scale_factor);
989
990     bool need_to_set_raster_scale = layer->raster_scale_is_unknown();
991
992     // If we've previously saved a raster_scale but the ideal changes, things
993     // are unpredictable and we should just use 1.
994     if (!need_to_set_raster_scale && layer->raster_scale() != 1.f &&
995         ideal_raster_scale != layer->raster_scale()) {
996       ideal_raster_scale = 1.f;
997       need_to_set_raster_scale = true;
998     }
999
1000     if (need_to_set_raster_scale) {
1001       bool use_and_save_ideal_scale =
1002           ideal_raster_scale >= 1.f && !animating_transform_to_screen;
1003       if (use_and_save_ideal_scale)
1004         layer->set_raster_scale(ideal_raster_scale);
1005     }
1006   }
1007
1008   float raster_scale = 1.f;
1009   if (!layer->raster_scale_is_unknown())
1010     raster_scale = layer->raster_scale();
1011
1012   gfx::Size old_content_bounds = layer->content_bounds();
1013   float old_contents_scale_x = layer->contents_scale_x();
1014   float old_contents_scale_y = layer->contents_scale_y();
1015
1016   float contents_scale = raster_scale * device_scale_factor * page_scale_factor;
1017   CalculateContentsScale(layer, contents_scale);
1018
1019   if (layer->content_bounds() != old_content_bounds ||
1020       layer->contents_scale_x() != old_contents_scale_x ||
1021       layer->contents_scale_y() != old_contents_scale_y)
1022     layer->SetNeedsPushProperties();
1023 }
1024
1025 static inline void CalculateAnimationContentsScale(
1026     Layer* layer,
1027     bool ancestor_is_animating_scale,
1028     float ancestor_maximum_animation_contents_scale,
1029     const gfx::Transform& parent_transform,
1030     const gfx::Transform& combined_transform,
1031     bool* combined_is_animating_scale,
1032     float* combined_maximum_animation_contents_scale) {
1033   *combined_is_animating_scale = false;
1034   *combined_maximum_animation_contents_scale = 0.f;
1035 }
1036
1037 static inline void CalculateAnimationContentsScale(
1038     LayerImpl* layer,
1039     bool ancestor_is_animating_scale,
1040     float ancestor_maximum_animation_contents_scale,
1041     const gfx::Transform& ancestor_transform,
1042     const gfx::Transform& combined_transform,
1043     bool* combined_is_animating_scale,
1044     float* combined_maximum_animation_contents_scale) {
1045   if (ancestor_is_animating_scale &&
1046       ancestor_maximum_animation_contents_scale == 0.f) {
1047     // We've already failed to compute a maximum animated scale at an
1048     // ancestor, so we'll continue to fail.
1049     *combined_maximum_animation_contents_scale = 0.f;
1050     *combined_is_animating_scale = true;
1051     return;
1052   }
1053
1054   if (!combined_transform.IsScaleOrTranslation()) {
1055     // Computing maximum animated scale in the presence of
1056     // non-scale/translation transforms isn't supported.
1057     *combined_maximum_animation_contents_scale = 0.f;
1058     *combined_is_animating_scale = true;
1059     return;
1060   }
1061
1062   // We currently only support computing maximum scale for combinations of
1063   // scales and translations. We treat all non-translations as potentially
1064   // affecting scale. Animations that include non-translation/scale components
1065   // will cause the computation of MaximumScale below to fail.
1066   bool layer_is_animating_scale =
1067       !layer->layer_animation_controller()->HasOnlyTranslationTransforms();
1068
1069   if (!layer_is_animating_scale && !ancestor_is_animating_scale) {
1070     *combined_maximum_animation_contents_scale = 0.f;
1071     *combined_is_animating_scale = false;
1072     return;
1073   }
1074
1075   // We don't attempt to accumulate animation scale from multiple nodes,
1076   // because of the risk of significant overestimation. For example, one node
1077   // may be increasing scale from 1 to 10 at the same time as a descendant is
1078   // decreasing scale from 10 to 1. Naively combining these scales would produce
1079   // a scale of 100.
1080   if (layer_is_animating_scale && ancestor_is_animating_scale) {
1081     *combined_maximum_animation_contents_scale = 0.f;
1082     *combined_is_animating_scale = true;
1083     return;
1084   }
1085
1086   // At this point, we know either the layer or an ancestor, but not both,
1087   // is animating scale.
1088   *combined_is_animating_scale = true;
1089   if (!layer_is_animating_scale) {
1090     gfx::Vector2dF layer_transform_scales =
1091         MathUtil::ComputeTransform2dScaleComponents(layer->transform(), 0.f);
1092     *combined_maximum_animation_contents_scale =
1093         ancestor_maximum_animation_contents_scale *
1094         std::max(layer_transform_scales.x(), layer_transform_scales.y());
1095     return;
1096   }
1097
1098   float layer_maximum_animated_scale = 0.f;
1099   if (!layer->layer_animation_controller()->MaximumTargetScale(
1100           &layer_maximum_animated_scale)) {
1101     *combined_maximum_animation_contents_scale = 0.f;
1102     return;
1103   }
1104   gfx::Vector2dF ancestor_transform_scales =
1105       MathUtil::ComputeTransform2dScaleComponents(ancestor_transform, 0.f);
1106   *combined_maximum_animation_contents_scale =
1107       layer_maximum_animated_scale *
1108       std::max(ancestor_transform_scales.x(), ancestor_transform_scales.y());
1109 }
1110
1111 template <typename LayerType>
1112 static inline typename LayerType::RenderSurfaceType* CreateOrReuseRenderSurface(
1113     LayerType* layer) {
1114   if (!layer->render_surface()) {
1115     layer->CreateRenderSurface();
1116     return layer->render_surface();
1117   }
1118
1119   layer->render_surface()->ClearLayerLists();
1120   return layer->render_surface();
1121 }
1122
1123 template <typename LayerTypePtr>
1124 static inline void MarkLayerWithRenderSurfaceLayerListId(
1125     LayerTypePtr layer,
1126     int current_render_surface_layer_list_id) {
1127   layer->draw_properties().last_drawn_render_surface_layer_list_id =
1128       current_render_surface_layer_list_id;
1129 }
1130
1131 template <typename LayerTypePtr>
1132 static inline void MarkMasksWithRenderSurfaceLayerListId(
1133     LayerTypePtr layer,
1134     int current_render_surface_layer_list_id) {
1135   if (layer->mask_layer()) {
1136     MarkLayerWithRenderSurfaceLayerListId(layer->mask_layer(),
1137                                           current_render_surface_layer_list_id);
1138   }
1139   if (layer->replica_layer() && layer->replica_layer()->mask_layer()) {
1140     MarkLayerWithRenderSurfaceLayerListId(layer->replica_layer()->mask_layer(),
1141                                           current_render_surface_layer_list_id);
1142   }
1143 }
1144
1145 template <typename LayerListType>
1146 static inline void MarkLayerListWithRenderSurfaceLayerListId(
1147     LayerListType* layer_list,
1148     int current_render_surface_layer_list_id) {
1149   for (typename LayerListType::iterator it = layer_list->begin();
1150        it != layer_list->end();
1151        ++it) {
1152     MarkLayerWithRenderSurfaceLayerListId(*it,
1153                                           current_render_surface_layer_list_id);
1154     MarkMasksWithRenderSurfaceLayerListId(*it,
1155                                           current_render_surface_layer_list_id);
1156   }
1157 }
1158
1159 template <typename LayerType>
1160 static inline void RemoveSurfaceForEarlyExit(
1161     LayerType* layer_to_remove,
1162     typename LayerType::RenderSurfaceListType* render_surface_layer_list) {
1163   DCHECK(layer_to_remove->render_surface());
1164   // Technically, we know that the layer we want to remove should be
1165   // at the back of the render_surface_layer_list. However, we have had
1166   // bugs before that added unnecessary layers here
1167   // (https://bugs.webkit.org/show_bug.cgi?id=74147), but that causes
1168   // things to crash. So here we proactively remove any additional
1169   // layers from the end of the list.
1170   while (render_surface_layer_list->back() != layer_to_remove) {
1171     MarkLayerListWithRenderSurfaceLayerListId(
1172         &render_surface_layer_list->back()->render_surface()->layer_list(), 0);
1173     MarkLayerWithRenderSurfaceLayerListId(render_surface_layer_list->back(), 0);
1174
1175     render_surface_layer_list->back()->ClearRenderSurfaceLayerList();
1176     render_surface_layer_list->pop_back();
1177   }
1178   DCHECK_EQ(render_surface_layer_list->back(), layer_to_remove);
1179   MarkLayerListWithRenderSurfaceLayerListId(
1180       &layer_to_remove->render_surface()->layer_list(), 0);
1181   MarkLayerWithRenderSurfaceLayerListId(layer_to_remove, 0);
1182   render_surface_layer_list->pop_back();
1183   layer_to_remove->ClearRenderSurfaceLayerList();
1184 }
1185
1186 struct PreCalculateMetaInformationRecursiveData {
1187   bool layer_or_descendant_has_copy_request;
1188   bool layer_or_descendant_has_input_handler;
1189   int num_unclipped_descendants;
1190
1191   PreCalculateMetaInformationRecursiveData()
1192       : layer_or_descendant_has_copy_request(false),
1193         layer_or_descendant_has_input_handler(false),
1194         num_unclipped_descendants(0) {}
1195
1196   void Merge(const PreCalculateMetaInformationRecursiveData& data) {
1197     layer_or_descendant_has_copy_request |=
1198         data.layer_or_descendant_has_copy_request;
1199     layer_or_descendant_has_input_handler |=
1200         data.layer_or_descendant_has_input_handler;
1201     num_unclipped_descendants +=
1202         data.num_unclipped_descendants;
1203   }
1204 };
1205
1206 // Recursively walks the layer tree to compute any information that is needed
1207 // before doing the main recursion.
1208 template <typename LayerType>
1209 static void PreCalculateMetaInformation(
1210     LayerType* layer,
1211     PreCalculateMetaInformationRecursiveData* recursive_data) {
1212
1213   layer->draw_properties().sorted_for_recursion = false;
1214   layer->draw_properties().has_child_with_a_scroll_parent = false;
1215
1216   if (!HasInvertibleOrAnimatedTransform(layer)) {
1217     // Layers with singular transforms should not be drawn, the whole subtree
1218     // can be skipped.
1219     return;
1220   }
1221
1222   if (layer->clip_parent())
1223     recursive_data->num_unclipped_descendants++;
1224
1225   for (size_t i = 0; i < layer->children().size(); ++i) {
1226     LayerType* child_layer =
1227         LayerTreeHostCommon::get_layer_as_raw_ptr(layer->children(), i);
1228
1229     PreCalculateMetaInformationRecursiveData data_for_child;
1230     PreCalculateMetaInformation(child_layer, &data_for_child);
1231
1232     if (child_layer->scroll_parent())
1233       layer->draw_properties().has_child_with_a_scroll_parent = true;
1234     recursive_data->Merge(data_for_child);
1235   }
1236
1237   if (layer->clip_children()) {
1238     int num_clip_children = layer->clip_children()->size();
1239     DCHECK_GE(recursive_data->num_unclipped_descendants, num_clip_children);
1240     recursive_data->num_unclipped_descendants -= num_clip_children;
1241   }
1242
1243   if (layer->HasCopyRequest())
1244     recursive_data->layer_or_descendant_has_copy_request = true;
1245
1246   if (!layer->touch_event_handler_region().IsEmpty() ||
1247       layer->have_wheel_event_handlers())
1248     recursive_data->layer_or_descendant_has_input_handler = true;
1249
1250   layer->draw_properties().num_unclipped_descendants =
1251       recursive_data->num_unclipped_descendants;
1252   layer->draw_properties().layer_or_descendant_has_copy_request =
1253       recursive_data->layer_or_descendant_has_copy_request;
1254   layer->draw_properties().layer_or_descendant_has_input_handler =
1255       recursive_data->layer_or_descendant_has_input_handler;
1256 }
1257
1258 static void RoundTranslationComponents(gfx::Transform* transform) {
1259   transform->matrix().set(0, 3, MathUtil::Round(transform->matrix().get(0, 3)));
1260   transform->matrix().set(1, 3, MathUtil::Round(transform->matrix().get(1, 3)));
1261 }
1262
1263 template <typename LayerType>
1264 struct SubtreeGlobals {
1265   LayerSorter* layer_sorter;
1266   int max_texture_size;
1267   float device_scale_factor;
1268   float page_scale_factor;
1269   const LayerType* page_scale_application_layer;
1270   bool can_adjust_raster_scales;
1271   bool can_render_to_separate_surface;
1272 };
1273
1274 template<typename LayerType>
1275 struct DataForRecursion {
1276   // The accumulated sequence of transforms a layer will use to determine its
1277   // own draw transform.
1278   gfx::Transform parent_matrix;
1279
1280   // The accumulated sequence of transforms a layer will use to determine its
1281   // own screen-space transform.
1282   gfx::Transform full_hierarchy_matrix;
1283
1284   // The transform that removes all scrolling that may have occurred between a
1285   // fixed-position layer and its container, so that the layer actually does
1286   // remain fixed.
1287   gfx::Transform scroll_compensation_matrix;
1288
1289   // The ancestor that would be the container for any fixed-position / sticky
1290   // layers.
1291   LayerType* fixed_container;
1292
1293   // This is the normal clip rect that is propagated from parent to child.
1294   gfx::Rect clip_rect_in_target_space;
1295
1296   // When the layer's children want to compute their visible content rect, they
1297   // want to know what their target surface's clip rect will be. BUT - they
1298   // want to know this clip rect represented in their own target space. This
1299   // requires inverse-projecting the surface's clip rect from the surface's
1300   // render target space down to the surface's own space. Instead of computing
1301   // this value redundantly for each child layer, it is computed only once
1302   // while dealing with the parent layer, and then this precomputed value is
1303   // passed down the recursion to the children that actually use it.
1304   gfx::Rect clip_rect_of_target_surface_in_target_space;
1305
1306   // The maximum amount by which this layer will be scaled during the lifetime
1307   // of currently running animations.
1308   float maximum_animation_contents_scale;
1309
1310   bool ancestor_is_animating_scale;
1311   bool ancestor_clips_subtree;
1312   typename LayerType::RenderSurfaceType*
1313       nearest_occlusion_immune_ancestor_surface;
1314   bool in_subtree_of_page_scale_application_layer;
1315   bool subtree_can_use_lcd_text;
1316   bool subtree_is_visible_from_ancestor;
1317 };
1318
1319 template <typename LayerType>
1320 static LayerType* GetChildContainingLayer(const LayerType& parent,
1321                                           LayerType* layer) {
1322   for (LayerType* ancestor = layer; ancestor; ancestor = ancestor->parent()) {
1323     if (ancestor->parent() == &parent)
1324       return ancestor;
1325   }
1326   NOTREACHED();
1327   return 0;
1328 }
1329
1330 template <typename LayerType>
1331 static void AddScrollParentChain(std::vector<LayerType*>* out,
1332                                  const LayerType& parent,
1333                                  LayerType* layer) {
1334   // At a high level, this function walks up the chain of scroll parents
1335   // recursively, and once we reach the end of the chain, we add the child
1336   // of |parent| containing each scroll ancestor as we unwind. The result is
1337   // an ordering of parent's children that ensures that scroll parents are
1338   // visited before their descendants.
1339   // Take for example this layer tree:
1340   //
1341   // + stacking_context
1342   //   + scroll_child (1)
1343   //   + scroll_parent_graphics_layer (*)
1344   //   | + scroll_parent_scrolling_layer
1345   //   |   + scroll_parent_scrolling_content_layer (2)
1346   //   + scroll_grandparent_graphics_layer (**)
1347   //     + scroll_grandparent_scrolling_layer
1348   //       + scroll_grandparent_scrolling_content_layer (3)
1349   //
1350   // The scroll child is (1), its scroll parent is (2) and its scroll
1351   // grandparent is (3). Note, this doesn't mean that (2)'s scroll parent is
1352   // (3), it means that (*)'s scroll parent is (3). We don't want our list to
1353   // look like [ (3), (2), (1) ], even though that does have the ancestor chain
1354   // in the right order. Instead, we want [ (**), (*), (1) ]. That is, only want
1355   // (1)'s siblings in the list, but we want them to appear in such an order
1356   // that the scroll ancestors get visited in the correct order.
1357   //
1358   // So our first task at this step of the recursion is to determine the layer
1359   // that we will potentionally add to the list. That is, the child of parent
1360   // containing |layer|.
1361   LayerType* child = GetChildContainingLayer(parent, layer);
1362   if (child->draw_properties().sorted_for_recursion)
1363     return;
1364
1365   if (LayerType* scroll_parent = child->scroll_parent())
1366     AddScrollParentChain(out, parent, scroll_parent);
1367
1368   out->push_back(child);
1369   child->draw_properties().sorted_for_recursion = true;
1370 }
1371
1372 template <typename LayerType>
1373 static bool SortChildrenForRecursion(std::vector<LayerType*>* out,
1374                                      const LayerType& parent) {
1375   out->reserve(parent.children().size());
1376   bool order_changed = false;
1377   for (size_t i = 0; i < parent.children().size(); ++i) {
1378     LayerType* current =
1379         LayerTreeHostCommon::get_layer_as_raw_ptr(parent.children(), i);
1380
1381     if (current->draw_properties().sorted_for_recursion) {
1382       order_changed = true;
1383       continue;
1384     }
1385
1386     AddScrollParentChain(out, parent, current);
1387   }
1388
1389   DCHECK_EQ(parent.children().size(), out->size());
1390   return order_changed;
1391 }
1392
1393 template <typename LayerType>
1394 static void GetNewDescendantsStartIndexAndCount(LayerType* layer,
1395                                                 size_t* start_index,
1396                                                 size_t* count) {
1397   *start_index = layer->draw_properties().index_of_first_descendants_addition;
1398   *count = layer->draw_properties().num_descendants_added;
1399 }
1400
1401 template <typename LayerType>
1402 static void GetNewRenderSurfacesStartIndexAndCount(LayerType* layer,
1403                                                    size_t* start_index,
1404                                                    size_t* count) {
1405   *start_index = layer->draw_properties()
1406                      .index_of_first_render_surface_layer_list_addition;
1407   *count = layer->draw_properties().num_render_surfaces_added;
1408 }
1409
1410 // We need to extract a list from the the two flavors of RenderSurfaceListType
1411 // for use in the sorting function below.
1412 static LayerList* GetLayerListForSorting(RenderSurfaceLayerList* rsll) {
1413   return &rsll->AsLayerList();
1414 }
1415
1416 static LayerImplList* GetLayerListForSorting(LayerImplList* layer_list) {
1417   return layer_list;
1418 }
1419
1420 template <typename LayerType, typename GetIndexAndCountType>
1421 static void SortLayerListContributions(
1422     const LayerType& parent,
1423     typename LayerType::LayerListType* unsorted,
1424     size_t start_index_for_all_contributions,
1425     GetIndexAndCountType get_index_and_count) {
1426   typename LayerType::LayerListType buffer;
1427   for (size_t i = 0; i < parent.children().size(); ++i) {
1428     LayerType* child =
1429         LayerTreeHostCommon::get_layer_as_raw_ptr(parent.children(), i);
1430
1431     size_t start_index = 0;
1432     size_t count = 0;
1433     get_index_and_count(child, &start_index, &count);
1434     for (size_t j = start_index; j < start_index + count; ++j)
1435       buffer.push_back(unsorted->at(j));
1436   }
1437
1438   DCHECK_EQ(buffer.size(),
1439             unsorted->size() - start_index_for_all_contributions);
1440
1441   for (size_t i = 0; i < buffer.size(); ++i)
1442     (*unsorted)[i + start_index_for_all_contributions] = buffer[i];
1443 }
1444
1445 // Recursively walks the layer tree starting at the given node and computes all
1446 // the necessary transformations, clip rects, render surfaces, etc.
1447 template <typename LayerType>
1448 static void CalculateDrawPropertiesInternal(
1449     LayerType* layer,
1450     const SubtreeGlobals<LayerType>& globals,
1451     const DataForRecursion<LayerType>& data_from_ancestor,
1452     typename LayerType::RenderSurfaceListType* render_surface_layer_list,
1453     typename LayerType::LayerListType* layer_list,
1454     std::vector<AccumulatedSurfaceState<LayerType>>* accumulated_surface_state,
1455     int current_render_surface_layer_list_id) {
1456   // This function computes the new matrix transformations recursively for this
1457   // layer and all its descendants. It also computes the appropriate render
1458   // surfaces.
1459   // Some important points to remember:
1460   //
1461   // 0. Here, transforms are notated in Matrix x Vector order, and in words we
1462   // describe what the transform does from left to right.
1463   //
1464   // 1. In our terminology, the "layer origin" refers to the top-left corner of
1465   // a layer, and the positive Y-axis points downwards. This interpretation is
1466   // valid because the orthographic projection applied at draw time flips the Y
1467   // axis appropriately.
1468   //
1469   // 2. The anchor point, when given as a PointF object, is specified in "unit
1470   // layer space", where the bounds of the layer map to [0, 1]. However, as a
1471   // Transform object, the transform to the anchor point is specified in "layer
1472   // space", where the bounds of the layer map to [bounds.width(),
1473   // bounds.height()].
1474   //
1475   // 3. Definition of various transforms used:
1476   //        M[parent] is the parent matrix, with respect to the nearest render
1477   //        surface, passed down recursively.
1478   //
1479   //        M[root] is the full hierarchy, with respect to the root, passed down
1480   //        recursively.
1481   //
1482   //        Tr[origin] is the translation matrix from the parent's origin to
1483   //        this layer's origin.
1484   //
1485   //        Tr[origin2anchor] is the translation from the layer's origin to its
1486   //        anchor point
1487   //
1488   //        Tr[origin2center] is the translation from the layer's origin to its
1489   //        center
1490   //
1491   //        M[layer] is the layer's matrix (applied at the anchor point)
1492   //
1493   //        S[layer2content] is the ratio of a layer's content_bounds() to its
1494   //        Bounds().
1495   //
1496   //    Some composite transforms can help in understanding the sequence of
1497   //    transforms:
1498   //        composite_layer_transform = Tr[origin2anchor] * M[layer] *
1499   //        Tr[origin2anchor].inverse()
1500   //
1501   // 4. When a layer (or render surface) is drawn, it is drawn into a "target
1502   // render surface". Therefore the draw transform does not necessarily
1503   // transform from screen space to local layer space. Instead, the draw
1504   // transform is the transform between the "target render surface space" and
1505   // local layer space. Note that render surfaces, except for the root, also
1506   // draw themselves into a different target render surface, and so their draw
1507   // transform and origin transforms are also described with respect to the
1508   // target.
1509   //
1510   // Using these definitions, then:
1511   //
1512   // The draw transform for the layer is:
1513   //        M[draw] = M[parent] * Tr[origin] * composite_layer_transform *
1514   //            S[layer2content] = M[parent] * Tr[layer->position() + anchor] *
1515   //            M[layer] * Tr[anchor2origin] * S[layer2content]
1516   //
1517   //        Interpreting the math left-to-right, this transforms from the
1518   //        layer's render surface to the origin of the layer in content space.
1519   //
1520   // The screen space transform is:
1521   //        M[screenspace] = M[root] * Tr[origin] * composite_layer_transform *
1522   //            S[layer2content]
1523   //                       = M[root] * Tr[layer->position() + anchor] * M[layer]
1524   //                           * Tr[anchor2origin] * S[layer2content]
1525   //
1526   //        Interpreting the math left-to-right, this transforms from the root
1527   //        render surface's content space to the origin of the layer in content
1528   //        space.
1529   //
1530   // The transform hierarchy that is passed on to children (i.e. the child's
1531   // parent_matrix) is:
1532   //        M[parent]_for_child = M[parent] * Tr[origin] *
1533   //            composite_layer_transform
1534   //                            = M[parent] * Tr[layer->position() + anchor] *
1535   //                              M[layer] * Tr[anchor2origin]
1536   //
1537   //        and a similar matrix for the full hierarchy with respect to the
1538   //        root.
1539   //
1540   // Finally, note that the final matrix used by the shader for the layer is P *
1541   // M[draw] * S . This final product is computed in drawTexturedQuad(), where:
1542   //        P is the projection matrix
1543   //        S is the scale adjustment (to scale up a canonical quad to the
1544   //            layer's size)
1545   //
1546   // When a render surface has a replica layer, that layer's transform is used
1547   // to draw a second copy of the surface.  gfx::Transforms named here are
1548   // relative to the surface, unless they specify they are relative to the
1549   // replica layer.
1550   //
1551   // We will denote a scale by device scale S[deviceScale]
1552   //
1553   // The render surface draw transform to its target surface origin is:
1554   //        M[surfaceDraw] = M[owningLayer->Draw]
1555   //
1556   // The render surface origin transform to its the root (screen space) origin
1557   // is:
1558   //        M[surface2root] =  M[owningLayer->screenspace] *
1559   //            S[deviceScale].inverse()
1560   //
1561   // The replica draw transform to its target surface origin is:
1562   //        M[replicaDraw] = S[deviceScale] * M[surfaceDraw] *
1563   //            Tr[replica->position() + replica->anchor()] * Tr[replica] *
1564   //            Tr[origin2anchor].inverse() * S[contents_scale].inverse()
1565   //
1566   // The replica draw transform to the root (screen space) origin is:
1567   //        M[replica2root] = M[surface2root] * Tr[replica->position()] *
1568   //            Tr[replica] * Tr[origin2anchor].inverse()
1569   //
1570
1571   // It makes no sense to have a non-unit page_scale_factor without specifying
1572   // which layer roots the subtree the scale is applied to.
1573   DCHECK(globals.page_scale_application_layer ||
1574          (globals.page_scale_factor == 1.f));
1575
1576   DataForRecursion<LayerType> data_for_children;
1577   typename LayerType::RenderSurfaceType*
1578       nearest_occlusion_immune_ancestor_surface =
1579           data_from_ancestor.nearest_occlusion_immune_ancestor_surface;
1580   data_for_children.in_subtree_of_page_scale_application_layer =
1581       data_from_ancestor.in_subtree_of_page_scale_application_layer;
1582   data_for_children.subtree_can_use_lcd_text =
1583       data_from_ancestor.subtree_can_use_lcd_text;
1584
1585   // Layers that are marked as hidden will hide themselves and their subtree.
1586   // Exception: Layers with copy requests, whether hidden or not, must be drawn
1587   // anyway.  In this case, we will inform their subtree they are visible to get
1588   // the right results.
1589   const bool layer_is_visible =
1590       data_from_ancestor.subtree_is_visible_from_ancestor &&
1591       !layer->hide_layer_and_subtree();
1592   const bool layer_is_drawn = layer_is_visible || layer->HasCopyRequest();
1593
1594   // The root layer cannot skip CalcDrawProperties.
1595   if (!IsRootLayer(layer) && SubtreeShouldBeSkipped(layer, layer_is_drawn)) {
1596     if (layer->render_surface())
1597       layer->ClearRenderSurfaceLayerList();
1598     return;
1599   }
1600
1601   // We need to circumvent the normal recursive flow of information for clip
1602   // children (they don't inherit their direct ancestor's clip information).
1603   // This is unfortunate, and would be unnecessary if we were to formally
1604   // separate the clipping hierarchy from the layer hierarchy.
1605   bool ancestor_clips_subtree = data_from_ancestor.ancestor_clips_subtree;
1606   gfx::Rect ancestor_clip_rect_in_target_space =
1607       data_from_ancestor.clip_rect_in_target_space;
1608
1609   // Update our clipping state. If we have a clip parent we will need to pull
1610   // from the clip state cache rather than using the clip state passed from our
1611   // immediate ancestor.
1612   UpdateClipRectsForClipChild<LayerType>(
1613       layer, &ancestor_clip_rect_in_target_space, &ancestor_clips_subtree);
1614
1615   // As this function proceeds, these are the properties for the current
1616   // layer that actually get computed. To avoid unnecessary copies
1617   // (particularly for matrices), we do computations directly on these values
1618   // when possible.
1619   DrawProperties<LayerType>& layer_draw_properties = layer->draw_properties();
1620
1621   gfx::Rect clip_rect_in_target_space;
1622   bool layer_or_ancestor_clips_descendants = false;
1623
1624   // This value is cached on the stack so that we don't have to inverse-project
1625   // the surface's clip rect redundantly for every layer. This value is the
1626   // same as the target surface's clip rect, except that instead of being
1627   // described in the target surface's target's space, it is described in the
1628   // current render target's space.
1629   gfx::Rect clip_rect_of_target_surface_in_target_space;
1630
1631   float accumulated_draw_opacity = layer->opacity();
1632   bool animating_opacity_to_target = layer->OpacityIsAnimating();
1633   bool animating_opacity_to_screen = animating_opacity_to_target;
1634   if (layer->parent()) {
1635     accumulated_draw_opacity *= layer->parent()->draw_opacity();
1636     animating_opacity_to_target |= layer->parent()->draw_opacity_is_animating();
1637     animating_opacity_to_screen |=
1638         layer->parent()->screen_space_opacity_is_animating();
1639   }
1640
1641   bool animating_transform_to_target = layer->TransformIsAnimating();
1642   bool animating_transform_to_screen = animating_transform_to_target;
1643   if (layer->parent()) {
1644     animating_transform_to_target |=
1645         layer->parent()->draw_transform_is_animating();
1646     animating_transform_to_screen |=
1647         layer->parent()->screen_space_transform_is_animating();
1648   }
1649   gfx::Point3F transform_origin = layer->transform_origin();
1650   gfx::ScrollOffset scroll_offset = GetEffectiveTotalScrollOffset(layer);
1651   gfx::PointF position =
1652       layer->position() - ScrollOffsetToVector2dF(scroll_offset);
1653   gfx::Transform combined_transform = data_from_ancestor.parent_matrix;
1654   if (!layer->transform().IsIdentity()) {
1655     // LT = Tr[origin] * Tr[origin2transformOrigin]
1656     combined_transform.Translate3d(position.x() + transform_origin.x(),
1657                                    position.y() + transform_origin.y(),
1658                                    transform_origin.z());
1659     // LT = Tr[origin] * Tr[origin2origin] * M[layer]
1660     combined_transform.PreconcatTransform(layer->transform());
1661     // LT = Tr[origin] * Tr[origin2origin] * M[layer] *
1662     // Tr[transformOrigin2origin]
1663     combined_transform.Translate3d(
1664         -transform_origin.x(), -transform_origin.y(), -transform_origin.z());
1665   } else {
1666     combined_transform.Translate(position.x(), position.y());
1667   }
1668
1669   gfx::Vector2dF effective_scroll_delta = GetEffectiveScrollDelta(layer);
1670   if (!animating_transform_to_target && layer->scrollable() &&
1671       combined_transform.IsScaleOrTranslation()) {
1672     // Align the scrollable layer's position to screen space pixels to avoid
1673     // blurriness.  To avoid side-effects, do this only if the transform is
1674     // simple.
1675     gfx::Vector2dF previous_translation = combined_transform.To2dTranslation();
1676     RoundTranslationComponents(&combined_transform);
1677     gfx::Vector2dF current_translation = combined_transform.To2dTranslation();
1678
1679     // This rounding changes the scroll delta, and so must be included
1680     // in the scroll compensation matrix.  The scaling converts from physical
1681     // coordinates to the scroll delta's CSS coordinates (using the parent
1682     // matrix instead of combined transform since scrolling is applied before
1683     // the layer's transform).  For example, if we have a total scale factor of
1684     // 3.0, then 1 physical pixel is only 1/3 of a CSS pixel.
1685     gfx::Vector2dF parent_scales = MathUtil::ComputeTransform2dScaleComponents(
1686         data_from_ancestor.parent_matrix, 1.f);
1687     effective_scroll_delta -=
1688         gfx::ScaleVector2d(current_translation - previous_translation,
1689                            1.f / parent_scales.x(),
1690                            1.f / parent_scales.y());
1691   }
1692
1693   // Apply adjustment from position constraints.
1694   ApplyPositionAdjustment(layer, data_from_ancestor.fixed_container,
1695       data_from_ancestor.scroll_compensation_matrix, &combined_transform);
1696
1697   bool combined_is_animating_scale = false;
1698   float combined_maximum_animation_contents_scale = 0.f;
1699   if (globals.can_adjust_raster_scales) {
1700     CalculateAnimationContentsScale(
1701         layer,
1702         data_from_ancestor.ancestor_is_animating_scale,
1703         data_from_ancestor.maximum_animation_contents_scale,
1704         data_from_ancestor.parent_matrix,
1705         combined_transform,
1706         &combined_is_animating_scale,
1707         &combined_maximum_animation_contents_scale);
1708   }
1709   data_for_children.ancestor_is_animating_scale = combined_is_animating_scale;
1710   data_for_children.maximum_animation_contents_scale =
1711       combined_maximum_animation_contents_scale;
1712
1713   // Compute the 2d scale components of the transform hierarchy up to the target
1714   // surface. From there, we can decide on a contents scale for the layer.
1715   float layer_scale_factors = globals.device_scale_factor;
1716   if (data_from_ancestor.in_subtree_of_page_scale_application_layer)
1717     layer_scale_factors *= globals.page_scale_factor;
1718   gfx::Vector2dF combined_transform_scales =
1719       MathUtil::ComputeTransform2dScaleComponents(
1720           combined_transform,
1721           layer_scale_factors);
1722
1723   float ideal_contents_scale =
1724       globals.can_adjust_raster_scales
1725       ? std::max(combined_transform_scales.x(),
1726                  combined_transform_scales.y())
1727       : layer_scale_factors;
1728   UpdateLayerContentsScale(
1729       layer,
1730       globals.can_adjust_raster_scales,
1731       ideal_contents_scale,
1732       globals.device_scale_factor,
1733       data_from_ancestor.in_subtree_of_page_scale_application_layer
1734           ? globals.page_scale_factor
1735           : 1.f,
1736       animating_transform_to_screen);
1737
1738   UpdateLayerScaleDrawProperties(
1739       layer,
1740       ideal_contents_scale,
1741       combined_maximum_animation_contents_scale,
1742       data_from_ancestor.in_subtree_of_page_scale_application_layer
1743           ? globals.page_scale_factor
1744           : 1.f,
1745       globals.device_scale_factor);
1746
1747   LayerType* mask_layer = layer->mask_layer();
1748   if (mask_layer) {
1749     UpdateLayerScaleDrawProperties(
1750         mask_layer,
1751         ideal_contents_scale,
1752         combined_maximum_animation_contents_scale,
1753         data_from_ancestor.in_subtree_of_page_scale_application_layer
1754             ? globals.page_scale_factor
1755             : 1.f,
1756         globals.device_scale_factor);
1757   }
1758
1759   LayerType* replica_mask_layer =
1760       layer->replica_layer() ? layer->replica_layer()->mask_layer() : NULL;
1761   if (replica_mask_layer) {
1762     UpdateLayerScaleDrawProperties(
1763         replica_mask_layer,
1764         ideal_contents_scale,
1765         combined_maximum_animation_contents_scale,
1766         data_from_ancestor.in_subtree_of_page_scale_application_layer
1767             ? globals.page_scale_factor
1768             : 1.f,
1769         globals.device_scale_factor);
1770   }
1771
1772   // The draw_transform that gets computed below is effectively the layer's
1773   // draw_transform, unless the layer itself creates a render_surface. In that
1774   // case, the render_surface re-parents the transforms.
1775   layer_draw_properties.target_space_transform = combined_transform;
1776   // M[draw] = M[parent] * LT * S[layer2content]
1777   layer_draw_properties.target_space_transform.Scale(
1778       SK_MScalar1 / layer->contents_scale_x(),
1779       SK_MScalar1 / layer->contents_scale_y());
1780
1781   // The layer's screen_space_transform represents the transform between root
1782   // layer's "screen space" and local content space.
1783   layer_draw_properties.screen_space_transform =
1784       data_from_ancestor.full_hierarchy_matrix;
1785   if (layer->should_flatten_transform())
1786     layer_draw_properties.screen_space_transform.FlattenTo2d();
1787   layer_draw_properties.screen_space_transform.PreconcatTransform
1788       (layer_draw_properties.target_space_transform);
1789
1790   // Adjusting text AA method during animation may cause repaints, which in-turn
1791   // causes jank.
1792   bool adjust_text_aa =
1793       !animating_opacity_to_screen && !animating_transform_to_screen;
1794   // To avoid color fringing, LCD text should only be used on opaque layers with
1795   // just integral translation.
1796   bool layer_can_use_lcd_text =
1797       data_from_ancestor.subtree_can_use_lcd_text &&
1798       accumulated_draw_opacity == 1.f &&
1799       layer_draw_properties.target_space_transform.
1800           IsIdentityOrIntegerTranslation();
1801
1802   gfx::Rect content_rect(layer->content_bounds());
1803
1804   // full_hierarchy_matrix is the matrix that transforms objects between screen
1805   // space (except projection matrix) and the most recent RenderSurfaceImpl's
1806   // space.  next_hierarchy_matrix will only change if this layer uses a new
1807   // RenderSurfaceImpl, otherwise remains the same.
1808   data_for_children.full_hierarchy_matrix =
1809       data_from_ancestor.full_hierarchy_matrix;
1810
1811   // If the subtree will scale layer contents by the transform hierarchy, then
1812   // we should scale things into the render surface by the transform hierarchy
1813   // to take advantage of that.
1814   gfx::Vector2dF render_surface_sublayer_scale =
1815       globals.can_adjust_raster_scales
1816       ? combined_transform_scales
1817       : gfx::Vector2dF(layer_scale_factors, layer_scale_factors);
1818
1819   bool render_to_separate_surface;
1820   if (globals.can_render_to_separate_surface) {
1821     render_to_separate_surface = SubtreeShouldRenderToSeparateSurface(
1822           layer, combined_transform.Preserves2dAxisAlignment());
1823   } else {
1824     render_to_separate_surface = IsRootLayer(layer);
1825   }
1826   if (render_to_separate_surface) {
1827     // Check back-face visibility before continuing with this surface and its
1828     // subtree
1829     if (!layer->double_sided() && TransformToParentIsKnown(layer) &&
1830         IsSurfaceBackFaceVisible(layer, combined_transform)) {
1831       layer->ClearRenderSurfaceLayerList();
1832       return;
1833     }
1834
1835     typename LayerType::RenderSurfaceType* render_surface =
1836         CreateOrReuseRenderSurface(layer);
1837
1838     if (IsRootLayer(layer)) {
1839       // The root layer's render surface size is predetermined and so the root
1840       // layer can't directly support non-identity transforms.  It should just
1841       // forward top-level transforms to the rest of the tree.
1842       data_for_children.parent_matrix = combined_transform;
1843
1844       // The root surface does not contribute to any other surface, it has no
1845       // target.
1846       layer->render_surface()->set_contributes_to_drawn_surface(false);
1847     } else {
1848       // The owning layer's draw transform has a scale from content to layer
1849       // space which we do not want; so here we use the combined_transform
1850       // instead of the draw_transform. However, we do need to add a different
1851       // scale factor that accounts for the surface's pixel dimensions.
1852       combined_transform.Scale(1.0 / render_surface_sublayer_scale.x(),
1853                                1.0 / render_surface_sublayer_scale.y());
1854       render_surface->SetDrawTransform(combined_transform);
1855
1856       // The owning layer's transform was re-parented by the surface, so the
1857       // layer's new draw_transform only needs to scale the layer to surface
1858       // space.
1859       layer_draw_properties.target_space_transform.MakeIdentity();
1860       layer_draw_properties.target_space_transform.
1861           Scale(render_surface_sublayer_scale.x() / layer->contents_scale_x(),
1862                 render_surface_sublayer_scale.y() / layer->contents_scale_y());
1863
1864       // Inside the surface's subtree, we scale everything to the owning layer's
1865       // scale.  The sublayer matrix transforms layer rects into target surface
1866       // content space.  Conceptually, all layers in the subtree inherit the
1867       // scale at the point of the render surface in the transform hierarchy,
1868       // but we apply it explicitly to the owning layer and the remainder of the
1869       // subtree independently.
1870       DCHECK(data_for_children.parent_matrix.IsIdentity());
1871       data_for_children.parent_matrix.Scale(render_surface_sublayer_scale.x(),
1872                             render_surface_sublayer_scale.y());
1873
1874       // Even if the |layer_is_drawn|, it only contributes to a drawn surface
1875       // when the |layer_is_visible|.
1876       layer->render_surface()->set_contributes_to_drawn_surface(
1877           layer_is_visible);
1878     }
1879
1880     // The opacity value is moved from the layer to its surface, so that the
1881     // entire subtree properly inherits opacity.
1882     render_surface->SetDrawOpacity(accumulated_draw_opacity);
1883     render_surface->SetDrawOpacityIsAnimating(animating_opacity_to_target);
1884     animating_opacity_to_target = false;
1885     layer_draw_properties.opacity = 1.f;
1886     layer_draw_properties.opacity_is_animating = animating_opacity_to_target;
1887     layer_draw_properties.screen_space_opacity_is_animating =
1888         animating_opacity_to_screen;
1889
1890     render_surface->SetTargetSurfaceTransformsAreAnimating(
1891         animating_transform_to_target);
1892     render_surface->SetScreenSpaceTransformsAreAnimating(
1893         animating_transform_to_screen);
1894     animating_transform_to_target = false;
1895     layer_draw_properties.target_space_transform_is_animating =
1896         animating_transform_to_target;
1897     layer_draw_properties.screen_space_transform_is_animating =
1898         animating_transform_to_screen;
1899
1900     // Update the aggregate hierarchy matrix to include the transform of the
1901     // newly created RenderSurfaceImpl.
1902     data_for_children.full_hierarchy_matrix.PreconcatTransform(
1903         render_surface->draw_transform());
1904
1905     if (layer->mask_layer()) {
1906       DrawProperties<LayerType>& mask_layer_draw_properties =
1907           layer->mask_layer()->draw_properties();
1908       mask_layer_draw_properties.render_target = layer;
1909       mask_layer_draw_properties.visible_content_rect =
1910           gfx::Rect(layer->content_bounds());
1911     }
1912
1913     if (layer->replica_layer() && layer->replica_layer()->mask_layer()) {
1914       DrawProperties<LayerType>& replica_mask_draw_properties =
1915           layer->replica_layer()->mask_layer()->draw_properties();
1916       replica_mask_draw_properties.render_target = layer;
1917       replica_mask_draw_properties.visible_content_rect =
1918           gfx::Rect(layer->content_bounds());
1919     }
1920
1921     // Ignore occlusion from outside the surface when surface contents need to
1922     // be fully drawn. Layers with copy-request need to be complete.
1923     // We could be smarter about layers with replica and exclude regions
1924     // where both layer and the replica are occluded, but this seems like an
1925     // overkill. The same is true for layers with filters that move pixels.
1926     // TODO(senorblanco): make this smarter for the SkImageFilter case (check
1927     // for pixel-moving filters)
1928     if (layer->HasCopyRequest() ||
1929         layer->has_replica() ||
1930         layer->filters().HasReferenceFilter() ||
1931         layer->filters().HasFilterThatMovesPixels()) {
1932       nearest_occlusion_immune_ancestor_surface = render_surface;
1933     }
1934     render_surface->SetNearestOcclusionImmuneAncestor(
1935         nearest_occlusion_immune_ancestor_surface);
1936
1937     layer_or_ancestor_clips_descendants = false;
1938     bool subtree_is_clipped_by_surface_bounds = false;
1939     if (ancestor_clips_subtree) {
1940       // It may be the layer or the surface doing the clipping of the subtree,
1941       // but in either case, we'll be clipping to the projected clip rect of our
1942       // ancestor.
1943       gfx::Transform inverse_surface_draw_transform(
1944           gfx::Transform::kSkipInitialization);
1945       if (!render_surface->draw_transform().GetInverse(
1946               &inverse_surface_draw_transform)) {
1947         // TODO(shawnsingh): Either we need to handle uninvertible transforms
1948         // here, or DCHECK that the transform is invertible.
1949       }
1950
1951       gfx::Rect surface_clip_rect_in_target_space = gfx::IntersectRects(
1952           data_from_ancestor.clip_rect_of_target_surface_in_target_space,
1953           ancestor_clip_rect_in_target_space);
1954       gfx::Rect projected_surface_rect = MathUtil::ProjectEnclosingClippedRect(
1955           inverse_surface_draw_transform, surface_clip_rect_in_target_space);
1956
1957       if (layer_draw_properties.num_unclipped_descendants > 0) {
1958         // If we have unclipped descendants, we cannot count on the render
1959         // surface's bounds clipping our subtree: the unclipped descendants
1960         // could cause us to expand our bounds. In this case, we must rely on
1961         // layer clipping for correctess. NB: since we can only encounter
1962         // translations between a clip child and its clip parent, clipping is
1963         // guaranteed to be exact in this case.
1964         layer_or_ancestor_clips_descendants = true;
1965         clip_rect_in_target_space = projected_surface_rect;
1966       } else {
1967         // The new render_surface here will correctly clip the entire subtree.
1968         // So, we do not need to continue propagating the clipping state further
1969         // down the tree. This way, we can avoid transforming clip rects from
1970         // ancestor target surface space to current target surface space that
1971         // could cause more w < 0 headaches. The render surface clip rect is
1972         // expressed in the space where this surface draws, i.e. the same space
1973         // as clip_rect_from_ancestor_in_ancestor_target_space.
1974         render_surface->SetClipRect(ancestor_clip_rect_in_target_space);
1975         clip_rect_of_target_surface_in_target_space = projected_surface_rect;
1976         subtree_is_clipped_by_surface_bounds = true;
1977       }
1978     }
1979
1980     DCHECK(layer->render_surface());
1981     DCHECK(!layer->parent() || layer->parent()->render_target() ==
1982            accumulated_surface_state->back().render_target);
1983
1984     accumulated_surface_state->push_back(
1985         AccumulatedSurfaceState<LayerType>(layer));
1986
1987     render_surface->SetIsClipped(subtree_is_clipped_by_surface_bounds);
1988     if (!subtree_is_clipped_by_surface_bounds) {
1989       render_surface->SetClipRect(gfx::Rect());
1990       clip_rect_of_target_surface_in_target_space =
1991           data_from_ancestor.clip_rect_of_target_surface_in_target_space;
1992     }
1993
1994     // If the new render surface is drawn translucent or with a non-integral
1995     // translation then the subtree that gets drawn on this render surface
1996     // cannot use LCD text.
1997     data_for_children.subtree_can_use_lcd_text = layer_can_use_lcd_text;
1998
1999     render_surface_layer_list->push_back(layer);
2000   } else {
2001     DCHECK(layer->parent());
2002
2003     // Note: layer_draw_properties.target_space_transform is computed above,
2004     // before this if-else statement.
2005     layer_draw_properties.target_space_transform_is_animating =
2006         animating_transform_to_target;
2007     layer_draw_properties.screen_space_transform_is_animating =
2008         animating_transform_to_screen;
2009     layer_draw_properties.opacity = accumulated_draw_opacity;
2010     layer_draw_properties.opacity_is_animating = animating_opacity_to_target;
2011     layer_draw_properties.screen_space_opacity_is_animating =
2012         animating_opacity_to_screen;
2013     data_for_children.parent_matrix = combined_transform;
2014
2015     layer->ClearRenderSurface();
2016
2017     // Layers without render_surfaces directly inherit the ancestor's clip
2018     // status.
2019     layer_or_ancestor_clips_descendants = ancestor_clips_subtree;
2020     if (ancestor_clips_subtree) {
2021       clip_rect_in_target_space =
2022           ancestor_clip_rect_in_target_space;
2023     }
2024
2025     // The surface's cached clip rect value propagates regardless of what
2026     // clipping goes on between layers here.
2027     clip_rect_of_target_surface_in_target_space =
2028         data_from_ancestor.clip_rect_of_target_surface_in_target_space;
2029
2030     // Layers that are not their own render_target will render into the target
2031     // of their nearest ancestor.
2032     layer_draw_properties.render_target = layer->parent()->render_target();
2033   }
2034
2035   if (adjust_text_aa)
2036     layer_draw_properties.can_use_lcd_text = layer_can_use_lcd_text;
2037
2038   gfx::Rect rect_in_target_space =
2039       MathUtil::MapEnclosingClippedRect(layer->draw_transform(), content_rect);
2040
2041   if (LayerClipsSubtree(layer)) {
2042     layer_or_ancestor_clips_descendants = true;
2043     if (ancestor_clips_subtree && !layer->render_surface()) {
2044       // A layer without render surface shares the same target as its ancestor.
2045       clip_rect_in_target_space =
2046           ancestor_clip_rect_in_target_space;
2047       clip_rect_in_target_space.Intersect(rect_in_target_space);
2048     } else {
2049       clip_rect_in_target_space = rect_in_target_space;
2050     }
2051   }
2052
2053   // Tell the layer the rect that it's clipped by. In theory we could use a
2054   // tighter clip rect here (drawable_content_rect), but that actually does not
2055   // reduce how much would be drawn, and instead it would create unnecessary
2056   // changes to scissor state affecting GPU performance. Our clip information
2057   // is used in the recursion below, so we must set it beforehand.
2058   layer_draw_properties.is_clipped = layer_or_ancestor_clips_descendants;
2059   if (layer_or_ancestor_clips_descendants) {
2060     layer_draw_properties.clip_rect = clip_rect_in_target_space;
2061   } else {
2062     // Initialize the clip rect to a safe value that will not clip the
2063     // layer, just in case clipping is still accidentally used.
2064     layer_draw_properties.clip_rect = rect_in_target_space;
2065   }
2066
2067   typename LayerType::LayerListType& descendants =
2068       (layer->render_surface() ? layer->render_surface()->layer_list()
2069                                : *layer_list);
2070
2071   // Any layers that are appended after this point are in the layer's subtree
2072   // and should be included in the sorting process.
2073   size_t sorting_start_index = descendants.size();
2074
2075   if (!LayerShouldBeSkipped(layer, layer_is_drawn)) {
2076     MarkLayerWithRenderSurfaceLayerListId(layer,
2077                                           current_render_surface_layer_list_id);
2078     descendants.push_back(layer);
2079   }
2080
2081   // Any layers that are appended after this point may need to be sorted if we
2082   // visit the children out of order.
2083   size_t render_surface_layer_list_child_sorting_start_index =
2084       render_surface_layer_list->size();
2085   size_t layer_list_child_sorting_start_index = descendants.size();
2086
2087   if (!layer->children().empty()) {
2088     if (layer == globals.page_scale_application_layer) {
2089       data_for_children.parent_matrix.Scale(
2090           globals.page_scale_factor,
2091           globals.page_scale_factor);
2092       data_for_children.in_subtree_of_page_scale_application_layer = true;
2093     }
2094
2095     // Flatten to 2D if the layer doesn't preserve 3D.
2096     if (layer->should_flatten_transform())
2097       data_for_children.parent_matrix.FlattenTo2d();
2098
2099     data_for_children.scroll_compensation_matrix =
2100         ComputeScrollCompensationMatrixForChildren(
2101             layer,
2102             data_from_ancestor.parent_matrix,
2103             data_from_ancestor.scroll_compensation_matrix,
2104             effective_scroll_delta);
2105     data_for_children.fixed_container =
2106         layer->IsContainerForFixedPositionLayers() ?
2107             layer : data_from_ancestor.fixed_container;
2108
2109     data_for_children.clip_rect_in_target_space = clip_rect_in_target_space;
2110     data_for_children.clip_rect_of_target_surface_in_target_space =
2111         clip_rect_of_target_surface_in_target_space;
2112     data_for_children.ancestor_clips_subtree =
2113         layer_or_ancestor_clips_descendants;
2114     data_for_children.nearest_occlusion_immune_ancestor_surface =
2115         nearest_occlusion_immune_ancestor_surface;
2116     data_for_children.subtree_is_visible_from_ancestor = layer_is_drawn;
2117   }
2118
2119   std::vector<LayerType*> sorted_children;
2120   bool child_order_changed = false;
2121   if (layer_draw_properties.has_child_with_a_scroll_parent)
2122     child_order_changed = SortChildrenForRecursion(&sorted_children, *layer);
2123
2124   for (size_t i = 0; i < layer->children().size(); ++i) {
2125     // If one of layer's children has a scroll parent, then we may have to
2126     // visit the children out of order. The new order is stored in
2127     // sorted_children. Otherwise, we'll grab the child directly from the
2128     // layer's list of children.
2129     LayerType* child =
2130         layer_draw_properties.has_child_with_a_scroll_parent
2131             ? sorted_children[i]
2132             : LayerTreeHostCommon::get_layer_as_raw_ptr(layer->children(), i);
2133
2134     child->draw_properties().index_of_first_descendants_addition =
2135         descendants.size();
2136     child->draw_properties().index_of_first_render_surface_layer_list_addition =
2137         render_surface_layer_list->size();
2138
2139     CalculateDrawPropertiesInternal<LayerType>(
2140         child,
2141         globals,
2142         data_for_children,
2143         render_surface_layer_list,
2144         &descendants,
2145         accumulated_surface_state,
2146         current_render_surface_layer_list_id);
2147     if (child->render_surface() &&
2148         !child->render_surface()->layer_list().empty() &&
2149         !child->render_surface()->content_rect().IsEmpty()) {
2150       // This child will contribute its render surface, which means
2151       // we need to mark just the mask layer (and replica mask layer)
2152       // with the id.
2153       MarkMasksWithRenderSurfaceLayerListId(
2154           child, current_render_surface_layer_list_id);
2155       descendants.push_back(child);
2156     }
2157
2158     child->draw_properties().num_descendants_added =
2159         descendants.size() -
2160         child->draw_properties().index_of_first_descendants_addition;
2161     child->draw_properties().num_render_surfaces_added =
2162         render_surface_layer_list->size() -
2163         child->draw_properties()
2164             .index_of_first_render_surface_layer_list_addition;
2165   }
2166
2167   // Add the unsorted layer list contributions, if necessary.
2168   if (child_order_changed) {
2169     SortLayerListContributions(
2170         *layer,
2171         GetLayerListForSorting(render_surface_layer_list),
2172         render_surface_layer_list_child_sorting_start_index,
2173         &GetNewRenderSurfacesStartIndexAndCount<LayerType>);
2174
2175     SortLayerListContributions(
2176         *layer,
2177         &descendants,
2178         layer_list_child_sorting_start_index,
2179         &GetNewDescendantsStartIndexAndCount<LayerType>);
2180   }
2181
2182   // Compute the total drawable_content_rect for this subtree (the rect is in
2183   // target surface space).
2184   gfx::Rect local_drawable_content_rect_of_subtree =
2185       accumulated_surface_state->back().drawable_content_rect;
2186   if (layer->render_surface()) {
2187     DCHECK(accumulated_surface_state->back().render_target == layer);
2188     accumulated_surface_state->pop_back();
2189   }
2190
2191   if (layer->render_surface() && !IsRootLayer(layer) &&
2192       layer->render_surface()->layer_list().empty()) {
2193     RemoveSurfaceForEarlyExit(layer, render_surface_layer_list);
2194     return;
2195   }
2196
2197   // Compute the layer's drawable content rect (the rect is in target surface
2198   // space).
2199   layer_draw_properties.drawable_content_rect = rect_in_target_space;
2200   if (layer_or_ancestor_clips_descendants) {
2201     layer_draw_properties.drawable_content_rect.Intersect(
2202         clip_rect_in_target_space);
2203   }
2204   if (layer->DrawsContent()) {
2205     local_drawable_content_rect_of_subtree.Union(
2206         layer_draw_properties.drawable_content_rect);
2207   }
2208
2209   // Compute the layer's visible content rect (the rect is in content space).
2210   layer_draw_properties.visible_content_rect = CalculateVisibleContentRect(
2211       layer, clip_rect_of_target_surface_in_target_space, rect_in_target_space);
2212
2213   // Compute the remaining properties for the render surface, if the layer has
2214   // one.
2215   if (IsRootLayer(layer)) {
2216     // The root layer's surface's content_rect is always the entire viewport.
2217     DCHECK(layer->render_surface());
2218     layer->render_surface()->SetContentRect(
2219         ancestor_clip_rect_in_target_space);
2220   } else if (layer->render_surface()) {
2221     typename LayerType::RenderSurfaceType* render_surface =
2222         layer->render_surface();
2223     gfx::Rect clipped_content_rect = local_drawable_content_rect_of_subtree;
2224
2225     // Don't clip if the layer is reflected as the reflection shouldn't be
2226     // clipped. If the layer is animating, then the surface's transform to
2227     // its target is not known on the main thread, and we should not use it
2228     // to clip.
2229     if (!layer->replica_layer() && TransformToParentIsKnown(layer)) {
2230       // Note, it is correct to use data_from_ancestor.ancestor_clips_subtree
2231       // here, because we are looking at this layer's render_surface, not the
2232       // layer itself.
2233       if (render_surface->is_clipped() && !clipped_content_rect.IsEmpty()) {
2234         gfx::Rect surface_clip_rect = LayerTreeHostCommon::CalculateVisibleRect(
2235             render_surface->clip_rect(),
2236             clipped_content_rect,
2237             render_surface->draw_transform());
2238         clipped_content_rect.Intersect(surface_clip_rect);
2239       }
2240     }
2241
2242     // The RenderSurfaceImpl backing texture cannot exceed the maximum supported
2243     // texture size.
2244     clipped_content_rect.set_width(
2245         std::min(clipped_content_rect.width(), globals.max_texture_size));
2246     clipped_content_rect.set_height(
2247         std::min(clipped_content_rect.height(), globals.max_texture_size));
2248
2249     if (clipped_content_rect.IsEmpty()) {
2250       RemoveSurfaceForEarlyExit(layer, render_surface_layer_list);
2251       return;
2252     }
2253
2254     // Layers having a non-default blend mode will blend with the content
2255     // inside its parent's render target. This render target should be
2256     // either root_for_isolated_group, or the root of the layer tree.
2257     // Otherwise, this layer will use an incomplete backdrop, limited to its
2258     // render target and the blending result will be incorrect.
2259     DCHECK(layer->uses_default_blend_mode() || IsRootLayer(layer) ||
2260            !layer->parent()->render_target() ||
2261            IsRootLayer(layer->parent()->render_target()) ||
2262            layer->parent()->render_target()->is_root_for_isolated_group());
2263
2264     render_surface->SetContentRect(clipped_content_rect);
2265
2266     // The owning layer's screen_space_transform has a scale from content to
2267     // layer space which we need to undo and replace with a scale from the
2268     // surface's subtree into layer space.
2269     gfx::Transform screen_space_transform = layer->screen_space_transform();
2270     screen_space_transform.Scale(
2271         layer->contents_scale_x() / render_surface_sublayer_scale.x(),
2272         layer->contents_scale_y() / render_surface_sublayer_scale.y());
2273     render_surface->SetScreenSpaceTransform(screen_space_transform);
2274
2275     if (layer->replica_layer()) {
2276       gfx::Transform surface_origin_to_replica_origin_transform;
2277       surface_origin_to_replica_origin_transform.Scale(
2278           render_surface_sublayer_scale.x(), render_surface_sublayer_scale.y());
2279       surface_origin_to_replica_origin_transform.Translate(
2280           layer->replica_layer()->position().x() +
2281               layer->replica_layer()->transform_origin().x(),
2282           layer->replica_layer()->position().y() +
2283               layer->replica_layer()->transform_origin().y());
2284       surface_origin_to_replica_origin_transform.PreconcatTransform(
2285           layer->replica_layer()->transform());
2286       surface_origin_to_replica_origin_transform.Translate(
2287           -layer->replica_layer()->transform_origin().x(),
2288           -layer->replica_layer()->transform_origin().y());
2289       surface_origin_to_replica_origin_transform.Scale(
2290           1.0 / render_surface_sublayer_scale.x(),
2291           1.0 / render_surface_sublayer_scale.y());
2292
2293       // Compute the replica's "originTransform" that maps from the replica's
2294       // origin space to the target surface origin space.
2295       gfx::Transform replica_origin_transform =
2296           layer->render_surface()->draw_transform() *
2297           surface_origin_to_replica_origin_transform;
2298       render_surface->SetReplicaDrawTransform(replica_origin_transform);
2299
2300       // Compute the replica's "screen_space_transform" that maps from the
2301       // replica's origin space to the screen's origin space.
2302       gfx::Transform replica_screen_space_transform =
2303           layer->render_surface()->screen_space_transform() *
2304           surface_origin_to_replica_origin_transform;
2305       render_surface->SetReplicaScreenSpaceTransform(
2306           replica_screen_space_transform);
2307     }
2308   }
2309
2310   SavePaintPropertiesLayer(layer);
2311
2312   // If neither this layer nor any of its children were added, early out.
2313   if (sorting_start_index == descendants.size()) {
2314     DCHECK(!layer->render_surface() || IsRootLayer(layer));
2315     return;
2316   }
2317
2318   // If preserves-3d then sort all the descendants in 3D so that they can be
2319   // drawn from back to front. If the preserves-3d property is also set on the
2320   // parent then skip the sorting as the parent will sort all the descendants
2321   // anyway.
2322   if (globals.layer_sorter && descendants.size() && layer->Is3dSorted() &&
2323       !LayerIsInExisting3DRenderingContext(layer)) {
2324     SortLayers(descendants.begin() + sorting_start_index,
2325                descendants.end(),
2326                globals.layer_sorter);
2327   }
2328
2329   UpdateAccumulatedSurfaceState<LayerType>(
2330       layer, local_drawable_content_rect_of_subtree, accumulated_surface_state);
2331
2332   if (layer->HasContributingDelegatedRenderPasses()) {
2333     layer->render_target()->render_surface()->
2334         AddContributingDelegatedRenderPassLayer(layer);
2335   }
2336 }  // NOLINT(readability/fn_size)
2337
2338 template <typename LayerType, typename RenderSurfaceLayerListType>
2339 static void ProcessCalcDrawPropsInputs(
2340     const LayerTreeHostCommon::CalcDrawPropsInputs<LayerType,
2341                                                    RenderSurfaceLayerListType>&
2342         inputs,
2343     SubtreeGlobals<LayerType>* globals,
2344     DataForRecursion<LayerType>* data_for_recursion) {
2345   DCHECK(inputs.root_layer);
2346   DCHECK(IsRootLayer(inputs.root_layer));
2347   DCHECK(inputs.render_surface_layer_list);
2348
2349   gfx::Transform identity_matrix;
2350
2351   // The root layer's render_surface should receive the device viewport as the
2352   // initial clip rect.
2353   gfx::Rect device_viewport_rect(inputs.device_viewport_size);
2354
2355   gfx::Vector2dF device_transform_scale_components =
2356       MathUtil::ComputeTransform2dScaleComponents(inputs.device_transform, 1.f);
2357   // Not handling the rare case of different x and y device scale.
2358   float device_transform_scale =
2359       std::max(device_transform_scale_components.x(),
2360                device_transform_scale_components.y());
2361
2362   gfx::Transform scaled_device_transform = inputs.device_transform;
2363   scaled_device_transform.Scale(inputs.device_scale_factor,
2364                                 inputs.device_scale_factor);
2365
2366   globals->layer_sorter = NULL;
2367   globals->max_texture_size = inputs.max_texture_size;
2368   globals->device_scale_factor =
2369       inputs.device_scale_factor * device_transform_scale;
2370   globals->page_scale_factor = inputs.page_scale_factor;
2371   globals->page_scale_application_layer = inputs.page_scale_application_layer;
2372   globals->can_render_to_separate_surface =
2373       inputs.can_render_to_separate_surface;
2374   globals->can_adjust_raster_scales = inputs.can_adjust_raster_scales;
2375
2376   data_for_recursion->parent_matrix = scaled_device_transform;
2377   data_for_recursion->full_hierarchy_matrix = identity_matrix;
2378   data_for_recursion->scroll_compensation_matrix = identity_matrix;
2379   data_for_recursion->fixed_container = inputs.root_layer;
2380   data_for_recursion->clip_rect_in_target_space = device_viewport_rect;
2381   data_for_recursion->clip_rect_of_target_surface_in_target_space =
2382       device_viewport_rect;
2383   data_for_recursion->maximum_animation_contents_scale = 0.f;
2384   data_for_recursion->ancestor_is_animating_scale = false;
2385   data_for_recursion->ancestor_clips_subtree = true;
2386   data_for_recursion->nearest_occlusion_immune_ancestor_surface = NULL;
2387   data_for_recursion->in_subtree_of_page_scale_application_layer = false;
2388   data_for_recursion->subtree_can_use_lcd_text = inputs.can_use_lcd_text;
2389   data_for_recursion->subtree_is_visible_from_ancestor = true;
2390 }
2391
2392 void LayerTreeHostCommon::CalculateDrawProperties(
2393     CalcDrawPropsMainInputs* inputs) {
2394   LayerList dummy_layer_list;
2395   SubtreeGlobals<Layer> globals;
2396   DataForRecursion<Layer> data_for_recursion;
2397   ProcessCalcDrawPropsInputs(*inputs, &globals, &data_for_recursion);
2398
2399   PreCalculateMetaInformationRecursiveData recursive_data;
2400   PreCalculateMetaInformation(inputs->root_layer, &recursive_data);
2401   std::vector<AccumulatedSurfaceState<Layer>> accumulated_surface_state;
2402   CalculateDrawPropertiesInternal<Layer>(
2403       inputs->root_layer,
2404       globals,
2405       data_for_recursion,
2406       inputs->render_surface_layer_list,
2407       &dummy_layer_list,
2408       &accumulated_surface_state,
2409       inputs->current_render_surface_layer_list_id);
2410
2411   // The dummy layer list should not have been used.
2412   DCHECK_EQ(0u, dummy_layer_list.size());
2413   // A root layer render_surface should always exist after
2414   // CalculateDrawProperties.
2415   DCHECK(inputs->root_layer->render_surface());
2416 }
2417
2418 void LayerTreeHostCommon::CalculateDrawProperties(
2419     CalcDrawPropsImplInputs* inputs) {
2420   LayerImplList dummy_layer_list;
2421   SubtreeGlobals<LayerImpl> globals;
2422   DataForRecursion<LayerImpl> data_for_recursion;
2423   ProcessCalcDrawPropsInputs(*inputs, &globals, &data_for_recursion);
2424
2425   LayerSorter layer_sorter;
2426   globals.layer_sorter = &layer_sorter;
2427
2428   PreCalculateMetaInformationRecursiveData recursive_data;
2429   PreCalculateMetaInformation(inputs->root_layer, &recursive_data);
2430   std::vector<AccumulatedSurfaceState<LayerImpl>> accumulated_surface_state;
2431   CalculateDrawPropertiesInternal<LayerImpl>(
2432       inputs->root_layer,
2433       globals,
2434       data_for_recursion,
2435       inputs->render_surface_layer_list,
2436       &dummy_layer_list,
2437       &accumulated_surface_state,
2438       inputs->current_render_surface_layer_list_id);
2439
2440   // The dummy layer list should not have been used.
2441   DCHECK_EQ(0u, dummy_layer_list.size());
2442   // A root layer render_surface should always exist after
2443   // CalculateDrawProperties.
2444   DCHECK(inputs->root_layer->render_surface());
2445 }
2446
2447 }  // namespace cc