-
Notifications
You must be signed in to change notification settings - Fork 54
/
clip.rs
1652 lines (1500 loc) · 60.8 KB
/
clip.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/. */
//! Internal representation of clips in WebRender.
//!
//! # Data structures
//!
//! There are a number of data structures involved in the clip module:
//!
//! - ClipStore - Main interface used by other modules.
//!
//! - ClipItem - A single clip item (e.g. a rounded rect, or a box shadow).
//! These are an exposed API type, stored inline in a ClipNode.
//!
//! - ClipNode - A ClipItem with an attached GPU handle. The GPU handle is populated
//! when a ClipNodeInstance is built from this node (which happens while
//! preparing primitives for render).
//!
//! ClipNodeInstance - A ClipNode with attached positioning information (a spatial
//! node index). This is stored as a contiguous array of nodes
//! within the ClipStore.
//!
//! ```ascii
//! +-----------------------+-----------------------+-----------------------+
//! | ClipNodeInstance | ClipNodeInstance | ClipNodeInstance |
//! +-----------------------+-----------------------+-----------------------+
//! | ClipItem | ClipItem | ClipItem |
//! | Spatial Node Index | Spatial Node Index | Spatial Node Index |
//! | GPU cache handle | GPU cache handle | GPU cache handle |
//! | ... | ... | ... |
//! +-----------------------+-----------------------+-----------------------+
//! 0 1 2
//! +----------------+ | |
//! | ClipNodeRange |____| |
//! | index: 1 | |
//! | count: 2 |___________________________________________________|
//! +----------------+
//! ```
//!
//! - ClipNodeRange - A clip item range identifies a range of clip nodes instances.
//! It is stored as an (index, count).
//!
//! - ClipChainNode - A clip chain node contains a handle to an interned clip item,
//! positioning information (from where the clip was defined), and
//! an optional parent link to another ClipChainNode. ClipChainId
//! is an index into an array, or ClipChainId::NONE for no parent.
//!
//! ```ascii
//! +----------------+ ____+----------------+ ____+----------------+ /---> ClipChainId::NONE
//! | ClipChainNode | | | ClipChainNode | | | ClipChainNode | |
//! +----------------+ | +----------------+ | +----------------+ |
//! | ClipDataHandle | | | ClipDataHandle | | | ClipDataHandle | |
//! | Spatial index | | | Spatial index | | | Spatial index | |
//! | Parent Id |___| | Parent Id |___| | Parent Id |___|
//! | ... | | ... | | ... |
//! +----------------+ +----------------+ +----------------+
//! ```
//!
//! - ClipChainInstance - A ClipChain that has been built for a specific primitive + positioning node.
//!
//! When given a clip chain ID, and a local primitive rect and its spatial node, the clip module
//! creates a clip chain instance. This is a struct with various pieces of useful information
//! (such as a local clip rect). It also contains a (index, count)
//! range specifier into an index buffer of the ClipNodeInstance structures that are actually relevant
//! for this clip chain instance. The index buffer structure allows a single array to be used for
//! all of the clip-chain instances built in a single frame. Each entry in the index buffer
//! also stores some flags relevant to the clip node in this positioning context.
//!
//! ```ascii
//! +----------------------+
//! | ClipChainInstance |
//! +----------------------+
//! | ... |
//! | local_clip_rect |________________________________________________________________________
//! | clips_range |_______________ |
//! +----------------------+ | |
//! | |
//! +------------------+------------------+------------------+------------------+------------------+
//! | ClipNodeInstance | ClipNodeInstance | ClipNodeInstance | ClipNodeInstance | ClipNodeInstance |
//! +------------------+------------------+------------------+------------------+------------------+
//! | flags | flags | flags | flags | flags |
//! | ... | ... | ... | ... | ... |
//! +------------------+------------------+------------------+------------------+------------------+
//! ```
//!
//! # Rendering clipped primitives
//!
//! See the [`segment` module documentation][segment.rs].
//!
//!
//! [segment.rs]: ../segment/index.html
//!
use api::{BorderRadius, ClipIntern, ClipMode, ComplexClipRegion, ImageMask};
use api::{BoxShadowClipMode, ImageKey, ImageRendering};
use api::units::*;
use crate::border::{ensure_no_corner_overlap, BorderRadiusAu};
use crate::box_shadow::{BLUR_SAMPLE_SCALE, BoxShadowClipSource, BoxShadowCacheKey};
use crate::spatial_tree::{ROOT_SPATIAL_NODE_INDEX, SpatialTree, SpatialNodeIndex};
use crate::ellipse::Ellipse;
use crate::gpu_cache::{GpuCache, GpuCacheHandle, ToGpuBlocks};
use crate::gpu_types::{BoxShadowStretchMode};
use crate::image::{self, Repetition};
use crate::intern;
use crate::prim_store::{ClipData, ImageMaskData, SpaceMapper, VisibleMaskImageTile};
use crate::prim_store::{PointKey, SizeKey, RectangleKey};
use crate::render_task_cache::to_cache_size;
use crate::resource_cache::{ImageRequest, ResourceCache};
use std::{iter, ops, u32};
use crate::util::{extract_inner_rect_safe, project_rect, ScaleOffset};
// Type definitions for interning clip nodes.
pub type ClipDataStore = intern::DataStore<ClipIntern>;
pub type ClipDataHandle = intern::Handle<ClipIntern>;
/// Helper to identify simple clips (normal rects) from other kinds of clips,
/// which can often be handled via fast code paths.
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
#[derive(Debug, Copy, Clone, MallocSizeOf)]
pub enum ClipNodeKind {
/// A normal clip rectangle, with Clip mode.
Rectangle,
/// A rectangle with ClipOut, or any other kind of clip.
Complex,
}
// Result of comparing a clip node instance against a local rect.
#[derive(Debug)]
enum ClipResult {
// The clip does not affect the region at all.
Accept,
// The clip prevents the region from being drawn.
Reject,
// The clip affects part of the region. This may
// require a clip mask, depending on other factors.
Partial,
}
// A clip node is a single clip source, along with some
// positioning information and implementation details
// that control where the GPU data for this clip source
// can be found.
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
#[derive(MallocSizeOf)]
pub struct ClipNode {
pub item: ClipItem,
pub gpu_cache_handle: GpuCacheHandle,
}
// Convert from an interning key for a clip item
// to a clip node, which is cached in the document.
impl From<ClipItemKey> for ClipNode {
fn from(item: ClipItemKey) -> Self {
let kind = match item.kind {
ClipItemKeyKind::Rectangle(rect, mode) => {
ClipItemKind::Rectangle { rect: rect.into(), mode }
}
ClipItemKeyKind::RoundedRectangle(rect, radius, mode) => {
ClipItemKind::RoundedRectangle {
rect: rect.into(),
radius: radius.into(),
mode,
}
}
ClipItemKeyKind::ImageMask(rect, image, repeat) => {
ClipItemKind::Image {
image,
rect: rect.into(),
repeat,
}
}
ClipItemKeyKind::BoxShadow(shadow_rect_fract_offset, shadow_rect_size, shadow_radius, prim_shadow_rect, blur_radius, clip_mode) => {
ClipItemKind::new_box_shadow(
shadow_rect_fract_offset.into(),
shadow_rect_size.into(),
shadow_radius.into(),
prim_shadow_rect.into(),
blur_radius.to_f32_px(),
clip_mode,
)
}
};
ClipNode {
item: ClipItem {
kind,
spatial_node_index: item.spatial_node_index,
},
gpu_cache_handle: GpuCacheHandle::new(),
}
}
}
// Flags that are attached to instances of clip nodes.
bitflags! {
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
#[derive(MallocSizeOf)]
pub struct ClipNodeFlags: u8 {
const SAME_SPATIAL_NODE = 0x1;
const SAME_COORD_SYSTEM = 0x2;
const USE_FAST_PATH = 0x4;
}
}
// Identifier for a clip chain. Clip chains are stored
// in a contiguous array in the clip store. They are
// identified by a simple index into that array.
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, Hash)]
#[cfg_attr(feature = "capture", derive(Serialize))]
pub struct ClipChainId(pub u32);
// The root of each clip chain is the NONE id. The
// value is specifically set to u32::MAX so that if
// any code accidentally tries to access the root
// node, a bounds error will occur.
impl ClipChainId {
pub const NONE: Self = ClipChainId(u32::MAX);
pub const INVALID: Self = ClipChainId(0xDEADBEEF);
}
// A clip chain node is an id for a range of clip sources,
// and a link to a parent clip chain node, or ClipChainId::NONE.
#[derive(Clone, Debug, MallocSizeOf)]
#[cfg_attr(feature = "capture", derive(Serialize))]
pub struct ClipChainNode {
pub handle: ClipDataHandle,
pub parent_clip_chain_id: ClipChainId,
}
// When a clip node is found to be valid for a
// clip chain instance, it's stored in an index
// buffer style structure. This struct contains
// an index to the node data itself, as well as
// some flags describing how this clip node instance
// is positioned.
#[derive(Debug, MallocSizeOf)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct ClipNodeInstance {
pub handle: ClipDataHandle,
pub flags: ClipNodeFlags,
pub visible_tiles: Option<Vec<VisibleMaskImageTile>>,
}
// A range of clip node instances that were found by
// building a clip chain instance.
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct ClipNodeRange {
pub first: u32,
pub count: u32,
}
impl ClipNodeRange {
pub fn to_range(&self) -> ops::Range<usize> {
let start = self.first as usize;
let end = start + self.count as usize;
ops::Range {
start,
end,
}
}
}
/// A helper struct for converting between coordinate systems
/// of clip sources and primitives.
// todo(gw): optimize:
// separate arrays for matrices
// cache and only build as needed.
//TODO: merge with `CoordinateSpaceMapping`?
#[derive(Debug, MallocSizeOf)]
#[cfg_attr(feature = "capture", derive(Serialize))]
enum ClipSpaceConversion {
Local,
ScaleOffset(ScaleOffset),
Transform(LayoutToWorldTransform),
}
impl ClipSpaceConversion {
/// Construct a new clip space converter between two spatial nodes.
fn new(
prim_spatial_node_index: SpatialNodeIndex,
clip_spatial_node_index: SpatialNodeIndex,
spatial_tree: &SpatialTree,
) -> Self {
//Note: this code is different from `get_relative_transform` in a way that we only try
// getting the relative transform if it's Local or ScaleOffset,
// falling back to the world transform otherwise.
let clip_spatial_node = &spatial_tree
.spatial_nodes[clip_spatial_node_index.0 as usize];
let prim_spatial_node = &spatial_tree
.spatial_nodes[prim_spatial_node_index.0 as usize];
if prim_spatial_node_index == clip_spatial_node_index {
ClipSpaceConversion::Local
} else if prim_spatial_node.coordinate_system_id == clip_spatial_node.coordinate_system_id {
let scale_offset = prim_spatial_node.content_transform
.inverse()
.accumulate(&clip_spatial_node.content_transform);
ClipSpaceConversion::ScaleOffset(scale_offset)
} else {
ClipSpaceConversion::Transform(
spatial_tree
.get_world_transform(clip_spatial_node_index)
.into_transform()
)
}
}
fn to_flags(&self) -> ClipNodeFlags {
match *self {
ClipSpaceConversion::Local => {
ClipNodeFlags::SAME_SPATIAL_NODE | ClipNodeFlags::SAME_COORD_SYSTEM
}
ClipSpaceConversion::ScaleOffset(..) => {
ClipNodeFlags::SAME_COORD_SYSTEM
}
ClipSpaceConversion::Transform(..) => {
ClipNodeFlags::empty()
}
}
}
}
// Temporary information that is cached and reused
// during building of a clip chain instance.
#[derive(MallocSizeOf)]
#[cfg_attr(feature = "capture", derive(Serialize))]
struct ClipNodeInfo {
conversion: ClipSpaceConversion,
handle: ClipDataHandle,
}
impl ClipNodeInfo {
fn create_instance(
&self,
node: &ClipNode,
clipped_rect: &LayoutRect,
gpu_cache: &mut GpuCache,
resource_cache: &mut ResourceCache,
spatial_tree: &SpatialTree,
request_resources: bool,
) -> Option<ClipNodeInstance> {
// Calculate some flags that are required for the segment
// building logic.
let mut flags = self.conversion.to_flags();
// Some clip shaders support a fast path mode for simple clips.
// TODO(gw): We could also apply fast path when segments are created, since we only write
// the mask for a single corner at a time then, so can always consider radii uniform.
let is_raster_2d =
flags.contains(ClipNodeFlags::SAME_COORD_SYSTEM) ||
spatial_tree
.get_world_viewport_transform(node.item.spatial_node_index)
.is_2d_axis_aligned();
if is_raster_2d && node.item.kind.supports_fast_path_rendering() {
flags |= ClipNodeFlags::USE_FAST_PATH;
}
let mut visible_tiles = None;
if let ClipItemKind::Image { rect, image, repeat } = node.item.kind {
let request = ImageRequest {
key: image,
rendering: ImageRendering::Auto,
tile: None,
};
if let Some(props) = resource_cache.get_image_properties(image) {
if let Some(tile_size) = props.tiling {
let mut mask_tiles = Vec::new();
let visible_rect = if repeat {
*clipped_rect
} else {
clipped_rect.intersection(&rect).unwrap()
};
let repetitions = image::repetitions(
&rect,
&visible_rect,
rect.size,
);
for Repetition { origin, .. } in repetitions {
let layout_image_rect = LayoutRect {
origin,
size: rect.size,
};
let tiles = image::tiles(
&layout_image_rect,
&visible_rect,
&props.visible_rect,
tile_size as i32,
);
for tile in tiles {
if request_resources {
resource_cache.request_image(
request.with_tile(tile.offset),
gpu_cache,
);
}
mask_tiles.push(VisibleMaskImageTile {
tile_offset: tile.offset,
tile_rect: tile.rect,
});
}
}
visible_tiles = Some(mask_tiles);
} else if request_resources {
resource_cache.request_image(request, gpu_cache);
}
} else {
// If the supplied image key doesn't exist in the resource cache,
// skip the clip node since there is nothing to mask with.
warn!("Clip mask with missing image key {:?}", request.key);
return None;
}
}
Some(ClipNodeInstance {
handle: self.handle,
flags,
visible_tiles,
})
}
}
impl ClipNode {
pub fn update(
&mut self,
gpu_cache: &mut GpuCache,
device_pixel_scale: DevicePixelScale,
) {
match self.item.kind {
ClipItemKind::Image { rect, .. } => {
if let Some(request) = gpu_cache.request(&mut self.gpu_cache_handle) {
let data = ImageMaskData {
local_mask_size: rect.size,
};
data.write_gpu_blocks(request);
}
}
ClipItemKind::BoxShadow { ref mut source } => {
if let Some(mut request) = gpu_cache.request(&mut self.gpu_cache_handle) {
request.push([
source.original_alloc_size.width,
source.original_alloc_size.height,
source.clip_mode as i32 as f32,
0.0,
]);
request.push([
source.stretch_mode_x as i32 as f32,
source.stretch_mode_y as i32 as f32,
0.0,
0.0,
]);
request.push(source.prim_shadow_rect);
}
// Quote from https://drafts.csswg.org/css-backgrounds-3/#shadow-blur
// "the image that would be generated by applying to the shadow a
// Gaussian blur with a standard deviation equal to half the blur radius."
let blur_radius_dp = source.blur_radius * 0.5;
// Create scaling from requested size to cache size.
let content_scale = LayoutToWorldScale::new(1.0) * device_pixel_scale;
// Create the cache key for this box-shadow render task.
let cache_size = to_cache_size(source.shadow_rect_alloc_size * content_scale);
let bs_cache_key = BoxShadowCacheKey {
blur_radius_dp: (blur_radius_dp * content_scale.0).round() as i32,
clip_mode: source.clip_mode,
original_alloc_size: (source.original_alloc_size * content_scale).round().to_i32(),
br_top_left: (source.shadow_radius.top_left * content_scale).round().to_i32(),
br_top_right: (source.shadow_radius.top_right * content_scale).round().to_i32(),
br_bottom_right: (source.shadow_radius.bottom_right * content_scale).round().to_i32(),
br_bottom_left: (source.shadow_radius.bottom_left * content_scale).round().to_i32(),
};
source.cache_key = Some((cache_size, bs_cache_key));
if let Some(mut request) = gpu_cache.request(&mut source.clip_data_handle) {
let data = ClipData::rounded_rect(
source.minimal_shadow_rect.size,
&source.shadow_radius,
ClipMode::Clip,
);
data.write(&mut request);
}
}
ClipItemKind::Rectangle { rect, mode } => {
if let Some(mut request) = gpu_cache.request(&mut self.gpu_cache_handle) {
let data = ClipData::uniform(rect.size, 0.0, mode);
data.write(&mut request);
}
}
ClipItemKind::RoundedRectangle { rect, ref radius, mode } => {
if let Some(mut request) = gpu_cache.request(&mut self.gpu_cache_handle) {
let data = ClipData::rounded_rect(rect.size, radius, mode);
data.write(&mut request);
}
}
}
}
}
/// The main clipping public interface that other modules access.
#[derive(MallocSizeOf)]
#[cfg_attr(feature = "capture", derive(Serialize))]
pub struct ClipStore {
pub clip_chain_nodes: Vec<ClipChainNode>,
pub clip_node_instances: Vec<ClipNodeInstance>,
active_clip_node_info: Vec<ClipNodeInfo>,
active_local_clip_rect: Option<LayoutRect>,
}
// A clip chain instance is what gets built for a given clip
// chain id + local primitive region + positioning node.
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
pub struct ClipChainInstance {
pub clips_range: ClipNodeRange,
// Combined clip rect for clips that are in the
// same coordinate system as the primitive.
pub local_clip_rect: LayoutRect,
pub has_non_local_clips: bool,
// If true, this clip chain requires allocation
// of a clip mask.
pub needs_mask: bool,
// Combined clip rect in picture space (may
// be more conservative that local_clip_rect).
pub pic_clip_rect: PictureRect,
// Space, in which the `pic_clip_rect` is defined.
pub pic_spatial_node_index: SpatialNodeIndex,
}
impl ClipChainInstance {
pub fn empty() -> Self {
ClipChainInstance {
clips_range: ClipNodeRange {
first: 0,
count: 0,
},
local_clip_rect: LayoutRect::zero(),
has_non_local_clips: false,
needs_mask: false,
pic_clip_rect: PictureRect::zero(),
pic_spatial_node_index: ROOT_SPATIAL_NODE_INDEX,
}
}
}
/// Maintains a (flattened) list of clips for a given level in the surface level stack.
#[derive(Debug)]
pub struct ClipChainLevel {
/// These clips will be handled when compositing this surface into the parent,
/// and can thus be ignored on the primitives that are drawn as part of this surface.
shared_clips: Vec<ClipDataHandle>,
/// Index of the first element in ClipChainStack::clip that belongs to this level.
first_clip_index: usize,
/// Used to sanity check push/pop balance.
initial_clip_counts_len: usize,
}
/// Maintains a stack of clip chain ids that are currently active,
/// when a clip exists on a picture that has no surface, and is passed
/// on down to the child primitive(s).
///
///
/// In order to avoid many small vector allocations, all clip chain ids are
/// stored in a single vector instead of per-level.
/// Since we only work with the top-most level of the stack, we only need to
/// know the first index in the clips vector that belongs to each level. The
/// last index for the top-most level is always the end of the clips array.
///
/// Likewise, we push several clip chain ids to the clips array at each
/// push_clip, and the number of clip chain ids removed during pop_clip
/// must match. This is done by having a separate stack of clip counts
/// in the clip-stack rather than per-level to avoid vector allocations.
///
/// ```ascii
/// +----+----+---
/// levels: | | | ...
/// +----+----+---
/// |first \
/// | \
/// | \
/// +--+--+--+--+--+--+--
/// clips: | | | | | | | ...
/// +--+--+--+--+--+--+--
/// | / /
/// | / /
/// | / /
/// +--+--+--+--
/// clip_counts: | 1| 2| 2| ...
/// +--+--+--+--
/// ```
pub struct ClipChainStack {
/// A stack of clip chain lists. Each time a new surface is pushed,
/// a new level is added. Each time a new picture without surface is
/// pushed, it adds the picture clip chain to the clips vector in the
/// range belonging to the level (always the top-most level, so always
/// at the end of the clips array).
levels: Vec<ClipChainLevel>,
/// The actual stack of clip ids.
clips: Vec<ClipChainId>,
/// How many clip ids to pop from the vector each time we call pop_clip.
clip_counts: Vec<usize>,
}
impl ClipChainStack {
pub fn new() -> Self {
ClipChainStack {
levels: vec![
ClipChainLevel {
shared_clips: Vec::new(),
first_clip_index: 0,
initial_clip_counts_len: 0,
}
],
clips: Vec::new(),
clip_counts: Vec::new(),
}
}
/// Push a clip chain root onto the currently active list.
pub fn push_clip(
&mut self,
clip_chain_id: ClipChainId,
clip_store: &ClipStore,
) {
let mut clip_count = 0;
let mut current_clip_chain_id = clip_chain_id;
while current_clip_chain_id != ClipChainId::NONE {
let clip_chain_node = &clip_store.clip_chain_nodes[current_clip_chain_id.0 as usize];
let clip_uid = clip_chain_node.handle.uid();
// The clip is required, so long as it doesn't exist in any of the shared_clips
// array from this or any parent surfaces.
// TODO(gw): We could consider making this a HashSet if it ever shows up in
// profiles, but the typical array length is 2-3 elements.
let mut valid_clip = true;
for level in &self.levels {
if level.shared_clips.iter().any(|handle| {
handle.uid() == clip_uid
}) {
valid_clip = false;
break;
}
}
if valid_clip {
self.clips.push(current_clip_chain_id);
clip_count += 1;
}
current_clip_chain_id = clip_chain_node.parent_clip_chain_id;
}
self.clip_counts.push(clip_count);
}
/// Pop a clip chain root from the currently active list.
pub fn pop_clip(&mut self) {
let count = self.clip_counts.pop().unwrap();
for _ in 0 .. count {
self.clips.pop().unwrap();
}
}
/// When a surface is created, it takes all clips and establishes a new
/// stack of clips to be propagated.
pub fn push_surface(
&mut self,
shared_clips: &[ClipDataHandle],
) {
let level = ClipChainLevel {
shared_clips: shared_clips.to_vec(),
first_clip_index: self.clips.len(),
initial_clip_counts_len: self.clip_counts.len(),
};
self.levels.push(level);
}
/// Pop a surface from the clip chain stack
pub fn pop_surface(&mut self) {
let level = self.levels.pop().unwrap();
assert!(self.clip_counts.len() == level.initial_clip_counts_len);
assert!(self.clips.len() == level.first_clip_index);
}
/// Get the list of currently active clip chains
pub fn current_clips_array(&self) -> &[ClipChainId] {
let first = self.levels.last().unwrap().first_clip_index;
&self.clips[first..]
}
}
impl ClipStore {
pub fn new() -> Self {
ClipStore {
clip_chain_nodes: Vec::new(),
clip_node_instances: Vec::new(),
active_clip_node_info: Vec::new(),
active_local_clip_rect: None,
}
}
pub fn get_clip_chain(&self, clip_chain_id: ClipChainId) -> &ClipChainNode {
&self.clip_chain_nodes[clip_chain_id.0 as usize]
}
pub fn add_clip_chain_node(
&mut self,
handle: ClipDataHandle,
parent_clip_chain_id: ClipChainId,
) -> ClipChainId {
let id = ClipChainId(self.clip_chain_nodes.len() as u32);
self.clip_chain_nodes.push(ClipChainNode {
handle,
parent_clip_chain_id,
});
id
}
pub fn get_instance_from_range(
&self,
node_range: &ClipNodeRange,
index: u32,
) -> &ClipNodeInstance {
&self.clip_node_instances[(node_range.first + index) as usize]
}
/// Setup the active clip chains for building a clip chain instance.
pub fn set_active_clips(
&mut self,
local_prim_clip_rect: LayoutRect,
spatial_node_index: SpatialNodeIndex,
clip_chains: &[ClipChainId],
spatial_tree: &SpatialTree,
clip_data_store: &mut ClipDataStore,
) {
self.active_clip_node_info.clear();
self.active_local_clip_rect = None;
let mut local_clip_rect = local_prim_clip_rect;
for clip_chain_id in clip_chains {
let clip_chain_node = &self.clip_chain_nodes[clip_chain_id.0 as usize];
if !add_clip_node_to_current_chain(
clip_chain_node,
spatial_node_index,
&mut local_clip_rect,
&mut self.active_clip_node_info,
clip_data_store,
spatial_tree,
) {
return;
}
}
self.active_local_clip_rect = Some(local_clip_rect);
}
/// Setup the active clip chains, based on an existing primitive clip chain instance.
pub fn set_active_clips_from_clip_chain(
&mut self,
prim_clip_chain: &ClipChainInstance,
prim_spatial_node_index: SpatialNodeIndex,
spatial_tree: &SpatialTree,
clip_data_store: &ClipDataStore,
) {
// TODO(gw): Although this does less work than set_active_clips(), it does
// still do some unnecessary work (such as the clip space conversion).
// We could consider optimizing this if it ever shows up in a profile.
self.active_clip_node_info.clear();
self.active_local_clip_rect = Some(prim_clip_chain.local_clip_rect);
let clip_instances = &self
.clip_node_instances[prim_clip_chain.clips_range.to_range()];
for clip_instance in clip_instances {
let clip_node = &clip_data_store[clip_instance.handle];
let conversion = ClipSpaceConversion::new(
prim_spatial_node_index,
clip_node.item.spatial_node_index,
spatial_tree,
);
self.active_clip_node_info.push(ClipNodeInfo {
handle: clip_instance.handle,
conversion,
});
}
}
/// The main interface external code uses. Given a local primitive, positioning
/// information, and a clip chain id, build an optimized clip chain instance.
pub fn build_clip_chain_instance(
&mut self,
local_prim_rect: LayoutRect,
prim_to_pic_mapper: &SpaceMapper<LayoutPixel, PicturePixel>,
pic_to_world_mapper: &SpaceMapper<PicturePixel, WorldPixel>,
spatial_tree: &SpatialTree,
gpu_cache: &mut GpuCache,
resource_cache: &mut ResourceCache,
device_pixel_scale: DevicePixelScale,
world_rect: &WorldRect,
clip_data_store: &mut ClipDataStore,
request_resources: bool,
is_chased: bool,
) -> Option<ClipChainInstance> {
let local_clip_rect = match self.active_local_clip_rect {
Some(rect) => rect,
None => return None,
};
if is_chased {
println!("\tbuilding clip chain instance with local rect {:?}", local_prim_rect);
}
let local_bounding_rect = local_prim_rect.intersection(&local_clip_rect)?;
let pic_clip_rect = prim_to_pic_mapper.map(&local_bounding_rect)?;
let world_clip_rect = pic_to_world_mapper.map(&pic_clip_rect)?;
// Now, we've collected all the clip nodes that *potentially* affect this
// primitive region, and reduced the size of the prim region as much as possible.
// Run through the clip nodes, and see which ones affect this prim region.
let first_clip_node_index = self.clip_node_instances.len() as u32;
let mut has_non_local_clips = false;
let mut needs_mask = false;
// For each potential clip node
for node_info in self.active_clip_node_info.drain(..) {
let node = &mut clip_data_store[node_info.handle];
// See how this clip affects the prim region.
let clip_result = match node_info.conversion {
ClipSpaceConversion::Local => {
node.item.kind.get_clip_result(&local_bounding_rect)
}
ClipSpaceConversion::ScaleOffset(ref scale_offset) => {
has_non_local_clips = true;
node.item.kind.get_clip_result(&scale_offset.unmap_rect(&local_bounding_rect))
}
ClipSpaceConversion::Transform(ref transform) => {
has_non_local_clips = true;
node.item.kind.get_clip_result_complex(
transform,
&world_clip_rect,
world_rect,
)
}
};
if is_chased {
println!("\t\tclip {:?}", node.item);
println!("\t\tflags {:?}, resulted in {:?}", node_info.conversion.to_flags(), clip_result);
}
match clip_result {
ClipResult::Accept => {
// Doesn't affect the primitive at all, so skip adding to list
}
ClipResult::Reject => {
// Completely clips the supplied prim rect
return None;
}
ClipResult::Partial => {
// Needs a mask -> add to clip node indices
// TODO(gw): Ensure this only runs once on each node per frame?
node.update(
gpu_cache,
device_pixel_scale,
);
// Create the clip node instance for this clip node
if let Some(instance) = node_info.create_instance(
node,
&local_bounding_rect,
gpu_cache,
resource_cache,
spatial_tree,
request_resources,
) {
// As a special case, a partial accept of a clip rect that is
// in the same coordinate system as the primitive doesn't need
// a clip mask. Instead, it can be handled by the primitive
// vertex shader as part of the local clip rect. This is an
// important optimization for reducing the number of clip
// masks that are allocated on common pages.
needs_mask |= match node.item.kind {
ClipItemKind::Rectangle { mode: ClipMode::ClipOut, .. } |
ClipItemKind::RoundedRectangle { .. } |
ClipItemKind::Image { .. } |
ClipItemKind::BoxShadow { .. } => {
true
}
ClipItemKind::Rectangle { mode: ClipMode::Clip, .. } => {
!instance.flags.contains(ClipNodeFlags::SAME_COORD_SYSTEM)
}
};
// Store this in the index buffer for this clip chain instance.
self.clip_node_instances.push(instance);
}
}
}
}
// Get the range identifying the clip nodes in the index buffer.
let clips_range = ClipNodeRange {
first: first_clip_node_index,
count: self.clip_node_instances.len() as u32 - first_clip_node_index,
};
// Return a valid clip chain instance
Some(ClipChainInstance {
clips_range,
has_non_local_clips,
local_clip_rect,
pic_clip_rect,
pic_spatial_node_index: prim_to_pic_mapper.ref_spatial_node_index,
needs_mask,
})
}
pub fn clear_old_instances(&mut self) {
self.clip_node_instances.clear();
}
}
pub struct ComplexTranslateIter<I> {
source: I,
offset: LayoutVector2D,
}
impl<I: Iterator<Item = ComplexClipRegion>> Iterator for ComplexTranslateIter<I> {
type Item = ComplexClipRegion;
fn next(&mut self) -> Option<Self::Item> {
self.source
.next()
.map(|mut complex| {
complex.rect = complex.rect.translate(self.offset);
complex
})
}
}
#[derive(Clone, Debug)]
pub struct ClipRegion<I> {
pub main: LayoutRect,
pub image_mask: Option<ImageMask>,
pub complex_clips: I,
}
impl<J> ClipRegion<ComplexTranslateIter<J>> {
pub fn create_for_clip_node(
rect: LayoutRect,
complex_clips: J,
mut image_mask: Option<ImageMask>,
reference_frame_relative_offset: &LayoutVector2D,
) -> Self
where
J: Iterator<Item = ComplexClipRegion>
{
if let Some(ref mut image_mask) = image_mask {
image_mask.rect = image_mask.rect.translate(*reference_frame_relative_offset);
}
ClipRegion {
main: rect.translate(*reference_frame_relative_offset),
image_mask,
complex_clips: ComplexTranslateIter {
source: complex_clips,
offset: *reference_frame_relative_offset,
},
}
}
}
impl ClipRegion<Option<ComplexClipRegion>> {