free-rusty-maker/src/engine/map/mod.rs

525 lines
16 KiB
Rust

use std::fs::File;
use std::io::Read;
use std::path::Path;
use sfml::graphics::{FloatRect, IntRect};
use sfml::system::Vector2;
use crate::engine::character::Damage;
use crate::engine::math::{clamp, Matrix};
use crate::engine::renderer::Drawable;
use crate::engine::texture::{byte_to_index, Texture, SPRITE_SIZE_F32, SPRITE_SIZE_I32};
use crate::{Error, Result};
/// This enum represents if the collision happens on the X axis or the Y axis.
#[derive(Copy, Clone)]
pub enum CollisionAxis {
/// The X axis.
X,
/// The Y axis.
Y,
/// Both axis simultaneously
Both,
}
impl CollisionAxis {
/// Returns true if the collision occured on X axis.
pub fn is_x(self) -> bool {
match self {
CollisionAxis::Y => false,
_ => true,
}
}
/// Returns true if the collision occured on Y axis.
pub fn is_y(self) -> bool {
match self {
CollisionAxis::X => false,
_ => true,
}
}
}
/// This struct represents the different sides from which a collision can occur.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct CollisionTile {
/// If the character comes from the top, it will collide if this bool is true.
pub from_top: bool,
/// If the character comes from the left, it will collide if this bool is true.
pub from_left: bool,
/// If the character comes from the right, it will collide if this bool is true.
pub from_right: bool,
/// If the character comes from the bottom, it will collide if this bool is true.
pub from_bottom: bool,
}
impl CollisionTile {
/// Creates a collision tile that does not collide.
pub fn empty() -> CollisionTile {
CollisionTile {
from_top: false,
from_left: false,
from_right: false,
from_bottom: false,
}
}
/// Creates a collision tile that collides from every side.
pub fn full() -> CollisionTile {
CollisionTile {
from_top: true,
from_left: true,
from_right: true,
from_bottom: true,
}
}
/// Tests whether a collision tile is full or not.
pub fn is_full(self) -> bool {
self.from_top && self.from_left && self.from_right && self.from_bottom
}
/// Tests whether a collision tile is empty or not.
pub fn is_empty(self) -> bool {
!self.from_top && !self.from_left && !self.from_right && !self.from_bottom
}
}
/// This struct represents a renderable tile linking to its part in the tileset texture.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct GraphicTile(Option<i32>);
impl GraphicTile {
/// Creates the correct graphic tile depending on the neighbours.
///
/// A none will be considered solid.
pub fn from_neighbour_options(tiles: &[Option<CollisionTile>; 8]) -> GraphicTile {
GraphicTile::from_neighbours(&[
tiles[0].unwrap_or_else(CollisionTile::full),
tiles[1].unwrap_or_else(CollisionTile::full),
tiles[2].unwrap_or_else(CollisionTile::full),
tiles[3].unwrap_or_else(CollisionTile::full),
tiles[4].unwrap_or_else(CollisionTile::full),
tiles[5].unwrap_or_else(CollisionTile::full),
tiles[6].unwrap_or_else(CollisionTile::full),
tiles[7].unwrap_or_else(CollisionTile::full),
])
}
/// Creates the correct graphic tile depending on the neighbours.
pub fn from_neighbours(tiles: &[CollisionTile; 8]) -> GraphicTile {
let mut byte = 0;
if !tiles[7].is_full() || !tiles[0].is_full() || !tiles[1].is_full() {
byte += 1;
}
if !tiles[1].is_full() {
byte += 2;
}
if !tiles[1].is_full() || !tiles[2].is_full() || !tiles[3].is_full() {
byte += 4;
}
if !tiles[3].is_full() {
byte += 8;
}
if !tiles[3].is_full() || !tiles[4].is_full() || !tiles[5].is_full() {
byte += 16;
}
if !tiles[5].is_full() {
byte += 32;
}
if !tiles[5].is_full() || !tiles[6].is_full() || !tiles[7].is_full() {
byte += 64;
}
if !tiles[7].is_full() {
byte += 128;
}
GraphicTile(Some(byte_to_index(byte)))
}
/// Returns the offset to the corresponding graphic tile in the texture.
pub fn offset(self) -> (i32, i32) {
match self.0 {
None => (0, 0),
Some(v) => (32 * v, 0),
}
}
/// Returns true if the tile is visible.
pub fn is_visible(&self) -> bool {
self.0.is_some()
}
}
/// A tile and its position.
pub struct PositionedTile {
/// The graphic representation of the positioned tile.
pub graphic: GraphicTile,
/// The collision representation of the positioned tile.
pub collision: CollisionTile,
/// The position of the positioned tile.
pub position: (f32, f32),
}
impl Drawable for PositionedTile {
fn texture(&self) -> Texture {
Texture::Overworld
}
fn texture_rect(&self) -> IntRect {
let offset = self.graphic.offset();
IntRect::new(offset.0, offset.1, SPRITE_SIZE_I32, SPRITE_SIZE_I32)
}
fn position(&self) -> Vector2<f32> {
self.position.into()
}
}
/// The map represents the tiles contained in a level.
#[derive(Clone)]
pub struct Map {
/// The entrace point of the character in the map.
entrance: (usize, usize),
/// The collision tiles contained in the level.
collision_tiles: Matrix<CollisionTile>,
/// The graphic tiles contained in the level.
graphic_tiles: Matrix<GraphicTile>,
}
impl Map {
/// Creates a map full of nothing, with a ground at the bottom.
pub fn new(rows: usize, cols: usize) -> Map {
let mut tiles = Matrix::from_size(rows, cols, CollisionTile::empty());
let rows = tiles.rows();
for i in 0..tiles.cols() {
tiles[(rows - 1, i)] = CollisionTile::full();
}
Map::from_collision_tiles(tiles)
}
/// Loads a map from a file.
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Map> {
let mut file = File::open(path.as_ref()).map_err(Error::Load)?;
let mut s = String::new();
file.read_to_string(&mut s).map_err(Error::Load)?;
Map::from_str(&s)
}
/// Loads a map from a string.
pub fn from_str(text: &str) -> Result<Map> {
let split = text.split('\n').collect::<Vec<_>>();
// First two usize are the size of the map
let size = split[0]
.split_whitespace()
.map(|x| x.parse::<usize>().unwrap())
.collect::<Vec<_>>();
let mut tiles = Matrix::from_size(size[0], size[1], CollisionTile::empty());
for (row, line) in split.iter().skip(1).enumerate() {
for (col, tile) in line.split_whitespace().enumerate() {
let num = tile.parse::<u8>().unwrap();
match num {
0 => (),
1 => tiles[(row, col)] = CollisionTile::full(),
_ => panic!("Expecting 0 or 1 in level files"),
}
}
}
Ok(Map::from_collision_tiles(tiles))
}
// /// Encodes the map into a binary format.
// pub fn encode(&self) -> Result<Vec<u8>> {
// serialize(&self.save_map()).map_err(Error::Encoding)
// }
// /// Decodes a map from bytes.
// pub fn decode(content: &[u8]) -> Result<Map> {
// deserialize(content)
// .map(SaveMap::to_map)
// .map_err(Error::Decoding)
// }
// /// Saves the map to a file.
// pub fn save<P: AsRef<Path>>(&self, path: P) -> Result<()> {
// let file = File::create(path.as_ref()).map_err(Error::Save)?;
// let mut writer = BufWriter::new(file);
// serialize_into(&mut writer, &self.save_map()).map_err(Error::Encoding)?;
// Ok(())
// }
// /// Loads a map from a file.
// pub fn load<P: AsRef<Path>>(path: P) -> Result<Map> {
// let file = File::open(path.as_ref()).map_err(Error::Load)?;
// let mut reader = BufReader::new(file);
// Ok(deserialize_from(&mut reader)
// .map(SaveMap::to_map)
// .map_err(Error::Decoding)?)
// }
/// Creates a map from its entrance and collision tiles.
pub fn from_entrance_and_collision_tiles(e: (usize, usize), t: Matrix<CollisionTile>) -> Map {
let rows = t.rows();
let cols = t.cols();
let graphic_tiles = Matrix::from_size(rows, cols, GraphicTile(None));
let mut map = Map {
entrance: e,
collision_tiles: t,
graphic_tiles,
};
for i in 0..rows {
for j in 0..cols {
map.graphic_tiles[(i, j)] = map.graphic_tile(i, j);
}
}
map
}
/// Creates a map from its tiles.
pub fn from_collision_tiles(collision_tiles: Matrix<CollisionTile>) -> Map {
let entrance = Map::find_entrance(&collision_tiles);
Map::from_entrance_and_collision_tiles(entrance, collision_tiles)
}
/// Creates the neighbours of a tile.
pub fn neighbours(&self, i: usize, j: usize) -> [Option<CollisionTile>; 8] {
[
if i > 0 && j > 0 {
self.collision_tiles.get(i - 1, j - 1).cloned()
} else {
None
},
if i > 0 {
self.collision_tiles.get(i - 1, j).cloned()
} else {
None
},
if i > 0 {
self.collision_tiles.get(i - 1, j + 1).cloned()
} else {
None
},
self.collision_tiles.get(i, j + 1).cloned(),
self.collision_tiles.get(i + 1, j + 1).cloned(),
self.collision_tiles.get(i + 1, j).cloned(),
if j > 0 {
self.collision_tiles.get(i + 1, j - 1).cloned()
} else {
None
},
if j > 0 {
self.collision_tiles.get(i, j - 1).cloned()
} else {
None
},
]
}
/// Returns the graphic tile corresponding to the collision tiles.
pub fn graphic_tile(&self, i: usize, j: usize) -> GraphicTile {
if self.collision_tiles[(i, j)].is_full() {
GraphicTile::from_neighbour_options(&self.neighbours(i, j))
} else {
GraphicTile(None)
}
}
/// Returns a tile of the map.
pub fn collision_tile(&self, i: usize, j: usize) -> Option<CollisionTile> {
self.collision_tiles.get(i, j).cloned()
}
/// Changes a tile of the map.
pub fn set_tile(&mut self, i: usize, j: usize, tile: CollisionTile) {
// Change the collision tile
self.collision_tiles[(i, j)] = tile;
// Refresh the current graphic tile and their neighbours
use std::cmp::max;
for i in max(i, 1) - 1..=(i + 1) {
for j in max(j, 1) - 1..=(j + 1) {
let new_tile = self.graphic_tile(i, j);
if let Some(tile) = self.graphic_tiles.get_mut(i, j) {
*tile = new_tile;
}
}
}
}
/// Finds a possible entrance.
pub fn find_entrance(tiles: &Matrix<CollisionTile>) -> (usize, usize) {
(tiles.rows() - 5, 1)
}
/// Returns the entrance of the map.
pub fn entrance(&self) -> (usize, usize) {
self.entrance
}
/// Returns an iterator to the positioned tiles.
pub fn at(&self, row: usize, col: usize) -> PositionedTile {
PositionedTile {
collision: self.collision_tiles[(row, col)],
graphic: self.graphic_tiles[(row, col)],
position: (col as f32 * SPRITE_SIZE_F32, row as f32 * SPRITE_SIZE_F32),
}
}
/// Returns the number of rows of the map.
pub fn rows(&self) -> usize {
self.collision_tiles.rows()
}
/// Returns the number of columns of the map.
pub fn cols(&self) -> usize {
self.collision_tiles.cols()
}
/// Checks whether the bounding box collides with elements of the map.
///
/// Returns the new correct position.
pub fn collides_bbox(
&self,
old: FloatRect,
new: FloatRect,
) -> Option<(CollisionAxis, Vector2<f32>, Damage)> {
let mut damage = Damage::None;
let cols = self.collision_tiles.cols() - 1;
let rows = self.collision_tiles.rows() - 1;
let min_col = clamp(new.left / SPRITE_SIZE_F32, 0.0, cols as f32) as usize;
let min_row = clamp(new.top / SPRITE_SIZE_F32, 0.0, rows as f32) as usize;
let max_col = clamp((new.left + new.width) / SPRITE_SIZE_F32, 0.0, cols as f32) as usize;
let max_row = clamp((new.top + new.height) / SPRITE_SIZE_F32, 0.0, rows as f32) as usize;
let mut collision_x = false;
let mut collision_y = false;
let mut new = new;
for col in min_col..=max_col {
for row in min_row..=max_row {
let tile_left = col as f32 * SPRITE_SIZE_F32;
let tile_top = row as f32 * SPRITE_SIZE_F32;
let tile = FloatRect::new(tile_left, tile_top, SPRITE_SIZE_F32, SPRITE_SIZE_F32);
if !overlap(new, tile) {
continue;
}
// Collisions between feet and ground
if self.collision_tiles[(row, col)].from_top
&& old.top + old.height <= tile_top
&& new.top + new.height >= tile_top
{
collision_y = true;
new.top = tile_top - new.height;
}
if !overlap(new, tile) {
continue;
}
// Collisions between right and right wall
if self.collision_tiles[(row, col)].from_left
&& old.left + old.width <= tile_left
&& new.left + new.width >= tile_left
{
collision_x = true;
new.left = tile_left - new.width;
}
if !overlap(new, tile) {
continue;
}
// Collisions between left and left wall
if self.collision_tiles[(row, col)].from_right
&& old.left >= tile_left + SPRITE_SIZE_F32
&& new.left <= tile_left + SPRITE_SIZE_F32
{
collision_x = true;
new.left = tile_left + SPRITE_SIZE_F32;
}
if !overlap(new, tile) {
continue;
}
// Collisions between head and roof
if self.collision_tiles[(row, col)].from_bottom
&& old.top >= tile_top + SPRITE_SIZE_F32
&& new.top <= tile_top + SPRITE_SIZE_F32
{
collision_y = true;
new.top = tile_top + SPRITE_SIZE_F32;
}
}
}
// Collision between the player and left border of the level
if new.left < 0.0 {
new.left = 0.0;
collision_x = true;
}
// Collision between the player and right border of the level
if new.left > cols as f32 * SPRITE_SIZE_F32 {
new.left = cols as f32 * SPRITE_SIZE_F32;
collision_x = true;
}
// Collision between the player and the void
if new.top > self.collision_tiles.rows() as f32 * SPRITE_SIZE_F32 {
new.top = self.collision_tiles.rows() as f32 * SPRITE_SIZE_F32;
collision_y = true;
damage = Damage::Death;
}
let new_pos = Vector2::new(new.left, new.top);
match (collision_x, collision_y) {
(true, true) => Some((CollisionAxis::Both, new_pos, damage)),
(true, false) => Some((CollisionAxis::X, new_pos, damage)),
(false, true) => Some((CollisionAxis::Y, new_pos, damage)),
(false, false) => None,
}
}
}
/// Checks if two boxes overlap.
pub fn overlap(box1: FloatRect, box2: FloatRect) -> bool {
box2.left < box1.left + box1.width
&& box2.left + box2.width > box1.left
&& box2.top < box1.top + box1.height
&& box2.top + box2.height > box1.top
}