Skip to main content

devpage_design/tiles/
cache.rs

1//! The tile cache: tiles by key, capped by a cost, least recently used
2//! dropped first; damage marks the tiles it overlaps stale, and a stale tile
3//! is still returned, as stale, until it is replaced. Generic over what a
4//! tile holds — the server's pixels, the module's GPU textures.
5
6use std::collections::{BTreeMap, HashMap};
7
8use kurbo::Rect as KRect;
9
10use crate::scene::Theme;
11
12use super::*;
13
14/// A cached tile: what it holds, what it costs, whether damage made it
15/// stale, and when it was last used.
16struct Entry<T> {
17    /// What the tile holds.
18    value: T,
19    /// What it counts against the cache's cap.
20    cost: usize,
21    /// Whether damage overlapped it since it was painted.
22    stale: bool,
23    /// The cache's clock when it was last used: its key in `by_use`.
24    used: u64,
25}
26
27/// Painted tiles, keyed by theme, level, column and row, holding at most
28/// `cap` of cost — bytes of pixels, or a count — the least recently used
29/// dropped first. Damage marks the tiles it overlaps stale; a stale tile is
30/// still there, and says so, until it is painted again. What a tile holds is
31/// the cache's user's: pixels in the server, a texture on the GPU.
32pub struct Cache<T, K: Tiled = Key> {
33    /// The most the tiles may cost together.
34    cap: usize,
35    /// What the tiles held cost together.
36    cost: usize,
37    /// Counts each use, so the latest has the highest number.
38    clock: u64,
39    /// Every tile held, by key.
40    entries: HashMap<K, Entry<T>>,
41    /// Every tile's key by when it was last used, oldest first: what to drop
42    /// next.
43    by_use: BTreeMap<u64, K>,
44}
45
46impl<T, K: Tiled> Cache<T, K> {
47    /// An empty cache whose tiles may cost `cap` together.
48    pub fn new(cap: usize) -> Cache<T, K> {
49        Cache {
50            cap,
51            cost: 0,
52            clock: 0,
53            entries: HashMap::new(),
54            by_use: BTreeMap::new(),
55        }
56    }
57
58    /// The tile at `key`, and whether it is stale; it counts as used.
59    pub fn get(&mut self, key: &K) -> Option<(&T, bool)> {
60        self.clock += 1;
61        let e = self.entries.get_mut(key)?;
62        self.by_use.remove(&e.used);
63        e.used = self.clock;
64        self.by_use.insert(self.clock, *key);
65        Some((&e.value, e.stale))
66    }
67
68    /// The tile at `key` and whether it is stale, without counting a use.
69    pub fn peek(&self, key: &K) -> Option<(&T, bool)> {
70        self.entries.get(key).map(|e| (&e.value, e.stale))
71    }
72
73    /// Keeps `value` as the current tile at `key`, costing `cost`, and drops
74    /// the least recently used others until the cache is within its cap.
75    /// Returns what was dropped.
76    pub fn insert(&mut self, key: K, value: T, cost: usize) -> Vec<(K, T)> {
77        // The tile it replaces isn't dropped: it is the same tile, painted again.
78        self.remove(&key);
79        let mut dropped = Vec::new();
80        self.clock += 1;
81        self.entries.insert(
82            key,
83            Entry {
84                value,
85                cost,
86                stale: false,
87                used: self.clock,
88            },
89        );
90        self.by_use.insert(self.clock, key);
91        self.cost += cost;
92        while self.cost > self.cap {
93            let Some((_, oldest)) = self.by_use.iter().next().map(|(u, k)| (*u, *k)) else {
94                break;
95            };
96            if oldest == key {
97                break;
98            }
99            if let Some(v) = self.remove(&oldest) {
100                dropped.push((oldest, v));
101            }
102        }
103        dropped
104    }
105
106    /// Takes the tile at `key` out.
107    pub fn remove(&mut self, key: &K) -> Option<T> {
108        let e = self.entries.remove(key)?;
109        self.by_use.remove(&e.used);
110        self.cost -= e.cost;
111        Some(e.value)
112    }
113
114    /// Marks stale every tile of `theme` that overlaps one of `rects` — in
115    /// the design's coordinates, the drawing's top-left at `origin` — at
116    /// every level.
117    pub fn damage(&mut self, theme: Theme, origin: (f64, f64), rects: &[KRect]) {
118        self.damage_where(|k| k.key().theme == theme, origin, rects);
119    }
120
121    /// Marks stale every tile `which` picks that overlaps one of `rects`, as
122    /// [`Cache::damage`] does.
123    pub fn damage_where(
124        &mut self,
125        which: impl Fn(&K) -> bool,
126        origin: (f64, f64),
127        rects: &[KRect],
128    ) {
129        for (k, e) in &mut self.entries {
130            if !e.stale && which(k) && k.key().overlaps(origin, rects) {
131                e.stale = true;
132            }
133        }
134    }
135
136    /// Marks every tile of `theme` stale.
137    pub fn damage_all(&mut self, theme: Theme) {
138        self.damage_all_where(|k| k.key().theme == theme);
139    }
140
141    /// Marks every tile `which` picks stale.
142    pub fn damage_all_where(&mut self, which: impl Fn(&K) -> bool) {
143        for (k, e) in &mut self.entries {
144            if which(k) {
145                e.stale = true;
146            }
147        }
148    }
149
150    /// Drops every tile `which` picks.
151    pub fn forget(&mut self, which: impl Fn(&K) -> bool) {
152        let gone: Vec<K> = self.entries.keys().filter(|k| which(k)).copied().collect();
153        for k in gone {
154            self.remove(&k);
155        }
156    }
157
158    /// Every tile, with whether it is stale.
159    pub fn iter(&self) -> impl Iterator<Item = (&K, &T, bool)> {
160        self.entries.iter().map(|(k, e)| (k, &e.value, e.stale))
161    }
162
163    /// Drops every tile.
164    pub fn clear(&mut self) -> Vec<T> {
165        self.by_use.clear();
166        self.cost = 0;
167        self.entries.drain().map(|(_, e)| e.value).collect()
168    }
169
170    /// How many tiles it holds.
171    pub fn len(&self) -> usize {
172        self.entries.len()
173    }
174
175    /// Whether it holds no tiles.
176    pub fn is_empty(&self) -> bool {
177        self.entries.is_empty()
178    }
179
180    /// What the tiles held cost together.
181    pub fn cost(&self) -> usize {
182        self.cost
183    }
184}
185
186#[cfg(test)]
187mod tests;