NaCl: Reinstate the "nacl_revision" field in DEPS
[chromium-blink-merge.git] / cc / layers / picture_layer_impl.cc
blob763f05e1e33ccaac7a3351bf28883ace51575183
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/layers/picture_layer_impl.h"
7 #include <algorithm>
8 #include <limits>
9 #include <set>
11 #include "base/debug/trace_event_argument.h"
12 #include "base/time/time.h"
13 #include "cc/base/math_util.h"
14 #include "cc/base/util.h"
15 #include "cc/debug/debug_colors.h"
16 #include "cc/debug/micro_benchmark_impl.h"
17 #include "cc/debug/traced_value.h"
18 #include "cc/layers/append_quads_data.h"
19 #include "cc/output/begin_frame_args.h"
20 #include "cc/quads/checkerboard_draw_quad.h"
21 #include "cc/quads/debug_border_draw_quad.h"
22 #include "cc/quads/picture_draw_quad.h"
23 #include "cc/quads/solid_color_draw_quad.h"
24 #include "cc/quads/tile_draw_quad.h"
25 #include "cc/resources/tile_manager.h"
26 #include "cc/trees/layer_tree_impl.h"
27 #include "cc/trees/occlusion_tracker.h"
28 #include "ui/gfx/quad_f.h"
29 #include "ui/gfx/rect_conversions.h"
30 #include "ui/gfx/size_conversions.h"
32 namespace {
33 const float kMaxScaleRatioDuringPinch = 2.0f;
35 // When creating a new tiling during pinch, snap to an existing
36 // tiling's scale if the desired scale is within this ratio.
37 const float kSnapToExistingTilingRatio = 1.2f;
39 // Estimate skewport 60 frames ahead for pre-rasterization on the CPU.
40 const float kCpuSkewportTargetTimeInFrames = 60.0f;
42 // Don't pre-rasterize on the GPU (except for kBackflingGuardDistancePixels in
43 // TileManager::BinFromTilePriority).
44 const float kGpuSkewportTargetTimeInFrames = 0.0f;
46 } // namespace
48 namespace cc {
50 PictureLayerImpl::Pair::Pair() : active(NULL), pending(NULL) {
53 PictureLayerImpl::Pair::Pair(PictureLayerImpl* active_layer,
54 PictureLayerImpl* pending_layer)
55 : active(active_layer), pending(pending_layer) {
58 PictureLayerImpl::Pair::~Pair() {
61 PictureLayerImpl::PictureLayerImpl(LayerTreeImpl* tree_impl, int id)
62 : LayerImpl(tree_impl, id),
63 twin_layer_(NULL),
64 pile_(PicturePileImpl::Create()),
65 is_mask_(false),
66 ideal_page_scale_(0.f),
67 ideal_device_scale_(0.f),
68 ideal_source_scale_(0.f),
69 ideal_contents_scale_(0.f),
70 raster_page_scale_(0.f),
71 raster_device_scale_(0.f),
72 raster_source_scale_(0.f),
73 raster_contents_scale_(0.f),
74 low_res_raster_contents_scale_(0.f),
75 raster_source_scale_is_fixed_(false),
76 was_screen_space_transform_animating_(false),
77 needs_post_commit_initialization_(true),
78 should_update_tile_priorities_(false) {
79 layer_tree_impl()->RegisterPictureLayerImpl(this);
82 PictureLayerImpl::~PictureLayerImpl() {
83 layer_tree_impl()->UnregisterPictureLayerImpl(this);
86 const char* PictureLayerImpl::LayerTypeAsString() const {
87 return "cc::PictureLayerImpl";
90 scoped_ptr<LayerImpl> PictureLayerImpl::CreateLayerImpl(
91 LayerTreeImpl* tree_impl) {
92 return PictureLayerImpl::Create(tree_impl, id()).PassAs<LayerImpl>();
95 void PictureLayerImpl::PushPropertiesTo(LayerImpl* base_layer) {
96 // It's possible this layer was never drawn or updated (e.g. because it was
97 // a descendant of an opacity 0 layer).
98 DoPostCommitInitializationIfNeeded();
99 PictureLayerImpl* layer_impl = static_cast<PictureLayerImpl*>(base_layer);
101 // We have already synced the important bits from the the active layer, and
102 // we will soon swap out its tilings and use them for recycling. However,
103 // there are now tiles in this layer's tilings that were unref'd and replaced
104 // with new tiles (due to invalidation). This resets all active priorities on
105 // the to-be-recycled tiling to ensure replaced tiles don't linger and take
106 // memory (due to a stale 'active' priority).
107 if (layer_impl->tilings_)
108 layer_impl->tilings_->DidBecomeRecycled();
110 LayerImpl::PushPropertiesTo(base_layer);
112 // When the pending tree pushes to the active tree, the pending twin
113 // becomes recycled.
114 layer_impl->twin_layer_ = NULL;
115 twin_layer_ = NULL;
117 layer_impl->SetIsMask(is_mask_);
118 layer_impl->pile_ = pile_;
120 // Tilings would be expensive to push, so we swap.
121 layer_impl->tilings_.swap(tilings_);
122 layer_impl->tilings_->SetClient(layer_impl);
123 if (tilings_)
124 tilings_->SetClient(this);
126 // Remove invalidated tiles from what will become a recycle tree.
127 if (tilings_)
128 tilings_->RemoveTilesInRegion(invalidation_);
130 layer_impl->raster_page_scale_ = raster_page_scale_;
131 layer_impl->raster_device_scale_ = raster_device_scale_;
132 layer_impl->raster_source_scale_ = raster_source_scale_;
133 layer_impl->raster_contents_scale_ = raster_contents_scale_;
134 layer_impl->low_res_raster_contents_scale_ = low_res_raster_contents_scale_;
135 layer_impl->needs_post_commit_initialization_ = false;
137 // The invalidation on this soon-to-be-recycled layer must be cleared to
138 // mirror clearing the invalidation in PictureLayer's version of this function
139 // in case push properties is skipped.
140 layer_impl->invalidation_.Swap(&invalidation_);
141 invalidation_.Clear();
142 needs_post_commit_initialization_ = true;
144 // We always need to push properties.
145 // See http://crbug.com/303943
146 needs_push_properties_ = true;
149 void PictureLayerImpl::AppendQuads(
150 RenderPass* render_pass,
151 const OcclusionTracker<LayerImpl>& occlusion_tracker,
152 AppendQuadsData* append_quads_data) {
153 DCHECK(!needs_post_commit_initialization_);
155 float max_contents_scale = MaximumTilingContentsScale();
156 gfx::Transform scaled_draw_transform = draw_transform();
157 scaled_draw_transform.Scale(SK_MScalar1 / max_contents_scale,
158 SK_MScalar1 / max_contents_scale);
159 gfx::Size scaled_content_bounds =
160 gfx::ToCeiledSize(gfx::ScaleSize(content_bounds(), max_contents_scale));
162 gfx::Rect scaled_visible_content_rect =
163 gfx::ScaleToEnclosingRect(visible_content_rect(), max_contents_scale);
164 scaled_visible_content_rect.Intersect(gfx::Rect(scaled_content_bounds));
166 SharedQuadState* shared_quad_state =
167 render_pass->CreateAndAppendSharedQuadState();
168 shared_quad_state->SetAll(scaled_draw_transform,
169 scaled_content_bounds,
170 scaled_visible_content_rect,
171 draw_properties().clip_rect,
172 draw_properties().is_clipped,
173 draw_properties().opacity,
174 blend_mode(),
175 sorting_context_id_);
177 if (current_draw_mode_ == DRAW_MODE_RESOURCELESS_SOFTWARE) {
178 AppendDebugBorderQuad(
179 render_pass,
180 scaled_content_bounds,
181 shared_quad_state,
182 append_quads_data,
183 DebugColors::DirectPictureBorderColor(),
184 DebugColors::DirectPictureBorderWidth(layer_tree_impl()));
186 gfx::Rect geometry_rect = scaled_visible_content_rect;
187 gfx::Rect opaque_rect = contents_opaque() ? geometry_rect : gfx::Rect();
188 gfx::Rect visible_geometry_rect = occlusion_tracker.UnoccludedContentRect(
189 geometry_rect, scaled_draw_transform);
190 if (visible_geometry_rect.IsEmpty())
191 return;
193 gfx::Size texture_size = scaled_visible_content_rect.size();
194 gfx::RectF texture_rect = gfx::RectF(texture_size);
195 gfx::Rect quad_content_rect = scaled_visible_content_rect;
197 PictureDrawQuad* quad =
198 render_pass->CreateAndAppendDrawQuad<PictureDrawQuad>();
199 quad->SetNew(shared_quad_state,
200 geometry_rect,
201 opaque_rect,
202 visible_geometry_rect,
203 texture_rect,
204 texture_size,
205 RGBA_8888,
206 quad_content_rect,
207 max_contents_scale,
208 pile_);
209 return;
212 AppendDebugBorderQuad(
213 render_pass, scaled_content_bounds, shared_quad_state, append_quads_data);
215 if (ShowDebugBorders()) {
216 for (PictureLayerTilingSet::CoverageIterator iter(
217 tilings_.get(),
218 max_contents_scale,
219 scaled_visible_content_rect,
220 ideal_contents_scale_);
221 iter;
222 ++iter) {
223 SkColor color;
224 float width;
225 if (*iter && iter->IsReadyToDraw()) {
226 ManagedTileState::TileVersion::Mode mode =
227 iter->GetTileVersionForDrawing().mode();
228 if (mode == ManagedTileState::TileVersion::SOLID_COLOR_MODE) {
229 color = DebugColors::SolidColorTileBorderColor();
230 width = DebugColors::SolidColorTileBorderWidth(layer_tree_impl());
231 } else if (mode == ManagedTileState::TileVersion::PICTURE_PILE_MODE) {
232 color = DebugColors::PictureTileBorderColor();
233 width = DebugColors::PictureTileBorderWidth(layer_tree_impl());
234 } else if (iter->priority(ACTIVE_TREE).resolution == HIGH_RESOLUTION) {
235 color = DebugColors::HighResTileBorderColor();
236 width = DebugColors::HighResTileBorderWidth(layer_tree_impl());
237 } else if (iter->priority(ACTIVE_TREE).resolution == LOW_RESOLUTION) {
238 color = DebugColors::LowResTileBorderColor();
239 width = DebugColors::LowResTileBorderWidth(layer_tree_impl());
240 } else if (iter->contents_scale() > max_contents_scale) {
241 color = DebugColors::ExtraHighResTileBorderColor();
242 width = DebugColors::ExtraHighResTileBorderWidth(layer_tree_impl());
243 } else {
244 color = DebugColors::ExtraLowResTileBorderColor();
245 width = DebugColors::ExtraLowResTileBorderWidth(layer_tree_impl());
247 } else {
248 color = DebugColors::MissingTileBorderColor();
249 width = DebugColors::MissingTileBorderWidth(layer_tree_impl());
252 DebugBorderDrawQuad* debug_border_quad =
253 render_pass->CreateAndAppendDrawQuad<DebugBorderDrawQuad>();
254 gfx::Rect geometry_rect = iter.geometry_rect();
255 gfx::Rect visible_geometry_rect = geometry_rect;
256 debug_border_quad->SetNew(shared_quad_state,
257 geometry_rect,
258 visible_geometry_rect,
259 color,
260 width);
264 // Keep track of the tilings that were used so that tilings that are
265 // unused can be considered for removal.
266 std::vector<PictureLayerTiling*> seen_tilings;
268 // Ignore missing tiles outside of viewport for tile priority. This is
269 // normally the same as draw viewport but can be independently overridden by
270 // embedders like Android WebView with SetExternalDrawConstraints.
271 gfx::Rect scaled_viewport_for_tile_priority = gfx::ScaleToEnclosingRect(
272 GetViewportForTilePriorityInContentSpace(), max_contents_scale);
274 size_t missing_tile_count = 0u;
275 size_t on_demand_missing_tile_count = 0u;
276 for (PictureLayerTilingSet::CoverageIterator iter(tilings_.get(),
277 max_contents_scale,
278 scaled_visible_content_rect,
279 ideal_contents_scale_);
280 iter;
281 ++iter) {
282 gfx::Rect geometry_rect = iter.geometry_rect();
283 gfx::Rect visible_geometry_rect = occlusion_tracker.UnoccludedContentRect(
284 geometry_rect, scaled_draw_transform);
285 if (visible_geometry_rect.IsEmpty())
286 continue;
288 append_quads_data->visible_content_area +=
289 visible_geometry_rect.width() * visible_geometry_rect.height();
291 bool has_draw_quad = false;
292 if (*iter && iter->IsReadyToDraw()) {
293 const ManagedTileState::TileVersion& tile_version =
294 iter->GetTileVersionForDrawing();
295 switch (tile_version.mode()) {
296 case ManagedTileState::TileVersion::RESOURCE_MODE: {
297 gfx::RectF texture_rect = iter.texture_rect();
298 gfx::Rect opaque_rect = iter->opaque_rect();
299 opaque_rect.Intersect(geometry_rect);
301 // The raster_contents_scale_ is the best scale that the layer is
302 // trying to produce, even though it may not be ideal. Since that's
303 // the best the layer can promise in the future, consider those as
304 // complete. But if a tile is ideal scale, we don't want to consider
305 // it incomplete and trying to replace it with a tile at a worse
306 // scale.
307 if (iter->contents_scale() != raster_contents_scale_ &&
308 iter->contents_scale() != ideal_contents_scale_ &&
309 geometry_rect.Intersects(scaled_viewport_for_tile_priority)) {
310 append_quads_data->num_incomplete_tiles++;
313 TileDrawQuad* quad =
314 render_pass->CreateAndAppendDrawQuad<TileDrawQuad>();
315 quad->SetNew(shared_quad_state,
316 geometry_rect,
317 opaque_rect,
318 visible_geometry_rect,
319 tile_version.get_resource_id(),
320 texture_rect,
321 iter.texture_size(),
322 tile_version.contents_swizzled());
323 has_draw_quad = true;
324 break;
326 case ManagedTileState::TileVersion::PICTURE_PILE_MODE: {
327 if (!layer_tree_impl()
328 ->GetRendererCapabilities()
329 .allow_rasterize_on_demand) {
330 ++on_demand_missing_tile_count;
331 break;
334 gfx::RectF texture_rect = iter.texture_rect();
335 gfx::Rect opaque_rect = iter->opaque_rect();
336 opaque_rect.Intersect(geometry_rect);
338 ResourceProvider* resource_provider =
339 layer_tree_impl()->resource_provider();
340 ResourceFormat format =
341 resource_provider->memory_efficient_texture_format();
342 PictureDrawQuad* quad =
343 render_pass->CreateAndAppendDrawQuad<PictureDrawQuad>();
344 quad->SetNew(shared_quad_state,
345 geometry_rect,
346 opaque_rect,
347 visible_geometry_rect,
348 texture_rect,
349 iter.texture_size(),
350 format,
351 iter->content_rect(),
352 iter->contents_scale(),
353 pile_);
354 has_draw_quad = true;
355 break;
357 case ManagedTileState::TileVersion::SOLID_COLOR_MODE: {
358 SolidColorDrawQuad* quad =
359 render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
360 quad->SetNew(shared_quad_state,
361 geometry_rect,
362 visible_geometry_rect,
363 tile_version.get_solid_color(),
364 false);
365 has_draw_quad = true;
366 break;
371 if (!has_draw_quad) {
372 if (draw_checkerboard_for_missing_tiles()) {
373 CheckerboardDrawQuad* quad =
374 render_pass->CreateAndAppendDrawQuad<CheckerboardDrawQuad>();
375 SkColor color = DebugColors::DefaultCheckerboardColor();
376 quad->SetNew(
377 shared_quad_state, geometry_rect, visible_geometry_rect, color);
378 } else {
379 SkColor color = SafeOpaqueBackgroundColor();
380 SolidColorDrawQuad* quad =
381 render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
382 quad->SetNew(shared_quad_state,
383 geometry_rect,
384 visible_geometry_rect,
385 color,
386 false);
389 if (geometry_rect.Intersects(scaled_viewport_for_tile_priority)) {
390 append_quads_data->num_missing_tiles++;
391 ++missing_tile_count;
393 append_quads_data->approximated_visible_content_area +=
394 visible_geometry_rect.width() * visible_geometry_rect.height();
395 continue;
398 if (iter->priority(ACTIVE_TREE).resolution != HIGH_RESOLUTION) {
399 append_quads_data->approximated_visible_content_area +=
400 visible_geometry_rect.width() * visible_geometry_rect.height();
403 if (seen_tilings.empty() || seen_tilings.back() != iter.CurrentTiling())
404 seen_tilings.push_back(iter.CurrentTiling());
407 if (missing_tile_count) {
408 TRACE_EVENT_INSTANT2("cc",
409 "PictureLayerImpl::AppendQuads checkerboard",
410 TRACE_EVENT_SCOPE_THREAD,
411 "missing_tile_count",
412 missing_tile_count,
413 "on_demand_missing_tile_count",
414 on_demand_missing_tile_count);
417 // Aggressively remove any tilings that are not seen to save memory. Note
418 // that this is at the expense of doing cause more frequent re-painting. A
419 // better scheme would be to maintain a tighter visible_content_rect for the
420 // finer tilings.
421 CleanUpTilingsOnActiveLayer(seen_tilings);
424 void PictureLayerImpl::UpdateTiles(
425 const OcclusionTracker<LayerImpl>* occlusion_tracker) {
426 TRACE_EVENT0("cc", "PictureLayerImpl::UpdateTiles");
428 DoPostCommitInitializationIfNeeded();
430 // TODO(danakj): We should always get an occlusion tracker when we are using
431 // occlusion, so update this check when we don't use a pending tree in the
432 // browser compositor.
433 DCHECK(!occlusion_tracker ||
434 layer_tree_impl()->settings().use_occlusion_for_tile_prioritization);
436 visible_rect_for_tile_priority_ = visible_content_rect();
437 viewport_rect_for_tile_priority_ =
438 layer_tree_impl()->ViewportRectForTilePriority();
439 screen_space_transform_for_tile_priority_ = screen_space_transform();
441 if (!CanHaveTilings()) {
442 ideal_page_scale_ = 0.f;
443 ideal_device_scale_ = 0.f;
444 ideal_contents_scale_ = 0.f;
445 ideal_source_scale_ = 0.f;
446 SanityCheckTilingState();
447 return;
450 UpdateIdealScales();
452 DCHECK(tilings_->num_tilings() > 0 || raster_contents_scale_ == 0.f)
453 << "A layer with no tilings shouldn't have valid raster scales";
454 if (!raster_contents_scale_ || ShouldAdjustRasterScale()) {
455 RecalculateRasterScales();
456 AddTilingsForRasterScale();
459 DCHECK(raster_page_scale_);
460 DCHECK(raster_device_scale_);
461 DCHECK(raster_source_scale_);
462 DCHECK(raster_contents_scale_);
463 DCHECK(low_res_raster_contents_scale_);
465 was_screen_space_transform_animating_ =
466 draw_properties().screen_space_transform_is_animating;
468 should_update_tile_priorities_ = true;
470 UpdateTilePriorities(occlusion_tracker);
472 if (layer_tree_impl()->IsPendingTree())
473 MarkVisibleResourcesAsRequired();
476 void PictureLayerImpl::UpdateTilePriorities(
477 const OcclusionTracker<LayerImpl>* occlusion_tracker) {
478 TRACE_EVENT0("cc", "PictureLayerImpl::UpdateTilePriorities");
480 double current_frame_time_in_seconds =
481 (layer_tree_impl()->CurrentBeginFrameArgs().frame_time -
482 base::TimeTicks()).InSecondsF();
484 bool tiling_needs_update = false;
485 for (size_t i = 0; i < tilings_->num_tilings(); ++i) {
486 if (tilings_->tiling_at(i)->NeedsUpdateForFrameAtTime(
487 current_frame_time_in_seconds)) {
488 tiling_needs_update = true;
489 break;
492 if (!tiling_needs_update)
493 return;
495 gfx::Rect visible_rect_in_content_space(
496 GetViewportForTilePriorityInContentSpace());
497 visible_rect_in_content_space.Intersect(visible_content_rect());
498 gfx::Rect visible_layer_rect = gfx::ScaleToEnclosingRect(
499 visible_rect_in_content_space, 1.f / contents_scale_x());
500 WhichTree tree =
501 layer_tree_impl()->IsActiveTree() ? ACTIVE_TREE : PENDING_TREE;
502 for (size_t i = 0; i < tilings_->num_tilings(); ++i) {
503 tilings_->tiling_at(i)->UpdateTilePriorities(tree,
504 visible_layer_rect,
505 ideal_contents_scale_,
506 current_frame_time_in_seconds,
507 occlusion_tracker,
508 render_target(),
509 draw_transform());
512 // Tile priorities were modified.
513 layer_tree_impl()->DidModifyTilePriorities();
516 gfx::Rect PictureLayerImpl::GetViewportForTilePriorityInContentSpace() const {
517 // If visible_rect_for_tile_priority_ is empty or
518 // viewport_rect_for_tile_priority_ is set to be different from the device
519 // viewport, try to inverse project the viewport into layer space and use
520 // that. Otherwise just use visible_rect_for_tile_priority_
521 gfx::Rect visible_rect_in_content_space = visible_rect_for_tile_priority_;
523 if (visible_rect_in_content_space.IsEmpty() ||
524 layer_tree_impl()->DeviceViewport() != viewport_rect_for_tile_priority_) {
525 gfx::Transform view_to_layer(gfx::Transform::kSkipInitialization);
527 if (screen_space_transform_for_tile_priority_.GetInverse(&view_to_layer)) {
528 // Transform from view space to content space.
529 visible_rect_in_content_space =
530 gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
531 view_to_layer, viewport_rect_for_tile_priority_));
533 visible_rect_in_content_space.Intersect(gfx::Rect(content_bounds()));
537 return visible_rect_in_content_space;
540 PictureLayerImpl* PictureLayerImpl::GetRecycledTwinLayer() {
541 // TODO(vmpstr): Maintain recycled twin as a member. crbug.com/407418
542 return static_cast<PictureLayerImpl*>(
543 layer_tree_impl()->FindRecycleTreeLayerById(id()));
546 void PictureLayerImpl::NotifyTileStateChanged(const Tile* tile) {
547 if (layer_tree_impl()->IsActiveTree()) {
548 gfx::RectF layer_damage_rect =
549 gfx::ScaleRect(tile->content_rect(), 1.f / tile->contents_scale());
550 AddDamageRect(layer_damage_rect);
554 void PictureLayerImpl::DidBecomeActive() {
555 LayerImpl::DidBecomeActive();
556 tilings_->DidBecomeActive();
557 layer_tree_impl()->DidModifyTilePriorities();
560 void PictureLayerImpl::DidBeginTracing() {
561 pile_->DidBeginTracing();
564 void PictureLayerImpl::ReleaseResources() {
565 if (tilings_)
566 RemoveAllTilings();
568 ResetRasterScale();
570 // To avoid an edge case after lost context where the tree is up to date but
571 // the tilings have not been managed, request an update draw properties
572 // to force tilings to get managed.
573 layer_tree_impl()->set_needs_update_draw_properties();
576 skia::RefPtr<SkPicture> PictureLayerImpl::GetPicture() {
577 return pile_->GetFlattenedPicture();
580 scoped_refptr<Tile> PictureLayerImpl::CreateTile(PictureLayerTiling* tiling,
581 const gfx::Rect& content_rect) {
582 if (!pile_->CanRaster(tiling->contents_scale(), content_rect))
583 return scoped_refptr<Tile>();
585 // TODO(vmpstr): Revisit this. For now, enabling analysis means that we get as
586 // much savings on memory as we can. However, for some cases like ganesh or
587 // small layers, the amount of time we spend analyzing might not justify
588 // memory savings that we can get.
589 // Bugs: crbug.com/397198, crbug.com/396908
590 int flags = Tile::USE_PICTURE_ANALYSIS;
592 return layer_tree_impl()->tile_manager()->CreateTile(
593 pile_.get(),
594 content_rect.size(),
595 content_rect,
596 contents_opaque() ? content_rect : gfx::Rect(),
597 tiling->contents_scale(),
598 id(),
599 layer_tree_impl()->source_frame_number(),
600 flags);
603 PicturePileImpl* PictureLayerImpl::GetPile() {
604 return pile_.get();
607 const Region* PictureLayerImpl::GetInvalidation() {
608 return &invalidation_;
611 const PictureLayerTiling* PictureLayerImpl::GetTwinTiling(
612 const PictureLayerTiling* tiling) const {
613 if (!twin_layer_)
614 return NULL;
615 return twin_layer_->tilings_->TilingAtScale(tiling->contents_scale());
618 PictureLayerTiling* PictureLayerImpl::GetRecycledTwinTiling(
619 const PictureLayerTiling* tiling) {
620 PictureLayerImpl* recycled_twin = GetRecycledTwinLayer();
621 if (!recycled_twin || !recycled_twin->tilings_)
622 return NULL;
623 return recycled_twin->tilings_->TilingAtScale(tiling->contents_scale());
626 size_t PictureLayerImpl::GetMaxTilesForInterestArea() const {
627 return layer_tree_impl()->settings().max_tiles_for_interest_area;
630 float PictureLayerImpl::GetSkewportTargetTimeInSeconds() const {
631 float skewport_target_time_in_frames =
632 layer_tree_impl()->use_gpu_rasterization()
633 ? kGpuSkewportTargetTimeInFrames
634 : kCpuSkewportTargetTimeInFrames;
635 return skewport_target_time_in_frames *
636 layer_tree_impl()->begin_impl_frame_interval().InSecondsF() *
637 layer_tree_impl()->settings().skewport_target_time_multiplier;
640 int PictureLayerImpl::GetSkewportExtrapolationLimitInContentPixels() const {
641 return layer_tree_impl()
642 ->settings()
643 .skewport_extrapolation_limit_in_content_pixels;
646 gfx::Size PictureLayerImpl::CalculateTileSize(
647 const gfx::Size& content_bounds) const {
648 if (is_mask_) {
649 int max_size = layer_tree_impl()->MaxTextureSize();
650 return gfx::Size(
651 std::min(max_size, content_bounds.width()),
652 std::min(max_size, content_bounds.height()));
655 int max_texture_size =
656 layer_tree_impl()->resource_provider()->max_texture_size();
658 gfx::Size default_tile_size = layer_tree_impl()->settings().default_tile_size;
659 if (layer_tree_impl()->use_gpu_rasterization()) {
660 // TODO(ernstm) crbug.com/365877: We need a unified way to override the
661 // default-tile-size.
662 default_tile_size =
663 gfx::Size(layer_tree_impl()->device_viewport_size().width(),
664 layer_tree_impl()->device_viewport_size().height() / 4);
666 default_tile_size.SetToMin(gfx::Size(max_texture_size, max_texture_size));
668 gfx::Size max_untiled_content_size =
669 layer_tree_impl()->settings().max_untiled_layer_size;
670 max_untiled_content_size.SetToMin(
671 gfx::Size(max_texture_size, max_texture_size));
673 bool any_dimension_too_large =
674 content_bounds.width() > max_untiled_content_size.width() ||
675 content_bounds.height() > max_untiled_content_size.height();
677 bool any_dimension_one_tile =
678 content_bounds.width() <= default_tile_size.width() ||
679 content_bounds.height() <= default_tile_size.height();
681 // If long and skinny, tile at the max untiled content size, and clamp
682 // the smaller dimension to the content size, e.g. 1000x12 layer with
683 // 500x500 max untiled size would get 500x12 tiles. Also do this
684 // if the layer is small.
685 if (any_dimension_one_tile || !any_dimension_too_large) {
686 int width = std::min(
687 std::max(max_untiled_content_size.width(), default_tile_size.width()),
688 content_bounds.width());
689 int height = std::min(
690 std::max(max_untiled_content_size.height(), default_tile_size.height()),
691 content_bounds.height());
692 // Round up to the closest multiple of 64. This improves recycling and
693 // avoids odd texture sizes.
694 width = RoundUp(width, 64);
695 height = RoundUp(height, 64);
696 return gfx::Size(width, height);
699 return default_tile_size;
702 void PictureLayerImpl::SyncFromActiveLayer(const PictureLayerImpl* other) {
703 TRACE_EVENT0("cc", "SyncFromActiveLayer");
704 DCHECK(!other->needs_post_commit_initialization_);
705 DCHECK(other->tilings_);
707 if (!DrawsContent()) {
708 RemoveAllTilings();
709 return;
712 raster_page_scale_ = other->raster_page_scale_;
713 raster_device_scale_ = other->raster_device_scale_;
714 raster_source_scale_ = other->raster_source_scale_;
715 raster_contents_scale_ = other->raster_contents_scale_;
716 low_res_raster_contents_scale_ = other->low_res_raster_contents_scale_;
718 bool synced_high_res_tiling = false;
719 if (CanHaveTilings()) {
720 synced_high_res_tiling = tilings_->SyncTilings(
721 *other->tilings_, bounds(), invalidation_, MinimumContentsScale());
722 } else {
723 RemoveAllTilings();
726 // If our MinimumContentsScale has changed to prevent the twin's high res
727 // tiling from being synced, we should reset the raster scale and let it be
728 // recalculated (1) again. This can happen if our bounds shrink to the point
729 // where min contents scale grows.
730 // (1) - TODO(vmpstr) Instead of hoping that this will be recalculated, we
731 // should refactor this code a little bit and actually recalculate this.
732 // However, this is a larger undertaking, so this will work for now.
733 if (!synced_high_res_tiling)
734 ResetRasterScale();
735 else
736 SanityCheckTilingState();
739 void PictureLayerImpl::SyncTiling(
740 const PictureLayerTiling* tiling) {
741 if (!CanHaveTilingWithScale(tiling->contents_scale()))
742 return;
743 tilings_->AddTiling(tiling->contents_scale());
745 // If this tree needs update draw properties, then the tiling will
746 // get updated prior to drawing or activation. If this tree does not
747 // need update draw properties, then its transforms are up to date and
748 // we can create tiles for this tiling immediately.
749 if (!layer_tree_impl()->needs_update_draw_properties() &&
750 should_update_tile_priorities_) {
751 // TODO(danakj): Add a DCHECK() that we are not using occlusion tracking
752 // when we stop using the pending tree in the browser compositor. If we want
753 // to support occlusion tracking here, we need to dirty the draw properties
754 // or save occlusion as a draw property.
755 UpdateTilePriorities(NULL);
759 void PictureLayerImpl::SetIsMask(bool is_mask) {
760 if (is_mask_ == is_mask)
761 return;
762 is_mask_ = is_mask;
763 if (tilings_)
764 tilings_->RemoveAllTiles();
767 ResourceProvider::ResourceId PictureLayerImpl::ContentsResourceId() const {
768 gfx::Rect content_rect(content_bounds());
769 float scale = MaximumTilingContentsScale();
770 PictureLayerTilingSet::CoverageIterator iter(
771 tilings_.get(), scale, content_rect, ideal_contents_scale_);
773 // Mask resource not ready yet.
774 if (!iter || !*iter)
775 return 0;
777 // Masks only supported if they fit on exactly one tile.
778 if (iter.geometry_rect() != content_rect)
779 return 0;
781 const ManagedTileState::TileVersion& tile_version =
782 iter->GetTileVersionForDrawing();
783 if (!tile_version.IsReadyToDraw() ||
784 tile_version.mode() != ManagedTileState::TileVersion::RESOURCE_MODE)
785 return 0;
787 return tile_version.get_resource_id();
790 void PictureLayerImpl::MarkVisibleResourcesAsRequired() const {
791 DCHECK(layer_tree_impl()->IsPendingTree());
792 DCHECK(ideal_contents_scale_);
793 DCHECK_GT(tilings_->num_tilings(), 0u);
795 // The goal of this function is to find the minimum set of tiles that need to
796 // be ready to draw in order to activate without flashing content from a
797 // higher res on the active tree to a lower res on the pending tree.
799 // First, early out for layers with no visible content.
800 if (visible_content_rect().IsEmpty())
801 return;
803 gfx::Rect rect(visible_content_rect());
805 // Only mark tiles inside the viewport for tile priority as required for
806 // activation. This viewport is normally the same as the draw viewport but
807 // can be independently overridden by embedders like Android WebView with
808 // SetExternalDrawConstraints.
809 rect.Intersect(GetViewportForTilePriorityInContentSpace());
811 float min_acceptable_scale =
812 std::min(raster_contents_scale_, ideal_contents_scale_);
814 if (PictureLayerImpl* twin = twin_layer_) {
815 float twin_min_acceptable_scale =
816 std::min(twin->ideal_contents_scale_, twin->raster_contents_scale_);
817 // Ignore 0 scale in case CalculateContentsScale() has never been
818 // called for active twin.
819 if (twin_min_acceptable_scale != 0.0f) {
820 min_acceptable_scale =
821 std::min(min_acceptable_scale, twin_min_acceptable_scale);
825 PictureLayerTiling* high_res = NULL;
826 PictureLayerTiling* low_res = NULL;
828 // First pass: ready to draw tiles in acceptable but non-ideal tilings are
829 // marked as required for activation so that their textures are not thrown
830 // away; any non-ready tiles are not marked as required.
831 Region missing_region = rect;
832 for (size_t i = 0; i < tilings_->num_tilings(); ++i) {
833 PictureLayerTiling* tiling = tilings_->tiling_at(i);
834 DCHECK(tiling->has_ever_been_updated());
836 if (tiling->resolution() == LOW_RESOLUTION) {
837 DCHECK(!low_res) << "There can only be one low res tiling";
838 low_res = tiling;
840 if (tiling->contents_scale() < min_acceptable_scale)
841 continue;
842 if (tiling->resolution() == HIGH_RESOLUTION) {
843 DCHECK(!high_res) << "There can only be one high res tiling";
844 high_res = tiling;
845 continue;
847 for (PictureLayerTiling::CoverageIterator iter(tiling,
848 contents_scale_x(),
849 rect);
850 iter;
851 ++iter) {
852 if (!*iter || !iter->IsReadyToDraw())
853 continue;
855 missing_region.Subtract(iter.geometry_rect());
856 iter->MarkRequiredForActivation();
859 DCHECK(high_res) << "There must be one high res tiling";
861 // If these pointers are null (because no twin, no matching tiling, or the
862 // simpification just below), then high res tiles will be required to fill any
863 // holes left by the first pass above. If the pointers are valid, then this
864 // layer is allowed to skip any tiles that are not ready on its twin.
865 const PictureLayerTiling* twin_high_res = NULL;
866 const PictureLayerTiling* twin_low_res = NULL;
868 if (twin_layer_) {
869 // As a simplification, only allow activating to skip twin tiles that the
870 // active layer is also missing when both this layer and its twin have
871 // "simple" sets of tilings: only 2 tilings (high and low) or only 1 high
872 // res tiling. This avoids having to iterate/track coverage of non-ideal
873 // tilings during the last draw call on the active layer.
874 if (tilings_->num_tilings() <= 2 &&
875 twin_layer_->tilings_->num_tilings() <= tilings_->num_tilings()) {
876 twin_low_res = low_res ? GetTwinTiling(low_res) : NULL;
877 twin_high_res = high_res ? GetTwinTiling(high_res) : NULL;
880 // If this layer and its twin have different transforms, then don't compare
881 // them and only allow activating to high res tiles, since tiles on each
882 // layer will be in different places on screen.
883 if (twin_layer_->layer_tree_impl()->RequiresHighResToDraw() ||
884 bounds() != twin_layer_->bounds() ||
885 draw_properties().screen_space_transform !=
886 twin_layer_->draw_properties().screen_space_transform) {
887 twin_high_res = NULL;
888 twin_low_res = NULL;
892 // As a second pass, mark as required any visible high res tiles not filled in
893 // by acceptable non-ideal tiles from the first pass.
894 if (MarkVisibleTilesAsRequired(
895 high_res, twin_high_res, contents_scale_x(), rect, missing_region)) {
896 // As an optional third pass, if a high res tile was skipped because its
897 // twin was also missing, then fall back to mark low res tiles as required
898 // in case the active twin is substituting those for missing high res
899 // content. Only suitable, when low res is enabled.
900 if (low_res) {
901 MarkVisibleTilesAsRequired(
902 low_res, twin_low_res, contents_scale_x(), rect, missing_region);
907 bool PictureLayerImpl::MarkVisibleTilesAsRequired(
908 PictureLayerTiling* tiling,
909 const PictureLayerTiling* optional_twin_tiling,
910 float contents_scale,
911 const gfx::Rect& rect,
912 const Region& missing_region) const {
913 bool twin_had_missing_tile = false;
914 for (PictureLayerTiling::CoverageIterator iter(tiling,
915 contents_scale,
916 rect);
917 iter;
918 ++iter) {
919 Tile* tile = *iter;
920 // A null tile (i.e. missing recording) can just be skipped.
921 if (!tile)
922 continue;
924 // If the tile is occluded, don't mark it as required for activation.
925 if (tile->is_occluded(PENDING_TREE))
926 continue;
928 // If the missing region doesn't cover it, this tile is fully
929 // covered by acceptable tiles at other scales.
930 if (!missing_region.Intersects(iter.geometry_rect()))
931 continue;
933 // If the twin tile doesn't exist (i.e. missing recording or so far away
934 // that it is outside the visible tile rect) or this tile is shared between
935 // with the twin, then this tile isn't required to prevent flashing.
936 if (optional_twin_tiling) {
937 Tile* twin_tile = optional_twin_tiling->TileAt(iter.i(), iter.j());
938 if (!twin_tile || twin_tile == tile) {
939 // However if the shared tile is being used on the active tree, then
940 // there's no missing content in this place, and low res is not needed.
941 if (!twin_tile || !twin_tile->IsReadyToDraw())
942 twin_had_missing_tile = true;
943 continue;
947 tile->MarkRequiredForActivation();
949 return twin_had_missing_tile;
952 void PictureLayerImpl::DoPostCommitInitialization() {
953 DCHECK(needs_post_commit_initialization_);
954 DCHECK(layer_tree_impl()->IsPendingTree());
956 if (!tilings_)
957 tilings_.reset(new PictureLayerTilingSet(this, bounds()));
959 DCHECK(!twin_layer_);
960 twin_layer_ = static_cast<PictureLayerImpl*>(
961 layer_tree_impl()->FindActiveTreeLayerById(id()));
962 if (twin_layer_) {
963 DCHECK(!twin_layer_->twin_layer_);
964 twin_layer_->twin_layer_ = this;
965 // If the twin has never been pushed to, do not sync from it.
966 // This can happen if this function is called during activation.
967 if (!twin_layer_->needs_post_commit_initialization_)
968 SyncFromActiveLayer(twin_layer_);
971 needs_post_commit_initialization_ = false;
974 PictureLayerTiling* PictureLayerImpl::AddTiling(float contents_scale) {
975 DCHECK(CanHaveTilingWithScale(contents_scale)) <<
976 "contents_scale: " << contents_scale;
978 PictureLayerTiling* tiling = tilings_->AddTiling(contents_scale);
980 DCHECK(pile_->HasRecordings());
982 if (twin_layer_)
983 twin_layer_->SyncTiling(tiling);
985 return tiling;
988 void PictureLayerImpl::RemoveTiling(float contents_scale) {
989 if (!tilings_ || tilings_->num_tilings() == 0)
990 return;
992 for (size_t i = 0; i < tilings_->num_tilings(); ++i) {
993 PictureLayerTiling* tiling = tilings_->tiling_at(i);
994 if (tiling->contents_scale() == contents_scale) {
995 tilings_->Remove(tiling);
996 break;
999 if (tilings_->num_tilings() == 0)
1000 ResetRasterScale();
1001 SanityCheckTilingState();
1004 void PictureLayerImpl::RemoveAllTilings() {
1005 if (tilings_)
1006 tilings_->RemoveAllTilings();
1007 // If there are no tilings, then raster scales are no longer meaningful.
1008 ResetRasterScale();
1011 namespace {
1013 inline float PositiveRatio(float float1, float float2) {
1014 DCHECK_GT(float1, 0);
1015 DCHECK_GT(float2, 0);
1016 return float1 > float2 ? float1 / float2 : float2 / float1;
1019 } // namespace
1021 void PictureLayerImpl::AddTilingsForRasterScale() {
1022 PictureLayerTiling* high_res = NULL;
1023 PictureLayerTiling* low_res = NULL;
1025 PictureLayerTiling* previous_low_res = NULL;
1026 for (size_t i = 0; i < tilings_->num_tilings(); ++i) {
1027 PictureLayerTiling* tiling = tilings_->tiling_at(i);
1028 if (tiling->contents_scale() == raster_contents_scale_)
1029 high_res = tiling;
1030 if (tiling->contents_scale() == low_res_raster_contents_scale_)
1031 low_res = tiling;
1032 if (tiling->resolution() == LOW_RESOLUTION)
1033 previous_low_res = tiling;
1035 // Reset all tilings to non-ideal until the end of this function.
1036 tiling->set_resolution(NON_IDEAL_RESOLUTION);
1039 if (!high_res) {
1040 high_res = AddTiling(raster_contents_scale_);
1041 if (raster_contents_scale_ == low_res_raster_contents_scale_)
1042 low_res = high_res;
1045 // Only create new low res tilings when the transform is static. This
1046 // prevents wastefully creating a paired low res tiling for every new high res
1047 // tiling during a pinch or a CSS animation.
1048 bool is_pinching = layer_tree_impl()->PinchGestureActive();
1049 if (layer_tree_impl()->create_low_res_tiling() && !is_pinching &&
1050 !draw_properties().screen_space_transform_is_animating && !low_res &&
1051 low_res != high_res)
1052 low_res = AddTiling(low_res_raster_contents_scale_);
1054 // Set low-res if we have one.
1055 if (!low_res)
1056 low_res = previous_low_res;
1057 if (low_res && low_res != high_res)
1058 low_res->set_resolution(LOW_RESOLUTION);
1060 // Make sure we always have one high-res (even if high == low).
1061 high_res->set_resolution(HIGH_RESOLUTION);
1063 SanityCheckTilingState();
1066 bool PictureLayerImpl::ShouldAdjustRasterScale() const {
1067 if (was_screen_space_transform_animating_ !=
1068 draw_properties().screen_space_transform_is_animating)
1069 return true;
1071 if (draw_properties().screen_space_transform_is_animating &&
1072 raster_contents_scale_ != ideal_contents_scale_ &&
1073 ShouldAdjustRasterScaleDuringScaleAnimations())
1074 return true;
1076 bool is_pinching = layer_tree_impl()->PinchGestureActive();
1077 if (is_pinching && raster_page_scale_) {
1078 // We change our raster scale when it is:
1079 // - Higher than ideal (need a lower-res tiling available)
1080 // - Too far from ideal (need a higher-res tiling available)
1081 float ratio = ideal_page_scale_ / raster_page_scale_;
1082 if (raster_page_scale_ > ideal_page_scale_ ||
1083 ratio > kMaxScaleRatioDuringPinch)
1084 return true;
1087 if (!is_pinching) {
1088 // When not pinching, match the ideal page scale factor.
1089 if (raster_page_scale_ != ideal_page_scale_)
1090 return true;
1093 // Always match the ideal device scale factor.
1094 if (raster_device_scale_ != ideal_device_scale_)
1095 return true;
1097 // When the source scale changes we want to match it, but not when animating
1098 // or when we've fixed the scale in place.
1099 if (!draw_properties().screen_space_transform_is_animating &&
1100 !raster_source_scale_is_fixed_ &&
1101 raster_source_scale_ != ideal_source_scale_)
1102 return true;
1104 return false;
1107 float PictureLayerImpl::SnappedContentsScale(float scale) {
1108 // If a tiling exists within the max snapping ratio, snap to its scale.
1109 float snapped_contents_scale = scale;
1110 float snapped_ratio = kSnapToExistingTilingRatio;
1111 for (size_t i = 0; i < tilings_->num_tilings(); ++i) {
1112 float tiling_contents_scale = tilings_->tiling_at(i)->contents_scale();
1113 float ratio = PositiveRatio(tiling_contents_scale, scale);
1114 if (ratio < snapped_ratio) {
1115 snapped_contents_scale = tiling_contents_scale;
1116 snapped_ratio = ratio;
1119 return snapped_contents_scale;
1122 void PictureLayerImpl::RecalculateRasterScales() {
1123 float old_raster_contents_scale = raster_contents_scale_;
1124 float old_raster_page_scale = raster_page_scale_;
1125 float old_raster_source_scale = raster_source_scale_;
1127 raster_device_scale_ = ideal_device_scale_;
1128 raster_page_scale_ = ideal_page_scale_;
1129 raster_source_scale_ = ideal_source_scale_;
1130 raster_contents_scale_ = ideal_contents_scale_;
1132 // If we're not animating, or leaving an animation, and the
1133 // ideal_source_scale_ changes, then things are unpredictable, and we fix
1134 // the raster_source_scale_ in place.
1135 if (old_raster_source_scale &&
1136 !draw_properties().screen_space_transform_is_animating &&
1137 !was_screen_space_transform_animating_ &&
1138 old_raster_source_scale != ideal_source_scale_)
1139 raster_source_scale_is_fixed_ = true;
1141 // TODO(danakj): Adjust raster source scale closer to ideal source scale at
1142 // a throttled rate. Possibly make use of invalidation_.IsEmpty() on pending
1143 // tree. This will allow CSS scale changes to get re-rastered at an
1144 // appropriate rate.
1145 if (raster_source_scale_is_fixed_) {
1146 raster_contents_scale_ /= raster_source_scale_;
1147 raster_source_scale_ = 1.f;
1150 // During pinch we completely ignore the current ideal scale, and just use
1151 // a multiple of the previous scale.
1152 // TODO(danakj): This seems crazy, we should use the current ideal, no?
1153 bool is_pinching = layer_tree_impl()->PinchGestureActive();
1154 if (is_pinching && old_raster_contents_scale) {
1155 // See ShouldAdjustRasterScale:
1156 // - When zooming out, preemptively create new tiling at lower resolution.
1157 // - When zooming in, approximate ideal using multiple of kMaxScaleRatio.
1158 bool zooming_out = old_raster_page_scale > ideal_page_scale_;
1159 float desired_contents_scale =
1160 zooming_out ? old_raster_contents_scale / kMaxScaleRatioDuringPinch
1161 : old_raster_contents_scale * kMaxScaleRatioDuringPinch;
1162 raster_contents_scale_ = SnappedContentsScale(desired_contents_scale);
1163 raster_page_scale_ =
1164 raster_contents_scale_ / raster_device_scale_ / raster_source_scale_;
1167 raster_contents_scale_ =
1168 std::max(raster_contents_scale_, MinimumContentsScale());
1170 // If we're not re-rasterizing during animation, rasterize at the maximum
1171 // scale that will occur during the animation, if the maximum scale is
1172 // known. However, to avoid excessive memory use, don't rasterize at a scale
1173 // at which this layer would become larger than the viewport.
1174 if (draw_properties().screen_space_transform_is_animating &&
1175 !ShouldAdjustRasterScaleDuringScaleAnimations()) {
1176 bool can_raster_at_maximum_scale = false;
1177 if (draw_properties().maximum_animation_contents_scale > 0.f) {
1178 gfx::Size bounds_at_maximum_scale = gfx::ToCeiledSize(gfx::ScaleSize(
1179 bounds(), draw_properties().maximum_animation_contents_scale));
1180 if (bounds_at_maximum_scale.GetArea() <=
1181 layer_tree_impl()->device_viewport_size().GetArea())
1182 can_raster_at_maximum_scale = true;
1184 if (can_raster_at_maximum_scale) {
1185 raster_contents_scale_ =
1186 std::max(raster_contents_scale_,
1187 draw_properties().maximum_animation_contents_scale);
1188 } else {
1189 raster_contents_scale_ =
1190 std::max(raster_contents_scale_,
1191 1.f * ideal_page_scale_ * ideal_device_scale_);
1195 // If this layer would only create one tile at this content scale,
1196 // don't create a low res tiling.
1197 gfx::Size content_bounds =
1198 gfx::ToCeiledSize(gfx::ScaleSize(bounds(), raster_contents_scale_));
1199 gfx::Size tile_size = CalculateTileSize(content_bounds);
1200 if (tile_size.width() >= content_bounds.width() &&
1201 tile_size.height() >= content_bounds.height()) {
1202 low_res_raster_contents_scale_ = raster_contents_scale_;
1203 return;
1206 float low_res_factor =
1207 layer_tree_impl()->settings().low_res_contents_scale_factor;
1208 low_res_raster_contents_scale_ = std::max(
1209 raster_contents_scale_ * low_res_factor,
1210 MinimumContentsScale());
1213 void PictureLayerImpl::CleanUpTilingsOnActiveLayer(
1214 std::vector<PictureLayerTiling*> used_tilings) {
1215 DCHECK(layer_tree_impl()->IsActiveTree());
1216 if (tilings_->num_tilings() == 0)
1217 return;
1219 float min_acceptable_high_res_scale = std::min(
1220 raster_contents_scale_, ideal_contents_scale_);
1221 float max_acceptable_high_res_scale = std::max(
1222 raster_contents_scale_, ideal_contents_scale_);
1223 float twin_low_res_scale = 0.f;
1225 PictureLayerImpl* twin = twin_layer_;
1226 if (twin && twin->CanHaveTilings()) {
1227 min_acceptable_high_res_scale = std::min(
1228 min_acceptable_high_res_scale,
1229 std::min(twin->raster_contents_scale_, twin->ideal_contents_scale_));
1230 max_acceptable_high_res_scale = std::max(
1231 max_acceptable_high_res_scale,
1232 std::max(twin->raster_contents_scale_, twin->ideal_contents_scale_));
1234 for (size_t i = 0; i < twin->tilings_->num_tilings(); ++i) {
1235 PictureLayerTiling* tiling = twin->tilings_->tiling_at(i);
1236 if (tiling->resolution() == LOW_RESOLUTION)
1237 twin_low_res_scale = tiling->contents_scale();
1241 std::vector<PictureLayerTiling*> to_remove;
1242 for (size_t i = 0; i < tilings_->num_tilings(); ++i) {
1243 PictureLayerTiling* tiling = tilings_->tiling_at(i);
1245 // Keep multiple high resolution tilings even if not used to help
1246 // activate earlier at non-ideal resolutions.
1247 if (tiling->contents_scale() >= min_acceptable_high_res_scale &&
1248 tiling->contents_scale() <= max_acceptable_high_res_scale)
1249 continue;
1251 // Keep low resolution tilings, if the layer should have them.
1252 if (layer_tree_impl()->create_low_res_tiling()) {
1253 if (tiling->resolution() == LOW_RESOLUTION ||
1254 tiling->contents_scale() == twin_low_res_scale)
1255 continue;
1258 // Don't remove tilings that are being used (and thus would cause a flash.)
1259 if (std::find(used_tilings.begin(), used_tilings.end(), tiling) !=
1260 used_tilings.end())
1261 continue;
1263 to_remove.push_back(tiling);
1266 if (to_remove.empty())
1267 return;
1269 PictureLayerImpl* recycled_twin = GetRecycledTwinLayer();
1270 // Remove tilings on this tree and the twin tree.
1271 for (size_t i = 0; i < to_remove.size(); ++i) {
1272 const PictureLayerTiling* twin_tiling = GetTwinTiling(to_remove[i]);
1273 // Only remove tilings from the twin layer if they have
1274 // NON_IDEAL_RESOLUTION.
1275 if (twin_tiling && twin_tiling->resolution() == NON_IDEAL_RESOLUTION)
1276 twin->RemoveTiling(to_remove[i]->contents_scale());
1277 // Remove the tiling from the recycle tree. Note that we ignore resolution,
1278 // since we don't need to maintain high/low res on the recycle tree.
1279 if (recycled_twin)
1280 recycled_twin->RemoveTiling(to_remove[i]->contents_scale());
1281 // TODO(enne): temporary sanity CHECK for http://crbug.com/358350
1282 CHECK_NE(HIGH_RESOLUTION, to_remove[i]->resolution());
1283 tilings_->Remove(to_remove[i]);
1286 DCHECK_GT(tilings_->num_tilings(), 0u);
1287 SanityCheckTilingState();
1290 float PictureLayerImpl::MinimumContentsScale() const {
1291 float setting_min = layer_tree_impl()->settings().minimum_contents_scale;
1293 // If the contents scale is less than 1 / width (also for height),
1294 // then it will end up having less than one pixel of content in that
1295 // dimension. Bump the minimum contents scale up in this case to prevent
1296 // this from happening.
1297 int min_dimension = std::min(bounds().width(), bounds().height());
1298 if (!min_dimension)
1299 return setting_min;
1301 return std::max(1.f / min_dimension, setting_min);
1304 void PictureLayerImpl::ResetRasterScale() {
1305 raster_page_scale_ = 0.f;
1306 raster_device_scale_ = 0.f;
1307 raster_source_scale_ = 0.f;
1308 raster_contents_scale_ = 0.f;
1309 low_res_raster_contents_scale_ = 0.f;
1310 raster_source_scale_is_fixed_ = false;
1312 // When raster scales aren't valid, don't update tile priorities until
1313 // this layer has been updated via UpdateDrawProperties.
1314 should_update_tile_priorities_ = false;
1317 bool PictureLayerImpl::CanHaveTilings() const {
1318 if (!DrawsContent())
1319 return false;
1320 if (!pile_->HasRecordings())
1321 return false;
1322 return true;
1325 bool PictureLayerImpl::CanHaveTilingWithScale(float contents_scale) const {
1326 if (!CanHaveTilings())
1327 return false;
1328 if (contents_scale < MinimumContentsScale())
1329 return false;
1330 return true;
1333 void PictureLayerImpl::SanityCheckTilingState() const {
1334 #if DCHECK_IS_ON
1335 // Recycle tree doesn't have any restrictions.
1336 if (layer_tree_impl()->IsRecycleTree())
1337 return;
1339 if (!CanHaveTilings()) {
1340 DCHECK_EQ(0u, tilings_->num_tilings());
1341 return;
1343 if (tilings_->num_tilings() == 0)
1344 return;
1346 // MarkVisibleResourcesAsRequired depends on having exactly 1 high res
1347 // tiling to mark its tiles as being required for activation.
1348 DCHECK_EQ(1, tilings_->NumHighResTilings());
1349 #endif
1352 bool PictureLayerImpl::ShouldAdjustRasterScaleDuringScaleAnimations() const {
1353 if (!layer_tree_impl()->use_gpu_rasterization())
1354 return false;
1356 // Re-rastering text at different scales using GPU rasterization causes
1357 // texture uploads for glyphs at each scale (see crbug.com/366225). To
1358 // workaround this performance issue, we don't re-rasterize layers with
1359 // text during scale animations.
1360 // TODO(ajuma): Remove this workaround once text can be efficiently
1361 // re-rastered at different scales (e.g. by using distance-field fonts).
1362 if (pile_->has_text())
1363 return false;
1365 return true;
1368 float PictureLayerImpl::MaximumTilingContentsScale() const {
1369 float max_contents_scale = MinimumContentsScale();
1370 for (size_t i = 0; i < tilings_->num_tilings(); ++i) {
1371 const PictureLayerTiling* tiling = tilings_->tiling_at(i);
1372 max_contents_scale = std::max(max_contents_scale, tiling->contents_scale());
1374 return max_contents_scale;
1377 void PictureLayerImpl::UpdateIdealScales() {
1378 DCHECK(CanHaveTilings());
1380 float min_contents_scale = MinimumContentsScale();
1381 DCHECK_GT(min_contents_scale, 0.f);
1382 float min_page_scale = layer_tree_impl()->min_page_scale_factor();
1383 DCHECK_GT(min_page_scale, 0.f);
1384 float min_device_scale = 1.f;
1385 float min_source_scale =
1386 min_contents_scale / min_page_scale / min_device_scale;
1388 float ideal_page_scale = draw_properties().page_scale_factor;
1389 float ideal_device_scale = draw_properties().device_scale_factor;
1390 float ideal_source_scale = draw_properties().ideal_contents_scale /
1391 ideal_page_scale / ideal_device_scale;
1392 ideal_contents_scale_ =
1393 std::max(draw_properties().ideal_contents_scale, min_contents_scale);
1394 ideal_page_scale_ = draw_properties().page_scale_factor;
1395 ideal_device_scale_ = draw_properties().device_scale_factor;
1396 ideal_source_scale_ = std::max(ideal_source_scale, min_source_scale);
1399 void PictureLayerImpl::GetDebugBorderProperties(
1400 SkColor* color,
1401 float* width) const {
1402 *color = DebugColors::TiledContentLayerBorderColor();
1403 *width = DebugColors::TiledContentLayerBorderWidth(layer_tree_impl());
1406 void PictureLayerImpl::GetAllTilesForTracing(
1407 std::set<const Tile*>* tiles) const {
1408 if (!tilings_)
1409 return;
1411 for (size_t i = 0; i < tilings_->num_tilings(); ++i)
1412 tilings_->tiling_at(i)->GetAllTilesForTracing(tiles);
1415 void PictureLayerImpl::AsValueInto(base::debug::TracedValue* state) const {
1416 const_cast<PictureLayerImpl*>(this)->DoPostCommitInitializationIfNeeded();
1417 LayerImpl::AsValueInto(state);
1418 state->SetDouble("ideal_contents_scale", ideal_contents_scale_);
1419 state->SetDouble("geometry_contents_scale", MaximumTilingContentsScale());
1420 state->BeginArray("tilings");
1421 tilings_->AsValueInto(state);
1422 state->EndArray();
1424 state->BeginArray("pictures");
1425 pile_->AsValueInto(state);
1426 state->EndArray();
1428 state->BeginArray("invalidation");
1429 invalidation_.AsValueInto(state);
1430 state->EndArray();
1432 state->BeginArray("coverage_tiles");
1433 for (PictureLayerTilingSet::CoverageIterator iter(tilings_.get(),
1434 contents_scale_x(),
1435 gfx::Rect(content_bounds()),
1436 ideal_contents_scale_);
1437 iter;
1438 ++iter) {
1439 state->BeginDictionary();
1441 state->BeginArray("geometry_rect");
1442 MathUtil::AddToTracedValue(iter.geometry_rect(), state);
1443 state->EndArray();
1445 if (*iter)
1446 TracedValue::SetIDRef(*iter, state, "tile");
1448 state->EndDictionary();
1450 state->EndArray();
1453 size_t PictureLayerImpl::GPUMemoryUsageInBytes() const {
1454 const_cast<PictureLayerImpl*>(this)->DoPostCommitInitializationIfNeeded();
1455 return tilings_->GPUMemoryUsageInBytes();
1458 void PictureLayerImpl::RunMicroBenchmark(MicroBenchmarkImpl* benchmark) {
1459 benchmark->RunOnLayer(this);
1462 WhichTree PictureLayerImpl::GetTree() const {
1463 return layer_tree_impl()->IsActiveTree() ? ACTIVE_TREE : PENDING_TREE;
1466 bool PictureLayerImpl::IsOnActiveOrPendingTree() const {
1467 return !layer_tree_impl()->IsRecycleTree();
1470 bool PictureLayerImpl::HasValidTilePriorities() const {
1471 return IsOnActiveOrPendingTree() && IsDrawnRenderSurfaceLayerListMember();
1474 bool PictureLayerImpl::AllTilesRequiredForActivationAreReadyToDraw() const {
1475 if (!layer_tree_impl()->IsPendingTree())
1476 return true;
1478 if (!HasValidTilePriorities())
1479 return true;
1481 if (!tilings_)
1482 return true;
1484 if (visible_content_rect().IsEmpty())
1485 return true;
1487 for (size_t i = 0; i < tilings_->num_tilings(); ++i) {
1488 PictureLayerTiling* tiling = tilings_->tiling_at(i);
1489 if (tiling->resolution() != HIGH_RESOLUTION &&
1490 tiling->resolution() != LOW_RESOLUTION)
1491 continue;
1493 gfx::Rect rect(visible_content_rect());
1494 for (PictureLayerTiling::CoverageIterator iter(
1495 tiling, contents_scale_x(), rect);
1496 iter;
1497 ++iter) {
1498 const Tile* tile = *iter;
1499 // A null tile (i.e. missing recording) can just be skipped.
1500 if (!tile)
1501 continue;
1503 if (tile->required_for_activation() && !tile->IsReadyToDraw())
1504 return false;
1508 return true;
1511 PictureLayerImpl::LayerRasterTileIterator::LayerRasterTileIterator()
1512 : layer_(NULL), current_stage_(arraysize(stages_)) {
1515 PictureLayerImpl::LayerRasterTileIterator::LayerRasterTileIterator(
1516 PictureLayerImpl* layer,
1517 bool prioritize_low_res)
1518 : layer_(layer), current_stage_(0) {
1519 DCHECK(layer_);
1521 // Early out if the layer has no tilings.
1522 if (!layer_->tilings_ || !layer_->tilings_->num_tilings()) {
1523 current_stage_ = arraysize(stages_);
1524 return;
1527 // Tiles without valid priority are treated as having lowest priority and
1528 // never considered for raster.
1529 if (!layer_->HasValidTilePriorities()) {
1530 current_stage_ = arraysize(stages_);
1531 return;
1534 WhichTree tree = layer_->GetTree();
1536 // Find high and low res tilings and initialize the iterators.
1537 for (size_t i = 0; i < layer_->tilings_->num_tilings(); ++i) {
1538 PictureLayerTiling* tiling = layer_->tilings_->tiling_at(i);
1539 if (tiling->resolution() == HIGH_RESOLUTION) {
1540 iterators_[HIGH_RES] =
1541 PictureLayerTiling::TilingRasterTileIterator(tiling, tree);
1544 if (tiling->resolution() == LOW_RESOLUTION) {
1545 iterators_[LOW_RES] =
1546 PictureLayerTiling::TilingRasterTileIterator(tiling, tree);
1550 if (prioritize_low_res) {
1551 stages_[0].iterator_type = LOW_RES;
1552 stages_[0].tile_type = TilePriority::NOW;
1554 stages_[1].iterator_type = HIGH_RES;
1555 stages_[1].tile_type = TilePriority::NOW;
1556 } else {
1557 stages_[0].iterator_type = HIGH_RES;
1558 stages_[0].tile_type = TilePriority::NOW;
1560 stages_[1].iterator_type = LOW_RES;
1561 stages_[1].tile_type = TilePriority::NOW;
1564 stages_[2].iterator_type = HIGH_RES;
1565 stages_[2].tile_type = TilePriority::SOON;
1567 stages_[3].iterator_type = HIGH_RES;
1568 stages_[3].tile_type = TilePriority::EVENTUALLY;
1570 IteratorType index = stages_[current_stage_].iterator_type;
1571 TilePriority::PriorityBin tile_type = stages_[current_stage_].tile_type;
1572 if (!iterators_[index] || iterators_[index].get_type() != tile_type)
1573 ++(*this);
1576 PictureLayerImpl::LayerRasterTileIterator::~LayerRasterTileIterator() {}
1578 PictureLayerImpl::LayerRasterTileIterator::operator bool() const {
1579 return current_stage_ < arraysize(stages_);
1582 PictureLayerImpl::LayerRasterTileIterator&
1583 PictureLayerImpl::LayerRasterTileIterator::
1584 operator++() {
1585 IteratorType index = stages_[current_stage_].iterator_type;
1586 TilePriority::PriorityBin tile_type = stages_[current_stage_].tile_type;
1588 // First advance the iterator.
1589 if (iterators_[index])
1590 ++iterators_[index];
1592 if (iterators_[index] && iterators_[index].get_type() == tile_type)
1593 return *this;
1595 // Next, advance the stage.
1596 ++current_stage_;
1597 while (current_stage_ < arraysize(stages_)) {
1598 index = stages_[current_stage_].iterator_type;
1599 tile_type = stages_[current_stage_].tile_type;
1601 if (iterators_[index] && iterators_[index].get_type() == tile_type)
1602 break;
1603 ++current_stage_;
1605 return *this;
1608 Tile* PictureLayerImpl::LayerRasterTileIterator::operator*() {
1609 DCHECK(*this);
1611 IteratorType index = stages_[current_stage_].iterator_type;
1612 DCHECK(iterators_[index]);
1613 DCHECK(iterators_[index].get_type() == stages_[current_stage_].tile_type);
1615 return *iterators_[index];
1618 const Tile* PictureLayerImpl::LayerRasterTileIterator::operator*() const {
1619 DCHECK(*this);
1621 IteratorType index = stages_[current_stage_].iterator_type;
1622 DCHECK(iterators_[index]);
1623 DCHECK(iterators_[index].get_type() == stages_[current_stage_].tile_type);
1625 return *iterators_[index];
1628 PictureLayerImpl::LayerEvictionTileIterator::LayerEvictionTileIterator()
1629 : layer_(NULL),
1630 tree_priority_(SAME_PRIORITY_FOR_BOTH_TREES),
1631 current_category_(PictureLayerTiling::EVENTUALLY),
1632 current_tiling_range_type_(PictureLayerTilingSet::HIGHER_THAN_HIGH_RES),
1633 current_tiling_(0u) {
1636 PictureLayerImpl::LayerEvictionTileIterator::LayerEvictionTileIterator(
1637 PictureLayerImpl* layer,
1638 TreePriority tree_priority)
1639 : layer_(layer),
1640 tree_priority_(tree_priority),
1641 current_category_(PictureLayerTiling::EVENTUALLY),
1642 current_tiling_range_type_(PictureLayerTilingSet::HIGHER_THAN_HIGH_RES),
1643 current_tiling_(CurrentTilingRange().start - 1u) {
1644 // TODO(vmpstr): Once tile priorities are determined by the iterators, ensure
1645 // that layers that don't have valid tile priorities have lowest priorities so
1646 // they evict their tiles first (crbug.com/381704)
1647 DCHECK(layer_->tilings_);
1648 do {
1649 if (!AdvanceToNextTiling())
1650 break;
1652 current_iterator_ = PictureLayerTiling::TilingEvictionTileIterator(
1653 layer_->tilings_->tiling_at(CurrentTilingIndex()),
1654 tree_priority,
1655 current_category_);
1656 } while (!current_iterator_);
1659 PictureLayerImpl::LayerEvictionTileIterator::~LayerEvictionTileIterator() {
1662 Tile* PictureLayerImpl::LayerEvictionTileIterator::operator*() {
1663 DCHECK(*this);
1664 return *current_iterator_;
1667 const Tile* PictureLayerImpl::LayerEvictionTileIterator::operator*() const {
1668 DCHECK(*this);
1669 return *current_iterator_;
1672 PictureLayerImpl::LayerEvictionTileIterator&
1673 PictureLayerImpl::LayerEvictionTileIterator::
1674 operator++() {
1675 DCHECK(*this);
1676 ++current_iterator_;
1677 while (!current_iterator_) {
1678 if (!AdvanceToNextTiling())
1679 break;
1681 current_iterator_ = PictureLayerTiling::TilingEvictionTileIterator(
1682 layer_->tilings_->tiling_at(CurrentTilingIndex()),
1683 tree_priority_,
1684 current_category_);
1686 return *this;
1689 PictureLayerImpl::LayerEvictionTileIterator::operator bool() const {
1690 return !!current_iterator_;
1693 bool PictureLayerImpl::LayerEvictionTileIterator::AdvanceToNextCategory() {
1694 switch (current_category_) {
1695 case PictureLayerTiling::EVENTUALLY:
1696 current_category_ =
1697 PictureLayerTiling::EVENTUALLY_AND_REQUIRED_FOR_ACTIVATION;
1698 return true;
1699 case PictureLayerTiling::EVENTUALLY_AND_REQUIRED_FOR_ACTIVATION:
1700 current_category_ = PictureLayerTiling::SOON;
1701 return true;
1702 case PictureLayerTiling::SOON:
1703 current_category_ = PictureLayerTiling::SOON_AND_REQUIRED_FOR_ACTIVATION;
1704 return true;
1705 case PictureLayerTiling::SOON_AND_REQUIRED_FOR_ACTIVATION:
1706 current_category_ = PictureLayerTiling::NOW;
1707 return true;
1708 case PictureLayerTiling::NOW:
1709 current_category_ = PictureLayerTiling::NOW_AND_REQUIRED_FOR_ACTIVATION;
1710 return true;
1711 case PictureLayerTiling::NOW_AND_REQUIRED_FOR_ACTIVATION:
1712 return false;
1714 NOTREACHED();
1715 return false;
1718 bool
1719 PictureLayerImpl::LayerEvictionTileIterator::AdvanceToNextTilingRangeType() {
1720 switch (current_tiling_range_type_) {
1721 case PictureLayerTilingSet::HIGHER_THAN_HIGH_RES:
1722 current_tiling_range_type_ = PictureLayerTilingSet::LOWER_THAN_LOW_RES;
1723 return true;
1724 case PictureLayerTilingSet::LOWER_THAN_LOW_RES:
1725 current_tiling_range_type_ =
1726 PictureLayerTilingSet::BETWEEN_HIGH_AND_LOW_RES;
1727 return true;
1728 case PictureLayerTilingSet::BETWEEN_HIGH_AND_LOW_RES:
1729 current_tiling_range_type_ = PictureLayerTilingSet::LOW_RES;
1730 return true;
1731 case PictureLayerTilingSet::LOW_RES:
1732 current_tiling_range_type_ = PictureLayerTilingSet::HIGH_RES;
1733 return true;
1734 case PictureLayerTilingSet::HIGH_RES:
1735 if (!AdvanceToNextCategory())
1736 return false;
1738 current_tiling_range_type_ = PictureLayerTilingSet::HIGHER_THAN_HIGH_RES;
1739 return true;
1741 NOTREACHED();
1742 return false;
1745 bool PictureLayerImpl::LayerEvictionTileIterator::AdvanceToNextTiling() {
1746 DCHECK_NE(current_tiling_, CurrentTilingRange().end);
1747 ++current_tiling_;
1748 while (current_tiling_ == CurrentTilingRange().end) {
1749 if (!AdvanceToNextTilingRangeType())
1750 return false;
1752 current_tiling_ = CurrentTilingRange().start;
1754 return true;
1757 PictureLayerTilingSet::TilingRange
1758 PictureLayerImpl::LayerEvictionTileIterator::CurrentTilingRange() const {
1759 return layer_->tilings_->GetTilingRange(current_tiling_range_type_);
1762 size_t PictureLayerImpl::LayerEvictionTileIterator::CurrentTilingIndex() const {
1763 DCHECK_NE(current_tiling_, CurrentTilingRange().end);
1764 switch (current_tiling_range_type_) {
1765 case PictureLayerTilingSet::HIGHER_THAN_HIGH_RES:
1766 case PictureLayerTilingSet::LOW_RES:
1767 case PictureLayerTilingSet::HIGH_RES:
1768 return current_tiling_;
1769 // Tilings in the following ranges are accessed in reverse order.
1770 case PictureLayerTilingSet::BETWEEN_HIGH_AND_LOW_RES:
1771 case PictureLayerTilingSet::LOWER_THAN_LOW_RES: {
1772 PictureLayerTilingSet::TilingRange tiling_range = CurrentTilingRange();
1773 size_t current_tiling_range_offset = current_tiling_ - tiling_range.start;
1774 return tiling_range.end - 1 - current_tiling_range_offset;
1777 NOTREACHED();
1778 return 0;
1781 } // namespace cc