Skip to main content

voxel_framework/world/
loading.rs

1//! Initial world loading lifecycle — progress tracking and the ready signal.
2//!
3//! # Overview
4//!
5//! When a world first starts, the streaming system begins requesting chunks
6//! around the viewer. This module tracks how many of those chunks have been
7//! fully generated and meshed, and fires a one-shot signal when the world is
8//! ready to display.
9//!
10//! # What "loaded" means
11//!
12//! A chunk is considered **loaded** when it is registered in [`ChunkManager`]
13//! via [`ChunkManager::register`] — meaning voxel data has been generated
14//! **and** the renderable mesh entity has been spawned. The total number of
15//! chunks expected in the initial load sphere is computed once from
16//! `load_distance` using `count_chunks_in_sphere`.
17//!
18//! # Event flow
19//!
20//! ```text
21//! WorldPlugin starts
22//!     │
23//!     ▼
24//! loading_progress_system runs each frame (after GeneratorSystems)
25//!     │
26//!     ├─ emits LoadingProgress { loaded, total, progress }  every frame
27//!     │
28//!     └─ when progress >= 1.0:
29//!            emits WorldReady (once)
30//!            sets WorldLoadingState::ready = true → system becomes a no-op
31//! ```
32//!
33//! # Usage
34//!
35//! Add [`LoadingPlugin`] to your [`App`] alongside [`super::WorldPlugin`].
36//! Subscribe to [`LoadingProgress`] to drive a loading screen, and to
37//! [`WorldReady`] to transition out of it:
38//!
39//! ```rust,no_run
40//! use bevy::prelude::*;
41//! use voxel_framework::world::{WorldPlugin, LoadingPlugin, LoadingProgress, WorldReady};
42//!
43//! fn on_world_ready(mut reader: MessageReader<WorldReady>) {
44//!     for _ in reader.read() {
45//!         println!("world is ready!");
46//!     }
47//! }
48//!
49//! App::new()
50//!     .add_plugins((WorldPlugin, LoadingPlugin))
51//!     .add_systems(Update, on_world_ready)
52//!     .run();
53//! ```
54
55use bevy::prelude::*;
56
57use crate::chunk::{CHUNK_SIZE, VOXEL_SIZE};
58use crate::generator::GeneratorSystems;
59use crate::mesh::{MeshSystems, PendingChunkMeshes};
60
61use super::ChunkManager;
62
63// ─── Messages ────────────────────────────────────────────────────────────────
64
65/// Emitted every frame while the initial chunk sphere is still loading.
66///
67/// [`loading_progress_system`] writes this message once per frame from the
68/// moment the world starts until [`WorldReady`] fires. Once [`WorldReady`] has
69/// been emitted, this message is no longer written.
70///
71/// - `loaded` — number of chunks currently registered in [`ChunkManager`].
72/// - `total` — expected chunk count for the full load sphere (computed once
73///   from `load_distance` on the first frame).
74/// - `progress` — `loaded / total`, clamped to `[0.0, 1.0]`.
75///
76/// # Example
77///
78/// ```rust,no_run
79/// use bevy::prelude::*;
80/// use voxel_framework::world::LoadingProgress;
81///
82/// fn show_progress(mut reader: MessageReader<LoadingProgress>) {
83///     for msg in reader.read() {
84///         println!("loading: {:.0}%", msg.progress * 100.0);
85///     }
86/// }
87/// ```
88#[derive(Message, Debug, Clone)]
89pub struct LoadingProgress {
90    pub loaded: u32,
91    pub total: u32,
92    pub progress: f32,
93}
94
95/// One-shot signal emitted when the initial chunk sphere is fully loaded.
96///
97/// [`loading_progress_system`] emits this message exactly once, on the first
98/// frame that [`LoadingProgress::progress`] has reached `1.0` and no chunk is
99/// still waiting for its mesh (see [`PendingChunkMeshes`]). Without
100/// [`MeshPlugin`](crate::mesh::MeshPlugin) there is no mesh queue and only the
101/// progress counts; the same applies while the queue is stalled because no
102/// chunk material exists. After it fires,
103/// [`WorldLoadingState::ready`] is set to `true` and the progress system
104/// becomes a no-op — no further [`LoadingProgress`] or `WorldReady` messages
105/// are written.
106///
107/// Use this event to transition your app out of a loading screen, enable
108/// gameplay input, or trigger any one-time "world is ready" logic.
109///
110/// # Example
111///
112/// ```rust,no_run
113/// use bevy::prelude::*;
114/// use voxel_framework::world::WorldReady;
115///
116/// fn on_world_ready(mut reader: MessageReader<WorldReady>) {
117///     for _ in reader.read() {
118///         println!("all chunks generated — entering gameplay");
119///     }
120/// }
121///
122/// # fn main() {
123/// App::new()
124///     .add_message::<WorldReady>()
125///     .add_systems(Update, on_world_ready)
126///     .run();
127/// # }
128/// ```
129#[derive(Message, Debug, Clone)]
130pub struct WorldReady;
131
132// ─── Resource ─────────────────────────────────────────────────────────────────
133
134/// Internal resource that guards the one-shot [`WorldReady`] emission.
135///
136/// Inserted by [`LoadingPlugin`] via `init_resource`. [`loading_progress_system`]
137/// reads and mutates this resource each frame:
138///
139/// - `expected` is computed once on the first frame from [`ChunkManager::load_distance`]
140///   and cached here to avoid recomputing it every tick.
141/// - `ready` is set to `true` after [`WorldReady`] fires, turning the system
142///   into a no-op for the remainder of the session.
143///
144/// This resource is not intended to be mutated by user code. To check whether
145/// the world has finished loading, subscribe to [`WorldReady`] instead.
146#[derive(Resource, Default)]
147pub struct WorldLoadingState {
148    /// Set to `true` after [`WorldReady`] has been emitted.
149    pub ready: bool,
150    /// Total chunks expected in the initial load sphere (computed once).
151    pub expected: u32,
152}
153
154// ─── Helpers (pure, testable) ─────────────────────────────────────────────────
155
156/// Returns the number of chunk coords within a cubic grid of `[-r, r]^3` that
157/// also fall inside the sphere of radius `r` (measured in chunk units).
158pub(crate) fn count_chunks_in_sphere(radius_in_chunks: i32) -> u32 {
159    let r = radius_in_chunks;
160    let mut count = 0u32;
161    for dx in -r..=r {
162        for dy in -r..=r {
163            for dz in -r..=r {
164                // Use squared distance to stay in integer arithmetic.
165                let dist_sq = dx * dx + dy * dy + dz * dz;
166                if dist_sq <= r * r {
167                    count += 1;
168                }
169            }
170        }
171    }
172    count
173}
174
175/// Computes the loading progress fraction given `loaded` and `expected` counts.
176/// Returns 0.0 when `expected` is 0 to avoid division by zero.
177pub(crate) fn compute_progress(loaded: u32, expected: u32) -> f32 {
178    if expected == 0 {
179        0.0
180    } else {
181        (loaded as f32 / expected as f32).min(1.0)
182    }
183}
184
185// ─── System ───────────────────────────────────────────────────────────────────
186
187/// Tracks initial chunk loading and emits [`LoadingProgress`] and [`WorldReady`].
188///
189/// Scheduled in [`Update`], ordered after [`GeneratorSystems`] so that any
190/// chunks completed in the current frame are already counted before progress
191/// is computed.
192///
193/// On the first invocation, the expected chunk count is derived from
194/// [`ChunkManager::load_distance`] and cached in [`WorldLoadingState::expected`].
195/// Subsequent frames skip this computation and go straight to the progress
196/// check.
197///
198/// Once [`WorldLoadingState::ready`] is `true` (set after [`WorldReady`]
199/// fires), the system returns immediately without writing any messages.
200pub fn loading_progress_system(
201    manager: Res<ChunkManager>,
202    mut loading_state: ResMut<WorldLoadingState>,
203    mut progress_writer: MessageWriter<LoadingProgress>,
204    mut ready_writer: MessageWriter<WorldReady>,
205    pending_meshes: Option<Res<PendingChunkMeshes>>,
206) {
207    // Compute the expected chunk count once.
208    if loading_state.expected == 0 {
209        let radius_in_chunks =
210            (manager.load_distance / (CHUNK_SIZE as f32 * VOXEL_SIZE)).ceil() as i32;
211        loading_state.expected = count_chunks_in_sphere(radius_in_chunks);
212    }
213
214    if loading_state.ready {
215        return;
216    }
217
218    let loaded = manager.loaded_count() as u32;
219    let expected = loading_state.expected;
220    let progress = compute_progress(loaded, expected);
221
222    progress_writer.write(LoadingProgress {
223        loaded,
224        total: expected,
225        progress,
226    });
227
228    // Chunks are meshed a bounded number per frame, so the last ones to load
229    // can still be waiting for geometry. The world is ready once they have it.
230    // A stalled queue (no chunk material) will never drain, so do not wait.
231    let meshing_done =
232        pending_meshes.is_none_or(|pending| pending.is_empty() || pending.is_stalled());
233
234    if progress >= 1.0 && meshing_done {
235        ready_writer.write(WorldReady);
236        loading_state.ready = true;
237    }
238}
239
240// ─── Plugin ───────────────────────────────────────────────────────────────────
241
242/// Plugin that tracks initial world loading and emits [`LoadingProgress`] and [`WorldReady`].
243///
244/// Registers the following on the Bevy [`App`]:
245///
246/// - [`WorldLoadingState`] resource (via `init_resource`).
247/// - [`LoadingProgress`] and [`WorldReady`] messages.
248/// - [`loading_progress_system`] scheduled in [`Update`] after [`GeneratorSystems`]
249///   and [`MeshSystems`].
250///
251/// Must be used together with [`super::WorldPlugin`], which provides the
252/// [`ChunkManager`] resource this plugin reads.
253///
254/// # Example
255///
256/// ```rust,no_run
257/// use bevy::prelude::*;
258/// use voxel_framework::world::{WorldPlugin, LoadingPlugin, WorldReady};
259///
260/// fn on_ready(mut reader: MessageReader<WorldReady>) {
261///     for _ in reader.read() {
262///         println!("world ready — starting gameplay");
263///     }
264/// }
265///
266/// App::new()
267///     .add_plugins((WorldPlugin, LoadingPlugin))
268///     .add_systems(Update, on_ready)
269///     .run();
270/// ```
271pub struct LoadingPlugin;
272
273impl Plugin for LoadingPlugin {
274    fn build(&self, app: &mut App) {
275        app.init_resource::<WorldLoadingState>();
276        app.add_message::<LoadingProgress>();
277        app.add_message::<WorldReady>();
278        app.add_systems(
279            Update,
280            loading_progress_system
281                .after(GeneratorSystems)
282                .after(MeshSystems),
283        );
284    }
285}
286
287// ─── Tests ────────────────────────────────────────────────────────────────────
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292
293    #[test]
294    fn test_loading_progress_zero_when_nothing_loaded() {
295        // With nothing loaded, progress should be 0.0.
296        let progress = compute_progress(0, 100);
297        assert_eq!(progress, 0.0);
298    }
299
300    #[test]
301    fn test_loading_progress_zero_when_expected_is_zero() {
302        // Guard against division by zero when expected hasn't been computed yet.
303        let progress = compute_progress(0, 0);
304        assert_eq!(progress, 0.0);
305    }
306
307    #[test]
308    fn test_loading_progress_partial() {
309        let progress = compute_progress(50, 100);
310        assert!((progress - 0.5).abs() < f32::EPSILON);
311    }
312
313    #[test]
314    fn test_loading_ready_when_fully_loaded() {
315        // When loaded >= expected, progress reaches 1.0 — WorldReady condition met.
316        let progress = compute_progress(100, 100);
317        assert_eq!(progress, 1.0);
318        // Simulate the ready trigger.
319        assert!(progress >= 1.0);
320    }
321
322    use bevy::ecs::message::Messages;
323    use bevy::ecs::system::RunSystemOnce;
324
325    /// World whose initial sphere is a single chunk, already loaded.
326    fn fully_loaded_world() -> World {
327        let mut world = World::new();
328        let mut manager = ChunkManager::new(0.0, 0.0);
329        let entity = world.spawn_empty().id();
330        manager.register(IVec3::ZERO, entity);
331        world.insert_resource(manager);
332        world.init_resource::<WorldLoadingState>();
333        world.init_resource::<Messages<LoadingProgress>>();
334        world.init_resource::<Messages<WorldReady>>();
335        world
336    }
337
338    fn run_loading(world: &mut World) {
339        world
340            .run_system_once(loading_progress_system)
341            .expect("loading_progress_system should run");
342    }
343
344    fn ready_count(world: &World) -> usize {
345        world.resource::<Messages<WorldReady>>().len()
346    }
347
348    #[test]
349    fn world_is_ready_when_loaded_and_there_is_no_mesh_queue() {
350        let mut world = fully_loaded_world();
351
352        run_loading(&mut world);
353
354        assert_eq!(ready_count(&world), 1);
355        assert!(world.resource::<WorldLoadingState>().ready);
356    }
357
358    #[test]
359    fn world_ready_waits_for_pending_chunk_meshes() {
360        let mut world = fully_loaded_world();
361        let mut pending = PendingChunkMeshes::default();
362        pending.push(IVec3::ZERO);
363        world.insert_resource(pending);
364
365        run_loading(&mut world);
366        assert_eq!(ready_count(&world), 0, "a chunk still has no mesh");
367        assert!(!world.resource::<WorldLoadingState>().ready);
368        let progress = world
369            .resource::<Messages<LoadingProgress>>()
370            .iter_current_update_messages()
371            .last()
372            .map(|message| message.progress);
373        assert_eq!(progress, Some(1.0), "loading itself is complete");
374
375        world.insert_resource(PendingChunkMeshes::default());
376        run_loading(&mut world);
377        assert_eq!(ready_count(&world), 1);
378    }
379
380    #[test]
381    fn world_ready_does_not_wait_for_a_stalled_mesh_queue() {
382        use crate::mesh::chunk_mesh_system;
383        use crate::render::material::ChunkMaterialHandle;
384        use crate::voxel::DefaultVoxel;
385        use crate::world::{ChunkModified, ViewerPosition};
386
387        // MeshPlugin-like setup with no chunk material: nothing can be meshed.
388        let mut world = fully_loaded_world();
389        world.init_resource::<Messages<ChunkModified>>();
390        world.init_resource::<crate::mesh::PendingNeighborRemesh>();
391        world.init_resource::<PendingChunkMeshes>();
392        world.init_resource::<ViewerPosition>();
393        world.init_resource::<Assets<Mesh>>();
394        world.init_resource::<ChunkMaterialHandle>();
395        world.write_message(ChunkModified(IVec3::ZERO));
396        world
397            .run_system_once(chunk_mesh_system::<DefaultVoxel>)
398            .expect("chunk_mesh_system should run");
399        assert!(!world.resource::<PendingChunkMeshes>().is_empty());
400
401        run_loading(&mut world);
402
403        assert_eq!(ready_count(&world), 1);
404    }
405
406    #[test]
407    fn world_ready_is_evaluated_after_this_frame_meshing() {
408        use crate::chunk::Chunk;
409        use crate::mesh::{ChunkMeshBudget, MeshPlugin};
410        use crate::render::material::ChunkMaterialHandle;
411        use crate::voxel::DefaultVoxel;
412        use crate::world::{ChunkModified, ChunkUnloadRequest, ViewerPosition};
413
414        let mut app = App::new();
415        app.add_message::<ChunkModified>();
416        app.add_message::<ChunkUnloadRequest>();
417        app.init_resource::<ViewerPosition>();
418        app.init_resource::<Assets<Mesh>>();
419        let mut materials = Assets::<StandardMaterial>::default();
420        let standard = materials.add(StandardMaterial::default());
421        app.insert_resource(materials);
422        app.insert_resource(ChunkMaterialHandle {
423            standard: Some(standard),
424            custom: None,
425        });
426        // Two loaded chunks with geometry, far apart, in a one-chunk region.
427        let mut manager = ChunkManager::new(0.0, 0.0);
428        let coords = [IVec3::ZERO, IVec3::new(5, 0, 0)];
429        for coord in coords {
430            let mut chunk = Chunk::<DefaultVoxel>::new();
431            chunk.set(8, 8, 8, DefaultVoxel::Rock);
432            let entity = app.world_mut().spawn(chunk).id();
433            manager.register(coord, entity);
434        }
435        app.insert_resource(manager);
436        app.add_plugins((MeshPlugin::<DefaultVoxel>::new(), LoadingPlugin));
437        app.insert_resource(ChunkMeshBudget::new(1));
438        for coord in coords {
439            app.world_mut().write_message(ChunkModified(coord));
440        }
441
442        // Frame 1 meshes one chunk; the other is still queued when the loading
443        // system looks, because it runs after the mesh system.
444        app.update();
445        assert!(!app.world().resource::<WorldLoadingState>().ready);
446
447        app.update();
448        assert!(app.world().resource::<WorldLoadingState>().ready);
449    }
450
451    #[test]
452    fn test_loading_ready_when_overloaded() {
453        // loaded can exceed expected briefly; progress is clamped to 1.0.
454        let progress = compute_progress(110, 100);
455        assert_eq!(progress, 1.0);
456    }
457
458    #[test]
459    fn test_count_chunks_in_sphere_radius_zero() {
460        // Radius 0 → only the origin chunk.
461        assert_eq!(count_chunks_in_sphere(0), 1);
462    }
463
464    #[test]
465    fn test_count_chunks_in_sphere_radius_one() {
466        // Radius 1 → 7 chunks (origin + 6 face-adjacent).
467        assert_eq!(count_chunks_in_sphere(1), 7);
468    }
469
470    #[test]
471    fn test_count_chunks_in_sphere_positive_count() {
472        // Any positive radius should yield a positive chunk count.
473        assert!(count_chunks_in_sphere(5) > 0);
474    }
475}