aboutsummaryrefslogtreecommitdiff
path: root/src/bitmap.rs
blob: 41af74516832c6e8a213b92404fcd2b363f6ee96 (plain)
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
use std::{
    convert::{From, Into, TryFrom},
    ops::{Add, Sub},
};

#[derive(Debug)]
pub struct Pixmap<T> {
    pub width: u32,
    pub height: u32,
    pub data: Vec<T>,
}

#[derive(Copy, Clone, Debug)]
pub struct MapPoint {
    pub x: u32,
    pub y: u32,
}

impl From<(u32, u32)> for MapPoint {
    fn from((x, y): (u32, u32)) -> MapPoint {
        MapPoint { x, y }
    }
}

impl TryFrom<(i32, i32)> for MapPoint {
    type Error = ();
    fn try_from((x, y): (i32, i32)) -> Result<Self, Self::Error> {
        if x < 0 || y < 0 {
            return Err(());
        } else {
            Ok(MapPoint {
                x: x as u32,
                y: y as u32,
            })
        }
    }
}

impl TryFrom<(i64, i64)> for MapPoint {
    type Error = ();
    fn try_from((x, y): (i64, i64)) -> Result<Self, Self::Error> {
        if x < 0 || y < 0 {
            return Err(());
        } else {
            Ok(MapPoint {
                x: x as u32,
                y: y as u32,
            })
        }
    }
}

impl Add for MapPoint {
    type Output = Self;
    fn add(self, rhs: Self) -> Self::Output {
        MapPoint {
            x: self.x.saturating_add(rhs.x),
            y: self.y.saturating_add(rhs.y),
        }
    }
}

impl Sub for MapPoint {
    type Output = Self;
    fn sub(self, rhs: Self) -> Self::Output {
        MapPoint {
            x: self.x.saturating_sub(rhs.x),
            y: self.y.saturating_sub(rhs.y),
        }
    }
}

#[derive(Debug, Copy, Clone)]
pub enum Axis {
    X,
    Y,
}

impl MapPoint {
    #[inline]
    pub fn scale(self, c: u32) -> MapPoint {
        MapPoint {
            x: self.x * c,
            y: self.y * c,
        }
    }

    #[inline]
    pub fn mirror_about(self, line: u32, axis: Axis) -> MapPoint {
        let MapPoint { x, y } = self;
        match axis {
            Axis::X => MapPoint { x, y: 2 * line - y },
            Axis::Y => MapPoint { x: 2 * line - x, y },
        }
    }

    #[inline]
    pub fn reflect(self, around: MapPoint) -> MapPoint {
        around.scale(2) - self
    }
}

