-
Notifications
You must be signed in to change notification settings - Fork 54
/
batch.rs
3147 lines (2854 loc) · 134 KB
/
batch.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::{AlphaType, ClipMode, ExternalImageType, ImageRendering};
use api::{YuvColorSpace, YuvFormat, ColorDepth, PremultipliedColorF, RasterSpace};
use api::units::*;
use crate::clip::{ClipDataStore, ClipNodeFlags, ClipNodeRange, ClipItem, ClipStore, ClipNodeInstance};
use crate::clip_scroll_tree::{ClipScrollTree, ROOT_SPATIAL_NODE_INDEX, SpatialNodeIndex, CoordinateSystemId};
use crate::glyph_rasterizer::GlyphFormat;
use crate::gpu_cache::{GpuBlockData, GpuCache, GpuCacheHandle, GpuCacheAddress};
use crate::gpu_types::{BrushFlags, BrushInstance, PrimitiveHeaders, ZBufferId, ZBufferIdGenerator};
use crate::gpu_types::{ClipMaskInstance, SplitCompositeInstance, SnapOffsets};
use crate::gpu_types::{PrimitiveInstanceData, RasterizationSpace, GlyphInstance};
use crate::gpu_types::{PrimitiveHeader, PrimitiveHeaderIndex, TransformPaletteId, TransformPalette};
use crate::internal_types::{FastHashMap, SavedTargetIndex, TextureSource, Filter};
use crate::picture::{Picture3DContext, PictureCompositeMode, PicturePrimitive};
use crate::prim_store::{DeferredResolve, EdgeAaSegmentMask, PrimitiveInstanceKind, PrimitiveVisibilityIndex, PrimitiveVisibilityMask};
use crate::prim_store::{VisibleGradientTile, PrimitiveInstance, PrimitiveOpacity, SegmentInstanceIndex};
use crate::prim_store::{BrushSegment, ClipMaskKind, ClipTaskIndex, VECS_PER_SEGMENT};
use crate::prim_store::{recompute_snap_offsets};
use crate::prim_store::image::ImageSource;
use crate::render_backend::DataStores;
use crate::render_task::{RenderTaskAddress, RenderTaskId, RenderTaskGraph};
use crate::renderer::{BlendMode, ImageBufferKind, ShaderColorMode};
use crate::renderer::{BLOCKS_PER_UV_RECT, MAX_VERTEX_TEXTURE_WIDTH};
use crate::resource_cache::{CacheItem, GlyphFetchResult, ImageRequest, ResourceCache, ImageProperties};
use smallvec::SmallVec;
use std::{f32, i32, usize};
use crate::tiling::{RenderTargetContext};
use crate::util::{project_rect, TransformedRectKind};
// Special sentinel value recognized by the shader. It is considered to be
// a dummy task that doesn't mask out anything.
const OPAQUE_TASK_ADDRESS: RenderTaskAddress = RenderTaskAddress(0x7fff);
/// Used to signal there are no segments provided with this primitive.
const INVALID_SEGMENT_INDEX: i32 = 0xffff;
/// Size in device pixels for tiles that clip masks are drawn in.
const CLIP_RECTANGLE_TILE_SIZE: i32 = 128;
/// The minimum size of a clip mask before trying to draw in tiles.
const CLIP_RECTANGLE_AREA_THRESHOLD: i32 = CLIP_RECTANGLE_TILE_SIZE * CLIP_RECTANGLE_TILE_SIZE * 4;
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum BrushBatchKind {
Solid,
Image(ImageBufferKind),
Blend,
MixBlend {
task_id: RenderTaskId,
source_id: RenderTaskId,
backdrop_id: RenderTaskId,
},
YuvImage(ImageBufferKind, YuvFormat, ColorDepth, YuvColorSpace),
RadialGradient,
LinearGradient,
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum BatchKind {
SplitComposite,
TextRun(GlyphFormat),
Brush(BrushBatchKind),
}
/// Optional textures that can be used as a source in the shaders.
/// Textures that are not used by the batch are equal to TextureId::invalid().
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct BatchTextures {
pub colors: [TextureSource; 3],
}
impl BatchTextures {
pub fn no_texture() -> Self {
BatchTextures {
colors: [TextureSource::Invalid; 3],
}
}
pub fn render_target_cache() -> Self {
BatchTextures {
colors: [
TextureSource::PrevPassColor,
TextureSource::PrevPassAlpha,
TextureSource::Invalid,
],
}
}
pub fn color(texture: TextureSource) -> Self {
BatchTextures {
colors: [texture, texture, TextureSource::Invalid],
}
}
}
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct BatchKey {
pub kind: BatchKind,
pub blend_mode: BlendMode,
pub textures: BatchTextures,
}
impl BatchKey {
pub fn new(kind: BatchKind, blend_mode: BlendMode, textures: BatchTextures) -> Self {
BatchKey {
kind,
blend_mode,
textures,
}
}
pub fn is_compatible_with(&self, other: &BatchKey) -> bool {
self.kind == other.kind && self.blend_mode == other.blend_mode &&
textures_compatible(self.textures.colors[0], other.textures.colors[0]) &&
textures_compatible(self.textures.colors[1], other.textures.colors[1]) &&
textures_compatible(self.textures.colors[2], other.textures.colors[2])
}
}
#[inline]
fn textures_compatible(t1: TextureSource, t2: TextureSource) -> bool {
t1 == TextureSource::Invalid || t2 == TextureSource::Invalid || t1 == t2
}
pub struct AlphaBatchList {
pub batches: Vec<PrimitiveBatch>,
pub item_rects: Vec<Vec<PictureRect>>,
current_batch_index: usize,
current_z_id: ZBufferId,
break_advanced_blend_batches: bool,
lookback_count: usize,
}
impl AlphaBatchList {
fn new(break_advanced_blend_batches: bool, lookback_count: usize) -> Self {
AlphaBatchList {
batches: Vec::new(),
item_rects: Vec::new(),
current_z_id: ZBufferId::invalid(),
current_batch_index: usize::MAX,
break_advanced_blend_batches,
lookback_count,
}
}
pub fn set_params_and_get_batch(
&mut self,
key: BatchKey,
features: BatchFeatures,
// The bounding box of everything at this Z plane. We expect potentially
// multiple primitive segments coming with the same `z_id`.
z_bounding_rect: &PictureRect,
z_id: ZBufferId,
) -> &mut Vec<PrimitiveInstanceData> {
if z_id != self.current_z_id ||
self.current_batch_index == usize::MAX ||
!self.batches[self.current_batch_index].key.is_compatible_with(&key)
{
let mut selected_batch_index = None;
match key.blend_mode {
BlendMode::SubpixelWithBgColor => {
'outer_multipass: for (batch_index, batch) in self.batches.iter().enumerate().rev().take(self.lookback_count) {
// Some subpixel batches are drawn in two passes. Because of this, we need
// to check for overlaps with every batch (which is a bit different
// than the normal batching below).
for item_rect in &self.item_rects[batch_index] {
if item_rect.intersects(z_bounding_rect) {
break 'outer_multipass;
}
}
if batch.key.is_compatible_with(&key) {
selected_batch_index = Some(batch_index);
break;
}
}
}
BlendMode::Advanced(_) if self.break_advanced_blend_batches => {
// don't try to find a batch
}
_ => {
'outer_default: for (batch_index, batch) in self.batches.iter().enumerate().rev().take(self.lookback_count) {
// For normal batches, we only need to check for overlaps for batches
// other than the first batch we consider. If the first batch
// is compatible, then we know there isn't any potential overlap
// issues to worry about.
if batch.key.is_compatible_with(&key) {
selected_batch_index = Some(batch_index);
break;
}
// check for intersections
for item_rect in &self.item_rects[batch_index] {
if item_rect.intersects(z_bounding_rect) {
break 'outer_default;
}
}
}
}
}
if selected_batch_index.is_none() {
let new_batch = PrimitiveBatch::new(key);
selected_batch_index = Some(self.batches.len());
self.batches.push(new_batch);
self.item_rects.push(Vec::new());
}
self.current_batch_index = selected_batch_index.unwrap();
self.item_rects[self.current_batch_index].push(*z_bounding_rect);
self.current_z_id = z_id;
} else if cfg!(debug_assertions) {
// If it's a different segment of the same (larger) primitive, we expect the bounding box
// to be the same - coming from the primitive itself, not the segment.
assert_eq!(self.item_rects[self.current_batch_index].last(), Some(z_bounding_rect));
}
let batch = &mut self.batches[self.current_batch_index];
batch.features |= features;
&mut batch.instances
}
}
pub struct OpaqueBatchList {
pub pixel_area_threshold_for_new_batch: f32,
pub batches: Vec<PrimitiveBatch>,
pub current_batch_index: usize,
lookback_count: usize,
}
impl OpaqueBatchList {
fn new(pixel_area_threshold_for_new_batch: f32, lookback_count: usize) -> Self {
OpaqueBatchList {
batches: Vec::new(),
pixel_area_threshold_for_new_batch,
current_batch_index: usize::MAX,
lookback_count,
}
}
pub fn set_params_and_get_batch(
&mut self,
key: BatchKey,
features: BatchFeatures,
// The bounding box of everything at the current Z, whatever it is. We expect potentially
// multiple primitive segments produced by a primitive, which we allow to check
// `current_batch_index` instead of iterating the batches.
z_bounding_rect: &PictureRect,
) -> &mut Vec<PrimitiveInstanceData> {
if self.current_batch_index == usize::MAX ||
!self.batches[self.current_batch_index].key.is_compatible_with(&key) {
let mut selected_batch_index = None;
let item_area = z_bounding_rect.size.area();
// If the area of this primitive is larger than the given threshold,
// then it is large enough to warrant breaking a batch for. In this
// case we just see if it can be added to the existing batch or
// create a new one.
if item_area > self.pixel_area_threshold_for_new_batch {
if let Some(batch) = self.batches.last() {
if batch.key.is_compatible_with(&key) {
selected_batch_index = Some(self.batches.len() - 1);
}
}
} else {
// Otherwise, look back through a reasonable number of batches.
for (batch_index, batch) in self.batches.iter().enumerate().rev().take(self.lookback_count) {
if batch.key.is_compatible_with(&key) {
selected_batch_index = Some(batch_index);
break;
}
}
}
if selected_batch_index.is_none() {
let new_batch = PrimitiveBatch::new(key);
selected_batch_index = Some(self.batches.len());
self.batches.push(new_batch);
}
self.current_batch_index = selected_batch_index.unwrap();
}
let batch = &mut self.batches[self.current_batch_index];
batch.features |= features;
&mut batch.instances
}
fn finalize(&mut self) {
// Reverse the instance arrays in the opaque batches
// to get maximum z-buffer efficiency by drawing
// front-to-back.
// TODO(gw): Maybe we can change the batch code to
// build these in reverse and avoid having
// to reverse the instance array here.
for batch in &mut self.batches {
batch.instances.reverse();
}
}
}
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct PrimitiveBatch {
pub key: BatchKey,
pub instances: Vec<PrimitiveInstanceData>,
pub features: BatchFeatures,
}
bitflags! {
/// Features of the batch that, if not requested, may allow a fast-path.
///
/// Rather than breaking batches when primitives request different features,
/// we always request the minimum amount of features to satisfy all items in
/// the batch.
/// The goal is to let the renderer be optionally select more specialized
/// versions of a shader if the batch doesn't require code certain code paths.
/// Not all shaders necessarily implement all of these features.
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct BatchFeatures: u8 {
const ALPHA_PASS = 1 << 0;
const ANTIALIASING = 1 << 1;
const REPETITION = 1 << 2;
}
}
impl PrimitiveBatch {
fn new(key: BatchKey) -> PrimitiveBatch {
PrimitiveBatch {
key,
instances: Vec::new(),
features: BatchFeatures::empty(),
}
}
fn merge(&mut self, other: PrimitiveBatch) {
self.instances.extend(other.instances);
self.features |= other.features;
}
}
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct AlphaBatchContainer {
pub opaque_batches: Vec<PrimitiveBatch>,
pub alpha_batches: Vec<PrimitiveBatch>,
/// The overall scissor rect for this render task, if one
/// is required.
pub task_scissor_rect: Option<DeviceIntRect>,
/// The rectangle of the owning render target that this
/// set of batches affects.
pub task_rect: DeviceIntRect,
}
impl AlphaBatchContainer {
pub fn new(
task_scissor_rect: Option<DeviceIntRect>,
) -> AlphaBatchContainer {
AlphaBatchContainer {
opaque_batches: Vec::new(),
alpha_batches: Vec::new(),
task_scissor_rect,
task_rect: DeviceIntRect::zero(),
}
}
pub fn is_empty(&self) -> bool {
self.opaque_batches.is_empty() &&
self.alpha_batches.is_empty()
}
fn merge(&mut self, builder: AlphaBatchBuilder, task_rect: &DeviceIntRect) {
self.task_rect = self.task_rect.union(task_rect);
for other_batch in builder.opaque_batch_list.batches {
let batch_index = self.opaque_batches.iter().position(|batch| {
batch.key.is_compatible_with(&other_batch.key)
});
match batch_index {
Some(batch_index) => {
self.opaque_batches[batch_index].merge(other_batch);
}
None => {
self.opaque_batches.push(other_batch);
}
}
}
let mut min_batch_index = 0;
for other_batch in builder.alpha_batch_list.batches {
let batch_index = self.alpha_batches.iter().skip(min_batch_index).position(|batch| {
batch.key.is_compatible_with(&other_batch.key)
});
match batch_index {
Some(batch_index) => {
let index = batch_index + min_batch_index;
self.alpha_batches[index].merge(other_batch);
min_batch_index = index;
}
None => {
self.alpha_batches.push(other_batch);
min_batch_index = self.alpha_batches.len();
}
}
}
}
}
/// Each segment can optionally specify a per-segment
/// texture set and one user data field.
#[derive(Debug, Copy, Clone)]
struct SegmentInstanceData {
textures: BatchTextures,
user_data: i32,
}
/// Encapsulates the logic of building batches for items that are blended.
pub struct AlphaBatchBuilder {
pub alpha_batch_list: AlphaBatchList,
pub opaque_batch_list: OpaqueBatchList,
pub render_task_id: RenderTaskId,
render_task_address: RenderTaskAddress,
pub vis_mask: PrimitiveVisibilityMask,
}
impl AlphaBatchBuilder {
pub fn new(
screen_size: DeviceIntSize,
break_advanced_blend_batches: bool,
lookback_count: usize,
render_task_id: RenderTaskId,
render_task_address: RenderTaskAddress,
vis_mask: PrimitiveVisibilityMask,
) -> Self {
// The threshold for creating a new batch is
// one quarter the screen size.
let batch_area_threshold = (screen_size.width * screen_size.height) as f32 / 4.0;
AlphaBatchBuilder {
alpha_batch_list: AlphaBatchList::new(break_advanced_blend_batches, lookback_count),
opaque_batch_list: OpaqueBatchList::new(batch_area_threshold, lookback_count),
render_task_id,
render_task_address,
vis_mask,
}
}
pub fn build(
mut self,
batch_containers: &mut Vec<AlphaBatchContainer>,
merged_batches: &mut AlphaBatchContainer,
task_rect: DeviceIntRect,
task_scissor_rect: Option<DeviceIntRect>,
) {
self.opaque_batch_list.finalize();
if task_scissor_rect.is_none() {
merged_batches.merge(self, &task_rect);
} else {
batch_containers.push(AlphaBatchContainer {
alpha_batches: self.alpha_batch_list.batches,
opaque_batches: self.opaque_batch_list.batches,
task_scissor_rect,
task_rect,
});
}
}
pub fn push_single_instance(
&mut self,
key: BatchKey,
features: BatchFeatures,
bounding_rect: &PictureRect,
z_id: ZBufferId,
instance: PrimitiveInstanceData,
) {
self.set_params_and_get_batch(key, features, bounding_rect, z_id)
.push(instance);
}
pub fn set_params_and_get_batch(
&mut self,
key: BatchKey,
features: BatchFeatures,
bounding_rect: &PictureRect,
z_id: ZBufferId,
) -> &mut Vec<PrimitiveInstanceData> {
match key.blend_mode {
BlendMode::None => {
self.opaque_batch_list
.set_params_and_get_batch(key, features, bounding_rect)
}
BlendMode::Alpha |
BlendMode::PremultipliedAlpha |
BlendMode::PremultipliedDestOut |
BlendMode::SubpixelConstantTextColor(..) |
BlendMode::SubpixelWithBgColor |
BlendMode::SubpixelDualSource |
BlendMode::Advanced(_) => {
self.alpha_batch_list
.set_params_and_get_batch(key, features, bounding_rect, z_id)
}
}
}
}
/// Supports (recursively) adding a list of primitives and pictures to an alpha batch
/// builder. In future, it will support multiple dirty regions / slices, allowing the
/// contents of a picture to be spliced into multiple batch builders.
pub struct BatchBuilder {
/// A temporary buffer that is used during glyph fetching, stored here
/// to reduce memory allocations.
glyph_fetch_buffer: Vec<GlyphFetchResult>,
pub batchers: Vec<AlphaBatchBuilder>,
}
impl BatchBuilder {
pub fn new(batchers: Vec<AlphaBatchBuilder>) -> Self {
BatchBuilder {
glyph_fetch_buffer: Vec::new(),
batchers,
}
}
pub fn finalize(self) -> Vec<AlphaBatchBuilder> {
self.batchers
}
fn add_brush_instance_to_batches(
&mut self,
batch_key: BatchKey,
features: BatchFeatures,
bounding_rect: &PictureRect,
z_id: ZBufferId,
segment_index: i32,
edge_flags: EdgeAaSegmentMask,
clip_task_address: RenderTaskAddress,
brush_flags: BrushFlags,
prim_header_index: PrimitiveHeaderIndex,
user_data: i32,
prim_vis_mask: PrimitiveVisibilityMask,
) {
for batcher in &mut self.batchers {
if batcher.vis_mask.intersects(prim_vis_mask) {
let render_task_address = batcher.render_task_address;
let instance = BrushInstance {
segment_index,
edge_flags,
clip_task_address,
render_task_address,
brush_flags,
prim_header_index,
user_data,
};
batcher.push_single_instance(
batch_key,
features,
bounding_rect,
z_id,
PrimitiveInstanceData::from(instance),
);
}
}
}
fn add_split_composite_instance_to_batches(
&mut self,
batch_key: BatchKey,
bounding_rect: &PictureRect,
z_id: ZBufferId,
prim_header_index: PrimitiveHeaderIndex,
polygons_address: GpuCacheAddress,
prim_vis_mask: PrimitiveVisibilityMask,
) {
for batcher in &mut self.batchers {
if batcher.vis_mask.intersects(prim_vis_mask) {
let render_task_address = batcher.render_task_address;
batcher.push_single_instance(
batch_key,
BatchFeatures::empty(),
bounding_rect,
z_id,
PrimitiveInstanceData::from(SplitCompositeInstance {
prim_header_index,
render_task_address,
polygons_address,
z: z_id,
}),
);
}
}
}
/// Add a picture to a given batch builder.
pub fn add_pic_to_batch(
&mut self,
pic: &PicturePrimitive,
ctx: &RenderTargetContext,
gpu_cache: &mut GpuCache,
render_tasks: &RenderTaskGraph,
deferred_resolves: &mut Vec<DeferredResolve>,
prim_headers: &mut PrimitiveHeaders,
transforms: &mut TransformPalette,
root_spatial_node_index: SpatialNodeIndex,
surface_spatial_node_index: SpatialNodeIndex,
z_generator: &mut ZBufferIdGenerator,
) {
// Add each run in this picture to the batch.
for prim_instance in &pic.prim_list.prim_instances {
self.add_prim_to_batch(
prim_instance,
ctx,
gpu_cache,
render_tasks,
deferred_resolves,
prim_headers,
transforms,
root_spatial_node_index,
surface_spatial_node_index,
z_generator,
);
}
}
// Adds a primitive to a batch.
// It can recursively call itself in some situations, for
// example if it encounters a picture where the items
// in that picture are being drawn into the same target.
fn add_prim_to_batch(
&mut self,
prim_instance: &PrimitiveInstance,
ctx: &RenderTargetContext,
gpu_cache: &mut GpuCache,
render_tasks: &RenderTaskGraph,
deferred_resolves: &mut Vec<DeferredResolve>,
prim_headers: &mut PrimitiveHeaders,
transforms: &mut TransformPalette,
root_spatial_node_index: SpatialNodeIndex,
surface_spatial_node_index: SpatialNodeIndex,
z_generator: &mut ZBufferIdGenerator,
) {
if prim_instance.visibility_info == PrimitiveVisibilityIndex::INVALID {
return;
}
#[cfg(debug_assertions)] //TODO: why is this needed?
debug_assert_eq!(prim_instance.prepared_frame_id, render_tasks.frame_id());
let is_chased = prim_instance.is_chased();
let transform_id = transforms
.get_id(
prim_instance.spatial_node_index,
root_spatial_node_index,
ctx.clip_scroll_tree,
);
// TODO(gw): Calculating this for every primitive is a bit
// wasteful. We should probably cache this in
// the scroll node...
let transform_kind = transform_id.transform_kind();
let prim_info = &ctx.scratch.prim_info[prim_instance.visibility_info.0 as usize];
let bounding_rect = &prim_info.clip_chain.pic_clip_rect;
let z_id = z_generator.next();
let prim_common_data = &ctx.data_stores.as_common_data(&prim_instance);
let prim_rect = LayoutRect::new(
prim_instance.prim_origin,
prim_common_data.prim_size,
);
let mut batch_features = BatchFeatures::empty();
if prim_common_data.may_need_repetition {
batch_features |= BatchFeatures::REPETITION;
}
if transform_kind != TransformedRectKind::AxisAligned {
batch_features |= BatchFeatures::ANTIALIASING;
}
let snap_offsets = prim_info.snap_offsets;
let prim_vis_mask = prim_info.visibility_mask;
if is_chased {
println!("\tbatch {:?} with bound {:?}", prim_rect, bounding_rect);
}
if !bounding_rect.is_empty() {
debug_assert_eq!(prim_info.clip_chain.pic_spatial_node_index, surface_spatial_node_index,
"The primitive's bounding box is specified in a different coordinate system from the current batch!");
}
match prim_instance.kind {
PrimitiveInstanceKind::PushClipChain |
PrimitiveInstanceKind::PopClipChain => {}
PrimitiveInstanceKind::Clear { data_handle } => {
let prim_data = &ctx.data_stores.prim[data_handle];
let prim_cache_address = gpu_cache.get_address(&prim_data.gpu_cache_handle);
// TODO(gw): We can abstract some of the common code below into
// helper methods, as we port more primitives to make
// use of interning.
let prim_header = PrimitiveHeader {
local_rect: prim_rect,
local_clip_rect: prim_info.combined_local_clip_rect,
snap_offsets,
specific_prim_address: prim_cache_address,
transform_id,
};
let prim_header_index = prim_headers.push(
&prim_header,
z_id,
[get_shader_opacity(1.0), 0, 0, 0],
);
let batch_key = BatchKey {
blend_mode: BlendMode::PremultipliedDestOut,
kind: BatchKind::Brush(BrushBatchKind::Solid),
textures: BatchTextures::no_texture(),
};
let clip_task_address = ctx.get_prim_clip_task_address(
prim_info.clip_task_index,
render_tasks,
).unwrap_or(OPAQUE_TASK_ADDRESS);
self.add_brush_instance_to_batches(
batch_key,
batch_features,
bounding_rect,
z_id,
INVALID_SEGMENT_INDEX,
EdgeAaSegmentMask::all(),
clip_task_address,
BrushFlags::PERSPECTIVE_INTERPOLATION,
prim_header_index,
0,
prim_vis_mask,
);
}
PrimitiveInstanceKind::NormalBorder { data_handle, ref cache_handles, .. } => {
let prim_data = &ctx.data_stores.normal_border[data_handle];
let common_data = &prim_data.common;
let prim_cache_address = gpu_cache.get_address(&common_data.gpu_cache_handle);
let cache_handles = &ctx.scratch.border_cache_handles[*cache_handles];
let specified_blend_mode = BlendMode::PremultipliedAlpha;
let mut segment_data: SmallVec<[SegmentInstanceData; 8]> = SmallVec::new();
// Collect the segment instance data from each render
// task for each valid edge / corner of the border.
for handle in cache_handles {
let rt_cache_entry = ctx.resource_cache
.get_cached_render_task(handle);
let cache_item = ctx.resource_cache
.get_texture_cache_item(&rt_cache_entry.handle);
segment_data.push(
SegmentInstanceData {
textures: BatchTextures::color(cache_item.texture_id),
user_data: cache_item.uv_rect_handle.as_int(gpu_cache),
}
);
}
let non_segmented_blend_mode = if !common_data.opacity.is_opaque ||
prim_info.clip_task_index != ClipTaskIndex::INVALID ||
transform_kind == TransformedRectKind::Complex
{
specified_blend_mode
} else {
BlendMode::None
};
let prim_header = PrimitiveHeader {
local_rect: prim_rect,
local_clip_rect: prim_info.combined_local_clip_rect,
snap_offsets,
specific_prim_address: prim_cache_address,
transform_id,
};
let batch_params = BrushBatchParameters::instanced(
BrushBatchKind::Image(ImageBufferKind::Texture2DArray),
[
ShaderColorMode::Image as i32 | ((AlphaType::PremultipliedAlpha as i32) << 16),
RasterizationSpace::Local as i32,
get_shader_opacity(1.0),
0,
],
segment_data,
);
let prim_header_index = prim_headers.push(
&prim_header,
z_id,
batch_params.prim_user_data,
);
let border_data = &prim_data.kind;
self.add_segmented_prim_to_batch(
Some(border_data.brush_segments.as_slice()),
common_data.opacity,
&batch_params,
specified_blend_mode,
non_segmented_blend_mode,
batch_features,
prim_header_index,
bounding_rect,
transform_kind,
render_tasks,
z_id,
prim_info.clip_task_index,
prim_vis_mask,
ctx,
);
}
PrimitiveInstanceKind::TextRun { data_handle, run_index, .. } => {
let run = &ctx.prim_store.text_runs[run_index];
let subpx_dir = run.used_font.get_subpx_dir();
// The GPU cache data is stored in the template and reused across
// frames and display lists.
let prim_data = &ctx.data_stores.text_run[data_handle];
let prim_cache_address = gpu_cache.get_address(&prim_data.gpu_cache_handle);
let prim_header = PrimitiveHeader {
local_rect: prim_rect,
local_clip_rect: prim_info.combined_local_clip_rect,
snap_offsets,
specific_prim_address: prim_cache_address,
transform_id,
};
let clip_task_address = ctx.get_prim_clip_task_address(
prim_info.clip_task_index,
render_tasks,
).unwrap_or(OPAQUE_TASK_ADDRESS);
let glyph_keys = &ctx.scratch.glyph_keys[run.glyph_keys_range];
let rasterization_space = match run.raster_space {
RasterSpace::Screen => RasterizationSpace::Screen,
RasterSpace::Local(..) => RasterizationSpace::Local,
};
let raster_scale = run.raster_space.local_scale().unwrap_or(1.0).max(0.001);
let prim_header_index = prim_headers.push(
&prim_header,
z_id,
[
(run.reference_frame_relative_offset.x * 256.0) as i32,
(run.reference_frame_relative_offset.y * 256.0) as i32,
(raster_scale * 65535.0).round() as i32,
clip_task_address.0 as i32,
],
);
let base_instance = GlyphInstance::new(
prim_header_index,
);
let batchers = &mut self.batchers;
ctx.resource_cache.fetch_glyphs(
run.used_font.clone(),
&glyph_keys,
&mut self.glyph_fetch_buffer,
gpu_cache,
|texture_id, mut glyph_format, glyphs| {
debug_assert_ne!(texture_id, TextureSource::Invalid);
// Ignore color and only sample alpha when shadowing.
if run.shadow {
glyph_format = glyph_format.ignore_color();
}
let subpx_dir = subpx_dir.limit_by(glyph_format);
let textures = BatchTextures {
colors: [
texture_id,
TextureSource::Invalid,
TextureSource::Invalid,
],
};
let kind = BatchKind::TextRun(glyph_format);
let (blend_mode, color_mode) = match glyph_format {
GlyphFormat::Subpixel |
GlyphFormat::TransformedSubpixel => {
if run.used_font.bg_color.a != 0 {
(
BlendMode::SubpixelWithBgColor,
ShaderColorMode::FromRenderPassMode,
)
} else if ctx.use_dual_source_blending {
(
BlendMode::SubpixelDualSource,
ShaderColorMode::SubpixelDualSource,
)
} else {
(
BlendMode::SubpixelConstantTextColor(run.used_font.color.into()),
ShaderColorMode::SubpixelConstantTextColor,
)
}
}
GlyphFormat::Alpha |
GlyphFormat::TransformedAlpha => {
(
BlendMode::PremultipliedAlpha,
ShaderColorMode::Alpha,
)
}
GlyphFormat::Bitmap => {
(
BlendMode::PremultipliedAlpha,
ShaderColorMode::Bitmap,
)
}
GlyphFormat::ColorBitmap => {
(
BlendMode::PremultipliedAlpha,
ShaderColorMode::ColorBitmap,
)
}
};
let key = BatchKey::new(kind, blend_mode, textures);
for batcher in batchers.iter_mut() {
if batcher.vis_mask.intersects(prim_vis_mask) {
let render_task_address = batcher.render_task_address;
let batch = batcher.alpha_batch_list.set_params_and_get_batch(
key,
BatchFeatures::empty(),
bounding_rect,
z_id,
);
for glyph in glyphs {
batch.push(base_instance.build(
glyph.index_in_text_run | ((render_task_address.0 as i32) << 16),
glyph.uv_rect_address.as_int(),
(rasterization_space as i32) << 16 |
(subpx_dir as u32 as i32) << 8 |
(color_mode as u32 as i32),
));
}
}
}
},
);
}
PrimitiveInstanceKind::LineDecoration { data_handle, ref cache_handle, .. } => {
// The GPU cache data is stored in the template and reused across
// frames and display lists.
let common_data = &ctx.data_stores.line_decoration[data_handle].common;
let prim_cache_address = gpu_cache.get_address(&common_data.gpu_cache_handle);
let (batch_kind, textures, prim_user_data, segment_user_data) = match cache_handle {
Some(cache_handle) => {
let rt_cache_entry = ctx
.resource_cache
.get_cached_render_task(cache_handle);
let cache_item = ctx
.resource_cache
.get_texture_cache_item(&rt_cache_entry.handle);
let textures = BatchTextures::color(cache_item.texture_id);
(
BrushBatchKind::Image(get_buffer_kind(cache_item.texture_id)),
textures,
[
ShaderColorMode::Image as i32 | ((AlphaType::PremultipliedAlpha as i32) << 16),
RasterizationSpace::Local as i32,
get_shader_opacity(1.0),
0,