voxel-framework 0.13.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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//! Initial world loading lifecycle — progress tracking and the ready signal.
//!
//! # Overview
//!
//! When a world first starts, the streaming system begins requesting chunks
//! around the viewer. This module tracks how many of those chunks have been
//! fully generated and meshed, and fires a one-shot signal when the world is
//! ready to display.
//!
//! # What "loaded" means
//!
//! A chunk is considered **loaded** when it is registered in [`ChunkManager`]
//! via [`ChunkManager::register`] — meaning voxel data has been generated
//! **and** the renderable mesh entity has been spawned. The chunks that count
//! are the ones the streaming system requests: those whose center is within
//! `load_distance` of the [`ViewerPosition`]. The total is counted from the
//! viewer's position each frame, so it follows a viewer that moves while the
//! world loads.
//!
//! # Event flow
//!
//! ```text
//! WorldPlugin starts
//!     │
//!     ▼
//! loading_progress_system runs each frame (after GeneratorSystems)
//!     │
//!     ├─ emits LoadingProgress { loaded, total, progress }  every frame
//!     │
//!     └─ when progress >= 1.0:
//!            emits WorldReady (once)
//!            sets WorldLoadingState::ready = true → system becomes a no-op
//! ```
//!
//! # Usage
//!
//! Add [`LoadingPlugin`] to your [`App`] alongside [`super::WorldPlugin`].
//! Subscribe to [`LoadingProgress`] to drive a loading screen, and to
//! [`WorldReady`] to transition out of it:
//!
//! ```rust,no_run
//! use bevy::prelude::*;
//! use voxel_framework::world::{WorldPlugin, LoadingPlugin, LoadingProgress, WorldReady};
//!
//! fn on_world_ready(mut reader: MessageReader<WorldReady>) {
//!     for _ in reader.read() {
//!         println!("world is ready!");
//!     }
//! }
//!
//! App::new()
//!     .add_plugins((WorldPlugin, LoadingPlugin))
//!     .add_systems(Update, on_world_ready)
//!     .run();
//! ```

use bevy::prelude::*;

use crate::generator::GeneratorSystems;
use crate::mesh::{MeshSystems, PendingChunkMeshes};

use super::systems::chunks_in_load_range;
use super::{ChunkManager, ViewerPosition};

// ─── Messages ────────────────────────────────────────────────────────────────

/// Emitted every frame while the initial chunk sphere is still loading.
///
/// [`loading_progress_system`] writes this message once per frame from the
/// moment the world starts until [`WorldReady`] fires. Once [`WorldReady`] has
/// been emitted, this message is no longer written.
///
/// - `total` — number of chunks in the load range: those whose center is
///   within `load_distance` of the [`ViewerPosition`] this frame. It can change
///   a little between frames if the viewer moves while the world loads.
/// - `loaded` — how many of those chunks are registered in [`ChunkManager`].
///   It never exceeds `total`; chunks loaded outside the range are not counted.
/// - `progress` — `loaded / total`, in `[0.0, 1.0]`.
///
/// # Example
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::world::LoadingProgress;
///
/// fn show_progress(mut reader: MessageReader<LoadingProgress>) {
///     for msg in reader.read() {
///         println!("loading: {:.0}%", msg.progress * 100.0);
///     }
/// }
/// ```
#[derive(Message, Debug, Clone)]
pub struct LoadingProgress {
    pub loaded: u32,
    pub total: u32,
    pub progress: f32,
}

