1use crate::Viewport;
3use crate::core::{Point, Rectangle, Size};
4
5pub fn diff<T>(
7 previous: &[T],
8 current: &[T],
9 bounds: impl Fn(&T) -> Vec<Rectangle>,
10 diff: impl Fn(&T, &T) -> Vec<Rectangle>,
11) -> Vec<Rectangle> {
12 let damage = previous.iter().zip(current).flat_map(|(a, b)| diff(a, b));
13
14 if previous.len() == current.len() {
15 damage.collect()
16 } else {
17 let (smaller, bigger) = if previous.len() < current.len() {
18 (previous, current)
19 } else {
20 (current, previous)
21 };
22
23 damage
25 .chain(bigger[smaller.len()..].iter().flat_map(bounds))
26 .collect()
27 }
28}
29
30pub fn list<T>(
32 previous: &[T],
33 current: &[T],
34 bounds: impl Fn(&T) -> Vec<Rectangle>,
35 are_equal: impl Fn(&T, &T) -> bool,
36) -> Vec<Rectangle> {
37 diff(previous, current, &bounds, |a, b| {
38 if are_equal(a, b) {
39 vec![]
40 } else {
41 bounds(a).into_iter().chain(bounds(b)).collect()
42 }
43 })
44}
45
46pub fn group(mut damage: Vec<Rectangle>, bounds: Rectangle) -> impl Iterator<Item = Rectangle> {
49 const AREA_THRESHOLD: f32 = 20_000.0;
50
51 damage.sort_by(|a, b| {
52 a.center()
53 .distance(Point::ORIGIN)
54 .total_cmp(&b.center().distance(Point::ORIGIN))
55 });
56
57 let mut scaled = damage
58 .into_iter()
59 .filter_map(move |region| region.intersection(&bounds))
60 .filter(|region| region.width >= 1.0 && region.height >= 1.0)
61 .peekable();
62
63 let mut group = scaled.next();
64
65 std::iter::from_fn(move || {
66 loop {
67 let Some(region) = scaled.next() else {
68 return group.take();
69 };
70
71 let current = group?;
72 let union = current.union(®ion);
73
74 if union.area() - current.area() - region.area() <= AREA_THRESHOLD {
75 group = Some(union);
76 } else {
77 group = Some(region);
78 return Some(current);
79 }
80 }
81 })
82}
83
84pub fn physical(
86 damage: impl IntoIterator<Item = Rectangle>,
87 viewport: &Viewport,
88) -> impl Iterator<Item = Rectangle<u32>> {
89 let scale = viewport.scale_factor();
90
91 let viewport = Rectangle::with_size(Size::new(
92 viewport.physical_width() as f32,
93 viewport.physical_height() as f32,
94 ));
95
96 damage
97 .into_iter()
98 .map(move |region| region * scale)
99 .filter_map(move |region| region.expand(2).intersection(&viewport))
100 .filter_map(Rectangle::snap)
101}