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
//! World streaming, chunk lifecycle, and runtime configuration.
//!
//! # Overview
//!
//! The world module owns three concerns:
//!
//! - **Chunk registry** — [`ChunkManager`] tracks which chunks are fully
//! loaded, which are in-flight, and the configured streaming distances.
//! - **Viewer tracking** — [`ViewerPosition`] is a lightweight resource that
//! your player/camera system updates every frame. The streaming system reads
//! it to decide which chunks to load or unload.
//! - **Lifecycle events** — [`ChunkLoadRequest`], [`ChunkUnloadRequest`], and
//! [`ChunkModified`] are the message bus between the streaming system and
//! the rest of the engine (generation, meshing, persistence).
//!
//! Add [`WorldPlugin`] to your [`App`] to register all of the above
//! automatically.
//!
//! # The Streaming Pipeline
//!
//! Every frame the [`systems::streaming_system`] executes the following steps:
//!
//! ```text
//! ┌─────────────────────┐
//! │ ViewerPosition │ updated by your camera/player system each frame
//! └────────┬────────────┘
//! │ read by streaming_system
//! ▼
//! ┌─────────────────────┐
//! │ Distance check │ iterate cube of radius ceil(load_distance/CHUNK_SIZE)
//! │ around viewer │ compute world-space center distance per coord
//! └────────┬────────────┘
//! │
//! ┌────┴─────┐
//! │ │
//! ▼ ▼
//! ChunkLoad ChunkUnload
//! Request Request
//! (enter (exit
//! sphere) sphere)
//! │ │
//! ▼ ▼
//! Generator Despawn
//! system system
//! (async)
//! │
//! ▼
//! ChunkModified ←── voxel edits (mining, placement, etc.)
//! │
//! ▼
//! Mesh rebuild system
//! ```
//!
//! 1. [`ViewerPosition`] is updated by your player/camera system.
//! 2. [`systems::streaming_system`] converts it to chunk-grid space and
//! iterates every coordinate within a bounding cube of radius
//! `ceil(load_distance / CHUNK_SIZE)`.
//! 3. For each coordinate inside the load sphere that is neither loaded nor
//! pending, the system emits [`ChunkLoadRequest`] and marks the coord
//! pending in [`ChunkManager`].
//! 4. For each currently loaded chunk whose center has drifted beyond
//! `unload_distance`, the system emits [`ChunkUnloadRequest`].
//! 5. An external generation system receives [`ChunkLoadRequest`], generates
//! voxel data asynchronously, spawns the entity, and calls
//! [`ChunkManager::register`].
//! 6. Whenever voxel data changes (mining, placement, etc.), the responsible
//! system emits [`ChunkModified`], which triggers mesh regeneration for
//! that chunk and its affected neighbors.
//!
//! # Events and Messages
//!
//! | Event | When it fires | Who consumes it |
//! |---|---|---|
//! | [`ChunkLoadRequest`] | Chunk coord enters `load_distance` sphere | Generation system |
//! | [`ChunkUnloadRequest`] | Loaded chunk center exits `unload_distance` sphere | Despawn system |
//! | [`ChunkModified`] | Voxel data written to a loaded chunk | Mesh rebuild system |
//!
//! # World Configuration
//!
//! [`config::WorldConfig`] is loaded from `world.toml` in the working
//! directory at startup by [`config::WorldConfigPlugin`]. It is inserted as a
//! Bevy [`Resource`] and its `load_distance` / `unload_distance` values are
//! applied directly to [`ChunkManager`]. If the file is absent or malformed,
//! [`config::WorldConfig::default`] is used silently.
pub use ;
pub use ;
pub use ;
pub use ;
pub use MiningInputPlugin;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ViewerPosition;
pub use ;
use ;
use *;
use crateChunkCoord;
// ─── Constants ───────────────────────────────────────────────────────────────
/// Default radius in world units within which chunks are loaded (150.0).
///
/// Used as the initial value for [`ChunkManager::load_distance`] when no
/// [`config::WorldConfig`] overrides it. Can be overridden per-instance via
/// [`ChunkManager::new`] or by loading a `world.toml` with
/// [`config::WorldConfigPlugin`].
pub const DEFAULT_LOAD_DISTANCE: f32 = 150.0;
/// Default radius in world units beyond which chunks are unloaded (200.0).
///
/// Used as the initial value for [`ChunkManager::unload_distance`]. The
/// 50-unit gap between this constant and [`DEFAULT_LOAD_DISTANCE`] creates a
/// **hysteresis band**: chunks that have been loaded are not immediately
/// unloaded when the viewer steps back past the load boundary. This prevents
/// rapid load/unload cycling ("thrashing") near the edge of the streaming
/// sphere.
pub const DEFAULT_UNLOAD_DISTANCE: f32 = 200.0;
// ─── Events ──────────────────────────────────────────────────────────────────
/// Fired by [`systems::streaming_system`] when a chunk coordinate enters the
/// load sphere and must be generated and spawned.
///
/// The wrapped [`ChunkCoord`] identifies the chunk-grid position that should
/// be populated. Upon receiving this event, a generation system should:
///
/// 1. Generate voxel data for the coordinate (typically on a thread pool).
/// 2. Spawn a Bevy entity with the resulting mesh and voxel components.
/// 3. Call [`ChunkManager::register`] with the coord and new entity so the
/// streaming system considers the chunk fully loaded.
///
/// The coord is guaranteed to be neither already loaded nor pending at the
/// moment the event is written.
;
/// Fired by [`systems::streaming_system`] when a loaded chunk's world-space
/// center drifts beyond [`ChunkManager::unload_distance`].
///
/// The wrapped [`ChunkCoord`] identifies the chunk to remove. Upon receiving
/// this event, a despawn system should despawn the entity returned by
/// [`ChunkManager::get_entity`] and call [`ChunkManager::unregister`] so the
/// coord becomes eligible for reloading in the future.
///
/// Note that the 50-unit hysteresis gap between [`DEFAULT_LOAD_DISTANCE`] and
/// [`DEFAULT_UNLOAD_DISTANCE`] means this event fires noticeably later than
/// the chunk first became "out of load range".
;
/// Fired whenever voxel data inside a loaded chunk is written.
///
/// The wrapped [`ChunkCoord`] identifies the modified chunk. Consumers
/// — typically the mesh rebuild system — should regenerate the mesh for this
/// chunk and re-evaluate the face visibility of its six face-adjacent
/// neighbors, because a voxel change at a chunk boundary affects the neighbor's
/// exposed faces as well.
///
/// This event is emitted by high-level operations such as [`mining`] and
/// [`placement`], and also by any system that calls [`voxel_ops::set_voxel_at`]
/// directly.
;
// ─── ChunkManager ─────────────────────────────────────────────────────────────
/// Central registry that tracks the state of every chunk in the streaming system.
///
/// `ChunkManager` is inserted as a Bevy [`Resource`] by [`WorldPlugin`] and
/// updated by [`systems::streaming_system`] every frame. It maintains two
/// internal sets:
///
/// - **Loaded** — chunks that have a live Bevy entity with a built mesh. Query
/// membership with [`is_loaded`](ChunkManager::is_loaded) and retrieve the
/// entity with [`get_entity`](ChunkManager::get_entity).
/// - **Pending** — chunk coordinates for which a [`ChunkLoadRequest`] has been
/// emitted but whose generation is not yet complete. Query membership with
/// [`is_pending`](ChunkManager::is_pending).
///
/// The two public distance fields, [`load_distance`](ChunkManager::load_distance)
/// and [`unload_distance`](ChunkManager::unload_distance), are read every frame
/// by the streaming system. They default to [`DEFAULT_LOAD_DISTANCE`] and
/// [`DEFAULT_UNLOAD_DISTANCE`] respectively, and can be overridden at runtime
/// or by loading a [`config::WorldConfig`].
///
/// # Querying chunks
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::world::ChunkManager;
///
/// fn inspect_chunks(manager: Res<ChunkManager>) {
/// println!("loaded: {}, pending: {}", manager.loaded_count(), manager.pending_count());
///
/// for (coord, entity) in manager.iter_loaded() {
/// println!("chunk {:?} → entity {:?}", coord, entity);
/// }
/// }
/// ```
///
/// # Registering a generated chunk
///
/// After generating voxel data and spawning the entity, call
/// [`register`](ChunkManager::register) to promote the coord from pending to
/// loaded:
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::world::ChunkManager;
///
/// fn finish_generation(mut manager: ResMut<ChunkManager>, mut commands: Commands) {
/// let coord = IVec3::new(1, 0, 0);
/// let entity = commands.spawn_empty().id();
/// manager.register(coord, entity);
/// }
/// ```
// ─── WorldPlugin ─────────────────────────────────────────────────────────────
/// Plugin that wires up the world streaming system.
///
/// Registers the following on the Bevy [`App`]:
///
/// - [`ChunkManager`] resource (via `init_resource`, defaults to
/// [`DEFAULT_LOAD_DISTANCE`] / [`DEFAULT_UNLOAD_DISTANCE`]).
/// - [`ViewerPosition`] resource (via `init_resource`, defaults to the origin).
/// - [`ChunkLoadRequest`], [`ChunkUnloadRequest`], and [`ChunkModified`]
/// messages.
/// - [`systems::streaming_system`] scheduled in [`Update`].
///
/// For configuration loading, add [`config::WorldConfigPlugin`] as well. For
/// initial-load progress tracking, add [`loading::LoadingPlugin`].
///
/// # Example
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::world::{WorldPlugin, config::WorldConfigPlugin};
///
/// App::new()
/// .add_plugins((WorldPlugin, WorldConfigPlugin))
/// .run();
/// ```
;
// ─── Tests ───────────────────────────────────────────────────────────────────