Skip to main content

voxel_framework/world/
persistence.rs

1//! Chunk persistence integration — auto-save and disk-backed load.
2//!
3//! This module wires the low-level [`chunk::persistence`](crate::chunk::persistence) I/O into the Bevy
4//! game loop via two pieces:
5//!
6//! - [`PersistenceConfig`] — a [`Resource`] that controls where chunk files
7//!   live on disk and whether auto-save is enabled.
8//! - [`chunk_autosave_system`] — listens for [`ChunkModified`] messages and
9//!   saves the affected chunk to disk when [`PersistenceConfig::auto_save`] is
10//!   `true` and the chunk has unsaved changes.
11//! - [`try_load_chunk`] — a free function (not a system) that attempts to load
12//!   a chunk from disk; the generator pipeline calls it from its background
13//!   task before falling back to generation.
14//!
15//! ## What gets written
16//!
17//! Only chunks whose data changed are saved ([`Chunk::is_dirty`]). Generated
18//! and restored chunks start clean, so [`ChunkModified`] messages that only
19//! ask for a remesh (first mesh, neighbour borders, LOD changes) write nothing.
20//! A chunk that is still dirty when it streams out is saved on unload by
21//! [`chunk_despawn_system`](crate::mesh::chunk_despawn_system).
22
23use 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// ─── WorldDataDir ─────────────────────────────────────────────────────────────
32
33/// Resource that holds the base data directory for the active world.
34///
35/// Set automatically by [`PersistencePlugin::with_world`] and
36/// [`PlayerPlugin::with_world`](crate::player::PlayerPlugin::with_world).  All world-specific files (chunks,
37/// `player_data.json`) are stored under this path:
38///
39/// ```text
40/// ./worlds/{world_name}/
41///   ├── chunks/
42///   │   └── chunk_X_Y_Z.bin
43///   └── player_data.json
44/// ```
45///
46/// The default value (`"./worlds/world"`) matches the default world name.
47#[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    /// Creates a `WorldDataDir` for the given world name.
58    pub fn for_world(world_name: &str) -> Self {
59        Self(format!("./worlds/{}", world_name))
60    }
61    /// Returns the directory path as a string slice.
62    pub fn as_str(&self) -> &str {
63        &self.0
64    }
65}
66
67// ─── PersistenceConfig ────────────────────────────────────────────────────────
68
69/// Configuration resource that controls chunk persistence behaviour.
70///
71/// Insert this resource before or after adding [`PersistencePlugin`] to
72/// override the defaults.
73///
74/// # Example
75///
76/// ```rust,no_run
77/// use bevy::prelude::*;
78/// use voxel_framework::world::PersistenceConfig;
79///
80/// App::new()
81///     .insert_resource(PersistenceConfig {
82///         save_dir: "./saves/chunks".to_string(),
83///         auto_save: true,
84///     });
85/// ```
86#[derive(Resource, Debug, Clone)]
87pub struct PersistenceConfig {
88    /// Directory where chunk binary files are stored.
89    ///
90    /// The directory is created automatically (including all parent
91    /// directories) the first time a chunk is saved.
92    ///
93    /// Default: `"./worlds/world/chunks"`.
94    pub save_dir: String,
95
96    /// When `true`, chunks with unsaved changes are written to disk: on the
97    /// [`ChunkModified`] message that follows an edit, and when the chunk is
98    /// unloaded. Unmodified chunks are never written.
99    ///
100    /// Default: `true`.
101    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
113// ─── try_load_chunk ───────────────────────────────────────────────────────────
114
115/// Attempts to load a chunk from disk.
116///
117/// Constructs the expected file path from `save_dir` and `coord`, then tries
118/// to read and deserialise it via [`load_chunk`](crate::chunk::persistence::load_chunk).
119///
120/// Returns `Some(chunk)` on success, `None` if the file does not exist or
121/// cannot be read. The returned chunk is clean ([`Chunk::is_dirty`] is
122/// `false`): it matches its file, so it is not written again until edited.
123///
124/// Does blocking file I/O. The generator pipeline calls it from a background
125/// task.
126pub 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
137/// Writes `chunk` to its file under `save_dir`, creating the directory first.
138///
139/// Returns `true` when the chunk is on disk. Failures are reported with
140/// `eprintln!`; `context` says which path triggered the save.
141pub(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
171// ─── chunk_autosave_system ────────────────────────────────────────────────────
172
173/// Saves modified chunks to disk when [`PersistenceConfig::auto_save`] is enabled.
174///
175/// For each [`ChunkModified`] message this system:
176/// 1. Resolves the chunk entity from [`ChunkManager`].
177/// 2. Skips the chunk unless it has unsaved changes ([`Chunk::is_dirty`]).
178///    [`ChunkModified`] is also sent when a chunk only needs a new mesh, and
179///    those chunks have nothing to save.
180/// 3. Ensures the save directory exists and writes the chunk via
181///    [`save_chunk`](crate::chunk::persistence::save_chunk).
182/// 4. Marks the chunk clean, so it is not written again until the next edit.
183///
184/// Errors are reported with `eprintln!` and do not panic. A chunk whose save
185/// failed stays dirty and is retried on its next [`ChunkModified`] or when it
186/// is unloaded.
187pub 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            // Clearing the flag is bookkeeping, not a data change.
212            chunk.bypass_change_detection().mark_clean();
213        }
214    }
215}
216
217// ─── PersistencePlugin ────────────────────────────────────────────────────────
218
219/// Plugin that registers [`PersistenceConfig`] and the auto-save system.
220///
221/// The plugin is generic over the voxel type `V` so it can operate on any
222/// [`Chunk<V>`] component.
223///
224/// Users who want the default [`DefaultVoxel`] pipeline can add
225/// [`PersistencePlugin::<DefaultVoxel>::new()`].  Users with a custom voxel
226/// type add `PersistencePlugin::<MyVoxel>::new()`.
227///
228/// [`DefaultVoxel`]: crate::voxel::DefaultVoxel
229///
230/// # Example
231///
232/// ```rust,no_run
233/// use bevy::prelude::*;
234/// use voxel_framework::world::{PersistenceConfig, PersistencePlugin};
235/// use voxel_framework::voxel::DefaultVoxel;
236///
237/// App::new()
238///     .add_plugins(PersistencePlugin::<DefaultVoxel>::new());
239/// ```
240pub struct PersistencePlugin<V: VoxelType> {
241    _marker: std::marker::PhantomData<V>,
242    world_name: String,
243}
244
245impl<V: VoxelType> PersistencePlugin<V> {
246    /// Creates a `PersistencePlugin` using the default world name (`"world"`).
247    pub fn new() -> Self {
248        Self {
249            _marker: std::marker::PhantomData,
250            world_name: String::new(),
251        }
252    }
253
254    /// Creates a `PersistencePlugin` that saves chunks under
255    /// `./worlds/{world_name}/chunks/`.
256    ///
257    /// # Example
258    ///
259    /// ```rust,no_run
260    /// use bevy::prelude::*;
261    /// use voxel_framework::world::PersistencePlugin;
262    /// use voxel_framework::voxel::DefaultVoxel;
263    ///
264    /// App::new().add_plugins(PersistencePlugin::<DefaultVoxel>::with_world("survival"));
265    /// ```
266    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    /// App with only the autosave system, one loaded chunk at `coord`, and
310    /// chunk files written under `save_dir`.
311    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        // A remesh-only notification: the data did not change.
427        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        // The save "directory" is a regular file, so every write fails.
454        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}