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