/// One-shot signal emitted when the initial chunk sphere is fully loaded.
///
/// [`loading_progress_system`] emits this message exactly once, on the first
/// frame that [`LoadingProgress::progress`] has reached `1.0` and no chunk is
/// still waiting for its mesh (see [`PendingChunkMeshes`]). Without
/// [`MeshPlugin`](crate::mesh::MeshPlugin) there is no mesh queue and only the
/// progress counts; the same applies while the queue is stalled because no
/// chunk material exists. After it fires,
/// [`WorldLoadingState::ready`] is set to `true` and the progress system
/// becomes a no-op — no further [`LoadingProgress`] or `WorldReady` messages
/// are written.
///
/// Use this event to transition your app out of a loading screen, enable
/// gameplay input, or trigger any one-time "world is ready" logic.
///
/// # Example
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::world::WorldReady;
///
/// fn on_world_ready(mut reader: MessageReader<WorldReady>) {
///     for _ in reader.read() {
///         println!("all chunks generated — entering gameplay");
///     }
/// }
///
/// # fn main() {
/// App::new()
///     .add_message::<WorldReady>()
///     .add_systems(Update, on_world_ready)
///     .run();
/// # }
/// ```
#[derive(Message, Debug, Clone)]
pub struct WorldReady;

// ─── Resource ─────────────────────────────────────────────────────────────────

/// Internal resource that guards the one-shot [`WorldReady`] emission.
///
/// Inserted by [`LoadingPlugin`] via `init_resource`. [`loading_progress_system`]
/// reads and mutates this resource each frame:
///
/// - `expected` is the number of chunks in the load range around the viewer,
///   updated every frame until the world is ready.
/// - `ready` is set to `true` after [`WorldReady`] fires, turning the system
///   into a no-op for the remainder of the session.
///
/// This resource is not intended to be mutated by user code. To check whether
/// the world has finished loading, subscribe to [`WorldReady`] instead.
#[derive(Resource, Default)]
pub struct WorldLoadingState {
    /// Set to `true` after [`WorldReady`] has been emitted.
    pub ready: bool,
    /// Chunks in the load range around the viewer, as of the last frame before
    /// the world became ready.
    pub expected: u32,
}

// ─── Helpers (pure, testable) ─────────────────────────────────────────────────

/// Computes the loading progress fraction given `loaded` and `expected` counts.
/// Returns 0.0 when `expected` is 0 to avoid division by zero.
pub(crate) fn compute_progress(loaded: u32, expected: u32) -> f32 {
    if expected == 0 {
        0.0
    } else {
        (loaded as f32 / expected as f32).min(1.0)
    }
}

// ─── System ───────────────────────────────────────────────────────────────────

/// Tracks initial chunk loading and emits [`LoadingProgress`] and [`WorldReady`].
///
/// Scheduled in [`Update`], ordered after [`GeneratorSystems`] so that any
/// chunks completed in the current frame are already counted before progress
/// is computed.
///
/// Each frame it counts the chunks in the load range around the
/// [`ViewerPosition`] (the same chunks [`streaming_system`](super::systems::streaming_system)
/// requests) and how many of them are loaded, and stores the first count in
/// [`WorldLoadingState::expected`].
///
/// Once [`WorldLoadingState::ready`] is `true` (set after [`WorldReady`]
/// fires), the system returns immediately without writing any messages.
pub fn loading_progress_system(
    manager: Res<ChunkManager>,
    viewer: Res<ViewerPosition>,
    mut loading_state: ResMut<WorldLoadingState>,
    mut progress_writer: MessageWriter<LoadingProgress>,
    mut ready_writer: MessageWriter<WorldReady>,
    pending_meshes: Option<Res<PendingChunkMeshes>>,
) {
    if loading_state.ready {
        return;
    }

    let mut expected = 0u32;
    let mut loaded = 0u32;
    for coord in chunks_in_load_range(viewer.position, manager.load_distance) {
        expected += 1;
        if manager.is_loaded(coord) {
            loaded += 1;
        }
    }
    loading_state.expected = expected;
    let progress = compute_progress(loaded, expected);

    progress_writer.write(LoadingProgress {
        loaded,
        total: expected,
        progress,
    });

    // Chunks are meshed a bounded number per frame, so the last ones to load
    // can still be waiting for geometry. The world is ready once they have it.
    // A stalled queue (no chunk material) will never drain, so do not wait.
    let meshing_done =
        pending_meshes.is_none_or(|pending| pending.is_empty() || pending.is_stalled());

    // An empty load range has nothing to wait for.
    if loaded >= expected && meshing_done {
        ready_writer.write(WorldReady);
        loading_state.ready = true;
    }
}

