Skip to main content

strata_render/
tiling.rs

1//! Viewport Tiling, 256x256 Surface Partitioning, and Front-to-Back Quad Occlusion Culling.
2
3use crate::compositor::{DisplayList, DrawCommand};
4use strata_layout::Rect;
5
6/// Standard viewport tile dimension in physical pixels (matching Chromium cc compositor standard).
7pub const DEFAULT_TILE_SIZE: u32 = 256;
8
9/// 2D Discrete Grid Coordinate for a viewport tile.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
11pub struct TileCoord {
12    pub col: u32,
13    pub row: u32,
14}
15
16impl TileCoord {
17    #[inline(always)]
18    pub const fn new(col: u32, row: u32) -> Self {
19        Self { col, row }
20    }
21}
22
23/// A discrete 256x256 pixel viewport surface partition.
24#[derive(Debug, Clone, PartialEq)]
25pub struct Tile {
26    pub coord: TileCoord,
27    pub bounds: Rect,
28    pub is_dirty: bool,
29    pub is_occluded: bool,
30}
31
32impl Tile {
33    pub fn new(col: u32, row: u32, bounds: Rect) -> Self {
34        Self {
35            coord: TileCoord::new(col, row),
36            bounds,
37            is_dirty: false,
38            is_occluded: false,
39        }
40    }
41
42    #[inline]
43    pub fn mark_dirty(&mut self) {
44        self.is_dirty = true;
45    }
46
47    #[inline]
48    pub fn mark_occluded(&mut self) {
49        self.is_occluded = true;
50    }
51
52    #[inline]
53    pub fn reset(&mut self) {
54        self.is_dirty = false;
55        self.is_occluded = false;
56    }
57}
58
59/// A regular 2D grid partitioning of a presentation surface into fixed-size tiles.
60#[derive(Debug, Clone, PartialEq)]
61pub struct TilingSet {
62    pub tile_size: u32,
63    pub cols: u32,
64    pub rows: u32,
65    pub surface_width: u32,
66    pub surface_height: u32,
67    pub tiles: Vec<Tile>,
68}
69
70impl TilingSet {
71    /// Constructs a tiling grid covering the specified surface dimensions.
72    pub fn new(surface_width: u32, surface_height: u32, tile_size: u32) -> Self {
73        let ts = tile_size.max(16);
74        let cols = if surface_width == 0 {
75            0
76        } else {
77            surface_width.div_ceil(ts)
78        };
79        let rows = if surface_height == 0 {
80            0
81        } else {
82            surface_height.div_ceil(ts)
83        };
84
85        let mut tiles = Vec::with_capacity((cols * rows) as usize);
86        for r in 0..rows {
87            let y = (r * ts) as f32;
88            let h = ((r + 1) * ts).min(surface_height) as f32 - y;
89            for c in 0..cols {
90                let x = (c * ts) as f32;
91                let w = ((c + 1) * ts).min(surface_width) as f32 - x;
92                tiles.push(Tile::new(c, r, Rect::new(x, y, w, h)));
93            }
94        }
95
96        Self {
97            tile_size: ts,
98            cols,
99            rows,
100            surface_width,
101            surface_height,
102            tiles,
103        }
104    }
105
106    /// Default 256x256 grid constructor.
107    pub fn with_default_size(surface_width: u32, surface_height: u32) -> Self {
108        Self::new(surface_width, surface_height, DEFAULT_TILE_SIZE)
109    }
110
111    #[inline]
112    pub fn total_tiles(&self) -> usize {
113        self.tiles.len()
114    }
115
116    #[inline]
117    pub fn tile_index(&self, col: u32, row: u32) -> Option<usize> {
118        if col < self.cols && row < self.rows {
119            Some((row * self.cols + col) as usize)
120        } else {
121            None
122        }
123    }
124
125    #[inline]
126    pub fn tile_at(&self, col: u32, row: u32) -> Option<&Tile> {
127        self.tile_index(col, row).map(|idx| &self.tiles[idx])
128    }
129
130    #[inline]
131    pub fn tile_at_mut(&mut self, col: u32, row: u32) -> Option<&mut Tile> {
132        self.tile_index(col, row).map(|idx| &mut self.tiles[idx])
133    }
134
135    /// Marks all tiles intersecting the damage rectangle as dirty.
136    pub fn mark_damage(&mut self, damage: Rect) {
137        if damage.width <= 0.0 || damage.height <= 0.0 || self.cols == 0 || self.rows == 0 {
138            return;
139        }
140
141        let ts = self.tile_size as f32;
142        let min_col = (damage.x.max(0.0) / ts).floor() as u32;
143        let max_col = ((damage.max_x() / ts).ceil() as u32).min(self.cols);
144        let min_row = (damage.y.max(0.0) / ts).floor() as u32;
145        let max_row = ((damage.max_y() / ts).ceil() as u32).min(self.rows);
146
147        for r in min_row..max_row {
148            for c in min_col..max_col {
149                if let Some(idx) = self.tile_index(c, r) {
150                    if self.tiles[idx].bounds.intersect(damage).is_some() {
151                        self.tiles[idx].is_dirty = true;
152                    }
153                }
154            }
155        }
156    }
157
158    /// Returns an iterator over all dirty tiles.
159    pub fn dirty_tiles(&self) -> impl Iterator<Item = &Tile> {
160        self.tiles.iter().filter(|t| t.is_dirty)
161    }
162
163    /// Returns an iterator over dirty tiles that are not occluded.
164    pub fn active_render_tiles(&self) -> impl Iterator<Item = &Tile> {
165        self.tiles.iter().filter(|t| t.is_dirty && !t.is_occluded)
166    }
167
168    pub fn dirty_count(&self) -> usize {
169        self.tiles.iter().filter(|t| t.is_dirty).count()
170    }
171
172    pub fn occluded_count(&self) -> usize {
173        self.tiles.iter().filter(|t| t.is_occluded).count()
174    }
175
176    pub fn reset_dirty(&mut self) {
177        for t in &mut self.tiles {
178            t.is_dirty = false;
179        }
180    }
181
182    pub fn reset_occlusion(&mut self) {
183        for t in &mut self.tiles {
184            t.is_occluded = false;
185        }
186    }
187
188    pub fn reset_all(&mut self) {
189        for t in &mut self.tiles {
190            t.reset();
191        }
192    }
193}
194
195/// Tracks fully opaque rectangular occluders to eliminate redundant rasterization of underlying elements.
196#[derive(Debug, Default, Clone, PartialEq)]
197pub struct OcclusionTracker {
198    pub opaque_occluders: Vec<Rect>,
199}
200
201impl OcclusionTracker {
202    pub fn new() -> Self {
203        Self::default()
204    }
205
206    /// Adds a fully opaque axis-aligned rectangle to the occlusion database.
207    pub fn add_occluder(&mut self, rect: Rect) {
208        if rect.width > 0.0 && rect.height > 0.0 {
209            // Check if already subsumed by an existing occluder
210            for o in &self.opaque_occluders {
211                if o.contains_rect(rect) {
212                    return;
213                }
214            }
215
216            // Remove any existing occluders fully subsumed by the new rect
217            self.opaque_occluders.retain(|o| !rect.contains_rect(*o));
218            self.opaque_occluders.push(rect);
219        }
220    }
221
222    /// Returns true if the target rectangle is completely covered by an opaque occluder.
223    pub fn is_occluded(&self, rect: Rect) -> bool {
224        if rect.width <= 0.0 || rect.height <= 0.0 {
225            return true;
226        }
227
228        // Direct single-occluder containment check (covers 95%+ of UI cases)
229        for o in &self.opaque_occluders {
230            if o.contains_rect(rect) {
231                return true;
232            }
233        }
234
235        false
236    }
237
238    /// Evaluates occlusion against a tiling set, marking fully covered tiles as occluded.
239    pub fn evaluate_tiling_set(&self, tiling_set: &mut TilingSet) {
240        for tile in &mut tiling_set.tiles {
241            if self.is_occluded(tile.bounds) {
242                tile.is_occluded = true;
243            }
244        }
245    }
246
247    /// Analyzes a slice of DisplayList commands in reverse (front-to-back),
248    /// identifying opaque occluders and marking occluded background commands.
249    ///
250    /// Returns the accumulated OcclusionTracker and a boolean mask indicating whether
251    /// each command is occluded (true = occluded, skip rendering).
252    pub fn analyze_front_to_back(commands: &[DrawCommand]) -> (Self, Vec<bool>) {
253        let mut tracker = Self::new();
254        let mut occluded_mask = vec![false; commands.len()];
255
256        // Scan in reverse order: frontmost commands first
257        for (i, cmd) in commands.iter().enumerate().rev() {
258            if cmd.is_state_command() {
259                continue;
260            }
261
262            if let Some(bounds) = cmd.bounds() {
263                if tracker.is_occluded(bounds) {
264                    occluded_mask[i] = true;
265                    continue;
266                }
267
268                // Check if this command can act as an opaque occluder
269                match cmd {
270                    DrawCommand::DrawRect { bounds, color } => {
271                        if color.a() >= 0.999 {
272                            tracker.add_occluder(*bounds);
273                        }
274                    }
275                    DrawCommand::DrawRoundedRect {
276                        bounds,
277                        color,
278                        border_radius,
279                        ..
280                    } => {
281                        // A rounded rect is opaque in its inner core box
282                        if color.a() >= 0.999
283                            && border_radius.top_left == 0.0
284                            && border_radius.top_right == 0.0
285                            && border_radius.bottom_right == 0.0
286                            && border_radius.bottom_left == 0.0
287                        {
288                            tracker.add_occluder(*bounds);
289                        }
290                    }
291                    _ => {}
292                }
293            }
294        }
295
296        (tracker, occluded_mask)
297    }
298
299    /// Filters a display list, dropping non-clipping commands that are completely occluded.
300    pub fn cull_display_list(list: &DisplayList) -> DisplayList {
301        let (_, mask) = Self::analyze_front_to_back(list.commands());
302        let mut culled = DisplayList::new();
303
304        for (cmd, is_occluded) in list.commands().iter().zip(mask.iter()) {
305            if !*is_occluded || cmd.is_state_command() {
306                culled.push(cmd.clone());
307            }
308        }
309
310        culled
311    }
312
313    pub fn clear(&mut self) {
314        self.opaque_occluders.clear();
315    }
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321    use strata_style::types::Color;
322
323    #[test]
324    fn test_tiling_set_dimensions() {
325        let set = TilingSet::new(1920, 1080, 256);
326        assert_eq!(set.cols, 8); // 1920 / 256 = 7.5 -> 8
327        assert_eq!(set.rows, 5); // 1080 / 256 = 4.21875 -> 5
328        assert_eq!(set.total_tiles(), 40);
329
330        let t0 = set.tile_at(0, 0).unwrap();
331        assert_eq!(t0.bounds, Rect::new(0.0, 0.0, 256.0, 256.0));
332
333        let t_last = set.tile_at(7, 4).unwrap();
334        assert_eq!(t_last.bounds.x, 7.0 * 256.0);
335        assert_eq!(t_last.bounds.y, 4.0 * 256.0);
336        assert_eq!(t_last.bounds.width, 1920.0 - 7.0 * 256.0); // 128.0
337        assert_eq!(t_last.bounds.height, 1080.0 - 4.0 * 256.0); // 56.0
338    }
339
340    #[test]
341    fn test_tiling_mark_damage() {
342        let mut set = TilingSet::new(1920, 1080, 256);
343        assert_eq!(set.dirty_count(), 0);
344
345        // Damage badge in top-left (10, 10, 120, 36)
346        set.mark_damage(Rect::new(10.0, 10.0, 120.0, 36.0));
347        assert_eq!(set.dirty_count(), 1);
348        assert!(set.tile_at(0, 0).unwrap().is_dirty);
349
350        // Reset
351        set.reset_dirty();
352        assert_eq!(set.dirty_count(), 0);
353
354        // Damage overlapping column border: (250, 100, 20, 50) -> spans col 0 and col 1
355        set.mark_damage(Rect::new(250.0, 100.0, 20.0, 50.0));
356        assert_eq!(set.dirty_count(), 2);
357        assert!(set.tile_at(0, 0).unwrap().is_dirty);
358        assert!(set.tile_at(1, 0).unwrap().is_dirty);
359    }
360
361    #[test]
362    fn test_occlusion_tracker_culling() {
363        let mut tracker = OcclusionTracker::new();
364        let background = Rect::new(0.0, 0.0, 500.0, 500.0);
365        let modal = Rect::new(50.0, 50.0, 400.0, 400.0);
366        let button = Rect::new(100.0, 100.0, 80.0, 32.0);
367
368        tracker.add_occluder(modal);
369
370        // Button is inside modal -> occluded from behind
371        assert!(tracker.is_occluded(button));
372
373        // Background is larger than modal -> not completely occluded
374        assert!(!tracker.is_occluded(background));
375
376        // Evaluate tiles
377        let mut set = TilingSet::new(500, 500, 100);
378        tracker.evaluate_tiling_set(&mut set);
379
380        // Tile at col 2, row 2 bounds is (200, 200, 100, 100), fully inside modal (50, 50, 400, 400)
381        let t22 = set.tile_at(2, 2).unwrap();
382        assert!(t22.is_occluded);
383
384        // Tile at col 0, row 0 bounds is (0, 0, 100, 100), partially outside modal -> not fully occluded
385        let t00 = set.tile_at(0, 0).unwrap();
386        assert!(!t00.is_occluded);
387    }
388
389    #[test]
390    fn test_cull_display_list_front_to_back() {
391        let mut list = DisplayList::new();
392
393        // 1. Bottom wallpaper (1920x1080)
394        list.push(DrawCommand::DrawRect {
395            bounds: Rect::new(0.0, 0.0, 1920.0, 1080.0),
396            color: Color::rgb(15, 23, 42),
397        });
398
399        // 2. Underlying button that will be occluded
400        list.push(DrawCommand::DrawRect {
401            bounds: Rect::new(500.0, 300.0, 100.0, 40.0),
402            color: Color::rgb(255, 0, 0),
403        });
404
405        // 3. Large opaque dialog window covering (400, 200, 800, 600)
406        list.push(DrawCommand::DrawRect {
407            bounds: Rect::new(400.0, 200.0, 800.0, 600.0),
408            color: Color::rgb(30, 41, 59),
409        });
410
411        // 4. Dialog close icon
412        list.push(DrawCommand::DrawRect {
413            bounds: Rect::new(1150.0, 220.0, 24.0, 24.0),
414            color: Color::rgb(255, 255, 255),
415        });
416
417        let culled = OcclusionTracker::cull_display_list(&list);
418
419        // The underlying button (command 2) was completely occluded by the dialog (command 3),
420        // so it must have been culled out!
421        assert_eq!(culled.len(), 3);
422        assert_eq!(culled.commands()[0], list.commands()[0]); // wallpaper
423        assert_eq!(culled.commands()[1], list.commands()[2]); // dialog
424        assert_eq!(culled.commands()[2], list.commands()[3]); // close icon
425    }
426}