Roll src/third_party/skia 99c7c07:4af6580
[chromium-blink-merge.git] / cc / resources / picture_layer_tiling.cc
blob30a73b8e8dbf1e47e6332878a0d18810512a4518
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"
7 #include <algorithm>
8 #include <cmath>
9 #include <limits>
10 #include <set>
12 #include "base/logging.h"
13 #include "base/trace_event/trace_event.h"
14 #include "base/trace_event/trace_event_argument.h"
15 #include "cc/base/math_util.h"
16 #include "cc/resources/tile.h"
17 #include "cc/resources/tile_priority.h"
18 #include "ui/gfx/geometry/point_conversions.h"
19 #include "ui/gfx/geometry/rect_conversions.h"
20 #include "ui/gfx/geometry/safe_integer_conversions.h"
21 #include "ui/gfx/geometry/size_conversions.h"
23 namespace cc {
24 namespace {
26 const float kSoonBorderDistanceViewportPercentage = 0.15f;
27 const float kMaxSoonBorderDistanceInScreenPixels = 312.f;
29 } // namespace
31 scoped_ptr<PictureLayerTiling> PictureLayerTiling::Create(
32 float contents_scale,
33 scoped_refptr<RasterSource> raster_source,
34 PictureLayerTilingClient* client,
35 size_t max_tiles_for_interest_area,
36 float skewport_target_time_in_seconds,
37 int skewport_extrapolation_limit_in_content_pixels) {
38 return make_scoped_ptr(new PictureLayerTiling(
39 contents_scale, raster_source, client, max_tiles_for_interest_area,
40 skewport_target_time_in_seconds,
41 skewport_extrapolation_limit_in_content_pixels));
44 PictureLayerTiling::PictureLayerTiling(
45 float contents_scale,
46 scoped_refptr<RasterSource> raster_source,
47 PictureLayerTilingClient* client,
48 size_t max_tiles_for_interest_area,
49 float skewport_target_time_in_seconds,
50 int skewport_extrapolation_limit_in_content_pixels)
51 : max_tiles_for_interest_area_(max_tiles_for_interest_area),
52 skewport_target_time_in_seconds_(skewport_target_time_in_seconds),
53 skewport_extrapolation_limit_in_content_pixels_(
54 skewport_extrapolation_limit_in_content_pixels),
55 contents_scale_(contents_scale),
56 client_(client),
57 raster_source_(raster_source),
58 resolution_(NON_IDEAL_RESOLUTION),
59 tiling_data_(gfx::Size(), gfx::Size(), kBorderTexels),
60 can_require_tiles_for_activation_(false),
61 current_content_to_screen_scale_(0.f),
62 has_visible_rect_tiles_(false),
63 has_skewport_rect_tiles_(false),
64 has_soon_border_rect_tiles_(false),
65 has_eventually_rect_tiles_(false) {
66 DCHECK(!raster_source->IsSolidColor());
67 gfx::Size content_bounds = gfx::ToCeiledSize(
68 gfx::ScaleSize(raster_source_->GetSize(), contents_scale));
69 gfx::Size tile_size = client_->CalculateTileSize(content_bounds);
71 DCHECK(!gfx::ToFlooredSize(gfx::ScaleSize(raster_source_->GetSize(),
72 contents_scale)).IsEmpty())
73 << "Tiling created with scale too small as contents become empty."
74 << " Layer bounds: " << raster_source_->GetSize().ToString()
75 << " Contents scale: " << contents_scale;
77 tiling_data_.SetTilingSize(content_bounds);
78 tiling_data_.SetMaxTextureSize(tile_size);
81 PictureLayerTiling::~PictureLayerTiling() {
84 // static
85 float PictureLayerTiling::CalculateSoonBorderDistance(
86 const gfx::Rect& visible_rect_in_content_space,
87 float content_to_screen_scale) {
88 float max_dimension = std::max(visible_rect_in_content_space.width(),
89 visible_rect_in_content_space.height());
90 return std::min(
91 kMaxSoonBorderDistanceInScreenPixels / content_to_screen_scale,
92 max_dimension * kSoonBorderDistanceViewportPercentage);
95 Tile* PictureLayerTiling::CreateTile(int i, int j) {
96 TileMapKey key(i, j);
97 DCHECK(tiles_.find(key) == tiles_.end());
99 gfx::Rect paint_rect = tiling_data_.TileBoundsWithBorder(i, j);
100 gfx::Rect tile_rect = paint_rect;
101 tile_rect.set_size(tiling_data_.max_texture_size());
103 if (!raster_source_->CoversRect(tile_rect, contents_scale_))
104 return nullptr;
106 scoped_refptr<Tile> tile = client_->CreateTile(contents_scale_, tile_rect);
107 tile->set_tiling_index(i, j);
108 tiles_[key] = tile;
109 return tile.get();
112 void PictureLayerTiling::CreateMissingTilesInLiveTilesRect() {
113 bool include_borders = false;
114 for (TilingData::Iterator iter(&tiling_data_, live_tiles_rect_,
115 include_borders);
116 iter; ++iter) {
117 TileMapKey key = iter.index();
118 TileMap::iterator find = tiles_.find(key);
119 if (find != tiles_.end())
120 continue;
122 if (ShouldCreateTileAt(key.first, key.second))
123 CreateTile(key.first, key.second);
125 VerifyLiveTilesRect(false);
128 void PictureLayerTiling::TakeTilesAndPropertiesFrom(
129 PictureLayerTiling* pending_twin,
130 const Region& layer_invalidation) {
131 TRACE_EVENT0("cc", "TakeTilesAndPropertiesFrom");
132 SetRasterSourceAndResize(pending_twin->raster_source_);
134 RemoveTilesInRegion(layer_invalidation, false /* recreate tiles */);
136 for (TileMap::value_type& tile_pair : tiles_)
137 tile_pair.second->set_raster_source(raster_source_.get());
139 resolution_ = pending_twin->resolution_;
140 bool create_missing_tiles = false;
141 if (live_tiles_rect_.IsEmpty()) {
142 live_tiles_rect_ = pending_twin->live_tiles_rect();
143 create_missing_tiles = true;
144 } else {
145 SetLiveTilesRect(pending_twin->live_tiles_rect());
148 if (tiles_.size() < pending_twin->tiles_.size()) {
149 tiles_.swap(pending_twin->tiles_);
150 tiles_.insert(pending_twin->tiles_.begin(), pending_twin->tiles_.end());
151 } else {
152 for (TileMap::value_type& tile_pair : pending_twin->tiles_) {
153 tiles_[tile_pair.first].swap(tile_pair.second);
154 DCHECK(tiles_[tile_pair.first]->raster_source() == raster_source_.get());
157 pending_twin->tiles_.clear();
159 if (create_missing_tiles)
160 CreateMissingTilesInLiveTilesRect();
162 VerifyLiveTilesRect(false);
164 SetTilePriorityRects(pending_twin->current_content_to_screen_scale_,
165 pending_twin->current_visible_rect_,
166 pending_twin->current_skewport_rect_,
167 pending_twin->current_soon_border_rect_,
168 pending_twin->current_eventually_rect_,
169 pending_twin->current_occlusion_in_layer_space_);
172 void PictureLayerTiling::SetRasterSourceAndResize(
173 scoped_refptr<RasterSource> raster_source) {
174 DCHECK(!raster_source->IsSolidColor());
175 gfx::Size old_layer_bounds = raster_source_->GetSize();
176 raster_source_.swap(raster_source);
177 gfx::Size new_layer_bounds = raster_source_->GetSize();
178 gfx::Size content_bounds =
179 gfx::ToCeiledSize(gfx::ScaleSize(new_layer_bounds, contents_scale_));
180 gfx::Size tile_size = client_->CalculateTileSize(content_bounds);
182 if (tile_size != tiling_data_.max_texture_size()) {
183 tiling_data_.SetTilingSize(content_bounds);
184 tiling_data_.SetMaxTextureSize(tile_size);
185 // When the tile size changes, the TilingData positions no longer work
186 // as valid keys to the TileMap, so just drop all tiles and clear the live
187 // tiles rect.
188 Reset();
189 return;
192 if (old_layer_bounds == new_layer_bounds)
193 return;
195 // The SetLiveTilesRect() method would drop tiles outside the new bounds,
196 // but may do so incorrectly if resizing the tiling causes the number of
197 // tiles in the tiling_data_ to change.
198 gfx::Rect content_rect(content_bounds);
199 int before_left = tiling_data_.TileXIndexFromSrcCoord(live_tiles_rect_.x());
200 int before_top = tiling_data_.TileYIndexFromSrcCoord(live_tiles_rect_.y());
201 int before_right =
202 tiling_data_.TileXIndexFromSrcCoord(live_tiles_rect_.right() - 1);
203 int before_bottom =
204 tiling_data_.TileYIndexFromSrcCoord(live_tiles_rect_.bottom() - 1);
206 // The live_tiles_rect_ is clamped to stay within the tiling size as we
207 // change it.
208 live_tiles_rect_.Intersect(content_rect);
209 tiling_data_.SetTilingSize(content_bounds);
211 int after_right = -1;
212 int after_bottom = -1;
213 if (!live_tiles_rect_.IsEmpty()) {
214 after_right =
215 tiling_data_.TileXIndexFromSrcCoord(live_tiles_rect_.right() - 1);
216 after_bottom =
217 tiling_data_.TileYIndexFromSrcCoord(live_tiles_rect_.bottom() - 1);
220 // There is no recycled twin since this is run on the pending tiling
221 // during commit, and on the active tree during activate.
222 // Drop tiles outside the new layer bounds if the layer shrank.
223 for (int i = after_right + 1; i <= before_right; ++i) {
224 for (int j = before_top; j <= before_bottom; ++j)
225 RemoveTileAt(i, j);
227 for (int i = before_left; i <= after_right; ++i) {
228 for (int j = after_bottom + 1; j <= before_bottom; ++j)
229 RemoveTileAt(i, j);
232 if (after_right > before_right) {
233 DCHECK_EQ(after_right, before_right + 1);
234 for (int j = before_top; j <= after_bottom; ++j) {
235 if (ShouldCreateTileAt(after_right, j))
236 CreateTile(after_right, j);
239 if (after_bottom > before_bottom) {
240 DCHECK_EQ(after_bottom, before_bottom + 1);
241 for (int i = before_left; i <= before_right; ++i) {
242 if (ShouldCreateTileAt(i, after_bottom))
243 CreateTile(i, after_bottom);
248 void PictureLayerTiling::Invalidate(const Region& layer_invalidation) {
249 DCHECK_IMPLIES(client_->GetTree() == ACTIVE_TREE,
250 !client_->GetPendingOrActiveTwinTiling(this));
251 RemoveTilesInRegion(layer_invalidation, true /* recreate tiles */);
254 void PictureLayerTiling::RemoveTilesInRegion(const Region& layer_invalidation,
255 bool recreate_tiles) {
256 // We only invalidate the active tiling when it's orphaned: it has no pending
257 // twin, so it's slated for removal in the future.
258 if (live_tiles_rect_.IsEmpty())
259 return;
260 std::vector<TileMapKey> new_tile_keys;
261 gfx::Rect expanded_live_tiles_rect =
262 tiling_data_.ExpandRectIgnoringBordersToTileBounds(live_tiles_rect_);
263 for (Region::Iterator iter(layer_invalidation); iter.has_rect();
264 iter.next()) {
265 gfx::Rect layer_rect = iter.rect();
266 gfx::Rect content_rect =
267 gfx::ScaleToEnclosingRect(layer_rect, contents_scale_);
268 // Consider tiles inside the live tiles rect even if only their border
269 // pixels intersect the invalidation. But don't consider tiles outside
270 // the live tiles rect with the same conditions, as they won't exist.
271 int border_pixels = tiling_data_.border_texels();
272 content_rect.Inset(-border_pixels, -border_pixels);
273 // Avoid needless work by not bothering to invalidate where there aren't
274 // tiles.
275 content_rect.Intersect(expanded_live_tiles_rect);
276 if (content_rect.IsEmpty())
277 continue;
278 // Since the content_rect includes border pixels already, don't include
279 // borders when iterating to avoid double counting them.
280 bool include_borders = false;
281 for (
282 TilingData::Iterator iter(&tiling_data_, content_rect, include_borders);
283 iter; ++iter) {
284 if (RemoveTileAt(iter.index_x(), iter.index_y())) {
285 if (recreate_tiles)
286 new_tile_keys.push_back(iter.index());
291 for (const auto& key : new_tile_keys)
292 CreateTile(key.first, key.second);
295 void PictureLayerTiling::SetRasterSourceOnTiles() {
296 if (client_->GetTree() == PENDING_TREE)
297 return;
299 for (TileMap::value_type& tile_pair : tiles_)
300 tile_pair.second->set_raster_source(raster_source_.get());
303 bool PictureLayerTiling::ShouldCreateTileAt(int i, int j) const {
304 // Active tree should always create a tile. The reason for this is that active
305 // tree represents content that we draw on screen, which means that whenever
306 // we check whether a tile should exist somewhere, the answer is yes. This
307 // doesn't mean it will actually be created (if raster source doesn't cover
308 // the tile for instance). Pending tree, on the other hand, should only be
309 // creating tiles that are different from the current active tree, which is
310 // represented by the logic in the rest of the function.
311 if (client_->GetTree() == ACTIVE_TREE)
312 return true;
314 // If the pending tree has no active twin, then it needs to create all tiles.
315 const PictureLayerTiling* active_twin =
316 client_->GetPendingOrActiveTwinTiling(this);
317 if (!active_twin)
318 return true;
320 // Pending tree will override the entire active tree if indices don't match.
321 if (!TilingMatchesTileIndices(active_twin))
322 return true;
324 gfx::Rect paint_rect = tiling_data_.TileBoundsWithBorder(i, j);
325 gfx::Rect tile_rect = paint_rect;
326 tile_rect.set_size(tiling_data_.max_texture_size());
328 // If the active tree can't create a tile, because of its raster source, then
329 // the pending tree should create one.
330 if (!active_twin->raster_source()->CoversRect(tile_rect, contents_scale()))
331 return true;
333 const Region* layer_invalidation = client_->GetPendingInvalidation();
334 gfx::Rect layer_rect =
335 gfx::ScaleToEnclosingRect(tile_rect, 1.f / contents_scale());
337 // If this tile is invalidated, then the pending tree should create one.
338 if (layer_invalidation && layer_invalidation->Intersects(layer_rect))
339 return true;
341 // If the active tree doesn't have a tile here, but it's in the pending tree's
342 // visible rect, then the pending tree should create a tile. This can happen
343 // if the pending visible rect is outside of the active tree's live tiles
344 // rect. In those situations, we need to block activation until we're ready to
345 // display content, which will have to come from the pending tree.
346 if (!active_twin->TileAt(i, j) && current_visible_rect_.Intersects(tile_rect))
347 return true;
349 // In all other cases, the pending tree doesn't need to create a tile.
350 return false;
353 bool PictureLayerTiling::TilingMatchesTileIndices(
354 const PictureLayerTiling* twin) const {
355 return tiling_data_.max_texture_size() ==
356 twin->tiling_data_.max_texture_size();
359 PictureLayerTiling::CoverageIterator::CoverageIterator()
360 : tiling_(NULL),
361 current_tile_(NULL),
362 tile_i_(0),
363 tile_j_(0),
364 left_(0),
365 top_(0),
366 right_(-1),
367 bottom_(-1) {
370 PictureLayerTiling::CoverageIterator::CoverageIterator(
371 const PictureLayerTiling* tiling,
372 float dest_scale,
373 const gfx::Rect& dest_rect)
374 : tiling_(tiling),
375 dest_rect_(dest_rect),
376 dest_to_content_scale_(0),
377 current_tile_(NULL),
378 tile_i_(0),
379 tile_j_(0),
380 left_(0),
381 top_(0),
382 right_(-1),
383 bottom_(-1) {
384 DCHECK(tiling_);
385 if (dest_rect_.IsEmpty())
386 return;
388 dest_to_content_scale_ = tiling_->contents_scale_ / dest_scale;
390 gfx::Rect content_rect =
391 gfx::ScaleToEnclosingRect(dest_rect_,
392 dest_to_content_scale_,
393 dest_to_content_scale_);
394 // IndexFromSrcCoord clamps to valid tile ranges, so it's necessary to
395 // check for non-intersection first.
396 content_rect.Intersect(gfx::Rect(tiling_->tiling_size()));
397 if (content_rect.IsEmpty())
398 return;
400 left_ = tiling_->tiling_data_.TileXIndexFromSrcCoord(content_rect.x());
401 top_ = tiling_->tiling_data_.TileYIndexFromSrcCoord(content_rect.y());
402 right_ = tiling_->tiling_data_.TileXIndexFromSrcCoord(
403 content_rect.right() - 1);
404 bottom_ = tiling_->tiling_data_.TileYIndexFromSrcCoord(
405 content_rect.bottom() - 1);
407 tile_i_ = left_ - 1;
408 tile_j_ = top_;
409 ++(*this);
412 PictureLayerTiling::CoverageIterator::~CoverageIterator() {
415 PictureLayerTiling::CoverageIterator&
416 PictureLayerTiling::CoverageIterator::operator++() {
417 if (tile_j_ > bottom_)
418 return *this;
420 bool first_time = tile_i_ < left_;
421 bool new_row = false;
422 tile_i_++;
423 if (tile_i_ > right_) {
424 tile_i_ = left_;
425 tile_j_++;
426 new_row = true;
427 if (tile_j_ > bottom_) {
428 current_tile_ = NULL;
429 return *this;
433 current_tile_ = tiling_->TileAt(tile_i_, tile_j_);
435 // Calculate the current geometry rect. Due to floating point rounding
436 // and ToEnclosingRect, tiles might overlap in destination space on the
437 // edges.
438 gfx::Rect last_geometry_rect = current_geometry_rect_;
440 gfx::Rect content_rect = tiling_->tiling_data_.TileBounds(tile_i_, tile_j_);
442 current_geometry_rect_ =
443 gfx::ScaleToEnclosingRect(content_rect,
444 1 / dest_to_content_scale_,
445 1 / dest_to_content_scale_);
447 current_geometry_rect_.Intersect(dest_rect_);
449 if (first_time)
450 return *this;
452 // Iteration happens left->right, top->bottom. Running off the bottom-right
453 // edge is handled by the intersection above with dest_rect_. Here we make
454 // sure that the new current geometry rect doesn't overlap with the last.
455 int min_left;
456 int min_top;
457 if (new_row) {
458 min_left = dest_rect_.x();
459 min_top = last_geometry_rect.bottom();
460 } else {
461 min_left = last_geometry_rect.right();
462 min_top = last_geometry_rect.y();
465 int inset_left = std::max(0, min_left - current_geometry_rect_.x());
466 int inset_top = std::max(0, min_top - current_geometry_rect_.y());
467 current_geometry_rect_.Inset(inset_left, inset_top, 0, 0);
469 if (!new_row) {
470 DCHECK_EQ(last_geometry_rect.right(), current_geometry_rect_.x());
471 DCHECK_EQ(last_geometry_rect.bottom(), current_geometry_rect_.bottom());
472 DCHECK_EQ(last_geometry_rect.y(), current_geometry_rect_.y());
475 return *this;
478 gfx::Rect PictureLayerTiling::CoverageIterator::geometry_rect() const {
479 return current_geometry_rect_;
482 gfx::RectF PictureLayerTiling::CoverageIterator::texture_rect() const {
483 gfx::PointF tex_origin =
484 tiling_->tiling_data_.TileBoundsWithBorder(tile_i_, tile_j_).origin();
486 // Convert from dest space => content space => texture space.
487 gfx::RectF texture_rect(current_geometry_rect_);
488 texture_rect.Scale(dest_to_content_scale_,
489 dest_to_content_scale_);
490 texture_rect.Intersect(gfx::Rect(tiling_->tiling_size()));
491 if (texture_rect.IsEmpty())
492 return texture_rect;
493 texture_rect.Offset(-tex_origin.OffsetFromOrigin());
495 return texture_rect;
498 bool PictureLayerTiling::RemoveTileAt(int i, int j) {
499 TileMap::iterator found = tiles_.find(TileMapKey(i, j));
500 if (found == tiles_.end())
501 return false;
502 tiles_.erase(found);
503 return true;
506 void PictureLayerTiling::Reset() {
507 live_tiles_rect_ = gfx::Rect();
508 tiles_.clear();
511 gfx::Rect PictureLayerTiling::ComputeSkewport(
512 double current_frame_time_in_seconds,
513 const gfx::Rect& visible_rect_in_content_space) const {
514 gfx::Rect skewport = visible_rect_in_content_space;
515 if (skewport.IsEmpty())
516 return skewport;
518 if (visible_rect_history_[1].frame_time_in_seconds == 0.0)
519 return skewport;
521 double time_delta = current_frame_time_in_seconds -
522 visible_rect_history_[1].frame_time_in_seconds;
523 if (time_delta == 0.0)
524 return skewport;
526 double extrapolation_multiplier =
527 skewport_target_time_in_seconds_ / time_delta;
529 int old_x = visible_rect_history_[1].visible_rect_in_content_space.x();
530 int old_y = visible_rect_history_[1].visible_rect_in_content_space.y();
531 int old_right =
532 visible_rect_history_[1].visible_rect_in_content_space.right();
533 int old_bottom =
534 visible_rect_history_[1].visible_rect_in_content_space.bottom();
536 int new_x = visible_rect_in_content_space.x();
537 int new_y = visible_rect_in_content_space.y();
538 int new_right = visible_rect_in_content_space.right();
539 int new_bottom = visible_rect_in_content_space.bottom();
541 // Compute the maximum skewport based on
542 // |skewport_extrapolation_limit_in_content_pixels_|.
543 gfx::Rect max_skewport = skewport;
544 max_skewport.Inset(-skewport_extrapolation_limit_in_content_pixels_,
545 -skewport_extrapolation_limit_in_content_pixels_);
547 // Inset the skewport by the needed adjustment.
548 skewport.Inset(extrapolation_multiplier * (new_x - old_x),
549 extrapolation_multiplier * (new_y - old_y),
550 extrapolation_multiplier * (old_right - new_right),
551 extrapolation_multiplier * (old_bottom - new_bottom));
553 // Ensure that visible rect is contained in the skewport.
554 skewport.Union(visible_rect_in_content_space);
556 // Clip the skewport to |max_skewport|. This needs to happen after the
557 // union in case intersecting would have left the empty rect.
558 skewport.Intersect(max_skewport);
560 return skewport;
563 bool PictureLayerTiling::ComputeTilePriorityRects(
564 const gfx::Rect& viewport_in_layer_space,
565 float ideal_contents_scale,
566 double current_frame_time_in_seconds,
567 const Occlusion& occlusion_in_layer_space) {
568 if (!NeedsUpdateForFrameAtTimeAndViewport(current_frame_time_in_seconds,
569 viewport_in_layer_space)) {
570 // This should never be zero for the purposes of has_ever_been_updated().
571 DCHECK_NE(current_frame_time_in_seconds, 0.0);
572 return false;
575 gfx::Rect visible_rect_in_content_space =
576 gfx::ScaleToEnclosingRect(viewport_in_layer_space, contents_scale_);
578 if (tiling_size().IsEmpty()) {
579 UpdateVisibleRectHistory(current_frame_time_in_seconds,
580 visible_rect_in_content_space);
581 last_viewport_in_layer_space_ = viewport_in_layer_space;
582 return false;
585 // Calculate the skewport.
586 gfx::Rect skewport = ComputeSkewport(current_frame_time_in_seconds,
587 visible_rect_in_content_space);
588 DCHECK(skewport.Contains(visible_rect_in_content_space));
590 // Calculate the eventually/live tiles rect.
591 gfx::Size tile_size = tiling_data_.max_texture_size();
592 int64 eventually_rect_area =
593 max_tiles_for_interest_area_ * tile_size.width() * tile_size.height();
595 gfx::Rect eventually_rect =
596 ExpandRectEquallyToAreaBoundedBy(visible_rect_in_content_space,
597 eventually_rect_area,
598 gfx::Rect(tiling_size()),
599 &expansion_cache_);
601 DCHECK(eventually_rect.IsEmpty() ||
602 gfx::Rect(tiling_size()).Contains(eventually_rect))
603 << "tiling_size: " << tiling_size().ToString()
604 << " eventually_rect: " << eventually_rect.ToString();
606 // Calculate the soon border rect.
607 float content_to_screen_scale = ideal_contents_scale / contents_scale_;
608 gfx::Rect soon_border_rect = visible_rect_in_content_space;
609 float border = CalculateSoonBorderDistance(visible_rect_in_content_space,
610 content_to_screen_scale);
611 soon_border_rect.Inset(-border, -border, -border, -border);
613 UpdateVisibleRectHistory(current_frame_time_in_seconds,
614 visible_rect_in_content_space);
615 last_viewport_in_layer_space_ = viewport_in_layer_space;
617 SetTilePriorityRects(content_to_screen_scale, visible_rect_in_content_space,
618 skewport, soon_border_rect, eventually_rect,
619 occlusion_in_layer_space);
620 SetLiveTilesRect(eventually_rect);
621 return true;
624 void PictureLayerTiling::SetTilePriorityRects(
625 float content_to_screen_scale,
626 const gfx::Rect& visible_rect_in_content_space,
627 const gfx::Rect& skewport,
628 const gfx::Rect& soon_border_rect,
629 const gfx::Rect& eventually_rect,
630 const Occlusion& occlusion_in_layer_space) {
631 current_visible_rect_ = visible_rect_in_content_space;
632 current_skewport_rect_ = skewport;
633 current_soon_border_rect_ = soon_border_rect;
634 current_eventually_rect_ = eventually_rect;
635 current_occlusion_in_layer_space_ = occlusion_in_layer_space;
636 current_content_to_screen_scale_ = content_to_screen_scale;
638 gfx::Rect tiling_rect(tiling_size());
639 has_visible_rect_tiles_ = tiling_rect.Intersects(current_visible_rect_);
640 has_skewport_rect_tiles_ = tiling_rect.Intersects(current_skewport_rect_);
641 has_soon_border_rect_tiles_ =
642 tiling_rect.Intersects(current_soon_border_rect_);
643 has_eventually_rect_tiles_ = tiling_rect.Intersects(current_eventually_rect_);
646 void PictureLayerTiling::SetLiveTilesRect(
647 const gfx::Rect& new_live_tiles_rect) {
648 DCHECK(new_live_tiles_rect.IsEmpty() ||
649 gfx::Rect(tiling_size()).Contains(new_live_tiles_rect))
650 << "tiling_size: " << tiling_size().ToString()
651 << " new_live_tiles_rect: " << new_live_tiles_rect.ToString();
652 if (live_tiles_rect_ == new_live_tiles_rect)
653 return;
655 // Iterate to delete all tiles outside of our new live_tiles rect.
656 for (TilingData::DifferenceIterator iter(&tiling_data_, live_tiles_rect_,
657 new_live_tiles_rect);
658 iter; ++iter) {
659 RemoveTileAt(iter.index_x(), iter.index_y());
662 // Iterate to allocate new tiles for all regions with newly exposed area.
663 for (TilingData::DifferenceIterator iter(&tiling_data_, new_live_tiles_rect,
664 live_tiles_rect_);
665 iter; ++iter) {
666 TileMapKey key(iter.index());
667 if (ShouldCreateTileAt(key.first, key.second))
668 CreateTile(key.first, key.second);
671 live_tiles_rect_ = new_live_tiles_rect;
672 VerifyLiveTilesRect(false);
675 void PictureLayerTiling::VerifyLiveTilesRect(bool is_on_recycle_tree) const {
676 #if DCHECK_IS_ON()
677 for (auto it = tiles_.begin(); it != tiles_.end(); ++it) {
678 if (!it->second.get())
679 continue;
680 DCHECK(it->first.first < tiling_data_.num_tiles_x())
681 << this << " " << it->first.first << "," << it->first.second
682 << " num_tiles_x " << tiling_data_.num_tiles_x() << " live_tiles_rect "
683 << live_tiles_rect_.ToString();
684 DCHECK(it->first.second < tiling_data_.num_tiles_y())
685 << this << " " << it->first.first << "," << it->first.second
686 << " num_tiles_y " << tiling_data_.num_tiles_y() << " live_tiles_rect "
687 << live_tiles_rect_.ToString();
688 DCHECK(tiling_data_.TileBounds(it->first.first, it->first.second)
689 .Intersects(live_tiles_rect_))
690 << this << " " << it->first.first << "," << it->first.second
691 << " tile bounds "
692 << tiling_data_.TileBounds(it->first.first, it->first.second).ToString()
693 << " live_tiles_rect " << live_tiles_rect_.ToString();
695 #endif
698 bool PictureLayerTiling::IsTileOccluded(const Tile* tile) const {
699 // If this tile is not occluded on this tree, then it is not occluded.
700 if (!IsTileOccludedOnCurrentTree(tile))
701 return false;
703 // Otherwise, if this is the pending tree, we're done and the tile is
704 // occluded.
705 if (client_->GetTree() == PENDING_TREE)
706 return true;
708 // On the active tree however, we need to check if this tile will be
709 // unoccluded upon activation, in which case it has to be considered
710 // unoccluded.
711 const PictureLayerTiling* pending_twin =
712 client_->GetPendingOrActiveTwinTiling(this);
713 if (pending_twin) {
714 // If there's a pending tile in the same position. Or if the pending twin
715 // would have to be creating all tiles, then we don't need to worry about
716 // occlusion on the twin.
717 if (!TilingMatchesTileIndices(pending_twin) ||
718 pending_twin->TileAt(tile->tiling_i_index(), tile->tiling_j_index())) {
719 return true;
721 return pending_twin->IsTileOccludedOnCurrentTree(tile);
723 return true;
726 bool PictureLayerTiling::IsTileOccludedOnCurrentTree(const Tile* tile) const {
727 if (!current_occlusion_in_layer_space_.HasOcclusion())
728 return false;
729 gfx::Rect tile_query_rect =
730 gfx::IntersectRects(tile->content_rect(), current_visible_rect_);
731 // Explicitly check if the tile is outside the viewport. If so, we need to
732 // return false, since occlusion for this tile is unknown.
733 if (tile_query_rect.IsEmpty())
734 return false;
736 if (contents_scale_ != 1.f) {
737 tile_query_rect =
738 gfx::ScaleToEnclosingRect(tile_query_rect, 1.f / contents_scale_);
740 return current_occlusion_in_layer_space_.IsOccluded(tile_query_rect);
743 bool PictureLayerTiling::IsTileRequiredForActivation(const Tile* tile) const {
744 if (client_->GetTree() == PENDING_TREE) {
745 if (!can_require_tiles_for_activation_)
746 return false;
748 if (resolution_ != HIGH_RESOLUTION)
749 return false;
751 if (IsTileOccluded(tile))
752 return false;
754 bool tile_is_visible =
755 tile->content_rect().Intersects(current_visible_rect_);
756 if (!tile_is_visible)
757 return false;
759 if (client_->RequiresHighResToDraw())
760 return true;
762 const PictureLayerTiling* active_twin =
763 client_->GetPendingOrActiveTwinTiling(this);
764 if (!active_twin || !TilingMatchesTileIndices(active_twin))
765 return true;
767 if (active_twin->raster_source()->GetSize() != raster_source()->GetSize())
768 return true;
770 if (active_twin->current_visible_rect_ != current_visible_rect_)
771 return true;
773 Tile* twin_tile =
774 active_twin->TileAt(tile->tiling_i_index(), tile->tiling_j_index());
775 if (!twin_tile)
776 return false;
777 return true;
780 DCHECK(client_->GetTree() == ACTIVE_TREE);
781 const PictureLayerTiling* pending_twin =
782 client_->GetPendingOrActiveTwinTiling(this);
783 // If we don't have a pending tree, or the pending tree will overwrite the
784 // given tile, then it is not required for activation.
785 if (!pending_twin || !TilingMatchesTileIndices(pending_twin) ||
786 pending_twin->TileAt(tile->tiling_i_index(), tile->tiling_j_index())) {
787 return false;
789 // Otherwise, ask the pending twin if this tile is required for activation.
790 return pending_twin->IsTileRequiredForActivation(tile);
793 bool PictureLayerTiling::IsTileRequiredForDraw(const Tile* tile) const {
794 if (client_->GetTree() == PENDING_TREE)
795 return false;
797 if (resolution_ != HIGH_RESOLUTION)
798 return false;
800 bool tile_is_visible = current_visible_rect_.Intersects(tile->content_rect());
801 if (!tile_is_visible)
802 return false;
804 if (IsTileOccludedOnCurrentTree(tile))
805 return false;
806 return true;
809 void PictureLayerTiling::UpdateTileAndTwinPriority(Tile* tile) const {
810 tile->set_priority(ComputePriorityForTile(tile));
811 tile->set_is_occluded(IsTileOccluded(tile));
812 tile->set_required_for_activation(IsTileRequiredForActivation(tile));
813 tile->set_required_for_draw(IsTileRequiredForDraw(tile));
816 void PictureLayerTiling::VerifyAllTilesHaveCurrentRasterSource() const {
817 #if DCHECK_IS_ON()
818 for (const auto& tile_pair : tiles_)
819 DCHECK_EQ(raster_source_.get(), tile_pair.second->raster_source());
820 #endif
823 TilePriority PictureLayerTiling::ComputePriorityForTile(
824 const Tile* tile) const {
825 // TODO(vmpstr): See if this can be moved to iterators.
826 TilePriority::PriorityBin max_tile_priority_bin =
827 client_->GetMaxTilePriorityBin();
829 DCHECK_EQ(TileAt(tile->tiling_i_index(), tile->tiling_j_index()), tile);
830 gfx::Rect tile_bounds =
831 tiling_data_.TileBounds(tile->tiling_i_index(), tile->tiling_j_index());
833 if (max_tile_priority_bin <= TilePriority::NOW &&
834 current_visible_rect_.Intersects(tile_bounds)) {
835 return TilePriority(resolution_, TilePriority::NOW, 0);
838 if (max_tile_priority_bin <= TilePriority::SOON &&
839 pending_visible_rect().Intersects(tile_bounds)) {
840 return TilePriority(resolution_, TilePriority::SOON, 0);
843 DCHECK_GT(current_content_to_screen_scale_, 0.f);
844 float distance_to_visible =
845 current_visible_rect_.ManhattanInternalDistance(tile_bounds) *
846 current_content_to_screen_scale_;
848 if (max_tile_priority_bin <= TilePriority::SOON &&
849 (current_soon_border_rect_.Intersects(tile_bounds) ||
850 current_skewport_rect_.Intersects(tile_bounds))) {
851 return TilePriority(resolution_, TilePriority::SOON, distance_to_visible);
854 return TilePriority(resolution_, TilePriority::EVENTUALLY,
855 distance_to_visible);
858 void PictureLayerTiling::GetAllTilesAndPrioritiesForTracing(
859 std::map<const Tile*, TilePriority>* tile_map) const {
860 for (const auto& tile_pair : tiles_) {
861 const Tile* tile = tile_pair.second.get();
862 const TilePriority& priority = ComputePriorityForTile(tile);
863 // Store combined priority.
864 (*tile_map)[tile] = priority;
868 void PictureLayerTiling::AsValueInto(
869 base::trace_event::TracedValue* state) const {
870 state->SetInteger("num_tiles", tiles_.size());
871 state->SetDouble("content_scale", contents_scale_);
872 MathUtil::AddToTracedValue("visible_rect", current_visible_rect_, state);
873 MathUtil::AddToTracedValue("skewport_rect", current_skewport_rect_, state);
874 MathUtil::AddToTracedValue("soon_rect", current_soon_border_rect_, state);
875 MathUtil::AddToTracedValue("eventually_rect", current_eventually_rect_,
876 state);
877 MathUtil::AddToTracedValue("tiling_size", tiling_size(), state);
880 size_t PictureLayerTiling::GPUMemoryUsageInBytes() const {
881 size_t amount = 0;
882 for (TileMap::const_iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
883 const Tile* tile = it->second.get();
884 amount += tile->GPUMemoryUsageInBytes();
886 return amount;
889 PictureLayerTiling::RectExpansionCache::RectExpansionCache()
890 : previous_target(0) {
893 namespace {
895 // This struct represents an event at which the expending rect intersects
896 // one of its boundaries. 4 intersection events will occur during expansion.
897 struct EdgeEvent {
898 enum { BOTTOM, TOP, LEFT, RIGHT } edge;
899 int* num_edges;
900 int distance;
903 // Compute the delta to expand from edges to cover target_area.
904 int ComputeExpansionDelta(int num_x_edges, int num_y_edges,
905 int width, int height,
906 int64 target_area) {
907 // Compute coefficients for the quadratic equation:
908 // a*x^2 + b*x + c = 0
909 int a = num_y_edges * num_x_edges;
910 int b = num_y_edges * width + num_x_edges * height;
911 int64 c = static_cast<int64>(width) * height - target_area;
913 // Compute the delta for our edges using the quadratic equation.
914 int delta =
915 (a == 0) ? -c / b : (-b + static_cast<int>(std::sqrt(
916 static_cast<int64>(b) * b - 4.0 * a * c))) /
917 (2 * a);
918 return std::max(0, delta);
921 } // namespace
923 gfx::Rect PictureLayerTiling::ExpandRectEquallyToAreaBoundedBy(
924 const gfx::Rect& starting_rect,
925 int64 target_area,
926 const gfx::Rect& bounding_rect,
927 RectExpansionCache* cache) {
928 if (starting_rect.IsEmpty())
929 return starting_rect;
931 if (cache &&
932 cache->previous_start == starting_rect &&
933 cache->previous_bounds == bounding_rect &&
934 cache->previous_target == target_area)
935 return cache->previous_result;
937 if (cache) {
938 cache->previous_start = starting_rect;
939 cache->previous_bounds = bounding_rect;
940 cache->previous_target = target_area;
943 DCHECK(!bounding_rect.IsEmpty());
944 DCHECK_GT(target_area, 0);
946 // Expand the starting rect to cover target_area, if it is smaller than it.
947 int delta = ComputeExpansionDelta(
948 2, 2, starting_rect.width(), starting_rect.height(), target_area);
949 gfx::Rect expanded_starting_rect = starting_rect;
950 if (delta > 0)
951 expanded_starting_rect.Inset(-delta, -delta);
953 gfx::Rect rect = IntersectRects(expanded_starting_rect, bounding_rect);
954 if (rect.IsEmpty()) {
955 // The starting_rect and bounding_rect are far away.
956 if (cache)
957 cache->previous_result = rect;
958 return rect;
960 if (delta >= 0 && rect == expanded_starting_rect) {
961 // The starting rect already covers the entire bounding_rect and isn't too
962 // large for the target_area.
963 if (cache)
964 cache->previous_result = rect;
965 return rect;
968 // Continue to expand/shrink rect to let it cover target_area.
970 // These values will be updated by the loop and uses as the output.
971 int origin_x = rect.x();
972 int origin_y = rect.y();
973 int width = rect.width();
974 int height = rect.height();
976 // In the beginning we will consider 2 edges in each dimension.
977 int num_y_edges = 2;
978 int num_x_edges = 2;
980 // Create an event list.
981 EdgeEvent events[] = {
982 { EdgeEvent::BOTTOM, &num_y_edges, rect.y() - bounding_rect.y() },
983 { EdgeEvent::TOP, &num_y_edges, bounding_rect.bottom() - rect.bottom() },
984 { EdgeEvent::LEFT, &num_x_edges, rect.x() - bounding_rect.x() },
985 { EdgeEvent::RIGHT, &num_x_edges, bounding_rect.right() - rect.right() }
988 // Sort the events by distance (closest first).
989 if (events[0].distance > events[1].distance) std::swap(events[0], events[1]);
990 if (events[2].distance > events[3].distance) std::swap(events[2], events[3]);
991 if (events[0].distance > events[2].distance) std::swap(events[0], events[2]);
992 if (events[1].distance > events[3].distance) std::swap(events[1], events[3]);
993 if (events[1].distance > events[2].distance) std::swap(events[1], events[2]);
995 for (int event_index = 0; event_index < 4; event_index++) {
996 const EdgeEvent& event = events[event_index];
998 int delta = ComputeExpansionDelta(
999 num_x_edges, num_y_edges, width, height, target_area);
1001 // Clamp delta to our event distance.
1002 if (delta > event.distance)
1003 delta = event.distance;
1005 // Adjust the edge count for this kind of edge.
1006 --*event.num_edges;
1008 // Apply the delta to the edges and edge events.
1009 for (int i = event_index; i < 4; i++) {
1010 switch (events[i].edge) {
1011 case EdgeEvent::BOTTOM:
1012 origin_y -= delta;
1013 height += delta;
1014 break;
1015 case EdgeEvent::TOP:
1016 height += delta;
1017 break;
1018 case EdgeEvent::LEFT:
1019 origin_x -= delta;
1020 width += delta;
1021 break;
1022 case EdgeEvent::RIGHT:
1023 width += delta;
1024 break;
1026 events[i].distance -= delta;
1029 // If our delta is less then our event distance, we're done.
1030 if (delta < event.distance)
1031 break;
1034 gfx::Rect result(origin_x, origin_y, width, height);
1035 if (cache)
1036 cache->previous_result = result;
1037 return result;
1040 } // namespace cc