voxel-framework 0.12.2

A reusable voxel engine framework built on Bevy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! Chunk persistence integration — auto-save and disk-backed load.
//!
//! This module wires the low-level [`chunk::persistence`](crate::chunk::persistence) I/O into the Bevy
//! game loop via two pieces:
//!
//! - [`PersistenceConfig`] — a [`Resource`] that controls where chunk files
//!   live on disk and whether auto-save is enabled.
//! - [`chunk_autosave_system`] — listens for [`ChunkModified`] messages and
//!   saves the affected chunk to disk when [`PersistenceConfig::auto_save`] is
//!   `true` and the chunk has unsaved changes.
//! - [`try_load_chunk`] — a free function (not a system) that attempts to load
//!   a chunk from disk; the generator pipeline calls it from its background
//!   task before falling back to generation.
//!
//! ## What gets written
//!
//! Only chunks whose data changed are saved ([`Chunk::is_dirty`]). Generated
//! and restored chunks start clean, so [`ChunkModified`] messages that only
//! ask for a remesh (first mesh, neighbour borders, LOD changes) write nothing.
//! A chunk that is still dirty when it streams out is saved on unload by
//! [`chunk_despawn_system`](crate::mesh::chunk_despawn_system).

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};

// ─── WorldDataDir ─────────────────────────────────────────────────────────────

/// Resource that holds the base data directory for the active world.
///
/// Set automatically by [`PersistencePlugin::with_world`] and
/// [`PlayerPlugin::with_world`](crate::player::PlayerPlugin::with_world).  All world-specific files (chunks,
/// `player_data.json`) are stored under this path:
///
/// ```text
/// ./worlds/{world_name}/
///   ├── chunks/
///   │   └── chunk_X_Y_Z.bin
///   └── player_data.json
/// ```
///
/// The default value (`"./worlds/world"`) matches the default world name.
#[derive(Resource, Clone, Debug)]
pub struct WorldDataDir(pub String);

impl Default for WorldDataDir {
    fn default() -> Self {
        Self("./worlds/world".to_string())
    }
}

impl WorldDataDir {
    /// Creates a `WorldDataDir` for the given world name.
    pub fn for_world(world_name: &str) -> Self {
        Self(format!("./worlds/{}", world_name))
    }
    /// Returns the directory path as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

// ─── PersistenceConfig ────────────────────────────────────────────────────────

/// Configuration resource that controls chunk persistence behaviour.
///
/// Insert this resource before or after adding [`PersistencePlugin`] to
/// override the defaults.
///
/// # Example
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::world::PersistenceConfig;
///
/// App::new()
///     .insert_resource(PersistenceConfig {
///         save_dir: "./saves/chunks".to_string(),
///         auto_save: true,
///     });
/// ```
#[derive(Resource, Debug, Clone)]
pub struct PersistenceConfig {
    /// Directory where chunk binary files are stored.
    ///
    /// The directory is created automatically (including all parent
    /// directories) the first time a chunk is saved.
    ///
    /// Default: `"./worlds/world/chunks"`.
    pub save_dir: String,

    /// When `true`, chunks with unsaved changes are written to disk: on the
    /// [`ChunkModified`] message that follows an edit, and when the chunk is
    /// unloaded. Unmodified chunks are never written.
    ///
    /// Default: `true`.
    pub auto_save: bool,
}

impl Default for PersistenceConfig {
    fn default() -> Self {
        Self {
            save_dir: "./worlds/world/chunks".to_string(),
            auto_save: true,
        }
    }
}

// ─── try_load_chunk ───────────────────────────────────────────────────────────

/// Attempts to load a chunk from disk.
///
/// Constructs the expected file path from `save_dir` and `coord`, then tries
/// to read and deserialise it via [`load_chunk`](crate::chunk::persistence::load_chunk).
///
/// Returns `Some(chunk)` on success, `None` if the file does not exist or
/// cannot be read. The returned chunk is clean ([`Chunk::is_dirty`] is
/// `false`): it matches its file, so it is not written again until edited.
///
/// Does blocking file I/O. The generator pipeline calls it from a background
/// task.
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()
}

/// Writes `chunk` to its file under `save_dir`, creating the directory first.
///
/// Returns `true` when the chunk is on disk. Failures are reported with
/// `eprintln!`; `context` says which path triggered the save.
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
        }
    }
}

// ─── chunk_autosave_system ────────────────────────────────────────────────────

/// Saves modified chunks to disk when [`PersistenceConfig::auto_save`] is enabled.
///
/// For each [`ChunkModified`] message this system:
/// 1. Resolves the chunk entity from [`ChunkManager`].
/// 2. Skips the chunk unless it has unsaved changes ([`Chunk::is_dirty`]).
///    [`ChunkModified`] is also sent when a chunk only needs a new mesh, and
///    those chunks have nothing to save.
/// 3. Ensures the save directory exists and writes the chunk via
///    [`save_chunk`](crate::chunk::persistence::save_chunk).
/// 4. Marks the chunk clean, so it is not written again until the next edit.
///
/// Errors are reported with `eprintln!` and do not panic. A chunk whose save
/// failed stays dirty and is retried on its next [`ChunkModified`] or when it
/// is unloaded.
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, "") {
            // Clearing the flag is bookkeeping, not a data change.
            chunk.bypass_change_detection().mark_clean();
        }
    }
}

// ─── PersistencePlugin ────────────────────────────────────────────────────────

/// Plugin that registers [`PersistenceConfig`] and the auto-save system.
///
/// The plugin is generic over the voxel type `V` so it can operate on any
/// [`Chunk<V>`] component.
///
/// Users who want the default [`DefaultVoxel`] pipeline can add
/// [`PersistencePlugin::<DefaultVoxel>::new()`].  Users with a custom voxel
/// type add `PersistencePlugin::<MyVoxel>::new()`.
///
/// [`DefaultVoxel`]: crate::voxel::DefaultVoxel
///
/// # Example
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::world::{PersistenceConfig, PersistencePlugin};
/// use voxel_framework::voxel::DefaultVoxel;
///
/// App::new()
///     .add_plugins(PersistencePlugin::<DefaultVoxel>::new());
/// ```
pub struct PersistencePlugin<V: VoxelType> {
    _marker: std::marker::PhantomData<V>,
    world_name: String,
}

impl<V: VoxelType> PersistencePlugin<V> {
    /// Creates a `PersistencePlugin` using the default world name (`"world"`).
    pub fn new() -> Self {
        Self {
            _marker: std::marker::PhantomData,
            world_name: String::new(),
        }
    }

    /// Creates a `PersistencePlugin` that saves chunks under
    /// `./worlds/{world_name}/chunks/`.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use bevy::prelude::*;
    /// use voxel_framework::world::PersistencePlugin;
    /// use voxel_framework::voxel::DefaultVoxel;
    ///
    /// App::new().add_plugins(PersistencePlugin::<DefaultVoxel>::with_world("survival"));
    /// ```
    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
    }

    /// App with only the autosave system, one loaded chunk at `coord`, and
    /// chunk files written under `save_dir`.
    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);

        // A remesh-only notification: the data did not change.
        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();
        // The save "directory" is a regular file, so every write fails.
        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");
    }
}