-
Notifications
You must be signed in to change notification settings - Fork 54
/
gradient.rs
793 lines (708 loc) · 27.9 KB
/
gradient.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
/* 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, ColorU, ExtendMode, GradientStop,
PremultipliedColorF, LineOrientation,
};
use api::units::{LayoutPoint, LayoutSize, LayoutVector2D};
use crate::display_list_flattener::IsVisible;
use euclid::approxeq::ApproxEq;
use crate::frame_builder::FrameBuildingState;
use crate::gpu_cache::{GpuCacheHandle, GpuDataRequest};
use crate::intern::{Internable, InternDebug, Handle as InternHandle};
use crate::internal_types::LayoutPrimitiveInfo;
use crate::prim_store::{BrushSegment, GradientTileRange, VectorKey};
use crate::prim_store::{PrimitiveInstanceKind, PrimitiveOpacity, PrimitiveSceneData};
use crate::prim_store::{PrimKeyCommonData, PrimTemplateCommonData, PrimitiveStore};
use crate::prim_store::{NinePatchDescriptor, PointKey, SizeKey, InternablePrimitive};
use crate::render_task::RenderTaskCacheEntryHandle;
use std::{hash, ops::{Deref, DerefMut}, mem};
use crate::util::pack_as_float;
/// The maximum number of stops a gradient may have to use the fast path.
pub const GRADIENT_FP_STOPS: usize = 4;
/// A hashable gradient stop that can be used in primitive keys.
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
#[derive(Debug, Copy, Clone, MallocSizeOf, PartialEq)]
pub struct GradientStopKey {
pub offset: f32,
pub color: ColorU,
}
impl GradientStopKey {
pub fn empty() -> Self {
GradientStopKey {
offset: 0.0,
color: ColorU::new(0, 0, 0, 0),
}
}
}
impl Into<GradientStopKey> for GradientStop {
fn into(self) -> GradientStopKey {
GradientStopKey {
offset: self.offset,
color: self.color.into(),
}
}
}
impl Eq for GradientStopKey {}
impl hash::Hash for GradientStopKey {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.offset.to_bits().hash(state);
self.color.hash(state);
}
}
/// Identifying key for a line decoration.
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
#[derive(Debug, Clone, Eq, PartialEq, Hash, MallocSizeOf)]
pub struct LinearGradientKey {
pub common: PrimKeyCommonData,
pub extend_mode: ExtendMode,
pub start_point: PointKey,
pub end_point: PointKey,
pub stretch_size: SizeKey,
pub tile_spacing: SizeKey,
pub stops: Vec<GradientStopKey>,
pub reverse_stops: bool,
pub nine_patch: Option<Box<NinePatchDescriptor>>,
}
impl LinearGradientKey {
pub fn new(
is_backface_visible: bool,
prim_size: LayoutSize,
linear_grad: LinearGradient,
) -> Self {
LinearGradientKey {
common: PrimKeyCommonData {
is_backface_visible,
prim_size: prim_size.into(),
},
extend_mode: linear_grad.extend_mode,
start_point: linear_grad.start_point,
end_point: linear_grad.end_point,
stretch_size: linear_grad.stretch_size,
tile_spacing: linear_grad.tile_spacing,
stops: linear_grad.stops,
reverse_stops: linear_grad.reverse_stops,
nine_patch: linear_grad.nine_patch,
}
}
}
impl InternDebug for LinearGradientKey {}
#[derive(Clone, Debug, Hash, MallocSizeOf, PartialEq, Eq)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct GradientCacheKey {
pub orientation: LineOrientation,
pub start_stop_point: VectorKey,
pub stops: [GradientStopKey; GRADIENT_FP_STOPS],
}
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
#[derive(MallocSizeOf)]
pub struct LinearGradientTemplate {
pub common: PrimTemplateCommonData,
pub extend_mode: ExtendMode,
pub start_point: LayoutPoint,
pub end_point: LayoutPoint,
pub stretch_size: LayoutSize,
pub tile_spacing: LayoutSize,
pub stops_opacity: PrimitiveOpacity,
pub stops: Vec<GradientStop>,
pub brush_segments: Vec<BrushSegment>,
pub reverse_stops: bool,
pub stops_handle: GpuCacheHandle,
/// If true, this gradient can be drawn via the fast path
/// (cache gradient, and draw as image).
pub supports_caching: bool,
}
impl Deref for LinearGradientTemplate {
type Target = PrimTemplateCommonData;
fn deref(&self) -> &Self::Target {
&self.common
}
}
impl DerefMut for LinearGradientTemplate {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.common
}
}
impl From<LinearGradientKey> for LinearGradientTemplate {
fn from(item: LinearGradientKey) -> Self {
let common = PrimTemplateCommonData::with_key_common(item.common);
let mut min_alpha: f32 = 1.0;
// Check if we can draw this gradient via a fast path by caching the
// gradient in a smaller task, and drawing as an image.
// TODO(gw): Aim to reduce the constraints on fast path gradients in future,
// although this catches the vast majority of gradients on real pages.
let mut supports_caching =
// No repeating support in fast path
item.extend_mode == ExtendMode::Clamp &&
// Gradient must cover entire primitive
item.tile_spacing.w + item.stretch_size.w >= common.prim_size.width &&
item.tile_spacing.h + item.stretch_size.h >= common.prim_size.height &&
// Must be a vertical or horizontal gradient
(item.start_point.x.approx_eq(&item.end_point.x) ||
item.start_point.y.approx_eq(&item.end_point.y)) &&
// Fast path supports a limited number of stops
item.stops.len() <= GRADIENT_FP_STOPS &&
// Fast path not supported on segmented (border-image) gradients.
item.nine_patch.is_none();
// Convert the stops to more convenient representation
// for the current gradient builder.
let mut prev_color = None;
let stops: Vec<GradientStop> = item.stops.iter().map(|stop| {
let color: ColorF = stop.color.into();
min_alpha = min_alpha.min(color.a);
if let Some(prev_color) = prev_color {
// The fast path doesn't support hard color stops, yet.
// Since the length of the gradient is a fixed size (512 device pixels), if there
// is a hard stop you will see bilinear interpolation with this method, instead
// of an abrupt color change.
if prev_color == color {
supports_caching = false;
}
}
prev_color = Some(color);
GradientStop {
offset: stop.offset,
color,
}
}).collect();
let mut brush_segments = Vec::new();
if let Some(ref nine_patch) = item.nine_patch {
brush_segments = nine_patch.create_segments(common.prim_size);
}
// Save opacity of the stops for use in
// selecting which pass this gradient
// should be drawn in.
let stops_opacity = PrimitiveOpacity::from_alpha(min_alpha);
LinearGradientTemplate {
common,
extend_mode: item.extend_mode,
start_point: item.start_point.into(),
end_point: item.end_point.into(),
stretch_size: item.stretch_size.into(),
tile_spacing: item.tile_spacing.into(),
stops_opacity,
stops,
brush_segments,
reverse_stops: item.reverse_stops,
stops_handle: GpuCacheHandle::new(),
supports_caching,
}
}
}
impl LinearGradientTemplate {
/// Update the GPU cache for a given primitive template. This may be called multiple
/// times per frame, by each primitive reference that refers to this interned
/// template. The initial request call to the GPU cache ensures that work is only
/// done if the cache entry is invalid (due to first use or eviction).
pub fn update(
&mut self,
frame_state: &mut FrameBuildingState,
) {
if let Some(mut request) =
frame_state.gpu_cache.request(&mut self.common.gpu_cache_handle) {
// write_prim_gpu_blocks
request.push([
self.start_point.x,
self.start_point.y,
self.end_point.x,
self.end_point.y,
]);
request.push([
pack_as_float(self.extend_mode as u32),
self.stretch_size.width,
self.stretch_size.height,
0.0,
]);
// write_segment_gpu_blocks
for segment in &self.brush_segments {
// has to match VECS_PER_SEGMENT
request.write_segment(
segment.local_rect,
segment.extra_data,
);
}
}
if let Some(mut request) = frame_state.gpu_cache.request(&mut self.stops_handle) {
GradientGpuBlockBuilder::build(
self.reverse_stops,
&mut request,
&self.stops,
);
}
self.opacity = {
// If the coverage of the gradient extends to or beyond
// the primitive rect, then the opacity can be determined
// by the colors of the stops. If we have tiling / spacing
// then we just assume the gradient is translucent for now.
// (In the future we could consider segmenting in some cases).
let stride = self.stretch_size + self.tile_spacing;
if stride.width >= self.common.prim_size.width &&
stride.height >= self.common.prim_size.height {
self.stops_opacity
} else {
PrimitiveOpacity::translucent()
}
}
}
}
pub type LinearGradientDataHandle = InternHandle<LinearGradient>;
#[derive(Debug, MallocSizeOf)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct LinearGradient {
pub extend_mode: ExtendMode,
pub start_point: PointKey,
pub end_point: PointKey,
pub stretch_size: SizeKey,
pub tile_spacing: SizeKey,
pub stops: Vec<GradientStopKey>,
pub reverse_stops: bool,
pub nine_patch: Option<Box<NinePatchDescriptor>>,
}
impl Internable for LinearGradient {
type Key = LinearGradientKey;
type StoreData = LinearGradientTemplate;
type InternData = PrimitiveSceneData;
}
impl InternablePrimitive for LinearGradient {
fn into_key(
self,
info: &LayoutPrimitiveInfo,
) -> LinearGradientKey {
LinearGradientKey::new(
info.is_backface_visible,
info.rect.size,
self
)
}
fn make_instance_kind(
_key: LinearGradientKey,
data_handle: LinearGradientDataHandle,
prim_store: &mut PrimitiveStore,
_reference_frame_relative_offset: LayoutVector2D,
) -> PrimitiveInstanceKind {
let gradient_index = prim_store.linear_gradients.push(LinearGradientPrimitive {
cache_handle: None,
visible_tiles_range: GradientTileRange::empty(),
});
PrimitiveInstanceKind::LinearGradient {
data_handle,
gradient_index,
}
}
}
impl IsVisible for LinearGradient {
fn is_visible(&self) -> bool {
true
}
}
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
pub struct LinearGradientPrimitive {
pub cache_handle: Option<RenderTaskCacheEntryHandle>,
pub visible_tiles_range: GradientTileRange,
}
////////////////////////////////////////////////////////////////////////////////
/// Hashable radial gradient parameters, for use during prim interning.
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
#[derive(Debug, Clone, MallocSizeOf, PartialEq)]
pub struct RadialGradientParams {
pub start_radius: f32,
pub end_radius: f32,
pub ratio_xy: f32,
}
impl Eq for RadialGradientParams {}
impl hash::Hash for RadialGradientParams {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.start_radius.to_bits().hash(state);
self.end_radius.to_bits().hash(state);
self.ratio_xy.to_bits().hash(state);
}
}
/// Identifying key for a line decoration.
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
#[derive(Debug, Clone, Eq, PartialEq, Hash, MallocSizeOf)]
pub struct RadialGradientKey {
pub common: PrimKeyCommonData,
pub extend_mode: ExtendMode,
pub center: PointKey,
pub params: RadialGradientParams,
pub stretch_size: SizeKey,
pub stops: Vec<GradientStopKey>,
pub tile_spacing: SizeKey,
pub nine_patch: Option<Box<NinePatchDescriptor>>,
}
impl RadialGradientKey {
pub fn new(
is_backface_visible: bool,
prim_size: LayoutSize,
radial_grad: RadialGradient,
) -> Self {
RadialGradientKey {
common: PrimKeyCommonData {
is_backface_visible,
prim_size: prim_size.into(),
},
extend_mode: radial_grad.extend_mode,
center: radial_grad.center,
params: radial_grad.params,
stretch_size: radial_grad.stretch_size,
stops: radial_grad.stops,
tile_spacing: radial_grad.tile_spacing,
nine_patch: radial_grad.nine_patch,
}
}
}
impl InternDebug for RadialGradientKey {}
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
#[derive(MallocSizeOf)]
pub struct RadialGradientTemplate {
pub common: PrimTemplateCommonData,
pub extend_mode: ExtendMode,
pub center: LayoutPoint,
pub params: RadialGradientParams,
pub stretch_size: LayoutSize,
pub tile_spacing: LayoutSize,
pub brush_segments: Vec<BrushSegment>,
pub stops: Vec<GradientStop>,
pub stops_handle: GpuCacheHandle,
}
impl Deref for RadialGradientTemplate {
type Target = PrimTemplateCommonData;
fn deref(&self) -> &Self::Target {
&self.common
}
}
impl DerefMut for RadialGradientTemplate {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.common
}
}
impl From<RadialGradientKey> for RadialGradientTemplate {
fn from(item: RadialGradientKey) -> Self {
let common = PrimTemplateCommonData::with_key_common(item.common);
let mut brush_segments = Vec::new();
if let Some(ref nine_patch) = item.nine_patch {
brush_segments = nine_patch.create_segments(common.prim_size);
}
let stops = item.stops.iter().map(|stop| {
GradientStop {
offset: stop.offset,
color: stop.color.into(),
}
}).collect();
RadialGradientTemplate {
common,
center: item.center.into(),
extend_mode: item.extend_mode,
params: item.params,
stretch_size: item.stretch_size.into(),
tile_spacing: item.tile_spacing.into(),
brush_segments: brush_segments,
stops,
stops_handle: GpuCacheHandle::new(),
}
}
}
impl RadialGradientTemplate {
/// Update the GPU cache for a given primitive template. This may be called multiple
/// times per frame, by each primitive reference that refers to this interned
/// template. The initial request call to the GPU cache ensures that work is only
/// done if the cache entry is invalid (due to first use or eviction).
pub fn update(
&mut self,
frame_state: &mut FrameBuildingState,
) {
if let Some(mut request) =
frame_state.gpu_cache.request(&mut self.common.gpu_cache_handle) {
// write_prim_gpu_blocks
request.push([
self.center.x,
self.center.y,
self.params.start_radius,
self.params.end_radius,
]);
request.push([
self.params.ratio_xy,
pack_as_float(self.extend_mode as u32),
self.stretch_size.width,
self.stretch_size.height,
]);
// write_segment_gpu_blocks
for segment in &self.brush_segments {
// has to match VECS_PER_SEGMENT
request.write_segment(
segment.local_rect,
segment.extra_data,
);
}
}
if let Some(mut request) = frame_state.gpu_cache.request(&mut self.stops_handle) {
GradientGpuBlockBuilder::build(
false,
&mut request,
&self.stops,
);
}
self.opacity = PrimitiveOpacity::translucent();
}
}
pub type RadialGradientDataHandle = InternHandle<RadialGradient>;
#[derive(Debug, MallocSizeOf)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct RadialGradient {
pub extend_mode: ExtendMode,
pub center: PointKey,
pub params: RadialGradientParams,
pub stretch_size: SizeKey,
pub stops: Vec<GradientStopKey>,
pub tile_spacing: SizeKey,
pub nine_patch: Option<Box<NinePatchDescriptor>>,
}
impl Internable for RadialGradient {
type Key = RadialGradientKey;
type StoreData = RadialGradientTemplate;
type InternData = PrimitiveSceneData;
}
impl InternablePrimitive for RadialGradient {
fn into_key(
self,
info: &LayoutPrimitiveInfo,
) -> RadialGradientKey {
RadialGradientKey::new(
info.is_backface_visible,
info.rect.size,
self,
)
}
fn make_instance_kind(
_key: RadialGradientKey,
data_handle: RadialGradientDataHandle,
_prim_store: &mut PrimitiveStore,
_reference_frame_relative_offset: LayoutVector2D,
) -> PrimitiveInstanceKind {
PrimitiveInstanceKind::RadialGradient {
data_handle,
visible_tiles_range: GradientTileRange::empty(),
}
}
}
impl IsVisible for RadialGradient {
fn is_visible(&self) -> bool {
true
}
}
////////////////////////////////////////////////////////////////////////////////
// The gradient entry index for the first color stop
pub const GRADIENT_DATA_FIRST_STOP: usize = 0;
// The gradient entry index for the last color stop
pub const GRADIENT_DATA_LAST_STOP: usize = GRADIENT_DATA_SIZE - 1;
// The start of the gradient data table
pub const GRADIENT_DATA_TABLE_BEGIN: usize = GRADIENT_DATA_FIRST_STOP + 1;
// The exclusive bound of the gradient data table
pub const GRADIENT_DATA_TABLE_END: usize = GRADIENT_DATA_LAST_STOP;
// The number of entries in the gradient data table.
pub const GRADIENT_DATA_TABLE_SIZE: usize = 128;
// The number of entries in a gradient data: GRADIENT_DATA_TABLE_SIZE + first stop entry + last stop entry
pub const GRADIENT_DATA_SIZE: usize = GRADIENT_DATA_TABLE_SIZE + 2;
#[derive(Debug)]
#[repr(C)]
// An entry in a gradient data table representing a segment of the gradient color space.
pub struct GradientDataEntry {
pub start_color: PremultipliedColorF,
pub end_color: PremultipliedColorF,
}
// TODO(gw): Tidy this up to be a free function / module?
struct GradientGpuBlockBuilder {}
impl GradientGpuBlockBuilder {
/// Generate a color ramp filling the indices in [start_idx, end_idx) and interpolating
/// from start_color to end_color.
fn fill_colors(
start_idx: usize,
end_idx: usize,
start_color: &PremultipliedColorF,
end_color: &PremultipliedColorF,
entries: &mut [GradientDataEntry; GRADIENT_DATA_SIZE],
) {
// Calculate the color difference for individual steps in the ramp.
let inv_steps = 1.0 / (end_idx - start_idx) as f32;
let step_r = (end_color.r - start_color.r) * inv_steps;
let step_g = (end_color.g - start_color.g) * inv_steps;
let step_b = (end_color.b - start_color.b) * inv_steps;
let step_a = (end_color.a - start_color.a) * inv_steps;
let mut cur_color = *start_color;
// Walk the ramp writing start and end colors for each entry.
for index in start_idx .. end_idx {
let entry = &mut entries[index];
entry.start_color = cur_color;
cur_color.r += step_r;
cur_color.g += step_g;
cur_color.b += step_b;
cur_color.a += step_a;
entry.end_color = cur_color;
}
}
/// Compute an index into the gradient entry table based on a gradient stop offset. This
/// function maps offsets from [0, 1] to indices in [GRADIENT_DATA_TABLE_BEGIN, GRADIENT_DATA_TABLE_END].
#[inline]
fn get_index(offset: f32) -> usize {
(offset.max(0.0).min(1.0) * GRADIENT_DATA_TABLE_SIZE as f32 +
GRADIENT_DATA_TABLE_BEGIN as f32)
.round() as usize
}
// Build the gradient data from the supplied stops, reversing them if necessary.
fn build(
reverse_stops: bool,
request: &mut GpuDataRequest,
src_stops: &[GradientStop],
) {
// Preconditions (should be ensured by DisplayListBuilder):
// * we have at least two stops
// * first stop has offset 0.0
// * last stop has offset 1.0
let mut src_stops = src_stops.into_iter();
let mut cur_color = match src_stops.next() {
Some(stop) => {
debug_assert_eq!(stop.offset, 0.0);
stop.color.premultiplied()
}
None => {
error!("Zero gradient stops found!");
PremultipliedColorF::BLACK
}
};
// A table of gradient entries, with two colors per entry, that specify the start and end color
// within the segment of the gradient space represented by that entry. To lookup a gradient result,
// first the entry index is calculated to determine which two colors to interpolate between, then
// the offset within that entry bucket is used to interpolate between the two colors in that entry.
// This layout preserves hard stops, as the end color for a given entry can differ from the start
// color for the following entry, despite them being adjacent. Colors are stored within in BGRA8
// format for texture upload. This table requires the gradient color stops to be normalized to the
// range [0, 1]. The first and last entries hold the first and last color stop colors respectively,
// while the entries in between hold the interpolated color stop values for the range [0, 1].
let mut entries: [GradientDataEntry; GRADIENT_DATA_SIZE] = unsafe { mem::uninitialized() };
if reverse_stops {
// Fill in the first entry (for reversed stops) with the first color stop
GradientGpuBlockBuilder::fill_colors(
GRADIENT_DATA_LAST_STOP,
GRADIENT_DATA_LAST_STOP + 1,
&cur_color,
&cur_color,
&mut entries,
);
// Fill in the center of the gradient table, generating a color ramp between each consecutive pair
// of gradient stops. Each iteration of a loop will fill the indices in [next_idx, cur_idx). The
// loop will then fill indices in [GRADIENT_DATA_TABLE_BEGIN, GRADIENT_DATA_TABLE_END).
let mut cur_idx = GRADIENT_DATA_TABLE_END;
for next in src_stops {
let next_color = next.color.premultiplied();
let next_idx = Self::get_index(1.0 - next.offset);
if next_idx < cur_idx {
GradientGpuBlockBuilder::fill_colors(
next_idx,
cur_idx,
&next_color,
&cur_color,
&mut entries,
);
cur_idx = next_idx;
}
cur_color = next_color;
}
if cur_idx != GRADIENT_DATA_TABLE_BEGIN {
error!("Gradient stops abruptly at {}, auto-completing to white", cur_idx);
GradientGpuBlockBuilder::fill_colors(
GRADIENT_DATA_TABLE_BEGIN,
cur_idx,
&PremultipliedColorF::WHITE,
&cur_color,
&mut entries,
);
}
// Fill in the last entry (for reversed stops) with the last color stop
GradientGpuBlockBuilder::fill_colors(
GRADIENT_DATA_FIRST_STOP,
GRADIENT_DATA_FIRST_STOP + 1,
&cur_color,
&cur_color,
&mut entries,
);
} else {
// Fill in the first entry with the first color stop
GradientGpuBlockBuilder::fill_colors(
GRADIENT_DATA_FIRST_STOP,
GRADIENT_DATA_FIRST_STOP + 1,
&cur_color,
&cur_color,
&mut entries,
);
// Fill in the center of the gradient table, generating a color ramp between each consecutive pair
// of gradient stops. Each iteration of a loop will fill the indices in [cur_idx, next_idx). The
// loop will then fill indices in [GRADIENT_DATA_TABLE_BEGIN, GRADIENT_DATA_TABLE_END).
let mut cur_idx = GRADIENT_DATA_TABLE_BEGIN;
for next in src_stops {
let next_color = next.color.premultiplied();
let next_idx = Self::get_index(next.offset);
if next_idx > cur_idx {
GradientGpuBlockBuilder::fill_colors(
cur_idx,
next_idx,
&cur_color,
&next_color,
&mut entries,
);
cur_idx = next_idx;
}
cur_color = next_color;
}
if cur_idx != GRADIENT_DATA_TABLE_END {
error!("Gradient stops abruptly at {}, auto-completing to white", cur_idx);
GradientGpuBlockBuilder::fill_colors(
cur_idx,
GRADIENT_DATA_TABLE_END,
&PremultipliedColorF::WHITE,
&cur_color,
&mut entries,
);
}
// Fill in the last entry with the last color stop
GradientGpuBlockBuilder::fill_colors(
GRADIENT_DATA_LAST_STOP,
GRADIENT_DATA_LAST_STOP + 1,
&cur_color,
&cur_color,
&mut entries,
);
}
for entry in entries.iter() {
request.push(entry.start_color);
request.push(entry.end_color);
}
}
}
#[test]
#[cfg(target_pointer_width = "64")]
fn test_struct_sizes() {
use std::mem;
// The sizes of these structures are critical for performance on a number of
// talos stress tests. If you get a failure here on CI, there's two possibilities:
// (a) You made a structure smaller than it currently is. Great work! Update the
// test expectations and move on.
// (b) You made a structure larger. This is not necessarily a problem, but should only
// be done with care, and after checking if talos performance regresses badly.
assert_eq!(mem::size_of::<LinearGradient>(), 72, "LinearGradient size changed");
assert_eq!(mem::size_of::<LinearGradientTemplate>(), 112, "LinearGradientTemplate size changed");
assert_eq!(mem::size_of::<LinearGradientKey>(), 80, "LinearGradientKey size changed");
assert_eq!(mem::size_of::<RadialGradient>(), 72, "RadialGradient size changed");
assert_eq!(mem::size_of::<RadialGradientTemplate>(), 120, "RadialGradientTemplate size changed");
assert_eq!(mem::size_of::<RadialGradientKey>(), 88, "RadialGradientKey size changed");
}