voxel-framework 0.12.3

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
//! 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 total number of
//! chunks expected in the initial load sphere is computed once from
//! `load_distance` using `count_chunks_in_sphere`.
//!
//! # 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::chunk::{CHUNK_SIZE, VOXEL_SIZE};
use crate::generator::GeneratorSystems;
use crate::mesh::{MeshSystems, PendingChunkMeshes};

use super::ChunkManager;

// ─── 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.
///
/// - `loaded` — number of chunks currently registered in [`ChunkManager`].
/// - `total` — expected chunk count for the full load sphere (computed once
///   from `load_distance` on the first frame).
/// - `progress` — `loaded / total`, clamped to `[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 computed once on the first frame from [`ChunkManager::load_distance`]
///   and cached here to avoid recomputing it every tick.
/// - `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,
    /// Total chunks expected in the initial load sphere (computed once).
    pub expected: u32,
}

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

/// Returns the number of chunk coords within a cubic grid of `[-r, r]^3` that
/// also fall inside the sphere of radius `r` (measured in chunk units).
pub(crate) fn count_chunks_in_sphere(radius_in_chunks: i32) -> u32 {
    let r = radius_in_chunks;
    let mut count = 0u32;
    for dx in -r..=r {
        for dy in -r..=r {
            for dz in -r..=r {
                // Use squared distance to stay in integer arithmetic.
                let dist_sq = dx * dx + dy * dy + dz * dz;
                if dist_sq <= r * r {
                    count += 1;
                }
            }
        }
    }
    count
}

/// 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.
///
/// On the first invocation, the expected chunk count is derived from
/// [`ChunkManager::load_distance`] and cached in [`WorldLoadingState::expected`].
/// Subsequent frames skip this computation and go straight to the progress
/// check.
///
/// 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>,
    mut loading_state: ResMut<WorldLoadingState>,
    mut progress_writer: MessageWriter<LoadingProgress>,
    mut ready_writer: MessageWriter<WorldReady>,
    pending_meshes: Option<Res<PendingChunkMeshes>>,
) {
    // Compute the expected chunk count once.
    if loading_state.expected == 0 {
        let radius_in_chunks =
            (manager.load_distance / (CHUNK_SIZE as f32 * VOXEL_SIZE)).ceil() as i32;
        loading_state.expected = count_chunks_in_sphere(radius_in_chunks);
    }

    if loading_state.ready {
        return;
    }

    let loaded = manager.loaded_count() as u32;
    let expected = loading_state.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());

    if progress >= 1.0 && 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::*;

    #[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.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()
    }

    #[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, ViewerPosition};

        // 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::<ViewerPosition>();
        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>();
        app.init_resource::<ViewerPosition>();
        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);
    }

    #[test]
    fn test_count_chunks_in_sphere_radius_zero() {
        // Radius 0 → only the origin chunk.
        assert_eq!(count_chunks_in_sphere(0), 1);
    }

    #[test]
    fn test_count_chunks_in_sphere_radius_one() {
        // Radius 1 → 7 chunks (origin + 6 face-adjacent).
        assert_eq!(count_chunks_in_sphere(1), 7);
    }

    #[test]
    fn test_count_chunks_in_sphere_positive_count() {
        // Any positive radius should yield a positive chunk count.
        assert!(count_chunks_in_sphere(5) > 0);
    }
}