-
Notifications
You must be signed in to change notification settings - Fork 54
/
tiling.rs
1441 lines (1321 loc) · 56.1 KB
/
tiling.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::{ColorF, BorderStyle, MixBlendMode, PipelineId, PremultipliedColorF};
use api::{DocumentLayer, FilterData, ImageFormat, LineOrientation};
use api::units::*;
#[cfg(feature = "pathfinder")]
use api::FontRenderMode;
use crate::batch::{AlphaBatchBuilder, AlphaBatchContainer, ClipBatcher, resolve_image, BatchBuilder};
use crate::clip::ClipStore;
use crate::clip_scroll_tree::{ClipScrollTree, ROOT_SPATIAL_NODE_INDEX};
use crate::debug_render::DebugItem;
use crate::device::{Texture};
#[cfg(feature = "pathfinder")]
use euclid::{TypedPoint2D, TypedVector2D};
use crate::frame_builder::FrameGlobalResources;
use crate::gpu_cache::{GpuCache};
use crate::gpu_types::{BorderInstance, BlurDirection, BlurInstance, PrimitiveHeaders, ScalingInstance};
use crate::gpu_types::{TransformData, TransformPalette, ZBufferIdGenerator};
use crate::internal_types::{CacheTextureId, FastHashMap, SavedTargetIndex, TextureSource, Filter};
#[cfg(feature = "pathfinder")]
use pathfinder_partitioner::mesh::Mesh;
use crate::picture::{RecordedDirtyRegion, SurfaceInfo};
use crate::prim_store::gradient::GRADIENT_FP_STOPS;
use crate::prim_store::{PrimitiveStore, DeferredResolve, PrimitiveScratchBuffer, PrimitiveVisibilityMask};
use crate::profiler::FrameProfileCounters;
use crate::render_backend::{DataStores, FrameId};
use crate::render_task::{BlitSource, RenderTaskAddress, RenderTaskId, RenderTaskKind};
use crate::render_task::{BlurTask, ClearMode, GlyphTask, RenderTaskLocation, RenderTaskGraph, ScalingTask};
use crate::resource_cache::ResourceCache;
use std::{cmp, usize, f32, i32, mem};
use crate::texture_allocator::{ArrayAllocationTracker, FreeRectSlice};
const STYLE_SOLID: i32 = ((BorderStyle::Solid as i32) << 8) | ((BorderStyle::Solid as i32) << 16);
const STYLE_MASK: i32 = 0x00FF_FF00;
/// According to apitrace, textures larger than 2048 break fast clear
/// optimizations on some intel drivers. We sometimes need to go larger, but
/// we try to avoid it. This can go away when proper tiling support lands,
/// since we can then split large primitives across multiple textures.
const IDEAL_MAX_TEXTURE_DIMENSION: i32 = 2048;
/// If we ever need a larger texture than the ideal, we better round it up to a
/// reasonable number in order to have a bit of leeway in placing things inside.
const TEXTURE_DIMENSION_MASK: i32 = 0xFF;
/// Identifies a given `RenderTarget` in a `RenderTargetList`.
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct RenderTargetIndex(pub usize);
pub struct RenderTargetContext<'a, 'rc> {
pub global_device_pixel_scale: DevicePixelScale,
pub prim_store: &'a PrimitiveStore,
pub resource_cache: &'rc mut ResourceCache,
pub use_dual_source_blending: bool,
pub use_advanced_blending: bool,
pub break_advanced_blend_batches: bool,
pub batch_lookback_count: usize,
pub clip_scroll_tree: &'a ClipScrollTree,
pub data_stores: &'a DataStores,
pub surfaces: &'a [SurfaceInfo],
pub scratch: &'a PrimitiveScratchBuffer,
pub screen_world_rect: WorldRect,
pub globals: &'a FrameGlobalResources,
}
/// Represents a number of rendering operations on a surface.
///
/// In graphics parlance, a "render target" usually means "a surface (texture or
/// framebuffer) bound to the output of a shader". This trait has a slightly
/// different meaning, in that it represents the operations on that surface
/// _before_ it's actually bound and rendered. So a `RenderTarget` is built by
/// the `RenderBackend` by inserting tasks, and then shipped over to the
/// `Renderer` where a device surface is resolved and the tasks are transformed
/// into draw commands on that surface.
///
/// We express this as a trait to generalize over color and alpha surfaces.
/// a given `RenderTask` will draw to one or the other, depending on its type
/// and sometimes on its parameters. See `RenderTask::target_kind`.
pub trait RenderTarget {
/// Creates a new RenderTarget of the given type.
fn new(
screen_size: DeviceIntSize,
gpu_supports_fast_clears: bool,
) -> Self;
/// Optional hook to provide additional processing for the target at the
/// end of the build phase.
fn build(
&mut self,
_ctx: &mut RenderTargetContext,
_gpu_cache: &mut GpuCache,
_render_tasks: &mut RenderTaskGraph,
_deferred_resolves: &mut Vec<DeferredResolve>,
_prim_headers: &mut PrimitiveHeaders,
_transforms: &mut TransformPalette,
_z_generator: &mut ZBufferIdGenerator,
) {
}
/// Associates a `RenderTask` with this target. That task must be assigned
/// to a region returned by invoking `allocate()` on this target.
///
/// TODO(gw): It's a bit odd that we need the deferred resolves and mutable
/// GPU cache here. They are typically used by the build step above. They
/// are used for the blit jobs to allow resolve_image to be called. It's a
/// bit of extra overhead to store the image key here and the resolve them
/// in the build step separately. BUT: if/when we add more texture cache
/// target jobs, we might want to tidy this up.
fn add_task(
&mut self,
task_id: RenderTaskId,
ctx: &RenderTargetContext,
gpu_cache: &mut GpuCache,
render_tasks: &RenderTaskGraph,
clip_store: &ClipStore,
transforms: &mut TransformPalette,
deferred_resolves: &mut Vec<DeferredResolve>,
);
fn needs_depth(&self) -> bool;
fn used_rect(&self) -> DeviceIntRect;
fn add_used(&mut self, rect: DeviceIntRect);
}
/// 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
}
/// A series of `RenderTarget` instances, serving as the high-level container
/// into which `RenderTasks` are assigned.
///
/// During the build phase, we iterate over the tasks in each `RenderPass`. For
/// each task, we invoke `allocate()` on the `RenderTargetList`, which in turn
/// attempts to allocate an output region in the last `RenderTarget` in the
/// list. If allocation fails (or if the list is empty), a new `RenderTarget` is
/// created and appended to the list. The build phase then assign the task into
/// the target associated with the final allocation.
///
/// The result is that each `RenderPass` is associated with one or two
/// `RenderTargetLists`, depending on whether we have all our tasks have the
/// same `RenderTargetKind`. The lists are then shipped to the `Renderer`, which
/// allocates a device texture array, with one slice per render target in the
/// list.
///
/// The upshot of this scheme is that it maximizes batching. In a given pass,
/// we need to do a separate batch for each individual render target. But with
/// the texture array, we can expose the entirety of the previous pass to each
/// task in the current pass in a single batch, which generally allows each
/// task to be drawn in a single batch regardless of how many results from the
/// previous pass it depends on.
///
/// Note that in some cases (like drop-shadows), we can depend on the output of
/// a pass earlier than the immediately-preceding pass. See `SavedTargetIndex`.
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct RenderTargetList<T> {
screen_size: DeviceIntSize,
pub format: ImageFormat,
/// The maximum width and height of any single primitive we've encountered
/// that will be drawn to a dynamic location.
///
/// We initially create our per-slice allocators with a width and height of
/// IDEAL_MAX_TEXTURE_DIMENSION. If we encounter a larger primitive, the
/// allocation will fail, but we'll bump max_dynamic_size, which will cause the
/// allocator for the next slice to be just large enough to accomodate it.
pub max_dynamic_size: DeviceIntSize,
pub targets: Vec<T>,
pub saved_index: Option<SavedTargetIndex>,
pub alloc_tracker: ArrayAllocationTracker,
gpu_supports_fast_clears: bool,
}
impl<T: RenderTarget> RenderTargetList<T> {
fn new(
screen_size: DeviceIntSize,
format: ImageFormat,
gpu_supports_fast_clears: bool,
) -> Self {
RenderTargetList {
screen_size,
format,
max_dynamic_size: DeviceIntSize::new(0, 0),
targets: Vec::new(),
saved_index: None,
alloc_tracker: ArrayAllocationTracker::new(),
gpu_supports_fast_clears,
}
}
fn build(
&mut self,
ctx: &mut RenderTargetContext,
gpu_cache: &mut GpuCache,
render_tasks: &mut RenderTaskGraph,
deferred_resolves: &mut Vec<DeferredResolve>,
saved_index: Option<SavedTargetIndex>,
prim_headers: &mut PrimitiveHeaders,
transforms: &mut TransformPalette,
z_generator: &mut ZBufferIdGenerator,
) {
debug_assert_eq!(None, self.saved_index);
self.saved_index = saved_index;
for target in &mut self.targets {
target.build(
ctx,
gpu_cache,
render_tasks,
deferred_resolves,
prim_headers,
transforms,
z_generator,
);
}
}
fn allocate(
&mut self,
alloc_size: DeviceIntSize,
) -> (RenderTargetIndex, DeviceIntPoint) {
let (free_rect_slice, origin) = match self.alloc_tracker.allocate(&alloc_size) {
Some(allocation) => allocation,
None => {
// Have the allocator restrict slice sizes to our max ideal
// dimensions, unless we've already gone bigger on a previous
// slice.
let rounded_dimensions = DeviceIntSize::new(
(self.max_dynamic_size.width + TEXTURE_DIMENSION_MASK) & !TEXTURE_DIMENSION_MASK,
(self.max_dynamic_size.height + TEXTURE_DIMENSION_MASK) & !TEXTURE_DIMENSION_MASK,
);
let allocator_dimensions = DeviceIntSize::new(
cmp::max(IDEAL_MAX_TEXTURE_DIMENSION, rounded_dimensions.width),
cmp::max(IDEAL_MAX_TEXTURE_DIMENSION, rounded_dimensions.height),
);
assert!(alloc_size.width <= allocator_dimensions.width &&
alloc_size.height <= allocator_dimensions.height);
let slice = FreeRectSlice(self.targets.len() as u32);
self.targets.push(T::new(self.screen_size, self.gpu_supports_fast_clears));
self.alloc_tracker.extend(
slice,
allocator_dimensions,
alloc_size,
);
(slice, DeviceIntPoint::zero())
}
};
if alloc_size.is_empty_or_negative() && self.targets.is_empty() {
// push an unused target here, only if we don't have any
self.targets.push(T::new(self.screen_size, self.gpu_supports_fast_clears));
}
self.targets[free_rect_slice.0 as usize]
.add_used(DeviceIntRect::new(origin, alloc_size));
(RenderTargetIndex(free_rect_slice.0 as usize), origin)
}
pub fn needs_depth(&self) -> bool {
self.targets.iter().any(|target| target.needs_depth())
}
pub fn check_ready(&self, t: &Texture) {
let dimensions = t.get_dimensions();
assert!(dimensions.width >= self.max_dynamic_size.width);
assert!(dimensions.height >= self.max_dynamic_size.height);
assert_eq!(t.get_format(), self.format);
assert_eq!(t.get_layer_count() as usize, self.targets.len());
assert!(t.supports_depth() >= self.needs_depth());
}
}
/// Frame output information for a given pipeline ID.
/// Storing the task ID allows the renderer to find
/// the target rect within the render target that this
/// pipeline exists at.
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct FrameOutput {
pub task_id: RenderTaskId,
pub pipeline_id: PipelineId,
}
// Defines where the source data for a blit job can be found.
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum BlitJobSource {
Texture(TextureSource, i32, DeviceIntRect),
RenderTask(RenderTaskId),
}
// Information required to do a blit from a source to a target.
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct BlitJob {
pub source: BlitJobSource,
pub target_rect: DeviceIntRect,
}
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct LineDecorationJob {
pub task_rect: DeviceRect,
pub local_size: LayoutSize,
pub wavy_line_thickness: f32,
pub style: i32,
pub orientation: i32,
}
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
#[repr(C)]
pub struct GradientJob {
pub task_rect: DeviceRect,
pub stops: [f32; GRADIENT_FP_STOPS],
pub colors: [PremultipliedColorF; GRADIENT_FP_STOPS],
pub axis_select: f32,
pub start_stop: [f32; 2],
}
#[cfg(feature = "pathfinder")]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct GlyphJob {
pub mesh: Mesh,
pub target_rect: DeviceIntRect,
pub origin: DeviceIntPoint,
pub subpixel_offset: TypedPoint2D<f32, DevicePixel>,
pub render_mode: FontRenderMode,
pub embolden_amount: TypedVector2D<f32, DevicePixel>,
}
#[cfg(not(feature = "pathfinder"))]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct GlyphJob;
/// Contains the work (in the form of instance arrays) needed to fill a color
/// color output surface (RGBA8).
///
/// See `RenderTarget`.
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct ColorRenderTarget {
pub alpha_batch_containers: Vec<AlphaBatchContainer>,
// List of blur operations to apply for this render target.
pub vertical_blurs: Vec<BlurInstance>,
pub horizontal_blurs: Vec<BlurInstance>,
pub readbacks: Vec<DeviceIntRect>,
pub scalings: Vec<ScalingInstance>,
pub blits: Vec<BlitJob>,
// List of frame buffer outputs for this render target.
pub outputs: Vec<FrameOutput>,
alpha_tasks: Vec<RenderTaskId>,
screen_size: DeviceIntSize,
// Track the used rect of the render target, so that
// we can set a scissor rect and only clear to the
// used portion of the target as an optimization.
pub used_rect: DeviceIntRect,
}
impl RenderTarget for ColorRenderTarget {
fn new(
screen_size: DeviceIntSize,
_: bool,
) -> Self {
ColorRenderTarget {
alpha_batch_containers: Vec::new(),
vertical_blurs: Vec::new(),
horizontal_blurs: Vec::new(),
readbacks: Vec::new(),
scalings: Vec::new(),
blits: Vec::new(),
outputs: Vec::new(),
alpha_tasks: Vec::new(),
screen_size,
used_rect: DeviceIntRect::zero(),
}
}
fn build(
&mut self,
ctx: &mut RenderTargetContext,
gpu_cache: &mut GpuCache,
render_tasks: &mut RenderTaskGraph,
deferred_resolves: &mut Vec<DeferredResolve>,
prim_headers: &mut PrimitiveHeaders,
transforms: &mut TransformPalette,
z_generator: &mut ZBufferIdGenerator,
) {
let mut merged_batches = AlphaBatchContainer::new(None);
for task_id in &self.alpha_tasks {
let task = &render_tasks[*task_id];
match task.clear_mode {
ClearMode::One |
ClearMode::Zero => {
panic!("bug: invalid clear mode for color task");
}
ClearMode::DontCare |
ClearMode::Transparent => {}
}
match task.kind {
RenderTaskKind::Picture(ref pic_task) => {
let pic = &ctx.prim_store.pictures[pic_task.pic_index.0];
let raster_spatial_node_index = match pic.raster_config {
Some(ref raster_config) => {
let surface = &ctx.surfaces[raster_config.surface_index.0];
surface.raster_spatial_node_index
}
None => {
// This must be the main framebuffer
ROOT_SPATIAL_NODE_INDEX
}
};
let (target_rect, _) = task.get_target_rect();
let scissor_rect = if pic_task.can_merge {
None
} else {
Some(target_rect)
};
// TODO(gw): The type names of AlphaBatchBuilder and BatchBuilder
// are still confusing. Once more of the picture caching
// improvement code lands, the AlphaBatchBuilder and
// AlphaBatchList types will be collapsed into one, which
// should simplify coming up with better type names.
let alpha_batch_builder = AlphaBatchBuilder::new(
self.screen_size,
ctx.break_advanced_blend_batches,
ctx.batch_lookback_count,
*task_id,
render_tasks.get_task_address(*task_id),
PrimitiveVisibilityMask::all(),
);
let mut batch_builder = BatchBuilder::new(
vec![alpha_batch_builder],
);
batch_builder.add_pic_to_batch(
pic,
ctx,
gpu_cache,
render_tasks,
deferred_resolves,
prim_headers,
transforms,
raster_spatial_node_index,
pic_task.surface_spatial_node_index,
z_generator,
);
let alpha_batch_builders = batch_builder.finalize();
for batcher in alpha_batch_builders {
batcher.build(
&mut self.alpha_batch_containers,
&mut merged_batches,
target_rect,
scissor_rect,
);
}
}
_ => {
unreachable!();
}
}
}
if !merged_batches.is_empty() {
self.alpha_batch_containers.push(merged_batches);
}
}
fn add_task(
&mut self,
task_id: RenderTaskId,
ctx: &RenderTargetContext,
gpu_cache: &mut GpuCache,
render_tasks: &RenderTaskGraph,
_: &ClipStore,
_: &mut TransformPalette,
deferred_resolves: &mut Vec<DeferredResolve>,
) {
let task = &render_tasks[task_id];
match task.kind {
RenderTaskKind::VerticalBlur(ref info) => {
info.add_instances(
&mut self.vertical_blurs,
BlurDirection::Vertical,
render_tasks.get_task_address(task_id),
render_tasks.get_task_address(task.children[0]),
);
}
RenderTaskKind::HorizontalBlur(ref info) => {
info.add_instances(
&mut self.horizontal_blurs,
BlurDirection::Horizontal,
render_tasks.get_task_address(task_id),
render_tasks.get_task_address(task.children[0]),
);
}
RenderTaskKind::Picture(ref task_info) => {
let pic = &ctx.prim_store.pictures[task_info.pic_index.0];
self.alpha_tasks.push(task_id);
// If this pipeline is registered as a frame output
// store the information necessary to do the copy.
if let Some(pipeline_id) = pic.frame_output_pipeline_id {
self.outputs.push(FrameOutput {
pipeline_id,
task_id,
});
}
}
RenderTaskKind::ClipRegion(..) |
RenderTaskKind::Border(..) |
RenderTaskKind::CacheMask(..) |
RenderTaskKind::Gradient(..) |
RenderTaskKind::LineDecoration(..) => {
panic!("Should not be added to color target!");
}
RenderTaskKind::Glyph(..) => {
// FIXME(pcwalton): Support color glyphs.
panic!("Glyphs should not be added to color target!");
}
RenderTaskKind::Readback(device_rect) => {
self.readbacks.push(device_rect);
}
RenderTaskKind::Scaling(..) => {
self.scalings.push(ScalingInstance {
task_address: render_tasks.get_task_address(task_id),
src_task_address: render_tasks.get_task_address(task.children[0]),
});
}
RenderTaskKind::Blit(ref task_info) => {
match task_info.source {
BlitSource::Image { key } => {
// Get the cache item for the source texture.
let cache_item = resolve_image(
key.request,
ctx.resource_cache,
gpu_cache,
deferred_resolves,
);
// Work out a source rect to copy from the texture, depending on whether
// a sub-rect is present or not.
let source_rect = key.texel_rect.map_or(cache_item.uv_rect.to_i32(), |sub_rect| {
DeviceIntRect::new(
DeviceIntPoint::new(
cache_item.uv_rect.origin.x as i32 + sub_rect.origin.x,
cache_item.uv_rect.origin.y as i32 + sub_rect.origin.y,
),
sub_rect.size,
)
});
// Store the blit job for the renderer to execute, including
// the allocated destination rect within this target.
let (target_rect, _) = task.get_target_rect();
self.blits.push(BlitJob {
source: BlitJobSource::Texture(
cache_item.texture_id,
cache_item.texture_layer,
source_rect,
),
target_rect: target_rect.inner_rect(task_info.padding)
});
}
BlitSource::RenderTask { task_id } => {
let (target_rect, _) = task.get_target_rect();
self.blits.push(BlitJob {
source: BlitJobSource::RenderTask(task_id),
target_rect: target_rect.inner_rect(task_info.padding)
});
}
}
}
#[cfg(test)]
RenderTaskKind::Test(..) => {}
}
}
fn needs_depth(&self) -> bool {
self.alpha_batch_containers.iter().any(|ab| {
!ab.opaque_batches.is_empty()
})
}
fn used_rect(&self) -> DeviceIntRect {
self.used_rect
}
fn add_used(&mut self, rect: DeviceIntRect) {
self.used_rect = self.used_rect.union(&rect);
}
}
/// Contains the work (in the form of instance arrays) needed to fill an alpha
/// output surface (R8).
///
/// See `RenderTarget`.
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct AlphaRenderTarget {
pub clip_batcher: ClipBatcher,
// List of blur operations to apply for this render target.
pub vertical_blurs: Vec<BlurInstance>,
pub horizontal_blurs: Vec<BlurInstance>,
pub scalings: Vec<ScalingInstance>,
pub zero_clears: Vec<RenderTaskId>,
pub one_clears: Vec<RenderTaskId>,
// Track the used rect of the render target, so that
// we can set a scissor rect and only clear to the
// used portion of the target as an optimization.
pub used_rect: DeviceIntRect,
}
impl RenderTarget for AlphaRenderTarget {
fn new(
_: DeviceIntSize,
gpu_supports_fast_clears: bool,
) -> Self {
AlphaRenderTarget {
clip_batcher: ClipBatcher::new(gpu_supports_fast_clears),
vertical_blurs: Vec::new(),
horizontal_blurs: Vec::new(),
scalings: Vec::new(),
zero_clears: Vec::new(),
one_clears: Vec::new(),
used_rect: DeviceIntRect::zero(),
}
}
fn add_task(
&mut self,
task_id: RenderTaskId,
ctx: &RenderTargetContext,
gpu_cache: &mut GpuCache,
render_tasks: &RenderTaskGraph,
clip_store: &ClipStore,
transforms: &mut TransformPalette,
_: &mut Vec<DeferredResolve>,
) {
let task = &render_tasks[task_id];
let (target_rect, _) = task.get_target_rect();
match task.clear_mode {
ClearMode::Zero => {
self.zero_clears.push(task_id);
}
ClearMode::One => {
self.one_clears.push(task_id);
}
ClearMode::DontCare => {}
ClearMode::Transparent => {
panic!("bug: invalid clear mode for alpha task");
}
}
match task.kind {
RenderTaskKind::Readback(..) |
RenderTaskKind::Picture(..) |
RenderTaskKind::Blit(..) |
RenderTaskKind::Border(..) |
RenderTaskKind::LineDecoration(..) |
RenderTaskKind::Gradient(..) |
RenderTaskKind::Glyph(..) => {
panic!("BUG: should not be added to alpha target!");
}
RenderTaskKind::VerticalBlur(ref info) => {
info.add_instances(
&mut self.vertical_blurs,
BlurDirection::Vertical,
render_tasks.get_task_address(task_id),
render_tasks.get_task_address(task.children[0]),
);
}
RenderTaskKind::HorizontalBlur(ref info) => {
info.add_instances(
&mut self.horizontal_blurs,
BlurDirection::Horizontal,
render_tasks.get_task_address(task_id),
render_tasks.get_task_address(task.children[0]),
);
}
RenderTaskKind::CacheMask(ref task_info) => {
self.clip_batcher.add(
task_info.clip_node_range,
task_info.root_spatial_node_index,
ctx.resource_cache,
gpu_cache,
clip_store,
ctx.clip_scroll_tree,
transforms,
&ctx.data_stores.clip,
task_info.actual_rect,
&ctx.screen_world_rect,
task_info.device_pixel_scale,
task_info.snap_offsets,
target_rect.origin.to_f32(),
task_info.actual_rect.origin.to_f32(),
);
}
RenderTaskKind::ClipRegion(ref region_task) => {
let device_rect = DeviceRect::new(
DevicePoint::zero(),
target_rect.size.to_f32(),
);
self.clip_batcher.add_clip_region(
region_task.clip_data_address,
region_task.local_pos,
device_rect,
target_rect.origin.to_f32(),
DevicePoint::zero(),
region_task.device_pixel_scale.0,
);
}
RenderTaskKind::Scaling(ref info) => {
info.add_instances(
&mut self.scalings,
render_tasks.get_task_address(task_id),
render_tasks.get_task_address(task.children[0]),
);
}
#[cfg(test)]
RenderTaskKind::Test(..) => {}
}
}
fn needs_depth(&self) -> bool {
false
}
fn used_rect(&self) -> DeviceIntRect {
self.used_rect
}
fn add_used(&mut self, rect: DeviceIntRect) {
self.used_rect = self.used_rect.union(&rect);
}
}
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct PictureCacheTarget {
pub texture: TextureSource,
pub layer: usize,
pub alpha_batch_container: AlphaBatchContainer,
pub clear_color: Option<ColorF>,
}
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct TextureCacheRenderTarget {
pub target_kind: RenderTargetKind,
pub horizontal_blurs: Vec<BlurInstance>,
pub blits: Vec<BlitJob>,
pub glyphs: Vec<GlyphJob>,
pub border_segments_complex: Vec<BorderInstance>,
pub border_segments_solid: Vec<BorderInstance>,
pub clears: Vec<DeviceIntRect>,
pub line_decorations: Vec<LineDecorationJob>,
pub gradients: Vec<GradientJob>,
}
impl TextureCacheRenderTarget {
fn new(target_kind: RenderTargetKind) -> Self {
TextureCacheRenderTarget {
target_kind,
horizontal_blurs: vec![],
blits: vec![],
glyphs: vec![],
border_segments_complex: vec![],
border_segments_solid: vec![],
clears: vec![],
line_decorations: vec![],
gradients: vec![],
}
}
fn add_task(
&mut self,
task_id: RenderTaskId,
render_tasks: &mut RenderTaskGraph,
) {
let task_address = render_tasks.get_task_address(task_id);
let src_task_address = render_tasks[task_id].children.get(0).map(|src_task_id| {
render_tasks.get_task_address(*src_task_id)
});
let task = &mut render_tasks[task_id];
let target_rect = task.get_target_rect();
match task.kind {
RenderTaskKind::LineDecoration(ref info) => {
self.clears.push(target_rect.0);
self.line_decorations.push(LineDecorationJob {
task_rect: target_rect.0.to_f32(),
local_size: info.local_size,
style: info.style as i32,
orientation: info.orientation as i32,
wavy_line_thickness: info.wavy_line_thickness,
});
}
RenderTaskKind::HorizontalBlur(ref info) => {
info.add_instances(
&mut self.horizontal_blurs,
BlurDirection::Horizontal,
task_address,
src_task_address.unwrap(),
);
}
RenderTaskKind::Blit(ref task_info) => {
match task_info.source {
BlitSource::Image { .. } => {
// reading/writing from the texture cache at the same time
// is undefined behavior.
panic!("bug: a single blit cannot be to/from texture cache");
}
BlitSource::RenderTask { task_id } => {
// Add a blit job to copy from an existing render
// task to this target.
self.blits.push(BlitJob {
source: BlitJobSource::RenderTask(task_id),
target_rect: target_rect.0.inner_rect(task_info.padding),
});
}
}
}
RenderTaskKind::Border(ref mut task_info) => {
self.clears.push(target_rect.0);
let task_origin = target_rect.0.origin.to_f32();
let instances = mem::replace(&mut task_info.instances, Vec::new());
for mut instance in instances {
// TODO(gw): It may be better to store the task origin in
// the render task data instead of per instance.
instance.task_origin = task_origin;
if instance.flags & STYLE_MASK == STYLE_SOLID {
self.border_segments_solid.push(instance);
} else {
self.border_segments_complex.push(instance);
}
}
}
RenderTaskKind::Glyph(ref mut task_info) => {
self.add_glyph_task(task_info, target_rect.0)
}
RenderTaskKind::Gradient(ref task_info) => {
let mut stops = [0.0; 4];
let mut colors = [PremultipliedColorF::BLACK; 4];
let axis_select = match task_info.orientation {
LineOrientation::Horizontal => 0.0,
LineOrientation::Vertical => 1.0,
};
for (stop, (offset, color)) in task_info.stops.iter().zip(stops.iter_mut().zip(colors.iter_mut())) {
*offset = stop.offset;
*color = ColorF::from(stop.color).premultiplied();
}
self.gradients.push(GradientJob {
task_rect: target_rect.0.to_f32(),
axis_select,
stops,
colors,
start_stop: [task_info.start_point, task_info.end_point],
});
}
RenderTaskKind::VerticalBlur(..) |
RenderTaskKind::Picture(..) |
RenderTaskKind::ClipRegion(..) |
RenderTaskKind::CacheMask(..) |
RenderTaskKind::Readback(..) |
RenderTaskKind::Scaling(..) => {
panic!("BUG: unexpected task kind for texture cache target");
}
#[cfg(test)]
RenderTaskKind::Test(..) => {}
}
}
#[cfg(feature = "pathfinder")]
fn add_glyph_task(&mut self, task_info: &mut GlyphTask, target_rect: DeviceIntRect) {
self.glyphs.push(GlyphJob {
mesh: task_info.mesh.take().unwrap(),
target_rect,
origin: task_info.origin,
subpixel_offset: task_info.subpixel_offset,
render_mode: task_info.render_mode,
embolden_amount: task_info.embolden_amount,
})
}
#[cfg(not(feature = "pathfinder"))]
fn add_glyph_task(&mut self, _: &mut GlyphTask, _: DeviceIntRect) {}
}
/// Contains the set of `RenderTarget`s specific to the kind of pass.
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum RenderPassKind {
/// The final pass to the main frame buffer, where we have a single color
/// target for display to the user.
MainFramebuffer {
main_target: ColorRenderTarget,
},
/// An intermediate pass, where we may have multiple targets.
OffScreen {
alpha: RenderTargetList<AlphaRenderTarget>,
color: RenderTargetList<ColorRenderTarget>,
texture_cache: FastHashMap<(CacheTextureId, usize), TextureCacheRenderTarget>,
picture_cache: Vec<PictureCacheTarget>,
},
}
/// A render pass represents a set of rendering operations that don't depend on one
/// another.
///
/// A render pass can have several render targets if there wasn't enough space in one
/// target to do all of the rendering for that pass. See `RenderTargetList`.
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct RenderPass {
/// The kind of pass, as well as the set of targets associated with that
/// kind of pass.
pub kind: RenderPassKind,
/// The set of tasks to be performed in this pass, as indices into the
/// `RenderTaskGraph`.
pub tasks: Vec<RenderTaskId>,
/// Screen size in device pixels - used for opaque alpha batch break threshold.
screen_size: DeviceIntSize,
}
impl RenderPass {
/// Creates a pass for the main framebuffer. There is only one of these, and
/// it is always the last pass.
pub fn new_main_framebuffer(
screen_size: DeviceIntSize,
gpu_supports_fast_clears: bool,
) -> Self {
let main_target = ColorRenderTarget::new(screen_size, gpu_supports_fast_clears);
RenderPass {
kind: RenderPassKind::MainFramebuffer {
main_target,
},
tasks: vec![],
screen_size,
}
}
/// Creates an intermediate off-screen pass.
pub fn new_off_screen(
screen_size: DeviceIntSize,
gpu_supports_fast_clears: bool,
) -> Self {
RenderPass {
kind: RenderPassKind::OffScreen {
color: RenderTargetList::new(
screen_size,
ImageFormat::BGRA8,
gpu_supports_fast_clears,
),
alpha: RenderTargetList::new(
screen_size,
ImageFormat::R8,
gpu_supports_fast_clears,
),
texture_cache: FastHashMap::default(),
picture_cache: Vec::new(),
},
tasks: vec![],
screen_size,
}
}