Only collide with walls from the front
[kaka/rust-sdl-test.git] / src / core / level / mod.rs
index 3336b95..bdc6cb0 100644 (file)
@@ -1,6 +1,8 @@
-use common::Point;
 use core::render::Renderer;
+use geometry::{Point, Dimension, Intersection, Angle, ToAngle, supercover_line};
 use sprites::SpriteManager;
+use std::rc::Rc;
+use {point, dimen};
 
 mod lvlgen;
 
@@ -12,45 +14,269 @@ pub use self::lvlgen::LevelGenerator;
 pub struct Level {
     pub gravity: Point<f64>,
     pub grid: Grid<bool>,
-    walls: Vec<Vec<Point<isize>>>,
+    walls: Vec<Rc<WallRegion>>,
+    wall_grid: Grid<Vec<Rc<WallEdge>>>,
 }
 
 impl Level {
-    // pub fn new(gravity: Point<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 new(gravity: Point<f64>, grid: Grid<bool>, mut walls: Vec<WallRegion>) -> Self {
+       let size = (2560, 1440); // TODO: get actual size from walls or something
+       let wall_grid = Level::build_wall_grid(&mut walls, &size.into());
+       dbg!(&wall_grid.scale);
+       Level {
+           gravity,
+           grid,
+           walls: walls.into_iter().map(|i| Rc::new(i)).collect(),
+           wall_grid,
+       }
+    }
+
+    /// Creates a grid of wall edges for fast lookup
+    fn build_wall_grid(walls: &mut Vec<WallRegion>, lvlsize: &Dimension<usize>) -> Grid<Vec<Rc<WallEdge>>> {
+       let size = dimen!(lvlsize.width / 20, lvlsize.height / 20); // TODO: make sure all walls fit within the grid bounds
+       let cs = point!(lvlsize.width / size.width, lvlsize.height / size.height);
+       //let cs = point!(scale.width as f64, scale.height as f64);
+       let mut grid = Grid {
+           cells: vec!(vec!(vec!(); size.height); size.width),
+           size,
+           scale: dimen!(cs.x as f64, cs.y as f64),
+       };
+
+       for wall in walls {
+           for edge in &wall.edges {
+               for c in grid.grid_coordinates_on_line(edge.p1, edge.p2) {
+                   grid.cells[c.x][c.y].push(Rc::clone(edge));
+               }
+           }
+       }
+
+       grid
+    }
 
-    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();
+    pub fn render(&mut self, renderer: &mut Renderer, _sprites: &SpriteManager, debug_mode: bool) {
+       if debug_mode {
+           // original grid
+           renderer.canvas().set_draw_color((64, 64, 64));
+           let size = &self.grid.scale;
+           for x in 0..self.grid.size.width {
+               for y in 0..self.grid.size.height {
+                   if self.grid.cells[x][y] {
+                       renderer.canvas().fill_rect(sdl2::rect::Rect::new(
+                           x as i32 * size.width as i32,
+                           y as i32 * size.height as i32,
+                           size.width as u32,
+                           size.height as u32)).unwrap();
+                   }
+               }
+           }
+
+           // wall grid
+           renderer.canvas().set_draw_color((0, 32, 0));
+           let size = &self.wall_grid.scale;
+           for x in 0..self.wall_grid.size.width {
+               for y in 0..self.wall_grid.size.height {
+                   if !self.wall_grid.cells[x][y].is_empty() {
+                       let num = self.wall_grid.cells[x][y].len();
+                       renderer.canvas().set_draw_color((0, 32*num as u8, 0));
+                       renderer.canvas().fill_rect(sdl2::rect::Rect::new(
+                           x as i32 * size.width as i32,
+                           y as i32 * size.height as i32,
+                           size.width as u32,
+                           size.height as u32)).unwrap();
+                   }
+               }
+           }
+
+           // wall normals
+           for wall in &self.walls {
+               for e in &wall.edges {
+                   let c = (e.p1 + e.p2) / 2.0;
+                   let a = (e.p2 - e.p1).to_angle() + std::f64::consts::FRAC_PI_2.radians();
+
+                   renderer.draw_line(
+                       <(i32, i32)>::from(c.to_i32()),
+                       <(i32, i32)>::from((c + Point::from(a) * 10.0).to_i32()),
+                       (0, 128, 255));
                }
            }
        }
 
-       let off = (size / 2) as i32;
+       // walls
        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));
+           for e in &wall.edges {
+               if !debug_mode {
+                   let c = (e.p1 + e.p2) / 2.0;
+                   let a = (e.p2 - e.p1).to_angle() - std::f64::consts::FRAC_PI_2.radians();
+
+                   renderer.draw_line(
+                       <(i32, i32)>::from(c.to_i32()),
+                       <(i32, i32)>::from((c + Point::from(a) * 10.0).to_i32()),
+                       (255, 128, 0));
+
+                   renderer.draw_line(
+                       <(i32, i32)>::from(e.p1.to_i32()),
+                       <(i32, i32)>::from((c + Point::from(a) * 20.0).to_i32()),
+                       (96, 48, 0));
+                   renderer.draw_line(
+                       <(i32, i32)>::from(e.p2.to_i32()),
+                       <(i32, i32)>::from((c + Point::from(a) * 20.0).to_i32()),
+                       (96, 48, 0));
+               }
+
+               renderer.draw_line(
+                   <(i32, i32)>::from(e.p1.to_i32()),
+                   <(i32, i32)>::from(e.p2.to_i32()),
+                   (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));
        }
     }
