Refactor walls
[kaka/rust-sdl-test.git] / src / core / level / lvlgen.rs
index 3dcc3a7..109337a 100644 (file)
@@ -1,32 +1,37 @@
-use {point, time_scope};
-use common::Point2D;
-use super::{Grid, Level};
+use common::{Point, Dimension};
 use noise::{NoiseFn, OpenSimplex, Seedable};
 use rand::Rng;
+use super::{Grid, Level, WallRegion};
+use {point, time_scope};
 
 ////////// LEVEL GENERATOR /////////////////////////////////////////////////////
 
-#[derive(Default)]
+#[derive(Debug, Default)]
 pub struct LevelGenerator {
     pub seed: u32,
     pub iterations: u8,
+    pub wall_smooth_radius: u8,
 }
 
 impl LevelGenerator {
-    pub fn new(seed: u32, iterations: u8) -> Self{
-       LevelGenerator { seed, iterations }
+    pub fn new(seed: u32) -> Self{
+       LevelGenerator {
+           seed,
+           iterations: 5,
+           wall_smooth_radius: 2,
+       }
     }
 
     pub fn generate(&self) -> Level {
-       time_scope!("grid generation");
+       dbg!(self);
+       time_scope!("level generation");
 
        let cell_size = 20;
        let (width, height) = (2560 / cell_size, 1440 / cell_size);
 
        let mut grid = Grid {
-           cell_size,
-           width,
-           height,
+           cell_size: (cell_size, cell_size).into(),
+           size: (width, height).into(),
            cells: vec!(vec!(true; height); width),
        };
 
@@ -48,21 +53,17 @@ impl LevelGenerator {
        self.filter_regions(&mut grid);
 
        let walls = self.find_walls(&grid);
-       Level {
-           gravity: point!(0.0, 0.1),
-           grid,
-           walls,
-       }
+       Level::new(point!(0.0, 0.1), grid, walls)
     }
 
     #[allow(dead_code)]
-    fn simplex_noise(&self, grid: &mut Grid) {
+    fn simplex_noise(&self, grid: &mut Grid<bool>) {
        let noise = OpenSimplex::new().set_seed(self.seed);
        self.set_each(grid, |x, y| noise.get([x as f64 / 12.0, y as f64 / 12.0]) > 0.055, 1);
     }
 
     #[allow(dead_code)]
-    fn random_noise(&self, grid: &mut Grid) {
+    fn random_noise(&self, grid: &mut Grid<bool>) {
        let mut rng: rand::prelude::StdRng = rand::SeedableRng::seed_from_u64(self.seed as u64);
        let noise = OpenSimplex::new().set_seed(self.seed);
        self.set_each(grid, |_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
@@ -71,12 +72,12 @@ impl LevelGenerator {
     }
 
     #[allow(dead_code)]
-    fn smooth(&self, grid: &mut Grid) {
+    fn smooth(&self, grid: &mut Grid<bool>) {
        let distance = 1;
        for _i in 0..self.iterations {
-           let mut next = vec!(vec!(true; grid.height); grid.width);
-           for x in distance..(grid.width - distance) {
-               for y in distance..(grid.height - distance) {
+           let mut next = vec!(vec!(true; grid.size.height); grid.size.width);
+           for x in distance..(grid.size.width - distance) {
+               for y in distance..(grid.size.height - distance) {
                    match self.neighbours(&grid.cells, x, y, distance) {
                        n if n < 4 => next[x][y] = false,
                        n if n > 4 => next[x][y] = true,
@@ -93,14 +94,14 @@ impl LevelGenerator {
     }
 
     #[allow(dead_code)]
-    fn smooth_until_equilibrium(&self, grid: &mut Grid) {
+    fn smooth_until_equilibrium(&self, grid: &mut Grid<bool>) {
        let distance = 1;
        let mut count = 0;
        loop {
            count += 1;
-           let mut next = vec!(vec!(true; grid.height); grid.width);
-           for x in distance..(grid.width - distance) {
-               for y in distance..(grid.height - distance) {
+           let mut next = vec!(vec!(true; grid.size.height); grid.size.width);
+           for x in distance..(grid.size.width - distance) {
+               for y in distance..(grid.size.height - distance) {
                    match self.neighbours(&grid.cells, x, y, distance) {
                        n if n < 4 => next[x][y] = false,
                        n if n > 4 => next[x][y] = true,
@@ -114,7 +115,7 @@ impl LevelGenerator {
                grid.cells = next;
            }
        }
-       println!("{} iterations needed", count);
+       println!("  {} iterations needed", count);
     }
 
     fn neighbours(&self, grid: &Vec<Vec<bool>>, px: usize, py: usize, distance: usize) -> u8 {
@@ -129,16 +130,16 @@ impl LevelGenerator {
        count
     }
 
-    fn set_each<F: FnMut(usize, usize) -> bool>(&self, grid: &mut Grid, mut func: F, walls: usize) {
-       for x in walls..(grid.width - walls) {
-           for y in walls..(grid.height - walls) {
+    fn set_each<F: FnMut(usize, usize) -> bool>(&self, grid: &mut Grid<bool>, mut func: F, walls: usize) {
+       for x in walls..(grid.size.width - walls) {
+           for y in walls..(grid.size.height - walls) {
                grid.cells[x][y] = func(x, y);
            }
        }
     }
 
-    fn subdivide(&self, grid: &mut Grid) -> Grid {
-       let (width, height) = (grid.width * 2, grid.height * 2);
+    fn subdivide(&self, grid: &mut Grid<bool>) -> Grid<bool> {
+       let (width, height) = (grid.size.width * 2, grid.size.height * 2);
        let mut cells = vec!(vec!(true; height); width);
        for x in 1..(width - 1) {
            for y in 1..(height - 1) {
@@ -146,19 +147,18 @@ impl LevelGenerator {
            }
        }
        Grid {
-           cell_size: grid.cell_size / 2,
-           width,
-           height,
+           cell_size: (grid.cell_size.width / 2, grid.cell_size.height / 2).into(),
+           size: (width, height).into(),
            cells
        }
     }
 
-    fn find_regions(&self, grid: &Grid) -> Vec<Region> {
-       time_scope!("finding all regions");
+    fn find_regions(&self, grid: &Grid<bool>) -> Vec<Region> {
+       time_scope!("  finding all regions");
        let mut regions = vec!();
-       let mut marked = vec!(vec!(false; grid.height); grid.width);
-       for x in 0..grid.width {
-           for y in 0..grid.height {
+       let mut marked = vec!(vec!(false; grid.size.height); grid.size.width);
+       for x in 0..grid.size.width {
+           for y in 0..grid.size.height {
                if !marked[x][y] {
                    regions.push(self.get_region_at_point(grid, x, y, &mut marked));
                }
@@ -167,7 +167,7 @@ impl LevelGenerator {
        regions
     }
 
-    fn get_region_at_point(&self, grid: &Grid, x: usize, y: usize, marked: &mut Vec<Vec<bool>>) -> Region {
+    fn get_region_at_point(&self, grid: &Grid<bool>, x: usize, y: usize, marked: &mut Vec<Vec<bool>>) -> Region {
        let value = grid.cells[x][y];
        let mut cells = vec!();
        let mut queue = vec!((x, y));
@@ -177,7 +177,7 @@ impl LevelGenerator {
            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 < grid.width as isize && ip.1 >= 0 && ip.1 < grid.height as isize {
+               if ip.0 >= 0 && ip.0 < grid.size.width as isize && ip.1 >= 0 && ip.1 < grid.size.height as isize {
                    let up = (ip.0 as usize, ip.1 as usize);
                    if grid.cells[up.0][up.1] == value && !marked[up.0][up.1] {
                        marked[up.0][up.1] = true;
@@ -190,22 +190,22 @@ impl LevelGenerator {
        Region { value, cells }
     }
 
-    fn delete_region(&self, grid: &mut Grid, region: &Region) {
+    fn delete_region(&self, grid: &mut Grid<bool>, region: &Region) {
        for c in &region.cells {
            grid.cells[c.0][c.1] = !region.value;
        }
     }
 
-    fn filter_regions(&self, grid: &mut Grid) {
+    fn filter_regions(&self, grid: &mut Grid<bool>) {
        let min_wall_size = 0.0015;
-       println!("grid size: ({}, {}) = {} cells", grid.width, grid.height, grid.width * grid.height);
-       println!("min wall size: {}", (grid.width * grid.height) as f64 * min_wall_size);
+       println!("  grid size: ({}, {}) = {} cells", grid.size.width, grid.size.height, grid.size.width * grid.size.height);
+       println!("  min wall size: {}", (grid.size.width * grid.size.height) as f64 * min_wall_size);
 
        // delete all smaller wall regions
        for r in self.find_regions(grid).iter().filter(|r| r.value) {
-           let percent = r.cells.len() as f64 / (grid.width * grid.height) as f64;
+           let percent = r.cells.len() as f64 / (grid.size.width * grid.size.height) as f64;
            if percent < min_wall_size {
-               // println!("delete wall region of size {}", r.cells.len());
+               // println!("  delete wall region of size {}", r.cells.len());
                self.delete_region(grid, r);
            }
        }
@@ -220,20 +220,30 @@ impl LevelGenerator {
        }
     }
 
-    fn find_walls(&self, grid: &Grid) -> Vec<Vec<Point2D<isize>>> {
+    fn find_walls(&self, grid: &Grid<bool>) -> Vec<WallRegion> {
        let mut walls = vec!();
        for r in self.find_regions(&grid) {
            if r.value {
-               let mut outline = r.outline(grid.cell_size);
-               for i in 2..(outline.len() - 2) {
-//                 outline[i] = (outline[i - 1] + outline[i] + outline[i + 1]) / 3;
-                   outline[i] = (outline[i - 2] + outline[i - 1] + outline[i] + outline[i + 1] + outline[i + 2]) / 5;
-               }
-               walls.push(outline);
+               let outline = r.outline(&grid.cell_size);
+               let mut floats = outline.iter().map(|p| point!(p.x as f64, p.y as f64)).collect();
+               self.smooth_wall(&mut floats, self.wall_smooth_radius as isize);
+               let wall = WallRegion::new(floats);
+               walls.push(wall);
            }
        }
        walls
     }
+
+    fn smooth_wall(&self, points: &mut Vec<Point<f64>>, radius: isize) {
+       let idx = |n| (n as isize + points.len() as isize) as usize % points.len();
+       let mut new_points = points.clone();
+       for i in 0..points.len() {
+           new_points[i] = ((i as isize + 1 - radius)..=(i as isize + radius))                  // aggregates all points from -radius to +radius
+               .fold(points[idx(i as isize - radius)], |acc, o| acc + points[idx(o)]) // with addition
+               / (radius * 2 + 1) as f64;
+       }
+       *points = new_points;
+    }
 }
 
 ////////// REGION //////////////////////////////////////////////////////////////
@@ -256,21 +266,23 @@ impl Region {
        (min.0, min.1, 1 + max.0 - min.0, 1 + max.1 - min.1)
     }
 
-    pub fn outline(&self, scale: usize) -> Vec<Point2D<isize>> {
+    pub fn outline(&self, scale: &Dimension<usize>) -> Vec<Point<isize>> {
        let rect = self.enclosing_rect();
        let (ox, oy, w, h) = rect;
        let grid = self.grid(&rect);
        let mut marked = vec!(vec!(false; h); w);
        let mut outline = vec!();
        let mut directions = vec!((1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)); // 8 directions rotating right from starting direction right
+       let multiplier = (scale.width as isize, scale.height as isize);
+       let offset = (scale.width as isize / 2, scale.height as isize / 2);
 
-       let mut p = self.find_first_point_of_outline(&rect, &grid);
+       let start = self.find_first_point_of_outline(&rect, &grid);
+       let mut p = start;
        marked[p.x as usize][p.y as usize] = true;
        loop {
-           outline.push((p + (ox as isize, oy as isize)) * scale as isize);
+           outline.push((p + (ox as isize, oy as isize)) * multiplier + offset);
            self.find_next_point_of_outline(&grid, &mut p, &mut directions);
-           if marked[p.x as usize][p.y as usize] {
-               // we're back at the beginning
+           if p == start {
                break;
            }
            marked[p.x as usize][p.y as usize] = true;
@@ -313,7 +325,7 @@ impl Region {
        grid
     }
 
-    fn find_first_point_of_outline(&self, rect: &(usize, usize, usize, usize), grid: &Vec<Vec<bool>>) -> Point2D<isize> {
+    fn find_first_point_of_outline(&self, rect: &(usize, usize, usize, usize), grid: &Vec<Vec<bool>>) -> Point<isize> {
        let (ox, oy, w, h) = rect;
        let is_outer_wall = (ox, oy) == (&0, &0); // we know this is always the outer wall of the level
        for x in 0..*w {
@@ -329,7 +341,7 @@ impl Region {
        panic!("no wall found!");
     }
 
-    fn find_next_point_of_outline(&self, grid: &Vec<Vec<bool>>, p: &mut Point2D<isize>, directions: &mut Vec<(isize, isize)>) {
+    fn find_next_point_of_outline(&self, grid: &Vec<Vec<bool>>, p: &mut Point<isize>, directions: &mut Vec<(isize, isize)>) {
        directions.rotate_left(2);
        loop {
            let d = directions[0];
@@ -341,7 +353,7 @@ impl Region {
        }
     }
 
-    fn check(&self, p: Point2D<isize>, grid: &Vec<Vec<bool>>) -> bool {
+    fn check(&self, p: Point<isize>, grid: &Vec<Vec<bool>>) -> bool {
        if p.x < 0 || p.x >= grid.len() as isize || p.y < 0 || p.y >= grid[0].len() as isize {
            false
        } else {