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