use common::Point2D; use ::{point, time_scope}; use core::render::Renderer; use noise::{NoiseFn, OpenSimplex, Seedable}; use rand::Rng; use sprites::SpriteManager; ////////// LEVEL /////////////////////////////////////////////////////////////// #[derive(Default)] pub struct Level { pub gravity: Point2D, pub grid: Grid, iterations: u8, } impl Level { pub fn new(gravity: Point2D) -> Self { Level { gravity, grid: Grid::generate(10), iterations: 10 } } pub fn regenerate(&mut self) { self.grid = Grid::generate(self.iterations); } pub fn increase_iteration(&mut self) { self.iterations += 1; self.regenerate(); println!("iterate {} time(s)", self.iterations); } pub fn decrease_iteration(&mut self) { self.iterations -= 1; self.regenerate(); println!("iterate {} time(s)", self.iterations); } pub fn filter_regions(&mut self) { self.grid.filter_regions(); } pub fn render(&mut self, renderer: &mut Renderer, _sprites: &SpriteManager) { renderer.canvas().set_draw_color((64, 64, 64)); let size = self.grid.cell_size; for x in 0..self.grid.width { for y in 0..self.grid.height { if self.grid.cells[x][y] { 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(); } } } } } ////////// GRID //////////////////////////////////////////////////////////////// #[derive(Default)] pub struct Grid { pub width: usize, pub height: usize, pub cell_size: usize, pub cells: Vec>, } impl Grid { fn generate(iterations: u8) -> Grid { time_scope!("grid generation"); let cell_size = 20; let (width, height) = (2560 / cell_size, 1440 / cell_size); let mut grid = Grid { cell_size, width, height, cells: vec!(vec!(true; height); width), }; // start with some noise // grid.simplex_noise(); grid.random_noise(); // smooth with cellular automata grid.smooth(iterations); // grid.smooth_until_equilibrium(); // increase resolution for _i in 0..1 { grid = grid.subdivide(); grid.smooth(iterations); } grid } #[allow(dead_code)] fn simplex_noise(&mut self) { let noise = OpenSimplex::new().set_seed(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as u32); self.set_each(|x, y| noise.get([x as f64 / 12.0, y as f64 / 12.0]) > 0.055, 1); } #[allow(dead_code)] fn random_noise(&mut self) { let mut rng = rand::thread_rng(); let noise = OpenSimplex::new().set_seed(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as u32); 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 // let w = self.width as f64; // self.set_each(|_x, _y| rng.gen_range(0, 100) > (45 + ((15 * _x) as f64 / w) as usize), 1); // opens up to the right } #[allow(dead_code)] fn smooth(&mut self, iterations: u8) { let distance = 1; for _i in 0..iterations { let mut next = vec!(vec!(true; self.height); self.width); for x in distance..(self.width - distance) { for y in distance..(self.height - distance) { match Grid::neighbours(&self.cells, x, y, distance) { n if n < 4 => next[x][y] = false, n if n > 4 => next[x][y] = true, _ => next[x][y] = self.cells[x][y] } } } if self.cells == next { break; // exit early } else { self.cells = next; } } } #[allow(dead_code)] fn smooth_until_equilibrium(&mut self) { let distance = 1; let mut count = 0; loop { count += 1; let mut next = vec!(vec!(true; self.height); self.width); for x in distance..(self.width - distance) { for y in distance..(self.height - distance) { match Grid::neighbours(&self.cells, x, y, distance) { n if n < 4 => next[x][y] = false, n if n > 4 => next[x][y] = true, _ => next[x][y] = self.cells[x][y] }; } } if self.cells == next { break; } else { self.cells = next; } } println!("{} iterations needed", count); } fn neighbours(grid: &Vec>, px: usize, py: usize, distance: usize) -> u8 { let mut count = 0; for x in (px - distance)..=(px + distance) { for y in (py - distance)..=(py + distance) { if !(x == px && y == py) && grid[x][y] { count += 1; } } } count } fn set_each bool>(&mut self, mut func: F, walls: usize) { for x in walls..(self.width - walls) { for y in walls..(self.height - walls) { self.cells[x][y] = func(x, y); } } } fn subdivide(&mut self) -> Grid { let (width, height) = (self.width * 2, self.height * 2); let mut cells = vec!(vec!(true; height); width); for x in 1..(width - 1) { for y in 1..(height - 1) { cells[x][y] = self.cells[x / 2][y / 2]; } } Grid { cell_size: self.cell_size / 2, width, height, cells } } fn find_regions(&self) -> Vec { time_scope!("finding all regions"); let mut regions = vec!(); let mut marked = vec!(vec!(false; self.height); self.width); for x in 0..self.width { for y in 0..self.height { if !marked[x][y] { regions.push(self.get_region_at_point(x, y, &mut marked)); } } } regions } fn get_region_at_point(&self, x: usize, y: usize, marked: &mut Vec>) -> Region { let value = self.cells[x][y]; let mut cells = vec!(); let mut queue = vec!((x, y)); marked[x][y] = true; while let Some(p) = queue.pop() { cells.push(p); for i in &[(-1, 0), (1, 0), (0, -1), (0, 1)] { let ip = (p.0 as isize + i.0, p.1 as isize + i.1); if ip.0 >= 0 && ip.0 < self.width as isize && ip.1 >= 0 && ip.1 < self.height as isize { let up = (ip.0 as usize, ip.1 as usize); if self.cells[up.0][up.1] == value && !marked[up.0][up.1] { marked[up.0][up.1] = true; queue.push(up); } } } } Region { value, cells } } fn delete_region(&mut self, region: &Region) { for c in ®ion.cells { self.cells[c.0][c.1] = !region.value; } } pub fn filter_regions(&mut self) { let min_wall_size = 0.0015; println!("grid size: ({}, {}) = {} cells", self.width, self.height, self.width * self.height); println!("min wall size: {}", (self.width * self.height) as f64 * min_wall_size); // delete all smaller wall regions for r in self.find_regions().iter().filter(|r| r.value) { let percent = r.cells.len() as f64 / (self.width * self.height) as f64; if percent < min_wall_size { println!("delete wall region of size {}", r.cells.len()); self.delete_region(r); } } // delete all rooms but the largest let regions = self.find_regions(); // check again, because if a removed room contains a removed wall, the removed wall will become a room let mut rooms: Vec<&Region> = regions.iter().filter(|r| !r.value).collect(); rooms.sort_by_key(|r| r.cells.len()); rooms.reverse(); while rooms.len() > 1 { self.delete_region(rooms.pop().unwrap()); } } } ////////// REGION ////////////////////////////////////////////////////////////// struct Region { value: bool, cells: Vec<(usize, usize)>, }