1use std::path::PathBuf;
24
25use bevy::prelude::*;
26
27use crate::chunk::{Chunk, ChunkCoord, persistence as chunk_persistence};
28use crate::voxel::VoxelType;
29use crate::world::{ChunkManager, ChunkModified};
30
31#[derive(Resource, Clone, Debug)]
48pub struct WorldDataDir(pub String);
49
50impl Default for WorldDataDir {
51 fn default() -> Self {
52 Self("./worlds/world".to_string())
53 }
54}
55
56impl WorldDataDir {
57 pub fn for_world(world_name: &str) -> Self {
59 Self(format!("./worlds/{}", world_name))
60 }
61 pub fn as_str(&self) -> &str {
63 &self.0
64 }
65}
66
67#[derive(Resource, Debug, Clone)]
87pub struct PersistenceConfig {
88 pub save_dir: String,
95
96 pub auto_save: bool,
102}
103
104impl Default for PersistenceConfig {
105 fn default() -> Self {
106 Self {
107 save_dir: "./worlds/world/chunks".to_string(),
108 auto_save: true,
109 }
110 }
111}
112
113pub fn try_load_chunk<V: VoxelType>(coord: ChunkCoord, save_dir: &str) -> Option<Chunk<V>> {
127 let mut chunk = chunk_persistence::load_chunk::<V>(chunk_path(coord, save_dir)).ok()?;
128 chunk.mark_clean();
129 Some(chunk)
130}
131
132fn chunk_path(coord: ChunkCoord, save_dir: &str) -> PathBuf {
133 let filename = chunk_persistence::chunk_filename(coord);
134 [save_dir, &filename].iter().collect()
135}
136
137pub(crate) fn save_chunk_to_dir<V: VoxelType>(
142 chunk: &Chunk<V>,
143 coord: ChunkCoord,
144 save_dir: &str,
145 context: &str,
146) -> bool {
147 let path = chunk_path(coord, save_dir);
148
149 if let Some(parent) = path.parent()
150 && let Err(e) = std::fs::create_dir_all(parent)
151 {
152 eprintln!(
153 "voxel-framework: failed to create chunk save directory '{}': {e}",
154 parent.display()
155 );
156 return false;
157 }
158
159 match chunk_persistence::save_chunk(chunk, &path) {
160 Ok(()) => true,
161 Err(e) => {
162 eprintln!(
163 "voxel-framework: failed to save chunk {coord}{context} to '{}': {e}",
164 path.display()
165 );
166 false
167 }
168 }
169}
170
171pub fn chunk_autosave_system<V: VoxelType>(
188 mut modified_reader: MessageReader<ChunkModified>,
189 config: Res<PersistenceConfig>,
190 manager: Res<ChunkManager>,
191 mut chunks: Query<&mut Chunk<V>>,
192) {
193 if !config.auto_save {
194 return;
195 }
196
197 for &ChunkModified(coord) in modified_reader.read() {
198 let Some(entity) = manager.get_entity(coord) else {
199 continue;
200 };
201
202 let Ok(mut chunk) = chunks.get_mut(entity) else {
203 continue;
204 };
205
206 if !chunk.is_dirty() {
207 continue;
208 }
209
210 if save_chunk_to_dir(&*chunk, coord, &config.save_dir, "") {
211 chunk.bypass_change_detection().mark_clean();
213 }
214 }
215}
216
217pub struct PersistencePlugin<V: VoxelType> {
241 _marker: std::marker::PhantomData<V>,
242 world_name: String,
243}
244
245impl<V: VoxelType> PersistencePlugin<V> {
246 pub fn new() -> Self {
248 Self {
249 _marker: std::marker::PhantomData,
250 world_name: String::new(),
251 }
252 }
253
254 pub fn with_world(world_name: impl Into<String>) -> Self {
267 Self {
268 _marker: std::marker::PhantomData,
269 world_name: world_name.into(),
270 }
271 }
272}
273
274impl<V: VoxelType> Default for PersistencePlugin<V> {
275 fn default() -> Self {
276 Self::new()
277 }
278}
279
280impl<V: VoxelType> Plugin for PersistencePlugin<V> {
281 fn build(&self, app: &mut App) {
282 let name = if self.world_name.is_empty() {
283 "world"
284 } else {
285 &self.world_name
286 };
287 let save_dir = format!("./worlds/{}/chunks", name);
288 app.insert_resource(PersistenceConfig {
289 save_dir,
290 auto_save: true,
291 });
292 app.add_systems(Update, chunk_autosave_system::<V>);
293 }
294}
295
296#[cfg(test)]
297mod tests {
298 use super::*;
299 use crate::chunk::persistence::{chunk_filename, save_chunk};
300 use crate::voxel::DefaultVoxel;
301
302 fn chunk_with_marker() -> Chunk<DefaultVoxel> {
303 let mut chunk = Chunk::new();
304 chunk.set(3, 4, 5, DefaultVoxel::IronOre);
305 chunk.set_state(3, 4, 5, 7);
306 chunk
307 }
308
309 fn autosave_app(coord: IVec3, save_dir: &std::path::Path, auto_save: bool) -> App {
312 let mut app = App::new();
313 app.add_message::<ChunkModified>();
314 app.insert_resource(PersistenceConfig {
315 save_dir: save_dir.to_string_lossy().into_owned(),
316 auto_save,
317 });
318 let entity = app.world_mut().spawn(chunk_with_marker()).id();
319 let mut manager = ChunkManager::default();
320 manager.register(coord, entity);
321 app.insert_resource(manager);
322 app.add_systems(Update, chunk_autosave_system::<DefaultVoxel>);
323 app
324 }
325
326 #[test]
327 fn try_load_chunk_returns_none_when_file_is_missing() {
328 let dir = tempfile::tempdir().unwrap();
329 let loaded = try_load_chunk::<DefaultVoxel>(IVec3::ZERO, dir.path().to_str().unwrap());
330 assert!(loaded.is_none());
331 }
332
333 #[test]
334 fn try_load_chunk_reads_saved_chunk_with_negative_coord() {
335 let dir = tempfile::tempdir().unwrap();
336 let coord = IVec3::new(-3, 0, 12);
337 save_chunk(&chunk_with_marker(), dir.path().join(chunk_filename(coord))).unwrap();
338
339 let loaded = try_load_chunk::<DefaultVoxel>(coord, dir.path().to_str().unwrap())
340 .expect("saved chunk should load");
341 assert_eq!(loaded.get(3, 4, 5), DefaultVoxel::IronOre);
342 assert_eq!(loaded.get_state(3, 4, 5), 7);
343 }
344
345 #[test]
346 fn autosave_writes_modified_chunk_and_creates_missing_dirs() {
347 let dir = tempfile::tempdir().unwrap();
348 let save_dir = dir.path().join("nested").join("chunks");
349 let coord = IVec3::new(1, -2, 3);
350 let mut app = autosave_app(coord, &save_dir, true);
351
352 app.world_mut().write_message(ChunkModified(coord));
353 app.update();
354
355 let loaded = try_load_chunk::<DefaultVoxel>(coord, save_dir.to_str().unwrap())
356 .expect("autosave should have written the chunk");
357 assert_eq!(loaded.get(3, 4, 5), DefaultVoxel::IronOre);
358 assert_eq!(loaded.get_state(3, 4, 5), 7);
359 }
360
361 #[test]
362 fn autosave_disabled_writes_nothing() {
363 let dir = tempfile::tempdir().unwrap();
364 let mut app = autosave_app(IVec3::ZERO, dir.path(), false);
365
366 app.world_mut().write_message(ChunkModified(IVec3::ZERO));
367 app.update();
368
369 assert!(!dir.path().join(chunk_filename(IVec3::ZERO)).exists());
370 }
371
372 #[test]
373 fn autosave_skips_chunks_that_are_not_loaded() {
374 let dir = tempfile::tempdir().unwrap();
375 let mut app = autosave_app(IVec3::ZERO, dir.path(), true);
376 let unloaded = IVec3::new(9, 9, 9);
377
378 app.world_mut().write_message(ChunkModified(unloaded));
379 app.update();
380
381 assert!(!dir.path().join(chunk_filename(unloaded)).exists());
382 }
383
384 fn chunk_at(app: &App, coord: IVec3) -> &Chunk<DefaultVoxel> {
385 let entity = app
386 .world()
387 .resource::<ChunkManager>()
388 .get_entity(coord)
389 .expect("chunk is registered");
390 app.world().get::<Chunk<DefaultVoxel>>(entity).unwrap()
391 }
392
393 fn mark_clean(app: &mut App, coord: IVec3) {
394 let entity = app
395 .world()
396 .resource::<ChunkManager>()
397 .get_entity(coord)
398 .expect("chunk is registered");
399 app.world_mut()
400 .get_mut::<Chunk<DefaultVoxel>>(entity)
401 .unwrap()
402 .mark_clean();
403 }
404
405 #[test]
406 fn try_load_chunk_returns_a_clean_chunk() {
407 let dir = tempfile::tempdir().unwrap();
408 save_chunk(
409 &chunk_with_marker(),
410 dir.path().join(chunk_filename(IVec3::ZERO)),
411 )
412 .unwrap();
413
414 let loaded =
415 try_load_chunk::<DefaultVoxel>(IVec3::ZERO, dir.path().to_str().unwrap()).unwrap();
416
417 assert!(!loaded.is_dirty(), "a restored chunk matches its file");
418 }
419
420 #[test]
421 fn autosave_skips_a_chunk_without_unsaved_changes() {
422 let dir = tempfile::tempdir().unwrap();
423 let mut app = autosave_app(IVec3::ZERO, dir.path(), true);
424 mark_clean(&mut app, IVec3::ZERO);
425
426 app.world_mut().write_message(ChunkModified(IVec3::ZERO));
428 app.update();
429
430 assert!(!dir.path().join(chunk_filename(IVec3::ZERO)).exists());
431 }
432
433 #[test]
434 fn autosave_marks_the_chunk_clean_and_does_not_write_it_again() {
435 let dir = tempfile::tempdir().unwrap();
436 let file = dir.path().join(chunk_filename(IVec3::ZERO));
437 let mut app = autosave_app(IVec3::ZERO, dir.path(), true);
438
439 app.world_mut().write_message(ChunkModified(IVec3::ZERO));
440 app.update();
441 assert!(file.is_file());
442 assert!(!chunk_at(&app, IVec3::ZERO).is_dirty());
443
444 std::fs::remove_file(&file).unwrap();
445 app.world_mut().write_message(ChunkModified(IVec3::ZERO));
446 app.update();
447 assert!(!file.exists(), "an unchanged chunk must not be rewritten");
448 }
449
450 #[test]
451 fn autosave_failure_keeps_the_chunk_dirty() {
452 let dir = tempfile::tempdir().unwrap();
453 let blocked = dir.path().join("not-a-directory");
455 std::fs::write(&blocked, b"x").unwrap();
456 let mut app = autosave_app(IVec3::ZERO, &blocked, true);
457
458 app.world_mut().write_message(ChunkModified(IVec3::ZERO));
459 app.update();
460
461 assert!(
462 chunk_at(&app, IVec3::ZERO).is_dirty(),
463 "a failed save must be retried later"
464 );
465 }
466
467 #[test]
468 fn plugin_save_dir_follows_world_name() {
469 let mut app = App::new();
470 app.add_plugins(PersistencePlugin::<DefaultVoxel>::with_world("survival"));
471 let config = app.world().resource::<PersistenceConfig>();
472 assert_eq!(config.save_dir, "./worlds/survival/chunks");
473 assert!(config.auto_save);
474
475 let mut app = App::new();
476 app.add_plugins(PersistencePlugin::<DefaultVoxel>::new());
477 assert_eq!(
478 app.world().resource::<PersistenceConfig>().save_dir,
479 PersistenceConfig::default().save_dir
480 );
481 }
482
483 #[test]
484 fn world_data_dir_for_world() {
485 assert_eq!(WorldDataDir::for_world("alpha").as_str(), "./worlds/alpha");
486 assert_eq!(WorldDataDir::default().as_str(), "./worlds/world");
487 }
488}