voxel_framework/generator/mod.rs
1//! Procedural chunk generation trait, async pipeline, and Bevy plugin.
2//!
3//! # Architecture
4//!
5//! World generation is split across two systems that run every frame inside
6//! [`GeneratorSystems`]:
7//!
8//! 1. **[`chunk_request_system`]** — receives [`crate::world::ChunkLoadRequest`]
9//! messages. It first tries to restore the chunk from disk (when
10//! [`crate::world::PersistenceConfig`] is present); on a cache miss it
11//! clones the [`Arc`]-wrapped generator and offloads work to Bevy's
12//! [`bevy::tasks::AsyncComputeTaskPool`], storing the returned [`Task`] as a
13//! [`ChunkTask<V>`] component on a new entity.
14//!
15//! 2. **[`chunk_task_poll_system`]** — polls every in-flight [`ChunkTask<V>`]
16//! with a single non-blocking `poll_once`. When a task resolves it removes
17//! the task component, inserts the completed [`crate::chunk::Chunk<V>`], and
18//! emits [`crate::world::ChunkModified`] so that the mesh system in
19//! [`crate::mesh`] can build geometry on the same frame.
20//!
21//! # The `ChunkGenerator` contract
22//!
23//! Every implementation of [`ChunkGenerator<V>`] runs on a worker thread from
24//! `AsyncComputeTaskPool`. It **must not** access the Bevy [`bevy::ecs::world::World`]
25//! or any `Res<T>` — the generator `Arc` is the only shared state it may touch.
26//! The trait bounds `Send + Sync + 'static` enforce this at compile time.
27//!
28//! # Wiring into a Bevy app
29//!
30//! ```rust,no_run
31//! use std::sync::Arc;
32//! use bevy::prelude::*;
33//! use voxel_framework::{
34//! generator::{GeneratorPlugin, GeneratorResource},
35//! mesh::MeshPlugin,
36//! voxel::DefaultVoxel,
37//! VoxelPlugin,
38//! };
39//! use voxel_framework::generator::asteroid::{AsteroidConfig, AsteroidGenerator};
40//!
41//! App::new()
42//! .add_plugins(DefaultPlugins)
43//! .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
44//! .insert_resource(GeneratorResource::<DefaultVoxel> {
45//! generator: Arc::new(AsteroidGenerator::new(AsteroidConfig::default())),
46//! })
47//! .add_plugins(GeneratorPlugin::<DefaultVoxel>::new())
48//! .add_plugins(MeshPlugin::<DefaultVoxel>::new())
49//! .run();
50//! ```
51//!
52//! [`Arc`]: std::sync::Arc
53//! [`Task`]: bevy::tasks::Task
54
55pub mod asteroid;
56pub mod region;
57pub mod systems;
58pub mod terrain;
59
60pub use region::{MultiGenerator, MultiGeneratorPlugin, RegionGenerator};
61pub use systems::{ChunkTask, chunk_request_system, chunk_task_poll_system};
62
63use std::sync::Arc;
64
65use bevy::prelude::*;
66
67use crate::chunk::Chunk;
68use crate::voxel::VoxelType;
69
70/// System set label for the generator pipeline.
71///
72/// `chunk_mesh_system` uses `.after(GeneratorSystems)` to guarantee it reads
73/// `ChunkModified` messages emitted in the same frame by `chunk_task_poll_system`.
74#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
75pub struct GeneratorSystems;
76
77/// Contract for procedural chunk generation strategies.
78///
79/// An implementation receives an empty [`Chunk<V>`] and a chunk-grid coordinate,
80/// and fills the chunk with whatever voxel data the strategy produces. The
81/// framework stores implementations behind an [`std::sync::Arc`] and calls
82/// [`ChunkGenerator::generate`] on worker threads from Bevy's
83/// [`bevy::tasks::AsyncComputeTaskPool`].
84///
85/// # Thread safety contract
86///
87/// `generate` is called from a **background thread** — never from the Bevy main
88/// thread. Implementations **must not**:
89///
90/// - access any [`bevy::ecs::world::World`] data (queries, resources, etc.),
91/// - hold non-`Send` types, or
92/// - perform blocking I/O on the calling thread.
93///
94/// The `Send + Sync + 'static` bounds on the trait enforce these constraints at
95/// compile time. Internal state may be freely read (shared references via
96/// `Arc`), but must not be mutated without interior synchronization.
97///
98/// # Coordinate space
99///
100/// `coord` is in **chunk-grid space**: each axis unit corresponds to
101/// `CHUNK_SIZE` world units. Convert to world space with
102/// `coord.as_vec3() * CHUNK_SIZE as f32`.
103///
104/// # Examples
105///
106/// ```rust,no_run
107/// use bevy::math::IVec3;
108/// use voxel_framework::{
109/// chunk::Chunk,
110/// generator::ChunkGenerator,
111/// voxel::DefaultVoxel,
112/// };
113///
114/// struct FlatWorldGenerator {
115/// ground_level: i32,
116/// }
117///
118/// impl ChunkGenerator<DefaultVoxel> for FlatWorldGenerator {
119/// fn generate(&self, coord: IVec3, chunk: &mut Chunk<DefaultVoxel>) {
120/// // Fill voxels below ground_level with rock, leave the rest as air.
121/// if coord.y < self.ground_level {
122/// for x in 0..voxel_framework::chunk::CHUNK_SIZE {
123/// for y in 0..voxel_framework::chunk::CHUNK_SIZE {
124/// for z in 0..voxel_framework::chunk::CHUNK_SIZE {
125/// chunk.set(x, y, z, DefaultVoxel::Rock);
126/// }
127/// }
128/// }
129/// }
130/// }
131/// }
132/// ```
133pub trait ChunkGenerator<V: VoxelType>: Send + Sync + 'static {
134 /// Fills `chunk` with voxel data for the chunk at `coord`.
135 ///
136 /// `coord` is in chunk-grid space; each unit equals `CHUNK_SIZE` world units.
137 ///
138 /// **Called on a background thread. Must not access the Bevy `World`.**
139 fn generate(&self, coord: IVec3, chunk: &mut Chunk<V>);
140}
141
142/// Bevy [`Resource`] that holds the active [`ChunkGenerator<V>`].
143///
144/// Insert this resource before adding [`GeneratorPlugin<V>`] to provide the
145/// generation strategy. The inner [`std::sync::Arc`] is cloned cheaply into
146/// each async task so that the generator is shared without blocking or copying.
147///
148/// ```rust,no_run
149/// use std::sync::Arc;
150/// use bevy::prelude::*;
151/// use voxel_framework::{
152/// generator::GeneratorResource,
153/// voxel::DefaultVoxel,
154/// };
155/// use voxel_framework::generator::asteroid::{AsteroidConfig, AsteroidGenerator};
156///
157/// fn main() {
158/// App::new()
159/// .insert_resource(GeneratorResource::<DefaultVoxel> {
160/// generator: Arc::new(AsteroidGenerator::new(AsteroidConfig::default())),
161/// })
162/// // ... add other plugins ...
163/// .run();
164/// }
165/// ```
166#[derive(Resource)]
167pub struct GeneratorResource<V: VoxelType> {
168 /// The active chunk generator, shared across worker threads via [`std::sync::Arc`].
169 pub generator: Arc<dyn ChunkGenerator<V>>,
170}
171
172/// Bevy [`Plugin`] that registers the async chunk generation pipeline for
173/// voxel type `V`.
174///
175/// Adds two systems to the [`Update`] schedule inside [`GeneratorSystems`],
176/// chained so that poll results are available to downstream systems in the same
177/// frame:
178///
179/// 1. [`chunk_request_system`] — converts [`crate::world::ChunkLoadRequest`]
180/// messages into async tasks (or immediate disk loads).
181/// 2. [`chunk_task_poll_system`] — harvests completed tasks and attaches
182/// [`crate::chunk::Chunk<V>`] components.
183///
184/// [`GeneratorResource<V>`] must be inserted separately; the plugin does not
185/// require it at registration time (the system accepts it as `Option<Res<_>>`).
186pub struct GeneratorPlugin<V: VoxelType> {
187 _marker: std::marker::PhantomData<V>,
188}
189
190impl<V: VoxelType> GeneratorPlugin<V> {
191 /// Creates a new [`GeneratorPlugin`] for voxel type `V`.
192 pub fn new() -> Self {
193 Self {
194 _marker: std::marker::PhantomData,
195 }
196 }
197}
198
199impl<V: VoxelType> Default for GeneratorPlugin<V> {
200 fn default() -> Self {
201 Self::new()
202 }
203}
204
205impl<V: VoxelType> Plugin for GeneratorPlugin<V> {
206 fn build(&self, app: &mut App) {
207 app.add_systems(
208 Update,
209 (
210 systems::chunk_request_system::<V>,
211 systems::chunk_task_poll_system::<V>,
212 )
213 .chain()
214 .in_set(GeneratorSystems),
215 );
216 }
217}