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