-
Notifications
You must be signed in to change notification settings - Fork 265
/
render_task.rs
2510 lines (2235 loc) · 89.5 KB
/
render_task.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::{ImageDescriptor, FilterPrimitive, FilterPrimitiveInput, FilterPrimitiveKind};
use api::{LineStyle, LineOrientation, ClipMode, DirtyRect, MixBlendMode, ColorF, ColorSpace};
use api::units::*;
use crate::border::BorderSegmentCacheKey;
use crate::box_shadow::{BoxShadowCacheKey};
use crate::clip::{ClipDataStore, ClipItem, ClipStore, ClipNodeRange, ClipNodeFlags};
use crate::clip_scroll_tree::SpatialNodeIndex;
use crate::device::TextureFilter;
use crate::filterdata::SFilterData;
use crate::frame_builder::FrameBuilderConfig;
use crate::freelist::{FreeList, FreeListHandle, WeakFreeListHandle};
use crate::gpu_cache::{GpuCache, GpuCacheAddress, GpuCacheHandle};
use crate::gpu_types::{BorderInstance, ImageSource, UvRectKind, SnapOffsets};
use crate::internal_types::{CacheTextureId, FastHashMap, LayerIndex, SavedTargetIndex, TextureSource};
use crate::prim_store::{PictureIndex, PrimitiveVisibilityMask};
use crate::prim_store::image::ImageCacheKey;
use crate::prim_store::gradient::{GRADIENT_FP_STOPS, GradientCacheKey, GradientStopKey};
use crate::prim_store::line_dec::LineDecorationCacheKey;
#[cfg(feature = "debugger")]
use crate::print_tree::{PrintTreePrinter};
use crate::render_backend::FrameId;
use crate::resource_cache::{CacheItem, ResourceCache};
use std::{ops, mem, usize, f32, i32, u32};
use crate::texture_cache::{TextureCache, TextureCacheHandle, Eviction};
use crate::tiling::{RenderPass, RenderTargetIndex};
use std::io;
const RENDER_TASK_SIZE_SANITY_CHECK: i32 = 16000;
const FLOATS_PER_RENDER_TASK_INFO: usize = 8;
pub const MAX_BLUR_STD_DEVIATION: f32 = 4.0;
pub const MIN_DOWNSCALING_RT_SIZE: i32 = 8;
fn render_task_sanity_check(size: &DeviceIntSize) {
if size.width > RENDER_TASK_SIZE_SANITY_CHECK ||
size.height > RENDER_TASK_SIZE_SANITY_CHECK {
error!("Attempting to create a render task of size {}x{}", size.width, size.height);
panic!();
}
}
/// A tag used to identify the output format of a `RenderTarget`.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum RenderTargetKind {
Color, // RGBA8
Alpha, // R8
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct RenderTaskId {
pub index: u32,
#[cfg(debug_assertions)]
#[cfg_attr(feature = "replay", serde(default = "FrameId::first"))]
frame_id: FrameId,
}
impl RenderTaskId {
pub const INVALID: RenderTaskId = RenderTaskId {
index: u32::MAX,
#[cfg(debug_assertions)]
frame_id: FrameId::INVALID,
};
}
#[derive(Debug, Copy, Clone, PartialEq)]
#[repr(C)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct RenderTaskAddress(pub u16);
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct RenderTaskGraph {
pub tasks: Vec<RenderTask>,
pub task_data: Vec<RenderTaskData>,
/// Tasks that don't have dependencies, and that may be shared between
/// picture tasks.
///
/// We render these unconditionally before-rendering the rest of the tree.
pub cacheable_render_tasks: Vec<RenderTaskId>,
next_saved: SavedTargetIndex,
frame_id: FrameId,
}
#[derive(Debug)]
pub struct RenderTaskGraphCounters {
tasks_len: usize,
task_data_len: usize,
cacheable_render_tasks_len: usize,
}
impl RenderTaskGraphCounters {
pub fn new() -> Self {
RenderTaskGraphCounters {
tasks_len: 0,
task_data_len: 0,
cacheable_render_tasks_len: 0,
}
}
}
impl RenderTaskGraph {
pub fn new(frame_id: FrameId, counters: &RenderTaskGraphCounters) -> Self {
// Preallocate a little more than what we needed in the previous frame so that small variations
// in the number of items don't cause us to constantly reallocate.
let extra_items = 8;
RenderTaskGraph {
tasks: Vec::with_capacity(counters.tasks_len + extra_items),
task_data: Vec::with_capacity(counters.task_data_len + extra_items),
cacheable_render_tasks: Vec::with_capacity(counters.cacheable_render_tasks_len + extra_items),
next_saved: SavedTargetIndex(0),
frame_id,
}
}
pub fn counters(&self) -> RenderTaskGraphCounters {
RenderTaskGraphCounters {
tasks_len: self.tasks.len(),
task_data_len: self.task_data.len(),
cacheable_render_tasks_len: self.cacheable_render_tasks.len(),
}
}
pub fn add(&mut self, task: RenderTask) -> RenderTaskId {
let index = self.tasks.len() as _;
self.tasks.push(task);
RenderTaskId {
index,
#[cfg(debug_assertions)]
frame_id: self.frame_id,
}
}
/// Express a render task dependency between a parent and child task.
/// This is used to assign tasks to render passes.
pub fn add_dependency(
&mut self,
parent_id: RenderTaskId,
child_id: RenderTaskId,
) {
let parent = &mut self[parent_id];
parent.children.push(child_id);
}
/// Assign this frame's render tasks to render passes ordered so that passes appear
/// earlier than the ones that depend on them.
pub fn generate_passes(
&mut self,
main_render_task: Option<RenderTaskId>,
screen_size: DeviceIntSize,
gpu_supports_fast_clears: bool,
) -> Vec<RenderPass> {
let mut passes = Vec::new();
if !self.cacheable_render_tasks.is_empty() {
self.generate_passes_impl(
&self.cacheable_render_tasks[..],
screen_size,
gpu_supports_fast_clears,
false,
&mut passes,
);
}
if let Some(main_task) = main_render_task {
self.generate_passes_impl(
&[main_task],
screen_size,
gpu_supports_fast_clears,
true,
&mut passes,
);
}
self.resolve_target_conflicts(&mut passes);
passes
}
/// Assign the render tasks from the tree rooted at root_task to render passes and
/// append them to the `passes` vector so that the passes that we depend on end up
/// _earlier_ in the pass list.
fn generate_passes_impl(
&self,
root_tasks: &[RenderTaskId],
screen_size: DeviceIntSize,
gpu_supports_fast_clears: bool,
for_main_framebuffer: bool,
passes: &mut Vec<RenderPass>,
) {
// We recursively visit tasks from the roots (main and cached render tasks), to figure out
// which ones affect the frame and which passes they should be assigned to.
//
// We track the maximum depth of each task (how far it is from the roots) as well as the total
// maximum depth of the graph to determine each tasks' pass index. In a nutshell, depth 0 is
// for the last render pass (for example the main framebuffer), while the highest depth
// corresponds to the first pass.
fn assign_task_depth(
tasks: &[RenderTask],
task_id: RenderTaskId,
task_depth: i32,
task_max_depths: &mut [i32],
max_depth: &mut i32,
) {
*max_depth = std::cmp::max(*max_depth, task_depth);
let task_max_depth = &mut task_max_depths[task_id.index as usize];
if task_depth > *task_max_depth {
*task_max_depth = task_depth;
} else {
// If this task has already been processed at a larger depth,
// there is no need to process it again.
return;
}
let task = &tasks[task_id.index as usize];
for child in &task.children {
assign_task_depth(
tasks,
*child,
task_depth + 1,
task_max_depths,
max_depth,
);
}
}
// The maximum depth of each task. Values that are still equal to -1 after recursively visiting
// the nodes correspond to tasks that don't contribute to the frame.
let mut task_max_depths = vec![-1; self.tasks.len()];
let mut max_depth = 0;
for root_task in root_tasks {
assign_task_depth(
&self.tasks,
*root_task,
0,
&mut task_max_depths,
&mut max_depth,
);
}
let offset = passes.len();
passes.reserve(max_depth as usize + 1);
for _ in 0..max_depth {
passes.push(RenderPass::new_off_screen(screen_size, gpu_supports_fast_clears));
}
if for_main_framebuffer {
passes.push(RenderPass::new_main_framebuffer(screen_size, gpu_supports_fast_clears));
} else {
passes.push(RenderPass::new_off_screen(screen_size, gpu_supports_fast_clears));
}
// Assign tasks to their render passes.
for task_index in 0..self.tasks.len() {
if task_max_depths[task_index] < 0 {
// The task wasn't visited, it means it doesn't contribute to this frame.
continue;
}
let pass_index = offset + (max_depth - task_max_depths[task_index]) as usize;
let task_id = RenderTaskId {
index: task_index as u32,
#[cfg(debug_assertions)]
frame_id: self.frame_id,
};
let task = &self.tasks[task_index];
passes[pass_index as usize].add_render_task(
task_id,
task.get_dynamic_size(),
task.target_kind(),
&task.location,
);
}
}
/// Resolve conflicts between the generated passes and the limitiations of our target
/// allocation scheme.
///
/// The render task graph operates with a ping-pong target allocation scheme where
/// a set of targets is written to by even passes and a different set of targets is
/// written to by odd passes.
/// Since tasks cannot read and write the same target, we can run into issues if a
/// task pass in N + 2 reads the result of a task in pass N.
/// To avoid such cases have to insert blit tasks to copy the content of the task
/// into pass N + 1 which is readable by pass N + 2.
///
/// In addition, allocated rects of pass N are currently not tracked and can be
/// overwritten by allocations in later passes on the same target, unless the task
/// has been marked for saving, which perserves the allocated rect until the end of
/// the frame. This is a big hammer, hopefully we won't need to mark many passes
/// for saving. A better solution would be to track allocations through the entire
/// graph, there is a prototype of that in https://github.com/nical/toy-render-graph/
fn resolve_target_conflicts(&mut self, passes: &mut [RenderPass]) {
// Keep track of blit tasks we inserted to avoid adding several blits for the same
// task.
let mut task_redirects = vec![None; self.tasks.len()];
let mut task_passes = vec![-1; self.tasks.len()];
for pass_index in 0..passes.len() {
for task in &passes[pass_index].tasks {
task_passes[task.index as usize] = pass_index as i32;
}
}
for task_index in 0..self.tasks.len() {
if task_passes[task_index] < 0 {
// The task doesn't contribute to this frame.
continue;
}
let pass_index = task_passes[task_index];
// Go through each dependency and check whether they belong
// to a pass that uses the same targets and/or are more than
// one pass behind.
for nth_child in 0..self.tasks[task_index].children.len() {
let child_task_index = self.tasks[task_index].children[nth_child].index as usize;
let child_pass_index = task_passes[child_task_index];
if child_pass_index == pass_index - 1 {
// This should be the most common case.
continue;
}
// TODO: Picture tasks don't support having their dependency tasks redirected.
// Pictures store their respective render task(s) on their SurfaceInfo.
// We cannot blit the picture task here because we would need to update the
// surface's render tasks, but we don't have access to that info here.
// Also a surface may be expecting a picture task and not a blit task, so
// even if we could update the surface's render task(s), it might cause other issues.
// For now we mark the task to be saved rather than trying to redirect to a blit task.
let task_is_picture = if let RenderTaskKind::Picture(..) = self.tasks[task_index].kind {
true
} else {
false
};
if child_pass_index % 2 != pass_index % 2 || task_is_picture {
// The tasks and its dependency aren't on the same targets,
// but the dependency needs to be kept alive.
self.tasks[child_task_index].mark_for_saving();
continue;
}
if let Some(blit_id) = task_redirects[child_task_index] {
// We already resolved a similar conflict with a blit task,
// reuse the same blit instead of creating a new one.
self.tasks[task_index].children[nth_child] = blit_id;
// Mark for saving if the blit is more than pass appart from
// our task.
if child_pass_index < pass_index - 2 {
self.tasks[blit_id.index as usize].mark_for_saving();
}
continue;
}
// Our dependency is an even number of passes behind, need
// to insert a blit to ensure we don't read and write from
// the same target.
let child_task_id = RenderTaskId {
index: child_task_index as u32,
#[cfg(debug_assertions)]
frame_id: self.frame_id,
};
let mut blit = RenderTask::new_blit(
self.tasks[child_task_index].location.size(),
BlitSource::RenderTask { task_id: child_task_id },
);
// Mark for saving if the blit is more than pass appart from
// our task.
if child_pass_index < pass_index - 2 {
blit.mark_for_saving();
}
let blit_id = RenderTaskId {
index: self.tasks.len() as u32,
#[cfg(debug_assertions)]
frame_id: self.frame_id,
};
self.tasks.push(blit);
passes[child_pass_index as usize + 1].tasks.push(blit_id);
self.tasks[task_index].children[nth_child] = blit_id;
task_redirects[child_task_index] = Some(blit_id);
}
}
}
pub fn get_task_address(&self, id: RenderTaskId) -> RenderTaskAddress {
#[cfg(all(debug_assertions, not(feature = "replay")))]
debug_assert_eq!(self.frame_id, id.frame_id);
RenderTaskAddress(id.index as u16)
}
pub fn write_task_data(&mut self) {
for task in &self.tasks {
self.task_data.push(task.write_task_data());
}
}
pub fn save_target(&mut self) -> SavedTargetIndex {
let id = self.next_saved;
self.next_saved.0 += 1;
id
}
#[cfg(debug_assertions)]
pub fn frame_id(&self) -> FrameId {
self.frame_id
}
}
impl ops::Index<RenderTaskId> for RenderTaskGraph {
type Output = RenderTask;
fn index(&self, id: RenderTaskId) -> &RenderTask {
#[cfg(all(debug_assertions, not(feature = "replay")))]
debug_assert_eq!(self.frame_id, id.frame_id);
&self.tasks[id.index as usize]
}
}
impl ops::IndexMut<RenderTaskId> for RenderTaskGraph {
fn index_mut(&mut self, id: RenderTaskId) -> &mut RenderTask {
#[cfg(all(debug_assertions, not(feature = "replay")))]
debug_assert_eq!(self.frame_id, id.frame_id);
&mut self.tasks[id.index as usize]
}
}
/// Identifies the output buffer location for a given `RenderTask`.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum RenderTaskLocation {
/// The `RenderTask` should be drawn to a fixed region in a specific render
/// target. This is used for the root `RenderTask`, where the main
/// framebuffer is used as the render target.
Fixed(DeviceIntRect),
/// The `RenderTask` should be drawn to a target provided by the atlas
/// allocator. This is the most common case.
///
/// The second member specifies the width and height of the task
/// output, and the first member is initially left as `None`. During the
/// build phase, we invoke `RenderTargetList::alloc()` and store the
/// resulting location in the first member. That location identifies the
/// render target and the offset of the allocated region within that target.
Dynamic(Option<(DeviceIntPoint, RenderTargetIndex)>, DeviceIntSize),
/// The output of the `RenderTask` will be persisted beyond this frame, and
/// thus should be drawn into the `TextureCache`.
TextureCache {
/// Which texture in the texture cache should be drawn into.
texture: CacheTextureId,
/// The target layer in the above texture.
layer: LayerIndex,
/// The target region within the above layer.
rect: DeviceIntRect,
},
/// This render task will be drawn to a picture cache texture that is
/// persisted between both frames and scenes, if the content remains valid.
PictureCache {
/// The texture ID to draw to.
texture: TextureSource,
/// Slice index in the texture array to draw to.
layer: i32,
/// Size in device pixels of this picture cache tile.
size: DeviceIntSize,
},
}
impl RenderTaskLocation {
/// Returns true if this is a dynamic location.
pub fn is_dynamic(&self) -> bool {
match *self {
RenderTaskLocation::Dynamic(..) => true,
_ => false,
}
}
pub fn size(&self) -> DeviceIntSize {
match self {
RenderTaskLocation::Fixed(rect) => rect.size,
RenderTaskLocation::Dynamic(_, size) => *size,
RenderTaskLocation::TextureCache { rect, .. } => rect.size,
RenderTaskLocation::PictureCache { size, .. } => *size,
}
}
pub fn to_source_rect(&self) -> (DeviceIntRect, LayerIndex) {
match *self {
RenderTaskLocation::Fixed(rect) => (rect, 0),
RenderTaskLocation::Dynamic(None, _) => panic!("Expected position to be set for the task!"),
RenderTaskLocation::Dynamic(Some((origin, layer)), size) => (DeviceIntRect::new(origin, size), layer.0 as LayerIndex),
RenderTaskLocation::TextureCache { rect, layer, .. } => (rect, layer),
RenderTaskLocation::PictureCache { layer, size, .. } => (size.into(), layer as LayerIndex),
}
}
}
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct CacheMaskTask {
pub actual_rect: DeviceIntRect,
pub root_spatial_node_index: SpatialNodeIndex,
pub clip_node_range: ClipNodeRange,
pub snap_offsets: SnapOffsets,
pub device_pixel_scale: DevicePixelScale,
}
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct ClipRegionTask {
pub clip_data_address: GpuCacheAddress,
pub local_pos: LayoutPoint,
pub device_pixel_scale: DevicePixelScale,
}
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct PictureTask {
pub pic_index: PictureIndex,
pub can_merge: bool,
pub content_origin: DeviceIntPoint,
pub uv_rect_handle: GpuCacheHandle,
pub surface_spatial_node_index: SpatialNodeIndex,
uv_rect_kind: UvRectKind,
device_pixel_scale: DevicePixelScale,
/// A bitfield that describes which dirty regions should be included
/// in batches built for this picture task.
pub vis_mask: PrimitiveVisibilityMask,
}
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct BlurTask {
pub blur_std_deviation: f32,
pub target_kind: RenderTargetKind,
pub uv_rect_handle: GpuCacheHandle,
pub blur_region: DeviceIntSize,
uv_rect_kind: UvRectKind,
}
impl BlurTask {
#[cfg(feature = "debugger")]
fn print_with<T: PrintTreePrinter>(&self, pt: &mut T) {
pt.add_item(format!("std deviation: {}", self.blur_std_deviation));
pt.add_item(format!("target: {:?}", self.target_kind));
}
}
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct ScalingTask {
pub target_kind: RenderTargetKind,
pub image: Option<ImageCacheKey>,
uv_rect_kind: UvRectKind,
pub padding: DeviceIntSideOffsets,
}
// Where the source data for a blit task can be found.
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum BlitSource {
Image {
key: ImageCacheKey,
},
RenderTask {
task_id: RenderTaskId,
},
}
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct BorderTask {
pub instances: Vec<BorderInstance>,
}
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct BlitTask {
pub source: BlitSource,
pub padding: DeviceIntSideOffsets,
}
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct GradientTask {
pub stops: [GradientStopKey; GRADIENT_FP_STOPS],
pub orientation: LineOrientation,
pub start_point: f32,
pub end_point: f32,
}
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct LineDecorationTask {
pub wavy_line_thickness: f32,
pub style: LineStyle,
pub orientation: LineOrientation,
pub local_size: LayoutSize,
}
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum SvgFilterInfo {
Blend(MixBlendMode),
Flood(ColorF),
LinearToSrgb,
SrgbToLinear,
Opacity(f32),
ColorMatrix(Box<[f32; 20]>),
DropShadow(ColorF),
Offset(DeviceVector2D),
ComponentTransfer(SFilterData),
// TODO: This is used as a hack to ensure that a blur task's input is always in the blur's previous pass.
Identity,
}
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct SvgFilterTask {
pub info: SvgFilterInfo,
pub extra_gpu_cache_handle: Option<GpuCacheHandle>,
pub uv_rect_handle: GpuCacheHandle,
uv_rect_kind: UvRectKind,
}
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct RenderTaskData {
pub data: [f32; FLOATS_PER_RENDER_TASK_INFO],
}
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum RenderTaskKind {
Picture(PictureTask),
CacheMask(CacheMaskTask),
ClipRegion(ClipRegionTask),
VerticalBlur(BlurTask),
HorizontalBlur(BlurTask),
Readback(DeviceIntRect),
Scaling(ScalingTask),
Blit(BlitTask),
Border(BorderTask),
LineDecoration(LineDecorationTask),
Gradient(GradientTask),
SvgFilter(SvgFilterTask),
#[cfg(test)]
Test(RenderTargetKind),
}
impl RenderTaskKind {
pub fn as_str(&self) -> &'static str {
match *self {
RenderTaskKind::Picture(..) => "Picture",
RenderTaskKind::CacheMask(..) => "CacheMask",
RenderTaskKind::ClipRegion(..) => "ClipRegion",
RenderTaskKind::VerticalBlur(..) => "VerticalBlur",
RenderTaskKind::HorizontalBlur(..) => "HorizontalBlur",
RenderTaskKind::Readback(..) => "Readback",
RenderTaskKind::Scaling(..) => "Scaling",
RenderTaskKind::Blit(..) => "Blit",
RenderTaskKind::Border(..) => "Border",
RenderTaskKind::LineDecoration(..) => "LineDecoration",
RenderTaskKind::Gradient(..) => "Gradient",
RenderTaskKind::SvgFilter(..) => "SvgFilter",
#[cfg(test)]
RenderTaskKind::Test(..) => "Test",
}
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum ClearMode {
// Applicable to color and alpha targets.
Zero,
One,
/// This task doesn't care what it is cleared to - it will completely overwrite it.
DontCare,
// Applicable to color targets only.
Transparent,
}
/// In order to avoid duplicating the down-scaling and blur passes when a picture has several blurs,
/// we use a local (primitive-level) cache of the render tasks generated for a single shadowed primitive
/// in a single frame.
pub type BlurTaskCache = FastHashMap<BlurTaskKey, RenderTaskId>;
/// Since we only use it within a single primitive, the key only needs to contain the down-scaling level
/// and the blur std deviation.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum BlurTaskKey {
DownScale(u32),
Blur { downscale_level: u32, stddev_x: u32, stddev_y: u32 },
}
impl BlurTaskKey {
fn downscale_and_blur(downscale_level: u32, blur_stddev: DeviceSize) -> Self {
// Quantise the std deviations and store it as integers to work around
// Eq and Hash's f32 allergy.
// The blur radius is rounded before RenderTask::new_blur so we don't need
// a lot of precision.
const QUANTIZATION_FACTOR: f32 = 1024.0;
let stddev_x = (blur_stddev.width * QUANTIZATION_FACTOR) as u32;
let stddev_y = (blur_stddev.height * QUANTIZATION_FACTOR) as u32;
BlurTaskKey::Blur { downscale_level, stddev_x, stddev_y }
}
}
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct RenderTask {
pub location: RenderTaskLocation,
pub children: Vec<RenderTaskId>,
pub kind: RenderTaskKind,
pub clear_mode: ClearMode,
pub saved_index: Option<SavedTargetIndex>,
}
impl RenderTask {
#[inline]
pub fn with_dynamic_location(
size: DeviceIntSize,
children: Vec<RenderTaskId>,
kind: RenderTaskKind,
clear_mode: ClearMode,
) -> Self {
render_task_sanity_check(&size);
RenderTask {
location: RenderTaskLocation::Dynamic(None, size),
children,
kind,
clear_mode,
saved_index: None,
}
}
#[cfg(test)]
pub fn new_test(
target: RenderTargetKind,
location: RenderTaskLocation,
children: Vec<RenderTaskId>,
) -> Self {
RenderTask {
location,
children,
kind: RenderTaskKind::Test(target),
clear_mode: ClearMode::Transparent,
saved_index: None,
}
}
pub fn new_picture(
location: RenderTaskLocation,
unclipped_size: DeviceSize,
pic_index: PictureIndex,
content_origin: DeviceIntPoint,
uv_rect_kind: UvRectKind,
surface_spatial_node_index: SpatialNodeIndex,
device_pixel_scale: DevicePixelScale,
vis_mask: PrimitiveVisibilityMask,
) -> Self {
let size = match location {
RenderTaskLocation::Dynamic(_, size) => size,
RenderTaskLocation::Fixed(rect) => rect.size,
RenderTaskLocation::TextureCache { rect, .. } => rect.size,
RenderTaskLocation::PictureCache { size, .. } => size,
};
render_task_sanity_check(&size);
let can_merge = size.width as f32 >= unclipped_size.width &&
size.height as f32 >= unclipped_size.height;
RenderTask {
location,
children: Vec::new(),
kind: RenderTaskKind::Picture(PictureTask {
pic_index,
content_origin,
can_merge,
uv_rect_handle: GpuCacheHandle::new(),
uv_rect_kind,
surface_spatial_node_index,
device_pixel_scale,
vis_mask,
}),
clear_mode: ClearMode::Transparent,
saved_index: None,
}
}
pub fn new_gradient(
size: DeviceIntSize,
stops: [GradientStopKey; GRADIENT_FP_STOPS],
orientation: LineOrientation,
start_point: f32,
end_point: f32,
) -> Self {
RenderTask::with_dynamic_location(
size,
Vec::new(),
RenderTaskKind::Gradient(GradientTask {
stops,
orientation,
start_point,
end_point,
}),
ClearMode::DontCare,
)
}
pub fn new_readback(screen_rect: DeviceIntRect) -> Self {
RenderTask::with_dynamic_location(
screen_rect.size,
Vec::new(),
RenderTaskKind::Readback(screen_rect),
ClearMode::Transparent,
)
}
pub fn new_blit(
size: DeviceIntSize,
source: BlitSource,
) -> Self {
RenderTask::new_blit_with_padding(size, DeviceIntSideOffsets::zero(), source)
}
pub fn new_blit_with_padding(
padded_size: DeviceIntSize,
padding: DeviceIntSideOffsets,
source: BlitSource,
) -> Self {
// If this blit uses a render task as a source,
// ensure it's added as a child task. This will
// ensure it gets allocated in the correct pass
// and made available as an input when this task
// executes.
let children = match source {
BlitSource::RenderTask { task_id } => vec![task_id],
BlitSource::Image { .. } => vec![],
};
RenderTask::with_dynamic_location(
padded_size,
children,
RenderTaskKind::Blit(BlitTask {
source,
padding,
}),
ClearMode::Transparent,
)
}
pub fn new_line_decoration(
size: DeviceIntSize,
style: LineStyle,
orientation: LineOrientation,
wavy_line_thickness: f32,
local_size: LayoutSize,
) -> Self {
RenderTask::with_dynamic_location(
size,
Vec::new(),
RenderTaskKind::LineDecoration(LineDecorationTask {
style,
orientation,
wavy_line_thickness,
local_size,
}),
ClearMode::Transparent,
)
}
pub fn new_mask(
outer_rect: DeviceIntRect,
clip_node_range: ClipNodeRange,
root_spatial_node_index: SpatialNodeIndex,
clip_store: &mut ClipStore,
gpu_cache: &mut GpuCache,
resource_cache: &mut ResourceCache,
render_tasks: &mut RenderTaskGraph,
clip_data_store: &mut ClipDataStore,
snap_offsets: SnapOffsets,
device_pixel_scale: DevicePixelScale,
fb_config: &FrameBuilderConfig,
) -> Self {
// Step through the clip sources that make up this mask. If we find
// any box-shadow clip sources, request that image from the render
// task cache. This allows the blurred box-shadow rect to be cached
// in the texture cache across frames.
// TODO(gw): Consider moving this logic outside this function, especially
// as we add more clip sources that depend on render tasks.
// TODO(gw): If this ever shows up in a profile, we could pre-calculate
// whether a ClipSources contains any box-shadows and skip
// this iteration for the majority of cases.
let mut needs_clear = fb_config.gpu_supports_fast_clears;
for i in 0 .. clip_node_range.count {
let clip_instance = clip_store.get_instance_from_range(&clip_node_range, i);
let clip_node = &mut clip_data_store[clip_instance.handle];
match clip_node.item {
ClipItem::BoxShadow(ref mut info) => {
let (cache_size, cache_key) = info.cache_key
.as_ref()
.expect("bug: no cache key set")
.clone();
let blur_radius_dp = cache_key.blur_radius_dp as f32;
let clip_data_address = gpu_cache.get_address(&info.clip_data_handle);
// Request a cacheable render task with a blurred, minimal
// sized box-shadow rect.
info.cache_handle = Some(resource_cache.request_render_task(
RenderTaskCacheKey {
size: cache_size,
kind: RenderTaskCacheKeyKind::BoxShadow(cache_key),
},
gpu_cache,
render_tasks,
None,
false,
|render_tasks| {
// Draw the rounded rect.
let mask_task = RenderTask::new_rounded_rect_mask(
cache_size,
clip_data_address,
info.minimal_shadow_rect.origin,
device_pixel_scale,
fb_config,
);
let mask_task_id = render_tasks.add(mask_task);
// Blur it
RenderTask::new_blur(
DeviceSize::new(blur_radius_dp, blur_radius_dp),
mask_task_id,
render_tasks,
RenderTargetKind::Alpha,
ClearMode::Zero,
None,
cache_size,
)
}
));
}
ClipItem::Rectangle(_, ClipMode::Clip) => {
if !clip_instance.flags.contains(ClipNodeFlags::SAME_COORD_SYSTEM) {
// This is conservative - it's only the case that we actually need
// a clear here if we end up adding this mask via add_tiled_clip_mask,
// but for simplicity we will just clear if any of these are encountered,
// since they are rare.
needs_clear = true;
}
}
ClipItem::Rectangle(_, ClipMode::ClipOut) |
ClipItem::RoundedRectangle(..) |
ClipItem::Image { .. } => {}
}
}
// If we have a potentially tiled clip mask, clear the mask area first. Otherwise,
// the first (primary) clip mask will overwrite all the clip mask pixels with