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
/* 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 std::mem;
use smallvec::SmallVec;
use api::{ImageFormat, ImageBufferKind, DebugFlags};
use api::units::*;
use crate::device::TextureFilter;
use crate::internal_types::{
    CacheTextureId, TextureUpdateList, Swizzle, TextureCacheAllocInfo, TextureCacheCategory,
    TextureSource, FrameStamp, FrameId,
};
use crate::profiler::{self, TransactionProfile};
use crate::gpu_types::{ImageSource, UvRectKind};
use crate::gpu_cache::{GpuCache, GpuCacheHandle};
use crate::freelist::{FreeList, FreeListHandle, WeakFreeListHandle};


#[derive(Debug, PartialEq)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum PictureCacheEntryMarker {}

malloc_size_of::malloc_size_of_is_0!(PictureCacheEntryMarker);

pub type PictureCacheTextureHandle = WeakFreeListHandle<PictureCacheEntryMarker>;

use std::cmp;

// Stores information related to a single entry in the texture
// cache. This is stored for each item whether it's in the shared
// cache or a standalone texture.
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct PictureCacheEntry {
    /// Size of the requested tile.
    pub size: DeviceIntSize,
    /// The last frame this item was requested for rendering.
    // TODO(gw): This stamp is only used for picture cache tiles, and some checks
    //           in the glyph cache eviction code. We could probably remove it
    //           entirely in future (or move to EntryDetails::Picture).
    pub last_access: FrameStamp,
    /// Handle to the resource rect in the GPU cache.
    pub uv_rect_handle: GpuCacheHandle,
    /// Image format of the data that the entry expects.
    pub filter: TextureFilter,
    /// The actual device texture ID this is part of.
    pub texture_id: CacheTextureId,
}

impl PictureCacheEntry {
    fn update_gpu_cache(&mut self, gpu_cache: &mut GpuCache) {
        if let Some(mut request) = gpu_cache.request(&mut self.uv_rect_handle) {
            let origin = DeviceIntPoint::zero();
            let image_source = ImageSource {
                p0: origin.to_f32(),
                p1: (origin + self.size).to_f32(),
                uv_rect_kind: UvRectKind::Rect,
                user_data: [0.0; 4],
            };
            image_source.write_gpu_blocks(&mut request);
        }
    }
}

/// The textures used to hold picture cache tiles.
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
struct PictureTexture {
    texture_id: CacheTextureId,
    size: DeviceIntSize,
    is_allocated: bool,
    last_frame_used: FrameId,
}

/// The textures used to hold picture cache tiles.
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct PictureTextures {
    /// Current list of textures in the pool
    textures: Vec<PictureTexture>,
    /// Default tile size for content tiles
    default_tile_size: DeviceIntSize,
    /// Number of currently allocated textures in the pool
    allocated_texture_count: usize,
    /// Texture filter to use for picture cache textures
    filter: TextureFilter,

    debug_flags: DebugFlags,

    /// Cache of picture cache entries.
    cache_entries: FreeList<PictureCacheEntry, PictureCacheEntryMarker>,
    /// Strong handles for the picture_cache_entries FreeList.
    cache_handles: Vec<FreeListHandle<PictureCacheEntryMarker>>,

    now: FrameStamp,
}

impl PictureTextures {
    pub fn new(
        default_tile_size: DeviceIntSize,
        filter: TextureFilter,
    ) -> Self {
        PictureTextures {
            textures: Vec::new(),
            default_tile_size,
            allocated_texture_count: 0,
            filter,
            debug_flags: DebugFlags::empty(),
            cache_entries: FreeList::new(),
            cache_handles: Vec::new(),
            now: FrameStamp::INVALID,
        }
    }

    pub fn begin_frame(&mut self, stamp: FrameStamp, pending_updates: &mut TextureUpdateList) {
        self.now = stamp;

        // Expire picture cache tiles that haven't been referenced in the last frame.
        // The picture cache code manually keeps tiles alive by calling `request` on
        // them if it wants to retain a tile that is currently not visible.
        self.expire_old_tiles(pending_updates);
    }

    pub fn default_tile_size(&self) -> DeviceIntSize {
        self.default_tile_size
    }

    pub fn update(
        &mut self,
        tile_size: DeviceIntSize,
        handle: &mut Option<PictureCacheTextureHandle>,
        gpu_cache: &mut GpuCache,
        next_texture_id: &mut CacheTextureId,
        pending_updates: &mut TextureUpdateList,
    ) {
        debug_assert!(self.now.is_valid());
        debug_assert!(tile_size.width > 0 && tile_size.height > 0);

        let need_alloc = match handle {
            None => true,
            Some(handle) => {
                // Check if the entry has been evicted.
                !self.entry_exists(&handle)
            },
        };

        if need_alloc {
            let new_handle = self.get_or_allocate_tile(
                tile_size,
                next_texture_id,
                pending_updates,
            );

            *handle = Some(new_handle);
        }

        if let Some(handle) = handle {
            // Upload the resource rect and texture array layer.
            self.cache_entries
                .get_opt_mut(handle)
                .expect("BUG: handle must be valid now")
                .update_gpu_cache(gpu_cache);
        } else {
            panic!("The handle should be valid picture cache handle now")
        }
    }

    pub fn get_or_allocate_tile(
        &mut self,
        tile_size: DeviceIntSize,
        next_texture_id: &mut CacheTextureId,
        pending_updates: &mut TextureUpdateList,
    ) -> PictureCacheTextureHandle {
        let mut texture_id = None;
        self.allocated_texture_count += 1;

        for texture in &mut self.textures {
            if texture.size == tile_size && !texture.is_allocated {
                // Found a target that's not currently in use which matches. Update
                // the last_frame_used for GC purposes.
                texture.is_allocated = true;
                texture.last_frame_used = FrameId::INVALID;
                texture_id = Some(texture.texture_id);
                break;
            }
        }

        // Need to create a new render target and add it to the pool

        let texture_id = texture_id.unwrap_or_else(|| {
            let texture_id = *next_texture_id;
            next_texture_id.0 += 1;

            // Push a command to allocate device storage of the right size / format.
            let info = TextureCacheAllocInfo {
                target: ImageBufferKind::Texture2D,
                width: tile_size.width,
                height: tile_size.height,
                format: ImageFormat::RGBA8,
                filter: self.filter,
                is_shared_cache: false,
                has_depth: true,
                category: TextureCacheCategory::PictureTile,
            };

            pending_updates.push_alloc(texture_id, info);

            self.textures.push(PictureTexture {
                texture_id,
                is_allocated: true,
                size: tile_size,
                last_frame_used: FrameId::INVALID,
            });

            texture_id
        });

        let cache_entry = PictureCacheEntry {
            size: tile_size,
            last_access: self.now,
            uv_rect_handle: GpuCacheHandle::new(),
            filter: self.filter,
            texture_id,
        };

        // Add the cache entry to the picture_textures.cache_entries FreeList.
        let strong_handle = self.cache_entries.insert(cache_entry);
        let new_handle = strong_handle.weak();

        self.cache_handles.push(strong_handle);

        new_handle        
    }

    pub fn free_tile(
        &mut self,
        id: CacheTextureId,
        current_frame_id: FrameId,
        pending_updates: &mut TextureUpdateList,
    ) {
        self.allocated_texture_count -= 1;

        let texture = self.textures
            .iter_mut()
            .find(|t| t.texture_id == id)
            .expect("bug: invalid texture id");

        assert!(texture.is_allocated);
        texture.is_allocated = false;

        assert_eq!(texture.last_frame_used, FrameId::INVALID);
        texture.last_frame_used = current_frame_id;

        if self.debug_flags.contains(
            DebugFlags::TEXTURE_CACHE_DBG |
            DebugFlags::TEXTURE_CACHE_DBG_CLEAR_EVICTED)
        {
            pending_updates.push_debug_clear(
                id,
                DeviceIntPoint::zero(),
                texture.size.width,
                texture.size.height,
            );
        }
    }

    pub fn request(&mut self, handle: &PictureCacheTextureHandle, gpu_cache: &mut GpuCache) -> bool {
        let entry = self.cache_entries.get_opt_mut(handle);
        let now = self.now;
        entry.map_or(true, |entry| {
            // If an image is requested that is already in the cache,
            // refresh the GPU cache data associated with this item.
            entry.last_access = now;
            entry.update_gpu_cache(gpu_cache);
            false
        })
    }

    pub fn get_texture_source(&self, handle: &PictureCacheTextureHandle) -> TextureSource {
        let entry = self.cache_entries.get_opt(handle)
            .expect("BUG: was dropped from cache or not updated!");

        debug_assert_eq!(entry.last_access, self.now);

        TextureSource::TextureCache(entry.texture_id, Swizzle::default())
    }

    /// Expire picture cache tiles that haven't been referenced in the last frame.
    /// The picture cache code manually keeps tiles alive by calling `request` on
    /// them if it wants to retain a tile that is currently not visible.
    pub fn expire_old_tiles(&mut self, pending_updates: &mut TextureUpdateList) {
        for i in (0 .. self.cache_handles.len()).rev() {
            let evict = {
                let entry = self.cache_entries.get(
                    &self.cache_handles[i]
                );

                // This function is called at the beginning of the frame,
                // so we don't yet know which picture cache tiles will be
                // requested this frame. Therefore only evict picture cache
                // tiles which weren't requested in the *previous* frame.
                entry.last_access.frame_id() < self.now.frame_id() - 1
            };

            if evict {
                let handle = self.cache_handles.swap_remove(i);
                let entry = self.cache_entries.free(handle);
                self.free_tile(entry.texture_id, self.now.frame_id(), pending_updates);
            }
        }
    }

    pub fn clear(&mut self, pending_updates: &mut TextureUpdateList) {
        for handle in mem::take(&mut self.cache_handles) {
            let entry = self.cache_entries.free(handle);
            self.free_tile(entry.texture_id, self.now.frame_id(), pending_updates);
        }

        for texture in self.textures.drain(..) {
            pending_updates.push_free(texture.texture_id);
        }
    }

    pub fn update_profile(&self, profile: &mut TransactionProfile) {
        profile.set(profiler::PICTURE_TILES, self.textures.len());
    }

    /// Simple garbage collect of picture cache tiles
    pub fn gc(
        &mut self,
        pending_updates: &mut TextureUpdateList,
    ) {
        // Allow the picture cache pool to keep 25% of the current allocated tile count
        // as free textures to be reused. This ensures the allowed tile count is appropriate
        // based on current window size.
        let free_texture_count = self.textures.len() - self.allocated_texture_count;
        let allowed_retained_count = (self.allocated_texture_count as f32 * 0.25).ceil() as usize;
        let do_gc = free_texture_count > allowed_retained_count;

        if do_gc {
            // Sort the current pool by age, so that we remove oldest textures first
            self.textures.sort_unstable_by_key(|t| cmp::Reverse(t.last_frame_used));

            // We can't just use retain() because `PictureTexture` requires manual cleanup.
            let mut allocated_targets = SmallVec::<[PictureTexture; 32]>::new();
            let mut retained_targets = SmallVec::<[PictureTexture; 32]>::new();

            for target in self.textures.drain(..) {
                if target.is_allocated {
                    // Allocated targets can't be collected
                    allocated_targets.push(target);
                } else if retained_targets.len() < allowed_retained_count {
                    // Retain the most recently used targets up to the allowed count
                    retained_targets.push(target);
                } else {
                    // The rest of the targets get freed
                    assert_ne!(target.last_frame_used, FrameId::INVALID);
                    pending_updates.push_free(target.texture_id);
                }
            }

            self.textures.extend(retained_targets);
            self.textures.extend(allocated_targets);
        }
    }

    pub fn entry_exists(&self, handle: &PictureCacheTextureHandle) -> bool {
        self.cache_entries.get_opt(handle).is_some()
    }

    pub fn set_debug_flags(&mut self, flags: DebugFlags) {
        self.debug_flags = flags;
    }

    #[cfg(feature = "replay")]
    pub fn filter(&self) -> TextureFilter {
        self.filter
    }
}