Added abstraction for coordinates.
These ensure that there aren't any out of bound values and make the code significantly more readable
This commit is contained in:
1 parent
3b438872a8
commit
be98a730b0
7 files changed
+172
-40
No files matched your search
+14
-15
@@ -2,11 +2,15 @@ use std::collections::HashMap;
|
||||
|
||||
use fastnbt::LongArray;
|
||||
|
||||
use crate::{level::WorldError, vector3::Vector3, WORLD_HEIGHT, WORLD_Y_START_AT};
|
||||
use crate::{
|
||||
coordinates::{ChunkCoordinates, ChunkRelativeBlockCoordinates},
|
||||
level::WorldError,
|
||||
WORLD_HEIGHT,
|
||||
};
|
||||
|
||||
pub struct ChunkData {
|
||||
pub blocks: Box<[i32; 16 * 16 * WORLD_HEIGHT]>,
|
||||
pub position: (i32, i32),
|
||||
pub position: ChunkCoordinates,
|
||||
pub heightmaps: ChunkHeightmaps,
|
||||
}
|
||||
|
||||
@@ -49,7 +53,7 @@ struct ChunkNbt {
|
||||
}
|
||||
|
||||
impl ChunkData {
|
||||
pub fn from_bytes(chunk_data: Vec<u8>, at: (i32, i32)) -> Result<Self, WorldError> {
|
||||
pub fn from_bytes(chunk_data: Vec<u8>, at: ChunkCoordinates) -> Result<Self, WorldError> {
|
||||
let chunk_data = match fastnbt::from_bytes::<ChunkNbt>(chunk_data.as_slice()) {
|
||||
Ok(v) => v,
|
||||
Err(err) => return Err(WorldError::ErrorDeserializingChunk(err.to_string())),
|
||||
@@ -111,19 +115,14 @@ impl ChunkData {
|
||||
})
|
||||
}
|
||||
/// Sets the given block in the chunk, returning the old block
|
||||
pub fn set_block(&mut self, at: Vector3<i32>, block_id: i32) -> Result<i32, WorldError> {
|
||||
let x = at.x - self.position.0 * 16;
|
||||
let z = at.z - self.position.1 * 16;
|
||||
let y = at.y - WORLD_Y_START_AT;
|
||||
if !(0..16).contains(&x)
|
||||
|| !(0..16).contains(&z)
|
||||
|| !(0..(WORLD_HEIGHT as i32)).contains(&y)
|
||||
{
|
||||
return Err(WorldError::BlockOutsideChunk);
|
||||
}
|
||||
|
||||
pub fn set_block(
|
||||
&mut self,
|
||||
at: ChunkRelativeBlockCoordinates,
|
||||
block_id: i32,
|
||||
) -> Result<i32, WorldError> {
|
||||
Ok(std::mem::replace(
|
||||
&mut self.blocks[(y * 16 * 16 + z * 16 + x) as usize],
|
||||
&mut self.blocks
|
||||
[(at.y.get_absolute() * 16 * 16 + *at.z as u16 * 16 + *at.x as u16) as usize],
|
||||
block_id,
|
||||
))
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user