-
Notifications
You must be signed in to change notification settings - Fork 54
/
picture.rs
3232 lines (2863 loc) · 128 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, FontRenderMode};
use api::{DebugFlags, RasterSpace, ImageKey, ColorF};
use api::units::*;
use crate::box_shadow::{BLUR_SAMPLE_SCALE};
use crate::clip::{ClipStore, ClipDataStore, ClipChainInstance};
use crate::clip_scroll_tree::{ROOT_SPATIAL_NODE_INDEX,
ClipScrollTree, CoordinateSpaceMapping, SpatialNodeIndex, VisibleFace, CoordinateSystemId
};
use crate::debug_colors;
use euclid::{vec3, TypedPoint2D, TypedScale, TypedSize2D, Vector2D, TypedRect};
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, PrimitiveVisibilityMask, PointKey, PrimitiveTemplateKind};
use crate::prim_store::{PictureIndex, PrimitiveInstance, PrimitiveInstanceKind};
use crate::prim_store::{get_raster_rects, PrimitiveScratchBuffer, RectangleKey};
use crate::prim_store::{OpacityBindingStorage, ImageInstanceStorage, OpacityBindingIndex};
use crate::print_tree::PrintTreePrinter;
use crate::render_backend::DataStores;
use crate::render_task::{ClearMode, RenderTask};
use crate::render_task::{RenderTaskId, RenderTaskLocation, BlurTaskCache};
use crate::resource_cache::ResourceCache;
use crate::scene::SceneProperties;
use crate::scene_builder::Interners;
use crate::spatial_node::SpatialNodeType;
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).
*/
/// Specify whether a surface allows subpixel AA text rendering.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum SubpixelMode {
/// This surface allows subpixel AA text
Allow,
/// Subpixel AA text cannot be drawn on this surface
Deny,
}
/// A comparable transform matrix, that compares with epsilon checks.
#[derive(Debug, Clone)]
struct MatrixKey {
m: [f32; 16],
}
impl PartialEq for MatrixKey {
fn eq(&self, other: &Self) -> bool {
const EPSILON: f32 = 0.001;
// TODO(gw): It's possible that we may need to adjust the epsilon
// to be tighter on most of the matrix, except the
// translation parts?
for (i, j) in self.m.iter().zip(other.m.iter()) {
if !i.approx_eq_eps(j, &EPSILON) {
return false;
}
}
true
}
}
/// A comparable / hashable version of a coordinate space mapping. Used to determine
/// if a transform dependency for a tile has changed.
#[derive(Debug, PartialEq, Clone)]
enum TransformKey {
Local,
ScaleOffset {
scale_x: f32,
scale_y: f32,
offset_x: f32,
offset_y: f32,
},
Transform {
m: MatrixKey,
}
}
impl<Src, Dst> From<CoordinateSpaceMapping<Src, Dst>> for TransformKey {
fn from(transform: CoordinateSpaceMapping<Src, Dst>) -> TransformKey {
match transform {
CoordinateSpaceMapping::Local => {
TransformKey::Local
}
CoordinateSpaceMapping::ScaleOffset(ref scale_offset) => {
TransformKey::ScaleOffset {
scale_x: scale_offset.scale.x,
scale_y: scale_offset.scale.y,
offset_x: scale_offset.offset.x,
offset_y: scale_offset.offset.y,
}
}
CoordinateSpaceMapping::Transform(ref m) => {
TransformKey::Transform {
m: MatrixKey {
m: m.to_row_major_array(),
},
}
}
}
}
}
/// 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,
}
pub struct PictureCacheState {
/// The tiles retained by this picture cache.
pub tiles: FastHashMap<TileOffset, Tile>,
/// The current fractional offset of the cache transform root.
fract_offset: PictureVector2D,
}
/// 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 caches: FastHashMap<usize, PictureCacheState>,
}
impl RetainedTiles {
pub fn new() -> Self {
RetainedTiles {
caches: FastHashMap::default(),
}
}
/// Merge items from one retained tiles into another.
pub fn merge(&mut self, other: RetainedTiles) {
assert!(self.caches.is_empty() || other.caches.is_empty());
if self.caches.is_empty() {
self.caches = other.caches;
}
}
}
/// 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 type TileRect = TypedRect<i32, TileCoordinate>;
/// 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.
pub const TILE_SIZE_WIDTH: i32 = 1024;
pub const TILE_SIZE_HEIGHT: i32 = 512;
/// The maximum size per axis of a surface,
/// in WorldPixel coordinates.
const MAX_SURFACE_SIZE: f32 = 4096.0;
/// 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)
}
fn clampf(value: f32, low: f32, high: f32) -> f32 {
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)]
pub struct TileId(usize);
/// Information about a cached tile.
#[derive(Debug)]
pub struct Tile {
/// The current world rect of this tile.
pub world_rect: WorldRect,
/// The current local rect of this tile.
pub rect: PictureRect,
/// The local rect of the tile clipped to the overal picture local rect.
clipped_rect: PictureRect,
/// Uniquely describes the content of this tile, in a way that can be
/// (reasonably) efficiently hashed and compared.
pub 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.
pub is_valid: bool,
/// If true, the content on this tile is the same as last frame.
is_same_content: bool,
/// The tile id is stable between display lists and / or frames,
/// if the tile is retained. Useful for debugging tile evictions.
pub 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>,
/// Bitfield specifying the dirty region(s) that are relevant to this tile.
visibility_mask: PrimitiveVisibilityMask,
/// If true, the tile was determined to be opaque, which means blending
/// can be disabled when drawing it.
pub is_opaque: bool,
}
impl Tile {
/// Construct a new, invalid tile.
fn new(
id: TileId,
) -> Self {
Tile {
rect: PictureRect::zero(),
clipped_rect: PictureRect::zero(),
world_rect: WorldRect::zero(),
handle: TextureCacheHandle::invalid(),
descriptor: TileDescriptor::new(),
is_same_content: false,
is_valid: false,
transforms: FastHashSet::default(),
id,
visibility_mask: PrimitiveVisibilityMask::empty(),
is_opaque: false,
}
}
/// Clear the dependencies for a tile.
fn clear(&mut self) {
self.transforms.clear();
self.descriptor.clear();
}
/// Invalidate a tile based on change in content. This
/// must 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.id);
self.is_valid &= self.is_same_content;
}
}
/// Defines a key that uniquely identifies a primitive instance.
#[derive(Debug, Clone)]
pub struct PrimitiveDescriptor {
/// Uniquely identifies the content of the primitive template.
prim_uid: ItemUid,
/// The origin in world space of this primitive.
origin: PointKey,
/// The clip rect for this primitive. Included here in
/// dependencies since there is no entry in the clip chain
/// dependencies for the local clip rect.
prim_clip_rect: RectangleKey,
/// 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,
}
impl PartialEq for PrimitiveDescriptor {
fn eq(&self, other: &Self) -> bool {
const EPSILON: f32 = 0.001;
if self.prim_uid != other.prim_uid {
return false;
}
if self.first_clip != other.first_clip {
return false;
}
if self.clip_count != other.clip_count {
return false;
}
if !self.origin.x.approx_eq_eps(&other.origin.x, &EPSILON) {
return false;
}
if !self.origin.y.approx_eq_eps(&other.origin.y, &EPSILON) {
return false;
}
if !self.prim_clip_rect.x.approx_eq_eps(&other.prim_clip_rect.x, &EPSILON) {
return false;
}
if !self.prim_clip_rect.y.approx_eq_eps(&other.prim_clip_rect.y, &EPSILON) {
return false;
}
if !self.prim_clip_rect.w.approx_eq_eps(&other.prim_clip_rect.w, &EPSILON) {
return false;
}
if !self.prim_clip_rect.h.approx_eq_eps(&other.prim_clip_rect.h, &EPSILON) {
return false;
}
true
}
}
/// Defines a key that uniquely identifies a clip instance.
#[derive(Debug, Clone)]
pub struct ClipDescriptor {
/// The uid is guaranteed to uniquely describe the content of the clip node.
uid: ItemUid,
/// The origin defines the relative position of this clip template.
origin: PointKey,
}
impl PartialEq for ClipDescriptor {
fn eq(&self, other: &Self) -> bool {
const EPSILON: f32 = 0.001;
if self.uid != other.uid {
return false;
}
if !self.origin.x.approx_eq_eps(&other.origin.x, &EPSILON) {
return false;
}
if !self.origin.y.approx_eq_eps(&other.origin.y, &EPSILON) {
return false;
}
true
}
}
/// 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.
pub prims: ComparableVec<PrimitiveDescriptor>,
/// List of clip node descriptors.
clips: ComparableVec<ClipDescriptor>,
/// 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<TransformKey>,
}
impl TileDescriptor {
fn new() -> Self {
TileDescriptor {
prims: ComparableVec::new(),
clips: 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.clips.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, _id: TileId) -> bool {
if !self.image_keys.is_valid() {
return false;
}
if !self.opacity_bindings.is_valid() {
return false;
}
if !self.clips.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 {
/// World rect of this dirty region
pub world_rect: WorldRect,
/// Bitfield for picture render tasks that draw this dirty region.
pub visibility_mask: PrimitiveVisibilityMask,
}
/// 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: WorldRect,
}
impl DirtyRegion {
/// Construct a new dirty region tracker.
pub fn new(
) -> Self {
DirtyRegion {
dirty_rects: Vec::with_capacity(PrimitiveVisibilityMask::MAX_DIRTY_REGIONS),
combined: WorldRect::zero(),
}
}
/// Reset the dirty regions back to empty
pub fn clear(&mut self) {
self.dirty_rects.clear();
self.combined = WorldRect::zero();
}
/// Push a dirty rect into this region
pub fn push(
&mut self,
rect: WorldRect,
visibility_mask: PrimitiveVisibilityMask,
) {
// Include this in the overall dirty rect
self.combined = self.combined.union(&rect);
// Store the individual dirty rect.
self.dirty_rects.push(DirtyRegionRect {
world_rect: rect,
visibility_mask,
});
}
/// Include another rect into an existing dirty region.
pub fn include_rect(
&mut self,
region_index: usize,
rect: WorldRect,
) {
self.combined = self.combined.union(&rect);
let region = &mut self.dirty_rects[region_index];
region.world_rect = region.world_rect.union(&rect);
}
// TODO(gw): This returns a heap allocated object. Perhaps we can simplify this
// logic? Although - it's only used very rarely so it may not be an issue.
pub fn inflate(
&self,
inflate_amount: f32,
) -> DirtyRegion {
let mut dirty_rects = Vec::with_capacity(self.dirty_rects.len());
let mut combined = WorldRect::zero();
for rect in &self.dirty_rects {
let world_rect = rect.world_rect.inflate(inflate_amount, inflate_amount);
combined = combined.union(&world_rect);
dirty_rects.push(DirtyRegionRect {
world_rect,
visibility_mask: rect.visibility_mask,
});
}
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)
}
}
/// Represents a cache of tiles that make up a picture primitives.
pub struct TileCacheInstance {
/// Index of the tile cache / slice for this frame builder. It's determined
/// by the setup_picture_caching method during flattening, which splits the
/// picture tree into multiple slices. It's used as a simple input to the tile
/// keys. It does mean we invalidate tiles if a new layer gets inserted / removed
/// between display lists - this seems very unlikely to occur on most pages, but
/// can be revisited if we ever notice that.
pub slice: usize,
/// The positioning node for this tile cache.
pub spatial_node_index: SpatialNodeIndex,
/// Hash of tiles present in this picture.
pub tiles: FastHashMap<TileOffset, Tile>,
/// A helper struct to map local rects into surface coords.
map_local_to_surface: SpaceMapper<LayoutPixel, PicturePixel>,
/// 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,
/// Current size of tiles in picture units.
tile_size: PictureSize,
/// Tile coords of the currently allocated grid.
tile_rect: TileRect,
/// Pre-calculated versions of the tile_rect above, used to speed up the
/// calculations in get_tile_coords_for_rect.
tile_bounds_p0: TileOffset,
tile_bounds_p1: TileOffset,
/// Local rect (unclipped) of the picture this cache covers.
pub local_rect: PictureRect,
/// Local clip rect for this tile cache.
pub local_clip_rect: PictureRect,
/// A list of tiles that are valid and visible, which should be drawn to the main scene.
pub tiles_to_draw: Vec<TileOffset>,
/// The world space viewport that this tile cache draws into.
/// Any clips outside this viewport can be ignored (and must be removed so that
/// we can draw outside the bounds of the viewport).
pub world_viewport_rect: WorldRect,
/// The surface index that this tile cache will be drawn into.
surface_index: SurfaceIndex,
/// The background color from the renderer. If this is set opaque, we know it's
/// fine to clear the tiles to this and allow subpixel text on the first slice.
pub background_color: Option<ColorF>,
/// The picture space rectangle that is known to be opaque. This is used
/// to determine where subpixel AA can be used, and where alpha blending
/// can be disabled.
pub opaque_rect: PictureRect,
/// The allowed subpixel mode for this surface, which depends on the detected
/// opacity of the background.
pub subpixel_mode: SubpixelMode,
/// The current fractional offset of the cache transform root. If this changes,
/// all tiles need to be invalidated and redrawn, since snapping differences are
/// likely to occur.
fract_offset: PictureVector2D,
}
impl TileCacheInstance {
pub fn new(
slice: usize,
spatial_node_index: SpatialNodeIndex,
background_color: Option<ColorF>,
) -> Self {
TileCacheInstance {
slice,
spatial_node_index,
tiles: FastHashMap::default(),
map_local_to_surface: SpaceMapper::new(
ROOT_SPATIAL_NODE_INDEX,
PictureRect::zero(),
),
opacity_bindings: FastHashMap::default(),
dirty_region: DirtyRegion::new(),
tile_size: PictureSize::zero(),
tile_rect: TileRect::zero(),
tile_bounds_p0: TileOffset::zero(),
tile_bounds_p1: TileOffset::zero(),
local_rect: PictureRect::zero(),
local_clip_rect: PictureRect::zero(),
tiles_to_draw: Vec::new(),
world_viewport_rect: WorldRect::zero(),
surface_index: SurfaceIndex(0),
background_color,
opaque_rect: PictureRect::zero(),
subpixel_mode: SubpixelMode::Allow,
fract_offset: PictureVector2D::zero(),
}
}
/// Returns true if this tile cache is considered opaque.
pub fn is_opaque(&self) -> bool {
// If known opaque due to background clear color and being the first slice.
// The background_color will only be Some(..) if this is the first slice.
match self.background_color {
Some(color) => color.a >= 1.0,
None => false
}
}
/// Get the tile coordinates for a given rectangle.
fn get_tile_coords_for_rect(
&self,
rect: &PictureRect,
) -> (TileOffset, TileOffset) {
// Get the tile coordinates in the picture space.
let mut p0 = TileOffset::new(
(rect.origin.x / self.tile_size.width).floor() as i32,
(rect.origin.y / self.tile_size.height).floor() as i32,
);
let mut p1 = TileOffset::new(
((rect.origin.x + rect.size.width) / self.tile_size.width).ceil() as i32,
((rect.origin.y + rect.size.height) / self.tile_size.height).ceil() as i32,
);
// Clamp the tile coordinates here to avoid looping over irrelevant tiles later on.
p0.x = clamp(p0.x, self.tile_bounds_p0.x, self.tile_bounds_p1.x);
p0.y = clamp(p0.y, self.tile_bounds_p0.y, self.tile_bounds_p1.y);
p1.x = clamp(p1.x, self.tile_bounds_p0.x, self.tile_bounds_p1.x);
p1.y = clamp(p1.y, self.tile_bounds_p0.y, self.tile_bounds_p1.y);
(p0, p1)
}
/// Update transforms, opacity bindings and tile rects.
pub fn pre_update(
&mut self,
pic_rect: PictureRect,
surface_index: SurfaceIndex,
frame_context: &FrameVisibilityContext,
frame_state: &mut FrameVisibilityState,
) -> WorldRect {
let tile_width = TILE_SIZE_WIDTH;
let tile_height = TILE_SIZE_HEIGHT;
self.surface_index = surface_index;
// Reset the opaque rect + subpixel mode, as they are calculated
// during the prim dependency checks.
self.opaque_rect = PictureRect::zero();
self.subpixel_mode = SubpixelMode::Allow;
self.map_local_to_surface = SpaceMapper::new(
self.spatial_node_index,
PictureRect::from_untyped(&pic_rect.to_untyped()),
);
let pic_to_world_mapper = SpaceMapper::new_with_target(
ROOT_SPATIAL_NODE_INDEX,
self.spatial_node_index,
frame_context.global_screen_world_rect,
frame_context.clip_scroll_tree,
);
// If there are pending retained state, retrieve it.
if let Some(prev_state) = frame_state.retained_tiles.caches.remove(&self.slice) {
self.tiles.extend(prev_state.tiles);
self.fract_offset = prev_state.fract_offset;
}
// Map an arbitrary point in picture space to world space, to work out
// what the fractional translation is that's applied by this scroll root.
// TODO(gw): I'm not 100% sure this is right. At least, in future, we should
// make a specific API for this, and/or enforce that the picture
// cache transform only includes scale and/or translation (we
// already ensure it doesn't have perspective).
let world_origin = pic_to_world_mapper
.map(&PictureRect::new(PicturePoint::zero(), PictureSize::new(1.0, 1.0)))
.expect("bug: unable to map origin to world space")
.origin;
// Get the desired integer device coordinate
let device_origin = world_origin * frame_context.global_device_pixel_scale;
let desired_device_origin = device_origin.round();
// Unmap from device space to world space rect
let ref_world_rect = WorldRect::new(
desired_device_origin / frame_context.global_device_pixel_scale,
WorldSize::new(1.0, 1.0),
);
// Unmap from world space to picture space
let ref_point = pic_to_world_mapper
.unmap(&ref_world_rect)
.expect("bug: unable to unmap ref world rect")
.origin;
// Extract the fractional offset required in picture space to align in device space
let fract_offset = PictureVector2D::new(
ref_point.x.fract(),
ref_point.y.fract(),
);
// Determine if the fractional offset of the transform is different this frame
// from the currently cached tile set.
let fract_changed = (self.fract_offset.x - fract_offset.x).abs() > 0.001 ||
(self.fract_offset.y - fract_offset.y).abs() > 0.001;
if fract_changed {
self.fract_offset = fract_offset;
}
let spatial_node = &frame_context
.clip_scroll_tree
.spatial_nodes[self.spatial_node_index.0 as usize];
let (viewport_rect, viewport_spatial_node_index) = match spatial_node.node_type {
SpatialNodeType::ScrollFrame(ref info) => {
(info.viewport_rect, spatial_node.parent.unwrap())
}
SpatialNodeType::StickyFrame(..) => {
unreachable!();
}
SpatialNodeType::ReferenceFrame(..) => {
assert_eq!(self.spatial_node_index, ROOT_SPATIAL_NODE_INDEX);
(LayoutRect::max_rect(), ROOT_SPATIAL_NODE_INDEX)
}
};
let viewport_to_world_mapper = SpaceMapper::new_with_target(
ROOT_SPATIAL_NODE_INDEX,
viewport_spatial_node_index,
frame_context.global_screen_world_rect,
frame_context.clip_scroll_tree,
);
self.world_viewport_rect = viewport_to_world_mapper
.map(&viewport_rect)
.expect("bug: unable to map viewport to world space");
// TODO(gw): This is a reverse mapping. It should always work since we know
// that this path only runs for slices in the root coordinate system.
// But perhaps we should assert that?
// TODO(gw): We could change to directly use the ScaleOffset in content_transform
// which would make this clearer that we know the coordinate systems are the
// same and that it's a safe / exact conversion.
self.map_local_to_surface.set_target_spatial_node(
viewport_spatial_node_index,
frame_context.clip_scroll_tree,
);
let local_viewport_rect = self
.map_local_to_surface
.map(&viewport_rect)
.expect("bug: unable to map to local viewport rect");
self.local_rect = pic_rect;
self.local_clip_rect = local_viewport_rect;
// 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,
});
}
let 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,
);
// We know that this is an exact rectangle, since we (for now) only support tile
// caches where the scroll root is in the root coordinate system.
let local_tile_rect = pic_to_world_mapper
.unmap(&WorldRect::new(WorldPoint::zero(), world_tile_size))
.expect("bug: unable to get local tile rect");
self.tile_size = local_tile_rect.size;
let screen_rect_in_pic_space = pic_to_world_mapper
.unmap(&frame_context.global_screen_world_rect)
.expect("unable to unmap screen rect");
let visible_rect_in_pic_space = screen_rect_in_pic_space
.intersection(&self.local_clip_rect)
.unwrap_or(PictureRect::zero());
// Inflate the needed rect a bit, so that we retain tiles that we have drawn
// but have just recently gone off-screen. This means that we avoid re-drawing
// tiles if the user is scrolling up and down small amounts, at the cost of
// a bit of extra texture memory.
let desired_rect_in_pic_space = visible_rect_in_pic_space
.inflate(0.0, 3.0 * self.tile_size.height);
let needed_rect_in_pic_space = desired_rect_in_pic_space
.intersection(&pic_rect)
.unwrap_or(PictureRect::zero());
let p0 = needed_rect_in_pic_space.origin;
let p1 = needed_rect_in_pic_space.bottom_right();
let x0 = (p0.x / local_tile_rect.size.width).floor() as i32;
let x1 = (p1.x / local_tile_rect.size.width).ceil() as i32;
let y0 = (p0.y / local_tile_rect.size.height).floor() as i32;
let y1 = (p1.y / local_tile_rect.size.height).ceil() as i32;
let x_tiles = x1 - x0;
let y_tiles = y1 - y0;
self.tile_rect = TileRect::new(
TileOffset::new(x0, y0),
TileSize::new(x_tiles, y_tiles),
);
// This is duplicated information from tile_rect, but cached here to avoid
// redundant calculations during get_tile_coords_for_rect
self.tile_bounds_p0 = TileOffset::new(x0, y0);
self.tile_bounds_p1 = TileOffset::new(x1, y1);
let mut world_culling_rect = WorldRect::zero();
let mut old_tiles = mem::replace(
&mut self.tiles,
FastHashMap::default(),
);
for y in y0 .. y1 {
for x in x0 .. x1 {
let key = TileOffset::new(x, y);
let mut tile = old_tiles
.remove(&key)
.unwrap_or_else(|| {
let next_id = TileId(NEXT_TILE_ID.fetch_add(1, Ordering::Relaxed));
Tile::new(next_id)
});
// Ensure each tile is offset by the appropriate amount from the
// origin, such that the content origin will be a whole number and
// the snapping will be consistent.
tile.rect = PictureRect::new(
PicturePoint::new(
x as f32 * self.tile_size.width + fract_offset.x,
y as f32 * self.tile_size.height + fract_offset.y,
),
self.tile_size,
);
tile.clipped_rect = tile.rect
.intersection(&self.local_rect)
.unwrap_or(PictureRect::zero());
tile.world_rect = pic_to_world_mapper
.map(&tile.rect)
.expect("bug: map local tile rect");
world_culling_rect = world_culling_rect.union(&tile.world_rect);
self.tiles.insert(key, tile);
}
}
// Do tile invalidation for any dependencies that we know now.
for (_, tile) in &mut self.tiles {
// Start frame assuming that the tile has the same content,
// unless the fractional offset of the transform root changed.
tile.is_same_content = !fract_changed;
// Content has changed if any opacity bindings changed.
for binding in tile.descriptor.opacity_bindings.items() {
if let OpacityBinding::Binding(id) = binding {
let changed = match self.opacity_bindings.get(id) {
Some(info) => info.changed,
None => true,
};
if changed {
tile.is_same_content = false;
break;
}
}
}
// Clear any dependencies so that when we rebuild them we
// can compare if the tile has the same content.
tile.clear();
}
world_culling_rect
}
/// Update the dependencies for each tile for a given primitive instance.
pub fn update_prim_dependencies(
&mut self,
prim_instance: &PrimitiveInstance,
prim_clip_chain: Option<&ClipChainInstance>,
local_prim_rect: LayoutRect,
clip_scroll_tree: &ClipScrollTree,
data_stores: &DataStores,
clip_store: &ClipStore,
pictures: &[PicturePrimitive],
resource_cache: &ResourceCache,
opacity_binding_store: &OpacityBindingStorage,
image_instances: &ImageInstanceStorage,
surface_index: SurfaceIndex,
) -> bool {
self.map_local_to_surface.set_target_spatial_node(
prim_instance.spatial_node_index,
clip_scroll_tree,
);
// Map the primitive local rect into picture space.
let prim_rect = match self.map_local_to_surface.map(&local_prim_rect) {
Some(rect) => rect,
None => return false,
};
// If the rect is invalid, no need to create dependencies.
if prim_rect.size.is_empty_or_negative() {
return false;
}
// Get the tile coordinates in the picture space.
let (p0, p1) = self.get_tile_coords_for_rect(&prim_rect);
// If the primitive is outside the tiling rects, it's known to not
// be visible.
if p0.x == p1.x || p0.y == p1.y {
return false;
}
// Build the list of resources that this primitive has dependencies on.
let mut opacity_bindings: SmallVec<[OpacityBinding; 4]> = SmallVec::new();
let mut clips: SmallVec<[ClipDescriptor; 8]> = SmallVec::new();
let mut image_keys: SmallVec<[ImageKey; 8]> = SmallVec::new();
let mut clip_spatial_nodes = FastHashSet::default();
let mut prim_clip_rect = PictureRect::zero();