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

528 lines
16 KiB
Rust
Raw Normal View History

2019-03-30 13:34:09 +01:00
use std::path::Path;
use std::fs::File;
use std::io::{BufWriter, BufReader};
use serde::{Serialize, Deserialize};
use bincode::{serialize, deserialize, serialize_into, deserialize_from};
2018-11-19 15:30:57 +01:00
use sfml::graphics::{FloatRect, IntRect};
2018-10-03 21:47:48 +02:00
use sfml::system::Vector2;
2019-03-30 13:34:09 +01:00
use crate::{Error, Result};
2019-03-30 09:33:33 +01:00
use crate::engine::math::{clamp, Matrix};
use crate::engine::renderer::Drawable;
use crate::engine::texture::Texture;
2019-03-30 14:32:04 +01:00
use crate::engine::character::Damage;
2018-10-03 21:47:48 +02:00
2018-10-06 12:10:18 +02:00
/// This enum represents if the collision happens on the X axis or the Y axis.
2018-10-06 18:41:30 +02:00
#[derive(Copy, Clone)]
2018-10-06 12:10:18 +02:00
pub enum CollisionAxis {
/// The X axis.
X,
/// The Y axis.
Y,
2018-10-06 18:41:30 +02:00
/// Both axis simultaneously
Both,
2018-10-06 12:10:18 +02:00
}
2018-10-06 18:41:30 +02:00
impl CollisionAxis {
/// Returns true if the collision occured on X axis.
2018-11-19 15:21:02 +01:00
pub fn is_x(self) -> bool {
match self {
2018-10-06 18:41:30 +02:00
CollisionAxis::Y => false,
_ => true,
}
}
/// Returns true if the collision occured on Y axis.
2018-11-19 15:21:02 +01:00
pub fn is_y(self) -> bool {
match self {
2018-10-06 18:41:30 +02:00
CollisionAxis::X => false,
_ => true,
}
}
}
2018-10-06 10:16:38 +02:00
/// This struct represents the different sides from which a collision can occur.
2019-03-30 13:34:09 +01:00
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
2018-10-06 10:16:38 +02:00
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,
2018-10-03 21:47:48 +02:00
}
2018-10-04 21:44:00 +02:00
impl CollisionTile {
2018-10-06 10:16:38 +02:00
/// 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,
2018-10-04 21:44:00 +02:00
}
}
}
/// This struct represents a renderable tile linking to its part in the tileset texture.
2019-03-30 13:34:09 +01:00
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
2018-10-04 21:44:00 +02:00
pub enum GraphicTile {
/// There is nothing to draw.
Hidden,
/// Top left corner of a solid tile.
TopLeft,
/// Top of a solid tile.
Top,
/// Top right corner of a solid tile.
TopRight,
/// Left of a solid tile.
Left,
/// Center of a solid tile.
Center,
/// Right of a solid tile.
Right,
/// Bottom left corner of a solid tile.
BottomLeft,
/// Bottom of a solid tile.
Bottom,
/// Bottom right corner of a solid tile.
BottomRight,
}
impl GraphicTile {
2019-03-30 12:53:29 +01:00
/// Returns a graphic tile from a collision tile.
///
/// This might be ugly for the moment.
pub fn from_collision_tile(collision: CollisionTile) -> GraphicTile {
if collision == CollisionTile::empty() {
GraphicTile::Hidden
} else {
GraphicTile::Center
}
}
2018-10-04 21:44:00 +02:00
/// Checks if a graphic tile has a top border.
2018-11-19 15:21:02 +01:00
pub fn is_top(self) -> bool {
match self {
2018-10-04 21:44:00 +02:00
GraphicTile::TopLeft | GraphicTile::Top | GraphicTile::TopRight => true,
_ => false,
2018-10-03 21:47:48 +02:00
}
}
2018-10-04 19:40:34 +02:00
2018-10-04 21:44:00 +02:00
/// Checks if a graphic tile has a left border.
2018-11-19 15:21:02 +01:00
pub fn is_left(self) -> bool {
match self {
2018-10-04 21:44:00 +02:00
GraphicTile::TopLeft | GraphicTile::Left | GraphicTile::BottomLeft => true,
_ => false,
}
}
/// Checks if a graphic tile has a right border.
2018-11-19 15:21:02 +01:00
pub fn is_right(self) -> bool {
match self {
2018-10-04 21:44:00 +02:00
GraphicTile::TopRight | GraphicTile::Right | GraphicTile::BottomRight => true,
_ => false,
}
}
/// Checks if a graphic tile has a bottom border.
2018-11-19 15:21:02 +01:00
pub fn is_bottom(self) -> bool {
match self {
2018-10-04 21:44:00 +02:00
GraphicTile::BottomLeft | GraphicTile::Bottom | GraphicTile::BottomRight => true,
_ => false,
}
}
/// Creates a vec containing all the non hidden graphic tiles.
pub fn all() -> Vec<GraphicTile> {
vec![
GraphicTile::TopLeft,
GraphicTile::Top,
GraphicTile::TopRight,
GraphicTile::Left,
GraphicTile::Center,
GraphicTile::Right,
GraphicTile::BottomLeft,
GraphicTile::Bottom,
GraphicTile::BottomRight,
]
}
/// Creates the correct graphic tile depending on the neighbours.
///
/// A none will be considered solid.
pub fn from_neighbour_options(
top: Option<CollisionTile>,
left: Option<CollisionTile>,
right: Option<CollisionTile>,
2018-11-19 15:30:57 +01:00
bottom: Option<CollisionTile>,
) -> GraphicTile {
2018-10-04 21:44:00 +02:00
GraphicTile::from_neighbours(
2018-11-19 15:21:02 +01:00
top.unwrap_or_else(CollisionTile::full),
left.unwrap_or_else(CollisionTile::full),
right.unwrap_or_else(CollisionTile::full),
bottom.unwrap_or_else(CollisionTile::full),
2018-10-04 21:44:00 +02:00
)
}
/// Creates the correct graphic tile depending on the neighbours.
pub fn from_neighbours(
top: CollisionTile,
left: CollisionTile,
right: CollisionTile,
2018-11-19 15:30:57 +01:00
bottom: CollisionTile,
) -> GraphicTile {
2018-10-04 21:44:00 +02:00
let mut all = GraphicTile::all()
.into_iter()
.map(|x| (x, true))
.collect::<Vec<_>>();
for (ref mut tile, ref mut possible) in &mut all {
2018-10-06 10:16:38 +02:00
if tile.is_top() == (top == CollisionTile::full()) {
2018-10-04 21:44:00 +02:00
*possible = false;
}
2018-10-06 10:16:38 +02:00
if tile.is_left() == (left == CollisionTile::full()) {
2018-10-04 21:44:00 +02:00
*possible = false;
}
2018-10-06 10:16:38 +02:00
if tile.is_right() == (right == CollisionTile::full()) {
2018-10-04 21:44:00 +02:00
*possible = false;
}
2018-10-06 10:16:38 +02:00
if tile.is_bottom() == (bottom == CollisionTile::full()) {
2018-10-04 21:44:00 +02:00
*possible = false;
}
}
for (tile, possible) in all {
if possible {
return tile;
}
2018-10-04 19:40:34 +02:00
}
2018-10-04 21:44:00 +02:00
2019-03-30 10:13:29 +01:00
GraphicTile::Center
2018-10-04 21:44:00 +02:00
}
/// Returns the offset to the corresponding graphic tile in the texture.
2018-11-19 15:21:02 +01:00
pub fn offset(self) -> (i32, i32) {
let vertical = match self {
2018-10-04 21:44:00 +02:00
GraphicTile::TopLeft | GraphicTile::Top | GraphicTile::TopRight => 0,
GraphicTile::Left | GraphicTile::Center | GraphicTile::Right => 16,
GraphicTile::BottomLeft | GraphicTile::Bottom | GraphicTile::BottomRight => 32,
_ => 0,
};
2018-11-19 15:21:02 +01:00
let horizontal = match self {
2018-10-04 21:44:00 +02:00
GraphicTile::TopLeft | GraphicTile::Left | GraphicTile::BottomLeft => 0,
GraphicTile::Top | GraphicTile::Center | GraphicTile::Bottom => 16,
GraphicTile::TopRight | GraphicTile::Right | GraphicTile::BottomRight => 32,
_ => 0,
};
// (horizontal, vertical)
(vertical, horizontal)
2018-10-04 19:40:34 +02:00
}
2018-10-03 21:47:48 +02:00
}
/// A tile and its position.
pub struct PositionedTile {
2018-10-04 21:44:00 +02:00
/// The graphic representation of the positioned tile.
pub graphic: GraphicTile,
/// The collision representation of the positioned tile.
pub collision: CollisionTile,
2018-10-03 21:47:48 +02:00
/// 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 {
2018-10-04 21:44:00 +02:00
let offset = self.graphic.offset();
2018-10-03 21:47:48 +02:00
IntRect::new(offset.0, offset.1, 16, 16)
}
fn position(&self) -> Vector2<f32> {
self.position.into()
}
}
/// The map represents the tiles contained in a level.
2019-03-30 13:34:09 +01:00
#[derive(Serialize, Deserialize)]
2018-10-03 21:47:48 +02:00
pub struct Map {
2018-10-06 21:28:26 +02:00
/// The entrace point of the character in the map.
entrance: (usize, usize),
2018-10-03 21:47:48 +02:00
/// The tiles contained in the level.
2018-10-04 21:44:00 +02:00
tiles: Matrix<(CollisionTile, GraphicTile)>,
2018-10-03 21:47:48 +02:00
}
impl Map {
/// Creates a map full of nothing, with a ground at the bottom.
pub fn new(rows: usize, cols: usize) -> Map {
2018-10-06 10:16:38 +02:00
let mut tiles = Matrix::from_size(rows, cols, CollisionTile::empty());
2018-10-03 21:47:48 +02:00
let rows = tiles.rows();
2018-11-19 15:30:57 +01:00
for i in 0..tiles.cols() {
2018-10-06 10:16:38 +02:00
tiles[(rows - 1, i)] = CollisionTile::full();
2018-10-03 21:47:48 +02:00
}
2018-10-04 21:44:00 +02:00
Map::from_collision_tiles(tiles)
2018-10-03 21:47:48 +02:00
}
2019-03-30 13:34:09 +01:00
/// Encodes the map into a binary format.
pub fn encode(&self) -> Result<Vec<u8>> {
serialize(&self).map_err(Error::Encoding)
}
/// Decodes a map from bytes.
pub fn decode(content: &[u8]) -> Result<Map> {
deserialize(content).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).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_err(Error::Decoding)?)
}
2018-10-04 21:44:00 +02:00
/// Creates a map from its tiles.
pub fn from_collision_tiles(tiles: Matrix<CollisionTile>) -> Map {
let rows = tiles.rows();
let cols = tiles.cols();
2018-11-19 15:30:57 +01:00
let mut matrix =
Matrix::from_size(rows, cols, (CollisionTile::empty(), GraphicTile::Hidden));
2018-10-04 21:44:00 +02:00
2018-11-19 15:30:57 +01:00
for i in 0..rows {
for j in 0..cols {
2018-10-06 10:16:38 +02:00
let graphic = if tiles[(i, j)] == CollisionTile::full() {
2018-10-04 21:44:00 +02:00
// TODO This is uggly
// If there is an overflow, we should give None instead
let (i, j) = (i as isize, j as isize);
GraphicTile::from_neighbour_options(
2018-11-19 15:30:57 +01:00
tiles.get(((i) as usize, (j - 1) as usize)).cloned(),
tiles.get(((i - 1) as usize, (j) as usize)).cloned(),
tiles.get(((i + 1) as usize, (j) as usize)).cloned(),
tiles.get(((i) as usize, (j + 1) as usize)).cloned(),
2018-10-04 21:44:00 +02:00
)
} else {
GraphicTile::Hidden
};
matrix[(i, j)] = (tiles[(i, j)], graphic);
2018-10-04 19:40:34 +02:00
}
}
2018-10-04 21:44:00 +02:00
Map {
2018-10-06 21:28:26 +02:00
entrance: Map::find_entrance(&matrix),
2018-10-04 21:44:00 +02:00
tiles: matrix,
}
2018-10-04 19:40:34 +02:00
}
2019-03-30 12:53:29 +01:00
/// Returns a tile of the map.
2019-03-30 13:34:09 +01:00
pub fn tile(&self, i: usize, j: usize) -> Option<CollisionTile> {
self.tiles.get((i, j)).map(|x| x.0)
2019-03-30 12:53:29 +01:00
}
/// Changes a tile of the map.
pub fn set_tile(&mut self, i: usize, j: usize, tile: CollisionTile) {
self.tiles[(i, j)] = (tile, GraphicTile::from_collision_tile(tile));
}
2018-10-06 21:28:26 +02:00
/// Finds a possible entrance.
pub fn find_entrance(tiles: &Matrix<(CollisionTile, GraphicTile)>) -> (usize, usize) {
(tiles.rows() - 5, 1)
}
/// Returns the entrance of the map.
pub fn entrance(&self) -> (usize, usize) {
self.entrance
}
2018-10-03 21:47:48 +02:00
/// Returns an iterator to the positioned tiles.
pub fn at(&self, row: usize, col: usize) -> PositionedTile {
PositionedTile {
2018-10-04 21:44:00 +02:00
collision: self.tiles[(row, col)].0,
graphic: self.tiles[(row, col)].1,
2018-10-03 21:47:48 +02:00
position: (col as f32 * 16.0, row as f32 * 16.0),
}
}
/// Returns the number of rows of the map.
pub fn rows(&self) -> usize {
self.tiles.rows()
}
/// Returns the number of columns of the map.
pub fn cols(&self) -> usize {
self.tiles.cols()
}
2018-10-06 18:41:30 +02:00
/// Checks whether the bounding box collides with elements of the map.
2018-10-03 21:47:48 +02:00
///
2018-10-06 18:41:30 +02:00
/// Returns the new correct position.
2018-11-19 15:30:57 +01:00
pub fn collides_bbox(
&self,
old: FloatRect,
new: FloatRect,
2019-03-30 14:32:04 +01:00
) -> Option<(CollisionAxis, Vector2<f32>, Damage)> {
let mut damage = Damage::None;
2018-10-06 18:41:30 +02:00
let cols = self.tiles.cols() - 1;
let rows = self.tiles.rows() - 1;
2018-10-06 14:13:31 +02:00
2018-10-06 18:41:30 +02:00
let min_col = clamp(new.left / 16.0, 0.0, cols as f32) as usize;
let min_row = clamp(new.top / 16.0, 0.0, rows as f32) as usize;
2018-10-06 14:13:31 +02:00
2018-10-06 18:41:30 +02:00
let max_col = clamp((new.left + new.width) / 16.0, 0.0, cols as f32) as usize;
let max_row = clamp((new.top + new.height) / 16.0, 0.0, rows as f32) as usize;
2018-10-06 14:13:31 +02:00
2018-10-06 18:41:30 +02:00
let mut collision_x = false;
let mut collision_y = false;
let mut new = new;
2018-10-06 14:13:31 +02:00
2018-11-19 15:30:57 +01:00
for col in min_col..=max_col {
for row in min_row..=max_row {
2018-10-06 18:41:30 +02:00
let tile_left = col as f32 * 16.0;
let tile_top = row as f32 * 16.0;
2018-10-06 14:13:31 +02:00
2018-10-06 18:41:30 +02:00
let tile = FloatRect::new(tile_left, tile_top, 16.0, 16.0);
2018-10-06 14:13:31 +02:00
2018-11-19 15:30:57 +01:00
if !overlap(new, tile) {
2018-10-06 18:41:30 +02:00
continue;
}
2018-10-06 14:13:31 +02:00
2018-10-06 18:41:30 +02:00
// Collisions between feet and ground
2018-11-19 15:30:57 +01:00
if self.tiles[(row, col)].0.from_top
&& old.top + old.height <= tile_top
&& new.top + new.height >= tile_top
{
collision_y = true;
new.top = tile_top - new.height;
2018-10-06 18:41:30 +02:00
}
2018-10-06 14:13:31 +02:00
2018-11-19 15:30:57 +01:00
if !overlap(new, tile) {
2018-10-06 18:41:30 +02:00
continue;
}
2018-10-06 14:13:31 +02:00
2018-10-06 18:41:30 +02:00
// Collisions between right and right wall
2018-11-19 15:30:57 +01:00
if self.tiles[(row, col)].0.from_left
&& old.left + old.width <= tile_left
&& new.left + new.width >= tile_left
{
2018-11-19 15:21:02 +01:00
collision_x = true;
new.left = tile_left - new.width;
2018-10-06 18:41:30 +02:00
}
2018-10-06 14:13:31 +02:00
2018-11-19 15:30:57 +01:00
if !overlap(new, tile) {
2018-10-06 18:41:30 +02:00
continue;
}
2018-10-06 14:13:31 +02:00
2018-10-06 18:41:30 +02:00
// Collisions between left and left wall
2018-11-19 15:30:57 +01:00
if self.tiles[(row, col)].0.from_right
&& old.left >= tile_left + 16.0
&& new.left <= tile_left + 16.0
{
2018-11-19 15:21:02 +01:00
collision_x = true;
new.left = tile_left + 16.0;
2018-10-06 18:41:30 +02:00
}
2018-10-03 21:47:48 +02:00
2018-11-19 15:30:57 +01:00
if !overlap(new, tile) {
2018-10-06 18:41:30 +02:00
continue;
}
2018-10-04 21:44:00 +02:00
2018-10-06 18:41:30 +02:00
// Collisions between head and roof
2018-11-19 15:30:57 +01:00
if self.tiles[(row, col)].0.from_bottom
&& old.top >= tile_top + 16.0
&& new.top <= tile_top + 16.0
{
2018-11-19 15:21:02 +01:00
collision_y = true;
new.top = tile_top + 16.0;
2018-10-04 21:44:00 +02:00
}
2018-10-03 21:47:48 +02:00
}
}
2019-03-30 14:32:04 +01:00
// 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 * 16.0 {
new.left = cols as f32 * 16.0;
collision_x = true;
}
// Collision between the player and the void
if new.top > self.tiles.rows() as f32 * 16.0 {
new.top = self.tiles.rows() as f32 * 16.0;
collision_y = true;
damage = Damage::Death;
}
2018-10-06 18:41:30 +02:00
let new_pos = Vector2::new(new.left, new.top);
match (collision_x, collision_y) {
2019-03-30 14:32:04 +01:00
(true, true) => Some((CollisionAxis::Both, new_pos, damage)),
(true, false) => Some((CollisionAxis::X, new_pos, damage)),
(false, true) => Some((CollisionAxis::Y, new_pos, damage)),
2018-10-06 18:41:30 +02:00
(false, false) => None,
}
2018-10-03 21:47:48 +02:00
}
2018-10-06 18:41:30 +02:00
}
2018-10-06 14:13:31 +02:00
2018-10-06 18:41:30 +02:00
/// Checks if two boxes overlap.
pub fn overlap(box1: FloatRect, box2: FloatRect) -> bool {
2018-11-19 15:30:57 +01:00
box2.left < box1.left + box1.width
&& box2.left + box2.width > box1.left
&& box2.top < box1.top + box1.height
&& box2.top + box2.height > box1.top
2018-10-03 21:47:48 +02:00
}