From 5186b360a6c84e1621be08c08248ad1070fc96c3 Mon Sep 17 00:00:00 2001 From: caelunshun Date: Mon, 30 Sep 2019 19:02:52 -0600 Subject: [PATCH 01/20] Implement sector allocator --- Cargo.lock | 7 +- core/Cargo.toml | 3 +- core/src/save/region.rs | 195 ++++++++++++++++++++++++++++++++++++---- 3 files changed, 183 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 69dd2b37f..e81d03d6b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -153,7 +153,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "bitvec" -version = "0.15.1" +version = "0.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -555,6 +555,7 @@ name = "feather-core" version = "0.4.1" dependencies = [ "aes 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "bitvec 0.15.2 (registry+https://github.com/rust-lang/crates.io-index)", "byteorder 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)", "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)", "cfb8 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", @@ -623,7 +624,7 @@ version = "0.4.1" dependencies = [ "base64 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", "bitflags 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "bitvec 0.15.1 (registry+https://github.com/rust-lang/crates.io-index)", + "bitvec 0.15.2 (registry+https://github.com/rust-lang/crates.io-index)", "bumpalo 2.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)", "criterion 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2793,7 +2794,7 @@ dependencies = [ "checksum backtrace-sys 0.1.31 (registry+https://github.com/rust-lang/crates.io-index)" = "82a830b4ef2d1124a711c71d263c5abdc710ef8e907bd508c88be475cebc422b" "checksum base64 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0b25d992356d2eb0ed82172f5248873db5560c4721f564b13cb5193bda5e668e" "checksum bitflags 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3d155346769a6855b86399e9bc3814ab343cd3d62c7e985113d46a0ec3c281fd" -"checksum bitvec 0.15.1 (registry+https://github.com/rust-lang/crates.io-index)" = "461d7d0e952343f575470daeb04d38aad19675b4f170e122c6b5dd618612c8a8" +"checksum bitvec 0.15.2 (registry+https://github.com/rust-lang/crates.io-index)" = "a993f74b4c99c1908d156b8d2e0fb6277736b0ecbd833982fd1241d39b2766a6" "checksum block-cipher-trait 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "1c924d49bd09e7c06003acda26cd9742e796e34282ec6c1189404dee0c1f4774" "checksum bstr 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8d6c2c5b58ab920a4f5aeaaca34b4488074e8cc7596af94e6f8c6ff247c60245" "checksum bumpalo 2.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ad807f2fc2bf185eeb98ff3a901bd46dc5ad58163d0fa4577ba0d25674d71708" diff --git a/core/Cargo.toml b/core/Cargo.toml index dc75cbdc1..b22e262dc 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -31,4 +31,5 @@ hash32-derive = "0.1.0" strum = "0.15.0" strum_macros = "0.15.0" tokio = "=0.2.0-alpha.5" -failure = "0.1.5" \ No newline at end of file +failure = "0.1.5" +bitvec = "0.15.2" diff --git a/core/src/save/region.rs b/core/src/save/region.rs index a95b587ec..3b481b5d4 100644 --- a/core/src/save/region.rs +++ b/core/src/save/region.rs @@ -4,10 +4,10 @@ use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use std::fs::File; -use std::io; use std::io::prelude::*; use std::io::{Cursor, SeekFrom}; use std::path::PathBuf; +use std::{io, iter}; use byteorder::{BigEndian, ReadBytesExt}; use serde::Deserialize; @@ -17,6 +17,8 @@ use crate::world::block::*; use crate::world::chunk::{BitArray, Chunk, ChunkSection}; use crate::world::ChunkPosition; use crate::Biome; +use bitvec::bitvec; +use bitvec::vec::BitVec; /// The length and width of a region, in chunks. const REGION_SIZE: usize = 32; @@ -84,12 +86,23 @@ struct LevelProperties { props: HashMap, } +/// A block of sectors in a region file. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +struct SectorBlock { + /// Offset, in sectors, from the start of the file (beginning of the header.) + offset: u32, + /// Number of sectors in this block. Each sector is 4KiB. + count: u32, +} + /// A region file handle. pub struct RegionHandle { /// The region file. file: File, /// The region file's header, pre-loaded into memory. header: RegionHeader, + /// Sector allocator to allocate sectors where we can store chunks. + allocator: SectorAllocator, } impl RegionHandle { @@ -112,7 +125,7 @@ impl RegionHandle { // Get the offset of the chunk within the file // so that it can be read. - let offset = self.header.location_for_chunk(pos).offset; + let offset = self.header.location_for_chunk(pos).0.offset; // If the chunk doesn't exist, return early if !self.header.location_for_chunk(pos).exists() { @@ -183,6 +196,12 @@ impl RegionHandle { Ok((chunk, level.entities.to_vec())) } + + /// Saves the given chunk to this region file. The header will be updated + /// accordingly and saved as well. + pub fn save_chunk(&mut self, chunk: &Chunk) { + unimplemented!() + } } fn read_section_into_chunk(section: &LevelSection, chunk: &mut Chunk) -> Result<(), Error> { @@ -257,6 +276,90 @@ fn read_section_into_chunk(section: &LevelSection, chunk: &mut Chunk) -> Result< Ok(()) } +/// An allocator for sectors. +struct SectorAllocator { + /// Vector of bits, with a bit set for each sector which is in use. + /// + /// TODO: use a more efficient allocation model, such as a `LinkedList` + /// of free blocks. + used_sectors: BitVec, +} + +impl SectorAllocator { + /// Creates a `SectorAllocator` from the given file header + /// and total file size __in sectors.__ + pub fn new(header: &RegionHeader, file_size: u32) -> Self { + let mut used_sectors = bitvec![0; file_size as usize]; + + // Detect used sectors + for chunk_location in &header.locations { + if !chunk_location.exists() { + continue; + } + + let offset = chunk_location.0.offset; + let count = chunk_location.0.count; + (offset..offset + count).for_each(|sector| used_sectors.set(sector as usize, true)); + } + + // Allocate two sectors at start for header + used_sectors.set(0, true); + used_sectors.set(1, true); + + Self { used_sectors } + } + + /// Frees the given block from this allocator. + pub fn free(&mut self, block: SectorBlock) { + (block.offset..block.offset + block.count) + .for_each(|sector| self.used_sectors.set(sector as usize, false)); + } + + /// Allocates a block of sectors with the given + /// minimum size __in sectors__. + /// + /// The returned block may + /// stretch past the end of the file. + pub fn allocate(&mut self, min_size: u32) -> SectorBlock { + // TODO: fairly inefficient way to do this. + let mut start = 0; + let mut length = 0; + + for (index, is_used) in self.used_sectors.iter().enumerate() { + if is_used { + start = 0; + length = 0; + } else { + if start == 0 { + start = index; + } + length += 1; + + if length >= min_size { + let block = SectorBlock { + offset: start as u32, + count: length as u32, + }; + + (block.offset..block.offset + block.count) + .for_each(|sector| self.used_sectors.set(sector as usize, true)); + + return block; + } + } + } + + // No sector found: must allocate into end + self.used_sectors + .extend(iter::repeat(true).take(min_size as usize)); + + SectorBlock { + offset: self.used_sectors.len() as u32, + count: min_size, + } + } +} + /// An error which occurred during region file processing. #[derive(Debug)] pub enum Error { @@ -333,7 +436,15 @@ pub fn load_region(dir: &PathBuf, pos: RegionPosition) -> Result Result { for _ in 0..1024 { let val = file.read_u32::().map_err(Error::Io)?; let offset = val >> 8; - let sector_count = (val & 0b1111_1111) as u8; + let count = val & 0b1111_1111; - header.locations.push(ChunkLocation { - offset, - sector_count, - }); + header + .locations + .push(ChunkLocation(SectorBlock { offset, count })); } // The next 4 KiB contains timestamp data - one @@ -404,15 +514,7 @@ impl RegionHeader { /// Contains information about a chunk inside /// a region file. #[derive(Clone, Copy, Debug)] -struct ChunkLocation { - /// The offset of the chunk from the start of the file - /// in 4 KiB sectors such that a value of 2 corresponds - /// to byte 8192 in the file. - offset: u32, - /// The length of the data for the chunk, also - /// in 4 KiB sectors. This value is always rounded up. - sector_count: u8, -} +struct ChunkLocation(SectorBlock); impl ChunkLocation { /// Chunks in a region which have not been generated @@ -420,7 +522,7 @@ impl ChunkLocation { /// This function checks whether a chunk exists /// in a region file or not. pub fn exists(self) -> bool { - self.offset != 0 && self.sector_count != 0 + self.0.offset != 0 && self.0.count != 0 } } @@ -441,3 +543,60 @@ impl RegionPosition { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_sector_allocator() { + let header = RegionHeader { + locations: vec![ + ChunkLocation(SectorBlock { + offset: 0, + count: 0, + }), + ChunkLocation(SectorBlock { + offset: 6, + count: 5, + }), + ], + timestamps: vec![0; 2], + }; + + let mut alloc = SectorAllocator::new(&header, 1024); + + assert_eq!( + alloc.allocate(2), + SectorBlock { + offset: 2, + count: 2 + } + ); + assert_eq!( + alloc.allocate(2), + SectorBlock { + offset: 4, + count: 2 + } + ); + assert_eq!( + alloc.allocate(2), + SectorBlock { + offset: 11, + count: 2, + } + ); + alloc.free(SectorBlock { + offset: 2, + count: 2, + }); + assert_eq!( + alloc.allocate(2), + SectorBlock { + offset: 2, + count: 2 + } + ); + } +} From cfb006bb0af9a25211ca3a811b5e6f851b84221e Mon Sep 17 00:00:00 2001 From: caelunshun Date: Wed, 2 Oct 2019 18:34:21 -0600 Subject: [PATCH 02/20] Implement conversion of chunk data compound to `nbt::Blob` --- core/src/save/entity.rs | 71 ++++++++++ core/src/save/region/blob.rs | 146 +++++++++++++++++++++ core/src/save/{region.rs => region/mod.rs} | 2 + 3 files changed, 219 insertions(+) create mode 100644 core/src/save/region/blob.rs rename core/src/save/{region.rs => region/mod.rs} (99%) diff --git a/core/src/save/entity.rs b/core/src/save/entity.rs index 809ad0bf4..63312f4bc 100644 --- a/core/src/save/entity.rs +++ b/core/src/save/entity.rs @@ -1,4 +1,6 @@ use crate::Position; +use nbt::Value; +use std::collections::HashMap; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "id")] @@ -13,6 +15,20 @@ pub enum EntityData { Unknown, } +impl EntityData { + pub fn into_nbt_value(self) -> Value { + let mut map = HashMap::new(); + + match self { + EntityData::Item(data) => data.write_to_map(&mut map), + EntityData::Arrow(data) => data.write_to_map(&mut map), + EntityData::Unknown => panic!("Cannot write unknown entities"), + } + + Value::Compound(map) + } +} + /// Common entity tags. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BaseEntityData { @@ -24,6 +40,33 @@ pub struct BaseEntityData { pub velocity: Vec, } +impl BaseEntityData { + fn write_to_map(self, map: &mut HashMap) { + map.insert( + String::from("Pos"), + Value::List( + self.position + .into_iter() + .map(|x| Value::Double(x)) + .collect(), + ), + ); + map.insert( + String::from("Rotation"), + Value::List(self.rotation.into_iter().map(|x| Value::Float(x)).collect()), + ); + map.insert( + String::from("Motion"), + Value::List( + self.velocity + .into_iter() + .map(|x| Value::Double(x)) + .collect(), + ), + ); + } +} + impl BaseEntityData { /// Reads the position and rotation fields. If the fields are invalid, None is returned. pub fn read_position(self: &BaseEntityData) -> Option { @@ -74,6 +117,13 @@ pub struct ItemData { pub item: String, } +impl ItemData { + fn write_to_map(self, map: &mut HashMap) { + map.insert(String::from("Count"), Value::Byte(self.count as i8)); + map.insert(String::from("id"), Value::String(self.item)); + } +} + /// Data for an Item entity (`minecraft:item`). #[derive(Clone, Default, Serialize, Deserialize, Debug)] pub struct ItemEntityData { @@ -90,6 +140,19 @@ pub struct ItemEntityData { pub item: ItemData, } +impl ItemEntityData { + fn write_to_map(self, map: &mut HashMap) { + self.entity.write_to_map(map); + self.item.write_to_map(map); + + map.insert(String::from("Age"), Value::Short(self.age)); + map.insert( + String::from("PickupDelay"), + Value::Byte(self.pickup_delay as i8), + ); + } +} + /// Data for an Arrow entity (`minecraft:arrow`). #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct ArrowEntityData { @@ -105,6 +168,14 @@ pub struct ArrowEntityData { pub critical: u8, } +impl ArrowEntityData { + fn write_to_map(self, map: &mut HashMap) { + self.entity.write_to_map(map); + + map.insert(String::from("crit"), Value::Byte(self.critical as i8)); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/core/src/save/region/blob.rs b/core/src/save/region/blob.rs new file mode 100644 index 000000000..ac620c76a --- /dev/null +++ b/core/src/save/region/blob.rs @@ -0,0 +1,146 @@ +//! Conversion of `ChunkRoot` to `nbt::Blob`. +//! This is required due to https://github.com/PistonDevelopers/hematite_nbt/issues/27. + +use crate::region::ChunkLevel; +use crate::save::region::{ChunkRoot, LevelSection}; +use nbt::{Blob, Value}; +use std::collections::HashMap; + +fn chunk_root_to_blob(root: ChunkRoot) -> Blob { + let mut blob = Blob::new(); + blob.insert("DataVersion", root.data_version).unwrap(); + + blob.insert("Level", level_to_value(root.level)).unwrap(); + + blob +} + +fn level_to_value(level: ChunkLevel) -> Value { + let mut map = HashMap::new(); + + map.insert(String::from("xPos"), Value::Int(level.x_pos)); + map.insert(String::from("zPos"), Value::Int(level.z_pos)); + map.insert(String::from("LastUpdate"), Value::Long(0)); // TODO + map.insert(String::from("InhabitedTime"), Value::Long(0)); // TODO + map.insert(String::from("Biomes"), Value::IntArray(level.biomes)); + + let mut hmaps = HashMap::new(); + hmaps.insert( + String::from("MOTION_BLOCKING"), + Value::LongArray(vec![0; 32]), + ); // TODO + hmaps.insert( + String::from("MOTION_BLOCKING_NO_LEAVES"), + Value::LongArray(vec![0; 32]), + ); // TODO + hmaps.insert(String::from("OCEAN_FLOOR"), Value::LongArray(vec![0; 32])); // TODO + hmaps.insert( + String::from("OCEAN_FLOOR_WG"), + Value::LongArray(vec![0; 32]), + ); // TODO + hmaps.insert(String::from("WORLD_SURFACE"), Value::LongArray(vec![0; 32])); // TODO + hmaps.insert( + String::from("WORLD_SURFACE_WG"), + Value::LongArray(vec![0; 32]), + ); // TODO + map.insert(String::from("Heightmaps"), Value::Compound(hmaps)); + + let sections = level.sections.into_iter().map(section_to_value).collect(); + map.insert(String::from("Sections"), Value::List(sections)); + + map.insert(String::from("TileEntities"), Value::List(vec![])); // TODO + map.insert(String::from("TileTicks"), Value::List(vec![])); // TODO + map.insert(String::from("ToBeTicked"), Value::List(vec![])); // TODO + + // Entities + let mut entities = Vec::with_capacity(level.entities.len()); + level.entities.into_iter().for_each(|entity| { + entities.push(entity.into_nbt_value()); + }); + + map.insert(String::from("Entities"), Value::List(entities)); + + Value::Compound(map) +} + +fn section_to_value(section: LevelSection) -> Value { + let mut map = HashMap::new(); + + map.insert(String::from("Y"), Value::Byte(section.y)); + map.insert( + String::from("BlockLight"), + Value::ByteArray(section.block_light), + ); + map.insert( + String::from("SkyLight"), + Value::ByteArray(section.sky_light), + ); + map.insert( + String::from("BlockStates"), + Value::LongArray(section.states), + ); + + let mut entries = vec![]; + for entry in section.palette { + let mut map = HashMap::new(); + map.insert(String::from("Name"), Value::String(entry.name)); + + if let Some(props) = entry.props { + map.insert( + String::from("Properties"), + Value::List( + props + .props + .into_iter() + .map(|(x, y)| { + let mut map = HashMap::new(); + map.insert(x, Value::String(y)); + map + }) + .map(|map| Value::Compound(map)) + .collect(), + ), + ); + } + + entries.push(Value::Compound(map)) + } + + map.insert(String::from("Palette"), Value::List(entries)); + + Value::Compound(map) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::region::DATA_VERSION; + use std::io::Cursor; + + #[test] + fn test_to_blob_roundtrip() { + let root = ChunkRoot { + data_version: DATA_VERSION, + level: ChunkLevel { + x_pos: 0, + z_pos: 0, + sections: vec![LevelSection { + y: 0, + states: vec![0], + palette: vec![], + block_light: vec![0], + sky_light: vec![0], + }], + biomes: vec![10], + entities: vec![], + }, + }; + + let blob = chunk_root_to_blob(root); + + let mut buf = vec![]; + blob.to_writer(&mut buf).unwrap(); + + let _: ChunkRoot = nbt::from_reader(Cursor::new(&buf)).unwrap(); + } +} diff --git a/core/src/save/region.rs b/core/src/save/region/mod.rs similarity index 99% rename from core/src/save/region.rs rename to core/src/save/region/mod.rs index 3b481b5d4..9e805fd07 100644 --- a/core/src/save/region.rs +++ b/core/src/save/region/mod.rs @@ -20,6 +20,8 @@ use crate::Biome; use bitvec::bitvec; use bitvec::vec::BitVec; +mod blob; + /// The length and width of a region, in chunks. const REGION_SIZE: usize = 32; From c3f97c412f1b05dbecaaa16d44cb7acee73397d2 Mon Sep 17 00:00:00 2001 From: caelunshun Date: Wed, 2 Oct 2019 19:01:38 -0600 Subject: [PATCH 03/20] Initial implementation of RegionHandle::save_chunk (untested) --- core/src/save/entity.rs | 16 +--- core/src/save/region/blob.rs | 8 +- core/src/save/region/mod.rs | 172 ++++++++++++++++++++++++++++++++--- 3 files changed, 164 insertions(+), 32 deletions(-) diff --git a/core/src/save/entity.rs b/core/src/save/entity.rs index 63312f4bc..791721441 100644 --- a/core/src/save/entity.rs +++ b/core/src/save/entity.rs @@ -44,25 +44,15 @@ impl BaseEntityData { fn write_to_map(self, map: &mut HashMap) { map.insert( String::from("Pos"), - Value::List( - self.position - .into_iter() - .map(|x| Value::Double(x)) - .collect(), - ), + Value::List(self.position.into_iter().map(Value::Double).collect()), ); map.insert( String::from("Rotation"), - Value::List(self.rotation.into_iter().map(|x| Value::Float(x)).collect()), + Value::List(self.rotation.into_iter().map(Value::Float).collect()), ); map.insert( String::from("Motion"), - Value::List( - self.velocity - .into_iter() - .map(|x| Value::Double(x)) - .collect(), - ), + Value::List(self.velocity.into_iter().map(Value::Double).collect()), ); } } diff --git a/core/src/save/region/blob.rs b/core/src/save/region/blob.rs index ac620c76a..a64168f59 100644 --- a/core/src/save/region/blob.rs +++ b/core/src/save/region/blob.rs @@ -1,12 +1,12 @@ //! Conversion of `ChunkRoot` to `nbt::Blob`. //! This is required due to https://github.com/PistonDevelopers/hematite_nbt/issues/27. -use crate::region::ChunkLevel; -use crate::save::region::{ChunkRoot, LevelSection}; +use super::ChunkLevel; +use super::{ChunkRoot, LevelSection}; use nbt::{Blob, Value}; use std::collections::HashMap; -fn chunk_root_to_blob(root: ChunkRoot) -> Blob { +pub fn chunk_root_to_blob(root: ChunkRoot) -> Blob { let mut blob = Blob::new(); blob.insert("DataVersion", root.data_version).unwrap(); @@ -97,7 +97,7 @@ fn section_to_value(section: LevelSection) -> Value { map.insert(x, Value::String(y)); map }) - .map(|map| Value::Compound(map)) + .map(Value::Compound) .collect(), ), ); diff --git a/core/src/save/region/mod.rs b/core/src/save/region/mod.rs index 9e805fd07..b1311aa08 100644 --- a/core/src/save/region/mod.rs +++ b/core/src/save/region/mod.rs @@ -9,7 +9,7 @@ use std::io::{Cursor, SeekFrom}; use std::path::PathBuf; use std::{io, iter}; -use byteorder::{BigEndian, ReadBytesExt}; +use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use serde::Deserialize; use crate::save::entity::EntityData; @@ -29,9 +29,12 @@ const REGION_SIZE: usize = 32; /// to 1.13.2. const DATA_VERSION: i32 = 1631; +/// Length, in bytes, of a sector. +const SECTOR_BYTES: usize = 4096; + /// Represents the data for a chunk after the "Chunk [x, y]" tag. #[derive(Serialize, Deserialize, Debug)] -struct ChunkRoot { +pub struct ChunkRoot { #[serde(rename = "Level")] level: ChunkLevel, #[serde(rename = "DataVersion")] @@ -40,7 +43,7 @@ struct ChunkRoot { /// Represents the level data for a chunk. #[derive(Serialize, Deserialize, Debug)] -struct ChunkLevel { +pub struct ChunkLevel { // TODO heightmaps, etc. #[serde(rename = "xPos")] x_pos: i32, @@ -56,7 +59,7 @@ struct ChunkLevel { /// Represents a chunk section in a region file. #[derive(Serialize, Deserialize, Debug)] -struct LevelSection { +pub struct LevelSection { #[serde(rename = "Y")] y: i8, #[serde(rename = "BlockStates")] @@ -71,7 +74,7 @@ struct LevelSection { /// Represents a palette entry in a region file. #[derive(Serialize, Deserialize, Debug)] -struct LevelPaletteEntry { +pub struct LevelPaletteEntry { /// The identifier of the type of this block #[serde(rename = "Name")] name: String, @@ -82,7 +85,7 @@ struct LevelPaletteEntry { /// Represents the proprties for a palette entry. #[derive(Serialize, Deserialize, Debug)] -struct LevelProperties { +pub struct LevelProperties { /// Map containing a list of property names to values. #[serde(flatten)] props: HashMap, @@ -90,7 +93,7 @@ struct LevelProperties { /// A block of sectors in a region file. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -struct SectorBlock { +pub struct SectorBlock { /// Offset, in sectors, from the start of the file (beginning of the header.) offset: u32, /// Number of sectors in this block. Each sector is 4KiB. @@ -135,10 +138,10 @@ impl RegionHandle { } // Seek to the offset position. Note that since the offset in the header - // is in "sectors" of 4KiB each, the value needs to be multiplied by 4096 + // is in "sectors" of 4KiB each, the value needs to be multiplied by SECTOR_BYTES // to get the offset in bytes. self.file - .seek(SeekFrom::Start(u64::from(offset) * 4096)) + .seek(SeekFrom::Start(u64::from(offset) * SECTOR_BYTES as u64)) .map_err(Error::Io)?; // A chunk begins with a four-byte, big-endian value @@ -201,8 +204,55 @@ impl RegionHandle { /// Saves the given chunk to this region file. The header will be updated /// accordingly and saved as well. - pub fn save_chunk(&mut self, chunk: &Chunk) { - unimplemented!() + /// + /// Behavior may be unexpected if this region file does not contain the given + /// chunk position. + pub fn save_chunk(&mut self, chunk: &Chunk, entities: Vec) -> Result<(), Error> { + let chunk_pos = chunk.position(); + + let (local_x, local_z) = (chunk_pos.x % 32, chunk_pos.z % 32); + + // Find position in header and deallocate it if it currently exists. + let location = self + .header + .location_for_chunk(ChunkPosition::new(local_x, local_z)); + if location.exists() { + self.allocator.free(location.0); + } + + // Write chunk to `ChunkRoot` tag. + let root = chunk_to_chunk_root(chunk, entities); + + let blob = blob::chunk_root_to_blob(root); + + // Write to intermediate buffer, because we need to know the length. + let mut buf = Vec::with_capacity(4096); + blob.to_writer(&mut buf) + .expect("Could not write chunk blob"); + + let sectors = (buf.len() + SECTOR_BYTES - 1) / SECTOR_BYTES; + + let block = self.allocator.allocate(sectors as u32); + + // Write to file + self.file + .seek(SeekFrom::Start(block.offset as u64 * SECTOR_BYTES as u64)) + .map_err(Error::Io)?; + + self.file.write_all(&buf).map_err(Error::Io)?; + + // Update header + self.header + .set_location_for_chunk(ChunkPosition::new(local_x, local_z), ChunkLocation(block)); + self.save_header().map_err(Error::Io)?; + + Ok(()) + } + + fn save_header(&mut self) -> Result<(), io::Error> { + self.file.seek(SeekFrom::Start(0))?; + + self.header.write_to(&mut self.file) } } @@ -278,6 +328,69 @@ fn read_section_into_chunk(section: &LevelSection, chunk: &mut Chunk) -> Result< Ok(()) } +fn chunk_to_chunk_root(chunk: &Chunk, entities: Vec) -> ChunkRoot { + ChunkRoot { + level: ChunkLevel { + x_pos: chunk.position().x, + z_pos: chunk.position().z, + sections: chunk + .sections() + .iter() + .enumerate() + .filter_map(|(y, sec)| sec.map(|sec| (y, sec.clone()))) + .map(|(y, section)| { + LevelSection { + y: y as i8, + states: section.data().inner().iter().map(|x| *x as i64).collect(), + palette: section + .palette() + .unwrap_or(&vec![]) + .iter() + .map(|id| { + let block = Block::from_native_state_id(*id).unwrap(); + + let (name, props) = block.to_name_and_props(); + + let mut prop_map = HashMap::new(); + props.into_iter().for_each(|(name, value)| { + prop_map.insert(name.to_string(), value); + }); + + LevelPaletteEntry { + name: name.to_string(), + props: Some(LevelProperties { props: prop_map }), + } + }) + .collect(), // TODO: what happens with the global palette? + block_light: slice_u64_to_i8(section.block_light().inner()).to_vec(), + sky_light: slice_u64_to_i8(section.sky_light().inner()).to_vec(), + } + }) + .collect(), + biomes: chunk + .biomes() + .iter() + .map(|biome| biome.protocol_id()) + .collect(), + entities, + }, + data_version: DATA_VERSION, + } +} + +fn slice_u64_to_i8(input: &[u64]) -> &[i8] { + // TODO: someone should check this isn't undefined behavior. + // Pretty sure the alignment check makes this sound, + // but I'm not certain. + let (head, body, tail) = unsafe { input.align_to::() }; + + // Ensure that alignment is correct + assert!(head.is_empty()); + assert!(tail.is_empty()); + + body +} + /// An allocator for sectors. struct SectorAllocator { /// Vector of bits, with a bit set for each sector which is in use. @@ -438,7 +551,7 @@ pub fn load_region(dir: &PathBuf, pos: RegionPosition) -> Result ChunkLocation { - let index = (pos.x & 31) + (pos.z & 31) * (REGION_SIZE as i32); - self.locations[index as usize] + let index = Self::index(pos); + self.locations[index] + } + + /// Sets the location for the given chunk position. + fn set_location_for_chunk(&mut self, pos: ChunkPosition, location: ChunkLocation) { + let index = Self::index(pos); + self.locations[index] = location; + } + + /// Writes this header to the given writer. + fn write_to(&self, w: &mut W) -> Result<(), io::Error> + where + W: Write, + { + for location in &self.locations { + let value = (location.0.offset << 8) | (location.0.count & 0b1111_1111); + w.write_u32::(value)?; + } + + for timestamp in &self.timestamps { + w.write_u32::(*timestamp)?; + } + + Ok(()) + } + + fn index(pos: ChunkPosition) -> usize { + ((pos.x & 31) + (pos.z & 31) * (REGION_SIZE as i32)) as usize } } From ab7123b363eb62e1abc38ef6b964991bf1f3e7a6 Mon Sep 17 00:00:00 2001 From: caelunshun Date: Wed, 2 Oct 2019 20:03:23 -0600 Subject: [PATCH 04/20] Initial chunk worker support for chunk saving --- server/src/chunk_logic.rs | 5 +- server/src/chunkworker.rs | 119 ++++++++++++++++++++++++-------------- 2 files changed, 79 insertions(+), 45 deletions(-) diff --git a/server/src/chunk_logic.rs b/server/src/chunk_logic.rs index 1f771649c..257fd30fa 100644 --- a/server/src/chunk_logic.rs +++ b/server/src/chunk_logic.rs @@ -480,6 +480,9 @@ mod tests { load_chunk(&handle, pos); let recv = recv1.try_recv().unwrap(); - assert_eq!(recv, chunkworker::Request::LoadChunk(pos)); + match recv { + chunkworker::Request::LoadChunk(recv_pos) => assert_eq!(recv_pos, pos), + _ => panic!(), + } } } diff --git a/server/src/chunkworker.rs b/server/src/chunkworker.rs index ac49c2a5b..ae4a6971d 100644 --- a/server/src/chunkworker.rs +++ b/server/src/chunkworker.rs @@ -1,11 +1,9 @@ -//! This module handles the asynchronous loading of chunks from -//! region files. It runs on a separate thread and receives -//! load requests over a channel. Upon receiving a request, -//! it attempts to load the chunk from the world directory. -//! If the chunk was loaded successfully, it will send -//! the chunk back over a channel. If the chunk did not exist, -//! it will notify the server thread of the incident. -//! In response, the server thread should generate the chunk. +//! This module handles the asynchronous loading and saving +//! of chunks. It receives load and save requests from the server +//! (over a channel) and executes them. +//! +//! If a chunk cannot be loaded, it is generated on the Rayon thread pool +//! instead. use crate::worldgen::WorldGenerator; use crossbeam::channel::{Receiver, Sender}; use feather_core::entity::EntityData; @@ -20,9 +18,10 @@ use std::time::{SystemTime, UNIX_EPOCH}; pub type Reply = (ChunkPosition, Result<(Chunk, Vec), Error>); -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Clone)] pub enum Request { LoadChunk(ChunkPosition), + SaveChunk(Arc, Vec), ShutDown, } @@ -117,6 +116,9 @@ fn run(mut worker: ChunkWorker) { while let Ok(request) = worker.receiver.recv() { match request { Request::ShutDown => break, + Request::SaveChunk(chunk, entities) => { + save_chunk(&mut worker, &chunk, entities); + } Request::LoadChunk(pos) => { if let Some(reply) = load_chunk(&mut worker, pos) { worker.sender.send(reply).unwrap(); @@ -131,44 +133,27 @@ fn run(mut worker: ChunkWorker) { /// Attempts to load the chunk at the specified position. fn load_chunk(worker: &mut ChunkWorker, pos: ChunkPosition) -> Option { let rpos = RegionPosition::from_chunk(pos); - if !is_region_loaded(worker, pos) { - // Need to load region into memory - let handle = region::load_region(&worker.dir, rpos); - if handle.is_err() { - // TODO: Create a new region file before generating chunk + + match worker_region(&mut worker.open_regions, &worker.dir, rpos) { + Some(file) => { + // Load from region file + load_chunk_from_handle( + pos, + &mut file.handle, + &Arc::from(worker.sender.clone()), + &worker.world_generator, + ) + } + None => { + // Region doesn't exist: generate schedule_generate_new_chunk( &Arc::from(worker.sender.clone()), pos, &worker.world_generator, ); - return None; + None } - - let handle = handle.unwrap(); - - let last_used = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_secs(); - - let file = RegionFile { - handle, - _last_used: last_used, - }; - - worker.open_regions.insert(rpos, file); } - - // Load from region file - let file = worker.open_regions.get_mut(&rpos).unwrap(); - let handle = &mut file.handle; - - load_chunk_from_handle( - pos, - handle, - &Arc::from(worker.sender.clone()), - &worker.world_generator, - ) } fn load_chunk_from_handle( @@ -211,10 +196,56 @@ fn generate_new_chunk(pos: ChunkPosition, generator: &Arc) - (pos, Ok((generator.generate_chunk(pos), vec![]))) } +/// Saves the chunk at the specified position. +fn save_chunk(worker: &mut ChunkWorker, chunk: &Chunk, entities: Vec) { + let rpos = RegionPosition::from_chunk(chunk.position()); + + let file = match worker_region(&mut worker.open_regions, &worker.dir, rpos) { + Some(file) => file, + None => { + warn!("Region file creation not supported; skipping saving chunk"); + return; + } + }; + + file.handle.save_chunk(chunk, entities).unwrap(); +} + /// Returns whether the given chunk's region /// is already loaded. -fn is_region_loaded(worker: &ChunkWorker, chunk_pos: ChunkPosition) -> bool { - worker - .open_regions - .contains_key(&RegionPosition::from_chunk(chunk_pos)) +fn is_region_loaded( + open_regions: &HashMap, + rpos: RegionPosition, +) -> bool { + open_regions.contains_key(&rpos) +} + +fn worker_region<'a>( + open_regions: &'a mut HashMap, + dir: &PathBuf, + rpos: RegionPosition, +) -> Option<&'a mut RegionFile> { + if !is_region_loaded(open_regions, rpos) { + // Need to load region into memory + let handle = region::load_region(&dir, rpos); + if handle.is_err() { + // TODO: Create a new region file + return None; + } + + let handle = handle.unwrap(); + + let last_used = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs(); + + let file = RegionFile { + handle, + _last_used: last_used, + }; + + open_regions.insert(rpos, file); + } + open_regions.get_mut(&rpos) } From bc2dcf50f511416b2d21394b4ec4610012027349 Mon Sep 17 00:00:00 2001 From: caelunshun Date: Wed, 2 Oct 2019 21:44:33 -0600 Subject: [PATCH 05/20] Save chunks upon unload --- core/src/save/region/blob.rs | 20 +++++--------------- core/src/save/region/mod.rs | 17 ++++++++++++++--- core/src/world/mod.rs | 4 ++-- server/src/chunk_logic.rs | 35 +++++++++++++++++++++++++++++++---- server/src/entity/mod.rs | 11 +++++++---- server/src/entity/save.rs | 33 +++++++++++++++++++++++++++++++++ server/src/systems.rs | 1 + 7 files changed, 93 insertions(+), 28 deletions(-) create mode 100644 server/src/entity/save.rs diff --git a/core/src/save/region/blob.rs b/core/src/save/region/blob.rs index a64168f59..d366234b2 100644 --- a/core/src/save/region/blob.rs +++ b/core/src/save/region/blob.rs @@ -86,21 +86,11 @@ fn section_to_value(section: LevelSection) -> Value { map.insert(String::from("Name"), Value::String(entry.name)); if let Some(props) = entry.props { - map.insert( - String::from("Properties"), - Value::List( - props - .props - .into_iter() - .map(|(x, y)| { - let mut map = HashMap::new(); - map.insert(x, Value::String(y)); - map - }) - .map(Value::Compound) - .collect(), - ), - ); + let mut props_map = HashMap::new(); + props.props.into_iter().for_each(|(name, value)| { + props_map.insert(name, Value::String(value)); + }); + map.insert(String::from("Properties"), Value::Compound(props_map)); } entries.push(Value::Compound(map)) diff --git a/core/src/save/region/mod.rs b/core/src/save/region/mod.rs index b1311aa08..14f3f1913 100644 --- a/core/src/save/region/mod.rs +++ b/core/src/save/region/mod.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; -use std::fs::File; +use std::fs::{File, OpenOptions}; use std::io::prelude::*; use std::io::{Cursor, SeekFrom}; use std::path::PathBuf; @@ -227,7 +227,9 @@ impl RegionHandle { // Write to intermediate buffer, because we need to know the length. let mut buf = Vec::with_capacity(4096); - blob.to_writer(&mut buf) + buf.write_u8(2).map_err(Error::Io)?; // Compression type: zlib + + blob.to_zlib_writer(&mut buf) .expect("Could not write chunk blob"); let sectors = (buf.len() + SECTOR_BYTES - 1) / SECTOR_BYTES; @@ -239,6 +241,9 @@ impl RegionHandle { .seek(SeekFrom::Start(block.offset as u64 * SECTOR_BYTES as u64)) .map_err(Error::Io)?; + self.file + .write_u32::(buf.len() as u32) + .map_err(Error::Io)?; self.file.write_all(&buf).map_err(Error::Io)?; // Update header @@ -546,7 +551,13 @@ pub fn load_region(dir: &PathBuf, pos: RegionPosition) -> Result Chunk { + self.chunk_map.remove(&pos).unwrap() } /// Returns an immutable reference to the internal map. diff --git a/server/src/chunk_logic.rs b/server/src/chunk_logic.rs index 257fd30fa..4806fc66c 100644 --- a/server/src/chunk_logic.rs +++ b/server/src/chunk_logic.rs @@ -19,6 +19,7 @@ use crate::systems::{CHUNK_HOLD_REMOVE, CHUNK_LOAD, CHUNK_OPTIMIZE, CHUNK_UNLOAD use crate::worldgen::WorldGenerator; use crate::{chunkworker, current_time_in_millis, TickCount, TPS}; use feather_core::entity::EntityData; +use feather_core::Chunk; use hashbrown::HashSet; use multimap::MultiMap; use specs::storage::BTreeStorage; @@ -47,6 +48,13 @@ pub struct ChunkLoadFailEvent { pub pos: ChunkPosition, } +/// Event which is triggered when a chunk is unloaded. +#[derive(Clone)] +pub struct ChunkUnloadEvent { + /// The chunk which was unloaded. + pub chunk: Arc, +} + /// System for receiving loaded chunks from the chunk worker thread. pub struct ChunkLoadSystem; @@ -111,6 +119,14 @@ pub fn load_chunk(handle: &ChunkWorkerHandle, pos: ChunkPosition) { .unwrap(); } +/// Asynchronously saves the chunk at the given position. +pub fn save_chunk(handle: &ChunkWorkerHandle, chunk: Arc, entities: Vec) { + handle + .sender + .send(chunkworker::Request::SaveChunk(chunk, entities)) + .unwrap(); +} + /// The chunk holder map contains a mapping /// of chunk positions to any number of entities, called "holders." /// When a chunk position has no holders, it will be queued @@ -225,6 +241,7 @@ impl ChunkUnloadSystem { impl<'a> System<'a> for ChunkUnloadSystem { type SystemData = ( Write<'a, ChunkMap>, + Write<'a, EventChannel>, Read<'a, EventChannel>, Write<'a, ChunkUnloadQueue>, Read<'a, ChunkHolders>, @@ -232,10 +249,17 @@ impl<'a> System<'a> for ChunkUnloadSystem { ); fn run(&mut self, data: Self::SystemData) { - let (mut chunk_map, events, mut unload_queue, holders, tick_count) = data; + let ( + mut chunk_map, + mut unload_events, + release_events, + mut unload_queue, + holders, + tick_count, + ) = data; // Handle holder release events. - for event in events.read(&mut self.reader.as_mut().unwrap()) { + for event in release_events.read(&mut self.reader.as_mut().unwrap()) { // If the chunk now has zero holders, queue it for unloading. if !holders.chunk_has_holders(event.chunk) { let unload = ChunkUnload { @@ -261,10 +285,13 @@ impl<'a> System<'a> for ChunkUnloadSystem { continue; } - trace!("Unloading chunk at {:?}", unload.chunk); + warn!("Unloading chunk at {:?}", unload.chunk); // Unload chunk and pop from queue. - chunk_map.unload_chunk_at(unload.chunk); + let chunk = Arc::new(chunk_map.unload_chunk_at(unload.chunk)); + let event = ChunkUnloadEvent { chunk }; + unload_events.single_write(event); + unload_queue.queue.pop_front(); } else { // We're done - all chunks farther up in diff --git a/server/src/entity/mod.rs b/server/src/entity/mod.rs index 220b391ff..5f775512f 100644 --- a/server/src/entity/mod.rs +++ b/server/src/entity/mod.rs @@ -11,13 +11,14 @@ mod falling_block; mod item; pub mod metadata; mod movement; +mod save; mod types; use crate::systems::{ - BLOCK_FALLING_LANDING, CHUNK_CROSS, CHUNK_ENTITIES_LOAD, CHUNK_ENTITIES_UPDATE, ENTITY_DESTROY, - ENTITY_DESTROY_BROADCAST, ENTITY_METADATA_BROADCAST, ENTITY_MOVE_BROADCAST, ENTITY_PHYSICS, - ENTITY_SEND, ENTITY_SPAWN_BROADCAST, ENTITY_VELOCITY_BROADCAST, ITEM_COLLECT, ITEM_MERGE, - ITEM_SPAWN, JOIN_BROADCAST, SHOOT_ARROW, + BLOCK_FALLING_LANDING, CHUNK_CROSS, CHUNK_ENTITIES_LOAD, CHUNK_ENTITIES_UPDATE, CHUNK_SAVE, + ENTITY_DESTROY, ENTITY_DESTROY_BROADCAST, ENTITY_METADATA_BROADCAST, ENTITY_MOVE_BROADCAST, + ENTITY_PHYSICS, ENTITY_SEND, ENTITY_SPAWN_BROADCAST, ENTITY_VELOCITY_BROADCAST, ITEM_COLLECT, + ITEM_MERGE, ITEM_SPAWN, JOIN_BROADCAST, SHOOT_ARROW, }; pub use arrow::{ArrowComponent, ShootArrowEvent}; pub use broadcast::EntitySendSystem; @@ -39,6 +40,7 @@ use crate::entity::destroy::EntityDestroyBroadcastSystem; use crate::entity::falling_block::FallingBlockLandSystem; use crate::entity::item::ItemCollectSystem; use crate::entity::metadata::MetadataBroadcastSystem; +use crate::entity::save::ChunkSaveSystem; use broadcast::EntityBroadcastSystem; use component::ComponentResetSystem; use destroy::EntityDestroySystem; @@ -66,6 +68,7 @@ pub fn init_handlers(dispatcher: &mut DispatcherBuilder) { &[], ); dispatcher.add(ShootArrowSystem::default(), SHOOT_ARROW, &[]); + dispatcher.add(ChunkSaveSystem::default(), CHUNK_SAVE, &[]); } pub fn init_broadcast(dispatcher: &mut DispatcherBuilder) { diff --git a/server/src/entity/save.rs b/server/src/entity/save.rs new file mode 100644 index 000000000..5ee7c614a --- /dev/null +++ b/server/src/entity/save.rs @@ -0,0 +1,33 @@ +//! Saving of entity data (and chunk data along with it). + +use crate::chunk_logic; +use crate::chunk_logic::{ChunkUnloadEvent, ChunkWorkerHandle}; +use shrev::{EventChannel, ReaderId}; +use specs::{Read, ReadExpect, System}; +use std::sync::Arc; + +/// System to save chunk and entity data upon a chunk unload. +/// +/// This system listens to `ChunkUnloadEvent`s. +#[derive(Default)] +pub struct ChunkSaveSystem { + reader: Option>, +} + +impl<'a> System<'a> for ChunkSaveSystem { + type SystemData = ( + Read<'a, EventChannel>, + ReadExpect<'a, ChunkWorkerHandle>, + ); + + fn run(&mut self, data: Self::SystemData) { + let (unload_events, worker_handle) = data; + + for event in unload_events.read(self.reader.as_mut().unwrap()) { + let entities = vec![]; // TODO + chunk_logic::save_chunk(&worker_handle, Arc::clone(&event.chunk), entities); + } + } + + setup_impl!(reader); +} diff --git a/server/src/systems.rs b/server/src/systems.rs index d0cfd2b44..ab592b39d 100644 --- a/server/src/systems.rs +++ b/server/src/systems.rs @@ -46,6 +46,7 @@ pub const ITEM_SPAWN: &str = "item_spawn"; pub const SPAWNER: &str = "spawner"; pub const ITEM_MERGE: &str = "item_merge"; pub const SHOOT_ARROW: &str = "shoot_arrow"; +pub const CHUNK_SAVE: &str = "chunk_save"; pub const ENTITY_MOVE_BROADCAST: &str = "entity_move_broadcast"; pub const ENTITY_SPAWN_BROADCAST: &str = "entity_spawn_broadcast"; From 692531b7defcf368c128396c6e5c4b1a53a6a22a Mon Sep 17 00:00:00 2001 From: caelunshun Date: Thu, 3 Oct 2019 14:53:04 -0600 Subject: [PATCH 06/20] Implement periodic saving of chunks, with interval defined in config --- Cargo.lock | 26 +++++++++ core/src/world/chunk.rs | 31 +++++++++++ server/Cargo.toml | 1 + server/config/feather.toml | 4 +- server/src/chunk_logic.rs | 6 +- server/src/config.rs | 4 ++ server/src/entity/save.rs | 110 ++++++++++++++++++++++++++++++++++++- 7 files changed, 174 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e81d03d6b..cea446ba5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -641,6 +641,7 @@ dependencies = [ "hashbrown 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "heapless 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", "hematite-nbt 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", + "humantime-serde 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "mojang-api 0.3.0 (git+https://github.com/caelunshun/mojang-api-rs?rev=bf73e0a34d770224f69f926d78f2679b3eeabc73)", @@ -972,6 +973,23 @@ name = "httparse" version = "1.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "humantime" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "humantime-serde" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "humantime 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.100 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "hyper" version = "0.13.0-alpha.2" @@ -1583,6 +1601,11 @@ dependencies = [ "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "quick-error" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "quote" version = "0.5.2" @@ -2869,6 +2892,8 @@ dependencies = [ "checksum http 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)" = "372bcb56f939e449117fb0869c2e8fd8753a8223d92a172c6e808cf123a5b6e4" "checksum http-body 0.2.0-alpha.1 (registry+https://github.com/rust-lang/crates.io-index)" = "1bc8dfa1f6155eadd665d39458a6c1a2c37bbd372a053383a4245775a0d9d98a" "checksum httparse 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "cd179ae861f0c2e53da70d892f5f3029f9594be0c41dc5269cd371691b1dc2f9" +"checksum humantime 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f" +"checksum humantime-serde 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8f59e8a805c18bc9ded3f4e596cb5f0157d88a235e875480a7593b5926f95065" "checksum hyper 0.13.0-alpha.2 (registry+https://github.com/rust-lang/crates.io-index)" = "0808cc9f4342dc1389de9bc3b75c43cc030ccd2ebc5accc630d8acc1f0d25ae6" "checksum hyper-tls 0.4.0-alpha.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7217758984f72468964706a47dcc7f5325ea4c9ea57d304948d2bf46041d0ff7" "checksum idna 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "02e2673c30ee86b5b96a9cb52ad15718aa1f966f5ab9ad54a8b95d5ca33120a9" @@ -2935,6 +2960,7 @@ dependencies = [ "checksum proc-macro2 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "1b06e2f335f48d24442b35a19df506a835fb3547bc3c06ef27340da9acf5cae7" "checksum proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)" = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" "checksum proc-macro2 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "e98a83a9f9b331f54b924e68a66acb1bb35cb01fb0a23645139967abefb697e8" +"checksum quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9274b940887ce9addde99c4eee6b5c44cc494b182b97e73dc8ffdcb3397fd3f0" "checksum quote 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9949cfe66888ffe1d53e6ec9d9f3b70714083854be20fd5e271b232a017401e8" "checksum quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)" = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1" "checksum quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe" diff --git a/core/src/world/chunk.rs b/core/src/world/chunk.rs index 58f7c4c48..707a18f4e 100644 --- a/core/src/world/chunk.rs +++ b/core/src/world/chunk.rs @@ -56,6 +56,9 @@ pub struct Chunk { /// The biomes in this section, indexable by /// ((z << 4) | x). biomes: [Biome; SECTION_WIDTH * SECTION_WIDTH], + /// Whether this chunk has been modified since the most recent + /// call to `check_modified`(). + modified: bool, } impl Default for Chunk { @@ -71,6 +74,7 @@ impl Default for Chunk { Self { location: ChunkPosition::new(0, 0), + modified: true, sections, biomes: [Biome::Plains; SECTION_WIDTH * SECTION_WIDTH], } @@ -83,6 +87,7 @@ impl Chunk { pub fn new(location: ChunkPosition) -> Self { Self { location, + modified: true, ..Default::default() } } @@ -94,6 +99,7 @@ impl Chunk { pub fn new_with_default_biome(location: ChunkPosition, default_biome: Biome) -> Self { Self { location, + modified: true, biomes: [default_biome; SECTION_WIDTH * SECTION_HEIGHT], ..Default::default() } @@ -130,6 +136,7 @@ impl Chunk { assert!(x < CHUNK_WIDTH); assert!(y < CHUNK_HEIGHT); assert!(z < CHUNK_WIDTH); + self.modified = true; let chunk_section = &mut self.sections[y / 16]; let section; @@ -158,6 +165,7 @@ impl Chunk { /// Returns a mutable slice of the 16 sections /// in this chunk. pub fn sections_mut(&mut self) -> Vec> { + self.modified = true; self.sections.iter_mut().map(|sec| sec.as_mut()).collect() } @@ -186,6 +194,7 @@ impl Chunk { /// to be empty, meaning it consists only of air. pub fn section_mut(&mut self, index: usize) -> Option<&mut ChunkSection> { assert!(index < NUM_SECTIONS); + self.modified = true; self.sections[index].as_mut() } @@ -193,6 +202,7 @@ impl Chunk { pub fn set_section_at(&mut self, index: usize, section: Option) { assert!(index < NUM_SECTIONS); self.sections[index] = section; + self.modified = true; } /// Optimizes each section in this chunk. @@ -231,6 +241,7 @@ impl Chunk { /// Returns a mutable reference to the biomes of this chunk. pub fn biomes_mut(&mut self) -> &mut [Biome] { + self.modified = true; &mut self.biomes } @@ -249,9 +260,18 @@ impl Chunk { /// Panics if `x < 16` or `z < 16`. pub fn set_biome_at(&mut self, x: usize, z: usize, biome: Biome) { let index = Self::biome_index(x, z); + self.modified = true; self.biomes[index] = biome; } + /// Checks whether this chunk has been modified since the last + /// call to this function. + pub fn check_modified(&mut self) -> bool { + let res = self.modified; + self.modified = false; + res + } + fn biome_index(x: usize, z: usize) -> usize { assert!(x < 16); assert!(z < 16); @@ -1034,4 +1054,15 @@ mod tests { } } } + + #[test] + fn test_modified() { + let mut chunk = Chunk::default(); + assert!(chunk.check_modified()); + assert!(!chunk.check_modified()); + + chunk.set_block_at(0, 0, 0, Block::Stone); + assert!(chunk.check_modified()); + assert!(!chunk.check_modified()); + } } diff --git a/server/Cargo.toml b/server/Cargo.toml index 335b984f5..8bbaef634 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -62,6 +62,7 @@ simdeez = "0.6.4" bitvec = "0.15.1" tokio = "=0.2.0-alpha.5" futures-preview = { version = "=0.3.0-alpha.18", features = ["async-await", "nightly"] } +humantime-serde = "0.1.1" [dev-dependencies] criterion = "0.3.0" diff --git a/server/config/feather.toml b/server/config/feather.toml index 14ad4f662..e647521ab 100644 --- a/server/config/feather.toml +++ b/server/config/feather.toml @@ -53,4 +53,6 @@ generator = "default" # Leaving this value empty will generate a random seed. # If this value is not a valid integer (i64), the string # will be converted using a hash function. -seed = "" \ No newline at end of file +seed = "" +# Interval at which to save modified chunks. +save_interval = "1min" \ No newline at end of file diff --git a/server/src/chunk_logic.rs b/server/src/chunk_logic.rs index 4806fc66c..b31effb31 100644 --- a/server/src/chunk_logic.rs +++ b/server/src/chunk_logic.rs @@ -31,8 +31,8 @@ use std::sync::Arc; /// worker thread. #[derive(Debug, Clone)] pub struct ChunkWorkerHandle { - sender: Sender, - receiver: Receiver, + pub sender: Sender, + pub receiver: Receiver, } /// Event which is triggered when a chunk is loaded. @@ -285,8 +285,6 @@ impl<'a> System<'a> for ChunkUnloadSystem { continue; } - warn!("Unloading chunk at {:?}", unload.chunk); - // Unload chunk and pop from queue. let chunk = Arc::new(chunk_map.unload_chunk_at(unload.chunk)); let event = ChunkUnloadEvent { chunk }; diff --git a/server/src/config.rs b/server/src/config.rs index 5aa66b72b..14af9ddb1 100644 --- a/server/src/config.rs +++ b/server/src/config.rs @@ -1,3 +1,4 @@ +use failure::_core::time::Duration; use std::fs::read_to_string; #[derive(Debug, Fail)] @@ -70,6 +71,8 @@ pub struct World { pub name: String, pub generator: String, pub seed: String, + #[serde(with = "humantime_serde")] + pub save_interval: Duration, } /// Loads the configuration from the given file/ @@ -129,5 +132,6 @@ mod tests { assert_eq!(world.name, "world"); assert_eq!(world.generator, "default"); assert_eq!(world.seed, ""); + assert_eq!(world.save_interval.as_millis(), 1000 * 60); } } diff --git a/server/src/entity/save.rs b/server/src/entity/save.rs index 5ee7c614a..5c35b0af3 100644 --- a/server/src/entity/save.rs +++ b/server/src/entity/save.rs @@ -2,11 +2,15 @@ use crate::chunk_logic; use crate::chunk_logic::{ChunkUnloadEvent, ChunkWorkerHandle}; +use crate::config::Config; +use feather_core::world::ChunkMap; use shrev::{EventChannel, ReaderId}; -use specs::{Read, ReadExpect, System}; +use specs::{Read, ReadExpect, System, Write}; use std::sync::Arc; +use std::time::Instant; -/// System to save chunk and entity data upon a chunk unload. +/// System to save chunk and entity data upon a chunk unload +/// and periodically. /// /// This system listens to `ChunkUnloadEvent`s. #[derive(Default)] @@ -14,20 +18,120 @@ pub struct ChunkSaveSystem { reader: Option>, } +/// Previous time at which chunks were saved. +pub struct PreviousSaveTime(Instant); + +impl Default for PreviousSaveTime { + fn default() -> Self { + Self(Instant::now()) + } +} + impl<'a> System<'a> for ChunkSaveSystem { type SystemData = ( + Write<'a, PreviousSaveTime>, + Write<'a, ChunkMap>, Read<'a, EventChannel>, + Read<'a, Arc>, ReadExpect<'a, ChunkWorkerHandle>, ); fn run(&mut self, data: Self::SystemData) { - let (unload_events, worker_handle) = data; + let (mut prev_save_time, mut chunk_map, unload_events, config, worker_handle) = data; + + // TODO: entities for event in unload_events.read(self.reader.as_mut().unwrap()) { let entities = vec![]; // TODO chunk_logic::save_chunk(&worker_handle, Arc::clone(&event.chunk), entities); } + + if prev_save_time.0.elapsed() >= config.world.save_interval { + // Save chunks + let mut count = 0; + for (_, chunk) in chunk_map.chunks_mut() { + if chunk.check_modified() { + let entities = vec![]; // TODO + chunk_logic::save_chunk(&worker_handle, Arc::new(chunk.clone()), entities); + count += 1; + } + } + + prev_save_time.0 = Instant::now(); + + debug!("Saving {} chunks", count); + } } setup_impl!(reader); } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{chunkworker, testframework as t}; + use failure::_core::time::Duration; + use feather_core::{Chunk, ChunkPosition}; + + #[test] + fn test_chunk_unload() { + let (mut world, mut dispatcher) = t::builder().with(ChunkSaveSystem::default(), "").build(); + + let (tx, rx) = crossbeam::unbounded(); + let (_tx2, rx2) = crossbeam::unbounded(); + world.insert(ChunkWorkerHandle { + sender: tx, + receiver: rx2, + }); + + let event = ChunkUnloadEvent { + chunk: Arc::new(Chunk::default()), + }; + + t::trigger_event(&world, event); + + dispatcher.dispatch(&world); + + let msg = rx.try_recv().unwrap(); + + match msg { + chunkworker::Request::SaveChunk(chunk, entities) => { + assert_eq!(chunk.position(), ChunkPosition::new(0, 0)); + assert!(entities.is_empty()); // TODO + } + _ => panic!(), + } + } + + #[test] + fn test_periodic() { + let (mut world, mut dispatcher) = t::builder().with(ChunkSaveSystem::default(), "").build(); + + let (tx, rx) = crossbeam::unbounded(); + let (_tx2, rx2) = crossbeam::unbounded(); + world.insert(ChunkWorkerHandle { + sender: tx, + receiver: rx2, + }); + + let last_save_time = PreviousSaveTime(Instant::now() - Duration::from_secs(1_000_000)); + world.insert(last_save_time); + + let pos = ChunkPosition::new(0, 0); + world + .fetch_mut::() + .set_chunk_at(pos, Chunk::new(pos)); + + dispatcher.dispatch(&world); + + let msg = rx.try_recv().unwrap(); + + match msg { + chunkworker::Request::SaveChunk(chunk, entities) => { + assert_eq!(chunk.position(), pos); + assert!(entities.is_empty()); // TODO + } + _ => panic!(), + } + } +} From 6a631073e1245319678d2d402d48904a26d34e3b Mon Sep 17 00:00:00 2001 From: caelunshun Date: Thu, 3 Oct 2019 15:15:57 -0600 Subject: [PATCH 07/20] Implement saving of chunks on shutdown --- Cargo.lock | 30 +++++++++++++++++++++++ core/src/save/region/mod.rs | 3 +++ server/Cargo.toml | 1 + server/src/chunk_logic.rs | 36 ++++++++++++++-------------- server/src/chunkworker.rs | 15 ++++++++---- server/src/entity/mod.rs | 2 ++ server/src/entity/save.rs | 27 ++++++++++++--------- server/src/lib.rs | 47 +++++++++++++++++++++++++++++++++++-- server/src/shutdown.rs | 10 ++++++++ 9 files changed, 137 insertions(+), 34 deletions(-) create mode 100644 server/src/shutdown.rs diff --git a/Cargo.lock b/Cargo.lock index cea446ba5..7f3cb5285 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -438,6 +438,15 @@ dependencies = [ "memchr 2.2.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "ctrlc" +version = "3.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "derivative" version = "1.0.3" @@ -629,6 +638,7 @@ dependencies = [ "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)", "criterion 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "crossbeam 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "ctrlc 3.1.3 (registry+https://github.com/rust-lang/crates.io-index)", "derive-new 0.5.8 (registry+https://github.com/rust-lang/crates.io-index)", "derive_deref 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1320,6 +1330,18 @@ dependencies = [ "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "nix" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cc 1.0.45 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)", + "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "nodrop" version = "0.1.13" @@ -2586,6 +2608,11 @@ name = "version_check" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "void" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "walkdir" version = "2.2.9" @@ -2849,6 +2876,7 @@ dependencies = [ "checksum crossbeam-utils 0.6.6 (registry+https://github.com/rust-lang/crates.io-index)" = "04973fa96e96579258a5091af6003abde64af786b860f18622b82e026cca60e6" "checksum csv 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "37519ccdfd73a75821cac9319d4fce15a81b9fcf75f951df5b9988aa3a0af87d" "checksum csv-core 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "9b5cadb6b25c77aeff80ba701712494213f4a8418fcda2ee11b6560c3ad0bf4c" +"checksum ctrlc 3.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "c7dfd2d8b4c82121dfdff120f818e09fc4380b0b7e17a742081a89b94853e87f" "checksum derivative 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "942ca430eef7a3806595a6737bc388bf51adb888d3fc0dd1b50f1c170167ee3a" "checksum derive-new 0.5.8 (registry+https://github.com/rust-lang/crates.io-index)" = "71f31892cd5c62e414316f2963c5689242c43d8e7bbcaaeca97e5e28c95d91d9" "checksum derive_deref 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "11554fdb0aa42363a442e0c4278f51c9621e20c1ce3bac51d79e60646f3b8b8f" @@ -2927,6 +2955,7 @@ dependencies = [ "checksum native-tls 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "4b2df1a4c22fd44a62147fd8f13dd0f95c9d8ca7b2610299b2a2f9cf8964274e" "checksum ncollide3d 0.20.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3ee57cac70a2892e89fab7d5fd295b0ad544d1f877fa70fe8ae4be477514dd61" "checksum net2 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)" = "42550d9fb7b6684a6d404d9fa7250c2eb2646df731d1c06afc06dcee9e1bcf88" +"checksum nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)" = "6c722bee1037d430d0f8e687bbdbf222f27cc6e4e68d5caf630857bb2b6dbdce" "checksum nodrop 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)" = "2f9667ddcc6cc8a43afc9b7917599d7216aa09c463919ea32c59ed6cac8bc945" "checksum nom 4.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2ad2a91a8e869eeb30b9cb3119ae87773a8f4ae617f41b1eb9c154b2905f7bd6" "checksum num-bigint 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "f9c3f34cdd24f334cb265d9bf8bfa8a241920d026916785747a92f0e55541a1a" @@ -3070,6 +3099,7 @@ dependencies = [ "checksum vcpkg 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)" = "33dd455d0f96e90a75803cfeb7f948768c08d70a6de9a8d2362461935698bf95" "checksum vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "05c78687fb1a80548ae3250346c3db86a80a7cdd77bda190189f2d0a0987c81a" "checksum version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "914b1a6776c4c929a602fafd8bc742e06365d4bcbe48c30f9cca5824f70dc9dd" +"checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" "checksum walkdir 2.2.9 (registry+https://github.com/rust-lang/crates.io-index)" = "9658c94fa8b940eab2250bd5a457f9c48b748420d71293b165c8cdbe2f55f71e" "checksum want 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0" "checksum wasi 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b89c3ce4ce14bdc6fb6beaf9ec7928ca331de5df7e5ea278375642a2f478570d" diff --git a/core/src/save/region/mod.rs b/core/src/save/region/mod.rs index 14f3f1913..5f653b451 100644 --- a/core/src/save/region/mod.rs +++ b/core/src/save/region/mod.rs @@ -199,6 +199,9 @@ impl RegionHandle { Biome::from_protocol_id(id).ok_or_else(|| Error::InvalidBiomeId(id))?; } + // Chunk was not modified, but it thinks it was: disable this + chunk.check_modified(); + Ok((chunk, level.entities.to_vec())) } diff --git a/server/Cargo.toml b/server/Cargo.toml index 8bbaef634..760f9bb99 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -63,6 +63,7 @@ bitvec = "0.15.1" tokio = "=0.2.0-alpha.5" futures-preview = { version = "=0.3.0-alpha.18", features = ["async-await", "nightly"] } humantime-serde = "0.1.1" +ctrlc = "3.1.3" [dev-dependencies] criterion = "0.3.0" diff --git a/server/src/chunk_logic.rs b/server/src/chunk_logic.rs index b31effb31..1d0563842 100644 --- a/server/src/chunk_logic.rs +++ b/server/src/chunk_logic.rs @@ -69,23 +69,25 @@ impl<'a> System<'a> for ChunkLoadSystem { fn run(&mut self, data: Self::SystemData) { let (mut chunk_map, mut load_events, mut fail_events, handle) = data; - while let Ok((pos, result)) = handle.receiver.try_recv() { - match result { - Ok((chunk, entities)) => { - chunk_map.set_chunk_at(pos, chunk); - - // Trigger event - let event = ChunkLoadEvent { pos, entities }; - load_events.single_write(event); - - trace!("Loaded chunk at {:?}", pos); - } - Err(err) => { - // TODO generate chunk if it didn't exist - warn!("Failed to load chunk at {:?}: {}", pos, err); - let event = ChunkLoadFailEvent { pos }; - fail_events.single_write(event); - } + while let Ok(reply) = handle.receiver.try_recv() { + match reply { + chunkworker::Reply::LoadedChunk(pos, result) => match result { + Ok((chunk, entities)) => { + chunk_map.set_chunk_at(pos, chunk); + + // Trigger event + let event = ChunkLoadEvent { pos, entities }; + load_events.single_write(event); + + trace!("Loaded chunk at {:?}", pos); + } + Err(err) => { + warn!("Failed to load chunk at {:?}: {}", pos, err); + let event = ChunkLoadFailEvent { pos }; + fail_events.single_write(event); + } + }, + _ => (), } } } diff --git a/server/src/chunkworker.rs b/server/src/chunkworker.rs index ae4a6971d..aec90f08b 100644 --- a/server/src/chunkworker.rs +++ b/server/src/chunkworker.rs @@ -16,7 +16,10 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::{SystemTime, UNIX_EPOCH}; -pub type Reply = (ChunkPosition, Result<(Chunk, Vec), Error>); +pub enum Reply { + LoadedChunk(ChunkPosition, Result<(Chunk, Vec), Error>), + SavedChunk(ChunkPosition), +} #[derive(Clone)] pub enum Request { @@ -165,13 +168,13 @@ fn load_chunk_from_handle( let result = handle.load_chunk(pos); match result { - Ok(chunk) => Some((pos, Ok(chunk))), + Ok(chunk) => Some(Reply::LoadedChunk(pos, Ok(chunk))), Err(e) => match e { region::Error::ChunkNotExist => { schedule_generate_new_chunk(sender, pos, generator); None } - err => Some((pos, Err(Error::LoadError(err)))), + err => Some(Reply::LoadedChunk(pos, Err(Error::LoadError(err)))), }, } } @@ -193,7 +196,7 @@ fn schedule_generate_new_chunk( /// Generates a new chunk synchronously, /// returning a Reply to send to a Sender. fn generate_new_chunk(pos: ChunkPosition, generator: &Arc) -> Reply { - (pos, Ok((generator.generate_chunk(pos), vec![]))) + Reply::LoadedChunk(pos, Ok((generator.generate_chunk(pos), vec![]))) } /// Saves the chunk at the specified position. @@ -209,6 +212,10 @@ fn save_chunk(worker: &mut ChunkWorker, chunk: &Chunk, entities: Vec }; file.handle.save_chunk(chunk, entities).unwrap(); + worker + .sender + .send(Reply::SavedChunk(chunk.position())) + .unwrap(); } /// Returns whether the given chunk's region diff --git a/server/src/entity/mod.rs b/server/src/entity/mod.rs index 5f775512f..ed9a7c911 100644 --- a/server/src/entity/mod.rs +++ b/server/src/entity/mod.rs @@ -34,6 +34,8 @@ pub use metadata::{EntityBitMask, Metadata}; pub use movement::broadcast_entity_movement; pub use types::EntityType; +pub use save::save_chunks; + use crate::entity::arrow::ShootArrowSystem; use crate::entity::chunk::EntityChunkLoadSystem; use crate::entity::destroy::EntityDestroyBroadcastSystem; diff --git a/server/src/entity/save.rs b/server/src/entity/save.rs index 5c35b0af3..0ff3ddf57 100644 --- a/server/src/entity/save.rs +++ b/server/src/entity/save.rs @@ -48,24 +48,29 @@ impl<'a> System<'a> for ChunkSaveSystem { if prev_save_time.0.elapsed() >= config.world.save_interval { // Save chunks - let mut count = 0; - for (_, chunk) in chunk_map.chunks_mut() { - if chunk.check_modified() { - let entities = vec![]; // TODO - chunk_logic::save_chunk(&worker_handle, Arc::new(chunk.clone()), entities); - count += 1; - } - } - + save_chunks(&mut chunk_map, &worker_handle); prev_save_time.0 = Instant::now(); - - debug!("Saving {} chunks", count); } } setup_impl!(reader); } +/// Saves all modified chunks. +pub fn save_chunks(chunk_map: &mut ChunkMap, handle: &ChunkWorkerHandle) -> u32 { + let mut count = 0; + for (_, chunk) in chunk_map.chunks_mut() { + if chunk.check_modified() { + let entities = vec![]; // TODO + chunk_logic::save_chunk(&handle, Arc::new(chunk.clone()), entities); + count += 1; + } + } + + debug!("Saving {} chunks", count); + count +} + #[cfg(test)] mod tests { use super::*; diff --git a/server/src/lib.rs b/server/src/lib.rs index 0b710da1f..64421f56d 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -28,6 +28,7 @@ extern crate feather_core; extern crate nalgebra_glm as glm; +use crossbeam::Receiver; use std::alloc::System; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; @@ -74,6 +75,7 @@ pub mod network; pub mod physics; pub mod player; pub mod prelude; +pub mod shutdown; pub mod systems; #[cfg(test)] pub mod testframework; @@ -133,6 +135,11 @@ pub fn main() { let (mut world, mut dispatcher) = init_world(config, player_count, io_manager, level); + // Channel used by the shutdown handler to notify the server thread. + let (shutdown_tx, shutdown_rx) = crossbeam::unbounded(); + + shutdown::init(shutdown_tx); + info!("Initialized world"); info!("Generating RSA keypair"); @@ -142,7 +149,38 @@ pub fn main() { load_spawn_chunks(&mut world); info!("Server started"); - run_loop(&mut world, &mut dispatcher); + run_loop(&mut world, &mut dispatcher, shutdown_rx); + + info!("Shutting down"); + + info!("Saving chunks"); + let mut chunk_map = world.fetch_mut::(); + let handle = world.fetch::(); + let count = entity::save_chunks(&mut chunk_map, &handle); + + handle.sender.send(chunkworker::Request::ShutDown).unwrap(); + + let mut saved = 0; + // Wait for chunks to finish saving + while let Ok(msg) = handle.receiver.recv() { + match msg { + chunkworker::Reply::SavedChunk(_) => saved += 1, + _ => (), + } + + if saved == count { + break; + } + } + + assert!( + count == saved, + "didn't save all chunks: {} != {}", + count, + saved + ); + + info!("Goodbye"); } /// Loads the configuration file, creating a default @@ -263,8 +301,13 @@ fn load_spawn_chunks(world: &mut World) { /// Runs the server loop, blocking until the server /// is shut down. -fn run_loop(world: &mut World, dispatcher: &mut Dispatcher) { +fn run_loop(world: &mut World, dispatcher: &mut Dispatcher, shutdown_rx: Receiver<()>) { loop { + if let Ok(_) = shutdown_rx.try_recv() { + // Shut down + return; + } + let start_time = current_time_in_millis(); dispatcher.dispatch(&world); diff --git a/server/src/shutdown.rs b/server/src/shutdown.rs new file mode 100644 index 000000000..4b18d3823 --- /dev/null +++ b/server/src/shutdown.rs @@ -0,0 +1,10 @@ +//! Shutdown behavior. + +use crossbeam::Sender; + +pub fn init(tx: Sender<()>) { + ctrlc::set_handler(move || { + tx.send(()).unwrap(); + }) + .unwrap(); +} From c330d89b10aa32f30c80c9f206caf9cc9806f888 Mon Sep 17 00:00:00 2001 From: caelunshun Date: Thu, 3 Oct 2019 17:14:42 -0600 Subject: [PATCH 08/20] Implement creation of new region files --- core/src/save/region/mod.rs | 98 ++++++++++++++++++++++++++++++++----- core/src/world/chunk.rs | 3 ++ server/src/chunkworker.rs | 46 ++++++----------- 3 files changed, 103 insertions(+), 44 deletions(-) diff --git a/core/src/save/region/mod.rs b/core/src/save/region/mod.rs index 5f653b451..db4f1ebf9 100644 --- a/core/src/save/region/mod.rs +++ b/core/src/save/region/mod.rs @@ -7,7 +7,7 @@ use std::fs::{File, OpenOptions}; use std::io::prelude::*; use std::io::{Cursor, SeekFrom}; use std::path::PathBuf; -use std::{io, iter}; +use std::{fs, io, iter}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use serde::Deserialize; @@ -235,7 +235,9 @@ impl RegionHandle { blob.to_zlib_writer(&mut buf) .expect("Could not write chunk blob"); - let sectors = (buf.len() + SECTOR_BYTES - 1) / SECTOR_BYTES; + let total_len = buf.len() + 4; // 4 bytes for length header + + let sectors = (total_len + SECTOR_BYTES - 1) / SECTOR_BYTES; let block = self.allocator.allocate(sectors as u32); @@ -249,6 +251,13 @@ impl RegionHandle { .map_err(Error::Io)?; self.file.write_all(&buf).map_err(Error::Io)?; + // Write padding to align to sector count + let padding_count = SECTOR_BYTES - total_len % SECTOR_BYTES; + + for _ in 0..padding_count { + self.file.write_u8(0).map_err(Error::Io)?; + } + // Update header self.header .set_location_for_chunk(ChunkPosition::new(local_x, local_z), ChunkLocation(block)); @@ -473,13 +482,16 @@ impl SectorAllocator { } // No sector found: must allocate into end - self.used_sectors - .extend(iter::repeat(true).take(min_size as usize)); - SectorBlock { + let block = SectorBlock { offset: self.used_sectors.len() as u32, count: min_size, - } + }; + + self.used_sectors + .extend(iter::repeat(true).take(min_size as usize)); + + block } } @@ -551,13 +563,9 @@ impl std::error::Error for Error {} /// header so that chunks can be retrieved later. pub fn load_region(dir: &PathBuf, pos: RegionPosition) -> Result { let mut file = { - let mut buf = dir.clone(); - buf.push(format!("region/r.{}.{}.mca", pos.x, pos.z)); + let buf = region_file_path(dir, pos); - OpenOptions::new() - .read(true) - .write(true) - .append(false) + open_opts() .create(false) .open(buf.as_path()) .map_err(Error::Io)? @@ -576,6 +584,57 @@ pub fn load_region(dir: &PathBuf, pos: RegionPosition) -> Result Result { + create_region_dir(dir).map_err(Error::Io)?; + let mut file = { + let buf = region_file_path(dir, pos); + + open_opts().create(true).open(buf.as_path()) + } + .map_err(Error::Io)?; + + let header = RegionHeader::default(); + header.write_to(&mut file).map_err(Error::Io)?; + + let allocator = SectorAllocator::new(&header, 2); + Ok(RegionHandle { + file, + header, + allocator, + }) +} + +fn open_opts() -> OpenOptions { + OpenOptions::new() + .read(true) + .write(true) + .append(false) + .clone() +} + +fn region_file_path(dir: &PathBuf, pos: RegionPosition) -> PathBuf { + let mut buf = dir.clone(); + buf.push(format!("region/r.{}.{}.mca", pos.x, pos.z)); + buf +} + +fn create_region_dir(dir: &PathBuf) -> Result<(), io::Error> { + let mut dir = dir.clone(); + dir.push("region"); + fs::create_dir_all(dir.as_path()) +} + /// Reads the region header from the given file. fn read_header(file: &mut File) -> Result { let len = { @@ -629,6 +688,21 @@ struct RegionHeader { timestamps: Vec, } +impl Default for RegionHeader { + fn default() -> Self { + Self { + locations: vec![ + ChunkLocation(SectorBlock { + offset: 0, + count: 0 + }); + REGION_SIZE * REGION_SIZE + ], + timestamps: vec![0; REGION_SIZE * REGION_SIZE], + } + } +} + impl RegionHeader { /// Returns the `ChunkLocation` for the given /// chunk position. diff --git a/core/src/world/chunk.rs b/core/src/world/chunk.rs index 707a18f4e..7466dd8a4 100644 --- a/core/src/world/chunk.rs +++ b/core/src/world/chunk.rs @@ -212,6 +212,7 @@ impl Chunk { /// modified since the last time they were optimized /// are not optimized. pub fn optimize(&mut self) -> u32 { + let modified = self.modified; let mut count = 0; let mut to_remove = vec![]; for (i, s) in self.sections.iter_mut().enumerate() { @@ -231,6 +232,8 @@ impl Chunk { self.set_section_at(i, None); } + self.modified = modified; + count } diff --git a/server/src/chunkworker.rs b/server/src/chunkworker.rs index aec90f08b..98b996e0a 100644 --- a/server/src/chunkworker.rs +++ b/server/src/chunkworker.rs @@ -137,26 +137,14 @@ fn run(mut worker: ChunkWorker) { fn load_chunk(worker: &mut ChunkWorker, pos: ChunkPosition) -> Option { let rpos = RegionPosition::from_chunk(pos); - match worker_region(&mut worker.open_regions, &worker.dir, rpos) { - Some(file) => { - // Load from region file - load_chunk_from_handle( - pos, - &mut file.handle, - &Arc::from(worker.sender.clone()), - &worker.world_generator, - ) - } - None => { - // Region doesn't exist: generate - schedule_generate_new_chunk( - &Arc::from(worker.sender.clone()), - pos, - &worker.world_generator, - ); - None - } - } + let file = worker_region(&mut worker.open_regions, &worker.dir, rpos); + // Load from region file + load_chunk_from_handle( + pos, + &mut file.handle, + &Arc::from(worker.sender.clone()), + &worker.world_generator, + ) } fn load_chunk_from_handle( @@ -203,13 +191,7 @@ fn generate_new_chunk(pos: ChunkPosition, generator: &Arc) - fn save_chunk(worker: &mut ChunkWorker, chunk: &Chunk, entities: Vec) { let rpos = RegionPosition::from_chunk(chunk.position()); - let file = match worker_region(&mut worker.open_regions, &worker.dir, rpos) { - Some(file) => file, - None => { - warn!("Region file creation not supported; skipping saving chunk"); - return; - } - }; + let file = worker_region(&mut worker.open_regions, &worker.dir, rpos); file.handle.save_chunk(chunk, entities).unwrap(); worker @@ -231,13 +213,13 @@ fn worker_region<'a>( open_regions: &'a mut HashMap, dir: &PathBuf, rpos: RegionPosition, -) -> Option<&'a mut RegionFile> { +) -> &'a mut RegionFile { if !is_region_loaded(open_regions, rpos) { // Need to load region into memory - let handle = region::load_region(&dir, rpos); + let mut handle = region::load_region(&dir, rpos); if handle.is_err() { - // TODO: Create a new region file - return None; + // Create a new region file + handle = region::create_region(&dir, rpos); } let handle = handle.unwrap(); @@ -254,5 +236,5 @@ fn worker_region<'a>( open_regions.insert(rpos, file); } - open_regions.get_mut(&rpos) + open_regions.get_mut(&rpos).unwrap() } From 1ff37e9643921229e9738276e32a8ebffd62a684 Mon Sep 17 00:00:00 2001 From: caelunshun Date: Thu, 3 Oct 2019 17:42:20 -0600 Subject: [PATCH 09/20] Save level.dat on shutdown --- server/src/chunk_logic.rs | 7 +++--- server/src/chunkworker.rs | 1 + server/src/lib.rs | 30 +++------------------- server/src/shutdown.rs | 52 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 60 insertions(+), 30 deletions(-) diff --git a/server/src/chunk_logic.rs b/server/src/chunk_logic.rs index 3aa71c046..6f88adf38 100644 --- a/server/src/chunk_logic.rs +++ b/server/src/chunk_logic.rs @@ -70,8 +70,8 @@ impl<'a> System<'a> for ChunkLoadSystem { let (mut chunk_map, mut load_events, mut fail_events, handle) = data; while let Ok(reply) = handle.receiver.try_recv() { - match reply { - chunkworker::Reply::LoadedChunk(pos, result) => match result { + if let chunkworker::Reply::LoadedChunk(pos, result) = reply { + match result { Ok((chunk, entities)) => { chunk_map.set_chunk_at(pos, chunk); @@ -86,8 +86,7 @@ impl<'a> System<'a> for ChunkLoadSystem { let event = ChunkLoadFailEvent { pos }; fail_events.single_write(event); } - }, - _ => (), + } } } } diff --git a/server/src/chunkworker.rs b/server/src/chunkworker.rs index 98b996e0a..358a5b799 100644 --- a/server/src/chunkworker.rs +++ b/server/src/chunkworker.rs @@ -16,6 +16,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::{SystemTime, UNIX_EPOCH}; +#[allow(clippy::large_enum_variant)] pub enum Reply { LoadedChunk(ChunkPosition, Result<(Chunk, Vec), Error>), SavedChunk(ChunkPosition), diff --git a/server/src/lib.rs b/server/src/lib.rs index 64421f56d..0ec421c94 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -154,31 +154,9 @@ pub fn main() { info!("Shutting down"); info!("Saving chunks"); - let mut chunk_map = world.fetch_mut::(); - let handle = world.fetch::(); - let count = entity::save_chunks(&mut chunk_map, &handle); - - handle.sender.send(chunkworker::Request::ShutDown).unwrap(); - - let mut saved = 0; - // Wait for chunks to finish saving - while let Ok(msg) = handle.receiver.recv() { - match msg { - chunkworker::Reply::SavedChunk(_) => saved += 1, - _ => (), - } - - if saved == count { - break; - } - } - - assert!( - count == saved, - "didn't save all chunks: {} != {}", - count, - saved - ); + shutdown::save_chunks(&world); + info!("Saving level.dat"); + shutdown::save_level(&world); info!("Goodbye"); } @@ -303,7 +281,7 @@ fn load_spawn_chunks(world: &mut World) { /// is shut down. fn run_loop(world: &mut World, dispatcher: &mut Dispatcher, shutdown_rx: Receiver<()>) { loop { - if let Ok(_) = shutdown_rx.try_recv() { + if shutdown_rx.try_recv().is_ok() { // Shut down return; } diff --git a/server/src/shutdown.rs b/server/src/shutdown.rs index 4b18d3823..5975b148c 100644 --- a/server/src/shutdown.rs +++ b/server/src/shutdown.rs @@ -1,6 +1,15 @@ //! Shutdown behavior. +use crate::chunk_logic::ChunkWorkerHandle; +use crate::config::Config; +use crate::time::Time; +use crate::{chunkworker, entity}; use crossbeam::Sender; +use feather_core::level::{save_level_file, LevelData, Root}; +use feather_core::prelude::ChunkMap; +use specs::World; +use std::fs::File; +use std::sync::Arc; pub fn init(tx: Sender<()>) { ctrlc::set_handler(move || { @@ -8,3 +17,46 @@ pub fn init(tx: Sender<()>) { }) .unwrap(); } + +pub fn save_chunks(world: &World) { + let mut chunk_map = world.fetch_mut::(); + let handle = world.fetch::(); + let count = entity::save_chunks(&mut chunk_map, &handle); + + handle.sender.send(chunkworker::Request::ShutDown).unwrap(); + + let mut saved = 0; + // Wait for chunks to finish saving + while let Ok(msg) = handle.receiver.recv() { + if let chunkworker::Reply::SavedChunk(_) = msg { + saved += 1; + } + + if saved == count { + break; + } + } + + assert!( + count == saved, + "didn't save all chunks: {} != {}", + count, + saved + ); +} + +pub fn save_level(world: &World) { + let mut level = (*world.fetch::()).clone(); + + // Sync world time + level time + let time = world.fetch::