use std::path::PathBuf;
use bevy::prelude::*;
use crate::chunk::{Chunk, ChunkCoord, persistence as chunk_persistence};
use crate::voxel::VoxelType;
use crate::world::{ChunkManager, ChunkModified};
#[derive(Resource, Clone, Debug)]
pub struct WorldDataDir(pub String);
impl Default for WorldDataDir {
fn default() -> Self {
Self("./worlds/world".to_string())
}
}
impl WorldDataDir {
pub fn for_world(world_name: &str) -> Self {
Self(format!("./worlds/{}", world_name))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Resource, Debug, Clone)]
pub struct PersistenceConfig {
pub save_dir: String,
pub auto_save: bool,
}
impl Default for PersistenceConfig {
fn default() -> Self {
Self {
save_dir: "./worlds/world/chunks".to_string(),
auto_save: true,
}
}
}
pub fn try_load_chunk<V: VoxelType>(coord: ChunkCoord, save_dir: &str) -> Option<Chunk<V>> {
let mut chunk = chunk_persistence::load_chunk::<V>(chunk_path(coord, save_dir)).ok()?;
chunk.mark_clean();
Some(chunk)
}
fn chunk_path(coord: ChunkCoord, save_dir: &str) -> PathBuf {
let filename = chunk_persistence::chunk_filename(coord);
[save_dir, &filename].iter().collect()
}
pub(crate) fn save_chunk_to_dir<V: VoxelType>(
chunk: &Chunk<V>,
coord: ChunkCoord,
save_dir: &str,
context: &str,
) -> bool {
let path = chunk_path(coord, save_dir);
if let Some(parent) = path.parent()
&& let Err(e) = std::fs::create_dir_all(parent)
{
eprintln!(
"voxel-framework: failed to create chunk save directory '{}': {e}",
parent.display()
);
return false;
}
match chunk_persistence::save_chunk(chunk, &path) {
Ok(()) => true,
Err(e) => {
eprintln!(
"voxel-framework: failed to save chunk {coord}{context} to '{}': {e}",
path.display()
);
false
}
}
}
pub fn chunk_autosave_system<V: VoxelType>(
mut modified_reader: MessageReader<ChunkModified>,
config: Res<PersistenceConfig>,
manager: Res<ChunkManager>,
mut chunks: Query<&mut Chunk<V>>,
) {
if !config.auto_save {
return;
}
for &ChunkModified(coord) in modified_reader.read() {
let Some(entity) = manager.get_entity(coord) else {
continue;
};
let Ok(mut chunk) = chunks.get_mut(entity) else {
continue;
};
if !chunk.is_dirty() {
continue;
}
if save_chunk_to_dir(&*chunk, coord, &config.save_dir, "") {
chunk.bypass_change_detection().mark_clean();
}
}
}
pub struct PersistencePlugin<V: VoxelType> {
_marker: std::marker::PhantomData<V>,
world_name: String,
}
impl<V: VoxelType> PersistencePlugin<V> {
pub fn new() -> Self {
Self {
_marker: std::marker::PhantomData,
world_name: String::new(),
}
}
pub fn with_world(world_name: impl Into<String>) -> Self {
Self {
_marker: std::marker::PhantomData,
world_name: world_name.into(),
}
}
}
impl<V: VoxelType> Default for PersistencePlugin<V> {
fn default() -> Self {
Self::new()
}
}
impl<V: VoxelType> Plugin for PersistencePlugin<V> {
fn build(&self, app: &mut App) {
let name = if self.world_name.is_empty() {
"world"
} else {
&self.world_name
};
let save_dir = format!("./worlds/{}/chunks", name);
app.insert_resource(PersistenceConfig {
save_dir,
auto_save: true,
});
app.add_systems(Update, chunk_autosave_system::<V>);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::chunk::persistence::{chunk_filename, save_chunk};
use crate::voxel::DefaultVoxel;
fn chunk_with_marker() -> Chunk<DefaultVoxel> {
let mut chunk = Chunk::new();
chunk.set(3, 4, 5, DefaultVoxel::IronOre);
chunk.set_state(3, 4, 5, 7);
chunk
}
fn autosave_app(coord: IVec3, save_dir: &std::path::Path, auto_save: bool) -> App {
let mut app = App::new();
app.add_message::<ChunkModified>();
app.insert_resource(PersistenceConfig {
save_dir: save_dir.to_string_lossy().into_owned(),
auto_save,
});
let entity = app.world_mut().spawn(chunk_with_marker()).id();
let mut manager = ChunkManager::default();
manager.register(coord, entity);
app.insert_resource(manager);
app.add_systems(Update, chunk_autosave_system::<DefaultVoxel>);
app
}
#[test]
fn try_load_chunk_returns_none_when_file_is_missing() {
let dir = tempfile::tempdir().unwrap();
let loaded = try_load_chunk::<DefaultVoxel>(IVec3::ZERO, dir.path().to_str().unwrap());
assert!(loaded.is_none());
}
#[test]
fn try_load_chunk_reads_saved_chunk_with_negative_coord() {
let dir = tempfile::tempdir().unwrap();
let coord = IVec3::new(-3, 0, 12);
save_chunk(&chunk_with_marker(), dir.path().join(chunk_filename(coord))).unwrap();
let loaded = try_load_chunk::<DefaultVoxel>(coord, dir.path().to_str().unwrap())
.expect("saved chunk should load");
assert_eq!(loaded.get(3, 4, 5), DefaultVoxel::IronOre);
assert_eq!(loaded.get_state(3, 4, 5), 7);
}
#[test]
fn autosave_writes_modified_chunk_and_creates_missing_dirs() {
let dir = tempfile::tempdir().unwrap();
let save_dir = dir.path().join("nested").join("chunks");
let coord = IVec3::new(1, -2, 3);
let mut app = autosave_app(coord, &save_dir, true);
app.world_mut().write_message(ChunkModified(coord));
app.update();
let loaded = try_load_chunk::<DefaultVoxel>(coord, save_dir.to_str().unwrap())
.expect("autosave should have written the chunk");
assert_eq!(loaded.get(3, 4, 5), DefaultVoxel::IronOre);
assert_eq!(loaded.get_state(3, 4, 5), 7);
}
#[test]
fn autosave_disabled_writes_nothing() {
let dir = tempfile::tempdir().unwrap();
let mut app = autosave_app(IVec3::ZERO, dir.path(), false);
app.world_mut().write_message(ChunkModified(IVec3::ZERO));
app.update();
assert!(!dir.path().join(chunk_filename(IVec3::ZERO)).exists());
}
#[test]
fn autosave_skips_chunks_that_are_not_loaded() {
let dir = tempfile::tempdir().unwrap();
let mut app = autosave_app(IVec3::ZERO, dir.path(), true);
let unloaded = IVec3::new(9, 9, 9);
app.world_mut().write_message(ChunkModified(unloaded));
app.update();
assert!(!dir.path().join(chunk_filename(unloaded)).exists());
}
fn chunk_at(app: &App, coord: IVec3) -> &Chunk<DefaultVoxel> {
let entity = app
.world()
.resource::<ChunkManager>()
.get_entity(coord)
.expect("chunk is registered");
app.world().get::<Chunk<DefaultVoxel>>(entity).unwrap()
}
fn mark_clean(app: &mut App, coord: IVec3) {
let entity = app
.world()
.resource::<ChunkManager>()
.get_entity(coord)
.expect("chunk is registered");
app.world_mut()
.get_mut::<Chunk<DefaultVoxel>>(entity)
.unwrap()
.mark_clean();
}
#[test]
fn try_load_chunk_returns_a_clean_chunk() {
let dir = tempfile::tempdir().unwrap();
save_chunk(
&chunk_with_marker(),
dir.path().join(chunk_filename(IVec3::ZERO)),
)
.unwrap();
let loaded =
try_load_chunk::<DefaultVoxel>(IVec3::ZERO, dir.path().to_str().unwrap()).unwrap();
assert!(!loaded.is_dirty(), "a restored chunk matches its file");
}
#[test]
fn autosave_skips_a_chunk_without_unsaved_changes() {
let dir = tempfile::tempdir().unwrap();
let mut app = autosave_app(IVec3::ZERO, dir.path(), true);
mark_clean(&mut app, IVec3::ZERO);
app.world_mut().write_message(ChunkModified(IVec3::ZERO));
app.update();
assert!(!dir.path().join(chunk_filename(IVec3::ZERO)).exists());
}
#[test]
fn autosave_marks_the_chunk_clean_and_does_not_write_it_again() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join(chunk_filename(IVec3::ZERO));
let mut app = autosave_app(IVec3::ZERO, dir.path(), true);
app.world_mut().write_message(ChunkModified(IVec3::ZERO));
app.update();
assert!(file.is_file());
assert!(!chunk_at(&app, IVec3::ZERO).is_dirty());
std::fs::remove_file(&file).unwrap();
app.world_mut().write_message(ChunkModified(IVec3::ZERO));
app.update();
assert!(!file.exists(), "an unchanged chunk must not be rewritten");
}
#[test]
fn autosave_failure_keeps_the_chunk_dirty() {
let dir = tempfile::tempdir().unwrap();
let blocked = dir.path().join("not-a-directory");
std::fs::write(&blocked, b"x").unwrap();
let mut app = autosave_app(IVec3::ZERO, &blocked, true);
app.world_mut().write_message(ChunkModified(IVec3::ZERO));
app.update();
assert!(
chunk_at(&app, IVec3::ZERO).is_dirty(),
"a failed save must be retried later"
);
}
#[test]
fn plugin_save_dir_follows_world_name() {
let mut app = App::new();
app.add_plugins(PersistencePlugin::<DefaultVoxel>::with_world("survival"));
let config = app.world().resource::<PersistenceConfig>();
assert_eq!(config.save_dir, "./worlds/survival/chunks");
assert!(config.auto_save);
let mut app = App::new();
app.add_plugins(PersistencePlugin::<DefaultVoxel>::new());
assert_eq!(
app.world().resource::<PersistenceConfig>().save_dir,
PersistenceConfig::default().save_dir
);
}
#[test]
fn world_data_dir_for_world() {
assert_eq!(WorldDataDir::for_world("alpha").as_str(), "./worlds/alpha");
assert_eq!(WorldDataDir::default().as_str(), "./worlds/world");
}
}