impl<T> Pixmap<T>
where
    T: Copy + Clone + Default + PartialEq,
{
    pub fn new(width: u32, height: u32) -> Self {
        let data = vec![Default::default(); (width * height) as usize];
        Pixmap {
            width,
            height,
            data,
        }
    }

    pub fn new_with(width: u32, height: u32, data: Vec<T>) -> Self {
        Pixmap {
            width,
            height,
            data,
        }
    }

    pub fn contains<P: Into<MapPoint>>(&self, pt: P) -> bool {
        let MapPoint { x, y } = pt.into();
        x < self.width && y < self.height
    }

    pub fn idx<P: Into<MapPoint>>(&self, pt: P) -> usize {
        let MapPoint { x, y } = pt.into();
        (y * self.width + x) as usize
    }

    pub fn get<P: Into<MapPoint>>(&self, pt: P) -> T {
        let idx = self.idx(pt);
        self.data[idx]
    }

    pub fn set<P: Into<MapPoint>>(&mut self, pt: P, new_val: T) -> T {
        let pt = pt.into();
        let old_val = self.get(pt);
        let idx = self.idx(pt);
        self.data[idx] = new_val;
        old_val
    }

    pub fn get_circle<P: Into<MapPoint>>(
        &self,
        center: P,
        radius: u32,
        filled: bool,
    ) -> Vec<MapPoint> {
        let mut circle: Vec<(i64, i64)> = vec![];
        let MapPoint { x, y } = center.into();
        let x = x as i64;
        let y = y as i64;
        let (mut dx, mut dy, mut err) = (radius as i64, 0i64, 1 - radius as i64);
        while dx >= dy {
            circle.push((x + dx, y + dy));
            circle.push((x - dx, y + dy));
            circle.push((x + dx, y - dy));
            circle.push((x - dx, y - dy));
            circle.push((x + dy, y + dx));
            circle.push((x - dy, y + dx));
            circle.push((x + dy, y - dx));
            circle.push((x - dy, y - dx));
            if filled {
                circle.extend((x - dx.abs() + 1..x + dx.abs()).map(|x| (x, y + dy)));
                circle.extend((x - dx.abs() + 1..x + dx.abs()).map(|x| (x, y - dy)));
                circle.extend((x - dy.abs() + 1..x + dy.abs()).map(|x| (x, y + dx)));
                circle.extend((x - dy.abs() + 1..x + dy.abs()).map(|x| (x, y - dx)));
            }
            dy = dy + 1;
            if err < 0 {
                err = err + 2 * dy + 1;
            } else {
                dx -= 1;
                err += 2 * (dy - dx) + 1;
            }
        }
        circle
            .into_iter()
            .flat_map(|pt| MapPoint::try_from(pt))
            .filter(|&pt| self.contains(pt))
            .collect()
    }

    pub fn get_line<P: Into<MapPoint>>(&self, start: P, end: P) -> Vec<MapPoint> {
        let MapPoint { x: x1, y: y1 } = start.into();
        let MapPoint { x: x2, y: y2 } = end.into();
        let mut coordinates = vec![];
        let dx = abs_difference(x1, x2) as i64;
        let dy = abs_difference(y1, y2) as i64;
        let sx = {
            if x1 < x2 {
                1
            } else {
                -1
            }
        };
        let sy = {
            if y1 < y2 {
                1
            } else {
                -1
            }
        };
        let mut err: i64 = dx - dy;
        let mut current_x = x1 as i64;
        let mut current_y = y1 as i64;
        loop {
            coordinates.push((current_x, current_y));
            if current_x == x2 as i64 && current_y == y2 as i64 {
                break;
            }
            let e2 = 2 * err;
            if e2 > -dy {
                err -= dy;
                current_x += sx;
            }
            if e2 < dx {
                err += dx;
                current_y += sy;
            }
        }
        coordinates
            .into_iter()
            .flat_map(|pt| MapPoint::try_from(pt))
            .filter(|&pt| self.contains(pt))
            .collect()
    }

    pub fn flood_fill(
        &mut self,
        start: MapPoint,
        target: T,
        replacement: T,
        pts: &mut Vec<MapPoint>,
    ) {
        if !self.contains(start) || self.get(start) != target || self.get(start) == replacement {
            return;
        } else {
            pts.push(start);
            self.set(start, replacement);
            for (x, y) in [(1, 0), (0, 1), (-1, 0), (0, -1)].iter() {
                let dir = MapPoint::try_from((start.x as i64 - x, start.y as i64 + y));
                if let Ok(pt) = dir {
                    self.flood_fill(pt, target, replacement, pts);
                }
            }
        }
    }
}

impl Pixmap<bool> {
    pub fn invert(&mut self) {
        for px in self.data.iter_mut() {
            *px = !(*px);
        }
    }
}

fn abs_difference<T: Sub<Output = T> + Ord>(x: T, y: T) -> T {
    if x < y {
        y - x
    } else {
        x - y
    }
}

pub fn mirror_figure(figure: &[MapPoint], line: u32, axis: Axis) -> Vec<MapPoint> {
    figure
        .iter()
        .map(|pt| pt.mirror_about(line, axis))
        .collect()
}

pub fn reflect_figure(figure: &[MapPoint], around: MapPoint) -> Vec<MapPoint> {
    figure.iter().map(|pt| pt.reflect(around)).collect()
}