1use alloc::{vec, vec::Vec};
14use core::{
15 hash::{BuildHasher, Hash, Hasher},
16 ops::Range,
17};
18
19use blit::{PhysicalRect, Scale2};
20
21use super::{DamageTracker, DisplayList};
22
23pub struct TileDamage {
24 shift: u32,
25 screen: PhysicalRect,
26 columns: usize,
27 previous: Vec<u64>,
28 ages: Vec<u8>,
29 hashes: Vec<u64>,
30 sums: Vec<u32>,
31 clips: Vec<Clip>,
32 hash_builder: hashbrown::DefaultHashBuilder,
33 invalidated: bool,
34}
35
36struct Clip {
37 hash: u64,
38 bounds: PhysicalRect,
39 inner: PhysicalRect,
40}
41
42impl TileDamage {
43 pub fn new(tile_size: u16) -> Self {
44 assert!(
45 tile_size.is_power_of_two(),
46 "damage tile size must be a nonzero power of two"
47 );
48 Self {
49 shift: tile_size.trailing_zeros(),
50 screen: PhysicalRect::default(),
51 columns: 0,
52 previous: Vec::new(),
53 ages: Vec::new(),
54 hashes: Vec::new(),
55 sums: vec![0],
56 clips: Vec::new(),
57 hash_builder: Default::default(),
58 invalidated: true,
59 }
60 }
61}
62
63impl DamageTracker for TileDamage {
64 fn update(&mut self, input: &DisplayList, screen: PhysicalRect, scale: f32, buffer_age: u8) {
65 let tile_size = 1usize << self.shift;
66 if self.screen != screen {
67 self.screen = screen;
68 self.columns = (screen.width as usize).div_ceil(tile_size);
69 let rows = (screen.height as usize).div_ceil(tile_size);
70 let count = self.columns.checked_mul(rows).expect("damage grid is too large");
71 u32::try_from(count).expect("too many damage tiles");
72 self.previous.resize(count, 0);
73 self.ages.resize(count, 0);
74 self.hashes.resize(count, 0);
75 let sums = (self.columns + 1)
76 .checked_mul(rows + 1)
77 .expect("damage grid is too large");
78 self.sums.resize(sums, 0);
79 self.sums.fill(0);
80 self.invalidated = true;
81 }
82 self.hashes.fill(0);
83 self.clips.clear();
84 self.clips.push(Clip {
85 hash: 0,
86 bounds: screen,
87 inner: screen,
88 });
89 for clip in input.clips() {
90 let parent = &self.clips[clip.parent as usize];
91 let area = clip.area.to_physical(Scale2::uniform(scale));
92 let radius = [
93 clip.radius.top_left,
94 clip.radius.top_right,
95 clip.radius.bottom_right,
96 clip.radius.bottom_left,
97 ]
98 .into_iter()
99 .fold(0.0f32, f32::max);
100 let inset = libm::ceilf(radius * scale) as i32;
101 let inner = PhysicalRect::new(
102 area.x.saturating_add(inset),
103 area.y.saturating_add(inset),
104 area.width.saturating_sub(inset.saturating_mul(2)).max(0),
105 area.height.saturating_sub(inset.saturating_mul(2)).max(0),
106 );
107 let mut hash = self.hash_builder.build_hasher();
108 hash.write_u64(parent.hash);
109 [
110 clip.area.x,
111 clip.area.y,
112 clip.area.width,
113 clip.area.height,
114 clip.radius.top_left,
115 clip.radius.top_right,
116 clip.radius.bottom_right,
117 clip.radius.bottom_left,
118 ]
119 .map(f32::to_bits)
120 .hash(&mut hash);
121 self.clips.push(Clip {
122 hash: hash.finish(),
123 bounds: area.intersection(parent.bounds).unwrap_or_default(),
124 inner: inner.intersection(parent.inner).unwrap_or_default(),
125 });
126 }
127 for (index, record) in input.commands().iter().enumerate() {
128 let clip = &self.clips[record.clip as usize];
129 let Some(bounds) = record.bounds.intersection(clip.bounds) else {
130 continue;
131 };
132 let mut hash = self.hash_builder.build_hasher();
133 [bounds.x, bounds.y, bounds.width, bounds.height].hash(&mut hash);
134 if bounds.intersection(clip.inner) != Some(bounds) {
135 hash.write_u64(clip.hash);
136 }
137 input.hash(index, &mut hash);
138 let hash = hash.finish();
139 let left = bounds.x as usize >> self.shift;
140 let right = ((bounds.x + bounds.width - 1) as usize >> self.shift) + 1;
141 let top = bounds.y as usize >> self.shift;
142 let bottom = ((bounds.y + bounds.height - 1) as usize >> self.shift) + 1;
143 for row in top..bottom {
144 for cell in &mut self.hashes[row * self.columns + left..row * self.columns + right] {
145 *cell = cell.rotate_left(5).wrapping_add(hash).wrapping_mul(0xf1357aea2e62a9c5);
146 }
147 }
148 }
149 let stride = self.columns + 1;
150 for (row, ((previous, hashes), ages)) in self
151 .previous
152 .chunks_mut(self.columns.max(1))
153 .zip(self.hashes.chunks(self.columns.max(1)))
154 .zip(self.ages.chunks_mut(self.columns.max(1)))
155 .enumerate()
156 {
157 let mut count = 0;
158 for (column, ((previous, hash), age)) in previous.iter_mut().zip(hashes).zip(ages).enumerate() {
159 if self.invalidated || *previous != *hash {
160 *previous = *hash;
161 *age = 0;
162 } else {
163 *age = age.saturating_add(1);
164 }
165 count += u32::from(buffer_age == 0 || *age < buffer_age);
166 self.sums[(row + 1) * stride + column + 1] = self.sums[row * stride + column + 1] + count;
167 }
168 }
169 self.invalidated = false;
170 }
171
172 fn invalidate(&mut self) {
173 self.invalidated = true;
174 }
175
176 fn is_empty(&self) -> bool {
177 self.sums.last() == Some(&0)
178 }
179
180 fn intersects(&self, bounds: PhysicalRect, clip: u32) -> bool {
182 let Some(bounds) = bounds.intersection(self.clips[clip as usize].bounds) else {
183 return false;
184 };
185 let left = bounds.x as usize >> self.shift;
186 let right = ((bounds.x + bounds.width - 1) as usize >> self.shift) + 1;
187 let top = bounds.y as usize >> self.shift;
188 let bottom = ((bounds.y + bounds.height - 1) as usize >> self.shift) + 1;
189 let stride = self.columns + 1;
190 self.sums[bottom * stride + right] - self.sums[top * stride + right]
191 != self.sums[bottom * stride + left] - self.sums[top * stride + left]
192 }
193
194 fn line_ranges(&self, line: i32, bounds: PhysicalRect, ranges: &mut Vec<Range<usize>>) -> i32 {
196 ranges.clear();
197 let mut next = bounds.y.saturating_add(bounds.height);
198 let Some(bounds) = bounds.intersection(self.screen) else {
199 return next;
200 };
201 if line < bounds.y || line >= bounds.y + bounds.height {
202 return next;
203 }
204 let row = line as usize >> self.shift;
205 let size = 1usize << self.shift;
206 let left = bounds.x as usize >> self.shift;
207 let right = ((bounds.x + bounds.width - 1) as usize >> self.shift) + 1;
208 let stride = self.columns + 1;
209 let dirty = |row: usize, column: usize| {
210 let above = row * stride + column;
211 let below = above + stride;
212 self.sums[below + 1] - self.sums[above + 1] != self.sums[below] - self.sums[above]
213 };
214 let limit = next.min(self.screen.height) as usize;
216 let mut end = row + 1;
217 while end * size < limit && (left..right).all(|column| dirty(end, column) == dirty(row, column)) {
218 end += 1;
219 }
220 next = next.min((end * size).min(limit) as i32);
221 let mut start = None;
222 for column in left..right {
223 if dirty(row, column) {
224 start.get_or_insert((column * size).max(bounds.x as usize));
225 } else if let Some(start) = start.take() {
226 ranges.push(start..column * size);
227 }
228 }
229 if let Some(start) = start {
230 ranges.push(start..(bounds.x + bounds.width) as usize);
231 }
232 next
233 }
234}