-
Notifications
You must be signed in to change notification settings - Fork 54
/
resource_cache.rs
2306 lines (2070 loc) · 86.5 KB
/
resource_cache.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::{AddFont, BlobImageResources, AsyncBlobImageRasterizer, ResourceUpdate};
use api::{BlobImageDescriptor, BlobImageHandler, BlobImageRequest, RasterizedBlobImage};
use api::{ClearCache, DebugFlags, FontInstanceKey, FontKey, FontTemplate, GlyphIndex};
use api::{ExternalImageData, ExternalImageType, BlobImageResult, BlobImageParams};
use api::{FontInstanceData, FontInstanceOptions, FontInstancePlatformOptions, FontVariation};
use api::{DirtyRect, GlyphDimensions, IdNamespace};
use api::{ImageData, ImageDescriptor, ImageKey, ImageRendering, TileSize};
use api::{BlobImageData, BlobImageKey, MemoryReport, VoidPtrToSizeFn};
use api::units::*;
#[cfg(feature = "capture")]
use crate::capture::ExternalCaptureImage;
#[cfg(feature = "replay")]
use crate::capture::PlainExternalImage;
#[cfg(any(feature = "replay", feature = "png"))]
use crate::capture::CaptureConfig;
use crate::device::TextureFilter;
use euclid::{point2, size2};
use crate::glyph_cache::GlyphCache;
#[cfg(not(feature = "pathfinder"))]
use crate::glyph_cache::GlyphCacheEntry;
use crate::glyph_rasterizer::{BaseFontInstance, FontInstance, GlyphFormat, GlyphKey, GlyphRasterizer};
use crate::gpu_cache::{GpuCache, GpuCacheAddress, GpuCacheHandle};
use crate::gpu_types::UvRectKind;
use crate::image::{compute_tile_size, compute_tile_range, for_each_tile_in_range};
use crate::internal_types::{FastHashMap, FastHashSet, TextureSource, TextureUpdateList};
use crate::profiler::{ResourceProfileCounters, TextureCacheProfileCounters};
use crate::render_backend::{FrameId, FrameStamp};
use crate::render_task::{RenderTaskCache, RenderTaskCacheKey, RenderTaskId};
use crate::render_task::{RenderTaskCacheEntry, RenderTaskCacheEntryHandle, RenderTaskGraph};
use smallvec::SmallVec;
use std::collections::hash_map::Entry::{self, Occupied, Vacant};
use std::collections::hash_map::{Iter, IterMut};
use std::collections::VecDeque;
use std::{cmp, mem};
use std::fmt::Debug;
use std::hash::Hash;
use std::os::raw::c_void;
#[cfg(any(feature = "capture", feature = "replay"))]
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
use std::time::SystemTime;
use crate::texture_cache::{TextureCache, TextureCacheHandle, Eviction};
use crate::util::drain_filter;
const DEFAULT_TILE_SIZE: TileSize = 512;
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct GlyphFetchResult {
pub index_in_text_run: i32,
pub uv_rect_address: GpuCacheAddress,
}
// These coordinates are always in texels.
// They are converted to normalized ST
// values in the vertex shader. The reason
// for this is that the texture may change
// dimensions (e.g. the pages in a texture
// atlas can grow). When this happens, by
// storing the coordinates as texel values
// we don't need to go through and update
// various CPU-side structures.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct CacheItem {
pub texture_id: TextureSource,
pub uv_rect_handle: GpuCacheHandle,
pub uv_rect: DeviceIntRect,
pub texture_layer: i32,
}
impl CacheItem {
pub fn invalid() -> Self {
CacheItem {
texture_id: TextureSource::Invalid,
uv_rect_handle: GpuCacheHandle::new(),
uv_rect: DeviceIntRect::zero(),
texture_layer: 0,
}
}
}
/// Represents the backing store of an image in the cache.
/// This storage can take several forms.
#[derive(Clone, Debug)]
pub enum CachedImageData {
/// A simple series of bytes, provided by the embedding and owned by WebRender.
/// The format is stored out-of-band, currently in ImageDescriptor.
Raw(Arc<Vec<u8>>),
/// An series of commands that can be rasterized into an image via an
/// embedding-provided callback.
///
/// The commands are stored elsewhere and this variant is used as a placeholder.
Blob,
/// An image owned by the embedding, and referenced by WebRender. This may
/// take the form of a texture or a heap-allocated buffer.
External(ExternalImageData),
}
impl From<ImageData> for CachedImageData {
fn from(img_data: ImageData) -> Self {
match img_data {
ImageData::Raw(data) => CachedImageData::Raw(data),
ImageData::External(data) => CachedImageData::External(data),
}
}
}
impl CachedImageData {
/// Returns true if this represents a blob.
#[inline]
pub fn is_blob(&self) -> bool {
match *self {
CachedImageData::Blob => true,
_ => false,
}
}
/// Returns true if this variant of CachedImageData should go through the texture
/// cache.
#[inline]
pub fn uses_texture_cache(&self) -> bool {
match *self {
CachedImageData::External(ref ext_data) => match ext_data.image_type {
ExternalImageType::TextureHandle(_) => false,
ExternalImageType::Buffer => true,
},
CachedImageData::Blob => true,
CachedImageData::Raw(_) => true,
}
}
}
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct ImageProperties {
pub descriptor: ImageDescriptor,
pub external_image: Option<ExternalImageData>,
pub tiling: Option<TileSize>,
}
#[derive(Debug, Copy, Clone, PartialEq)]
enum State {
Idle,
AddResources,
QueryResources,
}
/// Post scene building state.
enum RasterizedBlob {
Tiled(FastHashMap<TileOffset, RasterizedBlobImage>),
NonTiled(Vec<RasterizedBlobImage>),
}
/// Pre scene building state.
/// We use this to generate the async blob rendering requests.
struct BlobImageTemplate {
descriptor: ImageDescriptor,
tiling: Option<TileSize>,
dirty_rect: BlobDirtyRect,
viewport_tiles: Option<TileRange>,
}
struct ImageResource {
data: CachedImageData,
descriptor: ImageDescriptor,
tiling: Option<TileSize>,
}
#[derive(Clone, Debug)]
pub struct ImageTiling {
pub image_size: DeviceIntSize,
pub tile_size: TileSize,
}
#[derive(Default)]
struct ImageTemplates {
images: FastHashMap<ImageKey, ImageResource>,
}
impl ImageTemplates {
fn insert(&mut self, key: ImageKey, resource: ImageResource) {
self.images.insert(key, resource);
}
fn remove(&mut self, key: ImageKey) -> Option<ImageResource> {
self.images.remove(&key)
}
fn get(&self, key: ImageKey) -> Option<&ImageResource> {
self.images.get(&key)
}
fn get_mut(&mut self, key: ImageKey) -> Option<&mut ImageResource> {
self.images.get_mut(&key)
}
}
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
struct CachedImageInfo {
texture_cache_handle: TextureCacheHandle,
dirty_rect: ImageDirtyRect,
manual_eviction: bool,
}
impl CachedImageInfo {
fn mark_unused(&mut self, texture_cache: &mut TextureCache) {
texture_cache.mark_unused(&self.texture_cache_handle);
self.manual_eviction = false;
}
}
#[cfg(debug_assertions)]
impl Drop for CachedImageInfo {
fn drop(&mut self) {
debug_assert!(!self.manual_eviction, "Manual eviction requires cleanup");
}
}
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct ResourceClassCache<K: Hash + Eq, V, U: Default> {
resources: FastHashMap<K, V>,
pub user_data: U,
}
impl<K, V, U> ResourceClassCache<K, V, U>
where
K: Clone + Hash + Eq + Debug,
U: Default,
{
pub fn new() -> Self {
ResourceClassCache {
resources: FastHashMap::default(),
user_data: Default::default(),
}
}
pub fn get(&self, key: &K) -> &V {
self.resources.get(key)
.expect("Didn't find a cached resource with that ID!")
}
pub fn try_get(&self, key: &K) -> Option<&V> {
self.resources.get(key)
}
pub fn insert(&mut self, key: K, value: V) {
self.resources.insert(key, value);
}
pub fn remove(&mut self, key: &K) -> Option<V> {
self.resources.remove(key)
}
pub fn get_mut(&mut self, key: &K) -> &mut V {
self.resources.get_mut(key)
.expect("Didn't find a cached resource with that ID!")
}
pub fn try_get_mut(&mut self, key: &K) -> Option<&mut V> {
self.resources.get_mut(key)
}
pub fn entry(&mut self, key: K) -> Entry<K, V> {
self.resources.entry(key)
}
pub fn iter(&self) -> Iter<K, V> {
self.resources.iter()
}
pub fn iter_mut(&mut self) -> IterMut<K, V> {
self.resources.iter_mut()
}
pub fn is_empty(&mut self) -> bool {
self.resources.is_empty()
}
pub fn clear(&mut self) {
self.resources.clear();
}
pub fn retain<F>(&mut self, f: F)
where
F: FnMut(&K, &mut V) -> bool,
{
self.resources.retain(f);
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
struct CachedImageKey {
pub rendering: ImageRendering,
pub tile: Option<TileOffset>,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct ImageRequest {
pub key: ImageKey,
pub rendering: ImageRendering,
pub tile: Option<TileOffset>,
}
impl ImageRequest {
pub fn with_tile(&self, offset: TileOffset) -> Self {
ImageRequest {
key: self.key,
rendering: self.rendering,
tile: Some(offset),
}
}
pub fn is_untiled_auto(&self) -> bool {
self.tile.is_none() && self.rendering == ImageRendering::Auto
}
}
impl Into<BlobImageRequest> for ImageRequest {
fn into(self) -> BlobImageRequest {
BlobImageRequest {
key: BlobImageKey(self.key),
tile: self.tile,
}
}
}
impl Into<CachedImageKey> for ImageRequest {
fn into(self) -> CachedImageKey {
CachedImageKey {
rendering: self.rendering,
tile: self.tile,
}
}
}
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Clone, Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum ImageCacheError {
OverLimitSize,
}
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
enum ImageResult {
UntiledAuto(CachedImageInfo),
Multi(ResourceClassCache<CachedImageKey, CachedImageInfo, ()>),
Err(ImageCacheError),
}
impl ImageResult {
/// Releases any texture cache entries held alive by this ImageResult.
fn drop_from_cache(&mut self, texture_cache: &mut TextureCache) {
match *self {
ImageResult::UntiledAuto(ref mut entry) => {
entry.mark_unused(texture_cache);
},
ImageResult::Multi(ref mut entries) => {
for (_, entry) in &mut entries.resources {
entry.mark_unused(texture_cache);
}
},
ImageResult::Err(_) => {},
}
}
}
type ImageCache = ResourceClassCache<ImageKey, ImageResult, ()>;
pub type FontInstanceMap = Arc<RwLock<FastHashMap<FontInstanceKey, Arc<BaseFontInstance>>>>;
#[derive(Default)]
struct Resources {
font_templates: FastHashMap<FontKey, FontTemplate>,
font_instances: FontInstanceMap,
image_templates: ImageTemplates,
}
impl BlobImageResources for Resources {
fn get_font_data(&self, key: FontKey) -> &FontTemplate {
self.font_templates.get(&key).unwrap()
}
fn get_font_instance_data(&self, key: FontInstanceKey) -> Option<FontInstanceData> {
match self.font_instances.read().unwrap().get(&key) {
Some(instance) => Some(FontInstanceData {
font_key: instance.font_key,
size: instance.size,
options: Some(FontInstanceOptions {
render_mode: instance.render_mode,
flags: instance.flags,
bg_color: instance.bg_color,
synthetic_italics: instance.synthetic_italics,
}),
platform_options: instance.platform_options,
variations: instance.variations.clone(),
}),
None => None,
}
}
}
// We only use this to report glyph dimensions to the user of the API, so using
// the font instance key should be enough. If we start using it to cache dimensions
// for internal font instances we should change the hash key accordingly.
pub type GlyphDimensionsCache = FastHashMap<(FontInstanceKey, GlyphIndex), Option<GlyphDimensions>>;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BlobImageRasterizerEpoch(usize);
/// Stores parameters for clearing blob image tiles.
///
/// The clearing is necessary when originally requested tile range exceeds
/// MAX_TILES_PER_REQUEST. In this case, some tiles are not rasterized by
/// AsyncBlobImageRasterizer. They need to be cleared.
#[derive(Clone, Copy, Debug)]
pub struct BlobImageClearParams {
pub key: BlobImageKey,
/// Originally requested tile range to rasterize.
pub original_tile_range: TileRange,
/// Actual tile range that is requested to rasterize by
/// AsyncBlobImageRasterizer.
pub actual_tile_range: TileRange,
}
/// Information attached to AsyncBlobImageRasterizer.
#[derive(Clone, Debug)]
pub struct AsyncBlobImageInfo {
pub epoch: BlobImageRasterizerEpoch,
pub clear_requests: Vec<BlobImageClearParams>,
}
/// High-level container for resources managed by the `RenderBackend`.
///
/// This includes a variety of things, including images, fonts, and glyphs,
/// which may be stored as memory buffers, GPU textures, or handles to resources
/// managed by the OS or other parts of WebRender.
pub struct ResourceCache {
cached_glyphs: GlyphCache,
cached_images: ImageCache,
cached_render_tasks: RenderTaskCache,
resources: Resources,
state: State,
current_frame_id: FrameId,
pub texture_cache: TextureCache,
/// TODO(gw): We should expire (parts of) this cache semi-regularly!
cached_glyph_dimensions: GlyphDimensionsCache,
glyph_rasterizer: GlyphRasterizer,
/// The set of images that aren't present or valid in the texture cache,
/// and need to be rasterized and/or uploaded this frame. This includes
/// both blobs and regular images.
pending_image_requests: FastHashSet<ImageRequest>,
blob_image_handler: Option<Box<dyn BlobImageHandler>>,
rasterized_blob_images: FastHashMap<BlobImageKey, RasterizedBlob>,
blob_image_templates: FastHashMap<BlobImageKey, BlobImageTemplate>,
/// If while building a frame we encounter blobs that we didn't already
/// rasterize, add them to this list and rasterize them synchronously.
missing_blob_images: Vec<BlobImageParams>,
/// The rasterizer associated with the current scene.
blob_image_rasterizer: Option<Box<dyn AsyncBlobImageRasterizer>>,
/// An epoch of the stored blob image rasterizer, used to skip the ones
/// coming from low-priority scene builds if the current one is newer.
/// This is to be removed when we get rid of the whole "missed" blob
/// images concept.
/// The produced one gets bumped whenever we produce a rasteriezer,
/// which then travels through the scene building and eventually gets
/// consumed back by us, bumping the consumed epoch.
blob_image_rasterizer_produced_epoch: BlobImageRasterizerEpoch,
blob_image_rasterizer_consumed_epoch: BlobImageRasterizerEpoch,
/// A log of the last three frames worth of deleted image keys kept
/// for debugging purposes.
deleted_blob_keys: VecDeque<Vec<BlobImageKey>>,
/// A set of the image keys that have been requested, and require
/// updates to the texture cache. Images in this category trigger
/// invalidations for picture caching tiles.
dirty_image_keys: FastHashSet<ImageKey>,
}
impl ResourceCache {
pub fn new(
texture_cache: TextureCache,
glyph_rasterizer: GlyphRasterizer,
cached_glyphs: GlyphCache,
blob_image_handler: Option<Box<dyn BlobImageHandler>>,
) -> Self {
ResourceCache {
cached_glyphs,
cached_images: ResourceClassCache::new(),
cached_render_tasks: RenderTaskCache::new(),
resources: Resources::default(),
cached_glyph_dimensions: FastHashMap::default(),
texture_cache,
state: State::Idle,
current_frame_id: FrameId::INVALID,
pending_image_requests: FastHashSet::default(),
glyph_rasterizer,
blob_image_handler,
rasterized_blob_images: FastHashMap::default(),
blob_image_templates: FastHashMap::default(),
missing_blob_images: Vec::new(),
blob_image_rasterizer: None,
blob_image_rasterizer_produced_epoch: BlobImageRasterizerEpoch(0),
blob_image_rasterizer_consumed_epoch: BlobImageRasterizerEpoch(0),
// We want to keep three frames worth of delete blob keys
deleted_blob_keys: vec![Vec::new(), Vec::new(), Vec::new()].into(),
dirty_image_keys: FastHashSet::default(),
}
}
pub fn max_texture_size(&self) -> i32 {
self.texture_cache.max_texture_size()
}
fn should_tile(limit: i32, descriptor: &ImageDescriptor, data: &CachedImageData) -> bool {
let size_check = descriptor.size.width > limit || descriptor.size.height > limit;
match *data {
CachedImageData::Raw(_) | CachedImageData::Blob => size_check,
CachedImageData::External(info) => {
// External handles already represent existing textures so it does
// not make sense to tile them into smaller ones.
info.image_type == ExternalImageType::Buffer && size_check
}
}
}
// Request the texture cache item for a cacheable render
// task. If the item is already cached, the texture cache
// handle will be returned. Otherwise, the user supplied
// closure will be invoked to generate the render task
// chain that is required to draw this task.
pub fn request_render_task<F>(
&mut self,
key: RenderTaskCacheKey,
gpu_cache: &mut GpuCache,
render_tasks: &mut RenderTaskGraph,
user_data: Option<[f32; 3]>,
is_opaque: bool,
f: F,
) -> RenderTaskCacheEntryHandle where F: FnOnce(&mut RenderTaskGraph) -> RenderTaskId {
self.cached_render_tasks.request_render_task(
key,
&mut self.texture_cache,
gpu_cache,
render_tasks,
user_data,
is_opaque,
|render_task_tree| Ok(f(render_task_tree))
).expect("Failed to request a render task from the resource cache!")
}
pub fn post_scene_building_update(
&mut self,
updates: Vec<ResourceUpdate>,
profile_counters: &mut ResourceProfileCounters,
) {
// TODO, there is potential for optimization here, by processing updates in
// bulk rather than one by one (for example by sorting allocations by size or
// in a way that reduces fragmentation in the atlas).
for update in updates {
match update {
ResourceUpdate::AddImage(img) => {
if let ImageData::Raw(ref bytes) = img.data {
profile_counters.image_templates.inc(bytes.len());
}
self.add_image_template(img.key, img.descriptor, img.data.into(), img.tiling);
}
ResourceUpdate::UpdateImage(img) => {
self.update_image_template(img.key, img.descriptor, img.data.into(), &img.dirty_rect);
}
ResourceUpdate::AddBlobImage(img) => {
self.add_image_template(
img.key.as_image(),
img.descriptor,
CachedImageData::Blob,
img.tiling,
);
}
ResourceUpdate::UpdateBlobImage(img) => {
self.update_image_template(
img.key.as_image(),
img.descriptor,
CachedImageData::Blob,
&to_image_dirty_rect(
&img.dirty_rect
),
);
}
ResourceUpdate::DeleteImage(img) => {
self.delete_image_template(img);
}
ResourceUpdate::DeleteFont(font) => {
self.delete_font_template(font);
}
ResourceUpdate::DeleteFontInstance(font) => {
self.delete_font_instance(font);
}
ResourceUpdate::SetBlobImageVisibleArea(key, area) => {
self.discard_tiles_outside_visible_area(key, &area);
}
ResourceUpdate::AddFont(_) |
ResourceUpdate::AddFontInstance(_) => {
// Handled in update_resources_pre_scene_building
}
}
}
}
pub fn pre_scene_building_update(
&mut self,
updates: &mut Vec<ResourceUpdate>,
profile_counters: &mut ResourceProfileCounters,
) {
for update in updates.iter() {
match *update {
ResourceUpdate::AddBlobImage(ref img) => {
self.add_blob_image(
img.key,
&img.descriptor,
img.tiling,
Arc::clone(&img.data),
);
}
ResourceUpdate::UpdateBlobImage(ref img) => {
self.update_blob_image(
img.key,
&img.descriptor,
&img.dirty_rect,
Arc::clone(&img.data),
);
}
ResourceUpdate::SetBlobImageVisibleArea(ref key, ref area) => {
if let Some(template) = self.blob_image_templates.get_mut(&key) {
if let Some(tile_size) = template.tiling {
template.viewport_tiles = Some(compute_tile_range(
&area,
tile_size,
));
}
}
}
_ => {}
}
}
drain_filter(
updates,
|update| match *update {
ResourceUpdate::AddFont(_) |
ResourceUpdate::AddFontInstance(_) => true,
_ => false,
},
// Updates that were moved out of the array:
|update: ResourceUpdate| match update {
ResourceUpdate::AddFont(font) => {
match font {
AddFont::Raw(id, bytes, index) => {
profile_counters.font_templates.inc(bytes.len());
self.add_font_template(id, FontTemplate::Raw(Arc::new(bytes), index));
}
AddFont::Native(id, native_font_handle) => {
self.add_font_template(id, FontTemplate::Native(native_font_handle));
}
}
}
ResourceUpdate::AddFontInstance(instance) => {
self.add_font_instance(
instance.key,
instance.font_key,
instance.glyph_size,
instance.options,
instance.platform_options,
instance.variations,
);
}
_ => { unreachable!(); }
}
);
}
pub fn set_blob_rasterizer(
&mut self, rasterizer: Box<dyn AsyncBlobImageRasterizer>,
supp: AsyncBlobImageInfo,
) {
if self.blob_image_rasterizer_consumed_epoch.0 < supp.epoch.0 {
self.blob_image_rasterizer = Some(rasterizer);
self.blob_image_rasterizer_consumed_epoch = supp.epoch;
}
// Discard blob image tiles that are not rendered by AsyncBlobImageRasterizer.
// It happens when originally requested tile range exceeds MAX_TILES_PER_REQUEST.
for req in supp.clear_requests {
let tiles = match self.rasterized_blob_images.get_mut(&req.key) {
Some(RasterizedBlob::Tiled(tiles)) => tiles,
_ => { continue; }
};
tiles.retain(|tile, _| {
!req.original_tile_range.contains(tile) ||
req.actual_tile_range.contains(tile)
});
let texture_cache = &mut self.texture_cache;
match self.cached_images.try_get_mut(&req.key.as_image()) {
Some(&mut ImageResult::Multi(ref mut entries)) => {
entries.retain(|key, entry| {
if !req.original_tile_range.contains(&key.tile.unwrap()) ||
req.actual_tile_range.contains(&key.tile.unwrap()) {
return true;
}
entry.mark_unused(texture_cache);
return false;
});
}
_ => {}
}
}
}
pub fn add_rasterized_blob_images(&mut self, images: Vec<(BlobImageRequest, BlobImageResult)>) {
for (request, result) in images {
let data = match result {
Ok(data) => data,
Err(..) => {
warn!("Failed to rasterize a blob image");
continue;
}
};
// First make sure we have an entry for this key (using a placeholder
// if need be).
let image = self.rasterized_blob_images.entry(request.key).or_insert_with(
|| { RasterizedBlob::Tiled(FastHashMap::default()) }
);
if let Some(tile) = request.tile {
if let RasterizedBlob::NonTiled(..) = *image {
*image = RasterizedBlob::Tiled(FastHashMap::default());
}
if let RasterizedBlob::Tiled(ref mut tiles) = *image {
tiles.insert(tile, data);
}
} else {
if let RasterizedBlob::NonTiled(ref mut queue) = *image {
// If our new rasterized rect overwrites items in the queue, discard them.
queue.retain(|img| {
!data.rasterized_rect.contains_rect(&img.rasterized_rect)
});
queue.push(data);
} else {
*image = RasterizedBlob::NonTiled(vec![data]);
}
}
}
}
pub fn add_font_template(&mut self, font_key: FontKey, template: FontTemplate) {
// Push the new font to the font renderer, and also store
// it locally for glyph metric requests.
self.glyph_rasterizer.add_font(font_key, template.clone());
self.resources.font_templates.insert(font_key, template);
}
pub fn delete_font_template(&mut self, font_key: FontKey) {
self.glyph_rasterizer.delete_font(font_key);
self.resources.font_templates.remove(&font_key);
self.cached_glyphs
.clear_fonts(&mut self.texture_cache, |font| font.font_key == font_key);
if let Some(ref mut r) = self.blob_image_handler {
r.delete_font(font_key);
}
}
pub fn add_font_instance(
&mut self,
instance_key: FontInstanceKey,
font_key: FontKey,
size: Au,
options: Option<FontInstanceOptions>,
platform_options: Option<FontInstancePlatformOptions>,
variations: Vec<FontVariation>,
) {
let FontInstanceOptions {
render_mode,
flags,
bg_color,
synthetic_italics,
..
} = options.unwrap_or_default();
let instance = Arc::new(BaseFontInstance {
instance_key,
font_key,
size,
bg_color,
render_mode,
flags,
synthetic_italics,
platform_options,
variations,
});
self.resources.font_instances
.write()
.unwrap()
.insert(instance_key, instance);
}
pub fn delete_font_instance(&mut self, instance_key: FontInstanceKey) {
self.resources.font_instances
.write()
.unwrap()
.remove(&instance_key);
if let Some(ref mut r) = self.blob_image_handler {
r.delete_font_instance(instance_key);
}
}
pub fn get_font_instances(&self) -> FontInstanceMap {
self.resources.font_instances.clone()
}
pub fn get_font_instance(&self, instance_key: FontInstanceKey) -> Option<Arc<BaseFontInstance>> {
let instance_map = self.resources.font_instances.read().unwrap();
instance_map.get(&instance_key).map(|instance| { Arc::clone(instance) })
}
pub fn add_image_template(
&mut self,
image_key: ImageKey,
descriptor: ImageDescriptor,
data: CachedImageData,
mut tiling: Option<TileSize>,
) {
if tiling.is_none() && Self::should_tile(self.max_texture_size(), &descriptor, &data) {
// We aren't going to be able to upload a texture this big, so tile it, even
// if tiling was not requested.
tiling = Some(DEFAULT_TILE_SIZE);
}
let resource = ImageResource {
descriptor,
data,
tiling,
};
self.resources.image_templates.insert(image_key, resource);
}
pub fn update_image_template(
&mut self,
image_key: ImageKey,
descriptor: ImageDescriptor,
data: CachedImageData,
dirty_rect: &ImageDirtyRect,
) {
let max_texture_size = self.max_texture_size();
let image = match self.resources.image_templates.get_mut(image_key) {
Some(res) => res,
None => panic!("Attempt to update non-existent image"),
};
let mut tiling = image.tiling;
if tiling.is_none() && Self::should_tile(max_texture_size, &descriptor, &data) {
tiling = Some(DEFAULT_TILE_SIZE);
}
// Each cache entry stores its own copy of the image's dirty rect. This allows them to be
// updated independently.
match self.cached_images.try_get_mut(&image_key) {
Some(&mut ImageResult::UntiledAuto(ref mut entry)) => {
entry.dirty_rect = entry.dirty_rect.union(dirty_rect);
}
Some(&mut ImageResult::Multi(ref mut entries)) => {
for (key, entry) in entries.iter_mut() {
// We want the dirty rect relative to the tile and not the whole image.
let local_dirty_rect = match (tiling, key.tile) {
(Some(tile_size), Some(tile)) => {
dirty_rect.map(|mut rect|{
let tile_offset = DeviceIntPoint::new(
tile.x as i32,
tile.y as i32,
) * tile_size as i32;
rect.origin -= tile_offset.to_vector();
let tile_rect = compute_tile_size(
&descriptor.size.into(),
tile_size,
tile,
).into();
rect.intersection(&tile_rect).unwrap_or(DeviceIntRect::zero())
})
}
(None, Some(..)) => DirtyRect::All,
_ => *dirty_rect,
};
entry.dirty_rect = entry.dirty_rect.union(&local_dirty_rect);
}
}
_ => {}
}
*image = ImageResource {
descriptor,
data,
tiling,
};
}
// Happens before scene building.
pub fn add_blob_image(
&mut self,
key: BlobImageKey,
descriptor: &ImageDescriptor,
mut tiling: Option<TileSize>,
data: Arc<BlobImageData>,
) {
let max_texture_size = self.max_texture_size();
tiling = get_blob_tiling(tiling, descriptor, max_texture_size);
self.blob_image_handler.as_mut().unwrap().add(key, data, tiling);
self.blob_image_templates.insert(
key,
BlobImageTemplate {
descriptor: *descriptor,
tiling,
dirty_rect: DirtyRect::All,
viewport_tiles: None,
},
);
}
// Happens before scene building.
pub fn update_blob_image(
&mut self,
key: BlobImageKey,
descriptor: &ImageDescriptor,
dirty_rect: &BlobDirtyRect,
data: Arc<BlobImageData>,
) {
self.blob_image_handler.as_mut().unwrap().update(key, data, dirty_rect);
let max_texture_size = self.max_texture_size();
let image = self.blob_image_templates
.get_mut(&key)
.expect("Attempt to update non-existent blob image");
let tiling = get_blob_tiling(image.tiling, descriptor, max_texture_size);
*image = BlobImageTemplate {
descriptor: *descriptor,
tiling,
dirty_rect: dirty_rect.union(&image.dirty_rect),
viewport_tiles: image.viewport_tiles,
};
}
pub fn delete_image_template(&mut self, image_key: ImageKey) {
// Remove the template.
let value = self.resources.image_templates.remove(image_key);
// Release the corresponding texture cache entry, if any.
if let Some(mut cached) = self.cached_images.remove(&image_key) {
cached.drop_from_cache(&mut self.texture_cache);
}
match value {
Some(image) => if image.data.is_blob() {
let blob_key = BlobImageKey(image_key);
self.blob_image_handler.as_mut().unwrap().delete(blob_key);
self.deleted_blob_keys.back_mut().unwrap().push(blob_key);
self.blob_image_templates.remove(&blob_key);
self.rasterized_blob_images.remove(&blob_key);
},
None => {
warn!("Delete the non-exist key");
debug!("key={:?}", image_key);
}
}
}