+
+    pub fn intersect_walls(&self, p1: Point<f64>, p2: Point<f64>) -> IntersectResult {
+       for c in self.wall_grid.grid_coordinates_on_line(p1, p2) {
+           for w in &self.wall_grid.cells[c.x][c.y] {
+               if let Intersection::Point(p) = Intersection::lines(p1, p2, w.p1, w.p2) {
+                   if w.point_is_in_front(p1) {
+                       let wall = Wall {
+                           region: Rc::clone(&self.walls[w.region]),
+                           edge: Rc::clone(w),
+                       };
+                       return IntersectResult::Intersection(wall, p)
+                   }
+               }
+           }
+       }
+       IntersectResult::None
+    }
+}
+
+pub enum IntersectResult {
+    Intersection(Wall, Point<f64>),
+    None
 }
 
 ////////// GRID ////////////////////////////////////////////////////////////////
 
-#[derive(Default)]
+#[derive(Debug, Default)]
 pub struct Grid<T> {
-    pub width: usize,
-    pub height: usize,
-    pub cell_size: usize,
+    pub size: Dimension<usize>,
+    pub scale: Dimension<f64>,
     pub cells: Vec<Vec<T>>,
 }
+
+impl<T> Grid<T> {
+    // pub fn at<C>(&self, c: C) -> Option<&T>
+    // where C: Into<(isize, isize)>
+    // {
+    //         let c = c.into();
+    //         if c.0 >= 0 && c.0 < self.size.width as isize && c.1 >= 0 && c.1 < self.size.height as isize {
+    //             Some(&self.cells[c.0 as usize][c.1 as usize])
+    //         } else {
+    //             None
+    //         }
+    // }
+
+    pub fn to_grid_coordinate<C>(&self, c: C) -> Option<Point<usize>>
+    where C: Into<(isize, isize)>
+    {
+       let c = c.into();
+       if c.0 >= 0 && c.0 < self.size.width as isize && c.1 >= 0 && c.1 < self.size.height as isize {
+           Some(point!(c.0 as usize, c.1 as usize))
+       } else {
+           None
+       }
+    }
+
+    /// Returns a list of grid coordinates that a line in world coordinates passes through.
+    pub fn grid_coordinates_on_line(&self, p1: Point<f64>, p2: Point<f64>) -> Vec<Point<usize>> {
+       supercover_line(p1 / self.scale, p2 / self.scale)
+           .iter()
+           .map(|c| self.to_grid_coordinate(*c))
+           .flatten()
+           .collect()
+    }
+}
+
+////////// WALL REGION /////////////////////////////////////////////////////////
+
+#[derive(Debug, Default)]
+pub struct WallRegion {
+    edges: Vec<Rc<WallEdge>>,
+}
+
+impl WallRegion {
+    pub fn new(points: Vec<Point<f64>>) -> Self {
+       let index: RegionIndex = 0; // use as param
+       let mut edges = Vec::with_capacity(points.len());
+
+       for i in 0..points.len() {
+           let edge = Rc::new(WallEdge {
+               region: index,
+               id: i,
+               p1: points[i],
+               p2: points[(i + 1) % points.len()],
+           });
+           edges.push(edge);
+       }
+
+       WallRegion { edges }
+    }
+
+    fn next(&self, index: EdgeIndex) -> Rc<WallEdge> {
+       let index = (index + 1) % self.edges.len();
+       Rc::clone(&self.edges[index])
+    }
+
+    fn previous(&self, index: EdgeIndex) -> Rc<WallEdge> {
+       let index = (index + self.edges.len() + 1) % self.edges.len();
+       Rc::clone(&self.edges[index])
+    }
+}
+
+////////// WALL EDGE ///////////////////////////////////////////////////////////
+
+type RegionIndex = usize;
+type EdgeIndex = usize;
+
+#[derive(Debug, Default)]
+struct WallEdge {
+    region: RegionIndex,
+    id: EdgeIndex,
+    pub p1: Point<f64>,
+    pub p2: Point<f64>,
+}
+
+impl WallEdge {
+    fn point_is_in_front(&self, p: Point<f64>) -> bool {
+       let cross = (self.p2 - self.p1).cross_product(p - self.p1);
+       cross > 0.0
+    }
+}
+
+////////// WALL ////////////////////////////////////////////////////////////////
+
+pub struct Wall {
+    region: Rc<WallRegion>,
+    edge: Rc<WallEdge>,
+}
+
+impl Wall {
+    #[allow(dead_code)]
+    pub fn next(self) -> Wall {
+       Wall {
+           edge: self.region.next(self.edge.id),
+           region: self.region,
+       }
+    }
+
+    #[allow(dead_code)]
+    pub fn previous(self) -> Wall {
+       Wall {
+           edge: self.region.previous(self.edge.id),
+           region: self.region,
+       }
+    }
+
+    pub fn normal(&self) -> Angle {
+       (self.edge.p2 - self.edge.p1).to_angle() + std::f64::consts::FRAC_PI_2.radians()
+    }
+}