voxel_framework/world/mod.rs
1//! World streaming, chunk lifecycle, and runtime configuration.
2//!
3//! # Overview
4//!
5//! The world module owns three concerns:
6//!
7//! - **Chunk registry** — [`ChunkManager`] tracks which chunks are fully
8//! loaded, which are in-flight, and the configured streaming distances.
9//! - **Viewer tracking** — [`ViewerPosition`] is a lightweight resource that
10//! your player/camera system updates every frame. The streaming system reads
11//! it to decide which chunks to load or unload.
12//! - **Lifecycle events** — [`ChunkLoadRequest`], [`ChunkUnloadRequest`], and
13//! [`ChunkModified`] are the message bus between the streaming system and
14//! the rest of the engine (generation, meshing, persistence).
15//!
16//! Add [`WorldPlugin`] to your [`App`] to register all of the above
17//! automatically.
18//!
19//! # The Streaming Pipeline
20//!
21//! Every frame the [`systems::streaming_system`] executes the following steps:
22//!
23//! ```text
24//! ┌─────────────────────┐
25//! │ ViewerPosition │ updated by your camera/player system each frame
26//! └────────┬────────────┘
27//! │ read by streaming_system
28//! ▼
29//! ┌─────────────────────┐
30//! │ Distance check │ iterate cube of radius ceil(load_distance/CHUNK_SIZE)
31//! │ around viewer │ compute world-space center distance per coord
32//! └────────┬────────────┘
33//! │
34//! ┌────┴─────┐
35//! │ │
36//! ▼ ▼
37//! ChunkLoad ChunkUnload
38//! Request Request
39//! (enter (exit
40//! sphere) sphere)
41//! │ │
42//! ▼ ▼
43//! Generator Despawn
44//! system system
45//! (async)
46//! │
47//! ▼
48//! ChunkModified ←── voxel edits (mining, placement, etc.)
49//! │
50//! ▼
51//! Mesh rebuild system
52//! ```
53//!
54//! 1. [`ViewerPosition`] is updated by your player/camera system.
55//! 2. [`systems::streaming_system`] converts it to chunk-grid space and
56//! iterates every coordinate within a bounding cube of radius
57//! `ceil(load_distance / CHUNK_SIZE)`.
58//! 3. For each coordinate inside the load sphere that is neither loaded nor
59//! pending, the system emits [`ChunkLoadRequest`] and marks the coord
60//! pending in [`ChunkManager`].
61//! 4. For each currently loaded chunk whose center has drifted beyond
62//! `unload_distance`, the system emits [`ChunkUnloadRequest`].
63//! 5. An external generation system receives [`ChunkLoadRequest`], generates
64//! voxel data asynchronously, spawns the entity, and calls
65//! [`ChunkManager::register`].
66//! 6. Whenever voxel data changes (mining, placement, etc.), the responsible
67//! system emits [`ChunkModified`], which triggers mesh regeneration for
68//! that chunk and its affected neighbors.
69//!
70//! # Events and Messages
71//!
72//! | Event | When it fires | Who consumes it |
73//! |---|---|---|
74//! | [`ChunkLoadRequest`] | Chunk coord enters `load_distance` sphere | Generation system |
75//! | [`ChunkUnloadRequest`] | Loaded chunk center exits `unload_distance` sphere | Despawn system |
76//! | [`ChunkModified`] | A loaded chunk needs a remesh: data written, finished loading, or a neighbour/LOD change | Mesh rebuild, occlusion, autosave (chunks with unsaved changes only) |
77//!
78//! # World Configuration
79//!
80//! [`config::WorldConfig`] is loaded from `world.toml` in the working
81//! directory at startup by [`config::WorldConfigPlugin`]. It is inserted as a
82//! Bevy [`Resource`] and its `load_distance` / `unload_distance` values are
83//! applied directly to [`ChunkManager`]. If the file is absent or malformed,
84//! [`config::WorldConfig::default`] is used silently.
85
86pub mod collision;
87pub mod config;
88pub mod daycycle;
89pub mod loading;
90#[cfg(feature = "crafting")]
91pub mod manifest;
92pub mod mining;
93pub mod occlusion;
94pub mod persistence;
95pub mod placement;
96pub mod raycast;
97pub mod systems;
98pub mod voxel_ops;
99
100pub use collision::{
101 capsule_overlaps_voxels, resolve_capsule_collision, resolve_sphere_collision,
102 sphere_overlaps_voxels,
103};
104pub use config::{WorldConfig, WorldConfigPlugin};
105pub use daycycle::{DayCycleConfig, DayCyclePlugin, SunLight};
106pub use loading::{LoadingPlugin, LoadingProgress, WorldLoadingState, WorldReady};
107#[cfg(feature = "items")]
108pub use mining::MiningInputPlugin;
109pub use mining::{
110 MiningConfig, MiningPlugin, MiningProgress, MiningState, VoxelBroken, mining_input_system,
111 stop_mining, tick_mining,
112};
113pub use occlusion::{OcclusionPlugin, is_chunk_occluded};
114pub use persistence::{
115 PersistenceConfig, PersistencePlugin, WorldDataDir, chunk_autosave_system, try_load_chunk,
116};
117pub use placement::{
118 PlacementConfig, PlacementPlugin, PlacementState, VoxelPlaced, tick_placement, try_place_voxel,
119};
120#[cfg(feature = "items")]
121pub use placement::{PlacementInputPlugin, placement_input_system};
122pub use raycast::{RaycastHit, raycast};
123pub use systems::ViewerPosition;
124pub use voxel_ops::{get_state_at, get_voxel_at, set_state_at, set_voxel_at};
125
126use std::collections::{HashMap, HashSet};
127
128use bevy::prelude::*;
129
130use crate::chunk::ChunkCoord;
131
132// ─── Constants ───────────────────────────────────────────────────────────────
133
134/// Default radius in world units within which chunks are loaded (150.0).
135///
136/// Used as the initial value for [`ChunkManager::load_distance`] when no
137/// [`config::WorldConfig`] overrides it. Can be overridden per-instance via
138/// [`ChunkManager::new`] or by loading a `world.toml` with
139/// [`config::WorldConfigPlugin`].
140pub const DEFAULT_LOAD_DISTANCE: f32 = 150.0;
141
142/// Default radius in world units beyond which chunks are unloaded (200.0).
143///
144/// Used as the initial value for [`ChunkManager::unload_distance`]. The
145/// 50-unit gap between this constant and [`DEFAULT_LOAD_DISTANCE`] creates a
146/// **hysteresis band**: chunks that have been loaded are not immediately
147/// unloaded when the viewer steps back past the load boundary. This prevents
148/// rapid load/unload cycling ("thrashing") near the edge of the streaming
149/// sphere.
150pub const DEFAULT_UNLOAD_DISTANCE: f32 = 200.0;
151
152// ─── Events ──────────────────────────────────────────────────────────────────
153
154/// Fired by [`systems::streaming_system`] when a chunk coordinate enters the
155/// load sphere and must be generated and spawned.
156///
157/// The wrapped [`ChunkCoord`] identifies the chunk-grid position that should
158/// be populated. Upon receiving this event, a generation system should:
159///
160/// 1. Generate voxel data for the coordinate (typically on a thread pool).
161/// 2. Spawn a Bevy entity with the resulting mesh and voxel components.
162/// 3. Call [`ChunkManager::register`] with the coord and new entity so the
163/// streaming system considers the chunk fully loaded.
164///
165/// The coord is guaranteed to be neither already loaded nor pending at the
166/// moment the event is written.
167#[derive(Message, Debug, Clone, Copy, PartialEq, Eq, Hash)]
168pub struct ChunkLoadRequest(pub ChunkCoord);
169
170/// Fired by [`systems::streaming_system`] when a loaded chunk's world-space
171/// center drifts beyond [`ChunkManager::unload_distance`].
172///
173/// The wrapped [`ChunkCoord`] identifies the chunk to remove. Upon receiving
174/// this event, a despawn system should despawn the entity returned by
175/// [`ChunkManager::get_entity`] and call [`ChunkManager::unregister`] so the
176/// coord becomes eligible for reloading in the future.
177///
178/// Note that the 50-unit hysteresis gap between [`DEFAULT_LOAD_DISTANCE`] and
179/// [`DEFAULT_UNLOAD_DISTANCE`] means this event fires noticeably later than
180/// the chunk first became "out of load range".
181#[derive(Message, Debug, Clone, Copy, PartialEq, Eq, Hash)]
182pub struct ChunkUnloadRequest(pub ChunkCoord);
183
184/// Fired whenever a loaded chunk needs its mesh rebuilt: its voxel data was
185/// written, it just finished loading, or a neighbour or LOD change affects
186/// its faces.
187///
188/// The message alone does not mean the data changed. Whether a chunk has
189/// unsaved changes is tracked by [`Chunk::is_dirty`](crate::chunk::Chunk::is_dirty),
190/// which is what the persistence systems check before writing.
191///
192/// The wrapped [`ChunkCoord`] identifies the modified chunk. Consumers
193/// — typically the mesh rebuild system — should regenerate the mesh for this
194/// chunk and re-evaluate the face visibility of its six face-adjacent
195/// neighbors, because a voxel change at a chunk boundary affects the neighbor's
196/// exposed faces as well.
197///
198/// This event is emitted by high-level operations such as [`mining`] and
199/// [`placement`], and also by any system that calls [`voxel_ops::set_voxel_at`]
200/// directly.
201#[derive(Message, Debug, Clone, Copy, PartialEq, Eq, Hash)]
202pub struct ChunkModified(pub ChunkCoord);
203
204// ─── ChunkManager ─────────────────────────────────────────────────────────────
205
206/// Central registry that tracks the state of every chunk in the streaming system.
207///
208/// `ChunkManager` is inserted as a Bevy [`Resource`] by [`WorldPlugin`] and
209/// updated by [`systems::streaming_system`] every frame. It maintains two
210/// internal sets:
211///
212/// - **Loaded** — chunks that have a live Bevy entity with a built mesh. Query
213/// membership with [`is_loaded`](ChunkManager::is_loaded) and retrieve the
214/// entity with [`get_entity`](ChunkManager::get_entity).
215/// - **Pending** — chunk coordinates for which a [`ChunkLoadRequest`] has been
216/// emitted but whose generation is not yet complete. Query membership with
217/// [`is_pending`](ChunkManager::is_pending).
218///
219/// The two public distance fields, [`load_distance`](ChunkManager::load_distance)
220/// and [`unload_distance`](ChunkManager::unload_distance), are read every frame
221/// by the streaming system. They default to [`DEFAULT_LOAD_DISTANCE`] and
222/// [`DEFAULT_UNLOAD_DISTANCE`] respectively, and can be overridden at runtime
223/// or by loading a [`config::WorldConfig`].
224///
225/// # Querying chunks
226///
227/// ```rust,no_run
228/// use bevy::prelude::*;
229/// use voxel_framework::world::ChunkManager;
230///
231/// fn inspect_chunks(manager: Res<ChunkManager>) {
232/// println!("loaded: {}, pending: {}", manager.loaded_count(), manager.pending_count());
233///
234/// for (coord, entity) in manager.iter_loaded() {
235/// println!("chunk {:?} → entity {:?}", coord, entity);
236/// }
237/// }
238/// ```
239///
240/// # Registering a generated chunk
241///
242/// After generating voxel data and spawning the entity, call
243/// [`register`](ChunkManager::register) to promote the coord from pending to
244/// loaded:
245///
246/// ```rust,no_run
247/// use bevy::prelude::*;
248/// use voxel_framework::world::ChunkManager;
249///
250/// fn finish_generation(mut manager: ResMut<ChunkManager>, mut commands: Commands) {
251/// let coord = IVec3::new(1, 0, 0);
252/// let entity = commands.spawn_empty().id();
253/// manager.register(coord, entity);
254/// }
255/// ```
256#[derive(Resource, Debug)]
257pub struct ChunkManager {
258 /// Fully loaded chunks: coord → Bevy entity with voxel mesh.
259 loaded_chunks: HashMap<IVec3, Entity>,
260 /// Chunk coords that have been requested but not yet fully loaded.
261 pending_load: HashSet<IVec3>,
262 /// Distance (world units) within which chunks are loaded.
263 pub load_distance: f32,
264 /// Distance (world units) beyond which chunks are unloaded.
265 pub unload_distance: f32,
266}
267
268impl ChunkManager {
269 /// Creates a new `ChunkManager` with the given streaming distances.
270 pub fn new(load_distance: f32, unload_distance: f32) -> Self {
271 Self {
272 loaded_chunks: HashMap::new(),
273 pending_load: HashSet::new(),
274 load_distance,
275 unload_distance,
276 }
277 }
278
279 /// Returns `true` if the chunk at `coord` is fully loaded.
280 #[inline]
281 pub fn is_loaded(&self, coord: IVec3) -> bool {
282 self.loaded_chunks.contains_key(&coord)
283 }
284
285 /// Returns `true` if the chunk at `coord` is queued or in-flight.
286 #[inline]
287 pub fn is_pending(&self, coord: IVec3) -> bool {
288 self.pending_load.contains(&coord)
289 }
290
291 /// Returns the Bevy entity for a fully loaded chunk, if any.
292 #[inline]
293 pub fn get_entity(&self, coord: IVec3) -> Option<Entity> {
294 self.loaded_chunks.get(&coord).copied()
295 }
296
297 /// Marks a chunk coord as pending load.
298 ///
299 /// No-op if the chunk is already loaded or already pending.
300 pub fn mark_pending(&mut self, coord: IVec3) {
301 if !self.is_loaded(coord) {
302 self.pending_load.insert(coord);
303 }
304 }
305
306 /// Registers a fully loaded chunk with its Bevy entity.
307 ///
308 /// Removes the coord from the pending set if it was there.
309 pub fn register(&mut self, coord: IVec3, entity: Entity) {
310 self.pending_load.remove(&coord);
311 self.loaded_chunks.insert(coord, entity);
312 }
313
314 /// Unregisters a chunk, removing it from loaded and pending sets.
315 ///
316 /// Returns the entity if it was loaded, `None` otherwise.
317 pub fn unregister(&mut self, coord: IVec3) -> Option<Entity> {
318 self.pending_load.remove(&coord);
319 self.loaded_chunks.remove(&coord)
320 }
321
322 /// Returns an iterator over all loaded chunk coordinates and their entities.
323 pub fn iter_loaded(&self) -> impl Iterator<Item = (IVec3, Entity)> + '_ {
324 self.loaded_chunks
325 .iter()
326 .map(|(&coord, &entity)| (coord, entity))
327 }
328
329 /// Returns the number of fully loaded chunks.
330 #[inline]
331 pub fn loaded_count(&self) -> usize {
332 self.loaded_chunks.len()
333 }
334
335 /// Returns the number of chunks queued for loading.
336 #[inline]
337 pub fn pending_count(&self) -> usize {
338 self.pending_load.len()
339 }
340}
341
342impl Default for ChunkManager {
343 fn default() -> Self {
344 Self::new(DEFAULT_LOAD_DISTANCE, DEFAULT_UNLOAD_DISTANCE)
345 }
346}
347
348// ─── WorldPlugin ─────────────────────────────────────────────────────────────
349
350/// Plugin that wires up the world streaming system.
351///
352/// Registers the following on the Bevy [`App`]:
353///
354/// - [`ChunkManager`] resource (via `init_resource`, defaults to
355/// [`DEFAULT_LOAD_DISTANCE`] / [`DEFAULT_UNLOAD_DISTANCE`]).
356/// - [`ViewerPosition`] resource (via `init_resource`, defaults to the origin).
357/// - [`ChunkLoadRequest`], [`ChunkUnloadRequest`], and [`ChunkModified`]
358/// messages.
359/// - [`systems::streaming_system`] scheduled in [`Update`].
360///
361/// For configuration loading, add [`config::WorldConfigPlugin`] as well. For
362/// initial-load progress tracking, add [`loading::LoadingPlugin`].
363///
364/// # Example
365///
366/// ```rust,no_run
367/// use bevy::prelude::*;
368/// use voxel_framework::world::{WorldPlugin, config::WorldConfigPlugin};
369///
370/// App::new()
371/// .add_plugins((WorldPlugin, WorldConfigPlugin))
372/// .run();
373/// ```
374pub struct WorldPlugin;
375
376impl Plugin for WorldPlugin {
377 fn build(&self, app: &mut App) {
378 app.init_resource::<ChunkManager>();
379 app.init_resource::<ViewerPosition>();
380 app.add_message::<ChunkLoadRequest>();
381 app.add_message::<ChunkUnloadRequest>();
382 app.add_message::<ChunkModified>();
383 app.add_systems(Update, systems::streaming_system);
384 }
385}
386
387// ─── Tests ───────────────────────────────────────────────────────────────────
388
389#[cfg(test)]
390mod tests {
391 use super::*;
392
393 fn manager() -> ChunkManager {
394 ChunkManager::default()
395 }
396
397 #[test]
398 fn new_manager_is_empty() {
399 let m = manager();
400 assert_eq!(m.loaded_count(), 0);
401 assert_eq!(m.pending_count(), 0);
402 }
403
404 #[test]
405 fn mark_pending_adds_to_pending_set() {
406 let mut m = manager();
407 let coord = IVec3::new(1, 0, 0);
408 m.mark_pending(coord);
409 assert!(m.is_pending(coord));
410 assert!(!m.is_loaded(coord));
411 assert_eq!(m.pending_count(), 1);
412 }
413
414 #[test]
415 fn register_promotes_pending_to_loaded() {
416 let mut m = manager();
417 let coord = IVec3::new(2, 0, 0);
418 m.mark_pending(coord);
419
420 // Use bits to construct a fake Entity for testing.
421 let entity = Entity::from_bits(1);
422 m.register(coord, entity);
423
424 assert!(m.is_loaded(coord));
425 assert!(!m.is_pending(coord));
426 assert_eq!(m.get_entity(coord), Some(entity));
427 assert_eq!(m.loaded_count(), 1);
428 assert_eq!(m.pending_count(), 0);
429 }
430
431 #[test]
432 fn unregister_removes_loaded_chunk() {
433 let mut m = manager();
434 let coord = IVec3::new(3, 0, 0);
435 let entity = Entity::from_bits(2);
436 m.register(coord, entity);
437
438 let removed = m.unregister(coord);
439 assert_eq!(removed, Some(entity));
440 assert!(!m.is_loaded(coord));
441 assert_eq!(m.loaded_count(), 0);
442 }
443
444 #[test]
445 fn mark_pending_no_op_if_already_loaded() {
446 let mut m = manager();
447 let coord = IVec3::new(4, 0, 0);
448 let entity = Entity::from_bits(3);
449 m.register(coord, entity);
450
451 // Marking a loaded chunk pending should be a no-op.
452 m.mark_pending(coord);
453 assert!(!m.is_pending(coord));
454 assert!(m.is_loaded(coord));
455 }
456
457 #[test]
458 fn iter_loaded_yields_all_registered_chunks() {
459 let mut m = manager();
460 let coords: Vec<IVec3> = (0..5).map(|i| IVec3::new(i, 0, 0)).collect();
461
462 for (i, &coord) in coords.iter().enumerate() {
463 m.register(coord, Entity::from_bits(i as u64 + 1));
464 }
465
466 let loaded: Vec<IVec3> = m.iter_loaded().map(|(c, _)| c).collect();
467 assert_eq!(loaded.len(), coords.len());
468 for coord in &coords {
469 assert!(loaded.contains(coord));
470 }
471 }
472
473 #[test]
474 fn default_distances_match_constants() {
475 let m = manager();
476 assert_eq!(m.load_distance, DEFAULT_LOAD_DISTANCE);
477 assert_eq!(m.unload_distance, DEFAULT_UNLOAD_DISTANCE);
478 }
479}