voxel_framework/world/systems.rs
1//! Bevy systems that implement the chunk streaming loop.
2//!
3//! # Systems in this module
4//!
5//! | System | Schedule | Reads | Writes / Emits |
6//! |---|---|---|---|
7//! | [`streaming_system`] | [`Update`] | [`ViewerPosition`], [`ChunkManager`] | [`ChunkLoadRequest`], [`ChunkUnloadRequest`], `ChunkManager` pending set |
8//!
9//! # Execution order
10//!
11//! [`streaming_system`] has no explicit ordering constraints relative to other
12//! `Update` systems. It should run **after** your camera/player system has
13//! updated [`ViewerPosition`] for the current frame. If you need a hard
14//! ordering guarantee, use `.after(YourMovementSystem)` when adding the plugin
15//! or configure a system set.
16//!
17//! # Authoring note
18//!
19//! [`ViewerPosition`] is defined here (alongside the system that consumes it)
20//! because both share the same module-level concern: mapping a world-space
21//! position to chunk-grid decisions. It is re-exported from the crate root via
22//! [`super`].
23
24use bevy::prelude::*;
25
26use crate::chunk::{CHUNK_SIZE, ChunkCoord};
27
28use super::{ChunkLoadRequest, ChunkManager, ChunkUnloadRequest};
29
30// ─── ViewerPosition ───────────────────────────────────────────────────────────
31
32/// World-space position of the primary viewer (player or camera).
33///
34/// This resource is read by [`streaming_system`] every frame to decide which
35/// chunk coordinates lie within the load sphere and which loaded chunks have
36/// drifted beyond the unload sphere. It **must be updated every frame** by
37/// your player or camera system — if it is stale, the streaming system will
38/// not respond to player movement and chunks near the new position will never
39/// be requested.
40///
41/// The resource defaults to the origin (`Vec3::ZERO`). [`WorldPlugin`](crate::world::WorldPlugin)
42/// registers it via `init_resource`, so it is always present when the plugin
43/// is active.
44///
45/// # What happens if it is not updated?
46///
47/// The streaming system will continue to evaluate distances against the last
48/// written position. No new [`ChunkLoadRequest`] events will be emitted for
49/// the region around the player's actual position, and no
50/// [`ChunkUnloadRequest`] events will fire for chunks the player has left
51/// behind. The world will appear frozen at the last known viewer position.
52///
53/// # Example
54///
55/// ```rust,no_run
56/// use bevy::prelude::*;
57/// use voxel_framework::world::ViewerPosition;
58///
59/// fn sync_viewer_to_camera(
60/// mut viewer: ResMut<ViewerPosition>,
61/// camera: Query<&Transform, With<Camera3d>>,
62/// ) {
63/// if let Ok(transform) = camera.single() {
64/// viewer.position = transform.translation;
65/// }
66/// }
67/// ```
68///
69/// Register your sync system in [`Update`] before the streaming system runs:
70///
71/// ```rust,no_run
72/// use bevy::prelude::*;
73/// use voxel_framework::world::ViewerPosition;
74///
75/// # fn sync_viewer_to_camera() {}
76/// # fn main() {
77/// App::new()
78/// .add_systems(Update, sync_viewer_to_camera)
79/// .run();
80/// # }
81/// ```
82#[derive(Resource, Default, Debug, Clone, Copy)]
83pub struct ViewerPosition {
84 /// Current world-space position of the viewer.
85 pub position: Vec3,
86}
87
88// ─── streaming_system ────────────────────────────────────────────────────────
89
90/// Drives chunk load and unload decisions based on [`ViewerPosition`].
91///
92/// Scheduled in [`Update`] by [`super::WorldPlugin`]. Each frame this system:
93///
94/// 1. Reads [`ViewerPosition`] and converts it to fractional chunk-grid space
95/// by dividing by `CHUNK_SIZE`.
96/// 2. Computes `load_radius_chunks = ceil(load_distance / CHUNK_SIZE)` and
97/// iterates every integer coordinate in the `[-r, r]³` bounding cube.
98/// 3. For each coordinate whose world-space center is within `load_distance`
99/// and that is neither already loaded nor pending in [`ChunkManager`]:
100/// - calls [`ChunkManager::mark_pending`] to prevent duplicate requests,
101/// - writes a [`ChunkLoadRequest`] for the generation system to consume.
102/// 4. Collects all currently loaded chunk coordinates whose world-space center
103/// distance exceeds `unload_distance`, then writes one
104/// [`ChunkUnloadRequest`] per coordinate.
105///
106/// The unload pass uses a separate `Vec` to avoid holding a shared borrow on
107/// [`ChunkManager`] while emitting messages that may mutate it in the same
108/// frame.
109pub fn streaming_system(
110 viewer: Res<ViewerPosition>,
111 mut manager: ResMut<ChunkManager>,
112 mut load_writer: MessageWriter<ChunkLoadRequest>,
113 mut unload_writer: MessageWriter<ChunkUnloadRequest>,
114) {
115 crate::profile_span!("voxel::world::streaming");
116 let chunk_size_f = CHUNK_SIZE as f32;
117
118 // Viewer position expressed in chunk-grid units (fractional).
119 let viewer_chunk_f = viewer.position / chunk_size_f;
120
121 // ── Emit load requests ────────────────────────────────────────────────
122
123 let load_radius_chunks = (manager.load_distance / chunk_size_f).ceil() as i32;
124
125 for dx in -load_radius_chunks..=load_radius_chunks {
126 for dy in -load_radius_chunks..=load_radius_chunks {
127 for dz in -load_radius_chunks..=load_radius_chunks {
128 let coord: ChunkCoord = IVec3::new(
129 viewer_chunk_f.x.floor() as i32 + dx,
130 viewer_chunk_f.y.floor() as i32 + dy,
131 viewer_chunk_f.z.floor() as i32 + dz,
132 );
133
134 // World-space center of this chunk.
135 let center = coord.as_vec3() * chunk_size_f + Vec3::splat(chunk_size_f * 0.5);
136 let dist = center.distance(viewer.position);
137
138 if dist <= manager.load_distance
139 && !manager.is_loaded(coord)
140 && !manager.is_pending(coord)
141 {
142 manager.mark_pending(coord);
143 load_writer.write(ChunkLoadRequest(coord));
144 }
145 }
146 }
147 }
148
149 // ── Emit unload requests ──────────────────────────────────────────────
150
151 // Collect coords to unload first to avoid borrowing `manager` mutably
152 // while iterating its loaded set.
153 let to_unload: Vec<ChunkCoord> = manager
154 .iter_loaded()
155 .filter_map(|(coord, _entity)| {
156 let center = coord.as_vec3() * chunk_size_f + Vec3::splat(chunk_size_f * 0.5);
157 if center.distance(viewer.position) > manager.unload_distance {
158 Some(coord)
159 } else {
160 None
161 }
162 })
163 .collect();
164
165 for coord in to_unload {
166 unload_writer.write(ChunkUnloadRequest(coord));
167 }
168}