// ─── Plugin ───────────────────────────────────────────────────────────────────

/// Plugin that tracks initial world loading and emits [`LoadingProgress`] and [`WorldReady`].
///
/// Registers the following on the Bevy [`App`]:
///
/// - [`WorldLoadingState`] resource (via `init_resource`).
/// - [`LoadingProgress`] and [`WorldReady`] messages.
/// - [`loading_progress_system`] scheduled in [`Update`] after [`GeneratorSystems`]
///   and [`MeshSystems`].
///
/// Must be used together with [`super::WorldPlugin`], which provides the
/// [`ChunkManager`] resource this plugin reads.
///
/// # Example
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::world::{WorldPlugin, LoadingPlugin, WorldReady};
///
/// fn on_ready(mut reader: MessageReader<WorldReady>) {
///     for _ in reader.read() {
///         println!("world ready — starting gameplay");
///     }
/// }
///
/// App::new()
///     .add_plugins((WorldPlugin, LoadingPlugin))
///     .add_systems(Update, on_ready)
///     .run();
/// ```
pub struct LoadingPlugin;

impl Plugin for LoadingPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<WorldLoadingState>();
        app.add_message::<LoadingProgress>();
        app.add_message::<WorldReady>();
        app.add_systems(
            Update,
            loading_progress_system
                .after(GeneratorSystems)
                .after(MeshSystems),
        );
    }
}

