-
Notifications
You must be signed in to change notification settings - Fork 54
/
picture.rs
3462 lines (3070 loc) · 138 KB
/
picture.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use api::{MixBlendMode, PipelineId, PremultipliedColorF};
use api::{PropertyBinding, PropertyBindingId};
use api::{DebugFlags, RasterSpace, ColorF, ImageKey, ClipMode};
use api::units::*;
use crate::box_shadow::{BLUR_SAMPLE_SCALE};
use crate::clip::{ClipChainId, ClipChainNode, ClipItem, ClipStore, ClipDataStore, ClipChainStack};
use crate::clip_scroll_tree::{ROOT_SPATIAL_NODE_INDEX,
ClipScrollTree, CoordinateSystemId, CoordinateSpaceMapping, SpatialNodeIndex, VisibleFace
};
use crate::debug_colors;
use euclid::{size2, vec3, TypedPoint2D, TypedScale, TypedSize2D, Vector2D};
use euclid::approxeq::ApproxEq;
use crate::frame_builder::{FrameVisibilityContext, FrameVisibilityState};
use crate::intern::ItemUid;
use crate::internal_types::{FastHashMap, FastHashSet, PlaneSplitter, Filter};
use crate::frame_builder::{FrameBuildingContext, FrameBuildingState, PictureState, PictureContext};
use crate::gpu_cache::{GpuCache, GpuCacheAddress, GpuCacheHandle};
use crate::gpu_types::UvRectKind;
use plane_split::{Clipper, Polygon, Splitter};
use crate::prim_store::SpaceMapper;
use crate::prim_store::{PictureIndex, PrimitiveInstance, PrimitiveInstanceKind};
use crate::prim_store::{get_raster_rects, PrimitiveScratchBuffer, VectorKey, PointKey};
use crate::prim_store::{OpacityBindingStorage, ImageInstanceStorage, OpacityBindingIndex, RectangleKey};
use crate::print_tree::PrintTreePrinter;
use crate::render_backend::DataStores;
use crate::render_task::{ClearMode, RenderTask, TileBlit};
use crate::render_task::{RenderTaskId, RenderTaskLocation, BlurTaskCache};
use crate::resource_cache::ResourceCache;
use crate::scene::SceneProperties;
use crate::scene_builder::Interners;
use smallvec::SmallVec;
use std::{mem, u16};
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::texture_cache::TextureCacheHandle;
use crate::tiling::RenderTargetKind;
use crate::util::{ComparableVec, TransformedRectKind, MatrixHelpers, MaxRect, scale_factors};
use crate::filterdata::{FilterDataHandle};
/*
A picture represents a dynamically rendered image. It consists of:
* A number of primitives that are drawn onto the picture.
* A composite operation describing how to composite this
picture into its parent.
* A configuration describing how to draw the primitives on
this picture (e.g. in screen space or local space).
*/
/// Information about a picture that is pushed / popped on the
/// PictureUpdateState during picture traversal pass.
struct PictureInfo {
/// The spatial node for this picture.
_spatial_node_index: SpatialNodeIndex,
}
/// Stores a list of cached picture tiles that are retained
/// between new scenes.
#[cfg_attr(feature = "capture", derive(Serialize))]
pub struct RetainedTiles {
/// The tiles retained between display lists.
#[cfg_attr(feature = "capture", serde(skip))] //TODO
pub tiles: Vec<Tile>,
/// List of reference primitives that we will compare
/// to try and correlate the positioning of items
/// between display lists.
pub ref_prims: FastHashMap<ItemUid, WorldPoint>,
}
impl RetainedTiles {
pub fn new() -> Self {
RetainedTiles {
tiles: Vec::new(),
ref_prims: FastHashMap::default(),
}
}
/// Merge items from one retained tiles into another.
pub fn merge(&mut self, other: RetainedTiles) {
assert!(self.tiles.is_empty() || other.tiles.is_empty());
self.tiles.extend(other.tiles);
self.ref_prims.extend(other.ref_prims);
}
}
/// Unit for tile coordinates.
#[derive(Hash, Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct TileCoordinate;
// Geometry types for tile coordinates.
pub type TileOffset = TypedPoint2D<i32, TileCoordinate>;
pub type TileSize = TypedSize2D<i32, TileCoordinate>;
pub struct TileIndex(pub usize);
/// The size in device pixels of a cached tile. The currently chosen
/// size is arbitrary. We should do some profiling to find the best
/// size for real world pages.
///
/// Note that we use a separate, smaller size during wrench testing, so that
/// we get tighter dirty rects and can do more meaningful invalidation
/// tests.
const TILE_SIZE_WIDTH: i32 = 1024;
const TILE_SIZE_HEIGHT: i32 = 256;
const TILE_SIZE_TESTING: i32 = 64;
const FRAMES_BEFORE_PICTURE_CACHING: usize = 2;
const MAX_DIRTY_RECTS: usize = 3;
/// The maximum size per axis of a surface,
/// in WorldPixel coordinates.
const MAX_SURFACE_SIZE: f32 = 4096.0;
/// The maximum number of primitives to look for in a display
/// list, trying to find unique primitives.
const MAX_PRIMS_TO_SEARCH: usize = 128;
/// Used to get unique tile IDs, even when the tile cache is
/// destroyed between display lists / scenes.
static NEXT_TILE_ID: AtomicUsize = AtomicUsize::new(0);
fn clamp(value: i32, low: i32, high: i32) -> i32 {
value.max(low).min(high)
}
/// Information about the state of an opacity binding.
#[derive(Debug)]
pub struct OpacityBindingInfo {
/// The current value retrieved from dynamic scene properties.
value: f32,
/// True if it was changed (or is new) since the last frame build.
changed: bool,
}
/// Information stored in a tile descriptor for an opacity binding.
#[derive(Debug, PartialEq, Clone)]
pub enum OpacityBinding {
Value(f32),
Binding(PropertyBindingId),
}
impl From<PropertyBinding<f32>> for OpacityBinding {
fn from(binding: PropertyBinding<f32>) -> OpacityBinding {
match binding {
PropertyBinding::Binding(key, _) => OpacityBinding::Binding(key.id),
PropertyBinding::Value(value) => OpacityBinding::Value(value),
}
}
}
/// A stable ID for a given tile, to help debugging.
#[derive(Debug, Copy, Clone, PartialEq)]
struct TileId(usize);
/// Information about a cached tile.
#[derive(Debug)]
pub struct Tile {
/// The current world rect of thie tile.
world_rect: WorldRect,
/// The current local rect of this tile.
pub local_rect: LayoutRect,
/// The currently visible rect within this tile, updated per frame.
/// If None, this tile is not currently visible.
visible_rect: Option<WorldRect>,
/// The currently valid rect of the tile, used to invalidate
/// tiles that were only partially drawn.
valid_rect: WorldRect,
/// Uniquely describes the content of this tile, in a way that can be
/// (reasonably) efficiently hashed and compared.
descriptor: TileDescriptor,
/// Handle to the cached texture for this tile.
pub handle: TextureCacheHandle,
/// If true, this tile is marked valid, and the existing texture
/// cache handle can be used. Tiles are invalidated during the
/// build_dirty_regions method.
is_valid: bool,
/// If true, the content on this tile is the same as last frame.
is_same_content: bool,
/// The number of frames this tile has had the same content.
same_frames: usize,
/// The tile id is stable between display lists and / or frames,
/// if the tile is retained. Useful for debugging tile evictions.
id: TileId,
/// The set of transforms that affect primitives on this tile we
/// care about. Stored as a set here, and then collected, sorted
/// and converted to transform key values during post_update.
transforms: FastHashSet<SpatialNodeIndex>,
/// A list of potentially important clips. We can't know if
/// they were important or can be discarded until we know the
/// tile cache bounding rect.
potential_clips: FastHashMap<RectangleKey, SpatialNodeIndex>,
/// If true, this tile should still be considered as part of
/// the dirty rect calculations.
consider_for_dirty_rect: bool,
}
impl Tile {
/// Construct a new, invalid tile.
fn new(
id: TileId,
) -> Self {
Tile {
local_rect: LayoutRect::zero(),
world_rect: WorldRect::zero(),
visible_rect: None,
valid_rect: WorldRect::zero(),
handle: TextureCacheHandle::invalid(),
descriptor: TileDescriptor::new(),
is_same_content: false,
is_valid: false,
same_frames: 0,
transforms: FastHashSet::default(),
potential_clips: FastHashMap::default(),
id,
consider_for_dirty_rect: false,
}
}
/// Clear the dependencies for a tile.
fn clear(&mut self) {
self.transforms.clear();
self.descriptor.clear();
self.potential_clips.clear();
}
/// Invalidate a tile based on change in content. This
/// muct be called even if the tile is not currently
/// visible on screen. We might be able to improve this
/// later by changing how ComparableVec is used.
fn update_content_validity(&mut self) {
// Check if the contents of the primitives, clips, and
// other dependencies are the same.
self.is_same_content &= self.descriptor.is_same_content();
self.is_valid &= self.is_same_content;
}
/// Update state related to whether a tile has a valid rect that
/// covers the required visible part of the tile.
fn update_rect_validity(&mut self, tile_bounding_rect: &WorldRect) {
// The tile is only valid if:
// - The content is the same *and*
// - The valid part of the tile includes the needed part.
self.is_valid &= self.valid_rect.contains_rect(tile_bounding_rect);
// Update count of how many times this tile has had the same content.
if !self.is_same_content {
self.same_frames = 0;
}
self.same_frames += 1;
}
}
/// Defines a key that uniquely identifies a primitive instance.
#[derive(Debug, Clone, PartialEq)]
pub struct PrimitiveDescriptor {
/// Uniquely identifies the content of the primitive template.
prim_uid: ItemUid,
/// The origin in world space of this primitive.
origin: WorldPoint,
/// The first clip in the clip_uids array of clips that affect this tile.
first_clip: u16,
/// The number of clips that affect this primitive instance.
clip_count: u16,
/// The combined local clips + prim rect for this primitive.
world_culling_rect: WorldRect,
}
/// Uniquely describes the content of this tile, in a way that can be
/// (reasonably) efficiently hashed and compared.
#[derive(Debug)]
pub struct TileDescriptor {
/// List of primitive instance unique identifiers. The uid is guaranteed
/// to uniquely describe the content of the primitive template, while
/// the other parameters describe the clip chain and instance params.
prims: ComparableVec<PrimitiveDescriptor>,
/// List of clip node unique identifiers. The uid is guaranteed
/// to uniquely describe the content of the clip node.
clip_uids: ComparableVec<ItemUid>,
/// List of local offsets of the clip node origins. This
/// ensures that if a clip node is supplied but has a different
/// transform between frames that the tile is invalidated.
clip_vertices: ComparableVec<PointKey>,
/// List of image keys that this tile depends on.
image_keys: ComparableVec<ImageKey>,
/// The set of opacity bindings that this tile depends on.
// TODO(gw): Ugh, get rid of all opacity binding support!
opacity_bindings: ComparableVec<OpacityBinding>,
/// List of the effects of transforms that we care about
/// tracking for this tile.
transforms: ComparableVec<PointKey>,
}
impl TileDescriptor {
fn new() -> Self {
TileDescriptor {
prims: ComparableVec::new(),
clip_uids: ComparableVec::new(),
clip_vertices: ComparableVec::new(),
opacity_bindings: ComparableVec::new(),
image_keys: ComparableVec::new(),
transforms: ComparableVec::new(),
}
}
/// Clear the dependency information for a tile, when the dependencies
/// are being rebuilt.
fn clear(&mut self) {
self.prims.reset();
self.clip_uids.reset();
self.clip_vertices.reset();
self.opacity_bindings.reset();
self.image_keys.reset();
self.transforms.reset();
}
/// Return true if the content of the tile is the same
/// as last frame. This doesn't check validity of the
/// tile based on the currently valid regions.
fn is_same_content(&self) -> bool {
if !self.image_keys.is_valid() {
return false;
}
if !self.opacity_bindings.is_valid() {
return false;
}
if !self.clip_uids.is_valid() {
return false;
}
if !self.clip_vertices.is_valid() {
return false;
}
if !self.prims.is_valid() {
return false;
}
if !self.transforms.is_valid() {
return false;
}
true
}
}
/// Stores both the world and devices rects for a single dirty rect.
#[derive(Debug, Clone)]
pub struct DirtyRegionRect {
pub world_rect: WorldRect,
}
/// Represents the dirty region of a tile cache picture.
#[derive(Debug, Clone)]
pub struct DirtyRegion {
/// The individual dirty rects of this region.
pub dirty_rects: Vec<DirtyRegionRect>,
/// The overall dirty rect, a combination of dirty_rects
pub combined: DirtyRegionRect,
}
impl DirtyRegion {
/// Construct a new dirty region tracker.
pub fn new() -> Self {
DirtyRegion {
dirty_rects: Vec::with_capacity(MAX_DIRTY_RECTS),
combined: DirtyRegionRect {
world_rect: WorldRect::zero(),
},
}
}
/// Reset the dirty regions back to empty
pub fn clear(&mut self) {
self.dirty_rects.clear();
self.combined = DirtyRegionRect {
world_rect: WorldRect::zero(),
}
}
/// Push a dirty rect into this region
pub fn push(
&mut self,
rect: WorldRect,
) {
// Include this in the overall dirty rect
self.combined.world_rect = self.combined.world_rect.union(&rect);
// Store the individual dirty rect.
self.dirty_rects.push(DirtyRegionRect {
world_rect: rect,
});
}
/// Returns true if this region has no dirty rects
pub fn is_empty(&self) -> bool {
self.dirty_rects.is_empty()
}
/// Collapse all dirty rects into a single dirty rect.
pub fn collapse(&mut self) {
self.dirty_rects.clear();
self.dirty_rects.push(self.combined.clone());
}
pub fn inflate(
&self,
inflate_amount: f32,
) -> DirtyRegion {
let mut dirty_rects = Vec::with_capacity(self.dirty_rects.len());
let mut combined = DirtyRegionRect {
world_rect: WorldRect::zero(),
};
for rect in &self.dirty_rects {
let world_rect = rect.world_rect.inflate(inflate_amount, inflate_amount);
combined.world_rect = combined.world_rect.union(&world_rect);
dirty_rects.push(DirtyRegionRect {
world_rect,
});
}
DirtyRegion {
dirty_rects,
combined,
}
}
/// Creates a record of this dirty region for exporting to test infrastructure.
pub fn record(&self) -> RecordedDirtyRegion {
let mut rects: Vec<WorldRect> =
self.dirty_rects.iter().map(|r| r.world_rect.clone()).collect();
rects.sort_unstable_by_key(|r| (r.origin.y as usize, r.origin.x as usize));
RecordedDirtyRegion { rects }
}
}
/// A recorded copy of the dirty region for exporting to test infrastructure.
pub struct RecordedDirtyRegion {
pub rects: Vec<WorldRect>,
}
impl ::std::fmt::Display for RecordedDirtyRegion {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
for r in self.rects.iter() {
let (x, y, w, h) = (r.origin.x, r.origin.y, r.size.width, r.size.height);
write!(f, "[({},{}):{}x{}]", x, y, w, h)?;
}
Ok(())
}
}
impl ::std::fmt::Debug for RecordedDirtyRegion {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::std::fmt::Display::fmt(self, f)
}
}
/// A helper struct to build a (roughly) minimal set of dirty rectangles
/// from a list of individual dirty rectangles. This minimizes the number
/// of scissors rects and batch resubmissions that are needed.
struct DirtyRegionBuilder<'a> {
tiles: &'a mut [Tile],
tile_count: TileSize,
}
impl<'a> DirtyRegionBuilder<'a> {
fn new(
tiles: &'a mut [Tile],
tile_count: TileSize,
) -> Self {
DirtyRegionBuilder {
tiles,
tile_count,
}
}
fn tile_index(&self, x: i32, y: i32) -> usize {
(y * self.tile_count.width + x) as usize
}
fn is_dirty(&self, x: i32, y: i32) -> bool {
if x == self.tile_count.width || y == self.tile_count.height {
return false;
}
self.get_tile(x, y).consider_for_dirty_rect
}
fn get_tile(&self, x: i32, y: i32) -> &Tile {
&self.tiles[self.tile_index(x, y)]
}
fn get_tile_mut(&mut self, x: i32, y: i32) -> &mut Tile {
&mut self.tiles[self.tile_index(x, y)]
}
/// Return true if the entire column is dirty
fn column_is_dirty(&self, x: i32, y0: i32, y1: i32) -> bool {
for y in y0 .. y1 {
if !self.is_dirty(x, y) {
return false;
}
}
true
}
/// Push a dirty rect into the final region list.
fn push_dirty_rect(
&mut self,
x0: i32,
y0: i32,
x1: i32,
y1: i32,
dirty_region: &mut DirtyRegion,
) {
// Construct the overall dirty rect by combining the visible
// parts of the dirty rects that were combined.
let mut dirty_world_rect = WorldRect::zero();
for y in y0 .. y1 {
for x in x0 .. x1 {
let tile = self.get_tile_mut(x, y);
tile.consider_for_dirty_rect = false;
if let Some(visible_rect) = tile.visible_rect {
dirty_world_rect = dirty_world_rect.union(&visible_rect);
}
}
}
dirty_region.push(dirty_world_rect);
}
/// Simple sweep through the tile grid to try and coalesce individual
/// dirty rects into a smaller number of larger dirty rectangles.
fn build(&mut self, dirty_region: &mut DirtyRegion) {
for x0 in 0 .. self.tile_count.width {
for y0 in 0 .. self.tile_count.height {
let mut y1 = y0;
while self.is_dirty(x0, y1) {
y1 += 1;
}
if y1 > y0 {
let mut x1 = x0;
while self.column_is_dirty(x1, y0, y1) {
x1 += 1;
}
self.push_dirty_rect(x0, y0, x1, y1, dirty_region);
}
}
}
}
}
/// Represents a cache of tiles that make up a picture primitives.
pub struct TileCache {
/// The positioning node for this tile cache.
spatial_node_index: SpatialNodeIndex,
/// List of tiles present in this picture (stored as a 2D array)
pub tiles: Vec<Tile>,
/// A helper struct to map local rects into world coords.
map_local_to_world: SpaceMapper<LayoutPixel, WorldPixel>,
/// A list of tiles to draw during batching.
pub tiles_to_draw: Vec<TileIndex>,
/// List of opacity bindings, with some extra information
/// about whether they changed since last frame.
opacity_bindings: FastHashMap<PropertyBindingId, OpacityBindingInfo>,
/// The current dirty region tracker for this picture.
pub dirty_region: DirtyRegion,
/// The current world reference point that tiles are created around.
world_origin: WorldPoint,
/// Current size of tiles in world units.
world_tile_size: WorldSize,
/// Current number of tiles in the allocated grid.
tile_count: TileSize,
/// The current scroll offset for this frame builder. Reset when
/// a new scene arrives.
scroll_offset: Option<WorldVector2D>,
/// A list of blits from the framebuffer to be applied during this frame.
pub pending_blits: Vec<TileBlit>,
/// The current world bounding rect of this tile cache. This is used
/// to derive a local clip rect, such that we don't obscure in the
/// z-buffer any items placed earlier in the render order (such as
/// scroll bars in gecko, when the content overflows under the
/// scroll bar).
world_bounding_rect: WorldRect,
/// World space clip rect of the root clipping node. Every primitive
/// has this as the root of the clip chain attached to the primitive.
root_clip_rect: WorldRect,
/// List of reference primitive information used for
/// correlating the position between display lists.
reference_prims: ReferencePrimitiveList,
/// The root clip chain for this tile cache.
root_clip_chain_id: ClipChainId,
/// If true, this tile cache is enabled. For now, it doesn't
/// support tile caching if the surface is not the main framebuffer.
pub is_enabled: bool,
/// Local clip rect for this tile cache.
pub local_clip_rect: LayoutRect,
}
/// Stores information about a primitive in the cache that we will
/// try to use to correlate positions between display lists.
#[derive(Clone)]
struct ReferencePrimitive {
uid: ItemUid,
local_pos: LayoutPoint,
spatial_node_index: SpatialNodeIndex,
ref_count: usize,
}
/// A list of primitive with uids that only exist once in a display
/// list. Used to obtain reference points to correlate the offset
/// between two similar display lists.
struct ReferencePrimitiveList {
ref_prims: Vec<ReferencePrimitive>,
}
impl ReferencePrimitiveList {
fn new(
prim_instances: &[PrimitiveInstance],
pictures: &[PicturePrimitive],
) -> Self {
let mut map = FastHashMap::default();
let mut search_count = 0;
// Collect a set of primitives that we can
// potentially use for correlation.
collect_ref_prims(
prim_instances,
pictures,
&mut map,
&mut search_count,
);
// Select only primitives where the uid is unique
// in the display list, giving the best chance
// of finding correct correlations.
let ref_prims = map.values().filter(|prim| {
prim.ref_count == 1
}).cloned().collect();
ReferencePrimitiveList {
ref_prims,
}
}
}
/// Collect a sample of primitives from the prim list that can
/// be used to correlate positions.
fn collect_ref_prims(
prim_instances: &[PrimitiveInstance],
pictures: &[PicturePrimitive],
map: &mut FastHashMap<ItemUid, ReferencePrimitive>,
search_count: &mut usize,
) {
for prim_instance in prim_instances {
if *search_count > MAX_PRIMS_TO_SEARCH {
return;
}
match prim_instance.kind {
PrimitiveInstanceKind::Picture { pic_index, .. } => {
collect_ref_prims(
&pictures[pic_index.0].prim_list.prim_instances,
pictures,
map,
search_count,
);
}
_ => {
let uid = prim_instance.uid();
let entry = map.entry(uid).or_insert_with(|| {
ReferencePrimitive {
uid,
local_pos: prim_instance.prim_origin,
spatial_node_index: prim_instance.spatial_node_index,
ref_count: 0,
}
});
entry.ref_count += 1;
*search_count = *search_count + 1;
}
}
}
}
impl TileCache {
pub fn new(
spatial_node_index: SpatialNodeIndex,
prim_instances: &[PrimitiveInstance],
root_clip_chain_id: ClipChainId,
pictures: &[PicturePrimitive],
) -> Self {
// Build the list of reference primitives
// for this picture cache.
let reference_prims = ReferencePrimitiveList::new(
prim_instances,
pictures,
);
TileCache {
spatial_node_index,
tiles: Vec::new(),
map_local_to_world: SpaceMapper::new(
ROOT_SPATIAL_NODE_INDEX,
WorldRect::zero(),
),
tiles_to_draw: Vec::new(),
opacity_bindings: FastHashMap::default(),
dirty_region: DirtyRegion::new(),
world_origin: WorldPoint::zero(),
world_tile_size: WorldSize::zero(),
tile_count: TileSize::zero(),
scroll_offset: None,
pending_blits: Vec::new(),
world_bounding_rect: WorldRect::zero(),
root_clip_rect: WorldRect::max_rect(),
reference_prims,
root_clip_chain_id,
is_enabled: true,
local_clip_rect: LayoutRect::zero(),
}
}
/// Get the tile coordinates for a given rectangle.
fn get_tile_coords_for_rect(
&self,
rect: &WorldRect,
) -> (TileOffset, TileOffset) {
// Translate the rectangle into the virtual tile space
let origin = rect.origin - self.world_origin;
// Get the tile coordinates in the picture space.
let mut p0 = TileOffset::new(
(origin.x / self.world_tile_size.width).floor() as i32,
(origin.y / self.world_tile_size.height).floor() as i32,
);
let mut p1 = TileOffset::new(
((origin.x + rect.size.width) / self.world_tile_size.width).ceil() as i32,
((origin.y + rect.size.height) / self.world_tile_size.height).ceil() as i32,
);
// Clamp the tile coordinates here to avoid looping over irrelevant tiles later on.
p0.x = clamp(p0.x, 0, self.tile_count.width);
p0.y = clamp(p0.y, 0, self.tile_count.height);
p1.x = clamp(p1.x, 0, self.tile_count.width);
p1.y = clamp(p1.y, 0, self.tile_count.height);
(p0, p1)
}
/// Update transforms, opacity bindings and tile rects.
pub fn pre_update(
&mut self,
pic_rect: LayoutRect,
frame_context: &FrameVisibilityContext,
frame_state: &mut FrameVisibilityState,
surface_index: SurfaceIndex,
) {
// If the tile cache is the first surface on the root
// surface, then we can enable it. If the client has
// requested caching on an offscreen surface, we will
// need to disable it (for now).
self.is_enabled = surface_index == SurfaceIndex(1);
if !self.is_enabled {
// TODO(gw): It's technically possible that this tile cache
// might have been enabled in a valid state, and
// then got an offscreen surface. In this case,
// there may be some pre-cached tiles still existing.
// They will expire from the texture cache as normal,
// but we should check this path a bit more carefully
// to see if any other memory should be freed.
return;
}
let DeviceIntSize { width: tile_width, height: tile_height, _unit: _ } =
Self::tile_dimensions(frame_context.config.testing);
// Work out the scroll offset to apply to the world reference point.
let scroll_offset_point = frame_context.clip_scroll_tree
.get_world_transform(self.spatial_node_index)
.inverse_project_2d_origin()
.unwrap_or_else(LayoutPoint::zero);
let scroll_offset = WorldVector2D::new(scroll_offset_point.x, scroll_offset_point.y);
let scroll_delta = match self.scroll_offset {
Some(prev) => prev - scroll_offset,
None => WorldVector2D::zero(),
};
self.scroll_offset = Some(scroll_offset);
// Pull any retained tiles from the previous scene.
let world_offset = if frame_state.retained_tiles.tiles.is_empty() {
None
} else {
assert!(self.tiles.is_empty());
self.tiles = mem::replace(&mut frame_state.retained_tiles.tiles, Vec::new());
// Get the positions of the reference primitives for this
// new display list.
let mut new_prim_map = FastHashMap::default();
build_ref_prims(
&self.reference_prims.ref_prims,
&mut new_prim_map,
frame_context.clip_scroll_tree,
);
// Attempt to correlate them to work out which offset to apply.
correlate_prim_maps(
&frame_state.retained_tiles.ref_prims,
&new_prim_map,
)
}.unwrap_or(WorldVector2D::zero());
// Assume no tiles are valid to draw by default
self.tiles_to_draw.clear();
self.map_local_to_world = SpaceMapper::new(
ROOT_SPATIAL_NODE_INDEX,
frame_context.screen_world_rect,
);
let world_mapper = SpaceMapper::new_with_target(
ROOT_SPATIAL_NODE_INDEX,
self.spatial_node_index,
frame_context.screen_world_rect,
frame_context.clip_scroll_tree,
);
// Do a hacky diff of opacity binding values from the last frame. This is
// used later on during tile invalidation tests.
let current_properties = frame_context.scene_properties.float_properties();
let old_properties = mem::replace(&mut self.opacity_bindings, FastHashMap::default());
for (id, value) in current_properties {
let changed = match old_properties.get(id) {
Some(old_property) => !old_property.value.approx_eq(value),
None => true,
};
self.opacity_bindings.insert(*id, OpacityBindingInfo {
value: *value,
changed,
});
}
// Map the picture rect to world and device space and work out the tiles
// that we need in order to ensure the screen is covered. We haven't done
// any snapping yet, so we need to round out in device space to ensure we
// cover all pixels the picture may touch.
let pic_device_rect = {
let unsnapped_world_rect = world_mapper
.map(&pic_rect)
.expect("bug: unable to map picture rect to world");
(unsnapped_world_rect * frame_context.global_device_pixel_scale)
.round_out()
};
let pic_world_rect = pic_device_rect / frame_context.global_device_pixel_scale;
// If the bounding rect of the picture to cache doesn't intersect with
// the visible world rect at all, just take the screen world rect as
// a reference for the area to create tiles for. This allows existing
// tiles to be retained in case they are still valid if / when they
// get scrolled back onto the screen.
let needed_world_rect = frame_context
.screen_world_rect
.intersection(&pic_world_rect)
.unwrap_or(frame_context.screen_world_rect);
// Get a reference point that serves as an origin that all tiles we create
// must be aligned to. This ensures that tiles get reused correctly between
// scrolls and display list changes, even with the different local coord
// systems that gecko supplies.
let mut world_ref_point = if self.tiles.is_empty() {
needed_world_rect.origin.floor()
} else {
self.tiles[0].world_rect.origin + world_offset
};
// Apply the scroll delta so that existing tiles still get used.
world_ref_point += scroll_delta;
// Work out the required device rect that we need to cover the screen,
// given the world reference point constraint.
let device_ref_point = world_ref_point * frame_context.global_device_pixel_scale;
let device_world_rect = frame_context.screen_world_rect * frame_context.global_device_pixel_scale;
let needed_device_rect = pic_device_rect
.intersection(&device_world_rect)
.unwrap_or(device_world_rect);
// Expand the needed device rect vertically by a small number of tiles. This
// ensures that as tiles are scrolled in/out of view, they are retained for
// a while before being discarded.
// TODO(gw): On some pages it might be worth also inflating horizontally.
// (is this locale specific?). It might be possible to make a good
// guess based on the size of the picture rect for the tile cache.
let needed_device_rect = needed_device_rect.inflate(
0.0,
3.0 * tile_height as f32,
);
let p0 = needed_device_rect.origin;
let p1 = needed_device_rect.bottom_right();
let p0 = DevicePoint::new(
device_ref_point.x + ((p0.x - device_ref_point.x) / tile_width as f32).floor() * tile_width as f32,
device_ref_point.y + ((p0.y - device_ref_point.y) / tile_height as f32).floor() * tile_height as f32,
);
let p1 = DevicePoint::new(
device_ref_point.x + ((p1.x - device_ref_point.x) / tile_width as f32).ceil() * tile_width as f32,
device_ref_point.y + ((p1.y - device_ref_point.y) / tile_height as f32).ceil() * tile_height as f32,
);
// And now the number of tiles from that device rect.
let x_tiles = ((p1.x - p0.x) / tile_width as f32).round() as i32;
let y_tiles = ((p1.y - p0.y) / tile_height as f32).round() as i32;
// Step through any old tiles, and retain them if we can. They are keyed only on
// the (scroll adjusted) world position, relying on the descriptor content checks
// later to invalidate them if the content has changed.
let mut old_tiles = FastHashMap::default();
for tile in self.tiles.drain(..) {
let tile_device_pos = (tile.world_rect.origin + scroll_delta) * frame_context.global_device_pixel_scale;
let key = (
(tile_device_pos.x + world_offset.x).round() as i32,
(tile_device_pos.y + world_offset.y).round() as i32,
);
old_tiles.insert(key, tile);
}
// Store parameters about the current tiling rect for use during dependency updates.
self.world_origin = WorldPoint::new(
p0.x / frame_context.global_device_pixel_scale.0,
p0.y / frame_context.global_device_pixel_scale.0,
);
self.world_tile_size = WorldSize::new(
tile_width as f32 / frame_context.global_device_pixel_scale.0,
tile_height as f32 / frame_context.global_device_pixel_scale.0,
);
self.tile_count = TileSize::new(x_tiles, y_tiles);
// Step through each tile and try to retain an old tile from the
// previous frame, and update bounding rects.
for y in 0 .. y_tiles {
for x in 0 .. x_tiles {
let px = p0.x + x as f32 * tile_width as f32;
let py = p0.y + y as f32 * tile_height as f32;
let key = (px.round() as i32, py.round() as i32);
let mut tile = match old_tiles.remove(&key) {
Some(tile) => tile,
None => {
let next_id = TileId(NEXT_TILE_ID.fetch_add(1, Ordering::Relaxed));
Tile::new(next_id)
}
};
tile.world_rect = WorldRect::new(
WorldPoint::new(
px / frame_context.global_device_pixel_scale.0,
py / frame_context.global_device_pixel_scale.0,
),
self.world_tile_size,
);
tile.local_rect = world_mapper
.unmap(&tile.world_rect)
.expect("bug: can't unmap world rect");
tile.visible_rect = tile.world_rect.intersection(&frame_context.screen_world_rect);
self.tiles.push(tile);
}
}
if !old_tiles.is_empty() {
// TODO(gw): Should we explicitly drop the tile texture cache handles here?
}
self.world_bounding_rect = WorldRect::zero();
self.root_clip_rect = WorldRect::max_rect();
// Calculate the world space of the root clip node, that every primitive has
// at the root of its clip chain (this is enforced by the per-pipeline-root
// clip node added implicitly during display list flattening). Doing it once