CHUNK LOADING KINDA WORKS

This commit is contained in:
lukas0008 committed 2024-08-12 20:22:59 +02:00
1 parent b4abc6b297
commit a991ce214b
19 files changed
+273205 -264

No files matched your search

+9 -3
View File
@@ -4,8 +4,14 @@ version.workspace = true
edition.workspace = true
[dependencies]
pumpkin-protocol = { path = "../pumpkin-protocol"}
fastanvil = "0.31"
# fastanvil = "0.31"
fastnbt = { git = "https://github.com/owengage/fastnbt.git" }
fastsnbt = "0.2"
tokio.workspace = true
tokio.workspace = true
itertools = "0.13.0"
thiserror = "1.0.63"
futures = "0.3.30"
flate2 = "1.0.31"
serde = { version = "1.0.205", features = ["derive"] }
lazy_static = "1.5.0"
serde_json = "1.0.122"
File diff suppressed because it is too large. Load diff
+58
View File
@@ -0,0 +1,58 @@
use std::collections::HashMap;
use lazy_static::lazy_static;
use crate::world::WorldError;
const BLOCKS_JSON: &'static str = include_str!("../blocks.json");
#[derive(serde::Deserialize, Debug, Clone, PartialEq, Eq)]
struct BlockDefinition {
#[serde(rename = "type")]
kind: String,
block_set_type: Option<String>,
}
#[derive(serde::Deserialize, Debug, Clone, PartialEq, Eq)]
struct BlockState {
default: Option<bool>,
id: i64,
properties: Option<HashMap<String, String>>,
}
#[derive(serde::Deserialize, Debug, Clone, PartialEq, Eq)]
struct BlocksElement {
definition: BlockDefinition,
properties: Option<HashMap<String, Vec<String>>>,
states: Vec<BlockState>,
}
lazy_static! {
static ref BLOCKS: HashMap<String, BlocksElement> =
serde_json::from_str(BLOCKS_JSON).expect("Could not parse block.json registry.");
}
pub fn block_id_and_properties_to_block_state_id(
block_id: &str,
properties: Option<&HashMap<String, String>>,
) -> Result<i64, WorldError> {
let block = match BLOCKS.get(block_id) {
Some(block) => block,
None => return Err(WorldError::BlockStateIdNotFound),
};
let block_state_id = match properties {
None => Ok(block
.states
.iter()
.find(|state| state.default.unwrap_or(false))
.expect("Each block should have at least one default state")
.id),
Some(properties) => block
.states
.iter()
.find(|state| state.properties.as_ref() == Some(properties))
.map(|state| state.id)
.ok_or(WorldError::BlockStateIdNotFound),
};
block_state_id
}
+151 -16
View File
@@ -1,26 +1,161 @@
use fastnbt::nbt;
// use fastnbt::nbt;
pub const BLOCKS_AND_BIOMES: [u8; 2000] = [0x80; 2000];
pub const SKY_LIGHT_ARRAYS: [FixedArray<u8, 2048>; 26] = [FixedArray([0xff; 2048]); 26];
// pub const BLOCKS_AND_BIOMES: [u8; 2000] = [0x80; 2000];
// pub const SKY_LIGHT_ARRAYS: [FixedArray<u8, 2048>; 26] = [FixedArray([0xff; 2048]); 26];
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[repr(transparent)]
pub struct FixedArray<T, const N: usize>(pub [T; N]);
// #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
// #[repr(transparent)]
// pub struct FixedArray<T, const N: usize>(pub [T; N]);
pub struct TestChunk {
pub heightmap: Vec<u8>,
// pub struct TestChunk {
// pub heightmap: Vec<u8>,
// }
// impl Default for TestChunk {
// fn default() -> Self {
// Self::new()
// }
// }
// impl TestChunk {
// pub fn new() -> Self {
// let bytes = fastnbt::to_bytes(&nbt!({"MOTION_BLOCKING": [L; 123, 256]})).unwrap();
// Self { heightmap: bytes }
// }
// }
use std::{collections::HashMap, io::Write};
use fastnbt::LongArray;
use itertools::Itertools;
use crate::{world::WorldError, WORLD_HEIGHT};
pub struct ChunkData {
pub blocks: Box<[i64; 16 * 16 * WORLD_HEIGHT]>,
pub position: (i32, i32),
pub heightmaps: ChunkHeightmaps,
}
impl Default for TestChunk {
fn default() -> Self {
Self::new()
}
#[derive(serde::Deserialize, Debug, Clone)]
#[serde(rename_all = "PascalCase")]
struct PaletteEntry {
name: String,
properties: Option<HashMap<String, String>>,
}
impl TestChunk {
pub fn new() -> Self {
let bytes = fastnbt::to_bytes(&nbt!({"MOTION_BLOCKING": [L; 123, 256]})).unwrap();
#[derive(serde::Deserialize, Debug, Clone)]
struct ChunkSectionBlockStates {
data: Option<LongArray>, // TODO: see if you can use u32 here
palette: Vec<PaletteEntry>,
}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub struct ChunkHeightmaps {
motion_blocking: LongArray,
world_surface: LongArray,
}
#[derive(serde::Deserialize, Debug)]
struct ChunkSection {
#[serde(rename = "Y")]
y: i32,
block_states: Option<ChunkSectionBlockStates>,
}
#[derive(serde::Deserialize, Debug)]
struct ChunkNbt {
#[serde(rename = "DataVersion")]
data_version: usize,
sections: Vec<ChunkSection>,
#[serde(rename = "Heightmaps")]
heightmaps: ChunkHeightmaps,
}
impl ChunkData {
pub fn from_bytes(chunk_data: Vec<u8>, at: (i32, i32)) -> 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())),
};
// this needs to be boxed, otherwise it will cause a stack-overflow
let mut blocks = Box::new([0; 16 * 16 * WORLD_HEIGHT]);
for (k, section) in chunk_data.sections.into_iter().enumerate() {
let block_states = match section.block_states {
Some(states) => states,
None => continue, // this should instead fill all blocks with the only element of the palette
};
let palette = block_states
.palette
.iter()
.map(|entry| {
crate::block_registry::block_id_and_properties_to_block_state_id(
&entry.name,
entry.properties.as_ref(),
)
})
.collect::<Result<Vec<_>, _>>()?;
let block_data = match block_states.data {
None => continue,
Some(d) => d,
}
.into_inner();
let block_size = {
let size = 64 - (palette.len() - 1).leading_zeros();
if size >= 4 {
size
} else {
4
}
};
let mask = (1 << block_size) - 1;
println!("{block_size} {:#08b}", mask);
println!(
"{} {}",
block_size,
palette.iter().map(|v| v.to_string()).join(",")
);
let mut blocks_left = 16 * 16 * 16;
'block_loop: for (j, block) in block_data.iter().enumerate() {
for i in 0..64 / block_size {
if blocks_left <= 0 {
break 'block_loop;
}
let index = (block >> (i * block_size)) & mask;
let block = palette[index as usize];
blocks[k * 16 * 16 * 16 + j * ((64 / block_size) as usize) + i as usize] =
block;
blocks_left -= 1;
}
}
}
// std::fs::File::create_new("../mafaile.txt")
// .unwrap()
// .write_all(
// blocks
// .iter()
// .map(|v| v.to_string())
// .collect::<Vec<_>>()
// .join(",")
// .as_bytes(),
// );
Self { heightmap: bytes }
if at == (0, 0) {
println!(
"[{}]",
&blocks[0..10000].iter().map(|v| v.to_string()).join(",")
);
}
Ok(ChunkData {
blocks: blocks,
position: at,
heightmaps: chunk_data.heightmaps,
})
}
}
+21
View File
@@ -0,0 +1,21 @@
use std::path::PathBuf;
use crate::world::Level;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum Dimension {
OverWorld,
Nether,
End,
}
impl Dimension {
pub fn into_level(&self, mut base_directory: PathBuf) -> Level {
match self {
Dimension::OverWorld => {}
Dimension::Nether => base_directory.push("DIM-1"),
Dimension::End => base_directory.push("DIM1"),
}
Level::from_root_folder(base_directory)
}
}
+5 -25
View File
@@ -1,26 +1,6 @@
use std::{fs::File, path::Path};
use fastanvil::Region;
pub mod chunk;
pub struct World {
pub region: Region<File>,
}
impl World {
pub fn load<P: AsRef<Path>>(path: P) -> Self {
let file = std::fs::File::open(path).unwrap();
let region = Region::from_stream(file).unwrap();
Self { region }
}
/* pub fn load_chunk(&mut self, x: usize, y: usize) -> Chunk {
let data = self.region.read_chunk(x, y).unwrap().unwrap();
let complete_chunk = complete::Chunk::from_bytes(&data).unwrap();
}
*/
}
pub mod dimension;
pub const WORLD_HEIGHT: usize = 384;
pub const WORLD_Y_START_AT: i32 = -64; // TODO: make sure where it actually starts at (i think its at -64 but not sure)
mod world;
mod block_registry;
+245
View File
@@ -0,0 +1,245 @@
use std::{collections::VecDeque, future, io::Read, path::PathBuf, sync::Arc};
use flate2::bufread::ZlibDecoder;
use itertools::Itertools;
use thiserror::Error;
use tokio::{
fs::File,
io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt},
sync::Mutex,
};
use crate::{chunk::ChunkData, dimension::Dimension};
pub struct Level {
root_folder: PathBuf,
}
#[derive(Error, Debug)]
pub enum WorldError {
// using ErrorKind instead of Error, beacuse the function read_chunks and read_region_chunks is designed to return an error on a per-chunk basis, while std::io::Error does not implement Copy or Clone
#[error("Io error: {0}")]
IoError(std::io::ErrorKind),
#[error("Region not found")]
RegionNotFound,
#[error("Region is invalid")]
RegionIsInvalid,
#[error("Chunk not found")]
ChunkNotFound,
#[error("Compression scheme not recognised")]
UnknownCompression,
#[error("Error while working with zlib compression: {0}")]
ZlibError(std::io::Error),
#[error("Error deserializing chunk: {0}")]
ErrorDeserializingChunk(String),
#[error("The requested block state id does not exist")]
BlockStateIdNotFound,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Compression {
Gzip,
Zlib,
None,
LZ4,
}
impl Level {
pub fn from_root_folder(root_folder: PathBuf) -> Self {
Level { root_folder }
}
/// Read one chunk in the world
///
/// Do not use this function if reading many chunks is required, since in case those two chunks which are read seperately using `.read_chunk` are in the same region file, it will need to be opened and closed separately for both of them, leading to a performance loss.
pub async fn read_chunk(&self, chunk: (i32, i32)) -> Result<ChunkData, WorldError> {
self.read_chunks(vec![chunk])
.await
.pop()
.expect("Read chunks must return a chunk")
.1
}
/// Read many chunks in a world
///
/// Note: The order of the output chunks will almost never be in the same order as the order of input chunks
pub async fn read_chunks(
&self,
chunks: Vec<(i32, i32)>,
) -> Vec<((i32, i32), Result<ChunkData, WorldError>)> {
futures::future::join_all(
chunks
.into_iter()
// split chunks into their corresponding region files to be able to read all of them at once, instead of reopening the file multiple times
.chunk_by(|chunk| {
(
((chunk.0 as f32) / 32.0).floor() as i32,
((chunk.1 as f32) / 32.0).floor() as i32,
)
})
.into_iter()
.map(|(region, chunk_vec)| {
let mut path = self.root_folder.clone();
path.push("region");
path.push(format!("r.{}.{}.mca", region.0, region.1));
self.read_region_chunks(path, chunk_vec.collect_vec())
}),
)
.await
.into_iter()
.flatten()
.collect_vec()
}
async fn read_region_chunks(
&self,
region_file: PathBuf,
chunks: Vec<(i32, i32)>,
) -> Vec<((i32, i32), Result<ChunkData, WorldError>)> {
// dbg!(at);
println!(
"Getting chunks {:?}, from region file {}",
&chunks,
region_file.to_str().unwrap_or("")
);
// return different error when file is not found (because that means that the chunks have just not been generated yet)
let mut region_file = match File::open(region_file).await {
Ok(f) => f,
Err(err) => match err.kind() {
std::io::ErrorKind::NotFound => {
return chunks
.into_iter()
.map(|c| (c, Err(WorldError::RegionNotFound)))
.collect_vec()
}
_ => {
return chunks
.into_iter()
.map(|c| (c, Err(WorldError::IoError(err.kind()))))
.collect_vec()
}
},
};
let mut location_table: [u8; 4096] = [0; 4096];
let mut timestamp_table: [u8; 4096] = [0; 4096];
// fill the location and timestamp tables
{
match region_file.read_exact(&mut location_table).await {
Ok(_) => {}
Err(err) => {
return chunks
.into_iter()
.map(|c| (c, Err(WorldError::IoError(err.kind()))))
.collect_vec()
}
}
match region_file.read_exact(&mut timestamp_table).await {
Ok(_) => {}
Err(err) => {
return chunks
.into_iter()
.map(|c| (c, Err(WorldError::IoError(err.kind()))))
.collect_vec()
}
}
}
// println!("Location table: {:?}", &location_table);
// wrap file with arc mutex to allow for multithreading
let region_file = Arc::new(Mutex::new(region_file));
futures::future::join_all(chunks.into_iter().map(|(old_chunk_x, old_chunk_z)| {
let region_file = region_file.clone();
let modulus = |a: i32, b: i32| ((a % b) + b) % b;
let chunk_x = modulus(old_chunk_x, 32) as u32;
let chunk_z = modulus(old_chunk_z, 32) as u32;
async move {
let table_entry = (chunk_x + chunk_z * 32) * 4;
let mut offset = vec![0u8];
offset.extend_from_slice(
&location_table[table_entry as usize..table_entry as usize + 3],
);
let offset = u32::from_be_bytes(offset.try_into().unwrap()) as u64 * 4096;
let size = location_table[table_entry as usize + 3] as usize * 4096;
if offset == 0 && size == 0 {
return ((old_chunk_x, old_chunk_z), Err(WorldError::ChunkNotFound));
}
// Read the file using the offset and size
let mut file_buf = {
let mut region_file = region_file.lock().await;
let seek_result = region_file.seek(std::io::SeekFrom::Start(offset)).await;
if seek_result.is_err() {
return ((old_chunk_x, old_chunk_z), Err(WorldError::RegionIsInvalid));
}
let mut out = vec![0; size];
let read_result = region_file.read_exact(&mut out).await;
if read_result.is_err() {
return ((old_chunk_x, old_chunk_z), Err(WorldError::RegionIsInvalid));
}
out
};
// TODO: check checksum to make sure chunk is not corrupted
let header = file_buf.drain(0..5).collect_vec();
let compression = match header[4] {
1 => Compression::Gzip,
2 => Compression::Zlib,
3 => Compression::None,
4 => Compression::LZ4,
_ => return ((old_chunk_x, old_chunk_z), Err(WorldError::RegionIsInvalid)),
};
match compression {
Compression::Zlib => {}
_ => panic!(), // TODO: support other compression types
}
let size = u32::from_be_bytes(header[0..4].try_into().unwrap());
let chunk_data = file_buf.drain(0..size as usize).collect_vec();
let mut z = ZlibDecoder::new(&chunk_data[..]);
let mut chunk_data = Vec::new();
match z.read_to_end(&mut chunk_data) {
Ok(_) => {}
Err(err) => {
return ((old_chunk_x, old_chunk_z), Err(WorldError::ZlibError(err)))
}
}
// TODO: remove
// File::create_new(format!("./test-{}.{}.nbt", old_chunk_x, old_chunk_z))
// .await
// .unwrap()
// .write_all(&chunk_data)
// .await
// .unwrap();
(
(old_chunk_x, old_chunk_z),
ChunkData::from_bytes(chunk_data, (old_chunk_x, old_chunk_z)),
)
}
}))
.await
.into_iter()
.collect_vec()
}
}
#[test]
fn wawa() {
tokio::runtime::Runtime::new().unwrap().block_on(async {
Dimension::OverWorld
.into_level(
"C:\\Users\\lukza\\Desktop\\code\\rust\\vanilla_mc_server\\world"
.parse()
.unwrap(),
)
.read_chunk((0, 0))
.await
.unwrap();
});
}
Binary file not shown.