- add sources.
[platform/framework/web/crosswalk.git] / src / cc / layers / tiled_layer.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/layers/tiled_layer.h"
6
7 #include <algorithm>
8 #include <vector>
9
10 #include "base/auto_reset.h"
11 #include "base/basictypes.h"
12 #include "build/build_config.h"
13 #include "cc/debug/overdraw_metrics.h"
14 #include "cc/layers/layer_impl.h"
15 #include "cc/layers/tiled_layer_impl.h"
16 #include "cc/resources/layer_updater.h"
17 #include "cc/resources/prioritized_resource.h"
18 #include "cc/resources/priority_calculator.h"
19 #include "cc/trees/layer_tree_host.h"
20 #include "third_party/khronos/GLES2/gl2.h"
21 #include "ui/gfx/rect_conversions.h"
22
23 namespace cc {
24
25 // Maximum predictive expansion of the visible area.
26 static const int kMaxPredictiveTilesCount = 2;
27
28 // Number of rows/columns of tiles to pre-paint.
29 // We should increase these further as all textures are
30 // prioritized and we insure performance doesn't suffer.
31 static const int kPrepaintRows = 4;
32 static const int kPrepaintColumns = 2;
33
34 class UpdatableTile : public LayerTilingData::Tile {
35  public:
36   static scoped_ptr<UpdatableTile> Create(
37       scoped_ptr<LayerUpdater::Resource> updater_resource) {
38     return make_scoped_ptr(new UpdatableTile(updater_resource.Pass()));
39   }
40
41   LayerUpdater::Resource* updater_resource() { return updater_resource_.get(); }
42   PrioritizedResource* managed_resource() {
43     return updater_resource_->texture();
44   }
45
46   bool is_dirty() const { return !dirty_rect.IsEmpty(); }
47
48   // Reset update state for the current frame. This should occur before painting
49   // for all layers. Since painting one layer can invalidate another layer after
50   // it has already painted, mark all non-dirty tiles as valid before painting
51   // such that invalidations during painting won't prevent them from being
52   // pushed.
53   void ResetUpdateState() {
54     update_rect = gfx::Rect();
55     occluded = false;
56     partial_update = false;
57     valid_for_frame = !is_dirty();
58   }
59
60   // This promises to update the tile and therefore also guarantees the tile
61   // will be valid for this frame. dirty_rect is copied into update_rect so we
62   // can continue to track re-entrant invalidations that occur during painting.
63   void MarkForUpdate() {
64     valid_for_frame = true;
65     update_rect = dirty_rect;
66     dirty_rect = gfx::Rect();
67   }
68
69   gfx::Rect dirty_rect;
70   gfx::Rect update_rect;
71   bool partial_update;
72   bool valid_for_frame;
73   bool occluded;
74
75  private:
76   explicit UpdatableTile(scoped_ptr<LayerUpdater::Resource> updater_resource)
77       : partial_update(false),
78         valid_for_frame(false),
79         occluded(false),
80         updater_resource_(updater_resource.Pass()) {}
81
82   scoped_ptr<LayerUpdater::Resource> updater_resource_;
83
84   DISALLOW_COPY_AND_ASSIGN(UpdatableTile);
85 };
86
87 TiledLayer::TiledLayer()
88     : ContentsScalingLayer(),
89       texture_format_(RGBA_8888),
90       skips_draw_(false),
91       failed_update_(false),
92       tiling_option_(AUTO_TILE) {
93   tiler_ =
94       LayerTilingData::Create(gfx::Size(), LayerTilingData::HAS_BORDER_TEXELS);
95 }
96
97 TiledLayer::~TiledLayer() {}
98
99 scoped_ptr<LayerImpl> TiledLayer::CreateLayerImpl(LayerTreeImpl* tree_impl) {
100   return TiledLayerImpl::Create(tree_impl, id()).PassAs<LayerImpl>();
101 }
102
103 void TiledLayer::UpdateTileSizeAndTilingOption() {
104   DCHECK(layer_tree_host());
105
106   gfx::Size default_tile_size = layer_tree_host()->settings().default_tile_size;
107   gfx::Size max_untiled_layer_size =
108       layer_tree_host()->settings().max_untiled_layer_size;
109   int layer_width = content_bounds().width();
110   int layer_height = content_bounds().height();
111
112   gfx::Size tile_size(std::min(default_tile_size.width(), layer_width),
113                       std::min(default_tile_size.height(), layer_height));
114
115   // Tile if both dimensions large, or any one dimension large and the other
116   // extends into a second tile but the total layer area isn't larger than that
117   // of the largest possible untiled layer. This heuristic allows for long
118   // skinny layers (e.g. scrollbars) that are Nx1 tiles to minimize wasted
119   // texture space but still avoids creating very large tiles.
120   bool any_dimension_large = layer_width > max_untiled_layer_size.width() ||
121                              layer_height > max_untiled_layer_size.height();
122   bool any_dimension_one_tile =
123       (layer_width <= default_tile_size.width() ||
124        layer_height <= default_tile_size.height()) &&
125       (layer_width * layer_height) <= (max_untiled_layer_size.width() *
126                                        max_untiled_layer_size.height());
127   bool auto_tiled = any_dimension_large && !any_dimension_one_tile;
128
129   bool is_tiled;
130   if (tiling_option_ == ALWAYS_TILE)
131     is_tiled = true;
132   else if (tiling_option_ == NEVER_TILE)
133     is_tiled = false;
134   else
135     is_tiled = auto_tiled;
136
137   gfx::Size requested_size = is_tiled ? tile_size : content_bounds();
138   const int max_size =
139       layer_tree_host()->GetRendererCapabilities().max_texture_size;
140   requested_size.SetToMin(gfx::Size(max_size, max_size));
141   SetTileSize(requested_size);
142 }
143
144 void TiledLayer::UpdateBounds() {
145   gfx::Size old_bounds = tiler_->bounds();
146   gfx::Size new_bounds = content_bounds();
147   if (old_bounds == new_bounds)
148     return;
149   tiler_->SetBounds(new_bounds);
150
151   // Invalidate any areas that the new bounds exposes.
152   Region old_region = gfx::Rect(old_bounds);
153   Region new_region = gfx::Rect(new_bounds);
154   new_region.Subtract(old_region);
155   for (Region::Iterator new_rects(new_region);
156        new_rects.has_rect();
157        new_rects.next())
158     InvalidateContentRect(new_rects.rect());
159 }
160
161 void TiledLayer::SetTileSize(gfx::Size size) { tiler_->SetTileSize(size); }
162
163 void TiledLayer::SetBorderTexelOption(
164     LayerTilingData::BorderTexelOption border_texel_option) {
165   tiler_->SetBorderTexelOption(border_texel_option);
166 }
167
168 bool TiledLayer::DrawsContent() const {
169   if (!ContentsScalingLayer::DrawsContent())
170     return false;
171
172   bool has_more_than_one_tile =
173       tiler_->num_tiles_x() > 1 || tiler_->num_tiles_y() > 1;
174   if (tiling_option_ == NEVER_TILE && has_more_than_one_tile)
175     return false;
176
177   return true;
178 }
179
180 void TiledLayer::ReduceMemoryUsage() {
181   if (Updater())
182     Updater()->ReduceMemoryUsage();
183 }
184
185 void TiledLayer::SetIsMask(bool is_mask) {
186   set_tiling_option(is_mask ? NEVER_TILE : AUTO_TILE);
187 }
188
189 void TiledLayer::PushPropertiesTo(LayerImpl* layer) {
190   ContentsScalingLayer::PushPropertiesTo(layer);
191
192   TiledLayerImpl* tiled_layer = static_cast<TiledLayerImpl*>(layer);
193
194   tiled_layer->set_skips_draw(skips_draw_);
195   tiled_layer->SetTilingData(*tiler_);
196   std::vector<UpdatableTile*> invalid_tiles;
197
198   for (LayerTilingData::TileMap::const_iterator iter = tiler_->tiles().begin();
199        iter != tiler_->tiles().end();
200        ++iter) {
201     int i = iter->first.first;
202     int j = iter->first.second;
203     UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second);
204     // TODO(enne): This should not ever be null.
205     if (!tile)
206       continue;
207
208     if (!tile->managed_resource()->have_backing_texture()) {
209       // Evicted tiles get deleted from both layers
210       invalid_tiles.push_back(tile);
211       continue;
212     }
213
214     if (!tile->valid_for_frame) {
215       // Invalidated tiles are set so they can get different debug colors.
216       tiled_layer->PushInvalidTile(i, j);
217       continue;
218     }
219
220     tiled_layer->PushTileProperties(
221         i,
222         j,
223         tile->managed_resource()->resource_id(),
224         tile->opaque_rect(),
225         tile->managed_resource()->contents_swizzled());
226   }
227   for (std::vector<UpdatableTile*>::const_iterator iter = invalid_tiles.begin();
228        iter != invalid_tiles.end();
229        ++iter)
230     tiler_->TakeTile((*iter)->i(), (*iter)->j());
231
232   // TiledLayer must push properties every frame, since viewport state and
233   // occlusion from anywhere in the tree can change what the layer decides to
234   // push to the impl tree.
235   needs_push_properties_ = true;
236 }
237
238 PrioritizedResourceManager* TiledLayer::ResourceManager() {
239   if (!layer_tree_host())
240     return NULL;
241   return layer_tree_host()->contents_texture_manager();
242 }
243
244 const PrioritizedResource* TiledLayer::ResourceAtForTesting(int i,
245                                                             int j) const {
246   UpdatableTile* tile = TileAt(i, j);
247   if (!tile)
248     return NULL;
249   return tile->managed_resource();
250 }
251
252 void TiledLayer::SetLayerTreeHost(LayerTreeHost* host) {
253   if (host && host != layer_tree_host()) {
254     for (LayerTilingData::TileMap::const_iterator
255              iter = tiler_->tiles().begin();
256          iter != tiler_->tiles().end();
257          ++iter) {
258       UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second);
259       // TODO(enne): This should not ever be null.
260       if (!tile)
261         continue;
262       tile->managed_resource()->SetTextureManager(
263           host->contents_texture_manager());
264     }
265   }
266   ContentsScalingLayer::SetLayerTreeHost(host);
267 }
268
269 UpdatableTile* TiledLayer::TileAt(int i, int j) const {
270   return static_cast<UpdatableTile*>(tiler_->TileAt(i, j));
271 }
272
273 UpdatableTile* TiledLayer::CreateTile(int i, int j) {
274   CreateUpdaterIfNeeded();
275
276   scoped_ptr<UpdatableTile> tile(
277       UpdatableTile::Create(Updater()->CreateResource(ResourceManager())));
278   tile->managed_resource()->SetDimensions(tiler_->tile_size(), texture_format_);
279
280   UpdatableTile* added_tile = tile.get();
281   tiler_->AddTile(tile.PassAs<LayerTilingData::Tile>(), i, j);
282
283   added_tile->dirty_rect = tiler_->TileRect(added_tile);
284
285   // Temporary diagnostic crash.
286   CHECK(added_tile);
287   CHECK(TileAt(i, j));
288
289   return added_tile;
290 }
291
292 void TiledLayer::SetNeedsDisplayRect(const gfx::RectF& dirty_rect) {
293   InvalidateContentRect(LayerRectToContentRect(dirty_rect));
294   ContentsScalingLayer::SetNeedsDisplayRect(dirty_rect);
295 }
296
297 void TiledLayer::InvalidateContentRect(gfx::Rect content_rect) {
298   UpdateBounds();
299   if (tiler_->is_empty() || content_rect.IsEmpty() || skips_draw_)
300     return;
301
302   for (LayerTilingData::TileMap::const_iterator iter = tiler_->tiles().begin();
303        iter != tiler_->tiles().end();
304        ++iter) {
305     UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second);
306     DCHECK(tile);
307     // TODO(enne): This should not ever be null.
308     if (!tile)
309       continue;
310     gfx::Rect bound = tiler_->TileRect(tile);
311     bound.Intersect(content_rect);
312     tile->dirty_rect.Union(bound);
313   }
314 }
315
316 // Returns true if tile is dirty and only part of it needs to be updated.
317 bool TiledLayer::TileOnlyNeedsPartialUpdate(UpdatableTile* tile) {
318   return !tile->dirty_rect.Contains(tiler_->TileRect(tile)) &&
319          tile->managed_resource()->have_backing_texture();
320 }
321
322 bool TiledLayer::UpdateTiles(int left,
323                              int top,
324                              int right,
325                              int bottom,
326                              ResourceUpdateQueue* queue,
327                              const OcclusionTracker* occlusion,
328                              bool* updated) {
329   CreateUpdaterIfNeeded();
330
331   bool ignore_occlusions = !occlusion;
332   if (!HaveTexturesForTiles(left, top, right, bottom, ignore_occlusions)) {
333     failed_update_ = true;
334     return false;
335   }
336
337   gfx::Rect paint_rect =
338       MarkTilesForUpdate(left, top, right, bottom, ignore_occlusions);
339
340   if (occlusion)
341     occlusion->overdraw_metrics()->DidPaint(paint_rect);
342
343   if (paint_rect.IsEmpty())
344     return true;
345
346   *updated = true;
347   UpdateTileTextures(
348       paint_rect, left, top, right, bottom, queue, occlusion);
349   return true;
350 }
351
352 void TiledLayer::MarkOcclusionsAndRequestTextures(
353     int left,
354     int top,
355     int right,
356     int bottom,
357     const OcclusionTracker* occlusion) {
358   // There is some difficult dependancies between occlusions, recording
359   // occlusion metrics and requesting memory so those are encapsulated in this
360   // function: - We only want to call RequestLate on unoccluded textures (to
361   // preserve memory for other layers when near OOM).  - We only want to record
362   // occlusion metrics if all memory requests succeed.
363
364   int occluded_tile_count = 0;
365   bool succeeded = true;
366   for (int j = top; j <= bottom; ++j) {
367     for (int i = left; i <= right; ++i) {
368       UpdatableTile* tile = TileAt(i, j);
369       DCHECK(tile);  // Did SetTexturePriorities get skipped?
370       // TODO(enne): This should not ever be null.
371       if (!tile)
372         continue;
373       // Did ResetUpdateState get skipped? Are we doing more than one occlusion
374       // pass?
375       DCHECK(!tile->occluded);
376       gfx::Rect visible_tile_rect = gfx::IntersectRects(
377           tiler_->tile_bounds(i, j), visible_content_rect());
378       if (occlusion && occlusion->Occluded(render_target(),
379                                            visible_tile_rect,
380                                            draw_transform(),
381                                            draw_transform_is_animating())) {
382         tile->occluded = true;
383         occluded_tile_count++;
384       } else {
385         succeeded &= tile->managed_resource()->RequestLate();
386       }
387     }
388   }
389
390   if (!succeeded)
391     return;
392   if (occlusion)
393     occlusion->overdraw_metrics()->DidCullTilesForUpload(occluded_tile_count);
394 }
395
396 bool TiledLayer::HaveTexturesForTiles(int left,
397                                       int top,
398                                       int right,
399                                       int bottom,
400                                       bool ignore_occlusions) {
401   for (int j = top; j <= bottom; ++j) {
402     for (int i = left; i <= right; ++i) {
403       UpdatableTile* tile = TileAt(i, j);
404       DCHECK(tile);  // Did SetTexturePriorites get skipped?
405                      // TODO(enne): This should not ever be null.
406       if (!tile)
407         continue;
408
409       // Ensure the entire tile is dirty if we don't have the texture.
410       if (!tile->managed_resource()->have_backing_texture())
411         tile->dirty_rect = tiler_->TileRect(tile);
412
413       // If using occlusion and the visible region of the tile is occluded,
414       // don't reserve a texture or update the tile.
415       if (tile->occluded && !ignore_occlusions)
416         continue;
417
418       if (!tile->managed_resource()->can_acquire_backing_texture())
419         return false;
420     }
421   }
422   return true;
423 }
424
425 gfx::Rect TiledLayer::MarkTilesForUpdate(int left,
426                                          int top,
427                                          int right,
428                                          int bottom,
429                                          bool ignore_occlusions) {
430   gfx::Rect paint_rect;
431   for (int j = top; j <= bottom; ++j) {
432     for (int i = left; i <= right; ++i) {
433       UpdatableTile* tile = TileAt(i, j);
434       DCHECK(tile);  // Did SetTexturePriorites get skipped?
435                      // TODO(enne): This should not ever be null.
436       if (!tile)
437         continue;
438       if (tile->occluded && !ignore_occlusions)
439         continue;
440       // TODO(reveman): Decide if partial update should be allowed based on cost
441       // of update. https://bugs.webkit.org/show_bug.cgi?id=77376
442       if (tile->is_dirty() &&
443           !layer_tree_host()->AlwaysUsePartialTextureUpdates()) {
444         // If we get a partial update, we use the same texture, otherwise return
445         // the current texture backing, so we don't update visible textures
446         // non-atomically.  If the current backing is in-use, it won't be
447         // deleted until after the commit as the texture manager will not allow
448         // deletion or recycling of in-use textures.
449         if (TileOnlyNeedsPartialUpdate(tile) &&
450             layer_tree_host()->RequestPartialTextureUpdate()) {
451           tile->partial_update = true;
452         } else {
453           tile->dirty_rect = tiler_->TileRect(tile);
454           tile->managed_resource()->ReturnBackingTexture();
455         }
456       }
457
458       paint_rect.Union(tile->dirty_rect);
459       tile->MarkForUpdate();
460     }
461   }
462   return paint_rect;
463 }
464
465 void TiledLayer::UpdateTileTextures(gfx::Rect paint_rect,
466                                     int left,
467                                     int top,
468                                     int right,
469                                     int bottom,
470                                     ResourceUpdateQueue* queue,
471                                     const OcclusionTracker* occlusion) {
472   // The update_rect should be in layer space. So we have to convert the
473   // paint_rect from content space to layer space.
474   float width_scale =
475       paint_properties().bounds.width() /
476       static_cast<float>(content_bounds().width());
477   float height_scale =
478       paint_properties().bounds.height() /
479       static_cast<float>(content_bounds().height());
480   update_rect_ = gfx::ScaleRect(paint_rect, width_scale, height_scale);
481
482   // Calling PrepareToUpdate() calls into WebKit to paint, which may have the
483   // side effect of disabling compositing, which causes our reference to the
484   // texture updater to be deleted.  However, we can't free the memory backing
485   // the SkCanvas until the paint finishes, so we grab a local reference here to
486   // hold the updater alive until the paint completes.
487   scoped_refptr<LayerUpdater> protector(Updater());
488   gfx::Rect painted_opaque_rect;
489   Updater()->PrepareToUpdate(paint_rect,
490                              tiler_->tile_size(),
491                              1.f / width_scale,
492                              1.f / height_scale,
493                              &painted_opaque_rect);
494
495   for (int j = top; j <= bottom; ++j) {
496     for (int i = left; i <= right; ++i) {
497       UpdatableTile* tile = TileAt(i, j);
498       DCHECK(tile);  // Did SetTexturePriorites get skipped?
499                      // TODO(enne): This should not ever be null.
500       if (!tile)
501         continue;
502
503       gfx::Rect tile_rect = tiler_->tile_bounds(i, j);
504
505       // Use update_rect as the above loop copied the dirty rect for this frame
506       // to update_rect.
507       gfx::Rect dirty_rect = tile->update_rect;
508       if (dirty_rect.IsEmpty())
509         continue;
510
511       // Save what was painted opaque in the tile. Keep the old area if the
512       // paint didn't touch it, and didn't paint some other part of the tile
513       // opaque.
514       gfx::Rect tile_painted_rect = gfx::IntersectRects(tile_rect, paint_rect);
515       gfx::Rect tile_painted_opaque_rect =
516           gfx::IntersectRects(tile_rect, painted_opaque_rect);
517       if (!tile_painted_rect.IsEmpty()) {
518         gfx::Rect paint_inside_tile_opaque_rect =
519             gfx::IntersectRects(tile->opaque_rect(), tile_painted_rect);
520         bool paint_inside_tile_opaque_rect_is_non_opaque =
521             !paint_inside_tile_opaque_rect.IsEmpty() &&
522             !tile_painted_opaque_rect.Contains(paint_inside_tile_opaque_rect);
523         bool opaque_paint_not_inside_tile_opaque_rect =
524             !tile_painted_opaque_rect.IsEmpty() &&
525             !tile->opaque_rect().Contains(tile_painted_opaque_rect);
526
527         if (paint_inside_tile_opaque_rect_is_non_opaque ||
528             opaque_paint_not_inside_tile_opaque_rect)
529           tile->set_opaque_rect(tile_painted_opaque_rect);
530       }
531
532       // source_rect starts as a full-sized tile with border texels included.
533       gfx::Rect source_rect = tiler_->TileRect(tile);
534       source_rect.Intersect(dirty_rect);
535       // Paint rect not guaranteed to line up on tile boundaries, so
536       // make sure that source_rect doesn't extend outside of it.
537       source_rect.Intersect(paint_rect);
538
539       tile->update_rect = source_rect;
540
541       if (source_rect.IsEmpty())
542         continue;
543
544       const gfx::Point anchor = tiler_->TileRect(tile).origin();
545
546       // Calculate tile-space rectangle to upload into.
547       gfx::Vector2d dest_offset = source_rect.origin() - anchor;
548       CHECK_GE(dest_offset.x(), 0);
549       CHECK_GE(dest_offset.y(), 0);
550
551       // Offset from paint rectangle to this tile's dirty rectangle.
552       gfx::Vector2d paint_offset = source_rect.origin() - paint_rect.origin();
553       CHECK_GE(paint_offset.x(), 0);
554       CHECK_GE(paint_offset.y(), 0);
555       CHECK_LE(paint_offset.x() + source_rect.width(), paint_rect.width());
556       CHECK_LE(paint_offset.y() + source_rect.height(), paint_rect.height());
557
558       tile->updater_resource()->Update(
559           queue, source_rect, dest_offset, tile->partial_update);
560       if (occlusion) {
561         occlusion->overdraw_metrics()->
562             DidUpload(gfx::Transform(), source_rect, tile->opaque_rect());
563       }
564     }
565   }
566 }
567
568 // This picks a small animated layer to be anything less than one viewport. This
569 // is specifically for page transitions which are viewport-sized layers. The
570 // extra tile of padding is due to these layers being slightly larger than the
571 // viewport in some cases.
572 bool TiledLayer::IsSmallAnimatedLayer() const {
573   if (!draw_transform_is_animating() && !screen_space_transform_is_animating())
574     return false;
575   gfx::Size viewport_size =
576       layer_tree_host() ? layer_tree_host()->device_viewport_size()
577                         : gfx::Size();
578   gfx::Rect content_rect(content_bounds());
579   return content_rect.width() <=
580          viewport_size.width() + tiler_->tile_size().width() &&
581          content_rect.height() <=
582          viewport_size.height() + tiler_->tile_size().height();
583 }
584
585 namespace {
586 // TODO(epenner): Remove this and make this based on distance once distance can
587 // be calculated for offscreen layers. For now, prioritize all small animated
588 // layers after 512 pixels of pre-painting.
589 void SetPriorityForTexture(gfx::Rect visible_rect,
590                            gfx::Rect tile_rect,
591                            bool draws_to_root,
592                            bool is_small_animated_layer,
593                            PrioritizedResource* texture) {
594   int priority = PriorityCalculator::LowestPriority();
595   if (!visible_rect.IsEmpty()) {
596     priority = PriorityCalculator::PriorityFromDistance(
597         visible_rect, tile_rect, draws_to_root);
598   }
599
600   if (is_small_animated_layer) {
601     priority = PriorityCalculator::max_priority(
602         priority, PriorityCalculator::SmallAnimatedLayerMinPriority());
603   }
604
605   if (priority != PriorityCalculator::LowestPriority())
606     texture->set_request_priority(priority);
607 }
608 }  // namespace
609
610 void TiledLayer::SetTexturePriorities(const PriorityCalculator& priority_calc) {
611   UpdateBounds();
612   ResetUpdateState();
613   UpdateScrollPrediction();
614
615   if (tiler_->has_empty_bounds())
616     return;
617
618   bool draws_to_root = !render_target()->parent();
619   bool small_animated_layer = IsSmallAnimatedLayer();
620
621   // Minimally create the tiles in the desired pre-paint rect.
622   gfx::Rect create_tiles_rect = IdlePaintRect();
623   if (small_animated_layer)
624     create_tiles_rect = gfx::Rect(content_bounds());
625   if (!create_tiles_rect.IsEmpty()) {
626     int left, top, right, bottom;
627     tiler_->ContentRectToTileIndices(
628         create_tiles_rect, &left, &top, &right, &bottom);
629     for (int j = top; j <= bottom; ++j) {
630       for (int i = left; i <= right; ++i) {
631         if (!TileAt(i, j))
632           CreateTile(i, j);
633       }
634     }
635   }
636
637   // Now update priorities on all tiles we have in the layer, no matter where
638   // they are.
639   for (LayerTilingData::TileMap::const_iterator iter = tiler_->tiles().begin();
640        iter != tiler_->tiles().end();
641        ++iter) {
642     UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second);
643     // TODO(enne): This should not ever be null.
644     if (!tile)
645       continue;
646     gfx::Rect tile_rect = tiler_->TileRect(tile);
647     SetPriorityForTexture(predicted_visible_rect_,
648                           tile_rect,
649                           draws_to_root,
650                           small_animated_layer,
651                           tile->managed_resource());
652   }
653 }
654
655 Region TiledLayer::VisibleContentOpaqueRegion() const {
656   if (skips_draw_)
657     return Region();
658   if (contents_opaque())
659     return visible_content_rect();
660   return tiler_->OpaqueRegionInContentRect(visible_content_rect());
661 }
662
663 void TiledLayer::ResetUpdateState() {
664   skips_draw_ = false;
665   failed_update_ = false;
666
667   LayerTilingData::TileMap::const_iterator end = tiler_->tiles().end();
668   for (LayerTilingData::TileMap::const_iterator iter = tiler_->tiles().begin();
669        iter != end;
670        ++iter) {
671     UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second);
672     // TODO(enne): This should not ever be null.
673     if (!tile)
674       continue;
675     tile->ResetUpdateState();
676   }
677 }
678
679 namespace {
680 gfx::Rect ExpandRectByDelta(gfx::Rect rect, gfx::Vector2d delta) {
681   int width = rect.width() + std::abs(delta.x());
682   int height = rect.height() + std::abs(delta.y());
683   int x = rect.x() + ((delta.x() < 0) ? delta.x() : 0);
684   int y = rect.y() + ((delta.y() < 0) ? delta.y() : 0);
685   return gfx::Rect(x, y, width, height);
686 }
687 }
688
689 void TiledLayer::UpdateScrollPrediction() {
690   // This scroll prediction is very primitive and should be replaced by a
691   // a recursive calculation on all layers which uses actual scroll/animation
692   // velocities. To insure this doesn't miss-predict, we only use it to predict
693   // the visible_rect if:
694   // - content_bounds() hasn't changed.
695   // - visible_rect.size() hasn't changed.
696   // These two conditions prevent rotations, scales, pinch-zooms etc. where
697   // the prediction would be incorrect.
698   gfx::Vector2d delta = visible_content_rect().CenterPoint() -
699                         previous_visible_rect_.CenterPoint();
700   predicted_scroll_ = -delta;
701   predicted_visible_rect_ = visible_content_rect();
702   if (previous_content_bounds_ == content_bounds() &&
703       previous_visible_rect_.size() == visible_content_rect().size()) {
704     // Only expand the visible rect in the major scroll direction, to prevent
705     // massive paints due to diagonal scrolls.
706     gfx::Vector2d major_scroll_delta =
707         (std::abs(delta.x()) > std::abs(delta.y())) ?
708         gfx::Vector2d(delta.x(), 0) :
709         gfx::Vector2d(0, delta.y());
710     predicted_visible_rect_ =
711         ExpandRectByDelta(visible_content_rect(), major_scroll_delta);
712
713     // Bound the prediction to prevent unbounded paints, and clamp to content
714     // bounds.
715     gfx::Rect bound = visible_content_rect();
716     bound.Inset(-tiler_->tile_size().width() * kMaxPredictiveTilesCount,
717                 -tiler_->tile_size().height() * kMaxPredictiveTilesCount);
718     bound.Intersect(gfx::Rect(content_bounds()));
719     predicted_visible_rect_.Intersect(bound);
720   }
721   previous_content_bounds_ = content_bounds();
722   previous_visible_rect_ = visible_content_rect();
723 }
724
725 bool TiledLayer::Update(ResourceUpdateQueue* queue,
726                         const OcclusionTracker* occlusion) {
727   DCHECK(!skips_draw_ && !failed_update_);  // Did ResetUpdateState get skipped?
728
729   // Tiled layer always causes commits to wait for activation, as it does
730   // not support pending trees.
731   SetNextCommitWaitsForActivation();
732
733   bool updated = false;
734
735   {
736     base::AutoReset<bool> ignore_set_needs_commit(&ignore_set_needs_commit_,
737                                                   true);
738
739     updated |= ContentsScalingLayer::Update(queue, occlusion);
740     UpdateBounds();
741   }
742
743   if (tiler_->has_empty_bounds() || !DrawsContent())
744     return false;
745
746   // Animation pre-paint. If the layer is small, try to paint it all
747   // immediately whether or not it is occluded, to avoid paint/upload
748   // hiccups while it is animating.
749   if (IsSmallAnimatedLayer()) {
750     int left, top, right, bottom;
751     tiler_->ContentRectToTileIndices(gfx::Rect(content_bounds()),
752                                      &left,
753                                      &top,
754                                      &right,
755                                      &bottom);
756     UpdateTiles(left, top, right, bottom, queue, NULL, &updated);
757     if (updated)
758       return updated;
759     // This was an attempt to paint the entire layer so if we fail it's okay,
760     // just fallback on painting visible etc. below.
761     failed_update_ = false;
762   }
763
764   if (predicted_visible_rect_.IsEmpty())
765     return updated;
766
767   // Visible painting. First occlude visible tiles and paint the non-occluded
768   // tiles.
769   int left, top, right, bottom;
770   tiler_->ContentRectToTileIndices(
771       predicted_visible_rect_, &left, &top, &right, &bottom);
772   MarkOcclusionsAndRequestTextures(left, top, right, bottom, occlusion);
773   skips_draw_ = !UpdateTiles(
774       left, top, right, bottom, queue, occlusion, &updated);
775   if (skips_draw_)
776     tiler_->reset();
777   if (skips_draw_ || updated)
778     return true;
779
780   // If we have already painting everything visible. Do some pre-painting while
781   // idle.
782   gfx::Rect idle_paint_content_rect = IdlePaintRect();
783   if (idle_paint_content_rect.IsEmpty())
784     return updated;
785
786   // Prepaint anything that was occluded but inside the layer's visible region.
787   if (!UpdateTiles(left, top, right, bottom, queue, NULL, &updated) ||
788       updated)
789     return updated;
790
791   int prepaint_left, prepaint_top, prepaint_right, prepaint_bottom;
792   tiler_->ContentRectToTileIndices(idle_paint_content_rect,
793                                    &prepaint_left,
794                                    &prepaint_top,
795                                    &prepaint_right,
796                                    &prepaint_bottom);
797
798   // Then expand outwards one row/column at a time until we find a dirty
799   // row/column to update. Increment along the major and minor scroll directions
800   // first.
801   gfx::Vector2d delta = -predicted_scroll_;
802   delta = gfx::Vector2d(delta.x() == 0 ? 1 : delta.x(),
803                         delta.y() == 0 ? 1 : delta.y());
804   gfx::Vector2d major_delta =
805       (std::abs(delta.x()) > std::abs(delta.y())) ? gfx::Vector2d(delta.x(), 0)
806                                         : gfx::Vector2d(0, delta.y());
807   gfx::Vector2d minor_delta =
808       (std::abs(delta.x()) <= std::abs(delta.y())) ? gfx::Vector2d(delta.x(), 0)
809                                          : gfx::Vector2d(0, delta.y());
810   gfx::Vector2d deltas[4] = { major_delta, minor_delta, -major_delta,
811                               -minor_delta };
812   for (int i = 0; i < 4; i++) {
813     if (deltas[i].y() > 0) {
814       while (bottom < prepaint_bottom) {
815         ++bottom;
816         if (!UpdateTiles(
817                 left, bottom, right, bottom, queue, NULL, &updated) ||
818             updated)
819           return updated;
820       }
821     }
822     if (deltas[i].y() < 0) {
823       while (top > prepaint_top) {
824         --top;
825         if (!UpdateTiles(
826                 left, top, right, top, queue, NULL, &updated) ||
827             updated)
828           return updated;
829       }
830     }
831     if (deltas[i].x() < 0) {
832       while (left > prepaint_left) {
833         --left;
834         if (!UpdateTiles(
835                 left, top, left, bottom, queue, NULL, &updated) ||
836             updated)
837           return updated;
838       }
839     }
840     if (deltas[i].x() > 0) {
841       while (right < prepaint_right) {
842         ++right;
843         if (!UpdateTiles(
844                 right, top, right, bottom, queue, NULL, &updated) ||
845             updated)
846           return updated;
847       }
848     }
849   }
850   return updated;
851 }
852
853 void TiledLayer::OnOutputSurfaceCreated() {
854   // Ensure that all textures are of the right format.
855   for (LayerTilingData::TileMap::const_iterator iter = tiler_->tiles().begin();
856        iter != tiler_->tiles().end();
857        ++iter) {
858     UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second);
859     if (!tile)
860       continue;
861     PrioritizedResource* resource = tile->managed_resource();
862     resource->SetDimensions(resource->size(), texture_format_);
863   }
864 }
865
866 bool TiledLayer::NeedsIdlePaint() {
867   // Don't trigger more paints if we failed (as we'll just fail again).
868   if (failed_update_ || visible_content_rect().IsEmpty() ||
869       tiler_->has_empty_bounds() || !DrawsContent())
870     return false;
871
872   gfx::Rect idle_paint_content_rect = IdlePaintRect();
873   if (idle_paint_content_rect.IsEmpty())
874     return false;
875
876   int left, top, right, bottom;
877   tiler_->ContentRectToTileIndices(
878       idle_paint_content_rect, &left, &top, &right, &bottom);
879
880   for (int j = top; j <= bottom; ++j) {
881     for (int i = left; i <= right; ++i) {
882       UpdatableTile* tile = TileAt(i, j);
883       DCHECK(tile);  // Did SetTexturePriorities get skipped?
884       if (!tile)
885         continue;
886
887       bool updated = !tile->update_rect.IsEmpty();
888       bool can_acquire =
889           tile->managed_resource()->can_acquire_backing_texture();
890       bool dirty =
891           tile->is_dirty() || !tile->managed_resource()->have_backing_texture();
892       if (!updated && can_acquire && dirty)
893         return true;
894     }
895   }
896   return false;
897 }
898
899 gfx::Rect TiledLayer::IdlePaintRect() {
900   // Don't inflate an empty rect.
901   if (visible_content_rect().IsEmpty())
902     return gfx::Rect();
903
904   gfx::Rect prepaint_rect = visible_content_rect();
905   prepaint_rect.Inset(-tiler_->tile_size().width() * kPrepaintColumns,
906                       -tiler_->tile_size().height() * kPrepaintRows);
907   gfx::Rect content_rect(content_bounds());
908   prepaint_rect.Intersect(content_rect);
909
910   return prepaint_rect;
911 }
912
913 }  // namespace cc