1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "cc/resources/picture_layer_tiling.h"
11 #include "base/debug/trace_event.h"
12 #include "base/debug/trace_event_argument.h"
13 #include "base/logging.h"
14 #include "cc/base/math_util.h"
15 #include "cc/resources/tile.h"
16 #include "cc/resources/tile_priority.h"
17 #include "cc/trees/occlusion_tracker.h"
18 #include "ui/gfx/point_conversions.h"
19 #include "ui/gfx/rect_conversions.h"
20 #include "ui/gfx/safe_integer_conversions.h"
21 #include "ui/gfx/size_conversions.h"
26 const float kSoonBorderDistanceInScreenPixels = 312.f;
28 class TileEvictionOrder {
30 explicit TileEvictionOrder(TreePriority tree_priority)
31 : tree_priority_(tree_priority) {}
32 ~TileEvictionOrder() {}
34 bool operator()(const Tile* a, const Tile* b) {
35 const TilePriority& a_priority =
36 a->priority_for_tree_priority(tree_priority_);
37 const TilePriority& b_priority =
38 b->priority_for_tree_priority(tree_priority_);
40 DCHECK(a_priority.priority_bin == b_priority.priority_bin);
41 DCHECK(a->required_for_activation() == b->required_for_activation());
43 // Or if a is occluded and b is unoccluded.
44 bool a_is_occluded = a->is_occluded_for_tree_priority(tree_priority_);
45 bool b_is_occluded = b->is_occluded_for_tree_priority(tree_priority_);
46 if (a_is_occluded != b_is_occluded)
49 // Or if a is farther away from visible.
50 return a_priority.distance_to_visible > b_priority.distance_to_visible;
54 TreePriority tree_priority_;
57 void ReleaseTile(Tile* tile, WhichTree tree) {
58 // Reset priority as tile is ref-counted and might still be used
59 // even though we no longer hold a reference to it here anymore.
60 tile->SetPriority(tree, TilePriority());
65 scoped_ptr<PictureLayerTiling> PictureLayerTiling::Create(
67 const gfx::Size& layer_bounds,
68 PictureLayerTilingClient* client) {
69 return make_scoped_ptr(new PictureLayerTiling(contents_scale,
74 PictureLayerTiling::PictureLayerTiling(float contents_scale,
75 const gfx::Size& layer_bounds,
76 PictureLayerTilingClient* client)
77 : contents_scale_(contents_scale),
78 layer_bounds_(layer_bounds),
79 resolution_(NON_IDEAL_RESOLUTION),
81 tiling_data_(gfx::Size(), gfx::Size(), true),
82 last_impl_frame_time_in_seconds_(0.0),
83 has_visible_rect_tiles_(false),
84 has_skewport_rect_tiles_(false),
85 has_soon_border_rect_tiles_(false),
86 has_eventually_rect_tiles_(false),
87 eviction_tiles_cache_valid_(false),
88 eviction_cache_tree_priority_(SAME_PRIORITY_FOR_BOTH_TREES) {
89 gfx::Size content_bounds =
90 gfx::ToCeiledSize(gfx::ScaleSize(layer_bounds, contents_scale));
91 gfx::Size tile_size = client_->CalculateTileSize(content_bounds);
92 if (tile_size.IsEmpty()) {
93 layer_bounds_ = gfx::Size();
94 content_bounds = gfx::Size();
97 DCHECK(!gfx::ToFlooredSize(
98 gfx::ScaleSize(layer_bounds, contents_scale)).IsEmpty()) <<
99 "Tiling created with scale too small as contents become empty." <<
100 " Layer bounds: " << layer_bounds.ToString() <<
101 " Contents scale: " << contents_scale;
103 tiling_data_.SetTilingSize(content_bounds);
104 tiling_data_.SetMaxTextureSize(tile_size);
107 PictureLayerTiling::~PictureLayerTiling() {
108 for (TileMap::const_iterator it = tiles_.begin(); it != tiles_.end(); ++it)
109 ReleaseTile(it->second.get(), client_->GetTree());
112 void PictureLayerTiling::SetClient(PictureLayerTilingClient* client) {
116 Tile* PictureLayerTiling::CreateTile(int i,
118 const PictureLayerTiling* twin_tiling) {
119 TileMapKey key(i, j);
120 DCHECK(tiles_.find(key) == tiles_.end());
122 gfx::Rect paint_rect = tiling_data_.TileBoundsWithBorder(i, j);
123 gfx::Rect tile_rect = paint_rect;
124 tile_rect.set_size(tiling_data_.max_texture_size());
126 // Check our twin for a valid tile.
128 tiling_data_.max_texture_size() ==
129 twin_tiling->tiling_data_.max_texture_size()) {
130 if (Tile* candidate_tile = twin_tiling->TileAt(i, j)) {
132 gfx::ScaleToEnclosingRect(paint_rect, 1.0f / contents_scale_);
133 if (!client_->GetInvalidation()->Intersects(rect)) {
134 tiles_[key] = candidate_tile;
135 return candidate_tile;
140 // Create a new tile because our twin didn't have a valid one.
141 scoped_refptr<Tile> tile = client_->CreateTile(this, tile_rect);
147 void PictureLayerTiling::CreateMissingTilesInLiveTilesRect() {
148 const PictureLayerTiling* twin_tiling = client_->GetTwinTiling(this);
149 bool include_borders = false;
150 for (TilingData::Iterator iter(
151 &tiling_data_, live_tiles_rect_, include_borders);
154 TileMapKey key = iter.index();
155 TileMap::iterator find = tiles_.find(key);
156 if (find != tiles_.end())
158 CreateTile(key.first, key.second, twin_tiling);
161 VerifyLiveTilesRect();
164 void PictureLayerTiling::UpdateTilesToCurrentPile(
165 const Region& layer_invalidation,
166 const gfx::Size& new_layer_bounds) {
167 DCHECK(!new_layer_bounds.IsEmpty());
169 gfx::Size tile_size = tiling_data_.max_texture_size();
171 if (new_layer_bounds != layer_bounds_) {
172 gfx::Size content_bounds =
173 gfx::ToCeiledSize(gfx::ScaleSize(new_layer_bounds, contents_scale_));
175 tile_size = client_->CalculateTileSize(content_bounds);
176 if (tile_size.IsEmpty()) {
177 layer_bounds_ = gfx::Size();
178 content_bounds = gfx::Size();
180 layer_bounds_ = new_layer_bounds;
183 // The SetLiveTilesRect() method would drop tiles outside the new bounds,
184 // but may do so incorrectly if resizing the tiling causes the number of
185 // tiles in the tiling_data_ to change.
186 gfx::Rect content_rect(content_bounds);
187 int before_left = tiling_data_.TileXIndexFromSrcCoord(live_tiles_rect_.x());
188 int before_top = tiling_data_.TileYIndexFromSrcCoord(live_tiles_rect_.y());
190 tiling_data_.TileXIndexFromSrcCoord(live_tiles_rect_.right() - 1);
192 tiling_data_.TileYIndexFromSrcCoord(live_tiles_rect_.bottom() - 1);
194 // The live_tiles_rect_ is clamped to stay within the tiling size as we
196 live_tiles_rect_.Intersect(content_rect);
197 tiling_data_.SetTilingSize(content_bounds);
199 int after_right = -1;
200 int after_bottom = -1;
201 if (!live_tiles_rect_.IsEmpty()) {
203 tiling_data_.TileXIndexFromSrcCoord(live_tiles_rect_.right() - 1);
205 tiling_data_.TileYIndexFromSrcCoord(live_tiles_rect_.bottom() - 1);
208 // Drop tiles outside the new layer bounds if the layer shrank.
209 for (int i = after_right + 1; i <= before_right; ++i) {
210 for (int j = before_top; j <= before_bottom; ++j) {
211 TileMap::iterator found = tiles_.find(TileMapKey(i, j));
212 if (found == tiles_.end())
214 ReleaseTile(found->second.get(), client_->GetTree());
218 for (int i = before_left; i <= after_right; ++i) {
219 for (int j = after_bottom + 1; j <= before_bottom; ++j) {
220 TileMap::iterator found = tiles_.find(TileMapKey(i, j));
221 if (found == tiles_.end())
223 ReleaseTile(found->second.get(), client_->GetTree());
228 // If the layer grew, the live_tiles_rect_ is not changed, but a new row
229 // and/or column of tiles may now exist inside the same live_tiles_rect_.
230 const PictureLayerTiling* twin_tiling = client_->GetTwinTiling(this);
231 if (after_right > before_right) {
232 DCHECK_EQ(after_right, before_right + 1);
233 for (int j = before_top; j <= after_bottom; ++j)
234 CreateTile(after_right, j, twin_tiling);
236 if (after_bottom > before_bottom) {
237 DCHECK_EQ(after_bottom, before_bottom + 1);
238 for (int i = before_left; i <= before_right; ++i)
239 CreateTile(i, after_bottom, twin_tiling);
243 if (tile_size != tiling_data_.max_texture_size()) {
244 tiling_data_.SetMaxTextureSize(tile_size);
245 // When the tile size changes, the TilingData positions no longer work
246 // as valid keys to the TileMap, so just drop all tiles.
249 Invalidate(layer_invalidation);
252 PicturePileImpl* pile = client_->GetPile();
253 for (TileMap::const_iterator it = tiles_.begin(); it != tiles_.end(); ++it)
254 it->second->set_picture_pile(pile);
255 VerifyLiveTilesRect();
258 void PictureLayerTiling::RemoveTilesInRegion(const Region& layer_region) {
259 bool recreate_invalidated_tiles = false;
260 DoInvalidate(layer_region, recreate_invalidated_tiles);
263 void PictureLayerTiling::Invalidate(const Region& layer_region) {
264 bool recreate_invalidated_tiles = true;
265 DoInvalidate(layer_region, recreate_invalidated_tiles);
268 void PictureLayerTiling::DoInvalidate(const Region& layer_region,
269 bool recreate_invalidated_tiles) {
270 std::vector<TileMapKey> new_tile_keys;
271 gfx::Rect expanded_live_tiles_rect =
272 tiling_data_.ExpandRectIgnoringBordersToTileBounds(live_tiles_rect_);
273 for (Region::Iterator iter(layer_region); iter.has_rect(); iter.next()) {
274 gfx::Rect layer_rect = iter.rect();
275 gfx::Rect content_rect =
276 gfx::ScaleToEnclosingRect(layer_rect, contents_scale_);
277 // Consider tiles inside the live tiles rect even if only their border
278 // pixels intersect the invalidation. But don't consider tiles outside
279 // the live tiles rect with the same conditions, as they won't exist.
280 int border_pixels = tiling_data_.border_texels();
281 content_rect.Inset(-border_pixels, -border_pixels);
282 // Avoid needless work by not bothering to invalidate where there aren't
284 content_rect.Intersect(expanded_live_tiles_rect);
285 if (content_rect.IsEmpty())
287 // Since the content_rect includes border pixels already, don't include
288 // borders when iterating to avoid double counting them.
289 bool include_borders = false;
290 for (TilingData::Iterator iter(
291 &tiling_data_, content_rect, include_borders);
294 TileMapKey key(iter.index());
295 TileMap::iterator find = tiles_.find(key);
296 if (find == tiles_.end())
299 ReleaseTile(find->second.get(), client_->GetTree());
302 new_tile_keys.push_back(key);
306 if (recreate_invalidated_tiles && !new_tile_keys.empty()) {
307 for (size_t i = 0; i < new_tile_keys.size(); ++i) {
308 // Don't try to share a tile with the twin layer, it's been invalidated so
309 // we have to make our own tile here.
310 const PictureLayerTiling* twin_tiling = NULL;
311 CreateTile(new_tile_keys[i].first, new_tile_keys[i].second, twin_tiling);
316 PictureLayerTiling::CoverageIterator::CoverageIterator()
327 PictureLayerTiling::CoverageIterator::CoverageIterator(
328 const PictureLayerTiling* tiling,
330 const gfx::Rect& dest_rect)
332 dest_rect_(dest_rect),
333 dest_to_content_scale_(0),
342 if (dest_rect_.IsEmpty())
345 dest_to_content_scale_ = tiling_->contents_scale_ / dest_scale;
347 gfx::Rect content_rect =
348 gfx::ScaleToEnclosingRect(dest_rect_,
349 dest_to_content_scale_,
350 dest_to_content_scale_);
351 // IndexFromSrcCoord clamps to valid tile ranges, so it's necessary to
352 // check for non-intersection first.
353 content_rect.Intersect(gfx::Rect(tiling_->tiling_size()));
354 if (content_rect.IsEmpty())
357 left_ = tiling_->tiling_data_.TileXIndexFromSrcCoord(content_rect.x());
358 top_ = tiling_->tiling_data_.TileYIndexFromSrcCoord(content_rect.y());
359 right_ = tiling_->tiling_data_.TileXIndexFromSrcCoord(
360 content_rect.right() - 1);
361 bottom_ = tiling_->tiling_data_.TileYIndexFromSrcCoord(
362 content_rect.bottom() - 1);
369 PictureLayerTiling::CoverageIterator::~CoverageIterator() {
372 PictureLayerTiling::CoverageIterator&
373 PictureLayerTiling::CoverageIterator::operator++() {
374 if (tile_j_ > bottom_)
377 bool first_time = tile_i_ < left_;
378 bool new_row = false;
380 if (tile_i_ > right_) {
384 if (tile_j_ > bottom_) {
385 current_tile_ = NULL;
390 current_tile_ = tiling_->TileAt(tile_i_, tile_j_);
392 // Calculate the current geometry rect. Due to floating point rounding
393 // and ToEnclosingRect, tiles might overlap in destination space on the
395 gfx::Rect last_geometry_rect = current_geometry_rect_;
397 gfx::Rect content_rect = tiling_->tiling_data_.TileBounds(tile_i_, tile_j_);
399 current_geometry_rect_ =
400 gfx::ScaleToEnclosingRect(content_rect,
401 1 / dest_to_content_scale_,
402 1 / dest_to_content_scale_);
404 current_geometry_rect_.Intersect(dest_rect_);
409 // Iteration happens left->right, top->bottom. Running off the bottom-right
410 // edge is handled by the intersection above with dest_rect_. Here we make
411 // sure that the new current geometry rect doesn't overlap with the last.
415 min_left = dest_rect_.x();
416 min_top = last_geometry_rect.bottom();
418 min_left = last_geometry_rect.right();
419 min_top = last_geometry_rect.y();
422 int inset_left = std::max(0, min_left - current_geometry_rect_.x());
423 int inset_top = std::max(0, min_top - current_geometry_rect_.y());
424 current_geometry_rect_.Inset(inset_left, inset_top, 0, 0);
427 DCHECK_EQ(last_geometry_rect.right(), current_geometry_rect_.x());
428 DCHECK_EQ(last_geometry_rect.bottom(), current_geometry_rect_.bottom());
429 DCHECK_EQ(last_geometry_rect.y(), current_geometry_rect_.y());
435 gfx::Rect PictureLayerTiling::CoverageIterator::geometry_rect() const {
436 return current_geometry_rect_;
440 PictureLayerTiling::CoverageIterator::full_tile_geometry_rect() const {
441 gfx::Rect rect = tiling_->tiling_data_.TileBoundsWithBorder(tile_i_, tile_j_);
442 rect.set_size(tiling_->tiling_data_.max_texture_size());
446 gfx::RectF PictureLayerTiling::CoverageIterator::texture_rect() const {
447 gfx::PointF tex_origin =
448 tiling_->tiling_data_.TileBoundsWithBorder(tile_i_, tile_j_).origin();
450 // Convert from dest space => content space => texture space.
451 gfx::RectF texture_rect(current_geometry_rect_);
452 texture_rect.Scale(dest_to_content_scale_,
453 dest_to_content_scale_);
454 texture_rect.Intersect(gfx::Rect(tiling_->tiling_size()));
455 if (texture_rect.IsEmpty())
457 texture_rect.Offset(-tex_origin.OffsetFromOrigin());
462 gfx::Size PictureLayerTiling::CoverageIterator::texture_size() const {
463 return tiling_->tiling_data_.max_texture_size();
466 void PictureLayerTiling::Reset() {
467 live_tiles_rect_ = gfx::Rect();
468 for (TileMap::const_iterator it = tiles_.begin(); it != tiles_.end(); ++it)
469 ReleaseTile(it->second.get(), client_->GetTree());
473 gfx::Rect PictureLayerTiling::ComputeSkewport(
474 double current_frame_time_in_seconds,
475 const gfx::Rect& visible_rect_in_content_space) const {
476 gfx::Rect skewport = visible_rect_in_content_space;
477 if (last_impl_frame_time_in_seconds_ == 0.0)
481 current_frame_time_in_seconds - last_impl_frame_time_in_seconds_;
482 if (time_delta == 0.0)
485 float skewport_target_time_in_seconds =
486 client_->GetSkewportTargetTimeInSeconds();
487 double extrapolation_multiplier =
488 skewport_target_time_in_seconds / time_delta;
490 int old_x = last_visible_rect_in_content_space_.x();
491 int old_y = last_visible_rect_in_content_space_.y();
492 int old_right = last_visible_rect_in_content_space_.right();
493 int old_bottom = last_visible_rect_in_content_space_.bottom();
495 int new_x = visible_rect_in_content_space.x();
496 int new_y = visible_rect_in_content_space.y();
497 int new_right = visible_rect_in_content_space.right();
498 int new_bottom = visible_rect_in_content_space.bottom();
500 int skewport_limit = client_->GetSkewportExtrapolationLimitInContentPixels();
502 // Compute the maximum skewport based on |skewport_limit|.
503 gfx::Rect max_skewport = skewport;
505 -skewport_limit, -skewport_limit, -skewport_limit, -skewport_limit);
507 // Inset the skewport by the needed adjustment.
508 skewport.Inset(extrapolation_multiplier * (new_x - old_x),
509 extrapolation_multiplier * (new_y - old_y),
510 extrapolation_multiplier * (old_right - new_right),
511 extrapolation_multiplier * (old_bottom - new_bottom));
513 // Clip the skewport to |max_skewport|.
514 skewport.Intersect(max_skewport);
516 // Finally, ensure that visible rect is contained in the skewport.
517 skewport.Union(visible_rect_in_content_space);
521 void PictureLayerTiling::UpdateTilePriorities(
523 const gfx::Rect& visible_layer_rect,
524 float ideal_contents_scale,
525 double current_frame_time_in_seconds,
526 const OcclusionTracker<LayerImpl>* occlusion_tracker,
527 const LayerImpl* render_target,
528 const gfx::Transform& draw_transform) {
529 if (!NeedsUpdateForFrameAtTime(current_frame_time_in_seconds)) {
530 // This should never be zero for the purposes of has_ever_been_updated().
531 DCHECK_NE(current_frame_time_in_seconds, 0.0);
535 gfx::Rect visible_rect_in_content_space =
536 gfx::ScaleToEnclosingRect(visible_layer_rect, contents_scale_);
538 if (tiling_size().IsEmpty()) {
539 last_impl_frame_time_in_seconds_ = current_frame_time_in_seconds;
540 last_visible_rect_in_content_space_ = visible_rect_in_content_space;
544 size_t max_tiles_for_interest_area = client_->GetMaxTilesForInterestArea();
546 gfx::Size tile_size = tiling_data_.max_texture_size();
547 int64 eventually_rect_area =
548 max_tiles_for_interest_area * tile_size.width() * tile_size.height();
550 gfx::Rect skewport = ComputeSkewport(current_frame_time_in_seconds,
551 visible_rect_in_content_space);
552 DCHECK(skewport.Contains(visible_rect_in_content_space));
554 gfx::Rect eventually_rect =
555 ExpandRectEquallyToAreaBoundedBy(visible_rect_in_content_space,
556 eventually_rect_area,
557 gfx::Rect(tiling_size()),
560 DCHECK(eventually_rect.IsEmpty() ||
561 gfx::Rect(tiling_size()).Contains(eventually_rect))
562 << "tiling_size: " << tiling_size().ToString()
563 << " eventually_rect: " << eventually_rect.ToString();
565 SetLiveTilesRect(eventually_rect);
567 last_impl_frame_time_in_seconds_ = current_frame_time_in_seconds;
568 last_visible_rect_in_content_space_ = visible_rect_in_content_space;
570 eviction_tiles_cache_valid_ = false;
572 TilePriority now_priority(resolution_, TilePriority::NOW, 0);
573 float content_to_screen_scale = ideal_contents_scale / contents_scale_;
575 // Assign now priority to all visible tiles.
576 bool include_borders = false;
577 has_visible_rect_tiles_ = false;
578 for (TilingData::Iterator iter(
579 &tiling_data_, visible_rect_in_content_space, include_borders);
582 TileMap::iterator find = tiles_.find(iter.index());
583 if (find == tiles_.end())
585 has_visible_rect_tiles_ = true;
586 Tile* tile = find->second.get();
588 tile->SetPriority(tree, now_priority);
590 // Set whether tile is occluded or not.
591 bool is_occluded = false;
592 if (occlusion_tracker) {
593 gfx::Rect tile_query_rect = ScaleToEnclosingRect(
594 IntersectRects(tile->content_rect(), visible_rect_in_content_space),
595 1.0f / contents_scale_);
596 // TODO(vmpstr): Remove render_target and draw_transform from the
597 // parameters so they can be hidden from the tiling.
598 is_occluded = occlusion_tracker->Occluded(
599 render_target, tile_query_rect, draw_transform);
601 tile->set_is_occluded(tree, is_occluded);
604 // Assign soon priority to skewport tiles.
605 has_skewport_rect_tiles_ = false;
606 for (TilingData::DifferenceIterator iter(
607 &tiling_data_, skewport, visible_rect_in_content_space);
610 TileMap::iterator find = tiles_.find(iter.index());
611 if (find == tiles_.end())
613 has_skewport_rect_tiles_ = true;
614 Tile* tile = find->second.get();
616 gfx::Rect tile_bounds =
617 tiling_data_.TileBounds(iter.index_x(), iter.index_y());
619 float distance_to_visible =
620 visible_rect_in_content_space.ManhattanInternalDistance(tile_bounds) *
621 content_to_screen_scale;
623 TilePriority priority(resolution_, TilePriority::SOON, distance_to_visible);
624 tile->SetPriority(tree, priority);
627 // Assign eventually priority to interest rect tiles.
628 has_eventually_rect_tiles_ = false;
629 for (TilingData::DifferenceIterator iter(
630 &tiling_data_, eventually_rect, skewport);
633 TileMap::iterator find = tiles_.find(iter.index());
634 if (find == tiles_.end())
636 has_eventually_rect_tiles_ = true;
637 Tile* tile = find->second.get();
639 gfx::Rect tile_bounds =
640 tiling_data_.TileBounds(iter.index_x(), iter.index_y());
642 float distance_to_visible =
643 visible_rect_in_content_space.ManhattanInternalDistance(tile_bounds) *
644 content_to_screen_scale;
645 TilePriority priority(
646 resolution_, TilePriority::EVENTUALLY, distance_to_visible);
647 tile->SetPriority(tree, priority);
650 // Upgrade the priority on border tiles to be SOON.
651 gfx::Rect soon_border_rect = visible_rect_in_content_space;
652 float border = kSoonBorderDistanceInScreenPixels / content_to_screen_scale;
653 soon_border_rect.Inset(-border, -border, -border, -border);
654 has_soon_border_rect_tiles_ = false;
655 for (TilingData::DifferenceIterator iter(
656 &tiling_data_, soon_border_rect, skewport);
659 TileMap::iterator find = tiles_.find(iter.index());
660 if (find == tiles_.end())
662 has_soon_border_rect_tiles_ = true;
663 Tile* tile = find->second.get();
665 TilePriority priority(resolution_,
667 tile->priority(tree).distance_to_visible);
668 tile->SetPriority(tree, priority);
671 // Update iteration rects.
672 current_visible_rect_ = visible_rect_in_content_space;
673 current_skewport_rect_ = skewport;
674 current_soon_border_rect_ = soon_border_rect;
675 current_eventually_rect_ = eventually_rect;
678 void PictureLayerTiling::RemoveTileAt(int i, int j) {
679 TileMapKey key(i, j);
680 TileMap::iterator found = tiles_.find(key);
681 if (found == tiles_.end())
683 ReleaseTile(found->second.get(), client_->GetTree());
687 void PictureLayerTiling::SetLiveTilesRect(
688 const gfx::Rect& new_live_tiles_rect) {
689 DCHECK(new_live_tiles_rect.IsEmpty() ||
690 gfx::Rect(tiling_size()).Contains(new_live_tiles_rect))
691 << "tiling_size: " << tiling_size().ToString()
692 << " new_live_tiles_rect: " << new_live_tiles_rect.ToString();
693 if (live_tiles_rect_ == new_live_tiles_rect)
696 // Iterate to delete all tiles outside of our new live_tiles rect.
697 PictureLayerTiling* recycled_twin = client_->GetRecycledTwinTiling(this);
698 for (TilingData::DifferenceIterator iter(&tiling_data_,
700 new_live_tiles_rect);
703 TileMapKey key(iter.index());
704 TileMap::iterator found = tiles_.find(key);
705 // If the tile was outside of the recorded region, it won't exist even
706 // though it was in the live rect.
707 if (found != tiles_.end()) {
708 ReleaseTile(found->second.get(), client_->GetTree());
711 recycled_twin->RemoveTileAt(iter.index_x(), iter.index_y());
715 const PictureLayerTiling* twin_tiling = client_->GetTwinTiling(this);
717 // Iterate to allocate new tiles for all regions with newly exposed area.
718 for (TilingData::DifferenceIterator iter(&tiling_data_,
723 TileMapKey key(iter.index());
724 CreateTile(key.first, key.second, twin_tiling);
727 live_tiles_rect_ = new_live_tiles_rect;
728 VerifyLiveTilesRect();
731 void PictureLayerTiling::VerifyLiveTilesRect() {
733 for (TileMap::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
734 if (!it->second.get())
736 DCHECK(it->first.first < tiling_data_.num_tiles_x())
737 << this << " " << it->first.first << "," << it->first.second
738 << " num_tiles_x " << tiling_data_.num_tiles_x() << " live_tiles_rect "
739 << live_tiles_rect_.ToString();
740 DCHECK(it->first.second < tiling_data_.num_tiles_y())
741 << this << " " << it->first.first << "," << it->first.second
742 << " num_tiles_y " << tiling_data_.num_tiles_y() << " live_tiles_rect "
743 << live_tiles_rect_.ToString();
744 DCHECK(tiling_data_.TileBounds(it->first.first, it->first.second)
745 .Intersects(live_tiles_rect_))
746 << this << " " << it->first.first << "," << it->first.second
748 << tiling_data_.TileBounds(it->first.first, it->first.second).ToString()
749 << " live_tiles_rect " << live_tiles_rect_.ToString();
754 void PictureLayerTiling::DidBecomeRecycled() {
755 // DidBecomeActive below will set the active priority for tiles that are
756 // still in the tree. Calling this first on an active tiling that is becoming
757 // recycled takes care of tiles that are no longer in the active tree (eg.
758 // due to a pending invalidation).
759 for (TileMap::const_iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
760 it->second->SetPriority(ACTIVE_TREE, TilePriority());
764 void PictureLayerTiling::DidBecomeActive() {
765 PicturePileImpl* active_pile = client_->GetPile();
766 for (TileMap::const_iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
767 it->second->SetPriority(ACTIVE_TREE, it->second->priority(PENDING_TREE));
768 it->second->SetPriority(PENDING_TREE, TilePriority());
770 // Tile holds a ref onto a picture pile. If the tile never gets invalidated
771 // and recreated, then that picture pile ref could exist indefinitely. To
772 // prevent this, ask the client to update the pile to its own ref. This
773 // will cause PicturePileImpls and their clones to get deleted once the
774 // corresponding PictureLayerImpl and any in flight raster jobs go out of
776 it->second->set_picture_pile(active_pile);
780 void PictureLayerTiling::AsValueInto(base::debug::TracedValue* state) const {
781 state->SetInteger("num_tiles", tiles_.size());
782 state->SetDouble("content_scale", contents_scale_);
783 state->BeginDictionary("tiling_size");
784 MathUtil::AddToTracedValue(tiling_size(), state);
785 state->EndDictionary();
788 size_t PictureLayerTiling::GPUMemoryUsageInBytes() const {
790 for (TileMap::const_iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
791 const Tile* tile = it->second.get();
792 amount += tile->GPUMemoryUsageInBytes();
797 PictureLayerTiling::RectExpansionCache::RectExpansionCache()
798 : previous_target(0) {
803 // This struct represents an event at which the expending rect intersects
804 // one of its boundaries. 4 intersection events will occur during expansion.
806 enum { BOTTOM, TOP, LEFT, RIGHT } edge;
811 // Compute the delta to expand from edges to cover target_area.
812 int ComputeExpansionDelta(int num_x_edges, int num_y_edges,
813 int width, int height,
815 // Compute coefficients for the quadratic equation:
816 // a*x^2 + b*x + c = 0
817 int a = num_y_edges * num_x_edges;
818 int b = num_y_edges * width + num_x_edges * height;
819 int64 c = static_cast<int64>(width) * height - target_area;
821 // Compute the delta for our edges using the quadratic equation.
822 return a == 0 ? -c / b :
823 (-b + static_cast<int>(
824 std::sqrt(static_cast<int64>(b) * b - 4.0 * a * c))) / (2 * a);
829 gfx::Rect PictureLayerTiling::ExpandRectEquallyToAreaBoundedBy(
830 const gfx::Rect& starting_rect,
832 const gfx::Rect& bounding_rect,
833 RectExpansionCache* cache) {
834 if (starting_rect.IsEmpty())
835 return starting_rect;
838 cache->previous_start == starting_rect &&
839 cache->previous_bounds == bounding_rect &&
840 cache->previous_target == target_area)
841 return cache->previous_result;
844 cache->previous_start = starting_rect;
845 cache->previous_bounds = bounding_rect;
846 cache->previous_target = target_area;
849 DCHECK(!bounding_rect.IsEmpty());
850 DCHECK_GT(target_area, 0);
852 // Expand the starting rect to cover target_area, if it is smaller than it.
853 int delta = ComputeExpansionDelta(
854 2, 2, starting_rect.width(), starting_rect.height(), target_area);
855 gfx::Rect expanded_starting_rect = starting_rect;
857 expanded_starting_rect.Inset(-delta, -delta);
859 gfx::Rect rect = IntersectRects(expanded_starting_rect, bounding_rect);
860 if (rect.IsEmpty()) {
861 // The starting_rect and bounding_rect are far away.
863 cache->previous_result = rect;
866 if (delta >= 0 && rect == expanded_starting_rect) {
867 // The starting rect already covers the entire bounding_rect and isn't too
868 // large for the target_area.
870 cache->previous_result = rect;
874 // Continue to expand/shrink rect to let it cover target_area.
876 // These values will be updated by the loop and uses as the output.
877 int origin_x = rect.x();
878 int origin_y = rect.y();
879 int width = rect.width();
880 int height = rect.height();
882 // In the beginning we will consider 2 edges in each dimension.
886 // Create an event list.
887 EdgeEvent events[] = {
888 { EdgeEvent::BOTTOM, &num_y_edges, rect.y() - bounding_rect.y() },
889 { EdgeEvent::TOP, &num_y_edges, bounding_rect.bottom() - rect.bottom() },
890 { EdgeEvent::LEFT, &num_x_edges, rect.x() - bounding_rect.x() },
891 { EdgeEvent::RIGHT, &num_x_edges, bounding_rect.right() - rect.right() }
894 // Sort the events by distance (closest first).
895 if (events[0].distance > events[1].distance) std::swap(events[0], events[1]);
896 if (events[2].distance > events[3].distance) std::swap(events[2], events[3]);
897 if (events[0].distance > events[2].distance) std::swap(events[0], events[2]);
898 if (events[1].distance > events[3].distance) std::swap(events[1], events[3]);
899 if (events[1].distance > events[2].distance) std::swap(events[1], events[2]);
901 for (int event_index = 0; event_index < 4; event_index++) {
902 const EdgeEvent& event = events[event_index];
904 int delta = ComputeExpansionDelta(
905 num_x_edges, num_y_edges, width, height, target_area);
907 // Clamp delta to our event distance.
908 if (delta > event.distance)
909 delta = event.distance;
911 // Adjust the edge count for this kind of edge.
914 // Apply the delta to the edges and edge events.
915 for (int i = event_index; i < 4; i++) {
916 switch (events[i].edge) {
917 case EdgeEvent::BOTTOM:
924 case EdgeEvent::LEFT:
928 case EdgeEvent::RIGHT:
932 events[i].distance -= delta;
935 // If our delta is less then our event distance, we're done.
936 if (delta < event.distance)
940 gfx::Rect result(origin_x, origin_y, width, height);
942 cache->previous_result = result;
946 void PictureLayerTiling::UpdateEvictionCacheIfNeeded(
947 TreePriority tree_priority) {
948 if (eviction_tiles_cache_valid_ &&
949 eviction_cache_tree_priority_ == tree_priority)
952 eviction_tiles_now_.clear();
953 eviction_tiles_now_and_required_for_activation_.clear();
954 eviction_tiles_soon_.clear();
955 eviction_tiles_soon_and_required_for_activation_.clear();
956 eviction_tiles_eventually_.clear();
957 eviction_tiles_eventually_and_required_for_activation_.clear();
959 for (TileMap::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
960 // TODO(vmpstr): This should update the priority if UpdateTilePriorities
961 // changes not to do this.
962 Tile* tile = it->second;
963 const TilePriority& priority =
964 tile->priority_for_tree_priority(tree_priority);
965 switch (priority.priority_bin) {
966 case TilePriority::EVENTUALLY:
967 if (tile->required_for_activation())
968 eviction_tiles_eventually_and_required_for_activation_.push_back(
971 eviction_tiles_eventually_.push_back(tile);
973 case TilePriority::SOON:
974 if (tile->required_for_activation())
975 eviction_tiles_soon_and_required_for_activation_.push_back(tile);
977 eviction_tiles_soon_.push_back(tile);
979 case TilePriority::NOW:
980 if (tile->required_for_activation())
981 eviction_tiles_now_and_required_for_activation_.push_back(tile);
983 eviction_tiles_now_.push_back(tile);
988 // TODO(vmpstr): Do this lazily. One option is to have a "sorted" flag that
989 // can be updated for each of the queues.
990 TileEvictionOrder sort_order(tree_priority);
991 std::sort(eviction_tiles_now_.begin(), eviction_tiles_now_.end(), sort_order);
992 std::sort(eviction_tiles_now_and_required_for_activation_.begin(),
993 eviction_tiles_now_and_required_for_activation_.end(),
996 eviction_tiles_soon_.begin(), eviction_tiles_soon_.end(), sort_order);
997 std::sort(eviction_tiles_soon_and_required_for_activation_.begin(),
998 eviction_tiles_soon_and_required_for_activation_.end(),
1000 std::sort(eviction_tiles_eventually_.begin(),
1001 eviction_tiles_eventually_.end(),
1003 std::sort(eviction_tiles_eventually_and_required_for_activation_.begin(),
1004 eviction_tiles_eventually_and_required_for_activation_.end(),
1007 eviction_tiles_cache_valid_ = true;
1008 eviction_cache_tree_priority_ = tree_priority;
1011 const std::vector<Tile*>* PictureLayerTiling::GetEvictionTiles(
1012 TreePriority tree_priority,
1013 EvictionCategory category) {
1014 UpdateEvictionCacheIfNeeded(tree_priority);
1017 return &eviction_tiles_eventually_;
1018 case EVENTUALLY_AND_REQUIRED_FOR_ACTIVATION:
1019 return &eviction_tiles_eventually_and_required_for_activation_;
1021 return &eviction_tiles_soon_;
1022 case SOON_AND_REQUIRED_FOR_ACTIVATION:
1023 return &eviction_tiles_soon_and_required_for_activation_;
1025 return &eviction_tiles_now_;
1026 case NOW_AND_REQUIRED_FOR_ACTIVATION:
1027 return &eviction_tiles_now_and_required_for_activation_;
1030 return &eviction_tiles_eventually_;
1033 PictureLayerTiling::TilingRasterTileIterator::TilingRasterTileIterator()
1034 : tiling_(NULL), current_tile_(NULL) {}
1036 PictureLayerTiling::TilingRasterTileIterator::TilingRasterTileIterator(
1037 PictureLayerTiling* tiling,
1039 : tiling_(tiling), phase_(VISIBLE_RECT), tree_(tree), current_tile_(NULL) {
1040 if (!tiling_->has_visible_rect_tiles_) {
1045 visible_iterator_ = TilingData::Iterator(&tiling_->tiling_data_,
1046 tiling_->current_visible_rect_,
1047 false /* include_borders */);
1048 if (!visible_iterator_) {
1054 tiling_->TileAt(visible_iterator_.index_x(), visible_iterator_.index_y());
1055 if (!current_tile_ || !TileNeedsRaster(current_tile_))
1059 PictureLayerTiling::TilingRasterTileIterator::~TilingRasterTileIterator() {}
1061 void PictureLayerTiling::TilingRasterTileIterator::AdvancePhase() {
1062 DCHECK_LT(phase_, EVENTUALLY_RECT);
1065 phase_ = static_cast<Phase>(phase_ + 1);
1071 if (!tiling_->has_skewport_rect_tiles_)
1074 spiral_iterator_ = TilingData::SpiralDifferenceIterator(
1075 &tiling_->tiling_data_,
1076 tiling_->current_skewport_rect_,
1077 tiling_->current_visible_rect_,
1078 tiling_->current_visible_rect_);
1080 case SOON_BORDER_RECT:
1081 if (!tiling_->has_soon_border_rect_tiles_)
1084 spiral_iterator_ = TilingData::SpiralDifferenceIterator(
1085 &tiling_->tiling_data_,
1086 tiling_->current_soon_border_rect_,
1087 tiling_->current_skewport_rect_,
1088 tiling_->current_visible_rect_);
1090 case EVENTUALLY_RECT:
1091 if (!tiling_->has_eventually_rect_tiles_) {
1092 current_tile_ = NULL;
1096 spiral_iterator_ = TilingData::SpiralDifferenceIterator(
1097 &tiling_->tiling_data_,
1098 tiling_->current_eventually_rect_,
1099 tiling_->current_skewport_rect_,
1100 tiling_->current_soon_border_rect_);
1104 while (spiral_iterator_) {
1105 current_tile_ = tiling_->TileAt(spiral_iterator_.index_x(),
1106 spiral_iterator_.index_y());
1107 if (current_tile_ && TileNeedsRaster(current_tile_))
1112 if (!spiral_iterator_ && phase_ == EVENTUALLY_RECT) {
1113 current_tile_ = NULL;
1116 } while (!spiral_iterator_);
1119 PictureLayerTiling::TilingRasterTileIterator&
1120 PictureLayerTiling::TilingRasterTileIterator::
1122 current_tile_ = NULL;
1123 while (!current_tile_ || !TileNeedsRaster(current_tile_)) {
1124 std::pair<int, int> next_index;
1127 ++visible_iterator_;
1128 if (!visible_iterator_) {
1132 next_index = visible_iterator_.index();
1135 case SOON_BORDER_RECT:
1137 if (!spiral_iterator_) {
1141 next_index = spiral_iterator_.index();
1143 case EVENTUALLY_RECT:
1145 if (!spiral_iterator_) {
1146 current_tile_ = NULL;
1149 next_index = spiral_iterator_.index();
1152 current_tile_ = tiling_->TileAt(next_index.first, next_index.second);
1157 PictureLayerTiling::TilingEvictionTileIterator::TilingEvictionTileIterator()
1158 : eviction_tiles_(NULL), current_eviction_tiles_index_(0u) {
1161 PictureLayerTiling::TilingEvictionTileIterator::TilingEvictionTileIterator(
1162 PictureLayerTiling* tiling,
1163 TreePriority tree_priority,
1164 EvictionCategory category)
1165 : eviction_tiles_(tiling->GetEvictionTiles(tree_priority, category)),
1166 // Note: initializing to "0 - 1" works as overflow is well defined for
1167 // unsigned integers.
1168 current_eviction_tiles_index_(static_cast<size_t>(0) - 1) {
1169 DCHECK(eviction_tiles_);
1173 PictureLayerTiling::TilingEvictionTileIterator::~TilingEvictionTileIterator() {
1176 PictureLayerTiling::TilingEvictionTileIterator::operator bool() const {
1177 return eviction_tiles_ &&
1178 current_eviction_tiles_index_ != eviction_tiles_->size();
1181 Tile* PictureLayerTiling::TilingEvictionTileIterator::operator*() {
1183 return (*eviction_tiles_)[current_eviction_tiles_index_];
1186 const Tile* PictureLayerTiling::TilingEvictionTileIterator::operator*() const {
1188 return (*eviction_tiles_)[current_eviction_tiles_index_];
1191 PictureLayerTiling::TilingEvictionTileIterator&
1192 PictureLayerTiling::TilingEvictionTileIterator::
1196 ++current_eviction_tiles_index_;
1197 } while (current_eviction_tiles_index_ != eviction_tiles_->size() &&
1198 !(*eviction_tiles_)[current_eviction_tiles_index_]->HasResources());