Skip to main content

voxel_framework/generator/
region.rs

1//! Region-based generator composition.
2//!
3//! `RegionGenerator<V>` is a refinement of [`ChunkGenerator<V>`] that decides
4//! per-chunk whether it wants to produce that chunk.  [`MultiGenerator<V>`]
5//! holds an ordered list of region generators plus a universal fallback and
6//! itself implements [`ChunkGenerator<V>`], so it slots into the existing
7//! async generation pipeline (`GeneratorPlugin`) with **zero changes** to the
8//! pipeline.
9//!
10//! Use this to compose heterogeneous worlds — e.g. a starting moon at the
11//! origin, an asteroid belt in a torus, and a void fallback for empty space.
12//!
13//! # Back-compat
14//!
15//! Every [`ChunkGenerator<V>`] is automatically a universal [`RegionGenerator<V>`]
16//! via a blanket impl ([`applies_to`](RegionGenerator::applies_to) returns
17//! `true` for every chunk).  Single-generator setups continue to work
18//! unchanged.
19//!
20//! # Example
21//!
22//! ```rust,no_run
23//! use std::sync::Arc;
24//! use bevy::math::IVec3;
25//! use bevy::prelude::*;
26//! use voxel_framework::chunk::Chunk;
27//! use voxel_framework::generator::{
28//!     ChunkGenerator, MultiGenerator, MultiGeneratorPlugin, RegionGenerator,
29//! };
30//! use voxel_framework::voxel::DefaultVoxel;
31//!
32//! struct OriginMoon;
33//! impl RegionGenerator<DefaultVoxel> for OriginMoon {
34//!     fn applies_to(&self, c: IVec3) -> bool { c.length_squared() < 16 }
35//!     fn generate(&self, _c: IVec3, chunk: &mut Chunk<DefaultVoxel>) {
36//!         chunk.set(0, 0, 0, DefaultVoxel::Rock);
37//!     }
38//! }
39//!
40//! struct VoidFallback;
41//! impl ChunkGenerator<DefaultVoxel> for VoidFallback {
42//!     fn generate(&self, _c: IVec3, _chunk: &mut Chunk<DefaultVoxel>) {}
43//! }
44//!
45//! let multi = MultiGenerator::<DefaultVoxel>::new(Box::new(VoidFallback))
46//!     .with_region(Box::new(OriginMoon));
47//!
48//! // Then: app.add_plugins(MultiGeneratorPlugin::<DefaultVoxel>::from_generator(multi));
49//! ```
50
51use std::sync::Arc;
52
53use bevy::math::IVec3;
54use bevy::prelude::*;
55
56use crate::chunk::Chunk;
57use crate::voxel::VoxelType;
58
59use super::{ChunkGenerator, GeneratorResource};
60
61/// A generator that only applies to certain regions of world space.
62///
63/// Composed via [`MultiGenerator`] / [`MultiGeneratorPlugin`] to build
64/// heterogeneous worlds.  Implementations must be `Send + Sync + 'static`
65/// because they are invoked from background worker threads.
66///
67/// # Thread-safety contract
68///
69/// Same as [`ChunkGenerator`]: implementations **must not** access the Bevy
70/// `World`, hold non-`Send` state, or perform blocking I/O.
71pub trait RegionGenerator<V: VoxelType>: Send + Sync + 'static {
72    /// Returns `true` iff this generator should produce the chunk at
73    /// `chunk_pos`.
74    ///
75    /// `chunk_pos` is in chunk-grid space (one unit per `CHUNK_SIZE` world
76    /// units).  Called on the worker thread; must be cheap and side-effect
77    /// free.
78    fn applies_to(&self, chunk_pos: IVec3) -> bool;
79
80    /// Fills `chunk` with voxel data for the chunk at `chunk_pos`.
81    ///
82    /// Only called by [`MultiGenerator`] when [`applies_to`] returns `true`.
83    /// Same thread-safety contract as [`ChunkGenerator::generate`].
84    ///
85    /// [`applies_to`]: RegionGenerator::applies_to
86    fn generate(&self, chunk_pos: IVec3, chunk: &mut Chunk<V>);
87}
88
89/// Blanket impl: any [`ChunkGenerator`] is a universal [`RegionGenerator`]
90/// (applies to every chunk).  This is the back-compat bridge — single-generator
91/// setups continue to work and can be dropped into `MultiGenerator` without
92/// any changes.
93impl<V: VoxelType, G: ChunkGenerator<V>> RegionGenerator<V> for G {
94    #[inline]
95    fn applies_to(&self, _chunk_pos: IVec3) -> bool {
96        true
97    }
98
99    #[inline]
100    fn generate(&self, chunk_pos: IVec3, chunk: &mut Chunk<V>) {
101        ChunkGenerator::generate(self, chunk_pos, chunk)
102    }
103}
104
105/// Composite generator that dispatches each chunk request to the first
106/// [`RegionGenerator`] whose [`applies_to`](RegionGenerator::applies_to)
107/// returns `true`, falling back to a universal [`ChunkGenerator`] when none
108/// match.
109///
110/// Itself implements [`ChunkGenerator<V>`], so it is a drop-in replacement for
111/// any single-generator setup and slots into the existing
112/// [`GeneratorPlugin`](super::GeneratorPlugin) async pipeline with no changes.
113///
114/// # Dispatch order
115///
116/// Regions are walked in **insertion order**.  The first region whose
117/// `applies_to` returns `true` wins; later regions never see that chunk.
118/// Order your regions from most specific to most general.
119pub struct MultiGenerator<V: VoxelType> {
120    regions: Vec<Box<dyn RegionGenerator<V>>>,
121    fallback: Box<dyn ChunkGenerator<V>>,
122}
123
124impl<V: VoxelType> MultiGenerator<V> {
125    /// Creates a [`MultiGenerator`] with the given universal fallback and no
126    /// regions.  Add regions via [`add_region`](Self::add_region) or
127    /// [`with_region`](Self::with_region).
128    pub fn new(fallback: Box<dyn ChunkGenerator<V>>) -> Self {
129        Self {
130            regions: Vec::new(),
131            fallback,
132        }
133    }
134
135    /// Appends a region generator.  Regions are tried in insertion order.
136    pub fn add_region(&mut self, region: Box<dyn RegionGenerator<V>>) -> &mut Self {
137        self.regions.push(region);
138        self
139    }
140
141    /// Builder-style variant of [`add_region`](Self::add_region).
142    pub fn with_region(mut self, region: Box<dyn RegionGenerator<V>>) -> Self {
143        self.regions.push(region);
144        self
145    }
146
147    /// Replaces the universal fallback.
148    pub fn with_fallback(mut self, fallback: Box<dyn ChunkGenerator<V>>) -> Self {
149        self.fallback = fallback;
150        self
151    }
152
153    /// Returns the number of registered regions (excluding the fallback).
154    pub fn region_count(&self) -> usize {
155        self.regions.len()
156    }
157}
158
159impl<V: VoxelType> ChunkGenerator<V> for MultiGenerator<V> {
160    fn generate(&self, coord: IVec3, chunk: &mut Chunk<V>) {
161        for region in &self.regions {
162            if region.applies_to(coord) {
163                region.generate(coord, chunk);
164                return;
165            }
166        }
167        self.fallback.generate(coord, chunk);
168    }
169}
170
171/// Bevy [`Plugin`] that installs a [`MultiGenerator<V>`] as the active
172/// [`GeneratorResource<V>`] for voxel type `V`.
173///
174/// Mirrors the behaviour of [`GeneratorPlugin`](super::GeneratorPlugin) but
175/// inserts the resource itself, so no separate
176/// `app.insert_resource(GeneratorResource { ... })` step is needed.  Add this
177/// plugin **alongside** [`GeneratorPlugin`](super::GeneratorPlugin) — the latter
178/// still owns the async job-queue systems; this plugin only provides the
179/// generator backing them.
180///
181/// # Builder workflow
182///
183/// ```rust,no_run
184/// use bevy::prelude::*;
185/// use bevy::math::IVec3;
186/// use voxel_framework::chunk::Chunk;
187/// use voxel_framework::generator::{
188///     ChunkGenerator, GeneratorPlugin, MultiGenerator, MultiGeneratorPlugin,
189///     RegionGenerator,
190/// };
191/// use voxel_framework::voxel::DefaultVoxel;
192///
193/// struct VoidGen;
194/// impl ChunkGenerator<DefaultVoxel> for VoidGen {
195///     fn generate(&self, _c: IVec3, _chunk: &mut Chunk<DefaultVoxel>) {}
196/// }
197///
198/// struct MoonGen;
199/// impl RegionGenerator<DefaultVoxel> for MoonGen {
200///     fn applies_to(&self, c: IVec3) -> bool { c.length_squared() < 4 }
201///     fn generate(&self, _c: IVec3, chunk: &mut Chunk<DefaultVoxel>) {
202///         chunk.set(0, 0, 0, DefaultVoxel::Rock);
203///     }
204/// }
205///
206/// let plugin = MultiGeneratorPlugin::<DefaultVoxel>::new(Box::new(VoidGen))
207///     .add_region(Box::new(MoonGen));
208///
209/// App::new()
210///     .add_plugins(plugin)
211///     .add_plugins(GeneratorPlugin::<DefaultVoxel>::new());
212/// ```
213pub struct MultiGeneratorPlugin<V: VoxelType> {
214    /// Holds the in-progress generator until [`Plugin::build`] takes it.
215    /// `Mutex` provides the interior mutability needed because `build` is
216    /// called with `&self`; the `Option` lets us move the value out exactly
217    /// once.  Bevy calls `build` from a single thread, so there is no real
218    /// contention.
219    multi: std::sync::Mutex<Option<MultiGenerator<V>>>,
220}
221
222impl<V: VoxelType> MultiGeneratorPlugin<V> {
223    /// Creates a plugin builder seeded with a fallback generator and no
224    /// regions.
225    pub fn new(fallback: Box<dyn ChunkGenerator<V>>) -> Self {
226        Self {
227            multi: std::sync::Mutex::new(Some(MultiGenerator::new(fallback))),
228        }
229    }
230
231    /// Wraps an existing [`MultiGenerator`] in a plugin without further
232    /// builder calls.
233    pub fn from_generator(multi: MultiGenerator<V>) -> Self {
234        Self {
235            multi: std::sync::Mutex::new(Some(multi)),
236        }
237    }
238
239    /// Appends a region generator (builder style).
240    pub fn add_region(self, region: Box<dyn RegionGenerator<V>>) -> Self {
241        {
242            let mut guard = self.multi.lock().expect("MultiGeneratorPlugin mutex");
243            guard
244                .as_mut()
245                .expect("MultiGeneratorPlugin already consumed")
246                .add_region(region);
247        }
248        self
249    }
250
251    /// Replaces the fallback generator (builder style).
252    pub fn with_fallback(self, fallback: Box<dyn ChunkGenerator<V>>) -> Self {
253        {
254            let mut guard = self.multi.lock().expect("MultiGeneratorPlugin mutex");
255            let multi = guard.take().expect("MultiGeneratorPlugin already consumed");
256            *guard = Some(multi.with_fallback(fallback));
257        }
258        self
259    }
260}
261
262impl<V: VoxelType> Plugin for MultiGeneratorPlugin<V> {
263    fn build(&self, app: &mut App) {
264        let multi = self
265            .multi
266            .lock()
267            .expect("MultiGeneratorPlugin mutex")
268            .take()
269            .expect("MultiGeneratorPlugin built twice or never seeded");
270
271        app.insert_resource(GeneratorResource::<V> {
272            generator: Arc::new(multi),
273        });
274    }
275}
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280
281    use crate::chunk::CHUNK_SIZE;
282    use crate::voxel::DefaultVoxel;
283
284    /// Region that applies to chunks with `chunk_pos.x >= 0`.  Marks voxel
285    /// `(0, 0, 0)` with `Rock`.
286    struct PositiveX;
287    impl RegionGenerator<DefaultVoxel> for PositiveX {
288        fn applies_to(&self, chunk_pos: IVec3) -> bool {
289            chunk_pos.x >= 0
290        }
291        fn generate(&self, _chunk_pos: IVec3, chunk: &mut Chunk<DefaultVoxel>) {
292            chunk.set(0, 0, 0, DefaultVoxel::Rock);
293        }
294    }
295
296    /// Region that applies to chunks with `chunk_pos.x < 0`.  Marks voxel
297    /// `(0, 0, 0)` with `IronOre`.
298    struct NegativeX;
299    impl RegionGenerator<DefaultVoxel> for NegativeX {
300        fn applies_to(&self, chunk_pos: IVec3) -> bool {
301            chunk_pos.x < 0
302        }
303        fn generate(&self, _chunk_pos: IVec3, chunk: &mut Chunk<DefaultVoxel>) {
304            chunk.set(0, 0, 0, DefaultVoxel::IronOre);
305        }
306    }
307
308    /// Universal fallback that leaves every voxel as air.  Used as the
309    /// "should never be called" sentinel — sets `(1, 1, 1)` to `RareMineral`
310    /// so the test can detect when fallback ran unexpectedly.
311    struct VoidFallback;
312    impl ChunkGenerator<DefaultVoxel> for VoidFallback {
313        fn generate(&self, _coord: IVec3, chunk: &mut Chunk<DefaultVoxel>) {
314            chunk.set(1, 1, 1, DefaultVoxel::RareMineral);
315        }
316    }
317
318    #[test]
319    fn region_dispatch_positive_x_runs_first_region() {
320        let multi = MultiGenerator::<DefaultVoxel>::new(Box::new(VoidFallback))
321            .with_region(Box::new(PositiveX))
322            .with_region(Box::new(NegativeX));
323
324        let mut chunk = Chunk::<DefaultVoxel>::new();
325        ChunkGenerator::generate(&multi, IVec3::new(5, 0, 0), &mut chunk);
326
327        assert_eq!(chunk.get(0, 0, 0), DefaultVoxel::Rock);
328        // Fallback must not have run.
329        assert_eq!(chunk.get(1, 1, 1), DefaultVoxel::Air);
330    }
331
332    #[test]
333    fn region_dispatch_negative_x_runs_second_region() {
334        let multi = MultiGenerator::<DefaultVoxel>::new(Box::new(VoidFallback))
335            .with_region(Box::new(PositiveX))
336            .with_region(Box::new(NegativeX));
337
338        let mut chunk = Chunk::<DefaultVoxel>::new();
339        ChunkGenerator::generate(&multi, IVec3::new(-3, 0, 0), &mut chunk);
340
341        assert_eq!(chunk.get(0, 0, 0), DefaultVoxel::IronOre);
342        assert_eq!(chunk.get(1, 1, 1), DefaultVoxel::Air);
343    }
344
345    #[test]
346    fn fallback_runs_when_no_region_matches() {
347        // Region that never matches.
348        struct Never;
349        impl RegionGenerator<DefaultVoxel> for Never {
350            fn applies_to(&self, _: IVec3) -> bool {
351                false
352            }
353            fn generate(&self, _: IVec3, chunk: &mut Chunk<DefaultVoxel>) {
354                chunk.set(0, 0, 0, DefaultVoxel::Rock);
355            }
356        }
357
358        let multi = MultiGenerator::<DefaultVoxel>::new(Box::new(VoidFallback))
359            .with_region(Box::new(Never));
360
361        let mut chunk = Chunk::<DefaultVoxel>::new();
362        ChunkGenerator::generate(&multi, IVec3::new(0, 0, 0), &mut chunk);
363
364        // Fallback ran.
365        assert_eq!(chunk.get(1, 1, 1), DefaultVoxel::RareMineral);
366        // Region did NOT run.
367        assert_eq!(chunk.get(0, 0, 0), DefaultVoxel::Air);
368    }
369
370    #[test]
371    fn insertion_order_wins_on_overlap() {
372        // Two regions that both match every chunk.  First wins.
373        struct AllRock;
374        impl RegionGenerator<DefaultVoxel> for AllRock {
375            fn applies_to(&self, _: IVec3) -> bool {
376                true
377            }
378            fn generate(&self, _: IVec3, chunk: &mut Chunk<DefaultVoxel>) {
379                chunk.set(0, 0, 0, DefaultVoxel::Rock);
380            }
381        }
382        struct AllIron;
383        impl RegionGenerator<DefaultVoxel> for AllIron {
384            fn applies_to(&self, _: IVec3) -> bool {
385                true
386            }
387            fn generate(&self, _: IVec3, chunk: &mut Chunk<DefaultVoxel>) {
388                chunk.set(0, 0, 0, DefaultVoxel::IronOre);
389            }
390        }
391
392        let multi = MultiGenerator::<DefaultVoxel>::new(Box::new(VoidFallback))
393            .with_region(Box::new(AllRock))
394            .with_region(Box::new(AllIron));
395
396        let mut chunk = Chunk::<DefaultVoxel>::new();
397        ChunkGenerator::generate(&multi, IVec3::ZERO, &mut chunk);
398
399        assert_eq!(chunk.get(0, 0, 0), DefaultVoxel::Rock);
400    }
401
402    #[test]
403    fn blanket_impl_lets_chunk_generator_serve_as_region() {
404        // VoidFallback is a ChunkGenerator; the blanket impl makes it a
405        // universal RegionGenerator too.
406        let multi = MultiGenerator::<DefaultVoxel>::new(Box::new(VoidFallback))
407            .with_region(Box::new(VoidFallback));
408
409        let mut chunk = Chunk::<DefaultVoxel>::new();
410        ChunkGenerator::generate(&multi, IVec3::new(7, 7, 7), &mut chunk);
411
412        // First region (the universal VoidFallback) ran, not the fallback.
413        // VoidFallback marks (1,1,1) with RareMineral either way, so we can't
414        // distinguish here — instead, assert the chunk volume is otherwise
415        // untouched, confirming the dispatcher ran exactly one generator.
416        let mut nonair = 0;
417        for x in 0..CHUNK_SIZE {
418            for y in 0..CHUNK_SIZE {
419                for z in 0..CHUNK_SIZE {
420                    if chunk.get(x, y, z) != DefaultVoxel::Air {
421                        nonair += 1;
422                    }
423                }
424            }
425        }
426        assert_eq!(
427            nonair, 1,
428            "exactly one voxel should be set; got {nonair} non-air voxels"
429        );
430    }
431}