Delete smaller wall regions and leave only one room
[kaka/rust-sdl-test.git] / src / core / level.rs
1 use common::Point2D;
2 use core::render::Renderer;
3 use rand::Rng;
4 use sprites::SpriteManager;
5
6 ////////// LEVEL ///////////////////////////////////////////////////////////////
7
8 #[derive(Default)]
9 pub struct Level {
10     pub gravity: Point2D<f64>,
11     pub ground: f64,            // just to have something
12     pub grid: Grid,
13     iterations: u8,
14 }
15
16 impl Level {
17     pub fn new(gravity: Point2D<f64>, ground: f64) -> Self {
18         Level { gravity, ground, grid: Grid::generate(10), iterations: 10 }
19     }
20
21     pub fn regenerate(&mut self) {
22         self.grid = Grid::generate(self.iterations);
23     }
24
25     pub fn increase_iteration(&mut self) {
26         self.iterations += 1;
27         self.regenerate();
28         println!("iterate {} time(s)", self.iterations);
29     }
30
31     pub fn decrease_iteration(&mut self) {
32         self.iterations -= 1;
33         self.regenerate();
34         println!("iterate {} time(s)", self.iterations);
35     }
36
37     pub fn filter_regions(&mut self) {
38         self.grid.filter_regions();
39     }
40
41     pub fn render(&mut self, renderer: &mut Renderer, _sprites: &SpriteManager) {
42         let w = renderer.viewport().0 as i32;
43
44         renderer.canvas().set_draw_color((64, 64, 64));
45         let size = self.grid.cell_size;
46         for x in 0..self.grid.width {
47             for y in 0..self.grid.height {
48                 if self.grid.cells[x][y] {
49                     renderer.canvas().fill_rect(sdl2::rect::Rect::new(x as i32 * size as i32, y as i32 * size as i32, size as u32, size as u32)).unwrap();
50                 }
51             }
52         }
53
54         for i in 1..11 {
55             let y = (i * i - 1) as i32 + self.ground as i32;
56             renderer.canvas().set_draw_color((255 - i * 20, 255 - i * 20, 0));
57             renderer.canvas().draw_line((0, y), (w, y)).unwrap();
58         }
59     }
60 }
61
62 ////////// GRID ////////////////////////////////////////////////////////////////
63
64 #[derive(Default)]
65 pub struct Grid {
66     pub width: usize,
67     pub height: usize,
68     pub cell_size: usize,
69     pub cells: Vec<Vec<bool>>,
70 }
71
72 impl Grid {
73     fn generate(iterations: u8) -> Grid {
74         let cell_size = 20;
75         let (width, height) = (2560 / cell_size, 1440 / cell_size);
76
77         let mut grid = Grid {
78             cell_size,
79             width,
80             height,
81             cells: vec!(vec!(true; height); width),
82         };
83
84         // start with some noise
85 //      grid.simplex_noise();
86         grid.random_noise();
87
88         // smooth with cellular automata
89         grid.smooth(iterations);
90 //      grid.smooth_until_equilibrium();
91
92         // increase resolution
93         for _i in 0..1 {
94             grid = grid.subdivide();
95             grid.smooth(iterations);
96         }
97
98         grid
99     }
100
101     #[allow(dead_code)]
102     fn simplex_noise(&mut self) {
103         use noise::{NoiseFn, OpenSimplex, Seedable};
104         let noise = OpenSimplex::new().set_seed(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as u32);
105         self.set_each(|x, y| noise.get([x as f64 / 12.0, y as f64 / 12.0]) > 0.055, 1);
106     }
107
108     #[allow(dead_code)]
109     fn random_noise(&mut self) {
110         let mut rng = rand::thread_rng();
111         self.set_each(|_x, _y| rng.gen_range(0, 100) > 55, 1);
112     }
113
114     #[allow(dead_code)]
115     fn smooth(&mut self, iterations: u8) {
116         let distance = 1;
117         for _i in 0..iterations {
118             let mut next = vec!(vec!(true; self.height); self.width);
119             for x in distance..(self.width - distance) {
120                 for y in distance..(self.height - distance) {
121                     match Grid::neighbours(&self.cells, x, y, distance) {
122                         n if n < 4 => next[x][y] = false,
123                         n if n > 4 => next[x][y] = true,
124                         _ => next[x][y] = self.cells[x][y]
125                     }
126                 }
127             }
128             if self.cells == next {
129                 break; // exit early
130             } else {
131                 self.cells = next;
132             }
133         }
134     }
135
136     #[allow(dead_code)]
137     fn smooth_until_equilibrium(&mut self) {
138         let distance = 1;
139         let mut count = 0;
140         loop {
141             count += 1;
142             let mut next = vec!(vec!(true; self.height); self.width);
143             for x in distance..(self.width - distance) {
144                 for y in distance..(self.height - distance) {
145                     match Grid::neighbours(&self.cells, x, y, distance) {
146                         n if n < 4 => next[x][y] = false,
147                         n if n > 4 => next[x][y] = true,
148                         _ => next[x][y] = self.cells[x][y]
149                     };
150                 }
151             }
152             if self.cells == next {
153                 break;
154             } else {
155                 self.cells = next;
156             }
157         }
158         println!("{} iterations needed", count);
159     }
160
161     fn neighbours(grid: &Vec<Vec<bool>>, px: usize, py: usize, distance: usize) -> u8 {
162         let mut count = 0;
163         for x in (px - distance)..=(px + distance) {
164             for y in (py - distance)..=(py + distance) {
165                 if !(x == px && y == py) && grid[x][y] {
166                     count += 1;
167                 }
168             }
169         }
170         count
171     }
172
173     fn set_each<F: FnMut(usize, usize) -> bool>(&mut self, mut func: F, walls: usize) {
174         for x in walls..(self.width - walls) {
175             for y in walls..(self.height - walls) {
176                 self.cells[x][y] = func(x, y);
177             }
178         }
179     }
180
181     fn subdivide(&mut self) -> Grid {
182         let (width, height) = (self.width * 2, self.height * 2);
183         let mut cells = vec!(vec!(true; height); width);
184         for x in 1..(width - 1) {
185             for y in 1..(height - 1) {
186                 cells[x][y] = self.cells[x / 2][y / 2];
187             }
188         }
189         Grid {
190             cell_size: self.cell_size / 2,
191             width,
192             height,
193             cells
194         }
195     }
196
197     fn find_regions(&self) -> Vec<Region> {
198         let mut regions = vec!();
199         let mut marked = vec!(vec!(false; self.height); self.width);
200         for x in 0..self.width {
201             for y in 0..self.height {
202                 if !marked[x][y] {
203                     regions.push(self.get_region_at_point(x, y, &mut marked));
204                 }
205             }
206         }
207         regions
208     }
209
210     fn get_region_at_point(&self, x: usize, y: usize, marked: &mut Vec<Vec<bool>>) -> Region {
211         let value = self.cells[x][y];
212         let mut cells = vec!();
213         let mut queue = vec!((x, y));
214         marked[x][y] = true;
215
216         while let Some(p) = queue.pop() {
217             cells.push(p);
218             for i in &[(-1, 0), (1, 0), (0, -1), (0, 1)] {
219                 let ip = (p.0 as isize + i.0, p.1 as isize + i.1);
220                 if ip.0 >= 0 && ip.0 < self.width as isize && ip.1 >= 0 && ip.1 < self.height as isize {
221                     let up = (ip.0 as usize, ip.1 as usize);
222                     if self.cells[up.0][up.1] == value && !marked[up.0][up.1] {
223                         marked[up.0][up.1] = true;
224                         queue.push(up);
225                     }
226                 }
227             }
228         }
229
230         Region { value, cells }
231     }
232
233     fn delete_region(&mut self, region: &Region) {
234         for c in &region.cells {
235             self.cells[c.0][c.1] = !region.value;
236         }
237     }
238
239     pub fn filter_regions(&mut self) {
240         let min_wall_size = 0.0015;
241         println!("grid size: ({}, {}) = {} cells", self.width, self.height, self.width * self.height);
242         println!("min wall size: {}", (self.width * self.height) as f64 * min_wall_size);
243
244         // delete all smaller wall regions
245         for r in self.find_regions().iter().filter(|r| r.value) {
246             let percent = r.cells.len() as f64 / (self.width * self.height) as f64;
247             if percent < min_wall_size {
248                 println!("delete wall region of size {}", r.cells.len());
249                 self.delete_region(r);
250             }
251         }
252
253         // delete all rooms but the largest
254         let regions = self.find_regions(); // check again, because if a removed room contains a removed wall, the removed wall will become a room
255         let mut rooms: Vec<&Region> = regions.iter().filter(|r| !r.value).collect();
256         rooms.sort_by_key(|r| r.cells.len());
257         rooms.reverse();
258         while rooms.len() > 1 {
259             self.delete_region(rooms.pop().unwrap());
260         }
261     }
262 }
263
264 ////////// REGION //////////////////////////////////////////////////////////////
265
266 struct Region {
267     value: bool,
268     cells: Vec<(usize, usize)>,
269 }