// ─── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::chunk::CHUNK_SIZE;

    #[test]
    fn test_loading_progress_zero_when_nothing_loaded() {
        // With nothing loaded, progress should be 0.0.
        let progress = compute_progress(0, 100);
        assert_eq!(progress, 0.0);
    }

    #[test]
    fn test_loading_progress_zero_when_expected_is_zero() {
        // Guard against division by zero when expected hasn't been computed yet.
        let progress = compute_progress(0, 0);
        assert_eq!(progress, 0.0);
    }

    #[test]
    fn test_loading_progress_partial() {
        let progress = compute_progress(50, 100);
        assert!((progress - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn test_loading_ready_when_fully_loaded() {
        // When loaded >= expected, progress reaches 1.0 — WorldReady condition met.
        let progress = compute_progress(100, 100);
        assert_eq!(progress, 1.0);
        // Simulate the ready trigger.
        assert!(progress >= 1.0);
    }

    use bevy::ecs::message::Messages;
    use bevy::ecs::system::RunSystemOnce;

    /// World whose initial sphere is a single chunk, already loaded.
    fn fully_loaded_world() -> World {
        let mut world = World::new();
        let mut manager = ChunkManager::new(0.0, 0.0);
        let entity = world.spawn_empty().id();
        manager.register(IVec3::ZERO, entity);
        world.insert_resource(manager);
        world.insert_resource(ViewerPosition {
            position: Vec3::splat(CHUNK_SIZE as f32 * 0.5),
        });
        world.init_resource::<WorldLoadingState>();
        world.init_resource::<Messages<LoadingProgress>>();
        world.init_resource::<Messages<WorldReady>>();
        world
    }

    fn run_loading(world: &mut World) {
        world
            .run_system_once(loading_progress_system)
            .expect("loading_progress_system should run");
    }

    fn ready_count(world: &World) -> usize {
        world.resource::<Messages<WorldReady>>().len()
    }

    /// World with a 40-unit load range around `viewer` and nothing loaded.
    fn world_with_viewer(viewer: Vec3) -> World {
        let mut world = World::new();
        world.insert_resource(ChunkManager::new(40.0, 80.0));
        world.insert_resource(ViewerPosition { position: viewer });
        world.init_resource::<WorldLoadingState>();
        world.init_resource::<Messages<LoadingProgress>>();
        world.init_resource::<Messages<WorldReady>>();
        world
    }

    fn register(world: &mut World, coord: IVec3) {
        let entity = world.spawn_empty().id();
        world.resource_mut::<ChunkManager>().register(coord, entity);
    }

    fn last_progress(world: &World) -> LoadingProgress {
        world
            .resource::<Messages<LoadingProgress>>()
            .iter_current_update_messages()
            .last()
            .cloned()
            .expect("a progress message")
    }

    #[test]
    fn total_is_the_number_of_chunks_streaming_requests() {
        // The viewer sits on a chunk corner, where a lattice estimate is off.
        for viewer in [
            Vec3::ZERO,
            Vec3::new(8.0, 8.0, 8.0),
            Vec3::new(3.0, 15.0, -70.5),
        ] {
            let mut world = world_with_viewer(viewer);
            let in_range: Vec<IVec3> = chunks_in_load_range(viewer, 40.0).collect();
            assert!(!in_range.is_empty());
            for &coord in &in_range {
                register(&mut world, coord);
            }

            run_loading(&mut world);

            let progress = last_progress(&world);
            assert_eq!(progress.total as usize, in_range.len());
            assert_eq!(progress.loaded, progress.total);
            assert_eq!(progress.progress, 1.0);
            assert_eq!(ready_count(&world), 1);
        }
    }

    #[test]
    fn an_empty_load_range_is_ready_at_once() {
        // On a chunk corner the nearest centers are farther than 1 unit away.
        let mut world = world_with_viewer(Vec3::ZERO);
        world.insert_resource(ChunkManager::new(1.0, 2.0));

        run_loading(&mut world);

        let progress = last_progress(&world);
        assert_eq!((progress.loaded, progress.total), (0, 0));
        assert_eq!(ready_count(&world), 1);
    }

    #[test]
    fn loaded_never_exceeds_total() {
        let viewer = Vec3::ZERO;
        let mut world = world_with_viewer(viewer);
        for coord in chunks_in_load_range(viewer, 40.0).collect::<Vec<_>>() {
            register(&mut world, coord);
        }
        // Chunks outside the load range, as left behind by a moving viewer.
        for x in 50..60 {
            register(&mut world, IVec3::new(x, 0, 0));
        }

        run_loading(&mut world);

        let progress = last_progress(&world);
        assert_eq!(progress.loaded, progress.total);
    }

    #[test]
    fn chunks_outside_the_load_range_do_not_complete_the_load() {
        let viewer = Vec3::ZERO;
        let mut world = world_with_viewer(viewer);
        let in_range: Vec<IVec3> = chunks_in_load_range(viewer, 40.0).collect();
        for &coord in &in_range[1..] {
            register(&mut world, coord);
        }
        for x in 50..60 {
            register(&mut world, IVec3::new(x, 0, 0));
        }

        run_loading(&mut world);

        let progress = last_progress(&world);
        assert_eq!(progress.loaded + 1, progress.total);
        assert!(progress.progress < 1.0);
        assert_eq!(ready_count(&world), 0, "one chunk in range is missing");
    }

    #[test]
    fn world_is_ready_when_loaded_and_there_is_no_mesh_queue() {
        let mut world = fully_loaded_world();

        run_loading(&mut world);

        assert_eq!(ready_count(&world), 1);
        assert!(world.resource::<WorldLoadingState>().ready);
    }

    #[test]
    fn world_ready_waits_for_pending_chunk_meshes() {
        let mut world = fully_loaded_world();
        let mut pending = PendingChunkMeshes::default();
        pending.push(IVec3::ZERO);
        world.insert_resource(pending);

        run_loading(&mut world);
        assert_eq!(ready_count(&world), 0, "a chunk still has no mesh");
        assert!(!world.resource::<WorldLoadingState>().ready);
        let progress = world
            .resource::<Messages<LoadingProgress>>()
            .iter_current_update_messages()
            .last()
            .map(|message| message.progress);
        assert_eq!(progress, Some(1.0), "loading itself is complete");

        world.insert_resource(PendingChunkMeshes::default());
        run_loading(&mut world);
        assert_eq!(ready_count(&world), 1);
    }

    #[test]
    fn world_ready_does_not_wait_for_a_stalled_mesh_queue() {
        use crate::mesh::chunk_mesh_system;
        use crate::render::material::ChunkMaterialHandle;
        use crate::voxel::DefaultVoxel;
        use crate::world::ChunkModified;

        // MeshPlugin-like setup with no chunk material: nothing can be meshed.
        let mut world = fully_loaded_world();
        world.init_resource::<Messages<ChunkModified>>();
        world.init_resource::<crate::mesh::PendingNeighborRemesh>();
        world.init_resource::<PendingChunkMeshes>();
        world.init_resource::<Assets<Mesh>>();
        world.init_resource::<ChunkMaterialHandle>();
        world.write_message(ChunkModified(IVec3::ZERO));
        world
            .run_system_once(chunk_mesh_system::<DefaultVoxel>)
            .expect("chunk_mesh_system should run");
        assert!(!world.resource::<PendingChunkMeshes>().is_empty());

        run_loading(&mut world);

        assert_eq!(ready_count(&world), 1);
    }

    #[test]
    fn world_ready_is_evaluated_after_this_frame_meshing() {
        use crate::chunk::Chunk;
        use crate::mesh::{ChunkMeshBudget, MeshPlugin};
        use crate::render::material::ChunkMaterialHandle;
        use crate::voxel::DefaultVoxel;
        use crate::world::{ChunkModified, ChunkUnloadRequest, ViewerPosition};

        let mut app = App::new();
        app.add_message::<ChunkModified>();
        app.add_message::<ChunkUnloadRequest>();
        // The viewer is at the center of chunk (0, 0, 0), the only one in range.
        app.insert_resource(ViewerPosition {
            position: Vec3::splat(CHUNK_SIZE as f32 * 0.5),
        });
        app.init_resource::<Assets<Mesh>>();
        let mut materials = Assets::<StandardMaterial>::default();
        let standard = materials.add(StandardMaterial::default());
        app.insert_resource(materials);
        app.insert_resource(ChunkMaterialHandle {
            standard: Some(standard),
            custom: None,
        });
        // Two loaded chunks with geometry, far apart, in a one-chunk region.
        let mut manager = ChunkManager::new(0.0, 0.0);
        let coords = [IVec3::ZERO, IVec3::new(5, 0, 0)];
        for coord in coords {
            let mut chunk = Chunk::<DefaultVoxel>::new();
            chunk.set(8, 8, 8, DefaultVoxel::Rock);
            let entity = app.world_mut().spawn(chunk).id();
            manager.register(coord, entity);
        }
        app.insert_resource(manager);
        app.add_plugins((MeshPlugin::<DefaultVoxel>::new(), LoadingPlugin));
        app.insert_resource(ChunkMeshBudget::new(1));
        for coord in coords {
            app.world_mut().write_message(ChunkModified(coord));
        }

        // Frame 1 meshes one chunk; the other is still queued when the loading
        // system looks, because it runs after the mesh system.
        app.update();
        assert!(!app.world().resource::<WorldLoadingState>().ready);

        app.update();
        assert!(app.world().resource::<WorldLoadingState>().ready);
    }

    #[test]
    fn test_loading_ready_when_overloaded() {
        // loaded can exceed expected briefly; progress is clamped to 1.0.
        let progress = compute_progress(110, 100);
        assert_eq!(progress, 1.0);
    }
}