-use AppState;
use ActiveState;
+use AppState;
use common::{Point2D, Radians};
use core::app::StateChange;
use core::controller::Controller;
use core::controller::ControllerManager;
-use core::level::Level;
+use core::level::{Level, LevelGenerator};
use core::render::Renderer;
use point;
use sdl2::event::Event;
#[derive(Default)]
pub struct GameState {
world: World,
+ lvlgen: LevelGenerator,
}
impl GameState {
pub fn new() -> Self {
+ let lvlgen = LevelGenerator::new(0, 5);
GameState {
- world: World::new(),
+ world: World::new(lvlgen.generate()),
+ lvlgen,
}
}
}
return Some(StateChange::Push(Box::new(ActiveState::new((800, 600)))))
}
Event::KeyDown { keycode: Some(Keycode::Space), .. } => {
- self.world.level = Level::new(self.world.level.gravity);
+ self.lvlgen.seed = std::time::UNIX_EPOCH.elapsed().unwrap().as_secs() as u32;
+ self.world.level = self.lvlgen.generate();
}
Event::KeyDown { keycode: Some(Keycode::KpPlus), .. } => {
- self.world.level.increase_iteration();
+ self.lvlgen.iterations += 1;
+ println!("{} iteration(s) of cellular automata", self.lvlgen.iterations);
+ self.world.level = self.lvlgen.generate();
}
Event::KeyDown { keycode: Some(Keycode::KpMinus), .. } => {
- self.world.level.decrease_iteration();
- }
- Event::KeyDown { keycode: Some(Keycode::KpEnter), .. } => {
- self.world.level.filter_regions();
+ self.lvlgen.iterations = 1.max(self.lvlgen.iterations - 1);
+ println!("{} iteration(s) of cellular automata", self.lvlgen.iterations);
+ self.world.level = self.lvlgen.generate();
}
_ => {}
}
}
impl World {
- pub fn new() -> Self {
+ pub fn new(level: Level) -> Self {
World {
- level: Level::new(point!(0.0, 0.1)),
+ level,
..Default::default()
}
}
+++ /dev/null
-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<f64>,
- pub grid: Grid,
- iterations: u8,
- walls: Vec<Vec<Point2D<isize>>>,
-}
-
-impl Level {
- pub fn new(gravity: Point2D<f64>) -> Self {
- let mut lvl = Level { gravity, grid: Grid::generate(10), iterations: 10, walls: vec!() };
- lvl.filter_regions();
- lvl
- }
-
- fn generate(&mut self) {
- self.grid = Grid::generate(self.iterations);
- }
-
- pub fn increase_iteration(&mut self) {
- self.iterations += 1;
- self.generate();
- println!("iterate {} time(s)", self.iterations);
- }
-
- pub fn decrease_iteration(&mut self) {
- self.iterations -= 1;
- self.generate();
- println!("iterate {} time(s)", self.iterations);
- }
-
- pub fn filter_regions(&mut self) {
- self.grid.filter_regions();
- let mut walls = vec!();
- for mut r in self.grid.find_regions() {
- if r.value {
- let mut outline = r.outline(self.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);
- }
- }
- self.walls = walls;
- }
-
- 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();
- }
- }
- }
-
- let off = (size / 2) as i32;
- for wall in &self.walls {
- for w in wall.windows(2) {
- renderer.draw_line((w[0].x as i32 + off, w[0].y as i32 + off), (w[1].x as i32 + off, w[1].y as i32 + off), (255, 255, 0));
- }
- let last = wall.len() - 1;
- renderer.draw_line((wall[0].x as i32 + off, wall[0].y as i32 + off), (wall[last].x as i32 + off, wall[last].y as i32 + off), (255, 255, 0));
- }
- }
-}
-
-////////// GRID ////////////////////////////////////////////////////////////////
-
-
-#[derive(Default)]
-pub struct Grid {
- pub width: usize,
- pub height: usize,
- pub cell_size: usize,
- pub cells: Vec<Vec<bool>>,
-}
-
-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<Vec<bool>>, 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<F: FnMut(usize, usize) -> 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<Region> {
- 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<Vec<bool>>) -> 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)>,
-}
-
-impl Region {
- fn enclosing_rect(&self) -> (usize, usize, usize, usize) {
- let mut min = (usize::MAX, usize::MAX);
- let mut max = (0, 0);
- for c in &self.cells {
- if c.0 < min.0 { min.0 = c.0; }
- else if c.0 > max.0 { max.0 = c.0; }
- if c.1 < min.1 { min.1 = c.1; }
- else if c.1 > max.1 { max.1 = c.1; }
- }
- (min.0, min.1, 1 + max.0 - min.0, 1 + max.1 - min.1)
- }
-
- pub fn outline(&mut self, scale: usize) -> Vec<Point2D<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 p, mut dir) = self.find_first_point_of_outline(&rect, &grid);
-// println!("starting at {:?} with dir {:?}", p, dir);
- marked[p.x as usize][p.y as usize] = true;
- loop {
- outline.push((p + (ox as isize, oy as isize)) * scale as isize);
- let result = self.find_next_point_of_outline(&grid, p, dir);
- p = result.0;
- dir = result.1;
-// println!("next at {:?} with dir {:?}", p, dir);
- if marked[p.x as usize][p.y as usize] {
- // we're back at the beginning
- break;
- }
- marked[p.x as usize][p.y as usize] = true;
- }
-
- outline
- }
-
- fn grid(&self, rect: &(usize, usize, usize, usize)) -> Vec<Vec<bool>> {
- let (x, y, w, h) = rect;
- let mut grid = vec!(vec!(false; *h); *w);
- for c in &self.cells {
- grid[c.0 - x][c.1 - y] = true;
- }
- grid
- }
-
- fn find_first_point_of_outline(&self, rect: &(usize, usize, usize, usize), grid: &Vec<Vec<bool>>) -> (Point2D<isize>, Point2D<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 {
- for y in 0..*h {
- if is_outer_wall && !grid[x][y] {
- return (point!(x as isize, y as isize - 1), point!(0, 1)) // one step back because we're not on a wall tile
- }
- else if !is_outer_wall && grid[x][y] {
- return (point!(x as isize, y as isize), point!(1, 0))
- }
- }
- }
- panic!("no wall found!");
- }
-
- fn find_next_point_of_outline(&self, grid: &Vec<Vec<bool>>, p: Point2D<isize>, dir: Point2D<isize>) -> (Point2D<isize>, Point2D<isize>) {
- let left = match dir.into() {
- (-1, 0) => (0, 1),
- (0, 1) => (1, 0),
- (1, 0) => (0, -1),
- (0, -1) => (-1, 0),
- _ => (0, 0),
- };
- let right = match dir.into() {
- (0, 1) => (-1, 0),
- (1, 0) => (0, 1),
- (0, -1) => (1, 0),
- (-1, 0) => (0, -1),
- _ => (0, 0),
- };
- if self.check(p + dir, grid) {
-// println!("{:?} is true", p + dir);
- if self.check(p + dir + left, grid) {
-// println!("going left to {:?}", p + dir + left);
- return (p + dir + left, left.into())
- } else {
- return (p + dir, dir)
- }
- } else {
-// println!("{:?} is false", p + dir);
- if self.check(p + dir + right, grid) {
-// println!("going right to {:?}", p + dir + right);
- return (p + dir + right, dir)
- } else {
-// println!("going right from p to {:?}", p + right);
- return (p + right, right.into())
- }
- }
- }
-
- fn check(&self, p: Point2D<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 {
- grid[p.x as usize][p.y as usize]
- }
- }
-}
--- /dev/null
+use {point, time_scope};
+use common::Point2D;
+use super::{Grid, Level};
+use noise::{NoiseFn, OpenSimplex, Seedable};
+use rand::Rng;
+
+////////// LEVEL GENERATOR /////////////////////////////////////////////////////
+
+#[derive(Default)]
+pub struct LevelGenerator {
+ pub seed: u32,
+ pub iterations: u8,
+}
+
+impl LevelGenerator {
+ pub fn new(seed: u32, iterations: u8) -> Self{
+ LevelGenerator { seed, iterations }
+ }
+
+ pub fn generate(&self) -> Level {
+ 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
+// self.simplex_noise(&mut grid);
+ self.random_noise(&mut grid);
+
+ // smooth with cellular automata
+ self.smooth(&mut grid);
+// grid.smooth_until_equilibrium(&mut grid);
+
+ // increase resolution
+ for _i in 0..1 {
+ grid = self.subdivide(&mut grid);
+ self.smooth(&mut grid);
+// self.smooth_until_equilibrium(&mut grid);
+ }
+
+ self.filter_regions(&mut grid);
+
+ let walls = self.find_walls(&grid);
+ Level {
+ gravity: point!(0.0, 0.1),
+ grid,
+ walls,
+ }
+ }
+
+ #[allow(dead_code)]
+ fn simplex_noise(&self, grid: &mut Grid) {
+ 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) {
+ 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
+ // 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(&self, grid: &mut Grid) {
+ 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) {
+ match self.neighbours(&grid.cells, x, y, distance) {
+ n if n < 4 => next[x][y] = false,
+ n if n > 4 => next[x][y] = true,
+ _ => next[x][y] = grid.cells[x][y]
+ }
+ }
+ }
+ if grid.cells == next {
+ break; // exit early
+ } else {
+ grid.cells = next;
+ }
+ }
+ }
+
+ #[allow(dead_code)]
+ fn smooth_until_equilibrium(&self, grid: &mut Grid) {
+ 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) {
+ match self.neighbours(&grid.cells, x, y, distance) {
+ n if n < 4 => next[x][y] = false,
+ n if n > 4 => next[x][y] = true,
+ _ => next[x][y] = grid.cells[x][y]
+ };
+ }
+ }
+ if grid.cells == next {
+ break;
+ } else {
+ grid.cells = next;
+ }
+ }
+ println!("{} iterations needed", count);
+ }
+
+ fn neighbours(&self, grid: &Vec<Vec<bool>>, 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<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) {
+ grid.cells[x][y] = func(x, y);
+ }
+ }
+ }
+
+ fn subdivide(&self, grid: &mut Grid) -> Grid {
+ let (width, height) = (grid.width * 2, grid.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] = grid.cells[x / 2][y / 2];
+ }
+ }
+ Grid {
+ cell_size: grid.cell_size / 2,
+ width,
+ height,
+ cells
+ }
+ }
+
+ fn find_regions(&self, grid: &Grid) -> 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 {
+ if !marked[x][y] {
+ regions.push(self.get_region_at_point(grid, x, y, &mut marked));
+ }
+ }
+ }
+ regions
+ }
+
+ fn get_region_at_point(&self, grid: &Grid, 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));
+ 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 < grid.width as isize && ip.1 >= 0 && ip.1 < grid.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;
+ queue.push(up);
+ }
+ }
+ }
+ }
+
+ Region { value, cells }
+ }
+
+ fn delete_region(&self, grid: &mut Grid, region: &Region) {
+ for c in ®ion.cells {
+ grid.cells[c.0][c.1] = !region.value;
+ }
+ }
+
+ fn filter_regions(&self, grid: &mut Grid) {
+ 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);
+
+ // 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;
+ if percent < min_wall_size {
+ // println!("delete wall region of size {}", r.cells.len());
+ self.delete_region(grid, r);
+ }
+ }
+
+ // delete all rooms but the largest
+ let regions = self.find_regions(grid); // 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(grid, rooms.pop().unwrap());
+ }
+ }
+
+ fn find_walls(&self, grid: &Grid) -> Vec<Vec<Point2D<isize>>> {
+ 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);
+ }
+ }
+ walls
+ }
+}
+
+////////// REGION //////////////////////////////////////////////////////////////
+
+struct Region {
+ value: bool,
+ cells: Vec<(usize, usize)>,
+}
+
+impl Region {
+ fn enclosing_rect(&self) -> (usize, usize, usize, usize) {
+ let mut min = (usize::MAX, usize::MAX);
+ let mut max = (0, 0);
+ for c in &self.cells {
+ if c.0 < min.0 { min.0 = c.0; }
+ else if c.0 > max.0 { max.0 = c.0; }
+ if c.1 < min.1 { min.1 = c.1; }
+ else if c.1 > max.1 { max.1 = c.1; }
+ }
+ (min.0, min.1, 1 + max.0 - min.0, 1 + max.1 - min.1)
+ }
+
+ pub fn outline(&self, scale: usize) -> Vec<Point2D<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 mut p = self.find_first_point_of_outline(&rect, &grid);
+ marked[p.x as usize][p.y as usize] = true;
+ loop {
+ outline.push((p + (ox as isize, oy as isize)) * scale as isize);
+ 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
+ break;
+ }
+ marked[p.x as usize][p.y as usize] = true;
+ }
+
+ outline
+ }
+
+ #[allow(dead_code)]
+ fn print_grid(&self, grid: &Vec<Vec<bool>>) {
+ let w = grid.len();
+ let h = grid[0].len();
+ let mut g = vec!(vec!(false; w); h);
+ for x in 0..w {
+ for y in 0..h {
+ g[y][x] = grid[x][y];
+ }
+ }
+ println!("grid {} x {}", w, h);
+ print!(" ");
+ for n in 0..w {
+ print!("{}", n % 10);
+ }
+ println!();
+ for (n, row) in g.iter().enumerate() {
+ print!("{:>3}|", n);
+ for col in row {
+ print!("{}", if *col { "#" } else { " " });
+ }
+ println!("|");
+ }
+ }
+
+ fn grid(&self, rect: &(usize, usize, usize, usize)) -> Vec<Vec<bool>> {
+ let (x, y, w, h) = rect;
+ let mut grid = vec!(vec!(false; *h); *w);
+ for c in &self.cells {
+ grid[c.0 - x][c.1 - y] = true;
+ }
+ grid
+ }
+
+ fn find_first_point_of_outline(&self, rect: &(usize, usize, usize, usize), grid: &Vec<Vec<bool>>) -> Point2D<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 {
+ for y in 0..*h {
+ if is_outer_wall && !grid[x][y] {
+ return point!(x as isize, y as isize - 1); // one step back because we're not on a wall tile
+ }
+ else if !is_outer_wall && grid[x][y] {
+ return point!(x as isize, y as isize);
+ }
+ }
+ }
+ panic!("no wall found!");
+ }
+
+ fn find_next_point_of_outline(&self, grid: &Vec<Vec<bool>>, p: &mut Point2D<isize>, directions: &mut Vec<(isize, isize)>) {
+ directions.rotate_left(2);
+ loop {
+ let d = directions[0];
+ if self.check(*p + d, grid) {
+ *p += d;
+ break;
+ }
+ directions.rotate_right(1);
+ }
+ }
+
+ fn check(&self, p: Point2D<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 {
+ grid[p.x as usize][p.y as usize]
+ }
+ }
+}
--- /dev/null
+use common::Point2D;
+use core::render::Renderer;
+use sprites::SpriteManager;
+
+mod lvlgen;
+
+pub use self::lvlgen::LevelGenerator;
+
+////////// LEVEL ///////////////////////////////////////////////////////////////
+
+#[derive(Default)]
+pub struct Level {
+ pub gravity: Point2D<f64>,
+ pub grid: Grid,
+ walls: Vec<Vec<Point2D<isize>>>,
+}
+
+impl Level {
+ // pub fn new(gravity: Point2D<f64>) -> Self {
+ // let seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as u32;
+ // let mut lvl = Level { gravity, grid: Grid::generate(seed, 10), iterations: 10, walls: vec!() };
+ // lvl.filter_regions();
+ // lvl
+ // }
+
+ 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();
+ }
+ }
+ }
+
+ let off = (size / 2) as i32;
+ for wall in &self.walls {
+ for w in wall.windows(2) {
+ renderer.draw_line((w[0].x as i32 + off, w[0].y as i32 + off), (w[1].x as i32 + off, w[1].y as i32 + off), (255, 255, 0));
+ }
+ let last = wall.len() - 1;
+ renderer.draw_line((wall[0].x as i32 + off, wall[0].y as i32 + off), (wall[last].x as i32 + off, wall[last].y as i32 + off), (255, 255, 0));
+ }
+ }
+}
+
+////////// GRID ////////////////////////////////////////////////////////////////
+
+#[derive(Default)]
+pub struct Grid {
+ pub width: usize,
+ pub height: usize,
+ pub cell_size: usize,
+ pub cells: Vec<Vec<bool>>,
+}